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W,IACjC58B,G,MCHR,IAAI68B,EACA7B,EAAoBh4B,EAAE85B,gBAAeD,EAAY7B,EAAoBh4B,EAAE6O,SAAW,IACtF,IAAIxnD,EAAW2wE,EAAoBh4B,EAAE34C,SACrC,IAAKwyE,GAAaxyE,IACbA,EAAS0yE,gBACZF,EAAYxyE,EAAS0yE,cAAcC,MAC/BH,GAAW,CACf,IAAII,EAAU5yE,EAAS6yE,qBAAqB,UACzCD,EAAQh1E,SAAQ40E,EAAYI,EAAQA,EAAQh1E,OAAS,GAAG+0E,KAK7D,IAAKH,EAAW,MAAM,IAAIpuD,MAAM,yDAChCouD,EAAYA,EAAU/0E,QAAQ,OAAQ,IAAIA,QAAQ,QAAS,IAAIA,QAAQ,YAAa,KACpFkzE,EAAoB32B,EAAIw4B,G,SCXxB,IAAIM,EAAkB,CACrB,IAAK,GAgBNnC,EAAoBnF,EAAE3tE,EAAI,CAACg0E,EAASnmB,KAE/BonB,EAAgBjB,IAElBY,cAAc9B,EAAoB32B,EAAI22B,EAAoBh+C,EAAEk/C,KAK/D,IAAIkB,EAAqBlhE,KAA6B,uBAAIA,KAA6B,wBAAK,GACxFmhE,EAA6BD,EAAmB1wE,KAAK6/C,KAAK6wB,GAC9DA,EAAmB1wE,KAvBCG,IACnB,IAAK0uE,EAAU+B,EAAaC,GAAW1wE,EACvC,IAAI,IAAIouE,KAAYqC,EAChBtC,EAAoBX,EAAEiD,EAAarC,KACrCD,EAAoB36B,EAAE46B,GAAYqC,EAAYrC,IAIhD,IADGsC,GAASA,EAAQvC,GACdO,EAAStzE,QACdk1E,EAAgB5B,EAAS1c,OAAS,EACnCwe,EAA2BxwE,K,GlHnBxBzH,EAAO41E,EAAoBx5B,EAC/Bw5B,EAAoBx5B,EAAI,IAChBw5B,EAAoBluD,EAAE,KAAKuvB,KAAKj3C,GmHDd41E,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/schedulers.ts","webpack://telegram-t/./src/util/iteratees.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/helpers.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/apiBuilders/peers.ts","webpack://telegram-t/./src/api/gramjs/helpers.ts","webpack://telegram-t/./src/api/gramjs/gramjsBuilders/index.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/messages.ts","webpack://telegram-t/./src/util/serverTime.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/chats.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/apiBuilders/calls.ts","webpack://telegram-t/./src/api/gramjs/updater.ts","webpack://telegram-t/./src/api/gramjs/methods/auth.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/util/files.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/calls.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/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-v7';\nexport const ASSET_CACHE_NAME = 'tt-assets';\nexport const AUTODOWNLOAD_FILESIZE_MB_LIMITS = [1, 5, 10, 50, 100, 500];\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_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;\nexport const COMMON_CHATS_LIMIT = 100;\nexport const GROUP_CALL_PARTICIPANTS_LIMIT = 100;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 20;\nexport const ALL_CHATS_PRELOAD_DISABLED = false;\n\nexport const SPONSORED_MESSAGE_CACHE_MS = 300000; // 5 min\n\nexport const DEFAULT_VOLUME = 1;\nexport const DEFAULT_PLAYBACK_RATE = 1;\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\nexport const SEND_MESSAGE_ACTION_INTERVAL = 3000; // 3s\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;\nexport const TMP_CHAT_ID = '0';\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 VIDEO_MOV_TYPE = 'video/quicktime';\n\nexport const SUPPORTED_IMAGE_CONTENT_TYPES = new Set([\n 'image/png', 'image/gif', 'image/jpeg',\n]);\n\nexport const SUPPORTED_VIDEO_CONTENT_TYPES = new Set([\n 'video/mp4', // video/quicktime added dynamically in environment.ts\n]);\n\nexport const CONTENT_TYPES_WITH_PREVIEW = new Set([\n ...SUPPORTED_IMAGE_CONTENT_TYPES,\n ...SUPPORTED_VIDEO_CONTENT_TYPES,\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_TG_LINK = /^tg:(\\/\\/)?([?=&\\d\\w_-]+)?/gm;\nexport const RE_TME_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/)/gm;\n\n// eslint-disable-next-line max-len\nexport const COUNTRIES_WITH_12H_TIME_FORMAT = new Set(['AU', 'BD', 'CA', 'CO', 'EG', 'HN', 'IE', 'IN', 'JO', 'MX', 'MY', 'NI', 'NZ', 'PH', 'PK', 'SA', 'SV', 'US']);\n\n// MTProto constants\nexport const SERVICE_NOTIFICATIONS_USER_ID = '777000';\nexport const REPLIES_USER_ID = '1271266957'; // TODO For Test connection ID must be equal to 708513\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// TODO Get values from `getConfig` method once it's available\nexport const SEEN_BY_MEMBERS_CHAT_MAX = 50;\nexport const SEEN_BY_MEMBERS_EXPIRE = 604680; // One week - 2 min\n\n// Group calls\nexport const GROUP_CALL_VOLUME_MULTIPLIER = 100;\nexport const GROUP_CALL_DEFAULT_VOLUME = 100 * GROUP_CALL_VOLUME_MULTIPLIER;\nexport const ENABLE_THUMBNAIL_VIDEO = false;\n","type Scheduler =\n typeof requestAnimationFrame\n | typeof onTickEnd\n | typeof runNow;\n\nexport function debounce(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n shouldRunLast = true,\n) {\n let waitingTimeout: number | undefined;\n\n return (...args: Parameters) => {\n if (waitingTimeout) {\n clearTimeout(waitingTimeout);\n waitingTimeout = undefined;\n } else if (shouldRunFirst) {\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n waitingTimeout = self.setTimeout(() => {\n if (shouldRunLast) {\n fn(...args);\n }\n\n waitingTimeout = undefined;\n }, ms);\n };\n}\n\nexport function throttle(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n) {\n let interval: number | undefined;\n let isPending: boolean;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n isPending = true;\n args = _args;\n\n if (!interval) {\n if (shouldRunFirst) {\n isPending = false;\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 fn(...args);\n }, ms);\n }\n };\n}\n\nexport function throttleWithRaf(fn: F) {\n return throttleWith(fastRaf, fn);\n}\n\nexport function throttleWithPrimaryRaf(fn: F) {\n return throttleWith(fastRafPrimary, fn);\n}\n\nexport function throttleWithTickEnd(fn: F) {\n return throttleWith(onTickEnd, fn);\n}\n\nexport function throttleWithNow(fn: F) {\n return throttleWith(runNow, fn);\n}\n\nexport function throttleWith(schedulerFn: Scheduler, fn: F) {\n let waiting = false;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n args = _args;\n\n if (!waiting) {\n waiting = true;\n\n schedulerFn(() => {\n waiting = false;\n fn(...args);\n });\n }\n };\n}\n\nexport function onIdle(cb: NoneToVoidFunction, timeout?: number) {\n // eslint-disable-next-line no-restricted-globals\n if (self.requestIdleCallback) {\n // eslint-disable-next-line no-restricted-globals\n self.requestIdleCallback(cb, { timeout });\n } else {\n onTickEnd(cb);\n }\n}\n\nfunction runNow(fn: NoneToVoidFunction) {\n fn();\n}\n\nexport const pause = (ms: number) => new Promise((resolve) => {\n setTimeout(() => resolve(), ms);\n});\n\nexport function rafPromise() {\n return new Promise((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 fastRafPrimary(callback: NoneToVoidFunction) {\n fastRaf(callback, true);\n}\n\nlet onTickEndCallbacks: NoneToVoidFunction[] | undefined;\nlet onTickEndPrimaryCallbacks: NoneToVoidFunction[] | undefined;\n\nexport function onTickEnd(callback: NoneToVoidFunction, isPrimary = false) {\n if (!onTickEndCallbacks) {\n onTickEndCallbacks = isPrimary ? [] : [callback];\n onTickEndPrimaryCallbacks = isPrimary ? [callback] : [];\n\n Promise.resolve().then(() => {\n const currentCallbacks = onTickEndCallbacks!;\n const currentPrimaryCallbacks = onTickEndPrimaryCallbacks!;\n onTickEndCallbacks = undefined;\n onTickEndPrimaryCallbacks = undefined;\n currentPrimaryCallbacks.forEach((cb) => cb());\n currentCallbacks.forEach((cb) => cb());\n });\n } else if (isPrimary) {\n onTickEndPrimaryCallbacks!.push(callback);\n } else {\n onTickEndCallbacks.push(callback);\n }\n}\n\nexport function onTickEndPrimary(callback: NoneToVoidFunction) {\n onTickEnd(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","type CollectionByKey = Record;\n\ntype OrderDirection =\n 'asc'\n | 'desc';\n\ninterface OrderCallback {\n (member: T): any;\n}\n\nexport function buildCollectionByKey(collection: T[], key: keyof T) {\n return collection.reduce((byKey: CollectionByKey, member: T) => {\n byKey[member[key]] = member;\n\n return byKey;\n }, {});\n}\n\nexport function mapValues(\n byKey: CollectionByKey,\n callback: (member: M, key: string, index: number, originalByKey: CollectionByKey) => R,\n): CollectionByKey {\n return Object.keys(byKey).reduce((newByKey: CollectionByKey, key, index) => {\n newByKey[key] = callback(byKey[key], key, index, byKey);\n return newByKey;\n }, {});\n}\n\nexport function pick(object: T, keys: K[]) {\n return keys.reduce((result, key) => {\n result[key] = object[key];\n return result;\n }, {} as Pick);\n}\n\nexport function pickTruthy(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);\n}\n\nexport function omit(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>;\n\n return pick(object, savedKeys);\n}\n\nexport function orderBy(\n collection: T[],\n orderRule: (keyof T) | OrderCallback | ((keyof T) | OrderCallback)[],\n mode: OrderDirection | [OrderDirection, OrderDirection] = 'asc',\n): T[] {\n function compareValues(a: T, b: T, currentOrderRule: (keyof T) | OrderCallback, isAsc: boolean) {\n const aValue = (typeof currentOrderRule === 'function' ? currentOrderRule(a) : a[currentOrderRule]) || 0;\n const bValue = (typeof currentOrderRule === 'function' ? currentOrderRule(b) : b[currentOrderRule]) || 0;\n\n return isAsc ? aValue - bValue : bValue - aValue;\n }\n\n if (Array.isArray(orderRule)) {\n const [mode1, mode2] = Array.isArray(mode) ? mode : [mode, mode];\n const [orderRule1, orderRule2] = orderRule;\n const isAsc1 = mode1 === 'asc';\n const isAsc2 = mode2 === 'asc';\n\n return collection.sort((a, b) => {\n return compareValues(a, b, orderRule1, isAsc1) || compareValues(a, b, orderRule2, isAsc2);\n });\n }\n\n const isAsc = mode === 'asc';\n return collection.sort((a, b) => {\n return compareValues(a, b, orderRule, isAsc);\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(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(array: T[], set: Set): 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(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\nexport function findLast(array: Array, 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\ntype VirtualFields =\n 'flags'\n | 'CONSTRUCTOR_ID'\n | 'SUBCLASS_OF_ID'\n | 'className'\n | 'classType'\n | 'getBytes';\n\nexport 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 & { flags?: any }>(\n instance: T,\n): Omit {\n const {\n flags,\n CONSTRUCTOR_ID,\n SUBCLASS_OF_ID,\n className,\n classType,\n getBytes,\n ...rest\n } = instance;\n\n return rest;\n}\n","/* eslint-disable no-bitwise */\n\n// eslint-disable-next-line max-len\nconst TEMPLATE = '';\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.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;\n // Used for loading avatars and media through in-memory Gram JS instances.\n chats: Record;\n users: Record;\n messages: Record;\n documents: Record;\n stickerSets: Record;\n photos: Record;\n webDocuments: Record;\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?.alt;\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 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?.length),\n count,\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","import { ApiGroupCall } from './calls';\n\nexport 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 stickers?: ApiSticker[];\n packs?: Record;\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 id: string;\n size: number;\n mimeType: string;\n fileName: string;\n duration: number;\n performer?: string;\n title?: string;\n thumbnailSizes?: ApiPhotoSize[];\n}\n\nexport interface ApiVoice {\n id: string;\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: string;\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?: string[];\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?: string[];\n targetChatId?: string;\n type: 'historyClear' | 'contactSignUp' | 'chatCreate' | 'other';\n photo?: ApiPhoto;\n amount?: number;\n currency?: string;\n translationValues: string[];\n call?: Partial;\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 date: number;\n isChannelPost: boolean;\n channelPostId?: number;\n isLinkedChannelPost?: boolean;\n fromChatId?: string;\n senderUserId?: string;\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?: string;\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: string;\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?: string;\n replyToChatId?: string;\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 editDate?: number;\n isMentioned?: 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?: string;\n threadInfo?: ApiThreadInfo;\n adminTitle?: string;\n isScheduled?: boolean;\n shouldHideKeyboardButtons?: boolean;\n isFromScheduled?: boolean;\n seenByUserIds?: string[];\n isProtected?: boolean;\n}\n\nexport interface ApiThreadInfo {\n threadId: number;\n chatId: string;\n topMessageId?: number;\n originChannelId?: string;\n messagesCount: number;\n lastMessageId?: number;\n lastReadInboxMessageId?: number;\n recentReplierIds?: string[];\n}\n\nexport type ApiMessageOutgoingStatus = 'read' | 'succeeded' | 'pending' | 'failed';\n\nexport type ApiSponsoredMessage = {\n chatId?: string;\n randomId: string;\n isBot?: boolean;\n channelPostId?: number;\n startParam?: string;\n chatInviteHash?: string;\n chatInviteTitle?: string;\n text: ApiFormattedText;\n expiresAt: number;\n};\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' | 'voice' | '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 type ApiSendMessageAction = {\n type: 'cancel' | 'typing' | 'recordAudio' | 'chooseSticker';\n};\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 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 extends ApiMediaFormat.Lottie ? AnyLiteral : string;\n","import BigInt from 'big-integer';\n\nimport { Api as GramJs } from '../../../lib/gramjs';\n\nexport function isPeerUser(peer: GramJs.TypePeer | GramJs.TypeInputPeer): peer is GramJs.PeerUser {\n return peer.hasOwnProperty('userId');\n}\n\nexport function isPeerChat(peer: GramJs.TypePeer | GramJs.TypeInputPeer): peer is GramJs.PeerChat {\n return peer.hasOwnProperty('chatId');\n}\n\nexport function isPeerChannel(peer: GramJs.TypePeer | GramJs.TypeInputPeer): peer is GramJs.PeerChannel {\n return peer.hasOwnProperty('channelId');\n}\n\nexport function buildApiPeerId(id: BigInt.BigInteger, type: 'user' | 'chat' | 'channel') {\n return type === 'user' ? String(id) : `-${id}`;\n}\n\nexport function getApiChatIdFromMtpPeer(peer: GramJs.TypePeer | GramJs.TypeInputPeer) {\n if (isPeerUser(peer)) {\n return buildApiPeerId(peer.userId, 'user');\n } else if (isPeerChat(peer)) {\n return buildApiPeerId(peer.chatId, 'chat');\n } else {\n return buildApiPeerId((peer as GramJs.InputPeerChannel).channelId, 'channel');\n }\n}\n","import { Api as GramJs } from '../../lib/gramjs';\nimport localDb from './localDb';\nimport { buildApiPeerId, getApiChatIdFromMtpPeer } from './apiBuilders/peers';\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\nfunction addChatToLocalDb(chat: GramJs.Chat | GramJs.Channel, noOverwrite = false) {\n const id = buildApiPeerId(chat.id, chat instanceof GramJs.Chat ? 'chat' : 'channel');\n if (!noOverwrite || !localDb.chats[id]) {\n localDb.chats[id] = chat;\n }\n}\n\nexport function addUserToLocalDb(user: GramJs.User, shouldOverwrite = false) {\n const id = buildApiPeerId(user.id, 'user');\n if (shouldOverwrite || !localDb.users[id]) {\n localDb.users[id] = user;\n }\n}\n\nexport function addEntitiesWithPhotosToLocalDb(entities: (GramJs.TypeUser | GramJs.TypeChat)[]) {\n entities.forEach((entity) => {\n if (entity instanceof GramJs.User && entity.photo) {\n addUserToLocalDb(entity);\n } else if ((entity instanceof GramJs.Chat || entity instanceof GramJs.Channel) && entity.photo) {\n addChatToLocalDb(entity);\n }\n });\n}\n\nexport function serializeBytes(value: Buffer) {\n return String.fromCharCode(...value);\n}\n\nexport function deserializeBytes(value: string) {\n return Buffer.from(value, 'binary');\n}\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 ApiChatAdminRights,\n ApiChatBannedRights,\n ApiChatFolder,\n ApiGroupCall,\n ApiMessageEntity,\n ApiMessageEntityTypes,\n ApiNewPoll,\n ApiReportReason,\n ApiSendMessageAction,\n ApiSticker,\n ApiVideo,\n} from '../../types';\nimport localDb from '../localDb';\nimport { pick } from '../../../util/iteratees';\nimport { deserializeBytes } from '../helpers';\n\nconst CHANNEL_ID_MIN_LENGTH = 11; // Example: -1000000000\n\nexport function getEntityTypeById(chatOrUserId: string) {\n if (typeof chatOrUserId === 'number') {\n return getEntityTypeByDeprecatedId(chatOrUserId);\n }\n\n if (!chatOrUserId.startsWith('-')) {\n return 'user';\n } else if (chatOrUserId.length >= CHANNEL_ID_MIN_LENGTH) {\n return 'channel';\n } else {\n return 'chat';\n }\n}\n\n// Workaround for old-fashioned IDs stored locally\nexport function getEntityTypeByDeprecatedId(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: string): GramJs.TypePeer {\n const type = getEntityTypeById(chatOrUserId);\n\n if (type === 'user') {\n return new GramJs.PeerUser({\n userId: buildMtpPeerId(chatOrUserId, 'user'),\n });\n } else if (type === 'channel') {\n return new GramJs.PeerChannel({\n channelId: buildMtpPeerId(chatOrUserId, 'channel'),\n });\n } else {\n return new GramJs.PeerChat({\n chatId: buildMtpPeerId(chatOrUserId, 'chat'),\n });\n }\n}\n\nexport function buildInputPeer(chatOrUserId: string, accessHash?: string): GramJs.TypeInputPeer {\n const type = getEntityTypeById(chatOrUserId);\n\n if (type === 'user') {\n return new GramJs.InputPeerUser({\n userId: buildMtpPeerId(chatOrUserId, 'user'),\n accessHash: BigInt(accessHash!),\n });\n } else if (type === 'channel') {\n return new GramJs.InputPeerChannel({\n channelId: buildMtpPeerId(chatOrUserId, 'channel'),\n accessHash: BigInt(accessHash!),\n });\n } else {\n return new GramJs.InputPeerChat({\n chatId: buildMtpPeerId(chatOrUserId, 'chat'),\n });\n }\n}\n\nexport function buildInputPeerFromLocalDb(chatOrUserId: string): GramJs.TypeInputPeer | undefined {\n const type = getEntityTypeById(chatOrUserId);\n let accessHash: BigInt.BigInteger | undefined;\n\n if (type === 'user') {\n accessHash = localDb.users[chatOrUserId]?.accessHash;\n if (!accessHash) {\n return undefined;\n }\n } else if (type === 'channel') {\n accessHash = (localDb.chats[chatOrUserId] as GramJs.Channel)?.accessHash;\n if (!accessHash) {\n return undefined;\n }\n }\n\n return buildInputPeer(chatOrUserId, String(accessHash));\n}\n\nexport function buildInputEntity(chatOrUserId: string, accessHash?: string) {\n const type = getEntityTypeById(chatOrUserId);\n\n if (type === 'user') {\n return new GramJs.InputUser({\n userId: buildMtpPeerId(chatOrUserId, 'user'),\n accessHash: BigInt(accessHash!),\n });\n } else if (type === 'channel') {\n return new GramJs.InputChannel({\n channelId: buildMtpPeerId(chatOrUserId, 'channel'),\n accessHash: BigInt(accessHash!),\n });\n } else {\n return buildMtpPeerId(chatOrUserId, 'chat');\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 }) => {\n return new GramJs.PollAnswer({ text, option: deserializeBytes(option) });\n }),\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(deserializeBytes);\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(Boolean as any)\n : [];\n\n const includePeers = includedChatIds\n ? includedChatIds.map(buildInputPeerFromLocalDb).filter(Boolean as any)\n : [];\n\n const excludePeers = excludedChatIds\n ? excludedChatIds.map(buildInputPeerFromLocalDb).filter(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 generateRandomInt() {\n return readBigIntFromBuffer(generateRandomBytes(4), true, true).toJSNumber();\n}\n\nexport function buildMessageFromUpdate(\n id: number,\n chatId: string,\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: BigInt(userId!), accessHash: user!.accessHash! }),\n });\n default:\n return new GramJs.MessageEntityUnknown({ offset, length });\n }\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\nexport function buildSendMessageAction(action: ApiSendMessageAction) {\n switch (action.type) {\n case 'cancel':\n return new GramJs.SendMessageCancelAction();\n case 'typing':\n return new GramJs.SendMessageTypingAction();\n case 'recordAudio':\n return new GramJs.SendMessageRecordAudioAction();\n case 'chooseSticker':\n return new GramJs.SendMessageChooseStickerAction();\n }\n return undefined;\n}\n\nexport function buildMtpPeerId(id: string, type: 'user' | 'chat' | 'channel') {\n // Workaround for old-fashioned IDs stored locally\n if (typeof id === 'number') {\n return BigInt(Math.abs(id));\n }\n\n return type === 'user' ? BigInt(id) : BigInt(id.slice(1));\n}\n\nexport function buildInputGroupCall(groupCall: Partial) {\n return new GramJs.InputGroupCall({\n id: BigInt(groupCall.id!),\n accessHash: BigInt(groupCall.accessHash!),\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 ApiGroupCall,\n ApiUser,\n ApiSponsoredMessage,\n} from '../../types';\n\nimport {\n DELETED_COMMENTS_CHANNEL_ID,\n LOCAL_MESSAGE_ID_BASE,\n SERVICE_NOTIFICATIONS_USER_ID,\n SPONSORED_MESSAGE_CACHE_MS,\n SUPPORTED_IMAGE_CONTENT_TYPES,\n SUPPORTED_VIDEO_CONTENT_TYPES,\n VIDEO_MOV_TYPE,\n} from '../../../config';\nimport { pick } from '../../../util/iteratees';\nimport { buildStickerFromDocument } from './symbols';\nimport { buildApiPhoto, buildApiPhotoSize, buildApiThumbnailFromStripped } from './common';\nimport { interpolateArray } from '../../../util/waveform';\nimport { buildPeer } from '../gramjsBuilders';\nimport { addPhotoToLocalDb, resolveMessageApiChatId, serializeBytes } from '../helpers';\nimport { buildApiPeerId, getApiChatIdFromMtpPeer, isPeerUser } from './peers';\n\nconst LOCAL_MEDIA_UPLOADING_TEMP_ID = 'temp';\nconst INPUT_WAVEFORM_LENGTH = 63;\n\nlet localMessageCounter = LOCAL_MESSAGE_ID_BASE;\nlet currentUserId!: string;\n\nexport function setMessageBuilderCurrentUserId(_currentUserId: string) {\n currentUserId = _currentUserId;\n}\n\nexport function buildApiSponsoredMessage(mtpMessage: GramJs.SponsoredMessage): ApiSponsoredMessage | undefined {\n const {\n fromId, message, entities, startParam, channelPost, chatInvite, chatInviteHash, randomId,\n } = mtpMessage;\n const chatId = fromId ? getApiChatIdFromMtpPeer(fromId) : undefined;\n const chatInviteTitle = chatInvite\n ? (chatInvite instanceof GramJs.ChatInvite\n ? chatInvite.title\n : !(chatInvite.chat instanceof GramJs.ChatEmpty) ? chatInvite.chat.title : undefined)\n : undefined;\n\n return {\n randomId: serializeBytes(randomId),\n isBot: fromId ? isPeerUser(fromId) : false,\n text: buildMessageTextContent(message, entities),\n expiresAt: Math.round(Date.now() / 1000) + SPONSORED_MESSAGE_CACHE_MS,\n ...(chatId && { chatId }),\n ...(chatInviteHash && { chatInviteHash }),\n ...(chatInvite && { chatInviteTitle }),\n ...(startParam && { startParam }),\n ...(channelPost && { channelPostId: channelPost }),\n };\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 = buildApiPeerId(mtpMessage.userId, 'user');\n\n return buildApiMessageWithChatId(chatId, {\n ...mtpMessage,\n fromId: buildPeer(mtpMessage.out ? currentUserId : buildApiPeerId(mtpMessage.userId, 'user')),\n });\n}\n\nexport function buildApiMessageFromShortChat(mtpMessage: GramJs.UpdateShortChatMessage): ApiMessage {\n const chatId = buildApiPeerId(mtpMessage.chatId, 'chat');\n\n return buildApiMessageWithChatId(chatId, {\n ...mtpMessage,\n fromId: buildPeer(buildApiPeerId(mtpMessage.fromId, 'user')),\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\n & Pick, (\n 'out' | 'message' | 'entities' | 'fromId' | 'peerId' | 'fwdFrom' | 'replyTo' | 'replyMarkup' | 'post' |\n 'media' | 'action' | 'views' | 'editDate' | 'editHide' | 'mediaUnread' | 'groupedId' | 'mentioned' | 'viaBotId' |\n 'replies' | 'fromScheduled' | 'postAuthor' | 'noforwards'\n )>\n);\n\nexport function buildApiMessageWithChatId(chatId: string, 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, replyToPeerId } = 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 && String(mtpMessage.groupedId);\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 ...(replyToPeerId && { replyToChatId: getApiChatIdFromMtpPeer(replyToPeerId) }),\n ...(replyToTopId && { replyToTopMessageId: replyToTopId }),\n ...(forwardInfo && { forwardInfo }),\n ...(isEdited && { isEdited, editDate: mtpMessage.editDate }),\n ...(isMediaUnread && { isMediaUnread }),\n ...(mtpMessage.mentioned && isMediaUnread && { hasUnreadMention: true }),\n ...(mtpMessage.mentioned && { isMentioned: true }),\n ...(groupedId && {\n groupedId,\n isInAlbum,\n }),\n inlineButtons,\n ...(keyboardButtons && { keyboardButtons, keyboardPlaceholder, isKeyboardSingleUse }),\n ...(shouldHideKeyboardButtons && { shouldHideKeyboardButtons }),\n ...(mtpMessage.viaBotId && { viaBotId: buildApiPeerId(mtpMessage.viaBotId, 'user') }),\n ...(replies?.comments && { threadInfo: buildThreadInfo(replies, mtpMessage.id, chatId) }),\n ...(postAuthor && { adminTitle: postAuthor }),\n ...(mtpMessage.noforwards && { isProtected: true }),\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 if ('ttlSeconds' in media && media.ttlSeconds) {\n return undefined;\n }\n\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 date: fwdFrom.date,\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 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 // eslint-disable-next-line no-restricted-globals\n if (mimeType === VIDEO_MOV_TYPE && !(self as any).isMovSupported) {\n return undefined;\n }\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 const thumbnailSizes = media.document.thumbs && media.document.thumbs\n .filter((thumb): thumb is GramJs.PhotoSize => thumb instanceof GramJs.PhotoSize)\n .map((thumb) => buildApiPhotoSize(thumb));\n\n return {\n id: String(media.document.id),\n fileName: getFilenameFromDocument(media.document, 'audio'),\n thumbnailSizes,\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 id: String(media.document.id),\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 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 (SUPPORTED_IMAGE_CONTENT_TYPES.has(mimeType)) {\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 (SUPPORTED_VIDEO_CONTENT_TYPES.has(mimeType)) {\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 const {\n firstName, lastName, phoneNumber, userId,\n } = media;\n\n return {\n firstName, lastName, phoneNumber, userId: buildApiPeerId(userId, 'user'),\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: serializeBytes(answer.option),\n }));\n\n return {\n id: String(id),\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?.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: serializeBytes(option),\n votersCount: voters,\n }));\n\n return {\n totalVoters,\n recentVoterIds: recentVoters?.map((id) => buildApiPeerId(id, 'user')),\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: string | undefined,\n targetPeerId: string | undefined,\n isChannelPost: boolean,\n isOutgoing: boolean,\n): ApiAction | undefined {\n if (action instanceof GramJs.MessageActionEmpty) {\n return undefined;\n }\n\n let call: Partial | undefined;\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.map((id) => buildApiPeerId(id, 'user'))\n : ('userId' in action && [buildApiPeerId(action.userId, 'user')]) || [];\n let targetChatId: string | 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.MessageActionInviteToGroupCall) {\n text = 'Notification.VoiceChatInvitation';\n call = {\n id: action.call.id.toString(),\n accessHash: action.call.accessHash.toString(),\n };\n translationValues.push('%action_origin%', '%target_user%');\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 call = {\n id: action.call.id.toString(),\n accessHash: action.call.accessHash.toString(),\n };\n }\n } else if (action instanceof GramJs.MessageActionBotAllowed) {\n text = 'Chat.Service.BotPermissionAllowed';\n translationValues.push(action.domain);\n } else if (action instanceof GramJs.MessageActionCustomAction) {\n text = action.message;\n } else if (action instanceof GramJs.MessageActionChatJoinedByRequest) {\n text = 'ChatService.UserJoinedGroupByRequest';\n translationValues.push('%action_origin%');\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 call,\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 = serializeBytes(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 sendAs?: ApiChat | ApiUser,\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: sendAs?.id || 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 buildLocalForwardedMessage(\n toChat: ApiChat,\n message: ApiMessage,\n serverTimeOffset: number,\n scheduledAt?: 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: scheduledAt || Math.round(Date.now() / 1000) + serverTimeOffset,\n isOutgoing: !asIncomingInChatWithSelf && toChat.type !== 'chatTypeChannel',\n senderId: currentUserId,\n sendingState: 'messageSendingStatePending',\n groupedId,\n isInAlbum,\n // Forward info doesn't get added when users forwards his own messages, also when forwarding audio\n ...(senderId !== currentUserId && !isAudio && {\n forwardInfo: {\n date: message.date,\n isChannelPost: false,\n fromChatId,\n fromMessageId,\n senderUserId: senderId,\n },\n }),\n ...(scheduledAt && { isScheduled: true }),\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_MEDIA_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_MEDIA_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 id: LOCAL_MEDIA_UPLOADING_TEMP_ID,\n duration,\n waveform: inputWaveform,\n },\n };\n } else if (mimeType.startsWith('audio/')) {\n return {\n audio: {\n id: LOCAL_MEDIA_UPLOADING_TEMP_ID,\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: String(localId),\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 ...(entity instanceof GramJs.MessageEntityMentionName && { userId: buildApiPeerId(entity.userId, 'user') }),\n ...('url' in entity && { url: entity.url }),\n };\n}\n\nfunction buildThreadInfo(\n messageReplies: GramJs.TypeMessageReplies, messageId: number, chatId: string,\n): ApiThreadInfo | undefined {\n const {\n channelId, replies, maxId, readMaxId, recentRepliers,\n } = messageReplies;\n if (!channelId) {\n return undefined;\n }\n\n const apiChannelId = buildApiPeerId(channelId, 'channel');\n if (apiChannelId === DELETED_COMMENTS_CHANNEL_ID) {\n return undefined;\n }\n\n const isPostThread = chatId !== apiChannelId;\n\n return {\n threadId: messageId,\n ...(isPostThread ? {\n chatId: apiChannelId,\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","export const getServerTime = (serverTimeOffset: number) => {\n return Math.floor(Date.now() / 1000) + serverTimeOffset;\n};\n","import BigInt from 'big-integer';\nimport { 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 buildApiPeerId, getApiChatIdFromMtpPeer, isPeerChat, isPeerUser,\n} from './peers';\nimport { omitVirtualClassFields } from './helpers';\nimport { getServerTime } from '../../../util/serverTime';\n\ntype PeerEntityApiChatFields = Omit;\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 ...((peerEntity instanceof GramJs.Chat || peerEntity instanceof GramJs.Channel) && {\n isProtected: Boolean('noforwards' in peerEntity && peerEntity.noforwards),\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: peerEntity.adminRights ? omitVirtualClassFields(peerEntity.adminRights) : undefined,\n currentUserBannedRights: peerEntity instanceof GramJs.Channel && peerEntity.bannedRights\n ? omitVirtualClassFields(peerEntity.bannedRights)\n : undefined,\n defaultBannedRights: peerEntity.defaultBannedRights\n ? omitVirtualClassFields(peerEntity.defaultBannedRights)\n : undefined,\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: string;\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: String(peerEntity.migratedTo.accessHash),\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: buildApiPeerId(preview.id, preview instanceof GramJs.User ? 'user' : 'chat'),\n type: getApiChatTypeFromPeerEntity(preview),\n title: preview instanceof GramJs.User ? getUserName(preview) : preview.title,\n ...buildApiChatFieldsFromPeerEntity(preview, isSupport),\n };\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 String(photo.photoId);\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 : buildApiPeerId(member.userId, 'user');\n\n return {\n userId,\n inviterId: 'inviterId' in member ? buildApiPeerId(member.inviterId as BigInt.BigInteger, 'user') : undefined,\n joinedDate: 'date' in member ? member.date : undefined,\n kickedByUserId: 'kickedBy' in member ? buildApiPeerId(member.kickedBy, 'user') : undefined,\n promotedByUserId: 'promotedBy' in member ? buildApiPeerId(member.promotedBy, 'user') : 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(Boolean as any);\n }\n if (participants instanceof GramJs.channels.ChannelParticipants) {\n return participants.participants.map(buildChatMember).filter(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 } else if (update.action instanceof GramJs.SendMessageChooseStickerAction) {\n action = 'lng_send_action_choose_sticker';\n } else if (update.action instanceof GramJs.SpeakingInGroupCallAction) {\n return undefined;\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(getApiChatIdFromMtpPeer).filter(Boolean as any),\n includedChatIds: filter.includePeers.map(getApiChatIdFromMtpPeer).filter(Boolean as any),\n excludedChatIds: filter.excludePeers.map(getApiChatIdFromMtpPeer).filter(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 const botId = buildApiPeerId(botInfo.userId, 'user');\n\n botCommands = botCommands.concat(botInfo.commands.map((mtpCommand) => ({\n botId,\n ...omitVirtualClassFields(mtpCommand),\n })));\n\n return botCommands;\n }, [] as ApiBotCommand[]);\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n ApiBotCommand, ApiUser, ApiUserStatus, ApiUserType,\n} from '../../types';\nimport { buildApiPeerId } from './peers';\n\nexport function buildApiUserFromFull(mtpUserFull: GramJs.users.UserFull): ApiUser {\n const {\n fullUser: {\n about, commonChatsCount, pinnedMsgId, botInfo, blocked,\n },\n users,\n } = mtpUserFull;\n\n const user = buildApiUser(users[0])!;\n\n return {\n ...user,\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(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: buildApiPeerId(id, 'user'),\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 noStatus: !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: string, botInfo: GramJs.BotInfo) {\n return botInfo.commands.map(({ command, description }) => ({\n botId,\n command,\n description,\n })) as ApiBotCommand[];\n}\n\nexport function buildApiUsersAndStatuses(mtpUsers: GramJs.TypeUser[]) {\n const userStatusesById: Record = {};\n const users: ApiUser[] = [];\n\n mtpUsers.forEach((mtpUser) => {\n const user = buildApiUser(mtpUser);\n if (!user) {\n return;\n }\n\n users.push(user);\n\n if ('status' in mtpUser) {\n userStatusesById[user.id] = buildApiUserStatus(mtpUser.status);\n }\n });\n\n return { users, userStatusesById };\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\n\nimport { ApiCountry, ApiSession, ApiWallpaper } from '../../types';\nimport { ApiPrivacySettings, ApiPrivacyKey, PrivacyVisibility } from '../../../types';\n\nimport { buildApiDocument } from './messages';\nimport { buildApiPeerId, getApiChatIdFromMtpPeer } from './peers';\nimport { flatten, 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: string[] | undefined;\n let allowChatIds: string[] | undefined;\n let blockUserIds: string[] | undefined;\n let blockChatIds: string[] | 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.map((chatId) => buildApiPeerId(chatId, 'user'));\n } else if (rule instanceof GramJs.PrivacyValueDisallowUsers) {\n blockUserIds = rule.users.map((chatId) => buildApiPeerId(chatId, 'user'));\n } else if (rule instanceof GramJs.PrivacyValueAllowChatParticipants) {\n allowChatIds = rule.chats.map((chatId) => buildApiPeerId(chatId, 'chat'));\n } else if (rule instanceof GramJs.PrivacyValueDisallowChatParticipants) {\n blockChatIds = rule.chats.map((chatId) => buildApiPeerId(chatId, 'chat'));\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\nfunction buildApiCountry(country: GramJs.help.Country, code?: GramJs.help.CountryCode) {\n const {\n hidden, iso2, defaultName, name,\n } = country;\n const { countryCode, prefixes, patterns } = code || {};\n\n return {\n isHidden: hidden,\n iso2,\n defaultName,\n name,\n countryCode,\n prefixes,\n patterns,\n };\n}\n\nexport function buildApiCountryList(countries: GramJs.help.Country[]) {\n const listByCode = flatten(\n countries\n .filter((country) => !country.hidden)\n .map((country) => (\n country.countryCodes.map((code) => buildApiCountry(country, code))\n )),\n )\n .sort((a: ApiCountry, b: ApiCountry) => (\n a.name ? a.name.localeCompare(b.name!) : a.defaultName.localeCompare(b.defaultName)\n ));\n\n const generalList = countries\n .filter((country) => !country.hidden)\n .map((country) => buildApiCountry(country))\n .sort((a, b) => (\n a.name ? a.name.localeCompare(b.name!) : a.defaultName.localeCompare(b.defaultName)\n ));\n\n return {\n phoneCodes: listByCode,\n general: generalList,\n };\n}\n","import { GroupCallParticipant, GroupCallParticipantVideo, SsrcGroup } from '../../../lib/secret-sauce';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport { ApiGroupCall } from '../../types';\nimport { getApiChatIdFromMtpPeer, isPeerUser } from './peers';\n\nexport function buildApiGroupCallParticipant(participant: GramJs.GroupCallParticipant): GroupCallParticipant {\n const {\n self, min, about, date, versioned, canSelfUnmute, justJoined, left, muted, mutedByYou, source, volume,\n volumeByAdmin, videoJoined, peer, video, presentation, raiseHandRating,\n } = participant;\n\n return {\n isSelf: self,\n isMin: min,\n canSelfUnmute,\n isLeft: left,\n isMuted: muted,\n isMutedByMe: mutedByYou,\n hasJustJoined: justJoined,\n isVolumeByAdmin: volumeByAdmin,\n isVersioned: versioned,\n isVideoJoined: videoJoined,\n about,\n source,\n raiseHandRating: raiseHandRating?.toString(),\n volume,\n date: new Date(date),\n isUser: isPeerUser(peer),\n id: getApiChatIdFromMtpPeer(peer),\n video: video ? buildApiGroupCallParticipantVideo(video) : undefined,\n presentation: presentation ? buildApiGroupCallParticipantVideo(presentation) : undefined,\n };\n}\n\nfunction buildApiGroupCallParticipantVideo(\n participantVideo: GramJs.GroupCallParticipantVideo,\n): GroupCallParticipantVideo {\n const {\n audioSource, endpoint, paused, sourceGroups,\n } = participantVideo;\n return {\n audioSource,\n endpoint,\n isPaused: paused,\n sourceGroups: sourceGroups.map(buildApiGroupCallParticipantVideoSourceGroup),\n };\n}\n\nfunction buildApiGroupCallParticipantVideoSourceGroup(\n participantVideoSourceGroup: GramJs.GroupCallParticipantVideoSourceGroup,\n): SsrcGroup {\n return {\n semantics: participantVideoSourceGroup.semantics,\n sources: participantVideoSourceGroup.sources,\n };\n}\n\nexport function buildApiGroupCall(groupCall: GramJs.TypeGroupCall): ApiGroupCall {\n const {\n id, accessHash,\n } = groupCall;\n\n if (groupCall instanceof GramJs.GroupCallDiscarded) {\n return {\n connectionState: 'discarded',\n id: id.toString(),\n accessHash: accessHash.toString(),\n participantsCount: 0,\n version: 0,\n participants: {},\n };\n }\n\n const {\n version, participantsCount, streamDcId, scheduleDate, canChangeJoinMuted, joinMuted, canStartVideo,\n scheduleStartSubscribed,\n } = groupCall;\n\n return {\n connectionState: 'disconnected',\n isLoaded: true,\n id: id.toString(),\n accessHash: accessHash.toString(),\n version,\n participantsCount,\n streamDcId,\n scheduleDate,\n canChangeJoinMuted,\n joinMuted,\n canStartVideo,\n scheduleStartSubscribed,\n participants: {},\n };\n}\n\nexport function getGroupCallId(groupCall: GramJs.TypeInputGroupCall) {\n return groupCall.id.toString();\n}\n","import { GroupCallConnectionData } from '../../lib/secret-sauce';\nimport { 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 buildChatMember,\n buildChatMembers,\n buildChatTypingStatus,\n buildAvatarHash,\n buildApiChatFromPreview,\n buildApiChatFolder,\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 {\n addMessageToLocalDb,\n addEntitiesWithPhotosToLocalDb,\n addPhotoToLocalDb,\n resolveMessageApiChatId,\n serializeBytes,\n} from './helpers';\nimport { buildApiNotifyException, buildPrivacyKey, buildPrivacyRules } from './apiBuilders/misc';\nimport { buildApiPhoto } from './apiBuilders/common';\nimport {\n buildApiGroupCall,\n buildApiGroupCallParticipant,\n getGroupCallId,\n} from './apiBuilders/calls';\nimport { buildApiPeerId, getApiChatIdFromMtpPeer } from './apiBuilders/peers';\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// Workaround for a situation when an incorrect update comes with an undefined property `adminRights`\nlet shouldIgnoreNextChannelUpdate = false;\nconst IGNORE_NEXT_CHANNEL_UPDATE_TIMEOUT = 2000;\n\nfunction dispatchUserAndChatUpdates(entities: (GramJs.TypeUser | GramJs.TypeChat)[]) {\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\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\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 ) {\n let message: ApiMessage | undefined;\n let shouldForceReply: boolean | 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 {\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 shouldForceReply = 'replyMarkup' in update.message\n && update.message?.replyMarkup instanceof GramJs.ReplyKeyboardForceReply\n && (!update.message.replyMarkup.selective || message.isMentioned);\n }\n\n // eslint-disable-next-line no-underscore-dangle\n const entities = update._entities;\n if (entities) {\n addEntitiesWithPhotosToLocalDb(entities);\n dispatchUserAndChatUpdates(entities);\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 shouldForceReply,\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 = 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 = 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 } else if (action instanceof GramJs.MessageActionGroupCall) {\n if (!action.duration && action.call) {\n onUpdate({\n '@type': 'updateGroupCallChatId',\n chatId: message.chatId,\n call: {\n id: action.call.id.toString(),\n accessHash: action.call.accessHash.toString(),\n },\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: getApiChatIdFromMtpPeer(update.peer),\n });\n } else if (update instanceof GramJs.UpdateDeleteChannelMessages) {\n const chatId = buildApiPeerId(update.channelId, 'channel');\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(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 (update instanceof GramJs.UpdateServiceNotification) {\n if (update.popup) {\n onUpdate({\n '@type': 'error',\n error: {\n message: update.message,\n },\n });\n } else {\n const currentDate = Date.now() / 1000 + serverTimeOffset;\n const message = buildApiMessageFromNotification(update, currentDate);\n\n if (isMessageWithMedia(update)) {\n addMessageToLocalDb(buildMessageFromUpdate(message.id, message.chatId, update));\n }\n\n onUpdate({\n '@type': 'updateServiceNotification',\n message,\n });\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[String(randomId)];\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: buildApiPeerId(update.channelId, 'channel'),\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: String(pollId),\n pollUpdate: apiPoll,\n });\n } else {\n const pollResults = buildPollResults(results);\n onUpdate({\n '@type': 'updateMessagePoll',\n pollId: String(pollId),\n pollUpdate: { results: pollResults },\n });\n }\n } else if (update instanceof GramJs.UpdateMessagePollVote) {\n onUpdate({\n '@type': 'updateMessagePollVote',\n pollId: String(update.pollId),\n userId: buildApiPeerId(update.userId, 'user'),\n options: update.options.map(serializeBytes),\n });\n } else if (update instanceof GramJs.UpdateChannelMessageViews) {\n onUpdate({\n '@type': 'updateMessage',\n chatId: buildApiPeerId(update.channelId, 'channel'),\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: buildApiPeerId(update.channelId, 'channel'),\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: buildApiPeerId(update.channelId, 'channel'),\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: buildApiPeerId(update.participants.chatId, 'chat'),\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: buildApiPeerId(update.chatId, 'chat'),\n addedMember,\n });\n } else if (update instanceof GramJs.UpdateChatParticipantDelete) {\n onUpdate({\n '@type': 'updateChatMembers',\n id: buildApiPeerId(update.chatId, 'chat'),\n deletedMemberId: buildApiPeerId(update.userId, 'user'),\n });\n } else if (\n update instanceof GramJs.UpdatePinnedMessages\n || update instanceof GramJs.UpdatePinnedChannelMessages\n ) {\n const chatId = update instanceof GramJs.UpdatePinnedMessages\n ? getApiChatIdFromMtpPeer(update.peer)\n : buildApiPeerId(update.channelId, 'channel');\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 ? buildApiPeerId(update.userId, 'user')\n : buildApiPeerId(update.chatId, 'chat');\n\n onUpdate({\n '@type': 'updateChatTypingStatus',\n id,\n typingStatus: buildChatTypingStatus(update, serverTimeOffset),\n });\n } else if (update instanceof GramJs.UpdateChannelUserTyping) {\n const id = buildApiPeerId(update.channelId, 'channel');\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 if (shouldIgnoreNextChannelUpdate) {\n shouldIgnoreNextChannelUpdate = false;\n return;\n }\n\n if (originRequest instanceof GramJs.messages.ToggleNoForwards) {\n shouldIgnoreNextChannelUpdate = true;\n setTimeout(() => { shouldIgnoreNextChannelUpdate = false; }, IGNORE_NEXT_CHANNEL_UPDATE_TIMEOUT);\n }\n\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: buildApiPeerId(update.channelId, 'channel'),\n });\n }\n } else if (channel instanceof GramJs.ChannelForbidden) {\n const chatId = buildApiPeerId(update.channelId, 'channel');\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: buildApiPeerId(update.channelId, 'channel'),\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 onUpdate({\n '@type': 'updateUserStatus',\n userId: buildApiPeerId(update.userId, 'user'),\n status: buildApiUserStatus(update.status),\n });\n } else if (update instanceof GramJs.UpdateUserName) {\n const apiUserId = buildApiPeerId(update.userId, 'user');\n const updatedUser = localDb.users[apiUserId];\n const user = updatedUser?.mutualContact && !updatedUser.self\n ? pick(update, ['username'])\n : pick(update, ['firstName', 'lastName', 'username']);\n\n onUpdate({\n '@type': 'updateUser',\n id: apiUserId,\n user,\n });\n } else if (update instanceof GramJs.UpdateUserPhoto) {\n const { userId, photo } = update;\n const apiUserId = buildApiPeerId(userId, 'user');\n const avatarHash = buildAvatarHash(photo);\n\n if (localDb.users[apiUserId]) {\n localDb.users[apiUserId].photo = photo;\n }\n\n onUpdate({\n '@type': 'updateUser',\n id: apiUserId,\n user: { avatarHash },\n });\n } else if (update instanceof GramJs.UpdateUserPhone) {\n const { userId, phone } = update;\n\n onUpdate({\n '@type': 'updateUser',\n id: buildApiPeerId(userId, 'user'),\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?.length) {\n _entities\n .filter((e) => e instanceof GramJs.User && !e.contact)\n .forEach((user) => {\n onUpdate({\n '@type': 'deleteUser',\n id: buildApiPeerId(user.id, 'user'),\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 (update instanceof GramJs.UpdateGroupCall) {\n onUpdate({\n '@type': 'updateGroupCall',\n call: buildApiGroupCall(update.call),\n });\n } else if (update instanceof GramJs.UpdateGroupCallConnection) {\n onUpdate({\n '@type': 'updateGroupCallConnection',\n data: JSON.parse(update.params.data) as GroupCallConnectionData,\n presentation: Boolean(update.presentation),\n });\n } else if (update instanceof GramJs.UpdateGroupCallParticipants) {\n // eslint-disable-next-line no-underscore-dangle\n const entities = update._entities;\n if (entities) {\n addEntitiesWithPhotosToLocalDb(entities);\n dispatchUserAndChatUpdates(entities);\n }\n\n onUpdate({\n '@type': 'updateGroupCallParticipants',\n groupCallId: getGroupCallId(update.call),\n participants: update.participants.map(buildApiGroupCallParticipant),\n });\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 { 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: 'Invalid phone number.',\n PHONE_CODE_INVALID: 'Invalid code.',\n PASSWORD_HASH_INVALID: 'Incorrect password.',\n PHONE_PASSWORD_FLOOD: 'Limit exceeded. Please try again later.',\n PHONE_NUMBER_BANNED: 'This phone number is banned.',\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((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((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((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((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","// 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 const contentType = response.headers.get('Content-Type');\n\n switch (type) {\n case Type.Text:\n return await response.text();\n case Type.Blob: {\n // Ignore deprecated data-uri avatars\n if (key.startsWith('avatar') && contentType && contentType.startsWith('text')) {\n return undefined;\n }\n\n const blob = await response.blob();\n\n // Safari does not return correct Content-Type header for webp images.\n if (key.startsWith('sticker')) {\n return new Blob([blob], { type: 'image/webp' });\n }\n\n const shouldRecreate = !blob.type || (!isHtmlAllowed && blob.type.includes('html'));\n // iOS Safari fails to preserve `type` in cache\n let resolvedType = blob.type || contentType;\n\n if (!(shouldRecreate && resolvedType)) {\n return blob;\n }\n\n // Prevent HTML-in-video attacks (for files that were cached before fix)\n if (!isHtmlAllowed) {\n resolvedType = resolvedType.replace(/html/gi, '');\n }\n\n return new Blob([blob], { type: resolvedType });\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 * 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./]+)(?::\\d+)?(\\?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 const 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.MessageService |\n GramJs.Document | GramJs.StickerSet | GramJs.TypeWebDocument | undefined\n );\n\n if (mediaMatch[1] === 'avatar' || mediaMatch[1] === 'profile') {\n entityType = getEntityTypeById(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];\n break;\n case 'user':\n entity = localDb.users[entityId];\n break;\n case 'msg':\n entity = localDb.messages[entityId];\n break;\n case 'sticker':\n case 'gif':\n case 'wallpaper':\n entity = localDb.documents[entityId];\n break;\n case 'photo':\n entity = localDb.photos[entityId];\n break;\n case 'stickerSet':\n entity = localDb.stickerSets[entityId];\n break;\n case 'webDocument':\n entity = localDb.webDocuments[entityId];\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 {\n switch (mediaFormat) {\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';\nimport { buildApiPeerId } from '../apiBuilders/peers';\n\nconst DEFAULT_USER_AGENT = 'Unknown UserAgent';\nconst DEFAULT_PLATFORM = 'Unknown platform';\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 {\n userAgent, platform, sessionData, isTest, isMovSupported,\n } = initialArgs;\n const session = new sessions.CallbackSession(sessionData, onSessionUpdate);\n\n // eslint-disable-next-line no-restricted-globals\n (self as any).isMovSupported = isMovSupported;\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 systemVersion: platform || DEFAULT_PLATFORM,\n appVersion: `${APP_VERSION} ${APP_CODE_NAME}`,\n useWSS: true,\n additionalDcsDisabled: IS_TEST,\n testServers: isTest,\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 // 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 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\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(\n request: T,\n shouldHandleUpdates = false,\n shouldThrow = false,\n): Promise {\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 if (shouldThrow) {\n throw err;\n }\n\n dispatchErrorUpdate(err, request);\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.users[0] instanceof GramJs.User)) {\n return;\n }\n\n const user = userFull.users[0];\n\n localDb.users[buildApiPeerId(user.id, 'user')] = user;\n const currentUser = buildApiUserFromFull(userFull);\n\n setMessageBuilderCurrentUserId(currentUser.id);\n onCurrentUserUpdate(currentUser);\n}\n\nexport function dispatchErrorUpdate(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 BigInt from 'big-integer';\nimport { 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 ApiGroupCall,\n} from '../../types';\n\nimport {\n DEBUG, ARCHIVED_FOLDER_ID, MEMBERS_LOAD_SLICE, SERVICE_NOTIFICATIONS_USER_ID,\n} from '../../../config';\nimport { invokeRequest, uploadFile } from './client';\nimport {\n buildApiChatFromDialog,\n getPeerKey,\n buildChatMembers,\n buildApiChatFromPreview,\n buildApiChatFolder,\n buildApiChatFolderFromSuggested,\n buildApiChatBotCommands,\n} from '../apiBuilders/chats';\nimport { buildApiMessage, buildMessageDraft } from '../apiBuilders/messages';\nimport { buildApiUser, buildApiUsersAndStatuses } from '../apiBuilders/users';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport {\n buildInputEntity,\n buildInputPeer,\n buildMtpMessageEntity,\n buildFilterFromApiFolder,\n isMessageWithMedia,\n buildChatBannedRights,\n buildChatAdminRights,\n} from '../gramjsBuilders';\nimport { addEntitiesWithPhotosToLocalDb, addMessageToLocalDb, addPhotoToLocalDb } from '../helpers';\nimport { buildApiPeerId, getApiChatIdFromMtpPeer } from '../apiBuilders/peers';\nimport { buildApiPhoto } from '../apiBuilders/common';\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 lastLocalServiceMessage,\n}: {\n limit: number;\n offsetDate?: number;\n archived?: boolean;\n withPinned?: boolean;\n serverTimeOffset: number;\n lastLocalServiceMessage?: ApiMessage;\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(Boolean as any),\n 'chatId',\n );\n const peersByKey: Record = {\n ...(resultPinned && preparePeers(resultPinned)),\n ...preparePeers(result),\n };\n const chats: ApiChat[] = [];\n const draftsById: Record = {};\n const replyingToById: Record = {};\n\n const dialogs = (resultPinned ? resultPinned.dialogs : []).concat(result.dialogs);\n\n const orderedPinnedIds: string[] = [];\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\n if (\n chat.id === SERVICE_NOTIFICATIONS_USER_ID\n && lastLocalServiceMessage\n && (!lastMessagesByChatId[chat.id] || lastLocalServiceMessage.date > lastMessagesByChatId[chat.id].date)\n ) {\n chat.lastMessage = lastLocalServiceMessage;\n } else {\n chat.lastMessage = lastMessagesByChatId[chat.id];\n }\n\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 chatIds = chats.map((chat) => chat.id);\n\n const { users, userStatusesById } = buildApiUsersAndStatuses((resultPinned?.users || []).concat(result.users));\n\n let totalChatCount: number;\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 userStatusesById,\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(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 lastLocalMessage,\n noLastMessage,\n}: {\n chat: ApiChat; serverTimeOffset: number; lastLocalMessage?: ApiMessage; noLastMessage?: boolean;\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 lastRemoteMessage = buildApiMessage(result.messages[0]);\n const lastMessage = lastLocalMessage && (!lastRemoteMessage || (lastLocalMessage.date > lastRemoteMessage.date))\n ? lastLocalMessage\n : lastRemoteMessage;\n\n onUpdate({\n '@type': 'updateChat',\n id,\n chat: {\n ...buildApiChatFromDialog(dialog, peerEntity, serverTimeOffset),\n ...(!noLastMessage && { 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: string): Promise<{\n fullInfo: ApiChatFullInfo;\n users?: ApiUser[];\n groupCall?: Partial;\n} | undefined> {\n const result = await invokeRequest(new GramJs.messages.GetFullChat({\n chatId: buildInputEntity(chatId) as BigInt.BigInteger,\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 call,\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 groupCallId: call?.id.toString(),\n },\n users: result.users.map(buildApiUser).filter(Boolean as any),\n groupCall: call ? {\n chatId,\n isLoaded: false,\n id: call.id.toString(),\n accessHash: call.accessHash.toString(),\n connectionState: 'disconnected',\n participantsCount: 0,\n version: 0,\n participants: {},\n } : undefined,\n };\n}\n\nasync function getFullChannelInfo(\n id: string,\n accessHash: string,\n adminRights?: ApiChatAdminRights,\n): Promise<{\n fullInfo: ApiChatFullInfo;\n users?: ApiUser[];\n groupCall?: Partial;\n } | undefined> {\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 defaultSendAs,\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 if (result?.chats?.length > 1) {\n updateLocalDb(result);\n\n const [, mtpLinkedChat] = result.chats;\n const chat = buildApiChatFromPreview(mtpLinkedChat, undefined, true);\n if (chat) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n }\n }\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: buildApiPeerId(migratedFromChatId, 'chat'),\n maxMessageId: migratedFromMaxId,\n } : undefined,\n canViewMembers: canViewParticipants,\n isPreHistoryHidden: hiddenPrehistory,\n members,\n kickedMembers,\n adminMembers,\n groupCallId: call ? String(call.id) : undefined,\n linkedChatId: linkedChatId ? buildApiPeerId(linkedChatId, 'chat') : undefined,\n botCommands,\n sendAsId: defaultSendAs ? getApiChatIdFromMtpPeer(defaultSendAs) : undefined,\n },\n users: [...(users || []), ...(bannedUsers || []), ...(adminUsers || [])],\n groupCall: call ? {\n chatId: id,\n isLoaded: false,\n id: call.id.toString(),\n accessHash: call?.accessHash.toString(),\n participants: {},\n version: 0,\n participantsCount: 0,\n connectionState: 'disconnected',\n } : undefined,\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 noLastMessage: true,\n });\n}\n\nexport async function createChannel({\n title, about = '', users,\n}: {\n title: string; about?: string; users?: ApiUser[];\n}, noErrorUpdate = false): Promise {\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 if (users?.length) {\n try {\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 }), true, noErrorUpdate);\n } catch (err) {\n // `noErrorUpdate` will cause an exception which we don't want either\n }\n }\n\n return channel;\n}\n\nexport function joinChannel({\n channelId, accessHash,\n}: {\n channelId: string; 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 BigInt.BigInteger,\n userId: buildInputEntity(user.id, user.accessHash) as GramJs.InputUser,\n }), true);\n}\n\nexport function deleteChat({\n chatId,\n}: {\n chatId: string;\n}) {\n return invokeRequest(new GramJs.messages.DeleteChat({\n chatId: buildInputEntity(chatId) as BigInt.BigInteger,\n }), true);\n}\n\nexport function leaveChannel({\n channelId, accessHash,\n}: {\n channelId: string; 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: string; 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 {\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, 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: string; 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 BigInt.BigInteger,\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,\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 BigInt.BigInteger,\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: string,\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(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 BigInt.BigInteger }), 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 const {\n photo, participantsCount, title, channel, requestNeeded, about,\n } = result;\n\n if (photo instanceof GramJs.Photo) {\n addPhotoToLocalDb(result.photo);\n }\n\n onUpdate({\n '@type': 'showInvite',\n data: {\n title,\n about,\n hash,\n participantsCount,\n isChannel: channel,\n isRequestNeeded: requestNeeded,\n ...(photo instanceof GramJs.Photo && { photo: buildApiPhoto(photo) }),\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[], noErrorUpdate = false) {\n try {\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, noErrorUpdate);\n }\n\n return Promise.all(users.map((user) => {\n return invokeRequest(new GramJs.messages.AddChatUser({\n chatId: buildInputEntity(chat.id) as BigInt.BigInteger,\n userId: buildInputEntity(user.id, user.accessHash) as GramJs.InputUser,\n }), true, noErrorUpdate);\n }));\n } catch (err) {\n // `noErrorUpdate` will cause an exception which we don't want either\n return undefined;\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 BigInt.BigInteger,\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 = {};\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 addEntitiesWithPhotosToLocalDb(result.users);\n }\n\n if ('chats' in result) {\n addEntitiesWithPhotosToLocalDb(result.chats);\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 return buildApiChatFromPreview(updates.chats[0]);\n}\n\nexport function toggleIsProtected({\n chat, isProtected,\n}: { chat: ApiChat; isProtected: boolean }) {\n const { id, accessHash } = chat;\n\n return invokeRequest(new GramJs.messages.ToggleNoForwards({\n peer: buildInputPeer(id, accessHash),\n enabled: isProtected,\n }), true);\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 {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n\n reader.onload = (e: ProgressEvent) => {\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 {\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 {\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 {\n const video = await preloadVideo(url);\n\n return Promise.race([\n pause(2000) as Promise,\n new Promise((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","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 ApiSponsoredMessage,\n ApiSendMessageAction,\n} from '../../types';\n\nimport {\n ALL_FOLDER_ID,\n DEBUG,\n PINNED_MESSAGES_LIMIT,\n SUPPORTED_IMAGE_CONTENT_TYPES,\n SUPPORTED_VIDEO_CONTENT_TYPES,\n} from '../../../config';\nimport { invokeRequest, uploadFile } from './client';\nimport {\n buildApiMessage,\n buildLocalMessage,\n buildWebPage,\n buildLocalForwardedMessage,\n buildApiSponsoredMessage,\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 buildInputReportReason,\n buildSendMessageAction,\n} from '../gramjsBuilders';\nimport localDb from '../localDb';\nimport { buildApiChatFromPreview } from '../apiBuilders/chats';\nimport { fetchFile } from '../../../util/files';\nimport {\n addEntitiesWithPhotosToLocalDb,\n addMessageToLocalDb,\n deserializeBytes,\n resolveMessageApiChatId,\n} from '../helpers';\nimport { interpolateArray } from '../../../util/waveform';\nimport { requestChatUpdate } from './chats';\nimport { buildApiPeerId, getApiChatIdFromMtpPeer } from '../apiBuilders/peers';\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(Boolean as any);\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter(Boolean as any);\n const threadInfos = messages.map(({ threadInfo }) => threadInfo).filter(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 let result;\n try {\n 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 undefined,\n true,\n );\n } catch (err) {\n const { message } = err;\n\n // When fetching messages for the bot @replies, there may be situations when the user was banned\n // in the comment group or this group was deleted\n if (message !== 'CHANNEL_PRIVATE') {\n onUpdate({\n '@type': 'error',\n error: {\n message,\n isSlowMode: false,\n hasErrorKey: true,\n },\n });\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(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 sendAs,\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 sendAs?: ApiUser | ApiChat;\n serverTimeOffset?: number;\n },\n onProgress?: ApiOnProgress,\n) {\n const localMessage = buildLocalMessage(\n chat, text, entities, replyingTo, attachment, sticker, gif, poll, groupedId, scheduledAt,\n sendAs, 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[String(randomId)] = 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 ...(sendAs && { sendAs: buildInputPeer(sendAs.id, sendAs.accessHash) }),\n }), true);\n })();\n\n return queue;\n}\n\nconst groupedUploads: Record;\n}> = {};\n\nfunction sendGroupedMedia(\n {\n chat,\n text,\n entities,\n replyingTo,\n attachment,\n groupedId,\n isSilent,\n scheduledAt,\n sendAs,\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 sendAs?: ApiUser | ApiChat;\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 ...(sendAs && { sendAs: buildInputPeer(sendAs.id, sendAs.accessHash) }),\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 = {\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 (SUPPORTED_IMAGE_CONTENT_TYPES.has(mimeType)) {\n return new GramJs.InputMediaUploadedPhoto({ file: inputFile });\n }\n\n if (SUPPORTED_VIDEO_CONTENT_TYPES.has(mimeType)) {\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 supportsStreaming: true,\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 sendMessageAction({\n peer, threadId, action,\n}: {\n peer: ApiChat | ApiUser; threadId?: number; action: ApiSendMessageAction;\n}) {\n const gramAction = buildSendMessageAction(action);\n if (!gramAction) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('Unsupported message action', action);\n }\n return undefined;\n }\n\n const result = await invokeRequest(new GramJs.messages.SetTyping({\n peer: buildInputPeer(peer.id, peer.accessHash),\n topMsgId: threadId,\n action: gramAction,\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, noLastMessage: true });\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 undefined;\n }\n\n const discussionChatId = resolveMessageApiChatId(topMessageResult.messages[0]);\n if (!discussionChatId) {\n return undefined;\n }\n\n onUpdate({\n '@type': 'updateThreadInfo',\n chatId: discussionChatId,\n threadId,\n threadInfo: {\n threadId,\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(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 return {\n discussionChatId,\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.InputMessagesFilterRoundVoice();\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(Boolean as any);\n const users = result.users.map(buildApiUser).filter(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.InputMessagesFilterRoundVoice();\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(Boolean as any);\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const messages = result.messages.map(buildApiMessage).filter(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(deserializeBytes),\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: deserializeBytes(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(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 isSilent,\n scheduledAt,\n sendAs,\n}: {\n fromChat: ApiChat;\n toChat: ApiChat;\n messages: ApiMessage[];\n serverTimeOffset: number;\n isSilent?: boolean;\n scheduledAt?: number;\n sendAs?: ApiUser | ApiChat;\n}) {\n const messageIds = messages.map(({ id }) => id);\n const randomIds = messages.map(generateRandomBigInt);\n\n messages.forEach((message, index) => {\n const localMessage = buildLocalForwardedMessage(toChat, message, serverTimeOffset, scheduledAt);\n localDb.localMessages[String(randomIds[index])] = localMessage;\n\n onUpdate({\n '@type': localMessage.isScheduled ? 'newScheduledMessage' : '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 ...(isSilent && { sil2ent: isSilent }),\n ...(scheduledAt && { scheduleDate: scheduledAt }),\n ...(sendAs && { sendAs: buildInputPeer(sendAs.id, sendAs.accessHash) }),\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 }: { chat: ApiChat }) {\n const { id, accessHash } = chat;\n\n const result = await invokeRequest(new GramJs.messages.GetScheduledHistory({\n peer: buildInputPeer(id, accessHash),\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(Boolean as any);\n\n return {\n messages,\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 | GramJs.messages.SponsoredMessages\n)) {\n result.users.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[buildApiPeerId(user.id, 'user')] = user;\n }\n });\n\n result.chats.forEach((chat) => {\n if (chat instanceof GramJs.Chat || chat instanceof GramJs.Channel) {\n localDb.chats[buildApiPeerId(chat.id, chat instanceof GramJs.Chat ? 'chat' : 'channel')] = 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(Boolean as any);\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter(Boolean as any);\n\n return {\n messages,\n users,\n chats,\n };\n}\n\nexport async function fetchSeenBy({ chat, messageId }: { chat: ApiChat; messageId: number }) {\n const result = await invokeRequest(new GramJs.messages.GetMessageReadParticipants({\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: messageId,\n }));\n\n return result ? result.map(String) : undefined;\n}\n\nexport async function fetchSendAs({\n chat,\n}: {\n chat: ApiChat;\n}) {\n const result = await invokeRequest(new GramJs.channels.GetSendAs({\n peer: buildInputPeer(chat.id, chat.accessHash),\n }));\n\n if (!result) {\n return undefined;\n }\n\n addEntitiesWithPhotosToLocalDb(result.users);\n addEntitiesWithPhotosToLocalDb(result.chats);\n\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter(Boolean as any);\n\n return {\n users,\n chats,\n ids: result.peers.map(getApiChatIdFromMtpPeer),\n };\n}\n\nexport function saveDefaultSendAs({\n sendAs, chat,\n}: {\n sendAs: ApiChat | ApiUser; chat: ApiChat;\n}) {\n return invokeRequest(new GramJs.messages.SaveDefaultSendAs({\n peer: buildInputPeer(chat.id, chat.accessHash),\n sendAs: buildInputPeer(sendAs.id, sendAs.accessHash),\n }));\n}\n\nexport async function fetchSponsoredMessages({ chat }: { chat: ApiChat }) {\n const result = await invokeRequest(new GramJs.channels.GetSponsoredMessages({\n channel: buildInputPeer(chat.id, chat.accessHash),\n }));\n\n if (!result || !result.messages.length) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiSponsoredMessage).filter(Boolean as any);\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter(Boolean as any);\n\n return {\n messages,\n users,\n chats,\n };\n}\n\nexport async function viewSponsoredMessage({ chat, random }: { chat: ApiChat; random: string }) {\n await invokeRequest(new GramJs.channels.ViewSponsoredMessage({\n channel: buildInputPeer(chat.id, chat.accessHash),\n randomId: deserializeBytes(random),\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 { COMMON_CHATS_LIMIT, PROFILE_PHOTOS_LIMIT } from '../../../config';\nimport { invokeRequest } from './client';\nimport { searchMessagesLocal } from './messages';\nimport {\n buildInputEntity,\n buildInputPeer,\n buildInputContact,\n buildMtpPeerId,\n getEntityTypeById,\n} from '../gramjsBuilders';\nimport { buildApiUser, buildApiUserFromFull, buildApiUsersAndStatuses } from '../apiBuilders/users';\nimport { buildApiChatFromPreview } from '../apiBuilders/chats';\nimport { buildApiPhoto } from '../apiBuilders/common';\nimport localDb from '../localDb';\nimport { addEntitiesWithPhotosToLocalDb, addPhotoToLocalDb } from '../helpers';\nimport { buildApiPeerId } from '../apiBuilders/peers';\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: string;\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 fetchCommonChats(id: string, accessHash?: string, maxId?: string) {\n const commonChats = await invokeRequest(new GramJs.messages.GetCommonChats({\n userId: buildInputEntity(id, accessHash) as GramJs.InputUser,\n maxId: maxId ? buildMtpPeerId(maxId, getEntityTypeById(maxId)) : undefined,\n limit: COMMON_CHATS_LIMIT,\n }));\n\n if (!commonChats) {\n return undefined;\n }\n\n updateLocalDb(commonChats);\n\n const chatIds: string[] = [];\n const chats: ApiChat[] = [];\n\n commonChats.chats.forEach((mtpChat) => {\n const chat = buildApiChatFromPreview(mtpChat);\n\n if (chat) {\n chats.push(chat);\n chatIds.push(chat.id);\n }\n });\n\n return { chats, chatIds, isFullyLoaded: chatIds.length < COMMON_CHATS_LIMIT };\n}\n\nexport async function fetchNearestCountry() {\n const dcInfo = await invokeRequest(new GramJs.help.GetNearestDc());\n\n return dcInfo?.country;\n}\n\nexport async function fetchTopUsers() {\n const topPeers = await invokeRequest(new GramJs.contacts.GetTopPeers({\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 ids,\n users,\n };\n}\n\nexport async function fetchContactList() {\n const result = await invokeRequest(new GramJs.contacts.GetContacts({ hash: BigInt('0') }));\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[buildApiPeerId(user.id, 'user')] = user;\n }\n });\n\n return {\n users: result.users.map(buildApiUser).filter(Boolean as any),\n chats: result.users.map((user) => buildApiChatFromPreview(user)).filter(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[buildApiPeerId(user.id, 'user')] = user;\n }\n });\n\n return buildApiUsersAndStatuses(result);\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 function addContact({\n id,\n accessHash,\n phoneNumber = '',\n firstName = '',\n lastName = '',\n}: {\n id: string;\n accessHash?: string;\n phoneNumber?: string;\n firstName?: string;\n lastName?: string;\n}) {\n return invokeRequest(new GramJs.contacts.AddContact({\n id: buildInputEntity(id, accessHash) as GramJs.InputUser,\n firstName,\n lastName,\n phone: phoneNumber,\n }), true);\n}\n\nexport async function deleteUser({\n id,\n accessHash,\n}: {\n id: string;\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(Boolean as any),\n users,\n };\n}\n\nfunction updateLocalDb(result: (GramJs.photos.Photos | GramJs.photos.PhotosSlice | GramJs.messages.Chats)) {\n if ('chats' in result) {\n addEntitiesWithPhotosToLocalDb(result.chats);\n }\n\n if ('photos' in result) {\n result.photos.forEach(addPhotoToLocalDb);\n }\n}\n","import BigInt from 'big-integer';\nimport { 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 = '0' }: { hash?: string }) {\n const allStickers = await invokeRequest(new GramJs.messages.GetAllStickers({ hash: BigInt(hash) }));\n\n if (!allStickers || allStickers instanceof GramJs.messages.AllStickersNotModified) {\n return undefined;\n }\n\n allStickers.sets.forEach((stickerSet) => {\n if (stickerSet.thumbs?.length) {\n localDb.stickerSets[String(stickerSet.id)] = stickerSet;\n }\n });\n\n return {\n hash: String(allStickers.hash),\n sets: allStickers.sets.map(buildStickerSet),\n };\n}\n\nexport async function fetchRecentStickers({ hash = '0' }: { hash?: string }) {\n const result = await invokeRequest(new GramJs.messages.GetRecentStickers({ hash: BigInt(hash) }));\n\n if (!result || result instanceof GramJs.messages.RecentStickersNotModified) {\n return undefined;\n }\n\n return {\n hash: String(result.hash),\n stickers: processStickerResult(result.stickers.slice(0, RECENT_STICKERS_LIMIT)),\n };\n}\n\nexport async function fetchFavoriteStickers({ hash = '0' }: { hash?: string }) {\n const result = await invokeRequest(new GramJs.messages.GetFavedStickers({ hash: BigInt(hash) }));\n\n if (!result || result instanceof GramJs.messages.FavedStickersNotModified) {\n return undefined;\n }\n\n return {\n hash: String(result.hash),\n stickers: processStickerResult(result.stickers),\n };\n}\n\nexport async function fetchFeaturedStickers({ hash = '0' }: { hash?: string }) {\n const result = await invokeRequest(new GramJs.messages.GetFeaturedStickers({ hash: BigInt(hash) }));\n\n if (!result || result instanceof GramJs.messages.FeaturedStickersNotModified) {\n return undefined;\n }\n\n return {\n hash: String(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(\n { stickerSetShortName, stickerSetId, accessHash }:\n { stickerSetShortName?: string; stickerSetId?: string; accessHash: string },\n) {\n const result = await invokeRequest(new GramJs.messages.GetStickerSet({\n stickerset: stickerSetId\n ? buildInputStickerSet(stickerSetId, accessHash)\n : buildInputStickerSetShortName(stickerSetShortName!),\n }));\n\n if (!(result instanceof GramJs.messages.StickerSet)) {\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 instanceof GramJs.messages.StickerSet)) {\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 = '0' }: { query: string; hash?: string }) {\n const result = await invokeRequest(new GramJs.messages.SearchStickerSets({\n q: query,\n hash: BigInt(hash),\n }));\n\n if (!result || result instanceof GramJs.messages.FoundStickerSetsNotModified) {\n return undefined;\n }\n\n return {\n hash: String(result.hash),\n sets: result.sets.map(buildStickerSetCovered),\n };\n}\n\nexport async function fetchSavedGifs({ hash = '0' }: { hash?: string }) {\n const result = await invokeRequest(new GramJs.messages.GetSavedGifs({ hash: BigInt(hash) }));\n\n if (!result || result instanceof GramJs.messages.SavedGifsNotModified) {\n return undefined;\n }\n\n return {\n hash: String(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(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?: string }) {\n const result = await invokeRequest(new GramJs.messages.GetStickers({\n emoticon: emoji,\n hash: BigInt(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: String(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),\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(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(Boolean as any);\n return acc;\n }, {} as Record);\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(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, usageLimit, expireDate,\n}: {\n chat: ApiChat; usageLimit?: number; expireDate?: number;\n}) {\n const result = await invokeRequest(new GramJs.messages.ExportChatInvite({\n peer: buildInputPeer(chat.id, chat.accessHash),\n usageLimit,\n expireDate,\n }));\n\n if (!result) {\n return undefined;\n }\n\n onUpdate({\n '@type': 'updateChatFullInfo',\n id: chat.id,\n fullInfo: {\n inviteLink: result.link,\n },\n });\n\n return result.link;\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((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 { JoinGroupCallPayload } from '../../../lib/secret-sauce';\nimport {\n ApiChat, ApiUser, OnApiUpdate, ApiGroupCall,\n} from '../../types';\nimport { Api as GramJs } from '../../../lib/gramjs';\n\nimport { invokeRequest } from './client';\nimport { buildInputGroupCall, buildInputPeer, generateRandomInt } from '../gramjsBuilders';\nimport {\n buildApiGroupCall,\n buildApiGroupCallParticipant,\n\n} from '../apiBuilders/calls';\nimport { buildApiUser } from '../apiBuilders/users';\nimport { buildApiChatFromPreview } from '../apiBuilders/chats';\nimport { addEntitiesWithPhotosToLocalDb } from '../helpers';\nimport { GROUP_CALL_PARTICIPANTS_LIMIT } from '../../../config';\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function getGroupCall({\n call,\n}: {\n call: Partial;\n}) {\n const result = await invokeRequest(new GramJs.phone.GetGroupCall({\n call: buildInputGroupCall(call),\n }));\n\n if (!result) {\n return undefined;\n }\n\n addEntitiesWithPhotosToLocalDb(result.users);\n addEntitiesWithPhotosToLocalDb(result.chats);\n\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter(Boolean as any);\n\n return {\n groupCall: buildApiGroupCall(result.call),\n users,\n chats,\n };\n}\n\nexport function discardGroupCall({\n call,\n}: {\n call: ApiGroupCall;\n}) {\n return invokeRequest(new GramJs.phone.DiscardGroupCall({\n call: buildInputGroupCall(call),\n }), true);\n}\n\nexport function editGroupCallParticipant({\n call, participant, muted, presentationPaused, videoStopped, videoPaused, volume,\n raiseHand,\n}: {\n call: ApiGroupCall; participant: ApiUser; muted?: boolean; presentationPaused?: boolean;\n videoStopped?: boolean; videoPaused?: boolean; raiseHand?: boolean; volume?: number;\n}) {\n return invokeRequest(new GramJs.phone.EditGroupCallParticipant({\n call: buildInputGroupCall(call),\n participant: buildInputPeer(participant.id, participant.accessHash),\n ...(videoStopped !== undefined && { videoStopped }),\n ...(videoPaused !== undefined && { videoPaused }),\n ...(muted !== undefined && { muted }),\n ...(presentationPaused !== undefined && { presentationPaused }),\n ...(raiseHand !== undefined && { raiseHand }),\n ...(volume !== undefined && { volume }),\n }), true);\n}\n\nexport function editGroupCallTitle({\n groupCall, title,\n}: {\n groupCall: ApiGroupCall; title: string;\n}) {\n return invokeRequest(new GramJs.phone.EditGroupCallTitle({\n title,\n call: buildInputGroupCall(groupCall),\n }), true);\n}\n\nexport async function exportGroupCallInvite({\n call, canSelfUnmute,\n}: {\n call: ApiGroupCall; canSelfUnmute: boolean;\n}) {\n const result = await invokeRequest(new GramJs.phone.ExportGroupCallInvite({\n canSelfUnmute: canSelfUnmute || undefined,\n call: buildInputGroupCall(call),\n }));\n\n if (!result) {\n return undefined;\n }\n\n return result.link;\n}\n\nexport async function fetchGroupCallParticipants({\n call, offset,\n}: {\n call: ApiGroupCall; offset?: string;\n}) {\n const result = await invokeRequest(new GramJs.phone.GetGroupParticipants({\n call: buildInputGroupCall(call),\n ids: [],\n sources: [],\n offset: offset || '',\n limit: GROUP_CALL_PARTICIPANTS_LIMIT,\n }));\n\n if (!result) {\n return undefined;\n }\n\n addEntitiesWithPhotosToLocalDb(result.users);\n addEntitiesWithPhotosToLocalDb(result.chats);\n\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter(Boolean as any);\n\n onUpdate({\n '@type': 'updateGroupCallParticipants',\n groupCallId: call.id,\n participants: result.participants.map(buildApiGroupCallParticipant),\n nextOffset: result.nextOffset,\n });\n\n return {\n users, chats,\n };\n}\n\nexport function leaveGroupCall({\n call,\n}: {\n call: ApiGroupCall;\n}) {\n return invokeRequest(new GramJs.phone.LeaveGroupCall({\n call: buildInputGroupCall(call),\n }), true);\n}\n\nexport async function joinGroupCall({\n call, inviteHash, params,\n}: {\n call: ApiGroupCall; inviteHash?: string; params: JoinGroupCallPayload;\n}) {\n const result = await invokeRequest(new GramJs.phone.JoinGroupCall({\n call: buildInputGroupCall(call),\n joinAs: new GramJs.InputPeerSelf(),\n muted: true,\n videoStopped: true,\n params: new GramJs.DataJSON({\n data: JSON.stringify(params),\n }),\n inviteHash,\n }), true);\n\n if (!result) return undefined;\n\n if (result instanceof GramJs.Updates) {\n const update = result.updates.find((u) => u instanceof GramJs.UpdateGroupCall);\n if (!(update instanceof GramJs.UpdateGroupCall)) return undefined;\n\n return buildApiGroupCall(update.call);\n }\n\n return undefined;\n}\n\nexport async function createGroupCall({\n peer,\n}: {\n peer: ApiChat;\n}) {\n const randomId = generateRandomInt();\n const result = await invokeRequest(new GramJs.phone.CreateGroupCall({\n peer: buildInputPeer(peer.id, peer.accessHash),\n randomId,\n }), true);\n\n if (!result) return undefined;\n\n if (result instanceof GramJs.Updates) {\n const update = result.updates[0];\n if (update instanceof GramJs.UpdateGroupCall) {\n return buildApiGroupCall(update.call);\n }\n }\n\n return undefined;\n}\n\nexport function joinGroupCallPresentation({\n call, params,\n}: {\n call: ApiGroupCall; params: JoinGroupCallPayload;\n}) {\n return invokeRequest(new GramJs.phone.JoinGroupCallPresentation({\n call: buildInputGroupCall(call),\n params: new GramJs.DataJSON({\n data: JSON.stringify(params),\n }),\n }), true);\n}\n\nexport function toggleGroupCallStartSubscription({\n call, subscribed,\n}: {\n call: ApiGroupCall; subscribed: boolean;\n}) {\n return invokeRequest(new GramJs.phone.ToggleGroupCallStartSubscription({\n call: buildInputGroupCall(call),\n subscribed,\n }), true);\n}\n\nexport function leaveGroupCallPresentation({\n call,\n}: {\n call: ApiGroupCall;\n}) {\n return invokeRequest(new GramJs.phone.LeaveGroupCallPresentation({\n call: buildInputGroupCall(call),\n }), true);\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, InputPrivacyRules, LangCode } from '../../../types';\n\nimport { BLOCKED_LIST_LIMIT, DEFAULT_LANG_PACK, LANG_PACKS } from '../../../config';\nimport {\n buildApiWallpaper, buildApiSession, buildPrivacyRules, buildApiNotifyException, buildApiCountryList,\n} from '../apiBuilders/misc';\n\nimport { buildApiUser } from '../apiBuilders/users';\nimport { buildApiChatFromPreview } from '../apiBuilders/chats';\nimport { buildInputPrivacyKey, buildInputPeer, buildInputEntity } from '../gramjsBuilders';\nimport { invokeRequest, uploadFile, getClient } from './client';\nimport { omitVirtualClassFields } from '../apiBuilders/helpers';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport { getServerTime } from '../../../util/serverTime';\nimport { buildApiPeerId, getApiChatIdFromMtpPeer } from '../apiBuilders/peers';\nimport localDb from '../localDb';\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() {\n const result = await invokeRequest(new GramJs.account.GetWallPapers({ hash: BigInt('0') }));\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 wallpapers: filteredWallpapers.map(buildApiWallpaper).filter(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(Boolean as any),\n chats: result.chats.map((chat) => buildApiChatFromPreview(chat, undefined, true)).filter(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: string, accessHash?: string) {\n return invokeRequest(new GramJs.contacts.Block({\n id: buildInputPeer(chatOrUserId, accessHash),\n }));\n}\n\nexport function unblockContact(chatOrUserId: string, 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 {\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(Boolean as any)\n .map((result) => {\n return buildCollectionByKey(result.strings.map(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: InputPrivacyRules,\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 }) => buildInputEntity(id, accessHash) as GramJs.InputUser),\n }));\n }\n if (rules.allowedChats) {\n privacyRules.push(new GramJs.InputPrivacyValueAllowChatParticipants({\n chats: rules.allowedChats.map(({ id }) => buildInputEntity(id) as BigInt.BigInteger),\n }));\n }\n if (rules.blockedUsers) {\n privacyRules.push(new GramJs.InputPrivacyValueDisallowUsers({\n users: rules.blockedUsers.map(({ id, accessHash }) => buildInputEntity(id, accessHash) as GramJs.InputUser),\n }));\n }\n if (rules.blockedChats) {\n privacyRules.push(new GramJs.InputPrivacyValueDisallowChatParticipants({\n chats: rules.blockedChats.map(({ id }) => buildInputEntity(id) as BigInt.BigInteger),\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[buildApiPeerId(user.id, 'user')] = user;\n }\n });\n\n result.chats.forEach((chat) => {\n if (chat instanceof GramJs.Chat || chat instanceof GramJs.Channel) {\n localDb.chats[buildApiPeerId(chat.id, chat instanceof GramJs.Chat ? 'chat' : 'channel')] = chat;\n }\n });\n}\n\nexport async function fetchCountryList({ langCode = 'en' }: { langCode?: LangCode }) {\n const countryList = await invokeRequest(new GramJs.help.GetCountriesList({\n langCode,\n }));\n\n if (!(countryList instanceof GramJs.help.CountriesList)) {\n return undefined;\n }\n return buildApiCountryList(countryList.countries);\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, generateRandomBigInt } from '../gramjsBuilders';\nimport { buildApiUser } from '../apiBuilders/users';\nimport { buildApiBotInlineMediaResult, buildApiBotInlineResult, buildBotSwitchPm } from '../apiBuilders/bots';\nimport { buildApiChatFromPreview } from '../apiBuilders/chats';\nimport { addEntitiesWithPhotosToLocalDb, addUserToLocalDb, deserializeBytes } from '../helpers';\n\nexport function init() {\n}\n\nexport function answerCallbackButton(\n {\n chatId, accessHash, messageId, data,\n }: {\n chatId: string; 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: deserializeBytes(data),\n }));\n}\n\nexport async function fetchTopInlineBots() {\n const topPeers = await invokeRequest(new GramJs.contacts.GetTopPeers({\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(Boolean as any);\n const ids = users.map(({ id }) => id);\n\n return {\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 addEntitiesWithPhotosToLocalDb(result.users);\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(Boolean as any),\n results: processInlineBotResult(String(result.queryId), result.results),\n };\n}\n\nexport async function sendInlineBotResult({\n chat, resultId, queryId, replyingTo, sendAs,\n}: {\n chat: ApiChat;\n resultId: string;\n queryId: string;\n replyingTo?: number;\n sendAs?: ApiUser | ApiChat;\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 ...(sendAs && { sendAs: buildInputPeer(sendAs.id, sendAs.accessHash) }),\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 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: String(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 { init as initCalls } from './methods/calls';\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 initCalls(handleUpdate);\n\n await initClient(handleUpdate, initialArgs);\n}\n\nexport function callApi(fnName: T, ...args: MethodArgs): MethodResponse {\n // @ts-ignore\n return methods[fnName](...args) as MethodResponse;\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","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();\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, 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EF, 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;\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\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\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 testServers: 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 // 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}\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, this._args.testServers,\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}\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}\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 this._args.testServers,\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}\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 _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 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 // 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}\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 // 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 // eslint-disable-next-line no-return-await\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);\n phoneCode: (isCodeViaApp?: boolean) => Promise;\n password: (hint?: string) => Promise;\n firstAndLastNames: () => Promise<[string, string?]>;\n qrCode: (qrCode: { token: Buffer; expires: number }) => Promise;\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 {\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 {\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((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 await 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 {\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;\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[] = [];\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 {\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 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('./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 this._queue.push(state);\n this.setReady(true);\n // 1658238041=MsgsAck, we don't care about MsgsAck here because they never resolve anyway.\n if (state && state.request.CONSTRUCTOR_ID !== 1658238041) {\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, testServers) {\n if (port === 443) {\n return `wss://${ip}:${port}/apiws${testServers ? '_test' : ''}`;\n } else {\n return `ws://${ip}:${port}/apiws${testServers ? '_test' : ''}`;\n }\n }\n\n connect(port, ip, testServers = false) {\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, testServers);\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 await mutex.runExclusive(async () => {\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 });\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 fingerprint: bigInt('-5595554452916591101'),\n n: bigInt(\n '2534288944884041556497168959071347320689884775908477905258202659454602246385394058588521595116849196570822' +\n '26493991806038180742006204637761354248846321625124031637930839216416315647409595294193595958529411668489405859523' +\n '37613333022396096584117954892216031229237302943701877588456738335398602461675225081791820393153757504952636234951' +\n '32323782003654358104782690612092797248736680529211579223142368426126233039432475078545094258975175539015664775146' +\n '07193514399690599495696153028090507215003302390050778898553239175099482557220816446894421272976054225797071426466' +\n '60768825302832201908302295573257427896031830742328565032949',\n ),\n e: 65537,\n },\n];\n\nexport const _serverKeys = new Map();\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 { RPCError } = require('../errors');\n\nconst 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 {\n UpdateConnectionState,\n UpdateServerTimeOffset,\n} = 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 * 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 * 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}\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}\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}\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 if (this._last_acks.length >= 10) {\n this._last_acks.shift();\n }\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._handleBadAuthKey();\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 // `RPCError` errors except for 'AUTH_KEY_UNREGISTERED' should be handled by the client\n if (e instanceof RPCError) {\n if (e.message === 'AUTH_KEY_UNREGISTERED') {\n // 'AUTH_KEY_UNREGISTERED' for the main sender is thrown when unauthorized and should be ignored\n this._handleBadAuthKey(true);\n }\n } else {\n this._log.error('Unhandled error while receiving data');\n this._log.error(e);\n }\n }\n }\n }\n\n _handleBadAuthKey(shouldSkipForMain) {\n if (shouldSkipForMain && this._isMainSender) {\n return;\n }\n\n this._log.warn(`Broken authorization key for dc ${this._dcId}, resetting...`);\n\n if (this._isMainSender && this._updateCallback) {\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.broken));\n } else if (!this._isMainSender && this._onConnectionBreak) {\n this._onConnectionBreak(this._dcId);\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}\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}\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 throw error;\n } else {\n try {\n const reader = new BinaryReader(result.body);\n const read = state.request.readResult(reader);\n state.resolve(read);\n } catch (err) {\n state.reject(err);\n throw err;\n }\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}\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}\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}\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}\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}\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}\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}\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}\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}\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 = FutureSalts;\n * @param message\n * @returns {Promise}\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}\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}\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)\n .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 this._connection._testServers,\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.msgIds = [];\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 this.msgIds = [];\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 // if we get a duplicate message id we should ignore it.\n if (this.msgIds.includes(remoteMsgId.toString())) {\n throw new SecurityError('Duplicate msgIds');\n }\n // we only store the latest 500 message ids from the server\n if (this.msgIds.length > 500) {\n this.msgIds.shift();\n }\n this.msgIds.push(remoteMsgId.toString());\n\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, testServers) {\n this._ip = ip;\n this._port = port;\n this._dcId = dcId;\n this._log = loggers;\n this._testServers = testServers;\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._testServers);\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 _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 = 136;\nconst tlobjects = {};\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#35a95cb9 chat_id:long = InputPeer;\ninputPeerUser#dde8a54c user_id:long access_hash:long = InputPeer;\ninputPeerChannel#27bcbbfc channel_id:long access_hash:long = InputPeer;\ninputPeerUserFromMessage#a87b0a1c peer:InputPeer msg_id:int user_id:long = InputPeer;\ninputPeerChannelFromMessage#bd2a0840 peer:InputPeer msg_id:int channel_id:long = InputPeer;\ninputUserEmpty#b98886cf = InputUser;\ninputUserSelf#f7c1b13f = InputUser;\ninputUser#f21158c6 user_id:long access_hash:long = InputUser;\ninputUserFromMessage#1da448e2 peer:InputPeer msg_id:int user_id:long = 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 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 stickers:flags.0?Vector 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 solution:flags.1?string solution_entities:flags.1?Vector = 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#598a92a flags:# call:InputGroupCall time_ms:long scale:int video_channel:flags.0?int video_quality:flags.0?int = InputFileLocation;\npeerUser#59511722 user_id:long = Peer;\npeerChat#36c6019a chat_id:long = Peer;\npeerChannel#a2a5371e channel_id:long = 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#d3bc4b7a id:long = User;\nuser#3ff6ecb0 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:long 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 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#29562865 id:long = Chat;\nchat#41cbf256 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 noforwards:flags.25?true id:long 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#6592a1a7 id:long title:string = Chat;\nchannel#8261ac61 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 noforwards:flags.27?true id:long access_hash:flags.13?long title:string username:flags.6?string photo:ChatPhoto date:int restriction_reason:flags.9?Vector admin_rights:flags.14?ChatAdminRights banned_rights:flags.15?ChatBannedRights default_banned_rights:flags.18?ChatBannedRights participants_count:flags.17?int = Chat;\nchannelForbidden#17d493d5 flags:# broadcast:flags.5?true megagroup:flags.8?true id:long access_hash:long title:string until_date:flags.16?int = Chat;\nchatFull#d18ee226 flags:# can_set_username:flags.7?true has_scheduled:flags.8?true id:long about:string participants:ChatParticipants chat_photo:flags.2?Photo notify_settings:PeerNotifySettings exported_invite:flags.13?ExportedChatInvite bot_info:flags.3?Vector 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 theme_emoticon:flags.16?string requests_pending:flags.17?int recent_requesters:flags.17?Vector available_reactions:flags.18?Vector = ChatFull;\nchannelFull#e13c3d20 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:long 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 migrated_from_chat_id:flags.4?long 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?long 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 groupcall_default_join_as:flags.26?Peer theme_emoticon:flags.27?string requests_pending:flags.28?int recent_requesters:flags.28?Vector default_send_as:flags.29?Peer available_reactions:flags.30?Vector = ChatFull;\nchatParticipant#c02d4007 user_id:long inviter_id:long date:int = ChatParticipant;\nchatParticipantCreator#e46bcee4 user_id:long = ChatParticipant;\nchatParticipantAdmin#a0933f5b user_id:long inviter_id:long date:int = ChatParticipant;\nchatParticipantsForbidden#8763d3e1 flags:# chat_id:long self_participant:flags.0?ChatParticipant = ChatParticipants;\nchatParticipants#3cbc93f8 chat_id:long participants:Vector 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#38116ee0 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 noforwards:flags.26?true id:int from_id:flags.8?Peer peer_id:Peer fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?long reply_to:flags.3?MessageReplyHeader date:int message:string media:flags.9?MessageMedia reply_markup:flags.6?ReplyMarkup entities:flags.7?Vector 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 reactions:flags.20?MessageReactions restriction_reason:flags.22?Vector 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#70322949 phone_number:string first_name:string last_name:string vcard:string user_id:long = 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#bd47cbad title:string users:Vector = MessageAction;\nmessageActionChatEditTitle#b5a1ce5a title:string = MessageAction;\nmessageActionChatEditPhoto#7fcb13a8 photo:Photo = MessageAction;\nmessageActionChatDeletePhoto#95e3fbef = MessageAction;\nmessageActionChatAddUser#15cefd00 users:Vector = MessageAction;\nmessageActionChatDeleteUser#a43f30cc user_id:long = MessageAction;\nmessageActionChatJoinedByLink#31224c3 inviter_id:long = MessageAction;\nmessageActionChannelCreate#95d2ac92 title:string = MessageAction;\nmessageActionChatMigrateTo#e1037f92 channel_id:long = MessageAction;\nmessageActionChannelMigrateFrom#ea3948e9 title:string chat_id:long = 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 credentials:SecureCredentialsEncrypted = MessageAction;\nmessageActionSecureValuesSent#d95c6154 types:Vector = 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#502f92f7 call:InputGroupCall users:Vector = MessageAction;\nmessageActionSetMessagesTTL#aa1afbfd period:int = MessageAction;\nmessageActionGroupCallScheduled#b3a07661 call:InputGroupCall schedule_date:int = MessageAction;\nmessageActionSetChatTheme#aa786345 emoticon:string = MessageAction;\nmessageActionChatJoinedByRequest#ebbca3cb = 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 video_sizes:flags.1?Vector 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 = 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#33fb7bb8 flags:# setup_password_required:flags.1?true otherwise_relogin_days:flags.1?int tmp_sessions:flags.0?int user:User = auth.Authorization;\nauth.authorizationSignUpRequired#44747e9a flags:# terms_of_service:flags.0?help.TermsOfService = auth.Authorization;\nauth.exportedAuthorization#b434e2b8 id:long 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#a518110d 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 request_chat_broadcast:flags.10?true geo_distance:flags.6?int request_chat_title:flags.9?string request_chat_date:flags.9?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#cf366521 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 id:long 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 theme_emoticon:flags.15?string private_forward_name:flags.16?string = UserFull;\ncontact#145ade0b user_id:long mutual:Bool = Contact;\nimportedContact#c13e3c50 user_id:long client_id:long = ImportedContact;\ncontactStatus#16d9703b user_id:long status:UserStatus = ContactStatus;\ncontacts.contactsNotModified#b74ba9d2 = contacts.Contacts;\ncontacts.contacts#eae87e42 contacts:Vector saved_count:int users:Vector = contacts.Contacts;\ncontacts.importedContacts#77d01c3b imported:Vector popular_invites:Vector retry_contacts:Vector users:Vector = contacts.ImportedContacts;\ncontacts.blocked#ade1591 blocked:Vector chats:Vector users:Vector = contacts.Blocked;\ncontacts.blockedSlice#e1664194 count:int blocked:Vector chats:Vector users:Vector = contacts.Blocked;\nmessages.dialogs#15ba6c40 dialogs:Vector messages:Vector chats:Vector users:Vector = messages.Dialogs;\nmessages.dialogsSlice#71e094f3 count:int dialogs:Vector messages:Vector chats:Vector users:Vector = messages.Dialogs;\nmessages.dialogsNotModified#f0e3e596 count:int = messages.Dialogs;\nmessages.messages#8c718e87 messages:Vector chats:Vector users:Vector = 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 chats:Vector users:Vector = messages.Messages;\nmessages.channelMessages#64479808 flags:# inexact:flags.1?true pts:int count:int offset_id_offset:flags.2?int messages:Vector chats:Vector users:Vector = messages.Messages;\nmessages.messagesNotModified#74535f21 count:int = messages.Messages;\nmessages.chats#64ff9fd5 chats:Vector = messages.Chats;\nmessages.chatsSlice#9cd81144 count:int chats:Vector = messages.Chats;\nmessages.chatFull#e5d7d19c full_chat:ChatFull chats:Vector users:Vector = 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 pts:int pts_count:int = Update;\nupdateUserTyping#c01e857f user_id:long action:SendMessageAction = Update;\nupdateChatUserTyping#83487af0 chat_id:long from_id:Peer action:SendMessageAction = Update;\nupdateChatParticipants#7761198 participants:ChatParticipants = Update;\nupdateUserStatus#e5bdf8de user_id:long status:UserStatus = Update;\nupdateUserName#c3f202e0 user_id:long first_name:string last_name:string username:string = Update;\nupdateUserPhoto#f227868c user_id:long 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#3dda5451 chat_id:long user_id:long inviter_id:long date:int version:int = Update;\nupdateChatParticipantDelete#e32f3d77 chat_id:long user_id:long version:int = Update;\nupdateDcOptions#8e5e9873 dc_options:Vector = 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 = Update;\nupdatePrivacy#ee3b272a key:PrivacyKey rules:Vector = Update;\nupdateUserPhone#5492a13 user_id:long 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 pts:int pts_count:int = Update;\nupdateChannelTooLong#108d941f flags:# channel_id:long pts:flags.0?int = Update;\nupdateChannel#635b4c09 channel_id:long = Update;\nupdateNewChannelMessage#62ba04d9 message:Message pts:int pts_count:int = Update;\nupdateReadChannelInbox#922e6e10 flags:# folder_id:flags.0?int channel_id:long max_id:int still_unread_count:int pts:int = Update;\nupdateDeleteChannelMessages#c32d5b12 channel_id:long messages:Vector pts:int pts_count:int = Update;\nupdateChannelMessageViews#f226ac08 channel_id:long id:int views:int = Update;\nupdateChatParticipantAdmin#d7ca61a2 chat_id:long user_id:long is_admin:Bool version:int = Update;\nupdateNewStickerSet#688a30aa stickerset:messages.StickerSet = Update;\nupdateStickerSetsOrder#bb2d201 flags:# masks:flags.0?true order:Vector = Update;\nupdateStickerSets#43ae3dec = Update;\nupdateSavedGifs#9375341e = Update;\nupdateBotInlineQuery#496f379c flags:# query_id:long user_id:long query:string geo:flags.0?GeoPoint peer_type:flags.1?InlineQueryPeerType offset:string = Update;\nupdateBotInlineSend#12f12a07 flags:# user_id:long 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#b9cfc48d flags:# query_id:long user_id:long 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#691e9052 flags:# query_id:long user_id:long msg_id:InputBotInlineMessageID chat_instance:long data:flags.0?bytes game_short_name:flags.1?string = Update;\nupdateReadChannelOutbox#b75f99a9 channel_id:long max_id:int = Update;\nupdateDraftMessage#ee2bb969 peer:Peer draft:DraftMessage = Update;\nupdateReadFeaturedStickers#571d2742 = Update;\nupdateRecentStickers#9a422c20 = Update;\nupdateConfig#a229dd06 = Update;\nupdatePtsChanged#3354678f = Update;\nupdateChannelWebPage#2f2ba99f channel_id:long 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 = Update;\nupdateBotWebhookJSON#8317c0c3 data:DataJSON = Update;\nupdateBotWebhookJSONQuery#9b9240a6 query_id:long data:DataJSON timeout:int = Update;\nupdateBotShippingQuery#b5aefd7d query_id:long user_id:long payload:bytes shipping_address:PostAddress = Update;\nupdateBotPrecheckoutQuery#8caa9a96 flags:# query_id:long user_id:long 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#44bdd535 channel_id:long messages:Vector = Update;\nupdateContactsReset#7084a7be = Update;\nupdateChannelAvailableMessages#b23fc698 channel_id:long 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 pts:int pts_count:int = Update;\nupdatePeerSettings#6a7e7366 peer:Peer settings:PeerSettings = Update;\nupdatePeerLocated#b4afcfb0 peers:Vector = Update;\nupdateNewScheduledMessage#39a51dfb message:Message = Update;\nupdateDeleteScheduledMessages#90866cee peer:Peer messages:Vector = Update;\nupdateTheme#8216fba3 theme:Theme = Update;\nupdateGeoLiveViewed#871fb939 peer:Peer msg_id:int = Update;\nupdateLoginToken#564fe691 = Update;\nupdateMessagePollVote#106395c9 poll_id:long user_id:long options:Vector qts:int = Update;\nupdateDialogFilter#26ffde7d flags:# id:int filter:flags.0?DialogFilter = Update;\nupdateDialogFilterOrder#a5d72105 order:Vector = Update;\nupdateDialogFilters#3504914f = Update;\nupdatePhoneCallSignalingData#2661bf09 phone_call_id:long data:bytes = Update;\nupdateChannelMessageForwards#d29a27f4 channel_id:long id:int forwards:int = Update;\nupdateReadChannelDiscussionInbox#d6b19546 flags:# channel_id:long top_msg_id:int read_max_id:int broadcast_id:flags.0?long broadcast_post:flags.0?int = Update;\nupdateReadChannelDiscussionOutbox#695c9e7c channel_id:long top_msg_id:int read_max_id:int = Update;\nupdatePeerBlocked#246a4b22 peer_id:Peer blocked:Bool = Update;\nupdateChannelUserTyping#8c88c923 flags:# channel_id:long top_msg_id:flags.0?int from_id:Peer action:SendMessageAction = Update;\nupdatePinnedMessages#ed85eab5 flags:# pinned:flags.0?true peer:Peer messages:Vector pts:int pts_count:int = Update;\nupdatePinnedChannelMessages#5bb98608 flags:# pinned:flags.0?true channel_id:long messages:Vector pts:int pts_count:int = Update;\nupdateChat#f89a6a4e chat_id:long = Update;\nupdateGroupCallParticipants#f2ebdb4e call:InputGroupCall participants:Vector version:int = Update;\nupdateGroupCall#14b24500 chat_id:long call:GroupCall = Update;\nupdatePeerHistoryTTL#bb9bb9a5 flags:# peer:Peer ttl_period:flags.0?int = Update;\nupdateChatParticipant#d087663a flags:# chat_id:long date:int actor_id:long user_id:long prev_participant:flags.0?ChatParticipant new_participant:flags.1?ChatParticipant invite:flags.2?ExportedChatInvite qts:int = Update;\nupdateChannelParticipant#985d3abb flags:# channel_id:long date:int actor_id:long user_id:long prev_participant:flags.0?ChannelParticipant new_participant:flags.1?ChannelParticipant invite:flags.2?ExportedChatInvite qts:int = Update;\nupdateBotStopped#c4870a49 user_id:long date:int stopped:Bool qts:int = Update;\nupdateGroupCallConnection#b783982 flags:# presentation:flags.0?true params:DataJSON = Update;\nupdateBotCommands#4d712f2e peer:Peer bot_id:long commands:Vector = Update;\nupdatePendingJoinRequests#7063c3db peer:Peer requests_pending:int recent_requesters:Vector = Update;\nupdateBotChatInviteRequester#11dfa986 peer:Peer date:int user_id:long about:string invite:ExportedChatInvite qts:int = Update;\nupdateMessageReactions#154798c3 peer:Peer msg_id:int reactions:MessageReactions = 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 new_encrypted_messages:Vector other_updates:Vector chats:Vector users:Vector state:updates.State = updates.Difference;\nupdates.differenceSlice#a8fb1981 new_messages:Vector new_encrypted_messages:Vector other_updates:Vector chats:Vector users:Vector intermediate_state:updates.State = updates.Difference;\nupdates.differenceTooLong#4afe8f6d pts:int = updates.Difference;\nupdatesTooLong#e317af7e = Updates;\nupdateShortMessage#313bc7f8 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true id:int user_id:long message:string pts:int pts_count:int date:int fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?long reply_to:flags.3?MessageReplyHeader entities:flags.7?Vector ttl_period:flags.25?int = Updates;\nupdateShortChatMessage#4d6deea5 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true id:int from_id:long chat_id:long message:string pts:int pts_count:int date:int fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?long reply_to:flags.3?MessageReplyHeader entities:flags.7?Vector ttl_period:flags.25?int = Updates;\nupdateShort#78d4dec1 update:Update date:int = Updates;\nupdatesCombined#725b04c3 updates:Vector users:Vector chats:Vector date:int seq_start:int seq:int = Updates;\nupdates#74ae4240 updates:Vector users:Vector chats:Vector 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 ttl_period:flags.25?int = Updates;\nphotos.photos#8dca6aa5 photos:Vector users:Vector = photos.Photos;\nphotos.photosSlice#15051f54 count:int photos:Vector users:Vector = photos.Photos;\nphotos.photo#20212ca8 photo:Photo users:Vector = 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 = 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 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 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#66b25953 id:int access_hash:long date:int admin_id:long participant_id:long = EncryptedChat;\nencryptedChatRequested#48f1d94c flags:# folder_id:flags.0?int id:int access_hash:long date:int admin_id:long participant_id:long g_a:bytes = EncryptedChat;\nencryptedChat#61f0d4c7 id:int access_hash:long date:int admin_id:long participant_id:long 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 video_thumbs:flags.1?Vector dc_id:int attributes:Vector = 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;\nsendMessageChooseStickerAction#b05ac6b1 = SendMessageAction;\nsendMessageEmojiInteraction#25972bcb emoticon:string msg_id:int interaction:DataJSON = SendMessageAction;\nsendMessageEmojiInteractionSeen#b665902e emoticon:string = SendMessageAction;\ncontacts.found#b3134d9d my_results:Vector results:Vector chats:Vector users:Vector = 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 = InputPrivacyRule;\ninputPrivacyValueDisallowContacts#ba52007 = InputPrivacyRule;\ninputPrivacyValueDisallowAll#d66b66c9 = InputPrivacyRule;\ninputPrivacyValueDisallowUsers#90110467 users:Vector = InputPrivacyRule;\ninputPrivacyValueAllowChatParticipants#840649cf chats:Vector = InputPrivacyRule;\ninputPrivacyValueDisallowChatParticipants#e94f0f86 chats:Vector = InputPrivacyRule;\nprivacyValueAllowContacts#fffe1bac = PrivacyRule;\nprivacyValueAllowAll#65427b82 = PrivacyRule;\nprivacyValueAllowUsers#b8905fb2 users:Vector = PrivacyRule;\nprivacyValueDisallowContacts#f888fa1a = PrivacyRule;\nprivacyValueDisallowAll#8b73e763 = PrivacyRule;\nprivacyValueDisallowUsers#e4621141 users:Vector = PrivacyRule;\nprivacyValueAllowChatParticipants#6b134e8e chats:Vector = PrivacyRule;\nprivacyValueDisallowChatParticipants#41c87565 chats:Vector = PrivacyRule;\naccount.privacyRules#50a04e45 rules:Vector chats:Vector users:Vector = 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#30a6ec7e hash:long stickers:Vector = messages.Stickers;\nstickerPack#12b299d4 emoticon:string documents:Vector = StickerPack;\nmessages.allStickersNotModified#e86602c3 = messages.AllStickers;\nmessages.allStickers#cdbbcebb hash:long sets:Vector = 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 = 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 encrypted_requests_disabled:flags.3?true call_requests_disabled:flags.4?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#4bff8ea0 authorization_ttl_days:int authorizations:Vector = 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#ab4a819 flags:# revoked:flags.0?true permanent:flags.5?true request_needed:flags.6?true link:string admin_id:long date:int start_date:flags.4?int expire_date:flags.1?int usage_limit:flags.2?int usage:flags.3?int requested:flags.7?int title:flags.8?string = ExportedChatInvite;\nchatInviteAlready#5a686d7c chat:Chat = ChatInvite;\nchatInvite#300c44c1 flags:# channel:flags.0?true broadcast:flags.1?true public:flags.2?true megagroup:flags.3?true request_needed:flags.6?true title:string about:flags.5?string photo:Photo participants_count:int participants:flags.4?Vector = 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;\ninputStickerSetAnimatedEmojiAnimations#cde3739 = 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 thumb_dc_id:flags.4?int thumb_version:flags.4?int count:int hash:int = StickerSet;\nmessages.stickerSet#b60a24a6 set:StickerSet packs:Vector documents:Vector = messages.StickerSet;\nmessages.stickerSetNotModified#d3f924eb = messages.StickerSet;\nbotCommand#c27ac8c7 command:string description:string = BotCommand;\nbotInfo#1b74b335 user_id:long description:string commands:Vector = 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;\ninputKeyboardButtonUserProfile#e988037b text:string user_id:InputUser = KeyboardButton;\nkeyboardButtonUserProfile#308660c1 text:string user_id:long = KeyboardButton;\nkeyboardButtonRow#77608b83 buttons:Vector = 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 placeholder:flags.3?string = ReplyMarkup;\nreplyInlineMarkup#48a30254 rows:Vector = 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#dc7b1140 offset:int length:int user_id:long = 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;\nmessageEntitySpoiler#32ca960f offset:int length:int = MessageEntity;\ninputChannelEmpty#ee8c1e86 = InputChannel;\ninputChannel#f35aec28 channel_id:long access_hash:long = InputChannel;\ninputChannelFromMessage#5b934f9d peer:InputPeer msg_id:int channel_id:long = InputChannel;\ncontacts.resolvedPeer#7f077ad9 peer:Peer chats:Vector users:Vector = 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 chats:Vector users:Vector = updates.ChannelDifference;\nupdates.channelDifference#2064674e flags:# final:flags.0?true pts:int timeout:flags.1?int new_messages:Vector other_updates:Vector chats:Vector users:Vector = updates.ChannelDifference;\nchannelMessagesFilterEmpty#94d42ee7 = ChannelMessagesFilter;\nchannelMessagesFilter#cd77d957 flags:# exclude_new_messages:flags.1?true ranges:Vector = ChannelMessagesFilter;\nchannelParticipant#c00c07c0 user_id:long date:int = ChannelParticipant;\nchannelParticipantSelf#35a8bfa7 flags:# via_request:flags.0?true user_id:long inviter_id:long date:int = ChannelParticipant;\nchannelParticipantCreator#2fe601d3 flags:# user_id:long admin_rights:ChatAdminRights rank:flags.0?string = ChannelParticipant;\nchannelParticipantAdmin#34c3bb53 flags:# can_edit:flags.0?true self:flags.1?true user_id:long inviter_id:flags.1?long promoted_by:long date:int admin_rights:ChatAdminRights rank:flags.2?string = ChannelParticipant;\nchannelParticipantBanned#6df8014e flags:# left:flags.0?true peer:Peer kicked_by:long 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 chats:Vector users:Vector = channels.ChannelParticipants;\nchannels.channelParticipantsNotModified#f0173fe9 = channels.ChannelParticipants;\nchannels.channelParticipant#dfb80317 participant:ChannelParticipant chats:Vector users:Vector = channels.ChannelParticipant;\nhelp.termsOfService#780a0310 flags:# popup:flags.0?true id:DataJSON text:string entities:Vector min_age_confirm:flags.1?int = help.TermsOfService;\nmessages.savedGifsNotModified#e8025ca2 = messages.SavedGifs;\nmessages.savedGifs#84a02a0d hash:long gifs:Vector = messages.SavedGifs;\ninputBotInlineMessageMediaAuto#3380c786 flags:# message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageText#3dcd7a87 flags:# no_webpage:flags.0?true message:string entities:flags.1?Vector 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 reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageText#8c7f65e2 flags:# no_webpage:flags.0?true message:string entities:flags.1?Vector 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 cache_time:int users:Vector = 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.codeTypeMissedCall#d61ad6ee = 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;\nauth.sentCodeTypeMissedCall#82006484 prefix:string length:int = 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;\ninputBotInlineMessageID64#b6d915d7 dc_id:int owner_id:long id:int access_hash:long = InputBotInlineMessageID;\ninlineBotSwitchPM#3c20629f text:string start_param:string = InlineBotSwitchPM;\nmessages.peerDialogs#3371c354 dialogs:Vector messages:Vector chats:Vector users:Vector 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 = TopPeerCategoryPeers;\ncontacts.topPeersNotModified#de266ef5 = contacts.TopPeers;\ncontacts.topPeers#70b772a8 categories:Vector chats:Vector users:Vector = 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 date:int = DraftMessage;\nmessages.featuredStickersNotModified#c6dc0c66 count:int = messages.FeaturedStickers;\nmessages.featuredStickers#84c02310 hash:long count:int sets:Vector unread:Vector = messages.FeaturedStickers;\nmessages.recentStickersNotModified#b17f890 = messages.RecentStickers;\nmessages.recentStickers#88d37c56 hash:long packs:Vector stickers:Vector dates:Vector = messages.RecentStickers;\nmessages.archivedStickers#4fcba9c8 count:int sets:Vector = messages.ArchivedStickers;\nmessages.stickerSetInstallResultSuccess#38641628 = messages.StickerSetInstallResult;\nmessages.stickerSetInstallResultArchive#35e410a8 sets:Vector = messages.StickerSetInstallResult;\nstickerSetCovered#6410a5d2 set:StickerSet cover:Document = StickerSetCovered;\nstickerSetMultiCovered#3407e51b set:StickerSet covers:Vector = 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#73a379eb pos:int user_id:long score:int = HighScore;\nmessages.highScores#9a3bfd99 scores:Vector users:Vector = 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;\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 = 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 caption:PageCaption = PageBlock;\npageBlockCollage#65a0fa4d items:Vector caption:PageCaption = PageBlock;\npageBlockSlideshow#31f9590 items:Vector 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 = PageBlock;\npageBlockOrderedList#9a8ae1e1 items:Vector = PageBlock;\npageBlockDetails#76768bed flags:# open:flags.0?true blocks:Vector title:RichText = PageBlock;\npageBlockRelatedArticles#16115a96 title:RichText articles:Vector = 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 max_tip_amount:flags.8?long suggested_tip_amounts:flags.8?Vector = 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 = WebDocument;\nwebDocumentNoProxy#f9c8bcc6 url:string size:int mime_type:string attributes:Vector = WebDocument;\ninputWebDocument#9bed434d url:string size:int mime_type:string attributes:Vector = 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#1694761b flags:# can_save_credentials:flags.2?true password_missing:flags.3?true form_id:long bot_id:long invoice:Invoice provider_id:long url:string native_provider:flags.4?string native_params:flags.4?DataJSON saved_info:flags.0?PaymentRequestedInfo saved_credentials:flags.1?PaymentSavedCredentials users:Vector = payments.PaymentForm;\npayments.validatedRequestedInfo#d1451883 flags:# id:flags.0?string shipping_options:flags.1?Vector = payments.ValidatedRequestedInfo;\npayments.paymentResult#4e5f810d updates:Updates = payments.PaymentResult;\npayments.paymentVerificationNeeded#d8411139 url:string = payments.PaymentResult;\npayments.paymentReceipt#70c4fe03 flags:# date:int bot_id:long provider_id:long 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 = 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 = 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#c5226f17 flags:# video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long protocol:PhoneCallProtocol receive_date:flags.0?int = PhoneCall;\nphoneCallRequested#14b0ed0c flags:# video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long g_a_hash:bytes protocol:PhoneCallProtocol = PhoneCall;\nphoneCallAccepted#3660c311 flags:# video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long g_b:bytes protocol:PhoneCallProtocol = PhoneCall;\nphoneCall#967f7c67 flags:# p2p_allowed:flags.5?true video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long g_a_or_b:bytes key_fingerprint:long protocol:PhoneCallProtocol connections:Vector 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 = PhoneCallProtocol;\nphone.phoneCall#ec82e140 phone_call:PhoneCall users:Vector = 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 = 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 = 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#50c7ac8 prev_value:long new_value:long = 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;\nchannelAdminLogEventActionParticipantJoinByRequest#afb6144a invite:ExportedChatInvite approved_by:long = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleNoForwards#cb2ac766 new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionSendMessage#278f2868 message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeAvailableReactions#9cf7f76a prev_value:Vector new_value:Vector = ChannelAdminLogEventAction;\nchannelAdminLogEvent#1fad68cd id:long date:int user_id:long action:ChannelAdminLogEventAction = ChannelAdminLogEvent;\nchannels.adminLogResults#ed8af74d events:Vector chats:Vector users:Vector = 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 send:flags.16?true = ChannelAdminLogEventsFilter;\npopularContact#5ce14175 client_id:long importers:int = PopularContact;\nmessages.favedStickersNotModified#9e8fa6d3 = messages.FavedStickers;\nmessages.favedStickers#2cb51097 hash:long packs:Vector stickers:Vector = messages.FavedStickers;\nrecentMeUrlUnknown#46e1d13d url:string = RecentMeUrl;\nrecentMeUrlUser#b92c09e2 url:string user_id:long = RecentMeUrl;\nrecentMeUrlChat#b2da71d2 url:string chat_id:long = RecentMeUrl;\nrecentMeUrlChatInvite#eb49081d url:string chat_invite:ChatInvite = RecentMeUrl;\nrecentMeUrlStickerSet#bc0a57dc url:string set:StickerSetCovered = RecentMeUrl;\nhelp.recentMeUrls#e0310d7 urls:Vector chats:Vector users:Vector = help.RecentMeUrls;\ninputSingleMedia#1cc6e91f flags:# media:InputMedia random_id:long message:string entities:flags.0?Vector = InputSingleMedia;\nwebAuthorization#a6f8f452 hash:long bot_id:long domain:string browser:string platform:string date_created:int date_active:int ip:string region:string = WebAuthorization;\naccount.webAuthorizations#ed56c9fc authorizations:Vector users:Vector = 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#8af09dd2 hash:long sets:Vector = 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 files:flags.4?Vector 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 files:flags.4?Vector 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 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 text:string = SecureValueError;\nsecureCredentialsEncrypted#33f0ea47 data:bytes hash:bytes secret:bytes = SecureCredentialsEncrypted;\naccount.authorizationForm#ad2e1cd8 flags:# required_types:Vector values:Vector errors:Vector users:Vector 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 = 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;\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;\njsonObject#99c1d49d value:Vector = 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 = PageTableRow;\npageCaption#6f747657 text:RichText credit:RichText = PageCaption;\npageListItemText#b92fb6cd text:RichText = PageListItem;\npageListItemBlocks#25e073fc blocks:Vector = PageListItem;\npageListOrderedItemText#5e068047 num:string text:RichText = PageListOrderedItem;\npageListOrderedItemBlocks#98dd8936 num:string blocks:Vector = 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 photos:Vector documents:Vector views:flags.3?int = Page;\nhelp.supportName#8c05f1c9 name:string = help.SupportName;\nhelp.userInfoEmpty#f3ae2eed = help.UserInfo;\nhelp.userInfo#1eb3758 message:string entities:Vector 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 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#dcb82ea3 flags:# min:flags.0?true results:flags.1?Vector total_voters:flags.2?int recent_voters:flags.3?Vector solution:flags.4?string solution_entities:flags.4?Vector = 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#cdc3858c hash:long wallpapers:Vector = account.WallPapers;\ncodeSettings#8a6469c2 flags:# allow_flashcall:flags.0?true current_number:flags.1?true allow_app_hash:flags.4?true allow_missed_call:flags.5?true logout_tokens:flags.6?Vector = 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 = EmojiKeyword;\nemojiKeywordDeleted#236df622 keyword:string emoticons:Vector = EmojiKeyword;\nemojiKeywordsDifference#5cc761bd lang_code:string from_version:int version:int keywords:Vector = 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#a00e67d6 flags:# creator:flags.0?true default:flags.1?true for_chat:flags.5?true id:long access_hash:long slug:string title:string document:flags.2?Document settings:flags.3?Vector emoticon:flags.6?string installs_count:flags.4?int = Theme;\naccount.themesNotModified#f41eb622 = account.Themes;\naccount.themes#9a3d8c6d hash:long themes:Vector = 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 chats:Vector users:Vector = messages.InactiveChats;\nbaseThemeClassic#c3a12462 = BaseTheme;\nbaseThemeDay#fbd81688 = BaseTheme;\nbaseThemeNight#b7b31ea8 = BaseTheme;\nbaseThemeTinted#6d5f77ee = BaseTheme;\nbaseThemeArctic#5b11125a = BaseTheme;\ninputThemeSettings#8fde504f flags:# message_colors_animated:flags.2?true base_theme:BaseTheme accent_color:int outbox_accent_color:flags.3?int message_colors:flags.0?Vector wallpaper:flags.1?InputWallPaper wallpaper_settings:flags.1?WallPaperSettings = InputThemeSettings;\nthemeSettings#fa58b6d4 flags:# message_colors_animated:flags.2?true base_theme:BaseTheme accent_color:int outbox_accent_color:flags.3?int message_colors:flags.0?Vector wallpaper:flags.1?WallPaper = ThemeSettings;\nwebPageAttributeTheme#54b56617 flags:# documents:flags.0?Vector settings:flags.1?ThemeSettings = WebPageAttribute;\nmessageUserVote#34d247b4 user_id:long option:bytes date:int = MessageUserVote;\nmessageUserVoteInputOption#3ca5b0ec user_id:long date:int = MessageUserVote;\nmessageUserVoteMultiple#8a65e557 user_id:long options:Vector date:int = MessageUserVote;\nmessages.votesList#823f649 flags:# count:int votes:Vector users:Vector next_offset:flags.0?string = messages.VotesList;\nbankCardOpenUrl#f568028a url:string name:string = BankCardOpenUrl;\npayments.bankCardData#3e24e573 title:string open_urls:Vector = 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 include_peers:Vector exclude_peers:Vector = 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 = stats.BroadcastStats;\nhelp.promoDataEmpty#98f6ac75 expires:int = help.PromoData;\nhelp.promoData#8c39793f flags:# proxy:flags.0?true expires:int peer:Peer chats:Vector users:Vector 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#9d04af9b user_id:long messages:int avg_chars:int = StatsGroupTopPoster;\nstatsGroupTopAdmin#d7584c87 user_id:long deleted:int kicked:int banned:int = StatsGroupTopAdmin;\nstatsGroupTopInviter#535f779d user_id:long 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 top_admins:Vector top_inviters:Vector users:Vector = 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 patterns:flags.1?Vector = help.CountryCode;\nhelp.country#c3878e23 flags:# hidden:flags.0?true iso2:string default_name:string name:flags.1?string country_codes:Vector = help.Country;\nhelp.countriesListNotModified#93cc1f32 = help.CountriesList;\nhelp.countriesList#87d0759e countries:Vector 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 chats:Vector users:Vector = messages.MessageViews;\nmessages.discussionMessage#a6341782 flags:# messages:Vector max_id:flags.0?int read_inbox_max_id:flags.1?int read_outbox_max_id:flags.2?int unread_count:int chats:Vector users:Vector = 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#83d60fc2 flags:# comments:flags.0?true replies:int replies_pts:int recent_repliers:flags.1?Vector channel_id:flags.0?long 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 record_video_active:flags.11?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 participants_next_offset:string chats:Vector users:Vector = phone.GroupCall;\nphone.groupParticipants#f47751b6 count:int participants:Vector next_offset:string chats:Vector users:Vector 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 = messages.AffectedFoundMessages;\nchatInviteImporter#8c5adfd9 flags:# requested:flags.0?true user_id:long date:int about:flags.2?string approved_by:flags.1?long = ChatInviteImporter;\nmessages.exportedChatInvites#bdc62dcc count:int invites:Vector users:Vector = messages.ExportedChatInvites;\nmessages.exportedChatInvite#1871be50 invite:ExportedChatInvite users:Vector = messages.ExportedChatInvite;\nmessages.exportedChatInviteReplaced#222600ef invite:ExportedChatInvite new_invite:ExportedChatInvite users:Vector = messages.ExportedChatInvite;\nmessages.chatInviteImporters#81b6b00a count:int importers:Vector users:Vector = messages.ChatInviteImporters;\nchatAdminWithInvites#f2ecef23 admin_id:long invites_count:int revoked_invites_count:int = ChatAdminWithInvites;\nmessages.chatAdminsWithInvites#b69b72d7 admins:Vector users:Vector = messages.ChatAdminsWithInvites;\nmessages.checkedHistoryImportPeer#a24de717 confirm_text:string = messages.CheckedHistoryImportPeer;\nphone.joinAsPeers#afe5623f peers:Vector chats:Vector users:Vector = phone.JoinAsPeers;\nphone.exportedGroupCallInvite#204bd158 link:string = phone.ExportedGroupCallInvite;\ngroupCallParticipantVideoSourceGroup#dcb118b7 semantics:string sources:Vector = GroupCallParticipantVideoSourceGroup;\ngroupCallParticipantVideo#67753ac8 flags:# paused:flags.0?true endpoint:string source_groups:Vector 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;\nsponsoredMessage#3a836df8 flags:# random_id:bytes from_id:flags.3?Peer chat_invite:flags.4?ChatInvite chat_invite_hash:flags.4?string channel_post:flags.2?int start_param:flags.0?string message:string entities:flags.1?Vector = SponsoredMessage;\nmessages.sponsoredMessages#65a4c7d5 messages:Vector chats:Vector users:Vector = messages.SponsoredMessages;\nsearchResultsCalendarPeriod#c9b0539f date:int min_msg_id:int max_msg_id:int count:int = SearchResultsCalendarPeriod;\nmessages.searchResultsCalendar#147ee23c flags:# inexact:flags.0?true count:int min_date:int min_msg_id:int offset_id_offset:flags.1?int periods:Vector messages:Vector chats:Vector users:Vector = messages.SearchResultsCalendar;\nsearchResultPosition#7f648b67 msg_id:int date:int offset:int = SearchResultsPosition;\nmessages.searchResultsPositions#53b22baf count:int positions:Vector = messages.SearchResultsPositions;\nchannels.sendAsPeers#8356cda9 peers:Vector chats:Vector users:Vector = channels.SendAsPeers;\nusers.userFull#3b6d152e full_user:UserFull chats:Vector users:Vector = users.UserFull;\nmessages.peerSettings#6880b94d settings:PeerSettings chats:Vector users:Vector = messages.PeerSettings;\nauth.loggedOut#c3a2835f flags:# future_auth_token:flags.0?bytes = auth.LoggedOut;\nreactionCount#6fb250d1 flags:# chosen:flags.0?true reaction:string count:int = ReactionCount;\nmessageReactions#87b6e36 flags:# min:flags.0?true can_see_list:flags.2?true results:Vector recent_reactons:flags.1?Vector = MessageReactions;\nmessageUserReaction#932844fa user_id:long reaction:string = MessageUserReaction;\nmessages.messageReactionsList#a366923c flags:# count:int reactions:Vector users:Vector next_offset:flags.0?string = messages.MessageReactionsList;\navailableReaction#21d7c4b flags:# inactive:flags.0?true reaction:string title:string static_icon:Document appear_animation:Document select_animation:Document activate_animation:Document effect_animation:Document = AvailableReaction;\nmessages.availableReactionsNotModified#9f071957 = messages.AvailableReactions;\nmessages.availableReactions#768e3aad hash:int reactions:Vector = messages.AvailableReactions;\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#3e72ba19 = auth.LoggedOut;\nauth.resetAuthorizations#9fab0d1a = Bool;\nauth.exportAuthorization#e5bfffcd dc_id:int = auth.ExportedAuthorization;\nauth.importAuthorization#a57a7dad id:long 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 = Bool;\nauth.exportLoginToken#b7e085fe api_id:int api_hash:string except_ids:Vector = auth.LoginToken;\nauth.importLoginToken#95ac5ce4 token:bytes = auth.LoginToken;\naccount.registerDevice#ec86017a flags:# no_muted:flags.0?true token_type:int token:string app_sandbox:Bool secret:bytes other_uids:Vector = Bool;\naccount.unregisterDevice#6a0d3206 token_type:int token:string other_uids:Vector = 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#7967d36 hash:long = 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 = 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 = Vector;\nusers.getFullUser#b60f5918 id:InputUser = users.UserFull;\ncontacts.getContacts#5dd69e12 hash:long = contacts.Contacts;\ncontacts.importContacts#2c800be5 contacts:Vector = contacts.ImportedContacts;\ncontacts.deleteContacts#96a0e00 id:Vector = 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#973478b6 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:long = contacts.TopPeers;\ncontacts.addContact#e8f463d0 flags:# add_phone_privacy_exception:flags.0?true id:InputUser first_name:string last_name:string phone:string = Updates;\nmessages.getMessages#63c66506 id:Vector = messages.Messages;\nmessages.getDialogs#a0f4cb4f flags:# exclude_pinned:flags.0?true folder_id:flags.1?int offset_date:int offset_id:int offset_peer:InputPeer limit:int hash:long = messages.Dialogs;\nmessages.getHistory#4423e6c5 peer:InputPeer offset_id:int offset_date:int add_offset:int limit:int max_id:int min_id:int hash:long = messages.Messages;\nmessages.search#a0fda762 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:long = messages.Messages;\nmessages.readHistory#e306d3a peer:InputPeer max_id:int = messages.AffectedMessages;\nmessages.deleteHistory#b08f922a flags:# just_clear:flags.0?true revoke:flags.1?true peer:InputPeer max_id:int min_date:flags.2?int max_date:flags.3?int = messages.AffectedHistory;\nmessages.deleteMessages#e58e95d2 flags:# revoke:flags.0?true id:Vector = messages.AffectedMessages;\nmessages.receivedMessages#5a954c0 max_id:int = Vector;\nmessages.setTyping#58943ee2 flags:# peer:InputPeer top_msg_id:flags.0?int action:SendMessageAction = Bool;\nmessages.sendMessage#d9d75a4 flags:# no_webpage:flags.1?true silent:flags.5?true background:flags.6?true clear_draft:flags.7?true noforwards:flags.14?true peer:InputPeer reply_to_msg_id:flags.0?int message:string random_id:long reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector schedule_date:flags.10?int send_as:flags.13?InputPeer = Updates;\nmessages.sendMedia#e25ff8e0 flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true noforwards:flags.14?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 schedule_date:flags.10?int send_as:flags.13?InputPeer = Updates;\nmessages.forwardMessages#cc30290b flags:# silent:flags.5?true background:flags.6?true with_my_score:flags.8?true drop_author:flags.11?true drop_media_captions:flags.12?true noforwards:flags.14?true from_peer:InputPeer id:Vector random_id:Vector to_peer:InputPeer schedule_date:flags.10?int send_as:flags.13?InputPeer = Updates;\nmessages.report#8953ab4e peer:InputPeer id:Vector reason:ReportReason message:string = Bool;\nmessages.getChats#49e9528f id:Vector = messages.Chats;\nmessages.getFullChat#aeb00b34 chat_id:long = messages.ChatFull;\nmessages.editChatTitle#73783ffd chat_id:long title:string = Updates;\nmessages.editChatPhoto#35ddd674 chat_id:long photo:InputChatPhoto = Updates;\nmessages.addChatUser#f24753e3 chat_id:long user_id:InputUser fwd_limit:int = Updates;\nmessages.deleteChatUser#a2185cab flags:# revoke_history:flags.0?true chat_id:long user_id:InputUser = Updates;\nmessages.createChat#9cb126e users:Vector title:string = Updates;\nmessages.getDhConfig#26cf8950 version:int random_length:int = messages.DhConfig;\nmessages.readMessageContents#36a73f77 id:Vector = messages.AffectedMessages;\nmessages.getStickers#d5a5d3a1 emoticon:string hash:long = messages.Stickers;\nmessages.getAllStickers#b8a0a1a8 hash:long = messages.AllStickers;\nmessages.getWebPagePreview#8b68b0cc flags:# message:string entities:flags.3?Vector = MessageMedia;\nmessages.exportChatInvite#a02ce5d5 flags:# legacy_revoke_permanent:flags.2?true request_needed:flags.3?true peer:InputPeer expire_date:flags.0?int usage_limit:flags.1?int title:flags.4?string = ExportedChatInvite;\nmessages.checkChatInvite#3eadb1bb hash:string = ChatInvite;\nmessages.importChatInvite#6c50051c hash:string = Updates;\nmessages.getStickerSet#c8a0ec74 stickerset:InputStickerSet hash:int = 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#a2875319 chat_id:long = 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#5cf09635 hash:long = messages.SavedGifs;\nmessages.getInlineBotResults#514e999d flags:# bot:InputUser peer:InputPeer geo_point:flags.0?InputGeoPoint query:string offset:string = messages.BotResults;\nmessages.sendInlineBotResult#7aa11297 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 send_as:flags.13?InputPeer = 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 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 = 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 = Bool;\nmessages.getFeaturedStickers#64780b14 hash:long = messages.FeaturedStickers;\nmessages.readFeaturedStickers#5b118126 id:Vector = Bool;\nmessages.getRecentStickers#9da9403b flags:# attached:flags.0?true hash:long = messages.RecentStickers;\nmessages.getCommonChats#e40ca104 user_id:InputUser max_id:long limit:int = messages.Chats;\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#4f1aaa9 hash:long = messages.FavedStickers;\nmessages.faveSticker#b9ffc55b id:InputDocument unfave:Bool = Bool;\nmessages.sendMultiMedia#f803138f flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true noforwards:flags.14?true peer:InputPeer reply_to_msg_id:flags.0?int multi_media:Vector schedule_date:flags.10?int send_as:flags.13?InputPeer = Updates;\nmessages.searchStickerSets#35705b8a flags:# exclude_featured:flags.0?true q:string hash:long = 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 = 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#f516760b peer:InputPeer hash:long = messages.Messages;\nmessages.sendScheduledMessages#bd38850a peer:InputPeer id:Vector = Updates;\nmessages.deleteScheduledMessages#59ae2b16 peer:InputPeer id:Vector = 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;\nmessages.getSuggestedDialogFilters#a29cd42c = Vector;\nmessages.updateDialogFilter#1ad4a04a flags:# id:int filter:flags.0?DialogFilter = Bool;\nmessages.getReplies#22ddd30c peer:InputPeer msg_id:int offset_id:int offset_date:int add_offset:int limit:int max_id:int min_id:int hash:long = 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#5bd0ee50 chat_id:long = Bool;\nmessages.getMessageReadParticipants#2c6f97b7 peer:InputPeer msg_id:int = Vector;\nmessages.toggleNoForwards#b11eafa2 peer:InputPeer enabled:Bool = Updates;\nmessages.saveDefaultSendAs#ccfddf96 peer:InputPeer send_as:InputPeer = 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;\nhelp.getCountriesList#735787a8 lang_code:string hash:int = help.CountriesList;\nchannels.readHistory#cc104937 channel:InputChannel max_id:int = Bool;\nchannels.deleteMessages#84c1fd4e channel:InputChannel id:Vector = messages.AffectedMessages;\nchannels.getMessages#ad8c9a23 channel:InputChannel id:Vector = messages.Messages;\nchannels.getParticipants#77ced9d0 channel:InputChannel filter:ChannelParticipantsFilter offset:int limit:int hash:long = channels.ChannelParticipants;\nchannels.getParticipant#a0ab6cc6 channel:InputChannel participant:InputPeer = channels.ChannelParticipant;\nchannels.getChannels#a7f6bbb id:Vector = 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 = 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 = Bool;\nchannels.togglePreHistoryHidden#eabbb94c channel:InputChannel enabled:Bool = Updates;\nchannels.getGroupsForDiscussion#f5dad378 = messages.Chats;\nchannels.setDiscussionGroup#40582bb2 broadcast:InputChannel group:InputChannel = Bool;\nchannels.viewSponsoredMessage#beaedb94 channel:InputChannel random_id:bytes = Bool;\nchannels.getSponsoredMessages#ec210fbf channel:InputChannel = messages.SponsoredMessages;\nchannels.getSendAs#dc770ee peer:InputPeer = channels.SendAsPeers;\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;\nphone.createGroupCall#48cdc6d8 flags:# peer:InputPeer random_id:int title:flags.0?string schedule_date:flags.1?int = Updates;\nphone.joinGroupCall#b132ff7b flags:# muted:flags.0?true video_stopped:flags.2?true call:InputGroupCall join_as:InputPeer invite_hash:flags.1?string params:DataJSON = Updates;\nphone.leaveGroupCall#500377f9 call:InputGroupCall source:int = Updates;\nphone.discardGroupCall#7a777135 call:InputGroupCall = Updates;\nphone.getGroupCall#41845db call:InputGroupCall limit:int = phone.GroupCall;\nphone.getGroupParticipants#c558d8ab call:InputGroupCall ids:Vector sources:Vector offset:string limit:int = phone.GroupParticipants;\nphone.editGroupCallParticipant#a5273abf flags:# call:InputGroupCall participant:InputPeer muted:flags.0?Bool volume:flags.1?int raise_hand:flags.2?Bool video_stopped:flags.3?Bool video_paused:flags.4?Bool presentation_paused:flags.5?Bool = Updates;\nphone.exportGroupCallInvite#e6aa647f flags:# can_self_unmute:flags.0?true call:InputGroupCall = phone.ExportedGroupCallInvite;\nphone.toggleGroupCallStartSubscription#219c34e6 call:InputGroupCall subscribed:Bool = Updates;\nphone.joinGroupCallPresentation#cbea6bc4 call:InputGroupCall params:DataJSON = Updates;\nphone.leaveGroupCallPresentation#1c50d144 call:InputGroupCall = Updates;\nlangpack.getLangPack#f2f2330a lang_pack:string lang_code:string = LangPackDifference;\nlangpack.getStrings#efea3803 lang_pack:string lang_code:string keys:Vector = Vector;\nlangpack.getLanguages#42c6978f lang_pack:string = Vector;\nfolders.editPeerFolders#6847d0ab folder_peers:Vector = Updates;`;","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(/ \\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\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 = ResPQ;\np_q_inner_data#83c95aec pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 = P_Q_inner_data;\np_q_inner_data_dc#a9f55f95 pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 dc:int = P_Q_inner_data;\np_q_inner_data_temp#3c6a84d4 pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 expires_in:int = P_Q_inner_data;\np_q_inner_data_temp_dc#56fddf88 pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 dc:int expires_in:int = 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 = 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 = MsgsStateReq;\nmsgs_state_info#04deb57d req_msg_id:long info:string = MsgsStateInfo;\nmsgs_all_info#8cc0d131 msg_ids:Vector 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 = MsgResendReq;\nrpc_error#2144ca19 error_code:int error_message:string = RpcError;\nrpc_answer_unknown#5e2ad36e = RpcDropAnswer;\nrpc_answer_dropped_running#cd78e586 = RpcDropAnswer;\nrpc_answer_dropped#a43ad8b7 msg_id:long seq_no:int bytes:int = RpcDropAnswer;\nfuture_salt#0949d9dc valid_since:int valid_until:int salt:long = FutureSalt;\nfuture_salts#ae500895 req_msg_id:long now:int salts:vector = 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;\nhttp_wait#9299359f max_delay:int wait_after:int max_wait:int = HttpWait;\nipPort#d433ad73 ipv4:int port:int = IpPort;\nipPortSecret#37982646 ipv4:int port:int secret:bytes = IpPort;\naccessPointRule#4679b65f phone_prefix_rules:string dc_id:int ips:vector = AccessPointRule;\nhelp.configSimple#5a592a6c date:int expires:int rules:vector = help.ConfigSimple;\ntlsClientHello blocks:vector = TlsClientHello;\ntlsBlockString data:string = TlsBlock;\ntlsBlockRandom length:int = TlsBlock;\ntlsBlockZero length:int = TlsBlock;\ntlsBlockDomain = TlsBlock;\ntlsBlockGrease seed:int = TlsBlock;\ntlsBlockScope entries:Vector = TlsBlock;\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__(6927)))\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\t927: 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","SUPPORTED_IMAGE_CONTENT_TYPES","SUPPORTED_VIDEO_CONTENT_TYPES","SERVICE_NOTIFICATIONS_USER_ID","onTickEndCallbacks","onTickEndPrimaryCallbacks","buildCollectionByKey","collection","key","reduce","byKey","member","pick","object","keys","result","bytesToDataUri","bytes","shouldOmitPrefix","mimeType","btoa","String","fromCharCode","omitVirtualClassFields","instance","flags","CONSTRUCTOR_ID","SUBCLASS_OF_ID","className","classType","getBytes","rest","pathBytesToSvg","width","height","replace","path","len","length","i","num","buildPath","DEFAULT_THUMB_SIZE","w","h","buildApiThumbnailFromStripped","sizes","thumb","find","s","GramJs","realSizes","filter","dataUri","strippedPhotoToJpg","undefined","buildApiPhoto","photo","map","buildApiPhotoSize","id","thumbnail","photoSize","type","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","accessHash","buildStickerSet","set","archived","animated","installedDate","title","count","shortName","hasThumbnail","Boolean","buildStickerSetCovered","coveredStickerSet","stickerSet","stickerSetCovers","covers","cover","forEach","coverSticker","push","localDb","interpolateArray","data","fitCount","peak","newData","Array","springFactor","leftFiller","rightFiller","idx","floor","val","ApiMessageEntityTypes","ApiMediaFormat","isPeerUser","peer","hasOwnProperty","isPeerChat","buildApiPeerId","getApiChatIdFromMtpPeer","userId","chatId","channelId","resolveMessageApiChatId","mtpMessage","peerId","addMessageToLocalDb","message","messageFullId","media","webpage","action","addPhotoToLocalDb","addUserToLocalDb","user","shouldOverwrite","addEntitiesWithPhotosToLocalDb","entities","entity","chat","noOverwrite","addChatToLocalDb","serializeBytes","value","deserializeBytes","Buffer","from","getEntityTypeById","chatOrUserId","getEntityTypeByDeprecatedId","startsWith","buildPeer","buildMtpPeerId","buildInputPeer","BigInt","buildInputPeerFromLocalDb","buildInputEntity","buildInputStickerSet","buildInputDocument","buildInputMediaDocument","inputDocument","generateRandomBigInt","readBigIntFromBuffer","generateRandomBytes","buildMessageFromUpdate","update","fromId","buildMtpMessageEntity","offset","url","Bold","Italic","Underline","Strike","Code","Pre","language","Blockquote","TextUrl","Url","Hashtag","MentionName","isMessageWithMedia","buildInputContact","phone","firstName","lastName","clientId","buildChatBannedRights","bannedRights","untilDate","buildChatAdminRights","adminRights","buildShippingInfo","info","shippingAddress","buildInputPrivacyKey","privacyKey","buildInputReportReason","reason","abs","slice","buildInputGroupCall","groupCall","LOCAL_MEDIA_UPLOADING_TEMP_ID","currentUserId","localMessageCounter","buildApiSponsoredMessage","startParam","channelPost","chatInvite","chatInviteHash","randomId","chatInviteTitle","isBot","text","buildMessageTextContent","expiresAt","Date","now","channelPostId","buildApiMessage","buildApiMessageWithChatId","isChatWithSelf","isOutgoing","out","post","fwdFrom","content","buildMessageMediaContent","sticker","poll","contact","senderId","targetPeerId","isChannelPost","call","amount","currency","translationValues","targetUserIds","targetChatId","includes","withDuration","duration","video","join","mins","max","toString","Number","totalAmount","domain","buildAction","replyToMsgId","replyToTopId","replyToPeerId","replyTo","isEdited","editDate","editHide","inlineButtons","keyboardButtons","keyboardPlaceholder","isKeyboardSingleUse","messageId","replyMarkup","markup","rows","buttons","button","receiptMsgId","placeholder","singleUse","buildReplyButtons","forwardInfo","savedFromPeerId","savedFromPeer","date","isLinkedChannelPost","fromChatId","fromMessageId","savedFromMsgId","senderUserId","hiddenUserName","fromName","adminTitle","postAuthor","buildApiMessageForwardInfo","replies","mediaUnread","isMediaUnread","groupedId","isInAlbum","audio","shouldHideKeyboardButtons","views","isFromScheduled","fromScheduled","replyToMessageId","replyToChatId","replyToTopMessageId","mentioned","hasUnreadMention","isMentioned","viaBotId","comments","threadInfo","buildThreadInfo","noforwards","isProtected","buildApiMessageEntity","buildMessageDraft","draft","formattedText","replyingToId","ttlSeconds","buildSticker","buildPhoto","buildVideoFromDocument","buildVideo","audioAttribute","voice","thumbnailSizes","fileName","getFilenameFromDocument","buildAudio","waveform","buildVoice","buildApiDocument","buildDocumentFromMedia","phoneNumber","buildContact","buildPoll","results","buildPollFromMedia","webPage","buildWebPage","invoice","description","test","photoUrl","isTest","buildInvoice","buildInvoiceFromMedia","size","self","isMovSupported","videoAttr","a","gifAttr","supportsStreaming","roundMessage","isRound","isGif","mediaType","mediaSize","has","imageAttribute","timestamp","pollResults","answers","rawAnswers","answer","option","summary","isPublic","publicVoters","buildPollResults","rawResults","totalVoters","recentVoters","solution","solutionEntities","chosen","correct","voters","isChosen","isCorrect","votersCount","recentVoterIds","defaultBase","filenameAttribute","extension","split","buildNewPoll","localId","messageReplies","maxId","readMaxId","recentRepliers","apiChannelId","threadId","originChannelId","messagesCount","lastMessageId","lastReadInboxMessageId","recentReplierIds","getServerTime","serverTimeOffset","buildApiChatFieldsFromPeerEntity","peerEntity","isSupport","isMin","min","avatarHash","buildAvatarHash","isSignaturesShown","signatures","hasPrivateLink","hasLink","username","isVerified","verified","isCallActive","callActive","isCallNotEmpty","callNotEmpty","participantsCount","membersCount","joinDate","buildApiChatPermissions","isCreator","creator","buildApiChatRestrictions","buildApiChatMigrationInfo","buildApiChatFromDialog","dialog","folderId","unreadMark","unreadCount","unreadMentionsCount","notifySettings","silent","muteUntil","readOutboxMaxId","readInboxMaxId","isMuted","getApiChatTypeFromPeerEntity","getApiChatTitleFromMtpPeer","lastReadOutboxMessageId","hasUnreadMark","draftDate","currentUserBannedRights","defaultBannedRights","isRestricted","restrictions","restrictionReason","restricted","restrictionReasons","targetReason","platform","buildApiChatRestrictionReason","Object","assign","isNotJoined","left","kicked","migratedTo","buildApiChatFromPreview","preview","withForbidden","getUserName","megagroup","getPeerKey","photoId","buildChatMember","inviterId","joinedDate","kickedByUserId","kickedBy","promotedByUserId","promotedBy","customTitle","rank","isAdmin","isOwner","buildChatMembers","participants","buildChatTypingStatus","buildApiChatFolder","channels","broadcasts","pinnedChatIds","pinnedPeers","includedChatIds","includePeers","excludedChatIds","excludePeers","buildApiChatFolderFromSuggested","buildApiChatBotCommands","botInfos","botCommands","botInfo","botId","concat","commands","mtpCommand","buildApiUserFromFull","mtpUserFull","fullUser","about","commonChatsCount","pinnedMsgId","blocked","buildApiUser","fullInfo","bio","pinnedMessageId","isBlocked","botDescription","buildApiBotCommands","mtpUser","userType","bot","deleted","isSelf","mutualContact","isContact","canBeInvitedToGroup","botNochats","noStatus","status","botInlinePlaceholder","botPlaceholder","buildApiUserStatus","mtpStatus","expires","wasOnline","command","buildApiUsersAndStatuses","mtpUsers","userStatusesById","buildApiWallpaper","wallpaper","slug","buildApiSession","session","isCurrent","current","isOfficialApp","officialApp","isPasswordPending","passwordPending","hash","buildPrivacyRules","rules","visibility","allowUserIds","allowChatIds","blockUserIds","blockChatIds","rule","buildApiNotifyException","showPreviews","sound","isSilent","shouldShowPreviews","buildApiCountry","country","code","hidden","iso2","defaultName","name","countryCode","prefixes","patterns","isHidden","buildApiGroupCallParticipant","participant","versioned","canSelfUnmute","justJoined","muted","mutedByYou","source","volume","volumeByAdmin","videoJoined","presentation","raiseHandRating","isLeft","isMutedByMe","hasJustJoined","isVolumeByAdmin","isVersioned","isVideoJoined","isUser","buildApiGroupCallParticipantVideo","participantVideo","audioSource","endpoint","paused","sourceGroups","isPaused","buildApiGroupCallParticipantVideoSourceGroup","participantVideoSourceGroup","semantics","sources","buildApiGroupCall","connectionState","version","streamDcId","scheduleDate","canChangeJoinMuted","joinMuted","canStartVideo","scheduleStartSubscribed","isLoaded","onUpdate","sentMessageIds","shouldIgnoreNextChannelUpdate","dispatchUserAndChatUpdates","e","updater","originRequest","connection","timeOffset","state","shouldForceReply","buildApiMessageFromShort","selective","_entities","dcId","buildChatPhotoForLocalDb","localDbChatId","newProfilePhoto","some","ids","existingIds","missingIds","profilePhotoIds","setTimeout","popup","error","notification","currentDate","inboxDate","buildApiMessageFromNotification","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","apiUserId","updatedUser","peerType","buildPrivacyKey","JSON","parse","params","groupCallId","ApiErrors","PHONE_NUMBER_INVALID","PHONE_CODE_INVALID","PASSWORD_HASH_INVALID","PHONE_PASSWORD_FLOOD","PHONE_NUMBER_BANNED","authController","onRequestPhoneNumber","buildAuthStateUpdate","Promise","resolve","reject","onRequestCode","isCodeViaApp","onRequestPassword","hint","onRequestRegistration","onRequestQrCode","qrCode","token","onAuthError","err","errors","hours","ceil","seconds","authorizationState","provideAuthPhoneNumber","provideAuthCode","provideAuthPassword","password","provideAuthRegistration","registration","restartAuth","restartAuthWithQr","cacheApi","caches","Type","async","fetch","cacheName","isHtmlAllowed","request","Request","cache","open","response","match","contentType","headers","get","Text","Blob","blob","shouldRecreate","resolvedType","Json","json","console","warn","save","cacheData","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","hasErrorKey","dispatchErrorUpdate","downloadMedia","args","onProgress","mediaFormat","start","end","fullSize","mediaMatch","arrayBuffer","entityType","entityId","sizeType","Stream","acceptsBuffer","progressCallback","workers","getMessageMediaMimeType","downloadStickerSetThumb","Lottie","downloadProfilePhoto","download","parsed","BlobUrl","inflate","to","Progressive","buffer","parseMedia","canCache","prepared","mediaData","URL","createObjectURL","downloadMediaWithClient","uploadFile","file","updateTwoFaSettings","fetchCurrentUser","userFull","currentUser","_currentUserId","onCurrentUserUpdate","MAX_INT_32","fetchChats","limit","offsetDate","withPinned","lastLocalServiceMessage","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","defaultSendAs","inviteLink","link","members","fetchMembers","kickedMembers","bannedUsers","adminMembers","adminUsers","mtpLinkedChat","slowMode","nextSendDate","migratedFrom","maxMessageId","canViewMembers","isPreHistoryHidden","sendAsId","getFullChannelInfo","getFullChatInfo","searchChats","query","q","localPeerIds","myResults","allChats","allUsers","localChats","r","localUsers","u","globalChats","globalUsers","fetchChat","requestChatUpdate","lastLocalMessage","noLastMessage","peers","lastRemoteMessage","saveDraft","clearDraft","updateChatMutedState","settings","createChannel","noErrorUpdate","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","updateChatAdmin","updateChatTitle","updateChatAbout","toggleSignatures","memberFilter","fetchGroupsForDiscussion","setDiscussionGroup","group","migrateChat","openChatByInvite","requestNeeded","isChannel","isRequestNeeded","addChatMembers","all","deleteChatMember","viewMessages","sendMessages","sendMedia","sendStickers","sendGifs","sendGames","sendInline","embedLinks","sendPolls","changeInfo","inviteUsers","pinMessages","store","importChatInvite","toggleIsProtected","File","constructor","fileBits","super","this","fetchMessages","pagination","RequestClass","msgId","c","threadInfos","fetchMessage","queue","sendMessage","replyingTo","attachment","gif","scheduledAt","noWebPage","sendAs","filename","blobUrl","previewBlobUrl","quick","inputWaveform","buildUploadingMedia","buildLocalMessage","groupIndex","groupedUploads","counter","singleMediaByIndex","prevQueue","uploadMedia","inputMedia","uploadedMedia","messageMedia","fileReference","fetchInputMedia","multiMedia","values","sendGroupedMedia","pollParams","quiz","question","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","sendMessageAction","gramAction","buildSendMessageAction","topMsgId","markMessageListRead","requestThreadInfoUpdate","markMessagesRead","topMessageResult","repliesResult","offsetId","addOffset","discussionChatId","topMessageId","firstMessageId","noTopChatsRequest","searchMessagesLocal","chatOrUser","minDate","maxDate","nextOffsetId","totalCount","searchMessagesGlobal","offsetRate","nextRate","fetchWebPagePreview","sendPollVote","loadPollOptionResults","shouldResetVoters","votes","vote","nextOffset","forwardMessages","fromChat","toChat","randomIds","index","isAudio","asIncomingInChatWithSelf","buildLocalForwardedMessage","fromPeer","toPeer","sil2ent","findFirstMessageIdAfterDate","fetchScheduledHistory","sendScheduledMessages","isServiceMessageWithMedia","fetchPinnedMessages","fetchSeenBy","fetchSendAs","saveDefaultSendAs","fetchSponsoredMessages","viewSponsoredMessage","random","inputGifBot","fetchFullUser","input","userWithFullInfo","fetchCommonChats","commonChats","mtpChat","isFullyLoaded","fetchNearestCountry","dcInfo","fetchTopUsers","topPeers","correspondents","fetchContactList","fetchUsers","updateContact","addContact","deleteUser","fetchProfilePhotos","fetchStickerSets","allStickers","sets","fetchRecentStickers","stickers","processStickerResult","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","keywords","emojiKeyword","keyword","emoticons","checkChatUsername","setChatUsername","updatePrivateLink","usageLimit","expireDate","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","getGroupCall","discardGroupCall","editGroupCallParticipant","presentationPaused","videoStopped","videoPaused","raiseHand","editGroupCallTitle","exportGroupCallInvite","fetchGroupCallParticipants","leaveGroupCall","joinGroupCall","inviteHash","joinAs","createGroupCall","toJSNumber","joinGroupCallPresentation","toggleGroupCallStartSubscription","subscribed","leaveGroupCallPresentation","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","fetchCountryList","countryList","countries","phoneCodes","array","countryCodes","isArray","sort","b","localeCompare","general","buildApiWebDocument","answerCallbackButton","fetchTopInlineBots","botsInline","fetchInlineBot","fetchInlineBotResults","queryId","switchPm","isGallery","gallery","help","buildApiBotInlineMediaResult","webDocument","webThumbnail","buildApiBotInlineResult","sendInlineBotResult","resultId","startBot","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","initCalls","userAgent","sessions","TelegramClient","process","deviceModel","navigator","systemVersion","appVersion","useWSS","additionalDcsDisabled","testServers","addEventHandler","phoneCode","firstAndLastNames","initialMethod","getSessionData","initClient","flushUpdatesOnTickEnd","schedulerFn","fn","waiting","_args","throttleWith","callback","isPrimary","then","currentCallbacks","currentPrimaryCallbacks","cb","throttleId","pendingUpdates","currentThrottleId","currentUpdates","flushUpdatesThrottled","ms","shouldRunFirst","interval","isPending","setInterval","clearInterval","throttle","onerror","sendToOrigin","addEventListener","callbackState","Map","postMessage","onmessage","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","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","target","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","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","reader","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","runExclusive","PromisedWebSockets","MessagePacker","AsyncQueue","tl","events","extensions","helpers","PUBLIC_KEYS","fingerprint","_serverKeys","keyInfo","doAuthentication","nonce","resPQ","factorize","pBuffer","qBuffer","pqInnerData","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","reconnect","decryptMessageData","_handleBadAuthKey","_processMessage","shouldSkipForMain","broken","obj","handler","_popStates","toPop","reqMsgId","readResult","innerMessage","pong","newTimeOffset","updateTimeOffset","badSalt","badMsgId","newServerSalt","badMsg","errorCode","_sequence","answerMsgId","serverSalt","repeat","_reconnect","reset","newConnection","_ip","_port","_testServers","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","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","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":""}