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AQwjE,EAAYI,EAAQA,EAAQ5jE,OAAS,GAAG2jE,KAK7D,IAAKH,EAAW,MAAM,IAAIprD,MAAM,yDAChCorD,EAAYA,EAAU3jE,QAAQ,OAAQ,IAAIA,QAAQ,QAAS,IAAIA,QAAQ,YAAa,KACpF8hE,EAAoB32B,EAAIw4B,G,SCXxB,IAAIM,EAAkB,CACrB,IAAK,GAgBNnC,EAAoBpF,EAAEt8D,EAAI,CAAC4iE,EAASnmB,KAE/BonB,EAAgBjB,IAElBY,cAAc9B,EAAoB32B,EAAI22B,EAAoBv6C,EAAEy7C,KAK/D,IAAIkB,EAAqB9vD,KAA6B,uBAAIA,KAA6B,wBAAK,GACxF+vD,EAA6BD,EAAmBhgE,KAAKmvC,KAAK6wB,GAC9DA,EAAmBhgE,KAvBCG,IACnB,IAAKg+D,EAAU+B,EAAaC,GAAWhgE,EACvC,IAAI,IAAI09D,KAAYqC,EAChBtC,EAAoBX,EAAEiD,EAAarC,KACrCD,EAAoB56B,EAAE66B,GAAYqC,EAAYrC,IAIhD,IADGsC,GAASA,EAAQvC,GACdO,EAASliE,QACd8jE,EAAgB5B,EAAS3c,OAAS,EACnCye,EAA2B9/D,K,GhHnBxBrP,EAAO8sE,EAAoBx5B,EAC/Bw5B,EAAoBx5B,EAAI,IAChBw5B,EAAoBtqD,EAAE,KAAK4rB,KAAKpuC,GiHDd8sE,EAAoBx5B,K","sources":["webpack://telegram-t/webpack/runtime/chunk loaded","webpack://telegram-t/webpack/runtime/startup chunk dependencies","webpack://telegram-t/./src/config.ts","webpack://telegram-t/./src/util/iteratees.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/peers.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/helpers.ts","webpack://telegram-t/./src/util/serverTime.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/chats.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/pathBytesToSvg.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/common.ts","webpack://telegram-t/./src/api/gramjs/localDb.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/symbols.ts","webpack://telegram-t/./src/util/waveform.ts","webpack://telegram-t/./src/api/types/messages.ts","webpack://telegram-t/./src/api/types/media.ts","webpack://telegram-t/./src/api/gramjs/gramjsBuilders/index.ts","webpack://telegram-t/./src/api/gramjs/helpers.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/messages.ts","webpack://telegram-t/./src/api/gramjs/updater.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/users.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/misc.ts","webpack://telegram-t/./src/api/gramjs/methods/auth.ts","webpack://telegram-t/./src/util/files.ts","webpack://telegram-t/./src/util/cacheApi.ts","webpack://telegram-t/./src/api/gramjs/methods/media.ts","webpack://telegram-t/./src/api/gramjs/methods/client.ts","webpack://telegram-t/./src/api/gramjs/methods/chats.ts","webpack://telegram-t/./src/api/gramjs/methods/messages.ts","webpack://telegram-t/./src/api/gramjs/methods/users.ts","webpack://telegram-t/./src/api/gramjs/methods/symbols.ts","webpack://telegram-t/./src/api/gramjs/methods/management.ts","webpack://telegram-t/./src/api/gramjs/methods/twoFaSettings.ts","webpack://telegram-t/./src/api/gramjs/methods/settings.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/bots.ts","webpack://telegram-t/./src/api/gramjs/methods/bots.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/payments.ts","webpack://telegram-t/./src/api/gramjs/methods/payments.ts","webpack://telegram-t/./src/api/gramjs/provider.ts","webpack://telegram-t/./src/util/schedulers.ts","webpack://telegram-t/./src/api/gramjs/worker/worker.ts","webpack://telegram-t/./src/lib/gramjs/Helpers.js","webpack://telegram-t/./src/lib/gramjs/Password.js","webpack://telegram-t/./src/lib/gramjs/Utils.js","webpack://telegram-t/./src/lib/gramjs/Version.js","webpack://telegram-t/./src/lib/gramjs/client/2fa.ts","webpack://telegram-t/./src/lib/gramjs/client/TelegramClient.js","webpack://telegram-t/./src/lib/gramjs/client/auth.ts","webpack://telegram-t/./src/lib/gramjs/client/downloadFile.ts","webpack://telegram-t/./src/lib/gramjs/client/uploadFile.ts","webpack://telegram-t/./src/lib/gramjs/crypto/AuthKey.js","webpack://telegram-t/./src/lib/gramjs/crypto/CTR.js","webpack://telegram-t/./src/lib/gramjs/crypto/Factorizator.js","webpack://telegram-t/./src/lib/gramjs/crypto/IGE.js","webpack://telegram-t/./src/lib/gramjs/crypto/converters.ts","webpack://telegram-t/./src/lib/gramjs/crypto/crypto.js","webpack://telegram-t/./src/lib/gramjs/crypto/words.ts","webpack://telegram-t/./src/lib/gramjs/errors/Common.js","webpack://telegram-t/./src/lib/gramjs/errors/RPCBaseErrors.js","webpack://telegram-t/./src/lib/gramjs/errors/RPCErrorList.js","webpack://telegram-t/./src/lib/gramjs/errors/index.js","webpack://telegram-t/./src/lib/gramjs/events/Raw.js","webpack://telegram-t/./src/lib/gramjs/events/common.js","webpack://telegram-t/./src/lib/gramjs/events/index.js","webpack://telegram-t/./src/lib/gramjs/extensions/AsyncQueue.js","webpack://telegram-t/./src/lib/gramjs/extensions/BinaryReader.js","webpack://telegram-t/./src/lib/gramjs/extensions/BinaryWriter.js","webpack://telegram-t/./src/lib/gramjs/extensions/Logger.js","webpack://telegram-t/./src/lib/gramjs/extensions/MessagePacker.js","webpack://telegram-t/./src/lib/gramjs/extensions/PromisedWebSockets.js","webpack://telegram-t/./src/lib/gramjs/extensions/index.js","webpack://telegram-t/./src/lib/gramjs/index.js","webpack://telegram-t/./src/lib/gramjs/crypto/RSA.ts","webpack://telegram-t/./src/lib/gramjs/network/Authenticator.ts","webpack://telegram-t/./src/lib/gramjs/network/MTProtoPlainSender.js","webpack://telegram-t/./src/lib/gramjs/network/MTProtoSender.js","webpack://telegram-t/./src/lib/gramjs/network/MTProtoState.js","webpack://telegram-t/./src/lib/gramjs/network/RequestState.js","webpack://telegram-t/./src/lib/gramjs/network/connection/Connection.js","webpack://telegram-t/./src/lib/gramjs/network/connection/TCPAbridged.js","webpack://telegram-t/./src/lib/gramjs/network/connection/TCPObfuscated.js","webpack://telegram-t/./src/lib/gramjs/network/connection/index.js","webpack://telegram-t/./src/lib/gramjs/network/index.js","webpack://telegram-t/./src/lib/gramjs/sessions/Abstract.js","webpack://telegram-t/./src/lib/gramjs/sessions/CacheApiSession.js","webpack://telegram-t/./src/lib/gramjs/sessions/CallbackSession.js","webpack://telegram-t/./src/lib/gramjs/sessions/IdbSession.js","webpack://telegram-t/./src/lib/gramjs/sessions/LocalStorageSession.js","webpack://telegram-t/./src/lib/gramjs/sessions/Memory.js","webpack://telegram-t/./src/lib/gramjs/sessions/StorageSession.js","webpack://telegram-t/./src/lib/gramjs/sessions/StringSession.js","webpack://telegram-t/./src/lib/gramjs/sessions/index.js","webpack://telegram-t/./src/lib/gramjs/tl/AllTLObjects.js","webpack://telegram-t/./src/lib/gramjs/tl/api.js","webpack://telegram-t/./src/lib/gramjs/tl/apiTl.js","webpack://telegram-t/./src/lib/gramjs/tl/core/GZIPPacked.js","webpack://telegram-t/./src/lib/gramjs/tl/core/MessageContainer.js","webpack://telegram-t/./src/lib/gramjs/tl/core/RPCResult.js","webpack://telegram-t/./src/lib/gramjs/tl/core/TLMessage.js","webpack://telegram-t/./src/lib/gramjs/tl/core/index.js","webpack://telegram-t/./src/lib/gramjs/tl/generationHelpers.js","webpack://telegram-t/./src/lib/gramjs/tl/index.js","webpack://telegram-t/./src/lib/gramjs/tl/schemaTl.js","webpack://telegram-t/webpack/bootstrap","webpack://telegram-t/webpack/runtime/compat get default export","webpack://telegram-t/webpack/runtime/define property getters","webpack://telegram-t/webpack/runtime/ensure chunk","webpack://telegram-t/webpack/runtime/get javascript chunk filename","webpack://telegram-t/webpack/runtime/get mini-css chunk filename","webpack://telegram-t/webpack/runtime/global","webpack://telegram-t/webpack/runtime/hasOwnProperty shorthand","webpack://telegram-t/webpack/runtime/make namespace object","webpack://telegram-t/webpack/runtime/node module decorator","webpack://telegram-t/webpack/runtime/publicPath","webpack://telegram-t/webpack/runtime/importScripts chunk loading","webpack://telegram-t/webpack/startup"],"sourcesContent":["var deferred = [];\n__webpack_require__.O = (result, chunkIds, fn, priority) => {\n\tif(chunkIds) {\n\t\tpriority = priority || 0;\n\t\tfor(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1];\n\t\tdeferred[i] = [chunkIds, fn, priority];\n\t\treturn;\n\t}\n\tvar notFulfilled = Infinity;\n\tfor (var i = 0; i < deferred.length; i++) {\n\t\tvar [chunkIds, fn, priority] = deferred[i];\n\t\tvar fulfilled = true;\n\t\tfor (var j = 0; j < chunkIds.length; j++) {\n\t\t\tif ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(__webpack_require__.O).every((key) => (__webpack_require__.O[key](chunkIds[j])))) {\n\t\t\t\tchunkIds.splice(j--, 1);\n\t\t\t} else {\n\t\t\t\tfulfilled = false;\n\t\t\t\tif(priority < notFulfilled) notFulfilled = priority;\n\t\t\t}\n\t\t}\n\t\tif(fulfilled) {\n\t\t\tdeferred.splice(i--, 1)\n\t\t\tvar r = fn();\n\t\t\tif (r !== undefined) result = r;\n\t\t}\n\t}\n\treturn result;\n};","var next = __webpack_require__.x;\n__webpack_require__.x = () => {\n\treturn __webpack_require__.e(592).then(next);\n};","export const PAGE_TITLE = 'Telegram';\nexport const INACTIVE_MARKER = ' [Inactive]';\n\nexport const APP_NAME = process.env.APP_NAME || 'Telegram WebZ';\nexport const APP_VERSION = process.env.APP_VERSION || 'dev';\n\nexport const DEBUG = (\n process.env.APP_ENV !== 'production' && process.env.APP_ENV !== 'perf' && process.env.APP_ENV !== 'test'\n);\nexport const DEBUG_MORE = false;\n\nexport const IS_TEST = process.env.APP_ENV === 'test';\nexport const IS_PERF = process.env.APP_ENV === 'perf';\n\nexport const DEBUG_ALERT_MSG = 'Shoot!\\nSomething went wrong, please see the error details in Dev Tools Console.';\nexport const DEBUG_GRAMJS = false;\n\nexport const SESSION_USER_KEY = 'user_auth';\nexport const LEGACY_SESSION_KEY = 'GramJs:sessionId';\n\nexport const GLOBAL_STATE_CACHE_DISABLED = false;\nexport const GLOBAL_STATE_CACHE_KEY = 'tt-global-state';\nexport const GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT = 30;\nexport const GLOBAL_STATE_CACHE_USER_LIST_LIMIT = 5000;\n\nexport const MEDIA_CACHE_DISABLED = false;\nexport const MEDIA_CACHE_NAME = 'tt-media';\nexport const MEDIA_CACHE_NAME_AVATARS = 'tt-media-avatars';\nexport const MEDIA_PROGRESSIVE_CACHE_DISABLED = false;\nexport const MEDIA_PROGRESSIVE_CACHE_NAME = 'tt-media-progressive';\nexport const MEDIA_CACHE_MAX_BYTES = 512 * 1024; // 512 KB\nexport const CUSTOM_BG_CACHE_NAME = 'tt-custom-bg';\nexport const LANG_CACHE_NAME = 'tt-lang-packs-v5';\nexport const ASSET_CACHE_NAME = 'tt-assets';\n\nexport const DOWNLOAD_WORKERS = 16;\nexport const UPLOAD_WORKERS = 16;\n\nconst isBigScreen = typeof window !== 'undefined' && window.innerHeight >= 900;\n\nexport const MIN_PASSWORD_LENGTH = 1;\n\nexport const MESSAGE_LIST_SENSITIVE_AREA = 750;\nexport const MESSAGE_LIST_SLICE = isBigScreen ? 60 : 40;\nexport const MESSAGE_LIST_VIEWPORT_LIMIT = MESSAGE_LIST_SLICE * 2;\n\nexport const CHAT_HEIGHT_PX = 72;\nexport const CHAT_LIST_SLICE = isBigScreen ? 30 : 25;\nexport const CHAT_LIST_LOAD_SLICE = 100;\nexport const SHARED_MEDIA_SLICE = 42;\nexport const MESSAGE_SEARCH_SLICE = 42;\nexport const GLOBAL_SEARCH_SLICE = 20;\nexport const MEMBERS_SLICE = 30;\nexport const MEMBERS_LOAD_SLICE = 200;\nexport const PINNED_MESSAGES_LIMIT = 50;\nexport const BLOCKED_LIST_LIMIT = 100;\nexport const PROFILE_PHOTOS_LIMIT = 40;\nexport const PROFILE_SENSITIVE_AREA = 500;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 20;\nexport const ALL_CHATS_PRELOAD_DISABLED = false;\n\nexport const ANIMATION_LEVEL_MIN = 0;\nexport const ANIMATION_LEVEL_MED = 1;\nexport const ANIMATION_LEVEL_MAX = 2;\nexport const ANIMATION_LEVEL_DEFAULT = ANIMATION_LEVEL_MAX;\n\nexport const DEFAULT_MESSAGE_TEXT_SIZE_PX = 16;\nexport const IOS_DEFAULT_MESSAGE_TEXT_SIZE_PX = 17;\nexport const MACOS_DEFAULT_MESSAGE_TEXT_SIZE_PX = 15;\n\nexport const DRAFT_DEBOUNCE = 10000; // 10s\n\nexport const EDITABLE_INPUT_ID = 'editable-message-text';\nexport const EDITABLE_INPUT_MODAL_ID = 'editable-message-text-modal';\n\n// Screen width where Pinned Message / Audio Player in the Middle Header can be safely displayed\nexport const SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1440; // px\n// Screen width where Pinned Message / Audio Player in the Middle Header shouldn't collapse with ChatInfo\nexport const SAFE_SCREEN_WIDTH_FOR_CHAT_INFO = 1150; // px\n\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1275; // px\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN = 925; // px\nexport const MOBILE_SCREEN_MAX_WIDTH = 600; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH = 950; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT = 450; // px\n\nexport const LOCAL_MESSAGE_ID_BASE = 1e9;\n\nexport const ANIMATION_END_DELAY = 100;\n\nexport const FAST_SMOOTH_MAX_DISTANCE = 1500;\nexport const FAST_SMOOTH_MIN_DURATION = 250;\nexport const FAST_SMOOTH_MAX_DURATION = 600;\nexport const FAST_SMOOTH_SHORT_TRANSITION_MAX_DISTANCE = 500; // px\n\n// Average duration of message sending animation\nexport const API_UPDATE_THROTTLE = Math.round((FAST_SMOOTH_MIN_DURATION + FAST_SMOOTH_MAX_DURATION) / 2);\nexport const API_THROTTLE_RESET_UPDATES = new Set([\n 'newMessage', 'newScheduledMessage', 'deleteMessages', 'deleteScheduledMessages', 'deleteHistory',\n]);\n\nexport const STICKER_SIZE_INLINE_DESKTOP_FACTOR = 13;\nexport const STICKER_SIZE_INLINE_MOBILE_FACTOR = 11;\nexport const STICKER_SIZE_AUTH = 160;\nexport const STICKER_SIZE_AUTH_MOBILE = 120;\nexport const STICKER_SIZE_PICKER = 64;\nexport const STICKER_SIZE_GENERAL_SETTINGS = 48;\nexport const STICKER_SIZE_PICKER_HEADER = 32;\nexport const STICKER_SIZE_SEARCH = 64;\nexport const STICKER_SIZE_MODAL = 64;\nexport const STICKER_SIZE_TWO_FA = 160;\nexport const STICKER_SIZE_DISCUSSION_GROUPS = 140;\nexport const STICKER_SIZE_FOLDER_SETTINGS = 80;\nexport const STICKER_SIZE_INLINE_BOT_RESULT = 100;\nexport const RECENT_STICKERS_LIMIT = 20;\nexport const MEMOJI_STICKER_ID = 'MEMOJI_STICKER';\n\nexport const BASE_EMOJI_KEYWORD_LANG = 'en';\n\nexport const MENU_TRANSITION_DURATION = 200;\nexport const SLIDE_TRANSITION_DURATION = 450;\n\nexport const CONTENT_TYPES_FOR_QUICK_UPLOAD = new Set([\n 'image/png', 'image/gif', 'image/jpeg', 'video/mp4', 'video/avi', 'video/quicktime',\n]);\n\n// eslint-disable-next-line max-len\nexport const RE_LINK_TEMPLATE = '((ftp|https?):\\\\/\\\\/)?((www\\\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\\\.[a-zA-Z0-9()]{1,63})\\\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)';\nexport const RE_MENTION_TEMPLATE = '(@[\\\\w\\\\d_-]+)';\nexport const RE_TME_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/)([\\d\\w_]+)(?:\\/([\\d]+))?(?:\\/([\\d]+))?$/gm;\nexport const RE_TME_INVITE_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/joinchat\\/)([\\d\\w_-]+)?$/gm;\n\n// MTProto constants\nexport const SERVICE_NOTIFICATIONS_USER_ID = 777000;\nexport const REPLIES_USER_ID = 1271266957;\nexport const ALL_FOLDER_ID = 0;\nexport const ARCHIVED_FOLDER_ID = 1;\nexport const DELETED_COMMENTS_CHANNEL_ID = 777;\nexport const MAX_MEDIA_FILES_FOR_ALBUM = 10;\nexport const MAX_ACTIVE_PINNED_CHATS = 5;\nexport const SCHEDULED_WHEN_ONLINE = 0x7FFFFFFE;\nexport const DEFAULT_LANG_CODE = 'en';\nexport const DEFAULT_LANG_PACK = 'android';\nexport const LANG_PACKS = ['android', 'ios', 'tdesktop', 'macos'] as const;\nexport const TIPS_USERNAME = 'TelegramTips';\nexport const LOCALIZED_TIPS = ['ar', 'pt-br', 'id', 'it', 'ko', 'ms', 'pl', 'es', 'tr'];\nexport const FEEDBACK_URL = 'https://bugs.telegram.org/?tag_ids=41&sort=time';\nexport const LIGHT_THEME_BG_COLOR = '#A2AF8E';\nexport const DARK_THEME_BG_COLOR = '#0F0F0F';\nexport const DARK_THEME_PATTERN_COLOR = '#0a0a0a8c';\nexport const DEFAULT_PATTERN_COLOR = 'rgba(90, 110, 70, 0.6)';\n","type CollectionByKey<Member> = Record<number | string, Member>;\n\ntype OrderDirection = 'asc' | 'desc';\n\ninterface OrderCallback<T> {\n (member: T): any;\n}\n\nexport function buildCollectionByKey<T extends AnyLiteral>(collection: T[], key: keyof T) {\n return collection.reduce((byKey: CollectionByKey<T>, member: T) => {\n byKey[member[key]] = member;\n\n return byKey;\n }, {});\n}\n\nexport function mapValues<R extends any, M extends any>(\n byKey: CollectionByKey<M>,\n callback: (member: M, key: string, index: number, originalByKey: CollectionByKey<M>) => R,\n): CollectionByKey<R> {\n return Object.keys(byKey).reduce((newByKey: CollectionByKey<R>, key, index) => {\n newByKey[key] = callback(byKey[key], key, index, byKey);\n return newByKey;\n }, {});\n}\n\nexport function pick<T, K extends keyof T>(object: T, keys: K[]) {\n return keys.reduce((result, key) => {\n result[key] = object[key];\n return result;\n }, {} as Pick<T, K>);\n}\n\nexport function pickTruthy<T, K extends keyof T>(object: T, keys: K[]) {\n return keys.reduce((result, key) => {\n if (object[key]) {\n result[key] = object[key];\n }\n\n return result;\n }, {} as Pick<T, K>);\n}\n\nexport function omit<T, K extends keyof T>(object: T, keys: K[]) {\n const stringKeys = new Set(keys.map(String));\n const savedKeys = Object.keys(object)\n .filter((key) => !stringKeys.has(key)) as Array<Exclude<keyof T, K>>;\n\n return pick(object, savedKeys);\n}\n\nexport function orderBy<T>(\n collection: T[],\n orderKey: (keyof T) | OrderCallback<T> | ((keyof T) | OrderCallback<T>)[],\n mode: OrderDirection | [OrderDirection, OrderDirection] = 'asc',\n): T[] {\n return collection.sort((a, b) => {\n if (Array.isArray(orderKey)) {\n const [mode1, mode2] = Array.isArray(mode) ? mode : [mode, mode];\n const [orderKey1, orderKey2] = orderKey;\n\n let aValue1;\n let bValue1;\n\n if (typeof orderKey1 === 'function') {\n aValue1 = orderKey1(a) || 0;\n bValue1 = orderKey1(b) || 0;\n } else if (typeof orderKey1 === 'string') {\n aValue1 = a[orderKey1] || 0;\n bValue1 = b[orderKey1] || 0;\n }\n\n if (aValue1 !== bValue1) {\n return mode1 === 'asc' ? aValue1 - bValue1 : bValue1 - aValue1;\n } else {\n let aValue2;\n let bValue2;\n\n if (typeof orderKey2 === 'function') {\n aValue2 = orderKey2(a) || 0;\n bValue2 = orderKey2(b) || 0;\n } else if (typeof orderKey2 === 'string') {\n aValue2 = a[orderKey2] || 0;\n bValue2 = b[orderKey2] || 0;\n }\n\n return mode2 === 'asc' ? aValue2 - bValue2 : bValue2 - aValue2;\n }\n }\n\n let aValue;\n let bValue;\n\n if (typeof orderKey === 'function') {\n aValue = orderKey(a) || 0;\n bValue = orderKey(b) || 0;\n } else if (typeof orderKey === 'string') {\n aValue = a[orderKey] || 0;\n bValue = b[orderKey] || 0;\n }\n\n return mode === 'asc' ? aValue - bValue : bValue - aValue;\n });\n}\n\nexport function flatten(array: any[]) {\n return array.reduce((result, member) => {\n if (Array.isArray(member)) {\n return result.concat(member);\n } else {\n result.push(member);\n return result;\n }\n }, []);\n}\n\nexport function unique<T extends any>(array: T[]): T[] {\n return Array.from(new Set(array));\n}\n\nexport function compact(array: any[]) {\n return array.filter(Boolean);\n}\n\nexport function areSortedArraysEqual(array1: any[], array2: any[]) {\n if (array1.length !== array2.length) {\n return false;\n }\n\n return array1.every((item, i) => item === array2[i]);\n}\n\nexport function areSortedArraysIntersecting(array1: any[], array2: any[]) {\n return array1[0] <= array2[array2.length - 1] && array1[array1.length - 1] >= array2[0];\n}\n\nexport function findIntersectionWithSet<T>(array: T[], set: Set<T>): T[] {\n return array.filter((a) => set.has(a));\n}\n\nexport function split(array: any[], chunkSize: number) {\n const result = [];\n for (let i = 0; i < array.length; i += chunkSize) {\n result.push(array.slice(i, i + chunkSize));\n }\n\n return result;\n}\n\nexport function cloneDeep<T>(value: T): T {\n if (typeof value !== 'object') {\n return value;\n }\n\n if (Array.isArray(value)) {\n return value.map(cloneDeep) as typeof value;\n }\n\n return Object.keys(value).reduce((acc, key) => {\n acc[key as keyof T] = cloneDeep(value[key as keyof T]);\n return acc;\n }, {} as T);\n}\n\n/**\n * Returns the index of the last element in the array where predicate is true, and -1 otherwise.\n *\n * @param array The source array to search in\n * @param predicate find calls predicate once for each element of the array, in descending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.\n */\nexport function findLast<T>(array: Array<T>, predicate: (value: T, index: number, obj: T[]) => boolean): T | undefined {\n let cursor = array.length;\n\n while (cursor--) {\n if (predicate(array[cursor], cursor, array)) {\n return array[cursor];\n }\n }\n\n return undefined;\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\n\nexport function isPeerUser(peer: GramJs.TypePeer): peer is GramJs.PeerUser {\n return peer.hasOwnProperty('userId');\n}\n\nexport function isPeerChat(peer: GramJs.TypePeer): peer is GramJs.PeerChat {\n return peer.hasOwnProperty('chatId');\n}\n\nexport function isPeerChannel(peer: GramJs.TypePeer): peer is GramJs.PeerChannel {\n return peer.hasOwnProperty('channelId');\n}\n\nexport function isInputPeerUser(peer: GramJs.TypeInputPeer): peer is GramJs.InputPeerUser {\n return peer.hasOwnProperty('userId');\n}\n\nexport function isInputPeerChat(peer: GramJs.TypeInputPeer): peer is GramJs.InputPeerChat {\n return peer.hasOwnProperty('chatId');\n}\n\nexport function isInputPeerChannel(peer: GramJs.TypeInputPeer): peer is GramJs.InputPeerChannel {\n return peer.hasOwnProperty('channelId');\n}\n","export function bytesToDataUri(bytes: Buffer, shouldOmitPrefix = false, mimeType: string = 'image/jpeg') {\n const prefix = shouldOmitPrefix ? '' : `data:${mimeType};base64,`;\n\n return `${prefix}${btoa(String.fromCharCode(...bytes))}`;\n}\n\nexport function omitVirtualClassFields(instance: any) {\n if (!instance) {\n return undefined;\n }\n\n const {\n flags,\n CONSTRUCTOR_ID,\n SUBCLASS_OF_ID,\n className,\n classType,\n ...rest\n } = instance;\n\n return rest;\n}\n","export const getServerTime = (serverTimeOffset: number) => {\n return Math.floor(Date.now() / 1000) + serverTimeOffset;\n};\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n ApiChat,\n ApiChatAdminRights,\n ApiChatBannedRights,\n ApiBotCommand,\n ApiChatFolder,\n ApiChatMember,\n ApiRestrictionReason,\n} from '../../types';\nimport { pick, pickTruthy } from '../../../util/iteratees';\nimport {\n isInputPeerChannel, isInputPeerChat, isInputPeerUser, isPeerChat, isPeerUser,\n} from './peers';\nimport { omitVirtualClassFields } from './helpers';\nimport { getServerTime } from '../../../util/serverTime';\n\ntype PeerEntityApiChatFields = Omit<ApiChat, (\n 'id' | 'type' | 'title' |\n 'lastReadOutboxMessageId' | 'lastReadInboxMessageId' |\n 'unreadCount' | 'unreadMentionsCount' | 'isMuted'\n)>;\n\nfunction buildApiChatFieldsFromPeerEntity(\n peerEntity: GramJs.TypeUser | GramJs.TypeChat,\n isSupport = false,\n): PeerEntityApiChatFields {\n const isMin = Boolean('min' in peerEntity && peerEntity.min);\n const accessHash = ('accessHash' in peerEntity) && String(peerEntity.accessHash);\n const avatarHash = ('photo' in peerEntity) && peerEntity.photo && buildAvatarHash(peerEntity.photo);\n const isSignaturesShown = Boolean('signatures' in peerEntity && peerEntity.signatures);\n const hasPrivateLink = Boolean('hasLink' in peerEntity && peerEntity.hasLink);\n\n return {\n isMin,\n hasPrivateLink,\n isSignaturesShown,\n ...(accessHash && { accessHash }),\n ...(avatarHash && { avatarHash }),\n ...(\n (peerEntity instanceof GramJs.Channel || peerEntity instanceof GramJs.User)\n && { username: peerEntity.username }\n ),\n ...(('verified' in peerEntity) && { isVerified: peerEntity.verified }),\n ...(('callActive' in peerEntity) && { isCallActive: peerEntity.callActive }),\n ...(('callNotEmpty' in peerEntity) && { isCallNotEmpty: peerEntity.callNotEmpty }),\n ...((peerEntity instanceof GramJs.Chat || peerEntity instanceof GramJs.Channel) && {\n ...(peerEntity.participantsCount && { membersCount: peerEntity.participantsCount }),\n joinDate: peerEntity.date,\n }),\n ...(isSupport && { isSupport: true }),\n ...buildApiChatPermissions(peerEntity),\n ...(('creator' in peerEntity) && { isCreator: peerEntity.creator }),\n ...buildApiChatRestrictions(peerEntity),\n ...buildApiChatMigrationInfo(peerEntity),\n };\n}\n\nexport function buildApiChatFromDialog(\n dialog: GramJs.Dialog,\n peerEntity: GramJs.TypeUser | GramJs.TypeChat,\n serverTimeOffset: number,\n): ApiChat {\n const {\n peer, folderId, unreadMark, unreadCount, unreadMentionsCount, notifySettings: { silent, muteUntil },\n readOutboxMaxId, readInboxMaxId, draft,\n } = dialog;\n const isMuted = silent || (typeof muteUntil === 'number' && getServerTime(serverTimeOffset) < muteUntil);\n\n return {\n id: getApiChatIdFromMtpPeer(peer),\n ...(folderId && { folderId }),\n type: getApiChatTypeFromPeerEntity(peerEntity),\n title: getApiChatTitleFromMtpPeer(peer, peerEntity),\n lastReadOutboxMessageId: readOutboxMaxId,\n lastReadInboxMessageId: readInboxMaxId,\n unreadCount,\n unreadMentionsCount,\n isMuted,\n ...(unreadMark && { hasUnreadMark: true }),\n ...(draft instanceof GramJs.DraftMessage && { draftDate: draft.date }),\n ...buildApiChatFieldsFromPeerEntity(peerEntity),\n };\n}\n\nfunction buildApiChatPermissions(peerEntity: GramJs.TypeUser | GramJs.TypeChat): {\n adminRights?: ApiChatAdminRights;\n currentUserBannedRights?: ApiChatBannedRights;\n defaultBannedRights?: ApiChatBannedRights;\n} {\n if (!(peerEntity instanceof GramJs.Chat || peerEntity instanceof GramJs.Channel)) {\n return {};\n }\n\n return {\n adminRights: omitVirtualClassFields(peerEntity.adminRights),\n currentUserBannedRights: peerEntity instanceof GramJs.Channel\n ? omitVirtualClassFields(peerEntity.bannedRights)\n : undefined,\n defaultBannedRights: omitVirtualClassFields(peerEntity.defaultBannedRights),\n };\n}\n\nfunction buildApiChatRestrictions(peerEntity: GramJs.TypeUser | GramJs.TypeChat): {\n isNotJoined?: boolean;\n isRestricted?: boolean;\n restrictionReason?: ApiRestrictionReason;\n} {\n if (peerEntity instanceof GramJs.ChatForbidden || peerEntity instanceof GramJs.ChannelForbidden) {\n return {\n isRestricted: true,\n };\n }\n\n const restrictions = {};\n\n if ('restricted' in peerEntity) {\n const restrictionReason = peerEntity.restricted\n ? buildApiChatRestrictionReason(peerEntity.restrictionReason)\n : undefined;\n\n if (restrictionReason) {\n Object.assign(restrictions, {\n isRestricted: true,\n restrictionReason,\n });\n }\n }\n\n if (peerEntity instanceof GramJs.Chat) {\n Object.assign(restrictions, {\n isNotJoined: peerEntity.left,\n isRestricted: peerEntity.kicked,\n });\n }\n\n if (peerEntity instanceof GramJs.Channel) {\n Object.assign(restrictions, {\n // `left` is weirdly set to `true` on all channels never joined before\n isNotJoined: peerEntity.left,\n });\n }\n\n return restrictions;\n}\n\nfunction buildApiChatMigrationInfo(peerEntity: GramJs.TypeChat): {\n migratedTo?: {\n chatId: number;\n accessHash?: string;\n };\n} {\n if (\n peerEntity instanceof GramJs.Chat\n && peerEntity.migratedTo\n && !(peerEntity.migratedTo instanceof GramJs.InputChannelEmpty)\n ) {\n return {\n migratedTo: {\n chatId: getApiChatIdFromMtpPeer(peerEntity.migratedTo),\n ...(peerEntity.migratedTo instanceof GramJs.InputChannel && {\n accessHash: peerEntity.migratedTo.accessHash.toString(),\n }),\n },\n };\n }\n\n return {};\n}\n\nfunction buildApiChatRestrictionReason(\n restrictionReasons?: GramJs.RestrictionReason[],\n): ApiRestrictionReason | undefined {\n if (!restrictionReasons) {\n return undefined;\n }\n\n const targetReason = restrictionReasons.find(({ platform }) => platform === 'all');\n return targetReason ? pick(targetReason, ['reason', 'text']) : undefined;\n}\n\nexport function buildApiChatFromPreview(\n preview: GramJs.TypeChat | GramJs.TypeUser,\n isSupport = false,\n withForbidden = false,\n): ApiChat | undefined {\n if (!(\n preview instanceof GramJs.Chat\n || preview instanceof GramJs.Channel\n || preview instanceof GramJs.User\n || (\n withForbidden\n && (\n preview instanceof GramJs.ChatForbidden\n || preview instanceof GramJs.ChannelForbidden\n )\n )\n )) {\n return undefined;\n }\n\n return {\n id: preview instanceof GramJs.User ? preview.id : -preview.id,\n type: getApiChatTypeFromPeerEntity(preview),\n title: preview instanceof GramJs.User ? getUserName(preview) : preview.title,\n ...buildApiChatFieldsFromPeerEntity(preview, isSupport),\n };\n}\n\nexport function getApiChatIdFromMtpPeer(peer: GramJs.TypePeer): number {\n if (isPeerUser(peer)) {\n return peer.userId;\n } else if (isPeerChat(peer)) {\n return -peer.chatId;\n } else {\n return -peer.channelId;\n }\n}\n\nexport function getApiChatIdFromInputMtpPeer(peer: GramJs.TypeInputPeer): number | undefined {\n if (isInputPeerUser(peer)) {\n return peer.userId;\n } else if (isInputPeerChat(peer)) {\n return -peer.chatId;\n } else if (isInputPeerChannel(peer)) {\n return -peer.channelId;\n }\n return undefined;\n}\n\nexport function getApiChatTypeFromPeerEntity(peerEntity: GramJs.TypeChat | GramJs.TypeUser) {\n if (peerEntity instanceof GramJs.User || peerEntity instanceof GramJs.UserEmpty) {\n return 'chatTypePrivate';\n } else if (\n peerEntity instanceof GramJs.Chat\n || peerEntity instanceof GramJs.ChatForbidden\n || peerEntity instanceof GramJs.ChatEmpty\n ) {\n return 'chatTypeBasicGroup';\n } else {\n return peerEntity.megagroup ? 'chatTypeSuperGroup' : 'chatTypeChannel';\n }\n}\n\nexport function getPeerKey(peer: GramJs.TypePeer) {\n if (isPeerUser(peer)) {\n return `user${peer.userId}`;\n } else if (isPeerChat(peer)) {\n return `chat${peer.chatId}`;\n } else {\n return `chat${peer.channelId}`;\n }\n}\n\nexport function getApiChatTitleFromMtpPeer(peer: GramJs.TypePeer, peerEntity: GramJs.User | GramJs.Chat) {\n if (isPeerUser(peer)) {\n return getUserName(peerEntity as GramJs.User);\n } else {\n return (peerEntity as GramJs.Chat).title;\n }\n}\n\nfunction getUserName(user: GramJs.User) {\n return user.firstName\n ? `${user.firstName}${user.lastName ? ` ${user.lastName}` : ''}`\n : (user.lastName || undefined);\n}\n\nexport function buildAvatarHash(photo: GramJs.TypeUserProfilePhoto | GramJs.TypeChatPhoto) {\n if ('photoId' in photo) {\n return photo.photoId.toString();\n }\n\n return undefined;\n}\n\nexport function buildChatMember(\n member: GramJs.TypeChatParticipant | GramJs.TypeChannelParticipant,\n): ApiChatMember | undefined {\n const userId = (member instanceof GramJs.ChannelParticipantBanned || member instanceof GramJs.ChannelParticipantLeft)\n ? getApiChatIdFromMtpPeer(member.peer)\n : member.userId;\n\n return {\n userId,\n inviterId: 'inviterId' in member ? member.inviterId : undefined,\n joinedDate: 'date' in member ? member.date : undefined,\n kickedByUserId: 'kickedBy' in member ? member.kickedBy : undefined,\n promotedByUserId: 'promotedBy' in member ? member.promotedBy : undefined,\n bannedRights: 'bannedRights' in member ? omitVirtualClassFields(member.bannedRights) : undefined,\n adminRights: 'adminRights' in member ? omitVirtualClassFields(member.adminRights) : undefined,\n customTitle: 'rank' in member ? member.rank : undefined,\n ...((member instanceof GramJs.ChannelParticipantAdmin || member instanceof GramJs.ChatParticipantAdmin) && {\n isAdmin: true,\n }),\n ...((member instanceof GramJs.ChannelParticipantCreator || member instanceof GramJs.ChatParticipantCreator) && {\n isOwner: true,\n }),\n };\n}\n\nexport function buildChatMembers(\n participants: GramJs.TypeChatParticipants | GramJs.channels.ChannelParticipants,\n) {\n // Duplicate code because of TS union-type shenanigans\n if (participants instanceof GramJs.ChatParticipants) {\n return participants.participants.map(buildChatMember).filter<ApiChatMember>(Boolean as any);\n }\n if (participants instanceof GramJs.channels.ChannelParticipants) {\n return participants.participants.map(buildChatMember).filter<ApiChatMember>(Boolean as any);\n }\n\n return undefined;\n}\n\nexport function buildChatTypingStatus(\n update: GramJs.UpdateUserTyping | GramJs.UpdateChatUserTyping | GramJs.UpdateChannelUserTyping,\n serverTimeOffset: number,\n) {\n let action: string = '';\n if (update.action instanceof GramJs.SendMessageCancelAction) {\n return undefined;\n } else if (update.action instanceof GramJs.SendMessageTypingAction) {\n action = 'lng_user_typing';\n } else if (update.action instanceof GramJs.SendMessageRecordVideoAction) {\n action = 'lng_send_action_record_video';\n } else if (update.action instanceof GramJs.SendMessageUploadVideoAction) {\n action = 'lng_send_action_upload_video';\n } else if (update.action instanceof GramJs.SendMessageRecordAudioAction) {\n action = 'lng_send_action_record_audio';\n } else if (update.action instanceof GramJs.SendMessageUploadAudioAction) {\n action = 'lng_send_action_upload_audio';\n } else if (update.action instanceof GramJs.SendMessageUploadPhotoAction) {\n action = 'lng_send_action_upload_photo';\n } else if (update.action instanceof GramJs.SendMessageUploadDocumentAction) {\n action = 'lng_send_action_upload_file';\n } else if (update.action instanceof GramJs.SendMessageGeoLocationAction) {\n action = 'selecting a location to share';\n } else if (update.action instanceof GramJs.SendMessageChooseContactAction) {\n action = 'selecting a contact to share';\n } else if (update.action instanceof GramJs.SendMessageGamePlayAction) {\n action = 'lng_playing_game';\n } else if (update.action instanceof GramJs.SendMessageRecordRoundAction) {\n action = 'lng_send_action_record_round';\n } else if (update.action instanceof GramJs.SendMessageUploadRoundAction) {\n action = 'lng_send_action_upload_round';\n }\n\n return {\n action,\n ...(!(update instanceof GramJs.UpdateUserTyping) && { userId: getApiChatIdFromMtpPeer(update.fromId) }),\n timestamp: Date.now() + serverTimeOffset * 1000,\n };\n}\n\nexport function buildApiChatFolder(filter: GramJs.DialogFilter): ApiChatFolder {\n return {\n ...pickTruthy(filter, [\n 'id', 'title', 'emoticon', 'contacts', 'nonContacts', 'groups', 'bots',\n 'excludeMuted', 'excludeRead', 'excludeArchived',\n ]),\n channels: filter.broadcasts,\n pinnedChatIds: filter.pinnedPeers.map(getApiChatIdFromInputMtpPeer).filter<number>(Boolean as any),\n includedChatIds: filter.includePeers.map(getApiChatIdFromInputMtpPeer).filter<number>(Boolean as any),\n excludedChatIds: filter.excludePeers.map(getApiChatIdFromInputMtpPeer).filter<number>(Boolean as any),\n };\n}\n\nexport function buildApiChatFolderFromSuggested({\n filter, description,\n}: {\n filter: GramJs.DialogFilter;\n description: string;\n}): ApiChatFolder {\n return {\n ...buildApiChatFolder(filter),\n description,\n };\n}\n\nexport function buildApiChatBotCommands(botInfos: GramJs.BotInfo[]) {\n return botInfos.reduce((botCommands, botInfo) => {\n botCommands = botCommands.concat(botInfo.commands.map((mtpCommand) => ({\n botId: botInfo.userId,\n ...omitVirtualClassFields(mtpCommand),\n })));\n\n return botCommands;\n }, [] as ApiBotCommand[]);\n}\n","/* eslint-disable no-bitwise */\n\n// eslint-disable-next-line max-len\nconst TEMPLATE = '<?xml version=\"1.0\" encoding=\"utf-8\"?><svg version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" viewBox=\"0 0 {{width}} {{height}}\" xml:space=\"preserve\"><path fill-opacity=\"0.1\" d=\"{{path}}\" /></svg>';\nconst LOOKUP = 'AACAAAAHAAALMAAAQASTAVAAAZaacaaaahaaalmaaaqastava.az0123456789-,';\n\nexport function pathBytesToSvg(bytes: Buffer, width: number, height: number) {\n return TEMPLATE\n .replace('{{path}}', buildPath(bytes))\n .replace('{{width}}', String(width))\n .replace('{{height}}', String(height));\n}\n\nfunction buildPath(bytes: Buffer) {\n let path = 'M';\n\n const len = bytes.length;\n for (let i = 0; i < len; i++) {\n const num = bytes[i];\n if (num >= 128 + 64) {\n path += LOOKUP[num - 128 - 64];\n } else {\n if (num >= 128) {\n path += ',';\n } else if (num >= 64) {\n path += '-';\n }\n path += String(num & 63);\n }\n }\n\n path += 'z';\n\n return path;\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport { strippedPhotoToJpg } from '../../../lib/gramjs/Utils';\n\nimport {\n ApiPhoto, ApiPhotoSize, ApiThumbnail,\n} from '../../types';\nimport { bytesToDataUri } from './helpers';\nimport { pathBytesToSvg } from './pathBytesToSvg';\n\nconst DEFAULT_THUMB_SIZE = { w: 100, h: 100 };\n\nexport function buildApiThumbnailFromStripped(\n sizes?: GramJs.TypePhotoSize[], mimeType?: string,\n): ApiThumbnail | undefined {\n if (!sizes || !sizes.length) {\n return undefined;\n }\n\n const thumb = sizes.find((s: any): s is GramJs.PhotoStrippedSize => s instanceof GramJs.PhotoStrippedSize);\n if (!thumb) {\n return undefined;\n }\n\n const realSizes = sizes.filter((s): s is GramJs.PhotoSize => s instanceof GramJs.PhotoSize);\n const { w, h } = realSizes && realSizes.length ? realSizes[realSizes.length - 1] : DEFAULT_THUMB_SIZE;\n const { bytes } = thumb;\n const dataUri = bytesToDataUri(\n !mimeType || mimeType === 'image/jpeg' ? strippedPhotoToJpg(bytes) : bytes,\n undefined,\n mimeType,\n );\n\n return {\n dataUri,\n width: w,\n height: h,\n };\n}\n\nexport function buildApiThumbnailFromCached(photoSize: GramJs.PhotoCachedSize): ApiThumbnail | undefined {\n const { w, h, bytes } = photoSize;\n const dataUri = bytesToDataUri(bytes, undefined, 'image/webp');\n\n return {\n dataUri,\n width: w,\n height: h,\n };\n}\n\nexport function buildApiThumbnailFromPath(\n photoSize: GramJs.PhotoPathSize,\n sizeAttribute: GramJs.DocumentAttributeImageSize,\n): ApiThumbnail | undefined {\n const { w, h } = sizeAttribute;\n const dataUri = `data:image/svg+xml;utf8,${pathBytesToSvg(photoSize.bytes, w, h)}`;\n\n return {\n dataUri,\n width: w,\n height: h,\n };\n}\n\nexport function buildApiPhoto(photo: GramJs.Photo): ApiPhoto {\n const sizes = photo.sizes\n .filter((s: any): s is GramJs.PhotoSize => {\n return s instanceof GramJs.PhotoSize || s instanceof GramJs.PhotoSizeProgressive;\n })\n .map(buildApiPhotoSize);\n\n return {\n id: String(photo.id),\n thumbnail: buildApiThumbnailFromStripped(photo.sizes),\n sizes,\n };\n}\n\nexport function buildApiPhotoSize(photoSize: GramJs.PhotoSize): ApiPhotoSize {\n const { w, h, type } = photoSize;\n\n return {\n width: w,\n height: h,\n type: type as ('m' | 'x' | 'y'),\n };\n}\n","import { Api as GramJs } from '../../lib/gramjs';\nimport { ApiMessage } from '../types';\n\ninterface LocalDb {\n localMessages: Record<string, ApiMessage>;\n // Used for loading avatars and media through in-memory Gram JS instances.\n chats: Record<number, GramJs.Chat | GramJs.Channel>;\n users: Record<number, GramJs.User>;\n messages: Record<string, GramJs.Message | GramJs.MessageService>;\n documents: Record<string, GramJs.Document>;\n stickerSets: Record<string, GramJs.StickerSet>;\n photos: Record<string, GramJs.Photo>;\n webDocuments: Record<string, GramJs.TypeWebDocument>;\n}\n\nexport default {\n localMessages: {},\n chats: {},\n users: {},\n messages: {},\n documents: {},\n stickerSets: {},\n photos: {},\n webDocuments: {},\n} as LocalDb;\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport { ApiSticker, ApiStickerSet } from '../../types';\nimport { MEMOJI_STICKER_ID } from '../../../config';\n\nimport { buildApiThumbnailFromCached, buildApiThumbnailFromPath } from './common';\nimport localDb from '../localDb';\n\nconst ANIMATED_STICKER_MIME_TYPE = 'application/x-tgsticker';\n\nexport function buildStickerFromDocument(document: GramJs.TypeDocument): ApiSticker | undefined {\n if (document instanceof GramJs.DocumentEmpty) {\n return undefined;\n }\n\n const stickerAttribute = document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeSticker => (\n attr instanceof GramJs.DocumentAttributeSticker\n ));\n\n const fileAttribute = document.mimeType === ANIMATED_STICKER_MIME_TYPE && document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeFilename => (\n attr instanceof GramJs.DocumentAttributeFilename\n ));\n\n if (!stickerAttribute && !fileAttribute) {\n return undefined;\n }\n\n const sizeAttribute = document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeImageSize => (\n attr instanceof GramJs.DocumentAttributeImageSize\n ));\n\n const stickerSetInfo = stickerAttribute && stickerAttribute.stickerset instanceof GramJs.InputStickerSetID\n ? stickerAttribute.stickerset\n : undefined;\n const emoji = stickerAttribute ? stickerAttribute.alt : undefined;\n const isAnimated = document.mimeType === ANIMATED_STICKER_MIME_TYPE;\n const cachedThumb = document.thumbs && document.thumbs.find(\n (s): s is GramJs.PhotoCachedSize => s instanceof GramJs.PhotoCachedSize,\n );\n const pathThumb = document.thumbs && document.thumbs.find(\n (s): s is GramJs.PhotoPathSize => s instanceof GramJs.PhotoPathSize,\n );\n const thumbnail = cachedThumb ? (\n buildApiThumbnailFromCached(cachedThumb)\n ) : pathThumb && sizeAttribute ? (\n buildApiThumbnailFromPath(pathThumb, sizeAttribute)\n ) : undefined;\n\n const { w: width, h: height } = cachedThumb as GramJs.PhotoCachedSize || sizeAttribute || {};\n\n return {\n id: String(document.id),\n stickerSetId: stickerSetInfo ? String(stickerSetInfo.id) : MEMOJI_STICKER_ID,\n stickerSetAccessHash: stickerSetInfo && String(stickerSetInfo.accessHash),\n emoji,\n isAnimated,\n width,\n height,\n thumbnail,\n };\n}\n\nexport function buildStickerSet(set: GramJs.StickerSet): ApiStickerSet {\n const {\n archived,\n animated,\n installedDate,\n id,\n accessHash,\n title,\n thumbs,\n count,\n hash,\n shortName,\n } = set;\n\n return {\n archived,\n isAnimated: animated,\n installedDate,\n id: String(id),\n accessHash: String(accessHash),\n title,\n hasThumbnail: Boolean(thumbs && thumbs.length),\n count,\n hash,\n shortName,\n };\n}\n\nexport function buildStickerSetCovered(coveredStickerSet: GramJs.TypeStickerSetCovered): ApiStickerSet {\n const stickerSet = buildStickerSet(coveredStickerSet.set);\n\n const stickerSetCovers = (coveredStickerSet instanceof GramJs.StickerSetMultiCovered)\n ? coveredStickerSet.covers\n : [coveredStickerSet.cover];\n\n stickerSet.covers = [];\n stickerSetCovers.forEach((cover) => {\n if (cover instanceof GramJs.Document) {\n const coverSticker = buildStickerFromDocument(cover);\n if (coverSticker) {\n stickerSet.covers!.push(coverSticker);\n localDb.documents[String(cover.id)] = cover;\n }\n }\n });\n\n return stickerSet;\n}\n","/* eslint-disable no-bitwise */\n\n// eslint-disable-next-line max-len\n// Ref: https://github.com/telegramdesktop/tdesktop/blob/0743e71ab6b928d2ee5bae1aed991849b1e2b291/Telegram/SourceFiles/data/data_document.cpp#L1018\nexport function decodeWaveform(encoded5bit: Uint8Array) {\n const bitsCount = encoded5bit.length * 8;\n const valuesCount = Math.floor(bitsCount / 5);\n if (!valuesCount) {\n return [];\n }\n\n // Read each 5 bit of encoded5bit as 0-31 unsigned char.\n // We count the index of the byte in which the desired 5-bit sequence starts.\n // And then we read a uint16 starting from that byte to guarantee to get all of those 5 bits.\n //\n // BUT! if it is the last byte we have, we're not allowed to read a uint16 starting with it.\n // Because it will be an overflow (we'll access one byte after the available memory).\n // We see, that only the last 5 bits could start in the last available byte and be problematic.\n // So we read in a general way all the entries in a general way except the last one.\n const result = Array(valuesCount);\n const bitsData = encoded5bit;\n for (let i = 0, l = valuesCount - 1; i !== l; ++i) {\n const byteIndex = Math.floor((i * 5) / 8);\n const bitShift = Math.floor((i * 5) % 8);\n const value = bitsData[byteIndex] + (bitsData[byteIndex + 1] << 8);\n result[i] = ((value >> bitShift) & 0x1F);\n }\n const lastByteIndex = Math.floor(((valuesCount - 1) * 5) / 8);\n const lastBitShift = Math.floor(((valuesCount - 1) * 5) % 8);\n const lastValue = bitsData[lastByteIndex] + (bitsData[lastByteIndex + 1] << 8);\n result[valuesCount - 1] = (lastValue >> lastBitShift) & 0x1F;\n\n return result;\n}\n\nexport function interpolateArray(data: number[], fitCount: number) {\n let peak = 0;\n const newData = new Array(fitCount);\n const springFactor = data.length / fitCount;\n const leftFiller = data[0];\n const rightFiller = data[data.length - 1];\n for (let i = 0; i < fitCount; i++) {\n const idx = Math.floor(i * springFactor);\n const val = ((data[idx - 1] ?? leftFiller) + (data[idx] ?? leftFiller) + (data[idx + 1] ?? rightFiller)) / 3;\n newData[i] = val;\n if (peak < val) {\n peak = val;\n }\n }\n return { data: newData, peak };\n}\n","export interface ApiDimensions {\n width: number;\n height: number;\n}\n\nexport interface ApiPhotoSize extends ApiDimensions {\n type: 's' | 'm' | 'x' | 'y' | 'z';\n}\n\nexport interface ApiThumbnail extends ApiDimensions {\n dataUri: string;\n}\n\nexport interface ApiPhoto {\n id: string;\n thumbnail?: ApiThumbnail;\n sizes: ApiPhotoSize[];\n blobUrl?: string;\n}\n\nexport interface ApiSticker {\n id: string;\n stickerSetId: string;\n stickerSetAccessHash?: string;\n emoji?: string;\n isAnimated: boolean;\n width?: number;\n height?: number;\n thumbnail?: ApiThumbnail;\n isPreloadedGlobally?: boolean;\n}\n\nexport interface ApiStickerSet {\n archived?: true;\n isAnimated?: true;\n installedDate?: number;\n id: string;\n accessHash: string;\n title: string;\n hasThumbnail?: boolean;\n count: number;\n hash: number;\n stickers?: ApiSticker[];\n packs?: Record<string, ApiSticker[]>;\n covers?: ApiSticker[];\n shortName: string;\n}\n\nexport interface ApiVideo {\n id: string;\n mimeType: string;\n duration: number;\n fileName: string;\n width?: number;\n height?: number;\n supportsStreaming?: boolean;\n isRound?: boolean;\n isGif?: boolean;\n thumbnail?: ApiThumbnail;\n blobUrl?: string;\n size: number;\n}\n\nexport interface ApiAudio {\n size: number;\n mimeType: string;\n fileName: string;\n duration: number;\n performer?: string;\n title?: string;\n}\n\nexport interface ApiVoice {\n duration: number;\n waveform?: number[];\n}\n\nexport interface ApiDocument {\n id?: string;\n fileName: string;\n size: number;\n timestamp?: number;\n mimeType: string;\n thumbnail?: ApiThumbnail;\n previewBlobUrl?: string;\n mediaType?: 'photo' | 'video';\n mediaSize?: ApiDimensions;\n}\n\nexport interface ApiContact {\n firstName: string;\n lastName: string;\n phoneNumber: string;\n userId: number;\n}\n\nexport interface ApiPollAnswer {\n text: string;\n option: string;\n}\n\nexport interface ApiPollResult {\n isChosen?: true;\n isCorrect?: true;\n option: string;\n votersCount: number;\n}\n\nexport interface ApiPoll {\n id: string;\n summary: {\n closed?: true;\n isPublic?: true;\n multipleChoice?: true;\n quiz?: true;\n question: string;\n answers: ApiPollAnswer[];\n closePeriod?: number;\n closeDate?: number;\n };\n results: {\n results?: ApiPollResult[];\n totalVoters?: number;\n recentVoterIds?: number[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n}\n\nexport interface ApiInvoice {\n text: string;\n title: string;\n photoUrl?: string;\n amount: number;\n currency: string;\n receiptMsgId?: number;\n isTest?: boolean;\n}\n\nexport type ApiNewPoll = {\n summary: ApiPoll['summary'];\n quiz?: {\n correctAnswers: string[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n};\n\nexport interface ApiAction {\n text: string;\n targetUserIds?: number[];\n targetChatId?: number;\n type: 'historyClear' | 'contactSignUp' | 'chatCreate' | 'other';\n photo?: ApiPhoto;\n amount?: number;\n currency?: string;\n translationValues: string[];\n}\n\nexport interface ApiWebPage {\n id: number;\n url: string;\n displayUrl: string;\n type?: string;\n siteName?: string;\n title?: string;\n description?: string;\n photo?: ApiPhoto;\n duration?: number;\n document?: ApiDocument;\n video?: ApiVideo;\n}\n\nexport interface ApiMessageForwardInfo {\n isChannelPost: boolean;\n channelPostId?: number;\n isLinkedChannelPost?: boolean;\n fromChatId?: number;\n senderUserId?: number;\n fromMessageId?: number;\n hiddenUserName?: string;\n adminTitle?: string;\n}\n\nexport interface ApiMessageEntity {\n type: string;\n offset: number;\n length: number;\n userId?: number;\n url?: string;\n}\n\nexport enum ApiMessageEntityTypes {\n Bold = 'MessageEntityBold',\n Blockquote = 'MessageEntityBlockquote',\n BotCommand = 'MessageEntityBotCommand',\n Cashtag = 'MessageEntityCashtag',\n Code = 'MessageEntityCode',\n Email = 'MessageEntityEmail',\n Hashtag = 'MessageEntityHashtag',\n Italic = 'MessageEntityItalic',\n MentionName = 'MessageEntityMentionName',\n Mention = 'MessageEntityMention',\n Phone = 'MessageEntityPhone',\n Pre = 'MessageEntityPre',\n Strike = 'MessageEntityStrike',\n TextUrl = 'MessageEntityTextUrl',\n Url = 'MessageEntityUrl',\n Underline = 'MessageEntityUnderline',\n Unknown = 'MessageEntityUnknown',\n}\n\nexport interface ApiFormattedText {\n text: string;\n entities?: ApiMessageEntity[];\n}\n\nexport interface ApiMessage {\n id: number;\n chatId: number;\n content: {\n text?: ApiFormattedText;\n photo?: ApiPhoto;\n video?: ApiVideo;\n document?: ApiDocument;\n sticker?: ApiSticker;\n contact?: ApiContact;\n poll?: ApiPoll;\n action?: ApiAction;\n webPage?: ApiWebPage;\n audio?: ApiAudio;\n voice?: ApiVoice;\n invoice?: ApiInvoice;\n };\n date: number;\n isOutgoing: boolean;\n senderId?: number;\n replyToMessageId?: number;\n replyToTopMessageId?: number;\n sendingState?: 'messageSendingStatePending' | 'messageSendingStateFailed';\n forwardInfo?: ApiMessageForwardInfo;\n isDeleting?: boolean;\n previousLocalId?: number;\n views?: number;\n isEdited?: boolean;\n isMediaUnread?: boolean;\n groupedId?: string;\n isInAlbum?: boolean;\n hasUnreadMention?: boolean;\n inlineButtons?: ApiKeyboardButtons;\n keyboardButtons?: ApiKeyboardButtons;\n keyboardPlaceholder?: string;\n isKeyboardSingleUse?: boolean;\n viaBotId?: number;\n threadInfo?: ApiThreadInfo;\n adminTitle?: string;\n isScheduled?: boolean;\n shouldHideKeyboardButtons?: boolean;\n isFromScheduled?: boolean;\n}\n\nexport interface ApiThreadInfo {\n threadId: number;\n chatId: number;\n topMessageId?: number;\n originChannelId?: number;\n messagesCount: number;\n lastMessageId?: number;\n lastReadInboxMessageId?: number;\n recentReplierIds?: number[];\n}\n\nexport type ApiMessageOutgoingStatus = 'read' | 'succeeded' | 'pending' | 'failed';\n\nexport interface ApiKeyboardButton {\n type: 'command' | 'url' | 'callback' | 'requestPoll' | 'buy' | 'NOT_SUPPORTED';\n text: string;\n messageId: number;\n value?: string;\n}\n\nexport type ApiKeyboardButtons = ApiKeyboardButton[][];\nexport type ApiReplyKeyboard = {\n keyboardPlaceholder?: string;\n isKeyboardSingleUse?: boolean;\n} & {\n [K in 'inlineButtons' | 'keyboardButtons']?: ApiKeyboardButtons;\n};\n\nexport type ApiMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'profilePhoto';\nexport type ApiGlobalMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'voice';\n\nexport type ApiReportReason = 'spam' | 'violence' | 'pornography' | 'childAbuse'\n| 'copyright' | 'geoIrrelevant' | 'fake' | 'other';\n\nexport const MAIN_THREAD_ID = -1;\n\n// `Symbol` can not be transferred from worker\nexport const MESSAGE_DELETED = 'MESSAGE_DELETED';\n","// We cache avatars as Data URI for faster initial load\n// and messages media as Blob for smaller size.\n\nexport enum ApiMediaFormat {\n DataUri,\n BlobUrl,\n Lottie,\n Progressive,\n Stream,\n}\n\nexport type ApiParsedMedia = string | Blob | AnyLiteral | ArrayBuffer;\nexport type ApiPreparedMedia = string | AnyLiteral;\nexport type ApiMediaFormatToPrepared<T> = T extends ApiMediaFormat.Lottie ? AnyLiteral : string;\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\n\nimport { ApiPrivacyKey } from '../../../types';\n\nimport { generateRandomBytes, readBigIntFromBuffer } from '../../../lib/gramjs/Helpers';\nimport {\n ApiSticker,\n ApiVideo,\n ApiNewPoll,\n ApiMessageEntity,\n ApiMessageEntityTypes,\n ApiChatFolder,\n ApiChatBannedRights,\n ApiChatAdminRights,\n ApiReportReason,\n} from '../../types';\nimport localDb from '../localDb';\nimport { pick } from '../../../util/iteratees';\n\nexport function getEntityTypeById(chatOrUserId: number) {\n if (chatOrUserId > 0) {\n return 'user';\n } else if (chatOrUserId <= -1000000000) {\n return 'channel';\n } else {\n return 'chat';\n }\n}\n\nexport function buildPeer(chatOrUserId: number): GramJs.TypePeer {\n if (chatOrUserId > 0) {\n return new GramJs.PeerUser({\n userId: chatOrUserId,\n });\n } else if (chatOrUserId <= -1000000000) {\n return new GramJs.PeerChannel({\n channelId: -chatOrUserId,\n });\n } else {\n return new GramJs.PeerChat({\n chatId: -chatOrUserId,\n });\n }\n}\n\nexport function buildInputPeer(chatOrUserId: number, accessHash?: string): GramJs.TypeInputPeer {\n if (chatOrUserId > 0 || chatOrUserId <= -1000000000) {\n return chatOrUserId > 0\n ? new GramJs.InputPeerUser({\n userId: chatOrUserId,\n accessHash: BigInt(accessHash!),\n })\n : new GramJs.InputPeerChannel({\n channelId: -chatOrUserId,\n accessHash: BigInt(accessHash!),\n });\n } else {\n return new GramJs.InputPeerChat({\n chatId: -chatOrUserId,\n });\n }\n}\n\nexport function buildInputPeerFromLocalDb(chatOrUserId: number): GramJs.TypeInputPeer | undefined {\n if (chatOrUserId > 0) {\n const { accessHash } = localDb.users[chatOrUserId] || {};\n\n return accessHash\n ? new GramJs.InputPeerUser({\n userId: chatOrUserId,\n accessHash,\n })\n : undefined;\n }\n\n if (chatOrUserId <= -1000000000) {\n const { accessHash } = (localDb.chats[-chatOrUserId] as GramJs.Channel) || {};\n\n return accessHash\n ? new GramJs.InputPeerChannel({\n channelId: -chatOrUserId,\n accessHash,\n })\n : undefined;\n }\n\n return new GramJs.InputPeerChat({\n chatId: -chatOrUserId,\n });\n}\n\nexport function buildInputEntity(chatOrUserId: number, accessHash?: string) {\n if (chatOrUserId > 0) {\n return new GramJs.InputUser({\n userId: chatOrUserId,\n accessHash: BigInt(accessHash!),\n });\n } else if (chatOrUserId <= -1000000000) {\n return new GramJs.InputChannel({\n channelId: -chatOrUserId,\n accessHash: BigInt(accessHash!),\n });\n } else {\n return -chatOrUserId;\n }\n}\n\nexport function buildInputStickerSet(id: string, accessHash: string) {\n return new GramJs.InputStickerSetID({\n id: BigInt(id),\n accessHash: BigInt(accessHash),\n });\n}\n\nexport function buildInputStickerSetShortName(shortName: string) {\n return new GramJs.InputStickerSetShortName({\n shortName,\n });\n}\n\nexport function buildInputDocument(media: ApiSticker | ApiVideo) {\n const document = localDb.documents[media.id];\n\n if (!document) {\n return undefined;\n }\n\n return new GramJs.InputDocument(pick(document, [\n 'id',\n 'accessHash',\n 'fileReference',\n ]));\n}\n\nexport function buildInputMediaDocument(media: ApiSticker | ApiVideo) {\n const inputDocument = buildInputDocument(media);\n\n if (!inputDocument) {\n return undefined;\n }\n\n return new GramJs.InputMediaDocument({ id: inputDocument });\n}\n\nexport function buildInputPoll(pollParams: ApiNewPoll, randomId: BigInt.BigInteger) {\n const { summary, quiz } = pollParams;\n\n const poll = new GramJs.Poll({\n id: randomId,\n publicVoters: summary.isPublic,\n question: summary.question,\n answers: summary.answers.map(({ text, option }) => new GramJs.PollAnswer({ text, option: Buffer.from(option) })),\n quiz: summary.quiz,\n multipleChoice: summary.multipleChoice,\n });\n\n if (!quiz) {\n return new GramJs.InputMediaPoll({ poll });\n }\n\n const correctAnswers = quiz.correctAnswers.map((key) => Buffer.from(key));\n const { solution } = quiz;\n const solutionEntities = quiz.solutionEntities ? quiz.solutionEntities.map(buildMtpMessageEntity) : [];\n\n return new GramJs.InputMediaPoll({\n poll,\n correctAnswers,\n ...(solution && {\n solution,\n solutionEntities,\n }),\n });\n}\n\nexport function buildFilterFromApiFolder(folder: ApiChatFolder): GramJs.DialogFilter {\n const {\n emoticon,\n contacts,\n nonContacts,\n groups,\n channels,\n bots,\n excludeArchived,\n excludeMuted,\n excludeRead,\n pinnedChatIds,\n includedChatIds,\n excludedChatIds,\n } = folder;\n\n const pinnedPeers = pinnedChatIds\n ? pinnedChatIds.map(buildInputPeerFromLocalDb).filter<GramJs.TypeInputPeer>(Boolean as any)\n : [];\n\n const includePeers = includedChatIds\n ? includedChatIds.map(buildInputPeerFromLocalDb).filter<GramJs.TypeInputPeer>(Boolean as any)\n : [];\n\n const excludePeers = excludedChatIds\n ? excludedChatIds.map(buildInputPeerFromLocalDb).filter<GramJs.TypeInputPeer>(Boolean as any)\n : [];\n\n return new GramJs.DialogFilter({\n id: folder.id,\n title: folder.title,\n emoticon: emoticon || undefined,\n contacts: contacts || undefined,\n nonContacts: nonContacts || undefined,\n groups: groups || undefined,\n bots: bots || undefined,\n excludeArchived: excludeArchived || undefined,\n excludeMuted: excludeMuted || undefined,\n excludeRead: excludeRead || undefined,\n broadcasts: channels || undefined,\n pinnedPeers,\n includePeers,\n excludePeers,\n });\n}\n\nexport function generateRandomBigInt() {\n return readBigIntFromBuffer(generateRandomBytes(8), true, true);\n}\n\nexport function buildMessageFromUpdate(\n id: number,\n chatId: number,\n update: GramJs.UpdateShortSentMessage | GramJs.UpdateServiceNotification,\n) {\n // This is not a proper message, but we only need these fields for downloading media through `localDb`.\n return new GramJs.Message({\n id,\n peerId: buildPeer(chatId),\n fromId: buildPeer(chatId),\n media: update.media,\n } as GramJs.Message);\n}\n\nexport function buildMtpMessageEntity(entity: ApiMessageEntity): GramJs.TypeMessageEntity {\n const {\n type, offset, length, url, userId,\n } = entity;\n\n const user = userId ? localDb.users[userId] : undefined;\n\n switch (type) {\n case ApiMessageEntityTypes.Bold:\n return new GramJs.MessageEntityBold({ offset, length });\n case ApiMessageEntityTypes.Italic:\n return new GramJs.MessageEntityItalic({ offset, length });\n case ApiMessageEntityTypes.Underline:\n return new GramJs.MessageEntityUnderline({ offset, length });\n case ApiMessageEntityTypes.Strike:\n return new GramJs.MessageEntityStrike({ offset, length });\n case ApiMessageEntityTypes.Code:\n return new GramJs.MessageEntityCode({ offset, length });\n case ApiMessageEntityTypes.Pre:\n return new GramJs.MessageEntityPre({ offset, length, language: '' });\n case ApiMessageEntityTypes.Blockquote:\n return new GramJs.MessageEntityBlockquote({ offset, length });\n case ApiMessageEntityTypes.TextUrl:\n return new GramJs.MessageEntityTextUrl({ offset, length, url: url! });\n case ApiMessageEntityTypes.Url:\n return new GramJs.MessageEntityUrl({ offset, length });\n case ApiMessageEntityTypes.Hashtag:\n return new GramJs.MessageEntityHashtag({ offset, length });\n case ApiMessageEntityTypes.MentionName:\n return new GramJs.InputMessageEntityMentionName({\n offset,\n length,\n userId: new GramJs.InputUser({ userId: userId!, accessHash: user!.accessHash! }),\n });\n default:\n return new GramJs.MessageEntityUnknown({ offset, length });\n }\n}\n\n// TODO: This formula is taken from API docs, but doesn't seem to calculate hash correctly\nexport function calculateResultHash(ids: number[]) {\n let hash = 0;\n ids.forEach((id) => {\n // eslint-disable-next-line no-bitwise\n hash = (((hash * 0x4F25) & 0x7FFFFFFF) + id) & 0x7FFFFFFF;\n });\n\n return hash;\n}\n\nexport function isMessageWithMedia(message: GramJs.Message | GramJs.UpdateServiceNotification) {\n const { media } = message;\n if (!media) {\n return false;\n }\n\n return (\n media instanceof GramJs.MessageMediaPhoto\n || media instanceof GramJs.MessageMediaDocument\n || (\n media instanceof GramJs.MessageMediaWebPage\n && media.webpage instanceof GramJs.WebPage\n && (\n media.webpage.photo instanceof GramJs.Photo || (\n media.webpage.document instanceof GramJs.Document\n && media.webpage.document.mimeType.startsWith('video')\n )\n )\n )\n );\n}\n\nexport function isServiceMessageWithMedia(message: GramJs.MessageService) {\n return 'photo' in message.action && message.action.photo instanceof GramJs.Photo;\n}\n\nexport function buildChatPhotoForLocalDb(photo: GramJs.TypePhoto) {\n if (photo instanceof GramJs.PhotoEmpty) {\n return new GramJs.ChatPhotoEmpty();\n }\n\n const { dcId, id: photoId } = photo;\n\n return new GramJs.ChatPhoto({\n dcId,\n photoId,\n });\n}\n\nexport function buildInputContact({\n phone,\n firstName,\n lastName,\n}: {\n phone: string;\n firstName: string;\n lastName: string;\n}) {\n return new GramJs.InputPhoneContact({\n clientId: BigInt(1),\n phone,\n firstName,\n lastName,\n });\n}\n\nexport function buildChatBannedRights(\n bannedRights: ApiChatBannedRights,\n untilDate = 0,\n) {\n return new GramJs.ChatBannedRights({\n ...bannedRights,\n untilDate,\n });\n}\n\nexport function buildChatAdminRights(\n adminRights: ApiChatAdminRights,\n) {\n return new GramJs.ChatAdminRights(adminRights);\n}\n\nexport function buildShippingInfo(info: GramJs.PaymentRequestedInfo) {\n const { shippingAddress } = info;\n return new GramJs.PaymentRequestedInfo({\n ...info,\n shippingAddress: shippingAddress\n ? new GramJs.PostAddress(shippingAddress)\n : undefined,\n });\n}\n\nexport function buildInputPrivacyKey(privacyKey: ApiPrivacyKey) {\n switch (privacyKey) {\n case 'phoneNumber':\n return new GramJs.InputPrivacyKeyPhoneNumber();\n\n case 'lastSeen':\n return new GramJs.InputPrivacyKeyStatusTimestamp();\n\n case 'profilePhoto':\n return new GramJs.InputPrivacyKeyProfilePhoto();\n\n case 'forwards':\n return new GramJs.InputPrivacyKeyForwards();\n\n case 'chatInvite':\n return new GramJs.InputPrivacyKeyChatInvite();\n }\n\n return undefined;\n}\n\nexport function buildInputReportReason(reason: ApiReportReason) {\n switch (reason) {\n case 'spam':\n return new GramJs.InputReportReasonSpam();\n case 'violence':\n return new GramJs.InputReportReasonViolence();\n case 'childAbuse':\n return new GramJs.InputReportReasonChildAbuse();\n case 'pornography':\n return new GramJs.InputReportReasonPornography();\n case 'copyright':\n return new GramJs.InputReportReasonCopyright();\n case 'fake':\n return new GramJs.InputReportReasonFake();\n case 'geoIrrelevant':\n return new GramJs.InputReportReasonGeoIrrelevant();\n case 'other':\n return new GramJs.InputReportReasonOther();\n }\n\n return undefined;\n}\n","import { Api as GramJs } from '../../lib/gramjs';\nimport localDb from './localDb';\nimport { getApiChatIdFromMtpPeer } from './apiBuilders/chats';\n\nexport function resolveMessageApiChatId(mtpMessage: GramJs.TypeMessage) {\n if (!(mtpMessage instanceof GramJs.Message || mtpMessage instanceof GramJs.MessageService)) {\n return undefined;\n }\n\n return getApiChatIdFromMtpPeer(mtpMessage.peerId);\n}\n\nexport function addMessageToLocalDb(message: GramJs.Message | GramJs.MessageService) {\n const messageFullId = `${resolveMessageApiChatId(message)}-${message.id}`;\n localDb.messages[messageFullId] = message;\n\n if (\n message instanceof GramJs.Message\n && message.media instanceof GramJs.MessageMediaDocument\n && message.media.document instanceof GramJs.Document\n ) {\n localDb.documents[String(message.media.document.id)] = message.media.document;\n }\n\n if (\n message instanceof GramJs.Message\n && message.media instanceof GramJs.MessageMediaWebPage\n && message.media.webpage instanceof GramJs.WebPage\n && message.media.webpage.document instanceof GramJs.Document\n ) {\n localDb.documents[String(message.media.webpage.document.id)] = message.media.webpage.document;\n }\n\n if (message instanceof GramJs.MessageService && 'photo' in message.action) {\n addPhotoToLocalDb(message.action.photo);\n }\n}\n\nexport function addPhotoToLocalDb(photo: GramJs.TypePhoto) {\n if (photo instanceof GramJs.Photo) {\n localDb.photos[String(photo.id)] = photo;\n }\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n ApiMessage,\n ApiMessageForwardInfo,\n ApiPhoto,\n ApiSticker,\n ApiVideo,\n ApiVoice,\n ApiAudio,\n ApiDocument,\n ApiAction,\n ApiContact,\n ApiAttachment,\n ApiPoll,\n ApiNewPoll,\n ApiWebPage,\n ApiMessageEntity,\n ApiFormattedText,\n ApiReplyKeyboard,\n ApiKeyboardButton,\n ApiChat,\n ApiThreadInfo,\n ApiInvoice,\n} from '../../types';\n\nimport { DELETED_COMMENTS_CHANNEL_ID, LOCAL_MESSAGE_ID_BASE, SERVICE_NOTIFICATIONS_USER_ID } from '../../../config';\nimport { pick } from '../../../util/iteratees';\nimport { getApiChatIdFromMtpPeer } from './chats';\nimport { buildStickerFromDocument } from './symbols';\nimport { buildApiPhoto, buildApiThumbnailFromStripped } from './common';\nimport { interpolateArray } from '../../../util/waveform';\nimport { buildPeer } from '../gramjsBuilders';\nimport { addPhotoToLocalDb, resolveMessageApiChatId } from '../helpers';\n\nconst LOCAL_IMAGE_UPLOADING_TEMP_ID = 'temp';\nconst LOCAL_VIDEO_UPLOADING_TEMP_ID = 'temp';\nconst INPUT_WAVEFORM_LENGTH = 63;\n\nlet localMessageCounter = LOCAL_MESSAGE_ID_BASE;\nlet currentUserId!: number;\n\nexport function setMessageBuilderCurrentUserId(_currentUserId: number) {\n currentUserId = _currentUserId;\n}\n\nexport function buildApiMessage(mtpMessage: GramJs.TypeMessage): ApiMessage | undefined {\n const chatId = resolveMessageApiChatId(mtpMessage);\n if (\n !chatId\n || !(mtpMessage instanceof GramJs.Message || mtpMessage instanceof GramJs.MessageService)) {\n return undefined;\n }\n\n return buildApiMessageWithChatId(chatId, mtpMessage);\n}\n\nexport function buildApiMessageFromShort(mtpMessage: GramJs.UpdateShortMessage): ApiMessage {\n const chatId = getApiChatIdFromMtpPeer({ userId: mtpMessage.userId } as GramJs.TypePeer);\n\n return buildApiMessageWithChatId(chatId, {\n ...mtpMessage,\n fromId: buildPeer(mtpMessage.out ? currentUserId : mtpMessage.userId),\n });\n}\n\nexport function buildApiMessageFromShortChat(mtpMessage: GramJs.UpdateShortChatMessage): ApiMessage {\n const chatId = getApiChatIdFromMtpPeer({ chatId: mtpMessage.chatId } as GramJs.TypePeer);\n\n return buildApiMessageWithChatId(chatId, {\n ...mtpMessage,\n fromId: buildPeer(mtpMessage.fromId),\n });\n}\n\nexport function buildApiMessageFromNotification(\n notification: GramJs.UpdateServiceNotification,\n currentDate: number,\n): ApiMessage {\n const localId = localMessageCounter++;\n let content: ApiMessage['content'] = {};\n\n if (notification.media) {\n content = {\n ...buildMessageMediaContent(notification.media),\n };\n }\n\n if (notification.message && !content.sticker && !content.poll && !content.contact) {\n content = {\n ...content,\n text: buildMessageTextContent(notification.message, notification.entities),\n };\n }\n\n return {\n id: localId,\n chatId: SERVICE_NOTIFICATIONS_USER_ID,\n date: notification.inboxDate || currentDate,\n content,\n isOutgoing: false,\n };\n}\n\ntype UniversalMessage = (\n Pick<GramJs.Message & GramJs.MessageService, ('id' | 'date')>\n & Pick<Partial<GramJs.Message & GramJs.MessageService>, (\n 'out' | 'message' | 'entities' | 'fromId' | 'peerId' | 'fwdFrom' | 'replyTo' | 'replyMarkup' | 'post' |\n 'media' | 'action' | 'views' | 'editDate' | 'editHide' | 'mediaUnread' | 'groupedId' | 'mentioned' | 'viaBotId' |\n 'replies' | 'fromScheduled' | 'postAuthor'\n )>\n);\n\nexport function buildApiMessageWithChatId(chatId: number, mtpMessage: UniversalMessage): ApiMessage {\n const fromId = mtpMessage.fromId ? getApiChatIdFromMtpPeer(mtpMessage.fromId) : undefined;\n const peerId = mtpMessage.peerId ? getApiChatIdFromMtpPeer(mtpMessage.peerId) : undefined;\n const isChatWithSelf = !fromId && chatId === currentUserId;\n const isOutgoing = (mtpMessage.out && !mtpMessage.post) || (isChatWithSelf && !mtpMessage.fwdFrom);\n\n let content: ApiMessage['content'] = {};\n\n if (mtpMessage.media) {\n content = {\n ...buildMessageMediaContent(mtpMessage.media),\n };\n }\n\n if (mtpMessage.message && !content.sticker && !content.poll && !content.contact) {\n content = {\n ...content,\n text: buildMessageTextContent(mtpMessage.message, mtpMessage.entities),\n };\n }\n\n const action = mtpMessage.action\n && buildAction(mtpMessage.action, fromId, peerId, Boolean(mtpMessage.post), isOutgoing);\n if (action) {\n content.action = action;\n }\n\n const { replyToMsgId, replyToTopId } = mtpMessage.replyTo || {};\n const isEdited = mtpMessage.editDate && !mtpMessage.editHide;\n const {\n inlineButtons, keyboardButtons, keyboardPlaceholder, isKeyboardSingleUse,\n } = buildReplyButtons(mtpMessage) || {};\n const forwardInfo = mtpMessage.fwdFrom && buildApiMessageForwardInfo(mtpMessage.fwdFrom, isChatWithSelf);\n const { replies, mediaUnread: isMediaUnread, postAuthor } = mtpMessage;\n const groupedId = mtpMessage.groupedId && mtpMessage.groupedId.toString();\n const isInAlbum = Boolean(groupedId) && !(content.document || content.audio);\n const shouldHideKeyboardButtons = mtpMessage.replyMarkup instanceof GramJs.ReplyKeyboardHide;\n\n return {\n id: mtpMessage.id,\n chatId,\n isOutgoing,\n content,\n date: mtpMessage.date,\n senderId: fromId || (mtpMessage.out && mtpMessage.post && currentUserId) || chatId,\n views: mtpMessage.views,\n isFromScheduled: mtpMessage.fromScheduled,\n ...(replyToMsgId && { replyToMessageId: replyToMsgId }),\n ...(replyToTopId && { replyToTopMessageId: replyToTopId }),\n ...(forwardInfo && { forwardInfo }),\n ...(isEdited && { isEdited }),\n ...(isMediaUnread && { isMediaUnread }),\n ...(mtpMessage.mentioned && isMediaUnread && { hasUnreadMention: true }),\n ...(groupedId && {\n groupedId,\n isInAlbum,\n }),\n inlineButtons,\n ...(keyboardButtons && { keyboardButtons, keyboardPlaceholder, isKeyboardSingleUse }),\n ...(shouldHideKeyboardButtons && { shouldHideKeyboardButtons }),\n ...(mtpMessage.viaBotId && { viaBotId: mtpMessage.viaBotId }),\n ...(replies && replies.comments && { threadInfo: buildThreadInfo(replies, mtpMessage.id, chatId) }),\n ...(postAuthor && { adminTitle: postAuthor }),\n };\n}\n\nexport function buildMessageTextContent(\n message: string,\n entities?: GramJs.TypeMessageEntity[],\n): ApiFormattedText {\n return {\n text: message,\n ...(entities && { entities: entities.map(buildApiMessageEntity) }),\n };\n}\n\nexport function buildMessageDraft(draft: GramJs.TypeDraftMessage) {\n if (draft instanceof GramJs.DraftMessageEmpty) {\n return undefined;\n }\n\n const {\n message, entities, replyToMsgId, date,\n } = draft;\n\n return {\n formattedText: message ? buildMessageTextContent(message, entities) : undefined,\n replyingToId: replyToMsgId,\n date,\n };\n}\n\nexport function buildMessageMediaContent(media: GramJs.TypeMessageMedia): ApiMessage['content'] | undefined {\n const sticker = buildSticker(media);\n if (sticker) return { sticker };\n\n const photo = buildPhoto(media);\n if (photo) return { photo };\n\n const video = buildVideo(media);\n if (video) return { video };\n\n const audio = buildAudio(media);\n if (audio) return { audio };\n\n const voice = buildVoice(media);\n if (voice) return { voice };\n\n const document = buildDocumentFromMedia(media);\n if (document) return { document };\n\n const contact = buildContact(media);\n if (contact) return { contact };\n\n const poll = buildPollFromMedia(media);\n if (poll) return { poll };\n\n const webPage = buildWebPage(media);\n if (webPage) return { webPage };\n\n const invoice = buildInvoiceFromMedia(media);\n if (invoice) return { invoice };\n\n return undefined;\n}\n\nfunction buildApiMessageForwardInfo(fwdFrom: GramJs.MessageFwdHeader, isChatWithSelf = false): ApiMessageForwardInfo {\n const savedFromPeerId = fwdFrom.savedFromPeer && getApiChatIdFromMtpPeer(fwdFrom.savedFromPeer);\n const fromId = fwdFrom.fromId && getApiChatIdFromMtpPeer(fwdFrom.fromId);\n\n return {\n isChannelPost: Boolean(fwdFrom.channelPost),\n channelPostId: fwdFrom.channelPost,\n isLinkedChannelPost: Boolean(fwdFrom.channelPost && savedFromPeerId && !isChatWithSelf),\n fromChatId: savedFromPeerId || fromId,\n fromMessageId: fwdFrom.channelPost || fwdFrom.savedFromMsgId,\n senderUserId: fromId,\n hiddenUserName: fwdFrom.fromName,\n adminTitle: fwdFrom.postAuthor,\n };\n}\n\nfunction buildSticker(media: GramJs.TypeMessageMedia): ApiSticker | undefined {\n if (\n !(media instanceof GramJs.MessageMediaDocument)\n || !media.document\n || !(media.document instanceof GramJs.Document)\n ) {\n return undefined;\n }\n\n return buildStickerFromDocument(media.document);\n}\n\nfunction buildPhoto(media: GramJs.TypeMessageMedia): ApiPhoto | undefined {\n if (!(media instanceof GramJs.MessageMediaPhoto) || !media.photo || !(media.photo instanceof GramJs.Photo)) {\n return undefined;\n }\n\n if (media.ttlSeconds) {\n return undefined;\n }\n\n return buildApiPhoto(media.photo);\n}\n\nexport function buildVideoFromDocument(document: GramJs.Document): ApiVideo | undefined {\n if (document instanceof GramJs.DocumentEmpty) {\n return undefined;\n }\n\n const {\n id, mimeType, thumbs, size, attributes,\n } = document;\n\n const videoAttr = attributes\n .find((a: any): a is GramJs.DocumentAttributeVideo => a instanceof GramJs.DocumentAttributeVideo);\n\n if (!videoAttr) {\n return undefined;\n }\n\n const gifAttr = attributes\n .find((a: any): a is GramJs.DocumentAttributeAnimated => a instanceof GramJs.DocumentAttributeAnimated);\n\n const {\n duration,\n w: width,\n h: height,\n supportsStreaming = false,\n roundMessage: isRound = false,\n } = videoAttr;\n\n return {\n id: String(id),\n mimeType,\n duration,\n fileName: getFilenameFromDocument(document, 'video'),\n width,\n height,\n supportsStreaming,\n isRound,\n isGif: Boolean(gifAttr),\n thumbnail: buildApiThumbnailFromStripped(thumbs),\n size,\n };\n}\n\nfunction buildVideo(media: GramJs.TypeMessageMedia): ApiVideo | undefined {\n if (\n !(media instanceof GramJs.MessageMediaDocument)\n || !(media.document instanceof GramJs.Document)\n || !media.document.mimeType.startsWith('video')\n ) {\n return undefined;\n }\n\n return buildVideoFromDocument(media.document);\n}\n\nfunction buildAudio(media: GramJs.TypeMessageMedia): ApiAudio | undefined {\n if (\n !(media instanceof GramJs.MessageMediaDocument)\n || !media.document\n || !(media.document instanceof GramJs.Document)\n ) {\n return undefined;\n }\n\n const audioAttribute = media.document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeAudio => (\n attr instanceof GramJs.DocumentAttributeAudio\n ));\n\n if (!audioAttribute || audioAttribute.voice) {\n return undefined;\n }\n\n return {\n fileName: getFilenameFromDocument(media.document, 'audio'),\n ...pick(media.document, ['size', 'mimeType']),\n ...pick(audioAttribute, ['duration', 'performer', 'title']),\n };\n}\n\nfunction buildVoice(media: GramJs.TypeMessageMedia): ApiVoice | undefined {\n if (\n !(media instanceof GramJs.MessageMediaDocument)\n || !media.document\n || !(media.document instanceof GramJs.Document)\n ) {\n return undefined;\n }\n\n const audioAttribute = media.document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeAudio => (\n attr instanceof GramJs.DocumentAttributeAudio\n ));\n\n if (!audioAttribute || !audioAttribute.voice) {\n return undefined;\n }\n\n const { duration, waveform } = audioAttribute;\n\n return {\n duration,\n waveform: waveform ? Array.from(waveform) : undefined,\n };\n}\n\nfunction buildDocumentFromMedia(media: GramJs.TypeMessageMedia) {\n if (!(media instanceof GramJs.MessageMediaDocument) || !media.document) {\n return undefined;\n }\n\n if (media.ttlSeconds) {\n return undefined;\n }\n\n return buildApiDocument(media.document);\n}\n\nexport function buildApiDocument(document: GramJs.TypeDocument): ApiDocument | undefined {\n if (!(document instanceof GramJs.Document)) {\n return undefined;\n }\n\n const {\n id, size, mimeType, date, thumbs, attributes,\n } = document;\n\n const thumbnail = thumbs && buildApiThumbnailFromStripped(thumbs);\n\n let mediaType: ApiDocument['mediaType'] | undefined;\n let mediaSize: ApiDocument['mediaSize'] | undefined;\n const photoSize = thumbs && thumbs.find((s: any): s is GramJs.PhotoSize => s instanceof GramJs.PhotoSize);\n if (photoSize) {\n mediaSize = {\n width: photoSize.w,\n height: photoSize.h,\n };\n\n if (mimeType.startsWith('image/')) {\n mediaType = 'photo';\n\n const imageAttribute = attributes\n .find((a: any): a is GramJs.DocumentAttributeImageSize => a instanceof GramJs.DocumentAttributeImageSize);\n\n if (imageAttribute) {\n const { w: width, h: height } = imageAttribute;\n mediaSize = {\n width,\n height,\n };\n }\n } else if (mimeType.startsWith('video/')) {\n mediaType = 'video';\n }\n }\n\n return {\n id: String(id),\n size,\n mimeType,\n timestamp: date,\n fileName: getFilenameFromDocument(document),\n thumbnail,\n mediaType,\n mediaSize,\n };\n}\n\nfunction buildContact(media: GramJs.TypeMessageMedia): ApiContact | undefined {\n if (!(media instanceof GramJs.MessageMediaContact)) {\n return undefined;\n }\n\n return pick(media, [\n 'firstName',\n 'lastName',\n 'phoneNumber',\n 'userId',\n ]);\n}\n\nfunction buildPollFromMedia(media: GramJs.TypeMessageMedia): ApiPoll | undefined {\n if (!(media instanceof GramJs.MessageMediaPoll)) {\n return undefined;\n }\n\n return buildPoll(media.poll, media.results);\n}\n\nfunction buildInvoiceFromMedia(media: GramJs.TypeMessageMedia): ApiInvoice | undefined {\n if (!(media instanceof GramJs.MessageMediaInvoice)) {\n return undefined;\n }\n\n return buildInvoice(media);\n}\n\nexport function buildPoll(poll: GramJs.Poll, pollResults: GramJs.PollResults): ApiPoll {\n const { id, answers: rawAnswers } = poll;\n const answers = rawAnswers.map((answer) => ({\n text: answer.text,\n option: String.fromCharCode(...answer.option),\n }));\n\n return {\n id: id.toString(),\n summary: {\n isPublic: poll.publicVoters,\n ...pick(poll, [\n 'closed',\n 'multipleChoice',\n 'quiz',\n 'question',\n 'closePeriod',\n 'closeDate',\n ]),\n answers,\n },\n results: buildPollResults(pollResults),\n };\n}\n\nexport function buildInvoice(media: GramJs.MessageMediaInvoice): ApiInvoice {\n const {\n description: text, title, photo, test, totalAmount, currency, receiptMsgId,\n } = media;\n\n return {\n text,\n title,\n photoUrl: photo && photo.url,\n receiptMsgId,\n amount: Number(totalAmount),\n currency,\n isTest: test,\n };\n}\n\nexport function buildPollResults(pollResults: GramJs.PollResults): ApiPoll['results'] {\n const {\n results: rawResults, totalVoters, recentVoters, solution, solutionEntities: entities,\n } = pollResults;\n const results = rawResults && rawResults.map(({\n option, chosen, correct, voters,\n }) => ({\n isChosen: chosen,\n isCorrect: correct,\n option: String.fromCharCode(...option),\n votersCount: voters,\n }));\n\n return {\n totalVoters,\n recentVoterIds: recentVoters,\n results,\n solution,\n ...(entities && { solutionEntities: entities.map(buildApiMessageEntity) }),\n };\n}\n\nexport function buildWebPage(media: GramJs.TypeMessageMedia): ApiWebPage | undefined {\n if (\n !(media instanceof GramJs.MessageMediaWebPage)\n || !(media.webpage instanceof GramJs.WebPage)\n ) {\n return undefined;\n }\n\n const { id, photo, document } = media.webpage;\n\n let video;\n if (document instanceof GramJs.Document && document.mimeType.startsWith('video/')) {\n video = buildVideoFromDocument(document);\n }\n\n return {\n id: Number(id),\n ...pick(media.webpage, [\n 'url',\n 'displayUrl',\n 'type',\n 'siteName',\n 'title',\n 'description',\n 'duration',\n ]),\n photo: photo instanceof GramJs.Photo ? buildApiPhoto(photo) : undefined,\n document: !video && document ? buildApiDocument(document) : undefined,\n video,\n };\n}\n\nfunction buildAction(\n action: GramJs.TypeMessageAction,\n senderId: number | undefined,\n targetPeerId: number | undefined,\n isChannelPost: boolean,\n isOutgoing: boolean,\n): ApiAction | undefined {\n if (action instanceof GramJs.MessageActionEmpty) {\n return undefined;\n }\n\n let amount: number | undefined;\n let currency: string | undefined;\n let text: string;\n const translationValues = [];\n let type: ApiAction['type'] = 'other';\n let photo: ApiPhoto | undefined;\n\n const targetUserIds = 'users' in action\n ? action.users && action.users\n : ('userId' in action && [action.userId]) || [];\n let targetChatId: number | undefined;\n\n if (action instanceof GramJs.MessageActionChatCreate) {\n text = 'Notification.CreatedChatWithTitle';\n translationValues.push('%action_origin%', action.title);\n type = 'chatCreate';\n } else if (action instanceof GramJs.MessageActionChatEditTitle) {\n if (isChannelPost) {\n text = 'Channel.MessageTitleUpdated';\n translationValues.push(action.title);\n } else {\n text = 'Notification.ChangedGroupName';\n translationValues.push('%action_origin%', action.title);\n }\n } else if (action instanceof GramJs.MessageActionChatEditPhoto) {\n if (isChannelPost) {\n text = 'Channel.MessagePhotoUpdated';\n } else {\n text = 'Notification.ChangedGroupPhoto';\n translationValues.push('%action_origin%');\n }\n } else if (action instanceof GramJs.MessageActionChatDeletePhoto) {\n if (isChannelPost) {\n text = 'Channel.MessagePhotoRemoved';\n } else {\n text = 'Group.MessagePhotoRemoved';\n }\n } else if (action instanceof GramJs.MessageActionChatAddUser) {\n if (!senderId || targetUserIds.includes(senderId)) {\n text = 'Notification.JoinedChat';\n translationValues.push('%target_user%');\n } else {\n text = 'Notification.Invited';\n translationValues.push('%action_origin%', '%target_user%');\n }\n } else if (action instanceof GramJs.MessageActionChatDeleteUser) {\n if (!senderId || targetUserIds.includes(senderId)) {\n text = 'Notification.LeftChat';\n translationValues.push('%target_user%');\n } else {\n text = 'Notification.Kicked';\n translationValues.push('%action_origin%', '%target_user%');\n }\n } else if (action instanceof GramJs.MessageActionChatJoinedByLink) {\n text = 'Notification.JoinedGroupByLink';\n translationValues.push('%action_origin%');\n } else if (action instanceof GramJs.MessageActionChannelCreate) {\n text = 'Notification.CreatedChannel';\n } else if (action instanceof GramJs.MessageActionChatMigrateTo) {\n targetChatId = getApiChatIdFromMtpPeer(action);\n text = 'Migrated to %target_chat%';\n translationValues.push('%target_chat%');\n } else if (action instanceof GramJs.MessageActionChannelMigrateFrom) {\n targetChatId = getApiChatIdFromMtpPeer(action);\n text = 'Migrated from %target_chat%';\n translationValues.push('%target_chat%');\n } else if (action instanceof GramJs.MessageActionPinMessage) {\n text = 'Chat.Service.Group.UpdatedPinnedMessage1';\n translationValues.push('%action_origin%', '%message%');\n } else if (action instanceof GramJs.MessageActionHistoryClear) {\n text = 'HistoryCleared';\n type = 'historyClear';\n } else if (action instanceof GramJs.MessageActionPhoneCall) {\n const withDuration = Boolean(action.duration);\n text = [\n withDuration ? 'ChatList.Service' : 'Chat',\n action.video ? 'VideoCall' : 'Call',\n isOutgoing ? (withDuration ? 'outgoing' : 'Outgoing') : (withDuration ? 'incoming' : 'Incoming'),\n ].join('.');\n\n if (withDuration) {\n const mins = Math.max(Math.round(action.duration! / 60), 1);\n translationValues.push(`${mins} min${mins > 1 ? 's' : ''}`);\n }\n } else if (action instanceof GramJs.MessageActionContactSignUp) {\n text = 'Notification.Joined';\n translationValues.push('%action_origin%');\n type = 'contactSignUp';\n } else if (action instanceof GramJs.MessageActionPaymentSent) {\n amount = Number(action.totalAmount);\n currency = action.currency;\n text = 'PaymentSuccessfullyPaid';\n if (targetPeerId) {\n targetUserIds.push(targetPeerId);\n }\n translationValues.push('%payment_amount%', '%target_user%', '%product%');\n } else if (action instanceof GramJs.MessageActionGroupCall) {\n if (action.duration) {\n const mins = Math.max(Math.round(action.duration / 60), 1);\n text = 'Notification.VoiceChatEnded';\n translationValues.push(`${mins} min${mins > 1 ? 's' : ''}`);\n } else {\n text = 'Notification.VoiceChatStartedChannel';\n }\n } else if (action instanceof GramJs.MessageActionBotAllowed) {\n text = 'Chat.Service.BotPermissionAllowed';\n translationValues.push(action.domain);\n } else {\n text = 'ChatList.UnsupportedMessage';\n }\n\n if ('photo' in action && action.photo instanceof GramJs.Photo) {\n addPhotoToLocalDb(action.photo);\n photo = buildApiPhoto(action.photo);\n }\n\n return {\n text,\n type,\n targetUserIds,\n targetChatId,\n photo, // TODO Only used internally now, will be used for the UI in future\n amount,\n currency,\n translationValues,\n };\n}\n\nfunction buildReplyButtons(message: UniversalMessage): ApiReplyKeyboard | undefined {\n const { id: messageId, replyMarkup, media } = message;\n\n if (!replyMarkup) {\n if (media instanceof GramJs.MessageMediaWebPage && media.webpage instanceof GramJs.WebPage) {\n if (media.webpage.type === 'telegram_message') {\n return {\n inlineButtons: [[{\n type: 'url' as const,\n text: 'Show Message',\n messageId,\n value: media.webpage.url,\n }]],\n };\n }\n }\n\n return undefined;\n }\n\n // TODO\n if (!(replyMarkup instanceof GramJs.ReplyKeyboardMarkup || replyMarkup instanceof GramJs.ReplyInlineMarkup)) {\n return undefined;\n }\n\n const markup = replyMarkup.rows.map(({ buttons }) => {\n return buttons.map((button) => {\n let { text } = button;\n\n let type;\n let value;\n if (button instanceof GramJs.KeyboardButton) {\n type = 'command';\n value = text;\n } else if (button instanceof GramJs.KeyboardButtonUrl) {\n type = 'url';\n value = button.url;\n } else if (button instanceof GramJs.KeyboardButtonCallback) {\n type = 'callback';\n value = String(button.data);\n } else if (button instanceof GramJs.KeyboardButtonRequestPoll) {\n type = 'requestPoll';\n } else if (button instanceof GramJs.KeyboardButtonBuy) {\n if (media instanceof GramJs.MessageMediaInvoice && media.receiptMsgId) {\n text = 'PaymentReceipt';\n value = media.receiptMsgId;\n }\n type = 'buy';\n } else {\n type = 'NOT_SUPPORTED';\n }\n\n return {\n type,\n text,\n messageId,\n value,\n } as ApiKeyboardButton;\n });\n });\n\n return {\n [replyMarkup instanceof GramJs.ReplyKeyboardMarkup ? 'keyboardButtons' : 'inlineButtons']: markup,\n ...(replyMarkup instanceof GramJs.ReplyKeyboardMarkup && {\n keyboardPlaceholder: replyMarkup.placeholder,\n isKeyboardSingleUse: replyMarkup.singleUse,\n }),\n };\n}\n\nfunction getFilenameFromDocument(document: GramJs.Document, defaultBase = 'file') {\n const { mimeType, attributes } = document;\n const filenameAttribute = attributes\n .find((a: any): a is GramJs.DocumentAttributeFilename => a instanceof GramJs.DocumentAttributeFilename);\n\n if (filenameAttribute) {\n return filenameAttribute.fileName;\n }\n\n const extension = mimeType.split('/')[1];\n\n return `${defaultBase}${String(document.id)}.${extension}`;\n}\n\nexport function buildLocalMessage(\n chat: ApiChat,\n text?: string,\n entities?: ApiMessageEntity[],\n replyingTo?: number,\n attachment?: ApiAttachment,\n sticker?: ApiSticker,\n gif?: ApiVideo,\n poll?: ApiNewPoll,\n groupedId?: string,\n scheduledAt?: number,\n serverTimeOffset = 0,\n): ApiMessage {\n const localId = localMessageCounter++;\n const media = attachment && buildUploadingMedia(attachment);\n const isChannel = chat.type === 'chatTypeChannel';\n\n return {\n id: localId,\n chatId: chat.id,\n content: {\n ...(text && {\n text: {\n text,\n entities,\n },\n }),\n ...media,\n ...(sticker && { sticker }),\n ...(gif && { video: gif }),\n ...(poll && buildNewPoll(poll, localId)),\n },\n date: scheduledAt || Math.round(Date.now() / 1000) + serverTimeOffset,\n isOutgoing: !isChannel,\n senderId: currentUserId,\n ...(replyingTo && { replyToMessageId: replyingTo }),\n ...(groupedId && {\n groupedId,\n ...(media && (media.photo || media.video) && { isInAlbum: true }),\n }),\n ...(scheduledAt && { isScheduled: true }),\n };\n}\n\nexport function buildForwardedMessage(\n toChat: ApiChat,\n message: ApiMessage,\n serverTimeOffset: number,\n): ApiMessage {\n const localId = localMessageCounter++;\n const {\n content,\n chatId: fromChatId,\n id: fromMessageId,\n senderId,\n groupedId,\n isInAlbum,\n } = message;\n\n const isAudio = content.audio;\n const asIncomingInChatWithSelf = (\n toChat.id === currentUserId && (fromChatId !== toChat.id || message.forwardInfo) && !isAudio\n );\n\n return {\n id: localId,\n chatId: toChat.id,\n content,\n date: Math.round(Date.now() / 1000) + serverTimeOffset,\n isOutgoing: !asIncomingInChatWithSelf && toChat.type !== 'chatTypeChannel',\n senderId: currentUserId,\n sendingState: 'messageSendingStatePending',\n // Forward info doesn't get added when users forwards his own messages, also when forwarding audio\n ...(senderId !== currentUserId && !isAudio && {\n forwardInfo: {\n isChannelPost: false,\n fromChatId,\n fromMessageId,\n senderUserId: senderId,\n },\n }),\n groupedId,\n isInAlbum,\n };\n}\n\nfunction buildUploadingMedia(\n attachment: ApiAttachment,\n): ApiMessage['content'] {\n const {\n filename: fileName,\n blobUrl,\n previewBlobUrl,\n mimeType,\n size,\n } = attachment;\n\n if (attachment.quick) {\n const { width, height, duration } = attachment.quick;\n\n if (mimeType.startsWith('image/')) {\n return {\n photo: {\n id: LOCAL_IMAGE_UPLOADING_TEMP_ID,\n sizes: [],\n thumbnail: { width, height, dataUri: '' }, // Used only for dimensions\n blobUrl,\n },\n };\n } else {\n return {\n video: {\n id: LOCAL_VIDEO_UPLOADING_TEMP_ID,\n mimeType,\n duration: duration || 0,\n fileName,\n width,\n height,\n blobUrl,\n ...(previewBlobUrl && { thumbnail: { width, height, dataUri: previewBlobUrl } }),\n size,\n },\n };\n }\n } else if (attachment.voice) {\n const { duration, waveform } = attachment.voice;\n const { data: inputWaveform } = interpolateArray(waveform, INPUT_WAVEFORM_LENGTH);\n return {\n voice: {\n duration,\n waveform: inputWaveform,\n },\n };\n } else if (mimeType.startsWith('audio/')) {\n return {\n audio: {\n mimeType,\n fileName,\n size,\n duration: 200, // Arbitrary\n },\n };\n } else {\n return {\n document: {\n mimeType,\n fileName,\n size,\n ...(previewBlobUrl && { previewBlobUrl }),\n },\n };\n }\n}\n\nfunction buildNewPoll(poll: ApiNewPoll, localId: number) {\n return {\n poll: {\n id: localId.toString(),\n summary: pick(poll.summary, ['question', 'answers']),\n results: {},\n },\n };\n}\n\nfunction buildApiMessageEntity(entity: GramJs.TypeMessageEntity): ApiMessageEntity {\n const { className: type, offset, length } = entity;\n return {\n type,\n offset,\n length,\n ...('userId' in entity && typeof entity.userId === 'number' && { userId: entity.userId }),\n ...('url' in entity && { url: entity.url }),\n };\n}\n\nfunction buildThreadInfo(\n messageReplies: GramJs.TypeMessageReplies, messageId: number, chatId: number,\n): ApiThreadInfo | undefined {\n const {\n channelId, replies, maxId, readMaxId, recentRepliers,\n } = messageReplies;\n\n if (channelId === DELETED_COMMENTS_CHANNEL_ID) {\n return undefined;\n }\n\n const isPostThread = chatId !== channelId;\n\n return {\n threadId: messageId,\n ...(isPostThread ? {\n chatId: getApiChatIdFromMtpPeer({ channelId } as GramJs.TypePeer),\n originChannelId: chatId,\n } : {\n chatId,\n }),\n messagesCount: replies,\n lastMessageId: maxId,\n lastReadInboxMessageId: readMaxId,\n ...(recentRepliers && { recentReplierIds: recentRepliers.map(getApiChatIdFromMtpPeer) }),\n };\n}\n","import { Api as GramJs, connection } from '../../lib/gramjs';\nimport { ApiMessage, ApiUpdateConnectionStateType, OnApiUpdate } from '../types';\n\nimport { pick } from '../../util/iteratees';\nimport {\n buildApiMessage,\n buildApiMessageFromShort,\n buildApiMessageFromShortChat,\n buildMessageMediaContent,\n buildMessageTextContent,\n buildPoll,\n buildPollResults,\n buildApiMessageFromNotification,\n buildMessageDraft,\n} from './apiBuilders/messages';\nimport {\n getApiChatIdFromMtpPeer,\n buildChatMember,\n buildChatMembers,\n buildChatTypingStatus,\n buildAvatarHash,\n buildApiChatFromPreview,\n buildApiChatFolder,\n getApiChatIdFromInputMtpPeer,\n} from './apiBuilders/chats';\nimport { buildApiUser, buildApiUserStatus } from './apiBuilders/users';\nimport {\n buildMessageFromUpdate,\n isMessageWithMedia,\n buildChatPhotoForLocalDb,\n} from './gramjsBuilders';\nimport localDb from './localDb';\nimport { omitVirtualClassFields } from './apiBuilders/helpers';\nimport { DEBUG } from '../../config';\nimport { addMessageToLocalDb, addPhotoToLocalDb, resolveMessageApiChatId } from './helpers';\nimport { buildApiNotifyException, buildPrivacyKey, buildPrivacyRules } from './apiBuilders/misc';\nimport { buildApiPhoto } from './apiBuilders/common';\n\ntype Update = (\n (GramJs.TypeUpdate | GramJs.TypeUpdates) & { _entities?: (GramJs.TypeUser | GramJs.TypeChat)[] }\n) | typeof connection.UpdateConnectionState;\n\nconst DELETE_MISSING_CHANNEL_MESSAGE_DELAY = 1000;\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nconst sentMessageIds = new Set();\nlet serverTimeOffset = 0;\n\nexport function updater(update: Update, originRequest?: GramJs.AnyRequest) {\n if (update instanceof connection.UpdateServerTimeOffset) {\n serverTimeOffset = update.timeOffset;\n } else if (update instanceof connection.UpdateConnectionState) {\n let connectionState: ApiUpdateConnectionStateType;\n\n switch (update.state) {\n case connection.UpdateConnectionState.disconnected:\n connectionState = 'connectionStateConnecting';\n break;\n case connection.UpdateConnectionState.broken:\n connectionState = 'connectionStateBroken';\n break;\n case connection.UpdateConnectionState.connected:\n default:\n connectionState = 'connectionStateReady';\n break;\n }\n\n onUpdate({\n '@type': 'updateConnectionState',\n connectionState,\n });\n\n // Messages\n } else if (\n update instanceof GramJs.UpdateNewMessage\n || update instanceof GramJs.UpdateNewScheduledMessage\n || update instanceof GramJs.UpdateNewChannelMessage\n || update instanceof GramJs.UpdateShortChatMessage\n || update instanceof GramJs.UpdateShortMessage\n || update instanceof GramJs.UpdateServiceNotification\n ) {\n let message: ApiMessage | undefined;\n\n if (update instanceof GramJs.UpdateShortChatMessage) {\n message = buildApiMessageFromShortChat(update);\n } else if (update instanceof GramJs.UpdateShortMessage) {\n message = buildApiMessageFromShort(update);\n } else if (update instanceof GramJs.UpdateServiceNotification) {\n const currentDate = Date.now() / 1000 + serverTimeOffset;\n message = buildApiMessageFromNotification(update, currentDate);\n\n if (isMessageWithMedia(update)) {\n addMessageToLocalDb(buildMessageFromUpdate(message.id, message.chatId, update));\n }\n } else {\n // TODO Remove if proven not reproducing\n if (update.message instanceof GramJs.MessageEmpty) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected update:', update.className, update);\n }\n\n return;\n }\n\n if (update.message instanceof GramJs.Message && isMessageWithMedia(update.message)) {\n addMessageToLocalDb(update.message);\n }\n\n message = buildApiMessage(update.message)!;\n }\n\n // eslint-disable-next-line no-underscore-dangle\n const entities = update._entities;\n if (entities && entities.length) {\n entities\n .filter((e) => e instanceof GramJs.User)\n .map(buildApiUser)\n .forEach((user) => {\n if (!user) {\n return;\n }\n\n onUpdate({\n '@type': 'updateUser',\n id: user.id,\n user,\n });\n });\n entities\n .filter((e) => e instanceof GramJs.Chat || e instanceof GramJs.Channel)\n .map((e) => buildApiChatFromPreview(e))\n .forEach((chat) => {\n if (!chat) {\n return;\n }\n\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n });\n }\n\n if (update instanceof GramJs.UpdateNewScheduledMessage) {\n onUpdate({\n '@type': sentMessageIds.has(message.id) ? 'updateScheduledMessage' : 'newScheduledMessage',\n id: message.id,\n chatId: message.chatId,\n message,\n });\n } else {\n onUpdate({\n '@type': sentMessageIds.has(message.id) ? 'updateMessage' : 'newMessage',\n id: message.id,\n chatId: message.chatId,\n message,\n });\n }\n\n // Some updates to a Chat/Channel don't have a dedicated update class.\n // We can get info on some updates from Service Messages.\n if (update.message instanceof GramJs.MessageService) {\n const { action } = update.message;\n\n if (action instanceof GramJs.MessageActionChatEditTitle) {\n onUpdate({\n '@type': 'updateChat',\n id: message.chatId,\n chat: {\n title: action.title,\n },\n });\n } else if (action instanceof GramJs.MessageActionChatEditPhoto) {\n const photo = buildChatPhotoForLocalDb(action.photo);\n const avatarHash = buildAvatarHash(photo);\n\n const localDbChatId = Math.abs(resolveMessageApiChatId(update.message)!);\n if (localDb.chats[localDbChatId]) {\n localDb.chats[localDbChatId].photo = photo;\n }\n addPhotoToLocalDb(action.photo);\n\n if (avatarHash) {\n onUpdate({\n '@type': 'updateChat',\n id: message.chatId,\n chat: {\n avatarHash,\n },\n ...(action.photo instanceof GramJs.Photo && { newProfilePhoto: buildApiPhoto(action.photo) }),\n });\n }\n } else if (action instanceof GramJs.MessageActionChatDeletePhoto) {\n const localDbChatId = Math.abs(resolveMessageApiChatId(update.message)!);\n if (localDb.chats[localDbChatId]) {\n localDb.chats[localDbChatId].photo = new GramJs.ChatPhotoEmpty();\n }\n\n onUpdate({\n '@type': 'updateChat',\n id: message.chatId,\n chat: { avatarHash: undefined },\n });\n } else if (action instanceof GramJs.MessageActionChatDeleteUser) {\n // eslint-disable-next-line no-underscore-dangle\n if (update._entities && update._entities.some((e): e is GramJs.User => (\n e instanceof GramJs.User && !!e.self && e.id === action.userId\n ))) {\n onUpdate({\n '@type': 'updateChat',\n id: message.chatId,\n chat: {\n isRestricted: true,\n },\n });\n\n onUpdate({\n '@type': 'updateChatLeave',\n id: message.chatId,\n });\n }\n } else if (action instanceof GramJs.MessageActionChatAddUser) {\n // eslint-disable-next-line no-underscore-dangle\n if (update._entities && update._entities.some((e): e is GramJs.User => (\n e instanceof GramJs.User && !!e.self && action.users.includes(e.id)\n ))) {\n onUpdate({\n '@type': 'updateChatJoin',\n id: message.chatId,\n });\n }\n }\n }\n } else if (\n update instanceof GramJs.UpdateEditMessage\n || update instanceof GramJs.UpdateEditChannelMessage\n ) {\n // TODO Remove if proven not reproducing\n if (update.message instanceof GramJs.MessageEmpty) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected update:', update.className, update);\n }\n\n return;\n }\n\n if (update.message instanceof GramJs.Message && isMessageWithMedia(update.message)) {\n addMessageToLocalDb(update.message);\n }\n\n const message = buildApiMessage(update.message)!;\n\n onUpdate({\n '@type': 'updateMessage',\n id: message.id,\n chatId: message.chatId,\n message,\n });\n } else if (update instanceof GramJs.UpdateDeleteMessages) {\n onUpdate({\n '@type': 'deleteMessages',\n ids: update.messages,\n });\n } else if (update instanceof GramJs.UpdateDeleteScheduledMessages) {\n onUpdate({\n '@type': 'deleteScheduledMessages',\n ids: update.messages,\n chatId: getApiChatIdFromInputMtpPeer(update.peer),\n });\n } else if (update instanceof GramJs.UpdateDeleteChannelMessages) {\n const chatId = getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel);\n const ids = update.messages;\n const existingIds = ids.filter((id) => localDb.messages[`${chatId}-${id}`]);\n const missingIds = ids.filter((id) => !localDb.messages[`${chatId}-${id}`]);\n const profilePhotoIds = ids.map((id) => {\n const message = localDb.messages[`${chatId}-${id}`];\n\n return message && message instanceof GramJs.MessageService && 'photo' in message.action\n ? String(message.action.photo.id)\n : undefined;\n }).filter<string>(Boolean as any);\n\n if (existingIds.length) {\n onUpdate({\n '@type': 'deleteMessages',\n ids: existingIds,\n chatId,\n });\n }\n\n if (profilePhotoIds.length) {\n onUpdate({\n '@type': 'deleteProfilePhotos',\n ids: profilePhotoIds,\n chatId,\n });\n }\n\n // For some reason delete message update sometimes comes before new message update\n if (missingIds.length) {\n setTimeout(() => {\n onUpdate({\n '@type': 'deleteMessages',\n ids: missingIds,\n chatId,\n });\n }, DELETE_MISSING_CHANNEL_MESSAGE_DELAY);\n }\n } else if ((\n originRequest instanceof GramJs.messages.SendMessage\n || originRequest instanceof GramJs.messages.SendMedia\n || originRequest instanceof GramJs.messages.SendMultiMedia\n || originRequest instanceof GramJs.messages.ForwardMessages\n ) && (\n update instanceof GramJs.UpdateMessageID\n || update instanceof GramJs.UpdateShortSentMessage\n )) {\n let randomId;\n if ('randomId' in update) {\n randomId = update.randomId;\n } else if ('randomId' in originRequest) {\n randomId = originRequest.randomId;\n }\n\n const localMessage = randomId && localDb.localMessages[randomId.toString()];\n if (!localMessage) {\n throw new Error('Local message not found');\n }\n\n let newContent: ApiMessage['content'] | undefined;\n if (update instanceof GramJs.UpdateShortSentMessage) {\n if (localMessage.content.text && update.entities) {\n newContent = {\n text: buildMessageTextContent(localMessage.content.text.text, update.entities),\n };\n }\n if (update.media) {\n newContent = {\n ...newContent,\n ...buildMessageMediaContent(update.media),\n };\n }\n\n const mtpMessage = buildMessageFromUpdate(update.id, localMessage.chatId, update);\n if (isMessageWithMedia(mtpMessage)) {\n addMessageToLocalDb(mtpMessage);\n }\n }\n\n sentMessageIds.add(update.id);\n\n // Edge case for \"Send When Online\"\n const isAlreadySent = 'date' in update && update.date * 1000 < Date.now() + serverTimeOffset * 1000;\n\n onUpdate({\n '@type': localMessage.isScheduled && !isAlreadySent\n ? 'updateScheduledMessageSendSucceeded'\n : 'updateMessageSendSucceeded',\n chatId: localMessage.chatId,\n localId: localMessage.id,\n message: {\n ...localMessage,\n ...(newContent && {\n content: {\n ...localMessage.content,\n ...newContent,\n },\n }),\n id: update.id,\n sendingState: undefined,\n ...('date' in update && { date: update.date }),\n },\n });\n } else if (update instanceof GramJs.UpdateReadMessagesContents) {\n onUpdate({\n '@type': 'updateCommonBoxMessages',\n ids: update.messages,\n messageUpdate: {\n hasUnreadMention: false,\n isMediaUnread: false,\n },\n });\n } else if (update instanceof GramJs.UpdateChannelReadMessagesContents) {\n onUpdate({\n '@type': 'updateChannelMessages',\n channelId: update.channelId,\n ids: update.messages,\n messageUpdate: {\n hasUnreadMention: false,\n isMediaUnread: false,\n },\n });\n } else if (update instanceof GramJs.UpdateMessagePoll) {\n const { pollId, poll, results } = update;\n if (poll) {\n const apiPoll = buildPoll(poll, results);\n\n onUpdate({\n '@type': 'updateMessagePoll',\n pollId: pollId.toString(),\n pollUpdate: apiPoll,\n });\n } else {\n const pollResults = buildPollResults(results);\n onUpdate({\n '@type': 'updateMessagePoll',\n pollId: pollId.toString(),\n pollUpdate: { results: pollResults },\n });\n }\n } else if (update instanceof GramJs.UpdateMessagePollVote) {\n onUpdate({\n '@type': 'updateMessagePollVote',\n pollId: update.pollId.toString(),\n userId: update.userId,\n options: update.options.map((option) => String.fromCharCode(...option)),\n });\n } else if (update instanceof GramJs.UpdateChannelMessageViews) {\n onUpdate({\n '@type': 'updateMessage',\n chatId: getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel),\n id: update.id,\n message: { views: update.views },\n });\n\n // Chats\n } else if (update instanceof GramJs.UpdateReadHistoryInbox) {\n onUpdate({\n '@type': 'updateChatInbox',\n id: getApiChatIdFromMtpPeer(update.peer),\n chat: {\n lastReadInboxMessageId: update.maxId,\n unreadCount: update.stillUnreadCount,\n },\n });\n } else if (update instanceof GramJs.UpdateReadHistoryOutbox) {\n onUpdate({\n '@type': 'updateChat',\n id: getApiChatIdFromMtpPeer(update.peer),\n chat: {\n lastReadOutboxMessageId: update.maxId,\n },\n });\n } else if (update instanceof GramJs.UpdateReadChannelInbox) {\n onUpdate({\n '@type': 'updateChat',\n id: getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel),\n chat: {\n lastReadInboxMessageId: update.maxId,\n unreadCount: update.stillUnreadCount,\n },\n });\n } else if (update instanceof GramJs.UpdateReadChannelOutbox) {\n onUpdate({\n '@type': 'updateChat',\n id: getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel),\n chat: {\n lastReadOutboxMessageId: update.maxId,\n },\n });\n } else if (\n update instanceof GramJs.UpdateDialogPinned\n && update.peer instanceof GramJs.DialogPeer\n ) {\n onUpdate({\n '@type': 'updateChatPinned',\n id: getApiChatIdFromMtpPeer(update.peer.peer),\n isPinned: update.pinned || false,\n });\n } else if (update instanceof GramJs.UpdatePinnedDialogs) {\n const ids = update.order\n ? update.order\n .filter((dp): dp is GramJs.DialogPeer => dp instanceof GramJs.DialogPeer)\n .map((dp) => getApiChatIdFromMtpPeer(dp.peer))\n : [];\n\n onUpdate({\n '@type': 'updatePinnedChatIds',\n ids,\n folderId: update.folderId || undefined,\n });\n } else if (update instanceof GramJs.UpdateFolderPeers) {\n update.folderPeers.forEach((folderPeer) => {\n const { folderId, peer } = folderPeer;\n\n onUpdate({\n '@type': 'updateChatListType',\n id: getApiChatIdFromMtpPeer(peer),\n folderId,\n });\n });\n } else if (update instanceof GramJs.UpdateDialogFilter) {\n const { id, filter } = update;\n const folder = filter ? buildApiChatFolder(filter) : undefined;\n\n onUpdate({\n '@type': 'updateChatFolder',\n id,\n folder,\n });\n } else if (update instanceof GramJs.UpdateDialogFilterOrder) {\n onUpdate({\n '@type': 'updateChatFoldersOrder',\n orderedIds: update.order,\n });\n } else if (update instanceof GramJs.UpdateChatParticipants) {\n const replacedMembers = buildChatMembers(update.participants);\n\n onUpdate({\n '@type': 'updateChatMembers',\n id: getApiChatIdFromMtpPeer({ chatId: update.participants.chatId } as GramJs.TypePeer),\n replacedMembers,\n });\n } else if (update instanceof GramJs.UpdateChatParticipantAdd) {\n const addedMember = buildChatMember(\n pick(update, ['userId', 'inviterId', 'date']) as GramJs.ChatParticipant,\n );\n\n onUpdate({\n '@type': 'updateChatMembers',\n id: getApiChatIdFromMtpPeer({ chatId: update.chatId } as GramJs.PeerChat),\n addedMember,\n });\n } else if (update instanceof GramJs.UpdateChatParticipantDelete) {\n const { userId: deletedMemberId } = update;\n\n onUpdate({\n '@type': 'updateChatMembers',\n id: getApiChatIdFromMtpPeer({ chatId: update.chatId } as GramJs.PeerChat),\n deletedMemberId,\n });\n } else if (\n update instanceof GramJs.UpdatePinnedMessages\n || update instanceof GramJs.UpdatePinnedChannelMessages\n ) {\n const peer = update instanceof GramJs.UpdatePinnedMessages\n ? update.peer\n : { channelId: update.channelId } as GramJs.PeerChannel;\n const chatId = getApiChatIdFromMtpPeer(peer);\n\n onUpdate({\n '@type': 'updatePinnedIds',\n chatId,\n messageIds: update.messages,\n isPinned: update.pinned,\n });\n } else if (\n update instanceof GramJs.UpdateNotifySettings\n && update.peer instanceof GramJs.NotifyPeer\n ) {\n onUpdate({\n '@type': 'updateNotifyExceptions',\n ...buildApiNotifyException(update.notifySettings, update.peer.peer, serverTimeOffset),\n });\n } else if (\n update instanceof GramJs.UpdateUserTyping\n || update instanceof GramJs.UpdateChatUserTyping\n ) {\n const id = update instanceof GramJs.UpdateUserTyping\n ? update.userId\n : getApiChatIdFromMtpPeer({ chatId: update.chatId } as GramJs.PeerChat);\n\n onUpdate({\n '@type': 'updateChatTypingStatus',\n id,\n typingStatus: buildChatTypingStatus(update, serverTimeOffset),\n });\n } else if (update instanceof GramJs.UpdateChannelUserTyping) {\n const id = getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel);\n\n onUpdate({\n '@type': 'updateChatTypingStatus',\n id,\n typingStatus: buildChatTypingStatus(update, serverTimeOffset),\n });\n } else if (update instanceof GramJs.UpdateChannel) {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n const { _entities } = update;\n if (!_entities) {\n return;\n }\n\n const channel = _entities.find((e): e is GramJs.Channel | GramJs.ChannelForbidden => (\n e instanceof GramJs.Channel || e instanceof GramJs.ChannelForbidden\n ));\n\n if (channel instanceof GramJs.Channel) {\n const chat = buildApiChatFromPreview(channel);\n if (chat) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n\n onUpdate({\n '@type': chat.isNotJoined ? 'updateChatLeave' : 'updateChatJoin',\n id: getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel),\n });\n }\n } else if (channel instanceof GramJs.ChannelForbidden) {\n const chatId = getApiChatIdFromMtpPeer({ channelId: update.channelId } as GramJs.PeerChannel);\n\n onUpdate({\n '@type': 'updateChat',\n id: chatId,\n chat: {\n isRestricted: true,\n },\n });\n\n onUpdate({\n '@type': 'updateChatLeave',\n id: chatId,\n });\n } else if (_entities.length === 0) {\n // The link to the discussion group may have been changed.\n // No corresponding update available at this moment https://core.telegram.org/type/Updates\n onUpdate({\n '@type': 'resetMessages',\n id: getApiChatIdFromMtpPeer({ chatId: update.channelId } as GramJs.PeerChat),\n });\n }\n } else if (\n update instanceof GramJs.UpdateDialogUnreadMark\n && update.peer instanceof GramJs.DialogPeer\n ) {\n onUpdate({\n '@type': 'updateChat',\n id: getApiChatIdFromMtpPeer(update.peer.peer),\n chat: {\n hasUnreadMark: update.unread,\n },\n });\n } else if (update instanceof GramJs.UpdateChatDefaultBannedRights) {\n onUpdate({\n '@type': 'updateChat',\n id: getApiChatIdFromMtpPeer(update.peer),\n chat: {\n defaultBannedRights: omitVirtualClassFields(update.defaultBannedRights),\n },\n });\n\n // Users\n } else if (update instanceof GramJs.UpdateUserStatus) {\n const { userId, status } = update;\n\n onUpdate({\n '@type': 'updateUserStatus',\n userId,\n status: buildApiUserStatus(status),\n });\n } else if (update instanceof GramJs.UpdateUserName) {\n const updatedUser = localDb.users[update.userId];\n const user = updatedUser && updatedUser.mutualContact && !updatedUser.self\n ? pick(update, ['username'])\n : pick(update, ['firstName', 'lastName', 'username']);\n\n onUpdate({\n '@type': 'updateUser',\n id: update.userId,\n user,\n });\n } else if (update instanceof GramJs.UpdateUserPhoto) {\n const { userId, photo } = update;\n const avatarHash = buildAvatarHash(photo);\n\n if (localDb.users[userId]) {\n localDb.users[userId].photo = photo;\n }\n\n onUpdate({\n '@type': 'updateUser',\n id: userId,\n user: { avatarHash },\n });\n } else if (update instanceof GramJs.UpdateUserPhone) {\n const { userId, phone } = update;\n\n onUpdate({\n '@type': 'updateUser',\n id: userId,\n user: { phoneNumber: phone },\n });\n } else if (update instanceof GramJs.UpdatePeerSettings) {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n const { _entities } = update;\n if (!_entities) {\n return;\n }\n\n if (_entities && _entities.length) {\n _entities\n .filter((e) => e instanceof GramJs.User && !e.contact)\n .forEach((user) => {\n onUpdate({\n '@type': 'deleteUser',\n id: user.id,\n });\n });\n\n _entities\n .filter((e) => e instanceof GramJs.User && e.contact)\n .map(buildApiUser)\n .forEach((user) => {\n if (!user) {\n return;\n }\n\n onUpdate({\n '@type': 'updateUser',\n id: user.id,\n user,\n });\n });\n }\n\n // Settings\n } else if (update instanceof GramJs.UpdateNotifySettings) {\n const {\n notifySettings: {\n showPreviews, silent, muteUntil,\n },\n peer: { className },\n } = update;\n\n const peerType = className === 'NotifyUsers'\n ? 'contact'\n : (className === 'NotifyChats'\n ? 'group'\n : (className === 'NotifyBroadcasts'\n ? 'broadcast'\n : undefined\n )\n );\n\n if (!peerType) {\n return;\n }\n\n onUpdate({\n '@type': 'updateNotifySettings',\n peerType,\n isSilent: Boolean(silent\n || (typeof muteUntil === 'number' && Date.now() + serverTimeOffset * 1000 < muteUntil * 1000)),\n shouldShowPreviews: Boolean(showPreviews),\n });\n } else if (update instanceof GramJs.UpdatePeerBlocked) {\n onUpdate({\n '@type': 'updatePeerBlocked',\n id: getApiChatIdFromMtpPeer(update.peerId),\n isBlocked: update.blocked,\n });\n } else if (update instanceof GramJs.UpdatePrivacy) {\n const key = buildPrivacyKey(update.key);\n if (key) {\n onUpdate({\n '@type': 'updatePrivacy',\n key,\n rules: buildPrivacyRules(update.rules),\n });\n }\n\n // Misc\n } else if (update instanceof GramJs.UpdateDraftMessage) {\n onUpdate({\n '@type': 'draftMessage',\n chatId: getApiChatIdFromMtpPeer(update.peer),\n ...buildMessageDraft(update.draft),\n });\n } else if (update instanceof GramJs.UpdateContactsReset) {\n onUpdate({ '@type': 'updateResetContactList' });\n } else if (update instanceof GramJs.UpdateFavedStickers) {\n onUpdate({ '@type': 'updateFavoriteStickers' });\n } else if (DEBUG) {\n const params = typeof update === 'object' && 'className' in update ? update.className : update;\n // eslint-disable-next-line no-console\n console.warn('[GramJs/updater] Unexpected update:', params);\n }\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n ApiBotCommand, ApiUser, ApiUserStatus, ApiUserType,\n} from '../../types';\n\nexport function buildApiUserFromFull(mtpUserFull: GramJs.UserFull): ApiUser {\n const {\n about, commonChatsCount, pinnedMsgId, botInfo, blocked,\n } = mtpUserFull;\n\n return {\n ...(buildApiUser(mtpUserFull.user) as ApiUser),\n fullInfo: {\n bio: about,\n commonChatsCount,\n pinnedMessageId: pinnedMsgId,\n isBlocked: Boolean(blocked),\n ...(botInfo && { botDescription: botInfo.description }),\n ...(botInfo && botInfo.commands.length && { botCommands: buildApiBotCommands(mtpUserFull.user.id, botInfo) }),\n },\n };\n}\n\nexport function buildApiUser(mtpUser: GramJs.TypeUser): ApiUser | undefined {\n if (!(mtpUser instanceof GramJs.User)) {\n return undefined;\n }\n\n const { id, firstName, lastName } = mtpUser;\n const avatarHash = mtpUser.photo instanceof GramJs.UserProfilePhoto\n ? String(mtpUser.photo.photoId)\n : undefined;\n const userType = buildApiUserType(mtpUser);\n\n return {\n id,\n isMin: Boolean(mtpUser.min),\n ...(mtpUser.self && { isSelf: true }),\n ...(mtpUser.verified && { isVerified: true }),\n ...((mtpUser.contact || mtpUser.mutualContact) && { isContact: true }),\n type: userType,\n ...(firstName && { firstName }),\n ...(userType === 'userTypeBot' && { canBeInvitedToGroup: !mtpUser.botNochats }),\n ...(lastName && { lastName }),\n username: mtpUser.username || '',\n phoneNumber: mtpUser.phone || '',\n status: buildApiUserStatus(mtpUser.status),\n ...(mtpUser.accessHash && { accessHash: String(mtpUser.accessHash) }),\n ...(avatarHash && { avatarHash }),\n ...(mtpUser.bot && mtpUser.botInlinePlaceholder && { botPlaceholder: mtpUser.botInlinePlaceholder }),\n };\n}\n\nfunction buildApiUserType(user: GramJs.User): ApiUserType {\n if (user.bot) {\n return 'userTypeBot';\n }\n if (user.deleted) {\n return 'userTypeDeleted';\n }\n\n return 'userTypeRegular';\n}\n\nexport function buildApiUserStatus(mtpStatus?: GramJs.TypeUserStatus): ApiUserStatus {\n if (!mtpStatus || mtpStatus instanceof GramJs.UserStatusEmpty) {\n return { type: 'userStatusEmpty' };\n } else if (mtpStatus instanceof GramJs.UserStatusOnline) {\n return { type: 'userStatusOnline', expires: mtpStatus.expires };\n } else if (mtpStatus instanceof GramJs.UserStatusOffline) {\n return { type: 'userStatusOffline', wasOnline: mtpStatus.wasOnline };\n } else if (mtpStatus instanceof GramJs.UserStatusRecently) {\n return { type: 'userStatusRecently' };\n } else if (mtpStatus instanceof GramJs.UserStatusLastWeek) {\n return { type: 'userStatusLastWeek' };\n } else {\n return { type: 'userStatusLastMonth' };\n }\n}\n\nfunction buildApiBotCommands(botId: number, botInfo: GramJs.BotInfo) {\n return botInfo.commands.map(({ command, description }) => ({\n botId,\n command,\n description,\n })) as ApiBotCommand[];\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\n\nimport { ApiSession, ApiWallpaper } from '../../types';\nimport { ApiPrivacySettings, ApiPrivacyKey, PrivacyVisibility } from '../../../types';\n\nimport { buildApiDocument } from './messages';\nimport { getApiChatIdFromMtpPeer } from './chats';\nimport { pick } from '../../../util/iteratees';\nimport { getServerTime } from '../../../util/serverTime';\n\nexport function buildApiWallpaper(wallpaper: GramJs.TypeWallPaper): ApiWallpaper | undefined {\n if (wallpaper instanceof GramJs.WallPaperNoFile) {\n // TODO: Plain color wallpapers\n return undefined;\n }\n\n const { slug } = wallpaper;\n\n const document = buildApiDocument(wallpaper.document);\n\n if (!document) {\n return undefined;\n }\n\n return {\n slug,\n document,\n };\n}\n\nexport function buildApiSession(session: GramJs.Authorization): ApiSession {\n return {\n isCurrent: Boolean(session.current),\n isOfficialApp: Boolean(session.officialApp),\n isPasswordPending: Boolean(session.passwordPending),\n hash: String(session.hash),\n ...pick(session, [\n 'deviceModel', 'platform', 'systemVersion', 'appName', 'appVersion', 'dateCreated', 'dateActive',\n 'ip', 'country', 'region',\n ]),\n };\n}\n\nexport function buildPrivacyKey(key: GramJs.TypePrivacyKey): ApiPrivacyKey | undefined {\n switch (key.className) {\n case 'PrivacyKeyPhoneNumber':\n return 'phoneNumber';\n case 'PrivacyKeyStatusTimestamp':\n return 'lastSeen';\n case 'PrivacyKeyProfilePhoto':\n return 'profilePhoto';\n case 'PrivacyKeyForwards':\n return 'forwards';\n case 'PrivacyKeyChatInvite':\n return 'chatInvite';\n }\n\n return undefined;\n}\n\nexport function buildPrivacyRules(rules: GramJs.TypePrivacyRule[]): ApiPrivacySettings {\n let visibility: PrivacyVisibility | undefined;\n let allowUserIds: number[] | undefined;\n let allowChatIds: number[] | undefined;\n let blockUserIds: number[] | undefined;\n let blockChatIds: number[] | undefined;\n\n rules.forEach((rule) => {\n if (rule instanceof GramJs.PrivacyValueAllowAll) {\n visibility = visibility || 'everybody';\n } else if (rule instanceof GramJs.PrivacyValueAllowContacts) {\n visibility = visibility || 'contacts';\n } else if (rule instanceof GramJs.PrivacyValueDisallowContacts) {\n visibility = visibility || 'nonContacts';\n } else if (rule instanceof GramJs.PrivacyValueDisallowAll) {\n visibility = visibility || 'nobody';\n } else if (rule instanceof GramJs.PrivacyValueAllowUsers) {\n allowUserIds = rule.users;\n } else if (rule instanceof GramJs.PrivacyValueDisallowUsers) {\n blockUserIds = rule.users;\n } else if (rule instanceof GramJs.PrivacyValueAllowChatParticipants) {\n allowChatIds = rule.chats.map((id) => -id);\n } else if (rule instanceof GramJs.PrivacyValueDisallowChatParticipants) {\n blockChatIds = rule.chats.map((id) => -id);\n }\n });\n\n if (!visibility) {\n // disallow by default.\n visibility = 'nobody';\n }\n\n return {\n visibility,\n allowUserIds: allowUserIds || [],\n allowChatIds: allowChatIds || [],\n blockUserIds: blockUserIds || [],\n blockChatIds: blockChatIds || [],\n };\n}\n\nexport function buildApiNotifyException(\n notifySettings: GramJs.TypePeerNotifySettings, peer: GramJs.TypePeer, serverTimeOffset: number,\n) {\n const {\n silent, muteUntil, showPreviews, sound,\n } = notifySettings;\n\n return {\n chatId: getApiChatIdFromMtpPeer(peer),\n isMuted: silent || (typeof muteUntil === 'number' && getServerTime(serverTimeOffset) < muteUntil),\n ...(sound === '' && { isSilent: true }),\n ...(showPreviews !== undefined && { shouldShowPreviews: Boolean(showPreviews) }),\n };\n}\n","import { errors } from '../../../lib/gramjs';\nimport {\n ApiUpdateAuthorizationState,\n ApiUpdateAuthorizationStateType,\n OnApiUpdate,\n ApiUser,\n} from '../../types';\n\nimport { DEBUG } from '../../../config';\n\nconst ApiErrors: { [k: string]: string } = {\n PHONE_NUMBER_INVALID: 'PHONE_NUMBER_INVALID',\n PHONE_CODE_INVALID: 'PHONE_CODE_INVALID',\n PASSWORD_HASH_INVALID: 'PASSWORD_HASH_INVALID',\n PHONE_PASSWORD_FLOOD: 'You have tried logging in too many times',\n};\n\nconst authController: {\n resolve?: Function;\n reject?: Function;\n} = {};\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport function onRequestPhoneNumber() {\n onUpdate(buildAuthStateUpdate('authorizationStateWaitPhoneNumber'));\n\n return new Promise<string>((resolve, reject) => {\n authController.resolve = resolve;\n authController.reject = reject;\n });\n}\n\nexport function onRequestCode(isCodeViaApp = false) {\n onUpdate({\n ...buildAuthStateUpdate('authorizationStateWaitCode'),\n isCodeViaApp,\n });\n\n return new Promise<string>((resolve, reject) => {\n authController.resolve = resolve;\n authController.reject = reject;\n });\n}\n\nexport function onRequestPassword(hint?: string) {\n onUpdate({\n ...buildAuthStateUpdate('authorizationStateWaitPassword'),\n hint,\n });\n\n return new Promise<string>((resolve) => {\n authController.resolve = resolve;\n });\n}\n\nexport function onRequestRegistration() {\n onUpdate(buildAuthStateUpdate('authorizationStateWaitRegistration'));\n\n return new Promise<[string, string?]>((resolve) => {\n authController.resolve = resolve;\n });\n}\n\nexport function onRequestQrCode(qrCode: { token: Buffer; expires: number }) {\n onUpdate({\n ...buildAuthStateUpdate('authorizationStateWaitQrCode'),\n qrCode: {\n token: btoa(String.fromCharCode(...qrCode.token)).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, ''),\n expires: qrCode.expires,\n },\n });\n\n return new Promise<void>((resolve, reject) => {\n authController.reject = reject;\n });\n}\n\nexport function onAuthError(err: Error) {\n let message: string;\n\n if (err instanceof errors.FloodWaitError) {\n const hours = Math.ceil(Number(err.seconds) / 60 / 60);\n message = `Too many attempts. Try again in ${hours > 1 ? `${hours} hours` : 'an hour'}`;\n } else {\n message = ApiErrors[err.message];\n }\n\n if (!message) {\n message = 'Unexpected Error';\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n }\n\n onUpdate({\n '@type': 'updateAuthorizationError',\n message,\n });\n}\n\nexport function onAuthReady() {\n onUpdate(buildAuthStateUpdate('authorizationStateReady'));\n}\n\nexport function onCurrentUserUpdate(currentUser: ApiUser) {\n onUpdate({\n '@type': 'updateCurrentUser',\n currentUser,\n });\n}\n\nexport function buildAuthStateUpdate(authorizationState: ApiUpdateAuthorizationStateType): ApiUpdateAuthorizationState {\n return {\n '@type': 'updateAuthorizationState',\n authorizationState,\n };\n}\n\nexport function provideAuthPhoneNumber(phoneNumber: string) {\n if (!authController.resolve) {\n return;\n }\n\n authController.resolve(phoneNumber);\n}\n\nexport function provideAuthCode(code: string) {\n if (!authController.resolve) {\n return;\n }\n\n authController.resolve(code);\n}\n\nexport function provideAuthPassword(password: string) {\n if (!authController.resolve) {\n return;\n }\n\n authController.resolve(password);\n}\n\nexport function provideAuthRegistration(registration: { firstName: string; lastName: string }) {\n const { firstName, lastName } = registration;\n\n if (!authController.resolve) {\n return;\n }\n\n authController.resolve([firstName, lastName]);\n}\n\nexport function restartAuth() {\n if (!authController.reject) {\n return;\n }\n\n authController.reject(new Error('RESTART_AUTH'));\n}\n\nexport function restartAuthWithQr() {\n if (!authController.reject) {\n return;\n }\n\n authController.reject(new Error('RESTART_AUTH_WITH_QR'));\n}\n","import { pause } from './schedulers';\n\n// Polyfill for Safari: `File` is not available in web worker\nif (typeof File === 'undefined') {\n // eslint-disable-next-line no-global-assign, no-restricted-globals, func-names\n self.File = class extends Blob {\n name: string;\n\n constructor(fileBits: BlobPart[], fileName: string, options?: FilePropertyBag) {\n if (options) {\n const { type, ...rest } = options;\n super(fileBits, { type });\n Object.assign(this, rest);\n } else {\n super(fileBits);\n }\n\n this.name = fileName;\n }\n } as typeof File;\n}\n\nexport function dataUriToBlob(dataUri: string) {\n const arr = dataUri.split(',');\n const mime = arr[0].match(/:(.*?);/)![1];\n const bstr = atob(arr[1]);\n let n = bstr.length;\n const u8arr = new Uint8Array(n);\n\n while (n--) {\n u8arr[n] = bstr.charCodeAt(n);\n }\n\n return new Blob([u8arr], { type: mime });\n}\n\nexport function blobToDataUri(blob: Blob): Promise<string> {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n\n reader.onload = (e: ProgressEvent<FileReader>) => {\n const { result } = e.target || {};\n if (typeof result === 'string') {\n resolve(result);\n }\n\n reject(new Error('Failed to read blob'));\n };\n\n reader.onerror = reject;\n reader.readAsDataURL(blob);\n });\n}\n\nexport function blobToFile(blob: Blob, fileName: string) {\n return new File([blob], fileName, {\n lastModified: Date.now(),\n type: blob.type,\n });\n}\n\nexport function preloadImage(url: string): Promise<HTMLImageElement> {\n return new Promise((resolve, reject) => {\n const img = new Image();\n img.onload = () => resolve(img);\n img.onerror = reject;\n img.src = url;\n });\n}\n\nexport function preloadVideo(url: string): Promise<HTMLVideoElement> {\n return new Promise((resolve, reject) => {\n const video = document.createElement('video');\n video.volume = 0;\n video.onloadedmetadata = () => resolve(video);\n video.onerror = reject;\n video.src = url;\n });\n}\n\nexport async function createPosterForVideo(url: string): Promise<string | undefined> {\n const video = await preloadVideo(url);\n\n return Promise.race([\n pause(2000) as Promise<undefined>,\n new Promise<string | undefined>((resolve, reject) => {\n video.onseeked = () => {\n if (!video.videoWidth || !video.videoHeight) {\n resolve(undefined);\n }\n\n const canvas = document.createElement('canvas');\n canvas.width = video.videoWidth;\n canvas.height = video.videoHeight;\n const ctx = canvas.getContext('2d')!;\n ctx.drawImage(video, 0, 0);\n resolve(canvas.toDataURL('image/jpeg'));\n };\n video.onerror = reject;\n video.currentTime = Math.min(video.duration, 1);\n }),\n ]);\n}\n\nexport async function fetchBlob(blobUrl: string) {\n const response = await fetch(blobUrl);\n return response.blob();\n}\n\nexport async function fetchFile(blobUrl: string, fileName: string) {\n const blob = await fetchBlob(blobUrl);\n return blobToFile(blob, fileName);\n}\n\nexport function imgToCanvas(img: HTMLImageElement) {\n const canvas = document.createElement('canvas');\n canvas.width = img.width;\n canvas.height = img.height;\n\n const ctx = canvas.getContext('2d')!;\n ctx.drawImage(img, 0, 0);\n\n return canvas;\n}\n","// eslint-disable-next-line no-restricted-globals\nconst cacheApi = self.caches;\n\nexport enum Type {\n Text,\n Blob,\n Json,\n}\n\nexport async function fetch(\n cacheName: string, key: string, type: Type, isHtmlAllowed = false,\n) {\n if (!cacheApi) {\n return undefined;\n }\n\n try {\n // To avoid the error \"Request scheme 'webdocument' is unsupported\"\n const request = new Request(key.replace(/:/g, '_'));\n const cache = await cacheApi.open(cacheName);\n const response = await cache.match(request);\n if (!response) {\n return undefined;\n }\n\n switch (type) {\n case Type.Text:\n return await response.text();\n case Type.Blob: {\n const blob = await response.blob();\n\n // Safari does not return correct Content-Type header for webp images.\n if (key.substr(0, 7) === 'sticker') {\n return new Blob([blob], { type: 'image/webp' });\n }\n\n // iOS Safari fails to preserve `type` in cache\n if (!blob.type) {\n const contentType = response.headers.get('Content-Type');\n if (contentType) {\n return new Blob([blob], { type: isHtmlAllowed ? contentType : contentType.replace(/html/gi, '') });\n }\n }\n\n // Prevent HTML-in-video attacks (for files that were cached before fix)\n if (!isHtmlAllowed && blob.type.includes('html')) {\n return new Blob([blob], { type: blob.type.replace(/html/gi, '') });\n }\n\n return blob;\n }\n case Type.Json:\n return await response.json();\n default:\n return undefined;\n }\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n\nexport async function save(cacheName: string, key: string, data: AnyLiteral | Blob | string) {\n if (!cacheApi) {\n return undefined;\n }\n\n try {\n const cacheData = typeof data === 'string' || data instanceof Blob ? data : JSON.stringify(data);\n // To avoid the error \"Request scheme 'webdocument' is unsupported\"\n const request = new Request(key.replace(/:/g, '_'));\n const response = new Response(cacheData);\n const cache = await cacheApi.open(cacheName);\n return await cache.put(request, response);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n\nexport async function clear(cacheName: string) {\n try {\n if (!cacheApi) {\n return undefined;\n }\n\n return await cacheApi.delete(cacheName);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n","import { inflate } from 'pako/dist/pako_inflate';\n\nimport { Api as GramJs, TelegramClient } from '../../../lib/gramjs';\nimport {\n ApiMediaFormat, ApiOnProgress, ApiParsedMedia, ApiPreparedMedia,\n} from '../../types';\n\nimport {\n DOWNLOAD_WORKERS,\n MEDIA_CACHE_DISABLED,\n MEDIA_CACHE_MAX_BYTES,\n MEDIA_CACHE_NAME,\n MEDIA_CACHE_NAME_AVATARS,\n} from '../../../config';\nimport localDb from '../localDb';\nimport { getEntityTypeById } from '../gramjsBuilders';\nimport { blobToDataUri } from '../../../util/files';\nimport * as cacheApi from '../../../util/cacheApi';\n\ntype EntityType = (\n 'msg' | 'sticker' | 'wallpaper' | 'gif' | 'channel' | 'chat' | 'user' | 'photo' | 'stickerSet' | 'webDocument'\n);\nconst MEDIA_ENTITY_TYPES = new Set(['msg', 'sticker', 'gif', 'wallpaper', 'photo', 'webDocument']);\n\nexport default async function downloadMedia(\n {\n url, mediaFormat, start, end, isHtmlAllowed,\n }: {\n url: string; mediaFormat: ApiMediaFormat; start?: number; end?: number; isHtmlAllowed?: boolean;\n },\n client: TelegramClient,\n isConnected: boolean,\n onProgress?: ApiOnProgress,\n) {\n const {\n data, mimeType, fullSize,\n } = await download(url, client, isConnected, onProgress, start, end, mediaFormat, isHtmlAllowed) || {};\n if (!data) {\n return undefined;\n }\n\n const parsed = await parseMedia(data, mediaFormat, mimeType);\n if (!parsed) {\n return undefined;\n }\n\n const canCache = mediaFormat !== ApiMediaFormat.Progressive && (\n mediaFormat !== ApiMediaFormat.BlobUrl || (parsed as Blob).size <= MEDIA_CACHE_MAX_BYTES\n );\n\n if (!MEDIA_CACHE_DISABLED && cacheApi && canCache) {\n const cacheName = url.startsWith('avatar') ? MEDIA_CACHE_NAME_AVATARS : MEDIA_CACHE_NAME;\n void cacheApi.save(cacheName, url, parsed);\n }\n\n const prepared = mediaFormat === ApiMediaFormat.Progressive ? '' : prepareMedia(parsed);\n const arrayBuffer = mediaFormat === ApiMediaFormat.Progressive ? parsed as ArrayBuffer : undefined;\n\n return {\n prepared,\n arrayBuffer,\n mimeType,\n fullSize,\n };\n}\n\nasync function download(\n url: string,\n client: TelegramClient,\n isConnected: boolean,\n onProgress?: ApiOnProgress,\n start?: number,\n end?: number,\n mediaFormat?: ApiMediaFormat,\n isHtmlAllowed?: boolean,\n) {\n const mediaMatch = url.startsWith('webDocument')\n ? url.match(/(webDocument):(.+)/)\n : url.match(/(avatar|profile|photo|msg|stickerSet|sticker|wallpaper|gif|file)([-\\d\\w./]+)(\\?size=\\w+)?/);\n if (!mediaMatch) {\n return undefined;\n }\n\n if (mediaMatch[1] === 'file') {\n const response = await fetch(mediaMatch[2]);\n const data = await response.arrayBuffer();\n return { data };\n }\n\n if (!isConnected) {\n return Promise.reject(new Error('ERROR: Client is not connected'));\n }\n\n let entityType: EntityType;\n let entityId: string | number = mediaMatch[2];\n const sizeType = mediaMatch[3] ? mediaMatch[3].replace('?size=', '') : undefined;\n let entity: (\n GramJs.User | GramJs.Chat | GramJs.Channel | GramJs.Photo |\n GramJs.Message | GramJs.Document | GramJs.StickerSet | GramJs.TypeWebDocument | undefined\n );\n\n if (mediaMatch[1] === 'avatar' || mediaMatch[1] === 'profile') {\n entityType = getEntityTypeById(Number(entityId));\n entityId = Math.abs(Number(entityId));\n } else {\n entityType = mediaMatch[1] as 'msg' | 'sticker' | 'wallpaper' | 'gif' | 'stickerSet' | 'photo' | 'webDocument';\n }\n\n switch (entityType) {\n case 'channel':\n case 'chat':\n entity = localDb.chats[entityId as number];\n break;\n case 'user':\n entity = localDb.users[entityId as number];\n break;\n case 'msg':\n entity = localDb.messages[entityId as string];\n break;\n case 'sticker':\n case 'gif':\n case 'wallpaper':\n entity = localDb.documents[entityId as string];\n break;\n case 'photo':\n entity = localDb.photos[entityId as string];\n break;\n case 'stickerSet':\n entity = localDb.stickerSets[entityId as string];\n break;\n case 'webDocument':\n entity = localDb.webDocuments[entityId as string];\n break;\n }\n\n if (!entity) {\n return undefined;\n }\n\n if (MEDIA_ENTITY_TYPES.has(entityType)) {\n if (mediaFormat === ApiMediaFormat.Stream) {\n onProgress!.acceptsBuffer = true;\n }\n\n const data = await client.downloadMedia(entity, {\n sizeType, start, end, progressCallback: onProgress, workers: DOWNLOAD_WORKERS,\n });\n let mimeType;\n let fullSize;\n\n if (entity instanceof GramJs.Message) {\n mimeType = getMessageMediaMimeType(entity, sizeType);\n if (entity.media instanceof GramJs.MessageMediaDocument && entity.media.document instanceof GramJs.Document) {\n fullSize = entity.media.document.size;\n }\n if (entity.media instanceof GramJs.MessageMediaWebPage\n && entity.media.webpage instanceof GramJs.WebPage\n && entity.media.webpage.document instanceof GramJs.Document) {\n fullSize = entity.media.webpage.document.size;\n }\n } else if (entity instanceof GramJs.Photo) {\n mimeType = 'image/jpeg';\n } else if (entityType === 'sticker' && sizeType) {\n mimeType = 'image/webp';\n } else if (entityType === 'webDocument') {\n mimeType = (entity as GramJs.TypeWebDocument).mimeType;\n } else {\n mimeType = (entity as GramJs.Document).mimeType;\n fullSize = (entity as GramJs.Document).size;\n }\n\n // Prevent HTML-in-video attacks\n if (!isHtmlAllowed && mimeType) {\n mimeType = mimeType.replace(/html/gi, '');\n }\n\n return { mimeType, data, fullSize };\n } else if (entityType === 'stickerSet') {\n const data = await client.downloadStickerSetThumb(entity);\n const mimeType = mediaFormat === ApiMediaFormat.Lottie ? 'application/json' : getMimeType(data);\n\n return { mimeType, data };\n } else {\n const data = await client.downloadProfilePhoto(entity, mediaMatch[1] === 'profile');\n const mimeType = getMimeType(data);\n\n return { mimeType, data };\n }\n}\n\nfunction getMessageMediaMimeType(message: GramJs.Message, sizeType?: string) {\n if (!message || !message.media) {\n return undefined;\n }\n\n if (message.media instanceof GramJs.MessageMediaPhoto) {\n return 'image/jpeg';\n }\n\n if (message.media instanceof GramJs.MessageMediaDocument && message.media.document instanceof GramJs.Document) {\n if (sizeType) {\n return message.media.document!.attributes.some((a) => a instanceof GramJs.DocumentAttributeSticker)\n ? 'image/webp'\n : 'image/jpeg';\n }\n\n return message.media.document!.mimeType;\n }\n\n if (message.media instanceof GramJs.MessageMediaWebPage\n && message.media.webpage instanceof GramJs.WebPage\n && message.media.webpage.document instanceof GramJs.Document) {\n return message.media.webpage.document.mimeType;\n }\n\n return undefined;\n}\n\n// eslint-disable-next-line no-async-without-await/no-async-without-await\nasync function parseMedia(\n data: Buffer, mediaFormat: ApiMediaFormat, mimeType?: string,\n): Promise<ApiParsedMedia | undefined> {\n switch (mediaFormat) {\n case ApiMediaFormat.DataUri:\n return blobToDataUri(new Blob([data], { type: mimeType }));\n case ApiMediaFormat.BlobUrl:\n return new Blob([data], { type: mimeType });\n case ApiMediaFormat.Lottie: {\n const json = inflate(data, { to: 'string' });\n return JSON.parse(json);\n }\n case ApiMediaFormat.Progressive: {\n return data.buffer;\n }\n }\n\n return undefined;\n}\n\nfunction prepareMedia(mediaData: ApiParsedMedia): ApiPreparedMedia {\n if (mediaData instanceof Blob) {\n return URL.createObjectURL(mediaData);\n }\n\n return mediaData;\n}\n\nfunction getMimeType(data: Uint8Array, fallbackMimeType = 'image/jpeg') {\n if (data.length < 4) {\n return fallbackMimeType;\n }\n\n let type = fallbackMimeType;\n const signature = data.subarray(0, 4).reduce((result, byte) => result + byte.toString(16), '');\n\n // https://en.wikipedia.org/wiki/List_of_file_signatures\n switch (signature) {\n case '89504e47':\n type = 'image/png';\n break;\n case '47494638':\n type = 'image/gif';\n break;\n case 'ffd8ffe0':\n case 'ffd8ffe1':\n case 'ffd8ffe2':\n case 'ffd8ffe3':\n case 'ffd8ffe8':\n type = 'image/jpeg';\n break;\n case '52494646':\n // In our case only webp is expected\n type = 'image/webp';\n break;\n }\n\n return type;\n}\n","import {\n TelegramClient, sessions, Api as GramJs, connection,\n} from '../../../lib/gramjs';\nimport { Logger as GramJsLogger } from '../../../lib/gramjs/extensions/index';\nimport { TwoFaParams } from '../../../lib/gramjs/client/2fa';\n\nimport {\n ApiInitialArgs,\n ApiMediaFormat,\n ApiOnProgress,\n ApiSessionData,\n OnApiUpdate,\n} from '../../types';\n\nimport {\n DEBUG, DEBUG_GRAMJS, UPLOAD_WORKERS, IS_TEST, APP_VERSION,\n} from '../../../config';\nimport {\n onRequestPhoneNumber, onRequestCode, onRequestPassword, onRequestRegistration,\n onAuthError, onAuthReady, onCurrentUserUpdate, onRequestQrCode,\n} from './auth';\nimport { updater } from '../updater';\nimport { setMessageBuilderCurrentUserId } from '../apiBuilders/messages';\nimport downloadMediaWithClient from './media';\nimport { buildApiUserFromFull } from '../apiBuilders/users';\nimport localDb from '../localDb';\n\nconst DEFAULT_USER_AGENT = 'Unknown UserAgent';\nconst APP_CODE_NAME = 'Z';\n\nGramJsLogger.setLevel(DEBUG_GRAMJS ? 'debug' : 'warn');\n\nconst gramJsUpdateEventBuilder = { build: (update: object) => update };\n\nlet onUpdate: OnApiUpdate;\nlet client: TelegramClient;\nlet isConnected = false;\n\nexport async function init(_onUpdate: OnApiUpdate, initialArgs: ApiInitialArgs) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START INIT API');\n }\n\n onUpdate = _onUpdate;\n\n const { userAgent, platform, sessionData } = initialArgs;\n const session = new sessions.CallbackSession(sessionData, onSessionUpdate);\n\n client = new TelegramClient(\n session,\n process.env.TELEGRAM_T_API_ID,\n process.env.TELEGRAM_T_API_HASH,\n {\n deviceModel: navigator.userAgent || userAgent || DEFAULT_USER_AGENT,\n appVersion: `${APP_VERSION} ${APP_CODE_NAME}`,\n useWSS: true,\n additionalDcsDisabled: IS_TEST,\n } as any,\n );\n\n client.addEventHandler(handleGramJsUpdate, gramJsUpdateEventBuilder);\n client.addEventHandler(updater, gramJsUpdateEventBuilder);\n\n try {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[GramJs/client] CONNECTING');\n }\n\n try {\n await client.start({\n phoneNumber: onRequestPhoneNumber,\n phoneCode: onRequestCode,\n password: onRequestPassword,\n firstAndLastNames: onRequestRegistration,\n qrCode: onRequestQrCode,\n onError: onAuthError,\n initialMethod: platform === 'iOS' || platform === 'Android' ? 'phoneNumber' : 'qrCode',\n });\n } catch (err) {\n // TODO Investigate which request causes this exception\n if (err.message !== 'Disconnect') {\n onUpdate({\n '@type': 'updateConnectionState',\n connectionState: 'connectionStateBroken',\n });\n\n return;\n }\n }\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH INIT API');\n // eslint-disable-next-line no-console\n console.log('[GramJs/client] CONNECTED');\n\n // eslint-disable-next-line no-restricted-globals\n (self as any).invoke = invokeRequest;\n // eslint-disable-next-line no-restricted-globals\n (self as any).GramJs = GramJs;\n }\n\n onAuthReady();\n onSessionUpdate(session.getSessionData());\n onUpdate({ '@type': 'updateApiReady' });\n\n void fetchCurrentUser();\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[GramJs/client] CONNECTING ERROR', err);\n }\n\n throw err;\n }\n}\n\nexport async function destroy() {\n await invokeRequest(new GramJs.auth.LogOut());\n await client.destroy();\n}\n\nexport async function disconnect() {\n await client.disconnect();\n}\n\nexport function getClient() {\n return client;\n}\n\nfunction onSessionUpdate(sessionData: ApiSessionData) {\n onUpdate({\n '@type': 'updateSession',\n sessionData,\n });\n}\n\nfunction handleGramJsUpdate(update: any) {\n if (update instanceof connection.UpdateConnectionState) {\n isConnected = update.state === connection.UpdateConnectionState.connected;\n } else if (update instanceof GramJs.UpdatesTooLong) {\n void handleTerminatedSession();\n } else if (update instanceof connection.UpdateServerTimeOffset) {\n onUpdate({\n '@type': 'updateServerTimeOffset',\n serverTimeOffset: update.timeOffset,\n });\n }\n}\n\nexport async function invokeRequest<T extends GramJs.AnyRequest>(\n request: T,\n shouldHandleUpdates = false,\n shouldThrow = false,\n): Promise<T['__response'] | undefined> {\n if (!isConnected) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(`[GramJs/client] INVOKE ERROR ${request.className}: Client is not connected`);\n }\n\n return undefined;\n }\n\n try {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log(`[GramJs/client] INVOKE ${request.className}`);\n }\n\n const result = await client.invoke(request);\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log(`[GramJs/client] INVOKE RESPONSE ${request.className}`, result);\n }\n\n if (shouldHandleUpdates) {\n type ResultWithUpdates =\n typeof result\n & { updates?: GramJs.Updates | GramJs.UpdatesCombined };\n\n let updatesContainer;\n if (result instanceof GramJs.Updates || result instanceof GramJs.UpdatesCombined) {\n updatesContainer = result;\n } else if ('updates' in (result as ResultWithUpdates) && (\n (result as ResultWithUpdates).updates instanceof GramJs.Updates\n || (result as ResultWithUpdates).updates instanceof GramJs.UpdatesCombined\n )) {\n updatesContainer = (result as ResultWithUpdates).updates;\n }\n\n if (updatesContainer) {\n injectUpdateEntities(updatesContainer);\n\n updatesContainer.updates.forEach((update) => {\n updater(update, request);\n });\n } else if (result instanceof GramJs.UpdatesTooLong) {\n // TODO Implement\n } else {\n updater(result as GramJs.TypeUpdates, request);\n }\n }\n\n return result;\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log(`[GramJs/client] INVOKE ERROR ${request.className}`);\n // eslint-disable-next-line no-console\n console.error(err);\n }\n\n dispatchErrorUpdate(err, request);\n\n if (shouldThrow) {\n throw err;\n }\n\n return undefined;\n }\n}\n\nexport function downloadMedia(\n args: { url: string; mediaFormat: ApiMediaFormat; start?: number; end?: number; isHtmlAllowed?: boolean },\n onProgress?: ApiOnProgress,\n) {\n return downloadMediaWithClient(args, client, isConnected, onProgress);\n}\n\nexport function uploadFile(file: File, onProgress?: ApiOnProgress) {\n return client.uploadFile({ file, onProgress, workers: UPLOAD_WORKERS });\n}\n\nexport function updateTwoFaSettings(params: TwoFaParams) {\n return client.updateTwoFaSettings(params);\n}\n\nexport async function fetchCurrentUser() {\n const userFull = await invokeRequest(new GramJs.users.GetFullUser({\n id: new GramJs.InputUserSelf(),\n }));\n\n if (!userFull || !(userFull.user instanceof GramJs.User)) {\n return;\n }\n\n localDb.users[userFull.user.id] = userFull.user;\n const currentUser = buildApiUserFromFull(userFull);\n\n setMessageBuilderCurrentUserId(currentUser.id);\n onCurrentUserUpdate(currentUser);\n}\n\nexport function dispatchErrorUpdate<T extends GramJs.AnyRequest>(err: Error, request: T) {\n const isSlowMode = err.message.startsWith('A wait of') && (\n request instanceof GramJs.messages.SendMessage\n || request instanceof GramJs.messages.SendMedia\n || request instanceof GramJs.messages.SendMultiMedia\n );\n\n const { message } = err;\n\n onUpdate({\n '@type': 'error',\n error: {\n message,\n isSlowMode,\n hasErrorKey: true,\n },\n });\n}\n\nfunction injectUpdateEntities(result: GramJs.Updates | GramJs.UpdatesCombined) {\n const entities = [...result.users, ...result.chats];\n\n result.updates.forEach((update) => {\n if (entities) {\n // eslint-disable-next-line no-underscore-dangle\n (update as any)._entities = entities;\n }\n });\n}\n\nasync function handleTerminatedSession() {\n try {\n await invokeRequest(new GramJs.users.GetFullUser({\n id: new GramJs.InputUserSelf(),\n }), undefined, true);\n } catch (err) {\n if (err.message === 'AUTH_KEY_UNREGISTERED') {\n onUpdate({\n '@type': 'updateConnectionState',\n connectionState: 'connectionStateBroken',\n });\n }\n }\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n OnApiUpdate,\n ApiChat,\n ApiMessage,\n ApiUser,\n ApiMessageEntity,\n ApiFormattedText,\n ApiChatFullInfo,\n ApiChatFolder,\n ApiChatBannedRights,\n ApiChatAdminRights,\n} from '../../types';\n\nimport { DEBUG, ARCHIVED_FOLDER_ID, MEMBERS_LOAD_SLICE } from '../../../config';\nimport { invokeRequest, uploadFile } from './client';\nimport {\n buildApiChatFromDialog,\n getPeerKey,\n buildChatMembers,\n buildApiChatFromPreview,\n getApiChatIdFromMtpPeer,\n buildApiChatFolder,\n buildApiChatFolderFromSuggested,\n buildApiChatBotCommands,\n} from '../apiBuilders/chats';\nimport { buildApiMessage, buildMessageDraft } from '../apiBuilders/messages';\nimport { buildApiUser } from '../apiBuilders/users';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport localDb from '../localDb';\nimport {\n buildInputEntity,\n buildInputPeer,\n buildMtpMessageEntity,\n buildFilterFromApiFolder,\n isMessageWithMedia,\n buildChatBannedRights,\n buildChatAdminRights,\n} from '../gramjsBuilders';\nimport { addMessageToLocalDb } from '../helpers';\n\nconst MAX_INT_32 = 2 ** 31 - 1;\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function fetchChats({\n limit,\n offsetDate,\n archived,\n withPinned,\n serverTimeOffset,\n}: {\n limit: number;\n offsetDate?: number;\n archived?: boolean;\n withPinned?: boolean;\n serverTimeOffset: number;\n}) {\n const result = await invokeRequest(new GramJs.messages.GetDialogs({\n offsetPeer: new GramJs.InputPeerEmpty(),\n limit,\n offsetDate,\n folderId: archived ? ARCHIVED_FOLDER_ID : undefined,\n ...(withPinned && { excludePinned: true }),\n }));\n const resultPinned = withPinned\n ? await invokeRequest(new GramJs.messages.GetPinnedDialogs({\n folderId: archived ? ARCHIVED_FOLDER_ID : undefined,\n }))\n : undefined;\n\n if (!result || result instanceof GramJs.messages.DialogsNotModified) {\n return undefined;\n }\n\n if (resultPinned) {\n updateLocalDb(resultPinned);\n }\n updateLocalDb(result);\n\n const lastMessagesByChatId = buildCollectionByKey(\n (resultPinned ? resultPinned.messages : []).concat(result.messages)\n .map(buildApiMessage)\n .filter<ApiMessage>(Boolean as any),\n 'chatId',\n );\n const peersByKey: Record<string, GramJs.TypeChat | GramJs.TypeUser> = {\n ...(resultPinned && preparePeers(resultPinned)),\n ...preparePeers(result),\n };\n const chats: ApiChat[] = [];\n const draftsById: Record<number, ApiFormattedText> = {};\n const replyingToById: Record<number, number> = {};\n\n const dialogs = (resultPinned ? resultPinned.dialogs : []).concat(result.dialogs);\n\n const orderedPinnedIds: number[] = [];\n\n dialogs.forEach((dialog) => {\n if (\n !(dialog instanceof GramJs.Dialog)\n // This request can return dialogs not belonging to specified folder\n || (!archived && dialog.folderId === ARCHIVED_FOLDER_ID)\n || (archived && dialog.folderId !== ARCHIVED_FOLDER_ID)\n ) {\n return;\n }\n\n const peerEntity = peersByKey[getPeerKey(dialog.peer)];\n const chat = buildApiChatFromDialog(dialog, peerEntity, serverTimeOffset);\n chat.lastMessage = lastMessagesByChatId[chat.id];\n chat.isListed = true;\n chats.push(chat);\n\n if (withPinned && dialog.pinned) {\n orderedPinnedIds.push(chat.id);\n }\n\n if (dialog.draft) {\n const { formattedText, replyingToId } = buildMessageDraft(dialog.draft) || {};\n if (formattedText) {\n draftsById[chat.id] = formattedText;\n }\n if (replyingToId) {\n replyingToById[chat.id] = replyingToId;\n }\n }\n });\n\n const users = (resultPinned ? resultPinned.users : []).concat(result.users)\n .map(buildApiUser)\n .filter<ApiUser>(Boolean as any);\n const chatIds = chats.map((chat) => chat.id);\n\n let totalChatCount: number;\n\n if (result instanceof GramJs.messages.DialogsSlice) {\n totalChatCount = result.count;\n } else {\n totalChatCount = chatIds.length;\n }\n\n return {\n chatIds,\n chats,\n users,\n draftsById,\n replyingToById,\n orderedPinnedIds: withPinned ? orderedPinnedIds : undefined,\n totalChatCount,\n };\n}\n\nexport function fetchFullChat(chat: ApiChat) {\n const { id, accessHash, adminRights } = chat;\n\n const input = buildInputEntity(id, accessHash);\n\n return input instanceof GramJs.InputChannel\n ? getFullChannelInfo(id, accessHash!, adminRights)\n : getFullChatInfo(id);\n}\n\nexport async function searchChats({ query }: { query: string }) {\n const result = await invokeRequest(new GramJs.contacts.Search({ q: query }));\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const localPeerIds = result.myResults.map(getApiChatIdFromMtpPeer);\n const allChats = result.chats.concat(result.users)\n .map((user) => buildApiChatFromPreview(user))\n .filter<ApiChat>(Boolean as any);\n const allUsers = result.users.map(buildApiUser).filter((user) => !!user && !user.isSelf) as ApiUser[];\n\n return {\n localChats: allChats.filter((r) => localPeerIds.includes(r.id)),\n localUsers: allUsers.filter((u) => localPeerIds.includes(u.id)),\n globalChats: allChats.filter((r) => !localPeerIds.includes(r.id)),\n globalUsers: allUsers.filter((u) => !localPeerIds.includes(u.id)),\n };\n}\n\nexport async function fetchChat({\n type, user,\n}: {\n type: 'user' | 'self' | 'support'; user?: ApiUser;\n}) {\n let mtpUser: GramJs.User | undefined;\n\n if (type === 'self' || type === 'user') {\n const result = await invokeRequest(new GramJs.users.GetUsers({\n id: [\n type === 'user' && user\n ? buildInputEntity(user.id, user.accessHash) as GramJs.InputUser\n : new GramJs.InputUserSelf(),\n ],\n }));\n if (!result || !result.length) {\n return undefined;\n }\n\n [mtpUser] = result;\n } else if (type === 'support') {\n const result = await invokeRequest(new GramJs.help.GetSupport());\n if (!result || !result.user) {\n return undefined;\n }\n\n mtpUser = result.user;\n }\n\n const chat = buildApiChatFromPreview(mtpUser!, type === 'support');\n if (!chat) {\n return undefined;\n }\n\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n\n return { chatId: chat.id };\n}\n\nexport async function requestChatUpdate({\n chat,\n serverTimeOffset,\n}: {\n chat: ApiChat; serverTimeOffset: number;\n}) {\n const { id, accessHash } = chat;\n\n const result = await invokeRequest(new GramJs.messages.GetPeerDialogs({\n peers: [new GramJs.InputDialogPeer({\n peer: buildInputPeer(id, accessHash),\n })],\n }));\n\n if (!result) {\n return;\n }\n\n const dialog = result.dialogs[0];\n if (!dialog || !(dialog instanceof GramJs.Dialog)) {\n return;\n }\n\n const peersByKey = preparePeers(result);\n const peerEntity = peersByKey[getPeerKey(dialog.peer)];\n if (!peerEntity) {\n return;\n }\n\n updateLocalDb(result);\n\n const lastMessage = buildApiMessage(result.messages[0]);\n\n onUpdate({\n '@type': 'updateChat',\n id,\n chat: {\n ...buildApiChatFromDialog(dialog, peerEntity, serverTimeOffset),\n lastMessage,\n },\n });\n}\n\nexport function saveDraft({\n chat,\n text,\n entities,\n replyToMsgId,\n}: {\n chat: ApiChat;\n text: string;\n entities?: ApiMessageEntity[];\n replyToMsgId?: number;\n}) {\n return invokeRequest(new GramJs.messages.SaveDraft({\n peer: buildInputPeer(chat.id, chat.accessHash),\n message: text,\n ...(entities && {\n entities: entities.map(buildMtpMessageEntity),\n }),\n replyToMsgId,\n }));\n}\n\nexport function clearDraft(chat: ApiChat) {\n return invokeRequest(new GramJs.messages.SaveDraft({\n peer: buildInputPeer(chat.id, chat.accessHash),\n message: '',\n }));\n}\n\nasync function getFullChatInfo(chatId: number): Promise<{\n fullInfo: ApiChatFullInfo;\n users?: ApiUser[];\n} | undefined> {\n const result = await invokeRequest(new GramJs.messages.GetFullChat({\n chatId: buildInputEntity(chatId) as number,\n }));\n\n if (!result || !(result.fullChat instanceof GramJs.ChatFull)) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const {\n about,\n participants,\n exportedInvite,\n botInfo,\n } = result.fullChat;\n\n const members = buildChatMembers(participants);\n const adminMembers = members ? members.filter(({ isAdmin, isOwner }) => isAdmin || isOwner) : undefined;\n const botCommands = botInfo ? buildApiChatBotCommands(botInfo) : undefined;\n\n return {\n fullInfo: {\n about,\n members,\n adminMembers,\n canViewMembers: true,\n botCommands,\n ...(exportedInvite && {\n inviteLink: exportedInvite.link,\n }),\n },\n users: result.users.map(buildApiUser).filter<ApiUser>(Boolean as any),\n };\n}\n\nasync function getFullChannelInfo(\n id: number,\n accessHash: string,\n adminRights?: ApiChatAdminRights,\n) {\n const result = await invokeRequest(new GramJs.channels.GetFullChannel({\n channel: buildInputEntity(id, accessHash) as GramJs.InputChannel,\n }));\n\n if (!result || !(result.fullChat instanceof GramJs.ChannelFull)) {\n return undefined;\n }\n\n const {\n about,\n onlineCount,\n exportedInvite,\n slowmodeSeconds,\n slowmodeNextSendDate,\n migratedFromChatId,\n migratedFromMaxId,\n canViewParticipants,\n linkedChatId,\n hiddenPrehistory,\n call,\n botInfo,\n } = result.fullChat;\n\n const inviteLink = exportedInvite instanceof GramJs.ChatInviteExported\n ? exportedInvite.link\n : undefined;\n\n const { members, users } = (canViewParticipants && await fetchMembers(id, accessHash)) || {};\n const { members: kickedMembers, users: bannedUsers } = (\n canViewParticipants && adminRights && await fetchMembers(id, accessHash, 'kicked')\n ) || {};\n const { members: adminMembers, users: adminUsers } = (\n canViewParticipants && adminRights && await fetchMembers(id, accessHash, 'admin')\n ) || {};\n const botCommands = botInfo ? buildApiChatBotCommands(botInfo) : undefined;\n\n return {\n fullInfo: {\n about,\n onlineCount,\n inviteLink,\n slowMode: slowmodeSeconds ? {\n seconds: slowmodeSeconds,\n nextSendDate: slowmodeNextSendDate,\n } : undefined,\n migratedFrom: migratedFromChatId ? {\n chatId: getApiChatIdFromMtpPeer({ chatId: migratedFromChatId } as GramJs.TypePeer),\n maxMessageId: migratedFromMaxId,\n } : undefined,\n canViewMembers: canViewParticipants,\n isPreHistoryHidden: hiddenPrehistory,\n members,\n kickedMembers,\n adminMembers,\n groupCallId: call ? call.id.toString() : undefined,\n linkedChatId: linkedChatId ? getApiChatIdFromMtpPeer({ chatId: linkedChatId } as GramJs.TypePeer) : undefined,\n botCommands,\n },\n users: [...(users || []), ...(bannedUsers || []), ...(adminUsers || [])],\n };\n}\n\nexport async function updateChatMutedState({\n chat, isMuted, serverTimeOffset,\n}: {\n chat: ApiChat; isMuted: boolean; serverTimeOffset: number;\n}) {\n await invokeRequest(new GramJs.account.UpdateNotifySettings({\n peer: new GramJs.InputNotifyPeer({\n peer: buildInputPeer(chat.id, chat.accessHash),\n }),\n settings: new GramJs.InputPeerNotifySettings({ muteUntil: isMuted ? MAX_INT_32 : 0 }),\n }));\n\n onUpdate({\n '@type': 'updateNotifyExceptions',\n chatId: chat.id,\n isMuted,\n });\n\n void requestChatUpdate({\n chat,\n serverTimeOffset,\n });\n}\n\nexport async function createChannel({\n title, about, users,\n}: {\n title: string; about?: string; users: ApiUser[];\n}): Promise<ApiChat | undefined> {\n const result = await invokeRequest(new GramJs.channels.CreateChannel({\n broadcast: true,\n title,\n about,\n }), true);\n\n // `createChannel` can return a lot of different update types according to docs,\n // but currently channel creation returns only `Updates` type.\n // Errors are added to catch unexpected cases in future testing\n if (!(result instanceof GramJs.Updates)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected channel creation update', result);\n }\n return undefined;\n }\n\n const newChannel = result.chats[0];\n if (!newChannel || !(newChannel instanceof GramJs.Channel)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Created channel not found', result);\n }\n return undefined;\n }\n\n const channel = buildApiChatFromPreview(newChannel)!;\n\n await invokeRequest(new GramJs.channels.InviteToChannel({\n channel: buildInputEntity(channel.id, channel.accessHash) as GramJs.InputChannel,\n users: users.map(({ id, accessHash }) => buildInputEntity(id, accessHash)) as GramJs.InputUser[],\n }));\n\n return channel;\n}\n\nexport function joinChannel({\n channelId, accessHash,\n}: {\n channelId: number; accessHash: string;\n}) {\n return invokeRequest(new GramJs.channels.JoinChannel({\n channel: buildInputEntity(channelId, accessHash) as GramJs.InputChannel,\n }), true);\n}\n\nexport function deleteChatUser({\n chat, user,\n}: {\n chat: ApiChat; user: ApiUser;\n}) {\n if (chat.type !== 'chatTypeBasicGroup') return undefined;\n return invokeRequest(new GramJs.messages.DeleteChatUser({\n chatId: buildInputEntity(chat.id, chat.accessHash) as number,\n userId: buildInputEntity(user.id, user.accessHash) as GramJs.InputUser,\n }), true);\n}\n\nexport function deleteChat({\n chatId,\n}: {\n chatId: number;\n}) {\n return invokeRequest(new GramJs.messages.DeleteChat({\n chatId: buildInputEntity(chatId) as number,\n }), true);\n}\n\nexport function leaveChannel({\n channelId, accessHash,\n}: {\n channelId: number; accessHash: string;\n}) {\n return invokeRequest(new GramJs.channels.LeaveChannel({\n channel: buildInputEntity(channelId, accessHash) as GramJs.InputChannel,\n }), true);\n}\n\nexport function deleteChannel({\n channelId, accessHash,\n}: {\n channelId: number; accessHash: string;\n}) {\n return invokeRequest(new GramJs.channels.DeleteChannel({\n channel: buildInputEntity(channelId, accessHash) as GramJs.InputChannel,\n }), true);\n}\n\nexport async function createGroupChat({\n title, users,\n}: {\n title: string; users: ApiUser[];\n}): Promise<ApiChat | undefined> {\n const result = await invokeRequest(new GramJs.messages.CreateChat({\n title,\n users: users.map(({ id, accessHash }) => buildInputEntity(id, accessHash)) as GramJs.InputUser[],\n }), true);\n\n // `createChat` can return a lot of different update types according to docs,\n // but currently chat creation returns only `Updates` type.\n // Errors are added to catch unexpected cases in future testing\n if (!(result instanceof GramJs.Updates)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected chat creation update', result);\n }\n return undefined;\n }\n\n const newChat = result.chats[0];\n if (!newChat || !(newChat instanceof GramJs.Chat)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Created chat not found', result);\n }\n return undefined;\n }\n\n return buildApiChatFromPreview(newChat);\n}\n\nexport async function editChatPhoto({\n chatId, accessHash, photo,\n}: {\n chatId: number; accessHash?: string; photo: File;\n}) {\n const uploadedPhoto = await uploadFile(photo);\n const inputEntity = buildInputEntity(chatId, accessHash);\n\n return invokeRequest(\n inputEntity instanceof GramJs.InputChannel\n ? new GramJs.channels.EditPhoto({\n channel: inputEntity as GramJs.InputChannel,\n photo: new GramJs.InputChatUploadedPhoto({\n file: uploadedPhoto,\n }),\n })\n : new GramJs.messages.EditChatPhoto({\n chatId: inputEntity as number,\n photo: new GramJs.InputChatUploadedPhoto({\n file: uploadedPhoto,\n }),\n }),\n true,\n );\n}\n\nexport async function toggleChatPinned({\n chat,\n shouldBePinned,\n}: {\n chat: ApiChat;\n shouldBePinned: boolean;\n}) {\n const { id, accessHash } = chat;\n\n const isActionSuccessful = await invokeRequest(new GramJs.messages.ToggleDialogPin({\n peer: new GramJs.InputDialogPeer({\n peer: buildInputPeer(id, accessHash),\n }),\n pinned: shouldBePinned || undefined,\n }));\n\n if (isActionSuccessful) {\n onUpdate({\n '@type': 'updateChatPinned',\n id: chat.id,\n isPinned: shouldBePinned,\n });\n }\n}\n\nexport function toggleChatArchived({\n chat, folderId,\n}: {\n chat: ApiChat; folderId: number;\n}) {\n const { id, accessHash } = chat;\n\n return invokeRequest(new GramJs.folders.EditPeerFolders({\n folderPeers: [new GramJs.InputFolderPeer({\n peer: buildInputPeer(id, accessHash),\n folderId,\n })],\n }), true);\n}\n\nexport async function fetchChatFolders() {\n const result = await invokeRequest(new GramJs.messages.GetDialogFilters());\n\n if (!result) {\n return undefined;\n }\n\n return {\n byId: buildCollectionByKey(result.map(buildApiChatFolder), 'id') as Record<number, ApiChatFolder>,\n orderedIds: result.map(({ id }) => id),\n };\n}\n\nexport async function fetchRecommendedChatFolders() {\n const results = await invokeRequest(new GramJs.messages.GetSuggestedDialogFilters());\n\n if (!results) {\n return undefined;\n }\n\n return results.map(buildApiChatFolderFromSuggested);\n}\n\nexport async function editChatFolder({\n id,\n folderUpdate,\n}: {\n id: number;\n folderUpdate: ApiChatFolder;\n}) {\n const filter = buildFilterFromApiFolder(folderUpdate);\n\n const isActionSuccessful = await invokeRequest(new GramJs.messages.UpdateDialogFilter({\n id,\n filter,\n }));\n\n if (isActionSuccessful) {\n onUpdate({\n '@type': 'updateChatFolder',\n id,\n folder: folderUpdate,\n });\n }\n}\n\nexport async function deleteChatFolder(id: number) {\n const isActionSuccessful = await invokeRequest(new GramJs.messages.UpdateDialogFilter({\n id,\n filter: undefined,\n }));\n const recommendedChatFolders = await fetchRecommendedChatFolders();\n\n if (isActionSuccessful) {\n onUpdate({\n '@type': 'updateChatFolder',\n id,\n folder: undefined,\n });\n }\n if (recommendedChatFolders) {\n onUpdate({\n '@type': 'updateRecommendedChatFolders',\n folders: recommendedChatFolders,\n });\n }\n}\n\nexport async function toggleDialogUnread({\n chat, hasUnreadMark,\n}: {\n chat: ApiChat; hasUnreadMark: boolean | undefined;\n}) {\n const { id, accessHash } = chat;\n\n const isActionSuccessful = await invokeRequest(new GramJs.messages.MarkDialogUnread({\n peer: new GramJs.InputDialogPeer({\n peer: buildInputPeer(id, accessHash),\n }),\n unread: hasUnreadMark || undefined,\n }));\n\n if (isActionSuccessful) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat: { hasUnreadMark },\n });\n }\n}\n\nexport async function getChatByUsername(username: string) {\n const result = await invokeRequest(new GramJs.contacts.ResolveUsername({\n username,\n }));\n\n if (!result) {\n return undefined;\n }\n\n const { users, chats } = result;\n\n const chat = chats.length\n ? buildApiChatFromPreview(chats[0])\n : buildApiChatFromPreview(users[0]);\n\n if (!chat) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return chat;\n}\n\nexport function togglePreHistoryHidden({\n chat, isEnabled,\n}: { chat: ApiChat; isEnabled: boolean }) {\n const { id, accessHash } = chat;\n const channel = buildInputEntity(id, accessHash);\n\n return invokeRequest(new GramJs.channels.TogglePreHistoryHidden({\n channel: channel as GramJs.InputChannel,\n enabled: isEnabled,\n }), true);\n}\n\nexport function updateChatDefaultBannedRights({\n chat, bannedRights,\n}: { chat: ApiChat; bannedRights: ApiChatBannedRights }) {\n const { id, accessHash } = chat;\n const peer = buildInputPeer(id, accessHash);\n\n return invokeRequest(new GramJs.messages.EditChatDefaultBannedRights({\n peer,\n bannedRights: buildChatBannedRights(bannedRights),\n }), true);\n}\n\nexport function updateChatMemberBannedRights({\n chat, user, bannedRights, untilDate,\n}: { chat: ApiChat; user: ApiUser; bannedRights: ApiChatBannedRights; untilDate?: number }) {\n const channel = buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel;\n const participant = buildInputPeer(user.id, user.accessHash) as GramJs.InputUser;\n\n return invokeRequest(new GramJs.channels.EditBanned({\n channel,\n participant,\n bannedRights: buildChatBannedRights(bannedRights, untilDate),\n }), true);\n}\n\nexport function updateChatAdmin({\n chat, user, adminRights, customTitle = '',\n}: { chat: ApiChat; user: ApiUser; adminRights: ApiChatAdminRights; customTitle: string }) {\n const channel = buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel;\n const userId = buildInputEntity(user.id, user.accessHash) as GramJs.InputUser;\n\n return invokeRequest(new GramJs.channels.EditAdmin({\n channel,\n userId,\n adminRights: buildChatAdminRights(adminRights),\n rank: customTitle,\n }), true);\n}\n\nexport async function updateChatTitle(chat: ApiChat, title: string) {\n const inputEntity = buildInputEntity(chat.id, chat.accessHash);\n await invokeRequest(\n inputEntity instanceof GramJs.InputChannel\n ? new GramJs.channels.EditTitle({\n channel: inputEntity as GramJs.InputChannel,\n title,\n }) : new GramJs.messages.EditChatTitle({\n chatId: inputEntity as number,\n title,\n }),\n true,\n );\n}\n\nexport async function updateChatAbout(chat: ApiChat, about: string) {\n const result = await invokeRequest(new GramJs.messages.EditChatAbout({\n peer: buildInputPeer(chat.id, chat.accessHash),\n about,\n }));\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'updateChatFullInfo',\n id: chat.id,\n fullInfo: {\n about,\n },\n });\n}\n\nexport function toggleSignatures({\n chat, isEnabled,\n}: { chat: ApiChat; isEnabled: boolean }) {\n const { id, accessHash } = chat;\n const channel = buildInputEntity(id, accessHash);\n\n return invokeRequest(new GramJs.channels.ToggleSignatures({\n channel: channel as GramJs.InputChannel,\n enabled: isEnabled,\n }), true);\n}\n\ntype ChannelMembersFilter =\n 'kicked'\n | 'admin'\n | 'recent';\n\nexport async function fetchMembers(\n chatId: number,\n accessHash: string,\n memberFilter: ChannelMembersFilter = 'recent',\n offset?: number,\n) {\n let filter: GramJs.TypeChannelParticipantsFilter;\n\n switch (memberFilter) {\n case 'kicked':\n filter = new GramJs.ChannelParticipantsKicked({ q: '' });\n break;\n case 'admin':\n filter = new GramJs.ChannelParticipantsAdmins();\n break;\n default:\n filter = new GramJs.ChannelParticipantsRecent();\n break;\n }\n\n const result = await invokeRequest(new GramJs.channels.GetParticipants({\n channel: buildInputEntity(chatId, accessHash) as GramJs.InputChannel,\n filter,\n offset,\n limit: MEMBERS_LOAD_SLICE,\n }));\n\n if (!result || result instanceof GramJs.channels.ChannelParticipantsNotModified) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return {\n members: buildChatMembers(result),\n users: result.users.map(buildApiUser).filter<ApiUser>(Boolean as any),\n };\n}\n\nexport async function fetchGroupsForDiscussion() {\n const result = await invokeRequest(new GramJs.channels.GetGroupsForDiscussion());\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return result.chats.map((chat) => buildApiChatFromPreview(chat));\n}\n\nexport function setDiscussionGroup({\n channel,\n chat,\n}: {\n channel: ApiChat;\n chat?: ApiChat;\n}) {\n return invokeRequest(new GramJs.channels.SetDiscussionGroup({\n broadcast: buildInputPeer(channel.id, channel.accessHash),\n group: chat ? buildInputPeer(chat.id, chat.accessHash) : new GramJs.InputChannelEmpty(),\n }));\n}\n\nexport async function migrateChat(chat: ApiChat) {\n const result = await invokeRequest(\n new GramJs.messages.MigrateChat({ chatId: buildInputEntity(chat.id) as number }), true,\n );\n\n // `migrateChat` can return a lot of different update types according to docs,\n // but currently chat migrations returns only `Updates` type.\n // Errors are added to catch unexpected cases in future testing\n if (!result || !(result instanceof GramJs.Updates)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected channel creation update', result);\n }\n\n return undefined;\n }\n\n updateLocalDb(result);\n\n return buildApiChatFromPreview(result.chats[1]);\n}\n\nexport async function openChatByInvite(hash: string) {\n const result = await invokeRequest(new GramJs.messages.CheckChatInvite({ hash }));\n\n if (!result) {\n return undefined;\n }\n\n let chat: ApiChat | undefined;\n\n if (result instanceof GramJs.ChatInvite) {\n onUpdate({\n '@type': 'showInvite',\n data: {\n title: result.title,\n hash,\n participantsCount: result.participantsCount,\n isChannel: result.channel,\n },\n });\n } else {\n chat = buildApiChatFromPreview(result.chat);\n\n if (chat) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n }\n }\n\n if (!chat) {\n return undefined;\n }\n\n return { chatId: chat.id };\n}\n\nexport function addChatMembers(chat: ApiChat, users: ApiUser[]) {\n if (chat.type === 'chatTypeChannel' || chat.type === 'chatTypeSuperGroup') {\n return invokeRequest(new GramJs.channels.InviteToChannel({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n users: users.map((user) => buildInputEntity(user.id, user.accessHash)) as GramJs.InputUser[],\n }), true);\n }\n\n return Promise.all(users.map((user) => {\n return invokeRequest(new GramJs.messages.AddChatUser({\n chatId: buildInputEntity(chat.id) as number,\n userId: buildInputEntity(user.id, user.accessHash) as GramJs.InputUser,\n }), true);\n }));\n}\n\nexport function deleteChatMember(chat: ApiChat, user: ApiUser) {\n if (chat.type === 'chatTypeChannel' || chat.type === 'chatTypeSuperGroup') {\n return updateChatMemberBannedRights({\n chat,\n user,\n bannedRights: {\n viewMessages: true,\n sendMessages: true,\n sendMedia: true,\n sendStickers: true,\n sendGifs: true,\n sendGames: true,\n sendInline: true,\n embedLinks: true,\n sendPolls: true,\n changeInfo: true,\n inviteUsers: true,\n pinMessages: true,\n },\n untilDate: MAX_INT_32,\n });\n } else {\n return invokeRequest(new GramJs.messages.DeleteChatUser({\n chatId: buildInputEntity(chat.id) as number,\n userId: buildInputEntity(user.id, user.accessHash) as GramJs.InputUser,\n }), true);\n }\n}\n\nfunction preparePeers(\n result: GramJs.messages.Dialogs | GramJs.messages.DialogsSlice | GramJs.messages.PeerDialogs,\n) {\n const store: Record<string, GramJs.TypeChat | GramJs.TypeUser> = {};\n\n result.chats.forEach((chat) => {\n store[`chat${chat.id}`] = chat;\n });\n\n result.users.forEach((user) => {\n store[`user${user.id}`] = user;\n });\n\n return store;\n}\n\nfunction updateLocalDb(result: (\n GramJs.messages.Dialogs | GramJs.messages.DialogsSlice | GramJs.messages.PeerDialogs |\n GramJs.messages.ChatFull | GramJs.contacts.Found |\n GramJs.contacts.ResolvedPeer | GramJs.channels.ChannelParticipants |\n GramJs.messages.Chats | GramJs.messages.ChatsSlice | GramJs.TypeUpdates\n)) {\n if ('users' in result) {\n result.users.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[user.id] = user;\n }\n });\n }\n\n if ('chats' in result) {\n result.chats.forEach((chat) => {\n if (chat instanceof GramJs.Chat || chat instanceof GramJs.Channel) {\n localDb.chats[chat.id] = chat;\n }\n });\n }\n\n if ('messages' in result) {\n result.messages.forEach((message) => {\n if (message instanceof GramJs.Message && isMessageWithMedia(message)) {\n addMessageToLocalDb(message);\n }\n });\n }\n}\n\nexport async function importChatInvite({ hash }: { hash: string }) {\n const updates = await invokeRequest(new GramJs.messages.ImportChatInvite({ hash }), true);\n if (!(updates instanceof GramJs.Updates) || !updates.chats.length) {\n return undefined;\n }\n\n const chat = buildApiChatFromPreview(updates.chats[0]);\n\n return chat;\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n ApiChat,\n ApiAttachment,\n ApiMessage,\n OnApiUpdate,\n ApiMessageSearchType,\n ApiUser,\n ApiSticker,\n ApiVideo,\n ApiNewPoll,\n ApiMessageEntity,\n ApiOnProgress,\n ApiThreadInfo,\n MAIN_THREAD_ID,\n MESSAGE_DELETED,\n ApiGlobalMessageSearchType,\n ApiReportReason,\n} from '../../types';\n\nimport { ALL_FOLDER_ID, DEBUG, PINNED_MESSAGES_LIMIT } from '../../../config';\nimport { invokeRequest, uploadFile } from './client';\nimport {\n buildApiMessage,\n buildLocalMessage,\n buildWebPage,\n buildForwardedMessage,\n} from '../apiBuilders/messages';\nimport { buildApiUser } from '../apiBuilders/users';\nimport {\n buildInputEntity,\n buildInputPeer,\n generateRandomBigInt,\n getEntityTypeById,\n buildInputMediaDocument,\n buildInputPoll,\n buildMtpMessageEntity,\n isMessageWithMedia,\n isServiceMessageWithMedia,\n calculateResultHash,\n buildInputReportReason,\n} from '../gramjsBuilders';\nimport localDb from '../localDb';\nimport { buildApiChatFromPreview } from '../apiBuilders/chats';\nimport { fetchFile } from '../../../util/files';\nimport { addMessageToLocalDb, resolveMessageApiChatId } from '../helpers';\nimport { interpolateArray } from '../../../util/waveform';\nimport { requestChatUpdate } from './chats';\n\nconst FAST_SEND_TIMEOUT = 1000;\nconst INPUT_WAVEFORM_LENGTH = 63;\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function fetchMessages({\n chat,\n threadId,\n ...pagination\n}: {\n chat: ApiChat;\n threadId?: number;\n offsetId?: number;\n addOffset?: number;\n limit: number;\n}) {\n const RequestClass = threadId === MAIN_THREAD_ID ? GramJs.messages.GetHistory : GramJs.messages.GetReplies;\n let result;\n\n try {\n result = await invokeRequest(new RequestClass({\n peer: buildInputPeer(chat.id, chat.accessHash),\n ...(threadId !== MAIN_THREAD_ID && {\n msgId: threadId,\n }),\n ...pagination,\n }), undefined, true);\n } catch (err) {\n if (err.message === 'CHANNEL_PRIVATE') {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat: {\n isRestricted: true,\n },\n });\n }\n }\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiMessage).filter<ApiMessage>(Boolean as any);\n const users = result.users.map(buildApiUser).filter<ApiUser>(Boolean as any);\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter<ApiChat>(Boolean as any);\n const threadInfos = messages.map(({ threadInfo }) => threadInfo).filter<ApiThreadInfo>(Boolean as any);\n\n return {\n messages,\n users,\n chats,\n threadInfos,\n };\n}\n\nexport async function fetchMessage({ chat, messageId }: { chat: ApiChat; messageId: number }) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n\n const result = await invokeRequest(\n isChannel\n ? new GramJs.channels.GetMessages({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n id: [new GramJs.InputMessageID({ id: messageId })],\n })\n : new GramJs.messages.GetMessages({\n id: [new GramJs.InputMessageID({ id: messageId })],\n }),\n );\n\n if (!result || result instanceof GramJs.messages.MessagesNotModified) {\n return undefined;\n }\n\n const mtpMessage = result.messages[0];\n if (!mtpMessage) {\n return undefined;\n }\n\n if (mtpMessage instanceof GramJs.MessageEmpty) {\n return MESSAGE_DELETED;\n }\n\n const message = mtpMessage && buildApiMessage(mtpMessage);\n if (!message) {\n return undefined;\n }\n\n if (mtpMessage instanceof GramJs.Message) {\n addMessageToLocalDb(mtpMessage);\n }\n\n const users = result.users.map(buildApiUser).filter<ApiUser>(Boolean as any);\n\n return { message, users };\n}\n\nlet queue = Promise.resolve();\n\nexport function sendMessage(\n {\n chat,\n text,\n entities,\n replyingTo,\n attachment,\n sticker,\n gif,\n poll,\n isSilent,\n scheduledAt,\n groupedId,\n noWebPage,\n serverTimeOffset,\n }: {\n chat: ApiChat;\n text?: string;\n entities?: ApiMessageEntity[];\n replyingTo?: number;\n attachment?: ApiAttachment;\n sticker?: ApiSticker;\n gif?: ApiVideo;\n poll?: ApiNewPoll;\n isSilent?: boolean;\n scheduledAt?: number;\n groupedId?: string;\n noWebPage?: boolean;\n serverTimeOffset?: number;\n },\n onProgress?: ApiOnProgress,\n) {\n const localMessage = buildLocalMessage(\n chat, text, entities, replyingTo, attachment, sticker, gif, poll, groupedId, scheduledAt, serverTimeOffset,\n );\n onUpdate({\n '@type': localMessage.isScheduled ? 'newScheduledMessage' : 'newMessage',\n id: localMessage.id,\n chatId: chat.id,\n message: localMessage,\n });\n\n // This is expected to arrive after `updateMessageSendSucceeded` which replaces the local ID,\n // so in most cases this will be simply ignored\n setTimeout(() => {\n onUpdate({\n '@type': localMessage.isScheduled ? 'updateScheduledMessage' : 'updateMessage',\n id: localMessage.id,\n chatId: chat.id,\n message: {\n sendingState: 'messageSendingStatePending',\n },\n });\n }, FAST_SEND_TIMEOUT);\n\n const randomId = generateRandomBigInt();\n localDb.localMessages[randomId.toString()] = localMessage;\n\n if (groupedId) {\n return sendGroupedMedia({\n chat, text, entities, replyingTo, attachment: attachment!, groupedId, isSilent, scheduledAt,\n }, randomId, localMessage, onProgress);\n }\n\n const prevQueue = queue;\n queue = (async () => {\n let media: GramJs.TypeInputMedia | undefined;\n if (attachment) {\n try {\n media = await uploadMedia(localMessage, attachment, onProgress!);\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n\n await prevQueue;\n\n return;\n }\n } else if (sticker) {\n media = buildInputMediaDocument(sticker);\n } else if (gif) {\n media = buildInputMediaDocument(gif);\n } else if (poll) {\n media = buildInputPoll(poll, randomId);\n }\n\n await prevQueue;\n\n const RequestClass = media ? GramJs.messages.SendMedia : GramJs.messages.SendMessage;\n\n await invokeRequest(new RequestClass({\n clearDraft: true,\n message: text || '',\n entities: entities ? entities.map(buildMtpMessageEntity) : undefined,\n peer: buildInputPeer(chat.id, chat.accessHash),\n randomId,\n ...(isSilent && { silent: isSilent }),\n ...(scheduledAt && { scheduleDate: scheduledAt }),\n ...(replyingTo && { replyToMsgId: replyingTo }),\n ...(media && { media }),\n ...(noWebPage && { noWebpage: noWebPage }),\n }), true);\n })();\n\n return queue;\n}\n\nconst groupedUploads: Record<string, {\n counter: number;\n singleMediaByIndex: Record<number, GramJs.InputSingleMedia>;\n}> = {};\n\nfunction sendGroupedMedia(\n {\n chat,\n text,\n entities,\n replyingTo,\n attachment,\n groupedId,\n isSilent,\n scheduledAt,\n }: {\n chat: ApiChat;\n text?: string;\n entities?: ApiMessageEntity[];\n replyingTo?: number;\n attachment: ApiAttachment;\n groupedId: string;\n isSilent?: boolean;\n scheduledAt?: number;\n },\n randomId: GramJs.long,\n localMessage: ApiMessage,\n onProgress?: ApiOnProgress,\n) {\n let groupIndex = -1;\n if (!groupedUploads[groupedId]) {\n groupedUploads[groupedId] = {\n counter: 0,\n singleMediaByIndex: {},\n };\n }\n\n groupIndex = groupedUploads[groupedId].counter++;\n\n const prevQueue = queue;\n queue = (async () => {\n let media;\n try {\n media = await uploadMedia(localMessage, attachment, onProgress!);\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n\n groupedUploads[groupedId].counter--;\n\n await prevQueue;\n\n return;\n }\n\n const inputMedia = await fetchInputMedia(\n buildInputPeer(chat.id, chat.accessHash),\n media as GramJs.InputMediaUploadedPhoto | GramJs.InputMediaUploadedDocument,\n );\n\n await prevQueue;\n\n if (!inputMedia) {\n groupedUploads[groupedId].counter--;\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('Failed to upload grouped media');\n }\n\n return;\n }\n\n groupedUploads[groupedId].singleMediaByIndex[groupIndex] = new GramJs.InputSingleMedia({\n media: inputMedia,\n randomId,\n message: text || '',\n entities: entities ? entities.map(buildMtpMessageEntity) : undefined,\n });\n\n if (Object.keys(groupedUploads[groupedId].singleMediaByIndex).length < groupedUploads[groupedId].counter) {\n return;\n }\n\n const { singleMediaByIndex } = groupedUploads[groupedId];\n delete groupedUploads[groupedId];\n\n await invokeRequest(new GramJs.messages.SendMultiMedia({\n clearDraft: true,\n peer: buildInputPeer(chat.id, chat.accessHash),\n multiMedia: Object.values(singleMediaByIndex), // Object keys are usually ordered\n replyToMsgId: replyingTo,\n ...(isSilent && { silent: isSilent }),\n ...(scheduledAt && { scheduleDate: scheduledAt }),\n }), true);\n })();\n\n return queue;\n}\n\nasync function fetchInputMedia(\n peer: GramJs.TypeInputPeer,\n uploadedMedia: GramJs.InputMediaUploadedPhoto | GramJs.InputMediaUploadedDocument,\n) {\n const messageMedia = await invokeRequest(new GramJs.messages.UploadMedia({\n peer,\n media: uploadedMedia,\n }));\n\n if ((\n messageMedia instanceof GramJs.MessageMediaPhoto\n && messageMedia.photo\n && messageMedia.photo instanceof GramJs.Photo)\n ) {\n const { photo: { id, accessHash, fileReference } } = messageMedia;\n\n return new GramJs.InputMediaPhoto({\n id: new GramJs.InputPhoto({ id, accessHash, fileReference }),\n });\n }\n\n if ((\n messageMedia instanceof GramJs.MessageMediaDocument\n && messageMedia.document\n && messageMedia.document instanceof GramJs.Document)\n ) {\n const { document: { id, accessHash, fileReference } } = messageMedia;\n\n return new GramJs.InputMediaDocument({\n id: new GramJs.InputDocument({ id, accessHash, fileReference }),\n });\n }\n\n return undefined;\n}\n\nexport async function editMessage({\n chat,\n message,\n text,\n entities,\n noWebPage,\n serverTimeOffset,\n}: {\n chat: ApiChat;\n message: ApiMessage;\n text: string;\n entities?: ApiMessageEntity[];\n noWebPage?: boolean;\n serverTimeOffset: number;\n}) {\n const isScheduled = message.date * 1000 > Date.now() + serverTimeOffset * 1000;\n const messageUpdate: Partial<ApiMessage> = {\n content: {\n ...message.content,\n ...(text && {\n text: {\n text,\n entities,\n },\n }),\n },\n };\n\n onUpdate({\n '@type': isScheduled ? 'updateScheduledMessage' : 'updateMessage',\n id: message.id,\n chatId: chat.id,\n message: messageUpdate,\n });\n\n // TODO Revise intersecting with scheduled\n localDb.localMessages[message.id] = { ...message, ...messageUpdate };\n\n const mtpEntities = entities && entities.map(buildMtpMessageEntity);\n\n await invokeRequest(new GramJs.messages.EditMessage({\n message: text || '',\n entities: mtpEntities,\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: message.id,\n ...(isScheduled && { scheduleDate: message.date }),\n ...(noWebPage && { noWebpage: noWebPage }),\n }), true);\n}\n\nexport async function rescheduleMessage({\n chat,\n message,\n scheduledAt,\n}: {\n chat: ApiChat;\n message: ApiMessage;\n scheduledAt: number;\n}) {\n await invokeRequest(new GramJs.messages.EditMessage({\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: message.id,\n scheduleDate: scheduledAt,\n }), true);\n}\n\nasync function uploadMedia(localMessage: ApiMessage, attachment: ApiAttachment, onProgress: ApiOnProgress) {\n const {\n filename, blobUrl, mimeType, quick, voice,\n } = attachment;\n\n const file = await fetchFile(blobUrl, filename);\n const patchedOnProgress: ApiOnProgress = (progress) => {\n if (onProgress.isCanceled) {\n patchedOnProgress.isCanceled = true;\n } else {\n onProgress(progress, localMessage.id);\n }\n };\n const inputFile = await uploadFile(file, patchedOnProgress);\n\n const attributes: GramJs.TypeDocumentAttribute[] = [new GramJs.DocumentAttributeFilename({ fileName: filename })];\n if (quick) {\n if (mimeType.startsWith('image/')) {\n return new GramJs.InputMediaUploadedPhoto({ file: inputFile });\n } else {\n const { width, height, duration } = quick;\n if (duration !== undefined) {\n attributes.push(new GramJs.DocumentAttributeVideo({\n duration,\n w: width,\n h: height,\n }));\n }\n }\n }\n\n if (voice) {\n const { duration, waveform } = voice;\n const { data: inputWaveform } = interpolateArray(waveform, INPUT_WAVEFORM_LENGTH);\n attributes.push(new GramJs.DocumentAttributeAudio({\n voice: true,\n duration,\n waveform: Buffer.from(inputWaveform),\n }));\n }\n\n return new GramJs.InputMediaUploadedDocument({\n file: inputFile,\n mimeType,\n attributes,\n });\n}\n\nexport async function pinMessage({\n chat, messageId, isUnpin, isOneSide, isSilent,\n}: { chat: ApiChat; messageId: number; isUnpin: boolean; isOneSide: boolean; isSilent: boolean }) {\n await invokeRequest(new GramJs.messages.UpdatePinnedMessage({\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: messageId,\n ...(isUnpin && { unpin: true }),\n ...(isOneSide && { pmOneside: true }),\n ...(isSilent && { silent: true }),\n }), true);\n}\n\nexport async function unpinAllMessages({ chat }: { chat: ApiChat }) {\n await invokeRequest(new GramJs.messages.UnpinAllMessages({\n peer: buildInputPeer(chat.id, chat.accessHash),\n }), true);\n}\n\nexport async function deleteMessages({\n chat, messageIds, shouldDeleteForAll,\n}: {\n chat: ApiChat; messageIds: number[]; shouldDeleteForAll?: boolean;\n}) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n\n const result = await invokeRequest(\n isChannel\n ? new GramJs.channels.DeleteMessages({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n id: messageIds,\n })\n : new GramJs.messages.DeleteMessages({\n id: messageIds,\n ...(shouldDeleteForAll && { revoke: true }),\n }),\n );\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'deleteMessages',\n ids: messageIds,\n ...(isChannel && { chatId: chat.id }),\n });\n}\n\nexport async function deleteScheduledMessages({\n chat, messageIds,\n}: {\n chat: ApiChat; messageIds: number[];\n}) {\n const result = await invokeRequest(\n new GramJs.messages.DeleteScheduledMessages({\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: messageIds,\n }),\n );\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'deleteScheduledMessages',\n ids: messageIds,\n chatId: chat.id,\n });\n}\n\nexport async function deleteHistory({\n chat, shouldDeleteForAll, maxId,\n}: {\n chat: ApiChat; shouldDeleteForAll?: boolean; maxId?: number;\n}) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n const result = await invokeRequest(\n isChannel\n ? new GramJs.channels.DeleteHistory({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n maxId,\n })\n : new GramJs.messages.DeleteHistory({\n peer: buildInputPeer(chat.id, chat.accessHash),\n ...(shouldDeleteForAll && { revoke: true }),\n ...(!shouldDeleteForAll && { just_clear: true }),\n maxId,\n }),\n );\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'deleteHistory',\n chatId: chat.id,\n });\n}\n\nexport async function reportMessages({\n peer, messageIds, reason, description,\n}: {\n peer: ApiChat | ApiUser; messageIds: number[]; reason: ApiReportReason; description?: string;\n}) {\n const result = await invokeRequest(new GramJs.messages.Report({\n peer: buildInputPeer(peer.id, peer.accessHash),\n id: messageIds,\n reason: buildInputReportReason(reason),\n message: description,\n }));\n\n return result;\n}\n\nexport async function markMessageListRead({\n chat, threadId, maxId, serverTimeOffset,\n}: {\n chat: ApiChat; threadId: number; maxId?: number; serverTimeOffset: number;\n}) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n\n if (isChannel && threadId === MAIN_THREAD_ID) {\n await invokeRequest(new GramJs.channels.ReadHistory({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n maxId,\n }));\n } else if (isChannel) {\n await invokeRequest(new GramJs.messages.ReadDiscussion({\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: threadId,\n readMaxId: maxId,\n }));\n } else {\n await invokeRequest(new GramJs.messages.ReadHistory({\n peer: buildInputPeer(chat.id, chat.accessHash),\n maxId,\n }));\n }\n\n if (threadId === MAIN_THREAD_ID) {\n void requestChatUpdate({ chat, serverTimeOffset });\n } else {\n void requestThreadInfoUpdate({ chat, threadId });\n }\n}\n\nexport async function markMessagesRead({\n chat, messageIds,\n}: {\n chat: ApiChat; messageIds: number[];\n}) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n\n await invokeRequest(\n isChannel\n ? new GramJs.channels.ReadMessageContents({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n id: messageIds,\n })\n : new GramJs.messages.ReadMessageContents({\n id: messageIds,\n }),\n );\n\n onUpdate({\n ...(isChannel ? {\n '@type': 'updateChannelMessages',\n channelId: chat.id,\n } : {\n '@type': 'updateCommonBoxMessages',\n }),\n ids: messageIds,\n messageUpdate: {\n hasUnreadMention: false,\n isMediaUnread: false,\n },\n });\n}\n\nexport async function requestThreadInfoUpdate({\n chat, threadId,\n}: {\n chat: ApiChat; threadId: number;\n}) {\n const [topMessageResult, repliesResult] = await Promise.all([\n invokeRequest(new GramJs.messages.GetDiscussionMessage({\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: threadId,\n })),\n invokeRequest(new GramJs.messages.GetReplies({\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: threadId,\n offsetId: 1,\n addOffset: -1,\n limit: 1,\n })),\n ]);\n\n if (!topMessageResult || !topMessageResult.messages.length) {\n return;\n }\n\n const discussionChatId = resolveMessageApiChatId(topMessageResult.messages[0]);\n if (!discussionChatId) {\n return;\n }\n\n onUpdate({\n '@type': 'updateThreadInfo',\n chatId: discussionChatId,\n threadId,\n threadInfo: {\n topMessageId: topMessageResult.messages[topMessageResult.messages.length - 1].id,\n lastReadInboxMessageId: topMessageResult.readInboxMaxId,\n messagesCount: (repliesResult instanceof GramJs.messages.ChannelMessages) ? repliesResult.count : undefined,\n },\n firstMessageId: repliesResult && 'messages' in repliesResult && repliesResult.messages.length\n ? repliesResult.messages[0].id\n : undefined,\n });\n\n const chats = topMessageResult.chats.map((c) => buildApiChatFromPreview(c)).filter<ApiChat>(Boolean as any);\n chats.forEach((newChat) => {\n onUpdate({\n '@type': 'updateChat',\n id: newChat.id,\n chat: newChat,\n noTopChatsRequest: true,\n });\n });\n}\n\nexport async function searchMessagesLocal({\n chatOrUser, type, query, topMessageId, minDate, maxDate, ...pagination\n}: {\n chatOrUser: ApiChat | ApiUser;\n type?: ApiMessageSearchType | ApiGlobalMessageSearchType;\n query?: string;\n topMessageId?: number;\n offsetId?: number;\n addOffset?: number;\n limit: number;\n minDate?: number;\n maxDate?: number;\n}) {\n let filter;\n switch (type) {\n case 'media':\n filter = new GramJs.InputMessagesFilterPhotoVideo();\n break;\n case 'documents':\n filter = new GramJs.InputMessagesFilterDocument();\n break;\n case 'links':\n filter = new GramJs.InputMessagesFilterUrl();\n break;\n case 'audio':\n filter = new GramJs.InputMessagesFilterMusic();\n break;\n case 'voice':\n filter = new GramJs.InputMessagesFilterVoice();\n break;\n case 'profilePhoto':\n filter = new GramJs.InputMessagesFilterChatPhotos();\n break;\n case 'text':\n default: {\n filter = new GramJs.InputMessagesFilterEmpty();\n }\n }\n\n const result = await invokeRequest(new GramJs.messages.Search({\n peer: buildInputPeer(chatOrUser.id, chatOrUser.accessHash),\n filter,\n q: query || '',\n topMsgId: topMessageId,\n minDate,\n maxDate,\n ...pagination,\n }));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiMessage).filter<ApiMessage>(Boolean as any);\n const users = result.users.map(buildApiUser).filter<ApiUser>(Boolean as any);\n\n let totalCount = messages.length;\n let nextOffsetId: number | undefined;\n if (result instanceof GramJs.messages.MessagesSlice || result instanceof GramJs.messages.ChannelMessages) {\n totalCount = result.count;\n\n if (messages.length) {\n nextOffsetId = messages[messages.length - 1].id;\n }\n }\n\n return {\n messages,\n users,\n totalCount,\n nextOffsetId,\n };\n}\n\nexport async function searchMessagesGlobal({\n query, offsetRate = 0, limit, type = 'text', minDate, maxDate,\n}: {\n query: string;\n offsetRate?: number;\n limit: number;\n type?: ApiGlobalMessageSearchType;\n minDate?: number;\n maxDate?: number;\n}) {\n let filter;\n switch (type) {\n case 'media':\n filter = new GramJs.InputMessagesFilterPhotoVideo();\n break;\n case 'documents':\n filter = new GramJs.InputMessagesFilterDocument();\n break;\n case 'links':\n filter = new GramJs.InputMessagesFilterUrl();\n break;\n case 'audio':\n filter = new GramJs.InputMessagesFilterMusic();\n break;\n case 'voice':\n filter = new GramJs.InputMessagesFilterVoice();\n break;\n case 'text':\n default: {\n if (!query && !(maxDate && minDate)) {\n return undefined;\n }\n\n filter = new GramJs.InputMessagesFilterEmpty();\n }\n }\n\n const result = await invokeRequest(new GramJs.messages.SearchGlobal({\n q: query,\n offsetRate,\n offsetPeer: new GramJs.InputPeerEmpty(),\n limit,\n filter,\n folderId: ALL_FOLDER_ID,\n minDate,\n maxDate,\n }));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb({\n chats: result.chats,\n users: result.users,\n messages: result.messages,\n } as GramJs.messages.Messages);\n\n const chats = result.chats.map((user) => buildApiChatFromPreview(user)).filter<ApiChat>(Boolean as any);\n const users = result.users.map(buildApiUser).filter<ApiUser>(Boolean as any);\n const messages = result.messages.map(buildApiMessage).filter<ApiMessage>(Boolean as any);\n\n let totalCount = messages.length;\n let nextRate: number | undefined;\n if (result instanceof GramJs.messages.MessagesSlice || result instanceof GramJs.messages.ChannelMessages) {\n totalCount = result.count;\n\n if (messages.length) {\n nextRate = messages[messages.length - 1].id;\n }\n }\n\n return {\n messages,\n users,\n chats,\n totalCount,\n nextRate: 'nextRate' in result && result.nextRate ? result.nextRate : nextRate,\n };\n}\n\nexport async function fetchWebPagePreview({ message }: { message: string }) {\n const preview = await invokeRequest(new GramJs.messages.GetWebPagePreview({\n message,\n }));\n\n return preview && buildWebPage(preview);\n}\n\nexport async function sendPollVote({\n chat, messageId, options,\n}: {\n chat: ApiChat;\n messageId: number;\n options: string[];\n}) {\n const { id, accessHash } = chat;\n\n await invokeRequest(new GramJs.messages.SendVote({\n peer: buildInputPeer(id, accessHash),\n msgId: messageId,\n options: options.map((option) => Buffer.from(option)),\n }), true);\n}\n\nexport async function loadPollOptionResults({\n chat, messageId, option, offset, limit, shouldResetVoters,\n}: {\n chat: ApiChat;\n messageId: number;\n option?: string;\n offset?: string;\n limit?: number;\n shouldResetVoters?: boolean;\n}) {\n const { id, accessHash } = chat;\n\n const result = await invokeRequest(new GramJs.messages.GetPollVotes({\n peer: buildInputPeer(id, accessHash),\n id: messageId,\n ...(option && { option: Buffer.from(option) }),\n ...(offset && { offset }),\n ...(limit && { limit }),\n }));\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb({\n chats: [] as GramJs.TypeChat[],\n users: result.users,\n messages: [] as GramJs.Message[],\n } as GramJs.messages.Messages);\n\n const users = result.users.map(buildApiUser).filter<ApiUser>(Boolean as any);\n const votes = result.votes.map((vote) => ({\n userId: vote.userId,\n date: vote.date,\n }));\n\n return {\n count: result.count,\n votes,\n users,\n nextOffset: result.nextOffset,\n shouldResetVoters,\n };\n}\n\nexport async function forwardMessages({\n fromChat,\n toChat,\n messages,\n serverTimeOffset,\n}: {\n fromChat: ApiChat;\n toChat: ApiChat;\n messages: ApiMessage[];\n serverTimeOffset: number;\n}) {\n const messageIds = messages.map(({ id }) => id);\n const randomIds = messages.map(generateRandomBigInt);\n\n messages.forEach((message, index) => {\n const localMessage = buildForwardedMessage(toChat, message, serverTimeOffset);\n localDb.localMessages[String(randomIds[index])] = localMessage;\n\n onUpdate({\n '@type': 'newMessage',\n id: localMessage.id,\n chatId: toChat.id,\n message: localMessage,\n });\n });\n\n await invokeRequest(new GramJs.messages.ForwardMessages({\n fromPeer: buildInputPeer(fromChat.id, fromChat.accessHash),\n toPeer: buildInputPeer(toChat.id, toChat.accessHash),\n randomId: randomIds,\n id: messageIds,\n }), true);\n}\n\nexport async function findFirstMessageIdAfterDate({\n chat,\n timestamp,\n}: {\n chat: ApiChat;\n timestamp: number;\n}) {\n const result = await invokeRequest(new GramJs.messages.GetHistory({\n peer: buildInputPeer(chat.id, chat.accessHash),\n offsetDate: timestamp,\n addOffset: -1,\n limit: 1,\n }));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages || !result.messages.length\n ) {\n return undefined;\n }\n\n return result.messages[0].id;\n}\n\nexport async function fetchScheduledHistory({ chat, hash = 0 }: { chat: ApiChat; hash?: number }) {\n const { id, accessHash } = chat;\n\n const result = await invokeRequest(new GramJs.messages.GetScheduledHistory({\n peer: buildInputPeer(id, accessHash),\n hash,\n }));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiMessage).filter<ApiMessage>(Boolean as any);\n\n return {\n messages,\n hash: calculateResultHash(messages.map((message) => message.id)),\n };\n}\n\nexport async function sendScheduledMessages({ chat, ids }: { chat: ApiChat; ids: number[] }) {\n const { id, accessHash } = chat;\n\n await invokeRequest(new GramJs.messages.SendScheduledMessages({\n peer: buildInputPeer(id, accessHash),\n id: ids,\n }), true);\n}\n\nfunction updateLocalDb(result: (\n GramJs.messages.MessagesSlice | GramJs.messages.Messages | GramJs.messages.ChannelMessages |\n GramJs.messages.DiscussionMessage\n)) {\n result.users.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[user.id] = user;\n }\n });\n\n result.chats.forEach((chat) => {\n if (chat instanceof GramJs.Chat || chat instanceof GramJs.Channel) {\n localDb.chats[chat.id] = chat;\n }\n });\n\n result.messages.forEach((message) => {\n if ((message instanceof GramJs.Message && isMessageWithMedia(message))\n || (message instanceof GramJs.MessageService && isServiceMessageWithMedia(message))\n ) {\n addMessageToLocalDb(message);\n }\n });\n}\n\nexport async function fetchPinnedMessages({ chat }: { chat: ApiChat }) {\n const result = await invokeRequest(new GramJs.messages.Search(\n {\n peer: buildInputPeer(chat.id, chat.accessHash),\n filter: new GramJs.InputMessagesFilterPinned(),\n q: '',\n limit: PINNED_MESSAGES_LIMIT,\n },\n ));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiMessage).filter<ApiMessage>(Boolean as any);\n const users = result.users.map(buildApiUser).filter<ApiUser>(Boolean as any);\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter<ApiChat>(Boolean as any);\n\n return {\n messages,\n users,\n chats,\n };\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport {\n OnApiUpdate, ApiUser, ApiChat, ApiPhoto,\n} from '../../types';\n\nimport { PROFILE_PHOTOS_LIMIT } from '../../../config';\nimport { invokeRequest } from './client';\nimport { searchMessagesLocal } from './messages';\nimport {\n buildInputEntity,\n calculateResultHash,\n buildInputPeer,\n buildInputContact,\n} from '../gramjsBuilders';\nimport { buildApiUser, buildApiUserFromFull } from '../apiBuilders/users';\nimport { buildApiChatFromPreview } from '../apiBuilders/chats';\nimport { buildApiPhoto } from '../apiBuilders/common';\nimport localDb from '../localDb';\nimport { addPhotoToLocalDb } from '../helpers';\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function fetchFullUser({\n id,\n accessHash,\n}: {\n id: number;\n accessHash?: string;\n}) {\n const input = buildInputEntity(id, accessHash);\n if (!(input instanceof GramJs.InputUser)) {\n return;\n }\n\n const fullInfo = await invokeRequest(new GramJs.users.GetFullUser({ id: input }));\n\n if (!fullInfo) {\n return;\n }\n\n const userWithFullInfo = buildApiUserFromFull(fullInfo);\n\n onUpdate({\n '@type': 'updateUser',\n id,\n user: {\n fullInfo: userWithFullInfo.fullInfo,\n },\n });\n}\n\nexport async function fetchNearestCountry() {\n const dcInfo = await invokeRequest(new GramJs.help.GetNearestDc());\n\n return dcInfo ? dcInfo.country : undefined;\n}\n\nexport async function fetchTopUsers({ hash = 0 }: { hash?: number }) {\n const topPeers = await invokeRequest(new GramJs.contacts.GetTopPeers({\n hash,\n correspondents: true,\n }));\n if (!(topPeers instanceof GramJs.contacts.TopPeers)) {\n return undefined;\n }\n\n const users = topPeers.users.map(buildApiUser).filter((user) => !!user && !user.isSelf) as ApiUser[];\n const ids = users.map(({ id }) => id);\n\n return {\n hash: calculateResultHash(ids),\n ids,\n users,\n };\n}\n\nexport async function fetchContactList({ hash = 0 }: { hash?: number }) {\n const result = await invokeRequest(new GramJs.contacts.GetContacts({ hash }));\n if (!result || result instanceof GramJs.contacts.ContactsNotModified) {\n return undefined;\n }\n\n result.users.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[user.id] = user;\n }\n });\n\n return {\n hash: calculateResultHash([\n result.savedCount,\n ...result.contacts.map(({ userId }) => userId),\n ]),\n users: result.users.map(buildApiUser).filter<ApiUser>(Boolean as any),\n chats: result.users.map((user) => buildApiChatFromPreview(user)).filter<ApiChat>(Boolean as any),\n };\n}\n\nexport async function fetchUsers({ users }: { users: ApiUser[] }) {\n const result = await invokeRequest(new GramJs.users.GetUsers({\n id: users.map(({ id, accessHash }) => buildInputPeer(id, accessHash)),\n }));\n if (!result || !result.length) {\n return undefined;\n }\n\n result.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[user.id] = user;\n }\n });\n\n return result.map(buildApiUser).filter<ApiUser>(Boolean as any);\n}\n\nexport function updateContact({\n phone,\n firstName,\n lastName,\n}: {\n phone?: string;\n firstName?: string;\n lastName?: string;\n}) {\n return invokeRequest(new GramJs.contacts.ImportContacts({\n contacts: [buildInputContact({\n phone: phone || '',\n firstName: firstName || '',\n lastName: lastName || '',\n })],\n }));\n}\n\nexport async function deleteUser({\n id,\n accessHash,\n}: {\n id: number;\n accessHash?: string;\n}) {\n const input = buildInputEntity(id, accessHash);\n if (!(input instanceof GramJs.InputUser)) {\n return;\n }\n\n const result = await invokeRequest(new GramJs.contacts.DeleteContacts({ id: [input] }));\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'deleteUser',\n id,\n });\n}\n\nexport async function fetchProfilePhotos(user?: ApiUser, chat?: ApiChat) {\n if (user) {\n const { id, accessHash } = user;\n\n const result = await invokeRequest(new GramJs.photos.GetUserPhotos({\n userId: buildInputEntity(id, accessHash) as GramJs.InputUser,\n limit: PROFILE_PHOTOS_LIMIT,\n offset: 0,\n maxId: BigInt('0'),\n }));\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return {\n photos: result.photos\n .filter((photo): photo is GramJs.Photo => photo instanceof GramJs.Photo)\n .map(buildApiPhoto),\n };\n }\n\n const result = await searchMessagesLocal({\n chatOrUser: chat!,\n type: 'profilePhoto',\n limit: PROFILE_PHOTOS_LIMIT,\n });\n\n if (!result) {\n return undefined;\n }\n\n const { messages, users } = result;\n\n return {\n photos: messages.map((message) => message.content.action!.photo).filter<ApiPhoto>(Boolean as any),\n users,\n };\n}\n\nfunction updateLocalDb(result: (GramJs.photos.Photos | GramJs.photos.PhotosSlice)) {\n result.photos.forEach(addPhotoToLocalDb);\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport { ApiSticker, ApiVideo, OnApiUpdate } from '../../types';\n\nimport { invokeRequest } from './client';\nimport { buildStickerFromDocument, buildStickerSet, buildStickerSetCovered } from '../apiBuilders/symbols';\nimport { buildInputStickerSet, buildInputDocument, buildInputStickerSetShortName } from '../gramjsBuilders';\nimport { buildVideoFromDocument } from '../apiBuilders/messages';\nimport { RECENT_STICKERS_LIMIT } from '../../../config';\n\nimport localDb from '../localDb';\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function fetchStickerSets({ hash }: { hash: number }) {\n const allStickers = await invokeRequest(new GramJs.messages.GetAllStickers({ hash }));\n\n if (!allStickers || allStickers instanceof GramJs.messages.AllStickersNotModified) {\n return undefined;\n }\n\n allStickers.sets.forEach((stickerSet) => {\n if (stickerSet.thumbs && stickerSet.thumbs.length) {\n localDb.stickerSets[String(stickerSet.id)] = stickerSet;\n }\n });\n\n return {\n hash: allStickers.hash,\n sets: allStickers.sets.map(buildStickerSet),\n };\n}\n\nexport async function fetchRecentStickers({ hash }: { hash: number }) {\n const result = await invokeRequest(new GramJs.messages.GetRecentStickers({ hash }));\n\n if (!result || result instanceof GramJs.messages.RecentStickersNotModified) {\n return undefined;\n }\n\n return {\n hash: result.hash,\n stickers: processStickerResult(result.stickers.slice(0, RECENT_STICKERS_LIMIT)),\n };\n}\n\nexport async function fetchFavoriteStickers({ hash }: { hash: number }) {\n const result = await invokeRequest(new GramJs.messages.GetFavedStickers({ hash }));\n\n if (!result || result instanceof GramJs.messages.FavedStickersNotModified) {\n return undefined;\n }\n\n return {\n hash: result.hash,\n stickers: processStickerResult(result.stickers),\n };\n}\n\nexport async function fetchFeaturedStickers({ hash }: { hash: number }) {\n const result = await invokeRequest(new GramJs.messages.GetFeaturedStickers({ hash }));\n\n if (!result || result instanceof GramJs.messages.FeaturedStickersNotModified) {\n return undefined;\n }\n\n return {\n hash: result.hash,\n sets: result.sets.map(buildStickerSetCovered),\n };\n}\n\nexport async function faveSticker({\n sticker,\n unfave,\n}: {\n sticker: ApiSticker;\n unfave?: boolean;\n}) {\n const request = new GramJs.messages.FaveSticker({\n id: buildInputDocument(sticker),\n unfave,\n });\n\n const result = await invokeRequest(request);\n if (result) {\n onUpdate({\n '@type': 'updateFavoriteStickers',\n });\n }\n}\n\nexport async function fetchStickers({ stickerSetShortName, stickerSetId, accessHash }:\n{ stickerSetShortName?: string; stickerSetId?: string; accessHash: string }) {\n const result = await invokeRequest(new GramJs.messages.GetStickerSet({\n stickerset: stickerSetId\n ? buildInputStickerSet(stickerSetId, accessHash)\n : buildInputStickerSetShortName(stickerSetShortName!),\n }));\n\n if (!result) {\n return undefined;\n }\n\n return {\n set: buildStickerSet(result.set),\n stickers: processStickerResult(result.documents),\n packs: processStickerPackResult(result.packs),\n };\n}\n\nexport async function fetchAnimatedEmojis() {\n const result = await invokeRequest(new GramJs.messages.GetStickerSet({\n stickerset: new GramJs.InputStickerSetAnimatedEmoji(),\n }));\n\n if (!result) {\n return undefined;\n }\n\n return {\n set: buildStickerSet(result.set),\n stickers: processStickerResult(result.documents),\n };\n}\n\nexport async function searchStickers({ query, hash }: { query: string; hash: number }) {\n const result = await invokeRequest(new GramJs.messages.SearchStickerSets({\n q: query,\n hash,\n }));\n\n if (!result || result instanceof GramJs.messages.FoundStickerSetsNotModified) {\n return undefined;\n }\n\n return {\n hash: result.hash,\n sets: result.sets.map(buildStickerSetCovered),\n };\n}\n\nexport async function fetchSavedGifs({ hash }: { hash: number }) {\n const result = await invokeRequest(new GramJs.messages.GetSavedGifs({ hash }));\n\n if (!result || result instanceof GramJs.messages.SavedGifsNotModified) {\n return undefined;\n }\n\n return {\n hash: result.hash,\n gifs: processGifResult(result.gifs),\n };\n}\n\nexport async function installStickerSet({ stickerSetId, accessHash }: { stickerSetId: string; accessHash: string }) {\n const result = await invokeRequest(new GramJs.messages.InstallStickerSet({\n stickerset: buildInputStickerSet(stickerSetId, accessHash),\n }));\n\n if (result) {\n onUpdate({\n '@type': 'updateStickerSet',\n id: stickerSetId,\n stickerSet: { installedDate: Date.now() },\n });\n }\n}\n\nexport async function uninstallStickerSet({ stickerSetId, accessHash }: { stickerSetId: string; accessHash: string }) {\n const result = await invokeRequest(new GramJs.messages.UninstallStickerSet({\n stickerset: buildInputStickerSet(stickerSetId, accessHash),\n }));\n\n if (result) {\n onUpdate({\n '@type': 'updateStickerSet',\n id: stickerSetId,\n stickerSet: { installedDate: undefined },\n });\n }\n}\n\nlet inputGifBot: GramJs.InputUser | undefined;\n\nexport async function searchGifs({ query, offset = '' }: { query: string; offset?: string }) {\n if (!inputGifBot) {\n const config = await invokeRequest(new GramJs.help.GetConfig());\n if (!config) {\n return undefined;\n }\n\n const resolvedPeer = await invokeRequest(new GramJs.contacts.ResolveUsername({\n username: config.gifSearchUsername,\n }));\n if (!resolvedPeer || !(resolvedPeer.users[0] instanceof GramJs.User)) {\n return undefined;\n }\n\n inputGifBot = new GramJs.InputUser({\n userId: (resolvedPeer.peer as GramJs.PeerUser).userId,\n accessHash: resolvedPeer.users[0].accessHash!,\n });\n }\n\n const result = await invokeRequest(new GramJs.messages.GetInlineBotResults({\n bot: inputGifBot,\n peer: new GramJs.InputPeerEmpty(),\n query,\n offset,\n }));\n if (!result) {\n return undefined;\n }\n\n const documents = result.results\n .map((foundGif) => {\n if (foundGif instanceof GramJs.BotInlineMediaResult) {\n return foundGif.document;\n }\n\n return undefined;\n })\n .filter<GramJs.TypeDocument>(Boolean as any);\n\n return {\n nextOffset: result.nextOffset,\n gifs: processGifResult(documents),\n };\n}\n\nexport async function fetchStickersForEmoji({\n emoji, hash = 0,\n}: { emoji: string; hash?: number }) {\n const result = await invokeRequest(new GramJs.messages.GetStickers({\n emoticon: emoji,\n hash,\n }));\n\n if (!result || result instanceof GramJs.messages.StickersNotModified) {\n return undefined;\n }\n\n return {\n stickers: processStickerResult(result.stickers),\n hash: result.hash,\n };\n}\n\nexport async function fetchEmojiKeywords({ language, fromVersion }: {\n language: string;\n fromVersion?: number;\n}) {\n const result = await invokeRequest(new GramJs.messages.GetEmojiKeywordsDifference({\n langCode: language,\n fromVersion,\n }));\n\n if (!result) {\n return undefined;\n }\n\n return {\n language: result.langCode,\n version: result.version,\n keywords: result.keywords.reduce((acc, emojiKeyword) => {\n acc[emojiKeyword.keyword] = emojiKeyword.emoticons;\n\n return acc;\n }, {} as Record<string, string[]>),\n };\n}\n\nfunction processStickerResult(stickers: GramJs.TypeDocument[]) {\n return stickers\n .map((document) => {\n if (document instanceof GramJs.Document) {\n const sticker = buildStickerFromDocument(document);\n if (sticker) {\n localDb.documents[String(document.id)] = document;\n\n return sticker;\n }\n }\n\n return undefined;\n })\n .filter<ApiSticker>(Boolean as any);\n}\n\nfunction processStickerPackResult(packs: GramJs.StickerPack[]) {\n return packs.reduce((acc, { emoticon, documents }) => {\n acc[emoticon] = documents.map((documentId) => buildStickerFromDocument(\n localDb.documents[String(documentId)],\n )).filter<ApiSticker>(Boolean as any);\n return acc;\n }, {} as Record<string, ApiSticker[]>);\n}\n\nfunction processGifResult(gifs: GramJs.TypeDocument[]) {\n return gifs\n .map((document) => {\n if (document instanceof GramJs.Document) {\n const gif = buildVideoFromDocument(document);\n if (gif) {\n localDb.documents[String(document.id)] = document;\n\n return gif;\n }\n }\n\n return undefined;\n })\n .filter<ApiVideo>(Boolean as any);\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\n\nimport { invokeRequest } from './client';\nimport { buildInputEntity, buildInputPeer } from '../gramjsBuilders';\nimport { ApiChat, OnApiUpdate } from '../../types';\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function checkChatUsername(\n { username }: { username: string },\n) {\n try {\n const result = await invokeRequest(new GramJs.channels.CheckUsername({\n channel: new GramJs.InputChannelEmpty(),\n username,\n }), undefined, true);\n\n return result!;\n } catch (err) {\n return false;\n }\n}\n\nexport async function setChatUsername(\n { chat, username }: { chat: ApiChat; username: string },\n) {\n const result = await invokeRequest(new GramJs.channels.UpdateUsername({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n username,\n }));\n\n if (result) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat: { username },\n });\n }\n}\n\nexport async function updatePrivateLink(\n { chat }: { chat: ApiChat },\n) {\n const result = await invokeRequest(new GramJs.messages.ExportChatInvite({\n peer: buildInputPeer(chat.id, chat.accessHash),\n }));\n\n if (!result || !(result instanceof GramJs.ChatInviteExported)) {\n return;\n }\n\n onUpdate({\n '@type': 'updateChatFullInfo',\n id: chat.id,\n fullInfo: {\n inviteLink: result.link,\n },\n });\n}\n","import { Api as GramJs, errors } from '../../../lib/gramjs';\n\nimport { OnApiUpdate } from '../../types';\n\nimport { DEBUG } from '../../../config';\nimport { invokeRequest, updateTwoFaSettings } from './client';\n\nconst ApiErrors: { [k: string]: string } = {\n EMAIL_UNCONFIRMED: 'Email unconfirmed',\n EMAIL_HASH_EXPIRED: 'Email hash expired',\n NEW_SALT_INVALID: 'The new salt is invalid',\n NEW_SETTINGS_INVALID: 'The new password settings are invalid',\n CODE_INVALID: 'Invalid Code',\n PASSWORD_HASH_INVALID: 'Invalid Password',\n};\n\nconst emailCodeController: {\n resolve?: Function;\n reject?: Function;\n} = {};\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function getPasswordInfo() {\n const result = await invokeRequest(new GramJs.account.GetPassword());\n if (!result) {\n return undefined;\n }\n\n const { hint, hasPassword } = result;\n\n return { hint, hasPassword };\n}\n\nfunction onRequestEmailCode(length: number) {\n onUpdate({\n '@type': 'updateTwoFaStateWaitCode',\n length,\n });\n\n return new Promise<string>((resolve, reject) => {\n emailCodeController.resolve = resolve;\n emailCodeController.reject = reject;\n });\n}\n\nexport async function checkPassword(currentPassword: string) {\n try {\n await updateTwoFaSettings({ isCheckPassword: true, currentPassword });\n\n return true;\n } catch (err) {\n onError(err);\n\n return false;\n }\n}\n\nexport async function clearPassword(currentPassword: string) {\n try {\n await updateTwoFaSettings({ currentPassword });\n\n return true;\n } catch (err) {\n onError(err);\n\n return false;\n }\n}\n\nexport async function updatePassword(currentPassword: string, password: string, hint?: string, email?: string) {\n try {\n await updateTwoFaSettings({\n currentPassword,\n newPassword: password,\n hint,\n email,\n emailCodeCallback: onRequestEmailCode,\n onEmailCodeError: onError,\n });\n\n return true;\n } catch (err) {\n onError(err);\n\n return false;\n }\n}\n\nexport async function updateRecoveryEmail(currentPassword: string, email: string) {\n try {\n await updateTwoFaSettings({\n currentPassword,\n newPassword: currentPassword,\n email,\n emailCodeCallback: onRequestEmailCode,\n onEmailCodeError: onError,\n });\n\n return true;\n } catch (err) {\n onError(err);\n\n return false;\n }\n}\n\nexport function provideRecoveryEmailCode(code: string) {\n emailCodeController.resolve!(code);\n}\n\nfunction onError(err: Error) {\n let message: string;\n\n if (err instanceof errors.FloodWaitError) {\n const hours = Math.ceil(Number(err.seconds) / 60 / 60);\n message = `Too many attempts. Try again in ${hours > 1 ? `${hours} hours` : 'an hour'}`;\n } else {\n message = ApiErrors[err.message];\n }\n\n if (!message) {\n message = 'Unexpected Error';\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n }\n\n onUpdate({\n '@type': 'updateTwoFaError',\n message,\n });\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\n\nimport {\n ApiChat, ApiLangString, ApiLanguage, ApiNotifyException, ApiUser, ApiWallpaper,\n} from '../../types';\nimport { ApiPrivacyKey, IInputPrivacyRules } from '../../../types';\n\nimport { BLOCKED_LIST_LIMIT, DEFAULT_LANG_PACK, LANG_PACKS } from '../../../config';\nimport {\n buildApiWallpaper, buildApiSession, buildPrivacyRules, buildApiNotifyException,\n} from '../apiBuilders/misc';\n\nimport { buildApiUser } from '../apiBuilders/users';\nimport { buildApiChatFromPreview, getApiChatIdFromMtpPeer } from '../apiBuilders/chats';\nimport { buildInputPrivacyKey, buildInputPeer } from '../gramjsBuilders';\nimport { invokeRequest, uploadFile, getClient } from './client';\nimport { omitVirtualClassFields } from '../apiBuilders/helpers';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport localDb from '../localDb';\nimport { getServerTime } from '../../../util/serverTime';\n\nconst MAX_INT_32 = 2 ** 31 - 1;\nconst BETA_LANG_CODES = ['ar', 'fa', 'id', 'ko', 'uz'];\n\nexport function updateProfile({\n firstName,\n lastName,\n about,\n}: {\n firstName?: string;\n lastName?: string;\n about?: string;\n}) {\n return invokeRequest(new GramJs.account.UpdateProfile({\n firstName: firstName || '',\n lastName: lastName || '',\n about: about || '',\n }));\n}\n\nexport function checkUsername(username: string) {\n return invokeRequest(new GramJs.account.CheckUsername({ username }));\n}\n\nexport function updateUsername(username: string) {\n return invokeRequest(new GramJs.account.UpdateUsername({ username }));\n}\n\nexport async function updateProfilePhoto(file: File) {\n const inputFile = await uploadFile(file);\n return invokeRequest(new GramJs.photos.UploadProfilePhoto({\n file: inputFile,\n }));\n}\n\nexport async function uploadProfilePhoto(file: File) {\n const inputFile = await uploadFile(file);\n await invokeRequest(new GramJs.photos.UploadProfilePhoto({\n file: inputFile,\n }));\n}\n\nexport async function fetchWallpapers(hash: number) {\n const result = await invokeRequest(new GramJs.account.GetWallPapers({ hash }));\n\n if (!result || result instanceof GramJs.account.WallPapersNotModified) {\n return undefined;\n }\n\n const filteredWallpapers = result.wallpapers.filter((wallpaper) => {\n if (\n !(wallpaper instanceof GramJs.WallPaper)\n || !(wallpaper.document instanceof GramJs.Document)\n ) {\n return false;\n }\n\n return !wallpaper.pattern && wallpaper.document.mimeType !== 'application/x-tgwallpattern';\n }) as GramJs.WallPaper[];\n\n filteredWallpapers.forEach((wallpaper) => {\n localDb.documents[String(wallpaper.document.id)] = wallpaper.document as GramJs.Document;\n });\n\n return {\n hash: result.hash,\n wallpapers: filteredWallpapers.map(buildApiWallpaper).filter<ApiWallpaper>(Boolean as any),\n };\n}\n\nexport async function uploadWallpaper(file: File) {\n const inputFile = await uploadFile(file);\n\n const result = await invokeRequest(new GramJs.account.UploadWallPaper({\n file: inputFile,\n mimeType: file.type,\n settings: new GramJs.WallPaperSettings(),\n }));\n\n if (!result || !(result instanceof GramJs.WallPaper)) {\n return undefined;\n }\n\n const wallpaper = buildApiWallpaper(result);\n if (!wallpaper) {\n return undefined;\n }\n\n localDb.documents[String(result.document.id)] = result.document as GramJs.Document;\n\n return { wallpaper };\n}\n\nexport async function fetchBlockedContacts() {\n const result = await invokeRequest(new GramJs.contacts.GetBlocked({\n limit: BLOCKED_LIST_LIMIT,\n }));\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return {\n users: result.users.map(buildApiUser).filter<ApiUser>(Boolean as any),\n chats: result.chats.map((chat) => buildApiChatFromPreview(chat, undefined, true)).filter<ApiChat>(Boolean as any),\n blockedIds: result.blocked.map((blocked) => getApiChatIdFromMtpPeer(blocked.peerId)),\n totalCount: result instanceof GramJs.contacts.BlockedSlice ? result.count : result.blocked.length,\n };\n}\n\nexport function blockContact(chatOrUserId: number, accessHash?: string) {\n return invokeRequest(new GramJs.contacts.Block({\n id: buildInputPeer(chatOrUserId, accessHash),\n }));\n}\n\nexport function unblockContact(chatOrUserId: number, accessHash?: string) {\n return invokeRequest(new GramJs.contacts.Unblock({\n id: buildInputPeer(chatOrUserId, accessHash),\n }));\n}\n\nexport async function fetchAuthorizations() {\n const result = await invokeRequest(new GramJs.account.GetAuthorizations());\n if (!result) {\n return undefined;\n }\n\n return result.authorizations.map(buildApiSession);\n}\n\nexport function terminateAuthorization(hash: string) {\n return invokeRequest(new GramJs.account.ResetAuthorization({ hash: BigInt(hash) }));\n}\n\nexport function terminateAllAuthorizations() {\n return invokeRequest(new GramJs.auth.ResetAuthorizations());\n}\n\nexport async function fetchNotificationExceptions({\n serverTimeOffset,\n}: { serverTimeOffset: number }) {\n const result = await invokeRequest(new GramJs.account.GetNotifyExceptions({ compareSound: true }));\n\n if (!(result instanceof GramJs.Updates || result instanceof GramJs.UpdatesCombined)) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return result.updates.reduce((acc, update) => {\n if (!(update instanceof GramJs.UpdateNotifySettings && update.peer instanceof GramJs.NotifyPeer)) {\n return acc;\n }\n\n acc.push(buildApiNotifyException(update.notifySettings, update.peer.peer, serverTimeOffset));\n\n return acc;\n }, [] as ApiNotifyException[]);\n}\n\nexport async function fetchNotificationSettings({\n serverTimeOffset,\n}: { serverTimeOffset: number }) {\n const [\n isMutedContactSignUpNotification,\n privateContactNotificationsSettings,\n groupNotificationsSettings,\n broadcastNotificationsSettings,\n ] = await Promise.all([\n invokeRequest(new GramJs.account.GetContactSignUpNotification()),\n invokeRequest(new GramJs.account.GetNotifySettings({\n peer: new GramJs.InputNotifyUsers(),\n })),\n invokeRequest(new GramJs.account.GetNotifySettings({\n peer: new GramJs.InputNotifyChats(),\n })),\n invokeRequest(new GramJs.account.GetNotifySettings({\n peer: new GramJs.InputNotifyBroadcasts(),\n })),\n ]);\n\n if (!privateContactNotificationsSettings || !groupNotificationsSettings || !broadcastNotificationsSettings) {\n return false;\n }\n\n const {\n silent: privateSilent, muteUntil: privateMuteUntil, showPreviews: privateShowPreviews,\n } = privateContactNotificationsSettings;\n const {\n silent: groupSilent, muteUntil: groupMuteUntil, showPreviews: groupShowPreviews,\n } = groupNotificationsSettings;\n const {\n silent: broadcastSilent, muteUntil: broadcastMuteUntil, showPreviews: broadcastShowPreviews,\n } = broadcastNotificationsSettings;\n\n return {\n hasContactJoinedNotifications: !isMutedContactSignUpNotification,\n hasPrivateChatsNotifications: !(\n privateSilent\n || (typeof privateMuteUntil === 'number' && getServerTime(serverTimeOffset) < privateMuteUntil)\n ),\n hasPrivateChatsMessagePreview: privateShowPreviews,\n hasGroupNotifications: !(\n groupSilent || (typeof groupMuteUntil === 'number'\n && getServerTime(serverTimeOffset) < groupMuteUntil)\n ),\n hasGroupMessagePreview: groupShowPreviews,\n hasBroadcastNotifications: !(\n broadcastSilent || (typeof broadcastMuteUntil === 'number'\n && getServerTime(serverTimeOffset) < broadcastMuteUntil)\n ),\n hasBroadcastMessagePreview: broadcastShowPreviews,\n };\n}\n\nexport function updateContactSignUpNotification(isSilent: boolean) {\n return invokeRequest(new GramJs.account.SetContactSignUpNotification({ silent: isSilent }));\n}\n\nexport function updateNotificationSettings(peerType: 'contact' | 'group' | 'broadcast', {\n isSilent,\n shouldShowPreviews,\n}: {\n isSilent: boolean;\n shouldShowPreviews: boolean;\n}) {\n let peer: GramJs.TypeInputNotifyPeer;\n if (peerType === 'contact') {\n peer = new GramJs.InputNotifyUsers();\n } else if (peerType === 'group') {\n peer = new GramJs.InputNotifyChats();\n } else {\n peer = new GramJs.InputNotifyBroadcasts();\n }\n\n const settings = {\n showPreviews: shouldShowPreviews,\n silent: isSilent,\n muteUntil: isSilent ? MAX_INT_32 : 0,\n };\n\n return invokeRequest(new GramJs.account.UpdateNotifySettings({\n peer,\n settings: new GramJs.InputPeerNotifySettings(settings),\n }));\n}\n\nexport async function fetchLanguages(): Promise<ApiLanguage[] | undefined> {\n const result = await invokeRequest(new GramJs.langpack.GetLanguages({\n langPack: DEFAULT_LANG_PACK,\n }));\n if (!result) {\n return undefined;\n }\n\n return result.map(omitVirtualClassFields);\n}\n\nexport async function fetchLangPack({ sourceLangPacks, langCode }: {\n sourceLangPacks: typeof LANG_PACKS;\n langCode: string;\n}) {\n const results = await Promise.all(sourceLangPacks.map((langPack) => {\n return invokeRequest(new GramJs.langpack.GetLangPack({\n langPack,\n langCode: BETA_LANG_CODES.includes(langCode) ? `${langCode}-raw` : langCode,\n }));\n }));\n\n const collections = results\n .filter<GramJs.LangPackDifference>(Boolean as any)\n .map((result) => {\n return buildCollectionByKey(result.strings.map<ApiLangString>(omitVirtualClassFields), 'key');\n });\n\n if (!collections.length) {\n return undefined;\n }\n\n return { langPack: Object.assign({}, ...collections.reverse()) };\n}\n\nexport async function fetchLangStrings({ langPack, langCode, keys }: {\n langPack: string; langCode: string; keys: string[];\n}) {\n const result = await invokeRequest(new GramJs.langpack.GetStrings({\n langPack,\n langCode: BETA_LANG_CODES.includes(langCode) ? `${langCode}-raw` : langCode,\n keys,\n }));\n\n if (!result) {\n return undefined;\n }\n\n return result.map(omitVirtualClassFields);\n}\n\nexport async function fetchPrivacySettings(privacyKey: ApiPrivacyKey) {\n const key = buildInputPrivacyKey(privacyKey);\n const result = await invokeRequest(new GramJs.account.GetPrivacy({ key }));\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return buildPrivacyRules(result.rules);\n}\n\nexport function registerDevice(token: string) {\n const client = getClient();\n const secret = client.session.getAuthKey().getKey();\n return invokeRequest(new GramJs.account.RegisterDevice({\n tokenType: 10,\n secret,\n appSandbox: false,\n otherUids: [],\n token,\n }));\n}\n\nexport function unregisterDevice(token: string) {\n return invokeRequest(new GramJs.account.UnregisterDevice({\n tokenType: 10,\n otherUids: [],\n token,\n }));\n}\n\nexport async function setPrivacySettings(\n privacyKey: ApiPrivacyKey, rules: IInputPrivacyRules,\n) {\n const key = buildInputPrivacyKey(privacyKey);\n const privacyRules: GramJs.TypeInputPrivacyRule[] = [];\n\n if (rules.allowedUsers) {\n privacyRules.push(new GramJs.InputPrivacyValueAllowUsers({\n users: rules.allowedUsers.map(({ id, accessHash }) => buildInputPeer(id, accessHash)),\n }));\n }\n if (rules.allowedChats) {\n privacyRules.push(new GramJs.InputPrivacyValueAllowChatParticipants({\n chats: rules.allowedChats.map(({ id }) => -id),\n }));\n }\n if (rules.blockedUsers) {\n privacyRules.push(new GramJs.InputPrivacyValueDisallowUsers({\n users: rules.blockedUsers.map(({ id, accessHash }) => buildInputPeer(id, accessHash)),\n }));\n }\n if (rules.blockedChats) {\n privacyRules.push(new GramJs.InputPrivacyValueDisallowChatParticipants({\n chats: rules.blockedChats.map(({ id }) => -id),\n }));\n }\n switch (rules.visibility) {\n case 'everybody':\n privacyRules.push(new GramJs.InputPrivacyValueAllowAll());\n break;\n\n case 'contacts':\n privacyRules.push(new GramJs.InputPrivacyValueAllowContacts());\n break;\n\n case 'nonContacts':\n privacyRules.push(new GramJs.InputPrivacyValueDisallowContacts());\n break;\n\n case 'nobody':\n privacyRules.push(new GramJs.InputPrivacyValueDisallowAll());\n break;\n }\n\n const result = await invokeRequest(new GramJs.account.SetPrivacy({ key, rules: privacyRules }));\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return buildPrivacyRules(result.rules);\n}\n\nexport async function updateIsOnline(isOnline: boolean) {\n await invokeRequest(new GramJs.account.UpdateStatus({ offline: !isOnline }));\n}\n\nexport async function fetchContentSettings() {\n const result = await invokeRequest(new GramJs.account.GetContentSettings());\n if (!result) {\n return undefined;\n }\n\n return {\n isSensitiveEnabled: Boolean(result.sensitiveEnabled),\n canChangeSensitive: Boolean(result.sensitiveCanChange),\n };\n}\n\nexport function updateContentSettings(isEnabled: boolean) {\n return invokeRequest(new GramJs.account.SetContentSettings({\n sensitiveEnabled: isEnabled || undefined,\n }));\n}\n\nfunction updateLocalDb(\n result: (\n GramJs.account.PrivacyRules | GramJs.contacts.Blocked | GramJs.contacts.BlockedSlice |\n GramJs.Updates | GramJs.UpdatesCombined\n ),\n) {\n result.users.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[user.id] = user;\n }\n });\n\n result.chats.forEach((chat) => {\n if (chat instanceof GramJs.Chat || chat instanceof GramJs.Channel) {\n localDb.chats[chat.id] = chat;\n }\n });\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n ApiBotInlineMediaResult, ApiBotInlineResult, ApiBotInlineSwitchPm, ApiInlineResultType, ApiWebDocument,\n} from '../../types';\n\nimport { pick } from '../../../util/iteratees';\nimport { buildApiPhoto, buildApiThumbnailFromStripped } from './common';\nimport { buildVideoFromDocument } from './messages';\nimport { buildStickerFromDocument } from './symbols';\n\nexport function buildApiBotInlineResult(result: GramJs.BotInlineResult, queryId: string): ApiBotInlineResult {\n const {\n id, type, title, description, url, thumb,\n } = result;\n\n return {\n id,\n queryId,\n type: type as ApiInlineResultType,\n title,\n description,\n url,\n webThumbnail: buildApiWebDocument(thumb),\n };\n}\n\nexport function buildApiBotInlineMediaResult(\n result: GramJs.BotInlineMediaResult, queryId: string,\n): ApiBotInlineMediaResult {\n const {\n id, type, title, description, photo, document,\n } = result;\n\n return {\n id,\n queryId,\n type: type as ApiInlineResultType,\n title,\n description,\n ...(type === 'sticker' && document instanceof GramJs.Document && { sticker: buildStickerFromDocument(document) }),\n ...(photo instanceof GramJs.Photo && { photo: buildApiPhoto(photo) }),\n ...(type === 'gif' && document instanceof GramJs.Document && { gif: buildVideoFromDocument(document) }),\n ...(type === 'video' && document instanceof GramJs.Document && {\n thumbnail: buildApiThumbnailFromStripped(document.thumbs),\n }),\n };\n}\n\nexport function buildBotSwitchPm(switchPm?: GramJs.InlineBotSwitchPM) {\n return switchPm ? pick(switchPm, ['text', 'startParam']) as ApiBotInlineSwitchPm : undefined;\n}\n\nfunction buildApiWebDocument(document?: GramJs.TypeWebDocument): ApiWebDocument | undefined {\n return document ? pick(document, ['url', 'mimeType']) : undefined;\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\n\nimport { ApiChat, ApiUser } from '../../types';\n\nimport localDb from '../localDb';\nimport { invokeRequest } from './client';\nimport { buildInputPeer, calculateResultHash, generateRandomBigInt } from '../gramjsBuilders';\nimport { buildApiUser } from '../apiBuilders/users';\nimport { buildApiBotInlineMediaResult, buildApiBotInlineResult, buildBotSwitchPm } from '../apiBuilders/bots';\nimport { buildApiChatFromPreview } from '../apiBuilders/chats';\n\nexport function init() {\n}\n\nexport function answerCallbackButton(\n {\n chatId, accessHash, messageId, data,\n }: {\n chatId: number; accessHash?: string; messageId: number; data: string;\n },\n) {\n return invokeRequest(new GramJs.messages.GetBotCallbackAnswer({\n peer: buildInputPeer(chatId, accessHash),\n msgId: messageId,\n data: Buffer.from(data),\n }));\n}\n\nexport async function fetchTopInlineBots({ hash = 0 }: { hash?: number }) {\n const topPeers = await invokeRequest(new GramJs.contacts.GetTopPeers({\n hash,\n botsInline: true,\n }));\n\n if (!(topPeers instanceof GramJs.contacts.TopPeers)) {\n return undefined;\n }\n\n const users = topPeers.users.map(buildApiUser).filter<ApiUser>(Boolean as any);\n const ids = users.map(({ id }) => id);\n\n return {\n hash: calculateResultHash(ids),\n ids,\n users,\n };\n}\n\nexport async function fetchInlineBot({ username }: { username: string }) {\n const resolvedPeer = await invokeRequest(new GramJs.contacts.ResolveUsername({ username }));\n\n if (\n !resolvedPeer\n || !(\n resolvedPeer.users[0] instanceof GramJs.User\n && resolvedPeer.users[0].bot\n && resolvedPeer.users[0].botInlinePlaceholder\n )\n ) {\n return undefined;\n }\n\n addUserToLocalDb(resolvedPeer.users[0]);\n\n return {\n user: buildApiUser(resolvedPeer.users[0]),\n chat: buildApiChatFromPreview(resolvedPeer.users[0]),\n };\n}\n\nexport async function fetchInlineBotResults({\n bot, chat, query, offset = '',\n}: {\n bot: ApiUser; chat: ApiChat; query: string; offset?: string;\n}) {\n const result = await invokeRequest(new GramJs.messages.GetInlineBotResults({\n bot: buildInputPeer(bot.id, bot.accessHash),\n peer: buildInputPeer(chat.id, chat.accessHash),\n query,\n offset,\n }));\n\n if (!result) {\n return undefined;\n }\n\n result.users.map(addUserToLocalDb);\n\n return {\n isGallery: Boolean(result.gallery),\n help: bot.botPlaceholder,\n nextOffset: getInlineBotResultsNextOffset(bot.username, result.nextOffset),\n switchPm: buildBotSwitchPm(result.switchPm),\n users: result.users.map(buildApiUser).filter<ApiUser>(Boolean as any),\n results: processInlineBotResult(String(result.queryId), result.results),\n };\n}\n\nexport async function sendInlineBotResult({\n chat, resultId, queryId, replyingTo,\n}: {\n chat: ApiChat;\n resultId: string;\n queryId: string;\n replyingTo?: number;\n}) {\n const randomId = generateRandomBigInt();\n\n await invokeRequest(new GramJs.messages.SendInlineBotResult({\n clearDraft: true,\n randomId,\n queryId: BigInt(queryId),\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: resultId,\n ...(replyingTo && { replyToMsgId: replyingTo }),\n }), true);\n}\n\nexport async function startBot({\n bot, startParam,\n}: {\n bot: ApiUser;\n startParam?: string;\n}) {\n const randomId = generateRandomBigInt();\n\n await invokeRequest(new GramJs.messages.StartBot({\n bot: buildInputPeer(bot.id, bot.accessHash),\n peer: buildInputPeer(bot.id, bot.accessHash),\n randomId,\n startParam,\n }), true);\n}\n\nfunction processInlineBotResult(queryId: string, results: GramJs.TypeBotInlineResult[]) {\n return results.map((result) => {\n if (result instanceof GramJs.BotInlineMediaResult) {\n if (result.document instanceof GramJs.Document) {\n addDocumentToLocalDb(result.document);\n }\n\n if (result.photo instanceof GramJs.Photo) {\n addPhotoToLocalDb(result.photo);\n }\n\n return buildApiBotInlineMediaResult(result, queryId);\n }\n\n if (result.thumb) {\n addWebDocumentToLocalDb(result.thumb);\n }\n\n return buildApiBotInlineResult(result, queryId);\n });\n}\n\nfunction getInlineBotResultsNextOffset(username: string, nextOffset?: string) {\n return username === 'gif' && nextOffset === '0' ? '' : nextOffset;\n}\n\nfunction addUserToLocalDb(user: GramJs.User) {\n localDb.users[user.id] = user;\n}\n\nfunction addDocumentToLocalDb(document: GramJs.Document) {\n localDb.documents[String(document.id)] = document;\n}\n\nfunction addPhotoToLocalDb(photo: GramJs.Photo) {\n localDb.photos[String(photo.id)] = photo;\n}\n\nfunction addWebDocumentToLocalDb(webDocument: GramJs.TypeWebDocument) {\n localDb.webDocuments[webDocument.url] = webDocument;\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\n\nexport function buildShippingOptions(shippingOptions: GramJs.ShippingOption[] | undefined) {\n if (!shippingOptions) {\n return undefined;\n }\n return Object.values(shippingOptions).map((option) => {\n return {\n id: option.id,\n title: option.title,\n amount: option.prices.reduce((ac, cur) => ac + Number((cur.amount as any).value), 0),\n prices: option.prices.map(({ label, amount }) => {\n return {\n label,\n amount: Number((amount as any).value),\n };\n }),\n };\n });\n}\n\nexport function buildReceipt(receipt: GramJs.payments.PaymentReceipt) {\n const {\n invoice,\n info,\n shipping,\n currency,\n totalAmount,\n credentialsTitle,\n } = receipt;\n\n const { shippingAddress, phone, name } = (info || {});\n\n const { prices } = invoice;\n const mapedPrices = prices.map(({ label, amount }) => ({\n label,\n amount: Number((amount as any).value),\n }));\n\n let shippingPrices;\n let shippingMethod;\n\n if (shipping) {\n shippingPrices = shipping.prices.map(({ label, amount }) => {\n return {\n label,\n amount: Number((amount as any).value),\n };\n });\n shippingMethod = shipping.title;\n }\n\n return {\n currency,\n prices: mapedPrices,\n info: { shippingAddress, phone, name },\n totalAmount: Number((totalAmount as any).value),\n credentialsTitle,\n shippingPrices,\n shippingMethod,\n };\n}\n\nexport function buildPaymentForm(form: GramJs.payments.PaymentForm) {\n const {\n formId,\n canSaveCredentials,\n passwordMissing,\n providerId,\n nativeProvider,\n nativeParams,\n savedInfo,\n invoice,\n } = form;\n\n const {\n test,\n nameRequested,\n phoneRequested,\n emailRequested,\n shippingAddressRequested,\n flexible,\n phoneToProvider,\n emailToProvider,\n currency,\n prices,\n } = invoice;\n\n const mapedPrices = prices.map(({ label, amount }) => ({\n label,\n amount: Number((amount as any).value),\n }));\n\n const nativeData = nativeParams ? JSON.parse(nativeParams.data) : {};\n return {\n canSaveCredentials,\n passwordMissing,\n formId: String(formId),\n providerId,\n nativeProvider,\n savedInfo,\n invoice: {\n test,\n nameRequested,\n phoneRequested,\n emailRequested,\n shippingAddressRequested,\n flexible,\n phoneToProvider,\n emailToProvider,\n currency,\n prices: mapedPrices,\n },\n nativeParams: {\n needCardholderName: nativeData.need_cardholder_name,\n needCountry: nativeData.need_country,\n needZip: nativeData.need_zip,\n publishableKey: nativeData.publishable_key,\n },\n };\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport { invokeRequest } from './client';\nimport { buildInputPeer, buildShippingInfo } from '../gramjsBuilders';\nimport { buildShippingOptions, buildPaymentForm, buildReceipt } from '../apiBuilders/payments';\nimport { ApiChat } from '../../types';\n\nexport async function validateRequestedInfo({\n chat,\n messageId,\n requestInfo,\n shouldSave,\n}: {\n chat: ApiChat;\n messageId: number;\n requestInfo: GramJs.TypePaymentRequestedInfo;\n shouldSave?: boolean;\n}): Promise<{\n id: string;\n shippingOptions: any;\n } | undefined> {\n const result = await invokeRequest(new GramJs.payments.ValidateRequestedInfo({\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: messageId,\n save: shouldSave || undefined,\n info: buildShippingInfo(requestInfo),\n }));\n if (!result) {\n return undefined;\n }\n\n const { id, shippingOptions } = result;\n if (!id) {\n return undefined;\n }\n\n return {\n id,\n shippingOptions: buildShippingOptions(shippingOptions),\n };\n}\n\nexport function sendPaymentForm({\n chat,\n messageId,\n formId,\n requestedInfoId,\n shippingOptionId,\n credentials,\n}: {\n chat: ApiChat;\n messageId: number;\n formId: string;\n credentials: any;\n requestedInfoId?: string;\n shippingOptionId?: string;\n}) {\n return invokeRequest(new GramJs.payments.SendPaymentForm({\n formId: BigInt(formId),\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: messageId,\n requestedInfoId,\n shippingOptionId,\n credentials: new GramJs.InputPaymentCredentials({\n save: credentials.save,\n data: new GramJs.DataJSON({ data: JSON.stringify(credentials.data) }),\n }),\n }), true);\n}\n\nexport async function getPaymentForm({\n chat, messageId,\n}: {\n chat: ApiChat;\n messageId: number;\n}) {\n const result = await invokeRequest(new GramJs.payments.GetPaymentForm({\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: messageId,\n }));\n\n if (!result) {\n return undefined;\n }\n\n return buildPaymentForm(result);\n}\n\nexport async function getReceipt(chat: ApiChat, msgId: number) {\n const result = await invokeRequest(new GramJs.payments.GetPaymentReceipt({\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId,\n }));\n if (!result) {\n return undefined;\n }\n\n return buildReceipt(result);\n}\n","import {\n OnApiUpdate,\n ApiInitialArgs,\n ApiUpdate,\n ApiOnProgress,\n} from '../types';\nimport { Methods, MethodArgs, MethodResponse } from './methods/types';\n\nimport { API_THROTTLE_RESET_UPDATES, API_UPDATE_THROTTLE } from '../../config';\nimport { throttle, throttleWithTickEnd } from '../../util/schedulers';\nimport { init as initUpdater } from './updater';\nimport { init as initAuth } from './methods/auth';\nimport { init as initChats } from './methods/chats';\nimport { init as initMessages } from './methods/messages';\nimport { init as initUsers } from './methods/users';\nimport { init as initClient } from './methods/client';\nimport { init as initStickers } from './methods/symbols';\nimport { init as initManagement } from './methods/management';\nimport { init as initTwoFaSettings } from './methods/twoFaSettings';\nimport * as methods from './methods';\n\nlet onUpdate: OnApiUpdate;\n\nexport async function initApi(_onUpdate: OnApiUpdate, initialArgs: ApiInitialArgs) {\n onUpdate = _onUpdate;\n\n initUpdater(handleUpdate);\n initAuth(handleUpdate);\n initChats(handleUpdate);\n initMessages(handleUpdate);\n initUsers(handleUpdate);\n initStickers(handleUpdate);\n initManagement(handleUpdate);\n initTwoFaSettings(handleUpdate);\n\n await initClient(handleUpdate, initialArgs);\n}\n\nexport function callApi<T extends keyof Methods>(fnName: T, ...args: MethodArgs<T>): MethodResponse<T> {\n // @ts-ignore\n return methods[fnName](...args) as MethodResponse<T>;\n}\n\nexport function cancelApiProgress(progressCallback: ApiOnProgress) {\n progressCallback.isCanceled = true;\n}\n\nconst flushUpdatesOnTickEnd = throttleWithTickEnd(flushUpdates);\n\nlet flushUpdatesThrottled: typeof flushUpdatesOnTickEnd | undefined;\nlet currentThrottleId: number | undefined;\n\nlet pendingUpdates: ApiUpdate[] | undefined;\n\nfunction handleUpdate(update: ApiUpdate) {\n if (!pendingUpdates) {\n pendingUpdates = [update];\n } else {\n pendingUpdates.push(update);\n }\n\n if (!flushUpdatesThrottled || API_THROTTLE_RESET_UPDATES.has(update['@type'])) {\n flushUpdatesThrottled = throttle(flushUpdatesOnTickEnd, API_UPDATE_THROTTLE, true);\n currentThrottleId = Math.random();\n }\n\n flushUpdatesThrottled(currentThrottleId!);\n}\n\nfunction flushUpdates(throttleId: number) {\n if (!pendingUpdates || throttleId !== currentThrottleId) {\n return;\n }\n\n const currentUpdates = pendingUpdates!;\n pendingUpdates = undefined;\n currentUpdates.forEach(onUpdate);\n}\n","type Scheduler =\n typeof requestAnimationFrame\n | typeof onTickEnd\n | typeof runNow;\n\nexport function debounce<F extends AnyToVoidFunction>(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n shouldRunLast = true,\n) {\n let waitingTimeout: number | undefined;\n\n return (...args: Parameters<F>) => {\n if (waitingTimeout) {\n clearTimeout(waitingTimeout);\n waitingTimeout = undefined;\n } else if (shouldRunFirst) {\n // @ts-ignore\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n waitingTimeout = self.setTimeout(() => {\n if (shouldRunLast) {\n // @ts-ignore\n fn(...args);\n }\n\n waitingTimeout = undefined;\n }, ms);\n };\n}\n\nexport function throttle<F extends AnyToVoidFunction>(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n) {\n let interval: number | undefined;\n let isPending: boolean;\n let args: Parameters<F>;\n\n return (..._args: Parameters<F>) => {\n isPending = true;\n args = _args;\n\n if (!interval) {\n if (shouldRunFirst) {\n isPending = false;\n // @ts-ignore\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n interval = self.setInterval(() => {\n if (!isPending) {\n // eslint-disable-next-line no-restricted-globals\n self.clearInterval(interval!);\n interval = undefined;\n return;\n }\n\n isPending = false;\n // @ts-ignore\n fn(...args);\n }, ms);\n }\n };\n}\n\nexport function throttleWithRaf<F extends AnyToVoidFunction>(fn: F) {\n return throttleWith(fastRaf, fn);\n}\n\nexport function throttleWithPrimaryRaf<F extends AnyToVoidFunction>(fn: F) {\n return throttleWith(fastPrimaryRaf, fn);\n}\n\nexport function throttleWithTickEnd<F extends AnyToVoidFunction>(fn: F) {\n return throttleWith(onTickEnd, fn);\n}\n\nexport function throttleWithNow<F extends AnyToVoidFunction>(fn: F) {\n return throttleWith(runNow, fn);\n}\n\nexport function throttleWith<F extends AnyToVoidFunction>(schedulerFn: Scheduler, fn: F) {\n let waiting = false;\n let args: Parameters<F>;\n\n return (..._args: Parameters<F>) => {\n args = _args;\n\n if (!waiting) {\n waiting = true;\n\n schedulerFn(() => {\n waiting = false;\n // @ts-ignore\n fn(...args);\n });\n }\n };\n}\n\nexport function onTickEnd(cb: NoneToVoidFunction) {\n Promise.resolve().then(cb);\n}\n\nexport function onIdle(cb: NoneToVoidFunction) {\n // eslint-disable-next-line no-restricted-globals\n if (self.requestIdleCallback) {\n // eslint-disable-next-line no-restricted-globals\n self.requestIdleCallback(cb);\n } else {\n onTickEnd(cb);\n }\n}\n\nfunction runNow(fn: NoneToVoidFunction) {\n fn();\n}\n\nexport const pause = (ms: number) => new Promise<void>((resolve) => {\n setTimeout(() => resolve(), ms);\n});\n\nexport function rafPromise() {\n return new Promise<void>((resolve) => {\n fastRaf(resolve);\n });\n}\n\nlet fastRafCallbacks: NoneToVoidFunction[] | undefined;\nlet fastRafPrimaryCallbacks: NoneToVoidFunction[] | undefined;\n\n// May result in an immediate execution if called from another `requestAnimationFrame` callback\nexport function fastRaf(callback: NoneToVoidFunction, isPrimary = false) {\n if (!fastRafCallbacks) {\n fastRafCallbacks = isPrimary ? [] : [callback];\n fastRafPrimaryCallbacks = isPrimary ? [callback] : [];\n\n requestAnimationFrame(() => {\n const currentCallbacks = fastRafCallbacks!;\n const currentPrimaryCallbacks = fastRafPrimaryCallbacks!;\n fastRafCallbacks = undefined;\n fastRafPrimaryCallbacks = undefined;\n currentPrimaryCallbacks.forEach((cb) => cb());\n currentCallbacks.forEach((cb) => cb());\n });\n } else if (isPrimary) {\n fastRafPrimaryCallbacks!.push(callback);\n } else {\n fastRafCallbacks.push(callback);\n }\n}\n\nexport function fastPrimaryRaf(callback: NoneToVoidFunction) {\n fastRaf(callback, true);\n}\n\nlet beforeUnloadCallbacks: NoneToVoidFunction[] | undefined;\n\nexport function onBeforeUnload(callback: NoneToVoidFunction, isLast = false) {\n if (!beforeUnloadCallbacks) {\n beforeUnloadCallbacks = [];\n // eslint-disable-next-line no-restricted-globals\n self.addEventListener('beforeunload', () => {\n beforeUnloadCallbacks!.forEach((cb) => cb());\n });\n }\n\n if (isLast) {\n beforeUnloadCallbacks.push(callback);\n } else {\n beforeUnloadCallbacks.unshift(callback);\n }\n\n return () => {\n beforeUnloadCallbacks = beforeUnloadCallbacks!.filter((cb) => cb !== callback);\n };\n}\n","import { ApiOnProgress, ApiUpdate } from '../../types';\nimport { OriginMessageEvent, WorkerMessageData } from './types';\n\nimport { DEBUG } from '../../../config';\nimport { initApi, callApi, cancelApiProgress } from '../provider';\n\ndeclare const self: WorkerGlobalScope;\n\nhandleErrors();\n\n// TODO Re-use `util/createWorkerInterface.ts`\n\nconst callbackState = new Map<string, ApiOnProgress>();\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH LOAD WORKER');\n}\n\nonmessage = async (message: OriginMessageEvent) => {\n const { data } = message;\n\n switch (data.type) {\n case 'initApi': {\n await initApi(onUpdate, data.args[0]);\n break;\n }\n case 'callMethod': {\n const { messageId, name, args } = data;\n try {\n if (messageId) {\n const callback = (...callbackArgs: any[]) => {\n const lastArg = callbackArgs[callbackArgs.length - 1];\n\n sendToOrigin({\n type: 'methodCallback',\n messageId,\n callbackArgs,\n }, lastArg instanceof ArrayBuffer ? lastArg : undefined);\n };\n\n callbackState.set(messageId, callback);\n\n args.push(callback as never);\n }\n\n const response = await callApi(name, ...args);\n const { arrayBuffer } = (typeof response === 'object' && 'arrayBuffer' in response && response) || {};\n\n if (messageId) {\n sendToOrigin({\n type: 'methodResponse',\n messageId,\n response,\n }, arrayBuffer);\n }\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(error);\n }\n\n if (messageId) {\n sendToOrigin({\n type: 'methodResponse',\n messageId,\n error: { message: error.message },\n });\n }\n }\n\n if (messageId) {\n callbackState.delete(messageId);\n }\n\n break;\n }\n case 'cancelProgress': {\n const callback = callbackState.get(data.messageId);\n if (callback) {\n cancelApiProgress(callback);\n }\n\n break;\n }\n case 'ping': {\n sendToOrigin({\n type: 'methodResponse',\n messageId: data.messageId!,\n });\n\n break;\n }\n }\n};\n\nfunction handleErrors() {\n self.onerror = (e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n sendToOrigin({ type: 'unhandledError', error: { message: e.error.message || 'Uncaught exception in worker' } });\n };\n\n self.addEventListener('unhandledrejection', (e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n sendToOrigin({ type: 'unhandledError', error: { message: e.reason.message || 'Uncaught rejection in worker' } });\n });\n}\n\nfunction onUpdate(update: ApiUpdate) {\n sendToOrigin({\n type: 'update',\n update,\n });\n}\n\nfunction sendToOrigin(data: WorkerMessageData, arrayBuffer?: ArrayBuffer) {\n if (arrayBuffer) {\n postMessage(data, [arrayBuffer]);\n } else {\n postMessage(data);\n }\n}\n","const BigInt = require('big-integer');\nconst crypto = require('./crypto/crypto');\n\n/**\n * converts a buffer to big int\n * @param buffer\n * @param little\n * @param signed\n * @returns {bigInt.BigInteger}\n */\nfunction readBigIntFromBuffer(buffer, little = true, signed = false) {\n let randBuffer = Buffer.from(buffer);\n const bytesNumber = randBuffer.length;\n if (little) {\n randBuffer = randBuffer.reverse();\n }\n let bigInt = BigInt(randBuffer.toString('hex'), 16);\n if (signed && Math.floor(bigInt.toString('2').length / 8) >= bytesNumber) {\n bigInt = bigInt.subtract(BigInt(2)\n .pow(BigInt(bytesNumber * 8)));\n }\n return bigInt;\n}\n\n/**\n * Special case signed little ints\n * @param big\n * @param number\n * @returns {Buffer}\n */\nfunction toSignedLittleBuffer(big, number = 8) {\n const bigNumber = BigInt(big);\n const byteArray = [];\n for (let i = 0; i < number; i++) {\n byteArray[i] = bigNumber.shiftRight(8 * i)\n .and(255);\n }\n return Buffer.from(byteArray);\n}\n\n\n/**\n * converts a big int to a buffer\n * @param bigInt {bigInt.BigInteger}\n * @param bytesNumber\n * @param little\n * @param signed\n * @returns {Buffer}\n */\nfunction readBufferFromBigInt(bigInt, bytesNumber, little = true, signed = false) {\n bigInt = BigInt(bigInt);\n const bitLength = bigInt.bitLength();\n\n const bytes = Math.ceil(bitLength / 8);\n if (bytesNumber < bytes) {\n throw new Error('OverflowError: int too big to convert');\n }\n if (!signed && bigInt.lesser(BigInt(0))) {\n throw new Error('Cannot convert to unsigned');\n }\n let below = false;\n if (bigInt.lesser(BigInt(0))) {\n below = true;\n bigInt = bigInt.abs();\n }\n\n const hex = bigInt.toString('16')\n .padStart(bytesNumber * 2, '0');\n let l = Buffer.from(hex, 'hex');\n if (little) {\n l = l.reverse();\n }\n\n if (signed && below) {\n if (little) {\n let reminder = false;\n if (l[0] !== 0) {\n l[0] -= 1;\n }\n for (let i = 0; i < l.length; i++) {\n if (l[i] === 0) {\n reminder = true;\n continue;\n }\n if (reminder) {\n l[i] -= 1;\n reminder = false;\n }\n l[i] = 255 - l[i];\n }\n } else {\n l[l.length - 1] = 256 - l[l.length - 1];\n for (let i = 0; i < l.length - 1; i++) {\n l[i] = 255 - l[i];\n }\n }\n }\n return l;\n}\n\n/**\n * Generates a random long integer (8 bytes), which is optionally signed\n * @returns {BigInteger}\n */\nfunction generateRandomLong(signed = true) {\n return readBigIntFromBuffer(generateRandomBytes(8), true, signed);\n}\n\n/**\n * .... really javascript\n * @param n {number}\n * @param m {number}\n * @returns {number}\n */\nfunction mod(n, m) {\n return ((n % m) + m) % m;\n}\n\n/**\n * returns a positive bigInt\n * @param n {BigInt}\n * @param m {BigInt}\n * @returns {BigInt}\n */\nfunction bigIntMod(n, m) {\n return ((n.remainder(m)).add(m)).remainder(m);\n}\n\n/**\n * Generates a random bytes array\n * @param count\n * @returns {Buffer}\n */\nfunction generateRandomBytes(count) {\n return Buffer.from(crypto.randomBytes(count));\n}\n\n/**\n * Calculate the key based on Telegram guidelines, specifying whether it's the client or not\n * @param sharedKey\n * @param msgKey\n * @param client\n * @returns {{iv: Buffer, key: Buffer}}\n */\n\n/* CONTEST\nthis is mtproto 1 (mostly used for secret chats)\nasync function calcKey(sharedKey, msgKey, client) {\n const x = client === true ? 0 : 8\n const [sha1a, sha1b, sha1c, sha1d] = await Promise.all([\n sha1(Buffer.concat([msgKey, sharedKey.slice(x, x + 32)])),\n sha1(Buffer.concat([sharedKey.slice(x + 32, x + 48), msgKey, sharedKey.slice(x + 48, x + 64)])),\n sha1(Buffer.concat([sharedKey.slice(x + 64, x + 96), msgKey])),\n sha1(Buffer.concat([msgKey, sharedKey.slice(x + 96, x + 128)]))\n ])\n const key = Buffer.concat([sha1a.slice(0, 8), sha1b.slice(8, 20), sha1c.slice(4, 16)])\n const iv = Buffer.concat([sha1a.slice(8, 20), sha1b.slice(0, 8), sha1c.slice(16, 20), sha1d.slice(0, 8)])\n return {\n key,\n iv\n }\n}\n\n */\n\n/**\n * Generates the key data corresponding to the given nonces\n * @param serverNonce\n * @param newNonce\n * @returns {{key: Buffer, iv: Buffer}}\n */\nasync function generateKeyDataFromNonce(serverNonce, newNonce) {\n serverNonce = toSignedLittleBuffer(serverNonce, 16);\n newNonce = toSignedLittleBuffer(newNonce, 32);\n const [hash1, hash2, hash3] = await Promise.all([\n sha1(Buffer.concat([newNonce, serverNonce])),\n sha1(Buffer.concat([serverNonce, newNonce])),\n sha1(Buffer.concat([newNonce, newNonce])),\n ]);\n const keyBuffer = Buffer.concat([hash1, hash2.slice(0, 12)]);\n const ivBuffer = Buffer.concat([hash2.slice(12, 20), hash3, newNonce.slice(0, 4)]);\n return {\n key: keyBuffer,\n iv: ivBuffer,\n };\n}\n\nfunction convertToLittle(buf) {\n const correct = Buffer.alloc(buf.length * 4);\n\n for (let i = 0; i < buf.length; i++) {\n correct.writeUInt32BE(buf[i], i * 4);\n }\n return correct;\n}\n\n/**\n * Calculates the SHA1 digest for the given data\n * @param data\n * @returns {Promise}\n */\nfunction sha1(data) {\n const shaSum = crypto.createHash('sha1');\n shaSum.update(data);\n return shaSum.digest();\n}\n\n\n/**\n * Calculates the SHA256 digest for the given data\n * @param data\n * @returns {Promise}\n */\nfunction sha256(data) {\n const shaSum = crypto.createHash('sha256');\n shaSum.update(data);\n return shaSum.digest();\n}\n\n/**\n * Fast mod pow for RSA calculation. a^b % n\n * @param a\n * @param b\n * @param n\n * @returns {bigInt.BigInteger}\n */\nfunction modExp(a, b, n) {\n a = a.remainder(n);\n let result = BigInt.one;\n let x = a;\n while (b.greater(BigInt.zero)) {\n const leastSignificantBit = b.remainder(BigInt(2));\n b = b.divide(BigInt(2));\n if (leastSignificantBit.eq(BigInt.one)) {\n result = result.multiply(x);\n result = result.remainder(n);\n }\n x = x.multiply(x);\n x = x.remainder(n);\n }\n return result;\n}\n\n\n/**\n * Gets the arbitrary-length byte array corresponding to the given integer\n * @param integer {number,BigInteger}\n * @param signed {boolean}\n * @returns {Buffer}\n */\nfunction getByteArray(integer, signed = false) {\n const bits = integer.toString(2).length;\n const byteLength = Math.floor((bits + 8 - 1) / 8);\n return readBufferFromBigInt(BigInt(integer), byteLength, false, signed);\n}\n\n/**\n * returns a random int from min (inclusive) and max (inclusive)\n * @param min\n * @param max\n * @returns {number}\n */\nfunction getRandomInt(min, max) {\n min = Math.ceil(min);\n max = Math.floor(max);\n return Math.floor(Math.random() * (max - min + 1)) + min;\n}\n\n/**\n * Sleeps a specified amount of time\n * @param ms time in milliseconds\n * @returns {Promise}\n */\nconst sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));\n\n/**\n * Helper to export two buffers of same length\n * @returns {Buffer}\n */\n\nfunction bufferXor(a, b) {\n const res = [];\n for (let i = 0; i < a.length; i++) {\n res.push(a[i] ^ b[i]);\n }\n return Buffer.from(res);\n}\n\n/**\n * Checks if the obj is an array\n * @param obj\n * @returns {boolean}\n */\n/*\nCONTEST\nwe do'nt support array requests anyway\nfunction isArrayLike(obj) {\n if (!obj) return false\n const l = obj.length\n if (typeof l != 'number' || l < 0) return false\n if (Math.floor(l) !== l) return false\n // fast check\n if (l > 0 && !(l - 1 in obj)) return false\n // more complete check (optional)\n for (let i = 0; i < l; ++i) {\n if (!(i in obj)) return false\n }\n return true\n}\n*/\n\n// Taken from https://stackoverflow.com/questions/18638900/javascript-crc32/18639999#18639999\nfunction makeCRCTable() {\n let c;\n const crcTable = [];\n for (let n = 0; n < 256; n++) {\n c = n;\n for (let k = 0; k < 8; k++) {\n c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));\n }\n crcTable[n] = c;\n }\n return crcTable;\n}\n\nlet crcTable;\n\nfunction crc32(buf) {\n if (!crcTable) {\n crcTable = makeCRCTable();\n }\n if (!Buffer.isBuffer(buf)) {\n buf = Buffer.from(buf);\n }\n let crc = -1;\n\n for (let index = 0; index < buf.length; index++) {\n const byte = buf[index];\n crc = crcTable[(crc ^ byte) & 0xff] ^ (crc >>> 8);\n }\n return (crc ^ (-1)) >>> 0;\n}\n\n/**\n * Creates a deferred object\n * @return {Deferred}\n */\nfunction createDeferred() {\n let resolve;\n const promise = new Promise((_resolve) => {\n resolve = _resolve;\n });\n\n return {\n promise,\n resolve,\n };\n}\n\nmodule.exports = {\n readBigIntFromBuffer,\n readBufferFromBigInt,\n generateRandomLong,\n mod,\n crc32,\n generateRandomBytes,\n // calcKey,\n generateKeyDataFromNonce,\n sha1,\n sha256,\n bigIntMod,\n modExp,\n getRandomInt,\n sleep,\n getByteArray,\n // isArrayLike,\n toSignedLittleBuffer,\n convertToLittle,\n bufferXor,\n createDeferred,\n};\n","const BigInt = require('big-integer');\nconst { constructors } = require('./tl');\nconst {\n readBigIntFromBuffer,\n readBufferFromBigInt,\n sha256,\n bigIntMod,\n modExp,\n generateRandomBytes,\n} = require('./Helpers');\nconst crypto = require('./crypto/crypto');\n\nconst SIZE_FOR_HASH = 256;\n\n/**\n *\n *\n * @param prime{BigInteger}\n * @param g{BigInteger}\n */\n\n/*\nWe don't support changing passwords yet\nfunction checkPrimeAndGoodCheck(prime, g) {\n console.error('Unsupported function `checkPrimeAndGoodCheck` call. Arguments:', prime, g)\n\n const goodPrimeBitsCount = 2048\n if (prime < 0 || prime.bitLength() !== goodPrimeBitsCount) {\n throw new Error(`bad prime count ${prime.bitLength()},expected ${goodPrimeBitsCount}`)\n }\n // TODO this is kinda slow\n if (Factorizator.factorize(prime)[0] !== 1) {\n throw new Error('give \"prime\" is not prime')\n }\n if (g.eq(BigInt(2))) {\n if ((prime.remainder(BigInt(8))).neq(BigInt(7))) {\n throw new Error(`bad g ${g}, mod8 ${prime % 8}`)\n }\n } else if (g.eq(BigInt(3))) {\n if ((prime.remainder(BigInt(3))).neq(BigInt(2))) {\n throw new Error(`bad g ${g}, mod3 ${prime % 3}`)\n }\n // eslint-disable-next-line no-empty\n } else if (g.eq(BigInt(4))) {\n\n } else if (g.eq(BigInt(5))) {\n if (!([ BigInt(1), BigInt(4) ].includes(prime.remainder(BigInt(5))))) {\n throw new Error(`bad g ${g}, mod8 ${prime % 5}`)\n }\n } else if (g.eq(BigInt(6))) {\n if (!([ BigInt(19), BigInt(23) ].includes(prime.remainder(BigInt(24))))) {\n throw new Error(`bad g ${g}, mod8 ${prime % 24}`)\n }\n } else if (g.eq(BigInt(7))) {\n if (!([ BigInt(3), BigInt(5), BigInt(6) ].includes(prime.remainder(BigInt(7))))) {\n throw new Error(`bad g ${g}, mod8 ${prime % 7}`)\n }\n } else {\n throw new Error(`bad g ${g}`)\n }\n const primeSub1Div2 = (prime.subtract(BigInt(1))).divide(BigInt(2))\n if (Factorizator.factorize(primeSub1Div2)[0] !== 1) {\n throw new Error('(prime - 1) // 2 is not prime')\n }\n}\n*/\n/**\n *\n * @param primeBytes{Buffer}\n * @param g{number}\n */\nfunction checkPrimeAndGood(primeBytes, g) {\n const goodPrime = Buffer.from([\n 0xC7, 0x1C, 0xAE, 0xB9, 0xC6, 0xB1, 0xC9, 0x04, 0x8E, 0x6C, 0x52, 0x2F, 0x70, 0xF1, 0x3F, 0x73,\n 0x98, 0x0D, 0x40, 0x23, 0x8E, 0x3E, 0x21, 0xC1, 0x49, 0x34, 0xD0, 0x37, 0x56, 0x3D, 0x93, 0x0F,\n 0x48, 0x19, 0x8A, 0x0A, 0xA7, 0xC1, 0x40, 0x58, 0x22, 0x94, 0x93, 0xD2, 0x25, 0x30, 0xF4, 0xDB,\n 0xFA, 0x33, 0x6F, 0x6E, 0x0A, 0xC9, 0x25, 0x13, 0x95, 0x43, 0xAE, 0xD4, 0x4C, 0xCE, 0x7C, 0x37,\n 0x20, 0xFD, 0x51, 0xF6, 0x94, 0x58, 0x70, 0x5A, 0xC6, 0x8C, 0xD4, 0xFE, 0x6B, 0x6B, 0x13, 0xAB,\n 0xDC, 0x97, 0x46, 0x51, 0x29, 0x69, 0x32, 0x84, 0x54, 0xF1, 0x8F, 0xAF, 0x8C, 0x59, 0x5F, 0x64,\n 0x24, 0x77, 0xFE, 0x96, 0xBB, 0x2A, 0x94, 0x1D, 0x5B, 0xCD, 0x1D, 0x4A, 0xC8, 0xCC, 0x49, 0x88,\n 0x07, 0x08, 0xFA, 0x9B, 0x37, 0x8E, 0x3C, 0x4F, 0x3A, 0x90, 0x60, 0xBE, 0xE6, 0x7C, 0xF9, 0xA4,\n 0xA4, 0xA6, 0x95, 0x81, 0x10, 0x51, 0x90, 0x7E, 0x16, 0x27, 0x53, 0xB5, 0x6B, 0x0F, 0x6B, 0x41,\n 0x0D, 0xBA, 0x74, 0xD8, 0xA8, 0x4B, 0x2A, 0x14, 0xB3, 0x14, 0x4E, 0x0E, 0xF1, 0x28, 0x47, 0x54,\n 0xFD, 0x17, 0xED, 0x95, 0x0D, 0x59, 0x65, 0xB4, 0xB9, 0xDD, 0x46, 0x58, 0x2D, 0xB1, 0x17, 0x8D,\n 0x16, 0x9C, 0x6B, 0xC4, 0x65, 0xB0, 0xD6, 0xFF, 0x9C, 0xA3, 0x92, 0x8F, 0xEF, 0x5B, 0x9A, 0xE4,\n 0xE4, 0x18, 0xFC, 0x15, 0xE8, 0x3E, 0xBE, 0xA0, 0xF8, 0x7F, 0xA9, 0xFF, 0x5E, 0xED, 0x70, 0x05,\n 0x0D, 0xED, 0x28, 0x49, 0xF4, 0x7B, 0xF9, 0x59, 0xD9, 0x56, 0x85, 0x0C, 0xE9, 0x29, 0x85, 0x1F,\n 0x0D, 0x81, 0x15, 0xF6, 0x35, 0xB1, 0x05, 0xEE, 0x2E, 0x4E, 0x15, 0xD0, 0x4B, 0x24, 0x54, 0xBF,\n 0x6F, 0x4F, 0xAD, 0xF0, 0x34, 0xB1, 0x04, 0x03, 0x11, 0x9C, 0xD8, 0xE3, 0xB9, 0x2F, 0xCC, 0x5B,\n ]);\n if (goodPrime.equals(primeBytes)) {\n if ([3, 4, 5, 7].includes(g)) {\n return; // It's good\n }\n }\n throw new Error('Changing passwords unsupported');\n // checkPrimeAndGoodCheck(readBigIntFromBuffer(primeBytes, false), g)\n}\n\n/**\n *\n * @param number{BigInteger}\n * @param p{BigInteger}\n * @returns {boolean}\n */\nfunction isGoodLarge(number, p) {\n return (number.greater(BigInt(0)) && (p.subtract(number)\n .greater(BigInt(0))));\n}\n\n/**\n *\n * @param number {Buffer}\n * @returns {Buffer}\n */\nfunction numBytesForHash(number) {\n return Buffer.concat([Buffer.alloc(SIZE_FOR_HASH - number.length), number]);\n}\n\n/**\n *\n * @param g {Buffer}\n * @returns {Buffer}\n */\nfunction bigNumForHash(g) {\n return readBufferFromBigInt(g, SIZE_FOR_HASH, false);\n}\n\n/**\n *\n * @param modexp {BigInteger}\n * @param prime {BigInteger}\n * @returns {Boolean}\n */\nfunction isGoodModExpFirst(modexp, prime) {\n const diff = prime.subtract(modexp);\n\n const minDiffBitsCount = 2048 - 64;\n const maxModExpSize = 256;\n\n return !(diff.lesser(BigInt(0)) || diff.bitLength() < minDiffBitsCount\n || modexp.bitLength() < minDiffBitsCount\n || Math.floor((modexp.bitLength() + 7) / 8) > maxModExpSize);\n}\n\nfunction xor(a, b) {\n const length = Math.min(a.length, b.length);\n\n for (let i = 0; i < length; i++) {\n a[i] ^= b[i];\n }\n\n return a;\n}\n\n/**\n *\n * @param password{Buffer}\n * @param salt{Buffer}\n * @param iterations{number}\n * @returns {*}\n */\n\nfunction pbkdf2sha512(password, salt, iterations) {\n return crypto.pbkdf2(password, salt, iterations, 64, 'sha512');\n}\n\n/**\n *\n * @param algo {constructors.PasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow}\n * @param password\n * @returns {Buffer|*}\n */\nasync function computeHash(algo, password) {\n const hash1 = await sha256(Buffer.concat([algo.salt1, Buffer.from(password, 'utf-8'), algo.salt1]));\n const hash2 = await sha256(Buffer.concat([algo.salt2, hash1, algo.salt2]));\n const hash3 = await pbkdf2sha512(hash2, algo.salt1, 100000);\n return sha256(Buffer.concat([algo.salt2, hash3, algo.salt2]));\n}\n\n/**\n *\n * @param algo {constructors.PasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow}\n * @param password\n */\nasync function computeDigest(algo, password) {\n try {\n checkPrimeAndGood(algo.p, algo.g);\n } catch (e) {\n throw new Error('bad p/g in password');\n }\n\n const value = modExp(BigInt(algo.g),\n readBigIntFromBuffer(await computeHash(algo, password), false),\n readBigIntFromBuffer(algo.p, false));\n return bigNumForHash(value);\n}\n\n/**\n *\n * @param request {constructors.account.Password}\n * @param password {string}\n */\nasync function computeCheck(request, password) {\n const algo = request.currentAlgo;\n if (!(algo instanceof constructors.PasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow)) {\n throw new Error(`Unsupported password algorithm ${algo.className}`);\n }\n\n const pwHash = await computeHash(algo, password);\n const p = readBigIntFromBuffer(algo.p, false);\n const { g } = algo;\n const B = readBigIntFromBuffer(request.srp_B, false);\n try {\n checkPrimeAndGood(algo.p, g);\n } catch (e) {\n throw new Error('bad /g in password');\n }\n if (!isGoodLarge(B, p)) {\n throw new Error('bad b in check');\n }\n const x = readBigIntFromBuffer(pwHash, false);\n const pForHash = numBytesForHash(algo.p);\n const gForHash = bigNumForHash(g);\n const bForHash = numBytesForHash(request.srp_B);\n const gX = modExp(BigInt(g), x, p);\n const k = readBigIntFromBuffer(await sha256(Buffer.concat([pForHash, gForHash])), false);\n const kgX = bigIntMod(k.multiply(gX), p);\n const generateAndCheckRandom = async () => {\n const randomSize = 256;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const random = generateRandomBytes(randomSize);\n const a = readBigIntFromBuffer(random, false);\n const A = modExp(BigInt(g), a, p);\n if (isGoodModExpFirst(A, p)) {\n const aForHash = bigNumForHash(A);\n const u = readBigIntFromBuffer(await sha256(Buffer.concat([aForHash, bForHash])), false);\n if (u.greater(BigInt(0))) {\n return [a, aForHash, u];\n }\n }\n }\n };\n const [a, aForHash, u] = await generateAndCheckRandom();\n const gB = bigIntMod(B.subtract(kgX), p);\n if (!isGoodModExpFirst(gB, p)) {\n throw new Error('bad gB');\n }\n\n const ux = u.multiply(x);\n const aUx = a.add(ux);\n const S = modExp(gB, aUx, p);\n const [K, pSha, gSha, salt1Sha, salt2Sha] = await Promise.all([\n sha256(bigNumForHash(S)),\n sha256(pForHash),\n sha256(gForHash),\n sha256(algo.salt1),\n sha256(algo.salt2),\n ]);\n const M1 = await sha256(Buffer.concat([\n xor(pSha, gSha),\n salt1Sha,\n salt2Sha,\n aForHash,\n bForHash,\n K,\n ]));\n\n\n return new constructors.InputCheckPasswordSRP({\n srpId: request.srpId,\n A: Buffer.from(aForHash),\n M1,\n\n });\n}\n\nmodule.exports = {\n computeCheck,\n computeDigest,\n};\n","const { constructors } = require('./tl');\n\n// eslint-disable-next-line max-len\nconst JPEG_HEADER = Buffer.from('ffd8ffe000104a46494600010100000100010000ffdb004300281c1e231e19282321232d2b28303c64413c37373c7b585d4964918099968f808c8aa0b4e6c3a0aadaad8a8cc8ffcbdaeef5ffffff9bc1fffffffaffe6fdfff8ffdb0043012b2d2d3c353c76414176f8a58ca5f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8ffc00011080000000003012200021101031101ffc4001f0000010501010101010100000000000000000102030405060708090a0bffc400b5100002010303020403050504040000017d01020300041105122131410613516107227114328191a1082342b1c11552d1f02433627282090a161718191a25262728292a3435363738393a434445464748494a535455565758595a636465666768696a737475767778797a838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae1e2e3e4e5e6e7e8e9eaf1f2f3f4f5f6f7f8f9faffc4001f0100030101010101010101010000000000000102030405060708090a0bffc400b51100020102040403040705040400010277000102031104052131061241510761711322328108144291a1b1c109233352f0156272d10a162434e125f11718191a262728292a35363738393a434445464748494a535455565758595a636465666768696a737475767778797a82838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae2e3e4e5e6e7e8e9eaf2f3f4f5f6f7f8f9faffda000c03010002110311003f00', 'hex');\nconst JPEG_FOOTER = Buffer.from('ffd9', 'hex');\n\nfunction _raiseCastFail(entity, target) {\n throw new Error(`Cannot cast ${entity.className} to any kind of ${target}`);\n}\n\n/**\n Gets the input peer for the given \"entity\" (user, chat or channel).\n\n A ``TypeError`` is raised if the given entity isn't a supported type\n or if ``check_hash is True`` but the entity's ``accessHash is None``\n *or* the entity contains ``min`` information. In this case, the hash\n cannot be used for general purposes, and thus is not returned to avoid\n any issues which can derive from invalid access hashes.\n\n Note that ``check_hash`` **is ignored** if an input peer is already\n passed since in that case we assume the user knows what they're doing.\n This is key to getting entities by explicitly passing ``hash = 0``.\n\n * @param entity\n * @param allowSelf\n * @param checkHash\n */\nfunction getInputPeer(entity, allowSelf = true, checkHash = true) {\n if (entity.SUBCLASS_OF_ID === undefined) {\n // e.g. custom.Dialog (can't cyclic import).\n\n if (allowSelf && 'inputEntity' in entity) {\n return entity.inputEntity;\n } else if ('entity' in entity) {\n return getInputPeer(entity.entity);\n } else {\n _raiseCastFail(entity, 'InputPeer');\n }\n }\n if (entity.SUBCLASS_OF_ID === 0xc91c90b6) { // crc32(b'InputPeer')\n return entity;\n }\n\n if (entity instanceof constructors.User) {\n if (entity.isSelf && allowSelf) {\n return new constructors.InputPeerSelf();\n } else if (entity.accessHash !== undefined || !checkHash) {\n return new constructors.InputPeerUser({\n userId: entity.id,\n accessHash: entity.accessHash,\n });\n } else {\n throw new Error('User without accessHash or min info cannot be input');\n }\n }\n if (entity instanceof constructors.Chat || entity instanceof constructors.ChatEmpty\n || entity instanceof constructors.ChatForbidden) {\n return new constructors.InputPeerChat({ chatId: entity.id });\n }\n if (entity instanceof constructors.Channel) {\n if (entity.accessHash !== undefined || !checkHash) {\n return new constructors.InputPeerChannel({\n channelId: entity.id,\n accessHash: entity.accessHash,\n });\n } else {\n throw new TypeError('Channel without accessHash or min info cannot be input');\n }\n }\n if (entity instanceof constructors.ChannelForbidden) {\n // \"channelForbidden are never min\", and since their hash is\n // also not optional, we assume that this truly is the case.\n return new constructors.InputPeerChannel({\n channelId: entity.id,\n accessHash: entity.accessHash,\n });\n }\n\n if (entity instanceof constructors.InputUser) {\n return new constructors.InputPeerUser({\n userId: entity.userId,\n accessHash: entity.accessHash,\n });\n }\n if (entity instanceof constructors.InputChannel) {\n return new constructors.InputPeerChannel({\n channelId: entity.channelId,\n accessHash: entity.accessHash,\n });\n }\n if (entity instanceof constructors.UserEmpty) {\n return new constructors.InputPeerEmpty();\n }\n if (entity instanceof constructors.UserFull) {\n return getInputPeer(entity.user);\n }\n\n if (entity instanceof constructors.ChatFull) {\n return new constructors.InputPeerChat({ chatId: entity.id });\n }\n\n if (entity instanceof constructors.PeerChat) {\n return new constructors.InputPeerChat(entity.chatId);\n }\n\n _raiseCastFail(entity, 'InputPeer');\n return undefined;\n}\n\n/**\n Similar to :meth:`get_input_peer`, but for :tl:`InputChannel`'s alone.\n\n .. important::\n\n This method does not validate for invalid general-purpose access\n hashes, unlike `get_input_peer`. Consider using instead:\n ``get_input_channel(get_input_peer(channel))``.\n\n * @param entity\n * @returns {InputChannel|*}\n */\n/* CONTEST\nfunction getInputChannel(entity) {\n if (entity.SUBCLASS_OF_ID === undefined) {\n _raiseCastFail(entity, 'InputChannel')\n }\n\n\n if (entity.SUBCLASS_OF_ID === 0x40f202fd) { // crc32(b'InputChannel')\n return entity\n }\n if (entity instanceof constructors.Channel || entity instanceof constructors.ChannelForbidden) {\n return new constructors.InputChannel({\n channelId: entity.id,\n accessHash: entity.accessHash || 0\n })\n }\n\n if (entity instanceof constructors.InputPeerChannel) {\n return new constructors.InputChannel({\n channelId: entity.channelId,\n accessHash: entity.accessHash\n })\n }\n _raiseCastFail(entity, 'InputChannel')\n}\n*/\n/**\n Similar to :meth:`get_input_peer`, but for :tl:`InputUser`'s alone.\n\n .. important::\n\n This method does not validate for invalid general-purpose access\n hashes, unlike `get_input_peer`. Consider using instead:\n ``get_input_channel(get_input_peer(channel))``.\n\n * @param entity\n */\n/* CONTEST\nfunction getInputUser(entity) {\n if (entity.SUBCLASS_OF_ID === undefined) {\n _raiseCastFail(entity, 'InputUser')\n }\n if (entity.SUBCLASS_OF_ID === 0xe669bf46) { // crc32(b'InputUser')\n return entity\n }\n\n if (entity instanceof constructors.User) {\n if (entity.isSelf) {\n return new constructors.InputPeerSelf()\n } else {\n return new constructors.InputUser({\n userId: entity.id,\n accessHash: entity.accessHash || 0,\n })\n }\n }\n if (entity instanceof constructors.InputPeerSelf) {\n return new constructors.InputPeerSelf()\n }\n if (entity instanceof constructors.UserEmpty || entity instanceof constructors.InputPeerEmpty) {\n return new constructors.InputUserEmpty()\n }\n\n if (entity instanceof constructors.UserFull) {\n return getInputUser(entity.user)\n }\n\n if (entity instanceof constructors.InputPeerUser) {\n return new constructors.InputUser({\n userId: entity.userId,\n accessHash: entity.accessHash\n })\n }\n\n _raiseCastFail(entity, 'InputUser')\n}\n*/\n/**\n Similar to :meth:`get_input_peer`, but for dialogs\n * @param dialog\n */\n/* CONTEST\nfunction getInputDialog(dialog) {\n try {\n if (dialog.SUBCLASS_OF_ID === 0xa21c9795) { // crc32(b'InputDialogPeer')\n return dialog\n }\n if (dialog.SUBCLASS_OF_ID === 0xc91c90b6) { // crc32(b'InputPeer')\n return new constructors.InputDialogPeer({ peer: dialog })\n }\n } catch (e) {\n _raiseCastFail(dialog, 'InputDialogPeer')\n }\n\n try {\n return new constructors.InputDialogPeer(getInputPeer(dialog))\n // eslint-disable-next-line no-empty\n } catch (e) {\n\n }\n _raiseCastFail(dialog, 'InputDialogPeer')\n}\n*/\n\n/* CONTEST\n\nfunction getInputMessage(message) {\n try {\n if (typeof message == 'number') { // This case is really common too\n return new constructors.InputMessageID({\n id: message,\n })\n } else if (message.SUBCLASS_OF_ID === 0x54b6bcc5) { // crc32(b'InputMessage')\n return message\n } else if (message.SUBCLASS_OF_ID === 0x790009e3) { // crc32(b'Message')\n return new constructors.InputMessageID(message.id)\n }\n // eslint-disable-next-line no-empty\n } catch (e) {\n }\n\n _raiseCastFail(message, 'InputMessage')\n}\n*/\n\n/**\n * Adds the JPG header and footer to a stripped image.\n * Ported from https://github.com/telegramdesktop/\n * tdesktop/blob/bec39d89e19670eb436dc794a8f20b657cb87c71/Telegram/SourceFiles/ui/image/image.cpp#L225\n\n * @param stripped{Buffer}\n * @returns {Buffer}\n */\nfunction strippedPhotoToJpg(stripped) {\n // Note: Changes here should update _stripped_real_length\n if (stripped.length < 3 || stripped[0] !== 1) {\n return stripped;\n }\n const header = Buffer.from(JPEG_HEADER);\n // eslint-disable-next-line prefer-destructuring\n header[164] = stripped[1];\n // eslint-disable-next-line prefer-destructuring\n header[166] = stripped[2];\n return Buffer.concat([header, stripped.slice(3), JPEG_FOOTER]);\n}\n\n/* CONTEST\nfunction getInputLocation(location) {\n try {\n if (!location.SUBCLASS_OF_ID) {\n throw new Error()\n }\n if (location.SUBCLASS_OF_ID === 0x1523d462) {\n return {\n dcId: null,\n inputLocation: location\n }\n }\n } catch (e) {\n _raiseCastFail(location, 'InputFileLocation')\n }\n if (location instanceof constructors.Message) {\n location = location.media\n }\n\n if (location instanceof constructors.MessageMediaDocument) {\n location = location.document\n } else if (location instanceof constructors.MessageMediaPhoto) {\n location = location.photo\n }\n\n if (location instanceof constructors.Document) {\n return {\n dcId: location.dcId,\n inputLocation: new constructors.InputDocumentFileLocation({\n id: location.id,\n accessHash: location.accessHash,\n fileReference: location.fileReference,\n thumbSize: '', // Presumably to download one of its thumbnails\n }),\n }\n } else if (location instanceof constructors.Photo) {\n return {\n dcId: location.dcId,\n inputLocation: new constructors.InputPhotoFileLocation({\n id: location.id,\n accessHash: location.accessHash,\n fileReference: location.fileReference,\n thumbSize: location.sizes[location.sizes.length - 1].type,\n }),\n }\n }\n\n if (location instanceof constructors.FileLocationToBeDeprecated) {\n throw new Error('Unavailable location cannot be used as input')\n }\n _raiseCastFail(location, 'InputFileLocation')\n}\n*/\n\n/**\n * Gets the appropriated part size when uploading or downloading files,\n * given an initial file size.\n * @param fileSize\n * @returns {Number}\n */\nfunction getAppropriatedPartSize(fileSize) {\n if (fileSize <= 104857600) { // 100MB\n return 128;\n }\n if (fileSize <= 786432000) { // 750MB\n return 256;\n }\n if (fileSize <= 2097152000) { // 2000MB\n return 512;\n }\n\n throw new Error('File size too large');\n}\n\n/* CONTEST\nfunction getPeer(peer) {\n try {\n if (typeof peer === 'number') {\n const res = resolveId(peer)\n\n if (res[1] === constructors.PeerChannel) {\n return new res[1]({ channelId: res[0] })\n } else if (res[1] === constructors.PeerChat) {\n return new res[1]({ chatId: res[0] })\n } else {\n return new res[1]({ userId: res[0] })\n }\n }\n if (peer.SUBCLASS_OF_ID === undefined) {\n throw new Error()\n }\n if (peer.SUBCLASS_OF_ID === 0x2d45687) {\n return peer\n } else if (peer instanceof constructors.contacts.ResolvedPeer ||\n peer instanceof constructors.InputNotifyPeer || peer instanceof constructors.TopPeer ||\n peer instanceof constructors.Dialog || peer instanceof constructors.DialogPeer) {\n return peer.peer\n } else if (peer instanceof constructors.ChannelFull) {\n return new constructors.PeerChannel({ channelId: peer.id })\n }\n if (peer.SUBCLASS_OF_ID === 0x7d7c6f86 || peer.SUBCLASS_OF_ID === 0xd9c7fc18) {\n // ChatParticipant, ChannelParticipant\n return new constructors.PeerUser({ userId: peer.userId })\n }\n peer = getInputPeer(peer, false, false)\n\n if (peer instanceof constructors.InputPeerUser) {\n return new constructors.PeerUser({ userId: peer.userId })\n } else if (peer instanceof constructors.InputPeerChat) {\n return new constructors.PeerChat({ chatId: peer.chatId })\n } else if (peer instanceof constructors.InputPeerChannel) {\n return new constructors.PeerChannel({ channelId: peer.channelId })\n }\n // eslint-disable-next-line no-empty\n } catch (e) {\n console.log(e)\n }\n _raiseCastFail(peer, 'peer')\n}\n*/\n\n/**\n Convert the given peer into its marked ID by default.\n\n This \"mark\" comes from the \"bot api\" format, and with it the peer type\n can be identified back. User ID is left unmodified, chat ID is negated,\n and channel ID is prefixed with -100:\n\n * ``userId``\n * ``-chatId``\n * ``-100channel_id``\n\n The original ID and the peer type class can be returned with\n a call to :meth:`resolve_id(marked_id)`.\n * @param peer\n * @param addMark\n */\n/* CONTEST\nfunction getPeerId(peer, addMark = true) {\n // First we assert it's a Peer TLObject, or early return for integers\n if (typeof peer == 'number') {\n return addMark ? peer : resolveId(peer)[0]\n }\n\n // Tell the user to use their client to resolve InputPeerSelf if we got one\n if (peer instanceof constructors.InputPeerSelf) {\n _raiseCastFail(peer, 'int (you might want to use client.get_peer_id)')\n }\n\n try {\n peer = getPeer(peer)\n } catch (e) {\n _raiseCastFail(peer, 'int')\n }\n if (peer instanceof constructors.PeerUser) {\n return peer.userId\n } else if (peer instanceof constructors.PeerChat) {\n // Check in case the user mixed things up to avoid blowing up\n if (!(0 < peer.chatId <= 0x7fffffff)) {\n peer.chatId = resolveId(peer.chatId)[0]\n }\n\n return addMark ? -(peer.chatId) : peer.chatId\n } else { // if (peer instanceof constructors.PeerChannel)\n // Check in case the user mixed things up to avoid blowing up\n if (!(0 < peer.channelId <= 0x7fffffff)) {\n peer.channelId = resolveId(peer.channelId)[0]\n }\n if (!addMark) {\n return peer.channelId\n }\n // Concat -100 through math tricks, .to_supergroup() on\n // Madeline IDs will be strictly positive -> log works.\n try {\n return -(peer.channelId + Math.pow(10, Math.floor(Math.log10(peer.channelId) + 3)))\n } catch (e) {\n throw new Error('Cannot get marked ID of a channel unless its ID is strictly positive')\n }\n }\n}\n*/\n/**\n * Given a marked ID, returns the original ID and its :tl:`Peer` type.\n * @param markedId\n */\n/* CONTEST\nfunction resolveId(markedId) {\n if (markedId >= 0) {\n return [markedId, constructors.PeerUser]\n }\n\n // There have been report of chat IDs being 10000xyz, which means their\n // marked version is -10000xyz, which in turn looks like a channel but\n // it becomes 00xyz (= xyz). Hence, we must assert that there are only\n // two zeroes.\n const m = markedId.toString()\n .match(/-100([^0]\\d*)/)\n if (m) {\n return [parseInt(m[1]), constructors.PeerChannel]\n }\n return [-markedId, constructors.PeerChat]\n}\n*/\n\n/**\n * returns an entity pair\n * @param entityId\n * @param entities\n * @param cache\n * @param getInputPeer\n * @returns {{inputEntity: *, entity: *}}\n * @private\n */\n\n/* CONTEST\n\nfunction _getEntityPair(entityId, entities, cache, getInputPeer = getInputPeer) {\n const entity = entities.get(entityId)\n let inputEntity = cache[entityId]\n if (inputEntity === undefined) {\n try {\n inputEntity = getInputPeer(inputEntity)\n } catch (e) {\n inputEntity = null\n }\n }\n return {\n entity,\n inputEntity\n }\n}\n*/\n\nfunction getMessageId(message) {\n if (message === undefined) {\n return undefined;\n }\n if (typeof message === 'number') {\n return message;\n }\n if (message.SUBCLASS_OF_ID === 0x790009e3) { // crc32(b'Message')\n return message.id;\n }\n throw new Error(`Invalid message type: ${message.constructor.name}`);\n}\n\n\n/**\n Parses the given username or channel access hash, given\n a string, username or URL. Returns a tuple consisting of\n both the stripped, lowercase username and whether it is\n a joinchat/ hash (in which case is not lowercase'd).\n\n Returns ``(None, False)`` if the ``username`` or link is not valid.\n\n * @param username {string}\n */\n\n/* CONTEST\n\nfunction parseUsername(username) {\n username = username.trim()\n const m = username.match(USERNAME_RE) || username.match(TG_JOIN_RE)\n if (m) {\n username = username.replace(m[0], '')\n if (m[1]) {\n return {\n username: username,\n isInvite: true\n }\n } else {\n username = rtrim(username, '/')\n }\n }\n if (username.match(VALID_USERNAME_RE)) {\n return {\n username: username.toLowerCase(),\n isInvite: false\n }\n } else {\n return {\n username: null,\n isInvite: false\n }\n }\n}\n\nfunction rtrim(s, mask) {\n while (~mask.indexOf(s[s.length - 1])) {\n s = s.slice(0, -1)\n }\n return s\n}\n\n */\n\n/**\n * Gets the display name for the given :tl:`User`,\n :tl:`Chat` or :tl:`Channel`. Returns an empty string otherwise\n * @param entity\n */\nfunction getDisplayName(entity) {\n if (entity instanceof constructors.User) {\n if (entity.lastName && entity.firstName) {\n return `${entity.firstName} ${entity.lastName}`;\n } else if (entity.firstName) {\n return entity.firstName;\n } else if (entity.lastName) {\n return entity.lastName;\n } else {\n return '';\n }\n } else if (entity instanceof constructors.Chat || entity instanceof constructors.Channel) {\n return entity.title;\n }\n return '';\n}\n\n/**\n * check if a given item is an array like or not\n * @param item\n * @returns {boolean}\n */\n\n/* CONTEST\nDuplicate ?\nfunction isListLike(item) {\n return (\n Array.isArray(item) ||\n (!!item &&\n typeof item === 'object' &&\n typeof (item.length) === 'number' &&\n (item.length === 0 ||\n (item.length > 0 &&\n (item.length - 1) in item)\n )\n )\n )\n}\n*/\n/**\n * Returns the appropriate DC based on the id\n * @param dcId the id of the DC.\n * @param downloadDC whether to use -1 DCs or not\n * (These only support downloading/uploading and not creating a new AUTH key)\n * @return {{port: number, ipAddress: string, id: number}}\n */\nfunction getDC(dcId, downloadDC = false) {\n // TODO Move to external config\n switch (dcId) {\n case 1:\n return {\n id: 1,\n ipAddress: `zws1${downloadDC ? '-1' : ''}.web.telegram.org`,\n port: 443,\n };\n case 2:\n return {\n id: 2,\n ipAddress: `zws2${downloadDC ? '-1' : ''}.web.telegram.org`,\n port: 443,\n };\n case 3:\n return {\n id: 3,\n ipAddress: `zws3${downloadDC ? '-1' : ''}.web.telegram.org`,\n port: 443,\n };\n case 4:\n return {\n id: 4,\n ipAddress: `zws4${downloadDC ? '-1' : ''}.web.telegram.org`,\n port: 443,\n };\n case 5:\n return {\n id: 5,\n ipAddress: `zws5${downloadDC ? '-1' : ''}.web.telegram.org`,\n port: 443,\n };\n default:\n throw new Error(`Cannot find the DC with the ID of ${dcId}`);\n }\n // TODO chose based on current connection method\n /*\n if (!this._config) {\n this._config = await this.invoke(new requests.help.GetConfig())\n }\n if (cdn && !this._cdnConfig) {\n this._cdnConfig = await this.invoke(new requests.help.GetCdnConfig())\n for (const pk of this._cdnConfig.publicKeys) {\n addKey(pk.publicKey)\n }\n }\n for (const DC of this._config.dcOptions) {\n if (DC.id === dcId && Boolean(DC.ipv6) === this._useIPV6 && Boolean(DC.cdn) === cdn) {\n return DC\n }\n } */\n}\n\nmodule.exports = {\n getMessageId,\n // _getEntityPair,\n // getInputMessage,\n // getInputDialog,\n // getInputUser,\n // getInputChannel,\n getInputPeer,\n // parsePhone,\n // parseUsername,\n // getPeer,\n // getPeerId,\n getDisplayName,\n // resolveId,\n // isListLike,\n getAppropriatedPartSize,\n // getInputLocation,\n strippedPhotoToJpg,\n getDC,\n};\n","module.exports = '0.0.2';\n","import TelegramClient from './TelegramClient';\n// eslint-disable-next-line import/no-named-default\nimport { default as Api } from '../tl/api';\nimport { generateRandomBytes } from '../Helpers';\nimport { computeCheck, computeDigest } from '../Password';\nimport errors from '../errors';\n\nexport interface TwoFaParams {\n isCheckPassword?: boolean;\n currentPassword?: string;\n newPassword?: string;\n hint?: string;\n email?: string;\n emailCodeCallback?: (length: number) => Promise<string>;\n onEmailCodeError?: (err: Error) => void;\n}\n\n/**\n * Changes the 2FA settings of the logged in user.\n Note that this method may be *incredibly* slow depending on the\n prime numbers that must be used during the process to make sure\n that everything is safe.\n\n Has no effect if both current and new password are omitted.\n\n * @param client: The telegram client instance\n * @param isCheckPassword: Must be ``true`` if you want to check the current password\n * @param currentPassword: The current password, to authorize changing to ``new_password``.\n Must be set if changing existing 2FA settings.\n Must **not** be set if 2FA is currently disabled.\n Passing this by itself will remove 2FA (if correct).\n * @param newPassword: The password to set as 2FA.\n If 2FA was already enabled, ``currentPassword`` **must** be set.\n Leaving this blank or `undefined` will remove the password.\n * @param hint: Hint to be displayed by Telegram when it asks for 2FA.\n Must be set when changing or creating a new password.\n Has no effect if ``newPassword`` is not set.\n * @param email: Recovery and verification email. If present, you must also\n set `emailCodeCallback`, else it raises an Error.\n * @param emailCodeCallback: If an email is provided, a callback that returns the code sent\n to it must also be set. This callback may be asynchronous.\n It should return a string with the code. The length of the\n code will be passed to the callback as an input parameter.\n\n If the callback returns an invalid code, it will raise an rpc error with the message\n ``CODE_INVALID``\n\n * @returns Promise<void>\n * @throws this method can throw:\n \"PASSWORD_HASH_INVALID\" if you entered a wrong password (or set it to undefined).\n \"EMAIL_INVALID\" if the entered email is wrong\n \"EMAIL_HASH_EXPIRED\" if the user took too long to verify their email\n */\nexport async function updateTwoFaSettings(\n client: TelegramClient,\n {\n isCheckPassword,\n currentPassword,\n newPassword,\n hint = '',\n email,\n emailCodeCallback,\n onEmailCodeError,\n }: TwoFaParams,\n) {\n if (!newPassword && !currentPassword) {\n throw new Error('Neither `currentPassword` nor `newPassword` is present');\n }\n\n if (email && !(emailCodeCallback && onEmailCodeError)) {\n throw new Error('`email` present without `emailCodeCallback` and `onEmailCodeError`');\n }\n\n const pwd = await client.invoke(new Api.account.GetPassword());\n\n if (!(pwd.newAlgo instanceof Api.PasswordKdfAlgoUnknown)) {\n pwd.newAlgo.salt1 = Buffer.concat([pwd.newAlgo.salt1, generateRandomBytes(32)]);\n }\n if (!pwd.hasPassword && currentPassword) {\n currentPassword = undefined;\n }\n\n const password = currentPassword ? await computeCheck(pwd, currentPassword!) : new Api.InputCheckPasswordEmpty();\n\n if (isCheckPassword) {\n await client.invoke(new Api.auth.CheckPassword({ password }));\n return;\n }\n\n try {\n await client.invoke(new Api.account.UpdatePasswordSettings({\n password,\n newSettings: new Api.account.PasswordInputSettings({\n newAlgo: pwd.newAlgo,\n newPasswordHash: newPassword ? await computeDigest(pwd.newAlgo, newPassword) : Buffer.alloc(0),\n hint,\n email,\n // not explained what it does and it seems to always be set to empty in tdesktop\n newSecureSettings: undefined,\n }),\n }));\n } catch (e) {\n if (e instanceof errors.EmailUnconfirmedError) {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n try {\n const code = await emailCodeCallback!(e.codeLength);\n\n if (!code) {\n throw new Error('Code is empty');\n }\n\n await client.invoke(new Api.account.ConfirmPasswordEmail({ code }));\n break;\n } catch (err) {\n onEmailCodeError!(err);\n }\n }\n } else {\n throw e;\n }\n }\n}\n","const os = require('os');\nconst Logger = require('../extensions/Logger');\nconst { sleep } = require('../Helpers');\nconst errors = require('../errors');\nconst MemorySession = require('../sessions/Memory');\nconst Helpers = require('../Helpers');\nconst utils = require('../Utils');\nconst Session = require('../sessions/Abstract');\nconst { LAYER } = require('../tl/AllTLObjects');\nconst {\n constructors,\n requests,\n} = require('../tl');\nconst MTProtoSender = require('../network/MTProtoSender');\nconst { ConnectionTCPObfuscated } = require('../network/connection/TCPObfuscated');\nconst {\n authFlow,\n checkAuthorization,\n} = require('./auth');\nconst { downloadFile } = require('./downloadFile');\nconst { uploadFile } = require('./uploadFile');\nconst { updateTwoFaSettings } = require('./2fa');\n\nconst DEFAULT_DC_ID = 2;\nconst WEBDOCUMENT_DC_ID = 4;\nconst DEFAULT_IPV4_IP = 'zws2.web.telegram.org';\nconst DEFAULT_IPV6_IP = '[2001:67c:4e8:f002::a]';\nconst EXPORTED_SENDER_RECONNECT_TIMEOUT = 1000; // 1 sec\nconst EXPORTED_SENDER_RELEASE_TIMEOUT = 30000; // 30 sec\nconst WEBDOCUMENT_REQUEST_PART_SIZE = 131072; // 128kb\n\nconst PING_INTERVAL = 3000; // 3 sec\nconst PING_TIMEOUT = 5000; // 5 sec\nconst PING_FAIL_ATTEMPTS = 3;\nconst PING_FAIL_INTERVAL = 100; // ms\nconst PING_DISCONNECT_DELAY = 60000; // 1 min\n\n// All types\nconst sizeTypes = ['w', 'y', 'd', 'x', 'c', 'm', 'b', 'a', 's'];\n\n\nclass TelegramClient {\n static DEFAULT_OPTIONS = {\n connection: ConnectionTCPObfuscated,\n useIPV6: false,\n proxy: undefined,\n timeout: 10,\n requestRetries: 5,\n connectionRetries: Infinity,\n retryDelay: 1000,\n autoReconnect: true,\n sequentialUpdates: false,\n floodSleepLimit: 60,\n deviceModel: undefined,\n systemVersion: undefined,\n appVersion: undefined,\n langCode: 'en',\n systemLangCode: 'en',\n baseLogger: 'gramjs',\n useWSS: false,\n additionalDcsDisabled: false,\n };\n\n /**\n *\n * @param session {StringSession|LocalStorageSession}\n * @param apiId\n * @param apiHash\n * @param opts\n */\n constructor(session, apiId, apiHash, opts = TelegramClient.DEFAULT_OPTIONS) {\n if (!apiId || !apiHash) {\n throw Error('Your API ID or Hash are invalid. Please read \"Requirements\" on README.md');\n }\n const args = { ...TelegramClient.DEFAULT_OPTIONS, ...opts };\n this.apiId = apiId;\n this.apiHash = apiHash;\n this._useIPV6 = args.useIPV6;\n // this._entityCache = new Set()\n if (typeof args.baseLogger === 'string') {\n this._log = new Logger();\n } else {\n this._log = args.baseLogger;\n }\n // Determine what session we will use\n if (typeof session === 'string' || !session) {\n try {\n throw new Error('not implemented');\n } catch (e) {\n session = new MemorySession();\n }\n } else if (!(session instanceof Session)) {\n throw new Error('The given session must be str or a session instance');\n }\n\n this.floodSleepLimit = args.floodSleepLimit;\n this._eventBuilders = [];\n\n this._phoneCodeHash = {};\n this.session = session;\n // this._entityCache = EntityCache();\n this.apiId = parseInt(apiId, 10);\n this.apiHash = apiHash;\n\n this._requestRetries = args.requestRetries;\n this._connectionRetries = args.connectionRetries;\n this._retryDelay = args.retryDelay || 0;\n if (args.proxy) {\n this._log.warn('proxies are not supported');\n }\n this._proxy = args.proxy;\n this._timeout = args.timeout;\n this._autoReconnect = args.autoReconnect;\n\n this._connection = args.connection;\n // TODO add proxy support\n\n this._floodWaitedRequests = {};\n\n this._initWith = (x) => {\n return new requests.InvokeWithLayer({\n layer: LAYER,\n query: new requests.InitConnection({\n apiId: this.apiId,\n deviceModel: args.deviceModel || os.type()\n .toString() || 'Unknown',\n systemVersion: args.systemVersion || os.release()\n .toString() || '1.0',\n appVersion: args.appVersion || '1.0',\n langCode: args.langCode,\n langPack: '', // this should be left empty.\n systemLangCode: args.systemLangCode,\n query: x,\n proxy: undefined, // no proxies yet.\n }),\n });\n };\n\n this._args = args;\n // These will be set later\n this._config = undefined;\n this.phoneCodeHashes = [];\n this._exportedSenderPromises = {};\n this._exportedSenderReleaseTimeouts = {};\n this._additionalDcsDisabled = args.additionalDcsDisabled;\n this._loopStarted = false;\n this._reconnecting = false;\n this._destroyed = false;\n }\n\n\n // region Connecting\n\n /**\n * Connects to the Telegram servers, executing authentication if required.\n * Note that authenticating to the Telegram servers is not the same as authenticating\n * the app, which requires to send a code first.\n * @returns {Promise<void>}\n */\n async connect() {\n await this._initSession();\n\n if (this._sender === undefined) {\n // only init sender once to avoid multiple loops.\n this._sender = new MTProtoSender(this.session.getAuthKey(), {\n logger: this._log,\n dcId: this.session.dcId,\n retries: this._connectionRetries,\n delay: this._retryDelay,\n autoReconnect: this._autoReconnect,\n connectTimeout: this._timeout,\n authKeyCallback: this._authKeyCallback.bind(this),\n updateCallback: this._handleUpdate.bind(this),\n isMainSender: true,\n });\n }\n // set defaults vars\n this._sender.userDisconnected = false;\n this._sender._user_connected = false;\n this._sender._reconnecting = false;\n this._sender._disconnected = true;\n\n const connection = new this._connection(\n this.session.serverAddress, this.session.port, this.session.dcId, this._log,\n );\n\n const newConnection = await this._sender.connect(connection);\n if (!newConnection) {\n // we're already connected so no need to reset auth key.\n if (!this._loopStarted) {\n this._updateLoop();\n this._loopStarted = true;\n }\n return;\n }\n\n this.session.setAuthKey(this._sender.authKey);\n await this._sender.send(this._initWith(\n new requests.help.GetConfig({}),\n ));\n\n if (!this._loopStarted) {\n this._updateLoop();\n this._loopStarted = true;\n }\n this._reconnecting = false;\n }\n\n async _initSession() {\n await this.session.load();\n\n if (!this.session.serverAddress || (this.session.serverAddress.includes(':') !== this._useIPV6)) {\n this.session.setDC(DEFAULT_DC_ID, this._useIPV6\n ? DEFAULT_IPV6_IP : DEFAULT_IPV4_IP, this._args.useWSS ? 443 : 80);\n }\n }\n\n async _updateLoop() {\n while (!this._destroyed) {\n await Helpers.sleep(PING_INTERVAL);\n if (this._reconnecting) {\n continue;\n }\n\n try {\n await attempts(() => {\n return timeout(this._sender.send(new requests.PingDelayDisconnect({\n pingId: Helpers.getRandomInt(Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER),\n disconnectDelay: PING_DISCONNECT_DELAY,\n })), PING_TIMEOUT);\n }, PING_FAIL_ATTEMPTS, PING_FAIL_INTERVAL);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n if (this._reconnecting) {\n continue;\n }\n\n await this.disconnect();\n await this.connect();\n }\n\n // We need to send some content-related request at least hourly\n // for Telegram to keep delivering updates, otherwise they will\n // just stop even if we're connected. Do so every 30 minutes.\n\n // TODO Call getDifference instead since it's more relevant\n if (new Date().getTime() - this._lastRequest > 30 * 60 * 1000) {\n try {\n await this.invoke(new requests.updates.GetState());\n } catch (e) {\n // we don't care about errors here\n }\n }\n }\n await this.disconnect();\n }\n\n /**\n * Disconnects from the Telegram server\n * @returns {Promise<void>}\n */\n async disconnect() {\n if (this._sender) {\n await this._sender.disconnect();\n }\n\n await Promise.all(\n Object.values(this._exportedSenderPromises)\n .map((promise) => {\n return promise && promise.then((sender) => {\n if (sender) {\n return sender.disconnect();\n }\n return undefined;\n });\n }),\n );\n\n this._exportedSenderPromises = {};\n }\n\n /**\n * Disconnects all senders and removes all handlers\n * @returns {Promise<void>}\n */\n async destroy() {\n this._destroyed = true;\n\n try {\n await this.disconnect();\n } catch (err) {\n // Do nothing\n }\n\n this.session.delete();\n this._eventBuilders = [];\n }\n\n async _switchDC(newDc) {\n this._log.info(`Reconnecting to new data center ${newDc}`);\n const DC = utils.getDC(newDc);\n this.session.setDC(newDc, DC.ipAddress, DC.port);\n // authKey's are associated with a server, which has now changed\n // so it's not valid anymore. Set to None to force recreating it.\n await this._sender.authKey.setKey(undefined);\n this.session.setAuthKey(undefined);\n this._reconnecting = true;\n await this.disconnect();\n return this.connect();\n }\n\n _authKeyCallback(authKey, dcId) {\n this.session.setAuthKey(authKey, dcId);\n }\n\n // endregion\n // export region\n\n async _cleanupExportedSender(dcId) {\n if (this.session.dcId !== dcId) {\n this.session.setAuthKey(undefined, dcId);\n }\n const sender = await this._exportedSenderPromises[dcId];\n this._exportedSenderPromises[dcId] = undefined;\n await sender.disconnect();\n }\n\n async _connectSender(sender, dcId) {\n // if we don't already have an auth key we want to use normal DCs not -1\n const dc = utils.getDC(dcId, !!sender.authKey.getKey());\n\n while (true) {\n try {\n await sender.connect(new this._connection(\n dc.ipAddress,\n dc.port,\n dcId,\n this._log,\n ));\n\n if (this.session.dcId !== dcId && !sender._authenticated) {\n this._log.info(`Exporting authorization for data center ${dc.ipAddress}`);\n const auth = await this.invoke(new requests.auth.ExportAuthorization({ dcId }));\n const req = this._initWith(new requests.auth.ImportAuthorization({\n id: auth.id,\n bytes: auth.bytes,\n }));\n await sender.send(req);\n sender._authenticated = true;\n }\n sender.dcId = dcId;\n sender.userDisconnected = false;\n\n return sender;\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(err);\n\n await Helpers.sleep(1000);\n await sender.disconnect();\n }\n }\n }\n\n async _borrowExportedSender(dcId, shouldReconnect, existingSender) {\n if (this._additionalDcsDisabled) {\n return undefined;\n }\n\n if (!this._exportedSenderPromises[dcId] || shouldReconnect) {\n this._exportedSenderPromises[dcId] = this._connectSender(\n existingSender || this._createExportedSender(dcId),\n dcId,\n );\n }\n\n let sender;\n try {\n sender = await this._exportedSenderPromises[dcId];\n\n if (!sender.isConnected()) {\n if (sender.isConnecting) {\n await Helpers.sleep(EXPORTED_SENDER_RECONNECT_TIMEOUT);\n return this._borrowExportedSender(dcId, false, sender);\n } else {\n return this._borrowExportedSender(dcId, true, sender);\n }\n }\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(err);\n\n return this._borrowExportedSender(dcId, true);\n }\n\n if (this._exportedSenderReleaseTimeouts[dcId]) {\n clearTimeout(this._exportedSenderReleaseTimeouts[dcId]);\n this._exportedSenderReleaseTimeouts[dcId] = undefined;\n }\n\n this._exportedSenderReleaseTimeouts[dcId] = setTimeout(() => {\n this._exportedSenderReleaseTimeouts[dcId] = undefined;\n sender.disconnect();\n }, EXPORTED_SENDER_RELEASE_TIMEOUT);\n\n return sender;\n }\n\n _createExportedSender(dcId) {\n return new MTProtoSender(this.session.getAuthKey(dcId), {\n logger: this._log,\n dcId,\n retries: this._connectionRetries,\n delay: this._retryDelay,\n autoReconnect: this._autoReconnect,\n connectTimeout: this._timeout,\n authKeyCallback: this._authKeyCallback.bind(this),\n isMainSender: dcId === this.session.dcId,\n onConnectionBreak: this._cleanupExportedSender.bind(this),\n });\n }\n\n getSender(dcId) {\n return dcId ? this._borrowExportedSender(dcId) : Promise.resolve(this._sender);\n }\n\n // end region\n\n // download region\n\n /**\n * Complete flow to download a file.\n * @param inputLocation {constructors.InputFileLocation}\n * @param [args[partSizeKb] {number}]\n * @param [args[fileSize] {number}]\n * @param [args[progressCallback] {Function}]\n * @param [args[start] {number}]\n * @param [args[end] {number}]\n * @param [args[dcId] {number}]\n * @param [args[workers] {number}]\n * @returns {Promise<Buffer>}\n */\n downloadFile(inputLocation, args = {}) {\n return downloadFile(this, inputLocation, args);\n }\n\n downloadMedia(messageOrMedia, args) {\n let media;\n if (messageOrMedia instanceof constructors.Message) {\n media = messageOrMedia.media;\n } else {\n media = messageOrMedia;\n }\n if (typeof media === 'string') {\n throw new Error('not implemented');\n }\n\n if (media instanceof constructors.MessageMediaWebPage) {\n if (media.webpage instanceof constructors.WebPage) {\n media = media.webpage.document || media.webpage.photo;\n }\n }\n if (media instanceof constructors.MessageMediaPhoto || media instanceof constructors.Photo) {\n return this._downloadPhoto(media, args);\n } else if (media instanceof constructors.MessageMediaDocument || media instanceof constructors.Document) {\n return this._downloadDocument(media, args);\n } else if (media instanceof constructors.MessageMediaContact) {\n return this._downloadContact(media, args);\n } else if (media instanceof constructors.WebDocument || media instanceof constructors.WebDocumentNoProxy) {\n return this._downloadWebDocument(media, args);\n }\n return undefined;\n }\n\n downloadProfilePhoto(entity, isBig = false) {\n // ('User', 'Chat', 'UserFull', 'ChatFull')\n const ENTITIES = [0x2da17977, 0xc5af5d94, 0x1f4661b9, 0xd49a2697];\n // ('InputPeer', 'InputUser', 'InputChannel')\n // const INPUTS = [0xc91c90b6, 0xe669bf46, 0x40f202fd]\n // Todo account for input methods\n const sizeType = isBig ? 'x' : 'm';\n let photo;\n if (!(ENTITIES.includes(entity.SUBCLASS_OF_ID))) {\n photo = entity;\n } else {\n if (!entity.photo) {\n // Special case: may be a ChatFull with photo:Photo\n if (!entity.chatPhoto) {\n return undefined;\n }\n\n return this._downloadPhoto(\n entity.chatPhoto, { sizeType },\n );\n }\n photo = entity.photo;\n }\n\n let dcId;\n let loc;\n if (photo instanceof constructors.UserProfilePhoto || photo instanceof constructors.ChatPhoto) {\n dcId = photo.dcId;\n loc = new constructors.InputPeerPhotoFileLocation({\n peer: utils.getInputPeer(entity),\n photoId: photo.photoId,\n big: isBig,\n });\n } else {\n // It doesn't make any sense to check if `photo` can be used\n // as input location, because then this method would be able\n // to \"download the profile photo of a message\", i.e. its\n // media which should be done with `download_media` instead.\n return undefined;\n }\n return this.downloadFile(loc, {\n dcId,\n });\n }\n\n downloadStickerSetThumb(stickerSet) {\n if (!stickerSet.thumbs || !stickerSet.thumbs.length) {\n return undefined;\n }\n\n const { thumbVersion } = stickerSet;\n return this.downloadFile(\n new constructors.InputStickerSetThumb({\n stickerset: new constructors.InputStickerSetID({\n id: stickerSet.id,\n accessHash: stickerSet.accessHash,\n }),\n thumbVersion,\n }),\n { dcId: stickerSet.thumbDcId },\n );\n }\n\n _pickFileSize(sizes, sizeType) {\n if (!sizeType || !sizes || !sizes.length) {\n return undefined;\n }\n const indexOfSize = sizeTypes.indexOf(sizeType);\n let size;\n for (let i = indexOfSize; i < sizeTypes.length; i++) {\n size = sizes.find((s) => s.type === sizeTypes[i]);\n if (size) {\n return size;\n }\n }\n return undefined;\n }\n\n\n _downloadCachedPhotoSize(size) {\n // No need to download anything, simply write the bytes\n let data;\n if (size instanceof constructors.PhotoStrippedSize) {\n data = utils.strippedPhotoToJpg(size.bytes);\n } else {\n data = size.bytes;\n }\n return data;\n }\n\n _downloadPhoto(photo, args) {\n if (photo instanceof constructors.MessageMediaPhoto) {\n photo = photo.photo;\n }\n if (!(photo instanceof constructors.Photo)) {\n return undefined;\n }\n const size = this._pickFileSize(photo.sizes, args.sizeType);\n if (!size || (size instanceof constructors.PhotoSizeEmpty)) {\n return undefined;\n }\n\n if (size instanceof constructors.PhotoCachedSize || size instanceof constructors.PhotoStrippedSize) {\n return this._downloadCachedPhotoSize(size);\n }\n return this.downloadFile(\n new constructors.InputPhotoFileLocation({\n id: photo.id,\n accessHash: photo.accessHash,\n fileReference: photo.fileReference,\n thumbSize: size.type,\n }),\n {\n dcId: photo.dcId,\n fileSize: size.size,\n progressCallback: args.progressCallback,\n },\n );\n }\n\n _downloadDocument(doc, args) {\n if (doc instanceof constructors.MessageMediaDocument) {\n doc = doc.document;\n }\n if (!(doc instanceof constructors.Document)) {\n return undefined;\n }\n\n let size;\n if (args.sizeType) {\n size = doc.thumbs ? this._pickFileSize(doc.thumbs, args.sizeType) : undefined;\n if (!size && doc.mimeType.startsWith('video/')) {\n return undefined;\n }\n\n if (size && (size instanceof constructors.PhotoCachedSize\n || size instanceof constructors.PhotoStrippedSize)) {\n return this._downloadCachedPhotoSize(size);\n }\n }\n\n return this.downloadFile(\n new constructors.InputDocumentFileLocation({\n id: doc.id,\n accessHash: doc.accessHash,\n fileReference: doc.fileReference,\n thumbSize: size ? size.type : '',\n }),\n {\n fileSize: size ? size.size : doc.size,\n progressCallback: args.progressCallback,\n start: args.start,\n end: args.end,\n dcId: doc.dcId,\n workers: args.workers,\n },\n );\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _downloadContact(media, args) {\n throw new Error('not implemented');\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async _downloadWebDocument(media) {\n try {\n const buff = [];\n let offset = 0;\n while (true) {\n const downloaded = new requests.upload.GetWebFile({\n location: new constructors.InputWebFileLocation({\n url: media.url,\n accessHash: media.accessHash,\n }),\n offset,\n limit: WEBDOCUMENT_REQUEST_PART_SIZE,\n });\n const sender = await this._borrowExportedSender(WEBDOCUMENT_DC_ID);\n const res = await sender.send(downloaded);\n offset += 131072;\n if (res.bytes.length) {\n buff.push(res.bytes);\n if (res.bytes.length < WEBDOCUMENT_REQUEST_PART_SIZE) {\n break;\n }\n } else {\n break;\n }\n }\n return Buffer.concat(buff);\n } catch (e) {\n // the file is no longer saved in telegram's cache.\n if (e.message === 'WEBFILE_NOT_AVAILABLE') {\n return Buffer.alloc(0);\n } else {\n throw e;\n }\n }\n }\n\n // region Invoking Telegram request\n /**\n * Invokes a MTProtoRequest (sends and receives it) and returns its result\n * @param request\n * @returns {Promise}\n */\n\n async invoke(request) {\n if (request.classType !== 'request') {\n throw new Error('You can only invoke MTProtoRequests');\n }\n // This causes issues for now because not enough utils\n // await request.resolve(this, utils)\n\n\n this._lastRequest = new Date().getTime();\n let attempt = 0;\n for (attempt = 0; attempt < this._requestRetries; attempt++) {\n const promise = this._sender.sendWithInvokeSupport(request);\n try {\n const result = await promise.promise;\n return result;\n } catch (e) {\n if (e instanceof errors.ServerError || e.message === 'RPC_CALL_FAIL'\n || e.message === 'RPC_MCGET_FAIL') {\n this._log.warn(`Telegram is having internal issues ${e.constructor.name}`);\n await sleep(2000);\n } else if (e instanceof errors.FloodWaitError || e instanceof errors.FloodTestPhoneWaitError) {\n if (e.seconds <= this.floodSleepLimit) {\n this._log.info(`Sleeping for ${e.seconds}s on flood wait`);\n await sleep(e.seconds * 1000);\n } else {\n throw e;\n }\n } else if (e instanceof errors.PhoneMigrateError || e instanceof errors.NetworkMigrateError\n || e instanceof errors.UserMigrateError) {\n this._log.info(`Phone migrated to ${e.newDc}`);\n const shouldRaise = e instanceof errors.PhoneMigrateError\n || e instanceof errors.NetworkMigrateError;\n if (shouldRaise && await checkAuthorization(this)) {\n throw e;\n }\n await this._switchDC(e.newDc);\n } else if (e instanceof errors.MsgWaitError) {\n // we need to resend this after the old one was confirmed.\n await promise.isReady();\n } else {\n throw e;\n }\n }\n }\n throw new Error(`Request was unsuccessful ${attempt} time(s)`);\n }\n\n async getMe() {\n try {\n return (await this.invoke(new requests.users\n .GetUsers({ id: [new constructors.InputUserSelf()] })))[0];\n } catch (e) {\n this._log.warn('error while getting me');\n this._log.warn(e);\n }\n return undefined;\n }\n\n async start(authParams) {\n if (!this.isConnected()) {\n await this.connect();\n }\n\n if (await checkAuthorization(this)) {\n return;\n }\n\n const apiCredentials = {\n apiId: this.apiId,\n apiHash: this.apiHash,\n };\n\n await authFlow(this, apiCredentials, authParams);\n }\n\n uploadFile(fileParams) {\n return uploadFile(this, fileParams);\n }\n\n updateTwoFaSettings(params) {\n return updateTwoFaSettings(this, params);\n }\n\n // event region\n addEventHandler(callback, event) {\n this._eventBuilders.push([event, callback]);\n }\n\n _handleUpdate(update) {\n // this.session.processEntities(update)\n // this._entityCache.add(update)\n\n if (update instanceof constructors.Updates || update instanceof constructors.UpdatesCombined) {\n // TODO deal with entities\n const entities = [];\n for (const x of [...update.users, ...update.chats]) {\n entities.push(x);\n }\n for (const u of update.updates) {\n this._processUpdate(u, update.updates, entities);\n }\n } else if (update instanceof constructors.UpdateShort) {\n this._processUpdate(update.update, undefined);\n } else {\n this._processUpdate(update, undefined);\n }\n // TODO add caching\n // this._stateCache.update(update)\n }\n\n _processUpdate(update, others, entities) {\n update._entities = entities || [];\n const args = {\n update,\n others,\n };\n this._dispatchUpdate(args);\n }\n\n\n // endregion\n\n // region private methods\n\n /**\n Gets a full entity from the given string, which may be a phone or\n a username, and processes all the found entities on the session.\n The string may also be a user link, or a channel/chat invite link.\n\n This method has the side effect of adding the found users to the\n session database, so it can be queried later without API calls,\n if this option is enabled on the session.\n\n Returns the found entity, or raises TypeError if not found.\n * @param string {string}\n * @returns {Promise<void>}\n * @private\n */\n /* CONTEST\n async _getEntityFromString(string) {\n const phone = utils.parsePhone(string)\n if (phone) {\n try {\n for (const user of (await this.invoke(\n new requests.contacts.GetContacts(0))).users) {\n if (user.phone === phone) {\n return user\n }\n }\n } catch (e) {\n if (e.message === 'BOT_METHOD_INVALID') {\n throw new Error('Cannot get entity by phone number as a ' +\n 'bot (try using integer IDs, not strings)')\n }\n throw e\n }\n } else if (['me', 'this'].includes(string.toLowerCase())) {\n return this.getMe()\n } else {\n const { username, isJoinChat } = utils.parseUsername(string)\n if (isJoinChat) {\n const invite = await this.invoke(new requests.messages.CheckChatInvite({\n 'hash': username,\n }))\n if (invite instanceof constructors.ChatInvite) {\n throw new Error('Cannot get entity from a channel (or group) ' +\n 'that you are not part of. Join the group and retry',\n )\n } else if (invite instanceof constructors.ChatInviteAlready) {\n return invite.chat\n }\n } else if (username) {\n try {\n const result = await this.invoke(\n new requests.contacts.ResolveUsername(username))\n const pid = utils.getPeerId(result.peer, false)\n if (result.peer instanceof constructors.PeerUser) {\n for (const x of result.users) {\n if (x.id === pid) {\n return x\n }\n }\n } else {\n for (const x of result.chats) {\n if (x.id === pid) {\n return x\n }\n }\n }\n } catch (e) {\n if (e.message === 'USERNAME_NOT_OCCUPIED') {\n throw new Error(`No user has \"${username}\" as username`)\n }\n throw e\n }\n }\n }\n throw new Error(`Cannot find any entity corresponding to \"${string}\"`)\n }\n */\n // endregion\n\n\n // users region\n /**\n Turns the given entity into its input entity version.\n\n Most requests use this kind of :tl:`InputPeer`, so this is the most\n suitable call to make for those cases. **Generally you should let the\n library do its job** and don't worry about getting the input entity\n first, but if you're going to use an entity often, consider making the\n call:\n\n Arguments\n entity (`str` | `int` | :tl:`Peer` | :tl:`InputPeer`):\n If a username or invite link is given, **the library will\n use the cache**. This means that it's possible to be using\n a username that *changed* or an old invite link (this only\n happens if an invite link for a small group chat is used\n after it was upgraded to a mega-group).\n\n If the username or ID from the invite link is not found in\n the cache, it will be fetched. The same rules apply to phone\n numbers (``'+34 123456789'``) from people in your contact list.\n\n If an exact name is given, it must be in the cache too. This\n is not reliable as different people can share the same name\n and which entity is returned is arbitrary, and should be used\n only for quick tests.\n\n If a positive integer ID is given, the entity will be searched\n in cached users, chats or channels, without making any call.\n\n If a negative integer ID is given, the entity will be searched\n exactly as either a chat (prefixed with ``-``) or as a channel\n (prefixed with ``-100``).\n\n If a :tl:`Peer` is given, it will be searched exactly in the\n cache as either a user, chat or channel.\n\n If the given object can be turned into an input entity directly,\n said operation will be done.\n\n Unsupported types will raise ``TypeError``.\n\n If the entity can't be found, ``ValueError`` will be raised.\n\n Returns\n :tl:`InputPeerUser`, :tl:`InputPeerChat` or :tl:`InputPeerChannel`\n or :tl:`InputPeerSelf` if the parameter is ``'me'`` or ``'self'``.\n\n If you need to get the ID of yourself, you should use\n `get_me` with ``input_peer=True``) instead.\n\n Example\n .. code-block:: python\n\n // If you're going to use \"username\" often in your code\n // (make a lot of calls), consider getting its input entity\n // once, and then using the \"user\" everywhere instead.\n user = await client.get_input_entity('username')\n\n // The same applies to IDs, chats or channels.\n chat = await client.get_input_entity(-123456789)\n\n * @param peer\n * @returns {Promise<>}\n */\n\n /* CONTEST\n async getInputEntity(peer) {\n // Short-circuit if the input parameter directly maps to an InputPeer\n try {\n return utils.getInputPeer(peer)\n // eslint-disable-next-line no-empty\n } catch (e) {\n }\n // Next in priority is having a peer (or its ID) cached in-memory\n try {\n // 0x2d45687 == crc32(b'Peer')\n if (typeof peer === 'number' || peer.SUBCLASS_OF_ID === 0x2d45687) {\n if (this._entityCache.has(peer)) {\n return this._entityCache[peer]\n }\n }\n // eslint-disable-next-line no-empty\n } catch (e) {\n }\n // Then come known strings that take precedence\n if (['me', 'this'].includes(peer)) {\n return new constructors.InputPeerSelf()\n }\n // No InputPeer, cached peer, or known string. Fetch from disk cache\n try {\n return this.session.getInputEntity(peer)\n // eslint-disable-next-line no-empty\n } catch (e) {\n }\n // Only network left to try\n if (typeof peer === 'string') {\n return utils.getInputPeer(await this._getEntityFromString(peer))\n }\n // If we're a bot and the user has messaged us privately users.getUsers\n // will work with accessHash = 0. Similar for channels.getChannels.\n // If we're not a bot but the user is in our contacts, it seems to work\n // regardless. These are the only two special-cased requests.\n peer = utils.getPeer(peer)\n if (peer instanceof constructors.PeerUser) {\n const users = await this.invoke(new requests.users.GetUsers({\n id: [new constructors.InputUser({\n userId: peer.userId,\n accessHash: 0,\n })],\n }))\n if (users && !(users[0] instanceof constructors.UserEmpty)) {\n // If the user passed a valid ID they expect to work for\n // channels but would be valid for users, we get UserEmpty.\n // Avoid returning the invalid empty input peer for that.\n //\n // We *could* try to guess if it's a channel first, and if\n // it's not, work as a chat and try to validate it through\n // another request, but that becomes too much work.\n return utils.getInputPeer(users[0])\n }\n } else if (peer instanceof constructors.PeerChat) {\n return new constructors.InputPeerChat({\n chatId: peer.chatId,\n })\n } else if (peer instanceof constructors.PeerChannel) {\n try {\n const channels = await this.invoke(new requests.channels.GetChannels({\n id: [new constructors.InputChannel({\n channelId: peer.channelId,\n accessHash: 0,\n })],\n }))\n\n return utils.getInputPeer(channels.chats[0])\n // eslint-disable-next-line no-empty\n } catch (e) {\n console.log(e)\n }\n }\n throw new Error(`Could not find the input entity for ${peer.id || peer.channelId || peer.chatId || peer.userId}.\n Please read https://` +\n 'docs.telethon.dev/en/latest/concepts/entities.html to' +\n ' find out more details.',\n )\n }\n */\n async _dispatchUpdate(args = {\n update: undefined,\n others: undefined,\n channelId: undefined,\n ptsDate: undefined,\n }) {\n for (const [builder, callback] of this._eventBuilders) {\n const event = builder.build(args.update);\n if (event) {\n await callback(event);\n }\n }\n }\n\n isConnected() {\n if (this._sender) {\n if (this._sender.isConnected()) {\n return true;\n }\n }\n return false;\n }\n}\n\nfunction timeout(promise, ms) {\n return Promise.race([\n promise,\n Helpers.sleep(ms)\n .then(() => Promise.reject(new Error('TIMEOUT'))),\n ]);\n}\n\nasync function attempts(cb, times, pause) {\n for (let i = 0; i < times; i++) {\n try {\n // We need to `return await` here so it can be caught locally\n return await cb();\n } catch (err) {\n if (i === times - 1) {\n throw err;\n }\n\n await Helpers.sleep(pause);\n }\n }\n return undefined;\n}\n\nmodule.exports = TelegramClient;\n","// eslint-disable-next-line import/no-named-default\nimport { default as Api } from '../tl/api';\nimport TelegramClient from './TelegramClient';\nimport utils from '../Utils';\nimport { sleep } from '../Helpers';\nimport { computeCheck as computePasswordSrpCheck } from '../Password';\n\nexport interface UserAuthParams {\n phoneNumber: string | (() => Promise<string>);\n phoneCode: (isCodeViaApp?: boolean) => Promise<string>;\n password: (hint?: string) => Promise<string>;\n firstAndLastNames: () => Promise<[string, string?]>;\n qrCode: (qrCode: { token: Buffer; expires: number }) => Promise<void>;\n onError: (err: Error) => void;\n forceSMS?: boolean;\n initialMethod?: 'phoneNumber' | 'qrCode';\n}\n\nexport interface BotAuthParams {\n botAuthToken: string;\n}\n\ninterface ApiCredentials {\n apiId: number;\n apiHash: string;\n}\n\nconst DEFAULT_INITIAL_METHOD = 'phoneNumber';\nconst QR_CODE_TIMEOUT = 30000;\n\nexport async function authFlow(\n client: TelegramClient,\n apiCredentials: ApiCredentials,\n authParams: UserAuthParams | BotAuthParams,\n) {\n let me: Api.TypeUser;\n\n if ('botAuthToken' in authParams) {\n me = await signInBot(client, apiCredentials, authParams);\n } else {\n const { initialMethod = DEFAULT_INITIAL_METHOD } = authParams;\n\n if (initialMethod === 'phoneNumber') {\n me = await signInUser(client, apiCredentials, authParams);\n } else {\n me = await signInUserWithQrCode(client, apiCredentials, authParams);\n }\n }\n\n client._log.info('Signed in successfully as', utils.getDisplayName(me));\n}\n\nexport async function checkAuthorization(client: TelegramClient) {\n try {\n await client.invoke(new Api.updates.GetState());\n return true;\n } catch (e) {\n if (e.message === 'Disconnect') throw e;\n return false;\n }\n}\n\nasync function signInUser(\n client: TelegramClient, apiCredentials: ApiCredentials, authParams: UserAuthParams,\n): Promise<Api.TypeUser> {\n let phoneNumber;\n let phoneCodeHash;\n let isCodeViaApp = false;\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n try {\n if (typeof authParams.phoneNumber === 'function') {\n try {\n phoneNumber = await authParams.phoneNumber();\n } catch (err) {\n if (err.message === 'RESTART_AUTH_WITH_QR') {\n return signInUserWithQrCode(client, apiCredentials, authParams);\n }\n\n throw err;\n }\n } else {\n phoneNumber = authParams.phoneNumber;\n }\n const sendCodeResult = await sendCode(client, apiCredentials, phoneNumber, authParams.forceSMS);\n phoneCodeHash = sendCodeResult.phoneCodeHash;\n isCodeViaApp = sendCodeResult.isCodeViaApp;\n\n if (typeof phoneCodeHash !== 'string') {\n throw new Error('Failed to retrieve phone code hash');\n }\n\n break;\n } catch (err) {\n if (typeof authParams.phoneNumber !== 'function') {\n throw err;\n }\n\n authParams.onError(err);\n }\n }\n\n let phoneCode;\n let isRegistrationRequired = false;\n let termsOfService;\n\n // eslint-disable-next-line no-constant-condition\n while (1) {\n try {\n try {\n phoneCode = await authParams.phoneCode(isCodeViaApp);\n } catch (err) {\n // This is the support for changing phone number from the phone code screen.\n if (err.message === 'RESTART_AUTH') {\n return signInUser(client, apiCredentials, authParams);\n }\n }\n\n if (!phoneCode) {\n throw new Error('Code is empty');\n }\n\n // May raise PhoneCodeEmptyError, PhoneCodeExpiredError,\n // PhoneCodeHashEmptyError or PhoneCodeInvalidError.\n const result = await client.invoke(new Api.auth.SignIn({\n phoneNumber,\n phoneCodeHash,\n phoneCode,\n }));\n\n if (result instanceof Api.auth.AuthorizationSignUpRequired) {\n isRegistrationRequired = true;\n termsOfService = result.termsOfService;\n break;\n }\n\n return result.user;\n } catch (err) {\n if (err.message === 'SESSION_PASSWORD_NEEDED') {\n return signInWithPassword(client, apiCredentials, authParams);\n } else {\n authParams.onError(err);\n }\n }\n }\n\n if (isRegistrationRequired) {\n // eslint-disable-next-line no-constant-condition\n while (1) {\n try {\n const [firstName, lastName] = await authParams.firstAndLastNames();\n if (!firstName) {\n throw new Error('First name is required');\n }\n\n const { user } = await client.invoke(new Api.auth.SignUp({\n phoneNumber,\n phoneCodeHash,\n firstName,\n lastName,\n })) as Api.auth.Authorization;\n\n if (termsOfService) {\n // This is a violation of Telegram rules: the user should be presented with and accept TOS.\n await client.invoke(new Api.help.AcceptTermsOfService({ id: termsOfService.id }));\n }\n\n return user;\n } catch (err) {\n authParams.onError(err);\n }\n }\n }\n\n authParams.onError(new Error('Auth failed'));\n return signInUser(client, apiCredentials, authParams);\n}\n\nasync function signInUserWithQrCode(\n client: TelegramClient, apiCredentials: ApiCredentials, authParams: UserAuthParams,\n): Promise<Api.TypeUser> {\n let isScanningComplete = false;\n\n const inputPromise = (async () => {\n // eslint-disable-next-line no-constant-condition\n while (1) {\n if (isScanningComplete) {\n break;\n }\n\n const result = await client.invoke(new Api.auth.ExportLoginToken({\n apiId: Number(process.env.TELEGRAM_T_API_ID),\n apiHash: process.env.TELEGRAM_T_API_HASH,\n exceptIds: [],\n }));\n if (!(result instanceof Api.auth.LoginToken)) {\n throw new Error('Unexpected');\n }\n\n const { token, expires } = result;\n\n await Promise.race([\n authParams.qrCode({ token, expires }),\n sleep(QR_CODE_TIMEOUT),\n ]);\n }\n })();\n\n const updatePromise = new Promise<void>((resolve) => {\n client.addEventHandler((update: Api.TypeUpdate) => {\n if (update instanceof Api.UpdateLoginToken) {\n resolve();\n }\n }, { build: (update: object) => update });\n });\n\n try {\n // Either we receive an update that QR is successfully scanned,\n // or we receive a rejection caused by user going back to the regular auth form\n await Promise.race([updatePromise, inputPromise]);\n } catch (err) {\n if (err.message === 'RESTART_AUTH') {\n return signInUser(client, apiCredentials, authParams);\n }\n\n throw err;\n } finally {\n isScanningComplete = true;\n }\n\n try {\n const result2 = await client.invoke(new Api.auth.ExportLoginToken({\n apiId: Number(process.env.TELEGRAM_T_API_ID),\n apiHash: process.env.TELEGRAM_T_API_HASH,\n exceptIds: [],\n }));\n\n if (result2 instanceof Api.auth.LoginTokenSuccess && result2.authorization instanceof Api.auth.Authorization) {\n return result2.authorization.user;\n } else if (result2 instanceof Api.auth.LoginTokenMigrateTo) {\n await client._switchDC(result2.dcId);\n const migratedResult = await client.invoke(new Api.auth.ImportLoginToken({\n token: result2.token,\n }));\n\n if (migratedResult instanceof Api.auth.LoginTokenSuccess\n && migratedResult.authorization instanceof Api.auth.Authorization) {\n return migratedResult.authorization.user;\n }\n }\n } catch (err) {\n if (err.message === 'SESSION_PASSWORD_NEEDED') {\n return signInWithPassword(client, apiCredentials, authParams);\n }\n\n throw err;\n }\n\n // This is a workaround for TypeScript (never actually reached)\n // eslint-disable-next-line no-throw-literal\n throw undefined;\n}\n\nasync function sendCode(\n client: TelegramClient, apiCredentials: ApiCredentials, phoneNumber: string, forceSMS = false,\n): Promise<{\n phoneCodeHash: string;\n isCodeViaApp: boolean;\n }> {\n try {\n const { apiId, apiHash } = apiCredentials;\n const sendResult = await client.invoke(new Api.auth.SendCode({\n phoneNumber,\n apiId,\n apiHash,\n settings: new Api.CodeSettings(),\n }));\n\n // If we already sent a SMS, do not resend the phoneCode (hash may be empty)\n if (!forceSMS || (sendResult.type instanceof Api.auth.SentCodeTypeSms)) {\n return {\n phoneCodeHash: sendResult.phoneCodeHash,\n isCodeViaApp: sendResult.type instanceof Api.auth.SentCodeTypeApp,\n };\n }\n\n const resendResult = await client.invoke(new Api.auth.ResendCode({\n phoneNumber,\n phoneCodeHash: sendResult.phoneCodeHash,\n }));\n\n return {\n phoneCodeHash: resendResult.phoneCodeHash,\n isCodeViaApp: resendResult.type instanceof Api.auth.SentCodeTypeApp,\n };\n } catch (err) {\n if (err.message === 'AUTH_RESTART') {\n return sendCode(client, apiCredentials, phoneNumber, forceSMS);\n } else {\n throw err;\n }\n }\n}\n\nasync function signInWithPassword(\n client: TelegramClient, apiCredentials: ApiCredentials, authParams: UserAuthParams,\n): Promise<Api.TypeUser> {\n // eslint-disable-next-line no-constant-condition\n while (1) {\n try {\n const passwordSrpResult = await client.invoke(new Api.account.GetPassword());\n const password = await authParams.password(passwordSrpResult.hint);\n if (!password) {\n throw new Error('Password is empty');\n }\n\n const passwordSrpCheck = await computePasswordSrpCheck(passwordSrpResult, password);\n const { user } = await client.invoke(new Api.auth.CheckPassword({\n password: passwordSrpCheck,\n })) as Api.auth.Authorization;\n\n return user;\n } catch (err) {\n authParams.onError(err);\n }\n }\n\n // eslint-disable-next-line no-unreachable\n return undefined!; // Never reached (TypeScript fix)\n}\n\nasync function signInBot(client: TelegramClient, apiCredentials: ApiCredentials, authParams: BotAuthParams) {\n const { apiId, apiHash } = apiCredentials;\n const { botAuthToken } = authParams;\n\n const { user } = await client.invoke(new Api.auth.ImportBotAuthorization({\n apiId,\n apiHash,\n botAuthToken,\n })) as Api.auth.Authorization;\n\n return user;\n}\n","// eslint-disable-next-line import/no-named-default\nimport { default as Api } from '../tl/api';\nimport TelegramClient from './TelegramClient';\nimport { getAppropriatedPartSize } from '../Utils';\nimport { sleep, createDeferred } from '../Helpers';\nimport errors from '../errors';\n\nexport interface progressCallback {\n isCanceled?: boolean;\n acceptsBuffer?: boolean;\n\n (\n progress: number, // Float between 0 and 1.\n ...args: any[]\n ): void;\n}\n\nexport interface DownloadFileParams {\n dcId: number;\n fileSize: number;\n workers?: number;\n partSizeKb?: number;\n start?: number;\n end?: number;\n progressCallback?: progressCallback;\n}\n\ninterface Deferred {\n promise: Promise<any>;\n resolve: (value?: any) => void;\n}\n\n// Chunk sizes for `upload.getFile` must be multiple of the smallest size\nconst MIN_CHUNK_SIZE = 4096;\nconst DEFAULT_CHUNK_SIZE = 64; // kb\nconst ONE_MB = 1024 * 1024;\nconst DISCONNECT_SLEEP = 1000;\n\n\nclass Foreman {\n private deferred: Deferred | undefined;\n\n private activeWorkers = 0;\n\n constructor(private maxWorkers: number) {\n }\n\n requestWorker() {\n this.activeWorkers++;\n\n if (this.activeWorkers > this.maxWorkers) {\n this.deferred = createDeferred();\n return this.deferred!.promise;\n }\n\n return Promise.resolve();\n }\n\n releaseWorker() {\n this.activeWorkers--;\n\n if (this.deferred && (this.activeWorkers <= this.maxWorkers)) {\n this.deferred.resolve();\n }\n }\n}\n\nexport async function downloadFile(\n client: TelegramClient,\n inputLocation: Api.InputFileLocation,\n fileParams: DownloadFileParams,\n) {\n let {\n partSizeKb, end,\n } = fileParams;\n const {\n fileSize, workers = 1,\n } = fileParams;\n const { dcId, progressCallback, start = 0 } = fileParams;\n\n end = end && end < fileSize ? end : fileSize - 1;\n\n if (!partSizeKb) {\n partSizeKb = fileSize ? getAppropriatedPartSize(fileSize) : DEFAULT_CHUNK_SIZE;\n }\n\n const partSize = partSizeKb * 1024;\n const partsCount = end ? Math.ceil((end - start) / partSize) : 1;\n\n if (partSize % MIN_CHUNK_SIZE !== 0) {\n throw new Error(`The part size must be evenly divisible by ${MIN_CHUNK_SIZE}`);\n }\n\n client._log.info(`Downloading file in chunks of ${partSize} bytes`);\n\n const foreman = new Foreman(workers);\n const promises: Promise<any>[] = [];\n let offset = start;\n // Used for files with unknown size and for manual cancellations\n let hasEnded = false;\n\n let progress = 0;\n if (progressCallback) {\n progressCallback(progress);\n }\n\n // Preload sender\n await client.getSender(dcId);\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n let limit = partSize;\n let isPrecise = false;\n\n if (Math.floor(offset / ONE_MB) !== Math.floor((offset + limit - 1) / ONE_MB)) {\n limit = ONE_MB - (offset % ONE_MB);\n isPrecise = true;\n }\n\n await foreman.requestWorker();\n\n if (hasEnded) {\n foreman.releaseWorker();\n break;\n }\n\n // eslint-disable-next-line no-loop-func\n promises.push((async (offsetMemo: number) => {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n let sender;\n try {\n sender = await client.getSender(dcId);\n const result = await sender.send(new Api.upload.GetFile({\n location: inputLocation,\n offset: offsetMemo,\n limit,\n precise: isPrecise || undefined,\n }));\n\n if (progressCallback) {\n if (progressCallback.isCanceled) {\n throw new Error('USER_CANCELED');\n }\n\n progress += (1 / partsCount);\n progressCallback(progress);\n }\n\n if (!end && (result.bytes.length < limit)) {\n hasEnded = true;\n }\n\n foreman.releaseWorker();\n\n return result.bytes;\n } catch (err) {\n if (sender && !sender.isConnected()) {\n await sleep(DISCONNECT_SLEEP);\n continue;\n } else if (err instanceof errors.FloodWaitError) {\n await sleep(err.seconds * 1000);\n continue;\n }\n\n foreman.releaseWorker();\n\n hasEnded = true;\n throw err;\n }\n }\n })(offset));\n\n offset += limit;\n\n if (end && (offset > end)) {\n break;\n }\n }\n const results = await Promise.all(promises);\n const buffers = results.filter(Boolean);\n const totalLength = end ? (end + 1) - start : undefined;\n return Buffer.concat(buffers, totalLength);\n}\n","// eslint-disable-next-line import/no-named-default\nimport { default as Api } from '../tl/api';\n\nimport TelegramClient from './TelegramClient';\nimport { generateRandomBytes, readBigIntFromBuffer, sleep } from '../Helpers';\nimport { getAppropriatedPartSize } from '../Utils';\nimport errors from '../errors';\n\ninterface OnProgress {\n isCanceled?: boolean;\n\n // Float between 0 and 1.\n (progress: number): void;\n}\n\nexport interface UploadFileParams {\n file: File;\n workers: number;\n onProgress?: OnProgress;\n}\n\nconst KB_TO_BYTES = 1024;\nconst LARGE_FILE_THRESHOLD = 10 * 1024 * 1024;\nconst DISCONNECT_SLEEP = 1000;\n\nexport async function uploadFile(\n client: TelegramClient,\n fileParams: UploadFileParams,\n): Promise<Api.InputFile | Api.InputFileBig> {\n const { file, onProgress } = fileParams;\n let { workers } = fileParams;\n\n const { name, size } = file;\n const fileId = readBigIntFromBuffer(generateRandomBytes(8), true, true);\n const isLarge = size > LARGE_FILE_THRESHOLD;\n\n const partSize = getAppropriatedPartSize(size) * KB_TO_BYTES;\n const partCount = Math.floor((size + partSize - 1) / partSize);\n const buffer = Buffer.from(await fileToBuffer(file));\n\n // Make sure a new sender can be created before starting upload\n await client.getSender(client.session.dcId);\n\n if (!workers || !size) {\n workers = 1;\n }\n if (workers >= partCount) {\n workers = partCount;\n }\n\n let progress = 0;\n if (onProgress) {\n onProgress(progress);\n }\n\n for (let i = 0; i < partCount; i += workers) {\n const sendingParts = [];\n let end = i + workers;\n if (end > partCount) {\n end = partCount;\n }\n\n for (let j = i; j < end; j++) {\n const bytes = buffer.slice(j * partSize, (j + 1) * partSize);\n\n // eslint-disable-next-line no-loop-func\n sendingParts.push((async (jMemo: number, bytesMemo: Buffer) => {\n while (true) {\n let sender;\n try {\n // We always upload from the DC we are in\n sender = await client.getSender(client.session.dcId);\n await sender.send(\n isLarge\n ? new Api.upload.SaveBigFilePart({\n fileId,\n filePart: jMemo,\n fileTotalParts: partCount,\n bytes: bytesMemo,\n })\n : new Api.upload.SaveFilePart({\n fileId,\n filePart: jMemo,\n bytes: bytesMemo,\n }),\n );\n } catch (err) {\n if (sender && !sender.isConnected()) {\n await sleep(DISCONNECT_SLEEP);\n continue;\n } else if (err instanceof errors.FloodWaitError) {\n await sleep(err.seconds * 1000);\n continue;\n }\n throw err;\n }\n\n if (onProgress) {\n if (onProgress.isCanceled) {\n throw new Error('USER_CANCELED');\n }\n\n progress += (1 / partCount);\n onProgress(progress);\n }\n break;\n }\n })(j, bytes));\n }\n\n await Promise.all(sendingParts);\n }\n\n return isLarge\n ? new Api.InputFileBig({\n id: fileId,\n parts: partCount,\n name,\n })\n : new Api.InputFile({\n id: fileId,\n parts: partCount,\n name,\n md5Checksum: '', // This is not a \"flag\", so not sure if we can make it optional.\n });\n}\n\nfunction fileToBuffer(file: File) {\n return new Response(file).arrayBuffer();\n}\n","const {\n sha1,\n toSignedLittleBuffer,\n readBufferFromBigInt,\n readBigIntFromBuffer,\n} = require('../Helpers');\nconst BinaryReader = require('../extensions/BinaryReader');\nconst { sleep } = require('../Helpers');\n\nclass AuthKey {\n constructor(value, hash) {\n if (!hash || !value) {\n return;\n }\n this._key = value;\n this._hash = hash;\n const reader = new BinaryReader(hash);\n this.auxHash = reader.readLong(false);\n reader.read(4);\n this.keyId = reader.readLong(false);\n }\n\n async setKey(value) {\n if (!value) {\n this._key = undefined;\n this.auxHash = undefined;\n this.keyId = undefined;\n this._hash = undefined;\n return;\n }\n if (value instanceof AuthKey) {\n this._key = value._key;\n this.auxHash = value.auxHash;\n this.keyId = value.keyId;\n this._hash = value._hash;\n return;\n }\n this._key = value;\n this._hash = await sha1(this._key);\n const reader = new BinaryReader(this._hash);\n this.auxHash = reader.readLong(false);\n reader.read(4);\n this.keyId = reader.readLong(false);\n }\n\n async waitForKey() {\n while (!this.keyId) {\n await sleep(20);\n }\n }\n\n getKey() {\n return this._key;\n }\n\n // TODO : This doesn't really fit here, it's only used in authentication\n\n /**\n * Calculates the new nonce hash based on the current class fields' values\n * @param newNonce\n * @param number\n * @returns {bigint}\n */\n async calcNewNonceHash(newNonce, number) {\n newNonce = toSignedLittleBuffer(newNonce, 32);\n const n = Buffer.alloc(1);\n n.writeUInt8(number, 0);\n const data = Buffer.concat([newNonce,\n Buffer.concat([n, readBufferFromBigInt(this.auxHash, 8, true)])]);\n\n // Calculates the message key from the given data\n const shaData = (await sha1(data)).slice(4, 20);\n return readBigIntFromBuffer(shaData, true, true);\n }\n\n equals(other) {\n return other instanceof this.constructor && this._key && other.getKey() && other.getKey()\n .equals(this._key);\n }\n}\n\nmodule.exports = AuthKey;\n","const crypto = require('./crypto');\n\nclass CTR {\n constructor(key, iv) {\n if (!Buffer.isBuffer(key) || !Buffer.isBuffer(iv) || iv.length !== 16) {\n throw new Error('Key and iv need to be a buffer');\n }\n\n this.cipher = crypto.createCipheriv('AES-256-CTR', key, iv);\n }\n\n encrypt(data) {\n return Buffer.from(this.cipher.update(data));\n }\n}\n\nmodule.exports = CTR;\n","const BigInt = require('big-integer');\nconst { modExp } = require('../Helpers');\n\nclass Factorizator {\n /**\n * Calculates the greatest common divisor\n * @param a {BigInteger}\n * @param b {BigInteger}\n * @returns {BigInteger}\n */\n static gcd(a, b) {\n while (b.neq(BigInt.zero)) {\n const temp = b;\n b = a.remainder(b);\n a = temp;\n }\n return a;\n }\n\n /**\n * Factorizes the given number and returns both the divisor and the number divided by the divisor\n * @param pq {BigInteger}\n * @returns {{p: *, q: *}}\n */\n static factorize(pq) {\n if (pq.remainder(2)\n .equals(BigInt.zero)) {\n return {\n p: BigInt(2),\n q: pq.divide(BigInt(2)),\n };\n }\n let y = BigInt.randBetween(BigInt(1), pq.minus(1));\n const c = BigInt.randBetween(BigInt(1), pq.minus(1));\n const m = BigInt.randBetween(BigInt(1), pq.minus(1));\n\n let g = BigInt.one;\n let r = BigInt.one;\n let q = BigInt.one;\n let x = BigInt.zero;\n let ys = BigInt.zero;\n let k;\n\n while (g.eq(BigInt.one)) {\n x = y;\n for (let i = 0; BigInt(i)\n .lesser(r); i++) {\n y = (modExp(y, BigInt(2), pq)).add(c)\n .remainder(pq);\n }\n k = BigInt.zero;\n\n while (k.lesser(r) && g.eq(BigInt.one)) {\n ys = y;\n const condition = BigInt.min(m, r.minus(k));\n for (let i = 0; BigInt(i)\n .lesser(condition); i++) {\n y = (modExp(y, BigInt(2), pq)).add(c)\n .remainder(pq);\n q = q.multiply(x.minus(y)\n .abs())\n .remainder(pq);\n }\n g = Factorizator.gcd(q, pq);\n k = k.add(m);\n }\n\n r = r.multiply(2);\n }\n\n\n if (g.eq(pq)) {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n ys = (modExp(ys, BigInt(2), pq)).add(c)\n .remainder(pq);\n g = Factorizator.gcd(x.minus(ys)\n .abs(), pq);\n\n if (g.greater(1)) {\n break;\n }\n }\n }\n const p = g;\n q = pq.divide(g);\n return p < q ? {\n p,\n q,\n } : {\n p: q,\n q: p,\n };\n }\n}\n\nmodule.exports = Factorizator;\n","const { IGE: AESIGE } = require('@cryptography/aes');\nconst Helpers = require('../Helpers');\n\n\nclass IGENEW {\n constructor(key, iv) {\n this.ige = new AESIGE(key, iv);\n }\n\n /**\n * Decrypts the given text in 16-bytes blocks by using the given key and 32-bytes initialization vector\n * @param cipherText {Buffer}\n * @returns {Buffer}\n */\n decryptIge(cipherText) {\n return Helpers.convertToLittle(this.ige.decrypt(cipherText));\n }\n\n /**\n * Encrypts the given text in 16-bytes blocks by using the given key and 32-bytes initialization vector\n * @param plainText {Buffer}\n * @returns {Buffer}\n */\n encryptIge(plainText) {\n const padding = plainText.length % 16;\n if (padding) {\n plainText = Buffer.concat([plainText, Helpers.generateRandomBytes(16 - padding)]);\n }\n\n return Helpers.convertToLittle(this.ige.encrypt(plainText));\n }\n}\n\nmodule.exports = IGENEW;\n","/**\n * Uint32Array -> ArrayBuffer (low-endian os)\n */\nexport function i2abLow(buf: Uint32Array): ArrayBuffer {\n const uint8 = new Uint8Array(buf.length * 4);\n let i = 0;\n\n for (let j = 0; j < buf.length; j++) {\n const int = buf[j];\n\n uint8[i++] = int >>> 24;\n uint8[i++] = (int >> 16) & 0xFF;\n uint8[i++] = (int >> 8) & 0xFF;\n uint8[i++] = int & 0xFF;\n }\n\n return uint8.buffer;\n}\n\n/**\n * Uint32Array -> ArrayBuffer (big-endian os)\n */\nexport function i2abBig(buf: Uint32Array): ArrayBuffer {\n return buf.buffer;\n}\n\n/**\n * ArrayBuffer -> Uint32Array (low-endian os)\n */\nexport function ab2iLow(ab: ArrayBuffer | SharedArrayBuffer | Uint8Array): Uint32Array {\n const uint8 = new Uint8Array(ab);\n const buf = new Uint32Array(uint8.length / 4);\n\n for (let i = 0; i < uint8.length; i += 4) {\n buf[i / 4] = (\n uint8[i] << 24\n ^ uint8[i + 1] << 16\n ^ uint8[i + 2] << 8\n ^ uint8[i + 3]\n );\n }\n\n return buf;\n}\n\n/**\n * ArrayBuffer -> Uint32Array (big-endian os)\n */\nexport function ab2iBig(ab: ArrayBuffer | SharedArrayBuffer | Uint8Array): Uint32Array {\n return new Uint32Array(ab);\n}\n\nexport const isBigEndian = new Uint8Array(new Uint32Array([0x01020304]))[0] === 0x01;\nexport const i2ab = isBigEndian ? i2abBig : i2abLow;\nexport const ab2i = isBigEndian ? ab2iBig : ab2iLow;\n","const AES = require('@cryptography/aes').default;\nconst {\n i2ab,\n ab2i,\n} = require('./converters');\nconst { getWords } = require('./words');\n\nclass Counter {\n constructor(initialValue) {\n this.setBytes(initialValue);\n }\n\n setBytes(bytes) {\n bytes = Buffer.from(bytes);\n this._counter = bytes;\n }\n\n increment() {\n for (let i = 15; i >= 0; i--) {\n if (this._counter[i] === 255) {\n this._counter[i] = 0;\n } else {\n this._counter[i]++;\n break;\n }\n }\n }\n}\n\nclass CTR {\n constructor(key, counter) {\n if (!(counter instanceof Counter)) {\n counter = new Counter(counter);\n }\n\n this._counter = counter;\n\n this._remainingCounter = undefined;\n this._remainingCounterIndex = 16;\n\n this._aes = new AES(getWords(key));\n }\n\n update(plainText) {\n return this.encrypt(plainText);\n }\n\n encrypt(plainText) {\n const encrypted = Buffer.from(plainText);\n\n for (let i = 0; i < encrypted.length; i++) {\n if (this._remainingCounterIndex === 16) {\n this._remainingCounter = Buffer.from(i2ab(this._aes.encrypt(ab2i(this._counter._counter))));\n this._remainingCounterIndex = 0;\n this._counter.increment();\n }\n encrypted[i] ^= this._remainingCounter[this._remainingCounterIndex++];\n }\n\n return encrypted;\n }\n}\n\n// endregion\nfunction createDecipheriv(algorithm, key, iv) {\n if (algorithm.includes('ECB')) {\n throw new Error('Not supported');\n } else {\n return new CTR(key, iv);\n }\n}\n\nfunction createCipheriv(algorithm, key, iv) {\n if (algorithm.includes('ECB')) {\n throw new Error('Not supported');\n } else {\n return new CTR(key, iv);\n }\n}\n\nfunction randomBytes(count) {\n const bytes = new Uint8Array(count);\n crypto.getRandomValues(bytes);\n return bytes;\n}\n\nclass Hash {\n constructor(algorithm) {\n this.algorithm = algorithm;\n }\n\n update(data) {\n // We shouldn't be needing new Uint8Array but it doesn't\n // work without it\n this.data = new Uint8Array(data);\n }\n\n\n async digest() {\n if (this.algorithm === 'sha1') {\n // eslint-disable-next-line no-restricted-globals\n return Buffer.from(await self.crypto.subtle.digest('SHA-1', this.data));\n } else if (this.algorithm === 'sha256') {\n // eslint-disable-next-line no-restricted-globals\n return Buffer.from(await self.crypto.subtle.digest('SHA-256', this.data));\n }\n return undefined;\n }\n}\n\nasync function pbkdf2(password, salt, iterations) {\n const passwordKey = await crypto.subtle.importKey('raw', password,\n { name: 'PBKDF2' }, false, ['deriveBits']);\n return Buffer.from(await crypto.subtle.deriveBits({\n name: 'PBKDF2',\n hash: 'SHA-512',\n salt,\n iterations,\n }, passwordKey, 512));\n}\n\nfunction createHash(algorithm) {\n return new Hash(algorithm);\n}\n\nmodule.exports = {\n createCipheriv,\n createDecipheriv,\n randomBytes,\n createHash,\n pbkdf2,\n};\n","/*\n * Imported from https://github.com/spalt08/cryptography/blob/master/packages/aes/src/utils/words.ts\n */\n\nexport function s2i(str: string, pos: number) {\n return (\n str.charCodeAt(pos) << 24\n ^ str.charCodeAt(pos + 1) << 16\n ^ str.charCodeAt(pos + 2) << 8\n ^ str.charCodeAt(pos + 3)\n );\n}\n\n/**\n * Helper function for transforming string key to Uint32Array\n */\nexport function getWords(key: string | Uint8Array | Uint32Array) {\n if (key instanceof Uint32Array) {\n return key;\n }\n\n if (typeof key === 'string') {\n if (key.length % 4 !== 0) for (let i = key.length % 4; i <= 4; i++) key += '\\0x00';\n\n const buf = new Uint32Array(key.length / 4);\n for (let i = 0; i < key.length; i += 4) buf[i / 4] = s2i(key, i);\n\n return buf;\n }\n\n if (key instanceof Uint8Array) {\n const buf = new Uint32Array(key.length / 4);\n\n for (let i = 0; i < key.length; i += 4) {\n buf[i / 4] = (\n key[i] << 24\n ^ key[i + 1] << 16\n ^ key[i + 2] << 8\n ^ key[i + 3]\n );\n }\n\n return buf;\n }\n\n throw new Error('Unable to create 32-bit words');\n}\n\nexport function xor(left: Uint32Array, right: Uint32Array, to = left) {\n for (let i = 0; i < left.length; i++) to[i] = left[i] ^ right[i];\n}\n","/**\n * Errors not related to the Telegram API itself\n */\n\n\n/**\n * Occurs when a read operation was cancelled.\n */\nclass ReadCancelledError extends Error {\n constructor() {\n super('The read operation was cancelled.');\n }\n}\n\n/**\n * Occurs when a type is not found, for example,\n * when trying to read a TLObject with an invalid constructor code.\n */\nclass TypeNotFoundError extends Error {\n constructor(invalidConstructorId, remaining) {\n super(`Could not find a matching Constructor ID for the TLObject that was supposed to be\n read with ID ${invalidConstructorId}. Most likely, a TLObject was trying to be read when\n it should not be read. Remaining bytes: ${remaining.length}`);\n if (typeof alert !== 'undefined') {\n // eslint-disable-next-line no-alert\n alert(`Missing MTProto Entity: Please, make sure to add TL definition for ID ${invalidConstructorId}`);\n }\n this.invalidConstructorId = invalidConstructorId;\n this.remaining = remaining;\n }\n}\n\n/**\n * Occurs when using the TCP full mode and the checksum of a received\n * packet doesn't match the expected checksum.\n */\nclass InvalidChecksumError extends Error {\n constructor(checksum, validChecksum) {\n super(`Invalid checksum (${checksum} when ${validChecksum} was expected). This packet should be skipped.`);\n this.checksum = checksum;\n this.validChecksum = validChecksum;\n }\n}\n\n/**\n * Occurs when the buffer is invalid, and may contain an HTTP error code.\n * For instance, 404 means \"forgotten/broken authorization key\", while\n */\nclass InvalidBufferError extends Error {\n constructor(payload) {\n let code;\n if (payload.length === 4) {\n code = -payload.readInt32LE(0);\n super(`Invalid response buffer (HTTP code ${code})`);\n } else {\n super(`Invalid response buffer (too short ${payload})`);\n }\n this.code = code;\n this.payload = payload;\n }\n}\n\n/**\n * Generic security error, mostly used when generating a new AuthKey.\n */\nclass SecurityError extends Error {\n constructor(...args) {\n if (!args.length) {\n args = ['A security check failed.'];\n }\n super(...args);\n }\n}\n\n/**\n * Occurs when there's a hash mismatch between the decrypted CDN file\n * and its expected hash.\n */\nclass CdnFileTamperedError extends SecurityError {\n constructor() {\n super('The CDN file has been altered and its download cancelled.');\n }\n}\n\n/**\n * Occurs when handling a badMessageNotification\n */\nclass BadMessageError extends Error {\n static ErrorMessages = {\n 16:\n 'msg_id too low (most likely, client time is wrong it would be worthwhile to '\n + 'synchronize it using msg_id notifications and re-send the original message '\n + 'with the correct msg_id or wrap it in a container with a new msg_id if the '\n + 'original message had waited too long on the client to be transmitted).',\n\n 17:\n 'msg_id too high (similar to the previous case, the client time has to be '\n + 'synchronized, and the message re-sent with the correct msg_id).',\n\n 18:\n 'Incorrect two lower order msg_id bits (the server expects client message msg_id '\n + 'to be divisible by 4).',\n\n 19: 'Container msg_id is the same as msg_id of a previously received message (this must never happen).',\n\n 20:\n 'Message too old, and it cannot be verified whether the server has received a '\n + 'message with this msg_id or not.',\n\n 32:\n 'msg_seqno too low (the server has already received a message with a lower '\n + 'msg_id but with either a higher or an equal and odd seqno).',\n\n 33:\n 'msg_seqno too high (similarly, there is a message with a higher msg_id but with '\n + 'either a lower or an equal and odd seqno).',\n\n 34: 'An even msg_seqno expected (irrelevant message), but odd received.',\n\n 35: 'Odd msg_seqno expected (relevant message), but even received.',\n\n 48:\n 'Incorrect server salt (in this case, the bad_server_salt response is received with '\n + 'the correct salt, and the message is to be re-sent with it).',\n\n 64: 'Invalid container.',\n };\n\n constructor(request, code) {\n let errorMessage = BadMessageError.ErrorMessages[code]\n || `Unknown error code (this should not happen): ${code}.`;\n errorMessage += ` Caused by ${request.className}`;\n super(errorMessage);\n this.message = errorMessage;\n this.code = code;\n }\n}\n\n// TODO : Support multi errors.\n\nmodule.exports = {\n ReadCancelledError,\n TypeNotFoundError,\n InvalidChecksumError,\n InvalidBufferError,\n SecurityError,\n CdnFileTamperedError,\n BadMessageError,\n};\n","/**\n * Base class for all Remote Procedure Call errors.\n */\nclass RPCError extends Error {\n constructor(message, request, code = undefined) {\n super(\n 'RPCError {0}: {1}{2}'\n .replace('{0}', code)\n .replace('{1}', message)\n .replace('{2}', RPCError._fmtRequest(request)),\n );\n this.code = code;\n this.message = message;\n }\n\n static _fmtRequest(request) {\n // TODO fix this\n if (request) {\n return ` (caused by ${request.className})`;\n } else {\n return '';\n }\n }\n}\n\n/**\n * The request must be repeated, but directed to a different data center.\n */\nclass InvalidDCError extends RPCError {\n constructor(request, message, code) {\n super(message, request, code);\n this.code = code || 303;\n this.message = message || 'ERROR_SEE_OTHER';\n }\n}\n\n/**\n * The query contains errors. In the event that a request was created\n * using a form and contains user generated data, the user should be\n * notified that the data must be corrected before the query is repeated.\n */\nclass BadRequestError extends RPCError {\n code = 400;\n\n message = 'BAD_REQUEST';\n}\n\n/**\n * There was an unauthorized attempt to use functionality available only\n * to authorized users.\n */\nclass UnauthorizedError extends RPCError {\n code = 401;\n\n message = 'UNAUTHORIZED';\n}\n\n/**\n * Privacy violation. For example, an attempt to write a message to\n * someone who has blacklisted the current user.\n */\nclass ForbiddenError extends RPCError {\n code = 403;\n\n message = 'FORBIDDEN';\n}\n\n/**\n * An attempt to invoke a non-existent object, such as a method.\n */\nclass NotFoundError extends RPCError {\n code = 404;\n\n message = 'NOT_FOUND';\n}\n\n/**\n * Errors related to invalid authorization key, like\n * AUTH_KEY_DUPLICATED which can cause the connection to fail.\n */\nclass AuthKeyError extends RPCError {\n code = 406;\n\n message = 'AUTH_KEY';\n}\n\n/**\n * The maximum allowed number of attempts to invoke the given method\n * with the given input parameters has been exceeded. For example, in an\n * attempt to request a large number of text messages (SMS) for the same\n * phone number.\n */\nclass FloodError extends RPCError {\n code = 420;\n\n message = 'FLOOD';\n}\n\n/**\n * An internal server error occurred while a request was being processed\n * for example, there was a disruption while accessing a database or file\n * storage\n */\nclass ServerError extends RPCError {\n code = 500; // Also witnessed as -500\n\n message = 'INTERNAL';\n}\n\n/**\n * Clicking the inline buttons of bots that never (or take to long to)\n * call ``answerCallbackQuery`` will result in this \"special\" RPCError.\n */\nclass TimedOutError extends RPCError {\n code = 503; // Only witnessed as -503\n\n message = 'Timeout';\n}\n\nmodule.exports = {\n RPCError,\n InvalidDCError,\n BadRequestError,\n UnauthorizedError,\n ForbiddenError,\n NotFoundError,\n AuthKeyError,\n FloodError,\n ServerError,\n TimedOutError,\n};\n","const {\n RPCError,\n InvalidDCError,\n FloodError,\n BadRequestError,\n} = require('./RPCBaseErrors');\n\n\nclass UserMigrateError extends InvalidDCError {\n constructor(args) {\n const newDc = Number(args.capture || 0);\n // eslint-disable-next-line max-len\n super(`The user whose identity is being used to execute queries is associated with DC ${newDc}${RPCError._fmtRequest(args.request)}`);\n // eslint-disable-next-line max-len\n this.message = `The user whose identity is being used to execute queries is associated with DC ${newDc}${RPCError._fmtRequest(args.request)}`;\n this.newDc = newDc;\n }\n}\n\n\nclass PhoneMigrateError extends InvalidDCError {\n constructor(args) {\n const newDc = Number(args.capture || 0);\n // eslint-disable-next-line max-len\n super(`The phone number a user is trying to use for authorization is associated with DC ${newDc}${RPCError._fmtRequest(args.request)}`);\n // eslint-disable-next-line max-len\n this.message = `The phone number a user is trying to use for authorization is associated with DC ${newDc}${RPCError._fmtRequest(args.request)}`;\n this.newDc = newDc;\n }\n}\n\nclass SlowModeWaitError extends FloodError {\n constructor(args) {\n const seconds = Number(args.capture || 0);\n // eslint-disable-next-line max-len\n super(`A wait of ${seconds} seconds is required before sending another message in this chat${RPCError._fmtRequest(args.request)}`);\n // eslint-disable-next-line max-len\n this.message = `A wait of ${seconds} seconds is required before sending another message in this chat${RPCError._fmtRequest(args.request)}`;\n this.seconds = seconds;\n }\n}\n\nclass FloodWaitError extends FloodError {\n constructor(args) {\n const seconds = Number(args.capture || 0);\n super(`A wait of ${seconds} seconds is required${RPCError._fmtRequest(args.request)}`);\n this.message = `A wait of ${seconds} seconds is required${RPCError._fmtRequest(args.request)}`;\n this.seconds = seconds;\n }\n}\nclass MsgWaitError extends FloodError {\n constructor(args) {\n super(`Message failed to be sent.${RPCError._fmtRequest(args.request)}`);\n this.message = `Message failed to be sent.${RPCError._fmtRequest(args.request)}`;\n }\n}\n\nclass FloodTestPhoneWaitError extends FloodError {\n constructor(args) {\n const seconds = Number(args.capture || 0);\n super(`A wait of ${seconds} seconds is required in the test servers${RPCError._fmtRequest(args.request)}`);\n // eslint-disable-next-line max-len\n this.message = `A wait of ${seconds} seconds is required in the test servers${RPCError._fmtRequest(args.request)}`;\n this.seconds = seconds;\n }\n}\n\nclass FileMigrateError extends InvalidDCError {\n constructor(args) {\n const newDc = Number(args.capture || 0);\n super(`The file to be accessed is currently stored in DC ${newDc}${RPCError._fmtRequest(args.request)}`);\n // eslint-disable-next-line max-len\n this.message = `The file to be accessed is currently stored in DC ${newDc}${RPCError._fmtRequest(args.request)}`;\n this.newDc = newDc;\n }\n}\n\nclass NetworkMigrateError extends InvalidDCError {\n constructor(args) {\n const newDc = Number(args.capture || 0);\n super(`The source IP address is associated with DC ${newDc}${RPCError._fmtRequest(args.request)}`);\n this.message = `The source IP address is associated with DC ${newDc}${RPCError._fmtRequest(args.request)}`;\n this.newDc = newDc;\n }\n}\n\nclass EmailUnconfirmedError extends BadRequestError {\n constructor(args) {\n const codeLength = Number(args.capture || 0);\n super(`Email unconfirmed, the length of the code must be ${codeLength}${RPCError._fmtRequest(args.request)}`);\n // eslint-disable-next-line max-len\n this.message = `Email unconfirmed, the length of the code must be ${codeLength}${RPCError._fmtRequest(args.request)}`;\n this.codeLength = codeLength;\n }\n}\n\nconst rpcErrorRe = [\n [/FILE_MIGRATE_(\\d+)/, FileMigrateError],\n [/FLOOD_TEST_PHONE_WAIT_(\\d+)/, FloodTestPhoneWaitError],\n [/FLOOD_WAIT_(\\d+)/, FloodWaitError],\n [/MSG_WAIT_(.*)/, MsgWaitError],\n [/PHONE_MIGRATE_(\\d+)/, PhoneMigrateError],\n [/SLOWMODE_WAIT_(\\d+)/, SlowModeWaitError],\n [/USER_MIGRATE_(\\d+)/, UserMigrateError],\n [/NETWORK_MIGRATE_(\\d+)/, NetworkMigrateError],\n [/EMAIL_UNCONFIRMED_(\\d+)/, EmailUnconfirmedError],\n\n];\nmodule.exports = {\n rpcErrorRe,\n FileMigrateError,\n FloodTestPhoneWaitError,\n FloodWaitError,\n PhoneMigrateError,\n SlowModeWaitError,\n UserMigrateError,\n NetworkMigrateError,\n MsgWaitError,\n EmailUnconfirmedError,\n};\n","/**\n * Converts a Telegram's RPC Error to a Python error.\n * @param rpcError the RPCError instance\n * @param request the request that caused this error\n * @constructor the RPCError as a Python exception that represents this error\n */\nconst { RPCError } = require('./RPCBaseErrors');\nconst { rpcErrorRe } = require('./RPCErrorList');\n\nfunction RPCMessageToError(rpcError, request) {\n for (const [msgRegex, Cls] of rpcErrorRe) {\n const m = rpcError.errorMessage.match(msgRegex);\n if (m) {\n const capture = m.length === 2 ? parseInt(m[1], 10) : undefined;\n return new Cls({\n request,\n capture,\n });\n }\n }\n\n return new RPCError(rpcError.errorMessage, request);\n}\n\nconst Common = require('./Common');\nconst RPCBaseErrors = require('./RPCBaseErrors');\nconst RPCErrorList = require('./RPCErrorList');\n\nmodule.exports = {\n RPCMessageToError,\n ...Common,\n ...RPCBaseErrors,\n ...RPCErrorList,\n};\n","const { EventBuilder } = require('./common');\n\nclass Raw extends EventBuilder {\n constructor(args = {\n types: undefined,\n func: undefined,\n }) {\n super();\n if (!args.types) {\n this.types = true;\n } else {\n this.types = args.types;\n }\n }\n\n build(update) {\n return update;\n }\n}\n\nmodule.exports = Raw;\n","class EventBuilder {\n constructor(args = {\n chats: undefined,\n blacklistChats: undefined,\n func: undefined,\n }) {\n this.chats = args.chats;\n this.blacklistChats = Boolean(args.blacklistChats);\n this.resolved = false;\n this.func = args.func;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n build(update) {\n\n }\n}\n\n\nmodule.exports = {\n EventBuilder,\n};\n","const NewMessage = require('./NewMessage');\nconst Raw = require('./Raw');\n\nclass StopPropagation extends Error {\n\n}\n\nmodule.exports = {\n NewMessage,\n StopPropagation,\n Raw,\n};\n","class AsyncQueue {\n constructor() {\n this._queue = [];\n this.canGet = new Promise((resolve) => {\n this.resolveGet = resolve;\n });\n this.canPush = true;\n }\n\n async push(value) {\n await this.canPush;\n this._queue.push(value);\n this.resolveGet(true);\n this.canPush = new Promise((resolve) => {\n this.resolvePush = resolve;\n });\n }\n\n async pop() {\n await this.canGet;\n const returned = this._queue.pop();\n this.resolvePush(true);\n this.canGet = new Promise((resolve) => {\n this.resolveGet = resolve;\n });\n return returned;\n }\n}\n\nmodule.exports = AsyncQueue;\n","const { TypeNotFoundError } = require('../errors/Common');\nconst { coreObjects } = require('../tl/core');\nconst { tlobjects } = require('../tl/AllTLObjects');\nconst { readBigIntFromBuffer } = require('../Helpers');\n\nclass BinaryReader {\n /**\n * Small utility class to read binary data.\n * @param data {Buffer}\n */\n constructor(data) {\n this.stream = data;\n this._last = undefined;\n this.offset = 0;\n }\n\n // region Reading\n\n // \"All numbers are written as little endian.\"\n // https://core.telegram.org/mtproto\n /**\n * Reads a single byte value.\n */\n readByte() {\n return this.read(1)[0];\n }\n\n /**\n * Reads an integer (4 bytes or 32 bits) value.\n * @param signed {Boolean}\n */\n readInt(signed = true) {\n let res;\n if (signed) {\n res = this.stream.readInt32LE(this.offset);\n } else {\n res = this.stream.readUInt32LE(this.offset);\n }\n this.offset += 4;\n return res;\n }\n\n /**\n * Reads a long integer (8 bytes or 64 bits) value.\n * @param signed\n * @returns {BigInteger}\n */\n readLong(signed = true) {\n return this.readLargeInt(64, signed);\n }\n\n /**\n * Reads a real floating point (4 bytes) value.\n * @returns {number}\n */\n readFloat() {\n return this.read(4)\n .readFloatLE(0);\n }\n\n /**\n * Reads a real floating point (8 bytes) value.\n * @returns {BigInteger}\n */\n readDouble() {\n // was this a bug ? it should have been <d\n return this.read(8)\n .readDoubleLE(0);\n }\n\n /**\n * Reads a n-bits long integer value.\n * @param bits\n * @param signed {Boolean}\n */\n readLargeInt(bits, signed = true) {\n const buffer = this.read(Math.floor(bits / 8));\n return readBigIntFromBuffer(buffer, true, signed);\n }\n\n /**\n * Read the given amount of bytes, or -1 to read all remaining.\n * @param length {number}\n */\n read(length = -1) {\n if (length === -1) {\n length = this.stream.length - this.offset;\n }\n const result = this.stream.slice(this.offset, this.offset + length);\n this.offset += length;\n if (result.length !== length) {\n throw Error(\n `No more data left to read (need ${length}, got ${result.length}: ${result}); last read ${this._last}`,\n );\n }\n this._last = result;\n return result;\n }\n\n /**\n * Gets the byte array representing the current buffer as a whole.\n * @returns {Buffer}\n */\n getBuffer() {\n return this.stream;\n }\n\n // endregion\n\n // region Telegram custom reading\n /**\n * Reads a Telegram-encoded byte array, without the need of\n * specifying its length.\n * @returns {Buffer}\n */\n tgReadBytes() {\n const firstByte = this.readByte();\n let padding;\n let length;\n if (firstByte === 254) {\n length = this.readByte() | (this.readByte() << 8) | (this.readByte() << 16);\n padding = length % 4;\n } else {\n length = firstByte;\n padding = (length + 1) % 4;\n }\n const data = this.read(length);\n\n if (padding > 0) {\n padding = 4 - padding;\n this.read(padding);\n }\n\n return data;\n }\n\n /**\n * Reads a Telegram-encoded string.\n * @returns {string}\n */\n tgReadString() {\n return this.tgReadBytes()\n .toString('utf-8');\n }\n\n /**\n * Reads a Telegram boolean value.\n * @returns {boolean}\n */\n tgReadBool() {\n const value = this.readInt(false);\n if (value === 0x997275b5) {\n // boolTrue\n return true;\n } else if (value === 0xbc799737) {\n // boolFalse\n return false;\n } else {\n throw new Error(`Invalid boolean code ${value.toString('16')}`);\n }\n }\n\n /**\n * Reads and converts Unix time (used by Telegram)\n * into a Javascript {Date} object.\n * @returns {Date}\n */\n tgReadDate() {\n const value = this.readInt();\n return new Date(value * 1000);\n }\n\n /**\n * Reads a Telegram object.\n */\n tgReadObject() {\n const constructorId = this.readInt(false);\n let clazz = tlobjects[constructorId];\n if (clazz === undefined) {\n /**\n * The class was None, but there's still a\n * chance of it being a manually parsed value like bool!\n */\n const value = constructorId;\n if (value === 0x997275b5) {\n // boolTrue\n return true;\n } else if (value === 0xbc799737) {\n // boolFalse\n return false;\n } else if (value === 0x1cb5c415) {\n // Vector\n const temp = [];\n const length = this.readInt();\n for (let i = 0; i < length; i++) {\n temp.push(this.tgReadObject());\n }\n return temp;\n }\n\n clazz = coreObjects[constructorId];\n\n if (clazz === undefined) {\n // If there was still no luck, give up\n this.seek(-4); // Go back\n const pos = this.tellPosition();\n const error = new TypeNotFoundError(constructorId, this.read());\n this.setPosition(pos);\n throw error;\n }\n }\n return clazz.fromReader(this);\n }\n\n /**\n * Reads a vector (a list) of Telegram objects.\n * @returns {[Buffer]}\n */\n tgReadVector() {\n if (this.readInt(false) !== 0x1cb5c415) {\n throw new Error('Invalid constructor code, vector was expected');\n }\n const count = this.readInt();\n const temp = [];\n for (let i = 0; i < count; i++) {\n temp.push(this.tgReadObject());\n }\n return temp;\n }\n\n // endregion\n\n /**\n * Closes the reader.\n */\n close() {\n this.stream = undefined;\n }\n\n // region Position related\n\n /**\n * Tells the current position on the stream.\n * @returns {number}\n */\n tellPosition() {\n return this.offset;\n }\n\n /**\n * Sets the current position on the stream.\n * @param position\n */\n setPosition(position) {\n this.offset = position;\n }\n\n /**\n * Seeks the stream position given an offset from the current position.\n * The offset may be negative.\n * @param offset\n */\n seek(offset) {\n this.offset += offset;\n }\n\n // endregion\n}\n\nmodule.exports = BinaryReader;\n","class BinaryWriter {\n constructor(stream) {\n this._stream = stream;\n }\n\n write(buffer) {\n this._stream = Buffer.concat([this._stream, buffer]);\n }\n\n getValue() {\n return this._stream;\n }\n}\n\nmodule.exports = BinaryWriter;\n","let _level;\n\nclass Logger {\n static levels = ['error', 'warn', 'info', 'debug'];\n\n constructor(level) {\n if (!_level) {\n _level = level || 'debug';\n }\n\n this.isBrowser = typeof process === 'undefined'\n || process.type === 'renderer'\n || process.browser === true\n || process.__nwjs;\n if (!this.isBrowser) {\n this.colors = {\n start: '\\x1b[2m',\n warn: '\\x1b[35m',\n info: '\\x1b[33m',\n debug: '\\x1b[36m',\n error: '\\x1b[31m',\n end: '\\x1b[0m',\n };\n } else {\n this.colors = {\n start: '%c',\n warn: 'color : #ff00ff',\n info: 'color : #ffff00',\n debug: 'color : #00ffff',\n error: 'color : #ff0000',\n end: '',\n };\n }\n this.messageFormat = '[%t] [%l] - [%m]';\n }\n\n static setLevel(level) {\n _level = level;\n }\n\n /**\n *\n * @param level {string}\n * @returns {boolean}\n */\n canSend(level) {\n return (Logger.levels.indexOf(_level) >= Logger.levels.indexOf(level));\n }\n\n /**\n * @param message {string}\n */\n warn(message) {\n // todo remove later\n if (_level === 'debug') {\n // eslint-disable-next-line no-console\n console.error(new Error().stack);\n }\n this._log('warn', message, this.colors.warn);\n }\n\n /**\n * @param message {string}\n */\n info(message) {\n this._log('info', message, this.colors.info);\n }\n\n /**\n * @param message {string}\n */\n debug(message) {\n this._log('debug', message, this.colors.debug);\n }\n\n /**\n * @param message {string}\n */\n error(message) {\n // todo remove later\n if (_level === 'debug') {\n // eslint-disable-next-line no-console\n console.error(new Error().stack);\n }\n this._log('error', message, this.colors.error);\n }\n\n format(message, level) {\n return this.messageFormat.replace('%t', new Date().toISOString())\n .replace('%l', level.toUpperCase())\n .replace('%m', message);\n }\n\n /**\n * @param level {string}\n * @param message {string}\n * @param color {string}\n */\n _log(level, message, color) {\n if (!_level) {\n return;\n }\n if (this.canSend(level)) {\n if (!this.isBrowser) {\n // eslint-disable-next-line no-console\n console.log(color + this.format(message, level) + this.colors.end);\n } else {\n // eslint-disable-next-line no-console\n console.log(this.colors.start + this.format(message, level), color);\n }\n }\n }\n}\n\nmodule.exports = Logger;\n","const MessageContainer = require('../tl/core/MessageContainer');\nconst TLMessage = require('../tl/core/TLMessage');\nconst BinaryWriter = require('../extensions/BinaryWriter');\n\nconst USE_INVOKE_AFTER_WITH = [\n 'messages.SendMessage', 'messages.SendMedia', 'messages.SendMultiMedia',\n 'messages.ForwardMessages', 'messages.SendInlineBotResult',\n];\n\nclass MessagePacker {\n constructor(state, logger) {\n this._state = state;\n this._queue = [];\n this._pendingStates = [];\n this._ready = new Promise(((resolve) => {\n this.setReady = resolve;\n }));\n this._log = logger;\n }\n\n values() {\n return this._queue;\n }\n\n append(state) {\n // we need to check if there is already a request with the same name that we should send after.\n if (state && USE_INVOKE_AFTER_WITH.includes(state.request.className)) {\n // we now need to check if there is any request in queue already.\n // we loop backwards since the latest request is the most recent\n for (let i = this._queue.length - 1; i >= 0; i--) {\n if (USE_INVOKE_AFTER_WITH.includes(this._queue[i].request.className)) {\n state.after = this._queue[i];\n break;\n }\n }\n }\n\n\n this._queue.push(state);\n this.setReady(true);\n\n if (state) {\n this._pendingStates.push(state);\n state.promise\n // Using finally causes triggering `unhandledrejection` event\n .catch(() => {\n })\n .finally(() => {\n this._pendingStates = this._pendingStates.filter((s) => s !== state);\n });\n }\n }\n\n extend(states) {\n for (const state of states) {\n this._queue.push(state);\n }\n this.setReady(true);\n }\n\n async get() {\n if (!this._queue.length) {\n this._ready = new Promise(((resolve) => {\n this.setReady = resolve;\n }));\n await this._ready;\n }\n if (!this._queue[this._queue.length - 1]) {\n this._queue = [];\n return undefined;\n }\n let data;\n let buffer = new BinaryWriter(Buffer.alloc(0));\n\n const batch = [];\n let size = 0;\n\n while (this._queue.length && batch.length <= MessageContainer.MAXIMUM_LENGTH) {\n const state = this._queue.shift();\n size += state.data.length + TLMessage.SIZE_OVERHEAD;\n if (size <= MessageContainer.MAXIMUM_SIZE) {\n let afterId;\n if (state.after) {\n afterId = state.after.msgId;\n }\n state.msgId = await this._state.writeDataAsMessage(\n buffer, state.data, state.request.classType === 'request',\n afterId,\n );\n this._log.debug(`Assigned msgId = ${state.msgId} to ${state.request.className\n || state.request.constructor.name}`);\n batch.push(state);\n continue;\n }\n if (batch.length) {\n this._queue.unshift(state);\n break;\n }\n this._log.warn(`Message payload for ${state.request.className\n || state.request.constructor.name} is too long ${state.data.length} and cannot be sent`);\n state.reject('Request Payload is too big');\n size = 0;\n }\n if (!batch.length) {\n return undefined;\n }\n if (batch.length > 1) {\n const b = Buffer.alloc(8);\n b.writeUInt32LE(MessageContainer.CONSTRUCTOR_ID, 0);\n b.writeInt32LE(batch.length, 4);\n data = Buffer.concat([b, buffer.getValue()]);\n buffer = new BinaryWriter(Buffer.alloc(0));\n const containerId = await this._state.writeDataAsMessage(\n buffer, data, false,\n );\n for (const s of batch) {\n s.containerId = containerId;\n }\n }\n\n data = buffer.getValue();\n return {\n batch,\n data,\n };\n }\n\n rejectAll() {\n this._pendingStates.forEach((requestState) => {\n requestState.reject(new Error('Disconnect'));\n });\n }\n}\n\nmodule.exports = MessagePacker;\n","const { Mutex } = require('async-mutex');\n\nconst mutex = new Mutex();\n\nconst WebSocketClient = require('websocket').w3cwebsocket;\n\nconst closeError = new Error('WebSocket was closed');\n\nclass PromisedWebSockets {\n constructor(disconnectedCallback) {\n /* CONTEST\n this.isBrowser = typeof process === 'undefined' ||\n process.type === 'renderer' ||\n process.browser === true ||\n process.__nwjs\n\n */\n this.client = undefined;\n this.closed = true;\n this.disconnectedCallback = disconnectedCallback;\n }\n\n async readExactly(number) {\n let readData = Buffer.alloc(0);\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const thisTime = await this.read(number);\n readData = Buffer.concat([readData, thisTime]);\n number -= thisTime.length;\n if (!number) {\n return readData;\n }\n }\n }\n\n async read(number) {\n if (this.closed) {\n throw closeError;\n }\n await this.canRead;\n if (this.closed) {\n throw closeError;\n }\n const toReturn = this.stream.slice(0, number);\n this.stream = this.stream.slice(number);\n if (this.stream.length === 0) {\n this.canRead = new Promise((resolve) => {\n this.resolveRead = resolve;\n });\n }\n\n return toReturn;\n }\n\n async readAll() {\n if (this.closed || !await this.canRead) {\n throw closeError;\n }\n const toReturn = this.stream;\n this.stream = Buffer.alloc(0);\n this.canRead = new Promise((resolve) => {\n this.resolveRead = resolve;\n });\n\n return toReturn;\n }\n\n getWebSocketLink(ip, port) {\n if (port === 443) {\n return `wss://${ip}:${port}/apiws`;\n } else {\n return `ws://${ip}:${port}/apiws`;\n }\n }\n\n connect(port, ip) {\n this.stream = Buffer.alloc(0);\n this.canRead = new Promise((resolve) => {\n this.resolveRead = resolve;\n });\n this.closed = false;\n this.website = this.getWebSocketLink(ip, port);\n this.client = new WebSocketClient(this.website, 'binary');\n return new Promise((resolve, reject) => {\n this.client.onopen = () => {\n this.receive();\n resolve(this);\n };\n this.client.onerror = (error) => {\n // eslint-disable-next-line no-console\n console.error('WebSocket error', error);\n reject(error);\n };\n this.client.onclose = (event) => {\n const { code, reason, wasClean } = event;\n if (code !== 1000) {\n // eslint-disable-next-line no-console\n console.error(`Socket ${ip} closed. Code: ${code}, reason: ${reason}, was clean: ${wasClean}`);\n }\n\n this.resolveRead(false);\n this.closed = true;\n if (this.disconnectedCallback) {\n this.disconnectedCallback();\n }\n };\n // CONTEST\n // Seems to not be working, at least in a web worker\n // eslint-disable-next-line no-restricted-globals\n self.addEventListener('offline', async () => {\n await this.close();\n this.resolveRead(false);\n });\n });\n }\n\n write(data) {\n if (this.closed) {\n throw closeError;\n }\n this.client.send(data);\n }\n\n async close() {\n await this.client.close();\n this.closed = true;\n }\n\n receive() {\n this.client.onmessage = async (message) => {\n const release = await mutex.acquire();\n try {\n const data = message.data instanceof ArrayBuffer\n ? Buffer.from(message.data)\n : Buffer.from(await new Response(message.data).arrayBuffer());\n this.stream = Buffer.concat([this.stream, data]);\n this.resolveRead(true);\n } finally {\n release();\n }\n };\n }\n}\n\nmodule.exports = PromisedWebSockets;\n","const Logger = require('./Logger');\nconst BinaryWriter = require('./BinaryWriter');\nconst BinaryReader = require('./BinaryReader');\nconst PromisedWebSockets = require('./PromisedWebSockets');\nconst MessagePacker = require('./MessagePacker');\nconst AsyncQueue = require('./AsyncQueue');\n\nmodule.exports = {\n BinaryWriter,\n BinaryReader,\n MessagePacker,\n AsyncQueue,\n Logger,\n PromisedWebSockets,\n};\n","const Api = require('./tl/api');\nconst TelegramClient = require('./client/TelegramClient');\nconst connection = require('./network');\nconst tl = require('./tl');\nconst version = require('./Version');\nconst events = require('./events');\nconst utils = require('./Utils');\nconst errors = require('./errors');\nconst sessions = require('./sessions');\nconst extensions = require('./extensions');\nconst helpers = require('./Helpers');\n\nmodule.exports = {\n Api,\n TelegramClient,\n sessions,\n connection,\n extensions,\n tl,\n version,\n events,\n utils,\n errors,\n helpers,\n};\n","import bigInt from 'big-integer';\nimport {\n generateRandomBytes,\n modExp,\n readBigIntFromBuffer,\n readBufferFromBigInt,\n sha1,\n} from '../Helpers';\n\nconst PUBLIC_KEYS = [\n {\n fingerprint: bigInt('-3414540481677951611'),\n n: bigInt(\n '2937959817066933702298617714945612856538843112005886376816255642404751219133084745514657634448776440866'\n + '1701890505066208632169112269581063774293102577308490531282748465986139880977280302242772832972539403531'\n + '3160108704012876427630091361567343395380424193887227773571344877461690935390938502512438971889287359033'\n + '8945177273024525306296338410881284207988753897636046529094613963869149149606209957083647645485599631919'\n + '2747663615955633778034897140982517446405334423701359108810182097749467210509584293428076654573384828809'\n + '574217079944388301239431309115013843331317877374435868468779972014486325557807783825502498215169806323',\n ),\n e: 65537,\n },\n];\n\nexport const _serverKeys = new Map<string, { n: bigInt.BigInteger; e: number }>();\n\nPUBLIC_KEYS.forEach(({ fingerprint, ...keyInfo }) => {\n _serverKeys.set(fingerprint.toString(),\n keyInfo);\n});\n\n/**\n * Encrypts the given data known the fingerprint to be used\n * in the way Telegram requires us to do so (sha1(data) + data + padding)\n\n * @param fingerprint the fingerprint of the RSA key.\n * @param data the data to be encrypted.\n * @returns {Buffer|*|undefined} the cipher text, or undefined if no key matching this fingerprint is found.\n */\nexport async function encrypt(fingerprint: bigInt.BigInteger, data: Buffer) {\n const key = _serverKeys.get(fingerprint.toString());\n if (!key) {\n return undefined;\n }\n\n // len(sha1.digest) is always 20, so we're left with 255 - 20 - x padding\n const rand = generateRandomBytes(235 - data.length);\n\n const toEncrypt = Buffer.concat([await sha1(data), data, rand]);\n\n // rsa module rsa.encrypt adds 11 bits for padding which we don't want\n // rsa module uses rsa.transform.bytes2int(to_encrypt), easier way:\n const payload = readBigIntFromBuffer(toEncrypt, false);\n const encrypted = modExp(payload, bigInt(key.e), key.n);\n // rsa module uses transform.int2bytes(encrypted, keylength), easier:\n return readBufferFromBigInt(encrypted, 256, false);\n}\n","/**\n * Executes the authentication process with the Telegram servers.\n * @param sender a connected {MTProtoPlainSender}.\n * @param log\n * @returns {Promise<{authKey: *, timeOffset: *}>}\n */\n// eslint-disable-next-line import/no-named-default\nimport { default as Api } from '../tl/api';\nimport { SecurityError } from '../errors';\n// eslint-disable-next-line import/no-named-default\nimport { default as MTProtoPlainSender } from './MTProtoPlainSender';\nimport { _serverKeys } from '../crypto/RSA';\n\nconst bigInt = require('big-integer');\nconst IGE = require('../crypto/IGE');\nconst AuthKey = require('../crypto/AuthKey');\nconst Factorizator = require('../crypto/Factorizator');\nconst Helpers = require('../Helpers');\nconst BinaryReader = require('../extensions/BinaryReader');\n\nconst RETRIES = 20;\n\nexport async function doAuthentication(sender: MTProtoPlainSender, log: any) {\n // Step 1 sending: PQ Request, endianness doesn't matter since it's random\n let bytes = Helpers.generateRandomBytes(16);\n\n const nonce = Helpers.readBigIntFromBuffer(bytes, false, true);\n const resPQ = await sender.send(new Api.ReqPqMulti({ nonce }));\n log.debug('Starting authKey generation step 1');\n\n if (!(resPQ instanceof Api.ResPQ)) {\n throw new SecurityError(`Step 1 answer was ${resPQ}`);\n }\n if (resPQ.nonce.neq(nonce)) {\n throw new SecurityError('Step 1 invalid nonce from server');\n }\n const pq = Helpers.readBigIntFromBuffer(resPQ.pq, false, true);\n log.debug('Finished authKey generation step 1');\n // Step 2 sending: DH Exchange\n const { p, q } = Factorizator.factorize(pq);\n\n const pBuffer = Helpers.getByteArray(p);\n const qBuffer = Helpers.getByteArray(q);\n\n bytes = Helpers.generateRandomBytes(32);\n const newNonce = Helpers.readBigIntFromBuffer(bytes, true, true);\n const pqInnerData = new Api.PQInnerData({\n pq: Helpers.getByteArray(pq), // unsigned\n p: pBuffer,\n q: qBuffer,\n nonce: resPQ.nonce,\n serverNonce: resPQ.serverNonce,\n newNonce,\n }).getBytes();\n if (pqInnerData.length > 144) {\n throw new SecurityError('Step 1 invalid nonce from server');\n }\n let targetFingerprint;\n let targetKey;\n for (const fingerprint of resPQ.serverPublicKeyFingerprints) {\n targetKey = _serverKeys.get(fingerprint.toString());\n if (targetKey !== undefined) {\n targetFingerprint = fingerprint;\n break;\n }\n }\n if (targetFingerprint === undefined || targetKey === undefined) {\n throw new SecurityError(\n 'Step 2 could not find a valid key for fingerprints',\n );\n }\n // Value should be padded to be made 192 exactly\n const padding = Helpers.generateRandomBytes(192 - pqInnerData.length);\n const dataWithPadding = Buffer.concat([pqInnerData, padding]);\n const dataPadReversed = Buffer.from(dataWithPadding).reverse();\n\n let encryptedData;\n for (let i = 0; i < RETRIES; i++) {\n const tempKey = Helpers.generateRandomBytes(32);\n const shaDigestKeyWithData = await Helpers.sha256(Buffer.concat([tempKey, dataWithPadding]));\n const dataWithHash = Buffer.concat([dataPadReversed, shaDigestKeyWithData]);\n\n const ige = new IGE(tempKey, Buffer.alloc(32));\n const aesEncrypted = ige.encryptIge(dataWithHash);\n const tempKeyXor = Helpers.bufferXor(tempKey, await Helpers.sha256(aesEncrypted));\n\n const keyAesEncrypted = Buffer.concat([tempKeyXor, aesEncrypted]);\n const keyAesEncryptedInt = Helpers.readBigIntFromBuffer(keyAesEncrypted, false, false);\n if (keyAesEncryptedInt.greaterOrEquals(targetKey.n)) {\n log.debug('Aes key greater than RSA. retrying');\n continue;\n }\n const encryptedDataBuffer = Helpers.modExp(keyAesEncryptedInt, bigInt(targetKey.e), targetKey.n);\n encryptedData = Helpers.readBufferFromBigInt(encryptedDataBuffer, 256, false, false);\n\n break;\n }\n if (encryptedData === undefined) {\n throw new SecurityError(\n 'Step 2 could create a secure encrypted key',\n );\n }\n log.debug('Step 2 : Generated a secure aes encrypted data');\n\n const serverDhParams = await sender.send(\n new Api.ReqDHParams({\n nonce: resPQ.nonce,\n serverNonce: resPQ.serverNonce,\n p: pBuffer,\n q: qBuffer,\n publicKeyFingerprint: targetFingerprint,\n encryptedData,\n }),\n );\n\n if (\n !(\n serverDhParams instanceof Api.ServerDHParamsOk\n || serverDhParams instanceof Api.ServerDHParamsFail\n )\n ) {\n throw new Error(`Step 2.1 answer was ${serverDhParams}`);\n }\n if (serverDhParams.nonce.neq(resPQ.nonce)) {\n throw new SecurityError('Step 2 invalid nonce from server');\n }\n\n if (serverDhParams.serverNonce.neq(resPQ.serverNonce)) {\n throw new SecurityError('Step 2 invalid server nonce from server');\n }\n\n if (serverDhParams instanceof Api.ServerDHParamsFail) {\n const sh = await Helpers.sha1(\n Helpers.toSignedLittleBuffer(newNonce, 32).slice(4, 20),\n );\n const nnh = Helpers.readBigIntFromBuffer(sh, true, true);\n if (serverDhParams.newNonceHash.neq(nnh)) {\n throw new SecurityError('Step 2 invalid DH fail nonce from server');\n }\n }\n if (!(serverDhParams instanceof Api.ServerDHParamsOk)) {\n throw new Error(`Step 2.2 answer was ${serverDhParams}`);\n }\n log.debug('Finished authKey generation step 2');\n log.debug('Starting authKey generation step 3');\n\n // Step 3 sending: Complete DH Exchange\n const { key, iv } = await Helpers.generateKeyDataFromNonce(\n resPQ.serverNonce,\n newNonce,\n );\n if (serverDhParams.encryptedAnswer.length % 16 !== 0) {\n // See PR#453\n throw new SecurityError('Step 3 AES block size mismatch');\n }\n const ige = new IGE(key, iv);\n const plainTextAnswer = ige.decryptIge(serverDhParams.encryptedAnswer);\n const reader = new BinaryReader(plainTextAnswer);\n reader.read(20); // hash sum\n const serverDhInner = reader.tgReadObject();\n if (!(serverDhInner instanceof Api.ServerDHInnerData)) {\n throw new Error(`Step 3 answer was ${serverDhInner}`);\n }\n\n if (serverDhInner.nonce.neq(resPQ.nonce)) {\n throw new SecurityError('Step 3 Invalid nonce in encrypted answer');\n }\n if (serverDhInner.serverNonce.neq(resPQ.serverNonce)) {\n throw new SecurityError(\n 'Step 3 Invalid server nonce in encrypted answer',\n );\n }\n const dhPrime = Helpers.readBigIntFromBuffer(\n serverDhInner.dhPrime,\n false,\n false,\n );\n const ga = Helpers.readBigIntFromBuffer(serverDhInner.gA, false, false);\n const timeOffset = serverDhInner.serverTime - Math.floor(new Date().getTime() / 1000);\n const b = Helpers.readBigIntFromBuffer(\n Helpers.generateRandomBytes(256),\n false,\n false,\n );\n const gb = Helpers.modExp(bigInt(serverDhInner.g), b, dhPrime);\n const gab = Helpers.modExp(ga, b, dhPrime);\n\n // Prepare client DH Inner Data\n const clientDhInner = new Api.ClientDHInnerData({\n nonce: resPQ.nonce,\n serverNonce: resPQ.serverNonce,\n retryId: bigInt.zero, // TODO Actual retry ID\n gB: Helpers.getByteArray(gb, false),\n }).getBytes();\n\n const clientDdhInnerHashed = Buffer.concat([\n await Helpers.sha1(clientDhInner),\n clientDhInner,\n ]);\n // Encryption\n\n const clientDhEncrypted = ige.encryptIge(clientDdhInnerHashed);\n const dhGen = await sender.send(\n new Api.SetClientDHParams({\n nonce: resPQ.nonce,\n serverNonce: resPQ.serverNonce,\n encryptedData: clientDhEncrypted,\n }),\n );\n const nonceTypes = [Api.DhGenOk, Api.DhGenRetry, Api.DhGenFail];\n // TS being weird again.\n const nonceTypesString = ['DhGenOk', 'DhGenRetry', 'DhGenFail'];\n if (\n !(\n dhGen instanceof nonceTypes[0]\n || dhGen instanceof nonceTypes[1]\n || dhGen instanceof nonceTypes[2]\n )\n ) {\n throw new Error(`Step 3.1 answer was ${dhGen}`);\n }\n const { name } = dhGen.constructor;\n if (dhGen.nonce.neq(resPQ.nonce)) {\n throw new SecurityError(`Step 3 invalid ${name} nonce from server`);\n }\n if (dhGen.serverNonce.neq(resPQ.serverNonce)) {\n throw new SecurityError(\n `Step 3 invalid ${name} server nonce from server`,\n );\n }\n const authKey = new AuthKey();\n await authKey.setKey(Helpers.getByteArray(gab));\n\n const nonceNumber = 1 + nonceTypesString.indexOf(dhGen.className);\n\n const newNonceHash = await authKey.calcNewNonceHash(newNonce, nonceNumber);\n // @ts-ignore\n const dhHash = dhGen[`newNonceHash${nonceNumber}`];\n\n if (dhHash.neq(newNonceHash)) {\n throw new SecurityError('Step 3 invalid new nonce hash');\n }\n\n if (!(dhGen instanceof Api.DhGenOk)) {\n throw new Error(`Step 3.2 answer was ${dhGen}`);\n }\n log.debug('Finished authKey generation step 3');\n\n return { authKey, timeOffset };\n}\n","/**\n * This module contains the class used to communicate with Telegram's servers\n * in plain text, when no authorization key has been created yet.\n */\nconst BigInt = require('big-integer');\nconst MTProtoState = require('./MTProtoState');\nconst BinaryReader = require('../extensions/BinaryReader');\nconst { InvalidBufferError } = require('../errors/Common');\nconst { toSignedLittleBuffer } = require('../Helpers');\n\n/**\n * MTProto Mobile Protocol plain sender (https://core.telegram.org/mtproto/description#unencrypted-messages)\n */\n\nclass MTProtoPlainSender {\n /**\n * Initializes the MTProto plain sender.\n * @param connection connection: the Connection to be used.\n * @param loggers\n */\n constructor(connection, loggers) {\n this._state = new MTProtoState(connection, loggers);\n this._connection = connection;\n }\n\n /**\n * Sends and receives the result for the given request.\n * @param request\n */\n async send(request) {\n let body = request.getBytes();\n let msgId = this._state._getNewMsgId();\n const m = toSignedLittleBuffer(msgId, 8);\n const b = Buffer.alloc(4);\n b.writeInt32LE(body.length, 0);\n\n const res = Buffer.concat([Buffer.concat([Buffer.alloc(8), m, b]), body]);\n\n await this._connection.send(res);\n body = await this._connection.recv();\n if (body.length < 8) {\n throw new InvalidBufferError(body);\n }\n const reader = new BinaryReader(body);\n const authKeyId = reader.readLong();\n if (authKeyId.neq(BigInt(0))) {\n throw new Error('Bad authKeyId');\n }\n msgId = reader.readLong();\n if (msgId.eq(BigInt(0))) {\n throw new Error('Bad msgId');\n }\n /** ^ We should make sure that the read ``msg_id`` is greater\n * than our own ``msg_id``. However, under some circumstances\n * (bad system clock/working behind proxies) this seems to not\n * be the case, which would cause endless assertion errors.\n */\n\n const length = reader.readInt();\n if (length <= 0) {\n throw new Error('Bad length');\n }\n /**\n * We could read length bytes and use those in a new reader to read\n * the next TLObject without including the padding, but since the\n * reader isn't used for anything else after this, it's unnecessary.\n */\n return reader.tgReadObject();\n }\n}\n\nmodule.exports = MTProtoPlainSender;\n","const MtProtoPlainSender = require('./MTProtoPlainSender');\nconst MTProtoState = require('./MTProtoState');\nconst Helpers = require('../Helpers');\nconst AuthKey = require('../crypto/AuthKey');\nconst { doAuthentication } = require('./Authenticator');\nconst RPCResult = require('../tl/core/RPCResult');\nconst MessageContainer = require('../tl/core/MessageContainer');\nconst GZIPPacked = require('../tl/core/GZIPPacked');\nconst RequestState = require('./RequestState');\n\nconst {\n MsgsAck,\n upload,\n MsgsStateInfo,\n Pong,\n} = require('../tl').constructors;\nconst MessagePacker = require('../extensions/MessagePacker');\nconst BinaryReader = require('../extensions/BinaryReader');\nconst { UpdateConnectionState, UpdateServerTimeOffset } = require('./index');\nconst { BadMessageError } = require('../errors/Common');\nconst {\n BadServerSalt,\n BadMsgNotification,\n MsgDetailedInfo,\n MsgNewDetailedInfo,\n NewSessionCreated,\n FutureSalts,\n MsgsStateReq,\n MsgResendReq,\n MsgsAllInfo,\n} = require('../tl').constructors;\nconst { SecurityError } = require('../errors/Common');\nconst { InvalidBufferError } = require('../errors/Common');\nconst { LogOut } = require('../tl').requests.auth;\nconst { RPCMessageToError } = require('../errors');\nconst { TypeNotFoundError } = require('../errors/Common');\n\n\n/**\n * MTProto Mobile Protocol sender\n * (https://core.telegram.org/mtproto/description)\n * This class is responsible for wrapping requests into `TLMessage`'s,\n * sending them over the network and receiving them in a safe manner.\n *\n * Automatic reconnection due to temporary network issues is a concern\n * for this class as well, including retry of messages that could not\n * be sent successfully.\n *\n * A new authorization key will be generated on connection if no other\n * key exists yet.\n */\nclass MTProtoSender {\n static DEFAULT_OPTIONS = {\n logger: undefined,\n retries: Infinity,\n delay: 2000,\n autoReconnect: true,\n connectTimeout: undefined,\n authKeyCallback: undefined,\n updateCallback: undefined,\n autoReconnectCallback: undefined,\n isMainSender: undefined,\n onConnectionBreak: undefined,\n };\n\n /**\n * @param authKey\n * @param opts\n */\n constructor(authKey, opts) {\n const args = { ...MTProtoSender.DEFAULT_OPTIONS, ...opts };\n this._connection = undefined;\n this._log = args.logger;\n this._dcId = args.dcId;\n this._retries = args.retries;\n this._delay = args.delay;\n this._autoReconnect = args.autoReconnect;\n this._connectTimeout = args.connectTimeout;\n this._authKeyCallback = args.authKeyCallback;\n this._updateCallback = args.updateCallback;\n this._autoReconnectCallback = args.autoReconnectCallback;\n this._isMainSender = args.isMainSender;\n this._onConnectionBreak = args.onConnectionBreak;\n\n\n /**\n * whether we disconnected ourself or telegram did it.\n */\n this.userDisconnected = false;\n\n /**\n * Whether the user has explicitly connected or disconnected.\n *\n * If a disconnection happens for any other reason and it\n * was *not* user action then the pending messages won't\n * be cleared but on explicit user disconnection all the\n * pending futures should be cancelled.\n */\n this._user_connected = false;\n this._reconnecting = false;\n this._disconnected = true;\n\n /**\n * We need to join the loops upon disconnection\n */\n this._send_loop_handle = undefined;\n this._recv_loop_handle = undefined;\n\n /**\n * Preserving the references of the AuthKey and state is important\n */\n this.authKey = authKey || new AuthKey();\n this._state = new MTProtoState(this.authKey, this._log);\n\n /**\n * Outgoing messages are put in a queue and sent in a batch.\n * Note that here we're also storing their ``_RequestState``.\n */\n this._send_queue = new MessagePacker(this._state, this._log);\n\n /**\n * Sent states are remembered until a response is received.\n */\n this._pending_state = {};\n\n /**\n * Responses must be acknowledged, and we can also batch these.\n */\n this._pending_ack = new Set();\n\n /**\n * Similar to pending_messages but only for the last acknowledges.\n * These can't go in pending_messages because no acknowledge for them\n * is received, but we may still need to resend their state on bad salts.\n */\n this._last_acks = [];\n\n /**\n * Jump table from response ID to method that handles it\n */\n\n this._handlers = {\n [RPCResult.CONSTRUCTOR_ID]: this._handleRPCResult.bind(this),\n [MessageContainer.CONSTRUCTOR_ID]: this._handleContainer.bind(this),\n [GZIPPacked.CONSTRUCTOR_ID]: this._handleGzipPacked.bind(this),\n [Pong.CONSTRUCTOR_ID]: this._handlePong.bind(this),\n [BadServerSalt.CONSTRUCTOR_ID]: this._handleBadServerSalt.bind(this),\n [BadMsgNotification.CONSTRUCTOR_ID]: this._handleBadNotification.bind(this),\n [MsgDetailedInfo.CONSTRUCTOR_ID]: this._handleDetailedInfo.bind(this),\n [MsgNewDetailedInfo.CONSTRUCTOR_ID]: this._handleNewDetailedInfo.bind(this),\n [NewSessionCreated.CONSTRUCTOR_ID]: this._handleNewSessionCreated.bind(this),\n [MsgsAck.CONSTRUCTOR_ID]: this._handleAck.bind(this),\n [FutureSalts.CONSTRUCTOR_ID]: this._handleFutureSalts.bind(this),\n [MsgsStateReq.CONSTRUCTOR_ID]: this._handleStateForgotten.bind(this),\n [MsgResendReq.CONSTRUCTOR_ID]: this._handleStateForgotten.bind(this),\n [MsgsAllInfo.CONSTRUCTOR_ID]: this._handleMsgAll.bind(this),\n };\n }\n\n // Public API\n\n /**\n * Connects to the specified given connection using the given auth key.\n * @param connection\n * @param [force]\n * @returns {Promise<boolean>}\n */\n async connect(connection, force) {\n if (this._user_connected && !force) {\n this._log.info('User is already connected!');\n return false;\n }\n this.isConnecting = true;\n this._connection = connection;\n\n for (let attempt = 0; attempt < this._retries; attempt++) {\n try {\n await this._connect();\n if (this._updateCallback) {\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.connected));\n }\n break;\n } catch (err) {\n if (this._updateCallback && attempt === 0) {\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.disconnected));\n }\n this._log.error(`WebSocket connection failed attempt: ${attempt + 1}`);\n // eslint-disable-next-line no-console\n console.error(err);\n await Helpers.sleep(this._delay);\n }\n }\n this.isConnecting = false;\n return true;\n }\n\n isConnected() {\n return this._user_connected;\n }\n\n /**\n * Cleanly disconnects the instance from the network, cancels\n * all pending requests, and closes the send and receive loops.\n */\n async disconnect() {\n this.userDisconnected = true;\n await this._disconnect();\n }\n\n /**\n *\n This method enqueues the given request to be sent. Its send\n state will be saved until a response arrives, and a ``Future``\n that will be resolved when the response arrives will be returned:\n\n .. code-block:: javascript\n\n async def method():\n # Sending (enqueued for the send loop)\n future = sender.send(request)\n # Receiving (waits for the receive loop to read the result)\n result = await future\n\n Designed like this because Telegram may send the response at\n any point, and it can send other items while one waits for it.\n Once the response for this future arrives, it is set with the\n received result, quite similar to how a ``receive()`` call\n would otherwise work.\n\n Since the receiving part is \"built in\" the future, it's\n impossible to await receive a result that was never sent.\n * @param request\n * @returns {RequestState}\n */\n send(request) {\n if (!this._user_connected) {\n throw new Error('Cannot send requests while disconnected');\n }\n const state = new RequestState(request);\n this._send_queue.append(state);\n return state.promise;\n }\n\n /**\n * Same as send but returns the full state. usefull for invoke after logic\n * @param request\n * @return {RequestState}\n */\n sendWithInvokeSupport(request) {\n if (!this._user_connected) {\n throw new Error('Cannot send requests while disconnected');\n }\n const state = new RequestState(request, undefined, this._pending_state);\n this._send_queue.append(state);\n return state;\n }\n\n /**\n * Performs the actual connection, retrying, generating the\n * authorization key if necessary, and starting the send and\n * receive loops.\n * @returns {Promise<void>}\n * @private\n */\n async _connect() {\n this._log.info('Connecting to {0}...'.replace('{0}', this._connection));\n await this._connection.connect();\n this._log.debug('Connection success!');\n // process.exit(0)\n if (!this.authKey.getKey()) {\n const plain = new MtProtoPlainSender(this._connection, this._log);\n this._log.debug('New auth_key attempt ...');\n const res = await doAuthentication(plain, this._log);\n this._log.debug('Generated new auth_key successfully');\n await this.authKey.setKey(res.authKey);\n\n this._state.timeOffset = res.timeOffset;\n\n if (this._updateCallback) {\n this._updateCallback(new UpdateServerTimeOffset(this._state.timeOffset));\n }\n\n /**\n * This is *EXTREMELY* important since we don't control\n * external references to the authorization key, we must\n * notify whenever we change it. This is crucial when we\n * switch to different data centers.\n */\n if (this._authKeyCallback) {\n await this._authKeyCallback(this.authKey, this._dcId);\n }\n } else {\n this._authenticated = true;\n this._log.debug('Already have an auth key ...');\n }\n this._user_connected = true;\n this._reconnecting = false;\n\n this._log.debug('Starting send loop');\n this._send_loop_handle = this._sendLoop();\n\n this._log.debug('Starting receive loop');\n this._recv_loop_handle = this._recvLoop();\n\n // _disconnected only completes after manual disconnection\n // or errors after which the sender cannot continue such\n // as failing to reconnect or any unexpected error.\n\n this._log.info('Connection to %s complete!'.replace('%s', this._connection.toString()));\n }\n\n async _disconnect() {\n this._send_queue.rejectAll();\n\n if (this._connection === undefined) {\n this._log.info('Not disconnecting (already have no connection)');\n return;\n }\n if (this._updateCallback) {\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.disconnected));\n }\n this._log.info('Disconnecting from %s...'.replace('%s', this._connection.toString()));\n this._user_connected = false;\n this._log.debug('Closing current connection...');\n await this._connection.disconnect();\n }\n\n /**\n * This loop is responsible for popping items off the send\n * queue, encrypting them, and sending them over the network.\n * Besides `connect`, only this method ever sends data.\n * @returns {Promise<void>}\n * @private\n */\n async _sendLoop() {\n this._send_queue = new MessagePacker(this._state, this._log);\n\n while (this._user_connected && !this._reconnecting) {\n if (this._pending_ack.size) {\n const ack = new RequestState(new MsgsAck({ msgIds: Array(...this._pending_ack) }));\n this._send_queue.append(ack);\n this._last_acks.push(ack);\n this._pending_ack.clear();\n }\n this._log.debug(`Waiting for messages to send...${this._reconnecting}`);\n // TODO Wait for the connection send queue to be empty?\n // This means that while it's not empty we can wait for\n // more messages to be added to the send queue.\n const res = await this._send_queue.get();\n\n if (this._reconnecting) {\n return;\n }\n\n if (!res) {\n continue;\n }\n let { data } = res;\n const { batch } = res;\n this._log.debug(`Encrypting ${batch.length} message(s) in ${data.length} bytes for sending`);\n\n data = await this._state.encryptMessageData(data);\n\n try {\n await this._connection.send(data);\n } catch (e) {\n this._log.error(e);\n this._log.info('Connection closed while sending data');\n return;\n }\n for (const state of batch) {\n if (!Array.isArray(state)) {\n if (state.request.classType === 'request') {\n this._pending_state[state.msgId] = state;\n }\n } else {\n for (const s of state) {\n if (s.request.classType === 'request') {\n this._pending_state[s.msgId] = s;\n }\n }\n }\n }\n this._log.debug('Encrypted messages put in a queue to be sent');\n }\n }\n\n async _recvLoop() {\n let body;\n let message;\n\n while (this._user_connected && !this._reconnecting) {\n // this._log.debug('Receiving items from the network...');\n this._log.debug('Receiving items from the network...');\n try {\n body = await this._connection.recv();\n } catch (e) {\n // this._log.info('Connection closed while receiving data');\n /** when the server disconnects us we want to reconnect */\n if (!this.userDisconnected) {\n this._log.error(e);\n this._log.warn('Connection closed while receiving data');\n this.reconnect();\n }\n return;\n }\n try {\n message = await this._state.decryptMessageData(body);\n } catch (e) {\n if (e instanceof TypeNotFoundError) {\n // Received object which we don't know how to deserialize\n this._log.info(`Type ${e.invalidConstructorId} not found, remaining data ${e.remaining}`);\n continue;\n } else if (e instanceof SecurityError) {\n // A step while decoding had the incorrect data. This message\n // should not be considered safe and it should be ignored.\n this._log.warn(`Security error while unpacking a received message: ${e}`);\n continue;\n } else if (e instanceof InvalidBufferError) {\n // 404 means that the server has \"forgotten\" our auth key and we need to create a new one.\n if (e.code === 404) {\n this._log.warn(`Broken authorization key for dc ${this._dcId}; resetting`);\n if (this._updateCallback && this._isMainSender) {\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.broken));\n } else if (this._onConnectionBreak && !this._isMainSender) {\n // Deletes the current sender from the object\n this._onConnectionBreak(this._dcId);\n }\n } else {\n // this happens sometimes when telegram is having some internal issues.\n // reconnecting should be enough usually\n // since the data we sent and received is probably wrong now.\n this._log.warn(`Invalid buffer ${e.code} for dc ${this._dcId}`);\n this.reconnect();\n }\n return;\n } else {\n this._log.error('Unhandled error while receiving data');\n this._log.error(e);\n this.reconnect();\n return;\n }\n }\n try {\n await this._processMessage(message);\n } catch (e) {\n this._log.error('Unhandled error while receiving data');\n this._log.error(e);\n }\n }\n }\n\n // Response Handlers\n\n /**\n * Adds the given message to the list of messages that must be\n * acknowledged and dispatches control to different ``_handle_*``\n * method based on its type.\n * @param message\n * @returns {Promise<void>}\n * @private\n */\n async _processMessage(message) {\n this._pending_ack.add(message.msgId);\n // eslint-disable-next-line require-atomic-updates\n message.obj = await message.obj;\n let handler = this._handlers[message.obj.CONSTRUCTOR_ID];\n if (!handler) {\n handler = this._handleUpdate.bind(this);\n }\n\n await handler(message);\n }\n\n /**\n * Pops the states known to match the given ID from pending messages.\n * This method should be used when the response isn't specific.\n * @param msgId\n * @returns {*[]}\n * @private\n */\n _popStates(msgId) {\n let state = this._pending_state[msgId];\n if (state) {\n this._pending_state[msgId].deferred.resolve();\n delete this._pending_state[msgId];\n return [state];\n }\n\n const toPop = [];\n\n for (state of Object.values(this._pending_state)) {\n if (state.containerId && state.containerId.equals(msgId)) {\n toPop.push(state.msgId);\n }\n }\n\n if (toPop.length) {\n const temp = [];\n for (const x of toPop) {\n temp.push(this._pending_state[x]);\n this._pending_state[x].deferred.resolve();\n delete this._pending_state[x];\n }\n return temp;\n }\n\n for (const ack of this._last_acks) {\n if (ack.msgId === msgId) {\n return [ack];\n }\n }\n\n return [];\n }\n\n /**\n * Handles the result for Remote Procedure Calls:\n * rpc_result#f35c6d01 req_msg_id:long result:bytes = RpcResult;\n * This is where the future results for sent requests are set.\n * @param message\n * @returns {Promise<void>}\n * @private\n */\n _handleRPCResult(message) {\n const result = message.obj;\n const state = this._pending_state[result.reqMsgId];\n if (state) {\n state.deferred.resolve();\n delete this._pending_state[result.reqMsgId];\n }\n this._log.debug(`Handling RPC result for message ${result.reqMsgId}`);\n\n if (!state) {\n // TODO We should not get responses to things we never sent\n // However receiving a File() with empty bytes is \"common\".\n // See #658, #759 and #958. They seem to happen in a container\n // which contain the real response right after.\n try {\n const reader = new BinaryReader(result.body);\n if (!(reader.tgReadObject() instanceof upload.File)) {\n throw new TypeNotFoundError('Not an upload.File');\n }\n } catch (e) {\n this._log.error(e);\n if (e instanceof TypeNotFoundError) {\n this._log.info(`Received response without parent request: ${result.body}`);\n return;\n } else {\n throw e;\n }\n }\n }\n if (result.error) {\n // eslint-disable-next-line new-cap\n const error = RPCMessageToError(result.error, state.request);\n this._send_queue.append(new RequestState(new MsgsAck({ msgIds: [state.msgId] })));\n state.reject(error);\n } else {\n const reader = new BinaryReader(result.body);\n const read = state.request.readResult(reader);\n state.resolve(read);\n }\n }\n\n /**\n * Processes the inner messages of a container with many of them:\n * msg_container#73f1f8dc messages:vector<%Message> = MessageContainer;\n * @param message\n * @returns {Promise<void>}\n * @private\n */\n async _handleContainer(message) {\n this._log.debug('Handling container');\n for (const innerMessage of message.obj.messages) {\n await this._processMessage(innerMessage);\n }\n }\n\n /**\n * Unpacks the data from a gzipped object and processes it:\n * gzip_packed#3072cfa1 packed_data:bytes = Object;\n * @param message\n * @returns {Promise<void>}\n * @private\n */\n async _handleGzipPacked(message) {\n this._log.debug('Handling gzipped data');\n const reader = new BinaryReader(message.obj.data);\n message.obj = reader.tgReadObject();\n await this._processMessage(message);\n }\n\n _handleUpdate(message) {\n if (message.obj.SUBCLASS_OF_ID !== 0x8af52aac) {\n // crc32(b'Updates')\n this._log.warn(`Note: ${message.obj.className} is not an update, not dispatching it`);\n return;\n }\n this._log.debug(`Handling update ${message.obj.className}`);\n if (this._updateCallback) {\n this._updateCallback(message.obj);\n }\n }\n\n /**\n * Handles pong results, which don't come inside a ``RPCResult``\n * but are still sent through a request:\n * pong#347773c5 msg_id:long ping_id:long = Pong;\n * @param message\n * @returns {Promise<void>}\n * @private\n */\n _handlePong(message) {\n const pong = message.obj;\n\n const newTimeOffset = this._state.updateTimeOffset(message.msgId);\n if (this._updateCallback) {\n this._updateCallback(new UpdateServerTimeOffset(newTimeOffset));\n }\n\n this._log.debug(`Handling pong for message ${pong.msgId}`);\n const state = this._pending_state[pong.msgId];\n this._pending_state[pong.msgId].deferred.resolve();\n delete this._pending_state[pong.msgId];\n\n // Todo Check result\n if (state) {\n state.resolve(pong);\n }\n }\n\n /**\n * Corrects the currently used server salt to use the right value\n * before enqueuing the rejected message to be re-sent:\n * bad_server_salt#edab447b bad_msg_id:long bad_msg_seqno:int\n * error_code:int new_server_salt:long = BadMsgNotification;\n * @param message\n * @returns {Promise<void>}\n * @private\n */\n _handleBadServerSalt(message) {\n const badSalt = message.obj;\n this._log.debug(`Handling bad salt for message ${badSalt.badMsgId}`);\n this._state.salt = badSalt.newServerSalt;\n const states = this._popStates(badSalt.badMsgId);\n this._send_queue.extend(states);\n this._log.debug(`${states.length} message(s) will be resent`);\n }\n\n /**\n * Adjusts the current state to be correct based on the\n * received bad message notification whenever possible:\n * bad_msg_notification#a7eff811 bad_msg_id:long bad_msg_seqno:int\n * error_code:int = BadMsgNotification;\n * @param message\n * @returns {Promise<void>}\n * @private\n */\n _handleBadNotification(message) {\n const badMsg = message.obj;\n const states = this._popStates(badMsg.badMsgId);\n this._log.debug(`Handling bad msg ${JSON.stringify(badMsg)}`);\n if ([16, 17].includes(badMsg.errorCode)) {\n // Sent msg_id too low or too high (respectively).\n // Use the current msg_id to determine the right time offset.\n const newTimeOffset = this._state.updateTimeOffset(message.msgId);\n\n if (this._updateCallback) {\n this._updateCallback(new UpdateServerTimeOffset(newTimeOffset));\n }\n\n this._log.info(`System clock is wrong, set time offset to ${newTimeOffset}s`);\n } else if (badMsg.errorCode === 32) {\n // msg_seqno too low, so just pump it up by some \"large\" amount\n // TODO A better fix would be to start with a new fresh session ID\n this._state._sequence += 64;\n } else if (badMsg.errorCode === 33) {\n // msg_seqno too high never seems to happen but just in case\n this._state._sequence -= 16;\n } else {\n for (const state of states) {\n state.reject(new BadMessageError(state.request, badMsg.errorCode));\n }\n\n return;\n }\n // Messages are to be re-sent once we've corrected the issue\n this._send_queue.extend(states);\n this._log.debug(`${states.length} messages will be resent due to bad msg`);\n }\n\n /**\n * Updates the current status with the received detailed information:\n * msg_detailed_info#276d3ec6 msg_id:long answer_msg_id:long\n * bytes:int status:int = MsgDetailedInfo;\n * @param message\n * @returns {Promise<void>}\n * @private\n */\n _handleDetailedInfo(message) {\n // TODO https://goo.gl/VvpCC6\n const msgId = message.obj.answerMsgId;\n this._log.debug(`Handling detailed info for message ${msgId}`);\n this._pending_ack.add(msgId);\n }\n\n /**\n * Updates the current status with the received detailed information:\n * msg_new_detailed_info#809db6df answer_msg_id:long\n * bytes:int status:int = MsgDetailedInfo;\n * @param message\n * @returns {Promise<void>}\n * @private\n */\n _handleNewDetailedInfo(message) {\n // TODO https://goo.gl/VvpCC6\n const msgId = message.obj.answerMsgId;\n this._log.debug(`Handling new detailed info for message ${msgId}`);\n this._pending_ack.add(msgId);\n }\n\n /**\n * Updates the current status with the received session information:\n * new_session_created#9ec20908 first_msg_id:long unique_id:long\n * server_salt:long = NewSession;\n * @param message\n * @returns {Promise<void>}\n * @private\n */\n _handleNewSessionCreated(message) {\n // TODO https://goo.gl/LMyN7A\n this._log.debug('Handling new session created');\n this._state.salt = message.obj.serverSalt;\n }\n\n /**\n * Handles a server acknowledge about our messages. Normally\n * these can be ignored except in the case of ``auth.logOut``:\n *\n * auth.logOut#5717da40 = Bool;\n *\n * Telegram doesn't seem to send its result so we need to confirm\n * it manually. No other request is known to have this behaviour.\n\n * Since the ID of sent messages consisting of a container is\n * never returned (unless on a bad notification), this method\n * also removes containers messages when any of their inner\n * messages are acknowledged.\n\n * @param message\n * @returns {Promise<void>}\n * @private\n */\n _handleAck(message) {\n const ack = message.obj;\n this._log.debug(`Handling acknowledge for ${ack.msgIds}`);\n for (const msgId of ack.msgIds) {\n const state = this._pending_state[msgId];\n if (state && state.request instanceof LogOut) {\n this._pending_state[msgId].deferred.resolve();\n delete this._pending_state[msgId];\n state.resolve(true);\n }\n }\n }\n\n /**\n * Handles future salt results, which don't come inside a\n * ``rpc_result`` but are still sent through a request:\n * future_salts#ae500895 req_msg_id:long now:int\n * salts:vector<future_salt> = FutureSalts;\n * @param message\n * @returns {Promise<void>}\n * @private\n */\n _handleFutureSalts(message) {\n // TODO save these salts and automatically adjust to the\n // correct one whenever the salt in use expires.\n this._log.debug(`Handling future salts for message ${message.msgId}`);\n const state = this._pending_state[message.msgId];\n\n if (state) {\n this._pending_state[message].deferred.resolve();\n delete this._pending_state[message];\n state.resolve(message.obj);\n }\n }\n\n /**\n * Handles both :tl:`MsgsStateReq` and :tl:`MsgResendReq` by\n * enqueuing a :tl:`MsgsStateInfo` to be sent at a later point.\n * @param message\n * @returns {Promise<void>}\n * @private\n */\n _handleStateForgotten(message) {\n this._send_queue.append(\n new RequestState(new MsgsStateInfo(message.msgId, String.fromCharCode(1)\n .repeat(message.obj.msgIds))),\n );\n }\n\n /**\n * Handles :tl:`MsgsAllInfo` by doing nothing (yet).\n * used as part of the telegram protocol https://core.telegram.org/mtproto/service_messages_about_messages\n * This message does not require an acknowledgment.\n * @param message\n * @returns {Promise<void>}\n * @private\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _handleMsgAll(message) {\n }\n\n reconnect() {\n if (this._user_connected && !this._reconnecting) {\n this._reconnecting = true;\n // TODO Should we set this?\n // this._user_connected = false\n // we want to wait a second between each reconnect try to not flood the server with reconnects\n // in case of internal server issues.\n Helpers.sleep(1000).then(() => {\n this._log.info('Started reconnecting');\n this._reconnect();\n });\n }\n }\n\n async _reconnect() {\n this._log.debug('Closing current connection...');\n try {\n await this._disconnect();\n } catch (err) {\n this._log.warn(err);\n }\n\n this._send_queue.append(undefined);\n this._state.reset();\n\n // For some reason reusing existing connection caused stuck requests\n const newConnection = new this._connection.constructor(\n this._connection._ip,\n this._connection._port,\n this._connection._dcId,\n this._connection._log,\n );\n await this.connect(newConnection, true);\n\n this._reconnecting = false;\n // uncomment this if you want to resend\n // this._send_queue.extend(Object.values(this._pending_state))\n for (const state of Object.values(this._pending_state)) {\n state.deferred.resolve();\n }\n this._pending_state = {};\n if (this._autoReconnectCallback) {\n await this._autoReconnectCallback();\n }\n }\n}\n\nmodule.exports = MTProtoSender;\n","const BigInt = require('big-integer');\n\nconst Helpers = require('../Helpers');\nconst IGE = require('../crypto/IGE');\nconst BinaryReader = require('../extensions/BinaryReader');\nconst GZIPPacked = require('../tl/core/GZIPPacked');\nconst { TLMessage } = require('../tl/core');\nconst {\n SecurityError,\n InvalidBufferError,\n} = require('../errors/Common');\nconst { InvokeAfterMsg } = require('../tl').requests;\nconst {\n toSignedLittleBuffer,\n} = require('../Helpers');\n\nclass MTProtoState {\n /**\n *\n `telethon.network.mtprotosender.MTProtoSender` needs to hold a state\n in order to be able to encrypt and decrypt incoming/outgoing messages,\n as well as generating the message IDs. Instances of this class hold\n together all the required information.\n\n It doesn't make sense to use `telethon.sessions.abstract.Session` for\n the sender because the sender should *not* be concerned about storing\n this information to disk, as one may create as many senders as they\n desire to any other data center, or some CDN. Using the same session\n for all these is not a good idea as each need their own authkey, and\n the concept of \"copying\" sessions with the unnecessary entities or\n updates state for these connections doesn't make sense.\n\n While it would be possible to have a `MTProtoPlainState` that does no\n encryption so that it was usable through the `MTProtoLayer` and thus\n avoid the need for a `MTProtoPlainSender`, the `MTProtoLayer` is more\n focused to efficiency and this state is also more advanced (since it\n supports gzipping and invoking after other message IDs). There are too\n many methods that would be needed to make it convenient to use for the\n authentication process, at which point the `MTProtoPlainSender` is better\n * @param authKey\n * @param loggers\n */\n constructor(authKey, loggers) {\n this.authKey = authKey;\n this._log = loggers;\n this.timeOffset = 0;\n this.salt = 0;\n\n this.id = undefined;\n this._sequence = undefined;\n this._lastMsgId = undefined;\n this.reset();\n }\n\n /**\n * Resets the state\n */\n reset() {\n // Session IDs can be random on every connection\n this.id = Helpers.generateRandomLong(true);\n this._sequence = 0;\n this._lastMsgId = BigInt(0);\n }\n\n /**\n * Updates the message ID to a new one,\n * used when the time offset changed.\n * @param message\n */\n updateMessageId(message) {\n message.msgId = this._getNewMsgId();\n }\n\n /**\n * Calculate the key based on Telegram guidelines, specifying whether it's the client or not\n * @param authKey\n * @param msgKey\n * @param client\n * @returns {{iv: Buffer, key: Buffer}}\n */\n async _calcKey(authKey, msgKey, client) {\n const x = client === true ? 0 : 8;\n const [sha256a, sha256b] = await Promise.all([\n Helpers.sha256(Buffer.concat([msgKey, authKey.slice(x, x + 36)])),\n Helpers.sha256(Buffer.concat([authKey.slice(x + 40, x + 76), msgKey])),\n ]);\n const key = Buffer.concat([sha256a.slice(0, 8), sha256b.slice(8, 24), sha256a.slice(24, 32)]);\n const iv = Buffer.concat([sha256b.slice(0, 8), sha256a.slice(8, 24), sha256b.slice(24, 32)]);\n return {\n key,\n iv,\n };\n }\n\n /**\n * Writes a message containing the given data into buffer.\n * Returns the message id.\n * @param buffer\n * @param data\n * @param contentRelated\n * @param afterId\n */\n async writeDataAsMessage(buffer, data, contentRelated, afterId) {\n const msgId = this._getNewMsgId();\n const seqNo = this._getSeqNo(contentRelated);\n let body;\n if (!afterId) {\n body = await GZIPPacked.gzipIfSmaller(contentRelated, data);\n } else {\n // Invoke query expects a query with a getBytes func\n body = await GZIPPacked.gzipIfSmaller(contentRelated, new InvokeAfterMsg(afterId, {\n getBytes() {\n return data;\n },\n }).getBytes());\n }\n const s = Buffer.alloc(4);\n s.writeInt32LE(seqNo, 0);\n const b = Buffer.alloc(4);\n b.writeInt32LE(body.length, 0);\n const m = toSignedLittleBuffer(msgId, 8);\n buffer.write(Buffer.concat([m, s, b]));\n buffer.write(body);\n return msgId;\n }\n\n /**\n * Encrypts the given message data using the current authorization key\n * following MTProto 2.0 guidelines core.telegram.org/mtproto/description.\n * @param data\n */\n async encryptMessageData(data) {\n await this.authKey.waitForKey();\n const s = toSignedLittleBuffer(this.salt, 8);\n const i = toSignedLittleBuffer(this.id, 8);\n data = Buffer.concat([Buffer.concat([s, i]), data]);\n const padding = Helpers.generateRandomBytes(Helpers.mod(-(data.length + 12), 16) + 12);\n // Being substr(what, offset, length); x = 0 for client\n // \"msg_key_large = SHA256(substr(auth_key, 88+x, 32) + pt + padding)\"\n const msgKeyLarge = await Helpers.sha256(Buffer.concat([this.authKey.getKey()\n .slice(88, 88 + 32), data, padding]));\n // \"msg_key = substr (msg_key_large, 8, 16)\"\n const msgKey = msgKeyLarge.slice(8, 24);\n\n const {\n iv,\n key,\n } = await this._calcKey(this.authKey.getKey(), msgKey, true);\n\n const keyId = Helpers.readBufferFromBigInt(this.authKey.keyId, 8);\n return Buffer.concat([keyId, msgKey, new IGE(key, iv).encryptIge(Buffer.concat([data, padding]))]);\n }\n\n /**\n * Inverse of `encrypt_message_data` for incoming server messages.\n * @param body\n */\n async decryptMessageData(body) {\n if (body.length < 8) {\n throw new InvalidBufferError(body);\n }\n if (body.length < 0) { // length needs to be positive\n throw new SecurityError('Server replied with negative length');\n }\n if (body.length % 4 !== 0) {\n throw new SecurityError('Server replied with length not divisible by 4');\n }\n // TODO Check salt,sessionId, and sequenceNumber\n const keyId = Helpers.readBigIntFromBuffer(body.slice(0, 8));\n if (keyId.neq(this.authKey.keyId)) {\n throw new SecurityError('Server replied with an invalid auth key');\n }\n\n const msgKey = body.slice(8, 24);\n const {\n iv,\n key,\n } = await this._calcKey(this.authKey.getKey(), msgKey, false);\n body = new IGE(key, iv).decryptIge(body.slice(24));\n\n // https://core.telegram.org/mtproto/security_guidelines\n // Sections \"checking sha256 hash\" and \"message length\"\n\n const ourKey = await Helpers.sha256(Buffer.concat([this.authKey.getKey()\n .slice(96, 96 + 32), body]));\n\n if (!msgKey.equals(ourKey.slice(8, 24))) {\n throw new SecurityError('Received msg_key doesn\\'t match with expected one');\n }\n\n const reader = new BinaryReader(body);\n reader.readLong(); // removeSalt\n const serverId = reader.readLong();\n if (!serverId.eq(this.id)) {\n throw new SecurityError('Server replied with a wrong session ID');\n }\n\n const remoteMsgId = reader.readLong();\n const remoteSequence = reader.readInt();\n const containerLen = reader.readInt(); // msgLen for the inner object, padding ignored\n const diff = body.length - containerLen;\n // We want to check if it's between 12 and 1024\n // https://core.telegram.org/mtproto/security_guidelines#checking-message-length\n if (diff < 12 || diff > 1024) {\n throw new SecurityError('Server replied with the wrong message padding');\n }\n\n // We could read msg_len bytes and use those in a new reader to read\n // the next TLObject without including the padding, but since the\n // reader isn't used for anything else after this, it's unnecessary.\n const obj = reader.tgReadObject();\n\n return new TLMessage(remoteMsgId, remoteSequence, obj);\n }\n\n /**\n * Generates a new unique message ID based on the current\n * time (in ms) since epoch, applying a known time offset.\n * @private\n */\n _getNewMsgId() {\n const now = new Date().getTime() / 1000 + this.timeOffset;\n const nanoseconds = Math.floor((now - Math.floor(now)) * 1e9);\n let newMsgId = (BigInt(Math.floor(now))\n .shiftLeft(BigInt(32))).or(BigInt(nanoseconds)\n .shiftLeft(BigInt(2)));\n if (this._lastMsgId.greaterOrEquals(newMsgId)) {\n newMsgId = this._lastMsgId.add(BigInt(4));\n }\n this._lastMsgId = newMsgId;\n return newMsgId;\n }\n\n /**\n * Updates the time offset to the correct\n * one given a known valid message ID.\n * @param correctMsgId {BigInteger}\n */\n updateTimeOffset(correctMsgId) {\n const bad = this._getNewMsgId();\n const old = this.timeOffset;\n const now = Math.floor(new Date().getTime() / 1000);\n const correct = correctMsgId.shiftRight(BigInt(32));\n this.timeOffset = correct - now;\n\n if (this.timeOffset !== old) {\n this._lastMsgId = BigInt(0);\n this._log.debug(\n `Updated time offset (old offset ${old}, bad ${bad}, good ${correctMsgId}, new ${this.timeOffset})`,\n );\n }\n\n return this.timeOffset;\n }\n\n /**\n * Generates the next sequence number depending on whether\n * it should be for a content-related query or not.\n * @param contentRelated\n * @private\n */\n _getSeqNo(contentRelated) {\n if (contentRelated) {\n const result = this._sequence * 2 + 1;\n this._sequence += 1;\n return result;\n } else {\n return this._sequence * 2;\n }\n }\n}\n\nmodule.exports = MTProtoState;\n","const { createDeferred } = require('../Helpers');\n\nclass RequestState {\n constructor(request, after = undefined, pending = {}) {\n this.containerId = undefined;\n this.msgId = undefined;\n this.request = request;\n this.data = request.getBytes();\n this.after = after;\n this.result = undefined;\n this.pending = pending;\n this.deferred = createDeferred();\n this.promise = new Promise((resolve, reject) => {\n this.resolve = resolve;\n this.reject = reject;\n });\n }\n\n isReady() {\n const state = this.pending[this.after.id];\n if (!state) {\n return true;\n }\n return state.deferred.promise;\n }\n}\n\nmodule.exports = RequestState;\n","const PromisedWebSockets = require('../../extensions/PromisedWebSockets');\nconst AsyncQueue = require('../../extensions/AsyncQueue');\n\n/**\n * The `Connection` class is a wrapper around ``asyncio.open_connection``.\n *\n * Subclasses will implement different transport modes as atomic operations,\n * which this class eases doing since the exposed interface simply puts and\n * gets complete data payloads to and from queues.\n *\n * The only error that will raise from send and receive methods is\n * ``ConnectionError``, which will raise when attempting to send if\n * the client is disconnected (includes remote disconnections).\n */\nclass Connection {\n PacketCodecClass = undefined;\n\n constructor(ip, port, dcId, loggers) {\n this._ip = ip;\n this._port = port;\n this._dcId = dcId;\n this._log = loggers;\n this._connected = false;\n this._sendTask = undefined;\n this._recvTask = undefined;\n this._codec = undefined;\n this._obfuscation = undefined; // TcpObfuscated and MTProxy\n this._sendArray = new AsyncQueue();\n this._recvArray = new AsyncQueue();\n // this.socket = new PromiseSocket(new Socket())\n\n this.socket = new PromisedWebSockets(this.disconnectCallback.bind(this));\n }\n\n async disconnectCallback() {\n await this.disconnect(true);\n }\n\n async _connect() {\n this._log.debug('Connecting');\n this._codec = new this.PacketCodecClass(this);\n await this.socket.connect(this._port, this._ip, this);\n this._log.debug('Finished connecting');\n // await this.socket.connect({host: this._ip, port: this._port});\n await this._initConn();\n }\n\n async connect() {\n await this._connect();\n this._connected = true;\n\n if (!this._sendTask) {\n this._sendTask = this._sendLoop();\n }\n this._recvTask = this._recvLoop();\n }\n\n async disconnect(fromCallback = false) {\n if (!this._connected) {\n return;\n }\n\n this._connected = false;\n void this._recvArray.push(undefined);\n if (!fromCallback) {\n await this.socket.close();\n }\n }\n\n async send(data) {\n if (!this._connected) {\n throw new Error('Not connected');\n }\n await this._sendArray.push(data);\n }\n\n async recv() {\n while (this._connected) {\n const result = await this._recvArray.pop();\n // null = sentinel value = keep trying\n if (result) {\n return result;\n }\n }\n throw new Error('Not connected');\n }\n\n async _sendLoop() {\n // TODO handle errors\n try {\n while (this._connected) {\n const data = await this._sendArray.pop();\n if (!data) {\n this._sendTask = undefined;\n return;\n }\n await this._send(data);\n }\n } catch (e) {\n this._log.info('The server closed the connection while sending');\n }\n }\n\n async _recvLoop() {\n let data;\n while (this._connected) {\n try {\n data = await this._recv();\n if (!data) {\n throw new Error('no data received');\n }\n } catch (e) {\n this._log.info('connection closed');\n // await this._recvArray.push()\n\n this.disconnect();\n return;\n }\n await this._recvArray.push(data);\n }\n }\n\n async _initConn() {\n if (this._codec.tag) {\n await this.socket.write(this._codec.tag);\n }\n }\n\n _send(data) {\n const encodedPacket = this._codec.encodePacket(data);\n this.socket.write(encodedPacket);\n }\n\n _recv() {\n return this._codec.readPacket(this.socket);\n }\n\n toString() {\n return `${this._ip}:${this._port}/${this.constructor.name.replace('Connection', '')}`;\n }\n}\n\nclass ObfuscatedConnection extends Connection {\n ObfuscatedIO = undefined;\n\n _initConn() {\n this._obfuscation = new this.ObfuscatedIO(this);\n this.socket.write(this._obfuscation.header);\n }\n\n _send(data) {\n this._obfuscation.write(this._codec.encodePacket(data));\n }\n\n\n _recv() {\n return this._codec.readPacket(this._obfuscation);\n }\n}\n\nclass PacketCodec {\n constructor(connection) {\n this._conn = connection;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n encodePacket(data) {\n throw new Error('Not Implemented');\n\n // Override\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n readPacket(reader) {\n // override\n throw new Error('Not Implemented');\n }\n}\n\nmodule.exports = {\n Connection,\n PacketCodec,\n ObfuscatedConnection,\n};\n","const BigInt = require('big-integer');\nconst { readBufferFromBigInt } = require('../../Helpers');\nconst {\n Connection,\n PacketCodec,\n} = require('./Connection');\n\nclass AbridgedPacketCodec extends PacketCodec {\n static tag = Buffer.from('ef', 'hex');\n\n static obfuscateTag = Buffer.from('efefefef', 'hex');\n\n constructor(props) {\n super(props);\n this.tag = AbridgedPacketCodec.tag;\n this.obfuscateTag = AbridgedPacketCodec.obfuscateTag;\n }\n\n encodePacket(data) {\n let length = data.length >> 2;\n if (length < 127) {\n const b = Buffer.alloc(1);\n b.writeUInt8(length, 0);\n length = b;\n } else {\n length = Buffer.concat([Buffer.from('7f', 'hex'), readBufferFromBigInt(BigInt(length), 3)]);\n }\n return Buffer.concat([length, data]);\n }\n\n async readPacket(reader) {\n const readData = await reader.read(1);\n let length = readData[0];\n if (length >= 127) {\n length = Buffer.concat([await reader.read(3), Buffer.alloc(1)])\n .readInt32LE(0);\n }\n\n return reader.read(length << 2);\n }\n}\n\n/**\n * This is the mode with the lowest overhead, as it will\n * only require 1 byte if the packet length is less than\n * 508 bytes (127 << 2, which is very common).\n */\nclass ConnectionTCPAbridged extends Connection {\n PacketCodecClass = AbridgedPacketCodec;\n}\n\nmodule.exports = {\n ConnectionTCPAbridged,\n AbridgedPacketCodec,\n};\n","const { generateRandomBytes } = require('../../Helpers');\nconst { ObfuscatedConnection } = require('./Connection');\nconst { AbridgedPacketCodec } = require('./TCPAbridged');\nconst CTR = require('../../crypto/CTR');\n\nclass ObfuscatedIO {\n header = undefined;\n\n constructor(connection) {\n this.connection = connection.socket;\n const res = this.initHeader(connection.PacketCodecClass);\n this.header = res.random;\n\n this._encrypt = res.encryptor;\n this._decrypt = res.decryptor;\n }\n\n initHeader(packetCodec) {\n // Obfuscated messages secrets cannot start with any of these\n const keywords = [Buffer.from('50567247', 'hex'), Buffer.from('474554', 'hex'),\n Buffer.from('504f5354', 'hex'), Buffer.from('eeeeeeee', 'hex')];\n let random;\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n random = generateRandomBytes(64);\n if (random[0] !== 0xef && !(random.slice(4, 8)\n .equals(Buffer.alloc(4)))) {\n let ok = true;\n for (const key of keywords) {\n if (key.equals(random.slice(0, 4))) {\n ok = false;\n break;\n }\n }\n if (ok) {\n break;\n }\n }\n }\n random = random.toJSON().data;\n\n const randomReversed = Buffer.from(random.slice(8, 56))\n .reverse();\n // Encryption has \"continuous buffer\" enabled\n const encryptKey = Buffer.from(random.slice(8, 40));\n const encryptIv = Buffer.from(random.slice(40, 56));\n const decryptKey = Buffer.from(randomReversed.slice(0, 32));\n const decryptIv = Buffer.from(randomReversed.slice(32, 48));\n const encryptor = new CTR(encryptKey, encryptIv);\n const decryptor = new CTR(decryptKey, decryptIv);\n\n random = Buffer.concat([\n Buffer.from(random.slice(0, 56)), packetCodec.obfuscateTag, Buffer.from(random.slice(60)),\n ]);\n random = Buffer.concat([\n Buffer.from(random.slice(0, 56)), Buffer.from(encryptor.encrypt(random)\n .slice(56, 64)), Buffer.from(random.slice(64)),\n ]);\n return {\n random,\n encryptor,\n decryptor,\n };\n }\n\n async read(n) {\n const data = await this.connection.readExactly(n);\n return this._decrypt.encrypt(data);\n }\n\n write(data) {\n this.connection.write(this._encrypt.encrypt(data));\n }\n}\n\nclass ConnectionTCPObfuscated extends ObfuscatedConnection {\n ObfuscatedIO = ObfuscatedIO;\n\n PacketCodecClass = AbridgedPacketCodec;\n}\n\nmodule.exports = {\n ConnectionTCPObfuscated,\n};\n","const { Connection } = require('./Connection');\nconst { ConnectionTCPFull } = require('./TCPFull');\nconst { ConnectionTCPAbridged } = require('./TCPAbridged');\nconst { ConnectionTCPObfuscated } = require('./TCPObfuscated');\n\nmodule.exports = {\n Connection,\n ConnectionTCPFull,\n ConnectionTCPAbridged,\n ConnectionTCPObfuscated,\n};\n","const MTProtoPlainSender = require('./MTProtoPlainSender');\nconst MTProtoSender = require('./MTProtoSender');\n\nclass UpdateConnectionState {\n static disconnected = -1;\n\n static connected = 1;\n\n static broken = 0;\n\n constructor(state) {\n this.state = state;\n }\n}\n\nclass UpdateServerTimeOffset {\n constructor(timeOffset) {\n this.timeOffset = timeOffset;\n }\n}\n\nconst {\n Connection,\n ConnectionTCPFull,\n ConnectionTCPAbridged,\n ConnectionTCPObfuscated,\n} = require('./connection');\n\nmodule.exports = {\n Connection,\n ConnectionTCPFull,\n ConnectionTCPAbridged,\n ConnectionTCPObfuscated,\n MTProtoPlainSender,\n MTProtoSender,\n UpdateConnectionState,\n UpdateServerTimeOffset,\n};\n","class Session {\n /**\n * Creates a clone of this session file\n * @param toInstance {Session|null}\n * @returns {Session}\n */\n\n /* CONTEST\n clone(toInstance = null) {\n return toInstance || new this.constructor()\n } */\n\n /**\n * Returns the currently-used data center ID.\n */\n get dcId() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Returns the server address where the library should connect to.\n */\n get serverAddress() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Returns the port to which the library should connect to.\n */\n get port() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Returns an ``AuthKey`` instance associated with the saved\n * data center, or `None` if a new one should be generated.\n */\n get authKey() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Sets the ``AuthKey`` to be used for the saved data center.\n * @param value\n */\n set authKey(value) {\n throw new Error('Not Implemented');\n }\n\n /**\n * Sets the information of the data center address and port that\n * the library should connect to, as well as the data center ID,\n * which is currently unused.\n * @param dcId {number}\n * @param serverAddress {string}\n * @param port {number}\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n setDC(dcId, serverAddress, port) {\n throw new Error('Not implemented');\n }\n\n /**\n * Returns an ID of the takeout process initialized for this session,\n * or `None` if there's no were any unfinished takeout requests.\n */\n /* CONTEST\n get takeoutId() {\n throw new Error('Not Implemented')\n }\n */\n /**\n * Sets the ID of the unfinished takeout process for this session.\n * @param value\n */\n /* CONTEST\n set takeoutId(value) {\n throw new Error('Not Implemented')\n }\n */\n /**\n * Returns the ``UpdateState`` associated with the given `entity_id`.\n * If the `entity_id` is 0, it should return the ``UpdateState`` for\n * no specific channel (the \"general\" state). If no state is known\n * it should ``return None``.\n * @param entityId\n */\n /* CONTEST\n getUpdateState(entityId) {\n throw new Error('Not Implemented')\n }\n\n */\n\n /**\n * Sets the given ``UpdateState`` for the specified `entity_id`, which\n * should be 0 if the ``UpdateState`` is the \"general\" state (and not\n * for any specific channel).\n * @param entityId\n * @param state\n */\n /* CONTEST\n setUpdateState(entityId, state) {\n throw new Error('Not Implemented')\n }\n\n */\n\n /**\n * Called on client disconnection. Should be used to\n * free any used resources. Can be left empty if none.\n */\n\n /* CONTEST\n close() {\n\n }\n\n */\n\n /**\n * called whenever important properties change. It should\n * make persist the relevant session information to disk.\n */\n save() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Called upon client.log_out(). Should delete the stored\n * information from disk since it's not valid anymore.\n */\n\n delete() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Lists available sessions. Not used by the library itself.\n */\n /* CONTEST\n listSessions() {\n throw new Error('Not Implemented')\n }\n\n */\n\n /**\n * Processes the input ``TLObject`` or ``list`` and saves\n * whatever information is relevant (e.g., ID or access hash).\n * @param tlo\n */\n /* CONTEST\n processEntities(tlo) {\n throw new Error('Not Implemented')\n }\n\n */\n\n /**\n * Turns the given key into an ``InputPeer`` (e.g. ``InputPeerUser``).\n * The library uses this method whenever an ``InputPeer`` is needed\n * to suit several purposes (e.g. user only provided its ID or wishes\n * to use a cached username to avoid extra RPC).\n */\n /* CONTEST\n getInputEntity(key) {\n throw new Error('Not Implemented')\n }\n\n */\n}\n\nmodule.exports = Session;\n","/* eslint-disable no-restricted-globals */\nconst StorageSession = require('./StorageSession');\n\nconst CACHE_NAME = 'GramJs';\n\nclass CacheApiSession extends StorageSession {\n async _delete() {\n const request = new Request(this._storageKey);\n const cache = await self.caches.open(CACHE_NAME);\n return cache.delete(request);\n }\n\n async _fetchFromCache() {\n const request = new Request(this._storageKey);\n const cache = await self.caches.open(CACHE_NAME);\n const cached = await cache.match(request);\n return cached ? cached.text() : undefined;\n }\n\n async _saveToCache(data) {\n const request = new Request(this._storageKey);\n const response = new Response(data);\n const cache = await self.caches.open(CACHE_NAME);\n return cache.put(request, response);\n }\n}\n\nmodule.exports = CacheApiSession;\n","const MemorySession = require('./Memory');\nconst AuthKey = require('../crypto/AuthKey');\nconst utils = require('../Utils');\n\nclass CallbackSession extends MemorySession {\n constructor(sessionData, callback) {\n super();\n\n this._sessionData = sessionData;\n this._callback = callback;\n\n this._authKeys = {};\n }\n\n get authKey() {\n throw new Error('Not supported');\n }\n\n set authKey(value) {\n throw new Error('Not supported');\n }\n\n async load() {\n if (!this._sessionData) {\n return;\n }\n\n const {\n mainDcId,\n keys,\n hashes,\n } = this._sessionData;\n const {\n ipAddress,\n port,\n } = utils.getDC(mainDcId);\n\n this.setDC(mainDcId, ipAddress, port, true);\n\n await Promise.all(Object.keys(keys)\n .map(async (dcId) => {\n const key = typeof keys[dcId] === 'string'\n ? Buffer.from(keys[dcId], 'hex')\n : Buffer.from(keys[dcId]);\n\n if (hashes[dcId]) {\n const hash = typeof hashes[dcId] === 'string'\n ? Buffer.from(hashes[dcId], 'hex')\n : Buffer.from(hashes[dcId]);\n\n this._authKeys[dcId] = new AuthKey(key, hash);\n } else {\n this._authKeys[dcId] = new AuthKey();\n await this._authKeys[dcId].setKey(key, true);\n }\n }));\n }\n\n setDC(dcId, serverAddress, port, skipOnUpdate = false) {\n this._dcId = dcId;\n this._serverAddress = serverAddress;\n this._port = port;\n\n delete this._authKeys[dcId];\n\n if (!skipOnUpdate) {\n void this._onUpdate();\n }\n }\n\n getAuthKey(dcId = this._dcId) {\n return this._authKeys[dcId];\n }\n\n setAuthKey(authKey, dcId = this._dcId) {\n this._authKeys[dcId] = authKey;\n\n void this._onUpdate();\n }\n\n getSessionData() {\n const sessionData = {\n mainDcId: this._dcId,\n keys: {},\n hashes: {},\n };\n\n Object\n .keys(this._authKeys)\n .forEach((dcId) => {\n const authKey = this._authKeys[dcId];\n if (!authKey || !authKey._key) return;\n\n sessionData.keys[dcId] = authKey._key.toString('hex');\n sessionData.hashes[dcId] = authKey._hash.toString('hex');\n });\n\n return sessionData;\n }\n\n _onUpdate() {\n this._callback(this.getSessionData());\n }\n\n delete() {\n this._callback(undefined);\n }\n}\n\nmodule.exports = CallbackSession;\n","const idb = require('idb-keyval');\nconst StorageSession = require('./StorageSession');\n\nconst CACHE_NAME = 'GramJs';\n\nclass IdbSession extends StorageSession {\n _delete() {\n return idb.del(`${CACHE_NAME}:${this._storageKey}`);\n }\n\n _fetchFromCache() {\n return idb.get(`${CACHE_NAME}:${this._storageKey}`);\n }\n\n _saveToCache(data) {\n return idb.set(`${CACHE_NAME}:${this._storageKey}`, data);\n }\n}\n\nmodule.exports = IdbSession;\n","const StorageSession = require('./StorageSession');\n\nclass LocalStorageSession extends StorageSession {\n _delete() {\n return localStorage.removeItem(this._storageKey);\n }\n\n _fetchFromCache() {\n return localStorage.getItem(this._storageKey);\n }\n\n _saveToCache(data) {\n return localStorage.setItem(this._storageKey, data);\n }\n}\n\nmodule.exports = LocalStorageSession;\n","const Session = require('./Abstract');\n\nclass MemorySession extends Session {\n constructor() {\n super();\n\n this._serverAddress = undefined;\n this._dcId = 0;\n this._port = undefined;\n this._takeoutId = undefined;\n\n this._entities = new Set();\n this._updateStates = {};\n }\n\n get dcId() {\n return this._dcId;\n }\n\n get serverAddress() {\n return this._serverAddress;\n }\n\n get port() {\n return this._port;\n }\n\n get authKey() {\n return this._authKey;\n }\n\n set authKey(value) {\n this._authKey = value;\n }\n\n setDC(dcId, serverAddress, port) {\n this._dcId = dcId | 0;\n this._serverAddress = serverAddress;\n this._port = port;\n }\n\n /* CONTEST\n get takeoutId() {\n return this._takeoutId\n }\n\n set takeoutId(value) {\n this._takeoutId = value\n }\n\n\n getUpdateState(entityId) {\n return this._updateStates[entityId]\n }\n\n setUpdateState(entityId, state) {\n return this._updateStates[entityId] = state\n }\n\n close() {\n }\n\n save() {\n }\n\n async load() {\n\n }\n\n delete() {\n }\n\n _entityValuesToRow(id, hash, username, phone, name) {\n // While this is a simple implementation it might be overrode by,\n // other classes so they don't need to implement the plural form\n // of the method. Don't remove.\n return [id, hash, username, phone, name]\n }\n\n _entityToRow(e) {\n if (!(e.classType === \"constructor\")) {\n return\n }\n let p\n let markedId\n try {\n p = utils.getInputPeer(e, false)\n markedId = utils.getPeerId(p)\n } catch (e) {\n // Note: `get_input_peer` already checks for non-zero `accessHash`.\n // See issues #354 and #392. It also checks that the entity\n // is not `min`, because its `accessHash` cannot be used\n // anywhere (since layer 102, there are two access hashes).\n return\n }\n let pHash\n if (p instanceof types.InputPeerUser || p instanceof types.InputPeerChannel) {\n pHash = p.accessHash\n } else if (p instanceof types.InputPeerChat) {\n pHash = 0\n } else {\n return\n }\n\n let username = e.username\n if (username) {\n username = username.toLowerCase()\n }\n const phone = e.phone\n const name = utils.getDisplayName(e)\n return this._entityValuesToRow(markedId, pHash, username, phone, name)\n }\n\n _entitiesToRows(tlo) {\n let entities = []\n if (tlo.classType === \"constructor\" && utils.isListLike(tlo)) {\n // This may be a list of users already for instance\n entities = tlo\n } else {\n if (tlo instanceof Object) {\n if ('user' in tlo) {\n entities.push(tlo.user)\n }\n if ('chats' in tlo && utils.isListLike(tlo.chats)) {\n entities.concat(tlo.chats)\n }\n if ('users' in tlo && utils.isListLike(tlo.users)) {\n entities.concat(tlo.users)\n }\n }\n }\n const rows = [] // Rows to add (id, hash, username, phone, name)\n for (const e of entities) {\n const row = this._entityToRow(e)\n if (row) {\n rows.push(row)\n }\n }\n return rows\n }\n\n processEntities(tlo) {\n const entitiesSet = this._entitiesToRows(tlo)\n for (const e of entitiesSet) {\n this._entities.add(e)\n }\n }\n\n getEntityRowsByPhone(phone) {\n for (const e of this._entities) { // id, hash, username, phone, name\n if (e[3] === phone) {\n return [e[0], e[1]]\n }\n }\n }\n\n getEntityRowsByUsername(username) {\n for (const e of this._entities) { // id, hash, username, phone, name\n if (e[2] === username) {\n return [e[0], e[1]]\n }\n }\n }\n\n getEntityRowsByName(name) {\n for (const e of this._entities) { // id, hash, username, phone, name\n if (e[4] === name) {\n return [e[0], e[1]]\n }\n }\n }\n\n getEntityRowsById(id, exact = true) {\n if (exact) {\n for (const e of this._entities) { // id, hash, username, phone, name\n if (e[0] === id) {\n return [e[0], e[1]]\n }\n }\n } else {\n const ids = [utils.getPeerId(new types.PeerUser({ userId: id })),\n utils.getPeerId(new types.PeerChat({ chatId: id })),\n utils.getPeerId(new types.PeerChannel({ channelId: id })),\n ]\n for (const e of this._entities) { // id, hash, username, phone, name\n if (ids.includes(e[0])) {\n return [e[0], e[1]]\n }\n }\n }\n }\n\n getInputEntity(key) {\n let exact\n if (key.SUBCLASS_OF_ID !== undefined) {\n if ([0xc91c90b6, 0xe669bf46, 0x40f202fd].includes(key.SUBCLASS_OF_ID)) {\n // hex(crc32(b'InputPeer', b'InputUser' and b'InputChannel'))\n // We already have an Input version, so nothing else required\n return key\n }\n // Try to early return if this key can be casted as input peer\n return utils.getInputPeer(key)\n } else {\n // Not a TLObject or can't be cast into InputPeer\n if (key.classType === 'constructor') {\n key = utils.getPeerId(key)\n exact = true\n } else {\n exact = !(typeof key == 'number') || key < 0\n }\n }\n let result = null\n if (typeof key === 'string') {\n const phone = utils.parsePhone(key)\n if (phone) {\n result = this.getEntityRowsByPhone(phone)\n } else {\n const { username, isInvite } = utils.parseUsername(key)\n if (username && !isInvite) {\n result = this.getEntityRowsByUsername(username)\n } else {\n const tup = utils.resolveInviteLink(key)[1]\n if (tup) {\n result = this.getEntityRowsById(tup, false)\n }\n }\n }\n } else if (typeof key === 'number') {\n result = this.getEntityRowsById(key, exact)\n }\n if (!result && typeof key === 'string') {\n result = this.getEntityRowsByName(key)\n }\n\n if (result) {\n let entityId = result[0] // unpack resulting tuple\n const entityHash = result[1]\n const resolved = utils.resolveId(entityId)\n entityId = resolved[0]\n const kind = resolved[1]\n // removes the mark and returns type of entity\n if (kind === types.PeerUser) {\n return new types.InputPeerUser({ userId: entityId, accessHash: entityHash })\n } else if (kind === types.PeerChat) {\n return new types.InputPeerChat({ chatId: entityId })\n } else if (kind === types.PeerChannel) {\n return new types.InputPeerChannel({ channelId: entityId, accessHash: entityHash })\n }\n } else {\n throw new Error('Could not find input entity with key ' + key)\n }\n } */\n}\n\nmodule.exports = MemorySession;\n","const MemorySession = require('./Memory');\nconst AuthKey = require('../crypto/AuthKey');\nconst utils = require('../Utils');\n\nconst STORAGE_KEY_BASE = 'GramJs-session-';\nconst SESSION_DATA_PREFIX = 'session:';\n\nclass StorageSession extends MemorySession {\n constructor(sessionInfo) {\n super();\n\n this._authKeys = {};\n\n if (sessionInfo && sessionInfo.startsWith(SESSION_DATA_PREFIX)) {\n this._sessionString = sessionInfo;\n } else if (sessionInfo) {\n this._storageKey = sessionInfo;\n }\n }\n\n get authKey() {\n throw new Error('Not supported');\n }\n\n set authKey(value) {\n throw new Error('Not supported');\n }\n\n async load() {\n if (this._sessionString) {\n await this._loadFromSessionString();\n return;\n }\n\n if (!this._storageKey) {\n return;\n }\n\n try {\n const json = await this._fetchFromCache();\n const {\n mainDcId,\n keys,\n hashes,\n } = JSON.parse(json);\n const {\n ipAddress,\n port,\n } = utils.getDC(mainDcId);\n\n this.setDC(mainDcId, ipAddress, port, true);\n\n Object.keys(keys)\n .forEach((dcId) => {\n if (keys[dcId] && hashes[dcId]) {\n this._authKeys[dcId] = new AuthKey(\n Buffer.from(keys[dcId].data),\n Buffer.from(hashes[dcId].data),\n );\n }\n });\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn('Failed to retrieve or parse session from storage');\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n }\n\n setDC(dcId, serverAddress, port, skipUpdateStorage = false) {\n this._dcId = dcId;\n this._serverAddress = serverAddress;\n this._port = port;\n\n delete this._authKeys[dcId];\n\n if (!skipUpdateStorage) {\n void this._updateStorage();\n }\n }\n\n async save() {\n if (!this._storageKey) {\n this._storageKey = generateStorageKey();\n }\n\n await this._updateStorage();\n\n return this._storageKey;\n }\n\n getAuthKey(dcId = this._dcId) {\n return this._authKeys[dcId];\n }\n\n setAuthKey(authKey, dcId = this._dcId) {\n this._authKeys[dcId] = authKey;\n\n void this._updateStorage();\n }\n\n getSessionData(asHex) {\n const sessionData = {\n mainDcId: this._dcId,\n keys: {},\n hashes: {},\n };\n\n Object\n .keys(this._authKeys)\n .forEach((dcId) => {\n const authKey = this._authKeys[dcId];\n if (!authKey._key) return;\n\n sessionData.keys[dcId] = asHex ? authKey._key.toString('hex') : authKey._key;\n sessionData.hashes[dcId] = asHex ? authKey._hash.toString('hex') : authKey._hash;\n });\n\n return sessionData;\n }\n\n async _loadFromSessionString() {\n const [, mainDcIdStr, mainDcKey] = this._sessionString.split(':');\n const mainDcId = Number(mainDcIdStr);\n const {\n ipAddress,\n port,\n } = utils.getDC(mainDcId);\n this.setDC(mainDcId, ipAddress, port);\n const authKey = new AuthKey();\n await authKey.setKey(Buffer.from(mainDcKey, 'hex'), true);\n this.setAuthKey(authKey, mainDcId);\n }\n\n async _updateStorage() {\n if (!this._storageKey) {\n return;\n }\n\n try {\n await this._saveToCache(JSON.stringify(this.getSessionData()));\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn('Failed to update session in storage');\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n }\n\n async delete() {\n try {\n return await this._delete();\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn('Failed to delete session from storage');\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n return undefined;\n }\n\n // @abstract\n _delete() {\n throw new Error('Not Implemented');\n }\n\n // @abstract\n _fetchFromCache() {\n throw new Error('Not Implemented');\n }\n\n // @abstract\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _saveToCache(data) {\n throw new Error('Not Implemented');\n }\n}\n\nfunction generateStorageKey() {\n // Creating two sessions at the same moment is not expected nor supported.\n return `${STORAGE_KEY_BASE}${Date.now()}`;\n}\n\nmodule.exports = StorageSession;\n","const MemorySession = require('./Memory');\nconst AuthKey = require('../crypto/AuthKey');\nconst BinaryReader = require('../extensions/BinaryReader');\n\nconst CURRENT_VERSION = '1';\n\n\nclass StringSession extends MemorySession {\n /**\n * This session file can be easily saved and loaded as a string. According\n * to the initial design, it contains only the data that is necessary for\n * successful connection and authentication, so takeout ID is not stored.\n\n * It is thought to be used where you don't want to create any on-disk\n * files but would still like to be able to save and load existing sessions\n * by other means.\n\n * You can use custom `encode` and `decode` functions, if present:\n\n * `encode` definition must be ``function encode(value: Buffer) -> string:``.\n * `decode` definition must be ``function decode(value: string) -> Buffer:``.\n * @param session {string|null}\n */\n constructor(session = undefined) {\n super();\n if (session) {\n if (session[0] !== CURRENT_VERSION) {\n throw new Error('Not a valid string');\n }\n session = session.slice(1);\n const r = StringSession.decode(session);\n const reader = new BinaryReader(r);\n this._dcId = reader.read(1)\n .readUInt8(0);\n const serverAddressLen = reader.read(2)\n .readInt16BE(0);\n this._serverAddress = String(reader.read(serverAddressLen));\n this._port = reader.read(2)\n .readInt16BE(0);\n this._key = reader.read(-1);\n }\n }\n\n /**\n * @param x {Buffer}\n * @returns {string}\n */\n static encode(x) {\n return x.toString('base64');\n }\n\n /**\n * @param x {string}\n * @returns {Buffer}\n */\n static decode(x) {\n return Buffer.from(x, 'base64');\n }\n\n async load() {\n if (this._key) {\n this._authKey = new AuthKey();\n await this._authKey.setKey(this._key);\n }\n }\n\n save() {\n if (!this.authKey) {\n return '';\n }\n const dcBuffer = Buffer.from([this.dcId]);\n const addressBuffer = Buffer.from(this.serverAddress);\n const addressLengthBuffer = Buffer.alloc(2);\n addressLengthBuffer.writeInt16BE(addressBuffer.length, 0);\n const portBuffer = Buffer.alloc(2);\n portBuffer.writeInt16BE(this.port, 0);\n\n return CURRENT_VERSION + StringSession.encode(Buffer.concat([\n dcBuffer,\n addressLengthBuffer,\n addressBuffer,\n portBuffer,\n this.authKey.getKey(),\n ]));\n }\n\n getAuthKey(dcId) {\n if (dcId && dcId !== this.dcId) {\n // Not supported.\n return undefined;\n }\n\n return this.authKey;\n }\n\n setAuthKey(authKey, dcId) {\n if (dcId && dcId !== this.dcId) {\n // Not supported.\n return;\n }\n\n this.authKey = authKey;\n }\n}\n\nmodule.exports = StringSession;\n","const Memory = require('./Memory');\nconst StringSession = require('./StringSession');\nconst CacheApiSession = require('./CacheApiSession');\nconst LocalStorageSession = require('./LocalStorageSession');\nconst IdbSession = require('./IdbSession');\nconst CallbackSession = require('./CallbackSession');\n\nmodule.exports = {\n Memory,\n StringSession,\n CacheApiSession,\n LocalStorageSession,\n IdbSession,\n CallbackSession,\n};\n","const api = require('./api');\n\nconst LAYER = 131;\nconst tlobjects = {};\n\n\nfor (const tl of Object.values(api)) {\n if (tl.CONSTRUCTOR_ID) {\n tlobjects[tl.CONSTRUCTOR_ID] = tl;\n } else {\n for (const sub of Object.values(tl)) {\n tlobjects[sub.CONSTRUCTOR_ID] = sub;\n }\n }\n}\n\nmodule.exports = {\n LAYER,\n tlobjects,\n};\n","const {\n parseTl,\n serializeBytes,\n serializeDate,\n} = require('./generationHelpers');\nconst {\n toSignedLittleBuffer,\n} = require('../Helpers');\n\nconst tlContent = require('./apiTl.js');\nconst schemeContent = require('./schemaTl.js');\n\n/* CONTEST\nconst NAMED_AUTO_CASTS = new Set([\n 'chatId,int'\n])\nconst NAMED_BLACKLIST = new Set([\n 'discardEncryption'\n])\nconst AUTO_CASTS = new Set([\n 'InputPeer',\n 'InputChannel',\n 'InputUser',\n 'InputDialogPeer',\n 'InputNotifyPeer',\n 'InputMedia',\n 'InputPhoto',\n 'InputMessage',\n 'InputDocument',\n 'InputChatPhoto'\n])\n\n */\n// eslint-disable-next-line no-restricted-globals\nconst CACHING_SUPPORTED = typeof self !== 'undefined' && self.localStorage !== undefined;\n\nconst CACHE_KEY = 'GramJs:apiCache';\n\nfunction buildApiFromTlSchema() {\n let definitions;\n const fromCache = CACHING_SUPPORTED && loadFromCache();\n\n if (fromCache) {\n definitions = fromCache;\n } else {\n definitions = loadFromTlSchemas();\n\n if (CACHING_SUPPORTED) {\n localStorage.setItem(CACHE_KEY, JSON.stringify(definitions));\n }\n }\n\n return mergeWithNamespaces(\n createClasses('constructor', definitions.constructors),\n createClasses('request', definitions.requests),\n );\n}\n\nfunction loadFromCache() {\n const jsonCache = localStorage.getItem(CACHE_KEY);\n return jsonCache && JSON.parse(jsonCache);\n}\n\nfunction loadFromTlSchemas() {\n const [constructorParamsApi, functionParamsApi] = extractParams(tlContent);\n const [constructorParamsSchema, functionParamsSchema] = extractParams(schemeContent);\n const constructors = [].concat(constructorParamsApi, constructorParamsSchema);\n const requests = [].concat(functionParamsApi, functionParamsSchema);\n\n return {\n constructors,\n requests,\n };\n}\n\nfunction mergeWithNamespaces(obj1, obj2) {\n const result = { ...obj1 };\n\n Object.keys(obj2)\n .forEach((key) => {\n if (typeof obj2[key] === 'function' || !result[key]) {\n result[key] = obj2[key];\n } else {\n Object.assign(result[key], obj2[key]);\n }\n });\n\n return result;\n}\n\nfunction extractParams(fileContent) {\n const f = parseTl(fileContent, 109);\n const constructors = [];\n const functions = [];\n for (const d of f) {\n if (d.isFunction) {\n functions.push(d);\n } else {\n constructors.push(d);\n }\n }\n return [constructors, functions];\n}\n\nfunction argToBytes(x, type) {\n switch (type) {\n case 'int': {\n const i = Buffer.alloc(4);\n i.writeInt32LE(x, 0);\n return i;\n }\n case 'long':\n return toSignedLittleBuffer(x, 8);\n case 'int128':\n return toSignedLittleBuffer(x, 16);\n case 'int256':\n return toSignedLittleBuffer(x, 32);\n case 'double': {\n const d = Buffer.alloc(8);\n d.writeDoubleLE(x, 0);\n return d;\n }\n case 'string':\n return serializeBytes(x);\n case 'Bool':\n return x ? Buffer.from('b5757299', 'hex') : Buffer.from('379779bc', 'hex');\n case 'true':\n return Buffer.alloc(0);\n case 'bytes':\n return serializeBytes(x);\n case 'date':\n return serializeDate(x);\n default:\n return x.getBytes();\n }\n}\n\n/*\nCONTEST\nasync function getInputFromResolve(utils, client, peer, peerType) {\n switch (peerType) {\n case 'InputPeer':\n return utils.getInputPeer(await client.getInputEntity(peer))\n case 'InputChannel':\n return utils.getInputChannel(await client.getInputEntity(peer))\n case 'InputUser':\n return utils.getInputUser(await client.getInputEntity(peer))\n case 'InputDialogPeer':\n return await client._getInputDialog(peer)\n case 'InputNotifyPeer':\n return await client._getInputNotify(peer)\n case 'InputMedia':\n return utils.getInputMedia(peer)\n case 'InputPhoto':\n return utils.getInputPhoto(peer)\n case 'InputMessage':\n return utils.getInputMessage(peer)\n case 'InputDocument':\n return utils.getInputDocument(peer)\n case 'InputChatPhoto':\n return utils.getInputChatPhoto(peer)\n case 'chatId,int' :\n return await client.getPeerId(peer, false)\n default:\n throw new Error('unsupported peer type : ' + peerType)\n }\n}\n*/\nfunction getArgFromReader(reader, arg) {\n if (arg.isVector) {\n if (arg.useVectorId) {\n reader.readInt();\n }\n const temp = [];\n const len = reader.readInt();\n arg.isVector = false;\n for (let i = 0; i < len; i++) {\n temp.push(getArgFromReader(reader, arg));\n }\n arg.isVector = true;\n return temp;\n } else if (arg.flagIndicator) {\n return reader.readInt();\n } else {\n switch (arg.type) {\n case 'int':\n return reader.readInt();\n case 'long':\n return reader.readLong();\n case 'int128':\n return reader.readLargeInt(128);\n case 'int256':\n return reader.readLargeInt(256);\n case 'double':\n return reader.readDouble();\n case 'string':\n return reader.tgReadString();\n case 'Bool':\n return reader.tgReadBool();\n case 'true':\n return true;\n case 'bytes':\n return reader.tgReadBytes();\n case 'date':\n return reader.tgReadDate();\n default:\n if (!arg.skipConstructorId) {\n return reader.tgReadObject();\n } else {\n throw new Error(`Unknown type ${arg}`);\n }\n }\n }\n}\n\nfunction createClasses(classesType, params) {\n const classes = {};\n for (const classParams of params) {\n const {\n name,\n constructorId,\n subclassOfId,\n argsConfig,\n namespace,\n result,\n } = classParams;\n const fullName = [namespace, name].join('.')\n .replace(/^\\./, '');\n\n class VirtualClass {\n static CONSTRUCTOR_ID = constructorId;\n\n static SUBCLASS_OF_ID = subclassOfId;\n\n static className = fullName;\n\n static classType = classesType;\n\n CONSTRUCTOR_ID = constructorId;\n\n SUBCLASS_OF_ID = subclassOfId;\n\n className = fullName;\n\n classType = classesType;\n\n constructor(args) {\n args = args || {};\n Object.keys(args)\n .forEach((argName) => {\n this[argName] = args[argName];\n });\n }\n\n static fromReader(reader) {\n const args = {};\n\n for (const argName in argsConfig) {\n if (argsConfig.hasOwnProperty(argName)) {\n const arg = argsConfig[argName];\n if (arg.isFlag) {\n if (arg.type === 'true') {\n args[argName] = Boolean(args.flags & (1 << arg.flagIndex));\n continue;\n }\n if (args.flags & (1 << arg.flagIndex)) {\n args[argName] = getArgFromReader(reader, arg);\n } else {\n args[argName] = undefined;\n }\n } else {\n if (arg.flagIndicator) {\n arg.name = 'flags';\n }\n args[argName] = getArgFromReader(reader, arg);\n }\n }\n }\n return new VirtualClass(args);\n }\n\n getBytes() {\n // The next is pseudo-code:\n const idForBytes = this.CONSTRUCTOR_ID;\n const c = Buffer.alloc(4);\n c.writeUInt32LE(idForBytes, 0);\n const buffers = [c];\n for (const arg in argsConfig) {\n if (argsConfig.hasOwnProperty(arg)) {\n if (argsConfig[arg].isFlag) {\n if ((this[arg] === false && argsConfig[arg].type === 'true')\n || this[arg] === undefined) {\n continue;\n }\n }\n if (argsConfig[arg].isVector) {\n if (argsConfig[arg].useVectorId) {\n buffers.push(Buffer.from('15c4b51c', 'hex'));\n }\n const l = Buffer.alloc(4);\n l.writeInt32LE(this[arg].length, 0);\n buffers.push(l, Buffer.concat(this[arg].map((x) => argToBytes(x, argsConfig[arg].type))));\n } else if (argsConfig[arg].flagIndicator) {\n if (!Object.values(argsConfig)\n .some((f) => f.isFlag)) {\n buffers.push(Buffer.alloc(4));\n } else {\n let flagCalculate = 0;\n for (const f in argsConfig) {\n if (argsConfig[f].isFlag) {\n if ((this[f] === false && argsConfig[f].type === 'true')\n || this[f] === undefined) {\n flagCalculate |= 0;\n } else {\n flagCalculate |= 1 << argsConfig[f].flagIndex;\n }\n }\n }\n const f = Buffer.alloc(4);\n f.writeUInt32LE(flagCalculate, 0);\n buffers.push(f);\n }\n } else {\n buffers.push(argToBytes(this[arg], argsConfig[arg].type));\n\n if (this[arg] && typeof this[arg].getBytes === 'function') {\n let boxed = (argsConfig[arg].type.charAt(argsConfig[arg].type.indexOf('.') + 1));\n boxed = boxed === boxed.toUpperCase();\n if (!boxed) {\n buffers.shift();\n }\n }\n }\n }\n }\n return Buffer.concat(buffers);\n }\n\n readResult(reader) {\n if (classesType !== 'request') {\n throw new Error('`readResult()` called for non-request instance');\n }\n\n const m = result.match(/Vector<(int|long)>/);\n if (m) {\n reader.readInt();\n const temp = [];\n const len = reader.readInt();\n if (m[1] === 'int') {\n for (let i = 0; i < len; i++) {\n temp.push(reader.readInt());\n }\n } else {\n for (let i = 0; i < len; i++) {\n temp.push(reader.readLong());\n }\n }\n return temp;\n } else {\n return reader.tgReadObject();\n }\n }\n\n /* CONTEST\n async resolve(client, utils) {\n\n if (classesType !== 'request') {\n throw new Error('`resolve()` called for non-request instance')\n }\n\n for (const arg in argsConfig) {\n if (argsConfig.hasOwnProperty(arg)) {\n if (!AUTO_CASTS.has(argsConfig[arg].type)) {\n if (!NAMED_AUTO_CASTS.has(`${argsConfig[arg].name},${argsConfig[arg].type}`)) {\n continue\n }\n }\n if (argsConfig[arg].isFlag) {\n if (!this[arg]) {\n continue\n }\n }\n if (argsConfig[arg].isVector) {\n const temp = []\n for (const x of this[arg]) {\n temp.push(await getInputFromResolve(utils, client, x, argsConfig[arg].type))\n }\n this[arg] = temp\n } else {\n this[arg] = await getInputFromResolve(utils, client, this[arg], argsConfig[arg].type)\n }\n }\n }\n } */\n }\n\n if (namespace) {\n if (!classes[namespace]) {\n classes[namespace] = {};\n }\n classes[namespace][name] = VirtualClass;\n } else {\n classes[name] = VirtualClass;\n }\n }\n\n return classes;\n}\n\nmodule.exports = buildApiFromTlSchema();\n","module.exports = `boolFalse#bc799737 = Bool;\nboolTrue#997275b5 = Bool;\ntrue#3fedd339 = True;\nvector#1cb5c415 {t:Type} # [ t ] = Vector t;\nerror#c4b9f9bb code:int text:string = Error;\nnull#56730bcc = Null;\ninputPeerEmpty#7f3b18ea = InputPeer;\ninputPeerSelf#7da07ec9 = InputPeer;\ninputPeerChat#179be863 chat_id:int = InputPeer;\ninputPeerUser#7b8e7de6 user_id:int access_hash:long = InputPeer;\ninputPeerChannel#20adaef8 channel_id:int access_hash:long = InputPeer;\ninputPeerUserFromMessage#17bae2e6 peer:InputPeer msg_id:int user_id:int = InputPeer;\ninputPeerChannelFromMessage#9c95f7bb peer:InputPeer msg_id:int channel_id:int = InputPeer;\ninputUserEmpty#b98886cf = InputUser;\ninputUserSelf#f7c1b13f = InputUser;\ninputUser#d8292816 user_id:int access_hash:long = InputUser;\ninputUserFromMessage#2d117597 peer:InputPeer msg_id:int user_id:int = InputUser;\ninputPhoneContact#f392b7f4 client_id:long phone:string first_name:string last_name:string = InputContact;\ninputFile#f52ff27f id:long parts:int name:string md5_checksum:string = InputFile;\ninputFileBig#fa4f0bb5 id:long parts:int name:string = InputFile;\ninputMediaEmpty#9664f57f = InputMedia;\ninputMediaUploadedPhoto#1e287d04 flags:# file:InputFile stickers:flags.0?Vector<InputDocument> ttl_seconds:flags.1?int = InputMedia;\ninputMediaPhoto#b3ba0635 flags:# id:InputPhoto ttl_seconds:flags.0?int = InputMedia;\ninputMediaGeoPoint#f9c44144 geo_point:InputGeoPoint = InputMedia;\ninputMediaContact#f8ab7dfb phone_number:string first_name:string last_name:string vcard:string = InputMedia;\ninputMediaUploadedDocument#5b38c6c1 flags:# nosound_video:flags.3?true force_file:flags.4?true file:InputFile thumb:flags.2?InputFile mime_type:string attributes:Vector<DocumentAttribute> stickers:flags.0?Vector<InputDocument> ttl_seconds:flags.1?int = InputMedia;\ninputMediaDocument#33473058 flags:# id:InputDocument ttl_seconds:flags.0?int query:flags.1?string = InputMedia;\ninputMediaVenue#c13d1c11 geo_point:InputGeoPoint title:string address:string provider:string venue_id:string venue_type:string = InputMedia;\ninputMediaPhotoExternal#e5bbfe1a flags:# url:string ttl_seconds:flags.0?int = InputMedia;\ninputMediaDocumentExternal#fb52dc99 flags:# url:string ttl_seconds:flags.0?int = InputMedia;\ninputMediaGame#d33f43f3 id:InputGame = InputMedia;\ninputMediaInvoice#d9799874 flags:# title:string description:string photo:flags.0?InputWebDocument invoice:Invoice payload:bytes provider:string provider_data:DataJSON start_param:flags.1?string = InputMedia;\ninputMediaGeoLive#971fa843 flags:# stopped:flags.0?true geo_point:InputGeoPoint heading:flags.2?int period:flags.1?int proximity_notification_radius:flags.3?int = InputMedia;\ninputMediaPoll#f94e5f1 flags:# poll:Poll correct_answers:flags.0?Vector<bytes> solution:flags.1?string solution_entities:flags.1?Vector<MessageEntity> = InputMedia;\ninputMediaDice#e66fbf7b emoticon:string = InputMedia;\ninputChatPhotoEmpty#1ca48f57 = InputChatPhoto;\ninputChatUploadedPhoto#c642724e flags:# file:flags.0?InputFile video:flags.1?InputFile video_start_ts:flags.2?double = InputChatPhoto;\ninputChatPhoto#8953ad37 id:InputPhoto = InputChatPhoto;\ninputGeoPointEmpty#e4c123d6 = InputGeoPoint;\ninputGeoPoint#48222faf flags:# lat:double long:double accuracy_radius:flags.0?int = InputGeoPoint;\ninputPhotoEmpty#1cd7bf0d = InputPhoto;\ninputPhoto#3bb3b94a id:long access_hash:long file_reference:bytes = InputPhoto;\ninputFileLocation#dfdaabe1 volume_id:long local_id:int secret:long file_reference:bytes = InputFileLocation;\ninputEncryptedFileLocation#f5235d55 id:long access_hash:long = InputFileLocation;\ninputDocumentFileLocation#bad07584 id:long access_hash:long file_reference:bytes thumb_size:string = InputFileLocation;\ninputSecureFileLocation#cbc7ee28 id:long access_hash:long = InputFileLocation;\ninputTakeoutFileLocation#29be5899 = InputFileLocation;\ninputPhotoFileLocation#40181ffe id:long access_hash:long file_reference:bytes thumb_size:string = InputFileLocation;\ninputPhotoLegacyFileLocation#d83466f3 id:long access_hash:long file_reference:bytes volume_id:long local_id:int secret:long = InputFileLocation;\ninputPeerPhotoFileLocation#37257e99 flags:# big:flags.0?true peer:InputPeer photo_id:long = InputFileLocation;\ninputStickerSetThumb#9d84f3db stickerset:InputStickerSet thumb_version:int = InputFileLocation;\ninputGroupCallStream#bba51639 call:InputGroupCall time_ms:long scale:int = InputFileLocation;\npeerUser#9db1bc6d user_id:int = Peer;\npeerChat#bad0e5bb chat_id:int = Peer;\npeerChannel#bddde532 channel_id:int = Peer;\nstorage.fileUnknown#aa963b05 = storage.FileType;\nstorage.filePartial#40bc6f52 = storage.FileType;\nstorage.fileJpeg#7efe0e = storage.FileType;\nstorage.fileGif#cae1aadf = storage.FileType;\nstorage.filePng#a4f63c0 = storage.FileType;\nstorage.filePdf#ae1e508d = storage.FileType;\nstorage.fileMp3#528a0677 = storage.FileType;\nstorage.fileMov#4b09ebbc = storage.FileType;\nstorage.fileMp4#b3cea0e4 = storage.FileType;\nstorage.fileWebp#1081464c = storage.FileType;\nuserEmpty#200250ba id:int = User;\nuser#938458c1 flags:# self:flags.10?true contact:flags.11?true mutual_contact:flags.12?true deleted:flags.13?true bot:flags.14?true bot_chat_history:flags.15?true bot_nochats:flags.16?true verified:flags.17?true restricted:flags.18?true min:flags.20?true bot_inline_geo:flags.21?true support:flags.23?true scam:flags.24?true apply_min_photo:flags.25?true fake:flags.26?true id:int access_hash:flags.0?long first_name:flags.1?string last_name:flags.2?string username:flags.3?string phone:flags.4?string photo:flags.5?UserProfilePhoto status:flags.6?UserStatus bot_info_version:flags.14?int restriction_reason:flags.18?Vector<RestrictionReason> bot_inline_placeholder:flags.19?string lang_code:flags.22?string = User;\nuserProfilePhotoEmpty#4f11bae1 = UserProfilePhoto;\nuserProfilePhoto#82d1f706 flags:# has_video:flags.0?true photo_id:long stripped_thumb:flags.1?bytes dc_id:int = UserProfilePhoto;\nuserStatusEmpty#9d05049 = UserStatus;\nuserStatusOnline#edb93949 expires:int = UserStatus;\nuserStatusOffline#8c703f was_online:int = UserStatus;\nuserStatusRecently#e26f42f1 = UserStatus;\nuserStatusLastWeek#7bf09fc = UserStatus;\nuserStatusLastMonth#77ebc742 = UserStatus;\nchatEmpty#9ba2d800 id:int = Chat;\nchat#3bda1bde flags:# creator:flags.0?true kicked:flags.1?true left:flags.2?true deactivated:flags.5?true call_active:flags.23?true call_not_empty:flags.24?true id:int title:string photo:ChatPhoto participants_count:int date:int version:int migrated_to:flags.6?InputChannel admin_rights:flags.14?ChatAdminRights default_banned_rights:flags.18?ChatBannedRights = Chat;\nchatForbidden#7328bdb id:int title:string = Chat;\nchannel#d31a961e flags:# creator:flags.0?true left:flags.2?true broadcast:flags.5?true verified:flags.7?true megagroup:flags.8?true restricted:flags.9?true signatures:flags.11?true min:flags.12?true scam:flags.19?true has_link:flags.20?true has_geo:flags.21?true slowmode_enabled:flags.22?true call_active:flags.23?true call_not_empty:flags.24?true fake:flags.25?true gigagroup:flags.26?true id:int access_hash:flags.13?long title:string username:flags.6?string photo:ChatPhoto date:int version:int restriction_reason:flags.9?Vector<RestrictionReason> admin_rights:flags.14?ChatAdminRights banned_rights:flags.15?ChatBannedRights default_banned_rights:flags.18?ChatBannedRights participants_count:flags.17?int = Chat;\nchannelForbidden#289da732 flags:# broadcast:flags.5?true megagroup:flags.8?true id:int access_hash:long title:string until_date:flags.16?int = Chat;\nchatFull#8a1e2983 flags:# can_set_username:flags.7?true has_scheduled:flags.8?true id:int about:string participants:ChatParticipants chat_photo:flags.2?Photo notify_settings:PeerNotifySettings exported_invite:flags.13?ExportedChatInvite bot_info:flags.3?Vector<BotInfo> pinned_msg_id:flags.6?int folder_id:flags.11?int call:flags.12?InputGroupCall ttl_period:flags.14?int groupcall_default_join_as:flags.15?Peer = ChatFull;\nchannelFull#548c3f93 flags:# can_view_participants:flags.3?true can_set_username:flags.6?true can_set_stickers:flags.7?true hidden_prehistory:flags.10?true can_set_location:flags.16?true has_scheduled:flags.19?true can_view_stats:flags.20?true blocked:flags.22?true id:int about:string participants_count:flags.0?int admins_count:flags.1?int kicked_count:flags.2?int banned_count:flags.2?int online_count:flags.13?int read_inbox_max_id:int read_outbox_max_id:int unread_count:int chat_photo:Photo notify_settings:PeerNotifySettings exported_invite:flags.23?ExportedChatInvite bot_info:Vector<BotInfo> migrated_from_chat_id:flags.4?int migrated_from_max_id:flags.4?int pinned_msg_id:flags.5?int stickerset:flags.8?StickerSet available_min_id:flags.9?int folder_id:flags.11?int linked_chat_id:flags.14?int location:flags.15?ChannelLocation slowmode_seconds:flags.17?int slowmode_next_send_date:flags.18?int stats_dc:flags.12?int pts:int call:flags.21?InputGroupCall ttl_period:flags.24?int pending_suggestions:flags.25?Vector<string> groupcall_default_join_as:flags.26?Peer = ChatFull;\nchatParticipant#c8d7493e user_id:int inviter_id:int date:int = ChatParticipant;\nchatParticipantCreator#da13538a user_id:int = ChatParticipant;\nchatParticipantAdmin#e2d6e436 user_id:int inviter_id:int date:int = ChatParticipant;\nchatParticipantsForbidden#fc900c2b flags:# chat_id:int self_participant:flags.0?ChatParticipant = ChatParticipants;\nchatParticipants#3f460fed chat_id:int participants:Vector<ChatParticipant> version:int = ChatParticipants;\nchatPhotoEmpty#37c1011c = ChatPhoto;\nchatPhoto#1c6e1c11 flags:# has_video:flags.0?true photo_id:long stripped_thumb:flags.1?bytes dc_id:int = ChatPhoto;\nmessageEmpty#90a6ca84 flags:# id:int peer_id:flags.0?Peer = Message;\nmessage#bce383d2 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true post:flags.14?true from_scheduled:flags.18?true legacy:flags.19?true edit_hide:flags.21?true pinned:flags.24?true id:int from_id:flags.8?Peer peer_id:Peer fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?int reply_to:flags.3?MessageReplyHeader date:int message:string media:flags.9?MessageMedia reply_markup:flags.6?ReplyMarkup entities:flags.7?Vector<MessageEntity> views:flags.10?int forwards:flags.10?int replies:flags.23?MessageReplies edit_date:flags.15?int post_author:flags.16?string grouped_id:flags.17?long restriction_reason:flags.22?Vector<RestrictionReason> ttl_period:flags.25?int = Message;\nmessageService#2b085862 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true post:flags.14?true legacy:flags.19?true id:int from_id:flags.8?Peer peer_id:Peer reply_to:flags.3?MessageReplyHeader date:int action:MessageAction ttl_period:flags.25?int = Message;\nmessageMediaEmpty#3ded6320 = MessageMedia;\nmessageMediaPhoto#695150d7 flags:# photo:flags.0?Photo ttl_seconds:flags.2?int = MessageMedia;\nmessageMediaGeo#56e0d474 geo:GeoPoint = MessageMedia;\nmessageMediaContact#cbf24940 phone_number:string first_name:string last_name:string vcard:string user_id:int = MessageMedia;\nmessageMediaUnsupported#9f84f49e = MessageMedia;\nmessageMediaDocument#9cb070d7 flags:# document:flags.0?Document ttl_seconds:flags.2?int = MessageMedia;\nmessageMediaWebPage#a32dd600 webpage:WebPage = MessageMedia;\nmessageMediaVenue#2ec0533f geo:GeoPoint title:string address:string provider:string venue_id:string venue_type:string = MessageMedia;\nmessageMediaGame#fdb19008 game:Game = MessageMedia;\nmessageMediaInvoice#84551347 flags:# shipping_address_requested:flags.1?true test:flags.3?true title:string description:string photo:flags.0?WebDocument receipt_msg_id:flags.2?int currency:string total_amount:long start_param:string = MessageMedia;\nmessageMediaGeoLive#b940c666 flags:# geo:GeoPoint heading:flags.0?int period:int proximity_notification_radius:flags.1?int = MessageMedia;\nmessageMediaPoll#4bd6e798 poll:Poll results:PollResults = MessageMedia;\nmessageMediaDice#3f7ee58b value:int emoticon:string = MessageMedia;\nmessageActionEmpty#b6aef7b0 = MessageAction;\nmessageActionChatCreate#a6638b9a title:string users:Vector<int> = MessageAction;\nmessageActionChatEditTitle#b5a1ce5a title:string = MessageAction;\nmessageActionChatEditPhoto#7fcb13a8 photo:Photo = MessageAction;\nmessageActionChatDeletePhoto#95e3fbef = MessageAction;\nmessageActionChatAddUser#488a7337 users:Vector<int> = MessageAction;\nmessageActionChatDeleteUser#b2ae9b0c user_id:int = MessageAction;\nmessageActionChatJoinedByLink#f89cf5e8 inviter_id:int = MessageAction;\nmessageActionChannelCreate#95d2ac92 title:string = MessageAction;\nmessageActionChatMigrateTo#51bdb021 channel_id:int = MessageAction;\nmessageActionChannelMigrateFrom#b055eaee title:string chat_id:int = MessageAction;\nmessageActionPinMessage#94bd38ed = MessageAction;\nmessageActionHistoryClear#9fbab604 = MessageAction;\nmessageActionGameScore#92a72876 game_id:long score:int = MessageAction;\nmessageActionPaymentSentMe#8f31b327 flags:# currency:string total_amount:long payload:bytes info:flags.0?PaymentRequestedInfo shipping_option_id:flags.1?string charge:PaymentCharge = MessageAction;\nmessageActionPaymentSent#40699cd0 currency:string total_amount:long = MessageAction;\nmessageActionPhoneCall#80e11a7f flags:# video:flags.2?true call_id:long reason:flags.0?PhoneCallDiscardReason duration:flags.1?int = MessageAction;\nmessageActionScreenshotTaken#4792929b = MessageAction;\nmessageActionCustomAction#fae69f56 message:string = MessageAction;\nmessageActionBotAllowed#abe9affe domain:string = MessageAction;\nmessageActionSecureValuesSentMe#1b287353 values:Vector<SecureValue> credentials:SecureCredentialsEncrypted = MessageAction;\nmessageActionSecureValuesSent#d95c6154 types:Vector<SecureValueType> = MessageAction;\nmessageActionContactSignUp#f3f25f76 = MessageAction;\nmessageActionGeoProximityReached#98e0d697 from_id:Peer to_id:Peer distance:int = MessageAction;\nmessageActionGroupCall#7a0d7f42 flags:# call:InputGroupCall duration:flags.0?int = MessageAction;\nmessageActionInviteToGroupCall#76b9f11a call:InputGroupCall users:Vector<int> = MessageAction;\nmessageActionSetMessagesTTL#aa1afbfd period:int = MessageAction;\nmessageActionGroupCallScheduled#b3a07661 call:InputGroupCall schedule_date:int = MessageAction;\ndialog#2c171f72 flags:# pinned:flags.2?true unread_mark:flags.3?true peer:Peer top_message:int read_inbox_max_id:int read_outbox_max_id:int unread_count:int unread_mentions_count:int notify_settings:PeerNotifySettings pts:flags.0?int draft:flags.1?DraftMessage folder_id:flags.4?int = Dialog;\ndialogFolder#71bd134c flags:# pinned:flags.2?true folder:Folder peer:Peer top_message:int unread_muted_peers_count:int unread_unmuted_peers_count:int unread_muted_messages_count:int unread_unmuted_messages_count:int = Dialog;\nphotoEmpty#2331b22d id:long = Photo;\nphoto#fb197a65 flags:# has_stickers:flags.0?true id:long access_hash:long file_reference:bytes date:int sizes:Vector<PhotoSize> video_sizes:flags.1?Vector<VideoSize> dc_id:int = Photo;\nphotoSizeEmpty#e17e23c type:string = PhotoSize;\nphotoSize#75c78e60 type:string w:int h:int size:int = PhotoSize;\nphotoCachedSize#21e1ad6 type:string w:int h:int bytes:bytes = PhotoSize;\nphotoStrippedSize#e0b0bc2e type:string bytes:bytes = PhotoSize;\nphotoSizeProgressive#fa3efb95 type:string w:int h:int sizes:Vector<int> = PhotoSize;\nphotoPathSize#d8214d41 type:string bytes:bytes = PhotoSize;\ngeoPointEmpty#1117dd5f = GeoPoint;\ngeoPoint#b2a2f663 flags:# long:double lat:double access_hash:long accuracy_radius:flags.0?int = GeoPoint;\nauth.sentCode#5e002502 flags:# type:auth.SentCodeType phone_code_hash:string next_type:flags.1?auth.CodeType timeout:flags.2?int = auth.SentCode;\nauth.authorization#cd050916 flags:# tmp_sessions:flags.0?int user:User = auth.Authorization;\nauth.authorizationSignUpRequired#44747e9a flags:# terms_of_service:flags.0?help.TermsOfService = auth.Authorization;\nauth.exportedAuthorization#df969c2d id:int bytes:bytes = auth.ExportedAuthorization;\ninputNotifyPeer#b8bc5b0c peer:InputPeer = InputNotifyPeer;\ninputNotifyUsers#193b4417 = InputNotifyPeer;\ninputNotifyChats#4a95e84e = InputNotifyPeer;\ninputNotifyBroadcasts#b1db7c7e = InputNotifyPeer;\ninputPeerNotifySettings#9c3d198e flags:# show_previews:flags.0?Bool silent:flags.1?Bool mute_until:flags.2?int sound:flags.3?string = InputPeerNotifySettings;\npeerNotifySettings#af509d20 flags:# show_previews:flags.0?Bool silent:flags.1?Bool mute_until:flags.2?int sound:flags.3?string = PeerNotifySettings;\npeerSettings#733f2961 flags:# report_spam:flags.0?true add_contact:flags.1?true block_contact:flags.2?true share_contact:flags.3?true need_contacts_exception:flags.4?true report_geo:flags.5?true autoarchived:flags.7?true invite_members:flags.8?true geo_distance:flags.6?int = PeerSettings;\nwallPaper#a437c3ed id:long flags:# creator:flags.0?true default:flags.1?true pattern:flags.3?true dark:flags.4?true access_hash:long slug:string document:Document settings:flags.2?WallPaperSettings = WallPaper;\nwallPaperNoFile#e0804116 id:long flags:# default:flags.1?true dark:flags.4?true settings:flags.2?WallPaperSettings = WallPaper;\ninputReportReasonSpam#58dbcab8 = ReportReason;\ninputReportReasonViolence#1e22c78d = ReportReason;\ninputReportReasonPornography#2e59d922 = ReportReason;\ninputReportReasonChildAbuse#adf44ee3 = ReportReason;\ninputReportReasonOther#c1e4a2b1 = ReportReason;\ninputReportReasonCopyright#9b89f93a = ReportReason;\ninputReportReasonGeoIrrelevant#dbd4feed = ReportReason;\ninputReportReasonFake#f5ddd6e7 = ReportReason;\nuserFull#139a9a77 flags:# blocked:flags.0?true phone_calls_available:flags.4?true phone_calls_private:flags.5?true can_pin_message:flags.7?true has_scheduled:flags.12?true video_calls_available:flags.13?true user:User about:flags.1?string settings:PeerSettings profile_photo:flags.2?Photo notify_settings:PeerNotifySettings bot_info:flags.3?BotInfo pinned_msg_id:flags.6?int common_chats_count:int folder_id:flags.11?int ttl_period:flags.14?int = UserFull;\ncontact#f911c994 user_id:int mutual:Bool = Contact;\nimportedContact#d0028438 user_id:int client_id:long = ImportedContact;\ncontactStatus#d3680c61 user_id:int status:UserStatus = ContactStatus;\ncontacts.contactsNotModified#b74ba9d2 = contacts.Contacts;\ncontacts.contacts#eae87e42 contacts:Vector<Contact> saved_count:int users:Vector<User> = contacts.Contacts;\ncontacts.importedContacts#77d01c3b imported:Vector<ImportedContact> popular_invites:Vector<PopularContact> retry_contacts:Vector<long> users:Vector<User> = contacts.ImportedContacts;\ncontacts.blocked#ade1591 blocked:Vector<PeerBlocked> chats:Vector<Chat> users:Vector<User> = contacts.Blocked;\ncontacts.blockedSlice#e1664194 count:int blocked:Vector<PeerBlocked> chats:Vector<Chat> users:Vector<User> = contacts.Blocked;\nmessages.dialogs#15ba6c40 dialogs:Vector<Dialog> messages:Vector<Message> chats:Vector<Chat> users:Vector<User> = messages.Dialogs;\nmessages.dialogsSlice#71e094f3 count:int dialogs:Vector<Dialog> messages:Vector<Message> chats:Vector<Chat> users:Vector<User> = messages.Dialogs;\nmessages.dialogsNotModified#f0e3e596 count:int = messages.Dialogs;\nmessages.messages#8c718e87 messages:Vector<Message> chats:Vector<Chat> users:Vector<User> = messages.Messages;\nmessages.messagesSlice#3a54685e flags:# inexact:flags.1?true count:int next_rate:flags.0?int offset_id_offset:flags.2?int messages:Vector<Message> chats:Vector<Chat> users:Vector<User> = messages.Messages;\nmessages.channelMessages#64479808 flags:# inexact:flags.1?true pts:int count:int offset_id_offset:flags.2?int messages:Vector<Message> chats:Vector<Chat> users:Vector<User> = messages.Messages;\nmessages.messagesNotModified#74535f21 count:int = messages.Messages;\nmessages.chats#64ff9fd5 chats:Vector<Chat> = messages.Chats;\nmessages.chatsSlice#9cd81144 count:int chats:Vector<Chat> = messages.Chats;\nmessages.chatFull#e5d7d19c full_chat:ChatFull chats:Vector<Chat> users:Vector<User> = messages.ChatFull;\nmessages.affectedHistory#b45c69d1 pts:int pts_count:int offset:int = messages.AffectedHistory;\ninputMessagesFilterEmpty#57e2f66c = MessagesFilter;\ninputMessagesFilterPhotos#9609a51c = MessagesFilter;\ninputMessagesFilterVideo#9fc00e65 = MessagesFilter;\ninputMessagesFilterPhotoVideo#56e9f0e4 = MessagesFilter;\ninputMessagesFilterDocument#9eddf188 = MessagesFilter;\ninputMessagesFilterUrl#7ef0dd87 = MessagesFilter;\ninputMessagesFilterGif#ffc86587 = MessagesFilter;\ninputMessagesFilterVoice#50f5c392 = MessagesFilter;\ninputMessagesFilterMusic#3751b49e = MessagesFilter;\ninputMessagesFilterChatPhotos#3a20ecb8 = MessagesFilter;\ninputMessagesFilterPhoneCalls#80c99768 flags:# missed:flags.0?true = MessagesFilter;\ninputMessagesFilterRoundVoice#7a7c17a4 = MessagesFilter;\ninputMessagesFilterRoundVideo#b549da53 = MessagesFilter;\ninputMessagesFilterMyMentions#c1f8e69a = MessagesFilter;\ninputMessagesFilterGeo#e7026d0d = MessagesFilter;\ninputMessagesFilterContacts#e062db83 = MessagesFilter;\ninputMessagesFilterPinned#1bb00451 = MessagesFilter;\nupdateNewMessage#1f2b0afd message:Message pts:int pts_count:int = Update;\nupdateMessageID#4e90bfd6 id:int random_id:long = Update;\nupdateDeleteMessages#a20db0e5 messages:Vector<int> pts:int pts_count:int = Update;\nupdateUserTyping#5c486927 user_id:int action:SendMessageAction = Update;\nupdateChatUserTyping#86cadb6c chat_id:int from_id:Peer action:SendMessageAction = Update;\nupdateChatParticipants#7761198 participants:ChatParticipants = Update;\nupdateUserStatus#1bfbd823 user_id:int status:UserStatus = Update;\nupdateUserName#a7332b73 user_id:int first_name:string last_name:string username:string = Update;\nupdateUserPhoto#95313b0c user_id:int date:int photo:UserProfilePhoto previous:Bool = Update;\nupdateNewEncryptedMessage#12bcbd9a message:EncryptedMessage qts:int = Update;\nupdateEncryptedChatTyping#1710f156 chat_id:int = Update;\nupdateEncryption#b4a2e88d chat:EncryptedChat date:int = Update;\nupdateEncryptedMessagesRead#38fe25b7 chat_id:int max_date:int date:int = Update;\nupdateChatParticipantAdd#ea4b0e5c chat_id:int user_id:int inviter_id:int date:int version:int = Update;\nupdateChatParticipantDelete#6e5f8c22 chat_id:int user_id:int version:int = Update;\nupdateDcOptions#8e5e9873 dc_options:Vector<DcOption> = Update;\nupdateNotifySettings#bec268ef peer:NotifyPeer notify_settings:PeerNotifySettings = Update;\nupdateServiceNotification#ebe46819 flags:# popup:flags.0?true inbox_date:flags.1?int type:string message:string media:MessageMedia entities:Vector<MessageEntity> = Update;\nupdatePrivacy#ee3b272a key:PrivacyKey rules:Vector<PrivacyRule> = Update;\nupdateUserPhone#12b9417b user_id:int phone:string = Update;\nupdateReadHistoryInbox#9c974fdf flags:# folder_id:flags.0?int peer:Peer max_id:int still_unread_count:int pts:int pts_count:int = Update;\nupdateReadHistoryOutbox#2f2f21bf peer:Peer max_id:int pts:int pts_count:int = Update;\nupdateWebPage#7f891213 webpage:WebPage pts:int pts_count:int = Update;\nupdateReadMessagesContents#68c13933 messages:Vector<int> pts:int pts_count:int = Update;\nupdateChannelTooLong#eb0467fb flags:# channel_id:int pts:flags.0?int = Update;\nupdateChannel#b6d45656 channel_id:int = Update;\nupdateNewChannelMessage#62ba04d9 message:Message pts:int pts_count:int = Update;\nupdateReadChannelInbox#330b5424 flags:# folder_id:flags.0?int channel_id:int max_id:int still_unread_count:int pts:int = Update;\nupdateDeleteChannelMessages#c37521c9 channel_id:int messages:Vector<int> pts:int pts_count:int = Update;\nupdateChannelMessageViews#98a12b4b channel_id:int id:int views:int = Update;\nupdateChatParticipantAdmin#b6901959 chat_id:int user_id:int is_admin:Bool version:int = Update;\nupdateNewStickerSet#688a30aa stickerset:messages.StickerSet = Update;\nupdateStickerSetsOrder#bb2d201 flags:# masks:flags.0?true order:Vector<long> = Update;\nupdateStickerSets#43ae3dec = Update;\nupdateSavedGifs#9375341e = Update;\nupdateBotInlineQuery#3f2038db flags:# query_id:long user_id:int query:string geo:flags.0?GeoPoint peer_type:flags.1?InlineQueryPeerType offset:string = Update;\nupdateBotInlineSend#e48f964 flags:# user_id:int query:string geo:flags.0?GeoPoint id:string msg_id:flags.1?InputBotInlineMessageID = Update;\nupdateEditChannelMessage#1b3f4df7 message:Message pts:int pts_count:int = Update;\nupdateBotCallbackQuery#e73547e1 flags:# query_id:long user_id:int peer:Peer msg_id:int chat_instance:long data:flags.0?bytes game_short_name:flags.1?string = Update;\nupdateEditMessage#e40370a3 message:Message pts:int pts_count:int = Update;\nupdateInlineBotCallbackQuery#f9d27a5a flags:# query_id:long user_id:int msg_id:InputBotInlineMessageID chat_instance:long data:flags.0?bytes game_short_name:flags.1?string = Update;\nupdateReadChannelOutbox#25d6c9c7 channel_id:int max_id:int = Update;\nupdateDraftMessage#ee2bb969 peer:Peer draft:DraftMessage = Update;\nupdateReadFeaturedStickers#571d2742 = Update;\nupdateRecentStickers#9a422c20 = Update;\nupdateConfig#a229dd06 = Update;\nupdatePtsChanged#3354678f = Update;\nupdateChannelWebPage#40771900 channel_id:int webpage:WebPage pts:int pts_count:int = Update;\nupdateDialogPinned#6e6fe51c flags:# pinned:flags.0?true folder_id:flags.1?int peer:DialogPeer = Update;\nupdatePinnedDialogs#fa0f3ca2 flags:# folder_id:flags.1?int order:flags.0?Vector<DialogPeer> = Update;\nupdateBotWebhookJSON#8317c0c3 data:DataJSON = Update;\nupdateBotWebhookJSONQuery#9b9240a6 query_id:long data:DataJSON timeout:int = Update;\nupdateBotShippingQuery#e0cdc940 query_id:long user_id:int payload:bytes shipping_address:PostAddress = Update;\nupdateBotPrecheckoutQuery#5d2f3aa9 flags:# query_id:long user_id:int payload:bytes info:flags.0?PaymentRequestedInfo shipping_option_id:flags.1?string currency:string total_amount:long = Update;\nupdatePhoneCall#ab0f6b1e phone_call:PhoneCall = Update;\nupdateLangPackTooLong#46560264 lang_code:string = Update;\nupdateLangPack#56022f4d difference:LangPackDifference = Update;\nupdateFavedStickers#e511996d = Update;\nupdateChannelReadMessagesContents#89893b45 channel_id:int messages:Vector<int> = Update;\nupdateContactsReset#7084a7be = Update;\nupdateChannelAvailableMessages#70db6837 channel_id:int available_min_id:int = Update;\nupdateDialogUnreadMark#e16459c3 flags:# unread:flags.0?true peer:DialogPeer = Update;\nupdateMessagePoll#aca1657b flags:# poll_id:long poll:flags.0?Poll results:PollResults = Update;\nupdateChatDefaultBannedRights#54c01850 peer:Peer default_banned_rights:ChatBannedRights version:int = Update;\nupdateFolderPeers#19360dc0 folder_peers:Vector<FolderPeer> pts:int pts_count:int = Update;\nupdatePeerSettings#6a7e7366 peer:Peer settings:PeerSettings = Update;\nupdatePeerLocated#b4afcfb0 peers:Vector<PeerLocated> = Update;\nupdateNewScheduledMessage#39a51dfb message:Message = Update;\nupdateDeleteScheduledMessages#90866cee peer:Peer messages:Vector<int> = Update;\nupdateTheme#8216fba3 theme:Theme = Update;\nupdateGeoLiveViewed#871fb939 peer:Peer msg_id:int = Update;\nupdateLoginToken#564fe691 = Update;\nupdateMessagePollVote#37f69f0b poll_id:long user_id:int options:Vector<bytes> qts:int = Update;\nupdateDialogFilter#26ffde7d flags:# id:int filter:flags.0?DialogFilter = Update;\nupdateDialogFilterOrder#a5d72105 order:Vector<int> = Update;\nupdateDialogFilters#3504914f = Update;\nupdatePhoneCallSignalingData#2661bf09 phone_call_id:long data:bytes = Update;\nupdateChannelMessageForwards#6e8a84df channel_id:int id:int forwards:int = Update;\nupdateReadChannelDiscussionInbox#1cc7de54 flags:# channel_id:int top_msg_id:int read_max_id:int broadcast_id:flags.0?int broadcast_post:flags.0?int = Update;\nupdateReadChannelDiscussionOutbox#4638a26c channel_id:int top_msg_id:int read_max_id:int = Update;\nupdatePeerBlocked#246a4b22 peer_id:Peer blocked:Bool = Update;\nupdateChannelUserTyping#6b171718 flags:# channel_id:int top_msg_id:flags.0?int from_id:Peer action:SendMessageAction = Update;\nupdatePinnedMessages#ed85eab5 flags:# pinned:flags.0?true peer:Peer messages:Vector<int> pts:int pts_count:int = Update;\nupdatePinnedChannelMessages#8588878b flags:# pinned:flags.0?true channel_id:int messages:Vector<int> pts:int pts_count:int = Update;\nupdateChat#1330a196 chat_id:int = Update;\nupdateGroupCallParticipants#f2ebdb4e call:InputGroupCall participants:Vector<GroupCallParticipant> version:int = Update;\nupdateGroupCall#a45eb99b chat_id:int call:GroupCall = Update;\nupdatePeerHistoryTTL#bb9bb9a5 flags:# peer:Peer ttl_period:flags.0?int = Update;\nupdateChatParticipant#f3b3781f flags:# chat_id:int date:int actor_id:int user_id:int prev_participant:flags.0?ChatParticipant new_participant:flags.1?ChatParticipant invite:flags.2?ExportedChatInvite qts:int = Update;\nupdateChannelParticipant#7fecb1ec flags:# channel_id:int date:int actor_id:int user_id:int prev_participant:flags.0?ChannelParticipant new_participant:flags.1?ChannelParticipant invite:flags.2?ExportedChatInvite qts:int = Update;\nupdateBotStopped#7f9488a user_id:int date:int stopped:Bool qts:int = Update;\nupdateGroupCallConnection#b783982 flags:# presentation:flags.0?true params:DataJSON = Update;\nupdateBotCommands#cf7e0873 peer:Peer bot_id:int commands:Vector<BotCommand> = Update;\nupdates.state#a56c2a3e pts:int qts:int date:int seq:int unread_count:int = updates.State;\nupdates.differenceEmpty#5d75a138 date:int seq:int = updates.Difference;\nupdates.difference#f49ca0 new_messages:Vector<Message> new_encrypted_messages:Vector<EncryptedMessage> other_updates:Vector<Update> chats:Vector<Chat> users:Vector<User> state:updates.State = updates.Difference;\nupdates.differenceSlice#a8fb1981 new_messages:Vector<Message> new_encrypted_messages:Vector<EncryptedMessage> other_updates:Vector<Update> chats:Vector<Chat> users:Vector<User> intermediate_state:updates.State = updates.Difference;\nupdates.differenceTooLong#4afe8f6d pts:int = updates.Difference;\nupdatesTooLong#e317af7e = Updates;\nupdateShortMessage#faeff833 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true id:int user_id:int message:string pts:int pts_count:int date:int fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?int reply_to:flags.3?MessageReplyHeader entities:flags.7?Vector<MessageEntity> ttl_period:flags.25?int = Updates;\nupdateShortChatMessage#1157b858 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true id:int from_id:int chat_id:int message:string pts:int pts_count:int date:int fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?int reply_to:flags.3?MessageReplyHeader entities:flags.7?Vector<MessageEntity> ttl_period:flags.25?int = Updates;\nupdateShort#78d4dec1 update:Update date:int = Updates;\nupdatesCombined#725b04c3 updates:Vector<Update> users:Vector<User> chats:Vector<Chat> date:int seq_start:int seq:int = Updates;\nupdates#74ae4240 updates:Vector<Update> users:Vector<User> chats:Vector<Chat> date:int seq:int = Updates;\nupdateShortSentMessage#9015e101 flags:# out:flags.1?true id:int pts:int pts_count:int date:int media:flags.9?MessageMedia entities:flags.7?Vector<MessageEntity> ttl_period:flags.25?int = Updates;\nphotos.photos#8dca6aa5 photos:Vector<Photo> users:Vector<User> = photos.Photos;\nphotos.photosSlice#15051f54 count:int photos:Vector<Photo> users:Vector<User> = photos.Photos;\nphotos.photo#20212ca8 photo:Photo users:Vector<User> = photos.Photo;\nupload.file#96a18d5 type:storage.FileType mtime:int bytes:bytes = upload.File;\nupload.fileCdnRedirect#f18cda44 dc_id:int file_token:bytes encryption_key:bytes encryption_iv:bytes file_hashes:Vector<FileHash> = upload.File;\ndcOption#18b7a10d flags:# ipv6:flags.0?true media_only:flags.1?true tcpo_only:flags.2?true cdn:flags.3?true static:flags.4?true id:int ip_address:string port:int secret:flags.10?bytes = DcOption;\nconfig#330b4067 flags:# phonecalls_enabled:flags.1?true default_p2p_contacts:flags.3?true preload_featured_stickers:flags.4?true ignore_phone_entities:flags.5?true revoke_pm_inbox:flags.6?true blocked_mode:flags.8?true pfs_enabled:flags.13?true date:int expires:int test_mode:Bool this_dc:int dc_options:Vector<DcOption> dc_txt_domain_name:string chat_size_max:int megagroup_size_max:int forwarded_count_max:int online_update_period_ms:int offline_blur_timeout_ms:int offline_idle_timeout_ms:int online_cloud_timeout_ms:int notify_cloud_delay_ms:int notify_default_delay_ms:int push_chat_period_ms:int push_chat_limit:int saved_gifs_limit:int edit_time_limit:int revoke_time_limit:int revoke_pm_time_limit:int rating_e_decay:int stickers_recent_limit:int stickers_faved_limit:int channels_read_media_period:int tmp_sessions:flags.0?int pinned_dialogs_count_max:int pinned_infolder_count_max:int call_receive_timeout_ms:int call_ring_timeout_ms:int call_connect_timeout_ms:int call_packet_timeout_ms:int me_url_prefix:string autoupdate_url_prefix:flags.7?string gif_search_username:flags.9?string venue_search_username:flags.10?string img_search_username:flags.11?string static_maps_provider:flags.12?string caption_length_max:int message_length_max:int webfile_dc_id:int suggested_lang_code:flags.2?string lang_pack_version:flags.2?int base_lang_pack_version:flags.2?int = Config;\nnearestDc#8e1a1775 country:string this_dc:int nearest_dc:int = NearestDc;\nhelp.appUpdate#ccbbce30 flags:# can_not_skip:flags.0?true id:int version:string text:string entities:Vector<MessageEntity> document:flags.1?Document url:flags.2?string sticker:flags.3?Document = help.AppUpdate;\nhelp.noAppUpdate#c45a6536 = help.AppUpdate;\nhelp.inviteText#18cb9f78 message:string = help.InviteText;\nencryptedChatEmpty#ab7ec0a0 id:int = EncryptedChat;\nencryptedChatWaiting#3bf703dc id:int access_hash:long date:int admin_id:int participant_id:int = EncryptedChat;\nencryptedChatRequested#62718a82 flags:# folder_id:flags.0?int id:int access_hash:long date:int admin_id:int participant_id:int g_a:bytes = EncryptedChat;\nencryptedChat#fa56ce36 id:int access_hash:long date:int admin_id:int participant_id:int g_a_or_b:bytes key_fingerprint:long = EncryptedChat;\nencryptedChatDiscarded#1e1c7c45 flags:# history_deleted:flags.0?true id:int = EncryptedChat;\ninputEncryptedChat#f141b5e1 chat_id:int access_hash:long = InputEncryptedChat;\nencryptedFileEmpty#c21f497e = EncryptedFile;\nencryptedFile#4a70994c id:long access_hash:long size:int dc_id:int key_fingerprint:int = EncryptedFile;\ninputEncryptedFileEmpty#1837c364 = InputEncryptedFile;\ninputEncryptedFileUploaded#64bd0306 id:long parts:int md5_checksum:string key_fingerprint:int = InputEncryptedFile;\ninputEncryptedFile#5a17b5e5 id:long access_hash:long = InputEncryptedFile;\ninputEncryptedFileBigUploaded#2dc173c8 id:long parts:int key_fingerprint:int = InputEncryptedFile;\nencryptedMessage#ed18c118 random_id:long chat_id:int date:int bytes:bytes file:EncryptedFile = EncryptedMessage;\nencryptedMessageService#23734b06 random_id:long chat_id:int date:int bytes:bytes = EncryptedMessage;\nmessages.dhConfigNotModified#c0e24635 random:bytes = messages.DhConfig;\nmessages.dhConfig#2c221edd g:int p:bytes version:int random:bytes = messages.DhConfig;\nmessages.sentEncryptedMessage#560f8935 date:int = messages.SentEncryptedMessage;\nmessages.sentEncryptedFile#9493ff32 date:int file:EncryptedFile = messages.SentEncryptedMessage;\ninputDocumentEmpty#72f0eaae = InputDocument;\ninputDocument#1abfb575 id:long access_hash:long file_reference:bytes = InputDocument;\ndocumentEmpty#36f8c871 id:long = Document;\ndocument#1e87342b flags:# id:long access_hash:long file_reference:bytes date:int mime_type:string size:int thumbs:flags.0?Vector<PhotoSize> video_thumbs:flags.1?Vector<VideoSize> dc_id:int attributes:Vector<DocumentAttribute> = Document;\nhelp.support#17c6b5f6 phone_number:string user:User = help.Support;\nnotifyPeer#9fd40bd8 peer:Peer = NotifyPeer;\nnotifyUsers#b4c83b4c = NotifyPeer;\nnotifyChats#c007cec3 = NotifyPeer;\nnotifyBroadcasts#d612e8ef = NotifyPeer;\nsendMessageTypingAction#16bf744e = SendMessageAction;\nsendMessageCancelAction#fd5ec8f5 = SendMessageAction;\nsendMessageRecordVideoAction#a187d66f = SendMessageAction;\nsendMessageUploadVideoAction#e9763aec progress:int = SendMessageAction;\nsendMessageRecordAudioAction#d52f73f7 = SendMessageAction;\nsendMessageUploadAudioAction#f351d7ab progress:int = SendMessageAction;\nsendMessageUploadPhotoAction#d1d34a26 progress:int = SendMessageAction;\nsendMessageUploadDocumentAction#aa0cd9e4 progress:int = SendMessageAction;\nsendMessageGeoLocationAction#176f8ba1 = SendMessageAction;\nsendMessageChooseContactAction#628cbc6f = SendMessageAction;\nsendMessageGamePlayAction#dd6a8f48 = SendMessageAction;\nsendMessageRecordRoundAction#88f27fbc = SendMessageAction;\nsendMessageUploadRoundAction#243e1c66 progress:int = SendMessageAction;\nspeakingInGroupCallAction#d92c2285 = SendMessageAction;\nsendMessageHistoryImportAction#dbda9246 progress:int = SendMessageAction;\ncontacts.found#b3134d9d my_results:Vector<Peer> results:Vector<Peer> chats:Vector<Chat> users:Vector<User> = contacts.Found;\ninputPrivacyKeyStatusTimestamp#4f96cb18 = InputPrivacyKey;\ninputPrivacyKeyChatInvite#bdfb0426 = InputPrivacyKey;\ninputPrivacyKeyPhoneCall#fabadc5f = InputPrivacyKey;\ninputPrivacyKeyPhoneP2P#db9e70d2 = InputPrivacyKey;\ninputPrivacyKeyForwards#a4dd4c08 = InputPrivacyKey;\ninputPrivacyKeyProfilePhoto#5719bacc = InputPrivacyKey;\ninputPrivacyKeyPhoneNumber#352dafa = InputPrivacyKey;\ninputPrivacyKeyAddedByPhone#d1219bdd = InputPrivacyKey;\nprivacyKeyStatusTimestamp#bc2eab30 = PrivacyKey;\nprivacyKeyChatInvite#500e6dfa = PrivacyKey;\nprivacyKeyPhoneCall#3d662b7b = PrivacyKey;\nprivacyKeyPhoneP2P#39491cc8 = PrivacyKey;\nprivacyKeyForwards#69ec56a3 = PrivacyKey;\nprivacyKeyProfilePhoto#96151fed = PrivacyKey;\nprivacyKeyPhoneNumber#d19ae46d = PrivacyKey;\nprivacyKeyAddedByPhone#42ffd42b = PrivacyKey;\ninputPrivacyValueAllowContacts#d09e07b = InputPrivacyRule;\ninputPrivacyValueAllowAll#184b35ce = InputPrivacyRule;\ninputPrivacyValueAllowUsers#131cc67f users:Vector<InputUser> = InputPrivacyRule;\ninputPrivacyValueDisallowContacts#ba52007 = InputPrivacyRule;\ninputPrivacyValueDisallowAll#d66b66c9 = InputPrivacyRule;\ninputPrivacyValueDisallowUsers#90110467 users:Vector<InputUser> = InputPrivacyRule;\ninputPrivacyValueAllowChatParticipants#4c81c1ba chats:Vector<int> = InputPrivacyRule;\ninputPrivacyValueDisallowChatParticipants#d82363af chats:Vector<int> = InputPrivacyRule;\nprivacyValueAllowContacts#fffe1bac = PrivacyRule;\nprivacyValueAllowAll#65427b82 = PrivacyRule;\nprivacyValueAllowUsers#4d5bbe0c users:Vector<int> = PrivacyRule;\nprivacyValueDisallowContacts#f888fa1a = PrivacyRule;\nprivacyValueDisallowAll#8b73e763 = PrivacyRule;\nprivacyValueDisallowUsers#c7f49b7 users:Vector<int> = PrivacyRule;\nprivacyValueAllowChatParticipants#18be796b chats:Vector<int> = PrivacyRule;\nprivacyValueDisallowChatParticipants#acae0690 chats:Vector<int> = PrivacyRule;\naccount.privacyRules#50a04e45 rules:Vector<PrivacyRule> chats:Vector<Chat> users:Vector<User> = account.PrivacyRules;\naccountDaysTTL#b8d0afdf days:int = AccountDaysTTL;\ndocumentAttributeImageSize#6c37c15c w:int h:int = DocumentAttribute;\ndocumentAttributeAnimated#11b58939 = DocumentAttribute;\ndocumentAttributeSticker#6319d612 flags:# mask:flags.1?true alt:string stickerset:InputStickerSet mask_coords:flags.0?MaskCoords = DocumentAttribute;\ndocumentAttributeVideo#ef02ce6 flags:# round_message:flags.0?true supports_streaming:flags.1?true duration:int w:int h:int = DocumentAttribute;\ndocumentAttributeAudio#9852f9c6 flags:# voice:flags.10?true duration:int title:flags.0?string performer:flags.1?string waveform:flags.2?bytes = DocumentAttribute;\ndocumentAttributeFilename#15590068 file_name:string = DocumentAttribute;\ndocumentAttributeHasStickers#9801d2f7 = DocumentAttribute;\nmessages.stickersNotModified#f1749a22 = messages.Stickers;\nmessages.stickers#e4599bbd hash:int stickers:Vector<Document> = messages.Stickers;\nstickerPack#12b299d4 emoticon:string documents:Vector<long> = StickerPack;\nmessages.allStickersNotModified#e86602c3 = messages.AllStickers;\nmessages.allStickers#edfd405f hash:int sets:Vector<StickerSet> = messages.AllStickers;\nmessages.affectedMessages#84d19185 pts:int pts_count:int = messages.AffectedMessages;\nwebPageEmpty#eb1477e8 id:long = WebPage;\nwebPagePending#c586da1c id:long date:int = WebPage;\nwebPage#e89c45b2 flags:# id:long url:string display_url:string hash:int type:flags.0?string site_name:flags.1?string title:flags.2?string description:flags.3?string photo:flags.4?Photo embed_url:flags.5?string embed_type:flags.5?string embed_width:flags.6?int embed_height:flags.6?int duration:flags.7?int author:flags.8?string document:flags.9?Document cached_page:flags.10?Page attributes:flags.12?Vector<WebPageAttribute> = WebPage;\nwebPageNotModified#7311ca11 flags:# cached_page_views:flags.0?int = WebPage;\nauthorization#ad01d61d flags:# current:flags.0?true official_app:flags.1?true password_pending:flags.2?true hash:long device_model:string platform:string system_version:string api_id:int app_name:string app_version:string date_created:int date_active:int ip:string country:string region:string = Authorization;\naccount.authorizations#1250abde authorizations:Vector<Authorization> = account.Authorizations;\naccount.password#185b184f flags:# has_recovery:flags.0?true has_secure_values:flags.1?true has_password:flags.2?true current_algo:flags.2?PasswordKdfAlgo srp_B:flags.2?bytes srp_id:flags.2?long hint:flags.3?string email_unconfirmed_pattern:flags.4?string new_algo:PasswordKdfAlgo new_secure_algo:SecurePasswordKdfAlgo secure_random:bytes pending_reset_date:flags.5?int = account.Password;\naccount.passwordSettings#9a5c33e5 flags:# email:flags.0?string secure_settings:flags.1?SecureSecretSettings = account.PasswordSettings;\naccount.passwordInputSettings#c23727c9 flags:# new_algo:flags.0?PasswordKdfAlgo new_password_hash:flags.0?bytes hint:flags.0?string email:flags.1?string new_secure_settings:flags.2?SecureSecretSettings = account.PasswordInputSettings;\nauth.passwordRecovery#137948a5 email_pattern:string = auth.PasswordRecovery;\nreceivedNotifyMessage#a384b779 id:int flags:int = ReceivedNotifyMessage;\nchatInviteExported#6e24fc9d flags:# revoked:flags.0?true permanent:flags.5?true link:string admin_id:int date:int start_date:flags.4?int expire_date:flags.1?int usage_limit:flags.2?int usage:flags.3?int = ExportedChatInvite;\nchatInviteAlready#5a686d7c chat:Chat = ChatInvite;\nchatInvite#dfc2f58e flags:# channel:flags.0?true broadcast:flags.1?true public:flags.2?true megagroup:flags.3?true title:string photo:Photo participants_count:int participants:flags.4?Vector<User> = ChatInvite;\nchatInvitePeek#61695cb0 chat:Chat expires:int = ChatInvite;\ninputStickerSetEmpty#ffb62b95 = InputStickerSet;\ninputStickerSetID#9de7a269 id:long access_hash:long = InputStickerSet;\ninputStickerSetShortName#861cc8a0 short_name:string = InputStickerSet;\ninputStickerSetAnimatedEmoji#28703c8 = InputStickerSet;\ninputStickerSetDice#e67f520e emoticon:string = InputStickerSet;\nstickerSet#d7df217a flags:# archived:flags.1?true official:flags.2?true masks:flags.3?true animated:flags.5?true installed_date:flags.0?int id:long access_hash:long title:string short_name:string thumbs:flags.4?Vector<PhotoSize> thumb_dc_id:flags.4?int thumb_version:flags.4?int count:int hash:int = StickerSet;\nmessages.stickerSet#b60a24a6 set:StickerSet packs:Vector<StickerPack> documents:Vector<Document> = messages.StickerSet;\nbotCommand#c27ac8c7 command:string description:string = BotCommand;\nbotInfo#98e81d3a user_id:int description:string commands:Vector<BotCommand> = BotInfo;\nkeyboardButton#a2fa4880 text:string = KeyboardButton;\nkeyboardButtonUrl#258aff05 text:string url:string = KeyboardButton;\nkeyboardButtonCallback#35bbdb6b flags:# requires_password:flags.0?true text:string data:bytes = KeyboardButton;\nkeyboardButtonRequestPhone#b16a6c29 text:string = KeyboardButton;\nkeyboardButtonRequestGeoLocation#fc796b3f text:string = KeyboardButton;\nkeyboardButtonSwitchInline#568a748 flags:# same_peer:flags.0?true text:string query:string = KeyboardButton;\nkeyboardButtonGame#50f41ccf text:string = KeyboardButton;\nkeyboardButtonBuy#afd93fbb text:string = KeyboardButton;\nkeyboardButtonUrlAuth#10b78d29 flags:# text:string fwd_text:flags.0?string url:string button_id:int = KeyboardButton;\ninputKeyboardButtonUrlAuth#d02e7fd4 flags:# request_write_access:flags.0?true text:string fwd_text:flags.1?string url:string bot:InputUser = KeyboardButton;\nkeyboardButtonRequestPoll#bbc7515d flags:# quiz:flags.0?Bool text:string = KeyboardButton;\nkeyboardButtonRow#77608b83 buttons:Vector<KeyboardButton> = KeyboardButtonRow;\nreplyKeyboardHide#a03e5b85 flags:# selective:flags.2?true = ReplyMarkup;\nreplyKeyboardForceReply#86b40b08 flags:# single_use:flags.1?true selective:flags.2?true placeholder:flags.3?string = ReplyMarkup;\nreplyKeyboardMarkup#85dd99d1 flags:# resize:flags.0?true single_use:flags.1?true selective:flags.2?true rows:Vector<KeyboardButtonRow> placeholder:flags.3?string = ReplyMarkup;\nreplyInlineMarkup#48a30254 rows:Vector<KeyboardButtonRow> = ReplyMarkup;\nmessageEntityUnknown#bb92ba95 offset:int length:int = MessageEntity;\nmessageEntityMention#fa04579d offset:int length:int = MessageEntity;\nmessageEntityHashtag#6f635b0d offset:int length:int = MessageEntity;\nmessageEntityBotCommand#6cef8ac7 offset:int length:int = MessageEntity;\nmessageEntityUrl#6ed02538 offset:int length:int = MessageEntity;\nmessageEntityEmail#64e475c2 offset:int length:int = MessageEntity;\nmessageEntityBold#bd610bc9 offset:int length:int = MessageEntity;\nmessageEntityItalic#826f8b60 offset:int length:int = MessageEntity;\nmessageEntityCode#28a20571 offset:int length:int = MessageEntity;\nmessageEntityPre#73924be0 offset:int length:int language:string = MessageEntity;\nmessageEntityTextUrl#76a6d327 offset:int length:int url:string = MessageEntity;\nmessageEntityMentionName#352dca58 offset:int length:int user_id:int = MessageEntity;\ninputMessageEntityMentionName#208e68c9 offset:int length:int user_id:InputUser = MessageEntity;\nmessageEntityPhone#9b69e34b offset:int length:int = MessageEntity;\nmessageEntityCashtag#4c4e743f offset:int length:int = MessageEntity;\nmessageEntityUnderline#9c4e7e8b offset:int length:int = MessageEntity;\nmessageEntityStrike#bf0693d4 offset:int length:int = MessageEntity;\nmessageEntityBlockquote#20df5d0 offset:int length:int = MessageEntity;\nmessageEntityBankCard#761e6af4 offset:int length:int = MessageEntity;\ninputChannelEmpty#ee8c1e86 = InputChannel;\ninputChannel#afeb712e channel_id:int access_hash:long = InputChannel;\ninputChannelFromMessage#2a286531 peer:InputPeer msg_id:int channel_id:int = InputChannel;\ncontacts.resolvedPeer#7f077ad9 peer:Peer chats:Vector<Chat> users:Vector<User> = contacts.ResolvedPeer;\nmessageRange#ae30253 min_id:int max_id:int = MessageRange;\nupdates.channelDifferenceEmpty#3e11affb flags:# final:flags.0?true pts:int timeout:flags.1?int = updates.ChannelDifference;\nupdates.channelDifferenceTooLong#a4bcc6fe flags:# final:flags.0?true timeout:flags.1?int dialog:Dialog messages:Vector<Message> chats:Vector<Chat> users:Vector<User> = updates.ChannelDifference;\nupdates.channelDifference#2064674e flags:# final:flags.0?true pts:int timeout:flags.1?int new_messages:Vector<Message> other_updates:Vector<Update> chats:Vector<Chat> users:Vector<User> = updates.ChannelDifference;\nchannelMessagesFilterEmpty#94d42ee7 = ChannelMessagesFilter;\nchannelMessagesFilter#cd77d957 flags:# exclude_new_messages:flags.1?true ranges:Vector<MessageRange> = ChannelMessagesFilter;\nchannelParticipant#15ebac1d user_id:int date:int = ChannelParticipant;\nchannelParticipantSelf#a3289a6d user_id:int inviter_id:int date:int = ChannelParticipant;\nchannelParticipantCreator#447dca4b flags:# user_id:int admin_rights:ChatAdminRights rank:flags.0?string = ChannelParticipant;\nchannelParticipantAdmin#ccbebbaf flags:# can_edit:flags.0?true self:flags.1?true user_id:int inviter_id:flags.1?int promoted_by:int date:int admin_rights:ChatAdminRights rank:flags.2?string = ChannelParticipant;\nchannelParticipantBanned#50a1dfd6 flags:# left:flags.0?true peer:Peer kicked_by:int date:int banned_rights:ChatBannedRights = ChannelParticipant;\nchannelParticipantLeft#1b03f006 peer:Peer = ChannelParticipant;\nchannelParticipantsRecent#de3f3c79 = ChannelParticipantsFilter;\nchannelParticipantsAdmins#b4608969 = ChannelParticipantsFilter;\nchannelParticipantsKicked#a3b54985 q:string = ChannelParticipantsFilter;\nchannelParticipantsBots#b0d1865b = ChannelParticipantsFilter;\nchannelParticipantsBanned#1427a5e1 q:string = ChannelParticipantsFilter;\nchannelParticipantsSearch#656ac4b q:string = ChannelParticipantsFilter;\nchannelParticipantsContacts#bb6ae88d q:string = ChannelParticipantsFilter;\nchannelParticipantsMentions#e04b5ceb flags:# q:flags.0?string top_msg_id:flags.1?int = ChannelParticipantsFilter;\nchannels.channelParticipants#9ab0feaf count:int participants:Vector<ChannelParticipant> chats:Vector<Chat> users:Vector<User> = channels.ChannelParticipants;\nchannels.channelParticipantsNotModified#f0173fe9 = channels.ChannelParticipants;\nchannels.channelParticipant#dfb80317 participant:ChannelParticipant chats:Vector<Chat> users:Vector<User> = channels.ChannelParticipant;\nhelp.termsOfService#780a0310 flags:# popup:flags.0?true id:DataJSON text:string entities:Vector<MessageEntity> min_age_confirm:flags.1?int = help.TermsOfService;\nmessages.savedGifsNotModified#e8025ca2 = messages.SavedGifs;\nmessages.savedGifs#2e0709a5 hash:int gifs:Vector<Document> = messages.SavedGifs;\ninputBotInlineMessageMediaAuto#3380c786 flags:# message:string entities:flags.1?Vector<MessageEntity> reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageText#3dcd7a87 flags:# no_webpage:flags.0?true message:string entities:flags.1?Vector<MessageEntity> reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaGeo#96929a85 flags:# geo_point:InputGeoPoint heading:flags.0?int period:flags.1?int proximity_notification_radius:flags.3?int reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaVenue#417bbf11 flags:# geo_point:InputGeoPoint title:string address:string provider:string venue_id:string venue_type:string reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaContact#a6edbffd flags:# phone_number:string first_name:string last_name:string vcard:string reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageGame#4b425864 flags:# reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaInvoice#d7e78225 flags:# title:string description:string photo:flags.0?InputWebDocument invoice:Invoice payload:bytes provider:string provider_data:DataJSON reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineResult#88bf9319 flags:# id:string type:string title:flags.1?string description:flags.2?string url:flags.3?string thumb:flags.4?InputWebDocument content:flags.5?InputWebDocument send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultPhoto#a8d864a7 id:string type:string photo:InputPhoto send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultDocument#fff8fdc4 flags:# id:string type:string title:flags.1?string description:flags.2?string document:InputDocument send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultGame#4fa417f2 id:string short_name:string send_message:InputBotInlineMessage = InputBotInlineResult;\nbotInlineMessageMediaAuto#764cf810 flags:# message:string entities:flags.1?Vector<MessageEntity> reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageText#8c7f65e2 flags:# no_webpage:flags.0?true message:string entities:flags.1?Vector<MessageEntity> reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaGeo#51846fd flags:# geo:GeoPoint heading:flags.0?int period:flags.1?int proximity_notification_radius:flags.3?int reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaVenue#8a86659c flags:# geo:GeoPoint title:string address:string provider:string venue_id:string venue_type:string reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaContact#18d1cdc2 flags:# phone_number:string first_name:string last_name:string vcard:string reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaInvoice#354a9b09 flags:# shipping_address_requested:flags.1?true test:flags.3?true title:string description:string photo:flags.0?WebDocument currency:string total_amount:long reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineResult#11965f3a flags:# id:string type:string title:flags.1?string description:flags.2?string url:flags.3?string thumb:flags.4?WebDocument content:flags.5?WebDocument send_message:BotInlineMessage = BotInlineResult;\nbotInlineMediaResult#17db940b flags:# id:string type:string photo:flags.0?Photo document:flags.1?Document title:flags.2?string description:flags.3?string send_message:BotInlineMessage = BotInlineResult;\nmessages.botResults#947ca848 flags:# gallery:flags.0?true query_id:long next_offset:flags.1?string switch_pm:flags.2?InlineBotSwitchPM results:Vector<BotInlineResult> cache_time:int users:Vector<User> = messages.BotResults;\nexportedMessageLink#5dab1af4 link:string html:string = ExportedMessageLink;\nmessageFwdHeader#5f777dce flags:# imported:flags.7?true from_id:flags.0?Peer from_name:flags.5?string date:int channel_post:flags.2?int post_author:flags.3?string saved_from_peer:flags.4?Peer saved_from_msg_id:flags.4?int psa_type:flags.6?string = MessageFwdHeader;\nauth.codeTypeSms#72a3158c = auth.CodeType;\nauth.codeTypeCall#741cd3e3 = auth.CodeType;\nauth.codeTypeFlashCall#226ccefb = auth.CodeType;\nauth.sentCodeTypeApp#3dbb5986 length:int = auth.SentCodeType;\nauth.sentCodeTypeSms#c000bba2 length:int = auth.SentCodeType;\nauth.sentCodeTypeCall#5353e5a7 length:int = auth.SentCodeType;\nauth.sentCodeTypeFlashCall#ab03c6d9 pattern:string = auth.SentCodeType;\nmessages.botCallbackAnswer#36585ea4 flags:# alert:flags.1?true has_url:flags.3?true native_ui:flags.4?true message:flags.0?string url:flags.2?string cache_time:int = messages.BotCallbackAnswer;\nmessages.messageEditData#26b5dde6 flags:# caption:flags.0?true = messages.MessageEditData;\ninputBotInlineMessageID#890c3d89 dc_id:int id:long access_hash:long = InputBotInlineMessageID;\ninlineBotSwitchPM#3c20629f text:string start_param:string = InlineBotSwitchPM;\nmessages.peerDialogs#3371c354 dialogs:Vector<Dialog> messages:Vector<Message> chats:Vector<Chat> users:Vector<User> state:updates.State = messages.PeerDialogs;\ntopPeer#edcdc05b peer:Peer rating:double = TopPeer;\ntopPeerCategoryBotsPM#ab661b5b = TopPeerCategory;\ntopPeerCategoryBotsInline#148677e2 = TopPeerCategory;\ntopPeerCategoryCorrespondents#637b7ed = TopPeerCategory;\ntopPeerCategoryGroups#bd17a14a = TopPeerCategory;\ntopPeerCategoryChannels#161d9628 = TopPeerCategory;\ntopPeerCategoryPhoneCalls#1e76a78c = TopPeerCategory;\ntopPeerCategoryForwardUsers#a8406ca9 = TopPeerCategory;\ntopPeerCategoryForwardChats#fbeec0f0 = TopPeerCategory;\ntopPeerCategoryPeers#fb834291 category:TopPeerCategory count:int peers:Vector<TopPeer> = TopPeerCategoryPeers;\ncontacts.topPeersNotModified#de266ef5 = contacts.TopPeers;\ncontacts.topPeers#70b772a8 categories:Vector<TopPeerCategoryPeers> chats:Vector<Chat> users:Vector<User> = contacts.TopPeers;\ncontacts.topPeersDisabled#b52c939d = contacts.TopPeers;\ndraftMessageEmpty#1b0c841a flags:# date:flags.0?int = DraftMessage;\ndraftMessage#fd8e711f flags:# no_webpage:flags.1?true reply_to_msg_id:flags.0?int message:string entities:flags.3?Vector<MessageEntity> date:int = DraftMessage;\nmessages.featuredStickersNotModified#c6dc0c66 count:int = messages.FeaturedStickers;\nmessages.featuredStickers#b6abc341 hash:int count:int sets:Vector<StickerSetCovered> unread:Vector<long> = messages.FeaturedStickers;\nmessages.recentStickersNotModified#b17f890 = messages.RecentStickers;\nmessages.recentStickers#22f3afb3 hash:int packs:Vector<StickerPack> stickers:Vector<Document> dates:Vector<int> = messages.RecentStickers;\nmessages.archivedStickers#4fcba9c8 count:int sets:Vector<StickerSetCovered> = messages.ArchivedStickers;\nmessages.stickerSetInstallResultSuccess#38641628 = messages.StickerSetInstallResult;\nmessages.stickerSetInstallResultArchive#35e410a8 sets:Vector<StickerSetCovered> = messages.StickerSetInstallResult;\nstickerSetCovered#6410a5d2 set:StickerSet cover:Document = StickerSetCovered;\nstickerSetMultiCovered#3407e51b set:StickerSet covers:Vector<Document> = StickerSetCovered;\nmaskCoords#aed6dbb2 n:int x:double y:double zoom:double = MaskCoords;\ninputStickeredMediaPhoto#4a992157 id:InputPhoto = InputStickeredMedia;\ninputStickeredMediaDocument#438865b id:InputDocument = InputStickeredMedia;\ngame#bdf9653b flags:# id:long access_hash:long short_name:string title:string description:string photo:Photo document:flags.0?Document = Game;\ninputGameID#32c3e77 id:long access_hash:long = InputGame;\ninputGameShortName#c331e80a bot_id:InputUser short_name:string = InputGame;\nhighScore#58fffcd0 pos:int user_id:int score:int = HighScore;\nmessages.highScores#9a3bfd99 scores:Vector<HighScore> users:Vector<User> = messages.HighScores;\ntextEmpty#dc3d824f = RichText;\ntextPlain#744694e0 text:string = RichText;\ntextBold#6724abc4 text:RichText = RichText;\ntextItalic#d912a59c text:RichText = RichText;\ntextUnderline#c12622c4 text:RichText = RichText;\ntextStrike#9bf8bb95 text:RichText = RichText;\ntextFixed#6c3f19b9 text:RichText = RichText;\ntextUrl#3c2884c1 text:RichText url:string webpage_id:long = RichText;\ntextEmail#de5a0dd6 text:RichText email:string = RichText;\ntextConcat#7e6260d7 texts:Vector<RichText> = RichText;\ntextSubscript#ed6a8504 text:RichText = RichText;\ntextSuperscript#c7fb5e01 text:RichText = RichText;\ntextMarked#34b8621 text:RichText = RichText;\ntextPhone#1ccb966a text:RichText phone:string = RichText;\ntextImage#81ccf4f document_id:long w:int h:int = RichText;\ntextAnchor#35553762 text:RichText name:string = RichText;\npageBlockUnsupported#13567e8a = PageBlock;\npageBlockTitle#70abc3fd text:RichText = PageBlock;\npageBlockSubtitle#8ffa9a1f text:RichText = PageBlock;\npageBlockAuthorDate#baafe5e0 author:RichText published_date:int = PageBlock;\npageBlockHeader#bfd064ec text:RichText = PageBlock;\npageBlockSubheader#f12bb6e1 text:RichText = PageBlock;\npageBlockParagraph#467a0766 text:RichText = PageBlock;\npageBlockPreformatted#c070d93e text:RichText language:string = PageBlock;\npageBlockFooter#48870999 text:RichText = PageBlock;\npageBlockDivider#db20b188 = PageBlock;\npageBlockAnchor#ce0d37b0 name:string = PageBlock;\npageBlockList#e4e88011 items:Vector<PageListItem> = PageBlock;\npageBlockBlockquote#263d7c26 text:RichText caption:RichText = PageBlock;\npageBlockPullquote#4f4456d3 text:RichText caption:RichText = PageBlock;\npageBlockPhoto#1759c560 flags:# photo_id:long caption:PageCaption url:flags.0?string webpage_id:flags.0?long = PageBlock;\npageBlockVideo#7c8fe7b6 flags:# autoplay:flags.0?true loop:flags.1?true video_id:long caption:PageCaption = PageBlock;\npageBlockCover#39f23300 cover:PageBlock = PageBlock;\npageBlockEmbed#a8718dc5 flags:# full_width:flags.0?true allow_scrolling:flags.3?true url:flags.1?string html:flags.2?string poster_photo_id:flags.4?long w:flags.5?int h:flags.5?int caption:PageCaption = PageBlock;\npageBlockEmbedPost#f259a80b url:string webpage_id:long author_photo_id:long author:string date:int blocks:Vector<PageBlock> caption:PageCaption = PageBlock;\npageBlockCollage#65a0fa4d items:Vector<PageBlock> caption:PageCaption = PageBlock;\npageBlockSlideshow#31f9590 items:Vector<PageBlock> caption:PageCaption = PageBlock;\npageBlockChannel#ef1751b5 channel:Chat = PageBlock;\npageBlockAudio#804361ea audio_id:long caption:PageCaption = PageBlock;\npageBlockKicker#1e148390 text:RichText = PageBlock;\npageBlockTable#bf4dea82 flags:# bordered:flags.0?true striped:flags.1?true title:RichText rows:Vector<PageTableRow> = PageBlock;\npageBlockOrderedList#9a8ae1e1 items:Vector<PageListOrderedItem> = PageBlock;\npageBlockDetails#76768bed flags:# open:flags.0?true blocks:Vector<PageBlock> title:RichText = PageBlock;\npageBlockRelatedArticles#16115a96 title:RichText articles:Vector<PageRelatedArticle> = PageBlock;\npageBlockMap#a44f3ef6 geo:GeoPoint zoom:int w:int h:int caption:PageCaption = PageBlock;\nphoneCallDiscardReasonMissed#85e42301 = PhoneCallDiscardReason;\nphoneCallDiscardReasonDisconnect#e095c1a0 = PhoneCallDiscardReason;\nphoneCallDiscardReasonHangup#57adc690 = PhoneCallDiscardReason;\nphoneCallDiscardReasonBusy#faf7e8c9 = PhoneCallDiscardReason;\ndataJSON#7d748d04 data:string = DataJSON;\nlabeledPrice#cb296bf8 label:string amount:long = LabeledPrice;\ninvoice#cd886e0 flags:# test:flags.0?true name_requested:flags.1?true phone_requested:flags.2?true email_requested:flags.3?true shipping_address_requested:flags.4?true flexible:flags.5?true phone_to_provider:flags.6?true email_to_provider:flags.7?true currency:string prices:Vector<LabeledPrice> max_tip_amount:flags.8?long suggested_tip_amounts:flags.8?Vector<long> = Invoice;\npaymentCharge#ea02c27e id:string provider_charge_id:string = PaymentCharge;\npostAddress#1e8caaeb street_line1:string street_line2:string city:string state:string country_iso2:string post_code:string = PostAddress;\npaymentRequestedInfo#909c3f94 flags:# name:flags.0?string phone:flags.1?string email:flags.2?string shipping_address:flags.3?PostAddress = PaymentRequestedInfo;\npaymentSavedCredentialsCard#cdc27a1f id:string title:string = PaymentSavedCredentials;\nwebDocument#1c570ed1 url:string access_hash:long size:int mime_type:string attributes:Vector<DocumentAttribute> = WebDocument;\nwebDocumentNoProxy#f9c8bcc6 url:string size:int mime_type:string attributes:Vector<DocumentAttribute> = WebDocument;\ninputWebDocument#9bed434d url:string size:int mime_type:string attributes:Vector<DocumentAttribute> = InputWebDocument;\ninputWebFileLocation#c239d686 url:string access_hash:long = InputWebFileLocation;\ninputWebFileGeoPointLocation#9f2221c9 geo_point:InputGeoPoint access_hash:long w:int h:int zoom:int scale:int = InputWebFileLocation;\nupload.webFile#21e753bc size:int mime_type:string file_type:storage.FileType mtime:int bytes:bytes = upload.WebFile;\npayments.paymentForm#8d0b2415 flags:# can_save_credentials:flags.2?true password_missing:flags.3?true form_id:long bot_id:int invoice:Invoice provider_id:int url:string native_provider:flags.4?string native_params:flags.4?DataJSON saved_info:flags.0?PaymentRequestedInfo saved_credentials:flags.1?PaymentSavedCredentials users:Vector<User> = payments.PaymentForm;\npayments.validatedRequestedInfo#d1451883 flags:# id:flags.0?string shipping_options:flags.1?Vector<ShippingOption> = payments.ValidatedRequestedInfo;\npayments.paymentResult#4e5f810d updates:Updates = payments.PaymentResult;\npayments.paymentVerificationNeeded#d8411139 url:string = payments.PaymentResult;\npayments.paymentReceipt#10b555d0 flags:# date:int bot_id:int provider_id:int title:string description:string photo:flags.2?WebDocument invoice:Invoice info:flags.0?PaymentRequestedInfo shipping:flags.1?ShippingOption tip_amount:flags.3?long currency:string total_amount:long credentials_title:string users:Vector<User> = payments.PaymentReceipt;\npayments.savedInfo#fb8fe43c flags:# has_saved_credentials:flags.1?true saved_info:flags.0?PaymentRequestedInfo = payments.SavedInfo;\ninputPaymentCredentialsSaved#c10eb2cf id:string tmp_password:bytes = InputPaymentCredentials;\ninputPaymentCredentials#3417d728 flags:# save:flags.0?true data:DataJSON = InputPaymentCredentials;\ninputPaymentCredentialsApplePay#aa1c39f payment_data:DataJSON = InputPaymentCredentials;\ninputPaymentCredentialsGooglePay#8ac32801 payment_token:DataJSON = InputPaymentCredentials;\naccount.tmpPassword#db64fd34 tmp_password:bytes valid_until:int = account.TmpPassword;\nshippingOption#b6213cdf id:string title:string prices:Vector<LabeledPrice> = ShippingOption;\ninputStickerSetItem#ffa0a496 flags:# document:InputDocument emoji:string mask_coords:flags.0?MaskCoords = InputStickerSetItem;\ninputPhoneCall#1e36fded id:long access_hash:long = InputPhoneCall;\nphoneCallEmpty#5366c915 id:long = PhoneCall;\nphoneCallWaiting#1b8f4ad1 flags:# video:flags.6?true id:long access_hash:long date:int admin_id:int participant_id:int protocol:PhoneCallProtocol receive_date:flags.0?int = PhoneCall;\nphoneCallRequested#87eabb53 flags:# video:flags.6?true id:long access_hash:long date:int admin_id:int participant_id:int g_a_hash:bytes protocol:PhoneCallProtocol = PhoneCall;\nphoneCallAccepted#997c454a flags:# video:flags.6?true id:long access_hash:long date:int admin_id:int participant_id:int g_b:bytes protocol:PhoneCallProtocol = PhoneCall;\nphoneCall#8742ae7f flags:# p2p_allowed:flags.5?true video:flags.6?true id:long access_hash:long date:int admin_id:int participant_id:int g_a_or_b:bytes key_fingerprint:long protocol:PhoneCallProtocol connections:Vector<PhoneConnection> start_date:int = PhoneCall;\nphoneCallDiscarded#50ca4de1 flags:# need_rating:flags.2?true need_debug:flags.3?true video:flags.6?true id:long reason:flags.0?PhoneCallDiscardReason duration:flags.1?int = PhoneCall;\nphoneConnection#9d4c17c0 id:long ip:string ipv6:string port:int peer_tag:bytes = PhoneConnection;\nphoneConnectionWebrtc#635fe375 flags:# turn:flags.0?true stun:flags.1?true id:long ip:string ipv6:string port:int username:string password:string = PhoneConnection;\nphoneCallProtocol#fc878fc8 flags:# udp_p2p:flags.0?true udp_reflector:flags.1?true min_layer:int max_layer:int library_versions:Vector<string> = PhoneCallProtocol;\nphone.phoneCall#ec82e140 phone_call:PhoneCall users:Vector<User> = phone.PhoneCall;\nupload.cdnFileReuploadNeeded#eea8e46e request_token:bytes = upload.CdnFile;\nupload.cdnFile#a99fca4f bytes:bytes = upload.CdnFile;\ncdnPublicKey#c982eaba dc_id:int public_key:string = CdnPublicKey;\ncdnConfig#5725e40a public_keys:Vector<CdnPublicKey> = CdnConfig;\nlangPackString#cad181f6 key:string value:string = LangPackString;\nlangPackStringPluralized#6c47ac9f flags:# key:string zero_value:flags.0?string one_value:flags.1?string two_value:flags.2?string few_value:flags.3?string many_value:flags.4?string other_value:string = LangPackString;\nlangPackStringDeleted#2979eeb2 key:string = LangPackString;\nlangPackDifference#f385c1f6 lang_code:string from_version:int version:int strings:Vector<LangPackString> = LangPackDifference;\nlangPackLanguage#eeca5ce3 flags:# official:flags.0?true rtl:flags.2?true beta:flags.3?true name:string native_name:string lang_code:string base_lang_code:flags.1?string plural_code:string strings_count:int translated_count:int translations_url:string = LangPackLanguage;\nchannelAdminLogEventActionChangeTitle#e6dfb825 prev_value:string new_value:string = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeAbout#55188a2e prev_value:string new_value:string = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeUsername#6a4afc38 prev_value:string new_value:string = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangePhoto#434bd2af prev_photo:Photo new_photo:Photo = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleInvites#1b7907ae new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleSignatures#26ae0971 new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionUpdatePinned#e9e82c18 message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionEditMessage#709b2405 prev_message:Message new_message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionDeleteMessage#42e047bb message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantJoin#183040d3 = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantLeave#f89777f2 = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantInvite#e31c34d8 participant:ChannelParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantToggleBan#e6d83d7e prev_participant:ChannelParticipant new_participant:ChannelParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantToggleAdmin#d5676710 prev_participant:ChannelParticipant new_participant:ChannelParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeStickerSet#b1c3caa7 prev_stickerset:InputStickerSet new_stickerset:InputStickerSet = ChannelAdminLogEventAction;\nchannelAdminLogEventActionTogglePreHistoryHidden#5f5c95f1 new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionDefaultBannedRights#2df5fc0a prev_banned_rights:ChatBannedRights new_banned_rights:ChatBannedRights = ChannelAdminLogEventAction;\nchannelAdminLogEventActionStopPoll#8f079643 message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeLinkedChat#a26f881b prev_value:int new_value:int = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeLocation#e6b76ae prev_value:ChannelLocation new_value:ChannelLocation = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleSlowMode#53909779 prev_value:int new_value:int = ChannelAdminLogEventAction;\nchannelAdminLogEventActionStartGroupCall#23209745 call:InputGroupCall = ChannelAdminLogEventAction;\nchannelAdminLogEventActionDiscardGroupCall#db9f9140 call:InputGroupCall = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantMute#f92424d2 participant:GroupCallParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantUnmute#e64429c0 participant:GroupCallParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleGroupCallSetting#56d6a247 join_muted:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantJoinByInvite#5cdada77 invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionExportedInviteDelete#5a50fca4 invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionExportedInviteRevoke#410a134e invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionExportedInviteEdit#e90ebb59 prev_invite:ExportedChatInvite new_invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantVolume#3e7f6847 participant:GroupCallParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeHistoryTTL#6e941a38 prev_value:int new_value:int = ChannelAdminLogEventAction;\nchannelAdminLogEvent#3b5a3e40 id:long date:int user_id:int action:ChannelAdminLogEventAction = ChannelAdminLogEvent;\nchannels.adminLogResults#ed8af74d events:Vector<ChannelAdminLogEvent> chats:Vector<Chat> users:Vector<User> = channels.AdminLogResults;\nchannelAdminLogEventsFilter#ea107ae4 flags:# join:flags.0?true leave:flags.1?true invite:flags.2?true ban:flags.3?true unban:flags.4?true kick:flags.5?true unkick:flags.6?true promote:flags.7?true demote:flags.8?true info:flags.9?true settings:flags.10?true pinned:flags.11?true edit:flags.12?true delete:flags.13?true group_call:flags.14?true invites:flags.15?true = ChannelAdminLogEventsFilter;\npopularContact#5ce14175 client_id:long importers:int = PopularContact;\nmessages.favedStickersNotModified#9e8fa6d3 = messages.FavedStickers;\nmessages.favedStickers#f37f2f16 hash:int packs:Vector<StickerPack> stickers:Vector<Document> = messages.FavedStickers;\nrecentMeUrlUnknown#46e1d13d url:string = RecentMeUrl;\nrecentMeUrlUser#8dbc3336 url:string user_id:int = RecentMeUrl;\nrecentMeUrlChat#a01b22f9 url:string chat_id:int = RecentMeUrl;\nrecentMeUrlChatInvite#eb49081d url:string chat_invite:ChatInvite = RecentMeUrl;\nrecentMeUrlStickerSet#bc0a57dc url:string set:StickerSetCovered = RecentMeUrl;\nhelp.recentMeUrls#e0310d7 urls:Vector<RecentMeUrl> chats:Vector<Chat> users:Vector<User> = help.RecentMeUrls;\ninputSingleMedia#1cc6e91f flags:# media:InputMedia random_id:long message:string entities:flags.0?Vector<MessageEntity> = InputSingleMedia;\nwebAuthorization#cac943f2 hash:long bot_id:int domain:string browser:string platform:string date_created:int date_active:int ip:string region:string = WebAuthorization;\naccount.webAuthorizations#ed56c9fc authorizations:Vector<WebAuthorization> users:Vector<User> = account.WebAuthorizations;\ninputMessageID#a676a322 id:int = InputMessage;\ninputMessageReplyTo#bad88395 id:int = InputMessage;\ninputMessagePinned#86872538 = InputMessage;\ninputMessageCallbackQuery#acfa1a7e id:int query_id:long = InputMessage;\ninputDialogPeer#fcaafeb7 peer:InputPeer = InputDialogPeer;\ninputDialogPeerFolder#64600527 folder_id:int = InputDialogPeer;\ndialogPeer#e56dbf05 peer:Peer = DialogPeer;\ndialogPeerFolder#514519e2 folder_id:int = DialogPeer;\nmessages.foundStickerSetsNotModified#d54b65d = messages.FoundStickerSets;\nmessages.foundStickerSets#5108d648 hash:int sets:Vector<StickerSetCovered> = messages.FoundStickerSets;\nfileHash#6242c773 offset:int limit:int hash:bytes = FileHash;\ninputClientProxy#75588b3f address:string port:int = InputClientProxy;\nhelp.termsOfServiceUpdateEmpty#e3309f7f expires:int = help.TermsOfServiceUpdate;\nhelp.termsOfServiceUpdate#28ecf961 expires:int terms_of_service:help.TermsOfService = help.TermsOfServiceUpdate;\ninputSecureFileUploaded#3334b0f0 id:long parts:int md5_checksum:string file_hash:bytes secret:bytes = InputSecureFile;\ninputSecureFile#5367e5be id:long access_hash:long = InputSecureFile;\nsecureFileEmpty#64199744 = SecureFile;\nsecureFile#e0277a62 id:long access_hash:long size:int dc_id:int date:int file_hash:bytes secret:bytes = SecureFile;\nsecureData#8aeabec3 data:bytes data_hash:bytes secret:bytes = SecureData;\nsecurePlainPhone#7d6099dd phone:string = SecurePlainData;\nsecurePlainEmail#21ec5a5f email:string = SecurePlainData;\nsecureValueTypePersonalDetails#9d2a81e3 = SecureValueType;\nsecureValueTypePassport#3dac6a00 = SecureValueType;\nsecureValueTypeDriverLicense#6e425c4 = SecureValueType;\nsecureValueTypeIdentityCard#a0d0744b = SecureValueType;\nsecureValueTypeInternalPassport#99a48f23 = SecureValueType;\nsecureValueTypeAddress#cbe31e26 = SecureValueType;\nsecureValueTypeUtilityBill#fc36954e = SecureValueType;\nsecureValueTypeBankStatement#89137c0d = SecureValueType;\nsecureValueTypeRentalAgreement#8b883488 = SecureValueType;\nsecureValueTypePassportRegistration#99e3806a = SecureValueType;\nsecureValueTypeTemporaryRegistration#ea02ec33 = SecureValueType;\nsecureValueTypePhone#b320aadb = SecureValueType;\nsecureValueTypeEmail#8e3ca7ee = SecureValueType;\nsecureValue#187fa0ca flags:# type:SecureValueType data:flags.0?SecureData front_side:flags.1?SecureFile reverse_side:flags.2?SecureFile selfie:flags.3?SecureFile translation:flags.6?Vector<SecureFile> files:flags.4?Vector<SecureFile> plain_data:flags.5?SecurePlainData hash:bytes = SecureValue;\ninputSecureValue#db21d0a7 flags:# type:SecureValueType data:flags.0?SecureData front_side:flags.1?InputSecureFile reverse_side:flags.2?InputSecureFile selfie:flags.3?InputSecureFile translation:flags.6?Vector<InputSecureFile> files:flags.4?Vector<InputSecureFile> plain_data:flags.5?SecurePlainData = InputSecureValue;\nsecureValueHash#ed1ecdb0 type:SecureValueType hash:bytes = SecureValueHash;\nsecureValueErrorData#e8a40bd9 type:SecureValueType data_hash:bytes field:string text:string = SecureValueError;\nsecureValueErrorFrontSide#be3dfa type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorReverseSide#868a2aa5 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorSelfie#e537ced6 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorFile#7a700873 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorFiles#666220e9 type:SecureValueType file_hash:Vector<bytes> text:string = SecureValueError;\nsecureValueError#869d758f type:SecureValueType hash:bytes text:string = SecureValueError;\nsecureValueErrorTranslationFile#a1144770 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorTranslationFiles#34636dd8 type:SecureValueType file_hash:Vector<bytes> text:string = SecureValueError;\nsecureCredentialsEncrypted#33f0ea47 data:bytes hash:bytes secret:bytes = SecureCredentialsEncrypted;\naccount.authorizationForm#ad2e1cd8 flags:# required_types:Vector<SecureRequiredType> values:Vector<SecureValue> errors:Vector<SecureValueError> users:Vector<User> privacy_policy_url:flags.0?string = account.AuthorizationForm;\naccount.sentEmailCode#811f854f email_pattern:string length:int = account.SentEmailCode;\nhelp.deepLinkInfoEmpty#66afa166 = help.DeepLinkInfo;\nhelp.deepLinkInfo#6a4ee832 flags:# update_app:flags.0?true message:string entities:flags.1?Vector<MessageEntity> = help.DeepLinkInfo;\nsavedPhoneContact#1142bd56 phone:string first_name:string last_name:string date:int = SavedContact;\naccount.takeout#4dba4501 id:long = account.Takeout;\npasswordKdfAlgoUnknown#d45ab096 = PasswordKdfAlgo;\npasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow#3a912d4a salt1:bytes salt2:bytes g:int p:bytes = PasswordKdfAlgo;\nsecurePasswordKdfAlgoUnknown#4a8537 = SecurePasswordKdfAlgo;\nsecurePasswordKdfAlgoPBKDF2HMACSHA512iter100000#bbf2dda0 salt:bytes = SecurePasswordKdfAlgo;\nsecurePasswordKdfAlgoSHA512#86471d92 salt:bytes = SecurePasswordKdfAlgo;\nsecureSecretSettings#1527bcac secure_algo:SecurePasswordKdfAlgo secure_secret:bytes secure_secret_id:long = SecureSecretSettings;\ninputCheckPasswordEmpty#9880f658 = InputCheckPasswordSRP;\ninputCheckPasswordSRP#d27ff082 srp_id:long A:bytes M1:bytes = InputCheckPasswordSRP;\nsecureRequiredType#829d99da flags:# native_names:flags.0?true selfie_required:flags.1?true translation_required:flags.2?true type:SecureValueType = SecureRequiredType;\nsecureRequiredTypeOneOf#27477b4 types:Vector<SecureRequiredType> = SecureRequiredType;\nhelp.passportConfigNotModified#bfb9f457 = help.PassportConfig;\nhelp.passportConfig#a098d6af hash:int countries_langs:DataJSON = help.PassportConfig;\ninputAppEvent#1d1b1245 time:double type:string peer:long data:JSONValue = InputAppEvent;\njsonObjectValue#c0de1bd9 key:string value:JSONValue = JSONObjectValue;\njsonNull#3f6d7b68 = JSONValue;\njsonBool#c7345e6a value:Bool = JSONValue;\njsonNumber#2be0dfa4 value:double = JSONValue;\njsonString#b71e767a value:string = JSONValue;\njsonArray#f7444763 value:Vector<JSONValue> = JSONValue;\njsonObject#99c1d49d value:Vector<JSONObjectValue> = JSONValue;\npageTableCell#34566b6a flags:# header:flags.0?true align_center:flags.3?true align_right:flags.4?true valign_middle:flags.5?true valign_bottom:flags.6?true text:flags.7?RichText colspan:flags.1?int rowspan:flags.2?int = PageTableCell;\npageTableRow#e0c0c5e5 cells:Vector<PageTableCell> = PageTableRow;\npageCaption#6f747657 text:RichText credit:RichText = PageCaption;\npageListItemText#b92fb6cd text:RichText = PageListItem;\npageListItemBlocks#25e073fc blocks:Vector<PageBlock> = PageListItem;\npageListOrderedItemText#5e068047 num:string text:RichText = PageListOrderedItem;\npageListOrderedItemBlocks#98dd8936 num:string blocks:Vector<PageBlock> = PageListOrderedItem;\npageRelatedArticle#b390dc08 flags:# url:string webpage_id:long title:flags.0?string description:flags.1?string photo_id:flags.2?long author:flags.3?string published_date:flags.4?int = PageRelatedArticle;\npage#98657f0d flags:# part:flags.0?true rtl:flags.1?true v2:flags.2?true url:string blocks:Vector<PageBlock> photos:Vector<Photo> documents:Vector<Document> views:flags.3?int = Page;\nhelp.supportName#8c05f1c9 name:string = help.SupportName;\nhelp.userInfoEmpty#f3ae2eed = help.UserInfo;\nhelp.userInfo#1eb3758 message:string entities:Vector<MessageEntity> author:string date:int = help.UserInfo;\npollAnswer#6ca9c2e9 text:string option:bytes = PollAnswer;\npoll#86e18161 id:long flags:# closed:flags.0?true public_voters:flags.1?true multiple_choice:flags.2?true quiz:flags.3?true question:string answers:Vector<PollAnswer> close_period:flags.4?int close_date:flags.5?int = Poll;\npollAnswerVoters#3b6ddad2 flags:# chosen:flags.0?true correct:flags.1?true option:bytes voters:int = PollAnswerVoters;\npollResults#badcc1a3 flags:# min:flags.0?true results:flags.1?Vector<PollAnswerVoters> total_voters:flags.2?int recent_voters:flags.3?Vector<int> solution:flags.4?string solution_entities:flags.4?Vector<MessageEntity> = PollResults;\nchatOnlines#f041e250 onlines:int = ChatOnlines;\nstatsURL#47a971e0 url:string = StatsURL;\nchatAdminRights#5fb224d5 flags:# change_info:flags.0?true post_messages:flags.1?true edit_messages:flags.2?true delete_messages:flags.3?true ban_users:flags.4?true invite_users:flags.5?true pin_messages:flags.7?true add_admins:flags.9?true anonymous:flags.10?true manage_call:flags.11?true other:flags.12?true = ChatAdminRights;\nchatBannedRights#9f120418 flags:# view_messages:flags.0?true send_messages:flags.1?true send_media:flags.2?true send_stickers:flags.3?true send_gifs:flags.4?true send_games:flags.5?true send_inline:flags.6?true embed_links:flags.7?true send_polls:flags.8?true change_info:flags.10?true invite_users:flags.15?true pin_messages:flags.17?true until_date:int = ChatBannedRights;\ninputWallPaper#e630b979 id:long access_hash:long = InputWallPaper;\ninputWallPaperSlug#72091c80 slug:string = InputWallPaper;\ninputWallPaperNoFile#967a462e id:long = InputWallPaper;\naccount.wallPapersNotModified#1c199183 = account.WallPapers;\naccount.wallPapers#702b65a9 hash:int wallpapers:Vector<WallPaper> = account.WallPapers;\ncodeSettings#debebe83 flags:# allow_flashcall:flags.0?true current_number:flags.1?true allow_app_hash:flags.4?true = CodeSettings;\nwallPaperSettings#1dc1bca4 flags:# blur:flags.1?true motion:flags.2?true background_color:flags.0?int second_background_color:flags.4?int third_background_color:flags.5?int fourth_background_color:flags.6?int intensity:flags.3?int rotation:flags.4?int = WallPaperSettings;\nautoDownloadSettings#e04232f3 flags:# disabled:flags.0?true video_preload_large:flags.1?true audio_preload_next:flags.2?true phonecalls_less_data:flags.3?true photo_size_max:int video_size_max:int file_size_max:int video_upload_maxbitrate:int = AutoDownloadSettings;\naccount.autoDownloadSettings#63cacf26 low:AutoDownloadSettings medium:AutoDownloadSettings high:AutoDownloadSettings = account.AutoDownloadSettings;\nemojiKeyword#d5b3b9f9 keyword:string emoticons:Vector<string> = EmojiKeyword;\nemojiKeywordDeleted#236df622 keyword:string emoticons:Vector<string> = EmojiKeyword;\nemojiKeywordsDifference#5cc761bd lang_code:string from_version:int version:int keywords:Vector<EmojiKeyword> = EmojiKeywordsDifference;\nemojiURL#a575739d url:string = EmojiURL;\nemojiLanguage#b3fb5361 lang_code:string = EmojiLanguage;\nfolder#ff544e65 flags:# autofill_new_broadcasts:flags.0?true autofill_public_groups:flags.1?true autofill_new_correspondents:flags.2?true id:int title:string photo:flags.3?ChatPhoto = Folder;\ninputFolderPeer#fbd2c296 peer:InputPeer folder_id:int = InputFolderPeer;\nfolderPeer#e9baa668 peer:Peer folder_id:int = FolderPeer;\nmessages.searchCounter#e844ebff flags:# inexact:flags.1?true filter:MessagesFilter count:int = messages.SearchCounter;\nurlAuthResultRequest#92d33a0e flags:# request_write_access:flags.0?true bot:User domain:string = UrlAuthResult;\nurlAuthResultAccepted#8f8c0e4e url:string = UrlAuthResult;\nurlAuthResultDefault#a9d6db1f = UrlAuthResult;\nchannelLocationEmpty#bfb5ad8b = ChannelLocation;\nchannelLocation#209b82db geo_point:GeoPoint address:string = ChannelLocation;\npeerLocated#ca461b5d peer:Peer expires:int distance:int = PeerLocated;\npeerSelfLocated#f8ec284b expires:int = PeerLocated;\nrestrictionReason#d072acb4 platform:string reason:string text:string = RestrictionReason;\ninputTheme#3c5693e9 id:long access_hash:long = InputTheme;\ninputThemeSlug#f5890df1 slug:string = InputTheme;\ntheme#28f1114 flags:# creator:flags.0?true default:flags.1?true id:long access_hash:long slug:string title:string document:flags.2?Document settings:flags.3?ThemeSettings installs_count:int = Theme;\naccount.themesNotModified#f41eb622 = account.Themes;\naccount.themes#7f676421 hash:int themes:Vector<Theme> = account.Themes;\nauth.loginToken#629f1980 expires:int token:bytes = auth.LoginToken;\nauth.loginTokenMigrateTo#68e9916 dc_id:int token:bytes = auth.LoginToken;\nauth.loginTokenSuccess#390d5c5e authorization:auth.Authorization = auth.LoginToken;\naccount.contentSettings#57e28221 flags:# sensitive_enabled:flags.0?true sensitive_can_change:flags.1?true = account.ContentSettings;\nmessages.inactiveChats#a927fec5 dates:Vector<int> chats:Vector<Chat> users:Vector<User> = messages.InactiveChats;\nbaseThemeClassic#c3a12462 = BaseTheme;\nbaseThemeDay#fbd81688 = BaseTheme;\nbaseThemeNight#b7b31ea8 = BaseTheme;\nbaseThemeTinted#6d5f77ee = BaseTheme;\nbaseThemeArctic#5b11125a = BaseTheme;\ninputThemeSettings#bd507cd1 flags:# base_theme:BaseTheme accent_color:int message_top_color:flags.0?int message_bottom_color:flags.0?int wallpaper:flags.1?InputWallPaper wallpaper_settings:flags.1?WallPaperSettings = InputThemeSettings;\nthemeSettings#9c14984a flags:# base_theme:BaseTheme accent_color:int message_top_color:flags.0?int message_bottom_color:flags.0?int wallpaper:flags.1?WallPaper = ThemeSettings;\nwebPageAttributeTheme#54b56617 flags:# documents:flags.0?Vector<Document> settings:flags.1?ThemeSettings = WebPageAttribute;\nmessageUserVote#a28e5559 user_id:int option:bytes date:int = MessageUserVote;\nmessageUserVoteInputOption#36377430 user_id:int date:int = MessageUserVote;\nmessageUserVoteMultiple#e8fe0de user_id:int options:Vector<bytes> date:int = MessageUserVote;\nmessages.votesList#823f649 flags:# count:int votes:Vector<MessageUserVote> users:Vector<User> next_offset:flags.0?string = messages.VotesList;\nbankCardOpenUrl#f568028a url:string name:string = BankCardOpenUrl;\npayments.bankCardData#3e24e573 title:string open_urls:Vector<BankCardOpenUrl> = payments.BankCardData;\ndialogFilter#7438f7e8 flags:# contacts:flags.0?true non_contacts:flags.1?true groups:flags.2?true broadcasts:flags.3?true bots:flags.4?true exclude_muted:flags.11?true exclude_read:flags.12?true exclude_archived:flags.13?true id:int title:string emoticon:flags.25?string pinned_peers:Vector<InputPeer> include_peers:Vector<InputPeer> exclude_peers:Vector<InputPeer> = DialogFilter;\ndialogFilterSuggested#77744d4a filter:DialogFilter description:string = DialogFilterSuggested;\nstatsDateRangeDays#b637edaf min_date:int max_date:int = StatsDateRangeDays;\nstatsAbsValueAndPrev#cb43acde current:double previous:double = StatsAbsValueAndPrev;\nstatsPercentValue#cbce2fe0 part:double total:double = StatsPercentValue;\nstatsGraphAsync#4a27eb2d token:string = StatsGraph;\nstatsGraphError#bedc9822 error:string = StatsGraph;\nstatsGraph#8ea464b6 flags:# json:DataJSON zoom_token:flags.0?string = StatsGraph;\nmessageInteractionCounters#ad4fc9bd msg_id:int views:int forwards:int = MessageInteractionCounters;\nstats.broadcastStats#bdf78394 period:StatsDateRangeDays followers:StatsAbsValueAndPrev views_per_post:StatsAbsValueAndPrev shares_per_post:StatsAbsValueAndPrev enabled_notifications:StatsPercentValue growth_graph:StatsGraph followers_graph:StatsGraph mute_graph:StatsGraph top_hours_graph:StatsGraph interactions_graph:StatsGraph iv_interactions_graph:StatsGraph views_by_source_graph:StatsGraph new_followers_by_source_graph:StatsGraph languages_graph:StatsGraph recent_message_interactions:Vector<MessageInteractionCounters> = stats.BroadcastStats;\nhelp.promoDataEmpty#98f6ac75 expires:int = help.PromoData;\nhelp.promoData#8c39793f flags:# proxy:flags.0?true expires:int peer:Peer chats:Vector<Chat> users:Vector<User> psa_type:flags.1?string psa_message:flags.2?string = help.PromoData;\nvideoSize#de33b094 flags:# type:string w:int h:int size:int video_start_ts:flags.0?double = VideoSize;\nstatsGroupTopPoster#18f3d0f7 user_id:int messages:int avg_chars:int = StatsGroupTopPoster;\nstatsGroupTopAdmin#6014f412 user_id:int deleted:int kicked:int banned:int = StatsGroupTopAdmin;\nstatsGroupTopInviter#31962a4c user_id:int invitations:int = StatsGroupTopInviter;\nstats.megagroupStats#ef7ff916 period:StatsDateRangeDays members:StatsAbsValueAndPrev messages:StatsAbsValueAndPrev viewers:StatsAbsValueAndPrev posters:StatsAbsValueAndPrev growth_graph:StatsGraph members_graph:StatsGraph new_members_by_source_graph:StatsGraph languages_graph:StatsGraph messages_graph:StatsGraph actions_graph:StatsGraph top_hours_graph:StatsGraph weekdays_graph:StatsGraph top_posters:Vector<StatsGroupTopPoster> top_admins:Vector<StatsGroupTopAdmin> top_inviters:Vector<StatsGroupTopInviter> users:Vector<User> = stats.MegagroupStats;\nglobalPrivacySettings#bea2f424 flags:# archive_and_mute_new_noncontact_peers:flags.0?Bool = GlobalPrivacySettings;\nhelp.countryCode#4203c5ef flags:# country_code:string prefixes:flags.0?Vector<string> patterns:flags.1?Vector<string> = help.CountryCode;\nhelp.country#c3878e23 flags:# hidden:flags.0?true iso2:string default_name:string name:flags.1?string country_codes:Vector<help.CountryCode> = help.Country;\nhelp.countriesListNotModified#93cc1f32 = help.CountriesList;\nhelp.countriesList#87d0759e countries:Vector<help.Country> hash:int = help.CountriesList;\nmessageViews#455b853d flags:# views:flags.0?int forwards:flags.1?int replies:flags.2?MessageReplies = MessageViews;\nmessages.messageViews#b6c4f543 views:Vector<MessageViews> chats:Vector<Chat> users:Vector<User> = messages.MessageViews;\nmessages.discussionMessage#f5dd8f9d flags:# messages:Vector<Message> max_id:flags.0?int read_inbox_max_id:flags.1?int read_outbox_max_id:flags.2?int chats:Vector<Chat> users:Vector<User> = messages.DiscussionMessage;\nmessageReplyHeader#a6d57763 flags:# reply_to_msg_id:int reply_to_peer_id:flags.0?Peer reply_to_top_id:flags.1?int = MessageReplyHeader;\nmessageReplies#4128faac flags:# comments:flags.0?true replies:int replies_pts:int recent_repliers:flags.1?Vector<Peer> channel_id:flags.0?int max_id:flags.2?int read_max_id:flags.3?int = MessageReplies;\npeerBlocked#e8fd8014 peer_id:Peer date:int = PeerBlocked;\nstats.messageStats#8999f295 views_graph:StatsGraph = stats.MessageStats;\ngroupCallDiscarded#7780bcb4 id:long access_hash:long duration:int = GroupCall;\ngroupCall#d597650c flags:# join_muted:flags.1?true can_change_join_muted:flags.2?true join_date_asc:flags.6?true schedule_start_subscribed:flags.8?true can_start_video:flags.9?true id:long access_hash:long participants_count:int title:flags.3?string stream_dc_id:flags.4?int record_start_date:flags.5?int schedule_date:flags.7?int unmuted_video_count:flags.10?int unmuted_video_limit:int version:int = GroupCall;\ninputGroupCall#d8aa840f id:long access_hash:long = InputGroupCall;\ngroupCallParticipant#eba636fe flags:# muted:flags.0?true left:flags.1?true can_self_unmute:flags.2?true just_joined:flags.4?true versioned:flags.5?true min:flags.8?true muted_by_you:flags.9?true volume_by_admin:flags.10?true self:flags.12?true video_joined:flags.15?true peer:Peer date:int active_date:flags.3?int source:int volume:flags.7?int about:flags.11?string raise_hand_rating:flags.13?long video:flags.6?GroupCallParticipantVideo presentation:flags.14?GroupCallParticipantVideo = GroupCallParticipant;\nphone.groupCall#9e727aad call:GroupCall participants:Vector<GroupCallParticipant> participants_next_offset:string chats:Vector<Chat> users:Vector<User> = phone.GroupCall;\nphone.groupParticipants#f47751b6 count:int participants:Vector<GroupCallParticipant> next_offset:string chats:Vector<Chat> users:Vector<User> version:int = phone.GroupParticipants;\ninlineQueryPeerTypeSameBotPM#3081ed9d = InlineQueryPeerType;\ninlineQueryPeerTypePM#833c0fac = InlineQueryPeerType;\ninlineQueryPeerTypeChat#d766c50a = InlineQueryPeerType;\ninlineQueryPeerTypeMegagroup#5ec4be43 = InlineQueryPeerType;\ninlineQueryPeerTypeBroadcast#6334ee9a = InlineQueryPeerType;\nmessages.historyImport#1662af0b id:long = messages.HistoryImport;\nmessages.historyImportParsed#5e0fb7b9 flags:# pm:flags.0?true group:flags.1?true title:flags.2?string = messages.HistoryImportParsed;\nmessages.affectedFoundMessages#ef8d3e6c pts:int pts_count:int offset:int messages:Vector<int> = messages.AffectedFoundMessages;\nchatInviteImporter#1e3e6680 user_id:int date:int = ChatInviteImporter;\nmessages.exportedChatInvites#bdc62dcc count:int invites:Vector<ExportedChatInvite> users:Vector<User> = messages.ExportedChatInvites;\nmessages.exportedChatInvite#1871be50 invite:ExportedChatInvite users:Vector<User> = messages.ExportedChatInvite;\nmessages.exportedChatInviteReplaced#222600ef invite:ExportedChatInvite new_invite:ExportedChatInvite users:Vector<User> = messages.ExportedChatInvite;\nmessages.chatInviteImporters#81b6b00a count:int importers:Vector<ChatInviteImporter> users:Vector<User> = messages.ChatInviteImporters;\nchatAdminWithInvites#dfd2330f admin_id:int invites_count:int revoked_invites_count:int = ChatAdminWithInvites;\nmessages.chatAdminsWithInvites#b69b72d7 admins:Vector<ChatAdminWithInvites> users:Vector<User> = messages.ChatAdminsWithInvites;\nmessages.checkedHistoryImportPeer#a24de717 confirm_text:string = messages.CheckedHistoryImportPeer;\nphone.joinAsPeers#afe5623f peers:Vector<Peer> chats:Vector<Chat> users:Vector<User> = phone.JoinAsPeers;\nphone.exportedGroupCallInvite#204bd158 link:string = phone.ExportedGroupCallInvite;\ngroupCallParticipantVideoSourceGroup#dcb118b7 semantics:string sources:Vector<int> = GroupCallParticipantVideoSourceGroup;\ngroupCallParticipantVideo#67753ac8 flags:# paused:flags.0?true endpoint:string source_groups:Vector<GroupCallParticipantVideoSourceGroup> audio_source:flags.1?int = GroupCallParticipantVideo;\nstickers.suggestedShortName#85fea03f short_name:string = stickers.SuggestedShortName;\nbotCommandScopeDefault#2f6cb2ab = BotCommandScope;\nbotCommandScopeUsers#3c4f04d8 = BotCommandScope;\nbotCommandScopeChats#6fe1a881 = BotCommandScope;\nbotCommandScopeChatAdmins#b9aa606a = BotCommandScope;\nbotCommandScopePeer#db9d897d peer:InputPeer = BotCommandScope;\nbotCommandScopePeerAdmins#3fd863d1 peer:InputPeer = BotCommandScope;\nbotCommandScopePeerUser#a1321f3 peer:InputPeer user_id:InputUser = BotCommandScope;\naccount.resetPasswordFailedWait#e3779861 retry_date:int = account.ResetPasswordResult;\naccount.resetPasswordRequestedWait#e9effc7d until_date:int = account.ResetPasswordResult;\naccount.resetPasswordOk#e926d63e = account.ResetPasswordResult;\n---functions---\ninitConnection#c1cd5ea9 {X:Type} flags:# api_id:int device_model:string system_version:string app_version:string system_lang_code:string lang_pack:string lang_code:string proxy:flags.0?InputClientProxy params:flags.1?JSONValue query:!X = X;\ninvokeWithLayer#da9b0d0d {X:Type} layer:int query:!X = X;\nauth.sendCode#a677244f phone_number:string api_id:int api_hash:string settings:CodeSettings = auth.SentCode;\nauth.signUp#80eee427 phone_number:string phone_code_hash:string first_name:string last_name:string = auth.Authorization;\nauth.signIn#bcd51581 phone_number:string phone_code_hash:string phone_code:string = auth.Authorization;\nauth.logOut#5717da40 = Bool;\nauth.resetAuthorizations#9fab0d1a = Bool;\nauth.exportAuthorization#e5bfffcd dc_id:int = auth.ExportedAuthorization;\nauth.importAuthorization#e3ef9613 id:int bytes:bytes = auth.Authorization;\nauth.bindTempAuthKey#cdd42a05 perm_auth_key_id:long nonce:long expires_at:int encrypted_message:bytes = Bool;\nauth.checkPassword#d18b4d16 password:InputCheckPasswordSRP = auth.Authorization;\nauth.requestPasswordRecovery#d897bc66 = auth.PasswordRecovery;\nauth.resendCode#3ef1a9bf phone_number:string phone_code_hash:string = auth.SentCode;\nauth.cancelCode#1f040578 phone_number:string phone_code_hash:string = Bool;\nauth.dropTempAuthKeys#8e48a188 except_auth_keys:Vector<long> = Bool;\nauth.exportLoginToken#b1b41517 api_id:int api_hash:string except_ids:Vector<int> = auth.LoginToken;\nauth.importLoginToken#95ac5ce4 token:bytes = auth.LoginToken;\naccount.registerDevice#68976c6f flags:# no_muted:flags.0?true token_type:int token:string app_sandbox:Bool secret:bytes other_uids:Vector<int> = Bool;\naccount.unregisterDevice#3076c4bf token_type:int token:string other_uids:Vector<int> = Bool;\naccount.updateNotifySettings#84be5b93 peer:InputNotifyPeer settings:InputPeerNotifySettings = Bool;\naccount.getNotifySettings#12b3ad31 peer:InputNotifyPeer = PeerNotifySettings;\naccount.updateProfile#78515775 flags:# first_name:flags.0?string last_name:flags.1?string about:flags.2?string = User;\naccount.updateStatus#6628562c offline:Bool = Bool;\naccount.getWallPapers#aabb1763 hash:int = account.WallPapers;\naccount.checkUsername#2714d86c username:string = Bool;\naccount.updateUsername#3e0bdd7c username:string = User;\naccount.getPrivacy#dadbc950 key:InputPrivacyKey = account.PrivacyRules;\naccount.setPrivacy#c9f81ce8 key:InputPrivacyKey rules:Vector<InputPrivacyRule> = account.PrivacyRules;\naccount.getAuthorizations#e320c158 = account.Authorizations;\naccount.resetAuthorization#df77f3bc hash:long = Bool;\naccount.getPassword#548a30f5 = account.Password;\naccount.getPasswordSettings#9cd4eaf9 password:InputCheckPasswordSRP = account.PasswordSettings;\naccount.updatePasswordSettings#a59b102f password:InputCheckPasswordSRP new_settings:account.PasswordInputSettings = Bool;\naccount.sendConfirmPhoneCode#1b3faa88 hash:string settings:CodeSettings = auth.SentCode;\naccount.confirmPhone#5f2178c3 phone_code_hash:string phone_code:string = Bool;\naccount.getTmpPassword#449e0b51 password:InputCheckPasswordSRP period:int = account.TmpPassword;\naccount.sendVerifyPhoneCode#a5a356f9 phone_number:string settings:CodeSettings = auth.SentCode;\naccount.confirmPasswordEmail#8fdf1920 code:string = Bool;\naccount.getContactSignUpNotification#9f07c728 = Bool;\naccount.setContactSignUpNotification#cff43f61 silent:Bool = Bool;\naccount.getNotifyExceptions#53577479 flags:# compare_sound:flags.1?true peer:flags.0?InputNotifyPeer = Updates;\naccount.uploadWallPaper#dd853661 file:InputFile mime_type:string settings:WallPaperSettings = WallPaper;\naccount.setContentSettings#b574b16b flags:# sensitive_enabled:flags.0?true = Bool;\naccount.getContentSettings#8b9b4dae = account.ContentSettings;\nusers.getUsers#d91a548 id:Vector<InputUser> = Vector<User>;\nusers.getFullUser#ca30a5b1 id:InputUser = UserFull;\ncontacts.getContacts#c023849f hash:int = contacts.Contacts;\ncontacts.importContacts#2c800be5 contacts:Vector<InputContact> = contacts.ImportedContacts;\ncontacts.deleteContacts#96a0e00 id:Vector<InputUser> = Updates;\ncontacts.block#68cc1411 id:InputPeer = Bool;\ncontacts.unblock#bea65d50 id:InputPeer = Bool;\ncontacts.getBlocked#f57c350f offset:int limit:int = contacts.Blocked;\ncontacts.search#11f812d8 q:string limit:int = contacts.Found;\ncontacts.resolveUsername#f93ccba3 username:string = contacts.ResolvedPeer;\ncontacts.getTopPeers#d4982db5 flags:# correspondents:flags.0?true bots_pm:flags.1?true bots_inline:flags.2?true phone_calls:flags.3?true forward_users:flags.4?true forward_chats:flags.5?true groups:flags.10?true channels:flags.15?true offset:int limit:int hash:int = contacts.TopPeers;\nmessages.getMessages#63c66506 id:Vector<InputMessage> = messages.Messages;\nmessages.getDialogs#a0ee3b73 flags:# exclude_pinned:flags.0?true folder_id:flags.1?int offset_date:int offset_id:int offset_peer:InputPeer limit:int hash:int = messages.Dialogs;\nmessages.getHistory#dcbb8260 peer:InputPeer offset_id:int offset_date:int add_offset:int limit:int max_id:int min_id:int hash:int = messages.Messages;\nmessages.search#c352eec flags:# peer:InputPeer q:string from_id:flags.0?InputPeer top_msg_id:flags.1?int filter:MessagesFilter min_date:int max_date:int offset_id:int add_offset:int limit:int max_id:int min_id:int hash:int = messages.Messages;\nmessages.readHistory#e306d3a peer:InputPeer max_id:int = messages.AffectedMessages;\nmessages.deleteHistory#1c015b09 flags:# just_clear:flags.0?true revoke:flags.1?true peer:InputPeer max_id:int = messages.AffectedHistory;\nmessages.deleteMessages#e58e95d2 flags:# revoke:flags.0?true id:Vector<int> = messages.AffectedMessages;\nmessages.receivedMessages#5a954c0 max_id:int = Vector<ReceivedNotifyMessage>;\nmessages.setTyping#58943ee2 flags:# peer:InputPeer top_msg_id:flags.0?int action:SendMessageAction = Bool;\nmessages.sendMessage#520c3870 flags:# no_webpage:flags.1?true silent:flags.5?true background:flags.6?true clear_draft:flags.7?true peer:InputPeer reply_to_msg_id:flags.0?int message:string random_id:long reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector<MessageEntity> schedule_date:flags.10?int = Updates;\nmessages.sendMedia#3491eba9 flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true peer:InputPeer reply_to_msg_id:flags.0?int media:InputMedia message:string random_id:long reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector<MessageEntity> schedule_date:flags.10?int = Updates;\nmessages.forwardMessages#d9fee60e flags:# silent:flags.5?true background:flags.6?true with_my_score:flags.8?true from_peer:InputPeer id:Vector<int> random_id:Vector<long> to_peer:InputPeer schedule_date:flags.10?int = Updates;\nmessages.report#8953ab4e peer:InputPeer id:Vector<int> reason:ReportReason message:string = Bool;\nmessages.getChats#3c6aa187 id:Vector<int> = messages.Chats;\nmessages.getFullChat#3b831c66 chat_id:int = messages.ChatFull;\nmessages.editChatTitle#dc452855 chat_id:int title:string = Updates;\nmessages.editChatPhoto#ca4c79d8 chat_id:int photo:InputChatPhoto = Updates;\nmessages.addChatUser#f9a0aa09 chat_id:int user_id:InputUser fwd_limit:int = Updates;\nmessages.deleteChatUser#c534459a flags:# revoke_history:flags.0?true chat_id:int user_id:InputUser = Updates;\nmessages.createChat#9cb126e users:Vector<InputUser> title:string = Updates;\nmessages.getDhConfig#26cf8950 version:int random_length:int = messages.DhConfig;\nmessages.readMessageContents#36a73f77 id:Vector<int> = messages.AffectedMessages;\nmessages.getStickers#43d4f2c emoticon:string hash:int = messages.Stickers;\nmessages.getAllStickers#1c9618b1 hash:int = messages.AllStickers;\nmessages.getWebPagePreview#8b68b0cc flags:# message:string entities:flags.3?Vector<MessageEntity> = MessageMedia;\nmessages.exportChatInvite#14b9bcd7 flags:# legacy_revoke_permanent:flags.2?true peer:InputPeer expire_date:flags.0?int usage_limit:flags.1?int = ExportedChatInvite;\nmessages.checkChatInvite#3eadb1bb hash:string = ChatInvite;\nmessages.importChatInvite#6c50051c hash:string = Updates;\nmessages.getStickerSet#2619a90e stickerset:InputStickerSet = messages.StickerSet;\nmessages.installStickerSet#c78fe460 stickerset:InputStickerSet archived:Bool = messages.StickerSetInstallResult;\nmessages.uninstallStickerSet#f96e55de stickerset:InputStickerSet = Bool;\nmessages.startBot#e6df7378 bot:InputUser peer:InputPeer random_id:long start_param:string = Updates;\nmessages.migrateChat#15a3b8e3 chat_id:int = Updates;\nmessages.searchGlobal#4bc6589a flags:# folder_id:flags.0?int q:string filter:MessagesFilter min_date:int max_date:int offset_rate:int offset_peer:InputPeer offset_id:int limit:int = messages.Messages;\nmessages.getDocumentByHash#338e2464 sha256:bytes size:int mime_type:string = Document;\nmessages.getSavedGifs#83bf3d52 hash:int = messages.SavedGifs;\nmessages.getInlineBotResults#514e999d flags:# bot:InputUser peer:InputPeer geo_point:flags.0?InputGeoPoint query:string offset:string = messages.BotResults;\nmessages.sendInlineBotResult#220815b0 flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true hide_via:flags.11?true peer:InputPeer reply_to_msg_id:flags.0?int random_id:long query_id:long id:string schedule_date:flags.10?int = Updates;\nmessages.editMessage#48f71778 flags:# no_webpage:flags.1?true peer:InputPeer id:int message:flags.11?string media:flags.14?InputMedia reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector<MessageEntity> schedule_date:flags.15?int = Updates;\nmessages.getBotCallbackAnswer#9342ca07 flags:# game:flags.1?true peer:InputPeer msg_id:int data:flags.0?bytes password:flags.2?InputCheckPasswordSRP = messages.BotCallbackAnswer;\nmessages.getPeerDialogs#e470bcfd peers:Vector<InputDialogPeer> = messages.PeerDialogs;\nmessages.saveDraft#bc39e14b flags:# no_webpage:flags.1?true reply_to_msg_id:flags.0?int peer:InputPeer message:string entities:flags.3?Vector<MessageEntity> = Bool;\nmessages.getFeaturedStickers#2dacca4f hash:int = messages.FeaturedStickers;\nmessages.readFeaturedStickers#5b118126 id:Vector<long> = Bool;\nmessages.getRecentStickers#5ea192c9 flags:# attached:flags.0?true hash:int = messages.RecentStickers;\nmessages.getWebPage#32ca8f91 url:string hash:int = WebPage;\nmessages.toggleDialogPin#a731e257 flags:# pinned:flags.0?true peer:InputDialogPeer = Bool;\nmessages.getPinnedDialogs#d6b94df2 folder_id:int = messages.PeerDialogs;\nmessages.uploadMedia#519bc2b1 peer:InputPeer media:InputMedia = MessageMedia;\nmessages.getFavedStickers#21ce0b0e hash:int = messages.FavedStickers;\nmessages.faveSticker#b9ffc55b id:InputDocument unfave:Bool = Bool;\nmessages.sendMultiMedia#cc0110cb flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true peer:InputPeer reply_to_msg_id:flags.0?int multi_media:Vector<InputSingleMedia> schedule_date:flags.10?int = Updates;\nmessages.searchStickerSets#c2b7d08b flags:# exclude_featured:flags.0?true q:string hash:int = messages.FoundStickerSets;\nmessages.markDialogUnread#c286d98f flags:# unread:flags.0?true peer:InputDialogPeer = Bool;\nmessages.updatePinnedMessage#d2aaf7ec flags:# silent:flags.0?true unpin:flags.1?true pm_oneside:flags.2?true peer:InputPeer id:int = Updates;\nmessages.sendVote#10ea6184 peer:InputPeer msg_id:int options:Vector<bytes> = Updates;\nmessages.getOnlines#6e2be050 peer:InputPeer = ChatOnlines;\nmessages.editChatAbout#def60797 peer:InputPeer about:string = Bool;\nmessages.editChatDefaultBannedRights#a5866b41 peer:InputPeer banned_rights:ChatBannedRights = Updates;\nmessages.getEmojiKeywordsDifference#1508b6af lang_code:string from_version:int = EmojiKeywordsDifference;\nmessages.getScheduledHistory#e2c2685b peer:InputPeer hash:int = messages.Messages;\nmessages.sendScheduledMessages#bd38850a peer:InputPeer id:Vector<int> = Updates;\nmessages.deleteScheduledMessages#59ae2b16 peer:InputPeer id:Vector<int> = Updates;\nmessages.getPollVotes#b86e380e flags:# peer:InputPeer id:int option:flags.0?bytes offset:flags.1?string limit:int = messages.VotesList;\nmessages.getDialogFilters#f19ed96d = Vector<DialogFilter>;\nmessages.getSuggestedDialogFilters#a29cd42c = Vector<DialogFilterSuggested>;\nmessages.updateDialogFilter#1ad4a04a flags:# id:int filter:flags.0?DialogFilter = Bool;\nmessages.getReplies#24b581ba peer:InputPeer msg_id:int offset_id:int offset_date:int add_offset:int limit:int max_id:int min_id:int hash:int = messages.Messages;\nmessages.getDiscussionMessage#446972fd peer:InputPeer msg_id:int = messages.DiscussionMessage;\nmessages.readDiscussion#f731a9f4 peer:InputPeer msg_id:int read_max_id:int = Bool;\nmessages.unpinAllMessages#f025bc8b peer:InputPeer = messages.AffectedHistory;\nmessages.deleteChat#83247d11 chat_id:int = Bool;\nupdates.getState#edd4882a = updates.State;\nupdates.getDifference#25939651 flags:# pts:int pts_total_limit:flags.0?int date:int qts:int = updates.Difference;\nupdates.getChannelDifference#3173d78 flags:# force:flags.0?true channel:InputChannel filter:ChannelMessagesFilter pts:int limit:int = updates.ChannelDifference;\nphotos.uploadProfilePhoto#89f30f69 flags:# file:flags.0?InputFile video:flags.1?InputFile video_start_ts:flags.2?double = photos.Photo;\nphotos.getUserPhotos#91cd32a8 user_id:InputUser offset:int max_id:long limit:int = photos.Photos;\nupload.saveFilePart#b304a621 file_id:long file_part:int bytes:bytes = Bool;\nupload.getFile#b15a9afc flags:# precise:flags.0?true cdn_supported:flags.1?true location:InputFileLocation offset:int limit:int = upload.File;\nupload.saveBigFilePart#de7b673d file_id:long file_part:int file_total_parts:int bytes:bytes = Bool;\nupload.getWebFile#24e6818d location:InputWebFileLocation offset:int limit:int = upload.WebFile;\nhelp.getConfig#c4f9186b = Config;\nhelp.getNearestDc#1fb33026 = NearestDc;\nhelp.getSupport#9cdf08cd = help.Support;\nhelp.acceptTermsOfService#ee72f79a id:DataJSON = Bool;\nchannels.readHistory#cc104937 channel:InputChannel max_id:int = Bool;\nchannels.deleteMessages#84c1fd4e channel:InputChannel id:Vector<int> = messages.AffectedMessages;\nchannels.getMessages#ad8c9a23 channel:InputChannel id:Vector<InputMessage> = messages.Messages;\nchannels.getParticipants#123e05e9 channel:InputChannel filter:ChannelParticipantsFilter offset:int limit:int hash:int = channels.ChannelParticipants;\nchannels.getParticipant#a0ab6cc6 channel:InputChannel participant:InputPeer = channels.ChannelParticipant;\nchannels.getChannels#a7f6bbb id:Vector<InputChannel> = messages.Chats;\nchannels.getFullChannel#8736a09 channel:InputChannel = messages.ChatFull;\nchannels.createChannel#3d5fb10f flags:# broadcast:flags.0?true megagroup:flags.1?true for_import:flags.3?true title:string about:string geo_point:flags.2?InputGeoPoint address:flags.2?string = Updates;\nchannels.editAdmin#d33c8902 channel:InputChannel user_id:InputUser admin_rights:ChatAdminRights rank:string = Updates;\nchannels.editTitle#566decd0 channel:InputChannel title:string = Updates;\nchannels.editPhoto#f12e57c9 channel:InputChannel photo:InputChatPhoto = Updates;\nchannels.checkUsername#10e6bd2c channel:InputChannel username:string = Bool;\nchannels.updateUsername#3514b3de channel:InputChannel username:string = Bool;\nchannels.joinChannel#24b524c5 channel:InputChannel = Updates;\nchannels.leaveChannel#f836aa95 channel:InputChannel = Updates;\nchannels.inviteToChannel#199f3a6c channel:InputChannel users:Vector<InputUser> = Updates;\nchannels.deleteChannel#c0111fe3 channel:InputChannel = Updates;\nchannels.toggleSignatures#1f69b606 channel:InputChannel enabled:Bool = Updates;\nchannels.editBanned#96e6cd81 channel:InputChannel participant:InputPeer banned_rights:ChatBannedRights = Updates;\nchannels.readMessageContents#eab5dc38 channel:InputChannel id:Vector<int> = Bool;\nchannels.togglePreHistoryHidden#eabbb94c channel:InputChannel enabled:Bool = Updates;\nchannels.getGroupsForDiscussion#f5dad378 = messages.Chats;\nchannels.setDiscussionGroup#40582bb2 broadcast:InputChannel group:InputChannel = Bool;\npayments.getPaymentForm#8a333c8d flags:# peer:InputPeer msg_id:int theme_params:flags.0?DataJSON = payments.PaymentForm;\npayments.getPaymentReceipt#2478d1cc peer:InputPeer msg_id:int = payments.PaymentReceipt;\npayments.validateRequestedInfo#db103170 flags:# save:flags.0?true peer:InputPeer msg_id:int info:PaymentRequestedInfo = payments.ValidatedRequestedInfo;\npayments.sendPaymentForm#30c3bc9d flags:# form_id:long peer:InputPeer msg_id:int requested_info_id:flags.0?string shipping_option_id:flags.1?string credentials:InputPaymentCredentials tip_amount:flags.2?long = payments.PaymentResult;\npayments.getSavedInfo#227d824b = payments.SavedInfo;\nlangpack.getLangPack#f2f2330a lang_pack:string lang_code:string = LangPackDifference;\nlangpack.getStrings#efea3803 lang_pack:string lang_code:string keys:Vector<string> = Vector<LangPackString>;\nlangpack.getLanguages#42c6978f lang_pack:string = Vector<LangPackLanguage>;\nfolders.editPeerFolders#6847d0ab folder_peers:Vector<InputFolderPeer> = Updates;\n`;","const { inflate } = require('pako/dist/pako_inflate');\nconst { serializeBytes } = require('../index');\n\n// CONTEST const { deflate } = require('pako/dist/pako_deflate')\n\nclass GZIPPacked {\n static CONSTRUCTOR_ID = 0x3072cfa1;\n\n static classType = 'constructor';\n\n constructor(data) {\n this.data = data;\n this.CONSTRUCTOR_ID = 0x3072cfa1;\n this.classType = 'constructor';\n }\n\n static async gzipIfSmaller(contentRelated, data) {\n if (contentRelated && data.length > 512) {\n const gzipped = await (new GZIPPacked(data)).toBytes();\n if (gzipped.length < data.length) {\n return gzipped;\n }\n }\n return data;\n }\n\n static gzip(input) {\n return Buffer.from(input);\n // TODO this usually makes it faster for large requests\n // return Buffer.from(deflate(input, { level: 9, gzip: true }))\n }\n\n static ungzip(input) {\n return Buffer.from(inflate(input));\n }\n\n static read(reader) {\n const constructor = reader.readInt(false);\n if (constructor !== GZIPPacked.CONSTRUCTOR_ID) {\n throw new Error('not equal');\n }\n return GZIPPacked.gzip(reader.tgReadBytes());\n }\n\n static async fromReader(reader) {\n return new GZIPPacked(await GZIPPacked.ungzip(reader.tgReadBytes()));\n }\n\n async toBytes() {\n const g = Buffer.alloc(4);\n g.writeUInt32LE(GZIPPacked.CONSTRUCTOR_ID, 0);\n return Buffer.concat([\n g,\n serializeBytes(await GZIPPacked.gzip(this.data)),\n ]);\n }\n}\n\nmodule.exports = GZIPPacked;\n","const TLMessage = require('./TLMessage');\n\nclass MessageContainer {\n static CONSTRUCTOR_ID = 0x73f1f8dc;\n\n static classType = 'constructor';\n\n // Maximum size in bytes for the inner payload of the container.\n // Telegram will close the connection if the payload is bigger.\n // The overhead of the container itself is subtracted.\n static MAXIMUM_SIZE = 1044456 - 8;\n\n // Maximum amount of messages that can't be sent inside a single\n // container, inclusive. Beyond this limit Telegram will respond\n // with BAD_MESSAGE 64 (invalid container).\n //\n // This limit is not 100% accurate and may in some cases be higher.\n // However, sending up to 100 requests at once in a single container\n // is a reasonable conservative value, since it could also depend on\n // other factors like size per request, but we cannot know this.\n static MAXIMUM_LENGTH = 100;\n\n constructor(messages) {\n this.CONSTRUCTOR_ID = 0x73f1f8dc;\n this.messages = messages;\n this.classType = 'constructor';\n }\n\n static fromReader(reader) {\n const messages = [];\n const length = reader.readInt();\n for (let x = 0; x < length; x++) {\n const msgId = reader.readLong();\n const seqNo = reader.readInt();\n const containerLength = reader.readInt();\n const before = reader.tellPosition();\n const obj = reader.tgReadObject();\n reader.setPosition(before + containerLength);\n const tlMessage = new TLMessage(msgId, seqNo, obj);\n messages.push(tlMessage);\n }\n return new MessageContainer(messages);\n }\n}\n\nmodule.exports = MessageContainer;\n","const { RpcError } = require('../index').constructors;\nconst GZIPPacked = require('./GZIPPacked');\n\nclass RPCResult {\n static CONSTRUCTOR_ID = 0xf35c6d01;\n\n static classType = 'constructor';\n\n constructor(reqMsgId, body, error) {\n this.CONSTRUCTOR_ID = 0xf35c6d01;\n this.reqMsgId = reqMsgId;\n this.body = body;\n this.error = error;\n this.classType = 'constructor';\n }\n\n static async fromReader(reader) {\n const msgId = reader.readLong();\n const innerCode = reader.readInt(false);\n if (innerCode === RpcError.CONSTRUCTOR_ID) {\n return new RPCResult(msgId, undefined, RpcError.fromReader(reader));\n }\n if (innerCode === GZIPPacked.CONSTRUCTOR_ID) {\n return new RPCResult(msgId, (await GZIPPacked.fromReader(reader)).data);\n }\n reader.seek(-4);\n // This reader.read() will read more than necessary, but it's okay.\n // We could make use of MessageContainer's length here, but since\n // it's not necessary we don't need to care about it.\n return new RPCResult(msgId, reader.read(), undefined);\n }\n}\n\nmodule.exports = RPCResult;\n","class TLMessage {\n static SIZE_OVERHEAD = 12;\n\n static classType = 'constructor';\n\n constructor(msgId, seqNo, obj) {\n this.msgId = msgId;\n this.seqNo = seqNo;\n this.obj = obj;\n this.classType = 'constructor';\n }\n}\n\nmodule.exports = TLMessage;\n","const TLMessage = require('./TLMessage');\nconst RPCResult = require('./RPCResult');\nconst MessageContainer = require('./MessageContainer');\nconst GZIPPacked = require('./GZIPPacked');\n\nconst coreObjects = {\n [RPCResult.CONSTRUCTOR_ID]: RPCResult,\n [GZIPPacked.CONSTRUCTOR_ID]: GZIPPacked,\n [MessageContainer.CONSTRUCTOR_ID]: MessageContainer,\n};\n\nmodule.exports = {\n TLMessage,\n RPCResult,\n MessageContainer,\n GZIPPacked,\n coreObjects,\n};\n","const snakeToCamelCase = (name) => {\n const result = name.replace(/(?:^|_)([a-z])/g, (_, g) => g.toUpperCase());\n return result.replace(/_/g, '');\n};\nconst variableSnakeToCamelCase = (str) => str.replace(\n /([-_][a-z])/g,\n (group) => group.toUpperCase()\n .replace('-', '')\n .replace('_', ''),\n);\n\nconst CORE_TYPES = new Set([\n 0xbc799737, // boolFalse#bc799737 = Bool;\n 0x997275b5, // boolTrue#997275b5 = Bool;\n 0x3fedd339, // true#3fedd339 = True;\n 0xc4b9f9bb, // error#c4b9f9bb code:int text:string = Error;\n 0x56730bcc, // null#56730bcc = Null;\n]);\nconst AUTH_KEY_TYPES = new Set([\n 0x05162463, // resPQ,\n 0x83c95aec, // p_q_inner_data\n 0xa9f55f95, // p_q_inner_data_dc\n 0x3c6a84d4, // p_q_inner_data_temp\n 0x56fddf88, // p_q_inner_data_temp_dc\n 0xd0e8075c, // server_DH_params_ok\n 0xb5890dba, // server_DH_inner_data\n 0x6643b654, // client_DH_inner_data\n 0xd712e4be, // req_DH_params\n 0xf5045f1f, // set_client_DH_params\n 0x3072cfa1, // gzip_packed\n]);\n\n// This is copy-pasted from `gramjs/Helpers.js` to not depend on TypeScript modules\nfunction makeCRCTable() {\n let c;\n const crcTable = [];\n for (let n = 0; n < 256; n++) {\n c = n;\n for (let k = 0; k < 8; k++) {\n c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));\n }\n crcTable[n] = c;\n }\n return crcTable;\n}\n\nlet crcTable;\n\nfunction crc32(buf) {\n if (!crcTable) {\n crcTable = makeCRCTable();\n }\n if (!Buffer.isBuffer(buf)) {\n buf = Buffer.from(buf);\n }\n let crc = -1;\n\n for (let index = 0; index < buf.length; index++) {\n const byte = buf[index];\n crc = crcTable[(crc ^ byte) & 0xff] ^ (crc >>> 8);\n }\n return (crc ^ (-1)) >>> 0;\n}\n\nconst findAll = (regex, str, matches = []) => {\n if (!regex.flags.includes('g')) {\n regex = new RegExp(regex.source, 'g');\n }\n\n const res = regex.exec(str);\n\n if (res) {\n matches.push(res.slice(1));\n findAll(regex, str, matches);\n }\n\n return matches;\n};\n\nconst fromLine = (line, isFunction) => {\n const match = line.match(/([\\w.]+)(?:#([0-9a-fA-F]+))?(?:\\s{?\\w+:[\\w\\d<>#.?!]+}?)*\\s=\\s([\\w\\d<>#.?]+);$/);\n if (!match) {\n // Probably \"vector#1cb5c415 {t:Type} # [ t ] = Vector t;\"\n throw new Error(`Cannot parse TLObject ${line}`);\n }\n\n const argsMatch = findAll(/({)?(\\w+):([\\w\\d<>#.?!]+)}?/, line);\n const currentConfig = {\n name: match[1],\n constructorId: parseInt(match[2], 16),\n argsConfig: {},\n subclassOfId: crc32(match[3]),\n result: match[3],\n isFunction,\n namespace: undefined,\n };\n if (!currentConfig.constructorId) {\n const hexId = '';\n let args;\n\n if (Object.values(currentConfig.argsConfig).length) {\n args = ` ${Object.keys(currentConfig.argsConfig)\n .map((arg) => arg.toString())\n .join(' ')}`;\n } else {\n args = '';\n }\n\n const representation = `${currentConfig.name}${hexId}${args} = ${currentConfig.result}`\n .replace(/(:|\\?)bytes /g, '$1string ')\n .replace(/</g, ' ')\n .replace(/>|{|}/g, '')\n .replace(/ \\w+:flags\\.\\d+\\?true/g, '');\n\n if (currentConfig.name === 'inputMediaInvoice') {\n // eslint-disable-next-line no-empty\n if (currentConfig.name === 'inputMediaInvoice') {\n }\n }\n\n currentConfig.constructorId = crc32(Buffer.from(representation, 'utf8'));\n }\n for (const [brace, name, argType] of argsMatch) {\n if (brace === undefined) {\n currentConfig.argsConfig[variableSnakeToCamelCase(name)] = buildArgConfig(name, argType);\n }\n }\n if (currentConfig.name.includes('.')) {\n [currentConfig.namespace, currentConfig.name] = currentConfig.name.split(/\\.(.+)/);\n }\n currentConfig.name = snakeToCamelCase(currentConfig.name);\n /*\n for (const arg in currentConfig.argsConfig){\n if (currentConfig.argsConfig.hasOwnProperty(arg)){\n if (currentConfig.argsConfig[arg].flagIndicator){\n delete currentConfig.argsConfig[arg]\n }\n }\n } */\n return currentConfig;\n};\n\nfunction buildArgConfig(name, argType) {\n name = name === 'self' ? 'is_self' : name;\n // Default values\n const currentConfig = {\n isVector: false,\n isFlag: false,\n skipConstructorId: false,\n flagIndex: -1,\n flagIndicator: true,\n type: undefined,\n useVectorId: undefined,\n };\n\n // The type can be an indicator that other arguments will be flags\n if (argType !== '#') {\n currentConfig.flagIndicator = false;\n // Strip the exclamation mark always to have only the name\n currentConfig.type = argType.replace(/^!+/, '');\n\n // The type may be a flag (flags.IDX?REAL_TYPE)\n // Note that 'flags' is NOT the flags name; this\n // is determined by a previous argument\n // However, we assume that the argument will always be called 'flags'\n // @ts-ignore\n const flagMatch = currentConfig.type.match(/flags.(\\d+)\\?([\\w<>.]+)/);\n\n if (flagMatch) {\n currentConfig.isFlag = true;\n currentConfig.flagIndex = Number(flagMatch[1]);\n // Update the type to match the exact type, not the \"flagged\" one\n [, , currentConfig.type] = flagMatch;\n }\n\n // Then check if the type is a Vector<REAL_TYPE>\n // @ts-ignore\n const vectorMatch = currentConfig.type.match(/[Vv]ector<([\\w\\d.]+)>/);\n\n if (vectorMatch) {\n currentConfig.isVector = true;\n\n // If the type's first letter is not uppercase, then\n // it is a constructor and we use (read/write) its ID.\n // @ts-ignore\n currentConfig.useVectorId = currentConfig.type.charAt(0) === 'V';\n\n // Update the type to match the one inside the vector\n [, currentConfig.type] = vectorMatch;\n }\n\n // See use_vector_id. An example of such case is ipPort in\n // help.configSpecial\n // @ts-ignore\n if (/^[a-z]$/.test(currentConfig.type.split('.')\n .pop()\n .charAt(0))\n ) {\n currentConfig.skipConstructorId = true;\n }\n\n // The name may contain \"date\" in it, if this is the case and\n // the type is \"int\", we can safely assume that this should be\n // treated as a \"date\" object. Note that this is not a valid\n // Telegram object, but it's easier to work with\n // if (\n // this.type === 'int' &&\n // (/(\\b|_)([dr]ate|until|since)(\\b|_)/.test(name) ||\n // ['expires', 'expires_at', 'was_online'].includes(name))\n // ) {\n // this.type = 'date';\n // }\n }\n return currentConfig;\n}\n\n\nfunction* parseTl(content, layer, methods = [], ignoreIds = CORE_TYPES) {\n (methods || []).reduce((o, m) => ({\n ...o,\n [m.name]: m,\n }), {});\n const objAll = [];\n const objByName = {};\n const objByType = {};\n\n const file = content;\n\n let isFunction = false;\n\n for (let line of file.split('\\n')) {\n const commentIndex = line.indexOf('//');\n\n if (commentIndex !== -1) {\n line = line.slice(0, commentIndex);\n }\n\n line = line.trim();\n\n if (!line) {\n continue;\n }\n\n const match = line.match(/---(\\w+)---/);\n\n if (match) {\n const [, followingTypes] = match;\n isFunction = followingTypes === 'functions';\n continue;\n }\n\n try {\n const result = fromLine(line, isFunction);\n\n if (ignoreIds.has(result.constructorId)) {\n continue;\n }\n\n objAll.push(result);\n\n if (!result.isFunction) {\n if (!objByType[result.result]) {\n objByType[result.result] = [];\n }\n\n objByName[result.name] = result;\n objByType[result.result].push(result);\n }\n } catch (e) {\n if (!e.toString()\n .includes('vector#1cb5c415')) {\n throw e;\n }\n }\n }\n\n // Once all objects have been parsed, replace the\n // string type from the arguments with references\n for (const obj of objAll) {\n // console.log(obj)\n if (AUTH_KEY_TYPES.has(obj.constructorId)) {\n for (const arg in obj.argsConfig) {\n if (obj.argsConfig[arg].type === 'string') {\n obj.argsConfig[arg].type = 'bytes';\n }\n }\n }\n }\n\n for (const obj of objAll) {\n yield obj;\n }\n}\n\nfunction serializeBytes(data) {\n if (!(data instanceof Buffer)) {\n if (typeof data === 'string') {\n data = Buffer.from(data);\n } else {\n throw Error(`Bytes or str expected, not ${data.constructor.name}`);\n }\n }\n const r = [];\n let padding;\n if (data.length < 254) {\n padding = (data.length + 1) % 4;\n if (padding !== 0) {\n padding = 4 - padding;\n }\n r.push(Buffer.from([data.length]));\n r.push(data);\n } else {\n padding = data.length % 4;\n if (padding !== 0) {\n padding = 4 - padding;\n }\n r.push(Buffer.from([254, data.length % 256, (data.length >> 8) % 256, (data.length >> 16) % 256]));\n r.push(data);\n }\n r.push(Buffer.alloc(padding)\n .fill(0));\n\n return Buffer.concat(r);\n}\n\nfunction serializeDate(dt) {\n if (!dt) {\n return Buffer.alloc(4)\n .fill(0);\n }\n if (dt instanceof Date) {\n dt = Math.floor((Date.now() - dt.getTime()) / 1000);\n }\n if (typeof dt === 'number') {\n const t = Buffer.alloc(4);\n t.writeInt32LE(dt, 0);\n return t;\n }\n throw Error(`Cannot interpret \"${dt}\" as a date`);\n}\n\nmodule.exports = {\n findAll,\n parseTl,\n buildArgConfig,\n fromLine,\n CORE_TYPES,\n serializeDate,\n serializeBytes,\n snakeToCamelCase,\n variableSnakeToCamelCase,\n};\n","const api = require('./api');\nconst {\n serializeBytes,\n serializeDate,\n} = require('./generationHelpers');\n\nmodule.exports = {\n // TODO Refactor internal usages to always use `api`.\n constructors: api,\n requests: api,\n serializeBytes,\n serializeDate,\n};\n","module.exports = `resPQ#05162463 nonce:int128 server_nonce:int128 pq:string server_public_key_fingerprints:Vector<long> = ResPQ;\np_q_inner_data#83c95aec pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 = P_Q_inner_data;\nserver_DH_params_fail#79cb045d nonce:int128 server_nonce:int128 new_nonce_hash:int128 = Server_DH_Params;\nserver_DH_params_ok#d0e8075c nonce:int128 server_nonce:int128 encrypted_answer:string = Server_DH_Params;\nserver_DH_inner_data#b5890dba nonce:int128 server_nonce:int128 g:int dh_prime:string g_a:string server_time:int = Server_DH_inner_data;\nclient_DH_inner_data#6643b654 nonce:int128 server_nonce:int128 retry_id:long g_b:string = Client_DH_Inner_Data;\ndh_gen_ok#3bcbf734 nonce:int128 server_nonce:int128 new_nonce_hash1:int128 = Set_client_DH_params_answer;\ndh_gen_retry#46dc1fb9 nonce:int128 server_nonce:int128 new_nonce_hash2:int128 = Set_client_DH_params_answer;\ndh_gen_fail#a69dae02 nonce:int128 server_nonce:int128 new_nonce_hash3:int128 = Set_client_DH_params_answer;\ndestroy_auth_key_ok#f660e1d4 = DestroyAuthKeyRes;\ndestroy_auth_key_none#0a9f2259 = DestroyAuthKeyRes;\ndestroy_auth_key_fail#ea109b13 = DestroyAuthKeyRes;\n---functions---\nreq_pq#60469778 nonce:int128 = ResPQ;\nreq_pq_multi#be7e8ef1 nonce:int128 = ResPQ;\nreq_pq_multi_new#51b410fd nonce:int128 = ResPQ;\nreq_DH_params#d712e4be nonce:int128 server_nonce:int128 p:string q:string public_key_fingerprint:long encrypted_data:string = Server_DH_Params;\nset_client_DH_params#f5045f1f nonce:int128 server_nonce:int128 encrypted_data:string = Set_client_DH_params_answer;\ndestroy_auth_key#d1435160 = DestroyAuthKeyRes;\n---types---\nmsgs_ack#62d6b459 msg_ids:Vector<long> = MsgsAck;\nbad_msg_notification#a7eff811 bad_msg_id:long bad_msg_seqno:int error_code:int = BadMsgNotification;\nbad_server_salt#edab447b bad_msg_id:long bad_msg_seqno:int error_code:int new_server_salt:long = BadMsgNotification;\nmsgs_state_req#da69fb52 msg_ids:Vector<long> = MsgsStateReq;\nmsgs_state_info#04deb57d req_msg_id:long info:string = MsgsStateInfo;\nmsgs_all_info#8cc0d131 msg_ids:Vector<long> info:string = MsgsAllInfo;\nmsg_detailed_info#276d3ec6 msg_id:long answer_msg_id:long bytes:int status:int = MsgDetailedInfo;\nmsg_new_detailed_info#809db6df answer_msg_id:long bytes:int status:int = MsgDetailedInfo;\nmsg_resend_req#7d861a08 msg_ids:Vector<long> = MsgResendReq;\nrpc_error#2144ca19 error_code:int error_message:string = RpcError;\nfuture_salt#0949d9dc valid_since:int valid_until:int salt:long = FutureSalt;\nfuture_salts#ae500895 req_msg_id:long now:int salts:vector<future_salt> = FutureSalts;\npong#347773c5 msg_id:long ping_id:long = Pong;\ndestroy_session_ok#e22045fc session_id:long = DestroySessionRes;\ndestroy_session_none#62d350c9 session_id:long = DestroySessionRes;\nnew_session_created#9ec20908 first_msg_id:long unique_id:long server_salt:long = NewSession;\n---functions---\nping#7abe77ec ping_id:long = Pong;\nping_delay_disconnect#f3427b8c ping_id:long disconnect_delay:int = Pong;`;","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\tid: moduleId,\n\t\tloaded: false,\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Flag the module as loaded\n\tmodule.loaded = true;\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n// expose the modules object (__webpack_modules__)\n__webpack_require__.m = __webpack_modules__;\n\n// the startup function\n__webpack_require__.x = () => {\n\t// Load entry module and return exports\n\t// This entry module depends on other loaded chunks and execution need to be delayed\n\tvar __webpack_exports__ = __webpack_require__.O(undefined, [592], () => (__webpack_require__(6514)))\n\t__webpack_exports__ = __webpack_require__.O(__webpack_exports__);\n\treturn __webpack_exports__;\n};\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.f = {};\n// This file contains only the entry chunk.\n// The chunk loading function for additional chunks\n__webpack_require__.e = (chunkId) => {\n\treturn Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => {\n\t\t__webpack_require__.f[key](chunkId, promises);\n\t\treturn promises;\n\t}, []));\n};","// This function allow to reference async chunks and sibling chunks for the entrypoint\n__webpack_require__.u = (chunkId) => {\n\t// return url for filenames based on template\n\treturn \"\" + chunkId + \".\" + \"d7ca037ed9b7d1c6792a\" + \".js\";\n};","// This function allow to reference all chunks\n__webpack_require__.miniCssF = (chunkId) => {\n\t// return url for filenames based on template\n\treturn undefined;\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","__webpack_require__.nmd = (module) => {\n\tmodule.paths = [];\n\tif (!module.children) module.children = [];\n\treturn module;\n};","var scriptUrl;\nif (__webpack_require__.g.importScripts) scriptUrl = __webpack_require__.g.location + \"\";\nvar document = __webpack_require__.g.document;\nif (!scriptUrl && document) {\n\tif (document.currentScript)\n\t\tscriptUrl = document.currentScript.src\n\tif (!scriptUrl) {\n\t\tvar scripts = document.getElementsByTagName(\"script\");\n\t\tif(scripts.length) scriptUrl = scripts[scripts.length - 1].src\n\t}\n}\n// When supporting browsers where an automatic publicPath is not supported you must specify an output.publicPath manually via configuration\n// or pass an empty string (\"\") and set the __webpack_public_path__ variable from your code to use your own logic.\nif (!scriptUrl) throw new Error(\"Automatic publicPath is not supported in this browser\");\nscriptUrl = scriptUrl.replace(/#.*$/, \"\").replace(/\\?.*$/, \"\").replace(/\\/[^\\/]+$/, \"/\");\n__webpack_require__.p = scriptUrl;","// no baseURI\n\n// object to store loaded chunks\n// \"1\" means \"already loaded\"\nvar installedChunks = {\n\t514: 1\n};\n\n// importScripts chunk loading\nvar installChunk = (data) => {\n\tvar [chunkIds, moreModules, runtime] = data;\n\tfor(var moduleId in moreModules) {\n\t\tif(__webpack_require__.o(moreModules, moduleId)) {\n\t\t\t__webpack_require__.m[moduleId] = moreModules[moduleId];\n\t\t}\n\t}\n\tif(runtime) runtime(__webpack_require__);\n\twhile(chunkIds.length)\n\t\tinstalledChunks[chunkIds.pop()] = 1;\n\tparentChunkLoadingFunction(data);\n};\n__webpack_require__.f.i = (chunkId, promises) => {\n\t// \"1\" is the signal for \"already loaded\"\n\tif(!installedChunks[chunkId]) {\n\t\tif(true) { // all chunks have JS\n\t\t\timportScripts(__webpack_require__.p + __webpack_require__.u(chunkId));\n\t\t}\n\t}\n};\n\nvar chunkLoadingGlobal = self[\"webpackChunktelegram_t\"] = self[\"webpackChunktelegram_t\"] || [];\nvar parentChunkLoadingFunction = chunkLoadingGlobal.push.bind(chunkLoadingGlobal);\nchunkLoadingGlobal.push = installChunk;\n\n// no HMR\n\n// no HMR manifest","// run startup\nvar __webpack_exports__ = __webpack_require__.x();\n"],"names":["deferred","next","API_UPDATE_THROTTLE","window","innerHeight","Math","round","API_THROTTLE_RESET_UPDATES","Set","buildCollectionByKey","collection","key","reduce","byKey","member","pick","object","keys","result","isPeerUser","peer","hasOwnProperty","isPeerChat","bytesToDataUri","bytes","shouldOmitPrefix","mimeType","btoa","String","fromCharCode","omitVirtualClassFields","instance","flags","CONSTRUCTOR_ID","SUBCLASS_OF_ID","className","classType","rest","getServerTime","serverTimeOffset","floor","Date","now","buildApiChatFieldsFromPeerEntity","peerEntity","isSupport","isMin","Boolean","min","accessHash","avatarHash","photo","buildAvatarHash","isSignaturesShown","signatures","hasPrivateLink","hasLink","GramJs","username","isVerified","verified","isCallActive","callActive","isCallNotEmpty","callNotEmpty","participantsCount","membersCount","joinDate","date","buildApiChatPermissions","isCreator","creator","buildApiChatRestrictions","buildApiChatMigrationInfo","buildApiChatFromDialog","dialog","folderId","unreadMark","unreadCount","unreadMentionsCount","notifySettings","silent","muteUntil","readOutboxMaxId","readInboxMaxId","draft","isMuted","id","getApiChatIdFromMtpPeer","type","getApiChatTypeFromPeerEntity","title","getApiChatTitleFromMtpPeer","lastReadOutboxMessageId","lastReadInboxMessageId","hasUnreadMark","draftDate","adminRights","currentUserBannedRights","bannedRights","undefined","defaultBannedRights","isRestricted","restrictions","restrictionReason","restricted","restrictionReasons","targetReason","find","platform","buildApiChatRestrictionReason","Object","assign","isNotJoined","left","kicked","migratedTo","chatId","toString","buildApiChatFromPreview","preview","withForbidden","getUserName","userId","channelId","getApiChatIdFromInputMtpPeer","isInputPeerUser","isInputPeerChat","isInputPeerChannel","megagroup","getPeerKey","user","firstName","lastName","photoId","buildChatMember","inviterId","joinedDate","kickedByUserId","kickedBy","promotedByUserId","promotedBy","customTitle","rank","isAdmin","isOwner","buildChatMembers","participants","map","filter","buildChatTypingStatus","update","action","fromId","timestamp","buildApiChatFolder","channels","broadcasts","pinnedChatIds","pinnedPeers","includedChatIds","includePeers","excludedChatIds","excludePeers","buildApiChatFolderFromSuggested","description","buildApiChatBotCommands","botInfos","botCommands","botInfo","concat","commands","mtpCommand","botId","pathBytesToSvg","width","height","replace","path","len","length","i","num","buildPath","DEFAULT_THUMB_SIZE","w","h","buildApiThumbnailFromStripped","sizes","thumb","s","realSizes","dataUri","strippedPhotoToJpg","buildApiPhoto","buildApiPhotoSize","thumbnail","photoSize","localMessages","chats","users","messages","documents","stickerSets","photos","webDocuments","ANIMATED_STICKER_MIME_TYPE","buildStickerFromDocument","document","stickerAttribute","attributes","attr","fileAttribute","sizeAttribute","stickerSetInfo","stickerset","emoji","alt","isAnimated","cachedThumb","thumbs","pathThumb","buildApiThumbnailFromCached","buildApiThumbnailFromPath","stickerSetId","stickerSetAccessHash","buildStickerSet","set","archived","animated","installedDate","count","hash","shortName","hasThumbnail","buildStickerSetCovered","coveredStickerSet","stickerSet","stickerSetCovers","covers","cover","forEach","coverSticker","push","localDb","interpolateArray","data","fitCount","peak","newData","Array","springFactor","leftFiller","rightFiller","idx","val","ApiMessageEntityTypes","ApiMediaFormat","getEntityTypeById","chatOrUserId","buildPeer","buildInputPeer","BigInt","buildInputPeerFromLocalDb","buildInputEntity","buildInputStickerSet","buildInputDocument","media","buildInputMediaDocument","inputDocument","generateRandomBigInt","readBigIntFromBuffer","generateRandomBytes","buildMessageFromUpdate","peerId","buildMtpMessageEntity","entity","offset","url","Bold","Italic","Underline","Strike","Code","Pre","language","Blockquote","TextUrl","Url","Hashtag","MentionName","calculateResultHash","ids","isMessageWithMedia","message","webpage","startsWith","buildInputContact","phone","clientId","buildChatBannedRights","untilDate","buildChatAdminRights","buildShippingInfo","info","shippingAddress","buildInputPrivacyKey","privacyKey","buildInputReportReason","reason","resolveMessageApiChatId","mtpMessage","addMessageToLocalDb","messageFullId","addPhotoToLocalDb","currentUserId","onUpdate","localMessageCounter","buildApiMessage","buildApiMessageWithChatId","isChatWithSelf","isOutgoing","out","post","fwdFrom","content","buildMessageMediaContent","sticker","poll","contact","text","buildMessageTextContent","entities","senderId","targetPeerId","isChannelPost","amount","currency","translationValues","targetUserIds","targetChatId","includes","withDuration","duration","video","join","mins","max","Number","totalAmount","domain","buildAction","replyToMsgId","replyToTopId","replyTo","isEdited","editDate","editHide","inlineButtons","keyboardButtons","keyboardPlaceholder","isKeyboardSingleUse","messageId","replyMarkup","value","markup","rows","buttons","button","receiptMsgId","placeholder","singleUse","buildReplyButtons","forwardInfo","savedFromPeerId","savedFromPeer","channelPost","channelPostId","isLinkedChannelPost","fromChatId","fromMessageId","savedFromMsgId","senderUserId","hiddenUserName","fromName","adminTitle","postAuthor","buildApiMessageForwardInfo","replies","mediaUnread","isMediaUnread","groupedId","isInAlbum","audio","shouldHideKeyboardButtons","views","isFromScheduled","fromScheduled","replyToMessageId","replyToTopMessageId","mentioned","hasUnreadMention","viaBotId","comments","threadInfo","buildThreadInfo","buildApiMessageEntity","buildMessageDraft","formattedText","replyingToId","buildSticker","ttlSeconds","buildPhoto","buildVideoFromDocument","buildVideo","audioAttribute","voice","fileName","getFilenameFromDocument","buildAudio","waveform","from","buildVoice","buildApiDocument","buildDocumentFromMedia","buildContact","buildPoll","results","buildPollFromMedia","webPage","buildWebPage","invoice","test","photoUrl","isTest","buildInvoice","buildInvoiceFromMedia","size","videoAttr","a","gifAttr","supportsStreaming","roundMessage","isRound","isGif","mediaType","mediaSize","imageAttribute","pollResults","answers","rawAnswers","answer","option","summary","isPublic","publicVoters","buildPollResults","rawResults","totalVoters","recentVoters","solution","solutionEntities","recentVoterIds","chosen","correct","voters","isChosen","isCorrect","votersCount","defaultBase","filenameAttribute","extension","split","buildNewPoll","localId","messageReplies","maxId","readMaxId","recentRepliers","threadId","originChannelId","messagesCount","lastMessageId","recentReplierIds","buildApiUserFromFull","mtpUserFull","about","commonChatsCount","pinnedMsgId","blocked","buildApiUser","fullInfo","bio","pinnedMessageId","isBlocked","botDescription","buildApiBotCommands","mtpUser","userType","bot","deleted","self","isSelf","mutualContact","isContact","canBeInvitedToGroup","botNochats","phoneNumber","status","buildApiUserStatus","botInlinePlaceholder","botPlaceholder","mtpStatus","expires","wasOnline","command","buildApiWallpaper","wallpaper","slug","buildApiSession","session","isCurrent","current","isOfficialApp","officialApp","isPasswordPending","passwordPending","buildPrivacyRules","rules","visibility","allowUserIds","allowChatIds","blockUserIds","blockChatIds","rule","buildApiNotifyException","showPreviews","sound","isSilent","shouldShowPreviews","sentMessageIds","updater","originRequest","connection","timeOffset","connectionState","state","buildApiMessageFromShort","notification","currentDate","inboxDate","buildApiMessageFromNotification","_entities","e","chat","has","dcId","buildChatPhotoForLocalDb","localDbChatId","abs","newProfilePhoto","some","existingIds","missingIds","profilePhotoIds","setTimeout","randomId","localMessage","Error","newContent","add","isAlreadySent","isScheduled","sendingState","messageUpdate","pollId","apiPoll","pollUpdate","options","stillUnreadCount","isPinned","pinned","order","dp","folderPeers","folderPeer","folder","orderedIds","replacedMembers","addedMember","deletedMemberId","messageIds","typingStatus","channel","unread","updatedUser","peerType","buildPrivacyKey","ApiErrors","PHONE_NUMBER_INVALID","PHONE_CODE_INVALID","PASSWORD_HASH_INVALID","PHONE_PASSWORD_FLOOD","authController","onRequestPhoneNumber","buildAuthStateUpdate","Promise","resolve","reject","onRequestCode","isCodeViaApp","onRequestPassword","hint","onRequestRegistration","onRequestQrCode","qrCode","token","onAuthError","err","errors","hours","ceil","seconds","authorizationState","provideAuthPhoneNumber","provideAuthCode","code","provideAuthPassword","password","provideAuthRegistration","registration","restartAuth","restartAuthWithQr","File","Blob","constructor","fileBits","super","this","name","cacheApi","caches","Type","async","fetch","cacheName","isHtmlAllowed","request","Request","cache","open","response","match","Text","blob","substr","contentType","headers","get","Json","json","console","warn","save","cacheData","JSON","stringify","Response","put","clear","delete","MEDIA_ENTITY_TYPES","getMimeType","fallbackMimeType","subarray","byte","GramJsLogger","gramJsUpdateEventBuilder","build","client","isConnected","destroy","invokeRequest","disconnect","onSessionUpdate","sessionData","handleGramJsUpdate","handleTerminatedSession","shouldHandleUpdates","shouldThrow","invoke","updatesContainer","updates","injectUpdateEntities","isSlowMode","error","hasErrorKey","dispatchErrorUpdate","downloadMedia","args","onProgress","mediaFormat","start","end","fullSize","mediaMatch","arrayBuffer","entityType","entityId","sizeType","Stream","acceptsBuffer","progressCallback","workers","getMessageMediaMimeType","downloadStickerSetThumb","Lottie","downloadProfilePhoto","download","parsed","DataUri","reader","FileReader","onload","target","onerror","readAsDataURL","BlobUrl","inflate","to","parse","Progressive","buffer","parseMedia","canCache","prepared","mediaData","URL","createObjectURL","downloadMediaWithClient","uploadFile","file","updateTwoFaSettings","params","fetchCurrentUser","userFull","currentUser","_currentUserId","onCurrentUserUpdate","MAX_INT_32","fetchChats","limit","offsetDate","withPinned","offsetPeer","excludePinned","resultPinned","updateLocalDb","lastMessagesByChatId","peersByKey","preparePeers","draftsById","replyingToById","dialogs","orderedPinnedIds","lastMessage","isListed","chatIds","totalChatCount","fetchFullChat","fullChat","onlineCount","exportedInvite","slowmodeSeconds","slowmodeNextSendDate","migratedFromChatId","migratedFromMaxId","canViewParticipants","linkedChatId","hiddenPrehistory","call","inviteLink","link","members","fetchMembers","kickedMembers","bannedUsers","adminMembers","adminUsers","slowMode","nextSendDate","migratedFrom","maxMessageId","canViewMembers","isPreHistoryHidden","groupCallId","getFullChannelInfo","getFullChatInfo","searchChats","query","q","localPeerIds","myResults","allChats","allUsers","localChats","r","localUsers","u","globalChats","globalUsers","fetchChat","requestChatUpdate","peers","saveDraft","clearDraft","updateChatMutedState","settings","createChannel","broadcast","newChannel","joinChannel","deleteChatUser","deleteChat","leaveChannel","deleteChannel","createGroupChat","newChat","editChatPhoto","uploadedPhoto","inputEntity","toggleChatPinned","shouldBePinned","toggleChatArchived","fetchChatFolders","byId","fetchRecommendedChatFolders","editChatFolder","folderUpdate","emoticon","contacts","nonContacts","groups","bots","excludeArchived","excludeMuted","excludeRead","buildFilterFromApiFolder","deleteChatFolder","isActionSuccessful","recommendedChatFolders","folders","toggleDialogUnread","getChatByUsername","togglePreHistoryHidden","isEnabled","enabled","updateChatDefaultBannedRights","updateChatMemberBannedRights","participant","updateChatAdmin","updateChatTitle","updateChatAbout","toggleSignatures","memberFilter","fetchGroupsForDiscussion","setDiscussionGroup","group","migrateChat","openChatByInvite","isChannel","addChatMembers","all","deleteChatMember","viewMessages","sendMessages","sendMedia","sendStickers","sendGifs","sendGames","sendInline","embedLinks","sendPolls","changeInfo","inviteUsers","pinMessages","store","importChatInvite","fetchMessages","pagination","RequestClass","msgId","c","threadInfos","fetchMessage","queue","sendMessage","replyingTo","attachment","gif","scheduledAt","noWebPage","filename","blobUrl","previewBlobUrl","quick","inputWaveform","buildUploadingMedia","buildLocalMessage","groupIndex","groupedUploads","counter","singleMediaByIndex","prevQueue","uploadMedia","inputMedia","uploadedMedia","messageMedia","fileReference","fetchInputMedia","multiMedia","values","scheduleDate","sendGroupedMedia","pollParams","quiz","question","Buffer","multipleChoice","correctAnswers","buildInputPoll","noWebpage","editMessage","mtpEntities","rescheduleMessage","lastModified","blobToFile","fetchBlob","fetchFile","patchedOnProgress","progress","isCanceled","inputFile","pinMessage","isUnpin","isOneSide","unpin","pmOneside","unpinAllMessages","deleteMessages","shouldDeleteForAll","revoke","deleteScheduledMessages","deleteHistory","just_clear","reportMessages","markMessageListRead","requestThreadInfoUpdate","markMessagesRead","topMessageResult","repliesResult","offsetId","addOffset","discussionChatId","topMessageId","firstMessageId","noTopChatsRequest","searchMessagesLocal","chatOrUser","minDate","maxDate","topMsgId","nextOffsetId","totalCount","searchMessagesGlobal","offsetRate","nextRate","fetchWebPagePreview","sendPollVote","loadPollOptionResults","shouldResetVoters","votes","vote","nextOffset","forwardMessages","fromChat","toChat","randomIds","index","isAudio","asIncomingInChatWithSelf","buildForwardedMessage","fromPeer","toPeer","findFirstMessageIdAfterDate","fetchScheduledHistory","sendScheduledMessages","isServiceMessageWithMedia","fetchPinnedMessages","inputGifBot","fetchFullUser","input","userWithFullInfo","fetchNearestCountry","dcInfo","country","fetchTopUsers","topPeers","correspondents","fetchContactList","savedCount","fetchUsers","updateContact","deleteUser","fetchProfilePhotos","fetchStickerSets","allStickers","sets","fetchRecentStickers","stickers","processStickerResult","slice","fetchFavoriteStickers","fetchFeaturedStickers","faveSticker","unfave","fetchStickers","stickerSetShortName","packs","acc","documentId","fetchAnimatedEmojis","searchStickers","fetchSavedGifs","gifs","processGifResult","installStickerSet","uninstallStickerSet","searchGifs","config","resolvedPeer","gifSearchUsername","foundGif","fetchStickersForEmoji","fetchEmojiKeywords","fromVersion","langCode","version","keywords","emojiKeyword","keyword","emoticons","checkChatUsername","setChatUsername","updatePrivateLink","EMAIL_UNCONFIRMED","EMAIL_HASH_EXPIRED","NEW_SALT_INVALID","NEW_SETTINGS_INVALID","CODE_INVALID","emailCodeController","getPasswordInfo","hasPassword","onRequestEmailCode","checkPassword","currentPassword","isCheckPassword","onError","clearPassword","updatePassword","email","newPassword","emailCodeCallback","onEmailCodeError","updateRecoveryEmail","provideRecoveryEmailCode","BETA_LANG_CODES","updateProfile","checkUsername","updateUsername","updateProfilePhoto","uploadProfilePhoto","fetchWallpapers","filteredWallpapers","wallpapers","pattern","uploadWallpaper","fetchBlockedContacts","blockedIds","blockContact","unblockContact","fetchAuthorizations","authorizations","terminateAuthorization","terminateAllAuthorizations","fetchNotificationExceptions","compareSound","fetchNotificationSettings","isMutedContactSignUpNotification","privateContactNotificationsSettings","groupNotificationsSettings","broadcastNotificationsSettings","privateSilent","privateMuteUntil","privateShowPreviews","groupSilent","groupMuteUntil","groupShowPreviews","broadcastSilent","broadcastMuteUntil","broadcastShowPreviews","hasContactJoinedNotifications","hasPrivateChatsNotifications","hasPrivateChatsMessagePreview","hasGroupNotifications","hasGroupMessagePreview","hasBroadcastNotifications","hasBroadcastMessagePreview","updateContactSignUpNotification","updateNotificationSettings","fetchLanguages","langPack","fetchLangPack","sourceLangPacks","collections","strings","reverse","fetchLangStrings","fetchPrivacySettings","registerDevice","secret","getAuthKey","getKey","tokenType","appSandbox","otherUids","unregisterDevice","setPrivacySettings","privacyRules","allowedUsers","allowedChats","blockedUsers","blockedChats","updateIsOnline","isOnline","offline","fetchContentSettings","isSensitiveEnabled","sensitiveEnabled","canChangeSensitive","sensitiveCanChange","updateContentSettings","buildApiWebDocument","answerCallbackButton","fetchTopInlineBots","botsInline","fetchInlineBot","addUserToLocalDb","fetchInlineBotResults","queryId","switchPm","isGallery","gallery","help","buildApiBotInlineMediaResult","webDocument","webThumbnail","buildApiBotInlineResult","sendInlineBotResult","resultId","startBot","startParam","buildShippingOptions","shippingOptions","prices","ac","cur","label","validateRequestedInfo","requestInfo","shouldSave","sendPaymentForm","formId","requestedInfoId","shippingOptionId","credentials","getPaymentForm","form","canSaveCredentials","passwordMissing","providerId","nativeProvider","nativeParams","savedInfo","nameRequested","phoneRequested","emailRequested","shippingAddressRequested","flexible","phoneToProvider","emailToProvider","mapedPrices","nativeData","needCardholderName","need_cardholder_name","needCountry","need_country","needZip","need_zip","publishableKey","publishable_key","buildPaymentForm","getReceipt","receipt","shipping","credentialsTitle","shippingPrices","shippingMethod","buildReceipt","initApi","_onUpdate","initialArgs","initUpdater","handleUpdate","initAuth","initChats","initMessages","initUsers","initStickers","initManagement","initTwoFaSettings","userAgent","sessions","TelegramClient","process","deviceModel","navigator","appVersion","useWSS","additionalDcsDisabled","addEventHandler","phoneCode","firstAndLastNames","initialMethod","getSessionData","initClient","flushUpdatesOnTickEnd","schedulerFn","fn","waiting","_args","throttleWith","cb","then","throttleId","pendingUpdates","currentThrottleId","currentUpdates","flushUpdatesThrottled","ms","shouldRunFirst","interval","isPending","setInterval","clearInterval","throttle","random","sendToOrigin","addEventListener","callbackState","Map","postMessage","onmessage","callback","callbackArgs","lastArg","ArrayBuffer","fnName","methods","callApi","require","crypto","little","signed","randBuffer","bytesNumber","bigInt","subtract","pow","toSignedLittleBuffer","big","number","bigNumber","byteArray","shiftRight","and","readBufferFromBigInt","bitLength","lesser","below","hex","padStart","l","reminder","randomBytes","sha1","shaSum","createHash","digest","crcTable","module","exports","generateRandomLong","mod","n","m","crc32","buf","k","makeCRCTable","isBuffer","crc","generateKeyDataFromNonce","serverNonce","newNonce","hash1","hash2","hash3","iv","sha256","bigIntMod","remainder","modExp","b","one","x","greater","zero","leastSignificantBit","divide","eq","multiply","getRandomInt","sleep","getByteArray","integer","bits","byteLength","convertToLittle","alloc","writeUInt32BE","bufferXor","res","createDeferred","promise","_resolve","constructors","checkPrimeAndGood","primeBytes","g","equals","numBytesForHash","bigNumForHash","isGoodModExpFirst","modexp","prime","diff","xor","computeHash","algo","salt1","salt2","salt","iterations","pbkdf2","pbkdf2sha512","computeCheck","currentAlgo","PasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow","pwHash","p","B","srp_B","isGoodLarge","pForHash","gForHash","bForHash","gX","kgX","aForHash","A","generateAndCheckRandom","gB","ux","aUx","S","K","pSha","gSha","salt1Sha","salt2Sha","M1","InputCheckPasswordSRP","srpId","computeDigest","JPEG_HEADER","JPEG_FOOTER","_raiseCastFail","getMessageId","getInputPeer","allowSelf","checkHash","User","InputPeerSelf","InputPeerUser","Chat","ChatEmpty","ChatForbidden","InputPeerChat","Channel","TypeError","InputPeerChannel","ChannelForbidden","InputUser","InputChannel","UserEmpty","InputPeerEmpty","UserFull","ChatFull","PeerChat","getDisplayName","getAppropriatedPartSize","fileSize","stripped","header","getDC","downloadDC","ipAddress","port","pwd","Api","newAlgo","newSettings","newPasswordHash","newSecureSettings","codeLength","os","Logger","MemorySession","Helpers","utils","Session","LAYER","requests","MTProtoSender","ConnectionTCPObfuscated","authFlow","checkAuthorization","downloadFile","WEBDOCUMENT_REQUEST_PART_SIZE","sizeTypes","apiId","apiHash","opts","DEFAULT_OPTIONS","_useIPV6","useIPV6","baseLogger","_log","floodSleepLimit","_eventBuilders","_phoneCodeHash","parseInt","_requestRetries","requestRetries","_connectionRetries","connectionRetries","_retryDelay","retryDelay","proxy","_proxy","_timeout","timeout","_autoReconnect","autoReconnect","_connection","_floodWaitedRequests","_initWith","InvokeWithLayer","layer","InitConnection","systemVersion","release","systemLangCode","_config","phoneCodeHashes","_exportedSenderPromises","_exportedSenderReleaseTimeouts","_additionalDcsDisabled","_loopStarted","_reconnecting","_destroyed","_initSession","_sender","logger","retries","delay","connectTimeout","authKeyCallback","_authKeyCallback","bind","updateCallback","_handleUpdate","isMainSender","userDisconnected","_user_connected","_disconnected","serverAddress","connect","setAuthKey","authKey","send","GetConfig","_updateLoop","load","setDC","attempts","PingDelayDisconnect","pingId","MIN_SAFE_INTEGER","MAX_SAFE_INTEGER","disconnectDelay","race","getTime","_lastRequest","GetState","sender","newDc","DC","setKey","dc","_authenticated","auth","ExportAuthorization","req","ImportAuthorization","shouldReconnect","existingSender","_connectSender","_createExportedSender","isConnecting","_borrowExportedSender","clearTimeout","onConnectionBreak","_cleanupExportedSender","getSender","inputLocation","messageOrMedia","Message","MessageMediaWebPage","WebPage","MessageMediaPhoto","Photo","_downloadPhoto","MessageMediaDocument","Document","_downloadDocument","MessageMediaContact","_downloadContact","WebDocument","WebDocumentNoProxy","_downloadWebDocument","isBig","loc","chatPhoto","UserProfilePhoto","ChatPhoto","InputPeerPhotoFileLocation","thumbVersion","InputStickerSetThumb","InputStickerSetID","thumbDcId","_pickFileSize","indexOf","_downloadCachedPhotoSize","PhotoStrippedSize","PhotoSizeEmpty","PhotoCachedSize","InputPhotoFileLocation","thumbSize","doc","InputDocumentFileLocation","buff","downloaded","upload","GetWebFile","location","InputWebFileLocation","attempt","sendWithInvokeSupport","ServerError","FloodWaitError","FloodTestPhoneWaitError","PhoneMigrateError","NetworkMigrateError","UserMigrateError","_switchDC","MsgWaitError","isReady","GetUsers","InputUserSelf","authParams","apiCredentials","fileParams","event","Updates","UpdatesCombined","_processUpdate","UpdateShort","others","_dispatchUpdate","ptsDate","builder","times","pause","Infinity","sequentialUpdates","DEFAULT_INITIAL_METHOD","me","botAuthToken","signInBot","signInUser","signInUserWithQrCode","phoneCodeHash","sendCodeResult","sendCode","forceSMS","termsOfService","isRegistrationRequired","signInWithPassword","isScanningComplete","inputPromise","exceptIds","updatePromise","result2","authorization","migratedResult","sendResult","resendResult","passwordSrpResult","passwordSrpCheck","computePasswordSrpCheck","ONE_MB","Foreman","maxWorkers","requestWorker","activeWorkers","releaseWorker","partSizeKb","partSize","partsCount","foreman","promises","hasEnded","isPrecise","offsetMemo","precise","buffers","totalLength","fileId","isLarge","partCount","fileToBuffer","sendingParts","j","jMemo","bytesMemo","filePart","fileTotalParts","parts","md5Checksum","BinaryReader","AuthKey","_key","_hash","auxHash","readLong","read","keyId","writeUInt8","shaData","other","cipher","createCipheriv","encrypt","Factorizator","neq","temp","pq","y","randBetween","minus","ys","condition","gcd","IGE","AESIGE","ige","decryptIge","cipherText","decrypt","encryptIge","plainText","padding","i2abLow","uint8","Uint8Array","int","i2abBig","ab2iLow","ab","Uint32Array","ab2iBig","isBigEndian","i2ab","ab2i","AES","getWords","Counter","initialValue","setBytes","_counter","increment","CTR","_remainingCounter","_remainingCounterIndex","_aes","encrypted","Hash","algorithm","subtle","createDecipheriv","getRandomValues","passwordKey","importKey","deriveBits","s2i","str","pos","charCodeAt","right","ReadCancelledError","TypeNotFoundError","invalidConstructorId","remaining","alert","InvalidChecksumError","checksum","validChecksum","InvalidBufferError","payload","readInt32LE","SecurityError","BadMessageError","errorMessage","ErrorMessages","CdnFileTamperedError","RPCError","_fmtRequest","InvalidDCError","BadRequestError","UnauthorizedError","ForbiddenError","NotFoundError","AuthKeyError","FloodError","TimedOutError","capture","SlowModeWaitError","FileMigrateError","EmailUnconfirmedError","rpcErrorRe","Common","RPCBaseErrors","RPCErrorList","RPCMessageToError","rpcError","msgRegex","Cls","EventBuilder","types","func","blacklistChats","resolved","NewMessage","Raw","StopPropagation","_queue","canGet","resolveGet","canPush","resolvePush","returned","pop","coreObjects","tlobjects","stream","_last","readByte","readInt","readUInt32LE","readLargeInt","readFloat","readFloatLE","readDouble","readDoubleLE","getBuffer","tgReadBytes","firstByte","tgReadString","tgReadBool","tgReadDate","tgReadObject","constructorId","clazz","seek","tellPosition","setPosition","fromReader","tgReadVector","close","position","_stream","write","getValue","_level","level","isBrowser","browser","__nwjs","colors","debug","messageFormat","canSend","levels","stack","format","toISOString","toUpperCase","color","log","MessageContainer","TLMessage","BinaryWriter","USE_INVOKE_AFTER_WITH","_state","_pendingStates","_ready","setReady","append","after","catch","finally","extend","states","batch","MAXIMUM_LENGTH","shift","SIZE_OVERHEAD","MAXIMUM_SIZE","afterId","writeDataAsMessage","unshift","writeUInt32LE","writeInt32LE","containerId","rejectAll","requestState","Mutex","mutex","WebSocketClient","closeError","disconnectedCallback","closed","readData","thisTime","canRead","toReturn","resolveRead","getWebSocketLink","ip","website","onopen","receive","onclose","wasClean","acquire","PromisedWebSockets","MessagePacker","AsyncQueue","tl","events","extensions","helpers","PUBLIC_KEYS","fingerprint","_serverKeys","keyInfo","doAuthentication","nonce","resPQ","factorize","pBuffer","qBuffer","pqInnerData","getBytes","targetFingerprint","targetKey","serverPublicKeyFingerprints","dataWithPadding","dataPadReversed","encryptedData","tempKey","shaDigestKeyWithData","dataWithHash","aesEncrypted","tempKeyXor","keyAesEncrypted","keyAesEncryptedInt","greaterOrEquals","encryptedDataBuffer","serverDhParams","publicKeyFingerprint","sh","nnh","newNonceHash","encryptedAnswer","plainTextAnswer","serverDhInner","dhPrime","ga","gA","serverTime","gb","gab","clientDhInner","retryId","clientDdhInnerHashed","clientDhEncrypted","dhGen","nonceTypes","nonceNumber","calcNewNonceHash","MTProtoState","loggers","body","_getNewMsgId","recv","MtProtoPlainSender","RPCResult","GZIPPacked","RequestState","MsgsAck","MsgsStateInfo","Pong","UpdateConnectionState","UpdateServerTimeOffset","BadServerSalt","BadMsgNotification","MsgDetailedInfo","MsgNewDetailedInfo","NewSessionCreated","FutureSalts","MsgsStateReq","MsgResendReq","MsgsAllInfo","LogOut","_dcId","_retries","_delay","_connectTimeout","_updateCallback","_autoReconnectCallback","autoReconnectCallback","_isMainSender","_onConnectionBreak","_send_loop_handle","_recv_loop_handle","_send_queue","_pending_state","_pending_ack","_last_acks","_handlers","_handleRPCResult","_handleContainer","_handleGzipPacked","_handlePong","_handleBadServerSalt","_handleBadNotification","_handleDetailedInfo","_handleNewDetailedInfo","_handleNewSessionCreated","_handleAck","_handleFutureSalts","_handleStateForgotten","_handleMsgAll","force","_connect","connected","disconnected","_disconnect","plain","_sendLoop","_recvLoop","ack","msgIds","encryptMessageData","isArray","reconnect","decryptMessageData","broken","_processMessage","obj","handler","_popStates","toPop","reqMsgId","readResult","innerMessage","pong","newTimeOffset","updateTimeOffset","badSalt","badMsgId","newServerSalt","badMsg","errorCode","_sequence","answerMsgId","serverSalt","repeat","_reconnect","reset","newConnection","_ip","_port","InvokeAfterMsg","_lastMsgId","updateMessageId","msgKey","sha256a","sha256b","contentRelated","seqNo","_getSeqNo","gzipIfSmaller","waitForKey","_calcKey","ourKey","remoteMsgId","remoteSequence","containerLen","nanoseconds","newMsgId","shiftLeft","or","correctMsgId","bad","old","pending","Connection","_connected","_sendTask","_recvTask","_codec","_obfuscation","_sendArray","_recvArray","socket","disconnectCallback","PacketCodecClass","_initConn","fromCallback","_send","_recv","tag","encodedPacket","encodePacket","readPacket","PacketCodec","_conn","ObfuscatedConnection","ObfuscatedIO","AbridgedPacketCodec","props","obfuscateTag","ConnectionTCPAbridged","initHeader","_encrypt","encryptor","_decrypt","decryptor","packetCodec","ok","toJSON","randomReversed","encryptKey","encryptIv","decryptKey","decryptIv","readExactly","ConnectionTCPFull","MTProtoPlainSender","StorageSession","CACHE_NAME","_storageKey","cached","_sessionData","_callback","_authKeys","mainDcId","hashes","skipOnUpdate","_serverAddress","idb","_delete","del","_fetchFromCache","_saveToCache","localStorage","removeItem","getItem","setItem","_takeoutId","_updateStates","_authKey","sessionInfo","_sessionString","_loadFromSessionString","skipUpdateStorage","_updateStorage","asHex","mainDcIdStr","mainDcKey","StringSession","decode","readUInt8","serverAddressLen","readInt16BE","dcBuffer","addressBuffer","addressLengthBuffer","writeInt16BE","portBuffer","encode","Memory","CacheApiSession","LocalStorageSession","IdbSession","CallbackSession","api","sub","parseTl","serializeBytes","serializeDate","tlContent","schemeContent","CACHING_SUPPORTED","CACHE_KEY","extractParams","fileContent","f","functions","d","isFunction","argToBytes","writeDoubleLE","getArgFromReader","arg","isVector","useVectorId","flagIndicator","skipConstructorId","createClasses","classesType","classes","classParams","subclassOfId","argsConfig","namespace","fullName","VirtualClass","argName","isFlag","flagIndex","idForBytes","flagCalculate","boxed","charAt","definitions","fromCache","jsonCache","loadFromCache","constructorParamsApi","functionParamsApi","constructorParamsSchema","functionParamsSchema","loadFromTlSchemas","obj1","obj2","mergeWithNamespaces","buildApiFromTlSchema","gzipped","toBytes","gzip","ungzip","containerLength","before","tlMessage","RpcError","innerCode","snakeToCamelCase","_","variableSnakeToCamelCase","CORE_TYPES","AUTH_KEY_TYPES","findAll","regex","matches","RegExp","source","exec","fromLine","line","argsMatch","currentConfig","hexId","representation","brace","argType","buildArgConfig","flagMatch","vectorMatch","ignoreIds","o","objAll","objByName","objByType","commentIndex","trim","followingTypes","dt","fill","t","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","loaded","__webpack_modules__","__webpack_exports__","O","chunkIds","priority","notFulfilled","fulfilled","every","splice","getter","__esModule","definition","defineProperty","enumerable","chunkId","miniCssF","globalThis","Function","prop","prototype","Symbol","toStringTag","nmd","paths","children","scriptUrl","importScripts","currentScript","src","scripts","getElementsByTagName","installedChunks","chunkLoadingGlobal","parentChunkLoadingFunction","moreModules","runtime"],"sourceRoot":""}