telegram-tt/dist/8090.31460a17f3f5829c1290.js.map
Alexander Zinchuk 5652dd1fc4 [Build]
2022-09-15 10:20:00 +02:00

1 line
1.1 MiB

{"version":3,"file":"8090.31460a17f3f5829c1290.js","mappings":"UAAIA,ECAAC,E,mlMCEG,MA2HMC,GA3EyB,oBAAXC,QAA0BA,OAAOC,YA2EzBC,KAAKC,MAAM,MACjCC,EAA6B,IAAIC,IAAI,CAChD,aAAc,sBAAuB,iBAAkB,0BAA2B,kBAkCvEC,EAAiB,kBAGjBC,EAAgC,IAAIF,IAAI,CACnD,YAAa,YAAa,eAGfG,EAAgC,IAAIH,IAAI,CACnD,cAGWI,EAAgC,IAAIJ,IAAI,CACnD,YACA,YACA,YACA,aACA,aACA,YACA,YACA,YACA,gBAsBWK,GAnB6B,IAAIL,IAAI,IAC7CE,KACAC,IAcyC,IAAIH,IAAI,CAAC,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,OAGhH,UAwBhCM,EAAkE,CAC7EC,mBAAoB,CAAC,IAAM,KAC3BC,cAAe,CAAC,EAAG,IACnBC,UAAW,CAAC,IAAK,KACjBC,mBAAoB,CAAC,IAAK,KAC1BC,cAAe,CAAC,GAAI,IACpBC,mBAAoB,CAAC,EAAG,IACxBC,cAAe,CAAC,KAAM,MACtBC,SAAU,CAAC,IAAK,KAChBC,eAAgB,CAAC,GAAI,IACrBC,YAAa,CAAC,GAAI,MCzHpB,IA4BIC,EACAC,E,eCvIG,SAASC,EAA2CC,EAAiBC,GAC1E,OAAOD,EAAWE,QAAO,CAACC,EAA2BC,KACnDD,EAAMC,EAAOH,IAAQG,EAEdD,IACN,IAaE,SAASE,EAA2BC,EAAWC,GACpD,OAAOA,EAAKL,QAAO,CAACM,EAAQP,KAC1BO,EAAOP,GAAOK,EAAOL,GACdO,IACN,ICmSE,IAAKC,EChUAC,G,SDgUAD,GAAAA,EAAAA,KAAAA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F,gBACZF,EAAYtyF,EAASwyF,cAAcC,MAC/BH,GAAW,CACf,IAAII,EAAU1yF,EAAS2yF,qBAAqB,UACzCD,EAAQ11F,SAAQs1F,EAAYI,EAAQA,EAAQ11F,OAAS,GAAGy1F,KAK7D,IAAKH,EAAW,MAAM,IAAI7gE,MAAM,yDAChC6gE,EAAYA,EAAUz1F,QAAQ,OAAQ,IAAIA,QAAQ,QAAS,IAAIA,QAAQ,YAAa,KACpF8zF,EAAoBz2C,EAAIo4C,G,SCXxB,IAAIM,EAAkB,CACrB,KAAM,GAgBPjC,EAAoBpF,EAAEtuF,EAAI,CAAC20F,EAAS/uB,KAE/B+vB,EAAgBhB,IAElBW,cAAc5B,EAAoBz2C,EAAIy2C,EAAoB3uD,EAAE4vD,KAK/D,IAAIiB,EAAqBlxF,KAA6B,uBAAIA,KAA6B,wBAAK,GACxFmxF,EAA6BD,EAAmBp+E,KAAKmsD,KAAKiyB,GAC9DA,EAAmBp+E,KAvBC7Q,IACnB,IAAKstF,EAAU6B,EAAaC,GAAWpvF,EACvC,IAAI,IAAIgtF,KAAYmC,EAChBpC,EAAoBjoF,EAAEqqF,EAAanC,KACrCD,EAAoB57B,EAAE67B,GAAYmC,EAAYnC,IAIhD,IADGoC,GAASA,EAAQrC,GACdO,EAASl0F,QACd41F,EAAgB1B,EAAS7b,OAAS,EACnCyd,EAA2BlvF,K,GzHnBxBzK,EAAOw3F,EAAoB7oC,EAC/B6oC,EAAoB7oC,EAAI,IAChB9yB,QAAQwR,IAAI,CAClBmqD,EAAoB3gE,EAAE,MACtB2gE,EAAoB3gE,EAAE,QACpBi+B,KAAK90D,G0HJiBw3F,EAAoB7oC,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/types/messages.ts","webpack://telegram-t/./src/api/types/media.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/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/calls.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/bots.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/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/bots.ts","webpack://telegram-t/./src/api/gramjs/methods/calls.ts","webpack://telegram-t/./src/api/gramjs/methods/payments.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/payments.ts","webpack://telegram-t/./src/api/gramjs/methods/account.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/appConfig.ts","webpack://telegram-t/./src/api/gramjs/methods/settings.ts","webpack://telegram-t/./src/api/gramjs/methods/reactions.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/statistics.ts","webpack://telegram-t/./src/api/gramjs/methods/statistics.ts","webpack://telegram-t/./src/api/gramjs/methods/phoneCallState.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/network/updates.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 Promise.all([\n\t\t__webpack_require__.e(5802),\n\t\t__webpack_require__.e(5313)\n\t]).then(next);\n};","import type { ApiLimitType } from './global/types';\n\nexport const APP_NAME = process.env.APP_NAME || 'Telegram WebZ';\nexport const APP_VERSION = process.env.APP_VERSION!;\n\nexport const PRODUCTION_HOSTNAME = 'web.telegram.org';\n\nexport const DEBUG = process.env.APP_ENV !== 'production';\nexport const DEBUG_MORE = false;\n\nexport const IS_MOCKED_CLIENT = process.env.APP_MOCKED_CLIENT === '1';\nexport const IS_TEST = process.env.APP_ENV === 'test';\nexport const IS_PERF = process.env.APP_ENV === 'perf';\nexport const IS_BETA = process.env.APP_ENV === 'staging';\n\nexport const BETA_CHANGELOG_URL = 'https://telegra.ph/WebZ-Beta-04-01';\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 PAGE_TITLE = 'Telegram';\nexport const INACTIVE_MARKER = ' [Inactive]';\n\nexport const DEBUG_PAYMENT_SMART_GLOCAL = false;\n\nexport const SESSION_USER_KEY = 'user_auth';\nexport const LEGACY_SESSION_KEY = 'GramJs:sessionId';\nexport const PASSCODE_CACHE_NAME = 'tt-passcode';\n\nexport const GLOBAL_STATE_CACHE_DISABLED = false;\nexport const GLOBAL_STATE_CACHE_KEY = 'tt-global-state';\nexport const GLOBAL_STATE_CACHE_USER_LIST_LIMIT = 500;\nexport const GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT = 200;\nexport const GLOBAL_STATE_CACHE_CHATS_WITH_MESSAGES_LIMIT = 30;\nexport const GLOBAL_STATE_CACHE_CUSTOM_EMOJI_LIMIT = 150;\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-v13';\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;\nexport const REACTION_LIST_LIMIT = 100;\nexport const REACTION_UNREAD_SLICE = 100;\nexport const MENTION_UNREAD_SLICE = 100;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 20;\n\nexport const SPONSORED_MESSAGE_CACHE_MS = 300000; // 5 min\n\nexport const DEFAULT_VOLUME = 1;\nexport const DEFAULT_PLAYBACK_RATE = 1;\nexport const PLAYBACK_RATE_FOR_AUDIO_MIN_DURATION = 20 * 60; // 20 min\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// eslint-disable-next-line max-len\nexport const EDITABLE_INPUT_CSS_SELECTOR = `.messages-layout .Transition__slide--active #${EDITABLE_INPUT_ID}, .messages-layout .Transition > .to #${EDITABLE_INPUT_ID}`;\n\nexport const CUSTOM_APPENDIX_ATTRIBUTE = 'data-has-custom-appendix';\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 MAX_SCREEN_WIDTH_FOR_EXPAND_PINNED_MESSAGES = 1340; // 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_MIN_ID = 1e11; // `Date.now()` is always used as base\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 LOCK_SCREEN_ANIMATION_DURATION_MS = 200;\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 EMOJI_SIZE_PICKER = 40;\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 EMOJI_SIZE_MODAL = 40;\nexport const STICKER_SIZE_TWO_FA = 160;\nexport const STICKER_SIZE_PASSCODE = 160;\nexport const STICKER_SIZE_DISCUSSION_GROUPS = 140;\nexport const STICKER_SIZE_FOLDER_SETTINGS = 100;\nexport const STICKER_SIZE_INLINE_BOT_RESULT = 100;\nexport const STICKER_SIZE_JOIN_REQUESTS = 140;\nexport const STICKER_SIZE_INVITES = 140;\nexport const RECENT_STICKERS_LIMIT = 20;\nexport const RECENT_SYMBOL_SET_ID = 'recent';\nexport const FAVORITE_SYMBOL_SET_ID = 'favorite';\nexport const CHAT_STICKER_SET_ID = 'chatStickers';\nexport const PREMIUM_STICKER_SET_ID = 'premium';\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';\nexport const VIDEO_WEBM_TYPE = 'video/webm';\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 SUPPORTED_AUDIO_CONTENT_TYPES = new Set([\n 'audio/mp3',\n 'audio/ogg',\n 'audio/wav',\n 'audio/mpeg',\n 'audio/flac',\n 'audio/aac',\n 'audio/m4a',\n 'audio/mp4',\n 'audio/x-m4a',\n]);\n\nexport const CONTENT_TYPES_WITH_PREVIEW = new Set([\n ...SUPPORTED_IMAGE_CONTENT_TYPES,\n ...SUPPORTED_VIDEO_CONTENT_TYPES,\n]);\n\nexport const CONTENT_NOT_SUPPORTED = 'The message is not supported on this version of Telegram.';\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_-]+)?/;\nexport const RE_TME_LINK = /^(https?:\\/\\/)?([-a-zA-Z0-9@:%_+~#=]{1,32}\\.)?t\\.me/;\nexport const RE_TELEGRAM_LINK = /^(https?:\\/\\/)?telegram\\.org\\//;\nexport const TME_LINK_PREFIX = 'https://t.me/';\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 FEEDBACK_URL = 'https://bugs.telegram.org/?tag_ids=41&sort=time';\n\nexport const LIGHT_THEME_BG_COLOR = '#99BA92';\nexport const DARK_THEME_BG_COLOR = '#0F0F0F';\nexport const DEFAULT_PATTERN_COLOR = '#4A8E3A8C';\nexport const DARK_THEME_PATTERN_COLOR = '#0A0A0A8C';\nexport const MAX_UPLOAD_FILEPART_SIZE = 524288;\n\n// Group calls\nexport const GROUP_CALL_VOLUME_MULTIPLIER = 100;\nexport const GROUP_CALL_DEFAULT_VOLUME = 100 * GROUP_CALL_VOLUME_MULTIPLIER;\nexport const GROUP_CALL_THUMB_VIDEO_DISABLED = true;\n\nexport const DEFAULT_LIMITS: Record<ApiLimitType, readonly [number, number]> = {\n uploadMaxFileparts: [4000, 8000],\n stickersFaved: [5, 10],\n savedGifs: [200, 400],\n dialogFiltersChats: [100, 200],\n dialogFilters: [10, 20],\n dialogFolderPinned: [5, 10],\n captionLength: [1024, 2048],\n channels: [500, 1000],\n channelsPublic: [10, 20],\n aboutLength: [70, 140],\n};\n","type Scheduler =\n typeof requestAnimationFrame\n | typeof onTickEnd;\n\nexport function debounce<F extends AnyToVoidFunction>(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n shouldRunLast = true,\n) {\n let waitingTimeout: number | undefined;\n\n return (...args: Parameters<F>) => {\n if (waitingTimeout) {\n clearTimeout(waitingTimeout);\n waitingTimeout = undefined;\n } else if (shouldRunFirst) {\n 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<F extends AnyToVoidFunction>(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n) {\n let interval: number | undefined;\n let isPending: boolean;\n let args: Parameters<F>;\n\n return (..._args: Parameters<F>) => {\n isPending = true;\n args = _args;\n\n if (!interval) {\n if (shouldRunFirst) {\n isPending = false;\n 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<F extends AnyToVoidFunction>(fn: F) {\n return throttleWith(fastRaf, fn);\n}\n\nexport function throttleWithPrimaryRaf<F extends AnyToVoidFunction>(fn: F) {\n return throttleWith(fastRafPrimary, fn);\n}\n\nexport function throttleWithTickEnd<F extends AnyToVoidFunction>(fn: F) {\n return throttleWith(onTickEnd, fn);\n}\n\nexport function throttleWith<F extends AnyToVoidFunction>(schedulerFn: Scheduler, fn: F) {\n let waiting = false;\n let args: Parameters<F>;\n\n return (..._args: Parameters<F>) => {\n args = _args;\n\n if (!waiting) {\n waiting = true;\n\n schedulerFn(() => {\n waiting = false;\n 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\nexport const pause = (ms: number) => new Promise<void>((resolve) => {\n setTimeout(() => resolve(), ms);\n});\n\nexport function rafPromise() {\n return new Promise<void>((resolve) => {\n fastRaf(resolve);\n });\n}\n\nlet fastRafCallbacks: NoneToVoidFunction[] | undefined;\nlet fastRafPrimaryCallbacks: NoneToVoidFunction[] | undefined;\n\n// May result in an immediate execution if called from another `requestAnimationFrame` callback\nexport function fastRaf(callback: NoneToVoidFunction, isPrimary = false) {\n if (!fastRafCallbacks) {\n fastRafCallbacks = isPrimary ? [] : [callback];\n fastRafPrimaryCallbacks = isPrimary ? [callback] : [];\n\n requestAnimationFrame(() => {\n const currentCallbacks = fastRafCallbacks!;\n const currentPrimaryCallbacks = fastRafPrimaryCallbacks!;\n fastRafCallbacks = undefined;\n fastRafPrimaryCallbacks = undefined;\n currentPrimaryCallbacks.forEach((cb) => cb());\n currentCallbacks.forEach((cb) => cb());\n });\n } else if (isPrimary) {\n fastRafPrimaryCallbacks!.push(callback);\n } else {\n fastRafCallbacks.push(callback);\n }\n}\n\nexport function 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<Member> = Record<number | string, Member>;\n\ntype OrderDirection =\n 'asc'\n | 'desc';\n\ninterface OrderCallback<T> {\n (member: T): any;\n}\n\nexport function buildCollectionByKey<T extends AnyLiteral>(collection: T[], key: keyof T) {\n return collection.reduce((byKey: CollectionByKey<T>, member: T) => {\n byKey[member[key]] = member;\n\n return byKey;\n }, {});\n}\n\nexport function mapValues<R extends any, M extends any>(\n byKey: CollectionByKey<M>,\n callback: (member: M, key: string, index: number, originalByKey: CollectionByKey<M>) => R,\n): CollectionByKey<R> {\n return Object.keys(byKey).reduce((newByKey: CollectionByKey<R>, key, index) => {\n newByKey[key] = callback(byKey[key], key, index, byKey);\n return newByKey;\n }, {});\n}\n\nexport function pick<T, K extends keyof T>(object: T, keys: K[]) {\n return keys.reduce((result, key) => {\n result[key] = object[key];\n return result;\n }, {} as Pick<T, K>);\n}\n\nexport function pickTruthy<T, K extends keyof T>(object: T, keys: K[]) {\n return keys.reduce((result, key) => {\n if (object[key]) {\n result[key] = object[key];\n }\n\n return result;\n }, {} as Pick<T, K>);\n}\n\nexport function omit<T, K extends keyof T>(object: T, keys: K[]) {\n const stringKeys = new Set(keys.map(String));\n const savedKeys = Object.keys(object)\n .filter((key) => !stringKeys.has(key)) as Array<Exclude<keyof T, K>>;\n\n return pick(object, savedKeys);\n}\n\nexport function orderBy<T>(\n collection: T[],\n orderRule: (keyof T) | OrderCallback<T> | ((keyof T) | OrderCallback<T>)[],\n mode: OrderDirection | [OrderDirection, OrderDirection] = 'asc',\n): T[] {\n function compareValues(a: T, b: T, currentOrderRule: (keyof T) | OrderCallback<T>, 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 unique<T extends any>(array: T[]): T[] {\n return Array.from(new Set(array));\n}\n\nexport function uniqueByField<T extends any>(array: T[], field: keyof T): T[] {\n return [...new Map(array.map((item) => [item[field], item])).values()];\n}\n\nexport function compact<T extends any>(array: T[]) {\n return array.filter(Boolean);\n}\n\nexport function areSortedArraysEqual(array1: any[], array2: any[]) {\n if (array1.length !== array2.length) {\n return false;\n }\n\n return array1.every((item, i) => item === array2[i]);\n}\n\nexport function areSortedArraysIntersecting(array1: any[], array2: any[]) {\n return array1[0] <= array2[array2.length - 1] && array1[array1.length - 1] >= array2[0];\n}\n\nexport function findIntersectionWithSet<T>(array: T[], set: Set<T>): T[] {\n return array.filter((a) => set.has(a));\n}\n\nexport function split<T extends any>(array: T[], chunkSize: number) {\n const result: T[][] = [];\n for (let i = 0; i < array.length; i += chunkSize) {\n result.push(array.slice(i, i + chunkSize));\n }\n\n return result;\n}\n\nexport function cloneDeep<T>(value: T): T {\n if (typeof value !== 'object') {\n return value;\n }\n\n if (Array.isArray(value)) {\n return value.map(cloneDeep) as typeof value;\n }\n\n return Object.keys(value).reduce((acc, key) => {\n acc[key as keyof T] = cloneDeep(value[key as keyof T]);\n return acc;\n }, {} as T);\n}\n\nexport function findLast<T>(array: Array<T>, predicate: (value: T, index: number, obj: T[]) => boolean): T | undefined {\n let cursor = array.length;\n\n while (cursor--) {\n if (predicate(array[cursor], cursor, array)) {\n return array[cursor];\n }\n }\n\n return undefined;\n}\n","import type { ApiWebDocument } from './bots';\nimport type { ApiGroupCall, PhoneCallAction } from './calls';\nimport type { ApiChat } from './chats';\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 ApiVideoSize extends ApiDimensions {\n type: 'u' | 'v';\n videoStartTs: number;\n size: number;\n}\n\nexport interface ApiThumbnail extends ApiDimensions {\n dataUri: string;\n}\n\nexport interface ApiPhoto {\n id: string;\n thumbnail?: ApiThumbnail;\n isVideo?: boolean;\n sizes: ApiPhotoSize[];\n videoSizes?: ApiVideoSize[];\n blobUrl?: string;\n}\n\nexport interface ApiSticker {\n id: string;\n stickerSetInfo: ApiStickerSetInfo;\n emoji?: string;\n isCustomEmoji?: boolean;\n isLottie: boolean;\n isVideo: boolean;\n width?: number;\n height?: number;\n thumbnail?: ApiThumbnail;\n isPreloadedGlobally?: boolean;\n hasEffect?: boolean;\n isFree?: boolean;\n}\n\nexport interface ApiStickerSet {\n archived?: true;\n isLottie?: true;\n isVideos?: true;\n isEmoji?: 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<string, ApiSticker[]>;\n covers?: ApiSticker[];\n shortName: string;\n}\n\ntype ApiStickerSetInfoShortName = {\n shortName: string;\n};\n\ntype ApiStickerSetInfoId = {\n id: string;\n accessHash: string;\n};\n\ntype ApiStickerSetInfoMissing = {\n isMissing: true;\n};\n\nexport type ApiStickerSetInfo = ApiStickerSetInfoShortName | ApiStickerSetInfoId | ApiStickerSetInfoMissing;\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 isMin?: true;\n results?: ApiPollResult[];\n totalVoters?: number;\n recentVoterIds?: string[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n}\n\n// First type used for state, second - for API requests\nexport type ApiInputInvoice = {\n chatId: string;\n messageId: number;\n} | {\n slug: string;\n};\n\nexport type ApiRequestInputInvoice = {\n chat: ApiChat;\n messageId: number;\n} | {\n slug: string;\n};\n\nexport interface ApiInvoice {\n text: string;\n title: string;\n photo?: ApiWebDocument;\n amount: number;\n currency: string;\n receiptMsgId?: number;\n isTest?: boolean;\n isRecurring?: boolean;\n recurringTermsUrl?: string;\n}\n\ninterface ApiGeoPoint {\n long: number;\n lat: number;\n accessHash: string;\n accuracyRadius?: number;\n}\n\ninterface ApiGeo {\n type: 'geo';\n geo: ApiGeoPoint;\n}\n\ninterface ApiVenue {\n type: 'venue';\n geo: ApiGeoPoint;\n title: string;\n address: string;\n provider: string;\n venueId: string;\n venueType: string;\n}\n\ninterface ApiGeoLive {\n type: 'geoLive';\n geo: ApiGeoPoint;\n heading?: number;\n period: number;\n}\n\nexport type ApiLocation = ApiGeo | ApiVenue | ApiGeoLive;\n\nexport type ApiGame = {\n title: string;\n description: string;\n photo?: ApiPhoto;\n shortName: string;\n id: string;\n accessHash: string;\n document?: ApiDocument;\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<ApiGroupCall>;\n phoneCall?: PhoneCallAction;\n score?: number;\n months?: number;\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 type ApiMessageEntityDefault = {\n type: Exclude<\n `${ApiMessageEntityTypes}`,\n `${ApiMessageEntityTypes.Pre}` | `${ApiMessageEntityTypes.TextUrl}` | `${ApiMessageEntityTypes.MentionName}` |\n `${ApiMessageEntityTypes.CustomEmoji}`\n >;\n offset: number;\n length: number;\n};\n\nexport type ApiMessageEntityPre = {\n type: ApiMessageEntityTypes.Pre;\n offset: number;\n length: number;\n language?: string;\n};\n\nexport type ApiMessageEntityTextUrl = {\n type: ApiMessageEntityTypes.TextUrl;\n offset: number;\n length: number;\n url: string;\n};\n\nexport type ApiMessageEntityMentionName = {\n type: ApiMessageEntityTypes.MentionName;\n offset: number;\n length: number;\n userId: string;\n};\n\nexport type ApiMessageEntityCustomEmoji = {\n type: ApiMessageEntityTypes.CustomEmoji;\n offset: number;\n length: number;\n documentId: string;\n};\n\nexport type ApiMessageEntity = ApiMessageEntityDefault | ApiMessageEntityPre | ApiMessageEntityTextUrl |\nApiMessageEntityMentionName | ApiMessageEntityCustomEmoji;\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 Spoiler = 'MessageEntitySpoiler',\n CustomEmoji = 'MessageEntityCustomEmoji',\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 location?: ApiLocation;\n game?: ApiGame;\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 forwards?: 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 transcriptionId?: string;\n isTranscriptionError?: boolean;\n reactors?: {\n nextOffset?: string;\n count: number;\n reactions: ApiUserReaction[];\n };\n reactions?: ApiReactions;\n}\n\nexport interface ApiReactions {\n canSeeList?: boolean;\n results: ApiReactionCount[];\n recentReactions?: ApiUserReaction[];\n}\n\nexport interface ApiUserReaction {\n userId: string;\n reaction: string;\n isBig?: boolean;\n isUnread?: boolean;\n}\n\nexport interface ApiReactionCount {\n isChosen?: boolean;\n count: number;\n reaction: string;\n}\n\nexport interface ApiAvailableReaction {\n selectAnimation?: ApiDocument;\n activateAnimation?: ApiDocument;\n effectAnimation?: ApiDocument;\n staticIcon?: ApiDocument;\n centerIcon?: ApiDocument;\n aroundAnimation?: ApiDocument;\n reaction: string;\n title: string;\n isInactive?: boolean;\n isPremium?: 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 isRecommended?: boolean;\n isBot?: boolean;\n channelPostId?: number;\n startParam?: string;\n chatInviteHash?: string;\n chatInviteTitle?: string;\n text: ApiFormattedText;\n expiresAt: number;\n};\n\n// KeyboardButtons\n\ninterface ApiKeyboardButtonSimple {\n type: 'unsupported' | 'buy' | 'command' | 'requestPhone' | 'game';\n text: string;\n}\n\ninterface ApiKeyboardButtonReceipt {\n type: 'receipt';\n text: string;\n receiptMessageId: number;\n}\n\ninterface ApiKeyboardButtonUrl {\n type: 'url';\n text: string;\n url: string;\n}\n\ninterface ApiKeyboardButtonSimpleWebView {\n type: 'simpleWebView';\n text: string;\n url: string;\n}\n\ninterface ApiKeyboardButtonWebView {\n type: 'webView';\n text: string;\n url: string;\n}\n\ninterface ApiKeyboardButtonCallback {\n type: 'callback';\n text: string;\n data: string;\n}\n\ninterface ApiKeyboardButtonRequestPoll {\n type: 'requestPoll';\n text: string;\n isQuiz?: boolean;\n}\n\ninterface ApiKeyboardButtonSwitchBotInline {\n type: 'switchBotInline';\n text: string;\n query: string;\n isSamePeer?: boolean;\n}\n\ninterface ApiKeyboardButtonUserProfile {\n type: 'userProfile';\n text: string;\n userId: string;\n}\n\ninterface ApiKeyboardButtonUrlAuth {\n type: 'urlAuth';\n text: string;\n url: string;\n buttonId: number;\n}\n\nexport type ApiTranscription = {\n text: string;\n isPending?: boolean;\n transcriptionId: string;\n};\n\nexport type ApiKeyboardButton = (\n ApiKeyboardButtonSimple\n | ApiKeyboardButtonReceipt\n | ApiKeyboardButtonUrl\n | ApiKeyboardButtonCallback\n | ApiKeyboardButtonRequestPoll\n | ApiKeyboardButtonSwitchBotInline\n | ApiKeyboardButtonUserProfile\n | ApiKeyboardButtonWebView\n | ApiKeyboardButtonSimpleWebView\n | ApiKeyboardButtonUrlAuth\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' | 'illegalDrugs' | 'personalDetails' | 'other';\n\nexport type ApiSendMessageAction = {\n type: 'cancel' | 'typing' | 'recordAudio' | 'chooseSticker' | 'playingGame';\n};\n\nexport type ApiThemeParameters = {\n bg_color: string;\n text_color: string;\n hint_color: string;\n link_color: string;\n button_color: string;\n button_text_color: string;\n secondary_bg_color: string;\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 Progressive,\n Stream,\n DownloadUrl,\n Text,\n}\n\nexport type ApiParsedMedia = string | Blob | ArrayBuffer;\nexport type ApiPreparedMedia = string;\n","import type { 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<T extends GramJs.VirtualClass<T> & { flags?: any }>(\n instance: T,\n): Omit<T, VirtualFields> {\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 = '<?xml version=\"1.0\" encoding=\"utf-8\"?><svg version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" viewBox=\"0 0 {{width}} {{height}}\" xml:space=\"preserve\"><path fill-opacity=\"0.1\" d=\"{{path}}\" /></svg>';\nconst LOOKUP = 'AACAAAAHAAALMAAAQASTAVAAAZaacaaaahaaalmaaaqastava.az0123456789-,';\n\nexport function pathBytesToSvg(bytes: Buffer, width: number, height: number) {\n return TEMPLATE\n .replace('{{path}}', buildPath(bytes))\n .replace('{{width}}', String(width))\n .replace('{{height}}', String(height));\n}\n\nfunction buildPath(bytes: Buffer) {\n let path = 'M';\n\n const len = bytes.length;\n for (let i = 0; i < len; i++) {\n const num = bytes[i];\n if (num >= 128 + 64) {\n path += LOOKUP[num - 128 - 64];\n } else {\n if (num >= 128) {\n path += ',';\n } else if (num >= 64) {\n path += '-';\n }\n path += String(num & 63);\n }\n }\n\n path += 'z';\n\n return path;\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport { strippedPhotoToJpg } from '../../../lib/gramjs/Utils';\n\nimport type {\n ApiPhoto, ApiPhotoSize, ApiThumbnail, ApiVideoSize,\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 | GramJs.DocumentAttributeVideo,\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 ...(photo.videoSizes && { videoSizes: photo.videoSizes.map(buildApiVideoSize), isVideo: true }),\n };\n}\n\nexport function buildApiVideoSize(videoSize: GramJs.VideoSize): ApiVideoSize {\n const {\n videoStartTs, size, h, w, type,\n } = videoSize;\n\n return {\n videoStartTs,\n size,\n height: h,\n width: w,\n type: type as ('u' | 'v'),\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 type { Api as GramJs } from '../../lib/gramjs';\nimport type { ApiMessage } from '../types';\n\ninterface LocalDb {\n localMessages: Record<string, ApiMessage>;\n // Used for loading avatars and media through in-memory Gram JS instances.\n chats: Record<string, GramJs.Chat | GramJs.Channel>;\n users: Record<string, GramJs.User>;\n messages: Record<string, GramJs.Message | GramJs.MessageService>;\n documents: Record<string, GramJs.Document>;\n stickerSets: Record<string, GramJs.StickerSet>;\n photos: Record<string, GramJs.Photo>;\n webDocuments: Record<string, GramJs.TypeWebDocument>;\n}\n\nconst LOCAL_DB_INITIAL = {\n localMessages: {},\n chats: {},\n users: {},\n messages: {},\n documents: {},\n stickerSets: {},\n photos: {},\n webDocuments: {},\n};\n\nconst localDb: LocalDb = LOCAL_DB_INITIAL;\n\nexport default localDb;\n\nexport function clearLocalDb() {\n Object.assign(localDb, LOCAL_DB_INITIAL);\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport type {\n ApiEmojiInteraction, ApiStickerSetInfo, ApiSticker, ApiStickerSet, GramJsEmojiInteraction,\n} from '../../types';\n\nimport { buildApiThumbnailFromCached, buildApiThumbnailFromPath } from './common';\nimport localDb from '../localDb';\n\nconst LOTTIE_STICKER_MIME_TYPE = 'application/x-tgsticker';\nconst VIDEO_STICKER_MIME_TYPE = 'video/webm';\n\nexport function buildStickerFromDocument(document: GramJs.TypeDocument, isNoPremium?: boolean): ApiSticker | undefined {\n if (document instanceof GramJs.DocumentEmpty) {\n return undefined;\n }\n\n const { mimeType, videoThumbs } = document;\n const stickerAttribute = document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeSticker => (\n attr instanceof GramJs.DocumentAttributeSticker\n ));\n const customEmojiAttribute = document.attributes\n .find((attr): attr is GramJs.DocumentAttributeCustomEmoji => attr instanceof GramJs.DocumentAttributeCustomEmoji);\n\n const fileAttribute = (mimeType === LOTTIE_STICKER_MIME_TYPE || mimeType === VIDEO_STICKER_MIME_TYPE)\n && document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeFilename => (\n attr instanceof GramJs.DocumentAttributeFilename\n ));\n\n if (!(stickerAttribute || customEmojiAttribute) && !fileAttribute) {\n return undefined;\n }\n\n const isLottie = mimeType === LOTTIE_STICKER_MIME_TYPE;\n const isVideo = mimeType === VIDEO_STICKER_MIME_TYPE;\n const isCustomEmoji = Boolean(customEmojiAttribute);\n\n const imageSizeAttribute = document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeImageSize => (\n attr instanceof GramJs.DocumentAttributeImageSize\n ));\n\n const videoSizeAttribute = document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeVideo => (\n attr instanceof GramJs.DocumentAttributeVideo\n ));\n\n const sizeAttribute = imageSizeAttribute || videoSizeAttribute;\n\n const stickerOrEmojiAttribute = (stickerAttribute || customEmojiAttribute)!;\n const stickerSetInfo = buildApiStickerSetInfo(stickerOrEmojiAttribute?.stickerset);\n const emoji = stickerOrEmojiAttribute?.alt;\n const isFree = Boolean(customEmojiAttribute?.free ?? true);\n\n const cachedThumb = document.thumbs && document.thumbs.find(\n (s): s is GramJs.PhotoCachedSize => s instanceof GramJs.PhotoCachedSize,\n );\n\n // eslint-disable-next-line no-restricted-globals\n if (mimeType === VIDEO_STICKER_MIME_TYPE && !(self as any).isWebmSupported && !cachedThumb) {\n const staticThumb = document.thumbs && document.thumbs.find(\n (s): s is GramJs.PhotoSize => s instanceof GramJs.PhotoSize,\n );\n\n if (!staticThumb) {\n return undefined;\n }\n }\n\n const pathThumb = document.thumbs && document.thumbs.find(\n (s): s is GramJs.PhotoPathSize => s instanceof GramJs.PhotoPathSize,\n );\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 const hasEffect = !isNoPremium && videoThumbs?.some(({ type }) => type === 'f');\n\n return {\n id: String(document.id),\n stickerSetInfo,\n emoji,\n isCustomEmoji,\n isLottie,\n isVideo,\n width,\n height,\n thumbnail,\n hasEffect,\n isFree,\n };\n}\n\nexport function buildStickerSet(set: GramJs.StickerSet): ApiStickerSet {\n const {\n archived,\n animated,\n installedDate,\n videos,\n id,\n accessHash,\n title,\n thumbs,\n count,\n shortName,\n emojis,\n } = set;\n\n return {\n archived,\n isLottie: animated,\n isVideos: videos,\n isEmoji: emojis,\n installedDate,\n id: String(id),\n accessHash: String(accessHash),\n title,\n hasThumbnail: Boolean(thumbs?.length),\n count,\n shortName,\n };\n}\n\nfunction buildApiStickerSetInfo(inputSet?: GramJs.TypeInputStickerSet): ApiStickerSetInfo {\n if (inputSet instanceof GramJs.InputStickerSetID) {\n return {\n id: String(inputSet.id),\n accessHash: String(inputSet.accessHash),\n };\n }\n if (inputSet instanceof GramJs.InputStickerSetShortName) {\n return {\n shortName: inputSet.shortName,\n };\n }\n\n return {\n isMissing: true,\n };\n}\n\nexport function buildStickerSetCovered(coveredStickerSet: GramJs.TypeStickerSetCovered): ApiStickerSet {\n const stickerSet = buildStickerSet(coveredStickerSet.set);\n\n const stickerSetCovers = (coveredStickerSet instanceof GramJs.StickerSetCovered) ? [coveredStickerSet.cover]\n : (coveredStickerSet instanceof GramJs.StickerSetMultiCovered) ? coveredStickerSet.covers\n : coveredStickerSet.documents;\n\n const stickers = processStickerResult(stickerSetCovers);\n\n if (coveredStickerSet instanceof GramJs.StickerSetFullCovered) {\n return {\n ...stickerSet,\n stickers,\n packs: processStickerPackResult(coveredStickerSet.packs),\n };\n }\n\n return {\n ...stickerSet,\n covers: stickers,\n };\n}\n\nexport function buildApiEmojiInteraction(json: GramJsEmojiInteraction): ApiEmojiInteraction {\n return {\n timestamps: json.a.map((l) => l.t),\n };\n}\n\nexport function processStickerPackResult(packs: GramJs.StickerPack[]) {\n return packs.reduce((acc, { emoticon, documents }) => {\n acc[emoticon] = documents.map((documentId) => buildStickerFromDocument(\n localDb.documents[String(documentId)],\n )).filter<ApiSticker>(Boolean as any);\n return acc;\n }, {} as Record<string, ApiSticker[]>);\n}\n\nexport function 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);\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 type BigInt from 'big-integer';\n\nimport type { 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 (message instanceof GramJs.Message) {\n if (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 (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.media instanceof GramJs.MessageMediaGame) {\n if (message.media.game.document instanceof GramJs.Document) {\n localDb.documents[String(message.media.game.document.id)] = message.media.game.document;\n }\n addPhotoToLocalDb(message.media.game.photo);\n }\n\n if (message.media instanceof GramJs.MessageMediaInvoice\n && message.media.photo) {\n localDb.webDocuments[String(message.media.photo.url)] = message.media.photo;\n }\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 type { ApiPrivacyKey } from '../../../types';\n\nimport { generateRandomBytes, readBigIntFromBuffer } from '../../../lib/gramjs/Helpers';\nimport type {\n ApiChatAdminRights,\n ApiChatBannedRights,\n ApiChatFolder,\n ApiGroupCall,\n ApiMessageEntity,\n ApiNewPoll,\n ApiPhoto,\n ApiPhoneCall,\n ApiReportReason,\n ApiSendMessageAction,\n ApiSticker,\n ApiVideo,\n ApiThemeParameters,\n ApiPoll,\n ApiRequestInputInvoice,\n} from '../../types';\nimport {\n ApiMessageEntityTypes,\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 buildInputPollFromExisting(poll: ApiPoll, shouldClose = false) {\n return new GramJs.InputMediaPoll({\n poll: new GramJs.Poll({\n id: BigInt(poll.id),\n publicVoters: poll.summary.isPublic,\n question: poll.summary.question,\n answers: poll.summary.answers.map(({ text, option }) => {\n return new GramJs.PollAnswer({ text, option: deserializeBytes(option) });\n }),\n quiz: poll.summary.quiz,\n multipleChoice: poll.summary.multipleChoice,\n closeDate: poll.summary.closeDate,\n closePeriod: poll.summary.closePeriod,\n closed: shouldClose ? true : poll.summary.closed,\n }),\n correctAnswers: poll.results.results?.filter((o) => o.isCorrect).map((o) => deserializeBytes(o.option)),\n solution: poll.results.solution,\n solutionEntities: poll.results.solutionEntities?.map(buildMtpMessageEntity),\n });\n}\n\nexport function buildFilterFromApiFolder(folder: ApiChatFolder): GramJs.DialogFilter {\n const {\n emoticon,\n contacts,\n nonContacts,\n groups,\n channels,\n bots,\n excludeArchived,\n excludeMuted,\n excludeRead,\n pinnedChatIds,\n includedChatIds,\n excludedChatIds,\n } = folder;\n\n const pinnedPeers = pinnedChatIds\n ? pinnedChatIds.map(buildInputPeerFromLocalDb).filter<GramJs.TypeInputPeer>(Boolean as any)\n : [];\n\n const includePeers = includedChatIds\n ? includedChatIds.map(buildInputPeerFromLocalDb).filter<GramJs.TypeInputPeer>(Boolean as any)\n : [];\n\n const excludePeers = excludedChatIds\n ? excludedChatIds.map(buildInputPeerFromLocalDb).filter<GramJs.TypeInputPeer>(Boolean as any)\n : [];\n\n return new GramJs.DialogFilter({\n id: folder.id,\n title: folder.title,\n emoticon: emoticon || undefined,\n contacts: contacts || undefined,\n nonContacts: nonContacts || undefined,\n groups: groups || undefined,\n bots: bots || undefined,\n excludeArchived: excludeArchived || undefined,\n excludeMuted: excludeMuted || undefined,\n excludeRead: excludeRead || undefined,\n broadcasts: channels || undefined,\n pinnedPeers,\n includePeers,\n excludePeers,\n });\n}\n\nexport function generateRandomBigInt() {\n return readBigIntFromBuffer(generateRandomBytes(8), true, true);\n}\n\nexport function 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,\n } = entity;\n\n const user = 'userId' in entity ? localDb.users[entity.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: entity.language || '' });\n case ApiMessageEntityTypes.Blockquote:\n return new GramJs.MessageEntityBlockquote({ offset, length });\n case ApiMessageEntityTypes.TextUrl:\n return new GramJs.MessageEntityTextUrl({ offset, length, url: entity.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(user!.id), accessHash: user!.accessHash! }),\n });\n case ApiMessageEntityTypes.Spoiler:\n return new GramJs.MessageEntitySpoiler({ offset, length });\n case ApiMessageEntityTypes.CustomEmoji:\n return new GramJs.MessageEntityCustomEmoji({ offset, length, documentId: BigInt(entity.documentId) });\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 media instanceof GramJs.MessageMediaGame\n && (media.game.document instanceof GramJs.Document || media.game.photo instanceof GramJs.Photo)\n ) || (\n media instanceof GramJs.MessageMediaInvoice && media.photo\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 buildInputPhoto(photo: ApiPhoto) {\n const localPhoto = localDb.photos[photo?.id];\n\n if (!localPhoto) {\n return undefined;\n }\n\n return new GramJs.InputPhoto(pick(localPhoto, [\n 'id',\n 'accessHash',\n 'fileReference',\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 case 'phoneCall':\n return new GramJs.InputPrivacyKeyPhoneCall();\n\n case 'phoneP2P':\n return new GramJs.InputPrivacyKeyPhoneP2P();\n\n case 'voiceMessages':\n return new GramJs.InputPrivacyKeyVoiceMessages();\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 'illegalDrugs':\n return new GramJs.InputReportReasonIllegalDrugs();\n case 'personalDetails':\n return new GramJs.InputReportReasonPersonalDetails();\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 case 'playingGame':\n return new GramJs.SendMessageGamePlayAction();\n }\n return undefined;\n}\n\nexport function buildInputThemeParams(params: ApiThemeParameters) {\n return new GramJs.DataJSON({\n data: JSON.stringify(params),\n });\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<ApiGroupCall>) {\n return new GramJs.InputGroupCall({\n id: BigInt(groupCall.id!),\n accessHash: BigInt(groupCall.accessHash!),\n });\n}\n\nexport function buildInputPhoneCall({ id, accessHash }: ApiPhoneCall) {\n return new GramJs.InputPhoneCall({\n id: BigInt(id),\n accessHash: BigInt(accessHash!),\n });\n}\n\nexport function buildInputInvoice(invoice: ApiRequestInputInvoice) {\n if ('slug' in invoice) {\n return new GramJs.InputInvoiceSlug({\n slug: invoice.slug,\n });\n } else {\n return new GramJs.InputInvoiceMessage({\n peer: buildInputPeer(invoice.chat.id, invoice.chat.accessHash),\n msgId: invoice.messageId,\n });\n }\n}\n","import type {\n ApiCallProtocol,\n ApiPhoneCallConnection,\n GroupCallParticipant,\n GroupCallParticipantVideo,\n SsrcGroup,\n} from '../../../lib/secret-sauce';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport type { ApiGroupCall, ApiPhoneCall } 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\nexport function buildPhoneCall(call: GramJs.TypePhoneCall): ApiPhoneCall {\n const { id } = call;\n\n let phoneCall: ApiPhoneCall = {\n id: id.toString(),\n };\n\n if (call instanceof GramJs.PhoneCallAccepted\n || call instanceof GramJs.PhoneCallWaiting\n || call instanceof GramJs.PhoneCall\n || call instanceof GramJs.PhoneCallRequested) {\n const {\n accessHash, adminId, date, video, participantId, protocol,\n } = call;\n\n phoneCall = {\n ...phoneCall,\n accessHash: accessHash.toString(),\n adminId: adminId.toString(),\n participantId: participantId.toString(),\n date,\n isVideo: video,\n protocol: buildApiCallProtocol(protocol),\n };\n }\n\n if (call instanceof GramJs.PhoneCall) {\n const {\n p2pAllowed, gAOrB, keyFingerprint, connections, startDate,\n } = call;\n\n phoneCall = {\n ...phoneCall,\n state: 'active',\n gAOrB: Array.from(gAOrB),\n keyFingerprint: keyFingerprint.toString(),\n startDate,\n p2pAllowed,\n connections: connections.map(buildApiCallConnection).filter(Boolean) as ApiPhoneCallConnection[],\n };\n }\n\n if (call instanceof GramJs.PhoneCallDiscarded) {\n phoneCall = {\n ...phoneCall,\n state: 'discarded',\n duration: call.duration,\n reason: buildApiCallDiscardReason(call.reason),\n needRating: call.needRating,\n needDebug: call.needDebug,\n };\n }\n\n if (call instanceof GramJs.PhoneCallWaiting) {\n phoneCall = {\n ...phoneCall,\n state: 'waiting',\n receiveDate: call.receiveDate,\n };\n }\n\n if (call instanceof GramJs.PhoneCallAccepted) {\n phoneCall = {\n ...phoneCall,\n state: 'accepted',\n gB: Array.from(call.gB),\n };\n }\n\n if (call instanceof GramJs.PhoneCallRequested) {\n phoneCall = {\n ...phoneCall,\n state: 'requested',\n gAHash: Array.from(call.gAHash),\n };\n }\n\n return phoneCall;\n}\n\nexport function buildApiCallDiscardReason(discardReason?: GramJs.TypePhoneCallDiscardReason) {\n if (discardReason instanceof GramJs.PhoneCallDiscardReasonMissed) {\n return 'missed';\n } else if (discardReason instanceof GramJs.PhoneCallDiscardReasonBusy) {\n return 'busy';\n } else if (discardReason instanceof GramJs.PhoneCallDiscardReasonHangup) {\n return 'hangup';\n } else {\n return 'disconnect';\n }\n}\n\nfunction buildApiCallConnection(connection: GramJs.TypePhoneConnection): ApiPhoneCallConnection | undefined {\n if (connection instanceof GramJs.PhoneConnectionWebrtc) {\n const {\n username, password, turn, stun, ip, ipv6, port,\n } = connection;\n\n return {\n username,\n password,\n isTurn: turn,\n isStun: stun,\n ip,\n ipv6,\n port,\n };\n } else {\n return undefined;\n }\n}\n\nexport function buildApiCallProtocol(protocol: GramJs.PhoneCallProtocol): ApiCallProtocol {\n const {\n libraryVersions, minLayer, maxLayer, udpP2p, udpReflector,\n } = protocol;\n\n return {\n libraryVersions,\n minLayer,\n maxLayer,\n isUdpP2p: udpP2p,\n isUdpReflector: udpReflector,\n };\n}\n\nexport function buildCallProtocol() {\n return new GramJs.PhoneCallProtocol({\n libraryVersions: ['4.0.0'],\n minLayer: 92,\n maxLayer: 92,\n udpReflector: true,\n udpP2p: true,\n });\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n ApiMessageEntityTypes,\n} from '../../types';\nimport type {\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 ApiReactions,\n ApiReactionCount,\n ApiUserReaction,\n ApiAvailableReaction,\n ApiSponsoredMessage,\n ApiUser,\n ApiLocation,\n ApiGame,\n PhoneCallAction,\n ApiWebDocument,\n ApiMessageEntityDefault,\n} from '../../types';\n\nimport {\n DELETED_COMMENTS_CHANNEL_ID,\n SERVICE_NOTIFICATIONS_USER_ID,\n SPONSORED_MESSAGE_CACHE_MS,\n SUPPORTED_AUDIO_CONTENT_TYPES,\n SUPPORTED_IMAGE_CONTENT_TYPES,\n SUPPORTED_VIDEO_CONTENT_TYPES,\n VIDEO_MOV_TYPE,\n VIDEO_WEBM_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';\nimport { buildApiCallDiscardReason } from './calls';\n\nconst LOCAL_MEDIA_UPLOADING_TEMP_ID = 'temp';\nconst INPUT_WAVEFORM_LENGTH = 63;\n\nlet localMessageCounter = 0;\nconst getNextLocalMessageId = () => parseFloat(`${Date.now()}.${localMessageCounter++}`);\n\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, recommended,\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 isRecommended: Boolean(recommended),\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 = getNextLocalMessageId();\n const content = buildMessageContent(notification);\n\n return {\n id: localId,\n chatId: SERVICE_NOTIFICATIONS_USER_ID,\n date: notification.inboxDate || currentDate,\n content,\n isOutgoing: false,\n };\n}\n\ntype UniversalMessage = (\n Pick<GramJs.Message & GramJs.MessageService, ('id' | 'date')>\n & Pick<Partial<GramJs.Message & GramJs.MessageService>, (\n 'out' | 'message' | 'entities' | 'fromId' | 'peerId' | 'fwdFrom' | 'replyTo' | 'replyMarkup' | 'post' |\n 'media' | 'action' | 'views' | 'editDate' | 'editHide' | 'mediaUnread' | 'groupedId' | 'mentioned' | 'viaBotId' |\n 'replies' | 'fromScheduled' | 'postAuthor' | 'noforwards' | 'reactions' | 'forwards'\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 const content = buildMessageContent(mtpMessage);\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 || content.sticker);\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 forwards: mtpMessage.forwards,\n isFromScheduled: mtpMessage.fromScheduled,\n reactions: mtpMessage.reactions && buildMessageReactions(mtpMessage.reactions),\n ...(replyToMsgId && { replyToMessageId: replyToMsgId }),\n ...(replyToPeerId && { replyToChatId: getApiChatIdFromMtpPeer(replyToPeerId) }),\n ...(replyToTopId && { replyToTopMessageId: replyToTopId }),\n ...(forwardInfo && { forwardInfo }),\n ...(isEdited && { isEdited }),\n ...(mtpMessage.editDate && { 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 buildMessageReactions(reactions: GramJs.MessageReactions): ApiReactions {\n const {\n recentReactions, results, canSeeList,\n } = reactions;\n\n return {\n canSeeList,\n results: results.map(buildReactionCount),\n recentReactions: recentReactions?.map(buildMessagePeerReaction),\n };\n}\n\nfunction buildReactionCount(reactionCount: GramJs.ReactionCount): ApiReactionCount {\n const { chosen, count, reaction } = reactionCount;\n\n return {\n isChosen: chosen,\n count,\n reaction,\n };\n}\n\nexport function buildMessagePeerReaction(userReaction: GramJs.MessagePeerReaction): ApiUserReaction {\n const {\n peerId, reaction, big, unread,\n } = userReaction;\n\n return {\n userId: getApiChatIdFromMtpPeer(peerId),\n reaction,\n isUnread: unread,\n isBig: big,\n };\n}\n\nexport function buildApiAvailableReaction(availableReaction: GramJs.AvailableReaction): ApiAvailableReaction {\n const {\n selectAnimation, staticIcon, reaction, title,\n inactive, aroundAnimation, centerIcon, effectAnimation, activateAnimation,\n premium,\n } = availableReaction;\n\n return {\n selectAnimation: buildApiDocument(selectAnimation),\n activateAnimation: buildApiDocument(activateAnimation),\n effectAnimation: buildApiDocument(effectAnimation),\n staticIcon: buildApiDocument(staticIcon),\n aroundAnimation: aroundAnimation ? buildApiDocument(aroundAnimation) : undefined,\n centerIcon: centerIcon ? buildApiDocument(centerIcon) : undefined,\n reaction,\n title,\n isInactive: inactive,\n isPremium: premium,\n };\n}\n\nexport function buildMessageContent(\n mtpMessage: UniversalMessage | GramJs.UpdateServiceNotification,\n) {\n let content: ApiMessage['content'] = {};\n\n if (mtpMessage.media) {\n content = {\n ...buildMessageMediaContent(mtpMessage.media),\n };\n }\n\n const hasUnsupportedMedia = mtpMessage.media instanceof GramJs.MessageMediaUnsupported;\n\n if (mtpMessage.message && !hasUnsupportedMedia\n && !content.sticker && !content.poll && !content.contact && !(content.video?.isRound)) {\n content = {\n ...content,\n text: buildMessageTextContent(mtpMessage.message, mtpMessage.entities),\n };\n }\n\n return content;\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 const location = buildLocationFromMedia(media);\n if (location) return { location };\n\n const game = buildGameFromMedia(media);\n if (game) return { game };\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.savedFromMsgId || fwdFrom.channelPost,\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, media.nopremium);\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_WEBM_TYPE && !(self as any).isWebmSupported) {\n return undefined;\n }\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: size.toJSNumber(),\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 size: media.document.size.toJSNumber(),\n ...pick(media.document, ['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 const videoAttribute = attributes\n .find((a: any): a is GramJs.DocumentAttributeVideo => a instanceof GramJs.DocumentAttributeVideo);\n\n if (videoAttribute) {\n const { w: width, h: height } = videoAttribute;\n mediaSize = {\n width,\n height,\n };\n }\n }\n }\n\n return {\n id: String(id),\n size: size.toJSNumber(),\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\nfunction buildLocationFromMedia(media: GramJs.TypeMessageMedia): ApiLocation | undefined {\n if (media instanceof GramJs.MessageMediaGeo) {\n return buildGeo(media);\n }\n\n if (media instanceof GramJs.MessageMediaVenue) {\n return buildVenue(media);\n }\n\n if (media instanceof GramJs.MessageMediaGeoLive) {\n return buildGeoLive(media);\n }\n\n return undefined;\n}\n\nfunction buildGeo(media: GramJs.MessageMediaGeo): ApiLocation | undefined {\n const point = buildGeoPoint(media.geo);\n return point && { type: 'geo', geo: point };\n}\n\nfunction buildVenue(media: GramJs.MessageMediaVenue): ApiLocation | undefined {\n const {\n geo, title, provider, address, venueId, venueType,\n } = media;\n const point = buildGeoPoint(geo);\n return point && {\n type: 'venue',\n geo: point,\n title,\n provider,\n address,\n venueId,\n venueType,\n };\n}\n\nfunction buildGeoLive(media: GramJs.MessageMediaGeoLive): ApiLocation | undefined {\n const { geo, period, heading } = media;\n const point = buildGeoPoint(geo);\n return point && {\n type: 'geoLive',\n geo: point,\n period,\n heading,\n };\n}\n\nfunction buildGeoPoint(geo: GramJs.TypeGeoPoint): ApiLocation['geo'] | undefined {\n if (geo instanceof GramJs.GeoPointEmpty) return undefined;\n const {\n long, lat, accuracyRadius, accessHash,\n } = geo;\n return {\n long,\n lat,\n accessHash: accessHash.toString(),\n accuracyRadius,\n };\n}\n\nfunction buildGameFromMedia(media: GramJs.TypeMessageMedia): ApiGame | undefined {\n if (!(media instanceof GramJs.MessageMediaGame)) {\n return undefined;\n }\n\n return buildGame(media);\n}\n\nfunction buildGame(media: GramJs.MessageMediaGame): ApiGame | undefined {\n const {\n id, accessHash, shortName, title, description, photo: apiPhoto, document: apiDocument,\n } = media.game;\n\n const photo = apiPhoto instanceof GramJs.Photo ? buildApiPhoto(apiPhoto) : undefined;\n const document = apiDocument instanceof GramJs.Document ? buildApiDocument(apiDocument) : undefined;\n\n return {\n id: id.toString(),\n accessHash: accessHash.toString(),\n shortName,\n title,\n description,\n photo,\n document,\n };\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 photo: buildApiWebDocument(photo),\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, min,\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 isMin: min,\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 phoneCall: PhoneCallAction | undefined;\n let call: Partial<ApiGroupCall> | 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 let score: number | undefined;\n let months: number | 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\n phoneCall = {\n isOutgoing,\n isVideo: action.video,\n duration: action.duration,\n reason: buildApiCallDiscardReason(action.reason),\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 if (action instanceof GramJs.MessageActionGameScore) {\n text = senderId === currentUserId ? 'ActionYouScoredInGame' : 'ActionUserScoredInGame';\n translationValues.push('%score%');\n score = action.score;\n } else if (action instanceof GramJs.MessageActionWebViewDataSent) {\n text = 'Notification.WebAppSentData';\n translationValues.push(action.text);\n } else if (action instanceof GramJs.MessageActionGiftPremium) {\n text = isOutgoing ? 'ActionGiftOutbound' : 'ActionGiftInbound';\n if (isOutgoing) {\n translationValues.push('%gift_payment_amount%');\n } else {\n translationValues.push('%action_origin%', '%gift_payment_amount%');\n }\n if (targetPeerId) {\n targetUserIds.push(targetPeerId);\n }\n currency = action.currency;\n amount = action.amount.toJSNumber();\n months = action.months;\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 phoneCall,\n score,\n months,\n };\n}\n\nfunction buildReplyButtons(message: UniversalMessage): ApiReplyKeyboard | undefined {\n const { replyMarkup, media } = message;\n\n // TODO Move to the proper button inside preview\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',\n text: 'Show Message',\n url: 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): ApiKeyboardButton => {\n const { text } = button;\n\n if (button instanceof GramJs.KeyboardButton) {\n return {\n type: 'command',\n text,\n };\n }\n\n if (button instanceof GramJs.KeyboardButtonUrl) {\n if (button.url.includes('?startgroup=')) {\n return {\n type: 'unsupported',\n text,\n };\n }\n\n return {\n type: 'url',\n text,\n url: button.url,\n };\n }\n\n if (button instanceof GramJs.KeyboardButtonCallback) {\n if (button.requiresPassword) {\n return {\n type: 'unsupported',\n text,\n };\n }\n\n return {\n type: 'callback',\n text,\n data: serializeBytes(button.data),\n };\n }\n\n if (button instanceof GramJs.KeyboardButtonRequestPoll) {\n return {\n type: 'requestPoll',\n text,\n isQuiz: button.quiz,\n };\n }\n\n if (button instanceof GramJs.KeyboardButtonRequestPhone) {\n return {\n type: 'requestPhone',\n text,\n };\n }\n\n if (button instanceof GramJs.KeyboardButtonBuy) {\n if (media instanceof GramJs.MessageMediaInvoice && media.receiptMsgId) {\n return {\n type: 'receipt',\n text: 'PaymentReceipt',\n receiptMessageId: media.receiptMsgId,\n };\n }\n return {\n type: 'buy',\n text,\n };\n }\n\n if (button instanceof GramJs.KeyboardButtonGame) {\n return {\n type: 'game',\n text,\n };\n }\n\n if (button instanceof GramJs.KeyboardButtonSwitchInline) {\n return {\n type: 'switchBotInline',\n text,\n query: button.query,\n isSamePeer: button.samePeer,\n };\n }\n\n if (button instanceof GramJs.KeyboardButtonUserProfile) {\n return {\n type: 'userProfile',\n text,\n userId: button.userId.toString(),\n };\n }\n\n if (button instanceof GramJs.KeyboardButtonSimpleWebView) {\n return {\n type: 'simpleWebView',\n text,\n url: button.url,\n };\n }\n\n if (button instanceof GramJs.KeyboardButtonWebView) {\n return {\n type: 'webView',\n text,\n url: button.url,\n };\n }\n\n if (button instanceof GramJs.KeyboardButtonUrlAuth) {\n return {\n type: 'urlAuth',\n text,\n url: button.url,\n buttonId: button.buttonId,\n };\n }\n\n return {\n type: 'unsupported',\n text,\n };\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 replyingToTopId?: number,\n attachment?: ApiAttachment,\n sticker?: ApiSticker,\n gif?: ApiVideo,\n poll?: ApiNewPoll,\n contact?: ApiContact,\n groupedId?: string,\n scheduledAt?: number,\n sendAs?: ApiChat | ApiUser,\n serverTimeOffset = 0,\n): ApiMessage {\n const localId = getNextLocalMessageId();\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 ...(contact && { contact }),\n },\n date: scheduledAt || Math.round(Date.now() / 1000) + serverTimeOffset,\n isOutgoing: !isChannel,\n senderId: sendAs?.id || currentUserId,\n ...(replyingTo && { replyToMessageId: replyingTo }),\n ...(replyingToTopId && { replyToTopMessageId: replyingToTopId }),\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 noAuthors?: boolean,\n noCaptions?: boolean,\n isCurrentUserPremium?: boolean,\n): ApiMessage {\n const localId = getNextLocalMessageId();\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 const shouldHideText = Object.keys(content).length > 1 && content.text && noCaptions;\n const shouldDropCustomEmoji = !isCurrentUserPremium;\n const strippedText = content.text?.entities && shouldDropCustomEmoji ? {\n text: content.text.text,\n entities: content.text.entities?.filter((entity) => entity.type !== ApiMessageEntityTypes.CustomEmoji),\n } : content.text;\n\n const updatedContent = {\n ...content,\n text: !shouldHideText ? strippedText : undefined,\n };\n\n return {\n id: localId,\n chatId: toChat.id,\n content: updatedContent,\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 && !noAuthors && {\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 if (SUPPORTED_IMAGE_CONTENT_TYPES.has(mimeType)) {\n const { width, height } = attachment.quick;\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 }\n if (SUPPORTED_VIDEO_CONTENT_TYPES.has(mimeType)) {\n const { width, height, duration } = attachment.quick;\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 }\n 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 }\n if (SUPPORTED_AUDIO_CONTENT_TYPES.has(mimeType)) {\n const { duration, performer, title } = attachment.audio || {};\n return {\n audio: {\n id: LOCAL_MEDIA_UPLOADING_TEMP_ID,\n mimeType,\n fileName,\n size,\n duration: duration || 0,\n title,\n performer,\n },\n };\n }\n return {\n document: {\n mimeType,\n fileName,\n size,\n ...(previewBlobUrl && { previewBlobUrl }),\n },\n };\n}\n\nexport function buildApiWebDocument(document?: GramJs.TypeWebDocument): ApiWebDocument | undefined {\n if (!document) return undefined;\n\n const {\n url, size, mimeType,\n } = document;\n const accessHash = document instanceof GramJs.WebDocument ? document.accessHash.toString() : undefined;\n const sizeAttr = document.attributes.find((attr): attr is GramJs.DocumentAttributeImageSize => (\n attr instanceof GramJs.DocumentAttributeImageSize\n ));\n const dimensions = sizeAttr && { width: sizeAttr.w, height: sizeAttr.h };\n\n return {\n url,\n accessHash,\n size,\n mimeType,\n dimensions,\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\nexport function buildApiMessageEntity(entity: GramJs.TypeMessageEntity): ApiMessageEntity {\n const {\n className: type, offset, length,\n } = entity;\n\n if (entity instanceof GramJs.MessageEntityMentionName) {\n return {\n type: ApiMessageEntityTypes.MentionName,\n offset,\n length,\n userId: buildApiPeerId(entity.userId, 'user'),\n };\n }\n\n if (entity instanceof GramJs.MessageEntityTextUrl) {\n return {\n type: ApiMessageEntityTypes.TextUrl,\n offset,\n length,\n url: entity.url,\n };\n }\n\n if (entity instanceof GramJs.MessageEntityPre) {\n return {\n type: ApiMessageEntityTypes.Pre,\n offset,\n length,\n language: entity.language,\n };\n }\n\n if (entity instanceof GramJs.MessageEntityCustomEmoji) {\n return {\n type: ApiMessageEntityTypes.CustomEmoji,\n offset,\n length,\n documentId: entity.documentId.toString(),\n };\n }\n\n return {\n type: type as `${ApiMessageEntityDefault['type']}`,\n offset,\n length,\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 type BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport type {\n ApiChat,\n ApiChatAdminRights,\n ApiChatBannedRights,\n ApiBotCommand,\n ApiChatFolder,\n ApiChatMember,\n ApiRestrictionReason,\n ApiExportedInvite,\n ApiChatInviteImporter,\n ApiChatSettings,\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<ApiChat, (\n 'id' | 'type' | 'title' |\n 'lastReadOutboxMessageId' | 'lastReadInboxMessageId' |\n 'unreadCount' | 'unreadMentionsCount' | 'isMuted'\n)>;\n\nfunction buildApiChatFieldsFromPeerEntity(\n peerEntity: GramJs.TypeUser | GramJs.TypeChat,\n isSupport = false,\n): PeerEntityApiChatFields {\n const isMin = Boolean('min' in peerEntity && peerEntity.min);\n const accessHash = ('accessHash' in peerEntity) && String(peerEntity.accessHash);\n const hasVideoAvatar = 'photo' in peerEntity && peerEntity.photo && 'hasVideo' in peerEntity.photo\n && peerEntity.photo.hasVideo;\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 const isScam = Boolean('scam' in peerEntity && peerEntity.scam);\n const isFake = Boolean('fake' in peerEntity && peerEntity.fake);\n const isJoinToSend = Boolean('joinToSend' in peerEntity && peerEntity.joinToSend);\n const isJoinRequest = Boolean('joinRequest' in peerEntity && peerEntity.joinRequest);\n\n return {\n isMin,\n hasPrivateLink,\n isSignaturesShown,\n ...(accessHash && { accessHash }),\n hasVideoAvatar,\n ...(avatarHash && { avatarHash }),\n ...(('username' in peerEntity) && { username: peerEntity.username }),\n ...(('verified' in peerEntity) && { isVerified: peerEntity.verified }),\n ...(('callActive' in peerEntity) && { isCallActive: peerEntity.callActive }),\n ...(('callNotEmpty' in peerEntity) && { isCallNotEmpty: peerEntity.callNotEmpty }),\n ...('date' in peerEntity && { joinDate: peerEntity.date }),\n ...('participantsCount' in peerEntity && { membersCount: peerEntity.participantsCount }),\n ...(('noforwards' in peerEntity) && { isProtected: Boolean(peerEntity.noforwards) }),\n ...(isSupport && { isSupport: true }),\n ...buildApiChatPermissions(peerEntity),\n ...(('creator' in peerEntity) && { isCreator: peerEntity.creator }),\n ...buildApiChatRestrictions(peerEntity),\n ...buildApiChatMigrationInfo(peerEntity),\n fakeType: isScam ? 'scam' : (isFake ? 'fake' : undefined),\n isJoinToSend,\n isJoinRequest,\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, unreadReactionsCount,\n 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 unreadReactionsCount,\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: 'bannedRights' in peerEntity && 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 isForbidden?: boolean;\n isRestricted?: boolean;\n restrictionReason?: ApiRestrictionReason;\n} {\n if (peerEntity instanceof GramJs.ChatForbidden) {\n return {\n isForbidden: true,\n };\n }\n\n if (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 });\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 'migratedTo' in peerEntity\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): ApiChat | undefined {\n if (preview instanceof GramJs.ChatEmpty || preview instanceof GramJs.UserEmpty) {\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<ApiChatMember>(Boolean as any);\n }\n if (participants instanceof GramJs.channels.ChannelParticipants) {\n return participants.participants.map(buildChatMember).filter<ApiChatMember>(Boolean as any);\n }\n\n return undefined;\n}\n\nexport function buildChatTypingStatus(\n update: GramJs.UpdateUserTyping | GramJs.UpdateChatUserTyping | GramJs.UpdateChannelUserTyping,\n serverTimeOffset: number,\n) {\n let action: string = '';\n let emoticon: string | undefined;\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 } else if (update.action instanceof GramJs.SendMessageEmojiInteractionSeen) {\n action = 'lng_user_action_watching_animations';\n emoticon = update.action.emoticon;\n } else if (update.action instanceof GramJs.SendMessageEmojiInteraction) {\n return undefined;\n }\n\n return {\n action,\n ...(emoticon && { emoji: emoticon }),\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<string>(Boolean as any),\n includedChatIds: filter.includePeers.map(getApiChatIdFromMtpPeer).filter<string>(Boolean as any),\n excludedChatIds: filter.excludePeers.map(getApiChatIdFromMtpPeer).filter<string>(Boolean as any),\n };\n}\n\nexport function buildApiChatFolderFromSuggested({\n filter, description,\n}: {\n filter: GramJs.TypeDialogFilter;\n description: string;\n}): ApiChatFolder | undefined {\n if (!(filter instanceof GramJs.DialogFilter)) return undefined;\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 if (botInfo.commands) {\n botCommands = botCommands.concat(botInfo.commands.map((mtpCommand) => ({\n botId,\n ...omitVirtualClassFields(mtpCommand),\n })));\n }\n\n return botCommands;\n }, [] as ApiBotCommand[]);\n}\n\nexport function buildApiExportedInvite(invite: GramJs.ChatInviteExported): ApiExportedInvite {\n const {\n revoked,\n date,\n expireDate,\n link,\n permanent,\n startDate,\n usage,\n usageLimit,\n requested,\n requestNeeded,\n title,\n adminId,\n } = invite;\n return {\n isRevoked: revoked,\n date,\n expireDate,\n link,\n isPermanent: permanent,\n startDate,\n usage,\n usageLimit,\n isRequestNeeded: requestNeeded,\n requested,\n title,\n adminId: buildApiPeerId(adminId, 'user'),\n };\n}\n\nexport function buildChatInviteImporter(importer: GramJs.ChatInviteImporter): ApiChatInviteImporter {\n const {\n userId,\n date,\n about,\n requested,\n } = importer;\n return {\n userId: buildApiPeerId(userId, 'user'),\n date,\n about,\n isRequested: requested,\n };\n}\n\nexport function buildApiChatSettings({\n autoarchived,\n reportSpam,\n addContact,\n blockContact,\n}: GramJs.PeerSettings): ApiChatSettings {\n return {\n isAutoArchived: Boolean(autoarchived),\n canReportSpam: Boolean(reportSpam),\n canAddContact: Boolean(addContact),\n canBlockContact: Boolean(blockContact),\n };\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport type {\n ApiAttachMenuBot,\n ApiAttachMenuBotIcon,\n ApiAttachMenuPeerType,\n ApiBotCommand,\n ApiBotInfo,\n ApiBotInlineMediaResult,\n ApiBotInlineResult,\n ApiBotInlineSwitchPm,\n ApiBotMenuButton,\n ApiInlineResultType,\n} from '../../types';\n\nimport { pick } from '../../../util/iteratees';\nimport { buildApiPhoto, buildApiThumbnailFromStripped } from './common';\nimport { buildApiDocument, buildApiWebDocument, buildVideoFromDocument } from './messages';\nimport { buildStickerFromDocument } from './symbols';\nimport localDb from '../localDb';\nimport { buildApiPeerId } from './peers';\nimport { omitVirtualClassFields } from './helpers';\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\nexport function buildApiAttachMenuBot(bot: GramJs.AttachMenuBot): ApiAttachMenuBot {\n return {\n id: bot.botId.toString(),\n hasSettings: bot.hasSettings,\n shortName: bot.shortName,\n peerTypes: bot.peerTypes.map(buildApiAttachMenuPeerType),\n icons: bot.icons.map(buildApiAttachMenuIcon).filter(Boolean),\n };\n}\n\nfunction buildApiAttachMenuPeerType(peerType: GramJs.TypeAttachMenuPeerType): ApiAttachMenuPeerType {\n if (peerType instanceof GramJs.AttachMenuPeerTypeBotPM) return 'bot';\n if (peerType instanceof GramJs.AttachMenuPeerTypePM) return 'private';\n if (peerType instanceof GramJs.AttachMenuPeerTypeChat) return 'chat';\n if (peerType instanceof GramJs.AttachMenuPeerTypeBroadcast) return 'channel';\n if (peerType instanceof GramJs.AttachMenuPeerTypeSameBotPM) return 'self';\n return undefined!; // Never reached\n}\n\nfunction buildApiAttachMenuIcon(icon: GramJs.AttachMenuBotIcon): ApiAttachMenuBotIcon | undefined {\n if (!(icon.icon instanceof GramJs.Document)) return undefined;\n\n const document = buildApiDocument(icon.icon);\n\n if (!document) return undefined;\n\n localDb.documents[String(icon.icon.id)] = icon.icon;\n\n return {\n name: icon.name,\n document,\n };\n}\n\nexport function buildApiBotInfo(botInfo: GramJs.BotInfo, chatId: string): ApiBotInfo {\n const {\n description, descriptionPhoto, descriptionDocument, userId, commands, menuButton,\n } = botInfo;\n\n const botId = userId && buildApiPeerId(userId, 'user');\n const photo = descriptionPhoto instanceof GramJs.Photo ? buildApiPhoto(descriptionPhoto) : undefined;\n const gif = descriptionDocument instanceof GramJs.Document ? buildVideoFromDocument(descriptionDocument) : undefined;\n\n const commandsArray = commands?.map((command) => buildApiBotCommand(botId || chatId, command));\n\n return {\n botId: botId || chatId,\n description,\n gif,\n photo,\n menuButton: buildApiBotMenuButton(menuButton),\n commands: commandsArray?.length ? commandsArray : undefined,\n };\n}\n\nfunction buildApiBotCommand(botId: string, command: GramJs.BotCommand): ApiBotCommand {\n return {\n botId,\n ...omitVirtualClassFields(command),\n };\n}\n\nexport function buildApiBotMenuButton(menuButton?: GramJs.TypeBotMenuButton): ApiBotMenuButton {\n if (menuButton instanceof GramJs.BotMenuButton) {\n return {\n type: 'webApp',\n text: menuButton.text,\n url: menuButton.url,\n };\n }\n\n return {\n type: 'commands',\n };\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport type {\n ApiPremiumGiftOption,\n ApiUser, ApiUserStatus, ApiUserType,\n} from '../../types';\nimport { buildApiPeerId } from './peers';\nimport { buildApiBotInfo } from './bots';\nimport { buildApiPhoto } from './common';\n\nexport function buildApiUserFromFull(mtpUserFull: GramJs.users.UserFull): ApiUser {\n const {\n fullUser: {\n about, commonChatsCount, pinnedMsgId, botInfo, blocked,\n profilePhoto, voiceMessagesForbidden, premiumGifts,\n },\n users,\n } = mtpUserFull;\n\n const user = buildApiUser(users[0])!;\n\n return {\n ...user,\n fullInfo: {\n ...(profilePhoto instanceof GramJs.Photo && { profilePhoto: buildApiPhoto(profilePhoto) }),\n bio: about,\n commonChatsCount,\n pinnedMessageId: pinnedMsgId,\n isBlocked: Boolean(blocked),\n noVoiceMessages: voiceMessagesForbidden,\n ...(premiumGifts && { premiumGifts: premiumGifts.map((gift) => buildApiPremiumGiftOption(gift)) }),\n ...(botInfo && { botInfo: buildApiBotInfo(botInfo, user.id) }),\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 {\n id, firstName, lastName, fake, scam,\n } = mtpUser;\n const hasVideoAvatar = mtpUser.photo instanceof GramJs.UserProfilePhoto\n ? Boolean(mtpUser.photo.hasVideo)\n : undefined;\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 fakeType: scam ? 'scam' : (fake ? 'fake' : undefined),\n ...(mtpUser.self && { isSelf: true }),\n isPremium: Boolean(mtpUser.premium),\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 hasVideoAvatar,\n ...(mtpUser.bot && mtpUser.botInlinePlaceholder && { botPlaceholder: mtpUser.botInlinePlaceholder }),\n ...(mtpUser.bot && mtpUser.botAttachMenu && { isAttachMenuBot: mtpUser.botAttachMenu }),\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\nexport function buildApiUsersAndStatuses(mtpUsers: GramJs.TypeUser[]) {\n const userStatusesById: Record<string, ApiUserStatus> = {};\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\nexport function buildApiPremiumGiftOption(option: GramJs.TypePremiumGiftOption): ApiPremiumGiftOption {\n const {\n months, currency, amount, botUrl,\n } = option;\n\n return {\n months,\n currency,\n amount: amount.toJSNumber(),\n botUrl,\n };\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\n\nimport type {\n ApiCountry, ApiSession, ApiUrlAuthResult, ApiWallpaper, ApiWebSession,\n} from '../../types';\nimport type { ApiPrivacySettings, ApiPrivacyKey, PrivacyVisibility } from '../../../types';\n\nimport { buildApiDocument } from './messages';\nimport { buildApiPeerId, getApiChatIdFromMtpPeer } from './peers';\nimport { pick } from '../../../util/iteratees';\nimport { getServerTime } from '../../../util/serverTime';\nimport { buildApiUser } from './users';\nimport { addUserToLocalDb } from '../helpers';\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 areCallsEnabled: !session.callRequestsDisabled,\n areSecretChatsEnabled: !session.encryptedRequestsDisabled,\n ...pick(session, [\n 'deviceModel', 'platform', 'systemVersion', 'appName', 'appVersion', 'dateCreated', 'dateActive',\n 'ip', 'country', 'region',\n ]),\n };\n}\n\nexport function buildApiWebSession(session: GramJs.WebAuthorization): ApiWebSession {\n return {\n hash: String(session.hash),\n botId: buildApiPeerId(session.botId, 'user'),\n ...pick(session, [\n 'platform', 'browser', 'dateCreated', 'dateActive', 'ip', 'region', 'domain',\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 'PrivacyKeyPhoneCall':\n return 'phoneCall';\n case 'PrivacyKeyPhoneP2P':\n return 'phoneP2P';\n case 'PrivacyKeyForwards':\n return 'forwards';\n case 'PrivacyKeyVoiceMessages':\n return 'voiceMessages';\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, otherSound,\n } = notifySettings;\n\n const hasSound = Boolean(otherSound && !(otherSound instanceof GramJs.NotificationSoundNone));\n\n return {\n chatId: getApiChatIdFromMtpPeer(peer),\n isMuted: silent || (typeof muteUntil === 'number' && getServerTime(serverTimeOffset) < muteUntil),\n ...(!hasSound && { 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 nonHiddenCountries = countries.filter(({ hidden }) => !hidden);\n const listByCode = nonHiddenCountries\n .map((country) => (\n country.countryCodes.map((code) => buildApiCountry(country, code))\n ))\n .flat()\n .sort((a: ApiCountry, b: ApiCountry) => (\n a.name ? a.name.localeCompare(b.name!) : a.defaultName.localeCompare(b.defaultName)\n ));\n\n const generalList = nonHiddenCountries\n .map((country) => buildApiCountry(country, country.countryCodes[0]))\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\nexport function buildJson(json: GramJs.TypeJSONValue): any {\n if (json instanceof GramJs.JsonNull) return undefined;\n if (json instanceof GramJs.JsonString\n || json instanceof GramJs.JsonBool\n || json instanceof GramJs.JsonNumber) return json.value;\n if (json instanceof GramJs.JsonArray) return json.value.map(buildJson);\n\n return json.value.reduce((acc: Record<string, any>, el) => {\n acc[el.key] = buildJson(el.value);\n return acc;\n }, {});\n}\n\nexport function buildApiUrlAuthResult(result: GramJs.TypeUrlAuthResult): ApiUrlAuthResult | undefined {\n if (result instanceof GramJs.UrlAuthResultRequest) {\n const { bot, domain, requestWriteAccess } = result;\n const user = buildApiUser(bot);\n if (!user) return undefined;\n\n addUserToLocalDb(bot);\n\n return {\n type: 'request',\n domain,\n shouldRequestWriteAccess: requestWriteAccess,\n bot: user,\n };\n }\n\n if (result instanceof GramJs.UrlAuthResultAccepted) {\n return {\n type: 'accepted',\n url: result.url,\n };\n }\n\n if (result instanceof GramJs.UrlAuthResultDefault) {\n return {\n type: 'default',\n };\n }\n return undefined;\n}\n","import type { GroupCallConnectionData } from '../../lib/secret-sauce';\nimport { Api as GramJs, connection } from '../../lib/gramjs';\nimport type { 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 buildMessageReactions,\n} from './apiBuilders/messages';\nimport {\n buildChatMember,\n buildChatMembers,\n buildChatTypingStatus,\n buildAvatarHash,\n buildApiChatFromPreview,\n buildApiChatFolder,\n buildApiChatSettings,\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 buildPhoneCall,\n getGroupCallId,\n} from './apiBuilders/calls';\nimport { buildApiPeerId, getApiChatIdFromMtpPeer } from './apiBuilders/peers';\nimport { buildApiEmojiInteraction, buildStickerSet } from './apiBuilders/symbols';\nimport { buildApiBotMenuButton } from './apiBuilders/bots';\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) => (\n e instanceof GramJs.Chat || e instanceof GramJs.ChatForbidden\n || e instanceof GramJs.Channel || e instanceof GramJs.ChannelForbidden\n ))\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.MessageActionPaymentSent) {\n onUpdate({\n '@type': 'updatePaymentStateCompleted',\n slug: action.invoiceSlug,\n });\n } else 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 && Boolean(e.self) && e.id === action.userId\n ))) {\n onUpdate({\n '@type': 'updateChat',\n id: message.chatId,\n chat: {\n isForbidden: true,\n isNotJoined: true,\n },\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 && Boolean(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.UpdateMessageReactions) {\n onUpdate({\n '@type': 'updateMessageReactions',\n id: update.msgId,\n chatId: getApiChatIdFromMtpPeer(update.peer),\n reactions: buildMessageReactions(update.reactions),\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<string>(Boolean as any);\n\n if (existingIds.length) {\n onUpdate({\n '@type': 'deleteMessages',\n ids: existingIds,\n chatId,\n });\n }\n\n if (profilePhotoIds.length) {\n onUpdate({\n '@type': 'deleteProfilePhotos',\n ids: profilePhotoIds,\n chatId,\n });\n }\n\n // For some reason delete message update sometimes comes before new message update\n if (missingIds.length) {\n setTimeout(() => {\n onUpdate({\n '@type': 'deleteMessages',\n ids: missingIds,\n chatId,\n });\n }, DELETE_MISSING_CHANNEL_MESSAGE_DELAY);\n }\n } else if (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 || 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 instanceof GramJs.DialogFilter ? 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 if (update.action instanceof GramJs.SendMessageEmojiInteraction) {\n onUpdate({\n '@type': 'updateStartEmojiInteraction',\n id,\n emoji: update.action.emoticon,\n messageId: update.action.msgId,\n interaction: buildApiEmojiInteraction(JSON.parse(update.action.interaction.data)),\n });\n } else {\n onUpdate({\n '@type': 'updateChatTypingStatus',\n id,\n typingStatus: buildChatTypingStatus(update, serverTimeOffset),\n });\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, settings } = 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': 'deleteContact',\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 ...user,\n ...(settings && { settings: buildApiChatSettings(settings) }),\n },\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.UpdateRecentStickers) {\n onUpdate({ '@type': 'updateRecentStickers' });\n } else if (update instanceof GramJs.UpdateStickerSets) {\n onUpdate({ '@type': 'updateStickerSets' });\n } else if (update instanceof GramJs.UpdateStickerSetsOrder) {\n onUpdate({\n '@type': 'updateStickerSetsOrder',\n order: update.order.map((n) => n.toString()),\n isCustomEmoji: update.emojis,\n });\n } else if (update instanceof GramJs.UpdateNewStickerSet) {\n if (update.stickerset instanceof GramJs.messages.StickerSet) {\n const stickerSet = buildStickerSet(update.stickerset.set);\n onUpdate({\n '@type': 'updateStickerSet',\n id: stickerSet.id,\n stickerSet,\n });\n }\n } else if (update instanceof GramJs.UpdateSavedGifs) {\n onUpdate({ '@type': 'updateSavedGifs' });\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 (update instanceof GramJs.UpdatePendingJoinRequests) {\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': 'updatePendingJoinRequests',\n chatId: getApiChatIdFromMtpPeer(update.peer),\n recentRequesterIds: update.recentRequesters.map((id) => buildApiPeerId(id, 'user')),\n requestsPending: update.requestsPending,\n });\n } else if (update instanceof GramJs.UpdatePhoneCall) {\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': 'updatePhoneCall',\n call: buildPhoneCall(update.phoneCall),\n });\n } else if (update instanceof GramJs.UpdatePhoneCallSignalingData) {\n onUpdate({\n '@type': 'updatePhoneCallSignalingData',\n callId: update.phoneCallId.toString(),\n data: Array.from(update.data),\n });\n } else if (update instanceof GramJs.UpdateWebViewResultSent) {\n const { queryId } = update;\n\n onUpdate({\n '@type': 'updateWebViewResultSent',\n queryId: queryId.toString(),\n });\n } else if (update instanceof GramJs.UpdateBotMenuButton) {\n const {\n botId,\n button,\n } = update;\n\n const id = buildApiPeerId(botId, 'user');\n\n onUpdate({\n '@type': 'updateBotMenuButton',\n botId: id,\n button: buildApiBotMenuButton(button),\n });\n } else if (update instanceof GramJs.UpdateTranscribedAudio) {\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': 'updateTranscribedAudio',\n transcriptionId: update.transcriptionId.toString(),\n text: update.text,\n isPending: update.pending,\n });\n } else if (update instanceof GramJs.UpdateConfig) {\n // eslint-disable-next-line no-underscore-dangle\n const entities = update._entities;\n if (entities) {\n addEntitiesWithPhotosToLocalDb(entities);\n dispatchUserAndChatUpdates(entities);\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 type {\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<string>((resolve, reject) => {\n authController.resolve = resolve;\n authController.reject = reject;\n });\n}\n\nexport function onRequestCode(isCodeViaApp = false) {\n onUpdate({\n ...buildAuthStateUpdate('authorizationStateWaitCode'),\n isCodeViaApp,\n });\n\n return new Promise<string>((resolve, reject) => {\n authController.resolve = resolve;\n authController.reject = reject;\n });\n}\n\nexport function onRequestPassword(hint?: string) {\n onUpdate({\n ...buildAuthStateUpdate('authorizationStateWaitPassword'),\n hint,\n });\n\n return new Promise<string>((resolve) => {\n authController.resolve = resolve;\n });\n}\n\nexport function onRequestRegistration() {\n onUpdate(buildAuthStateUpdate('authorizationStateWaitRegistration'));\n\n return new Promise<[string, string?]>((resolve) => {\n authController.resolve = resolve;\n });\n}\n\nexport function onRequestQrCode(qrCode: { token: Buffer; expires: number }) {\n onUpdate({\n ...buildAuthStateUpdate('authorizationStateWaitQrCode'),\n qrCode: {\n token: btoa(String.fromCharCode(...qrCode.token)).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, ''),\n expires: qrCode.expires,\n },\n });\n\n return new Promise<void>((resolve, reject) => {\n authController.reject = reject;\n });\n}\n\nexport function onAuthError(err: Error) {\n let message: string;\n\n if (err instanceof errors.FloodWaitError) {\n const hours = Math.ceil(Number(err.seconds) / 60 / 60);\n message = `Too many attempts. Try again in ${hours > 1 ? `${hours} hours` : 'an hour'}`;\n } else {\n message = ApiErrors[err.message];\n }\n\n if (!message) {\n message = 'Unexpected Error';\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n }\n\n onUpdate({\n '@type': 'updateAuthorizationError',\n message,\n });\n}\n\nexport function onAuthReady() {\n onUpdate(buildAuthStateUpdate('authorizationStateReady'));\n}\n\nexport function onCurrentUserUpdate(currentUser: ApiUser) {\n onUpdate({\n '@type': 'updateCurrentUser',\n currentUser,\n });\n}\n\nexport function buildAuthStateUpdate(authorizationState: ApiUpdateAuthorizationStateType): ApiUpdateAuthorizationState {\n return {\n '@type': 'updateAuthorizationState',\n authorizationState,\n };\n}\n\nexport function provideAuthPhoneNumber(phoneNumber: string) {\n if (!authController.resolve) {\n return;\n }\n\n authController.resolve(phoneNumber);\n}\n\nexport function provideAuthCode(code: string) {\n if (!authController.resolve) {\n return;\n }\n\n authController.resolve(code);\n}\n\nexport function provideAuthPassword(password: string) {\n if (!authController.resolve) {\n return;\n }\n\n authController.resolve(password);\n}\n\nexport function provideAuthRegistration(registration: { firstName: string; lastName: string }) {\n const { firstName, lastName } = registration;\n\n if (!authController.resolve) {\n return;\n }\n\n authController.resolve([firstName, lastName]);\n}\n\nexport function restartAuth() {\n if (!authController.reject) {\n return;\n }\n\n authController.reject(new Error('RESTART_AUTH'));\n}\n\nexport function restartAuthWithQr() {\n if (!authController.reject) {\n return;\n }\n\n authController.reject(new Error('RESTART_AUTH_WITH_QR'));\n}\n","// eslint-disable-next-line no-restricted-globals\nconst cacheApi = self.caches;\n\nexport enum Type {\n Text,\n Blob,\n Json,\n ArrayBuffer,\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 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 case Type.ArrayBuffer:\n return await response.arrayBuffer();\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 | ArrayBuffer | string) {\n if (!cacheApi) {\n return undefined;\n }\n\n try {\n const cacheData = typeof data === 'string' || data instanceof Blob || data instanceof ArrayBuffer\n ? data\n : 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 remove(cacheName: string, key: string) {\n try {\n if (!cacheApi) {\n return undefined;\n }\n\n const cache = await cacheApi.open(cacheName);\n return await cache.delete(key);\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 type { TelegramClient } from '../../../lib/gramjs';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport type { ApiOnProgress, ApiParsedMedia, ApiPreparedMedia } from '../../types';\nimport {\n ApiMediaFormat,\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 * as cacheApi from '../../../util/cacheApi';\nimport { getEntityTypeById } from '../gramjsBuilders';\n\nconst MEDIA_ENTITY_TYPES = new Set([\n 'msg', 'sticker', 'gif', 'wallpaper', 'photo', 'webDocument', 'document', 'videoAvatar',\n]);\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\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 as string | Blob);\n const arrayBuffer = mediaFormat === ApiMediaFormat.Progressive ? parsed as ArrayBuffer : undefined;\n\n return {\n prepared,\n arrayBuffer,\n mimeType,\n fullSize,\n };\n}\n\nexport type EntityType = (\n 'msg' | 'sticker' | 'wallpaper' | 'gif' | 'channel' | 'chat' | 'user' | 'photo' | 'stickerSet' | 'webDocument' |\n 'document' | 'staticMap' | 'videoAvatar'\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 parsed = parseMediaUrl(url);\n\n if (!parsed) return undefined;\n\n const {\n entityType, entityId, sizeType, params, mediaMatchType,\n } = parsed;\n\n if (!isConnected) {\n return Promise.reject(new Error('ERROR: Client is not connected'));\n }\n\n if (entityType === 'staticMap') {\n const accessHash = entityId;\n const parsedParams = new URLSearchParams(params);\n const long = parsedParams.get('long');\n const lat = parsedParams.get('lat');\n const w = parsedParams.get('w');\n const h = parsedParams.get('h');\n const zoom = parsedParams.get('zoom');\n const scale = parsedParams.get('scale');\n const accuracyRadius = parsedParams.get('accuracy_radius');\n\n const data = await client.downloadStaticMap(accessHash, long, lat, w, h, zoom, scale, accuracyRadius);\n return {\n mimeType: 'image/png',\n data,\n };\n }\n\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 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 'videoAvatar':\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 case 'document':\n entity = localDb.documents[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.toJSNumber();\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.toJSNumber();\n }\n } else if (entity instanceof GramJs.Photo) {\n if (entityType === 'videoAvatar') {\n mimeType = 'video/mp4';\n } else {\n mimeType = 'image/jpeg';\n }\n } else if (entityType === 'sticker' && sizeType) {\n mimeType = 'image/webp';\n } else if (entityType === 'webDocument') {\n mimeType = (entity as GramJs.TypeWebDocument).mimeType;\n fullSize = (entity as GramJs.TypeWebDocument).size;\n } else {\n mimeType = (entity as GramJs.Document).mimeType;\n fullSize = (entity as GramJs.Document).size.toJSNumber();\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 = getMimeType(data);\n\n return { mimeType, data };\n } else {\n const data = await client.downloadProfilePhoto(entity, mediaMatchType === '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.MessageMediaGeo\n || message.media instanceof GramJs.MessageMediaVenue\n || message.media instanceof GramJs.MessageMediaGeoLive) {\n return 'image/png';\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 if (sizeType) {\n return 'image/jpeg';\n }\n\n return message.media.webpage.document.mimeType;\n }\n\n return undefined;\n}\n\n// eslint-disable-next-line no-async-without-await/no-async-without-await\nasync function parseMedia(\n data: Buffer, mediaFormat: ApiMediaFormat, mimeType?: string,\n): Promise<ApiParsedMedia | undefined> {\n switch (mediaFormat) {\n case ApiMediaFormat.BlobUrl:\n return new Blob([data], { type: mimeType });\n case ApiMediaFormat.Text:\n return data.toString();\n case ApiMediaFormat.Progressive:\n case ApiMediaFormat.DownloadUrl:\n return data.buffer;\n }\n\n return undefined;\n}\n\nfunction prepareMedia(mediaData: Exclude<ApiParsedMedia, ArrayBuffer>): 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\nexport function parseMediaUrl(url: string) {\n const mediaMatch = url.startsWith('staticMap')\n ? url.match(/(staticMap):([0-9-]+)(\\?.+)/)\n : url.startsWith('webDocument')\n ? url.match(/(webDocument):(.+)/)\n : url.match(\n // eslint-disable-next-line max-len\n /(avatar|profile|photo|msg|stickerSet|sticker|wallpaper|gif|document|videoAvatar)([-\\d\\w./]+)(?::\\d+)?(\\?size=\\w+)?/,\n );\n if (!mediaMatch) {\n return undefined;\n }\n\n const mediaMatchType = mediaMatch[1];\n const entityId: string | number = mediaMatch[2];\n\n let entityType: EntityType;\n const params = mediaMatch[3];\n const sizeType = params?.replace('?size=', '') || undefined;\n\n if (mediaMatch[1] === 'avatar' || mediaMatch[1] === 'profile') {\n entityType = getEntityTypeById(entityId);\n } else {\n entityType = mediaMatch[1] as EntityType;\n }\n\n return {\n mediaMatchType,\n entityType,\n entityId,\n sizeType,\n params,\n };\n}\n","import {\n sessions, Api as GramJs, connection,\n} from '../../../lib/gramjs';\nimport TelegramClient from '../../../lib/gramjs/client/TelegramClient';\n\nimport { Logger as GramJsLogger } from '../../../lib/gramjs/extensions/index';\nimport type { TwoFaParams } from '../../../lib/gramjs/client/2fa';\n\nimport type {\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, SUPPORTED_VIDEO_CONTENT_TYPES, VIDEO_MOV_TYPE,\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, { parseMediaUrl } from './media';\nimport { buildApiUserFromFull } from '../apiBuilders/users';\nimport localDb, { clearLocalDb } from '../localDb';\nimport { buildApiPeerId } from '../apiBuilders/peers';\nimport { addMessageToLocalDb } from '../helpers';\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;\nlet currentUserId: string | undefined;\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, isWebmSupported, maxBufferSize,\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 // Hacky way to update this set inside GramJS worker\n if (isMovSupported) SUPPORTED_VIDEO_CONTENT_TYPES.add(VIDEO_MOV_TYPE);\n // eslint-disable-next-line no-restricted-globals\n (self as any).isWebmSupported = isWebmSupported;\n // eslint-disable-next-line no-restricted-globals\n (self as any).maxBufferSize = maxBufferSize;\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 shouldThrowIfUnauthorized: Boolean(sessionData),\n });\n } catch (err: any) {\n // eslint-disable-next-line no-console\n console.error(err);\n\n if (err.message !== 'Disconnect' && err.message !== 'Cannot send requests while disconnected') {\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 function setIsPremium({ isPremium }: { isPremium: boolean }) {\n client.setIsPremium(isPremium);\n}\n\nexport async function destroy(noLogOut = false) {\n if (!noLogOut) {\n await invokeRequest(new GramJs.auth.LogOut());\n }\n\n clearLocalDb();\n\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 } else if (update instanceof GramJs.UpdateConfig) {\n // eslint-disable-next-line no-underscore-dangle\n const currentUser = (update as GramJs.UpdateConfig & { _entities?: (GramJs.TypeUser | GramJs.TypeChat)[] })\n ._entities\n ?.find((entity) => entity instanceof GramJs.User && buildApiPeerId(entity.id, 'user') === currentUserId);\n if (!(currentUser instanceof GramJs.User)) return;\n\n setIsPremium({ isPremium: Boolean(currentUser.premium) });\n }\n}\n\nexport async function invokeRequest<T extends GramJs.AnyRequest>(\n request: T,\n shouldReturnTrue: true,\n shouldThrow?: boolean,\n shouldIgnoreUpdates?: undefined,\n dcId?: number,\n): Promise<true | undefined>;\n\nexport async function invokeRequest<T extends GramJs.AnyRequest>(\n request: T,\n shouldReturnTrue?: boolean,\n shouldThrow?: boolean,\n shouldIgnoreUpdates?: boolean,\n dcId?: number,\n): Promise<T['__response'] | undefined>;\n\nexport async function invokeRequest<T extends GramJs.AnyRequest>(\n request: T,\n shouldReturnTrue = false,\n shouldThrow = false,\n shouldIgnoreUpdates = false,\n dcId?: number,\n) {\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, dcId);\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 (!shouldIgnoreUpdates) {\n handleUpdatesFromRequest(request, result);\n }\n\n return shouldReturnTrue ? result && true : result;\n } catch (err: any) {\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\nfunction handleUpdatesFromRequest<T extends GramJs.AnyRequest>(request: T, result: T['__response']) {\n let manyUpdates;\n let singleUpdate;\n\n if (result instanceof GramJs.UpdatesCombined || result instanceof GramJs.Updates) {\n manyUpdates = result;\n } else if (typeof result === 'object' && 'updates' in result && (\n result.updates instanceof GramJs.Updates || result.updates instanceof GramJs.UpdatesCombined\n )) {\n manyUpdates = result.updates;\n } else if (\n result instanceof GramJs.UpdateShortMessage\n || result instanceof GramJs.UpdateShortChatMessage\n || result instanceof GramJs.UpdateShort\n || result instanceof GramJs.UpdateShortSentMessage\n ) {\n singleUpdate = result;\n }\n\n if (manyUpdates) {\n injectUpdateEntities(manyUpdates);\n\n manyUpdates.updates.forEach((update) => {\n updater(update, request);\n });\n } else if (singleUpdate) {\n updater(singleUpdate, request);\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).catch(async (err) => {\n if (err.message.startsWith('FILE_REFERENCE')) {\n const isFileReferenceRepaired = await repairFileReference({ url: args.url });\n if (!isFileReferenceRepaired) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Failed to repair file reference', args.url);\n }\n return undefined;\n }\n\n return downloadMediaWithClient(args, client, isConnected, onProgress);\n }\n return undefined;\n });\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 if (user.photo instanceof GramJs.Photo) {\n localDb.photos[user.photo.id.toString()] = user.photo;\n }\n localDb.users[buildApiPeerId(user.id, 'user')] = user;\n const currentUser = buildApiUserFromFull(userFull);\n\n setMessageBuilderCurrentUserId(currentUser.id);\n onCurrentUserUpdate(currentUser);\n\n currentUserId = currentUser.id;\n setIsPremium({ isPremium: Boolean(currentUser.isPremium) });\n}\n\nexport function dispatchErrorUpdate<T extends GramJs.AnyRequest>(err: Error, request: T) {\n const isSlowMode = err.message.startsWith('A wait of') && (\n request instanceof GramJs.messages.SendMessage\n || request instanceof GramJs.messages.SendMedia\n || request instanceof GramJs.messages.SendMultiMedia\n );\n\n const { message } = err;\n\n onUpdate({\n '@type': 'error',\n error: {\n message,\n isSlowMode,\n hasErrorKey: true,\n },\n });\n}\n\nfunction injectUpdateEntities(result: GramJs.Updates | GramJs.UpdatesCombined) {\n const entities = [...result.users, ...result.chats];\n\n result.updates.forEach((update) => {\n if (entities) {\n // eslint-disable-next-line no-underscore-dangle\n (update as any)._entities = entities;\n }\n });\n}\n\nasync function handleTerminatedSession() {\n try {\n await invokeRequest(new GramJs.users.GetFullUser({\n id: new GramJs.InputUserSelf(),\n }), undefined, true);\n } catch (err: any) {\n if (err.message === 'AUTH_KEY_UNREGISTERED') {\n onUpdate({\n '@type': 'updateConnectionState',\n connectionState: 'connectionStateBroken',\n });\n }\n }\n}\n\nexport async function repairFileReference({\n url,\n}: {\n url: string;\n}) {\n const parsed = parseMediaUrl(url);\n\n if (!parsed) return undefined;\n\n const {\n entityType, entityId, mediaMatchType,\n } = parsed;\n\n if (mediaMatchType === 'file') {\n return false;\n }\n\n if (entityType === 'msg') {\n const entity = localDb.messages[entityId]!;\n const messageId = entity.id;\n\n const peer = 'channelId' in entity.peerId ? new GramJs.InputChannel({\n channelId: entity.peerId.channelId,\n accessHash: (localDb.chats[buildApiPeerId(entity.peerId.channelId, 'channel')] as GramJs.Channel).accessHash!,\n }) : undefined;\n const result = await invokeRequest(\n peer\n ? new GramJs.channels.GetMessages({\n channel: peer,\n id: [new GramJs.InputMessageID({ id: messageId })],\n })\n : new GramJs.messages.GetMessages({\n id: [new GramJs.InputMessageID({ id: messageId })],\n }),\n );\n\n if (!result || result instanceof GramJs.messages.MessagesNotModified) return false;\n\n const message = result.messages[0];\n if (message instanceof GramJs.MessageEmpty) return false;\n addMessageToLocalDb(message);\n return true;\n }\n\n return false;\n}\n","import type BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport type {\n OnApiUpdate,\n ApiChat,\n ApiMessage,\n ApiUser,\n ApiMessageEntity,\n ApiFormattedText,\n ApiChatFullInfo,\n ApiChatFolder,\n ApiChatBannedRights,\n ApiChatAdminRights,\n ApiGroupCall,\n ApiUserStatus,\n} from '../../types';\n\nimport {\n DEBUG, ARCHIVED_FOLDER_ID, MEMBERS_LOAD_SLICE, SERVICE_NOTIFICATIONS_USER_ID, ALL_FOLDER_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 buildApiChatSettings,\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';\nimport { buildStickerSet } from '../apiBuilders/symbols';\nimport localDb from '../localDb';\n\ntype FullChatData = {\n fullInfo: ApiChatFullInfo;\n users?: ApiUser[];\n userStatusesById: { [userId: string]: ApiUserStatus };\n groupCall?: Partial<ApiGroupCall>;\n membersCount?: number;\n};\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<ApiMessage>(Boolean as any),\n 'chatId',\n );\n const peersByKey: Record<string, GramJs.TypeChat | GramJs.TypeUser> = {\n ...(resultPinned && preparePeers(resultPinned)),\n ...preparePeers(result),\n };\n const chats: ApiChat[] = [];\n const draftsById: Record<string, ApiFormattedText> = {};\n const replyingToById: Record<string, number> = {};\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 fetchChatSettings(chat: ApiChat) {\n const { id, accessHash } = chat;\n\n const result = await invokeRequest(new GramJs.messages.GetPeerSettings({\n peer: buildInputPeer(id, accessHash),\n }));\n\n if (!result) {\n return undefined;\n }\n\n return buildApiChatSettings(result.settings);\n}\n\nexport async function searchChats({ query }: { query: string }) {\n const result = await invokeRequest(new GramJs.contacts.Search({ q: query }));\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const localPeerIds = result.myResults.map(getApiChatIdFromMtpPeer);\n const allChats = result.chats.concat(result.users)\n .map((user) => buildApiChatFromPreview(user))\n .filter<ApiChat>(Boolean as any);\n const allUsers = result.users.map(buildApiUser).filter((user) => Boolean(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<FullChatData | 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 availableReactions,\n recentRequesters,\n requestsPending,\n chatPhoto,\n } = result.fullChat;\n\n if (chatPhoto instanceof GramJs.Photo) {\n localDb.photos[chatPhoto.id.toString()] = chatPhoto;\n }\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 const { users, userStatusesById } = buildApiUsersAndStatuses(result.users);\n\n return {\n fullInfo: {\n ...(chatPhoto instanceof GramJs.Photo && { profilePhoto: buildApiPhoto(chatPhoto) }),\n about,\n members,\n adminMembers,\n canViewMembers: true,\n botCommands,\n ...(exportedInvite instanceof GramJs.ChatInviteExported && {\n // TODO Verify Exported Invite logic\n inviteLink: exportedInvite.link,\n }),\n groupCallId: call?.id.toString(),\n enabledReactions: availableReactions,\n requestsPending,\n recentRequesterIds: recentRequesters?.map((userId) => buildApiPeerId(userId, 'user')),\n },\n users,\n userStatusesById,\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 membersCount: members?.length,\n };\n}\n\nasync function getFullChannelInfo(\n id: string,\n accessHash: string,\n adminRights?: ApiChatAdminRights,\n): Promise<FullChatData | 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 canViewStats,\n linkedChatId,\n hiddenPrehistory,\n call,\n botInfo,\n availableReactions,\n defaultSendAs,\n requestsPending,\n recentRequesters,\n statsDc,\n participantsCount,\n stickerset,\n chatPhoto,\n } = result.fullChat;\n\n if (chatPhoto instanceof GramJs.Photo) {\n localDb.photos[chatPhoto.id.toString()] = chatPhoto;\n }\n\n const inviteLink = exportedInvite instanceof GramJs.ChatInviteExported\n ? exportedInvite.link\n : undefined;\n\n const { members, users, userStatusesById } = (canViewParticipants && await fetchMembers(id, accessHash)) || {};\n const { members: kickedMembers, users: bannedUsers, userStatusesById: bannedStatusesById } = (\n canViewParticipants && adminRights && await fetchMembers(id, accessHash, 'kicked')\n ) || {};\n const { members: adminMembers, users: adminUsers, userStatusesById: adminStatusesById } = (\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);\n if (chat) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n }\n }\n\n const statusesById = {\n ...userStatusesById,\n ...bannedStatusesById,\n ...adminStatusesById,\n };\n\n return {\n fullInfo: {\n ...(chatPhoto instanceof GramJs.Photo && { profilePhoto: buildApiPhoto(chatPhoto) }),\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 canViewStatistics: canViewStats,\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 enabledReactions: availableReactions,\n sendAsId: defaultSendAs ? getApiChatIdFromMtpPeer(defaultSendAs) : undefined,\n requestsPending,\n recentRequesterIds: recentRequesters?.map((userId) => buildApiPeerId(userId, 'user')),\n statisticsDcId: statsDc,\n stickerSet: stickerset ? buildStickerSet(stickerset) : undefined,\n },\n users: [...(users || []), ...(bannedUsers || []), ...(adminUsers || [])],\n userStatusesById: statusesById,\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 membersCount: participantsCount,\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<ApiChat | undefined> {\n const result = await invokeRequest(new GramJs.channels.CreateChannel({\n broadcast: true,\n title,\n about,\n }), undefined, 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 }), undefined, 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, 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<ApiChat | undefined> {\n const result = await invokeRequest(new GramJs.messages.CreateChat({\n title,\n users: users.map(({ id, accessHash }) => buildInputEntity(id, accessHash)) as GramJs.InputUser[],\n }), undefined, 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 const defaultFolderPosition = result.findIndex((l) => l instanceof GramJs.DialogFilterDefault);\n const dialogFilters = result.filter((df): df is GramJs.DialogFilter => df instanceof GramJs.DialogFilter);\n const orderedIds = dialogFilters.map(({ id }) => id);\n if (defaultFolderPosition !== -1) {\n orderedIds.splice(defaultFolderPosition, 0, ALL_FOLDER_ID);\n }\n return {\n byId: buildCollectionByKey(\n dialogFilters\n .map(buildApiChatFolder), 'id',\n ) as Record<number, ApiChatFolder>,\n orderedIds,\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).filter(Boolean);\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 function sortChatFolders(ids: number[]) {\n return invokeRequest(new GramJs.messages.UpdateDialogFiltersOrder({\n order: ids,\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 getChatByPhoneNumber(phoneNumber: string) {\n const result = await invokeRequest(new GramJs.contacts.ResolvePhone({\n phone: phoneNumber,\n }));\n\n return processResolvedPeer(result);\n}\n\nexport async function getChatByUsername(username: string) {\n const result = await invokeRequest(new GramJs.contacts.ResolveUsername({\n username,\n }));\n\n return processResolvedPeer(result);\n}\n\nfunction processResolvedPeer(result?: GramJs.contacts.TypeResolvedPeer) {\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 const { users, userStatusesById } = buildApiUsersAndStatuses(result.users);\n\n return {\n members: buildChatMembers(result),\n users,\n userStatusesById,\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 }), true);\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 }),\n undefined,\n 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, megagroup,\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 && !megagroup,\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 async function addChatMembers(chat: ApiChat, users: ApiUser[], noErrorUpdate = false) {\n try {\n if (chat.type === 'chatTypeChannel' || chat.type === 'chatTypeSuperGroup') {\n return await 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 await 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\nexport function toggleJoinToSend(chat: ApiChat, isEnabled: boolean) {\n return invokeRequest(new GramJs.channels.ToggleJoinToSend({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n enabled: isEnabled,\n }), true);\n}\n\nexport function toggleJoinRequest(chat: ApiChat, isEnabled: boolean) {\n return invokeRequest(new GramJs.channels.ToggleJoinRequest({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n enabled: isEnabled,\n }), true);\n}\n\nfunction preparePeers(\n result: GramJs.messages.Dialogs | GramJs.messages.DialogsSlice | GramJs.messages.PeerDialogs,\n) {\n const store: Record<string, GramJs.TypeChat | GramJs.TypeUser> = {};\n\n result.chats?.forEach((chat) => {\n store[`chat${chat.id}`] = chat;\n });\n\n result.users?.forEach((user) => {\n store[`user${user.id}`] = user;\n });\n\n return store;\n}\n\nfunction updateLocalDb(result: (\n GramJs.messages.Dialogs | GramJs.messages.DialogsSlice | GramJs.messages.PeerDialogs |\n GramJs.messages.ChatFull | GramJs.contacts.Found |\n GramJs.contacts.ResolvedPeer | GramJs.channels.ChannelParticipants |\n GramJs.messages.Chats | GramJs.messages.ChatsSlice | GramJs.TypeUpdates\n)) {\n if ('users' in result) {\n 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 }));\n if (!(updates instanceof GramJs.Updates) || !updates.chats.length) {\n return undefined;\n }\n\n return buildApiChatFromPreview(updates.chats[0]);\n}\n\nexport function setChatEnabledReactions({\n chat, enabledReactions,\n}: {\n chat: ApiChat; enabledReactions: string[];\n}) {\n return invokeRequest(new GramJs.messages.SetChatAvailableReactions({\n peer: buildInputPeer(chat.id, chat.accessHash),\n availableReactions: enabledReactions,\n }), true);\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<string> {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n\n reader.onload = (e: ProgressEvent<FileReader>) => {\n const { result } = e.target || {};\n if (typeof result === 'string') {\n resolve(result);\n }\n\n reject(new Error('Failed to read blob'));\n };\n\n reader.onerror = reject;\n reader.readAsDataURL(blob);\n });\n}\n\nexport function blobToFile(blob: Blob, fileName: string) {\n return new File([blob], fileName, {\n lastModified: Date.now(),\n type: blob.type,\n });\n}\n\nexport function preloadImage(url: string): Promise<HTMLImageElement> {\n return new Promise((resolve, reject) => {\n const img = new Image();\n img.onload = () => resolve(img);\n img.onerror = reject;\n img.src = url;\n });\n}\n\nexport function preloadVideo(url: string): Promise<HTMLVideoElement> {\n return new Promise((resolve, reject) => {\n const video = document.createElement('video');\n video.volume = 0;\n video.onloadedmetadata = () => resolve(video);\n video.onerror = reject;\n video.src = url;\n });\n}\n\nexport async function createPosterForVideo(url: string): Promise<string | undefined> {\n const video = await preloadVideo(url);\n\n return Promise.race([\n pause(2000) as Promise<undefined>,\n new Promise<string | undefined>((resolve, reject) => {\n video.onseeked = () => {\n if (!video.videoWidth || !video.videoHeight) {\n resolve(undefined);\n }\n\n const canvas = document.createElement('canvas');\n canvas.width = video.videoWidth;\n canvas.height = video.videoHeight;\n const ctx = canvas.getContext('2d')!;\n ctx.drawImage(video, 0, 0);\n resolve(canvas.toDataURL('image/jpeg'));\n };\n video.onerror = reject;\n video.currentTime = Math.min(video.duration, 1);\n }),\n ]);\n}\n\nexport async function fetchBlob(blobUrl: string) {\n const response = await fetch(blobUrl);\n return response.blob();\n}\n\nexport async function fetchFile(blobUrl: string, fileName: string) {\n const blob = await fetchBlob(blobUrl);\n return blobToFile(blob, fileName);\n}\n\nexport function imgToCanvas(img: HTMLImageElement) {\n const canvas = document.createElement('canvas');\n canvas.width = img.width;\n canvas.height = img.height;\n\n const ctx = canvas.getContext('2d')!;\n ctx.drawImage(img, 0, 0);\n\n return canvas;\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport type {\n ApiAttachment,\n ApiChat,\n ApiGlobalMessageSearchType,\n ApiMessage,\n ApiMessageEntity,\n ApiMessageSearchType,\n ApiNewPoll,\n ApiOnProgress,\n ApiReportReason,\n ApiSticker,\n ApiThreadInfo,\n ApiUser,\n ApiVideo,\n OnApiUpdate,\n ApiSponsoredMessage,\n ApiSendMessageAction,\n ApiContact,\n ApiPoll,\n} from '../../types';\nimport {\n MAIN_THREAD_ID,\n MESSAGE_DELETED,\n} from '../../types';\n\nimport {\n ALL_FOLDER_ID,\n DEBUG, MENTION_UNREAD_SLICE,\n PINNED_MESSAGES_LIMIT, REACTION_UNREAD_SLICE,\n SUPPORTED_IMAGE_CONTENT_TYPES,\n SUPPORTED_VIDEO_CONTENT_TYPES,\n} from '../../../config';\nimport { invokeRequest, uploadFile } from './client';\nimport {\n buildApiMessage,\n buildLocalForwardedMessage,\n buildLocalMessage,\n buildWebPage,\n buildApiSponsoredMessage,\n} from '../apiBuilders/messages';\nimport { buildApiUser } from '../apiBuilders/users';\nimport {\n buildInputEntity,\n buildInputMediaDocument,\n buildInputPeer,\n buildInputPoll,\n buildInputReportReason,\n buildMtpMessageEntity,\n generateRandomBigInt,\n getEntityTypeById,\n isMessageWithMedia,\n isServiceMessageWithMedia,\n buildSendMessageAction,\n buildInputPollFromExisting,\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 { 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: any) {\n if (err.message === 'CHANNEL_PRIVATE') {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat: {\n isRestricted: true,\n },\n });\n }\n }\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiMessage).filter<ApiMessage>(Boolean as any);\n const users = result.users.map(buildApiUser).filter<ApiUser>(Boolean as any);\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter<ApiChat>(Boolean as any);\n const threadInfos = messages.map(({ threadInfo }) => threadInfo).filter<ApiThreadInfo>(Boolean as any);\n\n return {\n messages,\n users,\n chats,\n threadInfos,\n };\n}\n\nexport async function fetchMessage({ chat, messageId }: { chat: ApiChat; messageId: number }) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n\n 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: any) {\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<ApiUser>(Boolean as any);\n\n return { message, users };\n}\n\nlet queue = Promise.resolve();\n\nexport function sendMessage(\n {\n chat,\n text,\n entities,\n replyingTo,\n replyingToTopId,\n attachment,\n sticker,\n gif,\n poll,\n contact,\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 replyingToTopId?: number;\n attachment?: ApiAttachment;\n sticker?: ApiSticker;\n gif?: ApiVideo;\n poll?: ApiNewPoll;\n contact?: ApiContact;\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,\n text,\n entities,\n replyingTo,\n replyingToTopId,\n attachment,\n sticker,\n gif,\n poll,\n contact,\n groupedId,\n scheduledAt,\n sendAs,\n 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 } else if (contact) {\n media = new GramJs.InputMediaContact({\n phoneNumber: contact.phoneNumber,\n firstName: contact.firstName,\n lastName: contact.lastName,\n vcard: '',\n });\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<string, {\n counter: number;\n singleMediaByIndex: Record<number, GramJs.InputSingleMedia>;\n}> = {};\n\nfunction sendGroupedMedia(\n {\n chat,\n text,\n entities,\n replyingTo,\n attachment,\n groupedId,\n isSilent,\n scheduledAt,\n 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<ApiMessage> = {\n content: {\n ...message.content,\n ...(text && {\n text: {\n text,\n entities,\n },\n }),\n },\n };\n\n onUpdate({\n '@type': isScheduled ? 'updateScheduledMessage' : 'updateMessage',\n id: message.id,\n chatId: chat.id,\n message: messageUpdate,\n });\n\n // TODO Revise intersecting with scheduled\n localDb.localMessages[message.id] = { ...message, ...messageUpdate };\n\n const mtpEntities = entities && entities.map(buildMtpMessageEntity);\n\n await invokeRequest(new GramJs.messages.EditMessage({\n message: text || '',\n entities: mtpEntities,\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: message.id,\n ...(isScheduled && { scheduleDate: message.date }),\n ...(noWebPage && { noWebpage: noWebPage }),\n }), true);\n}\n\nexport async function rescheduleMessage({\n chat,\n message,\n scheduledAt,\n}: {\n chat: ApiChat;\n message: ApiMessage;\n scheduledAt: number;\n}) {\n await invokeRequest(new GramJs.messages.EditMessage({\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: message.id,\n scheduleDate: scheduledAt,\n }), true);\n}\n\nasync function uploadMedia(localMessage: ApiMessage, attachment: ApiAttachment, onProgress: ApiOnProgress) {\n const {\n filename, blobUrl, mimeType, quick, voice, audio, previewBlobUrl,\n } = attachment;\n\n const patchedOnProgress: ApiOnProgress = (progress) => {\n if (onProgress.isCanceled) {\n patchedOnProgress.isCanceled = true;\n } else {\n onProgress(progress, localMessage.id);\n }\n };\n\n const file = await fetchFile(blobUrl, filename);\n const inputFile = await uploadFile(file, patchedOnProgress);\n\n const thumbFile = previewBlobUrl && await fetchFile(previewBlobUrl, filename);\n const thumb = thumbFile ? await uploadFile(thumbFile) : undefined;\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 (audio) {\n const { duration, title, performer } = audio;\n attributes.push(new GramJs.DocumentAttributeAudio({\n duration,\n title,\n performer,\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 thumb,\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<ApiChat>(Boolean as any);\n chats.forEach((newChat) => {\n onUpdate({\n '@type': 'updateChat',\n id: newChat.id,\n chat: newChat,\n noTopChatsRequest: true,\n });\n });\n\n return {\n discussionChatId,\n };\n}\n\nexport async function searchMessagesLocal({\n chat, type, query, topMessageId, minDate, maxDate, ...pagination\n}: {\n chat: ApiChat;\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(chat.id, chat.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 chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter<ApiChat>(Boolean as any);\n const users = result.users.map(buildApiUser).filter<ApiUser>(Boolean as any);\n const messages = result.messages.map(buildApiMessage).filter<ApiMessage>(Boolean as any);\n\n let totalCount = messages.length;\n let 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 chats,\n users,\n messages,\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((c) => buildApiChatFromPreview(c)).filter<ApiChat>(Boolean as any);\n const users = result.users.map(buildApiUser).filter<ApiUser>(Boolean as any);\n const messages = result.messages.map(buildApiMessage).filter<ApiMessage>(Boolean as any);\n\n let totalCount = messages.length;\n let nextRate: number | undefined;\n if (result instanceof GramJs.messages.MessagesSlice || result instanceof GramJs.messages.ChannelMessages) {\n totalCount = result.count;\n\n if (messages.length) {\n nextRate = messages[messages.length - 1].id;\n }\n }\n\n return {\n messages,\n users,\n chats,\n totalCount,\n nextRate: 'nextRate' in result && result.nextRate ? result.nextRate : nextRate,\n };\n}\n\nexport async function fetchWebPagePreview({ message }: { message: string }) {\n const preview = await invokeRequest(new GramJs.messages.GetWebPagePreview({\n message,\n }));\n\n return preview && buildWebPage(preview);\n}\n\nexport async function sendPollVote({\n chat, messageId, options,\n}: {\n chat: ApiChat;\n messageId: number;\n options: string[];\n}) {\n const { id, accessHash } = chat;\n\n await invokeRequest(new GramJs.messages.SendVote({\n peer: buildInputPeer(id, accessHash),\n msgId: messageId,\n options: options.map(deserializeBytes),\n }), true);\n}\n\nexport async function closePoll({\n chat, messageId, poll,\n}: {\n chat: ApiChat;\n messageId: number;\n poll: ApiPoll;\n}) {\n const { id, accessHash } = chat;\n\n await invokeRequest(new GramJs.messages.EditMessage({\n peer: buildInputPeer(id, accessHash),\n id: messageId,\n media: buildInputPollFromExisting(poll, true),\n }));\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<ApiUser>(Boolean as any);\n const votes = result.votes.map((vote) => ({\n userId: vote.userId,\n date: vote.date,\n }));\n\n return {\n count: result.count,\n votes,\n users,\n nextOffset: result.nextOffset,\n shouldResetVoters,\n };\n}\n\nexport async function forwardMessages({\n fromChat,\n toChat,\n messages,\n serverTimeOffset,\n isSilent,\n scheduledAt,\n sendAs,\n withMyScore,\n noAuthors,\n noCaptions,\n isCurrentUserPremium,\n}: {\n fromChat: ApiChat;\n toChat: ApiChat;\n messages: ApiMessage[];\n serverTimeOffset: number;\n isSilent?: boolean;\n scheduledAt?: number;\n sendAs?: ApiUser | ApiChat;\n withMyScore?: boolean;\n noAuthors?: boolean;\n noCaptions?: boolean;\n isCurrentUserPremium?: boolean;\n}) {\n const messageIds = messages.map(({ id }) => id);\n const randomIds = messages.map(generateRandomBigInt);\n\n messages.forEach((message, index) => {\n const localMessage = buildLocalForwardedMessage(\n toChat, message, serverTimeOffset, scheduledAt, noAuthors, noCaptions, isCurrentUserPremium,\n );\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 withMyScore: withMyScore || undefined,\n silent: isSilent || undefined,\n dropAuthor: noAuthors || undefined,\n dropMediaCaptions: noCaptions || undefined,\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<ApiMessage>(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 addEntitiesWithPhotosToLocalDb(result.users);\n addEntitiesWithPhotosToLocalDb(result.chats);\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 chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter<ApiChat>(Boolean as any);\n const users = result.users.map(buildApiUser).filter<ApiUser>(Boolean as any);\n const messages = result.messages.map(buildApiMessage).filter<ApiMessage>(Boolean as any);\n\n 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<ApiUser>(Boolean as any);\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter<ApiChat>(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<ApiSponsoredMessage>(Boolean as any);\n const users = result.users.map(buildApiUser).filter<ApiUser>(Boolean as any);\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter<ApiChat>(Boolean as any);\n\n return {\n messages,\n users,\n chats,\n };\n}\n\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\nexport function readAllMentions({\n chat,\n}: {\n chat: ApiChat;\n}) {\n return invokeRequest(new GramJs.messages.ReadMentions({\n peer: buildInputPeer(chat.id, chat.accessHash),\n }), true);\n}\n\nexport function readAllReactions({\n chat,\n}: {\n chat: ApiChat;\n}) {\n return invokeRequest(new GramJs.messages.ReadReactions({\n peer: buildInputPeer(chat.id, chat.accessHash),\n }), true);\n}\n\nexport async function fetchUnreadMentions({\n chat, ...pagination\n}: {\n chat: ApiChat;\n offsetId?: number;\n addOffset?: number;\n maxId?: number;\n minId?: number;\n}) {\n const result = await invokeRequest(new GramJs.messages.GetUnreadMentions({\n peer: buildInputPeer(chat.id, chat.accessHash),\n limit: MENTION_UNREAD_SLICE,\n ...pagination,\n }));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiMessage).filter<ApiMessage>(Boolean as any);\n const users = result.users.map(buildApiUser).filter<ApiUser>(Boolean as any);\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter<ApiChat>(Boolean as any);\n\n return {\n messages,\n users,\n chats,\n };\n}\n\nexport async function fetchUnreadReactions({\n chat, ...pagination\n}: {\n chat: ApiChat;\n offsetId?: number;\n addOffset?: number;\n maxId?: number;\n minId?: number;\n}) {\n const result = await invokeRequest(new GramJs.messages.GetUnreadReactions({\n peer: buildInputPeer(chat.id, chat.accessHash),\n limit: REACTION_UNREAD_SLICE,\n ...pagination,\n }));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiMessage).filter<ApiMessage>(Boolean as any);\n const users = result.users.map(buildApiUser).filter<ApiUser>(Boolean as any);\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter<ApiChat>(Boolean as any);\n\n return {\n messages,\n users,\n chats,\n };\n}\n\nexport async function transcribeAudio({\n chat, messageId,\n}: {\n chat: ApiChat; messageId: number;\n}) {\n const result = await invokeRequest(new GramJs.messages.TranscribeAudio({\n msgId: messageId,\n peer: buildInputPeer(chat.id, chat.accessHash),\n }));\n\n if (!result) return undefined;\n\n onUpdate({\n '@type': 'updateTranscribedAudio',\n isPending: result.pending,\n transcriptionId: result.transcriptionId.toString(),\n text: result.text,\n });\n\n return result.transcriptionId.toString();\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport type {\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 { addEntitiesWithPhotosToLocalDb, addPhotoToLocalDb, addUserToLocalDb } from '../helpers';\nimport { buildApiPeerId } from '../apiBuilders/peers';\nimport localDb from '../localDb';\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 undefined;\n }\n\n const fullInfo = await invokeRequest(new GramJs.users.GetFullUser({ id: input }));\n\n if (!fullInfo) {\n return undefined;\n }\n\n if (fullInfo.fullUser.profilePhoto instanceof GramJs.Photo) {\n localDb.photos[fullInfo.fullUser.profilePhoto.id.toString()] = fullInfo.fullUser.profilePhoto;\n }\n\n const botInfo = fullInfo.fullUser.botInfo;\n if (botInfo?.descriptionPhoto instanceof GramJs.Photo) {\n localDb.photos[botInfo.descriptionPhoto.id.toString()] = botInfo.descriptionPhoto;\n }\n if (botInfo?.descriptionDocument instanceof GramJs.Document) {\n localDb.documents[botInfo.descriptionDocument.id.toString()] = botInfo.descriptionDocument;\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 return userWithFullInfo;\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) => Boolean(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 addUserToLocalDb(user, true);\n }\n });\n\n const { users, userStatusesById } = buildApiUsersAndStatuses(result.users);\n\n return {\n users,\n userStatusesById,\n chats: result.users.map((user) => buildApiChatFromPreview(user)).filter<ApiChat>(Boolean as any),\n };\n}\n\nexport async function fetchUsers({ users }: { users: ApiUser[] }) {\n const result = await invokeRequest(new GramJs.users.GetUsers({\n id: users.map(({ id, accessHash }) => buildInputPeer(id, accessHash)),\n }));\n if (!result || !result.length) {\n return undefined;\n }\n\n result.forEach((user) => {\n if (user instanceof GramJs.User) {\n addUserToLocalDb(user, true);\n }\n });\n\n return buildApiUsersAndStatuses(result);\n}\n\nexport async function importContact({\n phone,\n firstName,\n lastName,\n}: {\n phone?: string;\n firstName?: string;\n lastName?: string;\n}) {\n const result = await invokeRequest(new GramJs.contacts.ImportContacts({\n contacts: [buildInputContact({\n phone: phone || '',\n firstName: firstName || '',\n lastName: lastName || '',\n })],\n }));\n\n if (result instanceof GramJs.contacts.ImportedContacts && result.users.length) {\n addUserToLocalDb(result.users[0]);\n }\n\n return result?.imported.length ? buildApiPeerId(result.imported[0].userId, 'user') : undefined;\n}\n\nexport function updateContact({\n id,\n accessHash,\n phoneNumber = '',\n firstName = '',\n lastName = '',\n shouldSharePhoneNumber = false,\n}: {\n id: string;\n accessHash?: string;\n phoneNumber?: string;\n firstName?: string;\n lastName?: string;\n shouldSharePhoneNumber?: boolean;\n}) {\n return invokeRequest(new GramJs.contacts.AddContact({\n id: buildInputEntity(id, accessHash) as GramJs.InputUser,\n firstName,\n lastName,\n phone: phoneNumber,\n ...(shouldSharePhoneNumber && { addPhonePrivacyException: shouldSharePhoneNumber }),\n }), true);\n}\n\nexport async function deleteContact({\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': 'deleteContact',\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 chat: chat!,\n type: 'profilePhoto',\n limit: PROFILE_PHOTOS_LIMIT,\n });\n\n if (!result) {\n return undefined;\n }\n\n const { messages, users } = result;\n\n return {\n photos: messages.map((message) => message.content.action!.photo).filter<ApiPhoto>(Boolean as any),\n users,\n };\n}\n\nexport function reportSpam(userOrChat: ApiUser | ApiChat) {\n const { id, accessHash } = userOrChat;\n\n return invokeRequest(new GramJs.messages.ReportSpam({\n peer: buildInputPeer(id, accessHash),\n }), true);\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 type {\n ApiStickerSetInfo, ApiSticker, ApiVideo, OnApiUpdate,\n} from '../../types';\n\nimport { invokeRequest } from './client';\nimport {\n buildStickerSet, buildStickerSetCovered, processStickerPackResult, processStickerResult,\n} 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 fetchCustomEmojiSets({ hash = '0' }: { hash?: string }) {\n const allStickers = await invokeRequest(new GramJs.messages.GetEmojiStickers({ 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 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 isPremium: Boolean(result.premium),\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 function removeRecentSticker({\n sticker,\n}: {\n sticker: ApiSticker;\n}) {\n const request = new GramJs.messages.SaveRecentSticker({\n id: buildInputDocument(sticker),\n unsave: true,\n });\n\n return invokeRequest(request);\n}\n\nexport function clearRecentStickers() {\n return invokeRequest(new GramJs.messages.ClearRecentStickers());\n}\n\nexport async function fetchStickers(\n { stickerSetInfo }:\n { stickerSetInfo: ApiStickerSetInfo },\n) {\n if ('isMissing' in stickerSetInfo) return undefined;\n const result = await invokeRequest(new GramJs.messages.GetStickerSet({\n stickerset: 'id' in stickerSetInfo\n ? buildInputStickerSet(stickerSetInfo.id, stickerSetInfo.accessHash)\n : buildInputStickerSetShortName(stickerSetInfo.shortName),\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 fetchCustomEmoji({ documentId }: { documentId: string[] }) {\n if (!documentId.length) return undefined;\n const result = await invokeRequest(new GramJs.messages.GetCustomEmojiDocuments({\n documentId: documentId.map((id) => BigInt(id)),\n }));\n if (!result) return undefined;\n\n return processStickerResult(result);\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 fetchAnimatedEmojiEffects() {\n const result = await invokeRequest(new GramJs.messages.GetStickerSet({\n stickerset: new GramJs.InputStickerSetAnimatedEmojiAnimations(),\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 fetchPremiumGifts() {\n const result = await invokeRequest(new GramJs.messages.GetStickerSet({\n stickerset: new GramJs.InputStickerSetPremiumGifts(),\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 function saveGif({ gif, shouldUnsave }: { gif: ApiVideo; shouldUnsave?: boolean }) {\n const request = new GramJs.messages.SaveGif({\n id: buildInputDocument(gif),\n unsave: shouldUnsave,\n });\n\n return invokeRequest(request, true);\n}\n\nexport async function installStickerSet({ stickerSetId, accessHash }: { stickerSetId: string; accessHash: string }) {\n const result = await invokeRequest(new GramJs.messages.InstallStickerSet({\n stickerset: buildInputStickerSet(stickerSetId, accessHash),\n }));\n\n if (result) {\n onUpdate({\n '@type': 'updateStickerSet',\n id: stickerSetId,\n stickerSet: { installedDate: Date.now() },\n });\n }\n}\n\nexport async function uninstallStickerSet({ stickerSetId, accessHash }: { stickerSetId: string; accessHash: string }) {\n const result = await invokeRequest(new GramJs.messages.UninstallStickerSet({\n stickerset: buildInputStickerSet(stickerSetId, accessHash),\n }));\n\n if (result) {\n onUpdate({\n '@type': 'updateStickerSet',\n id: stickerSetId,\n stickerSet: { installedDate: undefined },\n });\n }\n}\n\nlet inputGifBot: GramJs.InputUser | undefined;\n\nexport async function searchGifs({ query, offset = '' }: { query: string; offset?: string }) {\n if (!inputGifBot) {\n const config = await invokeRequest(new GramJs.help.GetConfig());\n if (!config) {\n return undefined;\n }\n\n const resolvedPeer = await invokeRequest(new GramJs.contacts.ResolveUsername({\n username: config.gifSearchUsername,\n }));\n if (!resolvedPeer || !(resolvedPeer.users[0] instanceof GramJs.User)) {\n return undefined;\n }\n\n inputGifBot = new GramJs.InputUser({\n userId: (resolvedPeer.peer as GramJs.PeerUser).userId,\n accessHash: resolvedPeer.users[0].accessHash!,\n });\n }\n\n const result = await invokeRequest(new GramJs.messages.GetInlineBotResults({\n bot: inputGifBot,\n peer: new GramJs.InputPeerEmpty(),\n query,\n offset,\n }));\n if (!result) {\n return undefined;\n }\n\n const documents = result.results\n .map((foundGif) => {\n if (foundGif instanceof GramJs.BotInlineMediaResult) {\n return foundGif.document;\n }\n\n return undefined;\n })\n .filter<GramJs.TypeDocument>(Boolean as any);\n\n return {\n nextOffset: result.nextOffset,\n gifs: processGifResult(documents),\n };\n}\n\nexport async function fetchStickersForEmoji({\n emoji, hash = '0',\n}: { emoji: string; hash?: 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<string, string[]>),\n };\n}\n\nfunction processGifResult(gifs: GramJs.TypeDocument[]) {\n return gifs\n .map((document) => {\n if (document instanceof GramJs.Document) {\n const gif = buildVideoFromDocument(document);\n if (gif) {\n localDb.documents[String(document.id)] = document;\n\n return gif;\n }\n }\n\n return undefined;\n })\n .filter<ApiVideo>(Boolean as any);\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\n\nimport { invokeRequest } from './client';\nimport { buildInputEntity, buildInputPeer } from '../gramjsBuilders';\nimport type { ApiChat, ApiUser, OnApiUpdate } from '../../types';\nimport { addEntitiesWithPhotosToLocalDb } from '../helpers';\nimport { buildApiExportedInvite, buildChatInviteImporter } from '../apiBuilders/chats';\nimport { buildApiUser } from '../apiBuilders/users';\nimport { buildCollectionByKey } from '../../../util/iteratees';\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport function checkChatUsername({ username }: { username: string }) {\n return invokeRequest(new GramJs.channels.CheckUsername({\n channel: new GramJs.InputChannelEmpty(),\n username,\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 // TODO Verify Exported Invite logic\n if (!(result instanceof GramJs.ChatInviteExported)) return undefined;\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\nexport async function fetchExportedChatInvites({\n peer, admin, limit = 0, isRevoked,\n}: { peer: ApiChat; admin: ApiUser; limit: number; isRevoked?: boolean }) {\n const exportedInvites = await invokeRequest(new GramJs.messages.GetExportedChatInvites({\n peer: buildInputPeer(peer.id, peer.accessHash),\n adminId: buildInputEntity(admin.id, admin.accessHash) as GramJs.InputUser,\n limit,\n revoked: isRevoked || undefined,\n }));\n\n if (!exportedInvites) return undefined;\n addEntitiesWithPhotosToLocalDb(exportedInvites.users);\n // TODO Verify Exported Invite logic\n return (exportedInvites.invites\n .filter((l) => l instanceof GramJs.ChatInviteExported) as GramJs.ChatInviteExported[])\n .map(buildApiExportedInvite);\n}\n\nexport async function editExportedChatInvite({\n peer, isRevoked, link, expireDate, usageLimit, isRequestNeeded, title,\n}: {\n peer: ApiChat;\n isRevoked?: boolean;\n link: string;\n expireDate?: number;\n usageLimit?: number;\n isRequestNeeded?: boolean;\n title?: string;\n}) {\n // TODO Verify Exported Invite logic\n const invite = await invokeRequest(new GramJs.messages.EditExportedChatInvite({\n link,\n peer: buildInputPeer(peer.id, peer.accessHash),\n expireDate,\n usageLimit: !isRequestNeeded ? usageLimit : undefined,\n requestNeeded: isRequestNeeded,\n title,\n revoked: isRevoked || undefined,\n }));\n\n if (!invite) return undefined;\n\n addEntitiesWithPhotosToLocalDb(invite.users);\n if (invite instanceof GramJs.messages.ExportedChatInvite && invite.invite instanceof GramJs.ChatInviteExported) {\n const replaceInvite = buildApiExportedInvite(invite.invite);\n return {\n oldInvite: replaceInvite,\n newInvite: replaceInvite,\n };\n }\n\n if (invite instanceof GramJs.messages.ExportedChatInviteReplaced\n && invite.invite instanceof GramJs.ChatInviteExported\n && invite.newInvite instanceof GramJs.ChatInviteExported) {\n const oldInvite = buildApiExportedInvite(invite.invite);\n const newInvite = buildApiExportedInvite(invite.newInvite);\n return {\n oldInvite,\n newInvite,\n };\n }\n return undefined;\n}\n\nexport async function exportChatInvite({\n peer, expireDate, usageLimit, isRequestNeeded, title,\n}: {\n peer: ApiChat;\n expireDate?: number;\n usageLimit?: number;\n isRequestNeeded?: boolean;\n title?: string;\n}) {\n const invite = await invokeRequest(new GramJs.messages.ExportChatInvite({\n peer: buildInputPeer(peer.id, peer.accessHash),\n expireDate,\n usageLimit: !isRequestNeeded ? usageLimit : undefined,\n requestNeeded: isRequestNeeded || undefined,\n title,\n }));\n\n // TODO Verify Exported Invite logic\n if (!(invite instanceof GramJs.ChatInviteExported)) return undefined;\n return buildApiExportedInvite(invite);\n}\n\nexport async function deleteExportedChatInvite({\n peer, link,\n}: {\n peer: ApiChat; link: string;\n}) {\n const result = await invokeRequest(new GramJs.messages.DeleteExportedChatInvite({\n peer: buildInputPeer(peer.id, peer.accessHash),\n link,\n }));\n\n return result;\n}\n\nexport async function deleteRevokedExportedChatInvites({\n peer, admin,\n}: {\n peer: ApiChat; admin: ApiUser;\n}) {\n const result = await invokeRequest(new GramJs.messages.DeleteRevokedExportedChatInvites({\n peer: buildInputPeer(peer.id, peer.accessHash),\n adminId: buildInputEntity(admin.id, admin.accessHash) as GramJs.InputUser,\n }));\n\n return result;\n}\n\nexport async function fetchChatInviteImporters({\n peer, link, offsetDate = 0, offsetUser, limit = 0, isRequested,\n}: {\n peer: ApiChat; link?: string; offsetDate: number; offsetUser?: ApiUser; limit: number; isRequested?: boolean;\n}) {\n const result = await invokeRequest(new GramJs.messages.GetChatInviteImporters({\n peer: buildInputPeer(peer.id, peer.accessHash),\n link,\n offsetDate,\n offsetUser: offsetUser\n ? buildInputEntity(offsetUser.id, offsetUser.accessHash) as GramJs.InputUser : new GramJs.InputUserEmpty(),\n limit,\n requested: isRequested || undefined,\n }));\n\n if (!result) return undefined;\n const users = result.users.map((user) => buildApiUser(user)).filter(Boolean);\n addEntitiesWithPhotosToLocalDb(result.users);\n return {\n importers: result.importers.map((importer) => buildChatInviteImporter(importer)),\n users: buildCollectionByKey(users, 'id'),\n };\n}\n\nexport function hideChatJoinRequest({\n peer,\n user,\n isApproved,\n}: {\n peer: ApiChat;\n user: ApiUser;\n isApproved: boolean;\n}) {\n return invokeRequest(new GramJs.messages.HideChatJoinRequest({\n peer: buildInputPeer(peer.id, peer.accessHash),\n userId: buildInputEntity(user.id, user.accessHash) as GramJs.InputUser,\n approved: isApproved || undefined,\n }), true);\n}\n\nexport function hideAllChatJoinRequests({\n peer,\n isApproved,\n link,\n}: {\n peer: ApiChat;\n isApproved: boolean;\n link?: string;\n}) {\n return invokeRequest(new GramJs.messages.HideAllChatJoinRequests({\n peer: buildInputPeer(peer.id, peer.accessHash),\n approved: isApproved || undefined,\n link,\n }), true);\n}\n\nexport function hideChatReportPanel(chat: ApiChat) {\n const { id, accessHash } = chat;\n\n return invokeRequest(new GramJs.messages.HidePeerSettingsBar({\n peer: buildInputPeer(id, accessHash),\n }));\n}\n","import { Api as GramJs, errors } from '../../../lib/gramjs';\n\nimport type { OnApiUpdate } from '../../types';\n\nimport { DEBUG } from '../../../config';\nimport { invokeRequest, updateTwoFaSettings } from './client';\n\nconst ApiErrors: { [k: string]: string } = {\n EMAIL_UNCONFIRMED: 'Email unconfirmed',\n EMAIL_HASH_EXPIRED: 'Email hash expired',\n NEW_SALT_INVALID: 'The new salt is invalid',\n NEW_SETTINGS_INVALID: 'The new password settings are invalid',\n CODE_INVALID: 'Invalid Code',\n PASSWORD_HASH_INVALID: 'Invalid Password',\n};\n\nconst emailCodeController: {\n resolve?: Function;\n reject?: Function;\n} = {};\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function getPasswordInfo() {\n const result = await invokeRequest(new GramJs.account.GetPassword());\n if (!result) {\n return undefined;\n }\n\n const { hint, hasPassword } = result;\n\n return { hint, hasPassword };\n}\n\nfunction onRequestEmailCode(length: number) {\n onUpdate({\n '@type': 'updateTwoFaStateWaitCode',\n length,\n });\n\n return new Promise<string>((resolve, reject) => {\n emailCodeController.resolve = resolve;\n emailCodeController.reject = reject;\n });\n}\n\nexport async function checkPassword(currentPassword: string) {\n try {\n await updateTwoFaSettings({ isCheckPassword: true, currentPassword });\n\n return true;\n } catch (err: any) {\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: any) {\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: any) {\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: any) {\n onError(err);\n\n return false;\n }\n}\n\nexport function provideRecoveryEmailCode(code: string) {\n emailCodeController.resolve!(code);\n}\n\nfunction onError(err: Error) {\n let message: string;\n\n if (err instanceof errors.FloodWaitError) {\n const hours = Math.ceil(Number(err.seconds) / 60 / 60);\n message = `Too many attempts. Try again in ${hours > 1 ? `${hours} hours` : 'an hour'}`;\n } else {\n message = ApiErrors[err.message];\n }\n\n if (!message) {\n message = 'Unexpected Error';\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n }\n\n onUpdate({\n '@type': 'updateTwoFaError',\n message,\n });\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\n\nimport type {\n ApiChat, ApiThemeParameters, ApiUser, OnApiUpdate,\n} from '../../types';\n\nimport localDb from '../localDb';\nimport { invokeRequest } from './client';\nimport { buildInputPeer, buildInputThemeParams, generateRandomBigInt } from '../gramjsBuilders';\nimport { buildApiUser } from '../apiBuilders/users';\nimport {\n buildApiAttachMenuBot, buildApiBotInlineMediaResult, buildApiBotInlineResult, buildBotSwitchPm,\n} from '../apiBuilders/bots';\nimport { buildApiChatFromPreview } from '../apiBuilders/chats';\nimport { addEntitiesWithPhotosToLocalDb, addUserToLocalDb, deserializeBytes } from '../helpers';\nimport { omitVirtualClassFields } from '../apiBuilders/helpers';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport { buildApiUrlAuthResult } from '../apiBuilders/misc';\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function answerCallbackButton({\n chatId, accessHash, messageId, data, isGame,\n}: {\n chatId: string; accessHash?: string; messageId: number; data?: string; isGame?: boolean;\n}) {\n const result = await invokeRequest(new GramJs.messages.GetBotCallbackAnswer({\n peer: buildInputPeer(chatId, accessHash),\n msgId: messageId,\n data: data ? deserializeBytes(data) : undefined,\n game: isGame || undefined,\n }));\n\n return result ? omitVirtualClassFields(result) : undefined;\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<ApiUser>(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<ApiUser>(Boolean as any),\n results: processInlineBotResult(String(result.queryId), result.results),\n };\n}\n\nexport async function sendInlineBotResult({\n chat, resultId, queryId, replyingTo, sendAs, isSilent, scheduleDate,\n}: {\n chat: ApiChat;\n resultId: string;\n queryId: string;\n replyingTo?: number;\n sendAs?: ApiUser | ApiChat;\n isSilent?: boolean;\n scheduleDate?: number;\n}) {\n const randomId = generateRandomBigInt();\n\n await invokeRequest(new GramJs.messages.SendInlineBotResult({\n clearDraft: true,\n randomId,\n queryId: BigInt(queryId),\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: resultId,\n scheduleDate,\n ...(isSilent && { silent: true }),\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\nexport async function requestWebView({\n isSilent,\n peer,\n bot,\n url,\n startParam,\n replyToMessageId,\n theme,\n sendAs,\n isFromBotMenu,\n}: {\n isSilent?: boolean;\n peer: ApiChat | ApiUser;\n bot: ApiUser;\n url?: string;\n startParam?: string;\n replyToMessageId?: number;\n theme?: ApiThemeParameters;\n sendAs?: ApiUser | ApiChat;\n isFromBotMenu?: boolean;\n}) {\n const result = await invokeRequest(new GramJs.messages.RequestWebView({\n silent: isSilent || undefined,\n peer: buildInputPeer(peer.id, peer.accessHash),\n bot: buildInputPeer(bot.id, bot.accessHash),\n replyToMsgId: replyToMessageId,\n url,\n startParam,\n themeParams: theme ? buildInputThemeParams(theme) : undefined,\n fromBotMenu: isFromBotMenu || undefined,\n ...(sendAs && { sendAs: buildInputPeer(sendAs.id, sendAs.accessHash) }),\n }));\n\n if (result instanceof GramJs.WebViewResultUrl) {\n return {\n url: result.url,\n queryId: result.queryId.toString(),\n };\n }\n\n return undefined;\n}\n\nexport async function requestSimpleWebView({\n bot, url, theme,\n}: {\n bot: ApiUser;\n url: string;\n theme?: ApiThemeParameters;\n}) {\n const result = await invokeRequest(new GramJs.messages.RequestSimpleWebView({\n url,\n bot: buildInputPeer(bot.id, bot.accessHash),\n themeParams: theme ? buildInputThemeParams(theme) : undefined,\n }));\n\n return result?.url;\n}\n\nexport function prolongWebView({\n isSilent,\n peer,\n bot,\n queryId,\n replyToMessageId,\n sendAs,\n}: {\n isSilent?: boolean;\n peer: ApiChat | ApiUser;\n bot: ApiUser;\n queryId: string;\n replyToMessageId?: number;\n sendAs?: ApiUser | ApiChat;\n}) {\n return invokeRequest(new GramJs.messages.ProlongWebView({\n silent: isSilent || undefined,\n peer: buildInputPeer(peer.id, peer.accessHash),\n bot: buildInputPeer(bot.id, bot.accessHash),\n queryId: BigInt(queryId),\n replyToMsgId: replyToMessageId,\n ...(sendAs && { sendAs: buildInputPeer(sendAs.id, sendAs.accessHash) }),\n }));\n}\n\nexport async function sendWebViewData({\n bot, buttonText, data,\n}: {\n bot: ApiUser;\n buttonText: string;\n data: string;\n}) {\n const randomId = generateRandomBigInt();\n await invokeRequest(new GramJs.messages.SendWebViewData({\n bot: buildInputPeer(bot.id, bot.accessHash),\n buttonText,\n data,\n randomId,\n }), true);\n}\n\nexport async function loadAttachMenuBots({\n hash,\n}: {\n hash?: string;\n}) {\n const result = await invokeRequest(new GramJs.messages.GetAttachMenuBots({\n hash: hash ? BigInt(hash) : undefined,\n }));\n\n if (result instanceof GramJs.AttachMenuBots) {\n addEntitiesWithPhotosToLocalDb(result.users);\n return {\n hash: result.hash.toString(),\n bots: buildCollectionByKey(result.bots.map(buildApiAttachMenuBot), 'id'),\n };\n }\n return undefined;\n}\n\nexport function toggleBotInAttachMenu({\n bot,\n isEnabled,\n}: {\n bot: ApiUser;\n isEnabled: boolean;\n}) {\n return invokeRequest(new GramJs.messages.ToggleBotInAttachMenu({\n bot: buildInputPeer(bot.id, bot.accessHash),\n enabled: isEnabled,\n }));\n}\n\nexport async function requestBotUrlAuth({\n chat, buttonId, messageId,\n}: {\n chat: ApiChat;\n buttonId: number;\n messageId: number;\n}) {\n const result = await invokeRequest(new GramJs.messages.RequestUrlAuth({\n peer: buildInputPeer(chat.id, chat.accessHash),\n buttonId,\n msgId: messageId,\n }));\n\n if (!result) return undefined;\n\n const authResult = buildApiUrlAuthResult(result);\n if (authResult?.type === 'request') {\n onUpdate({\n '@type': 'updateUser',\n id: authResult.bot.id,\n user: authResult.bot,\n });\n }\n return authResult;\n}\n\nexport async function acceptBotUrlAuth({\n chat,\n messageId,\n buttonId,\n isWriteAllowed,\n}: {\n chat: ApiChat;\n messageId: number;\n buttonId: number;\n isWriteAllowed?: boolean;\n}) {\n const result = await invokeRequest(new GramJs.messages.AcceptUrlAuth({\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: messageId,\n buttonId,\n writeAllowed: isWriteAllowed || undefined,\n }));\n\n if (!result) return undefined;\n\n const authResult = buildApiUrlAuthResult(result);\n if (authResult?.type === 'request') {\n onUpdate({\n '@type': 'updateUser',\n id: authResult.bot.id,\n user: authResult.bot,\n });\n }\n return authResult;\n}\n\nexport async function requestLinkUrlAuth({ url }: { url: string }) {\n const result = await invokeRequest(new GramJs.messages.RequestUrlAuth({\n url,\n }));\n\n if (!result) return undefined;\n\n const authResult = buildApiUrlAuthResult(result);\n if (authResult?.type === 'request') {\n onUpdate({\n '@type': 'updateUser',\n id: authResult.bot.id,\n user: authResult.bot,\n });\n }\n return authResult;\n}\n\nexport async function acceptLinkUrlAuth({ url, isWriteAllowed }: { url: string; isWriteAllowed?: boolean }) {\n const result = await invokeRequest(new GramJs.messages.AcceptUrlAuth({\n url,\n writeAllowed: isWriteAllowed || undefined,\n }));\n\n if (!result) return undefined;\n\n const authResult = buildApiUrlAuthResult(result);\n if (authResult?.type === 'request') {\n onUpdate({\n '@type': 'updateUser',\n id: authResult.bot.id,\n user: authResult.bot,\n });\n }\n return authResult;\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 BigInt from 'big-integer';\nimport type { JoinGroupCallPayload } from '../../../lib/secret-sauce';\nimport type {\n ApiChat, ApiUser, OnApiUpdate, ApiGroupCall, ApiPhoneCall,\n} from '../../types';\nimport { Api as GramJs } from '../../../lib/gramjs';\n\nimport { invokeRequest } from './client';\nimport {\n buildInputGroupCall, buildInputPeer, buildInputPhoneCall, generateRandomInt,\n} from '../gramjsBuilders';\nimport {\n buildCallProtocol,\n buildApiGroupCall,\n buildApiGroupCallParticipant, buildPhoneCall,\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<ApiGroupCall>;\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<ApiUser>(Boolean as any);\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter<ApiChat>(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<ApiUser>(Boolean as any);\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter<ApiChat>(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 }));\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 }));\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\nexport async function getDhConfig() {\n const dhConfig = await invokeRequest(new GramJs.messages.GetDhConfig({}));\n\n if (!dhConfig || dhConfig instanceof GramJs.messages.DhConfigNotModified) return undefined;\n\n return {\n g: dhConfig.g,\n p: Array.from(dhConfig.p),\n random: Array.from(dhConfig.random),\n };\n}\n\nexport function discardCall({\n call, isBusy,\n}: {\n call: ApiPhoneCall; isBusy?: boolean;\n}) {\n return invokeRequest(new GramJs.phone.DiscardCall({\n peer: buildInputPhoneCall(call),\n reason: isBusy ? new GramJs.PhoneCallDiscardReasonBusy() : new GramJs.PhoneCallDiscardReasonHangup(),\n }), true);\n}\n\nexport async function requestCall({\n user, gAHash, isVideo,\n}: {\n user: ApiUser; gAHash: number[]; isVideo?: boolean;\n}) {\n const result = await invokeRequest(new GramJs.phone.RequestCall({\n randomId: generateRandomInt(),\n userId: buildInputPeer(user.id, user.accessHash),\n gAHash: Buffer.from(gAHash),\n ...(isVideo && { video: true }),\n protocol: buildCallProtocol(),\n }));\n\n if (!result) {\n return false;\n }\n\n const call = buildPhoneCall(result.phoneCall);\n\n onUpdate({\n '@type': 'updatePhoneCall',\n call,\n });\n\n return true;\n}\n\nexport function setCallRating({\n call, rating, comment,\n}: {\n call: ApiPhoneCall; rating: number; comment: string;\n}) {\n return invokeRequest(new GramJs.phone.SetCallRating({\n rating,\n peer: buildInputPhoneCall(call),\n comment,\n }), true);\n}\n\nexport function receivedCall({\n call,\n}: {\n call: ApiPhoneCall;\n}) {\n return invokeRequest(new GramJs.phone.ReceivedCall({\n peer: buildInputPhoneCall(call),\n }));\n}\n\nexport async function acceptCall({\n call, gB,\n}: {\n call: ApiPhoneCall; gB: number[];\n}) {\n const result = await invokeRequest(new GramJs.phone.AcceptCall({\n peer: buildInputPhoneCall(call),\n gB: Buffer.from(gB),\n protocol: buildCallProtocol(),\n }));\n\n if (!result) {\n return;\n }\n\n call = buildPhoneCall(result.phoneCall);\n\n onUpdate({\n '@type': 'updatePhoneCall',\n call,\n });\n}\n\nexport async function confirmCall({\n call, gA, keyFingerprint,\n}: {\n call: ApiPhoneCall; gA: number[]; keyFingerprint: string;\n}) {\n const result = await invokeRequest(new GramJs.phone.ConfirmCall({\n peer: buildInputPhoneCall(call),\n gA: Buffer.from(gA),\n keyFingerprint: BigInt(keyFingerprint),\n protocol: buildCallProtocol(),\n }));\n\n if (!result) {\n return;\n }\n\n call = buildPhoneCall(result.phoneCall);\n\n onUpdate({\n '@type': 'updatePhoneCall',\n call,\n });\n}\n\nexport function sendSignalingData({\n data, call,\n}: {\n data: number[]; call: ApiPhoneCall;\n}) {\n return invokeRequest(new GramJs.phone.SendSignalingData({\n data: Buffer.from(data),\n peer: buildInputPhoneCall(call),\n }));\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport { invokeRequest } from './client';\nimport { buildInputInvoice, buildInputPeer, buildShippingInfo } from '../gramjsBuilders';\nimport {\n buildShippingOptions, buildPaymentForm, buildReceipt, buildApiPremiumPromo, buildApiInvoiceFromForm,\n} from '../apiBuilders/payments';\nimport type {\n ApiChat, OnApiUpdate, ApiRequestInputInvoice,\n} from '../../types';\nimport localDb from '../localDb';\nimport { addEntitiesWithPhotosToLocalDb } from '../helpers';\nimport { buildApiUser } from '../apiBuilders/users';\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function validateRequestedInfo({\n inputInvoice,\n requestInfo,\n shouldSave,\n}: {\n inputInvoice: ApiRequestInputInvoice;\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 invoice: buildInputInvoice(inputInvoice),\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 async function sendPaymentForm({\n inputInvoice,\n formId,\n requestedInfoId,\n shippingOptionId,\n credentials,\n}: {\n inputInvoice: ApiRequestInputInvoice;\n formId: string;\n credentials: any;\n requestedInfoId?: string;\n shippingOptionId?: string;\n}) {\n const result = await invokeRequest(new GramJs.payments.SendPaymentForm({\n formId: BigInt(formId),\n invoice: buildInputInvoice(inputInvoice),\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 }));\n\n if (result instanceof GramJs.payments.PaymentVerificationNeeded) {\n onUpdate({\n '@type': 'updatePaymentVerificationNeeded',\n url: result.url,\n });\n\n return undefined;\n }\n\n return Boolean(result);\n}\n\nexport async function getPaymentForm(inputInvoice: ApiRequestInputInvoice) {\n const result = await invokeRequest(new GramJs.payments.GetPaymentForm({\n invoice: buildInputInvoice(inputInvoice),\n }));\n\n if (!result) {\n return undefined;\n }\n\n if (result.photo) {\n localDb.webDocuments[result.photo.url] = result.photo;\n }\n\n return {\n form: buildPaymentForm(result),\n invoice: buildApiInvoiceFromForm(result),\n };\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\nexport async function fetchPremiumPromo() {\n const result = await invokeRequest(new GramJs.help.GetPremiumPromo());\n if (!result) return undefined;\n\n addEntitiesWithPhotosToLocalDb(result.users);\n\n const users = result.users.map(buildApiUser).filter(Boolean);\n result.videos.forEach((video) => {\n if (video instanceof GramJs.Document) {\n localDb.documents[video.id.toString()] = video;\n }\n });\n\n return {\n promo: buildApiPremiumPromo(result),\n users,\n };\n}\n","import type { Api as GramJs } from '../../../lib/gramjs';\n\nimport type { ApiInvoice, ApiPaymentSavedInfo, ApiPremiumPromo } from '../../types';\n\nimport { buildApiDocument, buildApiMessageEntity, buildApiWebDocument } from './messages';\nimport { omitVirtualClassFields } from './helpers';\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 + cur.amount.toJSNumber(), 0),\n prices: option.prices.map(({ label, amount }) => {\n return {\n label,\n amount: amount.toJSNumber(),\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: amount.toJSNumber(),\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: amount.toJSNumber(),\n };\n });\n shippingMethod = shipping.title;\n }\n\n return {\n currency,\n prices: mapedPrices,\n info: { shippingAddress, phone, name },\n totalAmount: totalAmount.toJSNumber(),\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 mappedPrices = prices.map(({ label, amount }) => ({\n label,\n amount: amount.toJSNumber(),\n }));\n const { shippingAddress } = savedInfo || {};\n const cleanedInfo: ApiPaymentSavedInfo | undefined = savedInfo ? omitVirtualClassFields(savedInfo) : undefined;\n if (cleanedInfo && shippingAddress) {\n cleanedInfo.shippingAddress = omitVirtualClassFields(shippingAddress);\n }\n\n const nativeData = nativeParams ? JSON.parse(nativeParams.data) : {};\n\n return {\n canSaveCredentials,\n passwordMissing,\n formId: String(formId),\n providerId: String(providerId),\n nativeProvider,\n savedInfo: cleanedInfo,\n invoice: {\n test,\n nameRequested,\n phoneRequested,\n emailRequested,\n shippingAddressRequested,\n flexible,\n phoneToProvider,\n emailToProvider,\n currency,\n prices: mappedPrices,\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 publicToken: nativeData?.public_token,\n },\n };\n}\n\nexport function buildApiInvoiceFromForm(form: GramJs.payments.PaymentForm): ApiInvoice {\n const {\n invoice, description: text, title, photo,\n } = form;\n const {\n test, currency, prices, recurring, recurringTermsUrl,\n } = invoice;\n\n const totalAmount = prices.reduce((ac, cur) => ac + cur.amount.toJSNumber(), 0);\n\n return {\n text,\n title,\n photo: buildApiWebDocument(photo),\n amount: totalAmount,\n currency,\n isTest: test,\n isRecurring: recurring,\n recurringTermsUrl,\n };\n}\n\nexport function buildApiPremiumPromo(promo: GramJs.help.PremiumPromo): ApiPremiumPromo {\n const {\n statusText, statusEntities, videos, videoSections, currency, monthlyAmount,\n } = promo;\n\n return {\n statusText,\n statusEntities: statusEntities.map((l) => buildApiMessageEntity(l)),\n videoSections,\n currency,\n videos: videos.map(buildApiDocument).filter(Boolean),\n monthlyAmount: monthlyAmount.toString(),\n };\n}\n","import BigInt from 'big-integer';\nimport type {\n ApiChat, ApiPhoto, ApiReportReason, ApiUser,\n} from '../../types';\nimport { invokeRequest } from './client';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport { buildInputPeer, buildInputReportReason, buildInputPhoto } from '../gramjsBuilders';\n\nexport async function reportPeer({\n peer,\n reason,\n description,\n}: {\n peer: ApiChat | ApiUser; reason: ApiReportReason; description?: string;\n}) {\n const result = await invokeRequest(new GramJs.account.ReportPeer({\n peer: buildInputPeer(peer.id, peer.accessHash),\n reason: buildInputReportReason(reason),\n message: description,\n }));\n\n return result;\n}\n\nexport async function reportProfilePhoto({\n peer,\n photo,\n reason,\n description,\n}: {\n peer: ApiChat | ApiUser; photo: ApiPhoto; reason: ApiReportReason; description?: string;\n}) {\n const photoId = buildInputPhoto(photo);\n if (!photoId) return undefined;\n\n const result = await invokeRequest(new GramJs.account.ReportProfilePhoto({\n peer: buildInputPeer(peer.id, peer.accessHash),\n photoId,\n reason: buildInputReportReason(reason),\n message: description,\n }));\n\n return result;\n}\n\nexport async function changeSessionSettings({\n hash, areCallsEnabled, areSecretChatsEnabled,\n}: {\n hash: string; areCallsEnabled?: boolean; areSecretChatsEnabled?: boolean;\n}) {\n const result = await invokeRequest(new GramJs.account.ChangeAuthorizationSettings({\n hash: BigInt(hash),\n ...(areCallsEnabled !== undefined ? { callRequestsDisabled: !areCallsEnabled } : undefined),\n ...(areSecretChatsEnabled !== undefined ? { encryptedRequestsDisabled: !areSecretChatsEnabled } : undefined),\n }));\n\n return result;\n}\n\nexport async function changeSessionTtl({\n days,\n}: {\n days: number;\n}) {\n const result = await invokeRequest(new GramJs.account.SetAuthorizationTTL({\n authorizationTtlDays: days,\n }));\n\n return result;\n}\n","/* eslint-disable @typescript-eslint/naming-convention */\nimport BigInt from 'big-integer';\nimport localDb from '../localDb';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport type { ApiAppConfig } from '../../types';\nimport type { ApiLimitType } from '../../../global/types';\nimport { buildJson } from './misc';\nimport { DEFAULT_LIMITS } from '../../../config';\n\ntype LimitType = 'default' | 'premium';\ntype Limit = 'upload_max_fileparts' | 'stickers_faved_limit' | 'saved_gifs_limit' | 'dialog_filters_chats_limit' |\n'dialog_filters_limit' | 'dialogs_folder_pinned_limit' | 'dialogs_pinned_limit' | 'caption_length_limit' |\n'channels_limit' | 'channels_public_limit' | 'about_length_limit';\ntype LimitKey = `${Limit}_${LimitType}`;\ntype LimitsConfig = Record<LimitKey, number>;\n\ninterface GramJsAppConfig extends LimitsConfig {\n emojies_sounds: Record<string, {\n id: string;\n access_hash: string;\n file_reference_base64: string;\n }>;\n emojies_send_dice: string[];\n groupcall_video_participants_max: number;\n reactions_default: string;\n reactions_uniq_max: number;\n chat_read_mark_size_threshold: number;\n chat_read_mark_expire_period: number;\n autologin_domains: string[];\n autologin_token: string;\n url_auth_domains: string[];\n premium_purchase_blocked: boolean;\n premium_bot_username: string;\n premium_invoice_slug: string;\n premium_promo_order: string[];\n}\n\nfunction buildEmojiSounds(appConfig: GramJsAppConfig) {\n const { emojies_sounds } = appConfig;\n return emojies_sounds ? Object.keys(emojies_sounds).reduce((acc: Record<string, string>, key) => {\n const l = emojies_sounds[key];\n localDb.documents[l.id] = new GramJs.Document({\n id: BigInt(l.id),\n accessHash: BigInt(l.access_hash),\n dcId: 1,\n mimeType: 'audio/ogg',\n fileReference: Buffer.from(atob(l.file_reference_base64\n .replace(/-/g, '+')\n .replace(/_/g, '/'))),\n } as GramJs.Document);\n\n acc[key] = l.id;\n return acc;\n }, {}) : {};\n}\n\nfunction getLimit(appConfig: GramJsAppConfig, key: Limit, fallbackKey: ApiLimitType) {\n const defaultLimit = appConfig[`${key}_default`] || DEFAULT_LIMITS[fallbackKey][0];\n const premiumLimit = appConfig[`${key}_premium`] || DEFAULT_LIMITS[fallbackKey][1];\n return [defaultLimit, premiumLimit] as const;\n}\n\nexport function buildAppConfig(json: GramJs.TypeJSONValue): ApiAppConfig {\n const appConfig = buildJson(json) as GramJsAppConfig;\n\n return {\n emojiSounds: buildEmojiSounds(appConfig),\n defaultReaction: appConfig.reactions_default,\n seenByMaxChatMembers: appConfig.chat_read_mark_size_threshold,\n seenByExpiresAt: appConfig.chat_read_mark_expire_period,\n autologinDomains: appConfig.autologin_domains || [],\n autologinToken: appConfig.autologin_token || '',\n urlAuthDomains: appConfig.url_auth_domains || [],\n premiumBotUsername: appConfig.premium_bot_username,\n premiumInvoiceSlug: appConfig.premium_invoice_slug,\n premiumPromoOrder: appConfig.premium_promo_order,\n isPremiumPurchaseBlocked: appConfig.premium_purchase_blocked,\n limits: {\n uploadMaxFileparts: getLimit(appConfig, 'upload_max_fileparts', 'uploadMaxFileparts'),\n stickersFaved: getLimit(appConfig, 'stickers_faved_limit', 'stickersFaved'),\n savedGifs: getLimit(appConfig, 'saved_gifs_limit', 'savedGifs'),\n dialogFiltersChats: getLimit(appConfig, 'dialog_filters_chats_limit', 'dialogFiltersChats'),\n dialogFilters: getLimit(appConfig, 'dialog_filters_limit', 'dialogFilters'),\n dialogFolderPinned: getLimit(appConfig, 'dialogs_pinned_limit', 'dialogFolderPinned'),\n captionLength: getLimit(appConfig, 'caption_length_limit', 'captionLength'),\n channels: getLimit(appConfig, 'channels_limit', 'channels'),\n channelsPublic: getLimit(appConfig, 'channels_public_limit', 'channelsPublic'),\n aboutLength: getLimit(appConfig, 'about_length_limit', 'aboutLength'),\n },\n };\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\n\nimport type {\n ApiAppConfig,\n ApiChat,\n ApiLangString,\n ApiLanguage,\n ApiNotifyException,\n ApiUser,\n ApiWallpaper,\n} from '../../types';\nimport type { ApiPrivacyKey, InputPrivacyRules, LangCode } from '../../../types';\n\nimport type { LANG_PACKS } from '../../../config';\nimport { BLOCKED_LIST_LIMIT, DEFAULT_LANG_PACK } from '../../../config';\nimport {\n buildApiCountryList,\n buildApiNotifyException,\n buildApiSession,\n buildApiWallpaper,\n buildApiWebSession,\n buildPrivacyRules,\n} from '../apiBuilders/misc';\n\nimport { buildApiUser } from '../apiBuilders/users';\nimport { buildApiChatFromPreview } from '../apiBuilders/chats';\nimport { getApiChatIdFromMtpPeer } from '../apiBuilders/peers';\nimport { buildAppConfig } from '../apiBuilders/appConfig';\nimport { omitVirtualClassFields } from '../apiBuilders/helpers';\nimport { buildInputEntity, buildInputPeer, buildInputPrivacyKey } from '../gramjsBuilders';\nimport { getClient, invokeRequest, uploadFile } from './client';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport { getServerTime } from '../../../util/serverTime';\nimport { addEntitiesWithPhotosToLocalDb } from '../helpers';\nimport localDb from '../localDb';\n\nconst MAX_INT_32 = 2 ** 31 - 1;\nconst BETA_LANG_CODES = ['ar', 'fa', 'id', 'ko', 'uz', 'en'];\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 }), true);\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 }), true);\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 }), true);\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<ApiWallpaper>(Boolean as any),\n };\n}\n\nexport async function uploadWallpaper(file: File) {\n const inputFile = await uploadFile(file);\n\n const result = await invokeRequest(new GramJs.account.UploadWallPaper({\n file: inputFile,\n mimeType: file.type,\n settings: new GramJs.WallPaperSettings(),\n }));\n\n if (!result || !(result instanceof GramJs.WallPaper)) {\n return undefined;\n }\n\n const wallpaper = buildApiWallpaper(result);\n if (!wallpaper) {\n return undefined;\n }\n\n localDb.documents[String(result.document.id)] = result.document as GramJs.Document;\n\n return { wallpaper };\n}\n\nexport async function fetchBlockedContacts() {\n const result = await invokeRequest(new GramJs.contacts.GetBlocked({\n limit: BLOCKED_LIST_LIMIT,\n }));\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return {\n users: result.users.map(buildApiUser).filter<ApiUser>(Boolean as any),\n chats: result.chats.map((chat) => buildApiChatFromPreview(chat)).filter<ApiChat>(Boolean as any),\n blockedIds: result.blocked.map((blocked) => getApiChatIdFromMtpPeer(blocked.peerId)),\n totalCount: result instanceof GramJs.contacts.BlockedSlice ? result.count : result.blocked.length,\n };\n}\n\nexport function blockContact(chatOrUserId: 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 {\n authorizations: buildCollectionByKey(result.authorizations.map(buildApiSession), 'hash'),\n ttlDays: result.authorizationTtlDays,\n };\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 fetchWebAuthorizations() {\n const result = await invokeRequest(new GramJs.account.GetWebAuthorizations());\n if (!result) {\n return undefined;\n }\n\n return buildCollectionByKey(result.authorizations.map(buildApiWebSession), 'hash');\n}\n\nexport function terminateWebAuthorization(hash: string) {\n return invokeRequest(new GramJs.account.ResetWebAuthorization({ hash: BigInt(hash) }));\n}\n\nexport function terminateAllWebAuthorizations() {\n return invokeRequest(new GramJs.account.ResetWebAuthorizations());\n}\n\nexport async function fetchNotificationExceptions({\n serverTimeOffset,\n}: { serverTimeOffset: number }) {\n const result = await invokeRequest(new GramJs.account.GetNotifyExceptions({\n compareSound: true,\n }), undefined, undefined, true);\n\n if (!(result instanceof GramJs.Updates || result instanceof GramJs.UpdatesCombined)) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return result.updates.reduce((acc, update) => {\n if (!(update instanceof GramJs.UpdateNotifySettings && update.peer instanceof GramJs.NotifyPeer)) {\n return acc;\n }\n\n acc.push(buildApiNotifyException(update.notifySettings, update.peer.peer, serverTimeOffset));\n\n return acc;\n }, [] as ApiNotifyException[]);\n}\n\nexport async function fetchNotificationSettings({\n serverTimeOffset,\n}: { serverTimeOffset: number }) {\n const [\n isMutedContactSignUpNotification,\n privateContactNotificationsSettings,\n groupNotificationsSettings,\n broadcastNotificationsSettings,\n ] = await Promise.all([\n invokeRequest(new GramJs.account.GetContactSignUpNotification()),\n invokeRequest(new GramJs.account.GetNotifySettings({\n peer: new GramJs.InputNotifyUsers(),\n })),\n invokeRequest(new GramJs.account.GetNotifySettings({\n peer: new GramJs.InputNotifyChats(),\n })),\n invokeRequest(new GramJs.account.GetNotifySettings({\n peer: new GramJs.InputNotifyBroadcasts(),\n })),\n ]);\n\n if (!privateContactNotificationsSettings || !groupNotificationsSettings || !broadcastNotificationsSettings) {\n return false;\n }\n\n const {\n silent: privateSilent, muteUntil: privateMuteUntil, showPreviews: privateShowPreviews,\n } = privateContactNotificationsSettings;\n const {\n silent: groupSilent, muteUntil: groupMuteUntil, showPreviews: groupShowPreviews,\n } = groupNotificationsSettings;\n const {\n silent: broadcastSilent, muteUntil: broadcastMuteUntil, showPreviews: broadcastShowPreviews,\n } = broadcastNotificationsSettings;\n\n return {\n hasContactJoinedNotifications: !isMutedContactSignUpNotification,\n hasPrivateChatsNotifications: !(\n privateSilent\n || (typeof privateMuteUntil === 'number' && getServerTime(serverTimeOffset) < privateMuteUntil)\n ),\n hasPrivateChatsMessagePreview: privateShowPreviews,\n hasGroupNotifications: !(\n groupSilent || (typeof groupMuteUntil === 'number'\n && getServerTime(serverTimeOffset) < groupMuteUntil)\n ),\n hasGroupMessagePreview: groupShowPreviews,\n hasBroadcastNotifications: !(\n broadcastSilent || (typeof broadcastMuteUntil === 'number'\n && getServerTime(serverTimeOffset) < broadcastMuteUntil)\n ),\n hasBroadcastMessagePreview: broadcastShowPreviews,\n };\n}\n\nexport function updateContactSignUpNotification(isSilent: boolean) {\n return invokeRequest(new GramJs.account.SetContactSignUpNotification({ silent: isSilent }));\n}\n\nexport function updateNotificationSettings(peerType: 'contact' | 'group' | 'broadcast', {\n isSilent,\n shouldShowPreviews,\n}: {\n isSilent: boolean;\n shouldShowPreviews: boolean;\n}) {\n let peer: GramJs.TypeInputNotifyPeer;\n if (peerType === 'contact') {\n peer = new GramJs.InputNotifyUsers();\n } else if (peerType === 'group') {\n peer = new GramJs.InputNotifyChats();\n } else {\n peer = new GramJs.InputNotifyBroadcasts();\n }\n\n const settings = {\n showPreviews: shouldShowPreviews,\n silent: isSilent,\n muteUntil: isSilent ? MAX_INT_32 : 0,\n };\n\n return invokeRequest(new GramJs.account.UpdateNotifySettings({\n peer,\n settings: new GramJs.InputPeerNotifySettings(settings),\n }));\n}\n\nexport async function fetchLanguages(): Promise<ApiLanguage[] | undefined> {\n const result = await invokeRequest(new GramJs.langpack.GetLanguages({\n langPack: DEFAULT_LANG_PACK,\n }));\n if (!result) {\n return undefined;\n }\n\n return result.map(omitVirtualClassFields);\n}\n\nexport async function fetchLangPack({ sourceLangPacks, langCode }: {\n sourceLangPacks: typeof LANG_PACKS;\n langCode: string;\n}) {\n const results = await Promise.all(sourceLangPacks.map((langPack) => {\n return invokeRequest(new GramJs.langpack.GetLangPack({\n langPack,\n langCode: BETA_LANG_CODES.includes(langCode) ? `${langCode}-raw` : langCode,\n }));\n }));\n\n const collections = results\n .filter<GramJs.LangPackDifference>(Boolean as any)\n .map((result) => {\n return buildCollectionByKey(result.strings.map<ApiLangString>(omitVirtualClassFields), 'key');\n });\n\n if (!collections.length) {\n return undefined;\n }\n\n return { langPack: Object.assign({}, ...collections.reverse()) as typeof collections[0] };\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\nexport async function fetchAppConfig(): Promise<ApiAppConfig | undefined> {\n const result = await invokeRequest(new GramJs.help.GetAppConfig());\n if (!result) return undefined;\n\n return buildAppConfig(result);\n}\n\nfunction updateLocalDb(\n result: (\n GramJs.account.PrivacyRules | GramJs.contacts.Blocked | GramJs.contacts.BlockedSlice |\n GramJs.Updates | GramJs.UpdatesCombined\n ),\n) {\n addEntitiesWithPhotosToLocalDb(result.users);\n addEntitiesWithPhotosToLocalDb(result.chats);\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\nexport async function fetchGlobalPrivacySettings() {\n const result = await invokeRequest(new GramJs.account.GetGlobalPrivacySettings());\n\n if (!result) {\n return undefined;\n }\n\n return {\n shouldArchiveAndMuteNewNonContact: Boolean(result.archiveAndMuteNewNoncontactPeers),\n };\n}\n\nexport async function updateGlobalPrivacySettings({ shouldArchiveAndMuteNewNonContact } : {\n shouldArchiveAndMuteNewNonContact: boolean;\n}) {\n const result = await invokeRequest(new GramJs.account.SetGlobalPrivacySettings({\n settings: new GramJs.GlobalPrivacySettings({\n archiveAndMuteNewNoncontactPeers: shouldArchiveAndMuteNewNonContact,\n }),\n }));\n\n if (!result) {\n return undefined;\n }\n\n return {\n shouldArchiveAndMuteNewNonContact: Boolean(result.archiveAndMuteNewNoncontactPeers),\n };\n}\n","import type { ApiChat, ApiUser } from '../../types';\nimport { invokeRequest } from './client';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport { buildInputPeer } from '../gramjsBuilders';\nimport localDb from '../localDb';\nimport { buildApiAvailableReaction, buildMessagePeerReaction } from '../apiBuilders/messages';\nimport { REACTION_LIST_LIMIT } from '../../../config';\nimport { addEntitiesWithPhotosToLocalDb } from '../helpers';\nimport { buildApiUser } from '../apiBuilders/users';\n\nexport function sendWatchingEmojiInteraction({\n chat,\n emoticon,\n}: {\n chat: ApiChat; emoticon: string;\n}) {\n return invokeRequest(new GramJs.messages.SetTyping({\n peer: buildInputPeer(chat.id, chat.accessHash),\n action: new GramJs.SendMessageEmojiInteractionSeen({\n emoticon,\n }),\n }));\n}\n\nexport function sendEmojiInteraction({\n chat,\n emoticon,\n messageId,\n timestamps,\n}: {\n chat: ApiChat; messageId: number; emoticon: string; timestamps: number[];\n}) {\n return invokeRequest(new GramJs.messages.SetTyping({\n peer: buildInputPeer(chat.id, chat.accessHash),\n action: new GramJs.SendMessageEmojiInteraction({\n emoticon,\n msgId: messageId,\n interaction: new GramJs.DataJSON({\n data: JSON.stringify({\n v: 1,\n a: timestamps.map((t: number) => ({\n t,\n i: 1,\n })),\n }),\n }),\n }),\n }));\n}\n\nexport async function getAvailableReactions() {\n const result = await invokeRequest(new GramJs.messages.GetAvailableReactions({}));\n\n if (!result || result instanceof GramJs.messages.AvailableReactionsNotModified) {\n return undefined;\n }\n\n result.reactions.forEach((reaction) => {\n if (reaction.staticIcon instanceof GramJs.Document) {\n localDb.documents[String(reaction.staticIcon.id)] = reaction.staticIcon;\n }\n if (reaction.selectAnimation instanceof GramJs.Document) {\n localDb.documents[String(reaction.selectAnimation.id)] = reaction.selectAnimation;\n }\n if (reaction.aroundAnimation instanceof GramJs.Document) {\n localDb.documents[String(reaction.aroundAnimation.id)] = reaction.aroundAnimation;\n }\n if (reaction.centerIcon instanceof GramJs.Document) {\n localDb.documents[String(reaction.centerIcon.id)] = reaction.centerIcon;\n }\n });\n\n return result.reactions.map(buildApiAvailableReaction);\n}\n\nexport function sendReaction({\n chat, messageId, reaction,\n}: {\n chat: ApiChat; messageId: number; reaction?: string;\n}) {\n return invokeRequest(new GramJs.messages.SendReaction({\n ...(reaction && { reaction }),\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: messageId,\n }), true);\n}\n\nexport function fetchMessageReactions({\n ids, chat,\n}: {\n ids: number[]; chat: ApiChat;\n}) {\n return invokeRequest(new GramJs.messages.GetMessagesReactions({\n id: ids,\n peer: buildInputPeer(chat.id, chat.accessHash),\n }), true);\n}\n\nexport async function fetchMessageReactionsList({\n chat, messageId, reaction, offset,\n}: {\n chat: ApiChat; messageId: number; reaction?: string; offset?: string;\n}) {\n const result = await invokeRequest(new GramJs.messages.GetMessageReactionsList({\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: messageId,\n ...(reaction && { reaction }),\n limit: REACTION_LIST_LIMIT,\n ...(offset && { offset }),\n }));\n\n if (!result) {\n return undefined;\n }\n\n addEntitiesWithPhotosToLocalDb(result.users);\n\n const { nextOffset, reactions, count } = result;\n\n return {\n users: result.users.map(buildApiUser).filter<ApiUser>(Boolean as any),\n nextOffset,\n reactions: reactions.map(buildMessagePeerReaction),\n count,\n };\n}\n\nexport function setDefaultReaction({\n reaction,\n}: {\n reaction: string;\n}) {\n return invokeRequest(new GramJs.messages.SetDefaultReaction({\n reaction,\n }));\n}\n","import type { Api as GramJs } from '../../../lib/gramjs';\nimport type {\n ApiChannelStatistics,\n ApiGroupStatistics,\n ApiMessageStatistics,\n ApiMessagePublicForward,\n StatisticsGraph,\n StatisticsOverviewItem,\n StatisticsOverviewPercentage,\n StatisticsOverviewPeriod,\n} from '../../types';\nimport { buildAvatarHash } from './chats';\nimport { buildApiPeerId } from './peers';\n\nexport function buildChannelStatistics(stats: GramJs.stats.BroadcastStats): ApiChannelStatistics {\n return {\n // Graphs\n growthGraph: buildGraph(stats.growthGraph),\n followersGraph: buildGraph(stats.followersGraph),\n muteGraph: buildGraph(stats.muteGraph),\n topHoursGraph: buildGraph(stats.topHoursGraph),\n\n // Async graphs\n languagesGraph: (stats.languagesGraph as GramJs.StatsGraphAsync).token,\n viewsBySourceGraph: (stats.viewsBySourceGraph as GramJs.StatsGraphAsync).token,\n newFollowersBySourceGraph: (stats.newFollowersBySourceGraph as GramJs.StatsGraphAsync).token,\n interactionsGraph: (stats.interactionsGraph as GramJs.StatsGraphAsync).token,\n\n // Statistics overview\n followers: buildStatisticsOverview(stats.followers),\n viewsPerPost: buildStatisticsOverview(stats.viewsPerPost),\n sharesPerPost: buildStatisticsOverview(stats.sharesPerPost),\n enabledNotifications: buildStatisticsPercentage(stats.enabledNotifications),\n\n // Recent posts\n recentTopMessages: stats.recentMessageInteractions,\n };\n}\n\nexport function buildGroupStatistics(stats: GramJs.stats.MegagroupStats): ApiGroupStatistics {\n return {\n // Graphs\n growthGraph: buildGraph(stats.growthGraph),\n membersGraph: buildGraph(stats.membersGraph),\n topHoursGraph: buildGraph(stats.topHoursGraph),\n\n // Async graphs\n languagesGraph: (stats.languagesGraph as GramJs.StatsGraphAsync).token,\n messagesGraph: (stats.messagesGraph as GramJs.StatsGraphAsync).token,\n actionsGraph: (stats.actionsGraph as GramJs.StatsGraphAsync).token,\n\n // Statistics overview\n period: getOverviewPeriod(stats.period),\n members: buildStatisticsOverview(stats.members),\n viewers: buildStatisticsOverview(stats.viewers),\n messages: buildStatisticsOverview(stats.messages),\n posters: buildStatisticsOverview(stats.posters),\n };\n}\n\nexport function buildMessageStatistics(stats: GramJs.stats.MessageStats): ApiMessageStatistics {\n return {\n viewsGraph: buildGraph(stats.viewsGraph),\n };\n}\n\nexport function buildMessagePublicForwards(\n result: GramJs.messages.TypeMessages,\n): ApiMessagePublicForward[] | undefined {\n if (!result || !('messages' in result)) {\n return undefined;\n }\n\n return result.messages.map((message) => {\n const peerId = buildApiPeerId((message.peerId as GramJs.PeerChannel).channelId, 'channel');\n const channel = result.chats.find((p) => buildApiPeerId(p.id, 'channel') === peerId);\n\n return {\n messageId: message.id,\n views: (message as GramJs.Message).views,\n title: (channel as GramJs.Channel).title,\n chat: {\n id: peerId,\n type: 'chatTypeChannel',\n username: (channel as GramJs.Channel).username,\n avatarHash: buildAvatarHash((channel as GramJs.Channel).photo),\n },\n };\n });\n}\n\nexport function buildGraph(\n result: GramJs.TypeStatsGraph, isPercentage?: boolean,\n): StatisticsGraph | undefined {\n if ((result as GramJs.StatsGraphError).error) {\n return undefined;\n }\n\n const data = JSON.parse((result as GramJs.StatsGraph).json.data);\n const [x, ...y] = data.columns;\n const hasSecondYAxis = data.y_scaled;\n\n return {\n type: isPercentage ? 'area' : data.types.y0,\n zoomToken: (result as GramJs.StatsGraph).zoomToken,\n labelFormatter: data.xTickFormatter,\n tooltipFormatter: data.xTooltipFormatter,\n labels: x.slice(1),\n hideCaption: !data.subchart.show,\n hasSecondYAxis,\n isStacked: data.stacked && !hasSecondYAxis,\n isPercentage,\n datasets: y.map((item: any) => {\n const key = item[0];\n\n return {\n name: data.names[key],\n color: extractColor(data.colors[key]),\n values: item.slice(1),\n };\n }),\n ...calculateMinimapRange(data.subchart.defaultZoom, x.slice(1)),\n };\n}\n\nfunction extractColor(color: string): string {\n return color.substring(color.indexOf('#'));\n}\n\nfunction calculateMinimapRange(range: Array<number>, values: Array<number>) {\n const [min, max] = range;\n\n let minIndex = 0;\n let maxIndex = values.length - 1;\n\n values.forEach((item, index) => {\n if (!minIndex && item >= min) {\n minIndex = index;\n }\n\n if (!maxIndex && item >= max) {\n maxIndex = index;\n }\n });\n\n const begin = Math.max(0, minIndex / (values.length - 1));\n const end = Math.min(1, maxIndex / (values.length - 1));\n\n return { minimapRange: { begin, end }, labelFromIndex: minIndex, labelToIndex: maxIndex };\n}\n\nfunction buildStatisticsOverview({ current, previous }: GramJs.StatsAbsValueAndPrev): StatisticsOverviewItem {\n const change = current - previous;\n\n return {\n current,\n change,\n ...(previous && { percentage: (change ? ((Math.abs(change) / previous) * 100) : 0).toFixed(2) }),\n };\n}\n\nfunction buildStatisticsPercentage(data: GramJs.StatsPercentValue): StatisticsOverviewPercentage {\n return {\n percentage: ((data.part / data.total) * 100).toFixed(2),\n };\n}\n\nfunction getOverviewPeriod(data: GramJs.StatsDateRangeDays): StatisticsOverviewPeriod {\n return {\n maxDate: data.maxDate,\n minDate: data.minDate,\n };\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\n\nimport type {\n ApiChat, ApiChannelStatistics, ApiGroupStatistics, ApiMessageStatistics, ApiMessagePublicForward, StatisticsGraph,\n} from '../../types';\n\nimport { invokeRequest } from './client';\nimport { addEntitiesWithPhotosToLocalDb } from '../helpers';\nimport { buildInputEntity } from '../gramjsBuilders';\nimport {\n buildChannelStatistics, buildGroupStatistics, buildMessageStatistics, buildMessagePublicForwards, buildGraph,\n} from '../apiBuilders/statistics';\n\nexport async function fetchChannelStatistics({\n chat,\n}: { chat: ApiChat }): Promise<ApiChannelStatistics | undefined> {\n const result = await invokeRequest(new GramJs.stats.GetBroadcastStats({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n }), undefined, undefined, undefined, chat.fullInfo!.statisticsDcId);\n\n if (!result) {\n return undefined;\n }\n\n return buildChannelStatistics(result);\n}\n\nexport async function fetchGroupStatistics({\n chat,\n}: { chat: ApiChat }): Promise<ApiGroupStatistics | undefined> {\n const result = await invokeRequest(new GramJs.stats.GetMegagroupStats({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n }), undefined, undefined, undefined, chat.fullInfo!.statisticsDcId);\n\n if (!result) {\n return undefined;\n }\n\n return buildGroupStatistics(result);\n}\n\nexport async function fetchMessageStatistics({\n chat,\n messageId,\n}: {\n chat: ApiChat;\n messageId: number;\n}): Promise<ApiMessageStatistics | undefined> {\n const result = await invokeRequest(new GramJs.stats.GetMessageStats({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n msgId: messageId,\n }), undefined, undefined, undefined, chat.fullInfo!.statisticsDcId);\n\n if (!result) {\n return undefined;\n }\n\n return buildMessageStatistics(result);\n}\n\nexport async function fetchMessagePublicForwards({\n chat,\n messageId,\n dcId,\n}: {\n chat: ApiChat;\n messageId: number;\n dcId?: number;\n}): Promise<ApiMessagePublicForward[] | undefined> {\n const result = await invokeRequest(new GramJs.stats.GetMessagePublicForwards({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n msgId: messageId,\n offsetPeer: new GramJs.InputPeerEmpty(),\n }), undefined, undefined, undefined, dcId);\n\n if (!result) {\n return undefined;\n }\n\n if ('chats' in result) {\n addEntitiesWithPhotosToLocalDb(result.chats);\n }\n\n return buildMessagePublicForwards(result);\n}\n\nexport async function fetchStatisticsAsyncGraph({\n token,\n x,\n isPercentage,\n dcId,\n}: {\n token: string;\n x?: number;\n isPercentage?: boolean;\n dcId?: number;\n}): Promise<StatisticsGraph | undefined> {\n const result = await invokeRequest(new GramJs.stats.LoadAsyncGraph({\n token,\n ...(x && { x: BigInt(x) }),\n }), undefined, undefined, undefined, dcId);\n\n if (!result) {\n return undefined;\n }\n\n return buildGraph(result as GramJs.StatsGraph, isPercentage);\n}\n","import BigInt from 'big-integer';\nimport type bigInt from 'big-integer';\nimport MTProtoState from '../../../lib/gramjs/network/MTProtoState';\nimport Logger from '../../../lib/gramjs/extensions/Logger';\nimport Helpers from '../../../lib/gramjs/Helpers';\nimport AuthKey from '../../../lib/gramjs/crypto/AuthKey';\n\ntype DhConfig = {\n p: number[];\n g: number;\n random: number[];\n};\n\nlet currentPhoneCallState: PhoneCallState | undefined;\n\nclass PhoneCallState {\n private state?: MTProtoState;\n\n private seq = 0;\n\n private gA?: bigInt.BigInteger;\n\n private gB: any;\n\n private p?: bigInt.BigInteger;\n\n private random?: bigInt.BigInteger;\n\n private waitForState: Promise<void>;\n\n private resolveState?: VoidFunction;\n\n constructor(\n private isOutgoing: boolean,\n ) {\n this.waitForState = new Promise<void>((resolve) => {\n this.resolveState = resolve;\n });\n }\n\n async requestCall({ p, g, random }: DhConfig) {\n const pBN = Helpers.readBigIntFromBuffer(Buffer.from(p), false);\n const randomBN = Helpers.readBigIntFromBuffer(Buffer.from(random), false);\n\n const gA = Helpers.modExp(BigInt(g), randomBN, pBN);\n\n this.gA = gA;\n this.p = pBN;\n this.random = randomBN;\n\n const gAHash: Buffer = await Helpers.sha256(Helpers.getByteArray(gA));\n return Array.from(gAHash);\n }\n\n acceptCall({ p, g, random }: DhConfig) {\n const pLast = Helpers.readBigIntFromBuffer(p, false);\n const randomLast = Helpers.readBigIntFromBuffer(random, false);\n\n const gB = Helpers.modExp(BigInt(g), randomLast, pLast);\n this.gB = gB;\n this.p = pLast;\n this.random = randomLast;\n\n return Array.from(Helpers.getByteArray(gB));\n }\n\n async confirmCall(gAOrB: number[], emojiData: Uint16Array, emojiOffsets: number[]) {\n if (this.isOutgoing) {\n this.gB = Helpers.readBigIntFromBuffer(Buffer.from(gAOrB), false);\n } else {\n this.gA = Helpers.readBigIntFromBuffer(Buffer.from(gAOrB), false);\n }\n const authKey = Helpers.modExp(\n !this.isOutgoing ? this.gA : this.gB,\n this.random,\n this.p,\n );\n const fingerprint: Buffer = await Helpers.sha1(Helpers.getByteArray(authKey));\n const keyFingerprint = Helpers.readBigIntFromBuffer(fingerprint.slice(-8).reverse(), false);\n\n const emojis = await generateEmojiFingerprint(\n Helpers.getByteArray(authKey),\n Helpers.getByteArray(this.gA),\n emojiData,\n emojiOffsets,\n );\n\n const key = new AuthKey();\n await key.setKey(Helpers.getByteArray(authKey));\n this.state = new MTProtoState(key, new Logger(), true, this.isOutgoing);\n this.resolveState!();\n\n return { gA: Array.from(Helpers.getByteArray(this.gA)), keyFingerprint: keyFingerprint.toString(), emojis };\n }\n\n async encode(data: string) {\n if (!this.state) return undefined;\n\n const seqArray = new Uint32Array(1);\n seqArray[0] = this.seq++;\n const encodedData = await this.state.encryptMessageData(\n Buffer.concat([Helpers.convertToLittle(seqArray), Buffer.from(data)]),\n );\n return Array.from(encodedData);\n }\n\n async decode(data: number[]): Promise<any> {\n if (!this.state) {\n return this.waitForState.then(() => {\n return this.decode(data);\n });\n }\n\n const message = await this.state.decryptMessageData(Buffer.from(data));\n\n return JSON.parse(message.toString());\n }\n}\n\n// https://github.com/TelegramV/App/blob/ead52320975362139cabad18cf8346f98c349a22/src/js/MTProto/Calls/Internal.js#L72\nfunction computeEmojiIndex(bytes: Uint8Array) {\n return ((BigInt(bytes[0]).and(0x7F)).shiftLeft(56))\n .or((BigInt(bytes[1]).shiftLeft(48)))\n .or((BigInt(bytes[2]).shiftLeft(40)))\n .or((BigInt(bytes[3]).shiftLeft(32)))\n .or((BigInt(bytes[4]).shiftLeft(24)))\n .or((BigInt(bytes[5]).shiftLeft(16)))\n .or((BigInt(bytes[6]).shiftLeft(8)))\n .or((BigInt(bytes[7])));\n}\n\nexport async function generateEmojiFingerprint(\n authKey: Uint8Array, gA: Uint8Array, emojiData: Uint16Array, emojiOffsets: number[],\n) {\n const hash = await Helpers.sha256(Buffer.concat([new Uint8Array(authKey), new Uint8Array(gA)]));\n const result = [];\n const emojiCount = emojiOffsets.length - 1;\n const kPartSize = 8;\n for (let partOffset = 0; partOffset !== hash.byteLength; partOffset += kPartSize) {\n const value = computeEmojiIndex(hash.subarray(partOffset, partOffset + kPartSize));\n const index = value.modPow(1, emojiCount).toJSNumber();\n const offset = emojiOffsets[index];\n const size = emojiOffsets[index + 1] - offset;\n result.push(String.fromCharCode(...emojiData.subarray(offset, offset + size)));\n }\n return result.join('');\n}\n\nexport function createPhoneCallState(params: ConstructorParameters<typeof PhoneCallState>) {\n currentPhoneCallState = new PhoneCallState(...params);\n}\n\nexport function destroyPhoneCallState() {\n currentPhoneCallState = undefined;\n}\n\ntype FunctionPropertyOf<T> = {\n [P in keyof T]: T[P] extends Function\n ? P\n : never\n}[keyof T];\n\ntype ParamsOf<T extends FunctionPropertyOf<PhoneCallState>> = Parameters<PhoneCallState[T]>;\ntype ReturnTypeOf<T extends FunctionPropertyOf<PhoneCallState>> = ReturnType<PhoneCallState[T]>;\n\nexport function encodePhoneCallData(params: ParamsOf<'encode'>): ReturnTypeOf<'encode'> {\n return currentPhoneCallState!.encode(...params);\n}\n\nexport function decodePhoneCallData(params: ParamsOf<'decode'>): ReturnTypeOf<'decode'> {\n return currentPhoneCallState!.decode(...params);\n}\n\nexport function confirmPhoneCall(params: ParamsOf<'confirmCall'>): ReturnTypeOf<'confirmCall'> {\n return currentPhoneCallState!.confirmCall(...params);\n}\n\nexport function acceptPhoneCall(params: ParamsOf<'acceptCall'>): ReturnTypeOf<'acceptCall'> {\n return currentPhoneCallState!.acceptCall(...params);\n}\n\nexport function requestPhoneCall(params: ParamsOf<'requestCall'>): ReturnTypeOf<'requestCall'> {\n return currentPhoneCallState!.requestCall(...params);\n}\n","import type {\n OnApiUpdate,\n ApiInitialArgs,\n ApiUpdate,\n ApiOnProgress,\n} from '../types';\nimport type { 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 initBots } from './methods/bots';\nimport { init as initCalls } from './methods/calls';\nimport { init as initPayments } from './methods/payments';\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 initBots(handleUpdate);\n initCalls(handleUpdate);\n initPayments(handleUpdate);\n\n await initClient(handleUpdate, initialArgs);\n}\n\nexport function callApi<T extends keyof Methods>(fnName: T, ...args: MethodArgs<T>): MethodResponse<T> {\n // @ts-ignore\n return methods[fnName](...args) as MethodResponse<T>;\n}\n\nexport function cancelApiProgress(progressCallback: ApiOnProgress) {\n progressCallback.isCanceled = true;\n}\n\nconst flushUpdatesOnTickEnd = throttleWithTickEnd(flushUpdates);\n\nlet flushUpdatesThrottled: typeof flushUpdatesOnTickEnd | undefined;\nlet currentThrottleId: number | undefined;\n\nlet pendingUpdates: ApiUpdate[] | undefined;\n\nfunction handleUpdate(update: ApiUpdate) {\n if (!pendingUpdates) {\n pendingUpdates = [update];\n } else {\n pendingUpdates.push(update);\n }\n\n if (!flushUpdatesThrottled || API_THROTTLE_RESET_UPDATES.has(update['@type'])) {\n flushUpdatesThrottled = throttle(flushUpdatesOnTickEnd, API_UPDATE_THROTTLE, true);\n currentThrottleId = Math.random();\n }\n\n flushUpdatesThrottled(currentThrottleId!);\n}\n\nfunction flushUpdates(throttleId: number) {\n if (!pendingUpdates || throttleId !== currentThrottleId) {\n return;\n }\n\n const currentUpdates = pendingUpdates!;\n pendingUpdates = undefined;\n currentUpdates.forEach(onUpdate);\n}\n","import type { ApiOnProgress, ApiUpdate } from '../../types';\nimport type { OriginMessageEvent, WorkerMessageData } from './types';\n\nimport { DEBUG } from '../../../config';\nimport { initApi, callApi, cancelApiProgress } from '../provider';\n\ndeclare const self: WorkerGlobalScope;\n\nhandleErrors();\n\nconst callbackState = new Map<string, ApiOnProgress>();\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH LOAD WORKER');\n}\n\nonmessage = async (message: OriginMessageEvent) => {\n const { data } = message;\n\n switch (data.type) {\n case 'initApi': {\n await initApi(onUpdate, data.args[0]);\n break;\n }\n case 'callMethod': {\n const { messageId, name, args } = data;\n try {\n if (messageId) {\n const callback = (...callbackArgs: any[]) => {\n const lastArg = callbackArgs[callbackArgs.length - 1];\n\n sendToOrigin({\n type: 'methodCallback',\n messageId,\n callbackArgs,\n }, lastArg instanceof ArrayBuffer ? lastArg : undefined);\n };\n\n callbackState.set(messageId, callback);\n\n args.push(callback as never);\n }\n\n const response = await callApi(name, ...args);\n\n if (DEBUG && typeof response === 'object' && 'CONSTRUCTOR_ID' in response) {\n // eslint-disable-next-line no-console\n console.error(`[GramJs/worker] \\`${name}\\`: Unexpected response \\`${(response as any).className}\\``);\n }\n\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: any) {\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 * 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 * 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 * Gets the arbitrary-length byte array corresponding to the given integer\n * @param integer {any}\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) => {\n setTimeout(resolve, ms);\n});\n\n/**\n * Helper to export two buffers of same length\n * @returns {Buffer}\n */\n\nfunction bufferXor(a, b) {\n const res = [];\n for (let i = 0; i < a.length; i++) {\n res.push(a[i] ^ b[i]);\n }\n return Buffer.from(res);\n}\n\n/**\n * Checks if the obj is an array\n * @param obj\n * @returns {boolean}\n */\n/*\nCONTEST\nwe do'nt support array requests anyway\nfunction isArrayLike(obj) {\n if (!obj) return false\n const l = obj.length\n if (typeof l != 'number' || l < 0) return false\n if (Math.floor(l) !== l) return false\n // fast check\n if (l > 0 && !(l - 1 in obj)) return false\n // more complete check (optional)\n for (let i = 0; i < l; ++i) {\n if (!(i in obj)) return false\n }\n return true\n}\n*/\n\n// Taken from https://stackoverflow.com/questions/18638900/javascript-crc32/18639999#18639999\nfunction makeCRCTable() {\n let c;\n const crcTable = [];\n for (let n = 0; n < 256; n++) {\n c = n;\n for (let k = 0; k < 8; k++) {\n c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));\n }\n crcTable[n] = c;\n }\n return crcTable;\n}\n\nlet crcTable;\n\nfunction crc32(buf) {\n if (!crcTable) {\n crcTable = makeCRCTable();\n }\n if (!Buffer.isBuffer(buf)) {\n buf = Buffer.from(buf);\n }\n let crc = -1;\n\n for (let index = 0; index < buf.length; index++) {\n const byte = buf[index];\n crc = crcTable[(crc ^ byte) & 0xff] ^ (crc >>> 8);\n }\n return (crc ^ (-1)) >>> 0;\n}\n\n/**\n * Creates a deferred object\n * @return {Deferred}\n */\nfunction createDeferred() {\n let resolve;\n const promise = new Promise((_resolve) => {\n resolve = _resolve;\n });\n\n return {\n promise,\n resolve,\n };\n}\n\nmodule.exports = {\n readBigIntFromBuffer,\n readBufferFromBigInt,\n generateRandomLong,\n mod,\n crc32,\n generateRandomBytes,\n // calcKey,\n generateKeyDataFromNonce,\n sha1,\n sha256,\n bigIntMod,\n modExp,\n getRandomInt,\n sleep,\n getByteArray,\n // isArrayLike,\n toSignedLittleBuffer,\n convertToLittle,\n bufferXor,\n createDeferred,\n};\n","const BigInt = require('big-integer');\nconst { constructors } = require('./tl');\nconst {\n readBigIntFromBuffer,\n readBufferFromBigInt,\n sha256,\n bigIntMod,\n modExp,\n generateRandomBytes,\n} = require('./Helpers');\nconst crypto = require('./crypto/crypto');\n\nconst SIZE_FOR_HASH = 256;\n\n/**\n *\n *\n * @param prime{BigInteger}\n * @param g{BigInteger}\n */\n\n/*\nWe don't support changing passwords yet\nfunction checkPrimeAndGoodCheck(prime, g) {\n console.error('Unsupported function `checkPrimeAndGoodCheck` call. Arguments:', prime, g)\n\n const goodPrimeBitsCount = 2048\n if (prime < 0 || prime.bitLength() !== goodPrimeBitsCount) {\n throw new Error(`bad prime count ${prime.bitLength()},expected ${goodPrimeBitsCount}`)\n }\n // TODO this is kinda slow\n if (Factorizator.factorize(prime)[0] !== 1) {\n throw new Error('give \"prime\" is not prime')\n }\n if (g.eq(BigInt(2))) {\n if ((prime.remainder(BigInt(8))).neq(BigInt(7))) {\n throw new Error(`bad g ${g}, mod8 ${prime % 8}`)\n }\n } else if (g.eq(BigInt(3))) {\n if ((prime.remainder(BigInt(3))).neq(BigInt(2))) {\n throw new Error(`bad g ${g}, mod3 ${prime % 3}`)\n }\n // eslint-disable-next-line no-empty\n } else if (g.eq(BigInt(4))) {\n\n } else if (g.eq(BigInt(5))) {\n if (!([ BigInt(1), BigInt(4) ].includes(prime.remainder(BigInt(5))))) {\n throw new Error(`bad g ${g}, mod8 ${prime % 5}`)\n }\n } else if (g.eq(BigInt(6))) {\n if (!([ BigInt(19), BigInt(23) ].includes(prime.remainder(BigInt(24))))) {\n throw new Error(`bad g ${g}, mod8 ${prime % 24}`)\n }\n } else if (g.eq(BigInt(7))) {\n if (!([ BigInt(3), BigInt(5), BigInt(6) ].includes(prime.remainder(BigInt(7))))) {\n throw new Error(`bad g ${g}, mod8 ${prime % 7}`)\n }\n } else {\n throw new Error(`bad g ${g}`)\n }\n const primeSub1Div2 = (prime.subtract(BigInt(1))).divide(BigInt(2))\n if (Factorizator.factorize(primeSub1Div2)[0] !== 1) {\n throw new Error('(prime - 1) // 2 is not prime')\n }\n}\n*/\n/**\n *\n * @param primeBytes{Buffer}\n * @param g{number}\n */\nfunction checkPrimeAndGood(primeBytes, g) {\n const goodPrime = Buffer.from([\n 0xC7, 0x1C, 0xAE, 0xB9, 0xC6, 0xB1, 0xC9, 0x04, 0x8E, 0x6C, 0x52, 0x2F, 0x70, 0xF1, 0x3F, 0x73,\n 0x98, 0x0D, 0x40, 0x23, 0x8E, 0x3E, 0x21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xA9, 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 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\n// eslint-disable-next-line @typescript-eslint/naming-convention\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 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 downloading files,\n * given an initial file size.\n * @param fileSize\n * @returns {Number}\n */\nfunction getDownloadPartSize(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 if (fileSize <= 4194304000) { // 4000MB\n return 1024;\n }\n\n throw new Error('File size too large');\n}\n\n/**\n * Gets the appropriated part size when uploading files,\n * given an initial file size.\n * @param fileSize\n * @returns {Number}\n */\nfunction getUploadPartSize(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 if (fileSize <= 4194304000) { // 4000MB\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 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 (Boolean(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 getDownloadPartSize,\n getUploadPartSize,\n // getInputLocation,\n strippedPhotoToJpg,\n getDC,\n};\n","module.exports = '0.0.2';\n","import TelegramClient from './TelegramClient';\n// eslint-disable-next-line import/no-named-default\nimport { default as Api } from '../tl/api';\nimport { generateRandomBytes } from '../Helpers';\nimport { computeCheck, computeDigest } from '../Password';\nimport errors from '../errors';\n\nexport interface TwoFaParams {\n isCheckPassword?: boolean;\n currentPassword?: string;\n newPassword?: string;\n hint?: string;\n email?: string;\n emailCodeCallback?: (length: number) => Promise<string>;\n onEmailCodeError?: (err: Error) => void;\n}\n\n/**\n * Changes the 2FA settings of the logged in user.\n Note that this method may be *incredibly* slow depending on the\n prime numbers that must be used during the process to make sure\n that everything is safe.\n\n Has no effect if both current and new password are omitted.\n\n * @param client: The telegram client instance\n * @param isCheckPassword: Must be ``true`` if you want to check the current password\n * @param currentPassword: The current password, to authorize changing to ``new_password``.\n Must be set if changing existing 2FA settings.\n Must **not** be set if 2FA is currently disabled.\n Passing this by itself will remove 2FA (if correct).\n * @param newPassword: The password to set as 2FA.\n If 2FA was already enabled, ``currentPassword`` **must** be set.\n Leaving this blank or `undefined` will remove the password.\n * @param hint: Hint to be displayed by Telegram when it asks for 2FA.\n Must be set when changing or creating a new password.\n Has no effect if ``newPassword`` is not set.\n * @param email: Recovery and verification email. If present, you must also\n set `emailCodeCallback`, else it raises an Error.\n * @param emailCodeCallback: If an email is provided, a callback that returns the code sent\n to it must also be set. This callback may be asynchronous.\n It should return a string with the code. The length of the\n code will be passed to the callback as an input parameter.\n\n If the callback returns an invalid code, it will raise an rpc error with the message\n ``CODE_INVALID``\n\n * @returns Promise<void>\n * @throws this method can throw:\n \"PASSWORD_HASH_INVALID\" if you entered a wrong password (or set it to undefined).\n \"EMAIL_INVALID\" if the entered email is wrong\n \"EMAIL_HASH_EXPIRED\" if the user took too long to verify their email\n */\nexport async function updateTwoFaSettings(\n client: TelegramClient,\n {\n isCheckPassword,\n currentPassword,\n newPassword,\n hint = '',\n email,\n emailCodeCallback,\n onEmailCodeError,\n }: TwoFaParams,\n) {\n if (!newPassword && !currentPassword) {\n throw new Error('Neither `currentPassword` nor `newPassword` is present');\n }\n\n if (email && !(emailCodeCallback && onEmailCodeError)) {\n throw new Error('`email` present without `emailCodeCallback` and `onEmailCodeError`');\n }\n\n const pwd = await client.invoke(new Api.account.GetPassword());\n\n if (!(pwd.newAlgo instanceof Api.PasswordKdfAlgoUnknown)) {\n pwd.newAlgo.salt1 = Buffer.concat([pwd.newAlgo.salt1, generateRandomBytes(32)]);\n }\n if (!pwd.hasPassword && currentPassword) {\n currentPassword = undefined;\n }\n\n const password = currentPassword ? await computeCheck(pwd, currentPassword!) : new Api.InputCheckPasswordEmpty();\n\n if (isCheckPassword) {\n await client.invoke(new Api.auth.CheckPassword({ password }));\n return;\n }\n\n try {\n await client.invoke(new Api.account.UpdatePasswordSettings({\n password,\n newSettings: new Api.account.PasswordInputSettings({\n newAlgo: pwd.newAlgo,\n newPasswordHash: newPassword ? await computeDigest(pwd.newAlgo, newPassword) : Buffer.alloc(0),\n hint,\n email,\n // not explained what it does and it seems to always be set to empty in tdesktop\n newSecureSettings: undefined,\n }),\n }));\n } catch (e) {\n if (e instanceof errors.EmailUnconfirmedError) {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n try {\n const code = await emailCodeCallback!(e.codeLength);\n\n if (!code) {\n throw new Error('Code is empty');\n }\n\n await client.invoke(new Api.account.ConfirmPasswordEmail({ code }));\n break;\n } catch (err: any) {\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 {\n ConnectionTCPObfuscated,\n MTProtoSender,\n UpdateConnectionState,\n} = require('../network');\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\n\n// An unusually long interval is a sign of returning from background mode...\nconst PING_INTERVAL_TO_WAKE_UP = 5000; // 5 sec\n// ... so we send a quick \"wake-up\" ping to confirm than connection was dropped ASAP\nconst PING_WAKE_UP_TIMEOUT = 3000; // 3 sec\n// We also send a warning to the user even a bit more quickly\nconst PING_WAKE_UP_WARNING_TIMEOUT = 1000; // 1 sec\n\nconst PING_DISCONNECT_DELAY = 60000; // 1 min\n\n// All types\nconst sizeTypes = ['u', 'v', 'w', 'y', 'd', 'x', 'c', 'm', 'b', 'a', 's', 'f'];\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._waitingForAuthKey = {};\n this._exportedSenderReleaseTimeouts = {};\n this._additionalDcsDisabled = args.additionalDcsDisabled;\n this._loopStarted = false;\n this._isSwitchingDc = 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<void>}\n */\n async connect() {\n await this._initSession();\n\n if (this._sender === undefined) {\n // only init sender once to avoid multiple loops.\n this._sender = new MTProtoSender(this.session.getAuthKey(), {\n logger: this._log,\n dcId: this.session.dcId,\n retries: this._connectionRetries,\n delay: this._retryDelay,\n autoReconnect: this._autoReconnect,\n connectTimeout: this._timeout,\n authKeyCallback: this._authKeyCallback.bind(this),\n updateCallback: this._handleUpdate.bind(this),\n isMainSender: true,\n });\n }\n // set defaults vars\n this._sender.userDisconnected = false;\n this._sender._user_connected = false;\n this._sender.isReconnecting = 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._isSwitchingDc = 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 let lastPongAt;\n\n while (!this._destroyed) {\n await Helpers.sleep(PING_INTERVAL);\n if (this._sender.isReconnecting || this._isSwitchingDc) {\n lastPongAt = undefined;\n continue;\n }\n\n try {\n const ping = () => {\n return this._sender.send(new requests.PingDelayDisconnect({\n pingId: Helpers.getRandomInt(Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER),\n disconnectDelay: PING_DISCONNECT_DELAY,\n }));\n };\n\n const pingAt = Date.now();\n const lastInterval = lastPongAt ? pingAt - lastPongAt : undefined;\n\n if (!lastInterval || lastInterval < PING_INTERVAL_TO_WAKE_UP) {\n await attempts(() => timeout(ping, PING_TIMEOUT), PING_FAIL_ATTEMPTS, PING_FAIL_INTERVAL);\n } else {\n let wakeUpWarningTimeout = setTimeout(() => {\n this._handleUpdate(new UpdateConnectionState(UpdateConnectionState.disconnected));\n wakeUpWarningTimeout = undefined;\n }, PING_WAKE_UP_WARNING_TIMEOUT);\n\n await timeout(ping, PING_WAKE_UP_TIMEOUT);\n\n if (wakeUpWarningTimeout) {\n clearTimeout(wakeUpWarningTimeout);\n wakeUpWarningTimeout = undefined;\n }\n\n this._handleUpdate(new UpdateConnectionState(UpdateConnectionState.connected));\n }\n\n lastPongAt = Date.now();\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n\n lastPongAt = undefined;\n\n if (this._sender.isReconnecting || this._isSwitchingDc) {\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 lastPongAt = undefined;\n }\n }\n await this.disconnect();\n }\n\n /**\n * Disconnects from the Telegram server\n * @returns {Promise<void>}\n */\n async disconnect() {\n if (this._sender) {\n await this._sender.disconnect();\n }\n\n await Promise.all(\n Object.values(this._exportedSenderPromises)\n .map((promises) => {\n return Object.values(promises).map((promise) => {\n return promise && promise.then((sender) => {\n if (sender) {\n return sender.disconnect();\n }\n return undefined;\n });\n });\n }).flat(),\n );\n\n this._exportedSenderPromises = {};\n this._waitingForAuthKey = {};\n }\n\n /**\n * Disconnects all senders and removes all handlers\n * @returns {Promise<void>}\n */\n async destroy() {\n this._destroyed = true;\n\n try {\n await this.disconnect();\n } catch (err) {\n // Do nothing\n }\n\n this.session.delete();\n this._eventBuilders = [];\n }\n\n async _switchDC(newDc) {\n this._log.info(`Reconnecting to new data center ${newDc}`);\n const DC = utils.getDC(newDc);\n this.session.setDC(newDc, DC.ipAddress, DC.port);\n // authKey's are associated with a server, which has now changed\n // so it's not valid anymore. Set to None to force recreating it.\n await this._sender.authKey.setKey(undefined);\n this.session.setAuthKey(undefined);\n this._isSwitchingDc = 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, index) {\n if (this.session.dcId !== dcId) {\n this.session.setAuthKey(undefined, dcId);\n }\n const sender = await this._exportedSenderPromises[dcId][index];\n delete this._exportedSenderPromises[dcId][index];\n await sender.disconnect();\n }\n\n async _connectSender(sender, dcId, isPremium = false) {\n // if we don't already have an auth key we want to use normal DCs not -1\n let hasAuthKey = Boolean(sender.authKey.getKey());\n let firstConnectResolver;\n\n if (!hasAuthKey) {\n if (this._waitingForAuthKey[dcId]) {\n await this._waitingForAuthKey[dcId];\n\n const authKey = this.session.getAuthKey(dcId);\n await sender.authKey.setKey(authKey.getKey());\n hasAuthKey = Boolean(sender.authKey.getKey());\n } else {\n this._waitingForAuthKey[dcId] = new Promise((resolve) => {\n firstConnectResolver = resolve;\n });\n }\n }\n\n const dc = utils.getDC(dcId, hasAuthKey);\n\n // eslint-disable-next-line no-constant-condition\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 // Premium DCs are not stable for obtaining auth keys, so need to we first connect to regular ones\n hasAuthKey ? isPremium : false,\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 if (firstConnectResolver) {\n firstConnectResolver();\n delete this._waitingForAuthKey[dcId];\n }\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, index, isPremium) {\n if (this._additionalDcsDisabled) {\n return undefined;\n }\n\n const i = index || 0;\n\n if (!this._exportedSenderPromises[dcId]) this._exportedSenderPromises[dcId] = {};\n\n if (!this._exportedSenderPromises[dcId][i] || shouldReconnect) {\n this._exportedSenderPromises[dcId][i] = this._connectSender(\n existingSender || this._createExportedSender(dcId, i),\n dcId,\n isPremium,\n );\n }\n\n let sender;\n try {\n sender = await this._exportedSenderPromises[dcId][i];\n\n if (!sender.isConnected()) {\n if (sender.isConnecting) {\n await Helpers.sleep(EXPORTED_SENDER_RECONNECT_TIMEOUT);\n return this._borrowExportedSender(dcId, false, sender, i, isPremium);\n } else {\n return this._borrowExportedSender(dcId, true, sender, i, isPremium);\n }\n }\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(err);\n\n return this._borrowExportedSender(dcId, true, undefined, i, isPremium);\n }\n\n if (!this._exportedSenderReleaseTimeouts[dcId]) this._exportedSenderReleaseTimeouts[dcId] = {};\n if (this._exportedSenderReleaseTimeouts[dcId][i]) {\n clearTimeout(this._exportedSenderReleaseTimeouts[dcId][i]);\n this._exportedSenderReleaseTimeouts[dcId][i] = undefined;\n }\n\n this._exportedSenderReleaseTimeouts[dcId][i] = setTimeout(() => {\n this._exportedSenderReleaseTimeouts[dcId][i] = undefined;\n sender.disconnect();\n }, EXPORTED_SENDER_RELEASE_TIMEOUT);\n\n return sender;\n }\n\n _createExportedSender(dcId, index) {\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(dcId, index),\n });\n }\n\n getSender(dcId, index, isPremium) {\n return dcId\n ? this._borrowExportedSender(dcId, undefined, undefined, index, isPremium)\n : Promise.resolve(this._sender);\n }\n\n // end region\n\n // download region\n\n /**\n * Complete flow to download a file.\n * @param inputLocation {constructors.InputFileLocation}\n * @param [args[partSizeKb] {number}]\n * @param [args[fileSize] {number}]\n * @param [args[progressCallback] {Function}]\n * @param [args[start] {number}]\n * @param [args[end] {number}]\n * @param [args[dcId] {number}]\n * @param [args[workers] {number}]\n * @returns {Promise<Buffer>}\n */\n downloadFile(inputLocation, args = {}) {\n return downloadFile(this, inputLocation, args);\n }\n\n downloadMedia(messageOrMedia, args) {\n let media;\n if (messageOrMedia instanceof constructors.Message) {\n media = messageOrMedia.media;\n } else {\n media = messageOrMedia;\n }\n if (typeof media === 'string') {\n throw new Error('not implemented');\n }\n\n if (media instanceof constructors.MessageMediaWebPage) {\n if (media.webpage instanceof constructors.WebPage) {\n media = media.webpage.document || media.webpage.photo;\n }\n }\n if (media instanceof constructors.MessageMediaPhoto || media instanceof constructors.Photo) {\n return this._downloadPhoto(media, args);\n } else if (media instanceof constructors.MessageMediaDocument || media instanceof constructors.Document) {\n return this._downloadDocument(media, args);\n } else if (media instanceof constructors.MessageMediaContact) {\n return this._downloadContact(media, args);\n } else if (media instanceof constructors.WebDocument || media instanceof constructors.WebDocumentNoProxy) {\n return this._downloadWebDocument(media, args);\n }\n return undefined;\n }\n\n downloadProfilePhoto(entity, isBig = false) {\n // ('User', 'Chat', 'UserFull', 'ChatFull')\n const ENTITIES = [0x2da17977, 0xc5af5d94, 0x1f4661b9, 0xd49a2697];\n // ('InputPeer', 'InputUser', 'InputChannel')\n // const INPUTS = [0xc91c90b6, 0xe669bf46, 0x40f202fd]\n // Todo account for input methods\n const sizeType = isBig ? 'x' : 'm';\n let photo;\n if (!(ENTITIES.includes(entity.SUBCLASS_OF_ID))) {\n photo = entity;\n } else {\n if (!entity.photo) {\n // Special case: may be a ChatFull with photo:Photo\n if (!entity.chatPhoto) {\n return undefined;\n }\n\n return this._downloadPhoto(\n entity.chatPhoto, { sizeType },\n );\n }\n photo = entity.photo;\n }\n\n let dcId;\n let loc;\n if (photo instanceof constructors.UserProfilePhoto || photo instanceof constructors.ChatPhoto) {\n dcId = photo.dcId;\n loc = new constructors.InputPeerPhotoFileLocation({\n peer: utils.getInputPeer(entity),\n photoId: photo.photoId,\n big: isBig,\n });\n } else {\n // It doesn't make any sense to check if `photo` can be used\n // as input location, because then this method would be able\n // to \"download the profile photo of a message\", i.e. its\n // media which should be done with `download_media` instead.\n return undefined;\n }\n return this.downloadFile(loc, {\n dcId,\n });\n }\n\n downloadStickerSetThumb(stickerSet) {\n if (!stickerSet.thumbs || !stickerSet.thumbs.length) {\n return undefined;\n }\n\n const { thumbVersion } = stickerSet;\n return this.downloadFile(\n new constructors.InputStickerSetThumb({\n stickerset: new constructors.InputStickerSetID({\n id: stickerSet.id,\n accessHash: stickerSet.accessHash,\n }),\n thumbVersion,\n }),\n { dcId: stickerSet.thumbDcId },\n );\n }\n\n _pickFileSize(sizes, sizeType) {\n if (!sizeType || !sizes || !sizes.length) {\n return undefined;\n }\n const indexOfSize = sizeTypes.indexOf(sizeType);\n let size;\n for (let i = indexOfSize; i < sizeTypes.length; i++) {\n size = sizes.find((s) => s.type === sizeTypes[i]);\n if (size) {\n return size;\n }\n }\n return undefined;\n }\n\n _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 isVideoSize = args.sizeType === 'u' || args.sizeType === 'v';\n const size = this._pickFileSize(isVideoSize\n ? [...photo.videoSizes, ...photo.sizes]\n : 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 || Math.max(...(size.sizes || [])),\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.videoThumbs || []),\n ...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.toJSNumber(),\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 async _downloadWebDocument(media) {\n if (media.url && !('accessHash' in media)) {\n const arrayBuff = await fetch(media.url).then((res) => res.arrayBuffer());\n return Buffer.from(arrayBuff);\n }\n\n try {\n const buff = [];\n let offset = 0;\n // eslint-disable-next-line no-constant-condition\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 async downloadStaticMap(accessHash, long, lat, w, h, zoom, scale, accuracyRadius) {\n try {\n const buff = [];\n let offset = 0;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n try {\n const downloaded = new requests.upload.GetWebFile({\n location: new constructors.InputWebFileGeoPointLocation({\n geoPoint: new constructors.InputGeoPoint({\n lat,\n long,\n accuracyRadius,\n }),\n accessHash,\n w,\n h,\n zoom,\n scale,\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 } catch (err) {\n if (err instanceof errors.FloodWaitError) {\n // eslint-disable-next-line no-console\n console.warn(`getWebFile: sleeping for ${err.seconds}s on flood wait`);\n await sleep(err.seconds * 1000);\n continue;\n }\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 * @param dcId Optional dcId to use when sending the request\n * @returns {Promise}\n */\n\n async invoke(request, dcId) {\n if (request.classType !== 'request') {\n throw new Error('You can only invoke MTProtoRequests');\n }\n\n const sender = dcId === undefined ? this._sender : await this.getSender(dcId);\n this._lastRequest = new Date().getTime();\n let attempt = 0;\n for (attempt = 0; attempt < this._requestRetries; attempt++) {\n const promise = 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 setIsPremium(isPremium) {\n this.isPremium = isPremium;\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, authParams.shouldThrowIfUnauthorized)) {\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<void>}\n * @private\n */\n /* CONTEST\n async _getEntityFromString(string) {\n const phone = utils.parsePhone(string)\n if (phone) {\n try {\n for (const user of (await this.invoke(\n new requests.contacts.GetContacts(0))).users) {\n if (user.phone === phone) {\n return user\n }\n }\n } catch (e) {\n if (e.message === 'BOT_METHOD_INVALID') {\n throw new Error('Cannot get entity by phone number as a ' +\n 'bot (try using integer IDs, not strings)')\n }\n throw e\n }\n } else if (['me', 'this'].includes(string.toLowerCase())) {\n return this.getMe()\n } else {\n const { username, isJoinChat } = utils.parseUsername(string)\n if (isJoinChat) {\n const invite = await this.invoke(new requests.messages.CheckChatInvite({\n 'hash': username,\n }))\n if (invite instanceof constructors.ChatInvite) {\n throw new Error('Cannot get entity from a channel (or group) ' +\n 'that you are not part of. Join the group and retry',\n )\n } else if (invite instanceof constructors.ChatInviteAlready) {\n return invite.chat\n }\n } else if (username) {\n try {\n const result = await this.invoke(\n new requests.contacts.ResolveUsername(username))\n const pid = utils.getPeerId(result.peer, false)\n if (result.peer instanceof constructors.PeerUser) {\n for (const x of result.users) {\n if (x.id === pid) {\n return x\n }\n }\n } else {\n for (const x of result.chats) {\n if (x.id === pid) {\n return x\n }\n }\n }\n } catch (e) {\n if (e.message === 'USERNAME_NOT_OCCUPIED') {\n throw new Error(`No user has \"${username}\" as username`)\n }\n throw e\n }\n }\n }\n throw new Error(`Cannot find any entity corresponding to \"${string}\"`)\n }\n */\n // endregion\n\n // 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(cb, ms) {\n let isResolved = false;\n\n return Promise.race([\n cb(),\n Helpers.sleep(ms).then(() => (isResolved ? undefined : Promise.reject(new Error('TIMEOUT')))),\n ]).finally(() => {\n isResolved = true;\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 @typescript-eslint/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","import Api from '../tl/api';\nimport TelegramClient from './TelegramClient';\nimport utils from '../Utils';\nimport { sleep } from '../Helpers';\nimport { computeCheck as computePasswordSrpCheck } from '../Password';\n\nexport interface UserAuthParams {\n phoneNumber: string | (() => Promise<string>);\n phoneCode: (isCodeViaApp?: boolean) => Promise<string>;\n password: (hint?: string) => Promise<string>;\n firstAndLastNames: () => Promise<[string, string?]>;\n qrCode: (qrCode: { token: Buffer; expires: number }) => Promise<void>;\n onError: (err: Error) => void;\n forceSMS?: boolean;\n initialMethod?: 'phoneNumber' | 'qrCode';\n shouldThrowIfUnauthorized?: boolean;\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, shouldThrow = false) {\n try {\n await client.invoke(new Api.updates.GetState());\n return true;\n } catch (e: any) {\n if (e.message === 'Disconnect' || shouldThrow) throw e;\n return false;\n }\n}\n\nasync function signInUser(\n client: TelegramClient, apiCredentials: ApiCredentials, authParams: UserAuthParams,\n): Promise<Api.TypeUser> {\n let phoneNumber;\n let phoneCodeHash;\n let isCodeViaApp = false;\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n try {\n if (typeof authParams.phoneNumber === 'function') {\n try {\n phoneNumber = await authParams.phoneNumber();\n } catch (err: any) {\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: any) {\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: any) {\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: any) {\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: any) {\n authParams.onError(err);\n }\n }\n }\n\n authParams.onError(new Error('Auth failed'));\n return signInUser(client, apiCredentials, authParams);\n}\n\nasync function signInUserWithQrCode(\n client: TelegramClient, apiCredentials: ApiCredentials, authParams: UserAuthParams,\n): Promise<Api.TypeUser> {\n let isScanningComplete = false;\n\n const inputPromise = (async () => {\n // eslint-disable-next-line no-constant-condition\n while (1) {\n if (isScanningComplete) {\n break;\n }\n\n const result = await client.invoke(new Api.auth.ExportLoginToken({\n apiId: Number(process.env.TELEGRAM_T_API_ID),\n apiHash: process.env.TELEGRAM_T_API_HASH,\n exceptIds: [],\n }));\n if (!(result instanceof Api.auth.LoginToken)) {\n throw new Error('Unexpected');\n }\n\n const { token, expires } = result;\n\n await Promise.race([\n authParams.qrCode({ token, expires }),\n sleep(QR_CODE_TIMEOUT),\n ]);\n }\n })();\n\n const updatePromise = new Promise<void>((resolve) => {\n client.addEventHandler((update: Api.TypeUpdate) => {\n if (update instanceof Api.UpdateLoginToken) {\n resolve();\n }\n }, { build: (update: object) => update });\n });\n\n try {\n // Either we receive an update that QR is successfully scanned,\n // or we receive a rejection caused by user going back to the regular auth form\n await Promise.race([updatePromise, inputPromise]);\n } catch (err: any) {\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: any) {\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 @typescript-eslint/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: any) {\n if (err.message === 'AUTH_RESTART') {\n return sendCode(client, apiCredentials, phoneNumber, forceSMS);\n } else {\n throw err;\n }\n }\n}\n\nasync function signInWithPassword(\n client: TelegramClient, apiCredentials: ApiCredentials, authParams: UserAuthParams,\n): Promise<Api.TypeUser> {\n // eslint-disable-next-line no-constant-condition\n while (1) {\n try {\n const passwordSrpResult = await client.invoke(new Api.account.GetPassword());\n const password = await authParams.password(passwordSrpResult.hint);\n if (!password) {\n throw new Error('Password is empty');\n }\n\n const passwordSrpCheck = await computePasswordSrpCheck(passwordSrpResult, password);\n const { user } = await client.invoke(new Api.auth.CheckPassword({\n password: passwordSrpCheck,\n })) as Api.auth.Authorization;\n\n return user;\n } catch (err: any) {\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","import BigInt from 'big-integer';\nimport Api from '../tl/api';\nimport type TelegramClient from './TelegramClient';\nimport { sleep, createDeferred } from '../Helpers';\nimport { getDownloadPartSize } from '../Utils';\nimport errors from '../errors';\n\ninterface OnProgress {\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?: OnProgress;\n}\n\ninterface Deferred {\n promise: Promise<any>;\n resolve: (value?: any) => void;\n}\n\n// Chunk sizes for `upload.getFile` must be multiple of the smallest size\nconst MIN_CHUNK_SIZE = 4096;\nconst DEFAULT_CHUNK_SIZE = 64; // kb\nconst ONE_MB = 1024 * 1024;\nconst DISCONNECT_SLEEP = 1000;\n\n// when the sender requests hangs for 60 second we will reimport\nconst SENDER_TIMEOUT = 60 * 1000;\n// Telegram may have server issues so we try several times\nconst SENDER_RETRIES = 5;\n\nclass Foreman {\n private deferreds: Deferred[] = [];\n\n activeWorkers = 0;\n\n constructor(private maxWorkers: number) {\n }\n\n requestWorker() {\n if (this.activeWorkers === this.maxWorkers) {\n const deferred = createDeferred();\n this.deferreds.push(deferred);\n return deferred.promise;\n } else {\n this.activeWorkers++;\n }\n\n return Promise.resolve();\n }\n\n releaseWorker() {\n if (this.deferreds.length && (this.activeWorkers === this.maxWorkers)) {\n const deferred = this.deferreds.shift()!;\n deferred.resolve();\n } else {\n this.activeWorkers--;\n }\n }\n}\n\nclass FileView {\n private type: 'memory' | 'opfs';\n\n private size?: number;\n\n private buffer?: Buffer;\n\n private largeFile?: FileSystemFileHandle;\n\n private largeFileAccessHandle?: FileSystemSyncAccessHandle;\n\n constructor(size?: number) {\n this.size = size;\n // eslint-disable-next-line no-restricted-globals\n this.type = (size && size > (self as any).maxBufferSize) ? 'opfs' : 'memory';\n }\n\n async init() {\n if (this.type === 'opfs') {\n if (!FileSystemFileHandle?.prototype.createSyncAccessHandle) {\n throw new Error('`createSyncAccessHandle` is not available. Cannot download files larger than 2GB.');\n }\n const directory = await navigator.storage.getDirectory();\n const downloadsFolder = await directory.getDirectoryHandle('downloads', { create: true });\n this.largeFile = await downloadsFolder.getFileHandle(Math.random().toString(), { create: true });\n this.largeFileAccessHandle = await this.largeFile.createSyncAccessHandle();\n } else {\n this.buffer = this.size ? Buffer.alloc(this.size) : Buffer.alloc(0);\n }\n }\n\n write(data: Uint8Array, offset: number) {\n if (this.type === 'opfs') {\n this.largeFileAccessHandle!.write(data, { at: offset });\n } else if (this.size) {\n for (let i = 0; i < data.length; i++) {\n if (offset + i >= this.buffer!.length) return;\n this.buffer!.writeUInt8(data[i], offset + i);\n }\n } else {\n this.buffer = Buffer.concat([this.buffer!, data]);\n }\n }\n\n getData(): Promise<Buffer | File> {\n if (this.type === 'opfs') {\n return this.largeFile!.getFile();\n } else {\n return Promise.resolve(this.buffer!);\n }\n }\n}\n\nexport async function downloadFile(\n client: TelegramClient,\n inputLocation: Api.InputFileLocation,\n fileParams: DownloadFileParams,\n) {\n const { dcId } = fileParams;\n for (let i = 0; i < SENDER_RETRIES; i++) {\n try {\n return await downloadFile2(client, inputLocation, fileParams);\n } catch (err: any) {\n if (i === SENDER_RETRIES - 1 || !err.message.startsWith('SESSION_REVOKED')) {\n throw err;\n }\n await client._cleanupExportedSender(dcId);\n }\n }\n\n return undefined;\n}\n\nconst MAX_CONCURRENT_CONNECTIONS = 3;\nconst MAX_CONCURRENT_CONNECTIONS_PREMIUM = 6;\nconst MAX_WORKERS_PER_CONNECTION = 10;\nconst MULTIPLE_CONNECTIONS_MIN_FILE_SIZE = 10485760; // 10MB\n\nconst foremans = Array(MAX_CONCURRENT_CONNECTIONS_PREMIUM).fill(undefined)\n .map(() => new Foreman(MAX_WORKERS_PER_CONNECTION));\n\nasync function downloadFile2(\n client: TelegramClient,\n inputLocation: Api.InputFileLocation,\n fileParams: DownloadFileParams,\n) {\n let {\n partSizeKb, end,\n } = fileParams;\n const {\n fileSize,\n } = fileParams;\n const isPremium = Boolean(client.isPremium);\n const { dcId, progressCallback, start = 0 } = fileParams;\n\n end = end && end < fileSize ? end : fileSize - 1;\n\n if (!partSizeKb) {\n partSizeKb = fileSize ? getDownloadPartSize(fileSize) : DEFAULT_CHUNK_SIZE;\n }\n\n const partSize = partSizeKb * 1024;\n const partsCount = end ? Math.ceil((end - start) / partSize) : 1;\n const noParallel = !end;\n const shouldUseMultipleConnections = fileSize\n && fileSize >= MULTIPLE_CONNECTIONS_MIN_FILE_SIZE\n && !noParallel;\n let deferred: Deferred | undefined;\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 fileView = new FileView(end - start + 1);\n const promises: Promise<any>[] = [];\n let offset = start;\n // Pick the least busy foreman\n // For some reason, fresh connections give out a higher speed for the first couple of seconds\n // I have no idea why, but this may speed up the download of small files\n const activeCounts = foremans.map((l) => l.activeWorkers);\n let currentForemanIndex = activeCounts.indexOf(Math.min(...activeCounts));\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 // Allocate memory\n await fileView.init();\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 // Use only first connection for avatars, because no size is known and we don't want to\n // download empty parts using all connections at once\n const senderIndex = !shouldUseMultipleConnections ? 0 : currentForemanIndex % (\n isPremium ? MAX_CONCURRENT_CONNECTIONS_PREMIUM : MAX_CONCURRENT_CONNECTIONS\n );\n\n await foremans[senderIndex].requestWorker();\n\n if (deferred) await deferred.promise;\n\n if (noParallel) deferred = createDeferred();\n\n if (hasEnded) {\n foremans[senderIndex].releaseWorker();\n break;\n }\n\n // eslint-disable-next-line no-loop-func, @typescript-eslint/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, senderIndex, isPremium);\n // sometimes a session is revoked and will cause this to hang.\n const result = await Promise.race([\n sender.send(new Api.upload.GetFile({\n location: inputLocation,\n offset: BigInt(offsetMemo),\n limit,\n precise: isPrecise || undefined,\n })),\n sleep(SENDER_TIMEOUT).then(() => {\n // if we're on the main DC we just cancel the download and let the user retry later.\n if (dcId === client.session.dcId) {\n return Promise.reject(new Error('USER_CANCELED'));\n } else {\n return Promise.reject(new Error('SESSION_REVOKED'));\n }\n }),\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 foremans[senderIndex].releaseWorker();\n if (deferred) deferred.resolve();\n\n fileView.write(result.bytes, offsetMemo - start);\n\n return;\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 foremans[senderIndex].releaseWorker();\n if (deferred) deferred.resolve();\n\n hasEnded = true;\n throw err;\n }\n }\n })(offset));\n\n offset += limit;\n currentForemanIndex++;\n\n if (end && (offset > end)) {\n break;\n }\n }\n await Promise.all(promises);\n return fileView.getData();\n}\n","// eslint-disable-next-line import/no-named-default\nimport { default as Api } from '../tl/api';\n\nimport type TelegramClient from './TelegramClient';\nimport { generateRandomBytes, readBigIntFromBuffer, sleep } from '../Helpers';\nimport { getUploadPartSize } from '../Utils';\nimport errors from '../errors';\n\ninterface OnProgress {\n isCanceled?: boolean;\n\n // Float between 0 and 1.\n (progress: number): void;\n}\n\nexport interface UploadFileParams {\n file: File;\n workers: number;\n onProgress?: OnProgress;\n}\n\nconst KB_TO_BYTES = 1024;\nconst LARGE_FILE_THRESHOLD = 10 * 1024 * 1024;\nconst DISCONNECT_SLEEP = 1000;\n\nexport async function uploadFile(\n client: TelegramClient,\n fileParams: UploadFileParams,\n): Promise<Api.InputFile | Api.InputFileBig> {\n const { file, onProgress } = fileParams;\n let { workers } = fileParams;\n\n const { name, size } = file;\n const fileId = readBigIntFromBuffer(generateRandomBytes(8), true, true);\n const isLarge = size > LARGE_FILE_THRESHOLD;\n\n const partSize = getUploadPartSize(size) * KB_TO_BYTES;\n const partCount = Math.floor((size + partSize - 1) / partSize);\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 blobSlice = file.slice(j * partSize, (j + 1) * partSize);\n\n // eslint-disable-next-line no-loop-func, @typescript-eslint/no-loop-func\n sendingParts.push((async (jMemo: number, blobSliceMemo: Blob) => {\n // eslint-disable-next-line no-constant-condition\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 const partBytes = await blobSliceMemo.arrayBuffer();\n await sender.send(\n isLarge\n ? new Api.upload.SaveBigFilePart({\n fileId,\n filePart: jMemo,\n fileTotalParts: partCount,\n bytes: Buffer.from(partBytes),\n })\n : new Api.upload.SaveFilePart({\n fileId,\n filePart: jMemo,\n bytes: Buffer.from(partBytes),\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, blobSlice));\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","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 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\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 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, { 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 * 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\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\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\nmodule.exports = {\n EventBuilder,\n};\n","const NewMessage = require('./NewMessage');\nconst Raw = require('./Raw');\n\nclass StopPropagation extends Error {\n\n}\n\nmodule.exports = {\n NewMessage,\n StopPropagation,\n Raw,\n};\n","class AsyncQueue {\n constructor() {\n this._queue = [];\n this.canGet = new Promise((resolve) => {\n this.resolveGet = resolve;\n });\n this.canPush = true;\n }\n\n async push(value) {\n await this.canPush;\n this._queue.push(value);\n this.resolveGet(true);\n this.canPush = new Promise((resolve) => {\n this.resolvePush = resolve;\n });\n }\n\n async pop() {\n await this.canGet;\n const returned = this._queue.pop();\n this.resolvePush(true);\n this.canGet = new Promise((resolve) => {\n this.resolveGet = resolve;\n });\n return returned;\n }\n}\n\nmodule.exports = AsyncQueue;\n","const { TypeNotFoundError } = require('../errors/Common');\nconst { coreObjects } = require('../tl/core');\nconst { tlobjects } = require('../tl/AllTLObjects');\nconst { readBigIntFromBuffer } = require('../Helpers');\n\nclass BinaryReader {\n /**\n * Small utility class to read binary data.\n * @param data {Buffer}\n */\n constructor(data) {\n this.stream = data;\n this._last = undefined;\n this.offset = 0;\n }\n\n // region Reading\n\n // \"All numbers are written as little endian.\"\n // https://core.telegram.org/mtproto\n /**\n * Reads a single byte value.\n */\n readByte() {\n return this.read(1)[0];\n }\n\n /**\n * Reads an integer (4 bytes or 32 bits) value.\n * @param signed {Boolean}\n */\n readInt(signed = true) {\n let res;\n if (signed) {\n res = this.stream.readInt32LE(this.offset);\n } else {\n res = this.stream.readUInt32LE(this.offset);\n }\n this.offset += 4;\n return res;\n }\n\n /**\n * Reads a long integer (8 bytes or 64 bits) value.\n * @param signed\n * @returns {BigInteger}\n */\n readLong(signed = true) {\n return this.readLargeInt(64, signed);\n }\n\n /**\n * Reads a real floating point (4 bytes) value.\n * @returns {number}\n */\n readFloat() {\n return this.read(4)\n .readFloatLE(0);\n }\n\n /**\n * Reads a real floating point (8 bytes) value.\n * @returns {BigInteger}\n */\n readDouble() {\n // was this a bug ? it should have been <d\n return this.read(8)\n .readDoubleLE(0);\n }\n\n /**\n * Reads a n-bits long integer value.\n * @param bits\n * @param signed {Boolean}\n */\n readLargeInt(bits, signed = true) {\n const buffer = this.read(Math.floor(bits / 8));\n return readBigIntFromBuffer(buffer, true, signed);\n }\n\n /**\n * Read the given amount of bytes, or -1 to read all remaining.\n * @param length {number}\n */\n read(length = -1) {\n if (length === -1) {\n length = this.stream.length - this.offset;\n }\n const result = this.stream.slice(this.offset, this.offset + length);\n this.offset += length;\n if (result.length !== length) {\n throw Error(\n `No more data left to read (need ${length}, got ${result.length}: ${result}); last read ${this._last}`,\n );\n }\n this._last = result;\n return result;\n }\n\n /**\n * Gets the byte array representing the current buffer as a whole.\n * @returns {Buffer}\n */\n getBuffer() {\n return this.stream;\n }\n\n // endregion\n\n // region Telegram custom reading\n /**\n * Reads a Telegram-encoded byte array, without the need of\n * specifying its length.\n * @returns {Buffer}\n */\n tgReadBytes() {\n const firstByte = this.readByte();\n let padding;\n let length;\n if (firstByte === 254) {\n length = this.readByte() | (this.readByte() << 8) | (this.readByte() << 16);\n padding = length % 4;\n } else {\n length = firstByte;\n padding = (length + 1) % 4;\n }\n const data = this.read(length);\n\n if (padding > 0) {\n padding = 4 - padding;\n this.read(padding);\n }\n\n return data;\n }\n\n /**\n * Reads a Telegram-encoded string.\n * @returns {string}\n */\n tgReadString() {\n return this.tgReadBytes()\n .toString('utf-8');\n }\n\n /**\n * Reads a Telegram boolean value.\n * @returns {boolean}\n */\n tgReadBool() {\n const value = this.readInt(false);\n if (value === 0x997275b5) {\n // boolTrue\n return true;\n } else if (value === 0xbc799737) {\n // boolFalse\n return false;\n } else {\n throw new Error(`Invalid boolean code ${value.toString('16')}`);\n }\n }\n\n /**\n * Reads and converts Unix time (used by Telegram)\n * into a Javascript {Date} object.\n * @returns {Date}\n */\n tgReadDate() {\n const value = this.readInt();\n return new Date(value * 1000);\n }\n\n /**\n * Reads a Telegram object.\n */\n tgReadObject() {\n const constructorId = this.readInt(false);\n let clazz = tlobjects[constructorId];\n if (clazz === undefined) {\n /**\n * The class was None, but there's still a\n * chance of it being a manually parsed value like bool!\n */\n const value = constructorId;\n if (value === 0x997275b5) {\n // boolTrue\n return true;\n } else if (value === 0xbc799737) {\n // boolFalse\n return false;\n } else if (value === 0x1cb5c415) {\n // Vector\n const temp = [];\n const length = this.readInt();\n for (let i = 0; i < length; i++) {\n temp.push(this.tgReadObject());\n }\n return temp;\n }\n\n clazz = coreObjects[constructorId];\n\n if (clazz === undefined) {\n // If there was still no luck, give up\n this.seek(-4); // Go back\n const pos = this.tellPosition();\n const error = new TypeNotFoundError(constructorId, this.read());\n this.setPosition(pos);\n throw error;\n }\n }\n return clazz.fromReader(this);\n }\n\n /**\n * Reads a vector (a list) of Telegram objects.\n * @returns {[Buffer]}\n */\n tgReadVector() {\n if (this.readInt(false) !== 0x1cb5c415) {\n throw new Error('Invalid constructor code, vector was expected');\n }\n const count = this.readInt();\n const temp = [];\n for (let i = 0; i < count; i++) {\n temp.push(this.tgReadObject());\n }\n return temp;\n }\n\n // endregion\n\n /**\n * Closes the reader.\n */\n close() {\n this.stream = undefined;\n }\n\n // region Position related\n\n /**\n * Tells the current position on the stream.\n * @returns {number}\n */\n tellPosition() {\n return this.offset;\n }\n\n /**\n * Sets the current position on the stream.\n * @param position\n */\n setPosition(position) {\n this.offset = position;\n }\n\n /**\n * Seeks the stream position given an offset from the current position.\n * The offset may be negative.\n * @param offset\n */\n seek(offset) {\n this.offset += offset;\n }\n\n // endregion\n}\n\nmodule.exports = BinaryReader;\n","class BinaryWriter {\n constructor(stream) {\n this._stream = stream;\n }\n\n write(buffer) {\n this._stream = Buffer.concat([this._stream, buffer]);\n }\n\n getValue() {\n return this._stream;\n }\n}\n\nmodule.exports = BinaryWriter;\n","// eslint-disable-next-line @typescript-eslint/naming-convention\nlet _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', 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, isPremium) {\n if (port === 443) {\n return `wss://${ip}:${port}/apiws${testServers ? '_test' : ''}${isPremium ? '_premium' : ''}`;\n } else {\n return `ws://${ip}:${port}/apiws${testServers ? '_test' : ''}${isPremium ? '_premium' : ''}`;\n }\n }\n\n connect(port, ip, testServers = false, isPremium = 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, isPremium);\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\nexport const SERVER_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 '2534288944884041556497168959071347320689884775908477905258202659454602246385394058588521595116849196570'\n + '8222649399180603818074200620463776135424884632162512403163793083921641631564740959529419359595852941166'\n + '8489405859523376133330223960965841179548922160312292373029437018775884567383353986024616752250817918203'\n + '9315375750495263623495132323782003654358104782690612092797248736680529211579223142368426126233039432475'\n + '0785450942589751755390156647751460719351439969059949569615302809050721500330239005077889855323917509948'\n + '255722081644689442127297605422579707142646660768825302832201908302295573257427896031830742328565032949',\n ),\n e: 65537,\n },\n].reduce((acc, { fingerprint, ...keyInfo }) => {\n acc.set(fingerprint.toString(), keyInfo);\n return acc;\n}, new Map<string, { n: bigInt.BigInteger; e: number }>());\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 = SERVER_KEYS.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 { SERVER_KEYS } 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 = SERVER_KEYS.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('./updates');\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.isReconnecting = false;\n this._disconnected = true;\n\n /**\n * We need to join the loops upon disconnection\n */\n this._send_loop_handle = undefined;\n this._recv_loop_handle = undefined;\n\n /**\n * Preserving the references of the AuthKey and state is important\n */\n this.authKey = authKey || new AuthKey();\n this._state = new MTProtoState(this.authKey, this._log);\n\n /**\n * Outgoing messages are put in a queue and sent in a batch.\n * Note that here we're also storing their ``_RequestState``.\n */\n this._send_queue = new MessagePacker(this._state, this._log);\n\n /**\n * Sent states are remembered until a response is received.\n */\n this._pending_state = {};\n\n /**\n * Responses must be acknowledged, and we can also batch these.\n */\n this._pending_ack = new Set();\n\n /**\n * Similar to pending_messages but only for the last acknowledges.\n * These can't go in pending_messages because no acknowledge for them\n * is received, but we may still need to resend their state on bad salts.\n */\n this._last_acks = [];\n\n /**\n * Jump table from response ID to method that handles it\n */\n\n this._handlers = {\n [RPCResult.CONSTRUCTOR_ID]: this._handleRPCResult.bind(this),\n [MessageContainer.CONSTRUCTOR_ID]: this._handleContainer.bind(this),\n [GZIPPacked.CONSTRUCTOR_ID]: this._handleGzipPacked.bind(this),\n [Pong.CONSTRUCTOR_ID]: this._handlePong.bind(this),\n [BadServerSalt.CONSTRUCTOR_ID]: this._handleBadServerSalt.bind(this),\n [BadMsgNotification.CONSTRUCTOR_ID]: this._handleBadNotification.bind(this),\n [MsgDetailedInfo.CONSTRUCTOR_ID]: this._handleDetailedInfo.bind(this),\n [MsgNewDetailedInfo.CONSTRUCTOR_ID]: this._handleNewDetailedInfo.bind(this),\n [NewSessionCreated.CONSTRUCTOR_ID]: this._handleNewSessionCreated.bind(this),\n [MsgsAck.CONSTRUCTOR_ID]: this._handleAck.bind(this),\n [FutureSalts.CONSTRUCTOR_ID]: this._handleFutureSalts.bind(this),\n [MsgsStateReq.CONSTRUCTOR_ID]: this._handleStateForgotten.bind(this),\n [MsgResendReq.CONSTRUCTOR_ID]: this._handleStateForgotten.bind(this),\n [MsgsAllInfo.CONSTRUCTOR_ID]: this._handleMsgAll.bind(this),\n };\n }\n\n // Public API\n\n /**\n * Connects to the specified given connection using the given auth key.\n * @param connection\n * @param [force]\n * @returns {Promise<boolean>}\n */\n async connect(connection, force) {\n this.userDisconnected = false;\n\n if (this._user_connected && !force) {\n this._log.info('User is already connected!');\n return false;\n }\n this.isConnecting = true;\n this._connection = connection;\n\n for (let attempt = 0; attempt < this._retries; attempt++) {\n try {\n await this._connect();\n if (this._updateCallback) {\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.connected));\n }\n break;\n } catch (err) {\n if (this._updateCallback && attempt === 0) {\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.disconnected));\n }\n this._log.error(`WebSocket connection failed attempt: ${attempt + 1}`);\n // eslint-disable-next-line no-console\n console.error(err);\n await Helpers.sleep(this._delay);\n }\n }\n this.isConnecting = false;\n return true;\n }\n\n isConnected() {\n return this._user_connected;\n }\n\n /**\n * Cleanly disconnects the instance from the network, cancels\n * all pending requests, and closes the send and receive loops.\n */\n async disconnect() {\n this.userDisconnected = true;\n await this._disconnect();\n }\n\n /**\n *\n This method enqueues the given request to be sent. Its send\n state will be saved until a response arrives, and a ``Future``\n that will be resolved when the response arrives will be returned:\n\n .. code-block:: javascript\n\n async def method():\n # Sending (enqueued for the send loop)\n future = sender.send(request)\n # Receiving (waits for the receive loop to read the result)\n result = await future\n\n Designed like this because Telegram may send the response at\n any point, and it can send other items while one waits for it.\n Once the response for this future arrives, it is set with the\n received result, quite similar to how a ``receive()`` call\n would otherwise work.\n\n Since the receiving part is \"built in\" the future, it's\n impossible to await receive a result that was never sent.\n * @param request\n * @returns {RequestState}\n */\n send(request) {\n if (!this._user_connected) {\n throw new Error('Cannot send requests while disconnected');\n }\n const state = new RequestState(request);\n this._send_queue.append(state);\n return state.promise;\n }\n\n /**\n * Same as send but returns the full state. usefull for invoke after logic\n * @param request\n * @return {RequestState}\n */\n sendWithInvokeSupport(request) {\n if (!this._user_connected) {\n throw new Error('Cannot send requests while disconnected');\n }\n const state = new RequestState(request, undefined, this._pending_state);\n this._send_queue.append(state);\n return state;\n }\n\n /**\n * Performs the actual connection, retrying, generating the\n * authorization key if necessary, and starting the send and\n * receive loops.\n * @returns {Promise<void>}\n * @private\n */\n async _connect() {\n this._log.info('Connecting to {0}...'.replace('{0}', this._connection));\n await this._connection.connect();\n this._log.debug('Connection success!');\n // process.exit(0)\n if (!this.authKey.getKey()) {\n const plain = new MtProtoPlainSender(this._connection, this._log);\n this._log.debug('New auth_key attempt ...');\n const res = await doAuthentication(plain, this._log);\n this._log.debug('Generated new auth_key successfully');\n await this.authKey.setKey(res.authKey);\n\n this._state.timeOffset = res.timeOffset;\n\n if (this._updateCallback) {\n this._updateCallback(new UpdateServerTimeOffset(this._state.timeOffset));\n }\n\n /**\n * This is *EXTREMELY* important since we don't control\n * external references to the authorization key, we must\n * notify whenever we change it. This is crucial when we\n * switch to different data centers.\n */\n if (this._authKeyCallback) {\n await this._authKeyCallback(this.authKey, this._dcId);\n }\n } else {\n this._authenticated = true;\n this._log.debug('Already have an auth key ...');\n }\n this._user_connected = true;\n this.isReconnecting = 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._updateCallback) {\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.disconnected));\n }\n\n if (this._connection === undefined) {\n this._log.info('Not disconnecting (already have no connection)');\n return;\n }\n\n this._log.info('Disconnecting from %s...'.replace('%s', this._connection.toString()));\n this._user_connected = false;\n this._log.debug('Closing current connection...');\n await this._connection.disconnect();\n }\n\n /**\n * This loop is responsible for popping items off the send\n * queue, encrypting them, and sending them over the network.\n * Besides `connect`, only this method ever sends data.\n * @returns {Promise<void>}\n * @private\n */\n async _sendLoop() {\n this._send_queue = new MessagePacker(this._state, this._log);\n\n while (this._user_connected && !this.isReconnecting) {\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.isReconnecting}`);\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.isReconnecting) {\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.isReconnecting) {\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<void>}\n * @private\n */\n async _processMessage(message) {\n this._pending_ack.add(message.msgId);\n // eslint-disable-next-line require-atomic-updates\n message.obj = await message.obj;\n let handler = this._handlers[message.obj.CONSTRUCTOR_ID];\n if (!handler) {\n handler = this._handleUpdate.bind(this);\n }\n\n await handler(message);\n }\n\n /**\n * Pops the states known to match the given ID from pending messages.\n * This method should be used when the response isn't specific.\n * @param msgId\n * @returns {*[]}\n * @private\n */\n _popStates(msgId) {\n let state = this._pending_state[msgId];\n if (state) {\n this._pending_state[msgId].deferred.resolve();\n delete this._pending_state[msgId];\n return [state];\n }\n\n const toPop = [];\n\n for (state of Object.values(this._pending_state)) {\n if (state.containerId && state.containerId.equals(msgId)) {\n toPop.push(state.msgId);\n }\n }\n\n if (toPop.length) {\n const temp = [];\n for (const x of toPop) {\n temp.push(this._pending_state[x]);\n this._pending_state[x].deferred.resolve();\n delete this._pending_state[x];\n }\n return temp;\n }\n\n for (const ack of this._last_acks) {\n if (ack.msgId === msgId) {\n return [ack];\n }\n }\n\n return [];\n }\n\n /**\n * Handles the result for Remote Procedure Calls:\n * rpc_result#f35c6d01 req_msg_id:long result:bytes = RpcResult;\n * This is where the future results for sent requests are set.\n * @param message\n * @returns {Promise<void>}\n * @private\n */\n _handleRPCResult(message) {\n const result = message.obj;\n const state = this._pending_state[result.reqMsgId];\n if (state) {\n state.deferred.resolve();\n delete this._pending_state[result.reqMsgId];\n }\n this._log.debug(`Handling RPC result for message ${result.reqMsgId}`);\n\n if (!state) {\n // TODO We should not get responses to things we never sent\n // However receiving a File() with empty bytes is \"common\".\n // See #658, #759 and #958. They seem to happen in a container\n // which contain the real response right after.\n try {\n const reader = new BinaryReader(result.body);\n if (!(reader.tgReadObject() instanceof upload.File)) {\n throw new TypeNotFoundError('Not an upload.File');\n }\n } catch (e) {\n this._log.error(e);\n if (e instanceof TypeNotFoundError) {\n this._log.info(`Received response without parent request: ${result.body}`);\n return;\n } else {\n throw e;\n }\n }\n }\n if (result.error) {\n // eslint-disable-next-line new-cap\n const error = RPCMessageToError(result.error, state.request);\n this._send_queue.append(new RequestState(new MsgsAck({ msgIds: [state.msgId] })));\n state.reject(error);\n 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<void>}\n * @private\n */\n async _handleContainer(message) {\n this._log.debug('Handling container');\n for (const innerMessage of message.obj.messages) {\n await this._processMessage(innerMessage);\n }\n }\n\n /**\n * Unpacks the data from a gzipped object and processes it:\n * gzip_packed#3072cfa1 packed_data:bytes = Object;\n * @param message\n * @returns {Promise<void>}\n * @private\n */\n async _handleGzipPacked(message) {\n this._log.debug('Handling gzipped data');\n const reader = new BinaryReader(message.obj.data);\n message.obj = reader.tgReadObject();\n await this._processMessage(message);\n }\n\n _handleUpdate(message) {\n if (message.obj.SUBCLASS_OF_ID !== 0x8af52aac) {\n // crc32(b'Updates')\n this._log.warn(`Note: ${message.obj.className} is not an update, not dispatching it`);\n return;\n }\n this._log.debug(`Handling update ${message.obj.className}`);\n if (this._updateCallback) {\n this._updateCallback(message.obj);\n }\n }\n\n /**\n * Handles pong results, which don't come inside a ``RPCResult``\n * but are still sent through a request:\n * pong#347773c5 msg_id:long ping_id:long = Pong;\n * @param message\n * @returns {Promise<void>}\n * @private\n */\n _handlePong(message) {\n const pong = message.obj;\n\n const newTimeOffset = this._state.updateTimeOffset(message.msgId);\n if (this._updateCallback) {\n this._updateCallback(new UpdateServerTimeOffset(newTimeOffset));\n }\n\n this._log.debug(`Handling pong for message ${pong.msgId}`);\n const state = this._pending_state[pong.msgId];\n this._pending_state[pong.msgId].deferred.resolve();\n delete this._pending_state[pong.msgId];\n\n // Todo Check result\n if (state) {\n state.resolve(pong);\n }\n }\n\n /**\n * Corrects the currently used server salt to use the right value\n * before enqueuing the rejected message to be re-sent:\n * bad_server_salt#edab447b bad_msg_id:long bad_msg_seqno:int\n * error_code:int new_server_salt:long = BadMsgNotification;\n * @param message\n * @returns {Promise<void>}\n * @private\n */\n _handleBadServerSalt(message) {\n const badSalt = message.obj;\n this._log.debug(`Handling bad salt for message ${badSalt.badMsgId}`);\n this._state.salt = badSalt.newServerSalt;\n const states = this._popStates(badSalt.badMsgId);\n this._send_queue.extend(states);\n this._log.debug(`${states.length} message(s) will be resent`);\n }\n\n /**\n * Adjusts the current state to be correct based on the\n * received bad message notification whenever possible:\n * bad_msg_notification#a7eff811 bad_msg_id:long bad_msg_seqno:int\n * error_code:int = BadMsgNotification;\n * @param message\n * @returns {Promise<void>}\n * @private\n */\n _handleBadNotification(message) {\n const badMsg = message.obj;\n const states = this._popStates(badMsg.badMsgId);\n this._log.debug(`Handling bad msg ${JSON.stringify(badMsg)}`);\n if ([16, 17].includes(badMsg.errorCode)) {\n // Sent msg_id too low or too high (respectively).\n // Use the current msg_id to determine the right time offset.\n const newTimeOffset = this._state.updateTimeOffset(message.msgId);\n\n if (this._updateCallback) {\n this._updateCallback(new UpdateServerTimeOffset(newTimeOffset));\n }\n\n this._log.info(`System clock is wrong, set time offset to ${newTimeOffset}s`);\n } else if (badMsg.errorCode === 32) {\n // msg_seqno too low, so just pump it up by some \"large\" amount\n // TODO A better fix would be to start with a new fresh session ID\n this._state._sequence += 64;\n } else if (badMsg.errorCode === 33) {\n // msg_seqno too high never seems to happen but just in case\n this._state._sequence -= 16;\n } else {\n for (const state of states) {\n state.reject(new BadMessageError(state.request, badMsg.errorCode));\n }\n\n return;\n }\n // Messages are to be re-sent once we've corrected the issue\n this._send_queue.extend(states);\n this._log.debug(`${states.length} messages will be resent due to bad msg`);\n }\n\n /**\n * Updates the current status with the received detailed information:\n * msg_detailed_info#276d3ec6 msg_id:long answer_msg_id:long\n * bytes:int status:int = MsgDetailedInfo;\n * @param message\n * @returns {Promise<void>}\n * @private\n */\n _handleDetailedInfo(message) {\n // TODO https://goo.gl/VvpCC6\n const msgId = message.obj.answerMsgId;\n this._log.debug(`Handling detailed info for message ${msgId}`);\n this._pending_ack.add(msgId);\n }\n\n /**\n * Updates the current status with the received detailed information:\n * msg_new_detailed_info#809db6df answer_msg_id:long\n * bytes:int status:int = MsgDetailedInfo;\n * @param message\n * @returns {Promise<void>}\n * @private\n */\n _handleNewDetailedInfo(message) {\n // TODO https://goo.gl/VvpCC6\n const msgId = message.obj.answerMsgId;\n this._log.debug(`Handling new detailed info for message ${msgId}`);\n this._pending_ack.add(msgId);\n }\n\n /**\n * Updates the current status with the received session information:\n * new_session_created#9ec20908 first_msg_id:long unique_id:long\n * server_salt:long = NewSession;\n * @param message\n * @returns {Promise<void>}\n * @private\n */\n _handleNewSessionCreated(message) {\n // TODO https://goo.gl/LMyN7A\n this._log.debug('Handling new session created');\n this._state.salt = message.obj.serverSalt;\n }\n\n /**\n * Handles a server acknowledge about our messages. Normally\n * these can be ignored except in the case of ``auth.logOut``:\n *\n * auth.logOut#5717da40 = Bool;\n *\n * Telegram doesn't seem to send its result so we need to confirm\n * it manually. No other request is known to have this behaviour.\n\n * Since the ID of sent messages consisting of a container is\n * never returned (unless on a bad notification), this method\n * also removes containers messages when any of their inner\n * messages are acknowledged.\n\n * @param message\n * @returns {Promise<void>}\n * @private\n */\n _handleAck(message) {\n const ack = message.obj;\n this._log.debug(`Handling acknowledge for ${ack.msgIds}`);\n for (const msgId of ack.msgIds) {\n const state = this._pending_state[msgId];\n if (state && state.request instanceof LogOut) {\n this._pending_state[msgId].deferred.resolve();\n delete this._pending_state[msgId];\n state.resolve(true);\n }\n }\n }\n\n /**\n * Handles future salt results, which don't come inside a\n * ``rpc_result`` but are still sent through a request:\n * future_salts#ae500895 req_msg_id:long now:int\n * salts:vector<future_salt> = FutureSalts;\n * @param message\n * @returns {Promise<void>}\n * @private\n */\n _handleFutureSalts(message) {\n // TODO save these salts and automatically adjust to the\n // correct one whenever the salt in use expires.\n this._log.debug(`Handling future salts for message ${message.msgId}`);\n const state = this._pending_state[message.msgId];\n\n if (state) {\n this._pending_state[message].deferred.resolve();\n delete this._pending_state[message];\n state.resolve(message.obj);\n }\n }\n\n /**\n * Handles both :tl:`MsgsStateReq` and :tl:`MsgResendReq` by\n * enqueuing a :tl:`MsgsStateInfo` to be sent at a later point.\n * @param message\n * @returns {Promise<void>}\n * @private\n */\n _handleStateForgotten(message) {\n this._send_queue.append(\n new RequestState(new MsgsStateInfo(message.msgId, String.fromCharCode(1)\n .repeat(message.obj.msgIds))),\n );\n }\n\n /**\n * Handles :tl:`MsgsAllInfo` by doing nothing (yet).\n * used as part of the telegram protocol https://core.telegram.org/mtproto/service_messages_about_messages\n * This message does not require an acknowledgment.\n * @param message\n * @returns {Promise<void>}\n * @private\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _handleMsgAll(message) {\n }\n\n reconnect() {\n if (this._user_connected && !this.isReconnecting) {\n this.isReconnecting = 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.isReconnecting = 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');\nconst aes = require('@cryptography/aes');\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 * @param isCall\n * @param isOutgoing\n */\n constructor(authKey, loggers, isCall = false, isOutgoing = false) {\n this.authKey = authKey;\n this._log = loggers;\n this._isCall = isCall;\n this._isOutgoing = isOutgoing;\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 = (this._isCall ? 128 + ((this._isOutgoing ^ client) ? 8 : 0) : (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 if (this._isCall) {\n const iv = Buffer.concat([sha256b.slice(0, 4), sha256a.slice(8, 16), sha256b.slice(24, 28)]);\n\n return {\n key,\n iv,\n };\n }\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 if (this._isCall) {\n const x = 128 + (this._isOutgoing ? 0 : 8);\n const lengthStart = data.length;\n\n data = Buffer.from(data);\n if (lengthStart % 4 !== 0) {\n data = Buffer.concat([data, Buffer.from(new Array(4 - (lengthStart % 4)).fill(0x20))]);\n }\n\n const msgKeyLarge = await Helpers.sha256(Buffer.concat([this.authKey.getKey()\n .slice(88 + x, 88 + x + 32), Buffer.from(data)]));\n\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 data = Helpers.convertToLittle(new aes.CTR(key, iv).encrypt(data));\n // data = data.slice(0, lengthStart)\n return Buffer.concat([msgKey, data]);\n } else {\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 /**\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 && !this._isCall) {\n throw new SecurityError('Server replied with length not divisible by 4');\n }\n // TODO Check salt,sessionId, and sequenceNumber\n if (!this._isCall) {\n const keyId = Helpers.readBigIntFromBuffer(body.slice(0, 8));\n\n if (keyId.neq(this.authKey.keyId)) {\n throw new SecurityError('Server replied with an invalid auth key');\n }\n }\n const msgKey = this._isCall ? body.slice(0, 16) : body.slice(8, 24);\n\n const x = this._isCall ? 128 + (this.isOutgoing ? 8 : 0) : undefined;\n const {\n iv,\n key,\n } = await this._calcKey(this.authKey.getKey(), msgKey, false);\n\n if (this._isCall) {\n body = body.slice(16);\n const lengthStart = body.length;\n\n body = Buffer.concat([body, Buffer.from(new Array(4 - (lengthStart % 4)).fill(0))]);\n\n body = Helpers.convertToLittle(new aes.CTR(key, iv).decrypt(body));\n\n body = body.slice(0, lengthStart);\n } else {\n body = new IGE(key, iv).decryptIge(this._isCall ? body.slice(16) : body.slice(24));\n }\n // https://core.telegram.org/mtproto/security_guidelines\n // Sections \"checking sha256 hash\" and \"message length\"\n\n const ourKey = this._isCall\n ? await Helpers.sha256(Buffer.concat([this.authKey.getKey()\n .slice(88 + x, 88 + x + 32), body]))\n : await Helpers.sha256(Buffer.concat([this.authKey.getKey()\n .slice(96, 96 + 32), body]));\n\n if (!this._isCall && !msgKey.equals(ourKey.slice(8, 24))) {\n throw new SecurityError('Received msg_key doesn\\'t match with expected one');\n }\n const reader = new BinaryReader(body);\n\n if (this._isCall) {\n // Seq\n reader.readInt(false);\n return reader.read(body.length - 4);\n } else {\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 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 /**\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, isPremium) {\n this._ip = ip;\n this._port = port;\n this._dcId = dcId;\n this._log = loggers;\n this._testServers = testServers;\n this._isPremium = isPremium;\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, this._isPremium);\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\nconst {\n Connection,\n ConnectionTCPFull,\n ConnectionTCPAbridged,\n ConnectionTCPObfuscated,\n} = require('./connection');\n\nconst {\n UpdateConnectionState,\n UpdateServerTimeOffset,\n} = require('./updates');\n\nmodule.exports = {\n Connection,\n ConnectionTCPFull,\n ConnectionTCPAbridged,\n ConnectionTCPObfuscated,\n MTProtoPlainSender,\n MTProtoSender,\n UpdateConnectionState,\n UpdateServerTimeOffset,\n};\n","class UpdateConnectionState {\n static disconnected = -1;\n\n static connected = 1;\n\n static broken = 0;\n\n constructor(state, origin) {\n this.state = state;\n this.origin = origin;\n }\n}\n\nclass UpdateServerTimeOffset {\n constructor(timeOffset) {\n this.timeOffset = timeOffset;\n }\n}\n\nmodule.exports = {\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 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 const deleted = await this._delete();\n return deleted;\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\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 = 144;\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');\nconst schemeContent = require('./schemaTl');\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 const flagValue = arg.flagIndex > 30\n ? args.flags2 & (1 << (arg.flagIndex - 31)) : args.flags & (1 << arg.flagIndex);\n if (arg.type === 'true') {\n args[argName] = Boolean(flagValue);\n continue;\n }\n if (flagValue) {\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<InputDocument> ttl_seconds:flags.1?int = InputMedia;\ninputMediaPhoto#b3ba0635 flags:# id:InputPhoto ttl_seconds:flags.0?int = InputMedia;\ninputMediaGeoPoint#f9c44144 geo_point:InputGeoPoint = InputMedia;\ninputMediaContact#f8ab7dfb phone_number:string first_name:string last_name:string vcard:string = InputMedia;\ninputMediaUploadedDocument#5b38c6c1 flags:# nosound_video:flags.3?true force_file:flags.4?true file:InputFile thumb:flags.2?InputFile mime_type:string attributes:Vector<DocumentAttribute> stickers:flags.0?Vector<InputDocument> ttl_seconds:flags.1?int = InputMedia;\ninputMediaDocument#33473058 flags:# id:InputDocument ttl_seconds:flags.0?int query:flags.1?string = InputMedia;\ninputMediaVenue#c13d1c11 geo_point:InputGeoPoint title:string address:string provider:string venue_id:string venue_type:string = InputMedia;\ninputMediaPhotoExternal#e5bbfe1a flags:# url:string ttl_seconds:flags.0?int = InputMedia;\ninputMediaDocumentExternal#fb52dc99 flags:# url:string ttl_seconds:flags.0?int = InputMedia;\ninputMediaGame#d33f43f3 id:InputGame = InputMedia;\ninputMediaInvoice#d9799874 flags:# title:string description:string photo:flags.0?InputWebDocument invoice:Invoice payload:bytes provider:string provider_data:DataJSON start_param:flags.1?string = InputMedia;\ninputMediaGeoLive#971fa843 flags:# stopped:flags.0?true geo_point:InputGeoPoint heading:flags.2?int period:flags.1?int proximity_notification_radius:flags.3?int = InputMedia;\ninputMediaPoll#f94e5f1 flags:# poll:Poll correct_answers:flags.0?Vector<bytes> solution:flags.1?string solution_entities:flags.1?Vector<MessageEntity> = InputMedia;\ninputMediaDice#e66fbf7b emoticon:string = InputMedia;\ninputChatPhotoEmpty#1ca48f57 = InputChatPhoto;\ninputChatUploadedPhoto#c642724e flags:# file:flags.0?InputFile video:flags.1?InputFile video_start_ts:flags.2?double = InputChatPhoto;\ninputChatPhoto#8953ad37 id:InputPhoto = InputChatPhoto;\ninputGeoPointEmpty#e4c123d6 = InputGeoPoint;\ninputGeoPoint#48222faf flags:# lat:double long:double accuracy_radius:flags.0?int = InputGeoPoint;\ninputPhotoEmpty#1cd7bf0d = InputPhoto;\ninputPhoto#3bb3b94a id:long access_hash:long file_reference:bytes = InputPhoto;\ninputFileLocation#dfdaabe1 volume_id:long local_id:int secret:long file_reference:bytes = InputFileLocation;\ninputEncryptedFileLocation#f5235d55 id:long access_hash:long = InputFileLocation;\ninputDocumentFileLocation#bad07584 id:long access_hash:long file_reference:bytes thumb_size:string = InputFileLocation;\ninputSecureFileLocation#cbc7ee28 id:long access_hash:long = InputFileLocation;\ninputTakeoutFileLocation#29be5899 = InputFileLocation;\ninputPhotoFileLocation#40181ffe id:long access_hash:long file_reference:bytes thumb_size:string = InputFileLocation;\ninputPhotoLegacyFileLocation#d83466f3 id:long access_hash:long file_reference:bytes volume_id:long local_id:int secret:long = InputFileLocation;\ninputPeerPhotoFileLocation#37257e99 flags:# big:flags.0?true peer:InputPeer photo_id:long = InputFileLocation;\ninputStickerSetThumb#9d84f3db stickerset:InputStickerSet thumb_version:int = InputFileLocation;\ninputGroupCallStream#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 bot_attach_menu:flags.27?true premium:flags.28?true attach_menu_enabled:flags.29?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<RestrictionReason> bot_inline_placeholder:flags.19?string lang_code:flags.22?string = User;\nuserProfilePhotoEmpty#4f11bae1 = UserProfilePhoto;\nuserProfilePhoto#82d1f706 flags:# has_video:flags.0?true photo_id:long stripped_thumb:flags.1?bytes dc_id:int = UserProfilePhoto;\nuserStatusEmpty#9d05049 = UserStatus;\nuserStatusOnline#edb93949 expires:int = UserStatus;\nuserStatusOffline#8c703f was_online:int = UserStatus;\nuserStatusRecently#e26f42f1 = UserStatus;\nuserStatusLastWeek#7bf09fc = UserStatus;\nuserStatusLastMonth#77ebc742 = UserStatus;\nchatEmpty#29562865 id:long = Chat;\nchat#41cbf256 flags:# creator:flags.0?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 join_to_send:flags.28?true join_request:flags.29?true id:long access_hash:flags.13?long title:string username:flags.6?string photo:ChatPhoto date:int restriction_reason:flags.9?Vector<RestrictionReason> admin_rights:flags.14?ChatAdminRights banned_rights:flags.15?ChatBannedRights default_banned_rights:flags.18?ChatBannedRights participants_count:flags.17?int = Chat;\nchannelForbidden#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<BotInfo> pinned_msg_id:flags.6?int folder_id:flags.11?int call:flags.12?InputGroupCall ttl_period:flags.14?int groupcall_default_join_as:flags.15?Peer theme_emoticon:flags.16?string requests_pending:flags.17?int recent_requesters:flags.17?Vector<long> available_reactions:flags.18?Vector<string> = ChatFull;\nchannelFull#ea68a619 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 flags2:# can_delete_channel:flags.31?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<BotInfo> 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<string> groupcall_default_join_as:flags.26?Peer theme_emoticon:flags.27?string requests_pending:flags.28?int recent_requesters:flags.28?Vector<long> default_send_as:flags.29?Peer available_reactions:flags.30?Vector<string> = 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<ChatParticipant> version:int = ChatParticipants;\nchatPhotoEmpty#37c1011c = ChatPhoto;\nchatPhoto#1c6e1c11 flags:# has_video:flags.0?true photo_id:long stripped_thumb:flags.1?bytes dc_id:int = ChatPhoto;\nmessageEmpty#90a6ca84 flags:# id:int peer_id:flags.0?Peer = Message;\nmessage#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<MessageEntity> views:flags.10?int forwards:flags.10?int replies:flags.23?MessageReplies edit_date:flags.15?int post_author:flags.16?string grouped_id:flags.17?long reactions:flags.20?MessageReactions restriction_reason:flags.22?Vector<RestrictionReason> ttl_period:flags.25?int = Message;\nmessageService#2b085862 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true post:flags.14?true legacy:flags.19?true id:int from_id:flags.8?Peer peer_id:Peer reply_to:flags.3?MessageReplyHeader date:int action:MessageAction ttl_period:flags.25?int = Message;\nmessageMediaEmpty#3ded6320 = MessageMedia;\nmessageMediaPhoto#695150d7 flags:# photo:flags.0?Photo ttl_seconds:flags.2?int = MessageMedia;\nmessageMediaGeo#56e0d474 geo:GeoPoint = MessageMedia;\nmessageMediaContact#70322949 phone_number:string first_name:string last_name:string vcard:string user_id:long = MessageMedia;\nmessageMediaUnsupported#9f84f49e = MessageMedia;\nmessageMediaDocument#9cb070d7 flags:# nopremium:flags.3?true 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<long> = MessageAction;\nmessageActionChatEditTitle#b5a1ce5a title:string = MessageAction;\nmessageActionChatEditPhoto#7fcb13a8 photo:Photo = MessageAction;\nmessageActionChatDeletePhoto#95e3fbef = MessageAction;\nmessageActionChatAddUser#15cefd00 users:Vector<long> = 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:# recurring_init:flags.2?true recurring_used:flags.3?true currency:string total_amount:long payload:bytes info:flags.0?PaymentRequestedInfo shipping_option_id:flags.1?string charge:PaymentCharge = MessageAction;\nmessageActionPaymentSent#96163f56 flags:# recurring_init:flags.2?true recurring_used:flags.3?true currency:string total_amount:long invoice_slug:flags.0?string = MessageAction;\nmessageActionPhoneCall#80e11a7f flags:# video:flags.2?true call_id:long reason:flags.0?PhoneCallDiscardReason duration:flags.1?int = MessageAction;\nmessageActionScreenshotTaken#4792929b = MessageAction;\nmessageActionCustomAction#fae69f56 message:string = MessageAction;\nmessageActionBotAllowed#abe9affe domain:string = MessageAction;\nmessageActionSecureValuesSentMe#1b287353 values:Vector<SecureValue> credentials:SecureCredentialsEncrypted = MessageAction;\nmessageActionSecureValuesSent#d95c6154 types:Vector<SecureValueType> = MessageAction;\nmessageActionContactSignUp#f3f25f76 = MessageAction;\nmessageActionGeoProximityReached#98e0d697 from_id:Peer to_id:Peer distance:int = MessageAction;\nmessageActionGroupCall#7a0d7f42 flags:# call:InputGroupCall duration:flags.0?int = MessageAction;\nmessageActionInviteToGroupCall#502f92f7 call:InputGroupCall users:Vector<long> = MessageAction;\nmessageActionSetMessagesTTL#aa1afbfd period:int = MessageAction;\nmessageActionGroupCallScheduled#b3a07661 call:InputGroupCall schedule_date:int = MessageAction;\nmessageActionSetChatTheme#aa786345 emoticon:string = MessageAction;\nmessageActionChatJoinedByRequest#ebbca3cb = MessageAction;\nmessageActionWebViewDataSentMe#47dd8079 text:string data:string = MessageAction;\nmessageActionWebViewDataSent#b4c38cb5 text:string = MessageAction;\nmessageActionGiftPremium#aba0f5c6 currency:string amount:long months:int = MessageAction;\ndialog#a8edd0f5 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 unread_reactions_count:int notify_settings:PeerNotifySettings pts:flags.0?int draft:flags.1?DraftMessage folder_id:flags.4?int = Dialog;\ndialogFolder#71bd134c flags:# pinned:flags.2?true folder:Folder peer:Peer top_message:int unread_muted_peers_count:int unread_unmuted_peers_count:int unread_muted_messages_count:int unread_unmuted_messages_count:int = Dialog;\nphotoEmpty#2331b22d id:long = Photo;\nphoto#fb197a65 flags:# has_stickers:flags.0?true id:long access_hash:long file_reference:bytes date:int sizes:Vector<PhotoSize> video_sizes:flags.1?Vector<VideoSize> dc_id:int = Photo;\nphotoSizeEmpty#e17e23c type:string = PhotoSize;\nphotoSize#75c78e60 type:string w:int h:int size:int = PhotoSize;\nphotoCachedSize#21e1ad6 type:string w:int h:int bytes:bytes = PhotoSize;\nphotoStrippedSize#e0b0bc2e type:string bytes:bytes = PhotoSize;\nphotoSizeProgressive#fa3efb95 type:string w:int h:int sizes:Vector<int> = PhotoSize;\nphotoPathSize#d8214d41 type:string bytes:bytes = PhotoSize;\ngeoPointEmpty#1117dd5f = GeoPoint;\ngeoPoint#b2a2f663 flags:# long:double lat:double access_hash:long accuracy_radius:flags.0?int = GeoPoint;\nauth.sentCode#5e002502 flags:# type:auth.SentCodeType phone_code_hash:string next_type:flags.1?auth.CodeType timeout:flags.2?int = auth.SentCode;\nauth.authorization#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#df1f002b flags:# show_previews:flags.0?Bool silent:flags.1?Bool mute_until:flags.2?int sound:flags.3?NotificationSound = InputPeerNotifySettings;\npeerNotifySettings#a83b0426 flags:# show_previews:flags.0?Bool silent:flags.1?Bool mute_until:flags.2?int ios_sound:flags.3?NotificationSound android_sound:flags.4?NotificationSound other_sound:flags.5?NotificationSound = 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;\ninputReportReasonIllegalDrugs#a8eb2be = ReportReason;\ninputReportReasonPersonalDetails#9ec7863d = ReportReason;\nuserFull#c4b1fc3f 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 voice_messages_forbidden:flags.20?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 bot_group_admin_rights:flags.17?ChatAdminRights bot_broadcast_admin_rights:flags.18?ChatAdminRights premium_gifts:flags.19?Vector<PremiumGiftOption> = 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<Contact> saved_count:int users:Vector<User> = contacts.Contacts;\ncontacts.importedContacts#77d01c3b imported:Vector<ImportedContact> popular_invites:Vector<PopularContact> retry_contacts:Vector<long> users:Vector<User> = contacts.ImportedContacts;\ncontacts.blocked#ade1591 blocked:Vector<PeerBlocked> chats:Vector<Chat> users:Vector<User> = contacts.Blocked;\ncontacts.blockedSlice#e1664194 count:int blocked:Vector<PeerBlocked> chats:Vector<Chat> users:Vector<User> = contacts.Blocked;\nmessages.dialogs#15ba6c40 dialogs:Vector<Dialog> messages:Vector<Message> chats:Vector<Chat> users:Vector<User> = messages.Dialogs;\nmessages.dialogsSlice#71e094f3 count:int dialogs:Vector<Dialog> messages:Vector<Message> chats:Vector<Chat> users:Vector<User> = messages.Dialogs;\nmessages.dialogsNotModified#f0e3e596 count:int = messages.Dialogs;\nmessages.messages#8c718e87 messages:Vector<Message> chats:Vector<Chat> users:Vector<User> = messages.Messages;\nmessages.messagesSlice#3a54685e flags:# inexact:flags.1?true count:int next_rate:flags.0?int offset_id_offset:flags.2?int messages:Vector<Message> chats:Vector<Chat> users:Vector<User> = messages.Messages;\nmessages.channelMessages#64479808 flags:# inexact:flags.1?true pts:int count:int offset_id_offset:flags.2?int messages:Vector<Message> chats:Vector<Chat> users:Vector<User> = messages.Messages;\nmessages.messagesNotModified#74535f21 count:int = messages.Messages;\nmessages.chats#64ff9fd5 chats:Vector<Chat> = messages.Chats;\nmessages.chatsSlice#9cd81144 count:int chats:Vector<Chat> = messages.Chats;\nmessages.chatFull#e5d7d19c full_chat:ChatFull chats:Vector<Chat> users:Vector<User> = messages.ChatFull;\nmessages.affectedHistory#b45c69d1 pts:int pts_count:int offset:int = messages.AffectedHistory;\ninputMessagesFilterEmpty#57e2f66c = MessagesFilter;\ninputMessagesFilterPhotos#9609a51c = MessagesFilter;\ninputMessagesFilterVideo#9fc00e65 = MessagesFilter;\ninputMessagesFilterPhotoVideo#56e9f0e4 = MessagesFilter;\ninputMessagesFilterDocument#9eddf188 = MessagesFilter;\ninputMessagesFilterUrl#7ef0dd87 = MessagesFilter;\ninputMessagesFilterGif#ffc86587 = MessagesFilter;\ninputMessagesFilterVoice#50f5c392 = MessagesFilter;\ninputMessagesFilterMusic#3751b49e = MessagesFilter;\ninputMessagesFilterChatPhotos#3a20ecb8 = MessagesFilter;\ninputMessagesFilterPhoneCalls#80c99768 flags:# missed:flags.0?true = MessagesFilter;\ninputMessagesFilterRoundVoice#7a7c17a4 = MessagesFilter;\ninputMessagesFilterRoundVideo#b549da53 = MessagesFilter;\ninputMessagesFilterMyMentions#c1f8e69a = MessagesFilter;\ninputMessagesFilterGeo#e7026d0d = MessagesFilter;\ninputMessagesFilterContacts#e062db83 = MessagesFilter;\ninputMessagesFilterPinned#1bb00451 = MessagesFilter;\nupdateNewMessage#1f2b0afd message:Message pts:int pts_count:int = Update;\nupdateMessageID#4e90bfd6 id:int random_id:long = Update;\nupdateDeleteMessages#a20db0e5 messages:Vector<int> pts:int pts_count:int = Update;\nupdateUserTyping#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<DcOption> = Update;\nupdateNotifySettings#bec268ef peer:NotifyPeer notify_settings:PeerNotifySettings = Update;\nupdateServiceNotification#ebe46819 flags:# popup:flags.0?true inbox_date:flags.1?int type:string message:string media:MessageMedia entities:Vector<MessageEntity> = Update;\nupdatePrivacy#ee3b272a key:PrivacyKey rules:Vector<PrivacyRule> = Update;\nupdateUserPhone#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<int> 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<int> 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 emojis:flags.1?true order:Vector<long> = 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<DialogPeer> = 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<int> = 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<FolderPeer> pts:int pts_count:int = Update;\nupdatePeerSettings#6a7e7366 peer:Peer settings:PeerSettings = Update;\nupdatePeerLocated#b4afcfb0 peers:Vector<PeerLocated> = Update;\nupdateNewScheduledMessage#39a51dfb message:Message = Update;\nupdateDeleteScheduledMessages#90866cee peer:Peer messages:Vector<int> = Update;\nupdateTheme#8216fba3 theme:Theme = Update;\nupdateGeoLiveViewed#871fb939 peer:Peer msg_id:int = Update;\nupdateLoginToken#564fe691 = Update;\nupdateMessagePollVote#106395c9 poll_id:long user_id:long options:Vector<bytes> qts:int = Update;\nupdateDialogFilter#26ffde7d flags:# id:int filter:flags.0?DialogFilter = Update;\nupdateDialogFilterOrder#a5d72105 order:Vector<int> = Update;\nupdateDialogFilters#3504914f = Update;\nupdatePhoneCallSignalingData#2661bf09 phone_call_id:long data:bytes = Update;\nupdateChannelMessageForwards#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<int> pts:int pts_count:int = Update;\nupdatePinnedChannelMessages#5bb98608 flags:# pinned:flags.0?true channel_id:long messages:Vector<int> pts:int pts_count:int = Update;\nupdateChat#f89a6a4e chat_id:long = Update;\nupdateGroupCallParticipants#f2ebdb4e call:InputGroupCall participants:Vector<GroupCallParticipant> 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<BotCommand> = Update;\nupdatePendingJoinRequests#7063c3db peer:Peer requests_pending:int recent_requesters:Vector<long> = 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;\nupdateAttachMenuBots#17b7a20b = Update;\nupdateWebViewResultSent#1592b79d query_id:long = Update;\nupdateBotMenuButton#14b85813 bot_id:long button:BotMenuButton = Update;\nupdateSavedRingtones#74d8be99 = Update;\nupdateTranscribedAudio#84cd5a flags:# pending:flags.0?true peer:Peer msg_id:int transcription_id:long text:string = Update;\nupdateReadFeaturedEmojiStickers#fb4c496c = Update;\nupdates.state#a56c2a3e pts:int qts:int date:int seq:int unread_count:int = updates.State;\nupdates.differenceEmpty#5d75a138 date:int seq:int = updates.Difference;\nupdates.difference#f49ca0 new_messages:Vector<Message> new_encrypted_messages:Vector<EncryptedMessage> other_updates:Vector<Update> chats:Vector<Chat> users:Vector<User> state:updates.State = updates.Difference;\nupdates.differenceSlice#a8fb1981 new_messages:Vector<Message> new_encrypted_messages:Vector<EncryptedMessage> other_updates:Vector<Update> chats:Vector<Chat> users:Vector<User> intermediate_state:updates.State = updates.Difference;\nupdates.differenceTooLong#4afe8f6d pts:int = updates.Difference;\nupdatesTooLong#e317af7e = Updates;\nupdateShortMessage#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<MessageEntity> 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<MessageEntity> ttl_period:flags.25?int = Updates;\nupdateShort#78d4dec1 update:Update date:int = Updates;\nupdatesCombined#725b04c3 updates:Vector<Update> users:Vector<User> chats:Vector<Chat> date:int seq_start:int seq:int = Updates;\nupdates#74ae4240 updates:Vector<Update> users:Vector<User> chats:Vector<Chat> date:int seq:int = Updates;\nupdateShortSentMessage#9015e101 flags:# out:flags.1?true id:int pts:int pts_count:int date:int media:flags.9?MessageMedia entities:flags.7?Vector<MessageEntity> ttl_period:flags.25?int = Updates;\nphotos.photos#8dca6aa5 photos:Vector<Photo> users:Vector<User> = photos.Photos;\nphotos.photosSlice#15051f54 count:int photos:Vector<Photo> users:Vector<User> = photos.Photos;\nphotos.photo#20212ca8 photo:Photo users:Vector<User> = photos.Photo;\nupload.file#96a18d5 type:storage.FileType mtime:int bytes:bytes = upload.File;\nupload.fileCdnRedirect#f18cda44 dc_id:int file_token:bytes encryption_key:bytes encryption_iv:bytes file_hashes:Vector<FileHash> = upload.File;\ndcOption#18b7a10d flags:# ipv6:flags.0?true media_only:flags.1?true tcpo_only:flags.2?true cdn:flags.3?true static:flags.4?true this_port_only:flags.5?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 force_try_ipv6:flags.14?true date:int expires:int test_mode:Bool this_dc:int dc_options:Vector<DcOption> dc_txt_domain_name:string chat_size_max:int megagroup_size_max:int forwarded_count_max:int online_update_period_ms:int offline_blur_timeout_ms:int offline_idle_timeout_ms:int online_cloud_timeout_ms:int notify_cloud_delay_ms:int notify_default_delay_ms:int push_chat_period_ms:int push_chat_limit:int saved_gifs_limit:int edit_time_limit:int revoke_time_limit:int revoke_pm_time_limit:int rating_e_decay:int stickers_recent_limit:int stickers_faved_limit:int channels_read_media_period:int tmp_sessions:flags.0?int pinned_dialogs_count_max:int pinned_infolder_count_max:int call_receive_timeout_ms:int call_ring_timeout_ms:int call_connect_timeout_ms:int call_packet_timeout_ms:int me_url_prefix:string autoupdate_url_prefix:flags.7?string gif_search_username:flags.9?string venue_search_username:flags.10?string img_search_username:flags.11?string static_maps_provider:flags.12?string caption_length_max:int message_length_max:int webfile_dc_id:int suggested_lang_code:flags.2?string lang_pack_version:flags.2?int base_lang_pack_version:flags.2?int = Config;\nnearestDc#8e1a1775 country:string this_dc:int nearest_dc:int = NearestDc;\nhelp.appUpdate#ccbbce30 flags:# can_not_skip:flags.0?true id:int version:string text:string entities:Vector<MessageEntity> document:flags.1?Document url:flags.2?string sticker:flags.3?Document = help.AppUpdate;\nhelp.noAppUpdate#c45a6536 = help.AppUpdate;\nhelp.inviteText#18cb9f78 message:string = help.InviteText;\nencryptedChatEmpty#ab7ec0a0 id:int = EncryptedChat;\nencryptedChatWaiting#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#a8008cd8 id:long access_hash:long size:long 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#8fd4c4d8 flags:# id:long access_hash:long file_reference:bytes date:int mime_type:string size:long thumbs:flags.0?Vector<PhotoSize> video_thumbs:flags.1?Vector<VideoSize> dc_id:int attributes:Vector<DocumentAttribute> = Document;\nhelp.support#17c6b5f6 phone_number:string user:User = help.Support;\nnotifyPeer#9fd40bd8 peer:Peer = NotifyPeer;\nnotifyUsers#b4c83b4c = NotifyPeer;\nnotifyChats#c007cec3 = NotifyPeer;\nnotifyBroadcasts#d612e8ef = NotifyPeer;\nsendMessageTypingAction#16bf744e = SendMessageAction;\nsendMessageCancelAction#fd5ec8f5 = SendMessageAction;\nsendMessageRecordVideoAction#a187d66f = SendMessageAction;\nsendMessageUploadVideoAction#e9763aec progress:int = SendMessageAction;\nsendMessageRecordAudioAction#d52f73f7 = SendMessageAction;\nsendMessageUploadAudioAction#f351d7ab progress:int = SendMessageAction;\nsendMessageUploadPhotoAction#d1d34a26 progress:int = SendMessageAction;\nsendMessageUploadDocumentAction#aa0cd9e4 progress:int = SendMessageAction;\nsendMessageGeoLocationAction#176f8ba1 = SendMessageAction;\nsendMessageChooseContactAction#628cbc6f = SendMessageAction;\nsendMessageGamePlayAction#dd6a8f48 = SendMessageAction;\nsendMessageRecordRoundAction#88f27fbc = SendMessageAction;\nsendMessageUploadRoundAction#243e1c66 progress:int = SendMessageAction;\nspeakingInGroupCallAction#d92c2285 = SendMessageAction;\nsendMessageHistoryImportAction#dbda9246 progress:int = SendMessageAction;\nsendMessageChooseStickerAction#b05ac6b1 = SendMessageAction;\nsendMessageEmojiInteraction#25972bcb emoticon:string msg_id:int interaction:DataJSON = SendMessageAction;\nsendMessageEmojiInteractionSeen#b665902e emoticon:string = SendMessageAction;\ncontacts.found#b3134d9d my_results:Vector<Peer> results:Vector<Peer> chats:Vector<Chat> users:Vector<User> = contacts.Found;\ninputPrivacyKeyStatusTimestamp#4f96cb18 = InputPrivacyKey;\ninputPrivacyKeyChatInvite#bdfb0426 = InputPrivacyKey;\ninputPrivacyKeyPhoneCall#fabadc5f = InputPrivacyKey;\ninputPrivacyKeyPhoneP2P#db9e70d2 = InputPrivacyKey;\ninputPrivacyKeyForwards#a4dd4c08 = InputPrivacyKey;\ninputPrivacyKeyProfilePhoto#5719bacc = InputPrivacyKey;\ninputPrivacyKeyPhoneNumber#352dafa = InputPrivacyKey;\ninputPrivacyKeyAddedByPhone#d1219bdd = InputPrivacyKey;\ninputPrivacyKeyVoiceMessages#aee69d68 = 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;\nprivacyKeyVoiceMessages#697f414 = PrivacyKey;\ninputPrivacyValueAllowContacts#d09e07b = InputPrivacyRule;\ninputPrivacyValueAllowAll#184b35ce = InputPrivacyRule;\ninputPrivacyValueAllowUsers#131cc67f users:Vector<InputUser> = InputPrivacyRule;\ninputPrivacyValueDisallowContacts#ba52007 = InputPrivacyRule;\ninputPrivacyValueDisallowAll#d66b66c9 = InputPrivacyRule;\ninputPrivacyValueDisallowUsers#90110467 users:Vector<InputUser> = InputPrivacyRule;\ninputPrivacyValueAllowChatParticipants#840649cf chats:Vector<long> = InputPrivacyRule;\ninputPrivacyValueDisallowChatParticipants#e94f0f86 chats:Vector<long> = InputPrivacyRule;\nprivacyValueAllowContacts#fffe1bac = PrivacyRule;\nprivacyValueAllowAll#65427b82 = PrivacyRule;\nprivacyValueAllowUsers#b8905fb2 users:Vector<long> = PrivacyRule;\nprivacyValueDisallowContacts#f888fa1a = PrivacyRule;\nprivacyValueDisallowAll#8b73e763 = PrivacyRule;\nprivacyValueDisallowUsers#e4621141 users:Vector<long> = PrivacyRule;\nprivacyValueAllowChatParticipants#6b134e8e chats:Vector<long> = PrivacyRule;\nprivacyValueDisallowChatParticipants#41c87565 chats:Vector<long> = PrivacyRule;\naccount.privacyRules#50a04e45 rules:Vector<PrivacyRule> chats:Vector<Chat> users:Vector<User> = account.PrivacyRules;\naccountDaysTTL#b8d0afdf days:int = AccountDaysTTL;\ndocumentAttributeImageSize#6c37c15c w:int h:int = DocumentAttribute;\ndocumentAttributeAnimated#11b58939 = DocumentAttribute;\ndocumentAttributeSticker#6319d612 flags:# mask:flags.1?true alt:string stickerset:InputStickerSet mask_coords:flags.0?MaskCoords = DocumentAttribute;\ndocumentAttributeVideo#ef02ce6 flags:# round_message:flags.0?true supports_streaming:flags.1?true duration:int w:int h:int = DocumentAttribute;\ndocumentAttributeAudio#9852f9c6 flags:# voice:flags.10?true duration:int title:flags.0?string performer:flags.1?string waveform:flags.2?bytes = DocumentAttribute;\ndocumentAttributeFilename#15590068 file_name:string = DocumentAttribute;\ndocumentAttributeHasStickers#9801d2f7 = DocumentAttribute;\ndocumentAttributeCustomEmoji#fd149899 flags:# free:flags.0?true alt:string stickerset:InputStickerSet = DocumentAttribute;\nmessages.stickersNotModified#f1749a22 = messages.Stickers;\nmessages.stickers#30a6ec7e hash:long stickers:Vector<Document> = messages.Stickers;\nstickerPack#12b299d4 emoticon:string documents:Vector<long> = StickerPack;\nmessages.allStickersNotModified#e86602c3 = messages.AllStickers;\nmessages.allStickers#cdbbcebb hash:long sets:Vector<StickerSet> = messages.AllStickers;\nmessages.affectedMessages#84d19185 pts:int pts_count:int = messages.AffectedMessages;\nwebPageEmpty#eb1477e8 id:long = WebPage;\nwebPagePending#c586da1c id:long date:int = WebPage;\nwebPage#e89c45b2 flags:# id:long url:string display_url:string hash:int type:flags.0?string site_name:flags.1?string title:flags.2?string description:flags.3?string photo:flags.4?Photo embed_url:flags.5?string embed_type:flags.5?string embed_width:flags.6?int embed_height:flags.6?int duration:flags.7?int author:flags.8?string document:flags.9?Document cached_page:flags.10?Page attributes:flags.12?Vector<WebPageAttribute> = WebPage;\nwebPageNotModified#7311ca11 flags:# cached_page_views:flags.0?int = WebPage;\nauthorization#ad01d61d flags:# current:flags.0?true official_app:flags.1?true password_pending:flags.2?true 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<Authorization> = account.Authorizations;\naccount.password#185b184f flags:# has_recovery:flags.0?true has_secure_values:flags.1?true has_password:flags.2?true current_algo:flags.2?PasswordKdfAlgo srp_B:flags.2?bytes srp_id:flags.2?long hint:flags.3?string email_unconfirmed_pattern:flags.4?string new_algo:PasswordKdfAlgo new_secure_algo:SecurePasswordKdfAlgo secure_random:bytes pending_reset_date:flags.5?int = account.Password;\naccount.passwordSettings#9a5c33e5 flags:# email:flags.0?string secure_settings:flags.1?SecureSecretSettings = account.PasswordSettings;\naccount.passwordInputSettings#c23727c9 flags:# new_algo:flags.0?PasswordKdfAlgo new_password_hash:flags.0?bytes hint:flags.0?string email:flags.1?string new_secure_settings:flags.2?SecureSecretSettings = account.PasswordInputSettings;\nauth.passwordRecovery#137948a5 email_pattern:string = auth.PasswordRecovery;\nreceivedNotifyMessage#a384b779 id:int flags:int = ReceivedNotifyMessage;\nchatInviteExported#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;\nchatInvitePublicJoinRequests#ed107ab7 = 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<User> = ChatInvite;\nchatInvitePeek#61695cb0 chat:Chat expires:int = ChatInvite;\ninputStickerSetEmpty#ffb62b95 = InputStickerSet;\ninputStickerSetID#9de7a269 id:long access_hash:long = InputStickerSet;\ninputStickerSetShortName#861cc8a0 short_name:string = InputStickerSet;\ninputStickerSetAnimatedEmoji#28703c8 = InputStickerSet;\ninputStickerSetDice#e67f520e emoticon:string = InputStickerSet;\ninputStickerSetAnimatedEmojiAnimations#cde3739 = InputStickerSet;\ninputStickerSetPremiumGifts#c88b3b02 = InputStickerSet;\nstickerSet#2dd14edc flags:# archived:flags.1?true official:flags.2?true masks:flags.3?true animated:flags.5?true videos:flags.6?true emojis:flags.7?true installed_date:flags.0?int id:long access_hash:long title:string short_name:string thumbs:flags.4?Vector<PhotoSize> thumb_dc_id:flags.4?int thumb_version:flags.4?int thumb_document_id:flags.8?long count:int hash:int = StickerSet;\nmessages.stickerSet#b60a24a6 set:StickerSet packs:Vector<StickerPack> documents:Vector<Document> = messages.StickerSet;\nmessages.stickerSetNotModified#d3f924eb = messages.StickerSet;\nbotCommand#c27ac8c7 command:string description:string = BotCommand;\nbotInfo#8f300b57 flags:# user_id:flags.0?long description:flags.1?string description_photo:flags.4?Photo description_document:flags.5?Document commands:flags.2?Vector<BotCommand> menu_button:flags.3?BotMenuButton = 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;\nkeyboardButtonWebView#13767230 text:string url:string = KeyboardButton;\nkeyboardButtonSimpleWebView#a0c0505c text:string url:string = KeyboardButton;\nkeyboardButtonRow#77608b83 buttons:Vector<KeyboardButton> = KeyboardButtonRow;\nreplyKeyboardHide#a03e5b85 flags:# selective:flags.2?true = ReplyMarkup;\nreplyKeyboardForceReply#86b40b08 flags:# single_use:flags.1?true selective:flags.2?true placeholder:flags.3?string = ReplyMarkup;\nreplyKeyboardMarkup#85dd99d1 flags:# resize:flags.0?true single_use:flags.1?true selective:flags.2?true rows:Vector<KeyboardButtonRow> placeholder:flags.3?string = ReplyMarkup;\nreplyInlineMarkup#48a30254 rows:Vector<KeyboardButtonRow> = ReplyMarkup;\nmessageEntityUnknown#bb92ba95 offset:int length:int = MessageEntity;\nmessageEntityMention#fa04579d offset:int length:int = MessageEntity;\nmessageEntityHashtag#6f635b0d offset:int length:int = MessageEntity;\nmessageEntityBotCommand#6cef8ac7 offset:int length:int = MessageEntity;\nmessageEntityUrl#6ed02538 offset:int length:int = MessageEntity;\nmessageEntityEmail#64e475c2 offset:int length:int = MessageEntity;\nmessageEntityBold#bd610bc9 offset:int length:int = MessageEntity;\nmessageEntityItalic#826f8b60 offset:int length:int = MessageEntity;\nmessageEntityCode#28a20571 offset:int length:int = MessageEntity;\nmessageEntityPre#73924be0 offset:int length:int language:string = MessageEntity;\nmessageEntityTextUrl#76a6d327 offset:int length:int url:string = MessageEntity;\nmessageEntityMentionName#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;\nmessageEntityCustomEmoji#c8cf05f8 offset:int length:int document_id:long = 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<Chat> users:Vector<User> = contacts.ResolvedPeer;\nmessageRange#ae30253 min_id:int max_id:int = MessageRange;\nupdates.channelDifferenceEmpty#3e11affb flags:# final:flags.0?true pts:int timeout:flags.1?int = updates.ChannelDifference;\nupdates.channelDifferenceTooLong#a4bcc6fe flags:# final:flags.0?true timeout:flags.1?int dialog:Dialog messages:Vector<Message> chats:Vector<Chat> users:Vector<User> = updates.ChannelDifference;\nupdates.channelDifference#2064674e flags:# final:flags.0?true pts:int timeout:flags.1?int new_messages:Vector<Message> other_updates:Vector<Update> chats:Vector<Chat> users:Vector<User> = updates.ChannelDifference;\nchannelMessagesFilterEmpty#94d42ee7 = ChannelMessagesFilter;\nchannelMessagesFilter#cd77d957 flags:# exclude_new_messages:flags.1?true ranges:Vector<MessageRange> = ChannelMessagesFilter;\nchannelParticipant#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<ChannelParticipant> chats:Vector<Chat> users:Vector<User> = channels.ChannelParticipants;\nchannels.channelParticipantsNotModified#f0173fe9 = channels.ChannelParticipants;\nchannels.channelParticipant#dfb80317 participant:ChannelParticipant chats:Vector<Chat> users:Vector<User> = channels.ChannelParticipant;\nhelp.termsOfService#780a0310 flags:# popup:flags.0?true id:DataJSON text:string entities:Vector<MessageEntity> min_age_confirm:flags.1?int = help.TermsOfService;\nmessages.savedGifsNotModified#e8025ca2 = messages.SavedGifs;\nmessages.savedGifs#84a02a0d hash:long gifs:Vector<Document> = messages.SavedGifs;\ninputBotInlineMessageMediaAuto#3380c786 flags:# message:string entities:flags.1?Vector<MessageEntity> reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageText#3dcd7a87 flags:# no_webpage:flags.0?true message:string entities:flags.1?Vector<MessageEntity> reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaGeo#96929a85 flags:# geo_point:InputGeoPoint heading:flags.0?int period:flags.1?int proximity_notification_radius:flags.3?int reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaVenue#417bbf11 flags:# geo_point:InputGeoPoint title:string address:string provider:string venue_id:string venue_type:string reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaContact#a6edbffd flags:# phone_number:string first_name:string last_name:string vcard:string reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageGame#4b425864 flags:# reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaInvoice#d7e78225 flags:# title:string description:string photo:flags.0?InputWebDocument invoice:Invoice payload:bytes provider:string provider_data:DataJSON reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineResult#88bf9319 flags:# id:string type:string title:flags.1?string description:flags.2?string url:flags.3?string thumb:flags.4?InputWebDocument content:flags.5?InputWebDocument send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultPhoto#a8d864a7 id:string type:string photo:InputPhoto send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultDocument#fff8fdc4 flags:# id:string type:string title:flags.1?string description:flags.2?string document:InputDocument send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultGame#4fa417f2 id:string short_name:string send_message:InputBotInlineMessage = InputBotInlineResult;\nbotInlineMessageMediaAuto#764cf810 flags:# message:string entities:flags.1?Vector<MessageEntity> reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageText#8c7f65e2 flags:# no_webpage:flags.0?true message:string entities:flags.1?Vector<MessageEntity> reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaGeo#51846fd flags:# geo:GeoPoint heading:flags.0?int period:flags.1?int proximity_notification_radius:flags.3?int reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaVenue#8a86659c flags:# geo:GeoPoint title:string address:string provider:string venue_id:string venue_type:string reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaContact#18d1cdc2 flags:# phone_number:string first_name:string last_name:string vcard:string reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaInvoice#354a9b09 flags:# shipping_address_requested:flags.1?true test:flags.3?true title:string description:string photo:flags.0?WebDocument currency:string total_amount:long reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineResult#11965f3a flags:# id:string type:string title:flags.1?string description:flags.2?string url:flags.3?string thumb:flags.4?WebDocument content:flags.5?WebDocument send_message:BotInlineMessage = BotInlineResult;\nbotInlineMediaResult#17db940b flags:# id:string type:string photo:flags.0?Photo document:flags.1?Document title:flags.2?string description:flags.3?string send_message:BotInlineMessage = BotInlineResult;\nmessages.botResults#947ca848 flags:# gallery:flags.0?true query_id:long next_offset:flags.1?string switch_pm:flags.2?InlineBotSwitchPM results:Vector<BotInlineResult> cache_time:int users:Vector<User> = messages.BotResults;\nexportedMessageLink#5dab1af4 link:string html:string = ExportedMessageLink;\nmessageFwdHeader#5f777dce flags:# imported:flags.7?true from_id:flags.0?Peer from_name:flags.5?string date:int channel_post:flags.2?int post_author:flags.3?string saved_from_peer:flags.4?Peer saved_from_msg_id:flags.4?int psa_type:flags.6?string = MessageFwdHeader;\nauth.codeTypeSms#72a3158c = auth.CodeType;\nauth.codeTypeCall#741cd3e3 = auth.CodeType;\nauth.codeTypeFlashCall#226ccefb = auth.CodeType;\nauth.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<Dialog> messages:Vector<Message> chats:Vector<Chat> users:Vector<User> state:updates.State = messages.PeerDialogs;\ntopPeer#edcdc05b peer:Peer rating:double = TopPeer;\ntopPeerCategoryBotsPM#ab661b5b = TopPeerCategory;\ntopPeerCategoryBotsInline#148677e2 = TopPeerCategory;\ntopPeerCategoryCorrespondents#637b7ed = TopPeerCategory;\ntopPeerCategoryGroups#bd17a14a = TopPeerCategory;\ntopPeerCategoryChannels#161d9628 = TopPeerCategory;\ntopPeerCategoryPhoneCalls#1e76a78c = TopPeerCategory;\ntopPeerCategoryForwardUsers#a8406ca9 = TopPeerCategory;\ntopPeerCategoryForwardChats#fbeec0f0 = TopPeerCategory;\ntopPeerCategoryPeers#fb834291 category:TopPeerCategory count:int peers:Vector<TopPeer> = TopPeerCategoryPeers;\ncontacts.topPeersNotModified#de266ef5 = contacts.TopPeers;\ncontacts.topPeers#70b772a8 categories:Vector<TopPeerCategoryPeers> chats:Vector<Chat> users:Vector<User> = contacts.TopPeers;\ncontacts.topPeersDisabled#b52c939d = contacts.TopPeers;\ndraftMessageEmpty#1b0c841a flags:# date:flags.0?int = DraftMessage;\ndraftMessage#fd8e711f flags:# no_webpage:flags.1?true reply_to_msg_id:flags.0?int message:string entities:flags.3?Vector<MessageEntity> date:int = DraftMessage;\nmessages.featuredStickersNotModified#c6dc0c66 count:int = messages.FeaturedStickers;\nmessages.featuredStickers#be382906 flags:# premium:flags.0?true hash:long count:int sets:Vector<StickerSetCovered> unread:Vector<long> = messages.FeaturedStickers;\nmessages.recentStickersNotModified#b17f890 = messages.RecentStickers;\nmessages.recentStickers#88d37c56 hash:long packs:Vector<StickerPack> stickers:Vector<Document> dates:Vector<int> = messages.RecentStickers;\nmessages.archivedStickers#4fcba9c8 count:int sets:Vector<StickerSetCovered> = messages.ArchivedStickers;\nmessages.stickerSetInstallResultSuccess#38641628 = messages.StickerSetInstallResult;\nmessages.stickerSetInstallResultArchive#35e410a8 sets:Vector<StickerSetCovered> = messages.StickerSetInstallResult;\nstickerSetCovered#6410a5d2 set:StickerSet cover:Document = StickerSetCovered;\nstickerSetMultiCovered#3407e51b set:StickerSet covers:Vector<Document> = StickerSetCovered;\nstickerSetFullCovered#1aed5ee5 set:StickerSet packs:Vector<StickerPack> documents:Vector<Document> = StickerSetCovered;\nmaskCoords#aed6dbb2 n:int x:double y:double zoom:double = MaskCoords;\ninputStickeredMediaPhoto#4a992157 id:InputPhoto = InputStickeredMedia;\ninputStickeredMediaDocument#438865b id:InputDocument = InputStickeredMedia;\ngame#bdf9653b flags:# id:long access_hash:long short_name:string title:string description:string photo:Photo document:flags.0?Document = Game;\ninputGameID#32c3e77 id:long access_hash:long = InputGame;\ninputGameShortName#c331e80a bot_id:InputUser short_name:string = InputGame;\nhighScore#73a379eb pos:int user_id:long score:int = HighScore;\nmessages.highScores#9a3bfd99 scores:Vector<HighScore> users:Vector<User> = messages.HighScores;\ntextEmpty#dc3d824f = RichText;\ntextPlain#744694e0 text:string = RichText;\ntextBold#6724abc4 text:RichText = RichText;\ntextItalic#d912a59c text:RichText = RichText;\ntextUnderline#c12622c4 text:RichText = RichText;\ntextStrike#9bf8bb95 text:RichText = RichText;\ntextFixed#6c3f19b9 text:RichText = RichText;\ntextUrl#3c2884c1 text:RichText url:string webpage_id:long = RichText;\ntextEmail#de5a0dd6 text:RichText email:string = RichText;\ntextConcat#7e6260d7 texts:Vector<RichText> = RichText;\ntextSubscript#ed6a8504 text:RichText = RichText;\ntextSuperscript#c7fb5e01 text:RichText = RichText;\ntextMarked#34b8621 text:RichText = RichText;\ntextPhone#1ccb966a text:RichText phone:string = RichText;\ntextImage#81ccf4f document_id:long w:int h:int = RichText;\ntextAnchor#35553762 text:RichText name:string = RichText;\npageBlockUnsupported#13567e8a = PageBlock;\npageBlockTitle#70abc3fd text:RichText = PageBlock;\npageBlockSubtitle#8ffa9a1f text:RichText = PageBlock;\npageBlockAuthorDate#baafe5e0 author:RichText published_date:int = PageBlock;\npageBlockHeader#bfd064ec text:RichText = PageBlock;\npageBlockSubheader#f12bb6e1 text:RichText = PageBlock;\npageBlockParagraph#467a0766 text:RichText = PageBlock;\npageBlockPreformatted#c070d93e text:RichText language:string = PageBlock;\npageBlockFooter#48870999 text:RichText = PageBlock;\npageBlockDivider#db20b188 = PageBlock;\npageBlockAnchor#ce0d37b0 name:string = PageBlock;\npageBlockList#e4e88011 items:Vector<PageListItem> = PageBlock;\npageBlockBlockquote#263d7c26 text:RichText caption:RichText = PageBlock;\npageBlockPullquote#4f4456d3 text:RichText caption:RichText = PageBlock;\npageBlockPhoto#1759c560 flags:# photo_id:long caption:PageCaption url:flags.0?string webpage_id:flags.0?long = PageBlock;\npageBlockVideo#7c8fe7b6 flags:# autoplay:flags.0?true loop:flags.1?true video_id:long caption:PageCaption = PageBlock;\npageBlockCover#39f23300 cover:PageBlock = PageBlock;\npageBlockEmbed#a8718dc5 flags:# full_width:flags.0?true allow_scrolling:flags.3?true url:flags.1?string html:flags.2?string poster_photo_id:flags.4?long w:flags.5?int h:flags.5?int caption:PageCaption = PageBlock;\npageBlockEmbedPost#f259a80b url:string webpage_id:long author_photo_id:long author:string date:int blocks:Vector<PageBlock> caption:PageCaption = PageBlock;\npageBlockCollage#65a0fa4d items:Vector<PageBlock> caption:PageCaption = PageBlock;\npageBlockSlideshow#31f9590 items:Vector<PageBlock> caption:PageCaption = PageBlock;\npageBlockChannel#ef1751b5 channel:Chat = PageBlock;\npageBlockAudio#804361ea audio_id:long caption:PageCaption = PageBlock;\npageBlockKicker#1e148390 text:RichText = PageBlock;\npageBlockTable#bf4dea82 flags:# bordered:flags.0?true striped:flags.1?true title:RichText rows:Vector<PageTableRow> = PageBlock;\npageBlockOrderedList#9a8ae1e1 items:Vector<PageListOrderedItem> = PageBlock;\npageBlockDetails#76768bed flags:# open:flags.0?true blocks:Vector<PageBlock> title:RichText = PageBlock;\npageBlockRelatedArticles#16115a96 title:RichText articles:Vector<PageRelatedArticle> = PageBlock;\npageBlockMap#a44f3ef6 geo:GeoPoint zoom:int w:int h:int caption:PageCaption = PageBlock;\nphoneCallDiscardReasonMissed#85e42301 = PhoneCallDiscardReason;\nphoneCallDiscardReasonDisconnect#e095c1a0 = PhoneCallDiscardReason;\nphoneCallDiscardReasonHangup#57adc690 = PhoneCallDiscardReason;\nphoneCallDiscardReasonBusy#faf7e8c9 = PhoneCallDiscardReason;\ndataJSON#7d748d04 data:string = DataJSON;\nlabeledPrice#cb296bf8 label:string amount:long = LabeledPrice;\ninvoice#3e85a91b 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 recurring:flags.9?true currency:string prices:Vector<LabeledPrice> max_tip_amount:flags.8?long suggested_tip_amounts:flags.8?Vector<long> recurring_terms_url:flags.9?string = Invoice;\npaymentCharge#ea02c27e id:string provider_charge_id:string = PaymentCharge;\npostAddress#1e8caaeb street_line1:string street_line2:string city:string state:string country_iso2:string post_code:string = PostAddress;\npaymentRequestedInfo#909c3f94 flags:# name:flags.0?string phone:flags.1?string email:flags.2?string shipping_address:flags.3?PostAddress = PaymentRequestedInfo;\npaymentSavedCredentialsCard#cdc27a1f id:string title:string = PaymentSavedCredentials;\nwebDocument#1c570ed1 url:string access_hash:long size:int mime_type:string attributes:Vector<DocumentAttribute> = WebDocument;\nwebDocumentNoProxy#f9c8bcc6 url:string size:int mime_type:string attributes:Vector<DocumentAttribute> = WebDocument;\ninputWebDocument#9bed434d url:string size:int mime_type:string attributes:Vector<DocumentAttribute> = InputWebDocument;\ninputWebFileLocation#c239d686 url:string access_hash:long = InputWebFileLocation;\ninputWebFileGeoPointLocation#9f2221c9 geo_point:InputGeoPoint access_hash:long w:int h:int zoom:int scale:int = InputWebFileLocation;\ninputWebFileAudioAlbumThumbLocation#f46fe924 flags:# document:flags.0?InputDocument title:flags.1?string performer:flags.1?string = InputWebFileLocation;\nupload.webFile#21e753bc size:int mime_type:string file_type:storage.FileType mtime:int bytes:bytes = upload.WebFile;\npayments.paymentForm#a0058751 flags:# can_save_credentials:flags.2?true password_missing:flags.3?true form_id:long bot_id:long title:string description:string photo:flags.5?WebDocument invoice:Invoice provider_id:long url:string native_provider:flags.4?string native_params:flags.4?DataJSON additional_methods:flags.6?Vector<PaymentFormMethod> saved_info:flags.0?PaymentRequestedInfo saved_credentials:flags.1?Vector<PaymentSavedCredentials> users:Vector<User> = payments.PaymentForm;\npayments.validatedRequestedInfo#d1451883 flags:# id:flags.0?string shipping_options:flags.1?Vector<ShippingOption> = payments.ValidatedRequestedInfo;\npayments.paymentResult#4e5f810d updates:Updates = payments.PaymentResult;\npayments.paymentVerificationNeeded#d8411139 url:string = payments.PaymentResult;\npayments.paymentReceipt#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<User> = payments.PaymentReceipt;\npayments.savedInfo#fb8fe43c flags:# has_saved_credentials:flags.1?true saved_info:flags.0?PaymentRequestedInfo = payments.SavedInfo;\ninputPaymentCredentialsSaved#c10eb2cf id:string tmp_password:bytes = InputPaymentCredentials;\ninputPaymentCredentials#3417d728 flags:# save:flags.0?true data:DataJSON = InputPaymentCredentials;\ninputPaymentCredentialsApplePay#aa1c39f payment_data:DataJSON = InputPaymentCredentials;\ninputPaymentCredentialsGooglePay#8ac32801 payment_token:DataJSON = InputPaymentCredentials;\naccount.tmpPassword#db64fd34 tmp_password:bytes valid_until:int = account.TmpPassword;\nshippingOption#b6213cdf id:string title:string prices:Vector<LabeledPrice> = ShippingOption;\ninputStickerSetItem#ffa0a496 flags:# document:InputDocument emoji:string mask_coords:flags.0?MaskCoords = InputStickerSetItem;\ninputPhoneCall#1e36fded id:long access_hash:long = InputPhoneCall;\nphoneCallEmpty#5366c915 id:long = PhoneCall;\nphoneCallWaiting#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<PhoneConnection> start_date:int = PhoneCall;\nphoneCallDiscarded#50ca4de1 flags:# need_rating:flags.2?true need_debug:flags.3?true video:flags.6?true id:long reason:flags.0?PhoneCallDiscardReason duration:flags.1?int = PhoneCall;\nphoneConnection#9cc123c7 flags:# tcp:flags.0?true id:long ip:string ipv6:string port:int peer_tag:bytes = PhoneConnection;\nphoneConnectionWebrtc#635fe375 flags:# turn:flags.0?true stun:flags.1?true id:long ip:string ipv6:string port:int username:string password:string = PhoneConnection;\nphoneCallProtocol#fc878fc8 flags:# udp_p2p:flags.0?true udp_reflector:flags.1?true min_layer:int max_layer:int library_versions:Vector<string> = PhoneCallProtocol;\nphone.phoneCall#ec82e140 phone_call:PhoneCall users:Vector<User> = phone.PhoneCall;\nupload.cdnFileReuploadNeeded#eea8e46e request_token:bytes = upload.CdnFile;\nupload.cdnFile#a99fca4f bytes:bytes = upload.CdnFile;\ncdnPublicKey#c982eaba dc_id:int public_key:string = CdnPublicKey;\ncdnConfig#5725e40a public_keys:Vector<CdnPublicKey> = CdnConfig;\nlangPackString#cad181f6 key:string value:string = LangPackString;\nlangPackStringPluralized#6c47ac9f flags:# key:string zero_value:flags.0?string one_value:flags.1?string two_value:flags.2?string few_value:flags.3?string many_value:flags.4?string other_value:string = LangPackString;\nlangPackStringDeleted#2979eeb2 key:string = LangPackString;\nlangPackDifference#f385c1f6 lang_code:string from_version:int version:int strings:Vector<LangPackString> = LangPackDifference;\nlangPackLanguage#eeca5ce3 flags:# official:flags.0?true rtl:flags.2?true beta:flags.3?true name:string native_name:string lang_code:string base_lang_code:flags.1?string plural_code:string strings_count:int translated_count:int translations_url:string = LangPackLanguage;\nchannelAdminLogEventActionChangeTitle#e6dfb825 prev_value:string new_value:string = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeAbout#55188a2e prev_value:string new_value:string = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeUsername#6a4afc38 prev_value:string new_value:string = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangePhoto#434bd2af prev_photo:Photo new_photo:Photo = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleInvites#1b7907ae new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleSignatures#26ae0971 new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionUpdatePinned#e9e82c18 message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionEditMessage#709b2405 prev_message:Message new_message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionDeleteMessage#42e047bb message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantJoin#183040d3 = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantLeave#f89777f2 = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantInvite#e31c34d8 participant:ChannelParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantToggleBan#e6d83d7e prev_participant:ChannelParticipant new_participant:ChannelParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantToggleAdmin#d5676710 prev_participant:ChannelParticipant new_participant:ChannelParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeStickerSet#b1c3caa7 prev_stickerset:InputStickerSet new_stickerset:InputStickerSet = ChannelAdminLogEventAction;\nchannelAdminLogEventActionTogglePreHistoryHidden#5f5c95f1 new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionDefaultBannedRights#2df5fc0a prev_banned_rights:ChatBannedRights new_banned_rights:ChatBannedRights = ChannelAdminLogEventAction;\nchannelAdminLogEventActionStopPoll#8f079643 message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeLinkedChat#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<string> new_value:Vector<string> = ChannelAdminLogEventAction;\nchannelAdminLogEvent#1fad68cd id:long date:int user_id:long action:ChannelAdminLogEventAction = ChannelAdminLogEvent;\nchannels.adminLogResults#ed8af74d events:Vector<ChannelAdminLogEvent> chats:Vector<Chat> users:Vector<User> = channels.AdminLogResults;\nchannelAdminLogEventsFilter#ea107ae4 flags:# join:flags.0?true leave:flags.1?true invite:flags.2?true ban:flags.3?true unban:flags.4?true kick:flags.5?true unkick:flags.6?true promote:flags.7?true demote:flags.8?true info:flags.9?true settings:flags.10?true pinned:flags.11?true edit:flags.12?true delete:flags.13?true group_call:flags.14?true invites:flags.15?true 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<StickerPack> stickers:Vector<Document> = 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<RecentMeUrl> chats:Vector<Chat> users:Vector<User> = help.RecentMeUrls;\ninputSingleMedia#1cc6e91f flags:# media:InputMedia random_id:long message:string entities:flags.0?Vector<MessageEntity> = InputSingleMedia;\nwebAuthorization#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<WebAuthorization> users:Vector<User> = account.WebAuthorizations;\ninputMessageID#a676a322 id:int = InputMessage;\ninputMessageReplyTo#bad88395 id:int = InputMessage;\ninputMessagePinned#86872538 = InputMessage;\ninputMessageCallbackQuery#acfa1a7e id:int query_id:long = InputMessage;\ninputDialogPeer#fcaafeb7 peer:InputPeer = InputDialogPeer;\ninputDialogPeerFolder#64600527 folder_id:int = InputDialogPeer;\ndialogPeer#e56dbf05 peer:Peer = DialogPeer;\ndialogPeerFolder#514519e2 folder_id:int = DialogPeer;\nmessages.foundStickerSetsNotModified#d54b65d = messages.FoundStickerSets;\nmessages.foundStickerSets#8af09dd2 hash:long sets:Vector<StickerSetCovered> = messages.FoundStickerSets;\nfileHash#f39b035c offset:long 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#7d09c27e id:long access_hash:long size:long dc_id:int date:int file_hash:bytes secret:bytes = SecureFile;\nsecureData#8aeabec3 data:bytes data_hash:bytes secret:bytes = SecureData;\nsecurePlainPhone#7d6099dd phone:string = SecurePlainData;\nsecurePlainEmail#21ec5a5f email:string = SecurePlainData;\nsecureValueTypePersonalDetails#9d2a81e3 = SecureValueType;\nsecureValueTypePassport#3dac6a00 = SecureValueType;\nsecureValueTypeDriverLicense#6e425c4 = SecureValueType;\nsecureValueTypeIdentityCard#a0d0744b = SecureValueType;\nsecureValueTypeInternalPassport#99a48f23 = SecureValueType;\nsecureValueTypeAddress#cbe31e26 = SecureValueType;\nsecureValueTypeUtilityBill#fc36954e = SecureValueType;\nsecureValueTypeBankStatement#89137c0d = SecureValueType;\nsecureValueTypeRentalAgreement#8b883488 = SecureValueType;\nsecureValueTypePassportRegistration#99e3806a = SecureValueType;\nsecureValueTypeTemporaryRegistration#ea02ec33 = SecureValueType;\nsecureValueTypePhone#b320aadb = SecureValueType;\nsecureValueTypeEmail#8e3ca7ee = SecureValueType;\nsecureValue#187fa0ca flags:# type:SecureValueType data:flags.0?SecureData front_side:flags.1?SecureFile reverse_side:flags.2?SecureFile selfie:flags.3?SecureFile translation:flags.6?Vector<SecureFile> files:flags.4?Vector<SecureFile> plain_data:flags.5?SecurePlainData hash:bytes = SecureValue;\ninputSecureValue#db21d0a7 flags:# type:SecureValueType data:flags.0?SecureData front_side:flags.1?InputSecureFile reverse_side:flags.2?InputSecureFile selfie:flags.3?InputSecureFile translation:flags.6?Vector<InputSecureFile> files:flags.4?Vector<InputSecureFile> plain_data:flags.5?SecurePlainData = InputSecureValue;\nsecureValueHash#ed1ecdb0 type:SecureValueType hash:bytes = SecureValueHash;\nsecureValueErrorData#e8a40bd9 type:SecureValueType data_hash:bytes field:string text:string = SecureValueError;\nsecureValueErrorFrontSide#be3dfa type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorReverseSide#868a2aa5 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorSelfie#e537ced6 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorFile#7a700873 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorFiles#666220e9 type:SecureValueType file_hash:Vector<bytes> text:string = SecureValueError;\nsecureValueError#869d758f type:SecureValueType hash:bytes text:string = SecureValueError;\nsecureValueErrorTranslationFile#a1144770 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorTranslationFiles#34636dd8 type:SecureValueType file_hash:Vector<bytes> text:string = SecureValueError;\nsecureCredentialsEncrypted#33f0ea47 data:bytes hash:bytes secret:bytes = SecureCredentialsEncrypted;\naccount.authorizationForm#ad2e1cd8 flags:# required_types:Vector<SecureRequiredType> values:Vector<SecureValue> errors:Vector<SecureValueError> users:Vector<User> privacy_policy_url:flags.0?string = account.AuthorizationForm;\naccount.sentEmailCode#811f854f email_pattern:string length:int = account.SentEmailCode;\nhelp.deepLinkInfoEmpty#66afa166 = help.DeepLinkInfo;\nhelp.deepLinkInfo#6a4ee832 flags:# update_app:flags.0?true message:string entities:flags.1?Vector<MessageEntity> = help.DeepLinkInfo;\nsavedPhoneContact#1142bd56 phone:string first_name:string last_name:string date:int = SavedContact;\naccount.takeout#4dba4501 id:long = account.Takeout;\npasswordKdfAlgoUnknown#d45ab096 = PasswordKdfAlgo;\npasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow#3a912d4a salt1:bytes salt2:bytes g:int p:bytes = PasswordKdfAlgo;\nsecurePasswordKdfAlgoUnknown#4a8537 = SecurePasswordKdfAlgo;\nsecurePasswordKdfAlgoPBKDF2HMACSHA512iter100000#bbf2dda0 salt:bytes = SecurePasswordKdfAlgo;\nsecurePasswordKdfAlgoSHA512#86471d92 salt:bytes = SecurePasswordKdfAlgo;\nsecureSecretSettings#1527bcac secure_algo:SecurePasswordKdfAlgo secure_secret:bytes secure_secret_id:long = SecureSecretSettings;\ninputCheckPasswordEmpty#9880f658 = InputCheckPasswordSRP;\ninputCheckPasswordSRP#d27ff082 srp_id:long A:bytes M1:bytes = InputCheckPasswordSRP;\nsecureRequiredType#829d99da flags:# native_names:flags.0?true selfie_required:flags.1?true translation_required:flags.2?true type:SecureValueType = SecureRequiredType;\nsecureRequiredTypeOneOf#27477b4 types:Vector<SecureRequiredType> = SecureRequiredType;\nhelp.passportConfigNotModified#bfb9f457 = help.PassportConfig;\nhelp.passportConfig#a098d6af hash:int countries_langs:DataJSON = help.PassportConfig;\ninputAppEvent#1d1b1245 time:double type:string peer:long data:JSONValue = InputAppEvent;\njsonObjectValue#c0de1bd9 key:string value:JSONValue = JSONObjectValue;\njsonNull#3f6d7b68 = JSONValue;\njsonBool#c7345e6a value:Bool = JSONValue;\njsonNumber#2be0dfa4 value:double = JSONValue;\njsonString#b71e767a value:string = JSONValue;\njsonArray#f7444763 value:Vector<JSONValue> = JSONValue;\njsonObject#99c1d49d value:Vector<JSONObjectValue> = JSONValue;\npageTableCell#34566b6a flags:# header:flags.0?true align_center:flags.3?true align_right:flags.4?true valign_middle:flags.5?true valign_bottom:flags.6?true text:flags.7?RichText colspan:flags.1?int rowspan:flags.2?int = PageTableCell;\npageTableRow#e0c0c5e5 cells:Vector<PageTableCell> = PageTableRow;\npageCaption#6f747657 text:RichText credit:RichText = PageCaption;\npageListItemText#b92fb6cd text:RichText = PageListItem;\npageListItemBlocks#25e073fc blocks:Vector<PageBlock> = PageListItem;\npageListOrderedItemText#5e068047 num:string text:RichText = PageListOrderedItem;\npageListOrderedItemBlocks#98dd8936 num:string blocks:Vector<PageBlock> = PageListOrderedItem;\npageRelatedArticle#b390dc08 flags:# url:string webpage_id:long title:flags.0?string description:flags.1?string photo_id:flags.2?long author:flags.3?string published_date:flags.4?int = PageRelatedArticle;\npage#98657f0d flags:# part:flags.0?true rtl:flags.1?true v2:flags.2?true url:string blocks:Vector<PageBlock> photos:Vector<Photo> documents:Vector<Document> views:flags.3?int = Page;\nhelp.supportName#8c05f1c9 name:string = help.SupportName;\nhelp.userInfoEmpty#f3ae2eed = help.UserInfo;\nhelp.userInfo#1eb3758 message:string entities:Vector<MessageEntity> author:string date:int = help.UserInfo;\npollAnswer#6ca9c2e9 text:string option:bytes = PollAnswer;\npoll#86e18161 id:long flags:# closed:flags.0?true public_voters:flags.1?true multiple_choice:flags.2?true quiz:flags.3?true question:string answers:Vector<PollAnswer> close_period:flags.4?int close_date:flags.5?int = Poll;\npollAnswerVoters#3b6ddad2 flags:# chosen:flags.0?true correct:flags.1?true option:bytes voters:int = PollAnswerVoters;\npollResults#dcb82ea3 flags:# min:flags.0?true results:flags.1?Vector<PollAnswerVoters> total_voters:flags.2?int recent_voters:flags.3?Vector<long> solution:flags.4?string solution_entities:flags.4?Vector<MessageEntity> = PollResults;\nchatOnlines#f041e250 onlines:int = ChatOnlines;\nstatsURL#47a971e0 url:string = StatsURL;\nchatAdminRights#5fb224d5 flags:# change_info:flags.0?true post_messages:flags.1?true edit_messages:flags.2?true delete_messages:flags.3?true ban_users:flags.4?true invite_users:flags.5?true pin_messages:flags.7?true add_admins:flags.9?true anonymous:flags.10?true manage_call:flags.11?true other:flags.12?true = ChatAdminRights;\nchatBannedRights#9f120418 flags:# view_messages:flags.0?true send_messages:flags.1?true send_media:flags.2?true send_stickers:flags.3?true send_gifs:flags.4?true send_games:flags.5?true send_inline:flags.6?true embed_links:flags.7?true send_polls:flags.8?true change_info:flags.10?true invite_users:flags.15?true pin_messages:flags.17?true until_date:int = ChatBannedRights;\ninputWallPaper#e630b979 id:long access_hash:long = InputWallPaper;\ninputWallPaperSlug#72091c80 slug:string = InputWallPaper;\ninputWallPaperNoFile#967a462e id:long = InputWallPaper;\naccount.wallPapersNotModified#1c199183 = account.WallPapers;\naccount.wallPapers#cdc3858c hash:long wallpapers:Vector<WallPaper> = 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<bytes> = 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#8efab953 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:long file_size_max:long video_upload_maxbitrate:int = AutoDownloadSettings;\naccount.autoDownloadSettings#63cacf26 low:AutoDownloadSettings medium:AutoDownloadSettings high:AutoDownloadSettings = account.AutoDownloadSettings;\nemojiKeyword#d5b3b9f9 keyword:string emoticons:Vector<string> = EmojiKeyword;\nemojiKeywordDeleted#236df622 keyword:string emoticons:Vector<string> = EmojiKeyword;\nemojiKeywordsDifference#5cc761bd lang_code:string from_version:int version:int keywords:Vector<EmojiKeyword> = EmojiKeywordsDifference;\nemojiURL#a575739d url:string = EmojiURL;\nemojiLanguage#b3fb5361 lang_code:string = EmojiLanguage;\nfolder#ff544e65 flags:# autofill_new_broadcasts:flags.0?true autofill_public_groups:flags.1?true autofill_new_correspondents:flags.2?true id:int title:string photo:flags.3?ChatPhoto = Folder;\ninputFolderPeer#fbd2c296 peer:InputPeer folder_id:int = InputFolderPeer;\nfolderPeer#e9baa668 peer:Peer folder_id:int = FolderPeer;\nmessages.searchCounter#e844ebff flags:# inexact:flags.1?true filter:MessagesFilter count:int = messages.SearchCounter;\nurlAuthResultRequest#92d33a0e flags:# request_write_access:flags.0?true bot:User domain:string = UrlAuthResult;\nurlAuthResultAccepted#8f8c0e4e url:string = UrlAuthResult;\nurlAuthResultDefault#a9d6db1f = UrlAuthResult;\nchannelLocationEmpty#bfb5ad8b = ChannelLocation;\nchannelLocation#209b82db geo_point:GeoPoint address:string = ChannelLocation;\npeerLocated#ca461b5d peer:Peer expires:int distance:int = PeerLocated;\npeerSelfLocated#f8ec284b expires:int = PeerLocated;\nrestrictionReason#d072acb4 platform:string reason:string text:string = RestrictionReason;\ninputTheme#3c5693e9 id:long access_hash:long = InputTheme;\ninputThemeSlug#f5890df1 slug:string = InputTheme;\ntheme#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<ThemeSettings> emoticon:flags.6?string installs_count:flags.4?int = Theme;\naccount.themesNotModified#f41eb622 = account.Themes;\naccount.themes#9a3d8c6d hash:long themes:Vector<Theme> = account.Themes;\nauth.loginToken#629f1980 expires:int token:bytes = auth.LoginToken;\nauth.loginTokenMigrateTo#68e9916 dc_id:int token:bytes = auth.LoginToken;\nauth.loginTokenSuccess#390d5c5e authorization:auth.Authorization = auth.LoginToken;\naccount.contentSettings#57e28221 flags:# sensitive_enabled:flags.0?true sensitive_can_change:flags.1?true = account.ContentSettings;\nmessages.inactiveChats#a927fec5 dates:Vector<int> chats:Vector<Chat> users:Vector<User> = messages.InactiveChats;\nbaseThemeClassic#c3a12462 = BaseTheme;\nbaseThemeDay#fbd81688 = BaseTheme;\nbaseThemeNight#b7b31ea8 = BaseTheme;\nbaseThemeTinted#6d5f77ee = BaseTheme;\nbaseThemeArctic#5b11125a = BaseTheme;\ninputThemeSettings#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<int> 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<int> wallpaper:flags.1?WallPaper = ThemeSettings;\nwebPageAttributeTheme#54b56617 flags:# documents:flags.0?Vector<Document> 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<bytes> date:int = MessageUserVote;\nmessages.votesList#823f649 flags:# count:int votes:Vector<MessageUserVote> users:Vector<User> next_offset:flags.0?string = messages.VotesList;\nbankCardOpenUrl#f568028a url:string name:string = BankCardOpenUrl;\npayments.bankCardData#3e24e573 title:string open_urls:Vector<BankCardOpenUrl> = payments.BankCardData;\ndialogFilter#7438f7e8 flags:# contacts:flags.0?true non_contacts:flags.1?true groups:flags.2?true broadcasts:flags.3?true bots:flags.4?true exclude_muted:flags.11?true exclude_read:flags.12?true exclude_archived:flags.13?true id:int title:string emoticon:flags.25?string pinned_peers:Vector<InputPeer> include_peers:Vector<InputPeer> exclude_peers:Vector<InputPeer> = DialogFilter;\ndialogFilterDefault#363293ae = DialogFilter;\ndialogFilterSuggested#77744d4a filter:DialogFilter description:string = DialogFilterSuggested;\nstatsDateRangeDays#b637edaf min_date:int max_date:int = StatsDateRangeDays;\nstatsAbsValueAndPrev#cb43acde current:double previous:double = StatsAbsValueAndPrev;\nstatsPercentValue#cbce2fe0 part:double total:double = StatsPercentValue;\nstatsGraphAsync#4a27eb2d token:string = StatsGraph;\nstatsGraphError#bedc9822 error:string = StatsGraph;\nstatsGraph#8ea464b6 flags:# json:DataJSON zoom_token:flags.0?string = StatsGraph;\nmessageInteractionCounters#ad4fc9bd msg_id:int views:int forwards:int = MessageInteractionCounters;\nstats.broadcastStats#bdf78394 period:StatsDateRangeDays followers:StatsAbsValueAndPrev views_per_post:StatsAbsValueAndPrev shares_per_post:StatsAbsValueAndPrev enabled_notifications:StatsPercentValue growth_graph:StatsGraph followers_graph:StatsGraph mute_graph:StatsGraph top_hours_graph:StatsGraph interactions_graph:StatsGraph iv_interactions_graph:StatsGraph views_by_source_graph:StatsGraph new_followers_by_source_graph:StatsGraph languages_graph:StatsGraph recent_message_interactions:Vector<MessageInteractionCounters> = stats.BroadcastStats;\nhelp.promoDataEmpty#98f6ac75 expires:int = help.PromoData;\nhelp.promoData#8c39793f flags:# proxy:flags.0?true expires:int peer:Peer chats:Vector<Chat> users:Vector<User> psa_type:flags.1?string psa_message:flags.2?string = help.PromoData;\nvideoSize#de33b094 flags:# type:string w:int h:int size:int video_start_ts:flags.0?double = VideoSize;\nstatsGroupTopPoster#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<StatsGroupTopPoster> top_admins:Vector<StatsGroupTopAdmin> top_inviters:Vector<StatsGroupTopInviter> users:Vector<User> = stats.MegagroupStats;\nglobalPrivacySettings#bea2f424 flags:# archive_and_mute_new_noncontact_peers:flags.0?Bool = GlobalPrivacySettings;\nhelp.countryCode#4203c5ef flags:# country_code:string prefixes:flags.0?Vector<string> patterns:flags.1?Vector<string> = help.CountryCode;\nhelp.country#c3878e23 flags:# hidden:flags.0?true iso2:string default_name:string name:flags.1?string country_codes:Vector<help.CountryCode> = help.Country;\nhelp.countriesListNotModified#93cc1f32 = help.CountriesList;\nhelp.countriesList#87d0759e countries:Vector<help.Country> hash:int = help.CountriesList;\nmessageViews#455b853d flags:# views:flags.0?int forwards:flags.1?int replies:flags.2?MessageReplies = MessageViews;\nmessages.messageViews#b6c4f543 views:Vector<MessageViews> chats:Vector<Chat> users:Vector<User> = messages.MessageViews;\nmessages.discussionMessage#a6341782 flags:# messages:Vector<Message> max_id:flags.0?int read_inbox_max_id:flags.1?int read_outbox_max_id:flags.2?int unread_count:int chats:Vector<Chat> users:Vector<User> = messages.DiscussionMessage;\nmessageReplyHeader#a6d57763 flags:# reply_to_scheduled:flags.2?true 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<Peer> 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 rtmp_stream:flags.12?true listeners_hidden:flags.13?true id:long access_hash:long participants_count:int title:flags.3?string stream_dc_id:flags.4?int record_start_date:flags.5?int schedule_date:flags.7?int unmuted_video_count:flags.10?int unmuted_video_limit:int version:int = GroupCall;\ninputGroupCall#d8aa840f id:long access_hash:long = InputGroupCall;\ngroupCallParticipant#eba636fe flags:# muted:flags.0?true left:flags.1?true can_self_unmute:flags.2?true just_joined:flags.4?true versioned:flags.5?true min:flags.8?true muted_by_you:flags.9?true volume_by_admin:flags.10?true self:flags.12?true video_joined:flags.15?true peer:Peer date:int active_date:flags.3?int source:int volume:flags.7?int about:flags.11?string raise_hand_rating:flags.13?long video:flags.6?GroupCallParticipantVideo presentation:flags.14?GroupCallParticipantVideo = GroupCallParticipant;\nphone.groupCall#9e727aad call:GroupCall participants:Vector<GroupCallParticipant> participants_next_offset:string chats:Vector<Chat> users:Vector<User> = phone.GroupCall;\nphone.groupParticipants#f47751b6 count:int participants:Vector<GroupCallParticipant> next_offset:string chats:Vector<Chat> users:Vector<User> version:int = phone.GroupParticipants;\ninlineQueryPeerTypeSameBotPM#3081ed9d = InlineQueryPeerType;\ninlineQueryPeerTypePM#833c0fac = InlineQueryPeerType;\ninlineQueryPeerTypeChat#d766c50a = InlineQueryPeerType;\ninlineQueryPeerTypeMegagroup#5ec4be43 = InlineQueryPeerType;\ninlineQueryPeerTypeBroadcast#6334ee9a = InlineQueryPeerType;\nmessages.historyImport#1662af0b id:long = messages.HistoryImport;\nmessages.historyImportParsed#5e0fb7b9 flags:# pm:flags.0?true group:flags.1?true title:flags.2?string = messages.HistoryImportParsed;\nmessages.affectedFoundMessages#ef8d3e6c pts:int pts_count:int offset:int messages:Vector<int> = messages.AffectedFoundMessages;\nchatInviteImporter#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<ExportedChatInvite> users:Vector<User> = messages.ExportedChatInvites;\nmessages.exportedChatInvite#1871be50 invite:ExportedChatInvite users:Vector<User> = messages.ExportedChatInvite;\nmessages.exportedChatInviteReplaced#222600ef invite:ExportedChatInvite new_invite:ExportedChatInvite users:Vector<User> = messages.ExportedChatInvite;\nmessages.chatInviteImporters#81b6b00a count:int importers:Vector<ChatInviteImporter> users:Vector<User> = messages.ChatInviteImporters;\nchatAdminWithInvites#f2ecef23 admin_id:long invites_count:int revoked_invites_count:int = ChatAdminWithInvites;\nmessages.chatAdminsWithInvites#b69b72d7 admins:Vector<ChatAdminWithInvites> users:Vector<User> = messages.ChatAdminsWithInvites;\nmessages.checkedHistoryImportPeer#a24de717 confirm_text:string = messages.CheckedHistoryImportPeer;\nphone.joinAsPeers#afe5623f peers:Vector<Peer> chats:Vector<Chat> users:Vector<User> = phone.JoinAsPeers;\nphone.exportedGroupCallInvite#204bd158 link:string = phone.ExportedGroupCallInvite;\ngroupCallParticipantVideoSourceGroup#dcb118b7 semantics:string sources:Vector<int> = GroupCallParticipantVideoSourceGroup;\ngroupCallParticipantVideo#67753ac8 flags:# paused:flags.0?true endpoint:string source_groups:Vector<GroupCallParticipantVideoSourceGroup> audio_source:flags.1?int = GroupCallParticipantVideo;\nstickers.suggestedShortName#85fea03f short_name:string = stickers.SuggestedShortName;\nbotCommandScopeDefault#2f6cb2ab = BotCommandScope;\nbotCommandScopeUsers#3c4f04d8 = BotCommandScope;\nbotCommandScopeChats#6fe1a881 = BotCommandScope;\nbotCommandScopeChatAdmins#b9aa606a = BotCommandScope;\nbotCommandScopePeer#db9d897d peer:InputPeer = BotCommandScope;\nbotCommandScopePeerAdmins#3fd863d1 peer:InputPeer = BotCommandScope;\nbotCommandScopePeerUser#a1321f3 peer:InputPeer user_id:InputUser = BotCommandScope;\naccount.resetPasswordFailedWait#e3779861 retry_date:int = account.ResetPasswordResult;\naccount.resetPasswordRequestedWait#e9effc7d until_date:int = account.ResetPasswordResult;\naccount.resetPasswordOk#e926d63e = account.ResetPasswordResult;\nsponsoredMessage#3a836df8 flags:# recommended:flags.5?true 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<MessageEntity> = SponsoredMessage;\nmessages.sponsoredMessages#65a4c7d5 messages:Vector<SponsoredMessage> chats:Vector<Chat> users:Vector<User> = 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<SearchResultsCalendarPeriod> messages:Vector<Message> chats:Vector<Chat> users:Vector<User> = messages.SearchResultsCalendar;\nsearchResultPosition#7f648b67 msg_id:int date:int offset:int = SearchResultsPosition;\nmessages.searchResultsPositions#53b22baf count:int positions:Vector<SearchResultsPosition> = messages.SearchResultsPositions;\nchannels.sendAsPeers#8356cda9 peers:Vector<Peer> chats:Vector<Chat> users:Vector<User> = channels.SendAsPeers;\nusers.userFull#3b6d152e full_user:UserFull chats:Vector<Chat> users:Vector<User> = users.UserFull;\nmessages.peerSettings#6880b94d settings:PeerSettings chats:Vector<Chat> users:Vector<User> = 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#4f2b9479 flags:# min:flags.0?true can_see_list:flags.2?true results:Vector<ReactionCount> recent_reactions:flags.1?Vector<MessagePeerReaction> = MessageReactions;\nmessages.messageReactionsList#31bd492d flags:# count:int reactions:Vector<MessagePeerReaction> chats:Vector<Chat> users:Vector<User> next_offset:flags.0?string = messages.MessageReactionsList;\navailableReaction#c077ec01 flags:# inactive:flags.0?true premium:flags.2?true reaction:string title:string static_icon:Document appear_animation:Document select_animation:Document activate_animation:Document effect_animation:Document around_animation:flags.1?Document center_icon:flags.1?Document = AvailableReaction;\nmessages.availableReactionsNotModified#9f071957 = messages.AvailableReactions;\nmessages.availableReactions#768e3aad hash:int reactions:Vector<AvailableReaction> = messages.AvailableReactions;\nmessages.translateNoResult#67ca4737 = messages.TranslatedText;\nmessages.translateResultText#a214f7d0 text:string = messages.TranslatedText;\nmessagePeerReaction#51b67eff flags:# big:flags.0?true unread:flags.1?true peer_id:Peer reaction:string = MessagePeerReaction;\ngroupCallStreamChannel#80eb48af channel:int scale:int last_timestamp_ms:long = GroupCallStreamChannel;\nphone.groupCallStreamChannels#d0e482b2 channels:Vector<GroupCallStreamChannel> = phone.GroupCallStreamChannels;\nphone.groupCallStreamRtmpUrl#2dbf3432 url:string key:string = phone.GroupCallStreamRtmpUrl;\nattachMenuBotIconColor#4576f3f0 name:string color:int = AttachMenuBotIconColor;\nattachMenuBotIcon#b2a7386b flags:# name:string icon:Document colors:flags.0?Vector<AttachMenuBotIconColor> = AttachMenuBotIcon;\nattachMenuBot#c8aa2cd2 flags:# inactive:flags.0?true has_settings:flags.1?true bot_id:long short_name:string peer_types:Vector<AttachMenuPeerType> icons:Vector<AttachMenuBotIcon> = AttachMenuBot;\nattachMenuBotsNotModified#f1d88a5c = AttachMenuBots;\nattachMenuBots#3c4301c0 hash:long bots:Vector<AttachMenuBot> users:Vector<User> = AttachMenuBots;\nattachMenuBotsBot#93bf667f bot:AttachMenuBot users:Vector<User> = AttachMenuBotsBot;\nwebViewResultUrl#c14557c query_id:long url:string = WebViewResult;\nsimpleWebViewResultUrl#882f76bb url:string = SimpleWebViewResult;\nwebViewMessageSent#c94511c flags:# msg_id:flags.0?InputBotInlineMessageID = WebViewMessageSent;\nbotMenuButtonDefault#7533a588 = BotMenuButton;\nbotMenuButtonCommands#4258c205 = BotMenuButton;\nbotMenuButton#c7b57ce6 text:string url:string = BotMenuButton;\naccount.savedRingtonesNotModified#fbf6e8b1 = account.SavedRingtones;\naccount.savedRingtones#c1e92cc5 hash:long ringtones:Vector<Document> = account.SavedRingtones;\nnotificationSoundDefault#97e8bebe = NotificationSound;\nnotificationSoundNone#6f0c34df = NotificationSound;\nnotificationSoundLocal#830b9ae4 title:string data:string = NotificationSound;\nnotificationSoundRingtone#ff6c8049 id:long = NotificationSound;\naccount.savedRingtone#b7263f6d = account.SavedRingtone;\naccount.savedRingtoneConverted#1f307eb7 document:Document = account.SavedRingtone;\nattachMenuPeerTypeSameBotPM#7d6be90e = AttachMenuPeerType;\nattachMenuPeerTypeBotPM#c32bfa1a = AttachMenuPeerType;\nattachMenuPeerTypePM#f146d31f = AttachMenuPeerType;\nattachMenuPeerTypeChat#509113f = AttachMenuPeerType;\nattachMenuPeerTypeBroadcast#7bfbdefc = AttachMenuPeerType;\ninputInvoiceMessage#c5b56859 peer:InputPeer msg_id:int = InputInvoice;\ninputInvoiceSlug#c326caef slug:string = InputInvoice;\npayments.exportedInvoice#aed0cbd9 url:string = payments.ExportedInvoice;\nmessages.transcribedAudio#93752c52 flags:# pending:flags.0?true transcription_id:long text:string = messages.TranscribedAudio;\nhelp.premiumPromo#8a4f3c29 status_text:string status_entities:Vector<MessageEntity> video_sections:Vector<string> videos:Vector<Document> currency:string monthly_amount:long users:Vector<User> = help.PremiumPromo;\ninputStorePaymentPremiumSubscription#a6751e66 flags:# restore:flags.0?true = InputStorePaymentPurpose;\ninputStorePaymentGiftPremium#616f7fe8 user_id:InputUser currency:string amount:long = InputStorePaymentPurpose;\npremiumGiftOption#74c34319 flags:# months:int currency:string amount:long bot_url:string store_product:flags.0?string = PremiumGiftOption;\npaymentFormMethod#88f8f21b url:string title:string = PaymentFormMethod;\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<long> = Bool;\nauth.exportLoginToken#b7e085fe api_id:int api_hash:string except_ids:Vector<long> = 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<long> = Bool;\naccount.unregisterDevice#6a0d3206 token_type:int token:string other_uids:Vector<long> = 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.reportPeer#c5ba3d86 peer:InputPeer reason:ReportReason message:string = Bool;\naccount.checkUsername#2714d86c username:string = Bool;\naccount.updateUsername#3e0bdd7c username:string = User;\naccount.getPrivacy#dadbc950 key:InputPrivacyKey = account.PrivacyRules;\naccount.setPrivacy#c9f81ce8 key:InputPrivacyKey rules:Vector<InputPrivacyRule> = account.PrivacyRules;\naccount.getAuthorizations#e320c158 = account.Authorizations;\naccount.resetAuthorization#df77f3bc hash:long = Bool;\naccount.getPassword#548a30f5 = account.Password;\naccount.getPasswordSettings#9cd4eaf9 password:InputCheckPasswordSRP = account.PasswordSettings;\naccount.updatePasswordSettings#a59b102f password:InputCheckPasswordSRP new_settings:account.PasswordInputSettings = Bool;\naccount.sendConfirmPhoneCode#1b3faa88 hash:string settings:CodeSettings = auth.SentCode;\naccount.confirmPhone#5f2178c3 phone_code_hash:string phone_code:string = Bool;\naccount.getTmpPassword#449e0b51 password:InputCheckPasswordSRP period:int = account.TmpPassword;\naccount.getWebAuthorizations#182e6d6f = account.WebAuthorizations;\naccount.resetWebAuthorization#2d01b9ef hash:long = Bool;\naccount.resetWebAuthorizations#682d2594 = Bool;\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;\naccount.getGlobalPrivacySettings#eb2b4cf6 = GlobalPrivacySettings;\naccount.setGlobalPrivacySettings#1edaaac2 settings:GlobalPrivacySettings = GlobalPrivacySettings;\naccount.reportProfilePhoto#fa8cc6f5 peer:InputPeer photo_id:InputPhoto reason:ReportReason message:string = Bool;\naccount.setAuthorizationTTL#bf899aa0 authorization_ttl_days:int = Bool;\naccount.changeAuthorizationSettings#40f48462 flags:# hash:long encrypted_requests_disabled:flags.0?Bool call_requests_disabled:flags.1?Bool = Bool;\nusers.getUsers#d91a548 id:Vector<InputUser> = Vector<User>;\nusers.getFullUser#b60f5918 id:InputUser = users.UserFull;\ncontacts.getContacts#5dd69e12 hash:long = contacts.Contacts;\ncontacts.importContacts#2c800be5 contacts:Vector<InputContact> = contacts.ImportedContacts;\ncontacts.deleteContacts#96a0e00 id:Vector<InputUser> = Updates;\ncontacts.block#68cc1411 id:InputPeer = Bool;\ncontacts.unblock#bea65d50 id:InputPeer = Bool;\ncontacts.getBlocked#f57c350f offset:int limit:int = contacts.Blocked;\ncontacts.search#11f812d8 q:string limit:int = contacts.Found;\ncontacts.resolveUsername#f93ccba3 username:string = contacts.ResolvedPeer;\ncontacts.getTopPeers#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;\ncontacts.resolvePhone#8af94344 phone:string = contacts.ResolvedPeer;\nmessages.getMessages#63c66506 id:Vector<InputMessage> = 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<int> = messages.AffectedMessages;\nmessages.receivedMessages#5a954c0 max_id:int = Vector<ReceivedNotifyMessage>;\nmessages.setTyping#58943ee2 flags:# peer:InputPeer top_msg_id:flags.0?int action:SendMessageAction = Bool;\nmessages.sendMessage#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<MessageEntity> 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<MessageEntity> 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<int> random_id:Vector<long> to_peer:InputPeer schedule_date:flags.10?int send_as:flags.13?InputPeer = Updates;\nmessages.reportSpam#cf1592db peer:InputPeer = Bool;\nmessages.getPeerSettings#efd9a6a2 peer:InputPeer = messages.PeerSettings;\nmessages.report#8953ab4e peer:InputPeer id:Vector<int> reason:ReportReason message:string = Bool;\nmessages.getChats#49e9528f id:Vector<long> = 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<InputUser> title:string = Updates;\nmessages.getDhConfig#26cf8950 version:int random_length:int = messages.DhConfig;\nmessages.readMessageContents#36a73f77 id:Vector<int> = 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<MessageEntity> = 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#b1f2061f sha256:bytes size:long mime_type:string = Document;\nmessages.getSavedGifs#5cf09635 hash:long = messages.SavedGifs;\nmessages.saveGif#327a30cb id:InputDocument unsave:Bool = Bool;\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<MessageEntity> schedule_date:flags.15?int = Updates;\nmessages.getBotCallbackAnswer#9342ca07 flags:# game:flags.1?true peer:InputPeer msg_id:int data:flags.0?bytes password:flags.2?InputCheckPasswordSRP = messages.BotCallbackAnswer;\nmessages.getPeerDialogs#e470bcfd peers:Vector<InputDialogPeer> = messages.PeerDialogs;\nmessages.saveDraft#bc39e14b flags:# no_webpage:flags.1?true reply_to_msg_id:flags.0?int peer:InputPeer message:string entities:flags.3?Vector<MessageEntity> = Bool;\nmessages.getFeaturedStickers#64780b14 hash:long = messages.FeaturedStickers;\nmessages.readFeaturedStickers#5b118126 id:Vector<long> = Bool;\nmessages.getRecentStickers#9da9403b flags:# attached:flags.0?true hash:long = messages.RecentStickers;\nmessages.saveRecentSticker#392718f8 flags:# attached:flags.0?true id:InputDocument unsave:Bool = Bool;\nmessages.clearRecentStickers#8999602d flags:# attached:flags.0?true = Bool;\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.getUnreadMentions#46578472 peer:InputPeer offset_id:int add_offset:int limit:int max_id:int min_id:int = messages.Messages;\nmessages.readMentions#f0189d3 peer:InputPeer = messages.AffectedHistory;\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<InputSingleMedia> 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<bytes> = Updates;\nmessages.getOnlines#6e2be050 peer:InputPeer = ChatOnlines;\nmessages.editChatAbout#def60797 peer:InputPeer about:string = Bool;\nmessages.editChatDefaultBannedRights#a5866b41 peer:InputPeer banned_rights:ChatBannedRights = Updates;\nmessages.getEmojiKeywordsDifference#1508b6af lang_code:string from_version:int = EmojiKeywordsDifference;\nmessages.requestUrlAuth#198fb446 flags:# peer:flags.1?InputPeer msg_id:flags.1?int button_id:flags.1?int url:flags.2?string = UrlAuthResult;\nmessages.acceptUrlAuth#b12c7125 flags:# write_allowed:flags.0?true peer:flags.1?InputPeer msg_id:flags.1?int button_id:flags.1?int url:flags.2?string = UrlAuthResult;\nmessages.hidePeerSettingsBar#4facb138 peer:InputPeer = Bool;\nmessages.getScheduledHistory#f516760b peer:InputPeer hash:long = messages.Messages;\nmessages.sendScheduledMessages#bd38850a peer:InputPeer id:Vector<int> = Updates;\nmessages.deleteScheduledMessages#59ae2b16 peer:InputPeer id:Vector<int> = Updates;\nmessages.getPollVotes#b86e380e flags:# peer:InputPeer id:int option:flags.0?bytes offset:flags.1?string limit:int = messages.VotesList;\nmessages.getDialogFilters#f19ed96d = Vector<DialogFilter>;\nmessages.getSuggestedDialogFilters#a29cd42c = Vector<DialogFilterSuggested>;\nmessages.updateDialogFilter#1ad4a04a flags:# id:int filter:flags.0?DialogFilter = Bool;\nmessages.updateDialogFiltersOrder#c563c1e4 order:Vector<int> = 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.getExportedChatInvites#a2b5a3f6 flags:# revoked:flags.3?true peer:InputPeer admin_id:InputUser offset_date:flags.2?int offset_link:flags.2?string limit:int = messages.ExportedChatInvites;\nmessages.editExportedChatInvite#bdca2f75 flags:# revoked:flags.2?true peer:InputPeer link:string expire_date:flags.0?int usage_limit:flags.1?int request_needed:flags.3?Bool title:flags.4?string = messages.ExportedChatInvite;\nmessages.deleteRevokedExportedChatInvites#56987bd5 peer:InputPeer admin_id:InputUser = Bool;\nmessages.deleteExportedChatInvite#d464a42b peer:InputPeer link:string = Bool;\nmessages.getChatInviteImporters#df04dd4e flags:# requested:flags.0?true peer:InputPeer link:flags.1?string q:flags.2?string offset_date:int offset_user:InputUser limit:int = messages.ChatInviteImporters;\nmessages.getMessageReadParticipants#2c6f97b7 peer:InputPeer msg_id:int = Vector<long>;\nmessages.hideChatJoinRequest#7fe7e815 flags:# approved:flags.0?true peer:InputPeer user_id:InputUser = Updates;\nmessages.hideAllChatJoinRequests#e085f4ea flags:# approved:flags.0?true peer:InputPeer link:flags.1?string = Updates;\nmessages.toggleNoForwards#b11eafa2 peer:InputPeer enabled:Bool = Updates;\nmessages.saveDefaultSendAs#ccfddf96 peer:InputPeer send_as:InputPeer = Bool;\nmessages.sendReaction#25690ce4 flags:# big:flags.1?true peer:InputPeer msg_id:int reaction:flags.0?string = Updates;\nmessages.getMessagesReactions#8bba90e6 peer:InputPeer id:Vector<int> = Updates;\nmessages.getMessageReactionsList#e0ee6b77 flags:# peer:InputPeer id:int reaction:flags.0?string offset:flags.1?string limit:int = messages.MessageReactionsList;\nmessages.setChatAvailableReactions#14050ea6 peer:InputPeer available_reactions:Vector<string> = Updates;\nmessages.getAvailableReactions#18dea0ac hash:int = messages.AvailableReactions;\nmessages.setDefaultReaction#d960c4d4 reaction:string = Bool;\nmessages.getUnreadReactions#e85bae1a peer:InputPeer offset_id:int add_offset:int limit:int max_id:int min_id:int = messages.Messages;\nmessages.readReactions#82e251d7 peer:InputPeer = messages.AffectedHistory;\nmessages.getAttachMenuBots#16fcc2cb hash:long = AttachMenuBots;\nmessages.getAttachMenuBot#77216192 bot:InputUser = AttachMenuBotsBot;\nmessages.toggleBotInAttachMenu#1aee33af bot:InputUser enabled:Bool = Bool;\nmessages.requestWebView#91b15831 flags:# from_bot_menu:flags.4?true silent:flags.5?true peer:InputPeer bot:InputUser url:flags.1?string start_param:flags.3?string theme_params:flags.2?DataJSON reply_to_msg_id:flags.0?int send_as:flags.13?InputPeer = WebViewResult;\nmessages.prolongWebView#ea5fbcce flags:# silent:flags.5?true peer:InputPeer bot:InputUser query_id:long reply_to_msg_id:flags.0?int send_as:flags.13?InputPeer = Bool;\nmessages.requestSimpleWebView#6abb2f73 flags:# bot:InputUser url:string theme_params:flags.0?DataJSON = SimpleWebViewResult;\nmessages.sendWebViewResultMessage#a4314f5 bot_query_id:string result:InputBotInlineResult = WebViewMessageSent;\nmessages.sendWebViewData#dc0242c8 bot:InputUser random_id:long button_text:string data:string = Updates;\nmessages.transcribeAudio#269e9a49 peer:InputPeer msg_id:int = messages.TranscribedAudio;\nmessages.getCustomEmojiDocuments#d9ab0f54 document_id:Vector<long> = Vector<Document>;\nmessages.getEmojiStickers#fbfca18f hash:long = messages.AllStickers;\nmessages.getFeaturedEmojiStickers#ecf6736 hash:long = messages.FeaturedStickers;\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#be5335be flags:# precise:flags.0?true cdn_supported:flags.1?true location:InputFileLocation offset:long 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.getAppConfig#98914110 = JSONValue;\nhelp.getCountriesList#735787a8 lang_code:string hash:int = help.CountriesList;\nhelp.getPremiumPromo#b81b93d4 = help.PremiumPromo;\nchannels.readHistory#cc104937 channel:InputChannel max_id:int = Bool;\nchannels.deleteMessages#84c1fd4e channel:InputChannel id:Vector<int> = messages.AffectedMessages;\nchannels.getMessages#ad8c9a23 channel:InputChannel id:Vector<InputMessage> = messages.Messages;\nchannels.getParticipants#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<InputChannel> = messages.Chats;\nchannels.getFullChannel#8736a09 channel:InputChannel = messages.ChatFull;\nchannels.createChannel#3d5fb10f flags:# broadcast:flags.0?true megagroup:flags.1?true for_import:flags.3?true title:string about:string geo_point:flags.2?InputGeoPoint address:flags.2?string = Updates;\nchannels.editAdmin#d33c8902 channel:InputChannel user_id:InputUser admin_rights:ChatAdminRights rank:string = Updates;\nchannels.editTitle#566decd0 channel:InputChannel title:string = Updates;\nchannels.editPhoto#f12e57c9 channel:InputChannel photo:InputChatPhoto = Updates;\nchannels.checkUsername#10e6bd2c channel:InputChannel username:string = Bool;\nchannels.updateUsername#3514b3de channel:InputChannel username:string = Bool;\nchannels.joinChannel#24b524c5 channel:InputChannel = Updates;\nchannels.leaveChannel#f836aa95 channel:InputChannel = Updates;\nchannels.inviteToChannel#199f3a6c channel:InputChannel users:Vector<InputUser> = Updates;\nchannels.deleteChannel#c0111fe3 channel:InputChannel = Updates;\nchannels.toggleSignatures#1f69b606 channel:InputChannel enabled:Bool = Updates;\nchannels.editBanned#96e6cd81 channel:InputChannel participant:InputPeer banned_rights:ChatBannedRights = Updates;\nchannels.readMessageContents#eab5dc38 channel:InputChannel id:Vector<int> = Bool;\nchannels.togglePreHistoryHidden#eabbb94c channel:InputChannel enabled:Bool = Updates;\nchannels.getGroupsForDiscussion#f5dad378 = messages.Chats;\nchannels.setDiscussionGroup#40582bb2 broadcast:InputChannel group:InputChannel = Bool;\nchannels.viewSponsoredMessage#beaedb94 channel:InputChannel random_id:bytes = Bool;\nchannels.getSponsoredMessages#ec210fbf channel:InputChannel = messages.SponsoredMessages;\nchannels.getSendAs#dc770ee peer:InputPeer = channels.SendAsPeers;\nchannels.toggleJoinToSend#e4cb9580 channel:InputChannel enabled:Bool = Updates;\nchannels.toggleJoinRequest#4c2985b6 channel:InputChannel enabled:Bool = Updates;\npayments.getPaymentForm#37148dbb flags:# invoice:InputInvoice theme_params:flags.0?DataJSON = payments.PaymentForm;\npayments.getPaymentReceipt#2478d1cc peer:InputPeer msg_id:int = payments.PaymentReceipt;\npayments.validateRequestedInfo#b6c8f12b flags:# save:flags.0?true invoice:InputInvoice info:PaymentRequestedInfo = payments.ValidatedRequestedInfo;\npayments.sendPaymentForm#2d03522f flags:# form_id:long invoice:InputInvoice 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.requestCall#42ff96ed flags:# video:flags.0?true user_id:InputUser random_id:int g_a_hash:bytes protocol:PhoneCallProtocol = phone.PhoneCall;\nphone.acceptCall#3bd2b4a0 peer:InputPhoneCall g_b:bytes protocol:PhoneCallProtocol = phone.PhoneCall;\nphone.confirmCall#2efe1722 peer:InputPhoneCall g_a:bytes key_fingerprint:long protocol:PhoneCallProtocol = phone.PhoneCall;\nphone.receivedCall#17d54f61 peer:InputPhoneCall = Bool;\nphone.discardCall#b2cbc1c0 flags:# video:flags.0?true peer:InputPhoneCall duration:int reason:PhoneCallDiscardReason connection_id:long = Updates;\nphone.setCallRating#59ead627 flags:# user_initiative:flags.0?true peer:InputPhoneCall rating:int comment:string = Updates;\nphone.saveCallDebug#277add7e peer:InputPhoneCall debug:DataJSON = Bool;\nphone.sendSignalingData#ff7a9383 peer:InputPhoneCall data:bytes = Bool;\nphone.createGroupCall#48cdc6d8 flags:# rtmp_stream:flags.2?true 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<InputPeer> sources:Vector<int> 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<string> = Vector<LangPackString>;\nlangpack.getLanguages#42c6978f lang_pack:string = Vector<LangPackLanguage>;\nfolders.editPeerFolders#6847d0ab folder_peers:Vector<InputFolderPeer> = Updates;\nstats.getBroadcastStats#ab42441a flags:# dark:flags.0?true channel:InputChannel = stats.BroadcastStats;\nstats.loadAsyncGraph#621d5fa0 flags:# token:string x:flags.0?long = StatsGraph;\nstats.getMegagroupStats#dcdf8607 flags:# dark:flags.0?true channel:InputChannel = stats.MegagroupStats;\nstats.getMessagePublicForwards#5630281b channel:InputChannel msg_id:int offset_rate:int offset_peer:InputPeer offset_id:int limit:int = messages.Messages;\nstats.getMessageStats#b6e0a3f5 flags:# dark:flags.0?true channel:InputChannel msg_id:int = stats.MessageStats;`;","const { inflate } = require('pako/dist/pako_inflate');\nconst { serializeBytes } = require('../index');\n\n// CONTEST const { deflate } = require('pako/dist/pako_deflate')\n\nclass GZIPPacked {\n static CONSTRUCTOR_ID = 0x3072cfa1;\n\n static classType = 'constructor';\n\n constructor(data) {\n this.data = data;\n this.CONSTRUCTOR_ID = 0x3072cfa1;\n this.classType = 'constructor';\n }\n\n static async gzipIfSmaller(contentRelated, data) {\n if (contentRelated && data.length > 512) {\n const gzipped = await (new GZIPPacked(data)).toBytes();\n if (gzipped.length < data.length) {\n return gzipped;\n }\n }\n return data;\n }\n\n static gzip(input) {\n return Buffer.from(input);\n // TODO this usually makes it faster for large requests\n // return Buffer.from(deflate(input, { level: 9, gzip: true }))\n }\n\n static ungzip(input) {\n return Buffer.from(inflate(input));\n }\n\n static read(reader) {\n const constructor = reader.readInt(false);\n if (constructor !== GZIPPacked.CONSTRUCTOR_ID) {\n throw new Error('not equal');\n }\n return GZIPPacked.gzip(reader.tgReadBytes());\n }\n\n static async fromReader(reader) {\n return new GZIPPacked(await GZIPPacked.ungzip(reader.tgReadBytes()));\n }\n\n async toBytes() {\n const g = Buffer.alloc(4);\n g.writeUInt32LE(GZIPPacked.CONSTRUCTOR_ID, 0);\n return Buffer.concat([\n g,\n serializeBytes(await GZIPPacked.gzip(this.data)),\n ]);\n }\n}\n\nmodule.exports = GZIPPacked;\n","const TLMessage = require('./TLMessage');\n\nclass MessageContainer {\n static CONSTRUCTOR_ID = 0x73f1f8dc;\n\n static classType = 'constructor';\n\n // Maximum size in bytes for the inner payload of the container.\n // Telegram will close the connection if the payload is bigger.\n // The overhead of the container itself is subtracted.\n static MAXIMUM_SIZE = 1044456 - 8;\n\n // Maximum amount of messages that can't be sent inside a single\n // container, inclusive. Beyond this limit Telegram will respond\n // with BAD_MESSAGE 64 (invalid container).\n //\n // This limit is not 100% accurate and may in some cases be higher.\n // However, sending up to 100 requests at once in a single container\n // is a reasonable conservative value, since it could also depend on\n // other factors like size per request, but we cannot know this.\n static MAXIMUM_LENGTH = 100;\n\n constructor(messages) {\n this.CONSTRUCTOR_ID = 0x73f1f8dc;\n this.messages = messages;\n this.classType = 'constructor';\n }\n\n static fromReader(reader) {\n const messages = [];\n const length = reader.readInt();\n for (let x = 0; x < length; x++) {\n const msgId = reader.readLong();\n const seqNo = reader.readInt();\n const containerLength = reader.readInt();\n const before = reader.tellPosition();\n const obj = reader.tgReadObject();\n reader.setPosition(before + containerLength);\n const tlMessage = new TLMessage(msgId, seqNo, obj);\n messages.push(tlMessage);\n }\n return new MessageContainer(messages);\n }\n}\n\nmodule.exports = MessageContainer;\n","const { RpcError } = require('../index').constructors;\nconst GZIPPacked = require('./GZIPPacked');\n\nclass RPCResult {\n static CONSTRUCTOR_ID = 0xf35c6d01;\n\n static classType = 'constructor';\n\n constructor(reqMsgId, body, error) {\n this.CONSTRUCTOR_ID = 0xf35c6d01;\n this.reqMsgId = reqMsgId;\n this.body = body;\n this.error = error;\n this.classType = 'constructor';\n }\n\n static async fromReader(reader) {\n const msgId = reader.readLong();\n const innerCode = reader.readInt(false);\n if (innerCode === RpcError.CONSTRUCTOR_ID) {\n return new RPCResult(msgId, undefined, RpcError.fromReader(reader));\n }\n if (innerCode === GZIPPacked.CONSTRUCTOR_ID) {\n return new RPCResult(msgId, (await GZIPPacked.fromReader(reader)).data);\n }\n reader.seek(-4);\n // This reader.read() will read more than necessary, but it's okay.\n // We could make use of MessageContainer's length here, but since\n // it's not necessary we don't need to care about it.\n return new RPCResult(msgId, reader.read(), undefined);\n }\n}\n\nmodule.exports = RPCResult;\n","class TLMessage {\n static SIZE_OVERHEAD = 12;\n\n static classType = 'constructor';\n\n constructor(msgId, seqNo, obj) {\n this.msgId = msgId;\n this.seqNo = seqNo;\n this.obj = obj;\n this.classType = 'constructor';\n }\n}\n\nmodule.exports = TLMessage;\n","const TLMessage = require('./TLMessage');\nconst RPCResult = require('./RPCResult');\nconst MessageContainer = require('./MessageContainer');\nconst GZIPPacked = require('./GZIPPacked');\n\nconst coreObjects = {\n [RPCResult.CONSTRUCTOR_ID]: RPCResult,\n [GZIPPacked.CONSTRUCTOR_ID]: GZIPPacked,\n [MessageContainer.CONSTRUCTOR_ID]: MessageContainer,\n};\n\nmodule.exports = {\n TLMessage,\n RPCResult,\n MessageContainer,\n GZIPPacked,\n coreObjects,\n};\n","const snakeToCamelCase = (name) => {\n const result = name.replace(/(?:^|_)([a-z])/g, (_, g) => g.toUpperCase());\n return result.replace(/_/g, '');\n};\nconst variableSnakeToCamelCase = (str) => str.replace(\n /([-_][a-z])/g,\n (group) => group.toUpperCase()\n .replace('-', '')\n .replace('_', ''),\n);\n\nconst CORE_TYPES = new Set([\n 0xbc799737, // boolFalse#bc799737 = Bool;\n 0x997275b5, // boolTrue#997275b5 = Bool;\n 0x3fedd339, // true#3fedd339 = True;\n 0xc4b9f9bb, // error#c4b9f9bb code:int text:string = Error;\n 0x56730bcc, // null#56730bcc = Null;\n]);\nconst AUTH_KEY_TYPES = new Set([\n 0x05162463, // resPQ,\n 0x83c95aec, // p_q_inner_data\n 0xa9f55f95, // p_q_inner_data_dc\n 0x3c6a84d4, // p_q_inner_data_temp\n 0x56fddf88, // p_q_inner_data_temp_dc\n 0xd0e8075c, // server_DH_params_ok\n 0xb5890dba, // server_DH_inner_data\n 0x6643b654, // client_DH_inner_data\n 0xd712e4be, // req_DH_params\n 0xf5045f1f, // set_client_DH_params\n 0x3072cfa1, // gzip_packed\n]);\n\n// This is copy-pasted from `gramjs/Helpers.js` to not depend on TypeScript modules\nfunction makeCRCTable() {\n let c;\n const crcTable = [];\n for (let n = 0; n < 256; n++) {\n c = n;\n for (let k = 0; k < 8; k++) {\n c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));\n }\n crcTable[n] = c;\n }\n return crcTable;\n}\n\nlet crcTable;\n\nfunction crc32(buf) {\n if (!crcTable) {\n crcTable = makeCRCTable();\n }\n if (!Buffer.isBuffer(buf)) {\n buf = Buffer.from(buf);\n }\n let crc = -1;\n\n for (let index = 0; index < buf.length; index++) {\n const byte = buf[index];\n crc = crcTable[(crc ^ byte) & 0xff] ^ (crc >>> 8);\n }\n return (crc ^ (-1)) >>> 0;\n}\n\nconst findAll = (regex, str, matches = []) => {\n if (!regex.flags.includes('g')) {\n regex = new RegExp(regex.source, 'g');\n }\n\n const res = regex.exec(str);\n\n if (res) {\n matches.push(res.slice(1));\n findAll(regex, str, matches);\n }\n\n return matches;\n};\n\nconst fromLine = (line, isFunction) => {\n const match = line.match(/([\\w.]+)(?:#([0-9a-fA-F]+))?(?:\\s{?\\w+:[\\w\\d<>#.?!]+}?)*\\s=\\s([\\w\\d<>#.?]+);$/);\n if (!match) {\n // Probably \"vector#1cb5c415 {t:Type} # [ t ] = Vector t;\"\n throw new Error(`Cannot parse TLObject ${line}`);\n }\n\n const argsMatch = findAll(/({)?(\\w+):([\\w\\d<>#.?!]+)}?/, line);\n const currentConfig = {\n name: match[1],\n constructorId: parseInt(match[2], 16),\n argsConfig: {},\n subclassOfId: crc32(match[3]),\n result: match[3],\n isFunction,\n namespace: undefined,\n };\n if (!currentConfig.constructorId) {\n const hexId = '';\n let args;\n\n if (Object.values(currentConfig.argsConfig).length) {\n args = ` ${Object.keys(currentConfig.argsConfig)\n .map((arg) => arg.toString())\n .join(' ')}`;\n } else {\n args = '';\n }\n\n const representation = `${currentConfig.name}${hexId}${args} = ${currentConfig.result}`\n .replace(/(:|\\?)bytes /g, '$1string ')\n .replace(/</g, ' ')\n .replace(/>|{|}/g, '')\n .replace(/ \\w+:flags\\.\\d+\\?true/g, '');\n\n if (currentConfig.name === 'inputMediaInvoice') {\n // eslint-disable-next-line no-empty\n if (currentConfig.name === 'inputMediaInvoice') {\n }\n }\n\n currentConfig.constructorId = crc32(Buffer.from(representation, 'utf8'));\n }\n for (const [brace, name, argType] of argsMatch) {\n if (brace === undefined) {\n currentConfig.argsConfig[variableSnakeToCamelCase(name)] = buildArgConfig(name, argType);\n }\n }\n if (currentConfig.name.includes('.')) {\n [currentConfig.namespace, currentConfig.name] = currentConfig.name.split(/\\.(.+)/);\n }\n currentConfig.name = snakeToCamelCase(currentConfig.name);\n /*\n for (const arg in currentConfig.argsConfig){\n if (currentConfig.argsConfig.hasOwnProperty(arg)){\n if (currentConfig.argsConfig[arg].flagIndicator){\n delete currentConfig.argsConfig[arg]\n }\n }\n } */\n return currentConfig;\n};\n\nfunction buildArgConfig(name, argType) {\n name = name === 'self' ? 'is_self' : name;\n // Default values\n const currentConfig = {\n isVector: false,\n isFlag: false,\n skipConstructorId: false,\n flagIndex: -1,\n flagIndicator: true,\n type: undefined,\n useVectorId: undefined,\n };\n\n // The type can be an indicator that other arguments will be flags\n if (argType !== '#') {\n currentConfig.flagIndicator = false;\n // Strip the exclamation mark always to have only the name\n currentConfig.type = argType.replace(/^!+/, '');\n\n // The type may be a flag (flags.IDX?REAL_TYPE)\n // Note that 'flags' is NOT the flags name; this\n // is determined by a previous argument\n // However, we assume that the argument will always be called 'flags'\n const flagMatch = currentConfig.type.match(/flags.(\\d+)\\?([\\w<>.]+)/);\n\n if (flagMatch) {\n currentConfig.isFlag = true;\n currentConfig.flagIndex = Number(flagMatch[1]);\n // Update the type to match the exact type, not the \"flagged\" one\n [, , currentConfig.type] = flagMatch;\n }\n\n // Then check if the type is a Vector<REAL_TYPE>\n 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 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 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\nfunction* parseTl(content, layer, methods = [], ignoreIds = CORE_TYPES) {\n (methods || []).reduce((o, m) => ({\n ...o,\n [m.name]: m,\n }), {});\n const objAll = [];\n const objByName = {};\n const objByType = {};\n\n const file = content;\n\n let isFunction = false;\n\n for (let line of file.split('\\n')) {\n const commentIndex = line.indexOf('//');\n\n if (commentIndex !== -1) {\n line = line.slice(0, commentIndex);\n }\n\n line = line.trim();\n\n if (!line) {\n continue;\n }\n\n const match = line.match(/---(\\w+)---/);\n\n if (match) {\n const [, followingTypes] = match;\n isFunction = followingTypes === 'functions';\n continue;\n }\n\n try {\n const result = fromLine(line, isFunction);\n\n if (ignoreIds.has(result.constructorId)) {\n continue;\n }\n\n objAll.push(result);\n\n if (!result.isFunction) {\n if (!objByType[result.result]) {\n objByType[result.result] = [];\n }\n\n objByName[result.name] = result;\n objByType[result.result].push(result);\n }\n } catch (e) {\n if (!e.toString()\n .includes('vector#1cb5c415')) {\n throw e;\n }\n }\n }\n\n // Once all objects have been parsed, replace the\n // string type from the arguments with references\n for (const obj of objAll) {\n // console.log(obj)\n if (AUTH_KEY_TYPES.has(obj.constructorId)) {\n for (const arg in obj.argsConfig) {\n if (obj.argsConfig[arg].type === 'string') {\n obj.argsConfig[arg].type = 'bytes';\n }\n }\n }\n }\n\n for (const obj of objAll) {\n yield obj;\n }\n}\n\nfunction serializeBytes(data) {\n if (!(data instanceof Buffer)) {\n if (typeof data === 'string') {\n data = Buffer.from(data);\n } else {\n throw Error(`Bytes or str expected, not ${data.constructor.name}`);\n }\n }\n const r = [];\n let padding;\n if (data.length < 254) {\n padding = (data.length + 1) % 4;\n if (padding !== 0) {\n padding = 4 - padding;\n }\n r.push(Buffer.from([data.length]));\n r.push(data);\n } else {\n padding = data.length % 4;\n if (padding !== 0) {\n padding = 4 - padding;\n }\n r.push(Buffer.from([254, data.length % 256, (data.length >> 8) % 256, (data.length >> 16) % 256]));\n r.push(data);\n }\n r.push(Buffer.alloc(padding)\n .fill(0));\n\n return Buffer.concat(r);\n}\n\nfunction serializeDate(dt) {\n if (!dt) {\n return Buffer.alloc(4)\n .fill(0);\n }\n if (dt instanceof Date) {\n dt = Math.floor((Date.now() - dt.getTime()) / 1000);\n }\n if (typeof dt === 'number') {\n const t = Buffer.alloc(4);\n t.writeInt32LE(dt, 0);\n return t;\n }\n throw Error(`Cannot interpret \"${dt}\" as a date`);\n}\n\nmodule.exports = {\n findAll,\n parseTl,\n buildArgConfig,\n fromLine,\n CORE_TYPES,\n serializeDate,\n serializeBytes,\n snakeToCamelCase,\n variableSnakeToCamelCase,\n};\n","const api = require('./api');\nconst {\n serializeBytes,\n serializeDate,\n} = require('./generationHelpers');\n\nmodule.exports = {\n // TODO Refactor internal usages to always use `api`.\n constructors: api,\n requests: api,\n serializeBytes,\n serializeDate,\n};\n","module.exports = `resPQ#05162463 nonce:int128 server_nonce:int128 pq:string server_public_key_fingerprints:Vector<long> = ResPQ;\np_q_inner_data#83c95aec pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 = P_Q_inner_data;\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<long> = MsgsAck;\nbad_msg_notification#a7eff811 bad_msg_id:long bad_msg_seqno:int error_code:int = BadMsgNotification;\nbad_server_salt#edab447b bad_msg_id:long bad_msg_seqno:int error_code:int new_server_salt:long = BadMsgNotification;\nmsgs_state_req#da69fb52 msg_ids:Vector<long> = MsgsStateReq;\nmsgs_state_info#04deb57d req_msg_id:long info:string = MsgsStateInfo;\nmsgs_all_info#8cc0d131 msg_ids:Vector<long> info:string = MsgsAllInfo;\nmsg_detailed_info#276d3ec6 msg_id:long answer_msg_id:long bytes:int status:int = MsgDetailedInfo;\nmsg_new_detailed_info#809db6df answer_msg_id:long bytes:int status:int = MsgDetailedInfo;\nmsg_resend_req#7d861a08 msg_ids:Vector<long> = MsgResendReq;\nrpc_error#2144ca19 error_code:int error_message:string = RpcError;\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<future_salt> = FutureSalts;\npong#347773c5 msg_id:long ping_id:long = Pong;\ndestroy_session_ok#e22045fc session_id:long = DestroySessionRes;\ndestroy_session_none#62d350c9 session_id:long = DestroySessionRes;\nnew_session_created#9ec20908 first_msg_id:long unique_id:long server_salt:long = NewSession;\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<IpPort> = AccessPointRule;\nhelp.configSimple#5a592a6c date:int expires:int rules:vector<AccessPointRule> = help.ConfigSimple;\ntlsClientHello blocks:vector<TlsBlock> = TlsClientHello;\ntlsBlockString data:string = TlsBlock;\ntlsBlockRandom length:int = TlsBlock;\ntlsBlockZero length:int = TlsBlock;\ntlsBlockDomain = TlsBlock;\ntlsBlockGrease seed:int = TlsBlock;\ntlsBlockScope entries:Vector<TlsBlock> = 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, [5802,5313], () => (__webpack_require__(98090)))\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 + \".\" + {\"5313\":\"3417bfbe0af0b56e2830\",\"5802\":\"5a998479cf43543543ff\"}[chunkId] + \".js\";\n};","// This function allow to reference async chunks and sibling chunks for the entrypoint\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\t8090: 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","VIDEO_MOV_TYPE","SUPPORTED_IMAGE_CONTENT_TYPES","SUPPORTED_VIDEO_CONTENT_TYPES","SUPPORTED_AUDIO_CONTENT_TYPES","SERVICE_NOTIFICATIONS_USER_ID","DEFAULT_LIMITS","uploadMaxFileparts","stickersFaved","savedGifs","dialogFiltersChats","dialogFilters","dialogFolderPinned","captionLength","channels","channelsPublic","aboutLength","onTickEndCallbacks","onTickEndPrimaryCallbacks","buildCollectionByKey","collection","key","reduce","byKey","member","pick","object","keys","result","ApiMessageEntityTypes","ApiMediaFormat","bytesToDataUri","bytes","shouldOmitPrefix","mimeType","prefix","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","videoSizes","buildApiVideoSize","isVideo","videoSize","videoStartTs","size","type","photoSize","LOCAL_DB_INITIAL","localMessages","chats","users","messages","documents","stickerSets","photos","webDocuments","localDb","clearLocalDb","Object","assign","LOTTIE_STICKER_MIME_TYPE","VIDEO_STICKER_MIME_TYPE","buildStickerFromDocument","document","isNoPremium","videoThumbs","stickerAttribute","attributes","attr","customEmojiAttribute","fileAttribute","isLottie","isCustomEmoji","Boolean","imageSizeAttribute","videoSizeAttribute","sizeAttribute","stickerOrEmojiAttribute","stickerSetInfo","inputSet","stickerset","accessHash","shortName","isMissing","emoji","alt","isFree","free","cachedThumb","thumbs","self","isWebmSupported","pathThumb","buildApiThumbnailFromCached","buildApiThumbnailFromPath","hasEffect","some","buildStickerSet","set","archived","animated","installedDate","videos","title","count","emojis","isVideos","isEmoji","hasThumbnail","buildStickerSetCovered","coveredStickerSet","stickerSet","stickers","processStickerResult","cover","covers","packs","processStickerPackResult","acc","emoticon","documentId","sticker","interpolateArray","data","fitCount","peak","newData","Array","springFactor","leftFiller","rightFiller","idx","floor","val","isPeerUser","peer","hasOwnProperty","isPeerChat","buildApiPeerId","getApiChatIdFromMtpPeer","userId","chatId","channelId","resolveMessageApiChatId","mtpMessage","peerId","addMessageToLocalDb","message","messageFullId","media","webpage","game","addPhotoToLocalDb","url","action","addUserToLocalDb","user","shouldOverwrite","addEntitiesWithPhotosToLocalDb","entities","forEach","entity","chat","noOverwrite","addChatToLocalDb","serializeBytes","value","deserializeBytes","Buffer","from","getEntityTypeById","chatOrUserId","getEntityTypeByDeprecatedId","startsWith","buildPeer","buildMtpPeerId","buildInputPeer","BigInt","buildInputPeerFromLocalDb","buildInputEntity","buildInputStickerSet","buildInputDocument","buildInputMediaDocument","inputDocument","buildInputPollFromExisting","poll","shouldClose","publicVoters","summary","isPublic","question","answers","text","option","quiz","multipleChoice","closeDate","closePeriod","closed","correctAnswers","results","o","isCorrect","solution","solutionEntities","buildMtpMessageEntity","generateRandomBigInt","readBigIntFromBuffer","generateRandomBytes","generateRandomInt","toJSNumber","buildMessageFromUpdate","update","fromId","offset","Bold","Italic","Underline","Strike","Code","Pre","language","Blockquote","TextUrl","Url","Hashtag","MentionName","Spoiler","CustomEmoji","isMessageWithMedia","buildInputContact","phone","firstName","lastName","clientId","buildChatBannedRights","bannedRights","untilDate","buildChatAdminRights","adminRights","buildShippingInfo","info","shippingAddress","buildInputPrivacyKey","privacyKey","buildInputReportReason","reason","buildInputThemeParams","params","JSON","stringify","abs","slice","buildInputGroupCall","groupCall","buildInputPhoneCall","buildInputInvoice","invoice","slug","msgId","messageId","buildApiGroupCallParticipant","participant","min","about","date","versioned","canSelfUnmute","justJoined","left","muted","mutedByYou","source","volume","volumeByAdmin","videoJoined","video","presentation","raiseHandRating","isSelf","isMin","isLeft","isMuted","isMutedByMe","hasJustJoined","isVolumeByAdmin","isVersioned","isVideoJoined","toString","Date","isUser","buildApiGroupCallParticipantVideo","participantVideo","audioSource","endpoint","paused","sourceGroups","isPaused","buildApiGroupCallParticipantVideoSourceGroup","participantVideoSourceGroup","semantics","sources","buildApiGroupCall","connectionState","participantsCount","version","participants","streamDcId","scheduleDate","canChangeJoinMuted","joinMuted","canStartVideo","scheduleStartSubscribed","isLoaded","buildPhoneCall","call","phoneCall","adminId","participantId","protocol","buildApiCallProtocol","p2pAllowed","gAOrB","keyFingerprint","connections","startDate","state","buildApiCallConnection","duration","buildApiCallDiscardReason","needRating","needDebug","receiveDate","gB","gAHash","discardReason","connection","username","password","turn","stun","ip","ipv6","port","isTurn","isStun","libraryVersions","minLayer","maxLayer","udpP2p","udpReflector","isUdpP2p","isUdpReflector","buildCallProtocol","LOCAL_MEDIA_UPLOADING_TEMP_ID","localMessageCounter","getNextLocalMessageId","parseFloat","now","currentUserId","buildApiSponsoredMessage","startParam","channelPost","chatInvite","chatInviteHash","randomId","recommended","chatInviteTitle","isBot","buildMessageTextContent","expiresAt","isRecommended","channelPostId","buildApiMessage","buildApiMessageWithChatId","isChatWithSelf","isOutgoing","out","post","fwdFrom","content","buildMessageContent","senderId","targetPeerId","isChannelPost","amount","currency","translationValues","score","months","targetUserIds","targetChatId","push","includes","withDuration","join","mins","max","Number","totalAmount","domain","buildAction","replyToMsgId","replyToTopId","replyToPeerId","replyTo","isEdited","editDate","editHide","inlineButtons","keyboardButtons","keyboardPlaceholder","isKeyboardSingleUse","replyMarkup","markup","rows","buttons","button","requiresPassword","isQuiz","receiptMsgId","receiptMessageId","query","isSamePeer","samePeer","buttonId","placeholder","singleUse","buildReplyButtons","forwardInfo","savedFromPeerId","savedFromPeer","isLinkedChannelPost","fromChatId","fromMessageId","savedFromMsgId","senderUserId","hiddenUserName","fromName","adminTitle","postAuthor","buildApiMessageForwardInfo","replies","mediaUnread","isMediaUnread","groupedId","isInAlbum","audio","shouldHideKeyboardButtons","views","forwards","isFromScheduled","fromScheduled","reactions","buildMessageReactions","replyToMessageId","replyToChatId","replyToTopMessageId","mentioned","hasUnreadMention","isMentioned","viaBotId","comments","threadInfo","buildThreadInfo","noforwards","isProtected","recentReactions","canSeeList","buildReactionCount","buildMessagePeerReaction","reactionCount","chosen","reaction","isChosen","userReaction","big","unread","isUnread","isBig","buildApiAvailableReaction","availableReaction","selectAnimation","staticIcon","inactive","aroundAnimation","centerIcon","effectAnimation","activateAnimation","premium","buildApiDocument","isInactive","isPremium","buildMessageMediaContent","hasUnsupportedMedia","contact","isRound","buildApiMessageEntity","buildMessageDraft","draft","formattedText","replyingToId","ttlSeconds","nopremium","buildSticker","buildPhoto","buildVideoFromDocument","buildVideo","audioAttribute","voice","thumbnailSizes","fileName","getFilenameFromDocument","buildAudio","waveform","buildVoice","buildDocumentFromMedia","phoneNumber","buildContact","buildPoll","buildPollFromMedia","webPage","buildWebPage","description","test","buildApiWebDocument","isTest","buildInvoice","buildInvoiceFromMedia","location","point","buildGeoPoint","geo","buildGeo","provider","address","venueId","venueType","buildVenue","period","heading","buildGeoLive","buildLocationFromMedia","apiPhoto","apiDocument","buildGame","buildGameFromMedia","isMovSupported","videoAttr","a","gifAttr","supportsStreaming","roundMessage","isGif","mediaType","mediaSize","has","imageAttribute","videoAttribute","timestamp","long","lat","accuracyRadius","pollResults","rawAnswers","answer","buildPollResults","rawResults","totalVoters","recentVoters","correct","voters","votersCount","recentVoterIds","defaultBase","filenameAttribute","extension","split","buildUploadingMedia","attachment","filename","blobUrl","previewBlobUrl","quick","inputWaveform","performer","sizeAttr","dimensions","buildNewPoll","localId","messageReplies","maxId","readMaxId","recentRepliers","apiChannelId","threadId","originChannelId","messagesCount","lastMessageId","lastReadInboxMessageId","recentReplierIds","getServerTime","serverTimeOffset","buildApiChatFieldsFromPeerEntity","peerEntity","isSupport","hasVideoAvatar","hasVideo","avatarHash","buildAvatarHash","isSignaturesShown","signatures","hasPrivateLink","hasLink","isScam","scam","isFake","fake","isJoinToSend","joinToSend","isJoinRequest","joinRequest","isVerified","verified","isCallActive","callActive","isCallNotEmpty","callNotEmpty","joinDate","membersCount","buildApiChatPermissions","isCreator","creator","buildApiChatRestrictions","buildApiChatMigrationInfo","fakeType","buildApiChatFromDialog","dialog","folderId","unreadMark","unreadCount","unreadMentionsCount","unreadReactionsCount","notifySettings","silent","muteUntil","readOutboxMaxId","readInboxMaxId","getApiChatTypeFromPeerEntity","getApiChatTitleFromMtpPeer","lastReadOutboxMessageId","hasUnreadMark","draftDate","currentUserBannedRights","defaultBannedRights","isForbidden","isRestricted","restrictions","restrictionReason","restricted","restrictionReasons","targetReason","platform","buildApiChatRestrictionReason","isNotJoined","migratedTo","buildApiChatFromPreview","preview","getUserName","megagroup","getPeerKey","photoId","buildChatMember","inviterId","joinedDate","kickedByUserId","kickedBy","promotedByUserId","promotedBy","customTitle","rank","isAdmin","isOwner","buildChatMembers","buildChatTypingStatus","buildApiChatFolder","broadcasts","pinnedChatIds","pinnedPeers","includedChatIds","includePeers","excludedChatIds","excludePeers","buildApiChatFolderFromSuggested","buildApiChatBotCommands","botInfos","botCommands","botInfo","botId","commands","concat","mtpCommand","buildApiExportedInvite","invite","revoked","expireDate","link","permanent","usage","usageLimit","requested","requestNeeded","isRevoked","isPermanent","isRequestNeeded","buildApiChatSettings","autoarchived","reportSpam","addContact","blockContact","isAutoArchived","canReportSpam","canAddContact","canBlockContact","buildApiAttachMenuBot","bot","hasSettings","peerTypes","buildApiAttachMenuPeerType","icons","buildApiAttachMenuIcon","peerType","icon","name","buildApiBotInfo","descriptionPhoto","descriptionDocument","menuButton","gif","commandsArray","command","buildApiBotCommand","buildApiBotMenuButton","buildApiUserFromFull","mtpUserFull","fullUser","commonChatsCount","pinnedMsgId","blocked","profilePhoto","voiceMessagesForbidden","premiumGifts","buildApiUser","fullInfo","bio","pinnedMessageId","isBlocked","noVoiceMessages","gift","botUrl","buildApiPremiumGiftOption","mtpUser","userType","deleted","mutualContact","isContact","canBeInvitedToGroup","botNochats","noStatus","status","botInlinePlaceholder","botPlaceholder","botAttachMenu","isAttachMenuBot","buildApiUserStatus","mtpStatus","expires","wasOnline","buildApiUsersAndStatuses","mtpUsers","userStatusesById","buildApiWallpaper","wallpaper","buildApiSession","session","isCurrent","current","isOfficialApp","officialApp","isPasswordPending","passwordPending","hash","areCallsEnabled","callRequestsDisabled","areSecretChatsEnabled","encryptedRequestsDisabled","buildApiWebSession","buildPrivacyRules","rules","visibility","allowUserIds","allowChatIds","blockUserIds","blockChatIds","rule","buildApiNotifyException","showPreviews","otherSound","hasSound","isSilent","shouldShowPreviews","buildApiCountry","country","code","hidden","iso2","defaultName","countryCode","prefixes","patterns","isHidden","buildJson","json","el","buildApiUrlAuthResult","requestWriteAccess","shouldRequestWriteAccess","onUpdate","sentMessageIds","shouldIgnoreNextChannelUpdate","dispatchUserAndChatUpdates","e","updater","originRequest","timeOffset","shouldForceReply","buildApiMessageFromShort","selective","_entities","invoiceSlug","dcId","buildChatPhotoForLocalDb","localDbChatId","newProfilePhoto","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","interaction","parse","timestamps","l","t","typingStatus","channel","apiUserId","updatedUser","settings","buildPrivacyKey","n","groupCallId","recentRequesterIds","recentRequesters","requestsPending","callId","phoneCallId","queryId","transcriptionId","isPending","pending","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","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","ArrayBuffer","arrayBuffer","console","warn","save","cacheData","Response","put","remove","delete","clear","MEDIA_ENTITY_TYPES","downloadMedia","client","isConnected","onProgress","mediaFormat","start","end","fullSize","parsed","parseMediaUrl","entityType","entityId","sizeType","mediaMatchType","parsedParams","URLSearchParams","zoom","scale","downloadStaticMap","Stream","acceptsBuffer","progressCallback","workers","getMessageMediaMimeType","downloadStickerSetThumb","getMimeType","downloadProfilePhoto","download","BlobUrl","Progressive","DownloadUrl","buffer","parseMedia","canCache","prepared","mediaData","URL","createObjectURL","fallbackMimeType","signature","subarray","byte","mediaMatch","GramJsLogger","gramJsUpdateEventBuilder","build","setIsPremium","destroy","noLogOut","invokeRequest","disconnect","onSessionUpdate","sessionData","handleGramJsUpdate","handleTerminatedSession","currentUser","shouldReturnTrue","shouldThrow","shouldIgnoreUpdates","invoke","handleUpdatesFromRequest","dispatchErrorUpdate","manyUpdates","singleUpdate","updates","injectUpdateEntities","args","downloadMediaWithClient","catch","repairFileReference","uploadFile","file","updateTwoFaSettings","fetchCurrentUser","userFull","_currentUserId","onCurrentUserUpdate","isSlowMode","hasErrorKey","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","canViewStats","linkedChatId","hiddenPrehistory","availableReactions","defaultSendAs","statsDc","chatPhoto","inviteLink","members","fetchMembers","kickedMembers","bannedUsers","bannedStatusesById","adminMembers","adminUsers","adminStatusesById","mtpLinkedChat","statusesById","slowMode","nextSendDate","migratedFrom","maxMessageId","canViewMembers","canViewStatistics","isPreHistoryHidden","enabledReactions","sendAsId","statisticsDcId","getFullChannelInfo","getFullChatInfo","fetchChatSettings","searchChats","q","localPeerIds","myResults","allChats","allUsers","localChats","r","localUsers","u","globalChats","globalUsers","fetchChat","requestChatUpdate","lastLocalMessage","noLastMessage","peers","lastRemoteMessage","saveDraft","clearDraft","updateChatMutedState","createChannel","noErrorUpdate","broadcast","newChannel","joinChannel","deleteChatUser","deleteChat","leaveChannel","deleteChannel","createGroupChat","newChat","editChatPhoto","uploadedPhoto","inputEntity","toggleChatPinned","shouldBePinned","toggleChatArchived","fetchChatFolders","defaultFolderPosition","findIndex","df","splice","byId","fetchRecommendedChatFolders","editChatFolder","folderUpdate","contacts","nonContacts","groups","bots","excludeArchived","excludeMuted","excludeRead","buildFilterFromApiFolder","deleteChatFolder","isActionSuccessful","recommendedChatFolders","folders","sortChatFolders","toggleDialogUnread","getChatByPhoneNumber","processResolvedPeer","getChatByUsername","togglePreHistoryHidden","isEnabled","enabled","updateChatDefaultBannedRights","updateChatMemberBannedRights","updateChatAdmin","updateChatTitle","updateChatAbout","toggleSignatures","memberFilter","fetchGroupsForDiscussion","setDiscussionGroup","group","migrateChat","openChatByInvite","isChannel","addChatMembers","all","deleteChatMember","viewMessages","sendMessages","sendMedia","sendStickers","sendGifs","sendGames","sendInline","embedLinks","sendPolls","changeInfo","inviteUsers","pinMessages","toggleJoinToSend","toggleJoinRequest","store","importChatInvite","setChatEnabledReactions","toggleIsProtected","fetchFile","fetchBlob","File","lastModified","blobToFile","constructor","fileBits","super","this","fetchMessages","pagination","RequestClass","c","threadInfos","fetchMessage","queue","sendMessage","replyingTo","replyingToTopId","scheduledAt","noWebPage","sendAs","buildLocalMessage","groupIndex","groupedUploads","counter","singleMediaByIndex","prevQueue","uploadMedia","inputMedia","uploadedMedia","messageMedia","fileReference","fetchInputMedia","multiMedia","values","sendGroupedMedia","pollParams","buildInputPoll","vcard","noWebpage","editMessage","mtpEntities","rescheduleMessage","patchedOnProgress","progress","isCanceled","inputFile","thumbFile","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","minDate","maxDate","nextOffsetId","totalCount","searchMessagesGlobal","offsetRate","nextRate","fetchWebPagePreview","sendPollVote","closePoll","loadPollOptionResults","shouldResetVoters","votes","vote","nextOffset","forwardMessages","fromChat","toChat","withMyScore","noAuthors","noCaptions","isCurrentUserPremium","randomIds","index","isAudio","asIncomingInChatWithSelf","shouldHideText","shouldDropCustomEmoji","strippedText","updatedContent","buildLocalForwardedMessage","fromPeer","toPeer","dropAuthor","dropMediaCaptions","findFirstMessageIdAfterDate","fetchScheduledHistory","sendScheduledMessages","isServiceMessageWithMedia","fetchPinnedMessages","fetchSeenBy","fetchSendAs","saveDefaultSendAs","fetchSponsoredMessages","viewSponsoredMessage","random","readAllMentions","readAllReactions","fetchUnreadMentions","fetchUnreadReactions","transcribeAudio","inputGifBot","fetchFullUser","input","userWithFullInfo","fetchCommonChats","commonChats","mtpChat","isFullyLoaded","fetchNearestCountry","dcInfo","fetchTopUsers","topPeers","correspondents","fetchContactList","fetchUsers","importContact","imported","updateContact","shouldSharePhoneNumber","addPhonePrivacyException","deleteContact","fetchProfilePhotos","userOrChat","fetchCustomEmojiSets","allStickers","sets","fetchStickerSets","fetchRecentStickers","fetchFavoriteStickers","fetchFeaturedStickers","faveSticker","unfave","removeRecentSticker","unsave","clearRecentStickers","fetchStickers","fetchCustomEmoji","fetchAnimatedEmojis","fetchAnimatedEmojiEffects","fetchPremiumGifts","searchStickers","fetchSavedGifs","gifs","processGifResult","saveGif","shouldUnsave","installStickerSet","stickerSetId","uninstallStickerSet","searchGifs","config","resolvedPeer","gifSearchUsername","foundGif","fetchStickersForEmoji","fetchEmojiKeywords","fromVersion","langCode","keywords","emojiKeyword","keyword","emoticons","checkChatUsername","setChatUsername","updatePrivateLink","fetchExportedChatInvites","admin","exportedInvites","invites","editExportedChatInvite","replaceInvite","oldInvite","newInvite","exportChatInvite","deleteExportedChatInvite","deleteRevokedExportedChatInvites","fetchChatInviteImporters","offsetUser","isRequested","importers","importer","buildChatInviteImporter","hideChatJoinRequest","isApproved","approved","hideAllChatJoinRequests","hideChatReportPanel","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","answerCallbackButton","isGame","fetchTopInlineBots","botsInline","fetchInlineBot","fetchInlineBotResults","switchPm","isGallery","gallery","help","buildApiBotInlineMediaResult","webDocument","webThumbnail","buildApiBotInlineResult","sendInlineBotResult","resultId","startBot","requestWebView","theme","isFromBotMenu","themeParams","fromBotMenu","requestSimpleWebView","prolongWebView","sendWebViewData","buttonText","loadAttachMenuBots","toggleBotInAttachMenu","requestBotUrlAuth","authResult","acceptBotUrlAuth","isWriteAllowed","writeAllowed","requestLinkUrlAuth","acceptLinkUrlAuth","getGroupCall","discardGroupCall","editGroupCallParticipant","presentationPaused","videoStopped","videoPaused","raiseHand","editGroupCallTitle","exportGroupCallInvite","fetchGroupCallParticipants","leaveGroupCall","joinGroupCall","inviteHash","joinAs","createGroupCall","joinGroupCallPresentation","toggleGroupCallStartSubscription","subscribed","leaveGroupCallPresentation","getDhConfig","dhConfig","g","p","discardCall","isBusy","requestCall","setCallRating","rating","comment","receivedCall","acceptCall","confirmCall","gA","sendSignalingData","buildShippingOptions","shippingOptions","prices","ac","cur","label","buildPaymentForm","form","formId","canSaveCredentials","passwordMissing","providerId","nativeProvider","nativeParams","savedInfo","nameRequested","phoneRequested","emailRequested","shippingAddressRequested","flexible","phoneToProvider","emailToProvider","mappedPrices","cleanedInfo","nativeData","needCardholderName","need_cardholder_name","needCountry","need_country","needZip","need_zip","publishableKey","publishable_key","publicToken","public_token","buildApiInvoiceFromForm","recurring","recurringTermsUrl","isRecurring","buildApiPremiumPromo","promo","statusText","statusEntities","videoSections","monthlyAmount","validateRequestedInfo","inputInvoice","requestInfo","shouldSave","sendPaymentForm","requestedInfoId","shippingOptionId","credentials","getPaymentForm","getReceipt","receipt","shipping","credentialsTitle","mapedPrices","shippingPrices","shippingMethod","buildReceipt","fetchPremiumPromo","reportPeer","reportProfilePhoto","localPhoto","buildInputPhoto","changeSessionSettings","changeSessionTtl","days","authorizationTtlDays","buildEmojiSounds","appConfig","emojies_sounds","access_hash","atob","file_reference_base64","getLimit","fallbackKey","BETA_LANG_CODES","updateProfile","checkUsername","updateUsername","updateProfilePhoto","uploadProfilePhoto","fetchWallpapers","filteredWallpapers","wallpapers","pattern","uploadWallpaper","fetchBlockedContacts","blockedIds","unblockContact","fetchAuthorizations","authorizations","ttlDays","terminateAuthorization","terminateAllAuthorizations","fetchWebAuthorizations","terminateWebAuthorization","terminateAllWebAuthorizations","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","fetchAppConfig","emojiSounds","defaultReaction","reactions_default","seenByMaxChatMembers","chat_read_mark_size_threshold","seenByExpiresAt","chat_read_mark_expire_period","autologinDomains","autologin_domains","autologinToken","autologin_token","urlAuthDomains","url_auth_domains","premiumBotUsername","premium_bot_username","premiumInvoiceSlug","premium_invoice_slug","premiumPromoOrder","premium_promo_order","isPremiumPurchaseBlocked","premium_purchase_blocked","limits","buildAppConfig","fetchCountryList","countryList","countries","nonHiddenCountries","phoneCodes","countryCodes","flat","sort","b","localeCompare","general","buildApiCountryList","fetchGlobalPrivacySettings","shouldArchiveAndMuteNewNonContact","archiveAndMuteNewNoncontactPeers","updateGlobalPrivacySettings","sendWatchingEmojiInteraction","sendEmojiInteraction","v","getAvailableReactions","sendReaction","fetchMessageReactions","fetchMessageReactionsList","setDefaultReaction","buildGraph","isPercentage","x","y","columns","hasSecondYAxis","y_scaled","types","y0","zoomToken","labelFormatter","xTickFormatter","tooltipFormatter","xTooltipFormatter","labels","hideCaption","subchart","show","isStacked","stacked","datasets","item","names","color","colors","substring","indexOf","calculateMinimapRange","defaultZoom","range","minIndex","maxIndex","minimapRange","begin","labelFromIndex","labelToIndex","buildStatisticsOverview","previous","change","percentage","toFixed","fetchChannelStatistics","stats","growthGraph","followersGraph","muteGraph","topHoursGraph","languagesGraph","viewsBySourceGraph","newFollowersBySourceGraph","interactionsGraph","followers","viewsPerPost","sharesPerPost","enabledNotifications","part","total","recentTopMessages","recentMessageInteractions","fetchGroupStatistics","membersGraph","messagesGraph","actionsGraph","viewers","posters","fetchMessageStatistics","viewsGraph","fetchMessagePublicForwards","buildMessagePublicForwards","fetchStatisticsAsyncGraph","currentPhoneCallState","PhoneCallState","waitForState","resolveState","pBN","Helpers","randomBN","pLast","randomLast","emojiData","emojiOffsets","authKey","fingerprint","Uint8Array","emojiCount","partOffset","byteLength","and","shiftLeft","or","modPow","generateEmojiFingerprint","AuthKey","setKey","MTProtoState","Logger","seqArray","Uint32Array","seq","encodedData","encryptMessageData","then","decode","decryptMessageData","createPhoneCallState","destroyPhoneCallState","encodePhoneCallData","encode","decodePhoneCallData","confirmPhoneCall","acceptPhoneCall","requestPhoneCall","initApi","_onUpdate","initialArgs","initUpdater","handleUpdate","initAuth","initChats","initMessages","initUsers","initStickers","initManagement","initTwoFaSettings","initBots","initCalls","initPayments","userAgent","maxBufferSize","sessions","TelegramClient","process","deviceModel","navigator","systemVersion","appVersion","useWSS","additionalDcsDisabled","testServers","addEventHandler","phoneCode","firstAndLastNames","initialMethod","shouldThrowIfUnauthorized","getSessionData","initClient","flushUpdatesOnTickEnd","schedulerFn","fn","waiting","_args","throttleWith","callback","isPrimary","currentCallbacks","currentPrimaryCallbacks","cb","throttleId","pendingUpdates","currentThrottleId","currentUpdates","flushUpdatesThrottled","ms","interval","shouldRunFirst","setInterval","clearInterval","throttle","onerror","sendToOrigin","addEventListener","callbackState","Map","postMessage","onmessage","callbackArgs","lastArg","fnName","methods","callApi","require","crypto","little","signed","randBuffer","bytesNumber","bigInt","subtract","pow","toSignedLittleBuffer","number","bigNumber","byteArray","shiftRight","readBufferFromBigInt","bitLength","lesser","below","hex","padStart","reminder","randomBytes","sha1","shaSum","createHash","digest","crcTable","module","exports","generateRandomLong","mod","m","crc32","buf","k","makeCRCTable","isBuffer","crc","generateKeyDataFromNonce","serverNonce","newNonce","hash1","hash2","hash3","iv","sha256","bigIntMod","remainder","modExp","one","greater","zero","leastSignificantBit","divide","eq","multiply","getRandomInt","sleep","getByteArray","integer","bits","convertToLittle","alloc","writeUInt32BE","bufferXor","res","createDeferred","promise","_resolve","constructors","checkPrimeAndGood","primeBytes","equals","numBytesForHash","bigNumForHash","isGoodModExpFirst","modexp","prime","diff","xor","computeHash","algo","salt1","salt2","salt","iterations","pbkdf2","pbkdf2sha512","computeCheck","currentAlgo","PasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow","pwHash","B","srp_B","isGoodLarge","pForHash","gForHash","bForHash","gX","kgX","aForHash","A","generateAndCheckRandom","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","getDownloadPartSize","fileSize","getUploadPartSize","stripped","header","getDC","downloadDC","ipAddress","pwd","Api","newAlgo","newSettings","newPasswordHash","newSecureSettings","codeLength","os","MemorySession","utils","Session","LAYER","requests","ConnectionTCPObfuscated","MTProtoSender","UpdateConnectionState","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","_waitingForAuthKey","_exportedSenderReleaseTimeouts","_additionalDcsDisabled","_loopStarted","_isSwitchingDc","_destroyed","_initSession","_sender","logger","retries","delay","connectTimeout","authKeyCallback","_authKeyCallback","bind","updateCallback","_handleUpdate","isMainSender","userDisconnected","_user_connected","isReconnecting","_disconnected","serverAddress","connect","setAuthKey","send","GetConfig","_updateLoop","load","setDC","lastPongAt","ping","PingDelayDisconnect","pingId","MIN_SAFE_INTEGER","MAX_SAFE_INTEGER","disconnectDelay","pingAt","lastInterval","attempts","wakeUpWarningTimeout","disconnected","clearTimeout","connected","getTime","_lastRequest","GetState","promises","sender","newDc","DC","firstConnectResolver","hasAuthKey","dc","_authenticated","auth","ExportAuthorization","req","ImportAuthorization","shouldReconnect","existingSender","_connectSender","_createExportedSender","isConnecting","_borrowExportedSender","onConnectionBreak","_cleanupExportedSender","getSender","inputLocation","messageOrMedia","Message","MessageMediaWebPage","WebPage","MessageMediaPhoto","Photo","_downloadPhoto","MessageMediaDocument","Document","_downloadDocument","MessageMediaContact","_downloadContact","WebDocument","WebDocumentNoProxy","_downloadWebDocument","loc","UserProfilePhoto","ChatPhoto","InputPeerPhotoFileLocation","thumbVersion","InputStickerSetThumb","InputStickerSetID","thumbDcId","_pickFileSize","_downloadCachedPhotoSize","PhotoStrippedSize","isVideoSize","PhotoSizeEmpty","PhotoCachedSize","InputPhotoFileLocation","thumbSize","doc","InputDocumentFileLocation","arrayBuff","buff","downloaded","upload","GetWebFile","InputWebFileLocation","InputWebFileGeoPointLocation","geoPoint","InputGeoPoint","FloodWaitError","attempt","sendWithInvokeSupport","ServerError","FloodTestPhoneWaitError","PhoneMigrateError","NetworkMigrateError","UserMigrateError","_switchDC","MsgWaitError","isReady","GetUsers","InputUserSelf","authParams","apiCredentials","fileParams","event","Updates","UpdatesCombined","_processUpdate","UpdateShort","others","_dispatchUpdate","ptsDate","builder","isResolved","race","finally","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","deferreds","releaseWorker","shift","FileView","FileSystemFileHandle","prototype","createSyncAccessHandle","directory","storage","getDirectory","downloadsFolder","getDirectoryHandle","create","largeFile","getFileHandle","largeFileAccessHandle","write","at","writeUInt8","getData","getFile","downloadFile2","SENDER_RETRIES","foremans","fill","partSizeKb","partSize","partsCount","noParallel","shouldUseMultipleConnections","fileView","activeCounts","currentForemanIndex","hasEnded","init","isPrecise","senderIndex","offsetMemo","precise","fileId","isLarge","partCount","sendingParts","j","blobSlice","jMemo","blobSliceMemo","partBytes","filePart","fileTotalParts","parts","md5Checksum","BinaryReader","_key","_hash","reader","auxHash","readLong","read","keyId","shaData","other","cipher","createCipheriv","encrypt","Factorizator","neq","temp","pq","randBetween","minus","ys","condition","gcd","IGE","AESIGE","ige","decryptIge","cipherText","decrypt","encryptIge","plainText","padding","i2abLow","uint8","int","i2abBig","ab2iLow","ab","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","to","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","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","getValue","_level","level","isBrowser","browser","__nwjs","debug","messageFormat","canSend","levels","stack","format","toISOString","toUpperCase","log","MessageContainer","TLMessage","BinaryWriter","USE_INVOKE_AFTER_WITH","_state","_pendingStates","_ready","setReady","append","after","extend","states","batch","MAXIMUM_LENGTH","SIZE_OVERHEAD","MAXIMUM_SIZE","afterId","writeDataAsMessage","unshift","writeUInt32LE","writeInt32LE","containerId","rejectAll","requestState","Mutex","mutex","WebSocketClient","closeError","disconnectedCallback","readData","thisTime","canRead","toReturn","resolveRead","getWebSocketLink","website","onopen","receive","onclose","wasClean","runExclusive","PromisedWebSockets","MessagePacker","AsyncQueue","tl","events","extensions","helpers","SERVER_KEYS","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","serverTime","gb","gab","clientDhInner","retryId","clientDdhInnerHashed","clientDhEncrypted","dhGen","nonceTypes","nonceNumber","calcNewNonceHash","loggers","body","_getNewMsgId","recv","MtProtoPlainSender","RPCResult","GZIPPacked","RequestState","MsgsAck","MsgsStateInfo","Pong","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","_disconnect","plain","_sendLoop","_recvLoop","ack","msgIds","isArray","reconnect","_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","aes","InvokeAfterMsg","isCall","_isCall","_isOutgoing","_lastMsgId","updateMessageId","msgKey","sha256a","sha256b","contentRelated","seqNo","_getSeqNo","gzipIfSmaller","waitForKey","lengthStart","_calcKey","ourKey","remoteMsgId","remoteSequence","containerLen","nanoseconds","newMsgId","correctMsgId","bad","old","Connection","_isPremium","_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","origin","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","readUInt8","serverAddressLen","readInt16BE","dcBuffer","addressBuffer","addressLengthBuffer","writeInt16BE","portBuffer","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","flagValue","flagIndex","flags2","idForBytes","buffers","flagCalculate","boxed","charAt","definitions","fromCache","jsonCache","loadFromCache","constructorParamsApi","functionParamsApi","constructorParamsSchema","functionParamsSchema","loadFromTlSchemas","obj1","obj2","mergeWithNamespaces","buildApiFromTlSchema","inflate","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","objAll","objByName","objByType","commentIndex","trim","followingTypes","dt","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","loaded","__webpack_modules__","__webpack_exports__","O","chunkIds","priority","notFulfilled","fulfilled","every","getter","__esModule","definition","defineProperty","enumerable","chunkId","miniCssF","globalThis","Function","prop","Symbol","toStringTag","nmd","paths","children","scriptUrl","importScripts","currentScript","src","scripts","getElementsByTagName","installedChunks","chunkLoadingGlobal","parentChunkLoadingFunction","moreModules","runtime"],"sourceRoot":""}