From 7255298500ee737c6ba26cc67fda20e40248c991 Mon Sep 17 00:00:00 2001 From: Alexander Zinchuk Date: Sat, 20 Nov 2021 12:19:11 +0300 Subject: [PATCH] [Build] --- .patch-version | 2 +- ...54.f579d864cf3b32d15240.js => 354.959e19f0ca3e2bb07043.js} | 2 +- ...864cf3b32d15240.js.map => 354.959e19f0ca3e2bb07043.js.map} | 2 +- ...14.89d97ccb086a4c539d1a.js => 514.3cef19392d72a10cf6ea.js} | 4 ++-- ...ccb086a4c539d1a.js.map => 514.3cef19392d72a10cf6ea.js.map} | 2 +- ...24.57eea32f15dc5514a3eb.js => 524.632897f7413c1c081b04.js} | 2 +- ...32f15dc5514a3eb.js.map => 524.632897f7413c1c081b04.js.map} | 2 +- dist/index.html | 2 +- dist/main.385008a5f5d046ca97cd.js.map | 1 - ...n.385008a5f5d046ca97cd.js => main.4f9a89db11e14d2fa319.js} | 4 ++-- dist/main.4f9a89db11e14d2fa319.js.map | 1 + dist/report.html | 4 ++-- 12 files changed, 14 insertions(+), 14 deletions(-) rename dist/{354.f579d864cf3b32d15240.js => 354.959e19f0ca3e2bb07043.js} (97%) rename dist/{354.f579d864cf3b32d15240.js.map => 354.959e19f0ca3e2bb07043.js.map} (99%) rename dist/{514.89d97ccb086a4c539d1a.js => 514.3cef19392d72a10cf6ea.js} (99%) rename dist/{514.89d97ccb086a4c539d1a.js.map => 514.3cef19392d72a10cf6ea.js.map} (99%) rename dist/{524.57eea32f15dc5514a3eb.js => 524.632897f7413c1c081b04.js} (99%) rename dist/{524.57eea32f15dc5514a3eb.js.map => 524.632897f7413c1c081b04.js.map} (99%) delete mode 100644 dist/main.385008a5f5d046ca97cd.js.map rename dist/{main.385008a5f5d046ca97cd.js => main.4f9a89db11e14d2fa319.js} (74%) create mode 100644 dist/main.4f9a89db11e14d2fa319.js.map diff --git a/.patch-version b/.patch-version index d00491fd..0cfbf088 100644 --- a/.patch-version +++ b/.patch-version @@ -1 +1 @@ -1 +2 diff --git a/dist/354.f579d864cf3b32d15240.js b/dist/354.959e19f0ca3e2bb07043.js similarity index 97% rename from dist/354.f579d864cf3b32d15240.js rename to dist/354.959e19f0ca3e2bb07043.js index 67a89d4e..b76be752 100644 --- a/dist/354.f579d864cf3b32d15240.js +++ b/dist/354.959e19f0ca3e2bb07043.js @@ -1,2 +1,2 @@ (()=>{"use strict";"undefined"!=typeof window&&window.innerHeight,Math.round(425),new Set(["newMessage","newScheduledMessage","deleteMessages","deleteScheduledMessages","deleteHistory"]);const e=new Set(["image/png","image/gif","image/jpeg"]),r=new Set(["video/mp4"]);new Set([...e,...r]),new Set(["AU","BD","CA","CO","EG","HN","IE","IN","JO","MX","MY","NI","NZ","PH","PK","SA","SV","US"]),self.onerror=e=>{console.error(e),n({type:"unhandledError",error:{message:e.error.message||"Uncaught exception in worker"}})},self.addEventListener("unhandledrejection",(e=>{console.error(e),n({type:"unhandledError",error:{message:e.reason.message||"Uncaught rejection in worker"}})}));const t=new Map;function n(e,r){r?postMessage(e,r):postMessage(e)}let s;self.importScripts("rlottie-wasm.js");const a=new Promise((e=>{Module.onRuntimeInitialized=()=>{s={init:Module.cwrap("lottie_init","",[]),destroy:Module.cwrap("lottie_destroy","",["number"]),resize:Module.cwrap("lottie_resize","",["number","number","number"]),buffer:Module.cwrap("lottie_buffer","number",["number"]),render:Module.cwrap("lottie_render","",["number","number"]),loadFromData:Module.cwrap("lottie_load_from_data","number",["number","number"])},e()}})),o=new Map;var i;i={init:async function(e,r,t,n,i,d){s||await a;const c=JSON.stringify(r),l=allocate(intArrayFromString(c),"i8",0),m=s.init(),u=s.loadFromData(m,l);s.resize(m,t,t),o.set(e,{imgSize:t,reduceFactor:i,handle:m}),d(Math.ceil(u/i))},renderFrames:async function(e,r,t,n){s||await a;const{imgSize:i,reduceFactor:d,handle:c}=o.get(e);for(let e=r;e<=t;e++){const r=e*d;s.render(c,r);const t=s.buffer(c),a=Module.HEAPU8.subarray(t,t+i*i*4);n(e,new Uint8ClampedArray(a).buffer)}},destroy:function(e){const r=o.get(e);s.destroy(r.handle),o.delete(e)}},onmessage=async e=>{const{data:r}=e;switch(r.type){case"callMethod":{const{messageId:e,name:s,args:a}=r;try{if(e){const r=(...r)=>{const t=r[r.length-1];n({type:"methodCallback",messageId:e,callbackArgs:r},t instanceof ArrayBuffer?[t]:void 0)};t.set(e,r),a.push(r)}const[r,o]=await i[s](...a)||[];e&&n({type:"methodResponse",messageId:e,response:r},o)}catch(r){e&&n({type:"methodResponse",messageId:e,error:{message:r.message}})}e&&t.delete(e);break}case"cancelProgress":{const e=t.get(r.messageId);e&&(e.isCanceled=!0);break}}}})(); -//# sourceMappingURL=354.f579d864cf3b32d15240.js.map \ No newline at end of file +//# sourceMappingURL=354.959e19f0ca3e2bb07043.js.map \ No newline at end of file diff --git a/dist/354.f579d864cf3b32d15240.js.map b/dist/354.959e19f0ca3e2bb07043.js.map similarity index 99% rename from dist/354.f579d864cf3b32d15240.js.map rename to dist/354.959e19f0ca3e2bb07043.js.map index db017448..5e22e4f1 100644 --- a/dist/354.f579d864cf3b32d15240.js.map +++ b/dist/354.959e19f0ca3e2bb07043.js.map @@ -1 +1 @@ -{"version":3,"file":"354.f579d864cf3b32d15240.js","mappings":"mBAuCsC,oBAAXA,QAA0BA,OAAOC,YAgEzBC,KAAKC,MAAM,KACJ,IAAIC,IAAI,CAChD,aAAc,sBAAuB,iBAAkB,0BAA2B,kBAzG7E,MAmIMC,EAAgC,IAAID,IAAI,CACnD,YAAa,YAAa,eAGfE,EAAgC,IAAIF,IAAI,CACnD,cAGwC,IAAIA,IAAI,IAC7CC,KACAC,IAUyC,IAAIF,IAAI,CAAC,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,OCxE3JG,KAAKC,QAAWC,IAEdC,QAAQC,MAAMF,GACdG,EAAa,CAAEC,KAAM,iBAAkBF,MAAO,CAAEG,QAASL,EAAEE,MAAMG,SAAW,mC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B,EAAIJ,EAAWI,GAAKH,EAASG,IAAK,CACzC,MAAMC,EAAYD,EAAIjB,EAEtBrB,EAAWY,OAAOiB,EAAQU,GAC1B,MAAMC,EAAgBxC,EAAWW,OAAOkB,GAClChC,EAAOQ,OAAOoC,OAAOC,SAASF,EAAeA,EAAiBrB,EAAUA,EAAU,GAExFiB,EAAWE,EADS,IAAIK,kBAAkB9C,GAAMc,UAgBlDF,QAXF,SAAiBQ,GACf,MAAM2B,EAAW9B,EAAUuB,IAAIpB,GAE/BjB,EAAWS,QAAQmC,EAASf,QAE5Bf,EAAU+B,OAAO5B,KDzEjB6B,UAAY9B,MAAAA,IACV,MAAM,KAAEnB,GAASL,EAEjB,OAAQK,EAAKN,MACX,IAAK,aAAc,CACjB,MAAM,UAAEwD,EAAF,KAAaC,EAAb,KAAmBC,GAASpD,EAClC,IACE,GAAIkD,EAAW,CACb,MAAMG,EAAW,IAAIC,KACnB,MAAMC,EAAUD,EAAaA,EAAaE,OAAS,GAEnD/D,EAAa,CACXC,KAAM,iBACNwD,UAAAA,EACAI,aAAAA,GACCC,aAAmBE,YAAc,CAACF,QAAWG,IAGlD5D,EAAcoC,IAAIgB,EAAWG,GAE7BD,EAAKO,KAAKN,GAGZ,MAAOO,EAAU3D,SAAuBiB,EAAIiC,MAASC,IAAU,GAE3DF,GACFzD,EACE,CACEC,KAAM,iBACNwD,UAAAA,EACAU,SAAAA,GAEF3D,GAGJ,MAAOT,GAMH0D,GACFzD,EAAa,CACXC,KAAM,iBACNwD,UAAAA,EACA1D,MAAO,CAAEG,QAASH,EAAMG,WAK1BuD,GACFpD,EAAckD,OAAOE,GAGvB,MAEF,IAAK,iBAAkB,CACrB,MAAMG,EAAWvD,EAAc0C,IAAIxC,EAAKkD,WACpCG,IACFA,EAASQ,YAAa,GAGxB,U","sources":["webpack://telegram-t/./src/config.ts","webpack://telegram-t/./src/util/createWorkerInterface.ts","webpack://telegram-t/./src/lib/rlottie/rlottie.worker.ts"],"sourcesContent":["export const PAGE_TITLE = 'Telegram';\nexport const INACTIVE_MARKER = ' [Inactive]';\n\nexport const APP_NAME = process.env.APP_NAME || 'Telegram WebZ';\nexport const APP_VERSION = process.env.APP_VERSION || 'dev';\n\nexport const DEBUG = (\n process.env.APP_ENV !== 'production' && process.env.APP_ENV !== 'perf' && process.env.APP_ENV !== 'test'\n);\nexport const DEBUG_MORE = false;\n\nexport const IS_TEST = process.env.APP_ENV === 'test';\nexport const IS_PERF = process.env.APP_ENV === 'perf';\n\nexport const DEBUG_ALERT_MSG = 'Shoot!\\nSomething went wrong, please see the error details in Dev Tools Console.';\nexport const DEBUG_GRAMJS = false;\n\nexport const SESSION_USER_KEY = 'user_auth';\nexport const LEGACY_SESSION_KEY = 'GramJs:sessionId';\n\nexport const GLOBAL_STATE_CACHE_DISABLED = false;\nexport const GLOBAL_STATE_CACHE_KEY = 'tt-global-state';\nexport const GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT = 30;\nexport const GLOBAL_STATE_CACHE_USER_LIST_LIMIT = 5000;\n\nexport const MEDIA_CACHE_DISABLED = false;\nexport const MEDIA_CACHE_NAME = 'tt-media';\nexport const MEDIA_CACHE_NAME_AVATARS = 'tt-media-avatars';\nexport const MEDIA_PROGRESSIVE_CACHE_DISABLED = false;\nexport const MEDIA_PROGRESSIVE_CACHE_NAME = 'tt-media-progressive';\nexport const MEDIA_CACHE_MAX_BYTES = 512 * 1024; // 512 KB\nexport const CUSTOM_BG_CACHE_NAME = 'tt-custom-bg';\nexport const LANG_CACHE_NAME = 'tt-lang-packs-v6';\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_SENSITIVE_AREA = 750;\nexport const MESSAGE_LIST_SLICE = isBigScreen ? 60 : 40;\nexport const MESSAGE_LIST_VIEWPORT_LIMIT = MESSAGE_LIST_SLICE * 2;\n\nexport const CHAT_HEIGHT_PX = 72;\nexport const CHAT_LIST_SLICE = isBigScreen ? 30 : 25;\nexport const CHAT_LIST_LOAD_SLICE = 100;\nexport const SHARED_MEDIA_SLICE = 42;\nexport const MESSAGE_SEARCH_SLICE = 42;\nexport const GLOBAL_SEARCH_SLICE = 20;\nexport const MEMBERS_SLICE = 30;\nexport const MEMBERS_LOAD_SLICE = 200;\nexport const PINNED_MESSAGES_LIMIT = 50;\nexport const BLOCKED_LIST_LIMIT = 100;\nexport const PROFILE_PHOTOS_LIMIT = 40;\nexport const PROFILE_SENSITIVE_AREA = 500;\nexport const COMMON_CHATS_LIMIT = 100;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 20;\nexport const ALL_CHATS_PRELOAD_DISABLED = false;\n\nexport const DEFAULT_VOLUME = 1;\nexport const DEFAULT_PLAYBACK_RATE = 1;\n\nexport const ANIMATION_LEVEL_MIN = 0;\nexport const ANIMATION_LEVEL_MED = 1;\nexport const ANIMATION_LEVEL_MAX = 2;\nexport const ANIMATION_LEVEL_DEFAULT = ANIMATION_LEVEL_MAX;\n\nexport const DEFAULT_MESSAGE_TEXT_SIZE_PX = 16;\nexport const IOS_DEFAULT_MESSAGE_TEXT_SIZE_PX = 17;\nexport const MACOS_DEFAULT_MESSAGE_TEXT_SIZE_PX = 15;\n\nexport const DRAFT_DEBOUNCE = 10000; // 10s\n\nexport const EDITABLE_INPUT_ID = 'editable-message-text';\nexport const EDITABLE_INPUT_MODAL_ID = 'editable-message-text-modal';\n\n// Screen width where Pinned Message / Audio Player in the Middle Header can be safely displayed\nexport const SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1440; // px\n// Screen width where Pinned Message / Audio Player in the Middle Header shouldn't collapse with ChatInfo\nexport const SAFE_SCREEN_WIDTH_FOR_CHAT_INFO = 1150; // px\n\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1275; // px\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN = 925; // px\nexport const MOBILE_SCREEN_MAX_WIDTH = 600; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH = 950; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT = 450; // px\n\nexport const LOCAL_MESSAGE_ID_BASE = 1e9;\nexport const TMP_CHAT_ID = '0';\n\nexport const ANIMATION_END_DELAY = 100;\n\nexport const FAST_SMOOTH_MAX_DISTANCE = 1500;\nexport const FAST_SMOOTH_MIN_DURATION = 250;\nexport const FAST_SMOOTH_MAX_DURATION = 600;\nexport const FAST_SMOOTH_SHORT_TRANSITION_MAX_DISTANCE = 500; // px\n\n// Average duration of message sending animation\nexport const API_UPDATE_THROTTLE = Math.round((FAST_SMOOTH_MIN_DURATION + FAST_SMOOTH_MAX_DURATION) / 2);\nexport const API_THROTTLE_RESET_UPDATES = new Set([\n 'newMessage', 'newScheduledMessage', 'deleteMessages', 'deleteScheduledMessages', 'deleteHistory',\n]);\n\nexport const STICKER_SIZE_INLINE_DESKTOP_FACTOR = 13;\nexport const STICKER_SIZE_INLINE_MOBILE_FACTOR = 11;\nexport const STICKER_SIZE_AUTH = 160;\nexport const STICKER_SIZE_AUTH_MOBILE = 120;\nexport const STICKER_SIZE_PICKER = 64;\nexport const STICKER_SIZE_GENERAL_SETTINGS = 48;\nexport const STICKER_SIZE_PICKER_HEADER = 32;\nexport const STICKER_SIZE_SEARCH = 64;\nexport const STICKER_SIZE_MODAL = 64;\nexport const STICKER_SIZE_TWO_FA = 160;\nexport const STICKER_SIZE_DISCUSSION_GROUPS = 140;\nexport const STICKER_SIZE_FOLDER_SETTINGS = 80;\nexport const STICKER_SIZE_INLINE_BOT_RESULT = 100;\nexport const RECENT_STICKERS_LIMIT = 20;\nexport const MEMOJI_STICKER_ID = 'MEMOJI_STICKER';\n\nexport const BASE_EMOJI_KEYWORD_LANG = 'en';\n\nexport const MENU_TRANSITION_DURATION = 200;\nexport const SLIDE_TRANSITION_DURATION = 450;\n\nexport const VIDEO_MOV_TYPE = 'video/quicktime';\n\nexport const SUPPORTED_IMAGE_CONTENT_TYPES = new Set([\n 'image/png', 'image/gif', 'image/jpeg',\n]);\n\nexport const SUPPORTED_VIDEO_CONTENT_TYPES = new Set([\n 'video/mp4', // video/quicktime added dynamically in environment.ts\n]);\n\nexport const CONTENT_TYPES_WITH_PREVIEW = new Set([\n ...SUPPORTED_IMAGE_CONTENT_TYPES,\n ...SUPPORTED_VIDEO_CONTENT_TYPES,\n]);\n\n// eslint-disable-next-line max-len\nexport const RE_LINK_TEMPLATE = '((ftp|https?):\\\\/\\\\/)?((www\\\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\\\.[a-zA-Z0-9()]{1,63})\\\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)';\nexport const RE_MENTION_TEMPLATE = '(@[\\\\w\\\\d_-]+)';\nexport const RE_TG_LINK = /^tg:(\\/\\/)?([?=&\\d\\w_-]+)?/gm;\nexport const RE_TME_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/)/gm;\n\n// eslint-disable-next-line max-len\nexport const COUNTRIES_WITH_12H_TIME_FORMAT = new Set(['AU', 'BD', 'CA', 'CO', 'EG', 'HN', 'IE', 'IN', 'JO', 'MX', 'MY', 'NI', 'NZ', 'PH', 'PK', 'SA', 'SV', 'US']);\n\n// MTProto constants\nexport const SERVICE_NOTIFICATIONS_USER_ID = '777000';\nexport const REPLIES_USER_ID = '1271266957'; // TODO For Test connection ID must be equal to 708513\nexport const ALL_FOLDER_ID = 0;\nexport const ARCHIVED_FOLDER_ID = 1;\nexport const DELETED_COMMENTS_CHANNEL_ID = '-777';\nexport const MAX_MEDIA_FILES_FOR_ALBUM = 10;\nexport const MAX_ACTIVE_PINNED_CHATS = 5;\nexport const SCHEDULED_WHEN_ONLINE = 0x7FFFFFFE;\nexport const DEFAULT_LANG_CODE = 'en';\nexport const DEFAULT_LANG_PACK = 'android';\nexport const LANG_PACKS = ['android', 'ios', 'tdesktop', 'macos'] as const;\nexport const TIPS_USERNAME = 'TelegramTips';\nexport const LOCALIZED_TIPS = ['ar', 'pt-br', 'id', 'it', 'ko', 'ms', 'pl', 'es', 'tr'];\nexport const FEEDBACK_URL = 'https://bugs.telegram.org/?tag_ids=41&sort=time';\nexport const LIGHT_THEME_BG_COLOR = '#A2AF8E';\nexport const DARK_THEME_BG_COLOR = '#0F0F0F';\nexport const DARK_THEME_PATTERN_COLOR = '#0a0a0a8c';\nexport const DEFAULT_PATTERN_COLOR = 'rgba(90, 110, 70, 0.6)';\n","import { CancellableCallback, OriginMessageEvent, WorkerMessageData } from './WorkerConnector';\nimport { DEBUG } from '../config';\n\ndeclare const self: WorkerGlobalScope;\n\nhandleErrors();\n\nconst callbackState = new Map();\n\nexport default function createInterface(api: Record) {\n onmessage = async (message: OriginMessageEvent) => {\n const { data } = message;\n\n switch (data.type) {\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, arrayBuffers] = (await api[name](...args)) || [];\n\n if (messageId) {\n sendToOrigin(\n {\n type: 'methodResponse',\n messageId,\n response,\n },\n arrayBuffers,\n );\n }\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(error);\n }\n\n if (messageId) {\n sendToOrigin({\n type: 'methodResponse',\n messageId,\n error: { message: error.message },\n });\n }\n }\n\n if (messageId) {\n callbackState.delete(messageId);\n }\n\n break;\n }\n case 'cancelProgress': {\n const callback = callbackState.get(data.messageId);\n if (callback) {\n callback.isCanceled = true;\n }\n\n break;\n }\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 sendToOrigin(data: WorkerMessageData, arrayBuffers?: ArrayBuffer[]) {\n if (arrayBuffers) {\n postMessage(data, arrayBuffers);\n } else {\n postMessage(data);\n }\n}\n","import createWorkerInterface from '../../util/createWorkerInterface';\nimport { CancellableCallback } from '../../util/WorkerConnector';\n\ndeclare const Module: any;\n\ndeclare function allocate(...args: any[]): string;\n\ndeclare function intArrayFromString(str: String): string;\n\ndeclare const self: WorkerGlobalScope;\n\nself.importScripts('rlottie-wasm.js');\n\nlet rLottieApi: Record;\nconst rLottieApiPromise = new Promise((resolve) => {\n Module.onRuntimeInitialized = () => {\n rLottieApi = {\n init: Module.cwrap('lottie_init', '', []),\n destroy: Module.cwrap('lottie_destroy', '', ['number']),\n resize: Module.cwrap('lottie_resize', '', ['number', 'number', 'number']),\n buffer: Module.cwrap('lottie_buffer', 'number', ['number']),\n render: Module.cwrap('lottie_render', '', ['number', 'number']),\n loadFromData: Module.cwrap('lottie_load_from_data', 'number', ['number', 'number']),\n };\n\n resolve();\n };\n});\n\nconst renderers = new Map();\n\nasync function init(\n key: string,\n animationData: AnyLiteral,\n imgSize: number,\n isLowPriority: boolean,\n reduceFactor: number,\n onInit: CancellableCallback,\n) {\n if (!rLottieApi) {\n await rLottieApiPromise;\n }\n\n const json = JSON.stringify(animationData);\n const stringOnWasmHeap = allocate(intArrayFromString(json), 'i8', 0);\n const handle = rLottieApi.init();\n const framesCount = rLottieApi.loadFromData(handle, stringOnWasmHeap);\n rLottieApi.resize(handle, imgSize, imgSize);\n\n renderers.set(key, { imgSize, reduceFactor, handle });\n\n onInit(Math.ceil(framesCount / reduceFactor));\n}\n\nasync function renderFrames(\n key: string, fromIndex: number, toIndex: number, onProgress: CancellableCallback,\n) {\n if (!rLottieApi) {\n await rLottieApiPromise;\n }\n\n const { imgSize, reduceFactor, handle } = renderers.get(key)!;\n\n for (let i = fromIndex; i <= toIndex; i++) {\n const realIndex = i * reduceFactor;\n\n rLottieApi.render(handle, realIndex);\n const bufferPointer = rLottieApi.buffer(handle);\n const data = Module.HEAPU8.subarray(bufferPointer, bufferPointer + (imgSize * imgSize * 4));\n const arrayBuffer = new Uint8ClampedArray(data).buffer;\n onProgress(i, arrayBuffer);\n }\n}\n\nfunction destroy(key: string) {\n const renderer = renderers.get(key)!;\n\n rLottieApi.destroy(renderer.handle);\n\n renderers.delete(key);\n}\n\ncreateWorkerInterface({\n init,\n renderFrames,\n destroy,\n});\n"],"names":["window","innerHeight","Math","round","Set","SUPPORTED_IMAGE_CONTENT_TYPES","SUPPORTED_VIDEO_CONTENT_TYPES","self","onerror","e","console","error","sendToOrigin","type","message","addEventListener","reason","callbackState","Map","data","arrayBuffers","postMessage","rLottieApi","importScripts","rLottieApiPromise","Promise","resolve","Module","onRuntimeInitialized","init","cwrap","destroy","resize","buffer","render","loadFromData","renderers","api","async","key","animationData","imgSize","isLowPriority","reduceFactor","onInit","json","JSON","stringify","stringOnWasmHeap","allocate","intArrayFromString","handle","framesCount","set","ceil","renderFrames","fromIndex","toIndex","onProgress","get","i","realIndex","bufferPointer","HEAPU8","subarray","Uint8ClampedArray","renderer","delete","onmessage","messageId","name","args","callback","callbackArgs","lastArg","length","ArrayBuffer","undefined","push","response","isCanceled"],"sourceRoot":""} \ No newline at end of file +{"version":3,"file":"354.959e19f0ca3e2bb07043.js","mappings":"mBAuCsC,oBAAXA,QAA0BA,OAAOC,YAgEzBC,KAAKC,MAAM,KACJ,IAAIC,IAAI,CAChD,aAAc,sBAAuB,iBAAkB,0BAA2B,kBAzG7E,MAmIMC,EAA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,GAGJ,MAAOT,GAMH0D,GACFzD,EAAa,CACXC,KAAM,iBACNwD,UAAAA,EACA1D,MAAO,CAAEG,QAASH,EAAMG,WAK1BuD,GACFpD,EAAckD,OAAOE,GAGvB,MAEF,IAAK,iBAAkB,CACrB,MAAMG,EAAWvD,EAAc0C,IAAIxC,EAAKkD,WACpCG,IACFA,EAASQ,YAAa,GAGxB,U","sources":["webpack://telegram-t/./src/config.ts","webpack://telegram-t/./src/util/createWorkerInterface.ts","webpack://telegram-t/./src/lib/rlottie/rlottie.worker.ts"],"sourcesContent":["export const PAGE_TITLE = 'Telegram';\nexport const INACTIVE_MARKER = ' [Inactive]';\n\nexport const APP_NAME = process.env.APP_NAME || 'Telegram WebZ';\nexport const APP_VERSION = process.env.APP_VERSION || 'dev';\n\nexport const DEBUG = (\n process.env.APP_ENV !== 'production' && process.env.APP_ENV !== 'perf' && process.env.APP_ENV !== 'test'\n);\nexport const DEBUG_MORE = false;\n\nexport const IS_TEST = process.env.APP_ENV === 'test';\nexport const IS_PERF = process.env.APP_ENV === 'perf';\n\nexport const DEBUG_ALERT_MSG = 'Shoot!\\nSomething went wrong, please see the error details in Dev Tools Console.';\nexport const DEBUG_GRAMJS = false;\n\nexport const SESSION_USER_KEY = 'user_auth';\nexport const LEGACY_SESSION_KEY = 'GramJs:sessionId';\n\nexport const GLOBAL_STATE_CACHE_DISABLED = false;\nexport const GLOBAL_STATE_CACHE_KEY = 'tt-global-state';\nexport const GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT = 30;\nexport const GLOBAL_STATE_CACHE_USER_LIST_LIMIT = 5000;\n\nexport const MEDIA_CACHE_DISABLED = false;\nexport const MEDIA_CACHE_NAME = 'tt-media';\nexport const MEDIA_CACHE_NAME_AVATARS = 'tt-media-avatars';\nexport const MEDIA_PROGRESSIVE_CACHE_DISABLED = false;\nexport const MEDIA_PROGRESSIVE_CACHE_NAME = 'tt-media-progressive';\nexport const MEDIA_CACHE_MAX_BYTES = 512 * 1024; // 512 KB\nexport const CUSTOM_BG_CACHE_NAME = 'tt-custom-bg';\nexport const LANG_CACHE_NAME = 'tt-lang-packs-v6';\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_SENSITIVE_AREA = 750;\nexport const MESSAGE_LIST_SLICE = isBigScreen ? 60 : 40;\nexport const MESSAGE_LIST_VIEWPORT_LIMIT = MESSAGE_LIST_SLICE * 2;\n\nexport const CHAT_HEIGHT_PX = 72;\nexport const CHAT_LIST_SLICE = isBigScreen ? 30 : 25;\nexport const CHAT_LIST_LOAD_SLICE = 100;\nexport const SHARED_MEDIA_SLICE = 42;\nexport const MESSAGE_SEARCH_SLICE = 42;\nexport const GLOBAL_SEARCH_SLICE = 20;\nexport const MEMBERS_SLICE = 30;\nexport const MEMBERS_LOAD_SLICE = 200;\nexport const PINNED_MESSAGES_LIMIT = 50;\nexport const BLOCKED_LIST_LIMIT = 100;\nexport const PROFILE_PHOTOS_LIMIT = 40;\nexport const PROFILE_SENSITIVE_AREA = 500;\nexport const COMMON_CHATS_LIMIT = 100;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 20;\nexport const ALL_CHATS_PRELOAD_DISABLED = false;\n\nexport const DEFAULT_VOLUME = 1;\nexport const DEFAULT_PLAYBACK_RATE = 1;\n\nexport const ANIMATION_LEVEL_MIN = 0;\nexport const ANIMATION_LEVEL_MED = 1;\nexport const ANIMATION_LEVEL_MAX = 2;\nexport const ANIMATION_LEVEL_DEFAULT = ANIMATION_LEVEL_MAX;\n\nexport const DEFAULT_MESSAGE_TEXT_SIZE_PX = 16;\nexport const IOS_DEFAULT_MESSAGE_TEXT_SIZE_PX = 17;\nexport const MACOS_DEFAULT_MESSAGE_TEXT_SIZE_PX = 15;\n\nexport const DRAFT_DEBOUNCE = 10000; // 10s\n\nexport const EDITABLE_INPUT_ID = 'editable-message-text';\nexport const EDITABLE_INPUT_MODAL_ID = 'editable-message-text-modal';\n\n// Screen width where Pinned Message / Audio Player in the Middle Header can be safely displayed\nexport const SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1440; // px\n// Screen width where Pinned Message / Audio Player in the Middle Header shouldn't collapse with ChatInfo\nexport const SAFE_SCREEN_WIDTH_FOR_CHAT_INFO = 1150; // px\n\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1275; // px\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN = 925; // px\nexport const MOBILE_SCREEN_MAX_WIDTH = 600; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH = 950; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT = 450; // px\n\nexport const LOCAL_MESSAGE_ID_BASE = 1e9;\nexport const TMP_CHAT_ID = '0';\n\nexport const ANIMATION_END_DELAY = 100;\n\nexport const FAST_SMOOTH_MAX_DISTANCE = 1500;\nexport const FAST_SMOOTH_MIN_DURATION = 250;\nexport const FAST_SMOOTH_MAX_DURATION = 600;\nexport const FAST_SMOOTH_SHORT_TRANSITION_MAX_DISTANCE = 500; // px\n\n// Average duration of message sending animation\nexport const API_UPDATE_THROTTLE = Math.round((FAST_SMOOTH_MIN_DURATION + FAST_SMOOTH_MAX_DURATION) / 2);\nexport const API_THROTTLE_RESET_UPDATES = new Set([\n 'newMessage', 'newScheduledMessage', 'deleteMessages', 'deleteScheduledMessages', 'deleteHistory',\n]);\n\nexport const STICKER_SIZE_INLINE_DESKTOP_FACTOR = 13;\nexport const STICKER_SIZE_INLINE_MOBILE_FACTOR = 11;\nexport const STICKER_SIZE_AUTH = 160;\nexport const STICKER_SIZE_AUTH_MOBILE = 120;\nexport const STICKER_SIZE_PICKER = 64;\nexport const STICKER_SIZE_GENERAL_SETTINGS = 48;\nexport const STICKER_SIZE_PICKER_HEADER = 32;\nexport const STICKER_SIZE_SEARCH = 64;\nexport const STICKER_SIZE_MODAL = 64;\nexport const STICKER_SIZE_TWO_FA = 160;\nexport const STICKER_SIZE_DISCUSSION_GROUPS = 140;\nexport const STICKER_SIZE_FOLDER_SETTINGS = 80;\nexport const STICKER_SIZE_INLINE_BOT_RESULT = 100;\nexport const RECENT_STICKERS_LIMIT = 20;\nexport const MEMOJI_STICKER_ID = 'MEMOJI_STICKER';\n\nexport const BASE_EMOJI_KEYWORD_LANG = 'en';\n\nexport const MENU_TRANSITION_DURATION = 200;\nexport const SLIDE_TRANSITION_DURATION = 450;\n\nexport const VIDEO_MOV_TYPE = 'video/quicktime';\n\nexport const SUPPORTED_IMAGE_CONTENT_TYPES = new Set([\n 'image/png', 'image/gif', 'image/jpeg',\n]);\n\nexport const SUPPORTED_VIDEO_CONTENT_TYPES = new Set([\n 'video/mp4', // video/quicktime added dynamically in environment.ts\n]);\n\nexport const CONTENT_TYPES_WITH_PREVIEW = new Set([\n ...SUPPORTED_IMAGE_CONTENT_TYPES,\n ...SUPPORTED_VIDEO_CONTENT_TYPES,\n]);\n\n// eslint-disable-next-line max-len\nexport const RE_LINK_TEMPLATE = '((ftp|https?):\\\\/\\\\/)?((www\\\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\\\.[a-zA-Z0-9()]{1,63})\\\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)';\nexport const RE_MENTION_TEMPLATE = '(@[\\\\w\\\\d_-]+)';\nexport const RE_TG_LINK = /^tg:(\\/\\/)?([?=&\\d\\w_-]+)?/gm;\nexport const RE_TME_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/)/gm;\n\n// eslint-disable-next-line max-len\nexport const COUNTRIES_WITH_12H_TIME_FORMAT = new Set(['AU', 'BD', 'CA', 'CO', 'EG', 'HN', 'IE', 'IN', 'JO', 'MX', 'MY', 'NI', 'NZ', 'PH', 'PK', 'SA', 'SV', 'US']);\n\n// MTProto constants\nexport const SERVICE_NOTIFICATIONS_USER_ID = '777000';\nexport const REPLIES_USER_ID = '1271266957'; // TODO For Test connection ID must be equal to 708513\nexport const ALL_FOLDER_ID = 0;\nexport const ARCHIVED_FOLDER_ID = 1;\nexport const DELETED_COMMENTS_CHANNEL_ID = '-777';\nexport const MAX_MEDIA_FILES_FOR_ALBUM = 10;\nexport const MAX_ACTIVE_PINNED_CHATS = 5;\nexport const SCHEDULED_WHEN_ONLINE = 0x7FFFFFFE;\nexport const DEFAULT_LANG_CODE = 'en';\nexport const DEFAULT_LANG_PACK = 'android';\nexport const LANG_PACKS = ['android', 'ios', 'tdesktop', 'macos'] as const;\nexport const TIPS_USERNAME = 'TelegramTips';\nexport const LOCALIZED_TIPS = ['ar', 'pt-br', 'id', 'it', 'ko', 'ms', 'pl', 'es', 'tr'];\nexport const FEEDBACK_URL = 'https://bugs.telegram.org/?tag_ids=41&sort=time';\nexport const LIGHT_THEME_BG_COLOR = '#A2AF8E';\nexport const DARK_THEME_BG_COLOR = '#0F0F0F';\nexport const DARK_THEME_PATTERN_COLOR = '#0a0a0a8c';\nexport const DEFAULT_PATTERN_COLOR = 'rgba(90, 110, 70, 0.6)';\n","import { CancellableCallback, OriginMessageEvent, WorkerMessageData } from './WorkerConnector';\nimport { DEBUG } from '../config';\n\ndeclare const self: WorkerGlobalScope;\n\nhandleErrors();\n\nconst callbackState = new Map();\n\nexport default function createInterface(api: Record) {\n onmessage = async (message: OriginMessageEvent) => {\n const { data } = message;\n\n switch (data.type) {\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, arrayBuffers] = (await api[name](...args)) || [];\n\n if (messageId) {\n sendToOrigin(\n {\n type: 'methodResponse',\n messageId,\n response,\n },\n arrayBuffers,\n );\n }\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(error);\n }\n\n if (messageId) {\n sendToOrigin({\n type: 'methodResponse',\n messageId,\n error: { message: error.message },\n });\n }\n }\n\n if (messageId) {\n callbackState.delete(messageId);\n }\n\n break;\n }\n case 'cancelProgress': {\n const callback = callbackState.get(data.messageId);\n if (callback) {\n callback.isCanceled = true;\n }\n\n break;\n }\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 sendToOrigin(data: WorkerMessageData, arrayBuffers?: ArrayBuffer[]) {\n if (arrayBuffers) {\n postMessage(data, arrayBuffers);\n } else {\n postMessage(data);\n }\n}\n","import createWorkerInterface from '../../util/createWorkerInterface';\nimport { CancellableCallback } from '../../util/WorkerConnector';\n\ndeclare const Module: any;\n\ndeclare function allocate(...args: any[]): string;\n\ndeclare function intArrayFromString(str: String): string;\n\ndeclare const self: WorkerGlobalScope;\n\nself.importScripts('rlottie-wasm.js');\n\nlet rLottieApi: Record;\nconst rLottieApiPromise = new Promise((resolve) => {\n Module.onRuntimeInitialized = () => {\n rLottieApi = {\n init: Module.cwrap('lottie_init', '', []),\n destroy: Module.cwrap('lottie_destroy', '', ['number']),\n resize: Module.cwrap('lottie_resize', '', ['number', 'number', 'number']),\n buffer: Module.cwrap('lottie_buffer', 'number', ['number']),\n render: Module.cwrap('lottie_render', '', ['number', 'number']),\n loadFromData: Module.cwrap('lottie_load_from_data', 'number', ['number', 'number']),\n };\n\n resolve();\n };\n});\n\nconst renderers = new Map();\n\nasync function init(\n key: string,\n animationData: AnyLiteral,\n imgSize: number,\n isLowPriority: boolean,\n reduceFactor: number,\n onInit: CancellableCallback,\n) {\n if (!rLottieApi) {\n await rLottieApiPromise;\n }\n\n const json = JSON.stringify(animationData);\n const stringOnWasmHeap = allocate(intArrayFromString(json), 'i8', 0);\n const handle = rLottieApi.init();\n const framesCount = rLottieApi.loadFromData(handle, stringOnWasmHeap);\n rLottieApi.resize(handle, imgSize, imgSize);\n\n renderers.set(key, { imgSize, reduceFactor, handle });\n\n onInit(Math.ceil(framesCount / reduceFactor));\n}\n\nasync function renderFrames(\n key: string, fromIndex: number, toIndex: number, onProgress: CancellableCallback,\n) {\n if (!rLottieApi) {\n await rLottieApiPromise;\n }\n\n const { imgSize, reduceFactor, handle } = renderers.get(key)!;\n\n for (let i = fromIndex; i <= toIndex; i++) {\n const realIndex = i * reduceFactor;\n\n rLottieApi.render(handle, realIndex);\n const bufferPointer = rLottieApi.buffer(handle);\n const data = Module.HEAPU8.subarray(bufferPointer, bufferPointer + (imgSize * imgSize * 4));\n const arrayBuffer = new Uint8ClampedArray(data).buffer;\n onProgress(i, arrayBuffer);\n }\n}\n\nfunction destroy(key: string) {\n const renderer = renderers.get(key)!;\n\n rLottieApi.destroy(renderer.handle);\n\n renderers.delete(key);\n}\n\ncreateWorkerInterface({\n init,\n renderFrames,\n destroy,\n});\n"],"names":["window","innerHeight","Math","round","Set","SUPPORTED_IMAGE_CONTENT_TYPES","SUPPORTED_VIDEO_CONTENT_TYPES","self","onerror","e","console","error","sendToOrigin","type","message","addEventListener","reason","callbackState","Map","data","arrayBuffers","postMessage","rLottieApi","importScripts","rLottieApiPromise","Promise","resolve","Module","onRuntimeInitialized","init","cwrap","destroy","resize","buffer","render","loadFromData","renderers","api","async","key","animationData","imgSize","isLowPriority","reduceFactor","onInit","json","JSON","stringify","stringOnWasmHeap","allocate","intArrayFromString","handle","framesCount","set","ceil","renderFrames","fromIndex","toIndex","onProgress","get","i","realIndex","bufferPointer","HEAPU8","subarray","Uint8ClampedArray","renderer","delete","onmessage","messageId","name","args","callback","callbackArgs","lastArg","length","ArrayBuffer","undefined","push","response","isCanceled"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/514.89d97ccb086a4c539d1a.js b/dist/514.3cef19392d72a10cf6ea.js similarity index 99% rename from dist/514.89d97ccb086a4c539d1a.js rename to dist/514.3cef19392d72a10cf6ea.js index ab13887d..103e850c 100644 --- a/dist/514.89d97ccb086a4c539d1a.js +++ b/dist/514.3cef19392d72a10cf6ea.js @@ -1,2 +1,2 @@ -(()=>{var e,t,n={6514:(e,t,n)=>{"use strict";var s={};n.r(s),n.d(s,{Type:()=>Ct,clear:()=>Pt,fetch:()=>It,save:()=>vt});var a={};n.r(a),n.d(a,{addChatMembers:()=>Sn,addContact:()=>ys,answerCallbackButton:()=>Ua,blockContact:()=>ra,checkChatUsername:()=>Fs,checkPassword:()=>Ws,checkUsername:()=>ea,clearDraft:()=>$t,clearPassword:()=>js,createChannel:()=>Qt,createGroupChat:()=>nn,deleteChannel:()=>tn,deleteChat:()=>Yt,deleteChatFolder:()=>ln,deleteChatMember:()=>An,deleteChatUser:()=>Zt,deleteHistory:()=>zn,deleteMessages:()=>Gn,deleteScheduledMessages:()=>Kn,deleteUser:()=>bs,destroy:()=>Et,disconnect:()=>Tt,downloadMedia:()=>Vt,editChatFolder:()=>dn,editChatPhoto:()=>sn,editMessage:()=>Fn,faveSticker:()=>As,fetchAnimatedEmojis:()=>ks,fetchAuthorizations:()=>da,fetchBlockedContacts:()=>oa,fetchChat:()=>zt,fetchChatFolders:()=>rn,fetchChats:()=>Ht,fetchCommonChats:()=>gs,fetchContactList:()=>hs,fetchContentSettings:()=>Pa,fetchCountryList:()=>Ma,fetchCurrentUser:()=>Ot,fetchEmojiKeywords:()=>xs,fetchFavoriteStickers:()=>Ps,fetchFeaturedStickers:()=>Ss,fetchFullChat:()=>Gt,fetchFullUser:()=>us,fetchGroupsForDiscussion:()=>Cn,fetchInlineBot:()=>Ta,fetchInlineBotResults:()=>Da,fetchLangPack:()=>_a,fetchLangStrings:()=>ya,fetchLanguages:()=>ma,fetchMembers:()=>wn,fetchMessage:()=>Bn,fetchMessages:()=>Dn,fetchNearestCountry:()=>ps,fetchNotificationExceptions:()=>ga,fetchNotificationSettings:()=>pa,fetchPinnedMessages:()=>os,fetchPrivacySettings:()=>ba,fetchProfilePhotos:()=>ws,fetchRecentStickers:()=>vs,fetchRecommendedChatFolders:()=>cn,fetchSavedGifs:()=>Us,fetchScheduledHistory:()=>ss,fetchStickerSets:()=>Is,fetchStickers:()=>Ms,fetchStickersForEmoji:()=>Bs,fetchTopInlineBots:()=>Ea,fetchTopUsers:()=>fs,fetchUsers:()=>ms,fetchWallpapers:()=>aa,fetchWebPagePreview:()=>Zn,findFirstMessageIdAfterDate:()=>ns,forwardMessages:()=>ts,getChatByUsername:()=>gn,getPasswordInfo:()=>Ks,getPaymentForm:()=>La,getReceipt:()=>qa,importChatInvite:()=>Rn,installStickerSet:()=>Es,joinChannel:()=>Xt,leaveChannel:()=>en,loadPollOptionResults:()=>es,markMessageListRead:()=>jn,markMessagesRead:()=>$n,migrateChat:()=>vn,openChatByInvite:()=>Pn,pinMessage:()=>qn,provideAuthCode:()=>pt,provideAuthPassword:()=>ft,provideAuthPhoneNumber:()=>gt,provideAuthRegistration:()=>ht,provideRecoveryEmailCode:()=>Qs,registerDevice:()=>wa,reportMessages:()=>Wn,requestChatUpdate:()=>Wt,requestThreadInfoUpdate:()=>Jn,rescheduleMessage:()=>On,restartAuth:()=>mt,restartAuthWithQr:()=>_t,saveDraft:()=>jt,searchChats:()=>Kt,searchGifs:()=>Ds,searchMessagesGlobal:()=>Xn,searchMessagesLocal:()=>Qn,searchStickers:()=>Rs,sendInlineBotResult:()=>Ba,sendMessage:()=>Vn,sendPaymentForm:()=>Oa,sendPollVote:()=>Yn,sendScheduledMessages:()=>as,setChatUsername:()=>Os,setDiscussionGroup:()=>In,setPrivacySettings:()=>Ia,startBot:()=>xa,terminateAllAuthorizations:()=>ua,terminateAuthorization:()=>la,toggleChatArchived:()=>on,toggleChatPinned:()=>an,toggleDialogUnread:()=>un,togglePreHistoryHidden:()=>pn,toggleSignatures:()=>bn,unblockContact:()=>ca,uninstallStickerSet:()=>Ts,unpinAllMessages:()=>Hn,unregisterDevice:()=>Ca,updateChatAbout:()=>yn,updateChatAdmin:()=>mn,updateChatDefaultBannedRights:()=>fn,updateChatMemberBannedRights:()=>hn,updateChatMutedState:()=>Jt,updateChatTitle:()=>_n,updateContact:()=>_s,updateContactSignUpNotification:()=>fa,updateContentSettings:()=>Sa,updateIsOnline:()=>va,updateNotificationSettings:()=>ha,updatePassword:()=>$s,updatePrivateLink:()=>Ls,updateProfile:()=>Ys,updateProfilePhoto:()=>na,updateRecoveryEmail:()=>Js,updateUsername:()=>ta,uploadProfilePhoto:()=>sa,uploadWallpaper:()=>ia,validateRequestedInfo:()=>Fa});const i=("undefined"!=typeof window&&window.innerHeight,Math.round(425)),o=new Set(["newMessage","newScheduledMessage","deleteMessages","deleteScheduledMessages","deleteHistory"]),r=new Set(["image/png","image/gif","image/jpeg"]),c=new Set(["video/mp4"]),d=(new Set([...r,...c]),new Set(["AU","BD","CA","CO","EG","HN","IE","IN","JO","MX","MY","NI","NZ","PH","PK","SA","SV","US"]),"777000");let l,u;var g=n(3522);function p(e,t){return e.reduce(((e,n)=>(e[n[t]]=n,e)),{})}function f(e,t){return t.reduce(((t,n)=>(t[n]=e[n],t)),{})}var h=n(8960);function m(e,t=!1,n="image/jpeg"){return`${t?"":`data:${n};base64,`}${btoa(String.fromCharCode(...e))}`}function _(e){const{flags:t,CONSTRUCTOR_ID:n,SUBCLASS_OF_ID:s,className:a,classType:i,getBytes:o,...r}=e;return r}function y(e,t,n){return''.replace("{{path}}",function(e){let t="M";const n=e.length;for(let s=0;s=192?t+="AACAAAAHAAALMAAAQASTAVAAAZaacaaaahaaalmaaaqastava.az0123456789-,"[n-128-64]:(n>=128?t+=",":n>=64&&(t+="-"),t+=String(63&n))}return t+="z",t}(e)).replace("{{width}}",String(t)).replace("{{height}}",String(n))}const b={w:100,h:100};function w(e,t){if(!e||!e.length)return;const n=e.find((e=>e instanceof g.Api.PhotoStrippedSize));if(!n)return;const s=e.filter((e=>e instanceof g.Api.PhotoSize)),{w:a,h:i}=s.length?s[s.length-1]:b,{bytes:o}=n;return{dataUri:m(t&&"image/jpeg"!==t?o:(0,h.strippedPhotoToJpg)(o),void 0,t),width:a,height:i}}function C(e){const t=e.sizes.filter((e=>e instanceof g.Api.PhotoSize||e instanceof g.Api.PhotoSizeProgressive)).map(I);return{id:String(e.id),thumbnail:w(e.sizes),sizes:t}}function I(e){const{w:t,h:n,type:s}=e;return{width:t,height:n,type:s}}const v={localMessages:{},chats:{},users:{},messages:{},documents:{},stickerSets:{},photos:{},webDocuments:{}},P="application/x-tgsticker";function S(e){if(e instanceof g.Api.DocumentEmpty)return;const t=e.attributes.find((e=>e instanceof g.Api.DocumentAttributeSticker)),n=e.mimeType===P&&e.attributes.find((e=>e instanceof g.Api.DocumentAttributeFilename));if(!t&&!n)return;const s=e.attributes.find((e=>e instanceof g.Api.DocumentAttributeImageSize)),a=t&&t.stickerset instanceof g.Api.InputStickerSetID?t.stickerset:void 0,i=null==t?void 0:t.alt,o=e.mimeType===P,r=e.thumbs&&e.thumbs.find((e=>e instanceof g.Api.PhotoCachedSize)),c=e.thumbs&&e.thumbs.find((e=>e instanceof g.Api.PhotoPathSize)),d=r?function(e){const{w:t,h:n,bytes:s}=e;return{dataUri:m(s,void 0,"image/webp"),width:t,height:n}}(r):c&&s?function(e,t){const{w:n,h:s}=t;return{dataUri:`data:image/svg+xml;utf8,${y(e.bytes,n,s)}`,width:n,height:s}}(c,s):void 0,{w:l,h:u}=r||s||{};return{id:String(e.id),stickerSetId:a?String(a.id):"MEMOJI_STICKER",stickerSetAccessHash:a&&String(a.accessHash),emoji:i,isAnimated:o,width:l,height:u,thumbnail:d}}function A(e){const{archived:t,animated:n,installedDate:s,id:a,accessHash:i,title:o,thumbs:r,count:c,shortName:d}=e;return{archived:t,isAnimated:n,installedDate:s,id:String(a),accessHash:String(i),title:o,hasThumbnail:Boolean(null==r?void 0:r.length),count:c,shortName:d}}function M(e){const t=A(e.set),n=e instanceof g.Api.StickerSetMultiCovered?e.covers:[e.cover];return t.covers=[],n.forEach((e=>{if(e instanceof g.Api.Document){const n=S(e);n&&(t.covers.push(n),v.documents[String(e.id)]=e)}})),t}function k(e,t){let n=0;const s=new Array(t),a=e.length/t,i=e[0],o=e[e.length-1];for(let l=0;l0?"user":e<=-1e9?"channel":"chat"}(e):e.startsWith("-")?e.length>=11?"channel":"chat":"user"}function V(e){const t=x(e);return"user"===t?new g.Api.PeerUser({userId:Y(e,"user")}):"channel"===t?new g.Api.PeerChannel({channelId:Y(e,"channel")}):new g.Api.PeerChat({chatId:Y(e,"chat")})}function N(e,t){const n=x(e);return"user"===n?new g.Api.InputPeerUser({userId:Y(e,"user"),accessHash:U()(t)}):"channel"===n?new g.Api.InputPeerChannel({channelId:Y(e,"channel"),accessHash:U()(t)}):new g.Api.InputPeerChat({chatId:Y(e,"chat")})}function F(e){const t=x(e);let n;var s;if("user"===t){if(n=null===(s=v.users[e])||void 0===s?void 0:s.accessHash,!n)return}else if("channel"===t){var a;if(n=null===(a=v.chats[e])||void 0===a?void 0:a.accessHash,!n)return}return N(e,String(n))}function O(e,t){const n=x(e);return"user"===n?new g.Api.InputUser({userId:Y(e,"user"),accessHash:U()(t)}):"channel"===n?new g.Api.InputChannel({channelId:Y(e,"channel"),accessHash:U()(t)}):Y(e,"chat")}function L(e,t){return new g.Api.InputStickerSetID({id:U()(e),accessHash:U()(t)})}function q(e){const t=v.documents[e.id];if(t)return new g.Api.InputDocument(f(t,["id","accessHash","fileReference"]))}function H(e){const t=q(e);if(t)return new g.Api.InputMediaDocument({id:t})}function G(){return(0,E.readBigIntFromBuffer)((0,E.generateRandomBytes)(8),!0,!0)}function K(e,t,n){return new g.Api.Message({id:e,peerId:V(t),fromId:V(t),media:n.media})}function z(e){const{type:t,offset:n,length:s,url:a,userId:i}=e,o=i?v.users[i]:void 0;switch(t){case T.Bold:return new g.Api.MessageEntityBold({offset:n,length:s});case T.Italic:return new g.Api.MessageEntityItalic({offset:n,length:s});case T.Underline:return new g.Api.MessageEntityUnderline({offset:n,length:s});case T.Strike:return new g.Api.MessageEntityStrike({offset:n,length:s});case T.Code:return new g.Api.MessageEntityCode({offset:n,length:s});case T.Pre:return new g.Api.MessageEntityPre({offset:n,length:s,language:""});case T.Blockquote:return new g.Api.MessageEntityBlockquote({offset:n,length:s});case T.TextUrl:return new g.Api.MessageEntityTextUrl({offset:n,length:s,url:a});case T.Url:return new g.Api.MessageEntityUrl({offset:n,length:s});case T.Hashtag:return new g.Api.MessageEntityHashtag({offset:n,length:s});case T.MentionName:return new g.Api.InputMessageEntityMentionName({offset:n,length:s,userId:new g.Api.InputUser({userId:U()(i),accessHash:o.accessHash})});default:return new g.Api.MessageEntityUnknown({offset:n,length:s})}}function W(e){const{media:t}=e;return!!t&&(t instanceof g.Api.MessageMediaPhoto||t instanceof g.Api.MessageMediaDocument||t instanceof g.Api.MessageMediaWebPage&&t.webpage instanceof g.Api.WebPage&&(t.webpage.photo instanceof g.Api.Photo||t.webpage.document instanceof g.Api.Document&&t.webpage.document.mimeType.startsWith("video")))}function j({phone:e,firstName:t,lastName:n}){return new g.Api.InputPhoneContact({clientId:U()(1),phone:e,firstName:t,lastName:n})}function $(e,t=0){return new g.Api.ChatBannedRights({...e,untilDate:t})}function J(e){return new g.Api.ChatAdminRights(e)}function Q(e){const{shippingAddress:t}=e;return new g.Api.PaymentRequestedInfo({...e,shippingAddress:t?new g.Api.PostAddress(t):void 0})}function X(e){switch(e){case"phoneNumber":return new g.Api.InputPrivacyKeyPhoneNumber;case"lastSeen":return new g.Api.InputPrivacyKeyStatusTimestamp;case"profilePhoto":return new g.Api.InputPrivacyKeyProfilePhoto;case"forwards":return new g.Api.InputPrivacyKeyForwards;case"chatInvite":return new g.Api.InputPrivacyKeyChatInvite}}function Z(e){switch(e){case"spam":return new g.Api.InputReportReasonSpam;case"violence":return new g.Api.InputReportReasonViolence;case"childAbuse":return new g.Api.InputReportReasonChildAbuse;case"pornography":return new g.Api.InputReportReasonPornography;case"copyright":return new g.Api.InputReportReasonCopyright;case"fake":return new g.Api.InputReportReasonFake;case"geoIrrelevant":return new g.Api.InputReportReasonGeoIrrelevant;case"other":return new g.Api.InputReportReasonOther}}function Y(e,t){return"number"==typeof e?U()(Math.abs(e)):"user"===t?U()(e):U()(e.slice(1))}function ee(e){return e.hasOwnProperty("userId")}function te(e){return e.hasOwnProperty("chatId")}function ne(e,t){return"user"===t?String(e):`-${e}`}function se(e){return ee(e)?ne(e.userId,"user"):te(e)?ne(e.chatId,"chat"):ne(e.channelId,"channel")}function ae(e){if(e instanceof g.Api.Message||e instanceof g.Api.MessageService)return se(e.peerId)}function ie(e){const t=`${ae(e)}-${e.id}`;v.messages[t]=e,e instanceof g.Api.Message&&e.media instanceof g.Api.MessageMediaDocument&&e.media.document instanceof g.Api.Document&&(v.documents[String(e.media.document.id)]=e.media.document),e instanceof g.Api.Message&&e.media instanceof g.Api.MessageMediaWebPage&&e.media.webpage instanceof g.Api.WebPage&&e.media.webpage.document instanceof g.Api.Document&&(v.documents[String(e.media.webpage.document.id)]=e.media.webpage.document),e instanceof g.Api.MessageService&&"photo"in e.action&&oe(e.action.photo)}function oe(e){e instanceof g.Api.Photo&&(v.photos[String(e.id)]=e)}function re(e){(e instanceof g.Api.Chat||e instanceof g.Api.Channel)&&(v.chats[ne(e.id,e instanceof g.Api.Chat?"chat":"channel")]=e)}const ce="temp";let de,le=1e9;function ue(e){const t=ae(e);if(t&&(e instanceof g.Api.Message||e instanceof g.Api.MessageService))return ge(t,e)}function ge(e,t){const n=t.fromId?se(t.fromId):void 0,s=t.peerId?se(t.peerId):void 0,a=!n&&e===de,i=t.out&&!t.post||a&&!t.fwdFrom;let o={};t.media&&(o={...he(t.media)}),!t.message||o.sticker||o.poll||o.contact||(o={...o,text:pe(t.message,t.entities)});const r=t.action&&function(e,t,n,s,a){if(e instanceof g.Api.MessageActionEmpty)return;let i,o,r;const c=[];let d,l="other";const u="users"in e?e.users&&e.users.map((e=>ne(e,"user"))):"userId"in e&&[ne(e.userId,"user")]||[];let p;if(e instanceof g.Api.MessageActionChatCreate)r="Notification.CreatedChatWithTitle",c.push("%action_origin%",e.title),l="chatCreate";else if(e instanceof g.Api.MessageActionChatEditTitle)s?(r="Channel.MessageTitleUpdated",c.push(e.title)):(r="Notification.ChangedGroupName",c.push("%action_origin%",e.title));else if(e instanceof g.Api.MessageActionChatEditPhoto)s?r="Channel.MessagePhotoUpdated":(r="Notification.ChangedGroupPhoto",c.push("%action_origin%"));else if(e instanceof g.Api.MessageActionChatDeletePhoto)r=s?"Channel.MessagePhotoRemoved":"Group.MessagePhotoRemoved";else if(e instanceof g.Api.MessageActionChatAddUser)!t||u.includes(t)?(r="Notification.JoinedChat",c.push("%target_user%")):(r="Notification.Invited",c.push("%action_origin%","%target_user%"));else if(e instanceof g.Api.MessageActionChatDeleteUser)!t||u.includes(t)?(r="Notification.LeftChat",c.push("%target_user%")):(r="Notification.Kicked",c.push("%action_origin%","%target_user%"));else if(e instanceof g.Api.MessageActionChatJoinedByLink)r="Notification.JoinedGroupByLink",c.push("%action_origin%");else if(e instanceof g.Api.MessageActionChannelCreate)r="Notification.CreatedChannel";else if(e instanceof g.Api.MessageActionChatMigrateTo)p=se(e),r="Migrated to %target_chat%",c.push("%target_chat%");else if(e instanceof g.Api.MessageActionChannelMigrateFrom)p=se(e),r="Migrated from %target_chat%",c.push("%target_chat%");else if(e instanceof g.Api.MessageActionPinMessage)r="Chat.Service.Group.UpdatedPinnedMessage1",c.push("%action_origin%","%message%");else if(e instanceof g.Api.MessageActionHistoryClear)r="HistoryCleared",l="historyClear";else if(e instanceof g.Api.MessageActionPhoneCall){const t=Boolean(e.duration);if(r=[t?"ChatList.Service":"Chat",e.video?"VideoCall":"Call",a?t?"outgoing":"Outgoing":t?"incoming":"Incoming"].join("."),t){const t=Math.max(Math.round(e.duration/60),1);c.push(`${t} min${t>1?"s":""}`)}}else if(e instanceof g.Api.MessageActionContactSignUp)r="Notification.Joined",c.push("%action_origin%"),l="contactSignUp";else if(e instanceof g.Api.MessageActionPaymentSent)i=Number(e.totalAmount),o=e.currency,r="PaymentSuccessfullyPaid",n&&u.push(n),c.push("%payment_amount%","%target_user%","%product%");else if(e instanceof g.Api.MessageActionGroupCall)if(e.duration){const t=Math.max(Math.round(e.duration/60),1);r="Notification.VoiceChatEnded",c.push(`${t} min${t>1?"s":""}`)}else r="Notification.VoiceChatStartedChannel";else e instanceof g.Api.MessageActionBotAllowed?(r="Chat.Service.BotPermissionAllowed",c.push(e.domain)):r="ChatList.UnsupportedMessage";return"photo"in e&&e.photo instanceof g.Api.Photo&&(oe(e.photo),d=C(e.photo)),{text:r,type:l,targetUserIds:u,targetChatId:p,photo:d,amount:i,currency:o,translationValues:c}}(t.action,n,s,Boolean(t.post),i);r&&(o.action=r);const{replyToMsgId:c,replyToTopId:d,replyToPeerId:l}=t.replyTo||{},u=t.editDate&&!t.editHide,{inlineButtons:p,keyboardButtons:f,keyboardPlaceholder:h,isKeyboardSingleUse:m}=function(e){const{id:t,replyMarkup:n,media:s}=e;if(!n)return s instanceof g.Api.MessageMediaWebPage&&s.webpage instanceof g.Api.WebPage&&"telegram_message"===s.webpage.type?{inlineButtons:[[{type:"url",text:"Show Message",messageId:t,value:s.webpage.url}]]}:void 0;if(!(n instanceof g.Api.ReplyKeyboardMarkup||n instanceof g.Api.ReplyInlineMarkup))return;const a=n.rows.map((({buttons:e})=>e.map((e=>{let n,a,{text:i}=e;return e instanceof g.Api.KeyboardButton?(n="command",a=i):e instanceof g.Api.KeyboardButtonUrl?(n="url",a=e.url):e instanceof g.Api.KeyboardButtonCallback?(n="callback",a=String(e.data)):e instanceof g.Api.KeyboardButtonRequestPoll?n="requestPoll":e instanceof g.Api.KeyboardButtonBuy?(s instanceof g.Api.MessageMediaInvoice&&s.receiptMsgId&&(i="PaymentReceipt",a=s.receiptMsgId),n="buy"):n="NOT_SUPPORTED",{type:n,text:i,messageId:t,value:a}}))));return{[n instanceof g.Api.ReplyKeyboardMarkup?"keyboardButtons":"inlineButtons"]:a,...n instanceof g.Api.ReplyKeyboardMarkup&&{keyboardPlaceholder:n.placeholder,isKeyboardSingleUse:n.singleUse}}}(t)||{},_=t.fwdFrom&&function(e,t=!1){const n=e.savedFromPeer&&se(e.savedFromPeer),s=e.fromId&&se(e.fromId);return{isChannelPost:Boolean(e.channelPost),channelPostId:e.channelPost,isLinkedChannelPost:Boolean(e.channelPost&&n&&!t),fromChatId:n||s,fromMessageId:e.channelPost||e.savedFromMsgId,senderUserId:s,hiddenUserName:e.fromName,adminTitle:e.postAuthor}}(t.fwdFrom,a),{replies:y,mediaUnread:b,postAuthor:w}=t,I=t.groupedId&&String(t.groupedId),v=Boolean(I)&&!(o.document||o.audio),P=t.replyMarkup instanceof g.Api.ReplyKeyboardHide;return{id:t.id,chatId:e,isOutgoing:i,content:o,date:t.date,senderId:n||t.out&&t.post&&de||e,views:t.views,isFromScheduled:t.fromScheduled,...c&&{replyToMessageId:c},...l&&{replyToChatId:se(l)},...d&&{replyToTopMessageId:d},..._&&{forwardInfo:_},...u&&{isEdited:u},...b&&{isMediaUnread:b},...t.mentioned&&b&&{hasUnreadMention:!0},...t.mentioned&&{isMentioned:!0},...I&&{groupedId:I,isInAlbum:v},inlineButtons:p,...f&&{keyboardButtons:f,keyboardPlaceholder:h,isKeyboardSingleUse:m},...P&&{shouldHideKeyboardButtons:P},...t.viaBotId&&{viaBotId:ne(t.viaBotId,"user")},...(null==y?void 0:y.comments)&&{threadInfo:Pe(y,t.id,e)},...w&&{adminTitle:w}}}function pe(e,t){return{text:e,...t&&{entities:t.map(ve)}}}function fe(e){if(e instanceof g.Api.DraftMessageEmpty)return;const{message:t,entities:n,replyToMsgId:s,date:a}=e;return{formattedText:t?pe(t,n):void 0,replyingToId:s,date:a}}function he(e){if("ttlSeconds"in e&&e.ttlSeconds)return;const t=function(e){if(e instanceof g.Api.MessageMediaDocument&&e.document&&e.document instanceof g.Api.Document)return S(e.document)}(e);if(t)return{sticker:t};const n=function(e){if(e instanceof g.Api.MessageMediaPhoto&&e.photo&&e.photo instanceof g.Api.Photo)return C(e.photo)}(e);if(n)return{photo:n};const s=function(e){if(e instanceof g.Api.MessageMediaDocument&&e.document instanceof g.Api.Document&&e.document.mimeType.startsWith("video"))return me(e.document)}(e);if(s)return{video:s};const a=function(e){if(!(e instanceof g.Api.MessageMediaDocument&&e.document&&e.document instanceof g.Api.Document))return;const t=e.document.attributes.find((e=>e instanceof g.Api.DocumentAttributeAudio));if(!t||t.voice)return;const n=e.document.thumbs&&e.document.thumbs.filter((e=>e instanceof g.Api.PhotoSize)).map((e=>I(e)));return{fileName:Ce(e.document,"audio"),thumbnailSizes:n,...f(e.document,["size","mimeType"]),...f(t,["duration","performer","title"])}}(e);if(a)return{audio:a};const i=function(e){if(!(e instanceof g.Api.MessageMediaDocument&&e.document&&e.document instanceof g.Api.Document))return;const t=e.document.attributes.find((e=>e instanceof g.Api.DocumentAttributeAudio));if(!t||!t.voice)return;const{duration:n,waveform:s}=t;return{duration:n,waveform:s?Array.from(s):void 0}}(e);if(i)return{voice:i};const o=function(e){if(e instanceof g.Api.MessageMediaDocument&&e.document)return _e(e.document)}(e);if(o)return{document:o};const r=function(e){if(!(e instanceof g.Api.MessageMediaContact))return;const{firstName:t,lastName:n,phoneNumber:s,userId:a}=e;return{firstName:t,lastName:n,phoneNumber:s,userId:ne(a,"user")}}(e);if(r)return{contact:r};const c=function(e){if(e instanceof g.Api.MessageMediaPoll)return ye(e.poll,e.results)}(e);if(c)return{poll:c};const d=we(e);if(d)return{webPage:d};const l=function(e){if(e instanceof g.Api.MessageMediaInvoice)return function(e){const{description:t,title:n,photo:s,test:a,totalAmount:i,currency:o,receiptMsgId:r}=e;return{text:t,title:n,photoUrl:null==s?void 0:s.url,receiptMsgId:r,amount:Number(i),currency:o,isTest:a}}(e)}(e);return l?{invoice:l}:void 0}function me(e){if(e instanceof g.Api.DocumentEmpty)return;const{id:t,mimeType:n,thumbs:s,size:a,attributes:i}=e;if("video/quicktime"===n&&!self.isMovSupported)return;const o=i.find((e=>e instanceof g.Api.DocumentAttributeVideo));if(!o)return;const r=i.find((e=>e instanceof g.Api.DocumentAttributeAnimated)),{duration:c,w:d,h:l,supportsStreaming:u=!1,roundMessage:p=!1}=o;return{id:String(t),mimeType:n,duration:c,fileName:Ce(e,"video"),width:d,height:l,supportsStreaming:u,isRound:p,isGif:Boolean(r),thumbnail:w(s),size:a}}function _e(e){if(!(e instanceof g.Api.Document))return;const{id:t,size:n,mimeType:s,date:a,thumbs:i,attributes:o}=e,d=i&&w(i);let l,u;const p=i&&i.find((e=>e instanceof g.Api.PhotoSize));if(p)if(u={width:p.w,height:p.h},r.has(s)){l="photo";const e=o.find((e=>e instanceof g.Api.DocumentAttributeImageSize));if(e){const{w:t,h:n}=e;u={width:t,height:n}}}else c.has(s)&&(l="video");return{id:String(t),size:n,mimeType:s,timestamp:a,fileName:Ce(e),thumbnail:d,mediaType:l,mediaSize:u}}function ye(e,t){const{id:n,answers:s}=e,a=s.map((e=>({text:e.text,option:String.fromCharCode(...e.option)})));return{id:String(n),summary:{isPublic:e.publicVoters,...f(e,["closed","multipleChoice","quiz","question","closePeriod","closeDate"]),answers:a},results:be(t)}}function be(e){const{results:t,totalVoters:n,recentVoters:s,solution:a,solutionEntities:i}=e,o=t&&t.map((({option:e,chosen:t,correct:n,voters:s})=>({isChosen:t,isCorrect:n,option:String.fromCharCode(...e),votersCount:s})));return{totalVoters:n,recentVoterIds:null==s?void 0:s.map((e=>ne(e,"user"))),results:o,solution:a,...i&&{solutionEntities:i.map(ve)}}}function we(e){if(!(e instanceof g.Api.MessageMediaWebPage&&e.webpage instanceof g.Api.WebPage))return;const{id:t,photo:n,document:s}=e.webpage;let a;return s instanceof g.Api.Document&&s.mimeType.startsWith("video/")&&(a=me(s)),{id:Number(t),...f(e.webpage,["url","displayUrl","type","siteName","title","description","duration"]),photo:n instanceof g.Api.Photo?C(n):void 0,document:!a&&s?_e(s):void 0,video:a}}function Ce(e,t="file"){const{mimeType:n,attributes:s}=e,a=s.find((e=>e instanceof g.Api.DocumentAttributeFilename));if(a)return a.fileName;const i=n.split("/")[1];return`${t}${String(e.id)}.${i}`}function Ie(e,t){return{poll:{id:String(t),summary:f(e.summary,["question","answers"]),results:{}}}}function ve(e){const{className:t,offset:n,length:s}=e;return{type:t,offset:n,length:s,..."userId"in e&&"number"==typeof e.userId&&{userId:e.userId},..."url"in e&&{url:e.url}}}function Pe(e,t,n){const{channelId:s,replies:a,maxId:i,readMaxId:o,recentRepliers:r}=e;if(!s)return;const c=ne(s,"channel");return"-777"!==c?{threadId:t,...n!==c?{chatId:c,originChannelId:n}:{chatId:n},messagesCount:a,lastMessageId:i,lastReadInboxMessageId:o,...r&&{recentReplierIds:r.map(se)}}:void 0}const Se=e=>Math.floor(Date.now()/1e3)+e;function Ae(e,t=!1){const n=Boolean("min"in e&&e.min),s="accessHash"in e&&String(e.accessHash),a="photo"in e&&e.photo&&Ve(e.photo),i=Boolean("signatures"in e&&e.signatures);return{isMin:n,hasPrivateLink:Boolean("hasLink"in e&&e.hasLink),isSignaturesShown:i,...s&&{accessHash:s},...a&&{avatarHash:a},...(e instanceof g.Api.Channel||e instanceof g.Api.User)&&{username:e.username},..."verified"in e&&{isVerified:e.verified},..."callActive"in e&&{isCallActive:e.callActive},..."callNotEmpty"in e&&{isCallNotEmpty:e.callNotEmpty},...(e instanceof g.Api.Chat||e instanceof g.Api.Channel)&&{...e.participantsCount&&{membersCount:e.participantsCount},joinDate:e.date},...t&&{isSupport:!0},...ke(e),..."creator"in e&&{isCreator:e.creator},...Re(e),...Ue(e)}}function Me(e,t,n){const{peer:s,folderId:a,unreadMark:i,unreadCount:o,unreadMentionsCount:r,notifySettings:{silent:c,muteUntil:d},readOutboxMaxId:l,readInboxMaxId:u,draft:p}=e,f=c||"number"==typeof d&&Se(n)"all"===e));return t?f(t,["reason","text"]):void 0}(e.restrictionReason):void 0;n&&Object.assign(t,{isRestricted:!0,restrictionReason:n})}return e instanceof g.Api.Chat&&Object.assign(t,{isNotJoined:e.left,isRestricted:e.kicked}),e instanceof g.Api.Channel&&Object.assign(t,{isNotJoined:e.left}),t}function Ue(e){return e instanceof g.Api.Chat&&e.migratedTo&&!(e.migratedTo instanceof g.Api.InputChannelEmpty)?{migratedTo:{chatId:se(e.migratedTo),...e.migratedTo instanceof g.Api.InputChannel&&{accessHash:String(e.migratedTo.accessHash)}}}:{}}function Ee(e,t=!1,n=!1){if(e instanceof g.Api.Chat||e instanceof g.Api.Channel||e instanceof g.Api.User||n&&(e instanceof g.Api.ChatForbidden||e instanceof g.Api.ChannelForbidden))return{id:ne(e.id,e instanceof g.Api.User?"user":"chat"),type:Te(e),title:e instanceof g.Api.User?xe(e):e.title,...Ae(e,t)}}function Te(e){return e instanceof g.Api.User||e instanceof g.Api.UserEmpty?"chatTypePrivate":e instanceof g.Api.Chat||e instanceof g.Api.ChatForbidden||e instanceof g.Api.ChatEmpty?"chatTypeBasicGroup":e.megagroup?"chatTypeSuperGroup":"chatTypeChannel"}function De(e){return ee(e)?`user${e.userId}`:te(e)?`chat${e.chatId}`:`chat${e.channelId}`}function Be(e,t){return ee(e)?xe(t):t.title}function xe(e){return e.firstName?`${e.firstName}${e.lastName?` ${e.lastName}`:""}`:e.lastName||void 0}function Ve(e){if("photoId"in e)return String(e.photoId)}function Ne(e){return{userId:e instanceof g.Api.ChannelParticipantBanned||e instanceof g.Api.ChannelParticipantLeft?se(e.peer):ne(e.userId,"user"),inviterId:"inviterId"in e?ne(e.inviterId,"user"):void 0,joinedDate:"date"in e?e.date:void 0,kickedByUserId:"kickedBy"in e?ne(e.kickedBy,"user"):void 0,promotedByUserId:"promotedBy"in e?ne(e.promotedBy,"user"):void 0,bannedRights:"bannedRights"in e?_(e.bannedRights):void 0,adminRights:"adminRights"in e?_(e.adminRights):void 0,customTitle:"rank"in e?e.rank:void 0,...(e instanceof g.Api.ChannelParticipantAdmin||e instanceof g.Api.ChatParticipantAdmin)&&{isAdmin:!0},...(e instanceof g.Api.ChannelParticipantCreator||e instanceof g.Api.ChatParticipantCreator)&&{isOwner:!0}}}function Fe(e){return e instanceof g.Api.ChatParticipants||e instanceof g.Api.channels.ChannelParticipants?e.participants.map(Ne).filter(Boolean):void 0}function Oe(e,t){let n="";if(!(e.action instanceof g.Api.SendMessageCancelAction)){if(e.action instanceof g.Api.SendMessageTypingAction)n="lng_user_typing";else if(e.action instanceof g.Api.SendMessageRecordVideoAction)n="lng_send_action_record_video";else if(e.action instanceof g.Api.SendMessageUploadVideoAction)n="lng_send_action_upload_video";else if(e.action instanceof g.Api.SendMessageRecordAudioAction)n="lng_send_action_record_audio";else if(e.action instanceof g.Api.SendMessageUploadAudioAction)n="lng_send_action_upload_audio";else if(e.action instanceof g.Api.SendMessageUploadPhotoAction)n="lng_send_action_upload_photo";else if(e.action instanceof g.Api.SendMessageUploadDocumentAction)n="lng_send_action_upload_file";else if(e.action instanceof g.Api.SendMessageGeoLocationAction)n="selecting a location to share";else if(e.action instanceof g.Api.SendMessageChooseContactAction)n="selecting a contact to share";else if(e.action instanceof g.Api.SendMessageGamePlayAction)n="lng_playing_game";else if(e.action instanceof g.Api.SendMessageRecordRoundAction)n="lng_send_action_record_round";else if(e.action instanceof g.Api.SendMessageUploadRoundAction)n="lng_send_action_upload_round";else if(e.action instanceof g.Api.SendMessageChooseStickerAction)n="lng_send_action_choose_sticker";else if(e.action instanceof g.Api.SpeakingInGroupCallAction)return;return{action:n,...!(e instanceof g.Api.UpdateUserTyping)&&{userId:se(e.fromId)},timestamp:Date.now()+1e3*t}}}function Le(e){return{...(t=e,n=["id","title","emoticon","contacts","nonContacts","groups","bots","excludeMuted","excludeRead","excludeArchived"],n.reduce(((e,n)=>(t[n]&&(e[n]=t[n]),e)),{})),channels:e.broadcasts,pinnedChatIds:e.pinnedPeers.map(se).filter(Boolean),includedChatIds:e.includePeers.map(se).filter(Boolean),excludedChatIds:e.excludePeers.map(se).filter(Boolean)};var t,n}function qe({filter:e,description:t}){return{...Le(e),description:t}}function He(e){return e.reduce(((e,t)=>{const n=ne(t.userId,"user");return e.concat(t.commands.map((e=>({botId:n,..._(e)}))))}),[])}function Ge(e){const{about:t,commonChatsCount:n,pinnedMsgId:s,botInfo:a,blocked:i}=e,o=Ke(e.user);return{...o,fullInfo:{bio:t,commonChatsCount:n,pinnedMessageId:s,isBlocked:Boolean(i),...a&&{botDescription:a.description},...a&&a.commands.length&&{botCommands:We(o.id,a)}}}}function Ke(e){if(!(e instanceof g.Api.User))return;const{id:t,firstName:n,lastName:s}=e,a=e.photo instanceof g.Api.UserProfilePhoto?String(e.photo.photoId):void 0,i=(o=e).bot?"userTypeBot":o.deleted?"userTypeDeleted":"userTypeRegular";var o;return{id:ne(t,"user"),isMin:Boolean(e.min),...e.self&&{isSelf:!0},...e.verified&&{isVerified:!0},...(e.contact||e.mutualContact)&&{isContact:!0},type:i,...n&&{firstName:n},..."userTypeBot"===i&&{canBeInvitedToGroup:!e.botNochats},...s&&{lastName:s},username:e.username||"",phoneNumber:e.phone||"",status:ze(e.status),...e.accessHash&&{accessHash:String(e.accessHash)},...a&&{avatarHash:a},...e.bot&&e.botInlinePlaceholder&&{botPlaceholder:e.botInlinePlaceholder}}}function ze(e){return!e||e instanceof g.Api.UserStatusEmpty?{type:"userStatusEmpty"}:e instanceof g.Api.UserStatusOnline?{type:"userStatusOnline",expires:e.expires}:e instanceof g.Api.UserStatusOffline?{type:"userStatusOffline",wasOnline:e.wasOnline}:e instanceof g.Api.UserStatusRecently?{type:"userStatusRecently"}:e instanceof g.Api.UserStatusLastWeek?{type:"userStatusLastWeek"}:{type:"userStatusLastMonth"}}function We(e,t){return t.commands.map((({command:t,description:n})=>({botId:e,command:t,description:n})))}function je(e){if(e instanceof g.Api.WallPaperNoFile)return;const{slug:t}=e,n=_e(e.document);return n?{slug:t,document:n}:void 0}function $e(e){return{isCurrent:Boolean(e.current),isOfficialApp:Boolean(e.officialApp),isPasswordPending:Boolean(e.passwordPending),hash:String(e.hash),...f(e,["deviceModel","platform","systemVersion","appName","appVersion","dateCreated","dateActive","ip","country","region"])}}function Je(e){let t,n,s,a,i;return e.forEach((e=>{e instanceof g.Api.PrivacyValueAllowAll?t=t||"everybody":e instanceof g.Api.PrivacyValueAllowContacts?t=t||"contacts":e instanceof g.Api.PrivacyValueDisallowContacts?t=t||"nonContacts":e instanceof g.Api.PrivacyValueDisallowAll?t=t||"nobody":e instanceof g.Api.PrivacyValueAllowUsers?n=e.users.map((e=>ne(e,"user"))):e instanceof g.Api.PrivacyValueDisallowUsers?a=e.users.map((e=>ne(e,"user"))):e instanceof g.Api.PrivacyValueAllowChatParticipants?s=e.chats.map((e=>ne(e,"chat"))):e instanceof g.Api.PrivacyValueDisallowChatParticipants&&(i=e.chats.map((e=>ne(e,"chat"))))})),t||(t="nobody"),{visibility:t,allowUserIds:n||[],allowChatIds:s||[],blockUserIds:a||[],blockChatIds:i||[]}}function Qe(e,t,n){const{silent:s,muteUntil:a,showPreviews:i,sound:o}=e;return{chatId:se(t),isMuted:s||"number"==typeof a&&Se(n)e instanceof g.Api.User)).map(Ke).forEach((e=>{e&&Ze({"@type":"updateUser",id:e.id,user:e})})),i.filter((e=>e instanceof g.Api.Chat||e instanceof g.Api.Channel)).map((e=>Ee(e))).forEach((e=>{e&&Ze({"@type":"updateChat",id:e.id,chat:e})}))),e instanceof g.Api.UpdateNewScheduledMessage?Ze({"@type":Ye.has(t.id)?"updateScheduledMessage":"newScheduledMessage",id:t.id,chatId:t.chatId,message:t}):Ze({"@type":Ye.has(t.id)?"updateMessage":"newMessage",id:t.id,chatId:t.chatId,message:t,shouldForceReply:a}),e.message instanceof g.Api.MessageService){const{action:n}=e.message;if(n instanceof g.Api.MessageActionChatEditTitle)Ze({"@type":"updateChat",id:t.chatId,chat:{title:n.title}});else if(n instanceof g.Api.MessageActionChatEditPhoto){const s=function(e){if(e instanceof g.Api.PhotoEmpty)return new g.Api.ChatPhotoEmpty;const{dcId:t,id:n}=e;return new g.Api.ChatPhoto({dcId:t,photoId:n})}(n.photo),a=Ve(s),i=ae(e.message);v.chats[i]&&(v.chats[i].photo=s),oe(n.photo),a&&Ze({"@type":"updateChat",id:t.chatId,chat:{avatarHash:a},...n.photo instanceof g.Api.Photo&&{newProfilePhoto:C(n.photo)}})}else if(n instanceof g.Api.MessageActionChatDeletePhoto){const n=ae(e.message);v.chats[n]&&(v.chats[n].photo=new g.Api.ChatPhotoEmpty),Ze({"@type":"updateChat",id:t.chatId,chat:{avatarHash:void 0}})}else n instanceof g.Api.MessageActionChatDeleteUser?e._entities&&e._entities.some((e=>e instanceof g.Api.User&&!!e.self&&e.id===n.userId))&&(Ze({"@type":"updateChat",id:t.chatId,chat:{isRestricted:!0}}),Ze({"@type":"updateChatLeave",id:t.chatId})):n instanceof g.Api.MessageActionChatAddUser&&e._entities&&e._entities.some((e=>e instanceof g.Api.User&&!!e.self&&n.users.includes(e.id)))&&Ze({"@type":"updateChatJoin",id:t.chatId})}}else if(e instanceof g.Api.UpdateEditMessage||e instanceof g.Api.UpdateEditChannelMessage){if(e.message instanceof g.Api.MessageEmpty)return;e.message instanceof g.Api.Message&&W(e.message)&&ie(e.message);const t=ue(e.message);Ze({"@type":"updateMessage",id:t.id,chatId:t.chatId,message:t})}else if(e instanceof g.Api.UpdateDeleteMessages)Ze({"@type":"deleteMessages",ids:e.messages});else if(e instanceof g.Api.UpdateDeleteScheduledMessages)Ze({"@type":"deleteScheduledMessages",ids:e.messages,chatId:se(e.peer)});else if(e instanceof g.Api.UpdateDeleteChannelMessages){const t=ne(e.channelId,"channel"),n=e.messages,s=n.filter((e=>v.messages[`${t}-${e}`])),a=n.filter((e=>!v.messages[`${t}-${e}`])),i=n.map((e=>{const n=v.messages[`${t}-${e}`];return n&&n instanceof g.Api.MessageService&&"photo"in n.action?String(n.action.photo.id):void 0})).filter(Boolean);s.length&&Ze({"@type":"deleteMessages",ids:s,chatId:t}),i.length&&Ze({"@type":"deleteProfilePhotos",ids:i,chatId:t}),a.length&&setTimeout((()=>{Ze({"@type":"deleteMessages",ids:a,chatId:t})}),1e3)}else if(e instanceof g.Api.UpdateServiceNotification){const t=function(e,t){const n=le++;let s={};return e.media&&(s={...he(e.media)}),!e.message||s.sticker||s.poll||s.contact||(s={...s,text:pe(e.message,e.entities)}),{id:n,chatId:d,date:e.inboxDate||t,content:s,isOutgoing:!1}}(e,Date.now()/1e3+et);W(e)&&ie(K(t.id,t.chatId,e)),Ze({"@type":"updateServiceNotification",message:t})}else if((t instanceof g.Api.messages.SendMessage||t instanceof g.Api.messages.SendMedia||t instanceof g.Api.messages.SendMultiMedia||t instanceof g.Api.messages.ForwardMessages)&&(e instanceof g.Api.UpdateMessageID||e instanceof g.Api.UpdateShortSentMessage)){let n;"randomId"in e?n=e.randomId:"randomId"in t&&(n=t.randomId);const s=n&&v.localMessages[String(n)];if(!s)throw new Error("Local message not found");let a;if(e instanceof g.Api.UpdateShortSentMessage){s.content.text&&e.entities&&(a={text:pe(s.content.text.text,e.entities)}),e.media&&(a={...a,...he(e.media)});const t=K(e.id,s.chatId,e);W(t)&&ie(t)}Ye.add(e.id);const i="date"in e&&1e3*e.dateString.fromCharCode(...e)))});else if(e instanceof g.Api.UpdateChannelMessageViews)Ze({"@type":"updateMessage",chatId:ne(e.channelId,"channel"),id:e.id,message:{views:e.views}});else if(e instanceof g.Api.UpdateReadHistoryInbox)Ze({"@type":"updateChatInbox",id:se(e.peer),chat:{lastReadInboxMessageId:e.maxId,unreadCount:e.stillUnreadCount}});else if(e instanceof g.Api.UpdateReadHistoryOutbox)Ze({"@type":"updateChat",id:se(e.peer),chat:{lastReadOutboxMessageId:e.maxId}});else if(e instanceof g.Api.UpdateReadChannelInbox)Ze({"@type":"updateChat",id:ne(e.channelId,"channel"),chat:{lastReadInboxMessageId:e.maxId,unreadCount:e.stillUnreadCount}});else if(e instanceof g.Api.UpdateReadChannelOutbox)Ze({"@type":"updateChat",id:ne(e.channelId,"channel"),chat:{lastReadOutboxMessageId:e.maxId}});else if(e instanceof g.Api.UpdateDialogPinned&&e.peer instanceof g.Api.DialogPeer)Ze({"@type":"updateChatPinned",id:se(e.peer.peer),isPinned:e.pinned||!1});else if(e instanceof g.Api.UpdatePinnedDialogs){const t=e.order?e.order.filter((e=>e instanceof g.Api.DialogPeer)).map((e=>se(e.peer))):[];Ze({"@type":"updatePinnedChatIds",ids:t,folderId:e.folderId||void 0})}else if(e instanceof g.Api.UpdateFolderPeers)e.folderPeers.forEach((e=>{const{folderId:t,peer:n}=e;Ze({"@type":"updateChatListType",id:se(n),folderId:t})}));else if(e instanceof g.Api.UpdateDialogFilter){const{id:t,filter:n}=e,s=n?Le(n):void 0;Ze({"@type":"updateChatFolder",id:t,folder:s})}else if(e instanceof g.Api.UpdateDialogFilterOrder)Ze({"@type":"updateChatFoldersOrder",orderedIds:e.order});else if(e instanceof g.Api.UpdateChatParticipants){const t=Fe(e.participants);Ze({"@type":"updateChatMembers",id:ne(e.participants.chatId,"chat"),replacedMembers:t})}else if(e instanceof g.Api.UpdateChatParticipantAdd){const t=Ne(f(e,["userId","inviterId","date"]));Ze({"@type":"updateChatMembers",id:ne(e.chatId,"chat"),addedMember:t})}else if(e instanceof g.Api.UpdateChatParticipantDelete)Ze({"@type":"updateChatMembers",id:ne(e.chatId,"chat"),deletedMemberId:ne(e.userId,"user")});else if(e instanceof g.Api.UpdatePinnedMessages||e instanceof g.Api.UpdatePinnedChannelMessages){const t=e instanceof g.Api.UpdatePinnedMessages?se(e.peer):ne(e.channelId,"channel");Ze({"@type":"updatePinnedIds",chatId:t,messageIds:e.messages,isPinned:e.pinned})}else if(e instanceof g.Api.UpdateNotifySettings&&e.peer instanceof g.Api.NotifyPeer)Ze({"@type":"updateNotifyExceptions",...Qe(e.notifySettings,e.peer.peer,et)});else if(e instanceof g.Api.UpdateUserTyping||e instanceof g.Api.UpdateChatUserTyping){const t=e instanceof g.Api.UpdateUserTyping?ne(e.userId,"user"):ne(e.chatId,"chat");Ze({"@type":"updateChatTypingStatus",id:t,typingStatus:Oe(e,et)})}else if(e instanceof g.Api.UpdateChannelUserTyping){const t=ne(e.channelId,"channel");Ze({"@type":"updateChatTypingStatus",id:t,typingStatus:Oe(e,et)})}else if(e instanceof g.Api.UpdateChannel){const{_entities:t}=e;if(!t)return;const n=t.find((e=>e instanceof g.Api.Channel||e instanceof g.Api.ChannelForbidden));if(n instanceof g.Api.Channel){const t=Ee(n);t&&(Ze({"@type":"updateChat",id:t.id,chat:t}),Ze({"@type":t.isNotJoined?"updateChatLeave":"updateChatJoin",id:ne(e.channelId,"channel")}))}else if(n instanceof g.Api.ChannelForbidden){const t=ne(e.channelId,"channel");Ze({"@type":"updateChat",id:t,chat:{isRestricted:!0}}),Ze({"@type":"updateChatLeave",id:t})}else 0===t.length&&Ze({"@type":"resetMessages",id:ne(e.channelId,"channel")})}else if(e instanceof g.Api.UpdateDialogUnreadMark&&e.peer instanceof g.Api.DialogPeer)Ze({"@type":"updateChat",id:se(e.peer.peer),chat:{hasUnreadMark:e.unread}});else if(e instanceof g.Api.UpdateChatDefaultBannedRights)Ze({"@type":"updateChat",id:se(e.peer),chat:{defaultBannedRights:_(e.defaultBannedRights)}});else if(e instanceof g.Api.UpdateUserStatus)Ze({"@type":"updateUserStatus",userId:ne(e.userId,"user"),status:ze(e.status)});else if(e instanceof g.Api.UpdateUserName){const t=ne(e.userId,"user"),n=v.users[t],s=null!=n&&n.mutualContact&&!n.self?f(e,["username"]):f(e,["firstName","lastName","username"]);Ze({"@type":"updateUser",id:t,user:s})}else if(e instanceof g.Api.UpdateUserPhoto){const{userId:t,photo:n}=e,s=ne(t,"user"),a=Ve(n);v.users[s]&&(v.users[s].photo=n),Ze({"@type":"updateUser",id:s,user:{avatarHash:a}})}else if(e instanceof g.Api.UpdateUserPhone){const{userId:t,phone:n}=e;Ze({"@type":"updateUser",id:ne(t,"user"),user:{phoneNumber:n}})}else if(e instanceof g.Api.UpdatePeerSettings){const{_entities:t}=e;if(!t)return;null!=t&&t.length&&(t.filter((e=>e instanceof g.Api.User&&!e.contact)).forEach((e=>{Ze({"@type":"deleteUser",id:ne(e.id,"user")})})),t.filter((e=>e instanceof g.Api.User&&e.contact)).map(Ke).forEach((e=>{e&&Ze({"@type":"updateUser",id:e.id,user:e})})))}else if(e instanceof g.Api.UpdateNotifySettings){const{notifySettings:{showPreviews:t,silent:n,muteUntil:s},peer:{className:a}}=e,i="NotifyUsers"===a?"contact":"NotifyChats"===a?"group":"NotifyBroadcasts"===a?"broadcast":void 0;if(!i)return;Ze({"@type":"updateNotifySettings",peerType:i,isSilent:Boolean(n||"number"==typeof s&&Date.now()+1e3*et<1e3*s),shouldShowPreviews:Boolean(t)})}else if(e instanceof g.Api.UpdatePeerBlocked)Ze({"@type":"updatePeerBlocked",id:se(e.peerId),isBlocked:e.blocked});else if(e instanceof g.Api.UpdatePrivacy){const t=function(e){switch(e.className){case"PrivacyKeyPhoneNumber":return"phoneNumber";case"PrivacyKeyStatusTimestamp":return"lastSeen";case"PrivacyKeyProfilePhoto":return"profilePhoto";case"PrivacyKeyForwards":return"forwards";case"PrivacyKeyChatInvite":return"chatInvite"}}(e.key);t&&Ze({"@type":"updatePrivacy",key:t,rules:Je(e.rules)})}else e instanceof g.Api.UpdateDraftMessage?Ze({"@type":"draftMessage",chatId:se(e.peer),...fe(e.draft)}):e instanceof g.Api.UpdateContactsReset?Ze({"@type":"updateResetContactList"}):e instanceof g.Api.UpdateFavedStickers&&Ze({"@type":"updateFavoriteStickers"});var s}const nt={PHONE_NUMBER_INVALID:"Invalid phone number.",PHONE_CODE_INVALID:"Invalid code.",PASSWORD_HASH_INVALID:"Incorrect password.",PHONE_PASSWORD_FLOOD:"Limit exceeded. Please try again later.",PHONE_NUMBER_BANNED:"This phone number is banned."},st={};let at;function it(){return at(ut("authorizationStateWaitPhoneNumber")),new Promise(((e,t)=>{st.resolve=e,st.reject=t}))}function ot(e=!1){return at({...ut("authorizationStateWaitCode"),isCodeViaApp:e}),new Promise(((e,t)=>{st.resolve=e,st.reject=t}))}function rt(e){return at({...ut("authorizationStateWaitPassword"),hint:e}),new Promise((e=>{st.resolve=e}))}function ct(){return at(ut("authorizationStateWaitRegistration")),new Promise((e=>{st.resolve=e}))}function dt(e){return at({...ut("authorizationStateWaitQrCode"),qrCode:{token:btoa(String.fromCharCode(...e.token)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),expires:e.expires}}),new Promise(((e,t)=>{st.reject=t}))}function lt(e){let t;if(e instanceof g.errors.FloodWaitError){const n=Math.ceil(Number(e.seconds)/60/60);t="Too many attempts. Try again in "+(n>1?`${n} hours`:"an hour")}else t=nt[e.message];t||(t="Unexpected Error"),at({"@type":"updateAuthorizationError",message:t})}function ut(e){return{"@type":"updateAuthorizationState",authorizationState:e}}function gt(e){st.resolve&&st.resolve(e)}function pt(e){st.resolve&&st.resolve(e)}function ft(e){st.resolve&&st.resolve(e)}function ht(e){const{firstName:t,lastName:n}=e;st.resolve&&st.resolve([t,n])}function mt(){st.reject&&st.reject(new Error("RESTART_AUTH"))}function _t(){st.reject&&st.reject(new Error("RESTART_AUTH_WITH_QR"))}var yt=n(9832),bt=n(5802);const wt=self.caches;let Ct;async function It(e,t,n,s=!1){if(wt)try{const a=new Request(t.replace(/:/g,"_")),i=await wt.open(e),o=await i.match(a);if(!o)return;const r=o.headers.get("Content-Type");switch(n){case Ct.Text:return await o.text();case Ct.Blob:{if(t.startsWith("avatar")&&r&&r.startsWith("text"))return;const e=await o.blob();if(t.startsWith("sticker"))return new Blob([e],{type:"image/webp"});const n=!e.type||!s&&e.type.includes("html");let a=e.type||r;return n&&a?(s||(a=a.replace(/html/gi,"")),new Blob([e],{type:a})):e}case Ct.Json:return await o.json();default:return}}catch(e){return void console.warn(e)}}async function vt(e,t,n){if(wt)try{const s="string"==typeof n||n instanceof Blob?n:JSON.stringify(n),a=new Request(t.replace(/:/g,"_")),i=new Response(s),o=await wt.open(e);return await o.put(a,i)}catch(e){return void console.warn(e)}}async function Pt(e){try{if(!wt)return;return await wt.delete(e)}catch(e){return void console.warn(e)}}!function(e){e[e.Text=0]="Text",e[e.Blob=1]="Blob",e[e.Json=2]="Json"}(Ct||(Ct={}));const St=new Set(["msg","sticker","gif","wallpaper","photo","webDocument"]);function At(e,t="image/jpeg"){if(e.length<4)return t;let n=t;switch(e.subarray(0,4).reduce(((e,t)=>e+t.toString(16)),"")){case"89504e47":n="image/png";break;case"47494638":n="image/gif";break;case"ffd8ffe0":case"ffd8ffe1":case"ffd8ffe2":case"ffd8ffe3":case"ffd8ffe8":n="image/jpeg";break;case"52494646":n="image/webp"}return n}yt.Logger.setLevel("warn");const Mt={build:e=>e};let kt,Rt,Ut=!1;async function Et(){await xt(new g.Api.auth.LogOut),await Rt.destroy()}async function Tt(){await Rt.disconnect()}function Dt(e){kt({"@type":"updateSession",sessionData:e})}function Bt(e){e instanceof g.connection.UpdateConnectionState?Ut=e.state===g.connection.UpdateConnectionState.connected:e instanceof g.Api.UpdatesTooLong?async function(){try{await xt(new g.Api.users.GetFullUser({id:new g.Api.InputUserSelf}),void 0,!0)}catch(e){"AUTH_KEY_UNREGISTERED"===e.message&&kt({"@type":"updateConnectionState",connectionState:"connectionStateBroken"})}}():e instanceof g.connection.UpdateServerTimeOffset&&kt({"@type":"updateServerTimeOffset",serverTimeOffset:e.timeOffset})}async function xt(e,t=!1,n=!1){if(Ut)try{const n=await Rt.invoke(e);if(t){let t;n instanceof g.Api.Updates||n instanceof g.Api.UpdatesCombined?t=n:"updates"in n&&(n.updates instanceof g.Api.Updates||n.updates instanceof g.Api.UpdatesCombined)&&(t=n.updates),t?(function(e){const t=[...e.users,...e.chats];e.updates.forEach((e=>{t&&(e._entities=t)}))}(t),t.updates.forEach((t=>{tt(t,e)}))):n instanceof g.Api.UpdatesTooLong||tt(n,e)}return n}catch(t){if(n)throw t;return void function(e,t){const n=e.message.startsWith("A wait of")&&(t instanceof g.Api.messages.SendMessage||t instanceof g.Api.messages.SendMedia||t instanceof g.Api.messages.SendMultiMedia),{message:s}=e;kt({"@type":"error",error:{message:s,isSlowMode:n,hasErrorKey:!0}})}(t,e)}}function Vt(e,t){return async function({url:e,mediaFormat:t,start:n,end:a,isHtmlAllowed:i},o,r,c){const{data:d,mimeType:l,fullSize:u}=await async function(e,t,n,s,a,i,o,r){const c=e.startsWith("webDocument")?e.match(/(webDocument):(.+)/):e.match(/(avatar|profile|photo|msg|stickerSet|sticker|wallpaper|gif|file)([-\d\w./]+)(\?size=\w+)?/);if(!c)return;if("file"===c[1]){const e=await fetch(c[2]);return{data:await e.arrayBuffer()}}if(!n)return Promise.reject(new Error("ERROR: Client is not connected"));let d;const l=c[2],u=c[3]?c[3].replace("?size=",""):void 0;let p;switch(d="avatar"===c[1]||"profile"===c[1]?x(l):c[1],d){case"channel":case"chat":p=v.chats[l];break;case"user":p=v.users[l];break;case"msg":p=v.messages[l];break;case"sticker":case"gif":case"wallpaper":p=v.documents[l];break;case"photo":p=v.photos[l];break;case"stickerSet":p=v.stickerSets[l];break;case"webDocument":p=v.webDocuments[l]}if(p){if(St.has(d)){o===D.Stream&&(s.acceptsBuffer=!0);const e=await t.downloadMedia(p,{sizeType:u,start:a,end:i,progressCallback:s,workers:16});let n,c;return p instanceof g.Api.Message?(n=function(e,t){if(e&&e.media)return e.media instanceof g.Api.MessageMediaPhoto?"image/jpeg":e.media instanceof g.Api.MessageMediaDocument&&e.media.document instanceof g.Api.Document?t?e.media.document.attributes.some((e=>e instanceof g.Api.DocumentAttributeSticker))?"image/webp":"image/jpeg":e.media.document.mimeType:e.media instanceof g.Api.MessageMediaWebPage&&e.media.webpage instanceof g.Api.WebPage&&e.media.webpage.document instanceof g.Api.Document?e.media.webpage.document.mimeType:void 0}(p,u),p.media instanceof g.Api.MessageMediaDocument&&p.media.document instanceof g.Api.Document&&(c=p.media.document.size),p.media instanceof g.Api.MessageMediaWebPage&&p.media.webpage instanceof g.Api.WebPage&&p.media.webpage.document instanceof g.Api.Document&&(c=p.media.webpage.document.size)):p instanceof g.Api.Photo?n="image/jpeg":"sticker"===d&&u?n="image/webp":"webDocument"===d?n=p.mimeType:(n=p.mimeType,c=p.size),!r&&n&&(n=n.replace(/html/gi,"")),{mimeType:n,data:e,fullSize:c}}if("stickerSet"===d){const e=await t.downloadStickerSetThumb(p);return{mimeType:o===D.Lottie?"application/json":At(e),data:e}}{const e=await t.downloadProfilePhoto(p,"profile"===c[1]);return{mimeType:At(e),data:e}}}}(e,o,r,c,n,a,t,i)||{};if(!d)return;const p=await async function(e,t,n){switch(t){case D.BlobUrl:return new Blob([e],{type:n});case D.Lottie:{const t=(0,bt.inflate)(e,{to:"string"});return JSON.parse(t)}case D.Progressive:return e.buffer}}(d,t,l);if(!p)return;const f=t!==D.Progressive&&(t!==D.BlobUrl||p.size<=524288);return s&&f&&vt(e.startsWith("avatar")?"tt-media-avatars":"tt-media",e,p),{prepared:t===D.Progressive?"":(h=p,h instanceof Blob?URL.createObjectURL(h):h),arrayBuffer:t===D.Progressive?p:void 0,mimeType:l,fullSize:u};var h}(e,Rt,Ut,t)}function Nt(e,t){return Rt.uploadFile({file:e,onProgress:t,workers:16})}function Ft(e){return Rt.updateTwoFaSettings(e)}async function Ot(){const e=await xt(new g.Api.users.GetFullUser({id:new g.Api.InputUserSelf}));if(!(e&&e.user instanceof g.Api.User))return;v.users[ne(e.user.id,"user")]=e.user;const t=Ge(e);var n;n=t.id,de=n,function(e){at({"@type":"updateCurrentUser",currentUser:e})}(t)}const Lt=2**31-1;let qt;async function Ht({limit:e,offsetDate:t,archived:n,withPinned:s,serverTimeOffset:a,lastLocalServiceMessage:i}){const o=await xt(new g.Api.messages.GetDialogs({offsetPeer:new g.Api.InputPeerEmpty,limit:e,offsetDate:t,folderId:n?1:void 0,...s&&{excludePinned:!0}})),r=s?await xt(new g.Api.messages.GetPinnedDialogs({folderId:n?1:void 0})):void 0;if(!o||o instanceof g.Api.messages.DialogsNotModified)return;r&&kn(r),kn(o);const c=p((r?r.messages:[]).concat(o.messages).map(ue).filter(Boolean),"chatId"),l={...r&&Mn(r),...Mn(o)},u=[],f={},h={},m=(r?r.dialogs:[]).concat(o.dialogs),_=[];m.forEach((e=>{if(!(e instanceof g.Api.Dialog)||!n&&1===e.folderId||n&&1!==e.folderId)return;const t=Me(e,l[De(e.peer)],a);if(t.id===d&&i&&(!c[t.id]||i.date>c[t.id].date)?t.lastMessage=i:t.lastMessage=c[t.id],t.isListed=!0,u.push(t),s&&e.pinned&&_.push(t.id),e.draft){const{formattedText:n,replyingToId:s}=fe(e.draft)||{};n&&(f[t.id]=n),s&&(h[t.id]=s)}}));const y=(r?r.users:[]).concat(o.users).map(Ke).filter(Boolean),b=u.map((e=>e.id));let w;return w=o instanceof g.Api.messages.DialogsSlice?o.count:b.length,{chatIds:b,chats:u,users:y,draftsById:f,replyingToById:h,orderedPinnedIds:s?_:void 0,totalChatCount:w}}function Gt(e){const{id:t,accessHash:n,adminRights:s}=e;return O(t,n)instanceof g.Api.InputChannel?async function(e,t,n){var s;const a=await xt(new g.Api.channels.GetFullChannel({channel:O(e,t)}));if(!(a&&a.fullChat instanceof g.Api.ChannelFull))return;const{about:i,onlineCount:o,exportedInvite:r,slowmodeSeconds:c,slowmodeNextSendDate:d,migratedFromChatId:l,migratedFromMaxId:u,canViewParticipants:p,linkedChatId:f,hiddenPrehistory:h,call:m,botInfo:_}=a.fullChat,y=r instanceof g.Api.ChatInviteExported?r.link:void 0,{members:b,users:w}=p&&await wn(e,t)||{},{members:C,users:I}=p&&n&&await wn(e,t,"kicked")||{},{members:v,users:P}=p&&n&&await wn(e,t,"admin")||{},S=_?He(_):void 0;if((null==a||null===(s=a.chats)||void 0===s?void 0:s.length)>1){kn(a);const[,e]=a.chats,t=Ee(e,void 0,!0);t&&qt({"@type":"updateChat",id:t.id,chat:t})}return{fullInfo:{about:i,onlineCount:o,inviteLink:y,slowMode:c?{seconds:c,nextSendDate:d}:void 0,migratedFrom:l?{chatId:ne(l,"chat"),maxMessageId:u}:void 0,canViewMembers:p,isPreHistoryHidden:h,members:b,kickedMembers:C,adminMembers:v,groupCallId:m?String(m.id):void 0,linkedChatId:f?ne(f,"chat"):void 0,botCommands:S},users:[...w||[],...I||[],...P||[]]}}(t,n,s):async function(e){const t=await xt(new g.Api.messages.GetFullChat({chatId:O(e)}));if(!(t&&t.fullChat instanceof g.Api.ChatFull))return;kn(t);const{about:n,participants:s,exportedInvite:a,botInfo:i}=t.fullChat,o=Fe(s),r=o?o.filter((({isAdmin:e,isOwner:t})=>e||t)):void 0;return{fullInfo:{about:n,members:o,adminMembers:r,canViewMembers:!0,botCommands:i?He(i):void 0,...a&&{inviteLink:a.link}},users:t.users.map(Ke).filter(Boolean)}}(t)}async function Kt({query:e}){const t=await xt(new g.Api.contacts.Search({q:e}));if(!t)return;kn(t);const n=t.myResults.map(se),s=t.chats.concat(t.users).map((e=>Ee(e))).filter(Boolean),a=t.users.map(Ke).filter((e=>!!e&&!e.isSelf));return{localChats:s.filter((e=>n.includes(e.id))),localUsers:a.filter((e=>n.includes(e.id))),globalChats:s.filter((e=>!n.includes(e.id))),globalUsers:a.filter((e=>!n.includes(e.id)))}}async function zt({type:e,user:t}){let n;if("self"===e||"user"===e){const s=await xt(new g.Api.users.GetUsers({id:["user"===e&&t?O(t.id,t.accessHash):new g.Api.InputUserSelf]}));if(!s||!s.length)return;[n]=s}else if("support"===e){const e=await xt(new g.Api.help.GetSupport);if(!e||!e.user)return;n=e.user}const s=Ee(n,"support"===e);if(s)return qt({"@type":"updateChat",id:s.id,chat:s}),{chatId:s.id}}async function Wt({chat:e,serverTimeOffset:t,lastLocalMessage:n,noLastMessage:s}){const{id:a,accessHash:i}=e,o=await xt(new g.Api.messages.GetPeerDialogs({peers:[new g.Api.InputDialogPeer({peer:N(a,i)})]}));if(!o)return;const r=o.dialogs[0];if(!(r&&r instanceof g.Api.Dialog))return;const c=Mn(o)[De(r.peer)];if(!c)return;kn(o);const d=ue(o.messages[0]),l=n&&(!d||n.date>d.date)?n:d;qt({"@type":"updateChat",id:a,chat:{...Me(r,c,t),...!s&&{lastMessage:l}}})}function jt({chat:e,text:t,entities:n,replyToMsgId:s}){return xt(new g.Api.messages.SaveDraft({peer:N(e.id,e.accessHash),message:t,...n&&{entities:n.map(z)},replyToMsgId:s}))}function $t(e){return xt(new g.Api.messages.SaveDraft({peer:N(e.id,e.accessHash),message:""}))}async function Jt({chat:e,isMuted:t,serverTimeOffset:n}){await xt(new g.Api.account.UpdateNotifySettings({peer:new g.Api.InputNotifyPeer({peer:N(e.id,e.accessHash)}),settings:new g.Api.InputPeerNotifySettings({muteUntil:t?Lt:0})})),qt({"@type":"updateNotifyExceptions",chatId:e.id,isMuted:t}),Wt({chat:e,serverTimeOffset:n,noLastMessage:!0})}async function Qt({title:e,about:t,users:n}){const s=await xt(new g.Api.channels.CreateChannel({broadcast:!0,title:e,about:t}),!0);if(!(s instanceof g.Api.Updates))return;const a=s.chats[0];if(!(a&&a instanceof g.Api.Channel))return;const i=Ee(a);return await xt(new g.Api.channels.InviteToChannel({channel:O(i.id,i.accessHash),users:n.map((({id:e,accessHash:t})=>O(e,t)))})),i}function Xt({channelId:e,accessHash:t}){return xt(new g.Api.channels.JoinChannel({channel:O(e,t)}),!0)}function Zt({chat:e,user:t}){if("chatTypeBasicGroup"===e.type)return xt(new g.Api.messages.DeleteChatUser({chatId:O(e.id,e.accessHash),userId:O(t.id,t.accessHash)}),!0)}function Yt({chatId:e}){return xt(new g.Api.messages.DeleteChat({chatId:O(e)}),!0)}function en({channelId:e,accessHash:t}){return xt(new g.Api.channels.LeaveChannel({channel:O(e,t)}),!0)}function tn({channelId:e,accessHash:t}){return xt(new g.Api.channels.DeleteChannel({channel:O(e,t)}),!0)}async function nn({title:e,users:t}){const n=await xt(new g.Api.messages.CreateChat({title:e,users:t.map((({id:e,accessHash:t})=>O(e,t)))}),!0,!0);if(!(n instanceof g.Api.Updates))return;const s=n.chats[0];return s&&s instanceof g.Api.Chat?Ee(s):void 0}async function sn({chatId:e,accessHash:t,photo:n}){const s=await Nt(n),a=O(e,t);return xt(a instanceof g.Api.InputChannel?new g.Api.channels.EditPhoto({channel:a,photo:new g.Api.InputChatUploadedPhoto({file:s})}):new g.Api.messages.EditChatPhoto({chatId:a,photo:new g.Api.InputChatUploadedPhoto({file:s})}),!0)}async function an({chat:e,shouldBePinned:t}){const{id:n,accessHash:s}=e;await xt(new g.Api.messages.ToggleDialogPin({peer:new g.Api.InputDialogPeer({peer:N(n,s)}),pinned:t||void 0}))&&qt({"@type":"updateChatPinned",id:e.id,isPinned:t})}function on({chat:e,folderId:t}){const{id:n,accessHash:s}=e;return xt(new g.Api.folders.EditPeerFolders({folderPeers:[new g.Api.InputFolderPeer({peer:N(n,s),folderId:t})]}),!0)}async function rn(){const e=await xt(new g.Api.messages.GetDialogFilters);if(e)return{byId:p(e.map(Le),"id"),orderedIds:e.map((({id:e})=>e))}}async function cn(){const e=await xt(new g.Api.messages.GetSuggestedDialogFilters);if(e)return e.map(qe)}async function dn({id:e,folderUpdate:t}){const n=function(e){const{emoticon:t,contacts:n,nonContacts:s,groups:a,channels:i,bots:o,excludeArchived:r,excludeMuted:c,excludeRead:d,pinnedChatIds:l,includedChatIds:u,excludedChatIds:p}=e,f=l?l.map(F).filter(Boolean):[],h=u?u.map(F).filter(Boolean):[],m=p?p.map(F).filter(Boolean):[];return new g.Api.DialogFilter({id:e.id,title:e.title,emoticon:t||void 0,contacts:n||void 0,nonContacts:s||void 0,groups:a||void 0,bots:o||void 0,excludeArchived:r||void 0,excludeMuted:c||void 0,excludeRead:d||void 0,broadcasts:i||void 0,pinnedPeers:f,includePeers:h,excludePeers:m})}(t);await xt(new g.Api.messages.UpdateDialogFilter({id:e,filter:n}))&&qt({"@type":"updateChatFolder",id:e,folder:t})}async function ln(e){const t=await xt(new g.Api.messages.UpdateDialogFilter({id:e,filter:void 0})),n=await cn();t&&qt({"@type":"updateChatFolder",id:e,folder:void 0}),n&&qt({"@type":"updateRecommendedChatFolders",folders:n})}async function un({chat:e,hasUnreadMark:t}){const{id:n,accessHash:s}=e;await xt(new g.Api.messages.MarkDialogUnread({peer:new g.Api.InputDialogPeer({peer:N(n,s)}),unread:t||void 0}))&&qt({"@type":"updateChat",id:e.id,chat:{hasUnreadMark:t}})}async function gn(e){const t=await xt(new g.Api.contacts.ResolveUsername({username:e}));if(!t)return;const{users:n,chats:s}=t,a=s.length?Ee(s[0]):Ee(n[0]);return a?(kn(t),a):void 0}function pn({chat:e,isEnabled:t}){const{id:n,accessHash:s}=e,a=O(n,s);return xt(new g.Api.channels.TogglePreHistoryHidden({channel:a,enabled:t}),!0)}function fn({chat:e,bannedRights:t}){const{id:n,accessHash:s}=e,a=N(n,s);return xt(new g.Api.messages.EditChatDefaultBannedRights({peer:a,bannedRights:$(t)}),!0)}function hn({chat:e,user:t,bannedRights:n,untilDate:s}){const a=O(e.id,e.accessHash),i=N(t.id,t.accessHash);return xt(new g.Api.channels.EditBanned({channel:a,participant:i,bannedRights:$(n,s)}),!0)}function mn({chat:e,user:t,adminRights:n,customTitle:s=""}){const a=O(e.id,e.accessHash),i=O(t.id,t.accessHash);return xt(new g.Api.channels.EditAdmin({channel:a,userId:i,adminRights:J(n),rank:s}),!0)}async function _n(e,t){const n=O(e.id,e.accessHash);await xt(n instanceof g.Api.InputChannel?new g.Api.channels.EditTitle({channel:n,title:t}):new g.Api.messages.EditChatTitle({chatId:n,title:t}),!0)}async function yn(e,t){await xt(new g.Api.messages.EditChatAbout({peer:N(e.id,e.accessHash),about:t}))&&qt({"@type":"updateChatFullInfo",id:e.id,fullInfo:{about:t}})}function bn({chat:e,isEnabled:t}){const{id:n,accessHash:s}=e,a=O(n,s);return xt(new g.Api.channels.ToggleSignatures({channel:a,enabled:t}),!0)}async function wn(e,t,n="recent",s){let a;switch(n){case"kicked":a=new g.Api.ChannelParticipantsKicked({q:""});break;case"admin":a=new g.Api.ChannelParticipantsAdmins;break;default:a=new g.Api.ChannelParticipantsRecent}const i=await xt(new g.Api.channels.GetParticipants({channel:O(e,t),filter:a,offset:s,limit:200}));if(i&&!(i instanceof g.Api.channels.ChannelParticipantsNotModified))return kn(i),{members:Fe(i),users:i.users.map(Ke).filter(Boolean)}}async function Cn(){const e=await xt(new g.Api.channels.GetGroupsForDiscussion);if(e)return kn(e),e.chats.map((e=>Ee(e)))}function In({channel:e,chat:t}){return xt(new g.Api.channels.SetDiscussionGroup({broadcast:N(e.id,e.accessHash),group:t?N(t.id,t.accessHash):new g.Api.InputChannelEmpty}))}async function vn(e){const t=await xt(new g.Api.messages.MigrateChat({chatId:O(e.id)}),!0);if(t&&t instanceof g.Api.Updates)return kn(t),Ee(t.chats[1])}async function Pn(e){const t=await xt(new g.Api.messages.CheckChatInvite({hash:e}));if(!t)return;let n;return t instanceof g.Api.ChatInvite?qt({"@type":"showInvite",data:{title:t.title,hash:e,participantsCount:t.participantsCount,isChannel:t.channel}}):(n=Ee(t.chat),n&&qt({"@type":"updateChat",id:n.id,chat:n})),n?{chatId:n.id}:void 0}function Sn(e,t){return"chatTypeChannel"===e.type||"chatTypeSuperGroup"===e.type?xt(new g.Api.channels.InviteToChannel({channel:O(e.id,e.accessHash),users:t.map((e=>O(e.id,e.accessHash)))}),!0):Promise.all(t.map((t=>xt(new g.Api.messages.AddChatUser({chatId:O(e.id),userId:O(t.id,t.accessHash)}),!0))))}function An(e,t){return"chatTypeChannel"===e.type||"chatTypeSuperGroup"===e.type?hn({chat:e,user:t,bannedRights:{viewMessages:!0,sendMessages:!0,sendMedia:!0,sendStickers:!0,sendGifs:!0,sendGames:!0,sendInline:!0,embedLinks:!0,sendPolls:!0,changeInfo:!0,inviteUsers:!0,pinMessages:!0},untilDate:Lt}):xt(new g.Api.messages.DeleteChatUser({chatId:O(e.id),userId:O(t.id,t.accessHash)}),!0)}function Mn(e){const t={};return e.chats.forEach((e=>{t[`chat${e.id}`]=e})),e.users.forEach((e=>{t[`user${e.id}`]=e})),t}function kn(e){"users"in e&&e.users.forEach((e=>{e instanceof g.Api.User&&(v.users[ne(e.id,"user")]=e)})),"chats"in e&&e.chats.forEach(re),"messages"in e&&e.messages.forEach((e=>{e instanceof g.Api.Message&&W(e)&&ie(e)}))}async function Rn({hash:e}){const t=await xt(new g.Api.messages.ImportChatInvite({hash:e}),!0);if(t instanceof g.Api.Updates&&t.chats.length)return Ee(t.chats[0])}function Un(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}"undefined"==typeof File&&(self.File=class extends Blob{constructor(e,t,n){if(n){const{type:t,...s}=n;super(e,{type:t}),Un(this,"name",void 0),Object.assign(this,s)}else super(e),Un(this,"name",void 0);this.name=t}});var En=n(8764).Buffer;let Tn;async function Dn({chat:e,threadId:t,...n}){const s=-1===t?g.Api.messages.GetHistory:g.Api.messages.GetReplies;let a;try{a=await xt(new s({peer:N(e.id,e.accessHash),...-1!==t&&{msgId:t},...n}),void 0,!0)}catch(t){"CHANNEL_PRIVATE"===t.message&&Tn({"@type":"updateChat",id:e.id,chat:{isRestricted:!0}})}if(!a||a instanceof g.Api.messages.MessagesNotModified||!a.messages)return;is(a);const i=a.messages.map(ue).filter(Boolean),o=a.users.map(Ke).filter(Boolean),r=a.chats.map((e=>Ee(e))).filter(Boolean),c=i.map((({threadInfo:e})=>e)).filter(Boolean);return{messages:i,users:o,chats:r,threadInfos:c}}async function Bn({chat:e,messageId:t}){const n="channel"===x(e.id);let s;try{s=await xt(n?new g.Api.channels.GetMessages({channel:O(e.id,e.accessHash),id:[new g.Api.InputMessageID({id:t})]}):new g.Api.messages.GetMessages({id:[new g.Api.InputMessageID({id:t})]}),void 0,!0)}catch(e){const{message:t}=e;"CHANNEL_PRIVATE"!==t&&Tn({"@type":"error",error:{message:t,isSlowMode:!1,hasErrorKey:!0}})}if(!s||s instanceof g.Api.messages.MessagesNotModified)return;const a=s.messages[0];if(!a)return;if(a instanceof g.Api.MessageEmpty)return"MESSAGE_DELETED";const i=a&&ue(a);return i?(a instanceof g.Api.Message&&ie(a),{message:i,users:s.users.map(Ke).filter(Boolean)}):void 0}let xn=Promise.resolve();function Vn({chat:e,text:t,entities:n,replyingTo:s,attachment:a,sticker:i,gif:o,poll:r,isSilent:c,scheduledAt:d,groupedId:l,noWebPage:u,serverTimeOffset:p},f){const h=function(e,t,n,s,a,i,o,r,c,d,l=0){const u=le++,g=a&&function(e){const{filename:t,blobUrl:n,previewBlobUrl:s,mimeType:a,size:i}=e;if(e.quick){const{width:o,height:r,duration:c}=e.quick;return a.startsWith("image/")?{photo:{id:ce,sizes:[],thumbnail:{width:o,height:r,dataUri:""},blobUrl:n}}:{video:{id:ce,mimeType:a,duration:c||0,fileName:t,width:o,height:r,blobUrl:n,...s&&{thumbnail:{width:o,height:r,dataUri:s}},size:i}}}if(e.voice){const{duration:t,waveform:n}=e.voice,{data:s}=k(n,63);return{voice:{duration:t,waveform:s}}}return a.startsWith("audio/")?{audio:{mimeType:a,fileName:t,size:i,duration:200}}:{document:{mimeType:a,fileName:t,size:i,...s&&{previewBlobUrl:s}}}}(a),p="chatTypeChannel"===e.type;return{id:u,chatId:e.id,content:{...t&&{text:{text:t,entities:n}},...g,...i&&{sticker:i},...o&&{video:o},...r&&Ie(r,u)},date:d||Math.round(Date.now()/1e3)+l,isOutgoing:!p,senderId:de,...s&&{replyToMessageId:s},...c&&{groupedId:c,...g&&(g.photo||g.video)&&{isInAlbum:!0}},...d&&{isScheduled:!0}}}(e,t,n,s,a,i,o,r,l,d,p);Tn({"@type":h.isScheduled?"newScheduledMessage":"newMessage",id:h.id,chatId:e.id,message:h}),setTimeout((()=>{Tn({"@type":h.isScheduled?"updateScheduledMessage":"updateMessage",id:h.id,chatId:e.id,message:{sendingState:"messageSendingStatePending"}})}),1e3);const m=G();if(v.localMessages[String(m)]=h,l)return function({chat:e,text:t,entities:n,replyingTo:s,attachment:a,groupedId:i,isSilent:o,scheduledAt:r},c,d,l){let u=-1;Nn[i]||(Nn[i]={counter:0,singleMediaByIndex:{}}),u=Nn[i].counter++;const p=xn;return xn=(async()=>{let f;try{f=await Ln(d,a,l)}catch(e){return Nn[i].counter--,void await p}const h=await async function(e,t){const n=await xt(new g.Api.messages.UploadMedia({peer:e,media:t}));if(n instanceof g.Api.MessageMediaPhoto&&n.photo&&n.photo instanceof g.Api.Photo){const{photo:{id:e,accessHash:t,fileReference:s}}=n;return new g.Api.InputMediaPhoto({id:new g.Api.InputPhoto({id:e,accessHash:t,fileReference:s})})}if(n instanceof g.Api.MessageMediaDocument&&n.document&&n.document instanceof g.Api.Document){const{document:{id:e,accessHash:t,fileReference:s}}=n;return new g.Api.InputMediaDocument({id:new g.Api.InputDocument({id:e,accessHash:t,fileReference:s})})}}(N(e.id,e.accessHash),f);if(await p,!h)return void Nn[i].counter--;if(Nn[i].singleMediaByIndex[u]=new g.Api.InputSingleMedia({media:h,randomId:c,message:t||"",entities:n?n.map(z):void 0}),Object.keys(Nn[i].singleMediaByIndex).length{let l;if(a)try{l=await Ln(h,a,f)}catch(e){return void await _}else i?l=H(i):o?l=H(o):r&&(l=function(e,t){const{summary:n,quiz:s}=e,a=new g.Api.Poll({id:t,publicVoters:n.isPublic,question:n.question,answers:n.answers.map((({text:e,option:t})=>new g.Api.PollAnswer({text:e,option:B.from(t)}))),quiz:n.quiz,multipleChoice:n.multipleChoice});if(!s)return new g.Api.InputMediaPoll({poll:a});const i=s.correctAnswers.map((e=>B.from(e))),{solution:o}=s,r=s.solutionEntities?s.solutionEntities.map(z):[];return new g.Api.InputMediaPoll({poll:a,correctAnswers:i,...o&&{solution:o,solutionEntities:r}})}(r,m));await _;const p=l?g.Api.messages.SendMedia:g.Api.messages.SendMessage;await xt(new p({clearDraft:!0,message:t||"",entities:n?n.map(z):void 0,peer:N(e.id,e.accessHash),randomId:m,...c&&{silent:c},...d&&{scheduleDate:d},...s&&{replyToMsgId:s},...l&&{media:l},...u&&{noWebpage:u}}),!0)})(),xn}const Nn={};async function Fn({chat:e,message:t,text:n,entities:s,noWebPage:a,serverTimeOffset:i}){const o=1e3*t.date>Date.now()+1e3*i,r={content:{...t.content,...n&&{text:{text:n,entities:s}}}};Tn({"@type":o?"updateScheduledMessage":"updateMessage",id:t.id,chatId:e.id,message:r}),v.localMessages[t.id]={...t,...r};const c=s&&s.map(z);await xt(new g.Api.messages.EditMessage({message:n||"",entities:c,peer:N(e.id,e.accessHash),id:t.id,...o&&{scheduleDate:t.date},...a&&{noWebpage:a}}),!0)}async function On({chat:e,message:t,scheduledAt:n}){await xt(new g.Api.messages.EditMessage({peer:N(e.id,e.accessHash),id:t.id,scheduleDate:n}),!0)}async function Ln(e,t,n){const{filename:s,blobUrl:a,mimeType:i,quick:o,voice:d}=t,l=await async function(e,t){return function(e,t){return new File([e],t,{lastModified:Date.now(),type:e.type})}(await async function(e){return(await fetch(e)).blob()}(e),t)}(a,s),u=t=>{n.isCanceled?u.isCanceled=!0:n(t,e.id)},p=await Nt(l,u),f=[new g.Api.DocumentAttributeFilename({fileName:s})];if(o){if(r.has(i))return new g.Api.InputMediaUploadedPhoto({file:p});if(c.has(i)){const{width:e,height:t,duration:n}=o;void 0!==n&&f.push(new g.Api.DocumentAttributeVideo({duration:n,w:e,h:t,supportsStreaming:!0}))}}if(d){const{duration:e,waveform:t}=d,{data:n}=k(t,63);f.push(new g.Api.DocumentAttributeAudio({voice:!0,duration:e,waveform:En.from(n)}))}return new g.Api.InputMediaUploadedDocument({file:p,mimeType:i,attributes:f})}async function qn({chat:e,messageId:t,isUnpin:n,isOneSide:s,isSilent:a}){await xt(new g.Api.messages.UpdatePinnedMessage({peer:N(e.id,e.accessHash),id:t,...n&&{unpin:!0},...s&&{pmOneside:!0},...a&&{silent:!0}}),!0)}async function Hn({chat:e}){await xt(new g.Api.messages.UnpinAllMessages({peer:N(e.id,e.accessHash)}),!0)}async function Gn({chat:e,messageIds:t,shouldDeleteForAll:n}){const s="channel"===x(e.id);await xt(s?new g.Api.channels.DeleteMessages({channel:O(e.id,e.accessHash),id:t}):new g.Api.messages.DeleteMessages({id:t,...n&&{revoke:!0}}))&&Tn({"@type":"deleteMessages",ids:t,...s&&{chatId:e.id}})}async function Kn({chat:e,messageIds:t}){await xt(new g.Api.messages.DeleteScheduledMessages({peer:N(e.id,e.accessHash),id:t}))&&Tn({"@type":"deleteScheduledMessages",ids:t,chatId:e.id})}async function zn({chat:e,shouldDeleteForAll:t,maxId:n}){const s="channel"===x(e.id);await xt(s?new g.Api.channels.DeleteHistory({channel:O(e.id,e.accessHash),maxId:n}):new g.Api.messages.DeleteHistory({peer:N(e.id,e.accessHash),...t&&{revoke:!0},...!t&&{just_clear:!0},maxId:n}))&&Tn({"@type":"deleteHistory",chatId:e.id})}async function Wn({peer:e,messageIds:t,reason:n,description:s}){return await xt(new g.Api.messages.Report({peer:N(e.id,e.accessHash),id:t,reason:Z(n),message:s}))}async function jn({chat:e,threadId:t,maxId:n,serverTimeOffset:s}){const a="channel"===x(e.id);a&&-1===t?await xt(new g.Api.channels.ReadHistory({channel:O(e.id,e.accessHash),maxId:n})):a?await xt(new g.Api.messages.ReadDiscussion({peer:N(e.id,e.accessHash),msgId:t,readMaxId:n})):await xt(new g.Api.messages.ReadHistory({peer:N(e.id,e.accessHash),maxId:n})),-1===t?Wt({chat:e,serverTimeOffset:s,noLastMessage:!0}):Jn({chat:e,threadId:t})}async function $n({chat:e,messageIds:t}){const n="channel"===x(e.id);await xt(n?new g.Api.channels.ReadMessageContents({channel:O(e.id,e.accessHash),id:t}):new g.Api.messages.ReadMessageContents({id:t})),Tn({...n?{"@type":"updateChannelMessages",channelId:e.id}:{"@type":"updateCommonBoxMessages"},ids:t,messageUpdate:{hasUnreadMention:!1,isMediaUnread:!1}})}async function Jn({chat:e,threadId:t}){const[n,s]=await Promise.all([xt(new g.Api.messages.GetDiscussionMessage({peer:N(e.id,e.accessHash),msgId:t})),xt(new g.Api.messages.GetReplies({peer:N(e.id,e.accessHash),msgId:t,offsetId:1,addOffset:-1,limit:1}))]);if(!n||!n.messages.length)return;const a=ae(n.messages[0]);return a?(Tn({"@type":"updateThreadInfo",chatId:a,threadId:t,threadInfo:{threadId:t,topMessageId:n.messages[n.messages.length-1].id,lastReadInboxMessageId:n.readInboxMaxId,messagesCount:s instanceof g.Api.messages.ChannelMessages?s.count:void 0},firstMessageId:s&&"messages"in s&&s.messages.length?s.messages[0].id:void 0}),n.chats.map((e=>Ee(e))).filter(Boolean).forEach((e=>{Tn({"@type":"updateChat",id:e.id,chat:e,noTopChatsRequest:!0})})),{discussionChatId:a}):void 0}async function Qn({chatOrUser:e,type:t,query:n,topMessageId:s,minDate:a,maxDate:i,...o}){let r;switch(t){case"media":r=new g.Api.InputMessagesFilterPhotoVideo;break;case"documents":r=new g.Api.InputMessagesFilterDocument;break;case"links":r=new g.Api.InputMessagesFilterUrl;break;case"audio":r=new g.Api.InputMessagesFilterMusic;break;case"voice":r=new g.Api.InputMessagesFilterRoundVoice;break;case"profilePhoto":r=new g.Api.InputMessagesFilterChatPhotos;break;case"text":default:r=new g.Api.InputMessagesFilterEmpty}const c=await xt(new g.Api.messages.Search({peer:N(e.id,e.accessHash),filter:r,q:n||"",topMsgId:s,minDate:a,maxDate:i,...o}));if(!c||c instanceof g.Api.messages.MessagesNotModified||!c.messages)return;is(c);const d=c.messages.map(ue).filter(Boolean),l=c.users.map(Ke).filter(Boolean);let u,p=d.length;return(c instanceof g.Api.messages.MessagesSlice||c instanceof g.Api.messages.ChannelMessages)&&(p=c.count,d.length&&(u=d[d.length-1].id)),{messages:d,users:l,totalCount:p,nextOffsetId:u}}async function Xn({query:e,offsetRate:t=0,limit:n,type:s="text",minDate:a,maxDate:i}){let o;switch(s){case"media":o=new g.Api.InputMessagesFilterPhotoVideo;break;case"documents":o=new g.Api.InputMessagesFilterDocument;break;case"links":o=new g.Api.InputMessagesFilterUrl;break;case"audio":o=new g.Api.InputMessagesFilterMusic;break;case"voice":o=new g.Api.InputMessagesFilterRoundVoice;break;case"text":default:if(!(e||i&&a))return;o=new g.Api.InputMessagesFilterEmpty}const r=await xt(new g.Api.messages.SearchGlobal({q:e,offsetRate:t,offsetPeer:new g.Api.InputPeerEmpty,limit:n,filter:o,folderId:0,minDate:a,maxDate:i}));if(!r||r instanceof g.Api.messages.MessagesNotModified||!r.messages)return;is({chats:r.chats,users:r.users,messages:r.messages});const c=r.chats.map((e=>Ee(e))).filter(Boolean),d=r.users.map(Ke).filter(Boolean),l=r.messages.map(ue).filter(Boolean);let u,p=l.length;return(r instanceof g.Api.messages.MessagesSlice||r instanceof g.Api.messages.ChannelMessages)&&(p=r.count,l.length&&(u=l[l.length-1].id)),{messages:l,users:d,chats:c,totalCount:p,nextRate:"nextRate"in r&&r.nextRate?r.nextRate:u}}async function Zn({message:e}){const t=await xt(new g.Api.messages.GetWebPagePreview({message:e}));return t&&we(t)}async function Yn({chat:e,messageId:t,options:n}){const{id:s,accessHash:a}=e;await xt(new g.Api.messages.SendVote({peer:N(s,a),msgId:t,options:n.map((e=>En.from(e)))}),!0)}async function es({chat:e,messageId:t,option:n,offset:s,limit:a,shouldResetVoters:i}){const{id:o,accessHash:r}=e,c=await xt(new g.Api.messages.GetPollVotes({peer:N(o,r),id:t,...n&&{option:En.from(n)},...s&&{offset:s},...a&&{limit:a}}));if(!c)return;is({chats:[],users:c.users,messages:[]});const d=c.users.map(Ke).filter(Boolean),l=c.votes.map((e=>({userId:e.userId,date:e.date})));return{count:c.count,votes:l,users:d,nextOffset:c.nextOffset,shouldResetVoters:i}}async function ts({fromChat:e,toChat:t,messages:n,serverTimeOffset:s,isSilent:a,scheduledAt:i}){const o=n.map((({id:e})=>e)),r=n.map(G);n.forEach(((e,n)=>{const a=function(e,t,n,s){const a=le++,{content:i,chatId:o,id:r,senderId:c,groupedId:d,isInAlbum:l}=t,u=i.audio,g=e.id===de&&(o!==e.id||t.forwardInfo)&&!u;return{id:a,chatId:e.id,content:i,date:s||Math.round(Date.now()/1e3)+n,isOutgoing:!g&&"chatTypeChannel"!==e.type,senderId:de,sendingState:"messageSendingStatePending",groupedId:d,isInAlbum:l,...c!==de&&!u&&{forwardInfo:{isChannelPost:!1,fromChatId:o,fromMessageId:r,senderUserId:c}},...s&&{isScheduled:!0}}}(t,e,s,i);v.localMessages[String(r[n])]=a,Tn({"@type":a.isScheduled?"newScheduledMessage":"newMessage",id:a.id,chatId:t.id,message:a})})),await xt(new g.Api.messages.ForwardMessages({fromPeer:N(e.id,e.accessHash),toPeer:N(t.id,t.accessHash),randomId:r,id:o,...a&&{sil2ent:a},...i&&{scheduleDate:i}}),!0)}async function ns({chat:e,timestamp:t}){const n=await xt(new g.Api.messages.GetHistory({peer:N(e.id,e.accessHash),offsetDate:t,addOffset:-1,limit:1}));if(n&&!(n instanceof g.Api.messages.MessagesNotModified)&&n.messages&&n.messages.length)return n.messages[0].id}async function ss({chat:e}){const{id:t,accessHash:n}=e,s=await xt(new g.Api.messages.GetScheduledHistory({peer:N(t,n)}));if(s&&!(s instanceof g.Api.messages.MessagesNotModified)&&s.messages)return is(s),{messages:s.messages.map(ue).filter(Boolean)}}async function as({chat:e,ids:t}){const{id:n,accessHash:s}=e;await xt(new g.Api.messages.SendScheduledMessages({peer:N(n,s),id:t}),!0)}function is(e){e.users.forEach((e=>{e instanceof g.Api.User&&(v.users[ne(e.id,"user")]=e)})),e.chats.forEach((e=>{(e instanceof g.Api.Chat||e instanceof g.Api.Channel)&&(v.chats[ne(e.id,e instanceof g.Api.Chat?"chat":"channel")]=e)})),e.messages.forEach((e=>{(e instanceof g.Api.Message&&W(e)||e instanceof g.Api.MessageService&&function(e){return"photo"in e.action&&e.action.photo instanceof g.Api.Photo}(e))&&ie(e)}))}async function os({chat:e}){const t=await xt(new g.Api.messages.Search({peer:N(e.id,e.accessHash),filter:new g.Api.InputMessagesFilterPinned,q:"",limit:50}));if(t&&!(t instanceof g.Api.messages.MessagesNotModified)&&t.messages)return is(t),{messages:t.messages.map(ue).filter(Boolean),users:t.users.map(Ke).filter(Boolean),chats:t.chats.map((e=>Ee(e))).filter(Boolean)}}let rs,cs,ds,ls;async function us({id:e,accessHash:t}){const n=O(e,t);if(!(n instanceof g.Api.InputUser))return;const s=await xt(new g.Api.users.GetFullUser({id:n}));if(!s)return;const a=Ge(s);rs({"@type":"updateUser",id:e,user:{fullInfo:a.fullInfo}})}async function gs(e,t,n){const s=await xt(new g.Api.messages.GetCommonChats({userId:O(e,t),maxId:n?Y(n,x(n)):void 0,limit:100}));if(!s)return;Cs(s);const a=[],i=[];return s.chats.forEach((e=>{const t=Ee(e);t&&(i.push(t),a.push(t.id))})),{chats:i,chatIds:a,isFullyLoaded:a.length<100}}async function ps(){const e=await xt(new g.Api.help.GetNearestDc);return null==e?void 0:e.country}async function fs(){const e=await xt(new g.Api.contacts.GetTopPeers({correspondents:!0}));if(!(e instanceof g.Api.contacts.TopPeers))return;const t=e.users.map(Ke).filter((e=>!!e&&!e.isSelf));return{ids:t.map((({id:e})=>e)),users:t}}async function hs(){const e=await xt(new g.Api.contacts.GetContacts({hash:U()("0")}));if(e&&!(e instanceof g.Api.contacts.ContactsNotModified))return e.users.forEach((e=>{e instanceof g.Api.User&&(v.users[ne(e.id,"user")]=e)})),{users:e.users.map(Ke).filter(Boolean),chats:e.users.map((e=>Ee(e))).filter(Boolean)}}async function ms({users:e}){const t=await xt(new g.Api.users.GetUsers({id:e.map((({id:e,accessHash:t})=>N(e,t)))}));if(t&&t.length)return t.forEach((e=>{e instanceof g.Api.User&&(v.users[ne(e.id,"user")]=e)})),t.map(Ke).filter(Boolean)}function _s({phone:e,firstName:t,lastName:n}){return xt(new g.Api.contacts.ImportContacts({contacts:[j({phone:e||"",firstName:t||"",lastName:n||""})]}))}function ys({id:e,accessHash:t,phoneNumber:n="",firstName:s="",lastName:a=""}){return xt(new g.Api.contacts.AddContact({id:O(e,t),firstName:s,lastName:a,phone:n}),!0)}async function bs({id:e,accessHash:t}){const n=O(e,t);n instanceof g.Api.InputUser&&await xt(new g.Api.contacts.DeleteContacts({id:[n]}))&&rs({"@type":"deleteUser",id:e})}async function ws(e,t){if(e){const{id:t,accessHash:n}=e,s=await xt(new g.Api.photos.GetUserPhotos({userId:O(t,n),limit:40,offset:0,maxId:U()("0")}));if(!s)return;return Cs(s),{photos:s.photos.filter((e=>e instanceof g.Api.Photo)).map(C)}}const n=await Qn({chatOrUser:t,type:"profilePhoto",limit:40});if(!n)return;const{messages:s,users:a}=n;return{photos:s.map((e=>e.content.action.photo)).filter(Boolean),users:a}}function Cs(e){"chats"in e&&e.chats.forEach(re),"photos"in e&&e.photos.forEach(oe)}async function Is({hash:e="0"}){const t=await xt(new g.Api.messages.GetAllStickers({hash:U()(e)}));if(t&&!(t instanceof g.Api.messages.AllStickersNotModified))return t.sets.forEach((e=>{var t;null!==(t=e.thumbs)&&void 0!==t&&t.length&&(v.stickerSets[String(e.id)]=e)})),{hash:String(t.hash),sets:t.sets.map(A)}}async function vs({hash:e="0"}){const t=await xt(new g.Api.messages.GetRecentStickers({hash:U()(e)}));if(t&&!(t instanceof g.Api.messages.RecentStickersNotModified))return{hash:String(t.hash),stickers:Vs(t.stickers.slice(0,20))}}async function Ps({hash:e="0"}){const t=await xt(new g.Api.messages.GetFavedStickers({hash:U()(e)}));if(t&&!(t instanceof g.Api.messages.FavedStickersNotModified))return{hash:String(t.hash),stickers:Vs(t.stickers)}}async function Ss({hash:e="0"}){const t=await xt(new g.Api.messages.GetFeaturedStickers({hash:U()(e)}));if(t&&!(t instanceof g.Api.messages.FeaturedStickersNotModified))return{hash:String(t.hash),sets:t.sets.map(M)}}async function As({sticker:e,unfave:t}){const n=new g.Api.messages.FaveSticker({id:q(e),unfave:t});await xt(n)&&cs({"@type":"updateFavoriteStickers"})}async function Ms({stickerSetShortName:e,stickerSetId:t,accessHash:n}){const s=await xt(new g.Api.messages.GetStickerSet({stickerset:t?L(t,n):(a=e,new g.Api.InputStickerSetShortName({shortName:a}))}));var a,i;if(s)return{set:A(s.set),stickers:Vs(s.documents),packs:(i=s.packs,i.reduce(((e,{emoticon:t,documents:n})=>(e[t]=n.map((e=>S(v.documents[String(e)]))).filter(Boolean),e)),{}))}}async function ks(){const e=await xt(new g.Api.messages.GetStickerSet({stickerset:new g.Api.InputStickerSetAnimatedEmoji}));if(e)return{set:A(e.set),stickers:Vs(e.documents)}}async function Rs({query:e,hash:t="0"}){const n=await xt(new g.Api.messages.SearchStickerSets({q:e,hash:U()(t)}));if(n&&!(n instanceof g.Api.messages.FoundStickerSetsNotModified))return{hash:String(n.hash),sets:n.sets.map(M)}}async function Us({hash:e="0"}){const t=await xt(new g.Api.messages.GetSavedGifs({hash:U()(e)}));if(t&&!(t instanceof g.Api.messages.SavedGifsNotModified))return{hash:String(t.hash),gifs:Ns(t.gifs)}}async function Es({stickerSetId:e,accessHash:t}){await xt(new g.Api.messages.InstallStickerSet({stickerset:L(e,t)}))&&cs({"@type":"updateStickerSet",id:e,stickerSet:{installedDate:Date.now()}})}async function Ts({stickerSetId:e,accessHash:t}){await xt(new g.Api.messages.UninstallStickerSet({stickerset:L(e,t)}))&&cs({"@type":"updateStickerSet",id:e,stickerSet:{installedDate:void 0}})}async function Ds({query:e,offset:t=""}){if(!ds){const e=await xt(new g.Api.help.GetConfig);if(!e)return;const t=await xt(new g.Api.contacts.ResolveUsername({username:e.gifSearchUsername}));if(!(t&&t.users[0]instanceof g.Api.User))return;ds=new g.Api.InputUser({userId:t.peer.userId,accessHash:t.users[0].accessHash})}const n=await xt(new g.Api.messages.GetInlineBotResults({bot:ds,peer:new g.Api.InputPeerEmpty,query:e,offset:t}));if(!n)return;const s=n.results.map((e=>{if(e instanceof g.Api.BotInlineMediaResult)return e.document})).filter(Boolean);return{nextOffset:n.nextOffset,gifs:Ns(s)}}async function Bs({emoji:e,hash:t="0"}){const n=await xt(new g.Api.messages.GetStickers({emoticon:e,hash:U()(t)}));if(n&&!(n instanceof g.Api.messages.StickersNotModified))return{stickers:Vs(n.stickers),hash:String(n.hash)}}async function xs({language:e,fromVersion:t}){const n=await xt(new g.Api.messages.GetEmojiKeywordsDifference({langCode:e,fromVersion:t}));if(n)return{language:n.langCode,version:n.version,keywords:n.keywords.reduce(((e,t)=>(e[t.keyword]=t.emoticons,e)),{})}}function Vs(e){return e.map((e=>{if(e instanceof g.Api.Document){const t=S(e);if(t)return v.documents[String(e.id)]=e,t}})).filter(Boolean)}function Ns(e){return e.map((e=>{if(e instanceof g.Api.Document){const t=me(e);if(t)return v.documents[String(e.id)]=e,t}})).filter(Boolean)}async function Fs({username:e}){try{return await xt(new g.Api.channels.CheckUsername({channel:new g.Api.InputChannelEmpty,username:e}),void 0,!0)}catch(e){return!1}}async function Os({chat:e,username:t}){await xt(new g.Api.channels.UpdateUsername({channel:O(e.id,e.accessHash),username:t}))&&ls({"@type":"updateChat",id:e.id,chat:{username:t}})}async function Ls({chat:e}){const t=await xt(new g.Api.messages.ExportChatInvite({peer:N(e.id,e.accessHash)}));t&&t instanceof g.Api.ChatInviteExported&&ls({"@type":"updateChatFullInfo",id:e.id,fullInfo:{inviteLink:t.link}})}const qs={EMAIL_UNCONFIRMED:"Email unconfirmed",EMAIL_HASH_EXPIRED:"Email hash expired",NEW_SALT_INVALID:"The new salt is invalid",NEW_SETTINGS_INVALID:"The new password settings are invalid",CODE_INVALID:"Invalid Code",PASSWORD_HASH_INVALID:"Invalid Password"},Hs={};let Gs;async function Ks(){const e=await xt(new g.Api.account.GetPassword);if(!e)return;const{hint:t,hasPassword:n}=e;return{hint:t,hasPassword:n}}function zs(e){return Gs({"@type":"updateTwoFaStateWaitCode",length:e}),new Promise(((e,t)=>{Hs.resolve=e,Hs.reject=t}))}async function Ws(e){try{return await Ft({isCheckPassword:!0,currentPassword:e}),!0}catch(e){return Xs(e),!1}}async function js(e){try{return await Ft({currentPassword:e}),!0}catch(e){return Xs(e),!1}}async function $s(e,t,n,s){try{return await Ft({currentPassword:e,newPassword:t,hint:n,email:s,emailCodeCallback:zs,onEmailCodeError:Xs}),!0}catch(e){return Xs(e),!1}}async function Js(e,t){try{return await Ft({currentPassword:e,newPassword:e,email:t,emailCodeCallback:zs,onEmailCodeError:Xs}),!0}catch(e){return Xs(e),!1}}function Qs(e){Hs.resolve(e)}function Xs(e){let t;if(e instanceof g.errors.FloodWaitError){const n=Math.ceil(Number(e.seconds)/60/60);t="Too many attempts. Try again in "+(n>1?`${n} hours`:"an hour")}else t=qs[e.message];t||(t="Unexpected Error"),Gs({"@type":"updateTwoFaError",message:t})}const Zs=["ar","fa","id","ko","uz"];function Ys({firstName:e,lastName:t,about:n}){return xt(new g.Api.account.UpdateProfile({firstName:e||"",lastName:t||"",about:n||""}))}function ea(e){return xt(new g.Api.account.CheckUsername({username:e}))}function ta(e){return xt(new g.Api.account.UpdateUsername({username:e}))}async function na(e){const t=await Nt(e);return xt(new g.Api.photos.UploadProfilePhoto({file:t}))}async function sa(e){const t=await Nt(e);await xt(new g.Api.photos.UploadProfilePhoto({file:t}))}async function aa(){const e=await xt(new g.Api.account.GetWallPapers({hash:U()("0")}));if(!e||e instanceof g.Api.account.WallPapersNotModified)return;const t=e.wallpapers.filter((e=>e instanceof g.Api.WallPaper&&e.document instanceof g.Api.Document&&!e.pattern&&"application/x-tgwallpattern"!==e.document.mimeType));return t.forEach((e=>{v.documents[String(e.document.id)]=e.document})),{wallpapers:t.map(je).filter(Boolean)}}async function ia(e){const t=await Nt(e),n=await xt(new g.Api.account.UploadWallPaper({file:t,mimeType:e.type,settings:new g.Api.WallPaperSettings}));if(!(n&&n instanceof g.Api.WallPaper))return;const s=je(n);return s?(v.documents[String(n.document.id)]=n.document,{wallpaper:s}):void 0}async function oa(){const e=await xt(new g.Api.contacts.GetBlocked({limit:100}));if(e)return Aa(e),{users:e.users.map(Ke).filter(Boolean),chats:e.chats.map((e=>Ee(e,void 0,!0))).filter(Boolean),blockedIds:e.blocked.map((e=>se(e.peerId))),totalCount:e instanceof g.Api.contacts.BlockedSlice?e.count:e.blocked.length}}function ra(e,t){return xt(new g.Api.contacts.Block({id:N(e,t)}))}function ca(e,t){return xt(new g.Api.contacts.Unblock({id:N(e,t)}))}async function da(){const e=await xt(new g.Api.account.GetAuthorizations);if(e)return e.authorizations.map($e)}function la(e){return xt(new g.Api.account.ResetAuthorization({hash:U()(e)}))}function ua(){return xt(new g.Api.auth.ResetAuthorizations)}async function ga({serverTimeOffset:e}){const t=await xt(new g.Api.account.GetNotifyExceptions({compareSound:!0}));if(t instanceof g.Api.Updates||t instanceof g.Api.UpdatesCombined)return Aa(t),t.updates.reduce(((t,n)=>n instanceof g.Api.UpdateNotifySettings&&n.peer instanceof g.Api.NotifyPeer?(t.push(Qe(n.notifySettings,n.peer.peer,e)),t):t),[])}async function pa({serverTimeOffset:e}){const[t,n,s,a]=await Promise.all([xt(new g.Api.account.GetContactSignUpNotification),xt(new g.Api.account.GetNotifySettings({peer:new g.Api.InputNotifyUsers})),xt(new g.Api.account.GetNotifySettings({peer:new g.Api.InputNotifyChats})),xt(new g.Api.account.GetNotifySettings({peer:new g.Api.InputNotifyBroadcasts}))]);if(!n||!s||!a)return!1;const{silent:i,muteUntil:o,showPreviews:r}=n,{silent:c,muteUntil:d,showPreviews:l}=s,{silent:u,muteUntil:p,showPreviews:f}=a;return{hasContactJoinedNotifications:!t,hasPrivateChatsNotifications:!(i||"number"==typeof o&&Se(e)xt(new g.Api.langpack.GetLangPack({langPack:e,langCode:Zs.includes(t)?`${t}-raw`:t})))))).filter(Boolean).map((e=>p(e.strings.map(_),"key")));if(n.length)return{langPack:Object.assign({},...n.reverse())}}async function ya({langPack:e,langCode:t,keys:n}){const s=await xt(new g.Api.langpack.GetStrings({langPack:e,langCode:Zs.includes(t)?`${t}-raw`:t,keys:n}));if(s)return s.map(_)}async function ba(e){const t=X(e),n=await xt(new g.Api.account.GetPrivacy({key:t}));if(n)return Aa(n),Je(n.rules)}function wa(e){const t=Rt.session.getAuthKey().getKey();return xt(new g.Api.account.RegisterDevice({tokenType:10,secret:t,appSandbox:!1,otherUids:[],token:e}))}function Ca(e){return xt(new g.Api.account.UnregisterDevice({tokenType:10,otherUids:[],token:e}))}async function Ia(e,t){const n=X(e),s=[];switch(t.allowedUsers&&s.push(new g.Api.InputPrivacyValueAllowUsers({users:t.allowedUsers.map((({id:e,accessHash:t})=>O(e,t)))})),t.allowedChats&&s.push(new g.Api.InputPrivacyValueAllowChatParticipants({chats:t.allowedChats.map((({id:e})=>O(e)))})),t.blockedUsers&&s.push(new g.Api.InputPrivacyValueDisallowUsers({users:t.blockedUsers.map((({id:e,accessHash:t})=>O(e,t)))})),t.blockedChats&&s.push(new g.Api.InputPrivacyValueDisallowChatParticipants({chats:t.blockedChats.map((({id:e})=>O(e)))})),t.visibility){case"everybody":s.push(new g.Api.InputPrivacyValueAllowAll);break;case"contacts":s.push(new g.Api.InputPrivacyValueAllowContacts);break;case"nonContacts":s.push(new g.Api.InputPrivacyValueDisallowContacts);break;case"nobody":s.push(new g.Api.InputPrivacyValueDisallowAll)}const a=await xt(new g.Api.account.SetPrivacy({key:n,rules:s}));if(a)return Aa(a),Je(a.rules)}async function va(e){await xt(new g.Api.account.UpdateStatus({offline:!e}))}async function Pa(){const e=await xt(new g.Api.account.GetContentSettings);if(e)return{isSensitiveEnabled:Boolean(e.sensitiveEnabled),canChangeSensitive:Boolean(e.sensitiveCanChange)}}function Sa(e){return xt(new g.Api.account.SetContentSettings({sensitiveEnabled:e||void 0}))}function Aa(e){e.users.forEach((e=>{e instanceof g.Api.User&&(v.users[ne(e.id,"user")]=e)})),e.chats.forEach((e=>{(e instanceof g.Api.Chat||e instanceof g.Api.Channel)&&(v.chats[ne(e.id,e instanceof g.Api.Chat?"chat":"channel")]=e)}))}async function Ma({langCode:e="en"}){const t=await xt(new g.Api.help.GetCountriesList({langCode:e}));if(t instanceof g.Api.help.CountriesList)return n=t.countries,{phoneCodes:(s=n.filter((e=>!e.hidden)).map((e=>e.countryCodes.map((t=>Xe(e,t))))),s.reduce(((e,t)=>Array.isArray(t)?e.concat(t):(e.push(t),e)),[])).sort(((e,t)=>e.name?e.name.localeCompare(t.name):e.defaultName.localeCompare(t.defaultName))),general:n.filter((e=>!e.hidden)).map((e=>Xe(e))).sort(((e,t)=>e.name?e.name.localeCompare(t.name):e.defaultName.localeCompare(t.defaultName)))};var n,s}function ka(e){return e?f(e,["url","mimeType"]):void 0}var Ra=n(8764).Buffer;function Ua({chatId:e,accessHash:t,messageId:n,data:s}){return xt(new g.Api.messages.GetBotCallbackAnswer({peer:N(e,t),msgId:n,data:Ra.from(s)}))}async function Ea(){const e=await xt(new g.Api.contacts.GetTopPeers({botsInline:!0}));if(!(e instanceof g.Api.contacts.TopPeers))return;const t=e.users.map(Ke).filter(Boolean);return{ids:t.map((({id:e})=>e)),users:t}}async function Ta({username:e}){const t=await xt(new g.Api.contacts.ResolveUsername({username:e}));if(t&&t.users[0]instanceof g.Api.User&&t.users[0].bot&&t.users[0].botInlinePlaceholder)return Va(t.users[0]),{user:Ke(t.users[0]),chat:Ee(t.users[0])}}async function Da({bot:e,chat:t,query:n,offset:s=""}){const a=await xt(new g.Api.messages.GetInlineBotResults({bot:N(e.id,e.accessHash),peer:N(t.id,t.accessHash),query:n,offset:s}));var i,o,r,c,d;if(a)return a.users.map(Va),{isGallery:Boolean(a.gallery),help:e.botPlaceholder,nextOffset:(c=e.username,d=a.nextOffset,"gif"===c&&"0"===d?"":d),switchPm:(r=a.switchPm,r?f(r,["text","startParam"]):void 0),users:a.users.map(Ke).filter(Boolean),results:(i=String(a.queryId),o=a.results,o.map((e=>{return e instanceof g.Api.BotInlineMediaResult?(e.document instanceof g.Api.Document&&(t=e.document,v.documents[String(t.id)]=t),e.photo instanceof g.Api.Photo&&(n=e.photo,v.photos[String(n.id)]=n),function(e,t){const{id:n,type:s,title:a,description:i,photo:o,document:r}=e;return{id:n,queryId:t,type:s,title:a,description:i,..."sticker"===s&&r instanceof g.Api.Document&&{sticker:S(r)},...o instanceof g.Api.Photo&&{photo:C(o)},..."gif"===s&&r instanceof g.Api.Document&&{gif:me(r)},..."video"===s&&r instanceof g.Api.Document&&{thumbnail:w(r.thumbs)}}}(e,i)):(e.thumb&&(s=e.thumb,v.webDocuments[s.url]=s),function(e,t){const{id:n,type:s,title:a,description:i,url:o,thumb:r}=e;return{id:n,queryId:t,type:s,title:a,description:i,url:o,webThumbnail:ka(r)}}(e,i));var t,n,s})))}}async function Ba({chat:e,resultId:t,queryId:n,replyingTo:s}){const a=G();await xt(new g.Api.messages.SendInlineBotResult({clearDraft:!0,randomId:a,queryId:U()(n),peer:N(e.id,e.accessHash),id:t,...s&&{replyToMsgId:s}}),!0)}async function xa({bot:e,startParam:t}){const n=G();await xt(new g.Api.messages.StartBot({bot:N(e.id,e.accessHash),peer:N(e.id,e.accessHash),randomId:n,startParam:t}),!0)}function Va(e){v.users[ne(e.id,"user")]=e}function Na(e){if(e)return Object.values(e).map((e=>({id:e.id,title:e.title,amount:e.prices.reduce(((e,t)=>e+Number(t.amount.value)),0),prices:e.prices.map((({label:e,amount:t})=>({label:e,amount:Number(t.value)})))})))}async function Fa({chat:e,messageId:t,requestInfo:n,shouldSave:s}){const a=await xt(new g.Api.payments.ValidateRequestedInfo({peer:N(e.id,e.accessHash),msgId:t,save:s||void 0,info:Q(n)}));if(!a)return;const{id:i,shippingOptions:o}=a;return i?{id:i,shippingOptions:Na(o)}:void 0}function Oa({chat:e,messageId:t,formId:n,requestedInfoId:s,shippingOptionId:a,credentials:i}){return xt(new g.Api.payments.SendPaymentForm({formId:U()(n),peer:N(e.id,e.accessHash),msgId:t,requestedInfoId:s,shippingOptionId:a,credentials:new g.Api.InputPaymentCredentials({save:i.save,data:new g.Api.DataJSON({data:JSON.stringify(i.data)})})}),!0)}async function La({chat:e,messageId:t}){const n=await xt(new g.Api.payments.GetPaymentForm({peer:N(e.id,e.accessHash),msgId:t}));if(n)return function(e){const{formId:t,canSaveCredentials:n,passwordMissing:s,providerId:a,nativeProvider:i,nativeParams:o,savedInfo:r,invoice:c}=e,{test:d,nameRequested:l,phoneRequested:u,emailRequested:g,shippingAddressRequested:p,flexible:f,phoneToProvider:h,emailToProvider:m,currency:_,prices:y}=c,b=y.map((({label:e,amount:t})=>({label:e,amount:Number(t.value)}))),w=o?JSON.parse(o.data):{};return{canSaveCredentials:n,passwordMissing:s,formId:String(t),providerId:String(a),nativeProvider:i,savedInfo:r,invoice:{test:d,nameRequested:l,phoneRequested:u,emailRequested:g,shippingAddressRequested:p,flexible:f,phoneToProvider:h,emailToProvider:m,currency:_,prices:b},nativeParams:{needCardholderName:w.need_cardholder_name,needCountry:w.need_country,needZip:w.need_zip,publishableKey:w.publishable_key}}}(n)}async function qa(e,t){const n=await xt(new g.Api.payments.GetPaymentReceipt({peer:N(e.id,e.accessHash),msgId:t}));if(n)return function(e){const{invoice:t,info:n,shipping:s,currency:a,totalAmount:i,credentialsTitle:o}=e,{shippingAddress:r,phone:c,name:d}=n||{},{prices:l}=t,u=l.map((({label:e,amount:t})=>({label:e,amount:Number(t.value)})));let g,p;return s&&(g=s.prices.map((({label:e,amount:t})=>({label:e,amount:Number(t.value)}))),p=s.title),{currency:a,prices:u,info:{shippingAddress:r,phone:c,name:d},totalAmount:Number(i.value),credentialsTitle:o,shippingPrices:g,shippingMethod:p}}(n)}let Ha;async function Ga(e,t){Ha=e,function(e){Ze=e}($a),function(e){at=e}($a),function(e){qt=e}($a),function(e){Tn=e}($a),function(e){rs=e}($a),function(e){cs=e}($a),function(e){ls=e}($a),function(e){Gs=e}($a),await async function(e,t){kt=e;const{userAgent:n,platform:s,sessionData:a,isTest:i,isMovSupported:o}=t,r=new g.sessions.CallbackSession(a,Dt);self.isMovSupported=o,Rt=new g.TelegramClient(r,"2496","8da85b0d5bfe62527e5b244c209159c3",{deviceModel:navigator.userAgent||n||"Unknown UserAgent",systemVersion:s||"Unknown platform",appVersion:"1.22.1 Z",useWSS:!0,additionalDcsDisabled:!1,testServers:i}),Rt.addEventHandler(Bt,Mt),Rt.addEventHandler(tt,Mt);try{try{await Rt.start({phoneNumber:it,phoneCode:ot,password:rt,firstAndLastNames:ct,qrCode:dt,onError:lt,initialMethod:"iOS"===s||"Android"===s?"phoneNumber":"qrCode"})}catch(e){if("Disconnect"!==e.message)return void kt({"@type":"updateConnectionState",connectionState:"connectionStateBroken"})}at(ut("authorizationStateReady")),Dt(r.getSessionData()),kt({"@type":"updateApiReady"}),Ot()}catch(e){throw e}}($a,t)}const Ka=function(e,t){let n,s=!1;return(...a)=>{n=a,s||(s=!0,e((()=>{s=!1,t(...n)})))}}((function(e,t=!1){l?t?u.push(e):l.push(e):(l=t?[]:[e],u=t?[e]:[],Promise.resolve().then((()=>{const e=l,t=u;l=void 0,u=void 0,t.forEach((e=>e())),e.forEach((e=>e()))})))}),(function(e){if(!ja||e!==Wa)return;const t=ja;ja=void 0,t.forEach(Ha)}));let za,Wa,ja;function $a(e){ja?ja.push(e):ja=[e],za&&!o.has(e["@type"])||(za=function(e,t,n=!0){let s,a,i;return(...o)=>{a=!0,i=o,s||(n&&(a=!1,e(...i)),s=self.setInterval((()=>{if(!a)return self.clearInterval(s),void(s=void 0);a=!1,e(...i)}),t))}}(Ka,i,!0),Wa=Math.random()),za(Wa)}self.onerror=e=>{console.error(e),Xa({type:"unhandledError",error:{message:e.error.message||"Uncaught exception in worker"}})},self.addEventListener("unhandledrejection",(e=>{console.error(e),Xa({type:"unhandledError",error:{message:e.reason.message||"Uncaught rejection in worker"}})}));const Ja=new Map;function Qa(e){Xa({type:"update",update:e})}function Xa(e,t){t?postMessage(e,[t]):postMessage(e)}onmessage=async e=>{const{data:t}=e;switch(t.type){case"initApi":await Ga(Qa,t.args[0]);break;case"callMethod":{const{messageId:e,name:n,args:s}=t;try{if(e){const t=(...t)=>{const n=t[t.length-1];Xa({type:"methodCallback",messageId:e,callbackArgs:t},n instanceof ArrayBuffer?n:void 0)};Ja.set(e,t),s.push(t)}const t=await function(e,...t){return a[e](...t)}(n,...s),{arrayBuffer:i}="object"==typeof t&&"arrayBuffer"in t&&t||{};e&&Xa({type:"methodResponse",messageId:e,response:t},i)}catch(t){e&&Xa({type:"methodResponse",messageId:e,error:{message:t.message}})}e&&Ja.delete(e);break}case"cancelProgress":{const e=Ja.get(t.messageId);e&&(e.isCanceled=!0);break}case"ping":Xa({type:"methodResponse",messageId:t.messageId})}}},9618:(e,t,n)=>{var s=n(8764).Buffer;const a=n(4736),i=n(6842);function o(e,t=!0,n=!1){let i=s.from(e);const o=i.length;t&&(i=i.reverse());let r=a(i.toString("hex"),16);return n&&Math.floor(r.toString("2").length/8)>=o&&(r=r.subtract(a(2).pow(a(8*o)))),r}function r(e,t=8){const n=a(e),i=[];for(let e=0;e>>1:e>>>1;t[n]=e}return t}()),s.isBuffer(e)||(e=s.from(e));let t=-1;for(let n=0;n>>8}return(-1^t)>>>0},generateRandomBytes:d,generateKeyDataFromNonce:async function(e,t){e=r(e,16),t=r(t,32);const[n,a,i]=await Promise.all([l(s.concat([t,e])),l(s.concat([e,t])),l(s.concat([t,t]))]);return{key:s.concat([n,a.slice(0,12)]),iv:s.concat([a.slice(12,20),i,t.slice(0,4)])}},sha1:l,sha256:function(e){const t=i.createHash("sha256");return t.update(e),t.digest()},bigIntMod:function(e,t){return e.remainder(t).add(t).remainder(t)},modExp:function(e,t,n){e=e.remainder(n);let s=a.one,i=e;for(;t.greater(a.zero);){const e=t.remainder(a(2));t=t.divide(a(2)),e.eq(a.one)&&(s=s.multiply(i),s=s.remainder(n)),i=i.multiply(i),i=i.remainder(n)}return s},getRandomInt:function(e,t){return e=Math.ceil(e),t=Math.floor(t),Math.floor(Math.random()*(t-e+1))+e},sleep:e=>new Promise((t=>setTimeout(t,e))),getByteArray:function(e,t=!1){const n=e.toString(2).length,s=Math.floor((n+8-1)/8);return c(a(e),s,!1,t)},toSignedLittleBuffer:r,convertToLittle:function(e){const t=s.alloc(4*e.length);for(let n=0;n{e=t})),resolve:e}}}},9674:(e,t,n)=>{var s=n(8764).Buffer;const a=n(4736),{constructors:i}=n(7404),{readBigIntFromBuffer:o,readBufferFromBigInt:r,sha256:c,bigIntMod:d,modExp:l,generateRandomBytes:u}=n(9618),g=n(6842);function p(e,t){if(!s.from([199,28,174,185,198,177,201,4,142,108,82,47,112,241,63,115,152,13,64,35,142,62,33,193,73,52,208,55,86,61,147,15,72,25,138,10,167,193,64,88,34,148,147,210,37,48,244,219,250,51,111,110,10,201,37,19,149,67,174,212,76,206,124,55,32,253,81,246,148,88,112,90,198,140,212,254,107,107,19,171,220,151,70,81,41,105,50,132,84,241,143,175,140,89,95,100,36,119,254,150,187,42,148,29,91,205,29,74,200,204,73,136,7,8,250,155,55,142,60,79,58,144,96,190,230,124,249,164,164,166,149,129,16,81,144,126,22,39,83,181,107,15,107,65,13,186,116,216,168,75,42,20,179,20,78,14,241,40,71,84,253,23,237,149,13,89,101,180,185,221,70,88,45,177,23,141,22,156,107,196,101,176,214,255,156,163,146,143,239,91,154,228,228,24,252,21,232,62,190,160,248,127,169,255,94,237,112,5,13,237,40,73,244,123,249,89,217,86,133,12,233,41,133,31,13,129,21,246,53,177,5,238,46,78,21,208,75,36,84,191,111,79,173,240,52,177,4,3,17,156,216,227,185,47,204,91]).equals(e)||![3,4,5,7].includes(t))throw new Error("Changing passwords unsupported")}function f(e){return s.concat([s.alloc(256-e.length),e])}function h(e){return r(e,256,!1)}function m(e,t){const n=t.subtract(e);return!(n.lesser(a(0))||n.bitLength()<1984||e.bitLength()<1984||Math.floor((e.bitLength()+7)/8)>256)}function _(e,t){const n=Math.min(e.length,t.length);for(let s=0;s{for(;;){const e=u(256),t=o(e,!1),n=l(a(b),t,g);if(m(n,g)){const e=h(n),i=o(await c(s.concat([e,P])),!1);if(i.greater(a(0)))return[t,e,i]}}})(),E=d(w.subtract(M),g);if(!m(E,g))throw new Error("bad gB");const T=U.multiply(C),D=k.add(T),B=l(E,D,g),[x,V,N,F,O]=await Promise.all([c(h(B)),c(I),c(v),c(n.salt1),c(n.salt2)]),L=await c(s.concat([_(V,N),F,O,R,P,x]));return new i.InputCheckPasswordSRP({srpId:e.srpId,A:s.from(R),M1:L})},computeDigest:async function(e,t){try{p(e.p,e.g)}catch(e){throw new Error("bad p/g in password")}return h(l(a(e.g),o(await y(e,t),!1),o(e.p,!1)))}}},8960:(e,t,n)=>{var s=n(8764).Buffer;const{constructors:a}=n(7404),i=s.from("ffd8ffe000104a46494600010100000100010000ffdb004300281c1e231e19282321232d2b28303c64413c37373c7b585d4964918099968f808c8aa0b4e6c3a0aadaad8a8cc8ffcbdaeef5ffffff9bc1fffffffaffe6fdfff8ffdb0043012b2d2d3c353c76414176f8a58ca5f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8ffc00011080000000003012200021101031101ffc4001f0000010501010101010100000000000000000102030405060708090a0bffc400b5100002010303020403050504040000017d01020300041105122131410613516107227114328191a1082342b1c11552d1f02433627282090a161718191a25262728292a3435363738393a434445464748494a535455565758595a636465666768696a737475767778797a838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae1e2e3e4e5e6e7e8e9eaf1f2f3f4f5f6f7f8f9faffc4001f0100030101010101010101010000000000000102030405060708090a0bffc400b51100020102040403040705040400010277000102031104052131061241510761711322328108144291a1b1c109233352f0156272d10a162434e125f11718191a262728292a35363738393a434445464748494a535455565758595a636465666768696a737475767778797a82838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae2e3e4e5e6e7e8e9eaf2f3f4f5f6f7f8f9faffda000c03010002110311003f00","hex"),o=s.from("ffd9","hex");function r(e,t){throw new Error(`Cannot cast ${e.className} to any kind of ${t}`)}e.exports={getMessageId:function(e){if(void 0!==e){if("number"==typeof e)return e;if(2030045667===e.SUBCLASS_OF_ID)return e.id;throw new Error(`Invalid message type: ${e.constructor.name}`)}},getInputPeer:function e(t,n=!0,s=!0){if(void 0===t.SUBCLASS_OF_ID){if(n&&"inputEntity"in t)return t.inputEntity;if("entity"in t)return e(t.entity);r(t,"InputPeer")}if(3374092470===t.SUBCLASS_OF_ID)return t;if(t instanceof a.User){if(t.isSelf&&n)return new a.InputPeerSelf;if(void 0===t.accessHash&&s)throw new Error("User without accessHash or min info cannot be input");return new a.InputPeerUser({userId:t.id,accessHash:t.accessHash})}if(t instanceof a.Chat||t instanceof a.ChatEmpty||t instanceof a.ChatForbidden)return new a.InputPeerChat({chatId:t.id});if(t instanceof a.Channel){if(void 0===t.accessHash&&s)throw new TypeError("Channel without accessHash or min info cannot be input");return new a.InputPeerChannel({channelId:t.id,accessHash:t.accessHash})}return t instanceof a.ChannelForbidden?new a.InputPeerChannel({channelId:t.id,accessHash:t.accessHash}):t instanceof a.InputUser?new a.InputPeerUser({userId:t.userId,accessHash:t.accessHash}):t instanceof a.InputChannel?new a.InputPeerChannel({channelId:t.channelId,accessHash:t.accessHash}):t instanceof a.UserEmpty?new a.InputPeerEmpty:t instanceof a.UserFull?e(t.user):t instanceof a.ChatFull?new a.InputPeerChat({chatId:t.id}):t instanceof a.PeerChat?new a.InputPeerChat(t.chatId):void r(t,"InputPeer")},getDisplayName:function(e){return e instanceof a.User?e.lastName&&e.firstName?`${e.firstName} ${e.lastName}`:e.firstName?e.firstName:e.lastName?e.lastName:"":e instanceof a.Chat||e instanceof a.Channel?e.title:""},getAppropriatedPartSize:function(e){if(e<=104857600)return 128;if(e<=786432e3)return 256;if(e<=2097152e3)return 512;throw new Error("File size too large")},strippedPhotoToJpg:function(e){if(e.length<3||1!==e[0])return e;const t=s.from(i);return t[164]=e[1],t[166]=e[2],s.concat([t,e.slice(3),o])},getDC:function(e,t=!1){switch(e){case 1:return{id:1,ipAddress:`zws1${t?"-1":""}.web.telegram.org`,port:443};case 2:return{id:2,ipAddress:`zws2${t?"-1":""}.web.telegram.org`,port:443};case 3:return{id:3,ipAddress:`zws3${t?"-1":""}.web.telegram.org`,port:443};case 4:return{id:4,ipAddress:`zws4${t?"-1":""}.web.telegram.org`,port:443};case 5:return{id:5,ipAddress:`zws5${t?"-1":""}.web.telegram.org`,port:443};default:throw new Error(`Cannot find the DC with the ID of ${e}`)}}}},1472:e=>{e.exports="0.0.2"},243:(e,t,n)=>{"use strict";n.r(t),n.d(t,{updateTwoFaSettings:()=>l});var s=n(7150),a=n.n(s),i=n(9618),o=n(9674),r=n(7873),c=n.n(r),d=n(8764).Buffer;async function l(e,{isCheckPassword:t,currentPassword:n,newPassword:s,hint:r="",email:l,emailCodeCallback:u,onEmailCodeError:g}){if(!s&&!n)throw new Error("Neither `currentPassword` nor `newPassword` is present");if(l&&(!u||!g))throw new Error("`email` present without `emailCodeCallback` and `onEmailCodeError`");const p=await e.invoke(new(a().account.GetPassword));p.newAlgo instanceof a().PasswordKdfAlgoUnknown||(p.newAlgo.salt1=d.concat([p.newAlgo.salt1,(0,i.generateRandomBytes)(32)])),!p.hasPassword&&n&&(n=void 0);const f=n?await(0,o.computeCheck)(p,n):new(a().InputCheckPasswordEmpty);if(t)await e.invoke(new(a().auth.CheckPassword)({password:f}));else try{await e.invoke(new(a().account.UpdatePasswordSettings)({password:f,newSettings:new(a().account.PasswordInputSettings)({newAlgo:p.newAlgo,newPasswordHash:s?await(0,o.computeDigest)(p.newAlgo,s):d.alloc(0),hint:r,email:l,newSecureSettings:void 0})}))}catch(t){if(!(t instanceof c().EmailUnconfirmedError))throw t;for(;;)try{const n=await u(t.codeLength);if(!n)throw new Error("Code is empty");await e.invoke(new(a().account.ConfirmPasswordEmail)({code:n}));break}catch(e){g(e)}}}},8742:(e,t,n)=>{var s=n(8764).Buffer;const a=n(7435),i=n(6748),{sleep:o}=n(9618),r=n(7873),c=n(3995),d=n(9618),l=n(8960),u=n(9270),{LAYER:g}=n(845),{constructors:p,requests:f}=n(7404),h=n(4046),{ConnectionTCPObfuscated:m}=n(2986),{authFlow:_,checkAuthorization:y}=n(1545),{downloadFile:b}=n(2288),{uploadFile:w}=n(4766),{updateTwoFaSettings:C}=n(243),I=131072,v=["w","y","d","x","c","m","b","a","s"];class P{constructor(e,t,n,s=P.DEFAULT_OPTIONS){if(!t||!n)throw Error('Your API ID or Hash are invalid. Please read "Requirements" on README.md');const o={...P.DEFAULT_OPTIONS,...s};if(this.apiId=t,this.apiHash=n,this._useIPV6=o.useIPV6,"string"==typeof o.baseLogger?this._log=new i:this._log=o.baseLogger,"string"!=typeof e&&e){if(!(e instanceof u))throw new Error("The given session must be str or a session instance")}else try{throw new Error("not implemented")}catch(t){e=new c}this.floodSleepLimit=o.floodSleepLimit,this._eventBuilders=[],this._phoneCodeHash={},this.session=e,this.apiId=parseInt(t,10),this.apiHash=n,this._requestRetries=o.requestRetries,this._connectionRetries=o.connectionRetries,this._retryDelay=o.retryDelay||0,o.proxy&&this._log.warn("proxies are not supported"),this._proxy=o.proxy,this._timeout=o.timeout,this._autoReconnect=o.autoReconnect,this._connection=o.connection,this._floodWaitedRequests={},this._initWith=e=>new f.InvokeWithLayer({layer:g,query:new f.InitConnection({apiId:this.apiId,deviceModel:o.deviceModel||a.type().toString()||"Unknown",systemVersion:o.systemVersion||a.release().toString()||"1.0",appVersion:o.appVersion||"1.0",langCode:o.langCode,langPack:"",systemLangCode:o.systemLangCode,query:e,proxy:void 0})}),this._args=o,this._config=void 0,this.phoneCodeHashes=[],this._exportedSenderPromises={},this._exportedSenderReleaseTimeouts={},this._additionalDcsDisabled=o.additionalDcsDisabled,this._loopStarted=!1,this._reconnecting=!1,this._destroyed=!1}async connect(){await this._initSession(),void 0===this._sender&&(this._sender=new h(this.session.getAuthKey(),{logger:this._log,dcId:this.session.dcId,retries:this._connectionRetries,delay:this._retryDelay,autoReconnect:this._autoReconnect,connectTimeout:this._timeout,authKeyCallback:this._authKeyCallback.bind(this),updateCallback:this._handleUpdate.bind(this),isMainSender:!0})),this._sender.userDisconnected=!1,this._sender._user_connected=!1,this._sender._reconnecting=!1,this._sender._disconnected=!0;const e=new this._connection(this.session.serverAddress,this.session.port,this.session.dcId,this._log,this._args.testServers);await this._sender.connect(e)?(this.session.setAuthKey(this._sender.authKey),await this._sender.send(this._initWith(new f.help.GetConfig({}))),this._loopStarted||(this._updateLoop(),this._loopStarted=!0),this._reconnecting=!1):this._loopStarted||(this._updateLoop(),this._loopStarted=!0)}async _initSession(){await this.session.load(),this.session.serverAddress&&this.session.serverAddress.includes(":")===this._useIPV6||this.session.setDC(2,this._useIPV6?"[2001:67c:4e8:f002::a]":"zws2.web.telegram.org",this._args.useWSS?443:80)}async _updateLoop(){for(;!this._destroyed;)if(await d.sleep(3e3),!this._reconnecting){try{await k((()=>{return e=this._sender.send(new f.PingDelayDisconnect({pingId:d.getRandomInt(Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER),disconnectDelay:6e4})),5e3,Promise.race([e,d.sleep(5e3).then((()=>Promise.reject(new Error("TIMEOUT"))))]);var e}),3,100)}catch(e){if(console.warn(e),this._reconnecting)continue;await this.disconnect(),await this.connect()}if((new Date).getTime()-this._lastRequest>18e5)try{await this.invoke(new f.updates.GetState)}catch(e){}}await this.disconnect()}async disconnect(){this._sender&&await this._sender.disconnect(),await Promise.all(Object.values(this._exportedSenderPromises).map((e=>e&&e.then((e=>{if(e)return e.disconnect()}))))),this._exportedSenderPromises={}}async destroy(){this._destroyed=!0;try{await this.disconnect()}catch(e){}this.session.delete(),this._eventBuilders=[]}async _switchDC(e){this._log.info(`Reconnecting to new data center ${e}`);const t=l.getDC(e);return this.session.setDC(e,t.ipAddress,t.port),await this._sender.authKey.setKey(void 0),this.session.setAuthKey(void 0),this._reconnecting=!0,await this.disconnect(),this.connect()}_authKeyCallback(e,t){this.session.setAuthKey(e,t)}async _cleanupExportedSender(e){this.session.dcId!==e&&this.session.setAuthKey(void 0,e);const t=await this._exportedSenderPromises[e];this._exportedSenderPromises[e]=void 0,await t.disconnect()}async _connectSender(e,t){const n=l.getDC(t,!!e.authKey.getKey());for(;;)try{if(await e.connect(new this._connection(n.ipAddress,n.port,t,this._log,this._args.testServers)),this.session.dcId!==t&&!e._authenticated){this._log.info(`Exporting authorization for data center ${n.ipAddress}`);const s=await this.invoke(new f.auth.ExportAuthorization({dcId:t})),a=this._initWith(new f.auth.ImportAuthorization({id:s.id,bytes:s.bytes}));await e.send(a),e._authenticated=!0}return e.dcId=t,e.userDisconnected=!1,e}catch(t){console.error(t),await d.sleep(1e3),await e.disconnect()}}async _borrowExportedSender(e,t,n){if(this._additionalDcsDisabled)return;let s;this._exportedSenderPromises[e]&&!t||(this._exportedSenderPromises[e]=this._connectSender(n||this._createExportedSender(e),e));try{if(s=await this._exportedSenderPromises[e],!s.isConnected())return s.isConnecting?(await d.sleep(1e3),this._borrowExportedSender(e,!1,s)):this._borrowExportedSender(e,!0,s)}catch(t){return console.error(t),this._borrowExportedSender(e,!0)}return this._exportedSenderReleaseTimeouts[e]&&(clearTimeout(this._exportedSenderReleaseTimeouts[e]),this._exportedSenderReleaseTimeouts[e]=void 0),this._exportedSenderReleaseTimeouts[e]=setTimeout((()=>{this._exportedSenderReleaseTimeouts[e]=void 0,s.disconnect()}),3e4),s}_createExportedSender(e){return new h(this.session.getAuthKey(e),{logger:this._log,dcId:e,retries:this._connectionRetries,delay:this._retryDelay,autoReconnect:this._autoReconnect,connectTimeout:this._timeout,authKeyCallback:this._authKeyCallback.bind(this),isMainSender:e===this.session.dcId,onConnectionBreak:this._cleanupExportedSender.bind(this)})}getSender(e){return e?this._borrowExportedSender(e):Promise.resolve(this._sender)}downloadFile(e,t={}){return b(this,e,t)}downloadMedia(e,t){let n;if(n=e instanceof p.Message?e.media:e,"string"==typeof n)throw new Error("not implemented");return n instanceof p.MessageMediaWebPage&&n.webpage instanceof p.WebPage&&(n=n.webpage.document||n.webpage.photo),n instanceof p.MessageMediaPhoto||n instanceof p.Photo?this._downloadPhoto(n,t):n instanceof p.MessageMediaDocument||n instanceof p.Document?this._downloadDocument(n,t):n instanceof p.MessageMediaContact?this._downloadContact(n,t):n instanceof p.WebDocument||n instanceof p.WebDocumentNoProxy?this._downloadWebDocument(n,t):void 0}downloadProfilePhoto(e,t=!1){const n=t?"x":"m";let s,a,i;if([765557111,3316604308,524706233,3566872215].includes(e.SUBCLASS_OF_ID)){if(!e.photo){if(!e.chatPhoto)return;return this._downloadPhoto(e.chatPhoto,{sizeType:n})}s=e.photo}else s=e;if(s instanceof p.UserProfilePhoto||s instanceof p.ChatPhoto)return a=s.dcId,i=new p.InputPeerPhotoFileLocation({peer:l.getInputPeer(e),photoId:s.photoId,big:t}),this.downloadFile(i,{dcId:a})}downloadStickerSetThumb(e){if(!e.thumbs||!e.thumbs.length)return;const{thumbVersion:t}=e;return this.downloadFile(new p.InputStickerSetThumb({stickerset:new p.InputStickerSetID({id:e.id,accessHash:e.accessHash}),thumbVersion:t}),{dcId:e.thumbDcId})}_pickFileSize(e,t){if(!t||!e||!e.length)return;let n;for(let s=v.indexOf(t);se.type===v[s])),n)return n}_downloadCachedPhotoSize(e){let t;return t=e instanceof p.PhotoStrippedSize?l.strippedPhotoToJpg(e.bytes):e.bytes,t}_downloadPhoto(e,t){if(e instanceof p.MessageMediaPhoto&&(e=e.photo),!(e instanceof p.Photo))return;const n=this._pickFileSize(e.sizes,t.sizeType);return!n||n instanceof p.PhotoSizeEmpty?void 0:n instanceof p.PhotoCachedSize||n instanceof p.PhotoStrippedSize?this._downloadCachedPhotoSize(n):this.downloadFile(new p.InputPhotoFileLocation({id:e.id,accessHash:e.accessHash,fileReference:e.fileReference,thumbSize:n.type}),{dcId:e.dcId,fileSize:n.size,progressCallback:t.progressCallback})}_downloadDocument(e,t){if(e instanceof p.MessageMediaDocument&&(e=e.document),!(e instanceof p.Document))return;let n;if(t.sizeType){if(n=e.thumbs?this._pickFileSize(e.thumbs,t.sizeType):void 0,!n&&e.mimeType.startsWith("video/"))return;if(n&&(n instanceof p.PhotoCachedSize||n instanceof p.PhotoStrippedSize))return this._downloadCachedPhotoSize(n)}return this.downloadFile(new p.InputDocumentFileLocation({id:e.id,accessHash:e.accessHash,fileReference:e.fileReference,thumbSize:n?n.type:""}),{fileSize:n?n.size:e.size,progressCallback:t.progressCallback,start:t.start,end:t.end,dcId:e.dcId,workers:t.workers})}_downloadContact(e,t){throw new Error("not implemented")}async _downloadWebDocument(e){try{const t=[];let n=0;for(;;){const s=new f.upload.GetWebFile({location:new p.InputWebFileLocation({url:e.url,accessHash:e.accessHash}),offset:n,limit:I}),a=await this._borrowExportedSender(4),i=await a.send(s);if(n+=131072,!i.bytes.length)break;if(t.push(i.bytes),i.bytes.length{"use strict";n.r(t),n.d(t,{authFlow:()=>l,checkAuthorization:()=>u});var s=n(7150),a=n.n(s),i=n(8960),o=n.n(i),r=n(9618),c=n(9674);const d="phoneNumber";async function l(e,t,n){let s;if("botAuthToken"in n)s=await async function(e,t,n){const{apiId:s,apiHash:i}=t,{botAuthToken:o}=n,{user:r}=await e.invoke(new(a().auth.ImportBotAuthorization)({apiId:s,apiHash:i,botAuthToken:o}));return r}(e,t,n);else{const{initialMethod:a=d}=n;s="phoneNumber"===a?await g(e,t,n):await p(e,t,n)}e._log.info("Signed in successfully as",o().getDisplayName(s))}async function u(e){try{return await e.invoke(new(a().updates.GetState)),!0}catch(e){if("Disconnect"===e.message)throw e;return!1}}async function g(e,t,n){let s,i,o,r=!1;for(;;)try{if("function"==typeof n.phoneNumber)try{s=await n.phoneNumber()}catch(s){if("RESTART_AUTH_WITH_QR"===s.message)return p(e,t,n);throw s}else s=n.phoneNumber;const a=await f(e,t,s,n.forceSMS);if(i=a.phoneCodeHash,r=a.isCodeViaApp,"string"!=typeof i)throw new Error("Failed to retrieve phone code hash");break}catch(e){if("function"!=typeof n.phoneNumber)throw e;n.onError(e)}let c,d=!1;for(;;)try{try{o=await n.phoneCode(r)}catch(s){if("RESTART_AUTH"===s.message)return g(e,t,n)}if(!o)throw new Error("Code is empty");const l=await e.invoke(new(a().auth.SignIn)({phoneNumber:s,phoneCodeHash:i,phoneCode:o}));if(l instanceof a().auth.AuthorizationSignUpRequired){d=!0,c=l.termsOfService;break}return l.user}catch(t){if("SESSION_PASSWORD_NEEDED"===t.message)return h(e,0,n);n.onError(t)}if(d)for(;;)try{const[t,o]=await n.firstAndLastNames();if(!t)throw new Error("First name is required");const{user:r}=await e.invoke(new(a().auth.SignUp)({phoneNumber:s,phoneCodeHash:i,firstName:t,lastName:o}));return c&&await e.invoke(new(a().help.AcceptTermsOfService)({id:c.id})),r}catch(e){n.onError(e)}return n.onError(new Error("Auth failed")),g(e,t,n)}async function p(e,t,n){let s=!1;const i=(async()=>{for(;!s;){const t=await e.invoke(new(a().auth.ExportLoginToken)({apiId:Number("2496"),apiHash:"8da85b0d5bfe62527e5b244c209159c3",exceptIds:[]}));if(!(t instanceof a().auth.LoginToken))throw new Error("Unexpected");const{token:s,expires:i}=t;await Promise.race([n.qrCode({token:s,expires:i}),(0,r.sleep)(3e4)])}})(),o=new Promise((t=>{e.addEventHandler((e=>{e instanceof a().UpdateLoginToken&&t()}),{build:e=>e})}));try{await Promise.race([o,i])}catch(s){if("RESTART_AUTH"===s.message)return await g(e,t,n);throw s}finally{s=!0}try{const t=await e.invoke(new(a().auth.ExportLoginToken)({apiId:Number("2496"),apiHash:"8da85b0d5bfe62527e5b244c209159c3",exceptIds:[]}));if(t instanceof a().auth.LoginTokenSuccess&&t.authorization instanceof a().auth.Authorization)return t.authorization.user;if(t instanceof a().auth.LoginTokenMigrateTo){await e._switchDC(t.dcId);const n=await e.invoke(new(a().auth.ImportLoginToken)({token:t.token}));if(n instanceof a().auth.LoginTokenSuccess&&n.authorization instanceof a().auth.Authorization)return n.authorization.user}}catch(t){if("SESSION_PASSWORD_NEEDED"===t.message)return h(e,0,n);throw t}throw void 0}async function f(e,t,n,s=!1){try{const{apiId:i,apiHash:o}=t,r=await e.invoke(new(a().auth.SendCode)({phoneNumber:n,apiId:i,apiHash:o,settings:new(a().CodeSettings)}));if(!s||r.type instanceof a().auth.SentCodeTypeSms)return{phoneCodeHash:r.phoneCodeHash,isCodeViaApp:r.type instanceof a().auth.SentCodeTypeApp};const c=await e.invoke(new(a().auth.ResendCode)({phoneNumber:n,phoneCodeHash:r.phoneCodeHash}));return{phoneCodeHash:c.phoneCodeHash,isCodeViaApp:c.type instanceof a().auth.SentCodeTypeApp}}catch(a){if("AUTH_RESTART"===a.message)return f(e,t,n,s);throw a}}async function h(e,t,n){for(;;)try{const t=await e.invoke(new(a().account.GetPassword)),s=await n.password(t.hint);if(!s)throw new Error("Password is empty");const i=await(0,c.computeCheck)(t,s),{user:o}=await e.invoke(new(a().auth.CheckPassword)({password:i}));return o}catch(e){n.onError(e)}}},2288:(e,t,n)=>{"use strict";n.r(t),n.d(t,{downloadFile:()=>p});var s=n(7150),a=n.n(s),i=n(8960),o=n(9618),r=n(7873),c=n.n(r),d=n(8764).Buffer;function l(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const u=1048576;class g{constructor(e){this.maxWorkers=e,l(this,"deferred",void 0),l(this,"activeWorkers",0)}requestWorker(){return this.activeWorkers++,this.activeWorkers>this.maxWorkers?(this.deferred=(0,o.createDeferred)(),this.deferred.promise):Promise.resolve()}releaseWorker(){this.activeWorkers--,this.deferred&&this.activeWorkers<=this.maxWorkers&&this.deferred.resolve()}}async function p(e,t,n){let{partSizeKb:s,end:r}=n;const{fileSize:l,workers:p=1}=n,{dcId:f,progressCallback:h,start:m=0}=n;r=r&&r{for(;;){let d;try{d=await e.getSender(f);const o=await d.send(new(a().upload.GetFile)({location:t,offset:i,limit:n,precise:s||void 0}));if(h){if(h.isCanceled)throw new Error("USER_CANCELED");v+=1/y,h(v)}return!r&&o.bytes.lengthr)break}const P=(await Promise.all(w)).filter(Boolean),S=r?r+1-m:void 0;return d.concat(P,S)}},4766:(e,t,n)=>{"use strict";n.r(t),n.d(t,{uploadFile:()=>l});var s=n(7150),a=n.n(s),i=n(9618),o=n(8960),r=n(7873),c=n.n(r),d=n(8764).Buffer;async function l(e,t){const{file:n,onProgress:s}=t;let{workers:r}=t;const{name:l,size:u}=n,g=(0,i.readBigIntFromBuffer)((0,i.generateRandomBytes)(8),!0,!0),p=u>10485760,f=1024*(0,o.getAppropriatedPartSize)(u),h=Math.floor((u+f-1)/f),m=d.from(await function(e){return new Response(e).arrayBuffer()}(n));await e.getSender(e.session.dcId),r&&u||(r=1),r>=h&&(r=h);let _=0;s&&s(_);for(let t=0;th&&(o=h);for(let r=t;r{for(;;){let o;try{o=await e.getSender(e.session.dcId),await o.send(p?new(a().upload.SaveBigFilePart)({fileId:g,filePart:t,fileTotalParts:h,bytes:n}):new(a().upload.SaveFilePart)({fileId:g,filePart:t,bytes:n}))}catch(e){if(o&&!o.isConnected()){await(0,i.sleep)(1e3);continue}if(e instanceof c().FloodWaitError){await(0,i.sleep)(1e3*e.seconds);continue}throw e}if(s){if(s.isCanceled)throw new Error("USER_CANCELED");_+=1/h,s(_)}break}})(r,t))}await Promise.all(n)}return p?new(a().InputFileBig)({id:g,parts:h,name:l}):new(a().InputFile)({id:g,parts:h,name:l,md5Checksum:""})}},3302:(e,t,n)=>{var s=n(8764).Buffer;const{sha1:a,toSignedLittleBuffer:i,readBufferFromBigInt:o,readBigIntFromBuffer:r}=n(9618),c=n(5544),{sleep:d}=n(9618);class l{constructor(e,t){if(!t||!e)return;this._key=e,this._hash=t;const n=new c(t);this.auxHash=n.readLong(!1),n.read(4),this.keyId=n.readLong(!1)}async setKey(e){if(!e)return this._key=void 0,this.auxHash=void 0,this.keyId=void 0,void(this._hash=void 0);if(e instanceof l)return this._key=e._key,this.auxHash=e.auxHash,this.keyId=e.keyId,void(this._hash=e._hash);this._key=e,this._hash=await a(this._key);const t=new c(this._hash);this.auxHash=t.readLong(!1),t.read(4),this.keyId=t.readLong(!1)}async waitForKey(){for(;!this.keyId;)await d(20)}getKey(){return this._key}async calcNewNonceHash(e,t){e=i(e,32);const n=s.alloc(1);n.writeUInt8(t,0);const c=s.concat([e,s.concat([n,o(this.auxHash,8,!0)])]),d=(await a(c)).slice(4,20);return r(d,!0,!0)}equals(e){return e instanceof this.constructor&&this._key&&e.getKey()&&e.getKey().equals(this._key)}}e.exports=l},5830:(e,t,n)=>{var s=n(8764).Buffer;const a=n(6842);e.exports=class{constructor(e,t){if(!s.isBuffer(e)||!s.isBuffer(t)||16!==t.length)throw new Error("Key and iv need to be a buffer");this.cipher=a.createCipheriv("AES-256-CTR",e,t)}encrypt(e){return s.from(this.cipher.update(e))}}},9636:(e,t,n)=>{const s=n(4736),{modExp:a}=n(9618);class i{static gcd(e,t){for(;t.neq(s.zero);){const n=t;t=e.remainder(t),e=n}return e}static factorize(e){if(e.remainder(2).equals(s.zero))return{p:s(2),q:e.divide(s(2))};let t=s.randBetween(s(1),e.minus(1));const n=s.randBetween(s(1),e.minus(1)),o=s.randBetween(s(1),e.minus(1));let r,c=s.one,d=s.one,l=s.one,u=s.zero,g=s.zero;for(;c.eq(s.one);){u=t;for(let i=0;s(i).lesser(d);i++)t=a(t,s(2),e).add(n).remainder(e);for(r=s.zero;r.lesser(d)&&c.eq(s.one);){g=t;const p=s.min(o,d.minus(r));for(let i=0;s(i).lesser(p);i++)t=a(t,s(2),e).add(n).remainder(e),l=l.multiply(u.minus(t).abs()).remainder(e);c=i.gcd(l,e),r=r.add(o)}d=d.multiply(2)}if(c.eq(e))for(;g=a(g,s(2),e).add(n).remainder(e),c=i.gcd(u.minus(g).abs(),e),!c.greater(1););const p=c;return l=e.divide(c),p{var s=n(8764).Buffer;const{IGE:a}=n(8136),i=n(9618);e.exports=class{constructor(e,t){this.ige=new a(e,t)}decryptIge(e){return i.convertToLittle(this.ige.decrypt(e))}encryptIge(e){const t=e.length%16;return t&&(e=s.concat([e,i.generateRandomBytes(16-t)])),i.convertToLittle(this.ige.encrypt(e))}}},4121:(e,t,n)=>{"use strict";function s(e){const t=new Uint8Array(4*e.length);let n=0;for(let s=0;s>>24,t[n++]=a>>16&255,t[n++]=a>>8&255,t[n++]=255&a}return t.buffer}function a(e){return e.buffer}function i(e){const t=new Uint8Array(e),n=new Uint32Array(t.length/4);for(let e=0;es,i2abBig:()=>a,ab2iLow:()=>i,ab2iBig:()=>o,isBigEndian:()=>r,i2ab:()=>c,ab2i:()=>d});const r=1===new Uint8Array(new Uint32Array([16909060]))[0],c=r?a:s,d=r?o:i},6842:(e,t,n)=>{var s=n(8764).Buffer;const a=n(8136).default,{i2ab:i,ab2i:o}=n(4121),{getWords:r}=n(7760);class c{constructor(e){this.setBytes(e)}setBytes(e){e=s.from(e),this._counter=e}increment(){for(let e=15;e>=0;e--){if(255!==this._counter[e]){this._counter[e]++;break}this._counter[e]=0}}}class d{constructor(e,t){t instanceof c||(t=new c(t)),this._counter=t,this._remainingCounter=void 0,this._remainingCounterIndex=16,this._aes=new a(r(e))}update(e){return this.encrypt(e)}encrypt(e){const t=s.from(e);for(let e=0;e{"use strict";function s(e,t){return e.charCodeAt(t)<<24^e.charCodeAt(t+1)<<16^e.charCodeAt(t+2)<<8^e.charCodeAt(t+3)}function a(e){if(e instanceof Uint32Array)return e;if("string"==typeof e){if(e.length%4!=0)for(let t=e.length%4;t<=4;t++)e+="\0x00";const t=new Uint32Array(e.length/4);for(let n=0;ns,getWords:()=>a,xor:()=>i})},8187:e=>{class t extends Error{constructor(){super("The read operation was cancelled.")}}class n extends Error{constructor(e,t){super(`Could not find a matching Constructor ID for the TLObject that was supposed to be\n read with ID ${e}. Most likely, a TLObject was trying to be read when\n it should not be read. Remaining bytes: ${t.length}`),"undefined"!=typeof alert&&alert(`Missing MTProto Entity: Please, make sure to add TL definition for ID ${e}`),this.invalidConstructorId=e,this.remaining=t}}class s extends Error{constructor(e,t){super(`Invalid checksum (${e} when ${t} was expected). This packet should be skipped.`),this.checksum=e,this.validChecksum=t}}class a extends Error{constructor(e){let t;4===e.length?(t=-e.readInt32LE(0),super(`Invalid response buffer (HTTP code ${t})`)):super(`Invalid response buffer (too short ${e})`),this.code=t,this.payload=e}}class i extends Error{constructor(...e){e.length||(e=["A security check failed."]),super(...e)}}class o extends Error{constructor(e,t){let n=o.ErrorMessages[t]||`Unknown error code (this should not happen): ${t}.`;n+=` Caused by ${e.className}`,super(n),this.message=n,this.code=t}}var r,c,d;d={16:"msg_id too low (most likely, client time is wrong it would be worthwhile to synchronize it using msg_id notifications and re-send the original message with the “correct” msg_id or wrap it in a container with a new msg_id if the original message had waited too long on the client to be transmitted).",17:"msg_id too high (similar to the previous case, the client time has to be synchronized, and the message re-sent with the correct msg_id).",18:"Incorrect two lower order msg_id bits (the server expects client message msg_id to be divisible by 4).",19:"Container msg_id is the same as msg_id of a previously received message (this must never happen).",20:"Message too old, and it cannot be verified whether the server has received a message with this msg_id or not.",32:"msg_seqno too low (the server has already received a message with a lower msg_id but with either a higher or an equal and odd seqno).",33:"msg_seqno too high (similarly, there is a message with a higher msg_id but with either a lower or an equal and odd seqno).",34:"An even msg_seqno expected (irrelevant message), but odd received.",35:"Odd msg_seqno expected (relevant message), but even received.",48:"Incorrect server salt (in this case, the bad_server_salt response is received with the correct salt, and the message is to be re-sent with it).",64:"Invalid container."},(c="ErrorMessages")in(r=o)?Object.defineProperty(r,c,{value:d,enumerable:!0,configurable:!0,writable:!0}):r[c]=d,e.exports={ReadCancelledError:t,TypeNotFoundError:n,InvalidChecksumError:s,InvalidBufferError:a,SecurityError:i,CdnFileTamperedError:class extends i{constructor(){super("The CDN file has been altered and its download cancelled.")}},BadMessageError:o}},6952:e=>{function t(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class n extends Error{constructor(e,t,s){super("RPCError {0}: {1}{2}".replace("{0}",s).replace("{1}",e).replace("{2}",n._fmtRequest(t))),this.code=s,this.message=e}static _fmtRequest(e){return e?` (caused by ${e.className})`:""}}e.exports={RPCError:n,InvalidDCError:class extends n{constructor(e,t,n){super(t,e,n),this.code=n||303,this.message=t||"ERROR_SEE_OTHER"}},BadRequestError:class extends n{constructor(...e){super(...e),t(this,"code",400),t(this,"message","BAD_REQUEST")}},UnauthorizedError:class extends n{constructor(...e){super(...e),t(this,"code",401),t(this,"message","UNAUTHORIZED")}},ForbiddenError:class extends n{constructor(...e){super(...e),t(this,"code",403),t(this,"message","FORBIDDEN")}},NotFoundError:class extends n{constructor(...e){super(...e),t(this,"code",404),t(this,"message","NOT_FOUND")}},AuthKeyError:class extends n{constructor(...e){super(...e),t(this,"code",406),t(this,"message","AUTH_KEY")}},FloodError:class extends n{constructor(...e){super(...e),t(this,"code",420),t(this,"message","FLOOD")}},ServerError:class extends n{constructor(...e){super(...e),t(this,"code",500),t(this,"message","INTERNAL")}},TimedOutError:class extends n{constructor(...e){super(...e),t(this,"code",503),t(this,"message","Timeout")}}}},5651:(e,t,n)=>{const{RPCError:s,InvalidDCError:a,FloodError:i,BadRequestError:o}=n(6952);class r extends a{constructor(e){const t=Number(e.capture||0);super(`The user whose identity is being used to execute queries is associated with DC ${t}${s._fmtRequest(e.request)}`),this.message=`The user whose identity is being used to execute queries is associated with DC ${t}${s._fmtRequest(e.request)}`,this.newDc=t}}class c extends a{constructor(e){const t=Number(e.capture||0);super(`The phone number a user is trying to use for authorization is associated with DC ${t}${s._fmtRequest(e.request)}`),this.message=`The phone number a user is trying to use for authorization is associated with DC ${t}${s._fmtRequest(e.request)}`,this.newDc=t}}class d extends i{constructor(e){const t=Number(e.capture||0);super(`A wait of ${t} seconds is required before sending another message in this chat${s._fmtRequest(e.request)}`),this.message=`A wait of ${t} seconds is required before sending another message in this chat${s._fmtRequest(e.request)}`,this.seconds=t}}class l extends i{constructor(e){const t=Number(e.capture||0);super(`A wait of ${t} seconds is required${s._fmtRequest(e.request)}`),this.message=`A wait of ${t} seconds is required${s._fmtRequest(e.request)}`,this.seconds=t}}class u extends i{constructor(e){super(`Message failed to be sent.${s._fmtRequest(e.request)}`),this.message=`Message failed to be sent.${s._fmtRequest(e.request)}`}}class g extends i{constructor(e){const t=Number(e.capture||0);super(`A wait of ${t} seconds is required in the test servers${s._fmtRequest(e.request)}`),this.message=`A wait of ${t} seconds is required in the test servers${s._fmtRequest(e.request)}`,this.seconds=t}}class p extends a{constructor(e){const t=Number(e.capture||0);super(`The file to be accessed is currently stored in DC ${t}${s._fmtRequest(e.request)}`),this.message=`The file to be accessed is currently stored in DC ${t}${s._fmtRequest(e.request)}`,this.newDc=t}}class f extends a{constructor(e){const t=Number(e.capture||0);super(`The source IP address is associated with DC ${t}${s._fmtRequest(e.request)}`),this.message=`The source IP address is associated with DC ${t}${s._fmtRequest(e.request)}`,this.newDc=t}}class h extends o{constructor(e){const t=Number(e.capture||0);super(`Email unconfirmed, the length of the code must be ${t}${s._fmtRequest(e.request)}`),this.message=`Email unconfirmed, the length of the code must be ${t}${s._fmtRequest(e.request)}`,this.codeLength=t}}const m=[[/FILE_MIGRATE_(\d+)/,p],[/FLOOD_TEST_PHONE_WAIT_(\d+)/,g],[/FLOOD_WAIT_(\d+)/,l],[/MSG_WAIT_(.*)/,u],[/PHONE_MIGRATE_(\d+)/,c],[/SLOWMODE_WAIT_(\d+)/,d],[/USER_MIGRATE_(\d+)/,r],[/NETWORK_MIGRATE_(\d+)/,f],[/EMAIL_UNCONFIRMED_(\d+)/,h]];e.exports={rpcErrorRe:m,FileMigrateError:p,FloodTestPhoneWaitError:g,FloodWaitError:l,PhoneMigrateError:c,SlowModeWaitError:d,UserMigrateError:r,NetworkMigrateError:f,MsgWaitError:u,EmailUnconfirmedError:h}},7873:(e,t,n)=>{const{RPCError:s}=n(6952),{rpcErrorRe:a}=n(5651),i=n(8187),o=n(6952),r=n(5651);e.exports={RPCMessageToError:function(e,t){for(const[n,s]of a){const a=e.errorMessage.match(n);if(a)return new s({request:t,capture:2===a.length?parseInt(a[1],10):void 0})}return new s(e.errorMessage,t)},...i,...o,...r}},6316:()=>{},3903:(e,t,n)=>{const{EventBuilder:s}=n(6172);e.exports=class extends s{constructor(e={types:void 0,func:void 0}){super(),e.types?this.types=e.types:this.types=!0}build(e){return e}}},6172:e=>{e.exports={EventBuilder:class{constructor(e={chats:void 0,blacklistChats:void 0,func:void 0}){this.chats=e.chats,this.blacklistChats=Boolean(e.blacklistChats),this.resolved=!1,this.func=e.func}build(e){}}}},3182:(e,t,n)=>{const s=n(6316),a=n(3903);class i extends Error{}e.exports={NewMessage:s,StopPropagation:i,Raw:a}},6151:e=>{e.exports=class{constructor(){this._queue=[],this.canGet=new Promise((e=>{this.resolveGet=e})),this.canPush=!0}async push(e){await this.canPush,this._queue.push(e),this.resolveGet(!0),this.canPush=new Promise((e=>{this.resolvePush=e}))}async pop(){await this.canGet;const e=this._queue.pop();return this.resolvePush(!0),this.canGet=new Promise((e=>{this.resolveGet=e})),e}}},5544:(e,t,n)=>{const{TypeNotFoundError:s}=n(8187),{coreObjects:a}=n(2058),{tlobjects:i}=n(845),{readBigIntFromBuffer:o}=n(9618);e.exports=class{constructor(e){this.stream=e,this._last=void 0,this.offset=0}readByte(){return this.read(1)[0]}readInt(e=!0){let t;return t=e?this.stream.readInt32LE(this.offset):this.stream.readUInt32LE(this.offset),this.offset+=4,t}readLong(e=!0){return this.readLargeInt(64,e)}readFloat(){return this.read(4).readFloatLE(0)}readDouble(){return this.read(8).readDoubleLE(0)}readLargeInt(e,t=!0){const n=this.read(Math.floor(e/8));return o(n,!0,t)}read(e=-1){-1===e&&(e=this.stream.length-this.offset);const t=this.stream.slice(this.offset,this.offset+e);if(this.offset+=e,t.length!==e)throw Error(`No more data left to read (need ${e}, got ${t.length}: ${t}); last read ${this._last}`);return this._last=t,t}getBuffer(){return this.stream}tgReadBytes(){const e=this.readByte();let t,n;254===e?(n=this.readByte()|this.readByte()<<8|this.readByte()<<16,t=n%4):(n=e,t=(n+1)%4);const s=this.read(n);return t>0&&(t=4-t,this.read(t)),s}tgReadString(){return this.tgReadBytes().toString("utf-8")}tgReadBool(){const e=this.readInt(!1);if(2574415285===e)return!0;if(3162085175===e)return!1;throw new Error(`Invalid boolean code ${e.toString("16")}`)}tgReadDate(){const e=this.readInt();return new Date(1e3*e)}tgReadObject(){const e=this.readInt(!1);let t=i[e];if(void 0===t){if(2574415285===e)return!0;if(3162085175===e)return!1;if(481674261===e){const e=[],t=this.readInt();for(let n=0;n{var s=n(8764).Buffer;e.exports=class{constructor(e){this._stream=e}write(e){this._stream=s.concat([this._stream,e])}getValue(){return this._stream}}},6748:e=>{let t;class n{constructor(e){t||(t=e||"debug"),this.isBrowser="undefined"==typeof process||"renderer"===process.type||!0===process.browser||process.__nwjs,this.isBrowser?this.colors={start:"%c",warn:"color : #ff00ff",info:"color : #ffff00",debug:"color : #00ffff",error:"color : #ff0000",end:""}:this.colors={start:"",warn:"",info:"",debug:"",error:"",end:""},this.messageFormat="[%t] [%l] - [%m]"}static setLevel(e){t=e}canSend(e){return n.levels.indexOf(t)>=n.levels.indexOf(e)}warn(e){"debug"===t&&console.error((new Error).stack),this._log("warn",e,this.colors.warn)}info(e){this._log("info",e,this.colors.info)}debug(e){this._log("debug",e,this.colors.debug)}error(e){"debug"===t&&console.error((new Error).stack),this._log("error",e,this.colors.error)}format(e,t){return this.messageFormat.replace("%t",(new Date).toISOString()).replace("%l",t.toUpperCase()).replace("%m",e)}_log(e,n,s){t&&this.canSend(e)&&(this.isBrowser?console.log(this.colors.start+this.format(n,e),s):console.log(s+this.format(n,e)+this.colors.end))}}var s,a,i;i=["error","warn","info","debug"],(a="levels")in(s=n)?Object.defineProperty(s,a,{value:i,enumerable:!0,configurable:!0,writable:!0}):s[a]=i,e.exports=n},6411:(e,t,n)=>{var s=n(8764).Buffer;const a=n(3254),i=n(355),o=n(6472),r=["messages.SendMessage","messages.SendMedia","messages.SendMultiMedia","messages.ForwardMessages","messages.SendInlineBotResult"];e.exports=class{constructor(e,t){this._state=e,this._queue=[],this._pendingStates=[],this._ready=new Promise((e=>{this.setReady=e})),this._log=t}values(){return this._queue}append(e){if(e&&r.includes(e.request.className))for(let t=this._queue.length-1;t>=0;t--)if(r.includes(this._queue[t].request.className)){e.after=this._queue[t];break}this._queue.push(e),this.setReady(!0),e&&1658238041!==e.request.CONSTRUCTOR_ID&&(this._pendingStates.push(e),e.promise.catch((()=>{})).finally((()=>{this._pendingStates=this._pendingStates.filter((t=>t!==e))})))}extend(e){for(const t of e)this._queue.push(t);this.setReady(!0)}async get(){if(this._queue.length||(this._ready=new Promise((e=>{this.setReady=e})),await this._ready),!this._queue[this._queue.length-1])return void(this._queue=[]);let e,t=new o(s.alloc(0));const n=[];let r=0;for(;this._queue.length&&n.length<=a.MAXIMUM_LENGTH;){const e=this._queue.shift();if(r+=e.data.length+i.SIZE_OVERHEAD,r<=a.MAXIMUM_SIZE){let s;e.after&&(s=e.after.msgId),e.msgId=await this._state.writeDataAsMessage(t,e.data,"request"===e.request.classType,s),this._log.debug(`Assigned msgId = ${e.msgId} to ${e.request.className||e.request.constructor.name}`),n.push(e)}else{if(n.length){this._queue.unshift(e);break}this._log.warn(`Message payload for ${e.request.className||e.request.constructor.name} is too long ${e.data.length} and cannot be sent`),e.reject("Request Payload is too big"),r=0}}if(n.length){if(n.length>1){const i=s.alloc(8);i.writeUInt32LE(a.CONSTRUCTOR_ID,0),i.writeInt32LE(n.length,4),e=s.concat([i,t.getValue()]),t=new o(s.alloc(0));const r=await this._state.writeDataAsMessage(t,e,!1);for(const e of n)e.containerId=r}return e=t.getValue(),{batch:n,data:e}}}rejectAll(){this._pendingStates.forEach((e=>{e.reject(new Error("Disconnect"))}))}}},7214:(e,t,n)=>{var s=n(8764).Buffer;const{Mutex:a}=n(8125),i=new a,o=n(5840).w3cwebsocket,r=new Error("WebSocket was closed");e.exports=class{constructor(e){this.client=void 0,this.closed=!0,this.disconnectedCallback=e}async readExactly(e){let t=s.alloc(0);for(;;){const n=await this.read(e);if(t=s.concat([t,n]),!(e-=n.length))return t}}async read(e){if(this.closed)throw r;if(await this.canRead,this.closed)throw r;const t=this.stream.slice(0,e);return this.stream=this.stream.slice(e),0===this.stream.length&&(this.canRead=new Promise((e=>{this.resolveRead=e}))),t}async readAll(){if(this.closed||!await this.canRead)throw r;const e=this.stream;return this.stream=s.alloc(0),this.canRead=new Promise((e=>{this.resolveRead=e})),e}getWebSocketLink(e,t,n){return 443===t?`wss://${e}:${t}/apiws${n?"_test":""}`:`ws://${e}:${t}/apiws${n?"_test":""}`}connect(e,t,n=!1){return this.stream=s.alloc(0),this.canRead=new Promise((e=>{this.resolveRead=e})),this.closed=!1,this.website=this.getWebSocketLink(t,e,n),this.client=new o(this.website,"binary"),new Promise(((e,n)=>{this.client.onopen=()=>{this.receive(),e(this)},this.client.onerror=e=>{console.error("WebSocket error",e),n(e)},this.client.onclose=e=>{const{code:n,reason:s,wasClean:a}=e;1e3!==n&&console.error(`Socket ${t} closed. Code: ${n}, reason: ${s}, was clean: ${a}`),this.resolveRead(!1),this.closed=!0,this.disconnectedCallback&&this.disconnectedCallback()},self.addEventListener("offline",(async()=>{await this.close(),this.resolveRead(!1)}))}))}write(e){if(this.closed)throw r;this.client.send(e)}async close(){await this.client.close(),this.closed=!0}receive(){this.client.onmessage=async e=>{await i.runExclusive((async()=>{const t=e.data instanceof ArrayBuffer?s.from(e.data):s.from(await new Response(e.data).arrayBuffer());this.stream=s.concat([this.stream,t]),this.resolveRead(!0)}))}}}},9832:(e,t,n)=>{const s=n(6748),a=n(6472),i=n(5544),o=n(7214),r=n(6411),c=n(6151);e.exports={BinaryWriter:a,BinaryReader:i,MessagePacker:r,AsyncQueue:c,Logger:s,PromisedWebSockets:o}},3522:(e,t,n)=>{const s=n(7150),a=n(8742),i=n(8415),o=n(7404),r=n(1472),c=n(3182),d=n(8960),l=n(7873),u=n(5886),g=n(9832),p=n(9618);e.exports={Api:s,TelegramClient:a,sessions:u,connection:i,extensions:g,tl:o,version:r,events:c,utils:d,errors:l,helpers:p}},9870:(e,t,n)=>{"use strict";n.r(t),n.d(t,{doAuthentication:()=>_});var s=n(7150),a=n.n(s),i=n(7873),o=n(4736),r=n.n(o);n(9618),n(8764).Buffer;const c=[{fingerprint:r()("-3414540481677951611"),n:r()("29379598170669337022986177149456128565388431120058863768162556424047512191330847455146576344487764408661701890505066208632169112269581063774293102577308490531282748465986139880977280302242772832972539403531316010870401287642763009136156734339538042419388722777357134487746169093539093850251243897188928735903389451772730245253062963384108812842079887538976360465290946139638691491496062099570836476454855996319192747663615955633778034897140982517446405334423701359108810182097749467210509584293428076654573384828809574217079944388301239431309115013843331317877374435868468779972014486325557807783825502498215169806323"),e:65537},{fingerprint:r()("-5595554452916591101"),n:r()("25342889448840415564971689590713473206898847759084779052582026594546022463853940585885215951168491965708222649399180603818074200620463776135424884632162512403163793083921641631564740959529419359595852941166848940585952337613333022396096584117954892216031229237302943701877588456738335398602461675225081791820393153757504952636234951323237820036543581047826906120927972487366805292115792231423684261262330394324750785450942589751755390156647751460719351439969059949569615302809050721500330239005077889855323917509948255722081644689442127297605422579707142646660768825302832201908302295573257427896031830742328565032949"),e:65537}],d=new Map;c.forEach((({fingerprint:e,...t})=>{d.set(e.toString(),t)}));var l=n(8764).Buffer;const u=n(4736),g=n(2608),p=n(3302),f=n(9636),h=n(9618),m=n(5544);async function _(e,t){let n=h.generateRandomBytes(16);const s=h.readBigIntFromBuffer(n,!1,!0),o=await e.send(new(a().ReqPqMulti)({nonce:s}));if(t.debug("Starting authKey generation step 1"),!(o instanceof a().ResPQ))throw new i.SecurityError(`Step 1 answer was ${o}`);if(o.nonce.neq(s))throw new i.SecurityError("Step 1 invalid nonce from server");const r=h.readBigIntFromBuffer(o.pq,!1,!0);t.debug("Finished authKey generation step 1");const{p:c,q:_}=f.factorize(r),y=h.getByteArray(c),b=h.getByteArray(_);n=h.generateRandomBytes(32);const w=h.readBigIntFromBuffer(n,!0,!0),C=new(a().PQInnerData)({pq:h.getByteArray(r),p:y,q:b,nonce:o.nonce,serverNonce:o.serverNonce,newNonce:w}).getBytes();if(C.length>144)throw new i.SecurityError("Step 1 invalid nonce from server");let I,v;for(const e of o.serverPublicKeyFingerprints)if(v=d.get(e.toString()),void 0!==v){I=e;break}if(void 0===I||void 0===v)throw new i.SecurityError("Step 2 could not find a valid key for fingerprints");const P=h.generateRandomBytes(192-C.length),S=l.concat([C,P]),A=l.from(S).reverse();let M;for(let e=0;e<20;e++){const e=h.generateRandomBytes(32),n=await h.sha256(l.concat([e,S])),s=l.concat([A,n]),a=new g(e,l.alloc(32)).encryptIge(s),i=h.bufferXor(e,await h.sha256(a)),o=l.concat([i,a]),r=h.readBigIntFromBuffer(o,!1,!1);if(r.greaterOrEquals(v.n)){t.debug("Aes key greater than RSA. retrying");continue}const c=h.modExp(r,u(v.e),v.n);M=h.readBufferFromBigInt(c,256,!1,!1);break}if(void 0===M)throw new i.SecurityError("Step 2 could create a secure encrypted key");t.debug("Step 2 : Generated a secure aes encrypted data");const k=await e.send(new(a().ReqDHParams)({nonce:o.nonce,serverNonce:o.serverNonce,p:y,q:b,publicKeyFingerprint:I,encryptedData:M}));if(!(k instanceof a().ServerDHParamsOk||k instanceof a().ServerDHParamsFail))throw new Error(`Step 2.1 answer was ${k}`);if(k.nonce.neq(o.nonce))throw new i.SecurityError("Step 2 invalid nonce from server");if(k.serverNonce.neq(o.serverNonce))throw new i.SecurityError("Step 2 invalid server nonce from server");if(k instanceof a().ServerDHParamsFail){const e=await h.sha1(h.toSignedLittleBuffer(w,32).slice(4,20)),t=h.readBigIntFromBuffer(e,!0,!0);if(k.newNonceHash.neq(t))throw new i.SecurityError("Step 2 invalid DH fail nonce from server")}if(!(k instanceof a().ServerDHParamsOk))throw new Error(`Step 2.2 answer was ${k}`);t.debug("Finished authKey generation step 2"),t.debug("Starting authKey generation step 3");const{key:R,iv:U}=await h.generateKeyDataFromNonce(o.serverNonce,w);if(k.encryptedAnswer.length%16!=0)throw new i.SecurityError("Step 3 AES block size mismatch");const E=new g(R,U),T=E.decryptIge(k.encryptedAnswer),D=new m(T);D.read(20);const B=D.tgReadObject();if(!(B instanceof a().ServerDHInnerData))throw new Error(`Step 3 answer was ${B}`);if(B.nonce.neq(o.nonce))throw new i.SecurityError("Step 3 Invalid nonce in encrypted answer");if(B.serverNonce.neq(o.serverNonce))throw new i.SecurityError("Step 3 Invalid server nonce in encrypted answer");const x=h.readBigIntFromBuffer(B.dhPrime,!1,!1),V=h.readBigIntFromBuffer(B.gA,!1,!1),N=B.serverTime-Math.floor((new Date).getTime()/1e3),F=h.readBigIntFromBuffer(h.generateRandomBytes(256),!1,!1),O=h.modExp(u(B.g),F,x),L=h.modExp(V,F,x),q=new(a().ClientDHInnerData)({nonce:o.nonce,serverNonce:o.serverNonce,retryId:u.zero,gB:h.getByteArray(O,!1)}).getBytes(),H=l.concat([await h.sha1(q),q]),G=E.encryptIge(H),K=await e.send(new(a().SetClientDHParams)({nonce:o.nonce,serverNonce:o.serverNonce,encryptedData:G})),z=[a().DhGenOk,a().DhGenRetry,a().DhGenFail];if(!(K instanceof z[0]||K instanceof z[1]||K instanceof z[2]))throw new Error(`Step 3.1 answer was ${K}`);const{name:W}=K.constructor;if(K.nonce.neq(o.nonce))throw new i.SecurityError(`Step 3 invalid ${W} nonce from server`);if(K.serverNonce.neq(o.serverNonce))throw new i.SecurityError(`Step 3 invalid ${W} server nonce from server`);const j=new p;await j.setKey(h.getByteArray(L));const $=1+["DhGenOk","DhGenRetry","DhGenFail"].indexOf(K.className),J=await j.calcNewNonceHash(w,$);if(K[`newNonceHash${$}`].neq(J))throw new i.SecurityError("Step 3 invalid new nonce hash");if(!(K instanceof a().DhGenOk))throw new Error(`Step 3.2 answer was ${K}`);return t.debug("Finished authKey generation step 3"),{authKey:j,timeOffset:N}}},5585:(e,t,n)=>{var s=n(8764).Buffer;const a=n(4736),i=n(9109),o=n(5544),{InvalidBufferError:r}=n(8187),{toSignedLittleBuffer:c}=n(9618);e.exports=class{constructor(e,t){this._state=new i(e,t),this._connection=e}async send(e){let t=e.getBytes(),n=this._state._getNewMsgId();const i=c(n,8),d=s.alloc(4);d.writeInt32LE(t.length,0);const l=s.concat([s.concat([s.alloc(8),i,d]),t]);if(await this._connection.send(l),t=await this._connection.recv(),t.length<8)throw new r(t);const u=new o(t);if(u.readLong().neq(a(0)))throw new Error("Bad authKeyId");if(n=u.readLong(),n.eq(a(0)))throw new Error("Bad msgId");if(u.readInt()<=0)throw new Error("Bad length");return u.tgReadObject()}}},4046:(e,t,n)=>{const s=n(5585),a=n(9109),i=n(9618),o=n(3302),{doAuthentication:r}=n(9870),c=n(2301),d=n(3254),l=n(8963),u=n(4287),{MsgsAck:g,upload:p,MsgsStateInfo:f,Pong:h}=n(7404).constructors,m=n(6411),_=n(5544),{UpdateConnectionState:y,UpdateServerTimeOffset:b}=n(8415),{BadMessageError:w}=n(8187),{BadServerSalt:C,BadMsgNotification:I,MsgDetailedInfo:v,MsgNewDetailedInfo:P,NewSessionCreated:S,FutureSalts:A,MsgsStateReq:M,MsgResendReq:k,MsgsAllInfo:R}=n(7404).constructors,{SecurityError:U}=n(8187),{InvalidBufferError:E}=n(8187),{LogOut:T}=n(7404).requests.auth,{RPCMessageToError:D}=n(7873),{TypeNotFoundError:B}=n(8187);class x{constructor(e,t){const n={...x.DEFAULT_OPTIONS,...t};this._connection=void 0,this._log=n.logger,this._dcId=n.dcId,this._retries=n.retries,this._delay=n.delay,this._autoReconnect=n.autoReconnect,this._connectTimeout=n.connectTimeout,this._authKeyCallback=n.authKeyCallback,this._updateCallback=n.updateCallback,this._autoReconnectCallback=n.autoReconnectCallback,this._isMainSender=n.isMainSender,this._onConnectionBreak=n.onConnectionBreak,this.userDisconnected=!1,this._user_connected=!1,this._reconnecting=!1,this._disconnected=!0,this._send_loop_handle=void 0,this._recv_loop_handle=void 0,this.authKey=e||new o,this._state=new a(this.authKey,this._log),this._send_queue=new m(this._state,this._log),this._pending_state={},this._pending_ack=new Set,this._last_acks=[],this._handlers={[c.CONSTRUCTOR_ID]:this._handleRPCResult.bind(this),[d.CONSTRUCTOR_ID]:this._handleContainer.bind(this),[l.CONSTRUCTOR_ID]:this._handleGzipPacked.bind(this),[h.CONSTRUCTOR_ID]:this._handlePong.bind(this),[C.CONSTRUCTOR_ID]:this._handleBadServerSalt.bind(this),[I.CONSTRUCTOR_ID]:this._handleBadNotification.bind(this),[v.CONSTRUCTOR_ID]:this._handleDetailedInfo.bind(this),[P.CONSTRUCTOR_ID]:this._handleNewDetailedInfo.bind(this),[S.CONSTRUCTOR_ID]:this._handleNewSessionCreated.bind(this),[g.CONSTRUCTOR_ID]:this._handleAck.bind(this),[A.CONSTRUCTOR_ID]:this._handleFutureSalts.bind(this),[M.CONSTRUCTOR_ID]:this._handleStateForgotten.bind(this),[k.CONSTRUCTOR_ID]:this._handleStateForgotten.bind(this),[R.CONSTRUCTOR_ID]:this._handleMsgAll.bind(this)}}async connect(e,t){if(this._user_connected&&!t)return this._log.info("User is already connected!"),!1;this.isConnecting=!0,this._connection=e;for(let e=0;e=10&&this._last_acks.shift(),this._pending_ack.clear()}this._log.debug(`Waiting for messages to send...${this._reconnecting}`);const e=await this._send_queue.get();if(this._reconnecting)return;if(!e)continue;let{data:t}=e;const{batch:n}=e;this._log.debug(`Encrypting ${n.length} message(s) in ${t.length} bytes for sending`),t=await this._state.encryptMessageData(t);try{await this._connection.send(t)}catch(e){return this._log.error(e),void this._log.info("Connection closed while sending data")}for(const e of n)if(Array.isArray(e))for(const t of e)"request"===t.request.classType&&(this._pending_state[t.msgId]=t);else"request"===e.request.classType&&(this._pending_state[e.msgId]=e);this._log.debug("Encrypted messages put in a queue to be sent")}}async _recvLoop(){let e,t;for(;this._user_connected&&!this._reconnecting;){this._log.debug("Receiving items from the network...");try{e=await this._connection.recv()}catch(e){return void(this.userDisconnected||(this._log.error(e),this._log.warn("Connection closed while receiving data"),this.reconnect()))}try{t=await this._state.decryptMessageData(e)}catch(e){if(e instanceof B){this._log.info(`Type ${e.invalidConstructorId} not found, remaining data ${e.remaining}`);continue}if(e instanceof U){this._log.warn(`Security error while unpacking a received message: ${e}`);continue}return e instanceof E?void(404===e.code?(this._log.warn(`Broken authorization key for dc ${this._dcId}; resetting`),this._updateCallback&&this._isMainSender?this._updateCallback(new y(y.broken)):this._onConnectionBreak&&!this._isMainSender&&this._onConnectionBreak(this._dcId)):(this._log.warn(`Invalid buffer ${e.code} for dc ${this._dcId}`),this.reconnect())):(this._log.error("Unhandled error while receiving data"),this._log.error(e),void this.reconnect())}try{await this._processMessage(t)}catch(e){this._log.error("Unhandled error while receiving data"),this._log.error(e)}}}async _processMessage(e){this._pending_ack.add(e.msgId),e.obj=await e.obj;let t=this._handlers[e.obj.CONSTRUCTOR_ID];t||(t=this._handleUpdate.bind(this)),await t(e)}_popStates(e){let t=this._pending_state[e];if(t)return this._pending_state[e].deferred.resolve(),delete this._pending_state[e],[t];const n=[];for(t of Object.values(this._pending_state))t.containerId&&t.containerId.equals(e)&&n.push(t.msgId);if(n.length){const e=[];for(const t of n)e.push(this._pending_state[t]),this._pending_state[t].deferred.resolve(),delete this._pending_state[t];return e}for(const t of this._last_acks)if(t.msgId===e)return[t];return[]}_handleRPCResult(e){const t=e.obj,n=this._pending_state[t.reqMsgId];if(n&&(n.deferred.resolve(),delete this._pending_state[t.reqMsgId]),this._log.debug(`Handling RPC result for message ${t.reqMsgId}`),!n)try{if(!(new _(t.body).tgReadObject()instanceof p.File))throw new B("Not an upload.File")}catch(e){if(this._log.error(e),e instanceof B)return void this._log.info(`Received response without parent request: ${t.body}`);throw e}if(t.error){const e=D(t.error,n.request);this._send_queue.append(new u(new g({msgIds:[n.msgId]}))),n.reject(e)}else try{const e=new _(t.body),s=n.request.readResult(e);n.resolve(s)}catch(e){throw n.reject(e),e}}async _handleContainer(e){this._log.debug("Handling container");for(const t of e.obj.messages)await this._processMessage(t)}async _handleGzipPacked(e){this._log.debug("Handling gzipped data");const t=new _(e.obj.data);e.obj=t.tgReadObject(),await this._processMessage(e)}_handleUpdate(e){2331323052===e.obj.SUBCLASS_OF_ID?(this._log.debug(`Handling update ${e.obj.className}`),this._updateCallback&&this._updateCallback(e.obj)):this._log.warn(`Note: ${e.obj.className} is not an update, not dispatching it`)}_handlePong(e){const t=e.obj,n=this._state.updateTimeOffset(e.msgId);this._updateCallback&&this._updateCallback(new b(n)),this._log.debug(`Handling pong for message ${t.msgId}`);const s=this._pending_state[t.msgId];this._pending_state[t.msgId].deferred.resolve(),delete this._pending_state[t.msgId],s&&s.resolve(t)}_handleBadServerSalt(e){const t=e.obj;this._log.debug(`Handling bad salt for message ${t.badMsgId}`),this._state.salt=t.newServerSalt;const n=this._popStates(t.badMsgId);this._send_queue.extend(n),this._log.debug(`${n.length} message(s) will be resent`)}_handleBadNotification(e){const t=e.obj,n=this._popStates(t.badMsgId);if(this._log.debug(`Handling bad msg ${JSON.stringify(t)}`),[16,17].includes(t.errorCode)){const t=this._state.updateTimeOffset(e.msgId);this._updateCallback&&this._updateCallback(new b(t)),this._log.info(`System clock is wrong, set time offset to ${t}s`)}else if(32===t.errorCode)this._state._sequence+=64;else{if(33!==t.errorCode){for(const e of n)e.reject(new w(e.request,t.errorCode));return}this._state._sequence-=16}this._send_queue.extend(n),this._log.debug(`${n.length} messages will be resent due to bad msg`)}_handleDetailedInfo(e){const t=e.obj.answerMsgId;this._log.debug(`Handling detailed info for message ${t}`),this._pending_ack.add(t)}_handleNewDetailedInfo(e){const t=e.obj.answerMsgId;this._log.debug(`Handling new detailed info for message ${t}`),this._pending_ack.add(t)}_handleNewSessionCreated(e){this._log.debug("Handling new session created"),this._state.salt=e.obj.serverSalt}_handleAck(e){const t=e.obj;this._log.debug(`Handling acknowledge for ${t.msgIds}`);for(const e of t.msgIds){const t=this._pending_state[e];t&&t.request instanceof T&&(this._pending_state[e].deferred.resolve(),delete this._pending_state[e],t.resolve(!0))}}_handleFutureSalts(e){this._log.debug(`Handling future salts for message ${e.msgId}`);const t=this._pending_state[e.msgId];t&&(this._pending_state[e].deferred.resolve(),delete this._pending_state[e],t.resolve(e.obj))}_handleStateForgotten(e){this._send_queue.append(new u(new f(e.msgId,String.fromCharCode(1).repeat(e.obj.msgIds))))}_handleMsgAll(e){}reconnect(){this._user_connected&&!this._reconnecting&&(this._reconnecting=!0,i.sleep(1e3).then((()=>{this._log.info("Started reconnecting"),this._reconnect()})))}async _reconnect(){this._log.debug("Closing current connection...");try{await this._disconnect()}catch(e){this._log.warn(e)}this._send_queue.append(void 0),this._state.reset();const e=new this._connection.constructor(this._connection._ip,this._connection._port,this._connection._dcId,this._connection._log,this._connection._testServers);await this.connect(e,!0),this._reconnecting=!1;for(const e of Object.values(this._pending_state))e.deferred.resolve();this._pending_state={},this._autoReconnectCallback&&await this._autoReconnectCallback()}}var V,N,F;F={logger:void 0,retries:1/0,delay:2e3,autoReconnect:!0,connectTimeout:void 0,authKeyCallback:void 0,updateCallback:void 0,autoReconnectCallback:void 0,isMainSender:void 0,onConnectionBreak:void 0},(N="DEFAULT_OPTIONS")in(V=x)?Object.defineProperty(V,N,{value:F,enumerable:!0,configurable:!0,writable:!0}):V[N]=F,e.exports=x},9109:(e,t,n)=>{var s=n(8764).Buffer;const a=n(4736),i=n(9618),o=n(2608),r=n(5544),c=n(8963),{TLMessage:d}=n(2058),{SecurityError:l,InvalidBufferError:u}=n(8187),{InvokeAfterMsg:g}=n(7404).requests,{toSignedLittleBuffer:p}=n(9618);e.exports=class{constructor(e,t){this.authKey=e,this._log=t,this.timeOffset=0,this.salt=0,this.id=void 0,this._sequence=void 0,this._lastMsgId=void 0,this.reset()}reset(){this.id=i.generateRandomLong(!0),this._sequence=0,this._lastMsgId=a(0)}updateMessageId(e){e.msgId=this._getNewMsgId()}async _calcKey(e,t,n){const a=!0===n?0:8,[o,r]=await Promise.all([i.sha256(s.concat([t,e.slice(a,a+36)])),i.sha256(s.concat([e.slice(a+40,a+76),t]))]);return{key:s.concat([o.slice(0,8),r.slice(8,24),o.slice(24,32)]),iv:s.concat([r.slice(0,8),o.slice(8,24),r.slice(24,32)])}}async writeDataAsMessage(e,t,n,a){const i=this._getNewMsgId(),o=this._getSeqNo(n);let r;r=a?await c.gzipIfSmaller(n,new g(a,{getBytes:()=>t}).getBytes()):await c.gzipIfSmaller(n,t);const d=s.alloc(4);d.writeInt32LE(o,0);const l=s.alloc(4);l.writeInt32LE(r.length,0);const u=p(i,8);return e.write(s.concat([u,d,l])),e.write(r),i}async encryptMessageData(e){await this.authKey.waitForKey();const t=p(this.salt,8),n=p(this.id,8);e=s.concat([s.concat([t,n]),e]);const a=i.generateRandomBytes(i.mod(-(e.length+12),16)+12),r=(await i.sha256(s.concat([this.authKey.getKey().slice(88,120),e,a]))).slice(8,24),{iv:c,key:d}=await this._calcKey(this.authKey.getKey(),r,!0),l=i.readBufferFromBigInt(this.authKey.keyId,8);return s.concat([l,r,new o(d,c).encryptIge(s.concat([e,a]))])}async decryptMessageData(e){if(e.length<8)throw new u(e);if(e.length<0)throw new l("Server replied with negative length");if(e.length%4!=0)throw new l("Server replied with length not divisible by 4");if(i.readBigIntFromBuffer(e.slice(0,8)).neq(this.authKey.keyId))throw new l("Server replied with an invalid auth key");const t=e.slice(8,24),{iv:n,key:a}=await this._calcKey(this.authKey.getKey(),t,!1);e=new o(a,n).decryptIge(e.slice(24));const c=await i.sha256(s.concat([this.authKey.getKey().slice(96,128),e]));if(!t.equals(c.slice(8,24)))throw new l("Received msg_key doesn't match with expected one");const g=new r(e);if(g.readLong(),!g.readLong().eq(this.id))throw new l("Server replied with a wrong session ID");const p=g.readLong(),f=g.readInt(),h=g.readInt(),m=e.length-h;if(m<12||m>1024)throw new l("Server replied with the wrong message padding");const _=g.tgReadObject();return new d(p,f,_)}_getNewMsgId(){const e=(new Date).getTime()/1e3+this.timeOffset,t=Math.floor(1e9*(e-Math.floor(e)));let n=a(Math.floor(e)).shiftLeft(a(32)).or(a(t).shiftLeft(a(2)));return this._lastMsgId.greaterOrEquals(n)&&(n=this._lastMsgId.add(a(4))),this._lastMsgId=n,n}updateTimeOffset(e){const t=this._getNewMsgId(),n=this.timeOffset,s=Math.floor((new Date).getTime()/1e3),i=e.shiftRight(a(32));return this.timeOffset=i-s,this.timeOffset!==n&&(this._lastMsgId=a(0),this._log.debug(`Updated time offset (old offset ${n}, bad ${t}, good ${e}, new ${this.timeOffset})`)),this.timeOffset}_getSeqNo(e){if(e){const e=2*this._sequence+1;return this._sequence+=1,e}return 2*this._sequence}}},4287:(e,t,n)=>{const{createDeferred:s}=n(9618);e.exports=class{constructor(e,t,n={}){this.containerId=void 0,this.msgId=void 0,this.request=e,this.data=e.getBytes(),this.after=t,this.result=void 0,this.pending=n,this.deferred=s(),this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}isReady(){const e=this.pending[this.after.id];return!e||e.deferred.promise}}},4353:(e,t,n)=>{function s(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const a=n(7214),i=n(6151);class o{constructor(e,t,n,o,r){s(this,"PacketCodecClass",void 0),this._ip=e,this._port=t,this._dcId=n,this._log=o,this._testServers=r,this._connected=!1,this._sendTask=void 0,this._recvTask=void 0,this._codec=void 0,this._obfuscation=void 0,this._sendArray=new i,this._recvArray=new i,this.socket=new a(this.disconnectCallback.bind(this))}async disconnectCallback(){await this.disconnect(!0)}async _connect(){this._log.debug("Connecting"),this._codec=new this.PacketCodecClass(this),await this.socket.connect(this._port,this._ip,this._testServers),this._log.debug("Finished connecting"),await this._initConn()}async connect(){await this._connect(),this._connected=!0,this._sendTask||(this._sendTask=this._sendLoop()),this._recvTask=this._recvLoop()}async disconnect(e=!1){this._connected&&(this._connected=!1,this._recvArray.push(void 0),e||await this.socket.close())}async send(e){if(!this._connected)throw new Error("Not connected");await this._sendArray.push(e)}async recv(){for(;this._connected;){const e=await this._recvArray.pop();if(e)return e}throw new Error("Not connected")}async _sendLoop(){try{for(;this._connected;){const e=await this._sendArray.pop();if(!e)return void(this._sendTask=void 0);await this._send(e)}}catch(e){this._log.info("The server closed the connection while sending")}}async _recvLoop(){let e;for(;this._connected;){try{if(e=await this._recv(),!e)throw new Error("no data received")}catch(e){return this._log.info("connection closed"),void this.disconnect()}await this._recvArray.push(e)}}async _initConn(){this._codec.tag&&await this.socket.write(this._codec.tag)}_send(e){const t=this._codec.encodePacket(e);this.socket.write(t)}_recv(){return this._codec.readPacket(this.socket)}toString(){return`${this._ip}:${this._port}/${this.constructor.name.replace("Connection","")}`}}e.exports={Connection:o,PacketCodec:class{constructor(e){this._conn=e}encodePacket(e){throw new Error("Not Implemented")}readPacket(e){throw new Error("Not Implemented")}},ObfuscatedConnection:class extends o{constructor(...e){super(...e),s(this,"ObfuscatedIO",void 0)}_initConn(){this._obfuscation=new this.ObfuscatedIO(this),this.socket.write(this._obfuscation.header)}_send(e){this._obfuscation.write(this._codec.encodePacket(e))}_recv(){return this._codec.readPacket(this._obfuscation)}}}},6302:(e,t,n)=>{var s=n(8764).Buffer;function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const i=n(4736),{readBufferFromBigInt:o}=n(9618),{Connection:r,PacketCodec:c}=n(4353);class d extends c{constructor(e){super(e),this.tag=d.tag,this.obfuscateTag=d.obfuscateTag}encodePacket(e){let t=e.length>>2;if(t<127){const e=s.alloc(1);e.writeUInt8(t,0),t=e}else t=s.concat([s.from("7f","hex"),o(i(t),3)]);return s.concat([t,e])}async readPacket(e){let t=(await e.read(1))[0];return t>=127&&(t=s.concat([await e.read(3),s.alloc(1)]).readInt32LE(0)),e.read(t<<2)}}a(d,"tag",s.from("ef","hex")),a(d,"obfuscateTag",s.from("efefefef","hex")),e.exports={ConnectionTCPAbridged:class extends r{constructor(...e){super(...e),a(this,"PacketCodecClass",d)}},AbridgedPacketCodec:d}},5484:()=>{},2986:(e,t,n)=>{var s=n(8764).Buffer;function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const{generateRandomBytes:i}=n(9618),{ObfuscatedConnection:o}=n(4353),{AbridgedPacketCodec:r}=n(6302),c=n(5830);class d{constructor(e){a(this,"header",void 0),this.connection=e.socket;const t=this.initHeader(e.PacketCodecClass);this.header=t.random,this._encrypt=t.encryptor,this._decrypt=t.decryptor}initHeader(e){const t=[s.from("50567247","hex"),s.from("474554","hex"),s.from("504f5354","hex"),s.from("eeeeeeee","hex")];let n;for(;;)if(n=i(64),239!==n[0]&&!n.slice(4,8).equals(s.alloc(4))){let e=!0;for(const s of t)if(s.equals(n.slice(0,4))){e=!1;break}if(e)break}n=n.toJSON().data;const a=s.from(n.slice(8,56)).reverse(),o=s.from(n.slice(8,40)),r=s.from(n.slice(40,56)),d=s.from(a.slice(0,32)),l=s.from(a.slice(32,48)),u=new c(o,r),g=new c(d,l);return n=s.concat([s.from(n.slice(0,56)),e.obfuscateTag,s.from(n.slice(60))]),n=s.concat([s.from(n.slice(0,56)),s.from(u.encrypt(n).slice(56,64)),s.from(n.slice(64))]),{random:n,encryptor:u,decryptor:g}}async read(e){const t=await this.connection.readExactly(e);return this._decrypt.encrypt(t)}write(e){this.connection.write(this._encrypt.encrypt(e))}}e.exports={ConnectionTCPObfuscated:class extends o{constructor(...e){super(...e),a(this,"ObfuscatedIO",d),a(this,"PacketCodecClass",r)}}}},417:(e,t,n)=>{const{Connection:s}=n(4353),{ConnectionTCPFull:a}=n(5484),{ConnectionTCPAbridged:i}=n(6302),{ConnectionTCPObfuscated:o}=n(2986);e.exports={Connection:s,ConnectionTCPFull:a,ConnectionTCPAbridged:i,ConnectionTCPObfuscated:o}},8415:(e,t,n)=>{function s(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const a=n(5585),i=n(4046);class o{constructor(e){this.state=e}}s(o,"disconnected",-1),s(o,"connected",1),s(o,"broken",0);const{Connection:r,ConnectionTCPFull:c,ConnectionTCPAbridged:d,ConnectionTCPObfuscated:l}=n(417);e.exports={Connection:r,ConnectionTCPFull:c,ConnectionTCPAbridged:d,ConnectionTCPObfuscated:l,MTProtoPlainSender:a,MTProtoSender:i,UpdateConnectionState:o,UpdateServerTimeOffset:class{constructor(e){this.timeOffset=e}}}},9270:e=>{e.exports=class{get dcId(){throw new Error("Not Implemented")}get serverAddress(){throw new Error("Not Implemented")}get port(){throw new Error("Not Implemented")}get authKey(){throw new Error("Not Implemented")}set authKey(e){throw new Error("Not Implemented")}setDC(e,t,n){throw new Error("Not implemented")}save(){throw new Error("Not Implemented")}delete(){throw new Error("Not Implemented")}}},926:(e,t,n)=>{const s=n(8753),a="GramJs";e.exports=class extends s{async _delete(){const e=new Request(this._storageKey);return(await self.caches.open(a)).delete(e)}async _fetchFromCache(){const e=new Request(this._storageKey),t=await self.caches.open(a),n=await t.match(e);return n?n.text():void 0}async _saveToCache(e){const t=new Request(this._storageKey),n=new Response(e);return(await self.caches.open(a)).put(t,n)}}},7:(e,t,n)=>{var s=n(8764).Buffer;const a=n(3995),i=n(3302),o=n(8960);e.exports=class extends a{constructor(e,t){super(),this._sessionData=e,this._callback=t,this._authKeys={}}get authKey(){throw new Error("Not supported")}set authKey(e){throw new Error("Not supported")}async load(){if(!this._sessionData)return;const{mainDcId:e,keys:t,hashes:n}=this._sessionData,{ipAddress:a,port:r}=o.getDC(e);this.setDC(e,a,r,!0),await Promise.all(Object.keys(t).map((async e=>{const a="string"==typeof t[e]?s.from(t[e],"hex"):s.from(t[e]);if(n[e]){const t="string"==typeof n[e]?s.from(n[e],"hex"):s.from(n[e]);this._authKeys[e]=new i(a,t)}else this._authKeys[e]=new i,await this._authKeys[e].setKey(a,!0)})))}setDC(e,t,n,s=!1){this._dcId=e,this._serverAddress=t,this._port=n,delete this._authKeys[e],s||this._onUpdate()}getAuthKey(e=this._dcId){return this._authKeys[e]}setAuthKey(e,t=this._dcId){this._authKeys[t]=e,this._onUpdate()}getSessionData(){const e={mainDcId:this._dcId,keys:{},hashes:{}};return Object.keys(this._authKeys).forEach((t=>{const n=this._authKeys[t];n&&n._key&&(e.keys[t]=n._key.toString("hex"),e.hashes[t]=n._hash.toString("hex"))})),e}_onUpdate(){this._callback(this.getSessionData())}delete(){this._callback(void 0)}}},5945:(e,t,n)=>{const s=n(1875),a=n(8753);e.exports=class extends a{_delete(){return s.del(`GramJs:${this._storageKey}`)}_fetchFromCache(){return s.get(`GramJs:${this._storageKey}`)}_saveToCache(e){return s.set(`GramJs:${this._storageKey}`,e)}}},1753:(e,t,n)=>{const s=n(8753);e.exports=class extends s{_delete(){return localStorage.removeItem(this._storageKey)}_fetchFromCache(){return localStorage.getItem(this._storageKey)}_saveToCache(e){return localStorage.setItem(this._storageKey,e)}}},3995:(e,t,n)=>{const s=n(9270);e.exports=class extends s{constructor(){super(),this._serverAddress=void 0,this._dcId=0,this._port=void 0,this._takeoutId=void 0,this._entities=new Set,this._updateStates={}}get dcId(){return this._dcId}get serverAddress(){return this._serverAddress}get port(){return this._port}get authKey(){return this._authKey}set authKey(e){this._authKey=e}setDC(e,t,n){this._dcId=0|e,this._serverAddress=t,this._port=n}}},8753:(e,t,n)=>{var s=n(8764).Buffer;const a=n(3995),i=n(3302),o=n(8960);e.exports=class extends a{constructor(e){super(),this._authKeys={},e&&e.startsWith("session:")?this._sessionString=e:e&&(this._storageKey=e)}get authKey(){throw new Error("Not supported")}set authKey(e){throw new Error("Not supported")}async load(){if(this._sessionString)await this._loadFromSessionString();else if(this._storageKey)try{const e=await this._fetchFromCache(),{mainDcId:t,keys:n,hashes:a}=JSON.parse(e),{ipAddress:r,port:c}=o.getDC(t);this.setDC(t,r,c,!0),Object.keys(n).forEach((e=>{n[e]&&a[e]&&(this._authKeys[e]=new i(s.from(n[e].data),s.from(a[e].data)))}))}catch(e){console.warn("Failed to retrieve or parse session from storage"),console.warn(e)}}setDC(e,t,n,s=!1){this._dcId=e,this._serverAddress=t,this._port=n,delete this._authKeys[e],s||this._updateStorage()}async save(){return this._storageKey||(this._storageKey=`GramJs-session-${Date.now()}`),await this._updateStorage(),this._storageKey}getAuthKey(e=this._dcId){return this._authKeys[e]}setAuthKey(e,t=this._dcId){this._authKeys[t]=e,this._updateStorage()}getSessionData(e){const t={mainDcId:this._dcId,keys:{},hashes:{}};return Object.keys(this._authKeys).forEach((n=>{const s=this._authKeys[n];s._key&&(t.keys[n]=e?s._key.toString("hex"):s._key,t.hashes[n]=e?s._hash.toString("hex"):s._hash)})),t}async _loadFromSessionString(){const[,e,t]=this._sessionString.split(":"),n=Number(e),{ipAddress:a,port:r}=o.getDC(n);this.setDC(n,a,r);const c=new i;await c.setKey(s.from(t,"hex"),!0),this.setAuthKey(c,n)}async _updateStorage(){if(this._storageKey)try{await this._saveToCache(JSON.stringify(this.getSessionData()))}catch(e){console.warn("Failed to update session in storage"),console.warn(e)}}async delete(){try{return await this._delete()}catch(e){console.warn("Failed to delete session from storage"),console.warn(e)}}_delete(){throw new Error("Not Implemented")}_fetchFromCache(){throw new Error("Not Implemented")}_saveToCache(e){throw new Error("Not Implemented")}}},2433:(e,t,n)=>{var s=n(8764).Buffer;const a=n(3995),i=n(3302),o=n(5544);class r extends a{constructor(e){if(super(),e){if("1"!==e[0])throw new Error("Not a valid string");e=e.slice(1);const t=r.decode(e),n=new o(t);this._dcId=n.read(1).readUInt8(0);const s=n.read(2).readInt16BE(0);this._serverAddress=String(n.read(s)),this._port=n.read(2).readInt16BE(0),this._key=n.read(-1)}}static encode(e){return e.toString("base64")}static decode(e){return s.from(e,"base64")}async load(){this._key&&(this._authKey=new i,await this._authKey.setKey(this._key))}save(){if(!this.authKey)return"";const e=s.from([this.dcId]),t=s.from(this.serverAddress),n=s.alloc(2);n.writeInt16BE(t.length,0);const a=s.alloc(2);return a.writeInt16BE(this.port,0),"1"+r.encode(s.concat([e,n,t,a,this.authKey.getKey()]))}getAuthKey(e){if(!e||e===this.dcId)return this.authKey}setAuthKey(e,t){t&&t!==this.dcId||(this.authKey=e)}}e.exports=r},5886:(e,t,n)=>{const s=n(3995),a=n(2433),i=n(926),o=n(1753),r=n(5945),c=n(7);e.exports={Memory:s,StringSession:a,CacheApiSession:i,LocalStorageSession:o,IdbSession:r,CallbackSession:c}},845:(e,t,n)=>{const s=n(7150),a={};for(const e of Object.values(s))if(e.CONSTRUCTOR_ID)a[e.CONSTRUCTOR_ID]=e;else for(const t of Object.values(e))a[t.CONSTRUCTOR_ID]=t;e.exports={LAYER:133,tlobjects:a}},7150:(e,t,n)=>{var s=n(8764).Buffer;function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const{parseTl:i,serializeBytes:o,serializeDate:r}=n(1436),{toSignedLittleBuffer:c}=n(9618),d=n(4779),l=n(8106),u="undefined"!=typeof self&&void 0!==self.localStorage,g="GramJs:apiCache";function p(e){const t=i(e,109),n=[],s=[];for(const e of t)e.isFunction?s.push(e):n.push(e);return[n,s]}function f(e,t){switch(t){case"int":{const t=s.alloc(4);return t.writeInt32LE(e,0),t}case"long":return c(e,8);case"int128":return c(e,16);case"int256":return c(e,32);case"double":{const t=s.alloc(8);return t.writeDoubleLE(e,0),t}case"string":return o(e);case"Bool":return e?s.from("b5757299","hex"):s.from("379779bc","hex");case"true":return s.alloc(0);case"bytes":return o(e);case"date":return r(e);default:return e.getBytes()}}function h(e,t){if(t.isVector){t.useVectorId&&e.readInt();const n=[],s=e.readInt();t.isVector=!1;for(let a=0;a{this[e]=t[e]}))}static fromReader(e){const t={};for(const n in c)if(c.hasOwnProperty(n)){const s=c[n];if(s.isFlag){if("true"===s.type){t[n]=Boolean(t.flags&1<f(t,c[e].type)))))}else if(c[e].flagIndicator)if(Object.values(c).some((e=>e.isFlag))){let e=0;for(const t in c)c[t].isFlag&&(!1===this[t]&&"true"===c[t].type||void 0===this[t]?e|=0:e|=1</);if(n){t.readInt();const e=[],s=t.readInt();if("int"===n[1])for(let n=0;n{"function"!=typeof t[e]&&n[e]?Object.assign(n[e],t[e]):n[e]=t[e]})),n}(m("constructor",e.constructors),m("request",e.requests))}()},4779:e=>{e.exports="boolFalse#bc799737 = Bool;\nboolTrue#997275b5 = Bool;\ntrue#3fedd339 = True;\nvector#1cb5c415 {t:Type} # [ t ] = Vector t;\nerror#c4b9f9bb code:int text:string = Error;\nnull#56730bcc = Null;\ninputPeerEmpty#7f3b18ea = InputPeer;\ninputPeerSelf#7da07ec9 = InputPeer;\ninputPeerChat#35a95cb9 chat_id:long = InputPeer;\ninputPeerUser#dde8a54c user_id:long access_hash:long = InputPeer;\ninputPeerChannel#27bcbbfc channel_id:long access_hash:long = InputPeer;\ninputPeerUserFromMessage#a87b0a1c peer:InputPeer msg_id:int user_id:long = InputPeer;\ninputPeerChannelFromMessage#bd2a0840 peer:InputPeer msg_id:int channel_id:long = InputPeer;\ninputUserEmpty#b98886cf = InputUser;\ninputUserSelf#f7c1b13f = InputUser;\ninputUser#f21158c6 user_id:long access_hash:long = InputUser;\ninputUserFromMessage#1da448e2 peer:InputPeer msg_id:int user_id:long = InputUser;\ninputPhoneContact#f392b7f4 client_id:long phone:string first_name:string last_name:string = InputContact;\ninputFile#f52ff27f id:long parts:int name:string md5_checksum:string = InputFile;\ninputFileBig#fa4f0bb5 id:long parts:int name:string = InputFile;\ninputMediaEmpty#9664f57f = InputMedia;\ninputMediaUploadedPhoto#1e287d04 flags:# file:InputFile stickers:flags.0?Vector ttl_seconds:flags.1?int = InputMedia;\ninputMediaPhoto#b3ba0635 flags:# id:InputPhoto ttl_seconds:flags.0?int = InputMedia;\ninputMediaGeoPoint#f9c44144 geo_point:InputGeoPoint = InputMedia;\ninputMediaContact#f8ab7dfb phone_number:string first_name:string last_name:string vcard:string = InputMedia;\ninputMediaUploadedDocument#5b38c6c1 flags:# nosound_video:flags.3?true force_file:flags.4?true file:InputFile thumb:flags.2?InputFile mime_type:string attributes:Vector stickers:flags.0?Vector ttl_seconds:flags.1?int = InputMedia;\ninputMediaDocument#33473058 flags:# id:InputDocument ttl_seconds:flags.0?int query:flags.1?string = InputMedia;\ninputMediaVenue#c13d1c11 geo_point:InputGeoPoint title:string address:string provider:string venue_id:string venue_type:string = InputMedia;\ninputMediaPhotoExternal#e5bbfe1a flags:# url:string ttl_seconds:flags.0?int = InputMedia;\ninputMediaDocumentExternal#fb52dc99 flags:# url:string ttl_seconds:flags.0?int = InputMedia;\ninputMediaGame#d33f43f3 id:InputGame = InputMedia;\ninputMediaInvoice#d9799874 flags:# title:string description:string photo:flags.0?InputWebDocument invoice:Invoice payload:bytes provider:string provider_data:DataJSON start_param:flags.1?string = InputMedia;\ninputMediaGeoLive#971fa843 flags:# stopped:flags.0?true geo_point:InputGeoPoint heading:flags.2?int period:flags.1?int proximity_notification_radius:flags.3?int = InputMedia;\ninputMediaPoll#f94e5f1 flags:# poll:Poll correct_answers:flags.0?Vector solution:flags.1?string solution_entities:flags.1?Vector = InputMedia;\ninputMediaDice#e66fbf7b emoticon:string = InputMedia;\ninputChatPhotoEmpty#1ca48f57 = InputChatPhoto;\ninputChatUploadedPhoto#c642724e flags:# file:flags.0?InputFile video:flags.1?InputFile video_start_ts:flags.2?double = InputChatPhoto;\ninputChatPhoto#8953ad37 id:InputPhoto = InputChatPhoto;\ninputGeoPointEmpty#e4c123d6 = InputGeoPoint;\ninputGeoPoint#48222faf flags:# lat:double long:double accuracy_radius:flags.0?int = InputGeoPoint;\ninputPhotoEmpty#1cd7bf0d = InputPhoto;\ninputPhoto#3bb3b94a id:long access_hash:long file_reference:bytes = InputPhoto;\ninputFileLocation#dfdaabe1 volume_id:long local_id:int secret:long file_reference:bytes = InputFileLocation;\ninputEncryptedFileLocation#f5235d55 id:long access_hash:long = InputFileLocation;\ninputDocumentFileLocation#bad07584 id:long access_hash:long file_reference:bytes thumb_size:string = InputFileLocation;\ninputSecureFileLocation#cbc7ee28 id:long access_hash:long = InputFileLocation;\ninputTakeoutFileLocation#29be5899 = InputFileLocation;\ninputPhotoFileLocation#40181ffe id:long access_hash:long file_reference:bytes thumb_size:string = InputFileLocation;\ninputPhotoLegacyFileLocation#d83466f3 id:long access_hash:long file_reference:bytes volume_id:long local_id:int secret:long = InputFileLocation;\ninputPeerPhotoFileLocation#37257e99 flags:# big:flags.0?true peer:InputPeer photo_id:long = InputFileLocation;\ninputStickerSetThumb#9d84f3db stickerset:InputStickerSet thumb_version:int = InputFileLocation;\ninputGroupCallStream#598a92a flags:# call:InputGroupCall time_ms:long scale:int video_channel:flags.0?int video_quality:flags.0?int = InputFileLocation;\npeerUser#59511722 user_id:long = Peer;\npeerChat#36c6019a chat_id:long = Peer;\npeerChannel#a2a5371e channel_id:long = Peer;\nstorage.fileUnknown#aa963b05 = storage.FileType;\nstorage.filePartial#40bc6f52 = storage.FileType;\nstorage.fileJpeg#7efe0e = storage.FileType;\nstorage.fileGif#cae1aadf = storage.FileType;\nstorage.filePng#a4f63c0 = storage.FileType;\nstorage.filePdf#ae1e508d = storage.FileType;\nstorage.fileMp3#528a0677 = storage.FileType;\nstorage.fileMov#4b09ebbc = storage.FileType;\nstorage.fileMp4#b3cea0e4 = storage.FileType;\nstorage.fileWebp#1081464c = storage.FileType;\nuserEmpty#d3bc4b7a id:long = User;\nuser#3ff6ecb0 flags:# self:flags.10?true contact:flags.11?true mutual_contact:flags.12?true deleted:flags.13?true bot:flags.14?true bot_chat_history:flags.15?true bot_nochats:flags.16?true verified:flags.17?true restricted:flags.18?true min:flags.20?true bot_inline_geo:flags.21?true support:flags.23?true scam:flags.24?true apply_min_photo:flags.25?true fake:flags.26?true id:long access_hash:flags.0?long first_name:flags.1?string last_name:flags.2?string username:flags.3?string phone:flags.4?string photo:flags.5?UserProfilePhoto status:flags.6?UserStatus bot_info_version:flags.14?int restriction_reason:flags.18?Vector bot_inline_placeholder:flags.19?string lang_code:flags.22?string = User;\nuserProfilePhotoEmpty#4f11bae1 = UserProfilePhoto;\nuserProfilePhoto#82d1f706 flags:# has_video:flags.0?true photo_id:long stripped_thumb:flags.1?bytes dc_id:int = UserProfilePhoto;\nuserStatusEmpty#9d05049 = UserStatus;\nuserStatusOnline#edb93949 expires:int = UserStatus;\nuserStatusOffline#8c703f was_online:int = UserStatus;\nuserStatusRecently#e26f42f1 = UserStatus;\nuserStatusLastWeek#7bf09fc = UserStatus;\nuserStatusLastMonth#77ebc742 = UserStatus;\nchatEmpty#29562865 id:long = Chat;\nchat#41cbf256 flags:# creator:flags.0?true kicked:flags.1?true left:flags.2?true deactivated:flags.5?true call_active:flags.23?true call_not_empty:flags.24?true 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 id:long access_hash:flags.13?long title:string username:flags.6?string photo:ChatPhoto date:int restriction_reason:flags.9?Vector admin_rights:flags.14?ChatAdminRights banned_rights:flags.15?ChatBannedRights default_banned_rights:flags.18?ChatBannedRights participants_count:flags.17?int = Chat;\nchannelForbidden#17d493d5 flags:# broadcast:flags.5?true megagroup:flags.8?true id:long access_hash:long title:string until_date:flags.16?int = Chat;\nchatFull#4dbdc099 flags:# can_set_username:flags.7?true has_scheduled:flags.8?true id:long about:string participants:ChatParticipants chat_photo:flags.2?Photo notify_settings:PeerNotifySettings exported_invite:flags.13?ExportedChatInvite bot_info:flags.3?Vector pinned_msg_id:flags.6?int folder_id:flags.11?int call:flags.12?InputGroupCall ttl_period:flags.14?int groupcall_default_join_as:flags.15?Peer theme_emoticon:flags.16?string = ChatFull;\nchannelFull#e9b27a17 flags:# can_view_participants:flags.3?true can_set_username:flags.6?true can_set_stickers:flags.7?true hidden_prehistory:flags.10?true can_set_location:flags.16?true has_scheduled:flags.19?true can_view_stats:flags.20?true blocked:flags.22?true id:long about:string participants_count:flags.0?int admins_count:flags.1?int kicked_count:flags.2?int banned_count:flags.2?int online_count:flags.13?int read_inbox_max_id:int read_outbox_max_id:int unread_count:int chat_photo:Photo notify_settings:PeerNotifySettings exported_invite:flags.23?ExportedChatInvite bot_info:Vector migrated_from_chat_id:flags.4?long migrated_from_max_id:flags.4?int pinned_msg_id:flags.5?int stickerset:flags.8?StickerSet available_min_id:flags.9?int folder_id:flags.11?int linked_chat_id:flags.14?long location:flags.15?ChannelLocation slowmode_seconds:flags.17?int slowmode_next_send_date:flags.18?int stats_dc:flags.12?int pts:int call:flags.21?InputGroupCall ttl_period:flags.24?int pending_suggestions:flags.25?Vector groupcall_default_join_as:flags.26?Peer theme_emoticon:flags.27?string = ChatFull;\nchatParticipant#c02d4007 user_id:long inviter_id:long date:int = ChatParticipant;\nchatParticipantCreator#e46bcee4 user_id:long = ChatParticipant;\nchatParticipantAdmin#a0933f5b user_id:long inviter_id:long date:int = ChatParticipant;\nchatParticipantsForbidden#8763d3e1 flags:# chat_id:long self_participant:flags.0?ChatParticipant = ChatParticipants;\nchatParticipants#3cbc93f8 chat_id:long participants:Vector version:int = ChatParticipants;\nchatPhotoEmpty#37c1011c = ChatPhoto;\nchatPhoto#1c6e1c11 flags:# has_video:flags.0?true photo_id:long stripped_thumb:flags.1?bytes dc_id:int = ChatPhoto;\nmessageEmpty#90a6ca84 flags:# id:int peer_id:flags.0?Peer = Message;\nmessage#85d6cbe2 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true post:flags.14?true from_scheduled:flags.18?true legacy:flags.19?true edit_hide:flags.21?true pinned:flags.24?true id:int from_id:flags.8?Peer peer_id:Peer fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?long reply_to:flags.3?MessageReplyHeader date:int message:string media:flags.9?MessageMedia reply_markup:flags.6?ReplyMarkup entities:flags.7?Vector views:flags.10?int forwards:flags.10?int replies:flags.23?MessageReplies edit_date:flags.15?int post_author:flags.16?string grouped_id:flags.17?long restriction_reason:flags.22?Vector ttl_period:flags.25?int = Message;\nmessageService#2b085862 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true post:flags.14?true legacy:flags.19?true id:int from_id:flags.8?Peer peer_id:Peer reply_to:flags.3?MessageReplyHeader date:int action:MessageAction ttl_period:flags.25?int = Message;\nmessageMediaEmpty#3ded6320 = MessageMedia;\nmessageMediaPhoto#695150d7 flags:# photo:flags.0?Photo ttl_seconds:flags.2?int = MessageMedia;\nmessageMediaGeo#56e0d474 geo:GeoPoint = MessageMedia;\nmessageMediaContact#70322949 phone_number:string first_name:string last_name:string vcard:string user_id:long = MessageMedia;\nmessageMediaUnsupported#9f84f49e = MessageMedia;\nmessageMediaDocument#9cb070d7 flags:# document:flags.0?Document ttl_seconds:flags.2?int = MessageMedia;\nmessageMediaWebPage#a32dd600 webpage:WebPage = MessageMedia;\nmessageMediaVenue#2ec0533f geo:GeoPoint title:string address:string provider:string venue_id:string venue_type:string = MessageMedia;\nmessageMediaGame#fdb19008 game:Game = MessageMedia;\nmessageMediaInvoice#84551347 flags:# shipping_address_requested:flags.1?true test:flags.3?true title:string description:string photo:flags.0?WebDocument receipt_msg_id:flags.2?int currency:string total_amount:long start_param:string = MessageMedia;\nmessageMediaGeoLive#b940c666 flags:# geo:GeoPoint heading:flags.0?int period:int proximity_notification_radius:flags.1?int = MessageMedia;\nmessageMediaPoll#4bd6e798 poll:Poll results:PollResults = MessageMedia;\nmessageMediaDice#3f7ee58b value:int emoticon:string = MessageMedia;\nmessageActionEmpty#b6aef7b0 = MessageAction;\nmessageActionChatCreate#bd47cbad title:string users:Vector = MessageAction;\nmessageActionChatEditTitle#b5a1ce5a title:string = MessageAction;\nmessageActionChatEditPhoto#7fcb13a8 photo:Photo = MessageAction;\nmessageActionChatDeletePhoto#95e3fbef = MessageAction;\nmessageActionChatAddUser#15cefd00 users:Vector = MessageAction;\nmessageActionChatDeleteUser#a43f30cc user_id:long = MessageAction;\nmessageActionChatJoinedByLink#31224c3 inviter_id:long = MessageAction;\nmessageActionChannelCreate#95d2ac92 title:string = MessageAction;\nmessageActionChatMigrateTo#e1037f92 channel_id:long = MessageAction;\nmessageActionChannelMigrateFrom#ea3948e9 title:string chat_id:long = MessageAction;\nmessageActionPinMessage#94bd38ed = MessageAction;\nmessageActionHistoryClear#9fbab604 = MessageAction;\nmessageActionGameScore#92a72876 game_id:long score:int = MessageAction;\nmessageActionPaymentSentMe#8f31b327 flags:# currency:string total_amount:long payload:bytes info:flags.0?PaymentRequestedInfo shipping_option_id:flags.1?string charge:PaymentCharge = MessageAction;\nmessageActionPaymentSent#40699cd0 currency:string total_amount:long = MessageAction;\nmessageActionPhoneCall#80e11a7f flags:# video:flags.2?true call_id:long reason:flags.0?PhoneCallDiscardReason duration:flags.1?int = MessageAction;\nmessageActionScreenshotTaken#4792929b = MessageAction;\nmessageActionCustomAction#fae69f56 message:string = MessageAction;\nmessageActionBotAllowed#abe9affe domain:string = MessageAction;\nmessageActionSecureValuesSentMe#1b287353 values:Vector credentials:SecureCredentialsEncrypted = MessageAction;\nmessageActionSecureValuesSent#d95c6154 types:Vector = MessageAction;\nmessageActionContactSignUp#f3f25f76 = MessageAction;\nmessageActionGeoProximityReached#98e0d697 from_id:Peer to_id:Peer distance:int = MessageAction;\nmessageActionGroupCall#7a0d7f42 flags:# call:InputGroupCall duration:flags.0?int = MessageAction;\nmessageActionInviteToGroupCall#502f92f7 call:InputGroupCall users:Vector = MessageAction;\nmessageActionSetMessagesTTL#aa1afbfd period:int = MessageAction;\nmessageActionGroupCallScheduled#b3a07661 call:InputGroupCall schedule_date:int = MessageAction;\nmessageActionSetChatTheme#aa786345 emoticon:string = MessageAction;\ndialog#2c171f72 flags:# pinned:flags.2?true unread_mark:flags.3?true peer:Peer top_message:int read_inbox_max_id:int read_outbox_max_id:int unread_count:int unread_mentions_count:int notify_settings:PeerNotifySettings pts:flags.0?int draft:flags.1?DraftMessage folder_id:flags.4?int = Dialog;\ndialogFolder#71bd134c flags:# pinned:flags.2?true folder:Folder peer:Peer top_message:int unread_muted_peers_count:int unread_unmuted_peers_count:int unread_muted_messages_count:int unread_unmuted_messages_count:int = Dialog;\nphotoEmpty#2331b22d id:long = Photo;\nphoto#fb197a65 flags:# has_stickers:flags.0?true id:long access_hash:long file_reference:bytes date:int sizes:Vector video_sizes:flags.1?Vector dc_id:int = Photo;\nphotoSizeEmpty#e17e23c type:string = PhotoSize;\nphotoSize#75c78e60 type:string w:int h:int size:int = PhotoSize;\nphotoCachedSize#21e1ad6 type:string w:int h:int bytes:bytes = PhotoSize;\nphotoStrippedSize#e0b0bc2e type:string bytes:bytes = PhotoSize;\nphotoSizeProgressive#fa3efb95 type:string w:int h:int sizes:Vector = PhotoSize;\nphotoPathSize#d8214d41 type:string bytes:bytes = PhotoSize;\ngeoPointEmpty#1117dd5f = GeoPoint;\ngeoPoint#b2a2f663 flags:# long:double lat:double access_hash:long accuracy_radius:flags.0?int = GeoPoint;\nauth.sentCode#5e002502 flags:# type:auth.SentCodeType phone_code_hash:string next_type:flags.1?auth.CodeType timeout:flags.2?int = auth.SentCode;\nauth.authorization#cd050916 flags:# tmp_sessions:flags.0?int user:User = auth.Authorization;\nauth.authorizationSignUpRequired#44747e9a flags:# terms_of_service:flags.0?help.TermsOfService = auth.Authorization;\nauth.exportedAuthorization#b434e2b8 id:long bytes:bytes = auth.ExportedAuthorization;\ninputNotifyPeer#b8bc5b0c peer:InputPeer = InputNotifyPeer;\ninputNotifyUsers#193b4417 = InputNotifyPeer;\ninputNotifyChats#4a95e84e = InputNotifyPeer;\ninputNotifyBroadcasts#b1db7c7e = InputNotifyPeer;\ninputPeerNotifySettings#9c3d198e flags:# show_previews:flags.0?Bool silent:flags.1?Bool mute_until:flags.2?int sound:flags.3?string = InputPeerNotifySettings;\npeerNotifySettings#af509d20 flags:# show_previews:flags.0?Bool silent:flags.1?Bool mute_until:flags.2?int sound:flags.3?string = PeerNotifySettings;\npeerSettings#733f2961 flags:# report_spam:flags.0?true add_contact:flags.1?true block_contact:flags.2?true share_contact:flags.3?true need_contacts_exception:flags.4?true report_geo:flags.5?true autoarchived:flags.7?true invite_members:flags.8?true geo_distance:flags.6?int = PeerSettings;\nwallPaper#a437c3ed id:long flags:# creator:flags.0?true default:flags.1?true pattern:flags.3?true dark:flags.4?true access_hash:long slug:string document:Document settings:flags.2?WallPaperSettings = WallPaper;\nwallPaperNoFile#e0804116 id:long flags:# default:flags.1?true dark:flags.4?true settings:flags.2?WallPaperSettings = WallPaper;\ninputReportReasonSpam#58dbcab8 = ReportReason;\ninputReportReasonViolence#1e22c78d = ReportReason;\ninputReportReasonPornography#2e59d922 = ReportReason;\ninputReportReasonChildAbuse#adf44ee3 = ReportReason;\ninputReportReasonOther#c1e4a2b1 = ReportReason;\ninputReportReasonCopyright#9b89f93a = ReportReason;\ninputReportReasonGeoIrrelevant#dbd4feed = ReportReason;\ninputReportReasonFake#f5ddd6e7 = ReportReason;\nuserFull#d697ff05 flags:# blocked:flags.0?true phone_calls_available:flags.4?true phone_calls_private:flags.5?true can_pin_message:flags.7?true has_scheduled:flags.12?true video_calls_available:flags.13?true user:User about:flags.1?string settings:PeerSettings profile_photo:flags.2?Photo notify_settings:PeerNotifySettings bot_info:flags.3?BotInfo pinned_msg_id:flags.6?int common_chats_count:int folder_id:flags.11?int ttl_period:flags.14?int theme_emoticon:flags.15?string = UserFull;\ncontact#145ade0b user_id:long mutual:Bool = Contact;\nimportedContact#c13e3c50 user_id:long client_id:long = ImportedContact;\ncontactStatus#16d9703b user_id:long status:UserStatus = ContactStatus;\ncontacts.contactsNotModified#b74ba9d2 = contacts.Contacts;\ncontacts.contacts#eae87e42 contacts:Vector saved_count:int users:Vector = contacts.Contacts;\ncontacts.importedContacts#77d01c3b imported:Vector popular_invites:Vector retry_contacts:Vector users:Vector = contacts.ImportedContacts;\ncontacts.blocked#ade1591 blocked:Vector chats:Vector users:Vector = contacts.Blocked;\ncontacts.blockedSlice#e1664194 count:int blocked:Vector chats:Vector users:Vector = contacts.Blocked;\nmessages.dialogs#15ba6c40 dialogs:Vector messages:Vector chats:Vector users:Vector = messages.Dialogs;\nmessages.dialogsSlice#71e094f3 count:int dialogs:Vector messages:Vector chats:Vector users:Vector = messages.Dialogs;\nmessages.dialogsNotModified#f0e3e596 count:int = messages.Dialogs;\nmessages.messages#8c718e87 messages:Vector chats:Vector users:Vector = messages.Messages;\nmessages.messagesSlice#3a54685e flags:# inexact:flags.1?true count:int next_rate:flags.0?int offset_id_offset:flags.2?int messages:Vector chats:Vector users:Vector = messages.Messages;\nmessages.channelMessages#64479808 flags:# inexact:flags.1?true pts:int count:int offset_id_offset:flags.2?int messages:Vector chats:Vector users:Vector = messages.Messages;\nmessages.messagesNotModified#74535f21 count:int = messages.Messages;\nmessages.chats#64ff9fd5 chats:Vector = messages.Chats;\nmessages.chatsSlice#9cd81144 count:int chats:Vector = messages.Chats;\nmessages.chatFull#e5d7d19c full_chat:ChatFull chats:Vector users:Vector = messages.ChatFull;\nmessages.affectedHistory#b45c69d1 pts:int pts_count:int offset:int = messages.AffectedHistory;\ninputMessagesFilterEmpty#57e2f66c = MessagesFilter;\ninputMessagesFilterPhotos#9609a51c = MessagesFilter;\ninputMessagesFilterVideo#9fc00e65 = MessagesFilter;\ninputMessagesFilterPhotoVideo#56e9f0e4 = MessagesFilter;\ninputMessagesFilterDocument#9eddf188 = MessagesFilter;\ninputMessagesFilterUrl#7ef0dd87 = MessagesFilter;\ninputMessagesFilterGif#ffc86587 = MessagesFilter;\ninputMessagesFilterVoice#50f5c392 = MessagesFilter;\ninputMessagesFilterMusic#3751b49e = MessagesFilter;\ninputMessagesFilterChatPhotos#3a20ecb8 = MessagesFilter;\ninputMessagesFilterPhoneCalls#80c99768 flags:# missed:flags.0?true = MessagesFilter;\ninputMessagesFilterRoundVoice#7a7c17a4 = MessagesFilter;\ninputMessagesFilterRoundVideo#b549da53 = MessagesFilter;\ninputMessagesFilterMyMentions#c1f8e69a = MessagesFilter;\ninputMessagesFilterGeo#e7026d0d = MessagesFilter;\ninputMessagesFilterContacts#e062db83 = MessagesFilter;\ninputMessagesFilterPinned#1bb00451 = MessagesFilter;\nupdateNewMessage#1f2b0afd message:Message pts:int pts_count:int = Update;\nupdateMessageID#4e90bfd6 id:int random_id:long = Update;\nupdateDeleteMessages#a20db0e5 messages:Vector pts:int pts_count:int = Update;\nupdateUserTyping#c01e857f user_id:long action:SendMessageAction = Update;\nupdateChatUserTyping#83487af0 chat_id:long from_id:Peer action:SendMessageAction = Update;\nupdateChatParticipants#7761198 participants:ChatParticipants = Update;\nupdateUserStatus#e5bdf8de user_id:long status:UserStatus = Update;\nupdateUserName#c3f202e0 user_id:long first_name:string last_name:string username:string = Update;\nupdateUserPhoto#f227868c user_id:long date:int photo:UserProfilePhoto previous:Bool = Update;\nupdateNewEncryptedMessage#12bcbd9a message:EncryptedMessage qts:int = Update;\nupdateEncryptedChatTyping#1710f156 chat_id:int = Update;\nupdateEncryption#b4a2e88d chat:EncryptedChat date:int = Update;\nupdateEncryptedMessagesRead#38fe25b7 chat_id:int max_date:int date:int = Update;\nupdateChatParticipantAdd#3dda5451 chat_id:long user_id:long inviter_id:long date:int version:int = Update;\nupdateChatParticipantDelete#e32f3d77 chat_id:long user_id:long version:int = Update;\nupdateDcOptions#8e5e9873 dc_options:Vector = Update;\nupdateNotifySettings#bec268ef peer:NotifyPeer notify_settings:PeerNotifySettings = Update;\nupdateServiceNotification#ebe46819 flags:# popup:flags.0?true inbox_date:flags.1?int type:string message:string media:MessageMedia entities:Vector = Update;\nupdatePrivacy#ee3b272a key:PrivacyKey rules:Vector = Update;\nupdateUserPhone#5492a13 user_id:long phone:string = Update;\nupdateReadHistoryInbox#9c974fdf flags:# folder_id:flags.0?int peer:Peer max_id:int still_unread_count:int pts:int pts_count:int = Update;\nupdateReadHistoryOutbox#2f2f21bf peer:Peer max_id:int pts:int pts_count:int = Update;\nupdateWebPage#7f891213 webpage:WebPage pts:int pts_count:int = Update;\nupdateReadMessagesContents#68c13933 messages:Vector pts:int pts_count:int = Update;\nupdateChannelTooLong#108d941f flags:# channel_id:long pts:flags.0?int = Update;\nupdateChannel#635b4c09 channel_id:long = Update;\nupdateNewChannelMessage#62ba04d9 message:Message pts:int pts_count:int = Update;\nupdateReadChannelInbox#922e6e10 flags:# folder_id:flags.0?int channel_id:long max_id:int still_unread_count:int pts:int = Update;\nupdateDeleteChannelMessages#c32d5b12 channel_id:long messages:Vector pts:int pts_count:int = Update;\nupdateChannelMessageViews#f226ac08 channel_id:long id:int views:int = Update;\nupdateChatParticipantAdmin#d7ca61a2 chat_id:long user_id:long is_admin:Bool version:int = Update;\nupdateNewStickerSet#688a30aa stickerset:messages.StickerSet = Update;\nupdateStickerSetsOrder#bb2d201 flags:# masks:flags.0?true order:Vector = Update;\nupdateStickerSets#43ae3dec = Update;\nupdateSavedGifs#9375341e = Update;\nupdateBotInlineQuery#496f379c flags:# query_id:long user_id:long query:string geo:flags.0?GeoPoint peer_type:flags.1?InlineQueryPeerType offset:string = Update;\nupdateBotInlineSend#12f12a07 flags:# user_id:long query:string geo:flags.0?GeoPoint id:string msg_id:flags.1?InputBotInlineMessageID = Update;\nupdateEditChannelMessage#1b3f4df7 message:Message pts:int pts_count:int = Update;\nupdateBotCallbackQuery#b9cfc48d flags:# query_id:long user_id:long peer:Peer msg_id:int chat_instance:long data:flags.0?bytes game_short_name:flags.1?string = Update;\nupdateEditMessage#e40370a3 message:Message pts:int pts_count:int = Update;\nupdateInlineBotCallbackQuery#691e9052 flags:# query_id:long user_id:long msg_id:InputBotInlineMessageID chat_instance:long data:flags.0?bytes game_short_name:flags.1?string = Update;\nupdateReadChannelOutbox#b75f99a9 channel_id:long max_id:int = Update;\nupdateDraftMessage#ee2bb969 peer:Peer draft:DraftMessage = Update;\nupdateReadFeaturedStickers#571d2742 = Update;\nupdateRecentStickers#9a422c20 = Update;\nupdateConfig#a229dd06 = Update;\nupdatePtsChanged#3354678f = Update;\nupdateChannelWebPage#2f2ba99f channel_id:long webpage:WebPage pts:int pts_count:int = Update;\nupdateDialogPinned#6e6fe51c flags:# pinned:flags.0?true folder_id:flags.1?int peer:DialogPeer = Update;\nupdatePinnedDialogs#fa0f3ca2 flags:# folder_id:flags.1?int order:flags.0?Vector = Update;\nupdateBotWebhookJSON#8317c0c3 data:DataJSON = Update;\nupdateBotWebhookJSONQuery#9b9240a6 query_id:long data:DataJSON timeout:int = Update;\nupdateBotShippingQuery#b5aefd7d query_id:long user_id:long payload:bytes shipping_address:PostAddress = Update;\nupdateBotPrecheckoutQuery#8caa9a96 flags:# query_id:long user_id:long payload:bytes info:flags.0?PaymentRequestedInfo shipping_option_id:flags.1?string currency:string total_amount:long = Update;\nupdatePhoneCall#ab0f6b1e phone_call:PhoneCall = Update;\nupdateLangPackTooLong#46560264 lang_code:string = Update;\nupdateLangPack#56022f4d difference:LangPackDifference = Update;\nupdateFavedStickers#e511996d = Update;\nupdateChannelReadMessagesContents#44bdd535 channel_id:long messages:Vector = Update;\nupdateContactsReset#7084a7be = Update;\nupdateChannelAvailableMessages#b23fc698 channel_id:long available_min_id:int = Update;\nupdateDialogUnreadMark#e16459c3 flags:# unread:flags.0?true peer:DialogPeer = Update;\nupdateMessagePoll#aca1657b flags:# poll_id:long poll:flags.0?Poll results:PollResults = Update;\nupdateChatDefaultBannedRights#54c01850 peer:Peer default_banned_rights:ChatBannedRights version:int = Update;\nupdateFolderPeers#19360dc0 folder_peers:Vector pts:int pts_count:int = Update;\nupdatePeerSettings#6a7e7366 peer:Peer settings:PeerSettings = Update;\nupdatePeerLocated#b4afcfb0 peers:Vector = Update;\nupdateNewScheduledMessage#39a51dfb message:Message = Update;\nupdateDeleteScheduledMessages#90866cee peer:Peer messages:Vector = Update;\nupdateTheme#8216fba3 theme:Theme = Update;\nupdateGeoLiveViewed#871fb939 peer:Peer msg_id:int = Update;\nupdateLoginToken#564fe691 = Update;\nupdateMessagePollVote#106395c9 poll_id:long user_id:long options:Vector qts:int = Update;\nupdateDialogFilter#26ffde7d flags:# id:int filter:flags.0?DialogFilter = Update;\nupdateDialogFilterOrder#a5d72105 order:Vector = Update;\nupdateDialogFilters#3504914f = Update;\nupdatePhoneCallSignalingData#2661bf09 phone_call_id:long data:bytes = Update;\nupdateChannelMessageForwards#d29a27f4 channel_id:long id:int forwards:int = Update;\nupdateReadChannelDiscussionInbox#d6b19546 flags:# channel_id:long top_msg_id:int read_max_id:int broadcast_id:flags.0?long broadcast_post:flags.0?int = Update;\nupdateReadChannelDiscussionOutbox#695c9e7c channel_id:long top_msg_id:int read_max_id:int = Update;\nupdatePeerBlocked#246a4b22 peer_id:Peer blocked:Bool = Update;\nupdateChannelUserTyping#8c88c923 flags:# channel_id:long top_msg_id:flags.0?int from_id:Peer action:SendMessageAction = Update;\nupdatePinnedMessages#ed85eab5 flags:# pinned:flags.0?true peer:Peer messages:Vector pts:int pts_count:int = Update;\nupdatePinnedChannelMessages#5bb98608 flags:# pinned:flags.0?true channel_id:long messages:Vector pts:int pts_count:int = Update;\nupdateChat#f89a6a4e chat_id:long = Update;\nupdateGroupCallParticipants#f2ebdb4e call:InputGroupCall participants:Vector version:int = Update;\nupdateGroupCall#14b24500 chat_id:long call:GroupCall = Update;\nupdatePeerHistoryTTL#bb9bb9a5 flags:# peer:Peer ttl_period:flags.0?int = Update;\nupdateChatParticipant#d087663a flags:# chat_id:long date:int actor_id:long user_id:long prev_participant:flags.0?ChatParticipant new_participant:flags.1?ChatParticipant invite:flags.2?ExportedChatInvite qts:int = Update;\nupdateChannelParticipant#985d3abb flags:# channel_id:long date:int actor_id:long user_id:long prev_participant:flags.0?ChannelParticipant new_participant:flags.1?ChannelParticipant invite:flags.2?ExportedChatInvite qts:int = Update;\nupdateBotStopped#c4870a49 user_id:long date:int stopped:Bool qts:int = Update;\nupdateGroupCallConnection#b783982 flags:# presentation:flags.0?true params:DataJSON = Update;\nupdateBotCommands#4d712f2e peer:Peer bot_id:long commands:Vector = Update;\nupdates.state#a56c2a3e pts:int qts:int date:int seq:int unread_count:int = updates.State;\nupdates.differenceEmpty#5d75a138 date:int seq:int = updates.Difference;\nupdates.difference#f49ca0 new_messages:Vector new_encrypted_messages:Vector other_updates:Vector chats:Vector users:Vector state:updates.State = updates.Difference;\nupdates.differenceSlice#a8fb1981 new_messages:Vector new_encrypted_messages:Vector other_updates:Vector chats:Vector users:Vector intermediate_state:updates.State = updates.Difference;\nupdates.differenceTooLong#4afe8f6d pts:int = updates.Difference;\nupdatesTooLong#e317af7e = Updates;\nupdateShortMessage#313bc7f8 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true id:int user_id:long message:string pts:int pts_count:int date:int fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?long reply_to:flags.3?MessageReplyHeader entities:flags.7?Vector ttl_period:flags.25?int = Updates;\nupdateShortChatMessage#4d6deea5 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true id:int from_id:long chat_id:long message:string pts:int pts_count:int date:int fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?long reply_to:flags.3?MessageReplyHeader entities:flags.7?Vector ttl_period:flags.25?int = Updates;\nupdateShort#78d4dec1 update:Update date:int = Updates;\nupdatesCombined#725b04c3 updates:Vector users:Vector chats:Vector date:int seq_start:int seq:int = Updates;\nupdates#74ae4240 updates:Vector users:Vector chats:Vector date:int seq:int = Updates;\nupdateShortSentMessage#9015e101 flags:# out:flags.1?true id:int pts:int pts_count:int date:int media:flags.9?MessageMedia entities:flags.7?Vector ttl_period:flags.25?int = Updates;\nphotos.photos#8dca6aa5 photos:Vector users:Vector = photos.Photos;\nphotos.photosSlice#15051f54 count:int photos:Vector users:Vector = photos.Photos;\nphotos.photo#20212ca8 photo:Photo users:Vector = photos.Photo;\nupload.file#96a18d5 type:storage.FileType mtime:int bytes:bytes = upload.File;\nupload.fileCdnRedirect#f18cda44 dc_id:int file_token:bytes encryption_key:bytes encryption_iv:bytes file_hashes:Vector = upload.File;\ndcOption#18b7a10d flags:# ipv6:flags.0?true media_only:flags.1?true tcpo_only:flags.2?true cdn:flags.3?true static:flags.4?true id:int ip_address:string port:int secret:flags.10?bytes = DcOption;\nconfig#330b4067 flags:# phonecalls_enabled:flags.1?true default_p2p_contacts:flags.3?true preload_featured_stickers:flags.4?true ignore_phone_entities:flags.5?true revoke_pm_inbox:flags.6?true blocked_mode:flags.8?true pfs_enabled:flags.13?true date:int expires:int test_mode:Bool this_dc:int dc_options:Vector dc_txt_domain_name:string chat_size_max:int megagroup_size_max:int forwarded_count_max:int online_update_period_ms:int offline_blur_timeout_ms:int offline_idle_timeout_ms:int online_cloud_timeout_ms:int notify_cloud_delay_ms:int notify_default_delay_ms:int push_chat_period_ms:int push_chat_limit:int saved_gifs_limit:int edit_time_limit:int revoke_time_limit:int revoke_pm_time_limit:int rating_e_decay:int stickers_recent_limit:int stickers_faved_limit:int channels_read_media_period:int tmp_sessions:flags.0?int pinned_dialogs_count_max:int pinned_infolder_count_max:int call_receive_timeout_ms:int call_ring_timeout_ms:int call_connect_timeout_ms:int call_packet_timeout_ms:int me_url_prefix:string autoupdate_url_prefix:flags.7?string gif_search_username:flags.9?string venue_search_username:flags.10?string img_search_username:flags.11?string static_maps_provider:flags.12?string caption_length_max:int message_length_max:int webfile_dc_id:int suggested_lang_code:flags.2?string lang_pack_version:flags.2?int base_lang_pack_version:flags.2?int = Config;\nnearestDc#8e1a1775 country:string this_dc:int nearest_dc:int = NearestDc;\nhelp.appUpdate#ccbbce30 flags:# can_not_skip:flags.0?true id:int version:string text:string entities:Vector document:flags.1?Document url:flags.2?string sticker:flags.3?Document = help.AppUpdate;\nhelp.noAppUpdate#c45a6536 = help.AppUpdate;\nhelp.inviteText#18cb9f78 message:string = help.InviteText;\nencryptedChatEmpty#ab7ec0a0 id:int = EncryptedChat;\nencryptedChatWaiting#66b25953 id:int access_hash:long date:int admin_id:long participant_id:long = EncryptedChat;\nencryptedChatRequested#48f1d94c flags:# folder_id:flags.0?int id:int access_hash:long date:int admin_id:long participant_id:long g_a:bytes = EncryptedChat;\nencryptedChat#61f0d4c7 id:int access_hash:long date:int admin_id:long participant_id:long g_a_or_b:bytes key_fingerprint:long = EncryptedChat;\nencryptedChatDiscarded#1e1c7c45 flags:# history_deleted:flags.0?true id:int = EncryptedChat;\ninputEncryptedChat#f141b5e1 chat_id:int access_hash:long = InputEncryptedChat;\nencryptedFileEmpty#c21f497e = EncryptedFile;\nencryptedFile#4a70994c id:long access_hash:long size:int dc_id:int key_fingerprint:int = EncryptedFile;\ninputEncryptedFileEmpty#1837c364 = InputEncryptedFile;\ninputEncryptedFileUploaded#64bd0306 id:long parts:int md5_checksum:string key_fingerprint:int = InputEncryptedFile;\ninputEncryptedFile#5a17b5e5 id:long access_hash:long = InputEncryptedFile;\ninputEncryptedFileBigUploaded#2dc173c8 id:long parts:int key_fingerprint:int = InputEncryptedFile;\nencryptedMessage#ed18c118 random_id:long chat_id:int date:int bytes:bytes file:EncryptedFile = EncryptedMessage;\nencryptedMessageService#23734b06 random_id:long chat_id:int date:int bytes:bytes = EncryptedMessage;\nmessages.dhConfigNotModified#c0e24635 random:bytes = messages.DhConfig;\nmessages.dhConfig#2c221edd g:int p:bytes version:int random:bytes = messages.DhConfig;\nmessages.sentEncryptedMessage#560f8935 date:int = messages.SentEncryptedMessage;\nmessages.sentEncryptedFile#9493ff32 date:int file:EncryptedFile = messages.SentEncryptedMessage;\ninputDocumentEmpty#72f0eaae = InputDocument;\ninputDocument#1abfb575 id:long access_hash:long file_reference:bytes = InputDocument;\ndocumentEmpty#36f8c871 id:long = Document;\ndocument#1e87342b flags:# id:long access_hash:long file_reference:bytes date:int mime_type:string size:int thumbs:flags.0?Vector video_thumbs:flags.1?Vector dc_id:int attributes:Vector = Document;\nhelp.support#17c6b5f6 phone_number:string user:User = help.Support;\nnotifyPeer#9fd40bd8 peer:Peer = NotifyPeer;\nnotifyUsers#b4c83b4c = NotifyPeer;\nnotifyChats#c007cec3 = NotifyPeer;\nnotifyBroadcasts#d612e8ef = NotifyPeer;\nsendMessageTypingAction#16bf744e = SendMessageAction;\nsendMessageCancelAction#fd5ec8f5 = SendMessageAction;\nsendMessageRecordVideoAction#a187d66f = SendMessageAction;\nsendMessageUploadVideoAction#e9763aec progress:int = SendMessageAction;\nsendMessageRecordAudioAction#d52f73f7 = SendMessageAction;\nsendMessageUploadAudioAction#f351d7ab progress:int = SendMessageAction;\nsendMessageUploadPhotoAction#d1d34a26 progress:int = SendMessageAction;\nsendMessageUploadDocumentAction#aa0cd9e4 progress:int = SendMessageAction;\nsendMessageGeoLocationAction#176f8ba1 = SendMessageAction;\nsendMessageChooseContactAction#628cbc6f = SendMessageAction;\nsendMessageGamePlayAction#dd6a8f48 = SendMessageAction;\nsendMessageRecordRoundAction#88f27fbc = SendMessageAction;\nsendMessageUploadRoundAction#243e1c66 progress:int = SendMessageAction;\nspeakingInGroupCallAction#d92c2285 = SendMessageAction;\nsendMessageHistoryImportAction#dbda9246 progress:int = SendMessageAction;\nsendMessageChooseStickerAction#b05ac6b1 = SendMessageAction;\nsendMessageEmojiInteraction#25972bcb emoticon:string msg_id:int interaction:DataJSON = SendMessageAction;\nsendMessageEmojiInteractionSeen#b665902e emoticon:string = SendMessageAction;\ncontacts.found#b3134d9d my_results:Vector results:Vector chats:Vector users:Vector = contacts.Found;\ninputPrivacyKeyStatusTimestamp#4f96cb18 = InputPrivacyKey;\ninputPrivacyKeyChatInvite#bdfb0426 = InputPrivacyKey;\ninputPrivacyKeyPhoneCall#fabadc5f = InputPrivacyKey;\ninputPrivacyKeyPhoneP2P#db9e70d2 = InputPrivacyKey;\ninputPrivacyKeyForwards#a4dd4c08 = InputPrivacyKey;\ninputPrivacyKeyProfilePhoto#5719bacc = InputPrivacyKey;\ninputPrivacyKeyPhoneNumber#352dafa = InputPrivacyKey;\ninputPrivacyKeyAddedByPhone#d1219bdd = InputPrivacyKey;\nprivacyKeyStatusTimestamp#bc2eab30 = PrivacyKey;\nprivacyKeyChatInvite#500e6dfa = PrivacyKey;\nprivacyKeyPhoneCall#3d662b7b = PrivacyKey;\nprivacyKeyPhoneP2P#39491cc8 = PrivacyKey;\nprivacyKeyForwards#69ec56a3 = PrivacyKey;\nprivacyKeyProfilePhoto#96151fed = PrivacyKey;\nprivacyKeyPhoneNumber#d19ae46d = PrivacyKey;\nprivacyKeyAddedByPhone#42ffd42b = PrivacyKey;\ninputPrivacyValueAllowContacts#d09e07b = InputPrivacyRule;\ninputPrivacyValueAllowAll#184b35ce = InputPrivacyRule;\ninputPrivacyValueAllowUsers#131cc67f users:Vector = InputPrivacyRule;\ninputPrivacyValueDisallowContacts#ba52007 = InputPrivacyRule;\ninputPrivacyValueDisallowAll#d66b66c9 = InputPrivacyRule;\ninputPrivacyValueDisallowUsers#90110467 users:Vector = InputPrivacyRule;\ninputPrivacyValueAllowChatParticipants#840649cf chats:Vector = InputPrivacyRule;\ninputPrivacyValueDisallowChatParticipants#e94f0f86 chats:Vector = InputPrivacyRule;\nprivacyValueAllowContacts#fffe1bac = PrivacyRule;\nprivacyValueAllowAll#65427b82 = PrivacyRule;\nprivacyValueAllowUsers#b8905fb2 users:Vector = PrivacyRule;\nprivacyValueDisallowContacts#f888fa1a = PrivacyRule;\nprivacyValueDisallowAll#8b73e763 = PrivacyRule;\nprivacyValueDisallowUsers#e4621141 users:Vector = PrivacyRule;\nprivacyValueAllowChatParticipants#6b134e8e chats:Vector = PrivacyRule;\nprivacyValueDisallowChatParticipants#41c87565 chats:Vector = PrivacyRule;\naccount.privacyRules#50a04e45 rules:Vector chats:Vector users:Vector = account.PrivacyRules;\naccountDaysTTL#b8d0afdf days:int = AccountDaysTTL;\ndocumentAttributeImageSize#6c37c15c w:int h:int = DocumentAttribute;\ndocumentAttributeAnimated#11b58939 = DocumentAttribute;\ndocumentAttributeSticker#6319d612 flags:# mask:flags.1?true alt:string stickerset:InputStickerSet mask_coords:flags.0?MaskCoords = DocumentAttribute;\ndocumentAttributeVideo#ef02ce6 flags:# round_message:flags.0?true supports_streaming:flags.1?true duration:int w:int h:int = DocumentAttribute;\ndocumentAttributeAudio#9852f9c6 flags:# voice:flags.10?true duration:int title:flags.0?string performer:flags.1?string waveform:flags.2?bytes = DocumentAttribute;\ndocumentAttributeFilename#15590068 file_name:string = DocumentAttribute;\ndocumentAttributeHasStickers#9801d2f7 = DocumentAttribute;\nmessages.stickersNotModified#f1749a22 = messages.Stickers;\nmessages.stickers#30a6ec7e hash:long stickers:Vector = messages.Stickers;\nstickerPack#12b299d4 emoticon:string documents:Vector = StickerPack;\nmessages.allStickersNotModified#e86602c3 = messages.AllStickers;\nmessages.allStickers#cdbbcebb hash:long sets:Vector = messages.AllStickers;\nmessages.affectedMessages#84d19185 pts:int pts_count:int = messages.AffectedMessages;\nwebPageEmpty#eb1477e8 id:long = WebPage;\nwebPagePending#c586da1c id:long date:int = WebPage;\nwebPage#e89c45b2 flags:# id:long url:string display_url:string hash:int type:flags.0?string site_name:flags.1?string title:flags.2?string description:flags.3?string photo:flags.4?Photo embed_url:flags.5?string embed_type:flags.5?string embed_width:flags.6?int embed_height:flags.6?int duration:flags.7?int author:flags.8?string document:flags.9?Document cached_page:flags.10?Page attributes:flags.12?Vector = WebPage;\nwebPageNotModified#7311ca11 flags:# cached_page_views:flags.0?int = WebPage;\nauthorization#ad01d61d flags:# current:flags.0?true official_app:flags.1?true password_pending:flags.2?true hash:long device_model:string platform:string system_version:string api_id:int app_name:string app_version:string date_created:int date_active:int ip:string country:string region:string = Authorization;\naccount.authorizations#1250abde authorizations:Vector = 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#b18105e8 flags:# revoked:flags.0?true permanent:flags.5?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 = ExportedChatInvite;\nchatInviteAlready#5a686d7c chat:Chat = ChatInvite;\nchatInvite#dfc2f58e flags:# channel:flags.0?true broadcast:flags.1?true public:flags.2?true megagroup:flags.3?true title:string photo:Photo participants_count:int participants:flags.4?Vector = ChatInvite;\nchatInvitePeek#61695cb0 chat:Chat expires:int = ChatInvite;\ninputStickerSetEmpty#ffb62b95 = InputStickerSet;\ninputStickerSetID#9de7a269 id:long access_hash:long = InputStickerSet;\ninputStickerSetShortName#861cc8a0 short_name:string = InputStickerSet;\ninputStickerSetAnimatedEmoji#28703c8 = InputStickerSet;\ninputStickerSetDice#e67f520e emoticon:string = InputStickerSet;\ninputStickerSetAnimatedEmojiAnimations#cde3739 = InputStickerSet;\nstickerSet#d7df217a flags:# archived:flags.1?true official:flags.2?true masks:flags.3?true animated:flags.5?true installed_date:flags.0?int id:long access_hash:long title:string short_name:string thumbs:flags.4?Vector thumb_dc_id:flags.4?int thumb_version:flags.4?int count:int hash:int = StickerSet;\nmessages.stickerSet#b60a24a6 set:StickerSet packs:Vector documents:Vector = messages.StickerSet;\nbotCommand#c27ac8c7 command:string description:string = BotCommand;\nbotInfo#1b74b335 user_id:long description:string commands:Vector = BotInfo;\nkeyboardButton#a2fa4880 text:string = KeyboardButton;\nkeyboardButtonUrl#258aff05 text:string url:string = KeyboardButton;\nkeyboardButtonCallback#35bbdb6b flags:# requires_password:flags.0?true text:string data:bytes = KeyboardButton;\nkeyboardButtonRequestPhone#b16a6c29 text:string = KeyboardButton;\nkeyboardButtonRequestGeoLocation#fc796b3f text:string = KeyboardButton;\nkeyboardButtonSwitchInline#568a748 flags:# same_peer:flags.0?true text:string query:string = KeyboardButton;\nkeyboardButtonGame#50f41ccf text:string = KeyboardButton;\nkeyboardButtonBuy#afd93fbb text:string = KeyboardButton;\nkeyboardButtonUrlAuth#10b78d29 flags:# text:string fwd_text:flags.0?string url:string button_id:int = KeyboardButton;\ninputKeyboardButtonUrlAuth#d02e7fd4 flags:# request_write_access:flags.0?true text:string fwd_text:flags.1?string url:string bot:InputUser = KeyboardButton;\nkeyboardButtonRequestPoll#bbc7515d flags:# quiz:flags.0?Bool text:string = KeyboardButton;\nkeyboardButtonRow#77608b83 buttons:Vector = KeyboardButtonRow;\nreplyKeyboardHide#a03e5b85 flags:# selective:flags.2?true = ReplyMarkup;\nreplyKeyboardForceReply#86b40b08 flags:# single_use:flags.1?true selective:flags.2?true placeholder:flags.3?string = ReplyMarkup;\nreplyKeyboardMarkup#85dd99d1 flags:# resize:flags.0?true single_use:flags.1?true selective:flags.2?true rows:Vector placeholder:flags.3?string = ReplyMarkup;\nreplyInlineMarkup#48a30254 rows:Vector = ReplyMarkup;\nmessageEntityUnknown#bb92ba95 offset:int length:int = MessageEntity;\nmessageEntityMention#fa04579d offset:int length:int = MessageEntity;\nmessageEntityHashtag#6f635b0d offset:int length:int = MessageEntity;\nmessageEntityBotCommand#6cef8ac7 offset:int length:int = MessageEntity;\nmessageEntityUrl#6ed02538 offset:int length:int = MessageEntity;\nmessageEntityEmail#64e475c2 offset:int length:int = MessageEntity;\nmessageEntityBold#bd610bc9 offset:int length:int = MessageEntity;\nmessageEntityItalic#826f8b60 offset:int length:int = MessageEntity;\nmessageEntityCode#28a20571 offset:int length:int = MessageEntity;\nmessageEntityPre#73924be0 offset:int length:int language:string = MessageEntity;\nmessageEntityTextUrl#76a6d327 offset:int length:int url:string = MessageEntity;\nmessageEntityMentionName#dc7b1140 offset:int length:int user_id:long = MessageEntity;\ninputMessageEntityMentionName#208e68c9 offset:int length:int user_id:InputUser = MessageEntity;\nmessageEntityPhone#9b69e34b offset:int length:int = MessageEntity;\nmessageEntityCashtag#4c4e743f offset:int length:int = MessageEntity;\nmessageEntityUnderline#9c4e7e8b offset:int length:int = MessageEntity;\nmessageEntityStrike#bf0693d4 offset:int length:int = MessageEntity;\nmessageEntityBlockquote#20df5d0 offset:int length:int = MessageEntity;\nmessageEntityBankCard#761e6af4 offset:int length:int = MessageEntity;\ninputChannelEmpty#ee8c1e86 = InputChannel;\ninputChannel#f35aec28 channel_id:long access_hash:long = InputChannel;\ninputChannelFromMessage#5b934f9d peer:InputPeer msg_id:int channel_id:long = InputChannel;\ncontacts.resolvedPeer#7f077ad9 peer:Peer chats:Vector users:Vector = contacts.ResolvedPeer;\nmessageRange#ae30253 min_id:int max_id:int = MessageRange;\nupdates.channelDifferenceEmpty#3e11affb flags:# final:flags.0?true pts:int timeout:flags.1?int = updates.ChannelDifference;\nupdates.channelDifferenceTooLong#a4bcc6fe flags:# final:flags.0?true timeout:flags.1?int dialog:Dialog messages:Vector chats:Vector users:Vector = updates.ChannelDifference;\nupdates.channelDifference#2064674e flags:# final:flags.0?true pts:int timeout:flags.1?int new_messages:Vector other_updates:Vector chats:Vector users:Vector = updates.ChannelDifference;\nchannelMessagesFilterEmpty#94d42ee7 = ChannelMessagesFilter;\nchannelMessagesFilter#cd77d957 flags:# exclude_new_messages:flags.1?true ranges:Vector = ChannelMessagesFilter;\nchannelParticipant#c00c07c0 user_id:long date:int = ChannelParticipant;\nchannelParticipantSelf#28a8bc67 user_id:long inviter_id:long date:int = ChannelParticipant;\nchannelParticipantCreator#2fe601d3 flags:# user_id:long admin_rights:ChatAdminRights rank:flags.0?string = ChannelParticipant;\nchannelParticipantAdmin#34c3bb53 flags:# can_edit:flags.0?true self:flags.1?true user_id:long inviter_id:flags.1?long promoted_by:long date:int admin_rights:ChatAdminRights rank:flags.2?string = ChannelParticipant;\nchannelParticipantBanned#6df8014e flags:# left:flags.0?true peer:Peer kicked_by:long date:int banned_rights:ChatBannedRights = ChannelParticipant;\nchannelParticipantLeft#1b03f006 peer:Peer = ChannelParticipant;\nchannelParticipantsRecent#de3f3c79 = ChannelParticipantsFilter;\nchannelParticipantsAdmins#b4608969 = ChannelParticipantsFilter;\nchannelParticipantsKicked#a3b54985 q:string = ChannelParticipantsFilter;\nchannelParticipantsBots#b0d1865b = ChannelParticipantsFilter;\nchannelParticipantsBanned#1427a5e1 q:string = ChannelParticipantsFilter;\nchannelParticipantsSearch#656ac4b q:string = ChannelParticipantsFilter;\nchannelParticipantsContacts#bb6ae88d q:string = ChannelParticipantsFilter;\nchannelParticipantsMentions#e04b5ceb flags:# q:flags.0?string top_msg_id:flags.1?int = ChannelParticipantsFilter;\nchannels.channelParticipants#9ab0feaf count:int participants:Vector chats:Vector users:Vector = channels.ChannelParticipants;\nchannels.channelParticipantsNotModified#f0173fe9 = channels.ChannelParticipants;\nchannels.channelParticipant#dfb80317 participant:ChannelParticipant chats:Vector users:Vector = channels.ChannelParticipant;\nhelp.termsOfService#780a0310 flags:# popup:flags.0?true id:DataJSON text:string entities:Vector min_age_confirm:flags.1?int = help.TermsOfService;\nmessages.savedGifsNotModified#e8025ca2 = messages.SavedGifs;\nmessages.savedGifs#84a02a0d hash:long gifs:Vector = messages.SavedGifs;\ninputBotInlineMessageMediaAuto#3380c786 flags:# message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageText#3dcd7a87 flags:# no_webpage:flags.0?true message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaGeo#96929a85 flags:# geo_point:InputGeoPoint heading:flags.0?int period:flags.1?int proximity_notification_radius:flags.3?int reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaVenue#417bbf11 flags:# geo_point:InputGeoPoint title:string address:string provider:string venue_id:string venue_type:string reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaContact#a6edbffd flags:# phone_number:string first_name:string last_name:string vcard:string reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageGame#4b425864 flags:# reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaInvoice#d7e78225 flags:# title:string description:string photo:flags.0?InputWebDocument invoice:Invoice payload:bytes provider:string provider_data:DataJSON reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineResult#88bf9319 flags:# id:string type:string title:flags.1?string description:flags.2?string url:flags.3?string thumb:flags.4?InputWebDocument content:flags.5?InputWebDocument send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultPhoto#a8d864a7 id:string type:string photo:InputPhoto send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultDocument#fff8fdc4 flags:# id:string type:string title:flags.1?string description:flags.2?string document:InputDocument send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultGame#4fa417f2 id:string short_name:string send_message:InputBotInlineMessage = InputBotInlineResult;\nbotInlineMessageMediaAuto#764cf810 flags:# message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageText#8c7f65e2 flags:# no_webpage:flags.0?true message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaGeo#51846fd flags:# geo:GeoPoint heading:flags.0?int period:flags.1?int proximity_notification_radius:flags.3?int reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaVenue#8a86659c flags:# geo:GeoPoint title:string address:string provider:string venue_id:string venue_type:string reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaContact#18d1cdc2 flags:# phone_number:string first_name:string last_name:string vcard:string reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaInvoice#354a9b09 flags:# shipping_address_requested:flags.1?true test:flags.3?true title:string description:string photo:flags.0?WebDocument currency:string total_amount:long reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineResult#11965f3a flags:# id:string type:string title:flags.1?string description:flags.2?string url:flags.3?string thumb:flags.4?WebDocument content:flags.5?WebDocument send_message:BotInlineMessage = BotInlineResult;\nbotInlineMediaResult#17db940b flags:# id:string type:string photo:flags.0?Photo document:flags.1?Document title:flags.2?string description:flags.3?string send_message:BotInlineMessage = BotInlineResult;\nmessages.botResults#947ca848 flags:# gallery:flags.0?true query_id:long next_offset:flags.1?string switch_pm:flags.2?InlineBotSwitchPM results:Vector cache_time:int users:Vector = messages.BotResults;\nexportedMessageLink#5dab1af4 link:string html:string = ExportedMessageLink;\nmessageFwdHeader#5f777dce flags:# imported:flags.7?true from_id:flags.0?Peer from_name:flags.5?string date:int channel_post:flags.2?int post_author:flags.3?string saved_from_peer:flags.4?Peer saved_from_msg_id:flags.4?int psa_type:flags.6?string = MessageFwdHeader;\nauth.codeTypeSms#72a3158c = auth.CodeType;\nauth.codeTypeCall#741cd3e3 = auth.CodeType;\nauth.codeTypeFlashCall#226ccefb = auth.CodeType;\nauth.sentCodeTypeApp#3dbb5986 length:int = auth.SentCodeType;\nauth.sentCodeTypeSms#c000bba2 length:int = auth.SentCodeType;\nauth.sentCodeTypeCall#5353e5a7 length:int = auth.SentCodeType;\nauth.sentCodeTypeFlashCall#ab03c6d9 pattern:string = auth.SentCodeType;\nmessages.botCallbackAnswer#36585ea4 flags:# alert:flags.1?true has_url:flags.3?true native_ui:flags.4?true message:flags.0?string url:flags.2?string cache_time:int = messages.BotCallbackAnswer;\nmessages.messageEditData#26b5dde6 flags:# caption:flags.0?true = messages.MessageEditData;\ninputBotInlineMessageID#890c3d89 dc_id:int id:long access_hash:long = InputBotInlineMessageID;\ninputBotInlineMessageID64#b6d915d7 dc_id:int owner_id:long id:int access_hash:long = InputBotInlineMessageID;\ninlineBotSwitchPM#3c20629f text:string start_param:string = InlineBotSwitchPM;\nmessages.peerDialogs#3371c354 dialogs:Vector messages:Vector chats:Vector users:Vector state:updates.State = messages.PeerDialogs;\ntopPeer#edcdc05b peer:Peer rating:double = TopPeer;\ntopPeerCategoryBotsPM#ab661b5b = TopPeerCategory;\ntopPeerCategoryBotsInline#148677e2 = TopPeerCategory;\ntopPeerCategoryCorrespondents#637b7ed = TopPeerCategory;\ntopPeerCategoryGroups#bd17a14a = TopPeerCategory;\ntopPeerCategoryChannels#161d9628 = TopPeerCategory;\ntopPeerCategoryPhoneCalls#1e76a78c = TopPeerCategory;\ntopPeerCategoryForwardUsers#a8406ca9 = TopPeerCategory;\ntopPeerCategoryForwardChats#fbeec0f0 = TopPeerCategory;\ntopPeerCategoryPeers#fb834291 category:TopPeerCategory count:int peers:Vector = TopPeerCategoryPeers;\ncontacts.topPeersNotModified#de266ef5 = contacts.TopPeers;\ncontacts.topPeers#70b772a8 categories:Vector chats:Vector users:Vector = contacts.TopPeers;\ncontacts.topPeersDisabled#b52c939d = contacts.TopPeers;\ndraftMessageEmpty#1b0c841a flags:# date:flags.0?int = DraftMessage;\ndraftMessage#fd8e711f flags:# no_webpage:flags.1?true reply_to_msg_id:flags.0?int message:string entities:flags.3?Vector date:int = DraftMessage;\nmessages.featuredStickersNotModified#c6dc0c66 count:int = messages.FeaturedStickers;\nmessages.featuredStickers#84c02310 hash:long count:int sets:Vector unread:Vector = messages.FeaturedStickers;\nmessages.recentStickersNotModified#b17f890 = messages.RecentStickers;\nmessages.recentStickers#88d37c56 hash:long packs:Vector stickers:Vector dates:Vector = messages.RecentStickers;\nmessages.archivedStickers#4fcba9c8 count:int sets:Vector = messages.ArchivedStickers;\nmessages.stickerSetInstallResultSuccess#38641628 = messages.StickerSetInstallResult;\nmessages.stickerSetInstallResultArchive#35e410a8 sets:Vector = messages.StickerSetInstallResult;\nstickerSetCovered#6410a5d2 set:StickerSet cover:Document = StickerSetCovered;\nstickerSetMultiCovered#3407e51b set:StickerSet covers:Vector = StickerSetCovered;\nmaskCoords#aed6dbb2 n:int x:double y:double zoom:double = MaskCoords;\ninputStickeredMediaPhoto#4a992157 id:InputPhoto = InputStickeredMedia;\ninputStickeredMediaDocument#438865b id:InputDocument = InputStickeredMedia;\ngame#bdf9653b flags:# id:long access_hash:long short_name:string title:string description:string photo:Photo document:flags.0?Document = Game;\ninputGameID#32c3e77 id:long access_hash:long = InputGame;\ninputGameShortName#c331e80a bot_id:InputUser short_name:string = InputGame;\nhighScore#73a379eb pos:int user_id:long score:int = HighScore;\nmessages.highScores#9a3bfd99 scores:Vector users:Vector = messages.HighScores;\ntextEmpty#dc3d824f = RichText;\ntextPlain#744694e0 text:string = RichText;\ntextBold#6724abc4 text:RichText = RichText;\ntextItalic#d912a59c text:RichText = RichText;\ntextUnderline#c12622c4 text:RichText = RichText;\ntextStrike#9bf8bb95 text:RichText = RichText;\ntextFixed#6c3f19b9 text:RichText = RichText;\ntextUrl#3c2884c1 text:RichText url:string webpage_id:long = RichText;\ntextEmail#de5a0dd6 text:RichText email:string = RichText;\ntextConcat#7e6260d7 texts:Vector = RichText;\ntextSubscript#ed6a8504 text:RichText = RichText;\ntextSuperscript#c7fb5e01 text:RichText = RichText;\ntextMarked#34b8621 text:RichText = RichText;\ntextPhone#1ccb966a text:RichText phone:string = RichText;\ntextImage#81ccf4f document_id:long w:int h:int = RichText;\ntextAnchor#35553762 text:RichText name:string = RichText;\npageBlockUnsupported#13567e8a = PageBlock;\npageBlockTitle#70abc3fd text:RichText = PageBlock;\npageBlockSubtitle#8ffa9a1f text:RichText = PageBlock;\npageBlockAuthorDate#baafe5e0 author:RichText published_date:int = PageBlock;\npageBlockHeader#bfd064ec text:RichText = PageBlock;\npageBlockSubheader#f12bb6e1 text:RichText = PageBlock;\npageBlockParagraph#467a0766 text:RichText = PageBlock;\npageBlockPreformatted#c070d93e text:RichText language:string = PageBlock;\npageBlockFooter#48870999 text:RichText = PageBlock;\npageBlockDivider#db20b188 = PageBlock;\npageBlockAnchor#ce0d37b0 name:string = PageBlock;\npageBlockList#e4e88011 items:Vector = PageBlock;\npageBlockBlockquote#263d7c26 text:RichText caption:RichText = PageBlock;\npageBlockPullquote#4f4456d3 text:RichText caption:RichText = PageBlock;\npageBlockPhoto#1759c560 flags:# photo_id:long caption:PageCaption url:flags.0?string webpage_id:flags.0?long = PageBlock;\npageBlockVideo#7c8fe7b6 flags:# autoplay:flags.0?true loop:flags.1?true video_id:long caption:PageCaption = PageBlock;\npageBlockCover#39f23300 cover:PageBlock = PageBlock;\npageBlockEmbed#a8718dc5 flags:# full_width:flags.0?true allow_scrolling:flags.3?true url:flags.1?string html:flags.2?string poster_photo_id:flags.4?long w:flags.5?int h:flags.5?int caption:PageCaption = PageBlock;\npageBlockEmbedPost#f259a80b url:string webpage_id:long author_photo_id:long author:string date:int blocks:Vector caption:PageCaption = PageBlock;\npageBlockCollage#65a0fa4d items:Vector caption:PageCaption = PageBlock;\npageBlockSlideshow#31f9590 items:Vector caption:PageCaption = PageBlock;\npageBlockChannel#ef1751b5 channel:Chat = PageBlock;\npageBlockAudio#804361ea audio_id:long caption:PageCaption = PageBlock;\npageBlockKicker#1e148390 text:RichText = PageBlock;\npageBlockTable#bf4dea82 flags:# bordered:flags.0?true striped:flags.1?true title:RichText rows:Vector = PageBlock;\npageBlockOrderedList#9a8ae1e1 items:Vector = PageBlock;\npageBlockDetails#76768bed flags:# open:flags.0?true blocks:Vector title:RichText = PageBlock;\npageBlockRelatedArticles#16115a96 title:RichText articles:Vector = PageBlock;\npageBlockMap#a44f3ef6 geo:GeoPoint zoom:int w:int h:int caption:PageCaption = PageBlock;\nphoneCallDiscardReasonMissed#85e42301 = PhoneCallDiscardReason;\nphoneCallDiscardReasonDisconnect#e095c1a0 = PhoneCallDiscardReason;\nphoneCallDiscardReasonHangup#57adc690 = PhoneCallDiscardReason;\nphoneCallDiscardReasonBusy#faf7e8c9 = PhoneCallDiscardReason;\ndataJSON#7d748d04 data:string = DataJSON;\nlabeledPrice#cb296bf8 label:string amount:long = LabeledPrice;\ninvoice#cd886e0 flags:# test:flags.0?true name_requested:flags.1?true phone_requested:flags.2?true email_requested:flags.3?true shipping_address_requested:flags.4?true flexible:flags.5?true phone_to_provider:flags.6?true email_to_provider:flags.7?true currency:string prices:Vector max_tip_amount:flags.8?long suggested_tip_amounts:flags.8?Vector = Invoice;\npaymentCharge#ea02c27e id:string provider_charge_id:string = PaymentCharge;\npostAddress#1e8caaeb street_line1:string street_line2:string city:string state:string country_iso2:string post_code:string = PostAddress;\npaymentRequestedInfo#909c3f94 flags:# name:flags.0?string phone:flags.1?string email:flags.2?string shipping_address:flags.3?PostAddress = PaymentRequestedInfo;\npaymentSavedCredentialsCard#cdc27a1f id:string title:string = PaymentSavedCredentials;\nwebDocument#1c570ed1 url:string access_hash:long size:int mime_type:string attributes:Vector = WebDocument;\nwebDocumentNoProxy#f9c8bcc6 url:string size:int mime_type:string attributes:Vector = WebDocument;\ninputWebDocument#9bed434d url:string size:int mime_type:string attributes:Vector = InputWebDocument;\ninputWebFileLocation#c239d686 url:string access_hash:long = InputWebFileLocation;\ninputWebFileGeoPointLocation#9f2221c9 geo_point:InputGeoPoint access_hash:long w:int h:int zoom:int scale:int = InputWebFileLocation;\nupload.webFile#21e753bc size:int mime_type:string file_type:storage.FileType mtime:int bytes:bytes = upload.WebFile;\npayments.paymentForm#1694761b flags:# can_save_credentials:flags.2?true password_missing:flags.3?true form_id:long bot_id:long invoice:Invoice provider_id:long url:string native_provider:flags.4?string native_params:flags.4?DataJSON saved_info:flags.0?PaymentRequestedInfo saved_credentials:flags.1?PaymentSavedCredentials users:Vector = payments.PaymentForm;\npayments.validatedRequestedInfo#d1451883 flags:# id:flags.0?string shipping_options:flags.1?Vector = payments.ValidatedRequestedInfo;\npayments.paymentResult#4e5f810d updates:Updates = payments.PaymentResult;\npayments.paymentVerificationNeeded#d8411139 url:string = payments.PaymentResult;\npayments.paymentReceipt#70c4fe03 flags:# date:int bot_id:long provider_id:long title:string description:string photo:flags.2?WebDocument invoice:Invoice info:flags.0?PaymentRequestedInfo shipping:flags.1?ShippingOption tip_amount:flags.3?long currency:string total_amount:long credentials_title:string users:Vector = payments.PaymentReceipt;\npayments.savedInfo#fb8fe43c flags:# has_saved_credentials:flags.1?true saved_info:flags.0?PaymentRequestedInfo = payments.SavedInfo;\ninputPaymentCredentialsSaved#c10eb2cf id:string tmp_password:bytes = InputPaymentCredentials;\ninputPaymentCredentials#3417d728 flags:# save:flags.0?true data:DataJSON = InputPaymentCredentials;\ninputPaymentCredentialsApplePay#aa1c39f payment_data:DataJSON = InputPaymentCredentials;\ninputPaymentCredentialsGooglePay#8ac32801 payment_token:DataJSON = InputPaymentCredentials;\naccount.tmpPassword#db64fd34 tmp_password:bytes valid_until:int = account.TmpPassword;\nshippingOption#b6213cdf id:string title:string prices:Vector = ShippingOption;\ninputStickerSetItem#ffa0a496 flags:# document:InputDocument emoji:string mask_coords:flags.0?MaskCoords = InputStickerSetItem;\ninputPhoneCall#1e36fded id:long access_hash:long = InputPhoneCall;\nphoneCallEmpty#5366c915 id:long = PhoneCall;\nphoneCallWaiting#c5226f17 flags:# video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long protocol:PhoneCallProtocol receive_date:flags.0?int = PhoneCall;\nphoneCallRequested#14b0ed0c flags:# video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long g_a_hash:bytes protocol:PhoneCallProtocol = PhoneCall;\nphoneCallAccepted#3660c311 flags:# video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long g_b:bytes protocol:PhoneCallProtocol = PhoneCall;\nphoneCall#967f7c67 flags:# p2p_allowed:flags.5?true video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long g_a_or_b:bytes key_fingerprint:long protocol:PhoneCallProtocol connections:Vector start_date:int = PhoneCall;\nphoneCallDiscarded#50ca4de1 flags:# need_rating:flags.2?true need_debug:flags.3?true video:flags.6?true id:long reason:flags.0?PhoneCallDiscardReason duration:flags.1?int = PhoneCall;\nphoneConnection#9d4c17c0 id:long ip:string ipv6:string port:int peer_tag:bytes = PhoneConnection;\nphoneConnectionWebrtc#635fe375 flags:# turn:flags.0?true stun:flags.1?true id:long ip:string ipv6:string port:int username:string password:string = PhoneConnection;\nphoneCallProtocol#fc878fc8 flags:# udp_p2p:flags.0?true udp_reflector:flags.1?true min_layer:int max_layer:int library_versions:Vector = PhoneCallProtocol;\nphone.phoneCall#ec82e140 phone_call:PhoneCall users:Vector = phone.PhoneCall;\nupload.cdnFileReuploadNeeded#eea8e46e request_token:bytes = upload.CdnFile;\nupload.cdnFile#a99fca4f bytes:bytes = upload.CdnFile;\ncdnPublicKey#c982eaba dc_id:int public_key:string = CdnPublicKey;\ncdnConfig#5725e40a public_keys:Vector = CdnConfig;\nlangPackString#cad181f6 key:string value:string = LangPackString;\nlangPackStringPluralized#6c47ac9f flags:# key:string zero_value:flags.0?string one_value:flags.1?string two_value:flags.2?string few_value:flags.3?string many_value:flags.4?string other_value:string = LangPackString;\nlangPackStringDeleted#2979eeb2 key:string = LangPackString;\nlangPackDifference#f385c1f6 lang_code:string from_version:int version:int strings:Vector = LangPackDifference;\nlangPackLanguage#eeca5ce3 flags:# official:flags.0?true rtl:flags.2?true beta:flags.3?true name:string native_name:string lang_code:string base_lang_code:flags.1?string plural_code:string strings_count:int translated_count:int translations_url:string = LangPackLanguage;\nchannelAdminLogEventActionChangeTitle#e6dfb825 prev_value:string new_value:string = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeAbout#55188a2e prev_value:string new_value:string = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeUsername#6a4afc38 prev_value:string new_value:string = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangePhoto#434bd2af prev_photo:Photo new_photo:Photo = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleInvites#1b7907ae new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleSignatures#26ae0971 new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionUpdatePinned#e9e82c18 message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionEditMessage#709b2405 prev_message:Message new_message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionDeleteMessage#42e047bb message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantJoin#183040d3 = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantLeave#f89777f2 = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantInvite#e31c34d8 participant:ChannelParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantToggleBan#e6d83d7e prev_participant:ChannelParticipant new_participant:ChannelParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantToggleAdmin#d5676710 prev_participant:ChannelParticipant new_participant:ChannelParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeStickerSet#b1c3caa7 prev_stickerset:InputStickerSet new_stickerset:InputStickerSet = ChannelAdminLogEventAction;\nchannelAdminLogEventActionTogglePreHistoryHidden#5f5c95f1 new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionDefaultBannedRights#2df5fc0a prev_banned_rights:ChatBannedRights new_banned_rights:ChatBannedRights = ChannelAdminLogEventAction;\nchannelAdminLogEventActionStopPoll#8f079643 message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeLinkedChat#50c7ac8 prev_value:long new_value:long = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeLocation#e6b76ae prev_value:ChannelLocation new_value:ChannelLocation = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleSlowMode#53909779 prev_value:int new_value:int = ChannelAdminLogEventAction;\nchannelAdminLogEventActionStartGroupCall#23209745 call:InputGroupCall = ChannelAdminLogEventAction;\nchannelAdminLogEventActionDiscardGroupCall#db9f9140 call:InputGroupCall = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantMute#f92424d2 participant:GroupCallParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantUnmute#e64429c0 participant:GroupCallParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleGroupCallSetting#56d6a247 join_muted:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantJoinByInvite#5cdada77 invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionExportedInviteDelete#5a50fca4 invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionExportedInviteRevoke#410a134e invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionExportedInviteEdit#e90ebb59 prev_invite:ExportedChatInvite new_invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantVolume#3e7f6847 participant:GroupCallParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeHistoryTTL#6e941a38 prev_value:int new_value:int = ChannelAdminLogEventAction;\nchannelAdminLogEvent#1fad68cd id:long date:int user_id:long action:ChannelAdminLogEventAction = ChannelAdminLogEvent;\nchannels.adminLogResults#ed8af74d events:Vector chats:Vector users:Vector = channels.AdminLogResults;\nchannelAdminLogEventsFilter#ea107ae4 flags:# join:flags.0?true leave:flags.1?true invite:flags.2?true ban:flags.3?true unban:flags.4?true kick:flags.5?true unkick:flags.6?true promote:flags.7?true demote:flags.8?true info:flags.9?true settings:flags.10?true pinned:flags.11?true edit:flags.12?true delete:flags.13?true group_call:flags.14?true invites:flags.15?true = ChannelAdminLogEventsFilter;\npopularContact#5ce14175 client_id:long importers:int = PopularContact;\nmessages.favedStickersNotModified#9e8fa6d3 = messages.FavedStickers;\nmessages.favedStickers#2cb51097 hash:long packs:Vector stickers:Vector = messages.FavedStickers;\nrecentMeUrlUnknown#46e1d13d url:string = RecentMeUrl;\nrecentMeUrlUser#b92c09e2 url:string user_id:long = RecentMeUrl;\nrecentMeUrlChat#b2da71d2 url:string chat_id:long = RecentMeUrl;\nrecentMeUrlChatInvite#eb49081d url:string chat_invite:ChatInvite = RecentMeUrl;\nrecentMeUrlStickerSet#bc0a57dc url:string set:StickerSetCovered = RecentMeUrl;\nhelp.recentMeUrls#e0310d7 urls:Vector chats:Vector users:Vector = help.RecentMeUrls;\ninputSingleMedia#1cc6e91f flags:# media:InputMedia random_id:long message:string entities:flags.0?Vector = InputSingleMedia;\nwebAuthorization#a6f8f452 hash:long bot_id:long domain:string browser:string platform:string date_created:int date_active:int ip:string region:string = WebAuthorization;\naccount.webAuthorizations#ed56c9fc authorizations:Vector users:Vector = account.WebAuthorizations;\ninputMessageID#a676a322 id:int = InputMessage;\ninputMessageReplyTo#bad88395 id:int = InputMessage;\ninputMessagePinned#86872538 = InputMessage;\ninputMessageCallbackQuery#acfa1a7e id:int query_id:long = InputMessage;\ninputDialogPeer#fcaafeb7 peer:InputPeer = InputDialogPeer;\ninputDialogPeerFolder#64600527 folder_id:int = InputDialogPeer;\ndialogPeer#e56dbf05 peer:Peer = DialogPeer;\ndialogPeerFolder#514519e2 folder_id:int = DialogPeer;\nmessages.foundStickerSetsNotModified#d54b65d = messages.FoundStickerSets;\nmessages.foundStickerSets#8af09dd2 hash:long sets:Vector = messages.FoundStickerSets;\nfileHash#6242c773 offset:int limit:int hash:bytes = FileHash;\ninputClientProxy#75588b3f address:string port:int = InputClientProxy;\nhelp.termsOfServiceUpdateEmpty#e3309f7f expires:int = help.TermsOfServiceUpdate;\nhelp.termsOfServiceUpdate#28ecf961 expires:int terms_of_service:help.TermsOfService = help.TermsOfServiceUpdate;\ninputSecureFileUploaded#3334b0f0 id:long parts:int md5_checksum:string file_hash:bytes secret:bytes = InputSecureFile;\ninputSecureFile#5367e5be id:long access_hash:long = InputSecureFile;\nsecureFileEmpty#64199744 = SecureFile;\nsecureFile#e0277a62 id:long access_hash:long size:int dc_id:int date:int file_hash:bytes secret:bytes = SecureFile;\nsecureData#8aeabec3 data:bytes data_hash:bytes secret:bytes = SecureData;\nsecurePlainPhone#7d6099dd phone:string = SecurePlainData;\nsecurePlainEmail#21ec5a5f email:string = SecurePlainData;\nsecureValueTypePersonalDetails#9d2a81e3 = SecureValueType;\nsecureValueTypePassport#3dac6a00 = SecureValueType;\nsecureValueTypeDriverLicense#6e425c4 = SecureValueType;\nsecureValueTypeIdentityCard#a0d0744b = SecureValueType;\nsecureValueTypeInternalPassport#99a48f23 = SecureValueType;\nsecureValueTypeAddress#cbe31e26 = SecureValueType;\nsecureValueTypeUtilityBill#fc36954e = SecureValueType;\nsecureValueTypeBankStatement#89137c0d = SecureValueType;\nsecureValueTypeRentalAgreement#8b883488 = SecureValueType;\nsecureValueTypePassportRegistration#99e3806a = SecureValueType;\nsecureValueTypeTemporaryRegistration#ea02ec33 = SecureValueType;\nsecureValueTypePhone#b320aadb = SecureValueType;\nsecureValueTypeEmail#8e3ca7ee = SecureValueType;\nsecureValue#187fa0ca flags:# type:SecureValueType data:flags.0?SecureData front_side:flags.1?SecureFile reverse_side:flags.2?SecureFile selfie:flags.3?SecureFile translation:flags.6?Vector files:flags.4?Vector plain_data:flags.5?SecurePlainData hash:bytes = SecureValue;\ninputSecureValue#db21d0a7 flags:# type:SecureValueType data:flags.0?SecureData front_side:flags.1?InputSecureFile reverse_side:flags.2?InputSecureFile selfie:flags.3?InputSecureFile translation:flags.6?Vector files:flags.4?Vector plain_data:flags.5?SecurePlainData = InputSecureValue;\nsecureValueHash#ed1ecdb0 type:SecureValueType hash:bytes = SecureValueHash;\nsecureValueErrorData#e8a40bd9 type:SecureValueType data_hash:bytes field:string text:string = SecureValueError;\nsecureValueErrorFrontSide#be3dfa type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorReverseSide#868a2aa5 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorSelfie#e537ced6 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorFile#7a700873 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorFiles#666220e9 type:SecureValueType file_hash:Vector text:string = SecureValueError;\nsecureValueError#869d758f type:SecureValueType hash:bytes text:string = SecureValueError;\nsecureValueErrorTranslationFile#a1144770 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorTranslationFiles#34636dd8 type:SecureValueType file_hash:Vector text:string = SecureValueError;\nsecureCredentialsEncrypted#33f0ea47 data:bytes hash:bytes secret:bytes = SecureCredentialsEncrypted;\naccount.authorizationForm#ad2e1cd8 flags:# required_types:Vector values:Vector errors:Vector users:Vector privacy_policy_url:flags.0?string = account.AuthorizationForm;\naccount.sentEmailCode#811f854f email_pattern:string length:int = account.SentEmailCode;\nhelp.deepLinkInfoEmpty#66afa166 = help.DeepLinkInfo;\nhelp.deepLinkInfo#6a4ee832 flags:# update_app:flags.0?true message:string entities:flags.1?Vector = help.DeepLinkInfo;\nsavedPhoneContact#1142bd56 phone:string first_name:string last_name:string date:int = SavedContact;\naccount.takeout#4dba4501 id:long = account.Takeout;\npasswordKdfAlgoUnknown#d45ab096 = PasswordKdfAlgo;\npasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow#3a912d4a salt1:bytes salt2:bytes g:int p:bytes = PasswordKdfAlgo;\nsecurePasswordKdfAlgoUnknown#4a8537 = SecurePasswordKdfAlgo;\nsecurePasswordKdfAlgoPBKDF2HMACSHA512iter100000#bbf2dda0 salt:bytes = SecurePasswordKdfAlgo;\nsecurePasswordKdfAlgoSHA512#86471d92 salt:bytes = SecurePasswordKdfAlgo;\nsecureSecretSettings#1527bcac secure_algo:SecurePasswordKdfAlgo secure_secret:bytes secure_secret_id:long = SecureSecretSettings;\ninputCheckPasswordEmpty#9880f658 = InputCheckPasswordSRP;\ninputCheckPasswordSRP#d27ff082 srp_id:long A:bytes M1:bytes = InputCheckPasswordSRP;\nsecureRequiredType#829d99da flags:# native_names:flags.0?true selfie_required:flags.1?true translation_required:flags.2?true type:SecureValueType = SecureRequiredType;\nsecureRequiredTypeOneOf#27477b4 types:Vector = SecureRequiredType;\nhelp.passportConfigNotModified#bfb9f457 = help.PassportConfig;\nhelp.passportConfig#a098d6af hash:int countries_langs:DataJSON = help.PassportConfig;\ninputAppEvent#1d1b1245 time:double type:string peer:long data:JSONValue = InputAppEvent;\njsonObjectValue#c0de1bd9 key:string value:JSONValue = JSONObjectValue;\njsonNull#3f6d7b68 = JSONValue;\njsonBool#c7345e6a value:Bool = JSONValue;\njsonNumber#2be0dfa4 value:double = JSONValue;\njsonString#b71e767a value:string = JSONValue;\njsonArray#f7444763 value:Vector = JSONValue;\njsonObject#99c1d49d value:Vector = JSONValue;\npageTableCell#34566b6a flags:# header:flags.0?true align_center:flags.3?true align_right:flags.4?true valign_middle:flags.5?true valign_bottom:flags.6?true text:flags.7?RichText colspan:flags.1?int rowspan:flags.2?int = PageTableCell;\npageTableRow#e0c0c5e5 cells:Vector = PageTableRow;\npageCaption#6f747657 text:RichText credit:RichText = PageCaption;\npageListItemText#b92fb6cd text:RichText = PageListItem;\npageListItemBlocks#25e073fc blocks:Vector = PageListItem;\npageListOrderedItemText#5e068047 num:string text:RichText = PageListOrderedItem;\npageListOrderedItemBlocks#98dd8936 num:string blocks:Vector = PageListOrderedItem;\npageRelatedArticle#b390dc08 flags:# url:string webpage_id:long title:flags.0?string description:flags.1?string photo_id:flags.2?long author:flags.3?string published_date:flags.4?int = PageRelatedArticle;\npage#98657f0d flags:# part:flags.0?true rtl:flags.1?true v2:flags.2?true url:string blocks:Vector photos:Vector documents:Vector views:flags.3?int = Page;\nhelp.supportName#8c05f1c9 name:string = help.SupportName;\nhelp.userInfoEmpty#f3ae2eed = help.UserInfo;\nhelp.userInfo#1eb3758 message:string entities:Vector author:string date:int = help.UserInfo;\npollAnswer#6ca9c2e9 text:string option:bytes = PollAnswer;\npoll#86e18161 id:long flags:# closed:flags.0?true public_voters:flags.1?true multiple_choice:flags.2?true quiz:flags.3?true question:string answers:Vector close_period:flags.4?int close_date:flags.5?int = Poll;\npollAnswerVoters#3b6ddad2 flags:# chosen:flags.0?true correct:flags.1?true option:bytes voters:int = PollAnswerVoters;\npollResults#dcb82ea3 flags:# min:flags.0?true results:flags.1?Vector total_voters:flags.2?int recent_voters:flags.3?Vector solution:flags.4?string solution_entities:flags.4?Vector = PollResults;\nchatOnlines#f041e250 onlines:int = ChatOnlines;\nstatsURL#47a971e0 url:string = StatsURL;\nchatAdminRights#5fb224d5 flags:# change_info:flags.0?true post_messages:flags.1?true edit_messages:flags.2?true delete_messages:flags.3?true ban_users:flags.4?true invite_users:flags.5?true pin_messages:flags.7?true add_admins:flags.9?true anonymous:flags.10?true manage_call:flags.11?true other:flags.12?true = ChatAdminRights;\nchatBannedRights#9f120418 flags:# view_messages:flags.0?true send_messages:flags.1?true send_media:flags.2?true send_stickers:flags.3?true send_gifs:flags.4?true send_games:flags.5?true send_inline:flags.6?true embed_links:flags.7?true send_polls:flags.8?true change_info:flags.10?true invite_users:flags.15?true pin_messages:flags.17?true until_date:int = ChatBannedRights;\ninputWallPaper#e630b979 id:long access_hash:long = InputWallPaper;\ninputWallPaperSlug#72091c80 slug:string = InputWallPaper;\ninputWallPaperNoFile#967a462e id:long = InputWallPaper;\naccount.wallPapersNotModified#1c199183 = account.WallPapers;\naccount.wallPapers#cdc3858c hash:long wallpapers:Vector = account.WallPapers;\ncodeSettings#debebe83 flags:# allow_flashcall:flags.0?true current_number:flags.1?true allow_app_hash:flags.4?true = CodeSettings;\nwallPaperSettings#1dc1bca4 flags:# blur:flags.1?true motion:flags.2?true background_color:flags.0?int second_background_color:flags.4?int third_background_color:flags.5?int fourth_background_color:flags.6?int intensity:flags.3?int rotation:flags.4?int = WallPaperSettings;\nautoDownloadSettings#e04232f3 flags:# disabled:flags.0?true video_preload_large:flags.1?true audio_preload_next:flags.2?true phonecalls_less_data:flags.3?true photo_size_max:int video_size_max:int file_size_max:int video_upload_maxbitrate:int = AutoDownloadSettings;\naccount.autoDownloadSettings#63cacf26 low:AutoDownloadSettings medium:AutoDownloadSettings high:AutoDownloadSettings = account.AutoDownloadSettings;\nemojiKeyword#d5b3b9f9 keyword:string emoticons:Vector = EmojiKeyword;\nemojiKeywordDeleted#236df622 keyword:string emoticons:Vector = EmojiKeyword;\nemojiKeywordsDifference#5cc761bd lang_code:string from_version:int version:int keywords:Vector = EmojiKeywordsDifference;\nemojiURL#a575739d url:string = EmojiURL;\nemojiLanguage#b3fb5361 lang_code:string = EmojiLanguage;\nfolder#ff544e65 flags:# autofill_new_broadcasts:flags.0?true autofill_public_groups:flags.1?true autofill_new_correspondents:flags.2?true id:int title:string photo:flags.3?ChatPhoto = Folder;\ninputFolderPeer#fbd2c296 peer:InputPeer folder_id:int = InputFolderPeer;\nfolderPeer#e9baa668 peer:Peer folder_id:int = FolderPeer;\nmessages.searchCounter#e844ebff flags:# inexact:flags.1?true filter:MessagesFilter count:int = messages.SearchCounter;\nurlAuthResultRequest#92d33a0e flags:# request_write_access:flags.0?true bot:User domain:string = UrlAuthResult;\nurlAuthResultAccepted#8f8c0e4e url:string = UrlAuthResult;\nurlAuthResultDefault#a9d6db1f = UrlAuthResult;\nchannelLocationEmpty#bfb5ad8b = ChannelLocation;\nchannelLocation#209b82db geo_point:GeoPoint address:string = ChannelLocation;\npeerLocated#ca461b5d peer:Peer expires:int distance:int = PeerLocated;\npeerSelfLocated#f8ec284b expires:int = PeerLocated;\nrestrictionReason#d072acb4 platform:string reason:string text:string = RestrictionReason;\ninputTheme#3c5693e9 id:long access_hash:long = InputTheme;\ninputThemeSlug#f5890df1 slug:string = InputTheme;\ntheme#e802b8dc 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?ThemeSettings installs_count:flags.4?int = Theme;\naccount.themesNotModified#f41eb622 = account.Themes;\naccount.themes#9a3d8c6d hash:long themes:Vector = account.Themes;\nauth.loginToken#629f1980 expires:int token:bytes = auth.LoginToken;\nauth.loginTokenMigrateTo#68e9916 dc_id:int token:bytes = auth.LoginToken;\nauth.loginTokenSuccess#390d5c5e authorization:auth.Authorization = auth.LoginToken;\naccount.contentSettings#57e28221 flags:# sensitive_enabled:flags.0?true sensitive_can_change:flags.1?true = account.ContentSettings;\nmessages.inactiveChats#a927fec5 dates:Vector chats:Vector users:Vector = messages.InactiveChats;\nbaseThemeClassic#c3a12462 = BaseTheme;\nbaseThemeDay#fbd81688 = BaseTheme;\nbaseThemeNight#b7b31ea8 = BaseTheme;\nbaseThemeTinted#6d5f77ee = BaseTheme;\nbaseThemeArctic#5b11125a = BaseTheme;\ninputThemeSettings#8fde504f flags:# message_colors_animated:flags.2?true base_theme:BaseTheme accent_color:int outbox_accent_color:flags.3?int message_colors:flags.0?Vector wallpaper:flags.1?InputWallPaper wallpaper_settings:flags.1?WallPaperSettings = InputThemeSettings;\nthemeSettings#fa58b6d4 flags:# message_colors_animated:flags.2?true base_theme:BaseTheme accent_color:int outbox_accent_color:flags.3?int message_colors:flags.0?Vector wallpaper:flags.1?WallPaper = ThemeSettings;\nwebPageAttributeTheme#54b56617 flags:# documents:flags.0?Vector settings:flags.1?ThemeSettings = WebPageAttribute;\nmessageUserVote#34d247b4 user_id:long option:bytes date:int = MessageUserVote;\nmessageUserVoteInputOption#3ca5b0ec user_id:long date:int = MessageUserVote;\nmessageUserVoteMultiple#8a65e557 user_id:long options:Vector date:int = MessageUserVote;\nmessages.votesList#823f649 flags:# count:int votes:Vector users:Vector next_offset:flags.0?string = messages.VotesList;\nbankCardOpenUrl#f568028a url:string name:string = BankCardOpenUrl;\npayments.bankCardData#3e24e573 title:string open_urls:Vector = payments.BankCardData;\ndialogFilter#7438f7e8 flags:# contacts:flags.0?true non_contacts:flags.1?true groups:flags.2?true broadcasts:flags.3?true bots:flags.4?true exclude_muted:flags.11?true exclude_read:flags.12?true exclude_archived:flags.13?true id:int title:string emoticon:flags.25?string pinned_peers:Vector include_peers:Vector exclude_peers:Vector = DialogFilter;\ndialogFilterSuggested#77744d4a filter:DialogFilter description:string = DialogFilterSuggested;\nstatsDateRangeDays#b637edaf min_date:int max_date:int = StatsDateRangeDays;\nstatsAbsValueAndPrev#cb43acde current:double previous:double = StatsAbsValueAndPrev;\nstatsPercentValue#cbce2fe0 part:double total:double = StatsPercentValue;\nstatsGraphAsync#4a27eb2d token:string = StatsGraph;\nstatsGraphError#bedc9822 error:string = StatsGraph;\nstatsGraph#8ea464b6 flags:# json:DataJSON zoom_token:flags.0?string = StatsGraph;\nmessageInteractionCounters#ad4fc9bd msg_id:int views:int forwards:int = MessageInteractionCounters;\nstats.broadcastStats#bdf78394 period:StatsDateRangeDays followers:StatsAbsValueAndPrev views_per_post:StatsAbsValueAndPrev shares_per_post:StatsAbsValueAndPrev enabled_notifications:StatsPercentValue growth_graph:StatsGraph followers_graph:StatsGraph mute_graph:StatsGraph top_hours_graph:StatsGraph interactions_graph:StatsGraph iv_interactions_graph:StatsGraph views_by_source_graph:StatsGraph new_followers_by_source_graph:StatsGraph languages_graph:StatsGraph recent_message_interactions:Vector = stats.BroadcastStats;\nhelp.promoDataEmpty#98f6ac75 expires:int = help.PromoData;\nhelp.promoData#8c39793f flags:# proxy:flags.0?true expires:int peer:Peer chats:Vector users:Vector psa_type:flags.1?string psa_message:flags.2?string = help.PromoData;\nvideoSize#de33b094 flags:# type:string w:int h:int size:int video_start_ts:flags.0?double = VideoSize;\nstatsGroupTopPoster#9d04af9b user_id:long messages:int avg_chars:int = StatsGroupTopPoster;\nstatsGroupTopAdmin#d7584c87 user_id:long deleted:int kicked:int banned:int = StatsGroupTopAdmin;\nstatsGroupTopInviter#535f779d user_id:long invitations:int = StatsGroupTopInviter;\nstats.megagroupStats#ef7ff916 period:StatsDateRangeDays members:StatsAbsValueAndPrev messages:StatsAbsValueAndPrev viewers:StatsAbsValueAndPrev posters:StatsAbsValueAndPrev growth_graph:StatsGraph members_graph:StatsGraph new_members_by_source_graph:StatsGraph languages_graph:StatsGraph messages_graph:StatsGraph actions_graph:StatsGraph top_hours_graph:StatsGraph weekdays_graph:StatsGraph top_posters:Vector top_admins:Vector top_inviters:Vector users:Vector = stats.MegagroupStats;\nglobalPrivacySettings#bea2f424 flags:# archive_and_mute_new_noncontact_peers:flags.0?Bool = GlobalPrivacySettings;\nhelp.countryCode#4203c5ef flags:# country_code:string prefixes:flags.0?Vector patterns:flags.1?Vector = help.CountryCode;\nhelp.country#c3878e23 flags:# hidden:flags.0?true iso2:string default_name:string name:flags.1?string country_codes:Vector = help.Country;\nhelp.countriesListNotModified#93cc1f32 = help.CountriesList;\nhelp.countriesList#87d0759e countries:Vector hash:int = help.CountriesList;\nmessageViews#455b853d flags:# views:flags.0?int forwards:flags.1?int replies:flags.2?MessageReplies = MessageViews;\nmessages.messageViews#b6c4f543 views:Vector chats:Vector users:Vector = messages.MessageViews;\nmessages.discussionMessage#a6341782 flags:# messages:Vector max_id:flags.0?int read_inbox_max_id:flags.1?int read_outbox_max_id:flags.2?int unread_count:int chats:Vector users:Vector = messages.DiscussionMessage;\nmessageReplyHeader#a6d57763 flags:# reply_to_msg_id:int reply_to_peer_id:flags.0?Peer reply_to_top_id:flags.1?int = MessageReplyHeader;\nmessageReplies#83d60fc2 flags:# comments:flags.0?true replies:int replies_pts:int recent_repliers:flags.1?Vector channel_id:flags.0?long max_id:flags.2?int read_max_id:flags.3?int = MessageReplies;\npeerBlocked#e8fd8014 peer_id:Peer date:int = PeerBlocked;\nstats.messageStats#8999f295 views_graph:StatsGraph = stats.MessageStats;\ngroupCallDiscarded#7780bcb4 id:long access_hash:long duration:int = GroupCall;\ngroupCall#d597650c flags:# join_muted:flags.1?true can_change_join_muted:flags.2?true join_date_asc:flags.6?true schedule_start_subscribed:flags.8?true can_start_video:flags.9?true record_video_active:flags.11?true id:long access_hash:long participants_count:int title:flags.3?string stream_dc_id:flags.4?int record_start_date:flags.5?int schedule_date:flags.7?int unmuted_video_count:flags.10?int unmuted_video_limit:int version:int = GroupCall;\ninputGroupCall#d8aa840f id:long access_hash:long = InputGroupCall;\ngroupCallParticipant#eba636fe flags:# muted:flags.0?true left:flags.1?true can_self_unmute:flags.2?true just_joined:flags.4?true versioned:flags.5?true min:flags.8?true muted_by_you:flags.9?true volume_by_admin:flags.10?true self:flags.12?true video_joined:flags.15?true peer:Peer date:int active_date:flags.3?int source:int volume:flags.7?int about:flags.11?string raise_hand_rating:flags.13?long video:flags.6?GroupCallParticipantVideo presentation:flags.14?GroupCallParticipantVideo = GroupCallParticipant;\nphone.groupCall#9e727aad call:GroupCall participants:Vector participants_next_offset:string chats:Vector users:Vector = phone.GroupCall;\nphone.groupParticipants#f47751b6 count:int participants:Vector next_offset:string chats:Vector users:Vector version:int = phone.GroupParticipants;\ninlineQueryPeerTypeSameBotPM#3081ed9d = InlineQueryPeerType;\ninlineQueryPeerTypePM#833c0fac = InlineQueryPeerType;\ninlineQueryPeerTypeChat#d766c50a = InlineQueryPeerType;\ninlineQueryPeerTypeMegagroup#5ec4be43 = InlineQueryPeerType;\ninlineQueryPeerTypeBroadcast#6334ee9a = InlineQueryPeerType;\nmessages.historyImport#1662af0b id:long = messages.HistoryImport;\nmessages.historyImportParsed#5e0fb7b9 flags:# pm:flags.0?true group:flags.1?true title:flags.2?string = messages.HistoryImportParsed;\nmessages.affectedFoundMessages#ef8d3e6c pts:int pts_count:int offset:int messages:Vector = messages.AffectedFoundMessages;\nchatInviteImporter#b5cd5f4 user_id:long date:int = ChatInviteImporter;\nmessages.exportedChatInvites#bdc62dcc count:int invites:Vector users:Vector = messages.ExportedChatInvites;\nmessages.exportedChatInvite#1871be50 invite:ExportedChatInvite users:Vector = messages.ExportedChatInvite;\nmessages.exportedChatInviteReplaced#222600ef invite:ExportedChatInvite new_invite:ExportedChatInvite users:Vector = messages.ExportedChatInvite;\nmessages.chatInviteImporters#81b6b00a count:int importers:Vector users:Vector = messages.ChatInviteImporters;\nchatAdminWithInvites#f2ecef23 admin_id:long invites_count:int revoked_invites_count:int = ChatAdminWithInvites;\nmessages.chatAdminsWithInvites#b69b72d7 admins:Vector users:Vector = messages.ChatAdminsWithInvites;\nmessages.checkedHistoryImportPeer#a24de717 confirm_text:string = messages.CheckedHistoryImportPeer;\nphone.joinAsPeers#afe5623f peers:Vector chats:Vector users:Vector = phone.JoinAsPeers;\nphone.exportedGroupCallInvite#204bd158 link:string = phone.ExportedGroupCallInvite;\ngroupCallParticipantVideoSourceGroup#dcb118b7 semantics:string sources:Vector = GroupCallParticipantVideoSourceGroup;\ngroupCallParticipantVideo#67753ac8 flags:# paused:flags.0?true endpoint:string source_groups:Vector audio_source:flags.1?int = GroupCallParticipantVideo;\nstickers.suggestedShortName#85fea03f short_name:string = stickers.SuggestedShortName;\nbotCommandScopeDefault#2f6cb2ab = BotCommandScope;\nbotCommandScopeUsers#3c4f04d8 = BotCommandScope;\nbotCommandScopeChats#6fe1a881 = BotCommandScope;\nbotCommandScopeChatAdmins#b9aa606a = BotCommandScope;\nbotCommandScopePeer#db9d897d peer:InputPeer = BotCommandScope;\nbotCommandScopePeerAdmins#3fd863d1 peer:InputPeer = BotCommandScope;\nbotCommandScopePeerUser#a1321f3 peer:InputPeer user_id:InputUser = BotCommandScope;\naccount.resetPasswordFailedWait#e3779861 retry_date:int = account.ResetPasswordResult;\naccount.resetPasswordRequestedWait#e9effc7d until_date:int = account.ResetPasswordResult;\naccount.resetPasswordOk#e926d63e = account.ResetPasswordResult;\nchatTheme#ed0b5c33 emoticon:string theme:Theme dark_theme:Theme = ChatTheme;\naccount.chatThemesNotModified#e011e1c4 = account.ChatThemes;\naccount.chatThemes#fe4cbebd hash:int themes:Vector = account.ChatThemes;\nsponsoredMessage#2a3c381f flags:# random_id:bytes from_id:Peer start_param:flags.0?string message:string entities:flags.1?Vector = SponsoredMessage;\nmessages.sponsoredMessages#65a4c7d5 messages:Vector chats:Vector users:Vector = messages.SponsoredMessages;\n---functions---\ninitConnection#c1cd5ea9 {X:Type} flags:# api_id:int device_model:string system_version:string app_version:string system_lang_code:string lang_pack:string lang_code:string proxy:flags.0?InputClientProxy params:flags.1?JSONValue query:!X = X;\ninvokeWithLayer#da9b0d0d {X:Type} layer:int query:!X = X;\nauth.sendCode#a677244f phone_number:string api_id:int api_hash:string settings:CodeSettings = auth.SentCode;\nauth.signUp#80eee427 phone_number:string phone_code_hash:string first_name:string last_name:string = auth.Authorization;\nauth.signIn#bcd51581 phone_number:string phone_code_hash:string phone_code:string = auth.Authorization;\nauth.logOut#5717da40 = Bool;\nauth.resetAuthorizations#9fab0d1a = Bool;\nauth.exportAuthorization#e5bfffcd dc_id:int = auth.ExportedAuthorization;\nauth.importAuthorization#a57a7dad id:long bytes:bytes = auth.Authorization;\nauth.bindTempAuthKey#cdd42a05 perm_auth_key_id:long nonce:long expires_at:int encrypted_message:bytes = Bool;\nauth.checkPassword#d18b4d16 password:InputCheckPasswordSRP = auth.Authorization;\nauth.requestPasswordRecovery#d897bc66 = auth.PasswordRecovery;\nauth.resendCode#3ef1a9bf phone_number:string phone_code_hash:string = auth.SentCode;\nauth.cancelCode#1f040578 phone_number:string phone_code_hash:string = Bool;\nauth.dropTempAuthKeys#8e48a188 except_auth_keys:Vector = Bool;\nauth.exportLoginToken#b7e085fe api_id:int api_hash:string except_ids:Vector = auth.LoginToken;\nauth.importLoginToken#95ac5ce4 token:bytes = auth.LoginToken;\naccount.registerDevice#ec86017a flags:# no_muted:flags.0?true token_type:int token:string app_sandbox:Bool secret:bytes other_uids:Vector = Bool;\naccount.unregisterDevice#6a0d3206 token_type:int token:string other_uids:Vector = Bool;\naccount.updateNotifySettings#84be5b93 peer:InputNotifyPeer settings:InputPeerNotifySettings = Bool;\naccount.getNotifySettings#12b3ad31 peer:InputNotifyPeer = PeerNotifySettings;\naccount.updateProfile#78515775 flags:# first_name:flags.0?string last_name:flags.1?string about:flags.2?string = User;\naccount.updateStatus#6628562c offline:Bool = Bool;\naccount.getWallPapers#7967d36 hash:long = account.WallPapers;\naccount.checkUsername#2714d86c username:string = Bool;\naccount.updateUsername#3e0bdd7c username:string = User;\naccount.getPrivacy#dadbc950 key:InputPrivacyKey = account.PrivacyRules;\naccount.setPrivacy#c9f81ce8 key:InputPrivacyKey rules:Vector = account.PrivacyRules;\naccount.getAuthorizations#e320c158 = account.Authorizations;\naccount.resetAuthorization#df77f3bc hash:long = Bool;\naccount.getPassword#548a30f5 = account.Password;\naccount.getPasswordSettings#9cd4eaf9 password:InputCheckPasswordSRP = account.PasswordSettings;\naccount.updatePasswordSettings#a59b102f password:InputCheckPasswordSRP new_settings:account.PasswordInputSettings = Bool;\naccount.sendConfirmPhoneCode#1b3faa88 hash:string settings:CodeSettings = auth.SentCode;\naccount.confirmPhone#5f2178c3 phone_code_hash:string phone_code:string = Bool;\naccount.getTmpPassword#449e0b51 password:InputCheckPasswordSRP period:int = account.TmpPassword;\naccount.sendVerifyPhoneCode#a5a356f9 phone_number:string settings:CodeSettings = auth.SentCode;\naccount.confirmPasswordEmail#8fdf1920 code:string = Bool;\naccount.getContactSignUpNotification#9f07c728 = Bool;\naccount.setContactSignUpNotification#cff43f61 silent:Bool = Bool;\naccount.getNotifyExceptions#53577479 flags:# compare_sound:flags.1?true peer:flags.0?InputNotifyPeer = Updates;\naccount.uploadWallPaper#dd853661 file:InputFile mime_type:string settings:WallPaperSettings = WallPaper;\naccount.setContentSettings#b574b16b flags:# sensitive_enabled:flags.0?true = Bool;\naccount.getContentSettings#8b9b4dae = account.ContentSettings;\nusers.getUsers#d91a548 id:Vector = Vector;\nusers.getFullUser#ca30a5b1 id:InputUser = UserFull;\ncontacts.getContacts#5dd69e12 hash:long = contacts.Contacts;\ncontacts.importContacts#2c800be5 contacts:Vector = contacts.ImportedContacts;\ncontacts.deleteContacts#96a0e00 id:Vector = Updates;\ncontacts.block#68cc1411 id:InputPeer = Bool;\ncontacts.unblock#bea65d50 id:InputPeer = Bool;\ncontacts.getBlocked#f57c350f offset:int limit:int = contacts.Blocked;\ncontacts.search#11f812d8 q:string limit:int = contacts.Found;\ncontacts.resolveUsername#f93ccba3 username:string = contacts.ResolvedPeer;\ncontacts.getTopPeers#973478b6 flags:# correspondents:flags.0?true bots_pm:flags.1?true bots_inline:flags.2?true phone_calls:flags.3?true forward_users:flags.4?true forward_chats:flags.5?true groups:flags.10?true channels:flags.15?true offset:int limit:int hash:long = contacts.TopPeers;\ncontacts.addContact#e8f463d0 flags:# add_phone_privacy_exception:flags.0?true id:InputUser first_name:string last_name:string phone:string = Updates;\nmessages.getMessages#63c66506 id:Vector = messages.Messages;\nmessages.getDialogs#a0f4cb4f flags:# exclude_pinned:flags.0?true folder_id:flags.1?int offset_date:int offset_id:int offset_peer:InputPeer limit:int hash:long = messages.Dialogs;\nmessages.getHistory#4423e6c5 peer:InputPeer offset_id:int offset_date:int add_offset:int limit:int max_id:int min_id:int hash:long = messages.Messages;\nmessages.search#a0fda762 flags:# peer:InputPeer q:string from_id:flags.0?InputPeer top_msg_id:flags.1?int filter:MessagesFilter min_date:int max_date:int offset_id:int add_offset:int limit:int max_id:int min_id:int hash:long = messages.Messages;\nmessages.readHistory#e306d3a peer:InputPeer max_id:int = messages.AffectedMessages;\nmessages.deleteHistory#1c015b09 flags:# just_clear:flags.0?true revoke:flags.1?true peer:InputPeer max_id:int = messages.AffectedHistory;\nmessages.deleteMessages#e58e95d2 flags:# revoke:flags.0?true id:Vector = messages.AffectedMessages;\nmessages.receivedMessages#5a954c0 max_id:int = Vector;\nmessages.setTyping#58943ee2 flags:# peer:InputPeer top_msg_id:flags.0?int action:SendMessageAction = Bool;\nmessages.sendMessage#520c3870 flags:# no_webpage:flags.1?true silent:flags.5?true background:flags.6?true clear_draft:flags.7?true peer:InputPeer reply_to_msg_id:flags.0?int message:string random_id:long reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector schedule_date:flags.10?int = Updates;\nmessages.sendMedia#3491eba9 flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true peer:InputPeer reply_to_msg_id:flags.0?int media:InputMedia message:string random_id:long reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector schedule_date:flags.10?int = Updates;\nmessages.forwardMessages#d9fee60e 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 from_peer:InputPeer id:Vector random_id:Vector to_peer:InputPeer schedule_date:flags.10?int = Updates;\nmessages.report#8953ab4e peer:InputPeer id:Vector reason:ReportReason message:string = Bool;\nmessages.getChats#49e9528f id:Vector = messages.Chats;\nmessages.getFullChat#aeb00b34 chat_id:long = messages.ChatFull;\nmessages.editChatTitle#73783ffd chat_id:long title:string = Updates;\nmessages.editChatPhoto#35ddd674 chat_id:long photo:InputChatPhoto = Updates;\nmessages.addChatUser#f24753e3 chat_id:long user_id:InputUser fwd_limit:int = Updates;\nmessages.deleteChatUser#a2185cab flags:# revoke_history:flags.0?true chat_id:long user_id:InputUser = Updates;\nmessages.createChat#9cb126e users:Vector title:string = Updates;\nmessages.getDhConfig#26cf8950 version:int random_length:int = messages.DhConfig;\nmessages.readMessageContents#36a73f77 id:Vector = messages.AffectedMessages;\nmessages.getStickers#d5a5d3a1 emoticon:string hash:long = messages.Stickers;\nmessages.getAllStickers#b8a0a1a8 hash:long = messages.AllStickers;\nmessages.getWebPagePreview#8b68b0cc flags:# message:string entities:flags.3?Vector = MessageMedia;\nmessages.exportChatInvite#14b9bcd7 flags:# legacy_revoke_permanent:flags.2?true peer:InputPeer expire_date:flags.0?int usage_limit:flags.1?int = ExportedChatInvite;\nmessages.checkChatInvite#3eadb1bb hash:string = ChatInvite;\nmessages.importChatInvite#6c50051c hash:string = Updates;\nmessages.getStickerSet#2619a90e stickerset:InputStickerSet = messages.StickerSet;\nmessages.installStickerSet#c78fe460 stickerset:InputStickerSet archived:Bool = messages.StickerSetInstallResult;\nmessages.uninstallStickerSet#f96e55de stickerset:InputStickerSet = Bool;\nmessages.startBot#e6df7378 bot:InputUser peer:InputPeer random_id:long start_param:string = Updates;\nmessages.migrateChat#a2875319 chat_id:long = Updates;\nmessages.searchGlobal#4bc6589a flags:# folder_id:flags.0?int q:string filter:MessagesFilter min_date:int max_date:int offset_rate:int offset_peer:InputPeer offset_id:int limit:int = messages.Messages;\nmessages.getDocumentByHash#338e2464 sha256:bytes size:int mime_type:string = Document;\nmessages.getSavedGifs#5cf09635 hash:long = messages.SavedGifs;\nmessages.getInlineBotResults#514e999d flags:# bot:InputUser peer:InputPeer geo_point:flags.0?InputGeoPoint query:string offset:string = messages.BotResults;\nmessages.sendInlineBotResult#220815b0 flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true hide_via:flags.11?true peer:InputPeer reply_to_msg_id:flags.0?int random_id:long query_id:long id:string schedule_date:flags.10?int = Updates;\nmessages.editMessage#48f71778 flags:# no_webpage:flags.1?true peer:InputPeer id:int message:flags.11?string media:flags.14?InputMedia reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector schedule_date:flags.15?int = Updates;\nmessages.getBotCallbackAnswer#9342ca07 flags:# game:flags.1?true peer:InputPeer msg_id:int data:flags.0?bytes password:flags.2?InputCheckPasswordSRP = messages.BotCallbackAnswer;\nmessages.getPeerDialogs#e470bcfd peers:Vector = messages.PeerDialogs;\nmessages.saveDraft#bc39e14b flags:# no_webpage:flags.1?true reply_to_msg_id:flags.0?int peer:InputPeer message:string entities:flags.3?Vector = Bool;\nmessages.getFeaturedStickers#64780b14 hash:long = messages.FeaturedStickers;\nmessages.readFeaturedStickers#5b118126 id:Vector = Bool;\nmessages.getRecentStickers#9da9403b flags:# attached:flags.0?true hash:long = messages.RecentStickers;\nmessages.getCommonChats#e40ca104 user_id:InputUser max_id:long limit:int = messages.Chats;\nmessages.getWebPage#32ca8f91 url:string hash:int = WebPage;\nmessages.toggleDialogPin#a731e257 flags:# pinned:flags.0?true peer:InputDialogPeer = Bool;\nmessages.getPinnedDialogs#d6b94df2 folder_id:int = messages.PeerDialogs;\nmessages.uploadMedia#519bc2b1 peer:InputPeer media:InputMedia = MessageMedia;\nmessages.getFavedStickers#4f1aaa9 hash:long = messages.FavedStickers;\nmessages.faveSticker#b9ffc55b id:InputDocument unfave:Bool = Bool;\nmessages.sendMultiMedia#cc0110cb flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true peer:InputPeer reply_to_msg_id:flags.0?int multi_media:Vector schedule_date:flags.10?int = Updates;\nmessages.searchStickerSets#35705b8a flags:# exclude_featured:flags.0?true q:string hash:long = messages.FoundStickerSets;\nmessages.markDialogUnread#c286d98f flags:# unread:flags.0?true peer:InputDialogPeer = Bool;\nmessages.updatePinnedMessage#d2aaf7ec flags:# silent:flags.0?true unpin:flags.1?true pm_oneside:flags.2?true peer:InputPeer id:int = Updates;\nmessages.sendVote#10ea6184 peer:InputPeer msg_id:int options:Vector = Updates;\nmessages.getOnlines#6e2be050 peer:InputPeer = ChatOnlines;\nmessages.editChatAbout#def60797 peer:InputPeer about:string = Bool;\nmessages.editChatDefaultBannedRights#a5866b41 peer:InputPeer banned_rights:ChatBannedRights = Updates;\nmessages.getEmojiKeywordsDifference#1508b6af lang_code:string from_version:int = EmojiKeywordsDifference;\nmessages.getScheduledHistory#f516760b peer:InputPeer hash:long = messages.Messages;\nmessages.sendScheduledMessages#bd38850a peer:InputPeer id:Vector = Updates;\nmessages.deleteScheduledMessages#59ae2b16 peer:InputPeer id:Vector = Updates;\nmessages.getPollVotes#b86e380e flags:# peer:InputPeer id:int option:flags.0?bytes offset:flags.1?string limit:int = messages.VotesList;\nmessages.getDialogFilters#f19ed96d = Vector;\nmessages.getSuggestedDialogFilters#a29cd42c = Vector;\nmessages.updateDialogFilter#1ad4a04a flags:# id:int filter:flags.0?DialogFilter = Bool;\nmessages.getReplies#22ddd30c peer:InputPeer msg_id:int offset_id:int offset_date:int add_offset:int limit:int max_id:int min_id:int hash:long = messages.Messages;\nmessages.getDiscussionMessage#446972fd peer:InputPeer msg_id:int = messages.DiscussionMessage;\nmessages.readDiscussion#f731a9f4 peer:InputPeer msg_id:int read_max_id:int = Bool;\nmessages.unpinAllMessages#f025bc8b peer:InputPeer = messages.AffectedHistory;\nmessages.deleteChat#5bd0ee50 chat_id:long = Bool;\nupdates.getState#edd4882a = updates.State;\nupdates.getDifference#25939651 flags:# pts:int pts_total_limit:flags.0?int date:int qts:int = updates.Difference;\nupdates.getChannelDifference#3173d78 flags:# force:flags.0?true channel:InputChannel filter:ChannelMessagesFilter pts:int limit:int = updates.ChannelDifference;\nphotos.uploadProfilePhoto#89f30f69 flags:# file:flags.0?InputFile video:flags.1?InputFile video_start_ts:flags.2?double = photos.Photo;\nphotos.getUserPhotos#91cd32a8 user_id:InputUser offset:int max_id:long limit:int = photos.Photos;\nupload.saveFilePart#b304a621 file_id:long file_part:int bytes:bytes = Bool;\nupload.getFile#b15a9afc flags:# precise:flags.0?true cdn_supported:flags.1?true location:InputFileLocation offset:int limit:int = upload.File;\nupload.saveBigFilePart#de7b673d file_id:long file_part:int file_total_parts:int bytes:bytes = Bool;\nupload.getWebFile#24e6818d location:InputWebFileLocation offset:int limit:int = upload.WebFile;\nhelp.getConfig#c4f9186b = Config;\nhelp.getNearestDc#1fb33026 = NearestDc;\nhelp.getSupport#9cdf08cd = help.Support;\nhelp.acceptTermsOfService#ee72f79a id:DataJSON = Bool;\nhelp.getCountriesList#735787a8 lang_code:string hash:int = help.CountriesList;\nchannels.readHistory#cc104937 channel:InputChannel max_id:int = Bool;\nchannels.deleteMessages#84c1fd4e channel:InputChannel id:Vector = messages.AffectedMessages;\nchannels.getMessages#ad8c9a23 channel:InputChannel id:Vector = messages.Messages;\nchannels.getParticipants#77ced9d0 channel:InputChannel filter:ChannelParticipantsFilter offset:int limit:int hash:long = channels.ChannelParticipants;\nchannels.getParticipant#a0ab6cc6 channel:InputChannel participant:InputPeer = channels.ChannelParticipant;\nchannels.getChannels#a7f6bbb id:Vector = messages.Chats;\nchannels.getFullChannel#8736a09 channel:InputChannel = messages.ChatFull;\nchannels.createChannel#3d5fb10f flags:# broadcast:flags.0?true megagroup:flags.1?true for_import:flags.3?true title:string about:string geo_point:flags.2?InputGeoPoint address:flags.2?string = Updates;\nchannels.editAdmin#d33c8902 channel:InputChannel user_id:InputUser admin_rights:ChatAdminRights rank:string = Updates;\nchannels.editTitle#566decd0 channel:InputChannel title:string = Updates;\nchannels.editPhoto#f12e57c9 channel:InputChannel photo:InputChatPhoto = Updates;\nchannels.checkUsername#10e6bd2c channel:InputChannel username:string = Bool;\nchannels.updateUsername#3514b3de channel:InputChannel username:string = Bool;\nchannels.joinChannel#24b524c5 channel:InputChannel = Updates;\nchannels.leaveChannel#f836aa95 channel:InputChannel = Updates;\nchannels.inviteToChannel#199f3a6c channel:InputChannel users:Vector = Updates;\nchannels.deleteChannel#c0111fe3 channel:InputChannel = Updates;\nchannels.toggleSignatures#1f69b606 channel:InputChannel enabled:Bool = Updates;\nchannels.editBanned#96e6cd81 channel:InputChannel participant:InputPeer banned_rights:ChatBannedRights = Updates;\nchannels.readMessageContents#eab5dc38 channel:InputChannel id:Vector = Bool;\nchannels.togglePreHistoryHidden#eabbb94c channel:InputChannel enabled:Bool = Updates;\nchannels.getGroupsForDiscussion#f5dad378 = messages.Chats;\nchannels.setDiscussionGroup#40582bb2 broadcast:InputChannel group:InputChannel = Bool;\npayments.getPaymentForm#8a333c8d flags:# peer:InputPeer msg_id:int theme_params:flags.0?DataJSON = payments.PaymentForm;\npayments.getPaymentReceipt#2478d1cc peer:InputPeer msg_id:int = payments.PaymentReceipt;\npayments.validateRequestedInfo#db103170 flags:# save:flags.0?true peer:InputPeer msg_id:int info:PaymentRequestedInfo = payments.ValidatedRequestedInfo;\npayments.sendPaymentForm#30c3bc9d flags:# form_id:long peer:InputPeer msg_id:int requested_info_id:flags.0?string shipping_option_id:flags.1?string credentials:InputPaymentCredentials tip_amount:flags.2?long = payments.PaymentResult;\npayments.getSavedInfo#227d824b = payments.SavedInfo;\nlangpack.getLangPack#f2f2330a lang_pack:string lang_code:string = LangPackDifference;\nlangpack.getStrings#efea3803 lang_pack:string lang_code:string keys:Vector = Vector;\nlangpack.getLanguages#42c6978f lang_pack:string = Vector;\nfolders.editPeerFolders#6847d0ab folder_peers:Vector = Updates;\n"},8963:(e,t,n)=>{var s=n(8764).Buffer;function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const{inflate:i}=n(5802),{serializeBytes:o}=n(7404);class r{constructor(e){this.data=e,this.CONSTRUCTOR_ID=812830625,this.classType="constructor"}static async gzipIfSmaller(e,t){if(e&&t.length>512){const e=await new r(t).toBytes();if(e.length{function s(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const a=n(355);class i{constructor(e){this.CONSTRUCTOR_ID=1945237724,this.messages=e,this.classType="constructor"}static fromReader(e){const t=[],n=e.readInt();for(let s=0;s{function s(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const{RpcError:a}=n(7404).constructors,i=n(8963);class o{constructor(e,t,n){this.CONSTRUCTOR_ID=4082920705,this.reqMsgId=e,this.body=t,this.error=n,this.classType="constructor"}static async fromReader(e){const t=e.readLong(),n=e.readInt(!1);return n===a.CONSTRUCTOR_ID?new o(t,void 0,a.fromReader(e)):n===i.CONSTRUCTOR_ID?new o(t,(await i.fromReader(e)).data):(e.seek(-4),new o(t,e.read(),void 0))}}s(o,"CONSTRUCTOR_ID",4082920705),s(o,"classType","constructor"),e.exports=o},355:e=>{function t(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class n{constructor(e,t,n){this.msgId=e,this.seqNo=t,this.obj=n,this.classType="constructor"}}t(n,"SIZE_OVERHEAD",12),t(n,"classType","constructor"),e.exports=n},2058:(e,t,n)=>{const s=n(355),a=n(2301),i=n(3254),o=n(8963),r={[a.CONSTRUCTOR_ID]:a,[o.CONSTRUCTOR_ID]:o,[i.CONSTRUCTOR_ID]:i};e.exports={TLMessage:s,RPCResult:a,MessageContainer:i,GZIPPacked:o,coreObjects:r}},1436:(e,t,n)=>{var s=n(8764).Buffer;const a=e=>e.replace(/(?:^|_)([a-z])/g,((e,t)=>t.toUpperCase())).replace(/_/g,""),i=e=>e.replace(/([-_][a-z])/g,(e=>e.toUpperCase().replace("-","").replace("_",""))),o=new Set([3162085175,2574415285,1072550713,3300522427,1450380236]),r=new Set([85337187,2211011308,2851430293,1013613780,1459478408,3504867164,3045658042,1715713620,3608339646,4110704415,812830625]);let c;function d(e){c||(c=function(){let e;const t=[];for(let n=0;n<256;n++){e=n;for(let t=0;t<8;t++)e=1&e?3988292384^e>>>1:e>>>1;t[n]=e}return t}()),s.isBuffer(e)||(e=s.from(e));let t=-1;for(let n=0;n>>8}return(-1^t)>>>0}const l=(e,t,n=[])=>{e.flags.includes("g")||(e=new RegExp(e.source,"g"));const s=e.exec(t);return s&&(n.push(s.slice(1)),l(e,t,n)),n},u=(e,t)=>{const n=e.match(/([\w.]+)(?:#([0-9a-fA-F]+))?(?:\s{?\w+:[\w\d<>#.?!]+}?)*\s=\s([\w\d<>#.?]+);$/);if(!n)throw new Error(`Cannot parse TLObject ${e}`);const o=l(/({)?(\w+):([\w\d<>#.?!]+)}?/,e),r={name:n[1],constructorId:parseInt(n[2],16),argsConfig:{},subclassOfId:d(n[3]),result:n[3],isFunction:t,namespace:void 0};if(!r.constructorId){const e="";let t;t=Object.values(r.argsConfig).length?` ${Object.keys(r.argsConfig).map((e=>e.toString())).join(" ")}`:"";const n=`${r.name}${e}${t} = ${r.result}`.replace(/(:|\?)bytes /g,"$1string ").replace(/|{|}/g,"").replace(/ \w+:flags\.\d+\?true/g,"");"inputMediaInvoice"===r.name&&r.name,r.constructorId=d(s.from(n,"utf8"))}for(const[e,t,n]of o)void 0===e&&(r.argsConfig[i(t)]=g(t,n));return r.name.includes(".")&&([r.namespace,r.name]=r.name.split(/\.(.+)/)),r.name=a(r.name),r};function g(e,t){e="self"===e?"is_self":e;const n={isVector:!1,isFlag:!1,skipConstructorId:!1,flagIndex:-1,flagIndicator:!0,type:void 0,useVectorId:void 0};if("#"!==t){n.flagIndicator=!1,n.type=t.replace(/^!+/,"");const e=n.type.match(/flags.(\d+)\?([\w<>.]+)/);e&&(n.isFlag=!0,n.flagIndex=Number(e[1]),[,,n.type]=e);const s=n.type.match(/[Vv]ector<([\w\d.]+)>/);s&&(n.isVector=!0,n.useVectorId="V"===n.type.charAt(0),[,n.type]=s),/^[a-z]$/.test(n.type.split(".").pop().charAt(0))&&(n.skipConstructorId=!0)}return n}e.exports={findAll:l,parseTl:function*(e,t,n=[],s=o){(n||[]).reduce(((e,t)=>({...e,[t.name]:t})),{});const a=[],i={},c={},d=e;let l=!1;for(let e of d.split("\n")){const t=e.indexOf("//");if(-1!==t&&(e=e.slice(0,t)),e=e.trim(),!e)continue;const n=e.match(/---(\w+)---/);if(n){const[,e]=n;l="functions"===e}else try{const t=u(e,l);if(s.has(t.constructorId))continue;a.push(t),t.isFunction||(c[t.result]||(c[t.result]=[]),i[t.name]=t,c[t.result].push(t))}catch(e){if(!e.toString().includes("vector#1cb5c415"))throw e}}for(const e of a)if(r.has(e.constructorId))for(const t in e.argsConfig)"string"===e.argsConfig[t].type&&(e.argsConfig[t].type="bytes");for(const e of a)yield e},buildArgConfig:g,fromLine:u,CORE_TYPES:o,serializeDate:function(e){if(!e)return s.alloc(4).fill(0);if(e instanceof Date&&(e=Math.floor((Date.now()-e.getTime())/1e3)),"number"==typeof e){const t=s.alloc(4);return t.writeInt32LE(e,0),t}throw Error(`Cannot interpret "${e}" as a date`)},serializeBytes:function(e){if(!(e instanceof s)){if("string"!=typeof e)throw Error(`Bytes or str expected, not ${e.constructor.name}`);e=s.from(e)}const t=[];let n;return e.length<254?(n=(e.length+1)%4,0!==n&&(n=4-n),t.push(s.from([e.length])),t.push(e)):(n=e.length%4,0!==n&&(n=4-n),t.push(s.from([254,e.length%256,(e.length>>8)%256,(e.length>>16)%256])),t.push(e)),t.push(s.alloc(n).fill(0)),s.concat(t)},snakeToCamelCase:a,variableSnakeToCamelCase:i}},7404:(e,t,n)=>{const s=n(7150),{serializeBytes:a,serializeDate:i}=n(1436);e.exports={constructors:s,requests:s,serializeBytes:a,serializeDate:i}},8106:e=>{e.exports="resPQ#05162463 nonce:int128 server_nonce:int128 pq:string server_public_key_fingerprints:Vector = ResPQ;\np_q_inner_data#83c95aec pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 = P_Q_inner_data;\nserver_DH_params_fail#79cb045d nonce:int128 server_nonce:int128 new_nonce_hash:int128 = Server_DH_Params;\nserver_DH_params_ok#d0e8075c nonce:int128 server_nonce:int128 encrypted_answer:string = Server_DH_Params;\nserver_DH_inner_data#b5890dba nonce:int128 server_nonce:int128 g:int dh_prime:string g_a:string server_time:int = Server_DH_inner_data;\nclient_DH_inner_data#6643b654 nonce:int128 server_nonce:int128 retry_id:long g_b:string = Client_DH_Inner_Data;\ndh_gen_ok#3bcbf734 nonce:int128 server_nonce:int128 new_nonce_hash1:int128 = Set_client_DH_params_answer;\ndh_gen_retry#46dc1fb9 nonce:int128 server_nonce:int128 new_nonce_hash2:int128 = Set_client_DH_params_answer;\ndh_gen_fail#a69dae02 nonce:int128 server_nonce:int128 new_nonce_hash3:int128 = Set_client_DH_params_answer;\ndestroy_auth_key_ok#f660e1d4 = DestroyAuthKeyRes;\ndestroy_auth_key_none#0a9f2259 = DestroyAuthKeyRes;\ndestroy_auth_key_fail#ea109b13 = DestroyAuthKeyRes;\n---functions---\nreq_pq#60469778 nonce:int128 = ResPQ;\nreq_pq_multi#be7e8ef1 nonce:int128 = ResPQ;\nreq_pq_multi_new#51b410fd nonce:int128 = ResPQ;\nreq_DH_params#d712e4be nonce:int128 server_nonce:int128 p:string q:string public_key_fingerprint:long encrypted_data:string = Server_DH_Params;\nset_client_DH_params#f5045f1f nonce:int128 server_nonce:int128 encrypted_data:string = Set_client_DH_params_answer;\ndestroy_auth_key#d1435160 = DestroyAuthKeyRes;\n---types---\nmsgs_ack#62d6b459 msg_ids:Vector = MsgsAck;\nbad_msg_notification#a7eff811 bad_msg_id:long bad_msg_seqno:int error_code:int = BadMsgNotification;\nbad_server_salt#edab447b bad_msg_id:long bad_msg_seqno:int error_code:int new_server_salt:long = BadMsgNotification;\nmsgs_state_req#da69fb52 msg_ids:Vector = MsgsStateReq;\nmsgs_state_info#04deb57d req_msg_id:long info:string = MsgsStateInfo;\nmsgs_all_info#8cc0d131 msg_ids:Vector info:string = MsgsAllInfo;\nmsg_detailed_info#276d3ec6 msg_id:long answer_msg_id:long bytes:int status:int = MsgDetailedInfo;\nmsg_new_detailed_info#809db6df answer_msg_id:long bytes:int status:int = MsgDetailedInfo;\nmsg_resend_req#7d861a08 msg_ids:Vector = MsgResendReq;\nrpc_error#2144ca19 error_code:int error_message:string = RpcError;\nfuture_salt#0949d9dc valid_since:int valid_until:int salt:long = FutureSalt;\nfuture_salts#ae500895 req_msg_id:long now:int salts:vector = FutureSalts;\npong#347773c5 msg_id:long ping_id:long = Pong;\ndestroy_session_ok#e22045fc session_id:long = DestroySessionRes;\ndestroy_session_none#62d350c9 session_id:long = DestroySessionRes;\nnew_session_created#9ec20908 first_msg_id:long unique_id:long server_salt:long = NewSession;\n---functions---\nping#7abe77ec ping_id:long = Pong;\nping_delay_disconnect#f3427b8c ping_id:long disconnect_delay:int = Pong;"}},s={};function a(e){var t=s[e];if(void 0!==t)return t.exports;var i=s[e]={id:e,loaded:!1,exports:{}};return n[e].call(i.exports,i,i.exports,a),i.loaded=!0,i.exports}a.m=n,a.x=()=>{var e=a.O(void 0,[592],(()=>a(6514)));return a.O(e)},e=[],a.O=(t,n,s,i)=>{if(!n){var o=1/0;for(l=0;l=i)&&Object.keys(a.O).every((e=>a.O[e](n[c])))?n.splice(c--,1):(r=!1,i0&&e[l-1][2]>i;l--)e[l]=e[l-1];e[l]=[n,s,i]},a.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return a.d(t,{a:t}),t},a.d=(e,t)=>{for(var n in t)a.o(t,n)&&!a.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},a.f={},a.e=e=>Promise.all(Object.keys(a.f).reduce(((t,n)=>(a.f[n](e,t),t)),[])),a.u=e=>e+".d7ca037ed9b7d1c6792a.js",a.miniCssF=e=>{},a.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),a.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),a.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},a.nmd=e=>(e.paths=[],e.children||(e.children=[]),e),(()=>{var e;a.g.importScripts&&(e=a.g.location+"");var t=a.g.document;if(!e&&t&&(t.currentScript&&(e=t.currentScript.src),!e)){var n=t.getElementsByTagName("script");n.length&&(e=n[n.length-1].src)}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),a.p=e})(),(()=>{var e={514:1};a.f.i=(t,n)=>{e[t]||importScripts(a.p+a.u(t))};var t=self.webpackChunktelegram_t=self.webpackChunktelegram_t||[],n=t.push.bind(t);t.push=t=>{var[s,i,o]=t;for(var r in i)a.o(i,r)&&(a.m[r]=i[r]);for(o&&o(a);s.length;)e[s.pop()]=1;n(t)}})(),t=a.x,a.x=()=>a.e(592).then(t),a.x()})(); -//# sourceMappingURL=514.89d97ccb086a4c539d1a.js.map \ No newline at end of file +(()=>{var e,t,n={6514:(e,t,n)=>{"use strict";var s={};n.r(s),n.d(s,{Type:()=>Ct,clear:()=>Pt,fetch:()=>It,save:()=>vt});var a={};n.r(a),n.d(a,{addChatMembers:()=>Sn,addContact:()=>ys,answerCallbackButton:()=>Ua,blockContact:()=>ra,checkChatUsername:()=>Fs,checkPassword:()=>Ws,checkUsername:()=>ea,clearDraft:()=>$t,clearPassword:()=>js,createChannel:()=>Qt,createGroupChat:()=>nn,deleteChannel:()=>tn,deleteChat:()=>Yt,deleteChatFolder:()=>ln,deleteChatMember:()=>An,deleteChatUser:()=>Zt,deleteHistory:()=>zn,deleteMessages:()=>Gn,deleteScheduledMessages:()=>Kn,deleteUser:()=>bs,destroy:()=>Et,disconnect:()=>Tt,downloadMedia:()=>Vt,editChatFolder:()=>dn,editChatPhoto:()=>sn,editMessage:()=>Fn,faveSticker:()=>As,fetchAnimatedEmojis:()=>ks,fetchAuthorizations:()=>da,fetchBlockedContacts:()=>oa,fetchChat:()=>zt,fetchChatFolders:()=>rn,fetchChats:()=>Ht,fetchCommonChats:()=>gs,fetchContactList:()=>hs,fetchContentSettings:()=>Pa,fetchCountryList:()=>Ma,fetchCurrentUser:()=>Ot,fetchEmojiKeywords:()=>xs,fetchFavoriteStickers:()=>Ps,fetchFeaturedStickers:()=>Ss,fetchFullChat:()=>Gt,fetchFullUser:()=>us,fetchGroupsForDiscussion:()=>Cn,fetchInlineBot:()=>Ta,fetchInlineBotResults:()=>Da,fetchLangPack:()=>_a,fetchLangStrings:()=>ya,fetchLanguages:()=>ma,fetchMembers:()=>wn,fetchMessage:()=>Bn,fetchMessages:()=>Dn,fetchNearestCountry:()=>ps,fetchNotificationExceptions:()=>ga,fetchNotificationSettings:()=>pa,fetchPinnedMessages:()=>os,fetchPrivacySettings:()=>ba,fetchProfilePhotos:()=>ws,fetchRecentStickers:()=>vs,fetchRecommendedChatFolders:()=>cn,fetchSavedGifs:()=>Us,fetchScheduledHistory:()=>ss,fetchStickerSets:()=>Is,fetchStickers:()=>Ms,fetchStickersForEmoji:()=>Bs,fetchTopInlineBots:()=>Ea,fetchTopUsers:()=>fs,fetchUsers:()=>ms,fetchWallpapers:()=>aa,fetchWebPagePreview:()=>Zn,findFirstMessageIdAfterDate:()=>ns,forwardMessages:()=>ts,getChatByUsername:()=>gn,getPasswordInfo:()=>Ks,getPaymentForm:()=>La,getReceipt:()=>qa,importChatInvite:()=>Rn,installStickerSet:()=>Es,joinChannel:()=>Xt,leaveChannel:()=>en,loadPollOptionResults:()=>es,markMessageListRead:()=>jn,markMessagesRead:()=>$n,migrateChat:()=>vn,openChatByInvite:()=>Pn,pinMessage:()=>qn,provideAuthCode:()=>pt,provideAuthPassword:()=>ft,provideAuthPhoneNumber:()=>gt,provideAuthRegistration:()=>ht,provideRecoveryEmailCode:()=>Qs,registerDevice:()=>wa,reportMessages:()=>Wn,requestChatUpdate:()=>Wt,requestThreadInfoUpdate:()=>Jn,rescheduleMessage:()=>On,restartAuth:()=>mt,restartAuthWithQr:()=>_t,saveDraft:()=>jt,searchChats:()=>Kt,searchGifs:()=>Ds,searchMessagesGlobal:()=>Xn,searchMessagesLocal:()=>Qn,searchStickers:()=>Rs,sendInlineBotResult:()=>Ba,sendMessage:()=>Vn,sendPaymentForm:()=>Oa,sendPollVote:()=>Yn,sendScheduledMessages:()=>as,setChatUsername:()=>Os,setDiscussionGroup:()=>In,setPrivacySettings:()=>Ia,startBot:()=>xa,terminateAllAuthorizations:()=>ua,terminateAuthorization:()=>la,toggleChatArchived:()=>on,toggleChatPinned:()=>an,toggleDialogUnread:()=>un,togglePreHistoryHidden:()=>pn,toggleSignatures:()=>bn,unblockContact:()=>ca,uninstallStickerSet:()=>Ts,unpinAllMessages:()=>Hn,unregisterDevice:()=>Ca,updateChatAbout:()=>yn,updateChatAdmin:()=>mn,updateChatDefaultBannedRights:()=>fn,updateChatMemberBannedRights:()=>hn,updateChatMutedState:()=>Jt,updateChatTitle:()=>_n,updateContact:()=>_s,updateContactSignUpNotification:()=>fa,updateContentSettings:()=>Sa,updateIsOnline:()=>va,updateNotificationSettings:()=>ha,updatePassword:()=>$s,updatePrivateLink:()=>Ls,updateProfile:()=>Ys,updateProfilePhoto:()=>na,updateRecoveryEmail:()=>Js,updateUsername:()=>ta,uploadProfilePhoto:()=>sa,uploadWallpaper:()=>ia,validateRequestedInfo:()=>Fa});const i=("undefined"!=typeof window&&window.innerHeight,Math.round(425)),o=new Set(["newMessage","newScheduledMessage","deleteMessages","deleteScheduledMessages","deleteHistory"]),r=new Set(["image/png","image/gif","image/jpeg"]),c=new Set(["video/mp4"]),d=(new Set([...r,...c]),new Set(["AU","BD","CA","CO","EG","HN","IE","IN","JO","MX","MY","NI","NZ","PH","PK","SA","SV","US"]),"777000");let l,u;var g=n(3522);function p(e,t){return e.reduce(((e,n)=>(e[n[t]]=n,e)),{})}function f(e,t){return t.reduce(((t,n)=>(t[n]=e[n],t)),{})}var h=n(8960);function m(e,t=!1,n="image/jpeg"){return`${t?"":`data:${n};base64,`}${btoa(String.fromCharCode(...e))}`}function _(e){const{flags:t,CONSTRUCTOR_ID:n,SUBCLASS_OF_ID:s,className:a,classType:i,getBytes:o,...r}=e;return r}function y(e,t,n){return''.replace("{{path}}",function(e){let t="M";const n=e.length;for(let s=0;s=192?t+="AACAAAAHAAALMAAAQASTAVAAAZaacaaaahaaalmaaaqastava.az0123456789-,"[n-128-64]:(n>=128?t+=",":n>=64&&(t+="-"),t+=String(63&n))}return t+="z",t}(e)).replace("{{width}}",String(t)).replace("{{height}}",String(n))}const b={w:100,h:100};function w(e,t){if(!e||!e.length)return;const n=e.find((e=>e instanceof g.Api.PhotoStrippedSize));if(!n)return;const s=e.filter((e=>e instanceof g.Api.PhotoSize)),{w:a,h:i}=s.length?s[s.length-1]:b,{bytes:o}=n;return{dataUri:m(t&&"image/jpeg"!==t?o:(0,h.strippedPhotoToJpg)(o),void 0,t),width:a,height:i}}function C(e){const t=e.sizes.filter((e=>e instanceof g.Api.PhotoSize||e instanceof g.Api.PhotoSizeProgressive)).map(I);return{id:String(e.id),thumbnail:w(e.sizes),sizes:t}}function I(e){const{w:t,h:n,type:s}=e;return{width:t,height:n,type:s}}const v={localMessages:{},chats:{},users:{},messages:{},documents:{},stickerSets:{},photos:{},webDocuments:{}},P="application/x-tgsticker";function S(e){if(e instanceof g.Api.DocumentEmpty)return;const t=e.attributes.find((e=>e instanceof g.Api.DocumentAttributeSticker)),n=e.mimeType===P&&e.attributes.find((e=>e instanceof g.Api.DocumentAttributeFilename));if(!t&&!n)return;const s=e.attributes.find((e=>e instanceof g.Api.DocumentAttributeImageSize)),a=t&&t.stickerset instanceof g.Api.InputStickerSetID?t.stickerset:void 0,i=null==t?void 0:t.alt,o=e.mimeType===P,r=e.thumbs&&e.thumbs.find((e=>e instanceof g.Api.PhotoCachedSize)),c=e.thumbs&&e.thumbs.find((e=>e instanceof g.Api.PhotoPathSize)),d=r?function(e){const{w:t,h:n,bytes:s}=e;return{dataUri:m(s,void 0,"image/webp"),width:t,height:n}}(r):c&&s?function(e,t){const{w:n,h:s}=t;return{dataUri:`data:image/svg+xml;utf8,${y(e.bytes,n,s)}`,width:n,height:s}}(c,s):void 0,{w:l,h:u}=r||s||{};return{id:String(e.id),stickerSetId:a?String(a.id):"MEMOJI_STICKER",stickerSetAccessHash:a&&String(a.accessHash),emoji:i,isAnimated:o,width:l,height:u,thumbnail:d}}function A(e){const{archived:t,animated:n,installedDate:s,id:a,accessHash:i,title:o,thumbs:r,count:c,shortName:d}=e;return{archived:t,isAnimated:n,installedDate:s,id:String(a),accessHash:String(i),title:o,hasThumbnail:Boolean(null==r?void 0:r.length),count:c,shortName:d}}function M(e){const t=A(e.set),n=e instanceof g.Api.StickerSetMultiCovered?e.covers:[e.cover];return t.covers=[],n.forEach((e=>{if(e instanceof g.Api.Document){const n=S(e);n&&(t.covers.push(n),v.documents[String(e.id)]=e)}})),t}function k(e,t){let n=0;const s=new Array(t),a=e.length/t,i=e[0],o=e[e.length-1];for(let l=0;l0?"user":e<=-1e9?"channel":"chat"}(e):e.startsWith("-")?e.length>=11?"channel":"chat":"user"}function V(e){const t=x(e);return"user"===t?new g.Api.PeerUser({userId:Y(e,"user")}):"channel"===t?new g.Api.PeerChannel({channelId:Y(e,"channel")}):new g.Api.PeerChat({chatId:Y(e,"chat")})}function N(e,t){const n=x(e);return"user"===n?new g.Api.InputPeerUser({userId:Y(e,"user"),accessHash:U()(t)}):"channel"===n?new g.Api.InputPeerChannel({channelId:Y(e,"channel"),accessHash:U()(t)}):new g.Api.InputPeerChat({chatId:Y(e,"chat")})}function F(e){const t=x(e);let n;var s;if("user"===t){if(n=null===(s=v.users[e])||void 0===s?void 0:s.accessHash,!n)return}else if("channel"===t){var a;if(n=null===(a=v.chats[e])||void 0===a?void 0:a.accessHash,!n)return}return N(e,String(n))}function O(e,t){const n=x(e);return"user"===n?new g.Api.InputUser({userId:Y(e,"user"),accessHash:U()(t)}):"channel"===n?new g.Api.InputChannel({channelId:Y(e,"channel"),accessHash:U()(t)}):Y(e,"chat")}function L(e,t){return new g.Api.InputStickerSetID({id:U()(e),accessHash:U()(t)})}function q(e){const t=v.documents[e.id];if(t)return new g.Api.InputDocument(f(t,["id","accessHash","fileReference"]))}function H(e){const t=q(e);if(t)return new g.Api.InputMediaDocument({id:t})}function G(){return(0,E.readBigIntFromBuffer)((0,E.generateRandomBytes)(8),!0,!0)}function K(e,t,n){return new g.Api.Message({id:e,peerId:V(t),fromId:V(t),media:n.media})}function z(e){const{type:t,offset:n,length:s,url:a,userId:i}=e,o=i?v.users[i]:void 0;switch(t){case T.Bold:return new g.Api.MessageEntityBold({offset:n,length:s});case T.Italic:return new g.Api.MessageEntityItalic({offset:n,length:s});case T.Underline:return new g.Api.MessageEntityUnderline({offset:n,length:s});case T.Strike:return new g.Api.MessageEntityStrike({offset:n,length:s});case T.Code:return new g.Api.MessageEntityCode({offset:n,length:s});case T.Pre:return new g.Api.MessageEntityPre({offset:n,length:s,language:""});case T.Blockquote:return new g.Api.MessageEntityBlockquote({offset:n,length:s});case T.TextUrl:return new g.Api.MessageEntityTextUrl({offset:n,length:s,url:a});case T.Url:return new g.Api.MessageEntityUrl({offset:n,length:s});case T.Hashtag:return new g.Api.MessageEntityHashtag({offset:n,length:s});case T.MentionName:return new g.Api.InputMessageEntityMentionName({offset:n,length:s,userId:new g.Api.InputUser({userId:U()(i),accessHash:o.accessHash})});default:return new g.Api.MessageEntityUnknown({offset:n,length:s})}}function W(e){const{media:t}=e;return!!t&&(t instanceof g.Api.MessageMediaPhoto||t instanceof g.Api.MessageMediaDocument||t instanceof g.Api.MessageMediaWebPage&&t.webpage instanceof g.Api.WebPage&&(t.webpage.photo instanceof g.Api.Photo||t.webpage.document instanceof g.Api.Document&&t.webpage.document.mimeType.startsWith("video")))}function j({phone:e,firstName:t,lastName:n}){return new g.Api.InputPhoneContact({clientId:U()(1),phone:e,firstName:t,lastName:n})}function $(e,t=0){return new g.Api.ChatBannedRights({...e,untilDate:t})}function J(e){return new g.Api.ChatAdminRights(e)}function Q(e){const{shippingAddress:t}=e;return new g.Api.PaymentRequestedInfo({...e,shippingAddress:t?new g.Api.PostAddress(t):void 0})}function X(e){switch(e){case"phoneNumber":return new g.Api.InputPrivacyKeyPhoneNumber;case"lastSeen":return new g.Api.InputPrivacyKeyStatusTimestamp;case"profilePhoto":return new g.Api.InputPrivacyKeyProfilePhoto;case"forwards":return new g.Api.InputPrivacyKeyForwards;case"chatInvite":return new g.Api.InputPrivacyKeyChatInvite}}function Z(e){switch(e){case"spam":return new g.Api.InputReportReasonSpam;case"violence":return new g.Api.InputReportReasonViolence;case"childAbuse":return new g.Api.InputReportReasonChildAbuse;case"pornography":return new g.Api.InputReportReasonPornography;case"copyright":return new g.Api.InputReportReasonCopyright;case"fake":return new g.Api.InputReportReasonFake;case"geoIrrelevant":return new g.Api.InputReportReasonGeoIrrelevant;case"other":return new g.Api.InputReportReasonOther}}function Y(e,t){return"number"==typeof e?U()(Math.abs(e)):"user"===t?U()(e):U()(e.slice(1))}function ee(e){return e.hasOwnProperty("userId")}function te(e){return e.hasOwnProperty("chatId")}function ne(e,t){return"user"===t?String(e):`-${e}`}function se(e){return ee(e)?ne(e.userId,"user"):te(e)?ne(e.chatId,"chat"):ne(e.channelId,"channel")}function ae(e){if(e instanceof g.Api.Message||e instanceof g.Api.MessageService)return se(e.peerId)}function ie(e){const t=`${ae(e)}-${e.id}`;v.messages[t]=e,e instanceof g.Api.Message&&e.media instanceof g.Api.MessageMediaDocument&&e.media.document instanceof g.Api.Document&&(v.documents[String(e.media.document.id)]=e.media.document),e instanceof g.Api.Message&&e.media instanceof g.Api.MessageMediaWebPage&&e.media.webpage instanceof g.Api.WebPage&&e.media.webpage.document instanceof g.Api.Document&&(v.documents[String(e.media.webpage.document.id)]=e.media.webpage.document),e instanceof g.Api.MessageService&&"photo"in e.action&&oe(e.action.photo)}function oe(e){e instanceof g.Api.Photo&&(v.photos[String(e.id)]=e)}function re(e){(e instanceof g.Api.Chat||e instanceof g.Api.Channel)&&(v.chats[ne(e.id,e instanceof g.Api.Chat?"chat":"channel")]=e)}const ce="temp";let de,le=1e9;function ue(e){const t=ae(e);if(t&&(e instanceof g.Api.Message||e instanceof g.Api.MessageService))return ge(t,e)}function ge(e,t){const n=t.fromId?se(t.fromId):void 0,s=t.peerId?se(t.peerId):void 0,a=!n&&e===de,i=t.out&&!t.post||a&&!t.fwdFrom;let o={};t.media&&(o={...he(t.media)}),!t.message||o.sticker||o.poll||o.contact||(o={...o,text:pe(t.message,t.entities)});const r=t.action&&function(e,t,n,s,a){if(e instanceof g.Api.MessageActionEmpty)return;let i,o,r;const c=[];let d,l="other";const u="users"in e?e.users&&e.users.map((e=>ne(e,"user"))):"userId"in e&&[ne(e.userId,"user")]||[];let p;if(e instanceof g.Api.MessageActionChatCreate)r="Notification.CreatedChatWithTitle",c.push("%action_origin%",e.title),l="chatCreate";else if(e instanceof g.Api.MessageActionChatEditTitle)s?(r="Channel.MessageTitleUpdated",c.push(e.title)):(r="Notification.ChangedGroupName",c.push("%action_origin%",e.title));else if(e instanceof g.Api.MessageActionChatEditPhoto)s?r="Channel.MessagePhotoUpdated":(r="Notification.ChangedGroupPhoto",c.push("%action_origin%"));else if(e instanceof g.Api.MessageActionChatDeletePhoto)r=s?"Channel.MessagePhotoRemoved":"Group.MessagePhotoRemoved";else if(e instanceof g.Api.MessageActionChatAddUser)!t||u.includes(t)?(r="Notification.JoinedChat",c.push("%target_user%")):(r="Notification.Invited",c.push("%action_origin%","%target_user%"));else if(e instanceof g.Api.MessageActionChatDeleteUser)!t||u.includes(t)?(r="Notification.LeftChat",c.push("%target_user%")):(r="Notification.Kicked",c.push("%action_origin%","%target_user%"));else if(e instanceof g.Api.MessageActionChatJoinedByLink)r="Notification.JoinedGroupByLink",c.push("%action_origin%");else if(e instanceof g.Api.MessageActionChannelCreate)r="Notification.CreatedChannel";else if(e instanceof g.Api.MessageActionChatMigrateTo)p=se(e),r="Migrated to %target_chat%",c.push("%target_chat%");else if(e instanceof g.Api.MessageActionChannelMigrateFrom)p=se(e),r="Migrated from %target_chat%",c.push("%target_chat%");else if(e instanceof g.Api.MessageActionPinMessage)r="Chat.Service.Group.UpdatedPinnedMessage1",c.push("%action_origin%","%message%");else if(e instanceof g.Api.MessageActionHistoryClear)r="HistoryCleared",l="historyClear";else if(e instanceof g.Api.MessageActionPhoneCall){const t=Boolean(e.duration);if(r=[t?"ChatList.Service":"Chat",e.video?"VideoCall":"Call",a?t?"outgoing":"Outgoing":t?"incoming":"Incoming"].join("."),t){const t=Math.max(Math.round(e.duration/60),1);c.push(`${t} min${t>1?"s":""}`)}}else if(e instanceof g.Api.MessageActionContactSignUp)r="Notification.Joined",c.push("%action_origin%"),l="contactSignUp";else if(e instanceof g.Api.MessageActionPaymentSent)i=Number(e.totalAmount),o=e.currency,r="PaymentSuccessfullyPaid",n&&u.push(n),c.push("%payment_amount%","%target_user%","%product%");else if(e instanceof g.Api.MessageActionGroupCall)if(e.duration){const t=Math.max(Math.round(e.duration/60),1);r="Notification.VoiceChatEnded",c.push(`${t} min${t>1?"s":""}`)}else r="Notification.VoiceChatStartedChannel";else e instanceof g.Api.MessageActionBotAllowed?(r="Chat.Service.BotPermissionAllowed",c.push(e.domain)):r="ChatList.UnsupportedMessage";return"photo"in e&&e.photo instanceof g.Api.Photo&&(oe(e.photo),d=C(e.photo)),{text:r,type:l,targetUserIds:u,targetChatId:p,photo:d,amount:i,currency:o,translationValues:c}}(t.action,n,s,Boolean(t.post),i);r&&(o.action=r);const{replyToMsgId:c,replyToTopId:d,replyToPeerId:l}=t.replyTo||{},u=t.editDate&&!t.editHide,{inlineButtons:p,keyboardButtons:f,keyboardPlaceholder:h,isKeyboardSingleUse:m}=function(e){const{id:t,replyMarkup:n,media:s}=e;if(!n)return s instanceof g.Api.MessageMediaWebPage&&s.webpage instanceof g.Api.WebPage&&"telegram_message"===s.webpage.type?{inlineButtons:[[{type:"url",text:"Show Message",messageId:t,value:s.webpage.url}]]}:void 0;if(!(n instanceof g.Api.ReplyKeyboardMarkup||n instanceof g.Api.ReplyInlineMarkup))return;const a=n.rows.map((({buttons:e})=>e.map((e=>{let n,a,{text:i}=e;return e instanceof g.Api.KeyboardButton?(n="command",a=i):e instanceof g.Api.KeyboardButtonUrl?(n="url",a=e.url):e instanceof g.Api.KeyboardButtonCallback?(n="callback",a=String(e.data)):e instanceof g.Api.KeyboardButtonRequestPoll?n="requestPoll":e instanceof g.Api.KeyboardButtonBuy?(s instanceof g.Api.MessageMediaInvoice&&s.receiptMsgId&&(i="PaymentReceipt",a=s.receiptMsgId),n="buy"):n="NOT_SUPPORTED",{type:n,text:i,messageId:t,value:a}}))));return{[n instanceof g.Api.ReplyKeyboardMarkup?"keyboardButtons":"inlineButtons"]:a,...n instanceof g.Api.ReplyKeyboardMarkup&&{keyboardPlaceholder:n.placeholder,isKeyboardSingleUse:n.singleUse}}}(t)||{},_=t.fwdFrom&&function(e,t=!1){const n=e.savedFromPeer&&se(e.savedFromPeer),s=e.fromId&&se(e.fromId);return{isChannelPost:Boolean(e.channelPost),channelPostId:e.channelPost,isLinkedChannelPost:Boolean(e.channelPost&&n&&!t),fromChatId:n||s,fromMessageId:e.channelPost||e.savedFromMsgId,senderUserId:s,hiddenUserName:e.fromName,adminTitle:e.postAuthor}}(t.fwdFrom,a),{replies:y,mediaUnread:b,postAuthor:w}=t,I=t.groupedId&&String(t.groupedId),v=Boolean(I)&&!(o.document||o.audio),P=t.replyMarkup instanceof g.Api.ReplyKeyboardHide;return{id:t.id,chatId:e,isOutgoing:i,content:o,date:t.date,senderId:n||t.out&&t.post&&de||e,views:t.views,isFromScheduled:t.fromScheduled,...c&&{replyToMessageId:c},...l&&{replyToChatId:se(l)},...d&&{replyToTopMessageId:d},..._&&{forwardInfo:_},...u&&{isEdited:u},...b&&{isMediaUnread:b},...t.mentioned&&b&&{hasUnreadMention:!0},...t.mentioned&&{isMentioned:!0},...I&&{groupedId:I,isInAlbum:v},inlineButtons:p,...f&&{keyboardButtons:f,keyboardPlaceholder:h,isKeyboardSingleUse:m},...P&&{shouldHideKeyboardButtons:P},...t.viaBotId&&{viaBotId:ne(t.viaBotId,"user")},...(null==y?void 0:y.comments)&&{threadInfo:Pe(y,t.id,e)},...w&&{adminTitle:w}}}function pe(e,t){return{text:e,...t&&{entities:t.map(ve)}}}function fe(e){if(e instanceof g.Api.DraftMessageEmpty)return;const{message:t,entities:n,replyToMsgId:s,date:a}=e;return{formattedText:t?pe(t,n):void 0,replyingToId:s,date:a}}function he(e){if("ttlSeconds"in e&&e.ttlSeconds)return;const t=function(e){if(e instanceof g.Api.MessageMediaDocument&&e.document&&e.document instanceof g.Api.Document)return S(e.document)}(e);if(t)return{sticker:t};const n=function(e){if(e instanceof g.Api.MessageMediaPhoto&&e.photo&&e.photo instanceof g.Api.Photo)return C(e.photo)}(e);if(n)return{photo:n};const s=function(e){if(e instanceof g.Api.MessageMediaDocument&&e.document instanceof g.Api.Document&&e.document.mimeType.startsWith("video"))return me(e.document)}(e);if(s)return{video:s};const a=function(e){if(!(e instanceof g.Api.MessageMediaDocument&&e.document&&e.document instanceof g.Api.Document))return;const t=e.document.attributes.find((e=>e instanceof g.Api.DocumentAttributeAudio));if(!t||t.voice)return;const n=e.document.thumbs&&e.document.thumbs.filter((e=>e instanceof g.Api.PhotoSize)).map((e=>I(e)));return{fileName:Ce(e.document,"audio"),thumbnailSizes:n,...f(e.document,["size","mimeType"]),...f(t,["duration","performer","title"])}}(e);if(a)return{audio:a};const i=function(e){if(!(e instanceof g.Api.MessageMediaDocument&&e.document&&e.document instanceof g.Api.Document))return;const t=e.document.attributes.find((e=>e instanceof g.Api.DocumentAttributeAudio));if(!t||!t.voice)return;const{duration:n,waveform:s}=t;return{duration:n,waveform:s?Array.from(s):void 0}}(e);if(i)return{voice:i};const o=function(e){if(e instanceof g.Api.MessageMediaDocument&&e.document)return _e(e.document)}(e);if(o)return{document:o};const r=function(e){if(!(e instanceof g.Api.MessageMediaContact))return;const{firstName:t,lastName:n,phoneNumber:s,userId:a}=e;return{firstName:t,lastName:n,phoneNumber:s,userId:ne(a,"user")}}(e);if(r)return{contact:r};const c=function(e){if(e instanceof g.Api.MessageMediaPoll)return ye(e.poll,e.results)}(e);if(c)return{poll:c};const d=we(e);if(d)return{webPage:d};const l=function(e){if(e instanceof g.Api.MessageMediaInvoice)return function(e){const{description:t,title:n,photo:s,test:a,totalAmount:i,currency:o,receiptMsgId:r}=e;return{text:t,title:n,photoUrl:null==s?void 0:s.url,receiptMsgId:r,amount:Number(i),currency:o,isTest:a}}(e)}(e);return l?{invoice:l}:void 0}function me(e){if(e instanceof g.Api.DocumentEmpty)return;const{id:t,mimeType:n,thumbs:s,size:a,attributes:i}=e;if("video/quicktime"===n&&!self.isMovSupported)return;const o=i.find((e=>e instanceof g.Api.DocumentAttributeVideo));if(!o)return;const r=i.find((e=>e instanceof g.Api.DocumentAttributeAnimated)),{duration:c,w:d,h:l,supportsStreaming:u=!1,roundMessage:p=!1}=o;return{id:String(t),mimeType:n,duration:c,fileName:Ce(e,"video"),width:d,height:l,supportsStreaming:u,isRound:p,isGif:Boolean(r),thumbnail:w(s),size:a}}function _e(e){if(!(e instanceof g.Api.Document))return;const{id:t,size:n,mimeType:s,date:a,thumbs:i,attributes:o}=e,d=i&&w(i);let l,u;const p=i&&i.find((e=>e instanceof g.Api.PhotoSize));if(p)if(u={width:p.w,height:p.h},r.has(s)){l="photo";const e=o.find((e=>e instanceof g.Api.DocumentAttributeImageSize));if(e){const{w:t,h:n}=e;u={width:t,height:n}}}else c.has(s)&&(l="video");return{id:String(t),size:n,mimeType:s,timestamp:a,fileName:Ce(e),thumbnail:d,mediaType:l,mediaSize:u}}function ye(e,t){const{id:n,answers:s}=e,a=s.map((e=>({text:e.text,option:String.fromCharCode(...e.option)})));return{id:String(n),summary:{isPublic:e.publicVoters,...f(e,["closed","multipleChoice","quiz","question","closePeriod","closeDate"]),answers:a},results:be(t)}}function be(e){const{results:t,totalVoters:n,recentVoters:s,solution:a,solutionEntities:i}=e,o=t&&t.map((({option:e,chosen:t,correct:n,voters:s})=>({isChosen:t,isCorrect:n,option:String.fromCharCode(...e),votersCount:s})));return{totalVoters:n,recentVoterIds:null==s?void 0:s.map((e=>ne(e,"user"))),results:o,solution:a,...i&&{solutionEntities:i.map(ve)}}}function we(e){if(!(e instanceof g.Api.MessageMediaWebPage&&e.webpage instanceof g.Api.WebPage))return;const{id:t,photo:n,document:s}=e.webpage;let a;return s instanceof g.Api.Document&&s.mimeType.startsWith("video/")&&(a=me(s)),{id:Number(t),...f(e.webpage,["url","displayUrl","type","siteName","title","description","duration"]),photo:n instanceof g.Api.Photo?C(n):void 0,document:!a&&s?_e(s):void 0,video:a}}function Ce(e,t="file"){const{mimeType:n,attributes:s}=e,a=s.find((e=>e instanceof g.Api.DocumentAttributeFilename));if(a)return a.fileName;const i=n.split("/")[1];return`${t}${String(e.id)}.${i}`}function Ie(e,t){return{poll:{id:String(t),summary:f(e.summary,["question","answers"]),results:{}}}}function ve(e){const{className:t,offset:n,length:s}=e;return{type:t,offset:n,length:s,..."userId"in e&&"number"==typeof e.userId&&{userId:e.userId},..."url"in e&&{url:e.url}}}function Pe(e,t,n){const{channelId:s,replies:a,maxId:i,readMaxId:o,recentRepliers:r}=e;if(!s)return;const c=ne(s,"channel");return"-777"!==c?{threadId:t,...n!==c?{chatId:c,originChannelId:n}:{chatId:n},messagesCount:a,lastMessageId:i,lastReadInboxMessageId:o,...r&&{recentReplierIds:r.map(se)}}:void 0}const Se=e=>Math.floor(Date.now()/1e3)+e;function Ae(e,t=!1){const n=Boolean("min"in e&&e.min),s="accessHash"in e&&String(e.accessHash),a="photo"in e&&e.photo&&Ve(e.photo),i=Boolean("signatures"in e&&e.signatures);return{isMin:n,hasPrivateLink:Boolean("hasLink"in e&&e.hasLink),isSignaturesShown:i,...s&&{accessHash:s},...a&&{avatarHash:a},...(e instanceof g.Api.Channel||e instanceof g.Api.User)&&{username:e.username},..."verified"in e&&{isVerified:e.verified},..."callActive"in e&&{isCallActive:e.callActive},..."callNotEmpty"in e&&{isCallNotEmpty:e.callNotEmpty},...(e instanceof g.Api.Chat||e instanceof g.Api.Channel)&&{...e.participantsCount&&{membersCount:e.participantsCount},joinDate:e.date},...t&&{isSupport:!0},...ke(e),..."creator"in e&&{isCreator:e.creator},...Re(e),...Ue(e)}}function Me(e,t,n){const{peer:s,folderId:a,unreadMark:i,unreadCount:o,unreadMentionsCount:r,notifySettings:{silent:c,muteUntil:d},readOutboxMaxId:l,readInboxMaxId:u,draft:p}=e,f=c||"number"==typeof d&&Se(n)"all"===e));return t?f(t,["reason","text"]):void 0}(e.restrictionReason):void 0;n&&Object.assign(t,{isRestricted:!0,restrictionReason:n})}return e instanceof g.Api.Chat&&Object.assign(t,{isNotJoined:e.left,isRestricted:e.kicked}),e instanceof g.Api.Channel&&Object.assign(t,{isNotJoined:e.left}),t}function Ue(e){return e instanceof g.Api.Chat&&e.migratedTo&&!(e.migratedTo instanceof g.Api.InputChannelEmpty)?{migratedTo:{chatId:se(e.migratedTo),...e.migratedTo instanceof g.Api.InputChannel&&{accessHash:String(e.migratedTo.accessHash)}}}:{}}function Ee(e,t=!1,n=!1){if(e instanceof g.Api.Chat||e instanceof g.Api.Channel||e instanceof g.Api.User||n&&(e instanceof g.Api.ChatForbidden||e instanceof g.Api.ChannelForbidden))return{id:ne(e.id,e instanceof g.Api.User?"user":"chat"),type:Te(e),title:e instanceof g.Api.User?xe(e):e.title,...Ae(e,t)}}function Te(e){return e instanceof g.Api.User||e instanceof g.Api.UserEmpty?"chatTypePrivate":e instanceof g.Api.Chat||e instanceof g.Api.ChatForbidden||e instanceof g.Api.ChatEmpty?"chatTypeBasicGroup":e.megagroup?"chatTypeSuperGroup":"chatTypeChannel"}function De(e){return ee(e)?`user${e.userId}`:te(e)?`chat${e.chatId}`:`chat${e.channelId}`}function Be(e,t){return ee(e)?xe(t):t.title}function xe(e){return e.firstName?`${e.firstName}${e.lastName?` ${e.lastName}`:""}`:e.lastName||void 0}function Ve(e){if("photoId"in e)return String(e.photoId)}function Ne(e){return{userId:e instanceof g.Api.ChannelParticipantBanned||e instanceof g.Api.ChannelParticipantLeft?se(e.peer):ne(e.userId,"user"),inviterId:"inviterId"in e?ne(e.inviterId,"user"):void 0,joinedDate:"date"in e?e.date:void 0,kickedByUserId:"kickedBy"in e?ne(e.kickedBy,"user"):void 0,promotedByUserId:"promotedBy"in e?ne(e.promotedBy,"user"):void 0,bannedRights:"bannedRights"in e?_(e.bannedRights):void 0,adminRights:"adminRights"in e?_(e.adminRights):void 0,customTitle:"rank"in e?e.rank:void 0,...(e instanceof g.Api.ChannelParticipantAdmin||e instanceof g.Api.ChatParticipantAdmin)&&{isAdmin:!0},...(e instanceof g.Api.ChannelParticipantCreator||e instanceof g.Api.ChatParticipantCreator)&&{isOwner:!0}}}function Fe(e){return e instanceof g.Api.ChatParticipants||e instanceof g.Api.channels.ChannelParticipants?e.participants.map(Ne).filter(Boolean):void 0}function Oe(e,t){let n="";if(!(e.action instanceof g.Api.SendMessageCancelAction)){if(e.action instanceof g.Api.SendMessageTypingAction)n="lng_user_typing";else if(e.action instanceof g.Api.SendMessageRecordVideoAction)n="lng_send_action_record_video";else if(e.action instanceof g.Api.SendMessageUploadVideoAction)n="lng_send_action_upload_video";else if(e.action instanceof g.Api.SendMessageRecordAudioAction)n="lng_send_action_record_audio";else if(e.action instanceof g.Api.SendMessageUploadAudioAction)n="lng_send_action_upload_audio";else if(e.action instanceof g.Api.SendMessageUploadPhotoAction)n="lng_send_action_upload_photo";else if(e.action instanceof g.Api.SendMessageUploadDocumentAction)n="lng_send_action_upload_file";else if(e.action instanceof g.Api.SendMessageGeoLocationAction)n="selecting a location to share";else if(e.action instanceof g.Api.SendMessageChooseContactAction)n="selecting a contact to share";else if(e.action instanceof g.Api.SendMessageGamePlayAction)n="lng_playing_game";else if(e.action instanceof g.Api.SendMessageRecordRoundAction)n="lng_send_action_record_round";else if(e.action instanceof g.Api.SendMessageUploadRoundAction)n="lng_send_action_upload_round";else if(e.action instanceof g.Api.SendMessageChooseStickerAction)n="lng_send_action_choose_sticker";else if(e.action instanceof g.Api.SpeakingInGroupCallAction)return;return{action:n,...!(e instanceof g.Api.UpdateUserTyping)&&{userId:se(e.fromId)},timestamp:Date.now()+1e3*t}}}function Le(e){return{...(t=e,n=["id","title","emoticon","contacts","nonContacts","groups","bots","excludeMuted","excludeRead","excludeArchived"],n.reduce(((e,n)=>(t[n]&&(e[n]=t[n]),e)),{})),channels:e.broadcasts,pinnedChatIds:e.pinnedPeers.map(se).filter(Boolean),includedChatIds:e.includePeers.map(se).filter(Boolean),excludedChatIds:e.excludePeers.map(se).filter(Boolean)};var t,n}function qe({filter:e,description:t}){return{...Le(e),description:t}}function He(e){return e.reduce(((e,t)=>{const n=ne(t.userId,"user");return e.concat(t.commands.map((e=>({botId:n,..._(e)}))))}),[])}function Ge(e){const{about:t,commonChatsCount:n,pinnedMsgId:s,botInfo:a,blocked:i}=e,o=Ke(e.user);return{...o,fullInfo:{bio:t,commonChatsCount:n,pinnedMessageId:s,isBlocked:Boolean(i),...a&&{botDescription:a.description},...a&&a.commands.length&&{botCommands:We(o.id,a)}}}}function Ke(e){if(!(e instanceof g.Api.User))return;const{id:t,firstName:n,lastName:s}=e,a=e.photo instanceof g.Api.UserProfilePhoto?String(e.photo.photoId):void 0,i=(o=e).bot?"userTypeBot":o.deleted?"userTypeDeleted":"userTypeRegular";var o;return{id:ne(t,"user"),isMin:Boolean(e.min),...e.self&&{isSelf:!0},...e.verified&&{isVerified:!0},...(e.contact||e.mutualContact)&&{isContact:!0},type:i,...n&&{firstName:n},..."userTypeBot"===i&&{canBeInvitedToGroup:!e.botNochats},...s&&{lastName:s},username:e.username||"",phoneNumber:e.phone||"",status:ze(e.status),...e.accessHash&&{accessHash:String(e.accessHash)},...a&&{avatarHash:a},...e.bot&&e.botInlinePlaceholder&&{botPlaceholder:e.botInlinePlaceholder}}}function ze(e){return!e||e instanceof g.Api.UserStatusEmpty?{type:"userStatusEmpty"}:e instanceof g.Api.UserStatusOnline?{type:"userStatusOnline",expires:e.expires}:e instanceof g.Api.UserStatusOffline?{type:"userStatusOffline",wasOnline:e.wasOnline}:e instanceof g.Api.UserStatusRecently?{type:"userStatusRecently"}:e instanceof g.Api.UserStatusLastWeek?{type:"userStatusLastWeek"}:{type:"userStatusLastMonth"}}function We(e,t){return t.commands.map((({command:t,description:n})=>({botId:e,command:t,description:n})))}function je(e){if(e instanceof g.Api.WallPaperNoFile)return;const{slug:t}=e,n=_e(e.document);return n?{slug:t,document:n}:void 0}function $e(e){return{isCurrent:Boolean(e.current),isOfficialApp:Boolean(e.officialApp),isPasswordPending:Boolean(e.passwordPending),hash:String(e.hash),...f(e,["deviceModel","platform","systemVersion","appName","appVersion","dateCreated","dateActive","ip","country","region"])}}function Je(e){let t,n,s,a,i;return e.forEach((e=>{e instanceof g.Api.PrivacyValueAllowAll?t=t||"everybody":e instanceof g.Api.PrivacyValueAllowContacts?t=t||"contacts":e instanceof g.Api.PrivacyValueDisallowContacts?t=t||"nonContacts":e instanceof g.Api.PrivacyValueDisallowAll?t=t||"nobody":e instanceof g.Api.PrivacyValueAllowUsers?n=e.users.map((e=>ne(e,"user"))):e instanceof g.Api.PrivacyValueDisallowUsers?a=e.users.map((e=>ne(e,"user"))):e instanceof g.Api.PrivacyValueAllowChatParticipants?s=e.chats.map((e=>ne(e,"chat"))):e instanceof g.Api.PrivacyValueDisallowChatParticipants&&(i=e.chats.map((e=>ne(e,"chat"))))})),t||(t="nobody"),{visibility:t,allowUserIds:n||[],allowChatIds:s||[],blockUserIds:a||[],blockChatIds:i||[]}}function Qe(e,t,n){const{silent:s,muteUntil:a,showPreviews:i,sound:o}=e;return{chatId:se(t),isMuted:s||"number"==typeof a&&Se(n)e instanceof g.Api.User)).map(Ke).forEach((e=>{e&&Ze({"@type":"updateUser",id:e.id,user:e})})),i.filter((e=>e instanceof g.Api.Chat||e instanceof g.Api.Channel)).map((e=>Ee(e))).forEach((e=>{e&&Ze({"@type":"updateChat",id:e.id,chat:e})}))),e instanceof g.Api.UpdateNewScheduledMessage?Ze({"@type":Ye.has(t.id)?"updateScheduledMessage":"newScheduledMessage",id:t.id,chatId:t.chatId,message:t}):Ze({"@type":Ye.has(t.id)?"updateMessage":"newMessage",id:t.id,chatId:t.chatId,message:t,shouldForceReply:a}),e.message instanceof g.Api.MessageService){const{action:n}=e.message;if(n instanceof g.Api.MessageActionChatEditTitle)Ze({"@type":"updateChat",id:t.chatId,chat:{title:n.title}});else if(n instanceof g.Api.MessageActionChatEditPhoto){const s=function(e){if(e instanceof g.Api.PhotoEmpty)return new g.Api.ChatPhotoEmpty;const{dcId:t,id:n}=e;return new g.Api.ChatPhoto({dcId:t,photoId:n})}(n.photo),a=Ve(s),i=ae(e.message);v.chats[i]&&(v.chats[i].photo=s),oe(n.photo),a&&Ze({"@type":"updateChat",id:t.chatId,chat:{avatarHash:a},...n.photo instanceof g.Api.Photo&&{newProfilePhoto:C(n.photo)}})}else if(n instanceof g.Api.MessageActionChatDeletePhoto){const n=ae(e.message);v.chats[n]&&(v.chats[n].photo=new g.Api.ChatPhotoEmpty),Ze({"@type":"updateChat",id:t.chatId,chat:{avatarHash:void 0}})}else n instanceof g.Api.MessageActionChatDeleteUser?e._entities&&e._entities.some((e=>e instanceof g.Api.User&&!!e.self&&e.id===n.userId))&&(Ze({"@type":"updateChat",id:t.chatId,chat:{isRestricted:!0}}),Ze({"@type":"updateChatLeave",id:t.chatId})):n instanceof g.Api.MessageActionChatAddUser&&e._entities&&e._entities.some((e=>e instanceof g.Api.User&&!!e.self&&n.users.includes(e.id)))&&Ze({"@type":"updateChatJoin",id:t.chatId})}}else if(e instanceof g.Api.UpdateEditMessage||e instanceof g.Api.UpdateEditChannelMessage){if(e.message instanceof g.Api.MessageEmpty)return;e.message instanceof g.Api.Message&&W(e.message)&&ie(e.message);const t=ue(e.message);Ze({"@type":"updateMessage",id:t.id,chatId:t.chatId,message:t})}else if(e instanceof g.Api.UpdateDeleteMessages)Ze({"@type":"deleteMessages",ids:e.messages});else if(e instanceof g.Api.UpdateDeleteScheduledMessages)Ze({"@type":"deleteScheduledMessages",ids:e.messages,chatId:se(e.peer)});else if(e instanceof g.Api.UpdateDeleteChannelMessages){const t=ne(e.channelId,"channel"),n=e.messages,s=n.filter((e=>v.messages[`${t}-${e}`])),a=n.filter((e=>!v.messages[`${t}-${e}`])),i=n.map((e=>{const n=v.messages[`${t}-${e}`];return n&&n instanceof g.Api.MessageService&&"photo"in n.action?String(n.action.photo.id):void 0})).filter(Boolean);s.length&&Ze({"@type":"deleteMessages",ids:s,chatId:t}),i.length&&Ze({"@type":"deleteProfilePhotos",ids:i,chatId:t}),a.length&&setTimeout((()=>{Ze({"@type":"deleteMessages",ids:a,chatId:t})}),1e3)}else if(e instanceof g.Api.UpdateServiceNotification){const t=function(e,t){const n=le++;let s={};return e.media&&(s={...he(e.media)}),!e.message||s.sticker||s.poll||s.contact||(s={...s,text:pe(e.message,e.entities)}),{id:n,chatId:d,date:e.inboxDate||t,content:s,isOutgoing:!1}}(e,Date.now()/1e3+et);W(e)&&ie(K(t.id,t.chatId,e)),Ze({"@type":"updateServiceNotification",message:t})}else if((t instanceof g.Api.messages.SendMessage||t instanceof g.Api.messages.SendMedia||t instanceof g.Api.messages.SendMultiMedia||t instanceof g.Api.messages.ForwardMessages)&&(e instanceof g.Api.UpdateMessageID||e instanceof g.Api.UpdateShortSentMessage)){let n;"randomId"in e?n=e.randomId:"randomId"in t&&(n=t.randomId);const s=n&&v.localMessages[String(n)];if(!s)throw new Error("Local message not found");let a;if(e instanceof g.Api.UpdateShortSentMessage){s.content.text&&e.entities&&(a={text:pe(s.content.text.text,e.entities)}),e.media&&(a={...a,...he(e.media)});const t=K(e.id,s.chatId,e);W(t)&&ie(t)}Ye.add(e.id);const i="date"in e&&1e3*e.dateString.fromCharCode(...e)))});else if(e instanceof g.Api.UpdateChannelMessageViews)Ze({"@type":"updateMessage",chatId:ne(e.channelId,"channel"),id:e.id,message:{views:e.views}});else if(e instanceof g.Api.UpdateReadHistoryInbox)Ze({"@type":"updateChatInbox",id:se(e.peer),chat:{lastReadInboxMessageId:e.maxId,unreadCount:e.stillUnreadCount}});else if(e instanceof g.Api.UpdateReadHistoryOutbox)Ze({"@type":"updateChat",id:se(e.peer),chat:{lastReadOutboxMessageId:e.maxId}});else if(e instanceof g.Api.UpdateReadChannelInbox)Ze({"@type":"updateChat",id:ne(e.channelId,"channel"),chat:{lastReadInboxMessageId:e.maxId,unreadCount:e.stillUnreadCount}});else if(e instanceof g.Api.UpdateReadChannelOutbox)Ze({"@type":"updateChat",id:ne(e.channelId,"channel"),chat:{lastReadOutboxMessageId:e.maxId}});else if(e instanceof g.Api.UpdateDialogPinned&&e.peer instanceof g.Api.DialogPeer)Ze({"@type":"updateChatPinned",id:se(e.peer.peer),isPinned:e.pinned||!1});else if(e instanceof g.Api.UpdatePinnedDialogs){const t=e.order?e.order.filter((e=>e instanceof g.Api.DialogPeer)).map((e=>se(e.peer))):[];Ze({"@type":"updatePinnedChatIds",ids:t,folderId:e.folderId||void 0})}else if(e instanceof g.Api.UpdateFolderPeers)e.folderPeers.forEach((e=>{const{folderId:t,peer:n}=e;Ze({"@type":"updateChatListType",id:se(n),folderId:t})}));else if(e instanceof g.Api.UpdateDialogFilter){const{id:t,filter:n}=e,s=n?Le(n):void 0;Ze({"@type":"updateChatFolder",id:t,folder:s})}else if(e instanceof g.Api.UpdateDialogFilterOrder)Ze({"@type":"updateChatFoldersOrder",orderedIds:e.order});else if(e instanceof g.Api.UpdateChatParticipants){const t=Fe(e.participants);Ze({"@type":"updateChatMembers",id:ne(e.participants.chatId,"chat"),replacedMembers:t})}else if(e instanceof g.Api.UpdateChatParticipantAdd){const t=Ne(f(e,["userId","inviterId","date"]));Ze({"@type":"updateChatMembers",id:ne(e.chatId,"chat"),addedMember:t})}else if(e instanceof g.Api.UpdateChatParticipantDelete)Ze({"@type":"updateChatMembers",id:ne(e.chatId,"chat"),deletedMemberId:ne(e.userId,"user")});else if(e instanceof g.Api.UpdatePinnedMessages||e instanceof g.Api.UpdatePinnedChannelMessages){const t=e instanceof g.Api.UpdatePinnedMessages?se(e.peer):ne(e.channelId,"channel");Ze({"@type":"updatePinnedIds",chatId:t,messageIds:e.messages,isPinned:e.pinned})}else if(e instanceof g.Api.UpdateNotifySettings&&e.peer instanceof g.Api.NotifyPeer)Ze({"@type":"updateNotifyExceptions",...Qe(e.notifySettings,e.peer.peer,et)});else if(e instanceof g.Api.UpdateUserTyping||e instanceof g.Api.UpdateChatUserTyping){const t=e instanceof g.Api.UpdateUserTyping?ne(e.userId,"user"):ne(e.chatId,"chat");Ze({"@type":"updateChatTypingStatus",id:t,typingStatus:Oe(e,et)})}else if(e instanceof g.Api.UpdateChannelUserTyping){const t=ne(e.channelId,"channel");Ze({"@type":"updateChatTypingStatus",id:t,typingStatus:Oe(e,et)})}else if(e instanceof g.Api.UpdateChannel){const{_entities:t}=e;if(!t)return;const n=t.find((e=>e instanceof g.Api.Channel||e instanceof g.Api.ChannelForbidden));if(n instanceof g.Api.Channel){const t=Ee(n);t&&(Ze({"@type":"updateChat",id:t.id,chat:t}),Ze({"@type":t.isNotJoined?"updateChatLeave":"updateChatJoin",id:ne(e.channelId,"channel")}))}else if(n instanceof g.Api.ChannelForbidden){const t=ne(e.channelId,"channel");Ze({"@type":"updateChat",id:t,chat:{isRestricted:!0}}),Ze({"@type":"updateChatLeave",id:t})}else 0===t.length&&Ze({"@type":"resetMessages",id:ne(e.channelId,"channel")})}else if(e instanceof g.Api.UpdateDialogUnreadMark&&e.peer instanceof g.Api.DialogPeer)Ze({"@type":"updateChat",id:se(e.peer.peer),chat:{hasUnreadMark:e.unread}});else if(e instanceof g.Api.UpdateChatDefaultBannedRights)Ze({"@type":"updateChat",id:se(e.peer),chat:{defaultBannedRights:_(e.defaultBannedRights)}});else if(e instanceof g.Api.UpdateUserStatus)Ze({"@type":"updateUserStatus",userId:ne(e.userId,"user"),status:ze(e.status)});else if(e instanceof g.Api.UpdateUserName){const t=ne(e.userId,"user"),n=v.users[t],s=null!=n&&n.mutualContact&&!n.self?f(e,["username"]):f(e,["firstName","lastName","username"]);Ze({"@type":"updateUser",id:t,user:s})}else if(e instanceof g.Api.UpdateUserPhoto){const{userId:t,photo:n}=e,s=ne(t,"user"),a=Ve(n);v.users[s]&&(v.users[s].photo=n),Ze({"@type":"updateUser",id:s,user:{avatarHash:a}})}else if(e instanceof g.Api.UpdateUserPhone){const{userId:t,phone:n}=e;Ze({"@type":"updateUser",id:ne(t,"user"),user:{phoneNumber:n}})}else if(e instanceof g.Api.UpdatePeerSettings){const{_entities:t}=e;if(!t)return;null!=t&&t.length&&(t.filter((e=>e instanceof g.Api.User&&!e.contact)).forEach((e=>{Ze({"@type":"deleteUser",id:ne(e.id,"user")})})),t.filter((e=>e instanceof g.Api.User&&e.contact)).map(Ke).forEach((e=>{e&&Ze({"@type":"updateUser",id:e.id,user:e})})))}else if(e instanceof g.Api.UpdateNotifySettings){const{notifySettings:{showPreviews:t,silent:n,muteUntil:s},peer:{className:a}}=e,i="NotifyUsers"===a?"contact":"NotifyChats"===a?"group":"NotifyBroadcasts"===a?"broadcast":void 0;if(!i)return;Ze({"@type":"updateNotifySettings",peerType:i,isSilent:Boolean(n||"number"==typeof s&&Date.now()+1e3*et<1e3*s),shouldShowPreviews:Boolean(t)})}else if(e instanceof g.Api.UpdatePeerBlocked)Ze({"@type":"updatePeerBlocked",id:se(e.peerId),isBlocked:e.blocked});else if(e instanceof g.Api.UpdatePrivacy){const t=function(e){switch(e.className){case"PrivacyKeyPhoneNumber":return"phoneNumber";case"PrivacyKeyStatusTimestamp":return"lastSeen";case"PrivacyKeyProfilePhoto":return"profilePhoto";case"PrivacyKeyForwards":return"forwards";case"PrivacyKeyChatInvite":return"chatInvite"}}(e.key);t&&Ze({"@type":"updatePrivacy",key:t,rules:Je(e.rules)})}else e instanceof g.Api.UpdateDraftMessage?Ze({"@type":"draftMessage",chatId:se(e.peer),...fe(e.draft)}):e instanceof g.Api.UpdateContactsReset?Ze({"@type":"updateResetContactList"}):e instanceof g.Api.UpdateFavedStickers&&Ze({"@type":"updateFavoriteStickers"});var s}const nt={PHONE_NUMBER_INVALID:"Invalid phone number.",PHONE_CODE_INVALID:"Invalid code.",PASSWORD_HASH_INVALID:"Incorrect password.",PHONE_PASSWORD_FLOOD:"Limit exceeded. Please try again later.",PHONE_NUMBER_BANNED:"This phone number is banned."},st={};let at;function it(){return at(ut("authorizationStateWaitPhoneNumber")),new Promise(((e,t)=>{st.resolve=e,st.reject=t}))}function ot(e=!1){return at({...ut("authorizationStateWaitCode"),isCodeViaApp:e}),new Promise(((e,t)=>{st.resolve=e,st.reject=t}))}function rt(e){return at({...ut("authorizationStateWaitPassword"),hint:e}),new Promise((e=>{st.resolve=e}))}function ct(){return at(ut("authorizationStateWaitRegistration")),new Promise((e=>{st.resolve=e}))}function dt(e){return at({...ut("authorizationStateWaitQrCode"),qrCode:{token:btoa(String.fromCharCode(...e.token)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),expires:e.expires}}),new Promise(((e,t)=>{st.reject=t}))}function lt(e){let t;if(e instanceof g.errors.FloodWaitError){const n=Math.ceil(Number(e.seconds)/60/60);t="Too many attempts. Try again in "+(n>1?`${n} hours`:"an hour")}else t=nt[e.message];t||(t="Unexpected Error"),at({"@type":"updateAuthorizationError",message:t})}function ut(e){return{"@type":"updateAuthorizationState",authorizationState:e}}function gt(e){st.resolve&&st.resolve(e)}function pt(e){st.resolve&&st.resolve(e)}function ft(e){st.resolve&&st.resolve(e)}function ht(e){const{firstName:t,lastName:n}=e;st.resolve&&st.resolve([t,n])}function mt(){st.reject&&st.reject(new Error("RESTART_AUTH"))}function _t(){st.reject&&st.reject(new Error("RESTART_AUTH_WITH_QR"))}var yt=n(9832),bt=n(5802);const wt=self.caches;let Ct;async function It(e,t,n,s=!1){if(wt)try{const a=new Request(t.replace(/:/g,"_")),i=await wt.open(e),o=await i.match(a);if(!o)return;const r=o.headers.get("Content-Type");switch(n){case Ct.Text:return await o.text();case Ct.Blob:{if(t.startsWith("avatar")&&r&&r.startsWith("text"))return;const e=await o.blob();if(t.startsWith("sticker"))return new Blob([e],{type:"image/webp"});const n=!e.type||!s&&e.type.includes("html");let a=e.type||r;return n&&a?(s||(a=a.replace(/html/gi,"")),new Blob([e],{type:a})):e}case Ct.Json:return await o.json();default:return}}catch(e){return void console.warn(e)}}async function vt(e,t,n){if(wt)try{const s="string"==typeof n||n instanceof Blob?n:JSON.stringify(n),a=new Request(t.replace(/:/g,"_")),i=new Response(s),o=await wt.open(e);return await o.put(a,i)}catch(e){return void console.warn(e)}}async function Pt(e){try{if(!wt)return;return await wt.delete(e)}catch(e){return void console.warn(e)}}!function(e){e[e.Text=0]="Text",e[e.Blob=1]="Blob",e[e.Json=2]="Json"}(Ct||(Ct={}));const St=new Set(["msg","sticker","gif","wallpaper","photo","webDocument"]);function At(e,t="image/jpeg"){if(e.length<4)return t;let n=t;switch(e.subarray(0,4).reduce(((e,t)=>e+t.toString(16)),"")){case"89504e47":n="image/png";break;case"47494638":n="image/gif";break;case"ffd8ffe0":case"ffd8ffe1":case"ffd8ffe2":case"ffd8ffe3":case"ffd8ffe8":n="image/jpeg";break;case"52494646":n="image/webp"}return n}yt.Logger.setLevel("warn");const Mt={build:e=>e};let kt,Rt,Ut=!1;async function Et(){await xt(new g.Api.auth.LogOut),await Rt.destroy()}async function Tt(){await Rt.disconnect()}function Dt(e){kt({"@type":"updateSession",sessionData:e})}function Bt(e){e instanceof g.connection.UpdateConnectionState?Ut=e.state===g.connection.UpdateConnectionState.connected:e instanceof g.Api.UpdatesTooLong?async function(){try{await xt(new g.Api.users.GetFullUser({id:new g.Api.InputUserSelf}),void 0,!0)}catch(e){"AUTH_KEY_UNREGISTERED"===e.message&&kt({"@type":"updateConnectionState",connectionState:"connectionStateBroken"})}}():e instanceof g.connection.UpdateServerTimeOffset&&kt({"@type":"updateServerTimeOffset",serverTimeOffset:e.timeOffset})}async function xt(e,t=!1,n=!1){if(Ut)try{const n=await Rt.invoke(e);if(t){let t;n instanceof g.Api.Updates||n instanceof g.Api.UpdatesCombined?t=n:"updates"in n&&(n.updates instanceof g.Api.Updates||n.updates instanceof g.Api.UpdatesCombined)&&(t=n.updates),t?(function(e){const t=[...e.users,...e.chats];e.updates.forEach((e=>{t&&(e._entities=t)}))}(t),t.updates.forEach((t=>{tt(t,e)}))):n instanceof g.Api.UpdatesTooLong||tt(n,e)}return n}catch(t){if(n)throw t;return void function(e,t){const n=e.message.startsWith("A wait of")&&(t instanceof g.Api.messages.SendMessage||t instanceof g.Api.messages.SendMedia||t instanceof g.Api.messages.SendMultiMedia),{message:s}=e;kt({"@type":"error",error:{message:s,isSlowMode:n,hasErrorKey:!0}})}(t,e)}}function Vt(e,t){return async function({url:e,mediaFormat:t,start:n,end:a,isHtmlAllowed:i},o,r,c){const{data:d,mimeType:l,fullSize:u}=await async function(e,t,n,s,a,i,o,r){const c=e.startsWith("webDocument")?e.match(/(webDocument):(.+)/):e.match(/(avatar|profile|photo|msg|stickerSet|sticker|wallpaper|gif|file)([-\d\w./]+)(\?size=\w+)?/);if(!c)return;if("file"===c[1]){const e=await fetch(c[2]);return{data:await e.arrayBuffer()}}if(!n)return Promise.reject(new Error("ERROR: Client is not connected"));let d;const l=c[2],u=c[3]?c[3].replace("?size=",""):void 0;let p;switch(d="avatar"===c[1]||"profile"===c[1]?x(l):c[1],d){case"channel":case"chat":p=v.chats[l];break;case"user":p=v.users[l];break;case"msg":p=v.messages[l];break;case"sticker":case"gif":case"wallpaper":p=v.documents[l];break;case"photo":p=v.photos[l];break;case"stickerSet":p=v.stickerSets[l];break;case"webDocument":p=v.webDocuments[l]}if(p){if(St.has(d)){o===D.Stream&&(s.acceptsBuffer=!0);const e=await t.downloadMedia(p,{sizeType:u,start:a,end:i,progressCallback:s,workers:16});let n,c;return p instanceof g.Api.Message?(n=function(e,t){if(e&&e.media)return e.media instanceof g.Api.MessageMediaPhoto?"image/jpeg":e.media instanceof g.Api.MessageMediaDocument&&e.media.document instanceof g.Api.Document?t?e.media.document.attributes.some((e=>e instanceof g.Api.DocumentAttributeSticker))?"image/webp":"image/jpeg":e.media.document.mimeType:e.media instanceof g.Api.MessageMediaWebPage&&e.media.webpage instanceof g.Api.WebPage&&e.media.webpage.document instanceof g.Api.Document?e.media.webpage.document.mimeType:void 0}(p,u),p.media instanceof g.Api.MessageMediaDocument&&p.media.document instanceof g.Api.Document&&(c=p.media.document.size),p.media instanceof g.Api.MessageMediaWebPage&&p.media.webpage instanceof g.Api.WebPage&&p.media.webpage.document instanceof g.Api.Document&&(c=p.media.webpage.document.size)):p instanceof g.Api.Photo?n="image/jpeg":"sticker"===d&&u?n="image/webp":"webDocument"===d?n=p.mimeType:(n=p.mimeType,c=p.size),!r&&n&&(n=n.replace(/html/gi,"")),{mimeType:n,data:e,fullSize:c}}if("stickerSet"===d){const e=await t.downloadStickerSetThumb(p);return{mimeType:o===D.Lottie?"application/json":At(e),data:e}}{const e=await t.downloadProfilePhoto(p,"profile"===c[1]);return{mimeType:At(e),data:e}}}}(e,o,r,c,n,a,t,i)||{};if(!d)return;const p=await async function(e,t,n){switch(t){case D.BlobUrl:return new Blob([e],{type:n});case D.Lottie:{const t=(0,bt.inflate)(e,{to:"string"});return JSON.parse(t)}case D.Progressive:return e.buffer}}(d,t,l);if(!p)return;const f=t!==D.Progressive&&(t!==D.BlobUrl||p.size<=524288);return s&&f&&vt(e.startsWith("avatar")?"tt-media-avatars":"tt-media",e,p),{prepared:t===D.Progressive?"":(h=p,h instanceof Blob?URL.createObjectURL(h):h),arrayBuffer:t===D.Progressive?p:void 0,mimeType:l,fullSize:u};var h}(e,Rt,Ut,t)}function Nt(e,t){return Rt.uploadFile({file:e,onProgress:t,workers:16})}function Ft(e){return Rt.updateTwoFaSettings(e)}async function Ot(){const e=await xt(new g.Api.users.GetFullUser({id:new g.Api.InputUserSelf}));if(!(e&&e.user instanceof g.Api.User))return;v.users[ne(e.user.id,"user")]=e.user;const t=Ge(e);var n;n=t.id,de=n,function(e){at({"@type":"updateCurrentUser",currentUser:e})}(t)}const Lt=2**31-1;let qt;async function Ht({limit:e,offsetDate:t,archived:n,withPinned:s,serverTimeOffset:a,lastLocalServiceMessage:i}){const o=await xt(new g.Api.messages.GetDialogs({offsetPeer:new g.Api.InputPeerEmpty,limit:e,offsetDate:t,folderId:n?1:void 0,...s&&{excludePinned:!0}})),r=s?await xt(new g.Api.messages.GetPinnedDialogs({folderId:n?1:void 0})):void 0;if(!o||o instanceof g.Api.messages.DialogsNotModified)return;r&&kn(r),kn(o);const c=p((r?r.messages:[]).concat(o.messages).map(ue).filter(Boolean),"chatId"),l={...r&&Mn(r),...Mn(o)},u=[],f={},h={},m=(r?r.dialogs:[]).concat(o.dialogs),_=[];m.forEach((e=>{if(!(e instanceof g.Api.Dialog)||!n&&1===e.folderId||n&&1!==e.folderId)return;const t=Me(e,l[De(e.peer)],a);if(t.id===d&&i&&(!c[t.id]||i.date>c[t.id].date)?t.lastMessage=i:t.lastMessage=c[t.id],t.isListed=!0,u.push(t),s&&e.pinned&&_.push(t.id),e.draft){const{formattedText:n,replyingToId:s}=fe(e.draft)||{};n&&(f[t.id]=n),s&&(h[t.id]=s)}}));const y=(r?r.users:[]).concat(o.users).map(Ke).filter(Boolean),b=u.map((e=>e.id));let w;return w=o instanceof g.Api.messages.DialogsSlice?o.count:b.length,{chatIds:b,chats:u,users:y,draftsById:f,replyingToById:h,orderedPinnedIds:s?_:void 0,totalChatCount:w}}function Gt(e){const{id:t,accessHash:n,adminRights:s}=e;return O(t,n)instanceof g.Api.InputChannel?async function(e,t,n){var s;const a=await xt(new g.Api.channels.GetFullChannel({channel:O(e,t)}));if(!(a&&a.fullChat instanceof g.Api.ChannelFull))return;const{about:i,onlineCount:o,exportedInvite:r,slowmodeSeconds:c,slowmodeNextSendDate:d,migratedFromChatId:l,migratedFromMaxId:u,canViewParticipants:p,linkedChatId:f,hiddenPrehistory:h,call:m,botInfo:_}=a.fullChat,y=r instanceof g.Api.ChatInviteExported?r.link:void 0,{members:b,users:w}=p&&await wn(e,t)||{},{members:C,users:I}=p&&n&&await wn(e,t,"kicked")||{},{members:v,users:P}=p&&n&&await wn(e,t,"admin")||{},S=_?He(_):void 0;if((null==a||null===(s=a.chats)||void 0===s?void 0:s.length)>1){kn(a);const[,e]=a.chats,t=Ee(e,void 0,!0);t&&qt({"@type":"updateChat",id:t.id,chat:t})}return{fullInfo:{about:i,onlineCount:o,inviteLink:y,slowMode:c?{seconds:c,nextSendDate:d}:void 0,migratedFrom:l?{chatId:ne(l,"chat"),maxMessageId:u}:void 0,canViewMembers:p,isPreHistoryHidden:h,members:b,kickedMembers:C,adminMembers:v,groupCallId:m?String(m.id):void 0,linkedChatId:f?ne(f,"chat"):void 0,botCommands:S},users:[...w||[],...I||[],...P||[]]}}(t,n,s):async function(e){const t=await xt(new g.Api.messages.GetFullChat({chatId:O(e)}));if(!(t&&t.fullChat instanceof g.Api.ChatFull))return;kn(t);const{about:n,participants:s,exportedInvite:a,botInfo:i}=t.fullChat,o=Fe(s),r=o?o.filter((({isAdmin:e,isOwner:t})=>e||t)):void 0;return{fullInfo:{about:n,members:o,adminMembers:r,canViewMembers:!0,botCommands:i?He(i):void 0,...a&&{inviteLink:a.link}},users:t.users.map(Ke).filter(Boolean)}}(t)}async function Kt({query:e}){const t=await xt(new g.Api.contacts.Search({q:e}));if(!t)return;kn(t);const n=t.myResults.map(se),s=t.chats.concat(t.users).map((e=>Ee(e))).filter(Boolean),a=t.users.map(Ke).filter((e=>!!e&&!e.isSelf));return{localChats:s.filter((e=>n.includes(e.id))),localUsers:a.filter((e=>n.includes(e.id))),globalChats:s.filter((e=>!n.includes(e.id))),globalUsers:a.filter((e=>!n.includes(e.id)))}}async function zt({type:e,user:t}){let n;if("self"===e||"user"===e){const s=await xt(new g.Api.users.GetUsers({id:["user"===e&&t?O(t.id,t.accessHash):new g.Api.InputUserSelf]}));if(!s||!s.length)return;[n]=s}else if("support"===e){const e=await xt(new g.Api.help.GetSupport);if(!e||!e.user)return;n=e.user}const s=Ee(n,"support"===e);if(s)return qt({"@type":"updateChat",id:s.id,chat:s}),{chatId:s.id}}async function Wt({chat:e,serverTimeOffset:t,lastLocalMessage:n,noLastMessage:s}){const{id:a,accessHash:i}=e,o=await xt(new g.Api.messages.GetPeerDialogs({peers:[new g.Api.InputDialogPeer({peer:N(a,i)})]}));if(!o)return;const r=o.dialogs[0];if(!(r&&r instanceof g.Api.Dialog))return;const c=Mn(o)[De(r.peer)];if(!c)return;kn(o);const d=ue(o.messages[0]),l=n&&(!d||n.date>d.date)?n:d;qt({"@type":"updateChat",id:a,chat:{...Me(r,c,t),...!s&&{lastMessage:l}}})}function jt({chat:e,text:t,entities:n,replyToMsgId:s}){return xt(new g.Api.messages.SaveDraft({peer:N(e.id,e.accessHash),message:t,...n&&{entities:n.map(z)},replyToMsgId:s}))}function $t(e){return xt(new g.Api.messages.SaveDraft({peer:N(e.id,e.accessHash),message:""}))}async function Jt({chat:e,isMuted:t,serverTimeOffset:n}){await xt(new g.Api.account.UpdateNotifySettings({peer:new g.Api.InputNotifyPeer({peer:N(e.id,e.accessHash)}),settings:new g.Api.InputPeerNotifySettings({muteUntil:t?Lt:0})})),qt({"@type":"updateNotifyExceptions",chatId:e.id,isMuted:t}),Wt({chat:e,serverTimeOffset:n,noLastMessage:!0})}async function Qt({title:e,about:t,users:n}){const s=await xt(new g.Api.channels.CreateChannel({broadcast:!0,title:e,about:t}),!0);if(!(s instanceof g.Api.Updates))return;const a=s.chats[0];if(!(a&&a instanceof g.Api.Channel))return;const i=Ee(a);return await xt(new g.Api.channels.InviteToChannel({channel:O(i.id,i.accessHash),users:n.map((({id:e,accessHash:t})=>O(e,t)))})),i}function Xt({channelId:e,accessHash:t}){return xt(new g.Api.channels.JoinChannel({channel:O(e,t)}),!0)}function Zt({chat:e,user:t}){if("chatTypeBasicGroup"===e.type)return xt(new g.Api.messages.DeleteChatUser({chatId:O(e.id,e.accessHash),userId:O(t.id,t.accessHash)}),!0)}function Yt({chatId:e}){return xt(new g.Api.messages.DeleteChat({chatId:O(e)}),!0)}function en({channelId:e,accessHash:t}){return xt(new g.Api.channels.LeaveChannel({channel:O(e,t)}),!0)}function tn({channelId:e,accessHash:t}){return xt(new g.Api.channels.DeleteChannel({channel:O(e,t)}),!0)}async function nn({title:e,users:t}){const n=await xt(new g.Api.messages.CreateChat({title:e,users:t.map((({id:e,accessHash:t})=>O(e,t)))}),!0,!0);if(!(n instanceof g.Api.Updates))return;const s=n.chats[0];return s&&s instanceof g.Api.Chat?Ee(s):void 0}async function sn({chatId:e,accessHash:t,photo:n}){const s=await Nt(n),a=O(e,t);return xt(a instanceof g.Api.InputChannel?new g.Api.channels.EditPhoto({channel:a,photo:new g.Api.InputChatUploadedPhoto({file:s})}):new g.Api.messages.EditChatPhoto({chatId:a,photo:new g.Api.InputChatUploadedPhoto({file:s})}),!0)}async function an({chat:e,shouldBePinned:t}){const{id:n,accessHash:s}=e;await xt(new g.Api.messages.ToggleDialogPin({peer:new g.Api.InputDialogPeer({peer:N(n,s)}),pinned:t||void 0}))&&qt({"@type":"updateChatPinned",id:e.id,isPinned:t})}function on({chat:e,folderId:t}){const{id:n,accessHash:s}=e;return xt(new g.Api.folders.EditPeerFolders({folderPeers:[new g.Api.InputFolderPeer({peer:N(n,s),folderId:t})]}),!0)}async function rn(){const e=await xt(new g.Api.messages.GetDialogFilters);if(e)return{byId:p(e.map(Le),"id"),orderedIds:e.map((({id:e})=>e))}}async function cn(){const e=await xt(new g.Api.messages.GetSuggestedDialogFilters);if(e)return e.map(qe)}async function dn({id:e,folderUpdate:t}){const n=function(e){const{emoticon:t,contacts:n,nonContacts:s,groups:a,channels:i,bots:o,excludeArchived:r,excludeMuted:c,excludeRead:d,pinnedChatIds:l,includedChatIds:u,excludedChatIds:p}=e,f=l?l.map(F).filter(Boolean):[],h=u?u.map(F).filter(Boolean):[],m=p?p.map(F).filter(Boolean):[];return new g.Api.DialogFilter({id:e.id,title:e.title,emoticon:t||void 0,contacts:n||void 0,nonContacts:s||void 0,groups:a||void 0,bots:o||void 0,excludeArchived:r||void 0,excludeMuted:c||void 0,excludeRead:d||void 0,broadcasts:i||void 0,pinnedPeers:f,includePeers:h,excludePeers:m})}(t);await xt(new g.Api.messages.UpdateDialogFilter({id:e,filter:n}))&&qt({"@type":"updateChatFolder",id:e,folder:t})}async function ln(e){const t=await xt(new g.Api.messages.UpdateDialogFilter({id:e,filter:void 0})),n=await cn();t&&qt({"@type":"updateChatFolder",id:e,folder:void 0}),n&&qt({"@type":"updateRecommendedChatFolders",folders:n})}async function un({chat:e,hasUnreadMark:t}){const{id:n,accessHash:s}=e;await xt(new g.Api.messages.MarkDialogUnread({peer:new g.Api.InputDialogPeer({peer:N(n,s)}),unread:t||void 0}))&&qt({"@type":"updateChat",id:e.id,chat:{hasUnreadMark:t}})}async function gn(e){const t=await xt(new g.Api.contacts.ResolveUsername({username:e}));if(!t)return;const{users:n,chats:s}=t,a=s.length?Ee(s[0]):Ee(n[0]);return a?(kn(t),a):void 0}function pn({chat:e,isEnabled:t}){const{id:n,accessHash:s}=e,a=O(n,s);return xt(new g.Api.channels.TogglePreHistoryHidden({channel:a,enabled:t}),!0)}function fn({chat:e,bannedRights:t}){const{id:n,accessHash:s}=e,a=N(n,s);return xt(new g.Api.messages.EditChatDefaultBannedRights({peer:a,bannedRights:$(t)}),!0)}function hn({chat:e,user:t,bannedRights:n,untilDate:s}){const a=O(e.id,e.accessHash),i=N(t.id,t.accessHash);return xt(new g.Api.channels.EditBanned({channel:a,participant:i,bannedRights:$(n,s)}),!0)}function mn({chat:e,user:t,adminRights:n,customTitle:s=""}){const a=O(e.id,e.accessHash),i=O(t.id,t.accessHash);return xt(new g.Api.channels.EditAdmin({channel:a,userId:i,adminRights:J(n),rank:s}),!0)}async function _n(e,t){const n=O(e.id,e.accessHash);await xt(n instanceof g.Api.InputChannel?new g.Api.channels.EditTitle({channel:n,title:t}):new g.Api.messages.EditChatTitle({chatId:n,title:t}),!0)}async function yn(e,t){await xt(new g.Api.messages.EditChatAbout({peer:N(e.id,e.accessHash),about:t}))&&qt({"@type":"updateChatFullInfo",id:e.id,fullInfo:{about:t}})}function bn({chat:e,isEnabled:t}){const{id:n,accessHash:s}=e,a=O(n,s);return xt(new g.Api.channels.ToggleSignatures({channel:a,enabled:t}),!0)}async function wn(e,t,n="recent",s){let a;switch(n){case"kicked":a=new g.Api.ChannelParticipantsKicked({q:""});break;case"admin":a=new g.Api.ChannelParticipantsAdmins;break;default:a=new g.Api.ChannelParticipantsRecent}const i=await xt(new g.Api.channels.GetParticipants({channel:O(e,t),filter:a,offset:s,limit:200}));if(i&&!(i instanceof g.Api.channels.ChannelParticipantsNotModified))return kn(i),{members:Fe(i),users:i.users.map(Ke).filter(Boolean)}}async function Cn(){const e=await xt(new g.Api.channels.GetGroupsForDiscussion);if(e)return kn(e),e.chats.map((e=>Ee(e)))}function In({channel:e,chat:t}){return xt(new g.Api.channels.SetDiscussionGroup({broadcast:N(e.id,e.accessHash),group:t?N(t.id,t.accessHash):new g.Api.InputChannelEmpty}))}async function vn(e){const t=await xt(new g.Api.messages.MigrateChat({chatId:O(e.id)}),!0);if(t&&t instanceof g.Api.Updates)return kn(t),Ee(t.chats[1])}async function Pn(e){const t=await xt(new g.Api.messages.CheckChatInvite({hash:e}));if(!t)return;let n;return t instanceof g.Api.ChatInvite?qt({"@type":"showInvite",data:{title:t.title,hash:e,participantsCount:t.participantsCount,isChannel:t.channel}}):(n=Ee(t.chat),n&&qt({"@type":"updateChat",id:n.id,chat:n})),n?{chatId:n.id}:void 0}function Sn(e,t){return"chatTypeChannel"===e.type||"chatTypeSuperGroup"===e.type?xt(new g.Api.channels.InviteToChannel({channel:O(e.id,e.accessHash),users:t.map((e=>O(e.id,e.accessHash)))}),!0):Promise.all(t.map((t=>xt(new g.Api.messages.AddChatUser({chatId:O(e.id),userId:O(t.id,t.accessHash)}),!0))))}function An(e,t){return"chatTypeChannel"===e.type||"chatTypeSuperGroup"===e.type?hn({chat:e,user:t,bannedRights:{viewMessages:!0,sendMessages:!0,sendMedia:!0,sendStickers:!0,sendGifs:!0,sendGames:!0,sendInline:!0,embedLinks:!0,sendPolls:!0,changeInfo:!0,inviteUsers:!0,pinMessages:!0},untilDate:Lt}):xt(new g.Api.messages.DeleteChatUser({chatId:O(e.id),userId:O(t.id,t.accessHash)}),!0)}function Mn(e){const t={};return e.chats.forEach((e=>{t[`chat${e.id}`]=e})),e.users.forEach((e=>{t[`user${e.id}`]=e})),t}function kn(e){"users"in e&&e.users.forEach((e=>{e instanceof g.Api.User&&(v.users[ne(e.id,"user")]=e)})),"chats"in e&&e.chats.forEach(re),"messages"in e&&e.messages.forEach((e=>{e instanceof g.Api.Message&&W(e)&&ie(e)}))}async function Rn({hash:e}){const t=await xt(new g.Api.messages.ImportChatInvite({hash:e}),!0);if(t instanceof g.Api.Updates&&t.chats.length)return Ee(t.chats[0])}function Un(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}"undefined"==typeof File&&(self.File=class extends Blob{constructor(e,t,n){if(n){const{type:t,...s}=n;super(e,{type:t}),Un(this,"name",void 0),Object.assign(this,s)}else super(e),Un(this,"name",void 0);this.name=t}});var En=n(8764).Buffer;let Tn;async function Dn({chat:e,threadId:t,...n}){const s=-1===t?g.Api.messages.GetHistory:g.Api.messages.GetReplies;let a;try{a=await xt(new s({peer:N(e.id,e.accessHash),...-1!==t&&{msgId:t},...n}),void 0,!0)}catch(t){"CHANNEL_PRIVATE"===t.message&&Tn({"@type":"updateChat",id:e.id,chat:{isRestricted:!0}})}if(!a||a instanceof g.Api.messages.MessagesNotModified||!a.messages)return;is(a);const i=a.messages.map(ue).filter(Boolean),o=a.users.map(Ke).filter(Boolean),r=a.chats.map((e=>Ee(e))).filter(Boolean),c=i.map((({threadInfo:e})=>e)).filter(Boolean);return{messages:i,users:o,chats:r,threadInfos:c}}async function Bn({chat:e,messageId:t}){const n="channel"===x(e.id);let s;try{s=await xt(n?new g.Api.channels.GetMessages({channel:O(e.id,e.accessHash),id:[new g.Api.InputMessageID({id:t})]}):new g.Api.messages.GetMessages({id:[new g.Api.InputMessageID({id:t})]}),void 0,!0)}catch(e){const{message:t}=e;"CHANNEL_PRIVATE"!==t&&Tn({"@type":"error",error:{message:t,isSlowMode:!1,hasErrorKey:!0}})}if(!s||s instanceof g.Api.messages.MessagesNotModified)return;const a=s.messages[0];if(!a)return;if(a instanceof g.Api.MessageEmpty)return"MESSAGE_DELETED";const i=a&&ue(a);return i?(a instanceof g.Api.Message&&ie(a),{message:i,users:s.users.map(Ke).filter(Boolean)}):void 0}let xn=Promise.resolve();function Vn({chat:e,text:t,entities:n,replyingTo:s,attachment:a,sticker:i,gif:o,poll:r,isSilent:c,scheduledAt:d,groupedId:l,noWebPage:u,serverTimeOffset:p},f){const h=function(e,t,n,s,a,i,o,r,c,d,l=0){const u=le++,g=a&&function(e){const{filename:t,blobUrl:n,previewBlobUrl:s,mimeType:a,size:i}=e;if(e.quick){const{width:o,height:r,duration:c}=e.quick;return a.startsWith("image/")?{photo:{id:ce,sizes:[],thumbnail:{width:o,height:r,dataUri:""},blobUrl:n}}:{video:{id:ce,mimeType:a,duration:c||0,fileName:t,width:o,height:r,blobUrl:n,...s&&{thumbnail:{width:o,height:r,dataUri:s}},size:i}}}if(e.voice){const{duration:t,waveform:n}=e.voice,{data:s}=k(n,63);return{voice:{duration:t,waveform:s}}}return a.startsWith("audio/")?{audio:{mimeType:a,fileName:t,size:i,duration:200}}:{document:{mimeType:a,fileName:t,size:i,...s&&{previewBlobUrl:s}}}}(a),p="chatTypeChannel"===e.type;return{id:u,chatId:e.id,content:{...t&&{text:{text:t,entities:n}},...g,...i&&{sticker:i},...o&&{video:o},...r&&Ie(r,u)},date:d||Math.round(Date.now()/1e3)+l,isOutgoing:!p,senderId:de,...s&&{replyToMessageId:s},...c&&{groupedId:c,...g&&(g.photo||g.video)&&{isInAlbum:!0}},...d&&{isScheduled:!0}}}(e,t,n,s,a,i,o,r,l,d,p);Tn({"@type":h.isScheduled?"newScheduledMessage":"newMessage",id:h.id,chatId:e.id,message:h}),setTimeout((()=>{Tn({"@type":h.isScheduled?"updateScheduledMessage":"updateMessage",id:h.id,chatId:e.id,message:{sendingState:"messageSendingStatePending"}})}),1e3);const m=G();if(v.localMessages[String(m)]=h,l)return function({chat:e,text:t,entities:n,replyingTo:s,attachment:a,groupedId:i,isSilent:o,scheduledAt:r},c,d,l){let u=-1;Nn[i]||(Nn[i]={counter:0,singleMediaByIndex:{}}),u=Nn[i].counter++;const p=xn;return xn=(async()=>{let f;try{f=await Ln(d,a,l)}catch(e){return Nn[i].counter--,void await p}const h=await async function(e,t){const n=await xt(new g.Api.messages.UploadMedia({peer:e,media:t}));if(n instanceof g.Api.MessageMediaPhoto&&n.photo&&n.photo instanceof g.Api.Photo){const{photo:{id:e,accessHash:t,fileReference:s}}=n;return new g.Api.InputMediaPhoto({id:new g.Api.InputPhoto({id:e,accessHash:t,fileReference:s})})}if(n instanceof g.Api.MessageMediaDocument&&n.document&&n.document instanceof g.Api.Document){const{document:{id:e,accessHash:t,fileReference:s}}=n;return new g.Api.InputMediaDocument({id:new g.Api.InputDocument({id:e,accessHash:t,fileReference:s})})}}(N(e.id,e.accessHash),f);if(await p,!h)return void Nn[i].counter--;if(Nn[i].singleMediaByIndex[u]=new g.Api.InputSingleMedia({media:h,randomId:c,message:t||"",entities:n?n.map(z):void 0}),Object.keys(Nn[i].singleMediaByIndex).length{let l;if(a)try{l=await Ln(h,a,f)}catch(e){return void await _}else i?l=H(i):o?l=H(o):r&&(l=function(e,t){const{summary:n,quiz:s}=e,a=new g.Api.Poll({id:t,publicVoters:n.isPublic,question:n.question,answers:n.answers.map((({text:e,option:t})=>new g.Api.PollAnswer({text:e,option:B.from(t)}))),quiz:n.quiz,multipleChoice:n.multipleChoice});if(!s)return new g.Api.InputMediaPoll({poll:a});const i=s.correctAnswers.map((e=>B.from(e))),{solution:o}=s,r=s.solutionEntities?s.solutionEntities.map(z):[];return new g.Api.InputMediaPoll({poll:a,correctAnswers:i,...o&&{solution:o,solutionEntities:r}})}(r,m));await _;const p=l?g.Api.messages.SendMedia:g.Api.messages.SendMessage;await xt(new p({clearDraft:!0,message:t||"",entities:n?n.map(z):void 0,peer:N(e.id,e.accessHash),randomId:m,...c&&{silent:c},...d&&{scheduleDate:d},...s&&{replyToMsgId:s},...l&&{media:l},...u&&{noWebpage:u}}),!0)})(),xn}const Nn={};async function Fn({chat:e,message:t,text:n,entities:s,noWebPage:a,serverTimeOffset:i}){const o=1e3*t.date>Date.now()+1e3*i,r={content:{...t.content,...n&&{text:{text:n,entities:s}}}};Tn({"@type":o?"updateScheduledMessage":"updateMessage",id:t.id,chatId:e.id,message:r}),v.localMessages[t.id]={...t,...r};const c=s&&s.map(z);await xt(new g.Api.messages.EditMessage({message:n||"",entities:c,peer:N(e.id,e.accessHash),id:t.id,...o&&{scheduleDate:t.date},...a&&{noWebpage:a}}),!0)}async function On({chat:e,message:t,scheduledAt:n}){await xt(new g.Api.messages.EditMessage({peer:N(e.id,e.accessHash),id:t.id,scheduleDate:n}),!0)}async function Ln(e,t,n){const{filename:s,blobUrl:a,mimeType:i,quick:o,voice:d}=t,l=await async function(e,t){return function(e,t){return new File([e],t,{lastModified:Date.now(),type:e.type})}(await async function(e){return(await fetch(e)).blob()}(e),t)}(a,s),u=t=>{n.isCanceled?u.isCanceled=!0:n(t,e.id)},p=await Nt(l,u),f=[new g.Api.DocumentAttributeFilename({fileName:s})];if(o){if(r.has(i))return new g.Api.InputMediaUploadedPhoto({file:p});if(c.has(i)){const{width:e,height:t,duration:n}=o;void 0!==n&&f.push(new g.Api.DocumentAttributeVideo({duration:n,w:e,h:t,supportsStreaming:!0}))}}if(d){const{duration:e,waveform:t}=d,{data:n}=k(t,63);f.push(new g.Api.DocumentAttributeAudio({voice:!0,duration:e,waveform:En.from(n)}))}return new g.Api.InputMediaUploadedDocument({file:p,mimeType:i,attributes:f})}async function qn({chat:e,messageId:t,isUnpin:n,isOneSide:s,isSilent:a}){await xt(new g.Api.messages.UpdatePinnedMessage({peer:N(e.id,e.accessHash),id:t,...n&&{unpin:!0},...s&&{pmOneside:!0},...a&&{silent:!0}}),!0)}async function Hn({chat:e}){await xt(new g.Api.messages.UnpinAllMessages({peer:N(e.id,e.accessHash)}),!0)}async function Gn({chat:e,messageIds:t,shouldDeleteForAll:n}){const s="channel"===x(e.id);await xt(s?new g.Api.channels.DeleteMessages({channel:O(e.id,e.accessHash),id:t}):new g.Api.messages.DeleteMessages({id:t,...n&&{revoke:!0}}))&&Tn({"@type":"deleteMessages",ids:t,...s&&{chatId:e.id}})}async function Kn({chat:e,messageIds:t}){await xt(new g.Api.messages.DeleteScheduledMessages({peer:N(e.id,e.accessHash),id:t}))&&Tn({"@type":"deleteScheduledMessages",ids:t,chatId:e.id})}async function zn({chat:e,shouldDeleteForAll:t,maxId:n}){const s="channel"===x(e.id);await xt(s?new g.Api.channels.DeleteHistory({channel:O(e.id,e.accessHash),maxId:n}):new g.Api.messages.DeleteHistory({peer:N(e.id,e.accessHash),...t&&{revoke:!0},...!t&&{just_clear:!0},maxId:n}))&&Tn({"@type":"deleteHistory",chatId:e.id})}async function Wn({peer:e,messageIds:t,reason:n,description:s}){return await xt(new g.Api.messages.Report({peer:N(e.id,e.accessHash),id:t,reason:Z(n),message:s}))}async function jn({chat:e,threadId:t,maxId:n,serverTimeOffset:s}){const a="channel"===x(e.id);a&&-1===t?await xt(new g.Api.channels.ReadHistory({channel:O(e.id,e.accessHash),maxId:n})):a?await xt(new g.Api.messages.ReadDiscussion({peer:N(e.id,e.accessHash),msgId:t,readMaxId:n})):await xt(new g.Api.messages.ReadHistory({peer:N(e.id,e.accessHash),maxId:n})),-1===t?Wt({chat:e,serverTimeOffset:s,noLastMessage:!0}):Jn({chat:e,threadId:t})}async function $n({chat:e,messageIds:t}){const n="channel"===x(e.id);await xt(n?new g.Api.channels.ReadMessageContents({channel:O(e.id,e.accessHash),id:t}):new g.Api.messages.ReadMessageContents({id:t})),Tn({...n?{"@type":"updateChannelMessages",channelId:e.id}:{"@type":"updateCommonBoxMessages"},ids:t,messageUpdate:{hasUnreadMention:!1,isMediaUnread:!1}})}async function Jn({chat:e,threadId:t}){const[n,s]=await Promise.all([xt(new g.Api.messages.GetDiscussionMessage({peer:N(e.id,e.accessHash),msgId:t})),xt(new g.Api.messages.GetReplies({peer:N(e.id,e.accessHash),msgId:t,offsetId:1,addOffset:-1,limit:1}))]);if(!n||!n.messages.length)return;const a=ae(n.messages[0]);return a?(Tn({"@type":"updateThreadInfo",chatId:a,threadId:t,threadInfo:{threadId:t,topMessageId:n.messages[n.messages.length-1].id,lastReadInboxMessageId:n.readInboxMaxId,messagesCount:s instanceof g.Api.messages.ChannelMessages?s.count:void 0},firstMessageId:s&&"messages"in s&&s.messages.length?s.messages[0].id:void 0}),n.chats.map((e=>Ee(e))).filter(Boolean).forEach((e=>{Tn({"@type":"updateChat",id:e.id,chat:e,noTopChatsRequest:!0})})),{discussionChatId:a}):void 0}async function Qn({chatOrUser:e,type:t,query:n,topMessageId:s,minDate:a,maxDate:i,...o}){let r;switch(t){case"media":r=new g.Api.InputMessagesFilterPhotoVideo;break;case"documents":r=new g.Api.InputMessagesFilterDocument;break;case"links":r=new g.Api.InputMessagesFilterUrl;break;case"audio":r=new g.Api.InputMessagesFilterMusic;break;case"voice":r=new g.Api.InputMessagesFilterRoundVoice;break;case"profilePhoto":r=new g.Api.InputMessagesFilterChatPhotos;break;case"text":default:r=new g.Api.InputMessagesFilterEmpty}const c=await xt(new g.Api.messages.Search({peer:N(e.id,e.accessHash),filter:r,q:n||"",topMsgId:s,minDate:a,maxDate:i,...o}));if(!c||c instanceof g.Api.messages.MessagesNotModified||!c.messages)return;is(c);const d=c.messages.map(ue).filter(Boolean),l=c.users.map(Ke).filter(Boolean);let u,p=d.length;return(c instanceof g.Api.messages.MessagesSlice||c instanceof g.Api.messages.ChannelMessages)&&(p=c.count,d.length&&(u=d[d.length-1].id)),{messages:d,users:l,totalCount:p,nextOffsetId:u}}async function Xn({query:e,offsetRate:t=0,limit:n,type:s="text",minDate:a,maxDate:i}){let o;switch(s){case"media":o=new g.Api.InputMessagesFilterPhotoVideo;break;case"documents":o=new g.Api.InputMessagesFilterDocument;break;case"links":o=new g.Api.InputMessagesFilterUrl;break;case"audio":o=new g.Api.InputMessagesFilterMusic;break;case"voice":o=new g.Api.InputMessagesFilterRoundVoice;break;case"text":default:if(!(e||i&&a))return;o=new g.Api.InputMessagesFilterEmpty}const r=await xt(new g.Api.messages.SearchGlobal({q:e,offsetRate:t,offsetPeer:new g.Api.InputPeerEmpty,limit:n,filter:o,folderId:0,minDate:a,maxDate:i}));if(!r||r instanceof g.Api.messages.MessagesNotModified||!r.messages)return;is({chats:r.chats,users:r.users,messages:r.messages});const c=r.chats.map((e=>Ee(e))).filter(Boolean),d=r.users.map(Ke).filter(Boolean),l=r.messages.map(ue).filter(Boolean);let u,p=l.length;return(r instanceof g.Api.messages.MessagesSlice||r instanceof g.Api.messages.ChannelMessages)&&(p=r.count,l.length&&(u=l[l.length-1].id)),{messages:l,users:d,chats:c,totalCount:p,nextRate:"nextRate"in r&&r.nextRate?r.nextRate:u}}async function Zn({message:e}){const t=await xt(new g.Api.messages.GetWebPagePreview({message:e}));return t&&we(t)}async function Yn({chat:e,messageId:t,options:n}){const{id:s,accessHash:a}=e;await xt(new g.Api.messages.SendVote({peer:N(s,a),msgId:t,options:n.map((e=>En.from(e)))}),!0)}async function es({chat:e,messageId:t,option:n,offset:s,limit:a,shouldResetVoters:i}){const{id:o,accessHash:r}=e,c=await xt(new g.Api.messages.GetPollVotes({peer:N(o,r),id:t,...n&&{option:En.from(n)},...s&&{offset:s},...a&&{limit:a}}));if(!c)return;is({chats:[],users:c.users,messages:[]});const d=c.users.map(Ke).filter(Boolean),l=c.votes.map((e=>({userId:e.userId,date:e.date})));return{count:c.count,votes:l,users:d,nextOffset:c.nextOffset,shouldResetVoters:i}}async function ts({fromChat:e,toChat:t,messages:n,serverTimeOffset:s,isSilent:a,scheduledAt:i}){const o=n.map((({id:e})=>e)),r=n.map(G);n.forEach(((e,n)=>{const a=function(e,t,n,s){const a=le++,{content:i,chatId:o,id:r,senderId:c,groupedId:d,isInAlbum:l}=t,u=i.audio,g=e.id===de&&(o!==e.id||t.forwardInfo)&&!u;return{id:a,chatId:e.id,content:i,date:s||Math.round(Date.now()/1e3)+n,isOutgoing:!g&&"chatTypeChannel"!==e.type,senderId:de,sendingState:"messageSendingStatePending",groupedId:d,isInAlbum:l,...c!==de&&!u&&{forwardInfo:{isChannelPost:!1,fromChatId:o,fromMessageId:r,senderUserId:c}},...s&&{isScheduled:!0}}}(t,e,s,i);v.localMessages[String(r[n])]=a,Tn({"@type":a.isScheduled?"newScheduledMessage":"newMessage",id:a.id,chatId:t.id,message:a})})),await xt(new g.Api.messages.ForwardMessages({fromPeer:N(e.id,e.accessHash),toPeer:N(t.id,t.accessHash),randomId:r,id:o,...a&&{sil2ent:a},...i&&{scheduleDate:i}}),!0)}async function ns({chat:e,timestamp:t}){const n=await xt(new g.Api.messages.GetHistory({peer:N(e.id,e.accessHash),offsetDate:t,addOffset:-1,limit:1}));if(n&&!(n instanceof g.Api.messages.MessagesNotModified)&&n.messages&&n.messages.length)return n.messages[0].id}async function ss({chat:e}){const{id:t,accessHash:n}=e,s=await xt(new g.Api.messages.GetScheduledHistory({peer:N(t,n)}));if(s&&!(s instanceof g.Api.messages.MessagesNotModified)&&s.messages)return is(s),{messages:s.messages.map(ue).filter(Boolean)}}async function as({chat:e,ids:t}){const{id:n,accessHash:s}=e;await xt(new g.Api.messages.SendScheduledMessages({peer:N(n,s),id:t}),!0)}function is(e){e.users.forEach((e=>{e instanceof g.Api.User&&(v.users[ne(e.id,"user")]=e)})),e.chats.forEach((e=>{(e instanceof g.Api.Chat||e instanceof g.Api.Channel)&&(v.chats[ne(e.id,e instanceof g.Api.Chat?"chat":"channel")]=e)})),e.messages.forEach((e=>{(e instanceof g.Api.Message&&W(e)||e instanceof g.Api.MessageService&&function(e){return"photo"in e.action&&e.action.photo instanceof g.Api.Photo}(e))&&ie(e)}))}async function os({chat:e}){const t=await xt(new g.Api.messages.Search({peer:N(e.id,e.accessHash),filter:new g.Api.InputMessagesFilterPinned,q:"",limit:50}));if(t&&!(t instanceof g.Api.messages.MessagesNotModified)&&t.messages)return is(t),{messages:t.messages.map(ue).filter(Boolean),users:t.users.map(Ke).filter(Boolean),chats:t.chats.map((e=>Ee(e))).filter(Boolean)}}let rs,cs,ds,ls;async function us({id:e,accessHash:t}){const n=O(e,t);if(!(n instanceof g.Api.InputUser))return;const s=await xt(new g.Api.users.GetFullUser({id:n}));if(!s)return;const a=Ge(s);rs({"@type":"updateUser",id:e,user:{fullInfo:a.fullInfo}})}async function gs(e,t,n){const s=await xt(new g.Api.messages.GetCommonChats({userId:O(e,t),maxId:n?Y(n,x(n)):void 0,limit:100}));if(!s)return;Cs(s);const a=[],i=[];return s.chats.forEach((e=>{const t=Ee(e);t&&(i.push(t),a.push(t.id))})),{chats:i,chatIds:a,isFullyLoaded:a.length<100}}async function ps(){const e=await xt(new g.Api.help.GetNearestDc);return null==e?void 0:e.country}async function fs(){const e=await xt(new g.Api.contacts.GetTopPeers({correspondents:!0}));if(!(e instanceof g.Api.contacts.TopPeers))return;const t=e.users.map(Ke).filter((e=>!!e&&!e.isSelf));return{ids:t.map((({id:e})=>e)),users:t}}async function hs(){const e=await xt(new g.Api.contacts.GetContacts({hash:U()("0")}));if(e&&!(e instanceof g.Api.contacts.ContactsNotModified))return e.users.forEach((e=>{e instanceof g.Api.User&&(v.users[ne(e.id,"user")]=e)})),{users:e.users.map(Ke).filter(Boolean),chats:e.users.map((e=>Ee(e))).filter(Boolean)}}async function ms({users:e}){const t=await xt(new g.Api.users.GetUsers({id:e.map((({id:e,accessHash:t})=>N(e,t)))}));if(t&&t.length)return t.forEach((e=>{e instanceof g.Api.User&&(v.users[ne(e.id,"user")]=e)})),t.map(Ke).filter(Boolean)}function _s({phone:e,firstName:t,lastName:n}){return xt(new g.Api.contacts.ImportContacts({contacts:[j({phone:e||"",firstName:t||"",lastName:n||""})]}))}function ys({id:e,accessHash:t,phoneNumber:n="",firstName:s="",lastName:a=""}){return xt(new g.Api.contacts.AddContact({id:O(e,t),firstName:s,lastName:a,phone:n}),!0)}async function bs({id:e,accessHash:t}){const n=O(e,t);n instanceof g.Api.InputUser&&await xt(new g.Api.contacts.DeleteContacts({id:[n]}))&&rs({"@type":"deleteUser",id:e})}async function ws(e,t){if(e){const{id:t,accessHash:n}=e,s=await xt(new g.Api.photos.GetUserPhotos({userId:O(t,n),limit:40,offset:0,maxId:U()("0")}));if(!s)return;return Cs(s),{photos:s.photos.filter((e=>e instanceof g.Api.Photo)).map(C)}}const n=await Qn({chatOrUser:t,type:"profilePhoto",limit:40});if(!n)return;const{messages:s,users:a}=n;return{photos:s.map((e=>e.content.action.photo)).filter(Boolean),users:a}}function Cs(e){"chats"in e&&e.chats.forEach(re),"photos"in e&&e.photos.forEach(oe)}async function Is({hash:e="0"}){const t=await xt(new g.Api.messages.GetAllStickers({hash:U()(e)}));if(t&&!(t instanceof g.Api.messages.AllStickersNotModified))return t.sets.forEach((e=>{var t;null!==(t=e.thumbs)&&void 0!==t&&t.length&&(v.stickerSets[String(e.id)]=e)})),{hash:String(t.hash),sets:t.sets.map(A)}}async function vs({hash:e="0"}){const t=await xt(new g.Api.messages.GetRecentStickers({hash:U()(e)}));if(t&&!(t instanceof g.Api.messages.RecentStickersNotModified))return{hash:String(t.hash),stickers:Vs(t.stickers.slice(0,20))}}async function Ps({hash:e="0"}){const t=await xt(new g.Api.messages.GetFavedStickers({hash:U()(e)}));if(t&&!(t instanceof g.Api.messages.FavedStickersNotModified))return{hash:String(t.hash),stickers:Vs(t.stickers)}}async function Ss({hash:e="0"}){const t=await xt(new g.Api.messages.GetFeaturedStickers({hash:U()(e)}));if(t&&!(t instanceof g.Api.messages.FeaturedStickersNotModified))return{hash:String(t.hash),sets:t.sets.map(M)}}async function As({sticker:e,unfave:t}){const n=new g.Api.messages.FaveSticker({id:q(e),unfave:t});await xt(n)&&cs({"@type":"updateFavoriteStickers"})}async function Ms({stickerSetShortName:e,stickerSetId:t,accessHash:n}){const s=await xt(new g.Api.messages.GetStickerSet({stickerset:t?L(t,n):(a=e,new g.Api.InputStickerSetShortName({shortName:a}))}));var a,i;if(s)return{set:A(s.set),stickers:Vs(s.documents),packs:(i=s.packs,i.reduce(((e,{emoticon:t,documents:n})=>(e[t]=n.map((e=>S(v.documents[String(e)]))).filter(Boolean),e)),{}))}}async function ks(){const e=await xt(new g.Api.messages.GetStickerSet({stickerset:new g.Api.InputStickerSetAnimatedEmoji}));if(e)return{set:A(e.set),stickers:Vs(e.documents)}}async function Rs({query:e,hash:t="0"}){const n=await xt(new g.Api.messages.SearchStickerSets({q:e,hash:U()(t)}));if(n&&!(n instanceof g.Api.messages.FoundStickerSetsNotModified))return{hash:String(n.hash),sets:n.sets.map(M)}}async function Us({hash:e="0"}){const t=await xt(new g.Api.messages.GetSavedGifs({hash:U()(e)}));if(t&&!(t instanceof g.Api.messages.SavedGifsNotModified))return{hash:String(t.hash),gifs:Ns(t.gifs)}}async function Es({stickerSetId:e,accessHash:t}){await xt(new g.Api.messages.InstallStickerSet({stickerset:L(e,t)}))&&cs({"@type":"updateStickerSet",id:e,stickerSet:{installedDate:Date.now()}})}async function Ts({stickerSetId:e,accessHash:t}){await xt(new g.Api.messages.UninstallStickerSet({stickerset:L(e,t)}))&&cs({"@type":"updateStickerSet",id:e,stickerSet:{installedDate:void 0}})}async function Ds({query:e,offset:t=""}){if(!ds){const e=await xt(new g.Api.help.GetConfig);if(!e)return;const t=await xt(new g.Api.contacts.ResolveUsername({username:e.gifSearchUsername}));if(!(t&&t.users[0]instanceof g.Api.User))return;ds=new g.Api.InputUser({userId:t.peer.userId,accessHash:t.users[0].accessHash})}const n=await xt(new g.Api.messages.GetInlineBotResults({bot:ds,peer:new g.Api.InputPeerEmpty,query:e,offset:t}));if(!n)return;const s=n.results.map((e=>{if(e instanceof g.Api.BotInlineMediaResult)return e.document})).filter(Boolean);return{nextOffset:n.nextOffset,gifs:Ns(s)}}async function Bs({emoji:e,hash:t="0"}){const n=await xt(new g.Api.messages.GetStickers({emoticon:e,hash:U()(t)}));if(n&&!(n instanceof g.Api.messages.StickersNotModified))return{stickers:Vs(n.stickers),hash:String(n.hash)}}async function xs({language:e,fromVersion:t}){const n=await xt(new g.Api.messages.GetEmojiKeywordsDifference({langCode:e,fromVersion:t}));if(n)return{language:n.langCode,version:n.version,keywords:n.keywords.reduce(((e,t)=>(e[t.keyword]=t.emoticons,e)),{})}}function Vs(e){return e.map((e=>{if(e instanceof g.Api.Document){const t=S(e);if(t)return v.documents[String(e.id)]=e,t}})).filter(Boolean)}function Ns(e){return e.map((e=>{if(e instanceof g.Api.Document){const t=me(e);if(t)return v.documents[String(e.id)]=e,t}})).filter(Boolean)}async function Fs({username:e}){try{return await xt(new g.Api.channels.CheckUsername({channel:new g.Api.InputChannelEmpty,username:e}),void 0,!0)}catch(e){return!1}}async function Os({chat:e,username:t}){await xt(new g.Api.channels.UpdateUsername({channel:O(e.id,e.accessHash),username:t}))&&ls({"@type":"updateChat",id:e.id,chat:{username:t}})}async function Ls({chat:e}){const t=await xt(new g.Api.messages.ExportChatInvite({peer:N(e.id,e.accessHash)}));t&&t instanceof g.Api.ChatInviteExported&&ls({"@type":"updateChatFullInfo",id:e.id,fullInfo:{inviteLink:t.link}})}const qs={EMAIL_UNCONFIRMED:"Email unconfirmed",EMAIL_HASH_EXPIRED:"Email hash expired",NEW_SALT_INVALID:"The new salt is invalid",NEW_SETTINGS_INVALID:"The new password settings are invalid",CODE_INVALID:"Invalid Code",PASSWORD_HASH_INVALID:"Invalid Password"},Hs={};let Gs;async function Ks(){const e=await xt(new g.Api.account.GetPassword);if(!e)return;const{hint:t,hasPassword:n}=e;return{hint:t,hasPassword:n}}function zs(e){return Gs({"@type":"updateTwoFaStateWaitCode",length:e}),new Promise(((e,t)=>{Hs.resolve=e,Hs.reject=t}))}async function Ws(e){try{return await Ft({isCheckPassword:!0,currentPassword:e}),!0}catch(e){return Xs(e),!1}}async function js(e){try{return await Ft({currentPassword:e}),!0}catch(e){return Xs(e),!1}}async function $s(e,t,n,s){try{return await Ft({currentPassword:e,newPassword:t,hint:n,email:s,emailCodeCallback:zs,onEmailCodeError:Xs}),!0}catch(e){return Xs(e),!1}}async function Js(e,t){try{return await Ft({currentPassword:e,newPassword:e,email:t,emailCodeCallback:zs,onEmailCodeError:Xs}),!0}catch(e){return Xs(e),!1}}function Qs(e){Hs.resolve(e)}function Xs(e){let t;if(e instanceof g.errors.FloodWaitError){const n=Math.ceil(Number(e.seconds)/60/60);t="Too many attempts. Try again in "+(n>1?`${n} hours`:"an hour")}else t=qs[e.message];t||(t="Unexpected Error"),Gs({"@type":"updateTwoFaError",message:t})}const Zs=["ar","fa","id","ko","uz"];function Ys({firstName:e,lastName:t,about:n}){return xt(new g.Api.account.UpdateProfile({firstName:e||"",lastName:t||"",about:n||""}))}function ea(e){return xt(new g.Api.account.CheckUsername({username:e}))}function ta(e){return xt(new g.Api.account.UpdateUsername({username:e}))}async function na(e){const t=await Nt(e);return xt(new g.Api.photos.UploadProfilePhoto({file:t}))}async function sa(e){const t=await Nt(e);await xt(new g.Api.photos.UploadProfilePhoto({file:t}))}async function aa(){const e=await xt(new g.Api.account.GetWallPapers({hash:U()("0")}));if(!e||e instanceof g.Api.account.WallPapersNotModified)return;const t=e.wallpapers.filter((e=>e instanceof g.Api.WallPaper&&e.document instanceof g.Api.Document&&!e.pattern&&"application/x-tgwallpattern"!==e.document.mimeType));return t.forEach((e=>{v.documents[String(e.document.id)]=e.document})),{wallpapers:t.map(je).filter(Boolean)}}async function ia(e){const t=await Nt(e),n=await xt(new g.Api.account.UploadWallPaper({file:t,mimeType:e.type,settings:new g.Api.WallPaperSettings}));if(!(n&&n instanceof g.Api.WallPaper))return;const s=je(n);return s?(v.documents[String(n.document.id)]=n.document,{wallpaper:s}):void 0}async function oa(){const e=await xt(new g.Api.contacts.GetBlocked({limit:100}));if(e)return Aa(e),{users:e.users.map(Ke).filter(Boolean),chats:e.chats.map((e=>Ee(e,void 0,!0))).filter(Boolean),blockedIds:e.blocked.map((e=>se(e.peerId))),totalCount:e instanceof g.Api.contacts.BlockedSlice?e.count:e.blocked.length}}function ra(e,t){return xt(new g.Api.contacts.Block({id:N(e,t)}))}function ca(e,t){return xt(new g.Api.contacts.Unblock({id:N(e,t)}))}async function da(){const e=await xt(new g.Api.account.GetAuthorizations);if(e)return e.authorizations.map($e)}function la(e){return xt(new g.Api.account.ResetAuthorization({hash:U()(e)}))}function ua(){return xt(new g.Api.auth.ResetAuthorizations)}async function ga({serverTimeOffset:e}){const t=await xt(new g.Api.account.GetNotifyExceptions({compareSound:!0}));if(t instanceof g.Api.Updates||t instanceof g.Api.UpdatesCombined)return Aa(t),t.updates.reduce(((t,n)=>n instanceof g.Api.UpdateNotifySettings&&n.peer instanceof g.Api.NotifyPeer?(t.push(Qe(n.notifySettings,n.peer.peer,e)),t):t),[])}async function pa({serverTimeOffset:e}){const[t,n,s,a]=await Promise.all([xt(new g.Api.account.GetContactSignUpNotification),xt(new g.Api.account.GetNotifySettings({peer:new g.Api.InputNotifyUsers})),xt(new g.Api.account.GetNotifySettings({peer:new g.Api.InputNotifyChats})),xt(new g.Api.account.GetNotifySettings({peer:new g.Api.InputNotifyBroadcasts}))]);if(!n||!s||!a)return!1;const{silent:i,muteUntil:o,showPreviews:r}=n,{silent:c,muteUntil:d,showPreviews:l}=s,{silent:u,muteUntil:p,showPreviews:f}=a;return{hasContactJoinedNotifications:!t,hasPrivateChatsNotifications:!(i||"number"==typeof o&&Se(e)xt(new g.Api.langpack.GetLangPack({langPack:e,langCode:Zs.includes(t)?`${t}-raw`:t})))))).filter(Boolean).map((e=>p(e.strings.map(_),"key")));if(n.length)return{langPack:Object.assign({},...n.reverse())}}async function ya({langPack:e,langCode:t,keys:n}){const s=await xt(new g.Api.langpack.GetStrings({langPack:e,langCode:Zs.includes(t)?`${t}-raw`:t,keys:n}));if(s)return s.map(_)}async function ba(e){const t=X(e),n=await xt(new g.Api.account.GetPrivacy({key:t}));if(n)return Aa(n),Je(n.rules)}function wa(e){const t=Rt.session.getAuthKey().getKey();return xt(new g.Api.account.RegisterDevice({tokenType:10,secret:t,appSandbox:!1,otherUids:[],token:e}))}function Ca(e){return xt(new g.Api.account.UnregisterDevice({tokenType:10,otherUids:[],token:e}))}async function Ia(e,t){const n=X(e),s=[];switch(t.allowedUsers&&s.push(new g.Api.InputPrivacyValueAllowUsers({users:t.allowedUsers.map((({id:e,accessHash:t})=>O(e,t)))})),t.allowedChats&&s.push(new g.Api.InputPrivacyValueAllowChatParticipants({chats:t.allowedChats.map((({id:e})=>O(e)))})),t.blockedUsers&&s.push(new g.Api.InputPrivacyValueDisallowUsers({users:t.blockedUsers.map((({id:e,accessHash:t})=>O(e,t)))})),t.blockedChats&&s.push(new g.Api.InputPrivacyValueDisallowChatParticipants({chats:t.blockedChats.map((({id:e})=>O(e)))})),t.visibility){case"everybody":s.push(new g.Api.InputPrivacyValueAllowAll);break;case"contacts":s.push(new g.Api.InputPrivacyValueAllowContacts);break;case"nonContacts":s.push(new g.Api.InputPrivacyValueDisallowContacts);break;case"nobody":s.push(new g.Api.InputPrivacyValueDisallowAll)}const a=await xt(new g.Api.account.SetPrivacy({key:n,rules:s}));if(a)return Aa(a),Je(a.rules)}async function va(e){await xt(new g.Api.account.UpdateStatus({offline:!e}))}async function Pa(){const e=await xt(new g.Api.account.GetContentSettings);if(e)return{isSensitiveEnabled:Boolean(e.sensitiveEnabled),canChangeSensitive:Boolean(e.sensitiveCanChange)}}function Sa(e){return xt(new g.Api.account.SetContentSettings({sensitiveEnabled:e||void 0}))}function Aa(e){e.users.forEach((e=>{e instanceof g.Api.User&&(v.users[ne(e.id,"user")]=e)})),e.chats.forEach((e=>{(e instanceof g.Api.Chat||e instanceof g.Api.Channel)&&(v.chats[ne(e.id,e instanceof g.Api.Chat?"chat":"channel")]=e)}))}async function Ma({langCode:e="en"}){const t=await xt(new g.Api.help.GetCountriesList({langCode:e}));if(t instanceof g.Api.help.CountriesList)return n=t.countries,{phoneCodes:(s=n.filter((e=>!e.hidden)).map((e=>e.countryCodes.map((t=>Xe(e,t))))),s.reduce(((e,t)=>Array.isArray(t)?e.concat(t):(e.push(t),e)),[])).sort(((e,t)=>e.name?e.name.localeCompare(t.name):e.defaultName.localeCompare(t.defaultName))),general:n.filter((e=>!e.hidden)).map((e=>Xe(e))).sort(((e,t)=>e.name?e.name.localeCompare(t.name):e.defaultName.localeCompare(t.defaultName)))};var n,s}function ka(e){return e?f(e,["url","mimeType"]):void 0}var Ra=n(8764).Buffer;function Ua({chatId:e,accessHash:t,messageId:n,data:s}){return xt(new g.Api.messages.GetBotCallbackAnswer({peer:N(e,t),msgId:n,data:Ra.from(s)}))}async function Ea(){const e=await xt(new g.Api.contacts.GetTopPeers({botsInline:!0}));if(!(e instanceof g.Api.contacts.TopPeers))return;const t=e.users.map(Ke).filter(Boolean);return{ids:t.map((({id:e})=>e)),users:t}}async function Ta({username:e}){const t=await xt(new g.Api.contacts.ResolveUsername({username:e}));if(t&&t.users[0]instanceof g.Api.User&&t.users[0].bot&&t.users[0].botInlinePlaceholder)return Va(t.users[0]),{user:Ke(t.users[0]),chat:Ee(t.users[0])}}async function Da({bot:e,chat:t,query:n,offset:s=""}){const a=await xt(new g.Api.messages.GetInlineBotResults({bot:N(e.id,e.accessHash),peer:N(t.id,t.accessHash),query:n,offset:s}));var i,o,r,c,d;if(a)return a.users.map(Va),{isGallery:Boolean(a.gallery),help:e.botPlaceholder,nextOffset:(c=e.username,d=a.nextOffset,"gif"===c&&"0"===d?"":d),switchPm:(r=a.switchPm,r?f(r,["text","startParam"]):void 0),users:a.users.map(Ke).filter(Boolean),results:(i=String(a.queryId),o=a.results,o.map((e=>{return e instanceof g.Api.BotInlineMediaResult?(e.document instanceof g.Api.Document&&(t=e.document,v.documents[String(t.id)]=t),e.photo instanceof g.Api.Photo&&(n=e.photo,v.photos[String(n.id)]=n),function(e,t){const{id:n,type:s,title:a,description:i,photo:o,document:r}=e;return{id:n,queryId:t,type:s,title:a,description:i,..."sticker"===s&&r instanceof g.Api.Document&&{sticker:S(r)},...o instanceof g.Api.Photo&&{photo:C(o)},..."gif"===s&&r instanceof g.Api.Document&&{gif:me(r)},..."video"===s&&r instanceof g.Api.Document&&{thumbnail:w(r.thumbs)}}}(e,i)):(e.thumb&&(s=e.thumb,v.webDocuments[s.url]=s),function(e,t){const{id:n,type:s,title:a,description:i,url:o,thumb:r}=e;return{id:n,queryId:t,type:s,title:a,description:i,url:o,webThumbnail:ka(r)}}(e,i));var t,n,s})))}}async function Ba({chat:e,resultId:t,queryId:n,replyingTo:s}){const a=G();await xt(new g.Api.messages.SendInlineBotResult({clearDraft:!0,randomId:a,queryId:U()(n),peer:N(e.id,e.accessHash),id:t,...s&&{replyToMsgId:s}}),!0)}async function xa({bot:e,startParam:t}){const n=G();await xt(new g.Api.messages.StartBot({bot:N(e.id,e.accessHash),peer:N(e.id,e.accessHash),randomId:n,startParam:t}),!0)}function Va(e){v.users[ne(e.id,"user")]=e}function Na(e){if(e)return Object.values(e).map((e=>({id:e.id,title:e.title,amount:e.prices.reduce(((e,t)=>e+Number(t.amount.value)),0),prices:e.prices.map((({label:e,amount:t})=>({label:e,amount:Number(t.value)})))})))}async function Fa({chat:e,messageId:t,requestInfo:n,shouldSave:s}){const a=await xt(new g.Api.payments.ValidateRequestedInfo({peer:N(e.id,e.accessHash),msgId:t,save:s||void 0,info:Q(n)}));if(!a)return;const{id:i,shippingOptions:o}=a;return i?{id:i,shippingOptions:Na(o)}:void 0}function Oa({chat:e,messageId:t,formId:n,requestedInfoId:s,shippingOptionId:a,credentials:i}){return xt(new g.Api.payments.SendPaymentForm({formId:U()(n),peer:N(e.id,e.accessHash),msgId:t,requestedInfoId:s,shippingOptionId:a,credentials:new g.Api.InputPaymentCredentials({save:i.save,data:new g.Api.DataJSON({data:JSON.stringify(i.data)})})}),!0)}async function La({chat:e,messageId:t}){const n=await xt(new g.Api.payments.GetPaymentForm({peer:N(e.id,e.accessHash),msgId:t}));if(n)return function(e){const{formId:t,canSaveCredentials:n,passwordMissing:s,providerId:a,nativeProvider:i,nativeParams:o,savedInfo:r,invoice:c}=e,{test:d,nameRequested:l,phoneRequested:u,emailRequested:g,shippingAddressRequested:p,flexible:f,phoneToProvider:h,emailToProvider:m,currency:_,prices:y}=c,b=y.map((({label:e,amount:t})=>({label:e,amount:Number(t.value)}))),w=o?JSON.parse(o.data):{};return{canSaveCredentials:n,passwordMissing:s,formId:String(t),providerId:String(a),nativeProvider:i,savedInfo:r,invoice:{test:d,nameRequested:l,phoneRequested:u,emailRequested:g,shippingAddressRequested:p,flexible:f,phoneToProvider:h,emailToProvider:m,currency:_,prices:b},nativeParams:{needCardholderName:w.need_cardholder_name,needCountry:w.need_country,needZip:w.need_zip,publishableKey:w.publishable_key}}}(n)}async function qa(e,t){const n=await xt(new g.Api.payments.GetPaymentReceipt({peer:N(e.id,e.accessHash),msgId:t}));if(n)return function(e){const{invoice:t,info:n,shipping:s,currency:a,totalAmount:i,credentialsTitle:o}=e,{shippingAddress:r,phone:c,name:d}=n||{},{prices:l}=t,u=l.map((({label:e,amount:t})=>({label:e,amount:Number(t.value)})));let g,p;return s&&(g=s.prices.map((({label:e,amount:t})=>({label:e,amount:Number(t.value)}))),p=s.title),{currency:a,prices:u,info:{shippingAddress:r,phone:c,name:d},totalAmount:Number(i.value),credentialsTitle:o,shippingPrices:g,shippingMethod:p}}(n)}let Ha;async function Ga(e,t){Ha=e,function(e){Ze=e}($a),function(e){at=e}($a),function(e){qt=e}($a),function(e){Tn=e}($a),function(e){rs=e}($a),function(e){cs=e}($a),function(e){ls=e}($a),function(e){Gs=e}($a),await async function(e,t){kt=e;const{userAgent:n,platform:s,sessionData:a,isTest:i,isMovSupported:o}=t,r=new g.sessions.CallbackSession(a,Dt);self.isMovSupported=o,Rt=new g.TelegramClient(r,"2496","8da85b0d5bfe62527e5b244c209159c3",{deviceModel:navigator.userAgent||n||"Unknown UserAgent",systemVersion:s||"Unknown platform",appVersion:"1.22.2 Z",useWSS:!0,additionalDcsDisabled:!1,testServers:i}),Rt.addEventHandler(Bt,Mt),Rt.addEventHandler(tt,Mt);try{try{await Rt.start({phoneNumber:it,phoneCode:ot,password:rt,firstAndLastNames:ct,qrCode:dt,onError:lt,initialMethod:"iOS"===s||"Android"===s?"phoneNumber":"qrCode"})}catch(e){if("Disconnect"!==e.message)return void kt({"@type":"updateConnectionState",connectionState:"connectionStateBroken"})}at(ut("authorizationStateReady")),Dt(r.getSessionData()),kt({"@type":"updateApiReady"}),Ot()}catch(e){throw e}}($a,t)}const Ka=function(e,t){let n,s=!1;return(...a)=>{n=a,s||(s=!0,e((()=>{s=!1,t(...n)})))}}((function(e,t=!1){l?t?u.push(e):l.push(e):(l=t?[]:[e],u=t?[e]:[],Promise.resolve().then((()=>{const e=l,t=u;l=void 0,u=void 0,t.forEach((e=>e())),e.forEach((e=>e()))})))}),(function(e){if(!ja||e!==Wa)return;const t=ja;ja=void 0,t.forEach(Ha)}));let za,Wa,ja;function $a(e){ja?ja.push(e):ja=[e],za&&!o.has(e["@type"])||(za=function(e,t,n=!0){let s,a,i;return(...o)=>{a=!0,i=o,s||(n&&(a=!1,e(...i)),s=self.setInterval((()=>{if(!a)return self.clearInterval(s),void(s=void 0);a=!1,e(...i)}),t))}}(Ka,i,!0),Wa=Math.random()),za(Wa)}self.onerror=e=>{console.error(e),Xa({type:"unhandledError",error:{message:e.error.message||"Uncaught exception in worker"}})},self.addEventListener("unhandledrejection",(e=>{console.error(e),Xa({type:"unhandledError",error:{message:e.reason.message||"Uncaught rejection in worker"}})}));const Ja=new Map;function Qa(e){Xa({type:"update",update:e})}function Xa(e,t){t?postMessage(e,[t]):postMessage(e)}onmessage=async e=>{const{data:t}=e;switch(t.type){case"initApi":await Ga(Qa,t.args[0]);break;case"callMethod":{const{messageId:e,name:n,args:s}=t;try{if(e){const t=(...t)=>{const n=t[t.length-1];Xa({type:"methodCallback",messageId:e,callbackArgs:t},n instanceof ArrayBuffer?n:void 0)};Ja.set(e,t),s.push(t)}const t=await function(e,...t){return a[e](...t)}(n,...s),{arrayBuffer:i}="object"==typeof t&&"arrayBuffer"in t&&t||{};e&&Xa({type:"methodResponse",messageId:e,response:t},i)}catch(t){e&&Xa({type:"methodResponse",messageId:e,error:{message:t.message}})}e&&Ja.delete(e);break}case"cancelProgress":{const e=Ja.get(t.messageId);e&&(e.isCanceled=!0);break}case"ping":Xa({type:"methodResponse",messageId:t.messageId})}}},9618:(e,t,n)=>{var s=n(8764).Buffer;const a=n(4736),i=n(6842);function o(e,t=!0,n=!1){let i=s.from(e);const o=i.length;t&&(i=i.reverse());let r=a(i.toString("hex"),16);return n&&Math.floor(r.toString("2").length/8)>=o&&(r=r.subtract(a(2).pow(a(8*o)))),r}function r(e,t=8){const n=a(e),i=[];for(let e=0;e>>1:e>>>1;t[n]=e}return t}()),s.isBuffer(e)||(e=s.from(e));let t=-1;for(let n=0;n>>8}return(-1^t)>>>0},generateRandomBytes:d,generateKeyDataFromNonce:async function(e,t){e=r(e,16),t=r(t,32);const[n,a,i]=await Promise.all([l(s.concat([t,e])),l(s.concat([e,t])),l(s.concat([t,t]))]);return{key:s.concat([n,a.slice(0,12)]),iv:s.concat([a.slice(12,20),i,t.slice(0,4)])}},sha1:l,sha256:function(e){const t=i.createHash("sha256");return t.update(e),t.digest()},bigIntMod:function(e,t){return e.remainder(t).add(t).remainder(t)},modExp:function(e,t,n){e=e.remainder(n);let s=a.one,i=e;for(;t.greater(a.zero);){const e=t.remainder(a(2));t=t.divide(a(2)),e.eq(a.one)&&(s=s.multiply(i),s=s.remainder(n)),i=i.multiply(i),i=i.remainder(n)}return s},getRandomInt:function(e,t){return e=Math.ceil(e),t=Math.floor(t),Math.floor(Math.random()*(t-e+1))+e},sleep:e=>new Promise((t=>setTimeout(t,e))),getByteArray:function(e,t=!1){const n=e.toString(2).length,s=Math.floor((n+8-1)/8);return c(a(e),s,!1,t)},toSignedLittleBuffer:r,convertToLittle:function(e){const t=s.alloc(4*e.length);for(let n=0;n{e=t})),resolve:e}}}},9674:(e,t,n)=>{var s=n(8764).Buffer;const a=n(4736),{constructors:i}=n(7404),{readBigIntFromBuffer:o,readBufferFromBigInt:r,sha256:c,bigIntMod:d,modExp:l,generateRandomBytes:u}=n(9618),g=n(6842);function p(e,t){if(!s.from([199,28,174,185,198,177,201,4,142,108,82,47,112,241,63,115,152,13,64,35,142,62,33,193,73,52,208,55,86,61,147,15,72,25,138,10,167,193,64,88,34,148,147,210,37,48,244,219,250,51,111,110,10,201,37,19,149,67,174,212,76,206,124,55,32,253,81,246,148,88,112,90,198,140,212,254,107,107,19,171,220,151,70,81,41,105,50,132,84,241,143,175,140,89,95,100,36,119,254,150,187,42,148,29,91,205,29,74,200,204,73,136,7,8,250,155,55,142,60,79,58,144,96,190,230,124,249,164,164,166,149,129,16,81,144,126,22,39,83,181,107,15,107,65,13,186,116,216,168,75,42,20,179,20,78,14,241,40,71,84,253,23,237,149,13,89,101,180,185,221,70,88,45,177,23,141,22,156,107,196,101,176,214,255,156,163,146,143,239,91,154,228,228,24,252,21,232,62,190,160,248,127,169,255,94,237,112,5,13,237,40,73,244,123,249,89,217,86,133,12,233,41,133,31,13,129,21,246,53,177,5,238,46,78,21,208,75,36,84,191,111,79,173,240,52,177,4,3,17,156,216,227,185,47,204,91]).equals(e)||![3,4,5,7].includes(t))throw new Error("Changing passwords unsupported")}function f(e){return s.concat([s.alloc(256-e.length),e])}function h(e){return r(e,256,!1)}function m(e,t){const n=t.subtract(e);return!(n.lesser(a(0))||n.bitLength()<1984||e.bitLength()<1984||Math.floor((e.bitLength()+7)/8)>256)}function _(e,t){const n=Math.min(e.length,t.length);for(let s=0;s{for(;;){const e=u(256),t=o(e,!1),n=l(a(b),t,g);if(m(n,g)){const e=h(n),i=o(await c(s.concat([e,P])),!1);if(i.greater(a(0)))return[t,e,i]}}})(),E=d(w.subtract(M),g);if(!m(E,g))throw new Error("bad gB");const T=U.multiply(C),D=k.add(T),B=l(E,D,g),[x,V,N,F,O]=await Promise.all([c(h(B)),c(I),c(v),c(n.salt1),c(n.salt2)]),L=await c(s.concat([_(V,N),F,O,R,P,x]));return new i.InputCheckPasswordSRP({srpId:e.srpId,A:s.from(R),M1:L})},computeDigest:async function(e,t){try{p(e.p,e.g)}catch(e){throw new Error("bad p/g in password")}return h(l(a(e.g),o(await y(e,t),!1),o(e.p,!1)))}}},8960:(e,t,n)=>{var s=n(8764).Buffer;const{constructors:a}=n(7404),i=s.from("ffd8ffe000104a46494600010100000100010000ffdb004300281c1e231e19282321232d2b28303c64413c37373c7b585d4964918099968f808c8aa0b4e6c3a0aadaad8a8cc8ffcbdaeef5ffffff9bc1fffffffaffe6fdfff8ffdb0043012b2d2d3c353c76414176f8a58ca5f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8ffc00011080000000003012200021101031101ffc4001f0000010501010101010100000000000000000102030405060708090a0bffc400b5100002010303020403050504040000017d01020300041105122131410613516107227114328191a1082342b1c11552d1f02433627282090a161718191a25262728292a3435363738393a434445464748494a535455565758595a636465666768696a737475767778797a838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae1e2e3e4e5e6e7e8e9eaf1f2f3f4f5f6f7f8f9faffc4001f0100030101010101010101010000000000000102030405060708090a0bffc400b51100020102040403040705040400010277000102031104052131061241510761711322328108144291a1b1c109233352f0156272d10a162434e125f11718191a262728292a35363738393a434445464748494a535455565758595a636465666768696a737475767778797a82838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae2e3e4e5e6e7e8e9eaf2f3f4f5f6f7f8f9faffda000c03010002110311003f00","hex"),o=s.from("ffd9","hex");function r(e,t){throw new Error(`Cannot cast ${e.className} to any kind of ${t}`)}e.exports={getMessageId:function(e){if(void 0!==e){if("number"==typeof e)return e;if(2030045667===e.SUBCLASS_OF_ID)return e.id;throw new Error(`Invalid message type: ${e.constructor.name}`)}},getInputPeer:function e(t,n=!0,s=!0){if(void 0===t.SUBCLASS_OF_ID){if(n&&"inputEntity"in t)return t.inputEntity;if("entity"in t)return e(t.entity);r(t,"InputPeer")}if(3374092470===t.SUBCLASS_OF_ID)return t;if(t instanceof a.User){if(t.isSelf&&n)return new a.InputPeerSelf;if(void 0===t.accessHash&&s)throw new Error("User without accessHash or min info cannot be input");return new a.InputPeerUser({userId:t.id,accessHash:t.accessHash})}if(t instanceof a.Chat||t instanceof a.ChatEmpty||t instanceof a.ChatForbidden)return new a.InputPeerChat({chatId:t.id});if(t instanceof a.Channel){if(void 0===t.accessHash&&s)throw new TypeError("Channel without accessHash or min info cannot be input");return new a.InputPeerChannel({channelId:t.id,accessHash:t.accessHash})}return t instanceof a.ChannelForbidden?new a.InputPeerChannel({channelId:t.id,accessHash:t.accessHash}):t instanceof a.InputUser?new a.InputPeerUser({userId:t.userId,accessHash:t.accessHash}):t instanceof a.InputChannel?new a.InputPeerChannel({channelId:t.channelId,accessHash:t.accessHash}):t instanceof a.UserEmpty?new a.InputPeerEmpty:t instanceof a.UserFull?e(t.user):t instanceof a.ChatFull?new a.InputPeerChat({chatId:t.id}):t instanceof a.PeerChat?new a.InputPeerChat(t.chatId):void r(t,"InputPeer")},getDisplayName:function(e){return e instanceof a.User?e.lastName&&e.firstName?`${e.firstName} ${e.lastName}`:e.firstName?e.firstName:e.lastName?e.lastName:"":e instanceof a.Chat||e instanceof a.Channel?e.title:""},getAppropriatedPartSize:function(e){if(e<=104857600)return 128;if(e<=786432e3)return 256;if(e<=2097152e3)return 512;throw new Error("File size too large")},strippedPhotoToJpg:function(e){if(e.length<3||1!==e[0])return e;const t=s.from(i);return t[164]=e[1],t[166]=e[2],s.concat([t,e.slice(3),o])},getDC:function(e,t=!1){switch(e){case 1:return{id:1,ipAddress:`zws1${t?"-1":""}.web.telegram.org`,port:443};case 2:return{id:2,ipAddress:`zws2${t?"-1":""}.web.telegram.org`,port:443};case 3:return{id:3,ipAddress:`zws3${t?"-1":""}.web.telegram.org`,port:443};case 4:return{id:4,ipAddress:`zws4${t?"-1":""}.web.telegram.org`,port:443};case 5:return{id:5,ipAddress:`zws5${t?"-1":""}.web.telegram.org`,port:443};default:throw new Error(`Cannot find the DC with the ID of ${e}`)}}}},1472:e=>{e.exports="0.0.2"},243:(e,t,n)=>{"use strict";n.r(t),n.d(t,{updateTwoFaSettings:()=>l});var s=n(7150),a=n.n(s),i=n(9618),o=n(9674),r=n(7873),c=n.n(r),d=n(8764).Buffer;async function l(e,{isCheckPassword:t,currentPassword:n,newPassword:s,hint:r="",email:l,emailCodeCallback:u,onEmailCodeError:g}){if(!s&&!n)throw new Error("Neither `currentPassword` nor `newPassword` is present");if(l&&(!u||!g))throw new Error("`email` present without `emailCodeCallback` and `onEmailCodeError`");const p=await e.invoke(new(a().account.GetPassword));p.newAlgo instanceof a().PasswordKdfAlgoUnknown||(p.newAlgo.salt1=d.concat([p.newAlgo.salt1,(0,i.generateRandomBytes)(32)])),!p.hasPassword&&n&&(n=void 0);const f=n?await(0,o.computeCheck)(p,n):new(a().InputCheckPasswordEmpty);if(t)await e.invoke(new(a().auth.CheckPassword)({password:f}));else try{await e.invoke(new(a().account.UpdatePasswordSettings)({password:f,newSettings:new(a().account.PasswordInputSettings)({newAlgo:p.newAlgo,newPasswordHash:s?await(0,o.computeDigest)(p.newAlgo,s):d.alloc(0),hint:r,email:l,newSecureSettings:void 0})}))}catch(t){if(!(t instanceof c().EmailUnconfirmedError))throw t;for(;;)try{const n=await u(t.codeLength);if(!n)throw new Error("Code is empty");await e.invoke(new(a().account.ConfirmPasswordEmail)({code:n}));break}catch(e){g(e)}}}},8742:(e,t,n)=>{var s=n(8764).Buffer;const a=n(7435),i=n(6748),{sleep:o}=n(9618),r=n(7873),c=n(3995),d=n(9618),l=n(8960),u=n(9270),{LAYER:g}=n(845),{constructors:p,requests:f}=n(7404),h=n(4046),{ConnectionTCPObfuscated:m}=n(2986),{authFlow:_,checkAuthorization:y}=n(1545),{downloadFile:b}=n(2288),{uploadFile:w}=n(4766),{updateTwoFaSettings:C}=n(243),I=131072,v=["w","y","d","x","c","m","b","a","s"];class P{constructor(e,t,n,s=P.DEFAULT_OPTIONS){if(!t||!n)throw Error('Your API ID or Hash are invalid. Please read "Requirements" on README.md');const o={...P.DEFAULT_OPTIONS,...s};if(this.apiId=t,this.apiHash=n,this._useIPV6=o.useIPV6,"string"==typeof o.baseLogger?this._log=new i:this._log=o.baseLogger,"string"!=typeof e&&e){if(!(e instanceof u))throw new Error("The given session must be str or a session instance")}else try{throw new Error("not implemented")}catch(t){e=new c}this.floodSleepLimit=o.floodSleepLimit,this._eventBuilders=[],this._phoneCodeHash={},this.session=e,this.apiId=parseInt(t,10),this.apiHash=n,this._requestRetries=o.requestRetries,this._connectionRetries=o.connectionRetries,this._retryDelay=o.retryDelay||0,o.proxy&&this._log.warn("proxies are not supported"),this._proxy=o.proxy,this._timeout=o.timeout,this._autoReconnect=o.autoReconnect,this._connection=o.connection,this._floodWaitedRequests={},this._initWith=e=>new f.InvokeWithLayer({layer:g,query:new f.InitConnection({apiId:this.apiId,deviceModel:o.deviceModel||a.type().toString()||"Unknown",systemVersion:o.systemVersion||a.release().toString()||"1.0",appVersion:o.appVersion||"1.0",langCode:o.langCode,langPack:"",systemLangCode:o.systemLangCode,query:e,proxy:void 0})}),this._args=o,this._config=void 0,this.phoneCodeHashes=[],this._exportedSenderPromises={},this._exportedSenderReleaseTimeouts={},this._additionalDcsDisabled=o.additionalDcsDisabled,this._loopStarted=!1,this._reconnecting=!1,this._destroyed=!1}async connect(){await this._initSession(),void 0===this._sender&&(this._sender=new h(this.session.getAuthKey(),{logger:this._log,dcId:this.session.dcId,retries:this._connectionRetries,delay:this._retryDelay,autoReconnect:this._autoReconnect,connectTimeout:this._timeout,authKeyCallback:this._authKeyCallback.bind(this),updateCallback:this._handleUpdate.bind(this),isMainSender:!0})),this._sender.userDisconnected=!1,this._sender._user_connected=!1,this._sender._reconnecting=!1,this._sender._disconnected=!0;const e=new this._connection(this.session.serverAddress,this.session.port,this.session.dcId,this._log,this._args.testServers);await this._sender.connect(e)?(this.session.setAuthKey(this._sender.authKey),await this._sender.send(this._initWith(new f.help.GetConfig({}))),this._loopStarted||(this._updateLoop(),this._loopStarted=!0),this._reconnecting=!1):this._loopStarted||(this._updateLoop(),this._loopStarted=!0)}async _initSession(){await this.session.load(),this.session.serverAddress&&this.session.serverAddress.includes(":")===this._useIPV6||this.session.setDC(2,this._useIPV6?"[2001:67c:4e8:f002::a]":"zws2.web.telegram.org",this._args.useWSS?443:80)}async _updateLoop(){for(;!this._destroyed;)if(await d.sleep(3e3),!this._reconnecting){try{await k((()=>{return e=this._sender.send(new f.PingDelayDisconnect({pingId:d.getRandomInt(Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER),disconnectDelay:6e4})),5e3,Promise.race([e,d.sleep(5e3).then((()=>Promise.reject(new Error("TIMEOUT"))))]);var e}),3,100)}catch(e){if(console.warn(e),this._reconnecting)continue;await this.disconnect(),await this.connect()}if((new Date).getTime()-this._lastRequest>18e5)try{await this.invoke(new f.updates.GetState)}catch(e){}}await this.disconnect()}async disconnect(){this._sender&&await this._sender.disconnect(),await Promise.all(Object.values(this._exportedSenderPromises).map((e=>e&&e.then((e=>{if(e)return e.disconnect()}))))),this._exportedSenderPromises={}}async destroy(){this._destroyed=!0;try{await this.disconnect()}catch(e){}this.session.delete(),this._eventBuilders=[]}async _switchDC(e){this._log.info(`Reconnecting to new data center ${e}`);const t=l.getDC(e);return this.session.setDC(e,t.ipAddress,t.port),await this._sender.authKey.setKey(void 0),this.session.setAuthKey(void 0),this._reconnecting=!0,await this.disconnect(),this.connect()}_authKeyCallback(e,t){this.session.setAuthKey(e,t)}async _cleanupExportedSender(e){this.session.dcId!==e&&this.session.setAuthKey(void 0,e);const t=await this._exportedSenderPromises[e];this._exportedSenderPromises[e]=void 0,await t.disconnect()}async _connectSender(e,t){const n=l.getDC(t,!!e.authKey.getKey());for(;;)try{if(await e.connect(new this._connection(n.ipAddress,n.port,t,this._log,this._args.testServers)),this.session.dcId!==t&&!e._authenticated){this._log.info(`Exporting authorization for data center ${n.ipAddress}`);const s=await this.invoke(new f.auth.ExportAuthorization({dcId:t})),a=this._initWith(new f.auth.ImportAuthorization({id:s.id,bytes:s.bytes}));await e.send(a),e._authenticated=!0}return e.dcId=t,e.userDisconnected=!1,e}catch(t){console.error(t),await d.sleep(1e3),await e.disconnect()}}async _borrowExportedSender(e,t,n){if(this._additionalDcsDisabled)return;let s;this._exportedSenderPromises[e]&&!t||(this._exportedSenderPromises[e]=this._connectSender(n||this._createExportedSender(e),e));try{if(s=await this._exportedSenderPromises[e],!s.isConnected())return s.isConnecting?(await d.sleep(1e3),this._borrowExportedSender(e,!1,s)):this._borrowExportedSender(e,!0,s)}catch(t){return console.error(t),this._borrowExportedSender(e,!0)}return this._exportedSenderReleaseTimeouts[e]&&(clearTimeout(this._exportedSenderReleaseTimeouts[e]),this._exportedSenderReleaseTimeouts[e]=void 0),this._exportedSenderReleaseTimeouts[e]=setTimeout((()=>{this._exportedSenderReleaseTimeouts[e]=void 0,s.disconnect()}),3e4),s}_createExportedSender(e){return new h(this.session.getAuthKey(e),{logger:this._log,dcId:e,retries:this._connectionRetries,delay:this._retryDelay,autoReconnect:this._autoReconnect,connectTimeout:this._timeout,authKeyCallback:this._authKeyCallback.bind(this),isMainSender:e===this.session.dcId,onConnectionBreak:this._cleanupExportedSender.bind(this)})}getSender(e){return e?this._borrowExportedSender(e):Promise.resolve(this._sender)}downloadFile(e,t={}){return b(this,e,t)}downloadMedia(e,t){let n;if(n=e instanceof p.Message?e.media:e,"string"==typeof n)throw new Error("not implemented");return n instanceof p.MessageMediaWebPage&&n.webpage instanceof p.WebPage&&(n=n.webpage.document||n.webpage.photo),n instanceof p.MessageMediaPhoto||n instanceof p.Photo?this._downloadPhoto(n,t):n instanceof p.MessageMediaDocument||n instanceof p.Document?this._downloadDocument(n,t):n instanceof p.MessageMediaContact?this._downloadContact(n,t):n instanceof p.WebDocument||n instanceof p.WebDocumentNoProxy?this._downloadWebDocument(n,t):void 0}downloadProfilePhoto(e,t=!1){const n=t?"x":"m";let s,a,i;if([765557111,3316604308,524706233,3566872215].includes(e.SUBCLASS_OF_ID)){if(!e.photo){if(!e.chatPhoto)return;return this._downloadPhoto(e.chatPhoto,{sizeType:n})}s=e.photo}else s=e;if(s instanceof p.UserProfilePhoto||s instanceof p.ChatPhoto)return a=s.dcId,i=new p.InputPeerPhotoFileLocation({peer:l.getInputPeer(e),photoId:s.photoId,big:t}),this.downloadFile(i,{dcId:a})}downloadStickerSetThumb(e){if(!e.thumbs||!e.thumbs.length)return;const{thumbVersion:t}=e;return this.downloadFile(new p.InputStickerSetThumb({stickerset:new p.InputStickerSetID({id:e.id,accessHash:e.accessHash}),thumbVersion:t}),{dcId:e.thumbDcId})}_pickFileSize(e,t){if(!t||!e||!e.length)return;let n;for(let s=v.indexOf(t);se.type===v[s])),n)return n}_downloadCachedPhotoSize(e){let t;return t=e instanceof p.PhotoStrippedSize?l.strippedPhotoToJpg(e.bytes):e.bytes,t}_downloadPhoto(e,t){if(e instanceof p.MessageMediaPhoto&&(e=e.photo),!(e instanceof p.Photo))return;const n=this._pickFileSize(e.sizes,t.sizeType);return!n||n instanceof p.PhotoSizeEmpty?void 0:n instanceof p.PhotoCachedSize||n instanceof p.PhotoStrippedSize?this._downloadCachedPhotoSize(n):this.downloadFile(new p.InputPhotoFileLocation({id:e.id,accessHash:e.accessHash,fileReference:e.fileReference,thumbSize:n.type}),{dcId:e.dcId,fileSize:n.size,progressCallback:t.progressCallback})}_downloadDocument(e,t){if(e instanceof p.MessageMediaDocument&&(e=e.document),!(e instanceof p.Document))return;let n;if(t.sizeType){if(n=e.thumbs?this._pickFileSize(e.thumbs,t.sizeType):void 0,!n&&e.mimeType.startsWith("video/"))return;if(n&&(n instanceof p.PhotoCachedSize||n instanceof p.PhotoStrippedSize))return this._downloadCachedPhotoSize(n)}return this.downloadFile(new p.InputDocumentFileLocation({id:e.id,accessHash:e.accessHash,fileReference:e.fileReference,thumbSize:n?n.type:""}),{fileSize:n?n.size:e.size,progressCallback:t.progressCallback,start:t.start,end:t.end,dcId:e.dcId,workers:t.workers})}_downloadContact(e,t){throw new Error("not implemented")}async _downloadWebDocument(e){try{const t=[];let n=0;for(;;){const s=new f.upload.GetWebFile({location:new p.InputWebFileLocation({url:e.url,accessHash:e.accessHash}),offset:n,limit:I}),a=await this._borrowExportedSender(4),i=await a.send(s);if(n+=131072,!i.bytes.length)break;if(t.push(i.bytes),i.bytes.length{"use strict";n.r(t),n.d(t,{authFlow:()=>l,checkAuthorization:()=>u});var s=n(7150),a=n.n(s),i=n(8960),o=n.n(i),r=n(9618),c=n(9674);const d="phoneNumber";async function l(e,t,n){let s;if("botAuthToken"in n)s=await async function(e,t,n){const{apiId:s,apiHash:i}=t,{botAuthToken:o}=n,{user:r}=await e.invoke(new(a().auth.ImportBotAuthorization)({apiId:s,apiHash:i,botAuthToken:o}));return r}(e,t,n);else{const{initialMethod:a=d}=n;s="phoneNumber"===a?await g(e,t,n):await p(e,t,n)}e._log.info("Signed in successfully as",o().getDisplayName(s))}async function u(e){try{return await e.invoke(new(a().updates.GetState)),!0}catch(e){if("Disconnect"===e.message)throw e;return!1}}async function g(e,t,n){let s,i,o,r=!1;for(;;)try{if("function"==typeof n.phoneNumber)try{s=await n.phoneNumber()}catch(s){if("RESTART_AUTH_WITH_QR"===s.message)return p(e,t,n);throw s}else s=n.phoneNumber;const a=await f(e,t,s,n.forceSMS);if(i=a.phoneCodeHash,r=a.isCodeViaApp,"string"!=typeof i)throw new Error("Failed to retrieve phone code hash");break}catch(e){if("function"!=typeof n.phoneNumber)throw e;n.onError(e)}let c,d=!1;for(;;)try{try{o=await n.phoneCode(r)}catch(s){if("RESTART_AUTH"===s.message)return g(e,t,n)}if(!o)throw new Error("Code is empty");const l=await e.invoke(new(a().auth.SignIn)({phoneNumber:s,phoneCodeHash:i,phoneCode:o}));if(l instanceof a().auth.AuthorizationSignUpRequired){d=!0,c=l.termsOfService;break}return l.user}catch(t){if("SESSION_PASSWORD_NEEDED"===t.message)return h(e,0,n);n.onError(t)}if(d)for(;;)try{const[t,o]=await n.firstAndLastNames();if(!t)throw new Error("First name is required");const{user:r}=await e.invoke(new(a().auth.SignUp)({phoneNumber:s,phoneCodeHash:i,firstName:t,lastName:o}));return c&&await e.invoke(new(a().help.AcceptTermsOfService)({id:c.id})),r}catch(e){n.onError(e)}return n.onError(new Error("Auth failed")),g(e,t,n)}async function p(e,t,n){let s=!1;const i=(async()=>{for(;!s;){const t=await e.invoke(new(a().auth.ExportLoginToken)({apiId:Number("2496"),apiHash:"8da85b0d5bfe62527e5b244c209159c3",exceptIds:[]}));if(!(t instanceof a().auth.LoginToken))throw new Error("Unexpected");const{token:s,expires:i}=t;await Promise.race([n.qrCode({token:s,expires:i}),(0,r.sleep)(3e4)])}})(),o=new Promise((t=>{e.addEventHandler((e=>{e instanceof a().UpdateLoginToken&&t()}),{build:e=>e})}));try{await Promise.race([o,i])}catch(s){if("RESTART_AUTH"===s.message)return await g(e,t,n);throw s}finally{s=!0}try{const t=await e.invoke(new(a().auth.ExportLoginToken)({apiId:Number("2496"),apiHash:"8da85b0d5bfe62527e5b244c209159c3",exceptIds:[]}));if(t instanceof a().auth.LoginTokenSuccess&&t.authorization instanceof a().auth.Authorization)return t.authorization.user;if(t instanceof a().auth.LoginTokenMigrateTo){await e._switchDC(t.dcId);const n=await e.invoke(new(a().auth.ImportLoginToken)({token:t.token}));if(n instanceof a().auth.LoginTokenSuccess&&n.authorization instanceof a().auth.Authorization)return n.authorization.user}}catch(t){if("SESSION_PASSWORD_NEEDED"===t.message)return h(e,0,n);throw t}throw void 0}async function f(e,t,n,s=!1){try{const{apiId:i,apiHash:o}=t,r=await e.invoke(new(a().auth.SendCode)({phoneNumber:n,apiId:i,apiHash:o,settings:new(a().CodeSettings)}));if(!s||r.type instanceof a().auth.SentCodeTypeSms)return{phoneCodeHash:r.phoneCodeHash,isCodeViaApp:r.type instanceof a().auth.SentCodeTypeApp};const c=await e.invoke(new(a().auth.ResendCode)({phoneNumber:n,phoneCodeHash:r.phoneCodeHash}));return{phoneCodeHash:c.phoneCodeHash,isCodeViaApp:c.type instanceof a().auth.SentCodeTypeApp}}catch(a){if("AUTH_RESTART"===a.message)return f(e,t,n,s);throw a}}async function h(e,t,n){for(;;)try{const t=await e.invoke(new(a().account.GetPassword)),s=await n.password(t.hint);if(!s)throw new Error("Password is empty");const i=await(0,c.computeCheck)(t,s),{user:o}=await e.invoke(new(a().auth.CheckPassword)({password:i}));return o}catch(e){n.onError(e)}}},2288:(e,t,n)=>{"use strict";n.r(t),n.d(t,{downloadFile:()=>p});var s=n(7150),a=n.n(s),i=n(8960),o=n(9618),r=n(7873),c=n.n(r),d=n(8764).Buffer;function l(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const u=1048576;class g{constructor(e){this.maxWorkers=e,l(this,"deferred",void 0),l(this,"activeWorkers",0)}requestWorker(){return this.activeWorkers++,this.activeWorkers>this.maxWorkers?(this.deferred=(0,o.createDeferred)(),this.deferred.promise):Promise.resolve()}releaseWorker(){this.activeWorkers--,this.deferred&&this.activeWorkers<=this.maxWorkers&&this.deferred.resolve()}}async function p(e,t,n){let{partSizeKb:s,end:r}=n;const{fileSize:l,workers:p=1}=n,{dcId:f,progressCallback:h,start:m=0}=n;r=r&&r{for(;;){let d;try{d=await e.getSender(f);const o=await d.send(new(a().upload.GetFile)({location:t,offset:i,limit:n,precise:s||void 0}));if(h){if(h.isCanceled)throw new Error("USER_CANCELED");v+=1/y,h(v)}return!r&&o.bytes.lengthr)break}const P=(await Promise.all(w)).filter(Boolean),S=r?r+1-m:void 0;return d.concat(P,S)}},4766:(e,t,n)=>{"use strict";n.r(t),n.d(t,{uploadFile:()=>l});var s=n(7150),a=n.n(s),i=n(9618),o=n(8960),r=n(7873),c=n.n(r),d=n(8764).Buffer;async function l(e,t){const{file:n,onProgress:s}=t;let{workers:r}=t;const{name:l,size:u}=n,g=(0,i.readBigIntFromBuffer)((0,i.generateRandomBytes)(8),!0,!0),p=u>10485760,f=1024*(0,o.getAppropriatedPartSize)(u),h=Math.floor((u+f-1)/f),m=d.from(await function(e){return new Response(e).arrayBuffer()}(n));await e.getSender(e.session.dcId),r&&u||(r=1),r>=h&&(r=h);let _=0;s&&s(_);for(let t=0;th&&(o=h);for(let r=t;r{for(;;){let o;try{o=await e.getSender(e.session.dcId),await o.send(p?new(a().upload.SaveBigFilePart)({fileId:g,filePart:t,fileTotalParts:h,bytes:n}):new(a().upload.SaveFilePart)({fileId:g,filePart:t,bytes:n}))}catch(e){if(o&&!o.isConnected()){await(0,i.sleep)(1e3);continue}if(e instanceof c().FloodWaitError){await(0,i.sleep)(1e3*e.seconds);continue}throw e}if(s){if(s.isCanceled)throw new Error("USER_CANCELED");_+=1/h,s(_)}break}})(r,t))}await Promise.all(n)}return p?new(a().InputFileBig)({id:g,parts:h,name:l}):new(a().InputFile)({id:g,parts:h,name:l,md5Checksum:""})}},3302:(e,t,n)=>{var s=n(8764).Buffer;const{sha1:a,toSignedLittleBuffer:i,readBufferFromBigInt:o,readBigIntFromBuffer:r}=n(9618),c=n(5544),{sleep:d}=n(9618);class l{constructor(e,t){if(!t||!e)return;this._key=e,this._hash=t;const n=new c(t);this.auxHash=n.readLong(!1),n.read(4),this.keyId=n.readLong(!1)}async setKey(e){if(!e)return this._key=void 0,this.auxHash=void 0,this.keyId=void 0,void(this._hash=void 0);if(e instanceof l)return this._key=e._key,this.auxHash=e.auxHash,this.keyId=e.keyId,void(this._hash=e._hash);this._key=e,this._hash=await a(this._key);const t=new c(this._hash);this.auxHash=t.readLong(!1),t.read(4),this.keyId=t.readLong(!1)}async waitForKey(){for(;!this.keyId;)await d(20)}getKey(){return this._key}async calcNewNonceHash(e,t){e=i(e,32);const n=s.alloc(1);n.writeUInt8(t,0);const c=s.concat([e,s.concat([n,o(this.auxHash,8,!0)])]),d=(await a(c)).slice(4,20);return r(d,!0,!0)}equals(e){return e instanceof this.constructor&&this._key&&e.getKey()&&e.getKey().equals(this._key)}}e.exports=l},5830:(e,t,n)=>{var s=n(8764).Buffer;const a=n(6842);e.exports=class{constructor(e,t){if(!s.isBuffer(e)||!s.isBuffer(t)||16!==t.length)throw new Error("Key and iv need to be a buffer");this.cipher=a.createCipheriv("AES-256-CTR",e,t)}encrypt(e){return s.from(this.cipher.update(e))}}},9636:(e,t,n)=>{const s=n(4736),{modExp:a}=n(9618);class i{static gcd(e,t){for(;t.neq(s.zero);){const n=t;t=e.remainder(t),e=n}return e}static factorize(e){if(e.remainder(2).equals(s.zero))return{p:s(2),q:e.divide(s(2))};let t=s.randBetween(s(1),e.minus(1));const n=s.randBetween(s(1),e.minus(1)),o=s.randBetween(s(1),e.minus(1));let r,c=s.one,d=s.one,l=s.one,u=s.zero,g=s.zero;for(;c.eq(s.one);){u=t;for(let i=0;s(i).lesser(d);i++)t=a(t,s(2),e).add(n).remainder(e);for(r=s.zero;r.lesser(d)&&c.eq(s.one);){g=t;const p=s.min(o,d.minus(r));for(let i=0;s(i).lesser(p);i++)t=a(t,s(2),e).add(n).remainder(e),l=l.multiply(u.minus(t).abs()).remainder(e);c=i.gcd(l,e),r=r.add(o)}d=d.multiply(2)}if(c.eq(e))for(;g=a(g,s(2),e).add(n).remainder(e),c=i.gcd(u.minus(g).abs(),e),!c.greater(1););const p=c;return l=e.divide(c),p{var s=n(8764).Buffer;const{IGE:a}=n(8136),i=n(9618);e.exports=class{constructor(e,t){this.ige=new a(e,t)}decryptIge(e){return i.convertToLittle(this.ige.decrypt(e))}encryptIge(e){const t=e.length%16;return t&&(e=s.concat([e,i.generateRandomBytes(16-t)])),i.convertToLittle(this.ige.encrypt(e))}}},4121:(e,t,n)=>{"use strict";function s(e){const t=new Uint8Array(4*e.length);let n=0;for(let s=0;s>>24,t[n++]=a>>16&255,t[n++]=a>>8&255,t[n++]=255&a}return t.buffer}function a(e){return e.buffer}function i(e){const t=new Uint8Array(e),n=new Uint32Array(t.length/4);for(let e=0;es,i2abBig:()=>a,ab2iLow:()=>i,ab2iBig:()=>o,isBigEndian:()=>r,i2ab:()=>c,ab2i:()=>d});const r=1===new Uint8Array(new Uint32Array([16909060]))[0],c=r?a:s,d=r?o:i},6842:(e,t,n)=>{var s=n(8764).Buffer;const a=n(8136).default,{i2ab:i,ab2i:o}=n(4121),{getWords:r}=n(7760);class c{constructor(e){this.setBytes(e)}setBytes(e){e=s.from(e),this._counter=e}increment(){for(let e=15;e>=0;e--){if(255!==this._counter[e]){this._counter[e]++;break}this._counter[e]=0}}}class d{constructor(e,t){t instanceof c||(t=new c(t)),this._counter=t,this._remainingCounter=void 0,this._remainingCounterIndex=16,this._aes=new a(r(e))}update(e){return this.encrypt(e)}encrypt(e){const t=s.from(e);for(let e=0;e{"use strict";function s(e,t){return e.charCodeAt(t)<<24^e.charCodeAt(t+1)<<16^e.charCodeAt(t+2)<<8^e.charCodeAt(t+3)}function a(e){if(e instanceof Uint32Array)return e;if("string"==typeof e){if(e.length%4!=0)for(let t=e.length%4;t<=4;t++)e+="\0x00";const t=new Uint32Array(e.length/4);for(let n=0;ns,getWords:()=>a,xor:()=>i})},8187:e=>{class t extends Error{constructor(){super("The read operation was cancelled.")}}class n extends Error{constructor(e,t){super(`Could not find a matching Constructor ID for the TLObject that was supposed to be\n read with ID ${e}. Most likely, a TLObject was trying to be read when\n it should not be read. Remaining bytes: ${t.length}`),"undefined"!=typeof alert&&alert(`Missing MTProto Entity: Please, make sure to add TL definition for ID ${e}`),this.invalidConstructorId=e,this.remaining=t}}class s extends Error{constructor(e,t){super(`Invalid checksum (${e} when ${t} was expected). This packet should be skipped.`),this.checksum=e,this.validChecksum=t}}class a extends Error{constructor(e){let t;4===e.length?(t=-e.readInt32LE(0),super(`Invalid response buffer (HTTP code ${t})`)):super(`Invalid response buffer (too short ${e})`),this.code=t,this.payload=e}}class i extends Error{constructor(...e){e.length||(e=["A security check failed."]),super(...e)}}class o extends Error{constructor(e,t){let n=o.ErrorMessages[t]||`Unknown error code (this should not happen): ${t}.`;n+=` Caused by ${e.className}`,super(n),this.message=n,this.code=t}}var r,c,d;d={16:"msg_id too low (most likely, client time is wrong it would be worthwhile to synchronize it using msg_id notifications and re-send the original message with the “correct” msg_id or wrap it in a container with a new msg_id if the original message had waited too long on the client to be transmitted).",17:"msg_id too high (similar to the previous case, the client time has to be synchronized, and the message re-sent with the correct msg_id).",18:"Incorrect two lower order msg_id bits (the server expects client message msg_id to be divisible by 4).",19:"Container msg_id is the same as msg_id of a previously received message (this must never happen).",20:"Message too old, and it cannot be verified whether the server has received a message with this msg_id or not.",32:"msg_seqno too low (the server has already received a message with a lower msg_id but with either a higher or an equal and odd seqno).",33:"msg_seqno too high (similarly, there is a message with a higher msg_id but with either a lower or an equal and odd seqno).",34:"An even msg_seqno expected (irrelevant message), but odd received.",35:"Odd msg_seqno expected (relevant message), but even received.",48:"Incorrect server salt (in this case, the bad_server_salt response is received with the correct salt, and the message is to be re-sent with it).",64:"Invalid container."},(c="ErrorMessages")in(r=o)?Object.defineProperty(r,c,{value:d,enumerable:!0,configurable:!0,writable:!0}):r[c]=d,e.exports={ReadCancelledError:t,TypeNotFoundError:n,InvalidChecksumError:s,InvalidBufferError:a,SecurityError:i,CdnFileTamperedError:class extends i{constructor(){super("The CDN file has been altered and its download cancelled.")}},BadMessageError:o}},6952:e=>{function t(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class n extends Error{constructor(e,t,s){super("RPCError {0}: {1}{2}".replace("{0}",s).replace("{1}",e).replace("{2}",n._fmtRequest(t))),this.code=s,this.message=e}static _fmtRequest(e){return e?` (caused by ${e.className})`:""}}e.exports={RPCError:n,InvalidDCError:class extends n{constructor(e,t,n){super(t,e,n),this.code=n||303,this.message=t||"ERROR_SEE_OTHER"}},BadRequestError:class extends n{constructor(...e){super(...e),t(this,"code",400),t(this,"message","BAD_REQUEST")}},UnauthorizedError:class extends n{constructor(...e){super(...e),t(this,"code",401),t(this,"message","UNAUTHORIZED")}},ForbiddenError:class extends n{constructor(...e){super(...e),t(this,"code",403),t(this,"message","FORBIDDEN")}},NotFoundError:class extends n{constructor(...e){super(...e),t(this,"code",404),t(this,"message","NOT_FOUND")}},AuthKeyError:class extends n{constructor(...e){super(...e),t(this,"code",406),t(this,"message","AUTH_KEY")}},FloodError:class extends n{constructor(...e){super(...e),t(this,"code",420),t(this,"message","FLOOD")}},ServerError:class extends n{constructor(...e){super(...e),t(this,"code",500),t(this,"message","INTERNAL")}},TimedOutError:class extends n{constructor(...e){super(...e),t(this,"code",503),t(this,"message","Timeout")}}}},5651:(e,t,n)=>{const{RPCError:s,InvalidDCError:a,FloodError:i,BadRequestError:o}=n(6952);class r extends a{constructor(e){const t=Number(e.capture||0);super(`The user whose identity is being used to execute queries is associated with DC ${t}${s._fmtRequest(e.request)}`),this.message=`The user whose identity is being used to execute queries is associated with DC ${t}${s._fmtRequest(e.request)}`,this.newDc=t}}class c extends a{constructor(e){const t=Number(e.capture||0);super(`The phone number a user is trying to use for authorization is associated with DC ${t}${s._fmtRequest(e.request)}`),this.message=`The phone number a user is trying to use for authorization is associated with DC ${t}${s._fmtRequest(e.request)}`,this.newDc=t}}class d extends i{constructor(e){const t=Number(e.capture||0);super(`A wait of ${t} seconds is required before sending another message in this chat${s._fmtRequest(e.request)}`),this.message=`A wait of ${t} seconds is required before sending another message in this chat${s._fmtRequest(e.request)}`,this.seconds=t}}class l extends i{constructor(e){const t=Number(e.capture||0);super(`A wait of ${t} seconds is required${s._fmtRequest(e.request)}`),this.message=`A wait of ${t} seconds is required${s._fmtRequest(e.request)}`,this.seconds=t}}class u extends i{constructor(e){super(`Message failed to be sent.${s._fmtRequest(e.request)}`),this.message=`Message failed to be sent.${s._fmtRequest(e.request)}`}}class g extends i{constructor(e){const t=Number(e.capture||0);super(`A wait of ${t} seconds is required in the test servers${s._fmtRequest(e.request)}`),this.message=`A wait of ${t} seconds is required in the test servers${s._fmtRequest(e.request)}`,this.seconds=t}}class p extends a{constructor(e){const t=Number(e.capture||0);super(`The file to be accessed is currently stored in DC ${t}${s._fmtRequest(e.request)}`),this.message=`The file to be accessed is currently stored in DC ${t}${s._fmtRequest(e.request)}`,this.newDc=t}}class f extends a{constructor(e){const t=Number(e.capture||0);super(`The source IP address is associated with DC ${t}${s._fmtRequest(e.request)}`),this.message=`The source IP address is associated with DC ${t}${s._fmtRequest(e.request)}`,this.newDc=t}}class h extends o{constructor(e){const t=Number(e.capture||0);super(`Email unconfirmed, the length of the code must be ${t}${s._fmtRequest(e.request)}`),this.message=`Email unconfirmed, the length of the code must be ${t}${s._fmtRequest(e.request)}`,this.codeLength=t}}const m=[[/FILE_MIGRATE_(\d+)/,p],[/FLOOD_TEST_PHONE_WAIT_(\d+)/,g],[/FLOOD_WAIT_(\d+)/,l],[/MSG_WAIT_(.*)/,u],[/PHONE_MIGRATE_(\d+)/,c],[/SLOWMODE_WAIT_(\d+)/,d],[/USER_MIGRATE_(\d+)/,r],[/NETWORK_MIGRATE_(\d+)/,f],[/EMAIL_UNCONFIRMED_(\d+)/,h]];e.exports={rpcErrorRe:m,FileMigrateError:p,FloodTestPhoneWaitError:g,FloodWaitError:l,PhoneMigrateError:c,SlowModeWaitError:d,UserMigrateError:r,NetworkMigrateError:f,MsgWaitError:u,EmailUnconfirmedError:h}},7873:(e,t,n)=>{const{RPCError:s}=n(6952),{rpcErrorRe:a}=n(5651),i=n(8187),o=n(6952),r=n(5651);e.exports={RPCMessageToError:function(e,t){for(const[n,s]of a){const a=e.errorMessage.match(n);if(a)return new s({request:t,capture:2===a.length?parseInt(a[1],10):void 0})}return new s(e.errorMessage,t)},...i,...o,...r}},6316:()=>{},3903:(e,t,n)=>{const{EventBuilder:s}=n(6172);e.exports=class extends s{constructor(e={types:void 0,func:void 0}){super(),e.types?this.types=e.types:this.types=!0}build(e){return e}}},6172:e=>{e.exports={EventBuilder:class{constructor(e={chats:void 0,blacklistChats:void 0,func:void 0}){this.chats=e.chats,this.blacklistChats=Boolean(e.blacklistChats),this.resolved=!1,this.func=e.func}build(e){}}}},3182:(e,t,n)=>{const s=n(6316),a=n(3903);class i extends Error{}e.exports={NewMessage:s,StopPropagation:i,Raw:a}},6151:e=>{e.exports=class{constructor(){this._queue=[],this.canGet=new Promise((e=>{this.resolveGet=e})),this.canPush=!0}async push(e){await this.canPush,this._queue.push(e),this.resolveGet(!0),this.canPush=new Promise((e=>{this.resolvePush=e}))}async pop(){await this.canGet;const e=this._queue.pop();return this.resolvePush(!0),this.canGet=new Promise((e=>{this.resolveGet=e})),e}}},5544:(e,t,n)=>{const{TypeNotFoundError:s}=n(8187),{coreObjects:a}=n(2058),{tlobjects:i}=n(845),{readBigIntFromBuffer:o}=n(9618);e.exports=class{constructor(e){this.stream=e,this._last=void 0,this.offset=0}readByte(){return this.read(1)[0]}readInt(e=!0){let t;return t=e?this.stream.readInt32LE(this.offset):this.stream.readUInt32LE(this.offset),this.offset+=4,t}readLong(e=!0){return this.readLargeInt(64,e)}readFloat(){return this.read(4).readFloatLE(0)}readDouble(){return this.read(8).readDoubleLE(0)}readLargeInt(e,t=!0){const n=this.read(Math.floor(e/8));return o(n,!0,t)}read(e=-1){-1===e&&(e=this.stream.length-this.offset);const t=this.stream.slice(this.offset,this.offset+e);if(this.offset+=e,t.length!==e)throw Error(`No more data left to read (need ${e}, got ${t.length}: ${t}); last read ${this._last}`);return this._last=t,t}getBuffer(){return this.stream}tgReadBytes(){const e=this.readByte();let t,n;254===e?(n=this.readByte()|this.readByte()<<8|this.readByte()<<16,t=n%4):(n=e,t=(n+1)%4);const s=this.read(n);return t>0&&(t=4-t,this.read(t)),s}tgReadString(){return this.tgReadBytes().toString("utf-8")}tgReadBool(){const e=this.readInt(!1);if(2574415285===e)return!0;if(3162085175===e)return!1;throw new Error(`Invalid boolean code ${e.toString("16")}`)}tgReadDate(){const e=this.readInt();return new Date(1e3*e)}tgReadObject(){const e=this.readInt(!1);let t=i[e];if(void 0===t){if(2574415285===e)return!0;if(3162085175===e)return!1;if(481674261===e){const e=[],t=this.readInt();for(let n=0;n{var s=n(8764).Buffer;e.exports=class{constructor(e){this._stream=e}write(e){this._stream=s.concat([this._stream,e])}getValue(){return this._stream}}},6748:e=>{let t;class n{constructor(e){t||(t=e||"debug"),this.isBrowser="undefined"==typeof process||"renderer"===process.type||!0===process.browser||process.__nwjs,this.isBrowser?this.colors={start:"%c",warn:"color : #ff00ff",info:"color : #ffff00",debug:"color : #00ffff",error:"color : #ff0000",end:""}:this.colors={start:"",warn:"",info:"",debug:"",error:"",end:""},this.messageFormat="[%t] [%l] - [%m]"}static setLevel(e){t=e}canSend(e){return n.levels.indexOf(t)>=n.levels.indexOf(e)}warn(e){"debug"===t&&console.error((new Error).stack),this._log("warn",e,this.colors.warn)}info(e){this._log("info",e,this.colors.info)}debug(e){this._log("debug",e,this.colors.debug)}error(e){"debug"===t&&console.error((new Error).stack),this._log("error",e,this.colors.error)}format(e,t){return this.messageFormat.replace("%t",(new Date).toISOString()).replace("%l",t.toUpperCase()).replace("%m",e)}_log(e,n,s){t&&this.canSend(e)&&(this.isBrowser?console.log(this.colors.start+this.format(n,e),s):console.log(s+this.format(n,e)+this.colors.end))}}var s,a,i;i=["error","warn","info","debug"],(a="levels")in(s=n)?Object.defineProperty(s,a,{value:i,enumerable:!0,configurable:!0,writable:!0}):s[a]=i,e.exports=n},6411:(e,t,n)=>{var s=n(8764).Buffer;const a=n(3254),i=n(355),o=n(6472),r=["messages.SendMessage","messages.SendMedia","messages.SendMultiMedia","messages.ForwardMessages","messages.SendInlineBotResult"];e.exports=class{constructor(e,t){this._state=e,this._queue=[],this._pendingStates=[],this._ready=new Promise((e=>{this.setReady=e})),this._log=t}values(){return this._queue}append(e){if(e&&r.includes(e.request.className))for(let t=this._queue.length-1;t>=0;t--)if(r.includes(this._queue[t].request.className)){e.after=this._queue[t];break}this._queue.push(e),this.setReady(!0),e&&1658238041!==e.request.CONSTRUCTOR_ID&&(this._pendingStates.push(e),e.promise.catch((()=>{})).finally((()=>{this._pendingStates=this._pendingStates.filter((t=>t!==e))})))}extend(e){for(const t of e)this._queue.push(t);this.setReady(!0)}async get(){if(this._queue.length||(this._ready=new Promise((e=>{this.setReady=e})),await this._ready),!this._queue[this._queue.length-1])return void(this._queue=[]);let e,t=new o(s.alloc(0));const n=[];let r=0;for(;this._queue.length&&n.length<=a.MAXIMUM_LENGTH;){const e=this._queue.shift();if(r+=e.data.length+i.SIZE_OVERHEAD,r<=a.MAXIMUM_SIZE){let s;e.after&&(s=e.after.msgId),e.msgId=await this._state.writeDataAsMessage(t,e.data,"request"===e.request.classType,s),this._log.debug(`Assigned msgId = ${e.msgId} to ${e.request.className||e.request.constructor.name}`),n.push(e)}else{if(n.length){this._queue.unshift(e);break}this._log.warn(`Message payload for ${e.request.className||e.request.constructor.name} is too long ${e.data.length} and cannot be sent`),e.reject("Request Payload is too big"),r=0}}if(n.length){if(n.length>1){const i=s.alloc(8);i.writeUInt32LE(a.CONSTRUCTOR_ID,0),i.writeInt32LE(n.length,4),e=s.concat([i,t.getValue()]),t=new o(s.alloc(0));const r=await this._state.writeDataAsMessage(t,e,!1);for(const e of n)e.containerId=r}return e=t.getValue(),{batch:n,data:e}}}rejectAll(){this._pendingStates.forEach((e=>{e.reject(new Error("Disconnect"))}))}}},7214:(e,t,n)=>{var s=n(8764).Buffer;const{Mutex:a}=n(8125),i=new a,o=n(5840).w3cwebsocket,r=new Error("WebSocket was closed");e.exports=class{constructor(e){this.client=void 0,this.closed=!0,this.disconnectedCallback=e}async readExactly(e){let t=s.alloc(0);for(;;){const n=await this.read(e);if(t=s.concat([t,n]),!(e-=n.length))return t}}async read(e){if(this.closed)throw r;if(await this.canRead,this.closed)throw r;const t=this.stream.slice(0,e);return this.stream=this.stream.slice(e),0===this.stream.length&&(this.canRead=new Promise((e=>{this.resolveRead=e}))),t}async readAll(){if(this.closed||!await this.canRead)throw r;const e=this.stream;return this.stream=s.alloc(0),this.canRead=new Promise((e=>{this.resolveRead=e})),e}getWebSocketLink(e,t,n){return 443===t?`wss://${e}:${t}/apiws${n?"_test":""}`:`ws://${e}:${t}/apiws${n?"_test":""}`}connect(e,t,n=!1){return this.stream=s.alloc(0),this.canRead=new Promise((e=>{this.resolveRead=e})),this.closed=!1,this.website=this.getWebSocketLink(t,e,n),this.client=new o(this.website,"binary"),new Promise(((e,n)=>{this.client.onopen=()=>{this.receive(),e(this)},this.client.onerror=e=>{console.error("WebSocket error",e),n(e)},this.client.onclose=e=>{const{code:n,reason:s,wasClean:a}=e;1e3!==n&&console.error(`Socket ${t} closed. Code: ${n}, reason: ${s}, was clean: ${a}`),this.resolveRead(!1),this.closed=!0,this.disconnectedCallback&&this.disconnectedCallback()},self.addEventListener("offline",(async()=>{await this.close(),this.resolveRead(!1)}))}))}write(e){if(this.closed)throw r;this.client.send(e)}async close(){await this.client.close(),this.closed=!0}receive(){this.client.onmessage=async e=>{await i.runExclusive((async()=>{const t=e.data instanceof ArrayBuffer?s.from(e.data):s.from(await new Response(e.data).arrayBuffer());this.stream=s.concat([this.stream,t]),this.resolveRead(!0)}))}}}},9832:(e,t,n)=>{const s=n(6748),a=n(6472),i=n(5544),o=n(7214),r=n(6411),c=n(6151);e.exports={BinaryWriter:a,BinaryReader:i,MessagePacker:r,AsyncQueue:c,Logger:s,PromisedWebSockets:o}},3522:(e,t,n)=>{const s=n(7150),a=n(8742),i=n(8415),o=n(7404),r=n(1472),c=n(3182),d=n(8960),l=n(7873),u=n(5886),g=n(9832),p=n(9618);e.exports={Api:s,TelegramClient:a,sessions:u,connection:i,extensions:g,tl:o,version:r,events:c,utils:d,errors:l,helpers:p}},9870:(e,t,n)=>{"use strict";n.r(t),n.d(t,{doAuthentication:()=>_});var s=n(7150),a=n.n(s),i=n(7873),o=n(4736),r=n.n(o);n(9618),n(8764).Buffer;const c=[{fingerprint:r()("-3414540481677951611"),n:r()("29379598170669337022986177149456128565388431120058863768162556424047512191330847455146576344487764408661701890505066208632169112269581063774293102577308490531282748465986139880977280302242772832972539403531316010870401287642763009136156734339538042419388722777357134487746169093539093850251243897188928735903389451772730245253062963384108812842079887538976360465290946139638691491496062099570836476454855996319192747663615955633778034897140982517446405334423701359108810182097749467210509584293428076654573384828809574217079944388301239431309115013843331317877374435868468779972014486325557807783825502498215169806323"),e:65537},{fingerprint:r()("-5595554452916591101"),n:r()("25342889448840415564971689590713473206898847759084779052582026594546022463853940585885215951168491965708222649399180603818074200620463776135424884632162512403163793083921641631564740959529419359595852941166848940585952337613333022396096584117954892216031229237302943701877588456738335398602461675225081791820393153757504952636234951323237820036543581047826906120927972487366805292115792231423684261262330394324750785450942589751755390156647751460719351439969059949569615302809050721500330239005077889855323917509948255722081644689442127297605422579707142646660768825302832201908302295573257427896031830742328565032949"),e:65537}],d=new Map;c.forEach((({fingerprint:e,...t})=>{d.set(e.toString(),t)}));var l=n(8764).Buffer;const u=n(4736),g=n(2608),p=n(3302),f=n(9636),h=n(9618),m=n(5544);async function _(e,t){let n=h.generateRandomBytes(16);const s=h.readBigIntFromBuffer(n,!1,!0),o=await e.send(new(a().ReqPqMulti)({nonce:s}));if(t.debug("Starting authKey generation step 1"),!(o instanceof a().ResPQ))throw new i.SecurityError(`Step 1 answer was ${o}`);if(o.nonce.neq(s))throw new i.SecurityError("Step 1 invalid nonce from server");const r=h.readBigIntFromBuffer(o.pq,!1,!0);t.debug("Finished authKey generation step 1");const{p:c,q:_}=f.factorize(r),y=h.getByteArray(c),b=h.getByteArray(_);n=h.generateRandomBytes(32);const w=h.readBigIntFromBuffer(n,!0,!0),C=new(a().PQInnerData)({pq:h.getByteArray(r),p:y,q:b,nonce:o.nonce,serverNonce:o.serverNonce,newNonce:w}).getBytes();if(C.length>144)throw new i.SecurityError("Step 1 invalid nonce from server");let I,v;for(const e of o.serverPublicKeyFingerprints)if(v=d.get(e.toString()),void 0!==v){I=e;break}if(void 0===I||void 0===v)throw new i.SecurityError("Step 2 could not find a valid key for fingerprints");const P=h.generateRandomBytes(192-C.length),S=l.concat([C,P]),A=l.from(S).reverse();let M;for(let e=0;e<20;e++){const e=h.generateRandomBytes(32),n=await h.sha256(l.concat([e,S])),s=l.concat([A,n]),a=new g(e,l.alloc(32)).encryptIge(s),i=h.bufferXor(e,await h.sha256(a)),o=l.concat([i,a]),r=h.readBigIntFromBuffer(o,!1,!1);if(r.greaterOrEquals(v.n)){t.debug("Aes key greater than RSA. retrying");continue}const c=h.modExp(r,u(v.e),v.n);M=h.readBufferFromBigInt(c,256,!1,!1);break}if(void 0===M)throw new i.SecurityError("Step 2 could create a secure encrypted key");t.debug("Step 2 : Generated a secure aes encrypted data");const k=await e.send(new(a().ReqDHParams)({nonce:o.nonce,serverNonce:o.serverNonce,p:y,q:b,publicKeyFingerprint:I,encryptedData:M}));if(!(k instanceof a().ServerDHParamsOk||k instanceof a().ServerDHParamsFail))throw new Error(`Step 2.1 answer was ${k}`);if(k.nonce.neq(o.nonce))throw new i.SecurityError("Step 2 invalid nonce from server");if(k.serverNonce.neq(o.serverNonce))throw new i.SecurityError("Step 2 invalid server nonce from server");if(k instanceof a().ServerDHParamsFail){const e=await h.sha1(h.toSignedLittleBuffer(w,32).slice(4,20)),t=h.readBigIntFromBuffer(e,!0,!0);if(k.newNonceHash.neq(t))throw new i.SecurityError("Step 2 invalid DH fail nonce from server")}if(!(k instanceof a().ServerDHParamsOk))throw new Error(`Step 2.2 answer was ${k}`);t.debug("Finished authKey generation step 2"),t.debug("Starting authKey generation step 3");const{key:R,iv:U}=await h.generateKeyDataFromNonce(o.serverNonce,w);if(k.encryptedAnswer.length%16!=0)throw new i.SecurityError("Step 3 AES block size mismatch");const E=new g(R,U),T=E.decryptIge(k.encryptedAnswer),D=new m(T);D.read(20);const B=D.tgReadObject();if(!(B instanceof a().ServerDHInnerData))throw new Error(`Step 3 answer was ${B}`);if(B.nonce.neq(o.nonce))throw new i.SecurityError("Step 3 Invalid nonce in encrypted answer");if(B.serverNonce.neq(o.serverNonce))throw new i.SecurityError("Step 3 Invalid server nonce in encrypted answer");const x=h.readBigIntFromBuffer(B.dhPrime,!1,!1),V=h.readBigIntFromBuffer(B.gA,!1,!1),N=B.serverTime-Math.floor((new Date).getTime()/1e3),F=h.readBigIntFromBuffer(h.generateRandomBytes(256),!1,!1),O=h.modExp(u(B.g),F,x),L=h.modExp(V,F,x),q=new(a().ClientDHInnerData)({nonce:o.nonce,serverNonce:o.serverNonce,retryId:u.zero,gB:h.getByteArray(O,!1)}).getBytes(),H=l.concat([await h.sha1(q),q]),G=E.encryptIge(H),K=await e.send(new(a().SetClientDHParams)({nonce:o.nonce,serverNonce:o.serverNonce,encryptedData:G})),z=[a().DhGenOk,a().DhGenRetry,a().DhGenFail];if(!(K instanceof z[0]||K instanceof z[1]||K instanceof z[2]))throw new Error(`Step 3.1 answer was ${K}`);const{name:W}=K.constructor;if(K.nonce.neq(o.nonce))throw new i.SecurityError(`Step 3 invalid ${W} nonce from server`);if(K.serverNonce.neq(o.serverNonce))throw new i.SecurityError(`Step 3 invalid ${W} server nonce from server`);const j=new p;await j.setKey(h.getByteArray(L));const $=1+["DhGenOk","DhGenRetry","DhGenFail"].indexOf(K.className),J=await j.calcNewNonceHash(w,$);if(K[`newNonceHash${$}`].neq(J))throw new i.SecurityError("Step 3 invalid new nonce hash");if(!(K instanceof a().DhGenOk))throw new Error(`Step 3.2 answer was ${K}`);return t.debug("Finished authKey generation step 3"),{authKey:j,timeOffset:N}}},5585:(e,t,n)=>{var s=n(8764).Buffer;const a=n(4736),i=n(9109),o=n(5544),{InvalidBufferError:r}=n(8187),{toSignedLittleBuffer:c}=n(9618);e.exports=class{constructor(e,t){this._state=new i(e,t),this._connection=e}async send(e){let t=e.getBytes(),n=this._state._getNewMsgId();const i=c(n,8),d=s.alloc(4);d.writeInt32LE(t.length,0);const l=s.concat([s.concat([s.alloc(8),i,d]),t]);if(await this._connection.send(l),t=await this._connection.recv(),t.length<8)throw new r(t);const u=new o(t);if(u.readLong().neq(a(0)))throw new Error("Bad authKeyId");if(n=u.readLong(),n.eq(a(0)))throw new Error("Bad msgId");if(u.readInt()<=0)throw new Error("Bad length");return u.tgReadObject()}}},4046:(e,t,n)=>{const s=n(5585),a=n(9109),i=n(9618),o=n(3302),{doAuthentication:r}=n(9870),c=n(2301),d=n(3254),l=n(8963),u=n(4287),{MsgsAck:g,upload:p,MsgsStateInfo:f,Pong:h}=n(7404).constructors,m=n(6411),_=n(5544),{UpdateConnectionState:y,UpdateServerTimeOffset:b}=n(8415),{BadMessageError:w}=n(8187),{BadServerSalt:C,BadMsgNotification:I,MsgDetailedInfo:v,MsgNewDetailedInfo:P,NewSessionCreated:S,FutureSalts:A,MsgsStateReq:M,MsgResendReq:k,MsgsAllInfo:R}=n(7404).constructors,{SecurityError:U}=n(8187),{InvalidBufferError:E}=n(8187),{LogOut:T}=n(7404).requests.auth,{RPCMessageToError:D}=n(7873),{TypeNotFoundError:B}=n(8187);class x{constructor(e,t){const n={...x.DEFAULT_OPTIONS,...t};this._connection=void 0,this._log=n.logger,this._dcId=n.dcId,this._retries=n.retries,this._delay=n.delay,this._autoReconnect=n.autoReconnect,this._connectTimeout=n.connectTimeout,this._authKeyCallback=n.authKeyCallback,this._updateCallback=n.updateCallback,this._autoReconnectCallback=n.autoReconnectCallback,this._isMainSender=n.isMainSender,this._onConnectionBreak=n.onConnectionBreak,this.userDisconnected=!1,this._user_connected=!1,this._reconnecting=!1,this._disconnected=!0,this._send_loop_handle=void 0,this._recv_loop_handle=void 0,this.authKey=e||new o,this._state=new a(this.authKey,this._log),this._send_queue=new m(this._state,this._log),this._pending_state={},this._pending_ack=new Set,this._last_acks=[],this._handlers={[c.CONSTRUCTOR_ID]:this._handleRPCResult.bind(this),[d.CONSTRUCTOR_ID]:this._handleContainer.bind(this),[l.CONSTRUCTOR_ID]:this._handleGzipPacked.bind(this),[h.CONSTRUCTOR_ID]:this._handlePong.bind(this),[C.CONSTRUCTOR_ID]:this._handleBadServerSalt.bind(this),[I.CONSTRUCTOR_ID]:this._handleBadNotification.bind(this),[v.CONSTRUCTOR_ID]:this._handleDetailedInfo.bind(this),[P.CONSTRUCTOR_ID]:this._handleNewDetailedInfo.bind(this),[S.CONSTRUCTOR_ID]:this._handleNewSessionCreated.bind(this),[g.CONSTRUCTOR_ID]:this._handleAck.bind(this),[A.CONSTRUCTOR_ID]:this._handleFutureSalts.bind(this),[M.CONSTRUCTOR_ID]:this._handleStateForgotten.bind(this),[k.CONSTRUCTOR_ID]:this._handleStateForgotten.bind(this),[R.CONSTRUCTOR_ID]:this._handleMsgAll.bind(this)}}async connect(e,t){if(this._user_connected&&!t)return this._log.info("User is already connected!"),!1;this.isConnecting=!0,this._connection=e;for(let e=0;e=10&&this._last_acks.shift(),this._pending_ack.clear()}this._log.debug(`Waiting for messages to send...${this._reconnecting}`);const e=await this._send_queue.get();if(this._reconnecting)return;if(!e)continue;let{data:t}=e;const{batch:n}=e;this._log.debug(`Encrypting ${n.length} message(s) in ${t.length} bytes for sending`),t=await this._state.encryptMessageData(t);try{await this._connection.send(t)}catch(e){return this._log.error(e),void this._log.info("Connection closed while sending data")}for(const e of n)if(Array.isArray(e))for(const t of e)"request"===t.request.classType&&(this._pending_state[t.msgId]=t);else"request"===e.request.classType&&(this._pending_state[e.msgId]=e);this._log.debug("Encrypted messages put in a queue to be sent")}}async _recvLoop(){let e,t;for(;this._user_connected&&!this._reconnecting;){this._log.debug("Receiving items from the network...");try{e=await this._connection.recv()}catch(e){return void(this.userDisconnected||(this._log.error(e),this._log.warn("Connection closed while receiving data"),this.reconnect()))}try{t=await this._state.decryptMessageData(e)}catch(e){if(e instanceof B){this._log.info(`Type ${e.invalidConstructorId} not found, remaining data ${e.remaining}`);continue}if(e instanceof U){this._log.warn(`Security error while unpacking a received message: ${e}`);continue}return e instanceof E?void(404===e.code?(this._log.warn(`Broken authorization key for dc ${this._dcId}; resetting`),this._updateCallback&&this._isMainSender?this._updateCallback(new y(y.broken)):this._onConnectionBreak&&!this._isMainSender&&this._onConnectionBreak(this._dcId)):(this._log.warn(`Invalid buffer ${e.code} for dc ${this._dcId}`),this.reconnect())):(this._log.error("Unhandled error while receiving data"),this._log.error(e),void this.reconnect())}try{await this._processMessage(t)}catch(e){this._log.error("Unhandled error while receiving data"),this._log.error(e)}}}async _processMessage(e){this._pending_ack.add(e.msgId),e.obj=await e.obj;let t=this._handlers[e.obj.CONSTRUCTOR_ID];t||(t=this._handleUpdate.bind(this)),await t(e)}_popStates(e){let t=this._pending_state[e];if(t)return this._pending_state[e].deferred.resolve(),delete this._pending_state[e],[t];const n=[];for(t of Object.values(this._pending_state))t.containerId&&t.containerId.equals(e)&&n.push(t.msgId);if(n.length){const e=[];for(const t of n)e.push(this._pending_state[t]),this._pending_state[t].deferred.resolve(),delete this._pending_state[t];return e}for(const t of this._last_acks)if(t.msgId===e)return[t];return[]}_handleRPCResult(e){const t=e.obj,n=this._pending_state[t.reqMsgId];if(n&&(n.deferred.resolve(),delete this._pending_state[t.reqMsgId]),this._log.debug(`Handling RPC result for message ${t.reqMsgId}`),!n)try{if(!(new _(t.body).tgReadObject()instanceof p.File))throw new B("Not an upload.File")}catch(e){if(this._log.error(e),e instanceof B)return void this._log.info(`Received response without parent request: ${t.body}`);throw e}if(t.error){const e=D(t.error,n.request);this._send_queue.append(new u(new g({msgIds:[n.msgId]}))),n.reject(e)}else try{const e=new _(t.body),s=n.request.readResult(e);n.resolve(s)}catch(e){throw n.reject(e),e}}async _handleContainer(e){this._log.debug("Handling container");for(const t of e.obj.messages)await this._processMessage(t)}async _handleGzipPacked(e){this._log.debug("Handling gzipped data");const t=new _(e.obj.data);e.obj=t.tgReadObject(),await this._processMessage(e)}_handleUpdate(e){2331323052===e.obj.SUBCLASS_OF_ID?(this._log.debug(`Handling update ${e.obj.className}`),this._updateCallback&&this._updateCallback(e.obj)):this._log.warn(`Note: ${e.obj.className} is not an update, not dispatching it`)}_handlePong(e){const t=e.obj,n=this._state.updateTimeOffset(e.msgId);this._updateCallback&&this._updateCallback(new b(n)),this._log.debug(`Handling pong for message ${t.msgId}`);const s=this._pending_state[t.msgId];this._pending_state[t.msgId].deferred.resolve(),delete this._pending_state[t.msgId],s&&s.resolve(t)}_handleBadServerSalt(e){const t=e.obj;this._log.debug(`Handling bad salt for message ${t.badMsgId}`),this._state.salt=t.newServerSalt;const n=this._popStates(t.badMsgId);this._send_queue.extend(n),this._log.debug(`${n.length} message(s) will be resent`)}_handleBadNotification(e){const t=e.obj,n=this._popStates(t.badMsgId);if(this._log.debug(`Handling bad msg ${JSON.stringify(t)}`),[16,17].includes(t.errorCode)){const t=this._state.updateTimeOffset(e.msgId);this._updateCallback&&this._updateCallback(new b(t)),this._log.info(`System clock is wrong, set time offset to ${t}s`)}else if(32===t.errorCode)this._state._sequence+=64;else{if(33!==t.errorCode){for(const e of n)e.reject(new w(e.request,t.errorCode));return}this._state._sequence-=16}this._send_queue.extend(n),this._log.debug(`${n.length} messages will be resent due to bad msg`)}_handleDetailedInfo(e){const t=e.obj.answerMsgId;this._log.debug(`Handling detailed info for message ${t}`),this._pending_ack.add(t)}_handleNewDetailedInfo(e){const t=e.obj.answerMsgId;this._log.debug(`Handling new detailed info for message ${t}`),this._pending_ack.add(t)}_handleNewSessionCreated(e){this._log.debug("Handling new session created"),this._state.salt=e.obj.serverSalt}_handleAck(e){const t=e.obj;this._log.debug(`Handling acknowledge for ${t.msgIds}`);for(const e of t.msgIds){const t=this._pending_state[e];t&&t.request instanceof T&&(this._pending_state[e].deferred.resolve(),delete this._pending_state[e],t.resolve(!0))}}_handleFutureSalts(e){this._log.debug(`Handling future salts for message ${e.msgId}`);const t=this._pending_state[e.msgId];t&&(this._pending_state[e].deferred.resolve(),delete this._pending_state[e],t.resolve(e.obj))}_handleStateForgotten(e){this._send_queue.append(new u(new f(e.msgId,String.fromCharCode(1).repeat(e.obj.msgIds))))}_handleMsgAll(e){}reconnect(){this._user_connected&&!this._reconnecting&&(this._reconnecting=!0,i.sleep(1e3).then((()=>{this._log.info("Started reconnecting"),this._reconnect()})))}async _reconnect(){this._log.debug("Closing current connection...");try{await this._disconnect()}catch(e){this._log.warn(e)}this._send_queue.append(void 0),this._state.reset();const e=new this._connection.constructor(this._connection._ip,this._connection._port,this._connection._dcId,this._connection._log,this._connection._testServers);await this.connect(e,!0),this._reconnecting=!1;for(const e of Object.values(this._pending_state))e.deferred.resolve();this._pending_state={},this._autoReconnectCallback&&await this._autoReconnectCallback()}}var V,N,F;F={logger:void 0,retries:1/0,delay:2e3,autoReconnect:!0,connectTimeout:void 0,authKeyCallback:void 0,updateCallback:void 0,autoReconnectCallback:void 0,isMainSender:void 0,onConnectionBreak:void 0},(N="DEFAULT_OPTIONS")in(V=x)?Object.defineProperty(V,N,{value:F,enumerable:!0,configurable:!0,writable:!0}):V[N]=F,e.exports=x},9109:(e,t,n)=>{var s=n(8764).Buffer;const a=n(4736),i=n(9618),o=n(2608),r=n(5544),c=n(8963),{TLMessage:d}=n(2058),{SecurityError:l,InvalidBufferError:u}=n(8187),{InvokeAfterMsg:g}=n(7404).requests,{toSignedLittleBuffer:p}=n(9618);e.exports=class{constructor(e,t){this.authKey=e,this._log=t,this.timeOffset=0,this.salt=0,this.id=void 0,this._sequence=void 0,this._lastMsgId=void 0,this.reset()}reset(){this.id=i.generateRandomLong(!0),this._sequence=0,this._lastMsgId=a(0)}updateMessageId(e){e.msgId=this._getNewMsgId()}async _calcKey(e,t,n){const a=!0===n?0:8,[o,r]=await Promise.all([i.sha256(s.concat([t,e.slice(a,a+36)])),i.sha256(s.concat([e.slice(a+40,a+76),t]))]);return{key:s.concat([o.slice(0,8),r.slice(8,24),o.slice(24,32)]),iv:s.concat([r.slice(0,8),o.slice(8,24),r.slice(24,32)])}}async writeDataAsMessage(e,t,n,a){const i=this._getNewMsgId(),o=this._getSeqNo(n);let r;r=a?await c.gzipIfSmaller(n,new g(a,{getBytes:()=>t}).getBytes()):await c.gzipIfSmaller(n,t);const d=s.alloc(4);d.writeInt32LE(o,0);const l=s.alloc(4);l.writeInt32LE(r.length,0);const u=p(i,8);return e.write(s.concat([u,d,l])),e.write(r),i}async encryptMessageData(e){await this.authKey.waitForKey();const t=p(this.salt,8),n=p(this.id,8);e=s.concat([s.concat([t,n]),e]);const a=i.generateRandomBytes(i.mod(-(e.length+12),16)+12),r=(await i.sha256(s.concat([this.authKey.getKey().slice(88,120),e,a]))).slice(8,24),{iv:c,key:d}=await this._calcKey(this.authKey.getKey(),r,!0),l=i.readBufferFromBigInt(this.authKey.keyId,8);return s.concat([l,r,new o(d,c).encryptIge(s.concat([e,a]))])}async decryptMessageData(e){if(e.length<8)throw new u(e);if(e.length<0)throw new l("Server replied with negative length");if(e.length%4!=0)throw new l("Server replied with length not divisible by 4");if(i.readBigIntFromBuffer(e.slice(0,8)).neq(this.authKey.keyId))throw new l("Server replied with an invalid auth key");const t=e.slice(8,24),{iv:n,key:a}=await this._calcKey(this.authKey.getKey(),t,!1);e=new o(a,n).decryptIge(e.slice(24));const c=await i.sha256(s.concat([this.authKey.getKey().slice(96,128),e]));if(!t.equals(c.slice(8,24)))throw new l("Received msg_key doesn't match with expected one");const g=new r(e);if(g.readLong(),!g.readLong().eq(this.id))throw new l("Server replied with a wrong session ID");const p=g.readLong(),f=g.readInt(),h=g.readInt(),m=e.length-h;if(m<12||m>1024)throw new l("Server replied with the wrong message padding");const _=g.tgReadObject();return new d(p,f,_)}_getNewMsgId(){const e=(new Date).getTime()/1e3+this.timeOffset,t=Math.floor(1e9*(e-Math.floor(e)));let n=a(Math.floor(e)).shiftLeft(a(32)).or(a(t).shiftLeft(a(2)));return this._lastMsgId.greaterOrEquals(n)&&(n=this._lastMsgId.add(a(4))),this._lastMsgId=n,n}updateTimeOffset(e){const t=this._getNewMsgId(),n=this.timeOffset,s=Math.floor((new Date).getTime()/1e3),i=e.shiftRight(a(32));return this.timeOffset=i-s,this.timeOffset!==n&&(this._lastMsgId=a(0),this._log.debug(`Updated time offset (old offset ${n}, bad ${t}, good ${e}, new ${this.timeOffset})`)),this.timeOffset}_getSeqNo(e){if(e){const e=2*this._sequence+1;return this._sequence+=1,e}return 2*this._sequence}}},4287:(e,t,n)=>{const{createDeferred:s}=n(9618);e.exports=class{constructor(e,t,n={}){this.containerId=void 0,this.msgId=void 0,this.request=e,this.data=e.getBytes(),this.after=t,this.result=void 0,this.pending=n,this.deferred=s(),this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}isReady(){const e=this.pending[this.after.id];return!e||e.deferred.promise}}},4353:(e,t,n)=>{function s(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const a=n(7214),i=n(6151);class o{constructor(e,t,n,o,r){s(this,"PacketCodecClass",void 0),this._ip=e,this._port=t,this._dcId=n,this._log=o,this._testServers=r,this._connected=!1,this._sendTask=void 0,this._recvTask=void 0,this._codec=void 0,this._obfuscation=void 0,this._sendArray=new i,this._recvArray=new i,this.socket=new a(this.disconnectCallback.bind(this))}async disconnectCallback(){await this.disconnect(!0)}async _connect(){this._log.debug("Connecting"),this._codec=new this.PacketCodecClass(this),await this.socket.connect(this._port,this._ip,this._testServers),this._log.debug("Finished connecting"),await this._initConn()}async connect(){await this._connect(),this._connected=!0,this._sendTask||(this._sendTask=this._sendLoop()),this._recvTask=this._recvLoop()}async disconnect(e=!1){this._connected&&(this._connected=!1,this._recvArray.push(void 0),e||await this.socket.close())}async send(e){if(!this._connected)throw new Error("Not connected");await this._sendArray.push(e)}async recv(){for(;this._connected;){const e=await this._recvArray.pop();if(e)return e}throw new Error("Not connected")}async _sendLoop(){try{for(;this._connected;){const e=await this._sendArray.pop();if(!e)return void(this._sendTask=void 0);await this._send(e)}}catch(e){this._log.info("The server closed the connection while sending")}}async _recvLoop(){let e;for(;this._connected;){try{if(e=await this._recv(),!e)throw new Error("no data received")}catch(e){return this._log.info("connection closed"),void this.disconnect()}await this._recvArray.push(e)}}async _initConn(){this._codec.tag&&await this.socket.write(this._codec.tag)}_send(e){const t=this._codec.encodePacket(e);this.socket.write(t)}_recv(){return this._codec.readPacket(this.socket)}toString(){return`${this._ip}:${this._port}/${this.constructor.name.replace("Connection","")}`}}e.exports={Connection:o,PacketCodec:class{constructor(e){this._conn=e}encodePacket(e){throw new Error("Not Implemented")}readPacket(e){throw new Error("Not Implemented")}},ObfuscatedConnection:class extends o{constructor(...e){super(...e),s(this,"ObfuscatedIO",void 0)}_initConn(){this._obfuscation=new this.ObfuscatedIO(this),this.socket.write(this._obfuscation.header)}_send(e){this._obfuscation.write(this._codec.encodePacket(e))}_recv(){return this._codec.readPacket(this._obfuscation)}}}},6302:(e,t,n)=>{var s=n(8764).Buffer;function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const i=n(4736),{readBufferFromBigInt:o}=n(9618),{Connection:r,PacketCodec:c}=n(4353);class d extends c{constructor(e){super(e),this.tag=d.tag,this.obfuscateTag=d.obfuscateTag}encodePacket(e){let t=e.length>>2;if(t<127){const e=s.alloc(1);e.writeUInt8(t,0),t=e}else t=s.concat([s.from("7f","hex"),o(i(t),3)]);return s.concat([t,e])}async readPacket(e){let t=(await e.read(1))[0];return t>=127&&(t=s.concat([await e.read(3),s.alloc(1)]).readInt32LE(0)),e.read(t<<2)}}a(d,"tag",s.from("ef","hex")),a(d,"obfuscateTag",s.from("efefefef","hex")),e.exports={ConnectionTCPAbridged:class extends r{constructor(...e){super(...e),a(this,"PacketCodecClass",d)}},AbridgedPacketCodec:d}},5484:()=>{},2986:(e,t,n)=>{var s=n(8764).Buffer;function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const{generateRandomBytes:i}=n(9618),{ObfuscatedConnection:o}=n(4353),{AbridgedPacketCodec:r}=n(6302),c=n(5830);class d{constructor(e){a(this,"header",void 0),this.connection=e.socket;const t=this.initHeader(e.PacketCodecClass);this.header=t.random,this._encrypt=t.encryptor,this._decrypt=t.decryptor}initHeader(e){const t=[s.from("50567247","hex"),s.from("474554","hex"),s.from("504f5354","hex"),s.from("eeeeeeee","hex")];let n;for(;;)if(n=i(64),239!==n[0]&&!n.slice(4,8).equals(s.alloc(4))){let e=!0;for(const s of t)if(s.equals(n.slice(0,4))){e=!1;break}if(e)break}n=n.toJSON().data;const a=s.from(n.slice(8,56)).reverse(),o=s.from(n.slice(8,40)),r=s.from(n.slice(40,56)),d=s.from(a.slice(0,32)),l=s.from(a.slice(32,48)),u=new c(o,r),g=new c(d,l);return n=s.concat([s.from(n.slice(0,56)),e.obfuscateTag,s.from(n.slice(60))]),n=s.concat([s.from(n.slice(0,56)),s.from(u.encrypt(n).slice(56,64)),s.from(n.slice(64))]),{random:n,encryptor:u,decryptor:g}}async read(e){const t=await this.connection.readExactly(e);return this._decrypt.encrypt(t)}write(e){this.connection.write(this._encrypt.encrypt(e))}}e.exports={ConnectionTCPObfuscated:class extends o{constructor(...e){super(...e),a(this,"ObfuscatedIO",d),a(this,"PacketCodecClass",r)}}}},417:(e,t,n)=>{const{Connection:s}=n(4353),{ConnectionTCPFull:a}=n(5484),{ConnectionTCPAbridged:i}=n(6302),{ConnectionTCPObfuscated:o}=n(2986);e.exports={Connection:s,ConnectionTCPFull:a,ConnectionTCPAbridged:i,ConnectionTCPObfuscated:o}},8415:(e,t,n)=>{function s(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const a=n(5585),i=n(4046);class o{constructor(e){this.state=e}}s(o,"disconnected",-1),s(o,"connected",1),s(o,"broken",0);const{Connection:r,ConnectionTCPFull:c,ConnectionTCPAbridged:d,ConnectionTCPObfuscated:l}=n(417);e.exports={Connection:r,ConnectionTCPFull:c,ConnectionTCPAbridged:d,ConnectionTCPObfuscated:l,MTProtoPlainSender:a,MTProtoSender:i,UpdateConnectionState:o,UpdateServerTimeOffset:class{constructor(e){this.timeOffset=e}}}},9270:e=>{e.exports=class{get dcId(){throw new Error("Not Implemented")}get serverAddress(){throw new Error("Not Implemented")}get port(){throw new Error("Not Implemented")}get authKey(){throw new Error("Not Implemented")}set authKey(e){throw new Error("Not Implemented")}setDC(e,t,n){throw new Error("Not implemented")}save(){throw new Error("Not Implemented")}delete(){throw new Error("Not Implemented")}}},926:(e,t,n)=>{const s=n(8753),a="GramJs";e.exports=class extends s{async _delete(){const e=new Request(this._storageKey);return(await self.caches.open(a)).delete(e)}async _fetchFromCache(){const e=new Request(this._storageKey),t=await self.caches.open(a),n=await t.match(e);return n?n.text():void 0}async _saveToCache(e){const t=new Request(this._storageKey),n=new Response(e);return(await self.caches.open(a)).put(t,n)}}},7:(e,t,n)=>{var s=n(8764).Buffer;const a=n(3995),i=n(3302),o=n(8960);e.exports=class extends a{constructor(e,t){super(),this._sessionData=e,this._callback=t,this._authKeys={}}get authKey(){throw new Error("Not supported")}set authKey(e){throw new Error("Not supported")}async load(){if(!this._sessionData)return;const{mainDcId:e,keys:t,hashes:n}=this._sessionData,{ipAddress:a,port:r}=o.getDC(e);this.setDC(e,a,r,!0),await Promise.all(Object.keys(t).map((async e=>{const a="string"==typeof t[e]?s.from(t[e],"hex"):s.from(t[e]);if(n[e]){const t="string"==typeof n[e]?s.from(n[e],"hex"):s.from(n[e]);this._authKeys[e]=new i(a,t)}else this._authKeys[e]=new i,await this._authKeys[e].setKey(a,!0)})))}setDC(e,t,n,s=!1){this._dcId=e,this._serverAddress=t,this._port=n,delete this._authKeys[e],s||this._onUpdate()}getAuthKey(e=this._dcId){return this._authKeys[e]}setAuthKey(e,t=this._dcId){this._authKeys[t]=e,this._onUpdate()}getSessionData(){const e={mainDcId:this._dcId,keys:{},hashes:{}};return Object.keys(this._authKeys).forEach((t=>{const n=this._authKeys[t];n&&n._key&&(e.keys[t]=n._key.toString("hex"),e.hashes[t]=n._hash.toString("hex"))})),e}_onUpdate(){this._callback(this.getSessionData())}delete(){this._callback(void 0)}}},5945:(e,t,n)=>{const s=n(1875),a=n(8753);e.exports=class extends a{_delete(){return s.del(`GramJs:${this._storageKey}`)}_fetchFromCache(){return s.get(`GramJs:${this._storageKey}`)}_saveToCache(e){return s.set(`GramJs:${this._storageKey}`,e)}}},1753:(e,t,n)=>{const s=n(8753);e.exports=class extends s{_delete(){return localStorage.removeItem(this._storageKey)}_fetchFromCache(){return localStorage.getItem(this._storageKey)}_saveToCache(e){return localStorage.setItem(this._storageKey,e)}}},3995:(e,t,n)=>{const s=n(9270);e.exports=class extends s{constructor(){super(),this._serverAddress=void 0,this._dcId=0,this._port=void 0,this._takeoutId=void 0,this._entities=new Set,this._updateStates={}}get dcId(){return this._dcId}get serverAddress(){return this._serverAddress}get port(){return this._port}get authKey(){return this._authKey}set authKey(e){this._authKey=e}setDC(e,t,n){this._dcId=0|e,this._serverAddress=t,this._port=n}}},8753:(e,t,n)=>{var s=n(8764).Buffer;const a=n(3995),i=n(3302),o=n(8960);e.exports=class extends a{constructor(e){super(),this._authKeys={},e&&e.startsWith("session:")?this._sessionString=e:e&&(this._storageKey=e)}get authKey(){throw new Error("Not supported")}set authKey(e){throw new Error("Not supported")}async load(){if(this._sessionString)await this._loadFromSessionString();else if(this._storageKey)try{const e=await this._fetchFromCache(),{mainDcId:t,keys:n,hashes:a}=JSON.parse(e),{ipAddress:r,port:c}=o.getDC(t);this.setDC(t,r,c,!0),Object.keys(n).forEach((e=>{n[e]&&a[e]&&(this._authKeys[e]=new i(s.from(n[e].data),s.from(a[e].data)))}))}catch(e){console.warn("Failed to retrieve or parse session from storage"),console.warn(e)}}setDC(e,t,n,s=!1){this._dcId=e,this._serverAddress=t,this._port=n,delete this._authKeys[e],s||this._updateStorage()}async save(){return this._storageKey||(this._storageKey=`GramJs-session-${Date.now()}`),await this._updateStorage(),this._storageKey}getAuthKey(e=this._dcId){return this._authKeys[e]}setAuthKey(e,t=this._dcId){this._authKeys[t]=e,this._updateStorage()}getSessionData(e){const t={mainDcId:this._dcId,keys:{},hashes:{}};return Object.keys(this._authKeys).forEach((n=>{const s=this._authKeys[n];s._key&&(t.keys[n]=e?s._key.toString("hex"):s._key,t.hashes[n]=e?s._hash.toString("hex"):s._hash)})),t}async _loadFromSessionString(){const[,e,t]=this._sessionString.split(":"),n=Number(e),{ipAddress:a,port:r}=o.getDC(n);this.setDC(n,a,r);const c=new i;await c.setKey(s.from(t,"hex"),!0),this.setAuthKey(c,n)}async _updateStorage(){if(this._storageKey)try{await this._saveToCache(JSON.stringify(this.getSessionData()))}catch(e){console.warn("Failed to update session in storage"),console.warn(e)}}async delete(){try{return await this._delete()}catch(e){console.warn("Failed to delete session from storage"),console.warn(e)}}_delete(){throw new Error("Not Implemented")}_fetchFromCache(){throw new Error("Not Implemented")}_saveToCache(e){throw new Error("Not Implemented")}}},2433:(e,t,n)=>{var s=n(8764).Buffer;const a=n(3995),i=n(3302),o=n(5544);class r extends a{constructor(e){if(super(),e){if("1"!==e[0])throw new Error("Not a valid string");e=e.slice(1);const t=r.decode(e),n=new o(t);this._dcId=n.read(1).readUInt8(0);const s=n.read(2).readInt16BE(0);this._serverAddress=String(n.read(s)),this._port=n.read(2).readInt16BE(0),this._key=n.read(-1)}}static encode(e){return e.toString("base64")}static decode(e){return s.from(e,"base64")}async load(){this._key&&(this._authKey=new i,await this._authKey.setKey(this._key))}save(){if(!this.authKey)return"";const e=s.from([this.dcId]),t=s.from(this.serverAddress),n=s.alloc(2);n.writeInt16BE(t.length,0);const a=s.alloc(2);return a.writeInt16BE(this.port,0),"1"+r.encode(s.concat([e,n,t,a,this.authKey.getKey()]))}getAuthKey(e){if(!e||e===this.dcId)return this.authKey}setAuthKey(e,t){t&&t!==this.dcId||(this.authKey=e)}}e.exports=r},5886:(e,t,n)=>{const s=n(3995),a=n(2433),i=n(926),o=n(1753),r=n(5945),c=n(7);e.exports={Memory:s,StringSession:a,CacheApiSession:i,LocalStorageSession:o,IdbSession:r,CallbackSession:c}},845:(e,t,n)=>{const s=n(7150),a={};for(const e of Object.values(s))if(e.CONSTRUCTOR_ID)a[e.CONSTRUCTOR_ID]=e;else for(const t of Object.values(e))a[t.CONSTRUCTOR_ID]=t;e.exports={LAYER:133,tlobjects:a}},7150:(e,t,n)=>{var s=n(8764).Buffer;function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const{parseTl:i,serializeBytes:o,serializeDate:r}=n(1436),{toSignedLittleBuffer:c}=n(9618),d=n(4779),l=n(8106),u="undefined"!=typeof self&&void 0!==self.localStorage,g="GramJs:apiCache";function p(e){const t=i(e,109),n=[],s=[];for(const e of t)e.isFunction?s.push(e):n.push(e);return[n,s]}function f(e,t){switch(t){case"int":{const t=s.alloc(4);return t.writeInt32LE(e,0),t}case"long":return c(e,8);case"int128":return c(e,16);case"int256":return c(e,32);case"double":{const t=s.alloc(8);return t.writeDoubleLE(e,0),t}case"string":return o(e);case"Bool":return e?s.from("b5757299","hex"):s.from("379779bc","hex");case"true":return s.alloc(0);case"bytes":return o(e);case"date":return r(e);default:return e.getBytes()}}function h(e,t){if(t.isVector){t.useVectorId&&e.readInt();const n=[],s=e.readInt();t.isVector=!1;for(let a=0;a{this[e]=t[e]}))}static fromReader(e){const t={};for(const n in c)if(c.hasOwnProperty(n)){const s=c[n];if(s.isFlag){if("true"===s.type){t[n]=Boolean(t.flags&1<f(t,c[e].type)))))}else if(c[e].flagIndicator)if(Object.values(c).some((e=>e.isFlag))){let e=0;for(const t in c)c[t].isFlag&&(!1===this[t]&&"true"===c[t].type||void 0===this[t]?e|=0:e|=1</);if(n){t.readInt();const e=[],s=t.readInt();if("int"===n[1])for(let n=0;n{"function"!=typeof t[e]&&n[e]?Object.assign(n[e],t[e]):n[e]=t[e]})),n}(m("constructor",e.constructors),m("request",e.requests))}()},4779:e=>{e.exports="boolFalse#bc799737 = Bool;\nboolTrue#997275b5 = Bool;\ntrue#3fedd339 = True;\nvector#1cb5c415 {t:Type} # [ t ] = Vector t;\nerror#c4b9f9bb code:int text:string = Error;\nnull#56730bcc = Null;\ninputPeerEmpty#7f3b18ea = InputPeer;\ninputPeerSelf#7da07ec9 = InputPeer;\ninputPeerChat#35a95cb9 chat_id:long = InputPeer;\ninputPeerUser#dde8a54c user_id:long access_hash:long = InputPeer;\ninputPeerChannel#27bcbbfc channel_id:long access_hash:long = InputPeer;\ninputPeerUserFromMessage#a87b0a1c peer:InputPeer msg_id:int user_id:long = InputPeer;\ninputPeerChannelFromMessage#bd2a0840 peer:InputPeer msg_id:int channel_id:long = InputPeer;\ninputUserEmpty#b98886cf = InputUser;\ninputUserSelf#f7c1b13f = InputUser;\ninputUser#f21158c6 user_id:long access_hash:long = InputUser;\ninputUserFromMessage#1da448e2 peer:InputPeer msg_id:int user_id:long = InputUser;\ninputPhoneContact#f392b7f4 client_id:long phone:string first_name:string last_name:string = InputContact;\ninputFile#f52ff27f id:long parts:int name:string md5_checksum:string = InputFile;\ninputFileBig#fa4f0bb5 id:long parts:int name:string = InputFile;\ninputMediaEmpty#9664f57f = InputMedia;\ninputMediaUploadedPhoto#1e287d04 flags:# file:InputFile stickers:flags.0?Vector ttl_seconds:flags.1?int = InputMedia;\ninputMediaPhoto#b3ba0635 flags:# id:InputPhoto ttl_seconds:flags.0?int = InputMedia;\ninputMediaGeoPoint#f9c44144 geo_point:InputGeoPoint = InputMedia;\ninputMediaContact#f8ab7dfb phone_number:string first_name:string last_name:string vcard:string = InputMedia;\ninputMediaUploadedDocument#5b38c6c1 flags:# nosound_video:flags.3?true force_file:flags.4?true file:InputFile thumb:flags.2?InputFile mime_type:string attributes:Vector stickers:flags.0?Vector ttl_seconds:flags.1?int = InputMedia;\ninputMediaDocument#33473058 flags:# id:InputDocument ttl_seconds:flags.0?int query:flags.1?string = InputMedia;\ninputMediaVenue#c13d1c11 geo_point:InputGeoPoint title:string address:string provider:string venue_id:string venue_type:string = InputMedia;\ninputMediaPhotoExternal#e5bbfe1a flags:# url:string ttl_seconds:flags.0?int = InputMedia;\ninputMediaDocumentExternal#fb52dc99 flags:# url:string ttl_seconds:flags.0?int = InputMedia;\ninputMediaGame#d33f43f3 id:InputGame = InputMedia;\ninputMediaInvoice#d9799874 flags:# title:string description:string photo:flags.0?InputWebDocument invoice:Invoice payload:bytes provider:string provider_data:DataJSON start_param:flags.1?string = InputMedia;\ninputMediaGeoLive#971fa843 flags:# stopped:flags.0?true geo_point:InputGeoPoint heading:flags.2?int period:flags.1?int proximity_notification_radius:flags.3?int = InputMedia;\ninputMediaPoll#f94e5f1 flags:# poll:Poll correct_answers:flags.0?Vector solution:flags.1?string solution_entities:flags.1?Vector = InputMedia;\ninputMediaDice#e66fbf7b emoticon:string = InputMedia;\ninputChatPhotoEmpty#1ca48f57 = InputChatPhoto;\ninputChatUploadedPhoto#c642724e flags:# file:flags.0?InputFile video:flags.1?InputFile video_start_ts:flags.2?double = InputChatPhoto;\ninputChatPhoto#8953ad37 id:InputPhoto = InputChatPhoto;\ninputGeoPointEmpty#e4c123d6 = InputGeoPoint;\ninputGeoPoint#48222faf flags:# lat:double long:double accuracy_radius:flags.0?int = InputGeoPoint;\ninputPhotoEmpty#1cd7bf0d = InputPhoto;\ninputPhoto#3bb3b94a id:long access_hash:long file_reference:bytes = InputPhoto;\ninputFileLocation#dfdaabe1 volume_id:long local_id:int secret:long file_reference:bytes = InputFileLocation;\ninputEncryptedFileLocation#f5235d55 id:long access_hash:long = InputFileLocation;\ninputDocumentFileLocation#bad07584 id:long access_hash:long file_reference:bytes thumb_size:string = InputFileLocation;\ninputSecureFileLocation#cbc7ee28 id:long access_hash:long = InputFileLocation;\ninputTakeoutFileLocation#29be5899 = InputFileLocation;\ninputPhotoFileLocation#40181ffe id:long access_hash:long file_reference:bytes thumb_size:string = InputFileLocation;\ninputPhotoLegacyFileLocation#d83466f3 id:long access_hash:long file_reference:bytes volume_id:long local_id:int secret:long = InputFileLocation;\ninputPeerPhotoFileLocation#37257e99 flags:# big:flags.0?true peer:InputPeer photo_id:long = InputFileLocation;\ninputStickerSetThumb#9d84f3db stickerset:InputStickerSet thumb_version:int = InputFileLocation;\ninputGroupCallStream#598a92a flags:# call:InputGroupCall time_ms:long scale:int video_channel:flags.0?int video_quality:flags.0?int = InputFileLocation;\npeerUser#59511722 user_id:long = Peer;\npeerChat#36c6019a chat_id:long = Peer;\npeerChannel#a2a5371e channel_id:long = Peer;\nstorage.fileUnknown#aa963b05 = storage.FileType;\nstorage.filePartial#40bc6f52 = storage.FileType;\nstorage.fileJpeg#7efe0e = storage.FileType;\nstorage.fileGif#cae1aadf = storage.FileType;\nstorage.filePng#a4f63c0 = storage.FileType;\nstorage.filePdf#ae1e508d = storage.FileType;\nstorage.fileMp3#528a0677 = storage.FileType;\nstorage.fileMov#4b09ebbc = storage.FileType;\nstorage.fileMp4#b3cea0e4 = storage.FileType;\nstorage.fileWebp#1081464c = storage.FileType;\nuserEmpty#d3bc4b7a id:long = User;\nuser#3ff6ecb0 flags:# self:flags.10?true contact:flags.11?true mutual_contact:flags.12?true deleted:flags.13?true bot:flags.14?true bot_chat_history:flags.15?true bot_nochats:flags.16?true verified:flags.17?true restricted:flags.18?true min:flags.20?true bot_inline_geo:flags.21?true support:flags.23?true scam:flags.24?true apply_min_photo:flags.25?true fake:flags.26?true id:long access_hash:flags.0?long first_name:flags.1?string last_name:flags.2?string username:flags.3?string phone:flags.4?string photo:flags.5?UserProfilePhoto status:flags.6?UserStatus bot_info_version:flags.14?int restriction_reason:flags.18?Vector bot_inline_placeholder:flags.19?string lang_code:flags.22?string = User;\nuserProfilePhotoEmpty#4f11bae1 = UserProfilePhoto;\nuserProfilePhoto#82d1f706 flags:# has_video:flags.0?true photo_id:long stripped_thumb:flags.1?bytes dc_id:int = UserProfilePhoto;\nuserStatusEmpty#9d05049 = UserStatus;\nuserStatusOnline#edb93949 expires:int = UserStatus;\nuserStatusOffline#8c703f was_online:int = UserStatus;\nuserStatusRecently#e26f42f1 = UserStatus;\nuserStatusLastWeek#7bf09fc = UserStatus;\nuserStatusLastMonth#77ebc742 = UserStatus;\nchatEmpty#29562865 id:long = Chat;\nchat#41cbf256 flags:# creator:flags.0?true kicked:flags.1?true left:flags.2?true deactivated:flags.5?true call_active:flags.23?true call_not_empty:flags.24?true 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 id:long access_hash:flags.13?long title:string username:flags.6?string photo:ChatPhoto date:int restriction_reason:flags.9?Vector admin_rights:flags.14?ChatAdminRights banned_rights:flags.15?ChatBannedRights default_banned_rights:flags.18?ChatBannedRights participants_count:flags.17?int = Chat;\nchannelForbidden#17d493d5 flags:# broadcast:flags.5?true megagroup:flags.8?true id:long access_hash:long title:string until_date:flags.16?int = Chat;\nchatFull#4dbdc099 flags:# can_set_username:flags.7?true has_scheduled:flags.8?true id:long about:string participants:ChatParticipants chat_photo:flags.2?Photo notify_settings:PeerNotifySettings exported_invite:flags.13?ExportedChatInvite bot_info:flags.3?Vector pinned_msg_id:flags.6?int folder_id:flags.11?int call:flags.12?InputGroupCall ttl_period:flags.14?int groupcall_default_join_as:flags.15?Peer theme_emoticon:flags.16?string = ChatFull;\nchannelFull#e9b27a17 flags:# can_view_participants:flags.3?true can_set_username:flags.6?true can_set_stickers:flags.7?true hidden_prehistory:flags.10?true can_set_location:flags.16?true has_scheduled:flags.19?true can_view_stats:flags.20?true blocked:flags.22?true id:long about:string participants_count:flags.0?int admins_count:flags.1?int kicked_count:flags.2?int banned_count:flags.2?int online_count:flags.13?int read_inbox_max_id:int read_outbox_max_id:int unread_count:int chat_photo:Photo notify_settings:PeerNotifySettings exported_invite:flags.23?ExportedChatInvite bot_info:Vector migrated_from_chat_id:flags.4?long migrated_from_max_id:flags.4?int pinned_msg_id:flags.5?int stickerset:flags.8?StickerSet available_min_id:flags.9?int folder_id:flags.11?int linked_chat_id:flags.14?long location:flags.15?ChannelLocation slowmode_seconds:flags.17?int slowmode_next_send_date:flags.18?int stats_dc:flags.12?int pts:int call:flags.21?InputGroupCall ttl_period:flags.24?int pending_suggestions:flags.25?Vector groupcall_default_join_as:flags.26?Peer theme_emoticon:flags.27?string = ChatFull;\nchatParticipant#c02d4007 user_id:long inviter_id:long date:int = ChatParticipant;\nchatParticipantCreator#e46bcee4 user_id:long = ChatParticipant;\nchatParticipantAdmin#a0933f5b user_id:long inviter_id:long date:int = ChatParticipant;\nchatParticipantsForbidden#8763d3e1 flags:# chat_id:long self_participant:flags.0?ChatParticipant = ChatParticipants;\nchatParticipants#3cbc93f8 chat_id:long participants:Vector version:int = ChatParticipants;\nchatPhotoEmpty#37c1011c = ChatPhoto;\nchatPhoto#1c6e1c11 flags:# has_video:flags.0?true photo_id:long stripped_thumb:flags.1?bytes dc_id:int = ChatPhoto;\nmessageEmpty#90a6ca84 flags:# id:int peer_id:flags.0?Peer = Message;\nmessage#85d6cbe2 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true post:flags.14?true from_scheduled:flags.18?true legacy:flags.19?true edit_hide:flags.21?true pinned:flags.24?true id:int from_id:flags.8?Peer peer_id:Peer fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?long reply_to:flags.3?MessageReplyHeader date:int message:string media:flags.9?MessageMedia reply_markup:flags.6?ReplyMarkup entities:flags.7?Vector views:flags.10?int forwards:flags.10?int replies:flags.23?MessageReplies edit_date:flags.15?int post_author:flags.16?string grouped_id:flags.17?long restriction_reason:flags.22?Vector ttl_period:flags.25?int = Message;\nmessageService#2b085862 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true post:flags.14?true legacy:flags.19?true id:int from_id:flags.8?Peer peer_id:Peer reply_to:flags.3?MessageReplyHeader date:int action:MessageAction ttl_period:flags.25?int = Message;\nmessageMediaEmpty#3ded6320 = MessageMedia;\nmessageMediaPhoto#695150d7 flags:# photo:flags.0?Photo ttl_seconds:flags.2?int = MessageMedia;\nmessageMediaGeo#56e0d474 geo:GeoPoint = MessageMedia;\nmessageMediaContact#70322949 phone_number:string first_name:string last_name:string vcard:string user_id:long = MessageMedia;\nmessageMediaUnsupported#9f84f49e = MessageMedia;\nmessageMediaDocument#9cb070d7 flags:# document:flags.0?Document ttl_seconds:flags.2?int = MessageMedia;\nmessageMediaWebPage#a32dd600 webpage:WebPage = MessageMedia;\nmessageMediaVenue#2ec0533f geo:GeoPoint title:string address:string provider:string venue_id:string venue_type:string = MessageMedia;\nmessageMediaGame#fdb19008 game:Game = MessageMedia;\nmessageMediaInvoice#84551347 flags:# shipping_address_requested:flags.1?true test:flags.3?true title:string description:string photo:flags.0?WebDocument receipt_msg_id:flags.2?int currency:string total_amount:long start_param:string = MessageMedia;\nmessageMediaGeoLive#b940c666 flags:# geo:GeoPoint heading:flags.0?int period:int proximity_notification_radius:flags.1?int = MessageMedia;\nmessageMediaPoll#4bd6e798 poll:Poll results:PollResults = MessageMedia;\nmessageMediaDice#3f7ee58b value:int emoticon:string = MessageMedia;\nmessageActionEmpty#b6aef7b0 = MessageAction;\nmessageActionChatCreate#bd47cbad title:string users:Vector = MessageAction;\nmessageActionChatEditTitle#b5a1ce5a title:string = MessageAction;\nmessageActionChatEditPhoto#7fcb13a8 photo:Photo = MessageAction;\nmessageActionChatDeletePhoto#95e3fbef = MessageAction;\nmessageActionChatAddUser#15cefd00 users:Vector = MessageAction;\nmessageActionChatDeleteUser#a43f30cc user_id:long = MessageAction;\nmessageActionChatJoinedByLink#31224c3 inviter_id:long = MessageAction;\nmessageActionChannelCreate#95d2ac92 title:string = MessageAction;\nmessageActionChatMigrateTo#e1037f92 channel_id:long = MessageAction;\nmessageActionChannelMigrateFrom#ea3948e9 title:string chat_id:long = MessageAction;\nmessageActionPinMessage#94bd38ed = MessageAction;\nmessageActionHistoryClear#9fbab604 = MessageAction;\nmessageActionGameScore#92a72876 game_id:long score:int = MessageAction;\nmessageActionPaymentSentMe#8f31b327 flags:# currency:string total_amount:long payload:bytes info:flags.0?PaymentRequestedInfo shipping_option_id:flags.1?string charge:PaymentCharge = MessageAction;\nmessageActionPaymentSent#40699cd0 currency:string total_amount:long = MessageAction;\nmessageActionPhoneCall#80e11a7f flags:# video:flags.2?true call_id:long reason:flags.0?PhoneCallDiscardReason duration:flags.1?int = MessageAction;\nmessageActionScreenshotTaken#4792929b = MessageAction;\nmessageActionCustomAction#fae69f56 message:string = MessageAction;\nmessageActionBotAllowed#abe9affe domain:string = MessageAction;\nmessageActionSecureValuesSentMe#1b287353 values:Vector credentials:SecureCredentialsEncrypted = MessageAction;\nmessageActionSecureValuesSent#d95c6154 types:Vector = MessageAction;\nmessageActionContactSignUp#f3f25f76 = MessageAction;\nmessageActionGeoProximityReached#98e0d697 from_id:Peer to_id:Peer distance:int = MessageAction;\nmessageActionGroupCall#7a0d7f42 flags:# call:InputGroupCall duration:flags.0?int = MessageAction;\nmessageActionInviteToGroupCall#502f92f7 call:InputGroupCall users:Vector = MessageAction;\nmessageActionSetMessagesTTL#aa1afbfd period:int = MessageAction;\nmessageActionGroupCallScheduled#b3a07661 call:InputGroupCall schedule_date:int = MessageAction;\nmessageActionSetChatTheme#aa786345 emoticon:string = MessageAction;\ndialog#2c171f72 flags:# pinned:flags.2?true unread_mark:flags.3?true peer:Peer top_message:int read_inbox_max_id:int read_outbox_max_id:int unread_count:int unread_mentions_count:int notify_settings:PeerNotifySettings pts:flags.0?int draft:flags.1?DraftMessage folder_id:flags.4?int = Dialog;\ndialogFolder#71bd134c flags:# pinned:flags.2?true folder:Folder peer:Peer top_message:int unread_muted_peers_count:int unread_unmuted_peers_count:int unread_muted_messages_count:int unread_unmuted_messages_count:int = Dialog;\nphotoEmpty#2331b22d id:long = Photo;\nphoto#fb197a65 flags:# has_stickers:flags.0?true id:long access_hash:long file_reference:bytes date:int sizes:Vector video_sizes:flags.1?Vector dc_id:int = Photo;\nphotoSizeEmpty#e17e23c type:string = PhotoSize;\nphotoSize#75c78e60 type:string w:int h:int size:int = PhotoSize;\nphotoCachedSize#21e1ad6 type:string w:int h:int bytes:bytes = PhotoSize;\nphotoStrippedSize#e0b0bc2e type:string bytes:bytes = PhotoSize;\nphotoSizeProgressive#fa3efb95 type:string w:int h:int sizes:Vector = PhotoSize;\nphotoPathSize#d8214d41 type:string bytes:bytes = PhotoSize;\ngeoPointEmpty#1117dd5f = GeoPoint;\ngeoPoint#b2a2f663 flags:# long:double lat:double access_hash:long accuracy_radius:flags.0?int = GeoPoint;\nauth.sentCode#5e002502 flags:# type:auth.SentCodeType phone_code_hash:string next_type:flags.1?auth.CodeType timeout:flags.2?int = auth.SentCode;\nauth.authorization#cd050916 flags:# tmp_sessions:flags.0?int user:User = auth.Authorization;\nauth.authorizationSignUpRequired#44747e9a flags:# terms_of_service:flags.0?help.TermsOfService = auth.Authorization;\nauth.exportedAuthorization#b434e2b8 id:long bytes:bytes = auth.ExportedAuthorization;\ninputNotifyPeer#b8bc5b0c peer:InputPeer = InputNotifyPeer;\ninputNotifyUsers#193b4417 = InputNotifyPeer;\ninputNotifyChats#4a95e84e = InputNotifyPeer;\ninputNotifyBroadcasts#b1db7c7e = InputNotifyPeer;\ninputPeerNotifySettings#9c3d198e flags:# show_previews:flags.0?Bool silent:flags.1?Bool mute_until:flags.2?int sound:flags.3?string = InputPeerNotifySettings;\npeerNotifySettings#af509d20 flags:# show_previews:flags.0?Bool silent:flags.1?Bool mute_until:flags.2?int sound:flags.3?string = PeerNotifySettings;\npeerSettings#733f2961 flags:# report_spam:flags.0?true add_contact:flags.1?true block_contact:flags.2?true share_contact:flags.3?true need_contacts_exception:flags.4?true report_geo:flags.5?true autoarchived:flags.7?true invite_members:flags.8?true geo_distance:flags.6?int = PeerSettings;\nwallPaper#a437c3ed id:long flags:# creator:flags.0?true default:flags.1?true pattern:flags.3?true dark:flags.4?true access_hash:long slug:string document:Document settings:flags.2?WallPaperSettings = WallPaper;\nwallPaperNoFile#e0804116 id:long flags:# default:flags.1?true dark:flags.4?true settings:flags.2?WallPaperSettings = WallPaper;\ninputReportReasonSpam#58dbcab8 = ReportReason;\ninputReportReasonViolence#1e22c78d = ReportReason;\ninputReportReasonPornography#2e59d922 = ReportReason;\ninputReportReasonChildAbuse#adf44ee3 = ReportReason;\ninputReportReasonOther#c1e4a2b1 = ReportReason;\ninputReportReasonCopyright#9b89f93a = ReportReason;\ninputReportReasonGeoIrrelevant#dbd4feed = ReportReason;\ninputReportReasonFake#f5ddd6e7 = ReportReason;\nuserFull#d697ff05 flags:# blocked:flags.0?true phone_calls_available:flags.4?true phone_calls_private:flags.5?true can_pin_message:flags.7?true has_scheduled:flags.12?true video_calls_available:flags.13?true user:User about:flags.1?string settings:PeerSettings profile_photo:flags.2?Photo notify_settings:PeerNotifySettings bot_info:flags.3?BotInfo pinned_msg_id:flags.6?int common_chats_count:int folder_id:flags.11?int ttl_period:flags.14?int theme_emoticon:flags.15?string = UserFull;\ncontact#145ade0b user_id:long mutual:Bool = Contact;\nimportedContact#c13e3c50 user_id:long client_id:long = ImportedContact;\ncontactStatus#16d9703b user_id:long status:UserStatus = ContactStatus;\ncontacts.contactsNotModified#b74ba9d2 = contacts.Contacts;\ncontacts.contacts#eae87e42 contacts:Vector saved_count:int users:Vector = contacts.Contacts;\ncontacts.importedContacts#77d01c3b imported:Vector popular_invites:Vector retry_contacts:Vector users:Vector = contacts.ImportedContacts;\ncontacts.blocked#ade1591 blocked:Vector chats:Vector users:Vector = contacts.Blocked;\ncontacts.blockedSlice#e1664194 count:int blocked:Vector chats:Vector users:Vector = contacts.Blocked;\nmessages.dialogs#15ba6c40 dialogs:Vector messages:Vector chats:Vector users:Vector = messages.Dialogs;\nmessages.dialogsSlice#71e094f3 count:int dialogs:Vector messages:Vector chats:Vector users:Vector = messages.Dialogs;\nmessages.dialogsNotModified#f0e3e596 count:int = messages.Dialogs;\nmessages.messages#8c718e87 messages:Vector chats:Vector users:Vector = messages.Messages;\nmessages.messagesSlice#3a54685e flags:# inexact:flags.1?true count:int next_rate:flags.0?int offset_id_offset:flags.2?int messages:Vector chats:Vector users:Vector = messages.Messages;\nmessages.channelMessages#64479808 flags:# inexact:flags.1?true pts:int count:int offset_id_offset:flags.2?int messages:Vector chats:Vector users:Vector = messages.Messages;\nmessages.messagesNotModified#74535f21 count:int = messages.Messages;\nmessages.chats#64ff9fd5 chats:Vector = messages.Chats;\nmessages.chatsSlice#9cd81144 count:int chats:Vector = messages.Chats;\nmessages.chatFull#e5d7d19c full_chat:ChatFull chats:Vector users:Vector = messages.ChatFull;\nmessages.affectedHistory#b45c69d1 pts:int pts_count:int offset:int = messages.AffectedHistory;\ninputMessagesFilterEmpty#57e2f66c = MessagesFilter;\ninputMessagesFilterPhotos#9609a51c = MessagesFilter;\ninputMessagesFilterVideo#9fc00e65 = MessagesFilter;\ninputMessagesFilterPhotoVideo#56e9f0e4 = MessagesFilter;\ninputMessagesFilterDocument#9eddf188 = MessagesFilter;\ninputMessagesFilterUrl#7ef0dd87 = MessagesFilter;\ninputMessagesFilterGif#ffc86587 = MessagesFilter;\ninputMessagesFilterVoice#50f5c392 = MessagesFilter;\ninputMessagesFilterMusic#3751b49e = MessagesFilter;\ninputMessagesFilterChatPhotos#3a20ecb8 = MessagesFilter;\ninputMessagesFilterPhoneCalls#80c99768 flags:# missed:flags.0?true = MessagesFilter;\ninputMessagesFilterRoundVoice#7a7c17a4 = MessagesFilter;\ninputMessagesFilterRoundVideo#b549da53 = MessagesFilter;\ninputMessagesFilterMyMentions#c1f8e69a = MessagesFilter;\ninputMessagesFilterGeo#e7026d0d = MessagesFilter;\ninputMessagesFilterContacts#e062db83 = MessagesFilter;\ninputMessagesFilterPinned#1bb00451 = MessagesFilter;\nupdateNewMessage#1f2b0afd message:Message pts:int pts_count:int = Update;\nupdateMessageID#4e90bfd6 id:int random_id:long = Update;\nupdateDeleteMessages#a20db0e5 messages:Vector pts:int pts_count:int = Update;\nupdateUserTyping#c01e857f user_id:long action:SendMessageAction = Update;\nupdateChatUserTyping#83487af0 chat_id:long from_id:Peer action:SendMessageAction = Update;\nupdateChatParticipants#7761198 participants:ChatParticipants = Update;\nupdateUserStatus#e5bdf8de user_id:long status:UserStatus = Update;\nupdateUserName#c3f202e0 user_id:long first_name:string last_name:string username:string = Update;\nupdateUserPhoto#f227868c user_id:long date:int photo:UserProfilePhoto previous:Bool = Update;\nupdateNewEncryptedMessage#12bcbd9a message:EncryptedMessage qts:int = Update;\nupdateEncryptedChatTyping#1710f156 chat_id:int = Update;\nupdateEncryption#b4a2e88d chat:EncryptedChat date:int = Update;\nupdateEncryptedMessagesRead#38fe25b7 chat_id:int max_date:int date:int = Update;\nupdateChatParticipantAdd#3dda5451 chat_id:long user_id:long inviter_id:long date:int version:int = Update;\nupdateChatParticipantDelete#e32f3d77 chat_id:long user_id:long version:int = Update;\nupdateDcOptions#8e5e9873 dc_options:Vector = Update;\nupdateNotifySettings#bec268ef peer:NotifyPeer notify_settings:PeerNotifySettings = Update;\nupdateServiceNotification#ebe46819 flags:# popup:flags.0?true inbox_date:flags.1?int type:string message:string media:MessageMedia entities:Vector = Update;\nupdatePrivacy#ee3b272a key:PrivacyKey rules:Vector = Update;\nupdateUserPhone#5492a13 user_id:long phone:string = Update;\nupdateReadHistoryInbox#9c974fdf flags:# folder_id:flags.0?int peer:Peer max_id:int still_unread_count:int pts:int pts_count:int = Update;\nupdateReadHistoryOutbox#2f2f21bf peer:Peer max_id:int pts:int pts_count:int = Update;\nupdateWebPage#7f891213 webpage:WebPage pts:int pts_count:int = Update;\nupdateReadMessagesContents#68c13933 messages:Vector pts:int pts_count:int = Update;\nupdateChannelTooLong#108d941f flags:# channel_id:long pts:flags.0?int = Update;\nupdateChannel#635b4c09 channel_id:long = Update;\nupdateNewChannelMessage#62ba04d9 message:Message pts:int pts_count:int = Update;\nupdateReadChannelInbox#922e6e10 flags:# folder_id:flags.0?int channel_id:long max_id:int still_unread_count:int pts:int = Update;\nupdateDeleteChannelMessages#c32d5b12 channel_id:long messages:Vector pts:int pts_count:int = Update;\nupdateChannelMessageViews#f226ac08 channel_id:long id:int views:int = Update;\nupdateChatParticipantAdmin#d7ca61a2 chat_id:long user_id:long is_admin:Bool version:int = Update;\nupdateNewStickerSet#688a30aa stickerset:messages.StickerSet = Update;\nupdateStickerSetsOrder#bb2d201 flags:# masks:flags.0?true order:Vector = Update;\nupdateStickerSets#43ae3dec = Update;\nupdateSavedGifs#9375341e = Update;\nupdateBotInlineQuery#496f379c flags:# query_id:long user_id:long query:string geo:flags.0?GeoPoint peer_type:flags.1?InlineQueryPeerType offset:string = Update;\nupdateBotInlineSend#12f12a07 flags:# user_id:long query:string geo:flags.0?GeoPoint id:string msg_id:flags.1?InputBotInlineMessageID = Update;\nupdateEditChannelMessage#1b3f4df7 message:Message pts:int pts_count:int = Update;\nupdateBotCallbackQuery#b9cfc48d flags:# query_id:long user_id:long peer:Peer msg_id:int chat_instance:long data:flags.0?bytes game_short_name:flags.1?string = Update;\nupdateEditMessage#e40370a3 message:Message pts:int pts_count:int = Update;\nupdateInlineBotCallbackQuery#691e9052 flags:# query_id:long user_id:long msg_id:InputBotInlineMessageID chat_instance:long data:flags.0?bytes game_short_name:flags.1?string = Update;\nupdateReadChannelOutbox#b75f99a9 channel_id:long max_id:int = Update;\nupdateDraftMessage#ee2bb969 peer:Peer draft:DraftMessage = Update;\nupdateReadFeaturedStickers#571d2742 = Update;\nupdateRecentStickers#9a422c20 = Update;\nupdateConfig#a229dd06 = Update;\nupdatePtsChanged#3354678f = Update;\nupdateChannelWebPage#2f2ba99f channel_id:long webpage:WebPage pts:int pts_count:int = Update;\nupdateDialogPinned#6e6fe51c flags:# pinned:flags.0?true folder_id:flags.1?int peer:DialogPeer = Update;\nupdatePinnedDialogs#fa0f3ca2 flags:# folder_id:flags.1?int order:flags.0?Vector = Update;\nupdateBotWebhookJSON#8317c0c3 data:DataJSON = Update;\nupdateBotWebhookJSONQuery#9b9240a6 query_id:long data:DataJSON timeout:int = Update;\nupdateBotShippingQuery#b5aefd7d query_id:long user_id:long payload:bytes shipping_address:PostAddress = Update;\nupdateBotPrecheckoutQuery#8caa9a96 flags:# query_id:long user_id:long payload:bytes info:flags.0?PaymentRequestedInfo shipping_option_id:flags.1?string currency:string total_amount:long = Update;\nupdatePhoneCall#ab0f6b1e phone_call:PhoneCall = Update;\nupdateLangPackTooLong#46560264 lang_code:string = Update;\nupdateLangPack#56022f4d difference:LangPackDifference = Update;\nupdateFavedStickers#e511996d = Update;\nupdateChannelReadMessagesContents#44bdd535 channel_id:long messages:Vector = Update;\nupdateContactsReset#7084a7be = Update;\nupdateChannelAvailableMessages#b23fc698 channel_id:long available_min_id:int = Update;\nupdateDialogUnreadMark#e16459c3 flags:# unread:flags.0?true peer:DialogPeer = Update;\nupdateMessagePoll#aca1657b flags:# poll_id:long poll:flags.0?Poll results:PollResults = Update;\nupdateChatDefaultBannedRights#54c01850 peer:Peer default_banned_rights:ChatBannedRights version:int = Update;\nupdateFolderPeers#19360dc0 folder_peers:Vector pts:int pts_count:int = Update;\nupdatePeerSettings#6a7e7366 peer:Peer settings:PeerSettings = Update;\nupdatePeerLocated#b4afcfb0 peers:Vector = Update;\nupdateNewScheduledMessage#39a51dfb message:Message = Update;\nupdateDeleteScheduledMessages#90866cee peer:Peer messages:Vector = Update;\nupdateTheme#8216fba3 theme:Theme = Update;\nupdateGeoLiveViewed#871fb939 peer:Peer msg_id:int = Update;\nupdateLoginToken#564fe691 = Update;\nupdateMessagePollVote#106395c9 poll_id:long user_id:long options:Vector qts:int = Update;\nupdateDialogFilter#26ffde7d flags:# id:int filter:flags.0?DialogFilter = Update;\nupdateDialogFilterOrder#a5d72105 order:Vector = Update;\nupdateDialogFilters#3504914f = Update;\nupdatePhoneCallSignalingData#2661bf09 phone_call_id:long data:bytes = Update;\nupdateChannelMessageForwards#d29a27f4 channel_id:long id:int forwards:int = Update;\nupdateReadChannelDiscussionInbox#d6b19546 flags:# channel_id:long top_msg_id:int read_max_id:int broadcast_id:flags.0?long broadcast_post:flags.0?int = Update;\nupdateReadChannelDiscussionOutbox#695c9e7c channel_id:long top_msg_id:int read_max_id:int = Update;\nupdatePeerBlocked#246a4b22 peer_id:Peer blocked:Bool = Update;\nupdateChannelUserTyping#8c88c923 flags:# channel_id:long top_msg_id:flags.0?int from_id:Peer action:SendMessageAction = Update;\nupdatePinnedMessages#ed85eab5 flags:# pinned:flags.0?true peer:Peer messages:Vector pts:int pts_count:int = Update;\nupdatePinnedChannelMessages#5bb98608 flags:# pinned:flags.0?true channel_id:long messages:Vector pts:int pts_count:int = Update;\nupdateChat#f89a6a4e chat_id:long = Update;\nupdateGroupCallParticipants#f2ebdb4e call:InputGroupCall participants:Vector version:int = Update;\nupdateGroupCall#14b24500 chat_id:long call:GroupCall = Update;\nupdatePeerHistoryTTL#bb9bb9a5 flags:# peer:Peer ttl_period:flags.0?int = Update;\nupdateChatParticipant#d087663a flags:# chat_id:long date:int actor_id:long user_id:long prev_participant:flags.0?ChatParticipant new_participant:flags.1?ChatParticipant invite:flags.2?ExportedChatInvite qts:int = Update;\nupdateChannelParticipant#985d3abb flags:# channel_id:long date:int actor_id:long user_id:long prev_participant:flags.0?ChannelParticipant new_participant:flags.1?ChannelParticipant invite:flags.2?ExportedChatInvite qts:int = Update;\nupdateBotStopped#c4870a49 user_id:long date:int stopped:Bool qts:int = Update;\nupdateGroupCallConnection#b783982 flags:# presentation:flags.0?true params:DataJSON = Update;\nupdateBotCommands#4d712f2e peer:Peer bot_id:long commands:Vector = Update;\nupdates.state#a56c2a3e pts:int qts:int date:int seq:int unread_count:int = updates.State;\nupdates.differenceEmpty#5d75a138 date:int seq:int = updates.Difference;\nupdates.difference#f49ca0 new_messages:Vector new_encrypted_messages:Vector other_updates:Vector chats:Vector users:Vector state:updates.State = updates.Difference;\nupdates.differenceSlice#a8fb1981 new_messages:Vector new_encrypted_messages:Vector other_updates:Vector chats:Vector users:Vector intermediate_state:updates.State = updates.Difference;\nupdates.differenceTooLong#4afe8f6d pts:int = updates.Difference;\nupdatesTooLong#e317af7e = Updates;\nupdateShortMessage#313bc7f8 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true id:int user_id:long message:string pts:int pts_count:int date:int fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?long reply_to:flags.3?MessageReplyHeader entities:flags.7?Vector ttl_period:flags.25?int = Updates;\nupdateShortChatMessage#4d6deea5 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true id:int from_id:long chat_id:long message:string pts:int pts_count:int date:int fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?long reply_to:flags.3?MessageReplyHeader entities:flags.7?Vector ttl_period:flags.25?int = Updates;\nupdateShort#78d4dec1 update:Update date:int = Updates;\nupdatesCombined#725b04c3 updates:Vector users:Vector chats:Vector date:int seq_start:int seq:int = Updates;\nupdates#74ae4240 updates:Vector users:Vector chats:Vector date:int seq:int = Updates;\nupdateShortSentMessage#9015e101 flags:# out:flags.1?true id:int pts:int pts_count:int date:int media:flags.9?MessageMedia entities:flags.7?Vector ttl_period:flags.25?int = Updates;\nphotos.photos#8dca6aa5 photos:Vector users:Vector = photos.Photos;\nphotos.photosSlice#15051f54 count:int photos:Vector users:Vector = photos.Photos;\nphotos.photo#20212ca8 photo:Photo users:Vector = photos.Photo;\nupload.file#96a18d5 type:storage.FileType mtime:int bytes:bytes = upload.File;\nupload.fileCdnRedirect#f18cda44 dc_id:int file_token:bytes encryption_key:bytes encryption_iv:bytes file_hashes:Vector = upload.File;\ndcOption#18b7a10d flags:# ipv6:flags.0?true media_only:flags.1?true tcpo_only:flags.2?true cdn:flags.3?true static:flags.4?true id:int ip_address:string port:int secret:flags.10?bytes = DcOption;\nconfig#330b4067 flags:# phonecalls_enabled:flags.1?true default_p2p_contacts:flags.3?true preload_featured_stickers:flags.4?true ignore_phone_entities:flags.5?true revoke_pm_inbox:flags.6?true blocked_mode:flags.8?true pfs_enabled:flags.13?true date:int expires:int test_mode:Bool this_dc:int dc_options:Vector dc_txt_domain_name:string chat_size_max:int megagroup_size_max:int forwarded_count_max:int online_update_period_ms:int offline_blur_timeout_ms:int offline_idle_timeout_ms:int online_cloud_timeout_ms:int notify_cloud_delay_ms:int notify_default_delay_ms:int push_chat_period_ms:int push_chat_limit:int saved_gifs_limit:int edit_time_limit:int revoke_time_limit:int revoke_pm_time_limit:int rating_e_decay:int stickers_recent_limit:int stickers_faved_limit:int channels_read_media_period:int tmp_sessions:flags.0?int pinned_dialogs_count_max:int pinned_infolder_count_max:int call_receive_timeout_ms:int call_ring_timeout_ms:int call_connect_timeout_ms:int call_packet_timeout_ms:int me_url_prefix:string autoupdate_url_prefix:flags.7?string gif_search_username:flags.9?string venue_search_username:flags.10?string img_search_username:flags.11?string static_maps_provider:flags.12?string caption_length_max:int message_length_max:int webfile_dc_id:int suggested_lang_code:flags.2?string lang_pack_version:flags.2?int base_lang_pack_version:flags.2?int = Config;\nnearestDc#8e1a1775 country:string this_dc:int nearest_dc:int = NearestDc;\nhelp.appUpdate#ccbbce30 flags:# can_not_skip:flags.0?true id:int version:string text:string entities:Vector document:flags.1?Document url:flags.2?string sticker:flags.3?Document = help.AppUpdate;\nhelp.noAppUpdate#c45a6536 = help.AppUpdate;\nhelp.inviteText#18cb9f78 message:string = help.InviteText;\nencryptedChatEmpty#ab7ec0a0 id:int = EncryptedChat;\nencryptedChatWaiting#66b25953 id:int access_hash:long date:int admin_id:long participant_id:long = EncryptedChat;\nencryptedChatRequested#48f1d94c flags:# folder_id:flags.0?int id:int access_hash:long date:int admin_id:long participant_id:long g_a:bytes = EncryptedChat;\nencryptedChat#61f0d4c7 id:int access_hash:long date:int admin_id:long participant_id:long g_a_or_b:bytes key_fingerprint:long = EncryptedChat;\nencryptedChatDiscarded#1e1c7c45 flags:# history_deleted:flags.0?true id:int = EncryptedChat;\ninputEncryptedChat#f141b5e1 chat_id:int access_hash:long = InputEncryptedChat;\nencryptedFileEmpty#c21f497e = EncryptedFile;\nencryptedFile#4a70994c id:long access_hash:long size:int dc_id:int key_fingerprint:int = EncryptedFile;\ninputEncryptedFileEmpty#1837c364 = InputEncryptedFile;\ninputEncryptedFileUploaded#64bd0306 id:long parts:int md5_checksum:string key_fingerprint:int = InputEncryptedFile;\ninputEncryptedFile#5a17b5e5 id:long access_hash:long = InputEncryptedFile;\ninputEncryptedFileBigUploaded#2dc173c8 id:long parts:int key_fingerprint:int = InputEncryptedFile;\nencryptedMessage#ed18c118 random_id:long chat_id:int date:int bytes:bytes file:EncryptedFile = EncryptedMessage;\nencryptedMessageService#23734b06 random_id:long chat_id:int date:int bytes:bytes = EncryptedMessage;\nmessages.dhConfigNotModified#c0e24635 random:bytes = messages.DhConfig;\nmessages.dhConfig#2c221edd g:int p:bytes version:int random:bytes = messages.DhConfig;\nmessages.sentEncryptedMessage#560f8935 date:int = messages.SentEncryptedMessage;\nmessages.sentEncryptedFile#9493ff32 date:int file:EncryptedFile = messages.SentEncryptedMessage;\ninputDocumentEmpty#72f0eaae = InputDocument;\ninputDocument#1abfb575 id:long access_hash:long file_reference:bytes = InputDocument;\ndocumentEmpty#36f8c871 id:long = Document;\ndocument#1e87342b flags:# id:long access_hash:long file_reference:bytes date:int mime_type:string size:int thumbs:flags.0?Vector video_thumbs:flags.1?Vector dc_id:int attributes:Vector = Document;\nhelp.support#17c6b5f6 phone_number:string user:User = help.Support;\nnotifyPeer#9fd40bd8 peer:Peer = NotifyPeer;\nnotifyUsers#b4c83b4c = NotifyPeer;\nnotifyChats#c007cec3 = NotifyPeer;\nnotifyBroadcasts#d612e8ef = NotifyPeer;\nsendMessageTypingAction#16bf744e = SendMessageAction;\nsendMessageCancelAction#fd5ec8f5 = SendMessageAction;\nsendMessageRecordVideoAction#a187d66f = SendMessageAction;\nsendMessageUploadVideoAction#e9763aec progress:int = SendMessageAction;\nsendMessageRecordAudioAction#d52f73f7 = SendMessageAction;\nsendMessageUploadAudioAction#f351d7ab progress:int = SendMessageAction;\nsendMessageUploadPhotoAction#d1d34a26 progress:int = SendMessageAction;\nsendMessageUploadDocumentAction#aa0cd9e4 progress:int = SendMessageAction;\nsendMessageGeoLocationAction#176f8ba1 = SendMessageAction;\nsendMessageChooseContactAction#628cbc6f = SendMessageAction;\nsendMessageGamePlayAction#dd6a8f48 = SendMessageAction;\nsendMessageRecordRoundAction#88f27fbc = SendMessageAction;\nsendMessageUploadRoundAction#243e1c66 progress:int = SendMessageAction;\nspeakingInGroupCallAction#d92c2285 = SendMessageAction;\nsendMessageHistoryImportAction#dbda9246 progress:int = SendMessageAction;\nsendMessageChooseStickerAction#b05ac6b1 = SendMessageAction;\nsendMessageEmojiInteraction#25972bcb emoticon:string msg_id:int interaction:DataJSON = SendMessageAction;\nsendMessageEmojiInteractionSeen#b665902e emoticon:string = SendMessageAction;\ncontacts.found#b3134d9d my_results:Vector results:Vector chats:Vector users:Vector = contacts.Found;\ninputPrivacyKeyStatusTimestamp#4f96cb18 = InputPrivacyKey;\ninputPrivacyKeyChatInvite#bdfb0426 = InputPrivacyKey;\ninputPrivacyKeyPhoneCall#fabadc5f = InputPrivacyKey;\ninputPrivacyKeyPhoneP2P#db9e70d2 = InputPrivacyKey;\ninputPrivacyKeyForwards#a4dd4c08 = InputPrivacyKey;\ninputPrivacyKeyProfilePhoto#5719bacc = InputPrivacyKey;\ninputPrivacyKeyPhoneNumber#352dafa = InputPrivacyKey;\ninputPrivacyKeyAddedByPhone#d1219bdd = InputPrivacyKey;\nprivacyKeyStatusTimestamp#bc2eab30 = PrivacyKey;\nprivacyKeyChatInvite#500e6dfa = PrivacyKey;\nprivacyKeyPhoneCall#3d662b7b = PrivacyKey;\nprivacyKeyPhoneP2P#39491cc8 = PrivacyKey;\nprivacyKeyForwards#69ec56a3 = PrivacyKey;\nprivacyKeyProfilePhoto#96151fed = PrivacyKey;\nprivacyKeyPhoneNumber#d19ae46d = PrivacyKey;\nprivacyKeyAddedByPhone#42ffd42b = PrivacyKey;\ninputPrivacyValueAllowContacts#d09e07b = InputPrivacyRule;\ninputPrivacyValueAllowAll#184b35ce = InputPrivacyRule;\ninputPrivacyValueAllowUsers#131cc67f users:Vector = InputPrivacyRule;\ninputPrivacyValueDisallowContacts#ba52007 = InputPrivacyRule;\ninputPrivacyValueDisallowAll#d66b66c9 = InputPrivacyRule;\ninputPrivacyValueDisallowUsers#90110467 users:Vector = InputPrivacyRule;\ninputPrivacyValueAllowChatParticipants#840649cf chats:Vector = InputPrivacyRule;\ninputPrivacyValueDisallowChatParticipants#e94f0f86 chats:Vector = InputPrivacyRule;\nprivacyValueAllowContacts#fffe1bac = PrivacyRule;\nprivacyValueAllowAll#65427b82 = PrivacyRule;\nprivacyValueAllowUsers#b8905fb2 users:Vector = PrivacyRule;\nprivacyValueDisallowContacts#f888fa1a = PrivacyRule;\nprivacyValueDisallowAll#8b73e763 = PrivacyRule;\nprivacyValueDisallowUsers#e4621141 users:Vector = PrivacyRule;\nprivacyValueAllowChatParticipants#6b134e8e chats:Vector = PrivacyRule;\nprivacyValueDisallowChatParticipants#41c87565 chats:Vector = PrivacyRule;\naccount.privacyRules#50a04e45 rules:Vector chats:Vector users:Vector = account.PrivacyRules;\naccountDaysTTL#b8d0afdf days:int = AccountDaysTTL;\ndocumentAttributeImageSize#6c37c15c w:int h:int = DocumentAttribute;\ndocumentAttributeAnimated#11b58939 = DocumentAttribute;\ndocumentAttributeSticker#6319d612 flags:# mask:flags.1?true alt:string stickerset:InputStickerSet mask_coords:flags.0?MaskCoords = DocumentAttribute;\ndocumentAttributeVideo#ef02ce6 flags:# round_message:flags.0?true supports_streaming:flags.1?true duration:int w:int h:int = DocumentAttribute;\ndocumentAttributeAudio#9852f9c6 flags:# voice:flags.10?true duration:int title:flags.0?string performer:flags.1?string waveform:flags.2?bytes = DocumentAttribute;\ndocumentAttributeFilename#15590068 file_name:string = DocumentAttribute;\ndocumentAttributeHasStickers#9801d2f7 = DocumentAttribute;\nmessages.stickersNotModified#f1749a22 = messages.Stickers;\nmessages.stickers#30a6ec7e hash:long stickers:Vector = messages.Stickers;\nstickerPack#12b299d4 emoticon:string documents:Vector = StickerPack;\nmessages.allStickersNotModified#e86602c3 = messages.AllStickers;\nmessages.allStickers#cdbbcebb hash:long sets:Vector = messages.AllStickers;\nmessages.affectedMessages#84d19185 pts:int pts_count:int = messages.AffectedMessages;\nwebPageEmpty#eb1477e8 id:long = WebPage;\nwebPagePending#c586da1c id:long date:int = WebPage;\nwebPage#e89c45b2 flags:# id:long url:string display_url:string hash:int type:flags.0?string site_name:flags.1?string title:flags.2?string description:flags.3?string photo:flags.4?Photo embed_url:flags.5?string embed_type:flags.5?string embed_width:flags.6?int embed_height:flags.6?int duration:flags.7?int author:flags.8?string document:flags.9?Document cached_page:flags.10?Page attributes:flags.12?Vector = WebPage;\nwebPageNotModified#7311ca11 flags:# cached_page_views:flags.0?int = WebPage;\nauthorization#ad01d61d flags:# current:flags.0?true official_app:flags.1?true password_pending:flags.2?true hash:long device_model:string platform:string system_version:string api_id:int app_name:string app_version:string date_created:int date_active:int ip:string country:string region:string = Authorization;\naccount.authorizations#1250abde authorizations:Vector = 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#b18105e8 flags:# revoked:flags.0?true permanent:flags.5?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 = ExportedChatInvite;\nchatInviteAlready#5a686d7c chat:Chat = ChatInvite;\nchatInvite#dfc2f58e flags:# channel:flags.0?true broadcast:flags.1?true public:flags.2?true megagroup:flags.3?true title:string photo:Photo participants_count:int participants:flags.4?Vector = ChatInvite;\nchatInvitePeek#61695cb0 chat:Chat expires:int = ChatInvite;\ninputStickerSetEmpty#ffb62b95 = InputStickerSet;\ninputStickerSetID#9de7a269 id:long access_hash:long = InputStickerSet;\ninputStickerSetShortName#861cc8a0 short_name:string = InputStickerSet;\ninputStickerSetAnimatedEmoji#28703c8 = InputStickerSet;\ninputStickerSetDice#e67f520e emoticon:string = InputStickerSet;\ninputStickerSetAnimatedEmojiAnimations#cde3739 = InputStickerSet;\nstickerSet#d7df217a flags:# archived:flags.1?true official:flags.2?true masks:flags.3?true animated:flags.5?true installed_date:flags.0?int id:long access_hash:long title:string short_name:string thumbs:flags.4?Vector thumb_dc_id:flags.4?int thumb_version:flags.4?int count:int hash:int = StickerSet;\nmessages.stickerSet#b60a24a6 set:StickerSet packs:Vector documents:Vector = messages.StickerSet;\nbotCommand#c27ac8c7 command:string description:string = BotCommand;\nbotInfo#1b74b335 user_id:long description:string commands:Vector = BotInfo;\nkeyboardButton#a2fa4880 text:string = KeyboardButton;\nkeyboardButtonUrl#258aff05 text:string url:string = KeyboardButton;\nkeyboardButtonCallback#35bbdb6b flags:# requires_password:flags.0?true text:string data:bytes = KeyboardButton;\nkeyboardButtonRequestPhone#b16a6c29 text:string = KeyboardButton;\nkeyboardButtonRequestGeoLocation#fc796b3f text:string = KeyboardButton;\nkeyboardButtonSwitchInline#568a748 flags:# same_peer:flags.0?true text:string query:string = KeyboardButton;\nkeyboardButtonGame#50f41ccf text:string = KeyboardButton;\nkeyboardButtonBuy#afd93fbb text:string = KeyboardButton;\nkeyboardButtonUrlAuth#10b78d29 flags:# text:string fwd_text:flags.0?string url:string button_id:int = KeyboardButton;\ninputKeyboardButtonUrlAuth#d02e7fd4 flags:# request_write_access:flags.0?true text:string fwd_text:flags.1?string url:string bot:InputUser = KeyboardButton;\nkeyboardButtonRequestPoll#bbc7515d flags:# quiz:flags.0?Bool text:string = KeyboardButton;\nkeyboardButtonRow#77608b83 buttons:Vector = KeyboardButtonRow;\nreplyKeyboardHide#a03e5b85 flags:# selective:flags.2?true = ReplyMarkup;\nreplyKeyboardForceReply#86b40b08 flags:# single_use:flags.1?true selective:flags.2?true placeholder:flags.3?string = ReplyMarkup;\nreplyKeyboardMarkup#85dd99d1 flags:# resize:flags.0?true single_use:flags.1?true selective:flags.2?true rows:Vector placeholder:flags.3?string = ReplyMarkup;\nreplyInlineMarkup#48a30254 rows:Vector = ReplyMarkup;\nmessageEntityUnknown#bb92ba95 offset:int length:int = MessageEntity;\nmessageEntityMention#fa04579d offset:int length:int = MessageEntity;\nmessageEntityHashtag#6f635b0d offset:int length:int = MessageEntity;\nmessageEntityBotCommand#6cef8ac7 offset:int length:int = MessageEntity;\nmessageEntityUrl#6ed02538 offset:int length:int = MessageEntity;\nmessageEntityEmail#64e475c2 offset:int length:int = MessageEntity;\nmessageEntityBold#bd610bc9 offset:int length:int = MessageEntity;\nmessageEntityItalic#826f8b60 offset:int length:int = MessageEntity;\nmessageEntityCode#28a20571 offset:int length:int = MessageEntity;\nmessageEntityPre#73924be0 offset:int length:int language:string = MessageEntity;\nmessageEntityTextUrl#76a6d327 offset:int length:int url:string = MessageEntity;\nmessageEntityMentionName#dc7b1140 offset:int length:int user_id:long = MessageEntity;\ninputMessageEntityMentionName#208e68c9 offset:int length:int user_id:InputUser = MessageEntity;\nmessageEntityPhone#9b69e34b offset:int length:int = MessageEntity;\nmessageEntityCashtag#4c4e743f offset:int length:int = MessageEntity;\nmessageEntityUnderline#9c4e7e8b offset:int length:int = MessageEntity;\nmessageEntityStrike#bf0693d4 offset:int length:int = MessageEntity;\nmessageEntityBlockquote#20df5d0 offset:int length:int = MessageEntity;\nmessageEntityBankCard#761e6af4 offset:int length:int = MessageEntity;\ninputChannelEmpty#ee8c1e86 = InputChannel;\ninputChannel#f35aec28 channel_id:long access_hash:long = InputChannel;\ninputChannelFromMessage#5b934f9d peer:InputPeer msg_id:int channel_id:long = InputChannel;\ncontacts.resolvedPeer#7f077ad9 peer:Peer chats:Vector users:Vector = contacts.ResolvedPeer;\nmessageRange#ae30253 min_id:int max_id:int = MessageRange;\nupdates.channelDifferenceEmpty#3e11affb flags:# final:flags.0?true pts:int timeout:flags.1?int = updates.ChannelDifference;\nupdates.channelDifferenceTooLong#a4bcc6fe flags:# final:flags.0?true timeout:flags.1?int dialog:Dialog messages:Vector chats:Vector users:Vector = updates.ChannelDifference;\nupdates.channelDifference#2064674e flags:# final:flags.0?true pts:int timeout:flags.1?int new_messages:Vector other_updates:Vector chats:Vector users:Vector = updates.ChannelDifference;\nchannelMessagesFilterEmpty#94d42ee7 = ChannelMessagesFilter;\nchannelMessagesFilter#cd77d957 flags:# exclude_new_messages:flags.1?true ranges:Vector = ChannelMessagesFilter;\nchannelParticipant#c00c07c0 user_id:long date:int = ChannelParticipant;\nchannelParticipantSelf#28a8bc67 user_id:long inviter_id:long date:int = ChannelParticipant;\nchannelParticipantCreator#2fe601d3 flags:# user_id:long admin_rights:ChatAdminRights rank:flags.0?string = ChannelParticipant;\nchannelParticipantAdmin#34c3bb53 flags:# can_edit:flags.0?true self:flags.1?true user_id:long inviter_id:flags.1?long promoted_by:long date:int admin_rights:ChatAdminRights rank:flags.2?string = ChannelParticipant;\nchannelParticipantBanned#6df8014e flags:# left:flags.0?true peer:Peer kicked_by:long date:int banned_rights:ChatBannedRights = ChannelParticipant;\nchannelParticipantLeft#1b03f006 peer:Peer = ChannelParticipant;\nchannelParticipantsRecent#de3f3c79 = ChannelParticipantsFilter;\nchannelParticipantsAdmins#b4608969 = ChannelParticipantsFilter;\nchannelParticipantsKicked#a3b54985 q:string = ChannelParticipantsFilter;\nchannelParticipantsBots#b0d1865b = ChannelParticipantsFilter;\nchannelParticipantsBanned#1427a5e1 q:string = ChannelParticipantsFilter;\nchannelParticipantsSearch#656ac4b q:string = ChannelParticipantsFilter;\nchannelParticipantsContacts#bb6ae88d q:string = ChannelParticipantsFilter;\nchannelParticipantsMentions#e04b5ceb flags:# q:flags.0?string top_msg_id:flags.1?int = ChannelParticipantsFilter;\nchannels.channelParticipants#9ab0feaf count:int participants:Vector chats:Vector users:Vector = channels.ChannelParticipants;\nchannels.channelParticipantsNotModified#f0173fe9 = channels.ChannelParticipants;\nchannels.channelParticipant#dfb80317 participant:ChannelParticipant chats:Vector users:Vector = channels.ChannelParticipant;\nhelp.termsOfService#780a0310 flags:# popup:flags.0?true id:DataJSON text:string entities:Vector min_age_confirm:flags.1?int = help.TermsOfService;\nmessages.savedGifsNotModified#e8025ca2 = messages.SavedGifs;\nmessages.savedGifs#84a02a0d hash:long gifs:Vector = messages.SavedGifs;\ninputBotInlineMessageMediaAuto#3380c786 flags:# message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageText#3dcd7a87 flags:# no_webpage:flags.0?true message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaGeo#96929a85 flags:# geo_point:InputGeoPoint heading:flags.0?int period:flags.1?int proximity_notification_radius:flags.3?int reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaVenue#417bbf11 flags:# geo_point:InputGeoPoint title:string address:string provider:string venue_id:string venue_type:string reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaContact#a6edbffd flags:# phone_number:string first_name:string last_name:string vcard:string reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageGame#4b425864 flags:# reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaInvoice#d7e78225 flags:# title:string description:string photo:flags.0?InputWebDocument invoice:Invoice payload:bytes provider:string provider_data:DataJSON reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineResult#88bf9319 flags:# id:string type:string title:flags.1?string description:flags.2?string url:flags.3?string thumb:flags.4?InputWebDocument content:flags.5?InputWebDocument send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultPhoto#a8d864a7 id:string type:string photo:InputPhoto send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultDocument#fff8fdc4 flags:# id:string type:string title:flags.1?string description:flags.2?string document:InputDocument send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultGame#4fa417f2 id:string short_name:string send_message:InputBotInlineMessage = InputBotInlineResult;\nbotInlineMessageMediaAuto#764cf810 flags:# message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageText#8c7f65e2 flags:# no_webpage:flags.0?true message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaGeo#51846fd flags:# geo:GeoPoint heading:flags.0?int period:flags.1?int proximity_notification_radius:flags.3?int reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaVenue#8a86659c flags:# geo:GeoPoint title:string address:string provider:string venue_id:string venue_type:string reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaContact#18d1cdc2 flags:# phone_number:string first_name:string last_name:string vcard:string reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaInvoice#354a9b09 flags:# shipping_address_requested:flags.1?true test:flags.3?true title:string description:string photo:flags.0?WebDocument currency:string total_amount:long reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineResult#11965f3a flags:# id:string type:string title:flags.1?string description:flags.2?string url:flags.3?string thumb:flags.4?WebDocument content:flags.5?WebDocument send_message:BotInlineMessage = BotInlineResult;\nbotInlineMediaResult#17db940b flags:# id:string type:string photo:flags.0?Photo document:flags.1?Document title:flags.2?string description:flags.3?string send_message:BotInlineMessage = BotInlineResult;\nmessages.botResults#947ca848 flags:# gallery:flags.0?true query_id:long next_offset:flags.1?string switch_pm:flags.2?InlineBotSwitchPM results:Vector cache_time:int users:Vector = messages.BotResults;\nexportedMessageLink#5dab1af4 link:string html:string = ExportedMessageLink;\nmessageFwdHeader#5f777dce flags:# imported:flags.7?true from_id:flags.0?Peer from_name:flags.5?string date:int channel_post:flags.2?int post_author:flags.3?string saved_from_peer:flags.4?Peer saved_from_msg_id:flags.4?int psa_type:flags.6?string = MessageFwdHeader;\nauth.codeTypeSms#72a3158c = auth.CodeType;\nauth.codeTypeCall#741cd3e3 = auth.CodeType;\nauth.codeTypeFlashCall#226ccefb = auth.CodeType;\nauth.sentCodeTypeApp#3dbb5986 length:int = auth.SentCodeType;\nauth.sentCodeTypeSms#c000bba2 length:int = auth.SentCodeType;\nauth.sentCodeTypeCall#5353e5a7 length:int = auth.SentCodeType;\nauth.sentCodeTypeFlashCall#ab03c6d9 pattern:string = auth.SentCodeType;\nmessages.botCallbackAnswer#36585ea4 flags:# alert:flags.1?true has_url:flags.3?true native_ui:flags.4?true message:flags.0?string url:flags.2?string cache_time:int = messages.BotCallbackAnswer;\nmessages.messageEditData#26b5dde6 flags:# caption:flags.0?true = messages.MessageEditData;\ninputBotInlineMessageID#890c3d89 dc_id:int id:long access_hash:long = InputBotInlineMessageID;\ninputBotInlineMessageID64#b6d915d7 dc_id:int owner_id:long id:int access_hash:long = InputBotInlineMessageID;\ninlineBotSwitchPM#3c20629f text:string start_param:string = InlineBotSwitchPM;\nmessages.peerDialogs#3371c354 dialogs:Vector messages:Vector chats:Vector users:Vector state:updates.State = messages.PeerDialogs;\ntopPeer#edcdc05b peer:Peer rating:double = TopPeer;\ntopPeerCategoryBotsPM#ab661b5b = TopPeerCategory;\ntopPeerCategoryBotsInline#148677e2 = TopPeerCategory;\ntopPeerCategoryCorrespondents#637b7ed = TopPeerCategory;\ntopPeerCategoryGroups#bd17a14a = TopPeerCategory;\ntopPeerCategoryChannels#161d9628 = TopPeerCategory;\ntopPeerCategoryPhoneCalls#1e76a78c = TopPeerCategory;\ntopPeerCategoryForwardUsers#a8406ca9 = TopPeerCategory;\ntopPeerCategoryForwardChats#fbeec0f0 = TopPeerCategory;\ntopPeerCategoryPeers#fb834291 category:TopPeerCategory count:int peers:Vector = TopPeerCategoryPeers;\ncontacts.topPeersNotModified#de266ef5 = contacts.TopPeers;\ncontacts.topPeers#70b772a8 categories:Vector chats:Vector users:Vector = contacts.TopPeers;\ncontacts.topPeersDisabled#b52c939d = contacts.TopPeers;\ndraftMessageEmpty#1b0c841a flags:# date:flags.0?int = DraftMessage;\ndraftMessage#fd8e711f flags:# no_webpage:flags.1?true reply_to_msg_id:flags.0?int message:string entities:flags.3?Vector date:int = DraftMessage;\nmessages.featuredStickersNotModified#c6dc0c66 count:int = messages.FeaturedStickers;\nmessages.featuredStickers#84c02310 hash:long count:int sets:Vector unread:Vector = messages.FeaturedStickers;\nmessages.recentStickersNotModified#b17f890 = messages.RecentStickers;\nmessages.recentStickers#88d37c56 hash:long packs:Vector stickers:Vector dates:Vector = messages.RecentStickers;\nmessages.archivedStickers#4fcba9c8 count:int sets:Vector = messages.ArchivedStickers;\nmessages.stickerSetInstallResultSuccess#38641628 = messages.StickerSetInstallResult;\nmessages.stickerSetInstallResultArchive#35e410a8 sets:Vector = messages.StickerSetInstallResult;\nstickerSetCovered#6410a5d2 set:StickerSet cover:Document = StickerSetCovered;\nstickerSetMultiCovered#3407e51b set:StickerSet covers:Vector = StickerSetCovered;\nmaskCoords#aed6dbb2 n:int x:double y:double zoom:double = MaskCoords;\ninputStickeredMediaPhoto#4a992157 id:InputPhoto = InputStickeredMedia;\ninputStickeredMediaDocument#438865b id:InputDocument = InputStickeredMedia;\ngame#bdf9653b flags:# id:long access_hash:long short_name:string title:string description:string photo:Photo document:flags.0?Document = Game;\ninputGameID#32c3e77 id:long access_hash:long = InputGame;\ninputGameShortName#c331e80a bot_id:InputUser short_name:string = InputGame;\nhighScore#73a379eb pos:int user_id:long score:int = HighScore;\nmessages.highScores#9a3bfd99 scores:Vector users:Vector = messages.HighScores;\ntextEmpty#dc3d824f = RichText;\ntextPlain#744694e0 text:string = RichText;\ntextBold#6724abc4 text:RichText = RichText;\ntextItalic#d912a59c text:RichText = RichText;\ntextUnderline#c12622c4 text:RichText = RichText;\ntextStrike#9bf8bb95 text:RichText = RichText;\ntextFixed#6c3f19b9 text:RichText = RichText;\ntextUrl#3c2884c1 text:RichText url:string webpage_id:long = RichText;\ntextEmail#de5a0dd6 text:RichText email:string = RichText;\ntextConcat#7e6260d7 texts:Vector = RichText;\ntextSubscript#ed6a8504 text:RichText = RichText;\ntextSuperscript#c7fb5e01 text:RichText = RichText;\ntextMarked#34b8621 text:RichText = RichText;\ntextPhone#1ccb966a text:RichText phone:string = RichText;\ntextImage#81ccf4f document_id:long w:int h:int = RichText;\ntextAnchor#35553762 text:RichText name:string = RichText;\npageBlockUnsupported#13567e8a = PageBlock;\npageBlockTitle#70abc3fd text:RichText = PageBlock;\npageBlockSubtitle#8ffa9a1f text:RichText = PageBlock;\npageBlockAuthorDate#baafe5e0 author:RichText published_date:int = PageBlock;\npageBlockHeader#bfd064ec text:RichText = PageBlock;\npageBlockSubheader#f12bb6e1 text:RichText = PageBlock;\npageBlockParagraph#467a0766 text:RichText = PageBlock;\npageBlockPreformatted#c070d93e text:RichText language:string = PageBlock;\npageBlockFooter#48870999 text:RichText = PageBlock;\npageBlockDivider#db20b188 = PageBlock;\npageBlockAnchor#ce0d37b0 name:string = PageBlock;\npageBlockList#e4e88011 items:Vector = PageBlock;\npageBlockBlockquote#263d7c26 text:RichText caption:RichText = PageBlock;\npageBlockPullquote#4f4456d3 text:RichText caption:RichText = PageBlock;\npageBlockPhoto#1759c560 flags:# photo_id:long caption:PageCaption url:flags.0?string webpage_id:flags.0?long = PageBlock;\npageBlockVideo#7c8fe7b6 flags:# autoplay:flags.0?true loop:flags.1?true video_id:long caption:PageCaption = PageBlock;\npageBlockCover#39f23300 cover:PageBlock = PageBlock;\npageBlockEmbed#a8718dc5 flags:# full_width:flags.0?true allow_scrolling:flags.3?true url:flags.1?string html:flags.2?string poster_photo_id:flags.4?long w:flags.5?int h:flags.5?int caption:PageCaption = PageBlock;\npageBlockEmbedPost#f259a80b url:string webpage_id:long author_photo_id:long author:string date:int blocks:Vector caption:PageCaption = PageBlock;\npageBlockCollage#65a0fa4d items:Vector caption:PageCaption = PageBlock;\npageBlockSlideshow#31f9590 items:Vector caption:PageCaption = PageBlock;\npageBlockChannel#ef1751b5 channel:Chat = PageBlock;\npageBlockAudio#804361ea audio_id:long caption:PageCaption = PageBlock;\npageBlockKicker#1e148390 text:RichText = PageBlock;\npageBlockTable#bf4dea82 flags:# bordered:flags.0?true striped:flags.1?true title:RichText rows:Vector = PageBlock;\npageBlockOrderedList#9a8ae1e1 items:Vector = PageBlock;\npageBlockDetails#76768bed flags:# open:flags.0?true blocks:Vector title:RichText = PageBlock;\npageBlockRelatedArticles#16115a96 title:RichText articles:Vector = PageBlock;\npageBlockMap#a44f3ef6 geo:GeoPoint zoom:int w:int h:int caption:PageCaption = PageBlock;\nphoneCallDiscardReasonMissed#85e42301 = PhoneCallDiscardReason;\nphoneCallDiscardReasonDisconnect#e095c1a0 = PhoneCallDiscardReason;\nphoneCallDiscardReasonHangup#57adc690 = PhoneCallDiscardReason;\nphoneCallDiscardReasonBusy#faf7e8c9 = PhoneCallDiscardReason;\ndataJSON#7d748d04 data:string = DataJSON;\nlabeledPrice#cb296bf8 label:string amount:long = LabeledPrice;\ninvoice#cd886e0 flags:# test:flags.0?true name_requested:flags.1?true phone_requested:flags.2?true email_requested:flags.3?true shipping_address_requested:flags.4?true flexible:flags.5?true phone_to_provider:flags.6?true email_to_provider:flags.7?true currency:string prices:Vector max_tip_amount:flags.8?long suggested_tip_amounts:flags.8?Vector = Invoice;\npaymentCharge#ea02c27e id:string provider_charge_id:string = PaymentCharge;\npostAddress#1e8caaeb street_line1:string street_line2:string city:string state:string country_iso2:string post_code:string = PostAddress;\npaymentRequestedInfo#909c3f94 flags:# name:flags.0?string phone:flags.1?string email:flags.2?string shipping_address:flags.3?PostAddress = PaymentRequestedInfo;\npaymentSavedCredentialsCard#cdc27a1f id:string title:string = PaymentSavedCredentials;\nwebDocument#1c570ed1 url:string access_hash:long size:int mime_type:string attributes:Vector = WebDocument;\nwebDocumentNoProxy#f9c8bcc6 url:string size:int mime_type:string attributes:Vector = WebDocument;\ninputWebDocument#9bed434d url:string size:int mime_type:string attributes:Vector = InputWebDocument;\ninputWebFileLocation#c239d686 url:string access_hash:long = InputWebFileLocation;\ninputWebFileGeoPointLocation#9f2221c9 geo_point:InputGeoPoint access_hash:long w:int h:int zoom:int scale:int = InputWebFileLocation;\nupload.webFile#21e753bc size:int mime_type:string file_type:storage.FileType mtime:int bytes:bytes = upload.WebFile;\npayments.paymentForm#1694761b flags:# can_save_credentials:flags.2?true password_missing:flags.3?true form_id:long bot_id:long invoice:Invoice provider_id:long url:string native_provider:flags.4?string native_params:flags.4?DataJSON saved_info:flags.0?PaymentRequestedInfo saved_credentials:flags.1?PaymentSavedCredentials users:Vector = payments.PaymentForm;\npayments.validatedRequestedInfo#d1451883 flags:# id:flags.0?string shipping_options:flags.1?Vector = payments.ValidatedRequestedInfo;\npayments.paymentResult#4e5f810d updates:Updates = payments.PaymentResult;\npayments.paymentVerificationNeeded#d8411139 url:string = payments.PaymentResult;\npayments.paymentReceipt#70c4fe03 flags:# date:int bot_id:long provider_id:long title:string description:string photo:flags.2?WebDocument invoice:Invoice info:flags.0?PaymentRequestedInfo shipping:flags.1?ShippingOption tip_amount:flags.3?long currency:string total_amount:long credentials_title:string users:Vector = payments.PaymentReceipt;\npayments.savedInfo#fb8fe43c flags:# has_saved_credentials:flags.1?true saved_info:flags.0?PaymentRequestedInfo = payments.SavedInfo;\ninputPaymentCredentialsSaved#c10eb2cf id:string tmp_password:bytes = InputPaymentCredentials;\ninputPaymentCredentials#3417d728 flags:# save:flags.0?true data:DataJSON = InputPaymentCredentials;\ninputPaymentCredentialsApplePay#aa1c39f payment_data:DataJSON = InputPaymentCredentials;\ninputPaymentCredentialsGooglePay#8ac32801 payment_token:DataJSON = InputPaymentCredentials;\naccount.tmpPassword#db64fd34 tmp_password:bytes valid_until:int = account.TmpPassword;\nshippingOption#b6213cdf id:string title:string prices:Vector = ShippingOption;\ninputStickerSetItem#ffa0a496 flags:# document:InputDocument emoji:string mask_coords:flags.0?MaskCoords = InputStickerSetItem;\ninputPhoneCall#1e36fded id:long access_hash:long = InputPhoneCall;\nphoneCallEmpty#5366c915 id:long = PhoneCall;\nphoneCallWaiting#c5226f17 flags:# video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long protocol:PhoneCallProtocol receive_date:flags.0?int = PhoneCall;\nphoneCallRequested#14b0ed0c flags:# video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long g_a_hash:bytes protocol:PhoneCallProtocol = PhoneCall;\nphoneCallAccepted#3660c311 flags:# video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long g_b:bytes protocol:PhoneCallProtocol = PhoneCall;\nphoneCall#967f7c67 flags:# p2p_allowed:flags.5?true video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long g_a_or_b:bytes key_fingerprint:long protocol:PhoneCallProtocol connections:Vector start_date:int = PhoneCall;\nphoneCallDiscarded#50ca4de1 flags:# need_rating:flags.2?true need_debug:flags.3?true video:flags.6?true id:long reason:flags.0?PhoneCallDiscardReason duration:flags.1?int = PhoneCall;\nphoneConnection#9d4c17c0 id:long ip:string ipv6:string port:int peer_tag:bytes = PhoneConnection;\nphoneConnectionWebrtc#635fe375 flags:# turn:flags.0?true stun:flags.1?true id:long ip:string ipv6:string port:int username:string password:string = PhoneConnection;\nphoneCallProtocol#fc878fc8 flags:# udp_p2p:flags.0?true udp_reflector:flags.1?true min_layer:int max_layer:int library_versions:Vector = PhoneCallProtocol;\nphone.phoneCall#ec82e140 phone_call:PhoneCall users:Vector = phone.PhoneCall;\nupload.cdnFileReuploadNeeded#eea8e46e request_token:bytes = upload.CdnFile;\nupload.cdnFile#a99fca4f bytes:bytes = upload.CdnFile;\ncdnPublicKey#c982eaba dc_id:int public_key:string = CdnPublicKey;\ncdnConfig#5725e40a public_keys:Vector = CdnConfig;\nlangPackString#cad181f6 key:string value:string = LangPackString;\nlangPackStringPluralized#6c47ac9f flags:# key:string zero_value:flags.0?string one_value:flags.1?string two_value:flags.2?string few_value:flags.3?string many_value:flags.4?string other_value:string = LangPackString;\nlangPackStringDeleted#2979eeb2 key:string = LangPackString;\nlangPackDifference#f385c1f6 lang_code:string from_version:int version:int strings:Vector = LangPackDifference;\nlangPackLanguage#eeca5ce3 flags:# official:flags.0?true rtl:flags.2?true beta:flags.3?true name:string native_name:string lang_code:string base_lang_code:flags.1?string plural_code:string strings_count:int translated_count:int translations_url:string = LangPackLanguage;\nchannelAdminLogEventActionChangeTitle#e6dfb825 prev_value:string new_value:string = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeAbout#55188a2e prev_value:string new_value:string = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeUsername#6a4afc38 prev_value:string new_value:string = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangePhoto#434bd2af prev_photo:Photo new_photo:Photo = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleInvites#1b7907ae new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleSignatures#26ae0971 new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionUpdatePinned#e9e82c18 message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionEditMessage#709b2405 prev_message:Message new_message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionDeleteMessage#42e047bb message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantJoin#183040d3 = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantLeave#f89777f2 = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantInvite#e31c34d8 participant:ChannelParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantToggleBan#e6d83d7e prev_participant:ChannelParticipant new_participant:ChannelParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantToggleAdmin#d5676710 prev_participant:ChannelParticipant new_participant:ChannelParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeStickerSet#b1c3caa7 prev_stickerset:InputStickerSet new_stickerset:InputStickerSet = ChannelAdminLogEventAction;\nchannelAdminLogEventActionTogglePreHistoryHidden#5f5c95f1 new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionDefaultBannedRights#2df5fc0a prev_banned_rights:ChatBannedRights new_banned_rights:ChatBannedRights = ChannelAdminLogEventAction;\nchannelAdminLogEventActionStopPoll#8f079643 message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeLinkedChat#50c7ac8 prev_value:long new_value:long = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeLocation#e6b76ae prev_value:ChannelLocation new_value:ChannelLocation = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleSlowMode#53909779 prev_value:int new_value:int = ChannelAdminLogEventAction;\nchannelAdminLogEventActionStartGroupCall#23209745 call:InputGroupCall = ChannelAdminLogEventAction;\nchannelAdminLogEventActionDiscardGroupCall#db9f9140 call:InputGroupCall = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantMute#f92424d2 participant:GroupCallParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantUnmute#e64429c0 participant:GroupCallParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleGroupCallSetting#56d6a247 join_muted:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantJoinByInvite#5cdada77 invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionExportedInviteDelete#5a50fca4 invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionExportedInviteRevoke#410a134e invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionExportedInviteEdit#e90ebb59 prev_invite:ExportedChatInvite new_invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantVolume#3e7f6847 participant:GroupCallParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeHistoryTTL#6e941a38 prev_value:int new_value:int = ChannelAdminLogEventAction;\nchannelAdminLogEvent#1fad68cd id:long date:int user_id:long action:ChannelAdminLogEventAction = ChannelAdminLogEvent;\nchannels.adminLogResults#ed8af74d events:Vector chats:Vector users:Vector = channels.AdminLogResults;\nchannelAdminLogEventsFilter#ea107ae4 flags:# join:flags.0?true leave:flags.1?true invite:flags.2?true ban:flags.3?true unban:flags.4?true kick:flags.5?true unkick:flags.6?true promote:flags.7?true demote:flags.8?true info:flags.9?true settings:flags.10?true pinned:flags.11?true edit:flags.12?true delete:flags.13?true group_call:flags.14?true invites:flags.15?true = ChannelAdminLogEventsFilter;\npopularContact#5ce14175 client_id:long importers:int = PopularContact;\nmessages.favedStickersNotModified#9e8fa6d3 = messages.FavedStickers;\nmessages.favedStickers#2cb51097 hash:long packs:Vector stickers:Vector = messages.FavedStickers;\nrecentMeUrlUnknown#46e1d13d url:string = RecentMeUrl;\nrecentMeUrlUser#b92c09e2 url:string user_id:long = RecentMeUrl;\nrecentMeUrlChat#b2da71d2 url:string chat_id:long = RecentMeUrl;\nrecentMeUrlChatInvite#eb49081d url:string chat_invite:ChatInvite = RecentMeUrl;\nrecentMeUrlStickerSet#bc0a57dc url:string set:StickerSetCovered = RecentMeUrl;\nhelp.recentMeUrls#e0310d7 urls:Vector chats:Vector users:Vector = help.RecentMeUrls;\ninputSingleMedia#1cc6e91f flags:# media:InputMedia random_id:long message:string entities:flags.0?Vector = InputSingleMedia;\nwebAuthorization#a6f8f452 hash:long bot_id:long domain:string browser:string platform:string date_created:int date_active:int ip:string region:string = WebAuthorization;\naccount.webAuthorizations#ed56c9fc authorizations:Vector users:Vector = account.WebAuthorizations;\ninputMessageID#a676a322 id:int = InputMessage;\ninputMessageReplyTo#bad88395 id:int = InputMessage;\ninputMessagePinned#86872538 = InputMessage;\ninputMessageCallbackQuery#acfa1a7e id:int query_id:long = InputMessage;\ninputDialogPeer#fcaafeb7 peer:InputPeer = InputDialogPeer;\ninputDialogPeerFolder#64600527 folder_id:int = InputDialogPeer;\ndialogPeer#e56dbf05 peer:Peer = DialogPeer;\ndialogPeerFolder#514519e2 folder_id:int = DialogPeer;\nmessages.foundStickerSetsNotModified#d54b65d = messages.FoundStickerSets;\nmessages.foundStickerSets#8af09dd2 hash:long sets:Vector = messages.FoundStickerSets;\nfileHash#6242c773 offset:int limit:int hash:bytes = FileHash;\ninputClientProxy#75588b3f address:string port:int = InputClientProxy;\nhelp.termsOfServiceUpdateEmpty#e3309f7f expires:int = help.TermsOfServiceUpdate;\nhelp.termsOfServiceUpdate#28ecf961 expires:int terms_of_service:help.TermsOfService = help.TermsOfServiceUpdate;\ninputSecureFileUploaded#3334b0f0 id:long parts:int md5_checksum:string file_hash:bytes secret:bytes = InputSecureFile;\ninputSecureFile#5367e5be id:long access_hash:long = InputSecureFile;\nsecureFileEmpty#64199744 = SecureFile;\nsecureFile#e0277a62 id:long access_hash:long size:int dc_id:int date:int file_hash:bytes secret:bytes = SecureFile;\nsecureData#8aeabec3 data:bytes data_hash:bytes secret:bytes = SecureData;\nsecurePlainPhone#7d6099dd phone:string = SecurePlainData;\nsecurePlainEmail#21ec5a5f email:string = SecurePlainData;\nsecureValueTypePersonalDetails#9d2a81e3 = SecureValueType;\nsecureValueTypePassport#3dac6a00 = SecureValueType;\nsecureValueTypeDriverLicense#6e425c4 = SecureValueType;\nsecureValueTypeIdentityCard#a0d0744b = SecureValueType;\nsecureValueTypeInternalPassport#99a48f23 = SecureValueType;\nsecureValueTypeAddress#cbe31e26 = SecureValueType;\nsecureValueTypeUtilityBill#fc36954e = SecureValueType;\nsecureValueTypeBankStatement#89137c0d = SecureValueType;\nsecureValueTypeRentalAgreement#8b883488 = SecureValueType;\nsecureValueTypePassportRegistration#99e3806a = SecureValueType;\nsecureValueTypeTemporaryRegistration#ea02ec33 = SecureValueType;\nsecureValueTypePhone#b320aadb = SecureValueType;\nsecureValueTypeEmail#8e3ca7ee = SecureValueType;\nsecureValue#187fa0ca flags:# type:SecureValueType data:flags.0?SecureData front_side:flags.1?SecureFile reverse_side:flags.2?SecureFile selfie:flags.3?SecureFile translation:flags.6?Vector files:flags.4?Vector plain_data:flags.5?SecurePlainData hash:bytes = SecureValue;\ninputSecureValue#db21d0a7 flags:# type:SecureValueType data:flags.0?SecureData front_side:flags.1?InputSecureFile reverse_side:flags.2?InputSecureFile selfie:flags.3?InputSecureFile translation:flags.6?Vector files:flags.4?Vector plain_data:flags.5?SecurePlainData = InputSecureValue;\nsecureValueHash#ed1ecdb0 type:SecureValueType hash:bytes = SecureValueHash;\nsecureValueErrorData#e8a40bd9 type:SecureValueType data_hash:bytes field:string text:string = SecureValueError;\nsecureValueErrorFrontSide#be3dfa type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorReverseSide#868a2aa5 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorSelfie#e537ced6 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorFile#7a700873 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorFiles#666220e9 type:SecureValueType file_hash:Vector text:string = SecureValueError;\nsecureValueError#869d758f type:SecureValueType hash:bytes text:string = SecureValueError;\nsecureValueErrorTranslationFile#a1144770 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorTranslationFiles#34636dd8 type:SecureValueType file_hash:Vector text:string = SecureValueError;\nsecureCredentialsEncrypted#33f0ea47 data:bytes hash:bytes secret:bytes = SecureCredentialsEncrypted;\naccount.authorizationForm#ad2e1cd8 flags:# required_types:Vector values:Vector errors:Vector users:Vector privacy_policy_url:flags.0?string = account.AuthorizationForm;\naccount.sentEmailCode#811f854f email_pattern:string length:int = account.SentEmailCode;\nhelp.deepLinkInfoEmpty#66afa166 = help.DeepLinkInfo;\nhelp.deepLinkInfo#6a4ee832 flags:# update_app:flags.0?true message:string entities:flags.1?Vector = help.DeepLinkInfo;\nsavedPhoneContact#1142bd56 phone:string first_name:string last_name:string date:int = SavedContact;\naccount.takeout#4dba4501 id:long = account.Takeout;\npasswordKdfAlgoUnknown#d45ab096 = PasswordKdfAlgo;\npasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow#3a912d4a salt1:bytes salt2:bytes g:int p:bytes = PasswordKdfAlgo;\nsecurePasswordKdfAlgoUnknown#4a8537 = SecurePasswordKdfAlgo;\nsecurePasswordKdfAlgoPBKDF2HMACSHA512iter100000#bbf2dda0 salt:bytes = SecurePasswordKdfAlgo;\nsecurePasswordKdfAlgoSHA512#86471d92 salt:bytes = SecurePasswordKdfAlgo;\nsecureSecretSettings#1527bcac secure_algo:SecurePasswordKdfAlgo secure_secret:bytes secure_secret_id:long = SecureSecretSettings;\ninputCheckPasswordEmpty#9880f658 = InputCheckPasswordSRP;\ninputCheckPasswordSRP#d27ff082 srp_id:long A:bytes M1:bytes = InputCheckPasswordSRP;\nsecureRequiredType#829d99da flags:# native_names:flags.0?true selfie_required:flags.1?true translation_required:flags.2?true type:SecureValueType = SecureRequiredType;\nsecureRequiredTypeOneOf#27477b4 types:Vector = SecureRequiredType;\nhelp.passportConfigNotModified#bfb9f457 = help.PassportConfig;\nhelp.passportConfig#a098d6af hash:int countries_langs:DataJSON = help.PassportConfig;\ninputAppEvent#1d1b1245 time:double type:string peer:long data:JSONValue = InputAppEvent;\njsonObjectValue#c0de1bd9 key:string value:JSONValue = JSONObjectValue;\njsonNull#3f6d7b68 = JSONValue;\njsonBool#c7345e6a value:Bool = JSONValue;\njsonNumber#2be0dfa4 value:double = JSONValue;\njsonString#b71e767a value:string = JSONValue;\njsonArray#f7444763 value:Vector = JSONValue;\njsonObject#99c1d49d value:Vector = JSONValue;\npageTableCell#34566b6a flags:# header:flags.0?true align_center:flags.3?true align_right:flags.4?true valign_middle:flags.5?true valign_bottom:flags.6?true text:flags.7?RichText colspan:flags.1?int rowspan:flags.2?int = PageTableCell;\npageTableRow#e0c0c5e5 cells:Vector = PageTableRow;\npageCaption#6f747657 text:RichText credit:RichText = PageCaption;\npageListItemText#b92fb6cd text:RichText = PageListItem;\npageListItemBlocks#25e073fc blocks:Vector = PageListItem;\npageListOrderedItemText#5e068047 num:string text:RichText = PageListOrderedItem;\npageListOrderedItemBlocks#98dd8936 num:string blocks:Vector = PageListOrderedItem;\npageRelatedArticle#b390dc08 flags:# url:string webpage_id:long title:flags.0?string description:flags.1?string photo_id:flags.2?long author:flags.3?string published_date:flags.4?int = PageRelatedArticle;\npage#98657f0d flags:# part:flags.0?true rtl:flags.1?true v2:flags.2?true url:string blocks:Vector photos:Vector documents:Vector views:flags.3?int = Page;\nhelp.supportName#8c05f1c9 name:string = help.SupportName;\nhelp.userInfoEmpty#f3ae2eed = help.UserInfo;\nhelp.userInfo#1eb3758 message:string entities:Vector author:string date:int = help.UserInfo;\npollAnswer#6ca9c2e9 text:string option:bytes = PollAnswer;\npoll#86e18161 id:long flags:# closed:flags.0?true public_voters:flags.1?true multiple_choice:flags.2?true quiz:flags.3?true question:string answers:Vector close_period:flags.4?int close_date:flags.5?int = Poll;\npollAnswerVoters#3b6ddad2 flags:# chosen:flags.0?true correct:flags.1?true option:bytes voters:int = PollAnswerVoters;\npollResults#dcb82ea3 flags:# min:flags.0?true results:flags.1?Vector total_voters:flags.2?int recent_voters:flags.3?Vector solution:flags.4?string solution_entities:flags.4?Vector = PollResults;\nchatOnlines#f041e250 onlines:int = ChatOnlines;\nstatsURL#47a971e0 url:string = StatsURL;\nchatAdminRights#5fb224d5 flags:# change_info:flags.0?true post_messages:flags.1?true edit_messages:flags.2?true delete_messages:flags.3?true ban_users:flags.4?true invite_users:flags.5?true pin_messages:flags.7?true add_admins:flags.9?true anonymous:flags.10?true manage_call:flags.11?true other:flags.12?true = ChatAdminRights;\nchatBannedRights#9f120418 flags:# view_messages:flags.0?true send_messages:flags.1?true send_media:flags.2?true send_stickers:flags.3?true send_gifs:flags.4?true send_games:flags.5?true send_inline:flags.6?true embed_links:flags.7?true send_polls:flags.8?true change_info:flags.10?true invite_users:flags.15?true pin_messages:flags.17?true until_date:int = ChatBannedRights;\ninputWallPaper#e630b979 id:long access_hash:long = InputWallPaper;\ninputWallPaperSlug#72091c80 slug:string = InputWallPaper;\ninputWallPaperNoFile#967a462e id:long = InputWallPaper;\naccount.wallPapersNotModified#1c199183 = account.WallPapers;\naccount.wallPapers#cdc3858c hash:long wallpapers:Vector = account.WallPapers;\ncodeSettings#debebe83 flags:# allow_flashcall:flags.0?true current_number:flags.1?true allow_app_hash:flags.4?true = CodeSettings;\nwallPaperSettings#1dc1bca4 flags:# blur:flags.1?true motion:flags.2?true background_color:flags.0?int second_background_color:flags.4?int third_background_color:flags.5?int fourth_background_color:flags.6?int intensity:flags.3?int rotation:flags.4?int = WallPaperSettings;\nautoDownloadSettings#e04232f3 flags:# disabled:flags.0?true video_preload_large:flags.1?true audio_preload_next:flags.2?true phonecalls_less_data:flags.3?true photo_size_max:int video_size_max:int file_size_max:int video_upload_maxbitrate:int = AutoDownloadSettings;\naccount.autoDownloadSettings#63cacf26 low:AutoDownloadSettings medium:AutoDownloadSettings high:AutoDownloadSettings = account.AutoDownloadSettings;\nemojiKeyword#d5b3b9f9 keyword:string emoticons:Vector = EmojiKeyword;\nemojiKeywordDeleted#236df622 keyword:string emoticons:Vector = EmojiKeyword;\nemojiKeywordsDifference#5cc761bd lang_code:string from_version:int version:int keywords:Vector = EmojiKeywordsDifference;\nemojiURL#a575739d url:string = EmojiURL;\nemojiLanguage#b3fb5361 lang_code:string = EmojiLanguage;\nfolder#ff544e65 flags:# autofill_new_broadcasts:flags.0?true autofill_public_groups:flags.1?true autofill_new_correspondents:flags.2?true id:int title:string photo:flags.3?ChatPhoto = Folder;\ninputFolderPeer#fbd2c296 peer:InputPeer folder_id:int = InputFolderPeer;\nfolderPeer#e9baa668 peer:Peer folder_id:int = FolderPeer;\nmessages.searchCounter#e844ebff flags:# inexact:flags.1?true filter:MessagesFilter count:int = messages.SearchCounter;\nurlAuthResultRequest#92d33a0e flags:# request_write_access:flags.0?true bot:User domain:string = UrlAuthResult;\nurlAuthResultAccepted#8f8c0e4e url:string = UrlAuthResult;\nurlAuthResultDefault#a9d6db1f = UrlAuthResult;\nchannelLocationEmpty#bfb5ad8b = ChannelLocation;\nchannelLocation#209b82db geo_point:GeoPoint address:string = ChannelLocation;\npeerLocated#ca461b5d peer:Peer expires:int distance:int = PeerLocated;\npeerSelfLocated#f8ec284b expires:int = PeerLocated;\nrestrictionReason#d072acb4 platform:string reason:string text:string = RestrictionReason;\ninputTheme#3c5693e9 id:long access_hash:long = InputTheme;\ninputThemeSlug#f5890df1 slug:string = InputTheme;\ntheme#e802b8dc 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?ThemeSettings installs_count:flags.4?int = Theme;\naccount.themesNotModified#f41eb622 = account.Themes;\naccount.themes#9a3d8c6d hash:long themes:Vector = account.Themes;\nauth.loginToken#629f1980 expires:int token:bytes = auth.LoginToken;\nauth.loginTokenMigrateTo#68e9916 dc_id:int token:bytes = auth.LoginToken;\nauth.loginTokenSuccess#390d5c5e authorization:auth.Authorization = auth.LoginToken;\naccount.contentSettings#57e28221 flags:# sensitive_enabled:flags.0?true sensitive_can_change:flags.1?true = account.ContentSettings;\nmessages.inactiveChats#a927fec5 dates:Vector chats:Vector users:Vector = messages.InactiveChats;\nbaseThemeClassic#c3a12462 = BaseTheme;\nbaseThemeDay#fbd81688 = BaseTheme;\nbaseThemeNight#b7b31ea8 = BaseTheme;\nbaseThemeTinted#6d5f77ee = BaseTheme;\nbaseThemeArctic#5b11125a = BaseTheme;\ninputThemeSettings#8fde504f flags:# message_colors_animated:flags.2?true base_theme:BaseTheme accent_color:int outbox_accent_color:flags.3?int message_colors:flags.0?Vector wallpaper:flags.1?InputWallPaper wallpaper_settings:flags.1?WallPaperSettings = InputThemeSettings;\nthemeSettings#fa58b6d4 flags:# message_colors_animated:flags.2?true base_theme:BaseTheme accent_color:int outbox_accent_color:flags.3?int message_colors:flags.0?Vector wallpaper:flags.1?WallPaper = ThemeSettings;\nwebPageAttributeTheme#54b56617 flags:# documents:flags.0?Vector settings:flags.1?ThemeSettings = WebPageAttribute;\nmessageUserVote#34d247b4 user_id:long option:bytes date:int = MessageUserVote;\nmessageUserVoteInputOption#3ca5b0ec user_id:long date:int = MessageUserVote;\nmessageUserVoteMultiple#8a65e557 user_id:long options:Vector date:int = MessageUserVote;\nmessages.votesList#823f649 flags:# count:int votes:Vector users:Vector next_offset:flags.0?string = messages.VotesList;\nbankCardOpenUrl#f568028a url:string name:string = BankCardOpenUrl;\npayments.bankCardData#3e24e573 title:string open_urls:Vector = payments.BankCardData;\ndialogFilter#7438f7e8 flags:# contacts:flags.0?true non_contacts:flags.1?true groups:flags.2?true broadcasts:flags.3?true bots:flags.4?true exclude_muted:flags.11?true exclude_read:flags.12?true exclude_archived:flags.13?true id:int title:string emoticon:flags.25?string pinned_peers:Vector include_peers:Vector exclude_peers:Vector = DialogFilter;\ndialogFilterSuggested#77744d4a filter:DialogFilter description:string = DialogFilterSuggested;\nstatsDateRangeDays#b637edaf min_date:int max_date:int = StatsDateRangeDays;\nstatsAbsValueAndPrev#cb43acde current:double previous:double = StatsAbsValueAndPrev;\nstatsPercentValue#cbce2fe0 part:double total:double = StatsPercentValue;\nstatsGraphAsync#4a27eb2d token:string = StatsGraph;\nstatsGraphError#bedc9822 error:string = StatsGraph;\nstatsGraph#8ea464b6 flags:# json:DataJSON zoom_token:flags.0?string = StatsGraph;\nmessageInteractionCounters#ad4fc9bd msg_id:int views:int forwards:int = MessageInteractionCounters;\nstats.broadcastStats#bdf78394 period:StatsDateRangeDays followers:StatsAbsValueAndPrev views_per_post:StatsAbsValueAndPrev shares_per_post:StatsAbsValueAndPrev enabled_notifications:StatsPercentValue growth_graph:StatsGraph followers_graph:StatsGraph mute_graph:StatsGraph top_hours_graph:StatsGraph interactions_graph:StatsGraph iv_interactions_graph:StatsGraph views_by_source_graph:StatsGraph new_followers_by_source_graph:StatsGraph languages_graph:StatsGraph recent_message_interactions:Vector = stats.BroadcastStats;\nhelp.promoDataEmpty#98f6ac75 expires:int = help.PromoData;\nhelp.promoData#8c39793f flags:# proxy:flags.0?true expires:int peer:Peer chats:Vector users:Vector psa_type:flags.1?string psa_message:flags.2?string = help.PromoData;\nvideoSize#de33b094 flags:# type:string w:int h:int size:int video_start_ts:flags.0?double = VideoSize;\nstatsGroupTopPoster#9d04af9b user_id:long messages:int avg_chars:int = StatsGroupTopPoster;\nstatsGroupTopAdmin#d7584c87 user_id:long deleted:int kicked:int banned:int = StatsGroupTopAdmin;\nstatsGroupTopInviter#535f779d user_id:long invitations:int = StatsGroupTopInviter;\nstats.megagroupStats#ef7ff916 period:StatsDateRangeDays members:StatsAbsValueAndPrev messages:StatsAbsValueAndPrev viewers:StatsAbsValueAndPrev posters:StatsAbsValueAndPrev growth_graph:StatsGraph members_graph:StatsGraph new_members_by_source_graph:StatsGraph languages_graph:StatsGraph messages_graph:StatsGraph actions_graph:StatsGraph top_hours_graph:StatsGraph weekdays_graph:StatsGraph top_posters:Vector top_admins:Vector top_inviters:Vector users:Vector = stats.MegagroupStats;\nglobalPrivacySettings#bea2f424 flags:# archive_and_mute_new_noncontact_peers:flags.0?Bool = GlobalPrivacySettings;\nhelp.countryCode#4203c5ef flags:# country_code:string prefixes:flags.0?Vector patterns:flags.1?Vector = help.CountryCode;\nhelp.country#c3878e23 flags:# hidden:flags.0?true iso2:string default_name:string name:flags.1?string country_codes:Vector = help.Country;\nhelp.countriesListNotModified#93cc1f32 = help.CountriesList;\nhelp.countriesList#87d0759e countries:Vector hash:int = help.CountriesList;\nmessageViews#455b853d flags:# views:flags.0?int forwards:flags.1?int replies:flags.2?MessageReplies = MessageViews;\nmessages.messageViews#b6c4f543 views:Vector chats:Vector users:Vector = messages.MessageViews;\nmessages.discussionMessage#a6341782 flags:# messages:Vector max_id:flags.0?int read_inbox_max_id:flags.1?int read_outbox_max_id:flags.2?int unread_count:int chats:Vector users:Vector = messages.DiscussionMessage;\nmessageReplyHeader#a6d57763 flags:# reply_to_msg_id:int reply_to_peer_id:flags.0?Peer reply_to_top_id:flags.1?int = MessageReplyHeader;\nmessageReplies#83d60fc2 flags:# comments:flags.0?true replies:int replies_pts:int recent_repliers:flags.1?Vector channel_id:flags.0?long max_id:flags.2?int read_max_id:flags.3?int = MessageReplies;\npeerBlocked#e8fd8014 peer_id:Peer date:int = PeerBlocked;\nstats.messageStats#8999f295 views_graph:StatsGraph = stats.MessageStats;\ngroupCallDiscarded#7780bcb4 id:long access_hash:long duration:int = GroupCall;\ngroupCall#d597650c flags:# join_muted:flags.1?true can_change_join_muted:flags.2?true join_date_asc:flags.6?true schedule_start_subscribed:flags.8?true can_start_video:flags.9?true record_video_active:flags.11?true id:long access_hash:long participants_count:int title:flags.3?string stream_dc_id:flags.4?int record_start_date:flags.5?int schedule_date:flags.7?int unmuted_video_count:flags.10?int unmuted_video_limit:int version:int = GroupCall;\ninputGroupCall#d8aa840f id:long access_hash:long = InputGroupCall;\ngroupCallParticipant#eba636fe flags:# muted:flags.0?true left:flags.1?true can_self_unmute:flags.2?true just_joined:flags.4?true versioned:flags.5?true min:flags.8?true muted_by_you:flags.9?true volume_by_admin:flags.10?true self:flags.12?true video_joined:flags.15?true peer:Peer date:int active_date:flags.3?int source:int volume:flags.7?int about:flags.11?string raise_hand_rating:flags.13?long video:flags.6?GroupCallParticipantVideo presentation:flags.14?GroupCallParticipantVideo = GroupCallParticipant;\nphone.groupCall#9e727aad call:GroupCall participants:Vector participants_next_offset:string chats:Vector users:Vector = phone.GroupCall;\nphone.groupParticipants#f47751b6 count:int participants:Vector next_offset:string chats:Vector users:Vector version:int = phone.GroupParticipants;\ninlineQueryPeerTypeSameBotPM#3081ed9d = InlineQueryPeerType;\ninlineQueryPeerTypePM#833c0fac = InlineQueryPeerType;\ninlineQueryPeerTypeChat#d766c50a = InlineQueryPeerType;\ninlineQueryPeerTypeMegagroup#5ec4be43 = InlineQueryPeerType;\ninlineQueryPeerTypeBroadcast#6334ee9a = InlineQueryPeerType;\nmessages.historyImport#1662af0b id:long = messages.HistoryImport;\nmessages.historyImportParsed#5e0fb7b9 flags:# pm:flags.0?true group:flags.1?true title:flags.2?string = messages.HistoryImportParsed;\nmessages.affectedFoundMessages#ef8d3e6c pts:int pts_count:int offset:int messages:Vector = messages.AffectedFoundMessages;\nchatInviteImporter#b5cd5f4 user_id:long date:int = ChatInviteImporter;\nmessages.exportedChatInvites#bdc62dcc count:int invites:Vector users:Vector = messages.ExportedChatInvites;\nmessages.exportedChatInvite#1871be50 invite:ExportedChatInvite users:Vector = messages.ExportedChatInvite;\nmessages.exportedChatInviteReplaced#222600ef invite:ExportedChatInvite new_invite:ExportedChatInvite users:Vector = messages.ExportedChatInvite;\nmessages.chatInviteImporters#81b6b00a count:int importers:Vector users:Vector = messages.ChatInviteImporters;\nchatAdminWithInvites#f2ecef23 admin_id:long invites_count:int revoked_invites_count:int = ChatAdminWithInvites;\nmessages.chatAdminsWithInvites#b69b72d7 admins:Vector users:Vector = messages.ChatAdminsWithInvites;\nmessages.checkedHistoryImportPeer#a24de717 confirm_text:string = messages.CheckedHistoryImportPeer;\nphone.joinAsPeers#afe5623f peers:Vector chats:Vector users:Vector = phone.JoinAsPeers;\nphone.exportedGroupCallInvite#204bd158 link:string = phone.ExportedGroupCallInvite;\ngroupCallParticipantVideoSourceGroup#dcb118b7 semantics:string sources:Vector = GroupCallParticipantVideoSourceGroup;\ngroupCallParticipantVideo#67753ac8 flags:# paused:flags.0?true endpoint:string source_groups:Vector audio_source:flags.1?int = GroupCallParticipantVideo;\nstickers.suggestedShortName#85fea03f short_name:string = stickers.SuggestedShortName;\nbotCommandScopeDefault#2f6cb2ab = BotCommandScope;\nbotCommandScopeUsers#3c4f04d8 = BotCommandScope;\nbotCommandScopeChats#6fe1a881 = BotCommandScope;\nbotCommandScopeChatAdmins#b9aa606a = BotCommandScope;\nbotCommandScopePeer#db9d897d peer:InputPeer = BotCommandScope;\nbotCommandScopePeerAdmins#3fd863d1 peer:InputPeer = BotCommandScope;\nbotCommandScopePeerUser#a1321f3 peer:InputPeer user_id:InputUser = BotCommandScope;\naccount.resetPasswordFailedWait#e3779861 retry_date:int = account.ResetPasswordResult;\naccount.resetPasswordRequestedWait#e9effc7d until_date:int = account.ResetPasswordResult;\naccount.resetPasswordOk#e926d63e = account.ResetPasswordResult;\nchatTheme#ed0b5c33 emoticon:string theme:Theme dark_theme:Theme = ChatTheme;\naccount.chatThemesNotModified#e011e1c4 = account.ChatThemes;\naccount.chatThemes#fe4cbebd hash:int themes:Vector = account.ChatThemes;\nsponsoredMessage#2a3c381f flags:# random_id:bytes from_id:Peer start_param:flags.0?string message:string entities:flags.1?Vector = SponsoredMessage;\nmessages.sponsoredMessages#65a4c7d5 messages:Vector chats:Vector users:Vector = messages.SponsoredMessages;\n---functions---\ninitConnection#c1cd5ea9 {X:Type} flags:# api_id:int device_model:string system_version:string app_version:string system_lang_code:string lang_pack:string lang_code:string proxy:flags.0?InputClientProxy params:flags.1?JSONValue query:!X = X;\ninvokeWithLayer#da9b0d0d {X:Type} layer:int query:!X = X;\nauth.sendCode#a677244f phone_number:string api_id:int api_hash:string settings:CodeSettings = auth.SentCode;\nauth.signUp#80eee427 phone_number:string phone_code_hash:string first_name:string last_name:string = auth.Authorization;\nauth.signIn#bcd51581 phone_number:string phone_code_hash:string phone_code:string = auth.Authorization;\nauth.logOut#5717da40 = Bool;\nauth.resetAuthorizations#9fab0d1a = Bool;\nauth.exportAuthorization#e5bfffcd dc_id:int = auth.ExportedAuthorization;\nauth.importAuthorization#a57a7dad id:long bytes:bytes = auth.Authorization;\nauth.bindTempAuthKey#cdd42a05 perm_auth_key_id:long nonce:long expires_at:int encrypted_message:bytes = Bool;\nauth.checkPassword#d18b4d16 password:InputCheckPasswordSRP = auth.Authorization;\nauth.requestPasswordRecovery#d897bc66 = auth.PasswordRecovery;\nauth.resendCode#3ef1a9bf phone_number:string phone_code_hash:string = auth.SentCode;\nauth.cancelCode#1f040578 phone_number:string phone_code_hash:string = Bool;\nauth.dropTempAuthKeys#8e48a188 except_auth_keys:Vector = Bool;\nauth.exportLoginToken#b7e085fe api_id:int api_hash:string except_ids:Vector = auth.LoginToken;\nauth.importLoginToken#95ac5ce4 token:bytes = auth.LoginToken;\naccount.registerDevice#ec86017a flags:# no_muted:flags.0?true token_type:int token:string app_sandbox:Bool secret:bytes other_uids:Vector = Bool;\naccount.unregisterDevice#6a0d3206 token_type:int token:string other_uids:Vector = Bool;\naccount.updateNotifySettings#84be5b93 peer:InputNotifyPeer settings:InputPeerNotifySettings = Bool;\naccount.getNotifySettings#12b3ad31 peer:InputNotifyPeer = PeerNotifySettings;\naccount.updateProfile#78515775 flags:# first_name:flags.0?string last_name:flags.1?string about:flags.2?string = User;\naccount.updateStatus#6628562c offline:Bool = Bool;\naccount.getWallPapers#7967d36 hash:long = account.WallPapers;\naccount.checkUsername#2714d86c username:string = Bool;\naccount.updateUsername#3e0bdd7c username:string = User;\naccount.getPrivacy#dadbc950 key:InputPrivacyKey = account.PrivacyRules;\naccount.setPrivacy#c9f81ce8 key:InputPrivacyKey rules:Vector = account.PrivacyRules;\naccount.getAuthorizations#e320c158 = account.Authorizations;\naccount.resetAuthorization#df77f3bc hash:long = Bool;\naccount.getPassword#548a30f5 = account.Password;\naccount.getPasswordSettings#9cd4eaf9 password:InputCheckPasswordSRP = account.PasswordSettings;\naccount.updatePasswordSettings#a59b102f password:InputCheckPasswordSRP new_settings:account.PasswordInputSettings = Bool;\naccount.sendConfirmPhoneCode#1b3faa88 hash:string settings:CodeSettings = auth.SentCode;\naccount.confirmPhone#5f2178c3 phone_code_hash:string phone_code:string = Bool;\naccount.getTmpPassword#449e0b51 password:InputCheckPasswordSRP period:int = account.TmpPassword;\naccount.sendVerifyPhoneCode#a5a356f9 phone_number:string settings:CodeSettings = auth.SentCode;\naccount.confirmPasswordEmail#8fdf1920 code:string = Bool;\naccount.getContactSignUpNotification#9f07c728 = Bool;\naccount.setContactSignUpNotification#cff43f61 silent:Bool = Bool;\naccount.getNotifyExceptions#53577479 flags:# compare_sound:flags.1?true peer:flags.0?InputNotifyPeer = Updates;\naccount.uploadWallPaper#dd853661 file:InputFile mime_type:string settings:WallPaperSettings = WallPaper;\naccount.setContentSettings#b574b16b flags:# sensitive_enabled:flags.0?true = Bool;\naccount.getContentSettings#8b9b4dae = account.ContentSettings;\nusers.getUsers#d91a548 id:Vector = Vector;\nusers.getFullUser#ca30a5b1 id:InputUser = UserFull;\ncontacts.getContacts#5dd69e12 hash:long = contacts.Contacts;\ncontacts.importContacts#2c800be5 contacts:Vector = contacts.ImportedContacts;\ncontacts.deleteContacts#96a0e00 id:Vector = Updates;\ncontacts.block#68cc1411 id:InputPeer = Bool;\ncontacts.unblock#bea65d50 id:InputPeer = Bool;\ncontacts.getBlocked#f57c350f offset:int limit:int = contacts.Blocked;\ncontacts.search#11f812d8 q:string limit:int = contacts.Found;\ncontacts.resolveUsername#f93ccba3 username:string = contacts.ResolvedPeer;\ncontacts.getTopPeers#973478b6 flags:# correspondents:flags.0?true bots_pm:flags.1?true bots_inline:flags.2?true phone_calls:flags.3?true forward_users:flags.4?true forward_chats:flags.5?true groups:flags.10?true channels:flags.15?true offset:int limit:int hash:long = contacts.TopPeers;\ncontacts.addContact#e8f463d0 flags:# add_phone_privacy_exception:flags.0?true id:InputUser first_name:string last_name:string phone:string = Updates;\nmessages.getMessages#63c66506 id:Vector = messages.Messages;\nmessages.getDialogs#a0f4cb4f flags:# exclude_pinned:flags.0?true folder_id:flags.1?int offset_date:int offset_id:int offset_peer:InputPeer limit:int hash:long = messages.Dialogs;\nmessages.getHistory#4423e6c5 peer:InputPeer offset_id:int offset_date:int add_offset:int limit:int max_id:int min_id:int hash:long = messages.Messages;\nmessages.search#a0fda762 flags:# peer:InputPeer q:string from_id:flags.0?InputPeer top_msg_id:flags.1?int filter:MessagesFilter min_date:int max_date:int offset_id:int add_offset:int limit:int max_id:int min_id:int hash:long = messages.Messages;\nmessages.readHistory#e306d3a peer:InputPeer max_id:int = messages.AffectedMessages;\nmessages.deleteHistory#1c015b09 flags:# just_clear:flags.0?true revoke:flags.1?true peer:InputPeer max_id:int = messages.AffectedHistory;\nmessages.deleteMessages#e58e95d2 flags:# revoke:flags.0?true id:Vector = messages.AffectedMessages;\nmessages.receivedMessages#5a954c0 max_id:int = Vector;\nmessages.setTyping#58943ee2 flags:# peer:InputPeer top_msg_id:flags.0?int action:SendMessageAction = Bool;\nmessages.sendMessage#520c3870 flags:# no_webpage:flags.1?true silent:flags.5?true background:flags.6?true clear_draft:flags.7?true peer:InputPeer reply_to_msg_id:flags.0?int message:string random_id:long reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector schedule_date:flags.10?int = Updates;\nmessages.sendMedia#3491eba9 flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true peer:InputPeer reply_to_msg_id:flags.0?int media:InputMedia message:string random_id:long reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector schedule_date:flags.10?int = Updates;\nmessages.forwardMessages#d9fee60e 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 from_peer:InputPeer id:Vector random_id:Vector to_peer:InputPeer schedule_date:flags.10?int = Updates;\nmessages.report#8953ab4e peer:InputPeer id:Vector reason:ReportReason message:string = Bool;\nmessages.getChats#49e9528f id:Vector = messages.Chats;\nmessages.getFullChat#aeb00b34 chat_id:long = messages.ChatFull;\nmessages.editChatTitle#73783ffd chat_id:long title:string = Updates;\nmessages.editChatPhoto#35ddd674 chat_id:long photo:InputChatPhoto = Updates;\nmessages.addChatUser#f24753e3 chat_id:long user_id:InputUser fwd_limit:int = Updates;\nmessages.deleteChatUser#a2185cab flags:# revoke_history:flags.0?true chat_id:long user_id:InputUser = Updates;\nmessages.createChat#9cb126e users:Vector title:string = Updates;\nmessages.getDhConfig#26cf8950 version:int random_length:int = messages.DhConfig;\nmessages.readMessageContents#36a73f77 id:Vector = messages.AffectedMessages;\nmessages.getStickers#d5a5d3a1 emoticon:string hash:long = messages.Stickers;\nmessages.getAllStickers#b8a0a1a8 hash:long = messages.AllStickers;\nmessages.getWebPagePreview#8b68b0cc flags:# message:string entities:flags.3?Vector = MessageMedia;\nmessages.exportChatInvite#14b9bcd7 flags:# legacy_revoke_permanent:flags.2?true peer:InputPeer expire_date:flags.0?int usage_limit:flags.1?int = ExportedChatInvite;\nmessages.checkChatInvite#3eadb1bb hash:string = ChatInvite;\nmessages.importChatInvite#6c50051c hash:string = Updates;\nmessages.getStickerSet#2619a90e stickerset:InputStickerSet = messages.StickerSet;\nmessages.installStickerSet#c78fe460 stickerset:InputStickerSet archived:Bool = messages.StickerSetInstallResult;\nmessages.uninstallStickerSet#f96e55de stickerset:InputStickerSet = Bool;\nmessages.startBot#e6df7378 bot:InputUser peer:InputPeer random_id:long start_param:string = Updates;\nmessages.migrateChat#a2875319 chat_id:long = Updates;\nmessages.searchGlobal#4bc6589a flags:# folder_id:flags.0?int q:string filter:MessagesFilter min_date:int max_date:int offset_rate:int offset_peer:InputPeer offset_id:int limit:int = messages.Messages;\nmessages.getDocumentByHash#338e2464 sha256:bytes size:int mime_type:string = Document;\nmessages.getSavedGifs#5cf09635 hash:long = messages.SavedGifs;\nmessages.getInlineBotResults#514e999d flags:# bot:InputUser peer:InputPeer geo_point:flags.0?InputGeoPoint query:string offset:string = messages.BotResults;\nmessages.sendInlineBotResult#220815b0 flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true hide_via:flags.11?true peer:InputPeer reply_to_msg_id:flags.0?int random_id:long query_id:long id:string schedule_date:flags.10?int = Updates;\nmessages.editMessage#48f71778 flags:# no_webpage:flags.1?true peer:InputPeer id:int message:flags.11?string media:flags.14?InputMedia reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector schedule_date:flags.15?int = Updates;\nmessages.getBotCallbackAnswer#9342ca07 flags:# game:flags.1?true peer:InputPeer msg_id:int data:flags.0?bytes password:flags.2?InputCheckPasswordSRP = messages.BotCallbackAnswer;\nmessages.getPeerDialogs#e470bcfd peers:Vector = messages.PeerDialogs;\nmessages.saveDraft#bc39e14b flags:# no_webpage:flags.1?true reply_to_msg_id:flags.0?int peer:InputPeer message:string entities:flags.3?Vector = Bool;\nmessages.getFeaturedStickers#64780b14 hash:long = messages.FeaturedStickers;\nmessages.readFeaturedStickers#5b118126 id:Vector = Bool;\nmessages.getRecentStickers#9da9403b flags:# attached:flags.0?true hash:long = messages.RecentStickers;\nmessages.getCommonChats#e40ca104 user_id:InputUser max_id:long limit:int = messages.Chats;\nmessages.getWebPage#32ca8f91 url:string hash:int = WebPage;\nmessages.toggleDialogPin#a731e257 flags:# pinned:flags.0?true peer:InputDialogPeer = Bool;\nmessages.getPinnedDialogs#d6b94df2 folder_id:int = messages.PeerDialogs;\nmessages.uploadMedia#519bc2b1 peer:InputPeer media:InputMedia = MessageMedia;\nmessages.getFavedStickers#4f1aaa9 hash:long = messages.FavedStickers;\nmessages.faveSticker#b9ffc55b id:InputDocument unfave:Bool = Bool;\nmessages.sendMultiMedia#cc0110cb flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true peer:InputPeer reply_to_msg_id:flags.0?int multi_media:Vector schedule_date:flags.10?int = Updates;\nmessages.searchStickerSets#35705b8a flags:# exclude_featured:flags.0?true q:string hash:long = messages.FoundStickerSets;\nmessages.markDialogUnread#c286d98f flags:# unread:flags.0?true peer:InputDialogPeer = Bool;\nmessages.updatePinnedMessage#d2aaf7ec flags:# silent:flags.0?true unpin:flags.1?true pm_oneside:flags.2?true peer:InputPeer id:int = Updates;\nmessages.sendVote#10ea6184 peer:InputPeer msg_id:int options:Vector = Updates;\nmessages.getOnlines#6e2be050 peer:InputPeer = ChatOnlines;\nmessages.editChatAbout#def60797 peer:InputPeer about:string = Bool;\nmessages.editChatDefaultBannedRights#a5866b41 peer:InputPeer banned_rights:ChatBannedRights = Updates;\nmessages.getEmojiKeywordsDifference#1508b6af lang_code:string from_version:int = EmojiKeywordsDifference;\nmessages.getScheduledHistory#f516760b peer:InputPeer hash:long = messages.Messages;\nmessages.sendScheduledMessages#bd38850a peer:InputPeer id:Vector = Updates;\nmessages.deleteScheduledMessages#59ae2b16 peer:InputPeer id:Vector = Updates;\nmessages.getPollVotes#b86e380e flags:# peer:InputPeer id:int option:flags.0?bytes offset:flags.1?string limit:int = messages.VotesList;\nmessages.getDialogFilters#f19ed96d = Vector;\nmessages.getSuggestedDialogFilters#a29cd42c = Vector;\nmessages.updateDialogFilter#1ad4a04a flags:# id:int filter:flags.0?DialogFilter = Bool;\nmessages.getReplies#22ddd30c peer:InputPeer msg_id:int offset_id:int offset_date:int add_offset:int limit:int max_id:int min_id:int hash:long = messages.Messages;\nmessages.getDiscussionMessage#446972fd peer:InputPeer msg_id:int = messages.DiscussionMessage;\nmessages.readDiscussion#f731a9f4 peer:InputPeer msg_id:int read_max_id:int = Bool;\nmessages.unpinAllMessages#f025bc8b peer:InputPeer = messages.AffectedHistory;\nmessages.deleteChat#5bd0ee50 chat_id:long = Bool;\nupdates.getState#edd4882a = updates.State;\nupdates.getDifference#25939651 flags:# pts:int pts_total_limit:flags.0?int date:int qts:int = updates.Difference;\nupdates.getChannelDifference#3173d78 flags:# force:flags.0?true channel:InputChannel filter:ChannelMessagesFilter pts:int limit:int = updates.ChannelDifference;\nphotos.uploadProfilePhoto#89f30f69 flags:# file:flags.0?InputFile video:flags.1?InputFile video_start_ts:flags.2?double = photos.Photo;\nphotos.getUserPhotos#91cd32a8 user_id:InputUser offset:int max_id:long limit:int = photos.Photos;\nupload.saveFilePart#b304a621 file_id:long file_part:int bytes:bytes = Bool;\nupload.getFile#b15a9afc flags:# precise:flags.0?true cdn_supported:flags.1?true location:InputFileLocation offset:int limit:int = upload.File;\nupload.saveBigFilePart#de7b673d file_id:long file_part:int file_total_parts:int bytes:bytes = Bool;\nupload.getWebFile#24e6818d location:InputWebFileLocation offset:int limit:int = upload.WebFile;\nhelp.getConfig#c4f9186b = Config;\nhelp.getNearestDc#1fb33026 = NearestDc;\nhelp.getSupport#9cdf08cd = help.Support;\nhelp.acceptTermsOfService#ee72f79a id:DataJSON = Bool;\nhelp.getCountriesList#735787a8 lang_code:string hash:int = help.CountriesList;\nchannels.readHistory#cc104937 channel:InputChannel max_id:int = Bool;\nchannels.deleteMessages#84c1fd4e channel:InputChannel id:Vector = messages.AffectedMessages;\nchannels.getMessages#ad8c9a23 channel:InputChannel id:Vector = messages.Messages;\nchannels.getParticipants#77ced9d0 channel:InputChannel filter:ChannelParticipantsFilter offset:int limit:int hash:long = channels.ChannelParticipants;\nchannels.getParticipant#a0ab6cc6 channel:InputChannel participant:InputPeer = channels.ChannelParticipant;\nchannels.getChannels#a7f6bbb id:Vector = messages.Chats;\nchannels.getFullChannel#8736a09 channel:InputChannel = messages.ChatFull;\nchannels.createChannel#3d5fb10f flags:# broadcast:flags.0?true megagroup:flags.1?true for_import:flags.3?true title:string about:string geo_point:flags.2?InputGeoPoint address:flags.2?string = Updates;\nchannels.editAdmin#d33c8902 channel:InputChannel user_id:InputUser admin_rights:ChatAdminRights rank:string = Updates;\nchannels.editTitle#566decd0 channel:InputChannel title:string = Updates;\nchannels.editPhoto#f12e57c9 channel:InputChannel photo:InputChatPhoto = Updates;\nchannels.checkUsername#10e6bd2c channel:InputChannel username:string = Bool;\nchannels.updateUsername#3514b3de channel:InputChannel username:string = Bool;\nchannels.joinChannel#24b524c5 channel:InputChannel = Updates;\nchannels.leaveChannel#f836aa95 channel:InputChannel = Updates;\nchannels.inviteToChannel#199f3a6c channel:InputChannel users:Vector = Updates;\nchannels.deleteChannel#c0111fe3 channel:InputChannel = Updates;\nchannels.toggleSignatures#1f69b606 channel:InputChannel enabled:Bool = Updates;\nchannels.editBanned#96e6cd81 channel:InputChannel participant:InputPeer banned_rights:ChatBannedRights = Updates;\nchannels.readMessageContents#eab5dc38 channel:InputChannel id:Vector = Bool;\nchannels.togglePreHistoryHidden#eabbb94c channel:InputChannel enabled:Bool = Updates;\nchannels.getGroupsForDiscussion#f5dad378 = messages.Chats;\nchannels.setDiscussionGroup#40582bb2 broadcast:InputChannel group:InputChannel = Bool;\npayments.getPaymentForm#8a333c8d flags:# peer:InputPeer msg_id:int theme_params:flags.0?DataJSON = payments.PaymentForm;\npayments.getPaymentReceipt#2478d1cc peer:InputPeer msg_id:int = payments.PaymentReceipt;\npayments.validateRequestedInfo#db103170 flags:# save:flags.0?true peer:InputPeer msg_id:int info:PaymentRequestedInfo = payments.ValidatedRequestedInfo;\npayments.sendPaymentForm#30c3bc9d flags:# form_id:long peer:InputPeer msg_id:int requested_info_id:flags.0?string shipping_option_id:flags.1?string credentials:InputPaymentCredentials tip_amount:flags.2?long = payments.PaymentResult;\npayments.getSavedInfo#227d824b = payments.SavedInfo;\nlangpack.getLangPack#f2f2330a lang_pack:string lang_code:string = LangPackDifference;\nlangpack.getStrings#efea3803 lang_pack:string lang_code:string keys:Vector = Vector;\nlangpack.getLanguages#42c6978f lang_pack:string = Vector;\nfolders.editPeerFolders#6847d0ab folder_peers:Vector = Updates;\n"},8963:(e,t,n)=>{var s=n(8764).Buffer;function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const{inflate:i}=n(5802),{serializeBytes:o}=n(7404);class r{constructor(e){this.data=e,this.CONSTRUCTOR_ID=812830625,this.classType="constructor"}static async gzipIfSmaller(e,t){if(e&&t.length>512){const e=await new r(t).toBytes();if(e.length{function s(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const a=n(355);class i{constructor(e){this.CONSTRUCTOR_ID=1945237724,this.messages=e,this.classType="constructor"}static fromReader(e){const t=[],n=e.readInt();for(let s=0;s{function s(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const{RpcError:a}=n(7404).constructors,i=n(8963);class o{constructor(e,t,n){this.CONSTRUCTOR_ID=4082920705,this.reqMsgId=e,this.body=t,this.error=n,this.classType="constructor"}static async fromReader(e){const t=e.readLong(),n=e.readInt(!1);return n===a.CONSTRUCTOR_ID?new o(t,void 0,a.fromReader(e)):n===i.CONSTRUCTOR_ID?new o(t,(await i.fromReader(e)).data):(e.seek(-4),new o(t,e.read(),void 0))}}s(o,"CONSTRUCTOR_ID",4082920705),s(o,"classType","constructor"),e.exports=o},355:e=>{function t(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class n{constructor(e,t,n){this.msgId=e,this.seqNo=t,this.obj=n,this.classType="constructor"}}t(n,"SIZE_OVERHEAD",12),t(n,"classType","constructor"),e.exports=n},2058:(e,t,n)=>{const s=n(355),a=n(2301),i=n(3254),o=n(8963),r={[a.CONSTRUCTOR_ID]:a,[o.CONSTRUCTOR_ID]:o,[i.CONSTRUCTOR_ID]:i};e.exports={TLMessage:s,RPCResult:a,MessageContainer:i,GZIPPacked:o,coreObjects:r}},1436:(e,t,n)=>{var s=n(8764).Buffer;const a=e=>e.replace(/(?:^|_)([a-z])/g,((e,t)=>t.toUpperCase())).replace(/_/g,""),i=e=>e.replace(/([-_][a-z])/g,(e=>e.toUpperCase().replace("-","").replace("_",""))),o=new Set([3162085175,2574415285,1072550713,3300522427,1450380236]),r=new Set([85337187,2211011308,2851430293,1013613780,1459478408,3504867164,3045658042,1715713620,3608339646,4110704415,812830625]);let c;function d(e){c||(c=function(){let e;const t=[];for(let n=0;n<256;n++){e=n;for(let t=0;t<8;t++)e=1&e?3988292384^e>>>1:e>>>1;t[n]=e}return t}()),s.isBuffer(e)||(e=s.from(e));let t=-1;for(let n=0;n>>8}return(-1^t)>>>0}const l=(e,t,n=[])=>{e.flags.includes("g")||(e=new RegExp(e.source,"g"));const s=e.exec(t);return s&&(n.push(s.slice(1)),l(e,t,n)),n},u=(e,t)=>{const n=e.match(/([\w.]+)(?:#([0-9a-fA-F]+))?(?:\s{?\w+:[\w\d<>#.?!]+}?)*\s=\s([\w\d<>#.?]+);$/);if(!n)throw new Error(`Cannot parse TLObject ${e}`);const o=l(/({)?(\w+):([\w\d<>#.?!]+)}?/,e),r={name:n[1],constructorId:parseInt(n[2],16),argsConfig:{},subclassOfId:d(n[3]),result:n[3],isFunction:t,namespace:void 0};if(!r.constructorId){const e="";let t;t=Object.values(r.argsConfig).length?` ${Object.keys(r.argsConfig).map((e=>e.toString())).join(" ")}`:"";const n=`${r.name}${e}${t} = ${r.result}`.replace(/(:|\?)bytes /g,"$1string ").replace(/|{|}/g,"").replace(/ \w+:flags\.\d+\?true/g,"");"inputMediaInvoice"===r.name&&r.name,r.constructorId=d(s.from(n,"utf8"))}for(const[e,t,n]of o)void 0===e&&(r.argsConfig[i(t)]=g(t,n));return r.name.includes(".")&&([r.namespace,r.name]=r.name.split(/\.(.+)/)),r.name=a(r.name),r};function g(e,t){e="self"===e?"is_self":e;const n={isVector:!1,isFlag:!1,skipConstructorId:!1,flagIndex:-1,flagIndicator:!0,type:void 0,useVectorId:void 0};if("#"!==t){n.flagIndicator=!1,n.type=t.replace(/^!+/,"");const e=n.type.match(/flags.(\d+)\?([\w<>.]+)/);e&&(n.isFlag=!0,n.flagIndex=Number(e[1]),[,,n.type]=e);const s=n.type.match(/[Vv]ector<([\w\d.]+)>/);s&&(n.isVector=!0,n.useVectorId="V"===n.type.charAt(0),[,n.type]=s),/^[a-z]$/.test(n.type.split(".").pop().charAt(0))&&(n.skipConstructorId=!0)}return n}e.exports={findAll:l,parseTl:function*(e,t,n=[],s=o){(n||[]).reduce(((e,t)=>({...e,[t.name]:t})),{});const a=[],i={},c={},d=e;let l=!1;for(let e of d.split("\n")){const t=e.indexOf("//");if(-1!==t&&(e=e.slice(0,t)),e=e.trim(),!e)continue;const n=e.match(/---(\w+)---/);if(n){const[,e]=n;l="functions"===e}else try{const t=u(e,l);if(s.has(t.constructorId))continue;a.push(t),t.isFunction||(c[t.result]||(c[t.result]=[]),i[t.name]=t,c[t.result].push(t))}catch(e){if(!e.toString().includes("vector#1cb5c415"))throw e}}for(const e of a)if(r.has(e.constructorId))for(const t in e.argsConfig)"string"===e.argsConfig[t].type&&(e.argsConfig[t].type="bytes");for(const e of a)yield e},buildArgConfig:g,fromLine:u,CORE_TYPES:o,serializeDate:function(e){if(!e)return s.alloc(4).fill(0);if(e instanceof Date&&(e=Math.floor((Date.now()-e.getTime())/1e3)),"number"==typeof e){const t=s.alloc(4);return t.writeInt32LE(e,0),t}throw Error(`Cannot interpret "${e}" as a date`)},serializeBytes:function(e){if(!(e instanceof s)){if("string"!=typeof e)throw Error(`Bytes or str expected, not ${e.constructor.name}`);e=s.from(e)}const t=[];let n;return e.length<254?(n=(e.length+1)%4,0!==n&&(n=4-n),t.push(s.from([e.length])),t.push(e)):(n=e.length%4,0!==n&&(n=4-n),t.push(s.from([254,e.length%256,(e.length>>8)%256,(e.length>>16)%256])),t.push(e)),t.push(s.alloc(n).fill(0)),s.concat(t)},snakeToCamelCase:a,variableSnakeToCamelCase:i}},7404:(e,t,n)=>{const s=n(7150),{serializeBytes:a,serializeDate:i}=n(1436);e.exports={constructors:s,requests:s,serializeBytes:a,serializeDate:i}},8106:e=>{e.exports="resPQ#05162463 nonce:int128 server_nonce:int128 pq:string server_public_key_fingerprints:Vector = ResPQ;\np_q_inner_data#83c95aec pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 = P_Q_inner_data;\nserver_DH_params_fail#79cb045d nonce:int128 server_nonce:int128 new_nonce_hash:int128 = Server_DH_Params;\nserver_DH_params_ok#d0e8075c nonce:int128 server_nonce:int128 encrypted_answer:string = Server_DH_Params;\nserver_DH_inner_data#b5890dba nonce:int128 server_nonce:int128 g:int dh_prime:string g_a:string server_time:int = Server_DH_inner_data;\nclient_DH_inner_data#6643b654 nonce:int128 server_nonce:int128 retry_id:long g_b:string = Client_DH_Inner_Data;\ndh_gen_ok#3bcbf734 nonce:int128 server_nonce:int128 new_nonce_hash1:int128 = Set_client_DH_params_answer;\ndh_gen_retry#46dc1fb9 nonce:int128 server_nonce:int128 new_nonce_hash2:int128 = Set_client_DH_params_answer;\ndh_gen_fail#a69dae02 nonce:int128 server_nonce:int128 new_nonce_hash3:int128 = Set_client_DH_params_answer;\ndestroy_auth_key_ok#f660e1d4 = DestroyAuthKeyRes;\ndestroy_auth_key_none#0a9f2259 = DestroyAuthKeyRes;\ndestroy_auth_key_fail#ea109b13 = DestroyAuthKeyRes;\n---functions---\nreq_pq#60469778 nonce:int128 = ResPQ;\nreq_pq_multi#be7e8ef1 nonce:int128 = ResPQ;\nreq_pq_multi_new#51b410fd nonce:int128 = ResPQ;\nreq_DH_params#d712e4be nonce:int128 server_nonce:int128 p:string q:string public_key_fingerprint:long encrypted_data:string = Server_DH_Params;\nset_client_DH_params#f5045f1f nonce:int128 server_nonce:int128 encrypted_data:string = Set_client_DH_params_answer;\ndestroy_auth_key#d1435160 = DestroyAuthKeyRes;\n---types---\nmsgs_ack#62d6b459 msg_ids:Vector = MsgsAck;\nbad_msg_notification#a7eff811 bad_msg_id:long bad_msg_seqno:int error_code:int = BadMsgNotification;\nbad_server_salt#edab447b bad_msg_id:long bad_msg_seqno:int error_code:int new_server_salt:long = BadMsgNotification;\nmsgs_state_req#da69fb52 msg_ids:Vector = MsgsStateReq;\nmsgs_state_info#04deb57d req_msg_id:long info:string = MsgsStateInfo;\nmsgs_all_info#8cc0d131 msg_ids:Vector info:string = MsgsAllInfo;\nmsg_detailed_info#276d3ec6 msg_id:long answer_msg_id:long bytes:int status:int = MsgDetailedInfo;\nmsg_new_detailed_info#809db6df answer_msg_id:long bytes:int status:int = MsgDetailedInfo;\nmsg_resend_req#7d861a08 msg_ids:Vector = MsgResendReq;\nrpc_error#2144ca19 error_code:int error_message:string = RpcError;\nfuture_salt#0949d9dc valid_since:int valid_until:int salt:long = FutureSalt;\nfuture_salts#ae500895 req_msg_id:long now:int salts:vector = FutureSalts;\npong#347773c5 msg_id:long ping_id:long = Pong;\ndestroy_session_ok#e22045fc session_id:long = DestroySessionRes;\ndestroy_session_none#62d350c9 session_id:long = DestroySessionRes;\nnew_session_created#9ec20908 first_msg_id:long unique_id:long server_salt:long = NewSession;\n---functions---\nping#7abe77ec ping_id:long = Pong;\nping_delay_disconnect#f3427b8c ping_id:long disconnect_delay:int = Pong;"}},s={};function a(e){var t=s[e];if(void 0!==t)return t.exports;var i=s[e]={id:e,loaded:!1,exports:{}};return n[e].call(i.exports,i,i.exports,a),i.loaded=!0,i.exports}a.m=n,a.x=()=>{var e=a.O(void 0,[592],(()=>a(6514)));return a.O(e)},e=[],a.O=(t,n,s,i)=>{if(!n){var o=1/0;for(l=0;l=i)&&Object.keys(a.O).every((e=>a.O[e](n[c])))?n.splice(c--,1):(r=!1,i0&&e[l-1][2]>i;l--)e[l]=e[l-1];e[l]=[n,s,i]},a.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return a.d(t,{a:t}),t},a.d=(e,t)=>{for(var n in t)a.o(t,n)&&!a.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},a.f={},a.e=e=>Promise.all(Object.keys(a.f).reduce(((t,n)=>(a.f[n](e,t),t)),[])),a.u=e=>e+".d7ca037ed9b7d1c6792a.js",a.miniCssF=e=>{},a.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),a.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),a.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},a.nmd=e=>(e.paths=[],e.children||(e.children=[]),e),(()=>{var e;a.g.importScripts&&(e=a.g.location+"");var t=a.g.document;if(!e&&t&&(t.currentScript&&(e=t.currentScript.src),!e)){var n=t.getElementsByTagName("script");n.length&&(e=n[n.length-1].src)}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),a.p=e})(),(()=>{var e={514:1};a.f.i=(t,n)=>{e[t]||importScripts(a.p+a.u(t))};var t=self.webpackChunktelegram_t=self.webpackChunktelegram_t||[],n=t.push.bind(t);t.push=t=>{var[s,i,o]=t;for(var r in i)a.o(i,r)&&(a.m[r]=i[r]);for(o&&o(a);s.length;)e[s.pop()]=1;n(t)}})(),t=a.x,a.x=()=>a.e(592).then(t),a.x()})(); +//# sourceMappingURL=514.3cef19392d72a10cf6ea.js.map \ No newline at end of file diff --git a/dist/514.89d97ccb086a4c539d1a.js.map b/dist/514.3cef19392d72a10cf6ea.js.map similarity index 99% rename from dist/514.89d97ccb086a4c539d1a.js.map rename to dist/514.3cef19392d72a10cf6ea.js.map index 9102e0ea..9312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,EAAI,IAChBw5B,EAAoB3rD,EAAE,KAAK+sB,KAAK9wC,GiHDd0vE,EAAoBx5B,K","sources":["webpack://telegram-t/webpack/runtime/chunk loaded","webpack://telegram-t/webpack/runtime/startup chunk dependencies","webpack://telegram-t/./src/config.ts","webpack://telegram-t/./src/util/schedulers.ts","webpack://telegram-t/./src/util/iteratees.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/helpers.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/pathBytesToSvg.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/common.ts","webpack://telegram-t/./src/api/gramjs/localDb.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/symbols.ts","webpack://telegram-t/./src/util/waveform.ts","webpack://telegram-t/./src/api/types/messages.ts","webpack://telegram-t/./src/api/types/media.ts","webpack://telegram-t/./src/api/gramjs/gramjsBuilders/index.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/peers.ts","webpack://telegram-t/./src/api/gramjs/helpers.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/messages.ts","webpack://telegram-t/./src/util/serverTime.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/chats.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/users.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/misc.ts","webpack://telegram-t/./src/api/gramjs/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/settings.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/bots.ts","webpack://telegram-t/./src/api/gramjs/methods/bots.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/payments.ts","webpack://telegram-t/./src/api/gramjs/methods/payments.ts","webpack://telegram-t/./src/api/gramjs/provider.ts","webpack://telegram-t/./src/api/gramjs/worker/worker.ts","webpack://telegram-t/./src/lib/gramjs/Helpers.js","webpack://telegram-t/./src/lib/gramjs/Password.js","webpack://telegram-t/./src/lib/gramjs/Utils.js","webpack://telegram-t/./src/lib/gramjs/Version.js","webpack://telegram-t/./src/lib/gramjs/client/2fa.ts","webpack://telegram-t/./src/lib/gramjs/client/TelegramClient.js","webpack://telegram-t/./src/lib/gramjs/client/auth.ts","webpack://telegram-t/./src/lib/gramjs/client/downloadFile.ts","webpack://telegram-t/./src/lib/gramjs/client/uploadFile.ts","webpack://telegram-t/./src/lib/gramjs/crypto/AuthKey.js","webpack://telegram-t/./src/lib/gramjs/crypto/CTR.js","webpack://telegram-t/./src/lib/gramjs/crypto/Factorizator.js","webpack://telegram-t/./src/lib/gramjs/crypto/IGE.js","webpack://telegram-t/./src/lib/gramjs/crypto/converters.ts","webpack://telegram-t/./src/lib/gramjs/crypto/crypto.js","webpack://telegram-t/./src/lib/gramjs/crypto/words.ts","webpack://telegram-t/./src/lib/gramjs/errors/Common.js","webpack://telegram-t/./src/lib/gramjs/errors/RPCBaseErrors.js","webpack://telegram-t/./src/lib/gramjs/errors/RPCErrorList.js","webpack://telegram-t/./src/lib/gramjs/errors/index.js","webpack://telegram-t/./src/lib/gramjs/events/Raw.js","webpack://telegram-t/./src/lib/gramjs/events/common.js","webpack://telegram-t/./src/lib/gramjs/events/index.js","webpack://telegram-t/./src/lib/gramjs/extensions/AsyncQueue.js","webpack://telegram-t/./src/lib/gramjs/extensions/BinaryReader.js","webpack://telegram-t/./src/lib/gramjs/extensions/BinaryWriter.js","webpack://telegram-t/./src/lib/gramjs/extensions/Logger.js","webpack://telegram-t/./src/lib/gramjs/extensions/MessagePacker.js","webpack://telegram-t/./src/lib/gramjs/extensions/PromisedWebSockets.js","webpack://telegram-t/./src/lib/gramjs/extensions/index.js","webpack://telegram-t/./src/lib/gramjs/index.js","webpack://telegram-t/./src/lib/gramjs/crypto/RSA.ts","webpack://telegram-t/./src/lib/gramjs/network/Authenticator.ts","webpack://telegram-t/./src/lib/gramjs/network/MTProtoPlainSender.js","webpack://telegram-t/./src/lib/gramjs/network/MTProtoSender.js","webpack://telegram-t/./src/lib/gramjs/network/MTProtoState.js","webpack://telegram-t/./src/lib/gramjs/network/RequestState.js","webpack://telegram-t/./src/lib/gramjs/network/connection/Connection.js","webpack://telegram-t/./src/lib/gramjs/network/connection/TCPAbridged.js","webpack://telegram-t/./src/lib/gramjs/network/connection/TCPObfuscated.js","webpack://telegram-t/./src/lib/gramjs/network/connection/index.js","webpack://telegram-t/./src/lib/gramjs/network/index.js","webpack://telegram-t/./src/lib/gramjs/sessions/Abstract.js","webpack://telegram-t/./src/lib/gramjs/sessions/CacheApiSession.js","webpack://telegram-t/./src/lib/gramjs/sessions/CallbackSession.js","webpack://telegram-t/./src/lib/gramjs/sessions/IdbSession.js","webpack://telegram-t/./src/lib/gramjs/sessions/LocalStorageSession.js","webpack://telegram-t/./src/lib/gramjs/sessions/Memory.js","webpack://telegram-t/./src/lib/gramjs/sessions/StorageSession.js","webpack://telegram-t/./src/lib/gramjs/sessions/StringSession.js","webpack://telegram-t/./src/lib/gramjs/sessions/index.js","webpack://telegram-t/./src/lib/gramjs/tl/AllTLObjects.js","webpack://telegram-t/./src/lib/gramjs/tl/api.js","webpack://telegram-t/./src/lib/gramjs/tl/apiTl.js","webpack://telegram-t/./src/lib/gramjs/tl/core/GZIPPacked.js","webpack://telegram-t/./src/lib/gramjs/tl/core/MessageContainer.js","webpack://telegram-t/./src/lib/gramjs/tl/core/RPCResult.js","webpack://telegram-t/./src/lib/gramjs/tl/core/TLMessage.js","webpack://telegram-t/./src/lib/gramjs/tl/core/index.js","webpack://telegram-t/./src/lib/gramjs/tl/generationHelpers.js","webpack://telegram-t/./src/lib/gramjs/tl/index.js","webpack://telegram-t/./src/lib/gramjs/tl/schemaTl.js","webpack://telegram-t/webpack/bootstrap","webpack://telegram-t/webpack/runtime/compat get default export","webpack://telegram-t/webpack/runtime/define property getters","webpack://telegram-t/webpack/runtime/ensure chunk","webpack://telegram-t/webpack/runtime/get javascript chunk filename","webpack://telegram-t/webpack/runtime/get mini-css chunk filename","webpack://telegram-t/webpack/runtime/global","webpack://telegram-t/webpack/runtime/hasOwnProperty shorthand","webpack://telegram-t/webpack/runtime/make namespace object","webpack://telegram-t/webpack/runtime/node module decorator","webpack://telegram-t/webpack/runtime/publicPath","webpack://telegram-t/webpack/runtime/importScripts chunk loading","webpack://telegram-t/webpack/startup"],"sourcesContent":["var deferred = [];\n__webpack_require__.O = (result, chunkIds, fn, priority) => {\n\tif(chunkIds) {\n\t\tpriority = priority || 0;\n\t\tfor(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1];\n\t\tdeferred[i] = [chunkIds, fn, priority];\n\t\treturn;\n\t}\n\tvar notFulfilled = Infinity;\n\tfor (var i = 0; i < deferred.length; i++) {\n\t\tvar [chunkIds, fn, priority] = deferred[i];\n\t\tvar fulfilled = true;\n\t\tfor (var j = 0; j < chunkIds.length; j++) {\n\t\t\tif ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(__webpack_require__.O).every((key) => (__webpack_require__.O[key](chunkIds[j])))) {\n\t\t\t\tchunkIds.splice(j--, 1);\n\t\t\t} else {\n\t\t\t\tfulfilled = false;\n\t\t\t\tif(priority < notFulfilled) notFulfilled = priority;\n\t\t\t}\n\t\t}\n\t\tif(fulfilled) {\n\t\t\tdeferred.splice(i--, 1)\n\t\t\tvar r = fn();\n\t\t\tif (r !== undefined) result = r;\n\t\t}\n\t}\n\treturn result;\n};","var next = __webpack_require__.x;\n__webpack_require__.x = () => {\n\treturn __webpack_require__.e(592).then(next);\n};","export const PAGE_TITLE = 'Telegram';\nexport const INACTIVE_MARKER = ' [Inactive]';\n\nexport const APP_NAME = process.env.APP_NAME || 'Telegram WebZ';\nexport const APP_VERSION = process.env.APP_VERSION || 'dev';\n\nexport const DEBUG = (\n process.env.APP_ENV !== 'production' && process.env.APP_ENV !== 'perf' && process.env.APP_ENV !== 'test'\n);\nexport const DEBUG_MORE = false;\n\nexport const IS_TEST = process.env.APP_ENV === 'test';\nexport const IS_PERF = process.env.APP_ENV === 'perf';\n\nexport const DEBUG_ALERT_MSG = 'Shoot!\\nSomething went wrong, please see the error details in Dev Tools Console.';\nexport const DEBUG_GRAMJS = false;\n\nexport const SESSION_USER_KEY = 'user_auth';\nexport const LEGACY_SESSION_KEY = 'GramJs:sessionId';\n\nexport const GLOBAL_STATE_CACHE_DISABLED = false;\nexport const GLOBAL_STATE_CACHE_KEY = 'tt-global-state';\nexport const GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT = 30;\nexport const GLOBAL_STATE_CACHE_USER_LIST_LIMIT = 5000;\n\nexport const MEDIA_CACHE_DISABLED = false;\nexport const MEDIA_CACHE_NAME = 'tt-media';\nexport const MEDIA_CACHE_NAME_AVATARS = 'tt-media-avatars';\nexport const MEDIA_PROGRESSIVE_CACHE_DISABLED = false;\nexport const MEDIA_PROGRESSIVE_CACHE_NAME = 'tt-media-progressive';\nexport const MEDIA_CACHE_MAX_BYTES = 512 * 1024; // 512 KB\nexport const CUSTOM_BG_CACHE_NAME = 'tt-custom-bg';\nexport const LANG_CACHE_NAME = 'tt-lang-packs-v6';\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_SENSITIVE_AREA = 750;\nexport const MESSAGE_LIST_SLICE = isBigScreen ? 60 : 40;\nexport const MESSAGE_LIST_VIEWPORT_LIMIT = MESSAGE_LIST_SLICE * 2;\n\nexport const CHAT_HEIGHT_PX = 72;\nexport const CHAT_LIST_SLICE = isBigScreen ? 30 : 25;\nexport const CHAT_LIST_LOAD_SLICE = 100;\nexport const SHARED_MEDIA_SLICE = 42;\nexport const MESSAGE_SEARCH_SLICE = 42;\nexport const GLOBAL_SEARCH_SLICE = 20;\nexport const MEMBERS_SLICE = 30;\nexport const MEMBERS_LOAD_SLICE = 200;\nexport const PINNED_MESSAGES_LIMIT = 50;\nexport const BLOCKED_LIST_LIMIT = 100;\nexport const PROFILE_PHOTOS_LIMIT = 40;\nexport const PROFILE_SENSITIVE_AREA = 500;\nexport const COMMON_CHATS_LIMIT = 100;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 20;\nexport const ALL_CHATS_PRELOAD_DISABLED = false;\n\nexport const DEFAULT_VOLUME = 1;\nexport const DEFAULT_PLAYBACK_RATE = 1;\n\nexport const ANIMATION_LEVEL_MIN = 0;\nexport const ANIMATION_LEVEL_MED = 1;\nexport const ANIMATION_LEVEL_MAX = 2;\nexport const ANIMATION_LEVEL_DEFAULT = ANIMATION_LEVEL_MAX;\n\nexport const DEFAULT_MESSAGE_TEXT_SIZE_PX = 16;\nexport const IOS_DEFAULT_MESSAGE_TEXT_SIZE_PX = 17;\nexport const MACOS_DEFAULT_MESSAGE_TEXT_SIZE_PX = 15;\n\nexport const DRAFT_DEBOUNCE = 10000; // 10s\n\nexport const EDITABLE_INPUT_ID = 'editable-message-text';\nexport const EDITABLE_INPUT_MODAL_ID = 'editable-message-text-modal';\n\n// Screen width where Pinned Message / Audio Player in the Middle Header can be safely displayed\nexport const SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1440; // px\n// Screen width where Pinned Message / Audio Player in the Middle Header shouldn't collapse with ChatInfo\nexport const SAFE_SCREEN_WIDTH_FOR_CHAT_INFO = 1150; // px\n\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1275; // px\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN = 925; // px\nexport const MOBILE_SCREEN_MAX_WIDTH = 600; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH = 950; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT = 450; // px\n\nexport const LOCAL_MESSAGE_ID_BASE = 1e9;\nexport const TMP_CHAT_ID = '0';\n\nexport const ANIMATION_END_DELAY = 100;\n\nexport const FAST_SMOOTH_MAX_DISTANCE = 1500;\nexport const FAST_SMOOTH_MIN_DURATION = 250;\nexport const FAST_SMOOTH_MAX_DURATION = 600;\nexport const FAST_SMOOTH_SHORT_TRANSITION_MAX_DISTANCE = 500; // px\n\n// Average duration of message sending animation\nexport const API_UPDATE_THROTTLE = Math.round((FAST_SMOOTH_MIN_DURATION + FAST_SMOOTH_MAX_DURATION) / 2);\nexport const API_THROTTLE_RESET_UPDATES = new Set([\n 'newMessage', 'newScheduledMessage', 'deleteMessages', 'deleteScheduledMessages', 'deleteHistory',\n]);\n\nexport const STICKER_SIZE_INLINE_DESKTOP_FACTOR = 13;\nexport const STICKER_SIZE_INLINE_MOBILE_FACTOR = 11;\nexport const STICKER_SIZE_AUTH = 160;\nexport const STICKER_SIZE_AUTH_MOBILE = 120;\nexport const STICKER_SIZE_PICKER = 64;\nexport const STICKER_SIZE_GENERAL_SETTINGS = 48;\nexport const STICKER_SIZE_PICKER_HEADER = 32;\nexport const STICKER_SIZE_SEARCH = 64;\nexport const STICKER_SIZE_MODAL = 64;\nexport const STICKER_SIZE_TWO_FA = 160;\nexport const STICKER_SIZE_DISCUSSION_GROUPS = 140;\nexport const STICKER_SIZE_FOLDER_SETTINGS = 80;\nexport const STICKER_SIZE_INLINE_BOT_RESULT = 100;\nexport const RECENT_STICKERS_LIMIT = 20;\nexport const MEMOJI_STICKER_ID = 'MEMOJI_STICKER';\n\nexport const BASE_EMOJI_KEYWORD_LANG = 'en';\n\nexport const MENU_TRANSITION_DURATION = 200;\nexport const SLIDE_TRANSITION_DURATION = 450;\n\nexport const VIDEO_MOV_TYPE = 'video/quicktime';\n\nexport const SUPPORTED_IMAGE_CONTENT_TYPES = new Set([\n 'image/png', 'image/gif', 'image/jpeg',\n]);\n\nexport const SUPPORTED_VIDEO_CONTENT_TYPES = new Set([\n 'video/mp4', // video/quicktime added dynamically in environment.ts\n]);\n\nexport const CONTENT_TYPES_WITH_PREVIEW = new Set([\n ...SUPPORTED_IMAGE_CONTENT_TYPES,\n ...SUPPORTED_VIDEO_CONTENT_TYPES,\n]);\n\n// eslint-disable-next-line max-len\nexport const RE_LINK_TEMPLATE = '((ftp|https?):\\\\/\\\\/)?((www\\\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\\\.[a-zA-Z0-9()]{1,63})\\\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)';\nexport const RE_MENTION_TEMPLATE = '(@[\\\\w\\\\d_-]+)';\nexport const RE_TG_LINK = /^tg:(\\/\\/)?([?=&\\d\\w_-]+)?/gm;\nexport const RE_TME_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/)/gm;\n\n// eslint-disable-next-line max-len\nexport const COUNTRIES_WITH_12H_TIME_FORMAT = new Set(['AU', 'BD', 'CA', 'CO', 'EG', 'HN', 'IE', 'IN', 'JO', 'MX', 'MY', 'NI', 'NZ', 'PH', 'PK', 'SA', 'SV', 'US']);\n\n// MTProto constants\nexport const SERVICE_NOTIFICATIONS_USER_ID = '777000';\nexport const REPLIES_USER_ID = '1271266957'; // TODO For Test connection ID must be equal to 708513\nexport const ALL_FOLDER_ID = 0;\nexport const ARCHIVED_FOLDER_ID = 1;\nexport const DELETED_COMMENTS_CHANNEL_ID = '-777';\nexport const MAX_MEDIA_FILES_FOR_ALBUM = 10;\nexport const MAX_ACTIVE_PINNED_CHATS = 5;\nexport const SCHEDULED_WHEN_ONLINE = 0x7FFFFFFE;\nexport const DEFAULT_LANG_CODE = 'en';\nexport const DEFAULT_LANG_PACK = 'android';\nexport const LANG_PACKS = ['android', 'ios', 'tdesktop', 'macos'] as const;\nexport const TIPS_USERNAME = 'TelegramTips';\nexport const LOCALIZED_TIPS = ['ar', 'pt-br', 'id', 'it', 'ko', 'ms', 'pl', 'es', 'tr'];\nexport const FEEDBACK_URL = 'https://bugs.telegram.org/?tag_ids=41&sort=time';\nexport const LIGHT_THEME_BG_COLOR = '#A2AF8E';\nexport const DARK_THEME_BG_COLOR = '#0F0F0F';\nexport const DARK_THEME_PATTERN_COLOR = '#0a0a0a8c';\nexport const DEFAULT_PATTERN_COLOR = 'rgba(90, 110, 70, 0.6)';\n","type Scheduler =\n typeof requestAnimationFrame\n | typeof onTickEnd\n | typeof runNow;\n\nexport function debounce(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n shouldRunLast = true,\n) {\n let waitingTimeout: number | undefined;\n\n return (...args: Parameters) => {\n if (waitingTimeout) {\n clearTimeout(waitingTimeout);\n waitingTimeout = undefined;\n } else if (shouldRunFirst) {\n // @ts-ignore\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n waitingTimeout = self.setTimeout(() => {\n if (shouldRunLast) {\n // @ts-ignore\n fn(...args);\n }\n\n waitingTimeout = undefined;\n }, ms);\n };\n}\n\nexport function throttle(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n) {\n let interval: number | undefined;\n let isPending: boolean;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n isPending = true;\n args = _args;\n\n if (!interval) {\n if (shouldRunFirst) {\n isPending = false;\n // @ts-ignore\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n interval = self.setInterval(() => {\n if (!isPending) {\n // eslint-disable-next-line no-restricted-globals\n self.clearInterval(interval!);\n interval = undefined;\n return;\n }\n\n isPending = false;\n // @ts-ignore\n fn(...args);\n }, ms);\n }\n };\n}\n\nexport function throttleWithRaf(fn: F) {\n return throttleWith(fastRaf, fn);\n}\n\nexport function throttleWithPrimaryRaf(fn: F) {\n return throttleWith(fastRafPrimary, fn);\n}\n\nexport function throttleWithTickEnd(fn: F) {\n return throttleWith(onTickEnd, fn);\n}\n\nexport function throttleWithNow(fn: F) {\n return throttleWith(runNow, fn);\n}\n\nexport function throttleWith(schedulerFn: Scheduler, fn: F) {\n let waiting = false;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n args = _args;\n\n if (!waiting) {\n waiting = true;\n\n schedulerFn(() => {\n waiting = false;\n // @ts-ignore\n fn(...args);\n });\n }\n };\n}\n\nexport function onIdle(cb: NoneToVoidFunction) {\n // eslint-disable-next-line no-restricted-globals\n if (self.requestIdleCallback) {\n // eslint-disable-next-line no-restricted-globals\n self.requestIdleCallback(cb);\n } else {\n onTickEnd(cb);\n }\n}\n\nfunction runNow(fn: NoneToVoidFunction) {\n fn();\n}\n\nexport const pause = (ms: number) => new Promise((resolve) => {\n setTimeout(() => resolve(), ms);\n});\n\nexport function rafPromise() {\n return new Promise((resolve) => {\n fastRaf(resolve);\n });\n}\n\nlet fastRafCallbacks: NoneToVoidFunction[] | undefined;\nlet fastRafPrimaryCallbacks: NoneToVoidFunction[] | undefined;\n\n// May result in an immediate execution if called from another `requestAnimationFrame` callback\nexport function fastRaf(callback: NoneToVoidFunction, isPrimary = false) {\n if (!fastRafCallbacks) {\n fastRafCallbacks = isPrimary ? [] : [callback];\n fastRafPrimaryCallbacks = isPrimary ? [callback] : [];\n\n requestAnimationFrame(() => {\n const currentCallbacks = fastRafCallbacks!;\n const currentPrimaryCallbacks = fastRafPrimaryCallbacks!;\n fastRafCallbacks = undefined;\n fastRafPrimaryCallbacks = undefined;\n currentPrimaryCallbacks.forEach((cb) => cb());\n currentCallbacks.forEach((cb) => cb());\n });\n } else if (isPrimary) {\n fastRafPrimaryCallbacks!.push(callback);\n } else {\n fastRafCallbacks.push(callback);\n }\n}\n\nexport function fastRafPrimary(callback: NoneToVoidFunction) {\n fastRaf(callback, true);\n}\n\nlet onTickEndCallbacks: NoneToVoidFunction[] | undefined;\nlet onTickEndPrimaryCallbacks: NoneToVoidFunction[] | undefined;\n\nexport function onTickEnd(callback: NoneToVoidFunction, isPrimary = false) {\n if (!onTickEndCallbacks) {\n onTickEndCallbacks = isPrimary ? [] : [callback];\n onTickEndPrimaryCallbacks = isPrimary ? [callback] : [];\n\n Promise.resolve().then(() => {\n const currentCallbacks = onTickEndCallbacks!;\n const currentPrimaryCallbacks = onTickEndPrimaryCallbacks!;\n onTickEndCallbacks = undefined;\n onTickEndPrimaryCallbacks = undefined;\n currentPrimaryCallbacks.forEach((cb) => cb());\n currentCallbacks.forEach((cb) => cb());\n });\n } else if (isPrimary) {\n onTickEndPrimaryCallbacks!.push(callback);\n } else {\n onTickEndCallbacks.push(callback);\n }\n}\n\nexport function onTickEndPrimary(callback: NoneToVoidFunction) {\n onTickEnd(callback, true);\n}\n\nlet beforeUnloadCallbacks: NoneToVoidFunction[] | undefined;\n\nexport function onBeforeUnload(callback: NoneToVoidFunction, isLast = false) {\n if (!beforeUnloadCallbacks) {\n beforeUnloadCallbacks = [];\n // eslint-disable-next-line no-restricted-globals\n self.addEventListener('beforeunload', () => {\n beforeUnloadCallbacks!.forEach((cb) => cb());\n });\n }\n\n if (isLast) {\n beforeUnloadCallbacks.push(callback);\n } else {\n beforeUnloadCallbacks.unshift(callback);\n }\n\n return () => {\n beforeUnloadCallbacks = beforeUnloadCallbacks!.filter((cb) => cb !== callback);\n };\n}\n","type CollectionByKey = Record;\n\ntype OrderDirection = 'asc' | 'desc';\n\ninterface OrderCallback {\n (member: T): any;\n}\n\nexport function buildCollectionByKey(collection: T[], key: keyof T) {\n return collection.reduce((byKey: CollectionByKey, member: T) => {\n byKey[member[key]] = member;\n\n return byKey;\n }, {});\n}\n\nexport function mapValues(\n byKey: CollectionByKey,\n callback: (member: M, key: string, index: number, originalByKey: CollectionByKey) => R,\n): CollectionByKey {\n return Object.keys(byKey).reduce((newByKey: CollectionByKey, key, index) => {\n newByKey[key] = callback(byKey[key], key, index, byKey);\n return newByKey;\n }, {});\n}\n\nexport function pick(object: T, keys: K[]) {\n return keys.reduce((result, key) => {\n result[key] = object[key];\n return result;\n }, {} as Pick);\n}\n\nexport function pickTruthy(object: T, keys: K[]) {\n return keys.reduce((result, key) => {\n if (object[key]) {\n result[key] = object[key];\n }\n\n return result;\n }, {} as Pick);\n}\n\nexport function omit(object: T, keys: K[]) {\n const stringKeys = new Set(keys.map(String));\n const savedKeys = Object.keys(object)\n .filter((key) => !stringKeys.has(key)) as Array>;\n\n return pick(object, savedKeys);\n}\n\nexport function orderBy(\n collection: T[],\n orderKey: (keyof T) | OrderCallback | ((keyof T) | OrderCallback)[],\n mode: OrderDirection | [OrderDirection, OrderDirection] = 'asc',\n): T[] {\n return collection.sort((a, b) => {\n if (Array.isArray(orderKey)) {\n const [mode1, mode2] = Array.isArray(mode) ? mode : [mode, mode];\n const [orderKey1, orderKey2] = orderKey;\n\n let aValue1;\n let bValue1;\n\n if (typeof orderKey1 === 'function') {\n aValue1 = orderKey1(a) || 0;\n bValue1 = orderKey1(b) || 0;\n } else if (typeof orderKey1 === 'string') {\n aValue1 = a[orderKey1] || 0;\n bValue1 = b[orderKey1] || 0;\n }\n\n if (aValue1 !== bValue1) {\n return mode1 === 'asc' ? aValue1 - bValue1 : bValue1 - aValue1;\n } else {\n let aValue2;\n let bValue2;\n\n if (typeof orderKey2 === 'function') {\n aValue2 = orderKey2(a) || 0;\n bValue2 = orderKey2(b) || 0;\n } else if (typeof orderKey2 === 'string') {\n aValue2 = a[orderKey2] || 0;\n bValue2 = b[orderKey2] || 0;\n }\n\n return mode2 === 'asc' ? aValue2 - bValue2 : bValue2 - aValue2;\n }\n }\n\n let aValue;\n let bValue;\n\n if (typeof orderKey === 'function') {\n aValue = orderKey(a) || 0;\n bValue = orderKey(b) || 0;\n } else if (typeof orderKey === 'string') {\n aValue = a[orderKey] || 0;\n bValue = b[orderKey] || 0;\n }\n\n return mode === 'asc' ? aValue - bValue : bValue - aValue;\n });\n}\n\nexport function flatten(array: any[]) {\n return array.reduce((result, member) => {\n if (Array.isArray(member)) {\n return result.concat(member);\n } else {\n result.push(member);\n return result;\n }\n }, []);\n}\n\nexport function unique(array: T[]): T[] {\n return Array.from(new Set(array));\n}\n\nexport function compact(array: any[]) {\n return array.filter(Boolean);\n}\n\nexport function areSortedArraysEqual(array1: any[], array2: any[]) {\n if (array1.length !== array2.length) {\n return false;\n }\n\n return array1.every((item, i) => item === array2[i]);\n}\n\nexport function areSortedArraysIntersecting(array1: any[], array2: any[]) {\n return array1[0] <= array2[array2.length - 1] && array1[array1.length - 1] >= array2[0];\n}\n\nexport function findIntersectionWithSet(array: T[], set: Set): T[] {\n return array.filter((a) => set.has(a));\n}\n\nexport function split(array: any[], chunkSize: number) {\n const result = [];\n for (let i = 0; i < array.length; i += chunkSize) {\n result.push(array.slice(i, i + chunkSize));\n }\n\n return result;\n}\n\nexport function cloneDeep(value: T): T {\n if (typeof value !== 'object') {\n return value;\n }\n\n if (Array.isArray(value)) {\n return value.map(cloneDeep) as typeof value;\n }\n\n return Object.keys(value).reduce((acc, key) => {\n acc[key as keyof T] = cloneDeep(value[key as keyof T]);\n return acc;\n }, {} as T);\n}\n\n/**\n * Returns the index of the last element in the array where predicate is true, and -1 otherwise.\n *\n * @param array The source array to search in\n * @param predicate find calls predicate once for each element of the array, in descending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.\n */\nexport function findLast(array: Array, predicate: (value: T, index: number, obj: T[]) => boolean): T | undefined {\n let cursor = array.length;\n\n while (cursor--) {\n if (predicate(array[cursor], cursor, array)) {\n return array[cursor];\n }\n }\n\n return undefined;\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\n\ntype VirtualFields =\n 'flags'\n | 'CONSTRUCTOR_ID'\n | 'SUBCLASS_OF_ID'\n | 'className'\n | 'classType'\n | 'getBytes';\n\nexport function bytesToDataUri(bytes: Buffer, shouldOmitPrefix = false, mimeType: string = 'image/jpeg') {\n const prefix = shouldOmitPrefix ? '' : `data:${mimeType};base64,`;\n\n return `${prefix}${btoa(String.fromCharCode(...bytes))}`;\n}\n\nexport function omitVirtualClassFields & { flags?: any }>(\n instance: T,\n): Omit {\n const {\n flags,\n CONSTRUCTOR_ID,\n SUBCLASS_OF_ID,\n className,\n classType,\n getBytes,\n ...rest\n } = instance;\n\n return rest;\n}\n","/* eslint-disable no-bitwise */\n\n// eslint-disable-next-line max-len\nconst TEMPLATE = '';\nconst LOOKUP = 'AACAAAAHAAALMAAAQASTAVAAAZaacaaaahaaalmaaaqastava.az0123456789-,';\n\nexport function pathBytesToSvg(bytes: Buffer, width: number, height: number) {\n return TEMPLATE\n .replace('{{path}}', buildPath(bytes))\n .replace('{{width}}', String(width))\n .replace('{{height}}', String(height));\n}\n\nfunction buildPath(bytes: Buffer) {\n let path = 'M';\n\n const len = bytes.length;\n for (let i = 0; i < len; i++) {\n const num = bytes[i];\n if (num >= 128 + 64) {\n path += LOOKUP[num - 128 - 64];\n } else {\n if (num >= 128) {\n path += ',';\n } else if (num >= 64) {\n path += '-';\n }\n path += String(num & 63);\n }\n }\n\n path += 'z';\n\n return path;\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport { strippedPhotoToJpg } from '../../../lib/gramjs/Utils';\n\nimport {\n ApiPhoto, ApiPhotoSize, ApiThumbnail,\n} from '../../types';\nimport { bytesToDataUri } from './helpers';\nimport { pathBytesToSvg } from './pathBytesToSvg';\n\nconst DEFAULT_THUMB_SIZE = { w: 100, h: 100 };\n\nexport function buildApiThumbnailFromStripped(\n sizes?: GramJs.TypePhotoSize[], mimeType?: string,\n): ApiThumbnail | undefined {\n if (!sizes || !sizes.length) {\n return undefined;\n }\n\n const thumb = sizes.find((s: any): s is GramJs.PhotoStrippedSize => s instanceof GramJs.PhotoStrippedSize);\n if (!thumb) {\n return undefined;\n }\n\n const realSizes = sizes.filter((s): s is GramJs.PhotoSize => s instanceof GramJs.PhotoSize);\n const { w, h } = realSizes.length ? realSizes[realSizes.length - 1] : DEFAULT_THUMB_SIZE;\n const { bytes } = thumb;\n const dataUri = bytesToDataUri(\n !mimeType || mimeType === 'image/jpeg' ? strippedPhotoToJpg(bytes) : bytes,\n undefined,\n mimeType,\n );\n\n return {\n dataUri,\n width: w,\n height: h,\n };\n}\n\nexport function buildApiThumbnailFromCached(photoSize: GramJs.PhotoCachedSize): ApiThumbnail | undefined {\n const { w, h, bytes } = photoSize;\n const dataUri = bytesToDataUri(bytes, undefined, 'image/webp');\n\n return {\n dataUri,\n width: w,\n height: h,\n };\n}\n\nexport function buildApiThumbnailFromPath(\n photoSize: GramJs.PhotoPathSize,\n sizeAttribute: GramJs.DocumentAttributeImageSize,\n): ApiThumbnail | undefined {\n const { w, h } = sizeAttribute;\n const dataUri = `data:image/svg+xml;utf8,${pathBytesToSvg(photoSize.bytes, w, h)}`;\n\n return {\n dataUri,\n width: w,\n height: h,\n };\n}\n\nexport function buildApiPhoto(photo: GramJs.Photo): ApiPhoto {\n const sizes = photo.sizes\n .filter((s: any): s is GramJs.PhotoSize => {\n return s instanceof GramJs.PhotoSize || s instanceof GramJs.PhotoSizeProgressive;\n })\n .map(buildApiPhotoSize);\n\n return {\n id: String(photo.id),\n thumbnail: buildApiThumbnailFromStripped(photo.sizes),\n sizes,\n };\n}\n\nexport function buildApiPhotoSize(photoSize: GramJs.PhotoSize): ApiPhotoSize {\n const { w, h, type } = photoSize;\n\n return {\n width: w,\n height: h,\n type: type as ('m' | 'x' | 'y'),\n };\n}\n","import { Api as GramJs } from '../../lib/gramjs';\nimport { ApiMessage } from '../types';\n\ninterface LocalDb {\n localMessages: Record;\n // Used for loading avatars and media through in-memory Gram JS instances.\n chats: Record;\n users: Record;\n messages: Record;\n documents: Record;\n stickerSets: Record;\n photos: Record;\n webDocuments: Record;\n}\n\nexport default {\n localMessages: {},\n chats: {},\n users: {},\n messages: {},\n documents: {},\n stickerSets: {},\n photos: {},\n webDocuments: {},\n} as LocalDb;\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport { ApiSticker, ApiStickerSet } from '../../types';\nimport { MEMOJI_STICKER_ID } from '../../../config';\n\nimport { buildApiThumbnailFromCached, buildApiThumbnailFromPath } from './common';\nimport localDb from '../localDb';\n\nconst ANIMATED_STICKER_MIME_TYPE = 'application/x-tgsticker';\n\nexport function buildStickerFromDocument(document: GramJs.TypeDocument): ApiSticker | undefined {\n if (document instanceof GramJs.DocumentEmpty) {\n return undefined;\n }\n\n const stickerAttribute = document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeSticker => (\n attr instanceof GramJs.DocumentAttributeSticker\n ));\n\n const fileAttribute = document.mimeType === ANIMATED_STICKER_MIME_TYPE && document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeFilename => (\n attr instanceof GramJs.DocumentAttributeFilename\n ));\n\n if (!stickerAttribute && !fileAttribute) {\n return undefined;\n }\n\n const sizeAttribute = document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeImageSize => (\n attr instanceof GramJs.DocumentAttributeImageSize\n ));\n\n const stickerSetInfo = stickerAttribute && stickerAttribute.stickerset instanceof GramJs.InputStickerSetID\n ? stickerAttribute.stickerset\n : undefined;\n const emoji = stickerAttribute?.alt;\n const isAnimated = document.mimeType === ANIMATED_STICKER_MIME_TYPE;\n const cachedThumb = document.thumbs && document.thumbs.find(\n (s): s is GramJs.PhotoCachedSize => s instanceof GramJs.PhotoCachedSize,\n );\n const pathThumb = document.thumbs && document.thumbs.find(\n (s): s is GramJs.PhotoPathSize => s instanceof GramJs.PhotoPathSize,\n );\n const thumbnail = cachedThumb ? (\n buildApiThumbnailFromCached(cachedThumb)\n ) : pathThumb && sizeAttribute ? (\n buildApiThumbnailFromPath(pathThumb, sizeAttribute)\n ) : undefined;\n\n const { w: width, h: height } = cachedThumb as GramJs.PhotoCachedSize || sizeAttribute || {};\n\n return {\n id: String(document.id),\n stickerSetId: stickerSetInfo ? String(stickerSetInfo.id) : MEMOJI_STICKER_ID,\n stickerSetAccessHash: stickerSetInfo && String(stickerSetInfo.accessHash),\n emoji,\n isAnimated,\n width,\n height,\n thumbnail,\n };\n}\n\nexport function buildStickerSet(set: GramJs.StickerSet): ApiStickerSet {\n const {\n archived,\n animated,\n installedDate,\n id,\n accessHash,\n title,\n thumbs,\n count,\n shortName,\n } = set;\n\n return {\n archived,\n isAnimated: animated,\n installedDate,\n id: String(id),\n accessHash: String(accessHash),\n title,\n hasThumbnail: Boolean(thumbs?.length),\n count,\n shortName,\n };\n}\n\nexport function buildStickerSetCovered(coveredStickerSet: GramJs.TypeStickerSetCovered): ApiStickerSet {\n const stickerSet = buildStickerSet(coveredStickerSet.set);\n\n const stickerSetCovers = (coveredStickerSet instanceof GramJs.StickerSetMultiCovered)\n ? coveredStickerSet.covers\n : [coveredStickerSet.cover];\n\n stickerSet.covers = [];\n stickerSetCovers.forEach((cover) => {\n if (cover instanceof GramJs.Document) {\n const coverSticker = buildStickerFromDocument(cover);\n if (coverSticker) {\n stickerSet.covers!.push(coverSticker);\n localDb.documents[String(cover.id)] = cover;\n }\n }\n });\n\n return stickerSet;\n}\n","/* eslint-disable no-bitwise */\n\n// eslint-disable-next-line max-len\n// Ref: https://github.com/telegramdesktop/tdesktop/blob/0743e71ab6b928d2ee5bae1aed991849b1e2b291/Telegram/SourceFiles/data/data_document.cpp#L1018\nexport function decodeWaveform(encoded5bit: Uint8Array) {\n const bitsCount = encoded5bit.length * 8;\n const valuesCount = Math.floor(bitsCount / 5);\n if (!valuesCount) {\n return [];\n }\n\n // Read each 5 bit of encoded5bit as 0-31 unsigned char.\n // We count the index of the byte in which the desired 5-bit sequence starts.\n // And then we read a uint16 starting from that byte to guarantee to get all of those 5 bits.\n //\n // BUT! if it is the last byte we have, we're not allowed to read a uint16 starting with it.\n // Because it will be an overflow (we'll access one byte after the available memory).\n // We see, that only the last 5 bits could start in the last available byte and be problematic.\n // So we read in a general way all the entries in a general way except the last one.\n const result = Array(valuesCount);\n const bitsData = encoded5bit;\n for (let i = 0, l = valuesCount - 1; i !== l; ++i) {\n const byteIndex = Math.floor((i * 5) / 8);\n const bitShift = Math.floor((i * 5) % 8);\n const value = bitsData[byteIndex] + (bitsData[byteIndex + 1] << 8);\n result[i] = ((value >> bitShift) & 0x1F);\n }\n const lastByteIndex = Math.floor(((valuesCount - 1) * 5) / 8);\n const lastBitShift = Math.floor(((valuesCount - 1) * 5) % 8);\n const lastValue = bitsData[lastByteIndex] + (bitsData[lastByteIndex + 1] << 8);\n result[valuesCount - 1] = (lastValue >> lastBitShift) & 0x1F;\n\n return result;\n}\n\nexport function interpolateArray(data: number[], fitCount: number) {\n let peak = 0;\n const newData = new Array(fitCount);\n const springFactor = data.length / fitCount;\n const leftFiller = data[0];\n const rightFiller = data[data.length - 1];\n for (let i = 0; i < fitCount; i++) {\n const idx = Math.floor(i * springFactor);\n const val = ((data[idx - 1] ?? leftFiller) + (data[idx] ?? leftFiller) + (data[idx + 1] ?? rightFiller)) / 3;\n newData[i] = val;\n if (peak < val) {\n peak = val;\n }\n }\n return { data: newData, peak };\n}\n","export interface ApiDimensions {\n width: number;\n height: number;\n}\n\nexport interface ApiPhotoSize extends ApiDimensions {\n type: 's' | 'm' | 'x' | 'y' | 'z';\n}\n\nexport interface ApiThumbnail extends ApiDimensions {\n dataUri: string;\n}\n\nexport interface ApiPhoto {\n id: string;\n thumbnail?: ApiThumbnail;\n sizes: ApiPhotoSize[];\n blobUrl?: string;\n}\n\nexport interface ApiSticker {\n id: string;\n stickerSetId: string;\n stickerSetAccessHash?: string;\n emoji?: string;\n isAnimated: boolean;\n width?: number;\n height?: number;\n thumbnail?: ApiThumbnail;\n isPreloadedGlobally?: boolean;\n}\n\nexport interface ApiStickerSet {\n archived?: true;\n isAnimated?: true;\n installedDate?: number;\n id: string;\n accessHash: string;\n title: string;\n hasThumbnail?: boolean;\n count: number;\n stickers?: ApiSticker[];\n packs?: Record;\n covers?: ApiSticker[];\n shortName: string;\n}\n\nexport interface ApiVideo {\n id: string;\n mimeType: string;\n duration: number;\n fileName: string;\n width?: number;\n height?: number;\n supportsStreaming?: boolean;\n isRound?: boolean;\n isGif?: boolean;\n thumbnail?: ApiThumbnail;\n blobUrl?: string;\n size: number;\n}\n\nexport interface ApiAudio {\n 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 duration: number;\n waveform?: number[];\n}\n\nexport interface ApiDocument {\n id?: string;\n fileName: string;\n size: number;\n timestamp?: number;\n mimeType: string;\n thumbnail?: ApiThumbnail;\n previewBlobUrl?: string;\n mediaType?: 'photo' | 'video';\n mediaSize?: ApiDimensions;\n}\n\nexport interface ApiContact {\n firstName: string;\n lastName: string;\n phoneNumber: string;\n userId: string;\n}\n\nexport interface ApiPollAnswer {\n text: string;\n option: string;\n}\n\nexport interface ApiPollResult {\n isChosen?: true;\n isCorrect?: true;\n option: string;\n votersCount: number;\n}\n\nexport interface ApiPoll {\n id: string;\n summary: {\n closed?: true;\n isPublic?: true;\n multipleChoice?: true;\n quiz?: true;\n question: string;\n answers: ApiPollAnswer[];\n closePeriod?: number;\n closeDate?: number;\n };\n results: {\n results?: ApiPollResult[];\n totalVoters?: number;\n recentVoterIds?: string[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n}\n\nexport interface ApiInvoice {\n text: string;\n title: string;\n photoUrl?: string;\n amount: number;\n currency: string;\n receiptMsgId?: number;\n isTest?: boolean;\n}\n\nexport type ApiNewPoll = {\n summary: ApiPoll['summary'];\n quiz?: {\n correctAnswers: string[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n};\n\nexport interface ApiAction {\n text: string;\n targetUserIds?: string[];\n targetChatId?: string;\n type: 'historyClear' | 'contactSignUp' | 'chatCreate' | 'other';\n photo?: ApiPhoto;\n amount?: number;\n currency?: string;\n translationValues: string[];\n}\n\nexport interface ApiWebPage {\n id: number;\n url: string;\n displayUrl: string;\n type?: string;\n siteName?: string;\n title?: string;\n description?: string;\n photo?: ApiPhoto;\n duration?: number;\n document?: ApiDocument;\n video?: ApiVideo;\n}\n\nexport interface ApiMessageForwardInfo {\n isChannelPost: boolean;\n channelPostId?: number;\n isLinkedChannelPost?: boolean;\n fromChatId?: string;\n senderUserId?: string;\n fromMessageId?: number;\n hiddenUserName?: string;\n adminTitle?: string;\n}\n\nexport interface ApiMessageEntity {\n type: string;\n offset: number;\n length: number;\n userId?: string;\n url?: string;\n}\n\nexport enum ApiMessageEntityTypes {\n Bold = 'MessageEntityBold',\n Blockquote = 'MessageEntityBlockquote',\n BotCommand = 'MessageEntityBotCommand',\n Cashtag = 'MessageEntityCashtag',\n Code = 'MessageEntityCode',\n Email = 'MessageEntityEmail',\n Hashtag = 'MessageEntityHashtag',\n Italic = 'MessageEntityItalic',\n MentionName = 'MessageEntityMentionName',\n Mention = 'MessageEntityMention',\n Phone = 'MessageEntityPhone',\n Pre = 'MessageEntityPre',\n Strike = 'MessageEntityStrike',\n TextUrl = 'MessageEntityTextUrl',\n Url = 'MessageEntityUrl',\n Underline = 'MessageEntityUnderline',\n Unknown = 'MessageEntityUnknown',\n}\n\nexport interface ApiFormattedText {\n text: string;\n entities?: ApiMessageEntity[];\n}\n\nexport interface ApiMessage {\n id: number;\n chatId: string;\n content: {\n text?: ApiFormattedText;\n photo?: ApiPhoto;\n video?: ApiVideo;\n document?: ApiDocument;\n sticker?: ApiSticker;\n contact?: ApiContact;\n poll?: ApiPoll;\n action?: ApiAction;\n webPage?: ApiWebPage;\n audio?: ApiAudio;\n voice?: ApiVoice;\n invoice?: ApiInvoice;\n };\n date: number;\n isOutgoing: boolean;\n senderId?: string;\n replyToChatId?: string;\n replyToMessageId?: number;\n replyToTopMessageId?: number;\n sendingState?: 'messageSendingStatePending' | 'messageSendingStateFailed';\n forwardInfo?: ApiMessageForwardInfo;\n isDeleting?: boolean;\n previousLocalId?: number;\n views?: number;\n isEdited?: boolean;\n 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}\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 interface ApiKeyboardButton {\n type: 'command' | 'url' | 'callback' | 'requestPoll' | 'buy' | 'NOT_SUPPORTED';\n text: string;\n messageId: number;\n value?: string;\n}\n\nexport type ApiKeyboardButtons = ApiKeyboardButton[][];\nexport type ApiReplyKeyboard = {\n keyboardPlaceholder?: string;\n isKeyboardSingleUse?: boolean;\n} & {\n [K in 'inlineButtons' | 'keyboardButtons']?: ApiKeyboardButtons;\n};\n\nexport type ApiMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'voice' | 'profilePhoto';\nexport type ApiGlobalMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'voice';\n\nexport type ApiReportReason = 'spam' | 'violence' | 'pornography' | 'childAbuse'\n| 'copyright' | 'geoIrrelevant' | 'fake' | 'other';\n\nexport const MAIN_THREAD_ID = -1;\n\n// `Symbol` can not be transferred from worker\nexport const MESSAGE_DELETED = 'MESSAGE_DELETED';\n","// We cache avatars as Data URI for faster initial load\n// and messages media as Blob for smaller size.\n\nexport enum ApiMediaFormat {\n BlobUrl,\n Lottie,\n Progressive,\n Stream,\n}\n\nexport type ApiParsedMedia = string | Blob | AnyLiteral | ArrayBuffer;\nexport type ApiPreparedMedia = string | AnyLiteral;\nexport type ApiMediaFormatToPrepared = T extends ApiMediaFormat.Lottie ? AnyLiteral : string;\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\n\nimport { ApiPrivacyKey } from '../../../types';\n\nimport { generateRandomBytes, readBigIntFromBuffer } from '../../../lib/gramjs/Helpers';\nimport {\n ApiSticker,\n ApiVideo,\n ApiNewPoll,\n ApiMessageEntity,\n ApiMessageEntityTypes,\n ApiChatFolder,\n ApiChatBannedRights,\n ApiChatAdminRights,\n ApiReportReason,\n} from '../../types';\nimport localDb from '../localDb';\nimport { pick } from '../../../util/iteratees';\n\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 }) => new GramJs.PollAnswer({ text, option: Buffer.from(option) })),\n quiz: summary.quiz,\n multipleChoice: summary.multipleChoice,\n });\n\n if (!quiz) {\n return new GramJs.InputMediaPoll({ poll });\n }\n\n const correctAnswers = quiz.correctAnswers.map((key) => Buffer.from(key));\n const { solution } = quiz;\n const solutionEntities = quiz.solutionEntities ? quiz.solutionEntities.map(buildMtpMessageEntity) : [];\n\n return new GramJs.InputMediaPoll({\n poll,\n correctAnswers,\n ...(solution && {\n solution,\n solutionEntities,\n }),\n });\n}\n\nexport function buildFilterFromApiFolder(folder: ApiChatFolder): GramJs.DialogFilter {\n const {\n emoticon,\n contacts,\n nonContacts,\n groups,\n channels,\n bots,\n excludeArchived,\n excludeMuted,\n excludeRead,\n pinnedChatIds,\n includedChatIds,\n excludedChatIds,\n } = folder;\n\n const pinnedPeers = pinnedChatIds\n ? pinnedChatIds.map(buildInputPeerFromLocalDb).filter(Boolean as any)\n : [];\n\n const includePeers = includedChatIds\n ? includedChatIds.map(buildInputPeerFromLocalDb).filter(Boolean as any)\n : [];\n\n const excludePeers = excludedChatIds\n ? excludedChatIds.map(buildInputPeerFromLocalDb).filter(Boolean as any)\n : [];\n\n return new GramJs.DialogFilter({\n id: folder.id,\n title: folder.title,\n emoticon: emoticon || undefined,\n contacts: contacts || undefined,\n nonContacts: nonContacts || undefined,\n groups: groups || undefined,\n bots: bots || undefined,\n excludeArchived: excludeArchived || undefined,\n excludeMuted: excludeMuted || undefined,\n excludeRead: excludeRead || undefined,\n broadcasts: channels || undefined,\n pinnedPeers,\n includePeers,\n excludePeers,\n });\n}\n\nexport function generateRandomBigInt() {\n return readBigIntFromBuffer(generateRandomBytes(8), true, true);\n}\n\nexport function buildMessageFromUpdate(\n id: number,\n chatId: string,\n update: GramJs.UpdateShortSentMessage | GramJs.UpdateServiceNotification,\n) {\n // This is not a proper message, but we only need these fields for downloading media through `localDb`.\n return new GramJs.Message({\n id,\n peerId: buildPeer(chatId),\n fromId: buildPeer(chatId),\n media: update.media,\n } as GramJs.Message);\n}\n\nexport function buildMtpMessageEntity(entity: ApiMessageEntity): GramJs.TypeMessageEntity {\n const {\n type, offset, length, url, userId,\n } = entity;\n\n const user = userId ? localDb.users[userId] : undefined;\n\n switch (type) {\n case ApiMessageEntityTypes.Bold:\n return new GramJs.MessageEntityBold({ offset, length });\n case ApiMessageEntityTypes.Italic:\n return new GramJs.MessageEntityItalic({ offset, length });\n case ApiMessageEntityTypes.Underline:\n return new GramJs.MessageEntityUnderline({ offset, length });\n case ApiMessageEntityTypes.Strike:\n return new GramJs.MessageEntityStrike({ offset, length });\n case ApiMessageEntityTypes.Code:\n return new GramJs.MessageEntityCode({ offset, length });\n case ApiMessageEntityTypes.Pre:\n return new GramJs.MessageEntityPre({ offset, length, language: '' });\n case ApiMessageEntityTypes.Blockquote:\n return new GramJs.MessageEntityBlockquote({ offset, length });\n case ApiMessageEntityTypes.TextUrl:\n return new GramJs.MessageEntityTextUrl({ offset, length, url: url! });\n case ApiMessageEntityTypes.Url:\n return new GramJs.MessageEntityUrl({ offset, length });\n case ApiMessageEntityTypes.Hashtag:\n return new GramJs.MessageEntityHashtag({ offset, length });\n case ApiMessageEntityTypes.MentionName:\n return new GramJs.InputMessageEntityMentionName({\n offset,\n length,\n userId: new GramJs.InputUser({ userId: BigInt(userId!), accessHash: user!.accessHash! }),\n });\n default:\n return new GramJs.MessageEntityUnknown({ offset, length });\n }\n}\n\nexport function isMessageWithMedia(message: GramJs.Message | GramJs.UpdateServiceNotification) {\n const { media } = message;\n if (!media) {\n return false;\n }\n\n return (\n media instanceof GramJs.MessageMediaPhoto\n || media instanceof GramJs.MessageMediaDocument\n || (\n media instanceof GramJs.MessageMediaWebPage\n && media.webpage instanceof GramJs.WebPage\n && (\n media.webpage.photo instanceof GramJs.Photo || (\n media.webpage.document instanceof GramJs.Document\n && media.webpage.document.mimeType.startsWith('video')\n )\n )\n )\n );\n}\n\nexport function isServiceMessageWithMedia(message: GramJs.MessageService) {\n return 'photo' in message.action && message.action.photo instanceof GramJs.Photo;\n}\n\nexport function buildChatPhotoForLocalDb(photo: GramJs.TypePhoto) {\n if (photo instanceof GramJs.PhotoEmpty) {\n return new GramJs.ChatPhotoEmpty();\n }\n\n const { dcId, id: photoId } = photo;\n\n return new GramJs.ChatPhoto({\n dcId,\n photoId,\n });\n}\n\nexport function buildInputContact({\n phone,\n firstName,\n lastName,\n}: {\n phone: string;\n firstName: string;\n lastName: string;\n}) {\n return new GramJs.InputPhoneContact({\n clientId: BigInt(1),\n phone,\n firstName,\n lastName,\n });\n}\n\nexport function buildChatBannedRights(\n bannedRights: ApiChatBannedRights,\n untilDate = 0,\n) {\n return new GramJs.ChatBannedRights({\n ...bannedRights,\n untilDate,\n });\n}\n\nexport function buildChatAdminRights(\n adminRights: ApiChatAdminRights,\n) {\n return new GramJs.ChatAdminRights(adminRights);\n}\n\nexport function buildShippingInfo(info: GramJs.PaymentRequestedInfo) {\n const { shippingAddress } = info;\n return new GramJs.PaymentRequestedInfo({\n ...info,\n shippingAddress: shippingAddress\n ? new GramJs.PostAddress(shippingAddress)\n : undefined,\n });\n}\n\nexport function buildInputPrivacyKey(privacyKey: ApiPrivacyKey) {\n switch (privacyKey) {\n case 'phoneNumber':\n return new GramJs.InputPrivacyKeyPhoneNumber();\n\n case 'lastSeen':\n return new GramJs.InputPrivacyKeyStatusTimestamp();\n\n case 'profilePhoto':\n return new GramJs.InputPrivacyKeyProfilePhoto();\n\n case 'forwards':\n return new GramJs.InputPrivacyKeyForwards();\n\n case 'chatInvite':\n return new GramJs.InputPrivacyKeyChatInvite();\n }\n\n return undefined;\n}\n\nexport function buildInputReportReason(reason: ApiReportReason) {\n switch (reason) {\n case 'spam':\n return new GramJs.InputReportReasonSpam();\n case 'violence':\n return new GramJs.InputReportReasonViolence();\n case 'childAbuse':\n return new GramJs.InputReportReasonChildAbuse();\n case 'pornography':\n return new GramJs.InputReportReasonPornography();\n case 'copyright':\n return new GramJs.InputReportReasonCopyright();\n case 'fake':\n return new GramJs.InputReportReasonFake();\n case 'geoIrrelevant':\n return new GramJs.InputReportReasonGeoIrrelevant();\n case 'other':\n return new GramJs.InputReportReasonOther();\n }\n\n return undefined;\n}\n\nexport function 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","import BigInt from 'big-integer';\n\nimport { Api as GramJs } from '../../../lib/gramjs';\n\nexport function isPeerUser(peer: GramJs.TypePeer | GramJs.TypeInputPeer): peer is GramJs.PeerUser {\n return peer.hasOwnProperty('userId');\n}\n\nexport function isPeerChat(peer: GramJs.TypePeer | GramJs.TypeInputPeer): peer is GramJs.PeerChat {\n return peer.hasOwnProperty('chatId');\n}\n\nexport function isPeerChannel(peer: GramJs.TypePeer | GramJs.TypeInputPeer): peer is GramJs.PeerChannel {\n return peer.hasOwnProperty('channelId');\n}\n\nexport function buildApiPeerId(id: BigInt.BigInteger, type: 'user' | 'chat' | 'channel') {\n return type === 'user' ? String(id) : `-${id}`;\n}\n\nexport function getApiChatIdFromMtpPeer(peer: GramJs.TypePeer | GramJs.TypeInputPeer) {\n if (isPeerUser(peer)) {\n return buildApiPeerId(peer.userId, 'user');\n } else if (isPeerChat(peer)) {\n return buildApiPeerId(peer.chatId, 'chat');\n } else {\n return buildApiPeerId((peer as GramJs.InputPeerChannel).channelId, 'channel');\n }\n}\n","import { Api as GramJs } from '../../lib/gramjs';\nimport localDb from './localDb';\nimport { buildApiPeerId, getApiChatIdFromMtpPeer } from './apiBuilders/peers';\n\nexport function resolveMessageApiChatId(mtpMessage: GramJs.TypeMessage) {\n if (!(mtpMessage instanceof GramJs.Message || mtpMessage instanceof GramJs.MessageService)) {\n return undefined;\n }\n\n return getApiChatIdFromMtpPeer(mtpMessage.peerId);\n}\n\nexport function addMessageToLocalDb(message: GramJs.Message | GramJs.MessageService) {\n const messageFullId = `${resolveMessageApiChatId(message)}-${message.id}`;\n localDb.messages[messageFullId] = message;\n\n if (\n message instanceof GramJs.Message\n && message.media instanceof GramJs.MessageMediaDocument\n && message.media.document instanceof GramJs.Document\n ) {\n localDb.documents[String(message.media.document.id)] = message.media.document;\n }\n\n if (\n message instanceof GramJs.Message\n && message.media instanceof GramJs.MessageMediaWebPage\n && message.media.webpage instanceof GramJs.WebPage\n && message.media.webpage.document instanceof GramJs.Document\n ) {\n localDb.documents[String(message.media.webpage.document.id)] = message.media.webpage.document;\n }\n\n if (message instanceof GramJs.MessageService && 'photo' in message.action) {\n addPhotoToLocalDb(message.action.photo);\n }\n}\n\nexport function addPhotoToLocalDb(photo: GramJs.TypePhoto) {\n if (photo instanceof GramJs.Photo) {\n localDb.photos[String(photo.id)] = photo;\n }\n}\n\nexport function addChatToLocalDb(chat: GramJs.TypeChat) {\n if (chat instanceof GramJs.Chat || chat instanceof GramJs.Channel) {\n localDb.chats[buildApiPeerId(chat.id, chat instanceof GramJs.Chat ? 'chat' : 'channel')] = chat;\n }\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n ApiMessage,\n ApiMessageForwardInfo,\n ApiPhoto,\n ApiSticker,\n ApiVideo,\n ApiVoice,\n ApiAudio,\n ApiDocument,\n ApiAction,\n ApiContact,\n ApiAttachment,\n ApiPoll,\n ApiNewPoll,\n ApiWebPage,\n ApiMessageEntity,\n ApiFormattedText,\n ApiReplyKeyboard,\n ApiKeyboardButton,\n ApiChat,\n ApiThreadInfo,\n ApiInvoice,\n} from '../../types';\n\nimport {\n DELETED_COMMENTS_CHANNEL_ID,\n LOCAL_MESSAGE_ID_BASE,\n SERVICE_NOTIFICATIONS_USER_ID,\n SUPPORTED_IMAGE_CONTENT_TYPES,\n SUPPORTED_VIDEO_CONTENT_TYPES,\n VIDEO_MOV_TYPE,\n} from '../../../config';\nimport { pick } from '../../../util/iteratees';\nimport { buildStickerFromDocument } from './symbols';\nimport { buildApiPhoto, buildApiPhotoSize, buildApiThumbnailFromStripped } from './common';\nimport { interpolateArray } from '../../../util/waveform';\nimport { buildPeer } from '../gramjsBuilders';\nimport { addPhotoToLocalDb, resolveMessageApiChatId } from '../helpers';\nimport { buildApiPeerId, getApiChatIdFromMtpPeer } from './peers';\n\nconst LOCAL_MEDIA_UPLOADING_TEMP_ID = 'temp';\nconst INPUT_WAVEFORM_LENGTH = 63;\n\nlet localMessageCounter = LOCAL_MESSAGE_ID_BASE;\nlet currentUserId!: string;\n\nexport function setMessageBuilderCurrentUserId(_currentUserId: string) {\n currentUserId = _currentUserId;\n}\n\nexport function buildApiMessage(mtpMessage: GramJs.TypeMessage): ApiMessage | undefined {\n const chatId = resolveMessageApiChatId(mtpMessage);\n if (\n !chatId\n || !(mtpMessage instanceof GramJs.Message || mtpMessage instanceof GramJs.MessageService)) {\n return undefined;\n }\n\n return buildApiMessageWithChatId(chatId, mtpMessage);\n}\n\nexport function buildApiMessageFromShort(mtpMessage: GramJs.UpdateShortMessage): ApiMessage {\n const chatId = buildApiPeerId(mtpMessage.userId, 'user');\n\n return buildApiMessageWithChatId(chatId, {\n ...mtpMessage,\n fromId: buildPeer(mtpMessage.out ? currentUserId : buildApiPeerId(mtpMessage.userId, 'user')),\n });\n}\n\nexport function buildApiMessageFromShortChat(mtpMessage: GramJs.UpdateShortChatMessage): ApiMessage {\n const chatId = buildApiPeerId(mtpMessage.chatId, 'chat');\n\n return buildApiMessageWithChatId(chatId, {\n ...mtpMessage,\n fromId: buildPeer(buildApiPeerId(mtpMessage.fromId, 'user')),\n });\n}\n\nexport function buildApiMessageFromNotification(\n notification: GramJs.UpdateServiceNotification,\n currentDate: number,\n): ApiMessage {\n const localId = localMessageCounter++;\n let content: ApiMessage['content'] = {};\n\n if (notification.media) {\n content = {\n ...buildMessageMediaContent(notification.media),\n };\n }\n\n if (notification.message && !content.sticker && !content.poll && !content.contact) {\n content = {\n ...content,\n text: buildMessageTextContent(notification.message, notification.entities),\n };\n }\n\n return {\n id: localId,\n chatId: SERVICE_NOTIFICATIONS_USER_ID,\n date: notification.inboxDate || currentDate,\n content,\n isOutgoing: false,\n };\n}\n\ntype UniversalMessage = (\n Pick\n & Pick, (\n 'out' | 'message' | 'entities' | 'fromId' | 'peerId' | 'fwdFrom' | 'replyTo' | 'replyMarkup' | 'post' |\n 'media' | 'action' | 'views' | 'editDate' | 'editHide' | 'mediaUnread' | 'groupedId' | 'mentioned' | 'viaBotId' |\n 'replies' | 'fromScheduled' | 'postAuthor'\n )>\n);\n\nexport function buildApiMessageWithChatId(chatId: string, mtpMessage: UniversalMessage): ApiMessage {\n const fromId = mtpMessage.fromId ? getApiChatIdFromMtpPeer(mtpMessage.fromId) : undefined;\n const peerId = mtpMessage.peerId ? getApiChatIdFromMtpPeer(mtpMessage.peerId) : undefined;\n const isChatWithSelf = !fromId && chatId === currentUserId;\n const isOutgoing = (mtpMessage.out && !mtpMessage.post) || (isChatWithSelf && !mtpMessage.fwdFrom);\n\n let content: ApiMessage['content'] = {};\n\n if (mtpMessage.media) {\n content = {\n ...buildMessageMediaContent(mtpMessage.media),\n };\n }\n\n if (mtpMessage.message && !content.sticker && !content.poll && !content.contact) {\n content = {\n ...content,\n text: buildMessageTextContent(mtpMessage.message, mtpMessage.entities),\n };\n }\n\n const action = mtpMessage.action\n && buildAction(mtpMessage.action, fromId, peerId, Boolean(mtpMessage.post), isOutgoing);\n if (action) {\n content.action = action;\n }\n\n const { replyToMsgId, replyToTopId, replyToPeerId } = mtpMessage.replyTo || {};\n const isEdited = mtpMessage.editDate && !mtpMessage.editHide;\n const {\n inlineButtons, keyboardButtons, keyboardPlaceholder, isKeyboardSingleUse,\n } = buildReplyButtons(mtpMessage) || {};\n const forwardInfo = mtpMessage.fwdFrom && buildApiMessageForwardInfo(mtpMessage.fwdFrom, isChatWithSelf);\n const { replies, mediaUnread: isMediaUnread, postAuthor } = mtpMessage;\n const groupedId = mtpMessage.groupedId && String(mtpMessage.groupedId);\n const isInAlbum = Boolean(groupedId) && !(content.document || content.audio);\n const shouldHideKeyboardButtons = mtpMessage.replyMarkup instanceof GramJs.ReplyKeyboardHide;\n\n return {\n id: mtpMessage.id,\n chatId,\n isOutgoing,\n content,\n date: mtpMessage.date,\n senderId: fromId || (mtpMessage.out && mtpMessage.post && currentUserId) || chatId,\n views: mtpMessage.views,\n isFromScheduled: mtpMessage.fromScheduled,\n ...(replyToMsgId && { replyToMessageId: replyToMsgId }),\n ...(replyToPeerId && { replyToChatId: getApiChatIdFromMtpPeer(replyToPeerId) }),\n ...(replyToTopId && { replyToTopMessageId: replyToTopId }),\n ...(forwardInfo && { forwardInfo }),\n ...(isEdited && { isEdited }),\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 };\n}\n\nexport function buildMessageTextContent(\n message: string,\n entities?: GramJs.TypeMessageEntity[],\n): ApiFormattedText {\n return {\n text: message,\n ...(entities && { entities: entities.map(buildApiMessageEntity) }),\n };\n}\n\nexport function buildMessageDraft(draft: GramJs.TypeDraftMessage) {\n if (draft instanceof GramJs.DraftMessageEmpty) {\n return undefined;\n }\n\n const {\n message, entities, replyToMsgId, date,\n } = draft;\n\n return {\n formattedText: message ? buildMessageTextContent(message, entities) : undefined,\n replyingToId: replyToMsgId,\n date,\n };\n}\n\nexport function buildMessageMediaContent(media: GramJs.TypeMessageMedia): ApiMessage['content'] | undefined {\n if ('ttlSeconds' in media && media.ttlSeconds) {\n return undefined;\n }\n\n const sticker = buildSticker(media);\n if (sticker) return { sticker };\n\n const photo = buildPhoto(media);\n if (photo) return { photo };\n\n const video = buildVideo(media);\n if (video) return { video };\n\n const audio = buildAudio(media);\n if (audio) return { audio };\n\n const voice = buildVoice(media);\n if (voice) return { voice };\n\n const document = buildDocumentFromMedia(media);\n if (document) return { document };\n\n const contact = buildContact(media);\n if (contact) return { contact };\n\n const poll = buildPollFromMedia(media);\n if (poll) return { poll };\n\n const webPage = buildWebPage(media);\n if (webPage) return { webPage };\n\n const invoice = buildInvoiceFromMedia(media);\n if (invoice) return { invoice };\n\n return undefined;\n}\n\nfunction buildApiMessageForwardInfo(fwdFrom: GramJs.MessageFwdHeader, isChatWithSelf = false): ApiMessageForwardInfo {\n const savedFromPeerId = fwdFrom.savedFromPeer && getApiChatIdFromMtpPeer(fwdFrom.savedFromPeer);\n const fromId = fwdFrom.fromId && getApiChatIdFromMtpPeer(fwdFrom.fromId);\n\n return {\n isChannelPost: Boolean(fwdFrom.channelPost),\n channelPostId: fwdFrom.channelPost,\n isLinkedChannelPost: Boolean(fwdFrom.channelPost && savedFromPeerId && !isChatWithSelf),\n fromChatId: savedFromPeerId || fromId,\n fromMessageId: fwdFrom.channelPost || fwdFrom.savedFromMsgId,\n senderUserId: fromId,\n hiddenUserName: fwdFrom.fromName,\n adminTitle: fwdFrom.postAuthor,\n };\n}\n\nfunction buildSticker(media: GramJs.TypeMessageMedia): ApiSticker | undefined {\n if (\n !(media instanceof GramJs.MessageMediaDocument)\n || !media.document\n || !(media.document instanceof GramJs.Document)\n ) {\n return undefined;\n }\n\n return buildStickerFromDocument(media.document);\n}\n\nfunction buildPhoto(media: GramJs.TypeMessageMedia): ApiPhoto | undefined {\n if (!(media instanceof GramJs.MessageMediaPhoto) || !media.photo || !(media.photo instanceof GramJs.Photo)) {\n return undefined;\n }\n\n return buildApiPhoto(media.photo);\n}\n\nexport function buildVideoFromDocument(document: GramJs.Document): ApiVideo | undefined {\n if (document instanceof GramJs.DocumentEmpty) {\n return undefined;\n }\n\n const {\n id, mimeType, thumbs, size, attributes,\n } = document;\n\n // eslint-disable-next-line no-restricted-globals\n if (mimeType === VIDEO_MOV_TYPE && !(self as any).isMovSupported) {\n return undefined;\n }\n\n const videoAttr = attributes\n .find((a: any): a is GramJs.DocumentAttributeVideo => a instanceof GramJs.DocumentAttributeVideo);\n\n if (!videoAttr) {\n return undefined;\n }\n\n const gifAttr = attributes\n .find((a: any): a is GramJs.DocumentAttributeAnimated => a instanceof GramJs.DocumentAttributeAnimated);\n\n const {\n duration,\n w: width,\n h: height,\n supportsStreaming = false,\n roundMessage: isRound = false,\n } = videoAttr;\n\n return {\n id: String(id),\n mimeType,\n duration,\n fileName: getFilenameFromDocument(document, 'video'),\n width,\n height,\n supportsStreaming,\n isRound,\n isGif: Boolean(gifAttr),\n thumbnail: buildApiThumbnailFromStripped(thumbs),\n size,\n };\n}\n\nfunction buildVideo(media: GramJs.TypeMessageMedia): ApiVideo | undefined {\n if (\n !(media instanceof GramJs.MessageMediaDocument)\n || !(media.document instanceof GramJs.Document)\n || !media.document.mimeType.startsWith('video')\n ) {\n return undefined;\n }\n\n return buildVideoFromDocument(media.document);\n}\n\nfunction buildAudio(media: GramJs.TypeMessageMedia): ApiAudio | undefined {\n if (\n !(media instanceof GramJs.MessageMediaDocument)\n || !media.document\n || !(media.document instanceof GramJs.Document)\n ) {\n return undefined;\n }\n\n const audioAttribute = media.document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeAudio => (\n attr instanceof GramJs.DocumentAttributeAudio\n ));\n\n if (!audioAttribute || audioAttribute.voice) {\n return undefined;\n }\n\n const thumbnailSizes = media.document.thumbs && media.document.thumbs\n .filter((thumb): thumb is GramJs.PhotoSize => thumb instanceof GramJs.PhotoSize)\n .map((thumb) => buildApiPhotoSize(thumb));\n\n return {\n fileName: getFilenameFromDocument(media.document, 'audio'),\n thumbnailSizes,\n ...pick(media.document, ['size', 'mimeType']),\n ...pick(audioAttribute, ['duration', 'performer', 'title']),\n };\n}\n\nfunction buildVoice(media: GramJs.TypeMessageMedia): ApiVoice | undefined {\n if (\n !(media instanceof GramJs.MessageMediaDocument)\n || !media.document\n || !(media.document instanceof GramJs.Document)\n ) {\n return undefined;\n }\n\n const audioAttribute = media.document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeAudio => (\n attr instanceof GramJs.DocumentAttributeAudio\n ));\n\n if (!audioAttribute || !audioAttribute.voice) {\n return undefined;\n }\n\n const { duration, waveform } = audioAttribute;\n\n return {\n duration,\n waveform: waveform ? Array.from(waveform) : undefined,\n };\n}\n\nfunction buildDocumentFromMedia(media: GramJs.TypeMessageMedia) {\n if (!(media instanceof GramJs.MessageMediaDocument) || !media.document) {\n return undefined;\n }\n\n return buildApiDocument(media.document);\n}\n\nexport function buildApiDocument(document: GramJs.TypeDocument): ApiDocument | undefined {\n if (!(document instanceof GramJs.Document)) {\n return undefined;\n }\n\n const {\n id, size, mimeType, date, thumbs, attributes,\n } = document;\n\n const thumbnail = thumbs && buildApiThumbnailFromStripped(thumbs);\n\n let mediaType: ApiDocument['mediaType'] | undefined;\n let mediaSize: ApiDocument['mediaSize'] | undefined;\n const photoSize = thumbs && thumbs.find((s: any): s is GramJs.PhotoSize => s instanceof GramJs.PhotoSize);\n if (photoSize) {\n mediaSize = {\n width: photoSize.w,\n height: photoSize.h,\n };\n\n if (SUPPORTED_IMAGE_CONTENT_TYPES.has(mimeType)) {\n mediaType = 'photo';\n\n const imageAttribute = attributes\n .find((a: any): a is GramJs.DocumentAttributeImageSize => a instanceof GramJs.DocumentAttributeImageSize);\n\n if (imageAttribute) {\n const { w: width, h: height } = imageAttribute;\n mediaSize = {\n width,\n height,\n };\n }\n } else if (SUPPORTED_VIDEO_CONTENT_TYPES.has(mimeType)) {\n mediaType = 'video';\n }\n }\n\n return {\n id: String(id),\n size,\n mimeType,\n timestamp: date,\n fileName: getFilenameFromDocument(document),\n thumbnail,\n mediaType,\n mediaSize,\n };\n}\n\nfunction buildContact(media: GramJs.TypeMessageMedia): ApiContact | undefined {\n if (!(media instanceof GramJs.MessageMediaContact)) {\n return undefined;\n }\n\n const {\n firstName, lastName, phoneNumber, userId,\n } = media;\n\n return {\n firstName, lastName, phoneNumber, userId: buildApiPeerId(userId, 'user'),\n };\n}\n\nfunction buildPollFromMedia(media: GramJs.TypeMessageMedia): ApiPoll | undefined {\n if (!(media instanceof GramJs.MessageMediaPoll)) {\n return undefined;\n }\n\n return buildPoll(media.poll, media.results);\n}\n\nfunction buildInvoiceFromMedia(media: GramJs.TypeMessageMedia): ApiInvoice | undefined {\n if (!(media instanceof GramJs.MessageMediaInvoice)) {\n return undefined;\n }\n\n return buildInvoice(media);\n}\n\nexport function buildPoll(poll: GramJs.Poll, pollResults: GramJs.PollResults): ApiPoll {\n const { id, answers: rawAnswers } = poll;\n const answers = rawAnswers.map((answer) => ({\n text: answer.text,\n option: String.fromCharCode(...answer.option),\n }));\n\n return {\n id: String(id),\n summary: {\n isPublic: poll.publicVoters,\n ...pick(poll, [\n 'closed',\n 'multipleChoice',\n 'quiz',\n 'question',\n 'closePeriod',\n 'closeDate',\n ]),\n answers,\n },\n results: buildPollResults(pollResults),\n };\n}\n\nexport function buildInvoice(media: GramJs.MessageMediaInvoice): ApiInvoice {\n const {\n description: text, title, photo, test, totalAmount, currency, receiptMsgId,\n } = media;\n\n return {\n text,\n title,\n photoUrl: photo?.url,\n receiptMsgId,\n amount: Number(totalAmount),\n currency,\n isTest: test,\n };\n}\n\nexport function buildPollResults(pollResults: GramJs.PollResults): ApiPoll['results'] {\n const {\n results: rawResults, totalVoters, recentVoters, solution, solutionEntities: entities,\n } = pollResults;\n const results = rawResults && rawResults.map(({\n option, chosen, correct, voters,\n }) => ({\n isChosen: chosen,\n isCorrect: correct,\n option: String.fromCharCode(...option),\n votersCount: voters,\n }));\n\n return {\n totalVoters,\n recentVoterIds: recentVoters?.map((id) => buildApiPeerId(id, 'user')),\n results,\n solution,\n ...(entities && { solutionEntities: entities.map(buildApiMessageEntity) }),\n };\n}\n\nexport function buildWebPage(media: GramJs.TypeMessageMedia): ApiWebPage | undefined {\n if (\n !(media instanceof GramJs.MessageMediaWebPage)\n || !(media.webpage instanceof GramJs.WebPage)\n ) {\n return undefined;\n }\n\n const { id, photo, document } = media.webpage;\n\n let video;\n if (document instanceof GramJs.Document && document.mimeType.startsWith('video/')) {\n video = buildVideoFromDocument(document);\n }\n\n return {\n id: Number(id),\n ...pick(media.webpage, [\n 'url',\n 'displayUrl',\n 'type',\n 'siteName',\n 'title',\n 'description',\n 'duration',\n ]),\n photo: photo instanceof GramJs.Photo ? buildApiPhoto(photo) : undefined,\n document: !video && document ? buildApiDocument(document) : undefined,\n video,\n };\n}\n\nfunction buildAction(\n action: GramJs.TypeMessageAction,\n senderId: string | undefined,\n targetPeerId: string | undefined,\n isChannelPost: boolean,\n isOutgoing: boolean,\n): ApiAction | undefined {\n if (action instanceof GramJs.MessageActionEmpty) {\n return undefined;\n }\n\n let amount: number | undefined;\n let currency: string | undefined;\n let text: string;\n const translationValues = [];\n let type: ApiAction['type'] = 'other';\n let photo: ApiPhoto | undefined;\n\n const targetUserIds = 'users' in action\n ? action.users && action.users.map((id) => buildApiPeerId(id, 'user'))\n : ('userId' in action && [buildApiPeerId(action.userId, 'user')]) || [];\n let targetChatId: string | undefined;\n\n if (action instanceof GramJs.MessageActionChatCreate) {\n text = 'Notification.CreatedChatWithTitle';\n translationValues.push('%action_origin%', action.title);\n type = 'chatCreate';\n } else if (action instanceof GramJs.MessageActionChatEditTitle) {\n if (isChannelPost) {\n text = 'Channel.MessageTitleUpdated';\n translationValues.push(action.title);\n } else {\n text = 'Notification.ChangedGroupName';\n translationValues.push('%action_origin%', action.title);\n }\n } else if (action instanceof GramJs.MessageActionChatEditPhoto) {\n if (isChannelPost) {\n text = 'Channel.MessagePhotoUpdated';\n } else {\n text = 'Notification.ChangedGroupPhoto';\n translationValues.push('%action_origin%');\n }\n } else if (action instanceof GramJs.MessageActionChatDeletePhoto) {\n if (isChannelPost) {\n text = 'Channel.MessagePhotoRemoved';\n } else {\n text = 'Group.MessagePhotoRemoved';\n }\n } else if (action instanceof GramJs.MessageActionChatAddUser) {\n if (!senderId || targetUserIds.includes(senderId)) {\n text = 'Notification.JoinedChat';\n translationValues.push('%target_user%');\n } else {\n text = 'Notification.Invited';\n translationValues.push('%action_origin%', '%target_user%');\n }\n } else if (action instanceof GramJs.MessageActionChatDeleteUser) {\n if (!senderId || targetUserIds.includes(senderId)) {\n text = 'Notification.LeftChat';\n translationValues.push('%target_user%');\n } else {\n text = 'Notification.Kicked';\n translationValues.push('%action_origin%', '%target_user%');\n }\n } else if (action instanceof GramJs.MessageActionChatJoinedByLink) {\n text = 'Notification.JoinedGroupByLink';\n translationValues.push('%action_origin%');\n } else if (action instanceof GramJs.MessageActionChannelCreate) {\n text = 'Notification.CreatedChannel';\n } else if (action instanceof GramJs.MessageActionChatMigrateTo) {\n targetChatId = getApiChatIdFromMtpPeer(action);\n text = 'Migrated to %target_chat%';\n translationValues.push('%target_chat%');\n } else if (action instanceof GramJs.MessageActionChannelMigrateFrom) {\n targetChatId = getApiChatIdFromMtpPeer(action);\n text = 'Migrated from %target_chat%';\n translationValues.push('%target_chat%');\n } else if (action instanceof GramJs.MessageActionPinMessage) {\n text = 'Chat.Service.Group.UpdatedPinnedMessage1';\n translationValues.push('%action_origin%', '%message%');\n } else if (action instanceof GramJs.MessageActionHistoryClear) {\n text = 'HistoryCleared';\n type = 'historyClear';\n } else if (action instanceof GramJs.MessageActionPhoneCall) {\n const withDuration = Boolean(action.duration);\n text = [\n withDuration ? 'ChatList.Service' : 'Chat',\n action.video ? 'VideoCall' : 'Call',\n isOutgoing ? (withDuration ? 'outgoing' : 'Outgoing') : (withDuration ? 'incoming' : 'Incoming'),\n ].join('.');\n\n if (withDuration) {\n const mins = Math.max(Math.round(action.duration! / 60), 1);\n translationValues.push(`${mins} min${mins > 1 ? 's' : ''}`);\n }\n } else if (action instanceof GramJs.MessageActionContactSignUp) {\n text = 'Notification.Joined';\n translationValues.push('%action_origin%');\n type = 'contactSignUp';\n } else if (action instanceof GramJs.MessageActionPaymentSent) {\n amount = Number(action.totalAmount);\n currency = action.currency;\n text = 'PaymentSuccessfullyPaid';\n if (targetPeerId) {\n targetUserIds.push(targetPeerId);\n }\n translationValues.push('%payment_amount%', '%target_user%', '%product%');\n } else if (action instanceof GramJs.MessageActionGroupCall) {\n if (action.duration) {\n const mins = Math.max(Math.round(action.duration / 60), 1);\n text = 'Notification.VoiceChatEnded';\n translationValues.push(`${mins} min${mins > 1 ? 's' : ''}`);\n } else {\n text = 'Notification.VoiceChatStartedChannel';\n }\n } else if (action instanceof GramJs.MessageActionBotAllowed) {\n text = 'Chat.Service.BotPermissionAllowed';\n translationValues.push(action.domain);\n } else {\n text = 'ChatList.UnsupportedMessage';\n }\n\n if ('photo' in action && action.photo instanceof GramJs.Photo) {\n addPhotoToLocalDb(action.photo);\n photo = buildApiPhoto(action.photo);\n }\n\n return {\n text,\n type,\n targetUserIds,\n targetChatId,\n photo, // TODO Only used internally now, will be used for the UI in future\n amount,\n currency,\n translationValues,\n };\n}\n\nfunction buildReplyButtons(message: UniversalMessage): ApiReplyKeyboard | undefined {\n const { id: messageId, replyMarkup, media } = message;\n\n if (!replyMarkup) {\n if (media instanceof GramJs.MessageMediaWebPage && media.webpage instanceof GramJs.WebPage) {\n if (media.webpage.type === 'telegram_message') {\n return {\n inlineButtons: [[{\n type: 'url' as const,\n text: 'Show Message',\n messageId,\n value: media.webpage.url,\n }]],\n };\n }\n }\n\n return undefined;\n }\n\n // TODO\n if (!(replyMarkup instanceof GramJs.ReplyKeyboardMarkup || replyMarkup instanceof GramJs.ReplyInlineMarkup)) {\n return undefined;\n }\n\n const markup = replyMarkup.rows.map(({ buttons }) => {\n return buttons.map((button) => {\n let { text } = button;\n\n let type;\n let value;\n if (button instanceof GramJs.KeyboardButton) {\n type = 'command';\n value = text;\n } else if (button instanceof GramJs.KeyboardButtonUrl) {\n type = 'url';\n value = button.url;\n } else if (button instanceof GramJs.KeyboardButtonCallback) {\n type = 'callback';\n value = String(button.data);\n } else if (button instanceof GramJs.KeyboardButtonRequestPoll) {\n type = 'requestPoll';\n } else if (button instanceof GramJs.KeyboardButtonBuy) {\n if (media instanceof GramJs.MessageMediaInvoice && media.receiptMsgId) {\n text = 'PaymentReceipt';\n value = media.receiptMsgId;\n }\n type = 'buy';\n } else {\n type = 'NOT_SUPPORTED';\n }\n\n return {\n type,\n text,\n messageId,\n value,\n } as ApiKeyboardButton;\n });\n });\n\n return {\n [replyMarkup instanceof GramJs.ReplyKeyboardMarkup ? 'keyboardButtons' : 'inlineButtons']: markup,\n ...(replyMarkup instanceof GramJs.ReplyKeyboardMarkup && {\n keyboardPlaceholder: replyMarkup.placeholder,\n isKeyboardSingleUse: replyMarkup.singleUse,\n }),\n };\n}\n\nfunction getFilenameFromDocument(document: GramJs.Document, defaultBase = 'file') {\n const { mimeType, attributes } = document;\n const filenameAttribute = attributes\n .find((a: any): a is GramJs.DocumentAttributeFilename => a instanceof GramJs.DocumentAttributeFilename);\n\n if (filenameAttribute) {\n return filenameAttribute.fileName;\n }\n\n const extension = mimeType.split('/')[1];\n\n return `${defaultBase}${String(document.id)}.${extension}`;\n}\n\nexport function buildLocalMessage(\n chat: ApiChat,\n text?: string,\n entities?: ApiMessageEntity[],\n replyingTo?: number,\n attachment?: ApiAttachment,\n sticker?: ApiSticker,\n gif?: ApiVideo,\n poll?: ApiNewPoll,\n groupedId?: string,\n scheduledAt?: number,\n serverTimeOffset = 0,\n): ApiMessage {\n const localId = localMessageCounter++;\n const media = attachment && buildUploadingMedia(attachment);\n const isChannel = chat.type === 'chatTypeChannel';\n\n return {\n id: localId,\n chatId: chat.id,\n content: {\n ...(text && {\n text: {\n text,\n entities,\n },\n }),\n ...media,\n ...(sticker && { sticker }),\n ...(gif && { video: gif }),\n ...(poll && buildNewPoll(poll, localId)),\n },\n date: scheduledAt || Math.round(Date.now() / 1000) + serverTimeOffset,\n isOutgoing: !isChannel,\n senderId: currentUserId,\n ...(replyingTo && { replyToMessageId: replyingTo }),\n ...(groupedId && {\n groupedId,\n ...(media && (media.photo || media.video) && { isInAlbum: true }),\n }),\n ...(scheduledAt && { isScheduled: true }),\n };\n}\n\nexport function buildLocalForwardedMessage(\n toChat: ApiChat,\n message: ApiMessage,\n serverTimeOffset: number,\n scheduledAt?: number,\n): ApiMessage {\n const localId = localMessageCounter++;\n const {\n content,\n chatId: fromChatId,\n id: fromMessageId,\n senderId,\n groupedId,\n isInAlbum,\n } = message;\n\n const isAudio = content.audio;\n const asIncomingInChatWithSelf = (\n toChat.id === currentUserId && (fromChatId !== toChat.id || message.forwardInfo) && !isAudio\n );\n\n return {\n id: localId,\n chatId: toChat.id,\n content,\n date: scheduledAt || Math.round(Date.now() / 1000) + serverTimeOffset,\n isOutgoing: !asIncomingInChatWithSelf && toChat.type !== 'chatTypeChannel',\n senderId: currentUserId,\n sendingState: 'messageSendingStatePending',\n groupedId,\n isInAlbum,\n // Forward info doesn't get added when users forwards his own messages, also when forwarding audio\n ...(senderId !== currentUserId && !isAudio && {\n forwardInfo: {\n isChannelPost: false,\n fromChatId,\n fromMessageId,\n senderUserId: senderId,\n },\n }),\n ...(scheduledAt && { isScheduled: true }),\n };\n}\n\nfunction buildUploadingMedia(\n attachment: ApiAttachment,\n): ApiMessage['content'] {\n const {\n filename: fileName,\n blobUrl,\n previewBlobUrl,\n mimeType,\n size,\n } = attachment;\n\n if (attachment.quick) {\n const { width, height, duration } = attachment.quick;\n\n if (mimeType.startsWith('image/')) {\n return {\n photo: {\n id: LOCAL_MEDIA_UPLOADING_TEMP_ID,\n sizes: [],\n thumbnail: { width, height, dataUri: '' }, // Used only for dimensions\n blobUrl,\n },\n };\n } else {\n return {\n video: {\n id: LOCAL_MEDIA_UPLOADING_TEMP_ID,\n mimeType,\n duration: duration || 0,\n fileName,\n width,\n height,\n blobUrl,\n ...(previewBlobUrl && { thumbnail: { width, height, dataUri: previewBlobUrl } }),\n size,\n },\n };\n }\n } else if (attachment.voice) {\n const { duration, waveform } = attachment.voice;\n const { data: inputWaveform } = interpolateArray(waveform, INPUT_WAVEFORM_LENGTH);\n return {\n voice: {\n duration,\n waveform: inputWaveform,\n },\n };\n } else if (mimeType.startsWith('audio/')) {\n return {\n audio: {\n mimeType,\n fileName,\n size,\n duration: 200, // Arbitrary\n },\n };\n } else {\n return {\n document: {\n mimeType,\n fileName,\n size,\n ...(previewBlobUrl && { previewBlobUrl }),\n },\n };\n }\n}\n\nfunction buildNewPoll(poll: ApiNewPoll, localId: number) {\n return {\n poll: {\n id: String(localId),\n summary: pick(poll.summary, ['question', 'answers']),\n results: {},\n },\n };\n}\n\nfunction buildApiMessageEntity(entity: GramJs.TypeMessageEntity): ApiMessageEntity {\n const { className: type, offset, length } = entity;\n return {\n type,\n offset,\n length,\n ...('userId' in entity && typeof entity.userId === 'number' && { userId: entity.userId }),\n ...('url' in entity && { url: entity.url }),\n };\n}\n\nfunction buildThreadInfo(\n messageReplies: GramJs.TypeMessageReplies, messageId: number, chatId: string,\n): ApiThreadInfo | undefined {\n const {\n channelId, replies, maxId, readMaxId, recentRepliers,\n } = messageReplies;\n if (!channelId) {\n return undefined;\n }\n\n const apiChannelId = buildApiPeerId(channelId, 'channel');\n if (apiChannelId === DELETED_COMMENTS_CHANNEL_ID) {\n return undefined;\n }\n\n const isPostThread = chatId !== apiChannelId;\n\n return {\n threadId: messageId,\n ...(isPostThread ? {\n chatId: apiChannelId,\n originChannelId: chatId,\n } : {\n chatId,\n }),\n messagesCount: replies,\n lastMessageId: maxId,\n lastReadInboxMessageId: readMaxId,\n ...(recentRepliers && { recentReplierIds: recentRepliers.map(getApiChatIdFromMtpPeer) }),\n };\n}\n","export const getServerTime = (serverTimeOffset: number) => {\n return Math.floor(Date.now() / 1000) + serverTimeOffset;\n};\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport {\n ApiChat,\n ApiChatAdminRights,\n ApiChatBannedRights,\n ApiBotCommand,\n ApiChatFolder,\n ApiChatMember,\n ApiRestrictionReason,\n} from '../../types';\nimport { pick, pickTruthy } from '../../../util/iteratees';\nimport {\n buildApiPeerId, getApiChatIdFromMtpPeer, isPeerChat, isPeerUser,\n} from './peers';\nimport { omitVirtualClassFields } from './helpers';\nimport { getServerTime } from '../../../util/serverTime';\n\ntype PeerEntityApiChatFields = Omit;\n\nfunction buildApiChatFieldsFromPeerEntity(\n peerEntity: GramJs.TypeUser | GramJs.TypeChat,\n isSupport = false,\n): PeerEntityApiChatFields {\n const isMin = Boolean('min' in peerEntity && peerEntity.min);\n const accessHash = ('accessHash' in peerEntity) && String(peerEntity.accessHash);\n const avatarHash = ('photo' in peerEntity) && peerEntity.photo && buildAvatarHash(peerEntity.photo);\n const isSignaturesShown = Boolean('signatures' in peerEntity && peerEntity.signatures);\n const hasPrivateLink = Boolean('hasLink' in peerEntity && peerEntity.hasLink);\n\n return {\n isMin,\n hasPrivateLink,\n isSignaturesShown,\n ...(accessHash && { accessHash }),\n ...(avatarHash && { avatarHash }),\n ...(\n (peerEntity instanceof GramJs.Channel || peerEntity instanceof GramJs.User)\n && { username: peerEntity.username }\n ),\n ...(('verified' in peerEntity) && { isVerified: peerEntity.verified }),\n ...(('callActive' in peerEntity) && { isCallActive: peerEntity.callActive }),\n ...(('callNotEmpty' in peerEntity) && { isCallNotEmpty: peerEntity.callNotEmpty }),\n ...((peerEntity instanceof GramJs.Chat || peerEntity instanceof GramJs.Channel) && {\n ...(peerEntity.participantsCount && { membersCount: peerEntity.participantsCount }),\n joinDate: peerEntity.date,\n }),\n ...(isSupport && { isSupport: true }),\n ...buildApiChatPermissions(peerEntity),\n ...(('creator' in peerEntity) && { isCreator: peerEntity.creator }),\n ...buildApiChatRestrictions(peerEntity),\n ...buildApiChatMigrationInfo(peerEntity),\n };\n}\n\nexport function buildApiChatFromDialog(\n dialog: GramJs.Dialog,\n peerEntity: GramJs.TypeUser | GramJs.TypeChat,\n serverTimeOffset: number,\n): ApiChat {\n const {\n peer, folderId, unreadMark, unreadCount, unreadMentionsCount, notifySettings: { silent, muteUntil },\n readOutboxMaxId, readInboxMaxId, draft,\n } = dialog;\n const isMuted = silent || (typeof muteUntil === 'number' && getServerTime(serverTimeOffset) < muteUntil);\n\n return {\n id: getApiChatIdFromMtpPeer(peer),\n ...(folderId && { folderId }),\n type: getApiChatTypeFromPeerEntity(peerEntity),\n title: getApiChatTitleFromMtpPeer(peer, peerEntity),\n lastReadOutboxMessageId: readOutboxMaxId,\n lastReadInboxMessageId: readInboxMaxId,\n unreadCount,\n unreadMentionsCount,\n isMuted,\n ...(unreadMark && { hasUnreadMark: true }),\n ...(draft instanceof GramJs.DraftMessage && { draftDate: draft.date }),\n ...buildApiChatFieldsFromPeerEntity(peerEntity),\n };\n}\n\nfunction buildApiChatPermissions(peerEntity: GramJs.TypeUser | GramJs.TypeChat): {\n adminRights?: ApiChatAdminRights;\n currentUserBannedRights?: ApiChatBannedRights;\n defaultBannedRights?: ApiChatBannedRights;\n} {\n if (!(peerEntity instanceof GramJs.Chat || peerEntity instanceof GramJs.Channel)) {\n return {};\n }\n\n return {\n adminRights: peerEntity.adminRights ? omitVirtualClassFields(peerEntity.adminRights) : undefined,\n currentUserBannedRights: peerEntity instanceof GramJs.Channel && peerEntity.bannedRights\n ? omitVirtualClassFields(peerEntity.bannedRights)\n : undefined,\n defaultBannedRights: peerEntity.defaultBannedRights\n ? omitVirtualClassFields(peerEntity.defaultBannedRights)\n : undefined,\n };\n}\n\nfunction buildApiChatRestrictions(peerEntity: GramJs.TypeUser | GramJs.TypeChat): {\n isNotJoined?: boolean;\n isRestricted?: boolean;\n restrictionReason?: ApiRestrictionReason;\n} {\n if (peerEntity instanceof GramJs.ChatForbidden || peerEntity instanceof GramJs.ChannelForbidden) {\n return {\n isRestricted: true,\n };\n }\n\n const restrictions = {};\n\n if ('restricted' in peerEntity) {\n const restrictionReason = peerEntity.restricted\n ? buildApiChatRestrictionReason(peerEntity.restrictionReason)\n : undefined;\n\n if (restrictionReason) {\n Object.assign(restrictions, {\n isRestricted: true,\n restrictionReason,\n });\n }\n }\n\n if (peerEntity instanceof GramJs.Chat) {\n Object.assign(restrictions, {\n isNotJoined: peerEntity.left,\n isRestricted: peerEntity.kicked,\n });\n }\n\n if (peerEntity instanceof GramJs.Channel) {\n Object.assign(restrictions, {\n // `left` is weirdly set to `true` on all channels never joined before\n isNotJoined: peerEntity.left,\n });\n }\n\n return restrictions;\n}\n\nfunction buildApiChatMigrationInfo(peerEntity: GramJs.TypeChat): {\n migratedTo?: {\n chatId: string;\n accessHash?: string;\n };\n} {\n if (\n peerEntity instanceof GramJs.Chat\n && peerEntity.migratedTo\n && !(peerEntity.migratedTo instanceof GramJs.InputChannelEmpty)\n ) {\n return {\n migratedTo: {\n chatId: getApiChatIdFromMtpPeer(peerEntity.migratedTo),\n ...(peerEntity.migratedTo instanceof GramJs.InputChannel && {\n accessHash: String(peerEntity.migratedTo.accessHash),\n }),\n },\n };\n }\n\n return {};\n}\n\nfunction buildApiChatRestrictionReason(\n restrictionReasons?: GramJs.RestrictionReason[],\n): ApiRestrictionReason | undefined {\n if (!restrictionReasons) {\n return undefined;\n }\n\n const targetReason = restrictionReasons.find(({ platform }) => platform === 'all');\n return targetReason ? pick(targetReason, ['reason', 'text']) : undefined;\n}\n\nexport function buildApiChatFromPreview(\n preview: GramJs.TypeChat | GramJs.TypeUser,\n isSupport = false,\n withForbidden = false,\n): ApiChat | undefined {\n if (!(\n preview instanceof GramJs.Chat\n || preview instanceof GramJs.Channel\n || preview instanceof GramJs.User\n || (\n withForbidden\n && (\n preview instanceof GramJs.ChatForbidden\n || preview instanceof GramJs.ChannelForbidden\n )\n )\n )) {\n return undefined;\n }\n\n return {\n id: buildApiPeerId(preview.id, preview instanceof GramJs.User ? 'user' : 'chat'),\n type: getApiChatTypeFromPeerEntity(preview),\n title: preview instanceof GramJs.User ? getUserName(preview) : preview.title,\n ...buildApiChatFieldsFromPeerEntity(preview, isSupport),\n };\n}\n\nexport function getApiChatTypeFromPeerEntity(peerEntity: GramJs.TypeChat | GramJs.TypeUser) {\n if (peerEntity instanceof GramJs.User || peerEntity instanceof GramJs.UserEmpty) {\n return 'chatTypePrivate';\n } else if (\n peerEntity instanceof GramJs.Chat\n || peerEntity instanceof GramJs.ChatForbidden\n || peerEntity instanceof GramJs.ChatEmpty\n ) {\n return 'chatTypeBasicGroup';\n } else {\n return peerEntity.megagroup ? 'chatTypeSuperGroup' : 'chatTypeChannel';\n }\n}\n\nexport function getPeerKey(peer: GramJs.TypePeer) {\n if (isPeerUser(peer)) {\n return `user${peer.userId}`;\n } else if (isPeerChat(peer)) {\n return `chat${peer.chatId}`;\n } else {\n return `chat${peer.channelId}`;\n }\n}\n\nexport function getApiChatTitleFromMtpPeer(peer: GramJs.TypePeer, peerEntity: GramJs.User | GramJs.Chat) {\n if (isPeerUser(peer)) {\n return getUserName(peerEntity as GramJs.User);\n } else {\n return (peerEntity as GramJs.Chat).title;\n }\n}\n\nfunction getUserName(user: GramJs.User) {\n return user.firstName\n ? `${user.firstName}${user.lastName ? ` ${user.lastName}` : ''}`\n : (user.lastName || undefined);\n}\n\nexport function buildAvatarHash(photo: GramJs.TypeUserProfilePhoto | GramJs.TypeChatPhoto) {\n if ('photoId' in photo) {\n return String(photo.photoId);\n }\n\n return undefined;\n}\n\nexport function buildChatMember(\n member: GramJs.TypeChatParticipant | GramJs.TypeChannelParticipant,\n): ApiChatMember | undefined {\n const userId = (member instanceof GramJs.ChannelParticipantBanned || member instanceof GramJs.ChannelParticipantLeft)\n ? getApiChatIdFromMtpPeer(member.peer)\n : buildApiPeerId(member.userId, 'user');\n\n return {\n userId,\n inviterId: 'inviterId' in member ? buildApiPeerId(member.inviterId as BigInt.BigInteger, 'user') : undefined,\n joinedDate: 'date' in member ? member.date : undefined,\n kickedByUserId: 'kickedBy' in member ? buildApiPeerId(member.kickedBy, 'user') : undefined,\n promotedByUserId: 'promotedBy' in member ? buildApiPeerId(member.promotedBy, 'user') : undefined,\n bannedRights: 'bannedRights' in member ? omitVirtualClassFields(member.bannedRights) : undefined,\n adminRights: 'adminRights' in member ? omitVirtualClassFields(member.adminRights) : undefined,\n customTitle: 'rank' in member ? member.rank : undefined,\n ...((member instanceof GramJs.ChannelParticipantAdmin || member instanceof GramJs.ChatParticipantAdmin) && {\n isAdmin: true,\n }),\n ...((member instanceof GramJs.ChannelParticipantCreator || member instanceof GramJs.ChatParticipantCreator) && {\n isOwner: true,\n }),\n };\n}\n\nexport function buildChatMembers(\n participants: GramJs.TypeChatParticipants | GramJs.channels.ChannelParticipants,\n) {\n // Duplicate code because of TS union-type shenanigans\n if (participants instanceof GramJs.ChatParticipants) {\n return participants.participants.map(buildChatMember).filter(Boolean as any);\n }\n if (participants instanceof GramJs.channels.ChannelParticipants) {\n return participants.participants.map(buildChatMember).filter(Boolean as any);\n }\n\n return undefined;\n}\n\nexport function buildChatTypingStatus(\n update: GramJs.UpdateUserTyping | GramJs.UpdateChatUserTyping | GramJs.UpdateChannelUserTyping,\n serverTimeOffset: number,\n) {\n let action: string = '';\n if (update.action instanceof GramJs.SendMessageCancelAction) {\n return undefined;\n } else if (update.action instanceof GramJs.SendMessageTypingAction) {\n action = 'lng_user_typing';\n } else if (update.action instanceof GramJs.SendMessageRecordVideoAction) {\n action = 'lng_send_action_record_video';\n } else if (update.action instanceof GramJs.SendMessageUploadVideoAction) {\n action = 'lng_send_action_upload_video';\n } else if (update.action instanceof GramJs.SendMessageRecordAudioAction) {\n action = 'lng_send_action_record_audio';\n } else if (update.action instanceof GramJs.SendMessageUploadAudioAction) {\n action = 'lng_send_action_upload_audio';\n } else if (update.action instanceof GramJs.SendMessageUploadPhotoAction) {\n action = 'lng_send_action_upload_photo';\n } else if (update.action instanceof GramJs.SendMessageUploadDocumentAction) {\n action = 'lng_send_action_upload_file';\n } else if (update.action instanceof GramJs.SendMessageGeoLocationAction) {\n action = 'selecting a location to share';\n } else if (update.action instanceof GramJs.SendMessageChooseContactAction) {\n action = 'selecting a contact to share';\n } else if (update.action instanceof GramJs.SendMessageGamePlayAction) {\n action = 'lng_playing_game';\n } else if (update.action instanceof GramJs.SendMessageRecordRoundAction) {\n action = 'lng_send_action_record_round';\n } else if (update.action instanceof GramJs.SendMessageUploadRoundAction) {\n action = 'lng_send_action_upload_round';\n } else if (update.action instanceof GramJs.SendMessageChooseStickerAction) {\n action = 'lng_send_action_choose_sticker';\n } else if (update.action instanceof GramJs.SpeakingInGroupCallAction) {\n return undefined;\n }\n\n return {\n action,\n ...(!(update instanceof GramJs.UpdateUserTyping) && { userId: getApiChatIdFromMtpPeer(update.fromId) }),\n timestamp: Date.now() + serverTimeOffset * 1000,\n };\n}\n\nexport function buildApiChatFolder(filter: GramJs.DialogFilter): ApiChatFolder {\n return {\n ...pickTruthy(filter, [\n 'id', 'title', 'emoticon', 'contacts', 'nonContacts', 'groups', 'bots',\n 'excludeMuted', 'excludeRead', 'excludeArchived',\n ]),\n channels: filter.broadcasts,\n pinnedChatIds: filter.pinnedPeers.map(getApiChatIdFromMtpPeer).filter(Boolean as any),\n includedChatIds: filter.includePeers.map(getApiChatIdFromMtpPeer).filter(Boolean as any),\n excludedChatIds: filter.excludePeers.map(getApiChatIdFromMtpPeer).filter(Boolean as any),\n };\n}\n\nexport function buildApiChatFolderFromSuggested({\n filter, description,\n}: {\n filter: GramJs.DialogFilter;\n description: string;\n}): ApiChatFolder {\n return {\n ...buildApiChatFolder(filter),\n description,\n };\n}\n\nexport function buildApiChatBotCommands(botInfos: GramJs.BotInfo[]) {\n return botInfos.reduce((botCommands, botInfo) => {\n const botId = buildApiPeerId(botInfo.userId, 'user');\n\n botCommands = botCommands.concat(botInfo.commands.map((mtpCommand) => ({\n botId,\n ...omitVirtualClassFields(mtpCommand),\n })));\n\n return botCommands;\n }, [] as ApiBotCommand[]);\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n ApiBotCommand, ApiUser, ApiUserStatus, ApiUserType,\n} from '../../types';\nimport { buildApiPeerId } from './peers';\n\nexport function buildApiUserFromFull(mtpUserFull: GramJs.UserFull): ApiUser {\n const {\n about, commonChatsCount, pinnedMsgId, botInfo, blocked,\n } = mtpUserFull;\n\n const user = buildApiUser(mtpUserFull.user)!;\n\n return {\n ...user,\n fullInfo: {\n bio: about,\n commonChatsCount,\n pinnedMessageId: pinnedMsgId,\n isBlocked: Boolean(blocked),\n ...(botInfo && { botDescription: botInfo.description }),\n ...(botInfo && botInfo.commands.length && { botCommands: buildApiBotCommands(user.id, botInfo) }),\n },\n };\n}\n\nexport function buildApiUser(mtpUser: GramJs.TypeUser): ApiUser | undefined {\n if (!(mtpUser instanceof GramJs.User)) {\n return undefined;\n }\n\n const { id, firstName, lastName } = mtpUser;\n const avatarHash = mtpUser.photo instanceof GramJs.UserProfilePhoto\n ? String(mtpUser.photo.photoId)\n : undefined;\n const userType = buildApiUserType(mtpUser);\n\n return {\n id: buildApiPeerId(id, 'user'),\n isMin: Boolean(mtpUser.min),\n ...(mtpUser.self && { isSelf: true }),\n ...(mtpUser.verified && { isVerified: true }),\n ...((mtpUser.contact || mtpUser.mutualContact) && { isContact: true }),\n type: userType,\n ...(firstName && { firstName }),\n ...(userType === 'userTypeBot' && { canBeInvitedToGroup: !mtpUser.botNochats }),\n ...(lastName && { lastName }),\n username: mtpUser.username || '',\n phoneNumber: mtpUser.phone || '',\n status: buildApiUserStatus(mtpUser.status),\n ...(mtpUser.accessHash && { accessHash: String(mtpUser.accessHash) }),\n ...(avatarHash && { avatarHash }),\n ...(mtpUser.bot && mtpUser.botInlinePlaceholder && { botPlaceholder: mtpUser.botInlinePlaceholder }),\n };\n}\n\nfunction buildApiUserType(user: GramJs.User): ApiUserType {\n if (user.bot) {\n return 'userTypeBot';\n }\n if (user.deleted) {\n return 'userTypeDeleted';\n }\n\n return 'userTypeRegular';\n}\n\nexport function buildApiUserStatus(mtpStatus?: GramJs.TypeUserStatus): ApiUserStatus {\n if (!mtpStatus || mtpStatus instanceof GramJs.UserStatusEmpty) {\n return { type: 'userStatusEmpty' };\n } else if (mtpStatus instanceof GramJs.UserStatusOnline) {\n return { type: 'userStatusOnline', expires: mtpStatus.expires };\n } else if (mtpStatus instanceof GramJs.UserStatusOffline) {\n return { type: 'userStatusOffline', wasOnline: mtpStatus.wasOnline };\n } else if (mtpStatus instanceof GramJs.UserStatusRecently) {\n return { type: 'userStatusRecently' };\n } else if (mtpStatus instanceof GramJs.UserStatusLastWeek) {\n return { type: 'userStatusLastWeek' };\n } else {\n return { type: 'userStatusLastMonth' };\n }\n}\n\nfunction buildApiBotCommands(botId: string, botInfo: GramJs.BotInfo) {\n return botInfo.commands.map(({ command, description }) => ({\n botId,\n command,\n description,\n })) as ApiBotCommand[];\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\n\nimport { ApiCountry, ApiSession, ApiWallpaper } from '../../types';\nimport { ApiPrivacySettings, ApiPrivacyKey, PrivacyVisibility } from '../../../types';\n\nimport { buildApiDocument } from './messages';\nimport { buildApiPeerId, getApiChatIdFromMtpPeer } from './peers';\nimport { flatten, pick } from '../../../util/iteratees';\nimport { getServerTime } from '../../../util/serverTime';\n\nexport function buildApiWallpaper(wallpaper: GramJs.TypeWallPaper): ApiWallpaper | undefined {\n if (wallpaper instanceof GramJs.WallPaperNoFile) {\n // TODO: Plain color wallpapers\n return undefined;\n }\n\n const { slug } = wallpaper;\n\n const document = buildApiDocument(wallpaper.document);\n\n if (!document) {\n return undefined;\n }\n\n return {\n slug,\n document,\n };\n}\n\nexport function buildApiSession(session: GramJs.Authorization): ApiSession {\n return {\n isCurrent: Boolean(session.current),\n isOfficialApp: Boolean(session.officialApp),\n isPasswordPending: Boolean(session.passwordPending),\n hash: String(session.hash),\n ...pick(session, [\n 'deviceModel', 'platform', 'systemVersion', 'appName', 'appVersion', 'dateCreated', 'dateActive',\n 'ip', 'country', 'region',\n ]),\n };\n}\n\nexport function buildPrivacyKey(key: GramJs.TypePrivacyKey): ApiPrivacyKey | undefined {\n switch (key.className) {\n case 'PrivacyKeyPhoneNumber':\n return 'phoneNumber';\n case 'PrivacyKeyStatusTimestamp':\n return 'lastSeen';\n case 'PrivacyKeyProfilePhoto':\n return 'profilePhoto';\n case 'PrivacyKeyForwards':\n return 'forwards';\n case 'PrivacyKeyChatInvite':\n return 'chatInvite';\n }\n\n return undefined;\n}\n\nexport function buildPrivacyRules(rules: GramJs.TypePrivacyRule[]): ApiPrivacySettings {\n let visibility: PrivacyVisibility | undefined;\n let allowUserIds: string[] | undefined;\n let allowChatIds: string[] | undefined;\n let blockUserIds: string[] | undefined;\n let blockChatIds: string[] | undefined;\n\n rules.forEach((rule) => {\n if (rule instanceof GramJs.PrivacyValueAllowAll) {\n visibility = visibility || 'everybody';\n } else if (rule instanceof GramJs.PrivacyValueAllowContacts) {\n visibility = visibility || 'contacts';\n } else if (rule instanceof GramJs.PrivacyValueDisallowContacts) {\n visibility = visibility || 'nonContacts';\n } else if (rule instanceof GramJs.PrivacyValueDisallowAll) {\n visibility = visibility || 'nobody';\n } else if (rule instanceof GramJs.PrivacyValueAllowUsers) {\n allowUserIds = rule.users.map((chatId) => buildApiPeerId(chatId, 'user'));\n } else if (rule instanceof GramJs.PrivacyValueDisallowUsers) {\n blockUserIds = rule.users.map((chatId) => buildApiPeerId(chatId, 'user'));\n } else if (rule instanceof GramJs.PrivacyValueAllowChatParticipants) {\n allowChatIds = rule.chats.map((chatId) => buildApiPeerId(chatId, 'chat'));\n } else if (rule instanceof GramJs.PrivacyValueDisallowChatParticipants) {\n blockChatIds = rule.chats.map((chatId) => buildApiPeerId(chatId, 'chat'));\n }\n });\n\n if (!visibility) {\n // disallow by default.\n visibility = 'nobody';\n }\n\n return {\n visibility,\n allowUserIds: allowUserIds || [],\n allowChatIds: allowChatIds || [],\n blockUserIds: blockUserIds || [],\n blockChatIds: blockChatIds || [],\n };\n}\n\nexport function buildApiNotifyException(\n notifySettings: GramJs.TypePeerNotifySettings, peer: GramJs.TypePeer, serverTimeOffset: number,\n) {\n const {\n silent, muteUntil, showPreviews, sound,\n } = notifySettings;\n\n return {\n chatId: getApiChatIdFromMtpPeer(peer),\n isMuted: silent || (typeof muteUntil === 'number' && getServerTime(serverTimeOffset) < muteUntil),\n ...(sound === '' && { isSilent: true }),\n ...(showPreviews !== undefined && { shouldShowPreviews: Boolean(showPreviews) }),\n };\n}\n\nfunction buildApiCountry(country: GramJs.help.Country, code?: GramJs.help.CountryCode) {\n const {\n hidden, iso2, defaultName, name,\n } = country;\n const { countryCode, prefixes, patterns } = code || {};\n\n return {\n isHidden: hidden,\n iso2,\n defaultName,\n name,\n countryCode,\n prefixes,\n patterns,\n };\n}\n\nexport function buildApiCountryList(countries: GramJs.help.Country[]) {\n const listByCode = flatten(\n countries\n .filter((country) => !country.hidden)\n .map((country) => (\n country.countryCodes.map((code) => buildApiCountry(country, code))\n )),\n )\n .sort((a: ApiCountry, b: ApiCountry) => (\n a.name ? a.name.localeCompare(b.name!) : a.defaultName.localeCompare(b.defaultName)\n ));\n\n const generalList = countries\n .filter((country) => !country.hidden)\n .map((country) => buildApiCountry(country))\n .sort((a, b) => (\n a.name ? a.name.localeCompare(b.name!) : a.defaultName.localeCompare(b.defaultName)\n ));\n\n return {\n phoneCodes: listByCode,\n general: generalList,\n };\n}\n","import { Api as GramJs, connection } from '../../lib/gramjs';\nimport { ApiMessage, ApiUpdateConnectionStateType, OnApiUpdate } from '../types';\n\nimport { pick } from '../../util/iteratees';\nimport {\n buildApiMessage,\n buildApiMessageFromShort,\n buildApiMessageFromShortChat,\n buildMessageMediaContent,\n buildMessageTextContent,\n buildPoll,\n buildPollResults,\n buildApiMessageFromNotification,\n buildMessageDraft,\n} from './apiBuilders/messages';\nimport {\n buildChatMember,\n buildChatMembers,\n buildChatTypingStatus,\n buildAvatarHash,\n buildApiChatFromPreview,\n buildApiChatFolder,\n} from './apiBuilders/chats';\nimport { buildApiUser, buildApiUserStatus } from './apiBuilders/users';\nimport {\n buildMessageFromUpdate,\n isMessageWithMedia,\n buildChatPhotoForLocalDb,\n} from './gramjsBuilders';\nimport localDb from './localDb';\nimport { omitVirtualClassFields } from './apiBuilders/helpers';\nimport { DEBUG } from '../../config';\nimport { addMessageToLocalDb, addPhotoToLocalDb, resolveMessageApiChatId } from './helpers';\nimport { buildApiNotifyException, buildPrivacyKey, buildPrivacyRules } from './apiBuilders/misc';\nimport { buildApiPhoto } from './apiBuilders/common';\nimport { buildApiPeerId, getApiChatIdFromMtpPeer } from './apiBuilders/peers';\n\ntype Update = (\n (GramJs.TypeUpdate | GramJs.TypeUpdates) & { _entities?: (GramJs.TypeUser | GramJs.TypeChat)[] }\n) | typeof connection.UpdateConnectionState;\n\nconst DELETE_MISSING_CHANNEL_MESSAGE_DELAY = 1000;\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nconst sentMessageIds = new Set();\nlet serverTimeOffset = 0;\n\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?.length) {\n entities\n .filter((e) => e instanceof GramJs.User)\n .map(buildApiUser)\n .forEach((user) => {\n if (!user) {\n return;\n }\n\n onUpdate({\n '@type': 'updateUser',\n id: user.id,\n user,\n });\n });\n entities\n .filter((e) => e instanceof GramJs.Chat || e instanceof GramJs.Channel)\n .map((e) => buildApiChatFromPreview(e))\n .forEach((chat) => {\n if (!chat) {\n return;\n }\n\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n });\n }\n\n if (update instanceof GramJs.UpdateNewScheduledMessage) {\n onUpdate({\n '@type': sentMessageIds.has(message.id) ? 'updateScheduledMessage' : 'newScheduledMessage',\n id: message.id,\n chatId: message.chatId,\n message,\n });\n } else {\n onUpdate({\n '@type': sentMessageIds.has(message.id) ? 'updateMessage' : 'newMessage',\n id: message.id,\n chatId: message.chatId,\n message,\n shouldForceReply,\n });\n }\n\n // Some updates to a Chat/Channel don't have a dedicated update class.\n // We can get info on some updates from Service Messages.\n if (update.message instanceof GramJs.MessageService) {\n const { action } = update.message;\n\n if (action instanceof GramJs.MessageActionChatEditTitle) {\n onUpdate({\n '@type': 'updateChat',\n id: message.chatId,\n chat: {\n title: action.title,\n },\n });\n } else if (action instanceof GramJs.MessageActionChatEditPhoto) {\n const photo = buildChatPhotoForLocalDb(action.photo);\n const avatarHash = buildAvatarHash(photo);\n\n const localDbChatId = resolveMessageApiChatId(update.message)!;\n if (localDb.chats[localDbChatId]) {\n localDb.chats[localDbChatId].photo = photo;\n }\n addPhotoToLocalDb(action.photo);\n\n if (avatarHash) {\n onUpdate({\n '@type': 'updateChat',\n id: message.chatId,\n chat: {\n avatarHash,\n },\n ...(action.photo instanceof GramJs.Photo && { newProfilePhoto: buildApiPhoto(action.photo) }),\n });\n }\n } else if (action instanceof GramJs.MessageActionChatDeletePhoto) {\n const localDbChatId = resolveMessageApiChatId(update.message)!;\n if (localDb.chats[localDbChatId]) {\n localDb.chats[localDbChatId].photo = new GramJs.ChatPhotoEmpty();\n }\n\n onUpdate({\n '@type': 'updateChat',\n id: message.chatId,\n chat: { avatarHash: undefined },\n });\n } else if (action instanceof GramJs.MessageActionChatDeleteUser) {\n // eslint-disable-next-line no-underscore-dangle\n if (update._entities && update._entities.some((e): e is GramJs.User => (\n e instanceof GramJs.User && !!e.self && e.id === action.userId\n ))) {\n onUpdate({\n '@type': 'updateChat',\n id: message.chatId,\n chat: {\n isRestricted: true,\n },\n });\n\n onUpdate({\n '@type': 'updateChatLeave',\n id: message.chatId,\n });\n }\n } else if (action instanceof GramJs.MessageActionChatAddUser) {\n // eslint-disable-next-line no-underscore-dangle\n if (update._entities && update._entities.some((e): e is GramJs.User => (\n e instanceof GramJs.User && !!e.self && action.users.includes(e.id)\n ))) {\n onUpdate({\n '@type': 'updateChatJoin',\n id: message.chatId,\n });\n }\n }\n }\n } else if (\n update instanceof GramJs.UpdateEditMessage\n || update instanceof GramJs.UpdateEditChannelMessage\n ) {\n // TODO Remove if proven not reproducing\n if (update.message instanceof GramJs.MessageEmpty) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected update:', update.className, update);\n }\n\n return;\n }\n\n if (update.message instanceof GramJs.Message && isMessageWithMedia(update.message)) {\n addMessageToLocalDb(update.message);\n }\n\n const message = buildApiMessage(update.message)!;\n\n onUpdate({\n '@type': 'updateMessage',\n id: message.id,\n chatId: message.chatId,\n message,\n });\n } else if (update instanceof GramJs.UpdateDeleteMessages) {\n onUpdate({\n '@type': 'deleteMessages',\n ids: update.messages,\n });\n } else if (update instanceof GramJs.UpdateDeleteScheduledMessages) {\n onUpdate({\n '@type': 'deleteScheduledMessages',\n ids: update.messages,\n chatId: getApiChatIdFromMtpPeer(update.peer),\n });\n } else if (update instanceof GramJs.UpdateDeleteChannelMessages) {\n const chatId = buildApiPeerId(update.channelId, 'channel');\n const ids = update.messages;\n const existingIds = ids.filter((id) => localDb.messages[`${chatId}-${id}`]);\n const missingIds = ids.filter((id) => !localDb.messages[`${chatId}-${id}`]);\n const profilePhotoIds = ids.map((id) => {\n const message = localDb.messages[`${chatId}-${id}`];\n\n return message && message instanceof GramJs.MessageService && 'photo' in message.action\n ? String(message.action.photo.id)\n : undefined;\n }).filter(Boolean as any);\n\n if (existingIds.length) {\n onUpdate({\n '@type': 'deleteMessages',\n ids: existingIds,\n chatId,\n });\n }\n\n if (profilePhotoIds.length) {\n onUpdate({\n '@type': 'deleteProfilePhotos',\n ids: profilePhotoIds,\n chatId,\n });\n }\n\n // For some reason delete message update sometimes comes before new message update\n if (missingIds.length) {\n setTimeout(() => {\n onUpdate({\n '@type': 'deleteMessages',\n ids: missingIds,\n chatId,\n });\n }, DELETE_MISSING_CHANNEL_MESSAGE_DELAY);\n }\n } else if (update instanceof GramJs.UpdateServiceNotification) {\n 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 } else if ((\n originRequest instanceof GramJs.messages.SendMessage\n || originRequest instanceof GramJs.messages.SendMedia\n || originRequest instanceof GramJs.messages.SendMultiMedia\n || originRequest instanceof GramJs.messages.ForwardMessages\n ) && (\n update instanceof GramJs.UpdateMessageID\n || update instanceof GramJs.UpdateShortSentMessage\n )) {\n let randomId;\n if ('randomId' in update) {\n randomId = update.randomId;\n } else if ('randomId' in originRequest) {\n randomId = originRequest.randomId;\n }\n\n const localMessage = randomId && localDb.localMessages[String(randomId)];\n if (!localMessage) {\n throw new Error('Local message not found');\n }\n\n let newContent: ApiMessage['content'] | undefined;\n if (update instanceof GramJs.UpdateShortSentMessage) {\n if (localMessage.content.text && update.entities) {\n newContent = {\n text: buildMessageTextContent(localMessage.content.text.text, update.entities),\n };\n }\n if (update.media) {\n newContent = {\n ...newContent,\n ...buildMessageMediaContent(update.media),\n };\n }\n\n const mtpMessage = buildMessageFromUpdate(update.id, localMessage.chatId, update);\n if (isMessageWithMedia(mtpMessage)) {\n addMessageToLocalDb(mtpMessage);\n }\n }\n\n sentMessageIds.add(update.id);\n\n // Edge case for \"Send When Online\"\n const isAlreadySent = 'date' in update && update.date * 1000 < Date.now() + serverTimeOffset * 1000;\n\n onUpdate({\n '@type': localMessage.isScheduled && !isAlreadySent\n ? 'updateScheduledMessageSendSucceeded'\n : 'updateMessageSendSucceeded',\n chatId: localMessage.chatId,\n localId: localMessage.id,\n message: {\n ...localMessage,\n ...(newContent && {\n content: {\n ...localMessage.content,\n ...newContent,\n },\n }),\n id: update.id,\n sendingState: undefined,\n ...('date' in update && { date: update.date }),\n },\n });\n } else if (update instanceof GramJs.UpdateReadMessagesContents) {\n onUpdate({\n '@type': 'updateCommonBoxMessages',\n ids: update.messages,\n messageUpdate: {\n hasUnreadMention: false,\n isMediaUnread: false,\n },\n });\n } else if (update instanceof GramJs.UpdateChannelReadMessagesContents) {\n onUpdate({\n '@type': 'updateChannelMessages',\n channelId: buildApiPeerId(update.channelId, 'channel'),\n ids: update.messages,\n messageUpdate: {\n hasUnreadMention: false,\n isMediaUnread: false,\n },\n });\n } else if (update instanceof GramJs.UpdateMessagePoll) {\n const { pollId, poll, results } = update;\n if (poll) {\n const apiPoll = buildPoll(poll, results);\n\n onUpdate({\n '@type': 'updateMessagePoll',\n pollId: String(pollId),\n pollUpdate: apiPoll,\n });\n } else {\n const pollResults = buildPollResults(results);\n onUpdate({\n '@type': 'updateMessagePoll',\n pollId: String(pollId),\n pollUpdate: { results: pollResults },\n });\n }\n } else if (update instanceof GramJs.UpdateMessagePollVote) {\n onUpdate({\n '@type': 'updateMessagePollVote',\n pollId: String(update.pollId),\n userId: buildApiPeerId(update.userId, 'user'),\n options: update.options.map((option) => String.fromCharCode(...option)),\n });\n } else if (update instanceof GramJs.UpdateChannelMessageViews) {\n onUpdate({\n '@type': 'updateMessage',\n chatId: buildApiPeerId(update.channelId, 'channel'),\n id: update.id,\n message: { views: update.views },\n });\n\n // Chats\n } else if (update instanceof GramJs.UpdateReadHistoryInbox) {\n onUpdate({\n '@type': 'updateChatInbox',\n id: getApiChatIdFromMtpPeer(update.peer),\n chat: {\n lastReadInboxMessageId: update.maxId,\n unreadCount: update.stillUnreadCount,\n },\n });\n } else if (update instanceof GramJs.UpdateReadHistoryOutbox) {\n onUpdate({\n '@type': 'updateChat',\n id: getApiChatIdFromMtpPeer(update.peer),\n chat: {\n lastReadOutboxMessageId: update.maxId,\n },\n });\n } else if (update instanceof GramJs.UpdateReadChannelInbox) {\n onUpdate({\n '@type': 'updateChat',\n id: buildApiPeerId(update.channelId, 'channel'),\n chat: {\n lastReadInboxMessageId: update.maxId,\n unreadCount: update.stillUnreadCount,\n },\n });\n } else if (update instanceof GramJs.UpdateReadChannelOutbox) {\n onUpdate({\n '@type': 'updateChat',\n id: buildApiPeerId(update.channelId, 'channel'),\n chat: {\n lastReadOutboxMessageId: update.maxId,\n },\n });\n } else if (\n update instanceof GramJs.UpdateDialogPinned\n && update.peer instanceof GramJs.DialogPeer\n ) {\n onUpdate({\n '@type': 'updateChatPinned',\n id: getApiChatIdFromMtpPeer(update.peer.peer),\n isPinned: update.pinned || false,\n });\n } else if (update instanceof GramJs.UpdatePinnedDialogs) {\n const ids = update.order\n ? update.order\n .filter((dp): dp is GramJs.DialogPeer => dp instanceof GramJs.DialogPeer)\n .map((dp) => getApiChatIdFromMtpPeer(dp.peer))\n : [];\n\n onUpdate({\n '@type': 'updatePinnedChatIds',\n ids,\n folderId: update.folderId || undefined,\n });\n } else if (update instanceof GramJs.UpdateFolderPeers) {\n update.folderPeers.forEach((folderPeer) => {\n const { folderId, peer } = folderPeer;\n\n onUpdate({\n '@type': 'updateChatListType',\n id: getApiChatIdFromMtpPeer(peer),\n folderId,\n });\n });\n } else if (update instanceof GramJs.UpdateDialogFilter) {\n const { id, filter } = update;\n const folder = filter ? buildApiChatFolder(filter) : undefined;\n\n onUpdate({\n '@type': 'updateChatFolder',\n id,\n folder,\n });\n } else if (update instanceof GramJs.UpdateDialogFilterOrder) {\n onUpdate({\n '@type': 'updateChatFoldersOrder',\n orderedIds: update.order,\n });\n } else if (update instanceof GramJs.UpdateChatParticipants) {\n const replacedMembers = buildChatMembers(update.participants);\n\n onUpdate({\n '@type': 'updateChatMembers',\n id: buildApiPeerId(update.participants.chatId, 'chat'),\n replacedMembers,\n });\n } else if (update instanceof GramJs.UpdateChatParticipantAdd) {\n const addedMember = buildChatMember(\n pick(update, ['userId', 'inviterId', 'date']) as GramJs.ChatParticipant,\n );\n\n onUpdate({\n '@type': 'updateChatMembers',\n id: buildApiPeerId(update.chatId, 'chat'),\n addedMember,\n });\n } else if (update instanceof GramJs.UpdateChatParticipantDelete) {\n onUpdate({\n '@type': 'updateChatMembers',\n id: buildApiPeerId(update.chatId, 'chat'),\n deletedMemberId: buildApiPeerId(update.userId, 'user'),\n });\n } else if (\n update instanceof GramJs.UpdatePinnedMessages\n || update instanceof GramJs.UpdatePinnedChannelMessages\n ) {\n const chatId = update instanceof GramJs.UpdatePinnedMessages\n ? getApiChatIdFromMtpPeer(update.peer)\n : buildApiPeerId(update.channelId, 'channel');\n\n onUpdate({\n '@type': 'updatePinnedIds',\n chatId,\n messageIds: update.messages,\n isPinned: update.pinned,\n });\n } else if (\n update instanceof GramJs.UpdateNotifySettings\n && update.peer instanceof GramJs.NotifyPeer\n ) {\n onUpdate({\n '@type': 'updateNotifyExceptions',\n ...buildApiNotifyException(update.notifySettings, update.peer.peer, serverTimeOffset),\n });\n } else if (\n update instanceof GramJs.UpdateUserTyping\n || update instanceof GramJs.UpdateChatUserTyping\n ) {\n const id = update instanceof GramJs.UpdateUserTyping\n ? buildApiPeerId(update.userId, 'user')\n : buildApiPeerId(update.chatId, 'chat');\n\n onUpdate({\n '@type': 'updateChatTypingStatus',\n id,\n typingStatus: buildChatTypingStatus(update, serverTimeOffset),\n });\n } else if (update instanceof GramJs.UpdateChannelUserTyping) {\n const id = buildApiPeerId(update.channelId, 'channel');\n\n onUpdate({\n '@type': 'updateChatTypingStatus',\n id,\n typingStatus: buildChatTypingStatus(update, serverTimeOffset),\n });\n } else if (update instanceof GramJs.UpdateChannel) {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n const { _entities } = update;\n if (!_entities) {\n return;\n }\n\n const channel = _entities.find((e): e is GramJs.Channel | GramJs.ChannelForbidden => (\n e instanceof GramJs.Channel || e instanceof GramJs.ChannelForbidden\n ));\n\n if (channel instanceof GramJs.Channel) {\n const chat = buildApiChatFromPreview(channel);\n if (chat) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n\n onUpdate({\n '@type': chat.isNotJoined ? 'updateChatLeave' : 'updateChatJoin',\n id: buildApiPeerId(update.channelId, 'channel'),\n });\n }\n } else if (channel instanceof GramJs.ChannelForbidden) {\n const chatId = buildApiPeerId(update.channelId, 'channel');\n\n onUpdate({\n '@type': 'updateChat',\n id: chatId,\n chat: {\n isRestricted: true,\n },\n });\n\n onUpdate({\n '@type': 'updateChatLeave',\n id: chatId,\n });\n } else if (_entities.length === 0) {\n // The link to the discussion group may have been changed.\n // No corresponding update available at this moment https://core.telegram.org/type/Updates\n onUpdate({\n '@type': 'resetMessages',\n id: buildApiPeerId(update.channelId, 'channel'),\n });\n }\n } else if (\n update instanceof GramJs.UpdateDialogUnreadMark\n && update.peer instanceof GramJs.DialogPeer\n ) {\n onUpdate({\n '@type': 'updateChat',\n id: getApiChatIdFromMtpPeer(update.peer.peer),\n chat: {\n hasUnreadMark: update.unread,\n },\n });\n } else if (update instanceof GramJs.UpdateChatDefaultBannedRights) {\n onUpdate({\n '@type': 'updateChat',\n id: getApiChatIdFromMtpPeer(update.peer),\n chat: {\n defaultBannedRights: omitVirtualClassFields(update.defaultBannedRights),\n },\n });\n\n // Users\n } else if (update instanceof GramJs.UpdateUserStatus) {\n onUpdate({\n '@type': 'updateUserStatus',\n userId: buildApiPeerId(update.userId, 'user'),\n status: buildApiUserStatus(update.status),\n });\n } else if (update instanceof GramJs.UpdateUserName) {\n const apiUserId = buildApiPeerId(update.userId, 'user');\n const updatedUser = localDb.users[apiUserId];\n const user = updatedUser?.mutualContact && !updatedUser.self\n ? pick(update, ['username'])\n : pick(update, ['firstName', 'lastName', 'username']);\n\n onUpdate({\n '@type': 'updateUser',\n id: apiUserId,\n user,\n });\n } else if (update instanceof GramJs.UpdateUserPhoto) {\n const { userId, photo } = update;\n const apiUserId = buildApiPeerId(userId, 'user');\n const avatarHash = buildAvatarHash(photo);\n\n if (localDb.users[apiUserId]) {\n localDb.users[apiUserId].photo = photo;\n }\n\n onUpdate({\n '@type': 'updateUser',\n id: apiUserId,\n user: { avatarHash },\n });\n } else if (update instanceof GramJs.UpdateUserPhone) {\n const { userId, phone } = update;\n\n onUpdate({\n '@type': 'updateUser',\n id: buildApiPeerId(userId, 'user'),\n user: { phoneNumber: phone },\n });\n } else if (update instanceof GramJs.UpdatePeerSettings) {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n const { _entities } = update;\n if (!_entities) {\n return;\n }\n\n if (_entities?.length) {\n _entities\n .filter((e) => e instanceof GramJs.User && !e.contact)\n .forEach((user) => {\n onUpdate({\n '@type': 'deleteUser',\n id: buildApiPeerId(user.id, 'user'),\n });\n });\n\n _entities\n .filter((e) => e instanceof GramJs.User && e.contact)\n .map(buildApiUser)\n .forEach((user) => {\n if (!user) {\n return;\n }\n\n onUpdate({\n '@type': 'updateUser',\n id: user.id,\n user,\n });\n });\n }\n\n // Settings\n } else if (update instanceof GramJs.UpdateNotifySettings) {\n const {\n notifySettings: {\n showPreviews, silent, muteUntil,\n },\n peer: { className },\n } = update;\n\n const peerType = className === 'NotifyUsers'\n ? 'contact'\n : (className === 'NotifyChats'\n ? 'group'\n : (className === 'NotifyBroadcasts'\n ? 'broadcast'\n : undefined\n )\n );\n\n if (!peerType) {\n return;\n }\n\n onUpdate({\n '@type': 'updateNotifySettings',\n peerType,\n isSilent: Boolean(silent\n || (typeof muteUntil === 'number' && Date.now() + serverTimeOffset * 1000 < muteUntil * 1000)),\n shouldShowPreviews: Boolean(showPreviews),\n });\n } else if (update instanceof GramJs.UpdatePeerBlocked) {\n onUpdate({\n '@type': 'updatePeerBlocked',\n id: getApiChatIdFromMtpPeer(update.peerId),\n isBlocked: update.blocked,\n });\n } else if (update instanceof GramJs.UpdatePrivacy) {\n const key = buildPrivacyKey(update.key);\n if (key) {\n onUpdate({\n '@type': 'updatePrivacy',\n key,\n rules: buildPrivacyRules(update.rules),\n });\n }\n\n // Misc\n } else if (update instanceof GramJs.UpdateDraftMessage) {\n onUpdate({\n '@type': 'draftMessage',\n chatId: getApiChatIdFromMtpPeer(update.peer),\n ...buildMessageDraft(update.draft),\n });\n } else if (update instanceof GramJs.UpdateContactsReset) {\n onUpdate({ '@type': 'updateResetContactList' });\n } else if (update instanceof GramJs.UpdateFavedStickers) {\n onUpdate({ '@type': 'updateFavoriteStickers' });\n } else if (DEBUG) {\n const params = typeof update === 'object' && 'className' in update ? update.className : update;\n // eslint-disable-next-line no-console\n console.warn('[GramJs/updater] Unexpected update:', params);\n }\n}\n","import { errors } from '../../../lib/gramjs';\nimport {\n ApiUpdateAuthorizationState,\n ApiUpdateAuthorizationStateType,\n OnApiUpdate,\n ApiUser,\n} from '../../types';\n\nimport { DEBUG } from '../../../config';\n\nconst ApiErrors: { [k: string]: string } = {\n PHONE_NUMBER_INVALID: 'Invalid phone number.',\n PHONE_CODE_INVALID: 'Invalid code.',\n PASSWORD_HASH_INVALID: 'Incorrect password.',\n PHONE_PASSWORD_FLOOD: 'Limit exceeded. Please try again later.',\n PHONE_NUMBER_BANNED: 'This phone number is banned.',\n};\n\nconst authController: {\n resolve?: Function;\n reject?: Function;\n} = {};\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport function onRequestPhoneNumber() {\n onUpdate(buildAuthStateUpdate('authorizationStateWaitPhoneNumber'));\n\n return new Promise((resolve, reject) => {\n authController.resolve = resolve;\n authController.reject = reject;\n });\n}\n\nexport function onRequestCode(isCodeViaApp = false) {\n onUpdate({\n ...buildAuthStateUpdate('authorizationStateWaitCode'),\n isCodeViaApp,\n });\n\n return new Promise((resolve, reject) => {\n authController.resolve = resolve;\n authController.reject = reject;\n });\n}\n\nexport function onRequestPassword(hint?: string) {\n onUpdate({\n ...buildAuthStateUpdate('authorizationStateWaitPassword'),\n hint,\n });\n\n return new Promise((resolve) => {\n authController.resolve = resolve;\n });\n}\n\nexport function onRequestRegistration() {\n onUpdate(buildAuthStateUpdate('authorizationStateWaitRegistration'));\n\n return new Promise<[string, string?]>((resolve) => {\n authController.resolve = resolve;\n });\n}\n\nexport function onRequestQrCode(qrCode: { token: Buffer; expires: number }) {\n onUpdate({\n ...buildAuthStateUpdate('authorizationStateWaitQrCode'),\n qrCode: {\n token: btoa(String.fromCharCode(...qrCode.token)).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, ''),\n expires: qrCode.expires,\n },\n });\n\n return new Promise((resolve, reject) => {\n authController.reject = reject;\n });\n}\n\nexport function onAuthError(err: Error) {\n let message: string;\n\n if (err instanceof errors.FloodWaitError) {\n const hours = Math.ceil(Number(err.seconds) / 60 / 60);\n message = `Too many attempts. Try again in ${hours > 1 ? `${hours} hours` : 'an hour'}`;\n } else {\n message = ApiErrors[err.message];\n }\n\n if (!message) {\n message = 'Unexpected Error';\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n }\n\n onUpdate({\n '@type': 'updateAuthorizationError',\n message,\n });\n}\n\nexport function onAuthReady() {\n onUpdate(buildAuthStateUpdate('authorizationStateReady'));\n}\n\nexport function onCurrentUserUpdate(currentUser: ApiUser) {\n onUpdate({\n '@type': 'updateCurrentUser',\n currentUser,\n });\n}\n\nexport function buildAuthStateUpdate(authorizationState: ApiUpdateAuthorizationStateType): ApiUpdateAuthorizationState {\n return {\n '@type': 'updateAuthorizationState',\n authorizationState,\n };\n}\n\nexport function provideAuthPhoneNumber(phoneNumber: string) {\n if (!authController.resolve) {\n return;\n }\n\n authController.resolve(phoneNumber);\n}\n\nexport function provideAuthCode(code: string) {\n if (!authController.resolve) {\n return;\n }\n\n authController.resolve(code);\n}\n\nexport function provideAuthPassword(password: string) {\n if (!authController.resolve) {\n return;\n }\n\n authController.resolve(password);\n}\n\nexport function provideAuthRegistration(registration: { firstName: string; lastName: string }) {\n const { firstName, lastName } = registration;\n\n if (!authController.resolve) {\n return;\n }\n\n authController.resolve([firstName, lastName]);\n}\n\nexport function restartAuth() {\n if (!authController.reject) {\n return;\n }\n\n authController.reject(new Error('RESTART_AUTH'));\n}\n\nexport function restartAuthWithQr() {\n if (!authController.reject) {\n return;\n }\n\n authController.reject(new Error('RESTART_AUTH_WITH_QR'));\n}\n","// eslint-disable-next-line no-restricted-globals\nconst cacheApi = self.caches;\n\nexport enum Type {\n Text,\n Blob,\n Json,\n}\n\nexport async function fetch(\n cacheName: string, key: string, type: Type, isHtmlAllowed = false,\n) {\n if (!cacheApi) {\n return undefined;\n }\n\n try {\n // To avoid the error \"Request scheme 'webdocument' is unsupported\"\n const request = new Request(key.replace(/:/g, '_'));\n const cache = await cacheApi.open(cacheName);\n const response = await cache.match(request);\n if (!response) {\n return undefined;\n }\n\n const contentType = response.headers.get('Content-Type');\n\n switch (type) {\n case Type.Text:\n return await response.text();\n case Type.Blob: {\n // Ignore deprecated data-uri avatars\n if (key.startsWith('avatar') && contentType && contentType.startsWith('text')) {\n return undefined;\n }\n\n const blob = await response.blob();\n\n // Safari does not return correct Content-Type header for webp images.\n if (key.startsWith('sticker')) {\n return new Blob([blob], { type: 'image/webp' });\n }\n\n const shouldRecreate = !blob.type || (!isHtmlAllowed && blob.type.includes('html'));\n // iOS Safari fails to preserve `type` in cache\n let resolvedType = blob.type || contentType;\n\n if (!(shouldRecreate && resolvedType)) {\n return blob;\n }\n\n // Prevent HTML-in-video attacks (for files that were cached before fix)\n if (!isHtmlAllowed) {\n resolvedType = resolvedType.replace(/html/gi, '');\n }\n\n return new Blob([blob], { type: resolvedType });\n }\n case Type.Json:\n return await response.json();\n default:\n return undefined;\n }\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n\nexport async function save(cacheName: string, key: string, data: AnyLiteral | Blob | string) {\n if (!cacheApi) {\n return undefined;\n }\n\n try {\n const cacheData = typeof data === 'string' || data instanceof Blob ? data : JSON.stringify(data);\n // To avoid the error \"Request scheme 'webdocument' is unsupported\"\n const request = new Request(key.replace(/:/g, '_'));\n const response = new Response(cacheData);\n const cache = await cacheApi.open(cacheName);\n return await cache.put(request, response);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n\nexport async function clear(cacheName: string) {\n try {\n if (!cacheApi) {\n return undefined;\n }\n\n return await cacheApi.delete(cacheName);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n","import { inflate } from 'pako/dist/pako_inflate';\n\nimport { Api as GramJs, TelegramClient } from '../../../lib/gramjs';\nimport {\n ApiMediaFormat, ApiOnProgress, ApiParsedMedia, ApiPreparedMedia,\n} from '../../types';\n\nimport {\n DOWNLOAD_WORKERS,\n MEDIA_CACHE_DISABLED,\n MEDIA_CACHE_MAX_BYTES,\n MEDIA_CACHE_NAME,\n MEDIA_CACHE_NAME_AVATARS,\n} from '../../../config';\nimport localDb from '../localDb';\nimport { getEntityTypeById } from '../gramjsBuilders';\nimport * as cacheApi from '../../../util/cacheApi';\n\ntype EntityType = (\n 'msg' | 'sticker' | 'wallpaper' | 'gif' | 'channel' | 'chat' | 'user' | 'photo' | 'stickerSet' | 'webDocument'\n);\nconst MEDIA_ENTITY_TYPES = new Set(['msg', 'sticker', 'gif', 'wallpaper', 'photo', 'webDocument']);\n\nexport default async function downloadMedia(\n {\n url, mediaFormat, start, end, isHtmlAllowed,\n }: {\n url: string; mediaFormat: ApiMediaFormat; start?: number; end?: number; isHtmlAllowed?: boolean;\n },\n client: TelegramClient,\n isConnected: boolean,\n onProgress?: ApiOnProgress,\n) {\n const {\n data, mimeType, fullSize,\n } = await download(url, client, isConnected, onProgress, start, end, mediaFormat, isHtmlAllowed) || {};\n if (!data) {\n return undefined;\n }\n\n const parsed = await parseMedia(data, mediaFormat, mimeType);\n if (!parsed) {\n return undefined;\n }\n\n const canCache = mediaFormat !== ApiMediaFormat.Progressive && (\n mediaFormat !== ApiMediaFormat.BlobUrl || (parsed as Blob).size <= MEDIA_CACHE_MAX_BYTES\n );\n\n if (!MEDIA_CACHE_DISABLED && cacheApi && canCache) {\n const cacheName = url.startsWith('avatar') ? MEDIA_CACHE_NAME_AVATARS : MEDIA_CACHE_NAME;\n void cacheApi.save(cacheName, url, parsed);\n }\n\n const prepared = mediaFormat === ApiMediaFormat.Progressive ? '' : prepareMedia(parsed);\n const arrayBuffer = mediaFormat === ApiMediaFormat.Progressive ? parsed as ArrayBuffer : undefined;\n\n return {\n prepared,\n arrayBuffer,\n mimeType,\n fullSize,\n };\n}\n\nasync function download(\n url: string,\n client: TelegramClient,\n isConnected: boolean,\n onProgress?: ApiOnProgress,\n start?: number,\n end?: number,\n mediaFormat?: ApiMediaFormat,\n isHtmlAllowed?: boolean,\n) {\n const mediaMatch = url.startsWith('webDocument')\n ? url.match(/(webDocument):(.+)/)\n : url.match(/(avatar|profile|photo|msg|stickerSet|sticker|wallpaper|gif|file)([-\\d\\w./]+)(\\?size=\\w+)?/);\n if (!mediaMatch) {\n return undefined;\n }\n\n if (mediaMatch[1] === 'file') {\n const response = await fetch(mediaMatch[2]);\n const data = await response.arrayBuffer();\n return { data };\n }\n\n if (!isConnected) {\n return Promise.reject(new Error('ERROR: Client is not connected'));\n }\n\n let entityType: EntityType;\n const entityId: string | number = mediaMatch[2];\n const sizeType = mediaMatch[3] ? mediaMatch[3].replace('?size=', '') : undefined;\n let entity: (\n GramJs.User | GramJs.Chat | GramJs.Channel | GramJs.Photo |\n GramJs.Message | GramJs.MessageService |\n GramJs.Document | GramJs.StickerSet | GramJs.TypeWebDocument | undefined\n );\n\n if (mediaMatch[1] === 'avatar' || mediaMatch[1] === 'profile') {\n entityType = getEntityTypeById(entityId);\n } else {\n entityType = mediaMatch[1] as 'msg' | 'sticker' | 'wallpaper' | 'gif' | 'stickerSet' | 'photo' | 'webDocument';\n }\n\n switch (entityType) {\n case 'channel':\n case 'chat':\n entity = localDb.chats[entityId];\n break;\n case 'user':\n entity = localDb.users[entityId];\n break;\n case 'msg':\n entity = localDb.messages[entityId];\n break;\n case 'sticker':\n case 'gif':\n case 'wallpaper':\n entity = localDb.documents[entityId];\n break;\n case 'photo':\n entity = localDb.photos[entityId];\n break;\n case 'stickerSet':\n entity = localDb.stickerSets[entityId];\n break;\n case 'webDocument':\n entity = localDb.webDocuments[entityId];\n break;\n }\n\n if (!entity) {\n return undefined;\n }\n\n if (MEDIA_ENTITY_TYPES.has(entityType)) {\n if (mediaFormat === ApiMediaFormat.Stream) {\n onProgress!.acceptsBuffer = true;\n }\n\n const data = await client.downloadMedia(entity, {\n sizeType, start, end, progressCallback: onProgress, workers: DOWNLOAD_WORKERS,\n });\n let mimeType;\n let fullSize;\n\n if (entity instanceof GramJs.Message) {\n mimeType = getMessageMediaMimeType(entity, sizeType);\n if (entity.media instanceof GramJs.MessageMediaDocument && entity.media.document instanceof GramJs.Document) {\n fullSize = entity.media.document.size;\n }\n if (entity.media instanceof GramJs.MessageMediaWebPage\n && entity.media.webpage instanceof GramJs.WebPage\n && entity.media.webpage.document instanceof GramJs.Document) {\n fullSize = entity.media.webpage.document.size;\n }\n } else if (entity instanceof GramJs.Photo) {\n mimeType = 'image/jpeg';\n } else if (entityType === 'sticker' && sizeType) {\n mimeType = 'image/webp';\n } else if (entityType === 'webDocument') {\n mimeType = (entity as GramJs.TypeWebDocument).mimeType;\n } else {\n mimeType = (entity as GramJs.Document).mimeType;\n fullSize = (entity as GramJs.Document).size;\n }\n\n // Prevent HTML-in-video attacks\n if (!isHtmlAllowed && mimeType) {\n mimeType = mimeType.replace(/html/gi, '');\n }\n\n return { mimeType, data, fullSize };\n } else if (entityType === 'stickerSet') {\n const data = await client.downloadStickerSetThumb(entity);\n const mimeType = mediaFormat === ApiMediaFormat.Lottie ? 'application/json' : getMimeType(data);\n\n return { mimeType, data };\n } else {\n const data = await client.downloadProfilePhoto(entity, mediaMatch[1] === 'profile');\n const mimeType = getMimeType(data);\n\n return { mimeType, data };\n }\n}\n\nfunction getMessageMediaMimeType(message: GramJs.Message, sizeType?: string) {\n if (!message || !message.media) {\n return undefined;\n }\n\n if (message.media instanceof GramJs.MessageMediaPhoto) {\n return 'image/jpeg';\n }\n\n if (message.media instanceof GramJs.MessageMediaDocument && message.media.document instanceof GramJs.Document) {\n if (sizeType) {\n return message.media.document!.attributes.some((a) => a instanceof GramJs.DocumentAttributeSticker)\n ? 'image/webp'\n : 'image/jpeg';\n }\n\n return message.media.document!.mimeType;\n }\n\n if (message.media instanceof GramJs.MessageMediaWebPage\n && message.media.webpage instanceof GramJs.WebPage\n && message.media.webpage.document instanceof GramJs.Document) {\n return message.media.webpage.document.mimeType;\n }\n\n return undefined;\n}\n\n// eslint-disable-next-line no-async-without-await/no-async-without-await\nasync function parseMedia(\n data: Buffer, mediaFormat: ApiMediaFormat, mimeType?: string,\n): Promise {\n switch (mediaFormat) {\n case ApiMediaFormat.BlobUrl:\n return new Blob([data], { type: mimeType });\n case ApiMediaFormat.Lottie: {\n const json = inflate(data, { to: 'string' });\n return JSON.parse(json);\n }\n case ApiMediaFormat.Progressive: {\n return data.buffer;\n }\n }\n\n return undefined;\n}\n\nfunction prepareMedia(mediaData: ApiParsedMedia): ApiPreparedMedia {\n if (mediaData instanceof Blob) {\n return URL.createObjectURL(mediaData);\n }\n\n return mediaData;\n}\n\nfunction getMimeType(data: Uint8Array, fallbackMimeType = 'image/jpeg') {\n if (data.length < 4) {\n return fallbackMimeType;\n }\n\n let type = fallbackMimeType;\n const signature = data.subarray(0, 4).reduce((result, byte) => result + byte.toString(16), '');\n\n // https://en.wikipedia.org/wiki/List_of_file_signatures\n switch (signature) {\n case '89504e47':\n type = 'image/png';\n break;\n case '47494638':\n type = 'image/gif';\n break;\n case 'ffd8ffe0':\n case 'ffd8ffe1':\n case 'ffd8ffe2':\n case 'ffd8ffe3':\n case 'ffd8ffe8':\n type = 'image/jpeg';\n break;\n case '52494646':\n // In our case only webp is expected\n type = 'image/webp';\n break;\n }\n\n return type;\n}\n","import {\n TelegramClient, sessions, Api as GramJs, connection,\n} from '../../../lib/gramjs';\nimport { Logger as GramJsLogger } from '../../../lib/gramjs/extensions/index';\nimport { TwoFaParams } from '../../../lib/gramjs/client/2fa';\n\nimport {\n ApiInitialArgs,\n ApiMediaFormat,\n ApiOnProgress,\n ApiSessionData,\n OnApiUpdate,\n} from '../../types';\n\nimport {\n DEBUG, DEBUG_GRAMJS, UPLOAD_WORKERS, IS_TEST, APP_VERSION,\n} from '../../../config';\nimport {\n onRequestPhoneNumber, onRequestCode, onRequestPassword, onRequestRegistration,\n onAuthError, onAuthReady, onCurrentUserUpdate, onRequestQrCode,\n} from './auth';\nimport { updater } from '../updater';\nimport { setMessageBuilderCurrentUserId } from '../apiBuilders/messages';\nimport downloadMediaWithClient from './media';\nimport { buildApiUserFromFull } from '../apiBuilders/users';\nimport localDb from '../localDb';\nimport { buildApiPeerId } from '../apiBuilders/peers';\n\nconst DEFAULT_USER_AGENT = 'Unknown UserAgent';\nconst DEFAULT_PLATFORM = 'Unknown platform';\nconst APP_CODE_NAME = 'Z';\n\nGramJsLogger.setLevel(DEBUG_GRAMJS ? 'debug' : 'warn');\n\nconst gramJsUpdateEventBuilder = { build: (update: object) => update };\n\nlet onUpdate: OnApiUpdate;\nlet client: TelegramClient;\nlet isConnected = false;\n\nexport async function init(_onUpdate: OnApiUpdate, initialArgs: ApiInitialArgs) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START INIT API');\n }\n\n onUpdate = _onUpdate;\n\n const {\n userAgent, platform, sessionData, isTest, isMovSupported,\n } = initialArgs;\n const session = new sessions.CallbackSession(sessionData, onSessionUpdate);\n\n // eslint-disable-next-line no-restricted-globals\n (self as any).isMovSupported = isMovSupported;\n\n client = new TelegramClient(\n session,\n process.env.TELEGRAM_T_API_ID,\n process.env.TELEGRAM_T_API_HASH,\n {\n deviceModel: navigator.userAgent || userAgent || DEFAULT_USER_AGENT,\n systemVersion: platform || DEFAULT_PLATFORM,\n appVersion: `${APP_VERSION} ${APP_CODE_NAME}`,\n useWSS: true,\n additionalDcsDisabled: IS_TEST,\n testServers: isTest,\n } as any,\n );\n\n client.addEventHandler(handleGramJsUpdate, gramJsUpdateEventBuilder);\n client.addEventHandler(updater, gramJsUpdateEventBuilder);\n\n try {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[GramJs/client] CONNECTING');\n\n // eslint-disable-next-line no-restricted-globals\n (self as any).invoke = invokeRequest;\n // eslint-disable-next-line no-restricted-globals\n (self as any).GramJs = GramJs;\n }\n\n try {\n await client.start({\n phoneNumber: onRequestPhoneNumber,\n phoneCode: onRequestCode,\n password: onRequestPassword,\n firstAndLastNames: onRequestRegistration,\n qrCode: onRequestQrCode,\n onError: onAuthError,\n initialMethod: platform === 'iOS' || platform === 'Android' ? 'phoneNumber' : 'qrCode',\n });\n } catch (err) {\n // TODO Investigate which request causes this exception\n if (err.message !== 'Disconnect') {\n onUpdate({\n '@type': 'updateConnectionState',\n connectionState: 'connectionStateBroken',\n });\n\n return;\n }\n }\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH INIT API');\n // eslint-disable-next-line no-console\n console.log('[GramJs/client] CONNECTED');\n }\n\n onAuthReady();\n onSessionUpdate(session.getSessionData());\n onUpdate({ '@type': 'updateApiReady' });\n\n void fetchCurrentUser();\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[GramJs/client] CONNECTING ERROR', err);\n }\n\n throw err;\n }\n}\n\nexport async function destroy() {\n await invokeRequest(new GramJs.auth.LogOut());\n await client.destroy();\n}\n\nexport async function disconnect() {\n await client.disconnect();\n}\n\nexport function getClient() {\n return client;\n}\n\nfunction onSessionUpdate(sessionData: ApiSessionData) {\n onUpdate({\n '@type': 'updateSession',\n sessionData,\n });\n}\n\nfunction handleGramJsUpdate(update: any) {\n if (update instanceof connection.UpdateConnectionState) {\n isConnected = update.state === connection.UpdateConnectionState.connected;\n } else if (update instanceof GramJs.UpdatesTooLong) {\n void handleTerminatedSession();\n } else if (update instanceof connection.UpdateServerTimeOffset) {\n onUpdate({\n '@type': 'updateServerTimeOffset',\n serverTimeOffset: update.timeOffset,\n });\n }\n}\n\nexport async function invokeRequest(\n request: T,\n shouldHandleUpdates = false,\n shouldThrow = false,\n): Promise {\n if (!isConnected) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(`[GramJs/client] INVOKE ERROR ${request.className}: Client is not connected`);\n }\n\n return undefined;\n }\n\n try {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log(`[GramJs/client] INVOKE ${request.className}`);\n }\n\n const result = await client.invoke(request);\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log(`[GramJs/client] INVOKE RESPONSE ${request.className}`, result);\n }\n\n if (shouldHandleUpdates) {\n type ResultWithUpdates =\n typeof result\n & { updates?: GramJs.Updates | GramJs.UpdatesCombined };\n\n let updatesContainer;\n if (result instanceof GramJs.Updates || result instanceof GramJs.UpdatesCombined) {\n updatesContainer = result;\n } else if ('updates' in (result as ResultWithUpdates) && (\n (result as ResultWithUpdates).updates instanceof GramJs.Updates\n || (result as ResultWithUpdates).updates instanceof GramJs.UpdatesCombined\n )) {\n updatesContainer = (result as ResultWithUpdates).updates;\n }\n\n if (updatesContainer) {\n injectUpdateEntities(updatesContainer);\n\n updatesContainer.updates.forEach((update) => {\n updater(update, request);\n });\n } else if (result instanceof GramJs.UpdatesTooLong) {\n // TODO Implement\n } else {\n updater(result as GramJs.TypeUpdates, request);\n }\n }\n\n return result;\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log(`[GramJs/client] INVOKE ERROR ${request.className}`);\n // eslint-disable-next-line no-console\n console.error(err);\n }\n\n if (shouldThrow) {\n throw err;\n }\n\n dispatchErrorUpdate(err, request);\n\n return undefined;\n }\n}\n\nexport function downloadMedia(\n args: { url: string; mediaFormat: ApiMediaFormat; start?: number; end?: number; isHtmlAllowed?: boolean },\n onProgress?: ApiOnProgress,\n) {\n return downloadMediaWithClient(args, client, isConnected, onProgress);\n}\n\nexport function uploadFile(file: File, onProgress?: ApiOnProgress) {\n return client.uploadFile({ file, onProgress, workers: UPLOAD_WORKERS });\n}\n\nexport function updateTwoFaSettings(params: TwoFaParams) {\n return client.updateTwoFaSettings(params);\n}\n\nexport async function fetchCurrentUser() {\n const userFull = await invokeRequest(new GramJs.users.GetFullUser({\n id: new GramJs.InputUserSelf(),\n }));\n\n if (!userFull || !(userFull.user instanceof GramJs.User)) {\n return;\n }\n\n localDb.users[buildApiPeerId(userFull.user.id, 'user')] = userFull.user;\n const currentUser = buildApiUserFromFull(userFull);\n\n setMessageBuilderCurrentUserId(currentUser.id);\n onCurrentUserUpdate(currentUser);\n}\n\nexport function dispatchErrorUpdate(err: Error, request: T) {\n const isSlowMode = err.message.startsWith('A wait of') && (\n request instanceof GramJs.messages.SendMessage\n || request instanceof GramJs.messages.SendMedia\n || request instanceof GramJs.messages.SendMultiMedia\n );\n\n const { message } = err;\n\n onUpdate({\n '@type': 'error',\n error: {\n message,\n isSlowMode,\n hasErrorKey: true,\n },\n });\n}\n\nfunction injectUpdateEntities(result: GramJs.Updates | GramJs.UpdatesCombined) {\n const entities = [...result.users, ...result.chats];\n\n result.updates.forEach((update) => {\n if (entities) {\n // eslint-disable-next-line no-underscore-dangle\n (update as any)._entities = entities;\n }\n });\n}\n\nasync function handleTerminatedSession() {\n try {\n await invokeRequest(new GramJs.users.GetFullUser({\n id: new GramJs.InputUserSelf(),\n }), undefined, true);\n } catch (err) {\n if (err.message === 'AUTH_KEY_UNREGISTERED') {\n onUpdate({\n '@type': 'updateConnectionState',\n connectionState: 'connectionStateBroken',\n });\n }\n }\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport {\n OnApiUpdate,\n ApiChat,\n ApiMessage,\n ApiUser,\n ApiMessageEntity,\n ApiFormattedText,\n ApiChatFullInfo,\n ApiChatFolder,\n ApiChatBannedRights,\n ApiChatAdminRights,\n} from '../../types';\n\nimport {\n DEBUG, ARCHIVED_FOLDER_ID, MEMBERS_LOAD_SLICE, SERVICE_NOTIFICATIONS_USER_ID,\n} from '../../../config';\nimport { invokeRequest, uploadFile } from './client';\nimport {\n buildApiChatFromDialog,\n getPeerKey,\n buildChatMembers,\n buildApiChatFromPreview,\n buildApiChatFolder,\n buildApiChatFolderFromSuggested,\n buildApiChatBotCommands,\n} from '../apiBuilders/chats';\nimport { buildApiMessage, buildMessageDraft } from '../apiBuilders/messages';\nimport { buildApiUser } from '../apiBuilders/users';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport localDb from '../localDb';\nimport {\n buildInputEntity,\n buildInputPeer,\n buildMtpMessageEntity,\n buildFilterFromApiFolder,\n isMessageWithMedia,\n buildChatBannedRights,\n buildChatAdminRights,\n} from '../gramjsBuilders';\nimport { addChatToLocalDb, addMessageToLocalDb } from '../helpers';\nimport { buildApiPeerId, getApiChatIdFromMtpPeer } from '../apiBuilders/peers';\n\nconst MAX_INT_32 = 2 ** 31 - 1;\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function fetchChats({\n limit,\n offsetDate,\n archived,\n withPinned,\n serverTimeOffset,\n lastLocalServiceMessage,\n}: {\n limit: number;\n offsetDate?: number;\n archived?: boolean;\n withPinned?: boolean;\n serverTimeOffset: number;\n lastLocalServiceMessage?: ApiMessage;\n}) {\n const result = await invokeRequest(new GramJs.messages.GetDialogs({\n offsetPeer: new GramJs.InputPeerEmpty(),\n limit,\n offsetDate,\n folderId: archived ? ARCHIVED_FOLDER_ID : undefined,\n ...(withPinned && { excludePinned: true }),\n }));\n const resultPinned = withPinned\n ? await invokeRequest(new GramJs.messages.GetPinnedDialogs({\n folderId: archived ? ARCHIVED_FOLDER_ID : undefined,\n }))\n : undefined;\n\n if (!result || result instanceof GramJs.messages.DialogsNotModified) {\n return undefined;\n }\n\n if (resultPinned) {\n updateLocalDb(resultPinned);\n }\n updateLocalDb(result);\n\n const lastMessagesByChatId = buildCollectionByKey(\n (resultPinned ? resultPinned.messages : []).concat(result.messages)\n .map(buildApiMessage)\n .filter(Boolean as any),\n 'chatId',\n );\n const peersByKey: Record = {\n ...(resultPinned && preparePeers(resultPinned)),\n ...preparePeers(result),\n };\n const chats: ApiChat[] = [];\n const draftsById: Record = {};\n const replyingToById: Record = {};\n\n const dialogs = (resultPinned ? resultPinned.dialogs : []).concat(result.dialogs);\n\n const orderedPinnedIds: string[] = [];\n\n dialogs.forEach((dialog) => {\n if (\n !(dialog instanceof GramJs.Dialog)\n // This request can return dialogs not belonging to specified folder\n || (!archived && dialog.folderId === ARCHIVED_FOLDER_ID)\n || (archived && dialog.folderId !== ARCHIVED_FOLDER_ID)\n ) {\n return;\n }\n\n const peerEntity = peersByKey[getPeerKey(dialog.peer)];\n const chat = buildApiChatFromDialog(dialog, peerEntity, serverTimeOffset);\n\n if (\n chat.id === SERVICE_NOTIFICATIONS_USER_ID\n && lastLocalServiceMessage\n && (!lastMessagesByChatId[chat.id] || lastLocalServiceMessage.date > lastMessagesByChatId[chat.id].date)\n ) {\n chat.lastMessage = lastLocalServiceMessage;\n } else {\n chat.lastMessage = lastMessagesByChatId[chat.id];\n }\n\n chat.isListed = true;\n chats.push(chat);\n\n if (withPinned && dialog.pinned) {\n orderedPinnedIds.push(chat.id);\n }\n\n if (dialog.draft) {\n const { formattedText, replyingToId } = buildMessageDraft(dialog.draft) || {};\n if (formattedText) {\n draftsById[chat.id] = formattedText;\n }\n if (replyingToId) {\n replyingToById[chat.id] = replyingToId;\n }\n }\n });\n\n const users = (resultPinned ? resultPinned.users : []).concat(result.users)\n .map(buildApiUser)\n .filter(Boolean as any);\n const chatIds = chats.map((chat) => chat.id);\n\n let totalChatCount: number;\n\n if (result instanceof GramJs.messages.DialogsSlice) {\n totalChatCount = result.count;\n } else {\n totalChatCount = chatIds.length;\n }\n\n return {\n chatIds,\n chats,\n users,\n draftsById,\n replyingToById,\n orderedPinnedIds: withPinned ? orderedPinnedIds : undefined,\n totalChatCount,\n };\n}\n\nexport function fetchFullChat(chat: ApiChat) {\n const { id, accessHash, adminRights } = chat;\n\n const input = buildInputEntity(id, accessHash);\n\n return input instanceof GramJs.InputChannel\n ? getFullChannelInfo(id, accessHash!, adminRights)\n : getFullChatInfo(id);\n}\n\nexport async function searchChats({ query }: { query: string }) {\n const result = await invokeRequest(new GramJs.contacts.Search({ q: query }));\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const localPeerIds = result.myResults.map(getApiChatIdFromMtpPeer);\n const allChats = result.chats.concat(result.users)\n .map((user) => buildApiChatFromPreview(user))\n .filter(Boolean as any);\n const allUsers = result.users.map(buildApiUser).filter((user) => !!user && !user.isSelf) as ApiUser[];\n\n return {\n localChats: allChats.filter((r) => localPeerIds.includes(r.id)),\n localUsers: allUsers.filter((u) => localPeerIds.includes(u.id)),\n globalChats: allChats.filter((r) => !localPeerIds.includes(r.id)),\n globalUsers: allUsers.filter((u) => !localPeerIds.includes(u.id)),\n };\n}\n\nexport async function fetchChat({\n type, user,\n}: {\n type: 'user' | 'self' | 'support'; user?: ApiUser;\n}) {\n let mtpUser: GramJs.User | undefined;\n\n if (type === 'self' || type === 'user') {\n const result = await invokeRequest(new GramJs.users.GetUsers({\n id: [\n type === 'user' && user\n ? buildInputEntity(user.id, user.accessHash) as GramJs.InputUser\n : new GramJs.InputUserSelf(),\n ],\n }));\n if (!result || !result.length) {\n return undefined;\n }\n\n [mtpUser] = result;\n } else if (type === 'support') {\n const result = await invokeRequest(new GramJs.help.GetSupport());\n if (!result || !result.user) {\n return undefined;\n }\n\n mtpUser = result.user;\n }\n\n const chat = buildApiChatFromPreview(mtpUser!, type === 'support');\n if (!chat) {\n return undefined;\n }\n\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n\n return { chatId: chat.id };\n}\n\nexport async function requestChatUpdate({\n chat,\n serverTimeOffset,\n lastLocalMessage,\n noLastMessage,\n}: {\n chat: ApiChat; serverTimeOffset: number; lastLocalMessage?: ApiMessage; noLastMessage?: boolean;\n}) {\n const { id, accessHash } = chat;\n\n const result = await invokeRequest(new GramJs.messages.GetPeerDialogs({\n peers: [new GramJs.InputDialogPeer({\n peer: buildInputPeer(id, accessHash),\n })],\n }));\n\n if (!result) {\n return;\n }\n\n const dialog = result.dialogs[0];\n if (!dialog || !(dialog instanceof GramJs.Dialog)) {\n return;\n }\n\n const peersByKey = preparePeers(result);\n const peerEntity = peersByKey[getPeerKey(dialog.peer)];\n if (!peerEntity) {\n return;\n }\n\n updateLocalDb(result);\n\n const lastRemoteMessage = buildApiMessage(result.messages[0]);\n const lastMessage = lastLocalMessage && (!lastRemoteMessage || (lastLocalMessage.date > lastRemoteMessage.date))\n ? lastLocalMessage\n : lastRemoteMessage;\n\n onUpdate({\n '@type': 'updateChat',\n id,\n chat: {\n ...buildApiChatFromDialog(dialog, peerEntity, serverTimeOffset),\n ...(!noLastMessage && { lastMessage }),\n },\n });\n}\n\nexport function saveDraft({\n chat,\n text,\n entities,\n replyToMsgId,\n}: {\n chat: ApiChat;\n text: string;\n entities?: ApiMessageEntity[];\n replyToMsgId?: number;\n}) {\n return invokeRequest(new GramJs.messages.SaveDraft({\n peer: buildInputPeer(chat.id, chat.accessHash),\n message: text,\n ...(entities && {\n entities: entities.map(buildMtpMessageEntity),\n }),\n replyToMsgId,\n }));\n}\n\nexport function clearDraft(chat: ApiChat) {\n return invokeRequest(new GramJs.messages.SaveDraft({\n peer: buildInputPeer(chat.id, chat.accessHash),\n message: '',\n }));\n}\n\nasync function getFullChatInfo(chatId: string): Promise<{\n fullInfo: ApiChatFullInfo;\n users?: ApiUser[];\n} | 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 } = result.fullChat;\n\n const members = buildChatMembers(participants);\n const adminMembers = members ? members.filter(({ isAdmin, isOwner }) => isAdmin || isOwner) : undefined;\n const botCommands = botInfo ? buildApiChatBotCommands(botInfo) : undefined;\n\n return {\n fullInfo: {\n about,\n members,\n adminMembers,\n canViewMembers: true,\n botCommands,\n ...(exportedInvite && {\n inviteLink: exportedInvite.link,\n }),\n },\n users: result.users.map(buildApiUser).filter(Boolean as any),\n };\n}\n\nasync function getFullChannelInfo(\n id: string,\n accessHash: string,\n adminRights?: ApiChatAdminRights,\n) {\n const result = await invokeRequest(new GramJs.channels.GetFullChannel({\n channel: buildInputEntity(id, accessHash) as GramJs.InputChannel,\n }));\n\n if (!result || !(result.fullChat instanceof GramJs.ChannelFull)) {\n return undefined;\n }\n\n const {\n about,\n onlineCount,\n exportedInvite,\n slowmodeSeconds,\n slowmodeNextSendDate,\n migratedFromChatId,\n migratedFromMaxId,\n canViewParticipants,\n linkedChatId,\n hiddenPrehistory,\n call,\n botInfo,\n } = result.fullChat;\n\n const inviteLink = exportedInvite instanceof GramJs.ChatInviteExported\n ? exportedInvite.link\n : undefined;\n\n const { members, users } = (canViewParticipants && await fetchMembers(id, accessHash)) || {};\n const { members: kickedMembers, users: bannedUsers } = (\n canViewParticipants && adminRights && await fetchMembers(id, accessHash, 'kicked')\n ) || {};\n const { members: adminMembers, users: adminUsers } = (\n canViewParticipants && adminRights && await fetchMembers(id, accessHash, 'admin')\n ) || {};\n const botCommands = botInfo ? buildApiChatBotCommands(botInfo) : undefined;\n\n if (result?.chats?.length > 1) {\n updateLocalDb(result);\n\n const [, mtpLinkedChat] = result.chats;\n const chat = buildApiChatFromPreview(mtpLinkedChat, undefined, true);\n if (chat) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n }\n }\n\n return {\n fullInfo: {\n about,\n onlineCount,\n inviteLink,\n slowMode: slowmodeSeconds ? {\n seconds: slowmodeSeconds,\n nextSendDate: slowmodeNextSendDate,\n } : undefined,\n migratedFrom: migratedFromChatId ? {\n chatId: buildApiPeerId(migratedFromChatId, 'chat'),\n maxMessageId: migratedFromMaxId,\n } : undefined,\n canViewMembers: canViewParticipants,\n isPreHistoryHidden: hiddenPrehistory,\n members,\n kickedMembers,\n adminMembers,\n groupCallId: call ? String(call.id) : undefined,\n linkedChatId: linkedChatId ? buildApiPeerId(linkedChatId, 'chat') : undefined,\n botCommands,\n },\n users: [...(users || []), ...(bannedUsers || []), ...(adminUsers || [])],\n };\n}\n\nexport async function updateChatMutedState({\n chat, isMuted, serverTimeOffset,\n}: {\n chat: ApiChat; isMuted: boolean; serverTimeOffset: number;\n}) {\n await invokeRequest(new GramJs.account.UpdateNotifySettings({\n peer: new GramJs.InputNotifyPeer({\n peer: buildInputPeer(chat.id, chat.accessHash),\n }),\n settings: new GramJs.InputPeerNotifySettings({ muteUntil: isMuted ? MAX_INT_32 : 0 }),\n }));\n\n onUpdate({\n '@type': 'updateNotifyExceptions',\n chatId: chat.id,\n isMuted,\n });\n\n void requestChatUpdate({\n chat,\n serverTimeOffset,\n noLastMessage: true,\n });\n}\n\nexport async function createChannel({\n title, about, users,\n}: {\n title: string; about?: string; users: ApiUser[];\n}): Promise {\n const result = await invokeRequest(new GramJs.channels.CreateChannel({\n broadcast: true,\n title,\n about,\n }), true);\n\n // `createChannel` can return a lot of different update types according to docs,\n // but currently channel creation returns only `Updates` type.\n // Errors are added to catch unexpected cases in future testing\n if (!(result instanceof GramJs.Updates)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected channel creation update', result);\n }\n return undefined;\n }\n\n const newChannel = result.chats[0];\n if (!newChannel || !(newChannel instanceof GramJs.Channel)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Created channel not found', result);\n }\n return undefined;\n }\n\n const channel = buildApiChatFromPreview(newChannel)!;\n\n await invokeRequest(new GramJs.channels.InviteToChannel({\n channel: buildInputEntity(channel.id, channel.accessHash) as GramJs.InputChannel,\n users: users.map(({ id, accessHash }) => buildInputEntity(id, accessHash)) as GramJs.InputUser[],\n }));\n\n return channel;\n}\n\nexport function joinChannel({\n channelId, accessHash,\n}: {\n channelId: string; accessHash: string;\n}) {\n return invokeRequest(new GramJs.channels.JoinChannel({\n channel: buildInputEntity(channelId, accessHash) as GramJs.InputChannel,\n }), true);\n}\n\nexport function deleteChatUser({\n chat, user,\n}: {\n chat: ApiChat; user: ApiUser;\n}) {\n if (chat.type !== 'chatTypeBasicGroup') return undefined;\n return invokeRequest(new GramJs.messages.DeleteChatUser({\n chatId: buildInputEntity(chat.id, chat.accessHash) as BigInt.BigInteger,\n userId: buildInputEntity(user.id, user.accessHash) as GramJs.InputUser,\n }), true);\n}\n\nexport function deleteChat({\n chatId,\n}: {\n chatId: string;\n}) {\n return invokeRequest(new GramJs.messages.DeleteChat({\n chatId: buildInputEntity(chatId) as BigInt.BigInteger,\n }), true);\n}\n\nexport function leaveChannel({\n channelId, accessHash,\n}: {\n channelId: string; accessHash: string;\n}) {\n return invokeRequest(new GramJs.channels.LeaveChannel({\n channel: buildInputEntity(channelId, accessHash) as GramJs.InputChannel,\n }), true);\n}\n\nexport function deleteChannel({\n channelId, accessHash,\n}: {\n channelId: string; accessHash: string;\n}) {\n return invokeRequest(new GramJs.channels.DeleteChannel({\n channel: buildInputEntity(channelId, accessHash) as GramJs.InputChannel,\n }), true);\n}\n\nexport async function createGroupChat({\n title, users,\n}: {\n title: string; users: ApiUser[];\n}): Promise {\n const result = await invokeRequest(new GramJs.messages.CreateChat({\n title,\n users: users.map(({ id, accessHash }) => buildInputEntity(id, accessHash)) as GramJs.InputUser[],\n }), true, true);\n\n // `createChat` can return a lot of different update types according to docs,\n // but currently chat creation returns only `Updates` type.\n // Errors are added to catch unexpected cases in future testing\n if (!(result instanceof GramJs.Updates)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected chat creation update', result);\n }\n return undefined;\n }\n\n const newChat = result.chats[0];\n if (!newChat || !(newChat instanceof GramJs.Chat)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Created chat not found', result);\n }\n return undefined;\n }\n\n return buildApiChatFromPreview(newChat);\n}\n\nexport async function editChatPhoto({\n chatId, accessHash, photo,\n}: {\n chatId: string; accessHash?: string; photo: File;\n}) {\n const uploadedPhoto = await uploadFile(photo);\n const inputEntity = buildInputEntity(chatId, accessHash);\n\n return invokeRequest(\n inputEntity instanceof GramJs.InputChannel\n ? new GramJs.channels.EditPhoto({\n channel: inputEntity as GramJs.InputChannel,\n photo: new GramJs.InputChatUploadedPhoto({\n file: uploadedPhoto,\n }),\n })\n : new GramJs.messages.EditChatPhoto({\n chatId: inputEntity as BigInt.BigInteger,\n photo: new GramJs.InputChatUploadedPhoto({\n file: uploadedPhoto,\n }),\n }),\n true,\n );\n}\n\nexport async function toggleChatPinned({\n chat,\n shouldBePinned,\n}: {\n chat: ApiChat;\n shouldBePinned: boolean;\n}) {\n const { id, accessHash } = chat;\n\n const isActionSuccessful = await invokeRequest(new GramJs.messages.ToggleDialogPin({\n peer: new GramJs.InputDialogPeer({\n peer: buildInputPeer(id, accessHash),\n }),\n pinned: shouldBePinned || undefined,\n }));\n\n if (isActionSuccessful) {\n onUpdate({\n '@type': 'updateChatPinned',\n id: chat.id,\n isPinned: shouldBePinned,\n });\n }\n}\n\nexport function toggleChatArchived({\n chat, folderId,\n}: {\n chat: ApiChat; folderId: number;\n}) {\n const { id, accessHash } = chat;\n\n return invokeRequest(new GramJs.folders.EditPeerFolders({\n folderPeers: [new GramJs.InputFolderPeer({\n peer: buildInputPeer(id, accessHash),\n folderId,\n })],\n }), true);\n}\n\nexport async function fetchChatFolders() {\n const result = await invokeRequest(new GramJs.messages.GetDialogFilters());\n\n if (!result) {\n return undefined;\n }\n\n return {\n byId: buildCollectionByKey(result.map(buildApiChatFolder), 'id') as Record,\n orderedIds: result.map(({ id }) => id),\n };\n}\n\nexport async function fetchRecommendedChatFolders() {\n const results = await invokeRequest(new GramJs.messages.GetSuggestedDialogFilters());\n\n if (!results) {\n return undefined;\n }\n\n return results.map(buildApiChatFolderFromSuggested);\n}\n\nexport async function editChatFolder({\n id,\n folderUpdate,\n}: {\n id: number;\n folderUpdate: ApiChatFolder;\n}) {\n const filter = buildFilterFromApiFolder(folderUpdate);\n\n const isActionSuccessful = await invokeRequest(new GramJs.messages.UpdateDialogFilter({\n id,\n filter,\n }));\n\n if (isActionSuccessful) {\n onUpdate({\n '@type': 'updateChatFolder',\n id,\n folder: folderUpdate,\n });\n }\n}\n\nexport async function deleteChatFolder(id: number) {\n const isActionSuccessful = await invokeRequest(new GramJs.messages.UpdateDialogFilter({\n id,\n filter: undefined,\n }));\n const recommendedChatFolders = await fetchRecommendedChatFolders();\n\n if (isActionSuccessful) {\n onUpdate({\n '@type': 'updateChatFolder',\n id,\n folder: undefined,\n });\n }\n if (recommendedChatFolders) {\n onUpdate({\n '@type': 'updateRecommendedChatFolders',\n folders: recommendedChatFolders,\n });\n }\n}\n\nexport async function toggleDialogUnread({\n chat, hasUnreadMark,\n}: {\n chat: ApiChat; hasUnreadMark: boolean | undefined;\n}) {\n const { id, accessHash } = chat;\n\n const isActionSuccessful = await invokeRequest(new GramJs.messages.MarkDialogUnread({\n peer: new GramJs.InputDialogPeer({\n peer: buildInputPeer(id, accessHash),\n }),\n unread: hasUnreadMark || undefined,\n }));\n\n if (isActionSuccessful) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat: { hasUnreadMark },\n });\n }\n}\n\nexport async function getChatByUsername(username: string) {\n const result = await invokeRequest(new GramJs.contacts.ResolveUsername({\n username,\n }));\n\n if (!result) {\n return undefined;\n }\n\n const { users, chats } = result;\n\n const chat = chats.length\n ? buildApiChatFromPreview(chats[0])\n : buildApiChatFromPreview(users[0]);\n\n if (!chat) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return chat;\n}\n\nexport function togglePreHistoryHidden({\n chat, isEnabled,\n}: { chat: ApiChat; isEnabled: boolean }) {\n const { id, accessHash } = chat;\n const channel = buildInputEntity(id, accessHash);\n\n return invokeRequest(new GramJs.channels.TogglePreHistoryHidden({\n channel: channel as GramJs.InputChannel,\n enabled: isEnabled,\n }), true);\n}\n\nexport function updateChatDefaultBannedRights({\n chat, bannedRights,\n}: { chat: ApiChat; bannedRights: ApiChatBannedRights }) {\n const { id, accessHash } = chat;\n const peer = buildInputPeer(id, accessHash);\n\n return invokeRequest(new GramJs.messages.EditChatDefaultBannedRights({\n peer,\n bannedRights: buildChatBannedRights(bannedRights),\n }), true);\n}\n\nexport function updateChatMemberBannedRights({\n chat, user, bannedRights, untilDate,\n}: { chat: ApiChat; user: ApiUser; bannedRights: ApiChatBannedRights; untilDate?: number }) {\n const channel = buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel;\n const participant = buildInputPeer(user.id, user.accessHash) as GramJs.InputUser;\n\n return invokeRequest(new GramJs.channels.EditBanned({\n channel,\n participant,\n bannedRights: buildChatBannedRights(bannedRights, untilDate),\n }), true);\n}\n\nexport function updateChatAdmin({\n chat, user, adminRights, customTitle = '',\n}: { chat: ApiChat; user: ApiUser; adminRights: ApiChatAdminRights; customTitle: string }) {\n const channel = buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel;\n const userId = buildInputEntity(user.id, user.accessHash) as GramJs.InputUser;\n\n return invokeRequest(new GramJs.channels.EditAdmin({\n channel,\n userId,\n adminRights: buildChatAdminRights(adminRights),\n rank: customTitle,\n }), true);\n}\n\nexport async function updateChatTitle(chat: ApiChat, title: string) {\n const inputEntity = buildInputEntity(chat.id, chat.accessHash);\n await invokeRequest(\n inputEntity instanceof GramJs.InputChannel\n ? new GramJs.channels.EditTitle({\n channel: inputEntity as GramJs.InputChannel,\n title,\n }) : new GramJs.messages.EditChatTitle({\n chatId: inputEntity as BigInt.BigInteger,\n title,\n }),\n true,\n );\n}\n\nexport async function updateChatAbout(chat: ApiChat, about: string) {\n const result = await invokeRequest(new GramJs.messages.EditChatAbout({\n peer: buildInputPeer(chat.id, chat.accessHash),\n about,\n }));\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'updateChatFullInfo',\n id: chat.id,\n fullInfo: {\n about,\n },\n });\n}\n\nexport function toggleSignatures({\n chat, isEnabled,\n}: { chat: ApiChat; isEnabled: boolean }) {\n const { id, accessHash } = chat;\n const channel = buildInputEntity(id, accessHash);\n\n return invokeRequest(new GramJs.channels.ToggleSignatures({\n channel: channel as GramJs.InputChannel,\n enabled: isEnabled,\n }), true);\n}\n\ntype ChannelMembersFilter =\n 'kicked'\n | 'admin'\n | 'recent';\n\nexport async function fetchMembers(\n chatId: string,\n accessHash: string,\n memberFilter: ChannelMembersFilter = 'recent',\n offset?: number,\n) {\n let filter: GramJs.TypeChannelParticipantsFilter;\n\n switch (memberFilter) {\n case 'kicked':\n filter = new GramJs.ChannelParticipantsKicked({ q: '' });\n break;\n case 'admin':\n filter = new GramJs.ChannelParticipantsAdmins();\n break;\n default:\n filter = new GramJs.ChannelParticipantsRecent();\n break;\n }\n\n const result = await invokeRequest(new GramJs.channels.GetParticipants({\n channel: buildInputEntity(chatId, accessHash) as GramJs.InputChannel,\n filter,\n offset,\n limit: MEMBERS_LOAD_SLICE,\n }));\n\n if (!result || result instanceof GramJs.channels.ChannelParticipantsNotModified) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return {\n members: buildChatMembers(result),\n users: result.users.map(buildApiUser).filter(Boolean as any),\n };\n}\n\nexport async function fetchGroupsForDiscussion() {\n const result = await invokeRequest(new GramJs.channels.GetGroupsForDiscussion());\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return result.chats.map((chat) => buildApiChatFromPreview(chat));\n}\n\nexport function setDiscussionGroup({\n channel,\n chat,\n}: {\n channel: ApiChat;\n chat?: ApiChat;\n}) {\n return invokeRequest(new GramJs.channels.SetDiscussionGroup({\n broadcast: buildInputPeer(channel.id, channel.accessHash),\n group: chat ? buildInputPeer(chat.id, chat.accessHash) : new GramJs.InputChannelEmpty(),\n }));\n}\n\nexport async function migrateChat(chat: ApiChat) {\n const result = await invokeRequest(\n new GramJs.messages.MigrateChat({ chatId: buildInputEntity(chat.id) as BigInt.BigInteger }), true,\n );\n\n // `migrateChat` can return a lot of different update types according to docs,\n // but currently chat migrations returns only `Updates` type.\n // Errors are added to catch unexpected cases in future testing\n if (!result || !(result instanceof GramJs.Updates)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected channel creation update', result);\n }\n\n return undefined;\n }\n\n updateLocalDb(result);\n\n return buildApiChatFromPreview(result.chats[1]);\n}\n\nexport async function openChatByInvite(hash: string) {\n const result = await invokeRequest(new GramJs.messages.CheckChatInvite({ hash }));\n\n if (!result) {\n return undefined;\n }\n\n let chat: ApiChat | undefined;\n\n if (result instanceof GramJs.ChatInvite) {\n onUpdate({\n '@type': 'showInvite',\n data: {\n title: result.title,\n hash,\n participantsCount: result.participantsCount,\n isChannel: result.channel,\n },\n });\n } else {\n chat = buildApiChatFromPreview(result.chat);\n\n if (chat) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n }\n }\n\n if (!chat) {\n return undefined;\n }\n\n return { chatId: chat.id };\n}\n\nexport function addChatMembers(chat: ApiChat, users: ApiUser[]) {\n if (chat.type === 'chatTypeChannel' || chat.type === 'chatTypeSuperGroup') {\n return invokeRequest(new GramJs.channels.InviteToChannel({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n users: users.map((user) => buildInputEntity(user.id, user.accessHash)) as GramJs.InputUser[],\n }), true);\n }\n\n return Promise.all(users.map((user) => {\n return invokeRequest(new GramJs.messages.AddChatUser({\n chatId: buildInputEntity(chat.id) as BigInt.BigInteger,\n userId: buildInputEntity(user.id, user.accessHash) as GramJs.InputUser,\n }), true);\n }));\n}\n\nexport function deleteChatMember(chat: ApiChat, user: ApiUser) {\n if (chat.type === 'chatTypeChannel' || chat.type === 'chatTypeSuperGroup') {\n return updateChatMemberBannedRights({\n chat,\n user,\n bannedRights: {\n viewMessages: true,\n sendMessages: true,\n sendMedia: true,\n sendStickers: true,\n sendGifs: true,\n sendGames: true,\n sendInline: true,\n embedLinks: true,\n sendPolls: true,\n changeInfo: true,\n inviteUsers: true,\n pinMessages: true,\n },\n untilDate: MAX_INT_32,\n });\n } else {\n return invokeRequest(new GramJs.messages.DeleteChatUser({\n chatId: buildInputEntity(chat.id) as BigInt.BigInteger,\n userId: buildInputEntity(user.id, user.accessHash) as GramJs.InputUser,\n }), true);\n }\n}\n\nfunction preparePeers(\n result: GramJs.messages.Dialogs | GramJs.messages.DialogsSlice | GramJs.messages.PeerDialogs,\n) {\n const store: Record = {};\n\n result.chats.forEach((chat) => {\n store[`chat${chat.id}`] = chat;\n });\n\n result.users.forEach((user) => {\n store[`user${user.id}`] = user;\n });\n\n return store;\n}\n\nfunction updateLocalDb(result: (\n GramJs.messages.Dialogs | GramJs.messages.DialogsSlice | GramJs.messages.PeerDialogs |\n GramJs.messages.ChatFull | GramJs.contacts.Found |\n GramJs.contacts.ResolvedPeer | GramJs.channels.ChannelParticipants |\n GramJs.messages.Chats | GramJs.messages.ChatsSlice | GramJs.TypeUpdates\n)) {\n if ('users' in result) {\n result.users.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[buildApiPeerId(user.id, 'user')] = user;\n }\n });\n }\n\n if ('chats' in result) {\n result.chats.forEach(addChatToLocalDb);\n }\n\n if ('messages' in result) {\n result.messages.forEach((message) => {\n if (message instanceof GramJs.Message && isMessageWithMedia(message)) {\n addMessageToLocalDb(message);\n }\n });\n }\n}\n\nexport async function importChatInvite({ hash }: { hash: string }) {\n const updates = await invokeRequest(new GramJs.messages.ImportChatInvite({ hash }), true);\n if (!(updates instanceof GramJs.Updates) || !updates.chats.length) {\n return undefined;\n }\n\n return buildApiChatFromPreview(updates.chats[0]);\n}\n","import { pause } from './schedulers';\n\n// Polyfill for Safari: `File` is not available in web worker\nif (typeof File === 'undefined') {\n // eslint-disable-next-line no-global-assign, no-restricted-globals, func-names\n self.File = class extends Blob {\n name: string;\n\n constructor(fileBits: BlobPart[], fileName: string, options?: FilePropertyBag) {\n if (options) {\n const { type, ...rest } = options;\n super(fileBits, { type });\n Object.assign(this, rest);\n } else {\n super(fileBits);\n }\n\n this.name = fileName;\n }\n } as typeof File;\n}\n\nexport function dataUriToBlob(dataUri: string) {\n const arr = dataUri.split(',');\n const mime = arr[0].match(/:(.*?);/)![1];\n const bstr = atob(arr[1]);\n let n = bstr.length;\n const u8arr = new Uint8Array(n);\n\n while (n--) {\n u8arr[n] = bstr.charCodeAt(n);\n }\n\n return new Blob([u8arr], { type: mime });\n}\n\nexport function blobToDataUri(blob: Blob): Promise {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n\n reader.onload = (e: ProgressEvent) => {\n const { result } = e.target || {};\n if (typeof result === 'string') {\n resolve(result);\n }\n\n reject(new Error('Failed to read blob'));\n };\n\n reader.onerror = reject;\n reader.readAsDataURL(blob);\n });\n}\n\nexport function blobToFile(blob: Blob, fileName: string) {\n return new File([blob], fileName, {\n lastModified: Date.now(),\n type: blob.type,\n });\n}\n\nexport function preloadImage(url: string): Promise {\n return new Promise((resolve, reject) => {\n const img = new Image();\n img.onload = () => resolve(img);\n img.onerror = reject;\n img.src = url;\n });\n}\n\nexport function preloadVideo(url: string): Promise {\n return new Promise((resolve, reject) => {\n const video = document.createElement('video');\n video.volume = 0;\n video.onloadedmetadata = () => resolve(video);\n video.onerror = reject;\n video.src = url;\n });\n}\n\nexport async function createPosterForVideo(url: string): Promise {\n const video = await preloadVideo(url);\n\n return Promise.race([\n pause(2000) as Promise,\n new Promise((resolve, reject) => {\n video.onseeked = () => {\n if (!video.videoWidth || !video.videoHeight) {\n resolve(undefined);\n }\n\n const canvas = document.createElement('canvas');\n canvas.width = video.videoWidth;\n canvas.height = video.videoHeight;\n const ctx = canvas.getContext('2d')!;\n ctx.drawImage(video, 0, 0);\n resolve(canvas.toDataURL('image/jpeg'));\n };\n video.onerror = reject;\n video.currentTime = Math.min(video.duration, 1);\n }),\n ]);\n}\n\nexport async function fetchBlob(blobUrl: string) {\n const response = await fetch(blobUrl);\n return response.blob();\n}\n\nexport async function fetchFile(blobUrl: string, fileName: string) {\n const blob = await fetchBlob(blobUrl);\n return blobToFile(blob, fileName);\n}\n\nexport function imgToCanvas(img: HTMLImageElement) {\n const canvas = document.createElement('canvas');\n canvas.width = img.width;\n canvas.height = img.height;\n\n const ctx = canvas.getContext('2d')!;\n ctx.drawImage(img, 0, 0);\n\n return canvas;\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n ApiChat,\n ApiAttachment,\n ApiMessage,\n OnApiUpdate,\n ApiMessageSearchType,\n ApiUser,\n ApiSticker,\n ApiVideo,\n ApiNewPoll,\n ApiMessageEntity,\n ApiOnProgress,\n ApiThreadInfo,\n MAIN_THREAD_ID,\n MESSAGE_DELETED,\n ApiGlobalMessageSearchType,\n ApiReportReason,\n} from '../../types';\n\nimport {\n ALL_FOLDER_ID,\n DEBUG,\n PINNED_MESSAGES_LIMIT,\n SUPPORTED_IMAGE_CONTENT_TYPES,\n SUPPORTED_VIDEO_CONTENT_TYPES,\n} from '../../../config';\nimport { invokeRequest, uploadFile } from './client';\nimport {\n buildApiMessage,\n buildLocalMessage,\n buildWebPage,\n buildLocalForwardedMessage,\n} from '../apiBuilders/messages';\nimport { buildApiUser } from '../apiBuilders/users';\nimport {\n buildInputEntity,\n buildInputPeer,\n generateRandomBigInt,\n getEntityTypeById,\n buildInputMediaDocument,\n buildInputPoll,\n buildMtpMessageEntity,\n isMessageWithMedia,\n isServiceMessageWithMedia,\n buildInputReportReason,\n} from '../gramjsBuilders';\nimport localDb from '../localDb';\nimport { buildApiChatFromPreview } from '../apiBuilders/chats';\nimport { fetchFile } from '../../../util/files';\nimport { addMessageToLocalDb, resolveMessageApiChatId } from '../helpers';\nimport { interpolateArray } from '../../../util/waveform';\nimport { requestChatUpdate } from './chats';\nimport { buildApiPeerId } from '../apiBuilders/peers';\n\nconst FAST_SEND_TIMEOUT = 1000;\nconst INPUT_WAVEFORM_LENGTH = 63;\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function fetchMessages({\n chat,\n threadId,\n ...pagination\n}: {\n chat: ApiChat;\n threadId?: number;\n offsetId?: number;\n addOffset?: number;\n limit: number;\n}) {\n const RequestClass = threadId === MAIN_THREAD_ID ? GramJs.messages.GetHistory : GramJs.messages.GetReplies;\n let result;\n\n try {\n result = await invokeRequest(new RequestClass({\n peer: buildInputPeer(chat.id, chat.accessHash),\n ...(threadId !== MAIN_THREAD_ID && {\n msgId: threadId,\n }),\n ...pagination,\n }), undefined, true);\n } catch (err) {\n if (err.message === 'CHANNEL_PRIVATE') {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat: {\n isRestricted: true,\n },\n });\n }\n }\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter(Boolean as any);\n const threadInfos = messages.map(({ threadInfo }) => threadInfo).filter(Boolean as any);\n\n return {\n messages,\n users,\n chats,\n threadInfos,\n };\n}\n\nexport async function fetchMessage({ chat, messageId }: { chat: ApiChat; messageId: number }) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n\n let result;\n try {\n result = await invokeRequest(\n isChannel\n ? new GramJs.channels.GetMessages({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n id: [new GramJs.InputMessageID({ id: messageId })],\n })\n : new GramJs.messages.GetMessages({\n id: [new GramJs.InputMessageID({ id: messageId })],\n }),\n undefined,\n true,\n );\n } catch (err) {\n const { message } = err;\n\n // When fetching messages for the bot @replies, there may be situations when the user was banned\n // in the comment group or this group was deleted\n if (message !== 'CHANNEL_PRIVATE') {\n onUpdate({\n '@type': 'error',\n error: {\n message,\n isSlowMode: false,\n hasErrorKey: true,\n },\n });\n }\n }\n\n if (!result || result instanceof GramJs.messages.MessagesNotModified) {\n return undefined;\n }\n\n const mtpMessage = result.messages[0];\n if (!mtpMessage) {\n return undefined;\n }\n\n if (mtpMessage instanceof GramJs.MessageEmpty) {\n return MESSAGE_DELETED;\n }\n\n const message = mtpMessage && buildApiMessage(mtpMessage);\n if (!message) {\n return undefined;\n }\n\n if (mtpMessage instanceof GramJs.Message) {\n addMessageToLocalDb(mtpMessage);\n }\n\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n\n return { message, users };\n}\n\nlet queue = Promise.resolve();\n\nexport function sendMessage(\n {\n chat,\n text,\n entities,\n replyingTo,\n attachment,\n sticker,\n gif,\n poll,\n isSilent,\n scheduledAt,\n groupedId,\n noWebPage,\n serverTimeOffset,\n }: {\n chat: ApiChat;\n text?: string;\n entities?: ApiMessageEntity[];\n replyingTo?: number;\n attachment?: ApiAttachment;\n sticker?: ApiSticker;\n gif?: ApiVideo;\n poll?: ApiNewPoll;\n isSilent?: boolean;\n scheduledAt?: number;\n groupedId?: string;\n noWebPage?: boolean;\n serverTimeOffset?: number;\n },\n onProgress?: ApiOnProgress,\n) {\n const localMessage = buildLocalMessage(\n chat, text, entities, replyingTo, attachment, sticker, gif, poll, groupedId, scheduledAt, serverTimeOffset,\n );\n onUpdate({\n '@type': localMessage.isScheduled ? 'newScheduledMessage' : 'newMessage',\n id: localMessage.id,\n chatId: chat.id,\n message: localMessage,\n });\n\n // This is expected to arrive after `updateMessageSendSucceeded` which replaces the local ID,\n // so in most cases this will be simply ignored\n setTimeout(() => {\n onUpdate({\n '@type': localMessage.isScheduled ? 'updateScheduledMessage' : 'updateMessage',\n id: localMessage.id,\n chatId: chat.id,\n message: {\n sendingState: 'messageSendingStatePending',\n },\n });\n }, FAST_SEND_TIMEOUT);\n\n const randomId = generateRandomBigInt();\n localDb.localMessages[String(randomId)] = localMessage;\n\n if (groupedId) {\n return sendGroupedMedia({\n chat, text, entities, replyingTo, attachment: attachment!, groupedId, isSilent, scheduledAt,\n }, randomId, localMessage, onProgress);\n }\n\n const prevQueue = queue;\n queue = (async () => {\n let media: GramJs.TypeInputMedia | undefined;\n if (attachment) {\n try {\n media = await uploadMedia(localMessage, attachment, onProgress!);\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n\n await prevQueue;\n\n return;\n }\n } else if (sticker) {\n media = buildInputMediaDocument(sticker);\n } else if (gif) {\n media = buildInputMediaDocument(gif);\n } else if (poll) {\n media = buildInputPoll(poll, randomId);\n }\n\n await prevQueue;\n\n const RequestClass = media ? GramJs.messages.SendMedia : GramJs.messages.SendMessage;\n\n await invokeRequest(new RequestClass({\n clearDraft: true,\n message: text || '',\n entities: entities ? entities.map(buildMtpMessageEntity) : undefined,\n peer: buildInputPeer(chat.id, chat.accessHash),\n randomId,\n ...(isSilent && { silent: isSilent }),\n ...(scheduledAt && { scheduleDate: scheduledAt }),\n ...(replyingTo && { replyToMsgId: replyingTo }),\n ...(media && { media }),\n ...(noWebPage && { noWebpage: noWebPage }),\n }), true);\n })();\n\n return queue;\n}\n\nconst groupedUploads: Record;\n}> = {};\n\nfunction sendGroupedMedia(\n {\n chat,\n text,\n entities,\n replyingTo,\n attachment,\n groupedId,\n isSilent,\n scheduledAt,\n }: {\n chat: ApiChat;\n text?: string;\n entities?: ApiMessageEntity[];\n replyingTo?: number;\n attachment: ApiAttachment;\n groupedId: string;\n isSilent?: boolean;\n scheduledAt?: number;\n },\n randomId: GramJs.long,\n localMessage: ApiMessage,\n onProgress?: ApiOnProgress,\n) {\n let groupIndex = -1;\n if (!groupedUploads[groupedId]) {\n groupedUploads[groupedId] = {\n counter: 0,\n singleMediaByIndex: {},\n };\n }\n\n groupIndex = groupedUploads[groupedId].counter++;\n\n const prevQueue = queue;\n queue = (async () => {\n let media;\n try {\n media = await uploadMedia(localMessage, attachment, onProgress!);\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n\n groupedUploads[groupedId].counter--;\n\n await prevQueue;\n\n return;\n }\n\n const inputMedia = await fetchInputMedia(\n buildInputPeer(chat.id, chat.accessHash),\n media as GramJs.InputMediaUploadedPhoto | GramJs.InputMediaUploadedDocument,\n );\n\n await prevQueue;\n\n if (!inputMedia) {\n groupedUploads[groupedId].counter--;\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('Failed to upload grouped media');\n }\n\n return;\n }\n\n groupedUploads[groupedId].singleMediaByIndex[groupIndex] = new GramJs.InputSingleMedia({\n media: inputMedia,\n randomId,\n message: text || '',\n entities: entities ? entities.map(buildMtpMessageEntity) : undefined,\n });\n\n if (Object.keys(groupedUploads[groupedId].singleMediaByIndex).length < groupedUploads[groupedId].counter) {\n return;\n }\n\n const { singleMediaByIndex } = groupedUploads[groupedId];\n delete groupedUploads[groupedId];\n\n await invokeRequest(new GramJs.messages.SendMultiMedia({\n clearDraft: true,\n peer: buildInputPeer(chat.id, chat.accessHash),\n multiMedia: Object.values(singleMediaByIndex), // Object keys are usually ordered\n replyToMsgId: replyingTo,\n ...(isSilent && { silent: isSilent }),\n ...(scheduledAt && { scheduleDate: scheduledAt }),\n }), true);\n })();\n\n return queue;\n}\n\nasync function fetchInputMedia(\n peer: GramJs.TypeInputPeer,\n uploadedMedia: GramJs.InputMediaUploadedPhoto | GramJs.InputMediaUploadedDocument,\n) {\n const messageMedia = await invokeRequest(new GramJs.messages.UploadMedia({\n peer,\n media: uploadedMedia,\n }));\n\n if ((\n messageMedia instanceof GramJs.MessageMediaPhoto\n && messageMedia.photo\n && messageMedia.photo instanceof GramJs.Photo)\n ) {\n const { photo: { id, accessHash, fileReference } } = messageMedia;\n\n return new GramJs.InputMediaPhoto({\n id: new GramJs.InputPhoto({ id, accessHash, fileReference }),\n });\n }\n\n if ((\n messageMedia instanceof GramJs.MessageMediaDocument\n && messageMedia.document\n && messageMedia.document instanceof GramJs.Document)\n ) {\n const { document: { id, accessHash, fileReference } } = messageMedia;\n\n return new GramJs.InputMediaDocument({\n id: new GramJs.InputDocument({ id, accessHash, fileReference }),\n });\n }\n\n return undefined;\n}\n\nexport async function editMessage({\n chat,\n message,\n text,\n entities,\n noWebPage,\n serverTimeOffset,\n}: {\n chat: ApiChat;\n message: ApiMessage;\n text: string;\n entities?: ApiMessageEntity[];\n noWebPage?: boolean;\n serverTimeOffset: number;\n}) {\n const isScheduled = message.date * 1000 > Date.now() + serverTimeOffset * 1000;\n const messageUpdate: Partial = {\n content: {\n ...message.content,\n ...(text && {\n text: {\n text,\n entities,\n },\n }),\n },\n };\n\n onUpdate({\n '@type': isScheduled ? 'updateScheduledMessage' : 'updateMessage',\n id: message.id,\n chatId: chat.id,\n message: messageUpdate,\n });\n\n // TODO Revise intersecting with scheduled\n localDb.localMessages[message.id] = { ...message, ...messageUpdate };\n\n const mtpEntities = entities && entities.map(buildMtpMessageEntity);\n\n await invokeRequest(new GramJs.messages.EditMessage({\n message: text || '',\n entities: mtpEntities,\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: message.id,\n ...(isScheduled && { scheduleDate: message.date }),\n ...(noWebPage && { noWebpage: noWebPage }),\n }), true);\n}\n\nexport async function rescheduleMessage({\n chat,\n message,\n scheduledAt,\n}: {\n chat: ApiChat;\n message: ApiMessage;\n scheduledAt: number;\n}) {\n await invokeRequest(new GramJs.messages.EditMessage({\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: message.id,\n scheduleDate: scheduledAt,\n }), true);\n}\n\nasync function uploadMedia(localMessage: ApiMessage, attachment: ApiAttachment, onProgress: ApiOnProgress) {\n const {\n filename, blobUrl, mimeType, quick, voice,\n } = attachment;\n\n const file = await fetchFile(blobUrl, filename);\n const patchedOnProgress: ApiOnProgress = (progress) => {\n if (onProgress.isCanceled) {\n patchedOnProgress.isCanceled = true;\n } else {\n onProgress(progress, localMessage.id);\n }\n };\n const inputFile = await uploadFile(file, patchedOnProgress);\n\n const attributes: GramJs.TypeDocumentAttribute[] = [new GramJs.DocumentAttributeFilename({ fileName: filename })];\n if (quick) {\n if (SUPPORTED_IMAGE_CONTENT_TYPES.has(mimeType)) {\n return new GramJs.InputMediaUploadedPhoto({ file: inputFile });\n }\n\n if (SUPPORTED_VIDEO_CONTENT_TYPES.has(mimeType)) {\n const { width, height, duration } = quick;\n if (duration !== undefined) {\n attributes.push(new GramJs.DocumentAttributeVideo({\n duration,\n w: width,\n h: height,\n supportsStreaming: true,\n }));\n }\n }\n }\n\n if (voice) {\n const { duration, waveform } = voice;\n const { data: inputWaveform } = interpolateArray(waveform, INPUT_WAVEFORM_LENGTH);\n attributes.push(new GramJs.DocumentAttributeAudio({\n voice: true,\n duration,\n waveform: Buffer.from(inputWaveform),\n }));\n }\n\n return new GramJs.InputMediaUploadedDocument({\n file: inputFile,\n mimeType,\n attributes,\n });\n}\n\nexport async function pinMessage({\n chat, messageId, isUnpin, isOneSide, isSilent,\n}: { chat: ApiChat; messageId: number; isUnpin: boolean; isOneSide: boolean; isSilent: boolean }) {\n await invokeRequest(new GramJs.messages.UpdatePinnedMessage({\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: messageId,\n ...(isUnpin && { unpin: true }),\n ...(isOneSide && { pmOneside: true }),\n ...(isSilent && { silent: true }),\n }), true);\n}\n\nexport async function unpinAllMessages({ chat }: { chat: ApiChat }) {\n await invokeRequest(new GramJs.messages.UnpinAllMessages({\n peer: buildInputPeer(chat.id, chat.accessHash),\n }), true);\n}\n\nexport async function deleteMessages({\n chat, messageIds, shouldDeleteForAll,\n}: {\n chat: ApiChat; messageIds: number[]; shouldDeleteForAll?: boolean;\n}) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n\n const result = await invokeRequest(\n isChannel\n ? new GramJs.channels.DeleteMessages({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n id: messageIds,\n })\n : new GramJs.messages.DeleteMessages({\n id: messageIds,\n ...(shouldDeleteForAll && { revoke: true }),\n }),\n );\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'deleteMessages',\n ids: messageIds,\n ...(isChannel && { chatId: chat.id }),\n });\n}\n\nexport async function deleteScheduledMessages({\n chat, messageIds,\n}: {\n chat: ApiChat; messageIds: number[];\n}) {\n const result = await invokeRequest(\n new GramJs.messages.DeleteScheduledMessages({\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: messageIds,\n }),\n );\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'deleteScheduledMessages',\n ids: messageIds,\n chatId: chat.id,\n });\n}\n\nexport async function deleteHistory({\n chat, shouldDeleteForAll, maxId,\n}: {\n chat: ApiChat; shouldDeleteForAll?: boolean; maxId?: number;\n}) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n const result = await invokeRequest(\n isChannel\n ? new GramJs.channels.DeleteHistory({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n maxId,\n })\n : new GramJs.messages.DeleteHistory({\n peer: buildInputPeer(chat.id, chat.accessHash),\n ...(shouldDeleteForAll && { revoke: true }),\n ...(!shouldDeleteForAll && { just_clear: true }),\n maxId,\n }),\n );\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'deleteHistory',\n chatId: chat.id,\n });\n}\n\nexport async function reportMessages({\n peer, messageIds, reason, description,\n}: {\n peer: ApiChat | ApiUser; messageIds: number[]; reason: ApiReportReason; description?: string;\n}) {\n const result = await invokeRequest(new GramJs.messages.Report({\n peer: buildInputPeer(peer.id, peer.accessHash),\n id: messageIds,\n reason: buildInputReportReason(reason),\n message: description,\n }));\n\n return result;\n}\n\nexport async function markMessageListRead({\n chat, threadId, maxId, serverTimeOffset,\n}: {\n chat: ApiChat; threadId: number; maxId?: number; serverTimeOffset: number;\n}) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n\n if (isChannel && threadId === MAIN_THREAD_ID) {\n await invokeRequest(new GramJs.channels.ReadHistory({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n maxId,\n }));\n } else if (isChannel) {\n await invokeRequest(new GramJs.messages.ReadDiscussion({\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: threadId,\n readMaxId: maxId,\n }));\n } else {\n await invokeRequest(new GramJs.messages.ReadHistory({\n peer: buildInputPeer(chat.id, chat.accessHash),\n maxId,\n }));\n }\n\n if (threadId === MAIN_THREAD_ID) {\n void requestChatUpdate({ chat, serverTimeOffset, noLastMessage: true });\n } else {\n void requestThreadInfoUpdate({ chat, threadId });\n }\n}\n\nexport async function markMessagesRead({\n chat, messageIds,\n}: {\n chat: ApiChat; messageIds: number[];\n}) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n\n await invokeRequest(\n isChannel\n ? new GramJs.channels.ReadMessageContents({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n id: messageIds,\n })\n : new GramJs.messages.ReadMessageContents({\n id: messageIds,\n }),\n );\n\n onUpdate({\n ...(isChannel ? {\n '@type': 'updateChannelMessages',\n channelId: chat.id,\n } : {\n '@type': 'updateCommonBoxMessages',\n }),\n ids: messageIds,\n messageUpdate: {\n hasUnreadMention: false,\n isMediaUnread: false,\n },\n });\n}\n\nexport async function requestThreadInfoUpdate({\n chat, threadId,\n}: {\n chat: ApiChat; threadId: number;\n}) {\n const [topMessageResult, repliesResult] = await Promise.all([\n invokeRequest(new GramJs.messages.GetDiscussionMessage({\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: threadId,\n })),\n invokeRequest(new GramJs.messages.GetReplies({\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: threadId,\n offsetId: 1,\n addOffset: -1,\n limit: 1,\n })),\n ]);\n\n if (!topMessageResult || !topMessageResult.messages.length) {\n return undefined;\n }\n\n const discussionChatId = resolveMessageApiChatId(topMessageResult.messages[0]);\n if (!discussionChatId) {\n return undefined;\n }\n\n onUpdate({\n '@type': 'updateThreadInfo',\n chatId: discussionChatId,\n threadId,\n threadInfo: {\n threadId,\n topMessageId: topMessageResult.messages[topMessageResult.messages.length - 1].id,\n lastReadInboxMessageId: topMessageResult.readInboxMaxId,\n messagesCount: (repliesResult instanceof GramJs.messages.ChannelMessages) ? repliesResult.count : undefined,\n },\n firstMessageId: repliesResult && 'messages' in repliesResult && repliesResult.messages.length\n ? repliesResult.messages[0].id\n : undefined,\n });\n\n const chats = topMessageResult.chats.map((c) => buildApiChatFromPreview(c)).filter(Boolean as any);\n chats.forEach((newChat) => {\n onUpdate({\n '@type': 'updateChat',\n id: newChat.id,\n chat: newChat,\n noTopChatsRequest: true,\n });\n });\n\n return {\n discussionChatId,\n };\n}\n\nexport async function searchMessagesLocal({\n chatOrUser, type, query, topMessageId, minDate, maxDate, ...pagination\n}: {\n chatOrUser: ApiChat | ApiUser;\n type?: ApiMessageSearchType | ApiGlobalMessageSearchType;\n query?: string;\n topMessageId?: number;\n offsetId?: number;\n addOffset?: number;\n limit: number;\n minDate?: number;\n maxDate?: number;\n}) {\n let filter;\n switch (type) {\n case 'media':\n filter = new GramJs.InputMessagesFilterPhotoVideo();\n break;\n case 'documents':\n filter = new GramJs.InputMessagesFilterDocument();\n break;\n case 'links':\n filter = new GramJs.InputMessagesFilterUrl();\n break;\n case 'audio':\n filter = new GramJs.InputMessagesFilterMusic();\n break;\n case 'voice':\n filter = new GramJs.InputMessagesFilterRoundVoice();\n break;\n case 'profilePhoto':\n filter = new GramJs.InputMessagesFilterChatPhotos();\n break;\n case 'text':\n default: {\n filter = new GramJs.InputMessagesFilterEmpty();\n }\n }\n\n const result = await invokeRequest(new GramJs.messages.Search({\n peer: buildInputPeer(chatOrUser.id, chatOrUser.accessHash),\n filter,\n q: query || '',\n topMsgId: topMessageId,\n minDate,\n maxDate,\n ...pagination,\n }));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n\n let totalCount = messages.length;\n let nextOffsetId: number | undefined;\n if (result instanceof GramJs.messages.MessagesSlice || result instanceof GramJs.messages.ChannelMessages) {\n totalCount = result.count;\n\n if (messages.length) {\n nextOffsetId = messages[messages.length - 1].id;\n }\n }\n\n return {\n messages,\n users,\n totalCount,\n nextOffsetId,\n };\n}\n\nexport async function searchMessagesGlobal({\n query, offsetRate = 0, limit, type = 'text', minDate, maxDate,\n}: {\n query: string;\n offsetRate?: number;\n limit: number;\n type?: ApiGlobalMessageSearchType;\n minDate?: number;\n maxDate?: number;\n}) {\n let filter;\n switch (type) {\n case 'media':\n filter = new GramJs.InputMessagesFilterPhotoVideo();\n break;\n case 'documents':\n filter = new GramJs.InputMessagesFilterDocument();\n break;\n case 'links':\n filter = new GramJs.InputMessagesFilterUrl();\n break;\n case 'audio':\n filter = new GramJs.InputMessagesFilterMusic();\n break;\n case 'voice':\n filter = new GramJs.InputMessagesFilterRoundVoice();\n break;\n case 'text':\n default: {\n if (!query && !(maxDate && minDate)) {\n return undefined;\n }\n\n filter = new GramJs.InputMessagesFilterEmpty();\n }\n }\n\n const result = await invokeRequest(new GramJs.messages.SearchGlobal({\n q: query,\n offsetRate,\n offsetPeer: new GramJs.InputPeerEmpty(),\n limit,\n filter,\n folderId: ALL_FOLDER_ID,\n minDate,\n maxDate,\n }));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb({\n chats: result.chats,\n users: result.users,\n messages: result.messages,\n } as GramJs.messages.Messages);\n\n const chats = result.chats.map((user) => buildApiChatFromPreview(user)).filter(Boolean as any);\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n\n let totalCount = messages.length;\n let nextRate: number | undefined;\n if (result instanceof GramJs.messages.MessagesSlice || result instanceof GramJs.messages.ChannelMessages) {\n totalCount = result.count;\n\n if (messages.length) {\n nextRate = messages[messages.length - 1].id;\n }\n }\n\n return {\n messages,\n users,\n chats,\n totalCount,\n nextRate: 'nextRate' in result && result.nextRate ? result.nextRate : nextRate,\n };\n}\n\nexport async function fetchWebPagePreview({ message }: { message: string }) {\n const preview = await invokeRequest(new GramJs.messages.GetWebPagePreview({\n message,\n }));\n\n return preview && buildWebPage(preview);\n}\n\nexport async function sendPollVote({\n chat, messageId, options,\n}: {\n chat: ApiChat;\n messageId: number;\n options: string[];\n}) {\n const { id, accessHash } = chat;\n\n await invokeRequest(new GramJs.messages.SendVote({\n peer: buildInputPeer(id, accessHash),\n msgId: messageId,\n options: options.map((option) => Buffer.from(option)),\n }), true);\n}\n\nexport async function loadPollOptionResults({\n chat, messageId, option, offset, limit, shouldResetVoters,\n}: {\n chat: ApiChat;\n messageId: number;\n option?: string;\n offset?: string;\n limit?: number;\n shouldResetVoters?: boolean;\n}) {\n const { id, accessHash } = chat;\n\n const result = await invokeRequest(new GramJs.messages.GetPollVotes({\n peer: buildInputPeer(id, accessHash),\n id: messageId,\n ...(option && { option: Buffer.from(option) }),\n ...(offset && { offset }),\n ...(limit && { limit }),\n }));\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb({\n chats: [] as GramJs.TypeChat[],\n users: result.users,\n messages: [] as GramJs.Message[],\n } as GramJs.messages.Messages);\n\n const users = result.users.map(buildApiUser).filter(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}: {\n fromChat: ApiChat;\n toChat: ApiChat;\n messages: ApiMessage[];\n serverTimeOffset: number;\n isSilent?: boolean;\n scheduledAt?: number;\n}) {\n const messageIds = messages.map(({ id }) => id);\n const randomIds = messages.map(generateRandomBigInt);\n\n messages.forEach((message, index) => {\n const localMessage = buildLocalForwardedMessage(toChat, message, serverTimeOffset, scheduledAt);\n localDb.localMessages[String(randomIds[index])] = localMessage;\n\n onUpdate({\n '@type': localMessage.isScheduled ? 'newScheduledMessage' : 'newMessage',\n id: localMessage.id,\n chatId: toChat.id,\n message: localMessage,\n });\n });\n\n await invokeRequest(new GramJs.messages.ForwardMessages({\n fromPeer: buildInputPeer(fromChat.id, fromChat.accessHash),\n toPeer: buildInputPeer(toChat.id, toChat.accessHash),\n randomId: randomIds,\n id: messageIds,\n ...(isSilent && { sil2ent: isSilent }),\n ...(scheduledAt && { scheduleDate: scheduledAt }),\n }), true);\n}\n\nexport async function findFirstMessageIdAfterDate({\n chat,\n timestamp,\n}: {\n chat: ApiChat;\n timestamp: number;\n}) {\n const result = await invokeRequest(new GramJs.messages.GetHistory({\n peer: buildInputPeer(chat.id, chat.accessHash),\n offsetDate: timestamp,\n addOffset: -1,\n limit: 1,\n }));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages || !result.messages.length\n ) {\n return undefined;\n }\n\n return result.messages[0].id;\n}\n\nexport async function fetchScheduledHistory({ chat }: { chat: ApiChat }) {\n const { id, accessHash } = chat;\n\n const result = await invokeRequest(new GramJs.messages.GetScheduledHistory({\n peer: buildInputPeer(id, accessHash),\n }));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n\n return {\n messages,\n };\n}\n\nexport async function sendScheduledMessages({ chat, ids }: { chat: ApiChat; ids: number[] }) {\n const { id, accessHash } = chat;\n\n await invokeRequest(new GramJs.messages.SendScheduledMessages({\n peer: buildInputPeer(id, accessHash),\n id: ids,\n }), true);\n}\n\nfunction updateLocalDb(result: (\n GramJs.messages.MessagesSlice | GramJs.messages.Messages | GramJs.messages.ChannelMessages |\n GramJs.messages.DiscussionMessage\n)) {\n result.users.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[buildApiPeerId(user.id, 'user')] = user;\n }\n });\n\n result.chats.forEach((chat) => {\n if (chat instanceof GramJs.Chat || chat instanceof GramJs.Channel) {\n localDb.chats[buildApiPeerId(chat.id, chat instanceof GramJs.Chat ? 'chat' : 'channel')] = chat;\n }\n });\n\n result.messages.forEach((message) => {\n if ((message instanceof GramJs.Message && isMessageWithMedia(message))\n || (message instanceof GramJs.MessageService && isServiceMessageWithMedia(message))\n ) {\n addMessageToLocalDb(message);\n }\n });\n}\n\nexport async function fetchPinnedMessages({ chat }: { chat: ApiChat }) {\n const result = await invokeRequest(new GramJs.messages.Search(\n {\n peer: buildInputPeer(chat.id, chat.accessHash),\n filter: new GramJs.InputMessagesFilterPinned(),\n q: '',\n limit: PINNED_MESSAGES_LIMIT,\n },\n ));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter(Boolean as any);\n\n return {\n messages,\n users,\n chats,\n };\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport {\n OnApiUpdate, ApiUser, ApiChat, ApiPhoto,\n} from '../../types';\n\nimport { COMMON_CHATS_LIMIT, PROFILE_PHOTOS_LIMIT } from '../../../config';\nimport { invokeRequest } from './client';\nimport { searchMessagesLocal } from './messages';\nimport {\n buildInputEntity,\n buildInputPeer,\n buildInputContact,\n buildMtpPeerId,\n getEntityTypeById,\n} from '../gramjsBuilders';\nimport { buildApiUser, buildApiUserFromFull } from '../apiBuilders/users';\nimport { buildApiChatFromPreview } from '../apiBuilders/chats';\nimport { buildApiPhoto } from '../apiBuilders/common';\nimport localDb from '../localDb';\nimport { addChatToLocalDb, addPhotoToLocalDb } from '../helpers';\nimport { buildApiPeerId } from '../apiBuilders/peers';\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function fetchFullUser({\n id,\n accessHash,\n}: {\n id: string;\n accessHash?: string;\n}) {\n const input = buildInputEntity(id, accessHash);\n if (!(input instanceof GramJs.InputUser)) {\n return;\n }\n\n const fullInfo = await invokeRequest(new GramJs.users.GetFullUser({ id: input }));\n\n if (!fullInfo) {\n return;\n }\n\n const userWithFullInfo = buildApiUserFromFull(fullInfo);\n\n onUpdate({\n '@type': 'updateUser',\n id,\n user: {\n fullInfo: userWithFullInfo.fullInfo,\n },\n });\n}\n\nexport async function fetchCommonChats(id: string, accessHash?: string, maxId?: string) {\n const commonChats = await invokeRequest(new GramJs.messages.GetCommonChats({\n userId: buildInputEntity(id, accessHash) as GramJs.InputUser,\n maxId: maxId ? buildMtpPeerId(maxId, getEntityTypeById(maxId)) : undefined,\n limit: COMMON_CHATS_LIMIT,\n }));\n\n if (!commonChats) {\n return undefined;\n }\n\n updateLocalDb(commonChats);\n\n const chatIds: string[] = [];\n const chats: ApiChat[] = [];\n\n commonChats.chats.forEach((mtpChat) => {\n const chat = buildApiChatFromPreview(mtpChat);\n\n if (chat) {\n chats.push(chat);\n chatIds.push(chat.id);\n }\n });\n\n return { chats, chatIds, isFullyLoaded: chatIds.length < COMMON_CHATS_LIMIT };\n}\n\nexport async function fetchNearestCountry() {\n const dcInfo = await invokeRequest(new GramJs.help.GetNearestDc());\n\n return dcInfo?.country;\n}\n\nexport async function fetchTopUsers() {\n const topPeers = await invokeRequest(new GramJs.contacts.GetTopPeers({\n correspondents: true,\n }));\n if (!(topPeers instanceof GramJs.contacts.TopPeers)) {\n return undefined;\n }\n\n const users = topPeers.users.map(buildApiUser).filter((user) => !!user && !user.isSelf) as ApiUser[];\n const ids = users.map(({ id }) => id);\n\n return {\n ids,\n users,\n };\n}\n\nexport async function fetchContactList() {\n const result = await invokeRequest(new GramJs.contacts.GetContacts({ hash: BigInt('0') }));\n if (!result || result instanceof GramJs.contacts.ContactsNotModified) {\n return undefined;\n }\n\n result.users.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[buildApiPeerId(user.id, 'user')] = user;\n }\n });\n\n return {\n users: result.users.map(buildApiUser).filter(Boolean as any),\n chats: result.users.map((user) => buildApiChatFromPreview(user)).filter(Boolean as any),\n };\n}\n\nexport async function fetchUsers({ users }: { users: ApiUser[] }) {\n const result = await invokeRequest(new GramJs.users.GetUsers({\n id: users.map(({ id, accessHash }) => buildInputPeer(id, accessHash)),\n }));\n if (!result || !result.length) {\n return undefined;\n }\n\n result.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[buildApiPeerId(user.id, 'user')] = user;\n }\n });\n\n return result.map(buildApiUser).filter(Boolean as any);\n}\n\nexport function updateContact({\n phone,\n firstName,\n lastName,\n}: {\n phone?: string;\n firstName?: string;\n lastName?: string;\n}) {\n return invokeRequest(new GramJs.contacts.ImportContacts({\n contacts: [buildInputContact({\n phone: phone || '',\n firstName: firstName || '',\n lastName: lastName || '',\n })],\n }));\n}\n\nexport function addContact({\n id,\n accessHash,\n phoneNumber = '',\n firstName = '',\n lastName = '',\n}: {\n id: string;\n accessHash?: string;\n phoneNumber?: string;\n firstName?: string;\n lastName?: string;\n}) {\n return invokeRequest(new GramJs.contacts.AddContact({\n id: buildInputEntity(id, accessHash) as GramJs.InputUser,\n firstName,\n lastName,\n phone: phoneNumber,\n }), true);\n}\n\nexport async function deleteUser({\n id,\n accessHash,\n}: {\n id: string;\n accessHash?: string;\n}) {\n const input = buildInputEntity(id, accessHash);\n if (!(input instanceof GramJs.InputUser)) {\n return;\n }\n\n const result = await invokeRequest(new GramJs.contacts.DeleteContacts({ id: [input] }));\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'deleteUser',\n id,\n });\n}\n\nexport async function fetchProfilePhotos(user?: ApiUser, chat?: ApiChat) {\n if (user) {\n const { id, accessHash } = user;\n\n const result = await invokeRequest(new GramJs.photos.GetUserPhotos({\n userId: buildInputEntity(id, accessHash) as GramJs.InputUser,\n limit: PROFILE_PHOTOS_LIMIT,\n offset: 0,\n maxId: BigInt('0'),\n }));\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return {\n photos: result.photos\n .filter((photo): photo is GramJs.Photo => photo instanceof GramJs.Photo)\n .map(buildApiPhoto),\n };\n }\n\n const result = await searchMessagesLocal({\n chatOrUser: chat!,\n type: 'profilePhoto',\n limit: PROFILE_PHOTOS_LIMIT,\n });\n\n if (!result) {\n return undefined;\n }\n\n const { messages, users } = result;\n\n return {\n photos: messages.map((message) => message.content.action!.photo).filter(Boolean as any),\n users,\n };\n}\n\nfunction updateLocalDb(result: (GramJs.photos.Photos | GramJs.photos.PhotosSlice | GramJs.messages.Chats)) {\n if ('chats' in result) {\n result.chats.forEach(addChatToLocalDb);\n }\n\n if ('photos' in result) {\n result.photos.forEach(addPhotoToLocalDb);\n }\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport { ApiSticker, ApiVideo, OnApiUpdate } from '../../types';\n\nimport { invokeRequest } from './client';\nimport { buildStickerFromDocument, buildStickerSet, buildStickerSetCovered } from '../apiBuilders/symbols';\nimport { buildInputStickerSet, buildInputDocument, buildInputStickerSetShortName } from '../gramjsBuilders';\nimport { buildVideoFromDocument } from '../apiBuilders/messages';\nimport { RECENT_STICKERS_LIMIT } from '../../../config';\n\nimport localDb from '../localDb';\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function fetchStickerSets({ hash = '0' }: { hash?: string }) {\n const allStickers = await invokeRequest(new GramJs.messages.GetAllStickers({ hash: BigInt(hash) }));\n\n if (!allStickers || allStickers instanceof GramJs.messages.AllStickersNotModified) {\n return undefined;\n }\n\n allStickers.sets.forEach((stickerSet) => {\n if (stickerSet.thumbs?.length) {\n localDb.stickerSets[String(stickerSet.id)] = stickerSet;\n }\n });\n\n return {\n hash: String(allStickers.hash),\n sets: allStickers.sets.map(buildStickerSet),\n };\n}\n\nexport async function fetchRecentStickers({ hash = '0' }: { hash?: string }) {\n const result = await invokeRequest(new GramJs.messages.GetRecentStickers({ hash: BigInt(hash) }));\n\n if (!result || result instanceof GramJs.messages.RecentStickersNotModified) {\n return undefined;\n }\n\n return {\n hash: String(result.hash),\n stickers: processStickerResult(result.stickers.slice(0, RECENT_STICKERS_LIMIT)),\n };\n}\n\nexport async function fetchFavoriteStickers({ hash = '0' }: { hash?: string }) {\n const result = await invokeRequest(new GramJs.messages.GetFavedStickers({ hash: BigInt(hash) }));\n\n if (!result || result instanceof GramJs.messages.FavedStickersNotModified) {\n return undefined;\n }\n\n return {\n hash: String(result.hash),\n stickers: processStickerResult(result.stickers),\n };\n}\n\nexport async function fetchFeaturedStickers({ hash = '0' }: { hash?: string }) {\n const result = await invokeRequest(new GramJs.messages.GetFeaturedStickers({ hash: BigInt(hash) }));\n\n if (!result || result instanceof GramJs.messages.FeaturedStickersNotModified) {\n return undefined;\n }\n\n return {\n hash: String(result.hash),\n sets: result.sets.map(buildStickerSetCovered),\n };\n}\n\nexport async function faveSticker({\n sticker,\n unfave,\n}: {\n sticker: ApiSticker;\n unfave?: boolean;\n}) {\n const request = new GramJs.messages.FaveSticker({\n id: buildInputDocument(sticker),\n unfave,\n });\n\n const result = await invokeRequest(request);\n if (result) {\n onUpdate({\n '@type': 'updateFavoriteStickers',\n });\n }\n}\n\nexport async function fetchStickers(\n { stickerSetShortName, stickerSetId, accessHash }:\n { stickerSetShortName?: string; stickerSetId?: string; accessHash: string },\n) {\n const result = await invokeRequest(new GramJs.messages.GetStickerSet({\n stickerset: stickerSetId\n ? buildInputStickerSet(stickerSetId, accessHash)\n : buildInputStickerSetShortName(stickerSetShortName!),\n }));\n\n if (!result) {\n return undefined;\n }\n\n return {\n set: buildStickerSet(result.set),\n stickers: processStickerResult(result.documents),\n packs: processStickerPackResult(result.packs),\n };\n}\n\nexport async function fetchAnimatedEmojis() {\n const result = await invokeRequest(new GramJs.messages.GetStickerSet({\n stickerset: new GramJs.InputStickerSetAnimatedEmoji(),\n }));\n\n if (!result) {\n return undefined;\n }\n\n return {\n set: buildStickerSet(result.set),\n stickers: processStickerResult(result.documents),\n };\n}\n\nexport async function searchStickers({ query, hash = '0' }: { query: string; hash?: string }) {\n const result = await invokeRequest(new GramJs.messages.SearchStickerSets({\n q: query,\n hash: BigInt(hash),\n }));\n\n if (!result || result instanceof GramJs.messages.FoundStickerSetsNotModified) {\n return undefined;\n }\n\n return {\n hash: String(result.hash),\n sets: result.sets.map(buildStickerSetCovered),\n };\n}\n\nexport async function fetchSavedGifs({ hash = '0' }: { hash?: string }) {\n const result = await invokeRequest(new GramJs.messages.GetSavedGifs({ hash: BigInt(hash) }));\n\n if (!result || result instanceof GramJs.messages.SavedGifsNotModified) {\n return undefined;\n }\n\n return {\n hash: String(result.hash),\n gifs: processGifResult(result.gifs),\n };\n}\n\nexport async function installStickerSet({ stickerSetId, accessHash }: { stickerSetId: string; accessHash: string }) {\n const result = await invokeRequest(new GramJs.messages.InstallStickerSet({\n stickerset: buildInputStickerSet(stickerSetId, accessHash),\n }));\n\n if (result) {\n onUpdate({\n '@type': 'updateStickerSet',\n id: stickerSetId,\n stickerSet: { installedDate: Date.now() },\n });\n }\n}\n\nexport async function uninstallStickerSet({ stickerSetId, accessHash }: { stickerSetId: string; accessHash: string }) {\n const result = await invokeRequest(new GramJs.messages.UninstallStickerSet({\n stickerset: buildInputStickerSet(stickerSetId, accessHash),\n }));\n\n if (result) {\n onUpdate({\n '@type': 'updateStickerSet',\n id: stickerSetId,\n stickerSet: { installedDate: undefined },\n });\n }\n}\n\nlet inputGifBot: GramJs.InputUser | undefined;\n\nexport async function searchGifs({ query, offset = '' }: { query: string; offset?: string }) {\n if (!inputGifBot) {\n const config = await invokeRequest(new GramJs.help.GetConfig());\n if (!config) {\n return undefined;\n }\n\n const resolvedPeer = await invokeRequest(new GramJs.contacts.ResolveUsername({\n username: config.gifSearchUsername,\n }));\n if (!resolvedPeer || !(resolvedPeer.users[0] instanceof GramJs.User)) {\n return undefined;\n }\n\n inputGifBot = new GramJs.InputUser({\n userId: (resolvedPeer.peer as GramJs.PeerUser).userId,\n accessHash: resolvedPeer.users[0].accessHash!,\n });\n }\n\n const result = await invokeRequest(new GramJs.messages.GetInlineBotResults({\n bot: inputGifBot,\n peer: new GramJs.InputPeerEmpty(),\n query,\n offset,\n }));\n if (!result) {\n return undefined;\n }\n\n const documents = result.results\n .map((foundGif) => {\n if (foundGif instanceof GramJs.BotInlineMediaResult) {\n return foundGif.document;\n }\n\n return undefined;\n })\n .filter(Boolean as any);\n\n return {\n nextOffset: result.nextOffset,\n gifs: processGifResult(documents),\n };\n}\n\nexport async function fetchStickersForEmoji({\n emoji, hash = '0',\n}: { emoji: string; hash?: string }) {\n const result = await invokeRequest(new GramJs.messages.GetStickers({\n emoticon: emoji,\n hash: BigInt(hash),\n }));\n\n if (!result || result instanceof GramJs.messages.StickersNotModified) {\n return undefined;\n }\n\n return {\n stickers: processStickerResult(result.stickers),\n hash: String(result.hash),\n };\n}\n\nexport async function fetchEmojiKeywords({ language, fromVersion }: {\n language: string;\n fromVersion?: number;\n}) {\n const result = await invokeRequest(new GramJs.messages.GetEmojiKeywordsDifference({\n langCode: language,\n fromVersion,\n }));\n\n if (!result) {\n return undefined;\n }\n\n return {\n language: result.langCode,\n version: result.version,\n keywords: result.keywords.reduce((acc, emojiKeyword) => {\n acc[emojiKeyword.keyword] = emojiKeyword.emoticons;\n\n return acc;\n }, {} as Record),\n };\n}\n\nfunction processStickerResult(stickers: GramJs.TypeDocument[]) {\n return stickers\n .map((document) => {\n if (document instanceof GramJs.Document) {\n const sticker = buildStickerFromDocument(document);\n if (sticker) {\n localDb.documents[String(document.id)] = document;\n\n return sticker;\n }\n }\n\n return undefined;\n })\n .filter(Boolean as any);\n}\n\nfunction processStickerPackResult(packs: GramJs.StickerPack[]) {\n return packs.reduce((acc, { emoticon, documents }) => {\n acc[emoticon] = documents.map((documentId) => buildStickerFromDocument(\n localDb.documents[String(documentId)],\n )).filter(Boolean as any);\n return acc;\n }, {} as Record);\n}\n\nfunction processGifResult(gifs: GramJs.TypeDocument[]) {\n return gifs\n .map((document) => {\n if (document instanceof GramJs.Document) {\n const gif = buildVideoFromDocument(document);\n if (gif) {\n localDb.documents[String(document.id)] = document;\n\n return gif;\n }\n }\n\n return undefined;\n })\n .filter(Boolean as any);\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\n\nimport { invokeRequest } from './client';\nimport { buildInputEntity, buildInputPeer } from '../gramjsBuilders';\nimport { ApiChat, OnApiUpdate } from '../../types';\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function checkChatUsername(\n { username }: { username: string },\n) {\n try {\n const result = await invokeRequest(new GramJs.channels.CheckUsername({\n channel: new GramJs.InputChannelEmpty(),\n username,\n }), undefined, true);\n\n return result!;\n } catch (err) {\n return false;\n }\n}\n\nexport async function setChatUsername(\n { chat, username }: { chat: ApiChat; username: string },\n) {\n const result = await invokeRequest(new GramJs.channels.UpdateUsername({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n username,\n }));\n\n if (result) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat: { username },\n });\n }\n}\n\nexport async function updatePrivateLink(\n { chat }: { chat: ApiChat },\n) {\n const result = await invokeRequest(new GramJs.messages.ExportChatInvite({\n peer: buildInputPeer(chat.id, chat.accessHash),\n }));\n\n if (!result || !(result instanceof GramJs.ChatInviteExported)) {\n return;\n }\n\n onUpdate({\n '@type': 'updateChatFullInfo',\n id: chat.id,\n fullInfo: {\n inviteLink: result.link,\n },\n });\n}\n","import { Api as GramJs, errors } from '../../../lib/gramjs';\n\nimport { OnApiUpdate } from '../../types';\n\nimport { DEBUG } from '../../../config';\nimport { invokeRequest, updateTwoFaSettings } from './client';\n\nconst ApiErrors: { [k: string]: string } = {\n EMAIL_UNCONFIRMED: 'Email unconfirmed',\n EMAIL_HASH_EXPIRED: 'Email hash expired',\n NEW_SALT_INVALID: 'The new salt is invalid',\n NEW_SETTINGS_INVALID: 'The new password settings are invalid',\n CODE_INVALID: 'Invalid Code',\n PASSWORD_HASH_INVALID: 'Invalid Password',\n};\n\nconst emailCodeController: {\n resolve?: Function;\n reject?: Function;\n} = {};\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function getPasswordInfo() {\n const result = await invokeRequest(new GramJs.account.GetPassword());\n if (!result) {\n return undefined;\n }\n\n const { hint, hasPassword } = result;\n\n return { hint, hasPassword };\n}\n\nfunction onRequestEmailCode(length: number) {\n onUpdate({\n '@type': 'updateTwoFaStateWaitCode',\n length,\n });\n\n return new Promise((resolve, reject) => {\n emailCodeController.resolve = resolve;\n emailCodeController.reject = reject;\n });\n}\n\nexport async function checkPassword(currentPassword: string) {\n try {\n await updateTwoFaSettings({ isCheckPassword: true, currentPassword });\n\n return true;\n } catch (err) {\n onError(err);\n\n return false;\n }\n}\n\nexport async function clearPassword(currentPassword: string) {\n try {\n await updateTwoFaSettings({ currentPassword });\n\n return true;\n } catch (err) {\n onError(err);\n\n return false;\n }\n}\n\nexport async function updatePassword(currentPassword: string, password: string, hint?: string, email?: string) {\n try {\n await updateTwoFaSettings({\n currentPassword,\n newPassword: password,\n hint,\n email,\n emailCodeCallback: onRequestEmailCode,\n onEmailCodeError: onError,\n });\n\n return true;\n } catch (err) {\n onError(err);\n\n return false;\n }\n}\n\nexport async function updateRecoveryEmail(currentPassword: string, email: string) {\n try {\n await updateTwoFaSettings({\n currentPassword,\n newPassword: currentPassword,\n email,\n emailCodeCallback: onRequestEmailCode,\n onEmailCodeError: onError,\n });\n\n return true;\n } catch (err) {\n onError(err);\n\n return false;\n }\n}\n\nexport function provideRecoveryEmailCode(code: string) {\n emailCodeController.resolve!(code);\n}\n\nfunction onError(err: Error) {\n let message: string;\n\n if (err instanceof errors.FloodWaitError) {\n const hours = Math.ceil(Number(err.seconds) / 60 / 60);\n message = `Too many attempts. Try again in ${hours > 1 ? `${hours} hours` : 'an hour'}`;\n } else {\n message = ApiErrors[err.message];\n }\n\n if (!message) {\n message = 'Unexpected Error';\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n }\n\n onUpdate({\n '@type': 'updateTwoFaError',\n message,\n });\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\n\nimport {\n ApiChat, ApiLangString, ApiLanguage, ApiNotifyException, ApiUser, ApiWallpaper,\n} from '../../types';\nimport { ApiPrivacyKey, InputPrivacyRules, LangCode } from '../../../types';\n\nimport { BLOCKED_LIST_LIMIT, DEFAULT_LANG_PACK, LANG_PACKS } from '../../../config';\nimport {\n buildApiWallpaper, buildApiSession, buildPrivacyRules, buildApiNotifyException, buildApiCountryList,\n} from '../apiBuilders/misc';\n\nimport { buildApiUser } from '../apiBuilders/users';\nimport { buildApiChatFromPreview } from '../apiBuilders/chats';\nimport { buildInputPrivacyKey, buildInputPeer, buildInputEntity } from '../gramjsBuilders';\nimport { invokeRequest, uploadFile, getClient } from './client';\nimport { omitVirtualClassFields } from '../apiBuilders/helpers';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport { getServerTime } from '../../../util/serverTime';\nimport { buildApiPeerId, getApiChatIdFromMtpPeer } from '../apiBuilders/peers';\nimport localDb from '../localDb';\n\nconst MAX_INT_32 = 2 ** 31 - 1;\nconst BETA_LANG_CODES = ['ar', 'fa', 'id', 'ko', 'uz'];\n\nexport function updateProfile({\n firstName,\n lastName,\n about,\n}: {\n firstName?: string;\n lastName?: string;\n about?: string;\n}) {\n return invokeRequest(new GramJs.account.UpdateProfile({\n firstName: firstName || '',\n lastName: lastName || '',\n about: about || '',\n }));\n}\n\nexport function checkUsername(username: string) {\n return invokeRequest(new GramJs.account.CheckUsername({ username }));\n}\n\nexport function updateUsername(username: string) {\n return invokeRequest(new GramJs.account.UpdateUsername({ username }));\n}\n\nexport async function updateProfilePhoto(file: File) {\n const inputFile = await uploadFile(file);\n return invokeRequest(new GramJs.photos.UploadProfilePhoto({\n file: inputFile,\n }));\n}\n\nexport async function uploadProfilePhoto(file: File) {\n const inputFile = await uploadFile(file);\n await invokeRequest(new GramJs.photos.UploadProfilePhoto({\n file: inputFile,\n }));\n}\n\nexport async function fetchWallpapers() {\n const result = await invokeRequest(new GramJs.account.GetWallPapers({ hash: BigInt('0') }));\n\n if (!result || result instanceof GramJs.account.WallPapersNotModified) {\n return undefined;\n }\n\n const filteredWallpapers = result.wallpapers.filter((wallpaper) => {\n if (\n !(wallpaper instanceof GramJs.WallPaper)\n || !(wallpaper.document instanceof GramJs.Document)\n ) {\n return false;\n }\n\n return !wallpaper.pattern && wallpaper.document.mimeType !== 'application/x-tgwallpattern';\n }) as GramJs.WallPaper[];\n\n filteredWallpapers.forEach((wallpaper) => {\n localDb.documents[String(wallpaper.document.id)] = wallpaper.document as GramJs.Document;\n });\n\n return {\n wallpapers: filteredWallpapers.map(buildApiWallpaper).filter(Boolean as any),\n };\n}\n\nexport async function uploadWallpaper(file: File) {\n const inputFile = await uploadFile(file);\n\n const result = await invokeRequest(new GramJs.account.UploadWallPaper({\n file: inputFile,\n mimeType: file.type,\n settings: new GramJs.WallPaperSettings(),\n }));\n\n if (!result || !(result instanceof GramJs.WallPaper)) {\n return undefined;\n }\n\n const wallpaper = buildApiWallpaper(result);\n if (!wallpaper) {\n return undefined;\n }\n\n localDb.documents[String(result.document.id)] = result.document as GramJs.Document;\n\n return { wallpaper };\n}\n\nexport async function fetchBlockedContacts() {\n const result = await invokeRequest(new GramJs.contacts.GetBlocked({\n limit: BLOCKED_LIST_LIMIT,\n }));\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return {\n users: result.users.map(buildApiUser).filter(Boolean as any),\n chats: result.chats.map((chat) => buildApiChatFromPreview(chat, undefined, true)).filter(Boolean as any),\n blockedIds: result.blocked.map((blocked) => getApiChatIdFromMtpPeer(blocked.peerId)),\n totalCount: result instanceof GramJs.contacts.BlockedSlice ? result.count : result.blocked.length,\n };\n}\n\nexport function blockContact(chatOrUserId: string, accessHash?: string) {\n return invokeRequest(new GramJs.contacts.Block({\n id: buildInputPeer(chatOrUserId, accessHash),\n }));\n}\n\nexport function unblockContact(chatOrUserId: string, accessHash?: string) {\n return invokeRequest(new GramJs.contacts.Unblock({\n id: buildInputPeer(chatOrUserId, accessHash),\n }));\n}\n\nexport async function fetchAuthorizations() {\n const result = await invokeRequest(new GramJs.account.GetAuthorizations());\n if (!result) {\n return undefined;\n }\n\n return result.authorizations.map(buildApiSession);\n}\n\nexport function terminateAuthorization(hash: string) {\n return invokeRequest(new GramJs.account.ResetAuthorization({ hash: BigInt(hash) }));\n}\n\nexport function terminateAllAuthorizations() {\n return invokeRequest(new GramJs.auth.ResetAuthorizations());\n}\n\nexport async function fetchNotificationExceptions({\n serverTimeOffset,\n}: { serverTimeOffset: number }) {\n const result = await invokeRequest(new GramJs.account.GetNotifyExceptions({ compareSound: true }));\n\n if (!(result instanceof GramJs.Updates || result instanceof GramJs.UpdatesCombined)) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return result.updates.reduce((acc, update) => {\n if (!(update instanceof GramJs.UpdateNotifySettings && update.peer instanceof GramJs.NotifyPeer)) {\n return acc;\n }\n\n acc.push(buildApiNotifyException(update.notifySettings, update.peer.peer, serverTimeOffset));\n\n return acc;\n }, [] as ApiNotifyException[]);\n}\n\nexport async function fetchNotificationSettings({\n serverTimeOffset,\n}: { serverTimeOffset: number }) {\n const [\n isMutedContactSignUpNotification,\n privateContactNotificationsSettings,\n groupNotificationsSettings,\n broadcastNotificationsSettings,\n ] = await Promise.all([\n invokeRequest(new GramJs.account.GetContactSignUpNotification()),\n invokeRequest(new GramJs.account.GetNotifySettings({\n peer: new GramJs.InputNotifyUsers(),\n })),\n invokeRequest(new GramJs.account.GetNotifySettings({\n peer: new GramJs.InputNotifyChats(),\n })),\n invokeRequest(new GramJs.account.GetNotifySettings({\n peer: new GramJs.InputNotifyBroadcasts(),\n })),\n ]);\n\n if (!privateContactNotificationsSettings || !groupNotificationsSettings || !broadcastNotificationsSettings) {\n return false;\n }\n\n const {\n silent: privateSilent, muteUntil: privateMuteUntil, showPreviews: privateShowPreviews,\n } = privateContactNotificationsSettings;\n const {\n silent: groupSilent, muteUntil: groupMuteUntil, showPreviews: groupShowPreviews,\n } = groupNotificationsSettings;\n const {\n silent: broadcastSilent, muteUntil: broadcastMuteUntil, showPreviews: broadcastShowPreviews,\n } = broadcastNotificationsSettings;\n\n return {\n hasContactJoinedNotifications: !isMutedContactSignUpNotification,\n hasPrivateChatsNotifications: !(\n privateSilent\n || (typeof privateMuteUntil === 'number' && getServerTime(serverTimeOffset) < privateMuteUntil)\n ),\n hasPrivateChatsMessagePreview: privateShowPreviews,\n hasGroupNotifications: !(\n groupSilent || (typeof groupMuteUntil === 'number'\n && getServerTime(serverTimeOffset) < groupMuteUntil)\n ),\n hasGroupMessagePreview: groupShowPreviews,\n hasBroadcastNotifications: !(\n broadcastSilent || (typeof broadcastMuteUntil === 'number'\n && getServerTime(serverTimeOffset) < broadcastMuteUntil)\n ),\n hasBroadcastMessagePreview: broadcastShowPreviews,\n };\n}\n\nexport function updateContactSignUpNotification(isSilent: boolean) {\n return invokeRequest(new GramJs.account.SetContactSignUpNotification({ silent: isSilent }));\n}\n\nexport function updateNotificationSettings(peerType: 'contact' | 'group' | 'broadcast', {\n isSilent,\n shouldShowPreviews,\n}: {\n isSilent: boolean;\n shouldShowPreviews: boolean;\n}) {\n let peer: GramJs.TypeInputNotifyPeer;\n if (peerType === 'contact') {\n peer = new GramJs.InputNotifyUsers();\n } else if (peerType === 'group') {\n peer = new GramJs.InputNotifyChats();\n } else {\n peer = new GramJs.InputNotifyBroadcasts();\n }\n\n const settings = {\n showPreviews: shouldShowPreviews,\n silent: isSilent,\n muteUntil: isSilent ? MAX_INT_32 : 0,\n };\n\n return invokeRequest(new GramJs.account.UpdateNotifySettings({\n peer,\n settings: new GramJs.InputPeerNotifySettings(settings),\n }));\n}\n\nexport async function fetchLanguages(): Promise {\n const result = await invokeRequest(new GramJs.langpack.GetLanguages({\n langPack: DEFAULT_LANG_PACK,\n }));\n if (!result) {\n return undefined;\n }\n\n return result.map(omitVirtualClassFields);\n}\n\nexport async function fetchLangPack({ sourceLangPacks, langCode }: {\n sourceLangPacks: typeof LANG_PACKS;\n langCode: string;\n}) {\n const results = await Promise.all(sourceLangPacks.map((langPack) => {\n return invokeRequest(new GramJs.langpack.GetLangPack({\n langPack,\n langCode: BETA_LANG_CODES.includes(langCode) ? `${langCode}-raw` : langCode,\n }));\n }));\n\n const collections = results\n .filter(Boolean as any)\n .map((result) => {\n return buildCollectionByKey(result.strings.map(omitVirtualClassFields), 'key');\n });\n\n if (!collections.length) {\n return undefined;\n }\n\n return { langPack: Object.assign({}, ...collections.reverse()) };\n}\n\nexport async function fetchLangStrings({ langPack, langCode, keys }: {\n langPack: string; langCode: string; keys: string[];\n}) {\n const result = await invokeRequest(new GramJs.langpack.GetStrings({\n langPack,\n langCode: BETA_LANG_CODES.includes(langCode) ? `${langCode}-raw` : langCode,\n keys,\n }));\n\n if (!result) {\n return undefined;\n }\n\n return result.map(omitVirtualClassFields);\n}\n\nexport async function fetchPrivacySettings(privacyKey: ApiPrivacyKey) {\n const key = buildInputPrivacyKey(privacyKey);\n const result = await invokeRequest(new GramJs.account.GetPrivacy({ key }));\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return buildPrivacyRules(result.rules);\n}\n\nexport function registerDevice(token: string) {\n const client = getClient();\n const secret = client.session.getAuthKey().getKey();\n return invokeRequest(new GramJs.account.RegisterDevice({\n tokenType: 10,\n secret,\n appSandbox: false,\n otherUids: [],\n token,\n }));\n}\n\nexport function unregisterDevice(token: string) {\n return invokeRequest(new GramJs.account.UnregisterDevice({\n tokenType: 10,\n otherUids: [],\n token,\n }));\n}\n\nexport async function setPrivacySettings(\n privacyKey: ApiPrivacyKey, rules: InputPrivacyRules,\n) {\n const key = buildInputPrivacyKey(privacyKey);\n const privacyRules: GramJs.TypeInputPrivacyRule[] = [];\n\n if (rules.allowedUsers) {\n privacyRules.push(new GramJs.InputPrivacyValueAllowUsers({\n users: rules.allowedUsers.map(({ id, accessHash }) => buildInputEntity(id, accessHash) as GramJs.InputUser),\n }));\n }\n if (rules.allowedChats) {\n privacyRules.push(new GramJs.InputPrivacyValueAllowChatParticipants({\n chats: rules.allowedChats.map(({ id }) => buildInputEntity(id) as BigInt.BigInteger),\n }));\n }\n if (rules.blockedUsers) {\n privacyRules.push(new GramJs.InputPrivacyValueDisallowUsers({\n users: rules.blockedUsers.map(({ id, accessHash }) => buildInputEntity(id, accessHash) as GramJs.InputUser),\n }));\n }\n if (rules.blockedChats) {\n privacyRules.push(new GramJs.InputPrivacyValueDisallowChatParticipants({\n chats: rules.blockedChats.map(({ id }) => buildInputEntity(id) as BigInt.BigInteger),\n }));\n }\n switch (rules.visibility) {\n case 'everybody':\n privacyRules.push(new GramJs.InputPrivacyValueAllowAll());\n break;\n\n case 'contacts':\n privacyRules.push(new GramJs.InputPrivacyValueAllowContacts());\n break;\n\n case 'nonContacts':\n privacyRules.push(new GramJs.InputPrivacyValueDisallowContacts());\n break;\n\n case 'nobody':\n privacyRules.push(new GramJs.InputPrivacyValueDisallowAll());\n break;\n }\n\n const result = await invokeRequest(new GramJs.account.SetPrivacy({ key, rules: privacyRules }));\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return buildPrivacyRules(result.rules);\n}\n\nexport async function updateIsOnline(isOnline: boolean) {\n await invokeRequest(new GramJs.account.UpdateStatus({ offline: !isOnline }));\n}\n\nexport async function fetchContentSettings() {\n const result = await invokeRequest(new GramJs.account.GetContentSettings());\n if (!result) {\n return undefined;\n }\n\n return {\n isSensitiveEnabled: Boolean(result.sensitiveEnabled),\n canChangeSensitive: Boolean(result.sensitiveCanChange),\n };\n}\n\nexport function updateContentSettings(isEnabled: boolean) {\n return invokeRequest(new GramJs.account.SetContentSettings({\n sensitiveEnabled: isEnabled || undefined,\n }));\n}\n\nfunction updateLocalDb(\n result: (\n GramJs.account.PrivacyRules | GramJs.contacts.Blocked | GramJs.contacts.BlockedSlice |\n GramJs.Updates | GramJs.UpdatesCombined\n ),\n) {\n result.users.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[buildApiPeerId(user.id, 'user')] = user;\n }\n });\n\n result.chats.forEach((chat) => {\n if (chat instanceof GramJs.Chat || chat instanceof GramJs.Channel) {\n localDb.chats[buildApiPeerId(chat.id, chat instanceof GramJs.Chat ? 'chat' : 'channel')] = chat;\n }\n });\n}\n\nexport async function fetchCountryList({ langCode = 'en' }: { langCode?: LangCode }) {\n const countryList = await invokeRequest(new GramJs.help.GetCountriesList({\n langCode,\n }));\n\n if (!(countryList instanceof GramJs.help.CountriesList)) {\n return undefined;\n }\n return buildApiCountryList(countryList.countries);\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n ApiBotInlineMediaResult, ApiBotInlineResult, ApiBotInlineSwitchPm, ApiInlineResultType, ApiWebDocument,\n} from '../../types';\n\nimport { pick } from '../../../util/iteratees';\nimport { buildApiPhoto, buildApiThumbnailFromStripped } from './common';\nimport { buildVideoFromDocument } from './messages';\nimport { buildStickerFromDocument } from './symbols';\n\nexport function buildApiBotInlineResult(result: GramJs.BotInlineResult, queryId: string): ApiBotInlineResult {\n const {\n id, type, title, description, url, thumb,\n } = result;\n\n return {\n id,\n queryId,\n type: type as ApiInlineResultType,\n title,\n description,\n url,\n webThumbnail: buildApiWebDocument(thumb),\n };\n}\n\nexport function buildApiBotInlineMediaResult(\n result: GramJs.BotInlineMediaResult, queryId: string,\n): ApiBotInlineMediaResult {\n const {\n id, type, title, description, photo, document,\n } = result;\n\n return {\n id,\n queryId,\n type: type as ApiInlineResultType,\n title,\n description,\n ...(type === 'sticker' && document instanceof GramJs.Document && { sticker: buildStickerFromDocument(document) }),\n ...(photo instanceof GramJs.Photo && { photo: buildApiPhoto(photo) }),\n ...(type === 'gif' && document instanceof GramJs.Document && { gif: buildVideoFromDocument(document) }),\n ...(type === 'video' && document instanceof GramJs.Document && {\n thumbnail: buildApiThumbnailFromStripped(document.thumbs),\n }),\n };\n}\n\nexport function buildBotSwitchPm(switchPm?: GramJs.InlineBotSwitchPM) {\n return switchPm ? pick(switchPm, ['text', 'startParam']) as ApiBotInlineSwitchPm : undefined;\n}\n\nfunction buildApiWebDocument(document?: GramJs.TypeWebDocument): ApiWebDocument | undefined {\n return document ? pick(document, ['url', 'mimeType']) : undefined;\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\n\nimport { ApiChat, ApiUser } from '../../types';\n\nimport localDb from '../localDb';\nimport { invokeRequest } from './client';\nimport { buildInputPeer, generateRandomBigInt } from '../gramjsBuilders';\nimport { buildApiUser } from '../apiBuilders/users';\nimport { buildApiBotInlineMediaResult, buildApiBotInlineResult, buildBotSwitchPm } from '../apiBuilders/bots';\nimport { buildApiChatFromPreview } from '../apiBuilders/chats';\nimport { buildApiPeerId } from '../apiBuilders/peers';\n\nexport function init() {\n}\n\nexport function answerCallbackButton(\n {\n chatId, accessHash, messageId, data,\n }: {\n chatId: string; accessHash?: string; messageId: number; data: string;\n },\n) {\n return invokeRequest(new GramJs.messages.GetBotCallbackAnswer({\n peer: buildInputPeer(chatId, accessHash),\n msgId: messageId,\n data: Buffer.from(data),\n }));\n}\n\nexport async function fetchTopInlineBots() {\n const topPeers = await invokeRequest(new GramJs.contacts.GetTopPeers({\n botsInline: true,\n }));\n\n if (!(topPeers instanceof GramJs.contacts.TopPeers)) {\n return undefined;\n }\n\n const users = topPeers.users.map(buildApiUser).filter(Boolean as any);\n const ids = users.map(({ id }) => id);\n\n return {\n ids,\n users,\n };\n}\n\nexport async function fetchInlineBot({ username }: { username: string }) {\n const resolvedPeer = await invokeRequest(new GramJs.contacts.ResolveUsername({ username }));\n\n if (\n !resolvedPeer\n || !(\n resolvedPeer.users[0] instanceof GramJs.User\n && resolvedPeer.users[0].bot\n && resolvedPeer.users[0].botInlinePlaceholder\n )\n ) {\n return undefined;\n }\n\n addUserToLocalDb(resolvedPeer.users[0]);\n\n return {\n user: buildApiUser(resolvedPeer.users[0]),\n chat: buildApiChatFromPreview(resolvedPeer.users[0]),\n };\n}\n\nexport async function fetchInlineBotResults({\n bot, chat, query, offset = '',\n}: {\n bot: ApiUser; chat: ApiChat; query: string; offset?: string;\n}) {\n const result = await invokeRequest(new GramJs.messages.GetInlineBotResults({\n bot: buildInputPeer(bot.id, bot.accessHash),\n peer: buildInputPeer(chat.id, chat.accessHash),\n query,\n offset,\n }));\n\n if (!result) {\n return undefined;\n }\n\n result.users.map(addUserToLocalDb);\n\n return {\n isGallery: Boolean(result.gallery),\n help: bot.botPlaceholder,\n nextOffset: getInlineBotResultsNextOffset(bot.username, result.nextOffset),\n switchPm: buildBotSwitchPm(result.switchPm),\n users: result.users.map(buildApiUser).filter(Boolean as any),\n results: processInlineBotResult(String(result.queryId), result.results),\n };\n}\n\nexport async function sendInlineBotResult({\n chat, resultId, queryId, replyingTo,\n}: {\n chat: ApiChat;\n resultId: string;\n queryId: string;\n replyingTo?: number;\n}) {\n const randomId = generateRandomBigInt();\n\n await invokeRequest(new GramJs.messages.SendInlineBotResult({\n clearDraft: true,\n randomId,\n queryId: BigInt(queryId),\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: resultId,\n ...(replyingTo && { replyToMsgId: replyingTo }),\n }), true);\n}\n\nexport async function startBot({\n bot, startParam,\n}: {\n bot: ApiUser;\n startParam?: string;\n}) {\n const randomId = generateRandomBigInt();\n\n await invokeRequest(new GramJs.messages.StartBot({\n bot: buildInputPeer(bot.id, bot.accessHash),\n peer: buildInputPeer(bot.id, bot.accessHash),\n randomId,\n startParam,\n }), true);\n}\n\nfunction processInlineBotResult(queryId: string, results: GramJs.TypeBotInlineResult[]) {\n return results.map((result) => {\n if (result instanceof GramJs.BotInlineMediaResult) {\n if (result.document instanceof GramJs.Document) {\n addDocumentToLocalDb(result.document);\n }\n\n if (result.photo instanceof GramJs.Photo) {\n addPhotoToLocalDb(result.photo);\n }\n\n return buildApiBotInlineMediaResult(result, queryId);\n }\n\n if (result.thumb) {\n addWebDocumentToLocalDb(result.thumb);\n }\n\n return buildApiBotInlineResult(result, queryId);\n });\n}\n\nfunction getInlineBotResultsNextOffset(username: string, nextOffset?: string) {\n return username === 'gif' && nextOffset === '0' ? '' : nextOffset;\n}\n\nfunction addUserToLocalDb(user: GramJs.User) {\n localDb.users[buildApiPeerId(user.id, 'user')] = user;\n}\n\nfunction addDocumentToLocalDb(document: GramJs.Document) {\n localDb.documents[String(document.id)] = document;\n}\n\nfunction addPhotoToLocalDb(photo: GramJs.Photo) {\n localDb.photos[String(photo.id)] = photo;\n}\n\nfunction addWebDocumentToLocalDb(webDocument: GramJs.TypeWebDocument) {\n localDb.webDocuments[webDocument.url] = webDocument;\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\n\nexport function buildShippingOptions(shippingOptions: GramJs.ShippingOption[] | undefined) {\n if (!shippingOptions) {\n return undefined;\n }\n return Object.values(shippingOptions).map((option) => {\n return {\n id: option.id,\n title: option.title,\n amount: option.prices.reduce((ac, cur) => ac + Number((cur.amount as any).value), 0),\n prices: option.prices.map(({ label, amount }) => {\n return {\n label,\n amount: Number((amount as any).value),\n };\n }),\n };\n });\n}\n\nexport function buildReceipt(receipt: GramJs.payments.PaymentReceipt) {\n const {\n invoice,\n info,\n shipping,\n currency,\n totalAmount,\n credentialsTitle,\n } = receipt;\n\n const { shippingAddress, phone, name } = (info || {});\n\n const { prices } = invoice;\n const mapedPrices = prices.map(({ label, amount }) => ({\n label,\n amount: Number((amount as any).value),\n }));\n\n let shippingPrices;\n let shippingMethod;\n\n if (shipping) {\n shippingPrices = shipping.prices.map(({ label, amount }) => {\n return {\n label,\n amount: Number((amount as any).value),\n };\n });\n shippingMethod = shipping.title;\n }\n\n return {\n currency,\n prices: mapedPrices,\n info: { shippingAddress, phone, name },\n totalAmount: Number((totalAmount as any).value),\n credentialsTitle,\n shippingPrices,\n shippingMethod,\n };\n}\n\nexport function buildPaymentForm(form: GramJs.payments.PaymentForm) {\n const {\n formId,\n canSaveCredentials,\n passwordMissing,\n providerId,\n nativeProvider,\n nativeParams,\n savedInfo,\n invoice,\n } = form;\n\n const {\n test,\n nameRequested,\n phoneRequested,\n emailRequested,\n shippingAddressRequested,\n flexible,\n phoneToProvider,\n emailToProvider,\n currency,\n prices,\n } = invoice;\n\n const mapedPrices = prices.map(({ label, amount }) => ({\n label,\n amount: Number((amount as any).value),\n }));\n\n const nativeData = nativeParams ? JSON.parse(nativeParams.data) : {};\n return {\n canSaveCredentials,\n passwordMissing,\n formId: String(formId),\n providerId: String(providerId),\n nativeProvider,\n savedInfo,\n invoice: {\n test,\n nameRequested,\n phoneRequested,\n emailRequested,\n shippingAddressRequested,\n flexible,\n phoneToProvider,\n emailToProvider,\n currency,\n prices: mapedPrices,\n },\n nativeParams: {\n needCardholderName: nativeData.need_cardholder_name,\n needCountry: nativeData.need_country,\n needZip: nativeData.need_zip,\n publishableKey: nativeData.publishable_key,\n },\n };\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport { invokeRequest } from './client';\nimport { buildInputPeer, buildShippingInfo } from '../gramjsBuilders';\nimport { buildShippingOptions, buildPaymentForm, buildReceipt } from '../apiBuilders/payments';\nimport { ApiChat } from '../../types';\n\nexport async function validateRequestedInfo({\n chat,\n messageId,\n requestInfo,\n shouldSave,\n}: {\n chat: ApiChat;\n messageId: number;\n requestInfo: GramJs.TypePaymentRequestedInfo;\n shouldSave?: boolean;\n}): Promise<{\n id: string;\n shippingOptions: any;\n } | undefined> {\n const result = await invokeRequest(new GramJs.payments.ValidateRequestedInfo({\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: messageId,\n save: shouldSave || undefined,\n info: buildShippingInfo(requestInfo),\n }));\n if (!result) {\n return undefined;\n }\n\n const { id, shippingOptions } = result;\n if (!id) {\n return undefined;\n }\n\n return {\n id,\n shippingOptions: buildShippingOptions(shippingOptions),\n };\n}\n\nexport function sendPaymentForm({\n chat,\n messageId,\n formId,\n requestedInfoId,\n shippingOptionId,\n credentials,\n}: {\n chat: ApiChat;\n messageId: number;\n formId: string;\n credentials: any;\n requestedInfoId?: string;\n shippingOptionId?: string;\n}) {\n return invokeRequest(new GramJs.payments.SendPaymentForm({\n formId: BigInt(formId),\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: messageId,\n requestedInfoId,\n shippingOptionId,\n credentials: new GramJs.InputPaymentCredentials({\n save: credentials.save,\n data: new GramJs.DataJSON({ data: JSON.stringify(credentials.data) }),\n }),\n }), true);\n}\n\nexport async function getPaymentForm({\n chat, messageId,\n}: {\n chat: ApiChat;\n messageId: number;\n}) {\n const result = await invokeRequest(new GramJs.payments.GetPaymentForm({\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: messageId,\n }));\n\n if (!result) {\n return undefined;\n }\n\n return buildPaymentForm(result);\n}\n\nexport async function getReceipt(chat: ApiChat, msgId: number) {\n const result = await invokeRequest(new GramJs.payments.GetPaymentReceipt({\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId,\n }));\n if (!result) {\n return undefined;\n }\n\n return buildReceipt(result);\n}\n","import {\n OnApiUpdate,\n ApiInitialArgs,\n ApiUpdate,\n ApiOnProgress,\n} from '../types';\nimport { Methods, MethodArgs, MethodResponse } from './methods/types';\n\nimport { API_THROTTLE_RESET_UPDATES, API_UPDATE_THROTTLE } from '../../config';\nimport { throttle, throttleWithTickEnd } from '../../util/schedulers';\nimport { init as initUpdater } from './updater';\nimport { init as initAuth } from './methods/auth';\nimport { init as initChats } from './methods/chats';\nimport { init as initMessages } from './methods/messages';\nimport { init as initUsers } from './methods/users';\nimport { init as initClient } from './methods/client';\nimport { init as initStickers } from './methods/symbols';\nimport { init as initManagement } from './methods/management';\nimport { init as initTwoFaSettings } from './methods/twoFaSettings';\nimport * as methods from './methods';\n\nlet onUpdate: OnApiUpdate;\n\nexport async function initApi(_onUpdate: OnApiUpdate, initialArgs: ApiInitialArgs) {\n onUpdate = _onUpdate;\n\n initUpdater(handleUpdate);\n initAuth(handleUpdate);\n initChats(handleUpdate);\n initMessages(handleUpdate);\n initUsers(handleUpdate);\n initStickers(handleUpdate);\n initManagement(handleUpdate);\n initTwoFaSettings(handleUpdate);\n\n await initClient(handleUpdate, initialArgs);\n}\n\nexport function callApi(fnName: T, ...args: MethodArgs): MethodResponse {\n // @ts-ignore\n return methods[fnName](...args) as MethodResponse;\n}\n\nexport function cancelApiProgress(progressCallback: ApiOnProgress) {\n progressCallback.isCanceled = true;\n}\n\nconst flushUpdatesOnTickEnd = throttleWithTickEnd(flushUpdates);\n\nlet flushUpdatesThrottled: typeof flushUpdatesOnTickEnd | undefined;\nlet currentThrottleId: number | undefined;\n\nlet pendingUpdates: ApiUpdate[] | undefined;\n\nfunction handleUpdate(update: ApiUpdate) {\n if (!pendingUpdates) {\n pendingUpdates = [update];\n } else {\n pendingUpdates.push(update);\n }\n\n if (!flushUpdatesThrottled || API_THROTTLE_RESET_UPDATES.has(update['@type'])) {\n flushUpdatesThrottled = throttle(flushUpdatesOnTickEnd, API_UPDATE_THROTTLE, true);\n currentThrottleId = Math.random();\n }\n\n flushUpdatesThrottled(currentThrottleId!);\n}\n\nfunction flushUpdates(throttleId: number) {\n if (!pendingUpdates || throttleId !== currentThrottleId) {\n return;\n }\n\n const currentUpdates = pendingUpdates!;\n pendingUpdates = undefined;\n currentUpdates.forEach(onUpdate);\n}\n","import { ApiOnProgress, ApiUpdate } from '../../types';\nimport { OriginMessageEvent, WorkerMessageData } from './types';\n\nimport { DEBUG } from '../../../config';\nimport { initApi, callApi, cancelApiProgress } from '../provider';\n\ndeclare const self: WorkerGlobalScope;\n\nhandleErrors();\n\n// TODO Re-use `util/createWorkerInterface.ts`\n\nconst callbackState = new Map();\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH LOAD WORKER');\n}\n\nonmessage = async (message: OriginMessageEvent) => {\n const { data } = message;\n\n switch (data.type) {\n case 'initApi': {\n await initApi(onUpdate, data.args[0]);\n break;\n }\n case 'callMethod': {\n const { messageId, name, args } = data;\n try {\n if (messageId) {\n const callback = (...callbackArgs: any[]) => {\n const lastArg = callbackArgs[callbackArgs.length - 1];\n\n sendToOrigin({\n type: 'methodCallback',\n messageId,\n callbackArgs,\n }, lastArg instanceof ArrayBuffer ? lastArg : undefined);\n };\n\n callbackState.set(messageId, callback);\n\n args.push(callback as never);\n }\n\n const response = await callApi(name, ...args);\n const { arrayBuffer } = (typeof response === 'object' && 'arrayBuffer' in response && response) || {};\n\n if (messageId) {\n sendToOrigin({\n type: 'methodResponse',\n messageId,\n response,\n }, arrayBuffer);\n }\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(error);\n }\n\n if (messageId) {\n sendToOrigin({\n type: 'methodResponse',\n messageId,\n error: { message: error.message },\n });\n }\n }\n\n if (messageId) {\n callbackState.delete(messageId);\n }\n\n break;\n }\n case 'cancelProgress': {\n const callback = callbackState.get(data.messageId);\n if (callback) {\n cancelApiProgress(callback);\n }\n\n break;\n }\n case 'ping': {\n sendToOrigin({\n type: 'methodResponse',\n messageId: data.messageId!,\n });\n\n break;\n }\n }\n};\n\nfunction handleErrors() {\n self.onerror = (e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n sendToOrigin({ type: 'unhandledError', error: { message: e.error.message || 'Uncaught exception in worker' } });\n };\n\n self.addEventListener('unhandledrejection', (e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n sendToOrigin({ type: 'unhandledError', error: { message: e.reason.message || 'Uncaught rejection in worker' } });\n });\n}\n\nfunction onUpdate(update: ApiUpdate) {\n sendToOrigin({\n type: 'update',\n update,\n });\n}\n\nfunction sendToOrigin(data: WorkerMessageData, arrayBuffer?: ArrayBuffer) {\n if (arrayBuffer) {\n postMessage(data, [arrayBuffer]);\n } else {\n postMessage(data);\n }\n}\n","const BigInt = require('big-integer');\nconst crypto = require('./crypto/crypto');\n\n/**\n * converts a buffer to big int\n * @param buffer\n * @param little\n * @param signed\n * @returns {bigInt.BigInteger}\n */\nfunction readBigIntFromBuffer(buffer, little = true, signed = false) {\n let randBuffer = Buffer.from(buffer);\n const bytesNumber = randBuffer.length;\n if (little) {\n randBuffer = randBuffer.reverse();\n }\n let bigInt = BigInt(randBuffer.toString('hex'), 16);\n if (signed && Math.floor(bigInt.toString('2').length / 8) >= bytesNumber) {\n bigInt = bigInt.subtract(BigInt(2)\n .pow(BigInt(bytesNumber * 8)));\n }\n return bigInt;\n}\n\n/**\n * Special case signed little ints\n * @param big\n * @param number\n * @returns {Buffer}\n */\nfunction toSignedLittleBuffer(big, number = 8) {\n const bigNumber = BigInt(big);\n const byteArray = [];\n for (let i = 0; i < number; i++) {\n byteArray[i] = bigNumber.shiftRight(8 * i)\n .and(255);\n }\n return Buffer.from(byteArray);\n}\n\n\n/**\n * converts a big int to a buffer\n * @param bigInt {bigInt.BigInteger}\n * @param bytesNumber\n * @param little\n * @param signed\n * @returns {Buffer}\n */\nfunction readBufferFromBigInt(bigInt, bytesNumber, little = true, signed = false) {\n bigInt = BigInt(bigInt);\n const bitLength = bigInt.bitLength();\n\n const bytes = Math.ceil(bitLength / 8);\n if (bytesNumber < bytes) {\n throw new Error('OverflowError: int too big to convert');\n }\n if (!signed && bigInt.lesser(BigInt(0))) {\n throw new Error('Cannot convert to unsigned');\n }\n let below = false;\n if (bigInt.lesser(BigInt(0))) {\n below = true;\n bigInt = bigInt.abs();\n }\n\n const hex = bigInt.toString('16')\n .padStart(bytesNumber * 2, '0');\n let l = Buffer.from(hex, 'hex');\n if (little) {\n l = l.reverse();\n }\n\n if (signed && below) {\n if (little) {\n let reminder = false;\n if (l[0] !== 0) {\n l[0] -= 1;\n }\n for (let i = 0; i < l.length; i++) {\n if (l[i] === 0) {\n reminder = true;\n continue;\n }\n if (reminder) {\n l[i] -= 1;\n reminder = false;\n }\n l[i] = 255 - l[i];\n }\n } else {\n l[l.length - 1] = 256 - l[l.length - 1];\n for (let i = 0; i < l.length - 1; i++) {\n l[i] = 255 - l[i];\n }\n }\n }\n return l;\n}\n\n/**\n * Generates a random long integer (8 bytes), which is optionally signed\n * @returns {BigInteger}\n */\nfunction generateRandomLong(signed = true) {\n return readBigIntFromBuffer(generateRandomBytes(8), true, signed);\n}\n\n/**\n * .... really javascript\n * @param n {number}\n * @param m {number}\n * @returns {number}\n */\nfunction mod(n, m) {\n return ((n % m) + m) % m;\n}\n\n/**\n * returns a positive bigInt\n * @param n {BigInt}\n * @param m {BigInt}\n * @returns {BigInt}\n */\nfunction bigIntMod(n, m) {\n return ((n.remainder(m)).add(m)).remainder(m);\n}\n\n/**\n * Generates a random bytes array\n * @param count\n * @returns {Buffer}\n */\nfunction generateRandomBytes(count) {\n return Buffer.from(crypto.randomBytes(count));\n}\n\n/**\n * Calculate the key based on Telegram guidelines, specifying whether it's the client or not\n * @param sharedKey\n * @param msgKey\n * @param client\n * @returns {{iv: Buffer, key: Buffer}}\n */\n\n/* CONTEST\nthis is mtproto 1 (mostly used for secret chats)\nasync function calcKey(sharedKey, msgKey, client) {\n const x = client === true ? 0 : 8\n const [sha1a, sha1b, sha1c, sha1d] = await Promise.all([\n sha1(Buffer.concat([msgKey, sharedKey.slice(x, x + 32)])),\n sha1(Buffer.concat([sharedKey.slice(x + 32, x + 48), msgKey, sharedKey.slice(x + 48, x + 64)])),\n sha1(Buffer.concat([sharedKey.slice(x + 64, x + 96), msgKey])),\n sha1(Buffer.concat([msgKey, sharedKey.slice(x + 96, x + 128)]))\n ])\n const key = Buffer.concat([sha1a.slice(0, 8), sha1b.slice(8, 20), sha1c.slice(4, 16)])\n const iv = Buffer.concat([sha1a.slice(8, 20), sha1b.slice(0, 8), sha1c.slice(16, 20), sha1d.slice(0, 8)])\n return {\n key,\n iv\n }\n}\n\n */\n\n/**\n * Generates the key data corresponding to the given nonces\n * @param serverNonce\n * @param newNonce\n * @returns {{key: Buffer, iv: Buffer}}\n */\nasync function generateKeyDataFromNonce(serverNonce, newNonce) {\n serverNonce = toSignedLittleBuffer(serverNonce, 16);\n newNonce = toSignedLittleBuffer(newNonce, 32);\n const [hash1, hash2, hash3] = await Promise.all([\n sha1(Buffer.concat([newNonce, serverNonce])),\n sha1(Buffer.concat([serverNonce, newNonce])),\n sha1(Buffer.concat([newNonce, newNonce])),\n ]);\n const keyBuffer = Buffer.concat([hash1, hash2.slice(0, 12)]);\n const ivBuffer = Buffer.concat([hash2.slice(12, 20), hash3, newNonce.slice(0, 4)]);\n return {\n key: keyBuffer,\n iv: ivBuffer,\n };\n}\n\nfunction convertToLittle(buf) {\n const correct = Buffer.alloc(buf.length * 4);\n\n for (let i = 0; i < buf.length; i++) {\n correct.writeUInt32BE(buf[i], i * 4);\n }\n return correct;\n}\n\n/**\n * Calculates the SHA1 digest for the given data\n * @param data\n * @returns {Promise}\n */\nfunction sha1(data) {\n const shaSum = crypto.createHash('sha1');\n shaSum.update(data);\n return shaSum.digest();\n}\n\n\n/**\n * Calculates the SHA256 digest for the given data\n * @param data\n * @returns {Promise}\n */\nfunction sha256(data) {\n const shaSum = crypto.createHash('sha256');\n shaSum.update(data);\n return shaSum.digest();\n}\n\n/**\n * Fast mod pow for RSA calculation. a^b % n\n * @param a\n * @param b\n * @param n\n * @returns {bigInt.BigInteger}\n */\nfunction modExp(a, b, n) {\n a = a.remainder(n);\n let result = BigInt.one;\n let x = a;\n while (b.greater(BigInt.zero)) {\n const leastSignificantBit = b.remainder(BigInt(2));\n b = b.divide(BigInt(2));\n if (leastSignificantBit.eq(BigInt.one)) {\n result = result.multiply(x);\n result = result.remainder(n);\n }\n x = x.multiply(x);\n x = x.remainder(n);\n }\n return result;\n}\n\n\n/**\n * Gets the arbitrary-length byte array corresponding to the given integer\n * @param integer {number,BigInteger}\n * @param signed {boolean}\n * @returns {Buffer}\n */\nfunction getByteArray(integer, signed = false) {\n const bits = integer.toString(2).length;\n const byteLength = Math.floor((bits + 8 - 1) / 8);\n return readBufferFromBigInt(BigInt(integer), byteLength, false, signed);\n}\n\n/**\n * returns a random int from min (inclusive) and max (inclusive)\n * @param min\n * @param max\n * @returns {number}\n */\nfunction getRandomInt(min, max) {\n min = Math.ceil(min);\n max = Math.floor(max);\n return Math.floor(Math.random() * (max - min + 1)) + min;\n}\n\n/**\n * Sleeps a specified amount of time\n * @param ms time in milliseconds\n * @returns {Promise}\n */\nconst sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));\n\n/**\n * Helper to export two buffers of same length\n * @returns {Buffer}\n */\n\nfunction bufferXor(a, b) {\n const res = [];\n for (let i = 0; i < a.length; i++) {\n res.push(a[i] ^ b[i]);\n }\n return Buffer.from(res);\n}\n\n/**\n * Checks if the obj is an array\n * @param obj\n * @returns {boolean}\n */\n/*\nCONTEST\nwe do'nt support array requests anyway\nfunction isArrayLike(obj) {\n if (!obj) return false\n const l = obj.length\n if (typeof l != 'number' || l < 0) return false\n if (Math.floor(l) !== l) return false\n // fast check\n if (l > 0 && !(l - 1 in obj)) return false\n // more complete check (optional)\n for (let i = 0; i < l; ++i) {\n if (!(i in obj)) return false\n }\n return true\n}\n*/\n\n// Taken from https://stackoverflow.com/questions/18638900/javascript-crc32/18639999#18639999\nfunction makeCRCTable() {\n let c;\n const crcTable = [];\n for (let n = 0; n < 256; n++) {\n c = n;\n for (let k = 0; k < 8; k++) {\n c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));\n }\n crcTable[n] = c;\n }\n return crcTable;\n}\n\nlet crcTable;\n\nfunction crc32(buf) {\n if (!crcTable) {\n crcTable = makeCRCTable();\n }\n if (!Buffer.isBuffer(buf)) {\n buf = Buffer.from(buf);\n }\n let crc = -1;\n\n for (let index = 0; index < buf.length; index++) {\n const byte = buf[index];\n crc = crcTable[(crc ^ byte) & 0xff] ^ (crc >>> 8);\n }\n return (crc ^ (-1)) >>> 0;\n}\n\n/**\n * Creates a deferred object\n * @return {Deferred}\n */\nfunction createDeferred() {\n let resolve;\n const promise = new Promise((_resolve) => {\n resolve = _resolve;\n });\n\n return {\n promise,\n resolve,\n };\n}\n\nmodule.exports = {\n readBigIntFromBuffer,\n readBufferFromBigInt,\n generateRandomLong,\n mod,\n crc32,\n generateRandomBytes,\n // calcKey,\n generateKeyDataFromNonce,\n sha1,\n sha256,\n bigIntMod,\n modExp,\n getRandomInt,\n sleep,\n getByteArray,\n // isArrayLike,\n toSignedLittleBuffer,\n convertToLittle,\n bufferXor,\n createDeferred,\n};\n","const BigInt = require('big-integer');\nconst { constructors } = require('./tl');\nconst {\n readBigIntFromBuffer,\n readBufferFromBigInt,\n sha256,\n bigIntMod,\n modExp,\n generateRandomBytes,\n} = require('./Helpers');\nconst crypto = require('./crypto/crypto');\n\nconst SIZE_FOR_HASH = 256;\n\n/**\n *\n *\n * @param prime{BigInteger}\n * @param g{BigInteger}\n */\n\n/*\nWe don't support changing passwords yet\nfunction checkPrimeAndGoodCheck(prime, g) {\n console.error('Unsupported function `checkPrimeAndGoodCheck` call. Arguments:', prime, g)\n\n const goodPrimeBitsCount = 2048\n if (prime < 0 || prime.bitLength() !== goodPrimeBitsCount) {\n throw new Error(`bad prime count ${prime.bitLength()},expected ${goodPrimeBitsCount}`)\n }\n // TODO this is kinda slow\n if (Factorizator.factorize(prime)[0] !== 1) {\n throw new Error('give \"prime\" is not prime')\n }\n if (g.eq(BigInt(2))) {\n if ((prime.remainder(BigInt(8))).neq(BigInt(7))) {\n throw new Error(`bad g ${g}, mod8 ${prime % 8}`)\n }\n } else if (g.eq(BigInt(3))) {\n if ((prime.remainder(BigInt(3))).neq(BigInt(2))) {\n throw new Error(`bad g ${g}, mod3 ${prime % 3}`)\n }\n // eslint-disable-next-line no-empty\n } else if (g.eq(BigInt(4))) {\n\n } else if (g.eq(BigInt(5))) {\n if (!([ BigInt(1), BigInt(4) ].includes(prime.remainder(BigInt(5))))) {\n throw new Error(`bad g ${g}, mod8 ${prime % 5}`)\n }\n } else if (g.eq(BigInt(6))) {\n if (!([ BigInt(19), BigInt(23) ].includes(prime.remainder(BigInt(24))))) {\n throw new Error(`bad g ${g}, mod8 ${prime % 24}`)\n }\n } else if (g.eq(BigInt(7))) {\n if (!([ BigInt(3), BigInt(5), BigInt(6) ].includes(prime.remainder(BigInt(7))))) {\n throw new Error(`bad g ${g}, mod8 ${prime % 7}`)\n }\n } else {\n throw new Error(`bad g ${g}`)\n }\n const primeSub1Div2 = (prime.subtract(BigInt(1))).divide(BigInt(2))\n if (Factorizator.factorize(primeSub1Div2)[0] !== 1) {\n throw new Error('(prime - 1) // 2 is not prime')\n }\n}\n*/\n/**\n *\n * @param primeBytes{Buffer}\n * @param g{number}\n */\nfunction checkPrimeAndGood(primeBytes, g) {\n const goodPrime = Buffer.from([\n 0xC7, 0x1C, 0xAE, 0xB9, 0xC6, 0xB1, 0xC9, 0x04, 0x8E, 0x6C, 0x52, 0x2F, 0x70, 0xF1, 0x3F, 0x73,\n 0x98, 0x0D, 0x40, 0x23, 0x8E, 0x3E, 0x21, 0xC1, 0x49, 0x34, 0xD0, 0x37, 0x56, 0x3D, 0x93, 0x0F,\n 0x48, 0x19, 0x8A, 0x0A, 0xA7, 0xC1, 0x40, 0x58, 0x22, 0x94, 0x93, 0xD2, 0x25, 0x30, 0xF4, 0xDB,\n 0xFA, 0x33, 0x6F, 0x6E, 0x0A, 0xC9, 0x25, 0x13, 0x95, 0x43, 0xAE, 0xD4, 0x4C, 0xCE, 0x7C, 0x37,\n 0x20, 0xFD, 0x51, 0xF6, 0x94, 0x58, 0x70, 0x5A, 0xC6, 0x8C, 0xD4, 0xFE, 0x6B, 0x6B, 0x13, 0xAB,\n 0xDC, 0x97, 0x46, 0x51, 0x29, 0x69, 0x32, 0x84, 0x54, 0xF1, 0x8F, 0xAF, 0x8C, 0x59, 0x5F, 0x64,\n 0x24, 0x77, 0xFE, 0x96, 0xBB, 0x2A, 0x94, 0x1D, 0x5B, 0xCD, 0x1D, 0x4A, 0xC8, 0xCC, 0x49, 0x88,\n 0x07, 0x08, 0xFA, 0x9B, 0x37, 0x8E, 0x3C, 0x4F, 0x3A, 0x90, 0x60, 0xBE, 0xE6, 0x7C, 0xF9, 0xA4,\n 0xA4, 0xA6, 0x95, 0x81, 0x10, 0x51, 0x90, 0x7E, 0x16, 0x27, 0x53, 0xB5, 0x6B, 0x0F, 0x6B, 0x41,\n 0x0D, 0xBA, 0x74, 0xD8, 0xA8, 0x4B, 0x2A, 0x14, 0xB3, 0x14, 0x4E, 0x0E, 0xF1, 0x28, 0x47, 0x54,\n 0xFD, 0x17, 0xED, 0x95, 0x0D, 0x59, 0x65, 0xB4, 0xB9, 0xDD, 0x46, 0x58, 0x2D, 0xB1, 0x17, 0x8D,\n 0x16, 0x9C, 0x6B, 0xC4, 0x65, 0xB0, 0xD6, 0xFF, 0x9C, 0xA3, 0x92, 0x8F, 0xEF, 0x5B, 0x9A, 0xE4,\n 0xE4, 0x18, 0xFC, 0x15, 0xE8, 0x3E, 0xBE, 0xA0, 0xF8, 0x7F, 0xA9, 0xFF, 0x5E, 0xED, 0x70, 0x05,\n 0x0D, 0xED, 0x28, 0x49, 0xF4, 0x7B, 0xF9, 0x59, 0xD9, 0x56, 0x85, 0x0C, 0xE9, 0x29, 0x85, 0x1F,\n 0x0D, 0x81, 0x15, 0xF6, 0x35, 0xB1, 0x05, 0xEE, 0x2E, 0x4E, 0x15, 0xD0, 0x4B, 0x24, 0x54, 0xBF,\n 0x6F, 0x4F, 0xAD, 0xF0, 0x34, 0xB1, 0x04, 0x03, 0x11, 0x9C, 0xD8, 0xE3, 0xB9, 0x2F, 0xCC, 0x5B,\n ]);\n if (goodPrime.equals(primeBytes)) {\n if ([3, 4, 5, 7].includes(g)) {\n return; // It's good\n }\n }\n throw new Error('Changing passwords unsupported');\n // checkPrimeAndGoodCheck(readBigIntFromBuffer(primeBytes, false), g)\n}\n\n/**\n *\n * @param number{BigInteger}\n * @param p{BigInteger}\n * @returns {boolean}\n */\nfunction isGoodLarge(number, p) {\n return (number.greater(BigInt(0)) && (p.subtract(number)\n .greater(BigInt(0))));\n}\n\n/**\n *\n * @param number {Buffer}\n * @returns {Buffer}\n */\nfunction numBytesForHash(number) {\n return Buffer.concat([Buffer.alloc(SIZE_FOR_HASH - number.length), number]);\n}\n\n/**\n *\n * @param g {Buffer}\n * @returns {Buffer}\n */\nfunction bigNumForHash(g) {\n return readBufferFromBigInt(g, SIZE_FOR_HASH, false);\n}\n\n/**\n *\n * @param modexp {BigInteger}\n * @param prime {BigInteger}\n * @returns {Boolean}\n */\nfunction isGoodModExpFirst(modexp, prime) {\n const diff = prime.subtract(modexp);\n\n const minDiffBitsCount = 2048 - 64;\n const maxModExpSize = 256;\n\n return !(diff.lesser(BigInt(0)) || diff.bitLength() < minDiffBitsCount\n || modexp.bitLength() < minDiffBitsCount\n || Math.floor((modexp.bitLength() + 7) / 8) > maxModExpSize);\n}\n\nfunction xor(a, b) {\n const length = Math.min(a.length, b.length);\n\n for (let i = 0; i < length; i++) {\n a[i] ^= b[i];\n }\n\n return a;\n}\n\n/**\n *\n * @param password{Buffer}\n * @param salt{Buffer}\n * @param iterations{number}\n * @returns {*}\n */\n\nfunction pbkdf2sha512(password, salt, iterations) {\n return crypto.pbkdf2(password, salt, iterations, 64, 'sha512');\n}\n\n/**\n *\n * @param algo {constructors.PasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow}\n * @param password\n * @returns {Buffer|*}\n */\nasync function computeHash(algo, password) {\n const hash1 = await sha256(Buffer.concat([algo.salt1, Buffer.from(password, 'utf-8'), algo.salt1]));\n const hash2 = await sha256(Buffer.concat([algo.salt2, hash1, algo.salt2]));\n const hash3 = await pbkdf2sha512(hash2, algo.salt1, 100000);\n return sha256(Buffer.concat([algo.salt2, hash3, algo.salt2]));\n}\n\n/**\n *\n * @param algo {constructors.PasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow}\n * @param password\n */\nasync function computeDigest(algo, password) {\n try {\n checkPrimeAndGood(algo.p, algo.g);\n } catch (e) {\n throw new Error('bad p/g in password');\n }\n\n const value = modExp(BigInt(algo.g),\n readBigIntFromBuffer(await computeHash(algo, password), false),\n readBigIntFromBuffer(algo.p, false));\n return bigNumForHash(value);\n}\n\n/**\n *\n * @param request {constructors.account.Password}\n * @param password {string}\n */\nasync function computeCheck(request, password) {\n const algo = request.currentAlgo;\n if (!(algo instanceof constructors.PasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow)) {\n throw new Error(`Unsupported password algorithm ${algo.className}`);\n }\n\n const pwHash = await computeHash(algo, password);\n const p = readBigIntFromBuffer(algo.p, false);\n const { g } = algo;\n const B = readBigIntFromBuffer(request.srp_B, false);\n try {\n checkPrimeAndGood(algo.p, g);\n } catch (e) {\n throw new Error('bad /g in password');\n }\n if (!isGoodLarge(B, p)) {\n throw new Error('bad b in check');\n }\n const x = readBigIntFromBuffer(pwHash, false);\n const pForHash = numBytesForHash(algo.p);\n const gForHash = bigNumForHash(g);\n const bForHash = numBytesForHash(request.srp_B);\n const gX = modExp(BigInt(g), x, p);\n const k = readBigIntFromBuffer(await sha256(Buffer.concat([pForHash, gForHash])), false);\n const kgX = bigIntMod(k.multiply(gX), p);\n const generateAndCheckRandom = async () => {\n const randomSize = 256;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const random = generateRandomBytes(randomSize);\n const a = readBigIntFromBuffer(random, false);\n const A = modExp(BigInt(g), a, p);\n if (isGoodModExpFirst(A, p)) {\n const aForHash = bigNumForHash(A);\n const u = readBigIntFromBuffer(await sha256(Buffer.concat([aForHash, bForHash])), false);\n if (u.greater(BigInt(0))) {\n return [a, aForHash, u];\n }\n }\n }\n };\n const [a, aForHash, u] = await generateAndCheckRandom();\n const gB = bigIntMod(B.subtract(kgX), p);\n if (!isGoodModExpFirst(gB, p)) {\n throw new Error('bad gB');\n }\n\n const ux = u.multiply(x);\n const aUx = a.add(ux);\n const S = modExp(gB, aUx, p);\n const [K, pSha, gSha, salt1Sha, salt2Sha] = await Promise.all([\n sha256(bigNumForHash(S)),\n sha256(pForHash),\n sha256(gForHash),\n sha256(algo.salt1),\n sha256(algo.salt2),\n ]);\n const M1 = await sha256(Buffer.concat([\n xor(pSha, gSha),\n salt1Sha,\n salt2Sha,\n aForHash,\n bForHash,\n K,\n ]));\n\n\n return new constructors.InputCheckPasswordSRP({\n srpId: request.srpId,\n A: Buffer.from(aForHash),\n M1,\n\n });\n}\n\nmodule.exports = {\n computeCheck,\n computeDigest,\n};\n","const { constructors } = require('./tl');\n\n// eslint-disable-next-line max-len\nconst JPEG_HEADER = Buffer.from('ffd8ffe000104a46494600010100000100010000ffdb004300281c1e231e19282321232d2b28303c64413c37373c7b585d4964918099968f808c8aa0b4e6c3a0aadaad8a8cc8ffcbdaeef5ffffff9bc1fffffffaffe6fdfff8ffdb0043012b2d2d3c353c76414176f8a58ca5f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8ffc00011080000000003012200021101031101ffc4001f0000010501010101010100000000000000000102030405060708090a0bffc400b5100002010303020403050504040000017d01020300041105122131410613516107227114328191a1082342b1c11552d1f02433627282090a161718191a25262728292a3435363738393a434445464748494a535455565758595a636465666768696a737475767778797a838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae1e2e3e4e5e6e7e8e9eaf1f2f3f4f5f6f7f8f9faffc4001f0100030101010101010101010000000000000102030405060708090a0bffc400b51100020102040403040705040400010277000102031104052131061241510761711322328108144291a1b1c109233352f0156272d10a162434e125f11718191a262728292a35363738393a434445464748494a535455565758595a636465666768696a737475767778797a82838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae2e3e4e5e6e7e8e9eaf2f3f4f5f6f7f8f9faffda000c03010002110311003f00', 'hex');\nconst JPEG_FOOTER = Buffer.from('ffd9', 'hex');\n\nfunction _raiseCastFail(entity, target) {\n throw new Error(`Cannot cast ${entity.className} to any kind of ${target}`);\n}\n\n/**\n Gets the input peer for the given \"entity\" (user, chat or channel).\n\n A ``TypeError`` is raised if the given entity isn't a supported type\n or if ``check_hash is True`` but the entity's ``accessHash is None``\n *or* the entity contains ``min`` information. In this case, the hash\n cannot be used for general purposes, and thus is not returned to avoid\n any issues which can derive from invalid access hashes.\n\n Note that ``check_hash`` **is ignored** if an input peer is already\n passed since in that case we assume the user knows what they're doing.\n This is key to getting entities by explicitly passing ``hash = 0``.\n\n * @param entity\n * @param allowSelf\n * @param checkHash\n */\nfunction getInputPeer(entity, allowSelf = true, checkHash = true) {\n if (entity.SUBCLASS_OF_ID === undefined) {\n // e.g. custom.Dialog (can't cyclic import).\n\n if (allowSelf && 'inputEntity' in entity) {\n return entity.inputEntity;\n } else if ('entity' in entity) {\n return getInputPeer(entity.entity);\n } else {\n _raiseCastFail(entity, 'InputPeer');\n }\n }\n if (entity.SUBCLASS_OF_ID === 0xc91c90b6) { // crc32(b'InputPeer')\n return entity;\n }\n\n if (entity instanceof constructors.User) {\n if (entity.isSelf && allowSelf) {\n return new constructors.InputPeerSelf();\n } else if (entity.accessHash !== undefined || !checkHash) {\n return new constructors.InputPeerUser({\n userId: entity.id,\n accessHash: entity.accessHash,\n });\n } else {\n throw new Error('User without accessHash or min info cannot be input');\n }\n }\n if (entity instanceof constructors.Chat || entity instanceof constructors.ChatEmpty\n || entity instanceof constructors.ChatForbidden) {\n return new constructors.InputPeerChat({ chatId: entity.id });\n }\n if (entity instanceof constructors.Channel) {\n if (entity.accessHash !== undefined || !checkHash) {\n return new constructors.InputPeerChannel({\n channelId: entity.id,\n accessHash: entity.accessHash,\n });\n } else {\n throw new TypeError('Channel without accessHash or min info cannot be input');\n }\n }\n if (entity instanceof constructors.ChannelForbidden) {\n // \"channelForbidden are never min\", and since their hash is\n // also not optional, we assume that this truly is the case.\n return new constructors.InputPeerChannel({\n channelId: entity.id,\n accessHash: entity.accessHash,\n });\n }\n\n if (entity instanceof constructors.InputUser) {\n return new constructors.InputPeerUser({\n userId: entity.userId,\n accessHash: entity.accessHash,\n });\n }\n if (entity instanceof constructors.InputChannel) {\n return new constructors.InputPeerChannel({\n channelId: entity.channelId,\n accessHash: entity.accessHash,\n });\n }\n if (entity instanceof constructors.UserEmpty) {\n return new constructors.InputPeerEmpty();\n }\n if (entity instanceof constructors.UserFull) {\n return getInputPeer(entity.user);\n }\n\n if (entity instanceof constructors.ChatFull) {\n return new constructors.InputPeerChat({ chatId: entity.id });\n }\n\n if (entity instanceof constructors.PeerChat) {\n return new constructors.InputPeerChat(entity.chatId);\n }\n\n _raiseCastFail(entity, 'InputPeer');\n return undefined;\n}\n\n/**\n Similar to :meth:`get_input_peer`, but for :tl:`InputChannel`'s alone.\n\n .. important::\n\n This method does not validate for invalid general-purpose access\n hashes, unlike `get_input_peer`. Consider using instead:\n ``get_input_channel(get_input_peer(channel))``.\n\n * @param entity\n * @returns {InputChannel|*}\n */\n/* CONTEST\nfunction getInputChannel(entity) {\n if (entity.SUBCLASS_OF_ID === undefined) {\n _raiseCastFail(entity, 'InputChannel')\n }\n\n\n if (entity.SUBCLASS_OF_ID === 0x40f202fd) { // crc32(b'InputChannel')\n return entity\n }\n if (entity instanceof constructors.Channel || entity instanceof constructors.ChannelForbidden) {\n return new constructors.InputChannel({\n channelId: entity.id,\n accessHash: entity.accessHash || 0\n })\n }\n\n if (entity instanceof constructors.InputPeerChannel) {\n return new constructors.InputChannel({\n channelId: entity.channelId,\n accessHash: entity.accessHash\n })\n }\n _raiseCastFail(entity, 'InputChannel')\n}\n*/\n/**\n Similar to :meth:`get_input_peer`, but for :tl:`InputUser`'s alone.\n\n .. important::\n\n This method does not validate for invalid general-purpose access\n hashes, unlike `get_input_peer`. Consider using instead:\n ``get_input_channel(get_input_peer(channel))``.\n\n * @param entity\n */\n/* CONTEST\nfunction getInputUser(entity) {\n if (entity.SUBCLASS_OF_ID === undefined) {\n _raiseCastFail(entity, 'InputUser')\n }\n if (entity.SUBCLASS_OF_ID === 0xe669bf46) { // crc32(b'InputUser')\n return entity\n }\n\n if (entity instanceof constructors.User) {\n if (entity.isSelf) {\n return new constructors.InputPeerSelf()\n } else {\n return new constructors.InputUser({\n userId: entity.id,\n accessHash: entity.accessHash || 0,\n })\n }\n }\n if (entity instanceof constructors.InputPeerSelf) {\n return new constructors.InputPeerSelf()\n }\n if (entity instanceof constructors.UserEmpty || entity instanceof constructors.InputPeerEmpty) {\n return new constructors.InputUserEmpty()\n }\n\n if (entity instanceof constructors.UserFull) {\n return getInputUser(entity.user)\n }\n\n if (entity instanceof constructors.InputPeerUser) {\n return new constructors.InputUser({\n userId: entity.userId,\n accessHash: entity.accessHash\n })\n }\n\n _raiseCastFail(entity, 'InputUser')\n}\n*/\n/**\n Similar to :meth:`get_input_peer`, but for dialogs\n * @param dialog\n */\n/* CONTEST\nfunction getInputDialog(dialog) {\n try {\n if (dialog.SUBCLASS_OF_ID === 0xa21c9795) { // crc32(b'InputDialogPeer')\n return dialog\n }\n if (dialog.SUBCLASS_OF_ID === 0xc91c90b6) { // crc32(b'InputPeer')\n return new constructors.InputDialogPeer({ peer: dialog })\n }\n } catch (e) {\n _raiseCastFail(dialog, 'InputDialogPeer')\n }\n\n try {\n return new constructors.InputDialogPeer(getInputPeer(dialog))\n // eslint-disable-next-line no-empty\n } catch (e) {\n\n }\n _raiseCastFail(dialog, 'InputDialogPeer')\n}\n*/\n\n/* CONTEST\n\nfunction getInputMessage(message) {\n try {\n if (typeof message == 'number') { // This case is really common too\n return new constructors.InputMessageID({\n id: message,\n })\n } else if (message.SUBCLASS_OF_ID === 0x54b6bcc5) { // crc32(b'InputMessage')\n return message\n } else if (message.SUBCLASS_OF_ID === 0x790009e3) { // crc32(b'Message')\n return new constructors.InputMessageID(message.id)\n }\n // eslint-disable-next-line no-empty\n } catch (e) {\n }\n\n _raiseCastFail(message, 'InputMessage')\n}\n*/\n\n/**\n * Adds the JPG header and footer to a stripped image.\n * Ported from https://github.com/telegramdesktop/\n * tdesktop/blob/bec39d89e19670eb436dc794a8f20b657cb87c71/Telegram/SourceFiles/ui/image/image.cpp#L225\n\n * @param stripped{Buffer}\n * @returns {Buffer}\n */\nfunction strippedPhotoToJpg(stripped) {\n // Note: Changes here should update _stripped_real_length\n if (stripped.length < 3 || stripped[0] !== 1) {\n return stripped;\n }\n const header = Buffer.from(JPEG_HEADER);\n // eslint-disable-next-line prefer-destructuring\n header[164] = stripped[1];\n // eslint-disable-next-line prefer-destructuring\n header[166] = stripped[2];\n return Buffer.concat([header, stripped.slice(3), JPEG_FOOTER]);\n}\n\n/* CONTEST\nfunction getInputLocation(location) {\n try {\n if (!location.SUBCLASS_OF_ID) {\n throw new Error()\n }\n if (location.SUBCLASS_OF_ID === 0x1523d462) {\n return {\n dcId: null,\n inputLocation: location\n }\n }\n } catch (e) {\n _raiseCastFail(location, 'InputFileLocation')\n }\n if (location instanceof constructors.Message) {\n location = location.media\n }\n\n if (location instanceof constructors.MessageMediaDocument) {\n location = location.document\n } else if (location instanceof constructors.MessageMediaPhoto) {\n location = location.photo\n }\n\n if (location instanceof constructors.Document) {\n return {\n dcId: location.dcId,\n inputLocation: new constructors.InputDocumentFileLocation({\n id: location.id,\n accessHash: location.accessHash,\n fileReference: location.fileReference,\n thumbSize: '', // Presumably to download one of its thumbnails\n }),\n }\n } else if (location instanceof constructors.Photo) {\n return {\n dcId: location.dcId,\n inputLocation: new constructors.InputPhotoFileLocation({\n id: location.id,\n accessHash: location.accessHash,\n fileReference: location.fileReference,\n thumbSize: location.sizes[location.sizes.length - 1].type,\n }),\n }\n }\n\n if (location instanceof constructors.FileLocationToBeDeprecated) {\n throw new Error('Unavailable location cannot be used as input')\n }\n _raiseCastFail(location, 'InputFileLocation')\n}\n*/\n\n/**\n * Gets the appropriated part size when uploading or downloading files,\n * given an initial file size.\n * @param fileSize\n * @returns {Number}\n */\nfunction getAppropriatedPartSize(fileSize) {\n if (fileSize <= 104857600) { // 100MB\n return 128;\n }\n if (fileSize <= 786432000) { // 750MB\n return 256;\n }\n if (fileSize <= 2097152000) { // 2000MB\n return 512;\n }\n\n throw new Error('File size too large');\n}\n\n/* CONTEST\nfunction getPeer(peer) {\n try {\n if (typeof peer === 'number') {\n const res = resolveId(peer)\n\n if (res[1] === constructors.PeerChannel) {\n return new res[1]({ channelId: res[0] })\n } else if (res[1] === constructors.PeerChat) {\n return new res[1]({ chatId: res[0] })\n } else {\n return new res[1]({ userId: res[0] })\n }\n }\n if (peer.SUBCLASS_OF_ID === undefined) {\n throw new Error()\n }\n if (peer.SUBCLASS_OF_ID === 0x2d45687) {\n return peer\n } else if (peer instanceof constructors.contacts.ResolvedPeer ||\n peer instanceof constructors.InputNotifyPeer || peer instanceof constructors.TopPeer ||\n peer instanceof constructors.Dialog || peer instanceof constructors.DialogPeer) {\n return peer.peer\n } else if (peer instanceof constructors.ChannelFull) {\n return new constructors.PeerChannel({ channelId: peer.id })\n }\n if (peer.SUBCLASS_OF_ID === 0x7d7c6f86 || peer.SUBCLASS_OF_ID === 0xd9c7fc18) {\n // ChatParticipant, ChannelParticipant\n return new constructors.PeerUser({ userId: peer.userId })\n }\n peer = getInputPeer(peer, false, false)\n\n if (peer instanceof constructors.InputPeerUser) {\n return new constructors.PeerUser({ userId: peer.userId })\n } else if (peer instanceof constructors.InputPeerChat) {\n return new constructors.PeerChat({ chatId: peer.chatId })\n } else if (peer instanceof constructors.InputPeerChannel) {\n return new constructors.PeerChannel({ channelId: peer.channelId })\n }\n // eslint-disable-next-line no-empty\n } catch (e) {\n console.log(e)\n }\n _raiseCastFail(peer, 'peer')\n}\n*/\n\n/**\n Convert the given peer into its marked ID by default.\n\n This \"mark\" comes from the \"bot api\" format, and with it the peer type\n can be identified back. User ID is left unmodified, chat ID is negated,\n and channel ID is prefixed with -100:\n\n * ``userId``\n * ``-chatId``\n * ``-100channel_id``\n\n The original ID and the peer type class can be returned with\n a call to :meth:`resolve_id(marked_id)`.\n * @param peer\n * @param addMark\n */\n/* CONTEST\nfunction getPeerId(peer, addMark = true) {\n // First we assert it's a Peer TLObject, or early return for integers\n if (typeof peer == 'number') {\n return addMark ? peer : resolveId(peer)[0]\n }\n\n // Tell the user to use their client to resolve InputPeerSelf if we got one\n if (peer instanceof constructors.InputPeerSelf) {\n _raiseCastFail(peer, 'int (you might want to use client.get_peer_id)')\n }\n\n try {\n peer = getPeer(peer)\n } catch (e) {\n _raiseCastFail(peer, 'int')\n }\n if (peer instanceof constructors.PeerUser) {\n return peer.userId\n } else if (peer instanceof constructors.PeerChat) {\n // Check in case the user mixed things up to avoid blowing up\n if (!(0 < peer.chatId <= 0x7fffffff)) {\n peer.chatId = resolveId(peer.chatId)[0]\n }\n\n return addMark ? -(peer.chatId) : peer.chatId\n } else { // if (peer instanceof constructors.PeerChannel)\n // Check in case the user mixed things up to avoid blowing up\n if (!(0 < peer.channelId <= 0x7fffffff)) {\n peer.channelId = resolveId(peer.channelId)[0]\n }\n if (!addMark) {\n return peer.channelId\n }\n // Concat -100 through math tricks, .to_supergroup() on\n // Madeline IDs will be strictly positive -> log works.\n try {\n return -(peer.channelId + Math.pow(10, Math.floor(Math.log10(peer.channelId) + 3)))\n } catch (e) {\n throw new Error('Cannot get marked ID of a channel unless its ID is strictly positive')\n }\n }\n}\n*/\n/**\n * Given a marked ID, returns the original ID and its :tl:`Peer` type.\n * @param markedId\n */\n/* CONTEST\nfunction resolveId(markedId) {\n if (markedId >= 0) {\n return [markedId, constructors.PeerUser]\n }\n\n // There have been report of chat IDs being 10000xyz, which means their\n // marked version is -10000xyz, which in turn looks like a channel but\n // it becomes 00xyz (= xyz). Hence, we must assert that there are only\n // two zeroes.\n const m = markedId.toString()\n .match(/-100([^0]\\d*)/)\n if (m) {\n return [parseInt(m[1]), constructors.PeerChannel]\n }\n return [-markedId, constructors.PeerChat]\n}\n*/\n\n/**\n * returns an entity pair\n * @param entityId\n * @param entities\n * @param cache\n * @param getInputPeer\n * @returns {{inputEntity: *, entity: *}}\n * @private\n */\n\n/* CONTEST\n\nfunction _getEntityPair(entityId, entities, cache, getInputPeer = getInputPeer) {\n const entity = entities.get(entityId)\n let inputEntity = cache[entityId]\n if (inputEntity === undefined) {\n try {\n inputEntity = getInputPeer(inputEntity)\n } catch (e) {\n inputEntity = null\n }\n }\n return {\n entity,\n inputEntity\n }\n}\n*/\n\nfunction getMessageId(message) {\n if (message === undefined) {\n return undefined;\n }\n if (typeof message === 'number') {\n return message;\n }\n if (message.SUBCLASS_OF_ID === 0x790009e3) { // crc32(b'Message')\n return message.id;\n }\n throw new Error(`Invalid message type: ${message.constructor.name}`);\n}\n\n\n/**\n Parses the given username or channel access hash, given\n a string, username or URL. Returns a tuple consisting of\n both the stripped, lowercase username and whether it is\n a joinchat/ hash (in which case is not lowercase'd).\n\n Returns ``(None, False)`` if the ``username`` or link is not valid.\n\n * @param username {string}\n */\n\n/* CONTEST\n\nfunction parseUsername(username) {\n username = username.trim()\n const m = username.match(USERNAME_RE) || username.match(TG_JOIN_RE)\n if (m) {\n username = username.replace(m[0], '')\n if (m[1]) {\n return {\n username: username,\n isInvite: true\n }\n } else {\n username = rtrim(username, '/')\n }\n }\n if (username.match(VALID_USERNAME_RE)) {\n return {\n username: username.toLowerCase(),\n isInvite: false\n }\n } else {\n return {\n username: null,\n isInvite: false\n }\n }\n}\n\nfunction rtrim(s, mask) {\n while (~mask.indexOf(s[s.length - 1])) {\n s = s.slice(0, -1)\n }\n return s\n}\n\n */\n\n/**\n * Gets the display name for the given :tl:`User`,\n :tl:`Chat` or :tl:`Channel`. Returns an empty string otherwise\n * @param entity\n */\nfunction getDisplayName(entity) {\n if (entity instanceof constructors.User) {\n if (entity.lastName && entity.firstName) {\n return `${entity.firstName} ${entity.lastName}`;\n } else if (entity.firstName) {\n return entity.firstName;\n } else if (entity.lastName) {\n return entity.lastName;\n } else {\n return '';\n }\n } else if (entity instanceof constructors.Chat || entity instanceof constructors.Channel) {\n return entity.title;\n }\n return '';\n}\n\n/**\n * check if a given item is an array like or not\n * @param item\n * @returns {boolean}\n */\n\n/* CONTEST\nDuplicate ?\nfunction isListLike(item) {\n return (\n Array.isArray(item) ||\n (!!item &&\n typeof item === 'object' &&\n typeof (item.length) === 'number' &&\n (item.length === 0 ||\n (item.length > 0 &&\n (item.length - 1) in item)\n )\n )\n )\n}\n*/\n/**\n * Returns the appropriate DC based on the id\n * @param dcId the id of the DC.\n * @param downloadDC whether to use -1 DCs or not\n * (These only support downloading/uploading and not creating a new AUTH key)\n * @return {{port: number, ipAddress: string, id: number}}\n */\nfunction getDC(dcId, downloadDC = false) {\n // TODO Move to external config\n switch (dcId) {\n case 1:\n return {\n id: 1,\n ipAddress: `zws1${downloadDC ? '-1' : ''}.web.telegram.org`,\n port: 443,\n };\n case 2:\n return {\n id: 2,\n ipAddress: `zws2${downloadDC ? '-1' : ''}.web.telegram.org`,\n port: 443,\n };\n case 3:\n return {\n id: 3,\n ipAddress: `zws3${downloadDC ? '-1' : ''}.web.telegram.org`,\n port: 443,\n };\n case 4:\n return {\n id: 4,\n ipAddress: `zws4${downloadDC ? '-1' : ''}.web.telegram.org`,\n port: 443,\n };\n case 5:\n return {\n id: 5,\n ipAddress: `zws5${downloadDC ? '-1' : ''}.web.telegram.org`,\n port: 443,\n };\n default:\n throw new Error(`Cannot find the DC with the ID of ${dcId}`);\n }\n // TODO chose based on current connection method\n /*\n if (!this._config) {\n this._config = await this.invoke(new requests.help.GetConfig())\n }\n if (cdn && !this._cdnConfig) {\n this._cdnConfig = await this.invoke(new requests.help.GetCdnConfig())\n for (const pk of this._cdnConfig.publicKeys) {\n addKey(pk.publicKey)\n }\n }\n for (const DC of this._config.dcOptions) {\n if (DC.id === dcId && Boolean(DC.ipv6) === this._useIPV6 && Boolean(DC.cdn) === cdn) {\n return DC\n }\n } */\n}\n\nmodule.exports = {\n getMessageId,\n // _getEntityPair,\n // getInputMessage,\n // getInputDialog,\n // getInputUser,\n // getInputChannel,\n getInputPeer,\n // parsePhone,\n // parseUsername,\n // getPeer,\n // getPeerId,\n getDisplayName,\n // resolveId,\n // isListLike,\n getAppropriatedPartSize,\n // getInputLocation,\n strippedPhotoToJpg,\n getDC,\n};\n","module.exports = '0.0.2';\n","import TelegramClient from './TelegramClient';\n// eslint-disable-next-line import/no-named-default\nimport { default as Api } from '../tl/api';\nimport { generateRandomBytes } from '../Helpers';\nimport { computeCheck, computeDigest } from '../Password';\nimport errors from '../errors';\n\nexport interface TwoFaParams {\n isCheckPassword?: boolean;\n currentPassword?: string;\n newPassword?: string;\n hint?: string;\n email?: string;\n emailCodeCallback?: (length: number) => Promise;\n onEmailCodeError?: (err: Error) => void;\n}\n\n/**\n * Changes the 2FA settings of the logged in user.\n Note that this method may be *incredibly* slow depending on the\n prime numbers that must be used during the process to make sure\n that everything is safe.\n\n Has no effect if both current and new password are omitted.\n\n * @param client: The telegram client instance\n * @param isCheckPassword: Must be ``true`` if you want to check the current password\n * @param currentPassword: The current password, to authorize changing to ``new_password``.\n Must be set if changing existing 2FA settings.\n Must **not** be set if 2FA is currently disabled.\n Passing this by itself will remove 2FA (if correct).\n * @param newPassword: The password to set as 2FA.\n If 2FA was already enabled, ``currentPassword`` **must** be set.\n Leaving this blank or `undefined` will remove the password.\n * @param hint: Hint to be displayed by Telegram when it asks for 2FA.\n Must be set when changing or creating a new password.\n Has no effect if ``newPassword`` is not set.\n * @param email: Recovery and verification email. If present, you must also\n set `emailCodeCallback`, else it raises an Error.\n * @param emailCodeCallback: If an email is provided, a callback that returns the code sent\n to it must also be set. This callback may be asynchronous.\n It should return a string with the code. The length of the\n code will be passed to the callback as an input parameter.\n\n If the callback returns an invalid code, it will raise an rpc error with the message\n ``CODE_INVALID``\n\n * @returns Promise\n * @throws this method can throw:\n \"PASSWORD_HASH_INVALID\" if you entered a wrong password (or set it to undefined).\n \"EMAIL_INVALID\" if the entered email is wrong\n \"EMAIL_HASH_EXPIRED\" if the user took too long to verify their email\n */\nexport async function updateTwoFaSettings(\n client: TelegramClient,\n {\n isCheckPassword,\n currentPassword,\n newPassword,\n hint = '',\n email,\n emailCodeCallback,\n onEmailCodeError,\n }: TwoFaParams,\n) {\n if (!newPassword && !currentPassword) {\n throw new Error('Neither `currentPassword` nor `newPassword` is present');\n }\n\n if (email && !(emailCodeCallback && onEmailCodeError)) {\n throw new Error('`email` present without `emailCodeCallback` and `onEmailCodeError`');\n }\n\n const pwd = await client.invoke(new Api.account.GetPassword());\n\n if (!(pwd.newAlgo instanceof Api.PasswordKdfAlgoUnknown)) {\n pwd.newAlgo.salt1 = Buffer.concat([pwd.newAlgo.salt1, generateRandomBytes(32)]);\n }\n if (!pwd.hasPassword && currentPassword) {\n currentPassword = undefined;\n }\n\n const password = currentPassword ? await computeCheck(pwd, currentPassword!) : new Api.InputCheckPasswordEmpty();\n\n if (isCheckPassword) {\n await client.invoke(new Api.auth.CheckPassword({ password }));\n return;\n }\n\n try {\n await client.invoke(new Api.account.UpdatePasswordSettings({\n password,\n newSettings: new Api.account.PasswordInputSettings({\n newAlgo: pwd.newAlgo,\n newPasswordHash: newPassword ? await computeDigest(pwd.newAlgo, newPassword) : Buffer.alloc(0),\n hint,\n email,\n // not explained what it does and it seems to always be set to empty in tdesktop\n newSecureSettings: undefined,\n }),\n }));\n } catch (e) {\n if (e instanceof errors.EmailUnconfirmedError) {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n try {\n const code = await emailCodeCallback!(e.codeLength);\n\n if (!code) {\n throw new Error('Code is empty');\n }\n\n await client.invoke(new Api.account.ConfirmPasswordEmail({ code }));\n break;\n } catch (err) {\n onEmailCodeError!(err);\n }\n }\n } else {\n throw e;\n }\n }\n}\n","const os = require('os');\nconst Logger = require('../extensions/Logger');\nconst { sleep } = require('../Helpers');\nconst errors = require('../errors');\nconst MemorySession = require('../sessions/Memory');\nconst Helpers = require('../Helpers');\nconst utils = require('../Utils');\nconst Session = require('../sessions/Abstract');\nconst { LAYER } = require('../tl/AllTLObjects');\nconst {\n constructors,\n requests,\n} = require('../tl');\nconst MTProtoSender = require('../network/MTProtoSender');\nconst { ConnectionTCPObfuscated } = require('../network/connection/TCPObfuscated');\nconst {\n authFlow,\n checkAuthorization,\n} = require('./auth');\nconst { downloadFile } = require('./downloadFile');\nconst { uploadFile } = require('./uploadFile');\nconst { updateTwoFaSettings } = require('./2fa');\n\nconst DEFAULT_DC_ID = 2;\nconst WEBDOCUMENT_DC_ID = 4;\nconst DEFAULT_IPV4_IP = 'zws2.web.telegram.org';\nconst DEFAULT_IPV6_IP = '[2001:67c:4e8:f002::a]';\nconst EXPORTED_SENDER_RECONNECT_TIMEOUT = 1000; // 1 sec\nconst EXPORTED_SENDER_RELEASE_TIMEOUT = 30000; // 30 sec\nconst WEBDOCUMENT_REQUEST_PART_SIZE = 131072; // 128kb\n\nconst PING_INTERVAL = 3000; // 3 sec\nconst PING_TIMEOUT = 5000; // 5 sec\nconst PING_FAIL_ATTEMPTS = 3;\nconst PING_FAIL_INTERVAL = 100; // ms\nconst PING_DISCONNECT_DELAY = 60000; // 1 min\n\n// All types\nconst sizeTypes = ['w', 'y', 'd', 'x', 'c', 'm', 'b', 'a', 's'];\n\nclass TelegramClient {\n static DEFAULT_OPTIONS = {\n connection: ConnectionTCPObfuscated,\n useIPV6: false,\n proxy: undefined,\n timeout: 10,\n requestRetries: 5,\n connectionRetries: Infinity,\n retryDelay: 1000,\n autoReconnect: true,\n sequentialUpdates: false,\n floodSleepLimit: 60,\n deviceModel: undefined,\n systemVersion: undefined,\n appVersion: undefined,\n langCode: 'en',\n systemLangCode: 'en',\n baseLogger: 'gramjs',\n useWSS: false,\n additionalDcsDisabled: false,\n testServers: false,\n };\n\n /**\n *\n * @param session {StringSession|LocalStorageSession}\n * @param apiId\n * @param apiHash\n * @param opts\n */\n constructor(session, apiId, apiHash, opts = TelegramClient.DEFAULT_OPTIONS) {\n if (!apiId || !apiHash) {\n throw Error('Your API ID or Hash are invalid. Please read \"Requirements\" on README.md');\n }\n const args = { ...TelegramClient.DEFAULT_OPTIONS, ...opts };\n this.apiId = apiId;\n this.apiHash = apiHash;\n this._useIPV6 = args.useIPV6;\n // this._entityCache = new Set()\n if (typeof args.baseLogger === 'string') {\n this._log = new Logger();\n } else {\n this._log = args.baseLogger;\n }\n // Determine what session we will use\n if (typeof session === 'string' || !session) {\n try {\n throw new Error('not implemented');\n } catch (e) {\n session = new MemorySession();\n }\n } else if (!(session instanceof Session)) {\n throw new Error('The given session must be str or a session instance');\n }\n\n this.floodSleepLimit = args.floodSleepLimit;\n this._eventBuilders = [];\n\n this._phoneCodeHash = {};\n this.session = session;\n // this._entityCache = EntityCache();\n this.apiId = parseInt(apiId, 10);\n this.apiHash = apiHash;\n\n this._requestRetries = args.requestRetries;\n this._connectionRetries = args.connectionRetries;\n this._retryDelay = args.retryDelay || 0;\n if (args.proxy) {\n this._log.warn('proxies are not supported');\n }\n this._proxy = args.proxy;\n this._timeout = args.timeout;\n this._autoReconnect = args.autoReconnect;\n\n this._connection = args.connection;\n // TODO add proxy support\n\n this._floodWaitedRequests = {};\n\n this._initWith = (x) => {\n return new requests.InvokeWithLayer({\n layer: LAYER,\n query: new requests.InitConnection({\n apiId: this.apiId,\n deviceModel: args.deviceModel || os.type()\n .toString() || 'Unknown',\n systemVersion: args.systemVersion || os.release()\n .toString() || '1.0',\n appVersion: args.appVersion || '1.0',\n langCode: args.langCode,\n langPack: '', // this should be left empty.\n systemLangCode: args.systemLangCode,\n query: x,\n proxy: undefined, // no proxies yet.\n }),\n });\n };\n\n this._args = args;\n // These will be set later\n this._config = undefined;\n this.phoneCodeHashes = [];\n this._exportedSenderPromises = {};\n this._exportedSenderReleaseTimeouts = {};\n this._additionalDcsDisabled = args.additionalDcsDisabled;\n this._loopStarted = false;\n this._reconnecting = false;\n this._destroyed = false;\n }\n\n // region Connecting\n\n /**\n * Connects to the Telegram servers, executing authentication if required.\n * Note that authenticating to the Telegram servers is not the same as authenticating\n * the app, which requires to send a code first.\n * @returns {Promise}\n */\n async connect() {\n await this._initSession();\n\n if (this._sender === undefined) {\n // only init sender once to avoid multiple loops.\n this._sender = new MTProtoSender(this.session.getAuthKey(), {\n logger: this._log,\n dcId: this.session.dcId,\n retries: this._connectionRetries,\n delay: this._retryDelay,\n autoReconnect: this._autoReconnect,\n connectTimeout: this._timeout,\n authKeyCallback: this._authKeyCallback.bind(this),\n updateCallback: this._handleUpdate.bind(this),\n isMainSender: true,\n });\n }\n // set defaults vars\n this._sender.userDisconnected = false;\n this._sender._user_connected = false;\n this._sender._reconnecting = false;\n this._sender._disconnected = true;\n\n const connection = new this._connection(\n this.session.serverAddress, this.session.port, this.session.dcId, this._log, this._args.testServers,\n );\n\n const newConnection = await this._sender.connect(connection);\n if (!newConnection) {\n // we're already connected so no need to reset auth key.\n if (!this._loopStarted) {\n this._updateLoop();\n this._loopStarted = true;\n }\n return;\n }\n\n this.session.setAuthKey(this._sender.authKey);\n await this._sender.send(this._initWith(\n new requests.help.GetConfig({}),\n ));\n\n if (!this._loopStarted) {\n this._updateLoop();\n this._loopStarted = true;\n }\n this._reconnecting = false;\n }\n\n async _initSession() {\n await this.session.load();\n\n if (!this.session.serverAddress || (this.session.serverAddress.includes(':') !== this._useIPV6)) {\n this.session.setDC(DEFAULT_DC_ID, this._useIPV6\n ? DEFAULT_IPV6_IP : DEFAULT_IPV4_IP, this._args.useWSS ? 443 : 80);\n }\n }\n\n async _updateLoop() {\n while (!this._destroyed) {\n await Helpers.sleep(PING_INTERVAL);\n if (this._reconnecting) {\n continue;\n }\n\n try {\n await attempts(() => {\n return timeout(this._sender.send(new requests.PingDelayDisconnect({\n pingId: Helpers.getRandomInt(Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER),\n disconnectDelay: PING_DISCONNECT_DELAY,\n })), PING_TIMEOUT);\n }, PING_FAIL_ATTEMPTS, PING_FAIL_INTERVAL);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n if (this._reconnecting) {\n continue;\n }\n\n await this.disconnect();\n await this.connect();\n }\n\n // We need to send some content-related request at least hourly\n // for Telegram to keep delivering updates, otherwise they will\n // just stop even if we're connected. Do so every 30 minutes.\n\n // TODO Call getDifference instead since it's more relevant\n if (new Date().getTime() - this._lastRequest > 30 * 60 * 1000) {\n try {\n await this.invoke(new requests.updates.GetState());\n } catch (e) {\n // we don't care about errors here\n }\n }\n }\n await this.disconnect();\n }\n\n /**\n * Disconnects from the Telegram server\n * @returns {Promise}\n */\n async disconnect() {\n if (this._sender) {\n await this._sender.disconnect();\n }\n\n await Promise.all(\n Object.values(this._exportedSenderPromises)\n .map((promise) => {\n return promise && promise.then((sender) => {\n if (sender) {\n return sender.disconnect();\n }\n return undefined;\n });\n }),\n );\n\n this._exportedSenderPromises = {};\n }\n\n /**\n * Disconnects all senders and removes all handlers\n * @returns {Promise}\n */\n async destroy() {\n this._destroyed = true;\n\n try {\n await this.disconnect();\n } catch (err) {\n // Do nothing\n }\n\n this.session.delete();\n this._eventBuilders = [];\n }\n\n async _switchDC(newDc) {\n this._log.info(`Reconnecting to new data center ${newDc}`);\n const DC = utils.getDC(newDc);\n this.session.setDC(newDc, DC.ipAddress, DC.port);\n // authKey's are associated with a server, which has now changed\n // so it's not valid anymore. Set to None to force recreating it.\n await this._sender.authKey.setKey(undefined);\n this.session.setAuthKey(undefined);\n this._reconnecting = true;\n await this.disconnect();\n return this.connect();\n }\n\n _authKeyCallback(authKey, dcId) {\n this.session.setAuthKey(authKey, dcId);\n }\n\n // endregion\n // export region\n\n async _cleanupExportedSender(dcId) {\n if (this.session.dcId !== dcId) {\n this.session.setAuthKey(undefined, dcId);\n }\n const sender = await this._exportedSenderPromises[dcId];\n this._exportedSenderPromises[dcId] = undefined;\n await sender.disconnect();\n }\n\n async _connectSender(sender, dcId) {\n // if we don't already have an auth key we want to use normal DCs not -1\n const dc = utils.getDC(dcId, !!sender.authKey.getKey());\n\n while (true) {\n try {\n await sender.connect(new this._connection(\n dc.ipAddress,\n dc.port,\n dcId,\n this._log,\n this._args.testServers,\n ));\n\n if (this.session.dcId !== dcId && !sender._authenticated) {\n this._log.info(`Exporting authorization for data center ${dc.ipAddress}`);\n const auth = await this.invoke(new requests.auth.ExportAuthorization({ dcId }));\n const req = this._initWith(new requests.auth.ImportAuthorization({\n id: auth.id,\n bytes: auth.bytes,\n }));\n await sender.send(req);\n sender._authenticated = true;\n }\n sender.dcId = dcId;\n sender.userDisconnected = false;\n\n return sender;\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(err);\n\n await Helpers.sleep(1000);\n await sender.disconnect();\n }\n }\n }\n\n async _borrowExportedSender(dcId, shouldReconnect, existingSender) {\n if (this._additionalDcsDisabled) {\n return undefined;\n }\n\n if (!this._exportedSenderPromises[dcId] || shouldReconnect) {\n this._exportedSenderPromises[dcId] = this._connectSender(\n existingSender || this._createExportedSender(dcId),\n dcId,\n );\n }\n\n let sender;\n try {\n sender = await this._exportedSenderPromises[dcId];\n\n if (!sender.isConnected()) {\n if (sender.isConnecting) {\n await Helpers.sleep(EXPORTED_SENDER_RECONNECT_TIMEOUT);\n return this._borrowExportedSender(dcId, false, sender);\n } else {\n return this._borrowExportedSender(dcId, true, sender);\n }\n }\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(err);\n\n return this._borrowExportedSender(dcId, true);\n }\n\n if (this._exportedSenderReleaseTimeouts[dcId]) {\n clearTimeout(this._exportedSenderReleaseTimeouts[dcId]);\n this._exportedSenderReleaseTimeouts[dcId] = undefined;\n }\n\n this._exportedSenderReleaseTimeouts[dcId] = setTimeout(() => {\n this._exportedSenderReleaseTimeouts[dcId] = undefined;\n sender.disconnect();\n }, EXPORTED_SENDER_RELEASE_TIMEOUT);\n\n return sender;\n }\n\n _createExportedSender(dcId) {\n return new MTProtoSender(this.session.getAuthKey(dcId), {\n logger: this._log,\n dcId,\n retries: this._connectionRetries,\n delay: this._retryDelay,\n autoReconnect: this._autoReconnect,\n connectTimeout: this._timeout,\n authKeyCallback: this._authKeyCallback.bind(this),\n isMainSender: dcId === this.session.dcId,\n onConnectionBreak: this._cleanupExportedSender.bind(this),\n });\n }\n\n getSender(dcId) {\n return dcId ? this._borrowExportedSender(dcId) : Promise.resolve(this._sender);\n }\n\n // end region\n\n // download region\n\n /**\n * Complete flow to download a file.\n * @param inputLocation {constructors.InputFileLocation}\n * @param [args[partSizeKb] {number}]\n * @param [args[fileSize] {number}]\n * @param [args[progressCallback] {Function}]\n * @param [args[start] {number}]\n * @param [args[end] {number}]\n * @param [args[dcId] {number}]\n * @param [args[workers] {number}]\n * @returns {Promise}\n */\n downloadFile(inputLocation, args = {}) {\n return downloadFile(this, inputLocation, args);\n }\n\n downloadMedia(messageOrMedia, args) {\n let media;\n if (messageOrMedia instanceof constructors.Message) {\n media = messageOrMedia.media;\n } else {\n media = messageOrMedia;\n }\n if (typeof media === 'string') {\n throw new Error('not implemented');\n }\n\n if (media instanceof constructors.MessageMediaWebPage) {\n if (media.webpage instanceof constructors.WebPage) {\n media = media.webpage.document || media.webpage.photo;\n }\n }\n if (media instanceof constructors.MessageMediaPhoto || media instanceof constructors.Photo) {\n return this._downloadPhoto(media, args);\n } else if (media instanceof constructors.MessageMediaDocument || media instanceof constructors.Document) {\n return this._downloadDocument(media, args);\n } else if (media instanceof constructors.MessageMediaContact) {\n return this._downloadContact(media, args);\n } else if (media instanceof constructors.WebDocument || media instanceof constructors.WebDocumentNoProxy) {\n return this._downloadWebDocument(media, args);\n }\n return undefined;\n }\n\n downloadProfilePhoto(entity, isBig = false) {\n // ('User', 'Chat', 'UserFull', 'ChatFull')\n const ENTITIES = [0x2da17977, 0xc5af5d94, 0x1f4661b9, 0xd49a2697];\n // ('InputPeer', 'InputUser', 'InputChannel')\n // const INPUTS = [0xc91c90b6, 0xe669bf46, 0x40f202fd]\n // Todo account for input methods\n const sizeType = isBig ? 'x' : 'm';\n let photo;\n if (!(ENTITIES.includes(entity.SUBCLASS_OF_ID))) {\n photo = entity;\n } else {\n if (!entity.photo) {\n // Special case: may be a ChatFull with photo:Photo\n if (!entity.chatPhoto) {\n return undefined;\n }\n\n return this._downloadPhoto(\n entity.chatPhoto, { sizeType },\n );\n }\n photo = entity.photo;\n }\n\n let dcId;\n let loc;\n if (photo instanceof constructors.UserProfilePhoto || photo instanceof constructors.ChatPhoto) {\n dcId = photo.dcId;\n loc = new constructors.InputPeerPhotoFileLocation({\n peer: utils.getInputPeer(entity),\n photoId: photo.photoId,\n big: isBig,\n });\n } else {\n // It doesn't make any sense to check if `photo` can be used\n // as input location, because then this method would be able\n // to \"download the profile photo of a message\", i.e. its\n // media which should be done with `download_media` instead.\n return undefined;\n }\n return this.downloadFile(loc, {\n dcId,\n });\n }\n\n downloadStickerSetThumb(stickerSet) {\n if (!stickerSet.thumbs || !stickerSet.thumbs.length) {\n return undefined;\n }\n\n const { thumbVersion } = stickerSet;\n return this.downloadFile(\n new constructors.InputStickerSetThumb({\n stickerset: new constructors.InputStickerSetID({\n id: stickerSet.id,\n accessHash: stickerSet.accessHash,\n }),\n thumbVersion,\n }),\n { dcId: stickerSet.thumbDcId },\n );\n }\n\n _pickFileSize(sizes, sizeType) {\n if (!sizeType || !sizes || !sizes.length) {\n return undefined;\n }\n const indexOfSize = sizeTypes.indexOf(sizeType);\n let size;\n for (let i = indexOfSize; i < sizeTypes.length; i++) {\n size = sizes.find((s) => s.type === sizeTypes[i]);\n if (size) {\n return size;\n }\n }\n return undefined;\n }\n\n _downloadCachedPhotoSize(size) {\n // No need to download anything, simply write the bytes\n let data;\n if (size instanceof constructors.PhotoStrippedSize) {\n data = utils.strippedPhotoToJpg(size.bytes);\n } else {\n data = size.bytes;\n }\n return data;\n }\n\n _downloadPhoto(photo, args) {\n if (photo instanceof constructors.MessageMediaPhoto) {\n photo = photo.photo;\n }\n if (!(photo instanceof constructors.Photo)) {\n return undefined;\n }\n const size = this._pickFileSize(photo.sizes, args.sizeType);\n if (!size || (size instanceof constructors.PhotoSizeEmpty)) {\n return undefined;\n }\n\n if (size instanceof constructors.PhotoCachedSize || size instanceof constructors.PhotoStrippedSize) {\n return this._downloadCachedPhotoSize(size);\n }\n return this.downloadFile(\n new constructors.InputPhotoFileLocation({\n id: photo.id,\n accessHash: photo.accessHash,\n fileReference: photo.fileReference,\n thumbSize: size.type,\n }),\n {\n dcId: photo.dcId,\n fileSize: size.size,\n progressCallback: args.progressCallback,\n },\n );\n }\n\n _downloadDocument(doc, args) {\n if (doc instanceof constructors.MessageMediaDocument) {\n doc = doc.document;\n }\n if (!(doc instanceof constructors.Document)) {\n return undefined;\n }\n\n let size;\n if (args.sizeType) {\n size = doc.thumbs ? this._pickFileSize(doc.thumbs, args.sizeType) : undefined;\n if (!size && doc.mimeType.startsWith('video/')) {\n return undefined;\n }\n\n if (size && (size instanceof constructors.PhotoCachedSize\n || size instanceof constructors.PhotoStrippedSize)) {\n return this._downloadCachedPhotoSize(size);\n }\n }\n\n return this.downloadFile(\n new constructors.InputDocumentFileLocation({\n id: doc.id,\n accessHash: doc.accessHash,\n fileReference: doc.fileReference,\n thumbSize: size ? size.type : '',\n }),\n {\n fileSize: size ? size.size : doc.size,\n progressCallback: args.progressCallback,\n start: args.start,\n end: args.end,\n dcId: doc.dcId,\n workers: args.workers,\n },\n );\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _downloadContact(media, args) {\n throw new Error('not implemented');\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async _downloadWebDocument(media) {\n try {\n const buff = [];\n let offset = 0;\n while (true) {\n const downloaded = new requests.upload.GetWebFile({\n location: new constructors.InputWebFileLocation({\n url: media.url,\n accessHash: media.accessHash,\n }),\n offset,\n limit: WEBDOCUMENT_REQUEST_PART_SIZE,\n });\n const sender = await this._borrowExportedSender(WEBDOCUMENT_DC_ID);\n const res = await sender.send(downloaded);\n offset += 131072;\n if (res.bytes.length) {\n buff.push(res.bytes);\n if (res.bytes.length < WEBDOCUMENT_REQUEST_PART_SIZE) {\n break;\n }\n } else {\n break;\n }\n }\n return Buffer.concat(buff);\n } catch (e) {\n // the file is no longer saved in telegram's cache.\n if (e.message === 'WEBFILE_NOT_AVAILABLE') {\n return Buffer.alloc(0);\n } else {\n throw e;\n }\n }\n }\n\n // region Invoking Telegram request\n /**\n * Invokes a MTProtoRequest (sends and receives it) and returns its result\n * @param request\n * @returns {Promise}\n */\n\n async invoke(request) {\n if (request.classType !== 'request') {\n throw new Error('You can only invoke MTProtoRequests');\n }\n // This causes issues for now because not enough utils\n // await request.resolve(this, utils)\n\n this._lastRequest = new Date().getTime();\n let attempt = 0;\n for (attempt = 0; attempt < this._requestRetries; attempt++) {\n const promise = this._sender.sendWithInvokeSupport(request);\n try {\n const result = await promise.promise;\n return result;\n } catch (e) {\n if (e instanceof errors.ServerError || e.message === 'RPC_CALL_FAIL'\n || e.message === 'RPC_MCGET_FAIL') {\n this._log.warn(`Telegram is having internal issues ${e.constructor.name}`);\n await sleep(2000);\n } else if (e instanceof errors.FloodWaitError || e instanceof errors.FloodTestPhoneWaitError) {\n if (e.seconds <= this.floodSleepLimit) {\n this._log.info(`Sleeping for ${e.seconds}s on flood wait`);\n await sleep(e.seconds * 1000);\n } else {\n throw e;\n }\n } else if (e instanceof errors.PhoneMigrateError || e instanceof errors.NetworkMigrateError\n || e instanceof errors.UserMigrateError) {\n this._log.info(`Phone migrated to ${e.newDc}`);\n const shouldRaise = e instanceof errors.PhoneMigrateError\n || e instanceof errors.NetworkMigrateError;\n if (shouldRaise && await checkAuthorization(this)) {\n throw e;\n }\n await this._switchDC(e.newDc);\n } else if (e instanceof errors.MsgWaitError) {\n // we need to resend this after the old one was confirmed.\n await promise.isReady();\n } else {\n throw e;\n }\n }\n }\n throw new Error(`Request was unsuccessful ${attempt} time(s)`);\n }\n\n async getMe() {\n try {\n return (await this.invoke(new requests.users\n .GetUsers({ id: [new constructors.InputUserSelf()] })))[0];\n } catch (e) {\n this._log.warn('error while getting me');\n this._log.warn(e);\n }\n return undefined;\n }\n\n async start(authParams) {\n if (!this.isConnected()) {\n await this.connect();\n }\n\n if (await checkAuthorization(this)) {\n return;\n }\n\n const apiCredentials = {\n apiId: this.apiId,\n apiHash: this.apiHash,\n };\n\n await authFlow(this, apiCredentials, authParams);\n }\n\n uploadFile(fileParams) {\n return uploadFile(this, fileParams);\n }\n\n updateTwoFaSettings(params) {\n return updateTwoFaSettings(this, params);\n }\n\n // event region\n addEventHandler(callback, event) {\n this._eventBuilders.push([event, callback]);\n }\n\n _handleUpdate(update) {\n // this.session.processEntities(update)\n // this._entityCache.add(update)\n\n if (update instanceof constructors.Updates || update instanceof constructors.UpdatesCombined) {\n // TODO deal with entities\n const entities = [];\n for (const x of [...update.users, ...update.chats]) {\n entities.push(x);\n }\n for (const u of update.updates) {\n this._processUpdate(u, update.updates, entities);\n }\n } else if (update instanceof constructors.UpdateShort) {\n this._processUpdate(update.update, undefined);\n } else {\n this._processUpdate(update, undefined);\n }\n // TODO add caching\n // this._stateCache.update(update)\n }\n\n _processUpdate(update, others, entities) {\n update._entities = entities || [];\n const args = {\n update,\n others,\n };\n this._dispatchUpdate(args);\n }\n\n // endregion\n\n // region private methods\n\n /**\n Gets a full entity from the given string, which may be a phone or\n a username, and processes all the found entities on the session.\n The string may also be a user link, or a channel/chat invite link.\n\n This method has the side effect of adding the found users to the\n session database, so it can be queried later without API calls,\n if this option is enabled on the session.\n\n Returns the found entity, or raises TypeError if not found.\n * @param string {string}\n * @returns {Promise}\n * @private\n */\n /* CONTEST\n async _getEntityFromString(string) {\n const phone = utils.parsePhone(string)\n if (phone) {\n try {\n for (const user of (await this.invoke(\n new requests.contacts.GetContacts(0))).users) {\n if (user.phone === phone) {\n return user\n }\n }\n } catch (e) {\n if (e.message === 'BOT_METHOD_INVALID') {\n throw new Error('Cannot get entity by phone number as a ' +\n 'bot (try using integer IDs, not strings)')\n }\n throw e\n }\n } else if (['me', 'this'].includes(string.toLowerCase())) {\n return this.getMe()\n } else {\n const { username, isJoinChat } = utils.parseUsername(string)\n if (isJoinChat) {\n const invite = await this.invoke(new requests.messages.CheckChatInvite({\n 'hash': username,\n }))\n if (invite instanceof constructors.ChatInvite) {\n throw new Error('Cannot get entity from a channel (or group) ' +\n 'that you are not part of. Join the group and retry',\n )\n } else if (invite instanceof constructors.ChatInviteAlready) {\n return invite.chat\n }\n } else if (username) {\n try {\n const result = await this.invoke(\n new requests.contacts.ResolveUsername(username))\n const pid = utils.getPeerId(result.peer, false)\n if (result.peer instanceof constructors.PeerUser) {\n for (const x of result.users) {\n if (x.id === pid) {\n return x\n }\n }\n } else {\n for (const x of result.chats) {\n if (x.id === pid) {\n return x\n }\n }\n }\n } catch (e) {\n if (e.message === 'USERNAME_NOT_OCCUPIED') {\n throw new Error(`No user has \"${username}\" as username`)\n }\n throw e\n }\n }\n }\n throw new Error(`Cannot find any entity corresponding to \"${string}\"`)\n }\n */\n // endregion\n\n // users region\n /**\n Turns the given entity into its input entity version.\n\n Most requests use this kind of :tl:`InputPeer`, so this is the most\n suitable call to make for those cases. **Generally you should let the\n library do its job** and don't worry about getting the input entity\n first, but if you're going to use an entity often, consider making the\n call:\n\n Arguments\n entity (`str` | `int` | :tl:`Peer` | :tl:`InputPeer`):\n If a username or invite link is given, **the library will\n use the cache**. This means that it's possible to be using\n a username that *changed* or an old invite link (this only\n happens if an invite link for a small group chat is used\n after it was upgraded to a mega-group).\n\n If the username or ID from the invite link is not found in\n the cache, it will be fetched. The same rules apply to phone\n numbers (``'+34 123456789'``) from people in your contact list.\n\n If an exact name is given, it must be in the cache too. This\n is not reliable as different people can share the same name\n and which entity is returned is arbitrary, and should be used\n only for quick tests.\n\n If a positive integer ID is given, the entity will be searched\n in cached users, chats or channels, without making any call.\n\n If a negative integer ID is given, the entity will be searched\n exactly as either a chat (prefixed with ``-``) or as a channel\n (prefixed with ``-100``).\n\n If a :tl:`Peer` is given, it will be searched exactly in the\n cache as either a user, chat or channel.\n\n If the given object can be turned into an input entity directly,\n said operation will be done.\n\n Unsupported types will raise ``TypeError``.\n\n If the entity can't be found, ``ValueError`` will be raised.\n\n Returns\n :tl:`InputPeerUser`, :tl:`InputPeerChat` or :tl:`InputPeerChannel`\n or :tl:`InputPeerSelf` if the parameter is ``'me'`` or ``'self'``.\n\n If you need to get the ID of yourself, you should use\n `get_me` with ``input_peer=True``) instead.\n\n Example\n .. code-block:: python\n\n // If you're going to use \"username\" often in your code\n // (make a lot of calls), consider getting its input entity\n // once, and then using the \"user\" everywhere instead.\n user = await client.get_input_entity('username')\n\n // The same applies to IDs, chats or channels.\n chat = await client.get_input_entity(-123456789)\n\n * @param peer\n * @returns {Promise<>}\n */\n\n /* CONTEST\n async getInputEntity(peer) {\n // Short-circuit if the input parameter directly maps to an InputPeer\n try {\n return utils.getInputPeer(peer)\n // eslint-disable-next-line no-empty\n } catch (e) {\n }\n // Next in priority is having a peer (or its ID) cached in-memory\n try {\n // 0x2d45687 == crc32(b'Peer')\n if (typeof peer === 'number' || peer.SUBCLASS_OF_ID === 0x2d45687) {\n if (this._entityCache.has(peer)) {\n return this._entityCache[peer]\n }\n }\n // eslint-disable-next-line no-empty\n } catch (e) {\n }\n // Then come known strings that take precedence\n if (['me', 'this'].includes(peer)) {\n return new constructors.InputPeerSelf()\n }\n // No InputPeer, cached peer, or known string. Fetch from disk cache\n try {\n return this.session.getInputEntity(peer)\n // eslint-disable-next-line no-empty\n } catch (e) {\n }\n // Only network left to try\n if (typeof peer === 'string') {\n return utils.getInputPeer(await this._getEntityFromString(peer))\n }\n // If we're a bot and the user has messaged us privately users.getUsers\n // will work with accessHash = 0. Similar for channels.getChannels.\n // If we're not a bot but the user is in our contacts, it seems to work\n // regardless. These are the only two special-cased requests.\n peer = utils.getPeer(peer)\n if (peer instanceof constructors.PeerUser) {\n const users = await this.invoke(new requests.users.GetUsers({\n id: [new constructors.InputUser({\n userId: peer.userId,\n accessHash: 0,\n })],\n }))\n if (users && !(users[0] instanceof constructors.UserEmpty)) {\n // If the user passed a valid ID they expect to work for\n // channels but would be valid for users, we get UserEmpty.\n // Avoid returning the invalid empty input peer for that.\n //\n // We *could* try to guess if it's a channel first, and if\n // it's not, work as a chat and try to validate it through\n // another request, but that becomes too much work.\n return utils.getInputPeer(users[0])\n }\n } else if (peer instanceof constructors.PeerChat) {\n return new constructors.InputPeerChat({\n chatId: peer.chatId,\n })\n } else if (peer instanceof constructors.PeerChannel) {\n try {\n const channels = await this.invoke(new requests.channels.GetChannels({\n id: [new constructors.InputChannel({\n channelId: peer.channelId,\n accessHash: 0,\n })],\n }))\n\n return utils.getInputPeer(channels.chats[0])\n // eslint-disable-next-line no-empty\n } catch (e) {\n console.log(e)\n }\n }\n throw new Error(`Could not find the input entity for ${peer.id || peer.channelId || peer.chatId || peer.userId}.\n Please read https://` +\n 'docs.telethon.dev/en/latest/concepts/entities.html to' +\n ' find out more details.',\n )\n }\n */\n async _dispatchUpdate(args = {\n update: undefined,\n others: undefined,\n channelId: undefined,\n ptsDate: undefined,\n }) {\n for (const [builder, callback] of this._eventBuilders) {\n const event = builder.build(args.update);\n if (event) {\n await callback(event);\n }\n }\n }\n\n isConnected() {\n if (this._sender) {\n if (this._sender.isConnected()) {\n return true;\n }\n }\n return false;\n }\n}\n\nfunction timeout(promise, ms) {\n return Promise.race([\n promise,\n Helpers.sleep(ms)\n .then(() => Promise.reject(new Error('TIMEOUT'))),\n ]);\n}\n\nasync function attempts(cb, times, pause) {\n for (let i = 0; i < times; i++) {\n try {\n // We need to `return await` here so it can be caught locally\n // eslint-disable-next-line no-return-await\n return await cb();\n } catch (err) {\n if (i === times - 1) {\n throw err;\n }\n\n await Helpers.sleep(pause);\n }\n }\n return undefined;\n}\n\nmodule.exports = TelegramClient;\n","// eslint-disable-next-line import/no-named-default\nimport { default as Api } from '../tl/api';\nimport TelegramClient from './TelegramClient';\nimport utils from '../Utils';\nimport { sleep } from '../Helpers';\nimport { computeCheck as computePasswordSrpCheck } from '../Password';\n\nexport interface UserAuthParams {\n phoneNumber: string | (() => Promise);\n phoneCode: (isCodeViaApp?: boolean) => Promise;\n password: (hint?: string) => Promise;\n firstAndLastNames: () => Promise<[string, string?]>;\n qrCode: (qrCode: { token: Buffer; expires: number }) => Promise;\n onError: (err: Error) => void;\n forceSMS?: boolean;\n initialMethod?: 'phoneNumber' | 'qrCode';\n}\n\nexport interface BotAuthParams {\n botAuthToken: string;\n}\n\ninterface ApiCredentials {\n apiId: number;\n apiHash: string;\n}\n\nconst DEFAULT_INITIAL_METHOD = 'phoneNumber';\nconst QR_CODE_TIMEOUT = 30000;\n\nexport async function authFlow(\n client: TelegramClient,\n apiCredentials: ApiCredentials,\n authParams: UserAuthParams | BotAuthParams,\n) {\n let me: Api.TypeUser;\n\n if ('botAuthToken' in authParams) {\n me = await signInBot(client, apiCredentials, authParams);\n } else {\n const { initialMethod = DEFAULT_INITIAL_METHOD } = authParams;\n\n if (initialMethod === 'phoneNumber') {\n me = await signInUser(client, apiCredentials, authParams);\n } else {\n me = await signInUserWithQrCode(client, apiCredentials, authParams);\n }\n }\n\n client._log.info('Signed in successfully as', utils.getDisplayName(me));\n}\n\nexport async function checkAuthorization(client: TelegramClient) {\n try {\n await client.invoke(new Api.updates.GetState());\n return true;\n } catch (e) {\n if (e.message === 'Disconnect') throw e;\n return false;\n }\n}\n\nasync function signInUser(\n client: TelegramClient, apiCredentials: ApiCredentials, authParams: UserAuthParams,\n): Promise {\n let phoneNumber;\n let phoneCodeHash;\n let isCodeViaApp = false;\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n try {\n if (typeof authParams.phoneNumber === 'function') {\n try {\n phoneNumber = await authParams.phoneNumber();\n } catch (err) {\n if (err.message === 'RESTART_AUTH_WITH_QR') {\n return signInUserWithQrCode(client, apiCredentials, authParams);\n }\n\n throw err;\n }\n } else {\n phoneNumber = authParams.phoneNumber;\n }\n const sendCodeResult = await sendCode(client, apiCredentials, phoneNumber, authParams.forceSMS);\n phoneCodeHash = sendCodeResult.phoneCodeHash;\n isCodeViaApp = sendCodeResult.isCodeViaApp;\n\n if (typeof phoneCodeHash !== 'string') {\n throw new Error('Failed to retrieve phone code hash');\n }\n\n break;\n } catch (err) {\n if (typeof authParams.phoneNumber !== 'function') {\n throw err;\n }\n\n authParams.onError(err);\n }\n }\n\n let phoneCode;\n let isRegistrationRequired = false;\n let termsOfService;\n\n // eslint-disable-next-line no-constant-condition\n while (1) {\n try {\n try {\n phoneCode = await authParams.phoneCode(isCodeViaApp);\n } catch (err) {\n // This is the support for changing phone number from the phone code screen.\n if (err.message === 'RESTART_AUTH') {\n return signInUser(client, apiCredentials, authParams);\n }\n }\n\n if (!phoneCode) {\n throw new Error('Code is empty');\n }\n\n // May raise PhoneCodeEmptyError, PhoneCodeExpiredError,\n // PhoneCodeHashEmptyError or PhoneCodeInvalidError.\n const result = await client.invoke(new Api.auth.SignIn({\n phoneNumber,\n phoneCodeHash,\n phoneCode,\n }));\n\n if (result instanceof Api.auth.AuthorizationSignUpRequired) {\n isRegistrationRequired = true;\n termsOfService = result.termsOfService;\n break;\n }\n\n return result.user;\n } catch (err) {\n if (err.message === 'SESSION_PASSWORD_NEEDED') {\n return signInWithPassword(client, apiCredentials, authParams);\n } else {\n authParams.onError(err);\n }\n }\n }\n\n if (isRegistrationRequired) {\n // eslint-disable-next-line no-constant-condition\n while (1) {\n try {\n const [firstName, lastName] = await authParams.firstAndLastNames();\n if (!firstName) {\n throw new Error('First name is required');\n }\n\n const { user } = await client.invoke(new Api.auth.SignUp({\n phoneNumber,\n phoneCodeHash,\n firstName,\n lastName,\n })) as Api.auth.Authorization;\n\n if (termsOfService) {\n // This is a violation of Telegram rules: the user should be presented with and accept TOS.\n await client.invoke(new Api.help.AcceptTermsOfService({ id: termsOfService.id }));\n }\n\n return user;\n } catch (err) {\n authParams.onError(err);\n }\n }\n }\n\n authParams.onError(new Error('Auth failed'));\n return signInUser(client, apiCredentials, authParams);\n}\n\nasync function signInUserWithQrCode(\n client: TelegramClient, apiCredentials: ApiCredentials, authParams: UserAuthParams,\n): Promise {\n let isScanningComplete = false;\n\n const inputPromise = (async () => {\n // eslint-disable-next-line no-constant-condition\n while (1) {\n if (isScanningComplete) {\n break;\n }\n\n const result = await client.invoke(new Api.auth.ExportLoginToken({\n apiId: Number(process.env.TELEGRAM_T_API_ID),\n apiHash: process.env.TELEGRAM_T_API_HASH,\n exceptIds: [],\n }));\n if (!(result instanceof Api.auth.LoginToken)) {\n throw new Error('Unexpected');\n }\n\n const { token, expires } = result;\n\n await Promise.race([\n authParams.qrCode({ token, expires }),\n sleep(QR_CODE_TIMEOUT),\n ]);\n }\n })();\n\n const updatePromise = new Promise((resolve) => {\n client.addEventHandler((update: Api.TypeUpdate) => {\n if (update instanceof Api.UpdateLoginToken) {\n resolve();\n }\n }, { build: (update: object) => update });\n });\n\n try {\n // Either we receive an update that QR is successfully scanned,\n // or we receive a rejection caused by user going back to the regular auth form\n await Promise.race([updatePromise, inputPromise]);\n } catch (err) {\n if (err.message === 'RESTART_AUTH') {\n return await signInUser(client, apiCredentials, authParams);\n }\n\n throw err;\n } finally {\n isScanningComplete = true;\n }\n\n try {\n const result2 = await client.invoke(new Api.auth.ExportLoginToken({\n apiId: Number(process.env.TELEGRAM_T_API_ID),\n apiHash: process.env.TELEGRAM_T_API_HASH,\n exceptIds: [],\n }));\n\n if (result2 instanceof Api.auth.LoginTokenSuccess && result2.authorization instanceof Api.auth.Authorization) {\n return result2.authorization.user;\n } else if (result2 instanceof Api.auth.LoginTokenMigrateTo) {\n await client._switchDC(result2.dcId);\n const migratedResult = await client.invoke(new Api.auth.ImportLoginToken({\n token: result2.token,\n }));\n\n if (migratedResult instanceof Api.auth.LoginTokenSuccess\n && migratedResult.authorization instanceof Api.auth.Authorization) {\n return migratedResult.authorization.user;\n }\n }\n } catch (err) {\n if (err.message === 'SESSION_PASSWORD_NEEDED') {\n return signInWithPassword(client, apiCredentials, authParams);\n }\n\n throw err;\n }\n\n // This is a workaround for TypeScript (never actually reached)\n // eslint-disable-next-line no-throw-literal\n throw undefined;\n}\n\nasync function sendCode(\n client: TelegramClient, apiCredentials: ApiCredentials, phoneNumber: string, forceSMS = false,\n): Promise<{\n phoneCodeHash: string;\n isCodeViaApp: boolean;\n }> {\n try {\n const { apiId, apiHash } = apiCredentials;\n const sendResult = await client.invoke(new Api.auth.SendCode({\n phoneNumber,\n apiId,\n apiHash,\n settings: new Api.CodeSettings(),\n }));\n\n // If we already sent a SMS, do not resend the phoneCode (hash may be empty)\n if (!forceSMS || (sendResult.type instanceof Api.auth.SentCodeTypeSms)) {\n return {\n phoneCodeHash: sendResult.phoneCodeHash,\n isCodeViaApp: sendResult.type instanceof Api.auth.SentCodeTypeApp,\n };\n }\n\n const resendResult = await client.invoke(new Api.auth.ResendCode({\n phoneNumber,\n phoneCodeHash: sendResult.phoneCodeHash,\n }));\n\n return {\n phoneCodeHash: resendResult.phoneCodeHash,\n isCodeViaApp: resendResult.type instanceof Api.auth.SentCodeTypeApp,\n };\n } catch (err) {\n if (err.message === 'AUTH_RESTART') {\n return sendCode(client, apiCredentials, phoneNumber, forceSMS);\n } else {\n throw err;\n }\n }\n}\n\nasync function signInWithPassword(\n client: TelegramClient, apiCredentials: ApiCredentials, authParams: UserAuthParams,\n): Promise {\n // eslint-disable-next-line no-constant-condition\n while (1) {\n try {\n const passwordSrpResult = await client.invoke(new Api.account.GetPassword());\n const password = await authParams.password(passwordSrpResult.hint);\n if (!password) {\n throw new Error('Password is empty');\n }\n\n const passwordSrpCheck = await computePasswordSrpCheck(passwordSrpResult, password);\n const { user } = await client.invoke(new Api.auth.CheckPassword({\n password: passwordSrpCheck,\n })) as Api.auth.Authorization;\n\n return user;\n } catch (err) {\n authParams.onError(err);\n }\n }\n\n // eslint-disable-next-line no-unreachable\n return undefined!; // Never reached (TypeScript fix)\n}\n\nasync function signInBot(client: TelegramClient, apiCredentials: ApiCredentials, authParams: BotAuthParams) {\n const { apiId, apiHash } = apiCredentials;\n const { botAuthToken } = authParams;\n\n const { user } = await client.invoke(new Api.auth.ImportBotAuthorization({\n apiId,\n apiHash,\n botAuthToken,\n })) as Api.auth.Authorization;\n\n return user;\n}\n","// eslint-disable-next-line import/no-named-default\nimport { default as Api } from '../tl/api';\nimport TelegramClient from './TelegramClient';\nimport { getAppropriatedPartSize } from '../Utils';\nimport { sleep, createDeferred } from '../Helpers';\nimport errors from '../errors';\n\nexport interface progressCallback {\n isCanceled?: boolean;\n acceptsBuffer?: boolean;\n\n (\n progress: number, // Float between 0 and 1.\n ...args: any[]\n ): void;\n}\n\nexport interface DownloadFileParams {\n dcId: number;\n fileSize: number;\n workers?: number;\n partSizeKb?: number;\n start?: number;\n end?: number;\n progressCallback?: progressCallback;\n}\n\ninterface Deferred {\n promise: Promise;\n resolve: (value?: any) => void;\n}\n\n// Chunk sizes for `upload.getFile` must be multiple of the smallest size\nconst MIN_CHUNK_SIZE = 4096;\nconst DEFAULT_CHUNK_SIZE = 64; // kb\nconst ONE_MB = 1024 * 1024;\nconst DISCONNECT_SLEEP = 1000;\n\n\nclass Foreman {\n private deferred: Deferred | undefined;\n\n private activeWorkers = 0;\n\n constructor(private maxWorkers: number) {\n }\n\n requestWorker() {\n this.activeWorkers++;\n\n if (this.activeWorkers > this.maxWorkers) {\n this.deferred = createDeferred();\n return this.deferred!.promise;\n }\n\n return Promise.resolve();\n }\n\n releaseWorker() {\n this.activeWorkers--;\n\n if (this.deferred && (this.activeWorkers <= this.maxWorkers)) {\n this.deferred.resolve();\n }\n }\n}\n\nexport async function downloadFile(\n client: TelegramClient,\n inputLocation: Api.InputFileLocation,\n fileParams: DownloadFileParams,\n) {\n let {\n partSizeKb, end,\n } = fileParams;\n const {\n fileSize, workers = 1,\n } = fileParams;\n const { dcId, progressCallback, start = 0 } = fileParams;\n\n end = end && end < fileSize ? end : fileSize - 1;\n\n if (!partSizeKb) {\n partSizeKb = fileSize ? getAppropriatedPartSize(fileSize) : DEFAULT_CHUNK_SIZE;\n }\n\n const partSize = partSizeKb * 1024;\n const partsCount = end ? Math.ceil((end - start) / partSize) : 1;\n\n if (partSize % MIN_CHUNK_SIZE !== 0) {\n throw new Error(`The part size must be evenly divisible by ${MIN_CHUNK_SIZE}`);\n }\n\n client._log.info(`Downloading file in chunks of ${partSize} bytes`);\n\n const foreman = new Foreman(workers);\n const promises: Promise[] = [];\n let offset = start;\n // Used for files with unknown size and for manual cancellations\n let hasEnded = false;\n\n let progress = 0;\n if (progressCallback) {\n progressCallback(progress);\n }\n\n // Preload sender\n await client.getSender(dcId);\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n let limit = partSize;\n let isPrecise = false;\n\n if (Math.floor(offset / ONE_MB) !== Math.floor((offset + limit - 1) / ONE_MB)) {\n limit = ONE_MB - (offset % ONE_MB);\n isPrecise = true;\n }\n\n await foreman.requestWorker();\n\n if (hasEnded) {\n foreman.releaseWorker();\n break;\n }\n\n // eslint-disable-next-line no-loop-func\n promises.push((async (offsetMemo: number) => {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n let sender;\n try {\n sender = await client.getSender(dcId);\n const result = await sender.send(new Api.upload.GetFile({\n location: inputLocation,\n offset: offsetMemo,\n limit,\n precise: isPrecise || undefined,\n }));\n\n if (progressCallback) {\n if (progressCallback.isCanceled) {\n throw new Error('USER_CANCELED');\n }\n\n progress += (1 / partsCount);\n progressCallback(progress);\n }\n\n if (!end && (result.bytes.length < limit)) {\n hasEnded = true;\n }\n\n foreman.releaseWorker();\n\n return result.bytes;\n } catch (err) {\n if (sender && !sender.isConnected()) {\n await sleep(DISCONNECT_SLEEP);\n continue;\n } else if (err instanceof errors.FloodWaitError) {\n await sleep(err.seconds * 1000);\n continue;\n }\n\n foreman.releaseWorker();\n\n hasEnded = true;\n throw err;\n }\n }\n })(offset));\n\n offset += limit;\n\n if (end && (offset > end)) {\n break;\n }\n }\n const results = await Promise.all(promises);\n const buffers = results.filter(Boolean);\n const totalLength = end ? (end + 1) - start : undefined;\n return Buffer.concat(buffers, totalLength);\n}\n","// eslint-disable-next-line import/no-named-default\nimport { default as Api } from '../tl/api';\n\nimport TelegramClient from './TelegramClient';\nimport { generateRandomBytes, readBigIntFromBuffer, sleep } from '../Helpers';\nimport { getAppropriatedPartSize } from '../Utils';\nimport errors from '../errors';\n\ninterface OnProgress {\n isCanceled?: boolean;\n\n // Float between 0 and 1.\n (progress: number): void;\n}\n\nexport interface UploadFileParams {\n file: File;\n workers: number;\n onProgress?: OnProgress;\n}\n\nconst KB_TO_BYTES = 1024;\nconst LARGE_FILE_THRESHOLD = 10 * 1024 * 1024;\nconst DISCONNECT_SLEEP = 1000;\n\nexport async function uploadFile(\n client: TelegramClient,\n fileParams: UploadFileParams,\n): Promise {\n const { file, onProgress } = fileParams;\n let { workers } = fileParams;\n\n const { name, size } = file;\n const fileId = readBigIntFromBuffer(generateRandomBytes(8), true, true);\n const isLarge = size > LARGE_FILE_THRESHOLD;\n\n const partSize = getAppropriatedPartSize(size) * KB_TO_BYTES;\n const partCount = Math.floor((size + partSize - 1) / partSize);\n const buffer = Buffer.from(await fileToBuffer(file));\n\n // Make sure a new sender can be created before starting upload\n await client.getSender(client.session.dcId);\n\n if (!workers || !size) {\n workers = 1;\n }\n if (workers >= partCount) {\n workers = partCount;\n }\n\n let progress = 0;\n if (onProgress) {\n onProgress(progress);\n }\n\n for (let i = 0; i < partCount; i += workers) {\n const sendingParts = [];\n let end = i + workers;\n if (end > partCount) {\n end = partCount;\n }\n\n for (let j = i; j < end; j++) {\n const bytes = buffer.slice(j * partSize, (j + 1) * partSize);\n\n // eslint-disable-next-line no-loop-func\n sendingParts.push((async (jMemo: number, bytesMemo: Buffer) => {\n while (true) {\n let sender;\n try {\n // We always upload from the DC we are in\n sender = await client.getSender(client.session.dcId);\n await sender.send(\n isLarge\n ? new Api.upload.SaveBigFilePart({\n fileId,\n filePart: jMemo,\n fileTotalParts: partCount,\n bytes: bytesMemo,\n })\n : new Api.upload.SaveFilePart({\n fileId,\n filePart: jMemo,\n bytes: bytesMemo,\n }),\n );\n } catch (err) {\n if (sender && !sender.isConnected()) {\n await sleep(DISCONNECT_SLEEP);\n continue;\n } else if (err instanceof errors.FloodWaitError) {\n await sleep(err.seconds * 1000);\n continue;\n }\n throw err;\n }\n\n if (onProgress) {\n if (onProgress.isCanceled) {\n throw new Error('USER_CANCELED');\n }\n\n progress += (1 / partCount);\n onProgress(progress);\n }\n break;\n }\n })(j, bytes));\n }\n\n await Promise.all(sendingParts);\n }\n\n return isLarge\n ? new Api.InputFileBig({\n id: fileId,\n parts: partCount,\n name,\n })\n : new Api.InputFile({\n id: fileId,\n parts: partCount,\n name,\n md5Checksum: '', // This is not a \"flag\", so not sure if we can make it optional.\n });\n}\n\nfunction fileToBuffer(file: File) {\n return new Response(file).arrayBuffer();\n}\n","const {\n sha1,\n toSignedLittleBuffer,\n readBufferFromBigInt,\n readBigIntFromBuffer,\n} = require('../Helpers');\nconst BinaryReader = require('../extensions/BinaryReader');\nconst { sleep } = require('../Helpers');\n\nclass AuthKey {\n constructor(value, hash) {\n if (!hash || !value) {\n return;\n }\n this._key = value;\n this._hash = hash;\n const reader = new BinaryReader(hash);\n this.auxHash = reader.readLong(false);\n reader.read(4);\n this.keyId = reader.readLong(false);\n }\n\n async setKey(value) {\n if (!value) {\n this._key = undefined;\n this.auxHash = undefined;\n this.keyId = undefined;\n this._hash = undefined;\n return;\n }\n if (value instanceof AuthKey) {\n this._key = value._key;\n this.auxHash = value.auxHash;\n this.keyId = value.keyId;\n this._hash = value._hash;\n return;\n }\n this._key = value;\n this._hash = await sha1(this._key);\n const reader = new BinaryReader(this._hash);\n this.auxHash = reader.readLong(false);\n reader.read(4);\n this.keyId = reader.readLong(false);\n }\n\n async waitForKey() {\n while (!this.keyId) {\n await sleep(20);\n }\n }\n\n getKey() {\n return this._key;\n }\n\n // TODO : This doesn't really fit here, it's only used in authentication\n\n /**\n * Calculates the new nonce hash based on the current class fields' values\n * @param newNonce\n * @param number\n * @returns {bigint}\n */\n async calcNewNonceHash(newNonce, number) {\n newNonce = toSignedLittleBuffer(newNonce, 32);\n const n = Buffer.alloc(1);\n n.writeUInt8(number, 0);\n const data = Buffer.concat([newNonce,\n Buffer.concat([n, readBufferFromBigInt(this.auxHash, 8, true)])]);\n\n // Calculates the message key from the given data\n const shaData = (await sha1(data)).slice(4, 20);\n return readBigIntFromBuffer(shaData, true, true);\n }\n\n equals(other) {\n return other instanceof this.constructor && this._key && other.getKey() && other.getKey()\n .equals(this._key);\n }\n}\n\nmodule.exports = AuthKey;\n","const crypto = require('./crypto');\n\nclass CTR {\n constructor(key, iv) {\n if (!Buffer.isBuffer(key) || !Buffer.isBuffer(iv) || iv.length !== 16) {\n throw new Error('Key and iv need to be a buffer');\n }\n\n this.cipher = crypto.createCipheriv('AES-256-CTR', key, iv);\n }\n\n encrypt(data) {\n return Buffer.from(this.cipher.update(data));\n }\n}\n\nmodule.exports = CTR;\n","const BigInt = require('big-integer');\nconst { modExp } = require('../Helpers');\n\nclass Factorizator {\n /**\n * Calculates the greatest common divisor\n * @param a {BigInteger}\n * @param b {BigInteger}\n * @returns {BigInteger}\n */\n static gcd(a, b) {\n while (b.neq(BigInt.zero)) {\n const temp = b;\n b = a.remainder(b);\n a = temp;\n }\n return a;\n }\n\n /**\n * Factorizes the given number and returns both the divisor and the number divided by the divisor\n * @param pq {BigInteger}\n * @returns {{p: *, q: *}}\n */\n static factorize(pq) {\n if (pq.remainder(2)\n .equals(BigInt.zero)) {\n return {\n p: BigInt(2),\n q: pq.divide(BigInt(2)),\n };\n }\n let y = BigInt.randBetween(BigInt(1), pq.minus(1));\n const c = BigInt.randBetween(BigInt(1), pq.minus(1));\n const m = BigInt.randBetween(BigInt(1), pq.minus(1));\n\n let g = BigInt.one;\n let r = BigInt.one;\n let q = BigInt.one;\n let x = BigInt.zero;\n let ys = BigInt.zero;\n let k;\n\n while (g.eq(BigInt.one)) {\n x = y;\n for (let i = 0; BigInt(i)\n .lesser(r); i++) {\n y = (modExp(y, BigInt(2), pq)).add(c)\n .remainder(pq);\n }\n k = BigInt.zero;\n\n while (k.lesser(r) && g.eq(BigInt.one)) {\n ys = y;\n const condition = BigInt.min(m, r.minus(k));\n for (let i = 0; BigInt(i)\n .lesser(condition); i++) {\n y = (modExp(y, BigInt(2), pq)).add(c)\n .remainder(pq);\n q = q.multiply(x.minus(y)\n .abs())\n .remainder(pq);\n }\n g = Factorizator.gcd(q, pq);\n k = k.add(m);\n }\n\n r = r.multiply(2);\n }\n\n\n if (g.eq(pq)) {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n ys = (modExp(ys, BigInt(2), pq)).add(c)\n .remainder(pq);\n g = Factorizator.gcd(x.minus(ys)\n .abs(), pq);\n\n if (g.greater(1)) {\n break;\n }\n }\n }\n const p = g;\n q = pq.divide(g);\n return p < q ? {\n p,\n q,\n } : {\n p: q,\n q: p,\n };\n }\n}\n\nmodule.exports = Factorizator;\n","const { IGE: AESIGE } = require('@cryptography/aes');\nconst Helpers = require('../Helpers');\n\n\nclass IGENEW {\n constructor(key, iv) {\n this.ige = new AESIGE(key, iv);\n }\n\n /**\n * Decrypts the given text in 16-bytes blocks by using the given key and 32-bytes initialization vector\n * @param cipherText {Buffer}\n * @returns {Buffer}\n */\n decryptIge(cipherText) {\n return Helpers.convertToLittle(this.ige.decrypt(cipherText));\n }\n\n /**\n * Encrypts the given text in 16-bytes blocks by using the given key and 32-bytes initialization vector\n * @param plainText {Buffer}\n * @returns {Buffer}\n */\n encryptIge(plainText) {\n const padding = plainText.length % 16;\n if (padding) {\n plainText = Buffer.concat([plainText, Helpers.generateRandomBytes(16 - padding)]);\n }\n\n return Helpers.convertToLittle(this.ige.encrypt(plainText));\n }\n}\n\nmodule.exports = IGENEW;\n","/**\n * Uint32Array -> ArrayBuffer (low-endian os)\n */\nexport function i2abLow(buf: Uint32Array): ArrayBuffer {\n const uint8 = new Uint8Array(buf.length * 4);\n let i = 0;\n\n for (let j = 0; j < buf.length; j++) {\n const int = buf[j];\n\n uint8[i++] = int >>> 24;\n uint8[i++] = (int >> 16) & 0xFF;\n uint8[i++] = (int >> 8) & 0xFF;\n uint8[i++] = int & 0xFF;\n }\n\n return uint8.buffer;\n}\n\n/**\n * Uint32Array -> ArrayBuffer (big-endian os)\n */\nexport function i2abBig(buf: Uint32Array): ArrayBuffer {\n return buf.buffer;\n}\n\n/**\n * ArrayBuffer -> Uint32Array (low-endian os)\n */\nexport function ab2iLow(ab: ArrayBuffer | SharedArrayBuffer | Uint8Array): Uint32Array {\n const uint8 = new Uint8Array(ab);\n const buf = new Uint32Array(uint8.length / 4);\n\n for (let i = 0; i < uint8.length; i += 4) {\n buf[i / 4] = (\n uint8[i] << 24\n ^ uint8[i + 1] << 16\n ^ uint8[i + 2] << 8\n ^ uint8[i + 3]\n );\n }\n\n return buf;\n}\n\n/**\n * ArrayBuffer -> Uint32Array (big-endian os)\n */\nexport function ab2iBig(ab: ArrayBuffer | SharedArrayBuffer | Uint8Array): Uint32Array {\n return new Uint32Array(ab);\n}\n\nexport const isBigEndian = new Uint8Array(new Uint32Array([0x01020304]))[0] === 0x01;\nexport const i2ab = isBigEndian ? i2abBig : i2abLow;\nexport const ab2i = isBigEndian ? ab2iBig : ab2iLow;\n","const AES = require('@cryptography/aes').default;\nconst {\n i2ab,\n ab2i,\n} = require('./converters');\nconst { getWords } = require('./words');\n\nclass Counter {\n constructor(initialValue) {\n this.setBytes(initialValue);\n }\n\n setBytes(bytes) {\n bytes = Buffer.from(bytes);\n this._counter = bytes;\n }\n\n increment() {\n for (let i = 15; i >= 0; i--) {\n if (this._counter[i] === 255) {\n this._counter[i] = 0;\n } else {\n this._counter[i]++;\n break;\n }\n }\n }\n}\n\nclass CTR {\n constructor(key, counter) {\n if (!(counter instanceof Counter)) {\n counter = new Counter(counter);\n }\n\n this._counter = counter;\n\n this._remainingCounter = undefined;\n this._remainingCounterIndex = 16;\n\n this._aes = new AES(getWords(key));\n }\n\n update(plainText) {\n return this.encrypt(plainText);\n }\n\n encrypt(plainText) {\n const encrypted = Buffer.from(plainText);\n\n for (let i = 0; i < encrypted.length; i++) {\n if (this._remainingCounterIndex === 16) {\n this._remainingCounter = Buffer.from(i2ab(this._aes.encrypt(ab2i(this._counter._counter))));\n this._remainingCounterIndex = 0;\n this._counter.increment();\n }\n encrypted[i] ^= this._remainingCounter[this._remainingCounterIndex++];\n }\n\n return encrypted;\n }\n}\n\n// endregion\nfunction createDecipheriv(algorithm, key, iv) {\n if (algorithm.includes('ECB')) {\n throw new Error('Not supported');\n } else {\n return new CTR(key, iv);\n }\n}\n\nfunction createCipheriv(algorithm, key, iv) {\n if (algorithm.includes('ECB')) {\n throw new Error('Not supported');\n } else {\n return new CTR(key, iv);\n }\n}\n\nfunction randomBytes(count) {\n const bytes = new Uint8Array(count);\n crypto.getRandomValues(bytes);\n return bytes;\n}\n\nclass Hash {\n constructor(algorithm) {\n this.algorithm = algorithm;\n }\n\n update(data) {\n // We shouldn't be needing new Uint8Array but it doesn't\n // work without it\n this.data = new Uint8Array(data);\n }\n\n\n async digest() {\n if (this.algorithm === 'sha1') {\n // eslint-disable-next-line no-restricted-globals\n return Buffer.from(await self.crypto.subtle.digest('SHA-1', this.data));\n } else if (this.algorithm === 'sha256') {\n // eslint-disable-next-line no-restricted-globals\n return Buffer.from(await self.crypto.subtle.digest('SHA-256', this.data));\n }\n return undefined;\n }\n}\n\nasync function pbkdf2(password, salt, iterations) {\n const passwordKey = await crypto.subtle.importKey('raw', password,\n { name: 'PBKDF2' }, false, ['deriveBits']);\n return Buffer.from(await crypto.subtle.deriveBits({\n name: 'PBKDF2',\n hash: 'SHA-512',\n salt,\n iterations,\n }, passwordKey, 512));\n}\n\nfunction createHash(algorithm) {\n return new Hash(algorithm);\n}\n\nmodule.exports = {\n createCipheriv,\n createDecipheriv,\n randomBytes,\n createHash,\n pbkdf2,\n};\n","/*\n * Imported from https://github.com/spalt08/cryptography/blob/master/packages/aes/src/utils/words.ts\n */\n\nexport function s2i(str: string, pos: number) {\n return (\n str.charCodeAt(pos) << 24\n ^ str.charCodeAt(pos + 1) << 16\n ^ str.charCodeAt(pos + 2) << 8\n ^ str.charCodeAt(pos + 3)\n );\n}\n\n/**\n * Helper function for transforming string key to Uint32Array\n */\nexport function getWords(key: string | Uint8Array | Uint32Array) {\n if (key instanceof Uint32Array) {\n return key;\n }\n\n if (typeof key === 'string') {\n if (key.length % 4 !== 0) for (let i = key.length % 4; i <= 4; i++) key += '\\0x00';\n\n const buf = new Uint32Array(key.length / 4);\n for (let i = 0; i < key.length; i += 4) buf[i / 4] = s2i(key, i);\n\n return buf;\n }\n\n if (key instanceof Uint8Array) {\n const buf = new Uint32Array(key.length / 4);\n\n for (let i = 0; i < key.length; i += 4) {\n buf[i / 4] = (\n key[i] << 24\n ^ key[i + 1] << 16\n ^ key[i + 2] << 8\n ^ key[i + 3]\n );\n }\n\n return buf;\n }\n\n throw new Error('Unable to create 32-bit words');\n}\n\nexport function xor(left: Uint32Array, right: Uint32Array, to = left) {\n for (let i = 0; i < left.length; i++) to[i] = left[i] ^ right[i];\n}\n","/**\n * Errors not related to the Telegram API itself\n */\n\n\n/**\n * Occurs when a read operation was cancelled.\n */\nclass ReadCancelledError extends Error {\n constructor() {\n super('The read operation was cancelled.');\n }\n}\n\n/**\n * Occurs when a type is not found, for example,\n * when trying to read a TLObject with an invalid constructor code.\n */\nclass TypeNotFoundError extends Error {\n constructor(invalidConstructorId, remaining) {\n super(`Could not find a matching Constructor ID for the TLObject that was supposed to be\n read with ID ${invalidConstructorId}. Most likely, a TLObject was trying to be read when\n it should not be read. Remaining bytes: ${remaining.length}`);\n if (typeof alert !== 'undefined') {\n // eslint-disable-next-line no-alert\n alert(`Missing MTProto Entity: Please, make sure to add TL definition for ID ${invalidConstructorId}`);\n }\n this.invalidConstructorId = invalidConstructorId;\n this.remaining = remaining;\n }\n}\n\n/**\n * Occurs when using the TCP full mode and the checksum of a received\n * packet doesn't match the expected checksum.\n */\nclass InvalidChecksumError extends Error {\n constructor(checksum, validChecksum) {\n super(`Invalid checksum (${checksum} when ${validChecksum} was expected). This packet should be skipped.`);\n this.checksum = checksum;\n this.validChecksum = validChecksum;\n }\n}\n\n/**\n * Occurs when the buffer is invalid, and may contain an HTTP error code.\n * For instance, 404 means \"forgotten/broken authorization key\", while\n */\nclass InvalidBufferError extends Error {\n constructor(payload) {\n let code;\n if (payload.length === 4) {\n code = -payload.readInt32LE(0);\n super(`Invalid response buffer (HTTP code ${code})`);\n } else {\n super(`Invalid response buffer (too short ${payload})`);\n }\n this.code = code;\n this.payload = payload;\n }\n}\n\n/**\n * Generic security error, mostly used when generating a new AuthKey.\n */\nclass SecurityError extends Error {\n constructor(...args) {\n if (!args.length) {\n args = ['A security check failed.'];\n }\n super(...args);\n }\n}\n\n/**\n * Occurs when there's a hash mismatch between the decrypted CDN file\n * and its expected hash.\n */\nclass CdnFileTamperedError extends SecurityError {\n constructor() {\n super('The CDN file has been altered and its download cancelled.');\n }\n}\n\n/**\n * Occurs when handling a badMessageNotification\n */\nclass BadMessageError extends Error {\n static ErrorMessages = {\n 16:\n 'msg_id too low (most likely, client time is wrong it would be worthwhile to '\n + 'synchronize it using msg_id notifications and re-send the original message '\n + 'with the “correct” msg_id or wrap it in a container with a new msg_id if the '\n + 'original message had waited too long on the client to be transmitted).',\n\n 17:\n 'msg_id too high (similar to the previous case, the client time has to be '\n + 'synchronized, and the message re-sent with the correct msg_id).',\n\n 18:\n 'Incorrect two lower order msg_id bits (the server expects client message msg_id '\n + 'to be divisible by 4).',\n\n 19: 'Container msg_id is the same as msg_id of a previously received message (this must never happen).',\n\n 20:\n 'Message too old, and it cannot be verified whether the server has received a '\n + 'message with this msg_id or not.',\n\n 32:\n 'msg_seqno too low (the server has already received a message with a lower '\n + 'msg_id but with either a higher or an equal and odd seqno).',\n\n 33:\n 'msg_seqno too high (similarly, there is a message with a higher msg_id but with '\n + 'either a lower or an equal and odd seqno).',\n\n 34: 'An even msg_seqno expected (irrelevant message), but odd received.',\n\n 35: 'Odd msg_seqno expected (relevant message), but even received.',\n\n 48:\n 'Incorrect server salt (in this case, the bad_server_salt response is received with '\n + 'the correct salt, and the message is to be re-sent with it).',\n\n 64: 'Invalid container.',\n };\n\n constructor(request, code) {\n let errorMessage = BadMessageError.ErrorMessages[code]\n || `Unknown error code (this should not happen): ${code}.`;\n errorMessage += ` Caused by ${request.className}`;\n super(errorMessage);\n this.message = errorMessage;\n this.code = code;\n }\n}\n\n// TODO : Support multi errors.\n\nmodule.exports = {\n ReadCancelledError,\n TypeNotFoundError,\n InvalidChecksumError,\n InvalidBufferError,\n SecurityError,\n CdnFileTamperedError,\n BadMessageError,\n};\n","/**\n * Base class for all Remote Procedure Call errors.\n */\nclass RPCError extends Error {\n constructor(message, request, code = undefined) {\n super(\n 'RPCError {0}: {1}{2}'\n .replace('{0}', code)\n .replace('{1}', message)\n .replace('{2}', RPCError._fmtRequest(request)),\n );\n this.code = code;\n this.message = message;\n }\n\n static _fmtRequest(request) {\n // TODO fix this\n if (request) {\n return ` (caused by ${request.className})`;\n } else {\n return '';\n }\n }\n}\n\n/**\n * The request must be repeated, but directed to a different data center.\n */\nclass InvalidDCError extends RPCError {\n constructor(request, message, code) {\n super(message, request, code);\n this.code = code || 303;\n this.message = message || 'ERROR_SEE_OTHER';\n }\n}\n\n/**\n * The query contains errors. In the event that a request was created\n * using a form and contains user generated data, the user should be\n * notified that the data must be corrected before the query is repeated.\n */\nclass BadRequestError extends RPCError {\n code = 400;\n\n message = 'BAD_REQUEST';\n}\n\n/**\n * There was an unauthorized attempt to use functionality available only\n * to authorized users.\n */\nclass UnauthorizedError extends RPCError {\n code = 401;\n\n message = 'UNAUTHORIZED';\n}\n\n/**\n * Privacy violation. For example, an attempt to write a message to\n * someone who has blacklisted the current user.\n */\nclass ForbiddenError extends RPCError {\n code = 403;\n\n message = 'FORBIDDEN';\n}\n\n/**\n * An attempt to invoke a non-existent object, such as a method.\n */\nclass NotFoundError extends RPCError {\n code = 404;\n\n message = 'NOT_FOUND';\n}\n\n/**\n * Errors related to invalid authorization key, like\n * AUTH_KEY_DUPLICATED which can cause the connection to fail.\n */\nclass AuthKeyError extends RPCError {\n code = 406;\n\n message = 'AUTH_KEY';\n}\n\n/**\n * The maximum allowed number of attempts to invoke the given method\n * with the given input parameters has been exceeded. For example, in an\n * attempt to request a large number of text messages (SMS) for the same\n * phone number.\n */\nclass FloodError extends RPCError {\n code = 420;\n\n message = 'FLOOD';\n}\n\n/**\n * An internal server error occurred while a request was being processed\n * for example, there was a disruption while accessing a database or file\n * storage\n */\nclass ServerError extends RPCError {\n code = 500; // Also witnessed as -500\n\n message = 'INTERNAL';\n}\n\n/**\n * Clicking the inline buttons of bots that never (or take to long to)\n * call ``answerCallbackQuery`` will result in this \"special\" RPCError.\n */\nclass TimedOutError extends RPCError {\n code = 503; // Only witnessed as -503\n\n message = 'Timeout';\n}\n\nmodule.exports = {\n RPCError,\n InvalidDCError,\n BadRequestError,\n UnauthorizedError,\n ForbiddenError,\n NotFoundError,\n AuthKeyError,\n FloodError,\n ServerError,\n TimedOutError,\n};\n","const {\n RPCError,\n InvalidDCError,\n FloodError,\n BadRequestError,\n} = require('./RPCBaseErrors');\n\n\nclass UserMigrateError extends InvalidDCError {\n constructor(args) {\n const newDc = Number(args.capture || 0);\n // eslint-disable-next-line max-len\n super(`The user whose identity is being used to execute queries is associated with DC ${newDc}${RPCError._fmtRequest(args.request)}`);\n // eslint-disable-next-line max-len\n this.message = `The user whose identity is being used to execute queries is associated with DC ${newDc}${RPCError._fmtRequest(args.request)}`;\n this.newDc = newDc;\n }\n}\n\n\nclass PhoneMigrateError extends InvalidDCError {\n constructor(args) {\n const newDc = Number(args.capture || 0);\n // eslint-disable-next-line max-len\n super(`The phone number a user is trying to use for authorization is associated with DC ${newDc}${RPCError._fmtRequest(args.request)}`);\n // eslint-disable-next-line max-len\n this.message = `The phone number a user is trying to use for authorization is associated with DC ${newDc}${RPCError._fmtRequest(args.request)}`;\n this.newDc = newDc;\n }\n}\n\nclass SlowModeWaitError extends FloodError {\n constructor(args) {\n const seconds = Number(args.capture || 0);\n // eslint-disable-next-line max-len\n super(`A wait of ${seconds} seconds is required before sending another message in this chat${RPCError._fmtRequest(args.request)}`);\n // eslint-disable-next-line max-len\n this.message = `A wait of ${seconds} seconds is required before sending another message in this chat${RPCError._fmtRequest(args.request)}`;\n this.seconds = seconds;\n }\n}\n\nclass FloodWaitError extends FloodError {\n constructor(args) {\n const seconds = Number(args.capture || 0);\n super(`A wait of ${seconds} seconds is required${RPCError._fmtRequest(args.request)}`);\n this.message = `A wait of ${seconds} seconds is required${RPCError._fmtRequest(args.request)}`;\n this.seconds = seconds;\n }\n}\nclass MsgWaitError extends FloodError {\n constructor(args) {\n super(`Message failed to be sent.${RPCError._fmtRequest(args.request)}`);\n this.message = `Message failed to be sent.${RPCError._fmtRequest(args.request)}`;\n }\n}\n\nclass FloodTestPhoneWaitError extends FloodError {\n constructor(args) {\n const seconds = Number(args.capture || 0);\n super(`A wait of ${seconds} seconds is required in the test servers${RPCError._fmtRequest(args.request)}`);\n // eslint-disable-next-line max-len\n this.message = `A wait of ${seconds} seconds is required in the test servers${RPCError._fmtRequest(args.request)}`;\n this.seconds = seconds;\n }\n}\n\nclass FileMigrateError extends InvalidDCError {\n constructor(args) {\n const newDc = Number(args.capture || 0);\n super(`The file to be accessed is currently stored in DC ${newDc}${RPCError._fmtRequest(args.request)}`);\n // eslint-disable-next-line max-len\n this.message = `The file to be accessed is currently stored in DC ${newDc}${RPCError._fmtRequest(args.request)}`;\n this.newDc = newDc;\n }\n}\n\nclass NetworkMigrateError extends InvalidDCError {\n constructor(args) {\n const newDc = Number(args.capture || 0);\n super(`The source IP address is associated with DC ${newDc}${RPCError._fmtRequest(args.request)}`);\n this.message = `The source IP address is associated with DC ${newDc}${RPCError._fmtRequest(args.request)}`;\n this.newDc = newDc;\n }\n}\n\nclass EmailUnconfirmedError extends BadRequestError {\n constructor(args) {\n const codeLength = Number(args.capture || 0);\n super(`Email unconfirmed, the length of the code must be ${codeLength}${RPCError._fmtRequest(args.request)}`);\n // eslint-disable-next-line max-len\n this.message = `Email unconfirmed, the length of the code must be ${codeLength}${RPCError._fmtRequest(args.request)}`;\n this.codeLength = codeLength;\n }\n}\n\nconst rpcErrorRe = [\n [/FILE_MIGRATE_(\\d+)/, FileMigrateError],\n [/FLOOD_TEST_PHONE_WAIT_(\\d+)/, FloodTestPhoneWaitError],\n [/FLOOD_WAIT_(\\d+)/, FloodWaitError],\n [/MSG_WAIT_(.*)/, MsgWaitError],\n [/PHONE_MIGRATE_(\\d+)/, PhoneMigrateError],\n [/SLOWMODE_WAIT_(\\d+)/, SlowModeWaitError],\n [/USER_MIGRATE_(\\d+)/, UserMigrateError],\n [/NETWORK_MIGRATE_(\\d+)/, NetworkMigrateError],\n [/EMAIL_UNCONFIRMED_(\\d+)/, EmailUnconfirmedError],\n\n];\nmodule.exports = {\n rpcErrorRe,\n FileMigrateError,\n FloodTestPhoneWaitError,\n FloodWaitError,\n PhoneMigrateError,\n SlowModeWaitError,\n UserMigrateError,\n NetworkMigrateError,\n MsgWaitError,\n EmailUnconfirmedError,\n};\n","/**\n * Converts a Telegram's RPC Error to a Python error.\n * @param rpcError the RPCError instance\n * @param request the request that caused this error\n * @constructor the RPCError as a Python exception that represents this error\n */\nconst { RPCError } = require('./RPCBaseErrors');\nconst { rpcErrorRe } = require('./RPCErrorList');\n\nfunction RPCMessageToError(rpcError, request) {\n for (const [msgRegex, Cls] of rpcErrorRe) {\n const m = rpcError.errorMessage.match(msgRegex);\n if (m) {\n const capture = m.length === 2 ? parseInt(m[1], 10) : undefined;\n return new Cls({\n request,\n capture,\n });\n }\n }\n\n return new RPCError(rpcError.errorMessage, request);\n}\n\nconst Common = require('./Common');\nconst RPCBaseErrors = require('./RPCBaseErrors');\nconst RPCErrorList = require('./RPCErrorList');\n\nmodule.exports = {\n RPCMessageToError,\n ...Common,\n ...RPCBaseErrors,\n ...RPCErrorList,\n};\n","const { EventBuilder } = require('./common');\n\nclass Raw extends EventBuilder {\n constructor(args = {\n types: undefined,\n func: undefined,\n }) {\n super();\n if (!args.types) {\n this.types = true;\n } else {\n this.types = args.types;\n }\n }\n\n build(update) {\n return update;\n }\n}\n\nmodule.exports = Raw;\n","class EventBuilder {\n constructor(args = {\n chats: undefined,\n blacklistChats: undefined,\n func: undefined,\n }) {\n this.chats = args.chats;\n this.blacklistChats = Boolean(args.blacklistChats);\n this.resolved = false;\n this.func = args.func;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n build(update) {\n\n }\n}\n\n\nmodule.exports = {\n EventBuilder,\n};\n","const NewMessage = require('./NewMessage');\nconst Raw = require('./Raw');\n\nclass StopPropagation extends Error {\n\n}\n\nmodule.exports = {\n NewMessage,\n StopPropagation,\n Raw,\n};\n","class AsyncQueue {\n constructor() {\n this._queue = [];\n this.canGet = new Promise((resolve) => {\n this.resolveGet = resolve;\n });\n this.canPush = true;\n }\n\n async push(value) {\n await this.canPush;\n this._queue.push(value);\n this.resolveGet(true);\n this.canPush = new Promise((resolve) => {\n this.resolvePush = resolve;\n });\n }\n\n async pop() {\n await this.canGet;\n const returned = this._queue.pop();\n this.resolvePush(true);\n this.canGet = new Promise((resolve) => {\n this.resolveGet = resolve;\n });\n return returned;\n }\n}\n\nmodule.exports = AsyncQueue;\n","const { TypeNotFoundError } = require('../errors/Common');\nconst { coreObjects } = require('../tl/core');\nconst { tlobjects } = require('../tl/AllTLObjects');\nconst { readBigIntFromBuffer } = require('../Helpers');\n\nclass BinaryReader {\n /**\n * Small utility class to read binary data.\n * @param data {Buffer}\n */\n constructor(data) {\n this.stream = data;\n this._last = undefined;\n this.offset = 0;\n }\n\n // region Reading\n\n // \"All numbers are written as little endian.\"\n // https://core.telegram.org/mtproto\n /**\n * Reads a single byte value.\n */\n readByte() {\n return this.read(1)[0];\n }\n\n /**\n * Reads an integer (4 bytes or 32 bits) value.\n * @param signed {Boolean}\n */\n readInt(signed = true) {\n let res;\n if (signed) {\n res = this.stream.readInt32LE(this.offset);\n } else {\n res = this.stream.readUInt32LE(this.offset);\n }\n this.offset += 4;\n return res;\n }\n\n /**\n * Reads a long integer (8 bytes or 64 bits) value.\n * @param signed\n * @returns {BigInteger}\n */\n readLong(signed = true) {\n return this.readLargeInt(64, signed);\n }\n\n /**\n * Reads a real floating point (4 bytes) value.\n * @returns {number}\n */\n readFloat() {\n return this.read(4)\n .readFloatLE(0);\n }\n\n /**\n * Reads a real floating point (8 bytes) value.\n * @returns {BigInteger}\n */\n readDouble() {\n // was this a bug ? it should have been 0) {\n padding = 4 - padding;\n this.read(padding);\n }\n\n return data;\n }\n\n /**\n * Reads a Telegram-encoded string.\n * @returns {string}\n */\n tgReadString() {\n return this.tgReadBytes()\n .toString('utf-8');\n }\n\n /**\n * Reads a Telegram boolean value.\n * @returns {boolean}\n */\n tgReadBool() {\n const value = this.readInt(false);\n if (value === 0x997275b5) {\n // boolTrue\n return true;\n } else if (value === 0xbc799737) {\n // boolFalse\n return false;\n } else {\n throw new Error(`Invalid boolean code ${value.toString('16')}`);\n }\n }\n\n /**\n * Reads and converts Unix time (used by Telegram)\n * into a Javascript {Date} object.\n * @returns {Date}\n */\n tgReadDate() {\n const value = this.readInt();\n return new Date(value * 1000);\n }\n\n /**\n * Reads a Telegram object.\n */\n tgReadObject() {\n const constructorId = this.readInt(false);\n let clazz = tlobjects[constructorId];\n if (clazz === undefined) {\n /**\n * The class was None, but there's still a\n * chance of it being a manually parsed value like bool!\n */\n const value = constructorId;\n if (value === 0x997275b5) {\n // boolTrue\n return true;\n } else if (value === 0xbc799737) {\n // boolFalse\n return false;\n } else if (value === 0x1cb5c415) {\n // Vector\n const temp = [];\n const length = this.readInt();\n for (let i = 0; i < length; i++) {\n temp.push(this.tgReadObject());\n }\n return temp;\n }\n\n clazz = coreObjects[constructorId];\n\n if (clazz === undefined) {\n // If there was still no luck, give up\n this.seek(-4); // Go back\n const pos = this.tellPosition();\n const error = new TypeNotFoundError(constructorId, this.read());\n this.setPosition(pos);\n throw error;\n }\n }\n return clazz.fromReader(this);\n }\n\n /**\n * Reads a vector (a list) of Telegram objects.\n * @returns {[Buffer]}\n */\n tgReadVector() {\n if (this.readInt(false) !== 0x1cb5c415) {\n throw new Error('Invalid constructor code, vector was expected');\n }\n const count = this.readInt();\n const temp = [];\n for (let i = 0; i < count; i++) {\n temp.push(this.tgReadObject());\n }\n return temp;\n }\n\n // endregion\n\n /**\n * Closes the reader.\n */\n close() {\n this.stream = undefined;\n }\n\n // region Position related\n\n /**\n * Tells the current position on the stream.\n * @returns {number}\n */\n tellPosition() {\n return this.offset;\n }\n\n /**\n * Sets the current position on the stream.\n * @param position\n */\n setPosition(position) {\n this.offset = position;\n }\n\n /**\n * Seeks the stream position given an offset from the current position.\n * The offset may be negative.\n * @param offset\n */\n seek(offset) {\n this.offset += offset;\n }\n\n // endregion\n}\n\nmodule.exports = BinaryReader;\n","class BinaryWriter {\n constructor(stream) {\n this._stream = stream;\n }\n\n write(buffer) {\n this._stream = Buffer.concat([this._stream, buffer]);\n }\n\n getValue() {\n return this._stream;\n }\n}\n\nmodule.exports = BinaryWriter;\n","let _level;\n\nclass Logger {\n static levels = ['error', 'warn', 'info', 'debug'];\n\n constructor(level) {\n if (!_level) {\n _level = level || 'debug';\n }\n\n this.isBrowser = typeof process === 'undefined'\n || process.type === 'renderer'\n || process.browser === true\n || process.__nwjs;\n if (!this.isBrowser) {\n this.colors = {\n start: '\\x1b[2m',\n warn: '\\x1b[35m',\n info: '\\x1b[33m',\n debug: '\\x1b[36m',\n error: '\\x1b[31m',\n end: '\\x1b[0m',\n };\n } else {\n this.colors = {\n start: '%c',\n warn: 'color : #ff00ff',\n info: 'color : #ffff00',\n debug: 'color : #00ffff',\n error: 'color : #ff0000',\n end: '',\n };\n }\n this.messageFormat = '[%t] [%l] - [%m]';\n }\n\n static setLevel(level) {\n _level = level;\n }\n\n /**\n *\n * @param level {string}\n * @returns {boolean}\n */\n canSend(level) {\n return (Logger.levels.indexOf(_level) >= Logger.levels.indexOf(level));\n }\n\n /**\n * @param message {string}\n */\n warn(message) {\n // todo remove later\n if (_level === 'debug') {\n // eslint-disable-next-line no-console\n console.error(new Error().stack);\n }\n this._log('warn', message, this.colors.warn);\n }\n\n /**\n * @param message {string}\n */\n info(message) {\n this._log('info', message, this.colors.info);\n }\n\n /**\n * @param message {string}\n */\n debug(message) {\n this._log('debug', message, this.colors.debug);\n }\n\n /**\n * @param message {string}\n */\n error(message) {\n // todo remove later\n if (_level === 'debug') {\n // eslint-disable-next-line no-console\n console.error(new Error().stack);\n }\n this._log('error', message, this.colors.error);\n }\n\n format(message, level) {\n return this.messageFormat.replace('%t', new Date().toISOString())\n .replace('%l', level.toUpperCase())\n .replace('%m', message);\n }\n\n /**\n * @param level {string}\n * @param message {string}\n * @param color {string}\n */\n _log(level, message, color) {\n if (!_level) {\n return;\n }\n if (this.canSend(level)) {\n if (!this.isBrowser) {\n // eslint-disable-next-line no-console\n console.log(color + this.format(message, level) + this.colors.end);\n } else {\n // eslint-disable-next-line no-console\n console.log(this.colors.start + this.format(message, level), color);\n }\n }\n }\n}\n\nmodule.exports = Logger;\n","const MessageContainer = require('../tl/core/MessageContainer');\nconst TLMessage = require('../tl/core/TLMessage');\nconst BinaryWriter = require('./BinaryWriter');\n\nconst USE_INVOKE_AFTER_WITH = [\n 'messages.SendMessage', 'messages.SendMedia', 'messages.SendMultiMedia',\n 'messages.ForwardMessages', 'messages.SendInlineBotResult',\n];\n\nclass MessagePacker {\n constructor(state, logger) {\n this._state = state;\n this._queue = [];\n this._pendingStates = [];\n this._ready = new Promise(((resolve) => {\n this.setReady = resolve;\n }));\n this._log = logger;\n }\n\n values() {\n return this._queue;\n }\n\n append(state) {\n // we need to check if there is already a request with the same name that we should send after.\n if (state && USE_INVOKE_AFTER_WITH.includes(state.request.className)) {\n // we now need to check if there is any request in queue already.\n // we loop backwards since the latest request is the most recent\n for (let i = this._queue.length - 1; i >= 0; i--) {\n if (USE_INVOKE_AFTER_WITH.includes(this._queue[i].request.className)) {\n state.after = this._queue[i];\n break;\n }\n }\n }\n\n this._queue.push(state);\n this.setReady(true);\n // 1658238041=MsgsAck, we don't care about MsgsAck here because they never resolve anyway.\n if (state && state.request.CONSTRUCTOR_ID !== 1658238041) {\n this._pendingStates.push(state);\n state.promise\n // Using finally causes triggering `unhandledrejection` event\n .catch(() => {\n })\n .finally(() => {\n this._pendingStates = this._pendingStates.filter((s) => s !== state);\n });\n }\n }\n\n extend(states) {\n for (const state of states) {\n this._queue.push(state);\n }\n this.setReady(true);\n }\n\n async get() {\n if (!this._queue.length) {\n this._ready = new Promise(((resolve) => {\n this.setReady = resolve;\n }));\n await this._ready;\n }\n if (!this._queue[this._queue.length - 1]) {\n this._queue = [];\n return undefined;\n }\n let data;\n let buffer = new BinaryWriter(Buffer.alloc(0));\n\n const batch = [];\n let size = 0;\n\n while (this._queue.length && batch.length <= MessageContainer.MAXIMUM_LENGTH) {\n const state = this._queue.shift();\n size += state.data.length + TLMessage.SIZE_OVERHEAD;\n if (size <= MessageContainer.MAXIMUM_SIZE) {\n let afterId;\n if (state.after) {\n afterId = state.after.msgId;\n }\n state.msgId = await this._state.writeDataAsMessage(\n buffer, state.data, state.request.classType === 'request',\n afterId,\n );\n this._log.debug(`Assigned msgId = ${state.msgId} to ${state.request.className\n || state.request.constructor.name}`);\n batch.push(state);\n continue;\n }\n if (batch.length) {\n this._queue.unshift(state);\n break;\n }\n this._log.warn(`Message payload for ${state.request.className\n || state.request.constructor.name} is too long ${state.data.length} and cannot be sent`);\n state.reject('Request Payload is too big');\n size = 0;\n }\n if (!batch.length) {\n return undefined;\n }\n if (batch.length > 1) {\n const b = Buffer.alloc(8);\n b.writeUInt32LE(MessageContainer.CONSTRUCTOR_ID, 0);\n b.writeInt32LE(batch.length, 4);\n data = Buffer.concat([b, buffer.getValue()]);\n buffer = new BinaryWriter(Buffer.alloc(0));\n const containerId = await this._state.writeDataAsMessage(\n buffer, data, false,\n );\n for (const s of batch) {\n s.containerId = containerId;\n }\n }\n\n data = buffer.getValue();\n return {\n batch,\n data,\n };\n }\n\n rejectAll() {\n this._pendingStates.forEach((requestState) => {\n requestState.reject(new Error('Disconnect'));\n });\n }\n}\n\nmodule.exports = MessagePacker;\n","const { Mutex } = require('async-mutex');\n\nconst mutex = new Mutex();\n\nconst WebSocketClient = require('websocket').w3cwebsocket;\n\nconst closeError = new Error('WebSocket was closed');\n\nclass PromisedWebSockets {\n constructor(disconnectedCallback) {\n /* CONTEST\n this.isBrowser = typeof process === 'undefined' ||\n process.type === 'renderer' ||\n process.browser === true ||\n process.__nwjs\n\n */\n this.client = undefined;\n this.closed = true;\n this.disconnectedCallback = disconnectedCallback;\n }\n\n async readExactly(number) {\n let readData = Buffer.alloc(0);\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const thisTime = await this.read(number);\n readData = Buffer.concat([readData, thisTime]);\n number -= thisTime.length;\n if (!number) {\n return readData;\n }\n }\n }\n\n async read(number) {\n if (this.closed) {\n throw closeError;\n }\n await this.canRead;\n if (this.closed) {\n throw closeError;\n }\n const toReturn = this.stream.slice(0, number);\n this.stream = this.stream.slice(number);\n if (this.stream.length === 0) {\n this.canRead = new Promise((resolve) => {\n this.resolveRead = resolve;\n });\n }\n\n return toReturn;\n }\n\n async readAll() {\n if (this.closed || !await this.canRead) {\n throw closeError;\n }\n const toReturn = this.stream;\n this.stream = Buffer.alloc(0);\n this.canRead = new Promise((resolve) => {\n this.resolveRead = resolve;\n });\n\n return toReturn;\n }\n\n getWebSocketLink(ip, port, testServers) {\n if (port === 443) {\n return `wss://${ip}:${port}/apiws${testServers ? '_test' : ''}`;\n } else {\n return `ws://${ip}:${port}/apiws${testServers ? '_test' : ''}`;\n }\n }\n\n connect(port, ip, testServers = false) {\n this.stream = Buffer.alloc(0);\n this.canRead = new Promise((resolve) => {\n this.resolveRead = resolve;\n });\n this.closed = false;\n this.website = this.getWebSocketLink(ip, port, testServers);\n this.client = new WebSocketClient(this.website, 'binary');\n return new Promise((resolve, reject) => {\n this.client.onopen = () => {\n this.receive();\n resolve(this);\n };\n this.client.onerror = (error) => {\n // eslint-disable-next-line no-console\n console.error('WebSocket error', error);\n reject(error);\n };\n this.client.onclose = (event) => {\n const { code, reason, wasClean } = event;\n if (code !== 1000) {\n // eslint-disable-next-line no-console\n console.error(`Socket ${ip} closed. Code: ${code}, reason: ${reason}, was clean: ${wasClean}`);\n }\n\n this.resolveRead(false);\n this.closed = true;\n if (this.disconnectedCallback) {\n this.disconnectedCallback();\n }\n };\n // CONTEST\n // Seems to not be working, at least in a web worker\n // eslint-disable-next-line no-restricted-globals\n self.addEventListener('offline', async () => {\n await this.close();\n this.resolveRead(false);\n });\n });\n }\n\n write(data) {\n if (this.closed) {\n throw closeError;\n }\n this.client.send(data);\n }\n\n async close() {\n await this.client.close();\n this.closed = true;\n }\n\n receive() {\n this.client.onmessage = async (message) => {\n await mutex.runExclusive(async () => {\n const data = message.data instanceof ArrayBuffer\n ? Buffer.from(message.data)\n : Buffer.from(await new Response(message.data).arrayBuffer());\n this.stream = Buffer.concat([this.stream, data]);\n this.resolveRead(true);\n });\n };\n }\n}\n\nmodule.exports = PromisedWebSockets;\n","const Logger = require('./Logger');\nconst BinaryWriter = require('./BinaryWriter');\nconst BinaryReader = require('./BinaryReader');\nconst PromisedWebSockets = require('./PromisedWebSockets');\nconst MessagePacker = require('./MessagePacker');\nconst AsyncQueue = require('./AsyncQueue');\n\nmodule.exports = {\n BinaryWriter,\n BinaryReader,\n MessagePacker,\n AsyncQueue,\n Logger,\n PromisedWebSockets,\n};\n","const Api = require('./tl/api');\nconst TelegramClient = require('./client/TelegramClient');\nconst connection = require('./network');\nconst tl = require('./tl');\nconst version = require('./Version');\nconst events = require('./events');\nconst utils = require('./Utils');\nconst errors = require('./errors');\nconst sessions = require('./sessions');\nconst extensions = require('./extensions');\nconst helpers = require('./Helpers');\n\nmodule.exports = {\n Api,\n TelegramClient,\n sessions,\n connection,\n extensions,\n tl,\n version,\n events,\n utils,\n errors,\n helpers,\n};\n","import bigInt from 'big-integer';\nimport {\n generateRandomBytes,\n modExp,\n readBigIntFromBuffer,\n readBufferFromBigInt,\n sha1,\n} from '../Helpers';\n\nconst PUBLIC_KEYS = [\n {\n fingerprint: bigInt('-3414540481677951611'),\n n: bigInt(\n '2937959817066933702298617714945612856538843112005886376816255642404751219133084745514657634448776440866'\n + '1701890505066208632169112269581063774293102577308490531282748465986139880977280302242772832972539403531'\n + '3160108704012876427630091361567343395380424193887227773571344877461690935390938502512438971889287359033'\n + '8945177273024525306296338410881284207988753897636046529094613963869149149606209957083647645485599631919'\n + '2747663615955633778034897140982517446405334423701359108810182097749467210509584293428076654573384828809'\n + '574217079944388301239431309115013843331317877374435868468779972014486325557807783825502498215169806323',\n ),\n e: 65537,\n },\n {\n fingerprint: bigInt('-5595554452916591101'),\n n: bigInt(\n '2534288944884041556497168959071347320689884775908477905258202659454602246385394058588521595116849196570822' +\n '26493991806038180742006204637761354248846321625124031637930839216416315647409595294193595958529411668489405859523' +\n '37613333022396096584117954892216031229237302943701877588456738335398602461675225081791820393153757504952636234951' +\n '32323782003654358104782690612092797248736680529211579223142368426126233039432475078545094258975175539015664775146' +\n '07193514399690599495696153028090507215003302390050778898553239175099482557220816446894421272976054225797071426466' +\n '60768825302832201908302295573257427896031830742328565032949',\n ),\n e: 65537,\n },\n];\n\nexport const _serverKeys = new Map();\n\nPUBLIC_KEYS.forEach(({ fingerprint, ...keyInfo }) => {\n _serverKeys.set(fingerprint.toString(),\n keyInfo);\n});\n\n/**\n * Encrypts the given data known the fingerprint to be used\n * in the way Telegram requires us to do so (sha1(data) + data + padding)\n\n * @param fingerprint the fingerprint of the RSA key.\n * @param data the data to be encrypted.\n * @returns {Buffer|*|undefined} the cipher text, or undefined if no key matching this fingerprint is found.\n */\nexport async function encrypt(fingerprint: bigInt.BigInteger, data: Buffer) {\n const key = _serverKeys.get(fingerprint.toString());\n if (!key) {\n return undefined;\n }\n\n // len(sha1.digest) is always 20, so we're left with 255 - 20 - x padding\n const rand = generateRandomBytes(235 - data.length);\n\n const toEncrypt = Buffer.concat([await sha1(data), data, rand]);\n\n // rsa module rsa.encrypt adds 11 bits for padding which we don't want\n // rsa module uses rsa.transform.bytes2int(to_encrypt), easier way:\n const payload = readBigIntFromBuffer(toEncrypt, false);\n const encrypted = modExp(payload, bigInt(key.e), key.n);\n // rsa module uses transform.int2bytes(encrypted, keylength), easier:\n return readBufferFromBigInt(encrypted, 256, false);\n}\n","/**\n * Executes the authentication process with the Telegram servers.\n * @param sender a connected {MTProtoPlainSender}.\n * @param log\n * @returns {Promise<{authKey: *, timeOffset: *}>}\n */\n// eslint-disable-next-line import/no-named-default\nimport { default as Api } from '../tl/api';\nimport { SecurityError } from '../errors';\n// eslint-disable-next-line import/no-named-default\nimport { default as MTProtoPlainSender } from './MTProtoPlainSender';\nimport { _serverKeys } from '../crypto/RSA';\n\nconst bigInt = require('big-integer');\nconst IGE = require('../crypto/IGE');\nconst AuthKey = require('../crypto/AuthKey');\nconst Factorizator = require('../crypto/Factorizator');\nconst Helpers = require('../Helpers');\nconst BinaryReader = require('../extensions/BinaryReader');\n\nconst RETRIES = 20;\n\nexport async function doAuthentication(sender: MTProtoPlainSender, log: any) {\n // Step 1 sending: PQ Request, endianness doesn't matter since it's random\n let bytes = Helpers.generateRandomBytes(16);\n\n const nonce = Helpers.readBigIntFromBuffer(bytes, false, true);\n const resPQ = await sender.send(new Api.ReqPqMulti({ nonce }));\n log.debug('Starting authKey generation step 1');\n\n if (!(resPQ instanceof Api.ResPQ)) {\n throw new SecurityError(`Step 1 answer was ${resPQ}`);\n }\n if (resPQ.nonce.neq(nonce)) {\n throw new SecurityError('Step 1 invalid nonce from server');\n }\n const pq = Helpers.readBigIntFromBuffer(resPQ.pq, false, true);\n log.debug('Finished authKey generation step 1');\n // Step 2 sending: DH Exchange\n const { p, q } = Factorizator.factorize(pq);\n\n const pBuffer = Helpers.getByteArray(p);\n const qBuffer = Helpers.getByteArray(q);\n\n bytes = Helpers.generateRandomBytes(32);\n const newNonce = Helpers.readBigIntFromBuffer(bytes, true, true);\n const pqInnerData = new Api.PQInnerData({\n pq: Helpers.getByteArray(pq), // unsigned\n p: pBuffer,\n q: qBuffer,\n nonce: resPQ.nonce,\n serverNonce: resPQ.serverNonce,\n newNonce,\n }).getBytes();\n if (pqInnerData.length > 144) {\n throw new SecurityError('Step 1 invalid nonce from server');\n }\n let targetFingerprint;\n let targetKey;\n for (const fingerprint of resPQ.serverPublicKeyFingerprints) {\n targetKey = _serverKeys.get(fingerprint.toString());\n if (targetKey !== undefined) {\n targetFingerprint = fingerprint;\n break;\n }\n }\n if (targetFingerprint === undefined || targetKey === undefined) {\n throw new SecurityError(\n 'Step 2 could not find a valid key for fingerprints',\n );\n }\n // Value should be padded to be made 192 exactly\n const padding = Helpers.generateRandomBytes(192 - pqInnerData.length);\n const dataWithPadding = Buffer.concat([pqInnerData, padding]);\n const dataPadReversed = Buffer.from(dataWithPadding).reverse();\n\n let encryptedData;\n for (let i = 0; i < RETRIES; i++) {\n const tempKey = Helpers.generateRandomBytes(32);\n const shaDigestKeyWithData = await Helpers.sha256(Buffer.concat([tempKey, dataWithPadding]));\n const dataWithHash = Buffer.concat([dataPadReversed, shaDigestKeyWithData]);\n\n const ige = new IGE(tempKey, Buffer.alloc(32));\n const aesEncrypted = ige.encryptIge(dataWithHash);\n const tempKeyXor = Helpers.bufferXor(tempKey, await Helpers.sha256(aesEncrypted));\n\n const keyAesEncrypted = Buffer.concat([tempKeyXor, aesEncrypted]);\n const keyAesEncryptedInt = Helpers.readBigIntFromBuffer(keyAesEncrypted, false, false);\n if (keyAesEncryptedInt.greaterOrEquals(targetKey.n)) {\n log.debug('Aes key greater than RSA. retrying');\n continue;\n }\n const encryptedDataBuffer = Helpers.modExp(keyAesEncryptedInt, bigInt(targetKey.e), targetKey.n);\n encryptedData = Helpers.readBufferFromBigInt(encryptedDataBuffer, 256, false, false);\n\n break;\n }\n if (encryptedData === undefined) {\n throw new SecurityError(\n 'Step 2 could create a secure encrypted key',\n );\n }\n log.debug('Step 2 : Generated a secure aes encrypted data');\n\n const serverDhParams = await sender.send(\n new Api.ReqDHParams({\n nonce: resPQ.nonce,\n serverNonce: resPQ.serverNonce,\n p: pBuffer,\n q: qBuffer,\n publicKeyFingerprint: targetFingerprint,\n encryptedData,\n }),\n );\n\n if (\n !(\n serverDhParams instanceof Api.ServerDHParamsOk\n || serverDhParams instanceof Api.ServerDHParamsFail\n )\n ) {\n throw new Error(`Step 2.1 answer was ${serverDhParams}`);\n }\n if (serverDhParams.nonce.neq(resPQ.nonce)) {\n throw new SecurityError('Step 2 invalid nonce from server');\n }\n\n if (serverDhParams.serverNonce.neq(resPQ.serverNonce)) {\n throw new SecurityError('Step 2 invalid server nonce from server');\n }\n\n if (serverDhParams instanceof Api.ServerDHParamsFail) {\n const sh = await Helpers.sha1(\n Helpers.toSignedLittleBuffer(newNonce, 32).slice(4, 20),\n );\n const nnh = Helpers.readBigIntFromBuffer(sh, true, true);\n if (serverDhParams.newNonceHash.neq(nnh)) {\n throw new SecurityError('Step 2 invalid DH fail nonce from server');\n }\n }\n if (!(serverDhParams instanceof Api.ServerDHParamsOk)) {\n throw new Error(`Step 2.2 answer was ${serverDhParams}`);\n }\n log.debug('Finished authKey generation step 2');\n log.debug('Starting authKey generation step 3');\n\n // Step 3 sending: Complete DH Exchange\n const { key, iv } = await Helpers.generateKeyDataFromNonce(\n resPQ.serverNonce,\n newNonce,\n );\n if (serverDhParams.encryptedAnswer.length % 16 !== 0) {\n // See PR#453\n throw new SecurityError('Step 3 AES block size mismatch');\n }\n const ige = new IGE(key, iv);\n const plainTextAnswer = ige.decryptIge(serverDhParams.encryptedAnswer);\n const reader = new BinaryReader(plainTextAnswer);\n reader.read(20); // hash sum\n const serverDhInner = reader.tgReadObject();\n if (!(serverDhInner instanceof Api.ServerDHInnerData)) {\n throw new Error(`Step 3 answer was ${serverDhInner}`);\n }\n\n if (serverDhInner.nonce.neq(resPQ.nonce)) {\n throw new SecurityError('Step 3 Invalid nonce in encrypted answer');\n }\n if (serverDhInner.serverNonce.neq(resPQ.serverNonce)) {\n throw new SecurityError(\n 'Step 3 Invalid server nonce in encrypted answer',\n );\n }\n const dhPrime = Helpers.readBigIntFromBuffer(\n serverDhInner.dhPrime,\n false,\n false,\n );\n const ga = Helpers.readBigIntFromBuffer(serverDhInner.gA, false, false);\n const timeOffset = serverDhInner.serverTime - Math.floor(new Date().getTime() / 1000);\n const b = Helpers.readBigIntFromBuffer(\n Helpers.generateRandomBytes(256),\n false,\n false,\n );\n const gb = Helpers.modExp(bigInt(serverDhInner.g), b, dhPrime);\n const gab = Helpers.modExp(ga, b, dhPrime);\n\n // Prepare client DH Inner Data\n const clientDhInner = new Api.ClientDHInnerData({\n nonce: resPQ.nonce,\n serverNonce: resPQ.serverNonce,\n retryId: bigInt.zero, // TODO Actual retry ID\n gB: Helpers.getByteArray(gb, false),\n }).getBytes();\n\n const clientDdhInnerHashed = Buffer.concat([\n await Helpers.sha1(clientDhInner),\n clientDhInner,\n ]);\n // Encryption\n\n const clientDhEncrypted = ige.encryptIge(clientDdhInnerHashed);\n const dhGen = await sender.send(\n new Api.SetClientDHParams({\n nonce: resPQ.nonce,\n serverNonce: resPQ.serverNonce,\n encryptedData: clientDhEncrypted,\n }),\n );\n const nonceTypes = [Api.DhGenOk, Api.DhGenRetry, Api.DhGenFail];\n // TS being weird again.\n const nonceTypesString = ['DhGenOk', 'DhGenRetry', 'DhGenFail'];\n if (\n !(\n dhGen instanceof nonceTypes[0]\n || dhGen instanceof nonceTypes[1]\n || dhGen instanceof nonceTypes[2]\n )\n ) {\n throw new Error(`Step 3.1 answer was ${dhGen}`);\n }\n const { name } = dhGen.constructor;\n if (dhGen.nonce.neq(resPQ.nonce)) {\n throw new SecurityError(`Step 3 invalid ${name} nonce from server`);\n }\n if (dhGen.serverNonce.neq(resPQ.serverNonce)) {\n throw new SecurityError(\n `Step 3 invalid ${name} server nonce from server`,\n );\n }\n const authKey = new AuthKey();\n await authKey.setKey(Helpers.getByteArray(gab));\n\n const nonceNumber = 1 + nonceTypesString.indexOf(dhGen.className);\n\n const newNonceHash = await authKey.calcNewNonceHash(newNonce, nonceNumber);\n // @ts-ignore\n const dhHash = dhGen[`newNonceHash${nonceNumber}`];\n\n if (dhHash.neq(newNonceHash)) {\n throw new SecurityError('Step 3 invalid new nonce hash');\n }\n\n if (!(dhGen instanceof Api.DhGenOk)) {\n throw new Error(`Step 3.2 answer was ${dhGen}`);\n }\n log.debug('Finished authKey generation step 3');\n\n return { authKey, timeOffset };\n}\n","/**\n * This module contains the class used to communicate with Telegram's servers\n * in plain text, when no authorization key has been created yet.\n */\nconst BigInt = require('big-integer');\nconst MTProtoState = require('./MTProtoState');\nconst BinaryReader = require('../extensions/BinaryReader');\nconst { InvalidBufferError } = require('../errors/Common');\nconst { toSignedLittleBuffer } = require('../Helpers');\n\n/**\n * MTProto Mobile Protocol plain sender (https://core.telegram.org/mtproto/description#unencrypted-messages)\n */\n\nclass MTProtoPlainSender {\n /**\n * Initializes the MTProto plain sender.\n * @param connection connection: the Connection to be used.\n * @param loggers\n */\n constructor(connection, loggers) {\n this._state = new MTProtoState(connection, loggers);\n this._connection = connection;\n }\n\n /**\n * Sends and receives the result for the given request.\n * @param request\n */\n async send(request) {\n let body = request.getBytes();\n let msgId = this._state._getNewMsgId();\n const m = toSignedLittleBuffer(msgId, 8);\n const b = Buffer.alloc(4);\n b.writeInt32LE(body.length, 0);\n\n const res = Buffer.concat([Buffer.concat([Buffer.alloc(8), m, b]), body]);\n\n await this._connection.send(res);\n body = await this._connection.recv();\n if (body.length < 8) {\n throw new InvalidBufferError(body);\n }\n const reader = new BinaryReader(body);\n const authKeyId = reader.readLong();\n if (authKeyId.neq(BigInt(0))) {\n throw new Error('Bad authKeyId');\n }\n msgId = reader.readLong();\n if (msgId.eq(BigInt(0))) {\n throw new Error('Bad msgId');\n }\n /** ^ We should make sure that the read ``msg_id`` is greater\n * than our own ``msg_id``. However, under some circumstances\n * (bad system clock/working behind proxies) this seems to not\n * be the case, which would cause endless assertion errors.\n */\n\n const length = reader.readInt();\n if (length <= 0) {\n throw new Error('Bad length');\n }\n /**\n * We could read length bytes and use those in a new reader to read\n * the next TLObject without including the padding, but since the\n * reader isn't used for anything else after this, it's unnecessary.\n */\n return reader.tgReadObject();\n }\n}\n\nmodule.exports = MTProtoPlainSender;\n","const MtProtoPlainSender = require('./MTProtoPlainSender');\nconst MTProtoState = require('./MTProtoState');\nconst Helpers = require('../Helpers');\nconst AuthKey = require('../crypto/AuthKey');\nconst { doAuthentication } = require('./Authenticator');\nconst RPCResult = require('../tl/core/RPCResult');\nconst MessageContainer = require('../tl/core/MessageContainer');\nconst GZIPPacked = require('../tl/core/GZIPPacked');\nconst RequestState = require('./RequestState');\n\nconst {\n MsgsAck,\n upload,\n MsgsStateInfo,\n Pong,\n} = require('../tl').constructors;\nconst MessagePacker = require('../extensions/MessagePacker');\nconst BinaryReader = require('../extensions/BinaryReader');\nconst { UpdateConnectionState, UpdateServerTimeOffset } = require('./index');\nconst { BadMessageError } = require('../errors/Common');\nconst {\n BadServerSalt,\n BadMsgNotification,\n MsgDetailedInfo,\n MsgNewDetailedInfo,\n NewSessionCreated,\n FutureSalts,\n MsgsStateReq,\n MsgResendReq,\n MsgsAllInfo,\n} = require('../tl').constructors;\nconst { SecurityError } = require('../errors/Common');\nconst { InvalidBufferError } = require('../errors/Common');\nconst { LogOut } = require('../tl').requests.auth;\nconst { RPCMessageToError } = require('../errors');\nconst { TypeNotFoundError } = require('../errors/Common');\n\n/**\n * MTProto Mobile Protocol sender\n * (https://core.telegram.org/mtproto/description)\n * This class is responsible for wrapping requests into `TLMessage`'s,\n * sending them over the network and receiving them in a safe manner.\n *\n * Automatic reconnection due to temporary network issues is a concern\n * for this class as well, including retry of messages that could not\n * be sent successfully.\n *\n * A new authorization key will be generated on connection if no other\n * key exists yet.\n */\nclass MTProtoSender {\n static DEFAULT_OPTIONS = {\n logger: undefined,\n retries: Infinity,\n delay: 2000,\n autoReconnect: true,\n connectTimeout: undefined,\n authKeyCallback: undefined,\n updateCallback: undefined,\n autoReconnectCallback: undefined,\n isMainSender: undefined,\n onConnectionBreak: undefined,\n };\n\n /**\n * @param authKey\n * @param opts\n */\n constructor(authKey, opts) {\n const args = { ...MTProtoSender.DEFAULT_OPTIONS, ...opts };\n this._connection = undefined;\n this._log = args.logger;\n this._dcId = args.dcId;\n this._retries = args.retries;\n this._delay = args.delay;\n this._autoReconnect = args.autoReconnect;\n this._connectTimeout = args.connectTimeout;\n this._authKeyCallback = args.authKeyCallback;\n this._updateCallback = args.updateCallback;\n this._autoReconnectCallback = args.autoReconnectCallback;\n this._isMainSender = args.isMainSender;\n this._onConnectionBreak = args.onConnectionBreak;\n\n /**\n * whether we disconnected ourself or telegram did it.\n */\n this.userDisconnected = false;\n\n /**\n * Whether the user has explicitly connected or disconnected.\n *\n * If a disconnection happens for any other reason and it\n * was *not* user action then the pending messages won't\n * be cleared but on explicit user disconnection all the\n * pending futures should be cancelled.\n */\n this._user_connected = false;\n this._reconnecting = false;\n this._disconnected = true;\n\n /**\n * We need to join the loops upon disconnection\n */\n this._send_loop_handle = undefined;\n this._recv_loop_handle = undefined;\n\n /**\n * Preserving the references of the AuthKey and state is important\n */\n this.authKey = authKey || new AuthKey();\n this._state = new MTProtoState(this.authKey, this._log);\n\n /**\n * Outgoing messages are put in a queue and sent in a batch.\n * Note that here we're also storing their ``_RequestState``.\n */\n this._send_queue = new MessagePacker(this._state, this._log);\n\n /**\n * Sent states are remembered until a response is received.\n */\n this._pending_state = {};\n\n /**\n * Responses must be acknowledged, and we can also batch these.\n */\n this._pending_ack = new Set();\n\n /**\n * Similar to pending_messages but only for the last acknowledges.\n * These can't go in pending_messages because no acknowledge for them\n * is received, but we may still need to resend their state on bad salts.\n */\n this._last_acks = [];\n\n /**\n * Jump table from response ID to method that handles it\n */\n\n this._handlers = {\n [RPCResult.CONSTRUCTOR_ID]: this._handleRPCResult.bind(this),\n [MessageContainer.CONSTRUCTOR_ID]: this._handleContainer.bind(this),\n [GZIPPacked.CONSTRUCTOR_ID]: this._handleGzipPacked.bind(this),\n [Pong.CONSTRUCTOR_ID]: this._handlePong.bind(this),\n [BadServerSalt.CONSTRUCTOR_ID]: this._handleBadServerSalt.bind(this),\n [BadMsgNotification.CONSTRUCTOR_ID]: this._handleBadNotification.bind(this),\n [MsgDetailedInfo.CONSTRUCTOR_ID]: this._handleDetailedInfo.bind(this),\n [MsgNewDetailedInfo.CONSTRUCTOR_ID]: this._handleNewDetailedInfo.bind(this),\n [NewSessionCreated.CONSTRUCTOR_ID]: this._handleNewSessionCreated.bind(this),\n [MsgsAck.CONSTRUCTOR_ID]: this._handleAck.bind(this),\n [FutureSalts.CONSTRUCTOR_ID]: this._handleFutureSalts.bind(this),\n [MsgsStateReq.CONSTRUCTOR_ID]: this._handleStateForgotten.bind(this),\n [MsgResendReq.CONSTRUCTOR_ID]: this._handleStateForgotten.bind(this),\n [MsgsAllInfo.CONSTRUCTOR_ID]: this._handleMsgAll.bind(this),\n };\n }\n\n // Public API\n\n /**\n * Connects to the specified given connection using the given auth key.\n * @param connection\n * @param [force]\n * @returns {Promise}\n */\n async connect(connection, force) {\n if (this._user_connected && !force) {\n this._log.info('User is already connected!');\n return false;\n }\n this.isConnecting = true;\n this._connection = connection;\n\n for (let attempt = 0; attempt < this._retries; attempt++) {\n try {\n await this._connect();\n if (this._updateCallback) {\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.connected));\n }\n break;\n } catch (err) {\n if (this._updateCallback && attempt === 0) {\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.disconnected));\n }\n this._log.error(`WebSocket connection failed attempt: ${attempt + 1}`);\n // eslint-disable-next-line no-console\n console.error(err);\n await Helpers.sleep(this._delay);\n }\n }\n this.isConnecting = false;\n return true;\n }\n\n isConnected() {\n return this._user_connected;\n }\n\n /**\n * Cleanly disconnects the instance from the network, cancels\n * all pending requests, and closes the send and receive loops.\n */\n async disconnect() {\n this.userDisconnected = true;\n await this._disconnect();\n }\n\n /**\n *\n This method enqueues the given request to be sent. Its send\n state will be saved until a response arrives, and a ``Future``\n that will be resolved when the response arrives will be returned:\n\n .. code-block:: javascript\n\n async def method():\n # Sending (enqueued for the send loop)\n future = sender.send(request)\n # Receiving (waits for the receive loop to read the result)\n result = await future\n\n Designed like this because Telegram may send the response at\n any point, and it can send other items while one waits for it.\n Once the response for this future arrives, it is set with the\n received result, quite similar to how a ``receive()`` call\n would otherwise work.\n\n Since the receiving part is \"built in\" the future, it's\n impossible to await receive a result that was never sent.\n * @param request\n * @returns {RequestState}\n */\n send(request) {\n if (!this._user_connected) {\n throw new Error('Cannot send requests while disconnected');\n }\n const state = new RequestState(request);\n this._send_queue.append(state);\n return state.promise;\n }\n\n /**\n * Same as send but returns the full state. usefull for invoke after logic\n * @param request\n * @return {RequestState}\n */\n sendWithInvokeSupport(request) {\n if (!this._user_connected) {\n throw new Error('Cannot send requests while disconnected');\n }\n const state = new RequestState(request, undefined, this._pending_state);\n this._send_queue.append(state);\n return state;\n }\n\n /**\n * Performs the actual connection, retrying, generating the\n * authorization key if necessary, and starting the send and\n * receive loops.\n * @returns {Promise}\n * @private\n */\n async _connect() {\n this._log.info('Connecting to {0}...'.replace('{0}', this._connection));\n await this._connection.connect();\n this._log.debug('Connection success!');\n // process.exit(0)\n if (!this.authKey.getKey()) {\n const plain = new MtProtoPlainSender(this._connection, this._log);\n this._log.debug('New auth_key attempt ...');\n const res = await doAuthentication(plain, this._log);\n this._log.debug('Generated new auth_key successfully');\n await this.authKey.setKey(res.authKey);\n\n this._state.timeOffset = res.timeOffset;\n\n if (this._updateCallback) {\n this._updateCallback(new UpdateServerTimeOffset(this._state.timeOffset));\n }\n\n /**\n * This is *EXTREMELY* important since we don't control\n * external references to the authorization key, we must\n * notify whenever we change it. This is crucial when we\n * switch to different data centers.\n */\n if (this._authKeyCallback) {\n await this._authKeyCallback(this.authKey, this._dcId);\n }\n } else {\n this._authenticated = true;\n this._log.debug('Already have an auth key ...');\n }\n this._user_connected = true;\n this._reconnecting = false;\n\n this._log.debug('Starting send loop');\n this._send_loop_handle = this._sendLoop();\n\n this._log.debug('Starting receive loop');\n this._recv_loop_handle = this._recvLoop();\n\n // _disconnected only completes after manual disconnection\n // or errors after which the sender cannot continue such\n // as failing to reconnect or any unexpected error.\n\n this._log.info('Connection to %s complete!'.replace('%s', this._connection.toString()));\n }\n\n async _disconnect() {\n this._send_queue.rejectAll();\n\n if (this._connection === undefined) {\n this._log.info('Not disconnecting (already have no connection)');\n return;\n }\n if (this._updateCallback) {\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.disconnected));\n }\n this._log.info('Disconnecting from %s...'.replace('%s', this._connection.toString()));\n this._user_connected = false;\n this._log.debug('Closing current connection...');\n await this._connection.disconnect();\n }\n\n /**\n * This loop is responsible for popping items off the send\n * queue, encrypting them, and sending them over the network.\n * Besides `connect`, only this method ever sends data.\n * @returns {Promise}\n * @private\n */\n async _sendLoop() {\n this._send_queue = new MessagePacker(this._state, this._log);\n\n while (this._user_connected && !this._reconnecting) {\n if (this._pending_ack.size) {\n const ack = new RequestState(new MsgsAck({ msgIds: Array(...this._pending_ack) }));\n this._send_queue.append(ack);\n this._last_acks.push(ack);\n if (this._last_acks.length >= 10) {\n this._last_acks.shift();\n }\n this._pending_ack.clear();\n }\n this._log.debug(`Waiting for messages to send...${this._reconnecting}`);\n // TODO Wait for the connection send queue to be empty?\n // This means that while it's not empty we can wait for\n // more messages to be added to the send queue.\n const res = await this._send_queue.get();\n\n if (this._reconnecting) {\n return;\n }\n\n if (!res) {\n continue;\n }\n let { data } = res;\n const { batch } = res;\n this._log.debug(`Encrypting ${batch.length} message(s) in ${data.length} bytes for sending`);\n\n data = await this._state.encryptMessageData(data);\n\n try {\n await this._connection.send(data);\n } catch (e) {\n this._log.error(e);\n this._log.info('Connection closed while sending data');\n return;\n }\n for (const state of batch) {\n if (!Array.isArray(state)) {\n if (state.request.classType === 'request') {\n this._pending_state[state.msgId] = state;\n }\n } else {\n for (const s of state) {\n if (s.request.classType === 'request') {\n this._pending_state[s.msgId] = s;\n }\n }\n }\n }\n this._log.debug('Encrypted messages put in a queue to be sent');\n }\n }\n\n async _recvLoop() {\n let body;\n let message;\n\n while (this._user_connected && !this._reconnecting) {\n // this._log.debug('Receiving items from the network...');\n this._log.debug('Receiving items from the network...');\n try {\n body = await this._connection.recv();\n } catch (e) {\n // this._log.info('Connection closed while receiving data');\n /** when the server disconnects us we want to reconnect */\n if (!this.userDisconnected) {\n this._log.error(e);\n this._log.warn('Connection closed while receiving data');\n this.reconnect();\n }\n return;\n }\n try {\n message = await this._state.decryptMessageData(body);\n } catch (e) {\n if (e instanceof TypeNotFoundError) {\n // Received object which we don't know how to deserialize\n this._log.info(`Type ${e.invalidConstructorId} not found, remaining data ${e.remaining}`);\n continue;\n } else if (e instanceof SecurityError) {\n // A step while decoding had the incorrect data. This message\n // should not be considered safe and it should be ignored.\n this._log.warn(`Security error while unpacking a received message: ${e}`);\n continue;\n } else if (e instanceof InvalidBufferError) {\n // 404 means that the server has \"forgotten\" our auth key and we need to create a new one.\n if (e.code === 404) {\n this._log.warn(`Broken authorization key for dc ${this._dcId}; resetting`);\n if (this._updateCallback && this._isMainSender) {\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.broken));\n } else if (this._onConnectionBreak && !this._isMainSender) {\n // Deletes the current sender from the object\n this._onConnectionBreak(this._dcId);\n }\n } else {\n // this happens sometimes when telegram is having some internal issues.\n // reconnecting should be enough usually\n // since the data we sent and received is probably wrong now.\n this._log.warn(`Invalid buffer ${e.code} for dc ${this._dcId}`);\n this.reconnect();\n }\n return;\n } else {\n this._log.error('Unhandled error while receiving data');\n this._log.error(e);\n this.reconnect();\n return;\n }\n }\n try {\n await this._processMessage(message);\n } catch (e) {\n this._log.error('Unhandled error while receiving data');\n this._log.error(e);\n }\n }\n }\n\n // Response Handlers\n\n /**\n * Adds the given message to the list of messages that must be\n * acknowledged and dispatches control to different ``_handle_*``\n * method based on its type.\n * @param message\n * @returns {Promise}\n * @private\n */\n async _processMessage(message) {\n this._pending_ack.add(message.msgId);\n // eslint-disable-next-line require-atomic-updates\n message.obj = await message.obj;\n let handler = this._handlers[message.obj.CONSTRUCTOR_ID];\n if (!handler) {\n handler = this._handleUpdate.bind(this);\n }\n\n await handler(message);\n }\n\n /**\n * Pops the states known to match the given ID from pending messages.\n * This method should be used when the response isn't specific.\n * @param msgId\n * @returns {*[]}\n * @private\n */\n _popStates(msgId) {\n let state = this._pending_state[msgId];\n if (state) {\n this._pending_state[msgId].deferred.resolve();\n delete this._pending_state[msgId];\n return [state];\n }\n\n const toPop = [];\n\n for (state of Object.values(this._pending_state)) {\n if (state.containerId && state.containerId.equals(msgId)) {\n toPop.push(state.msgId);\n }\n }\n\n if (toPop.length) {\n const temp = [];\n for (const x of toPop) {\n temp.push(this._pending_state[x]);\n this._pending_state[x].deferred.resolve();\n delete this._pending_state[x];\n }\n return temp;\n }\n\n for (const ack of this._last_acks) {\n if (ack.msgId === msgId) {\n return [ack];\n }\n }\n\n return [];\n }\n\n /**\n * Handles the result for Remote Procedure Calls:\n * rpc_result#f35c6d01 req_msg_id:long result:bytes = RpcResult;\n * This is where the future results for sent requests are set.\n * @param message\n * @returns {Promise}\n * @private\n */\n _handleRPCResult(message) {\n const result = message.obj;\n const state = this._pending_state[result.reqMsgId];\n if (state) {\n state.deferred.resolve();\n delete this._pending_state[result.reqMsgId];\n }\n this._log.debug(`Handling RPC result for message ${result.reqMsgId}`);\n\n if (!state) {\n // TODO We should not get responses to things we never sent\n // However receiving a File() with empty bytes is \"common\".\n // See #658, #759 and #958. They seem to happen in a container\n // which contain the real response right after.\n try {\n const reader = new BinaryReader(result.body);\n if (!(reader.tgReadObject() instanceof upload.File)) {\n throw new TypeNotFoundError('Not an upload.File');\n }\n } catch (e) {\n this._log.error(e);\n if (e instanceof TypeNotFoundError) {\n this._log.info(`Received response without parent request: ${result.body}`);\n return;\n } else {\n throw e;\n }\n }\n }\n if (result.error) {\n // eslint-disable-next-line new-cap\n const error = RPCMessageToError(result.error, state.request);\n this._send_queue.append(new RequestState(new MsgsAck({ msgIds: [state.msgId] })));\n state.reject(error);\n } else {\n try {\n const reader = new BinaryReader(result.body);\n const read = state.request.readResult(reader);\n state.resolve(read);\n } catch (err) {\n state.reject(err);\n throw err;\n }\n }\n }\n\n /**\n * Processes the inner messages of a container with many of them:\n * msg_container#73f1f8dc messages:vector<%Message> = MessageContainer;\n * @param message\n * @returns {Promise}\n * @private\n */\n async _handleContainer(message) {\n this._log.debug('Handling container');\n for (const innerMessage of message.obj.messages) {\n await this._processMessage(innerMessage);\n }\n }\n\n /**\n * Unpacks the data from a gzipped object and processes it:\n * gzip_packed#3072cfa1 packed_data:bytes = Object;\n * @param message\n * @returns {Promise}\n * @private\n */\n async _handleGzipPacked(message) {\n this._log.debug('Handling gzipped data');\n const reader = new BinaryReader(message.obj.data);\n message.obj = reader.tgReadObject();\n await this._processMessage(message);\n }\n\n _handleUpdate(message) {\n if (message.obj.SUBCLASS_OF_ID !== 0x8af52aac) {\n // crc32(b'Updates')\n this._log.warn(`Note: ${message.obj.className} is not an update, not dispatching it`);\n return;\n }\n this._log.debug(`Handling update ${message.obj.className}`);\n if (this._updateCallback) {\n this._updateCallback(message.obj);\n }\n }\n\n /**\n * Handles pong results, which don't come inside a ``RPCResult``\n * but are still sent through a request:\n * pong#347773c5 msg_id:long ping_id:long = Pong;\n * @param message\n * @returns {Promise}\n * @private\n */\n _handlePong(message) {\n const pong = message.obj;\n\n const newTimeOffset = this._state.updateTimeOffset(message.msgId);\n if (this._updateCallback) {\n this._updateCallback(new UpdateServerTimeOffset(newTimeOffset));\n }\n\n this._log.debug(`Handling pong for message ${pong.msgId}`);\n const state = this._pending_state[pong.msgId];\n this._pending_state[pong.msgId].deferred.resolve();\n delete this._pending_state[pong.msgId];\n\n // Todo Check result\n if (state) {\n state.resolve(pong);\n }\n }\n\n /**\n * Corrects the currently used server salt to use the right value\n * before enqueuing the rejected message to be re-sent:\n * bad_server_salt#edab447b bad_msg_id:long bad_msg_seqno:int\n * error_code:int new_server_salt:long = BadMsgNotification;\n * @param message\n * @returns {Promise}\n * @private\n */\n _handleBadServerSalt(message) {\n const badSalt = message.obj;\n this._log.debug(`Handling bad salt for message ${badSalt.badMsgId}`);\n this._state.salt = badSalt.newServerSalt;\n const states = this._popStates(badSalt.badMsgId);\n this._send_queue.extend(states);\n this._log.debug(`${states.length} message(s) will be resent`);\n }\n\n /**\n * Adjusts the current state to be correct based on the\n * received bad message notification whenever possible:\n * bad_msg_notification#a7eff811 bad_msg_id:long bad_msg_seqno:int\n * error_code:int = BadMsgNotification;\n * @param message\n * @returns {Promise}\n * @private\n */\n _handleBadNotification(message) {\n const badMsg = message.obj;\n const states = this._popStates(badMsg.badMsgId);\n this._log.debug(`Handling bad msg ${JSON.stringify(badMsg)}`);\n if ([16, 17].includes(badMsg.errorCode)) {\n // Sent msg_id too low or too high (respectively).\n // Use the current msg_id to determine the right time offset.\n const newTimeOffset = this._state.updateTimeOffset(message.msgId);\n\n if (this._updateCallback) {\n this._updateCallback(new UpdateServerTimeOffset(newTimeOffset));\n }\n\n this._log.info(`System clock is wrong, set time offset to ${newTimeOffset}s`);\n } else if (badMsg.errorCode === 32) {\n // msg_seqno too low, so just pump it up by some \"large\" amount\n // TODO A better fix would be to start with a new fresh session ID\n this._state._sequence += 64;\n } else if (badMsg.errorCode === 33) {\n // msg_seqno too high never seems to happen but just in case\n this._state._sequence -= 16;\n } else {\n for (const state of states) {\n state.reject(new BadMessageError(state.request, badMsg.errorCode));\n }\n\n return;\n }\n // Messages are to be re-sent once we've corrected the issue\n this._send_queue.extend(states);\n this._log.debug(`${states.length} messages will be resent due to bad msg`);\n }\n\n /**\n * Updates the current status with the received detailed information:\n * msg_detailed_info#276d3ec6 msg_id:long answer_msg_id:long\n * bytes:int status:int = MsgDetailedInfo;\n * @param message\n * @returns {Promise}\n * @private\n */\n _handleDetailedInfo(message) {\n // TODO https://goo.gl/VvpCC6\n const msgId = message.obj.answerMsgId;\n this._log.debug(`Handling detailed info for message ${msgId}`);\n this._pending_ack.add(msgId);\n }\n\n /**\n * Updates the current status with the received detailed information:\n * msg_new_detailed_info#809db6df answer_msg_id:long\n * bytes:int status:int = MsgDetailedInfo;\n * @param message\n * @returns {Promise}\n * @private\n */\n _handleNewDetailedInfo(message) {\n // TODO https://goo.gl/VvpCC6\n const msgId = message.obj.answerMsgId;\n this._log.debug(`Handling new detailed info for message ${msgId}`);\n this._pending_ack.add(msgId);\n }\n\n /**\n * Updates the current status with the received session information:\n * new_session_created#9ec20908 first_msg_id:long unique_id:long\n * server_salt:long = NewSession;\n * @param message\n * @returns {Promise}\n * @private\n */\n _handleNewSessionCreated(message) {\n // TODO https://goo.gl/LMyN7A\n this._log.debug('Handling new session created');\n this._state.salt = message.obj.serverSalt;\n }\n\n /**\n * Handles a server acknowledge about our messages. Normally\n * these can be ignored except in the case of ``auth.logOut``:\n *\n * auth.logOut#5717da40 = Bool;\n *\n * Telegram doesn't seem to send its result so we need to confirm\n * it manually. No other request is known to have this behaviour.\n\n * Since the ID of sent messages consisting of a container is\n * never returned (unless on a bad notification), this method\n * also removes containers messages when any of their inner\n * messages are acknowledged.\n\n * @param message\n * @returns {Promise}\n * @private\n */\n _handleAck(message) {\n const ack = message.obj;\n this._log.debug(`Handling acknowledge for ${ack.msgIds}`);\n for (const msgId of ack.msgIds) {\n const state = this._pending_state[msgId];\n if (state && state.request instanceof LogOut) {\n this._pending_state[msgId].deferred.resolve();\n delete this._pending_state[msgId];\n state.resolve(true);\n }\n }\n }\n\n /**\n * Handles future salt results, which don't come inside a\n * ``rpc_result`` but are still sent through a request:\n * future_salts#ae500895 req_msg_id:long now:int\n * salts:vector = FutureSalts;\n * @param message\n * @returns {Promise}\n * @private\n */\n _handleFutureSalts(message) {\n // TODO save these salts and automatically adjust to the\n // correct one whenever the salt in use expires.\n this._log.debug(`Handling future salts for message ${message.msgId}`);\n const state = this._pending_state[message.msgId];\n\n if (state) {\n this._pending_state[message].deferred.resolve();\n delete this._pending_state[message];\n state.resolve(message.obj);\n }\n }\n\n /**\n * Handles both :tl:`MsgsStateReq` and :tl:`MsgResendReq` by\n * enqueuing a :tl:`MsgsStateInfo` to be sent at a later point.\n * @param message\n * @returns {Promise}\n * @private\n */\n _handleStateForgotten(message) {\n this._send_queue.append(\n new RequestState(new MsgsStateInfo(message.msgId, String.fromCharCode(1)\n .repeat(message.obj.msgIds))),\n );\n }\n\n /**\n * Handles :tl:`MsgsAllInfo` by doing nothing (yet).\n * used as part of the telegram protocol https://core.telegram.org/mtproto/service_messages_about_messages\n * This message does not require an acknowledgment.\n * @param message\n * @returns {Promise}\n * @private\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _handleMsgAll(message) {\n }\n\n reconnect() {\n if (this._user_connected && !this._reconnecting) {\n this._reconnecting = true;\n // TODO Should we set this?\n // this._user_connected = false\n // we want to wait a second between each reconnect try to not flood the server with reconnects\n // in case of internal server issues.\n Helpers.sleep(1000).then(() => {\n this._log.info('Started reconnecting');\n this._reconnect();\n });\n }\n }\n\n async _reconnect() {\n this._log.debug('Closing current connection...');\n try {\n await this._disconnect();\n } catch (err) {\n this._log.warn(err);\n }\n\n this._send_queue.append(undefined);\n this._state.reset();\n\n // For some reason reusing existing connection caused stuck requests\n const newConnection = new this._connection.constructor(\n this._connection._ip,\n this._connection._port,\n this._connection._dcId,\n this._connection._log,\n this._connection._testServers,\n );\n await this.connect(newConnection, true);\n\n this._reconnecting = false;\n // uncomment this if you want to resend\n // this._send_queue.extend(Object.values(this._pending_state))\n for (const state of Object.values(this._pending_state)) {\n state.deferred.resolve();\n }\n this._pending_state = {};\n if (this._autoReconnectCallback) {\n await this._autoReconnectCallback();\n }\n }\n}\n\nmodule.exports = MTProtoSender;\n","const BigInt = require('big-integer');\n\nconst Helpers = require('../Helpers');\nconst IGE = require('../crypto/IGE');\nconst BinaryReader = require('../extensions/BinaryReader');\nconst GZIPPacked = require('../tl/core/GZIPPacked');\nconst { TLMessage } = require('../tl/core');\nconst {\n SecurityError,\n InvalidBufferError,\n} = require('../errors/Common');\nconst { InvokeAfterMsg } = require('../tl').requests;\nconst {\n toSignedLittleBuffer,\n} = require('../Helpers');\n\nclass MTProtoState {\n /**\n *\n `telethon.network.mtprotosender.MTProtoSender` needs to hold a state\n in order to be able to encrypt and decrypt incoming/outgoing messages,\n as well as generating the message IDs. Instances of this class hold\n together all the required information.\n\n It doesn't make sense to use `telethon.sessions.abstract.Session` for\n the sender because the sender should *not* be concerned about storing\n this information to disk, as one may create as many senders as they\n desire to any other data center, or some CDN. Using the same session\n for all these is not a good idea as each need their own authkey, and\n the concept of \"copying\" sessions with the unnecessary entities or\n updates state for these connections doesn't make sense.\n\n While it would be possible to have a `MTProtoPlainState` that does no\n encryption so that it was usable through the `MTProtoLayer` and thus\n avoid the need for a `MTProtoPlainSender`, the `MTProtoLayer` is more\n focused to efficiency and this state is also more advanced (since it\n supports gzipping and invoking after other message IDs). There are too\n many methods that would be needed to make it convenient to use for the\n authentication process, at which point the `MTProtoPlainSender` is better\n * @param authKey\n * @param loggers\n */\n constructor(authKey, loggers) {\n this.authKey = authKey;\n this._log = loggers;\n this.timeOffset = 0;\n this.salt = 0;\n\n this.id = undefined;\n this._sequence = undefined;\n this._lastMsgId = undefined;\n this.reset();\n }\n\n /**\n * Resets the state\n */\n reset() {\n // Session IDs can be random on every connection\n this.id = Helpers.generateRandomLong(true);\n this._sequence = 0;\n this._lastMsgId = BigInt(0);\n }\n\n /**\n * Updates the message ID to a new one,\n * used when the time offset changed.\n * @param message\n */\n updateMessageId(message) {\n message.msgId = this._getNewMsgId();\n }\n\n /**\n * Calculate the key based on Telegram guidelines, specifying whether it's the client or not\n * @param authKey\n * @param msgKey\n * @param client\n * @returns {{iv: Buffer, key: Buffer}}\n */\n async _calcKey(authKey, msgKey, client) {\n const x = client === true ? 0 : 8;\n const [sha256a, sha256b] = await Promise.all([\n Helpers.sha256(Buffer.concat([msgKey, authKey.slice(x, x + 36)])),\n Helpers.sha256(Buffer.concat([authKey.slice(x + 40, x + 76), msgKey])),\n ]);\n const key = Buffer.concat([sha256a.slice(0, 8), sha256b.slice(8, 24), sha256a.slice(24, 32)]);\n const iv = Buffer.concat([sha256b.slice(0, 8), sha256a.slice(8, 24), sha256b.slice(24, 32)]);\n return {\n key,\n iv,\n };\n }\n\n /**\n * Writes a message containing the given data into buffer.\n * Returns the message id.\n * @param buffer\n * @param data\n * @param contentRelated\n * @param afterId\n */\n async writeDataAsMessage(buffer, data, contentRelated, afterId) {\n const msgId = this._getNewMsgId();\n const seqNo = this._getSeqNo(contentRelated);\n let body;\n if (!afterId) {\n body = await GZIPPacked.gzipIfSmaller(contentRelated, data);\n } else {\n // Invoke query expects a query with a getBytes func\n body = await GZIPPacked.gzipIfSmaller(contentRelated, new InvokeAfterMsg(afterId, {\n getBytes() {\n return data;\n },\n }).getBytes());\n }\n const s = Buffer.alloc(4);\n s.writeInt32LE(seqNo, 0);\n const b = Buffer.alloc(4);\n b.writeInt32LE(body.length, 0);\n const m = toSignedLittleBuffer(msgId, 8);\n buffer.write(Buffer.concat([m, s, b]));\n buffer.write(body);\n return msgId;\n }\n\n /**\n * Encrypts the given message data using the current authorization key\n * following MTProto 2.0 guidelines core.telegram.org/mtproto/description.\n * @param data\n */\n async encryptMessageData(data) {\n await this.authKey.waitForKey();\n const s = toSignedLittleBuffer(this.salt, 8);\n const i = toSignedLittleBuffer(this.id, 8);\n data = Buffer.concat([Buffer.concat([s, i]), data]);\n const padding = Helpers.generateRandomBytes(Helpers.mod(-(data.length + 12), 16) + 12);\n // Being substr(what, offset, length); x = 0 for client\n // \"msg_key_large = SHA256(substr(auth_key, 88+x, 32) + pt + padding)\"\n const msgKeyLarge = await Helpers.sha256(Buffer.concat([this.authKey.getKey()\n .slice(88, 88 + 32), data, padding]));\n // \"msg_key = substr (msg_key_large, 8, 16)\"\n const msgKey = msgKeyLarge.slice(8, 24);\n\n const {\n iv,\n key,\n } = await this._calcKey(this.authKey.getKey(), msgKey, true);\n\n const keyId = Helpers.readBufferFromBigInt(this.authKey.keyId, 8);\n return Buffer.concat([keyId, msgKey, new IGE(key, iv).encryptIge(Buffer.concat([data, padding]))]);\n }\n\n /**\n * Inverse of `encrypt_message_data` for incoming server messages.\n * @param body\n */\n async decryptMessageData(body) {\n if (body.length < 8) {\n throw new InvalidBufferError(body);\n }\n if (body.length < 0) { // length needs to be positive\n throw new SecurityError('Server replied with negative length');\n }\n if (body.length % 4 !== 0) {\n throw new SecurityError('Server replied with length not divisible by 4');\n }\n // TODO Check salt,sessionId, and sequenceNumber\n const keyId = Helpers.readBigIntFromBuffer(body.slice(0, 8));\n if (keyId.neq(this.authKey.keyId)) {\n throw new SecurityError('Server replied with an invalid auth key');\n }\n\n const msgKey = body.slice(8, 24);\n const {\n iv,\n key,\n } = await this._calcKey(this.authKey.getKey(), msgKey, false);\n body = new IGE(key, iv).decryptIge(body.slice(24));\n\n // https://core.telegram.org/mtproto/security_guidelines\n // Sections \"checking sha256 hash\" and \"message length\"\n\n const ourKey = await Helpers.sha256(Buffer.concat([this.authKey.getKey()\n .slice(96, 96 + 32), body]));\n\n if (!msgKey.equals(ourKey.slice(8, 24))) {\n throw new SecurityError('Received msg_key doesn\\'t match with expected one');\n }\n\n const reader = new BinaryReader(body);\n reader.readLong(); // removeSalt\n const serverId = reader.readLong();\n if (!serverId.eq(this.id)) {\n throw new SecurityError('Server replied with a wrong session ID');\n }\n\n const remoteMsgId = reader.readLong();\n const remoteSequence = reader.readInt();\n const containerLen = reader.readInt(); // msgLen for the inner object, padding ignored\n const diff = body.length - containerLen;\n // We want to check if it's between 12 and 1024\n // https://core.telegram.org/mtproto/security_guidelines#checking-message-length\n if (diff < 12 || diff > 1024) {\n throw new SecurityError('Server replied with the wrong message padding');\n }\n\n // We could read msg_len bytes and use those in a new reader to read\n // the next TLObject without including the padding, but since the\n // reader isn't used for anything else after this, it's unnecessary.\n const obj = reader.tgReadObject();\n\n return new TLMessage(remoteMsgId, remoteSequence, obj);\n }\n\n /**\n * Generates a new unique message ID based on the current\n * time (in ms) since epoch, applying a known time offset.\n * @private\n */\n _getNewMsgId() {\n const now = new Date().getTime() / 1000 + this.timeOffset;\n const nanoseconds = Math.floor((now - Math.floor(now)) * 1e9);\n let newMsgId = (BigInt(Math.floor(now))\n .shiftLeft(BigInt(32))).or(BigInt(nanoseconds)\n .shiftLeft(BigInt(2)));\n if (this._lastMsgId.greaterOrEquals(newMsgId)) {\n newMsgId = this._lastMsgId.add(BigInt(4));\n }\n this._lastMsgId = newMsgId;\n return newMsgId;\n }\n\n /**\n * Updates the time offset to the correct\n * one given a known valid message ID.\n * @param correctMsgId {BigInteger}\n */\n updateTimeOffset(correctMsgId) {\n const bad = this._getNewMsgId();\n const old = this.timeOffset;\n const now = Math.floor(new Date().getTime() / 1000);\n const correct = correctMsgId.shiftRight(BigInt(32));\n this.timeOffset = correct - now;\n\n if (this.timeOffset !== old) {\n this._lastMsgId = BigInt(0);\n this._log.debug(\n `Updated time offset (old offset ${old}, bad ${bad}, good ${correctMsgId}, new ${this.timeOffset})`,\n );\n }\n\n return this.timeOffset;\n }\n\n /**\n * Generates the next sequence number depending on whether\n * it should be for a content-related query or not.\n * @param contentRelated\n * @private\n */\n _getSeqNo(contentRelated) {\n if (contentRelated) {\n const result = this._sequence * 2 + 1;\n this._sequence += 1;\n return result;\n } else {\n return this._sequence * 2;\n }\n }\n}\n\nmodule.exports = MTProtoState;\n","const { createDeferred } = require('../Helpers');\n\nclass RequestState {\n constructor(request, after = undefined, pending = {}) {\n this.containerId = undefined;\n this.msgId = undefined;\n this.request = request;\n this.data = request.getBytes();\n this.after = after;\n this.result = undefined;\n this.pending = pending;\n this.deferred = createDeferred();\n this.promise = new Promise((resolve, reject) => {\n this.resolve = resolve;\n this.reject = reject;\n });\n }\n\n isReady() {\n const state = this.pending[this.after.id];\n if (!state) {\n return true;\n }\n return state.deferred.promise;\n }\n}\n\nmodule.exports = RequestState;\n","const PromisedWebSockets = require('../../extensions/PromisedWebSockets');\nconst AsyncQueue = require('../../extensions/AsyncQueue');\n\n/**\n * The `Connection` class is a wrapper around ``asyncio.open_connection``.\n *\n * Subclasses will implement different transport modes as atomic operations,\n * which this class eases doing since the exposed interface simply puts and\n * gets complete data payloads to and from queues.\n *\n * The only error that will raise from send and receive methods is\n * ``ConnectionError``, which will raise when attempting to send if\n * the client is disconnected (includes remote disconnections).\n */\nclass Connection {\n PacketCodecClass = undefined;\n\n constructor(ip, port, dcId, loggers, testServers) {\n this._ip = ip;\n this._port = port;\n this._dcId = dcId;\n this._log = loggers;\n this._testServers = testServers;\n this._connected = false;\n this._sendTask = undefined;\n this._recvTask = undefined;\n this._codec = undefined;\n this._obfuscation = undefined; // TcpObfuscated and MTProxy\n this._sendArray = new AsyncQueue();\n this._recvArray = new AsyncQueue();\n // this.socket = new PromiseSocket(new Socket())\n\n this.socket = new PromisedWebSockets(this.disconnectCallback.bind(this));\n }\n\n async disconnectCallback() {\n await this.disconnect(true);\n }\n\n async _connect() {\n this._log.debug('Connecting');\n this._codec = new this.PacketCodecClass(this);\n await this.socket.connect(this._port, this._ip, this._testServers);\n this._log.debug('Finished connecting');\n // await this.socket.connect({host: this._ip, port: this._port});\n await this._initConn();\n }\n\n async connect() {\n await this._connect();\n this._connected = true;\n\n if (!this._sendTask) {\n this._sendTask = this._sendLoop();\n }\n this._recvTask = this._recvLoop();\n }\n\n async disconnect(fromCallback = false) {\n if (!this._connected) {\n return;\n }\n\n this._connected = false;\n void this._recvArray.push(undefined);\n if (!fromCallback) {\n await this.socket.close();\n }\n }\n\n async send(data) {\n if (!this._connected) {\n throw new Error('Not connected');\n }\n await this._sendArray.push(data);\n }\n\n async recv() {\n while (this._connected) {\n const result = await this._recvArray.pop();\n // null = sentinel value = keep trying\n if (result) {\n return result;\n }\n }\n throw new Error('Not connected');\n }\n\n async _sendLoop() {\n // TODO handle errors\n try {\n while (this._connected) {\n const data = await this._sendArray.pop();\n if (!data) {\n this._sendTask = undefined;\n return;\n }\n await this._send(data);\n }\n } catch (e) {\n this._log.info('The server closed the connection while sending');\n }\n }\n\n async _recvLoop() {\n let data;\n while (this._connected) {\n try {\n data = await this._recv();\n if (!data) {\n throw new Error('no data received');\n }\n } catch (e) {\n this._log.info('connection closed');\n // await this._recvArray.push()\n\n this.disconnect();\n return;\n }\n await this._recvArray.push(data);\n }\n }\n\n async _initConn() {\n if (this._codec.tag) {\n await this.socket.write(this._codec.tag);\n }\n }\n\n _send(data) {\n const encodedPacket = this._codec.encodePacket(data);\n this.socket.write(encodedPacket);\n }\n\n _recv() {\n return this._codec.readPacket(this.socket);\n }\n\n toString() {\n return `${this._ip}:${this._port}/${this.constructor.name.replace('Connection', '')}`;\n }\n}\n\nclass ObfuscatedConnection extends Connection {\n ObfuscatedIO = undefined;\n\n _initConn() {\n this._obfuscation = new this.ObfuscatedIO(this);\n this.socket.write(this._obfuscation.header);\n }\n\n _send(data) {\n this._obfuscation.write(this._codec.encodePacket(data));\n }\n\n _recv() {\n return this._codec.readPacket(this._obfuscation);\n }\n}\n\nclass PacketCodec {\n constructor(connection) {\n this._conn = connection;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n encodePacket(data) {\n throw new Error('Not Implemented');\n\n // Override\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n readPacket(reader) {\n // override\n throw new Error('Not Implemented');\n }\n}\n\nmodule.exports = {\n Connection,\n PacketCodec,\n ObfuscatedConnection,\n};\n","const BigInt = require('big-integer');\nconst { readBufferFromBigInt } = require('../../Helpers');\nconst {\n Connection,\n PacketCodec,\n} = require('./Connection');\n\nclass AbridgedPacketCodec extends PacketCodec {\n static tag = Buffer.from('ef', 'hex');\n\n static obfuscateTag = Buffer.from('efefefef', 'hex');\n\n constructor(props) {\n super(props);\n this.tag = AbridgedPacketCodec.tag;\n this.obfuscateTag = AbridgedPacketCodec.obfuscateTag;\n }\n\n encodePacket(data) {\n let length = data.length >> 2;\n if (length < 127) {\n const b = Buffer.alloc(1);\n b.writeUInt8(length, 0);\n length = b;\n } else {\n length = Buffer.concat([Buffer.from('7f', 'hex'), readBufferFromBigInt(BigInt(length), 3)]);\n }\n return Buffer.concat([length, data]);\n }\n\n async readPacket(reader) {\n const readData = await reader.read(1);\n let length = readData[0];\n if (length >= 127) {\n length = Buffer.concat([await reader.read(3), Buffer.alloc(1)])\n .readInt32LE(0);\n }\n\n return reader.read(length << 2);\n }\n}\n\n/**\n * This is the mode with the lowest overhead, as it will\n * only require 1 byte if the packet length is less than\n * 508 bytes (127 << 2, which is very common).\n */\nclass ConnectionTCPAbridged extends Connection {\n PacketCodecClass = AbridgedPacketCodec;\n}\n\nmodule.exports = {\n ConnectionTCPAbridged,\n AbridgedPacketCodec,\n};\n","const { generateRandomBytes } = require('../../Helpers');\nconst { ObfuscatedConnection } = require('./Connection');\nconst { AbridgedPacketCodec } = require('./TCPAbridged');\nconst CTR = require('../../crypto/CTR');\n\nclass ObfuscatedIO {\n header = undefined;\n\n constructor(connection) {\n this.connection = connection.socket;\n const res = this.initHeader(connection.PacketCodecClass);\n this.header = res.random;\n\n this._encrypt = res.encryptor;\n this._decrypt = res.decryptor;\n }\n\n initHeader(packetCodec) {\n // Obfuscated messages secrets cannot start with any of these\n const keywords = [Buffer.from('50567247', 'hex'), Buffer.from('474554', 'hex'),\n Buffer.from('504f5354', 'hex'), Buffer.from('eeeeeeee', 'hex')];\n let random;\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n random = generateRandomBytes(64);\n if (random[0] !== 0xef && !(random.slice(4, 8)\n .equals(Buffer.alloc(4)))) {\n let ok = true;\n for (const key of keywords) {\n if (key.equals(random.slice(0, 4))) {\n ok = false;\n break;\n }\n }\n if (ok) {\n break;\n }\n }\n }\n random = random.toJSON().data;\n\n const randomReversed = Buffer.from(random.slice(8, 56))\n .reverse();\n // Encryption has \"continuous buffer\" enabled\n const encryptKey = Buffer.from(random.slice(8, 40));\n const encryptIv = Buffer.from(random.slice(40, 56));\n const decryptKey = Buffer.from(randomReversed.slice(0, 32));\n const decryptIv = Buffer.from(randomReversed.slice(32, 48));\n const encryptor = new CTR(encryptKey, encryptIv);\n const decryptor = new CTR(decryptKey, decryptIv);\n\n random = Buffer.concat([\n Buffer.from(random.slice(0, 56)), packetCodec.obfuscateTag, Buffer.from(random.slice(60)),\n ]);\n random = Buffer.concat([\n Buffer.from(random.slice(0, 56)), Buffer.from(encryptor.encrypt(random)\n .slice(56, 64)), Buffer.from(random.slice(64)),\n ]);\n return {\n random,\n encryptor,\n decryptor,\n };\n }\n\n async read(n) {\n const data = await this.connection.readExactly(n);\n return this._decrypt.encrypt(data);\n }\n\n write(data) {\n this.connection.write(this._encrypt.encrypt(data));\n }\n}\n\nclass ConnectionTCPObfuscated extends ObfuscatedConnection {\n ObfuscatedIO = ObfuscatedIO;\n\n PacketCodecClass = AbridgedPacketCodec;\n}\n\nmodule.exports = {\n ConnectionTCPObfuscated,\n};\n","const { Connection } = require('./Connection');\nconst { ConnectionTCPFull } = require('./TCPFull');\nconst { ConnectionTCPAbridged } = require('./TCPAbridged');\nconst { ConnectionTCPObfuscated } = require('./TCPObfuscated');\n\nmodule.exports = {\n Connection,\n ConnectionTCPFull,\n ConnectionTCPAbridged,\n ConnectionTCPObfuscated,\n};\n","const MTProtoPlainSender = require('./MTProtoPlainSender');\nconst MTProtoSender = require('./MTProtoSender');\n\nclass UpdateConnectionState {\n static disconnected = -1;\n\n static connected = 1;\n\n static broken = 0;\n\n constructor(state) {\n this.state = state;\n }\n}\n\nclass UpdateServerTimeOffset {\n constructor(timeOffset) {\n this.timeOffset = timeOffset;\n }\n}\n\nconst {\n Connection,\n ConnectionTCPFull,\n ConnectionTCPAbridged,\n ConnectionTCPObfuscated,\n} = require('./connection');\n\nmodule.exports = {\n Connection,\n ConnectionTCPFull,\n ConnectionTCPAbridged,\n ConnectionTCPObfuscated,\n MTProtoPlainSender,\n MTProtoSender,\n UpdateConnectionState,\n UpdateServerTimeOffset,\n};\n","class Session {\n /**\n * Creates a clone of this session file\n * @param toInstance {Session|null}\n * @returns {Session}\n */\n\n /* CONTEST\n clone(toInstance = null) {\n return toInstance || new this.constructor()\n } */\n\n /**\n * Returns the currently-used data center ID.\n */\n get dcId() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Returns the server address where the library should connect to.\n */\n get serverAddress() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Returns the port to which the library should connect to.\n */\n get port() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Returns an ``AuthKey`` instance associated with the saved\n * data center, or `None` if a new one should be generated.\n */\n get authKey() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Sets the ``AuthKey`` to be used for the saved data center.\n * @param value\n */\n set authKey(value) {\n throw new Error('Not Implemented');\n }\n\n /**\n * Sets the information of the data center address and port that\n * the library should connect to, as well as the data center ID,\n * which is currently unused.\n * @param dcId {number}\n * @param serverAddress {string}\n * @param port {number}\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n setDC(dcId, serverAddress, port) {\n throw new Error('Not implemented');\n }\n\n /**\n * Returns an ID of the takeout process initialized for this session,\n * or `None` if there's no were any unfinished takeout requests.\n */\n /* CONTEST\n get takeoutId() {\n throw new Error('Not Implemented')\n }\n */\n /**\n * Sets the ID of the unfinished takeout process for this session.\n * @param value\n */\n /* CONTEST\n set takeoutId(value) {\n throw new Error('Not Implemented')\n }\n */\n /**\n * Returns the ``UpdateState`` associated with the given `entity_id`.\n * If the `entity_id` is 0, it should return the ``UpdateState`` for\n * no specific channel (the \"general\" state). If no state is known\n * it should ``return None``.\n * @param entityId\n */\n /* CONTEST\n getUpdateState(entityId) {\n throw new Error('Not Implemented')\n }\n\n */\n\n /**\n * Sets the given ``UpdateState`` for the specified `entity_id`, which\n * should be 0 if the ``UpdateState`` is the \"general\" state (and not\n * for any specific channel).\n * @param entityId\n * @param state\n */\n /* CONTEST\n setUpdateState(entityId, state) {\n throw new Error('Not Implemented')\n }\n\n */\n\n /**\n * Called on client disconnection. Should be used to\n * free any used resources. Can be left empty if none.\n */\n\n /* CONTEST\n close() {\n\n }\n\n */\n\n /**\n * called whenever important properties change. It should\n * make persist the relevant session information to disk.\n */\n save() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Called upon client.log_out(). Should delete the stored\n * information from disk since it's not valid anymore.\n */\n\n delete() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Lists available sessions. Not used by the library itself.\n */\n /* CONTEST\n listSessions() {\n throw new Error('Not Implemented')\n }\n\n */\n\n /**\n * Processes the input ``TLObject`` or ``list`` and saves\n * whatever information is relevant (e.g., ID or access hash).\n * @param tlo\n */\n /* CONTEST\n processEntities(tlo) {\n throw new Error('Not Implemented')\n }\n\n */\n\n /**\n * Turns the given key into an ``InputPeer`` (e.g. ``InputPeerUser``).\n * The library uses this method whenever an ``InputPeer`` is needed\n * to suit several purposes (e.g. user only provided its ID or wishes\n * to use a cached username to avoid extra RPC).\n */\n /* CONTEST\n getInputEntity(key) {\n throw new Error('Not Implemented')\n }\n\n */\n}\n\nmodule.exports = Session;\n","/* eslint-disable no-restricted-globals */\nconst StorageSession = require('./StorageSession');\n\nconst CACHE_NAME = 'GramJs';\n\nclass CacheApiSession extends StorageSession {\n async _delete() {\n const request = new Request(this._storageKey);\n const cache = await self.caches.open(CACHE_NAME);\n return cache.delete(request);\n }\n\n async _fetchFromCache() {\n const request = new Request(this._storageKey);\n const cache = await self.caches.open(CACHE_NAME);\n const cached = await cache.match(request);\n return cached ? cached.text() : undefined;\n }\n\n async _saveToCache(data) {\n const request = new Request(this._storageKey);\n const response = new Response(data);\n const cache = await self.caches.open(CACHE_NAME);\n return cache.put(request, response);\n }\n}\n\nmodule.exports = CacheApiSession;\n","const MemorySession = require('./Memory');\nconst AuthKey = require('../crypto/AuthKey');\nconst utils = require('../Utils');\n\nclass CallbackSession extends MemorySession {\n constructor(sessionData, callback) {\n super();\n\n this._sessionData = sessionData;\n this._callback = callback;\n\n this._authKeys = {};\n }\n\n get authKey() {\n throw new Error('Not supported');\n }\n\n set authKey(value) {\n throw new Error('Not supported');\n }\n\n async load() {\n if (!this._sessionData) {\n return;\n }\n\n const {\n mainDcId,\n keys,\n hashes,\n } = this._sessionData;\n const {\n ipAddress,\n port,\n } = utils.getDC(mainDcId);\n\n this.setDC(mainDcId, ipAddress, port, true);\n\n await Promise.all(Object.keys(keys)\n .map(async (dcId) => {\n const key = typeof keys[dcId] === 'string'\n ? Buffer.from(keys[dcId], 'hex')\n : Buffer.from(keys[dcId]);\n\n if (hashes[dcId]) {\n const hash = typeof hashes[dcId] === 'string'\n ? Buffer.from(hashes[dcId], 'hex')\n : Buffer.from(hashes[dcId]);\n\n this._authKeys[dcId] = new AuthKey(key, hash);\n } else {\n this._authKeys[dcId] = new AuthKey();\n await this._authKeys[dcId].setKey(key, true);\n }\n }));\n }\n\n setDC(dcId, serverAddress, port, skipOnUpdate = false) {\n this._dcId = dcId;\n this._serverAddress = serverAddress;\n this._port = port;\n\n delete this._authKeys[dcId];\n\n if (!skipOnUpdate) {\n void this._onUpdate();\n }\n }\n\n getAuthKey(dcId = this._dcId) {\n return this._authKeys[dcId];\n }\n\n setAuthKey(authKey, dcId = this._dcId) {\n this._authKeys[dcId] = authKey;\n\n void this._onUpdate();\n }\n\n getSessionData() {\n const sessionData = {\n mainDcId: this._dcId,\n keys: {},\n hashes: {},\n };\n\n Object\n .keys(this._authKeys)\n .forEach((dcId) => {\n const authKey = this._authKeys[dcId];\n if (!authKey || !authKey._key) return;\n\n sessionData.keys[dcId] = authKey._key.toString('hex');\n sessionData.hashes[dcId] = authKey._hash.toString('hex');\n });\n\n return sessionData;\n }\n\n _onUpdate() {\n this._callback(this.getSessionData());\n }\n\n delete() {\n this._callback(undefined);\n }\n}\n\nmodule.exports = CallbackSession;\n","const idb = require('idb-keyval');\nconst StorageSession = require('./StorageSession');\n\nconst CACHE_NAME = 'GramJs';\n\nclass IdbSession extends StorageSession {\n _delete() {\n return idb.del(`${CACHE_NAME}:${this._storageKey}`);\n }\n\n _fetchFromCache() {\n return idb.get(`${CACHE_NAME}:${this._storageKey}`);\n }\n\n _saveToCache(data) {\n return idb.set(`${CACHE_NAME}:${this._storageKey}`, data);\n }\n}\n\nmodule.exports = IdbSession;\n","const StorageSession = require('./StorageSession');\n\nclass LocalStorageSession extends StorageSession {\n _delete() {\n return localStorage.removeItem(this._storageKey);\n }\n\n _fetchFromCache() {\n return localStorage.getItem(this._storageKey);\n }\n\n _saveToCache(data) {\n return localStorage.setItem(this._storageKey, data);\n }\n}\n\nmodule.exports = LocalStorageSession;\n","const Session = require('./Abstract');\n\nclass MemorySession extends Session {\n constructor() {\n super();\n\n this._serverAddress = undefined;\n this._dcId = 0;\n this._port = undefined;\n this._takeoutId = undefined;\n\n this._entities = new Set();\n this._updateStates = {};\n }\n\n get dcId() {\n return this._dcId;\n }\n\n get serverAddress() {\n return this._serverAddress;\n }\n\n get port() {\n return this._port;\n }\n\n get authKey() {\n return this._authKey;\n }\n\n set authKey(value) {\n this._authKey = value;\n }\n\n setDC(dcId, serverAddress, port) {\n this._dcId = dcId | 0;\n this._serverAddress = serverAddress;\n this._port = port;\n }\n\n /* CONTEST\n get takeoutId() {\n return this._takeoutId\n }\n\n set takeoutId(value) {\n this._takeoutId = value\n }\n\n\n getUpdateState(entityId) {\n return this._updateStates[entityId]\n }\n\n setUpdateState(entityId, state) {\n return this._updateStates[entityId] = state\n }\n\n close() {\n }\n\n save() {\n }\n\n async load() {\n\n }\n\n delete() {\n }\n\n _entityValuesToRow(id, hash, username, phone, name) {\n // While this is a simple implementation it might be overrode by,\n // other classes so they don't need to implement the plural form\n // of the method. Don't remove.\n return [id, hash, username, phone, name]\n }\n\n _entityToRow(e) {\n if (!(e.classType === \"constructor\")) {\n return\n }\n let p\n let markedId\n try {\n p = utils.getInputPeer(e, false)\n markedId = utils.getPeerId(p)\n } catch (e) {\n // Note: `get_input_peer` already checks for non-zero `accessHash`.\n // See issues #354 and #392. It also checks that the entity\n // is not `min`, because its `accessHash` cannot be used\n // anywhere (since layer 102, there are two access hashes).\n return\n }\n let pHash\n if (p instanceof types.InputPeerUser || p instanceof types.InputPeerChannel) {\n pHash = p.accessHash\n } else if (p instanceof types.InputPeerChat) {\n pHash = 0\n } else {\n return\n }\n\n let username = e.username\n if (username) {\n username = username.toLowerCase()\n }\n const phone = e.phone\n const name = utils.getDisplayName(e)\n return this._entityValuesToRow(markedId, pHash, username, phone, name)\n }\n\n _entitiesToRows(tlo) {\n let entities = []\n if (tlo.classType === \"constructor\" && utils.isListLike(tlo)) {\n // This may be a list of users already for instance\n entities = tlo\n } else {\n if (tlo instanceof Object) {\n if ('user' in tlo) {\n entities.push(tlo.user)\n }\n if ('chats' in tlo && utils.isListLike(tlo.chats)) {\n entities.concat(tlo.chats)\n }\n if ('users' in tlo && utils.isListLike(tlo.users)) {\n entities.concat(tlo.users)\n }\n }\n }\n const rows = [] // Rows to add (id, hash, username, phone, name)\n for (const e of entities) {\n const row = this._entityToRow(e)\n if (row) {\n rows.push(row)\n }\n }\n return rows\n }\n\n processEntities(tlo) {\n const entitiesSet = this._entitiesToRows(tlo)\n for (const e of entitiesSet) {\n this._entities.add(e)\n }\n }\n\n getEntityRowsByPhone(phone) {\n for (const e of this._entities) { // id, hash, username, phone, name\n if (e[3] === phone) {\n return [e[0], e[1]]\n }\n }\n }\n\n getEntityRowsByUsername(username) {\n for (const e of this._entities) { // id, hash, username, phone, name\n if (e[2] === username) {\n return [e[0], e[1]]\n }\n }\n }\n\n getEntityRowsByName(name) {\n for (const e of this._entities) { // id, hash, username, phone, name\n if (e[4] === name) {\n return [e[0], e[1]]\n }\n }\n }\n\n getEntityRowsById(id, exact = true) {\n if (exact) {\n for (const e of this._entities) { // id, hash, username, phone, name\n if (e[0] === id) {\n return [e[0], e[1]]\n }\n }\n } else {\n const ids = [utils.getPeerId(new types.PeerUser({ userId: id })),\n utils.getPeerId(new types.PeerChat({ chatId: id })),\n utils.getPeerId(new types.PeerChannel({ channelId: id })),\n ]\n for (const e of this._entities) { // id, hash, username, phone, name\n if (ids.includes(e[0])) {\n return [e[0], e[1]]\n }\n }\n }\n }\n\n getInputEntity(key) {\n let exact\n if (key.SUBCLASS_OF_ID !== undefined) {\n if ([0xc91c90b6, 0xe669bf46, 0x40f202fd].includes(key.SUBCLASS_OF_ID)) {\n // hex(crc32(b'InputPeer', b'InputUser' and b'InputChannel'))\n // We already have an Input version, so nothing else required\n return key\n }\n // Try to early return if this key can be casted as input peer\n return utils.getInputPeer(key)\n } else {\n // Not a TLObject or can't be cast into InputPeer\n if (key.classType === 'constructor') {\n key = utils.getPeerId(key)\n exact = true\n } else {\n exact = !(typeof key == 'number') || key < 0\n }\n }\n let result = null\n if (typeof key === 'string') {\n const phone = utils.parsePhone(key)\n if (phone) {\n result = this.getEntityRowsByPhone(phone)\n } else {\n const { username, isInvite } = utils.parseUsername(key)\n if (username && !isInvite) {\n result = this.getEntityRowsByUsername(username)\n } else {\n const tup = utils.resolveInviteLink(key)[1]\n if (tup) {\n result = this.getEntityRowsById(tup, false)\n }\n }\n }\n } else if (typeof key === 'number') {\n result = this.getEntityRowsById(key, exact)\n }\n if (!result && typeof key === 'string') {\n result = this.getEntityRowsByName(key)\n }\n\n if (result) {\n let entityId = result[0] // unpack resulting tuple\n const entityHash = result[1]\n const resolved = utils.resolveId(entityId)\n entityId = resolved[0]\n const kind = resolved[1]\n // removes the mark and returns type of entity\n if (kind === types.PeerUser) {\n return new types.InputPeerUser({ userId: entityId, accessHash: entityHash })\n } else if (kind === types.PeerChat) {\n return new types.InputPeerChat({ chatId: entityId })\n } else if (kind === types.PeerChannel) {\n return new types.InputPeerChannel({ channelId: entityId, accessHash: entityHash })\n }\n } else {\n throw new Error('Could not find input entity with key ' + key)\n }\n } */\n}\n\nmodule.exports = MemorySession;\n","const MemorySession = require('./Memory');\nconst AuthKey = require('../crypto/AuthKey');\nconst utils = require('../Utils');\n\nconst STORAGE_KEY_BASE = 'GramJs-session-';\nconst SESSION_DATA_PREFIX = 'session:';\n\nclass StorageSession extends MemorySession {\n constructor(sessionInfo) {\n super();\n\n this._authKeys = {};\n\n if (sessionInfo && sessionInfo.startsWith(SESSION_DATA_PREFIX)) {\n this._sessionString = sessionInfo;\n } else if (sessionInfo) {\n this._storageKey = sessionInfo;\n }\n }\n\n get authKey() {\n throw new Error('Not supported');\n }\n\n set authKey(value) {\n throw new Error('Not supported');\n }\n\n async load() {\n if (this._sessionString) {\n await this._loadFromSessionString();\n return;\n }\n\n if (!this._storageKey) {\n return;\n }\n\n try {\n const json = await this._fetchFromCache();\n const {\n mainDcId,\n keys,\n hashes,\n } = JSON.parse(json);\n const {\n ipAddress,\n port,\n } = utils.getDC(mainDcId);\n\n this.setDC(mainDcId, ipAddress, port, true);\n\n Object.keys(keys)\n .forEach((dcId) => {\n if (keys[dcId] && hashes[dcId]) {\n this._authKeys[dcId] = new AuthKey(\n Buffer.from(keys[dcId].data),\n Buffer.from(hashes[dcId].data),\n );\n }\n });\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn('Failed to retrieve or parse session from storage');\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n }\n\n setDC(dcId, serverAddress, port, skipUpdateStorage = false) {\n this._dcId = dcId;\n this._serverAddress = serverAddress;\n this._port = port;\n\n delete this._authKeys[dcId];\n\n if (!skipUpdateStorage) {\n void this._updateStorage();\n }\n }\n\n async save() {\n if (!this._storageKey) {\n this._storageKey = generateStorageKey();\n }\n\n await this._updateStorage();\n\n return this._storageKey;\n }\n\n getAuthKey(dcId = this._dcId) {\n return this._authKeys[dcId];\n }\n\n setAuthKey(authKey, dcId = this._dcId) {\n this._authKeys[dcId] = authKey;\n\n void this._updateStorage();\n }\n\n getSessionData(asHex) {\n const sessionData = {\n mainDcId: this._dcId,\n keys: {},\n hashes: {},\n };\n\n Object\n .keys(this._authKeys)\n .forEach((dcId) => {\n const authKey = this._authKeys[dcId];\n if (!authKey._key) return;\n\n sessionData.keys[dcId] = asHex ? authKey._key.toString('hex') : authKey._key;\n sessionData.hashes[dcId] = asHex ? authKey._hash.toString('hex') : authKey._hash;\n });\n\n return sessionData;\n }\n\n async _loadFromSessionString() {\n const [, mainDcIdStr, mainDcKey] = this._sessionString.split(':');\n const mainDcId = Number(mainDcIdStr);\n const {\n ipAddress,\n port,\n } = utils.getDC(mainDcId);\n this.setDC(mainDcId, ipAddress, port);\n const authKey = new AuthKey();\n await authKey.setKey(Buffer.from(mainDcKey, 'hex'), true);\n this.setAuthKey(authKey, mainDcId);\n }\n\n async _updateStorage() {\n if (!this._storageKey) {\n return;\n }\n\n try {\n await this._saveToCache(JSON.stringify(this.getSessionData()));\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn('Failed to update session in storage');\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n }\n\n async delete() {\n try {\n return await this._delete();\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn('Failed to delete session from storage');\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n return undefined;\n }\n\n // @abstract\n _delete() {\n throw new Error('Not Implemented');\n }\n\n // @abstract\n _fetchFromCache() {\n throw new Error('Not Implemented');\n }\n\n // @abstract\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _saveToCache(data) {\n throw new Error('Not Implemented');\n }\n}\n\nfunction generateStorageKey() {\n // Creating two sessions at the same moment is not expected nor supported.\n return `${STORAGE_KEY_BASE}${Date.now()}`;\n}\n\nmodule.exports = StorageSession;\n","const MemorySession = require('./Memory');\nconst AuthKey = require('../crypto/AuthKey');\nconst BinaryReader = require('../extensions/BinaryReader');\n\nconst CURRENT_VERSION = '1';\n\n\nclass StringSession extends MemorySession {\n /**\n * This session file can be easily saved and loaded as a string. According\n * to the initial design, it contains only the data that is necessary for\n * successful connection and authentication, so takeout ID is not stored.\n\n * It is thought to be used where you don't want to create any on-disk\n * files but would still like to be able to save and load existing sessions\n * by other means.\n\n * You can use custom `encode` and `decode` functions, if present:\n\n * `encode` definition must be ``function encode(value: Buffer) -> string:``.\n * `decode` definition must be ``function decode(value: string) -> Buffer:``.\n * @param session {string|null}\n */\n constructor(session = undefined) {\n super();\n if (session) {\n if (session[0] !== CURRENT_VERSION) {\n throw new Error('Not a valid string');\n }\n session = session.slice(1);\n const r = StringSession.decode(session);\n const reader = new BinaryReader(r);\n this._dcId = reader.read(1)\n .readUInt8(0);\n const serverAddressLen = reader.read(2)\n .readInt16BE(0);\n this._serverAddress = String(reader.read(serverAddressLen));\n this._port = reader.read(2)\n .readInt16BE(0);\n this._key = reader.read(-1);\n }\n }\n\n /**\n * @param x {Buffer}\n * @returns {string}\n */\n static encode(x) {\n return x.toString('base64');\n }\n\n /**\n * @param x {string}\n * @returns {Buffer}\n */\n static decode(x) {\n return Buffer.from(x, 'base64');\n }\n\n async load() {\n if (this._key) {\n this._authKey = new AuthKey();\n await this._authKey.setKey(this._key);\n }\n }\n\n save() {\n if (!this.authKey) {\n return '';\n }\n const dcBuffer = Buffer.from([this.dcId]);\n const addressBuffer = Buffer.from(this.serverAddress);\n const addressLengthBuffer = Buffer.alloc(2);\n addressLengthBuffer.writeInt16BE(addressBuffer.length, 0);\n const portBuffer = Buffer.alloc(2);\n portBuffer.writeInt16BE(this.port, 0);\n\n return CURRENT_VERSION + StringSession.encode(Buffer.concat([\n dcBuffer,\n addressLengthBuffer,\n addressBuffer,\n portBuffer,\n this.authKey.getKey(),\n ]));\n }\n\n getAuthKey(dcId) {\n if (dcId && dcId !== this.dcId) {\n // Not supported.\n return undefined;\n }\n\n return this.authKey;\n }\n\n setAuthKey(authKey, dcId) {\n if (dcId && dcId !== this.dcId) {\n // Not supported.\n return;\n }\n\n this.authKey = authKey;\n }\n}\n\nmodule.exports = StringSession;\n","const Memory = require('./Memory');\nconst StringSession = require('./StringSession');\nconst CacheApiSession = require('./CacheApiSession');\nconst LocalStorageSession = require('./LocalStorageSession');\nconst IdbSession = require('./IdbSession');\nconst CallbackSession = require('./CallbackSession');\n\nmodule.exports = {\n Memory,\n StringSession,\n CacheApiSession,\n LocalStorageSession,\n IdbSession,\n CallbackSession,\n};\n","const api = require('./api');\n\nconst LAYER = 133;\nconst tlobjects = {};\n\nfor (const tl of Object.values(api)) {\n if (tl.CONSTRUCTOR_ID) {\n tlobjects[tl.CONSTRUCTOR_ID] = tl;\n } else {\n for (const sub of Object.values(tl)) {\n tlobjects[sub.CONSTRUCTOR_ID] = sub;\n }\n }\n}\n\nmodule.exports = {\n LAYER,\n tlobjects,\n};\n","const {\n parseTl,\n serializeBytes,\n serializeDate,\n} = require('./generationHelpers');\nconst {\n toSignedLittleBuffer,\n} = require('../Helpers');\n\nconst tlContent = require('./apiTl.js');\nconst schemeContent = require('./schemaTl.js');\n\n/* CONTEST\nconst NAMED_AUTO_CASTS = new Set([\n 'chatId,int'\n])\nconst NAMED_BLACKLIST = new Set([\n 'discardEncryption'\n])\nconst AUTO_CASTS = new Set([\n 'InputPeer',\n 'InputChannel',\n 'InputUser',\n 'InputDialogPeer',\n 'InputNotifyPeer',\n 'InputMedia',\n 'InputPhoto',\n 'InputMessage',\n 'InputDocument',\n 'InputChatPhoto'\n])\n\n */\n// eslint-disable-next-line no-restricted-globals\nconst CACHING_SUPPORTED = typeof self !== 'undefined' && self.localStorage !== undefined;\n\nconst CACHE_KEY = 'GramJs:apiCache';\n\nfunction buildApiFromTlSchema() {\n let definitions;\n const fromCache = CACHING_SUPPORTED && loadFromCache();\n\n if (fromCache) {\n definitions = fromCache;\n } else {\n definitions = loadFromTlSchemas();\n\n if (CACHING_SUPPORTED) {\n localStorage.setItem(CACHE_KEY, JSON.stringify(definitions));\n }\n }\n\n return mergeWithNamespaces(\n createClasses('constructor', definitions.constructors),\n createClasses('request', definitions.requests),\n );\n}\n\nfunction loadFromCache() {\n const jsonCache = localStorage.getItem(CACHE_KEY);\n return jsonCache && JSON.parse(jsonCache);\n}\n\nfunction loadFromTlSchemas() {\n const [constructorParamsApi, functionParamsApi] = extractParams(tlContent);\n const [constructorParamsSchema, functionParamsSchema] = extractParams(schemeContent);\n const constructors = [].concat(constructorParamsApi, constructorParamsSchema);\n const requests = [].concat(functionParamsApi, functionParamsSchema);\n\n return {\n constructors,\n requests,\n };\n}\n\nfunction mergeWithNamespaces(obj1, obj2) {\n const result = { ...obj1 };\n\n Object.keys(obj2)\n .forEach((key) => {\n if (typeof obj2[key] === 'function' || !result[key]) {\n result[key] = obj2[key];\n } else {\n Object.assign(result[key], obj2[key]);\n }\n });\n\n return result;\n}\n\nfunction extractParams(fileContent) {\n const f = parseTl(fileContent, 109);\n const constructors = [];\n const functions = [];\n for (const d of f) {\n if (d.isFunction) {\n functions.push(d);\n } else {\n constructors.push(d);\n }\n }\n return [constructors, functions];\n}\n\nfunction argToBytes(x, type) {\n switch (type) {\n case 'int': {\n const i = Buffer.alloc(4);\n i.writeInt32LE(x, 0);\n return i;\n }\n case 'long':\n return toSignedLittleBuffer(x, 8);\n case 'int128':\n return toSignedLittleBuffer(x, 16);\n case 'int256':\n return toSignedLittleBuffer(x, 32);\n case 'double': {\n const d = Buffer.alloc(8);\n d.writeDoubleLE(x, 0);\n return d;\n }\n case 'string':\n return serializeBytes(x);\n case 'Bool':\n return x ? Buffer.from('b5757299', 'hex') : Buffer.from('379779bc', 'hex');\n case 'true':\n return Buffer.alloc(0);\n case 'bytes':\n return serializeBytes(x);\n case 'date':\n return serializeDate(x);\n default:\n return x.getBytes();\n }\n}\n\n/*\nCONTEST\nasync function getInputFromResolve(utils, client, peer, peerType) {\n switch (peerType) {\n case 'InputPeer':\n return utils.getInputPeer(await client.getInputEntity(peer))\n case 'InputChannel':\n return utils.getInputChannel(await client.getInputEntity(peer))\n case 'InputUser':\n return utils.getInputUser(await client.getInputEntity(peer))\n case 'InputDialogPeer':\n return await client._getInputDialog(peer)\n case 'InputNotifyPeer':\n return await client._getInputNotify(peer)\n case 'InputMedia':\n return utils.getInputMedia(peer)\n case 'InputPhoto':\n return utils.getInputPhoto(peer)\n case 'InputMessage':\n return utils.getInputMessage(peer)\n case 'InputDocument':\n return utils.getInputDocument(peer)\n case 'InputChatPhoto':\n return utils.getInputChatPhoto(peer)\n case 'chatId,int' :\n return await client.getPeerId(peer, false)\n default:\n throw new Error('unsupported peer type : ' + peerType)\n }\n}\n*/\nfunction getArgFromReader(reader, arg) {\n if (arg.isVector) {\n if (arg.useVectorId) {\n reader.readInt();\n }\n const temp = [];\n const len = reader.readInt();\n arg.isVector = false;\n for (let i = 0; i < len; i++) {\n temp.push(getArgFromReader(reader, arg));\n }\n arg.isVector = true;\n return temp;\n } else if (arg.flagIndicator) {\n return reader.readInt();\n } else {\n switch (arg.type) {\n case 'int':\n return reader.readInt();\n case 'long':\n return reader.readLong();\n case 'int128':\n return reader.readLargeInt(128);\n case 'int256':\n return reader.readLargeInt(256);\n case 'double':\n return reader.readDouble();\n case 'string':\n return reader.tgReadString();\n case 'Bool':\n return reader.tgReadBool();\n case 'true':\n return true;\n case 'bytes':\n return reader.tgReadBytes();\n case 'date':\n return reader.tgReadDate();\n default:\n if (!arg.skipConstructorId) {\n return reader.tgReadObject();\n } else {\n throw new Error(`Unknown type ${arg}`);\n }\n }\n }\n}\n\nfunction createClasses(classesType, params) {\n const classes = {};\n for (const classParams of params) {\n const {\n name,\n constructorId,\n subclassOfId,\n argsConfig,\n namespace,\n result,\n } = classParams;\n const fullName = [namespace, name].join('.')\n .replace(/^\\./, '');\n\n class VirtualClass {\n static CONSTRUCTOR_ID = constructorId;\n\n static SUBCLASS_OF_ID = subclassOfId;\n\n static className = fullName;\n\n static classType = classesType;\n\n CONSTRUCTOR_ID = constructorId;\n\n SUBCLASS_OF_ID = subclassOfId;\n\n className = fullName;\n\n classType = classesType;\n\n constructor(args) {\n args = args || {};\n Object.keys(args)\n .forEach((argName) => {\n this[argName] = args[argName];\n });\n }\n\n static fromReader(reader) {\n const args = {};\n\n for (const argName in argsConfig) {\n if (argsConfig.hasOwnProperty(argName)) {\n const arg = argsConfig[argName];\n if (arg.isFlag) {\n if (arg.type === 'true') {\n args[argName] = Boolean(args.flags & (1 << arg.flagIndex));\n continue;\n }\n if (args.flags & (1 << arg.flagIndex)) {\n args[argName] = getArgFromReader(reader, arg);\n } else {\n args[argName] = undefined;\n }\n } else {\n if (arg.flagIndicator) {\n arg.name = 'flags';\n }\n args[argName] = getArgFromReader(reader, arg);\n }\n }\n }\n return new VirtualClass(args);\n }\n\n getBytes() {\n // The next is pseudo-code:\n const idForBytes = this.CONSTRUCTOR_ID;\n const c = Buffer.alloc(4);\n c.writeUInt32LE(idForBytes, 0);\n const buffers = [c];\n for (const arg in argsConfig) {\n if (argsConfig.hasOwnProperty(arg)) {\n if (argsConfig[arg].isFlag) {\n if ((this[arg] === false && argsConfig[arg].type === 'true')\n || this[arg] === undefined) {\n continue;\n }\n }\n if (argsConfig[arg].isVector) {\n if (argsConfig[arg].useVectorId) {\n buffers.push(Buffer.from('15c4b51c', 'hex'));\n }\n const l = Buffer.alloc(4);\n l.writeInt32LE(this[arg].length, 0);\n buffers.push(l, Buffer.concat(this[arg].map((x) => argToBytes(x, argsConfig[arg].type))));\n } else if (argsConfig[arg].flagIndicator) {\n if (!Object.values(argsConfig)\n .some((f) => f.isFlag)) {\n buffers.push(Buffer.alloc(4));\n } else {\n let flagCalculate = 0;\n for (const f in argsConfig) {\n if (argsConfig[f].isFlag) {\n if ((this[f] === false && argsConfig[f].type === 'true')\n || this[f] === undefined) {\n flagCalculate |= 0;\n } else {\n flagCalculate |= 1 << argsConfig[f].flagIndex;\n }\n }\n }\n const f = Buffer.alloc(4);\n f.writeUInt32LE(flagCalculate, 0);\n buffers.push(f);\n }\n } else {\n buffers.push(argToBytes(this[arg], argsConfig[arg].type));\n\n if (this[arg] && typeof this[arg].getBytes === 'function') {\n let boxed = (argsConfig[arg].type.charAt(argsConfig[arg].type.indexOf('.') + 1));\n boxed = boxed === boxed.toUpperCase();\n if (!boxed) {\n buffers.shift();\n }\n }\n }\n }\n }\n return Buffer.concat(buffers);\n }\n\n readResult(reader) {\n if (classesType !== 'request') {\n throw new Error('`readResult()` called for non-request instance');\n }\n\n const m = result.match(/Vector<(int|long)>/);\n if (m) {\n reader.readInt();\n const temp = [];\n const len = reader.readInt();\n if (m[1] === 'int') {\n for (let i = 0; i < len; i++) {\n temp.push(reader.readInt());\n }\n } else {\n for (let i = 0; i < len; i++) {\n temp.push(reader.readLong());\n }\n }\n return temp;\n } else {\n return reader.tgReadObject();\n }\n }\n\n /* CONTEST\n async resolve(client, utils) {\n\n if (classesType !== 'request') {\n throw new Error('`resolve()` called for non-request instance')\n }\n\n for (const arg in argsConfig) {\n if (argsConfig.hasOwnProperty(arg)) {\n if (!AUTO_CASTS.has(argsConfig[arg].type)) {\n if (!NAMED_AUTO_CASTS.has(`${argsConfig[arg].name},${argsConfig[arg].type}`)) {\n continue\n }\n }\n if (argsConfig[arg].isFlag) {\n if (!this[arg]) {\n continue\n }\n }\n if (argsConfig[arg].isVector) {\n const temp = []\n for (const x of this[arg]) {\n temp.push(await getInputFromResolve(utils, client, x, argsConfig[arg].type))\n }\n this[arg] = temp\n } else {\n this[arg] = await getInputFromResolve(utils, client, this[arg], argsConfig[arg].type)\n }\n }\n }\n } */\n }\n\n if (namespace) {\n if (!classes[namespace]) {\n classes[namespace] = {};\n }\n classes[namespace][name] = VirtualClass;\n } else {\n classes[name] = VirtualClass;\n }\n }\n\n return classes;\n}\n\nmodule.exports = buildApiFromTlSchema();\n","module.exports = `boolFalse#bc799737 = Bool;\nboolTrue#997275b5 = Bool;\ntrue#3fedd339 = True;\nvector#1cb5c415 {t:Type} # [ t ] = Vector t;\nerror#c4b9f9bb code:int text:string = Error;\nnull#56730bcc = Null;\ninputPeerEmpty#7f3b18ea = InputPeer;\ninputPeerSelf#7da07ec9 = InputPeer;\ninputPeerChat#35a95cb9 chat_id:long = InputPeer;\ninputPeerUser#dde8a54c user_id:long access_hash:long = InputPeer;\ninputPeerChannel#27bcbbfc channel_id:long access_hash:long = InputPeer;\ninputPeerUserFromMessage#a87b0a1c peer:InputPeer msg_id:int user_id:long = InputPeer;\ninputPeerChannelFromMessage#bd2a0840 peer:InputPeer msg_id:int channel_id:long = InputPeer;\ninputUserEmpty#b98886cf = InputUser;\ninputUserSelf#f7c1b13f = InputUser;\ninputUser#f21158c6 user_id:long access_hash:long = InputUser;\ninputUserFromMessage#1da448e2 peer:InputPeer msg_id:int user_id:long = InputUser;\ninputPhoneContact#f392b7f4 client_id:long phone:string first_name:string last_name:string = InputContact;\ninputFile#f52ff27f id:long parts:int name:string md5_checksum:string = InputFile;\ninputFileBig#fa4f0bb5 id:long parts:int name:string = InputFile;\ninputMediaEmpty#9664f57f = InputMedia;\ninputMediaUploadedPhoto#1e287d04 flags:# file:InputFile stickers:flags.0?Vector ttl_seconds:flags.1?int = InputMedia;\ninputMediaPhoto#b3ba0635 flags:# id:InputPhoto ttl_seconds:flags.0?int = InputMedia;\ninputMediaGeoPoint#f9c44144 geo_point:InputGeoPoint = InputMedia;\ninputMediaContact#f8ab7dfb phone_number:string first_name:string last_name:string vcard:string = InputMedia;\ninputMediaUploadedDocument#5b38c6c1 flags:# nosound_video:flags.3?true force_file:flags.4?true file:InputFile thumb:flags.2?InputFile mime_type:string attributes:Vector stickers:flags.0?Vector ttl_seconds:flags.1?int = InputMedia;\ninputMediaDocument#33473058 flags:# id:InputDocument ttl_seconds:flags.0?int query:flags.1?string = InputMedia;\ninputMediaVenue#c13d1c11 geo_point:InputGeoPoint title:string address:string provider:string venue_id:string venue_type:string = InputMedia;\ninputMediaPhotoExternal#e5bbfe1a flags:# url:string ttl_seconds:flags.0?int = InputMedia;\ninputMediaDocumentExternal#fb52dc99 flags:# url:string ttl_seconds:flags.0?int = InputMedia;\ninputMediaGame#d33f43f3 id:InputGame = InputMedia;\ninputMediaInvoice#d9799874 flags:# title:string description:string photo:flags.0?InputWebDocument invoice:Invoice payload:bytes provider:string provider_data:DataJSON start_param:flags.1?string = InputMedia;\ninputMediaGeoLive#971fa843 flags:# stopped:flags.0?true geo_point:InputGeoPoint heading:flags.2?int period:flags.1?int proximity_notification_radius:flags.3?int = InputMedia;\ninputMediaPoll#f94e5f1 flags:# poll:Poll correct_answers:flags.0?Vector solution:flags.1?string solution_entities:flags.1?Vector = InputMedia;\ninputMediaDice#e66fbf7b emoticon:string = InputMedia;\ninputChatPhotoEmpty#1ca48f57 = InputChatPhoto;\ninputChatUploadedPhoto#c642724e flags:# file:flags.0?InputFile video:flags.1?InputFile video_start_ts:flags.2?double = InputChatPhoto;\ninputChatPhoto#8953ad37 id:InputPhoto = InputChatPhoto;\ninputGeoPointEmpty#e4c123d6 = InputGeoPoint;\ninputGeoPoint#48222faf flags:# lat:double long:double accuracy_radius:flags.0?int = InputGeoPoint;\ninputPhotoEmpty#1cd7bf0d = InputPhoto;\ninputPhoto#3bb3b94a id:long access_hash:long file_reference:bytes = InputPhoto;\ninputFileLocation#dfdaabe1 volume_id:long local_id:int secret:long file_reference:bytes = InputFileLocation;\ninputEncryptedFileLocation#f5235d55 id:long access_hash:long = InputFileLocation;\ninputDocumentFileLocation#bad07584 id:long access_hash:long file_reference:bytes thumb_size:string = InputFileLocation;\ninputSecureFileLocation#cbc7ee28 id:long access_hash:long = InputFileLocation;\ninputTakeoutFileLocation#29be5899 = InputFileLocation;\ninputPhotoFileLocation#40181ffe id:long access_hash:long file_reference:bytes thumb_size:string = InputFileLocation;\ninputPhotoLegacyFileLocation#d83466f3 id:long access_hash:long file_reference:bytes volume_id:long local_id:int secret:long = InputFileLocation;\ninputPeerPhotoFileLocation#37257e99 flags:# big:flags.0?true peer:InputPeer photo_id:long = InputFileLocation;\ninputStickerSetThumb#9d84f3db stickerset:InputStickerSet thumb_version:int = InputFileLocation;\ninputGroupCallStream#598a92a flags:# call:InputGroupCall time_ms:long scale:int video_channel:flags.0?int video_quality:flags.0?int = InputFileLocation;\npeerUser#59511722 user_id:long = Peer;\npeerChat#36c6019a chat_id:long = Peer;\npeerChannel#a2a5371e channel_id:long = Peer;\nstorage.fileUnknown#aa963b05 = storage.FileType;\nstorage.filePartial#40bc6f52 = storage.FileType;\nstorage.fileJpeg#7efe0e = storage.FileType;\nstorage.fileGif#cae1aadf = storage.FileType;\nstorage.filePng#a4f63c0 = storage.FileType;\nstorage.filePdf#ae1e508d = storage.FileType;\nstorage.fileMp3#528a0677 = storage.FileType;\nstorage.fileMov#4b09ebbc = storage.FileType;\nstorage.fileMp4#b3cea0e4 = storage.FileType;\nstorage.fileWebp#1081464c = storage.FileType;\nuserEmpty#d3bc4b7a id:long = User;\nuser#3ff6ecb0 flags:# self:flags.10?true contact:flags.11?true mutual_contact:flags.12?true deleted:flags.13?true bot:flags.14?true bot_chat_history:flags.15?true bot_nochats:flags.16?true verified:flags.17?true restricted:flags.18?true min:flags.20?true bot_inline_geo:flags.21?true support:flags.23?true scam:flags.24?true apply_min_photo:flags.25?true fake:flags.26?true id:long access_hash:flags.0?long first_name:flags.1?string last_name:flags.2?string username:flags.3?string phone:flags.4?string photo:flags.5?UserProfilePhoto status:flags.6?UserStatus bot_info_version:flags.14?int restriction_reason:flags.18?Vector bot_inline_placeholder:flags.19?string lang_code:flags.22?string = User;\nuserProfilePhotoEmpty#4f11bae1 = UserProfilePhoto;\nuserProfilePhoto#82d1f706 flags:# has_video:flags.0?true photo_id:long stripped_thumb:flags.1?bytes dc_id:int = UserProfilePhoto;\nuserStatusEmpty#9d05049 = UserStatus;\nuserStatusOnline#edb93949 expires:int = UserStatus;\nuserStatusOffline#8c703f was_online:int = UserStatus;\nuserStatusRecently#e26f42f1 = UserStatus;\nuserStatusLastWeek#7bf09fc = UserStatus;\nuserStatusLastMonth#77ebc742 = UserStatus;\nchatEmpty#29562865 id:long = Chat;\nchat#41cbf256 flags:# creator:flags.0?true kicked:flags.1?true left:flags.2?true deactivated:flags.5?true call_active:flags.23?true call_not_empty:flags.24?true 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 id:long access_hash:flags.13?long title:string username:flags.6?string photo:ChatPhoto date:int restriction_reason:flags.9?Vector admin_rights:flags.14?ChatAdminRights banned_rights:flags.15?ChatBannedRights default_banned_rights:flags.18?ChatBannedRights participants_count:flags.17?int = Chat;\nchannelForbidden#17d493d5 flags:# broadcast:flags.5?true megagroup:flags.8?true id:long access_hash:long title:string until_date:flags.16?int = Chat;\nchatFull#4dbdc099 flags:# can_set_username:flags.7?true has_scheduled:flags.8?true id:long about:string participants:ChatParticipants chat_photo:flags.2?Photo notify_settings:PeerNotifySettings exported_invite:flags.13?ExportedChatInvite bot_info:flags.3?Vector pinned_msg_id:flags.6?int folder_id:flags.11?int call:flags.12?InputGroupCall ttl_period:flags.14?int groupcall_default_join_as:flags.15?Peer theme_emoticon:flags.16?string = ChatFull;\nchannelFull#e9b27a17 flags:# can_view_participants:flags.3?true can_set_username:flags.6?true can_set_stickers:flags.7?true hidden_prehistory:flags.10?true can_set_location:flags.16?true has_scheduled:flags.19?true can_view_stats:flags.20?true blocked:flags.22?true id:long about:string participants_count:flags.0?int admins_count:flags.1?int kicked_count:flags.2?int banned_count:flags.2?int online_count:flags.13?int read_inbox_max_id:int read_outbox_max_id:int unread_count:int chat_photo:Photo notify_settings:PeerNotifySettings exported_invite:flags.23?ExportedChatInvite bot_info:Vector migrated_from_chat_id:flags.4?long migrated_from_max_id:flags.4?int pinned_msg_id:flags.5?int stickerset:flags.8?StickerSet available_min_id:flags.9?int folder_id:flags.11?int linked_chat_id:flags.14?long location:flags.15?ChannelLocation slowmode_seconds:flags.17?int slowmode_next_send_date:flags.18?int stats_dc:flags.12?int pts:int call:flags.21?InputGroupCall ttl_period:flags.24?int pending_suggestions:flags.25?Vector groupcall_default_join_as:flags.26?Peer theme_emoticon:flags.27?string = ChatFull;\nchatParticipant#c02d4007 user_id:long inviter_id:long date:int = ChatParticipant;\nchatParticipantCreator#e46bcee4 user_id:long = ChatParticipant;\nchatParticipantAdmin#a0933f5b user_id:long inviter_id:long date:int = ChatParticipant;\nchatParticipantsForbidden#8763d3e1 flags:# chat_id:long self_participant:flags.0?ChatParticipant = ChatParticipants;\nchatParticipants#3cbc93f8 chat_id:long participants:Vector version:int = ChatParticipants;\nchatPhotoEmpty#37c1011c = ChatPhoto;\nchatPhoto#1c6e1c11 flags:# has_video:flags.0?true photo_id:long stripped_thumb:flags.1?bytes dc_id:int = ChatPhoto;\nmessageEmpty#90a6ca84 flags:# id:int peer_id:flags.0?Peer = Message;\nmessage#85d6cbe2 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true post:flags.14?true from_scheduled:flags.18?true legacy:flags.19?true edit_hide:flags.21?true pinned:flags.24?true id:int from_id:flags.8?Peer peer_id:Peer fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?long reply_to:flags.3?MessageReplyHeader date:int message:string media:flags.9?MessageMedia reply_markup:flags.6?ReplyMarkup entities:flags.7?Vector views:flags.10?int forwards:flags.10?int replies:flags.23?MessageReplies edit_date:flags.15?int post_author:flags.16?string grouped_id:flags.17?long restriction_reason:flags.22?Vector ttl_period:flags.25?int = Message;\nmessageService#2b085862 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true post:flags.14?true legacy:flags.19?true id:int from_id:flags.8?Peer peer_id:Peer reply_to:flags.3?MessageReplyHeader date:int action:MessageAction ttl_period:flags.25?int = Message;\nmessageMediaEmpty#3ded6320 = MessageMedia;\nmessageMediaPhoto#695150d7 flags:# photo:flags.0?Photo ttl_seconds:flags.2?int = MessageMedia;\nmessageMediaGeo#56e0d474 geo:GeoPoint = MessageMedia;\nmessageMediaContact#70322949 phone_number:string first_name:string last_name:string vcard:string user_id:long = MessageMedia;\nmessageMediaUnsupported#9f84f49e = MessageMedia;\nmessageMediaDocument#9cb070d7 flags:# document:flags.0?Document ttl_seconds:flags.2?int = MessageMedia;\nmessageMediaWebPage#a32dd600 webpage:WebPage = MessageMedia;\nmessageMediaVenue#2ec0533f geo:GeoPoint title:string address:string provider:string venue_id:string venue_type:string = MessageMedia;\nmessageMediaGame#fdb19008 game:Game = MessageMedia;\nmessageMediaInvoice#84551347 flags:# shipping_address_requested:flags.1?true test:flags.3?true title:string description:string photo:flags.0?WebDocument receipt_msg_id:flags.2?int currency:string total_amount:long start_param:string = MessageMedia;\nmessageMediaGeoLive#b940c666 flags:# geo:GeoPoint heading:flags.0?int period:int proximity_notification_radius:flags.1?int = MessageMedia;\nmessageMediaPoll#4bd6e798 poll:Poll results:PollResults = MessageMedia;\nmessageMediaDice#3f7ee58b value:int emoticon:string = MessageMedia;\nmessageActionEmpty#b6aef7b0 = MessageAction;\nmessageActionChatCreate#bd47cbad title:string users:Vector = MessageAction;\nmessageActionChatEditTitle#b5a1ce5a title:string = MessageAction;\nmessageActionChatEditPhoto#7fcb13a8 photo:Photo = MessageAction;\nmessageActionChatDeletePhoto#95e3fbef = MessageAction;\nmessageActionChatAddUser#15cefd00 users:Vector = MessageAction;\nmessageActionChatDeleteUser#a43f30cc user_id:long = MessageAction;\nmessageActionChatJoinedByLink#31224c3 inviter_id:long = MessageAction;\nmessageActionChannelCreate#95d2ac92 title:string = MessageAction;\nmessageActionChatMigrateTo#e1037f92 channel_id:long = MessageAction;\nmessageActionChannelMigrateFrom#ea3948e9 title:string chat_id:long = MessageAction;\nmessageActionPinMessage#94bd38ed = MessageAction;\nmessageActionHistoryClear#9fbab604 = MessageAction;\nmessageActionGameScore#92a72876 game_id:long score:int = MessageAction;\nmessageActionPaymentSentMe#8f31b327 flags:# currency:string total_amount:long payload:bytes info:flags.0?PaymentRequestedInfo shipping_option_id:flags.1?string charge:PaymentCharge = MessageAction;\nmessageActionPaymentSent#40699cd0 currency:string total_amount:long = MessageAction;\nmessageActionPhoneCall#80e11a7f flags:# video:flags.2?true call_id:long reason:flags.0?PhoneCallDiscardReason duration:flags.1?int = MessageAction;\nmessageActionScreenshotTaken#4792929b = MessageAction;\nmessageActionCustomAction#fae69f56 message:string = MessageAction;\nmessageActionBotAllowed#abe9affe domain:string = MessageAction;\nmessageActionSecureValuesSentMe#1b287353 values:Vector credentials:SecureCredentialsEncrypted = MessageAction;\nmessageActionSecureValuesSent#d95c6154 types:Vector = MessageAction;\nmessageActionContactSignUp#f3f25f76 = MessageAction;\nmessageActionGeoProximityReached#98e0d697 from_id:Peer to_id:Peer distance:int = MessageAction;\nmessageActionGroupCall#7a0d7f42 flags:# call:InputGroupCall duration:flags.0?int = MessageAction;\nmessageActionInviteToGroupCall#502f92f7 call:InputGroupCall users:Vector = MessageAction;\nmessageActionSetMessagesTTL#aa1afbfd period:int = MessageAction;\nmessageActionGroupCallScheduled#b3a07661 call:InputGroupCall schedule_date:int = MessageAction;\nmessageActionSetChatTheme#aa786345 emoticon:string = MessageAction;\ndialog#2c171f72 flags:# pinned:flags.2?true unread_mark:flags.3?true peer:Peer top_message:int read_inbox_max_id:int read_outbox_max_id:int unread_count:int unread_mentions_count:int notify_settings:PeerNotifySettings pts:flags.0?int draft:flags.1?DraftMessage folder_id:flags.4?int = Dialog;\ndialogFolder#71bd134c flags:# pinned:flags.2?true folder:Folder peer:Peer top_message:int unread_muted_peers_count:int unread_unmuted_peers_count:int unread_muted_messages_count:int unread_unmuted_messages_count:int = Dialog;\nphotoEmpty#2331b22d id:long = Photo;\nphoto#fb197a65 flags:# has_stickers:flags.0?true id:long access_hash:long file_reference:bytes date:int sizes:Vector video_sizes:flags.1?Vector dc_id:int = Photo;\nphotoSizeEmpty#e17e23c type:string = PhotoSize;\nphotoSize#75c78e60 type:string w:int h:int size:int = PhotoSize;\nphotoCachedSize#21e1ad6 type:string w:int h:int bytes:bytes = PhotoSize;\nphotoStrippedSize#e0b0bc2e type:string bytes:bytes = PhotoSize;\nphotoSizeProgressive#fa3efb95 type:string w:int h:int sizes:Vector = PhotoSize;\nphotoPathSize#d8214d41 type:string bytes:bytes = PhotoSize;\ngeoPointEmpty#1117dd5f = GeoPoint;\ngeoPoint#b2a2f663 flags:# long:double lat:double access_hash:long accuracy_radius:flags.0?int = GeoPoint;\nauth.sentCode#5e002502 flags:# type:auth.SentCodeType phone_code_hash:string next_type:flags.1?auth.CodeType timeout:flags.2?int = auth.SentCode;\nauth.authorization#cd050916 flags:# tmp_sessions:flags.0?int user:User = auth.Authorization;\nauth.authorizationSignUpRequired#44747e9a flags:# terms_of_service:flags.0?help.TermsOfService = auth.Authorization;\nauth.exportedAuthorization#b434e2b8 id:long bytes:bytes = auth.ExportedAuthorization;\ninputNotifyPeer#b8bc5b0c peer:InputPeer = InputNotifyPeer;\ninputNotifyUsers#193b4417 = InputNotifyPeer;\ninputNotifyChats#4a95e84e = InputNotifyPeer;\ninputNotifyBroadcasts#b1db7c7e = InputNotifyPeer;\ninputPeerNotifySettings#9c3d198e flags:# show_previews:flags.0?Bool silent:flags.1?Bool mute_until:flags.2?int sound:flags.3?string = InputPeerNotifySettings;\npeerNotifySettings#af509d20 flags:# show_previews:flags.0?Bool silent:flags.1?Bool mute_until:flags.2?int sound:flags.3?string = PeerNotifySettings;\npeerSettings#733f2961 flags:# report_spam:flags.0?true add_contact:flags.1?true block_contact:flags.2?true share_contact:flags.3?true need_contacts_exception:flags.4?true report_geo:flags.5?true autoarchived:flags.7?true invite_members:flags.8?true geo_distance:flags.6?int = PeerSettings;\nwallPaper#a437c3ed id:long flags:# creator:flags.0?true default:flags.1?true pattern:flags.3?true dark:flags.4?true access_hash:long slug:string document:Document settings:flags.2?WallPaperSettings = WallPaper;\nwallPaperNoFile#e0804116 id:long flags:# default:flags.1?true dark:flags.4?true settings:flags.2?WallPaperSettings = WallPaper;\ninputReportReasonSpam#58dbcab8 = ReportReason;\ninputReportReasonViolence#1e22c78d = ReportReason;\ninputReportReasonPornography#2e59d922 = ReportReason;\ninputReportReasonChildAbuse#adf44ee3 = ReportReason;\ninputReportReasonOther#c1e4a2b1 = ReportReason;\ninputReportReasonCopyright#9b89f93a = ReportReason;\ninputReportReasonGeoIrrelevant#dbd4feed = ReportReason;\ninputReportReasonFake#f5ddd6e7 = ReportReason;\nuserFull#d697ff05 flags:# blocked:flags.0?true phone_calls_available:flags.4?true phone_calls_private:flags.5?true can_pin_message:flags.7?true has_scheduled:flags.12?true video_calls_available:flags.13?true user:User about:flags.1?string settings:PeerSettings profile_photo:flags.2?Photo notify_settings:PeerNotifySettings bot_info:flags.3?BotInfo pinned_msg_id:flags.6?int common_chats_count:int folder_id:flags.11?int ttl_period:flags.14?int theme_emoticon:flags.15?string = UserFull;\ncontact#145ade0b user_id:long mutual:Bool = Contact;\nimportedContact#c13e3c50 user_id:long client_id:long = ImportedContact;\ncontactStatus#16d9703b user_id:long status:UserStatus = ContactStatus;\ncontacts.contactsNotModified#b74ba9d2 = contacts.Contacts;\ncontacts.contacts#eae87e42 contacts:Vector saved_count:int users:Vector = contacts.Contacts;\ncontacts.importedContacts#77d01c3b imported:Vector popular_invites:Vector retry_contacts:Vector users:Vector = contacts.ImportedContacts;\ncontacts.blocked#ade1591 blocked:Vector chats:Vector users:Vector = contacts.Blocked;\ncontacts.blockedSlice#e1664194 count:int blocked:Vector chats:Vector users:Vector = contacts.Blocked;\nmessages.dialogs#15ba6c40 dialogs:Vector messages:Vector chats:Vector users:Vector = messages.Dialogs;\nmessages.dialogsSlice#71e094f3 count:int dialogs:Vector messages:Vector chats:Vector users:Vector = messages.Dialogs;\nmessages.dialogsNotModified#f0e3e596 count:int = messages.Dialogs;\nmessages.messages#8c718e87 messages:Vector chats:Vector users:Vector = messages.Messages;\nmessages.messagesSlice#3a54685e flags:# inexact:flags.1?true count:int next_rate:flags.0?int offset_id_offset:flags.2?int messages:Vector chats:Vector users:Vector = messages.Messages;\nmessages.channelMessages#64479808 flags:# inexact:flags.1?true pts:int count:int offset_id_offset:flags.2?int messages:Vector chats:Vector users:Vector = messages.Messages;\nmessages.messagesNotModified#74535f21 count:int = messages.Messages;\nmessages.chats#64ff9fd5 chats:Vector = messages.Chats;\nmessages.chatsSlice#9cd81144 count:int chats:Vector = messages.Chats;\nmessages.chatFull#e5d7d19c full_chat:ChatFull chats:Vector users:Vector = messages.ChatFull;\nmessages.affectedHistory#b45c69d1 pts:int pts_count:int offset:int = messages.AffectedHistory;\ninputMessagesFilterEmpty#57e2f66c = MessagesFilter;\ninputMessagesFilterPhotos#9609a51c = MessagesFilter;\ninputMessagesFilterVideo#9fc00e65 = MessagesFilter;\ninputMessagesFilterPhotoVideo#56e9f0e4 = MessagesFilter;\ninputMessagesFilterDocument#9eddf188 = MessagesFilter;\ninputMessagesFilterUrl#7ef0dd87 = MessagesFilter;\ninputMessagesFilterGif#ffc86587 = MessagesFilter;\ninputMessagesFilterVoice#50f5c392 = MessagesFilter;\ninputMessagesFilterMusic#3751b49e = MessagesFilter;\ninputMessagesFilterChatPhotos#3a20ecb8 = MessagesFilter;\ninputMessagesFilterPhoneCalls#80c99768 flags:# missed:flags.0?true = MessagesFilter;\ninputMessagesFilterRoundVoice#7a7c17a4 = MessagesFilter;\ninputMessagesFilterRoundVideo#b549da53 = MessagesFilter;\ninputMessagesFilterMyMentions#c1f8e69a = MessagesFilter;\ninputMessagesFilterGeo#e7026d0d = MessagesFilter;\ninputMessagesFilterContacts#e062db83 = MessagesFilter;\ninputMessagesFilterPinned#1bb00451 = MessagesFilter;\nupdateNewMessage#1f2b0afd message:Message pts:int pts_count:int = Update;\nupdateMessageID#4e90bfd6 id:int random_id:long = Update;\nupdateDeleteMessages#a20db0e5 messages:Vector pts:int pts_count:int = Update;\nupdateUserTyping#c01e857f user_id:long action:SendMessageAction = Update;\nupdateChatUserTyping#83487af0 chat_id:long from_id:Peer action:SendMessageAction = Update;\nupdateChatParticipants#7761198 participants:ChatParticipants = Update;\nupdateUserStatus#e5bdf8de user_id:long status:UserStatus = Update;\nupdateUserName#c3f202e0 user_id:long first_name:string last_name:string username:string = Update;\nupdateUserPhoto#f227868c user_id:long date:int photo:UserProfilePhoto previous:Bool = Update;\nupdateNewEncryptedMessage#12bcbd9a message:EncryptedMessage qts:int = Update;\nupdateEncryptedChatTyping#1710f156 chat_id:int = Update;\nupdateEncryption#b4a2e88d chat:EncryptedChat date:int = Update;\nupdateEncryptedMessagesRead#38fe25b7 chat_id:int max_date:int date:int = Update;\nupdateChatParticipantAdd#3dda5451 chat_id:long user_id:long inviter_id:long date:int version:int = Update;\nupdateChatParticipantDelete#e32f3d77 chat_id:long user_id:long version:int = Update;\nupdateDcOptions#8e5e9873 dc_options:Vector = Update;\nupdateNotifySettings#bec268ef peer:NotifyPeer notify_settings:PeerNotifySettings = Update;\nupdateServiceNotification#ebe46819 flags:# popup:flags.0?true inbox_date:flags.1?int type:string message:string media:MessageMedia entities:Vector = Update;\nupdatePrivacy#ee3b272a key:PrivacyKey rules:Vector = Update;\nupdateUserPhone#5492a13 user_id:long phone:string = Update;\nupdateReadHistoryInbox#9c974fdf flags:# folder_id:flags.0?int peer:Peer max_id:int still_unread_count:int pts:int pts_count:int = Update;\nupdateReadHistoryOutbox#2f2f21bf peer:Peer max_id:int pts:int pts_count:int = Update;\nupdateWebPage#7f891213 webpage:WebPage pts:int pts_count:int = Update;\nupdateReadMessagesContents#68c13933 messages:Vector pts:int pts_count:int = Update;\nupdateChannelTooLong#108d941f flags:# channel_id:long pts:flags.0?int = Update;\nupdateChannel#635b4c09 channel_id:long = Update;\nupdateNewChannelMessage#62ba04d9 message:Message pts:int pts_count:int = Update;\nupdateReadChannelInbox#922e6e10 flags:# folder_id:flags.0?int channel_id:long max_id:int still_unread_count:int pts:int = Update;\nupdateDeleteChannelMessages#c32d5b12 channel_id:long messages:Vector pts:int pts_count:int = Update;\nupdateChannelMessageViews#f226ac08 channel_id:long id:int views:int = Update;\nupdateChatParticipantAdmin#d7ca61a2 chat_id:long user_id:long is_admin:Bool version:int = Update;\nupdateNewStickerSet#688a30aa stickerset:messages.StickerSet = Update;\nupdateStickerSetsOrder#bb2d201 flags:# masks:flags.0?true order:Vector = Update;\nupdateStickerSets#43ae3dec = Update;\nupdateSavedGifs#9375341e = Update;\nupdateBotInlineQuery#496f379c flags:# query_id:long user_id:long query:string geo:flags.0?GeoPoint peer_type:flags.1?InlineQueryPeerType offset:string = Update;\nupdateBotInlineSend#12f12a07 flags:# user_id:long query:string geo:flags.0?GeoPoint id:string msg_id:flags.1?InputBotInlineMessageID = Update;\nupdateEditChannelMessage#1b3f4df7 message:Message pts:int pts_count:int = Update;\nupdateBotCallbackQuery#b9cfc48d flags:# query_id:long user_id:long peer:Peer msg_id:int chat_instance:long data:flags.0?bytes game_short_name:flags.1?string = Update;\nupdateEditMessage#e40370a3 message:Message pts:int pts_count:int = Update;\nupdateInlineBotCallbackQuery#691e9052 flags:# query_id:long user_id:long msg_id:InputBotInlineMessageID chat_instance:long data:flags.0?bytes game_short_name:flags.1?string = Update;\nupdateReadChannelOutbox#b75f99a9 channel_id:long max_id:int = Update;\nupdateDraftMessage#ee2bb969 peer:Peer draft:DraftMessage = Update;\nupdateReadFeaturedStickers#571d2742 = Update;\nupdateRecentStickers#9a422c20 = Update;\nupdateConfig#a229dd06 = Update;\nupdatePtsChanged#3354678f = Update;\nupdateChannelWebPage#2f2ba99f channel_id:long webpage:WebPage pts:int pts_count:int = Update;\nupdateDialogPinned#6e6fe51c flags:# pinned:flags.0?true folder_id:flags.1?int peer:DialogPeer = Update;\nupdatePinnedDialogs#fa0f3ca2 flags:# folder_id:flags.1?int order:flags.0?Vector = Update;\nupdateBotWebhookJSON#8317c0c3 data:DataJSON = Update;\nupdateBotWebhookJSONQuery#9b9240a6 query_id:long data:DataJSON timeout:int = Update;\nupdateBotShippingQuery#b5aefd7d query_id:long user_id:long payload:bytes shipping_address:PostAddress = Update;\nupdateBotPrecheckoutQuery#8caa9a96 flags:# query_id:long user_id:long payload:bytes info:flags.0?PaymentRequestedInfo shipping_option_id:flags.1?string currency:string total_amount:long = Update;\nupdatePhoneCall#ab0f6b1e phone_call:PhoneCall = Update;\nupdateLangPackTooLong#46560264 lang_code:string = Update;\nupdateLangPack#56022f4d difference:LangPackDifference = Update;\nupdateFavedStickers#e511996d = Update;\nupdateChannelReadMessagesContents#44bdd535 channel_id:long messages:Vector = Update;\nupdateContactsReset#7084a7be = Update;\nupdateChannelAvailableMessages#b23fc698 channel_id:long available_min_id:int = Update;\nupdateDialogUnreadMark#e16459c3 flags:# unread:flags.0?true peer:DialogPeer = Update;\nupdateMessagePoll#aca1657b flags:# poll_id:long poll:flags.0?Poll results:PollResults = Update;\nupdateChatDefaultBannedRights#54c01850 peer:Peer default_banned_rights:ChatBannedRights version:int = Update;\nupdateFolderPeers#19360dc0 folder_peers:Vector pts:int pts_count:int = Update;\nupdatePeerSettings#6a7e7366 peer:Peer settings:PeerSettings = Update;\nupdatePeerLocated#b4afcfb0 peers:Vector = Update;\nupdateNewScheduledMessage#39a51dfb message:Message = Update;\nupdateDeleteScheduledMessages#90866cee peer:Peer messages:Vector = Update;\nupdateTheme#8216fba3 theme:Theme = Update;\nupdateGeoLiveViewed#871fb939 peer:Peer msg_id:int = Update;\nupdateLoginToken#564fe691 = Update;\nupdateMessagePollVote#106395c9 poll_id:long user_id:long options:Vector qts:int = Update;\nupdateDialogFilter#26ffde7d flags:# id:int filter:flags.0?DialogFilter = Update;\nupdateDialogFilterOrder#a5d72105 order:Vector = Update;\nupdateDialogFilters#3504914f = Update;\nupdatePhoneCallSignalingData#2661bf09 phone_call_id:long data:bytes = Update;\nupdateChannelMessageForwards#d29a27f4 channel_id:long id:int forwards:int = Update;\nupdateReadChannelDiscussionInbox#d6b19546 flags:# channel_id:long top_msg_id:int read_max_id:int broadcast_id:flags.0?long broadcast_post:flags.0?int = Update;\nupdateReadChannelDiscussionOutbox#695c9e7c channel_id:long top_msg_id:int read_max_id:int = Update;\nupdatePeerBlocked#246a4b22 peer_id:Peer blocked:Bool = Update;\nupdateChannelUserTyping#8c88c923 flags:# channel_id:long top_msg_id:flags.0?int from_id:Peer action:SendMessageAction = Update;\nupdatePinnedMessages#ed85eab5 flags:# pinned:flags.0?true peer:Peer messages:Vector pts:int pts_count:int = Update;\nupdatePinnedChannelMessages#5bb98608 flags:# pinned:flags.0?true channel_id:long messages:Vector pts:int pts_count:int = Update;\nupdateChat#f89a6a4e chat_id:long = Update;\nupdateGroupCallParticipants#f2ebdb4e call:InputGroupCall participants:Vector version:int = Update;\nupdateGroupCall#14b24500 chat_id:long call:GroupCall = Update;\nupdatePeerHistoryTTL#bb9bb9a5 flags:# peer:Peer ttl_period:flags.0?int = Update;\nupdateChatParticipant#d087663a flags:# chat_id:long date:int actor_id:long user_id:long prev_participant:flags.0?ChatParticipant new_participant:flags.1?ChatParticipant invite:flags.2?ExportedChatInvite qts:int = Update;\nupdateChannelParticipant#985d3abb flags:# channel_id:long date:int actor_id:long user_id:long prev_participant:flags.0?ChannelParticipant new_participant:flags.1?ChannelParticipant invite:flags.2?ExportedChatInvite qts:int = Update;\nupdateBotStopped#c4870a49 user_id:long date:int stopped:Bool qts:int = Update;\nupdateGroupCallConnection#b783982 flags:# presentation:flags.0?true params:DataJSON = Update;\nupdateBotCommands#4d712f2e peer:Peer bot_id:long commands:Vector = Update;\nupdates.state#a56c2a3e pts:int qts:int date:int seq:int unread_count:int = updates.State;\nupdates.differenceEmpty#5d75a138 date:int seq:int = updates.Difference;\nupdates.difference#f49ca0 new_messages:Vector new_encrypted_messages:Vector other_updates:Vector chats:Vector users:Vector state:updates.State = updates.Difference;\nupdates.differenceSlice#a8fb1981 new_messages:Vector new_encrypted_messages:Vector other_updates:Vector chats:Vector users:Vector intermediate_state:updates.State = updates.Difference;\nupdates.differenceTooLong#4afe8f6d pts:int = updates.Difference;\nupdatesTooLong#e317af7e = Updates;\nupdateShortMessage#313bc7f8 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true id:int user_id:long message:string pts:int pts_count:int date:int fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?long reply_to:flags.3?MessageReplyHeader entities:flags.7?Vector ttl_period:flags.25?int = Updates;\nupdateShortChatMessage#4d6deea5 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true id:int from_id:long chat_id:long message:string pts:int pts_count:int date:int fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?long reply_to:flags.3?MessageReplyHeader entities:flags.7?Vector ttl_period:flags.25?int = Updates;\nupdateShort#78d4dec1 update:Update date:int = Updates;\nupdatesCombined#725b04c3 updates:Vector users:Vector chats:Vector date:int seq_start:int seq:int = Updates;\nupdates#74ae4240 updates:Vector users:Vector chats:Vector date:int seq:int = Updates;\nupdateShortSentMessage#9015e101 flags:# out:flags.1?true id:int pts:int pts_count:int date:int media:flags.9?MessageMedia entities:flags.7?Vector ttl_period:flags.25?int = Updates;\nphotos.photos#8dca6aa5 photos:Vector users:Vector = photos.Photos;\nphotos.photosSlice#15051f54 count:int photos:Vector users:Vector = photos.Photos;\nphotos.photo#20212ca8 photo:Photo users:Vector = photos.Photo;\nupload.file#96a18d5 type:storage.FileType mtime:int bytes:bytes = upload.File;\nupload.fileCdnRedirect#f18cda44 dc_id:int file_token:bytes encryption_key:bytes encryption_iv:bytes file_hashes:Vector = upload.File;\ndcOption#18b7a10d flags:# ipv6:flags.0?true media_only:flags.1?true tcpo_only:flags.2?true cdn:flags.3?true static:flags.4?true id:int ip_address:string port:int secret:flags.10?bytes = DcOption;\nconfig#330b4067 flags:# phonecalls_enabled:flags.1?true default_p2p_contacts:flags.3?true preload_featured_stickers:flags.4?true ignore_phone_entities:flags.5?true revoke_pm_inbox:flags.6?true blocked_mode:flags.8?true pfs_enabled:flags.13?true date:int expires:int test_mode:Bool this_dc:int dc_options:Vector dc_txt_domain_name:string chat_size_max:int megagroup_size_max:int forwarded_count_max:int online_update_period_ms:int offline_blur_timeout_ms:int offline_idle_timeout_ms:int online_cloud_timeout_ms:int notify_cloud_delay_ms:int notify_default_delay_ms:int push_chat_period_ms:int push_chat_limit:int saved_gifs_limit:int edit_time_limit:int revoke_time_limit:int revoke_pm_time_limit:int rating_e_decay:int stickers_recent_limit:int stickers_faved_limit:int channels_read_media_period:int tmp_sessions:flags.0?int pinned_dialogs_count_max:int pinned_infolder_count_max:int call_receive_timeout_ms:int call_ring_timeout_ms:int call_connect_timeout_ms:int call_packet_timeout_ms:int me_url_prefix:string autoupdate_url_prefix:flags.7?string gif_search_username:flags.9?string venue_search_username:flags.10?string img_search_username:flags.11?string static_maps_provider:flags.12?string caption_length_max:int message_length_max:int webfile_dc_id:int suggested_lang_code:flags.2?string lang_pack_version:flags.2?int base_lang_pack_version:flags.2?int = Config;\nnearestDc#8e1a1775 country:string this_dc:int nearest_dc:int = NearestDc;\nhelp.appUpdate#ccbbce30 flags:# can_not_skip:flags.0?true id:int version:string text:string entities:Vector document:flags.1?Document url:flags.2?string sticker:flags.3?Document = help.AppUpdate;\nhelp.noAppUpdate#c45a6536 = help.AppUpdate;\nhelp.inviteText#18cb9f78 message:string = help.InviteText;\nencryptedChatEmpty#ab7ec0a0 id:int = EncryptedChat;\nencryptedChatWaiting#66b25953 id:int access_hash:long date:int admin_id:long participant_id:long = EncryptedChat;\nencryptedChatRequested#48f1d94c flags:# folder_id:flags.0?int id:int access_hash:long date:int admin_id:long participant_id:long g_a:bytes = EncryptedChat;\nencryptedChat#61f0d4c7 id:int access_hash:long date:int admin_id:long participant_id:long g_a_or_b:bytes key_fingerprint:long = EncryptedChat;\nencryptedChatDiscarded#1e1c7c45 flags:# history_deleted:flags.0?true id:int = EncryptedChat;\ninputEncryptedChat#f141b5e1 chat_id:int access_hash:long = InputEncryptedChat;\nencryptedFileEmpty#c21f497e = EncryptedFile;\nencryptedFile#4a70994c id:long access_hash:long size:int dc_id:int key_fingerprint:int = EncryptedFile;\ninputEncryptedFileEmpty#1837c364 = InputEncryptedFile;\ninputEncryptedFileUploaded#64bd0306 id:long parts:int md5_checksum:string key_fingerprint:int = InputEncryptedFile;\ninputEncryptedFile#5a17b5e5 id:long access_hash:long = InputEncryptedFile;\ninputEncryptedFileBigUploaded#2dc173c8 id:long parts:int key_fingerprint:int = InputEncryptedFile;\nencryptedMessage#ed18c118 random_id:long chat_id:int date:int bytes:bytes file:EncryptedFile = EncryptedMessage;\nencryptedMessageService#23734b06 random_id:long chat_id:int date:int bytes:bytes = EncryptedMessage;\nmessages.dhConfigNotModified#c0e24635 random:bytes = messages.DhConfig;\nmessages.dhConfig#2c221edd g:int p:bytes version:int random:bytes = messages.DhConfig;\nmessages.sentEncryptedMessage#560f8935 date:int = messages.SentEncryptedMessage;\nmessages.sentEncryptedFile#9493ff32 date:int file:EncryptedFile = messages.SentEncryptedMessage;\ninputDocumentEmpty#72f0eaae = InputDocument;\ninputDocument#1abfb575 id:long access_hash:long file_reference:bytes = InputDocument;\ndocumentEmpty#36f8c871 id:long = Document;\ndocument#1e87342b flags:# id:long access_hash:long file_reference:bytes date:int mime_type:string size:int thumbs:flags.0?Vector video_thumbs:flags.1?Vector dc_id:int attributes:Vector = Document;\nhelp.support#17c6b5f6 phone_number:string user:User = help.Support;\nnotifyPeer#9fd40bd8 peer:Peer = NotifyPeer;\nnotifyUsers#b4c83b4c = NotifyPeer;\nnotifyChats#c007cec3 = NotifyPeer;\nnotifyBroadcasts#d612e8ef = NotifyPeer;\nsendMessageTypingAction#16bf744e = SendMessageAction;\nsendMessageCancelAction#fd5ec8f5 = SendMessageAction;\nsendMessageRecordVideoAction#a187d66f = SendMessageAction;\nsendMessageUploadVideoAction#e9763aec progress:int = SendMessageAction;\nsendMessageRecordAudioAction#d52f73f7 = SendMessageAction;\nsendMessageUploadAudioAction#f351d7ab progress:int = SendMessageAction;\nsendMessageUploadPhotoAction#d1d34a26 progress:int = SendMessageAction;\nsendMessageUploadDocumentAction#aa0cd9e4 progress:int = SendMessageAction;\nsendMessageGeoLocationAction#176f8ba1 = SendMessageAction;\nsendMessageChooseContactAction#628cbc6f = SendMessageAction;\nsendMessageGamePlayAction#dd6a8f48 = SendMessageAction;\nsendMessageRecordRoundAction#88f27fbc = SendMessageAction;\nsendMessageUploadRoundAction#243e1c66 progress:int = SendMessageAction;\nspeakingInGroupCallAction#d92c2285 = SendMessageAction;\nsendMessageHistoryImportAction#dbda9246 progress:int = SendMessageAction;\nsendMessageChooseStickerAction#b05ac6b1 = SendMessageAction;\nsendMessageEmojiInteraction#25972bcb emoticon:string msg_id:int interaction:DataJSON = SendMessageAction;\nsendMessageEmojiInteractionSeen#b665902e emoticon:string = SendMessageAction;\ncontacts.found#b3134d9d my_results:Vector results:Vector chats:Vector users:Vector = contacts.Found;\ninputPrivacyKeyStatusTimestamp#4f96cb18 = InputPrivacyKey;\ninputPrivacyKeyChatInvite#bdfb0426 = InputPrivacyKey;\ninputPrivacyKeyPhoneCall#fabadc5f = InputPrivacyKey;\ninputPrivacyKeyPhoneP2P#db9e70d2 = InputPrivacyKey;\ninputPrivacyKeyForwards#a4dd4c08 = InputPrivacyKey;\ninputPrivacyKeyProfilePhoto#5719bacc = InputPrivacyKey;\ninputPrivacyKeyPhoneNumber#352dafa = InputPrivacyKey;\ninputPrivacyKeyAddedByPhone#d1219bdd = InputPrivacyKey;\nprivacyKeyStatusTimestamp#bc2eab30 = PrivacyKey;\nprivacyKeyChatInvite#500e6dfa = PrivacyKey;\nprivacyKeyPhoneCall#3d662b7b = PrivacyKey;\nprivacyKeyPhoneP2P#39491cc8 = PrivacyKey;\nprivacyKeyForwards#69ec56a3 = PrivacyKey;\nprivacyKeyProfilePhoto#96151fed = PrivacyKey;\nprivacyKeyPhoneNumber#d19ae46d = PrivacyKey;\nprivacyKeyAddedByPhone#42ffd42b = PrivacyKey;\ninputPrivacyValueAllowContacts#d09e07b = InputPrivacyRule;\ninputPrivacyValueAllowAll#184b35ce = InputPrivacyRule;\ninputPrivacyValueAllowUsers#131cc67f users:Vector = InputPrivacyRule;\ninputPrivacyValueDisallowContacts#ba52007 = InputPrivacyRule;\ninputPrivacyValueDisallowAll#d66b66c9 = InputPrivacyRule;\ninputPrivacyValueDisallowUsers#90110467 users:Vector = InputPrivacyRule;\ninputPrivacyValueAllowChatParticipants#840649cf chats:Vector = InputPrivacyRule;\ninputPrivacyValueDisallowChatParticipants#e94f0f86 chats:Vector = InputPrivacyRule;\nprivacyValueAllowContacts#fffe1bac = PrivacyRule;\nprivacyValueAllowAll#65427b82 = PrivacyRule;\nprivacyValueAllowUsers#b8905fb2 users:Vector = PrivacyRule;\nprivacyValueDisallowContacts#f888fa1a = PrivacyRule;\nprivacyValueDisallowAll#8b73e763 = PrivacyRule;\nprivacyValueDisallowUsers#e4621141 users:Vector = PrivacyRule;\nprivacyValueAllowChatParticipants#6b134e8e chats:Vector = PrivacyRule;\nprivacyValueDisallowChatParticipants#41c87565 chats:Vector = PrivacyRule;\naccount.privacyRules#50a04e45 rules:Vector chats:Vector users:Vector = account.PrivacyRules;\naccountDaysTTL#b8d0afdf days:int = AccountDaysTTL;\ndocumentAttributeImageSize#6c37c15c w:int h:int = DocumentAttribute;\ndocumentAttributeAnimated#11b58939 = DocumentAttribute;\ndocumentAttributeSticker#6319d612 flags:# mask:flags.1?true alt:string stickerset:InputStickerSet mask_coords:flags.0?MaskCoords = DocumentAttribute;\ndocumentAttributeVideo#ef02ce6 flags:# round_message:flags.0?true supports_streaming:flags.1?true duration:int w:int h:int = DocumentAttribute;\ndocumentAttributeAudio#9852f9c6 flags:# voice:flags.10?true duration:int title:flags.0?string performer:flags.1?string waveform:flags.2?bytes = DocumentAttribute;\ndocumentAttributeFilename#15590068 file_name:string = DocumentAttribute;\ndocumentAttributeHasStickers#9801d2f7 = DocumentAttribute;\nmessages.stickersNotModified#f1749a22 = messages.Stickers;\nmessages.stickers#30a6ec7e hash:long stickers:Vector = messages.Stickers;\nstickerPack#12b299d4 emoticon:string documents:Vector = StickerPack;\nmessages.allStickersNotModified#e86602c3 = messages.AllStickers;\nmessages.allStickers#cdbbcebb hash:long sets:Vector = messages.AllStickers;\nmessages.affectedMessages#84d19185 pts:int pts_count:int = messages.AffectedMessages;\nwebPageEmpty#eb1477e8 id:long = WebPage;\nwebPagePending#c586da1c id:long date:int = WebPage;\nwebPage#e89c45b2 flags:# id:long url:string display_url:string hash:int type:flags.0?string site_name:flags.1?string title:flags.2?string description:flags.3?string photo:flags.4?Photo embed_url:flags.5?string embed_type:flags.5?string embed_width:flags.6?int embed_height:flags.6?int duration:flags.7?int author:flags.8?string document:flags.9?Document cached_page:flags.10?Page attributes:flags.12?Vector = WebPage;\nwebPageNotModified#7311ca11 flags:# cached_page_views:flags.0?int = WebPage;\nauthorization#ad01d61d flags:# current:flags.0?true official_app:flags.1?true password_pending:flags.2?true hash:long device_model:string platform:string system_version:string api_id:int app_name:string app_version:string date_created:int date_active:int ip:string country:string region:string = Authorization;\naccount.authorizations#1250abde authorizations:Vector = 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#b18105e8 flags:# revoked:flags.0?true permanent:flags.5?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 = ExportedChatInvite;\nchatInviteAlready#5a686d7c chat:Chat = ChatInvite;\nchatInvite#dfc2f58e flags:# channel:flags.0?true broadcast:flags.1?true public:flags.2?true megagroup:flags.3?true title:string photo:Photo participants_count:int participants:flags.4?Vector = ChatInvite;\nchatInvitePeek#61695cb0 chat:Chat expires:int = ChatInvite;\ninputStickerSetEmpty#ffb62b95 = InputStickerSet;\ninputStickerSetID#9de7a269 id:long access_hash:long = InputStickerSet;\ninputStickerSetShortName#861cc8a0 short_name:string = InputStickerSet;\ninputStickerSetAnimatedEmoji#28703c8 = InputStickerSet;\ninputStickerSetDice#e67f520e emoticon:string = InputStickerSet;\ninputStickerSetAnimatedEmojiAnimations#cde3739 = InputStickerSet;\nstickerSet#d7df217a flags:# archived:flags.1?true official:flags.2?true masks:flags.3?true animated:flags.5?true installed_date:flags.0?int id:long access_hash:long title:string short_name:string thumbs:flags.4?Vector thumb_dc_id:flags.4?int thumb_version:flags.4?int count:int hash:int = StickerSet;\nmessages.stickerSet#b60a24a6 set:StickerSet packs:Vector documents:Vector = messages.StickerSet;\nbotCommand#c27ac8c7 command:string description:string = BotCommand;\nbotInfo#1b74b335 user_id:long description:string commands:Vector = BotInfo;\nkeyboardButton#a2fa4880 text:string = KeyboardButton;\nkeyboardButtonUrl#258aff05 text:string url:string = KeyboardButton;\nkeyboardButtonCallback#35bbdb6b flags:# requires_password:flags.0?true text:string data:bytes = KeyboardButton;\nkeyboardButtonRequestPhone#b16a6c29 text:string = KeyboardButton;\nkeyboardButtonRequestGeoLocation#fc796b3f text:string = KeyboardButton;\nkeyboardButtonSwitchInline#568a748 flags:# same_peer:flags.0?true text:string query:string = KeyboardButton;\nkeyboardButtonGame#50f41ccf text:string = KeyboardButton;\nkeyboardButtonBuy#afd93fbb text:string = KeyboardButton;\nkeyboardButtonUrlAuth#10b78d29 flags:# text:string fwd_text:flags.0?string url:string button_id:int = KeyboardButton;\ninputKeyboardButtonUrlAuth#d02e7fd4 flags:# request_write_access:flags.0?true text:string fwd_text:flags.1?string url:string bot:InputUser = KeyboardButton;\nkeyboardButtonRequestPoll#bbc7515d flags:# quiz:flags.0?Bool text:string = KeyboardButton;\nkeyboardButtonRow#77608b83 buttons:Vector = KeyboardButtonRow;\nreplyKeyboardHide#a03e5b85 flags:# selective:flags.2?true = ReplyMarkup;\nreplyKeyboardForceReply#86b40b08 flags:# single_use:flags.1?true selective:flags.2?true placeholder:flags.3?string = ReplyMarkup;\nreplyKeyboardMarkup#85dd99d1 flags:# resize:flags.0?true single_use:flags.1?true selective:flags.2?true rows:Vector placeholder:flags.3?string = ReplyMarkup;\nreplyInlineMarkup#48a30254 rows:Vector = ReplyMarkup;\nmessageEntityUnknown#bb92ba95 offset:int length:int = MessageEntity;\nmessageEntityMention#fa04579d offset:int length:int = MessageEntity;\nmessageEntityHashtag#6f635b0d offset:int length:int = MessageEntity;\nmessageEntityBotCommand#6cef8ac7 offset:int length:int = MessageEntity;\nmessageEntityUrl#6ed02538 offset:int length:int = MessageEntity;\nmessageEntityEmail#64e475c2 offset:int length:int = MessageEntity;\nmessageEntityBold#bd610bc9 offset:int length:int = MessageEntity;\nmessageEntityItalic#826f8b60 offset:int length:int = MessageEntity;\nmessageEntityCode#28a20571 offset:int length:int = MessageEntity;\nmessageEntityPre#73924be0 offset:int length:int language:string = MessageEntity;\nmessageEntityTextUrl#76a6d327 offset:int length:int url:string = MessageEntity;\nmessageEntityMentionName#dc7b1140 offset:int length:int user_id:long = MessageEntity;\ninputMessageEntityMentionName#208e68c9 offset:int length:int user_id:InputUser = MessageEntity;\nmessageEntityPhone#9b69e34b offset:int length:int = MessageEntity;\nmessageEntityCashtag#4c4e743f offset:int length:int = MessageEntity;\nmessageEntityUnderline#9c4e7e8b offset:int length:int = MessageEntity;\nmessageEntityStrike#bf0693d4 offset:int length:int = MessageEntity;\nmessageEntityBlockquote#20df5d0 offset:int length:int = MessageEntity;\nmessageEntityBankCard#761e6af4 offset:int length:int = MessageEntity;\ninputChannelEmpty#ee8c1e86 = InputChannel;\ninputChannel#f35aec28 channel_id:long access_hash:long = InputChannel;\ninputChannelFromMessage#5b934f9d peer:InputPeer msg_id:int channel_id:long = InputChannel;\ncontacts.resolvedPeer#7f077ad9 peer:Peer chats:Vector users:Vector = contacts.ResolvedPeer;\nmessageRange#ae30253 min_id:int max_id:int = MessageRange;\nupdates.channelDifferenceEmpty#3e11affb flags:# final:flags.0?true pts:int timeout:flags.1?int = updates.ChannelDifference;\nupdates.channelDifferenceTooLong#a4bcc6fe flags:# final:flags.0?true timeout:flags.1?int dialog:Dialog messages:Vector chats:Vector users:Vector = updates.ChannelDifference;\nupdates.channelDifference#2064674e flags:# final:flags.0?true pts:int timeout:flags.1?int new_messages:Vector other_updates:Vector chats:Vector users:Vector = updates.ChannelDifference;\nchannelMessagesFilterEmpty#94d42ee7 = ChannelMessagesFilter;\nchannelMessagesFilter#cd77d957 flags:# exclude_new_messages:flags.1?true ranges:Vector = ChannelMessagesFilter;\nchannelParticipant#c00c07c0 user_id:long date:int = ChannelParticipant;\nchannelParticipantSelf#28a8bc67 user_id:long inviter_id:long date:int = ChannelParticipant;\nchannelParticipantCreator#2fe601d3 flags:# user_id:long admin_rights:ChatAdminRights rank:flags.0?string = ChannelParticipant;\nchannelParticipantAdmin#34c3bb53 flags:# can_edit:flags.0?true self:flags.1?true user_id:long inviter_id:flags.1?long promoted_by:long date:int admin_rights:ChatAdminRights rank:flags.2?string = ChannelParticipant;\nchannelParticipantBanned#6df8014e flags:# left:flags.0?true peer:Peer kicked_by:long date:int banned_rights:ChatBannedRights = ChannelParticipant;\nchannelParticipantLeft#1b03f006 peer:Peer = ChannelParticipant;\nchannelParticipantsRecent#de3f3c79 = ChannelParticipantsFilter;\nchannelParticipantsAdmins#b4608969 = ChannelParticipantsFilter;\nchannelParticipantsKicked#a3b54985 q:string = ChannelParticipantsFilter;\nchannelParticipantsBots#b0d1865b = ChannelParticipantsFilter;\nchannelParticipantsBanned#1427a5e1 q:string = ChannelParticipantsFilter;\nchannelParticipantsSearch#656ac4b q:string = ChannelParticipantsFilter;\nchannelParticipantsContacts#bb6ae88d q:string = ChannelParticipantsFilter;\nchannelParticipantsMentions#e04b5ceb flags:# q:flags.0?string top_msg_id:flags.1?int = ChannelParticipantsFilter;\nchannels.channelParticipants#9ab0feaf count:int participants:Vector chats:Vector users:Vector = channels.ChannelParticipants;\nchannels.channelParticipantsNotModified#f0173fe9 = channels.ChannelParticipants;\nchannels.channelParticipant#dfb80317 participant:ChannelParticipant chats:Vector users:Vector = channels.ChannelParticipant;\nhelp.termsOfService#780a0310 flags:# popup:flags.0?true id:DataJSON text:string entities:Vector min_age_confirm:flags.1?int = help.TermsOfService;\nmessages.savedGifsNotModified#e8025ca2 = messages.SavedGifs;\nmessages.savedGifs#84a02a0d hash:long gifs:Vector = messages.SavedGifs;\ninputBotInlineMessageMediaAuto#3380c786 flags:# message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageText#3dcd7a87 flags:# no_webpage:flags.0?true message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaGeo#96929a85 flags:# geo_point:InputGeoPoint heading:flags.0?int period:flags.1?int proximity_notification_radius:flags.3?int reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaVenue#417bbf11 flags:# geo_point:InputGeoPoint title:string address:string provider:string venue_id:string venue_type:string reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaContact#a6edbffd flags:# phone_number:string first_name:string last_name:string vcard:string reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageGame#4b425864 flags:# reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaInvoice#d7e78225 flags:# title:string description:string photo:flags.0?InputWebDocument invoice:Invoice payload:bytes provider:string provider_data:DataJSON reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineResult#88bf9319 flags:# id:string type:string title:flags.1?string description:flags.2?string url:flags.3?string thumb:flags.4?InputWebDocument content:flags.5?InputWebDocument send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultPhoto#a8d864a7 id:string type:string photo:InputPhoto send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultDocument#fff8fdc4 flags:# id:string type:string title:flags.1?string description:flags.2?string document:InputDocument send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultGame#4fa417f2 id:string short_name:string send_message:InputBotInlineMessage = InputBotInlineResult;\nbotInlineMessageMediaAuto#764cf810 flags:# message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageText#8c7f65e2 flags:# no_webpage:flags.0?true message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaGeo#51846fd flags:# geo:GeoPoint heading:flags.0?int period:flags.1?int proximity_notification_radius:flags.3?int reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaVenue#8a86659c flags:# geo:GeoPoint title:string address:string provider:string venue_id:string venue_type:string reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaContact#18d1cdc2 flags:# phone_number:string first_name:string last_name:string vcard:string reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaInvoice#354a9b09 flags:# shipping_address_requested:flags.1?true test:flags.3?true title:string description:string photo:flags.0?WebDocument currency:string total_amount:long reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineResult#11965f3a flags:# id:string type:string title:flags.1?string description:flags.2?string url:flags.3?string thumb:flags.4?WebDocument content:flags.5?WebDocument send_message:BotInlineMessage = BotInlineResult;\nbotInlineMediaResult#17db940b flags:# id:string type:string photo:flags.0?Photo document:flags.1?Document title:flags.2?string description:flags.3?string send_message:BotInlineMessage = BotInlineResult;\nmessages.botResults#947ca848 flags:# gallery:flags.0?true query_id:long next_offset:flags.1?string switch_pm:flags.2?InlineBotSwitchPM results:Vector cache_time:int users:Vector = messages.BotResults;\nexportedMessageLink#5dab1af4 link:string html:string = ExportedMessageLink;\nmessageFwdHeader#5f777dce flags:# imported:flags.7?true from_id:flags.0?Peer from_name:flags.5?string date:int channel_post:flags.2?int post_author:flags.3?string saved_from_peer:flags.4?Peer saved_from_msg_id:flags.4?int psa_type:flags.6?string = MessageFwdHeader;\nauth.codeTypeSms#72a3158c = auth.CodeType;\nauth.codeTypeCall#741cd3e3 = auth.CodeType;\nauth.codeTypeFlashCall#226ccefb = auth.CodeType;\nauth.sentCodeTypeApp#3dbb5986 length:int = auth.SentCodeType;\nauth.sentCodeTypeSms#c000bba2 length:int = auth.SentCodeType;\nauth.sentCodeTypeCall#5353e5a7 length:int = auth.SentCodeType;\nauth.sentCodeTypeFlashCall#ab03c6d9 pattern:string = auth.SentCodeType;\nmessages.botCallbackAnswer#36585ea4 flags:# alert:flags.1?true has_url:flags.3?true native_ui:flags.4?true message:flags.0?string url:flags.2?string cache_time:int = messages.BotCallbackAnswer;\nmessages.messageEditData#26b5dde6 flags:# caption:flags.0?true = messages.MessageEditData;\ninputBotInlineMessageID#890c3d89 dc_id:int id:long access_hash:long = InputBotInlineMessageID;\ninputBotInlineMessageID64#b6d915d7 dc_id:int owner_id:long id:int access_hash:long = InputBotInlineMessageID;\ninlineBotSwitchPM#3c20629f text:string start_param:string = InlineBotSwitchPM;\nmessages.peerDialogs#3371c354 dialogs:Vector messages:Vector chats:Vector users:Vector state:updates.State = messages.PeerDialogs;\ntopPeer#edcdc05b peer:Peer rating:double = TopPeer;\ntopPeerCategoryBotsPM#ab661b5b = TopPeerCategory;\ntopPeerCategoryBotsInline#148677e2 = TopPeerCategory;\ntopPeerCategoryCorrespondents#637b7ed = TopPeerCategory;\ntopPeerCategoryGroups#bd17a14a = TopPeerCategory;\ntopPeerCategoryChannels#161d9628 = TopPeerCategory;\ntopPeerCategoryPhoneCalls#1e76a78c = TopPeerCategory;\ntopPeerCategoryForwardUsers#a8406ca9 = TopPeerCategory;\ntopPeerCategoryForwardChats#fbeec0f0 = TopPeerCategory;\ntopPeerCategoryPeers#fb834291 category:TopPeerCategory count:int peers:Vector = TopPeerCategoryPeers;\ncontacts.topPeersNotModified#de266ef5 = contacts.TopPeers;\ncontacts.topPeers#70b772a8 categories:Vector chats:Vector users:Vector = contacts.TopPeers;\ncontacts.topPeersDisabled#b52c939d = contacts.TopPeers;\ndraftMessageEmpty#1b0c841a flags:# date:flags.0?int = DraftMessage;\ndraftMessage#fd8e711f flags:# no_webpage:flags.1?true reply_to_msg_id:flags.0?int message:string entities:flags.3?Vector date:int = DraftMessage;\nmessages.featuredStickersNotModified#c6dc0c66 count:int = messages.FeaturedStickers;\nmessages.featuredStickers#84c02310 hash:long count:int sets:Vector unread:Vector = messages.FeaturedStickers;\nmessages.recentStickersNotModified#b17f890 = messages.RecentStickers;\nmessages.recentStickers#88d37c56 hash:long packs:Vector stickers:Vector dates:Vector = messages.RecentStickers;\nmessages.archivedStickers#4fcba9c8 count:int sets:Vector = messages.ArchivedStickers;\nmessages.stickerSetInstallResultSuccess#38641628 = messages.StickerSetInstallResult;\nmessages.stickerSetInstallResultArchive#35e410a8 sets:Vector = messages.StickerSetInstallResult;\nstickerSetCovered#6410a5d2 set:StickerSet cover:Document = StickerSetCovered;\nstickerSetMultiCovered#3407e51b set:StickerSet covers:Vector = StickerSetCovered;\nmaskCoords#aed6dbb2 n:int x:double y:double zoom:double = MaskCoords;\ninputStickeredMediaPhoto#4a992157 id:InputPhoto = InputStickeredMedia;\ninputStickeredMediaDocument#438865b id:InputDocument = InputStickeredMedia;\ngame#bdf9653b flags:# id:long access_hash:long short_name:string title:string description:string photo:Photo document:flags.0?Document = Game;\ninputGameID#32c3e77 id:long access_hash:long = InputGame;\ninputGameShortName#c331e80a bot_id:InputUser short_name:string = InputGame;\nhighScore#73a379eb pos:int user_id:long score:int = HighScore;\nmessages.highScores#9a3bfd99 scores:Vector users:Vector = messages.HighScores;\ntextEmpty#dc3d824f = RichText;\ntextPlain#744694e0 text:string = RichText;\ntextBold#6724abc4 text:RichText = RichText;\ntextItalic#d912a59c text:RichText = RichText;\ntextUnderline#c12622c4 text:RichText = RichText;\ntextStrike#9bf8bb95 text:RichText = RichText;\ntextFixed#6c3f19b9 text:RichText = RichText;\ntextUrl#3c2884c1 text:RichText url:string webpage_id:long = RichText;\ntextEmail#de5a0dd6 text:RichText email:string = RichText;\ntextConcat#7e6260d7 texts:Vector = RichText;\ntextSubscript#ed6a8504 text:RichText = RichText;\ntextSuperscript#c7fb5e01 text:RichText = RichText;\ntextMarked#34b8621 text:RichText = RichText;\ntextPhone#1ccb966a text:RichText phone:string = RichText;\ntextImage#81ccf4f document_id:long w:int h:int = RichText;\ntextAnchor#35553762 text:RichText name:string = RichText;\npageBlockUnsupported#13567e8a = PageBlock;\npageBlockTitle#70abc3fd text:RichText = PageBlock;\npageBlockSubtitle#8ffa9a1f text:RichText = PageBlock;\npageBlockAuthorDate#baafe5e0 author:RichText published_date:int = PageBlock;\npageBlockHeader#bfd064ec text:RichText = PageBlock;\npageBlockSubheader#f12bb6e1 text:RichText = PageBlock;\npageBlockParagraph#467a0766 text:RichText = PageBlock;\npageBlockPreformatted#c070d93e text:RichText language:string = PageBlock;\npageBlockFooter#48870999 text:RichText = PageBlock;\npageBlockDivider#db20b188 = PageBlock;\npageBlockAnchor#ce0d37b0 name:string = PageBlock;\npageBlockList#e4e88011 items:Vector = PageBlock;\npageBlockBlockquote#263d7c26 text:RichText caption:RichText = PageBlock;\npageBlockPullquote#4f4456d3 text:RichText caption:RichText = PageBlock;\npageBlockPhoto#1759c560 flags:# photo_id:long caption:PageCaption url:flags.0?string webpage_id:flags.0?long = PageBlock;\npageBlockVideo#7c8fe7b6 flags:# autoplay:flags.0?true loop:flags.1?true video_id:long caption:PageCaption = PageBlock;\npageBlockCover#39f23300 cover:PageBlock = PageBlock;\npageBlockEmbed#a8718dc5 flags:# full_width:flags.0?true allow_scrolling:flags.3?true url:flags.1?string html:flags.2?string poster_photo_id:flags.4?long w:flags.5?int h:flags.5?int caption:PageCaption = PageBlock;\npageBlockEmbedPost#f259a80b url:string webpage_id:long author_photo_id:long author:string date:int blocks:Vector caption:PageCaption = PageBlock;\npageBlockCollage#65a0fa4d items:Vector caption:PageCaption = PageBlock;\npageBlockSlideshow#31f9590 items:Vector caption:PageCaption = PageBlock;\npageBlockChannel#ef1751b5 channel:Chat = PageBlock;\npageBlockAudio#804361ea audio_id:long caption:PageCaption = PageBlock;\npageBlockKicker#1e148390 text:RichText = PageBlock;\npageBlockTable#bf4dea82 flags:# bordered:flags.0?true striped:flags.1?true title:RichText rows:Vector = PageBlock;\npageBlockOrderedList#9a8ae1e1 items:Vector = PageBlock;\npageBlockDetails#76768bed flags:# open:flags.0?true blocks:Vector title:RichText = PageBlock;\npageBlockRelatedArticles#16115a96 title:RichText articles:Vector = PageBlock;\npageBlockMap#a44f3ef6 geo:GeoPoint zoom:int w:int h:int caption:PageCaption = PageBlock;\nphoneCallDiscardReasonMissed#85e42301 = PhoneCallDiscardReason;\nphoneCallDiscardReasonDisconnect#e095c1a0 = PhoneCallDiscardReason;\nphoneCallDiscardReasonHangup#57adc690 = PhoneCallDiscardReason;\nphoneCallDiscardReasonBusy#faf7e8c9 = PhoneCallDiscardReason;\ndataJSON#7d748d04 data:string = DataJSON;\nlabeledPrice#cb296bf8 label:string amount:long = LabeledPrice;\ninvoice#cd886e0 flags:# test:flags.0?true name_requested:flags.1?true phone_requested:flags.2?true email_requested:flags.3?true shipping_address_requested:flags.4?true flexible:flags.5?true phone_to_provider:flags.6?true email_to_provider:flags.7?true currency:string prices:Vector max_tip_amount:flags.8?long suggested_tip_amounts:flags.8?Vector = Invoice;\npaymentCharge#ea02c27e id:string provider_charge_id:string = PaymentCharge;\npostAddress#1e8caaeb street_line1:string street_line2:string city:string state:string country_iso2:string post_code:string = PostAddress;\npaymentRequestedInfo#909c3f94 flags:# name:flags.0?string phone:flags.1?string email:flags.2?string shipping_address:flags.3?PostAddress = PaymentRequestedInfo;\npaymentSavedCredentialsCard#cdc27a1f id:string title:string = PaymentSavedCredentials;\nwebDocument#1c570ed1 url:string access_hash:long size:int mime_type:string attributes:Vector = WebDocument;\nwebDocumentNoProxy#f9c8bcc6 url:string size:int mime_type:string attributes:Vector = WebDocument;\ninputWebDocument#9bed434d url:string size:int mime_type:string attributes:Vector = InputWebDocument;\ninputWebFileLocation#c239d686 url:string access_hash:long = InputWebFileLocation;\ninputWebFileGeoPointLocation#9f2221c9 geo_point:InputGeoPoint access_hash:long w:int h:int zoom:int scale:int = InputWebFileLocation;\nupload.webFile#21e753bc size:int mime_type:string file_type:storage.FileType mtime:int bytes:bytes = upload.WebFile;\npayments.paymentForm#1694761b flags:# can_save_credentials:flags.2?true password_missing:flags.3?true form_id:long bot_id:long invoice:Invoice provider_id:long url:string native_provider:flags.4?string native_params:flags.4?DataJSON saved_info:flags.0?PaymentRequestedInfo saved_credentials:flags.1?PaymentSavedCredentials users:Vector = payments.PaymentForm;\npayments.validatedRequestedInfo#d1451883 flags:# id:flags.0?string shipping_options:flags.1?Vector = payments.ValidatedRequestedInfo;\npayments.paymentResult#4e5f810d updates:Updates = payments.PaymentResult;\npayments.paymentVerificationNeeded#d8411139 url:string = payments.PaymentResult;\npayments.paymentReceipt#70c4fe03 flags:# date:int bot_id:long provider_id:long title:string description:string photo:flags.2?WebDocument invoice:Invoice info:flags.0?PaymentRequestedInfo shipping:flags.1?ShippingOption tip_amount:flags.3?long currency:string total_amount:long credentials_title:string users:Vector = payments.PaymentReceipt;\npayments.savedInfo#fb8fe43c flags:# has_saved_credentials:flags.1?true saved_info:flags.0?PaymentRequestedInfo = payments.SavedInfo;\ninputPaymentCredentialsSaved#c10eb2cf id:string tmp_password:bytes = InputPaymentCredentials;\ninputPaymentCredentials#3417d728 flags:# save:flags.0?true data:DataJSON = InputPaymentCredentials;\ninputPaymentCredentialsApplePay#aa1c39f payment_data:DataJSON = InputPaymentCredentials;\ninputPaymentCredentialsGooglePay#8ac32801 payment_token:DataJSON = InputPaymentCredentials;\naccount.tmpPassword#db64fd34 tmp_password:bytes valid_until:int = account.TmpPassword;\nshippingOption#b6213cdf id:string title:string prices:Vector = ShippingOption;\ninputStickerSetItem#ffa0a496 flags:# document:InputDocument emoji:string mask_coords:flags.0?MaskCoords = InputStickerSetItem;\ninputPhoneCall#1e36fded id:long access_hash:long = InputPhoneCall;\nphoneCallEmpty#5366c915 id:long = PhoneCall;\nphoneCallWaiting#c5226f17 flags:# video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long protocol:PhoneCallProtocol receive_date:flags.0?int = PhoneCall;\nphoneCallRequested#14b0ed0c flags:# video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long g_a_hash:bytes protocol:PhoneCallProtocol = PhoneCall;\nphoneCallAccepted#3660c311 flags:# video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long g_b:bytes protocol:PhoneCallProtocol = PhoneCall;\nphoneCall#967f7c67 flags:# p2p_allowed:flags.5?true video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long g_a_or_b:bytes key_fingerprint:long protocol:PhoneCallProtocol connections:Vector start_date:int = PhoneCall;\nphoneCallDiscarded#50ca4de1 flags:# need_rating:flags.2?true need_debug:flags.3?true video:flags.6?true id:long reason:flags.0?PhoneCallDiscardReason duration:flags.1?int = PhoneCall;\nphoneConnection#9d4c17c0 id:long ip:string ipv6:string port:int peer_tag:bytes = PhoneConnection;\nphoneConnectionWebrtc#635fe375 flags:# turn:flags.0?true stun:flags.1?true id:long ip:string ipv6:string port:int username:string password:string = PhoneConnection;\nphoneCallProtocol#fc878fc8 flags:# udp_p2p:flags.0?true udp_reflector:flags.1?true min_layer:int max_layer:int library_versions:Vector = PhoneCallProtocol;\nphone.phoneCall#ec82e140 phone_call:PhoneCall users:Vector = phone.PhoneCall;\nupload.cdnFileReuploadNeeded#eea8e46e request_token:bytes = upload.CdnFile;\nupload.cdnFile#a99fca4f bytes:bytes = upload.CdnFile;\ncdnPublicKey#c982eaba dc_id:int public_key:string = CdnPublicKey;\ncdnConfig#5725e40a public_keys:Vector = CdnConfig;\nlangPackString#cad181f6 key:string value:string = LangPackString;\nlangPackStringPluralized#6c47ac9f flags:# key:string zero_value:flags.0?string one_value:flags.1?string two_value:flags.2?string few_value:flags.3?string many_value:flags.4?string other_value:string = LangPackString;\nlangPackStringDeleted#2979eeb2 key:string = LangPackString;\nlangPackDifference#f385c1f6 lang_code:string from_version:int version:int strings:Vector = LangPackDifference;\nlangPackLanguage#eeca5ce3 flags:# official:flags.0?true rtl:flags.2?true beta:flags.3?true name:string native_name:string lang_code:string base_lang_code:flags.1?string plural_code:string strings_count:int translated_count:int translations_url:string = LangPackLanguage;\nchannelAdminLogEventActionChangeTitle#e6dfb825 prev_value:string new_value:string = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeAbout#55188a2e prev_value:string new_value:string = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeUsername#6a4afc38 prev_value:string new_value:string = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangePhoto#434bd2af prev_photo:Photo new_photo:Photo = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleInvites#1b7907ae new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleSignatures#26ae0971 new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionUpdatePinned#e9e82c18 message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionEditMessage#709b2405 prev_message:Message new_message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionDeleteMessage#42e047bb message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantJoin#183040d3 = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantLeave#f89777f2 = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantInvite#e31c34d8 participant:ChannelParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantToggleBan#e6d83d7e prev_participant:ChannelParticipant new_participant:ChannelParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantToggleAdmin#d5676710 prev_participant:ChannelParticipant new_participant:ChannelParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeStickerSet#b1c3caa7 prev_stickerset:InputStickerSet new_stickerset:InputStickerSet = ChannelAdminLogEventAction;\nchannelAdminLogEventActionTogglePreHistoryHidden#5f5c95f1 new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionDefaultBannedRights#2df5fc0a prev_banned_rights:ChatBannedRights new_banned_rights:ChatBannedRights = ChannelAdminLogEventAction;\nchannelAdminLogEventActionStopPoll#8f079643 message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeLinkedChat#50c7ac8 prev_value:long new_value:long = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeLocation#e6b76ae prev_value:ChannelLocation new_value:ChannelLocation = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleSlowMode#53909779 prev_value:int new_value:int = ChannelAdminLogEventAction;\nchannelAdminLogEventActionStartGroupCall#23209745 call:InputGroupCall = ChannelAdminLogEventAction;\nchannelAdminLogEventActionDiscardGroupCall#db9f9140 call:InputGroupCall = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantMute#f92424d2 participant:GroupCallParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantUnmute#e64429c0 participant:GroupCallParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleGroupCallSetting#56d6a247 join_muted:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantJoinByInvite#5cdada77 invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionExportedInviteDelete#5a50fca4 invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionExportedInviteRevoke#410a134e invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionExportedInviteEdit#e90ebb59 prev_invite:ExportedChatInvite new_invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantVolume#3e7f6847 participant:GroupCallParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeHistoryTTL#6e941a38 prev_value:int new_value:int = ChannelAdminLogEventAction;\nchannelAdminLogEvent#1fad68cd id:long date:int user_id:long action:ChannelAdminLogEventAction = ChannelAdminLogEvent;\nchannels.adminLogResults#ed8af74d events:Vector chats:Vector users:Vector = channels.AdminLogResults;\nchannelAdminLogEventsFilter#ea107ae4 flags:# join:flags.0?true leave:flags.1?true invite:flags.2?true ban:flags.3?true unban:flags.4?true kick:flags.5?true unkick:flags.6?true promote:flags.7?true demote:flags.8?true info:flags.9?true settings:flags.10?true pinned:flags.11?true edit:flags.12?true delete:flags.13?true group_call:flags.14?true invites:flags.15?true = ChannelAdminLogEventsFilter;\npopularContact#5ce14175 client_id:long importers:int = PopularContact;\nmessages.favedStickersNotModified#9e8fa6d3 = messages.FavedStickers;\nmessages.favedStickers#2cb51097 hash:long packs:Vector stickers:Vector = messages.FavedStickers;\nrecentMeUrlUnknown#46e1d13d url:string = RecentMeUrl;\nrecentMeUrlUser#b92c09e2 url:string user_id:long = RecentMeUrl;\nrecentMeUrlChat#b2da71d2 url:string chat_id:long = RecentMeUrl;\nrecentMeUrlChatInvite#eb49081d url:string chat_invite:ChatInvite = RecentMeUrl;\nrecentMeUrlStickerSet#bc0a57dc url:string set:StickerSetCovered = RecentMeUrl;\nhelp.recentMeUrls#e0310d7 urls:Vector chats:Vector users:Vector = help.RecentMeUrls;\ninputSingleMedia#1cc6e91f flags:# media:InputMedia random_id:long message:string entities:flags.0?Vector = InputSingleMedia;\nwebAuthorization#a6f8f452 hash:long bot_id:long domain:string browser:string platform:string date_created:int date_active:int ip:string region:string = WebAuthorization;\naccount.webAuthorizations#ed56c9fc authorizations:Vector users:Vector = account.WebAuthorizations;\ninputMessageID#a676a322 id:int = InputMessage;\ninputMessageReplyTo#bad88395 id:int = InputMessage;\ninputMessagePinned#86872538 = InputMessage;\ninputMessageCallbackQuery#acfa1a7e id:int query_id:long = InputMessage;\ninputDialogPeer#fcaafeb7 peer:InputPeer = InputDialogPeer;\ninputDialogPeerFolder#64600527 folder_id:int = InputDialogPeer;\ndialogPeer#e56dbf05 peer:Peer = DialogPeer;\ndialogPeerFolder#514519e2 folder_id:int = DialogPeer;\nmessages.foundStickerSetsNotModified#d54b65d = messages.FoundStickerSets;\nmessages.foundStickerSets#8af09dd2 hash:long sets:Vector = messages.FoundStickerSets;\nfileHash#6242c773 offset:int limit:int hash:bytes = FileHash;\ninputClientProxy#75588b3f address:string port:int = InputClientProxy;\nhelp.termsOfServiceUpdateEmpty#e3309f7f expires:int = help.TermsOfServiceUpdate;\nhelp.termsOfServiceUpdate#28ecf961 expires:int terms_of_service:help.TermsOfService = help.TermsOfServiceUpdate;\ninputSecureFileUploaded#3334b0f0 id:long parts:int md5_checksum:string file_hash:bytes secret:bytes = InputSecureFile;\ninputSecureFile#5367e5be id:long access_hash:long = InputSecureFile;\nsecureFileEmpty#64199744 = SecureFile;\nsecureFile#e0277a62 id:long access_hash:long size:int dc_id:int date:int file_hash:bytes secret:bytes = SecureFile;\nsecureData#8aeabec3 data:bytes data_hash:bytes secret:bytes = SecureData;\nsecurePlainPhone#7d6099dd phone:string = SecurePlainData;\nsecurePlainEmail#21ec5a5f email:string = SecurePlainData;\nsecureValueTypePersonalDetails#9d2a81e3 = SecureValueType;\nsecureValueTypePassport#3dac6a00 = SecureValueType;\nsecureValueTypeDriverLicense#6e425c4 = SecureValueType;\nsecureValueTypeIdentityCard#a0d0744b = SecureValueType;\nsecureValueTypeInternalPassport#99a48f23 = SecureValueType;\nsecureValueTypeAddress#cbe31e26 = SecureValueType;\nsecureValueTypeUtilityBill#fc36954e = SecureValueType;\nsecureValueTypeBankStatement#89137c0d = SecureValueType;\nsecureValueTypeRentalAgreement#8b883488 = SecureValueType;\nsecureValueTypePassportRegistration#99e3806a = SecureValueType;\nsecureValueTypeTemporaryRegistration#ea02ec33 = SecureValueType;\nsecureValueTypePhone#b320aadb = SecureValueType;\nsecureValueTypeEmail#8e3ca7ee = SecureValueType;\nsecureValue#187fa0ca flags:# type:SecureValueType data:flags.0?SecureData front_side:flags.1?SecureFile reverse_side:flags.2?SecureFile selfie:flags.3?SecureFile translation:flags.6?Vector files:flags.4?Vector plain_data:flags.5?SecurePlainData hash:bytes = SecureValue;\ninputSecureValue#db21d0a7 flags:# type:SecureValueType data:flags.0?SecureData front_side:flags.1?InputSecureFile reverse_side:flags.2?InputSecureFile selfie:flags.3?InputSecureFile translation:flags.6?Vector files:flags.4?Vector plain_data:flags.5?SecurePlainData = InputSecureValue;\nsecureValueHash#ed1ecdb0 type:SecureValueType hash:bytes = SecureValueHash;\nsecureValueErrorData#e8a40bd9 type:SecureValueType data_hash:bytes field:string text:string = SecureValueError;\nsecureValueErrorFrontSide#be3dfa type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorReverseSide#868a2aa5 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorSelfie#e537ced6 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorFile#7a700873 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorFiles#666220e9 type:SecureValueType file_hash:Vector text:string = SecureValueError;\nsecureValueError#869d758f type:SecureValueType hash:bytes text:string = SecureValueError;\nsecureValueErrorTranslationFile#a1144770 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorTranslationFiles#34636dd8 type:SecureValueType file_hash:Vector text:string = SecureValueError;\nsecureCredentialsEncrypted#33f0ea47 data:bytes hash:bytes secret:bytes = SecureCredentialsEncrypted;\naccount.authorizationForm#ad2e1cd8 flags:# required_types:Vector values:Vector errors:Vector users:Vector privacy_policy_url:flags.0?string = account.AuthorizationForm;\naccount.sentEmailCode#811f854f email_pattern:string length:int = account.SentEmailCode;\nhelp.deepLinkInfoEmpty#66afa166 = help.DeepLinkInfo;\nhelp.deepLinkInfo#6a4ee832 flags:# update_app:flags.0?true message:string entities:flags.1?Vector = help.DeepLinkInfo;\nsavedPhoneContact#1142bd56 phone:string first_name:string last_name:string date:int = SavedContact;\naccount.takeout#4dba4501 id:long = account.Takeout;\npasswordKdfAlgoUnknown#d45ab096 = PasswordKdfAlgo;\npasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow#3a912d4a salt1:bytes salt2:bytes g:int p:bytes = PasswordKdfAlgo;\nsecurePasswordKdfAlgoUnknown#4a8537 = SecurePasswordKdfAlgo;\nsecurePasswordKdfAlgoPBKDF2HMACSHA512iter100000#bbf2dda0 salt:bytes = SecurePasswordKdfAlgo;\nsecurePasswordKdfAlgoSHA512#86471d92 salt:bytes = SecurePasswordKdfAlgo;\nsecureSecretSettings#1527bcac secure_algo:SecurePasswordKdfAlgo secure_secret:bytes secure_secret_id:long = SecureSecretSettings;\ninputCheckPasswordEmpty#9880f658 = InputCheckPasswordSRP;\ninputCheckPasswordSRP#d27ff082 srp_id:long A:bytes M1:bytes = InputCheckPasswordSRP;\nsecureRequiredType#829d99da flags:# native_names:flags.0?true selfie_required:flags.1?true translation_required:flags.2?true type:SecureValueType = SecureRequiredType;\nsecureRequiredTypeOneOf#27477b4 types:Vector = SecureRequiredType;\nhelp.passportConfigNotModified#bfb9f457 = help.PassportConfig;\nhelp.passportConfig#a098d6af hash:int countries_langs:DataJSON = help.PassportConfig;\ninputAppEvent#1d1b1245 time:double type:string peer:long data:JSONValue = InputAppEvent;\njsonObjectValue#c0de1bd9 key:string value:JSONValue = JSONObjectValue;\njsonNull#3f6d7b68 = JSONValue;\njsonBool#c7345e6a value:Bool = JSONValue;\njsonNumber#2be0dfa4 value:double = JSONValue;\njsonString#b71e767a value:string = JSONValue;\njsonArray#f7444763 value:Vector = JSONValue;\njsonObject#99c1d49d value:Vector = JSONValue;\npageTableCell#34566b6a flags:# header:flags.0?true align_center:flags.3?true align_right:flags.4?true valign_middle:flags.5?true valign_bottom:flags.6?true text:flags.7?RichText colspan:flags.1?int rowspan:flags.2?int = PageTableCell;\npageTableRow#e0c0c5e5 cells:Vector = PageTableRow;\npageCaption#6f747657 text:RichText credit:RichText = PageCaption;\npageListItemText#b92fb6cd text:RichText = PageListItem;\npageListItemBlocks#25e073fc blocks:Vector = PageListItem;\npageListOrderedItemText#5e068047 num:string text:RichText = PageListOrderedItem;\npageListOrderedItemBlocks#98dd8936 num:string blocks:Vector = PageListOrderedItem;\npageRelatedArticle#b390dc08 flags:# url:string webpage_id:long title:flags.0?string description:flags.1?string photo_id:flags.2?long author:flags.3?string published_date:flags.4?int = PageRelatedArticle;\npage#98657f0d flags:# part:flags.0?true rtl:flags.1?true v2:flags.2?true url:string blocks:Vector photos:Vector documents:Vector views:flags.3?int = Page;\nhelp.supportName#8c05f1c9 name:string = help.SupportName;\nhelp.userInfoEmpty#f3ae2eed = help.UserInfo;\nhelp.userInfo#1eb3758 message:string entities:Vector author:string date:int = help.UserInfo;\npollAnswer#6ca9c2e9 text:string option:bytes = PollAnswer;\npoll#86e18161 id:long flags:# closed:flags.0?true public_voters:flags.1?true multiple_choice:flags.2?true quiz:flags.3?true question:string answers:Vector close_period:flags.4?int close_date:flags.5?int = Poll;\npollAnswerVoters#3b6ddad2 flags:# chosen:flags.0?true correct:flags.1?true option:bytes voters:int = PollAnswerVoters;\npollResults#dcb82ea3 flags:# min:flags.0?true results:flags.1?Vector total_voters:flags.2?int recent_voters:flags.3?Vector solution:flags.4?string solution_entities:flags.4?Vector = PollResults;\nchatOnlines#f041e250 onlines:int = ChatOnlines;\nstatsURL#47a971e0 url:string = StatsURL;\nchatAdminRights#5fb224d5 flags:# change_info:flags.0?true post_messages:flags.1?true edit_messages:flags.2?true delete_messages:flags.3?true ban_users:flags.4?true invite_users:flags.5?true pin_messages:flags.7?true add_admins:flags.9?true anonymous:flags.10?true manage_call:flags.11?true other:flags.12?true = ChatAdminRights;\nchatBannedRights#9f120418 flags:# view_messages:flags.0?true send_messages:flags.1?true send_media:flags.2?true send_stickers:flags.3?true send_gifs:flags.4?true send_games:flags.5?true send_inline:flags.6?true embed_links:flags.7?true send_polls:flags.8?true change_info:flags.10?true invite_users:flags.15?true pin_messages:flags.17?true until_date:int = ChatBannedRights;\ninputWallPaper#e630b979 id:long access_hash:long = InputWallPaper;\ninputWallPaperSlug#72091c80 slug:string = InputWallPaper;\ninputWallPaperNoFile#967a462e id:long = InputWallPaper;\naccount.wallPapersNotModified#1c199183 = account.WallPapers;\naccount.wallPapers#cdc3858c hash:long wallpapers:Vector = account.WallPapers;\ncodeSettings#debebe83 flags:# allow_flashcall:flags.0?true current_number:flags.1?true allow_app_hash:flags.4?true = CodeSettings;\nwallPaperSettings#1dc1bca4 flags:# blur:flags.1?true motion:flags.2?true background_color:flags.0?int second_background_color:flags.4?int third_background_color:flags.5?int fourth_background_color:flags.6?int intensity:flags.3?int rotation:flags.4?int = WallPaperSettings;\nautoDownloadSettings#e04232f3 flags:# disabled:flags.0?true video_preload_large:flags.1?true audio_preload_next:flags.2?true phonecalls_less_data:flags.3?true photo_size_max:int video_size_max:int file_size_max:int video_upload_maxbitrate:int = AutoDownloadSettings;\naccount.autoDownloadSettings#63cacf26 low:AutoDownloadSettings medium:AutoDownloadSettings high:AutoDownloadSettings = account.AutoDownloadSettings;\nemojiKeyword#d5b3b9f9 keyword:string emoticons:Vector = EmojiKeyword;\nemojiKeywordDeleted#236df622 keyword:string emoticons:Vector = EmojiKeyword;\nemojiKeywordsDifference#5cc761bd lang_code:string from_version:int version:int keywords:Vector = EmojiKeywordsDifference;\nemojiURL#a575739d url:string = EmojiURL;\nemojiLanguage#b3fb5361 lang_code:string = EmojiLanguage;\nfolder#ff544e65 flags:# autofill_new_broadcasts:flags.0?true autofill_public_groups:flags.1?true autofill_new_correspondents:flags.2?true id:int title:string photo:flags.3?ChatPhoto = Folder;\ninputFolderPeer#fbd2c296 peer:InputPeer folder_id:int = InputFolderPeer;\nfolderPeer#e9baa668 peer:Peer folder_id:int = FolderPeer;\nmessages.searchCounter#e844ebff flags:# inexact:flags.1?true filter:MessagesFilter count:int = messages.SearchCounter;\nurlAuthResultRequest#92d33a0e flags:# request_write_access:flags.0?true bot:User domain:string = UrlAuthResult;\nurlAuthResultAccepted#8f8c0e4e url:string = UrlAuthResult;\nurlAuthResultDefault#a9d6db1f = UrlAuthResult;\nchannelLocationEmpty#bfb5ad8b = ChannelLocation;\nchannelLocation#209b82db geo_point:GeoPoint address:string = ChannelLocation;\npeerLocated#ca461b5d peer:Peer expires:int distance:int = PeerLocated;\npeerSelfLocated#f8ec284b expires:int = PeerLocated;\nrestrictionReason#d072acb4 platform:string reason:string text:string = RestrictionReason;\ninputTheme#3c5693e9 id:long access_hash:long = InputTheme;\ninputThemeSlug#f5890df1 slug:string = InputTheme;\ntheme#e802b8dc 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?ThemeSettings installs_count:flags.4?int = Theme;\naccount.themesNotModified#f41eb622 = account.Themes;\naccount.themes#9a3d8c6d hash:long themes:Vector = account.Themes;\nauth.loginToken#629f1980 expires:int token:bytes = auth.LoginToken;\nauth.loginTokenMigrateTo#68e9916 dc_id:int token:bytes = auth.LoginToken;\nauth.loginTokenSuccess#390d5c5e authorization:auth.Authorization = auth.LoginToken;\naccount.contentSettings#57e28221 flags:# sensitive_enabled:flags.0?true sensitive_can_change:flags.1?true = account.ContentSettings;\nmessages.inactiveChats#a927fec5 dates:Vector chats:Vector users:Vector = messages.InactiveChats;\nbaseThemeClassic#c3a12462 = BaseTheme;\nbaseThemeDay#fbd81688 = BaseTheme;\nbaseThemeNight#b7b31ea8 = BaseTheme;\nbaseThemeTinted#6d5f77ee = BaseTheme;\nbaseThemeArctic#5b11125a = BaseTheme;\ninputThemeSettings#8fde504f flags:# message_colors_animated:flags.2?true base_theme:BaseTheme accent_color:int outbox_accent_color:flags.3?int message_colors:flags.0?Vector wallpaper:flags.1?InputWallPaper wallpaper_settings:flags.1?WallPaperSettings = InputThemeSettings;\nthemeSettings#fa58b6d4 flags:# message_colors_animated:flags.2?true base_theme:BaseTheme accent_color:int outbox_accent_color:flags.3?int message_colors:flags.0?Vector wallpaper:flags.1?WallPaper = ThemeSettings;\nwebPageAttributeTheme#54b56617 flags:# documents:flags.0?Vector settings:flags.1?ThemeSettings = WebPageAttribute;\nmessageUserVote#34d247b4 user_id:long option:bytes date:int = MessageUserVote;\nmessageUserVoteInputOption#3ca5b0ec user_id:long date:int = MessageUserVote;\nmessageUserVoteMultiple#8a65e557 user_id:long options:Vector date:int = MessageUserVote;\nmessages.votesList#823f649 flags:# count:int votes:Vector users:Vector next_offset:flags.0?string = messages.VotesList;\nbankCardOpenUrl#f568028a url:string name:string = BankCardOpenUrl;\npayments.bankCardData#3e24e573 title:string open_urls:Vector = payments.BankCardData;\ndialogFilter#7438f7e8 flags:# contacts:flags.0?true non_contacts:flags.1?true groups:flags.2?true broadcasts:flags.3?true bots:flags.4?true exclude_muted:flags.11?true exclude_read:flags.12?true exclude_archived:flags.13?true id:int title:string emoticon:flags.25?string pinned_peers:Vector include_peers:Vector exclude_peers:Vector = DialogFilter;\ndialogFilterSuggested#77744d4a filter:DialogFilter description:string = DialogFilterSuggested;\nstatsDateRangeDays#b637edaf min_date:int max_date:int = StatsDateRangeDays;\nstatsAbsValueAndPrev#cb43acde current:double previous:double = StatsAbsValueAndPrev;\nstatsPercentValue#cbce2fe0 part:double total:double = StatsPercentValue;\nstatsGraphAsync#4a27eb2d token:string = StatsGraph;\nstatsGraphError#bedc9822 error:string = StatsGraph;\nstatsGraph#8ea464b6 flags:# json:DataJSON zoom_token:flags.0?string = StatsGraph;\nmessageInteractionCounters#ad4fc9bd msg_id:int views:int forwards:int = MessageInteractionCounters;\nstats.broadcastStats#bdf78394 period:StatsDateRangeDays followers:StatsAbsValueAndPrev views_per_post:StatsAbsValueAndPrev shares_per_post:StatsAbsValueAndPrev enabled_notifications:StatsPercentValue growth_graph:StatsGraph followers_graph:StatsGraph mute_graph:StatsGraph top_hours_graph:StatsGraph interactions_graph:StatsGraph iv_interactions_graph:StatsGraph views_by_source_graph:StatsGraph new_followers_by_source_graph:StatsGraph languages_graph:StatsGraph recent_message_interactions:Vector = stats.BroadcastStats;\nhelp.promoDataEmpty#98f6ac75 expires:int = help.PromoData;\nhelp.promoData#8c39793f flags:# proxy:flags.0?true expires:int peer:Peer chats:Vector users:Vector psa_type:flags.1?string psa_message:flags.2?string = help.PromoData;\nvideoSize#de33b094 flags:# type:string w:int h:int size:int video_start_ts:flags.0?double = VideoSize;\nstatsGroupTopPoster#9d04af9b user_id:long messages:int avg_chars:int = StatsGroupTopPoster;\nstatsGroupTopAdmin#d7584c87 user_id:long deleted:int kicked:int banned:int = StatsGroupTopAdmin;\nstatsGroupTopInviter#535f779d user_id:long invitations:int = StatsGroupTopInviter;\nstats.megagroupStats#ef7ff916 period:StatsDateRangeDays members:StatsAbsValueAndPrev messages:StatsAbsValueAndPrev viewers:StatsAbsValueAndPrev posters:StatsAbsValueAndPrev growth_graph:StatsGraph members_graph:StatsGraph new_members_by_source_graph:StatsGraph languages_graph:StatsGraph messages_graph:StatsGraph actions_graph:StatsGraph top_hours_graph:StatsGraph weekdays_graph:StatsGraph top_posters:Vector top_admins:Vector top_inviters:Vector users:Vector = stats.MegagroupStats;\nglobalPrivacySettings#bea2f424 flags:# archive_and_mute_new_noncontact_peers:flags.0?Bool = GlobalPrivacySettings;\nhelp.countryCode#4203c5ef flags:# country_code:string prefixes:flags.0?Vector patterns:flags.1?Vector = help.CountryCode;\nhelp.country#c3878e23 flags:# hidden:flags.0?true iso2:string default_name:string name:flags.1?string country_codes:Vector = help.Country;\nhelp.countriesListNotModified#93cc1f32 = help.CountriesList;\nhelp.countriesList#87d0759e countries:Vector hash:int = help.CountriesList;\nmessageViews#455b853d flags:# views:flags.0?int forwards:flags.1?int replies:flags.2?MessageReplies = MessageViews;\nmessages.messageViews#b6c4f543 views:Vector chats:Vector users:Vector = messages.MessageViews;\nmessages.discussionMessage#a6341782 flags:# messages:Vector max_id:flags.0?int read_inbox_max_id:flags.1?int read_outbox_max_id:flags.2?int unread_count:int chats:Vector users:Vector = messages.DiscussionMessage;\nmessageReplyHeader#a6d57763 flags:# reply_to_msg_id:int reply_to_peer_id:flags.0?Peer reply_to_top_id:flags.1?int = MessageReplyHeader;\nmessageReplies#83d60fc2 flags:# comments:flags.0?true replies:int replies_pts:int recent_repliers:flags.1?Vector channel_id:flags.0?long max_id:flags.2?int read_max_id:flags.3?int = MessageReplies;\npeerBlocked#e8fd8014 peer_id:Peer date:int = PeerBlocked;\nstats.messageStats#8999f295 views_graph:StatsGraph = stats.MessageStats;\ngroupCallDiscarded#7780bcb4 id:long access_hash:long duration:int = GroupCall;\ngroupCall#d597650c flags:# join_muted:flags.1?true can_change_join_muted:flags.2?true join_date_asc:flags.6?true schedule_start_subscribed:flags.8?true can_start_video:flags.9?true record_video_active:flags.11?true id:long access_hash:long participants_count:int title:flags.3?string stream_dc_id:flags.4?int record_start_date:flags.5?int schedule_date:flags.7?int unmuted_video_count:flags.10?int unmuted_video_limit:int version:int = GroupCall;\ninputGroupCall#d8aa840f id:long access_hash:long = InputGroupCall;\ngroupCallParticipant#eba636fe flags:# muted:flags.0?true left:flags.1?true can_self_unmute:flags.2?true just_joined:flags.4?true versioned:flags.5?true min:flags.8?true muted_by_you:flags.9?true volume_by_admin:flags.10?true self:flags.12?true video_joined:flags.15?true peer:Peer date:int active_date:flags.3?int source:int volume:flags.7?int about:flags.11?string raise_hand_rating:flags.13?long video:flags.6?GroupCallParticipantVideo presentation:flags.14?GroupCallParticipantVideo = GroupCallParticipant;\nphone.groupCall#9e727aad call:GroupCall participants:Vector participants_next_offset:string chats:Vector users:Vector = phone.GroupCall;\nphone.groupParticipants#f47751b6 count:int participants:Vector next_offset:string chats:Vector users:Vector version:int = phone.GroupParticipants;\ninlineQueryPeerTypeSameBotPM#3081ed9d = InlineQueryPeerType;\ninlineQueryPeerTypePM#833c0fac = InlineQueryPeerType;\ninlineQueryPeerTypeChat#d766c50a = InlineQueryPeerType;\ninlineQueryPeerTypeMegagroup#5ec4be43 = InlineQueryPeerType;\ninlineQueryPeerTypeBroadcast#6334ee9a = InlineQueryPeerType;\nmessages.historyImport#1662af0b id:long = messages.HistoryImport;\nmessages.historyImportParsed#5e0fb7b9 flags:# pm:flags.0?true group:flags.1?true title:flags.2?string = messages.HistoryImportParsed;\nmessages.affectedFoundMessages#ef8d3e6c pts:int pts_count:int offset:int messages:Vector = messages.AffectedFoundMessages;\nchatInviteImporter#b5cd5f4 user_id:long date:int = ChatInviteImporter;\nmessages.exportedChatInvites#bdc62dcc count:int invites:Vector users:Vector = messages.ExportedChatInvites;\nmessages.exportedChatInvite#1871be50 invite:ExportedChatInvite users:Vector = messages.ExportedChatInvite;\nmessages.exportedChatInviteReplaced#222600ef invite:ExportedChatInvite new_invite:ExportedChatInvite users:Vector = messages.ExportedChatInvite;\nmessages.chatInviteImporters#81b6b00a count:int importers:Vector users:Vector = messages.ChatInviteImporters;\nchatAdminWithInvites#f2ecef23 admin_id:long invites_count:int revoked_invites_count:int = ChatAdminWithInvites;\nmessages.chatAdminsWithInvites#b69b72d7 admins:Vector users:Vector = messages.ChatAdminsWithInvites;\nmessages.checkedHistoryImportPeer#a24de717 confirm_text:string = messages.CheckedHistoryImportPeer;\nphone.joinAsPeers#afe5623f peers:Vector chats:Vector users:Vector = phone.JoinAsPeers;\nphone.exportedGroupCallInvite#204bd158 link:string = phone.ExportedGroupCallInvite;\ngroupCallParticipantVideoSourceGroup#dcb118b7 semantics:string sources:Vector = GroupCallParticipantVideoSourceGroup;\ngroupCallParticipantVideo#67753ac8 flags:# paused:flags.0?true endpoint:string source_groups:Vector audio_source:flags.1?int = GroupCallParticipantVideo;\nstickers.suggestedShortName#85fea03f short_name:string = stickers.SuggestedShortName;\nbotCommandScopeDefault#2f6cb2ab = BotCommandScope;\nbotCommandScopeUsers#3c4f04d8 = BotCommandScope;\nbotCommandScopeChats#6fe1a881 = BotCommandScope;\nbotCommandScopeChatAdmins#b9aa606a = BotCommandScope;\nbotCommandScopePeer#db9d897d peer:InputPeer = BotCommandScope;\nbotCommandScopePeerAdmins#3fd863d1 peer:InputPeer = BotCommandScope;\nbotCommandScopePeerUser#a1321f3 peer:InputPeer user_id:InputUser = BotCommandScope;\naccount.resetPasswordFailedWait#e3779861 retry_date:int = account.ResetPasswordResult;\naccount.resetPasswordRequestedWait#e9effc7d until_date:int = account.ResetPasswordResult;\naccount.resetPasswordOk#e926d63e = account.ResetPasswordResult;\nchatTheme#ed0b5c33 emoticon:string theme:Theme dark_theme:Theme = ChatTheme;\naccount.chatThemesNotModified#e011e1c4 = account.ChatThemes;\naccount.chatThemes#fe4cbebd hash:int themes:Vector = account.ChatThemes;\nsponsoredMessage#2a3c381f flags:# random_id:bytes from_id:Peer start_param:flags.0?string message:string entities:flags.1?Vector = SponsoredMessage;\nmessages.sponsoredMessages#65a4c7d5 messages:Vector chats:Vector users:Vector = messages.SponsoredMessages;\n---functions---\ninitConnection#c1cd5ea9 {X:Type} flags:# api_id:int device_model:string system_version:string app_version:string system_lang_code:string lang_pack:string lang_code:string proxy:flags.0?InputClientProxy params:flags.1?JSONValue query:!X = X;\ninvokeWithLayer#da9b0d0d {X:Type} layer:int query:!X = X;\nauth.sendCode#a677244f phone_number:string api_id:int api_hash:string settings:CodeSettings = auth.SentCode;\nauth.signUp#80eee427 phone_number:string phone_code_hash:string first_name:string last_name:string = auth.Authorization;\nauth.signIn#bcd51581 phone_number:string phone_code_hash:string phone_code:string = auth.Authorization;\nauth.logOut#5717da40 = Bool;\nauth.resetAuthorizations#9fab0d1a = Bool;\nauth.exportAuthorization#e5bfffcd dc_id:int = auth.ExportedAuthorization;\nauth.importAuthorization#a57a7dad id:long bytes:bytes = auth.Authorization;\nauth.bindTempAuthKey#cdd42a05 perm_auth_key_id:long nonce:long expires_at:int encrypted_message:bytes = Bool;\nauth.checkPassword#d18b4d16 password:InputCheckPasswordSRP = auth.Authorization;\nauth.requestPasswordRecovery#d897bc66 = auth.PasswordRecovery;\nauth.resendCode#3ef1a9bf phone_number:string phone_code_hash:string = auth.SentCode;\nauth.cancelCode#1f040578 phone_number:string phone_code_hash:string = Bool;\nauth.dropTempAuthKeys#8e48a188 except_auth_keys:Vector = Bool;\nauth.exportLoginToken#b7e085fe api_id:int api_hash:string except_ids:Vector = auth.LoginToken;\nauth.importLoginToken#95ac5ce4 token:bytes = auth.LoginToken;\naccount.registerDevice#ec86017a flags:# no_muted:flags.0?true token_type:int token:string app_sandbox:Bool secret:bytes other_uids:Vector = Bool;\naccount.unregisterDevice#6a0d3206 token_type:int token:string other_uids:Vector = Bool;\naccount.updateNotifySettings#84be5b93 peer:InputNotifyPeer settings:InputPeerNotifySettings = Bool;\naccount.getNotifySettings#12b3ad31 peer:InputNotifyPeer = PeerNotifySettings;\naccount.updateProfile#78515775 flags:# first_name:flags.0?string last_name:flags.1?string about:flags.2?string = User;\naccount.updateStatus#6628562c offline:Bool = Bool;\naccount.getWallPapers#7967d36 hash:long = account.WallPapers;\naccount.checkUsername#2714d86c username:string = Bool;\naccount.updateUsername#3e0bdd7c username:string = User;\naccount.getPrivacy#dadbc950 key:InputPrivacyKey = account.PrivacyRules;\naccount.setPrivacy#c9f81ce8 key:InputPrivacyKey rules:Vector = account.PrivacyRules;\naccount.getAuthorizations#e320c158 = account.Authorizations;\naccount.resetAuthorization#df77f3bc hash:long = Bool;\naccount.getPassword#548a30f5 = account.Password;\naccount.getPasswordSettings#9cd4eaf9 password:InputCheckPasswordSRP = account.PasswordSettings;\naccount.updatePasswordSettings#a59b102f password:InputCheckPasswordSRP new_settings:account.PasswordInputSettings = Bool;\naccount.sendConfirmPhoneCode#1b3faa88 hash:string settings:CodeSettings = auth.SentCode;\naccount.confirmPhone#5f2178c3 phone_code_hash:string phone_code:string = Bool;\naccount.getTmpPassword#449e0b51 password:InputCheckPasswordSRP period:int = account.TmpPassword;\naccount.sendVerifyPhoneCode#a5a356f9 phone_number:string settings:CodeSettings = auth.SentCode;\naccount.confirmPasswordEmail#8fdf1920 code:string = Bool;\naccount.getContactSignUpNotification#9f07c728 = Bool;\naccount.setContactSignUpNotification#cff43f61 silent:Bool = Bool;\naccount.getNotifyExceptions#53577479 flags:# compare_sound:flags.1?true peer:flags.0?InputNotifyPeer = Updates;\naccount.uploadWallPaper#dd853661 file:InputFile mime_type:string settings:WallPaperSettings = WallPaper;\naccount.setContentSettings#b574b16b flags:# sensitive_enabled:flags.0?true = Bool;\naccount.getContentSettings#8b9b4dae = account.ContentSettings;\nusers.getUsers#d91a548 id:Vector = Vector;\nusers.getFullUser#ca30a5b1 id:InputUser = UserFull;\ncontacts.getContacts#5dd69e12 hash:long = contacts.Contacts;\ncontacts.importContacts#2c800be5 contacts:Vector = contacts.ImportedContacts;\ncontacts.deleteContacts#96a0e00 id:Vector = Updates;\ncontacts.block#68cc1411 id:InputPeer = Bool;\ncontacts.unblock#bea65d50 id:InputPeer = Bool;\ncontacts.getBlocked#f57c350f offset:int limit:int = contacts.Blocked;\ncontacts.search#11f812d8 q:string limit:int = contacts.Found;\ncontacts.resolveUsername#f93ccba3 username:string = contacts.ResolvedPeer;\ncontacts.getTopPeers#973478b6 flags:# correspondents:flags.0?true bots_pm:flags.1?true bots_inline:flags.2?true phone_calls:flags.3?true forward_users:flags.4?true forward_chats:flags.5?true groups:flags.10?true channels:flags.15?true offset:int limit:int hash:long = contacts.TopPeers;\ncontacts.addContact#e8f463d0 flags:# add_phone_privacy_exception:flags.0?true id:InputUser first_name:string last_name:string phone:string = Updates;\nmessages.getMessages#63c66506 id:Vector = messages.Messages;\nmessages.getDialogs#a0f4cb4f flags:# exclude_pinned:flags.0?true folder_id:flags.1?int offset_date:int offset_id:int offset_peer:InputPeer limit:int hash:long = messages.Dialogs;\nmessages.getHistory#4423e6c5 peer:InputPeer offset_id:int offset_date:int add_offset:int limit:int max_id:int min_id:int hash:long = messages.Messages;\nmessages.search#a0fda762 flags:# peer:InputPeer q:string from_id:flags.0?InputPeer top_msg_id:flags.1?int filter:MessagesFilter min_date:int max_date:int offset_id:int add_offset:int limit:int max_id:int min_id:int hash:long = messages.Messages;\nmessages.readHistory#e306d3a peer:InputPeer max_id:int = messages.AffectedMessages;\nmessages.deleteHistory#1c015b09 flags:# just_clear:flags.0?true revoke:flags.1?true peer:InputPeer max_id:int = messages.AffectedHistory;\nmessages.deleteMessages#e58e95d2 flags:# revoke:flags.0?true id:Vector = messages.AffectedMessages;\nmessages.receivedMessages#5a954c0 max_id:int = Vector;\nmessages.setTyping#58943ee2 flags:# peer:InputPeer top_msg_id:flags.0?int action:SendMessageAction = Bool;\nmessages.sendMessage#520c3870 flags:# no_webpage:flags.1?true silent:flags.5?true background:flags.6?true clear_draft:flags.7?true peer:InputPeer reply_to_msg_id:flags.0?int message:string random_id:long reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector schedule_date:flags.10?int = Updates;\nmessages.sendMedia#3491eba9 flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true peer:InputPeer reply_to_msg_id:flags.0?int media:InputMedia message:string random_id:long reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector schedule_date:flags.10?int = Updates;\nmessages.forwardMessages#d9fee60e 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 from_peer:InputPeer id:Vector random_id:Vector to_peer:InputPeer schedule_date:flags.10?int = Updates;\nmessages.report#8953ab4e peer:InputPeer id:Vector reason:ReportReason message:string = Bool;\nmessages.getChats#49e9528f id:Vector = messages.Chats;\nmessages.getFullChat#aeb00b34 chat_id:long = messages.ChatFull;\nmessages.editChatTitle#73783ffd chat_id:long title:string = Updates;\nmessages.editChatPhoto#35ddd674 chat_id:long photo:InputChatPhoto = Updates;\nmessages.addChatUser#f24753e3 chat_id:long user_id:InputUser fwd_limit:int = Updates;\nmessages.deleteChatUser#a2185cab flags:# revoke_history:flags.0?true chat_id:long user_id:InputUser = Updates;\nmessages.createChat#9cb126e users:Vector title:string = Updates;\nmessages.getDhConfig#26cf8950 version:int random_length:int = messages.DhConfig;\nmessages.readMessageContents#36a73f77 id:Vector = messages.AffectedMessages;\nmessages.getStickers#d5a5d3a1 emoticon:string hash:long = messages.Stickers;\nmessages.getAllStickers#b8a0a1a8 hash:long = messages.AllStickers;\nmessages.getWebPagePreview#8b68b0cc flags:# message:string entities:flags.3?Vector = MessageMedia;\nmessages.exportChatInvite#14b9bcd7 flags:# legacy_revoke_permanent:flags.2?true peer:InputPeer expire_date:flags.0?int usage_limit:flags.1?int = ExportedChatInvite;\nmessages.checkChatInvite#3eadb1bb hash:string = ChatInvite;\nmessages.importChatInvite#6c50051c hash:string = Updates;\nmessages.getStickerSet#2619a90e stickerset:InputStickerSet = messages.StickerSet;\nmessages.installStickerSet#c78fe460 stickerset:InputStickerSet archived:Bool = messages.StickerSetInstallResult;\nmessages.uninstallStickerSet#f96e55de stickerset:InputStickerSet = Bool;\nmessages.startBot#e6df7378 bot:InputUser peer:InputPeer random_id:long start_param:string = Updates;\nmessages.migrateChat#a2875319 chat_id:long = Updates;\nmessages.searchGlobal#4bc6589a flags:# folder_id:flags.0?int q:string filter:MessagesFilter min_date:int max_date:int offset_rate:int offset_peer:InputPeer offset_id:int limit:int = messages.Messages;\nmessages.getDocumentByHash#338e2464 sha256:bytes size:int mime_type:string = Document;\nmessages.getSavedGifs#5cf09635 hash:long = messages.SavedGifs;\nmessages.getInlineBotResults#514e999d flags:# bot:InputUser peer:InputPeer geo_point:flags.0?InputGeoPoint query:string offset:string = messages.BotResults;\nmessages.sendInlineBotResult#220815b0 flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true hide_via:flags.11?true peer:InputPeer reply_to_msg_id:flags.0?int random_id:long query_id:long id:string schedule_date:flags.10?int = Updates;\nmessages.editMessage#48f71778 flags:# no_webpage:flags.1?true peer:InputPeer id:int message:flags.11?string media:flags.14?InputMedia reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector schedule_date:flags.15?int = Updates;\nmessages.getBotCallbackAnswer#9342ca07 flags:# game:flags.1?true peer:InputPeer msg_id:int data:flags.0?bytes password:flags.2?InputCheckPasswordSRP = messages.BotCallbackAnswer;\nmessages.getPeerDialogs#e470bcfd peers:Vector = messages.PeerDialogs;\nmessages.saveDraft#bc39e14b flags:# no_webpage:flags.1?true reply_to_msg_id:flags.0?int peer:InputPeer message:string entities:flags.3?Vector = Bool;\nmessages.getFeaturedStickers#64780b14 hash:long = messages.FeaturedStickers;\nmessages.readFeaturedStickers#5b118126 id:Vector = Bool;\nmessages.getRecentStickers#9da9403b flags:# attached:flags.0?true hash:long = messages.RecentStickers;\nmessages.getCommonChats#e40ca104 user_id:InputUser max_id:long limit:int = messages.Chats;\nmessages.getWebPage#32ca8f91 url:string hash:int = WebPage;\nmessages.toggleDialogPin#a731e257 flags:# pinned:flags.0?true peer:InputDialogPeer = Bool;\nmessages.getPinnedDialogs#d6b94df2 folder_id:int = messages.PeerDialogs;\nmessages.uploadMedia#519bc2b1 peer:InputPeer media:InputMedia = MessageMedia;\nmessages.getFavedStickers#4f1aaa9 hash:long = messages.FavedStickers;\nmessages.faveSticker#b9ffc55b id:InputDocument unfave:Bool = Bool;\nmessages.sendMultiMedia#cc0110cb flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true peer:InputPeer reply_to_msg_id:flags.0?int multi_media:Vector schedule_date:flags.10?int = Updates;\nmessages.searchStickerSets#35705b8a flags:# exclude_featured:flags.0?true q:string hash:long = messages.FoundStickerSets;\nmessages.markDialogUnread#c286d98f flags:# unread:flags.0?true peer:InputDialogPeer = Bool;\nmessages.updatePinnedMessage#d2aaf7ec flags:# silent:flags.0?true unpin:flags.1?true pm_oneside:flags.2?true peer:InputPeer id:int = Updates;\nmessages.sendVote#10ea6184 peer:InputPeer msg_id:int options:Vector = Updates;\nmessages.getOnlines#6e2be050 peer:InputPeer = ChatOnlines;\nmessages.editChatAbout#def60797 peer:InputPeer about:string = Bool;\nmessages.editChatDefaultBannedRights#a5866b41 peer:InputPeer banned_rights:ChatBannedRights = Updates;\nmessages.getEmojiKeywordsDifference#1508b6af lang_code:string from_version:int = EmojiKeywordsDifference;\nmessages.getScheduledHistory#f516760b peer:InputPeer hash:long = messages.Messages;\nmessages.sendScheduledMessages#bd38850a peer:InputPeer id:Vector = Updates;\nmessages.deleteScheduledMessages#59ae2b16 peer:InputPeer id:Vector = Updates;\nmessages.getPollVotes#b86e380e flags:# peer:InputPeer id:int option:flags.0?bytes offset:flags.1?string limit:int = messages.VotesList;\nmessages.getDialogFilters#f19ed96d = Vector;\nmessages.getSuggestedDialogFilters#a29cd42c = Vector;\nmessages.updateDialogFilter#1ad4a04a flags:# id:int filter:flags.0?DialogFilter = Bool;\nmessages.getReplies#22ddd30c peer:InputPeer msg_id:int offset_id:int offset_date:int add_offset:int limit:int max_id:int min_id:int hash:long = messages.Messages;\nmessages.getDiscussionMessage#446972fd peer:InputPeer msg_id:int = messages.DiscussionMessage;\nmessages.readDiscussion#f731a9f4 peer:InputPeer msg_id:int read_max_id:int = Bool;\nmessages.unpinAllMessages#f025bc8b peer:InputPeer = messages.AffectedHistory;\nmessages.deleteChat#5bd0ee50 chat_id:long = Bool;\nupdates.getState#edd4882a = updates.State;\nupdates.getDifference#25939651 flags:# pts:int pts_total_limit:flags.0?int date:int qts:int = updates.Difference;\nupdates.getChannelDifference#3173d78 flags:# force:flags.0?true channel:InputChannel filter:ChannelMessagesFilter pts:int limit:int = updates.ChannelDifference;\nphotos.uploadProfilePhoto#89f30f69 flags:# file:flags.0?InputFile video:flags.1?InputFile video_start_ts:flags.2?double = photos.Photo;\nphotos.getUserPhotos#91cd32a8 user_id:InputUser offset:int max_id:long limit:int = photos.Photos;\nupload.saveFilePart#b304a621 file_id:long file_part:int bytes:bytes = Bool;\nupload.getFile#b15a9afc flags:# precise:flags.0?true cdn_supported:flags.1?true location:InputFileLocation offset:int limit:int = upload.File;\nupload.saveBigFilePart#de7b673d file_id:long file_part:int file_total_parts:int bytes:bytes = Bool;\nupload.getWebFile#24e6818d location:InputWebFileLocation offset:int limit:int = upload.WebFile;\nhelp.getConfig#c4f9186b = Config;\nhelp.getNearestDc#1fb33026 = NearestDc;\nhelp.getSupport#9cdf08cd = help.Support;\nhelp.acceptTermsOfService#ee72f79a id:DataJSON = Bool;\nhelp.getCountriesList#735787a8 lang_code:string hash:int = help.CountriesList;\nchannels.readHistory#cc104937 channel:InputChannel max_id:int = Bool;\nchannels.deleteMessages#84c1fd4e channel:InputChannel id:Vector = messages.AffectedMessages;\nchannels.getMessages#ad8c9a23 channel:InputChannel id:Vector = messages.Messages;\nchannels.getParticipants#77ced9d0 channel:InputChannel filter:ChannelParticipantsFilter offset:int limit:int hash:long = channels.ChannelParticipants;\nchannels.getParticipant#a0ab6cc6 channel:InputChannel participant:InputPeer = channels.ChannelParticipant;\nchannels.getChannels#a7f6bbb id:Vector = messages.Chats;\nchannels.getFullChannel#8736a09 channel:InputChannel = messages.ChatFull;\nchannels.createChannel#3d5fb10f flags:# broadcast:flags.0?true megagroup:flags.1?true for_import:flags.3?true title:string about:string geo_point:flags.2?InputGeoPoint address:flags.2?string = Updates;\nchannels.editAdmin#d33c8902 channel:InputChannel user_id:InputUser admin_rights:ChatAdminRights rank:string = Updates;\nchannels.editTitle#566decd0 channel:InputChannel title:string = Updates;\nchannels.editPhoto#f12e57c9 channel:InputChannel photo:InputChatPhoto = Updates;\nchannels.checkUsername#10e6bd2c channel:InputChannel username:string = Bool;\nchannels.updateUsername#3514b3de channel:InputChannel username:string = Bool;\nchannels.joinChannel#24b524c5 channel:InputChannel = Updates;\nchannels.leaveChannel#f836aa95 channel:InputChannel = Updates;\nchannels.inviteToChannel#199f3a6c channel:InputChannel users:Vector = Updates;\nchannels.deleteChannel#c0111fe3 channel:InputChannel = Updates;\nchannels.toggleSignatures#1f69b606 channel:InputChannel enabled:Bool = Updates;\nchannels.editBanned#96e6cd81 channel:InputChannel participant:InputPeer banned_rights:ChatBannedRights = Updates;\nchannels.readMessageContents#eab5dc38 channel:InputChannel id:Vector = Bool;\nchannels.togglePreHistoryHidden#eabbb94c channel:InputChannel enabled:Bool = Updates;\nchannels.getGroupsForDiscussion#f5dad378 = messages.Chats;\nchannels.setDiscussionGroup#40582bb2 broadcast:InputChannel group:InputChannel = Bool;\npayments.getPaymentForm#8a333c8d flags:# peer:InputPeer msg_id:int theme_params:flags.0?DataJSON = payments.PaymentForm;\npayments.getPaymentReceipt#2478d1cc peer:InputPeer msg_id:int = payments.PaymentReceipt;\npayments.validateRequestedInfo#db103170 flags:# save:flags.0?true peer:InputPeer msg_id:int info:PaymentRequestedInfo = payments.ValidatedRequestedInfo;\npayments.sendPaymentForm#30c3bc9d flags:# form_id:long peer:InputPeer msg_id:int requested_info_id:flags.0?string shipping_option_id:flags.1?string credentials:InputPaymentCredentials tip_amount:flags.2?long = payments.PaymentResult;\npayments.getSavedInfo#227d824b = payments.SavedInfo;\nlangpack.getLangPack#f2f2330a lang_pack:string lang_code:string = LangPackDifference;\nlangpack.getStrings#efea3803 lang_pack:string lang_code:string keys:Vector = Vector;\nlangpack.getLanguages#42c6978f lang_pack:string = Vector;\nfolders.editPeerFolders#6847d0ab folder_peers:Vector = Updates;\n`;","const { inflate } = require('pako/dist/pako_inflate');\nconst { serializeBytes } = require('../index');\n\n// CONTEST const { deflate } = require('pako/dist/pako_deflate')\n\nclass GZIPPacked {\n static CONSTRUCTOR_ID = 0x3072cfa1;\n\n static classType = 'constructor';\n\n constructor(data) {\n this.data = data;\n this.CONSTRUCTOR_ID = 0x3072cfa1;\n this.classType = 'constructor';\n }\n\n static async gzipIfSmaller(contentRelated, data) {\n if (contentRelated && data.length > 512) {\n const gzipped = await (new GZIPPacked(data)).toBytes();\n if (gzipped.length < data.length) {\n return gzipped;\n }\n }\n return data;\n }\n\n static gzip(input) {\n return Buffer.from(input);\n // TODO this usually makes it faster for large requests\n // return Buffer.from(deflate(input, { level: 9, gzip: true }))\n }\n\n static ungzip(input) {\n return Buffer.from(inflate(input));\n }\n\n static read(reader) {\n const constructor = reader.readInt(false);\n if (constructor !== GZIPPacked.CONSTRUCTOR_ID) {\n throw new Error('not equal');\n }\n return GZIPPacked.gzip(reader.tgReadBytes());\n }\n\n static async fromReader(reader) {\n return new GZIPPacked(await GZIPPacked.ungzip(reader.tgReadBytes()));\n }\n\n async toBytes() {\n const g = Buffer.alloc(4);\n g.writeUInt32LE(GZIPPacked.CONSTRUCTOR_ID, 0);\n return Buffer.concat([\n g,\n serializeBytes(await GZIPPacked.gzip(this.data)),\n ]);\n }\n}\n\nmodule.exports = GZIPPacked;\n","const TLMessage = require('./TLMessage');\n\nclass MessageContainer {\n static CONSTRUCTOR_ID = 0x73f1f8dc;\n\n static classType = 'constructor';\n\n // Maximum size in bytes for the inner payload of the container.\n // Telegram will close the connection if the payload is bigger.\n // The overhead of the container itself is subtracted.\n static MAXIMUM_SIZE = 1044456 - 8;\n\n // Maximum amount of messages that can't be sent inside a single\n // container, inclusive. Beyond this limit Telegram will respond\n // with BAD_MESSAGE 64 (invalid container).\n //\n // This limit is not 100% accurate and may in some cases be higher.\n // However, sending up to 100 requests at once in a single container\n // is a reasonable conservative value, since it could also depend on\n // other factors like size per request, but we cannot know this.\n static MAXIMUM_LENGTH = 100;\n\n constructor(messages) {\n this.CONSTRUCTOR_ID = 0x73f1f8dc;\n this.messages = messages;\n this.classType = 'constructor';\n }\n\n static fromReader(reader) {\n const messages = [];\n const length = reader.readInt();\n for (let x = 0; x < length; x++) {\n const msgId = reader.readLong();\n const seqNo = reader.readInt();\n const containerLength = reader.readInt();\n const before = reader.tellPosition();\n const obj = reader.tgReadObject();\n reader.setPosition(before + containerLength);\n const tlMessage = new TLMessage(msgId, seqNo, obj);\n messages.push(tlMessage);\n }\n return new MessageContainer(messages);\n }\n}\n\nmodule.exports = MessageContainer;\n","const { RpcError } = require('../index').constructors;\nconst GZIPPacked = require('./GZIPPacked');\n\nclass RPCResult {\n static CONSTRUCTOR_ID = 0xf35c6d01;\n\n static classType = 'constructor';\n\n constructor(reqMsgId, body, error) {\n this.CONSTRUCTOR_ID = 0xf35c6d01;\n this.reqMsgId = reqMsgId;\n this.body = body;\n this.error = error;\n this.classType = 'constructor';\n }\n\n static async fromReader(reader) {\n const msgId = reader.readLong();\n const innerCode = reader.readInt(false);\n if (innerCode === RpcError.CONSTRUCTOR_ID) {\n return new RPCResult(msgId, undefined, RpcError.fromReader(reader));\n }\n if (innerCode === GZIPPacked.CONSTRUCTOR_ID) {\n return new RPCResult(msgId, (await GZIPPacked.fromReader(reader)).data);\n }\n reader.seek(-4);\n // This reader.read() will read more than necessary, but it's okay.\n // We could make use of MessageContainer's length here, but since\n // it's not necessary we don't need to care about it.\n return new RPCResult(msgId, reader.read(), undefined);\n }\n}\n\nmodule.exports = RPCResult;\n","class TLMessage {\n static SIZE_OVERHEAD = 12;\n\n static classType = 'constructor';\n\n constructor(msgId, seqNo, obj) {\n this.msgId = msgId;\n this.seqNo = seqNo;\n this.obj = obj;\n this.classType = 'constructor';\n }\n}\n\nmodule.exports = TLMessage;\n","const TLMessage = require('./TLMessage');\nconst RPCResult = require('./RPCResult');\nconst MessageContainer = require('./MessageContainer');\nconst GZIPPacked = require('./GZIPPacked');\n\nconst coreObjects = {\n [RPCResult.CONSTRUCTOR_ID]: RPCResult,\n [GZIPPacked.CONSTRUCTOR_ID]: GZIPPacked,\n [MessageContainer.CONSTRUCTOR_ID]: MessageContainer,\n};\n\nmodule.exports = {\n TLMessage,\n RPCResult,\n MessageContainer,\n GZIPPacked,\n coreObjects,\n};\n","const snakeToCamelCase = (name) => {\n const result = name.replace(/(?:^|_)([a-z])/g, (_, g) => g.toUpperCase());\n return result.replace(/_/g, '');\n};\nconst variableSnakeToCamelCase = (str) => str.replace(\n /([-_][a-z])/g,\n (group) => group.toUpperCase()\n .replace('-', '')\n .replace('_', ''),\n);\n\nconst CORE_TYPES = new Set([\n 0xbc799737, // boolFalse#bc799737 = Bool;\n 0x997275b5, // boolTrue#997275b5 = Bool;\n 0x3fedd339, // true#3fedd339 = True;\n 0xc4b9f9bb, // error#c4b9f9bb code:int text:string = Error;\n 0x56730bcc, // null#56730bcc = Null;\n]);\nconst AUTH_KEY_TYPES = new Set([\n 0x05162463, // resPQ,\n 0x83c95aec, // p_q_inner_data\n 0xa9f55f95, // p_q_inner_data_dc\n 0x3c6a84d4, // p_q_inner_data_temp\n 0x56fddf88, // p_q_inner_data_temp_dc\n 0xd0e8075c, // server_DH_params_ok\n 0xb5890dba, // server_DH_inner_data\n 0x6643b654, // client_DH_inner_data\n 0xd712e4be, // req_DH_params\n 0xf5045f1f, // set_client_DH_params\n 0x3072cfa1, // gzip_packed\n]);\n\n// This is copy-pasted from `gramjs/Helpers.js` to not depend on TypeScript modules\nfunction makeCRCTable() {\n let c;\n const crcTable = [];\n for (let n = 0; n < 256; n++) {\n c = n;\n for (let k = 0; k < 8; k++) {\n c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));\n }\n crcTable[n] = c;\n }\n return crcTable;\n}\n\nlet crcTable;\n\nfunction crc32(buf) {\n if (!crcTable) {\n crcTable = makeCRCTable();\n }\n if (!Buffer.isBuffer(buf)) {\n buf = Buffer.from(buf);\n }\n let crc = -1;\n\n for (let index = 0; index < buf.length; index++) {\n const byte = buf[index];\n crc = crcTable[(crc ^ byte) & 0xff] ^ (crc >>> 8);\n }\n return (crc ^ (-1)) >>> 0;\n}\n\nconst findAll = (regex, str, matches = []) => {\n if (!regex.flags.includes('g')) {\n regex = new RegExp(regex.source, 'g');\n }\n\n const res = regex.exec(str);\n\n if (res) {\n matches.push(res.slice(1));\n findAll(regex, str, matches);\n }\n\n return matches;\n};\n\nconst fromLine = (line, isFunction) => {\n const match = line.match(/([\\w.]+)(?:#([0-9a-fA-F]+))?(?:\\s{?\\w+:[\\w\\d<>#.?!]+}?)*\\s=\\s([\\w\\d<>#.?]+);$/);\n if (!match) {\n // Probably \"vector#1cb5c415 {t:Type} # [ t ] = Vector t;\"\n throw new Error(`Cannot parse TLObject ${line}`);\n }\n\n const argsMatch = findAll(/({)?(\\w+):([\\w\\d<>#.?!]+)}?/, line);\n const currentConfig = {\n name: match[1],\n constructorId: parseInt(match[2], 16),\n argsConfig: {},\n subclassOfId: crc32(match[3]),\n result: match[3],\n isFunction,\n namespace: undefined,\n };\n if (!currentConfig.constructorId) {\n const hexId = '';\n let args;\n\n if (Object.values(currentConfig.argsConfig).length) {\n args = ` ${Object.keys(currentConfig.argsConfig)\n .map((arg) => arg.toString())\n .join(' ')}`;\n } else {\n args = '';\n }\n\n const representation = `${currentConfig.name}${hexId}${args} = ${currentConfig.result}`\n .replace(/(:|\\?)bytes /g, '$1string ')\n .replace(/|{|}/g, '')\n .replace(/ \\w+:flags\\.\\d+\\?true/g, '');\n\n if (currentConfig.name === 'inputMediaInvoice') {\n // eslint-disable-next-line no-empty\n if (currentConfig.name === 'inputMediaInvoice') {\n }\n }\n\n currentConfig.constructorId = crc32(Buffer.from(representation, 'utf8'));\n }\n for (const [brace, name, argType] of argsMatch) {\n if (brace === undefined) {\n currentConfig.argsConfig[variableSnakeToCamelCase(name)] = buildArgConfig(name, argType);\n }\n }\n if (currentConfig.name.includes('.')) {\n [currentConfig.namespace, currentConfig.name] = currentConfig.name.split(/\\.(.+)/);\n }\n currentConfig.name = snakeToCamelCase(currentConfig.name);\n /*\n for (const arg in currentConfig.argsConfig){\n if (currentConfig.argsConfig.hasOwnProperty(arg)){\n if (currentConfig.argsConfig[arg].flagIndicator){\n delete currentConfig.argsConfig[arg]\n }\n }\n } */\n return currentConfig;\n};\n\nfunction buildArgConfig(name, argType) {\n name = name === 'self' ? 'is_self' : name;\n // Default values\n const currentConfig = {\n isVector: false,\n isFlag: false,\n skipConstructorId: false,\n flagIndex: -1,\n flagIndicator: true,\n type: undefined,\n useVectorId: undefined,\n };\n\n // The type can be an indicator that other arguments will be flags\n if (argType !== '#') {\n currentConfig.flagIndicator = false;\n // Strip the exclamation mark always to have only the name\n currentConfig.type = argType.replace(/^!+/, '');\n\n // The type may be a flag (flags.IDX?REAL_TYPE)\n // Note that 'flags' is NOT the flags name; this\n // is determined by a previous argument\n // However, we assume that the argument will always be called 'flags'\n // @ts-ignore\n const flagMatch = currentConfig.type.match(/flags.(\\d+)\\?([\\w<>.]+)/);\n\n if (flagMatch) {\n currentConfig.isFlag = true;\n currentConfig.flagIndex = Number(flagMatch[1]);\n // Update the type to match the exact type, not the \"flagged\" one\n [, , currentConfig.type] = flagMatch;\n }\n\n // Then check if the type is a Vector\n // @ts-ignore\n const vectorMatch = currentConfig.type.match(/[Vv]ector<([\\w\\d.]+)>/);\n\n if (vectorMatch) {\n currentConfig.isVector = true;\n\n // If the type's first letter is not uppercase, then\n // it is a constructor and we use (read/write) its ID.\n // @ts-ignore\n currentConfig.useVectorId = currentConfig.type.charAt(0) === 'V';\n\n // Update the type to match the one inside the vector\n [, currentConfig.type] = vectorMatch;\n }\n\n // See use_vector_id. An example of such case is ipPort in\n // help.configSpecial\n // @ts-ignore\n if (/^[a-z]$/.test(currentConfig.type.split('.')\n .pop()\n .charAt(0))\n ) {\n currentConfig.skipConstructorId = true;\n }\n\n // The name may contain \"date\" in it, if this is the case and\n // the type is \"int\", we can safely assume that this should be\n // treated as a \"date\" object. Note that this is not a valid\n // Telegram object, but it's easier to work with\n // if (\n // this.type === 'int' &&\n // (/(\\b|_)([dr]ate|until|since)(\\b|_)/.test(name) ||\n // ['expires', 'expires_at', 'was_online'].includes(name))\n // ) {\n // this.type = 'date';\n // }\n }\n return currentConfig;\n}\n\n\nfunction* parseTl(content, layer, methods = [], ignoreIds = CORE_TYPES) {\n (methods || []).reduce((o, m) => ({\n ...o,\n [m.name]: m,\n }), {});\n const objAll = [];\n const objByName = {};\n const objByType = {};\n\n const file = content;\n\n let isFunction = false;\n\n for (let line of file.split('\\n')) {\n const commentIndex = line.indexOf('//');\n\n if (commentIndex !== -1) {\n line = line.slice(0, commentIndex);\n }\n\n line = line.trim();\n\n if (!line) {\n continue;\n }\n\n const match = line.match(/---(\\w+)---/);\n\n if (match) {\n const [, followingTypes] = match;\n isFunction = followingTypes === 'functions';\n continue;\n }\n\n try {\n const result = fromLine(line, isFunction);\n\n if (ignoreIds.has(result.constructorId)) {\n continue;\n }\n\n objAll.push(result);\n\n if (!result.isFunction) {\n if (!objByType[result.result]) {\n objByType[result.result] = [];\n }\n\n objByName[result.name] = result;\n objByType[result.result].push(result);\n }\n } catch (e) {\n if (!e.toString()\n .includes('vector#1cb5c415')) {\n throw e;\n }\n }\n }\n\n // Once all objects have been parsed, replace the\n // string type from the arguments with references\n for (const obj of objAll) {\n // console.log(obj)\n if (AUTH_KEY_TYPES.has(obj.constructorId)) {\n for (const arg in obj.argsConfig) {\n if (obj.argsConfig[arg].type === 'string') {\n obj.argsConfig[arg].type = 'bytes';\n }\n }\n }\n }\n\n for (const obj of objAll) {\n yield obj;\n }\n}\n\nfunction serializeBytes(data) {\n if (!(data instanceof Buffer)) {\n if (typeof data === 'string') {\n data = Buffer.from(data);\n } else {\n throw Error(`Bytes or str expected, not ${data.constructor.name}`);\n }\n }\n const r = [];\n let padding;\n if (data.length < 254) {\n padding = (data.length + 1) % 4;\n if (padding !== 0) {\n padding = 4 - padding;\n }\n r.push(Buffer.from([data.length]));\n r.push(data);\n } else {\n padding = data.length % 4;\n if (padding !== 0) {\n padding = 4 - padding;\n }\n r.push(Buffer.from([254, data.length % 256, (data.length >> 8) % 256, (data.length >> 16) % 256]));\n r.push(data);\n }\n r.push(Buffer.alloc(padding)\n .fill(0));\n\n return Buffer.concat(r);\n}\n\nfunction serializeDate(dt) {\n if (!dt) {\n return Buffer.alloc(4)\n .fill(0);\n }\n if (dt instanceof Date) {\n dt = Math.floor((Date.now() - dt.getTime()) / 1000);\n }\n if (typeof dt === 'number') {\n const t = Buffer.alloc(4);\n t.writeInt32LE(dt, 0);\n return t;\n }\n throw Error(`Cannot interpret \"${dt}\" as a date`);\n}\n\nmodule.exports = {\n findAll,\n parseTl,\n buildArgConfig,\n fromLine,\n CORE_TYPES,\n serializeDate,\n serializeBytes,\n snakeToCamelCase,\n variableSnakeToCamelCase,\n};\n","const api = require('./api');\nconst {\n serializeBytes,\n serializeDate,\n} = require('./generationHelpers');\n\nmodule.exports = {\n // TODO Refactor internal usages to always use `api`.\n constructors: api,\n requests: api,\n serializeBytes,\n serializeDate,\n};\n","module.exports = `resPQ#05162463 nonce:int128 server_nonce:int128 pq:string server_public_key_fingerprints:Vector = ResPQ;\np_q_inner_data#83c95aec pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 = P_Q_inner_data;\nserver_DH_params_fail#79cb045d nonce:int128 server_nonce:int128 new_nonce_hash:int128 = Server_DH_Params;\nserver_DH_params_ok#d0e8075c nonce:int128 server_nonce:int128 encrypted_answer:string = Server_DH_Params;\nserver_DH_inner_data#b5890dba nonce:int128 server_nonce:int128 g:int dh_prime:string g_a:string server_time:int = Server_DH_inner_data;\nclient_DH_inner_data#6643b654 nonce:int128 server_nonce:int128 retry_id:long g_b:string = Client_DH_Inner_Data;\ndh_gen_ok#3bcbf734 nonce:int128 server_nonce:int128 new_nonce_hash1:int128 = Set_client_DH_params_answer;\ndh_gen_retry#46dc1fb9 nonce:int128 server_nonce:int128 new_nonce_hash2:int128 = Set_client_DH_params_answer;\ndh_gen_fail#a69dae02 nonce:int128 server_nonce:int128 new_nonce_hash3:int128 = Set_client_DH_params_answer;\ndestroy_auth_key_ok#f660e1d4 = DestroyAuthKeyRes;\ndestroy_auth_key_none#0a9f2259 = DestroyAuthKeyRes;\ndestroy_auth_key_fail#ea109b13 = DestroyAuthKeyRes;\n---functions---\nreq_pq#60469778 nonce:int128 = ResPQ;\nreq_pq_multi#be7e8ef1 nonce:int128 = ResPQ;\nreq_pq_multi_new#51b410fd nonce:int128 = ResPQ;\nreq_DH_params#d712e4be nonce:int128 server_nonce:int128 p:string q:string public_key_fingerprint:long encrypted_data:string = Server_DH_Params;\nset_client_DH_params#f5045f1f nonce:int128 server_nonce:int128 encrypted_data:string = Set_client_DH_params_answer;\ndestroy_auth_key#d1435160 = DestroyAuthKeyRes;\n---types---\nmsgs_ack#62d6b459 msg_ids:Vector = MsgsAck;\nbad_msg_notification#a7eff811 bad_msg_id:long bad_msg_seqno:int error_code:int = BadMsgNotification;\nbad_server_salt#edab447b bad_msg_id:long bad_msg_seqno:int error_code:int new_server_salt:long = BadMsgNotification;\nmsgs_state_req#da69fb52 msg_ids:Vector = MsgsStateReq;\nmsgs_state_info#04deb57d req_msg_id:long info:string = MsgsStateInfo;\nmsgs_all_info#8cc0d131 msg_ids:Vector info:string = MsgsAllInfo;\nmsg_detailed_info#276d3ec6 msg_id:long answer_msg_id:long bytes:int status:int = MsgDetailedInfo;\nmsg_new_detailed_info#809db6df answer_msg_id:long bytes:int status:int = MsgDetailedInfo;\nmsg_resend_req#7d861a08 msg_ids:Vector = MsgResendReq;\nrpc_error#2144ca19 error_code:int error_message:string = RpcError;\nfuture_salt#0949d9dc valid_since:int valid_until:int salt:long = FutureSalt;\nfuture_salts#ae500895 req_msg_id:long now:int salts:vector = FutureSalts;\npong#347773c5 msg_id:long ping_id:long = Pong;\ndestroy_session_ok#e22045fc session_id:long = DestroySessionRes;\ndestroy_session_none#62d350c9 session_id:long = DestroySessionRes;\nnew_session_created#9ec20908 first_msg_id:long unique_id:long server_salt:long = NewSession;\n---functions---\nping#7abe77ec ping_id:long = Pong;\nping_delay_disconnect#f3427b8c ping_id:long disconnect_delay:int = Pong;`;","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\tid: moduleId,\n\t\tloaded: false,\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Flag the module as loaded\n\tmodule.loaded = true;\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n// expose the modules object (__webpack_modules__)\n__webpack_require__.m = __webpack_modules__;\n\n// the startup function\n__webpack_require__.x = () => {\n\t// Load entry module and return exports\n\t// This entry module depends on other loaded chunks and execution need to be delayed\n\tvar __webpack_exports__ = __webpack_require__.O(undefined, [592], () => (__webpack_require__(6514)))\n\t__webpack_exports__ = __webpack_require__.O(__webpack_exports__);\n\treturn __webpack_exports__;\n};\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.f = {};\n// This file contains only the entry chunk.\n// The chunk loading function for additional chunks\n__webpack_require__.e = (chunkId) => {\n\treturn Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => {\n\t\t__webpack_require__.f[key](chunkId, promises);\n\t\treturn promises;\n\t}, []));\n};","// This function allow to reference async chunks and sibling chunks for the entrypoint\n__webpack_require__.u = (chunkId) => {\n\t// return url for filenames based on template\n\treturn \"\" + chunkId + \".\" + \"d7ca037ed9b7d1c6792a\" + \".js\";\n};","// This function allow to reference all chunks\n__webpack_require__.miniCssF = (chunkId) => {\n\t// return url for filenames based on template\n\treturn undefined;\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","__webpack_require__.nmd = (module) => {\n\tmodule.paths = [];\n\tif (!module.children) module.children = [];\n\treturn module;\n};","var scriptUrl;\nif (__webpack_require__.g.importScripts) scriptUrl = __webpack_require__.g.location + \"\";\nvar document = __webpack_require__.g.document;\nif (!scriptUrl && document) {\n\tif (document.currentScript)\n\t\tscriptUrl = document.currentScript.src\n\tif (!scriptUrl) {\n\t\tvar scripts = document.getElementsByTagName(\"script\");\n\t\tif(scripts.length) scriptUrl = scripts[scripts.length - 1].src\n\t}\n}\n// When supporting browsers where an automatic publicPath is not supported you must specify an output.publicPath manually via configuration\n// or pass an empty string (\"\") and set the __webpack_public_path__ variable from your code to use your own logic.\nif (!scriptUrl) throw new Error(\"Automatic publicPath is not supported in this browser\");\nscriptUrl = scriptUrl.replace(/#.*$/, \"\").replace(/\\?.*$/, \"\").replace(/\\/[^\\/]+$/, \"/\");\n__webpack_require__.p = scriptUrl;","// no baseURI\n\n// object to store loaded chunks\n// \"1\" means \"already loaded\"\nvar installedChunks = {\n\t514: 1\n};\n\n// importScripts chunk loading\nvar installChunk = (data) => {\n\tvar [chunkIds, moreModules, runtime] = data;\n\tfor(var moduleId in moreModules) {\n\t\tif(__webpack_require__.o(moreModules, moduleId)) {\n\t\t\t__webpack_require__.m[moduleId] = moreModules[moduleId];\n\t\t}\n\t}\n\tif(runtime) runtime(__webpack_require__);\n\twhile(chunkIds.length)\n\t\tinstalledChunks[chunkIds.pop()] = 1;\n\tparentChunkLoadingFunction(data);\n};\n__webpack_require__.f.i = (chunkId, promises) => {\n\t// \"1\" is the signal for \"already loaded\"\n\tif(!installedChunks[chunkId]) {\n\t\tif(true) { // all chunks have JS\n\t\t\timportScripts(__webpack_require__.p + __webpack_require__.u(chunkId));\n\t\t}\n\t}\n};\n\nvar chunkLoadingGlobal = self[\"webpackChunktelegram_t\"] = self[\"webpackChunktelegram_t\"] || [];\nvar parentChunkLoadingFunction = chunkLoadingGlobal.push.bind(chunkLoadingGlobal);\nchunkLoadingGlobal.push = installChunk;\n\n// no HMR\n\n// no HMR manifest","// run startup\nvar __webpack_exports__ = __webpack_require__.x();\n"],"names":["deferred","next","API_UPDATE_THROTTLE","window","innerHeight","Math","round","API_THROTTLE_RESET_UPDATES","Set","SUPPORTED_IMAGE_CONTENT_TYPES","SUPPORTED_VIDEO_CONTENT_TYPES","SERVICE_NOTIFICATIONS_USER_ID","onTickEndCallbacks","onTickEndPrimaryCallbacks","buildCollectionByKey","collection","key","reduce","byKey","member","pick","object","keys","result","bytesToDataUri","bytes","shouldOmitPrefix","mimeType","btoa","String","fromCharCode","omitVirtualClassFields","instance","flags","CONSTRUCTOR_ID","SUBCLASS_OF_ID","className","classType","getBytes","rest","pathBytesToSvg","width","height","replace","path","len","length","i","num","buildPath","DEFAULT_THUMB_SIZE","w","h","buildApiThumbnailFromStripped","sizes","thumb","find","s","GramJs","realSizes","filter","dataUri","strippedPhotoToJpg","undefined","buildApiPhoto","photo","map","buildApiPhotoSize","id","thumbnail","photoSize","type","localMessages","chats","users","messages","documents","stickerSets","photos","webDocuments","ANIMATED_STICKER_MIME_TYPE","buildStickerFromDocument","document","stickerAttribute","attributes","attr","fileAttribute","sizeAttribute","stickerSetInfo","stickerset","emoji","alt","isAnimated","cachedThumb","thumbs","pathThumb","buildApiThumbnailFromCached","buildApiThumbnailFromPath","stickerSetId","stickerSetAccessHash","accessHash","buildStickerSet","set","archived","animated","installedDate","title","count","shortName","hasThumbnail","Boolean","buildStickerSetCovered","coveredStickerSet","stickerSet","stickerSetCovers","covers","cover","forEach","coverSticker","push","localDb","interpolateArray","data","fitCount","peak","newData","Array","springFactor","leftFiller","rightFiller","idx","floor","val","ApiMessageEntityTypes","ApiMediaFormat","getEntityTypeById","chatOrUserId","getEntityTypeByDeprecatedId","startsWith","buildPeer","userId","buildMtpPeerId","channelId","chatId","buildInputPeer","BigInt","buildInputPeerFromLocalDb","buildInputEntity","buildInputStickerSet","buildInputDocument","media","buildInputMediaDocument","inputDocument","generateRandomBigInt","readBigIntFromBuffer","generateRandomBytes","buildMessageFromUpdate","update","peerId","fromId","buildMtpMessageEntity","entity","offset","url","user","Bold","Italic","Underline","Strike","Code","Pre","language","Blockquote","TextUrl","Url","Hashtag","MentionName","isMessageWithMedia","message","webpage","buildInputContact","phone","firstName","lastName","clientId","buildChatBannedRights","bannedRights","untilDate","buildChatAdminRights","adminRights","buildShippingInfo","info","shippingAddress","buildInputPrivacyKey","privacyKey","buildInputReportReason","reason","abs","slice","isPeerUser","peer","hasOwnProperty","isPeerChat","buildApiPeerId","getApiChatIdFromMtpPeer","resolveMessageApiChatId","mtpMessage","addMessageToLocalDb","messageFullId","action","addPhotoToLocalDb","addChatToLocalDb","chat","LOCAL_MEDIA_UPLOADING_TEMP_ID","currentUserId","localMessageCounter","buildApiMessage","buildApiMessageWithChatId","isChatWithSelf","isOutgoing","out","post","fwdFrom","content","buildMessageMediaContent","sticker","poll","contact","text","buildMessageTextContent","entities","senderId","targetPeerId","isChannelPost","amount","currency","translationValues","targetUserIds","targetChatId","includes","withDuration","duration","video","join","mins","max","Number","totalAmount","domain","buildAction","replyToMsgId","replyToTopId","replyToPeerId","replyTo","isEdited","editDate","editHide","inlineButtons","keyboardButtons","keyboardPlaceholder","isKeyboardSingleUse","messageId","replyMarkup","value","markup","rows","buttons","button","receiptMsgId","placeholder","singleUse","buildReplyButtons","forwardInfo","savedFromPeerId","savedFromPeer","channelPost","channelPostId","isLinkedChannelPost","fromChatId","fromMessageId","savedFromMsgId","senderUserId","hiddenUserName","fromName","adminTitle","postAuthor","buildApiMessageForwardInfo","replies","mediaUnread","isMediaUnread","groupedId","isInAlbum","audio","shouldHideKeyboardButtons","date","views","isFromScheduled","fromScheduled","replyToMessageId","replyToChatId","replyToTopMessageId","mentioned","hasUnreadMention","isMentioned","viaBotId","comments","threadInfo","buildThreadInfo","buildApiMessageEntity","buildMessageDraft","draft","formattedText","replyingToId","ttlSeconds","buildSticker","buildPhoto","buildVideoFromDocument","buildVideo","audioAttribute","voice","thumbnailSizes","fileName","getFilenameFromDocument","buildAudio","waveform","from","buildVoice","buildApiDocument","buildDocumentFromMedia","phoneNumber","buildContact","buildPoll","results","buildPollFromMedia","webPage","buildWebPage","invoice","description","test","photoUrl","isTest","buildInvoice","buildInvoiceFromMedia","size","self","isMovSupported","videoAttr","a","gifAttr","supportsStreaming","roundMessage","isRound","isGif","mediaType","mediaSize","has","imageAttribute","timestamp","pollResults","answers","rawAnswers","answer","option","summary","isPublic","publicVoters","buildPollResults","rawResults","totalVoters","recentVoters","solution","solutionEntities","chosen","correct","voters","isChosen","isCorrect","votersCount","recentVoterIds","defaultBase","filenameAttribute","extension","split","buildNewPoll","localId","messageReplies","maxId","readMaxId","recentRepliers","apiChannelId","threadId","originChannelId","messagesCount","lastMessageId","lastReadInboxMessageId","recentReplierIds","getServerTime","serverTimeOffset","Date","now","buildApiChatFieldsFromPeerEntity","peerEntity","isSupport","isMin","min","avatarHash","buildAvatarHash","isSignaturesShown","signatures","hasPrivateLink","hasLink","username","isVerified","verified","isCallActive","callActive","isCallNotEmpty","callNotEmpty","participantsCount","membersCount","joinDate","buildApiChatPermissions","isCreator","creator","buildApiChatRestrictions","buildApiChatMigrationInfo","buildApiChatFromDialog","dialog","folderId","unreadMark","unreadCount","unreadMentionsCount","notifySettings","silent","muteUntil","readOutboxMaxId","readInboxMaxId","isMuted","getApiChatTypeFromPeerEntity","getApiChatTitleFromMtpPeer","lastReadOutboxMessageId","hasUnreadMark","draftDate","currentUserBannedRights","defaultBannedRights","isRestricted","restrictions","restrictionReason","restricted","restrictionReasons","targetReason","platform","buildApiChatRestrictionReason","Object","assign","isNotJoined","left","kicked","migratedTo","buildApiChatFromPreview","preview","withForbidden","getUserName","megagroup","getPeerKey","photoId","buildChatMember","inviterId","joinedDate","kickedByUserId","kickedBy","promotedByUserId","promotedBy","customTitle","rank","isAdmin","isOwner","buildChatMembers","participants","buildChatTypingStatus","buildApiChatFolder","channels","broadcasts","pinnedChatIds","pinnedPeers","includedChatIds","includePeers","excludedChatIds","excludePeers","buildApiChatFolderFromSuggested","buildApiChatBotCommands","botInfos","botCommands","botInfo","botId","concat","commands","mtpCommand","buildApiUserFromFull","mtpUserFull","about","commonChatsCount","pinnedMsgId","blocked","buildApiUser","fullInfo","bio","pinnedMessageId","isBlocked","botDescription","buildApiBotCommands","mtpUser","userType","bot","deleted","isSelf","mutualContact","isContact","canBeInvitedToGroup","botNochats","status","buildApiUserStatus","botInlinePlaceholder","botPlaceholder","mtpStatus","expires","wasOnline","command","buildApiWallpaper","wallpaper","slug","buildApiSession","session","isCurrent","current","isOfficialApp","officialApp","isPasswordPending","passwordPending","hash","buildPrivacyRules","rules","visibility","allowUserIds","allowChatIds","blockUserIds","blockChatIds","rule","buildApiNotifyException","showPreviews","sound","isSilent","shouldShowPreviews","buildApiCountry","country","code","hidden","iso2","defaultName","name","countryCode","prefixes","patterns","isHidden","onUpdate","sentMessageIds","updater","originRequest","connection","timeOffset","connectionState","state","shouldForceReply","buildApiMessageFromShort","selective","_entities","e","dcId","buildChatPhotoForLocalDb","localDbChatId","newProfilePhoto","some","ids","existingIds","missingIds","profilePhotoIds","setTimeout","notification","currentDate","inboxDate","buildApiMessageFromNotification","randomId","localMessage","Error","newContent","add","isAlreadySent","isScheduled","sendingState","messageUpdate","pollId","apiPoll","pollUpdate","options","stillUnreadCount","isPinned","pinned","order","dp","folderPeers","folderPeer","folder","orderedIds","replacedMembers","addedMember","deletedMemberId","messageIds","typingStatus","channel","unread","apiUserId","updatedUser","peerType","buildPrivacyKey","ApiErrors","PHONE_NUMBER_INVALID","PHONE_CODE_INVALID","PASSWORD_HASH_INVALID","PHONE_PASSWORD_FLOOD","PHONE_NUMBER_BANNED","authController","onRequestPhoneNumber","buildAuthStateUpdate","Promise","resolve","reject","onRequestCode","isCodeViaApp","onRequestPassword","hint","onRequestRegistration","onRequestQrCode","qrCode","token","onAuthError","err","errors","hours","ceil","seconds","authorizationState","provideAuthPhoneNumber","provideAuthCode","provideAuthPassword","password","provideAuthRegistration","registration","restartAuth","restartAuthWithQr","cacheApi","caches","Type","async","fetch","cacheName","isHtmlAllowed","request","Request","cache","open","response","match","contentType","headers","get","Text","Blob","blob","shouldRecreate","resolvedType","Json","json","console","warn","save","cacheData","JSON","stringify","Response","put","clear","delete","MEDIA_ENTITY_TYPES","getMimeType","fallbackMimeType","subarray","byte","toString","GramJsLogger","gramJsUpdateEventBuilder","build","client","isConnected","destroy","invokeRequest","disconnect","onSessionUpdate","sessionData","handleGramJsUpdate","handleTerminatedSession","shouldHandleUpdates","shouldThrow","invoke","updatesContainer","updates","injectUpdateEntities","isSlowMode","error","hasErrorKey","dispatchErrorUpdate","downloadMedia","args","onProgress","mediaFormat","start","end","fullSize","mediaMatch","arrayBuffer","entityType","entityId","sizeType","Stream","acceptsBuffer","progressCallback","workers","getMessageMediaMimeType","downloadStickerSetThumb","Lottie","downloadProfilePhoto","download","parsed","BlobUrl","inflate","to","parse","Progressive","buffer","parseMedia","canCache","prepared","mediaData","URL","createObjectURL","downloadMediaWithClient","uploadFile","file","updateTwoFaSettings","params","fetchCurrentUser","userFull","currentUser","_currentUserId","onCurrentUserUpdate","MAX_INT_32","fetchChats","limit","offsetDate","withPinned","lastLocalServiceMessage","offsetPeer","excludePinned","resultPinned","updateLocalDb","lastMessagesByChatId","peersByKey","preparePeers","draftsById","replyingToById","dialogs","orderedPinnedIds","lastMessage","isListed","chatIds","totalChatCount","fetchFullChat","fullChat","onlineCount","exportedInvite","slowmodeSeconds","slowmodeNextSendDate","migratedFromChatId","migratedFromMaxId","canViewParticipants","linkedChatId","hiddenPrehistory","call","inviteLink","link","members","fetchMembers","kickedMembers","bannedUsers","adminMembers","adminUsers","mtpLinkedChat","slowMode","nextSendDate","migratedFrom","maxMessageId","canViewMembers","isPreHistoryHidden","groupCallId","getFullChannelInfo","getFullChatInfo","searchChats","query","q","localPeerIds","myResults","allChats","allUsers","localChats","r","localUsers","u","globalChats","globalUsers","fetchChat","requestChatUpdate","lastLocalMessage","noLastMessage","peers","lastRemoteMessage","saveDraft","clearDraft","updateChatMutedState","settings","createChannel","broadcast","newChannel","joinChannel","deleteChatUser","deleteChat","leaveChannel","deleteChannel","createGroupChat","newChat","editChatPhoto","uploadedPhoto","inputEntity","toggleChatPinned","shouldBePinned","toggleChatArchived","fetchChatFolders","byId","fetchRecommendedChatFolders","editChatFolder","folderUpdate","emoticon","contacts","nonContacts","groups","bots","excludeArchived","excludeMuted","excludeRead","buildFilterFromApiFolder","deleteChatFolder","isActionSuccessful","recommendedChatFolders","folders","toggleDialogUnread","getChatByUsername","togglePreHistoryHidden","isEnabled","enabled","updateChatDefaultBannedRights","updateChatMemberBannedRights","participant","updateChatAdmin","updateChatTitle","updateChatAbout","toggleSignatures","memberFilter","fetchGroupsForDiscussion","setDiscussionGroup","group","migrateChat","openChatByInvite","isChannel","addChatMembers","all","deleteChatMember","viewMessages","sendMessages","sendMedia","sendStickers","sendGifs","sendGames","sendInline","embedLinks","sendPolls","changeInfo","inviteUsers","pinMessages","store","importChatInvite","File","constructor","fileBits","super","this","fetchMessages","pagination","RequestClass","msgId","c","threadInfos","fetchMessage","queue","sendMessage","replyingTo","attachment","gif","scheduledAt","noWebPage","filename","blobUrl","previewBlobUrl","quick","inputWaveform","buildUploadingMedia","buildLocalMessage","groupIndex","groupedUploads","counter","singleMediaByIndex","prevQueue","uploadMedia","inputMedia","uploadedMedia","messageMedia","fileReference","fetchInputMedia","multiMedia","values","scheduleDate","sendGroupedMedia","pollParams","quiz","question","Buffer","multipleChoice","correctAnswers","buildInputPoll","noWebpage","editMessage","mtpEntities","rescheduleMessage","lastModified","blobToFile","fetchBlob","fetchFile","patchedOnProgress","progress","isCanceled","inputFile","pinMessage","isUnpin","isOneSide","unpin","pmOneside","unpinAllMessages","deleteMessages","shouldDeleteForAll","revoke","deleteScheduledMessages","deleteHistory","just_clear","reportMessages","markMessageListRead","requestThreadInfoUpdate","markMessagesRead","topMessageResult","repliesResult","offsetId","addOffset","discussionChatId","topMessageId","firstMessageId","noTopChatsRequest","searchMessagesLocal","chatOrUser","minDate","maxDate","topMsgId","nextOffsetId","totalCount","searchMessagesGlobal","offsetRate","nextRate","fetchWebPagePreview","sendPollVote","loadPollOptionResults","shouldResetVoters","votes","vote","nextOffset","forwardMessages","fromChat","toChat","randomIds","index","isAudio","asIncomingInChatWithSelf","buildLocalForwardedMessage","fromPeer","toPeer","sil2ent","findFirstMessageIdAfterDate","fetchScheduledHistory","sendScheduledMessages","isServiceMessageWithMedia","fetchPinnedMessages","inputGifBot","fetchFullUser","input","userWithFullInfo","fetchCommonChats","commonChats","mtpChat","isFullyLoaded","fetchNearestCountry","dcInfo","fetchTopUsers","topPeers","correspondents","fetchContactList","fetchUsers","updateContact","addContact","deleteUser","fetchProfilePhotos","fetchStickerSets","allStickers","sets","fetchRecentStickers","stickers","processStickerResult","fetchFavoriteStickers","fetchFeaturedStickers","faveSticker","unfave","fetchStickers","stickerSetShortName","packs","acc","documentId","fetchAnimatedEmojis","searchStickers","fetchSavedGifs","gifs","processGifResult","installStickerSet","uninstallStickerSet","searchGifs","config","resolvedPeer","gifSearchUsername","foundGif","fetchStickersForEmoji","fetchEmojiKeywords","fromVersion","langCode","version","keywords","emojiKeyword","keyword","emoticons","checkChatUsername","setChatUsername","updatePrivateLink","EMAIL_UNCONFIRMED","EMAIL_HASH_EXPIRED","NEW_SALT_INVALID","NEW_SETTINGS_INVALID","CODE_INVALID","emailCodeController","getPasswordInfo","hasPassword","onRequestEmailCode","checkPassword","currentPassword","isCheckPassword","onError","clearPassword","updatePassword","email","newPassword","emailCodeCallback","onEmailCodeError","updateRecoveryEmail","provideRecoveryEmailCode","BETA_LANG_CODES","updateProfile","checkUsername","updateUsername","updateProfilePhoto","uploadProfilePhoto","fetchWallpapers","filteredWallpapers","wallpapers","pattern","uploadWallpaper","fetchBlockedContacts","blockedIds","blockContact","unblockContact","fetchAuthorizations","authorizations","terminateAuthorization","terminateAllAuthorizations","fetchNotificationExceptions","compareSound","fetchNotificationSettings","isMutedContactSignUpNotification","privateContactNotificationsSettings","groupNotificationsSettings","broadcastNotificationsSettings","privateSilent","privateMuteUntil","privateShowPreviews","groupSilent","groupMuteUntil","groupShowPreviews","broadcastSilent","broadcastMuteUntil","broadcastShowPreviews","hasContactJoinedNotifications","hasPrivateChatsNotifications","hasPrivateChatsMessagePreview","hasGroupNotifications","hasGroupMessagePreview","hasBroadcastNotifications","hasBroadcastMessagePreview","updateContactSignUpNotification","updateNotificationSettings","fetchLanguages","langPack","fetchLangPack","sourceLangPacks","collections","strings","reverse","fetchLangStrings","fetchPrivacySettings","registerDevice","secret","getAuthKey","getKey","tokenType","appSandbox","otherUids","unregisterDevice","setPrivacySettings","privacyRules","allowedUsers","allowedChats","blockedUsers","blockedChats","updateIsOnline","isOnline","offline","fetchContentSettings","isSensitiveEnabled","sensitiveEnabled","canChangeSensitive","sensitiveCanChange","updateContentSettings","fetchCountryList","countryList","countries","phoneCodes","array","countryCodes","isArray","sort","b","localeCompare","general","buildApiWebDocument","answerCallbackButton","fetchTopInlineBots","botsInline","fetchInlineBot","addUserToLocalDb","fetchInlineBotResults","queryId","switchPm","isGallery","gallery","help","buildApiBotInlineMediaResult","webDocument","webThumbnail","buildApiBotInlineResult","sendInlineBotResult","resultId","startBot","startParam","buildShippingOptions","shippingOptions","prices","ac","cur","label","validateRequestedInfo","requestInfo","shouldSave","sendPaymentForm","formId","requestedInfoId","shippingOptionId","credentials","getPaymentForm","form","canSaveCredentials","passwordMissing","providerId","nativeProvider","nativeParams","savedInfo","nameRequested","phoneRequested","emailRequested","shippingAddressRequested","flexible","phoneToProvider","emailToProvider","mapedPrices","nativeData","needCardholderName","need_cardholder_name","needCountry","need_country","needZip","need_zip","publishableKey","publishable_key","buildPaymentForm","getReceipt","receipt","shipping","credentialsTitle","shippingPrices","shippingMethod","buildReceipt","initApi","_onUpdate","initialArgs","initUpdater","handleUpdate","initAuth","initChats","initMessages","initUsers","initStickers","initManagement","initTwoFaSettings","userAgent","sessions","TelegramClient","process","deviceModel","navigator","systemVersion","appVersion","useWSS","additionalDcsDisabled","testServers","addEventHandler","phoneCode","firstAndLastNames","initialMethod","getSessionData","initClient","flushUpdatesOnTickEnd","schedulerFn","fn","waiting","_args","throttleWith","callback","isPrimary","then","currentCallbacks","currentPrimaryCallbacks","cb","throttleId","pendingUpdates","currentThrottleId","currentUpdates","flushUpdatesThrottled","ms","shouldRunFirst","interval","isPending","setInterval","clearInterval","throttle","random","onerror","sendToOrigin","addEventListener","callbackState","Map","postMessage","onmessage","callbackArgs","lastArg","ArrayBuffer","fnName","methods","callApi","require","crypto","little","signed","randBuffer","bytesNumber","bigInt","subtract","pow","toSignedLittleBuffer","big","number","bigNumber","byteArray","shiftRight","and","readBufferFromBigInt","bitLength","lesser","below","hex","padStart","l","reminder","randomBytes","sha1","shaSum","createHash","digest","crcTable","module","exports","generateRandomLong","mod","n","m","crc32","buf","k","makeCRCTable","isBuffer","crc","generateKeyDataFromNonce","serverNonce","newNonce","hash1","hash2","hash3","iv","sha256","bigIntMod","remainder","modExp","one","x","greater","zero","leastSignificantBit","divide","eq","multiply","getRandomInt","sleep","getByteArray","integer","bits","byteLength","convertToLittle","alloc","writeUInt32BE","bufferXor","res","createDeferred","promise","_resolve","constructors","checkPrimeAndGood","primeBytes","g","equals","numBytesForHash","bigNumForHash","isGoodModExpFirst","modexp","prime","diff","xor","computeHash","algo","salt1","salt2","salt","iterations","pbkdf2","pbkdf2sha512","computeCheck","currentAlgo","PasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow","pwHash","p","B","srp_B","isGoodLarge","pForHash","gForHash","bForHash","gX","kgX","aForHash","A","generateAndCheckRandom","gB","ux","aUx","S","K","pSha","gSha","salt1Sha","salt2Sha","M1","InputCheckPasswordSRP","srpId","computeDigest","JPEG_HEADER","JPEG_FOOTER","_raiseCastFail","target","getMessageId","getInputPeer","allowSelf","checkHash","User","InputPeerSelf","InputPeerUser","Chat","ChatEmpty","ChatForbidden","InputPeerChat","Channel","TypeError","InputPeerChannel","ChannelForbidden","InputUser","InputChannel","UserEmpty","InputPeerEmpty","UserFull","ChatFull","PeerChat","getDisplayName","getAppropriatedPartSize","fileSize","stripped","header","getDC","downloadDC","ipAddress","port","pwd","Api","newAlgo","newSettings","newPasswordHash","newSecureSettings","codeLength","os","Logger","MemorySession","Helpers","utils","Session","LAYER","requests","MTProtoSender","ConnectionTCPObfuscated","authFlow","checkAuthorization","downloadFile","WEBDOCUMENT_REQUEST_PART_SIZE","sizeTypes","apiId","apiHash","opts","DEFAULT_OPTIONS","_useIPV6","useIPV6","baseLogger","_log","floodSleepLimit","_eventBuilders","_phoneCodeHash","parseInt","_requestRetries","requestRetries","_connectionRetries","connectionRetries","_retryDelay","retryDelay","proxy","_proxy","_timeout","timeout","_autoReconnect","autoReconnect","_connection","_floodWaitedRequests","_initWith","InvokeWithLayer","layer","InitConnection","release","systemLangCode","_config","phoneCodeHashes","_exportedSenderPromises","_exportedSenderReleaseTimeouts","_additionalDcsDisabled","_loopStarted","_reconnecting","_destroyed","_initSession","_sender","logger","retries","delay","connectTimeout","authKeyCallback","_authKeyCallback","bind","updateCallback","_handleUpdate","isMainSender","userDisconnected","_user_connected","_disconnected","serverAddress","connect","setAuthKey","authKey","send","GetConfig","_updateLoop","load","setDC","attempts","PingDelayDisconnect","pingId","MIN_SAFE_INTEGER","MAX_SAFE_INTEGER","disconnectDelay","race","getTime","_lastRequest","GetState","sender","newDc","DC","setKey","dc","_authenticated","auth","ExportAuthorization","req","ImportAuthorization","shouldReconnect","existingSender","_connectSender","_createExportedSender","isConnecting","_borrowExportedSender","clearTimeout","onConnectionBreak","_cleanupExportedSender","getSender","inputLocation","messageOrMedia","Message","MessageMediaWebPage","WebPage","MessageMediaPhoto","Photo","_downloadPhoto","MessageMediaDocument","Document","_downloadDocument","MessageMediaContact","_downloadContact","WebDocument","WebDocumentNoProxy","_downloadWebDocument","isBig","loc","chatPhoto","UserProfilePhoto","ChatPhoto","InputPeerPhotoFileLocation","thumbVersion","InputStickerSetThumb","InputStickerSetID","thumbDcId","_pickFileSize","indexOf","_downloadCachedPhotoSize","PhotoStrippedSize","PhotoSizeEmpty","PhotoCachedSize","InputPhotoFileLocation","thumbSize","doc","InputDocumentFileLocation","buff","downloaded","upload","GetWebFile","location","InputWebFileLocation","attempt","sendWithInvokeSupport","ServerError","FloodWaitError","FloodTestPhoneWaitError","PhoneMigrateError","NetworkMigrateError","UserMigrateError","_switchDC","MsgWaitError","isReady","GetUsers","InputUserSelf","authParams","apiCredentials","fileParams","event","Updates","UpdatesCombined","_processUpdate","UpdateShort","others","_dispatchUpdate","ptsDate","builder","times","pause","Infinity","sequentialUpdates","DEFAULT_INITIAL_METHOD","me","botAuthToken","signInBot","signInUser","signInUserWithQrCode","phoneCodeHash","sendCodeResult","sendCode","forceSMS","termsOfService","isRegistrationRequired","signInWithPassword","isScanningComplete","inputPromise","exceptIds","updatePromise","result2","authorization","migratedResult","sendResult","resendResult","passwordSrpResult","passwordSrpCheck","computePasswordSrpCheck","ONE_MB","Foreman","maxWorkers","requestWorker","activeWorkers","releaseWorker","partSizeKb","partSize","partsCount","foreman","promises","hasEnded","isPrecise","offsetMemo","precise","buffers","totalLength","fileId","isLarge","partCount","fileToBuffer","sendingParts","j","jMemo","bytesMemo","filePart","fileTotalParts","parts","md5Checksum","BinaryReader","AuthKey","_key","_hash","reader","auxHash","readLong","read","keyId","writeUInt8","shaData","other","cipher","createCipheriv","encrypt","Factorizator","neq","temp","pq","y","randBetween","minus","ys","condition","gcd","IGE","AESIGE","ige","decryptIge","cipherText","decrypt","encryptIge","plainText","padding","i2abLow","uint8","Uint8Array","int","i2abBig","ab2iLow","ab","Uint32Array","ab2iBig","isBigEndian","i2ab","ab2i","AES","getWords","Counter","initialValue","setBytes","_counter","increment","CTR","_remainingCounter","_remainingCounterIndex","_aes","encrypted","Hash","algorithm","subtle","createDecipheriv","getRandomValues","passwordKey","importKey","deriveBits","s2i","str","pos","charCodeAt","right","ReadCancelledError","TypeNotFoundError","invalidConstructorId","remaining","alert","InvalidChecksumError","checksum","validChecksum","InvalidBufferError","payload","readInt32LE","SecurityError","BadMessageError","errorMessage","ErrorMessages","CdnFileTamperedError","RPCError","_fmtRequest","InvalidDCError","BadRequestError","UnauthorizedError","ForbiddenError","NotFoundError","AuthKeyError","FloodError","TimedOutError","capture","SlowModeWaitError","FileMigrateError","EmailUnconfirmedError","rpcErrorRe","Common","RPCBaseErrors","RPCErrorList","RPCMessageToError","rpcError","msgRegex","Cls","EventBuilder","types","func","blacklistChats","resolved","NewMessage","Raw","StopPropagation","_queue","canGet","resolveGet","canPush","resolvePush","returned","pop","coreObjects","tlobjects","stream","_last","readByte","readInt","readUInt32LE","readLargeInt","readFloat","readFloatLE","readDouble","readDoubleLE","getBuffer","tgReadBytes","firstByte","tgReadString","tgReadBool","tgReadDate","tgReadObject","constructorId","clazz","seek","tellPosition","setPosition","fromReader","tgReadVector","close","position","_stream","write","getValue","_level","level","isBrowser","browser","__nwjs","colors","debug","messageFormat","canSend","levels","stack","format","toISOString","toUpperCase","color","log","MessageContainer","TLMessage","BinaryWriter","USE_INVOKE_AFTER_WITH","_state","_pendingStates","_ready","setReady","append","after","catch","finally","extend","states","batch","MAXIMUM_LENGTH","shift","SIZE_OVERHEAD","MAXIMUM_SIZE","afterId","writeDataAsMessage","unshift","writeUInt32LE","writeInt32LE","containerId","rejectAll","requestState","Mutex","mutex","WebSocketClient","closeError","disconnectedCallback","closed","readData","thisTime","canRead","toReturn","resolveRead","getWebSocketLink","ip","website","onopen","receive","onclose","wasClean","runExclusive","PromisedWebSockets","MessagePacker","AsyncQueue","tl","events","extensions","helpers","PUBLIC_KEYS","fingerprint","_serverKeys","keyInfo","doAuthentication","nonce","resPQ","factorize","pBuffer","qBuffer","pqInnerData","targetFingerprint","targetKey","serverPublicKeyFingerprints","dataWithPadding","dataPadReversed","encryptedData","tempKey","shaDigestKeyWithData","dataWithHash","aesEncrypted","tempKeyXor","keyAesEncrypted","keyAesEncryptedInt","greaterOrEquals","encryptedDataBuffer","serverDhParams","publicKeyFingerprint","sh","nnh","newNonceHash","encryptedAnswer","plainTextAnswer","serverDhInner","dhPrime","ga","gA","serverTime","gb","gab","clientDhInner","retryId","clientDdhInnerHashed","clientDhEncrypted","dhGen","nonceTypes","nonceNumber","calcNewNonceHash","MTProtoState","loggers","body","_getNewMsgId","recv","MtProtoPlainSender","RPCResult","GZIPPacked","RequestState","MsgsAck","MsgsStateInfo","Pong","UpdateConnectionState","UpdateServerTimeOffset","BadServerSalt","BadMsgNotification","MsgDetailedInfo","MsgNewDetailedInfo","NewSessionCreated","FutureSalts","MsgsStateReq","MsgResendReq","MsgsAllInfo","LogOut","_dcId","_retries","_delay","_connectTimeout","_updateCallback","_autoReconnectCallback","autoReconnectCallback","_isMainSender","_onConnectionBreak","_send_loop_handle","_recv_loop_handle","_send_queue","_pending_state","_pending_ack","_last_acks","_handlers","_handleRPCResult","_handleContainer","_handleGzipPacked","_handlePong","_handleBadServerSalt","_handleBadNotification","_handleDetailedInfo","_handleNewDetailedInfo","_handleNewSessionCreated","_handleAck","_handleFutureSalts","_handleStateForgotten","_handleMsgAll","force","_connect","connected","disconnected","_disconnect","plain","_sendLoop","_recvLoop","ack","msgIds","encryptMessageData","reconnect","decryptMessageData","broken","_processMessage","obj","handler","_popStates","toPop","reqMsgId","readResult","innerMessage","pong","newTimeOffset","updateTimeOffset","badSalt","badMsgId","newServerSalt","badMsg","errorCode","_sequence","answerMsgId","serverSalt","repeat","_reconnect","reset","newConnection","_ip","_port","_testServers","InvokeAfterMsg","_lastMsgId","updateMessageId","msgKey","sha256a","sha256b","contentRelated","seqNo","_getSeqNo","gzipIfSmaller","waitForKey","_calcKey","ourKey","remoteMsgId","remoteSequence","containerLen","nanoseconds","newMsgId","shiftLeft","or","correctMsgId","bad","old","pending","Connection","_connected","_sendTask","_recvTask","_codec","_obfuscation","_sendArray","_recvArray","socket","disconnectCallback","PacketCodecClass","_initConn","fromCallback","_send","_recv","tag","encodedPacket","encodePacket","readPacket","PacketCodec","_conn","ObfuscatedConnection","ObfuscatedIO","AbridgedPacketCodec","props","obfuscateTag","ConnectionTCPAbridged","initHeader","_encrypt","encryptor","_decrypt","decryptor","packetCodec","ok","toJSON","randomReversed","encryptKey","encryptIv","decryptKey","decryptIv","readExactly","ConnectionTCPFull","MTProtoPlainSender","StorageSession","CACHE_NAME","_storageKey","cached","_sessionData","_callback","_authKeys","mainDcId","hashes","skipOnUpdate","_serverAddress","idb","_delete","del","_fetchFromCache","_saveToCache","localStorage","removeItem","getItem","setItem","_takeoutId","_updateStates","_authKey","sessionInfo","_sessionString","_loadFromSessionString","skipUpdateStorage","_updateStorage","asHex","mainDcIdStr","mainDcKey","StringSession","decode","readUInt8","serverAddressLen","readInt16BE","dcBuffer","addressBuffer","addressLengthBuffer","writeInt16BE","portBuffer","encode","Memory","CacheApiSession","LocalStorageSession","IdbSession","CallbackSession","api","sub","parseTl","serializeBytes","serializeDate","tlContent","schemeContent","CACHING_SUPPORTED","CACHE_KEY","extractParams","fileContent","f","functions","d","isFunction","argToBytes","writeDoubleLE","getArgFromReader","arg","isVector","useVectorId","flagIndicator","skipConstructorId","createClasses","classesType","classes","classParams","subclassOfId","argsConfig","namespace","fullName","VirtualClass","argName","isFlag","flagIndex","idForBytes","flagCalculate","boxed","charAt","definitions","fromCache","jsonCache","loadFromCache","constructorParamsApi","functionParamsApi","constructorParamsSchema","functionParamsSchema","loadFromTlSchemas","obj1","obj2","mergeWithNamespaces","buildApiFromTlSchema","gzipped","toBytes","gzip","ungzip","containerLength","before","tlMessage","RpcError","innerCode","snakeToCamelCase","_","variableSnakeToCamelCase","CORE_TYPES","AUTH_KEY_TYPES","findAll","regex","matches","RegExp","source","exec","fromLine","line","argsMatch","currentConfig","hexId","representation","brace","argType","buildArgConfig","flagMatch","vectorMatch","ignoreIds","o","objAll","objByName","objByType","commentIndex","trim","followingTypes","dt","fill","t","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","loaded","__webpack_modules__","__webpack_exports__","O","chunkIds","priority","notFulfilled","fulfilled","every","splice","getter","__esModule","definition","defineProperty","enumerable","chunkId","miniCssF","globalThis","Function","prop","prototype","Symbol","toStringTag","nmd","paths","children","scriptUrl","importScripts","currentScript","src","scripts","getElementsByTagName","installedChunks","chunkLoadingGlobal","parentChunkLoadingFunction","moreModules","runtime"],"sourceRoot":""} \ No newline at end of file +{"version":3,"file":"514.3cef19392d72a10cf6ea.js","mappings":"UAAIA,ECAAC,E,ujHCAG,MAuGMC,GAhEyB,oBAAXC,QAA0BA,OAAOC,YAgEzBC,KAAKC,MAAM,MACjCC,EAA6B,IAAIC,IAAI,CAChD,aAAc,sBAAuB,iBAAkB,0BAA2B,kBA0BvEC,EAAgC,IAAID,IAAI,CACnD,YAAa,YAAa,eAGfE,EAAgC,IAAIF,IAAI,CACnD,cAkBWG,GAf6B,IAAIH,IAAI,IAC7CC,KACAC,IAUyC,IAAIF,IAAI,CAAC,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,OAGhH,UCxB7C,IA4BII,EACAC,E,cCvJG,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,I,cCpBE,SAASC,EAAeC,EAAeC,GAAmB,EAAOC,EAAmB,cAGzF,MAAQ,GAFOD,EAAmB,GAAM,QAAOC,cAE5BC,KAAKC,OAAOC,gBAAgBL,MAG1C,SAASM,EACdC,GAEA,MAAM,MACJC,EADI,eAEJC,EAFI,eAGJC,EAHI,UAIJC,EAJI,UAKJC,EALI,SAMJC,KACGC,GACDP,EAEJ,OAAOO,ECvBF,SAASC,EAAef,EAAegB,EAAeC,GAC3D,MAJe,gPAKZC,QAAQ,WAKb,SAAmBlB,GACjB,IAAImB,EAAO,IAEX,MAAMC,EAAMpB,EAAMqB,OAClB,IAAK,IAAIC,EAAI,EAAGA,EAAIF,EAAKE,IAAK,CAC5B,MAAMC,EAAMvB,EAAMsB,GACdC,GAAO,IACTJ,GAhB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wC,GiHDd0vE,EAAoBx5B,K","sources":["webpack://telegram-t/webpack/runtime/chunk loaded","webpack://telegram-t/webpack/runtime/startup chunk dependencies","webpack://telegram-t/./src/config.ts","webpack://telegram-t/./src/util/schedulers.ts","webpack://telegram-t/./src/util/iteratees.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/helpers.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/pathBytesToSvg.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/common.ts","webpack://telegram-t/./src/api/gramjs/localDb.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/symbols.ts","webpack://telegram-t/./src/util/waveform.ts","webpack://telegram-t/./src/api/types/messages.ts","webpack://telegram-t/./src/api/types/media.ts","webpack://telegram-t/./src/api/gramjs/gramjsBuilders/index.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/peers.ts","webpack://telegram-t/./src/api/gramjs/helpers.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/messages.ts","webpack://telegram-t/./src/util/serverTime.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/chats.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/users.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/misc.ts","webpack://telegram-t/./src/api/gramjs/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/settings.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/bots.ts","webpack://telegram-t/./src/api/gramjs/methods/bots.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/payments.ts","webpack://telegram-t/./src/api/gramjs/methods/payments.ts","webpack://telegram-t/./src/api/gramjs/provider.ts","webpack://telegram-t/./src/api/gramjs/worker/worker.ts","webpack://telegram-t/./src/lib/gramjs/Helpers.js","webpack://telegram-t/./src/lib/gramjs/Password.js","webpack://telegram-t/./src/lib/gramjs/Utils.js","webpack://telegram-t/./src/lib/gramjs/Version.js","webpack://telegram-t/./src/lib/gramjs/client/2fa.ts","webpack://telegram-t/./src/lib/gramjs/client/TelegramClient.js","webpack://telegram-t/./src/lib/gramjs/client/auth.ts","webpack://telegram-t/./src/lib/gramjs/client/downloadFile.ts","webpack://telegram-t/./src/lib/gramjs/client/uploadFile.ts","webpack://telegram-t/./src/lib/gramjs/crypto/AuthKey.js","webpack://telegram-t/./src/lib/gramjs/crypto/CTR.js","webpack://telegram-t/./src/lib/gramjs/crypto/Factorizator.js","webpack://telegram-t/./src/lib/gramjs/crypto/IGE.js","webpack://telegram-t/./src/lib/gramjs/crypto/converters.ts","webpack://telegram-t/./src/lib/gramjs/crypto/crypto.js","webpack://telegram-t/./src/lib/gramjs/crypto/words.ts","webpack://telegram-t/./src/lib/gramjs/errors/Common.js","webpack://telegram-t/./src/lib/gramjs/errors/RPCBaseErrors.js","webpack://telegram-t/./src/lib/gramjs/errors/RPCErrorList.js","webpack://telegram-t/./src/lib/gramjs/errors/index.js","webpack://telegram-t/./src/lib/gramjs/events/Raw.js","webpack://telegram-t/./src/lib/gramjs/events/common.js","webpack://telegram-t/./src/lib/gramjs/events/index.js","webpack://telegram-t/./src/lib/gramjs/extensions/AsyncQueue.js","webpack://telegram-t/./src/lib/gramjs/extensions/BinaryReader.js","webpack://telegram-t/./src/lib/gramjs/extensions/BinaryWriter.js","webpack://telegram-t/./src/lib/gramjs/extensions/Logger.js","webpack://telegram-t/./src/lib/gramjs/extensions/MessagePacker.js","webpack://telegram-t/./src/lib/gramjs/extensions/PromisedWebSockets.js","webpack://telegram-t/./src/lib/gramjs/extensions/index.js","webpack://telegram-t/./src/lib/gramjs/index.js","webpack://telegram-t/./src/lib/gramjs/crypto/RSA.ts","webpack://telegram-t/./src/lib/gramjs/network/Authenticator.ts","webpack://telegram-t/./src/lib/gramjs/network/MTProtoPlainSender.js","webpack://telegram-t/./src/lib/gramjs/network/MTProtoSender.js","webpack://telegram-t/./src/lib/gramjs/network/MTProtoState.js","webpack://telegram-t/./src/lib/gramjs/network/RequestState.js","webpack://telegram-t/./src/lib/gramjs/network/connection/Connection.js","webpack://telegram-t/./src/lib/gramjs/network/connection/TCPAbridged.js","webpack://telegram-t/./src/lib/gramjs/network/connection/TCPObfuscated.js","webpack://telegram-t/./src/lib/gramjs/network/connection/index.js","webpack://telegram-t/./src/lib/gramjs/network/index.js","webpack://telegram-t/./src/lib/gramjs/sessions/Abstract.js","webpack://telegram-t/./src/lib/gramjs/sessions/CacheApiSession.js","webpack://telegram-t/./src/lib/gramjs/sessions/CallbackSession.js","webpack://telegram-t/./src/lib/gramjs/sessions/IdbSession.js","webpack://telegram-t/./src/lib/gramjs/sessions/LocalStorageSession.js","webpack://telegram-t/./src/lib/gramjs/sessions/Memory.js","webpack://telegram-t/./src/lib/gramjs/sessions/StorageSession.js","webpack://telegram-t/./src/lib/gramjs/sessions/StringSession.js","webpack://telegram-t/./src/lib/gramjs/sessions/index.js","webpack://telegram-t/./src/lib/gramjs/tl/AllTLObjects.js","webpack://telegram-t/./src/lib/gramjs/tl/api.js","webpack://telegram-t/./src/lib/gramjs/tl/apiTl.js","webpack://telegram-t/./src/lib/gramjs/tl/core/GZIPPacked.js","webpack://telegram-t/./src/lib/gramjs/tl/core/MessageContainer.js","webpack://telegram-t/./src/lib/gramjs/tl/core/RPCResult.js","webpack://telegram-t/./src/lib/gramjs/tl/core/TLMessage.js","webpack://telegram-t/./src/lib/gramjs/tl/core/index.js","webpack://telegram-t/./src/lib/gramjs/tl/generationHelpers.js","webpack://telegram-t/./src/lib/gramjs/tl/index.js","webpack://telegram-t/./src/lib/gramjs/tl/schemaTl.js","webpack://telegram-t/webpack/bootstrap","webpack://telegram-t/webpack/runtime/compat get default export","webpack://telegram-t/webpack/runtime/define property getters","webpack://telegram-t/webpack/runtime/ensure chunk","webpack://telegram-t/webpack/runtime/get javascript chunk filename","webpack://telegram-t/webpack/runtime/get mini-css chunk filename","webpack://telegram-t/webpack/runtime/global","webpack://telegram-t/webpack/runtime/hasOwnProperty shorthand","webpack://telegram-t/webpack/runtime/make namespace object","webpack://telegram-t/webpack/runtime/node module decorator","webpack://telegram-t/webpack/runtime/publicPath","webpack://telegram-t/webpack/runtime/importScripts chunk loading","webpack://telegram-t/webpack/startup"],"sourcesContent":["var deferred = [];\n__webpack_require__.O = (result, chunkIds, fn, priority) => {\n\tif(chunkIds) {\n\t\tpriority = priority || 0;\n\t\tfor(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1];\n\t\tdeferred[i] = [chunkIds, fn, priority];\n\t\treturn;\n\t}\n\tvar notFulfilled = Infinity;\n\tfor (var i = 0; i < deferred.length; i++) {\n\t\tvar [chunkIds, fn, priority] = deferred[i];\n\t\tvar fulfilled = true;\n\t\tfor (var j = 0; j < chunkIds.length; j++) {\n\t\t\tif ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(__webpack_require__.O).every((key) => (__webpack_require__.O[key](chunkIds[j])))) {\n\t\t\t\tchunkIds.splice(j--, 1);\n\t\t\t} else {\n\t\t\t\tfulfilled = false;\n\t\t\t\tif(priority < notFulfilled) notFulfilled = priority;\n\t\t\t}\n\t\t}\n\t\tif(fulfilled) {\n\t\t\tdeferred.splice(i--, 1)\n\t\t\tvar r = fn();\n\t\t\tif (r !== undefined) result = r;\n\t\t}\n\t}\n\treturn result;\n};","var next = __webpack_require__.x;\n__webpack_require__.x = () => {\n\treturn __webpack_require__.e(592).then(next);\n};","export const PAGE_TITLE = 'Telegram';\nexport const INACTIVE_MARKER = ' [Inactive]';\n\nexport const APP_NAME = process.env.APP_NAME || 'Telegram WebZ';\nexport const APP_VERSION = process.env.APP_VERSION || 'dev';\n\nexport const DEBUG = (\n process.env.APP_ENV !== 'production' && process.env.APP_ENV !== 'perf' && process.env.APP_ENV !== 'test'\n);\nexport const DEBUG_MORE = false;\n\nexport const IS_TEST = process.env.APP_ENV === 'test';\nexport const IS_PERF = process.env.APP_ENV === 'perf';\n\nexport const DEBUG_ALERT_MSG = 'Shoot!\\nSomething went wrong, please see the error details in Dev Tools Console.';\nexport const DEBUG_GRAMJS = false;\n\nexport const SESSION_USER_KEY = 'user_auth';\nexport const LEGACY_SESSION_KEY = 'GramJs:sessionId';\n\nexport const GLOBAL_STATE_CACHE_DISABLED = false;\nexport const GLOBAL_STATE_CACHE_KEY = 'tt-global-state';\nexport const GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT = 30;\nexport const GLOBAL_STATE_CACHE_USER_LIST_LIMIT = 5000;\n\nexport const MEDIA_CACHE_DISABLED = false;\nexport const MEDIA_CACHE_NAME = 'tt-media';\nexport const MEDIA_CACHE_NAME_AVATARS = 'tt-media-avatars';\nexport const MEDIA_PROGRESSIVE_CACHE_DISABLED = false;\nexport const MEDIA_PROGRESSIVE_CACHE_NAME = 'tt-media-progressive';\nexport const MEDIA_CACHE_MAX_BYTES = 512 * 1024; // 512 KB\nexport const CUSTOM_BG_CACHE_NAME = 'tt-custom-bg';\nexport const LANG_CACHE_NAME = 'tt-lang-packs-v6';\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_SENSITIVE_AREA = 750;\nexport const MESSAGE_LIST_SLICE = isBigScreen ? 60 : 40;\nexport const MESSAGE_LIST_VIEWPORT_LIMIT = MESSAGE_LIST_SLICE * 2;\n\nexport const CHAT_HEIGHT_PX = 72;\nexport const CHAT_LIST_SLICE = isBigScreen ? 30 : 25;\nexport const CHAT_LIST_LOAD_SLICE = 100;\nexport const SHARED_MEDIA_SLICE = 42;\nexport const MESSAGE_SEARCH_SLICE = 42;\nexport const GLOBAL_SEARCH_SLICE = 20;\nexport const MEMBERS_SLICE = 30;\nexport const MEMBERS_LOAD_SLICE = 200;\nexport const PINNED_MESSAGES_LIMIT = 50;\nexport const BLOCKED_LIST_LIMIT = 100;\nexport const PROFILE_PHOTOS_LIMIT = 40;\nexport const PROFILE_SENSITIVE_AREA = 500;\nexport const COMMON_CHATS_LIMIT = 100;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 20;\nexport const ALL_CHATS_PRELOAD_DISABLED = false;\n\nexport const DEFAULT_VOLUME = 1;\nexport const DEFAULT_PLAYBACK_RATE = 1;\n\nexport const ANIMATION_LEVEL_MIN = 0;\nexport const ANIMATION_LEVEL_MED = 1;\nexport const ANIMATION_LEVEL_MAX = 2;\nexport const ANIMATION_LEVEL_DEFAULT = ANIMATION_LEVEL_MAX;\n\nexport const DEFAULT_MESSAGE_TEXT_SIZE_PX = 16;\nexport const IOS_DEFAULT_MESSAGE_TEXT_SIZE_PX = 17;\nexport const MACOS_DEFAULT_MESSAGE_TEXT_SIZE_PX = 15;\n\nexport const DRAFT_DEBOUNCE = 10000; // 10s\n\nexport const EDITABLE_INPUT_ID = 'editable-message-text';\nexport const EDITABLE_INPUT_MODAL_ID = 'editable-message-text-modal';\n\n// Screen width where Pinned Message / Audio Player in the Middle Header can be safely displayed\nexport const SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1440; // px\n// Screen width where Pinned Message / Audio Player in the Middle Header shouldn't collapse with ChatInfo\nexport const SAFE_SCREEN_WIDTH_FOR_CHAT_INFO = 1150; // px\n\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1275; // px\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN = 925; // px\nexport const MOBILE_SCREEN_MAX_WIDTH = 600; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH = 950; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT = 450; // px\n\nexport const LOCAL_MESSAGE_ID_BASE = 1e9;\nexport const TMP_CHAT_ID = '0';\n\nexport const ANIMATION_END_DELAY = 100;\n\nexport const FAST_SMOOTH_MAX_DISTANCE = 1500;\nexport const FAST_SMOOTH_MIN_DURATION = 250;\nexport const FAST_SMOOTH_MAX_DURATION = 600;\nexport const FAST_SMOOTH_SHORT_TRANSITION_MAX_DISTANCE = 500; // px\n\n// Average duration of message sending animation\nexport const API_UPDATE_THROTTLE = Math.round((FAST_SMOOTH_MIN_DURATION + FAST_SMOOTH_MAX_DURATION) / 2);\nexport const API_THROTTLE_RESET_UPDATES = new Set([\n 'newMessage', 'newScheduledMessage', 'deleteMessages', 'deleteScheduledMessages', 'deleteHistory',\n]);\n\nexport const STICKER_SIZE_INLINE_DESKTOP_FACTOR = 13;\nexport const STICKER_SIZE_INLINE_MOBILE_FACTOR = 11;\nexport const STICKER_SIZE_AUTH = 160;\nexport const STICKER_SIZE_AUTH_MOBILE = 120;\nexport const STICKER_SIZE_PICKER = 64;\nexport const STICKER_SIZE_GENERAL_SETTINGS = 48;\nexport const STICKER_SIZE_PICKER_HEADER = 32;\nexport const STICKER_SIZE_SEARCH = 64;\nexport const STICKER_SIZE_MODAL = 64;\nexport const STICKER_SIZE_TWO_FA = 160;\nexport const STICKER_SIZE_DISCUSSION_GROUPS = 140;\nexport const STICKER_SIZE_FOLDER_SETTINGS = 80;\nexport const STICKER_SIZE_INLINE_BOT_RESULT = 100;\nexport const RECENT_STICKERS_LIMIT = 20;\nexport const MEMOJI_STICKER_ID = 'MEMOJI_STICKER';\n\nexport const BASE_EMOJI_KEYWORD_LANG = 'en';\n\nexport const MENU_TRANSITION_DURATION = 200;\nexport const SLIDE_TRANSITION_DURATION = 450;\n\nexport const VIDEO_MOV_TYPE = 'video/quicktime';\n\nexport const SUPPORTED_IMAGE_CONTENT_TYPES = new Set([\n 'image/png', 'image/gif', 'image/jpeg',\n]);\n\nexport const SUPPORTED_VIDEO_CONTENT_TYPES = new Set([\n 'video/mp4', // video/quicktime added dynamically in environment.ts\n]);\n\nexport const CONTENT_TYPES_WITH_PREVIEW = new Set([\n ...SUPPORTED_IMAGE_CONTENT_TYPES,\n ...SUPPORTED_VIDEO_CONTENT_TYPES,\n]);\n\n// eslint-disable-next-line max-len\nexport const RE_LINK_TEMPLATE = '((ftp|https?):\\\\/\\\\/)?((www\\\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\\\.[a-zA-Z0-9()]{1,63})\\\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)';\nexport const RE_MENTION_TEMPLATE = '(@[\\\\w\\\\d_-]+)';\nexport const RE_TG_LINK = /^tg:(\\/\\/)?([?=&\\d\\w_-]+)?/gm;\nexport const RE_TME_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/)/gm;\n\n// eslint-disable-next-line max-len\nexport const COUNTRIES_WITH_12H_TIME_FORMAT = new Set(['AU', 'BD', 'CA', 'CO', 'EG', 'HN', 'IE', 'IN', 'JO', 'MX', 'MY', 'NI', 'NZ', 'PH', 'PK', 'SA', 'SV', 'US']);\n\n// MTProto constants\nexport const SERVICE_NOTIFICATIONS_USER_ID = '777000';\nexport const REPLIES_USER_ID = '1271266957'; // TODO For Test connection ID must be equal to 708513\nexport const ALL_FOLDER_ID = 0;\nexport const ARCHIVED_FOLDER_ID = 1;\nexport const DELETED_COMMENTS_CHANNEL_ID = '-777';\nexport const MAX_MEDIA_FILES_FOR_ALBUM = 10;\nexport const MAX_ACTIVE_PINNED_CHATS = 5;\nexport const SCHEDULED_WHEN_ONLINE = 0x7FFFFFFE;\nexport const DEFAULT_LANG_CODE = 'en';\nexport const DEFAULT_LANG_PACK = 'android';\nexport const LANG_PACKS = ['android', 'ios', 'tdesktop', 'macos'] as const;\nexport const TIPS_USERNAME = 'TelegramTips';\nexport const LOCALIZED_TIPS = ['ar', 'pt-br', 'id', 'it', 'ko', 'ms', 'pl', 'es', 'tr'];\nexport const FEEDBACK_URL = 'https://bugs.telegram.org/?tag_ids=41&sort=time';\nexport const LIGHT_THEME_BG_COLOR = '#A2AF8E';\nexport const DARK_THEME_BG_COLOR = '#0F0F0F';\nexport const DARK_THEME_PATTERN_COLOR = '#0a0a0a8c';\nexport const DEFAULT_PATTERN_COLOR = 'rgba(90, 110, 70, 0.6)';\n","type Scheduler =\n typeof requestAnimationFrame\n | typeof onTickEnd\n | typeof runNow;\n\nexport function debounce(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n shouldRunLast = true,\n) {\n let waitingTimeout: number | undefined;\n\n return (...args: Parameters) => {\n if (waitingTimeout) {\n clearTimeout(waitingTimeout);\n waitingTimeout = undefined;\n } else if (shouldRunFirst) {\n // @ts-ignore\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n waitingTimeout = self.setTimeout(() => {\n if (shouldRunLast) {\n // @ts-ignore\n fn(...args);\n }\n\n waitingTimeout = undefined;\n }, ms);\n };\n}\n\nexport function throttle(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n) {\n let interval: number | undefined;\n let isPending: boolean;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n isPending = true;\n args = _args;\n\n if (!interval) {\n if (shouldRunFirst) {\n isPending = false;\n // @ts-ignore\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n interval = self.setInterval(() => {\n if (!isPending) {\n // eslint-disable-next-line no-restricted-globals\n self.clearInterval(interval!);\n interval = undefined;\n return;\n }\n\n isPending = false;\n // @ts-ignore\n fn(...args);\n }, ms);\n }\n };\n}\n\nexport function throttleWithRaf(fn: F) {\n return throttleWith(fastRaf, fn);\n}\n\nexport function throttleWithPrimaryRaf(fn: F) {\n return throttleWith(fastRafPrimary, fn);\n}\n\nexport function throttleWithTickEnd(fn: F) {\n return throttleWith(onTickEnd, fn);\n}\n\nexport function throttleWithNow(fn: F) {\n return throttleWith(runNow, fn);\n}\n\nexport function throttleWith(schedulerFn: Scheduler, fn: F) {\n let waiting = false;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n args = _args;\n\n if (!waiting) {\n waiting = true;\n\n schedulerFn(() => {\n waiting = false;\n // @ts-ignore\n fn(...args);\n });\n }\n };\n}\n\nexport function onIdle(cb: NoneToVoidFunction) {\n // eslint-disable-next-line no-restricted-globals\n if (self.requestIdleCallback) {\n // eslint-disable-next-line no-restricted-globals\n self.requestIdleCallback(cb);\n } else {\n onTickEnd(cb);\n }\n}\n\nfunction runNow(fn: NoneToVoidFunction) {\n fn();\n}\n\nexport const pause = (ms: number) => new Promise((resolve) => {\n setTimeout(() => resolve(), ms);\n});\n\nexport function rafPromise() {\n return new Promise((resolve) => {\n fastRaf(resolve);\n });\n}\n\nlet fastRafCallbacks: NoneToVoidFunction[] | undefined;\nlet fastRafPrimaryCallbacks: NoneToVoidFunction[] | undefined;\n\n// May result in an immediate execution if called from another `requestAnimationFrame` callback\nexport function fastRaf(callback: NoneToVoidFunction, isPrimary = false) {\n if (!fastRafCallbacks) {\n fastRafCallbacks = isPrimary ? [] : [callback];\n fastRafPrimaryCallbacks = isPrimary ? [callback] : [];\n\n requestAnimationFrame(() => {\n const currentCallbacks = fastRafCallbacks!;\n const currentPrimaryCallbacks = fastRafPrimaryCallbacks!;\n fastRafCallbacks = undefined;\n fastRafPrimaryCallbacks = undefined;\n currentPrimaryCallbacks.forEach((cb) => cb());\n currentCallbacks.forEach((cb) => cb());\n });\n } else if (isPrimary) {\n fastRafPrimaryCallbacks!.push(callback);\n } else {\n fastRafCallbacks.push(callback);\n }\n}\n\nexport function fastRafPrimary(callback: NoneToVoidFunction) {\n fastRaf(callback, true);\n}\n\nlet onTickEndCallbacks: NoneToVoidFunction[] | undefined;\nlet onTickEndPrimaryCallbacks: NoneToVoidFunction[] | undefined;\n\nexport function onTickEnd(callback: NoneToVoidFunction, isPrimary = false) {\n if (!onTickEndCallbacks) {\n onTickEndCallbacks = isPrimary ? [] : [callback];\n onTickEndPrimaryCallbacks = isPrimary ? [callback] : [];\n\n Promise.resolve().then(() => {\n const currentCallbacks = onTickEndCallbacks!;\n const currentPrimaryCallbacks = onTickEndPrimaryCallbacks!;\n onTickEndCallbacks = undefined;\n onTickEndPrimaryCallbacks = undefined;\n currentPrimaryCallbacks.forEach((cb) => cb());\n currentCallbacks.forEach((cb) => cb());\n });\n } else if (isPrimary) {\n onTickEndPrimaryCallbacks!.push(callback);\n } else {\n onTickEndCallbacks.push(callback);\n }\n}\n\nexport function onTickEndPrimary(callback: NoneToVoidFunction) {\n onTickEnd(callback, true);\n}\n\nlet beforeUnloadCallbacks: NoneToVoidFunction[] | undefined;\n\nexport function onBeforeUnload(callback: NoneToVoidFunction, isLast = false) {\n if (!beforeUnloadCallbacks) {\n beforeUnloadCallbacks = [];\n // eslint-disable-next-line no-restricted-globals\n self.addEventListener('beforeunload', () => {\n beforeUnloadCallbacks!.forEach((cb) => cb());\n });\n }\n\n if (isLast) {\n beforeUnloadCallbacks.push(callback);\n } else {\n beforeUnloadCallbacks.unshift(callback);\n }\n\n return () => {\n beforeUnloadCallbacks = beforeUnloadCallbacks!.filter((cb) => cb !== callback);\n };\n}\n","type CollectionByKey = Record;\n\ntype OrderDirection = 'asc' | 'desc';\n\ninterface OrderCallback {\n (member: T): any;\n}\n\nexport function buildCollectionByKey(collection: T[], key: keyof T) {\n return collection.reduce((byKey: CollectionByKey, member: T) => {\n byKey[member[key]] = member;\n\n return byKey;\n }, {});\n}\n\nexport function mapValues(\n byKey: CollectionByKey,\n callback: (member: M, key: string, index: number, originalByKey: CollectionByKey) => R,\n): CollectionByKey {\n return Object.keys(byKey).reduce((newByKey: CollectionByKey, key, index) => {\n newByKey[key] = callback(byKey[key], key, index, byKey);\n return newByKey;\n }, {});\n}\n\nexport function pick(object: T, keys: K[]) {\n return keys.reduce((result, key) => {\n result[key] = object[key];\n return result;\n }, {} as Pick);\n}\n\nexport function pickTruthy(object: T, keys: K[]) {\n return keys.reduce((result, key) => {\n if (object[key]) {\n result[key] = object[key];\n }\n\n return result;\n }, {} as Pick);\n}\n\nexport function omit(object: T, keys: K[]) {\n const stringKeys = new Set(keys.map(String));\n const savedKeys = Object.keys(object)\n .filter((key) => !stringKeys.has(key)) as Array>;\n\n return pick(object, savedKeys);\n}\n\nexport function orderBy(\n collection: T[],\n orderKey: (keyof T) | OrderCallback | ((keyof T) | OrderCallback)[],\n mode: OrderDirection | [OrderDirection, OrderDirection] = 'asc',\n): T[] {\n return collection.sort((a, b) => {\n if (Array.isArray(orderKey)) {\n const [mode1, mode2] = Array.isArray(mode) ? mode : [mode, mode];\n const [orderKey1, orderKey2] = orderKey;\n\n let aValue1;\n let bValue1;\n\n if (typeof orderKey1 === 'function') {\n aValue1 = orderKey1(a) || 0;\n bValue1 = orderKey1(b) || 0;\n } else if (typeof orderKey1 === 'string') {\n aValue1 = a[orderKey1] || 0;\n bValue1 = b[orderKey1] || 0;\n }\n\n if (aValue1 !== bValue1) {\n return mode1 === 'asc' ? aValue1 - bValue1 : bValue1 - aValue1;\n } else {\n let aValue2;\n let bValue2;\n\n if (typeof orderKey2 === 'function') {\n aValue2 = orderKey2(a) || 0;\n bValue2 = orderKey2(b) || 0;\n } else if (typeof orderKey2 === 'string') {\n aValue2 = a[orderKey2] || 0;\n bValue2 = b[orderKey2] || 0;\n }\n\n return mode2 === 'asc' ? aValue2 - bValue2 : bValue2 - aValue2;\n }\n }\n\n let aValue;\n let bValue;\n\n if (typeof orderKey === 'function') {\n aValue = orderKey(a) || 0;\n bValue = orderKey(b) || 0;\n } else if (typeof orderKey === 'string') {\n aValue = a[orderKey] || 0;\n bValue = b[orderKey] || 0;\n }\n\n return mode === 'asc' ? aValue - bValue : bValue - aValue;\n });\n}\n\nexport function flatten(array: any[]) {\n return array.reduce((result, member) => {\n if (Array.isArray(member)) {\n return result.concat(member);\n } else {\n result.push(member);\n return result;\n }\n }, []);\n}\n\nexport function unique(array: T[]): T[] {\n return Array.from(new Set(array));\n}\n\nexport function compact(array: any[]) {\n return array.filter(Boolean);\n}\n\nexport function areSortedArraysEqual(array1: any[], array2: any[]) {\n if (array1.length !== array2.length) {\n return false;\n }\n\n return array1.every((item, i) => item === array2[i]);\n}\n\nexport function areSortedArraysIntersecting(array1: any[], array2: any[]) {\n return array1[0] <= array2[array2.length - 1] && array1[array1.length - 1] >= array2[0];\n}\n\nexport function findIntersectionWithSet(array: T[], set: Set): T[] {\n return array.filter((a) => set.has(a));\n}\n\nexport function split(array: any[], chunkSize: number) {\n const result = [];\n for (let i = 0; i < array.length; i += chunkSize) {\n result.push(array.slice(i, i + chunkSize));\n }\n\n return result;\n}\n\nexport function cloneDeep(value: T): T {\n if (typeof value !== 'object') {\n return value;\n }\n\n if (Array.isArray(value)) {\n return value.map(cloneDeep) as typeof value;\n }\n\n return Object.keys(value).reduce((acc, key) => {\n acc[key as keyof T] = cloneDeep(value[key as keyof T]);\n return acc;\n }, {} as T);\n}\n\n/**\n * Returns the index of the last element in the array where predicate is true, and -1 otherwise.\n *\n * @param array The source array to search in\n * @param predicate find calls predicate once for each element of the array, in descending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.\n */\nexport function findLast(array: Array, predicate: (value: T, index: number, obj: T[]) => boolean): T | undefined {\n let cursor = array.length;\n\n while (cursor--) {\n if (predicate(array[cursor], cursor, array)) {\n return array[cursor];\n }\n }\n\n return undefined;\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\n\ntype VirtualFields =\n 'flags'\n | 'CONSTRUCTOR_ID'\n | 'SUBCLASS_OF_ID'\n | 'className'\n | 'classType'\n | 'getBytes';\n\nexport function bytesToDataUri(bytes: Buffer, shouldOmitPrefix = false, mimeType: string = 'image/jpeg') {\n const prefix = shouldOmitPrefix ? '' : `data:${mimeType};base64,`;\n\n return `${prefix}${btoa(String.fromCharCode(...bytes))}`;\n}\n\nexport function omitVirtualClassFields & { flags?: any }>(\n instance: T,\n): Omit {\n const {\n flags,\n CONSTRUCTOR_ID,\n SUBCLASS_OF_ID,\n className,\n classType,\n getBytes,\n ...rest\n } = instance;\n\n return rest;\n}\n","/* eslint-disable no-bitwise */\n\n// eslint-disable-next-line max-len\nconst TEMPLATE = '';\nconst LOOKUP = 'AACAAAAHAAALMAAAQASTAVAAAZaacaaaahaaalmaaaqastava.az0123456789-,';\n\nexport function pathBytesToSvg(bytes: Buffer, width: number, height: number) {\n return TEMPLATE\n .replace('{{path}}', buildPath(bytes))\n .replace('{{width}}', String(width))\n .replace('{{height}}', String(height));\n}\n\nfunction buildPath(bytes: Buffer) {\n let path = 'M';\n\n const len = bytes.length;\n for (let i = 0; i < len; i++) {\n const num = bytes[i];\n if (num >= 128 + 64) {\n path += LOOKUP[num - 128 - 64];\n } else {\n if (num >= 128) {\n path += ',';\n } else if (num >= 64) {\n path += '-';\n }\n path += String(num & 63);\n }\n }\n\n path += 'z';\n\n return path;\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport { strippedPhotoToJpg } from '../../../lib/gramjs/Utils';\n\nimport {\n ApiPhoto, ApiPhotoSize, ApiThumbnail,\n} from '../../types';\nimport { bytesToDataUri } from './helpers';\nimport { pathBytesToSvg } from './pathBytesToSvg';\n\nconst DEFAULT_THUMB_SIZE = { w: 100, h: 100 };\n\nexport function buildApiThumbnailFromStripped(\n sizes?: GramJs.TypePhotoSize[], mimeType?: string,\n): ApiThumbnail | undefined {\n if (!sizes || !sizes.length) {\n return undefined;\n }\n\n const thumb = sizes.find((s: any): s is GramJs.PhotoStrippedSize => s instanceof GramJs.PhotoStrippedSize);\n if (!thumb) {\n return undefined;\n }\n\n const realSizes = sizes.filter((s): s is GramJs.PhotoSize => s instanceof GramJs.PhotoSize);\n const { w, h } = realSizes.length ? realSizes[realSizes.length - 1] : DEFAULT_THUMB_SIZE;\n const { bytes } = thumb;\n const dataUri = bytesToDataUri(\n !mimeType || mimeType === 'image/jpeg' ? strippedPhotoToJpg(bytes) : bytes,\n undefined,\n mimeType,\n );\n\n return {\n dataUri,\n width: w,\n height: h,\n };\n}\n\nexport function buildApiThumbnailFromCached(photoSize: GramJs.PhotoCachedSize): ApiThumbnail | undefined {\n const { w, h, bytes } = photoSize;\n const dataUri = bytesToDataUri(bytes, undefined, 'image/webp');\n\n return {\n dataUri,\n width: w,\n height: h,\n };\n}\n\nexport function buildApiThumbnailFromPath(\n photoSize: GramJs.PhotoPathSize,\n sizeAttribute: GramJs.DocumentAttributeImageSize,\n): ApiThumbnail | undefined {\n const { w, h } = sizeAttribute;\n const dataUri = `data:image/svg+xml;utf8,${pathBytesToSvg(photoSize.bytes, w, h)}`;\n\n return {\n dataUri,\n width: w,\n height: h,\n };\n}\n\nexport function buildApiPhoto(photo: GramJs.Photo): ApiPhoto {\n const sizes = photo.sizes\n .filter((s: any): s is GramJs.PhotoSize => {\n return s instanceof GramJs.PhotoSize || s instanceof GramJs.PhotoSizeProgressive;\n })\n .map(buildApiPhotoSize);\n\n return {\n id: String(photo.id),\n thumbnail: buildApiThumbnailFromStripped(photo.sizes),\n sizes,\n };\n}\n\nexport function buildApiPhotoSize(photoSize: GramJs.PhotoSize): ApiPhotoSize {\n const { w, h, type } = photoSize;\n\n return {\n width: w,\n height: h,\n type: type as ('m' | 'x' | 'y'),\n };\n}\n","import { Api as GramJs } from '../../lib/gramjs';\nimport { ApiMessage } from '../types';\n\ninterface LocalDb {\n localMessages: Record;\n // Used for loading avatars and media through in-memory Gram JS instances.\n chats: Record;\n users: Record;\n messages: Record;\n documents: Record;\n stickerSets: Record;\n photos: Record;\n webDocuments: Record;\n}\n\nexport default {\n localMessages: {},\n chats: {},\n users: {},\n messages: {},\n documents: {},\n stickerSets: {},\n photos: {},\n webDocuments: {},\n} as LocalDb;\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport { ApiSticker, ApiStickerSet } from '../../types';\nimport { MEMOJI_STICKER_ID } from '../../../config';\n\nimport { buildApiThumbnailFromCached, buildApiThumbnailFromPath } from './common';\nimport localDb from '../localDb';\n\nconst ANIMATED_STICKER_MIME_TYPE = 'application/x-tgsticker';\n\nexport function buildStickerFromDocument(document: GramJs.TypeDocument): ApiSticker | undefined {\n if (document instanceof GramJs.DocumentEmpty) {\n return undefined;\n }\n\n const stickerAttribute = document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeSticker => (\n attr instanceof GramJs.DocumentAttributeSticker\n ));\n\n const fileAttribute = document.mimeType === ANIMATED_STICKER_MIME_TYPE && document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeFilename => (\n attr instanceof GramJs.DocumentAttributeFilename\n ));\n\n if (!stickerAttribute && !fileAttribute) {\n return undefined;\n }\n\n const sizeAttribute = document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeImageSize => (\n attr instanceof GramJs.DocumentAttributeImageSize\n ));\n\n const stickerSetInfo = stickerAttribute && stickerAttribute.stickerset instanceof GramJs.InputStickerSetID\n ? stickerAttribute.stickerset\n : undefined;\n const emoji = stickerAttribute?.alt;\n const isAnimated = document.mimeType === ANIMATED_STICKER_MIME_TYPE;\n const cachedThumb = document.thumbs && document.thumbs.find(\n (s): s is GramJs.PhotoCachedSize => s instanceof GramJs.PhotoCachedSize,\n );\n const pathThumb = document.thumbs && document.thumbs.find(\n (s): s is GramJs.PhotoPathSize => s instanceof GramJs.PhotoPathSize,\n );\n const thumbnail = cachedThumb ? (\n buildApiThumbnailFromCached(cachedThumb)\n ) : pathThumb && sizeAttribute ? (\n buildApiThumbnailFromPath(pathThumb, sizeAttribute)\n ) : undefined;\n\n const { w: width, h: height } = cachedThumb as GramJs.PhotoCachedSize || sizeAttribute || {};\n\n return {\n id: String(document.id),\n stickerSetId: stickerSetInfo ? String(stickerSetInfo.id) : MEMOJI_STICKER_ID,\n stickerSetAccessHash: stickerSetInfo && String(stickerSetInfo.accessHash),\n emoji,\n isAnimated,\n width,\n height,\n thumbnail,\n };\n}\n\nexport function buildStickerSet(set: GramJs.StickerSet): ApiStickerSet {\n const {\n archived,\n animated,\n installedDate,\n id,\n accessHash,\n title,\n thumbs,\n count,\n shortName,\n } = set;\n\n return {\n archived,\n isAnimated: animated,\n installedDate,\n id: String(id),\n accessHash: String(accessHash),\n title,\n hasThumbnail: Boolean(thumbs?.length),\n count,\n shortName,\n };\n}\n\nexport function buildStickerSetCovered(coveredStickerSet: GramJs.TypeStickerSetCovered): ApiStickerSet {\n const stickerSet = buildStickerSet(coveredStickerSet.set);\n\n const stickerSetCovers = (coveredStickerSet instanceof GramJs.StickerSetMultiCovered)\n ? coveredStickerSet.covers\n : [coveredStickerSet.cover];\n\n stickerSet.covers = [];\n stickerSetCovers.forEach((cover) => {\n if (cover instanceof GramJs.Document) {\n const coverSticker = buildStickerFromDocument(cover);\n if (coverSticker) {\n stickerSet.covers!.push(coverSticker);\n localDb.documents[String(cover.id)] = cover;\n }\n }\n });\n\n return stickerSet;\n}\n","/* eslint-disable no-bitwise */\n\n// eslint-disable-next-line max-len\n// Ref: https://github.com/telegramdesktop/tdesktop/blob/0743e71ab6b928d2ee5bae1aed991849b1e2b291/Telegram/SourceFiles/data/data_document.cpp#L1018\nexport function decodeWaveform(encoded5bit: Uint8Array) {\n const bitsCount = encoded5bit.length * 8;\n const valuesCount = Math.floor(bitsCount / 5);\n if (!valuesCount) {\n return [];\n }\n\n // Read each 5 bit of encoded5bit as 0-31 unsigned char.\n // We count the index of the byte in which the desired 5-bit sequence starts.\n // And then we read a uint16 starting from that byte to guarantee to get all of those 5 bits.\n //\n // BUT! if it is the last byte we have, we're not allowed to read a uint16 starting with it.\n // Because it will be an overflow (we'll access one byte after the available memory).\n // We see, that only the last 5 bits could start in the last available byte and be problematic.\n // So we read in a general way all the entries in a general way except the last one.\n const result = Array(valuesCount);\n const bitsData = encoded5bit;\n for (let i = 0, l = valuesCount - 1; i !== l; ++i) {\n const byteIndex = Math.floor((i * 5) / 8);\n const bitShift = Math.floor((i * 5) % 8);\n const value = bitsData[byteIndex] + (bitsData[byteIndex + 1] << 8);\n result[i] = ((value >> bitShift) & 0x1F);\n }\n const lastByteIndex = Math.floor(((valuesCount - 1) * 5) / 8);\n const lastBitShift = Math.floor(((valuesCount - 1) * 5) % 8);\n const lastValue = bitsData[lastByteIndex] + (bitsData[lastByteIndex + 1] << 8);\n result[valuesCount - 1] = (lastValue >> lastBitShift) & 0x1F;\n\n return result;\n}\n\nexport function interpolateArray(data: number[], fitCount: number) {\n let peak = 0;\n const newData = new Array(fitCount);\n const springFactor = data.length / fitCount;\n const leftFiller = data[0];\n const rightFiller = data[data.length - 1];\n for (let i = 0; i < fitCount; i++) {\n const idx = Math.floor(i * springFactor);\n const val = ((data[idx - 1] ?? leftFiller) + (data[idx] ?? leftFiller) + (data[idx + 1] ?? rightFiller)) / 3;\n newData[i] = val;\n if (peak < val) {\n peak = val;\n }\n }\n return { data: newData, peak };\n}\n","export interface ApiDimensions {\n width: number;\n height: number;\n}\n\nexport interface ApiPhotoSize extends ApiDimensions {\n type: 's' | 'm' | 'x' | 'y' | 'z';\n}\n\nexport interface ApiThumbnail extends ApiDimensions {\n dataUri: string;\n}\n\nexport interface ApiPhoto {\n id: string;\n thumbnail?: ApiThumbnail;\n sizes: ApiPhotoSize[];\n blobUrl?: string;\n}\n\nexport interface ApiSticker {\n id: string;\n stickerSetId: string;\n stickerSetAccessHash?: string;\n emoji?: string;\n isAnimated: boolean;\n width?: number;\n height?: number;\n thumbnail?: ApiThumbnail;\n isPreloadedGlobally?: boolean;\n}\n\nexport interface ApiStickerSet {\n archived?: true;\n isAnimated?: true;\n installedDate?: number;\n id: string;\n accessHash: string;\n title: string;\n hasThumbnail?: boolean;\n count: number;\n stickers?: ApiSticker[];\n packs?: Record;\n covers?: ApiSticker[];\n shortName: string;\n}\n\nexport interface ApiVideo {\n id: string;\n mimeType: string;\n duration: number;\n fileName: string;\n width?: number;\n height?: number;\n supportsStreaming?: boolean;\n isRound?: boolean;\n isGif?: boolean;\n thumbnail?: ApiThumbnail;\n blobUrl?: string;\n size: number;\n}\n\nexport interface ApiAudio {\n 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 duration: number;\n waveform?: number[];\n}\n\nexport interface ApiDocument {\n id?: string;\n fileName: string;\n size: number;\n timestamp?: number;\n mimeType: string;\n thumbnail?: ApiThumbnail;\n previewBlobUrl?: string;\n mediaType?: 'photo' | 'video';\n mediaSize?: ApiDimensions;\n}\n\nexport interface ApiContact {\n firstName: string;\n lastName: string;\n phoneNumber: string;\n userId: string;\n}\n\nexport interface ApiPollAnswer {\n text: string;\n option: string;\n}\n\nexport interface ApiPollResult {\n isChosen?: true;\n isCorrect?: true;\n option: string;\n votersCount: number;\n}\n\nexport interface ApiPoll {\n id: string;\n summary: {\n closed?: true;\n isPublic?: true;\n multipleChoice?: true;\n quiz?: true;\n question: string;\n answers: ApiPollAnswer[];\n closePeriod?: number;\n closeDate?: number;\n };\n results: {\n results?: ApiPollResult[];\n totalVoters?: number;\n recentVoterIds?: string[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n}\n\nexport interface ApiInvoice {\n text: string;\n title: string;\n photoUrl?: string;\n amount: number;\n currency: string;\n receiptMsgId?: number;\n isTest?: boolean;\n}\n\nexport type ApiNewPoll = {\n summary: ApiPoll['summary'];\n quiz?: {\n correctAnswers: string[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n};\n\nexport interface ApiAction {\n text: string;\n targetUserIds?: string[];\n targetChatId?: string;\n type: 'historyClear' | 'contactSignUp' | 'chatCreate' | 'other';\n photo?: ApiPhoto;\n amount?: number;\n currency?: string;\n translationValues: string[];\n}\n\nexport interface ApiWebPage {\n id: number;\n url: string;\n displayUrl: string;\n type?: string;\n siteName?: string;\n title?: string;\n description?: string;\n photo?: ApiPhoto;\n duration?: number;\n document?: ApiDocument;\n video?: ApiVideo;\n}\n\nexport interface ApiMessageForwardInfo {\n isChannelPost: boolean;\n channelPostId?: number;\n isLinkedChannelPost?: boolean;\n fromChatId?: string;\n senderUserId?: string;\n fromMessageId?: number;\n hiddenUserName?: string;\n adminTitle?: string;\n}\n\nexport interface ApiMessageEntity {\n type: string;\n offset: number;\n length: number;\n userId?: string;\n url?: string;\n}\n\nexport enum ApiMessageEntityTypes {\n Bold = 'MessageEntityBold',\n Blockquote = 'MessageEntityBlockquote',\n BotCommand = 'MessageEntityBotCommand',\n Cashtag = 'MessageEntityCashtag',\n Code = 'MessageEntityCode',\n Email = 'MessageEntityEmail',\n Hashtag = 'MessageEntityHashtag',\n Italic = 'MessageEntityItalic',\n MentionName = 'MessageEntityMentionName',\n Mention = 'MessageEntityMention',\n Phone = 'MessageEntityPhone',\n Pre = 'MessageEntityPre',\n Strike = 'MessageEntityStrike',\n TextUrl = 'MessageEntityTextUrl',\n Url = 'MessageEntityUrl',\n Underline = 'MessageEntityUnderline',\n Unknown = 'MessageEntityUnknown',\n}\n\nexport interface ApiFormattedText {\n text: string;\n entities?: ApiMessageEntity[];\n}\n\nexport interface ApiMessage {\n id: number;\n chatId: string;\n content: {\n text?: ApiFormattedText;\n photo?: ApiPhoto;\n video?: ApiVideo;\n document?: ApiDocument;\n sticker?: ApiSticker;\n contact?: ApiContact;\n poll?: ApiPoll;\n action?: ApiAction;\n webPage?: ApiWebPage;\n audio?: ApiAudio;\n voice?: ApiVoice;\n invoice?: ApiInvoice;\n };\n date: number;\n isOutgoing: boolean;\n senderId?: string;\n replyToChatId?: string;\n replyToMessageId?: number;\n replyToTopMessageId?: number;\n sendingState?: 'messageSendingStatePending' | 'messageSendingStateFailed';\n forwardInfo?: ApiMessageForwardInfo;\n isDeleting?: boolean;\n previousLocalId?: number;\n views?: number;\n isEdited?: boolean;\n 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}\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 interface ApiKeyboardButton {\n type: 'command' | 'url' | 'callback' | 'requestPoll' | 'buy' | 'NOT_SUPPORTED';\n text: string;\n messageId: number;\n value?: string;\n}\n\nexport type ApiKeyboardButtons = ApiKeyboardButton[][];\nexport type ApiReplyKeyboard = {\n keyboardPlaceholder?: string;\n isKeyboardSingleUse?: boolean;\n} & {\n [K in 'inlineButtons' | 'keyboardButtons']?: ApiKeyboardButtons;\n};\n\nexport type ApiMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'voice' | 'profilePhoto';\nexport type ApiGlobalMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'voice';\n\nexport type ApiReportReason = 'spam' | 'violence' | 'pornography' | 'childAbuse'\n| 'copyright' | 'geoIrrelevant' | 'fake' | 'other';\n\nexport const MAIN_THREAD_ID = -1;\n\n// `Symbol` can not be transferred from worker\nexport const MESSAGE_DELETED = 'MESSAGE_DELETED';\n","// We cache avatars as Data URI for faster initial load\n// and messages media as Blob for smaller size.\n\nexport enum ApiMediaFormat {\n BlobUrl,\n Lottie,\n Progressive,\n Stream,\n}\n\nexport type ApiParsedMedia = string | Blob | AnyLiteral | ArrayBuffer;\nexport type ApiPreparedMedia = string | AnyLiteral;\nexport type ApiMediaFormatToPrepared = T extends ApiMediaFormat.Lottie ? AnyLiteral : string;\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\n\nimport { ApiPrivacyKey } from '../../../types';\n\nimport { generateRandomBytes, readBigIntFromBuffer } from '../../../lib/gramjs/Helpers';\nimport {\n ApiSticker,\n ApiVideo,\n ApiNewPoll,\n ApiMessageEntity,\n ApiMessageEntityTypes,\n ApiChatFolder,\n ApiChatBannedRights,\n ApiChatAdminRights,\n ApiReportReason,\n} from '../../types';\nimport localDb from '../localDb';\nimport { pick } from '../../../util/iteratees';\n\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 }) => new GramJs.PollAnswer({ text, option: Buffer.from(option) })),\n quiz: summary.quiz,\n multipleChoice: summary.multipleChoice,\n });\n\n if (!quiz) {\n return new GramJs.InputMediaPoll({ poll });\n }\n\n const correctAnswers = quiz.correctAnswers.map((key) => Buffer.from(key));\n const { solution } = quiz;\n const solutionEntities = quiz.solutionEntities ? quiz.solutionEntities.map(buildMtpMessageEntity) : [];\n\n return new GramJs.InputMediaPoll({\n poll,\n correctAnswers,\n ...(solution && {\n solution,\n solutionEntities,\n }),\n });\n}\n\nexport function buildFilterFromApiFolder(folder: ApiChatFolder): GramJs.DialogFilter {\n const {\n emoticon,\n contacts,\n nonContacts,\n groups,\n channels,\n bots,\n excludeArchived,\n excludeMuted,\n excludeRead,\n pinnedChatIds,\n includedChatIds,\n excludedChatIds,\n } = folder;\n\n const pinnedPeers = pinnedChatIds\n ? pinnedChatIds.map(buildInputPeerFromLocalDb).filter(Boolean as any)\n : [];\n\n const includePeers = includedChatIds\n ? includedChatIds.map(buildInputPeerFromLocalDb).filter(Boolean as any)\n : [];\n\n const excludePeers = excludedChatIds\n ? excludedChatIds.map(buildInputPeerFromLocalDb).filter(Boolean as any)\n : [];\n\n return new GramJs.DialogFilter({\n id: folder.id,\n title: folder.title,\n emoticon: emoticon || undefined,\n contacts: contacts || undefined,\n nonContacts: nonContacts || undefined,\n groups: groups || undefined,\n bots: bots || undefined,\n excludeArchived: excludeArchived || undefined,\n excludeMuted: excludeMuted || undefined,\n excludeRead: excludeRead || undefined,\n broadcasts: channels || undefined,\n pinnedPeers,\n includePeers,\n excludePeers,\n });\n}\n\nexport function generateRandomBigInt() {\n return readBigIntFromBuffer(generateRandomBytes(8), true, true);\n}\n\nexport function buildMessageFromUpdate(\n id: number,\n chatId: string,\n update: GramJs.UpdateShortSentMessage | GramJs.UpdateServiceNotification,\n) {\n // This is not a proper message, but we only need these fields for downloading media through `localDb`.\n return new GramJs.Message({\n id,\n peerId: buildPeer(chatId),\n fromId: buildPeer(chatId),\n media: update.media,\n } as GramJs.Message);\n}\n\nexport function buildMtpMessageEntity(entity: ApiMessageEntity): GramJs.TypeMessageEntity {\n const {\n type, offset, length, url, userId,\n } = entity;\n\n const user = userId ? localDb.users[userId] : undefined;\n\n switch (type) {\n case ApiMessageEntityTypes.Bold:\n return new GramJs.MessageEntityBold({ offset, length });\n case ApiMessageEntityTypes.Italic:\n return new GramJs.MessageEntityItalic({ offset, length });\n case ApiMessageEntityTypes.Underline:\n return new GramJs.MessageEntityUnderline({ offset, length });\n case ApiMessageEntityTypes.Strike:\n return new GramJs.MessageEntityStrike({ offset, length });\n case ApiMessageEntityTypes.Code:\n return new GramJs.MessageEntityCode({ offset, length });\n case ApiMessageEntityTypes.Pre:\n return new GramJs.MessageEntityPre({ offset, length, language: '' });\n case ApiMessageEntityTypes.Blockquote:\n return new GramJs.MessageEntityBlockquote({ offset, length });\n case ApiMessageEntityTypes.TextUrl:\n return new GramJs.MessageEntityTextUrl({ offset, length, url: url! });\n case ApiMessageEntityTypes.Url:\n return new GramJs.MessageEntityUrl({ offset, length });\n case ApiMessageEntityTypes.Hashtag:\n return new GramJs.MessageEntityHashtag({ offset, length });\n case ApiMessageEntityTypes.MentionName:\n return new GramJs.InputMessageEntityMentionName({\n offset,\n length,\n userId: new GramJs.InputUser({ userId: BigInt(userId!), accessHash: user!.accessHash! }),\n });\n default:\n return new GramJs.MessageEntityUnknown({ offset, length });\n }\n}\n\nexport function isMessageWithMedia(message: GramJs.Message | GramJs.UpdateServiceNotification) {\n const { media } = message;\n if (!media) {\n return false;\n }\n\n return (\n media instanceof GramJs.MessageMediaPhoto\n || media instanceof GramJs.MessageMediaDocument\n || (\n media instanceof GramJs.MessageMediaWebPage\n && media.webpage instanceof GramJs.WebPage\n && (\n media.webpage.photo instanceof GramJs.Photo || (\n media.webpage.document instanceof GramJs.Document\n && media.webpage.document.mimeType.startsWith('video')\n )\n )\n )\n );\n}\n\nexport function isServiceMessageWithMedia(message: GramJs.MessageService) {\n return 'photo' in message.action && message.action.photo instanceof GramJs.Photo;\n}\n\nexport function buildChatPhotoForLocalDb(photo: GramJs.TypePhoto) {\n if (photo instanceof GramJs.PhotoEmpty) {\n return new GramJs.ChatPhotoEmpty();\n }\n\n const { dcId, id: photoId } = photo;\n\n return new GramJs.ChatPhoto({\n dcId,\n photoId,\n });\n}\n\nexport function buildInputContact({\n phone,\n firstName,\n lastName,\n}: {\n phone: string;\n firstName: string;\n lastName: string;\n}) {\n return new GramJs.InputPhoneContact({\n clientId: BigInt(1),\n phone,\n firstName,\n lastName,\n });\n}\n\nexport function buildChatBannedRights(\n bannedRights: ApiChatBannedRights,\n untilDate = 0,\n) {\n return new GramJs.ChatBannedRights({\n ...bannedRights,\n untilDate,\n });\n}\n\nexport function buildChatAdminRights(\n adminRights: ApiChatAdminRights,\n) {\n return new GramJs.ChatAdminRights(adminRights);\n}\n\nexport function buildShippingInfo(info: GramJs.PaymentRequestedInfo) {\n const { shippingAddress } = info;\n return new GramJs.PaymentRequestedInfo({\n ...info,\n shippingAddress: shippingAddress\n ? new GramJs.PostAddress(shippingAddress)\n : undefined,\n });\n}\n\nexport function buildInputPrivacyKey(privacyKey: ApiPrivacyKey) {\n switch (privacyKey) {\n case 'phoneNumber':\n return new GramJs.InputPrivacyKeyPhoneNumber();\n\n case 'lastSeen':\n return new GramJs.InputPrivacyKeyStatusTimestamp();\n\n case 'profilePhoto':\n return new GramJs.InputPrivacyKeyProfilePhoto();\n\n case 'forwards':\n return new GramJs.InputPrivacyKeyForwards();\n\n case 'chatInvite':\n return new GramJs.InputPrivacyKeyChatInvite();\n }\n\n return undefined;\n}\n\nexport function buildInputReportReason(reason: ApiReportReason) {\n switch (reason) {\n case 'spam':\n return new GramJs.InputReportReasonSpam();\n case 'violence':\n return new GramJs.InputReportReasonViolence();\n case 'childAbuse':\n return new GramJs.InputReportReasonChildAbuse();\n case 'pornography':\n return new GramJs.InputReportReasonPornography();\n case 'copyright':\n return new GramJs.InputReportReasonCopyright();\n case 'fake':\n return new GramJs.InputReportReasonFake();\n case 'geoIrrelevant':\n return new GramJs.InputReportReasonGeoIrrelevant();\n case 'other':\n return new GramJs.InputReportReasonOther();\n }\n\n return undefined;\n}\n\nexport function 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","import BigInt from 'big-integer';\n\nimport { Api as GramJs } from '../../../lib/gramjs';\n\nexport function isPeerUser(peer: GramJs.TypePeer | GramJs.TypeInputPeer): peer is GramJs.PeerUser {\n return peer.hasOwnProperty('userId');\n}\n\nexport function isPeerChat(peer: GramJs.TypePeer | GramJs.TypeInputPeer): peer is GramJs.PeerChat {\n return peer.hasOwnProperty('chatId');\n}\n\nexport function isPeerChannel(peer: GramJs.TypePeer | GramJs.TypeInputPeer): peer is GramJs.PeerChannel {\n return peer.hasOwnProperty('channelId');\n}\n\nexport function buildApiPeerId(id: BigInt.BigInteger, type: 'user' | 'chat' | 'channel') {\n return type === 'user' ? String(id) : `-${id}`;\n}\n\nexport function getApiChatIdFromMtpPeer(peer: GramJs.TypePeer | GramJs.TypeInputPeer) {\n if (isPeerUser(peer)) {\n return buildApiPeerId(peer.userId, 'user');\n } else if (isPeerChat(peer)) {\n return buildApiPeerId(peer.chatId, 'chat');\n } else {\n return buildApiPeerId((peer as GramJs.InputPeerChannel).channelId, 'channel');\n }\n}\n","import { Api as GramJs } from '../../lib/gramjs';\nimport localDb from './localDb';\nimport { buildApiPeerId, getApiChatIdFromMtpPeer } from './apiBuilders/peers';\n\nexport function resolveMessageApiChatId(mtpMessage: GramJs.TypeMessage) {\n if (!(mtpMessage instanceof GramJs.Message || mtpMessage instanceof GramJs.MessageService)) {\n return undefined;\n }\n\n return getApiChatIdFromMtpPeer(mtpMessage.peerId);\n}\n\nexport function addMessageToLocalDb(message: GramJs.Message | GramJs.MessageService) {\n const messageFullId = `${resolveMessageApiChatId(message)}-${message.id}`;\n localDb.messages[messageFullId] = message;\n\n if (\n message instanceof GramJs.Message\n && message.media instanceof GramJs.MessageMediaDocument\n && message.media.document instanceof GramJs.Document\n ) {\n localDb.documents[String(message.media.document.id)] = message.media.document;\n }\n\n if (\n message instanceof GramJs.Message\n && message.media instanceof GramJs.MessageMediaWebPage\n && message.media.webpage instanceof GramJs.WebPage\n && message.media.webpage.document instanceof GramJs.Document\n ) {\n localDb.documents[String(message.media.webpage.document.id)] = message.media.webpage.document;\n }\n\n if (message instanceof GramJs.MessageService && 'photo' in message.action) {\n addPhotoToLocalDb(message.action.photo);\n }\n}\n\nexport function addPhotoToLocalDb(photo: GramJs.TypePhoto) {\n if (photo instanceof GramJs.Photo) {\n localDb.photos[String(photo.id)] = photo;\n }\n}\n\nexport function addChatToLocalDb(chat: GramJs.TypeChat) {\n if (chat instanceof GramJs.Chat || chat instanceof GramJs.Channel) {\n localDb.chats[buildApiPeerId(chat.id, chat instanceof GramJs.Chat ? 'chat' : 'channel')] = chat;\n }\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n ApiMessage,\n ApiMessageForwardInfo,\n ApiPhoto,\n ApiSticker,\n ApiVideo,\n ApiVoice,\n ApiAudio,\n ApiDocument,\n ApiAction,\n ApiContact,\n ApiAttachment,\n ApiPoll,\n ApiNewPoll,\n ApiWebPage,\n ApiMessageEntity,\n ApiFormattedText,\n ApiReplyKeyboard,\n ApiKeyboardButton,\n ApiChat,\n ApiThreadInfo,\n ApiInvoice,\n} from '../../types';\n\nimport {\n DELETED_COMMENTS_CHANNEL_ID,\n LOCAL_MESSAGE_ID_BASE,\n SERVICE_NOTIFICATIONS_USER_ID,\n SUPPORTED_IMAGE_CONTENT_TYPES,\n SUPPORTED_VIDEO_CONTENT_TYPES,\n VIDEO_MOV_TYPE,\n} from '../../../config';\nimport { pick } from '../../../util/iteratees';\nimport { buildStickerFromDocument } from './symbols';\nimport { buildApiPhoto, buildApiPhotoSize, buildApiThumbnailFromStripped } from './common';\nimport { interpolateArray } from '../../../util/waveform';\nimport { buildPeer } from '../gramjsBuilders';\nimport { addPhotoToLocalDb, resolveMessageApiChatId } from '../helpers';\nimport { buildApiPeerId, getApiChatIdFromMtpPeer } from './peers';\n\nconst LOCAL_MEDIA_UPLOADING_TEMP_ID = 'temp';\nconst INPUT_WAVEFORM_LENGTH = 63;\n\nlet localMessageCounter = LOCAL_MESSAGE_ID_BASE;\nlet currentUserId!: string;\n\nexport function setMessageBuilderCurrentUserId(_currentUserId: string) {\n currentUserId = _currentUserId;\n}\n\nexport function buildApiMessage(mtpMessage: GramJs.TypeMessage): ApiMessage | undefined {\n const chatId = resolveMessageApiChatId(mtpMessage);\n if (\n !chatId\n || !(mtpMessage instanceof GramJs.Message || mtpMessage instanceof GramJs.MessageService)) {\n return undefined;\n }\n\n return buildApiMessageWithChatId(chatId, mtpMessage);\n}\n\nexport function buildApiMessageFromShort(mtpMessage: GramJs.UpdateShortMessage): ApiMessage {\n const chatId = buildApiPeerId(mtpMessage.userId, 'user');\n\n return buildApiMessageWithChatId(chatId, {\n ...mtpMessage,\n fromId: buildPeer(mtpMessage.out ? currentUserId : buildApiPeerId(mtpMessage.userId, 'user')),\n });\n}\n\nexport function buildApiMessageFromShortChat(mtpMessage: GramJs.UpdateShortChatMessage): ApiMessage {\n const chatId = buildApiPeerId(mtpMessage.chatId, 'chat');\n\n return buildApiMessageWithChatId(chatId, {\n ...mtpMessage,\n fromId: buildPeer(buildApiPeerId(mtpMessage.fromId, 'user')),\n });\n}\n\nexport function buildApiMessageFromNotification(\n notification: GramJs.UpdateServiceNotification,\n currentDate: number,\n): ApiMessage {\n const localId = localMessageCounter++;\n let content: ApiMessage['content'] = {};\n\n if (notification.media) {\n content = {\n ...buildMessageMediaContent(notification.media),\n };\n }\n\n if (notification.message && !content.sticker && !content.poll && !content.contact) {\n content = {\n ...content,\n text: buildMessageTextContent(notification.message, notification.entities),\n };\n }\n\n return {\n id: localId,\n chatId: SERVICE_NOTIFICATIONS_USER_ID,\n date: notification.inboxDate || currentDate,\n content,\n isOutgoing: false,\n };\n}\n\ntype UniversalMessage = (\n Pick\n & Pick, (\n 'out' | 'message' | 'entities' | 'fromId' | 'peerId' | 'fwdFrom' | 'replyTo' | 'replyMarkup' | 'post' |\n 'media' | 'action' | 'views' | 'editDate' | 'editHide' | 'mediaUnread' | 'groupedId' | 'mentioned' | 'viaBotId' |\n 'replies' | 'fromScheduled' | 'postAuthor'\n )>\n);\n\nexport function buildApiMessageWithChatId(chatId: string, mtpMessage: UniversalMessage): ApiMessage {\n const fromId = mtpMessage.fromId ? getApiChatIdFromMtpPeer(mtpMessage.fromId) : undefined;\n const peerId = mtpMessage.peerId ? getApiChatIdFromMtpPeer(mtpMessage.peerId) : undefined;\n const isChatWithSelf = !fromId && chatId === currentUserId;\n const isOutgoing = (mtpMessage.out && !mtpMessage.post) || (isChatWithSelf && !mtpMessage.fwdFrom);\n\n let content: ApiMessage['content'] = {};\n\n if (mtpMessage.media) {\n content = {\n ...buildMessageMediaContent(mtpMessage.media),\n };\n }\n\n if (mtpMessage.message && !content.sticker && !content.poll && !content.contact) {\n content = {\n ...content,\n text: buildMessageTextContent(mtpMessage.message, mtpMessage.entities),\n };\n }\n\n const action = mtpMessage.action\n && buildAction(mtpMessage.action, fromId, peerId, Boolean(mtpMessage.post), isOutgoing);\n if (action) {\n content.action = action;\n }\n\n const { replyToMsgId, replyToTopId, replyToPeerId } = mtpMessage.replyTo || {};\n const isEdited = mtpMessage.editDate && !mtpMessage.editHide;\n const {\n inlineButtons, keyboardButtons, keyboardPlaceholder, isKeyboardSingleUse,\n } = buildReplyButtons(mtpMessage) || {};\n const forwardInfo = mtpMessage.fwdFrom && buildApiMessageForwardInfo(mtpMessage.fwdFrom, isChatWithSelf);\n const { replies, mediaUnread: isMediaUnread, postAuthor } = mtpMessage;\n const groupedId = mtpMessage.groupedId && String(mtpMessage.groupedId);\n const isInAlbum = Boolean(groupedId) && !(content.document || content.audio);\n const shouldHideKeyboardButtons = mtpMessage.replyMarkup instanceof GramJs.ReplyKeyboardHide;\n\n return {\n id: mtpMessage.id,\n chatId,\n isOutgoing,\n content,\n date: mtpMessage.date,\n senderId: fromId || (mtpMessage.out && mtpMessage.post && currentUserId) || chatId,\n views: mtpMessage.views,\n isFromScheduled: mtpMessage.fromScheduled,\n ...(replyToMsgId && { replyToMessageId: replyToMsgId }),\n ...(replyToPeerId && { replyToChatId: getApiChatIdFromMtpPeer(replyToPeerId) }),\n ...(replyToTopId && { replyToTopMessageId: replyToTopId }),\n ...(forwardInfo && { forwardInfo }),\n ...(isEdited && { isEdited }),\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 };\n}\n\nexport function buildMessageTextContent(\n message: string,\n entities?: GramJs.TypeMessageEntity[],\n): ApiFormattedText {\n return {\n text: message,\n ...(entities && { entities: entities.map(buildApiMessageEntity) }),\n };\n}\n\nexport function buildMessageDraft(draft: GramJs.TypeDraftMessage) {\n if (draft instanceof GramJs.DraftMessageEmpty) {\n return undefined;\n }\n\n const {\n message, entities, replyToMsgId, date,\n } = draft;\n\n return {\n formattedText: message ? buildMessageTextContent(message, entities) : undefined,\n replyingToId: replyToMsgId,\n date,\n };\n}\n\nexport function buildMessageMediaContent(media: GramJs.TypeMessageMedia): ApiMessage['content'] | undefined {\n if ('ttlSeconds' in media && media.ttlSeconds) {\n return undefined;\n }\n\n const sticker = buildSticker(media);\n if (sticker) return { sticker };\n\n const photo = buildPhoto(media);\n if (photo) return { photo };\n\n const video = buildVideo(media);\n if (video) return { video };\n\n const audio = buildAudio(media);\n if (audio) return { audio };\n\n const voice = buildVoice(media);\n if (voice) return { voice };\n\n const document = buildDocumentFromMedia(media);\n if (document) return { document };\n\n const contact = buildContact(media);\n if (contact) return { contact };\n\n const poll = buildPollFromMedia(media);\n if (poll) return { poll };\n\n const webPage = buildWebPage(media);\n if (webPage) return { webPage };\n\n const invoice = buildInvoiceFromMedia(media);\n if (invoice) return { invoice };\n\n return undefined;\n}\n\nfunction buildApiMessageForwardInfo(fwdFrom: GramJs.MessageFwdHeader, isChatWithSelf = false): ApiMessageForwardInfo {\n const savedFromPeerId = fwdFrom.savedFromPeer && getApiChatIdFromMtpPeer(fwdFrom.savedFromPeer);\n const fromId = fwdFrom.fromId && getApiChatIdFromMtpPeer(fwdFrom.fromId);\n\n return {\n isChannelPost: Boolean(fwdFrom.channelPost),\n channelPostId: fwdFrom.channelPost,\n isLinkedChannelPost: Boolean(fwdFrom.channelPost && savedFromPeerId && !isChatWithSelf),\n fromChatId: savedFromPeerId || fromId,\n fromMessageId: fwdFrom.channelPost || fwdFrom.savedFromMsgId,\n senderUserId: fromId,\n hiddenUserName: fwdFrom.fromName,\n adminTitle: fwdFrom.postAuthor,\n };\n}\n\nfunction buildSticker(media: GramJs.TypeMessageMedia): ApiSticker | undefined {\n if (\n !(media instanceof GramJs.MessageMediaDocument)\n || !media.document\n || !(media.document instanceof GramJs.Document)\n ) {\n return undefined;\n }\n\n return buildStickerFromDocument(media.document);\n}\n\nfunction buildPhoto(media: GramJs.TypeMessageMedia): ApiPhoto | undefined {\n if (!(media instanceof GramJs.MessageMediaPhoto) || !media.photo || !(media.photo instanceof GramJs.Photo)) {\n return undefined;\n }\n\n return buildApiPhoto(media.photo);\n}\n\nexport function buildVideoFromDocument(document: GramJs.Document): ApiVideo | undefined {\n if (document instanceof GramJs.DocumentEmpty) {\n return undefined;\n }\n\n const {\n id, mimeType, thumbs, size, attributes,\n } = document;\n\n // eslint-disable-next-line no-restricted-globals\n if (mimeType === VIDEO_MOV_TYPE && !(self as any).isMovSupported) {\n return undefined;\n }\n\n const videoAttr = attributes\n .find((a: any): a is GramJs.DocumentAttributeVideo => a instanceof GramJs.DocumentAttributeVideo);\n\n if (!videoAttr) {\n return undefined;\n }\n\n const gifAttr = attributes\n .find((a: any): a is GramJs.DocumentAttributeAnimated => a instanceof GramJs.DocumentAttributeAnimated);\n\n const {\n duration,\n w: width,\n h: height,\n supportsStreaming = false,\n roundMessage: isRound = false,\n } = videoAttr;\n\n return {\n id: String(id),\n mimeType,\n duration,\n fileName: getFilenameFromDocument(document, 'video'),\n width,\n height,\n supportsStreaming,\n isRound,\n isGif: Boolean(gifAttr),\n thumbnail: buildApiThumbnailFromStripped(thumbs),\n size,\n };\n}\n\nfunction buildVideo(media: GramJs.TypeMessageMedia): ApiVideo | undefined {\n if (\n !(media instanceof GramJs.MessageMediaDocument)\n || !(media.document instanceof GramJs.Document)\n || !media.document.mimeType.startsWith('video')\n ) {\n return undefined;\n }\n\n return buildVideoFromDocument(media.document);\n}\n\nfunction buildAudio(media: GramJs.TypeMessageMedia): ApiAudio | undefined {\n if (\n !(media instanceof GramJs.MessageMediaDocument)\n || !media.document\n || !(media.document instanceof GramJs.Document)\n ) {\n return undefined;\n }\n\n const audioAttribute = media.document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeAudio => (\n attr instanceof GramJs.DocumentAttributeAudio\n ));\n\n if (!audioAttribute || audioAttribute.voice) {\n return undefined;\n }\n\n const thumbnailSizes = media.document.thumbs && media.document.thumbs\n .filter((thumb): thumb is GramJs.PhotoSize => thumb instanceof GramJs.PhotoSize)\n .map((thumb) => buildApiPhotoSize(thumb));\n\n return {\n fileName: getFilenameFromDocument(media.document, 'audio'),\n thumbnailSizes,\n ...pick(media.document, ['size', 'mimeType']),\n ...pick(audioAttribute, ['duration', 'performer', 'title']),\n };\n}\n\nfunction buildVoice(media: GramJs.TypeMessageMedia): ApiVoice | undefined {\n if (\n !(media instanceof GramJs.MessageMediaDocument)\n || !media.document\n || !(media.document instanceof GramJs.Document)\n ) {\n return undefined;\n }\n\n const audioAttribute = media.document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeAudio => (\n attr instanceof GramJs.DocumentAttributeAudio\n ));\n\n if (!audioAttribute || !audioAttribute.voice) {\n return undefined;\n }\n\n const { duration, waveform } = audioAttribute;\n\n return {\n duration,\n waveform: waveform ? Array.from(waveform) : undefined,\n };\n}\n\nfunction buildDocumentFromMedia(media: GramJs.TypeMessageMedia) {\n if (!(media instanceof GramJs.MessageMediaDocument) || !media.document) {\n return undefined;\n }\n\n return buildApiDocument(media.document);\n}\n\nexport function buildApiDocument(document: GramJs.TypeDocument): ApiDocument | undefined {\n if (!(document instanceof GramJs.Document)) {\n return undefined;\n }\n\n const {\n id, size, mimeType, date, thumbs, attributes,\n } = document;\n\n const thumbnail = thumbs && buildApiThumbnailFromStripped(thumbs);\n\n let mediaType: ApiDocument['mediaType'] | undefined;\n let mediaSize: ApiDocument['mediaSize'] | undefined;\n const photoSize = thumbs && thumbs.find((s: any): s is GramJs.PhotoSize => s instanceof GramJs.PhotoSize);\n if (photoSize) {\n mediaSize = {\n width: photoSize.w,\n height: photoSize.h,\n };\n\n if (SUPPORTED_IMAGE_CONTENT_TYPES.has(mimeType)) {\n mediaType = 'photo';\n\n const imageAttribute = attributes\n .find((a: any): a is GramJs.DocumentAttributeImageSize => a instanceof GramJs.DocumentAttributeImageSize);\n\n if (imageAttribute) {\n const { w: width, h: height } = imageAttribute;\n mediaSize = {\n width,\n height,\n };\n }\n } else if (SUPPORTED_VIDEO_CONTENT_TYPES.has(mimeType)) {\n mediaType = 'video';\n }\n }\n\n return {\n id: String(id),\n size,\n mimeType,\n timestamp: date,\n fileName: getFilenameFromDocument(document),\n thumbnail,\n mediaType,\n mediaSize,\n };\n}\n\nfunction buildContact(media: GramJs.TypeMessageMedia): ApiContact | undefined {\n if (!(media instanceof GramJs.MessageMediaContact)) {\n return undefined;\n }\n\n const {\n firstName, lastName, phoneNumber, userId,\n } = media;\n\n return {\n firstName, lastName, phoneNumber, userId: buildApiPeerId(userId, 'user'),\n };\n}\n\nfunction buildPollFromMedia(media: GramJs.TypeMessageMedia): ApiPoll | undefined {\n if (!(media instanceof GramJs.MessageMediaPoll)) {\n return undefined;\n }\n\n return buildPoll(media.poll, media.results);\n}\n\nfunction buildInvoiceFromMedia(media: GramJs.TypeMessageMedia): ApiInvoice | undefined {\n if (!(media instanceof GramJs.MessageMediaInvoice)) {\n return undefined;\n }\n\n return buildInvoice(media);\n}\n\nexport function buildPoll(poll: GramJs.Poll, pollResults: GramJs.PollResults): ApiPoll {\n const { id, answers: rawAnswers } = poll;\n const answers = rawAnswers.map((answer) => ({\n text: answer.text,\n option: String.fromCharCode(...answer.option),\n }));\n\n return {\n id: String(id),\n summary: {\n isPublic: poll.publicVoters,\n ...pick(poll, [\n 'closed',\n 'multipleChoice',\n 'quiz',\n 'question',\n 'closePeriod',\n 'closeDate',\n ]),\n answers,\n },\n results: buildPollResults(pollResults),\n };\n}\n\nexport function buildInvoice(media: GramJs.MessageMediaInvoice): ApiInvoice {\n const {\n description: text, title, photo, test, totalAmount, currency, receiptMsgId,\n } = media;\n\n return {\n text,\n title,\n photoUrl: photo?.url,\n receiptMsgId,\n amount: Number(totalAmount),\n currency,\n isTest: test,\n };\n}\n\nexport function buildPollResults(pollResults: GramJs.PollResults): ApiPoll['results'] {\n const {\n results: rawResults, totalVoters, recentVoters, solution, solutionEntities: entities,\n } = pollResults;\n const results = rawResults && rawResults.map(({\n option, chosen, correct, voters,\n }) => ({\n isChosen: chosen,\n isCorrect: correct,\n option: String.fromCharCode(...option),\n votersCount: voters,\n }));\n\n return {\n totalVoters,\n recentVoterIds: recentVoters?.map((id) => buildApiPeerId(id, 'user')),\n results,\n solution,\n ...(entities && { solutionEntities: entities.map(buildApiMessageEntity) }),\n };\n}\n\nexport function buildWebPage(media: GramJs.TypeMessageMedia): ApiWebPage | undefined {\n if (\n !(media instanceof GramJs.MessageMediaWebPage)\n || !(media.webpage instanceof GramJs.WebPage)\n ) {\n return undefined;\n }\n\n const { id, photo, document } = media.webpage;\n\n let video;\n if (document instanceof GramJs.Document && document.mimeType.startsWith('video/')) {\n video = buildVideoFromDocument(document);\n }\n\n return {\n id: Number(id),\n ...pick(media.webpage, [\n 'url',\n 'displayUrl',\n 'type',\n 'siteName',\n 'title',\n 'description',\n 'duration',\n ]),\n photo: photo instanceof GramJs.Photo ? buildApiPhoto(photo) : undefined,\n document: !video && document ? buildApiDocument(document) : undefined,\n video,\n };\n}\n\nfunction buildAction(\n action: GramJs.TypeMessageAction,\n senderId: string | undefined,\n targetPeerId: string | undefined,\n isChannelPost: boolean,\n isOutgoing: boolean,\n): ApiAction | undefined {\n if (action instanceof GramJs.MessageActionEmpty) {\n return undefined;\n }\n\n let amount: number | undefined;\n let currency: string | undefined;\n let text: string;\n const translationValues = [];\n let type: ApiAction['type'] = 'other';\n let photo: ApiPhoto | undefined;\n\n const targetUserIds = 'users' in action\n ? action.users && action.users.map((id) => buildApiPeerId(id, 'user'))\n : ('userId' in action && [buildApiPeerId(action.userId, 'user')]) || [];\n let targetChatId: string | undefined;\n\n if (action instanceof GramJs.MessageActionChatCreate) {\n text = 'Notification.CreatedChatWithTitle';\n translationValues.push('%action_origin%', action.title);\n type = 'chatCreate';\n } else if (action instanceof GramJs.MessageActionChatEditTitle) {\n if (isChannelPost) {\n text = 'Channel.MessageTitleUpdated';\n translationValues.push(action.title);\n } else {\n text = 'Notification.ChangedGroupName';\n translationValues.push('%action_origin%', action.title);\n }\n } else if (action instanceof GramJs.MessageActionChatEditPhoto) {\n if (isChannelPost) {\n text = 'Channel.MessagePhotoUpdated';\n } else {\n text = 'Notification.ChangedGroupPhoto';\n translationValues.push('%action_origin%');\n }\n } else if (action instanceof GramJs.MessageActionChatDeletePhoto) {\n if (isChannelPost) {\n text = 'Channel.MessagePhotoRemoved';\n } else {\n text = 'Group.MessagePhotoRemoved';\n }\n } else if (action instanceof GramJs.MessageActionChatAddUser) {\n if (!senderId || targetUserIds.includes(senderId)) {\n text = 'Notification.JoinedChat';\n translationValues.push('%target_user%');\n } else {\n text = 'Notification.Invited';\n translationValues.push('%action_origin%', '%target_user%');\n }\n } else if (action instanceof GramJs.MessageActionChatDeleteUser) {\n if (!senderId || targetUserIds.includes(senderId)) {\n text = 'Notification.LeftChat';\n translationValues.push('%target_user%');\n } else {\n text = 'Notification.Kicked';\n translationValues.push('%action_origin%', '%target_user%');\n }\n } else if (action instanceof GramJs.MessageActionChatJoinedByLink) {\n text = 'Notification.JoinedGroupByLink';\n translationValues.push('%action_origin%');\n } else if (action instanceof GramJs.MessageActionChannelCreate) {\n text = 'Notification.CreatedChannel';\n } else if (action instanceof GramJs.MessageActionChatMigrateTo) {\n targetChatId = getApiChatIdFromMtpPeer(action);\n text = 'Migrated to %target_chat%';\n translationValues.push('%target_chat%');\n } else if (action instanceof GramJs.MessageActionChannelMigrateFrom) {\n targetChatId = getApiChatIdFromMtpPeer(action);\n text = 'Migrated from %target_chat%';\n translationValues.push('%target_chat%');\n } else if (action instanceof GramJs.MessageActionPinMessage) {\n text = 'Chat.Service.Group.UpdatedPinnedMessage1';\n translationValues.push('%action_origin%', '%message%');\n } else if (action instanceof GramJs.MessageActionHistoryClear) {\n text = 'HistoryCleared';\n type = 'historyClear';\n } else if (action instanceof GramJs.MessageActionPhoneCall) {\n const withDuration = Boolean(action.duration);\n text = [\n withDuration ? 'ChatList.Service' : 'Chat',\n action.video ? 'VideoCall' : 'Call',\n isOutgoing ? (withDuration ? 'outgoing' : 'Outgoing') : (withDuration ? 'incoming' : 'Incoming'),\n ].join('.');\n\n if (withDuration) {\n const mins = Math.max(Math.round(action.duration! / 60), 1);\n translationValues.push(`${mins} min${mins > 1 ? 's' : ''}`);\n }\n } else if (action instanceof GramJs.MessageActionContactSignUp) {\n text = 'Notification.Joined';\n translationValues.push('%action_origin%');\n type = 'contactSignUp';\n } else if (action instanceof GramJs.MessageActionPaymentSent) {\n amount = Number(action.totalAmount);\n currency = action.currency;\n text = 'PaymentSuccessfullyPaid';\n if (targetPeerId) {\n targetUserIds.push(targetPeerId);\n }\n translationValues.push('%payment_amount%', '%target_user%', '%product%');\n } else if (action instanceof GramJs.MessageActionGroupCall) {\n if (action.duration) {\n const mins = Math.max(Math.round(action.duration / 60), 1);\n text = 'Notification.VoiceChatEnded';\n translationValues.push(`${mins} min${mins > 1 ? 's' : ''}`);\n } else {\n text = 'Notification.VoiceChatStartedChannel';\n }\n } else if (action instanceof GramJs.MessageActionBotAllowed) {\n text = 'Chat.Service.BotPermissionAllowed';\n translationValues.push(action.domain);\n } else {\n text = 'ChatList.UnsupportedMessage';\n }\n\n if ('photo' in action && action.photo instanceof GramJs.Photo) {\n addPhotoToLocalDb(action.photo);\n photo = buildApiPhoto(action.photo);\n }\n\n return {\n text,\n type,\n targetUserIds,\n targetChatId,\n photo, // TODO Only used internally now, will be used for the UI in future\n amount,\n currency,\n translationValues,\n };\n}\n\nfunction buildReplyButtons(message: UniversalMessage): ApiReplyKeyboard | undefined {\n const { id: messageId, replyMarkup, media } = message;\n\n if (!replyMarkup) {\n if (media instanceof GramJs.MessageMediaWebPage && media.webpage instanceof GramJs.WebPage) {\n if (media.webpage.type === 'telegram_message') {\n return {\n inlineButtons: [[{\n type: 'url' as const,\n text: 'Show Message',\n messageId,\n value: media.webpage.url,\n }]],\n };\n }\n }\n\n return undefined;\n }\n\n // TODO\n if (!(replyMarkup instanceof GramJs.ReplyKeyboardMarkup || replyMarkup instanceof GramJs.ReplyInlineMarkup)) {\n return undefined;\n }\n\n const markup = replyMarkup.rows.map(({ buttons }) => {\n return buttons.map((button) => {\n let { text } = button;\n\n let type;\n let value;\n if (button instanceof GramJs.KeyboardButton) {\n type = 'command';\n value = text;\n } else if (button instanceof GramJs.KeyboardButtonUrl) {\n type = 'url';\n value = button.url;\n } else if (button instanceof GramJs.KeyboardButtonCallback) {\n type = 'callback';\n value = String(button.data);\n } else if (button instanceof GramJs.KeyboardButtonRequestPoll) {\n type = 'requestPoll';\n } else if (button instanceof GramJs.KeyboardButtonBuy) {\n if (media instanceof GramJs.MessageMediaInvoice && media.receiptMsgId) {\n text = 'PaymentReceipt';\n value = media.receiptMsgId;\n }\n type = 'buy';\n } else {\n type = 'NOT_SUPPORTED';\n }\n\n return {\n type,\n text,\n messageId,\n value,\n } as ApiKeyboardButton;\n });\n });\n\n return {\n [replyMarkup instanceof GramJs.ReplyKeyboardMarkup ? 'keyboardButtons' : 'inlineButtons']: markup,\n ...(replyMarkup instanceof GramJs.ReplyKeyboardMarkup && {\n keyboardPlaceholder: replyMarkup.placeholder,\n isKeyboardSingleUse: replyMarkup.singleUse,\n }),\n };\n}\n\nfunction getFilenameFromDocument(document: GramJs.Document, defaultBase = 'file') {\n const { mimeType, attributes } = document;\n const filenameAttribute = attributes\n .find((a: any): a is GramJs.DocumentAttributeFilename => a instanceof GramJs.DocumentAttributeFilename);\n\n if (filenameAttribute) {\n return filenameAttribute.fileName;\n }\n\n const extension = mimeType.split('/')[1];\n\n return `${defaultBase}${String(document.id)}.${extension}`;\n}\n\nexport function buildLocalMessage(\n chat: ApiChat,\n text?: string,\n entities?: ApiMessageEntity[],\n replyingTo?: number,\n attachment?: ApiAttachment,\n sticker?: ApiSticker,\n gif?: ApiVideo,\n poll?: ApiNewPoll,\n groupedId?: string,\n scheduledAt?: number,\n serverTimeOffset = 0,\n): ApiMessage {\n const localId = localMessageCounter++;\n const media = attachment && buildUploadingMedia(attachment);\n const isChannel = chat.type === 'chatTypeChannel';\n\n return {\n id: localId,\n chatId: chat.id,\n content: {\n ...(text && {\n text: {\n text,\n entities,\n },\n }),\n ...media,\n ...(sticker && { sticker }),\n ...(gif && { video: gif }),\n ...(poll && buildNewPoll(poll, localId)),\n },\n date: scheduledAt || Math.round(Date.now() / 1000) + serverTimeOffset,\n isOutgoing: !isChannel,\n senderId: currentUserId,\n ...(replyingTo && { replyToMessageId: replyingTo }),\n ...(groupedId && {\n groupedId,\n ...(media && (media.photo || media.video) && { isInAlbum: true }),\n }),\n ...(scheduledAt && { isScheduled: true }),\n };\n}\n\nexport function buildLocalForwardedMessage(\n toChat: ApiChat,\n message: ApiMessage,\n serverTimeOffset: number,\n scheduledAt?: number,\n): ApiMessage {\n const localId = localMessageCounter++;\n const {\n content,\n chatId: fromChatId,\n id: fromMessageId,\n senderId,\n groupedId,\n isInAlbum,\n } = message;\n\n const isAudio = content.audio;\n const asIncomingInChatWithSelf = (\n toChat.id === currentUserId && (fromChatId !== toChat.id || message.forwardInfo) && !isAudio\n );\n\n return {\n id: localId,\n chatId: toChat.id,\n content,\n date: scheduledAt || Math.round(Date.now() / 1000) + serverTimeOffset,\n isOutgoing: !asIncomingInChatWithSelf && toChat.type !== 'chatTypeChannel',\n senderId: currentUserId,\n sendingState: 'messageSendingStatePending',\n groupedId,\n isInAlbum,\n // Forward info doesn't get added when users forwards his own messages, also when forwarding audio\n ...(senderId !== currentUserId && !isAudio && {\n forwardInfo: {\n isChannelPost: false,\n fromChatId,\n fromMessageId,\n senderUserId: senderId,\n },\n }),\n ...(scheduledAt && { isScheduled: true }),\n };\n}\n\nfunction buildUploadingMedia(\n attachment: ApiAttachment,\n): ApiMessage['content'] {\n const {\n filename: fileName,\n blobUrl,\n previewBlobUrl,\n mimeType,\n size,\n } = attachment;\n\n if (attachment.quick) {\n const { width, height, duration } = attachment.quick;\n\n if (mimeType.startsWith('image/')) {\n return {\n photo: {\n id: LOCAL_MEDIA_UPLOADING_TEMP_ID,\n sizes: [],\n thumbnail: { width, height, dataUri: '' }, // Used only for dimensions\n blobUrl,\n },\n };\n } else {\n return {\n video: {\n id: LOCAL_MEDIA_UPLOADING_TEMP_ID,\n mimeType,\n duration: duration || 0,\n fileName,\n width,\n height,\n blobUrl,\n ...(previewBlobUrl && { thumbnail: { width, height, dataUri: previewBlobUrl } }),\n size,\n },\n };\n }\n } else if (attachment.voice) {\n const { duration, waveform } = attachment.voice;\n const { data: inputWaveform } = interpolateArray(waveform, INPUT_WAVEFORM_LENGTH);\n return {\n voice: {\n duration,\n waveform: inputWaveform,\n },\n };\n } else if (mimeType.startsWith('audio/')) {\n return {\n audio: {\n mimeType,\n fileName,\n size,\n duration: 200, // Arbitrary\n },\n };\n } else {\n return {\n document: {\n mimeType,\n fileName,\n size,\n ...(previewBlobUrl && { previewBlobUrl }),\n },\n };\n }\n}\n\nfunction buildNewPoll(poll: ApiNewPoll, localId: number) {\n return {\n poll: {\n id: String(localId),\n summary: pick(poll.summary, ['question', 'answers']),\n results: {},\n },\n };\n}\n\nfunction buildApiMessageEntity(entity: GramJs.TypeMessageEntity): ApiMessageEntity {\n const { className: type, offset, length } = entity;\n return {\n type,\n offset,\n length,\n ...('userId' in entity && typeof entity.userId === 'number' && { userId: entity.userId }),\n ...('url' in entity && { url: entity.url }),\n };\n}\n\nfunction buildThreadInfo(\n messageReplies: GramJs.TypeMessageReplies, messageId: number, chatId: string,\n): ApiThreadInfo | undefined {\n const {\n channelId, replies, maxId, readMaxId, recentRepliers,\n } = messageReplies;\n if (!channelId) {\n return undefined;\n }\n\n const apiChannelId = buildApiPeerId(channelId, 'channel');\n if (apiChannelId === DELETED_COMMENTS_CHANNEL_ID) {\n return undefined;\n }\n\n const isPostThread = chatId !== apiChannelId;\n\n return {\n threadId: messageId,\n ...(isPostThread ? {\n chatId: apiChannelId,\n originChannelId: chatId,\n } : {\n chatId,\n }),\n messagesCount: replies,\n lastMessageId: maxId,\n lastReadInboxMessageId: readMaxId,\n ...(recentRepliers && { recentReplierIds: recentRepliers.map(getApiChatIdFromMtpPeer) }),\n };\n}\n","export const getServerTime = (serverTimeOffset: number) => {\n return Math.floor(Date.now() / 1000) + serverTimeOffset;\n};\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport {\n ApiChat,\n ApiChatAdminRights,\n ApiChatBannedRights,\n ApiBotCommand,\n ApiChatFolder,\n ApiChatMember,\n ApiRestrictionReason,\n} from '../../types';\nimport { pick, pickTruthy } from '../../../util/iteratees';\nimport {\n buildApiPeerId, getApiChatIdFromMtpPeer, isPeerChat, isPeerUser,\n} from './peers';\nimport { omitVirtualClassFields } from './helpers';\nimport { getServerTime } from '../../../util/serverTime';\n\ntype PeerEntityApiChatFields = Omit;\n\nfunction buildApiChatFieldsFromPeerEntity(\n peerEntity: GramJs.TypeUser | GramJs.TypeChat,\n isSupport = false,\n): PeerEntityApiChatFields {\n const isMin = Boolean('min' in peerEntity && peerEntity.min);\n const accessHash = ('accessHash' in peerEntity) && String(peerEntity.accessHash);\n const avatarHash = ('photo' in peerEntity) && peerEntity.photo && buildAvatarHash(peerEntity.photo);\n const isSignaturesShown = Boolean('signatures' in peerEntity && peerEntity.signatures);\n const hasPrivateLink = Boolean('hasLink' in peerEntity && peerEntity.hasLink);\n\n return {\n isMin,\n hasPrivateLink,\n isSignaturesShown,\n ...(accessHash && { accessHash }),\n ...(avatarHash && { avatarHash }),\n ...(\n (peerEntity instanceof GramJs.Channel || peerEntity instanceof GramJs.User)\n && { username: peerEntity.username }\n ),\n ...(('verified' in peerEntity) && { isVerified: peerEntity.verified }),\n ...(('callActive' in peerEntity) && { isCallActive: peerEntity.callActive }),\n ...(('callNotEmpty' in peerEntity) && { isCallNotEmpty: peerEntity.callNotEmpty }),\n ...((peerEntity instanceof GramJs.Chat || peerEntity instanceof GramJs.Channel) && {\n ...(peerEntity.participantsCount && { membersCount: peerEntity.participantsCount }),\n joinDate: peerEntity.date,\n }),\n ...(isSupport && { isSupport: true }),\n ...buildApiChatPermissions(peerEntity),\n ...(('creator' in peerEntity) && { isCreator: peerEntity.creator }),\n ...buildApiChatRestrictions(peerEntity),\n ...buildApiChatMigrationInfo(peerEntity),\n };\n}\n\nexport function buildApiChatFromDialog(\n dialog: GramJs.Dialog,\n peerEntity: GramJs.TypeUser | GramJs.TypeChat,\n serverTimeOffset: number,\n): ApiChat {\n const {\n peer, folderId, unreadMark, unreadCount, unreadMentionsCount, notifySettings: { silent, muteUntil },\n readOutboxMaxId, readInboxMaxId, draft,\n } = dialog;\n const isMuted = silent || (typeof muteUntil === 'number' && getServerTime(serverTimeOffset) < muteUntil);\n\n return {\n id: getApiChatIdFromMtpPeer(peer),\n ...(folderId && { folderId }),\n type: getApiChatTypeFromPeerEntity(peerEntity),\n title: getApiChatTitleFromMtpPeer(peer, peerEntity),\n lastReadOutboxMessageId: readOutboxMaxId,\n lastReadInboxMessageId: readInboxMaxId,\n unreadCount,\n unreadMentionsCount,\n isMuted,\n ...(unreadMark && { hasUnreadMark: true }),\n ...(draft instanceof GramJs.DraftMessage && { draftDate: draft.date }),\n ...buildApiChatFieldsFromPeerEntity(peerEntity),\n };\n}\n\nfunction buildApiChatPermissions(peerEntity: GramJs.TypeUser | GramJs.TypeChat): {\n adminRights?: ApiChatAdminRights;\n currentUserBannedRights?: ApiChatBannedRights;\n defaultBannedRights?: ApiChatBannedRights;\n} {\n if (!(peerEntity instanceof GramJs.Chat || peerEntity instanceof GramJs.Channel)) {\n return {};\n }\n\n return {\n adminRights: peerEntity.adminRights ? omitVirtualClassFields(peerEntity.adminRights) : undefined,\n currentUserBannedRights: peerEntity instanceof GramJs.Channel && peerEntity.bannedRights\n ? omitVirtualClassFields(peerEntity.bannedRights)\n : undefined,\n defaultBannedRights: peerEntity.defaultBannedRights\n ? omitVirtualClassFields(peerEntity.defaultBannedRights)\n : undefined,\n };\n}\n\nfunction buildApiChatRestrictions(peerEntity: GramJs.TypeUser | GramJs.TypeChat): {\n isNotJoined?: boolean;\n isRestricted?: boolean;\n restrictionReason?: ApiRestrictionReason;\n} {\n if (peerEntity instanceof GramJs.ChatForbidden || peerEntity instanceof GramJs.ChannelForbidden) {\n return {\n isRestricted: true,\n };\n }\n\n const restrictions = {};\n\n if ('restricted' in peerEntity) {\n const restrictionReason = peerEntity.restricted\n ? buildApiChatRestrictionReason(peerEntity.restrictionReason)\n : undefined;\n\n if (restrictionReason) {\n Object.assign(restrictions, {\n isRestricted: true,\n restrictionReason,\n });\n }\n }\n\n if (peerEntity instanceof GramJs.Chat) {\n Object.assign(restrictions, {\n isNotJoined: peerEntity.left,\n isRestricted: peerEntity.kicked,\n });\n }\n\n if (peerEntity instanceof GramJs.Channel) {\n Object.assign(restrictions, {\n // `left` is weirdly set to `true` on all channels never joined before\n isNotJoined: peerEntity.left,\n });\n }\n\n return restrictions;\n}\n\nfunction buildApiChatMigrationInfo(peerEntity: GramJs.TypeChat): {\n migratedTo?: {\n chatId: string;\n accessHash?: string;\n };\n} {\n if (\n peerEntity instanceof GramJs.Chat\n && peerEntity.migratedTo\n && !(peerEntity.migratedTo instanceof GramJs.InputChannelEmpty)\n ) {\n return {\n migratedTo: {\n chatId: getApiChatIdFromMtpPeer(peerEntity.migratedTo),\n ...(peerEntity.migratedTo instanceof GramJs.InputChannel && {\n accessHash: String(peerEntity.migratedTo.accessHash),\n }),\n },\n };\n }\n\n return {};\n}\n\nfunction buildApiChatRestrictionReason(\n restrictionReasons?: GramJs.RestrictionReason[],\n): ApiRestrictionReason | undefined {\n if (!restrictionReasons) {\n return undefined;\n }\n\n const targetReason = restrictionReasons.find(({ platform }) => platform === 'all');\n return targetReason ? pick(targetReason, ['reason', 'text']) : undefined;\n}\n\nexport function buildApiChatFromPreview(\n preview: GramJs.TypeChat | GramJs.TypeUser,\n isSupport = false,\n withForbidden = false,\n): ApiChat | undefined {\n if (!(\n preview instanceof GramJs.Chat\n || preview instanceof GramJs.Channel\n || preview instanceof GramJs.User\n || (\n withForbidden\n && (\n preview instanceof GramJs.ChatForbidden\n || preview instanceof GramJs.ChannelForbidden\n )\n )\n )) {\n return undefined;\n }\n\n return {\n id: buildApiPeerId(preview.id, preview instanceof GramJs.User ? 'user' : 'chat'),\n type: getApiChatTypeFromPeerEntity(preview),\n title: preview instanceof GramJs.User ? getUserName(preview) : preview.title,\n ...buildApiChatFieldsFromPeerEntity(preview, isSupport),\n };\n}\n\nexport function getApiChatTypeFromPeerEntity(peerEntity: GramJs.TypeChat | GramJs.TypeUser) {\n if (peerEntity instanceof GramJs.User || peerEntity instanceof GramJs.UserEmpty) {\n return 'chatTypePrivate';\n } else if (\n peerEntity instanceof GramJs.Chat\n || peerEntity instanceof GramJs.ChatForbidden\n || peerEntity instanceof GramJs.ChatEmpty\n ) {\n return 'chatTypeBasicGroup';\n } else {\n return peerEntity.megagroup ? 'chatTypeSuperGroup' : 'chatTypeChannel';\n }\n}\n\nexport function getPeerKey(peer: GramJs.TypePeer) {\n if (isPeerUser(peer)) {\n return `user${peer.userId}`;\n } else if (isPeerChat(peer)) {\n return `chat${peer.chatId}`;\n } else {\n return `chat${peer.channelId}`;\n }\n}\n\nexport function getApiChatTitleFromMtpPeer(peer: GramJs.TypePeer, peerEntity: GramJs.User | GramJs.Chat) {\n if (isPeerUser(peer)) {\n return getUserName(peerEntity as GramJs.User);\n } else {\n return (peerEntity as GramJs.Chat).title;\n }\n}\n\nfunction getUserName(user: GramJs.User) {\n return user.firstName\n ? `${user.firstName}${user.lastName ? ` ${user.lastName}` : ''}`\n : (user.lastName || undefined);\n}\n\nexport function buildAvatarHash(photo: GramJs.TypeUserProfilePhoto | GramJs.TypeChatPhoto) {\n if ('photoId' in photo) {\n return String(photo.photoId);\n }\n\n return undefined;\n}\n\nexport function buildChatMember(\n member: GramJs.TypeChatParticipant | GramJs.TypeChannelParticipant,\n): ApiChatMember | undefined {\n const userId = (member instanceof GramJs.ChannelParticipantBanned || member instanceof GramJs.ChannelParticipantLeft)\n ? getApiChatIdFromMtpPeer(member.peer)\n : buildApiPeerId(member.userId, 'user');\n\n return {\n userId,\n inviterId: 'inviterId' in member ? buildApiPeerId(member.inviterId as BigInt.BigInteger, 'user') : undefined,\n joinedDate: 'date' in member ? member.date : undefined,\n kickedByUserId: 'kickedBy' in member ? buildApiPeerId(member.kickedBy, 'user') : undefined,\n promotedByUserId: 'promotedBy' in member ? buildApiPeerId(member.promotedBy, 'user') : undefined,\n bannedRights: 'bannedRights' in member ? omitVirtualClassFields(member.bannedRights) : undefined,\n adminRights: 'adminRights' in member ? omitVirtualClassFields(member.adminRights) : undefined,\n customTitle: 'rank' in member ? member.rank : undefined,\n ...((member instanceof GramJs.ChannelParticipantAdmin || member instanceof GramJs.ChatParticipantAdmin) && {\n isAdmin: true,\n }),\n ...((member instanceof GramJs.ChannelParticipantCreator || member instanceof GramJs.ChatParticipantCreator) && {\n isOwner: true,\n }),\n };\n}\n\nexport function buildChatMembers(\n participants: GramJs.TypeChatParticipants | GramJs.channels.ChannelParticipants,\n) {\n // Duplicate code because of TS union-type shenanigans\n if (participants instanceof GramJs.ChatParticipants) {\n return participants.participants.map(buildChatMember).filter(Boolean as any);\n }\n if (participants instanceof GramJs.channels.ChannelParticipants) {\n return participants.participants.map(buildChatMember).filter(Boolean as any);\n }\n\n return undefined;\n}\n\nexport function buildChatTypingStatus(\n update: GramJs.UpdateUserTyping | GramJs.UpdateChatUserTyping | GramJs.UpdateChannelUserTyping,\n serverTimeOffset: number,\n) {\n let action: string = '';\n if (update.action instanceof GramJs.SendMessageCancelAction) {\n return undefined;\n } else if (update.action instanceof GramJs.SendMessageTypingAction) {\n action = 'lng_user_typing';\n } else if (update.action instanceof GramJs.SendMessageRecordVideoAction) {\n action = 'lng_send_action_record_video';\n } else if (update.action instanceof GramJs.SendMessageUploadVideoAction) {\n action = 'lng_send_action_upload_video';\n } else if (update.action instanceof GramJs.SendMessageRecordAudioAction) {\n action = 'lng_send_action_record_audio';\n } else if (update.action instanceof GramJs.SendMessageUploadAudioAction) {\n action = 'lng_send_action_upload_audio';\n } else if (update.action instanceof GramJs.SendMessageUploadPhotoAction) {\n action = 'lng_send_action_upload_photo';\n } else if (update.action instanceof GramJs.SendMessageUploadDocumentAction) {\n action = 'lng_send_action_upload_file';\n } else if (update.action instanceof GramJs.SendMessageGeoLocationAction) {\n action = 'selecting a location to share';\n } else if (update.action instanceof GramJs.SendMessageChooseContactAction) {\n action = 'selecting a contact to share';\n } else if (update.action instanceof GramJs.SendMessageGamePlayAction) {\n action = 'lng_playing_game';\n } else if (update.action instanceof GramJs.SendMessageRecordRoundAction) {\n action = 'lng_send_action_record_round';\n } else if (update.action instanceof GramJs.SendMessageUploadRoundAction) {\n action = 'lng_send_action_upload_round';\n } else if (update.action instanceof GramJs.SendMessageChooseStickerAction) {\n action = 'lng_send_action_choose_sticker';\n } else if (update.action instanceof GramJs.SpeakingInGroupCallAction) {\n return undefined;\n }\n\n return {\n action,\n ...(!(update instanceof GramJs.UpdateUserTyping) && { userId: getApiChatIdFromMtpPeer(update.fromId) }),\n timestamp: Date.now() + serverTimeOffset * 1000,\n };\n}\n\nexport function buildApiChatFolder(filter: GramJs.DialogFilter): ApiChatFolder {\n return {\n ...pickTruthy(filter, [\n 'id', 'title', 'emoticon', 'contacts', 'nonContacts', 'groups', 'bots',\n 'excludeMuted', 'excludeRead', 'excludeArchived',\n ]),\n channels: filter.broadcasts,\n pinnedChatIds: filter.pinnedPeers.map(getApiChatIdFromMtpPeer).filter(Boolean as any),\n includedChatIds: filter.includePeers.map(getApiChatIdFromMtpPeer).filter(Boolean as any),\n excludedChatIds: filter.excludePeers.map(getApiChatIdFromMtpPeer).filter(Boolean as any),\n };\n}\n\nexport function buildApiChatFolderFromSuggested({\n filter, description,\n}: {\n filter: GramJs.DialogFilter;\n description: string;\n}): ApiChatFolder {\n return {\n ...buildApiChatFolder(filter),\n description,\n };\n}\n\nexport function buildApiChatBotCommands(botInfos: GramJs.BotInfo[]) {\n return botInfos.reduce((botCommands, botInfo) => {\n const botId = buildApiPeerId(botInfo.userId, 'user');\n\n botCommands = botCommands.concat(botInfo.commands.map((mtpCommand) => ({\n botId,\n ...omitVirtualClassFields(mtpCommand),\n })));\n\n return botCommands;\n }, [] as ApiBotCommand[]);\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n ApiBotCommand, ApiUser, ApiUserStatus, ApiUserType,\n} from '../../types';\nimport { buildApiPeerId } from './peers';\n\nexport function buildApiUserFromFull(mtpUserFull: GramJs.UserFull): ApiUser {\n const {\n about, commonChatsCount, pinnedMsgId, botInfo, blocked,\n } = mtpUserFull;\n\n const user = buildApiUser(mtpUserFull.user)!;\n\n return {\n ...user,\n fullInfo: {\n bio: about,\n commonChatsCount,\n pinnedMessageId: pinnedMsgId,\n isBlocked: Boolean(blocked),\n ...(botInfo && { botDescription: botInfo.description }),\n ...(botInfo && botInfo.commands.length && { botCommands: buildApiBotCommands(user.id, botInfo) }),\n },\n };\n}\n\nexport function buildApiUser(mtpUser: GramJs.TypeUser): ApiUser | undefined {\n if (!(mtpUser instanceof GramJs.User)) {\n return undefined;\n }\n\n const { id, firstName, lastName } = mtpUser;\n const avatarHash = mtpUser.photo instanceof GramJs.UserProfilePhoto\n ? String(mtpUser.photo.photoId)\n : undefined;\n const userType = buildApiUserType(mtpUser);\n\n return {\n id: buildApiPeerId(id, 'user'),\n isMin: Boolean(mtpUser.min),\n ...(mtpUser.self && { isSelf: true }),\n ...(mtpUser.verified && { isVerified: true }),\n ...((mtpUser.contact || mtpUser.mutualContact) && { isContact: true }),\n type: userType,\n ...(firstName && { firstName }),\n ...(userType === 'userTypeBot' && { canBeInvitedToGroup: !mtpUser.botNochats }),\n ...(lastName && { lastName }),\n username: mtpUser.username || '',\n phoneNumber: mtpUser.phone || '',\n status: buildApiUserStatus(mtpUser.status),\n ...(mtpUser.accessHash && { accessHash: String(mtpUser.accessHash) }),\n ...(avatarHash && { avatarHash }),\n ...(mtpUser.bot && mtpUser.botInlinePlaceholder && { botPlaceholder: mtpUser.botInlinePlaceholder }),\n };\n}\n\nfunction buildApiUserType(user: GramJs.User): ApiUserType {\n if (user.bot) {\n return 'userTypeBot';\n }\n if (user.deleted) {\n return 'userTypeDeleted';\n }\n\n return 'userTypeRegular';\n}\n\nexport function buildApiUserStatus(mtpStatus?: GramJs.TypeUserStatus): ApiUserStatus {\n if (!mtpStatus || mtpStatus instanceof GramJs.UserStatusEmpty) {\n return { type: 'userStatusEmpty' };\n } else if (mtpStatus instanceof GramJs.UserStatusOnline) {\n return { type: 'userStatusOnline', expires: mtpStatus.expires };\n } else if (mtpStatus instanceof GramJs.UserStatusOffline) {\n return { type: 'userStatusOffline', wasOnline: mtpStatus.wasOnline };\n } else if (mtpStatus instanceof GramJs.UserStatusRecently) {\n return { type: 'userStatusRecently' };\n } else if (mtpStatus instanceof GramJs.UserStatusLastWeek) {\n return { type: 'userStatusLastWeek' };\n } else {\n return { type: 'userStatusLastMonth' };\n }\n}\n\nfunction buildApiBotCommands(botId: string, botInfo: GramJs.BotInfo) {\n return botInfo.commands.map(({ command, description }) => ({\n botId,\n command,\n description,\n })) as ApiBotCommand[];\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\n\nimport { ApiCountry, ApiSession, ApiWallpaper } from '../../types';\nimport { ApiPrivacySettings, ApiPrivacyKey, PrivacyVisibility } from '../../../types';\n\nimport { buildApiDocument } from './messages';\nimport { buildApiPeerId, getApiChatIdFromMtpPeer } from './peers';\nimport { flatten, pick } from '../../../util/iteratees';\nimport { getServerTime } from '../../../util/serverTime';\n\nexport function buildApiWallpaper(wallpaper: GramJs.TypeWallPaper): ApiWallpaper | undefined {\n if (wallpaper instanceof GramJs.WallPaperNoFile) {\n // TODO: Plain color wallpapers\n return undefined;\n }\n\n const { slug } = wallpaper;\n\n const document = buildApiDocument(wallpaper.document);\n\n if (!document) {\n return undefined;\n }\n\n return {\n slug,\n document,\n };\n}\n\nexport function buildApiSession(session: GramJs.Authorization): ApiSession {\n return {\n isCurrent: Boolean(session.current),\n isOfficialApp: Boolean(session.officialApp),\n isPasswordPending: Boolean(session.passwordPending),\n hash: String(session.hash),\n ...pick(session, [\n 'deviceModel', 'platform', 'systemVersion', 'appName', 'appVersion', 'dateCreated', 'dateActive',\n 'ip', 'country', 'region',\n ]),\n };\n}\n\nexport function buildPrivacyKey(key: GramJs.TypePrivacyKey): ApiPrivacyKey | undefined {\n switch (key.className) {\n case 'PrivacyKeyPhoneNumber':\n return 'phoneNumber';\n case 'PrivacyKeyStatusTimestamp':\n return 'lastSeen';\n case 'PrivacyKeyProfilePhoto':\n return 'profilePhoto';\n case 'PrivacyKeyForwards':\n return 'forwards';\n case 'PrivacyKeyChatInvite':\n return 'chatInvite';\n }\n\n return undefined;\n}\n\nexport function buildPrivacyRules(rules: GramJs.TypePrivacyRule[]): ApiPrivacySettings {\n let visibility: PrivacyVisibility | undefined;\n let allowUserIds: string[] | undefined;\n let allowChatIds: string[] | undefined;\n let blockUserIds: string[] | undefined;\n let blockChatIds: string[] | undefined;\n\n rules.forEach((rule) => {\n if (rule instanceof GramJs.PrivacyValueAllowAll) {\n visibility = visibility || 'everybody';\n } else if (rule instanceof GramJs.PrivacyValueAllowContacts) {\n visibility = visibility || 'contacts';\n } else if (rule instanceof GramJs.PrivacyValueDisallowContacts) {\n visibility = visibility || 'nonContacts';\n } else if (rule instanceof GramJs.PrivacyValueDisallowAll) {\n visibility = visibility || 'nobody';\n } else if (rule instanceof GramJs.PrivacyValueAllowUsers) {\n allowUserIds = rule.users.map((chatId) => buildApiPeerId(chatId, 'user'));\n } else if (rule instanceof GramJs.PrivacyValueDisallowUsers) {\n blockUserIds = rule.users.map((chatId) => buildApiPeerId(chatId, 'user'));\n } else if (rule instanceof GramJs.PrivacyValueAllowChatParticipants) {\n allowChatIds = rule.chats.map((chatId) => buildApiPeerId(chatId, 'chat'));\n } else if (rule instanceof GramJs.PrivacyValueDisallowChatParticipants) {\n blockChatIds = rule.chats.map((chatId) => buildApiPeerId(chatId, 'chat'));\n }\n });\n\n if (!visibility) {\n // disallow by default.\n visibility = 'nobody';\n }\n\n return {\n visibility,\n allowUserIds: allowUserIds || [],\n allowChatIds: allowChatIds || [],\n blockUserIds: blockUserIds || [],\n blockChatIds: blockChatIds || [],\n };\n}\n\nexport function buildApiNotifyException(\n notifySettings: GramJs.TypePeerNotifySettings, peer: GramJs.TypePeer, serverTimeOffset: number,\n) {\n const {\n silent, muteUntil, showPreviews, sound,\n } = notifySettings;\n\n return {\n chatId: getApiChatIdFromMtpPeer(peer),\n isMuted: silent || (typeof muteUntil === 'number' && getServerTime(serverTimeOffset) < muteUntil),\n ...(sound === '' && { isSilent: true }),\n ...(showPreviews !== undefined && { shouldShowPreviews: Boolean(showPreviews) }),\n };\n}\n\nfunction buildApiCountry(country: GramJs.help.Country, code?: GramJs.help.CountryCode) {\n const {\n hidden, iso2, defaultName, name,\n } = country;\n const { countryCode, prefixes, patterns } = code || {};\n\n return {\n isHidden: hidden,\n iso2,\n defaultName,\n name,\n countryCode,\n prefixes,\n patterns,\n };\n}\n\nexport function buildApiCountryList(countries: GramJs.help.Country[]) {\n const listByCode = flatten(\n countries\n .filter((country) => !country.hidden)\n .map((country) => (\n country.countryCodes.map((code) => buildApiCountry(country, code))\n )),\n )\n .sort((a: ApiCountry, b: ApiCountry) => (\n a.name ? a.name.localeCompare(b.name!) : a.defaultName.localeCompare(b.defaultName)\n ));\n\n const generalList = countries\n .filter((country) => !country.hidden)\n .map((country) => buildApiCountry(country))\n .sort((a, b) => (\n a.name ? a.name.localeCompare(b.name!) : a.defaultName.localeCompare(b.defaultName)\n ));\n\n return {\n phoneCodes: listByCode,\n general: generalList,\n };\n}\n","import { Api as GramJs, connection } from '../../lib/gramjs';\nimport { ApiMessage, ApiUpdateConnectionStateType, OnApiUpdate } from '../types';\n\nimport { pick } from '../../util/iteratees';\nimport {\n buildApiMessage,\n buildApiMessageFromShort,\n buildApiMessageFromShortChat,\n buildMessageMediaContent,\n buildMessageTextContent,\n buildPoll,\n buildPollResults,\n buildApiMessageFromNotification,\n buildMessageDraft,\n} from './apiBuilders/messages';\nimport {\n buildChatMember,\n buildChatMembers,\n buildChatTypingStatus,\n buildAvatarHash,\n buildApiChatFromPreview,\n buildApiChatFolder,\n} from './apiBuilders/chats';\nimport { buildApiUser, buildApiUserStatus } from './apiBuilders/users';\nimport {\n buildMessageFromUpdate,\n isMessageWithMedia,\n buildChatPhotoForLocalDb,\n} from './gramjsBuilders';\nimport localDb from './localDb';\nimport { omitVirtualClassFields } from './apiBuilders/helpers';\nimport { DEBUG } from '../../config';\nimport { addMessageToLocalDb, addPhotoToLocalDb, resolveMessageApiChatId } from './helpers';\nimport { buildApiNotifyException, buildPrivacyKey, buildPrivacyRules } from './apiBuilders/misc';\nimport { buildApiPhoto } from './apiBuilders/common';\nimport { buildApiPeerId, getApiChatIdFromMtpPeer } from './apiBuilders/peers';\n\ntype Update = (\n (GramJs.TypeUpdate | GramJs.TypeUpdates) & { _entities?: (GramJs.TypeUser | GramJs.TypeChat)[] }\n) | typeof connection.UpdateConnectionState;\n\nconst DELETE_MISSING_CHANNEL_MESSAGE_DELAY = 1000;\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nconst sentMessageIds = new Set();\nlet serverTimeOffset = 0;\n\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?.length) {\n entities\n .filter((e) => e instanceof GramJs.User)\n .map(buildApiUser)\n .forEach((user) => {\n if (!user) {\n return;\n }\n\n onUpdate({\n '@type': 'updateUser',\n id: user.id,\n user,\n });\n });\n entities\n .filter((e) => e instanceof GramJs.Chat || e instanceof GramJs.Channel)\n .map((e) => buildApiChatFromPreview(e))\n .forEach((chat) => {\n if (!chat) {\n return;\n }\n\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n });\n }\n\n if (update instanceof GramJs.UpdateNewScheduledMessage) {\n onUpdate({\n '@type': sentMessageIds.has(message.id) ? 'updateScheduledMessage' : 'newScheduledMessage',\n id: message.id,\n chatId: message.chatId,\n message,\n });\n } else {\n onUpdate({\n '@type': sentMessageIds.has(message.id) ? 'updateMessage' : 'newMessage',\n id: message.id,\n chatId: message.chatId,\n message,\n shouldForceReply,\n });\n }\n\n // Some updates to a Chat/Channel don't have a dedicated update class.\n // We can get info on some updates from Service Messages.\n if (update.message instanceof GramJs.MessageService) {\n const { action } = update.message;\n\n if (action instanceof GramJs.MessageActionChatEditTitle) {\n onUpdate({\n '@type': 'updateChat',\n id: message.chatId,\n chat: {\n title: action.title,\n },\n });\n } else if (action instanceof GramJs.MessageActionChatEditPhoto) {\n const photo = buildChatPhotoForLocalDb(action.photo);\n const avatarHash = buildAvatarHash(photo);\n\n const localDbChatId = resolveMessageApiChatId(update.message)!;\n if (localDb.chats[localDbChatId]) {\n localDb.chats[localDbChatId].photo = photo;\n }\n addPhotoToLocalDb(action.photo);\n\n if (avatarHash) {\n onUpdate({\n '@type': 'updateChat',\n id: message.chatId,\n chat: {\n avatarHash,\n },\n ...(action.photo instanceof GramJs.Photo && { newProfilePhoto: buildApiPhoto(action.photo) }),\n });\n }\n } else if (action instanceof GramJs.MessageActionChatDeletePhoto) {\n const localDbChatId = resolveMessageApiChatId(update.message)!;\n if (localDb.chats[localDbChatId]) {\n localDb.chats[localDbChatId].photo = new GramJs.ChatPhotoEmpty();\n }\n\n onUpdate({\n '@type': 'updateChat',\n id: message.chatId,\n chat: { avatarHash: undefined },\n });\n } else if (action instanceof GramJs.MessageActionChatDeleteUser) {\n // eslint-disable-next-line no-underscore-dangle\n if (update._entities && update._entities.some((e): e is GramJs.User => (\n e instanceof GramJs.User && !!e.self && e.id === action.userId\n ))) {\n onUpdate({\n '@type': 'updateChat',\n id: message.chatId,\n chat: {\n isRestricted: true,\n },\n });\n\n onUpdate({\n '@type': 'updateChatLeave',\n id: message.chatId,\n });\n }\n } else if (action instanceof GramJs.MessageActionChatAddUser) {\n // eslint-disable-next-line no-underscore-dangle\n if (update._entities && update._entities.some((e): e is GramJs.User => (\n e instanceof GramJs.User && !!e.self && action.users.includes(e.id)\n ))) {\n onUpdate({\n '@type': 'updateChatJoin',\n id: message.chatId,\n });\n }\n }\n }\n } else if (\n update instanceof GramJs.UpdateEditMessage\n || update instanceof GramJs.UpdateEditChannelMessage\n ) {\n // TODO Remove if proven not reproducing\n if (update.message instanceof GramJs.MessageEmpty) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected update:', update.className, update);\n }\n\n return;\n }\n\n if (update.message instanceof GramJs.Message && isMessageWithMedia(update.message)) {\n addMessageToLocalDb(update.message);\n }\n\n const message = buildApiMessage(update.message)!;\n\n onUpdate({\n '@type': 'updateMessage',\n id: message.id,\n chatId: message.chatId,\n message,\n });\n } else if (update instanceof GramJs.UpdateDeleteMessages) {\n onUpdate({\n '@type': 'deleteMessages',\n ids: update.messages,\n });\n } else if (update instanceof GramJs.UpdateDeleteScheduledMessages) {\n onUpdate({\n '@type': 'deleteScheduledMessages',\n ids: update.messages,\n chatId: getApiChatIdFromMtpPeer(update.peer),\n });\n } else if (update instanceof GramJs.UpdateDeleteChannelMessages) {\n const chatId = buildApiPeerId(update.channelId, 'channel');\n const ids = update.messages;\n const existingIds = ids.filter((id) => localDb.messages[`${chatId}-${id}`]);\n const missingIds = ids.filter((id) => !localDb.messages[`${chatId}-${id}`]);\n const profilePhotoIds = ids.map((id) => {\n const message = localDb.messages[`${chatId}-${id}`];\n\n return message && message instanceof GramJs.MessageService && 'photo' in message.action\n ? String(message.action.photo.id)\n : undefined;\n }).filter(Boolean as any);\n\n if (existingIds.length) {\n onUpdate({\n '@type': 'deleteMessages',\n ids: existingIds,\n chatId,\n });\n }\n\n if (profilePhotoIds.length) {\n onUpdate({\n '@type': 'deleteProfilePhotos',\n ids: profilePhotoIds,\n chatId,\n });\n }\n\n // For some reason delete message update sometimes comes before new message update\n if (missingIds.length) {\n setTimeout(() => {\n onUpdate({\n '@type': 'deleteMessages',\n ids: missingIds,\n chatId,\n });\n }, DELETE_MISSING_CHANNEL_MESSAGE_DELAY);\n }\n } else if (update instanceof GramJs.UpdateServiceNotification) {\n 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 } else if ((\n originRequest instanceof GramJs.messages.SendMessage\n || originRequest instanceof GramJs.messages.SendMedia\n || originRequest instanceof GramJs.messages.SendMultiMedia\n || originRequest instanceof GramJs.messages.ForwardMessages\n ) && (\n update instanceof GramJs.UpdateMessageID\n || update instanceof GramJs.UpdateShortSentMessage\n )) {\n let randomId;\n if ('randomId' in update) {\n randomId = update.randomId;\n } else if ('randomId' in originRequest) {\n randomId = originRequest.randomId;\n }\n\n const localMessage = randomId && localDb.localMessages[String(randomId)];\n if (!localMessage) {\n throw new Error('Local message not found');\n }\n\n let newContent: ApiMessage['content'] | undefined;\n if (update instanceof GramJs.UpdateShortSentMessage) {\n if (localMessage.content.text && update.entities) {\n newContent = {\n text: buildMessageTextContent(localMessage.content.text.text, update.entities),\n };\n }\n if (update.media) {\n newContent = {\n ...newContent,\n ...buildMessageMediaContent(update.media),\n };\n }\n\n const mtpMessage = buildMessageFromUpdate(update.id, localMessage.chatId, update);\n if (isMessageWithMedia(mtpMessage)) {\n addMessageToLocalDb(mtpMessage);\n }\n }\n\n sentMessageIds.add(update.id);\n\n // Edge case for \"Send When Online\"\n const isAlreadySent = 'date' in update && update.date * 1000 < Date.now() + serverTimeOffset * 1000;\n\n onUpdate({\n '@type': localMessage.isScheduled && !isAlreadySent\n ? 'updateScheduledMessageSendSucceeded'\n : 'updateMessageSendSucceeded',\n chatId: localMessage.chatId,\n localId: localMessage.id,\n message: {\n ...localMessage,\n ...(newContent && {\n content: {\n ...localMessage.content,\n ...newContent,\n },\n }),\n id: update.id,\n sendingState: undefined,\n ...('date' in update && { date: update.date }),\n },\n });\n } else if (update instanceof GramJs.UpdateReadMessagesContents) {\n onUpdate({\n '@type': 'updateCommonBoxMessages',\n ids: update.messages,\n messageUpdate: {\n hasUnreadMention: false,\n isMediaUnread: false,\n },\n });\n } else if (update instanceof GramJs.UpdateChannelReadMessagesContents) {\n onUpdate({\n '@type': 'updateChannelMessages',\n channelId: buildApiPeerId(update.channelId, 'channel'),\n ids: update.messages,\n messageUpdate: {\n hasUnreadMention: false,\n isMediaUnread: false,\n },\n });\n } else if (update instanceof GramJs.UpdateMessagePoll) {\n const { pollId, poll, results } = update;\n if (poll) {\n const apiPoll = buildPoll(poll, results);\n\n onUpdate({\n '@type': 'updateMessagePoll',\n pollId: String(pollId),\n pollUpdate: apiPoll,\n });\n } else {\n const pollResults = buildPollResults(results);\n onUpdate({\n '@type': 'updateMessagePoll',\n pollId: String(pollId),\n pollUpdate: { results: pollResults },\n });\n }\n } else if (update instanceof GramJs.UpdateMessagePollVote) {\n onUpdate({\n '@type': 'updateMessagePollVote',\n pollId: String(update.pollId),\n userId: buildApiPeerId(update.userId, 'user'),\n options: update.options.map((option) => String.fromCharCode(...option)),\n });\n } else if (update instanceof GramJs.UpdateChannelMessageViews) {\n onUpdate({\n '@type': 'updateMessage',\n chatId: buildApiPeerId(update.channelId, 'channel'),\n id: update.id,\n message: { views: update.views },\n });\n\n // Chats\n } else if (update instanceof GramJs.UpdateReadHistoryInbox) {\n onUpdate({\n '@type': 'updateChatInbox',\n id: getApiChatIdFromMtpPeer(update.peer),\n chat: {\n lastReadInboxMessageId: update.maxId,\n unreadCount: update.stillUnreadCount,\n },\n });\n } else if (update instanceof GramJs.UpdateReadHistoryOutbox) {\n onUpdate({\n '@type': 'updateChat',\n id: getApiChatIdFromMtpPeer(update.peer),\n chat: {\n lastReadOutboxMessageId: update.maxId,\n },\n });\n } else if (update instanceof GramJs.UpdateReadChannelInbox) {\n onUpdate({\n '@type': 'updateChat',\n id: buildApiPeerId(update.channelId, 'channel'),\n chat: {\n lastReadInboxMessageId: update.maxId,\n unreadCount: update.stillUnreadCount,\n },\n });\n } else if (update instanceof GramJs.UpdateReadChannelOutbox) {\n onUpdate({\n '@type': 'updateChat',\n id: buildApiPeerId(update.channelId, 'channel'),\n chat: {\n lastReadOutboxMessageId: update.maxId,\n },\n });\n } else if (\n update instanceof GramJs.UpdateDialogPinned\n && update.peer instanceof GramJs.DialogPeer\n ) {\n onUpdate({\n '@type': 'updateChatPinned',\n id: getApiChatIdFromMtpPeer(update.peer.peer),\n isPinned: update.pinned || false,\n });\n } else if (update instanceof GramJs.UpdatePinnedDialogs) {\n const ids = update.order\n ? update.order\n .filter((dp): dp is GramJs.DialogPeer => dp instanceof GramJs.DialogPeer)\n .map((dp) => getApiChatIdFromMtpPeer(dp.peer))\n : [];\n\n onUpdate({\n '@type': 'updatePinnedChatIds',\n ids,\n folderId: update.folderId || undefined,\n });\n } else if (update instanceof GramJs.UpdateFolderPeers) {\n update.folderPeers.forEach((folderPeer) => {\n const { folderId, peer } = folderPeer;\n\n onUpdate({\n '@type': 'updateChatListType',\n id: getApiChatIdFromMtpPeer(peer),\n folderId,\n });\n });\n } else if (update instanceof GramJs.UpdateDialogFilter) {\n const { id, filter } = update;\n const folder = filter ? buildApiChatFolder(filter) : undefined;\n\n onUpdate({\n '@type': 'updateChatFolder',\n id,\n folder,\n });\n } else if (update instanceof GramJs.UpdateDialogFilterOrder) {\n onUpdate({\n '@type': 'updateChatFoldersOrder',\n orderedIds: update.order,\n });\n } else if (update instanceof GramJs.UpdateChatParticipants) {\n const replacedMembers = buildChatMembers(update.participants);\n\n onUpdate({\n '@type': 'updateChatMembers',\n id: buildApiPeerId(update.participants.chatId, 'chat'),\n replacedMembers,\n });\n } else if (update instanceof GramJs.UpdateChatParticipantAdd) {\n const addedMember = buildChatMember(\n pick(update, ['userId', 'inviterId', 'date']) as GramJs.ChatParticipant,\n );\n\n onUpdate({\n '@type': 'updateChatMembers',\n id: buildApiPeerId(update.chatId, 'chat'),\n addedMember,\n });\n } else if (update instanceof GramJs.UpdateChatParticipantDelete) {\n onUpdate({\n '@type': 'updateChatMembers',\n id: buildApiPeerId(update.chatId, 'chat'),\n deletedMemberId: buildApiPeerId(update.userId, 'user'),\n });\n } else if (\n update instanceof GramJs.UpdatePinnedMessages\n || update instanceof GramJs.UpdatePinnedChannelMessages\n ) {\n const chatId = update instanceof GramJs.UpdatePinnedMessages\n ? getApiChatIdFromMtpPeer(update.peer)\n : buildApiPeerId(update.channelId, 'channel');\n\n onUpdate({\n '@type': 'updatePinnedIds',\n chatId,\n messageIds: update.messages,\n isPinned: update.pinned,\n });\n } else if (\n update instanceof GramJs.UpdateNotifySettings\n && update.peer instanceof GramJs.NotifyPeer\n ) {\n onUpdate({\n '@type': 'updateNotifyExceptions',\n ...buildApiNotifyException(update.notifySettings, update.peer.peer, serverTimeOffset),\n });\n } else if (\n update instanceof GramJs.UpdateUserTyping\n || update instanceof GramJs.UpdateChatUserTyping\n ) {\n const id = update instanceof GramJs.UpdateUserTyping\n ? buildApiPeerId(update.userId, 'user')\n : buildApiPeerId(update.chatId, 'chat');\n\n onUpdate({\n '@type': 'updateChatTypingStatus',\n id,\n typingStatus: buildChatTypingStatus(update, serverTimeOffset),\n });\n } else if (update instanceof GramJs.UpdateChannelUserTyping) {\n const id = buildApiPeerId(update.channelId, 'channel');\n\n onUpdate({\n '@type': 'updateChatTypingStatus',\n id,\n typingStatus: buildChatTypingStatus(update, serverTimeOffset),\n });\n } else if (update instanceof GramJs.UpdateChannel) {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n const { _entities } = update;\n if (!_entities) {\n return;\n }\n\n const channel = _entities.find((e): e is GramJs.Channel | GramJs.ChannelForbidden => (\n e instanceof GramJs.Channel || e instanceof GramJs.ChannelForbidden\n ));\n\n if (channel instanceof GramJs.Channel) {\n const chat = buildApiChatFromPreview(channel);\n if (chat) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n\n onUpdate({\n '@type': chat.isNotJoined ? 'updateChatLeave' : 'updateChatJoin',\n id: buildApiPeerId(update.channelId, 'channel'),\n });\n }\n } else if (channel instanceof GramJs.ChannelForbidden) {\n const chatId = buildApiPeerId(update.channelId, 'channel');\n\n onUpdate({\n '@type': 'updateChat',\n id: chatId,\n chat: {\n isRestricted: true,\n },\n });\n\n onUpdate({\n '@type': 'updateChatLeave',\n id: chatId,\n });\n } else if (_entities.length === 0) {\n // The link to the discussion group may have been changed.\n // No corresponding update available at this moment https://core.telegram.org/type/Updates\n onUpdate({\n '@type': 'resetMessages',\n id: buildApiPeerId(update.channelId, 'channel'),\n });\n }\n } else if (\n update instanceof GramJs.UpdateDialogUnreadMark\n && update.peer instanceof GramJs.DialogPeer\n ) {\n onUpdate({\n '@type': 'updateChat',\n id: getApiChatIdFromMtpPeer(update.peer.peer),\n chat: {\n hasUnreadMark: update.unread,\n },\n });\n } else if (update instanceof GramJs.UpdateChatDefaultBannedRights) {\n onUpdate({\n '@type': 'updateChat',\n id: getApiChatIdFromMtpPeer(update.peer),\n chat: {\n defaultBannedRights: omitVirtualClassFields(update.defaultBannedRights),\n },\n });\n\n // Users\n } else if (update instanceof GramJs.UpdateUserStatus) {\n onUpdate({\n '@type': 'updateUserStatus',\n userId: buildApiPeerId(update.userId, 'user'),\n status: buildApiUserStatus(update.status),\n });\n } else if (update instanceof GramJs.UpdateUserName) {\n const apiUserId = buildApiPeerId(update.userId, 'user');\n const updatedUser = localDb.users[apiUserId];\n const user = updatedUser?.mutualContact && !updatedUser.self\n ? pick(update, ['username'])\n : pick(update, ['firstName', 'lastName', 'username']);\n\n onUpdate({\n '@type': 'updateUser',\n id: apiUserId,\n user,\n });\n } else if (update instanceof GramJs.UpdateUserPhoto) {\n const { userId, photo } = update;\n const apiUserId = buildApiPeerId(userId, 'user');\n const avatarHash = buildAvatarHash(photo);\n\n if (localDb.users[apiUserId]) {\n localDb.users[apiUserId].photo = photo;\n }\n\n onUpdate({\n '@type': 'updateUser',\n id: apiUserId,\n user: { avatarHash },\n });\n } else if (update instanceof GramJs.UpdateUserPhone) {\n const { userId, phone } = update;\n\n onUpdate({\n '@type': 'updateUser',\n id: buildApiPeerId(userId, 'user'),\n user: { phoneNumber: phone },\n });\n } else if (update instanceof GramJs.UpdatePeerSettings) {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n const { _entities } = update;\n if (!_entities) {\n return;\n }\n\n if (_entities?.length) {\n _entities\n .filter((e) => e instanceof GramJs.User && !e.contact)\n .forEach((user) => {\n onUpdate({\n '@type': 'deleteUser',\n id: buildApiPeerId(user.id, 'user'),\n });\n });\n\n _entities\n .filter((e) => e instanceof GramJs.User && e.contact)\n .map(buildApiUser)\n .forEach((user) => {\n if (!user) {\n return;\n }\n\n onUpdate({\n '@type': 'updateUser',\n id: user.id,\n user,\n });\n });\n }\n\n // Settings\n } else if (update instanceof GramJs.UpdateNotifySettings) {\n const {\n notifySettings: {\n showPreviews, silent, muteUntil,\n },\n peer: { className },\n } = update;\n\n const peerType = className === 'NotifyUsers'\n ? 'contact'\n : (className === 'NotifyChats'\n ? 'group'\n : (className === 'NotifyBroadcasts'\n ? 'broadcast'\n : undefined\n )\n );\n\n if (!peerType) {\n return;\n }\n\n onUpdate({\n '@type': 'updateNotifySettings',\n peerType,\n isSilent: Boolean(silent\n || (typeof muteUntil === 'number' && Date.now() + serverTimeOffset * 1000 < muteUntil * 1000)),\n shouldShowPreviews: Boolean(showPreviews),\n });\n } else if (update instanceof GramJs.UpdatePeerBlocked) {\n onUpdate({\n '@type': 'updatePeerBlocked',\n id: getApiChatIdFromMtpPeer(update.peerId),\n isBlocked: update.blocked,\n });\n } else if (update instanceof GramJs.UpdatePrivacy) {\n const key = buildPrivacyKey(update.key);\n if (key) {\n onUpdate({\n '@type': 'updatePrivacy',\n key,\n rules: buildPrivacyRules(update.rules),\n });\n }\n\n // Misc\n } else if (update instanceof GramJs.UpdateDraftMessage) {\n onUpdate({\n '@type': 'draftMessage',\n chatId: getApiChatIdFromMtpPeer(update.peer),\n ...buildMessageDraft(update.draft),\n });\n } else if (update instanceof GramJs.UpdateContactsReset) {\n onUpdate({ '@type': 'updateResetContactList' });\n } else if (update instanceof GramJs.UpdateFavedStickers) {\n onUpdate({ '@type': 'updateFavoriteStickers' });\n } else if (DEBUG) {\n const params = typeof update === 'object' && 'className' in update ? update.className : update;\n // eslint-disable-next-line no-console\n console.warn('[GramJs/updater] Unexpected update:', params);\n }\n}\n","import { errors } from '../../../lib/gramjs';\nimport {\n ApiUpdateAuthorizationState,\n ApiUpdateAuthorizationStateType,\n OnApiUpdate,\n ApiUser,\n} from '../../types';\n\nimport { DEBUG } from '../../../config';\n\nconst ApiErrors: { [k: string]: string } = {\n PHONE_NUMBER_INVALID: 'Invalid phone number.',\n PHONE_CODE_INVALID: 'Invalid code.',\n PASSWORD_HASH_INVALID: 'Incorrect password.',\n PHONE_PASSWORD_FLOOD: 'Limit exceeded. Please try again later.',\n PHONE_NUMBER_BANNED: 'This phone number is banned.',\n};\n\nconst authController: {\n resolve?: Function;\n reject?: Function;\n} = {};\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport function onRequestPhoneNumber() {\n onUpdate(buildAuthStateUpdate('authorizationStateWaitPhoneNumber'));\n\n return new Promise((resolve, reject) => {\n authController.resolve = resolve;\n authController.reject = reject;\n });\n}\n\nexport function onRequestCode(isCodeViaApp = false) {\n onUpdate({\n ...buildAuthStateUpdate('authorizationStateWaitCode'),\n isCodeViaApp,\n });\n\n return new Promise((resolve, reject) => {\n authController.resolve = resolve;\n authController.reject = reject;\n });\n}\n\nexport function onRequestPassword(hint?: string) {\n onUpdate({\n ...buildAuthStateUpdate('authorizationStateWaitPassword'),\n hint,\n });\n\n return new Promise((resolve) => {\n authController.resolve = resolve;\n });\n}\n\nexport function onRequestRegistration() {\n onUpdate(buildAuthStateUpdate('authorizationStateWaitRegistration'));\n\n return new Promise<[string, string?]>((resolve) => {\n authController.resolve = resolve;\n });\n}\n\nexport function onRequestQrCode(qrCode: { token: Buffer; expires: number }) {\n onUpdate({\n ...buildAuthStateUpdate('authorizationStateWaitQrCode'),\n qrCode: {\n token: btoa(String.fromCharCode(...qrCode.token)).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, ''),\n expires: qrCode.expires,\n },\n });\n\n return new Promise((resolve, reject) => {\n authController.reject = reject;\n });\n}\n\nexport function onAuthError(err: Error) {\n let message: string;\n\n if (err instanceof errors.FloodWaitError) {\n const hours = Math.ceil(Number(err.seconds) / 60 / 60);\n message = `Too many attempts. Try again in ${hours > 1 ? `${hours} hours` : 'an hour'}`;\n } else {\n message = ApiErrors[err.message];\n }\n\n if (!message) {\n message = 'Unexpected Error';\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n }\n\n onUpdate({\n '@type': 'updateAuthorizationError',\n message,\n });\n}\n\nexport function onAuthReady() {\n onUpdate(buildAuthStateUpdate('authorizationStateReady'));\n}\n\nexport function onCurrentUserUpdate(currentUser: ApiUser) {\n onUpdate({\n '@type': 'updateCurrentUser',\n currentUser,\n });\n}\n\nexport function buildAuthStateUpdate(authorizationState: ApiUpdateAuthorizationStateType): ApiUpdateAuthorizationState {\n return {\n '@type': 'updateAuthorizationState',\n authorizationState,\n };\n}\n\nexport function provideAuthPhoneNumber(phoneNumber: string) {\n if (!authController.resolve) {\n return;\n }\n\n authController.resolve(phoneNumber);\n}\n\nexport function provideAuthCode(code: string) {\n if (!authController.resolve) {\n return;\n }\n\n authController.resolve(code);\n}\n\nexport function provideAuthPassword(password: string) {\n if (!authController.resolve) {\n return;\n }\n\n authController.resolve(password);\n}\n\nexport function provideAuthRegistration(registration: { firstName: string; lastName: string }) {\n const { firstName, lastName } = registration;\n\n if (!authController.resolve) {\n return;\n }\n\n authController.resolve([firstName, lastName]);\n}\n\nexport function restartAuth() {\n if (!authController.reject) {\n return;\n }\n\n authController.reject(new Error('RESTART_AUTH'));\n}\n\nexport function restartAuthWithQr() {\n if (!authController.reject) {\n return;\n }\n\n authController.reject(new Error('RESTART_AUTH_WITH_QR'));\n}\n","// eslint-disable-next-line no-restricted-globals\nconst cacheApi = self.caches;\n\nexport enum Type {\n Text,\n Blob,\n Json,\n}\n\nexport async function fetch(\n cacheName: string, key: string, type: Type, isHtmlAllowed = false,\n) {\n if (!cacheApi) {\n return undefined;\n }\n\n try {\n // To avoid the error \"Request scheme 'webdocument' is unsupported\"\n const request = new Request(key.replace(/:/g, '_'));\n const cache = await cacheApi.open(cacheName);\n const response = await cache.match(request);\n if (!response) {\n return undefined;\n }\n\n const contentType = response.headers.get('Content-Type');\n\n switch (type) {\n case Type.Text:\n return await response.text();\n case Type.Blob: {\n // Ignore deprecated data-uri avatars\n if (key.startsWith('avatar') && contentType && contentType.startsWith('text')) {\n return undefined;\n }\n\n const blob = await response.blob();\n\n // Safari does not return correct Content-Type header for webp images.\n if (key.startsWith('sticker')) {\n return new Blob([blob], { type: 'image/webp' });\n }\n\n const shouldRecreate = !blob.type || (!isHtmlAllowed && blob.type.includes('html'));\n // iOS Safari fails to preserve `type` in cache\n let resolvedType = blob.type || contentType;\n\n if (!(shouldRecreate && resolvedType)) {\n return blob;\n }\n\n // Prevent HTML-in-video attacks (for files that were cached before fix)\n if (!isHtmlAllowed) {\n resolvedType = resolvedType.replace(/html/gi, '');\n }\n\n return new Blob([blob], { type: resolvedType });\n }\n case Type.Json:\n return await response.json();\n default:\n return undefined;\n }\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n\nexport async function save(cacheName: string, key: string, data: AnyLiteral | Blob | string) {\n if (!cacheApi) {\n return undefined;\n }\n\n try {\n const cacheData = typeof data === 'string' || data instanceof Blob ? data : JSON.stringify(data);\n // To avoid the error \"Request scheme 'webdocument' is unsupported\"\n const request = new Request(key.replace(/:/g, '_'));\n const response = new Response(cacheData);\n const cache = await cacheApi.open(cacheName);\n return await cache.put(request, response);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n\nexport async function clear(cacheName: string) {\n try {\n if (!cacheApi) {\n return undefined;\n }\n\n return await cacheApi.delete(cacheName);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n","import { inflate } from 'pako/dist/pako_inflate';\n\nimport { Api as GramJs, TelegramClient } from '../../../lib/gramjs';\nimport {\n ApiMediaFormat, ApiOnProgress, ApiParsedMedia, ApiPreparedMedia,\n} from '../../types';\n\nimport {\n DOWNLOAD_WORKERS,\n MEDIA_CACHE_DISABLED,\n MEDIA_CACHE_MAX_BYTES,\n MEDIA_CACHE_NAME,\n MEDIA_CACHE_NAME_AVATARS,\n} from '../../../config';\nimport localDb from '../localDb';\nimport { getEntityTypeById } from '../gramjsBuilders';\nimport * as cacheApi from '../../../util/cacheApi';\n\ntype EntityType = (\n 'msg' | 'sticker' | 'wallpaper' | 'gif' | 'channel' | 'chat' | 'user' | 'photo' | 'stickerSet' | 'webDocument'\n);\nconst MEDIA_ENTITY_TYPES = new Set(['msg', 'sticker', 'gif', 'wallpaper', 'photo', 'webDocument']);\n\nexport default async function downloadMedia(\n {\n url, mediaFormat, start, end, isHtmlAllowed,\n }: {\n url: string; mediaFormat: ApiMediaFormat; start?: number; end?: number; isHtmlAllowed?: boolean;\n },\n client: TelegramClient,\n isConnected: boolean,\n onProgress?: ApiOnProgress,\n) {\n const {\n data, mimeType, fullSize,\n } = await download(url, client, isConnected, onProgress, start, end, mediaFormat, isHtmlAllowed) || {};\n if (!data) {\n return undefined;\n }\n\n const parsed = await parseMedia(data, mediaFormat, mimeType);\n if (!parsed) {\n return undefined;\n }\n\n const canCache = mediaFormat !== ApiMediaFormat.Progressive && (\n mediaFormat !== ApiMediaFormat.BlobUrl || (parsed as Blob).size <= MEDIA_CACHE_MAX_BYTES\n );\n\n if (!MEDIA_CACHE_DISABLED && cacheApi && canCache) {\n const cacheName = url.startsWith('avatar') ? MEDIA_CACHE_NAME_AVATARS : MEDIA_CACHE_NAME;\n void cacheApi.save(cacheName, url, parsed);\n }\n\n const prepared = mediaFormat === ApiMediaFormat.Progressive ? '' : prepareMedia(parsed);\n const arrayBuffer = mediaFormat === ApiMediaFormat.Progressive ? parsed as ArrayBuffer : undefined;\n\n return {\n prepared,\n arrayBuffer,\n mimeType,\n fullSize,\n };\n}\n\nasync function download(\n url: string,\n client: TelegramClient,\n isConnected: boolean,\n onProgress?: ApiOnProgress,\n start?: number,\n end?: number,\n mediaFormat?: ApiMediaFormat,\n isHtmlAllowed?: boolean,\n) {\n const mediaMatch = url.startsWith('webDocument')\n ? url.match(/(webDocument):(.+)/)\n : url.match(/(avatar|profile|photo|msg|stickerSet|sticker|wallpaper|gif|file)([-\\d\\w./]+)(\\?size=\\w+)?/);\n if (!mediaMatch) {\n return undefined;\n }\n\n if (mediaMatch[1] === 'file') {\n const response = await fetch(mediaMatch[2]);\n const data = await response.arrayBuffer();\n return { data };\n }\n\n if (!isConnected) {\n return Promise.reject(new Error('ERROR: Client is not connected'));\n }\n\n let entityType: EntityType;\n const entityId: string | number = mediaMatch[2];\n const sizeType = mediaMatch[3] ? mediaMatch[3].replace('?size=', '') : undefined;\n let entity: (\n GramJs.User | GramJs.Chat | GramJs.Channel | GramJs.Photo |\n GramJs.Message | GramJs.MessageService |\n GramJs.Document | GramJs.StickerSet | GramJs.TypeWebDocument | undefined\n );\n\n if (mediaMatch[1] === 'avatar' || mediaMatch[1] === 'profile') {\n entityType = getEntityTypeById(entityId);\n } else {\n entityType = mediaMatch[1] as 'msg' | 'sticker' | 'wallpaper' | 'gif' | 'stickerSet' | 'photo' | 'webDocument';\n }\n\n switch (entityType) {\n case 'channel':\n case 'chat':\n entity = localDb.chats[entityId];\n break;\n case 'user':\n entity = localDb.users[entityId];\n break;\n case 'msg':\n entity = localDb.messages[entityId];\n break;\n case 'sticker':\n case 'gif':\n case 'wallpaper':\n entity = localDb.documents[entityId];\n break;\n case 'photo':\n entity = localDb.photos[entityId];\n break;\n case 'stickerSet':\n entity = localDb.stickerSets[entityId];\n break;\n case 'webDocument':\n entity = localDb.webDocuments[entityId];\n break;\n }\n\n if (!entity) {\n return undefined;\n }\n\n if (MEDIA_ENTITY_TYPES.has(entityType)) {\n if (mediaFormat === ApiMediaFormat.Stream) {\n onProgress!.acceptsBuffer = true;\n }\n\n const data = await client.downloadMedia(entity, {\n sizeType, start, end, progressCallback: onProgress, workers: DOWNLOAD_WORKERS,\n });\n let mimeType;\n let fullSize;\n\n if (entity instanceof GramJs.Message) {\n mimeType = getMessageMediaMimeType(entity, sizeType);\n if (entity.media instanceof GramJs.MessageMediaDocument && entity.media.document instanceof GramJs.Document) {\n fullSize = entity.media.document.size;\n }\n if (entity.media instanceof GramJs.MessageMediaWebPage\n && entity.media.webpage instanceof GramJs.WebPage\n && entity.media.webpage.document instanceof GramJs.Document) {\n fullSize = entity.media.webpage.document.size;\n }\n } else if (entity instanceof GramJs.Photo) {\n mimeType = 'image/jpeg';\n } else if (entityType === 'sticker' && sizeType) {\n mimeType = 'image/webp';\n } else if (entityType === 'webDocument') {\n mimeType = (entity as GramJs.TypeWebDocument).mimeType;\n } else {\n mimeType = (entity as GramJs.Document).mimeType;\n fullSize = (entity as GramJs.Document).size;\n }\n\n // Prevent HTML-in-video attacks\n if (!isHtmlAllowed && mimeType) {\n mimeType = mimeType.replace(/html/gi, '');\n }\n\n return { mimeType, data, fullSize };\n } else if (entityType === 'stickerSet') {\n const data = await client.downloadStickerSetThumb(entity);\n const mimeType = mediaFormat === ApiMediaFormat.Lottie ? 'application/json' : getMimeType(data);\n\n return { mimeType, data };\n } else {\n const data = await client.downloadProfilePhoto(entity, mediaMatch[1] === 'profile');\n const mimeType = getMimeType(data);\n\n return { mimeType, data };\n }\n}\n\nfunction getMessageMediaMimeType(message: GramJs.Message, sizeType?: string) {\n if (!message || !message.media) {\n return undefined;\n }\n\n if (message.media instanceof GramJs.MessageMediaPhoto) {\n return 'image/jpeg';\n }\n\n if (message.media instanceof GramJs.MessageMediaDocument && message.media.document instanceof GramJs.Document) {\n if (sizeType) {\n return message.media.document!.attributes.some((a) => a instanceof GramJs.DocumentAttributeSticker)\n ? 'image/webp'\n : 'image/jpeg';\n }\n\n return message.media.document!.mimeType;\n }\n\n if (message.media instanceof GramJs.MessageMediaWebPage\n && message.media.webpage instanceof GramJs.WebPage\n && message.media.webpage.document instanceof GramJs.Document) {\n return message.media.webpage.document.mimeType;\n }\n\n return undefined;\n}\n\n// eslint-disable-next-line no-async-without-await/no-async-without-await\nasync function parseMedia(\n data: Buffer, mediaFormat: ApiMediaFormat, mimeType?: string,\n): Promise {\n switch (mediaFormat) {\n case ApiMediaFormat.BlobUrl:\n return new Blob([data], { type: mimeType });\n case ApiMediaFormat.Lottie: {\n const json = inflate(data, { to: 'string' });\n return JSON.parse(json);\n }\n case ApiMediaFormat.Progressive: {\n return data.buffer;\n }\n }\n\n return undefined;\n}\n\nfunction prepareMedia(mediaData: ApiParsedMedia): ApiPreparedMedia {\n if (mediaData instanceof Blob) {\n return URL.createObjectURL(mediaData);\n }\n\n return mediaData;\n}\n\nfunction getMimeType(data: Uint8Array, fallbackMimeType = 'image/jpeg') {\n if (data.length < 4) {\n return fallbackMimeType;\n }\n\n let type = fallbackMimeType;\n const signature = data.subarray(0, 4).reduce((result, byte) => result + byte.toString(16), '');\n\n // https://en.wikipedia.org/wiki/List_of_file_signatures\n switch (signature) {\n case '89504e47':\n type = 'image/png';\n break;\n case '47494638':\n type = 'image/gif';\n break;\n case 'ffd8ffe0':\n case 'ffd8ffe1':\n case 'ffd8ffe2':\n case 'ffd8ffe3':\n case 'ffd8ffe8':\n type = 'image/jpeg';\n break;\n case '52494646':\n // In our case only webp is expected\n type = 'image/webp';\n break;\n }\n\n return type;\n}\n","import {\n TelegramClient, sessions, Api as GramJs, connection,\n} from '../../../lib/gramjs';\nimport { Logger as GramJsLogger } from '../../../lib/gramjs/extensions/index';\nimport { TwoFaParams } from '../../../lib/gramjs/client/2fa';\n\nimport {\n ApiInitialArgs,\n ApiMediaFormat,\n ApiOnProgress,\n ApiSessionData,\n OnApiUpdate,\n} from '../../types';\n\nimport {\n DEBUG, DEBUG_GRAMJS, UPLOAD_WORKERS, IS_TEST, APP_VERSION,\n} from '../../../config';\nimport {\n onRequestPhoneNumber, onRequestCode, onRequestPassword, onRequestRegistration,\n onAuthError, onAuthReady, onCurrentUserUpdate, onRequestQrCode,\n} from './auth';\nimport { updater } from '../updater';\nimport { setMessageBuilderCurrentUserId } from '../apiBuilders/messages';\nimport downloadMediaWithClient from './media';\nimport { buildApiUserFromFull } from '../apiBuilders/users';\nimport localDb from '../localDb';\nimport { buildApiPeerId } from '../apiBuilders/peers';\n\nconst DEFAULT_USER_AGENT = 'Unknown UserAgent';\nconst DEFAULT_PLATFORM = 'Unknown platform';\nconst APP_CODE_NAME = 'Z';\n\nGramJsLogger.setLevel(DEBUG_GRAMJS ? 'debug' : 'warn');\n\nconst gramJsUpdateEventBuilder = { build: (update: object) => update };\n\nlet onUpdate: OnApiUpdate;\nlet client: TelegramClient;\nlet isConnected = false;\n\nexport async function init(_onUpdate: OnApiUpdate, initialArgs: ApiInitialArgs) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START INIT API');\n }\n\n onUpdate = _onUpdate;\n\n const {\n userAgent, platform, sessionData, isTest, isMovSupported,\n } = initialArgs;\n const session = new sessions.CallbackSession(sessionData, onSessionUpdate);\n\n // eslint-disable-next-line no-restricted-globals\n (self as any).isMovSupported = isMovSupported;\n\n client = new TelegramClient(\n session,\n process.env.TELEGRAM_T_API_ID,\n process.env.TELEGRAM_T_API_HASH,\n {\n deviceModel: navigator.userAgent || userAgent || DEFAULT_USER_AGENT,\n systemVersion: platform || DEFAULT_PLATFORM,\n appVersion: `${APP_VERSION} ${APP_CODE_NAME}`,\n useWSS: true,\n additionalDcsDisabled: IS_TEST,\n testServers: isTest,\n } as any,\n );\n\n client.addEventHandler(handleGramJsUpdate, gramJsUpdateEventBuilder);\n client.addEventHandler(updater, gramJsUpdateEventBuilder);\n\n try {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[GramJs/client] CONNECTING');\n\n // eslint-disable-next-line no-restricted-globals\n (self as any).invoke = invokeRequest;\n // eslint-disable-next-line no-restricted-globals\n (self as any).GramJs = GramJs;\n }\n\n try {\n await client.start({\n phoneNumber: onRequestPhoneNumber,\n phoneCode: onRequestCode,\n password: onRequestPassword,\n firstAndLastNames: onRequestRegistration,\n qrCode: onRequestQrCode,\n onError: onAuthError,\n initialMethod: platform === 'iOS' || platform === 'Android' ? 'phoneNumber' : 'qrCode',\n });\n } catch (err) {\n // TODO Investigate which request causes this exception\n if (err.message !== 'Disconnect') {\n onUpdate({\n '@type': 'updateConnectionState',\n connectionState: 'connectionStateBroken',\n });\n\n return;\n }\n }\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH INIT API');\n // eslint-disable-next-line no-console\n console.log('[GramJs/client] CONNECTED');\n }\n\n onAuthReady();\n onSessionUpdate(session.getSessionData());\n onUpdate({ '@type': 'updateApiReady' });\n\n void fetchCurrentUser();\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[GramJs/client] CONNECTING ERROR', err);\n }\n\n throw err;\n }\n}\n\nexport async function destroy() {\n await invokeRequest(new GramJs.auth.LogOut());\n await client.destroy();\n}\n\nexport async function disconnect() {\n await client.disconnect();\n}\n\nexport function getClient() {\n return client;\n}\n\nfunction onSessionUpdate(sessionData: ApiSessionData) {\n onUpdate({\n '@type': 'updateSession',\n sessionData,\n });\n}\n\nfunction handleGramJsUpdate(update: any) {\n if (update instanceof connection.UpdateConnectionState) {\n isConnected = update.state === connection.UpdateConnectionState.connected;\n } else if (update instanceof GramJs.UpdatesTooLong) {\n void handleTerminatedSession();\n } else if (update instanceof connection.UpdateServerTimeOffset) {\n onUpdate({\n '@type': 'updateServerTimeOffset',\n serverTimeOffset: update.timeOffset,\n });\n }\n}\n\nexport async function invokeRequest(\n request: T,\n shouldHandleUpdates = false,\n shouldThrow = false,\n): Promise {\n if (!isConnected) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(`[GramJs/client] INVOKE ERROR ${request.className}: Client is not connected`);\n }\n\n return undefined;\n }\n\n try {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log(`[GramJs/client] INVOKE ${request.className}`);\n }\n\n const result = await client.invoke(request);\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log(`[GramJs/client] INVOKE RESPONSE ${request.className}`, result);\n }\n\n if (shouldHandleUpdates) {\n type ResultWithUpdates =\n typeof result\n & { updates?: GramJs.Updates | GramJs.UpdatesCombined };\n\n let updatesContainer;\n if (result instanceof GramJs.Updates || result instanceof GramJs.UpdatesCombined) {\n updatesContainer = result;\n } else if ('updates' in (result as ResultWithUpdates) && (\n (result as ResultWithUpdates).updates instanceof GramJs.Updates\n || (result as ResultWithUpdates).updates instanceof GramJs.UpdatesCombined\n )) {\n updatesContainer = (result as ResultWithUpdates).updates;\n }\n\n if (updatesContainer) {\n injectUpdateEntities(updatesContainer);\n\n updatesContainer.updates.forEach((update) => {\n updater(update, request);\n });\n } else if (result instanceof GramJs.UpdatesTooLong) {\n // TODO Implement\n } else {\n updater(result as GramJs.TypeUpdates, request);\n }\n }\n\n return result;\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log(`[GramJs/client] INVOKE ERROR ${request.className}`);\n // eslint-disable-next-line no-console\n console.error(err);\n }\n\n if (shouldThrow) {\n throw err;\n }\n\n dispatchErrorUpdate(err, request);\n\n return undefined;\n }\n}\n\nexport function downloadMedia(\n args: { url: string; mediaFormat: ApiMediaFormat; start?: number; end?: number; isHtmlAllowed?: boolean },\n onProgress?: ApiOnProgress,\n) {\n return downloadMediaWithClient(args, client, isConnected, onProgress);\n}\n\nexport function uploadFile(file: File, onProgress?: ApiOnProgress) {\n return client.uploadFile({ file, onProgress, workers: UPLOAD_WORKERS });\n}\n\nexport function updateTwoFaSettings(params: TwoFaParams) {\n return client.updateTwoFaSettings(params);\n}\n\nexport async function fetchCurrentUser() {\n const userFull = await invokeRequest(new GramJs.users.GetFullUser({\n id: new GramJs.InputUserSelf(),\n }));\n\n if (!userFull || !(userFull.user instanceof GramJs.User)) {\n return;\n }\n\n localDb.users[buildApiPeerId(userFull.user.id, 'user')] = userFull.user;\n const currentUser = buildApiUserFromFull(userFull);\n\n setMessageBuilderCurrentUserId(currentUser.id);\n onCurrentUserUpdate(currentUser);\n}\n\nexport function dispatchErrorUpdate(err: Error, request: T) {\n const isSlowMode = err.message.startsWith('A wait of') && (\n request instanceof GramJs.messages.SendMessage\n || request instanceof GramJs.messages.SendMedia\n || request instanceof GramJs.messages.SendMultiMedia\n );\n\n const { message } = err;\n\n onUpdate({\n '@type': 'error',\n error: {\n message,\n isSlowMode,\n hasErrorKey: true,\n },\n });\n}\n\nfunction injectUpdateEntities(result: GramJs.Updates | GramJs.UpdatesCombined) {\n const entities = [...result.users, ...result.chats];\n\n result.updates.forEach((update) => {\n if (entities) {\n // eslint-disable-next-line no-underscore-dangle\n (update as any)._entities = entities;\n }\n });\n}\n\nasync function handleTerminatedSession() {\n try {\n await invokeRequest(new GramJs.users.GetFullUser({\n id: new GramJs.InputUserSelf(),\n }), undefined, true);\n } catch (err) {\n if (err.message === 'AUTH_KEY_UNREGISTERED') {\n onUpdate({\n '@type': 'updateConnectionState',\n connectionState: 'connectionStateBroken',\n });\n }\n }\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport {\n OnApiUpdate,\n ApiChat,\n ApiMessage,\n ApiUser,\n ApiMessageEntity,\n ApiFormattedText,\n ApiChatFullInfo,\n ApiChatFolder,\n ApiChatBannedRights,\n ApiChatAdminRights,\n} from '../../types';\n\nimport {\n DEBUG, ARCHIVED_FOLDER_ID, MEMBERS_LOAD_SLICE, SERVICE_NOTIFICATIONS_USER_ID,\n} from '../../../config';\nimport { invokeRequest, uploadFile } from './client';\nimport {\n buildApiChatFromDialog,\n getPeerKey,\n buildChatMembers,\n buildApiChatFromPreview,\n buildApiChatFolder,\n buildApiChatFolderFromSuggested,\n buildApiChatBotCommands,\n} from '../apiBuilders/chats';\nimport { buildApiMessage, buildMessageDraft } from '../apiBuilders/messages';\nimport { buildApiUser } from '../apiBuilders/users';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport localDb from '../localDb';\nimport {\n buildInputEntity,\n buildInputPeer,\n buildMtpMessageEntity,\n buildFilterFromApiFolder,\n isMessageWithMedia,\n buildChatBannedRights,\n buildChatAdminRights,\n} from '../gramjsBuilders';\nimport { addChatToLocalDb, addMessageToLocalDb } from '../helpers';\nimport { buildApiPeerId, getApiChatIdFromMtpPeer } from '../apiBuilders/peers';\n\nconst MAX_INT_32 = 2 ** 31 - 1;\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function fetchChats({\n limit,\n offsetDate,\n archived,\n withPinned,\n serverTimeOffset,\n lastLocalServiceMessage,\n}: {\n limit: number;\n offsetDate?: number;\n archived?: boolean;\n withPinned?: boolean;\n serverTimeOffset: number;\n lastLocalServiceMessage?: ApiMessage;\n}) {\n const result = await invokeRequest(new GramJs.messages.GetDialogs({\n offsetPeer: new GramJs.InputPeerEmpty(),\n limit,\n offsetDate,\n folderId: archived ? ARCHIVED_FOLDER_ID : undefined,\n ...(withPinned && { excludePinned: true }),\n }));\n const resultPinned = withPinned\n ? await invokeRequest(new GramJs.messages.GetPinnedDialogs({\n folderId: archived ? ARCHIVED_FOLDER_ID : undefined,\n }))\n : undefined;\n\n if (!result || result instanceof GramJs.messages.DialogsNotModified) {\n return undefined;\n }\n\n if (resultPinned) {\n updateLocalDb(resultPinned);\n }\n updateLocalDb(result);\n\n const lastMessagesByChatId = buildCollectionByKey(\n (resultPinned ? resultPinned.messages : []).concat(result.messages)\n .map(buildApiMessage)\n .filter(Boolean as any),\n 'chatId',\n );\n const peersByKey: Record = {\n ...(resultPinned && preparePeers(resultPinned)),\n ...preparePeers(result),\n };\n const chats: ApiChat[] = [];\n const draftsById: Record = {};\n const replyingToById: Record = {};\n\n const dialogs = (resultPinned ? resultPinned.dialogs : []).concat(result.dialogs);\n\n const orderedPinnedIds: string[] = [];\n\n dialogs.forEach((dialog) => {\n if (\n !(dialog instanceof GramJs.Dialog)\n // This request can return dialogs not belonging to specified folder\n || (!archived && dialog.folderId === ARCHIVED_FOLDER_ID)\n || (archived && dialog.folderId !== ARCHIVED_FOLDER_ID)\n ) {\n return;\n }\n\n const peerEntity = peersByKey[getPeerKey(dialog.peer)];\n const chat = buildApiChatFromDialog(dialog, peerEntity, serverTimeOffset);\n\n if (\n chat.id === SERVICE_NOTIFICATIONS_USER_ID\n && lastLocalServiceMessage\n && (!lastMessagesByChatId[chat.id] || lastLocalServiceMessage.date > lastMessagesByChatId[chat.id].date)\n ) {\n chat.lastMessage = lastLocalServiceMessage;\n } else {\n chat.lastMessage = lastMessagesByChatId[chat.id];\n }\n\n chat.isListed = true;\n chats.push(chat);\n\n if (withPinned && dialog.pinned) {\n orderedPinnedIds.push(chat.id);\n }\n\n if (dialog.draft) {\n const { formattedText, replyingToId } = buildMessageDraft(dialog.draft) || {};\n if (formattedText) {\n draftsById[chat.id] = formattedText;\n }\n if (replyingToId) {\n replyingToById[chat.id] = replyingToId;\n }\n }\n });\n\n const users = (resultPinned ? resultPinned.users : []).concat(result.users)\n .map(buildApiUser)\n .filter(Boolean as any);\n const chatIds = chats.map((chat) => chat.id);\n\n let totalChatCount: number;\n\n if (result instanceof GramJs.messages.DialogsSlice) {\n totalChatCount = result.count;\n } else {\n totalChatCount = chatIds.length;\n }\n\n return {\n chatIds,\n chats,\n users,\n draftsById,\n replyingToById,\n orderedPinnedIds: withPinned ? orderedPinnedIds : undefined,\n totalChatCount,\n };\n}\n\nexport function fetchFullChat(chat: ApiChat) {\n const { id, accessHash, adminRights } = chat;\n\n const input = buildInputEntity(id, accessHash);\n\n return input instanceof GramJs.InputChannel\n ? getFullChannelInfo(id, accessHash!, adminRights)\n : getFullChatInfo(id);\n}\n\nexport async function searchChats({ query }: { query: string }) {\n const result = await invokeRequest(new GramJs.contacts.Search({ q: query }));\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const localPeerIds = result.myResults.map(getApiChatIdFromMtpPeer);\n const allChats = result.chats.concat(result.users)\n .map((user) => buildApiChatFromPreview(user))\n .filter(Boolean as any);\n const allUsers = result.users.map(buildApiUser).filter((user) => !!user && !user.isSelf) as ApiUser[];\n\n return {\n localChats: allChats.filter((r) => localPeerIds.includes(r.id)),\n localUsers: allUsers.filter((u) => localPeerIds.includes(u.id)),\n globalChats: allChats.filter((r) => !localPeerIds.includes(r.id)),\n globalUsers: allUsers.filter((u) => !localPeerIds.includes(u.id)),\n };\n}\n\nexport async function fetchChat({\n type, user,\n}: {\n type: 'user' | 'self' | 'support'; user?: ApiUser;\n}) {\n let mtpUser: GramJs.User | undefined;\n\n if (type === 'self' || type === 'user') {\n const result = await invokeRequest(new GramJs.users.GetUsers({\n id: [\n type === 'user' && user\n ? buildInputEntity(user.id, user.accessHash) as GramJs.InputUser\n : new GramJs.InputUserSelf(),\n ],\n }));\n if (!result || !result.length) {\n return undefined;\n }\n\n [mtpUser] = result;\n } else if (type === 'support') {\n const result = await invokeRequest(new GramJs.help.GetSupport());\n if (!result || !result.user) {\n return undefined;\n }\n\n mtpUser = result.user;\n }\n\n const chat = buildApiChatFromPreview(mtpUser!, type === 'support');\n if (!chat) {\n return undefined;\n }\n\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n\n return { chatId: chat.id };\n}\n\nexport async function requestChatUpdate({\n chat,\n serverTimeOffset,\n lastLocalMessage,\n noLastMessage,\n}: {\n chat: ApiChat; serverTimeOffset: number; lastLocalMessage?: ApiMessage; noLastMessage?: boolean;\n}) {\n const { id, accessHash } = chat;\n\n const result = await invokeRequest(new GramJs.messages.GetPeerDialogs({\n peers: [new GramJs.InputDialogPeer({\n peer: buildInputPeer(id, accessHash),\n })],\n }));\n\n if (!result) {\n return;\n }\n\n const dialog = result.dialogs[0];\n if (!dialog || !(dialog instanceof GramJs.Dialog)) {\n return;\n }\n\n const peersByKey = preparePeers(result);\n const peerEntity = peersByKey[getPeerKey(dialog.peer)];\n if (!peerEntity) {\n return;\n }\n\n updateLocalDb(result);\n\n const lastRemoteMessage = buildApiMessage(result.messages[0]);\n const lastMessage = lastLocalMessage && (!lastRemoteMessage || (lastLocalMessage.date > lastRemoteMessage.date))\n ? lastLocalMessage\n : lastRemoteMessage;\n\n onUpdate({\n '@type': 'updateChat',\n id,\n chat: {\n ...buildApiChatFromDialog(dialog, peerEntity, serverTimeOffset),\n ...(!noLastMessage && { lastMessage }),\n },\n });\n}\n\nexport function saveDraft({\n chat,\n text,\n entities,\n replyToMsgId,\n}: {\n chat: ApiChat;\n text: string;\n entities?: ApiMessageEntity[];\n replyToMsgId?: number;\n}) {\n return invokeRequest(new GramJs.messages.SaveDraft({\n peer: buildInputPeer(chat.id, chat.accessHash),\n message: text,\n ...(entities && {\n entities: entities.map(buildMtpMessageEntity),\n }),\n replyToMsgId,\n }));\n}\n\nexport function clearDraft(chat: ApiChat) {\n return invokeRequest(new GramJs.messages.SaveDraft({\n peer: buildInputPeer(chat.id, chat.accessHash),\n message: '',\n }));\n}\n\nasync function getFullChatInfo(chatId: string): Promise<{\n fullInfo: ApiChatFullInfo;\n users?: ApiUser[];\n} | 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 } = result.fullChat;\n\n const members = buildChatMembers(participants);\n const adminMembers = members ? members.filter(({ isAdmin, isOwner }) => isAdmin || isOwner) : undefined;\n const botCommands = botInfo ? buildApiChatBotCommands(botInfo) : undefined;\n\n return {\n fullInfo: {\n about,\n members,\n adminMembers,\n canViewMembers: true,\n botCommands,\n ...(exportedInvite && {\n inviteLink: exportedInvite.link,\n }),\n },\n users: result.users.map(buildApiUser).filter(Boolean as any),\n };\n}\n\nasync function getFullChannelInfo(\n id: string,\n accessHash: string,\n adminRights?: ApiChatAdminRights,\n) {\n const result = await invokeRequest(new GramJs.channels.GetFullChannel({\n channel: buildInputEntity(id, accessHash) as GramJs.InputChannel,\n }));\n\n if (!result || !(result.fullChat instanceof GramJs.ChannelFull)) {\n return undefined;\n }\n\n const {\n about,\n onlineCount,\n exportedInvite,\n slowmodeSeconds,\n slowmodeNextSendDate,\n migratedFromChatId,\n migratedFromMaxId,\n canViewParticipants,\n linkedChatId,\n hiddenPrehistory,\n call,\n botInfo,\n } = result.fullChat;\n\n const inviteLink = exportedInvite instanceof GramJs.ChatInviteExported\n ? exportedInvite.link\n : undefined;\n\n const { members, users } = (canViewParticipants && await fetchMembers(id, accessHash)) || {};\n const { members: kickedMembers, users: bannedUsers } = (\n canViewParticipants && adminRights && await fetchMembers(id, accessHash, 'kicked')\n ) || {};\n const { members: adminMembers, users: adminUsers } = (\n canViewParticipants && adminRights && await fetchMembers(id, accessHash, 'admin')\n ) || {};\n const botCommands = botInfo ? buildApiChatBotCommands(botInfo) : undefined;\n\n if (result?.chats?.length > 1) {\n updateLocalDb(result);\n\n const [, mtpLinkedChat] = result.chats;\n const chat = buildApiChatFromPreview(mtpLinkedChat, undefined, true);\n if (chat) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n }\n }\n\n return {\n fullInfo: {\n about,\n onlineCount,\n inviteLink,\n slowMode: slowmodeSeconds ? {\n seconds: slowmodeSeconds,\n nextSendDate: slowmodeNextSendDate,\n } : undefined,\n migratedFrom: migratedFromChatId ? {\n chatId: buildApiPeerId(migratedFromChatId, 'chat'),\n maxMessageId: migratedFromMaxId,\n } : undefined,\n canViewMembers: canViewParticipants,\n isPreHistoryHidden: hiddenPrehistory,\n members,\n kickedMembers,\n adminMembers,\n groupCallId: call ? String(call.id) : undefined,\n linkedChatId: linkedChatId ? buildApiPeerId(linkedChatId, 'chat') : undefined,\n botCommands,\n },\n users: [...(users || []), ...(bannedUsers || []), ...(adminUsers || [])],\n };\n}\n\nexport async function updateChatMutedState({\n chat, isMuted, serverTimeOffset,\n}: {\n chat: ApiChat; isMuted: boolean; serverTimeOffset: number;\n}) {\n await invokeRequest(new GramJs.account.UpdateNotifySettings({\n peer: new GramJs.InputNotifyPeer({\n peer: buildInputPeer(chat.id, chat.accessHash),\n }),\n settings: new GramJs.InputPeerNotifySettings({ muteUntil: isMuted ? MAX_INT_32 : 0 }),\n }));\n\n onUpdate({\n '@type': 'updateNotifyExceptions',\n chatId: chat.id,\n isMuted,\n });\n\n void requestChatUpdate({\n chat,\n serverTimeOffset,\n noLastMessage: true,\n });\n}\n\nexport async function createChannel({\n title, about, users,\n}: {\n title: string; about?: string; users: ApiUser[];\n}): Promise {\n const result = await invokeRequest(new GramJs.channels.CreateChannel({\n broadcast: true,\n title,\n about,\n }), true);\n\n // `createChannel` can return a lot of different update types according to docs,\n // but currently channel creation returns only `Updates` type.\n // Errors are added to catch unexpected cases in future testing\n if (!(result instanceof GramJs.Updates)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected channel creation update', result);\n }\n return undefined;\n }\n\n const newChannel = result.chats[0];\n if (!newChannel || !(newChannel instanceof GramJs.Channel)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Created channel not found', result);\n }\n return undefined;\n }\n\n const channel = buildApiChatFromPreview(newChannel)!;\n\n await invokeRequest(new GramJs.channels.InviteToChannel({\n channel: buildInputEntity(channel.id, channel.accessHash) as GramJs.InputChannel,\n users: users.map(({ id, accessHash }) => buildInputEntity(id, accessHash)) as GramJs.InputUser[],\n }));\n\n return channel;\n}\n\nexport function joinChannel({\n channelId, accessHash,\n}: {\n channelId: string; accessHash: string;\n}) {\n return invokeRequest(new GramJs.channels.JoinChannel({\n channel: buildInputEntity(channelId, accessHash) as GramJs.InputChannel,\n }), true);\n}\n\nexport function deleteChatUser({\n chat, user,\n}: {\n chat: ApiChat; user: ApiUser;\n}) {\n if (chat.type !== 'chatTypeBasicGroup') return undefined;\n return invokeRequest(new GramJs.messages.DeleteChatUser({\n chatId: buildInputEntity(chat.id, chat.accessHash) as BigInt.BigInteger,\n userId: buildInputEntity(user.id, user.accessHash) as GramJs.InputUser,\n }), true);\n}\n\nexport function deleteChat({\n chatId,\n}: {\n chatId: string;\n}) {\n return invokeRequest(new GramJs.messages.DeleteChat({\n chatId: buildInputEntity(chatId) as BigInt.BigInteger,\n }), true);\n}\n\nexport function leaveChannel({\n channelId, accessHash,\n}: {\n channelId: string; accessHash: string;\n}) {\n return invokeRequest(new GramJs.channels.LeaveChannel({\n channel: buildInputEntity(channelId, accessHash) as GramJs.InputChannel,\n }), true);\n}\n\nexport function deleteChannel({\n channelId, accessHash,\n}: {\n channelId: string; accessHash: string;\n}) {\n return invokeRequest(new GramJs.channels.DeleteChannel({\n channel: buildInputEntity(channelId, accessHash) as GramJs.InputChannel,\n }), true);\n}\n\nexport async function createGroupChat({\n title, users,\n}: {\n title: string; users: ApiUser[];\n}): Promise {\n const result = await invokeRequest(new GramJs.messages.CreateChat({\n title,\n users: users.map(({ id, accessHash }) => buildInputEntity(id, accessHash)) as GramJs.InputUser[],\n }), true, true);\n\n // `createChat` can return a lot of different update types according to docs,\n // but currently chat creation returns only `Updates` type.\n // Errors are added to catch unexpected cases in future testing\n if (!(result instanceof GramJs.Updates)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected chat creation update', result);\n }\n return undefined;\n }\n\n const newChat = result.chats[0];\n if (!newChat || !(newChat instanceof GramJs.Chat)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Created chat not found', result);\n }\n return undefined;\n }\n\n return buildApiChatFromPreview(newChat);\n}\n\nexport async function editChatPhoto({\n chatId, accessHash, photo,\n}: {\n chatId: string; accessHash?: string; photo: File;\n}) {\n const uploadedPhoto = await uploadFile(photo);\n const inputEntity = buildInputEntity(chatId, accessHash);\n\n return invokeRequest(\n inputEntity instanceof GramJs.InputChannel\n ? new GramJs.channels.EditPhoto({\n channel: inputEntity as GramJs.InputChannel,\n photo: new GramJs.InputChatUploadedPhoto({\n file: uploadedPhoto,\n }),\n })\n : new GramJs.messages.EditChatPhoto({\n chatId: inputEntity as BigInt.BigInteger,\n photo: new GramJs.InputChatUploadedPhoto({\n file: uploadedPhoto,\n }),\n }),\n true,\n );\n}\n\nexport async function toggleChatPinned({\n chat,\n shouldBePinned,\n}: {\n chat: ApiChat;\n shouldBePinned: boolean;\n}) {\n const { id, accessHash } = chat;\n\n const isActionSuccessful = await invokeRequest(new GramJs.messages.ToggleDialogPin({\n peer: new GramJs.InputDialogPeer({\n peer: buildInputPeer(id, accessHash),\n }),\n pinned: shouldBePinned || undefined,\n }));\n\n if (isActionSuccessful) {\n onUpdate({\n '@type': 'updateChatPinned',\n id: chat.id,\n isPinned: shouldBePinned,\n });\n }\n}\n\nexport function toggleChatArchived({\n chat, folderId,\n}: {\n chat: ApiChat; folderId: number;\n}) {\n const { id, accessHash } = chat;\n\n return invokeRequest(new GramJs.folders.EditPeerFolders({\n folderPeers: [new GramJs.InputFolderPeer({\n peer: buildInputPeer(id, accessHash),\n folderId,\n })],\n }), true);\n}\n\nexport async function fetchChatFolders() {\n const result = await invokeRequest(new GramJs.messages.GetDialogFilters());\n\n if (!result) {\n return undefined;\n }\n\n return {\n byId: buildCollectionByKey(result.map(buildApiChatFolder), 'id') as Record,\n orderedIds: result.map(({ id }) => id),\n };\n}\n\nexport async function fetchRecommendedChatFolders() {\n const results = await invokeRequest(new GramJs.messages.GetSuggestedDialogFilters());\n\n if (!results) {\n return undefined;\n }\n\n return results.map(buildApiChatFolderFromSuggested);\n}\n\nexport async function editChatFolder({\n id,\n folderUpdate,\n}: {\n id: number;\n folderUpdate: ApiChatFolder;\n}) {\n const filter = buildFilterFromApiFolder(folderUpdate);\n\n const isActionSuccessful = await invokeRequest(new GramJs.messages.UpdateDialogFilter({\n id,\n filter,\n }));\n\n if (isActionSuccessful) {\n onUpdate({\n '@type': 'updateChatFolder',\n id,\n folder: folderUpdate,\n });\n }\n}\n\nexport async function deleteChatFolder(id: number) {\n const isActionSuccessful = await invokeRequest(new GramJs.messages.UpdateDialogFilter({\n id,\n filter: undefined,\n }));\n const recommendedChatFolders = await fetchRecommendedChatFolders();\n\n if (isActionSuccessful) {\n onUpdate({\n '@type': 'updateChatFolder',\n id,\n folder: undefined,\n });\n }\n if (recommendedChatFolders) {\n onUpdate({\n '@type': 'updateRecommendedChatFolders',\n folders: recommendedChatFolders,\n });\n }\n}\n\nexport async function toggleDialogUnread({\n chat, hasUnreadMark,\n}: {\n chat: ApiChat; hasUnreadMark: boolean | undefined;\n}) {\n const { id, accessHash } = chat;\n\n const isActionSuccessful = await invokeRequest(new GramJs.messages.MarkDialogUnread({\n peer: new GramJs.InputDialogPeer({\n peer: buildInputPeer(id, accessHash),\n }),\n unread: hasUnreadMark || undefined,\n }));\n\n if (isActionSuccessful) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat: { hasUnreadMark },\n });\n }\n}\n\nexport async function getChatByUsername(username: string) {\n const result = await invokeRequest(new GramJs.contacts.ResolveUsername({\n username,\n }));\n\n if (!result) {\n return undefined;\n }\n\n const { users, chats } = result;\n\n const chat = chats.length\n ? buildApiChatFromPreview(chats[0])\n : buildApiChatFromPreview(users[0]);\n\n if (!chat) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return chat;\n}\n\nexport function togglePreHistoryHidden({\n chat, isEnabled,\n}: { chat: ApiChat; isEnabled: boolean }) {\n const { id, accessHash } = chat;\n const channel = buildInputEntity(id, accessHash);\n\n return invokeRequest(new GramJs.channels.TogglePreHistoryHidden({\n channel: channel as GramJs.InputChannel,\n enabled: isEnabled,\n }), true);\n}\n\nexport function updateChatDefaultBannedRights({\n chat, bannedRights,\n}: { chat: ApiChat; bannedRights: ApiChatBannedRights }) {\n const { id, accessHash } = chat;\n const peer = buildInputPeer(id, accessHash);\n\n return invokeRequest(new GramJs.messages.EditChatDefaultBannedRights({\n peer,\n bannedRights: buildChatBannedRights(bannedRights),\n }), true);\n}\n\nexport function updateChatMemberBannedRights({\n chat, user, bannedRights, untilDate,\n}: { chat: ApiChat; user: ApiUser; bannedRights: ApiChatBannedRights; untilDate?: number }) {\n const channel = buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel;\n const participant = buildInputPeer(user.id, user.accessHash) as GramJs.InputUser;\n\n return invokeRequest(new GramJs.channels.EditBanned({\n channel,\n participant,\n bannedRights: buildChatBannedRights(bannedRights, untilDate),\n }), true);\n}\n\nexport function updateChatAdmin({\n chat, user, adminRights, customTitle = '',\n}: { chat: ApiChat; user: ApiUser; adminRights: ApiChatAdminRights; customTitle: string }) {\n const channel = buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel;\n const userId = buildInputEntity(user.id, user.accessHash) as GramJs.InputUser;\n\n return invokeRequest(new GramJs.channels.EditAdmin({\n channel,\n userId,\n adminRights: buildChatAdminRights(adminRights),\n rank: customTitle,\n }), true);\n}\n\nexport async function updateChatTitle(chat: ApiChat, title: string) {\n const inputEntity = buildInputEntity(chat.id, chat.accessHash);\n await invokeRequest(\n inputEntity instanceof GramJs.InputChannel\n ? new GramJs.channels.EditTitle({\n channel: inputEntity as GramJs.InputChannel,\n title,\n }) : new GramJs.messages.EditChatTitle({\n chatId: inputEntity as BigInt.BigInteger,\n title,\n }),\n true,\n );\n}\n\nexport async function updateChatAbout(chat: ApiChat, about: string) {\n const result = await invokeRequest(new GramJs.messages.EditChatAbout({\n peer: buildInputPeer(chat.id, chat.accessHash),\n about,\n }));\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'updateChatFullInfo',\n id: chat.id,\n fullInfo: {\n about,\n },\n });\n}\n\nexport function toggleSignatures({\n chat, isEnabled,\n}: { chat: ApiChat; isEnabled: boolean }) {\n const { id, accessHash } = chat;\n const channel = buildInputEntity(id, accessHash);\n\n return invokeRequest(new GramJs.channels.ToggleSignatures({\n channel: channel as GramJs.InputChannel,\n enabled: isEnabled,\n }), true);\n}\n\ntype ChannelMembersFilter =\n 'kicked'\n | 'admin'\n | 'recent';\n\nexport async function fetchMembers(\n chatId: string,\n accessHash: string,\n memberFilter: ChannelMembersFilter = 'recent',\n offset?: number,\n) {\n let filter: GramJs.TypeChannelParticipantsFilter;\n\n switch (memberFilter) {\n case 'kicked':\n filter = new GramJs.ChannelParticipantsKicked({ q: '' });\n break;\n case 'admin':\n filter = new GramJs.ChannelParticipantsAdmins();\n break;\n default:\n filter = new GramJs.ChannelParticipantsRecent();\n break;\n }\n\n const result = await invokeRequest(new GramJs.channels.GetParticipants({\n channel: buildInputEntity(chatId, accessHash) as GramJs.InputChannel,\n filter,\n offset,\n limit: MEMBERS_LOAD_SLICE,\n }));\n\n if (!result || result instanceof GramJs.channels.ChannelParticipantsNotModified) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return {\n members: buildChatMembers(result),\n users: result.users.map(buildApiUser).filter(Boolean as any),\n };\n}\n\nexport async function fetchGroupsForDiscussion() {\n const result = await invokeRequest(new GramJs.channels.GetGroupsForDiscussion());\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return result.chats.map((chat) => buildApiChatFromPreview(chat));\n}\n\nexport function setDiscussionGroup({\n channel,\n chat,\n}: {\n channel: ApiChat;\n chat?: ApiChat;\n}) {\n return invokeRequest(new GramJs.channels.SetDiscussionGroup({\n broadcast: buildInputPeer(channel.id, channel.accessHash),\n group: chat ? buildInputPeer(chat.id, chat.accessHash) : new GramJs.InputChannelEmpty(),\n }));\n}\n\nexport async function migrateChat(chat: ApiChat) {\n const result = await invokeRequest(\n new GramJs.messages.MigrateChat({ chatId: buildInputEntity(chat.id) as BigInt.BigInteger }), true,\n );\n\n // `migrateChat` can return a lot of different update types according to docs,\n // but currently chat migrations returns only `Updates` type.\n // Errors are added to catch unexpected cases in future testing\n if (!result || !(result instanceof GramJs.Updates)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected channel creation update', result);\n }\n\n return undefined;\n }\n\n updateLocalDb(result);\n\n return buildApiChatFromPreview(result.chats[1]);\n}\n\nexport async function openChatByInvite(hash: string) {\n const result = await invokeRequest(new GramJs.messages.CheckChatInvite({ hash }));\n\n if (!result) {\n return undefined;\n }\n\n let chat: ApiChat | undefined;\n\n if (result instanceof GramJs.ChatInvite) {\n onUpdate({\n '@type': 'showInvite',\n data: {\n title: result.title,\n hash,\n participantsCount: result.participantsCount,\n isChannel: result.channel,\n },\n });\n } else {\n chat = buildApiChatFromPreview(result.chat);\n\n if (chat) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n }\n }\n\n if (!chat) {\n return undefined;\n }\n\n return { chatId: chat.id };\n}\n\nexport function addChatMembers(chat: ApiChat, users: ApiUser[]) {\n if (chat.type === 'chatTypeChannel' || chat.type === 'chatTypeSuperGroup') {\n return invokeRequest(new GramJs.channels.InviteToChannel({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n users: users.map((user) => buildInputEntity(user.id, user.accessHash)) as GramJs.InputUser[],\n }), true);\n }\n\n return Promise.all(users.map((user) => {\n return invokeRequest(new GramJs.messages.AddChatUser({\n chatId: buildInputEntity(chat.id) as BigInt.BigInteger,\n userId: buildInputEntity(user.id, user.accessHash) as GramJs.InputUser,\n }), true);\n }));\n}\n\nexport function deleteChatMember(chat: ApiChat, user: ApiUser) {\n if (chat.type === 'chatTypeChannel' || chat.type === 'chatTypeSuperGroup') {\n return updateChatMemberBannedRights({\n chat,\n user,\n bannedRights: {\n viewMessages: true,\n sendMessages: true,\n sendMedia: true,\n sendStickers: true,\n sendGifs: true,\n sendGames: true,\n sendInline: true,\n embedLinks: true,\n sendPolls: true,\n changeInfo: true,\n inviteUsers: true,\n pinMessages: true,\n },\n untilDate: MAX_INT_32,\n });\n } else {\n return invokeRequest(new GramJs.messages.DeleteChatUser({\n chatId: buildInputEntity(chat.id) as BigInt.BigInteger,\n userId: buildInputEntity(user.id, user.accessHash) as GramJs.InputUser,\n }), true);\n }\n}\n\nfunction preparePeers(\n result: GramJs.messages.Dialogs | GramJs.messages.DialogsSlice | GramJs.messages.PeerDialogs,\n) {\n const store: Record = {};\n\n result.chats.forEach((chat) => {\n store[`chat${chat.id}`] = chat;\n });\n\n result.users.forEach((user) => {\n store[`user${user.id}`] = user;\n });\n\n return store;\n}\n\nfunction updateLocalDb(result: (\n GramJs.messages.Dialogs | GramJs.messages.DialogsSlice | GramJs.messages.PeerDialogs |\n GramJs.messages.ChatFull | GramJs.contacts.Found |\n GramJs.contacts.ResolvedPeer | GramJs.channels.ChannelParticipants |\n GramJs.messages.Chats | GramJs.messages.ChatsSlice | GramJs.TypeUpdates\n)) {\n if ('users' in result) {\n result.users.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[buildApiPeerId(user.id, 'user')] = user;\n }\n });\n }\n\n if ('chats' in result) {\n result.chats.forEach(addChatToLocalDb);\n }\n\n if ('messages' in result) {\n result.messages.forEach((message) => {\n if (message instanceof GramJs.Message && isMessageWithMedia(message)) {\n addMessageToLocalDb(message);\n }\n });\n }\n}\n\nexport async function importChatInvite({ hash }: { hash: string }) {\n const updates = await invokeRequest(new GramJs.messages.ImportChatInvite({ hash }), true);\n if (!(updates instanceof GramJs.Updates) || !updates.chats.length) {\n return undefined;\n }\n\n return buildApiChatFromPreview(updates.chats[0]);\n}\n","import { pause } from './schedulers';\n\n// Polyfill for Safari: `File` is not available in web worker\nif (typeof File === 'undefined') {\n // eslint-disable-next-line no-global-assign, no-restricted-globals, func-names\n self.File = class extends Blob {\n name: string;\n\n constructor(fileBits: BlobPart[], fileName: string, options?: FilePropertyBag) {\n if (options) {\n const { type, ...rest } = options;\n super(fileBits, { type });\n Object.assign(this, rest);\n } else {\n super(fileBits);\n }\n\n this.name = fileName;\n }\n } as typeof File;\n}\n\nexport function dataUriToBlob(dataUri: string) {\n const arr = dataUri.split(',');\n const mime = arr[0].match(/:(.*?);/)![1];\n const bstr = atob(arr[1]);\n let n = bstr.length;\n const u8arr = new Uint8Array(n);\n\n while (n--) {\n u8arr[n] = bstr.charCodeAt(n);\n }\n\n return new Blob([u8arr], { type: mime });\n}\n\nexport function blobToDataUri(blob: Blob): Promise {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n\n reader.onload = (e: ProgressEvent) => {\n const { result } = e.target || {};\n if (typeof result === 'string') {\n resolve(result);\n }\n\n reject(new Error('Failed to read blob'));\n };\n\n reader.onerror = reject;\n reader.readAsDataURL(blob);\n });\n}\n\nexport function blobToFile(blob: Blob, fileName: string) {\n return new File([blob], fileName, {\n lastModified: Date.now(),\n type: blob.type,\n });\n}\n\nexport function preloadImage(url: string): Promise {\n return new Promise((resolve, reject) => {\n const img = new Image();\n img.onload = () => resolve(img);\n img.onerror = reject;\n img.src = url;\n });\n}\n\nexport function preloadVideo(url: string): Promise {\n return new Promise((resolve, reject) => {\n const video = document.createElement('video');\n video.volume = 0;\n video.onloadedmetadata = () => resolve(video);\n video.onerror = reject;\n video.src = url;\n });\n}\n\nexport async function createPosterForVideo(url: string): Promise {\n const video = await preloadVideo(url);\n\n return Promise.race([\n pause(2000) as Promise,\n new Promise((resolve, reject) => {\n video.onseeked = () => {\n if (!video.videoWidth || !video.videoHeight) {\n resolve(undefined);\n }\n\n const canvas = document.createElement('canvas');\n canvas.width = video.videoWidth;\n canvas.height = video.videoHeight;\n const ctx = canvas.getContext('2d')!;\n ctx.drawImage(video, 0, 0);\n resolve(canvas.toDataURL('image/jpeg'));\n };\n video.onerror = reject;\n video.currentTime = Math.min(video.duration, 1);\n }),\n ]);\n}\n\nexport async function fetchBlob(blobUrl: string) {\n const response = await fetch(blobUrl);\n return response.blob();\n}\n\nexport async function fetchFile(blobUrl: string, fileName: string) {\n const blob = await fetchBlob(blobUrl);\n return blobToFile(blob, fileName);\n}\n\nexport function imgToCanvas(img: HTMLImageElement) {\n const canvas = document.createElement('canvas');\n canvas.width = img.width;\n canvas.height = img.height;\n\n const ctx = canvas.getContext('2d')!;\n ctx.drawImage(img, 0, 0);\n\n return canvas;\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n ApiChat,\n ApiAttachment,\n ApiMessage,\n OnApiUpdate,\n ApiMessageSearchType,\n ApiUser,\n ApiSticker,\n ApiVideo,\n ApiNewPoll,\n ApiMessageEntity,\n ApiOnProgress,\n ApiThreadInfo,\n MAIN_THREAD_ID,\n MESSAGE_DELETED,\n ApiGlobalMessageSearchType,\n ApiReportReason,\n} from '../../types';\n\nimport {\n ALL_FOLDER_ID,\n DEBUG,\n PINNED_MESSAGES_LIMIT,\n SUPPORTED_IMAGE_CONTENT_TYPES,\n SUPPORTED_VIDEO_CONTENT_TYPES,\n} from '../../../config';\nimport { invokeRequest, uploadFile } from './client';\nimport {\n buildApiMessage,\n buildLocalMessage,\n buildWebPage,\n buildLocalForwardedMessage,\n} from '../apiBuilders/messages';\nimport { buildApiUser } from '../apiBuilders/users';\nimport {\n buildInputEntity,\n buildInputPeer,\n generateRandomBigInt,\n getEntityTypeById,\n buildInputMediaDocument,\n buildInputPoll,\n buildMtpMessageEntity,\n isMessageWithMedia,\n isServiceMessageWithMedia,\n buildInputReportReason,\n} from '../gramjsBuilders';\nimport localDb from '../localDb';\nimport { buildApiChatFromPreview } from '../apiBuilders/chats';\nimport { fetchFile } from '../../../util/files';\nimport { addMessageToLocalDb, resolveMessageApiChatId } from '../helpers';\nimport { interpolateArray } from '../../../util/waveform';\nimport { requestChatUpdate } from './chats';\nimport { buildApiPeerId } from '../apiBuilders/peers';\n\nconst FAST_SEND_TIMEOUT = 1000;\nconst INPUT_WAVEFORM_LENGTH = 63;\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function fetchMessages({\n chat,\n threadId,\n ...pagination\n}: {\n chat: ApiChat;\n threadId?: number;\n offsetId?: number;\n addOffset?: number;\n limit: number;\n}) {\n const RequestClass = threadId === MAIN_THREAD_ID ? GramJs.messages.GetHistory : GramJs.messages.GetReplies;\n let result;\n\n try {\n result = await invokeRequest(new RequestClass({\n peer: buildInputPeer(chat.id, chat.accessHash),\n ...(threadId !== MAIN_THREAD_ID && {\n msgId: threadId,\n }),\n ...pagination,\n }), undefined, true);\n } catch (err) {\n if (err.message === 'CHANNEL_PRIVATE') {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat: {\n isRestricted: true,\n },\n });\n }\n }\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter(Boolean as any);\n const threadInfos = messages.map(({ threadInfo }) => threadInfo).filter(Boolean as any);\n\n return {\n messages,\n users,\n chats,\n threadInfos,\n };\n}\n\nexport async function fetchMessage({ chat, messageId }: { chat: ApiChat; messageId: number }) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n\n let result;\n try {\n result = await invokeRequest(\n isChannel\n ? new GramJs.channels.GetMessages({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n id: [new GramJs.InputMessageID({ id: messageId })],\n })\n : new GramJs.messages.GetMessages({\n id: [new GramJs.InputMessageID({ id: messageId })],\n }),\n undefined,\n true,\n );\n } catch (err) {\n const { message } = err;\n\n // When fetching messages for the bot @replies, there may be situations when the user was banned\n // in the comment group or this group was deleted\n if (message !== 'CHANNEL_PRIVATE') {\n onUpdate({\n '@type': 'error',\n error: {\n message,\n isSlowMode: false,\n hasErrorKey: true,\n },\n });\n }\n }\n\n if (!result || result instanceof GramJs.messages.MessagesNotModified) {\n return undefined;\n }\n\n const mtpMessage = result.messages[0];\n if (!mtpMessage) {\n return undefined;\n }\n\n if (mtpMessage instanceof GramJs.MessageEmpty) {\n return MESSAGE_DELETED;\n }\n\n const message = mtpMessage && buildApiMessage(mtpMessage);\n if (!message) {\n return undefined;\n }\n\n if (mtpMessage instanceof GramJs.Message) {\n addMessageToLocalDb(mtpMessage);\n }\n\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n\n return { message, users };\n}\n\nlet queue = Promise.resolve();\n\nexport function sendMessage(\n {\n chat,\n text,\n entities,\n replyingTo,\n attachment,\n sticker,\n gif,\n poll,\n isSilent,\n scheduledAt,\n groupedId,\n noWebPage,\n serverTimeOffset,\n }: {\n chat: ApiChat;\n text?: string;\n entities?: ApiMessageEntity[];\n replyingTo?: number;\n attachment?: ApiAttachment;\n sticker?: ApiSticker;\n gif?: ApiVideo;\n poll?: ApiNewPoll;\n isSilent?: boolean;\n scheduledAt?: number;\n groupedId?: string;\n noWebPage?: boolean;\n serverTimeOffset?: number;\n },\n onProgress?: ApiOnProgress,\n) {\n const localMessage = buildLocalMessage(\n chat, text, entities, replyingTo, attachment, sticker, gif, poll, groupedId, scheduledAt, serverTimeOffset,\n );\n onUpdate({\n '@type': localMessage.isScheduled ? 'newScheduledMessage' : 'newMessage',\n id: localMessage.id,\n chatId: chat.id,\n message: localMessage,\n });\n\n // This is expected to arrive after `updateMessageSendSucceeded` which replaces the local ID,\n // so in most cases this will be simply ignored\n setTimeout(() => {\n onUpdate({\n '@type': localMessage.isScheduled ? 'updateScheduledMessage' : 'updateMessage',\n id: localMessage.id,\n chatId: chat.id,\n message: {\n sendingState: 'messageSendingStatePending',\n },\n });\n }, FAST_SEND_TIMEOUT);\n\n const randomId = generateRandomBigInt();\n localDb.localMessages[String(randomId)] = localMessage;\n\n if (groupedId) {\n return sendGroupedMedia({\n chat, text, entities, replyingTo, attachment: attachment!, groupedId, isSilent, scheduledAt,\n }, randomId, localMessage, onProgress);\n }\n\n const prevQueue = queue;\n queue = (async () => {\n let media: GramJs.TypeInputMedia | undefined;\n if (attachment) {\n try {\n media = await uploadMedia(localMessage, attachment, onProgress!);\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n\n await prevQueue;\n\n return;\n }\n } else if (sticker) {\n media = buildInputMediaDocument(sticker);\n } else if (gif) {\n media = buildInputMediaDocument(gif);\n } else if (poll) {\n media = buildInputPoll(poll, randomId);\n }\n\n await prevQueue;\n\n const RequestClass = media ? GramJs.messages.SendMedia : GramJs.messages.SendMessage;\n\n await invokeRequest(new RequestClass({\n clearDraft: true,\n message: text || '',\n entities: entities ? entities.map(buildMtpMessageEntity) : undefined,\n peer: buildInputPeer(chat.id, chat.accessHash),\n randomId,\n ...(isSilent && { silent: isSilent }),\n ...(scheduledAt && { scheduleDate: scheduledAt }),\n ...(replyingTo && { replyToMsgId: replyingTo }),\n ...(media && { media }),\n ...(noWebPage && { noWebpage: noWebPage }),\n }), true);\n })();\n\n return queue;\n}\n\nconst groupedUploads: Record;\n}> = {};\n\nfunction sendGroupedMedia(\n {\n chat,\n text,\n entities,\n replyingTo,\n attachment,\n groupedId,\n isSilent,\n scheduledAt,\n }: {\n chat: ApiChat;\n text?: string;\n entities?: ApiMessageEntity[];\n replyingTo?: number;\n attachment: ApiAttachment;\n groupedId: string;\n isSilent?: boolean;\n scheduledAt?: number;\n },\n randomId: GramJs.long,\n localMessage: ApiMessage,\n onProgress?: ApiOnProgress,\n) {\n let groupIndex = -1;\n if (!groupedUploads[groupedId]) {\n groupedUploads[groupedId] = {\n counter: 0,\n singleMediaByIndex: {},\n };\n }\n\n groupIndex = groupedUploads[groupedId].counter++;\n\n const prevQueue = queue;\n queue = (async () => {\n let media;\n try {\n media = await uploadMedia(localMessage, attachment, onProgress!);\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n\n groupedUploads[groupedId].counter--;\n\n await prevQueue;\n\n return;\n }\n\n const inputMedia = await fetchInputMedia(\n buildInputPeer(chat.id, chat.accessHash),\n media as GramJs.InputMediaUploadedPhoto | GramJs.InputMediaUploadedDocument,\n );\n\n await prevQueue;\n\n if (!inputMedia) {\n groupedUploads[groupedId].counter--;\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('Failed to upload grouped media');\n }\n\n return;\n }\n\n groupedUploads[groupedId].singleMediaByIndex[groupIndex] = new GramJs.InputSingleMedia({\n media: inputMedia,\n randomId,\n message: text || '',\n entities: entities ? entities.map(buildMtpMessageEntity) : undefined,\n });\n\n if (Object.keys(groupedUploads[groupedId].singleMediaByIndex).length < groupedUploads[groupedId].counter) {\n return;\n }\n\n const { singleMediaByIndex } = groupedUploads[groupedId];\n delete groupedUploads[groupedId];\n\n await invokeRequest(new GramJs.messages.SendMultiMedia({\n clearDraft: true,\n peer: buildInputPeer(chat.id, chat.accessHash),\n multiMedia: Object.values(singleMediaByIndex), // Object keys are usually ordered\n replyToMsgId: replyingTo,\n ...(isSilent && { silent: isSilent }),\n ...(scheduledAt && { scheduleDate: scheduledAt }),\n }), true);\n })();\n\n return queue;\n}\n\nasync function fetchInputMedia(\n peer: GramJs.TypeInputPeer,\n uploadedMedia: GramJs.InputMediaUploadedPhoto | GramJs.InputMediaUploadedDocument,\n) {\n const messageMedia = await invokeRequest(new GramJs.messages.UploadMedia({\n peer,\n media: uploadedMedia,\n }));\n\n if ((\n messageMedia instanceof GramJs.MessageMediaPhoto\n && messageMedia.photo\n && messageMedia.photo instanceof GramJs.Photo)\n ) {\n const { photo: { id, accessHash, fileReference } } = messageMedia;\n\n return new GramJs.InputMediaPhoto({\n id: new GramJs.InputPhoto({ id, accessHash, fileReference }),\n });\n }\n\n if ((\n messageMedia instanceof GramJs.MessageMediaDocument\n && messageMedia.document\n && messageMedia.document instanceof GramJs.Document)\n ) {\n const { document: { id, accessHash, fileReference } } = messageMedia;\n\n return new GramJs.InputMediaDocument({\n id: new GramJs.InputDocument({ id, accessHash, fileReference }),\n });\n }\n\n return undefined;\n}\n\nexport async function editMessage({\n chat,\n message,\n text,\n entities,\n noWebPage,\n serverTimeOffset,\n}: {\n chat: ApiChat;\n message: ApiMessage;\n text: string;\n entities?: ApiMessageEntity[];\n noWebPage?: boolean;\n serverTimeOffset: number;\n}) {\n const isScheduled = message.date * 1000 > Date.now() + serverTimeOffset * 1000;\n const messageUpdate: Partial = {\n content: {\n ...message.content,\n ...(text && {\n text: {\n text,\n entities,\n },\n }),\n },\n };\n\n onUpdate({\n '@type': isScheduled ? 'updateScheduledMessage' : 'updateMessage',\n id: message.id,\n chatId: chat.id,\n message: messageUpdate,\n });\n\n // TODO Revise intersecting with scheduled\n localDb.localMessages[message.id] = { ...message, ...messageUpdate };\n\n const mtpEntities = entities && entities.map(buildMtpMessageEntity);\n\n await invokeRequest(new GramJs.messages.EditMessage({\n message: text || '',\n entities: mtpEntities,\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: message.id,\n ...(isScheduled && { scheduleDate: message.date }),\n ...(noWebPage && { noWebpage: noWebPage }),\n }), true);\n}\n\nexport async function rescheduleMessage({\n chat,\n message,\n scheduledAt,\n}: {\n chat: ApiChat;\n message: ApiMessage;\n scheduledAt: number;\n}) {\n await invokeRequest(new GramJs.messages.EditMessage({\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: message.id,\n scheduleDate: scheduledAt,\n }), true);\n}\n\nasync function uploadMedia(localMessage: ApiMessage, attachment: ApiAttachment, onProgress: ApiOnProgress) {\n const {\n filename, blobUrl, mimeType, quick, voice,\n } = attachment;\n\n const file = await fetchFile(blobUrl, filename);\n const patchedOnProgress: ApiOnProgress = (progress) => {\n if (onProgress.isCanceled) {\n patchedOnProgress.isCanceled = true;\n } else {\n onProgress(progress, localMessage.id);\n }\n };\n const inputFile = await uploadFile(file, patchedOnProgress);\n\n const attributes: GramJs.TypeDocumentAttribute[] = [new GramJs.DocumentAttributeFilename({ fileName: filename })];\n if (quick) {\n if (SUPPORTED_IMAGE_CONTENT_TYPES.has(mimeType)) {\n return new GramJs.InputMediaUploadedPhoto({ file: inputFile });\n }\n\n if (SUPPORTED_VIDEO_CONTENT_TYPES.has(mimeType)) {\n const { width, height, duration } = quick;\n if (duration !== undefined) {\n attributes.push(new GramJs.DocumentAttributeVideo({\n duration,\n w: width,\n h: height,\n supportsStreaming: true,\n }));\n }\n }\n }\n\n if (voice) {\n const { duration, waveform } = voice;\n const { data: inputWaveform } = interpolateArray(waveform, INPUT_WAVEFORM_LENGTH);\n attributes.push(new GramJs.DocumentAttributeAudio({\n voice: true,\n duration,\n waveform: Buffer.from(inputWaveform),\n }));\n }\n\n return new GramJs.InputMediaUploadedDocument({\n file: inputFile,\n mimeType,\n attributes,\n });\n}\n\nexport async function pinMessage({\n chat, messageId, isUnpin, isOneSide, isSilent,\n}: { chat: ApiChat; messageId: number; isUnpin: boolean; isOneSide: boolean; isSilent: boolean }) {\n await invokeRequest(new GramJs.messages.UpdatePinnedMessage({\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: messageId,\n ...(isUnpin && { unpin: true }),\n ...(isOneSide && { pmOneside: true }),\n ...(isSilent && { silent: true }),\n }), true);\n}\n\nexport async function unpinAllMessages({ chat }: { chat: ApiChat }) {\n await invokeRequest(new GramJs.messages.UnpinAllMessages({\n peer: buildInputPeer(chat.id, chat.accessHash),\n }), true);\n}\n\nexport async function deleteMessages({\n chat, messageIds, shouldDeleteForAll,\n}: {\n chat: ApiChat; messageIds: number[]; shouldDeleteForAll?: boolean;\n}) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n\n const result = await invokeRequest(\n isChannel\n ? new GramJs.channels.DeleteMessages({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n id: messageIds,\n })\n : new GramJs.messages.DeleteMessages({\n id: messageIds,\n ...(shouldDeleteForAll && { revoke: true }),\n }),\n );\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'deleteMessages',\n ids: messageIds,\n ...(isChannel && { chatId: chat.id }),\n });\n}\n\nexport async function deleteScheduledMessages({\n chat, messageIds,\n}: {\n chat: ApiChat; messageIds: number[];\n}) {\n const result = await invokeRequest(\n new GramJs.messages.DeleteScheduledMessages({\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: messageIds,\n }),\n );\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'deleteScheduledMessages',\n ids: messageIds,\n chatId: chat.id,\n });\n}\n\nexport async function deleteHistory({\n chat, shouldDeleteForAll, maxId,\n}: {\n chat: ApiChat; shouldDeleteForAll?: boolean; maxId?: number;\n}) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n const result = await invokeRequest(\n isChannel\n ? new GramJs.channels.DeleteHistory({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n maxId,\n })\n : new GramJs.messages.DeleteHistory({\n peer: buildInputPeer(chat.id, chat.accessHash),\n ...(shouldDeleteForAll && { revoke: true }),\n ...(!shouldDeleteForAll && { just_clear: true }),\n maxId,\n }),\n );\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'deleteHistory',\n chatId: chat.id,\n });\n}\n\nexport async function reportMessages({\n peer, messageIds, reason, description,\n}: {\n peer: ApiChat | ApiUser; messageIds: number[]; reason: ApiReportReason; description?: string;\n}) {\n const result = await invokeRequest(new GramJs.messages.Report({\n peer: buildInputPeer(peer.id, peer.accessHash),\n id: messageIds,\n reason: buildInputReportReason(reason),\n message: description,\n }));\n\n return result;\n}\n\nexport async function markMessageListRead({\n chat, threadId, maxId, serverTimeOffset,\n}: {\n chat: ApiChat; threadId: number; maxId?: number; serverTimeOffset: number;\n}) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n\n if (isChannel && threadId === MAIN_THREAD_ID) {\n await invokeRequest(new GramJs.channels.ReadHistory({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n maxId,\n }));\n } else if (isChannel) {\n await invokeRequest(new GramJs.messages.ReadDiscussion({\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: threadId,\n readMaxId: maxId,\n }));\n } else {\n await invokeRequest(new GramJs.messages.ReadHistory({\n peer: buildInputPeer(chat.id, chat.accessHash),\n maxId,\n }));\n }\n\n if (threadId === MAIN_THREAD_ID) {\n void requestChatUpdate({ chat, serverTimeOffset, noLastMessage: true });\n } else {\n void requestThreadInfoUpdate({ chat, threadId });\n }\n}\n\nexport async function markMessagesRead({\n chat, messageIds,\n}: {\n chat: ApiChat; messageIds: number[];\n}) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n\n await invokeRequest(\n isChannel\n ? new GramJs.channels.ReadMessageContents({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n id: messageIds,\n })\n : new GramJs.messages.ReadMessageContents({\n id: messageIds,\n }),\n );\n\n onUpdate({\n ...(isChannel ? {\n '@type': 'updateChannelMessages',\n channelId: chat.id,\n } : {\n '@type': 'updateCommonBoxMessages',\n }),\n ids: messageIds,\n messageUpdate: {\n hasUnreadMention: false,\n isMediaUnread: false,\n },\n });\n}\n\nexport async function requestThreadInfoUpdate({\n chat, threadId,\n}: {\n chat: ApiChat; threadId: number;\n}) {\n const [topMessageResult, repliesResult] = await Promise.all([\n invokeRequest(new GramJs.messages.GetDiscussionMessage({\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: threadId,\n })),\n invokeRequest(new GramJs.messages.GetReplies({\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: threadId,\n offsetId: 1,\n addOffset: -1,\n limit: 1,\n })),\n ]);\n\n if (!topMessageResult || !topMessageResult.messages.length) {\n return undefined;\n }\n\n const discussionChatId = resolveMessageApiChatId(topMessageResult.messages[0]);\n if (!discussionChatId) {\n return undefined;\n }\n\n onUpdate({\n '@type': 'updateThreadInfo',\n chatId: discussionChatId,\n threadId,\n threadInfo: {\n threadId,\n topMessageId: topMessageResult.messages[topMessageResult.messages.length - 1].id,\n lastReadInboxMessageId: topMessageResult.readInboxMaxId,\n messagesCount: (repliesResult instanceof GramJs.messages.ChannelMessages) ? repliesResult.count : undefined,\n },\n firstMessageId: repliesResult && 'messages' in repliesResult && repliesResult.messages.length\n ? repliesResult.messages[0].id\n : undefined,\n });\n\n const chats = topMessageResult.chats.map((c) => buildApiChatFromPreview(c)).filter(Boolean as any);\n chats.forEach((newChat) => {\n onUpdate({\n '@type': 'updateChat',\n id: newChat.id,\n chat: newChat,\n noTopChatsRequest: true,\n });\n });\n\n return {\n discussionChatId,\n };\n}\n\nexport async function searchMessagesLocal({\n chatOrUser, type, query, topMessageId, minDate, maxDate, ...pagination\n}: {\n chatOrUser: ApiChat | ApiUser;\n type?: ApiMessageSearchType | ApiGlobalMessageSearchType;\n query?: string;\n topMessageId?: number;\n offsetId?: number;\n addOffset?: number;\n limit: number;\n minDate?: number;\n maxDate?: number;\n}) {\n let filter;\n switch (type) {\n case 'media':\n filter = new GramJs.InputMessagesFilterPhotoVideo();\n break;\n case 'documents':\n filter = new GramJs.InputMessagesFilterDocument();\n break;\n case 'links':\n filter = new GramJs.InputMessagesFilterUrl();\n break;\n case 'audio':\n filter = new GramJs.InputMessagesFilterMusic();\n break;\n case 'voice':\n filter = new GramJs.InputMessagesFilterRoundVoice();\n break;\n case 'profilePhoto':\n filter = new GramJs.InputMessagesFilterChatPhotos();\n break;\n case 'text':\n default: {\n filter = new GramJs.InputMessagesFilterEmpty();\n }\n }\n\n const result = await invokeRequest(new GramJs.messages.Search({\n peer: buildInputPeer(chatOrUser.id, chatOrUser.accessHash),\n filter,\n q: query || '',\n topMsgId: topMessageId,\n minDate,\n maxDate,\n ...pagination,\n }));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n\n let totalCount = messages.length;\n let nextOffsetId: number | undefined;\n if (result instanceof GramJs.messages.MessagesSlice || result instanceof GramJs.messages.ChannelMessages) {\n totalCount = result.count;\n\n if (messages.length) {\n nextOffsetId = messages[messages.length - 1].id;\n }\n }\n\n return {\n messages,\n users,\n totalCount,\n nextOffsetId,\n };\n}\n\nexport async function searchMessagesGlobal({\n query, offsetRate = 0, limit, type = 'text', minDate, maxDate,\n}: {\n query: string;\n offsetRate?: number;\n limit: number;\n type?: ApiGlobalMessageSearchType;\n minDate?: number;\n maxDate?: number;\n}) {\n let filter;\n switch (type) {\n case 'media':\n filter = new GramJs.InputMessagesFilterPhotoVideo();\n break;\n case 'documents':\n filter = new GramJs.InputMessagesFilterDocument();\n break;\n case 'links':\n filter = new GramJs.InputMessagesFilterUrl();\n break;\n case 'audio':\n filter = new GramJs.InputMessagesFilterMusic();\n break;\n case 'voice':\n filter = new GramJs.InputMessagesFilterRoundVoice();\n break;\n case 'text':\n default: {\n if (!query && !(maxDate && minDate)) {\n return undefined;\n }\n\n filter = new GramJs.InputMessagesFilterEmpty();\n }\n }\n\n const result = await invokeRequest(new GramJs.messages.SearchGlobal({\n q: query,\n offsetRate,\n offsetPeer: new GramJs.InputPeerEmpty(),\n limit,\n filter,\n folderId: ALL_FOLDER_ID,\n minDate,\n maxDate,\n }));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb({\n chats: result.chats,\n users: result.users,\n messages: result.messages,\n } as GramJs.messages.Messages);\n\n const chats = result.chats.map((user) => buildApiChatFromPreview(user)).filter(Boolean as any);\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n\n let totalCount = messages.length;\n let nextRate: number | undefined;\n if (result instanceof GramJs.messages.MessagesSlice || result instanceof GramJs.messages.ChannelMessages) {\n totalCount = result.count;\n\n if (messages.length) {\n nextRate = messages[messages.length - 1].id;\n }\n }\n\n return {\n messages,\n users,\n chats,\n totalCount,\n nextRate: 'nextRate' in result && result.nextRate ? result.nextRate : nextRate,\n };\n}\n\nexport async function fetchWebPagePreview({ message }: { message: string }) {\n const preview = await invokeRequest(new GramJs.messages.GetWebPagePreview({\n message,\n }));\n\n return preview && buildWebPage(preview);\n}\n\nexport async function sendPollVote({\n chat, messageId, options,\n}: {\n chat: ApiChat;\n messageId: number;\n options: string[];\n}) {\n const { id, accessHash } = chat;\n\n await invokeRequest(new GramJs.messages.SendVote({\n peer: buildInputPeer(id, accessHash),\n msgId: messageId,\n options: options.map((option) => Buffer.from(option)),\n }), true);\n}\n\nexport async function loadPollOptionResults({\n chat, messageId, option, offset, limit, shouldResetVoters,\n}: {\n chat: ApiChat;\n messageId: number;\n option?: string;\n offset?: string;\n limit?: number;\n shouldResetVoters?: boolean;\n}) {\n const { id, accessHash } = chat;\n\n const result = await invokeRequest(new GramJs.messages.GetPollVotes({\n peer: buildInputPeer(id, accessHash),\n id: messageId,\n ...(option && { option: Buffer.from(option) }),\n ...(offset && { offset }),\n ...(limit && { limit }),\n }));\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb({\n chats: [] as GramJs.TypeChat[],\n users: result.users,\n messages: [] as GramJs.Message[],\n } as GramJs.messages.Messages);\n\n const users = result.users.map(buildApiUser).filter(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}: {\n fromChat: ApiChat;\n toChat: ApiChat;\n messages: ApiMessage[];\n serverTimeOffset: number;\n isSilent?: boolean;\n scheduledAt?: number;\n}) {\n const messageIds = messages.map(({ id }) => id);\n const randomIds = messages.map(generateRandomBigInt);\n\n messages.forEach((message, index) => {\n const localMessage = buildLocalForwardedMessage(toChat, message, serverTimeOffset, scheduledAt);\n localDb.localMessages[String(randomIds[index])] = localMessage;\n\n onUpdate({\n '@type': localMessage.isScheduled ? 'newScheduledMessage' : 'newMessage',\n id: localMessage.id,\n chatId: toChat.id,\n message: localMessage,\n });\n });\n\n await invokeRequest(new GramJs.messages.ForwardMessages({\n fromPeer: buildInputPeer(fromChat.id, fromChat.accessHash),\n toPeer: buildInputPeer(toChat.id, toChat.accessHash),\n randomId: randomIds,\n id: messageIds,\n ...(isSilent && { sil2ent: isSilent }),\n ...(scheduledAt && { scheduleDate: scheduledAt }),\n }), true);\n}\n\nexport async function findFirstMessageIdAfterDate({\n chat,\n timestamp,\n}: {\n chat: ApiChat;\n timestamp: number;\n}) {\n const result = await invokeRequest(new GramJs.messages.GetHistory({\n peer: buildInputPeer(chat.id, chat.accessHash),\n offsetDate: timestamp,\n addOffset: -1,\n limit: 1,\n }));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages || !result.messages.length\n ) {\n return undefined;\n }\n\n return result.messages[0].id;\n}\n\nexport async function fetchScheduledHistory({ chat }: { chat: ApiChat }) {\n const { id, accessHash } = chat;\n\n const result = await invokeRequest(new GramJs.messages.GetScheduledHistory({\n peer: buildInputPeer(id, accessHash),\n }));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n\n return {\n messages,\n };\n}\n\nexport async function sendScheduledMessages({ chat, ids }: { chat: ApiChat; ids: number[] }) {\n const { id, accessHash } = chat;\n\n await invokeRequest(new GramJs.messages.SendScheduledMessages({\n peer: buildInputPeer(id, accessHash),\n id: ids,\n }), true);\n}\n\nfunction updateLocalDb(result: (\n GramJs.messages.MessagesSlice | GramJs.messages.Messages | GramJs.messages.ChannelMessages |\n GramJs.messages.DiscussionMessage\n)) {\n result.users.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[buildApiPeerId(user.id, 'user')] = user;\n }\n });\n\n result.chats.forEach((chat) => {\n if (chat instanceof GramJs.Chat || chat instanceof GramJs.Channel) {\n localDb.chats[buildApiPeerId(chat.id, chat instanceof GramJs.Chat ? 'chat' : 'channel')] = chat;\n }\n });\n\n result.messages.forEach((message) => {\n if ((message instanceof GramJs.Message && isMessageWithMedia(message))\n || (message instanceof GramJs.MessageService && isServiceMessageWithMedia(message))\n ) {\n addMessageToLocalDb(message);\n }\n });\n}\n\nexport async function fetchPinnedMessages({ chat }: { chat: ApiChat }) {\n const result = await invokeRequest(new GramJs.messages.Search(\n {\n peer: buildInputPeer(chat.id, chat.accessHash),\n filter: new GramJs.InputMessagesFilterPinned(),\n q: '',\n limit: PINNED_MESSAGES_LIMIT,\n },\n ));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter(Boolean as any);\n\n return {\n messages,\n users,\n chats,\n };\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport {\n OnApiUpdate, ApiUser, ApiChat, ApiPhoto,\n} from '../../types';\n\nimport { COMMON_CHATS_LIMIT, PROFILE_PHOTOS_LIMIT } from '../../../config';\nimport { invokeRequest } from './client';\nimport { searchMessagesLocal } from './messages';\nimport {\n buildInputEntity,\n buildInputPeer,\n buildInputContact,\n buildMtpPeerId,\n getEntityTypeById,\n} from '../gramjsBuilders';\nimport { buildApiUser, buildApiUserFromFull } from '../apiBuilders/users';\nimport { buildApiChatFromPreview } from '../apiBuilders/chats';\nimport { buildApiPhoto } from '../apiBuilders/common';\nimport localDb from '../localDb';\nimport { addChatToLocalDb, addPhotoToLocalDb } from '../helpers';\nimport { buildApiPeerId } from '../apiBuilders/peers';\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function fetchFullUser({\n id,\n accessHash,\n}: {\n id: string;\n accessHash?: string;\n}) {\n const input = buildInputEntity(id, accessHash);\n if (!(input instanceof GramJs.InputUser)) {\n return;\n }\n\n const fullInfo = await invokeRequest(new GramJs.users.GetFullUser({ id: input }));\n\n if (!fullInfo) {\n return;\n }\n\n const userWithFullInfo = buildApiUserFromFull(fullInfo);\n\n onUpdate({\n '@type': 'updateUser',\n id,\n user: {\n fullInfo: userWithFullInfo.fullInfo,\n },\n });\n}\n\nexport async function fetchCommonChats(id: string, accessHash?: string, maxId?: string) {\n const commonChats = await invokeRequest(new GramJs.messages.GetCommonChats({\n userId: buildInputEntity(id, accessHash) as GramJs.InputUser,\n maxId: maxId ? buildMtpPeerId(maxId, getEntityTypeById(maxId)) : undefined,\n limit: COMMON_CHATS_LIMIT,\n }));\n\n if (!commonChats) {\n return undefined;\n }\n\n updateLocalDb(commonChats);\n\n const chatIds: string[] = [];\n const chats: ApiChat[] = [];\n\n commonChats.chats.forEach((mtpChat) => {\n const chat = buildApiChatFromPreview(mtpChat);\n\n if (chat) {\n chats.push(chat);\n chatIds.push(chat.id);\n }\n });\n\n return { chats, chatIds, isFullyLoaded: chatIds.length < COMMON_CHATS_LIMIT };\n}\n\nexport async function fetchNearestCountry() {\n const dcInfo = await invokeRequest(new GramJs.help.GetNearestDc());\n\n return dcInfo?.country;\n}\n\nexport async function fetchTopUsers() {\n const topPeers = await invokeRequest(new GramJs.contacts.GetTopPeers({\n correspondents: true,\n }));\n if (!(topPeers instanceof GramJs.contacts.TopPeers)) {\n return undefined;\n }\n\n const users = topPeers.users.map(buildApiUser).filter((user) => !!user && !user.isSelf) as ApiUser[];\n const ids = users.map(({ id }) => id);\n\n return {\n ids,\n users,\n };\n}\n\nexport async function fetchContactList() {\n const result = await invokeRequest(new GramJs.contacts.GetContacts({ hash: BigInt('0') }));\n if (!result || result instanceof GramJs.contacts.ContactsNotModified) {\n return undefined;\n }\n\n result.users.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[buildApiPeerId(user.id, 'user')] = user;\n }\n });\n\n return {\n users: result.users.map(buildApiUser).filter(Boolean as any),\n chats: result.users.map((user) => buildApiChatFromPreview(user)).filter(Boolean as any),\n };\n}\n\nexport async function fetchUsers({ users }: { users: ApiUser[] }) {\n const result = await invokeRequest(new GramJs.users.GetUsers({\n id: users.map(({ id, accessHash }) => buildInputPeer(id, accessHash)),\n }));\n if (!result || !result.length) {\n return undefined;\n }\n\n result.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[buildApiPeerId(user.id, 'user')] = user;\n }\n });\n\n return result.map(buildApiUser).filter(Boolean as any);\n}\n\nexport function updateContact({\n phone,\n firstName,\n lastName,\n}: {\n phone?: string;\n firstName?: string;\n lastName?: string;\n}) {\n return invokeRequest(new GramJs.contacts.ImportContacts({\n contacts: [buildInputContact({\n phone: phone || '',\n firstName: firstName || '',\n lastName: lastName || '',\n })],\n }));\n}\n\nexport function addContact({\n id,\n accessHash,\n phoneNumber = '',\n firstName = '',\n lastName = '',\n}: {\n id: string;\n accessHash?: string;\n phoneNumber?: string;\n firstName?: string;\n lastName?: string;\n}) {\n return invokeRequest(new GramJs.contacts.AddContact({\n id: buildInputEntity(id, accessHash) as GramJs.InputUser,\n firstName,\n lastName,\n phone: phoneNumber,\n }), true);\n}\n\nexport async function deleteUser({\n id,\n accessHash,\n}: {\n id: string;\n accessHash?: string;\n}) {\n const input = buildInputEntity(id, accessHash);\n if (!(input instanceof GramJs.InputUser)) {\n return;\n }\n\n const result = await invokeRequest(new GramJs.contacts.DeleteContacts({ id: [input] }));\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'deleteUser',\n id,\n });\n}\n\nexport async function fetchProfilePhotos(user?: ApiUser, chat?: ApiChat) {\n if (user) {\n const { id, accessHash } = user;\n\n const result = await invokeRequest(new GramJs.photos.GetUserPhotos({\n userId: buildInputEntity(id, accessHash) as GramJs.InputUser,\n limit: PROFILE_PHOTOS_LIMIT,\n offset: 0,\n maxId: BigInt('0'),\n }));\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return {\n photos: result.photos\n .filter((photo): photo is GramJs.Photo => photo instanceof GramJs.Photo)\n .map(buildApiPhoto),\n };\n }\n\n const result = await searchMessagesLocal({\n chatOrUser: chat!,\n type: 'profilePhoto',\n limit: PROFILE_PHOTOS_LIMIT,\n });\n\n if (!result) {\n return undefined;\n }\n\n const { messages, users } = result;\n\n return {\n photos: messages.map((message) => message.content.action!.photo).filter(Boolean as any),\n users,\n };\n}\n\nfunction updateLocalDb(result: (GramJs.photos.Photos | GramJs.photos.PhotosSlice | GramJs.messages.Chats)) {\n if ('chats' in result) {\n result.chats.forEach(addChatToLocalDb);\n }\n\n if ('photos' in result) {\n result.photos.forEach(addPhotoToLocalDb);\n }\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport { ApiSticker, ApiVideo, OnApiUpdate } from '../../types';\n\nimport { invokeRequest } from './client';\nimport { buildStickerFromDocument, buildStickerSet, buildStickerSetCovered } from '../apiBuilders/symbols';\nimport { buildInputStickerSet, buildInputDocument, buildInputStickerSetShortName } from '../gramjsBuilders';\nimport { buildVideoFromDocument } from '../apiBuilders/messages';\nimport { RECENT_STICKERS_LIMIT } from '../../../config';\n\nimport localDb from '../localDb';\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function fetchStickerSets({ hash = '0' }: { hash?: string }) {\n const allStickers = await invokeRequest(new GramJs.messages.GetAllStickers({ hash: BigInt(hash) }));\n\n if (!allStickers || allStickers instanceof GramJs.messages.AllStickersNotModified) {\n return undefined;\n }\n\n allStickers.sets.forEach((stickerSet) => {\n if (stickerSet.thumbs?.length) {\n localDb.stickerSets[String(stickerSet.id)] = stickerSet;\n }\n });\n\n return {\n hash: String(allStickers.hash),\n sets: allStickers.sets.map(buildStickerSet),\n };\n}\n\nexport async function fetchRecentStickers({ hash = '0' }: { hash?: string }) {\n const result = await invokeRequest(new GramJs.messages.GetRecentStickers({ hash: BigInt(hash) }));\n\n if (!result || result instanceof GramJs.messages.RecentStickersNotModified) {\n return undefined;\n }\n\n return {\n hash: String(result.hash),\n stickers: processStickerResult(result.stickers.slice(0, RECENT_STICKERS_LIMIT)),\n };\n}\n\nexport async function fetchFavoriteStickers({ hash = '0' }: { hash?: string }) {\n const result = await invokeRequest(new GramJs.messages.GetFavedStickers({ hash: BigInt(hash) }));\n\n if (!result || result instanceof GramJs.messages.FavedStickersNotModified) {\n return undefined;\n }\n\n return {\n hash: String(result.hash),\n stickers: processStickerResult(result.stickers),\n };\n}\n\nexport async function fetchFeaturedStickers({ hash = '0' }: { hash?: string }) {\n const result = await invokeRequest(new GramJs.messages.GetFeaturedStickers({ hash: BigInt(hash) }));\n\n if (!result || result instanceof GramJs.messages.FeaturedStickersNotModified) {\n return undefined;\n }\n\n return {\n hash: String(result.hash),\n sets: result.sets.map(buildStickerSetCovered),\n };\n}\n\nexport async function faveSticker({\n sticker,\n unfave,\n}: {\n sticker: ApiSticker;\n unfave?: boolean;\n}) {\n const request = new GramJs.messages.FaveSticker({\n id: buildInputDocument(sticker),\n unfave,\n });\n\n const result = await invokeRequest(request);\n if (result) {\n onUpdate({\n '@type': 'updateFavoriteStickers',\n });\n }\n}\n\nexport async function fetchStickers(\n { stickerSetShortName, stickerSetId, accessHash }:\n { stickerSetShortName?: string; stickerSetId?: string; accessHash: string },\n) {\n const result = await invokeRequest(new GramJs.messages.GetStickerSet({\n stickerset: stickerSetId\n ? buildInputStickerSet(stickerSetId, accessHash)\n : buildInputStickerSetShortName(stickerSetShortName!),\n }));\n\n if (!result) {\n return undefined;\n }\n\n return {\n set: buildStickerSet(result.set),\n stickers: processStickerResult(result.documents),\n packs: processStickerPackResult(result.packs),\n };\n}\n\nexport async function fetchAnimatedEmojis() {\n const result = await invokeRequest(new GramJs.messages.GetStickerSet({\n stickerset: new GramJs.InputStickerSetAnimatedEmoji(),\n }));\n\n if (!result) {\n return undefined;\n }\n\n return {\n set: buildStickerSet(result.set),\n stickers: processStickerResult(result.documents),\n };\n}\n\nexport async function searchStickers({ query, hash = '0' }: { query: string; hash?: string }) {\n const result = await invokeRequest(new GramJs.messages.SearchStickerSets({\n q: query,\n hash: BigInt(hash),\n }));\n\n if (!result || result instanceof GramJs.messages.FoundStickerSetsNotModified) {\n return undefined;\n }\n\n return {\n hash: String(result.hash),\n sets: result.sets.map(buildStickerSetCovered),\n };\n}\n\nexport async function fetchSavedGifs({ hash = '0' }: { hash?: string }) {\n const result = await invokeRequest(new GramJs.messages.GetSavedGifs({ hash: BigInt(hash) }));\n\n if (!result || result instanceof GramJs.messages.SavedGifsNotModified) {\n return undefined;\n }\n\n return {\n hash: String(result.hash),\n gifs: processGifResult(result.gifs),\n };\n}\n\nexport async function installStickerSet({ stickerSetId, accessHash }: { stickerSetId: string; accessHash: string }) {\n const result = await invokeRequest(new GramJs.messages.InstallStickerSet({\n stickerset: buildInputStickerSet(stickerSetId, accessHash),\n }));\n\n if (result) {\n onUpdate({\n '@type': 'updateStickerSet',\n id: stickerSetId,\n stickerSet: { installedDate: Date.now() },\n });\n }\n}\n\nexport async function uninstallStickerSet({ stickerSetId, accessHash }: { stickerSetId: string; accessHash: string }) {\n const result = await invokeRequest(new GramJs.messages.UninstallStickerSet({\n stickerset: buildInputStickerSet(stickerSetId, accessHash),\n }));\n\n if (result) {\n onUpdate({\n '@type': 'updateStickerSet',\n id: stickerSetId,\n stickerSet: { installedDate: undefined },\n });\n }\n}\n\nlet inputGifBot: GramJs.InputUser | undefined;\n\nexport async function searchGifs({ query, offset = '' }: { query: string; offset?: string }) {\n if (!inputGifBot) {\n const config = await invokeRequest(new GramJs.help.GetConfig());\n if (!config) {\n return undefined;\n }\n\n const resolvedPeer = await invokeRequest(new GramJs.contacts.ResolveUsername({\n username: config.gifSearchUsername,\n }));\n if (!resolvedPeer || !(resolvedPeer.users[0] instanceof GramJs.User)) {\n return undefined;\n }\n\n inputGifBot = new GramJs.InputUser({\n userId: (resolvedPeer.peer as GramJs.PeerUser).userId,\n accessHash: resolvedPeer.users[0].accessHash!,\n });\n }\n\n const result = await invokeRequest(new GramJs.messages.GetInlineBotResults({\n bot: inputGifBot,\n peer: new GramJs.InputPeerEmpty(),\n query,\n offset,\n }));\n if (!result) {\n return undefined;\n }\n\n const documents = result.results\n .map((foundGif) => {\n if (foundGif instanceof GramJs.BotInlineMediaResult) {\n return foundGif.document;\n }\n\n return undefined;\n })\n .filter(Boolean as any);\n\n return {\n nextOffset: result.nextOffset,\n gifs: processGifResult(documents),\n };\n}\n\nexport async function fetchStickersForEmoji({\n emoji, hash = '0',\n}: { emoji: string; hash?: string }) {\n const result = await invokeRequest(new GramJs.messages.GetStickers({\n emoticon: emoji,\n hash: BigInt(hash),\n }));\n\n if (!result || result instanceof GramJs.messages.StickersNotModified) {\n return undefined;\n }\n\n return {\n stickers: processStickerResult(result.stickers),\n hash: String(result.hash),\n };\n}\n\nexport async function fetchEmojiKeywords({ language, fromVersion }: {\n language: string;\n fromVersion?: number;\n}) {\n const result = await invokeRequest(new GramJs.messages.GetEmojiKeywordsDifference({\n langCode: language,\n fromVersion,\n }));\n\n if (!result) {\n return undefined;\n }\n\n return {\n language: result.langCode,\n version: result.version,\n keywords: result.keywords.reduce((acc, emojiKeyword) => {\n acc[emojiKeyword.keyword] = emojiKeyword.emoticons;\n\n return acc;\n }, {} as Record),\n };\n}\n\nfunction processStickerResult(stickers: GramJs.TypeDocument[]) {\n return stickers\n .map((document) => {\n if (document instanceof GramJs.Document) {\n const sticker = buildStickerFromDocument(document);\n if (sticker) {\n localDb.documents[String(document.id)] = document;\n\n return sticker;\n }\n }\n\n return undefined;\n })\n .filter(Boolean as any);\n}\n\nfunction processStickerPackResult(packs: GramJs.StickerPack[]) {\n return packs.reduce((acc, { emoticon, documents }) => {\n acc[emoticon] = documents.map((documentId) => buildStickerFromDocument(\n localDb.documents[String(documentId)],\n )).filter(Boolean as any);\n return acc;\n }, {} as Record);\n}\n\nfunction processGifResult(gifs: GramJs.TypeDocument[]) {\n return gifs\n .map((document) => {\n if (document instanceof GramJs.Document) {\n const gif = buildVideoFromDocument(document);\n if (gif) {\n localDb.documents[String(document.id)] = document;\n\n return gif;\n }\n }\n\n return undefined;\n })\n .filter(Boolean as any);\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\n\nimport { invokeRequest } from './client';\nimport { buildInputEntity, buildInputPeer } from '../gramjsBuilders';\nimport { ApiChat, OnApiUpdate } from '../../types';\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function checkChatUsername(\n { username }: { username: string },\n) {\n try {\n const result = await invokeRequest(new GramJs.channels.CheckUsername({\n channel: new GramJs.InputChannelEmpty(),\n username,\n }), undefined, true);\n\n return result!;\n } catch (err) {\n return false;\n }\n}\n\nexport async function setChatUsername(\n { chat, username }: { chat: ApiChat; username: string },\n) {\n const result = await invokeRequest(new GramJs.channels.UpdateUsername({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n username,\n }));\n\n if (result) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat: { username },\n });\n }\n}\n\nexport async function updatePrivateLink(\n { chat }: { chat: ApiChat },\n) {\n const result = await invokeRequest(new GramJs.messages.ExportChatInvite({\n peer: buildInputPeer(chat.id, chat.accessHash),\n }));\n\n if (!result || !(result instanceof GramJs.ChatInviteExported)) {\n return;\n }\n\n onUpdate({\n '@type': 'updateChatFullInfo',\n id: chat.id,\n fullInfo: {\n inviteLink: result.link,\n },\n });\n}\n","import { Api as GramJs, errors } from '../../../lib/gramjs';\n\nimport { OnApiUpdate } from '../../types';\n\nimport { DEBUG } from '../../../config';\nimport { invokeRequest, updateTwoFaSettings } from './client';\n\nconst ApiErrors: { [k: string]: string } = {\n EMAIL_UNCONFIRMED: 'Email unconfirmed',\n EMAIL_HASH_EXPIRED: 'Email hash expired',\n NEW_SALT_INVALID: 'The new salt is invalid',\n NEW_SETTINGS_INVALID: 'The new password settings are invalid',\n CODE_INVALID: 'Invalid Code',\n PASSWORD_HASH_INVALID: 'Invalid Password',\n};\n\nconst emailCodeController: {\n resolve?: Function;\n reject?: Function;\n} = {};\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function getPasswordInfo() {\n const result = await invokeRequest(new GramJs.account.GetPassword());\n if (!result) {\n return undefined;\n }\n\n const { hint, hasPassword } = result;\n\n return { hint, hasPassword };\n}\n\nfunction onRequestEmailCode(length: number) {\n onUpdate({\n '@type': 'updateTwoFaStateWaitCode',\n length,\n });\n\n return new Promise((resolve, reject) => {\n emailCodeController.resolve = resolve;\n emailCodeController.reject = reject;\n });\n}\n\nexport async function checkPassword(currentPassword: string) {\n try {\n await updateTwoFaSettings({ isCheckPassword: true, currentPassword });\n\n return true;\n } catch (err) {\n onError(err);\n\n return false;\n }\n}\n\nexport async function clearPassword(currentPassword: string) {\n try {\n await updateTwoFaSettings({ currentPassword });\n\n return true;\n } catch (err) {\n onError(err);\n\n return false;\n }\n}\n\nexport async function updatePassword(currentPassword: string, password: string, hint?: string, email?: string) {\n try {\n await updateTwoFaSettings({\n currentPassword,\n newPassword: password,\n hint,\n email,\n emailCodeCallback: onRequestEmailCode,\n onEmailCodeError: onError,\n });\n\n return true;\n } catch (err) {\n onError(err);\n\n return false;\n }\n}\n\nexport async function updateRecoveryEmail(currentPassword: string, email: string) {\n try {\n await updateTwoFaSettings({\n currentPassword,\n newPassword: currentPassword,\n email,\n emailCodeCallback: onRequestEmailCode,\n onEmailCodeError: onError,\n });\n\n return true;\n } catch (err) {\n onError(err);\n\n return false;\n }\n}\n\nexport function provideRecoveryEmailCode(code: string) {\n emailCodeController.resolve!(code);\n}\n\nfunction onError(err: Error) {\n let message: string;\n\n if (err instanceof errors.FloodWaitError) {\n const hours = Math.ceil(Number(err.seconds) / 60 / 60);\n message = `Too many attempts. Try again in ${hours > 1 ? `${hours} hours` : 'an hour'}`;\n } else {\n message = ApiErrors[err.message];\n }\n\n if (!message) {\n message = 'Unexpected Error';\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n }\n\n onUpdate({\n '@type': 'updateTwoFaError',\n message,\n });\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\n\nimport {\n ApiChat, ApiLangString, ApiLanguage, ApiNotifyException, ApiUser, ApiWallpaper,\n} from '../../types';\nimport { ApiPrivacyKey, InputPrivacyRules, LangCode } from '../../../types';\n\nimport { BLOCKED_LIST_LIMIT, DEFAULT_LANG_PACK, LANG_PACKS } from '../../../config';\nimport {\n buildApiWallpaper, buildApiSession, buildPrivacyRules, buildApiNotifyException, buildApiCountryList,\n} from '../apiBuilders/misc';\n\nimport { buildApiUser } from '../apiBuilders/users';\nimport { buildApiChatFromPreview } from '../apiBuilders/chats';\nimport { buildInputPrivacyKey, buildInputPeer, buildInputEntity } from '../gramjsBuilders';\nimport { invokeRequest, uploadFile, getClient } from './client';\nimport { omitVirtualClassFields } from '../apiBuilders/helpers';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport { getServerTime } from '../../../util/serverTime';\nimport { buildApiPeerId, getApiChatIdFromMtpPeer } from '../apiBuilders/peers';\nimport localDb from '../localDb';\n\nconst MAX_INT_32 = 2 ** 31 - 1;\nconst BETA_LANG_CODES = ['ar', 'fa', 'id', 'ko', 'uz'];\n\nexport function updateProfile({\n firstName,\n lastName,\n about,\n}: {\n firstName?: string;\n lastName?: string;\n about?: string;\n}) {\n return invokeRequest(new GramJs.account.UpdateProfile({\n firstName: firstName || '',\n lastName: lastName || '',\n about: about || '',\n }));\n}\n\nexport function checkUsername(username: string) {\n return invokeRequest(new GramJs.account.CheckUsername({ username }));\n}\n\nexport function updateUsername(username: string) {\n return invokeRequest(new GramJs.account.UpdateUsername({ username }));\n}\n\nexport async function updateProfilePhoto(file: File) {\n const inputFile = await uploadFile(file);\n return invokeRequest(new GramJs.photos.UploadProfilePhoto({\n file: inputFile,\n }));\n}\n\nexport async function uploadProfilePhoto(file: File) {\n const inputFile = await uploadFile(file);\n await invokeRequest(new GramJs.photos.UploadProfilePhoto({\n file: inputFile,\n }));\n}\n\nexport async function fetchWallpapers() {\n const result = await invokeRequest(new GramJs.account.GetWallPapers({ hash: BigInt('0') }));\n\n if (!result || result instanceof GramJs.account.WallPapersNotModified) {\n return undefined;\n }\n\n const filteredWallpapers = result.wallpapers.filter((wallpaper) => {\n if (\n !(wallpaper instanceof GramJs.WallPaper)\n || !(wallpaper.document instanceof GramJs.Document)\n ) {\n return false;\n }\n\n return !wallpaper.pattern && wallpaper.document.mimeType !== 'application/x-tgwallpattern';\n }) as GramJs.WallPaper[];\n\n filteredWallpapers.forEach((wallpaper) => {\n localDb.documents[String(wallpaper.document.id)] = wallpaper.document as GramJs.Document;\n });\n\n return {\n wallpapers: filteredWallpapers.map(buildApiWallpaper).filter(Boolean as any),\n };\n}\n\nexport async function uploadWallpaper(file: File) {\n const inputFile = await uploadFile(file);\n\n const result = await invokeRequest(new GramJs.account.UploadWallPaper({\n file: inputFile,\n mimeType: file.type,\n settings: new GramJs.WallPaperSettings(),\n }));\n\n if (!result || !(result instanceof GramJs.WallPaper)) {\n return undefined;\n }\n\n const wallpaper = buildApiWallpaper(result);\n if (!wallpaper) {\n return undefined;\n }\n\n localDb.documents[String(result.document.id)] = result.document as GramJs.Document;\n\n return { wallpaper };\n}\n\nexport async function fetchBlockedContacts() {\n const result = await invokeRequest(new GramJs.contacts.GetBlocked({\n limit: BLOCKED_LIST_LIMIT,\n }));\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return {\n users: result.users.map(buildApiUser).filter(Boolean as any),\n chats: result.chats.map((chat) => buildApiChatFromPreview(chat, undefined, true)).filter(Boolean as any),\n blockedIds: result.blocked.map((blocked) => getApiChatIdFromMtpPeer(blocked.peerId)),\n totalCount: result instanceof GramJs.contacts.BlockedSlice ? result.count : result.blocked.length,\n };\n}\n\nexport function blockContact(chatOrUserId: string, accessHash?: string) {\n return invokeRequest(new GramJs.contacts.Block({\n id: buildInputPeer(chatOrUserId, accessHash),\n }));\n}\n\nexport function unblockContact(chatOrUserId: string, accessHash?: string) {\n return invokeRequest(new GramJs.contacts.Unblock({\n id: buildInputPeer(chatOrUserId, accessHash),\n }));\n}\n\nexport async function fetchAuthorizations() {\n const result = await invokeRequest(new GramJs.account.GetAuthorizations());\n if (!result) {\n return undefined;\n }\n\n return result.authorizations.map(buildApiSession);\n}\n\nexport function terminateAuthorization(hash: string) {\n return invokeRequest(new GramJs.account.ResetAuthorization({ hash: BigInt(hash) }));\n}\n\nexport function terminateAllAuthorizations() {\n return invokeRequest(new GramJs.auth.ResetAuthorizations());\n}\n\nexport async function fetchNotificationExceptions({\n serverTimeOffset,\n}: { serverTimeOffset: number }) {\n const result = await invokeRequest(new GramJs.account.GetNotifyExceptions({ compareSound: true }));\n\n if (!(result instanceof GramJs.Updates || result instanceof GramJs.UpdatesCombined)) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return result.updates.reduce((acc, update) => {\n if (!(update instanceof GramJs.UpdateNotifySettings && update.peer instanceof GramJs.NotifyPeer)) {\n return acc;\n }\n\n acc.push(buildApiNotifyException(update.notifySettings, update.peer.peer, serverTimeOffset));\n\n return acc;\n }, [] as ApiNotifyException[]);\n}\n\nexport async function fetchNotificationSettings({\n serverTimeOffset,\n}: { serverTimeOffset: number }) {\n const [\n isMutedContactSignUpNotification,\n privateContactNotificationsSettings,\n groupNotificationsSettings,\n broadcastNotificationsSettings,\n ] = await Promise.all([\n invokeRequest(new GramJs.account.GetContactSignUpNotification()),\n invokeRequest(new GramJs.account.GetNotifySettings({\n peer: new GramJs.InputNotifyUsers(),\n })),\n invokeRequest(new GramJs.account.GetNotifySettings({\n peer: new GramJs.InputNotifyChats(),\n })),\n invokeRequest(new GramJs.account.GetNotifySettings({\n peer: new GramJs.InputNotifyBroadcasts(),\n })),\n ]);\n\n if (!privateContactNotificationsSettings || !groupNotificationsSettings || !broadcastNotificationsSettings) {\n return false;\n }\n\n const {\n silent: privateSilent, muteUntil: privateMuteUntil, showPreviews: privateShowPreviews,\n } = privateContactNotificationsSettings;\n const {\n silent: groupSilent, muteUntil: groupMuteUntil, showPreviews: groupShowPreviews,\n } = groupNotificationsSettings;\n const {\n silent: broadcastSilent, muteUntil: broadcastMuteUntil, showPreviews: broadcastShowPreviews,\n } = broadcastNotificationsSettings;\n\n return {\n hasContactJoinedNotifications: !isMutedContactSignUpNotification,\n hasPrivateChatsNotifications: !(\n privateSilent\n || (typeof privateMuteUntil === 'number' && getServerTime(serverTimeOffset) < privateMuteUntil)\n ),\n hasPrivateChatsMessagePreview: privateShowPreviews,\n hasGroupNotifications: !(\n groupSilent || (typeof groupMuteUntil === 'number'\n && getServerTime(serverTimeOffset) < groupMuteUntil)\n ),\n hasGroupMessagePreview: groupShowPreviews,\n hasBroadcastNotifications: !(\n broadcastSilent || (typeof broadcastMuteUntil === 'number'\n && getServerTime(serverTimeOffset) < broadcastMuteUntil)\n ),\n hasBroadcastMessagePreview: broadcastShowPreviews,\n };\n}\n\nexport function updateContactSignUpNotification(isSilent: boolean) {\n return invokeRequest(new GramJs.account.SetContactSignUpNotification({ silent: isSilent }));\n}\n\nexport function updateNotificationSettings(peerType: 'contact' | 'group' | 'broadcast', {\n isSilent,\n shouldShowPreviews,\n}: {\n isSilent: boolean;\n shouldShowPreviews: boolean;\n}) {\n let peer: GramJs.TypeInputNotifyPeer;\n if (peerType === 'contact') {\n peer = new GramJs.InputNotifyUsers();\n } else if (peerType === 'group') {\n peer = new GramJs.InputNotifyChats();\n } else {\n peer = new GramJs.InputNotifyBroadcasts();\n }\n\n const settings = {\n showPreviews: shouldShowPreviews,\n silent: isSilent,\n muteUntil: isSilent ? MAX_INT_32 : 0,\n };\n\n return invokeRequest(new GramJs.account.UpdateNotifySettings({\n peer,\n settings: new GramJs.InputPeerNotifySettings(settings),\n }));\n}\n\nexport async function fetchLanguages(): Promise {\n const result = await invokeRequest(new GramJs.langpack.GetLanguages({\n langPack: DEFAULT_LANG_PACK,\n }));\n if (!result) {\n return undefined;\n }\n\n return result.map(omitVirtualClassFields);\n}\n\nexport async function fetchLangPack({ sourceLangPacks, langCode }: {\n sourceLangPacks: typeof LANG_PACKS;\n langCode: string;\n}) {\n const results = await Promise.all(sourceLangPacks.map((langPack) => {\n return invokeRequest(new GramJs.langpack.GetLangPack({\n langPack,\n langCode: BETA_LANG_CODES.includes(langCode) ? `${langCode}-raw` : langCode,\n }));\n }));\n\n const collections = results\n .filter(Boolean as any)\n .map((result) => {\n return buildCollectionByKey(result.strings.map(omitVirtualClassFields), 'key');\n });\n\n if (!collections.length) {\n return undefined;\n }\n\n return { langPack: Object.assign({}, ...collections.reverse()) };\n}\n\nexport async function fetchLangStrings({ langPack, langCode, keys }: {\n langPack: string; langCode: string; keys: string[];\n}) {\n const result = await invokeRequest(new GramJs.langpack.GetStrings({\n langPack,\n langCode: BETA_LANG_CODES.includes(langCode) ? `${langCode}-raw` : langCode,\n keys,\n }));\n\n if (!result) {\n return undefined;\n }\n\n return result.map(omitVirtualClassFields);\n}\n\nexport async function fetchPrivacySettings(privacyKey: ApiPrivacyKey) {\n const key = buildInputPrivacyKey(privacyKey);\n const result = await invokeRequest(new GramJs.account.GetPrivacy({ key }));\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return buildPrivacyRules(result.rules);\n}\n\nexport function registerDevice(token: string) {\n const client = getClient();\n const secret = client.session.getAuthKey().getKey();\n return invokeRequest(new GramJs.account.RegisterDevice({\n tokenType: 10,\n secret,\n appSandbox: false,\n otherUids: [],\n token,\n }));\n}\n\nexport function unregisterDevice(token: string) {\n return invokeRequest(new GramJs.account.UnregisterDevice({\n tokenType: 10,\n otherUids: [],\n token,\n }));\n}\n\nexport async function setPrivacySettings(\n privacyKey: ApiPrivacyKey, rules: InputPrivacyRules,\n) {\n const key = buildInputPrivacyKey(privacyKey);\n const privacyRules: GramJs.TypeInputPrivacyRule[] = [];\n\n if (rules.allowedUsers) {\n privacyRules.push(new GramJs.InputPrivacyValueAllowUsers({\n users: rules.allowedUsers.map(({ id, accessHash }) => buildInputEntity(id, accessHash) as GramJs.InputUser),\n }));\n }\n if (rules.allowedChats) {\n privacyRules.push(new GramJs.InputPrivacyValueAllowChatParticipants({\n chats: rules.allowedChats.map(({ id }) => buildInputEntity(id) as BigInt.BigInteger),\n }));\n }\n if (rules.blockedUsers) {\n privacyRules.push(new GramJs.InputPrivacyValueDisallowUsers({\n users: rules.blockedUsers.map(({ id, accessHash }) => buildInputEntity(id, accessHash) as GramJs.InputUser),\n }));\n }\n if (rules.blockedChats) {\n privacyRules.push(new GramJs.InputPrivacyValueDisallowChatParticipants({\n chats: rules.blockedChats.map(({ id }) => buildInputEntity(id) as BigInt.BigInteger),\n }));\n }\n switch (rules.visibility) {\n case 'everybody':\n privacyRules.push(new GramJs.InputPrivacyValueAllowAll());\n break;\n\n case 'contacts':\n privacyRules.push(new GramJs.InputPrivacyValueAllowContacts());\n break;\n\n case 'nonContacts':\n privacyRules.push(new GramJs.InputPrivacyValueDisallowContacts());\n break;\n\n case 'nobody':\n privacyRules.push(new GramJs.InputPrivacyValueDisallowAll());\n break;\n }\n\n const result = await invokeRequest(new GramJs.account.SetPrivacy({ key, rules: privacyRules }));\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return buildPrivacyRules(result.rules);\n}\n\nexport async function updateIsOnline(isOnline: boolean) {\n await invokeRequest(new GramJs.account.UpdateStatus({ offline: !isOnline }));\n}\n\nexport async function fetchContentSettings() {\n const result = await invokeRequest(new GramJs.account.GetContentSettings());\n if (!result) {\n return undefined;\n }\n\n return {\n isSensitiveEnabled: Boolean(result.sensitiveEnabled),\n canChangeSensitive: Boolean(result.sensitiveCanChange),\n };\n}\n\nexport function updateContentSettings(isEnabled: boolean) {\n return invokeRequest(new GramJs.account.SetContentSettings({\n sensitiveEnabled: isEnabled || undefined,\n }));\n}\n\nfunction updateLocalDb(\n result: (\n GramJs.account.PrivacyRules | GramJs.contacts.Blocked | GramJs.contacts.BlockedSlice |\n GramJs.Updates | GramJs.UpdatesCombined\n ),\n) {\n result.users.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[buildApiPeerId(user.id, 'user')] = user;\n }\n });\n\n result.chats.forEach((chat) => {\n if (chat instanceof GramJs.Chat || chat instanceof GramJs.Channel) {\n localDb.chats[buildApiPeerId(chat.id, chat instanceof GramJs.Chat ? 'chat' : 'channel')] = chat;\n }\n });\n}\n\nexport async function fetchCountryList({ langCode = 'en' }: { langCode?: LangCode }) {\n const countryList = await invokeRequest(new GramJs.help.GetCountriesList({\n langCode,\n }));\n\n if (!(countryList instanceof GramJs.help.CountriesList)) {\n return undefined;\n }\n return buildApiCountryList(countryList.countries);\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n ApiBotInlineMediaResult, ApiBotInlineResult, ApiBotInlineSwitchPm, ApiInlineResultType, ApiWebDocument,\n} from '../../types';\n\nimport { pick } from '../../../util/iteratees';\nimport { buildApiPhoto, buildApiThumbnailFromStripped } from './common';\nimport { buildVideoFromDocument } from './messages';\nimport { buildStickerFromDocument } from './symbols';\n\nexport function buildApiBotInlineResult(result: GramJs.BotInlineResult, queryId: string): ApiBotInlineResult {\n const {\n id, type, title, description, url, thumb,\n } = result;\n\n return {\n id,\n queryId,\n type: type as ApiInlineResultType,\n title,\n description,\n url,\n webThumbnail: buildApiWebDocument(thumb),\n };\n}\n\nexport function buildApiBotInlineMediaResult(\n result: GramJs.BotInlineMediaResult, queryId: string,\n): ApiBotInlineMediaResult {\n const {\n id, type, title, description, photo, document,\n } = result;\n\n return {\n id,\n queryId,\n type: type as ApiInlineResultType,\n title,\n description,\n ...(type === 'sticker' && document instanceof GramJs.Document && { sticker: buildStickerFromDocument(document) }),\n ...(photo instanceof GramJs.Photo && { photo: buildApiPhoto(photo) }),\n ...(type === 'gif' && document instanceof GramJs.Document && { gif: buildVideoFromDocument(document) }),\n ...(type === 'video' && document instanceof GramJs.Document && {\n thumbnail: buildApiThumbnailFromStripped(document.thumbs),\n }),\n };\n}\n\nexport function buildBotSwitchPm(switchPm?: GramJs.InlineBotSwitchPM) {\n return switchPm ? pick(switchPm, ['text', 'startParam']) as ApiBotInlineSwitchPm : undefined;\n}\n\nfunction buildApiWebDocument(document?: GramJs.TypeWebDocument): ApiWebDocument | undefined {\n return document ? pick(document, ['url', 'mimeType']) : undefined;\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\n\nimport { ApiChat, ApiUser } from '../../types';\n\nimport localDb from '../localDb';\nimport { invokeRequest } from './client';\nimport { buildInputPeer, generateRandomBigInt } from '../gramjsBuilders';\nimport { buildApiUser } from '../apiBuilders/users';\nimport { buildApiBotInlineMediaResult, buildApiBotInlineResult, buildBotSwitchPm } from '../apiBuilders/bots';\nimport { buildApiChatFromPreview } from '../apiBuilders/chats';\nimport { buildApiPeerId } from '../apiBuilders/peers';\n\nexport function init() {\n}\n\nexport function answerCallbackButton(\n {\n chatId, accessHash, messageId, data,\n }: {\n chatId: string; accessHash?: string; messageId: number; data: string;\n },\n) {\n return invokeRequest(new GramJs.messages.GetBotCallbackAnswer({\n peer: buildInputPeer(chatId, accessHash),\n msgId: messageId,\n data: Buffer.from(data),\n }));\n}\n\nexport async function fetchTopInlineBots() {\n const topPeers = await invokeRequest(new GramJs.contacts.GetTopPeers({\n botsInline: true,\n }));\n\n if (!(topPeers instanceof GramJs.contacts.TopPeers)) {\n return undefined;\n }\n\n const users = topPeers.users.map(buildApiUser).filter(Boolean as any);\n const ids = users.map(({ id }) => id);\n\n return {\n ids,\n users,\n };\n}\n\nexport async function fetchInlineBot({ username }: { username: string }) {\n const resolvedPeer = await invokeRequest(new GramJs.contacts.ResolveUsername({ username }));\n\n if (\n !resolvedPeer\n || !(\n resolvedPeer.users[0] instanceof GramJs.User\n && resolvedPeer.users[0].bot\n && resolvedPeer.users[0].botInlinePlaceholder\n )\n ) {\n return undefined;\n }\n\n addUserToLocalDb(resolvedPeer.users[0]);\n\n return {\n user: buildApiUser(resolvedPeer.users[0]),\n chat: buildApiChatFromPreview(resolvedPeer.users[0]),\n };\n}\n\nexport async function fetchInlineBotResults({\n bot, chat, query, offset = '',\n}: {\n bot: ApiUser; chat: ApiChat; query: string; offset?: string;\n}) {\n const result = await invokeRequest(new GramJs.messages.GetInlineBotResults({\n bot: buildInputPeer(bot.id, bot.accessHash),\n peer: buildInputPeer(chat.id, chat.accessHash),\n query,\n offset,\n }));\n\n if (!result) {\n return undefined;\n }\n\n result.users.map(addUserToLocalDb);\n\n return {\n isGallery: Boolean(result.gallery),\n help: bot.botPlaceholder,\n nextOffset: getInlineBotResultsNextOffset(bot.username, result.nextOffset),\n switchPm: buildBotSwitchPm(result.switchPm),\n users: result.users.map(buildApiUser).filter(Boolean as any),\n results: processInlineBotResult(String(result.queryId), result.results),\n };\n}\n\nexport async function sendInlineBotResult({\n chat, resultId, queryId, replyingTo,\n}: {\n chat: ApiChat;\n resultId: string;\n queryId: string;\n replyingTo?: number;\n}) {\n const randomId = generateRandomBigInt();\n\n await invokeRequest(new GramJs.messages.SendInlineBotResult({\n clearDraft: true,\n randomId,\n queryId: BigInt(queryId),\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: resultId,\n ...(replyingTo && { replyToMsgId: replyingTo }),\n }), true);\n}\n\nexport async function startBot({\n bot, startParam,\n}: {\n bot: ApiUser;\n startParam?: string;\n}) {\n const randomId = generateRandomBigInt();\n\n await invokeRequest(new GramJs.messages.StartBot({\n bot: buildInputPeer(bot.id, bot.accessHash),\n peer: buildInputPeer(bot.id, bot.accessHash),\n randomId,\n startParam,\n }), true);\n}\n\nfunction processInlineBotResult(queryId: string, results: GramJs.TypeBotInlineResult[]) {\n return results.map((result) => {\n if (result instanceof GramJs.BotInlineMediaResult) {\n if (result.document instanceof GramJs.Document) {\n addDocumentToLocalDb(result.document);\n }\n\n if (result.photo instanceof GramJs.Photo) {\n addPhotoToLocalDb(result.photo);\n }\n\n return buildApiBotInlineMediaResult(result, queryId);\n }\n\n if (result.thumb) {\n addWebDocumentToLocalDb(result.thumb);\n }\n\n return buildApiBotInlineResult(result, queryId);\n });\n}\n\nfunction getInlineBotResultsNextOffset(username: string, nextOffset?: string) {\n return username === 'gif' && nextOffset === '0' ? '' : nextOffset;\n}\n\nfunction addUserToLocalDb(user: GramJs.User) {\n localDb.users[buildApiPeerId(user.id, 'user')] = user;\n}\n\nfunction addDocumentToLocalDb(document: GramJs.Document) {\n localDb.documents[String(document.id)] = document;\n}\n\nfunction addPhotoToLocalDb(photo: GramJs.Photo) {\n localDb.photos[String(photo.id)] = photo;\n}\n\nfunction addWebDocumentToLocalDb(webDocument: GramJs.TypeWebDocument) {\n localDb.webDocuments[webDocument.url] = webDocument;\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\n\nexport function buildShippingOptions(shippingOptions: GramJs.ShippingOption[] | undefined) {\n if (!shippingOptions) {\n return undefined;\n }\n return Object.values(shippingOptions).map((option) => {\n return {\n id: option.id,\n title: option.title,\n amount: option.prices.reduce((ac, cur) => ac + Number((cur.amount as any).value), 0),\n prices: option.prices.map(({ label, amount }) => {\n return {\n label,\n amount: Number((amount as any).value),\n };\n }),\n };\n });\n}\n\nexport function buildReceipt(receipt: GramJs.payments.PaymentReceipt) {\n const {\n invoice,\n info,\n shipping,\n currency,\n totalAmount,\n credentialsTitle,\n } = receipt;\n\n const { shippingAddress, phone, name } = (info || {});\n\n const { prices } = invoice;\n const mapedPrices = prices.map(({ label, amount }) => ({\n label,\n amount: Number((amount as any).value),\n }));\n\n let shippingPrices;\n let shippingMethod;\n\n if (shipping) {\n shippingPrices = shipping.prices.map(({ label, amount }) => {\n return {\n label,\n amount: Number((amount as any).value),\n };\n });\n shippingMethod = shipping.title;\n }\n\n return {\n currency,\n prices: mapedPrices,\n info: { shippingAddress, phone, name },\n totalAmount: Number((totalAmount as any).value),\n credentialsTitle,\n shippingPrices,\n shippingMethod,\n };\n}\n\nexport function buildPaymentForm(form: GramJs.payments.PaymentForm) {\n const {\n formId,\n canSaveCredentials,\n passwordMissing,\n providerId,\n nativeProvider,\n nativeParams,\n savedInfo,\n invoice,\n } = form;\n\n const {\n test,\n nameRequested,\n phoneRequested,\n emailRequested,\n shippingAddressRequested,\n flexible,\n phoneToProvider,\n emailToProvider,\n currency,\n prices,\n } = invoice;\n\n const mapedPrices = prices.map(({ label, amount }) => ({\n label,\n amount: Number((amount as any).value),\n }));\n\n const nativeData = nativeParams ? JSON.parse(nativeParams.data) : {};\n return {\n canSaveCredentials,\n passwordMissing,\n formId: String(formId),\n providerId: String(providerId),\n nativeProvider,\n savedInfo,\n invoice: {\n test,\n nameRequested,\n phoneRequested,\n emailRequested,\n shippingAddressRequested,\n flexible,\n phoneToProvider,\n emailToProvider,\n currency,\n prices: mapedPrices,\n },\n nativeParams: {\n needCardholderName: nativeData.need_cardholder_name,\n needCountry: nativeData.need_country,\n needZip: nativeData.need_zip,\n publishableKey: nativeData.publishable_key,\n },\n };\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport { invokeRequest } from './client';\nimport { buildInputPeer, buildShippingInfo } from '../gramjsBuilders';\nimport { buildShippingOptions, buildPaymentForm, buildReceipt } from '../apiBuilders/payments';\nimport { ApiChat } from '../../types';\n\nexport async function validateRequestedInfo({\n chat,\n messageId,\n requestInfo,\n shouldSave,\n}: {\n chat: ApiChat;\n messageId: number;\n requestInfo: GramJs.TypePaymentRequestedInfo;\n shouldSave?: boolean;\n}): Promise<{\n id: string;\n shippingOptions: any;\n } | undefined> {\n const result = await invokeRequest(new GramJs.payments.ValidateRequestedInfo({\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: messageId,\n save: shouldSave || undefined,\n info: buildShippingInfo(requestInfo),\n }));\n if (!result) {\n return undefined;\n }\n\n const { id, shippingOptions } = result;\n if (!id) {\n return undefined;\n }\n\n return {\n id,\n shippingOptions: buildShippingOptions(shippingOptions),\n };\n}\n\nexport function sendPaymentForm({\n chat,\n messageId,\n formId,\n requestedInfoId,\n shippingOptionId,\n credentials,\n}: {\n chat: ApiChat;\n messageId: number;\n formId: string;\n credentials: any;\n requestedInfoId?: string;\n shippingOptionId?: string;\n}) {\n return invokeRequest(new GramJs.payments.SendPaymentForm({\n formId: BigInt(formId),\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: messageId,\n requestedInfoId,\n shippingOptionId,\n credentials: new GramJs.InputPaymentCredentials({\n save: credentials.save,\n data: new GramJs.DataJSON({ data: JSON.stringify(credentials.data) }),\n }),\n }), true);\n}\n\nexport async function getPaymentForm({\n chat, messageId,\n}: {\n chat: ApiChat;\n messageId: number;\n}) {\n const result = await invokeRequest(new GramJs.payments.GetPaymentForm({\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: messageId,\n }));\n\n if (!result) {\n return undefined;\n }\n\n return buildPaymentForm(result);\n}\n\nexport async function getReceipt(chat: ApiChat, msgId: number) {\n const result = await invokeRequest(new GramJs.payments.GetPaymentReceipt({\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId,\n }));\n if (!result) {\n return undefined;\n }\n\n return buildReceipt(result);\n}\n","import {\n OnApiUpdate,\n ApiInitialArgs,\n ApiUpdate,\n ApiOnProgress,\n} from '../types';\nimport { Methods, MethodArgs, MethodResponse } from './methods/types';\n\nimport { API_THROTTLE_RESET_UPDATES, API_UPDATE_THROTTLE } from '../../config';\nimport { throttle, throttleWithTickEnd } from '../../util/schedulers';\nimport { init as initUpdater } from './updater';\nimport { init as initAuth } from './methods/auth';\nimport { init as initChats } from './methods/chats';\nimport { init as initMessages } from './methods/messages';\nimport { init as initUsers } from './methods/users';\nimport { init as initClient } from './methods/client';\nimport { init as initStickers } from './methods/symbols';\nimport { init as initManagement } from './methods/management';\nimport { init as initTwoFaSettings } from './methods/twoFaSettings';\nimport * as methods from './methods';\n\nlet onUpdate: OnApiUpdate;\n\nexport async function initApi(_onUpdate: OnApiUpdate, initialArgs: ApiInitialArgs) {\n onUpdate = _onUpdate;\n\n initUpdater(handleUpdate);\n initAuth(handleUpdate);\n initChats(handleUpdate);\n initMessages(handleUpdate);\n initUsers(handleUpdate);\n initStickers(handleUpdate);\n initManagement(handleUpdate);\n initTwoFaSettings(handleUpdate);\n\n await initClient(handleUpdate, initialArgs);\n}\n\nexport function callApi(fnName: T, ...args: MethodArgs): MethodResponse {\n // @ts-ignore\n return methods[fnName](...args) as MethodResponse;\n}\n\nexport function cancelApiProgress(progressCallback: ApiOnProgress) {\n progressCallback.isCanceled = true;\n}\n\nconst flushUpdatesOnTickEnd = throttleWithTickEnd(flushUpdates);\n\nlet flushUpdatesThrottled: typeof flushUpdatesOnTickEnd | undefined;\nlet currentThrottleId: number | undefined;\n\nlet pendingUpdates: ApiUpdate[] | undefined;\n\nfunction handleUpdate(update: ApiUpdate) {\n if (!pendingUpdates) {\n pendingUpdates = [update];\n } else {\n pendingUpdates.push(update);\n }\n\n if (!flushUpdatesThrottled || API_THROTTLE_RESET_UPDATES.has(update['@type'])) {\n flushUpdatesThrottled = throttle(flushUpdatesOnTickEnd, API_UPDATE_THROTTLE, true);\n currentThrottleId = Math.random();\n }\n\n flushUpdatesThrottled(currentThrottleId!);\n}\n\nfunction flushUpdates(throttleId: number) {\n if (!pendingUpdates || throttleId !== currentThrottleId) {\n return;\n }\n\n const currentUpdates = pendingUpdates!;\n pendingUpdates = undefined;\n currentUpdates.forEach(onUpdate);\n}\n","import { ApiOnProgress, ApiUpdate } from '../../types';\nimport { OriginMessageEvent, WorkerMessageData } from './types';\n\nimport { DEBUG } from '../../../config';\nimport { initApi, callApi, cancelApiProgress } from '../provider';\n\ndeclare const self: WorkerGlobalScope;\n\nhandleErrors();\n\n// TODO Re-use `util/createWorkerInterface.ts`\n\nconst callbackState = new Map();\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH LOAD WORKER');\n}\n\nonmessage = async (message: OriginMessageEvent) => {\n const { data } = message;\n\n switch (data.type) {\n case 'initApi': {\n await initApi(onUpdate, data.args[0]);\n break;\n }\n case 'callMethod': {\n const { messageId, name, args } = data;\n try {\n if (messageId) {\n const callback = (...callbackArgs: any[]) => {\n const lastArg = callbackArgs[callbackArgs.length - 1];\n\n sendToOrigin({\n type: 'methodCallback',\n messageId,\n callbackArgs,\n }, lastArg instanceof ArrayBuffer ? lastArg : undefined);\n };\n\n callbackState.set(messageId, callback);\n\n args.push(callback as never);\n }\n\n const response = await callApi(name, ...args);\n const { arrayBuffer } = (typeof response === 'object' && 'arrayBuffer' in response && response) || {};\n\n if (messageId) {\n sendToOrigin({\n type: 'methodResponse',\n messageId,\n response,\n }, arrayBuffer);\n }\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(error);\n }\n\n if (messageId) {\n sendToOrigin({\n type: 'methodResponse',\n messageId,\n error: { message: error.message },\n });\n }\n }\n\n if (messageId) {\n callbackState.delete(messageId);\n }\n\n break;\n }\n case 'cancelProgress': {\n const callback = callbackState.get(data.messageId);\n if (callback) {\n cancelApiProgress(callback);\n }\n\n break;\n }\n case 'ping': {\n sendToOrigin({\n type: 'methodResponse',\n messageId: data.messageId!,\n });\n\n break;\n }\n }\n};\n\nfunction handleErrors() {\n self.onerror = (e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n sendToOrigin({ type: 'unhandledError', error: { message: e.error.message || 'Uncaught exception in worker' } });\n };\n\n self.addEventListener('unhandledrejection', (e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n sendToOrigin({ type: 'unhandledError', error: { message: e.reason.message || 'Uncaught rejection in worker' } });\n });\n}\n\nfunction onUpdate(update: ApiUpdate) {\n sendToOrigin({\n type: 'update',\n update,\n });\n}\n\nfunction sendToOrigin(data: WorkerMessageData, arrayBuffer?: ArrayBuffer) {\n if (arrayBuffer) {\n postMessage(data, [arrayBuffer]);\n } else {\n postMessage(data);\n }\n}\n","const BigInt = require('big-integer');\nconst crypto = require('./crypto/crypto');\n\n/**\n * converts a buffer to big int\n * @param buffer\n * @param little\n * @param signed\n * @returns {bigInt.BigInteger}\n */\nfunction readBigIntFromBuffer(buffer, little = true, signed = false) {\n let randBuffer = Buffer.from(buffer);\n const bytesNumber = randBuffer.length;\n if (little) {\n randBuffer = randBuffer.reverse();\n }\n let bigInt = BigInt(randBuffer.toString('hex'), 16);\n if (signed && Math.floor(bigInt.toString('2').length / 8) >= bytesNumber) {\n bigInt = bigInt.subtract(BigInt(2)\n .pow(BigInt(bytesNumber * 8)));\n }\n return bigInt;\n}\n\n/**\n * Special case signed little ints\n * @param big\n * @param number\n * @returns {Buffer}\n */\nfunction toSignedLittleBuffer(big, number = 8) {\n const bigNumber = BigInt(big);\n const byteArray = [];\n for (let i = 0; i < number; i++) {\n byteArray[i] = bigNumber.shiftRight(8 * i)\n .and(255);\n }\n return Buffer.from(byteArray);\n}\n\n\n/**\n * converts a big int to a buffer\n * @param bigInt {bigInt.BigInteger}\n * @param bytesNumber\n * @param little\n * @param signed\n * @returns {Buffer}\n */\nfunction readBufferFromBigInt(bigInt, bytesNumber, little = true, signed = false) {\n bigInt = BigInt(bigInt);\n const bitLength = bigInt.bitLength();\n\n const bytes = Math.ceil(bitLength / 8);\n if (bytesNumber < bytes) {\n throw new Error('OverflowError: int too big to convert');\n }\n if (!signed && bigInt.lesser(BigInt(0))) {\n throw new Error('Cannot convert to unsigned');\n }\n let below = false;\n if (bigInt.lesser(BigInt(0))) {\n below = true;\n bigInt = bigInt.abs();\n }\n\n const hex = bigInt.toString('16')\n .padStart(bytesNumber * 2, '0');\n let l = Buffer.from(hex, 'hex');\n if (little) {\n l = l.reverse();\n }\n\n if (signed && below) {\n if (little) {\n let reminder = false;\n if (l[0] !== 0) {\n l[0] -= 1;\n }\n for (let i = 0; i < l.length; i++) {\n if (l[i] === 0) {\n reminder = true;\n continue;\n }\n if (reminder) {\n l[i] -= 1;\n reminder = false;\n }\n l[i] = 255 - l[i];\n }\n } else {\n l[l.length - 1] = 256 - l[l.length - 1];\n for (let i = 0; i < l.length - 1; i++) {\n l[i] = 255 - l[i];\n }\n }\n }\n return l;\n}\n\n/**\n * Generates a random long integer (8 bytes), which is optionally signed\n * @returns {BigInteger}\n */\nfunction generateRandomLong(signed = true) {\n return readBigIntFromBuffer(generateRandomBytes(8), true, signed);\n}\n\n/**\n * .... really javascript\n * @param n {number}\n * @param m {number}\n * @returns {number}\n */\nfunction mod(n, m) {\n return ((n % m) + m) % m;\n}\n\n/**\n * returns a positive bigInt\n * @param n {BigInt}\n * @param m {BigInt}\n * @returns {BigInt}\n */\nfunction bigIntMod(n, m) {\n return ((n.remainder(m)).add(m)).remainder(m);\n}\n\n/**\n * Generates a random bytes array\n * @param count\n * @returns {Buffer}\n */\nfunction generateRandomBytes(count) {\n return Buffer.from(crypto.randomBytes(count));\n}\n\n/**\n * Calculate the key based on Telegram guidelines, specifying whether it's the client or not\n * @param sharedKey\n * @param msgKey\n * @param client\n * @returns {{iv: Buffer, key: Buffer}}\n */\n\n/* CONTEST\nthis is mtproto 1 (mostly used for secret chats)\nasync function calcKey(sharedKey, msgKey, client) {\n const x = client === true ? 0 : 8\n const [sha1a, sha1b, sha1c, sha1d] = await Promise.all([\n sha1(Buffer.concat([msgKey, sharedKey.slice(x, x + 32)])),\n sha1(Buffer.concat([sharedKey.slice(x + 32, x + 48), msgKey, sharedKey.slice(x + 48, x + 64)])),\n sha1(Buffer.concat([sharedKey.slice(x + 64, x + 96), msgKey])),\n sha1(Buffer.concat([msgKey, sharedKey.slice(x + 96, x + 128)]))\n ])\n const key = Buffer.concat([sha1a.slice(0, 8), sha1b.slice(8, 20), sha1c.slice(4, 16)])\n const iv = Buffer.concat([sha1a.slice(8, 20), sha1b.slice(0, 8), sha1c.slice(16, 20), sha1d.slice(0, 8)])\n return {\n key,\n iv\n }\n}\n\n */\n\n/**\n * Generates the key data corresponding to the given nonces\n * @param serverNonce\n * @param newNonce\n * @returns {{key: Buffer, iv: Buffer}}\n */\nasync function generateKeyDataFromNonce(serverNonce, newNonce) {\n serverNonce = toSignedLittleBuffer(serverNonce, 16);\n newNonce = toSignedLittleBuffer(newNonce, 32);\n const [hash1, hash2, hash3] = await Promise.all([\n sha1(Buffer.concat([newNonce, serverNonce])),\n sha1(Buffer.concat([serverNonce, newNonce])),\n sha1(Buffer.concat([newNonce, newNonce])),\n ]);\n const keyBuffer = Buffer.concat([hash1, hash2.slice(0, 12)]);\n const ivBuffer = Buffer.concat([hash2.slice(12, 20), hash3, newNonce.slice(0, 4)]);\n return {\n key: keyBuffer,\n iv: ivBuffer,\n };\n}\n\nfunction convertToLittle(buf) {\n const correct = Buffer.alloc(buf.length * 4);\n\n for (let i = 0; i < buf.length; i++) {\n correct.writeUInt32BE(buf[i], i * 4);\n }\n return correct;\n}\n\n/**\n * Calculates the SHA1 digest for the given data\n * @param data\n * @returns {Promise}\n */\nfunction sha1(data) {\n const shaSum = crypto.createHash('sha1');\n shaSum.update(data);\n return shaSum.digest();\n}\n\n\n/**\n * Calculates the SHA256 digest for the given data\n * @param data\n * @returns {Promise}\n */\nfunction sha256(data) {\n const shaSum = crypto.createHash('sha256');\n shaSum.update(data);\n return shaSum.digest();\n}\n\n/**\n * Fast mod pow for RSA calculation. a^b % n\n * @param a\n * @param b\n * @param n\n * @returns {bigInt.BigInteger}\n */\nfunction modExp(a, b, n) {\n a = a.remainder(n);\n let result = BigInt.one;\n let x = a;\n while (b.greater(BigInt.zero)) {\n const leastSignificantBit = b.remainder(BigInt(2));\n b = b.divide(BigInt(2));\n if (leastSignificantBit.eq(BigInt.one)) {\n result = result.multiply(x);\n result = result.remainder(n);\n }\n x = x.multiply(x);\n x = x.remainder(n);\n }\n return result;\n}\n\n\n/**\n * Gets the arbitrary-length byte array corresponding to the given integer\n * @param integer {number,BigInteger}\n * @param signed {boolean}\n * @returns {Buffer}\n */\nfunction getByteArray(integer, signed = false) {\n const bits = integer.toString(2).length;\n const byteLength = Math.floor((bits + 8 - 1) / 8);\n return readBufferFromBigInt(BigInt(integer), byteLength, false, signed);\n}\n\n/**\n * returns a random int from min (inclusive) and max (inclusive)\n * @param min\n * @param max\n * @returns {number}\n */\nfunction getRandomInt(min, max) {\n min = Math.ceil(min);\n max = Math.floor(max);\n return Math.floor(Math.random() * (max - min + 1)) + min;\n}\n\n/**\n * Sleeps a specified amount of time\n * @param ms time in milliseconds\n * @returns {Promise}\n */\nconst sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));\n\n/**\n * Helper to export two buffers of same length\n * @returns {Buffer}\n */\n\nfunction bufferXor(a, b) {\n const res = [];\n for (let i = 0; i < a.length; i++) {\n res.push(a[i] ^ b[i]);\n }\n return Buffer.from(res);\n}\n\n/**\n * Checks if the obj is an array\n * @param obj\n * @returns {boolean}\n */\n/*\nCONTEST\nwe do'nt support array requests anyway\nfunction isArrayLike(obj) {\n if (!obj) return false\n const l = obj.length\n if (typeof l != 'number' || l < 0) return false\n if (Math.floor(l) !== l) return false\n // fast check\n if (l > 0 && !(l - 1 in obj)) return false\n // more complete check (optional)\n for (let i = 0; i < l; ++i) {\n if (!(i in obj)) return false\n }\n return true\n}\n*/\n\n// Taken from https://stackoverflow.com/questions/18638900/javascript-crc32/18639999#18639999\nfunction makeCRCTable() {\n let c;\n const crcTable = [];\n for (let n = 0; n < 256; n++) {\n c = n;\n for (let k = 0; k < 8; k++) {\n c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));\n }\n crcTable[n] = c;\n }\n return crcTable;\n}\n\nlet crcTable;\n\nfunction crc32(buf) {\n if (!crcTable) {\n crcTable = makeCRCTable();\n }\n if (!Buffer.isBuffer(buf)) {\n buf = Buffer.from(buf);\n }\n let crc = -1;\n\n for (let index = 0; index < buf.length; index++) {\n const byte = buf[index];\n crc = crcTable[(crc ^ byte) & 0xff] ^ (crc >>> 8);\n }\n return (crc ^ (-1)) >>> 0;\n}\n\n/**\n * Creates a deferred object\n * @return {Deferred}\n */\nfunction createDeferred() {\n let resolve;\n const promise = new Promise((_resolve) => {\n resolve = _resolve;\n });\n\n return {\n promise,\n resolve,\n };\n}\n\nmodule.exports = {\n readBigIntFromBuffer,\n readBufferFromBigInt,\n generateRandomLong,\n mod,\n crc32,\n generateRandomBytes,\n // calcKey,\n generateKeyDataFromNonce,\n sha1,\n sha256,\n bigIntMod,\n modExp,\n getRandomInt,\n sleep,\n getByteArray,\n // isArrayLike,\n toSignedLittleBuffer,\n convertToLittle,\n bufferXor,\n createDeferred,\n};\n","const BigInt = require('big-integer');\nconst { constructors } = require('./tl');\nconst {\n readBigIntFromBuffer,\n readBufferFromBigInt,\n sha256,\n bigIntMod,\n modExp,\n generateRandomBytes,\n} = require('./Helpers');\nconst crypto = require('./crypto/crypto');\n\nconst SIZE_FOR_HASH = 256;\n\n/**\n *\n *\n * @param prime{BigInteger}\n * @param g{BigInteger}\n */\n\n/*\nWe don't support changing passwords yet\nfunction checkPrimeAndGoodCheck(prime, g) {\n console.error('Unsupported function `checkPrimeAndGoodCheck` call. Arguments:', prime, g)\n\n const goodPrimeBitsCount = 2048\n if (prime < 0 || prime.bitLength() !== goodPrimeBitsCount) {\n throw new Error(`bad prime count ${prime.bitLength()},expected ${goodPrimeBitsCount}`)\n }\n // TODO this is kinda slow\n if (Factorizator.factorize(prime)[0] !== 1) {\n throw new Error('give \"prime\" is not prime')\n }\n if (g.eq(BigInt(2))) {\n if ((prime.remainder(BigInt(8))).neq(BigInt(7))) {\n throw new Error(`bad g ${g}, mod8 ${prime % 8}`)\n }\n } else if (g.eq(BigInt(3))) {\n if ((prime.remainder(BigInt(3))).neq(BigInt(2))) {\n throw new Error(`bad g ${g}, mod3 ${prime % 3}`)\n }\n // eslint-disable-next-line no-empty\n } else if (g.eq(BigInt(4))) {\n\n } else if (g.eq(BigInt(5))) {\n if (!([ BigInt(1), BigInt(4) ].includes(prime.remainder(BigInt(5))))) {\n throw new Error(`bad g ${g}, mod8 ${prime % 5}`)\n }\n } else if (g.eq(BigInt(6))) {\n if (!([ BigInt(19), BigInt(23) ].includes(prime.remainder(BigInt(24))))) {\n throw new Error(`bad g ${g}, mod8 ${prime % 24}`)\n }\n } else if (g.eq(BigInt(7))) {\n if (!([ BigInt(3), BigInt(5), BigInt(6) ].includes(prime.remainder(BigInt(7))))) {\n throw new Error(`bad g ${g}, mod8 ${prime % 7}`)\n }\n } else {\n throw new Error(`bad g ${g}`)\n }\n const primeSub1Div2 = (prime.subtract(BigInt(1))).divide(BigInt(2))\n if (Factorizator.factorize(primeSub1Div2)[0] !== 1) {\n throw new Error('(prime - 1) // 2 is not prime')\n }\n}\n*/\n/**\n *\n * @param primeBytes{Buffer}\n * @param g{number}\n */\nfunction checkPrimeAndGood(primeBytes, g) {\n const goodPrime = Buffer.from([\n 0xC7, 0x1C, 0xAE, 0xB9, 0xC6, 0xB1, 0xC9, 0x04, 0x8E, 0x6C, 0x52, 0x2F, 0x70, 0xF1, 0x3F, 0x73,\n 0x98, 0x0D, 0x40, 0x23, 0x8E, 0x3E, 0x21, 0xC1, 0x49, 0x34, 0xD0, 0x37, 0x56, 0x3D, 0x93, 0x0F,\n 0x48, 0x19, 0x8A, 0x0A, 0xA7, 0xC1, 0x40, 0x58, 0x22, 0x94, 0x93, 0xD2, 0x25, 0x30, 0xF4, 0xDB,\n 0xFA, 0x33, 0x6F, 0x6E, 0x0A, 0xC9, 0x25, 0x13, 0x95, 0x43, 0xAE, 0xD4, 0x4C, 0xCE, 0x7C, 0x37,\n 0x20, 0xFD, 0x51, 0xF6, 0x94, 0x58, 0x70, 0x5A, 0xC6, 0x8C, 0xD4, 0xFE, 0x6B, 0x6B, 0x13, 0xAB,\n 0xDC, 0x97, 0x46, 0x51, 0x29, 0x69, 0x32, 0x84, 0x54, 0xF1, 0x8F, 0xAF, 0x8C, 0x59, 0x5F, 0x64,\n 0x24, 0x77, 0xFE, 0x96, 0xBB, 0x2A, 0x94, 0x1D, 0x5B, 0xCD, 0x1D, 0x4A, 0xC8, 0xCC, 0x49, 0x88,\n 0x07, 0x08, 0xFA, 0x9B, 0x37, 0x8E, 0x3C, 0x4F, 0x3A, 0x90, 0x60, 0xBE, 0xE6, 0x7C, 0xF9, 0xA4,\n 0xA4, 0xA6, 0x95, 0x81, 0x10, 0x51, 0x90, 0x7E, 0x16, 0x27, 0x53, 0xB5, 0x6B, 0x0F, 0x6B, 0x41,\n 0x0D, 0xBA, 0x74, 0xD8, 0xA8, 0x4B, 0x2A, 0x14, 0xB3, 0x14, 0x4E, 0x0E, 0xF1, 0x28, 0x47, 0x54,\n 0xFD, 0x17, 0xED, 0x95, 0x0D, 0x59, 0x65, 0xB4, 0xB9, 0xDD, 0x46, 0x58, 0x2D, 0xB1, 0x17, 0x8D,\n 0x16, 0x9C, 0x6B, 0xC4, 0x65, 0xB0, 0xD6, 0xFF, 0x9C, 0xA3, 0x92, 0x8F, 0xEF, 0x5B, 0x9A, 0xE4,\n 0xE4, 0x18, 0xFC, 0x15, 0xE8, 0x3E, 0xBE, 0xA0, 0xF8, 0x7F, 0xA9, 0xFF, 0x5E, 0xED, 0x70, 0x05,\n 0x0D, 0xED, 0x28, 0x49, 0xF4, 0x7B, 0xF9, 0x59, 0xD9, 0x56, 0x85, 0x0C, 0xE9, 0x29, 0x85, 0x1F,\n 0x0D, 0x81, 0x15, 0xF6, 0x35, 0xB1, 0x05, 0xEE, 0x2E, 0x4E, 0x15, 0xD0, 0x4B, 0x24, 0x54, 0xBF,\n 0x6F, 0x4F, 0xAD, 0xF0, 0x34, 0xB1, 0x04, 0x03, 0x11, 0x9C, 0xD8, 0xE3, 0xB9, 0x2F, 0xCC, 0x5B,\n ]);\n if (goodPrime.equals(primeBytes)) {\n if ([3, 4, 5, 7].includes(g)) {\n return; // It's good\n }\n }\n throw new Error('Changing passwords unsupported');\n // checkPrimeAndGoodCheck(readBigIntFromBuffer(primeBytes, false), g)\n}\n\n/**\n *\n * @param number{BigInteger}\n * @param p{BigInteger}\n * @returns {boolean}\n */\nfunction isGoodLarge(number, p) {\n return (number.greater(BigInt(0)) && (p.subtract(number)\n .greater(BigInt(0))));\n}\n\n/**\n *\n * @param number {Buffer}\n * @returns {Buffer}\n */\nfunction numBytesForHash(number) {\n return Buffer.concat([Buffer.alloc(SIZE_FOR_HASH - number.length), number]);\n}\n\n/**\n *\n * @param g {Buffer}\n * @returns {Buffer}\n */\nfunction bigNumForHash(g) {\n return readBufferFromBigInt(g, SIZE_FOR_HASH, false);\n}\n\n/**\n *\n * @param modexp {BigInteger}\n * @param prime {BigInteger}\n * @returns {Boolean}\n */\nfunction isGoodModExpFirst(modexp, prime) {\n const diff = prime.subtract(modexp);\n\n const minDiffBitsCount = 2048 - 64;\n const maxModExpSize = 256;\n\n return !(diff.lesser(BigInt(0)) || diff.bitLength() < minDiffBitsCount\n || modexp.bitLength() < minDiffBitsCount\n || Math.floor((modexp.bitLength() + 7) / 8) > maxModExpSize);\n}\n\nfunction xor(a, b) {\n const length = Math.min(a.length, b.length);\n\n for (let i = 0; i < length; i++) {\n a[i] ^= b[i];\n }\n\n return a;\n}\n\n/**\n *\n * @param password{Buffer}\n * @param salt{Buffer}\n * @param iterations{number}\n * @returns {*}\n */\n\nfunction pbkdf2sha512(password, salt, iterations) {\n return crypto.pbkdf2(password, salt, iterations, 64, 'sha512');\n}\n\n/**\n *\n * @param algo {constructors.PasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow}\n * @param password\n * @returns {Buffer|*}\n */\nasync function computeHash(algo, password) {\n const hash1 = await sha256(Buffer.concat([algo.salt1, Buffer.from(password, 'utf-8'), algo.salt1]));\n const hash2 = await sha256(Buffer.concat([algo.salt2, hash1, algo.salt2]));\n const hash3 = await pbkdf2sha512(hash2, algo.salt1, 100000);\n return sha256(Buffer.concat([algo.salt2, hash3, algo.salt2]));\n}\n\n/**\n *\n * @param algo {constructors.PasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow}\n * @param password\n */\nasync function computeDigest(algo, password) {\n try {\n checkPrimeAndGood(algo.p, algo.g);\n } catch (e) {\n throw new Error('bad p/g in password');\n }\n\n const value = modExp(BigInt(algo.g),\n readBigIntFromBuffer(await computeHash(algo, password), false),\n readBigIntFromBuffer(algo.p, false));\n return bigNumForHash(value);\n}\n\n/**\n *\n * @param request {constructors.account.Password}\n * @param password {string}\n */\nasync function computeCheck(request, password) {\n const algo = request.currentAlgo;\n if (!(algo instanceof constructors.PasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow)) {\n throw new Error(`Unsupported password algorithm ${algo.className}`);\n }\n\n const pwHash = await computeHash(algo, password);\n const p = readBigIntFromBuffer(algo.p, false);\n const { g } = algo;\n const B = readBigIntFromBuffer(request.srp_B, false);\n try {\n checkPrimeAndGood(algo.p, g);\n } catch (e) {\n throw new Error('bad /g in password');\n }\n if (!isGoodLarge(B, p)) {\n throw new Error('bad b in check');\n }\n const x = readBigIntFromBuffer(pwHash, false);\n const pForHash = numBytesForHash(algo.p);\n const gForHash = bigNumForHash(g);\n const bForHash = numBytesForHash(request.srp_B);\n const gX = modExp(BigInt(g), x, p);\n const k = readBigIntFromBuffer(await sha256(Buffer.concat([pForHash, gForHash])), false);\n const kgX = bigIntMod(k.multiply(gX), p);\n const generateAndCheckRandom = async () => {\n const randomSize = 256;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const random = generateRandomBytes(randomSize);\n const a = readBigIntFromBuffer(random, false);\n const A = modExp(BigInt(g), a, p);\n if (isGoodModExpFirst(A, p)) {\n const aForHash = bigNumForHash(A);\n const u = readBigIntFromBuffer(await sha256(Buffer.concat([aForHash, bForHash])), false);\n if (u.greater(BigInt(0))) {\n return [a, aForHash, u];\n }\n }\n }\n };\n const [a, aForHash, u] = await generateAndCheckRandom();\n const gB = bigIntMod(B.subtract(kgX), p);\n if (!isGoodModExpFirst(gB, p)) {\n throw new Error('bad gB');\n }\n\n const ux = u.multiply(x);\n const aUx = a.add(ux);\n const S = modExp(gB, aUx, p);\n const [K, pSha, gSha, salt1Sha, salt2Sha] = await Promise.all([\n sha256(bigNumForHash(S)),\n sha256(pForHash),\n sha256(gForHash),\n sha256(algo.salt1),\n sha256(algo.salt2),\n ]);\n const M1 = await sha256(Buffer.concat([\n xor(pSha, gSha),\n salt1Sha,\n salt2Sha,\n aForHash,\n bForHash,\n K,\n ]));\n\n\n return new constructors.InputCheckPasswordSRP({\n srpId: request.srpId,\n A: Buffer.from(aForHash),\n M1,\n\n });\n}\n\nmodule.exports = {\n computeCheck,\n computeDigest,\n};\n","const { constructors } = require('./tl');\n\n// eslint-disable-next-line max-len\nconst JPEG_HEADER = Buffer.from('ffd8ffe000104a46494600010100000100010000ffdb004300281c1e231e19282321232d2b28303c64413c37373c7b585d4964918099968f808c8aa0b4e6c3a0aadaad8a8cc8ffcbdaeef5ffffff9bc1fffffffaffe6fdfff8ffdb0043012b2d2d3c353c76414176f8a58ca5f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8ffc00011080000000003012200021101031101ffc4001f0000010501010101010100000000000000000102030405060708090a0bffc400b5100002010303020403050504040000017d01020300041105122131410613516107227114328191a1082342b1c11552d1f02433627282090a161718191a25262728292a3435363738393a434445464748494a535455565758595a636465666768696a737475767778797a838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae1e2e3e4e5e6e7e8e9eaf1f2f3f4f5f6f7f8f9faffc4001f0100030101010101010101010000000000000102030405060708090a0bffc400b51100020102040403040705040400010277000102031104052131061241510761711322328108144291a1b1c109233352f0156272d10a162434e125f11718191a262728292a35363738393a434445464748494a535455565758595a636465666768696a737475767778797a82838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae2e3e4e5e6e7e8e9eaf2f3f4f5f6f7f8f9faffda000c03010002110311003f00', 'hex');\nconst JPEG_FOOTER = Buffer.from('ffd9', 'hex');\n\nfunction _raiseCastFail(entity, target) {\n throw new Error(`Cannot cast ${entity.className} to any kind of ${target}`);\n}\n\n/**\n Gets the input peer for the given \"entity\" (user, chat or channel).\n\n A ``TypeError`` is raised if the given entity isn't a supported type\n or if ``check_hash is True`` but the entity's ``accessHash is None``\n *or* the entity contains ``min`` information. In this case, the hash\n cannot be used for general purposes, and thus is not returned to avoid\n any issues which can derive from invalid access hashes.\n\n Note that ``check_hash`` **is ignored** if an input peer is already\n passed since in that case we assume the user knows what they're doing.\n This is key to getting entities by explicitly passing ``hash = 0``.\n\n * @param entity\n * @param allowSelf\n * @param checkHash\n */\nfunction getInputPeer(entity, allowSelf = true, checkHash = true) {\n if (entity.SUBCLASS_OF_ID === undefined) {\n // e.g. custom.Dialog (can't cyclic import).\n\n if (allowSelf && 'inputEntity' in entity) {\n return entity.inputEntity;\n } else if ('entity' in entity) {\n return getInputPeer(entity.entity);\n } else {\n _raiseCastFail(entity, 'InputPeer');\n }\n }\n if (entity.SUBCLASS_OF_ID === 0xc91c90b6) { // crc32(b'InputPeer')\n return entity;\n }\n\n if (entity instanceof constructors.User) {\n if (entity.isSelf && allowSelf) {\n return new constructors.InputPeerSelf();\n } else if (entity.accessHash !== undefined || !checkHash) {\n return new constructors.InputPeerUser({\n userId: entity.id,\n accessHash: entity.accessHash,\n });\n } else {\n throw new Error('User without accessHash or min info cannot be input');\n }\n }\n if (entity instanceof constructors.Chat || entity instanceof constructors.ChatEmpty\n || entity instanceof constructors.ChatForbidden) {\n return new constructors.InputPeerChat({ chatId: entity.id });\n }\n if (entity instanceof constructors.Channel) {\n if (entity.accessHash !== undefined || !checkHash) {\n return new constructors.InputPeerChannel({\n channelId: entity.id,\n accessHash: entity.accessHash,\n });\n } else {\n throw new TypeError('Channel without accessHash or min info cannot be input');\n }\n }\n if (entity instanceof constructors.ChannelForbidden) {\n // \"channelForbidden are never min\", and since their hash is\n // also not optional, we assume that this truly is the case.\n return new constructors.InputPeerChannel({\n channelId: entity.id,\n accessHash: entity.accessHash,\n });\n }\n\n if (entity instanceof constructors.InputUser) {\n return new constructors.InputPeerUser({\n userId: entity.userId,\n accessHash: entity.accessHash,\n });\n }\n if (entity instanceof constructors.InputChannel) {\n return new constructors.InputPeerChannel({\n channelId: entity.channelId,\n accessHash: entity.accessHash,\n });\n }\n if (entity instanceof constructors.UserEmpty) {\n return new constructors.InputPeerEmpty();\n }\n if (entity instanceof constructors.UserFull) {\n return getInputPeer(entity.user);\n }\n\n if (entity instanceof constructors.ChatFull) {\n return new constructors.InputPeerChat({ chatId: entity.id });\n }\n\n if (entity instanceof constructors.PeerChat) {\n return new constructors.InputPeerChat(entity.chatId);\n }\n\n _raiseCastFail(entity, 'InputPeer');\n return undefined;\n}\n\n/**\n Similar to :meth:`get_input_peer`, but for :tl:`InputChannel`'s alone.\n\n .. important::\n\n This method does not validate for invalid general-purpose access\n hashes, unlike `get_input_peer`. Consider using instead:\n ``get_input_channel(get_input_peer(channel))``.\n\n * @param entity\n * @returns {InputChannel|*}\n */\n/* CONTEST\nfunction getInputChannel(entity) {\n if (entity.SUBCLASS_OF_ID === undefined) {\n _raiseCastFail(entity, 'InputChannel')\n }\n\n\n if (entity.SUBCLASS_OF_ID === 0x40f202fd) { // crc32(b'InputChannel')\n return entity\n }\n if (entity instanceof constructors.Channel || entity instanceof constructors.ChannelForbidden) {\n return new constructors.InputChannel({\n channelId: entity.id,\n accessHash: entity.accessHash || 0\n })\n }\n\n if (entity instanceof constructors.InputPeerChannel) {\n return new constructors.InputChannel({\n channelId: entity.channelId,\n accessHash: entity.accessHash\n })\n }\n _raiseCastFail(entity, 'InputChannel')\n}\n*/\n/**\n Similar to :meth:`get_input_peer`, but for :tl:`InputUser`'s alone.\n\n .. important::\n\n This method does not validate for invalid general-purpose access\n hashes, unlike `get_input_peer`. Consider using instead:\n ``get_input_channel(get_input_peer(channel))``.\n\n * @param entity\n */\n/* CONTEST\nfunction getInputUser(entity) {\n if (entity.SUBCLASS_OF_ID === undefined) {\n _raiseCastFail(entity, 'InputUser')\n }\n if (entity.SUBCLASS_OF_ID === 0xe669bf46) { // crc32(b'InputUser')\n return entity\n }\n\n if (entity instanceof constructors.User) {\n if (entity.isSelf) {\n return new constructors.InputPeerSelf()\n } else {\n return new constructors.InputUser({\n userId: entity.id,\n accessHash: entity.accessHash || 0,\n })\n }\n }\n if (entity instanceof constructors.InputPeerSelf) {\n return new constructors.InputPeerSelf()\n }\n if (entity instanceof constructors.UserEmpty || entity instanceof constructors.InputPeerEmpty) {\n return new constructors.InputUserEmpty()\n }\n\n if (entity instanceof constructors.UserFull) {\n return getInputUser(entity.user)\n }\n\n if (entity instanceof constructors.InputPeerUser) {\n return new constructors.InputUser({\n userId: entity.userId,\n accessHash: entity.accessHash\n })\n }\n\n _raiseCastFail(entity, 'InputUser')\n}\n*/\n/**\n Similar to :meth:`get_input_peer`, but for dialogs\n * @param dialog\n */\n/* CONTEST\nfunction getInputDialog(dialog) {\n try {\n if (dialog.SUBCLASS_OF_ID === 0xa21c9795) { // crc32(b'InputDialogPeer')\n return dialog\n }\n if (dialog.SUBCLASS_OF_ID === 0xc91c90b6) { // crc32(b'InputPeer')\n return new constructors.InputDialogPeer({ peer: dialog })\n }\n } catch (e) {\n _raiseCastFail(dialog, 'InputDialogPeer')\n }\n\n try {\n return new constructors.InputDialogPeer(getInputPeer(dialog))\n // eslint-disable-next-line no-empty\n } catch (e) {\n\n }\n _raiseCastFail(dialog, 'InputDialogPeer')\n}\n*/\n\n/* CONTEST\n\nfunction getInputMessage(message) {\n try {\n if (typeof message == 'number') { // This case is really common too\n return new constructors.InputMessageID({\n id: message,\n })\n } else if (message.SUBCLASS_OF_ID === 0x54b6bcc5) { // crc32(b'InputMessage')\n return message\n } else if (message.SUBCLASS_OF_ID === 0x790009e3) { // crc32(b'Message')\n return new constructors.InputMessageID(message.id)\n }\n // eslint-disable-next-line no-empty\n } catch (e) {\n }\n\n _raiseCastFail(message, 'InputMessage')\n}\n*/\n\n/**\n * Adds the JPG header and footer to a stripped image.\n * Ported from https://github.com/telegramdesktop/\n * tdesktop/blob/bec39d89e19670eb436dc794a8f20b657cb87c71/Telegram/SourceFiles/ui/image/image.cpp#L225\n\n * @param stripped{Buffer}\n * @returns {Buffer}\n */\nfunction strippedPhotoToJpg(stripped) {\n // Note: Changes here should update _stripped_real_length\n if (stripped.length < 3 || stripped[0] !== 1) {\n return stripped;\n }\n const header = Buffer.from(JPEG_HEADER);\n // eslint-disable-next-line prefer-destructuring\n header[164] = stripped[1];\n // eslint-disable-next-line prefer-destructuring\n header[166] = stripped[2];\n return Buffer.concat([header, stripped.slice(3), JPEG_FOOTER]);\n}\n\n/* CONTEST\nfunction getInputLocation(location) {\n try {\n if (!location.SUBCLASS_OF_ID) {\n throw new Error()\n }\n if (location.SUBCLASS_OF_ID === 0x1523d462) {\n return {\n dcId: null,\n inputLocation: location\n }\n }\n } catch (e) {\n _raiseCastFail(location, 'InputFileLocation')\n }\n if (location instanceof constructors.Message) {\n location = location.media\n }\n\n if (location instanceof constructors.MessageMediaDocument) {\n location = location.document\n } else if (location instanceof constructors.MessageMediaPhoto) {\n location = location.photo\n }\n\n if (location instanceof constructors.Document) {\n return {\n dcId: location.dcId,\n inputLocation: new constructors.InputDocumentFileLocation({\n id: location.id,\n accessHash: location.accessHash,\n fileReference: location.fileReference,\n thumbSize: '', // Presumably to download one of its thumbnails\n }),\n }\n } else if (location instanceof constructors.Photo) {\n return {\n dcId: location.dcId,\n inputLocation: new constructors.InputPhotoFileLocation({\n id: location.id,\n accessHash: location.accessHash,\n fileReference: location.fileReference,\n thumbSize: location.sizes[location.sizes.length - 1].type,\n }),\n }\n }\n\n if (location instanceof constructors.FileLocationToBeDeprecated) {\n throw new Error('Unavailable location cannot be used as input')\n }\n _raiseCastFail(location, 'InputFileLocation')\n}\n*/\n\n/**\n * Gets the appropriated part size when uploading or downloading files,\n * given an initial file size.\n * @param fileSize\n * @returns {Number}\n */\nfunction getAppropriatedPartSize(fileSize) {\n if (fileSize <= 104857600) { // 100MB\n return 128;\n }\n if (fileSize <= 786432000) { // 750MB\n return 256;\n }\n if (fileSize <= 2097152000) { // 2000MB\n return 512;\n }\n\n throw new Error('File size too large');\n}\n\n/* CONTEST\nfunction getPeer(peer) {\n try {\n if (typeof peer === 'number') {\n const res = resolveId(peer)\n\n if (res[1] === constructors.PeerChannel) {\n return new res[1]({ channelId: res[0] })\n } else if (res[1] === constructors.PeerChat) {\n return new res[1]({ chatId: res[0] })\n } else {\n return new res[1]({ userId: res[0] })\n }\n }\n if (peer.SUBCLASS_OF_ID === undefined) {\n throw new Error()\n }\n if (peer.SUBCLASS_OF_ID === 0x2d45687) {\n return peer\n } else if (peer instanceof constructors.contacts.ResolvedPeer ||\n peer instanceof constructors.InputNotifyPeer || peer instanceof constructors.TopPeer ||\n peer instanceof constructors.Dialog || peer instanceof constructors.DialogPeer) {\n return peer.peer\n } else if (peer instanceof constructors.ChannelFull) {\n return new constructors.PeerChannel({ channelId: peer.id })\n }\n if (peer.SUBCLASS_OF_ID === 0x7d7c6f86 || peer.SUBCLASS_OF_ID === 0xd9c7fc18) {\n // ChatParticipant, ChannelParticipant\n return new constructors.PeerUser({ userId: peer.userId })\n }\n peer = getInputPeer(peer, false, false)\n\n if (peer instanceof constructors.InputPeerUser) {\n return new constructors.PeerUser({ userId: peer.userId })\n } else if (peer instanceof constructors.InputPeerChat) {\n return new constructors.PeerChat({ chatId: peer.chatId })\n } else if (peer instanceof constructors.InputPeerChannel) {\n return new constructors.PeerChannel({ channelId: peer.channelId })\n }\n // eslint-disable-next-line no-empty\n } catch (e) {\n console.log(e)\n }\n _raiseCastFail(peer, 'peer')\n}\n*/\n\n/**\n Convert the given peer into its marked ID by default.\n\n This \"mark\" comes from the \"bot api\" format, and with it the peer type\n can be identified back. User ID is left unmodified, chat ID is negated,\n and channel ID is prefixed with -100:\n\n * ``userId``\n * ``-chatId``\n * ``-100channel_id``\n\n The original ID and the peer type class can be returned with\n a call to :meth:`resolve_id(marked_id)`.\n * @param peer\n * @param addMark\n */\n/* CONTEST\nfunction getPeerId(peer, addMark = true) {\n // First we assert it's a Peer TLObject, or early return for integers\n if (typeof peer == 'number') {\n return addMark ? peer : resolveId(peer)[0]\n }\n\n // Tell the user to use their client to resolve InputPeerSelf if we got one\n if (peer instanceof constructors.InputPeerSelf) {\n _raiseCastFail(peer, 'int (you might want to use client.get_peer_id)')\n }\n\n try {\n peer = getPeer(peer)\n } catch (e) {\n _raiseCastFail(peer, 'int')\n }\n if (peer instanceof constructors.PeerUser) {\n return peer.userId\n } else if (peer instanceof constructors.PeerChat) {\n // Check in case the user mixed things up to avoid blowing up\n if (!(0 < peer.chatId <= 0x7fffffff)) {\n peer.chatId = resolveId(peer.chatId)[0]\n }\n\n return addMark ? -(peer.chatId) : peer.chatId\n } else { // if (peer instanceof constructors.PeerChannel)\n // Check in case the user mixed things up to avoid blowing up\n if (!(0 < peer.channelId <= 0x7fffffff)) {\n peer.channelId = resolveId(peer.channelId)[0]\n }\n if (!addMark) {\n return peer.channelId\n }\n // Concat -100 through math tricks, .to_supergroup() on\n // Madeline IDs will be strictly positive -> log works.\n try {\n return -(peer.channelId + Math.pow(10, Math.floor(Math.log10(peer.channelId) + 3)))\n } catch (e) {\n throw new Error('Cannot get marked ID of a channel unless its ID is strictly positive')\n }\n }\n}\n*/\n/**\n * Given a marked ID, returns the original ID and its :tl:`Peer` type.\n * @param markedId\n */\n/* CONTEST\nfunction resolveId(markedId) {\n if (markedId >= 0) {\n return [markedId, constructors.PeerUser]\n }\n\n // There have been report of chat IDs being 10000xyz, which means their\n // marked version is -10000xyz, which in turn looks like a channel but\n // it becomes 00xyz (= xyz). Hence, we must assert that there are only\n // two zeroes.\n const m = markedId.toString()\n .match(/-100([^0]\\d*)/)\n if (m) {\n return [parseInt(m[1]), constructors.PeerChannel]\n }\n return [-markedId, constructors.PeerChat]\n}\n*/\n\n/**\n * returns an entity pair\n * @param entityId\n * @param entities\n * @param cache\n * @param getInputPeer\n * @returns {{inputEntity: *, entity: *}}\n * @private\n */\n\n/* CONTEST\n\nfunction _getEntityPair(entityId, entities, cache, getInputPeer = getInputPeer) {\n const entity = entities.get(entityId)\n let inputEntity = cache[entityId]\n if (inputEntity === undefined) {\n try {\n inputEntity = getInputPeer(inputEntity)\n } catch (e) {\n inputEntity = null\n }\n }\n return {\n entity,\n inputEntity\n }\n}\n*/\n\nfunction getMessageId(message) {\n if (message === undefined) {\n return undefined;\n }\n if (typeof message === 'number') {\n return message;\n }\n if (message.SUBCLASS_OF_ID === 0x790009e3) { // crc32(b'Message')\n return message.id;\n }\n throw new Error(`Invalid message type: ${message.constructor.name}`);\n}\n\n\n/**\n Parses the given username or channel access hash, given\n a string, username or URL. Returns a tuple consisting of\n both the stripped, lowercase username and whether it is\n a joinchat/ hash (in which case is not lowercase'd).\n\n Returns ``(None, False)`` if the ``username`` or link is not valid.\n\n * @param username {string}\n */\n\n/* CONTEST\n\nfunction parseUsername(username) {\n username = username.trim()\n const m = username.match(USERNAME_RE) || username.match(TG_JOIN_RE)\n if (m) {\n username = username.replace(m[0], '')\n if (m[1]) {\n return {\n username: username,\n isInvite: true\n }\n } else {\n username = rtrim(username, '/')\n }\n }\n if (username.match(VALID_USERNAME_RE)) {\n return {\n username: username.toLowerCase(),\n isInvite: false\n }\n } else {\n return {\n username: null,\n isInvite: false\n }\n }\n}\n\nfunction rtrim(s, mask) {\n while (~mask.indexOf(s[s.length - 1])) {\n s = s.slice(0, -1)\n }\n return s\n}\n\n */\n\n/**\n * Gets the display name for the given :tl:`User`,\n :tl:`Chat` or :tl:`Channel`. Returns an empty string otherwise\n * @param entity\n */\nfunction getDisplayName(entity) {\n if (entity instanceof constructors.User) {\n if (entity.lastName && entity.firstName) {\n return `${entity.firstName} ${entity.lastName}`;\n } else if (entity.firstName) {\n return entity.firstName;\n } else if (entity.lastName) {\n return entity.lastName;\n } else {\n return '';\n }\n } else if (entity instanceof constructors.Chat || entity instanceof constructors.Channel) {\n return entity.title;\n }\n return '';\n}\n\n/**\n * check if a given item is an array like or not\n * @param item\n * @returns {boolean}\n */\n\n/* CONTEST\nDuplicate ?\nfunction isListLike(item) {\n return (\n Array.isArray(item) ||\n (!!item &&\n typeof item === 'object' &&\n typeof (item.length) === 'number' &&\n (item.length === 0 ||\n (item.length > 0 &&\n (item.length - 1) in item)\n )\n )\n )\n}\n*/\n/**\n * Returns the appropriate DC based on the id\n * @param dcId the id of the DC.\n * @param downloadDC whether to use -1 DCs or not\n * (These only support downloading/uploading and not creating a new AUTH key)\n * @return {{port: number, ipAddress: string, id: number}}\n */\nfunction getDC(dcId, downloadDC = false) {\n // TODO Move to external config\n switch (dcId) {\n case 1:\n return {\n id: 1,\n ipAddress: `zws1${downloadDC ? '-1' : ''}.web.telegram.org`,\n port: 443,\n };\n case 2:\n return {\n id: 2,\n ipAddress: `zws2${downloadDC ? '-1' : ''}.web.telegram.org`,\n port: 443,\n };\n case 3:\n return {\n id: 3,\n ipAddress: `zws3${downloadDC ? '-1' : ''}.web.telegram.org`,\n port: 443,\n };\n case 4:\n return {\n id: 4,\n ipAddress: `zws4${downloadDC ? '-1' : ''}.web.telegram.org`,\n port: 443,\n };\n case 5:\n return {\n id: 5,\n ipAddress: `zws5${downloadDC ? '-1' : ''}.web.telegram.org`,\n port: 443,\n };\n default:\n throw new Error(`Cannot find the DC with the ID of ${dcId}`);\n }\n // TODO chose based on current connection method\n /*\n if (!this._config) {\n this._config = await this.invoke(new requests.help.GetConfig())\n }\n if (cdn && !this._cdnConfig) {\n this._cdnConfig = await this.invoke(new requests.help.GetCdnConfig())\n for (const pk of this._cdnConfig.publicKeys) {\n addKey(pk.publicKey)\n }\n }\n for (const DC of this._config.dcOptions) {\n if (DC.id === dcId && Boolean(DC.ipv6) === this._useIPV6 && Boolean(DC.cdn) === cdn) {\n return DC\n }\n } */\n}\n\nmodule.exports = {\n getMessageId,\n // _getEntityPair,\n // getInputMessage,\n // getInputDialog,\n // getInputUser,\n // getInputChannel,\n getInputPeer,\n // parsePhone,\n // parseUsername,\n // getPeer,\n // getPeerId,\n getDisplayName,\n // resolveId,\n // isListLike,\n getAppropriatedPartSize,\n // getInputLocation,\n strippedPhotoToJpg,\n getDC,\n};\n","module.exports = '0.0.2';\n","import TelegramClient from './TelegramClient';\n// eslint-disable-next-line import/no-named-default\nimport { default as Api } from '../tl/api';\nimport { generateRandomBytes } from '../Helpers';\nimport { computeCheck, computeDigest } from '../Password';\nimport errors from '../errors';\n\nexport interface TwoFaParams {\n isCheckPassword?: boolean;\n currentPassword?: string;\n newPassword?: string;\n hint?: string;\n email?: string;\n emailCodeCallback?: (length: number) => Promise;\n onEmailCodeError?: (err: Error) => void;\n}\n\n/**\n * Changes the 2FA settings of the logged in user.\n Note that this method may be *incredibly* slow depending on the\n prime numbers that must be used during the process to make sure\n that everything is safe.\n\n Has no effect if both current and new password are omitted.\n\n * @param client: The telegram client instance\n * @param isCheckPassword: Must be ``true`` if you want to check the current password\n * @param currentPassword: The current password, to authorize changing to ``new_password``.\n Must be set if changing existing 2FA settings.\n Must **not** be set if 2FA is currently disabled.\n Passing this by itself will remove 2FA (if correct).\n * @param newPassword: The password to set as 2FA.\n If 2FA was already enabled, ``currentPassword`` **must** be set.\n Leaving this blank or `undefined` will remove the password.\n * @param hint: Hint to be displayed by Telegram when it asks for 2FA.\n Must be set when changing or creating a new password.\n Has no effect if ``newPassword`` is not set.\n * @param email: Recovery and verification email. If present, you must also\n set `emailCodeCallback`, else it raises an Error.\n * @param emailCodeCallback: If an email is provided, a callback that returns the code sent\n to it must also be set. This callback may be asynchronous.\n It should return a string with the code. The length of the\n code will be passed to the callback as an input parameter.\n\n If the callback returns an invalid code, it will raise an rpc error with the message\n ``CODE_INVALID``\n\n * @returns Promise\n * @throws this method can throw:\n \"PASSWORD_HASH_INVALID\" if you entered a wrong password (or set it to undefined).\n \"EMAIL_INVALID\" if the entered email is wrong\n \"EMAIL_HASH_EXPIRED\" if the user took too long to verify their email\n */\nexport async function updateTwoFaSettings(\n client: TelegramClient,\n {\n isCheckPassword,\n currentPassword,\n newPassword,\n hint = '',\n email,\n emailCodeCallback,\n onEmailCodeError,\n }: TwoFaParams,\n) {\n if (!newPassword && !currentPassword) {\n throw new Error('Neither `currentPassword` nor `newPassword` is present');\n }\n\n if (email && !(emailCodeCallback && onEmailCodeError)) {\n throw new Error('`email` present without `emailCodeCallback` and `onEmailCodeError`');\n }\n\n const pwd = await client.invoke(new Api.account.GetPassword());\n\n if (!(pwd.newAlgo instanceof Api.PasswordKdfAlgoUnknown)) {\n pwd.newAlgo.salt1 = Buffer.concat([pwd.newAlgo.salt1, generateRandomBytes(32)]);\n }\n if (!pwd.hasPassword && currentPassword) {\n currentPassword = undefined;\n }\n\n const password = currentPassword ? await computeCheck(pwd, currentPassword!) : new Api.InputCheckPasswordEmpty();\n\n if (isCheckPassword) {\n await client.invoke(new Api.auth.CheckPassword({ password }));\n return;\n }\n\n try {\n await client.invoke(new Api.account.UpdatePasswordSettings({\n password,\n newSettings: new Api.account.PasswordInputSettings({\n newAlgo: pwd.newAlgo,\n newPasswordHash: newPassword ? await computeDigest(pwd.newAlgo, newPassword) : Buffer.alloc(0),\n hint,\n email,\n // not explained what it does and it seems to always be set to empty in tdesktop\n newSecureSettings: undefined,\n }),\n }));\n } catch (e) {\n if (e instanceof errors.EmailUnconfirmedError) {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n try {\n const code = await emailCodeCallback!(e.codeLength);\n\n if (!code) {\n throw new Error('Code is empty');\n }\n\n await client.invoke(new Api.account.ConfirmPasswordEmail({ code }));\n break;\n } catch (err) {\n onEmailCodeError!(err);\n }\n }\n } else {\n throw e;\n }\n }\n}\n","const os = require('os');\nconst Logger = require('../extensions/Logger');\nconst { sleep } = require('../Helpers');\nconst errors = require('../errors');\nconst MemorySession = require('../sessions/Memory');\nconst Helpers = require('../Helpers');\nconst utils = require('../Utils');\nconst Session = require('../sessions/Abstract');\nconst { LAYER } = require('../tl/AllTLObjects');\nconst {\n constructors,\n requests,\n} = require('../tl');\nconst MTProtoSender = require('../network/MTProtoSender');\nconst { ConnectionTCPObfuscated } = require('../network/connection/TCPObfuscated');\nconst {\n authFlow,\n checkAuthorization,\n} = require('./auth');\nconst { downloadFile } = require('./downloadFile');\nconst { uploadFile } = require('./uploadFile');\nconst { updateTwoFaSettings } = require('./2fa');\n\nconst DEFAULT_DC_ID = 2;\nconst WEBDOCUMENT_DC_ID = 4;\nconst DEFAULT_IPV4_IP = 'zws2.web.telegram.org';\nconst DEFAULT_IPV6_IP = '[2001:67c:4e8:f002::a]';\nconst EXPORTED_SENDER_RECONNECT_TIMEOUT = 1000; // 1 sec\nconst EXPORTED_SENDER_RELEASE_TIMEOUT = 30000; // 30 sec\nconst WEBDOCUMENT_REQUEST_PART_SIZE = 131072; // 128kb\n\nconst PING_INTERVAL = 3000; // 3 sec\nconst PING_TIMEOUT = 5000; // 5 sec\nconst PING_FAIL_ATTEMPTS = 3;\nconst PING_FAIL_INTERVAL = 100; // ms\nconst PING_DISCONNECT_DELAY = 60000; // 1 min\n\n// All types\nconst sizeTypes = ['w', 'y', 'd', 'x', 'c', 'm', 'b', 'a', 's'];\n\nclass TelegramClient {\n static DEFAULT_OPTIONS = {\n connection: ConnectionTCPObfuscated,\n useIPV6: false,\n proxy: undefined,\n timeout: 10,\n requestRetries: 5,\n connectionRetries: Infinity,\n retryDelay: 1000,\n autoReconnect: true,\n sequentialUpdates: false,\n floodSleepLimit: 60,\n deviceModel: undefined,\n systemVersion: undefined,\n appVersion: undefined,\n langCode: 'en',\n systemLangCode: 'en',\n baseLogger: 'gramjs',\n useWSS: false,\n additionalDcsDisabled: false,\n testServers: false,\n };\n\n /**\n *\n * @param session {StringSession|LocalStorageSession}\n * @param apiId\n * @param apiHash\n * @param opts\n */\n constructor(session, apiId, apiHash, opts = TelegramClient.DEFAULT_OPTIONS) {\n if (!apiId || !apiHash) {\n throw Error('Your API ID or Hash are invalid. Please read \"Requirements\" on README.md');\n }\n const args = { ...TelegramClient.DEFAULT_OPTIONS, ...opts };\n this.apiId = apiId;\n this.apiHash = apiHash;\n this._useIPV6 = args.useIPV6;\n // this._entityCache = new Set()\n if (typeof args.baseLogger === 'string') {\n this._log = new Logger();\n } else {\n this._log = args.baseLogger;\n }\n // Determine what session we will use\n if (typeof session === 'string' || !session) {\n try {\n throw new Error('not implemented');\n } catch (e) {\n session = new MemorySession();\n }\n } else if (!(session instanceof Session)) {\n throw new Error('The given session must be str or a session instance');\n }\n\n this.floodSleepLimit = args.floodSleepLimit;\n this._eventBuilders = [];\n\n this._phoneCodeHash = {};\n this.session = session;\n // this._entityCache = EntityCache();\n this.apiId = parseInt(apiId, 10);\n this.apiHash = apiHash;\n\n this._requestRetries = args.requestRetries;\n this._connectionRetries = args.connectionRetries;\n this._retryDelay = args.retryDelay || 0;\n if (args.proxy) {\n this._log.warn('proxies are not supported');\n }\n this._proxy = args.proxy;\n this._timeout = args.timeout;\n this._autoReconnect = args.autoReconnect;\n\n this._connection = args.connection;\n // TODO add proxy support\n\n this._floodWaitedRequests = {};\n\n this._initWith = (x) => {\n return new requests.InvokeWithLayer({\n layer: LAYER,\n query: new requests.InitConnection({\n apiId: this.apiId,\n deviceModel: args.deviceModel || os.type()\n .toString() || 'Unknown',\n systemVersion: args.systemVersion || os.release()\n .toString() || '1.0',\n appVersion: args.appVersion || '1.0',\n langCode: args.langCode,\n langPack: '', // this should be left empty.\n systemLangCode: args.systemLangCode,\n query: x,\n proxy: undefined, // no proxies yet.\n }),\n });\n };\n\n this._args = args;\n // These will be set later\n this._config = undefined;\n this.phoneCodeHashes = [];\n this._exportedSenderPromises = {};\n this._exportedSenderReleaseTimeouts = {};\n this._additionalDcsDisabled = args.additionalDcsDisabled;\n this._loopStarted = false;\n this._reconnecting = false;\n this._destroyed = false;\n }\n\n // region Connecting\n\n /**\n * Connects to the Telegram servers, executing authentication if required.\n * Note that authenticating to the Telegram servers is not the same as authenticating\n * the app, which requires to send a code first.\n * @returns {Promise}\n */\n async connect() {\n await this._initSession();\n\n if (this._sender === undefined) {\n // only init sender once to avoid multiple loops.\n this._sender = new MTProtoSender(this.session.getAuthKey(), {\n logger: this._log,\n dcId: this.session.dcId,\n retries: this._connectionRetries,\n delay: this._retryDelay,\n autoReconnect: this._autoReconnect,\n connectTimeout: this._timeout,\n authKeyCallback: this._authKeyCallback.bind(this),\n updateCallback: this._handleUpdate.bind(this),\n isMainSender: true,\n });\n }\n // set defaults vars\n this._sender.userDisconnected = false;\n this._sender._user_connected = false;\n this._sender._reconnecting = false;\n this._sender._disconnected = true;\n\n const connection = new this._connection(\n this.session.serverAddress, this.session.port, this.session.dcId, this._log, this._args.testServers,\n );\n\n const newConnection = await this._sender.connect(connection);\n if (!newConnection) {\n // we're already connected so no need to reset auth key.\n if (!this._loopStarted) {\n this._updateLoop();\n this._loopStarted = true;\n }\n return;\n }\n\n this.session.setAuthKey(this._sender.authKey);\n await this._sender.send(this._initWith(\n new requests.help.GetConfig({}),\n ));\n\n if (!this._loopStarted) {\n this._updateLoop();\n this._loopStarted = true;\n }\n this._reconnecting = false;\n }\n\n async _initSession() {\n await this.session.load();\n\n if (!this.session.serverAddress || (this.session.serverAddress.includes(':') !== this._useIPV6)) {\n this.session.setDC(DEFAULT_DC_ID, this._useIPV6\n ? DEFAULT_IPV6_IP : DEFAULT_IPV4_IP, this._args.useWSS ? 443 : 80);\n }\n }\n\n async _updateLoop() {\n while (!this._destroyed) {\n await Helpers.sleep(PING_INTERVAL);\n if (this._reconnecting) {\n continue;\n }\n\n try {\n await attempts(() => {\n return timeout(this._sender.send(new requests.PingDelayDisconnect({\n pingId: Helpers.getRandomInt(Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER),\n disconnectDelay: PING_DISCONNECT_DELAY,\n })), PING_TIMEOUT);\n }, PING_FAIL_ATTEMPTS, PING_FAIL_INTERVAL);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n if (this._reconnecting) {\n continue;\n }\n\n await this.disconnect();\n await this.connect();\n }\n\n // We need to send some content-related request at least hourly\n // for Telegram to keep delivering updates, otherwise they will\n // just stop even if we're connected. Do so every 30 minutes.\n\n // TODO Call getDifference instead since it's more relevant\n if (new Date().getTime() - this._lastRequest > 30 * 60 * 1000) {\n try {\n await this.invoke(new requests.updates.GetState());\n } catch (e) {\n // we don't care about errors here\n }\n }\n }\n await this.disconnect();\n }\n\n /**\n * Disconnects from the Telegram server\n * @returns {Promise}\n */\n async disconnect() {\n if (this._sender) {\n await this._sender.disconnect();\n }\n\n await Promise.all(\n Object.values(this._exportedSenderPromises)\n .map((promise) => {\n return promise && promise.then((sender) => {\n if (sender) {\n return sender.disconnect();\n }\n return undefined;\n });\n }),\n );\n\n this._exportedSenderPromises = {};\n }\n\n /**\n * Disconnects all senders and removes all handlers\n * @returns {Promise}\n */\n async destroy() {\n this._destroyed = true;\n\n try {\n await this.disconnect();\n } catch (err) {\n // Do nothing\n }\n\n this.session.delete();\n this._eventBuilders = [];\n }\n\n async _switchDC(newDc) {\n this._log.info(`Reconnecting to new data center ${newDc}`);\n const DC = utils.getDC(newDc);\n this.session.setDC(newDc, DC.ipAddress, DC.port);\n // authKey's are associated with a server, which has now changed\n // so it's not valid anymore. Set to None to force recreating it.\n await this._sender.authKey.setKey(undefined);\n this.session.setAuthKey(undefined);\n this._reconnecting = true;\n await this.disconnect();\n return this.connect();\n }\n\n _authKeyCallback(authKey, dcId) {\n this.session.setAuthKey(authKey, dcId);\n }\n\n // endregion\n // export region\n\n async _cleanupExportedSender(dcId) {\n if (this.session.dcId !== dcId) {\n this.session.setAuthKey(undefined, dcId);\n }\n const sender = await this._exportedSenderPromises[dcId];\n this._exportedSenderPromises[dcId] = undefined;\n await sender.disconnect();\n }\n\n async _connectSender(sender, dcId) {\n // if we don't already have an auth key we want to use normal DCs not -1\n const dc = utils.getDC(dcId, !!sender.authKey.getKey());\n\n while (true) {\n try {\n await sender.connect(new this._connection(\n dc.ipAddress,\n dc.port,\n dcId,\n this._log,\n this._args.testServers,\n ));\n\n if (this.session.dcId !== dcId && !sender._authenticated) {\n this._log.info(`Exporting authorization for data center ${dc.ipAddress}`);\n const auth = await this.invoke(new requests.auth.ExportAuthorization({ dcId }));\n const req = this._initWith(new requests.auth.ImportAuthorization({\n id: auth.id,\n bytes: auth.bytes,\n }));\n await sender.send(req);\n sender._authenticated = true;\n }\n sender.dcId = dcId;\n sender.userDisconnected = false;\n\n return sender;\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(err);\n\n await Helpers.sleep(1000);\n await sender.disconnect();\n }\n }\n }\n\n async _borrowExportedSender(dcId, shouldReconnect, existingSender) {\n if (this._additionalDcsDisabled) {\n return undefined;\n }\n\n if (!this._exportedSenderPromises[dcId] || shouldReconnect) {\n this._exportedSenderPromises[dcId] = this._connectSender(\n existingSender || this._createExportedSender(dcId),\n dcId,\n );\n }\n\n let sender;\n try {\n sender = await this._exportedSenderPromises[dcId];\n\n if (!sender.isConnected()) {\n if (sender.isConnecting) {\n await Helpers.sleep(EXPORTED_SENDER_RECONNECT_TIMEOUT);\n return this._borrowExportedSender(dcId, false, sender);\n } else {\n return this._borrowExportedSender(dcId, true, sender);\n }\n }\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(err);\n\n return this._borrowExportedSender(dcId, true);\n }\n\n if (this._exportedSenderReleaseTimeouts[dcId]) {\n clearTimeout(this._exportedSenderReleaseTimeouts[dcId]);\n this._exportedSenderReleaseTimeouts[dcId] = undefined;\n }\n\n this._exportedSenderReleaseTimeouts[dcId] = setTimeout(() => {\n this._exportedSenderReleaseTimeouts[dcId] = undefined;\n sender.disconnect();\n }, EXPORTED_SENDER_RELEASE_TIMEOUT);\n\n return sender;\n }\n\n _createExportedSender(dcId) {\n return new MTProtoSender(this.session.getAuthKey(dcId), {\n logger: this._log,\n dcId,\n retries: this._connectionRetries,\n delay: this._retryDelay,\n autoReconnect: this._autoReconnect,\n connectTimeout: this._timeout,\n authKeyCallback: this._authKeyCallback.bind(this),\n isMainSender: dcId === this.session.dcId,\n onConnectionBreak: this._cleanupExportedSender.bind(this),\n });\n }\n\n getSender(dcId) {\n return dcId ? this._borrowExportedSender(dcId) : Promise.resolve(this._sender);\n }\n\n // end region\n\n // download region\n\n /**\n * Complete flow to download a file.\n * @param inputLocation {constructors.InputFileLocation}\n * @param [args[partSizeKb] {number}]\n * @param [args[fileSize] {number}]\n * @param [args[progressCallback] {Function}]\n * @param [args[start] {number}]\n * @param [args[end] {number}]\n * @param [args[dcId] {number}]\n * @param [args[workers] {number}]\n * @returns {Promise}\n */\n downloadFile(inputLocation, args = {}) {\n return downloadFile(this, inputLocation, args);\n }\n\n downloadMedia(messageOrMedia, args) {\n let media;\n if (messageOrMedia instanceof constructors.Message) {\n media = messageOrMedia.media;\n } else {\n media = messageOrMedia;\n }\n if (typeof media === 'string') {\n throw new Error('not implemented');\n }\n\n if (media instanceof constructors.MessageMediaWebPage) {\n if (media.webpage instanceof constructors.WebPage) {\n media = media.webpage.document || media.webpage.photo;\n }\n }\n if (media instanceof constructors.MessageMediaPhoto || media instanceof constructors.Photo) {\n return this._downloadPhoto(media, args);\n } else if (media instanceof constructors.MessageMediaDocument || media instanceof constructors.Document) {\n return this._downloadDocument(media, args);\n } else if (media instanceof constructors.MessageMediaContact) {\n return this._downloadContact(media, args);\n } else if (media instanceof constructors.WebDocument || media instanceof constructors.WebDocumentNoProxy) {\n return this._downloadWebDocument(media, args);\n }\n return undefined;\n }\n\n downloadProfilePhoto(entity, isBig = false) {\n // ('User', 'Chat', 'UserFull', 'ChatFull')\n const ENTITIES = [0x2da17977, 0xc5af5d94, 0x1f4661b9, 0xd49a2697];\n // ('InputPeer', 'InputUser', 'InputChannel')\n // const INPUTS = [0xc91c90b6, 0xe669bf46, 0x40f202fd]\n // Todo account for input methods\n const sizeType = isBig ? 'x' : 'm';\n let photo;\n if (!(ENTITIES.includes(entity.SUBCLASS_OF_ID))) {\n photo = entity;\n } else {\n if (!entity.photo) {\n // Special case: may be a ChatFull with photo:Photo\n if (!entity.chatPhoto) {\n return undefined;\n }\n\n return this._downloadPhoto(\n entity.chatPhoto, { sizeType },\n );\n }\n photo = entity.photo;\n }\n\n let dcId;\n let loc;\n if (photo instanceof constructors.UserProfilePhoto || photo instanceof constructors.ChatPhoto) {\n dcId = photo.dcId;\n loc = new constructors.InputPeerPhotoFileLocation({\n peer: utils.getInputPeer(entity),\n photoId: photo.photoId,\n big: isBig,\n });\n } else {\n // It doesn't make any sense to check if `photo` can be used\n // as input location, because then this method would be able\n // to \"download the profile photo of a message\", i.e. its\n // media which should be done with `download_media` instead.\n return undefined;\n }\n return this.downloadFile(loc, {\n dcId,\n });\n }\n\n downloadStickerSetThumb(stickerSet) {\n if (!stickerSet.thumbs || !stickerSet.thumbs.length) {\n return undefined;\n }\n\n const { thumbVersion } = stickerSet;\n return this.downloadFile(\n new constructors.InputStickerSetThumb({\n stickerset: new constructors.InputStickerSetID({\n id: stickerSet.id,\n accessHash: stickerSet.accessHash,\n }),\n thumbVersion,\n }),\n { dcId: stickerSet.thumbDcId },\n );\n }\n\n _pickFileSize(sizes, sizeType) {\n if (!sizeType || !sizes || !sizes.length) {\n return undefined;\n }\n const indexOfSize = sizeTypes.indexOf(sizeType);\n let size;\n for (let i = indexOfSize; i < sizeTypes.length; i++) {\n size = sizes.find((s) => s.type === sizeTypes[i]);\n if (size) {\n return size;\n }\n }\n return undefined;\n }\n\n _downloadCachedPhotoSize(size) {\n // No need to download anything, simply write the bytes\n let data;\n if (size instanceof constructors.PhotoStrippedSize) {\n data = utils.strippedPhotoToJpg(size.bytes);\n } else {\n data = size.bytes;\n }\n return data;\n }\n\n _downloadPhoto(photo, args) {\n if (photo instanceof constructors.MessageMediaPhoto) {\n photo = photo.photo;\n }\n if (!(photo instanceof constructors.Photo)) {\n return undefined;\n }\n const size = this._pickFileSize(photo.sizes, args.sizeType);\n if (!size || (size instanceof constructors.PhotoSizeEmpty)) {\n return undefined;\n }\n\n if (size instanceof constructors.PhotoCachedSize || size instanceof constructors.PhotoStrippedSize) {\n return this._downloadCachedPhotoSize(size);\n }\n return this.downloadFile(\n new constructors.InputPhotoFileLocation({\n id: photo.id,\n accessHash: photo.accessHash,\n fileReference: photo.fileReference,\n thumbSize: size.type,\n }),\n {\n dcId: photo.dcId,\n fileSize: size.size,\n progressCallback: args.progressCallback,\n },\n );\n }\n\n _downloadDocument(doc, args) {\n if (doc instanceof constructors.MessageMediaDocument) {\n doc = doc.document;\n }\n if (!(doc instanceof constructors.Document)) {\n return undefined;\n }\n\n let size;\n if (args.sizeType) {\n size = doc.thumbs ? this._pickFileSize(doc.thumbs, args.sizeType) : undefined;\n if (!size && doc.mimeType.startsWith('video/')) {\n return undefined;\n }\n\n if (size && (size instanceof constructors.PhotoCachedSize\n || size instanceof constructors.PhotoStrippedSize)) {\n return this._downloadCachedPhotoSize(size);\n }\n }\n\n return this.downloadFile(\n new constructors.InputDocumentFileLocation({\n id: doc.id,\n accessHash: doc.accessHash,\n fileReference: doc.fileReference,\n thumbSize: size ? size.type : '',\n }),\n {\n fileSize: size ? size.size : doc.size,\n progressCallback: args.progressCallback,\n start: args.start,\n end: args.end,\n dcId: doc.dcId,\n workers: args.workers,\n },\n );\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _downloadContact(media, args) {\n throw new Error('not implemented');\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async _downloadWebDocument(media) {\n try {\n const buff = [];\n let offset = 0;\n while (true) {\n const downloaded = new requests.upload.GetWebFile({\n location: new constructors.InputWebFileLocation({\n url: media.url,\n accessHash: media.accessHash,\n }),\n offset,\n limit: WEBDOCUMENT_REQUEST_PART_SIZE,\n });\n const sender = await this._borrowExportedSender(WEBDOCUMENT_DC_ID);\n const res = await sender.send(downloaded);\n offset += 131072;\n if (res.bytes.length) {\n buff.push(res.bytes);\n if (res.bytes.length < WEBDOCUMENT_REQUEST_PART_SIZE) {\n break;\n }\n } else {\n break;\n }\n }\n return Buffer.concat(buff);\n } catch (e) {\n // the file is no longer saved in telegram's cache.\n if (e.message === 'WEBFILE_NOT_AVAILABLE') {\n return Buffer.alloc(0);\n } else {\n throw e;\n }\n }\n }\n\n // region Invoking Telegram request\n /**\n * Invokes a MTProtoRequest (sends and receives it) and returns its result\n * @param request\n * @returns {Promise}\n */\n\n async invoke(request) {\n if (request.classType !== 'request') {\n throw new Error('You can only invoke MTProtoRequests');\n }\n // This causes issues for now because not enough utils\n // await request.resolve(this, utils)\n\n this._lastRequest = new Date().getTime();\n let attempt = 0;\n for (attempt = 0; attempt < this._requestRetries; attempt++) {\n const promise = this._sender.sendWithInvokeSupport(request);\n try {\n const result = await promise.promise;\n return result;\n } catch (e) {\n if (e instanceof errors.ServerError || e.message === 'RPC_CALL_FAIL'\n || e.message === 'RPC_MCGET_FAIL') {\n this._log.warn(`Telegram is having internal issues ${e.constructor.name}`);\n await sleep(2000);\n } else if (e instanceof errors.FloodWaitError || e instanceof errors.FloodTestPhoneWaitError) {\n if (e.seconds <= this.floodSleepLimit) {\n this._log.info(`Sleeping for ${e.seconds}s on flood wait`);\n await sleep(e.seconds * 1000);\n } else {\n throw e;\n }\n } else if (e instanceof errors.PhoneMigrateError || e instanceof errors.NetworkMigrateError\n || e instanceof errors.UserMigrateError) {\n this._log.info(`Phone migrated to ${e.newDc}`);\n const shouldRaise = e instanceof errors.PhoneMigrateError\n || e instanceof errors.NetworkMigrateError;\n if (shouldRaise && await checkAuthorization(this)) {\n throw e;\n }\n await this._switchDC(e.newDc);\n } else if (e instanceof errors.MsgWaitError) {\n // we need to resend this after the old one was confirmed.\n await promise.isReady();\n } else {\n throw e;\n }\n }\n }\n throw new Error(`Request was unsuccessful ${attempt} time(s)`);\n }\n\n async getMe() {\n try {\n return (await this.invoke(new requests.users\n .GetUsers({ id: [new constructors.InputUserSelf()] })))[0];\n } catch (e) {\n this._log.warn('error while getting me');\n this._log.warn(e);\n }\n return undefined;\n }\n\n async start(authParams) {\n if (!this.isConnected()) {\n await this.connect();\n }\n\n if (await checkAuthorization(this)) {\n return;\n }\n\n const apiCredentials = {\n apiId: this.apiId,\n apiHash: this.apiHash,\n };\n\n await authFlow(this, apiCredentials, authParams);\n }\n\n uploadFile(fileParams) {\n return uploadFile(this, fileParams);\n }\n\n updateTwoFaSettings(params) {\n return updateTwoFaSettings(this, params);\n }\n\n // event region\n addEventHandler(callback, event) {\n this._eventBuilders.push([event, callback]);\n }\n\n _handleUpdate(update) {\n // this.session.processEntities(update)\n // this._entityCache.add(update)\n\n if (update instanceof constructors.Updates || update instanceof constructors.UpdatesCombined) {\n // TODO deal with entities\n const entities = [];\n for (const x of [...update.users, ...update.chats]) {\n entities.push(x);\n }\n for (const u of update.updates) {\n this._processUpdate(u, update.updates, entities);\n }\n } else if (update instanceof constructors.UpdateShort) {\n this._processUpdate(update.update, undefined);\n } else {\n this._processUpdate(update, undefined);\n }\n // TODO add caching\n // this._stateCache.update(update)\n }\n\n _processUpdate(update, others, entities) {\n update._entities = entities || [];\n const args = {\n update,\n others,\n };\n this._dispatchUpdate(args);\n }\n\n // endregion\n\n // region private methods\n\n /**\n Gets a full entity from the given string, which may be a phone or\n a username, and processes all the found entities on the session.\n The string may also be a user link, or a channel/chat invite link.\n\n This method has the side effect of adding the found users to the\n session database, so it can be queried later without API calls,\n if this option is enabled on the session.\n\n Returns the found entity, or raises TypeError if not found.\n * @param string {string}\n * @returns {Promise}\n * @private\n */\n /* CONTEST\n async _getEntityFromString(string) {\n const phone = utils.parsePhone(string)\n if (phone) {\n try {\n for (const user of (await this.invoke(\n new requests.contacts.GetContacts(0))).users) {\n if (user.phone === phone) {\n return user\n }\n }\n } catch (e) {\n if (e.message === 'BOT_METHOD_INVALID') {\n throw new Error('Cannot get entity by phone number as a ' +\n 'bot (try using integer IDs, not strings)')\n }\n throw e\n }\n } else if (['me', 'this'].includes(string.toLowerCase())) {\n return this.getMe()\n } else {\n const { username, isJoinChat } = utils.parseUsername(string)\n if (isJoinChat) {\n const invite = await this.invoke(new requests.messages.CheckChatInvite({\n 'hash': username,\n }))\n if (invite instanceof constructors.ChatInvite) {\n throw new Error('Cannot get entity from a channel (or group) ' +\n 'that you are not part of. Join the group and retry',\n )\n } else if (invite instanceof constructors.ChatInviteAlready) {\n return invite.chat\n }\n } else if (username) {\n try {\n const result = await this.invoke(\n new requests.contacts.ResolveUsername(username))\n const pid = utils.getPeerId(result.peer, false)\n if (result.peer instanceof constructors.PeerUser) {\n for (const x of result.users) {\n if (x.id === pid) {\n return x\n }\n }\n } else {\n for (const x of result.chats) {\n if (x.id === pid) {\n return x\n }\n }\n }\n } catch (e) {\n if (e.message === 'USERNAME_NOT_OCCUPIED') {\n throw new Error(`No user has \"${username}\" as username`)\n }\n throw e\n }\n }\n }\n throw new Error(`Cannot find any entity corresponding to \"${string}\"`)\n }\n */\n // endregion\n\n // users region\n /**\n Turns the given entity into its input entity version.\n\n Most requests use this kind of :tl:`InputPeer`, so this is the most\n suitable call to make for those cases. **Generally you should let the\n library do its job** and don't worry about getting the input entity\n first, but if you're going to use an entity often, consider making the\n call:\n\n Arguments\n entity (`str` | `int` | :tl:`Peer` | :tl:`InputPeer`):\n If a username or invite link is given, **the library will\n use the cache**. This means that it's possible to be using\n a username that *changed* or an old invite link (this only\n happens if an invite link for a small group chat is used\n after it was upgraded to a mega-group).\n\n If the username or ID from the invite link is not found in\n the cache, it will be fetched. The same rules apply to phone\n numbers (``'+34 123456789'``) from people in your contact list.\n\n If an exact name is given, it must be in the cache too. This\n is not reliable as different people can share the same name\n and which entity is returned is arbitrary, and should be used\n only for quick tests.\n\n If a positive integer ID is given, the entity will be searched\n in cached users, chats or channels, without making any call.\n\n If a negative integer ID is given, the entity will be searched\n exactly as either a chat (prefixed with ``-``) or as a channel\n (prefixed with ``-100``).\n\n If a :tl:`Peer` is given, it will be searched exactly in the\n cache as either a user, chat or channel.\n\n If the given object can be turned into an input entity directly,\n said operation will be done.\n\n Unsupported types will raise ``TypeError``.\n\n If the entity can't be found, ``ValueError`` will be raised.\n\n Returns\n :tl:`InputPeerUser`, :tl:`InputPeerChat` or :tl:`InputPeerChannel`\n or :tl:`InputPeerSelf` if the parameter is ``'me'`` or ``'self'``.\n\n If you need to get the ID of yourself, you should use\n `get_me` with ``input_peer=True``) instead.\n\n Example\n .. code-block:: python\n\n // If you're going to use \"username\" often in your code\n // (make a lot of calls), consider getting its input entity\n // once, and then using the \"user\" everywhere instead.\n user = await client.get_input_entity('username')\n\n // The same applies to IDs, chats or channels.\n chat = await client.get_input_entity(-123456789)\n\n * @param peer\n * @returns {Promise<>}\n */\n\n /* CONTEST\n async getInputEntity(peer) {\n // Short-circuit if the input parameter directly maps to an InputPeer\n try {\n return utils.getInputPeer(peer)\n // eslint-disable-next-line no-empty\n } catch (e) {\n }\n // Next in priority is having a peer (or its ID) cached in-memory\n try {\n // 0x2d45687 == crc32(b'Peer')\n if (typeof peer === 'number' || peer.SUBCLASS_OF_ID === 0x2d45687) {\n if (this._entityCache.has(peer)) {\n return this._entityCache[peer]\n }\n }\n // eslint-disable-next-line no-empty\n } catch (e) {\n }\n // Then come known strings that take precedence\n if (['me', 'this'].includes(peer)) {\n return new constructors.InputPeerSelf()\n }\n // No InputPeer, cached peer, or known string. Fetch from disk cache\n try {\n return this.session.getInputEntity(peer)\n // eslint-disable-next-line no-empty\n } catch (e) {\n }\n // Only network left to try\n if (typeof peer === 'string') {\n return utils.getInputPeer(await this._getEntityFromString(peer))\n }\n // If we're a bot and the user has messaged us privately users.getUsers\n // will work with accessHash = 0. Similar for channels.getChannels.\n // If we're not a bot but the user is in our contacts, it seems to work\n // regardless. These are the only two special-cased requests.\n peer = utils.getPeer(peer)\n if (peer instanceof constructors.PeerUser) {\n const users = await this.invoke(new requests.users.GetUsers({\n id: [new constructors.InputUser({\n userId: peer.userId,\n accessHash: 0,\n })],\n }))\n if (users && !(users[0] instanceof constructors.UserEmpty)) {\n // If the user passed a valid ID they expect to work for\n // channels but would be valid for users, we get UserEmpty.\n // Avoid returning the invalid empty input peer for that.\n //\n // We *could* try to guess if it's a channel first, and if\n // it's not, work as a chat and try to validate it through\n // another request, but that becomes too much work.\n return utils.getInputPeer(users[0])\n }\n } else if (peer instanceof constructors.PeerChat) {\n return new constructors.InputPeerChat({\n chatId: peer.chatId,\n })\n } else if (peer instanceof constructors.PeerChannel) {\n try {\n const channels = await this.invoke(new requests.channels.GetChannels({\n id: [new constructors.InputChannel({\n channelId: peer.channelId,\n accessHash: 0,\n })],\n }))\n\n return utils.getInputPeer(channels.chats[0])\n // eslint-disable-next-line no-empty\n } catch (e) {\n console.log(e)\n }\n }\n throw new Error(`Could not find the input entity for ${peer.id || peer.channelId || peer.chatId || peer.userId}.\n Please read https://` +\n 'docs.telethon.dev/en/latest/concepts/entities.html to' +\n ' find out more details.',\n )\n }\n */\n async _dispatchUpdate(args = {\n update: undefined,\n others: undefined,\n channelId: undefined,\n ptsDate: undefined,\n }) {\n for (const [builder, callback] of this._eventBuilders) {\n const event = builder.build(args.update);\n if (event) {\n await callback(event);\n }\n }\n }\n\n isConnected() {\n if (this._sender) {\n if (this._sender.isConnected()) {\n return true;\n }\n }\n return false;\n }\n}\n\nfunction timeout(promise, ms) {\n return Promise.race([\n promise,\n Helpers.sleep(ms)\n .then(() => Promise.reject(new Error('TIMEOUT'))),\n ]);\n}\n\nasync function attempts(cb, times, pause) {\n for (let i = 0; i < times; i++) {\n try {\n // We need to `return await` here so it can be caught locally\n // eslint-disable-next-line no-return-await\n return await cb();\n } catch (err) {\n if (i === times - 1) {\n throw err;\n }\n\n await Helpers.sleep(pause);\n }\n }\n return undefined;\n}\n\nmodule.exports = TelegramClient;\n","// eslint-disable-next-line import/no-named-default\nimport { default as Api } from '../tl/api';\nimport TelegramClient from './TelegramClient';\nimport utils from '../Utils';\nimport { sleep } from '../Helpers';\nimport { computeCheck as computePasswordSrpCheck } from '../Password';\n\nexport interface UserAuthParams {\n phoneNumber: string | (() => Promise);\n phoneCode: (isCodeViaApp?: boolean) => Promise;\n password: (hint?: string) => Promise;\n firstAndLastNames: () => Promise<[string, string?]>;\n qrCode: (qrCode: { token: Buffer; expires: number }) => Promise;\n onError: (err: Error) => void;\n forceSMS?: boolean;\n initialMethod?: 'phoneNumber' | 'qrCode';\n}\n\nexport interface BotAuthParams {\n botAuthToken: string;\n}\n\ninterface ApiCredentials {\n apiId: number;\n apiHash: string;\n}\n\nconst DEFAULT_INITIAL_METHOD = 'phoneNumber';\nconst QR_CODE_TIMEOUT = 30000;\n\nexport async function authFlow(\n client: TelegramClient,\n apiCredentials: ApiCredentials,\n authParams: UserAuthParams | BotAuthParams,\n) {\n let me: Api.TypeUser;\n\n if ('botAuthToken' in authParams) {\n me = await signInBot(client, apiCredentials, authParams);\n } else {\n const { initialMethod = DEFAULT_INITIAL_METHOD } = authParams;\n\n if (initialMethod === 'phoneNumber') {\n me = await signInUser(client, apiCredentials, authParams);\n } else {\n me = await signInUserWithQrCode(client, apiCredentials, authParams);\n }\n }\n\n client._log.info('Signed in successfully as', utils.getDisplayName(me));\n}\n\nexport async function checkAuthorization(client: TelegramClient) {\n try {\n await client.invoke(new Api.updates.GetState());\n return true;\n } catch (e) {\n if (e.message === 'Disconnect') throw e;\n return false;\n }\n}\n\nasync function signInUser(\n client: TelegramClient, apiCredentials: ApiCredentials, authParams: UserAuthParams,\n): Promise {\n let phoneNumber;\n let phoneCodeHash;\n let isCodeViaApp = false;\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n try {\n if (typeof authParams.phoneNumber === 'function') {\n try {\n phoneNumber = await authParams.phoneNumber();\n } catch (err) {\n if (err.message === 'RESTART_AUTH_WITH_QR') {\n return signInUserWithQrCode(client, apiCredentials, authParams);\n }\n\n throw err;\n }\n } else {\n phoneNumber = authParams.phoneNumber;\n }\n const sendCodeResult = await sendCode(client, apiCredentials, phoneNumber, authParams.forceSMS);\n phoneCodeHash = sendCodeResult.phoneCodeHash;\n isCodeViaApp = sendCodeResult.isCodeViaApp;\n\n if (typeof phoneCodeHash !== 'string') {\n throw new Error('Failed to retrieve phone code hash');\n }\n\n break;\n } catch (err) {\n if (typeof authParams.phoneNumber !== 'function') {\n throw err;\n }\n\n authParams.onError(err);\n }\n }\n\n let phoneCode;\n let isRegistrationRequired = false;\n let termsOfService;\n\n // eslint-disable-next-line no-constant-condition\n while (1) {\n try {\n try {\n phoneCode = await authParams.phoneCode(isCodeViaApp);\n } catch (err) {\n // This is the support for changing phone number from the phone code screen.\n if (err.message === 'RESTART_AUTH') {\n return signInUser(client, apiCredentials, authParams);\n }\n }\n\n if (!phoneCode) {\n throw new Error('Code is empty');\n }\n\n // May raise PhoneCodeEmptyError, PhoneCodeExpiredError,\n // PhoneCodeHashEmptyError or PhoneCodeInvalidError.\n const result = await client.invoke(new Api.auth.SignIn({\n phoneNumber,\n phoneCodeHash,\n phoneCode,\n }));\n\n if (result instanceof Api.auth.AuthorizationSignUpRequired) {\n isRegistrationRequired = true;\n termsOfService = result.termsOfService;\n break;\n }\n\n return result.user;\n } catch (err) {\n if (err.message === 'SESSION_PASSWORD_NEEDED') {\n return signInWithPassword(client, apiCredentials, authParams);\n } else {\n authParams.onError(err);\n }\n }\n }\n\n if (isRegistrationRequired) {\n // eslint-disable-next-line no-constant-condition\n while (1) {\n try {\n const [firstName, lastName] = await authParams.firstAndLastNames();\n if (!firstName) {\n throw new Error('First name is required');\n }\n\n const { user } = await client.invoke(new Api.auth.SignUp({\n phoneNumber,\n phoneCodeHash,\n firstName,\n lastName,\n })) as Api.auth.Authorization;\n\n if (termsOfService) {\n // This is a violation of Telegram rules: the user should be presented with and accept TOS.\n await client.invoke(new Api.help.AcceptTermsOfService({ id: termsOfService.id }));\n }\n\n return user;\n } catch (err) {\n authParams.onError(err);\n }\n }\n }\n\n authParams.onError(new Error('Auth failed'));\n return signInUser(client, apiCredentials, authParams);\n}\n\nasync function signInUserWithQrCode(\n client: TelegramClient, apiCredentials: ApiCredentials, authParams: UserAuthParams,\n): Promise {\n let isScanningComplete = false;\n\n const inputPromise = (async () => {\n // eslint-disable-next-line no-constant-condition\n while (1) {\n if (isScanningComplete) {\n break;\n }\n\n const result = await client.invoke(new Api.auth.ExportLoginToken({\n apiId: Number(process.env.TELEGRAM_T_API_ID),\n apiHash: process.env.TELEGRAM_T_API_HASH,\n exceptIds: [],\n }));\n if (!(result instanceof Api.auth.LoginToken)) {\n throw new Error('Unexpected');\n }\n\n const { token, expires } = result;\n\n await Promise.race([\n authParams.qrCode({ token, expires }),\n sleep(QR_CODE_TIMEOUT),\n ]);\n }\n })();\n\n const updatePromise = new Promise((resolve) => {\n client.addEventHandler((update: Api.TypeUpdate) => {\n if (update instanceof Api.UpdateLoginToken) {\n resolve();\n }\n }, { build: (update: object) => update });\n });\n\n try {\n // Either we receive an update that QR is successfully scanned,\n // or we receive a rejection caused by user going back to the regular auth form\n await Promise.race([updatePromise, inputPromise]);\n } catch (err) {\n if (err.message === 'RESTART_AUTH') {\n return await signInUser(client, apiCredentials, authParams);\n }\n\n throw err;\n } finally {\n isScanningComplete = true;\n }\n\n try {\n const result2 = await client.invoke(new Api.auth.ExportLoginToken({\n apiId: Number(process.env.TELEGRAM_T_API_ID),\n apiHash: process.env.TELEGRAM_T_API_HASH,\n exceptIds: [],\n }));\n\n if (result2 instanceof Api.auth.LoginTokenSuccess && result2.authorization instanceof Api.auth.Authorization) {\n return result2.authorization.user;\n } else if (result2 instanceof Api.auth.LoginTokenMigrateTo) {\n await client._switchDC(result2.dcId);\n const migratedResult = await client.invoke(new Api.auth.ImportLoginToken({\n token: result2.token,\n }));\n\n if (migratedResult instanceof Api.auth.LoginTokenSuccess\n && migratedResult.authorization instanceof Api.auth.Authorization) {\n return migratedResult.authorization.user;\n }\n }\n } catch (err) {\n if (err.message === 'SESSION_PASSWORD_NEEDED') {\n return signInWithPassword(client, apiCredentials, authParams);\n }\n\n throw err;\n }\n\n // This is a workaround for TypeScript (never actually reached)\n // eslint-disable-next-line no-throw-literal\n throw undefined;\n}\n\nasync function sendCode(\n client: TelegramClient, apiCredentials: ApiCredentials, phoneNumber: string, forceSMS = false,\n): Promise<{\n phoneCodeHash: string;\n isCodeViaApp: boolean;\n }> {\n try {\n const { apiId, apiHash } = apiCredentials;\n const sendResult = await client.invoke(new Api.auth.SendCode({\n phoneNumber,\n apiId,\n apiHash,\n settings: new Api.CodeSettings(),\n }));\n\n // If we already sent a SMS, do not resend the phoneCode (hash may be empty)\n if (!forceSMS || (sendResult.type instanceof Api.auth.SentCodeTypeSms)) {\n return {\n phoneCodeHash: sendResult.phoneCodeHash,\n isCodeViaApp: sendResult.type instanceof Api.auth.SentCodeTypeApp,\n };\n }\n\n const resendResult = await client.invoke(new Api.auth.ResendCode({\n phoneNumber,\n phoneCodeHash: sendResult.phoneCodeHash,\n }));\n\n return {\n phoneCodeHash: resendResult.phoneCodeHash,\n isCodeViaApp: resendResult.type instanceof Api.auth.SentCodeTypeApp,\n };\n } catch (err) {\n if (err.message === 'AUTH_RESTART') {\n return sendCode(client, apiCredentials, phoneNumber, forceSMS);\n } else {\n throw err;\n }\n }\n}\n\nasync function signInWithPassword(\n client: TelegramClient, apiCredentials: ApiCredentials, authParams: UserAuthParams,\n): Promise {\n // eslint-disable-next-line no-constant-condition\n while (1) {\n try {\n const passwordSrpResult = await client.invoke(new Api.account.GetPassword());\n const password = await authParams.password(passwordSrpResult.hint);\n if (!password) {\n throw new Error('Password is empty');\n }\n\n const passwordSrpCheck = await computePasswordSrpCheck(passwordSrpResult, password);\n const { user } = await client.invoke(new Api.auth.CheckPassword({\n password: passwordSrpCheck,\n })) as Api.auth.Authorization;\n\n return user;\n } catch (err) {\n authParams.onError(err);\n }\n }\n\n // eslint-disable-next-line no-unreachable\n return undefined!; // Never reached (TypeScript fix)\n}\n\nasync function signInBot(client: TelegramClient, apiCredentials: ApiCredentials, authParams: BotAuthParams) {\n const { apiId, apiHash } = apiCredentials;\n const { botAuthToken } = authParams;\n\n const { user } = await client.invoke(new Api.auth.ImportBotAuthorization({\n apiId,\n apiHash,\n botAuthToken,\n })) as Api.auth.Authorization;\n\n return user;\n}\n","// eslint-disable-next-line import/no-named-default\nimport { default as Api } from '../tl/api';\nimport TelegramClient from './TelegramClient';\nimport { getAppropriatedPartSize } from '../Utils';\nimport { sleep, createDeferred } from '../Helpers';\nimport errors from '../errors';\n\nexport interface progressCallback {\n isCanceled?: boolean;\n acceptsBuffer?: boolean;\n\n (\n progress: number, // Float between 0 and 1.\n ...args: any[]\n ): void;\n}\n\nexport interface DownloadFileParams {\n dcId: number;\n fileSize: number;\n workers?: number;\n partSizeKb?: number;\n start?: number;\n end?: number;\n progressCallback?: progressCallback;\n}\n\ninterface Deferred {\n promise: Promise;\n resolve: (value?: any) => void;\n}\n\n// Chunk sizes for `upload.getFile` must be multiple of the smallest size\nconst MIN_CHUNK_SIZE = 4096;\nconst DEFAULT_CHUNK_SIZE = 64; // kb\nconst ONE_MB = 1024 * 1024;\nconst DISCONNECT_SLEEP = 1000;\n\n\nclass Foreman {\n private deferred: Deferred | undefined;\n\n private activeWorkers = 0;\n\n constructor(private maxWorkers: number) {\n }\n\n requestWorker() {\n this.activeWorkers++;\n\n if (this.activeWorkers > this.maxWorkers) {\n this.deferred = createDeferred();\n return this.deferred!.promise;\n }\n\n return Promise.resolve();\n }\n\n releaseWorker() {\n this.activeWorkers--;\n\n if (this.deferred && (this.activeWorkers <= this.maxWorkers)) {\n this.deferred.resolve();\n }\n }\n}\n\nexport async function downloadFile(\n client: TelegramClient,\n inputLocation: Api.InputFileLocation,\n fileParams: DownloadFileParams,\n) {\n let {\n partSizeKb, end,\n } = fileParams;\n const {\n fileSize, workers = 1,\n } = fileParams;\n const { dcId, progressCallback, start = 0 } = fileParams;\n\n end = end && end < fileSize ? end : fileSize - 1;\n\n if (!partSizeKb) {\n partSizeKb = fileSize ? getAppropriatedPartSize(fileSize) : DEFAULT_CHUNK_SIZE;\n }\n\n const partSize = partSizeKb * 1024;\n const partsCount = end ? Math.ceil((end - start) / partSize) : 1;\n\n if (partSize % MIN_CHUNK_SIZE !== 0) {\n throw new Error(`The part size must be evenly divisible by ${MIN_CHUNK_SIZE}`);\n }\n\n client._log.info(`Downloading file in chunks of ${partSize} bytes`);\n\n const foreman = new Foreman(workers);\n const promises: Promise[] = [];\n let offset = start;\n // Used for files with unknown size and for manual cancellations\n let hasEnded = false;\n\n let progress = 0;\n if (progressCallback) {\n progressCallback(progress);\n }\n\n // Preload sender\n await client.getSender(dcId);\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n let limit = partSize;\n let isPrecise = false;\n\n if (Math.floor(offset / ONE_MB) !== Math.floor((offset + limit - 1) / ONE_MB)) {\n limit = ONE_MB - (offset % ONE_MB);\n isPrecise = true;\n }\n\n await foreman.requestWorker();\n\n if (hasEnded) {\n foreman.releaseWorker();\n break;\n }\n\n // eslint-disable-next-line no-loop-func\n promises.push((async (offsetMemo: number) => {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n let sender;\n try {\n sender = await client.getSender(dcId);\n const result = await sender.send(new Api.upload.GetFile({\n location: inputLocation,\n offset: offsetMemo,\n limit,\n precise: isPrecise || undefined,\n }));\n\n if (progressCallback) {\n if (progressCallback.isCanceled) {\n throw new Error('USER_CANCELED');\n }\n\n progress += (1 / partsCount);\n progressCallback(progress);\n }\n\n if (!end && (result.bytes.length < limit)) {\n hasEnded = true;\n }\n\n foreman.releaseWorker();\n\n return result.bytes;\n } catch (err) {\n if (sender && !sender.isConnected()) {\n await sleep(DISCONNECT_SLEEP);\n continue;\n } else if (err instanceof errors.FloodWaitError) {\n await sleep(err.seconds * 1000);\n continue;\n }\n\n foreman.releaseWorker();\n\n hasEnded = true;\n throw err;\n }\n }\n })(offset));\n\n offset += limit;\n\n if (end && (offset > end)) {\n break;\n }\n }\n const results = await Promise.all(promises);\n const buffers = results.filter(Boolean);\n const totalLength = end ? (end + 1) - start : undefined;\n return Buffer.concat(buffers, totalLength);\n}\n","// eslint-disable-next-line import/no-named-default\nimport { default as Api } from '../tl/api';\n\nimport TelegramClient from './TelegramClient';\nimport { generateRandomBytes, readBigIntFromBuffer, sleep } from '../Helpers';\nimport { getAppropriatedPartSize } from '../Utils';\nimport errors from '../errors';\n\ninterface OnProgress {\n isCanceled?: boolean;\n\n // Float between 0 and 1.\n (progress: number): void;\n}\n\nexport interface UploadFileParams {\n file: File;\n workers: number;\n onProgress?: OnProgress;\n}\n\nconst KB_TO_BYTES = 1024;\nconst LARGE_FILE_THRESHOLD = 10 * 1024 * 1024;\nconst DISCONNECT_SLEEP = 1000;\n\nexport async function uploadFile(\n client: TelegramClient,\n fileParams: UploadFileParams,\n): Promise {\n const { file, onProgress } = fileParams;\n let { workers } = fileParams;\n\n const { name, size } = file;\n const fileId = readBigIntFromBuffer(generateRandomBytes(8), true, true);\n const isLarge = size > LARGE_FILE_THRESHOLD;\n\n const partSize = getAppropriatedPartSize(size) * KB_TO_BYTES;\n const partCount = Math.floor((size + partSize - 1) / partSize);\n const buffer = Buffer.from(await fileToBuffer(file));\n\n // Make sure a new sender can be created before starting upload\n await client.getSender(client.session.dcId);\n\n if (!workers || !size) {\n workers = 1;\n }\n if (workers >= partCount) {\n workers = partCount;\n }\n\n let progress = 0;\n if (onProgress) {\n onProgress(progress);\n }\n\n for (let i = 0; i < partCount; i += workers) {\n const sendingParts = [];\n let end = i + workers;\n if (end > partCount) {\n end = partCount;\n }\n\n for (let j = i; j < end; j++) {\n const bytes = buffer.slice(j * partSize, (j + 1) * partSize);\n\n // eslint-disable-next-line no-loop-func\n sendingParts.push((async (jMemo: number, bytesMemo: Buffer) => {\n while (true) {\n let sender;\n try {\n // We always upload from the DC we are in\n sender = await client.getSender(client.session.dcId);\n await sender.send(\n isLarge\n ? new Api.upload.SaveBigFilePart({\n fileId,\n filePart: jMemo,\n fileTotalParts: partCount,\n bytes: bytesMemo,\n })\n : new Api.upload.SaveFilePart({\n fileId,\n filePart: jMemo,\n bytes: bytesMemo,\n }),\n );\n } catch (err) {\n if (sender && !sender.isConnected()) {\n await sleep(DISCONNECT_SLEEP);\n continue;\n } else if (err instanceof errors.FloodWaitError) {\n await sleep(err.seconds * 1000);\n continue;\n }\n throw err;\n }\n\n if (onProgress) {\n if (onProgress.isCanceled) {\n throw new Error('USER_CANCELED');\n }\n\n progress += (1 / partCount);\n onProgress(progress);\n }\n break;\n }\n })(j, bytes));\n }\n\n await Promise.all(sendingParts);\n }\n\n return isLarge\n ? new Api.InputFileBig({\n id: fileId,\n parts: partCount,\n name,\n })\n : new Api.InputFile({\n id: fileId,\n parts: partCount,\n name,\n md5Checksum: '', // This is not a \"flag\", so not sure if we can make it optional.\n });\n}\n\nfunction fileToBuffer(file: File) {\n return new Response(file).arrayBuffer();\n}\n","const {\n sha1,\n toSignedLittleBuffer,\n readBufferFromBigInt,\n readBigIntFromBuffer,\n} = require('../Helpers');\nconst BinaryReader = require('../extensions/BinaryReader');\nconst { sleep } = require('../Helpers');\n\nclass AuthKey {\n constructor(value, hash) {\n if (!hash || !value) {\n return;\n }\n this._key = value;\n this._hash = hash;\n const reader = new BinaryReader(hash);\n this.auxHash = reader.readLong(false);\n reader.read(4);\n this.keyId = reader.readLong(false);\n }\n\n async setKey(value) {\n if (!value) {\n this._key = undefined;\n this.auxHash = undefined;\n this.keyId = undefined;\n this._hash = undefined;\n return;\n }\n if (value instanceof AuthKey) {\n this._key = value._key;\n this.auxHash = value.auxHash;\n this.keyId = value.keyId;\n this._hash = value._hash;\n return;\n }\n this._key = value;\n this._hash = await sha1(this._key);\n const reader = new BinaryReader(this._hash);\n this.auxHash = reader.readLong(false);\n reader.read(4);\n this.keyId = reader.readLong(false);\n }\n\n async waitForKey() {\n while (!this.keyId) {\n await sleep(20);\n }\n }\n\n getKey() {\n return this._key;\n }\n\n // TODO : This doesn't really fit here, it's only used in authentication\n\n /**\n * Calculates the new nonce hash based on the current class fields' values\n * @param newNonce\n * @param number\n * @returns {bigint}\n */\n async calcNewNonceHash(newNonce, number) {\n newNonce = toSignedLittleBuffer(newNonce, 32);\n const n = Buffer.alloc(1);\n n.writeUInt8(number, 0);\n const data = Buffer.concat([newNonce,\n Buffer.concat([n, readBufferFromBigInt(this.auxHash, 8, true)])]);\n\n // Calculates the message key from the given data\n const shaData = (await sha1(data)).slice(4, 20);\n return readBigIntFromBuffer(shaData, true, true);\n }\n\n equals(other) {\n return other instanceof this.constructor && this._key && other.getKey() && other.getKey()\n .equals(this._key);\n }\n}\n\nmodule.exports = AuthKey;\n","const crypto = require('./crypto');\n\nclass CTR {\n constructor(key, iv) {\n if (!Buffer.isBuffer(key) || !Buffer.isBuffer(iv) || iv.length !== 16) {\n throw new Error('Key and iv need to be a buffer');\n }\n\n this.cipher = crypto.createCipheriv('AES-256-CTR', key, iv);\n }\n\n encrypt(data) {\n return Buffer.from(this.cipher.update(data));\n }\n}\n\nmodule.exports = CTR;\n","const BigInt = require('big-integer');\nconst { modExp } = require('../Helpers');\n\nclass Factorizator {\n /**\n * Calculates the greatest common divisor\n * @param a {BigInteger}\n * @param b {BigInteger}\n * @returns {BigInteger}\n */\n static gcd(a, b) {\n while (b.neq(BigInt.zero)) {\n const temp = b;\n b = a.remainder(b);\n a = temp;\n }\n return a;\n }\n\n /**\n * Factorizes the given number and returns both the divisor and the number divided by the divisor\n * @param pq {BigInteger}\n * @returns {{p: *, q: *}}\n */\n static factorize(pq) {\n if (pq.remainder(2)\n .equals(BigInt.zero)) {\n return {\n p: BigInt(2),\n q: pq.divide(BigInt(2)),\n };\n }\n let y = BigInt.randBetween(BigInt(1), pq.minus(1));\n const c = BigInt.randBetween(BigInt(1), pq.minus(1));\n const m = BigInt.randBetween(BigInt(1), pq.minus(1));\n\n let g = BigInt.one;\n let r = BigInt.one;\n let q = BigInt.one;\n let x = BigInt.zero;\n let ys = BigInt.zero;\n let k;\n\n while (g.eq(BigInt.one)) {\n x = y;\n for (let i = 0; BigInt(i)\n .lesser(r); i++) {\n y = (modExp(y, BigInt(2), pq)).add(c)\n .remainder(pq);\n }\n k = BigInt.zero;\n\n while (k.lesser(r) && g.eq(BigInt.one)) {\n ys = y;\n const condition = BigInt.min(m, r.minus(k));\n for (let i = 0; BigInt(i)\n .lesser(condition); i++) {\n y = (modExp(y, BigInt(2), pq)).add(c)\n .remainder(pq);\n q = q.multiply(x.minus(y)\n .abs())\n .remainder(pq);\n }\n g = Factorizator.gcd(q, pq);\n k = k.add(m);\n }\n\n r = r.multiply(2);\n }\n\n\n if (g.eq(pq)) {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n ys = (modExp(ys, BigInt(2), pq)).add(c)\n .remainder(pq);\n g = Factorizator.gcd(x.minus(ys)\n .abs(), pq);\n\n if (g.greater(1)) {\n break;\n }\n }\n }\n const p = g;\n q = pq.divide(g);\n return p < q ? {\n p,\n q,\n } : {\n p: q,\n q: p,\n };\n }\n}\n\nmodule.exports = Factorizator;\n","const { IGE: AESIGE } = require('@cryptography/aes');\nconst Helpers = require('../Helpers');\n\n\nclass IGENEW {\n constructor(key, iv) {\n this.ige = new AESIGE(key, iv);\n }\n\n /**\n * Decrypts the given text in 16-bytes blocks by using the given key and 32-bytes initialization vector\n * @param cipherText {Buffer}\n * @returns {Buffer}\n */\n decryptIge(cipherText) {\n return Helpers.convertToLittle(this.ige.decrypt(cipherText));\n }\n\n /**\n * Encrypts the given text in 16-bytes blocks by using the given key and 32-bytes initialization vector\n * @param plainText {Buffer}\n * @returns {Buffer}\n */\n encryptIge(plainText) {\n const padding = plainText.length % 16;\n if (padding) {\n plainText = Buffer.concat([plainText, Helpers.generateRandomBytes(16 - padding)]);\n }\n\n return Helpers.convertToLittle(this.ige.encrypt(plainText));\n }\n}\n\nmodule.exports = IGENEW;\n","/**\n * Uint32Array -> ArrayBuffer (low-endian os)\n */\nexport function i2abLow(buf: Uint32Array): ArrayBuffer {\n const uint8 = new Uint8Array(buf.length * 4);\n let i = 0;\n\n for (let j = 0; j < buf.length; j++) {\n const int = buf[j];\n\n uint8[i++] = int >>> 24;\n uint8[i++] = (int >> 16) & 0xFF;\n uint8[i++] = (int >> 8) & 0xFF;\n uint8[i++] = int & 0xFF;\n }\n\n return uint8.buffer;\n}\n\n/**\n * Uint32Array -> ArrayBuffer (big-endian os)\n */\nexport function i2abBig(buf: Uint32Array): ArrayBuffer {\n return buf.buffer;\n}\n\n/**\n * ArrayBuffer -> Uint32Array (low-endian os)\n */\nexport function ab2iLow(ab: ArrayBuffer | SharedArrayBuffer | Uint8Array): Uint32Array {\n const uint8 = new Uint8Array(ab);\n const buf = new Uint32Array(uint8.length / 4);\n\n for (let i = 0; i < uint8.length; i += 4) {\n buf[i / 4] = (\n uint8[i] << 24\n ^ uint8[i + 1] << 16\n ^ uint8[i + 2] << 8\n ^ uint8[i + 3]\n );\n }\n\n return buf;\n}\n\n/**\n * ArrayBuffer -> Uint32Array (big-endian os)\n */\nexport function ab2iBig(ab: ArrayBuffer | SharedArrayBuffer | Uint8Array): Uint32Array {\n return new Uint32Array(ab);\n}\n\nexport const isBigEndian = new Uint8Array(new Uint32Array([0x01020304]))[0] === 0x01;\nexport const i2ab = isBigEndian ? i2abBig : i2abLow;\nexport const ab2i = isBigEndian ? ab2iBig : ab2iLow;\n","const AES = require('@cryptography/aes').default;\nconst {\n i2ab,\n ab2i,\n} = require('./converters');\nconst { getWords } = require('./words');\n\nclass Counter {\n constructor(initialValue) {\n this.setBytes(initialValue);\n }\n\n setBytes(bytes) {\n bytes = Buffer.from(bytes);\n this._counter = bytes;\n }\n\n increment() {\n for (let i = 15; i >= 0; i--) {\n if (this._counter[i] === 255) {\n this._counter[i] = 0;\n } else {\n this._counter[i]++;\n break;\n }\n }\n }\n}\n\nclass CTR {\n constructor(key, counter) {\n if (!(counter instanceof Counter)) {\n counter = new Counter(counter);\n }\n\n this._counter = counter;\n\n this._remainingCounter = undefined;\n this._remainingCounterIndex = 16;\n\n this._aes = new AES(getWords(key));\n }\n\n update(plainText) {\n return this.encrypt(plainText);\n }\n\n encrypt(plainText) {\n const encrypted = Buffer.from(plainText);\n\n for (let i = 0; i < encrypted.length; i++) {\n if (this._remainingCounterIndex === 16) {\n this._remainingCounter = Buffer.from(i2ab(this._aes.encrypt(ab2i(this._counter._counter))));\n this._remainingCounterIndex = 0;\n this._counter.increment();\n }\n encrypted[i] ^= this._remainingCounter[this._remainingCounterIndex++];\n }\n\n return encrypted;\n }\n}\n\n// endregion\nfunction createDecipheriv(algorithm, key, iv) {\n if (algorithm.includes('ECB')) {\n throw new Error('Not supported');\n } else {\n return new CTR(key, iv);\n }\n}\n\nfunction createCipheriv(algorithm, key, iv) {\n if (algorithm.includes('ECB')) {\n throw new Error('Not supported');\n } else {\n return new CTR(key, iv);\n }\n}\n\nfunction randomBytes(count) {\n const bytes = new Uint8Array(count);\n crypto.getRandomValues(bytes);\n return bytes;\n}\n\nclass Hash {\n constructor(algorithm) {\n this.algorithm = algorithm;\n }\n\n update(data) {\n // We shouldn't be needing new Uint8Array but it doesn't\n // work without it\n this.data = new Uint8Array(data);\n }\n\n\n async digest() {\n if (this.algorithm === 'sha1') {\n // eslint-disable-next-line no-restricted-globals\n return Buffer.from(await self.crypto.subtle.digest('SHA-1', this.data));\n } else if (this.algorithm === 'sha256') {\n // eslint-disable-next-line no-restricted-globals\n return Buffer.from(await self.crypto.subtle.digest('SHA-256', this.data));\n }\n return undefined;\n }\n}\n\nasync function pbkdf2(password, salt, iterations) {\n const passwordKey = await crypto.subtle.importKey('raw', password,\n { name: 'PBKDF2' }, false, ['deriveBits']);\n return Buffer.from(await crypto.subtle.deriveBits({\n name: 'PBKDF2',\n hash: 'SHA-512',\n salt,\n iterations,\n }, passwordKey, 512));\n}\n\nfunction createHash(algorithm) {\n return new Hash(algorithm);\n}\n\nmodule.exports = {\n createCipheriv,\n createDecipheriv,\n randomBytes,\n createHash,\n pbkdf2,\n};\n","/*\n * Imported from https://github.com/spalt08/cryptography/blob/master/packages/aes/src/utils/words.ts\n */\n\nexport function s2i(str: string, pos: number) {\n return (\n str.charCodeAt(pos) << 24\n ^ str.charCodeAt(pos + 1) << 16\n ^ str.charCodeAt(pos + 2) << 8\n ^ str.charCodeAt(pos + 3)\n );\n}\n\n/**\n * Helper function for transforming string key to Uint32Array\n */\nexport function getWords(key: string | Uint8Array | Uint32Array) {\n if (key instanceof Uint32Array) {\n return key;\n }\n\n if (typeof key === 'string') {\n if (key.length % 4 !== 0) for (let i = key.length % 4; i <= 4; i++) key += '\\0x00';\n\n const buf = new Uint32Array(key.length / 4);\n for (let i = 0; i < key.length; i += 4) buf[i / 4] = s2i(key, i);\n\n return buf;\n }\n\n if (key instanceof Uint8Array) {\n const buf = new Uint32Array(key.length / 4);\n\n for (let i = 0; i < key.length; i += 4) {\n buf[i / 4] = (\n key[i] << 24\n ^ key[i + 1] << 16\n ^ key[i + 2] << 8\n ^ key[i + 3]\n );\n }\n\n return buf;\n }\n\n throw new Error('Unable to create 32-bit words');\n}\n\nexport function xor(left: Uint32Array, right: Uint32Array, to = left) {\n for (let i = 0; i < left.length; i++) to[i] = left[i] ^ right[i];\n}\n","/**\n * Errors not related to the Telegram API itself\n */\n\n\n/**\n * Occurs when a read operation was cancelled.\n */\nclass ReadCancelledError extends Error {\n constructor() {\n super('The read operation was cancelled.');\n }\n}\n\n/**\n * Occurs when a type is not found, for example,\n * when trying to read a TLObject with an invalid constructor code.\n */\nclass TypeNotFoundError extends Error {\n constructor(invalidConstructorId, remaining) {\n super(`Could not find a matching Constructor ID for the TLObject that was supposed to be\n read with ID ${invalidConstructorId}. Most likely, a TLObject was trying to be read when\n it should not be read. Remaining bytes: ${remaining.length}`);\n if (typeof alert !== 'undefined') {\n // eslint-disable-next-line no-alert\n alert(`Missing MTProto Entity: Please, make sure to add TL definition for ID ${invalidConstructorId}`);\n }\n this.invalidConstructorId = invalidConstructorId;\n this.remaining = remaining;\n }\n}\n\n/**\n * Occurs when using the TCP full mode and the checksum of a received\n * packet doesn't match the expected checksum.\n */\nclass InvalidChecksumError extends Error {\n constructor(checksum, validChecksum) {\n super(`Invalid checksum (${checksum} when ${validChecksum} was expected). This packet should be skipped.`);\n this.checksum = checksum;\n this.validChecksum = validChecksum;\n }\n}\n\n/**\n * Occurs when the buffer is invalid, and may contain an HTTP error code.\n * For instance, 404 means \"forgotten/broken authorization key\", while\n */\nclass InvalidBufferError extends Error {\n constructor(payload) {\n let code;\n if (payload.length === 4) {\n code = -payload.readInt32LE(0);\n super(`Invalid response buffer (HTTP code ${code})`);\n } else {\n super(`Invalid response buffer (too short ${payload})`);\n }\n this.code = code;\n this.payload = payload;\n }\n}\n\n/**\n * Generic security error, mostly used when generating a new AuthKey.\n */\nclass SecurityError extends Error {\n constructor(...args) {\n if (!args.length) {\n args = ['A security check failed.'];\n }\n super(...args);\n }\n}\n\n/**\n * Occurs when there's a hash mismatch between the decrypted CDN file\n * and its expected hash.\n */\nclass CdnFileTamperedError extends SecurityError {\n constructor() {\n super('The CDN file has been altered and its download cancelled.');\n }\n}\n\n/**\n * Occurs when handling a badMessageNotification\n */\nclass BadMessageError extends Error {\n static ErrorMessages = {\n 16:\n 'msg_id too low (most likely, client time is wrong it would be worthwhile to '\n + 'synchronize it using msg_id notifications and re-send the original message '\n + 'with the “correct” msg_id or wrap it in a container with a new msg_id if the '\n + 'original message had waited too long on the client to be transmitted).',\n\n 17:\n 'msg_id too high (similar to the previous case, the client time has to be '\n + 'synchronized, and the message re-sent with the correct msg_id).',\n\n 18:\n 'Incorrect two lower order msg_id bits (the server expects client message msg_id '\n + 'to be divisible by 4).',\n\n 19: 'Container msg_id is the same as msg_id of a previously received message (this must never happen).',\n\n 20:\n 'Message too old, and it cannot be verified whether the server has received a '\n + 'message with this msg_id or not.',\n\n 32:\n 'msg_seqno too low (the server has already received a message with a lower '\n + 'msg_id but with either a higher or an equal and odd seqno).',\n\n 33:\n 'msg_seqno too high (similarly, there is a message with a higher msg_id but with '\n + 'either a lower or an equal and odd seqno).',\n\n 34: 'An even msg_seqno expected (irrelevant message), but odd received.',\n\n 35: 'Odd msg_seqno expected (relevant message), but even received.',\n\n 48:\n 'Incorrect server salt (in this case, the bad_server_salt response is received with '\n + 'the correct salt, and the message is to be re-sent with it).',\n\n 64: 'Invalid container.',\n };\n\n constructor(request, code) {\n let errorMessage = BadMessageError.ErrorMessages[code]\n || `Unknown error code (this should not happen): ${code}.`;\n errorMessage += ` Caused by ${request.className}`;\n super(errorMessage);\n this.message = errorMessage;\n this.code = code;\n }\n}\n\n// TODO : Support multi errors.\n\nmodule.exports = {\n ReadCancelledError,\n TypeNotFoundError,\n InvalidChecksumError,\n InvalidBufferError,\n SecurityError,\n CdnFileTamperedError,\n BadMessageError,\n};\n","/**\n * Base class for all Remote Procedure Call errors.\n */\nclass RPCError extends Error {\n constructor(message, request, code = undefined) {\n super(\n 'RPCError {0}: {1}{2}'\n .replace('{0}', code)\n .replace('{1}', message)\n .replace('{2}', RPCError._fmtRequest(request)),\n );\n this.code = code;\n this.message = message;\n }\n\n static _fmtRequest(request) {\n // TODO fix this\n if (request) {\n return ` (caused by ${request.className})`;\n } else {\n return '';\n }\n }\n}\n\n/**\n * The request must be repeated, but directed to a different data center.\n */\nclass InvalidDCError extends RPCError {\n constructor(request, message, code) {\n super(message, request, code);\n this.code = code || 303;\n this.message = message || 'ERROR_SEE_OTHER';\n }\n}\n\n/**\n * The query contains errors. In the event that a request was created\n * using a form and contains user generated data, the user should be\n * notified that the data must be corrected before the query is repeated.\n */\nclass BadRequestError extends RPCError {\n code = 400;\n\n message = 'BAD_REQUEST';\n}\n\n/**\n * There was an unauthorized attempt to use functionality available only\n * to authorized users.\n */\nclass UnauthorizedError extends RPCError {\n code = 401;\n\n message = 'UNAUTHORIZED';\n}\n\n/**\n * Privacy violation. For example, an attempt to write a message to\n * someone who has blacklisted the current user.\n */\nclass ForbiddenError extends RPCError {\n code = 403;\n\n message = 'FORBIDDEN';\n}\n\n/**\n * An attempt to invoke a non-existent object, such as a method.\n */\nclass NotFoundError extends RPCError {\n code = 404;\n\n message = 'NOT_FOUND';\n}\n\n/**\n * Errors related to invalid authorization key, like\n * AUTH_KEY_DUPLICATED which can cause the connection to fail.\n */\nclass AuthKeyError extends RPCError {\n code = 406;\n\n message = 'AUTH_KEY';\n}\n\n/**\n * The maximum allowed number of attempts to invoke the given method\n * with the given input parameters has been exceeded. For example, in an\n * attempt to request a large number of text messages (SMS) for the same\n * phone number.\n */\nclass FloodError extends RPCError {\n code = 420;\n\n message = 'FLOOD';\n}\n\n/**\n * An internal server error occurred while a request was being processed\n * for example, there was a disruption while accessing a database or file\n * storage\n */\nclass ServerError extends RPCError {\n code = 500; // Also witnessed as -500\n\n message = 'INTERNAL';\n}\n\n/**\n * Clicking the inline buttons of bots that never (or take to long to)\n * call ``answerCallbackQuery`` will result in this \"special\" RPCError.\n */\nclass TimedOutError extends RPCError {\n code = 503; // Only witnessed as -503\n\n message = 'Timeout';\n}\n\nmodule.exports = {\n RPCError,\n InvalidDCError,\n BadRequestError,\n UnauthorizedError,\n ForbiddenError,\n NotFoundError,\n AuthKeyError,\n FloodError,\n ServerError,\n TimedOutError,\n};\n","const {\n RPCError,\n InvalidDCError,\n FloodError,\n BadRequestError,\n} = require('./RPCBaseErrors');\n\n\nclass UserMigrateError extends InvalidDCError {\n constructor(args) {\n const newDc = Number(args.capture || 0);\n // eslint-disable-next-line max-len\n super(`The user whose identity is being used to execute queries is associated with DC ${newDc}${RPCError._fmtRequest(args.request)}`);\n // eslint-disable-next-line max-len\n this.message = `The user whose identity is being used to execute queries is associated with DC ${newDc}${RPCError._fmtRequest(args.request)}`;\n this.newDc = newDc;\n }\n}\n\n\nclass PhoneMigrateError extends InvalidDCError {\n constructor(args) {\n const newDc = Number(args.capture || 0);\n // eslint-disable-next-line max-len\n super(`The phone number a user is trying to use for authorization is associated with DC ${newDc}${RPCError._fmtRequest(args.request)}`);\n // eslint-disable-next-line max-len\n this.message = `The phone number a user is trying to use for authorization is associated with DC ${newDc}${RPCError._fmtRequest(args.request)}`;\n this.newDc = newDc;\n }\n}\n\nclass SlowModeWaitError extends FloodError {\n constructor(args) {\n const seconds = Number(args.capture || 0);\n // eslint-disable-next-line max-len\n super(`A wait of ${seconds} seconds is required before sending another message in this chat${RPCError._fmtRequest(args.request)}`);\n // eslint-disable-next-line max-len\n this.message = `A wait of ${seconds} seconds is required before sending another message in this chat${RPCError._fmtRequest(args.request)}`;\n this.seconds = seconds;\n }\n}\n\nclass FloodWaitError extends FloodError {\n constructor(args) {\n const seconds = Number(args.capture || 0);\n super(`A wait of ${seconds} seconds is required${RPCError._fmtRequest(args.request)}`);\n this.message = `A wait of ${seconds} seconds is required${RPCError._fmtRequest(args.request)}`;\n this.seconds = seconds;\n }\n}\nclass MsgWaitError extends FloodError {\n constructor(args) {\n super(`Message failed to be sent.${RPCError._fmtRequest(args.request)}`);\n this.message = `Message failed to be sent.${RPCError._fmtRequest(args.request)}`;\n }\n}\n\nclass FloodTestPhoneWaitError extends FloodError {\n constructor(args) {\n const seconds = Number(args.capture || 0);\n super(`A wait of ${seconds} seconds is required in the test servers${RPCError._fmtRequest(args.request)}`);\n // eslint-disable-next-line max-len\n this.message = `A wait of ${seconds} seconds is required in the test servers${RPCError._fmtRequest(args.request)}`;\n this.seconds = seconds;\n }\n}\n\nclass FileMigrateError extends InvalidDCError {\n constructor(args) {\n const newDc = Number(args.capture || 0);\n super(`The file to be accessed is currently stored in DC ${newDc}${RPCError._fmtRequest(args.request)}`);\n // eslint-disable-next-line max-len\n this.message = `The file to be accessed is currently stored in DC ${newDc}${RPCError._fmtRequest(args.request)}`;\n this.newDc = newDc;\n }\n}\n\nclass NetworkMigrateError extends InvalidDCError {\n constructor(args) {\n const newDc = Number(args.capture || 0);\n super(`The source IP address is associated with DC ${newDc}${RPCError._fmtRequest(args.request)}`);\n this.message = `The source IP address is associated with DC ${newDc}${RPCError._fmtRequest(args.request)}`;\n this.newDc = newDc;\n }\n}\n\nclass EmailUnconfirmedError extends BadRequestError {\n constructor(args) {\n const codeLength = Number(args.capture || 0);\n super(`Email unconfirmed, the length of the code must be ${codeLength}${RPCError._fmtRequest(args.request)}`);\n // eslint-disable-next-line max-len\n this.message = `Email unconfirmed, the length of the code must be ${codeLength}${RPCError._fmtRequest(args.request)}`;\n this.codeLength = codeLength;\n }\n}\n\nconst rpcErrorRe = [\n [/FILE_MIGRATE_(\\d+)/, FileMigrateError],\n [/FLOOD_TEST_PHONE_WAIT_(\\d+)/, FloodTestPhoneWaitError],\n [/FLOOD_WAIT_(\\d+)/, FloodWaitError],\n [/MSG_WAIT_(.*)/, MsgWaitError],\n [/PHONE_MIGRATE_(\\d+)/, PhoneMigrateError],\n [/SLOWMODE_WAIT_(\\d+)/, SlowModeWaitError],\n [/USER_MIGRATE_(\\d+)/, UserMigrateError],\n [/NETWORK_MIGRATE_(\\d+)/, NetworkMigrateError],\n [/EMAIL_UNCONFIRMED_(\\d+)/, EmailUnconfirmedError],\n\n];\nmodule.exports = {\n rpcErrorRe,\n FileMigrateError,\n FloodTestPhoneWaitError,\n FloodWaitError,\n PhoneMigrateError,\n SlowModeWaitError,\n UserMigrateError,\n NetworkMigrateError,\n MsgWaitError,\n EmailUnconfirmedError,\n};\n","/**\n * Converts a Telegram's RPC Error to a Python error.\n * @param rpcError the RPCError instance\n * @param request the request that caused this error\n * @constructor the RPCError as a Python exception that represents this error\n */\nconst { RPCError } = require('./RPCBaseErrors');\nconst { rpcErrorRe } = require('./RPCErrorList');\n\nfunction RPCMessageToError(rpcError, request) {\n for (const [msgRegex, Cls] of rpcErrorRe) {\n const m = rpcError.errorMessage.match(msgRegex);\n if (m) {\n const capture = m.length === 2 ? parseInt(m[1], 10) : undefined;\n return new Cls({\n request,\n capture,\n });\n }\n }\n\n return new RPCError(rpcError.errorMessage, request);\n}\n\nconst Common = require('./Common');\nconst RPCBaseErrors = require('./RPCBaseErrors');\nconst RPCErrorList = require('./RPCErrorList');\n\nmodule.exports = {\n RPCMessageToError,\n ...Common,\n ...RPCBaseErrors,\n ...RPCErrorList,\n};\n","const { EventBuilder } = require('./common');\n\nclass Raw extends EventBuilder {\n constructor(args = {\n types: undefined,\n func: undefined,\n }) {\n super();\n if (!args.types) {\n this.types = true;\n } else {\n this.types = args.types;\n }\n }\n\n build(update) {\n return update;\n }\n}\n\nmodule.exports = Raw;\n","class EventBuilder {\n constructor(args = {\n chats: undefined,\n blacklistChats: undefined,\n func: undefined,\n }) {\n this.chats = args.chats;\n this.blacklistChats = Boolean(args.blacklistChats);\n this.resolved = false;\n this.func = args.func;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n build(update) {\n\n }\n}\n\n\nmodule.exports = {\n EventBuilder,\n};\n","const NewMessage = require('./NewMessage');\nconst Raw = require('./Raw');\n\nclass StopPropagation extends Error {\n\n}\n\nmodule.exports = {\n NewMessage,\n StopPropagation,\n Raw,\n};\n","class AsyncQueue {\n constructor() {\n this._queue = [];\n this.canGet = new Promise((resolve) => {\n this.resolveGet = resolve;\n });\n this.canPush = true;\n }\n\n async push(value) {\n await this.canPush;\n this._queue.push(value);\n this.resolveGet(true);\n this.canPush = new Promise((resolve) => {\n this.resolvePush = resolve;\n });\n }\n\n async pop() {\n await this.canGet;\n const returned = this._queue.pop();\n this.resolvePush(true);\n this.canGet = new Promise((resolve) => {\n this.resolveGet = resolve;\n });\n return returned;\n }\n}\n\nmodule.exports = AsyncQueue;\n","const { TypeNotFoundError } = require('../errors/Common');\nconst { coreObjects } = require('../tl/core');\nconst { tlobjects } = require('../tl/AllTLObjects');\nconst { readBigIntFromBuffer } = require('../Helpers');\n\nclass BinaryReader {\n /**\n * Small utility class to read binary data.\n * @param data {Buffer}\n */\n constructor(data) {\n this.stream = data;\n this._last = undefined;\n this.offset = 0;\n }\n\n // region Reading\n\n // \"All numbers are written as little endian.\"\n // https://core.telegram.org/mtproto\n /**\n * Reads a single byte value.\n */\n readByte() {\n return this.read(1)[0];\n }\n\n /**\n * Reads an integer (4 bytes or 32 bits) value.\n * @param signed {Boolean}\n */\n readInt(signed = true) {\n let res;\n if (signed) {\n res = this.stream.readInt32LE(this.offset);\n } else {\n res = this.stream.readUInt32LE(this.offset);\n }\n this.offset += 4;\n return res;\n }\n\n /**\n * Reads a long integer (8 bytes or 64 bits) value.\n * @param signed\n * @returns {BigInteger}\n */\n readLong(signed = true) {\n return this.readLargeInt(64, signed);\n }\n\n /**\n * Reads a real floating point (4 bytes) value.\n * @returns {number}\n */\n readFloat() {\n return this.read(4)\n .readFloatLE(0);\n }\n\n /**\n * Reads a real floating point (8 bytes) value.\n * @returns {BigInteger}\n */\n readDouble() {\n // was this a bug ? it should have been 0) {\n padding = 4 - padding;\n this.read(padding);\n }\n\n return data;\n }\n\n /**\n * Reads a Telegram-encoded string.\n * @returns {string}\n */\n tgReadString() {\n return this.tgReadBytes()\n .toString('utf-8');\n }\n\n /**\n * Reads a Telegram boolean value.\n * @returns {boolean}\n */\n tgReadBool() {\n const value = this.readInt(false);\n if (value === 0x997275b5) {\n // boolTrue\n return true;\n } else if (value === 0xbc799737) {\n // boolFalse\n return false;\n } else {\n throw new Error(`Invalid boolean code ${value.toString('16')}`);\n }\n }\n\n /**\n * Reads and converts Unix time (used by Telegram)\n * into a Javascript {Date} object.\n * @returns {Date}\n */\n tgReadDate() {\n const value = this.readInt();\n return new Date(value * 1000);\n }\n\n /**\n * Reads a Telegram object.\n */\n tgReadObject() {\n const constructorId = this.readInt(false);\n let clazz = tlobjects[constructorId];\n if (clazz === undefined) {\n /**\n * The class was None, but there's still a\n * chance of it being a manually parsed value like bool!\n */\n const value = constructorId;\n if (value === 0x997275b5) {\n // boolTrue\n return true;\n } else if (value === 0xbc799737) {\n // boolFalse\n return false;\n } else if (value === 0x1cb5c415) {\n // Vector\n const temp = [];\n const length = this.readInt();\n for (let i = 0; i < length; i++) {\n temp.push(this.tgReadObject());\n }\n return temp;\n }\n\n clazz = coreObjects[constructorId];\n\n if (clazz === undefined) {\n // If there was still no luck, give up\n this.seek(-4); // Go back\n const pos = this.tellPosition();\n const error = new TypeNotFoundError(constructorId, this.read());\n this.setPosition(pos);\n throw error;\n }\n }\n return clazz.fromReader(this);\n }\n\n /**\n * Reads a vector (a list) of Telegram objects.\n * @returns {[Buffer]}\n */\n tgReadVector() {\n if (this.readInt(false) !== 0x1cb5c415) {\n throw new Error('Invalid constructor code, vector was expected');\n }\n const count = this.readInt();\n const temp = [];\n for (let i = 0; i < count; i++) {\n temp.push(this.tgReadObject());\n }\n return temp;\n }\n\n // endregion\n\n /**\n * Closes the reader.\n */\n close() {\n this.stream = undefined;\n }\n\n // region Position related\n\n /**\n * Tells the current position on the stream.\n * @returns {number}\n */\n tellPosition() {\n return this.offset;\n }\n\n /**\n * Sets the current position on the stream.\n * @param position\n */\n setPosition(position) {\n this.offset = position;\n }\n\n /**\n * Seeks the stream position given an offset from the current position.\n * The offset may be negative.\n * @param offset\n */\n seek(offset) {\n this.offset += offset;\n }\n\n // endregion\n}\n\nmodule.exports = BinaryReader;\n","class BinaryWriter {\n constructor(stream) {\n this._stream = stream;\n }\n\n write(buffer) {\n this._stream = Buffer.concat([this._stream, buffer]);\n }\n\n getValue() {\n return this._stream;\n }\n}\n\nmodule.exports = BinaryWriter;\n","let _level;\n\nclass Logger {\n static levels = ['error', 'warn', 'info', 'debug'];\n\n constructor(level) {\n if (!_level) {\n _level = level || 'debug';\n }\n\n this.isBrowser = typeof process === 'undefined'\n || process.type === 'renderer'\n || process.browser === true\n || process.__nwjs;\n if (!this.isBrowser) {\n this.colors = {\n start: '\\x1b[2m',\n warn: '\\x1b[35m',\n info: '\\x1b[33m',\n debug: '\\x1b[36m',\n error: '\\x1b[31m',\n end: '\\x1b[0m',\n };\n } else {\n this.colors = {\n start: '%c',\n warn: 'color : #ff00ff',\n info: 'color : #ffff00',\n debug: 'color : #00ffff',\n error: 'color : #ff0000',\n end: '',\n };\n }\n this.messageFormat = '[%t] [%l] - [%m]';\n }\n\n static setLevel(level) {\n _level = level;\n }\n\n /**\n *\n * @param level {string}\n * @returns {boolean}\n */\n canSend(level) {\n return (Logger.levels.indexOf(_level) >= Logger.levels.indexOf(level));\n }\n\n /**\n * @param message {string}\n */\n warn(message) {\n // todo remove later\n if (_level === 'debug') {\n // eslint-disable-next-line no-console\n console.error(new Error().stack);\n }\n this._log('warn', message, this.colors.warn);\n }\n\n /**\n * @param message {string}\n */\n info(message) {\n this._log('info', message, this.colors.info);\n }\n\n /**\n * @param message {string}\n */\n debug(message) {\n this._log('debug', message, this.colors.debug);\n }\n\n /**\n * @param message {string}\n */\n error(message) {\n // todo remove later\n if (_level === 'debug') {\n // eslint-disable-next-line no-console\n console.error(new Error().stack);\n }\n this._log('error', message, this.colors.error);\n }\n\n format(message, level) {\n return this.messageFormat.replace('%t', new Date().toISOString())\n .replace('%l', level.toUpperCase())\n .replace('%m', message);\n }\n\n /**\n * @param level {string}\n * @param message {string}\n * @param color {string}\n */\n _log(level, message, color) {\n if (!_level) {\n return;\n }\n if (this.canSend(level)) {\n if (!this.isBrowser) {\n // eslint-disable-next-line no-console\n console.log(color + this.format(message, level) + this.colors.end);\n } else {\n // eslint-disable-next-line no-console\n console.log(this.colors.start + this.format(message, level), color);\n }\n }\n }\n}\n\nmodule.exports = Logger;\n","const MessageContainer = require('../tl/core/MessageContainer');\nconst TLMessage = require('../tl/core/TLMessage');\nconst BinaryWriter = require('./BinaryWriter');\n\nconst USE_INVOKE_AFTER_WITH = [\n 'messages.SendMessage', 'messages.SendMedia', 'messages.SendMultiMedia',\n 'messages.ForwardMessages', 'messages.SendInlineBotResult',\n];\n\nclass MessagePacker {\n constructor(state, logger) {\n this._state = state;\n this._queue = [];\n this._pendingStates = [];\n this._ready = new Promise(((resolve) => {\n this.setReady = resolve;\n }));\n this._log = logger;\n }\n\n values() {\n return this._queue;\n }\n\n append(state) {\n // we need to check if there is already a request with the same name that we should send after.\n if (state && USE_INVOKE_AFTER_WITH.includes(state.request.className)) {\n // we now need to check if there is any request in queue already.\n // we loop backwards since the latest request is the most recent\n for (let i = this._queue.length - 1; i >= 0; i--) {\n if (USE_INVOKE_AFTER_WITH.includes(this._queue[i].request.className)) {\n state.after = this._queue[i];\n break;\n }\n }\n }\n\n this._queue.push(state);\n this.setReady(true);\n // 1658238041=MsgsAck, we don't care about MsgsAck here because they never resolve anyway.\n if (state && state.request.CONSTRUCTOR_ID !== 1658238041) {\n this._pendingStates.push(state);\n state.promise\n // Using finally causes triggering `unhandledrejection` event\n .catch(() => {\n })\n .finally(() => {\n this._pendingStates = this._pendingStates.filter((s) => s !== state);\n });\n }\n }\n\n extend(states) {\n for (const state of states) {\n this._queue.push(state);\n }\n this.setReady(true);\n }\n\n async get() {\n if (!this._queue.length) {\n this._ready = new Promise(((resolve) => {\n this.setReady = resolve;\n }));\n await this._ready;\n }\n if (!this._queue[this._queue.length - 1]) {\n this._queue = [];\n return undefined;\n }\n let data;\n let buffer = new BinaryWriter(Buffer.alloc(0));\n\n const batch = [];\n let size = 0;\n\n while (this._queue.length && batch.length <= MessageContainer.MAXIMUM_LENGTH) {\n const state = this._queue.shift();\n size += state.data.length + TLMessage.SIZE_OVERHEAD;\n if (size <= MessageContainer.MAXIMUM_SIZE) {\n let afterId;\n if (state.after) {\n afterId = state.after.msgId;\n }\n state.msgId = await this._state.writeDataAsMessage(\n buffer, state.data, state.request.classType === 'request',\n afterId,\n );\n this._log.debug(`Assigned msgId = ${state.msgId} to ${state.request.className\n || state.request.constructor.name}`);\n batch.push(state);\n continue;\n }\n if (batch.length) {\n this._queue.unshift(state);\n break;\n }\n this._log.warn(`Message payload for ${state.request.className\n || state.request.constructor.name} is too long ${state.data.length} and cannot be sent`);\n state.reject('Request Payload is too big');\n size = 0;\n }\n if (!batch.length) {\n return undefined;\n }\n if (batch.length > 1) {\n const b = Buffer.alloc(8);\n b.writeUInt32LE(MessageContainer.CONSTRUCTOR_ID, 0);\n b.writeInt32LE(batch.length, 4);\n data = Buffer.concat([b, buffer.getValue()]);\n buffer = new BinaryWriter(Buffer.alloc(0));\n const containerId = await this._state.writeDataAsMessage(\n buffer, data, false,\n );\n for (const s of batch) {\n s.containerId = containerId;\n }\n }\n\n data = buffer.getValue();\n return {\n batch,\n data,\n };\n }\n\n rejectAll() {\n this._pendingStates.forEach((requestState) => {\n requestState.reject(new Error('Disconnect'));\n });\n }\n}\n\nmodule.exports = MessagePacker;\n","const { Mutex } = require('async-mutex');\n\nconst mutex = new Mutex();\n\nconst WebSocketClient = require('websocket').w3cwebsocket;\n\nconst closeError = new Error('WebSocket was closed');\n\nclass PromisedWebSockets {\n constructor(disconnectedCallback) {\n /* CONTEST\n this.isBrowser = typeof process === 'undefined' ||\n process.type === 'renderer' ||\n process.browser === true ||\n process.__nwjs\n\n */\n this.client = undefined;\n this.closed = true;\n this.disconnectedCallback = disconnectedCallback;\n }\n\n async readExactly(number) {\n let readData = Buffer.alloc(0);\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const thisTime = await this.read(number);\n readData = Buffer.concat([readData, thisTime]);\n number -= thisTime.length;\n if (!number) {\n return readData;\n }\n }\n }\n\n async read(number) {\n if (this.closed) {\n throw closeError;\n }\n await this.canRead;\n if (this.closed) {\n throw closeError;\n }\n const toReturn = this.stream.slice(0, number);\n this.stream = this.stream.slice(number);\n if (this.stream.length === 0) {\n this.canRead = new Promise((resolve) => {\n this.resolveRead = resolve;\n });\n }\n\n return toReturn;\n }\n\n async readAll() {\n if (this.closed || !await this.canRead) {\n throw closeError;\n }\n const toReturn = this.stream;\n this.stream = Buffer.alloc(0);\n this.canRead = new Promise((resolve) => {\n this.resolveRead = resolve;\n });\n\n return toReturn;\n }\n\n getWebSocketLink(ip, port, testServers) {\n if (port === 443) {\n return `wss://${ip}:${port}/apiws${testServers ? '_test' : ''}`;\n } else {\n return `ws://${ip}:${port}/apiws${testServers ? '_test' : ''}`;\n }\n }\n\n connect(port, ip, testServers = false) {\n this.stream = Buffer.alloc(0);\n this.canRead = new Promise((resolve) => {\n this.resolveRead = resolve;\n });\n this.closed = false;\n this.website = this.getWebSocketLink(ip, port, testServers);\n this.client = new WebSocketClient(this.website, 'binary');\n return new Promise((resolve, reject) => {\n this.client.onopen = () => {\n this.receive();\n resolve(this);\n };\n this.client.onerror = (error) => {\n // eslint-disable-next-line no-console\n console.error('WebSocket error', error);\n reject(error);\n };\n this.client.onclose = (event) => {\n const { code, reason, wasClean } = event;\n if (code !== 1000) {\n // eslint-disable-next-line no-console\n console.error(`Socket ${ip} closed. Code: ${code}, reason: ${reason}, was clean: ${wasClean}`);\n }\n\n this.resolveRead(false);\n this.closed = true;\n if (this.disconnectedCallback) {\n this.disconnectedCallback();\n }\n };\n // CONTEST\n // Seems to not be working, at least in a web worker\n // eslint-disable-next-line no-restricted-globals\n self.addEventListener('offline', async () => {\n await this.close();\n this.resolveRead(false);\n });\n });\n }\n\n write(data) {\n if (this.closed) {\n throw closeError;\n }\n this.client.send(data);\n }\n\n async close() {\n await this.client.close();\n this.closed = true;\n }\n\n receive() {\n this.client.onmessage = async (message) => {\n await mutex.runExclusive(async () => {\n const data = message.data instanceof ArrayBuffer\n ? Buffer.from(message.data)\n : Buffer.from(await new Response(message.data).arrayBuffer());\n this.stream = Buffer.concat([this.stream, data]);\n this.resolveRead(true);\n });\n };\n }\n}\n\nmodule.exports = PromisedWebSockets;\n","const Logger = require('./Logger');\nconst BinaryWriter = require('./BinaryWriter');\nconst BinaryReader = require('./BinaryReader');\nconst PromisedWebSockets = require('./PromisedWebSockets');\nconst MessagePacker = require('./MessagePacker');\nconst AsyncQueue = require('./AsyncQueue');\n\nmodule.exports = {\n BinaryWriter,\n BinaryReader,\n MessagePacker,\n AsyncQueue,\n Logger,\n PromisedWebSockets,\n};\n","const Api = require('./tl/api');\nconst TelegramClient = require('./client/TelegramClient');\nconst connection = require('./network');\nconst tl = require('./tl');\nconst version = require('./Version');\nconst events = require('./events');\nconst utils = require('./Utils');\nconst errors = require('./errors');\nconst sessions = require('./sessions');\nconst extensions = require('./extensions');\nconst helpers = require('./Helpers');\n\nmodule.exports = {\n Api,\n TelegramClient,\n sessions,\n connection,\n extensions,\n tl,\n version,\n events,\n utils,\n errors,\n helpers,\n};\n","import bigInt from 'big-integer';\nimport {\n generateRandomBytes,\n modExp,\n readBigIntFromBuffer,\n readBufferFromBigInt,\n sha1,\n} from '../Helpers';\n\nconst PUBLIC_KEYS = [\n {\n fingerprint: bigInt('-3414540481677951611'),\n n: bigInt(\n '2937959817066933702298617714945612856538843112005886376816255642404751219133084745514657634448776440866'\n + '1701890505066208632169112269581063774293102577308490531282748465986139880977280302242772832972539403531'\n + '3160108704012876427630091361567343395380424193887227773571344877461690935390938502512438971889287359033'\n + '8945177273024525306296338410881284207988753897636046529094613963869149149606209957083647645485599631919'\n + '2747663615955633778034897140982517446405334423701359108810182097749467210509584293428076654573384828809'\n + '574217079944388301239431309115013843331317877374435868468779972014486325557807783825502498215169806323',\n ),\n e: 65537,\n },\n {\n fingerprint: bigInt('-5595554452916591101'),\n n: bigInt(\n '2534288944884041556497168959071347320689884775908477905258202659454602246385394058588521595116849196570822' +\n '26493991806038180742006204637761354248846321625124031637930839216416315647409595294193595958529411668489405859523' +\n '37613333022396096584117954892216031229237302943701877588456738335398602461675225081791820393153757504952636234951' +\n '32323782003654358104782690612092797248736680529211579223142368426126233039432475078545094258975175539015664775146' +\n '07193514399690599495696153028090507215003302390050778898553239175099482557220816446894421272976054225797071426466' +\n '60768825302832201908302295573257427896031830742328565032949',\n ),\n e: 65537,\n },\n];\n\nexport const _serverKeys = new Map();\n\nPUBLIC_KEYS.forEach(({ fingerprint, ...keyInfo }) => {\n _serverKeys.set(fingerprint.toString(),\n keyInfo);\n});\n\n/**\n * Encrypts the given data known the fingerprint to be used\n * in the way Telegram requires us to do so (sha1(data) + data + padding)\n\n * @param fingerprint the fingerprint of the RSA key.\n * @param data the data to be encrypted.\n * @returns {Buffer|*|undefined} the cipher text, or undefined if no key matching this fingerprint is found.\n */\nexport async function encrypt(fingerprint: bigInt.BigInteger, data: Buffer) {\n const key = _serverKeys.get(fingerprint.toString());\n if (!key) {\n return undefined;\n }\n\n // len(sha1.digest) is always 20, so we're left with 255 - 20 - x padding\n const rand = generateRandomBytes(235 - data.length);\n\n const toEncrypt = Buffer.concat([await sha1(data), data, rand]);\n\n // rsa module rsa.encrypt adds 11 bits for padding which we don't want\n // rsa module uses rsa.transform.bytes2int(to_encrypt), easier way:\n const payload = readBigIntFromBuffer(toEncrypt, false);\n const encrypted = modExp(payload, bigInt(key.e), key.n);\n // rsa module uses transform.int2bytes(encrypted, keylength), easier:\n return readBufferFromBigInt(encrypted, 256, false);\n}\n","/**\n * Executes the authentication process with the Telegram servers.\n * @param sender a connected {MTProtoPlainSender}.\n * @param log\n * @returns {Promise<{authKey: *, timeOffset: *}>}\n */\n// eslint-disable-next-line import/no-named-default\nimport { default as Api } from '../tl/api';\nimport { SecurityError } from '../errors';\n// eslint-disable-next-line import/no-named-default\nimport { default as MTProtoPlainSender } from './MTProtoPlainSender';\nimport { _serverKeys } from '../crypto/RSA';\n\nconst bigInt = require('big-integer');\nconst IGE = require('../crypto/IGE');\nconst AuthKey = require('../crypto/AuthKey');\nconst Factorizator = require('../crypto/Factorizator');\nconst Helpers = require('../Helpers');\nconst BinaryReader = require('../extensions/BinaryReader');\n\nconst RETRIES = 20;\n\nexport async function doAuthentication(sender: MTProtoPlainSender, log: any) {\n // Step 1 sending: PQ Request, endianness doesn't matter since it's random\n let bytes = Helpers.generateRandomBytes(16);\n\n const nonce = Helpers.readBigIntFromBuffer(bytes, false, true);\n const resPQ = await sender.send(new Api.ReqPqMulti({ nonce }));\n log.debug('Starting authKey generation step 1');\n\n if (!(resPQ instanceof Api.ResPQ)) {\n throw new SecurityError(`Step 1 answer was ${resPQ}`);\n }\n if (resPQ.nonce.neq(nonce)) {\n throw new SecurityError('Step 1 invalid nonce from server');\n }\n const pq = Helpers.readBigIntFromBuffer(resPQ.pq, false, true);\n log.debug('Finished authKey generation step 1');\n // Step 2 sending: DH Exchange\n const { p, q } = Factorizator.factorize(pq);\n\n const pBuffer = Helpers.getByteArray(p);\n const qBuffer = Helpers.getByteArray(q);\n\n bytes = Helpers.generateRandomBytes(32);\n const newNonce = Helpers.readBigIntFromBuffer(bytes, true, true);\n const pqInnerData = new Api.PQInnerData({\n pq: Helpers.getByteArray(pq), // unsigned\n p: pBuffer,\n q: qBuffer,\n nonce: resPQ.nonce,\n serverNonce: resPQ.serverNonce,\n newNonce,\n }).getBytes();\n if (pqInnerData.length > 144) {\n throw new SecurityError('Step 1 invalid nonce from server');\n }\n let targetFingerprint;\n let targetKey;\n for (const fingerprint of resPQ.serverPublicKeyFingerprints) {\n targetKey = _serverKeys.get(fingerprint.toString());\n if (targetKey !== undefined) {\n targetFingerprint = fingerprint;\n break;\n }\n }\n if (targetFingerprint === undefined || targetKey === undefined) {\n throw new SecurityError(\n 'Step 2 could not find a valid key for fingerprints',\n );\n }\n // Value should be padded to be made 192 exactly\n const padding = Helpers.generateRandomBytes(192 - pqInnerData.length);\n const dataWithPadding = Buffer.concat([pqInnerData, padding]);\n const dataPadReversed = Buffer.from(dataWithPadding).reverse();\n\n let encryptedData;\n for (let i = 0; i < RETRIES; i++) {\n const tempKey = Helpers.generateRandomBytes(32);\n const shaDigestKeyWithData = await Helpers.sha256(Buffer.concat([tempKey, dataWithPadding]));\n const dataWithHash = Buffer.concat([dataPadReversed, shaDigestKeyWithData]);\n\n const ige = new IGE(tempKey, Buffer.alloc(32));\n const aesEncrypted = ige.encryptIge(dataWithHash);\n const tempKeyXor = Helpers.bufferXor(tempKey, await Helpers.sha256(aesEncrypted));\n\n const keyAesEncrypted = Buffer.concat([tempKeyXor, aesEncrypted]);\n const keyAesEncryptedInt = Helpers.readBigIntFromBuffer(keyAesEncrypted, false, false);\n if (keyAesEncryptedInt.greaterOrEquals(targetKey.n)) {\n log.debug('Aes key greater than RSA. retrying');\n continue;\n }\n const encryptedDataBuffer = Helpers.modExp(keyAesEncryptedInt, bigInt(targetKey.e), targetKey.n);\n encryptedData = Helpers.readBufferFromBigInt(encryptedDataBuffer, 256, false, false);\n\n break;\n }\n if (encryptedData === undefined) {\n throw new SecurityError(\n 'Step 2 could create a secure encrypted key',\n );\n }\n log.debug('Step 2 : Generated a secure aes encrypted data');\n\n const serverDhParams = await sender.send(\n new Api.ReqDHParams({\n nonce: resPQ.nonce,\n serverNonce: resPQ.serverNonce,\n p: pBuffer,\n q: qBuffer,\n publicKeyFingerprint: targetFingerprint,\n encryptedData,\n }),\n );\n\n if (\n !(\n serverDhParams instanceof Api.ServerDHParamsOk\n || serverDhParams instanceof Api.ServerDHParamsFail\n )\n ) {\n throw new Error(`Step 2.1 answer was ${serverDhParams}`);\n }\n if (serverDhParams.nonce.neq(resPQ.nonce)) {\n throw new SecurityError('Step 2 invalid nonce from server');\n }\n\n if (serverDhParams.serverNonce.neq(resPQ.serverNonce)) {\n throw new SecurityError('Step 2 invalid server nonce from server');\n }\n\n if (serverDhParams instanceof Api.ServerDHParamsFail) {\n const sh = await Helpers.sha1(\n Helpers.toSignedLittleBuffer(newNonce, 32).slice(4, 20),\n );\n const nnh = Helpers.readBigIntFromBuffer(sh, true, true);\n if (serverDhParams.newNonceHash.neq(nnh)) {\n throw new SecurityError('Step 2 invalid DH fail nonce from server');\n }\n }\n if (!(serverDhParams instanceof Api.ServerDHParamsOk)) {\n throw new Error(`Step 2.2 answer was ${serverDhParams}`);\n }\n log.debug('Finished authKey generation step 2');\n log.debug('Starting authKey generation step 3');\n\n // Step 3 sending: Complete DH Exchange\n const { key, iv } = await Helpers.generateKeyDataFromNonce(\n resPQ.serverNonce,\n newNonce,\n );\n if (serverDhParams.encryptedAnswer.length % 16 !== 0) {\n // See PR#453\n throw new SecurityError('Step 3 AES block size mismatch');\n }\n const ige = new IGE(key, iv);\n const plainTextAnswer = ige.decryptIge(serverDhParams.encryptedAnswer);\n const reader = new BinaryReader(plainTextAnswer);\n reader.read(20); // hash sum\n const serverDhInner = reader.tgReadObject();\n if (!(serverDhInner instanceof Api.ServerDHInnerData)) {\n throw new Error(`Step 3 answer was ${serverDhInner}`);\n }\n\n if (serverDhInner.nonce.neq(resPQ.nonce)) {\n throw new SecurityError('Step 3 Invalid nonce in encrypted answer');\n }\n if (serverDhInner.serverNonce.neq(resPQ.serverNonce)) {\n throw new SecurityError(\n 'Step 3 Invalid server nonce in encrypted answer',\n );\n }\n const dhPrime = Helpers.readBigIntFromBuffer(\n serverDhInner.dhPrime,\n false,\n false,\n );\n const ga = Helpers.readBigIntFromBuffer(serverDhInner.gA, false, false);\n const timeOffset = serverDhInner.serverTime - Math.floor(new Date().getTime() / 1000);\n const b = Helpers.readBigIntFromBuffer(\n Helpers.generateRandomBytes(256),\n false,\n false,\n );\n const gb = Helpers.modExp(bigInt(serverDhInner.g), b, dhPrime);\n const gab = Helpers.modExp(ga, b, dhPrime);\n\n // Prepare client DH Inner Data\n const clientDhInner = new Api.ClientDHInnerData({\n nonce: resPQ.nonce,\n serverNonce: resPQ.serverNonce,\n retryId: bigInt.zero, // TODO Actual retry ID\n gB: Helpers.getByteArray(gb, false),\n }).getBytes();\n\n const clientDdhInnerHashed = Buffer.concat([\n await Helpers.sha1(clientDhInner),\n clientDhInner,\n ]);\n // Encryption\n\n const clientDhEncrypted = ige.encryptIge(clientDdhInnerHashed);\n const dhGen = await sender.send(\n new Api.SetClientDHParams({\n nonce: resPQ.nonce,\n serverNonce: resPQ.serverNonce,\n encryptedData: clientDhEncrypted,\n }),\n );\n const nonceTypes = [Api.DhGenOk, Api.DhGenRetry, Api.DhGenFail];\n // TS being weird again.\n const nonceTypesString = ['DhGenOk', 'DhGenRetry', 'DhGenFail'];\n if (\n !(\n dhGen instanceof nonceTypes[0]\n || dhGen instanceof nonceTypes[1]\n || dhGen instanceof nonceTypes[2]\n )\n ) {\n throw new Error(`Step 3.1 answer was ${dhGen}`);\n }\n const { name } = dhGen.constructor;\n if (dhGen.nonce.neq(resPQ.nonce)) {\n throw new SecurityError(`Step 3 invalid ${name} nonce from server`);\n }\n if (dhGen.serverNonce.neq(resPQ.serverNonce)) {\n throw new SecurityError(\n `Step 3 invalid ${name} server nonce from server`,\n );\n }\n const authKey = new AuthKey();\n await authKey.setKey(Helpers.getByteArray(gab));\n\n const nonceNumber = 1 + nonceTypesString.indexOf(dhGen.className);\n\n const newNonceHash = await authKey.calcNewNonceHash(newNonce, nonceNumber);\n // @ts-ignore\n const dhHash = dhGen[`newNonceHash${nonceNumber}`];\n\n if (dhHash.neq(newNonceHash)) {\n throw new SecurityError('Step 3 invalid new nonce hash');\n }\n\n if (!(dhGen instanceof Api.DhGenOk)) {\n throw new Error(`Step 3.2 answer was ${dhGen}`);\n }\n log.debug('Finished authKey generation step 3');\n\n return { authKey, timeOffset };\n}\n","/**\n * This module contains the class used to communicate with Telegram's servers\n * in plain text, when no authorization key has been created yet.\n */\nconst BigInt = require('big-integer');\nconst MTProtoState = require('./MTProtoState');\nconst BinaryReader = require('../extensions/BinaryReader');\nconst { InvalidBufferError } = require('../errors/Common');\nconst { toSignedLittleBuffer } = require('../Helpers');\n\n/**\n * MTProto Mobile Protocol plain sender (https://core.telegram.org/mtproto/description#unencrypted-messages)\n */\n\nclass MTProtoPlainSender {\n /**\n * Initializes the MTProto plain sender.\n * @param connection connection: the Connection to be used.\n * @param loggers\n */\n constructor(connection, loggers) {\n this._state = new MTProtoState(connection, loggers);\n this._connection = connection;\n }\n\n /**\n * Sends and receives the result for the given request.\n * @param request\n */\n async send(request) {\n let body = request.getBytes();\n let msgId = this._state._getNewMsgId();\n const m = toSignedLittleBuffer(msgId, 8);\n const b = Buffer.alloc(4);\n b.writeInt32LE(body.length, 0);\n\n const res = Buffer.concat([Buffer.concat([Buffer.alloc(8), m, b]), body]);\n\n await this._connection.send(res);\n body = await this._connection.recv();\n if (body.length < 8) {\n throw new InvalidBufferError(body);\n }\n const reader = new BinaryReader(body);\n const authKeyId = reader.readLong();\n if (authKeyId.neq(BigInt(0))) {\n throw new Error('Bad authKeyId');\n }\n msgId = reader.readLong();\n if (msgId.eq(BigInt(0))) {\n throw new Error('Bad msgId');\n }\n /** ^ We should make sure that the read ``msg_id`` is greater\n * than our own ``msg_id``. However, under some circumstances\n * (bad system clock/working behind proxies) this seems to not\n * be the case, which would cause endless assertion errors.\n */\n\n const length = reader.readInt();\n if (length <= 0) {\n throw new Error('Bad length');\n }\n /**\n * We could read length bytes and use those in a new reader to read\n * the next TLObject without including the padding, but since the\n * reader isn't used for anything else after this, it's unnecessary.\n */\n return reader.tgReadObject();\n }\n}\n\nmodule.exports = MTProtoPlainSender;\n","const MtProtoPlainSender = require('./MTProtoPlainSender');\nconst MTProtoState = require('./MTProtoState');\nconst Helpers = require('../Helpers');\nconst AuthKey = require('../crypto/AuthKey');\nconst { doAuthentication } = require('./Authenticator');\nconst RPCResult = require('../tl/core/RPCResult');\nconst MessageContainer = require('../tl/core/MessageContainer');\nconst GZIPPacked = require('../tl/core/GZIPPacked');\nconst RequestState = require('./RequestState');\n\nconst {\n MsgsAck,\n upload,\n MsgsStateInfo,\n Pong,\n} = require('../tl').constructors;\nconst MessagePacker = require('../extensions/MessagePacker');\nconst BinaryReader = require('../extensions/BinaryReader');\nconst { UpdateConnectionState, UpdateServerTimeOffset } = require('./index');\nconst { BadMessageError } = require('../errors/Common');\nconst {\n BadServerSalt,\n BadMsgNotification,\n MsgDetailedInfo,\n MsgNewDetailedInfo,\n NewSessionCreated,\n FutureSalts,\n MsgsStateReq,\n MsgResendReq,\n MsgsAllInfo,\n} = require('../tl').constructors;\nconst { SecurityError } = require('../errors/Common');\nconst { InvalidBufferError } = require('../errors/Common');\nconst { LogOut } = require('../tl').requests.auth;\nconst { RPCMessageToError } = require('../errors');\nconst { TypeNotFoundError } = require('../errors/Common');\n\n/**\n * MTProto Mobile Protocol sender\n * (https://core.telegram.org/mtproto/description)\n * This class is responsible for wrapping requests into `TLMessage`'s,\n * sending them over the network and receiving them in a safe manner.\n *\n * Automatic reconnection due to temporary network issues is a concern\n * for this class as well, including retry of messages that could not\n * be sent successfully.\n *\n * A new authorization key will be generated on connection if no other\n * key exists yet.\n */\nclass MTProtoSender {\n static DEFAULT_OPTIONS = {\n logger: undefined,\n retries: Infinity,\n delay: 2000,\n autoReconnect: true,\n connectTimeout: undefined,\n authKeyCallback: undefined,\n updateCallback: undefined,\n autoReconnectCallback: undefined,\n isMainSender: undefined,\n onConnectionBreak: undefined,\n };\n\n /**\n * @param authKey\n * @param opts\n */\n constructor(authKey, opts) {\n const args = { ...MTProtoSender.DEFAULT_OPTIONS, ...opts };\n this._connection = undefined;\n this._log = args.logger;\n this._dcId = args.dcId;\n this._retries = args.retries;\n this._delay = args.delay;\n this._autoReconnect = args.autoReconnect;\n this._connectTimeout = args.connectTimeout;\n this._authKeyCallback = args.authKeyCallback;\n this._updateCallback = args.updateCallback;\n this._autoReconnectCallback = args.autoReconnectCallback;\n this._isMainSender = args.isMainSender;\n this._onConnectionBreak = args.onConnectionBreak;\n\n /**\n * whether we disconnected ourself or telegram did it.\n */\n this.userDisconnected = false;\n\n /**\n * Whether the user has explicitly connected or disconnected.\n *\n * If a disconnection happens for any other reason and it\n * was *not* user action then the pending messages won't\n * be cleared but on explicit user disconnection all the\n * pending futures should be cancelled.\n */\n this._user_connected = false;\n this._reconnecting = false;\n this._disconnected = true;\n\n /**\n * We need to join the loops upon disconnection\n */\n this._send_loop_handle = undefined;\n this._recv_loop_handle = undefined;\n\n /**\n * Preserving the references of the AuthKey and state is important\n */\n this.authKey = authKey || new AuthKey();\n this._state = new MTProtoState(this.authKey, this._log);\n\n /**\n * Outgoing messages are put in a queue and sent in a batch.\n * Note that here we're also storing their ``_RequestState``.\n */\n this._send_queue = new MessagePacker(this._state, this._log);\n\n /**\n * Sent states are remembered until a response is received.\n */\n this._pending_state = {};\n\n /**\n * Responses must be acknowledged, and we can also batch these.\n */\n this._pending_ack = new Set();\n\n /**\n * Similar to pending_messages but only for the last acknowledges.\n * These can't go in pending_messages because no acknowledge for them\n * is received, but we may still need to resend their state on bad salts.\n */\n this._last_acks = [];\n\n /**\n * Jump table from response ID to method that handles it\n */\n\n this._handlers = {\n [RPCResult.CONSTRUCTOR_ID]: this._handleRPCResult.bind(this),\n [MessageContainer.CONSTRUCTOR_ID]: this._handleContainer.bind(this),\n [GZIPPacked.CONSTRUCTOR_ID]: this._handleGzipPacked.bind(this),\n [Pong.CONSTRUCTOR_ID]: this._handlePong.bind(this),\n [BadServerSalt.CONSTRUCTOR_ID]: this._handleBadServerSalt.bind(this),\n [BadMsgNotification.CONSTRUCTOR_ID]: this._handleBadNotification.bind(this),\n [MsgDetailedInfo.CONSTRUCTOR_ID]: this._handleDetailedInfo.bind(this),\n [MsgNewDetailedInfo.CONSTRUCTOR_ID]: this._handleNewDetailedInfo.bind(this),\n [NewSessionCreated.CONSTRUCTOR_ID]: this._handleNewSessionCreated.bind(this),\n [MsgsAck.CONSTRUCTOR_ID]: this._handleAck.bind(this),\n [FutureSalts.CONSTRUCTOR_ID]: this._handleFutureSalts.bind(this),\n [MsgsStateReq.CONSTRUCTOR_ID]: this._handleStateForgotten.bind(this),\n [MsgResendReq.CONSTRUCTOR_ID]: this._handleStateForgotten.bind(this),\n [MsgsAllInfo.CONSTRUCTOR_ID]: this._handleMsgAll.bind(this),\n };\n }\n\n // Public API\n\n /**\n * Connects to the specified given connection using the given auth key.\n * @param connection\n * @param [force]\n * @returns {Promise}\n */\n async connect(connection, force) {\n if (this._user_connected && !force) {\n this._log.info('User is already connected!');\n return false;\n }\n this.isConnecting = true;\n this._connection = connection;\n\n for (let attempt = 0; attempt < this._retries; attempt++) {\n try {\n await this._connect();\n if (this._updateCallback) {\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.connected));\n }\n break;\n } catch (err) {\n if (this._updateCallback && attempt === 0) {\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.disconnected));\n }\n this._log.error(`WebSocket connection failed attempt: ${attempt + 1}`);\n // eslint-disable-next-line no-console\n console.error(err);\n await Helpers.sleep(this._delay);\n }\n }\n this.isConnecting = false;\n return true;\n }\n\n isConnected() {\n return this._user_connected;\n }\n\n /**\n * Cleanly disconnects the instance from the network, cancels\n * all pending requests, and closes the send and receive loops.\n */\n async disconnect() {\n this.userDisconnected = true;\n await this._disconnect();\n }\n\n /**\n *\n This method enqueues the given request to be sent. Its send\n state will be saved until a response arrives, and a ``Future``\n that will be resolved when the response arrives will be returned:\n\n .. code-block:: javascript\n\n async def method():\n # Sending (enqueued for the send loop)\n future = sender.send(request)\n # Receiving (waits for the receive loop to read the result)\n result = await future\n\n Designed like this because Telegram may send the response at\n any point, and it can send other items while one waits for it.\n Once the response for this future arrives, it is set with the\n received result, quite similar to how a ``receive()`` call\n would otherwise work.\n\n Since the receiving part is \"built in\" the future, it's\n impossible to await receive a result that was never sent.\n * @param request\n * @returns {RequestState}\n */\n send(request) {\n if (!this._user_connected) {\n throw new Error('Cannot send requests while disconnected');\n }\n const state = new RequestState(request);\n this._send_queue.append(state);\n return state.promise;\n }\n\n /**\n * Same as send but returns the full state. usefull for invoke after logic\n * @param request\n * @return {RequestState}\n */\n sendWithInvokeSupport(request) {\n if (!this._user_connected) {\n throw new Error('Cannot send requests while disconnected');\n }\n const state = new RequestState(request, undefined, this._pending_state);\n this._send_queue.append(state);\n return state;\n }\n\n /**\n * Performs the actual connection, retrying, generating the\n * authorization key if necessary, and starting the send and\n * receive loops.\n * @returns {Promise}\n * @private\n */\n async _connect() {\n this._log.info('Connecting to {0}...'.replace('{0}', this._connection));\n await this._connection.connect();\n this._log.debug('Connection success!');\n // process.exit(0)\n if (!this.authKey.getKey()) {\n const plain = new MtProtoPlainSender(this._connection, this._log);\n this._log.debug('New auth_key attempt ...');\n const res = await doAuthentication(plain, this._log);\n this._log.debug('Generated new auth_key successfully');\n await this.authKey.setKey(res.authKey);\n\n this._state.timeOffset = res.timeOffset;\n\n if (this._updateCallback) {\n this._updateCallback(new UpdateServerTimeOffset(this._state.timeOffset));\n }\n\n /**\n * This is *EXTREMELY* important since we don't control\n * external references to the authorization key, we must\n * notify whenever we change it. This is crucial when we\n * switch to different data centers.\n */\n if (this._authKeyCallback) {\n await this._authKeyCallback(this.authKey, this._dcId);\n }\n } else {\n this._authenticated = true;\n this._log.debug('Already have an auth key ...');\n }\n this._user_connected = true;\n this._reconnecting = false;\n\n this._log.debug('Starting send loop');\n this._send_loop_handle = this._sendLoop();\n\n this._log.debug('Starting receive loop');\n this._recv_loop_handle = this._recvLoop();\n\n // _disconnected only completes after manual disconnection\n // or errors after which the sender cannot continue such\n // as failing to reconnect or any unexpected error.\n\n this._log.info('Connection to %s complete!'.replace('%s', this._connection.toString()));\n }\n\n async _disconnect() {\n this._send_queue.rejectAll();\n\n if (this._connection === undefined) {\n this._log.info('Not disconnecting (already have no connection)');\n return;\n }\n if (this._updateCallback) {\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.disconnected));\n }\n this._log.info('Disconnecting from %s...'.replace('%s', this._connection.toString()));\n this._user_connected = false;\n this._log.debug('Closing current connection...');\n await this._connection.disconnect();\n }\n\n /**\n * This loop is responsible for popping items off the send\n * queue, encrypting them, and sending them over the network.\n * Besides `connect`, only this method ever sends data.\n * @returns {Promise}\n * @private\n */\n async _sendLoop() {\n this._send_queue = new MessagePacker(this._state, this._log);\n\n while (this._user_connected && !this._reconnecting) {\n if (this._pending_ack.size) {\n const ack = new RequestState(new MsgsAck({ msgIds: Array(...this._pending_ack) }));\n this._send_queue.append(ack);\n this._last_acks.push(ack);\n if (this._last_acks.length >= 10) {\n this._last_acks.shift();\n }\n this._pending_ack.clear();\n }\n this._log.debug(`Waiting for messages to send...${this._reconnecting}`);\n // TODO Wait for the connection send queue to be empty?\n // This means that while it's not empty we can wait for\n // more messages to be added to the send queue.\n const res = await this._send_queue.get();\n\n if (this._reconnecting) {\n return;\n }\n\n if (!res) {\n continue;\n }\n let { data } = res;\n const { batch } = res;\n this._log.debug(`Encrypting ${batch.length} message(s) in ${data.length} bytes for sending`);\n\n data = await this._state.encryptMessageData(data);\n\n try {\n await this._connection.send(data);\n } catch (e) {\n this._log.error(e);\n this._log.info('Connection closed while sending data');\n return;\n }\n for (const state of batch) {\n if (!Array.isArray(state)) {\n if (state.request.classType === 'request') {\n this._pending_state[state.msgId] = state;\n }\n } else {\n for (const s of state) {\n if (s.request.classType === 'request') {\n this._pending_state[s.msgId] = s;\n }\n }\n }\n }\n this._log.debug('Encrypted messages put in a queue to be sent');\n }\n }\n\n async _recvLoop() {\n let body;\n let message;\n\n while (this._user_connected && !this._reconnecting) {\n // this._log.debug('Receiving items from the network...');\n this._log.debug('Receiving items from the network...');\n try {\n body = await this._connection.recv();\n } catch (e) {\n // this._log.info('Connection closed while receiving data');\n /** when the server disconnects us we want to reconnect */\n if (!this.userDisconnected) {\n this._log.error(e);\n this._log.warn('Connection closed while receiving data');\n this.reconnect();\n }\n return;\n }\n try {\n message = await this._state.decryptMessageData(body);\n } catch (e) {\n if (e instanceof TypeNotFoundError) {\n // Received object which we don't know how to deserialize\n this._log.info(`Type ${e.invalidConstructorId} not found, remaining data ${e.remaining}`);\n continue;\n } else if (e instanceof SecurityError) {\n // A step while decoding had the incorrect data. This message\n // should not be considered safe and it should be ignored.\n this._log.warn(`Security error while unpacking a received message: ${e}`);\n continue;\n } else if (e instanceof InvalidBufferError) {\n // 404 means that the server has \"forgotten\" our auth key and we need to create a new one.\n if (e.code === 404) {\n this._log.warn(`Broken authorization key for dc ${this._dcId}; resetting`);\n if (this._updateCallback && this._isMainSender) {\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.broken));\n } else if (this._onConnectionBreak && !this._isMainSender) {\n // Deletes the current sender from the object\n this._onConnectionBreak(this._dcId);\n }\n } else {\n // this happens sometimes when telegram is having some internal issues.\n // reconnecting should be enough usually\n // since the data we sent and received is probably wrong now.\n this._log.warn(`Invalid buffer ${e.code} for dc ${this._dcId}`);\n this.reconnect();\n }\n return;\n } else {\n this._log.error('Unhandled error while receiving data');\n this._log.error(e);\n this.reconnect();\n return;\n }\n }\n try {\n await this._processMessage(message);\n } catch (e) {\n this._log.error('Unhandled error while receiving data');\n this._log.error(e);\n }\n }\n }\n\n // Response Handlers\n\n /**\n * Adds the given message to the list of messages that must be\n * acknowledged and dispatches control to different ``_handle_*``\n * method based on its type.\n * @param message\n * @returns {Promise}\n * @private\n */\n async _processMessage(message) {\n this._pending_ack.add(message.msgId);\n // eslint-disable-next-line require-atomic-updates\n message.obj = await message.obj;\n let handler = this._handlers[message.obj.CONSTRUCTOR_ID];\n if (!handler) {\n handler = this._handleUpdate.bind(this);\n }\n\n await handler(message);\n }\n\n /**\n * Pops the states known to match the given ID from pending messages.\n * This method should be used when the response isn't specific.\n * @param msgId\n * @returns {*[]}\n * @private\n */\n _popStates(msgId) {\n let state = this._pending_state[msgId];\n if (state) {\n this._pending_state[msgId].deferred.resolve();\n delete this._pending_state[msgId];\n return [state];\n }\n\n const toPop = [];\n\n for (state of Object.values(this._pending_state)) {\n if (state.containerId && state.containerId.equals(msgId)) {\n toPop.push(state.msgId);\n }\n }\n\n if (toPop.length) {\n const temp = [];\n for (const x of toPop) {\n temp.push(this._pending_state[x]);\n this._pending_state[x].deferred.resolve();\n delete this._pending_state[x];\n }\n return temp;\n }\n\n for (const ack of this._last_acks) {\n if (ack.msgId === msgId) {\n return [ack];\n }\n }\n\n return [];\n }\n\n /**\n * Handles the result for Remote Procedure Calls:\n * rpc_result#f35c6d01 req_msg_id:long result:bytes = RpcResult;\n * This is where the future results for sent requests are set.\n * @param message\n * @returns {Promise}\n * @private\n */\n _handleRPCResult(message) {\n const result = message.obj;\n const state = this._pending_state[result.reqMsgId];\n if (state) {\n state.deferred.resolve();\n delete this._pending_state[result.reqMsgId];\n }\n this._log.debug(`Handling RPC result for message ${result.reqMsgId}`);\n\n if (!state) {\n // TODO We should not get responses to things we never sent\n // However receiving a File() with empty bytes is \"common\".\n // See #658, #759 and #958. They seem to happen in a container\n // which contain the real response right after.\n try {\n const reader = new BinaryReader(result.body);\n if (!(reader.tgReadObject() instanceof upload.File)) {\n throw new TypeNotFoundError('Not an upload.File');\n }\n } catch (e) {\n this._log.error(e);\n if (e instanceof TypeNotFoundError) {\n this._log.info(`Received response without parent request: ${result.body}`);\n return;\n } else {\n throw e;\n }\n }\n }\n if (result.error) {\n // eslint-disable-next-line new-cap\n const error = RPCMessageToError(result.error, state.request);\n this._send_queue.append(new RequestState(new MsgsAck({ msgIds: [state.msgId] })));\n state.reject(error);\n } else {\n try {\n const reader = new BinaryReader(result.body);\n const read = state.request.readResult(reader);\n state.resolve(read);\n } catch (err) {\n state.reject(err);\n throw err;\n }\n }\n }\n\n /**\n * Processes the inner messages of a container with many of them:\n * msg_container#73f1f8dc messages:vector<%Message> = MessageContainer;\n * @param message\n * @returns {Promise}\n * @private\n */\n async _handleContainer(message) {\n this._log.debug('Handling container');\n for (const innerMessage of message.obj.messages) {\n await this._processMessage(innerMessage);\n }\n }\n\n /**\n * Unpacks the data from a gzipped object and processes it:\n * gzip_packed#3072cfa1 packed_data:bytes = Object;\n * @param message\n * @returns {Promise}\n * @private\n */\n async _handleGzipPacked(message) {\n this._log.debug('Handling gzipped data');\n const reader = new BinaryReader(message.obj.data);\n message.obj = reader.tgReadObject();\n await this._processMessage(message);\n }\n\n _handleUpdate(message) {\n if (message.obj.SUBCLASS_OF_ID !== 0x8af52aac) {\n // crc32(b'Updates')\n this._log.warn(`Note: ${message.obj.className} is not an update, not dispatching it`);\n return;\n }\n this._log.debug(`Handling update ${message.obj.className}`);\n if (this._updateCallback) {\n this._updateCallback(message.obj);\n }\n }\n\n /**\n * Handles pong results, which don't come inside a ``RPCResult``\n * but are still sent through a request:\n * pong#347773c5 msg_id:long ping_id:long = Pong;\n * @param message\n * @returns {Promise}\n * @private\n */\n _handlePong(message) {\n const pong = message.obj;\n\n const newTimeOffset = this._state.updateTimeOffset(message.msgId);\n if (this._updateCallback) {\n this._updateCallback(new UpdateServerTimeOffset(newTimeOffset));\n }\n\n this._log.debug(`Handling pong for message ${pong.msgId}`);\n const state = this._pending_state[pong.msgId];\n this._pending_state[pong.msgId].deferred.resolve();\n delete this._pending_state[pong.msgId];\n\n // Todo Check result\n if (state) {\n state.resolve(pong);\n }\n }\n\n /**\n * Corrects the currently used server salt to use the right value\n * before enqueuing the rejected message to be re-sent:\n * bad_server_salt#edab447b bad_msg_id:long bad_msg_seqno:int\n * error_code:int new_server_salt:long = BadMsgNotification;\n * @param message\n * @returns {Promise}\n * @private\n */\n _handleBadServerSalt(message) {\n const badSalt = message.obj;\n this._log.debug(`Handling bad salt for message ${badSalt.badMsgId}`);\n this._state.salt = badSalt.newServerSalt;\n const states = this._popStates(badSalt.badMsgId);\n this._send_queue.extend(states);\n this._log.debug(`${states.length} message(s) will be resent`);\n }\n\n /**\n * Adjusts the current state to be correct based on the\n * received bad message notification whenever possible:\n * bad_msg_notification#a7eff811 bad_msg_id:long bad_msg_seqno:int\n * error_code:int = BadMsgNotification;\n * @param message\n * @returns {Promise}\n * @private\n */\n _handleBadNotification(message) {\n const badMsg = message.obj;\n const states = this._popStates(badMsg.badMsgId);\n this._log.debug(`Handling bad msg ${JSON.stringify(badMsg)}`);\n if ([16, 17].includes(badMsg.errorCode)) {\n // Sent msg_id too low or too high (respectively).\n // Use the current msg_id to determine the right time offset.\n const newTimeOffset = this._state.updateTimeOffset(message.msgId);\n\n if (this._updateCallback) {\n this._updateCallback(new UpdateServerTimeOffset(newTimeOffset));\n }\n\n this._log.info(`System clock is wrong, set time offset to ${newTimeOffset}s`);\n } else if (badMsg.errorCode === 32) {\n // msg_seqno too low, so just pump it up by some \"large\" amount\n // TODO A better fix would be to start with a new fresh session ID\n this._state._sequence += 64;\n } else if (badMsg.errorCode === 33) {\n // msg_seqno too high never seems to happen but just in case\n this._state._sequence -= 16;\n } else {\n for (const state of states) {\n state.reject(new BadMessageError(state.request, badMsg.errorCode));\n }\n\n return;\n }\n // Messages are to be re-sent once we've corrected the issue\n this._send_queue.extend(states);\n this._log.debug(`${states.length} messages will be resent due to bad msg`);\n }\n\n /**\n * Updates the current status with the received detailed information:\n * msg_detailed_info#276d3ec6 msg_id:long answer_msg_id:long\n * bytes:int status:int = MsgDetailedInfo;\n * @param message\n * @returns {Promise}\n * @private\n */\n _handleDetailedInfo(message) {\n // TODO https://goo.gl/VvpCC6\n const msgId = message.obj.answerMsgId;\n this._log.debug(`Handling detailed info for message ${msgId}`);\n this._pending_ack.add(msgId);\n }\n\n /**\n * Updates the current status with the received detailed information:\n * msg_new_detailed_info#809db6df answer_msg_id:long\n * bytes:int status:int = MsgDetailedInfo;\n * @param message\n * @returns {Promise}\n * @private\n */\n _handleNewDetailedInfo(message) {\n // TODO https://goo.gl/VvpCC6\n const msgId = message.obj.answerMsgId;\n this._log.debug(`Handling new detailed info for message ${msgId}`);\n this._pending_ack.add(msgId);\n }\n\n /**\n * Updates the current status with the received session information:\n * new_session_created#9ec20908 first_msg_id:long unique_id:long\n * server_salt:long = NewSession;\n * @param message\n * @returns {Promise}\n * @private\n */\n _handleNewSessionCreated(message) {\n // TODO https://goo.gl/LMyN7A\n this._log.debug('Handling new session created');\n this._state.salt = message.obj.serverSalt;\n }\n\n /**\n * Handles a server acknowledge about our messages. Normally\n * these can be ignored except in the case of ``auth.logOut``:\n *\n * auth.logOut#5717da40 = Bool;\n *\n * Telegram doesn't seem to send its result so we need to confirm\n * it manually. No other request is known to have this behaviour.\n\n * Since the ID of sent messages consisting of a container is\n * never returned (unless on a bad notification), this method\n * also removes containers messages when any of their inner\n * messages are acknowledged.\n\n * @param message\n * @returns {Promise}\n * @private\n */\n _handleAck(message) {\n const ack = message.obj;\n this._log.debug(`Handling acknowledge for ${ack.msgIds}`);\n for (const msgId of ack.msgIds) {\n const state = this._pending_state[msgId];\n if (state && state.request instanceof LogOut) {\n this._pending_state[msgId].deferred.resolve();\n delete this._pending_state[msgId];\n state.resolve(true);\n }\n }\n }\n\n /**\n * Handles future salt results, which don't come inside a\n * ``rpc_result`` but are still sent through a request:\n * future_salts#ae500895 req_msg_id:long now:int\n * salts:vector = FutureSalts;\n * @param message\n * @returns {Promise}\n * @private\n */\n _handleFutureSalts(message) {\n // TODO save these salts and automatically adjust to the\n // correct one whenever the salt in use expires.\n this._log.debug(`Handling future salts for message ${message.msgId}`);\n const state = this._pending_state[message.msgId];\n\n if (state) {\n this._pending_state[message].deferred.resolve();\n delete this._pending_state[message];\n state.resolve(message.obj);\n }\n }\n\n /**\n * Handles both :tl:`MsgsStateReq` and :tl:`MsgResendReq` by\n * enqueuing a :tl:`MsgsStateInfo` to be sent at a later point.\n * @param message\n * @returns {Promise}\n * @private\n */\n _handleStateForgotten(message) {\n this._send_queue.append(\n new RequestState(new MsgsStateInfo(message.msgId, String.fromCharCode(1)\n .repeat(message.obj.msgIds))),\n );\n }\n\n /**\n * Handles :tl:`MsgsAllInfo` by doing nothing (yet).\n * used as part of the telegram protocol https://core.telegram.org/mtproto/service_messages_about_messages\n * This message does not require an acknowledgment.\n * @param message\n * @returns {Promise}\n * @private\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _handleMsgAll(message) {\n }\n\n reconnect() {\n if (this._user_connected && !this._reconnecting) {\n this._reconnecting = true;\n // TODO Should we set this?\n // this._user_connected = false\n // we want to wait a second between each reconnect try to not flood the server with reconnects\n // in case of internal server issues.\n Helpers.sleep(1000).then(() => {\n this._log.info('Started reconnecting');\n this._reconnect();\n });\n }\n }\n\n async _reconnect() {\n this._log.debug('Closing current connection...');\n try {\n await this._disconnect();\n } catch (err) {\n this._log.warn(err);\n }\n\n this._send_queue.append(undefined);\n this._state.reset();\n\n // For some reason reusing existing connection caused stuck requests\n const newConnection = new this._connection.constructor(\n this._connection._ip,\n this._connection._port,\n this._connection._dcId,\n this._connection._log,\n this._connection._testServers,\n );\n await this.connect(newConnection, true);\n\n this._reconnecting = false;\n // uncomment this if you want to resend\n // this._send_queue.extend(Object.values(this._pending_state))\n for (const state of Object.values(this._pending_state)) {\n state.deferred.resolve();\n }\n this._pending_state = {};\n if (this._autoReconnectCallback) {\n await this._autoReconnectCallback();\n }\n }\n}\n\nmodule.exports = MTProtoSender;\n","const BigInt = require('big-integer');\n\nconst Helpers = require('../Helpers');\nconst IGE = require('../crypto/IGE');\nconst BinaryReader = require('../extensions/BinaryReader');\nconst GZIPPacked = require('../tl/core/GZIPPacked');\nconst { TLMessage } = require('../tl/core');\nconst {\n SecurityError,\n InvalidBufferError,\n} = require('../errors/Common');\nconst { InvokeAfterMsg } = require('../tl').requests;\nconst {\n toSignedLittleBuffer,\n} = require('../Helpers');\n\nclass MTProtoState {\n /**\n *\n `telethon.network.mtprotosender.MTProtoSender` needs to hold a state\n in order to be able to encrypt and decrypt incoming/outgoing messages,\n as well as generating the message IDs. Instances of this class hold\n together all the required information.\n\n It doesn't make sense to use `telethon.sessions.abstract.Session` for\n the sender because the sender should *not* be concerned about storing\n this information to disk, as one may create as many senders as they\n desire to any other data center, or some CDN. Using the same session\n for all these is not a good idea as each need their own authkey, and\n the concept of \"copying\" sessions with the unnecessary entities or\n updates state for these connections doesn't make sense.\n\n While it would be possible to have a `MTProtoPlainState` that does no\n encryption so that it was usable through the `MTProtoLayer` and thus\n avoid the need for a `MTProtoPlainSender`, the `MTProtoLayer` is more\n focused to efficiency and this state is also more advanced (since it\n supports gzipping and invoking after other message IDs). There are too\n many methods that would be needed to make it convenient to use for the\n authentication process, at which point the `MTProtoPlainSender` is better\n * @param authKey\n * @param loggers\n */\n constructor(authKey, loggers) {\n this.authKey = authKey;\n this._log = loggers;\n this.timeOffset = 0;\n this.salt = 0;\n\n this.id = undefined;\n this._sequence = undefined;\n this._lastMsgId = undefined;\n this.reset();\n }\n\n /**\n * Resets the state\n */\n reset() {\n // Session IDs can be random on every connection\n this.id = Helpers.generateRandomLong(true);\n this._sequence = 0;\n this._lastMsgId = BigInt(0);\n }\n\n /**\n * Updates the message ID to a new one,\n * used when the time offset changed.\n * @param message\n */\n updateMessageId(message) {\n message.msgId = this._getNewMsgId();\n }\n\n /**\n * Calculate the key based on Telegram guidelines, specifying whether it's the client or not\n * @param authKey\n * @param msgKey\n * @param client\n * @returns {{iv: Buffer, key: Buffer}}\n */\n async _calcKey(authKey, msgKey, client) {\n const x = client === true ? 0 : 8;\n const [sha256a, sha256b] = await Promise.all([\n Helpers.sha256(Buffer.concat([msgKey, authKey.slice(x, x + 36)])),\n Helpers.sha256(Buffer.concat([authKey.slice(x + 40, x + 76), msgKey])),\n ]);\n const key = Buffer.concat([sha256a.slice(0, 8), sha256b.slice(8, 24), sha256a.slice(24, 32)]);\n const iv = Buffer.concat([sha256b.slice(0, 8), sha256a.slice(8, 24), sha256b.slice(24, 32)]);\n return {\n key,\n iv,\n };\n }\n\n /**\n * Writes a message containing the given data into buffer.\n * Returns the message id.\n * @param buffer\n * @param data\n * @param contentRelated\n * @param afterId\n */\n async writeDataAsMessage(buffer, data, contentRelated, afterId) {\n const msgId = this._getNewMsgId();\n const seqNo = this._getSeqNo(contentRelated);\n let body;\n if (!afterId) {\n body = await GZIPPacked.gzipIfSmaller(contentRelated, data);\n } else {\n // Invoke query expects a query with a getBytes func\n body = await GZIPPacked.gzipIfSmaller(contentRelated, new InvokeAfterMsg(afterId, {\n getBytes() {\n return data;\n },\n }).getBytes());\n }\n const s = Buffer.alloc(4);\n s.writeInt32LE(seqNo, 0);\n const b = Buffer.alloc(4);\n b.writeInt32LE(body.length, 0);\n const m = toSignedLittleBuffer(msgId, 8);\n buffer.write(Buffer.concat([m, s, b]));\n buffer.write(body);\n return msgId;\n }\n\n /**\n * Encrypts the given message data using the current authorization key\n * following MTProto 2.0 guidelines core.telegram.org/mtproto/description.\n * @param data\n */\n async encryptMessageData(data) {\n await this.authKey.waitForKey();\n const s = toSignedLittleBuffer(this.salt, 8);\n const i = toSignedLittleBuffer(this.id, 8);\n data = Buffer.concat([Buffer.concat([s, i]), data]);\n const padding = Helpers.generateRandomBytes(Helpers.mod(-(data.length + 12), 16) + 12);\n // Being substr(what, offset, length); x = 0 for client\n // \"msg_key_large = SHA256(substr(auth_key, 88+x, 32) + pt + padding)\"\n const msgKeyLarge = await Helpers.sha256(Buffer.concat([this.authKey.getKey()\n .slice(88, 88 + 32), data, padding]));\n // \"msg_key = substr (msg_key_large, 8, 16)\"\n const msgKey = msgKeyLarge.slice(8, 24);\n\n const {\n iv,\n key,\n } = await this._calcKey(this.authKey.getKey(), msgKey, true);\n\n const keyId = Helpers.readBufferFromBigInt(this.authKey.keyId, 8);\n return Buffer.concat([keyId, msgKey, new IGE(key, iv).encryptIge(Buffer.concat([data, padding]))]);\n }\n\n /**\n * Inverse of `encrypt_message_data` for incoming server messages.\n * @param body\n */\n async decryptMessageData(body) {\n if (body.length < 8) {\n throw new InvalidBufferError(body);\n }\n if (body.length < 0) { // length needs to be positive\n throw new SecurityError('Server replied with negative length');\n }\n if (body.length % 4 !== 0) {\n throw new SecurityError('Server replied with length not divisible by 4');\n }\n // TODO Check salt,sessionId, and sequenceNumber\n const keyId = Helpers.readBigIntFromBuffer(body.slice(0, 8));\n if (keyId.neq(this.authKey.keyId)) {\n throw new SecurityError('Server replied with an invalid auth key');\n }\n\n const msgKey = body.slice(8, 24);\n const {\n iv,\n key,\n } = await this._calcKey(this.authKey.getKey(), msgKey, false);\n body = new IGE(key, iv).decryptIge(body.slice(24));\n\n // https://core.telegram.org/mtproto/security_guidelines\n // Sections \"checking sha256 hash\" and \"message length\"\n\n const ourKey = await Helpers.sha256(Buffer.concat([this.authKey.getKey()\n .slice(96, 96 + 32), body]));\n\n if (!msgKey.equals(ourKey.slice(8, 24))) {\n throw new SecurityError('Received msg_key doesn\\'t match with expected one');\n }\n\n const reader = new BinaryReader(body);\n reader.readLong(); // removeSalt\n const serverId = reader.readLong();\n if (!serverId.eq(this.id)) {\n throw new SecurityError('Server replied with a wrong session ID');\n }\n\n const remoteMsgId = reader.readLong();\n const remoteSequence = reader.readInt();\n const containerLen = reader.readInt(); // msgLen for the inner object, padding ignored\n const diff = body.length - containerLen;\n // We want to check if it's between 12 and 1024\n // https://core.telegram.org/mtproto/security_guidelines#checking-message-length\n if (diff < 12 || diff > 1024) {\n throw new SecurityError('Server replied with the wrong message padding');\n }\n\n // We could read msg_len bytes and use those in a new reader to read\n // the next TLObject without including the padding, but since the\n // reader isn't used for anything else after this, it's unnecessary.\n const obj = reader.tgReadObject();\n\n return new TLMessage(remoteMsgId, remoteSequence, obj);\n }\n\n /**\n * Generates a new unique message ID based on the current\n * time (in ms) since epoch, applying a known time offset.\n * @private\n */\n _getNewMsgId() {\n const now = new Date().getTime() / 1000 + this.timeOffset;\n const nanoseconds = Math.floor((now - Math.floor(now)) * 1e9);\n let newMsgId = (BigInt(Math.floor(now))\n .shiftLeft(BigInt(32))).or(BigInt(nanoseconds)\n .shiftLeft(BigInt(2)));\n if (this._lastMsgId.greaterOrEquals(newMsgId)) {\n newMsgId = this._lastMsgId.add(BigInt(4));\n }\n this._lastMsgId = newMsgId;\n return newMsgId;\n }\n\n /**\n * Updates the time offset to the correct\n * one given a known valid message ID.\n * @param correctMsgId {BigInteger}\n */\n updateTimeOffset(correctMsgId) {\n const bad = this._getNewMsgId();\n const old = this.timeOffset;\n const now = Math.floor(new Date().getTime() / 1000);\n const correct = correctMsgId.shiftRight(BigInt(32));\n this.timeOffset = correct - now;\n\n if (this.timeOffset !== old) {\n this._lastMsgId = BigInt(0);\n this._log.debug(\n `Updated time offset (old offset ${old}, bad ${bad}, good ${correctMsgId}, new ${this.timeOffset})`,\n );\n }\n\n return this.timeOffset;\n }\n\n /**\n * Generates the next sequence number depending on whether\n * it should be for a content-related query or not.\n * @param contentRelated\n * @private\n */\n _getSeqNo(contentRelated) {\n if (contentRelated) {\n const result = this._sequence * 2 + 1;\n this._sequence += 1;\n return result;\n } else {\n return this._sequence * 2;\n }\n }\n}\n\nmodule.exports = MTProtoState;\n","const { createDeferred } = require('../Helpers');\n\nclass RequestState {\n constructor(request, after = undefined, pending = {}) {\n this.containerId = undefined;\n this.msgId = undefined;\n this.request = request;\n this.data = request.getBytes();\n this.after = after;\n this.result = undefined;\n this.pending = pending;\n this.deferred = createDeferred();\n this.promise = new Promise((resolve, reject) => {\n this.resolve = resolve;\n this.reject = reject;\n });\n }\n\n isReady() {\n const state = this.pending[this.after.id];\n if (!state) {\n return true;\n }\n return state.deferred.promise;\n }\n}\n\nmodule.exports = RequestState;\n","const PromisedWebSockets = require('../../extensions/PromisedWebSockets');\nconst AsyncQueue = require('../../extensions/AsyncQueue');\n\n/**\n * The `Connection` class is a wrapper around ``asyncio.open_connection``.\n *\n * Subclasses will implement different transport modes as atomic operations,\n * which this class eases doing since the exposed interface simply puts and\n * gets complete data payloads to and from queues.\n *\n * The only error that will raise from send and receive methods is\n * ``ConnectionError``, which will raise when attempting to send if\n * the client is disconnected (includes remote disconnections).\n */\nclass Connection {\n PacketCodecClass = undefined;\n\n constructor(ip, port, dcId, loggers, testServers) {\n this._ip = ip;\n this._port = port;\n this._dcId = dcId;\n this._log = loggers;\n this._testServers = testServers;\n this._connected = false;\n this._sendTask = undefined;\n this._recvTask = undefined;\n this._codec = undefined;\n this._obfuscation = undefined; // TcpObfuscated and MTProxy\n this._sendArray = new AsyncQueue();\n this._recvArray = new AsyncQueue();\n // this.socket = new PromiseSocket(new Socket())\n\n this.socket = new PromisedWebSockets(this.disconnectCallback.bind(this));\n }\n\n async disconnectCallback() {\n await this.disconnect(true);\n }\n\n async _connect() {\n this._log.debug('Connecting');\n this._codec = new this.PacketCodecClass(this);\n await this.socket.connect(this._port, this._ip, this._testServers);\n this._log.debug('Finished connecting');\n // await this.socket.connect({host: this._ip, port: this._port});\n await this._initConn();\n }\n\n async connect() {\n await this._connect();\n this._connected = true;\n\n if (!this._sendTask) {\n this._sendTask = this._sendLoop();\n }\n this._recvTask = this._recvLoop();\n }\n\n async disconnect(fromCallback = false) {\n if (!this._connected) {\n return;\n }\n\n this._connected = false;\n void this._recvArray.push(undefined);\n if (!fromCallback) {\n await this.socket.close();\n }\n }\n\n async send(data) {\n if (!this._connected) {\n throw new Error('Not connected');\n }\n await this._sendArray.push(data);\n }\n\n async recv() {\n while (this._connected) {\n const result = await this._recvArray.pop();\n // null = sentinel value = keep trying\n if (result) {\n return result;\n }\n }\n throw new Error('Not connected');\n }\n\n async _sendLoop() {\n // TODO handle errors\n try {\n while (this._connected) {\n const data = await this._sendArray.pop();\n if (!data) {\n this._sendTask = undefined;\n return;\n }\n await this._send(data);\n }\n } catch (e) {\n this._log.info('The server closed the connection while sending');\n }\n }\n\n async _recvLoop() {\n let data;\n while (this._connected) {\n try {\n data = await this._recv();\n if (!data) {\n throw new Error('no data received');\n }\n } catch (e) {\n this._log.info('connection closed');\n // await this._recvArray.push()\n\n this.disconnect();\n return;\n }\n await this._recvArray.push(data);\n }\n }\n\n async _initConn() {\n if (this._codec.tag) {\n await this.socket.write(this._codec.tag);\n }\n }\n\n _send(data) {\n const encodedPacket = this._codec.encodePacket(data);\n this.socket.write(encodedPacket);\n }\n\n _recv() {\n return this._codec.readPacket(this.socket);\n }\n\n toString() {\n return `${this._ip}:${this._port}/${this.constructor.name.replace('Connection', '')}`;\n }\n}\n\nclass ObfuscatedConnection extends Connection {\n ObfuscatedIO = undefined;\n\n _initConn() {\n this._obfuscation = new this.ObfuscatedIO(this);\n this.socket.write(this._obfuscation.header);\n }\n\n _send(data) {\n this._obfuscation.write(this._codec.encodePacket(data));\n }\n\n _recv() {\n return this._codec.readPacket(this._obfuscation);\n }\n}\n\nclass PacketCodec {\n constructor(connection) {\n this._conn = connection;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n encodePacket(data) {\n throw new Error('Not Implemented');\n\n // Override\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n readPacket(reader) {\n // override\n throw new Error('Not Implemented');\n }\n}\n\nmodule.exports = {\n Connection,\n PacketCodec,\n ObfuscatedConnection,\n};\n","const BigInt = require('big-integer');\nconst { readBufferFromBigInt } = require('../../Helpers');\nconst {\n Connection,\n PacketCodec,\n} = require('./Connection');\n\nclass AbridgedPacketCodec extends PacketCodec {\n static tag = Buffer.from('ef', 'hex');\n\n static obfuscateTag = Buffer.from('efefefef', 'hex');\n\n constructor(props) {\n super(props);\n this.tag = AbridgedPacketCodec.tag;\n this.obfuscateTag = AbridgedPacketCodec.obfuscateTag;\n }\n\n encodePacket(data) {\n let length = data.length >> 2;\n if (length < 127) {\n const b = Buffer.alloc(1);\n b.writeUInt8(length, 0);\n length = b;\n } else {\n length = Buffer.concat([Buffer.from('7f', 'hex'), readBufferFromBigInt(BigInt(length), 3)]);\n }\n return Buffer.concat([length, data]);\n }\n\n async readPacket(reader) {\n const readData = await reader.read(1);\n let length = readData[0];\n if (length >= 127) {\n length = Buffer.concat([await reader.read(3), Buffer.alloc(1)])\n .readInt32LE(0);\n }\n\n return reader.read(length << 2);\n }\n}\n\n/**\n * This is the mode with the lowest overhead, as it will\n * only require 1 byte if the packet length is less than\n * 508 bytes (127 << 2, which is very common).\n */\nclass ConnectionTCPAbridged extends Connection {\n PacketCodecClass = AbridgedPacketCodec;\n}\n\nmodule.exports = {\n ConnectionTCPAbridged,\n AbridgedPacketCodec,\n};\n","const { generateRandomBytes } = require('../../Helpers');\nconst { ObfuscatedConnection } = require('./Connection');\nconst { AbridgedPacketCodec } = require('./TCPAbridged');\nconst CTR = require('../../crypto/CTR');\n\nclass ObfuscatedIO {\n header = undefined;\n\n constructor(connection) {\n this.connection = connection.socket;\n const res = this.initHeader(connection.PacketCodecClass);\n this.header = res.random;\n\n this._encrypt = res.encryptor;\n this._decrypt = res.decryptor;\n }\n\n initHeader(packetCodec) {\n // Obfuscated messages secrets cannot start with any of these\n const keywords = [Buffer.from('50567247', 'hex'), Buffer.from('474554', 'hex'),\n Buffer.from('504f5354', 'hex'), Buffer.from('eeeeeeee', 'hex')];\n let random;\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n random = generateRandomBytes(64);\n if (random[0] !== 0xef && !(random.slice(4, 8)\n .equals(Buffer.alloc(4)))) {\n let ok = true;\n for (const key of keywords) {\n if (key.equals(random.slice(0, 4))) {\n ok = false;\n break;\n }\n }\n if (ok) {\n break;\n }\n }\n }\n random = random.toJSON().data;\n\n const randomReversed = Buffer.from(random.slice(8, 56))\n .reverse();\n // Encryption has \"continuous buffer\" enabled\n const encryptKey = Buffer.from(random.slice(8, 40));\n const encryptIv = Buffer.from(random.slice(40, 56));\n const decryptKey = Buffer.from(randomReversed.slice(0, 32));\n const decryptIv = Buffer.from(randomReversed.slice(32, 48));\n const encryptor = new CTR(encryptKey, encryptIv);\n const decryptor = new CTR(decryptKey, decryptIv);\n\n random = Buffer.concat([\n Buffer.from(random.slice(0, 56)), packetCodec.obfuscateTag, Buffer.from(random.slice(60)),\n ]);\n random = Buffer.concat([\n Buffer.from(random.slice(0, 56)), Buffer.from(encryptor.encrypt(random)\n .slice(56, 64)), Buffer.from(random.slice(64)),\n ]);\n return {\n random,\n encryptor,\n decryptor,\n };\n }\n\n async read(n) {\n const data = await this.connection.readExactly(n);\n return this._decrypt.encrypt(data);\n }\n\n write(data) {\n this.connection.write(this._encrypt.encrypt(data));\n }\n}\n\nclass ConnectionTCPObfuscated extends ObfuscatedConnection {\n ObfuscatedIO = ObfuscatedIO;\n\n PacketCodecClass = AbridgedPacketCodec;\n}\n\nmodule.exports = {\n ConnectionTCPObfuscated,\n};\n","const { Connection } = require('./Connection');\nconst { ConnectionTCPFull } = require('./TCPFull');\nconst { ConnectionTCPAbridged } = require('./TCPAbridged');\nconst { ConnectionTCPObfuscated } = require('./TCPObfuscated');\n\nmodule.exports = {\n Connection,\n ConnectionTCPFull,\n ConnectionTCPAbridged,\n ConnectionTCPObfuscated,\n};\n","const MTProtoPlainSender = require('./MTProtoPlainSender');\nconst MTProtoSender = require('./MTProtoSender');\n\nclass UpdateConnectionState {\n static disconnected = -1;\n\n static connected = 1;\n\n static broken = 0;\n\n constructor(state) {\n this.state = state;\n }\n}\n\nclass UpdateServerTimeOffset {\n constructor(timeOffset) {\n this.timeOffset = timeOffset;\n }\n}\n\nconst {\n Connection,\n ConnectionTCPFull,\n ConnectionTCPAbridged,\n ConnectionTCPObfuscated,\n} = require('./connection');\n\nmodule.exports = {\n Connection,\n ConnectionTCPFull,\n ConnectionTCPAbridged,\n ConnectionTCPObfuscated,\n MTProtoPlainSender,\n MTProtoSender,\n UpdateConnectionState,\n UpdateServerTimeOffset,\n};\n","class Session {\n /**\n * Creates a clone of this session file\n * @param toInstance {Session|null}\n * @returns {Session}\n */\n\n /* CONTEST\n clone(toInstance = null) {\n return toInstance || new this.constructor()\n } */\n\n /**\n * Returns the currently-used data center ID.\n */\n get dcId() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Returns the server address where the library should connect to.\n */\n get serverAddress() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Returns the port to which the library should connect to.\n */\n get port() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Returns an ``AuthKey`` instance associated with the saved\n * data center, or `None` if a new one should be generated.\n */\n get authKey() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Sets the ``AuthKey`` to be used for the saved data center.\n * @param value\n */\n set authKey(value) {\n throw new Error('Not Implemented');\n }\n\n /**\n * Sets the information of the data center address and port that\n * the library should connect to, as well as the data center ID,\n * which is currently unused.\n * @param dcId {number}\n * @param serverAddress {string}\n * @param port {number}\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n setDC(dcId, serverAddress, port) {\n throw new Error('Not implemented');\n }\n\n /**\n * Returns an ID of the takeout process initialized for this session,\n * or `None` if there's no were any unfinished takeout requests.\n */\n /* CONTEST\n get takeoutId() {\n throw new Error('Not Implemented')\n }\n */\n /**\n * Sets the ID of the unfinished takeout process for this session.\n * @param value\n */\n /* CONTEST\n set takeoutId(value) {\n throw new Error('Not Implemented')\n }\n */\n /**\n * Returns the ``UpdateState`` associated with the given `entity_id`.\n * If the `entity_id` is 0, it should return the ``UpdateState`` for\n * no specific channel (the \"general\" state). If no state is known\n * it should ``return None``.\n * @param entityId\n */\n /* CONTEST\n getUpdateState(entityId) {\n throw new Error('Not Implemented')\n }\n\n */\n\n /**\n * Sets the given ``UpdateState`` for the specified `entity_id`, which\n * should be 0 if the ``UpdateState`` is the \"general\" state (and not\n * for any specific channel).\n * @param entityId\n * @param state\n */\n /* CONTEST\n setUpdateState(entityId, state) {\n throw new Error('Not Implemented')\n }\n\n */\n\n /**\n * Called on client disconnection. Should be used to\n * free any used resources. Can be left empty if none.\n */\n\n /* CONTEST\n close() {\n\n }\n\n */\n\n /**\n * called whenever important properties change. It should\n * make persist the relevant session information to disk.\n */\n save() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Called upon client.log_out(). Should delete the stored\n * information from disk since it's not valid anymore.\n */\n\n delete() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Lists available sessions. Not used by the library itself.\n */\n /* CONTEST\n listSessions() {\n throw new Error('Not Implemented')\n }\n\n */\n\n /**\n * Processes the input ``TLObject`` or ``list`` and saves\n * whatever information is relevant (e.g., ID or access hash).\n * @param tlo\n */\n /* CONTEST\n processEntities(tlo) {\n throw new Error('Not Implemented')\n }\n\n */\n\n /**\n * Turns the given key into an ``InputPeer`` (e.g. ``InputPeerUser``).\n * The library uses this method whenever an ``InputPeer`` is needed\n * to suit several purposes (e.g. user only provided its ID or wishes\n * to use a cached username to avoid extra RPC).\n */\n /* CONTEST\n getInputEntity(key) {\n throw new Error('Not Implemented')\n }\n\n */\n}\n\nmodule.exports = Session;\n","/* eslint-disable no-restricted-globals */\nconst StorageSession = require('./StorageSession');\n\nconst CACHE_NAME = 'GramJs';\n\nclass CacheApiSession extends StorageSession {\n async _delete() {\n const request = new Request(this._storageKey);\n const cache = await self.caches.open(CACHE_NAME);\n return cache.delete(request);\n }\n\n async _fetchFromCache() {\n const request = new Request(this._storageKey);\n const cache = await self.caches.open(CACHE_NAME);\n const cached = await cache.match(request);\n return cached ? cached.text() : undefined;\n }\n\n async _saveToCache(data) {\n const request = new Request(this._storageKey);\n const response = new Response(data);\n const cache = await self.caches.open(CACHE_NAME);\n return cache.put(request, response);\n }\n}\n\nmodule.exports = CacheApiSession;\n","const MemorySession = require('./Memory');\nconst AuthKey = require('../crypto/AuthKey');\nconst utils = require('../Utils');\n\nclass CallbackSession extends MemorySession {\n constructor(sessionData, callback) {\n super();\n\n this._sessionData = sessionData;\n this._callback = callback;\n\n this._authKeys = {};\n }\n\n get authKey() {\n throw new Error('Not supported');\n }\n\n set authKey(value) {\n throw new Error('Not supported');\n }\n\n async load() {\n if (!this._sessionData) {\n return;\n }\n\n const {\n mainDcId,\n keys,\n hashes,\n } = this._sessionData;\n const {\n ipAddress,\n port,\n } = utils.getDC(mainDcId);\n\n this.setDC(mainDcId, ipAddress, port, true);\n\n await Promise.all(Object.keys(keys)\n .map(async (dcId) => {\n const key = typeof keys[dcId] === 'string'\n ? Buffer.from(keys[dcId], 'hex')\n : Buffer.from(keys[dcId]);\n\n if (hashes[dcId]) {\n const hash = typeof hashes[dcId] === 'string'\n ? Buffer.from(hashes[dcId], 'hex')\n : Buffer.from(hashes[dcId]);\n\n this._authKeys[dcId] = new AuthKey(key, hash);\n } else {\n this._authKeys[dcId] = new AuthKey();\n await this._authKeys[dcId].setKey(key, true);\n }\n }));\n }\n\n setDC(dcId, serverAddress, port, skipOnUpdate = false) {\n this._dcId = dcId;\n this._serverAddress = serverAddress;\n this._port = port;\n\n delete this._authKeys[dcId];\n\n if (!skipOnUpdate) {\n void this._onUpdate();\n }\n }\n\n getAuthKey(dcId = this._dcId) {\n return this._authKeys[dcId];\n }\n\n setAuthKey(authKey, dcId = this._dcId) {\n this._authKeys[dcId] = authKey;\n\n void this._onUpdate();\n }\n\n getSessionData() {\n const sessionData = {\n mainDcId: this._dcId,\n keys: {},\n hashes: {},\n };\n\n Object\n .keys(this._authKeys)\n .forEach((dcId) => {\n const authKey = this._authKeys[dcId];\n if (!authKey || !authKey._key) return;\n\n sessionData.keys[dcId] = authKey._key.toString('hex');\n sessionData.hashes[dcId] = authKey._hash.toString('hex');\n });\n\n return sessionData;\n }\n\n _onUpdate() {\n this._callback(this.getSessionData());\n }\n\n delete() {\n this._callback(undefined);\n }\n}\n\nmodule.exports = CallbackSession;\n","const idb = require('idb-keyval');\nconst StorageSession = require('./StorageSession');\n\nconst CACHE_NAME = 'GramJs';\n\nclass IdbSession extends StorageSession {\n _delete() {\n return idb.del(`${CACHE_NAME}:${this._storageKey}`);\n }\n\n _fetchFromCache() {\n return idb.get(`${CACHE_NAME}:${this._storageKey}`);\n }\n\n _saveToCache(data) {\n return idb.set(`${CACHE_NAME}:${this._storageKey}`, data);\n }\n}\n\nmodule.exports = IdbSession;\n","const StorageSession = require('./StorageSession');\n\nclass LocalStorageSession extends StorageSession {\n _delete() {\n return localStorage.removeItem(this._storageKey);\n }\n\n _fetchFromCache() {\n return localStorage.getItem(this._storageKey);\n }\n\n _saveToCache(data) {\n return localStorage.setItem(this._storageKey, data);\n }\n}\n\nmodule.exports = LocalStorageSession;\n","const Session = require('./Abstract');\n\nclass MemorySession extends Session {\n constructor() {\n super();\n\n this._serverAddress = undefined;\n this._dcId = 0;\n this._port = undefined;\n this._takeoutId = undefined;\n\n this._entities = new Set();\n this._updateStates = {};\n }\n\n get dcId() {\n return this._dcId;\n }\n\n get serverAddress() {\n return this._serverAddress;\n }\n\n get port() {\n return this._port;\n }\n\n get authKey() {\n return this._authKey;\n }\n\n set authKey(value) {\n this._authKey = value;\n }\n\n setDC(dcId, serverAddress, port) {\n this._dcId = dcId | 0;\n this._serverAddress = serverAddress;\n this._port = port;\n }\n\n /* CONTEST\n get takeoutId() {\n return this._takeoutId\n }\n\n set takeoutId(value) {\n this._takeoutId = value\n }\n\n\n getUpdateState(entityId) {\n return this._updateStates[entityId]\n }\n\n setUpdateState(entityId, state) {\n return this._updateStates[entityId] = state\n }\n\n close() {\n }\n\n save() {\n }\n\n async load() {\n\n }\n\n delete() {\n }\n\n _entityValuesToRow(id, hash, username, phone, name) {\n // While this is a simple implementation it might be overrode by,\n // other classes so they don't need to implement the plural form\n // of the method. Don't remove.\n return [id, hash, username, phone, name]\n }\n\n _entityToRow(e) {\n if (!(e.classType === \"constructor\")) {\n return\n }\n let p\n let markedId\n try {\n p = utils.getInputPeer(e, false)\n markedId = utils.getPeerId(p)\n } catch (e) {\n // Note: `get_input_peer` already checks for non-zero `accessHash`.\n // See issues #354 and #392. It also checks that the entity\n // is not `min`, because its `accessHash` cannot be used\n // anywhere (since layer 102, there are two access hashes).\n return\n }\n let pHash\n if (p instanceof types.InputPeerUser || p instanceof types.InputPeerChannel) {\n pHash = p.accessHash\n } else if (p instanceof types.InputPeerChat) {\n pHash = 0\n } else {\n return\n }\n\n let username = e.username\n if (username) {\n username = username.toLowerCase()\n }\n const phone = e.phone\n const name = utils.getDisplayName(e)\n return this._entityValuesToRow(markedId, pHash, username, phone, name)\n }\n\n _entitiesToRows(tlo) {\n let entities = []\n if (tlo.classType === \"constructor\" && utils.isListLike(tlo)) {\n // This may be a list of users already for instance\n entities = tlo\n } else {\n if (tlo instanceof Object) {\n if ('user' in tlo) {\n entities.push(tlo.user)\n }\n if ('chats' in tlo && utils.isListLike(tlo.chats)) {\n entities.concat(tlo.chats)\n }\n if ('users' in tlo && utils.isListLike(tlo.users)) {\n entities.concat(tlo.users)\n }\n }\n }\n const rows = [] // Rows to add (id, hash, username, phone, name)\n for (const e of entities) {\n const row = this._entityToRow(e)\n if (row) {\n rows.push(row)\n }\n }\n return rows\n }\n\n processEntities(tlo) {\n const entitiesSet = this._entitiesToRows(tlo)\n for (const e of entitiesSet) {\n this._entities.add(e)\n }\n }\n\n getEntityRowsByPhone(phone) {\n for (const e of this._entities) { // id, hash, username, phone, name\n if (e[3] === phone) {\n return [e[0], e[1]]\n }\n }\n }\n\n getEntityRowsByUsername(username) {\n for (const e of this._entities) { // id, hash, username, phone, name\n if (e[2] === username) {\n return [e[0], e[1]]\n }\n }\n }\n\n getEntityRowsByName(name) {\n for (const e of this._entities) { // id, hash, username, phone, name\n if (e[4] === name) {\n return [e[0], e[1]]\n }\n }\n }\n\n getEntityRowsById(id, exact = true) {\n if (exact) {\n for (const e of this._entities) { // id, hash, username, phone, name\n if (e[0] === id) {\n return [e[0], e[1]]\n }\n }\n } else {\n const ids = [utils.getPeerId(new types.PeerUser({ userId: id })),\n utils.getPeerId(new types.PeerChat({ chatId: id })),\n utils.getPeerId(new types.PeerChannel({ channelId: id })),\n ]\n for (const e of this._entities) { // id, hash, username, phone, name\n if (ids.includes(e[0])) {\n return [e[0], e[1]]\n }\n }\n }\n }\n\n getInputEntity(key) {\n let exact\n if (key.SUBCLASS_OF_ID !== undefined) {\n if ([0xc91c90b6, 0xe669bf46, 0x40f202fd].includes(key.SUBCLASS_OF_ID)) {\n // hex(crc32(b'InputPeer', b'InputUser' and b'InputChannel'))\n // We already have an Input version, so nothing else required\n return key\n }\n // Try to early return if this key can be casted as input peer\n return utils.getInputPeer(key)\n } else {\n // Not a TLObject or can't be cast into InputPeer\n if (key.classType === 'constructor') {\n key = utils.getPeerId(key)\n exact = true\n } else {\n exact = !(typeof key == 'number') || key < 0\n }\n }\n let result = null\n if (typeof key === 'string') {\n const phone = utils.parsePhone(key)\n if (phone) {\n result = this.getEntityRowsByPhone(phone)\n } else {\n const { username, isInvite } = utils.parseUsername(key)\n if (username && !isInvite) {\n result = this.getEntityRowsByUsername(username)\n } else {\n const tup = utils.resolveInviteLink(key)[1]\n if (tup) {\n result = this.getEntityRowsById(tup, false)\n }\n }\n }\n } else if (typeof key === 'number') {\n result = this.getEntityRowsById(key, exact)\n }\n if (!result && typeof key === 'string') {\n result = this.getEntityRowsByName(key)\n }\n\n if (result) {\n let entityId = result[0] // unpack resulting tuple\n const entityHash = result[1]\n const resolved = utils.resolveId(entityId)\n entityId = resolved[0]\n const kind = resolved[1]\n // removes the mark and returns type of entity\n if (kind === types.PeerUser) {\n return new types.InputPeerUser({ userId: entityId, accessHash: entityHash })\n } else if (kind === types.PeerChat) {\n return new types.InputPeerChat({ chatId: entityId })\n } else if (kind === types.PeerChannel) {\n return new types.InputPeerChannel({ channelId: entityId, accessHash: entityHash })\n }\n } else {\n throw new Error('Could not find input entity with key ' + key)\n }\n } */\n}\n\nmodule.exports = MemorySession;\n","const MemorySession = require('./Memory');\nconst AuthKey = require('../crypto/AuthKey');\nconst utils = require('../Utils');\n\nconst STORAGE_KEY_BASE = 'GramJs-session-';\nconst SESSION_DATA_PREFIX = 'session:';\n\nclass StorageSession extends MemorySession {\n constructor(sessionInfo) {\n super();\n\n this._authKeys = {};\n\n if (sessionInfo && sessionInfo.startsWith(SESSION_DATA_PREFIX)) {\n this._sessionString = sessionInfo;\n } else if (sessionInfo) {\n this._storageKey = sessionInfo;\n }\n }\n\n get authKey() {\n throw new Error('Not supported');\n }\n\n set authKey(value) {\n throw new Error('Not supported');\n }\n\n async load() {\n if (this._sessionString) {\n await this._loadFromSessionString();\n return;\n }\n\n if (!this._storageKey) {\n return;\n }\n\n try {\n const json = await this._fetchFromCache();\n const {\n mainDcId,\n keys,\n hashes,\n } = JSON.parse(json);\n const {\n ipAddress,\n port,\n } = utils.getDC(mainDcId);\n\n this.setDC(mainDcId, ipAddress, port, true);\n\n Object.keys(keys)\n .forEach((dcId) => {\n if (keys[dcId] && hashes[dcId]) {\n this._authKeys[dcId] = new AuthKey(\n Buffer.from(keys[dcId].data),\n Buffer.from(hashes[dcId].data),\n );\n }\n });\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn('Failed to retrieve or parse session from storage');\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n }\n\n setDC(dcId, serverAddress, port, skipUpdateStorage = false) {\n this._dcId = dcId;\n this._serverAddress = serverAddress;\n this._port = port;\n\n delete this._authKeys[dcId];\n\n if (!skipUpdateStorage) {\n void this._updateStorage();\n }\n }\n\n async save() {\n if (!this._storageKey) {\n this._storageKey = generateStorageKey();\n }\n\n await this._updateStorage();\n\n return this._storageKey;\n }\n\n getAuthKey(dcId = this._dcId) {\n return this._authKeys[dcId];\n }\n\n setAuthKey(authKey, dcId = this._dcId) {\n this._authKeys[dcId] = authKey;\n\n void this._updateStorage();\n }\n\n getSessionData(asHex) {\n const sessionData = {\n mainDcId: this._dcId,\n keys: {},\n hashes: {},\n };\n\n Object\n .keys(this._authKeys)\n .forEach((dcId) => {\n const authKey = this._authKeys[dcId];\n if (!authKey._key) return;\n\n sessionData.keys[dcId] = asHex ? authKey._key.toString('hex') : authKey._key;\n sessionData.hashes[dcId] = asHex ? authKey._hash.toString('hex') : authKey._hash;\n });\n\n return sessionData;\n }\n\n async _loadFromSessionString() {\n const [, mainDcIdStr, mainDcKey] = this._sessionString.split(':');\n const mainDcId = Number(mainDcIdStr);\n const {\n ipAddress,\n port,\n } = utils.getDC(mainDcId);\n this.setDC(mainDcId, ipAddress, port);\n const authKey = new AuthKey();\n await authKey.setKey(Buffer.from(mainDcKey, 'hex'), true);\n this.setAuthKey(authKey, mainDcId);\n }\n\n async _updateStorage() {\n if (!this._storageKey) {\n return;\n }\n\n try {\n await this._saveToCache(JSON.stringify(this.getSessionData()));\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn('Failed to update session in storage');\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n }\n\n async delete() {\n try {\n return await this._delete();\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn('Failed to delete session from storage');\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n return undefined;\n }\n\n // @abstract\n _delete() {\n throw new Error('Not Implemented');\n }\n\n // @abstract\n _fetchFromCache() {\n throw new Error('Not Implemented');\n }\n\n // @abstract\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _saveToCache(data) {\n throw new Error('Not Implemented');\n }\n}\n\nfunction generateStorageKey() {\n // Creating two sessions at the same moment is not expected nor supported.\n return `${STORAGE_KEY_BASE}${Date.now()}`;\n}\n\nmodule.exports = StorageSession;\n","const MemorySession = require('./Memory');\nconst AuthKey = require('../crypto/AuthKey');\nconst BinaryReader = require('../extensions/BinaryReader');\n\nconst CURRENT_VERSION = '1';\n\n\nclass StringSession extends MemorySession {\n /**\n * This session file can be easily saved and loaded as a string. According\n * to the initial design, it contains only the data that is necessary for\n * successful connection and authentication, so takeout ID is not stored.\n\n * It is thought to be used where you don't want to create any on-disk\n * files but would still like to be able to save and load existing sessions\n * by other means.\n\n * You can use custom `encode` and `decode` functions, if present:\n\n * `encode` definition must be ``function encode(value: Buffer) -> string:``.\n * `decode` definition must be ``function decode(value: string) -> Buffer:``.\n * @param session {string|null}\n */\n constructor(session = undefined) {\n super();\n if (session) {\n if (session[0] !== CURRENT_VERSION) {\n throw new Error('Not a valid string');\n }\n session = session.slice(1);\n const r = StringSession.decode(session);\n const reader = new BinaryReader(r);\n this._dcId = reader.read(1)\n .readUInt8(0);\n const serverAddressLen = reader.read(2)\n .readInt16BE(0);\n this._serverAddress = String(reader.read(serverAddressLen));\n this._port = reader.read(2)\n .readInt16BE(0);\n this._key = reader.read(-1);\n }\n }\n\n /**\n * @param x {Buffer}\n * @returns {string}\n */\n static encode(x) {\n return x.toString('base64');\n }\n\n /**\n * @param x {string}\n * @returns {Buffer}\n */\n static decode(x) {\n return Buffer.from(x, 'base64');\n }\n\n async load() {\n if (this._key) {\n this._authKey = new AuthKey();\n await this._authKey.setKey(this._key);\n }\n }\n\n save() {\n if (!this.authKey) {\n return '';\n }\n const dcBuffer = Buffer.from([this.dcId]);\n const addressBuffer = Buffer.from(this.serverAddress);\n const addressLengthBuffer = Buffer.alloc(2);\n addressLengthBuffer.writeInt16BE(addressBuffer.length, 0);\n const portBuffer = Buffer.alloc(2);\n portBuffer.writeInt16BE(this.port, 0);\n\n return CURRENT_VERSION + StringSession.encode(Buffer.concat([\n dcBuffer,\n addressLengthBuffer,\n addressBuffer,\n portBuffer,\n this.authKey.getKey(),\n ]));\n }\n\n getAuthKey(dcId) {\n if (dcId && dcId !== this.dcId) {\n // Not supported.\n return undefined;\n }\n\n return this.authKey;\n }\n\n setAuthKey(authKey, dcId) {\n if (dcId && dcId !== this.dcId) {\n // Not supported.\n return;\n }\n\n this.authKey = authKey;\n }\n}\n\nmodule.exports = StringSession;\n","const Memory = require('./Memory');\nconst StringSession = require('./StringSession');\nconst CacheApiSession = require('./CacheApiSession');\nconst LocalStorageSession = require('./LocalStorageSession');\nconst IdbSession = require('./IdbSession');\nconst CallbackSession = require('./CallbackSession');\n\nmodule.exports = {\n Memory,\n StringSession,\n CacheApiSession,\n LocalStorageSession,\n IdbSession,\n CallbackSession,\n};\n","const api = require('./api');\n\nconst LAYER = 133;\nconst tlobjects = {};\n\nfor (const tl of Object.values(api)) {\n if (tl.CONSTRUCTOR_ID) {\n tlobjects[tl.CONSTRUCTOR_ID] = tl;\n } else {\n for (const sub of Object.values(tl)) {\n tlobjects[sub.CONSTRUCTOR_ID] = sub;\n }\n }\n}\n\nmodule.exports = {\n LAYER,\n tlobjects,\n};\n","const {\n parseTl,\n serializeBytes,\n serializeDate,\n} = require('./generationHelpers');\nconst {\n toSignedLittleBuffer,\n} = require('../Helpers');\n\nconst tlContent = require('./apiTl.js');\nconst schemeContent = require('./schemaTl.js');\n\n/* CONTEST\nconst NAMED_AUTO_CASTS = new Set([\n 'chatId,int'\n])\nconst NAMED_BLACKLIST = new Set([\n 'discardEncryption'\n])\nconst AUTO_CASTS = new Set([\n 'InputPeer',\n 'InputChannel',\n 'InputUser',\n 'InputDialogPeer',\n 'InputNotifyPeer',\n 'InputMedia',\n 'InputPhoto',\n 'InputMessage',\n 'InputDocument',\n 'InputChatPhoto'\n])\n\n */\n// eslint-disable-next-line no-restricted-globals\nconst CACHING_SUPPORTED = typeof self !== 'undefined' && self.localStorage !== undefined;\n\nconst CACHE_KEY = 'GramJs:apiCache';\n\nfunction buildApiFromTlSchema() {\n let definitions;\n const fromCache = CACHING_SUPPORTED && loadFromCache();\n\n if (fromCache) {\n definitions = fromCache;\n } else {\n definitions = loadFromTlSchemas();\n\n if (CACHING_SUPPORTED) {\n localStorage.setItem(CACHE_KEY, JSON.stringify(definitions));\n }\n }\n\n return mergeWithNamespaces(\n createClasses('constructor', definitions.constructors),\n createClasses('request', definitions.requests),\n );\n}\n\nfunction loadFromCache() {\n const jsonCache = localStorage.getItem(CACHE_KEY);\n return jsonCache && JSON.parse(jsonCache);\n}\n\nfunction loadFromTlSchemas() {\n const [constructorParamsApi, functionParamsApi] = extractParams(tlContent);\n const [constructorParamsSchema, functionParamsSchema] = extractParams(schemeContent);\n const constructors = [].concat(constructorParamsApi, constructorParamsSchema);\n const requests = [].concat(functionParamsApi, functionParamsSchema);\n\n return {\n constructors,\n requests,\n };\n}\n\nfunction mergeWithNamespaces(obj1, obj2) {\n const result = { ...obj1 };\n\n Object.keys(obj2)\n .forEach((key) => {\n if (typeof obj2[key] === 'function' || !result[key]) {\n result[key] = obj2[key];\n } else {\n Object.assign(result[key], obj2[key]);\n }\n });\n\n return result;\n}\n\nfunction extractParams(fileContent) {\n const f = parseTl(fileContent, 109);\n const constructors = [];\n const functions = [];\n for (const d of f) {\n if (d.isFunction) {\n functions.push(d);\n } else {\n constructors.push(d);\n }\n }\n return [constructors, functions];\n}\n\nfunction argToBytes(x, type) {\n switch (type) {\n case 'int': {\n const i = Buffer.alloc(4);\n i.writeInt32LE(x, 0);\n return i;\n }\n case 'long':\n return toSignedLittleBuffer(x, 8);\n case 'int128':\n return toSignedLittleBuffer(x, 16);\n case 'int256':\n return toSignedLittleBuffer(x, 32);\n case 'double': {\n const d = Buffer.alloc(8);\n d.writeDoubleLE(x, 0);\n return d;\n }\n case 'string':\n return serializeBytes(x);\n case 'Bool':\n return x ? Buffer.from('b5757299', 'hex') : Buffer.from('379779bc', 'hex');\n case 'true':\n return Buffer.alloc(0);\n case 'bytes':\n return serializeBytes(x);\n case 'date':\n return serializeDate(x);\n default:\n return x.getBytes();\n }\n}\n\n/*\nCONTEST\nasync function getInputFromResolve(utils, client, peer, peerType) {\n switch (peerType) {\n case 'InputPeer':\n return utils.getInputPeer(await client.getInputEntity(peer))\n case 'InputChannel':\n return utils.getInputChannel(await client.getInputEntity(peer))\n case 'InputUser':\n return utils.getInputUser(await client.getInputEntity(peer))\n case 'InputDialogPeer':\n return await client._getInputDialog(peer)\n case 'InputNotifyPeer':\n return await client._getInputNotify(peer)\n case 'InputMedia':\n return utils.getInputMedia(peer)\n case 'InputPhoto':\n return utils.getInputPhoto(peer)\n case 'InputMessage':\n return utils.getInputMessage(peer)\n case 'InputDocument':\n return utils.getInputDocument(peer)\n case 'InputChatPhoto':\n return utils.getInputChatPhoto(peer)\n case 'chatId,int' :\n return await client.getPeerId(peer, false)\n default:\n throw new Error('unsupported peer type : ' + peerType)\n }\n}\n*/\nfunction getArgFromReader(reader, arg) {\n if (arg.isVector) {\n if (arg.useVectorId) {\n reader.readInt();\n }\n const temp = [];\n const len = reader.readInt();\n arg.isVector = false;\n for (let i = 0; i < len; i++) {\n temp.push(getArgFromReader(reader, arg));\n }\n arg.isVector = true;\n return temp;\n } else if (arg.flagIndicator) {\n return reader.readInt();\n } else {\n switch (arg.type) {\n case 'int':\n return reader.readInt();\n case 'long':\n return reader.readLong();\n case 'int128':\n return reader.readLargeInt(128);\n case 'int256':\n return reader.readLargeInt(256);\n case 'double':\n return reader.readDouble();\n case 'string':\n return reader.tgReadString();\n case 'Bool':\n return reader.tgReadBool();\n case 'true':\n return true;\n case 'bytes':\n return reader.tgReadBytes();\n case 'date':\n return reader.tgReadDate();\n default:\n if (!arg.skipConstructorId) {\n return reader.tgReadObject();\n } else {\n throw new Error(`Unknown type ${arg}`);\n }\n }\n }\n}\n\nfunction createClasses(classesType, params) {\n const classes = {};\n for (const classParams of params) {\n const {\n name,\n constructorId,\n subclassOfId,\n argsConfig,\n namespace,\n result,\n } = classParams;\n const fullName = [namespace, name].join('.')\n .replace(/^\\./, '');\n\n class VirtualClass {\n static CONSTRUCTOR_ID = constructorId;\n\n static SUBCLASS_OF_ID = subclassOfId;\n\n static className = fullName;\n\n static classType = classesType;\n\n CONSTRUCTOR_ID = constructorId;\n\n SUBCLASS_OF_ID = subclassOfId;\n\n className = fullName;\n\n classType = classesType;\n\n constructor(args) {\n args = args || {};\n Object.keys(args)\n .forEach((argName) => {\n this[argName] = args[argName];\n });\n }\n\n static fromReader(reader) {\n const args = {};\n\n for (const argName in argsConfig) {\n if (argsConfig.hasOwnProperty(argName)) {\n const arg = argsConfig[argName];\n if (arg.isFlag) {\n if (arg.type === 'true') {\n args[argName] = Boolean(args.flags & (1 << arg.flagIndex));\n continue;\n }\n if (args.flags & (1 << arg.flagIndex)) {\n args[argName] = getArgFromReader(reader, arg);\n } else {\n args[argName] = undefined;\n }\n } else {\n if (arg.flagIndicator) {\n arg.name = 'flags';\n }\n args[argName] = getArgFromReader(reader, arg);\n }\n }\n }\n return new VirtualClass(args);\n }\n\n getBytes() {\n // The next is pseudo-code:\n const idForBytes = this.CONSTRUCTOR_ID;\n const c = Buffer.alloc(4);\n c.writeUInt32LE(idForBytes, 0);\n const buffers = [c];\n for (const arg in argsConfig) {\n if (argsConfig.hasOwnProperty(arg)) {\n if (argsConfig[arg].isFlag) {\n if ((this[arg] === false && argsConfig[arg].type === 'true')\n || this[arg] === undefined) {\n continue;\n }\n }\n if (argsConfig[arg].isVector) {\n if (argsConfig[arg].useVectorId) {\n buffers.push(Buffer.from('15c4b51c', 'hex'));\n }\n const l = Buffer.alloc(4);\n l.writeInt32LE(this[arg].length, 0);\n buffers.push(l, Buffer.concat(this[arg].map((x) => argToBytes(x, argsConfig[arg].type))));\n } else if (argsConfig[arg].flagIndicator) {\n if (!Object.values(argsConfig)\n .some((f) => f.isFlag)) {\n buffers.push(Buffer.alloc(4));\n } else {\n let flagCalculate = 0;\n for (const f in argsConfig) {\n if (argsConfig[f].isFlag) {\n if ((this[f] === false && argsConfig[f].type === 'true')\n || this[f] === undefined) {\n flagCalculate |= 0;\n } else {\n flagCalculate |= 1 << argsConfig[f].flagIndex;\n }\n }\n }\n const f = Buffer.alloc(4);\n f.writeUInt32LE(flagCalculate, 0);\n buffers.push(f);\n }\n } else {\n buffers.push(argToBytes(this[arg], argsConfig[arg].type));\n\n if (this[arg] && typeof this[arg].getBytes === 'function') {\n let boxed = (argsConfig[arg].type.charAt(argsConfig[arg].type.indexOf('.') + 1));\n boxed = boxed === boxed.toUpperCase();\n if (!boxed) {\n buffers.shift();\n }\n }\n }\n }\n }\n return Buffer.concat(buffers);\n }\n\n readResult(reader) {\n if (classesType !== 'request') {\n throw new Error('`readResult()` called for non-request instance');\n }\n\n const m = result.match(/Vector<(int|long)>/);\n if (m) {\n reader.readInt();\n const temp = [];\n const len = reader.readInt();\n if (m[1] === 'int') {\n for (let i = 0; i < len; i++) {\n temp.push(reader.readInt());\n }\n } else {\n for (let i = 0; i < len; i++) {\n temp.push(reader.readLong());\n }\n }\n return temp;\n } else {\n return reader.tgReadObject();\n }\n }\n\n /* CONTEST\n async resolve(client, utils) {\n\n if (classesType !== 'request') {\n throw new Error('`resolve()` called for non-request instance')\n }\n\n for (const arg in argsConfig) {\n if (argsConfig.hasOwnProperty(arg)) {\n if (!AUTO_CASTS.has(argsConfig[arg].type)) {\n if (!NAMED_AUTO_CASTS.has(`${argsConfig[arg].name},${argsConfig[arg].type}`)) {\n continue\n }\n }\n if (argsConfig[arg].isFlag) {\n if (!this[arg]) {\n continue\n }\n }\n if (argsConfig[arg].isVector) {\n const temp = []\n for (const x of this[arg]) {\n temp.push(await getInputFromResolve(utils, client, x, argsConfig[arg].type))\n }\n this[arg] = temp\n } else {\n this[arg] = await getInputFromResolve(utils, client, this[arg], argsConfig[arg].type)\n }\n }\n }\n } */\n }\n\n if (namespace) {\n if (!classes[namespace]) {\n classes[namespace] = {};\n }\n classes[namespace][name] = VirtualClass;\n } else {\n classes[name] = VirtualClass;\n }\n }\n\n return classes;\n}\n\nmodule.exports = buildApiFromTlSchema();\n","module.exports = `boolFalse#bc799737 = Bool;\nboolTrue#997275b5 = Bool;\ntrue#3fedd339 = True;\nvector#1cb5c415 {t:Type} # [ t ] = Vector t;\nerror#c4b9f9bb code:int text:string = Error;\nnull#56730bcc = Null;\ninputPeerEmpty#7f3b18ea = InputPeer;\ninputPeerSelf#7da07ec9 = InputPeer;\ninputPeerChat#35a95cb9 chat_id:long = InputPeer;\ninputPeerUser#dde8a54c user_id:long access_hash:long = InputPeer;\ninputPeerChannel#27bcbbfc channel_id:long access_hash:long = InputPeer;\ninputPeerUserFromMessage#a87b0a1c peer:InputPeer msg_id:int user_id:long = InputPeer;\ninputPeerChannelFromMessage#bd2a0840 peer:InputPeer msg_id:int channel_id:long = InputPeer;\ninputUserEmpty#b98886cf = InputUser;\ninputUserSelf#f7c1b13f = InputUser;\ninputUser#f21158c6 user_id:long access_hash:long = InputUser;\ninputUserFromMessage#1da448e2 peer:InputPeer msg_id:int user_id:long = InputUser;\ninputPhoneContact#f392b7f4 client_id:long phone:string first_name:string last_name:string = InputContact;\ninputFile#f52ff27f id:long parts:int name:string md5_checksum:string = InputFile;\ninputFileBig#fa4f0bb5 id:long parts:int name:string = InputFile;\ninputMediaEmpty#9664f57f = InputMedia;\ninputMediaUploadedPhoto#1e287d04 flags:# file:InputFile stickers:flags.0?Vector ttl_seconds:flags.1?int = InputMedia;\ninputMediaPhoto#b3ba0635 flags:# id:InputPhoto ttl_seconds:flags.0?int = InputMedia;\ninputMediaGeoPoint#f9c44144 geo_point:InputGeoPoint = InputMedia;\ninputMediaContact#f8ab7dfb phone_number:string first_name:string last_name:string vcard:string = InputMedia;\ninputMediaUploadedDocument#5b38c6c1 flags:# nosound_video:flags.3?true force_file:flags.4?true file:InputFile thumb:flags.2?InputFile mime_type:string attributes:Vector stickers:flags.0?Vector ttl_seconds:flags.1?int = InputMedia;\ninputMediaDocument#33473058 flags:# id:InputDocument ttl_seconds:flags.0?int query:flags.1?string = InputMedia;\ninputMediaVenue#c13d1c11 geo_point:InputGeoPoint title:string address:string provider:string venue_id:string venue_type:string = InputMedia;\ninputMediaPhotoExternal#e5bbfe1a flags:# url:string ttl_seconds:flags.0?int = InputMedia;\ninputMediaDocumentExternal#fb52dc99 flags:# url:string ttl_seconds:flags.0?int = InputMedia;\ninputMediaGame#d33f43f3 id:InputGame = InputMedia;\ninputMediaInvoice#d9799874 flags:# title:string description:string photo:flags.0?InputWebDocument invoice:Invoice payload:bytes provider:string provider_data:DataJSON start_param:flags.1?string = InputMedia;\ninputMediaGeoLive#971fa843 flags:# stopped:flags.0?true geo_point:InputGeoPoint heading:flags.2?int period:flags.1?int proximity_notification_radius:flags.3?int = InputMedia;\ninputMediaPoll#f94e5f1 flags:# poll:Poll correct_answers:flags.0?Vector solution:flags.1?string solution_entities:flags.1?Vector = InputMedia;\ninputMediaDice#e66fbf7b emoticon:string = InputMedia;\ninputChatPhotoEmpty#1ca48f57 = InputChatPhoto;\ninputChatUploadedPhoto#c642724e flags:# file:flags.0?InputFile video:flags.1?InputFile video_start_ts:flags.2?double = InputChatPhoto;\ninputChatPhoto#8953ad37 id:InputPhoto = InputChatPhoto;\ninputGeoPointEmpty#e4c123d6 = InputGeoPoint;\ninputGeoPoint#48222faf flags:# lat:double long:double accuracy_radius:flags.0?int = InputGeoPoint;\ninputPhotoEmpty#1cd7bf0d = InputPhoto;\ninputPhoto#3bb3b94a id:long access_hash:long file_reference:bytes = InputPhoto;\ninputFileLocation#dfdaabe1 volume_id:long local_id:int secret:long file_reference:bytes = InputFileLocation;\ninputEncryptedFileLocation#f5235d55 id:long access_hash:long = InputFileLocation;\ninputDocumentFileLocation#bad07584 id:long access_hash:long file_reference:bytes thumb_size:string = InputFileLocation;\ninputSecureFileLocation#cbc7ee28 id:long access_hash:long = InputFileLocation;\ninputTakeoutFileLocation#29be5899 = InputFileLocation;\ninputPhotoFileLocation#40181ffe id:long access_hash:long file_reference:bytes thumb_size:string = InputFileLocation;\ninputPhotoLegacyFileLocation#d83466f3 id:long access_hash:long file_reference:bytes volume_id:long local_id:int secret:long = InputFileLocation;\ninputPeerPhotoFileLocation#37257e99 flags:# big:flags.0?true peer:InputPeer photo_id:long = InputFileLocation;\ninputStickerSetThumb#9d84f3db stickerset:InputStickerSet thumb_version:int = InputFileLocation;\ninputGroupCallStream#598a92a flags:# call:InputGroupCall time_ms:long scale:int video_channel:flags.0?int video_quality:flags.0?int = InputFileLocation;\npeerUser#59511722 user_id:long = Peer;\npeerChat#36c6019a chat_id:long = Peer;\npeerChannel#a2a5371e channel_id:long = Peer;\nstorage.fileUnknown#aa963b05 = storage.FileType;\nstorage.filePartial#40bc6f52 = storage.FileType;\nstorage.fileJpeg#7efe0e = storage.FileType;\nstorage.fileGif#cae1aadf = storage.FileType;\nstorage.filePng#a4f63c0 = storage.FileType;\nstorage.filePdf#ae1e508d = storage.FileType;\nstorage.fileMp3#528a0677 = storage.FileType;\nstorage.fileMov#4b09ebbc = storage.FileType;\nstorage.fileMp4#b3cea0e4 = storage.FileType;\nstorage.fileWebp#1081464c = storage.FileType;\nuserEmpty#d3bc4b7a id:long = User;\nuser#3ff6ecb0 flags:# self:flags.10?true contact:flags.11?true mutual_contact:flags.12?true deleted:flags.13?true bot:flags.14?true bot_chat_history:flags.15?true bot_nochats:flags.16?true verified:flags.17?true restricted:flags.18?true min:flags.20?true bot_inline_geo:flags.21?true support:flags.23?true scam:flags.24?true apply_min_photo:flags.25?true fake:flags.26?true id:long access_hash:flags.0?long first_name:flags.1?string last_name:flags.2?string username:flags.3?string phone:flags.4?string photo:flags.5?UserProfilePhoto status:flags.6?UserStatus bot_info_version:flags.14?int restriction_reason:flags.18?Vector bot_inline_placeholder:flags.19?string lang_code:flags.22?string = User;\nuserProfilePhotoEmpty#4f11bae1 = UserProfilePhoto;\nuserProfilePhoto#82d1f706 flags:# has_video:flags.0?true photo_id:long stripped_thumb:flags.1?bytes dc_id:int = UserProfilePhoto;\nuserStatusEmpty#9d05049 = UserStatus;\nuserStatusOnline#edb93949 expires:int = UserStatus;\nuserStatusOffline#8c703f was_online:int = UserStatus;\nuserStatusRecently#e26f42f1 = UserStatus;\nuserStatusLastWeek#7bf09fc = UserStatus;\nuserStatusLastMonth#77ebc742 = UserStatus;\nchatEmpty#29562865 id:long = Chat;\nchat#41cbf256 flags:# creator:flags.0?true kicked:flags.1?true left:flags.2?true deactivated:flags.5?true call_active:flags.23?true call_not_empty:flags.24?true 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 id:long access_hash:flags.13?long title:string username:flags.6?string photo:ChatPhoto date:int restriction_reason:flags.9?Vector admin_rights:flags.14?ChatAdminRights banned_rights:flags.15?ChatBannedRights default_banned_rights:flags.18?ChatBannedRights participants_count:flags.17?int = Chat;\nchannelForbidden#17d493d5 flags:# broadcast:flags.5?true megagroup:flags.8?true id:long access_hash:long title:string until_date:flags.16?int = Chat;\nchatFull#4dbdc099 flags:# can_set_username:flags.7?true has_scheduled:flags.8?true id:long about:string participants:ChatParticipants chat_photo:flags.2?Photo notify_settings:PeerNotifySettings exported_invite:flags.13?ExportedChatInvite bot_info:flags.3?Vector pinned_msg_id:flags.6?int folder_id:flags.11?int call:flags.12?InputGroupCall ttl_period:flags.14?int groupcall_default_join_as:flags.15?Peer theme_emoticon:flags.16?string = ChatFull;\nchannelFull#e9b27a17 flags:# can_view_participants:flags.3?true can_set_username:flags.6?true can_set_stickers:flags.7?true hidden_prehistory:flags.10?true can_set_location:flags.16?true has_scheduled:flags.19?true can_view_stats:flags.20?true blocked:flags.22?true id:long about:string participants_count:flags.0?int admins_count:flags.1?int kicked_count:flags.2?int banned_count:flags.2?int online_count:flags.13?int read_inbox_max_id:int read_outbox_max_id:int unread_count:int chat_photo:Photo notify_settings:PeerNotifySettings exported_invite:flags.23?ExportedChatInvite bot_info:Vector migrated_from_chat_id:flags.4?long migrated_from_max_id:flags.4?int pinned_msg_id:flags.5?int stickerset:flags.8?StickerSet available_min_id:flags.9?int folder_id:flags.11?int linked_chat_id:flags.14?long location:flags.15?ChannelLocation slowmode_seconds:flags.17?int slowmode_next_send_date:flags.18?int stats_dc:flags.12?int pts:int call:flags.21?InputGroupCall ttl_period:flags.24?int pending_suggestions:flags.25?Vector groupcall_default_join_as:flags.26?Peer theme_emoticon:flags.27?string = ChatFull;\nchatParticipant#c02d4007 user_id:long inviter_id:long date:int = ChatParticipant;\nchatParticipantCreator#e46bcee4 user_id:long = ChatParticipant;\nchatParticipantAdmin#a0933f5b user_id:long inviter_id:long date:int = ChatParticipant;\nchatParticipantsForbidden#8763d3e1 flags:# chat_id:long self_participant:flags.0?ChatParticipant = ChatParticipants;\nchatParticipants#3cbc93f8 chat_id:long participants:Vector version:int = ChatParticipants;\nchatPhotoEmpty#37c1011c = ChatPhoto;\nchatPhoto#1c6e1c11 flags:# has_video:flags.0?true photo_id:long stripped_thumb:flags.1?bytes dc_id:int = ChatPhoto;\nmessageEmpty#90a6ca84 flags:# id:int peer_id:flags.0?Peer = Message;\nmessage#85d6cbe2 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true post:flags.14?true from_scheduled:flags.18?true legacy:flags.19?true edit_hide:flags.21?true pinned:flags.24?true id:int from_id:flags.8?Peer peer_id:Peer fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?long reply_to:flags.3?MessageReplyHeader date:int message:string media:flags.9?MessageMedia reply_markup:flags.6?ReplyMarkup entities:flags.7?Vector views:flags.10?int forwards:flags.10?int replies:flags.23?MessageReplies edit_date:flags.15?int post_author:flags.16?string grouped_id:flags.17?long restriction_reason:flags.22?Vector ttl_period:flags.25?int = Message;\nmessageService#2b085862 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true post:flags.14?true legacy:flags.19?true id:int from_id:flags.8?Peer peer_id:Peer reply_to:flags.3?MessageReplyHeader date:int action:MessageAction ttl_period:flags.25?int = Message;\nmessageMediaEmpty#3ded6320 = MessageMedia;\nmessageMediaPhoto#695150d7 flags:# photo:flags.0?Photo ttl_seconds:flags.2?int = MessageMedia;\nmessageMediaGeo#56e0d474 geo:GeoPoint = MessageMedia;\nmessageMediaContact#70322949 phone_number:string first_name:string last_name:string vcard:string user_id:long = MessageMedia;\nmessageMediaUnsupported#9f84f49e = MessageMedia;\nmessageMediaDocument#9cb070d7 flags:# document:flags.0?Document ttl_seconds:flags.2?int = MessageMedia;\nmessageMediaWebPage#a32dd600 webpage:WebPage = MessageMedia;\nmessageMediaVenue#2ec0533f geo:GeoPoint title:string address:string provider:string venue_id:string venue_type:string = MessageMedia;\nmessageMediaGame#fdb19008 game:Game = MessageMedia;\nmessageMediaInvoice#84551347 flags:# shipping_address_requested:flags.1?true test:flags.3?true title:string description:string photo:flags.0?WebDocument receipt_msg_id:flags.2?int currency:string total_amount:long start_param:string = MessageMedia;\nmessageMediaGeoLive#b940c666 flags:# geo:GeoPoint heading:flags.0?int period:int proximity_notification_radius:flags.1?int = MessageMedia;\nmessageMediaPoll#4bd6e798 poll:Poll results:PollResults = MessageMedia;\nmessageMediaDice#3f7ee58b value:int emoticon:string = MessageMedia;\nmessageActionEmpty#b6aef7b0 = MessageAction;\nmessageActionChatCreate#bd47cbad title:string users:Vector = MessageAction;\nmessageActionChatEditTitle#b5a1ce5a title:string = MessageAction;\nmessageActionChatEditPhoto#7fcb13a8 photo:Photo = MessageAction;\nmessageActionChatDeletePhoto#95e3fbef = MessageAction;\nmessageActionChatAddUser#15cefd00 users:Vector = MessageAction;\nmessageActionChatDeleteUser#a43f30cc user_id:long = MessageAction;\nmessageActionChatJoinedByLink#31224c3 inviter_id:long = MessageAction;\nmessageActionChannelCreate#95d2ac92 title:string = MessageAction;\nmessageActionChatMigrateTo#e1037f92 channel_id:long = MessageAction;\nmessageActionChannelMigrateFrom#ea3948e9 title:string chat_id:long = MessageAction;\nmessageActionPinMessage#94bd38ed = MessageAction;\nmessageActionHistoryClear#9fbab604 = MessageAction;\nmessageActionGameScore#92a72876 game_id:long score:int = MessageAction;\nmessageActionPaymentSentMe#8f31b327 flags:# currency:string total_amount:long payload:bytes info:flags.0?PaymentRequestedInfo shipping_option_id:flags.1?string charge:PaymentCharge = MessageAction;\nmessageActionPaymentSent#40699cd0 currency:string total_amount:long = MessageAction;\nmessageActionPhoneCall#80e11a7f flags:# video:flags.2?true call_id:long reason:flags.0?PhoneCallDiscardReason duration:flags.1?int = MessageAction;\nmessageActionScreenshotTaken#4792929b = MessageAction;\nmessageActionCustomAction#fae69f56 message:string = MessageAction;\nmessageActionBotAllowed#abe9affe domain:string = MessageAction;\nmessageActionSecureValuesSentMe#1b287353 values:Vector credentials:SecureCredentialsEncrypted = MessageAction;\nmessageActionSecureValuesSent#d95c6154 types:Vector = MessageAction;\nmessageActionContactSignUp#f3f25f76 = MessageAction;\nmessageActionGeoProximityReached#98e0d697 from_id:Peer to_id:Peer distance:int = MessageAction;\nmessageActionGroupCall#7a0d7f42 flags:# call:InputGroupCall duration:flags.0?int = MessageAction;\nmessageActionInviteToGroupCall#502f92f7 call:InputGroupCall users:Vector = MessageAction;\nmessageActionSetMessagesTTL#aa1afbfd period:int = MessageAction;\nmessageActionGroupCallScheduled#b3a07661 call:InputGroupCall schedule_date:int = MessageAction;\nmessageActionSetChatTheme#aa786345 emoticon:string = MessageAction;\ndialog#2c171f72 flags:# pinned:flags.2?true unread_mark:flags.3?true peer:Peer top_message:int read_inbox_max_id:int read_outbox_max_id:int unread_count:int unread_mentions_count:int notify_settings:PeerNotifySettings pts:flags.0?int draft:flags.1?DraftMessage folder_id:flags.4?int = Dialog;\ndialogFolder#71bd134c flags:# pinned:flags.2?true folder:Folder peer:Peer top_message:int unread_muted_peers_count:int unread_unmuted_peers_count:int unread_muted_messages_count:int unread_unmuted_messages_count:int = Dialog;\nphotoEmpty#2331b22d id:long = Photo;\nphoto#fb197a65 flags:# has_stickers:flags.0?true id:long access_hash:long file_reference:bytes date:int sizes:Vector video_sizes:flags.1?Vector dc_id:int = Photo;\nphotoSizeEmpty#e17e23c type:string = PhotoSize;\nphotoSize#75c78e60 type:string w:int h:int size:int = PhotoSize;\nphotoCachedSize#21e1ad6 type:string w:int h:int bytes:bytes = PhotoSize;\nphotoStrippedSize#e0b0bc2e type:string bytes:bytes = PhotoSize;\nphotoSizeProgressive#fa3efb95 type:string w:int h:int sizes:Vector = PhotoSize;\nphotoPathSize#d8214d41 type:string bytes:bytes = PhotoSize;\ngeoPointEmpty#1117dd5f = GeoPoint;\ngeoPoint#b2a2f663 flags:# long:double lat:double access_hash:long accuracy_radius:flags.0?int = GeoPoint;\nauth.sentCode#5e002502 flags:# type:auth.SentCodeType phone_code_hash:string next_type:flags.1?auth.CodeType timeout:flags.2?int = auth.SentCode;\nauth.authorization#cd050916 flags:# tmp_sessions:flags.0?int user:User = auth.Authorization;\nauth.authorizationSignUpRequired#44747e9a flags:# terms_of_service:flags.0?help.TermsOfService = auth.Authorization;\nauth.exportedAuthorization#b434e2b8 id:long bytes:bytes = auth.ExportedAuthorization;\ninputNotifyPeer#b8bc5b0c peer:InputPeer = InputNotifyPeer;\ninputNotifyUsers#193b4417 = InputNotifyPeer;\ninputNotifyChats#4a95e84e = InputNotifyPeer;\ninputNotifyBroadcasts#b1db7c7e = InputNotifyPeer;\ninputPeerNotifySettings#9c3d198e flags:# show_previews:flags.0?Bool silent:flags.1?Bool mute_until:flags.2?int sound:flags.3?string = InputPeerNotifySettings;\npeerNotifySettings#af509d20 flags:# show_previews:flags.0?Bool silent:flags.1?Bool mute_until:flags.2?int sound:flags.3?string = PeerNotifySettings;\npeerSettings#733f2961 flags:# report_spam:flags.0?true add_contact:flags.1?true block_contact:flags.2?true share_contact:flags.3?true need_contacts_exception:flags.4?true report_geo:flags.5?true autoarchived:flags.7?true invite_members:flags.8?true geo_distance:flags.6?int = PeerSettings;\nwallPaper#a437c3ed id:long flags:# creator:flags.0?true default:flags.1?true pattern:flags.3?true dark:flags.4?true access_hash:long slug:string document:Document settings:flags.2?WallPaperSettings = WallPaper;\nwallPaperNoFile#e0804116 id:long flags:# default:flags.1?true dark:flags.4?true settings:flags.2?WallPaperSettings = WallPaper;\ninputReportReasonSpam#58dbcab8 = ReportReason;\ninputReportReasonViolence#1e22c78d = ReportReason;\ninputReportReasonPornography#2e59d922 = ReportReason;\ninputReportReasonChildAbuse#adf44ee3 = ReportReason;\ninputReportReasonOther#c1e4a2b1 = ReportReason;\ninputReportReasonCopyright#9b89f93a = ReportReason;\ninputReportReasonGeoIrrelevant#dbd4feed = ReportReason;\ninputReportReasonFake#f5ddd6e7 = ReportReason;\nuserFull#d697ff05 flags:# blocked:flags.0?true phone_calls_available:flags.4?true phone_calls_private:flags.5?true can_pin_message:flags.7?true has_scheduled:flags.12?true video_calls_available:flags.13?true user:User about:flags.1?string settings:PeerSettings profile_photo:flags.2?Photo notify_settings:PeerNotifySettings bot_info:flags.3?BotInfo pinned_msg_id:flags.6?int common_chats_count:int folder_id:flags.11?int ttl_period:flags.14?int theme_emoticon:flags.15?string = UserFull;\ncontact#145ade0b user_id:long mutual:Bool = Contact;\nimportedContact#c13e3c50 user_id:long client_id:long = ImportedContact;\ncontactStatus#16d9703b user_id:long status:UserStatus = ContactStatus;\ncontacts.contactsNotModified#b74ba9d2 = contacts.Contacts;\ncontacts.contacts#eae87e42 contacts:Vector saved_count:int users:Vector = contacts.Contacts;\ncontacts.importedContacts#77d01c3b imported:Vector popular_invites:Vector retry_contacts:Vector users:Vector = contacts.ImportedContacts;\ncontacts.blocked#ade1591 blocked:Vector chats:Vector users:Vector = contacts.Blocked;\ncontacts.blockedSlice#e1664194 count:int blocked:Vector chats:Vector users:Vector = contacts.Blocked;\nmessages.dialogs#15ba6c40 dialogs:Vector messages:Vector chats:Vector users:Vector = messages.Dialogs;\nmessages.dialogsSlice#71e094f3 count:int dialogs:Vector messages:Vector chats:Vector users:Vector = messages.Dialogs;\nmessages.dialogsNotModified#f0e3e596 count:int = messages.Dialogs;\nmessages.messages#8c718e87 messages:Vector chats:Vector users:Vector = messages.Messages;\nmessages.messagesSlice#3a54685e flags:# inexact:flags.1?true count:int next_rate:flags.0?int offset_id_offset:flags.2?int messages:Vector chats:Vector users:Vector = messages.Messages;\nmessages.channelMessages#64479808 flags:# inexact:flags.1?true pts:int count:int offset_id_offset:flags.2?int messages:Vector chats:Vector users:Vector = messages.Messages;\nmessages.messagesNotModified#74535f21 count:int = messages.Messages;\nmessages.chats#64ff9fd5 chats:Vector = messages.Chats;\nmessages.chatsSlice#9cd81144 count:int chats:Vector = messages.Chats;\nmessages.chatFull#e5d7d19c full_chat:ChatFull chats:Vector users:Vector = messages.ChatFull;\nmessages.affectedHistory#b45c69d1 pts:int pts_count:int offset:int = messages.AffectedHistory;\ninputMessagesFilterEmpty#57e2f66c = MessagesFilter;\ninputMessagesFilterPhotos#9609a51c = MessagesFilter;\ninputMessagesFilterVideo#9fc00e65 = MessagesFilter;\ninputMessagesFilterPhotoVideo#56e9f0e4 = MessagesFilter;\ninputMessagesFilterDocument#9eddf188 = MessagesFilter;\ninputMessagesFilterUrl#7ef0dd87 = MessagesFilter;\ninputMessagesFilterGif#ffc86587 = MessagesFilter;\ninputMessagesFilterVoice#50f5c392 = MessagesFilter;\ninputMessagesFilterMusic#3751b49e = MessagesFilter;\ninputMessagesFilterChatPhotos#3a20ecb8 = MessagesFilter;\ninputMessagesFilterPhoneCalls#80c99768 flags:# missed:flags.0?true = MessagesFilter;\ninputMessagesFilterRoundVoice#7a7c17a4 = MessagesFilter;\ninputMessagesFilterRoundVideo#b549da53 = MessagesFilter;\ninputMessagesFilterMyMentions#c1f8e69a = MessagesFilter;\ninputMessagesFilterGeo#e7026d0d = MessagesFilter;\ninputMessagesFilterContacts#e062db83 = MessagesFilter;\ninputMessagesFilterPinned#1bb00451 = MessagesFilter;\nupdateNewMessage#1f2b0afd message:Message pts:int pts_count:int = Update;\nupdateMessageID#4e90bfd6 id:int random_id:long = Update;\nupdateDeleteMessages#a20db0e5 messages:Vector pts:int pts_count:int = Update;\nupdateUserTyping#c01e857f user_id:long action:SendMessageAction = Update;\nupdateChatUserTyping#83487af0 chat_id:long from_id:Peer action:SendMessageAction = Update;\nupdateChatParticipants#7761198 participants:ChatParticipants = Update;\nupdateUserStatus#e5bdf8de user_id:long status:UserStatus = Update;\nupdateUserName#c3f202e0 user_id:long first_name:string last_name:string username:string = Update;\nupdateUserPhoto#f227868c user_id:long date:int photo:UserProfilePhoto previous:Bool = Update;\nupdateNewEncryptedMessage#12bcbd9a message:EncryptedMessage qts:int = Update;\nupdateEncryptedChatTyping#1710f156 chat_id:int = Update;\nupdateEncryption#b4a2e88d chat:EncryptedChat date:int = Update;\nupdateEncryptedMessagesRead#38fe25b7 chat_id:int max_date:int date:int = Update;\nupdateChatParticipantAdd#3dda5451 chat_id:long user_id:long inviter_id:long date:int version:int = Update;\nupdateChatParticipantDelete#e32f3d77 chat_id:long user_id:long version:int = Update;\nupdateDcOptions#8e5e9873 dc_options:Vector = Update;\nupdateNotifySettings#bec268ef peer:NotifyPeer notify_settings:PeerNotifySettings = Update;\nupdateServiceNotification#ebe46819 flags:# popup:flags.0?true inbox_date:flags.1?int type:string message:string media:MessageMedia entities:Vector = Update;\nupdatePrivacy#ee3b272a key:PrivacyKey rules:Vector = Update;\nupdateUserPhone#5492a13 user_id:long phone:string = Update;\nupdateReadHistoryInbox#9c974fdf flags:# folder_id:flags.0?int peer:Peer max_id:int still_unread_count:int pts:int pts_count:int = Update;\nupdateReadHistoryOutbox#2f2f21bf peer:Peer max_id:int pts:int pts_count:int = Update;\nupdateWebPage#7f891213 webpage:WebPage pts:int pts_count:int = Update;\nupdateReadMessagesContents#68c13933 messages:Vector pts:int pts_count:int = Update;\nupdateChannelTooLong#108d941f flags:# channel_id:long pts:flags.0?int = Update;\nupdateChannel#635b4c09 channel_id:long = Update;\nupdateNewChannelMessage#62ba04d9 message:Message pts:int pts_count:int = Update;\nupdateReadChannelInbox#922e6e10 flags:# folder_id:flags.0?int channel_id:long max_id:int still_unread_count:int pts:int = Update;\nupdateDeleteChannelMessages#c32d5b12 channel_id:long messages:Vector pts:int pts_count:int = Update;\nupdateChannelMessageViews#f226ac08 channel_id:long id:int views:int = Update;\nupdateChatParticipantAdmin#d7ca61a2 chat_id:long user_id:long is_admin:Bool version:int = Update;\nupdateNewStickerSet#688a30aa stickerset:messages.StickerSet = Update;\nupdateStickerSetsOrder#bb2d201 flags:# masks:flags.0?true order:Vector = Update;\nupdateStickerSets#43ae3dec = Update;\nupdateSavedGifs#9375341e = Update;\nupdateBotInlineQuery#496f379c flags:# query_id:long user_id:long query:string geo:flags.0?GeoPoint peer_type:flags.1?InlineQueryPeerType offset:string = Update;\nupdateBotInlineSend#12f12a07 flags:# user_id:long query:string geo:flags.0?GeoPoint id:string msg_id:flags.1?InputBotInlineMessageID = Update;\nupdateEditChannelMessage#1b3f4df7 message:Message pts:int pts_count:int = Update;\nupdateBotCallbackQuery#b9cfc48d flags:# query_id:long user_id:long peer:Peer msg_id:int chat_instance:long data:flags.0?bytes game_short_name:flags.1?string = Update;\nupdateEditMessage#e40370a3 message:Message pts:int pts_count:int = Update;\nupdateInlineBotCallbackQuery#691e9052 flags:# query_id:long user_id:long msg_id:InputBotInlineMessageID chat_instance:long data:flags.0?bytes game_short_name:flags.1?string = Update;\nupdateReadChannelOutbox#b75f99a9 channel_id:long max_id:int = Update;\nupdateDraftMessage#ee2bb969 peer:Peer draft:DraftMessage = Update;\nupdateReadFeaturedStickers#571d2742 = Update;\nupdateRecentStickers#9a422c20 = Update;\nupdateConfig#a229dd06 = Update;\nupdatePtsChanged#3354678f = Update;\nupdateChannelWebPage#2f2ba99f channel_id:long webpage:WebPage pts:int pts_count:int = Update;\nupdateDialogPinned#6e6fe51c flags:# pinned:flags.0?true folder_id:flags.1?int peer:DialogPeer = Update;\nupdatePinnedDialogs#fa0f3ca2 flags:# folder_id:flags.1?int order:flags.0?Vector = Update;\nupdateBotWebhookJSON#8317c0c3 data:DataJSON = Update;\nupdateBotWebhookJSONQuery#9b9240a6 query_id:long data:DataJSON timeout:int = Update;\nupdateBotShippingQuery#b5aefd7d query_id:long user_id:long payload:bytes shipping_address:PostAddress = Update;\nupdateBotPrecheckoutQuery#8caa9a96 flags:# query_id:long user_id:long payload:bytes info:flags.0?PaymentRequestedInfo shipping_option_id:flags.1?string currency:string total_amount:long = Update;\nupdatePhoneCall#ab0f6b1e phone_call:PhoneCall = Update;\nupdateLangPackTooLong#46560264 lang_code:string = Update;\nupdateLangPack#56022f4d difference:LangPackDifference = Update;\nupdateFavedStickers#e511996d = Update;\nupdateChannelReadMessagesContents#44bdd535 channel_id:long messages:Vector = Update;\nupdateContactsReset#7084a7be = Update;\nupdateChannelAvailableMessages#b23fc698 channel_id:long available_min_id:int = Update;\nupdateDialogUnreadMark#e16459c3 flags:# unread:flags.0?true peer:DialogPeer = Update;\nupdateMessagePoll#aca1657b flags:# poll_id:long poll:flags.0?Poll results:PollResults = Update;\nupdateChatDefaultBannedRights#54c01850 peer:Peer default_banned_rights:ChatBannedRights version:int = Update;\nupdateFolderPeers#19360dc0 folder_peers:Vector pts:int pts_count:int = Update;\nupdatePeerSettings#6a7e7366 peer:Peer settings:PeerSettings = Update;\nupdatePeerLocated#b4afcfb0 peers:Vector = Update;\nupdateNewScheduledMessage#39a51dfb message:Message = Update;\nupdateDeleteScheduledMessages#90866cee peer:Peer messages:Vector = Update;\nupdateTheme#8216fba3 theme:Theme = Update;\nupdateGeoLiveViewed#871fb939 peer:Peer msg_id:int = Update;\nupdateLoginToken#564fe691 = Update;\nupdateMessagePollVote#106395c9 poll_id:long user_id:long options:Vector qts:int = Update;\nupdateDialogFilter#26ffde7d flags:# id:int filter:flags.0?DialogFilter = Update;\nupdateDialogFilterOrder#a5d72105 order:Vector = Update;\nupdateDialogFilters#3504914f = Update;\nupdatePhoneCallSignalingData#2661bf09 phone_call_id:long data:bytes = Update;\nupdateChannelMessageForwards#d29a27f4 channel_id:long id:int forwards:int = Update;\nupdateReadChannelDiscussionInbox#d6b19546 flags:# channel_id:long top_msg_id:int read_max_id:int broadcast_id:flags.0?long broadcast_post:flags.0?int = Update;\nupdateReadChannelDiscussionOutbox#695c9e7c channel_id:long top_msg_id:int read_max_id:int = Update;\nupdatePeerBlocked#246a4b22 peer_id:Peer blocked:Bool = Update;\nupdateChannelUserTyping#8c88c923 flags:# channel_id:long top_msg_id:flags.0?int from_id:Peer action:SendMessageAction = Update;\nupdatePinnedMessages#ed85eab5 flags:# pinned:flags.0?true peer:Peer messages:Vector pts:int pts_count:int = Update;\nupdatePinnedChannelMessages#5bb98608 flags:# pinned:flags.0?true channel_id:long messages:Vector pts:int pts_count:int = Update;\nupdateChat#f89a6a4e chat_id:long = Update;\nupdateGroupCallParticipants#f2ebdb4e call:InputGroupCall participants:Vector version:int = Update;\nupdateGroupCall#14b24500 chat_id:long call:GroupCall = Update;\nupdatePeerHistoryTTL#bb9bb9a5 flags:# peer:Peer ttl_period:flags.0?int = Update;\nupdateChatParticipant#d087663a flags:# chat_id:long date:int actor_id:long user_id:long prev_participant:flags.0?ChatParticipant new_participant:flags.1?ChatParticipant invite:flags.2?ExportedChatInvite qts:int = Update;\nupdateChannelParticipant#985d3abb flags:# channel_id:long date:int actor_id:long user_id:long prev_participant:flags.0?ChannelParticipant new_participant:flags.1?ChannelParticipant invite:flags.2?ExportedChatInvite qts:int = Update;\nupdateBotStopped#c4870a49 user_id:long date:int stopped:Bool qts:int = Update;\nupdateGroupCallConnection#b783982 flags:# presentation:flags.0?true params:DataJSON = Update;\nupdateBotCommands#4d712f2e peer:Peer bot_id:long commands:Vector = Update;\nupdates.state#a56c2a3e pts:int qts:int date:int seq:int unread_count:int = updates.State;\nupdates.differenceEmpty#5d75a138 date:int seq:int = updates.Difference;\nupdates.difference#f49ca0 new_messages:Vector new_encrypted_messages:Vector other_updates:Vector chats:Vector users:Vector state:updates.State = updates.Difference;\nupdates.differenceSlice#a8fb1981 new_messages:Vector new_encrypted_messages:Vector other_updates:Vector chats:Vector users:Vector intermediate_state:updates.State = updates.Difference;\nupdates.differenceTooLong#4afe8f6d pts:int = updates.Difference;\nupdatesTooLong#e317af7e = Updates;\nupdateShortMessage#313bc7f8 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true id:int user_id:long message:string pts:int pts_count:int date:int fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?long reply_to:flags.3?MessageReplyHeader entities:flags.7?Vector ttl_period:flags.25?int = Updates;\nupdateShortChatMessage#4d6deea5 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true id:int from_id:long chat_id:long message:string pts:int pts_count:int date:int fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?long reply_to:flags.3?MessageReplyHeader entities:flags.7?Vector ttl_period:flags.25?int = Updates;\nupdateShort#78d4dec1 update:Update date:int = Updates;\nupdatesCombined#725b04c3 updates:Vector users:Vector chats:Vector date:int seq_start:int seq:int = Updates;\nupdates#74ae4240 updates:Vector users:Vector chats:Vector date:int seq:int = Updates;\nupdateShortSentMessage#9015e101 flags:# out:flags.1?true id:int pts:int pts_count:int date:int media:flags.9?MessageMedia entities:flags.7?Vector ttl_period:flags.25?int = Updates;\nphotos.photos#8dca6aa5 photos:Vector users:Vector = photos.Photos;\nphotos.photosSlice#15051f54 count:int photos:Vector users:Vector = photos.Photos;\nphotos.photo#20212ca8 photo:Photo users:Vector = photos.Photo;\nupload.file#96a18d5 type:storage.FileType mtime:int bytes:bytes = upload.File;\nupload.fileCdnRedirect#f18cda44 dc_id:int file_token:bytes encryption_key:bytes encryption_iv:bytes file_hashes:Vector = upload.File;\ndcOption#18b7a10d flags:# ipv6:flags.0?true media_only:flags.1?true tcpo_only:flags.2?true cdn:flags.3?true static:flags.4?true id:int ip_address:string port:int secret:flags.10?bytes = DcOption;\nconfig#330b4067 flags:# phonecalls_enabled:flags.1?true default_p2p_contacts:flags.3?true preload_featured_stickers:flags.4?true ignore_phone_entities:flags.5?true revoke_pm_inbox:flags.6?true blocked_mode:flags.8?true pfs_enabled:flags.13?true date:int expires:int test_mode:Bool this_dc:int dc_options:Vector dc_txt_domain_name:string chat_size_max:int megagroup_size_max:int forwarded_count_max:int online_update_period_ms:int offline_blur_timeout_ms:int offline_idle_timeout_ms:int online_cloud_timeout_ms:int notify_cloud_delay_ms:int notify_default_delay_ms:int push_chat_period_ms:int push_chat_limit:int saved_gifs_limit:int edit_time_limit:int revoke_time_limit:int revoke_pm_time_limit:int rating_e_decay:int stickers_recent_limit:int stickers_faved_limit:int channels_read_media_period:int tmp_sessions:flags.0?int pinned_dialogs_count_max:int pinned_infolder_count_max:int call_receive_timeout_ms:int call_ring_timeout_ms:int call_connect_timeout_ms:int call_packet_timeout_ms:int me_url_prefix:string autoupdate_url_prefix:flags.7?string gif_search_username:flags.9?string venue_search_username:flags.10?string img_search_username:flags.11?string static_maps_provider:flags.12?string caption_length_max:int message_length_max:int webfile_dc_id:int suggested_lang_code:flags.2?string lang_pack_version:flags.2?int base_lang_pack_version:flags.2?int = Config;\nnearestDc#8e1a1775 country:string this_dc:int nearest_dc:int = NearestDc;\nhelp.appUpdate#ccbbce30 flags:# can_not_skip:flags.0?true id:int version:string text:string entities:Vector document:flags.1?Document url:flags.2?string sticker:flags.3?Document = help.AppUpdate;\nhelp.noAppUpdate#c45a6536 = help.AppUpdate;\nhelp.inviteText#18cb9f78 message:string = help.InviteText;\nencryptedChatEmpty#ab7ec0a0 id:int = EncryptedChat;\nencryptedChatWaiting#66b25953 id:int access_hash:long date:int admin_id:long participant_id:long = EncryptedChat;\nencryptedChatRequested#48f1d94c flags:# folder_id:flags.0?int id:int access_hash:long date:int admin_id:long participant_id:long g_a:bytes = EncryptedChat;\nencryptedChat#61f0d4c7 id:int access_hash:long date:int admin_id:long participant_id:long g_a_or_b:bytes key_fingerprint:long = EncryptedChat;\nencryptedChatDiscarded#1e1c7c45 flags:# history_deleted:flags.0?true id:int = EncryptedChat;\ninputEncryptedChat#f141b5e1 chat_id:int access_hash:long = InputEncryptedChat;\nencryptedFileEmpty#c21f497e = EncryptedFile;\nencryptedFile#4a70994c id:long access_hash:long size:int dc_id:int key_fingerprint:int = EncryptedFile;\ninputEncryptedFileEmpty#1837c364 = InputEncryptedFile;\ninputEncryptedFileUploaded#64bd0306 id:long parts:int md5_checksum:string key_fingerprint:int = InputEncryptedFile;\ninputEncryptedFile#5a17b5e5 id:long access_hash:long = InputEncryptedFile;\ninputEncryptedFileBigUploaded#2dc173c8 id:long parts:int key_fingerprint:int = InputEncryptedFile;\nencryptedMessage#ed18c118 random_id:long chat_id:int date:int bytes:bytes file:EncryptedFile = EncryptedMessage;\nencryptedMessageService#23734b06 random_id:long chat_id:int date:int bytes:bytes = EncryptedMessage;\nmessages.dhConfigNotModified#c0e24635 random:bytes = messages.DhConfig;\nmessages.dhConfig#2c221edd g:int p:bytes version:int random:bytes = messages.DhConfig;\nmessages.sentEncryptedMessage#560f8935 date:int = messages.SentEncryptedMessage;\nmessages.sentEncryptedFile#9493ff32 date:int file:EncryptedFile = messages.SentEncryptedMessage;\ninputDocumentEmpty#72f0eaae = InputDocument;\ninputDocument#1abfb575 id:long access_hash:long file_reference:bytes = InputDocument;\ndocumentEmpty#36f8c871 id:long = Document;\ndocument#1e87342b flags:# id:long access_hash:long file_reference:bytes date:int mime_type:string size:int thumbs:flags.0?Vector video_thumbs:flags.1?Vector dc_id:int attributes:Vector = Document;\nhelp.support#17c6b5f6 phone_number:string user:User = help.Support;\nnotifyPeer#9fd40bd8 peer:Peer = NotifyPeer;\nnotifyUsers#b4c83b4c = NotifyPeer;\nnotifyChats#c007cec3 = NotifyPeer;\nnotifyBroadcasts#d612e8ef = NotifyPeer;\nsendMessageTypingAction#16bf744e = SendMessageAction;\nsendMessageCancelAction#fd5ec8f5 = SendMessageAction;\nsendMessageRecordVideoAction#a187d66f = SendMessageAction;\nsendMessageUploadVideoAction#e9763aec progress:int = SendMessageAction;\nsendMessageRecordAudioAction#d52f73f7 = SendMessageAction;\nsendMessageUploadAudioAction#f351d7ab progress:int = SendMessageAction;\nsendMessageUploadPhotoAction#d1d34a26 progress:int = SendMessageAction;\nsendMessageUploadDocumentAction#aa0cd9e4 progress:int = SendMessageAction;\nsendMessageGeoLocationAction#176f8ba1 = SendMessageAction;\nsendMessageChooseContactAction#628cbc6f = SendMessageAction;\nsendMessageGamePlayAction#dd6a8f48 = SendMessageAction;\nsendMessageRecordRoundAction#88f27fbc = SendMessageAction;\nsendMessageUploadRoundAction#243e1c66 progress:int = SendMessageAction;\nspeakingInGroupCallAction#d92c2285 = SendMessageAction;\nsendMessageHistoryImportAction#dbda9246 progress:int = SendMessageAction;\nsendMessageChooseStickerAction#b05ac6b1 = SendMessageAction;\nsendMessageEmojiInteraction#25972bcb emoticon:string msg_id:int interaction:DataJSON = SendMessageAction;\nsendMessageEmojiInteractionSeen#b665902e emoticon:string = SendMessageAction;\ncontacts.found#b3134d9d my_results:Vector results:Vector chats:Vector users:Vector = contacts.Found;\ninputPrivacyKeyStatusTimestamp#4f96cb18 = InputPrivacyKey;\ninputPrivacyKeyChatInvite#bdfb0426 = InputPrivacyKey;\ninputPrivacyKeyPhoneCall#fabadc5f = InputPrivacyKey;\ninputPrivacyKeyPhoneP2P#db9e70d2 = InputPrivacyKey;\ninputPrivacyKeyForwards#a4dd4c08 = InputPrivacyKey;\ninputPrivacyKeyProfilePhoto#5719bacc = InputPrivacyKey;\ninputPrivacyKeyPhoneNumber#352dafa = InputPrivacyKey;\ninputPrivacyKeyAddedByPhone#d1219bdd = InputPrivacyKey;\nprivacyKeyStatusTimestamp#bc2eab30 = PrivacyKey;\nprivacyKeyChatInvite#500e6dfa = PrivacyKey;\nprivacyKeyPhoneCall#3d662b7b = PrivacyKey;\nprivacyKeyPhoneP2P#39491cc8 = PrivacyKey;\nprivacyKeyForwards#69ec56a3 = PrivacyKey;\nprivacyKeyProfilePhoto#96151fed = PrivacyKey;\nprivacyKeyPhoneNumber#d19ae46d = PrivacyKey;\nprivacyKeyAddedByPhone#42ffd42b = PrivacyKey;\ninputPrivacyValueAllowContacts#d09e07b = InputPrivacyRule;\ninputPrivacyValueAllowAll#184b35ce = InputPrivacyRule;\ninputPrivacyValueAllowUsers#131cc67f users:Vector = InputPrivacyRule;\ninputPrivacyValueDisallowContacts#ba52007 = InputPrivacyRule;\ninputPrivacyValueDisallowAll#d66b66c9 = InputPrivacyRule;\ninputPrivacyValueDisallowUsers#90110467 users:Vector = InputPrivacyRule;\ninputPrivacyValueAllowChatParticipants#840649cf chats:Vector = InputPrivacyRule;\ninputPrivacyValueDisallowChatParticipants#e94f0f86 chats:Vector = InputPrivacyRule;\nprivacyValueAllowContacts#fffe1bac = PrivacyRule;\nprivacyValueAllowAll#65427b82 = PrivacyRule;\nprivacyValueAllowUsers#b8905fb2 users:Vector = PrivacyRule;\nprivacyValueDisallowContacts#f888fa1a = PrivacyRule;\nprivacyValueDisallowAll#8b73e763 = PrivacyRule;\nprivacyValueDisallowUsers#e4621141 users:Vector = PrivacyRule;\nprivacyValueAllowChatParticipants#6b134e8e chats:Vector = PrivacyRule;\nprivacyValueDisallowChatParticipants#41c87565 chats:Vector = PrivacyRule;\naccount.privacyRules#50a04e45 rules:Vector chats:Vector users:Vector = account.PrivacyRules;\naccountDaysTTL#b8d0afdf days:int = AccountDaysTTL;\ndocumentAttributeImageSize#6c37c15c w:int h:int = DocumentAttribute;\ndocumentAttributeAnimated#11b58939 = DocumentAttribute;\ndocumentAttributeSticker#6319d612 flags:# mask:flags.1?true alt:string stickerset:InputStickerSet mask_coords:flags.0?MaskCoords = DocumentAttribute;\ndocumentAttributeVideo#ef02ce6 flags:# round_message:flags.0?true supports_streaming:flags.1?true duration:int w:int h:int = DocumentAttribute;\ndocumentAttributeAudio#9852f9c6 flags:# voice:flags.10?true duration:int title:flags.0?string performer:flags.1?string waveform:flags.2?bytes = DocumentAttribute;\ndocumentAttributeFilename#15590068 file_name:string = DocumentAttribute;\ndocumentAttributeHasStickers#9801d2f7 = DocumentAttribute;\nmessages.stickersNotModified#f1749a22 = messages.Stickers;\nmessages.stickers#30a6ec7e hash:long stickers:Vector = messages.Stickers;\nstickerPack#12b299d4 emoticon:string documents:Vector = StickerPack;\nmessages.allStickersNotModified#e86602c3 = messages.AllStickers;\nmessages.allStickers#cdbbcebb hash:long sets:Vector = messages.AllStickers;\nmessages.affectedMessages#84d19185 pts:int pts_count:int = messages.AffectedMessages;\nwebPageEmpty#eb1477e8 id:long = WebPage;\nwebPagePending#c586da1c id:long date:int = WebPage;\nwebPage#e89c45b2 flags:# id:long url:string display_url:string hash:int type:flags.0?string site_name:flags.1?string title:flags.2?string description:flags.3?string photo:flags.4?Photo embed_url:flags.5?string embed_type:flags.5?string embed_width:flags.6?int embed_height:flags.6?int duration:flags.7?int author:flags.8?string document:flags.9?Document cached_page:flags.10?Page attributes:flags.12?Vector = WebPage;\nwebPageNotModified#7311ca11 flags:# cached_page_views:flags.0?int = WebPage;\nauthorization#ad01d61d flags:# current:flags.0?true official_app:flags.1?true password_pending:flags.2?true hash:long device_model:string platform:string system_version:string api_id:int app_name:string app_version:string date_created:int date_active:int ip:string country:string region:string = Authorization;\naccount.authorizations#1250abde authorizations:Vector = 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#b18105e8 flags:# revoked:flags.0?true permanent:flags.5?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 = ExportedChatInvite;\nchatInviteAlready#5a686d7c chat:Chat = ChatInvite;\nchatInvite#dfc2f58e flags:# channel:flags.0?true broadcast:flags.1?true public:flags.2?true megagroup:flags.3?true title:string photo:Photo participants_count:int participants:flags.4?Vector = ChatInvite;\nchatInvitePeek#61695cb0 chat:Chat expires:int = ChatInvite;\ninputStickerSetEmpty#ffb62b95 = InputStickerSet;\ninputStickerSetID#9de7a269 id:long access_hash:long = InputStickerSet;\ninputStickerSetShortName#861cc8a0 short_name:string = InputStickerSet;\ninputStickerSetAnimatedEmoji#28703c8 = InputStickerSet;\ninputStickerSetDice#e67f520e emoticon:string = InputStickerSet;\ninputStickerSetAnimatedEmojiAnimations#cde3739 = InputStickerSet;\nstickerSet#d7df217a flags:# archived:flags.1?true official:flags.2?true masks:flags.3?true animated:flags.5?true installed_date:flags.0?int id:long access_hash:long title:string short_name:string thumbs:flags.4?Vector thumb_dc_id:flags.4?int thumb_version:flags.4?int count:int hash:int = StickerSet;\nmessages.stickerSet#b60a24a6 set:StickerSet packs:Vector documents:Vector = messages.StickerSet;\nbotCommand#c27ac8c7 command:string description:string = BotCommand;\nbotInfo#1b74b335 user_id:long description:string commands:Vector = BotInfo;\nkeyboardButton#a2fa4880 text:string = KeyboardButton;\nkeyboardButtonUrl#258aff05 text:string url:string = KeyboardButton;\nkeyboardButtonCallback#35bbdb6b flags:# requires_password:flags.0?true text:string data:bytes = KeyboardButton;\nkeyboardButtonRequestPhone#b16a6c29 text:string = KeyboardButton;\nkeyboardButtonRequestGeoLocation#fc796b3f text:string = KeyboardButton;\nkeyboardButtonSwitchInline#568a748 flags:# same_peer:flags.0?true text:string query:string = KeyboardButton;\nkeyboardButtonGame#50f41ccf text:string = KeyboardButton;\nkeyboardButtonBuy#afd93fbb text:string = KeyboardButton;\nkeyboardButtonUrlAuth#10b78d29 flags:# text:string fwd_text:flags.0?string url:string button_id:int = KeyboardButton;\ninputKeyboardButtonUrlAuth#d02e7fd4 flags:# request_write_access:flags.0?true text:string fwd_text:flags.1?string url:string bot:InputUser = KeyboardButton;\nkeyboardButtonRequestPoll#bbc7515d flags:# quiz:flags.0?Bool text:string = KeyboardButton;\nkeyboardButtonRow#77608b83 buttons:Vector = KeyboardButtonRow;\nreplyKeyboardHide#a03e5b85 flags:# selective:flags.2?true = ReplyMarkup;\nreplyKeyboardForceReply#86b40b08 flags:# single_use:flags.1?true selective:flags.2?true placeholder:flags.3?string = ReplyMarkup;\nreplyKeyboardMarkup#85dd99d1 flags:# resize:flags.0?true single_use:flags.1?true selective:flags.2?true rows:Vector placeholder:flags.3?string = ReplyMarkup;\nreplyInlineMarkup#48a30254 rows:Vector = ReplyMarkup;\nmessageEntityUnknown#bb92ba95 offset:int length:int = MessageEntity;\nmessageEntityMention#fa04579d offset:int length:int = MessageEntity;\nmessageEntityHashtag#6f635b0d offset:int length:int = MessageEntity;\nmessageEntityBotCommand#6cef8ac7 offset:int length:int = MessageEntity;\nmessageEntityUrl#6ed02538 offset:int length:int = MessageEntity;\nmessageEntityEmail#64e475c2 offset:int length:int = MessageEntity;\nmessageEntityBold#bd610bc9 offset:int length:int = MessageEntity;\nmessageEntityItalic#826f8b60 offset:int length:int = MessageEntity;\nmessageEntityCode#28a20571 offset:int length:int = MessageEntity;\nmessageEntityPre#73924be0 offset:int length:int language:string = MessageEntity;\nmessageEntityTextUrl#76a6d327 offset:int length:int url:string = MessageEntity;\nmessageEntityMentionName#dc7b1140 offset:int length:int user_id:long = MessageEntity;\ninputMessageEntityMentionName#208e68c9 offset:int length:int user_id:InputUser = MessageEntity;\nmessageEntityPhone#9b69e34b offset:int length:int = MessageEntity;\nmessageEntityCashtag#4c4e743f offset:int length:int = MessageEntity;\nmessageEntityUnderline#9c4e7e8b offset:int length:int = MessageEntity;\nmessageEntityStrike#bf0693d4 offset:int length:int = MessageEntity;\nmessageEntityBlockquote#20df5d0 offset:int length:int = MessageEntity;\nmessageEntityBankCard#761e6af4 offset:int length:int = MessageEntity;\ninputChannelEmpty#ee8c1e86 = InputChannel;\ninputChannel#f35aec28 channel_id:long access_hash:long = InputChannel;\ninputChannelFromMessage#5b934f9d peer:InputPeer msg_id:int channel_id:long = InputChannel;\ncontacts.resolvedPeer#7f077ad9 peer:Peer chats:Vector users:Vector = contacts.ResolvedPeer;\nmessageRange#ae30253 min_id:int max_id:int = MessageRange;\nupdates.channelDifferenceEmpty#3e11affb flags:# final:flags.0?true pts:int timeout:flags.1?int = updates.ChannelDifference;\nupdates.channelDifferenceTooLong#a4bcc6fe flags:# final:flags.0?true timeout:flags.1?int dialog:Dialog messages:Vector chats:Vector users:Vector = updates.ChannelDifference;\nupdates.channelDifference#2064674e flags:# final:flags.0?true pts:int timeout:flags.1?int new_messages:Vector other_updates:Vector chats:Vector users:Vector = updates.ChannelDifference;\nchannelMessagesFilterEmpty#94d42ee7 = ChannelMessagesFilter;\nchannelMessagesFilter#cd77d957 flags:# exclude_new_messages:flags.1?true ranges:Vector = ChannelMessagesFilter;\nchannelParticipant#c00c07c0 user_id:long date:int = ChannelParticipant;\nchannelParticipantSelf#28a8bc67 user_id:long inviter_id:long date:int = ChannelParticipant;\nchannelParticipantCreator#2fe601d3 flags:# user_id:long admin_rights:ChatAdminRights rank:flags.0?string = ChannelParticipant;\nchannelParticipantAdmin#34c3bb53 flags:# can_edit:flags.0?true self:flags.1?true user_id:long inviter_id:flags.1?long promoted_by:long date:int admin_rights:ChatAdminRights rank:flags.2?string = ChannelParticipant;\nchannelParticipantBanned#6df8014e flags:# left:flags.0?true peer:Peer kicked_by:long date:int banned_rights:ChatBannedRights = ChannelParticipant;\nchannelParticipantLeft#1b03f006 peer:Peer = ChannelParticipant;\nchannelParticipantsRecent#de3f3c79 = ChannelParticipantsFilter;\nchannelParticipantsAdmins#b4608969 = ChannelParticipantsFilter;\nchannelParticipantsKicked#a3b54985 q:string = ChannelParticipantsFilter;\nchannelParticipantsBots#b0d1865b = ChannelParticipantsFilter;\nchannelParticipantsBanned#1427a5e1 q:string = ChannelParticipantsFilter;\nchannelParticipantsSearch#656ac4b q:string = ChannelParticipantsFilter;\nchannelParticipantsContacts#bb6ae88d q:string = ChannelParticipantsFilter;\nchannelParticipantsMentions#e04b5ceb flags:# q:flags.0?string top_msg_id:flags.1?int = ChannelParticipantsFilter;\nchannels.channelParticipants#9ab0feaf count:int participants:Vector chats:Vector users:Vector = channels.ChannelParticipants;\nchannels.channelParticipantsNotModified#f0173fe9 = channels.ChannelParticipants;\nchannels.channelParticipant#dfb80317 participant:ChannelParticipant chats:Vector users:Vector = channels.ChannelParticipant;\nhelp.termsOfService#780a0310 flags:# popup:flags.0?true id:DataJSON text:string entities:Vector min_age_confirm:flags.1?int = help.TermsOfService;\nmessages.savedGifsNotModified#e8025ca2 = messages.SavedGifs;\nmessages.savedGifs#84a02a0d hash:long gifs:Vector = messages.SavedGifs;\ninputBotInlineMessageMediaAuto#3380c786 flags:# message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageText#3dcd7a87 flags:# no_webpage:flags.0?true message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaGeo#96929a85 flags:# geo_point:InputGeoPoint heading:flags.0?int period:flags.1?int proximity_notification_radius:flags.3?int reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaVenue#417bbf11 flags:# geo_point:InputGeoPoint title:string address:string provider:string venue_id:string venue_type:string reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaContact#a6edbffd flags:# phone_number:string first_name:string last_name:string vcard:string reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageGame#4b425864 flags:# reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaInvoice#d7e78225 flags:# title:string description:string photo:flags.0?InputWebDocument invoice:Invoice payload:bytes provider:string provider_data:DataJSON reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineResult#88bf9319 flags:# id:string type:string title:flags.1?string description:flags.2?string url:flags.3?string thumb:flags.4?InputWebDocument content:flags.5?InputWebDocument send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultPhoto#a8d864a7 id:string type:string photo:InputPhoto send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultDocument#fff8fdc4 flags:# id:string type:string title:flags.1?string description:flags.2?string document:InputDocument send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultGame#4fa417f2 id:string short_name:string send_message:InputBotInlineMessage = InputBotInlineResult;\nbotInlineMessageMediaAuto#764cf810 flags:# message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageText#8c7f65e2 flags:# no_webpage:flags.0?true message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaGeo#51846fd flags:# geo:GeoPoint heading:flags.0?int period:flags.1?int proximity_notification_radius:flags.3?int reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaVenue#8a86659c flags:# geo:GeoPoint title:string address:string provider:string venue_id:string venue_type:string reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaContact#18d1cdc2 flags:# phone_number:string first_name:string last_name:string vcard:string reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaInvoice#354a9b09 flags:# shipping_address_requested:flags.1?true test:flags.3?true title:string description:string photo:flags.0?WebDocument currency:string total_amount:long reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineResult#11965f3a flags:# id:string type:string title:flags.1?string description:flags.2?string url:flags.3?string thumb:flags.4?WebDocument content:flags.5?WebDocument send_message:BotInlineMessage = BotInlineResult;\nbotInlineMediaResult#17db940b flags:# id:string type:string photo:flags.0?Photo document:flags.1?Document title:flags.2?string description:flags.3?string send_message:BotInlineMessage = BotInlineResult;\nmessages.botResults#947ca848 flags:# gallery:flags.0?true query_id:long next_offset:flags.1?string switch_pm:flags.2?InlineBotSwitchPM results:Vector cache_time:int users:Vector = messages.BotResults;\nexportedMessageLink#5dab1af4 link:string html:string = ExportedMessageLink;\nmessageFwdHeader#5f777dce flags:# imported:flags.7?true from_id:flags.0?Peer from_name:flags.5?string date:int channel_post:flags.2?int post_author:flags.3?string saved_from_peer:flags.4?Peer saved_from_msg_id:flags.4?int psa_type:flags.6?string = MessageFwdHeader;\nauth.codeTypeSms#72a3158c = auth.CodeType;\nauth.codeTypeCall#741cd3e3 = auth.CodeType;\nauth.codeTypeFlashCall#226ccefb = auth.CodeType;\nauth.sentCodeTypeApp#3dbb5986 length:int = auth.SentCodeType;\nauth.sentCodeTypeSms#c000bba2 length:int = auth.SentCodeType;\nauth.sentCodeTypeCall#5353e5a7 length:int = auth.SentCodeType;\nauth.sentCodeTypeFlashCall#ab03c6d9 pattern:string = auth.SentCodeType;\nmessages.botCallbackAnswer#36585ea4 flags:# alert:flags.1?true has_url:flags.3?true native_ui:flags.4?true message:flags.0?string url:flags.2?string cache_time:int = messages.BotCallbackAnswer;\nmessages.messageEditData#26b5dde6 flags:# caption:flags.0?true = messages.MessageEditData;\ninputBotInlineMessageID#890c3d89 dc_id:int id:long access_hash:long = InputBotInlineMessageID;\ninputBotInlineMessageID64#b6d915d7 dc_id:int owner_id:long id:int access_hash:long = InputBotInlineMessageID;\ninlineBotSwitchPM#3c20629f text:string start_param:string = InlineBotSwitchPM;\nmessages.peerDialogs#3371c354 dialogs:Vector messages:Vector chats:Vector users:Vector state:updates.State = messages.PeerDialogs;\ntopPeer#edcdc05b peer:Peer rating:double = TopPeer;\ntopPeerCategoryBotsPM#ab661b5b = TopPeerCategory;\ntopPeerCategoryBotsInline#148677e2 = TopPeerCategory;\ntopPeerCategoryCorrespondents#637b7ed = TopPeerCategory;\ntopPeerCategoryGroups#bd17a14a = TopPeerCategory;\ntopPeerCategoryChannels#161d9628 = TopPeerCategory;\ntopPeerCategoryPhoneCalls#1e76a78c = TopPeerCategory;\ntopPeerCategoryForwardUsers#a8406ca9 = TopPeerCategory;\ntopPeerCategoryForwardChats#fbeec0f0 = TopPeerCategory;\ntopPeerCategoryPeers#fb834291 category:TopPeerCategory count:int peers:Vector = TopPeerCategoryPeers;\ncontacts.topPeersNotModified#de266ef5 = contacts.TopPeers;\ncontacts.topPeers#70b772a8 categories:Vector chats:Vector users:Vector = contacts.TopPeers;\ncontacts.topPeersDisabled#b52c939d = contacts.TopPeers;\ndraftMessageEmpty#1b0c841a flags:# date:flags.0?int = DraftMessage;\ndraftMessage#fd8e711f flags:# no_webpage:flags.1?true reply_to_msg_id:flags.0?int message:string entities:flags.3?Vector date:int = DraftMessage;\nmessages.featuredStickersNotModified#c6dc0c66 count:int = messages.FeaturedStickers;\nmessages.featuredStickers#84c02310 hash:long count:int sets:Vector unread:Vector = messages.FeaturedStickers;\nmessages.recentStickersNotModified#b17f890 = messages.RecentStickers;\nmessages.recentStickers#88d37c56 hash:long packs:Vector stickers:Vector dates:Vector = messages.RecentStickers;\nmessages.archivedStickers#4fcba9c8 count:int sets:Vector = messages.ArchivedStickers;\nmessages.stickerSetInstallResultSuccess#38641628 = messages.StickerSetInstallResult;\nmessages.stickerSetInstallResultArchive#35e410a8 sets:Vector = messages.StickerSetInstallResult;\nstickerSetCovered#6410a5d2 set:StickerSet cover:Document = StickerSetCovered;\nstickerSetMultiCovered#3407e51b set:StickerSet covers:Vector = StickerSetCovered;\nmaskCoords#aed6dbb2 n:int x:double y:double zoom:double = MaskCoords;\ninputStickeredMediaPhoto#4a992157 id:InputPhoto = InputStickeredMedia;\ninputStickeredMediaDocument#438865b id:InputDocument = InputStickeredMedia;\ngame#bdf9653b flags:# id:long access_hash:long short_name:string title:string description:string photo:Photo document:flags.0?Document = Game;\ninputGameID#32c3e77 id:long access_hash:long = InputGame;\ninputGameShortName#c331e80a bot_id:InputUser short_name:string = InputGame;\nhighScore#73a379eb pos:int user_id:long score:int = HighScore;\nmessages.highScores#9a3bfd99 scores:Vector users:Vector = messages.HighScores;\ntextEmpty#dc3d824f = RichText;\ntextPlain#744694e0 text:string = RichText;\ntextBold#6724abc4 text:RichText = RichText;\ntextItalic#d912a59c text:RichText = RichText;\ntextUnderline#c12622c4 text:RichText = RichText;\ntextStrike#9bf8bb95 text:RichText = RichText;\ntextFixed#6c3f19b9 text:RichText = RichText;\ntextUrl#3c2884c1 text:RichText url:string webpage_id:long = RichText;\ntextEmail#de5a0dd6 text:RichText email:string = RichText;\ntextConcat#7e6260d7 texts:Vector = RichText;\ntextSubscript#ed6a8504 text:RichText = RichText;\ntextSuperscript#c7fb5e01 text:RichText = RichText;\ntextMarked#34b8621 text:RichText = RichText;\ntextPhone#1ccb966a text:RichText phone:string = RichText;\ntextImage#81ccf4f document_id:long w:int h:int = RichText;\ntextAnchor#35553762 text:RichText name:string = RichText;\npageBlockUnsupported#13567e8a = PageBlock;\npageBlockTitle#70abc3fd text:RichText = PageBlock;\npageBlockSubtitle#8ffa9a1f text:RichText = PageBlock;\npageBlockAuthorDate#baafe5e0 author:RichText published_date:int = PageBlock;\npageBlockHeader#bfd064ec text:RichText = PageBlock;\npageBlockSubheader#f12bb6e1 text:RichText = PageBlock;\npageBlockParagraph#467a0766 text:RichText = PageBlock;\npageBlockPreformatted#c070d93e text:RichText language:string = PageBlock;\npageBlockFooter#48870999 text:RichText = PageBlock;\npageBlockDivider#db20b188 = PageBlock;\npageBlockAnchor#ce0d37b0 name:string = PageBlock;\npageBlockList#e4e88011 items:Vector = PageBlock;\npageBlockBlockquote#263d7c26 text:RichText caption:RichText = PageBlock;\npageBlockPullquote#4f4456d3 text:RichText caption:RichText = PageBlock;\npageBlockPhoto#1759c560 flags:# photo_id:long caption:PageCaption url:flags.0?string webpage_id:flags.0?long = PageBlock;\npageBlockVideo#7c8fe7b6 flags:# autoplay:flags.0?true loop:flags.1?true video_id:long caption:PageCaption = PageBlock;\npageBlockCover#39f23300 cover:PageBlock = PageBlock;\npageBlockEmbed#a8718dc5 flags:# full_width:flags.0?true allow_scrolling:flags.3?true url:flags.1?string html:flags.2?string poster_photo_id:flags.4?long w:flags.5?int h:flags.5?int caption:PageCaption = PageBlock;\npageBlockEmbedPost#f259a80b url:string webpage_id:long author_photo_id:long author:string date:int blocks:Vector caption:PageCaption = PageBlock;\npageBlockCollage#65a0fa4d items:Vector caption:PageCaption = PageBlock;\npageBlockSlideshow#31f9590 items:Vector caption:PageCaption = PageBlock;\npageBlockChannel#ef1751b5 channel:Chat = PageBlock;\npageBlockAudio#804361ea audio_id:long caption:PageCaption = PageBlock;\npageBlockKicker#1e148390 text:RichText = PageBlock;\npageBlockTable#bf4dea82 flags:# bordered:flags.0?true striped:flags.1?true title:RichText rows:Vector = PageBlock;\npageBlockOrderedList#9a8ae1e1 items:Vector = PageBlock;\npageBlockDetails#76768bed flags:# open:flags.0?true blocks:Vector title:RichText = PageBlock;\npageBlockRelatedArticles#16115a96 title:RichText articles:Vector = PageBlock;\npageBlockMap#a44f3ef6 geo:GeoPoint zoom:int w:int h:int caption:PageCaption = PageBlock;\nphoneCallDiscardReasonMissed#85e42301 = PhoneCallDiscardReason;\nphoneCallDiscardReasonDisconnect#e095c1a0 = PhoneCallDiscardReason;\nphoneCallDiscardReasonHangup#57adc690 = PhoneCallDiscardReason;\nphoneCallDiscardReasonBusy#faf7e8c9 = PhoneCallDiscardReason;\ndataJSON#7d748d04 data:string = DataJSON;\nlabeledPrice#cb296bf8 label:string amount:long = LabeledPrice;\ninvoice#cd886e0 flags:# test:flags.0?true name_requested:flags.1?true phone_requested:flags.2?true email_requested:flags.3?true shipping_address_requested:flags.4?true flexible:flags.5?true phone_to_provider:flags.6?true email_to_provider:flags.7?true currency:string prices:Vector max_tip_amount:flags.8?long suggested_tip_amounts:flags.8?Vector = Invoice;\npaymentCharge#ea02c27e id:string provider_charge_id:string = PaymentCharge;\npostAddress#1e8caaeb street_line1:string street_line2:string city:string state:string country_iso2:string post_code:string = PostAddress;\npaymentRequestedInfo#909c3f94 flags:# name:flags.0?string phone:flags.1?string email:flags.2?string shipping_address:flags.3?PostAddress = PaymentRequestedInfo;\npaymentSavedCredentialsCard#cdc27a1f id:string title:string = PaymentSavedCredentials;\nwebDocument#1c570ed1 url:string access_hash:long size:int mime_type:string attributes:Vector = WebDocument;\nwebDocumentNoProxy#f9c8bcc6 url:string size:int mime_type:string attributes:Vector = WebDocument;\ninputWebDocument#9bed434d url:string size:int mime_type:string attributes:Vector = InputWebDocument;\ninputWebFileLocation#c239d686 url:string access_hash:long = InputWebFileLocation;\ninputWebFileGeoPointLocation#9f2221c9 geo_point:InputGeoPoint access_hash:long w:int h:int zoom:int scale:int = InputWebFileLocation;\nupload.webFile#21e753bc size:int mime_type:string file_type:storage.FileType mtime:int bytes:bytes = upload.WebFile;\npayments.paymentForm#1694761b flags:# can_save_credentials:flags.2?true password_missing:flags.3?true form_id:long bot_id:long invoice:Invoice provider_id:long url:string native_provider:flags.4?string native_params:flags.4?DataJSON saved_info:flags.0?PaymentRequestedInfo saved_credentials:flags.1?PaymentSavedCredentials users:Vector = payments.PaymentForm;\npayments.validatedRequestedInfo#d1451883 flags:# id:flags.0?string shipping_options:flags.1?Vector = payments.ValidatedRequestedInfo;\npayments.paymentResult#4e5f810d updates:Updates = payments.PaymentResult;\npayments.paymentVerificationNeeded#d8411139 url:string = payments.PaymentResult;\npayments.paymentReceipt#70c4fe03 flags:# date:int bot_id:long provider_id:long title:string description:string photo:flags.2?WebDocument invoice:Invoice info:flags.0?PaymentRequestedInfo shipping:flags.1?ShippingOption tip_amount:flags.3?long currency:string total_amount:long credentials_title:string users:Vector = payments.PaymentReceipt;\npayments.savedInfo#fb8fe43c flags:# has_saved_credentials:flags.1?true saved_info:flags.0?PaymentRequestedInfo = payments.SavedInfo;\ninputPaymentCredentialsSaved#c10eb2cf id:string tmp_password:bytes = InputPaymentCredentials;\ninputPaymentCredentials#3417d728 flags:# save:flags.0?true data:DataJSON = InputPaymentCredentials;\ninputPaymentCredentialsApplePay#aa1c39f payment_data:DataJSON = InputPaymentCredentials;\ninputPaymentCredentialsGooglePay#8ac32801 payment_token:DataJSON = InputPaymentCredentials;\naccount.tmpPassword#db64fd34 tmp_password:bytes valid_until:int = account.TmpPassword;\nshippingOption#b6213cdf id:string title:string prices:Vector = ShippingOption;\ninputStickerSetItem#ffa0a496 flags:# document:InputDocument emoji:string mask_coords:flags.0?MaskCoords = InputStickerSetItem;\ninputPhoneCall#1e36fded id:long access_hash:long = InputPhoneCall;\nphoneCallEmpty#5366c915 id:long = PhoneCall;\nphoneCallWaiting#c5226f17 flags:# video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long protocol:PhoneCallProtocol receive_date:flags.0?int = PhoneCall;\nphoneCallRequested#14b0ed0c flags:# video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long g_a_hash:bytes protocol:PhoneCallProtocol = PhoneCall;\nphoneCallAccepted#3660c311 flags:# video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long g_b:bytes protocol:PhoneCallProtocol = PhoneCall;\nphoneCall#967f7c67 flags:# p2p_allowed:flags.5?true video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long g_a_or_b:bytes key_fingerprint:long protocol:PhoneCallProtocol connections:Vector start_date:int = PhoneCall;\nphoneCallDiscarded#50ca4de1 flags:# need_rating:flags.2?true need_debug:flags.3?true video:flags.6?true id:long reason:flags.0?PhoneCallDiscardReason duration:flags.1?int = PhoneCall;\nphoneConnection#9d4c17c0 id:long ip:string ipv6:string port:int peer_tag:bytes = PhoneConnection;\nphoneConnectionWebrtc#635fe375 flags:# turn:flags.0?true stun:flags.1?true id:long ip:string ipv6:string port:int username:string password:string = PhoneConnection;\nphoneCallProtocol#fc878fc8 flags:# udp_p2p:flags.0?true udp_reflector:flags.1?true min_layer:int max_layer:int library_versions:Vector = PhoneCallProtocol;\nphone.phoneCall#ec82e140 phone_call:PhoneCall users:Vector = phone.PhoneCall;\nupload.cdnFileReuploadNeeded#eea8e46e request_token:bytes = upload.CdnFile;\nupload.cdnFile#a99fca4f bytes:bytes = upload.CdnFile;\ncdnPublicKey#c982eaba dc_id:int public_key:string = CdnPublicKey;\ncdnConfig#5725e40a public_keys:Vector = CdnConfig;\nlangPackString#cad181f6 key:string value:string = LangPackString;\nlangPackStringPluralized#6c47ac9f flags:# key:string zero_value:flags.0?string one_value:flags.1?string two_value:flags.2?string few_value:flags.3?string many_value:flags.4?string other_value:string = LangPackString;\nlangPackStringDeleted#2979eeb2 key:string = LangPackString;\nlangPackDifference#f385c1f6 lang_code:string from_version:int version:int strings:Vector = LangPackDifference;\nlangPackLanguage#eeca5ce3 flags:# official:flags.0?true rtl:flags.2?true beta:flags.3?true name:string native_name:string lang_code:string base_lang_code:flags.1?string plural_code:string strings_count:int translated_count:int translations_url:string = LangPackLanguage;\nchannelAdminLogEventActionChangeTitle#e6dfb825 prev_value:string new_value:string = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeAbout#55188a2e prev_value:string new_value:string = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeUsername#6a4afc38 prev_value:string new_value:string = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangePhoto#434bd2af prev_photo:Photo new_photo:Photo = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleInvites#1b7907ae new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleSignatures#26ae0971 new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionUpdatePinned#e9e82c18 message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionEditMessage#709b2405 prev_message:Message new_message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionDeleteMessage#42e047bb message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantJoin#183040d3 = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantLeave#f89777f2 = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantInvite#e31c34d8 participant:ChannelParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantToggleBan#e6d83d7e prev_participant:ChannelParticipant new_participant:ChannelParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantToggleAdmin#d5676710 prev_participant:ChannelParticipant new_participant:ChannelParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeStickerSet#b1c3caa7 prev_stickerset:InputStickerSet new_stickerset:InputStickerSet = ChannelAdminLogEventAction;\nchannelAdminLogEventActionTogglePreHistoryHidden#5f5c95f1 new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionDefaultBannedRights#2df5fc0a prev_banned_rights:ChatBannedRights new_banned_rights:ChatBannedRights = ChannelAdminLogEventAction;\nchannelAdminLogEventActionStopPoll#8f079643 message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeLinkedChat#50c7ac8 prev_value:long new_value:long = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeLocation#e6b76ae prev_value:ChannelLocation new_value:ChannelLocation = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleSlowMode#53909779 prev_value:int new_value:int = ChannelAdminLogEventAction;\nchannelAdminLogEventActionStartGroupCall#23209745 call:InputGroupCall = ChannelAdminLogEventAction;\nchannelAdminLogEventActionDiscardGroupCall#db9f9140 call:InputGroupCall = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantMute#f92424d2 participant:GroupCallParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantUnmute#e64429c0 participant:GroupCallParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleGroupCallSetting#56d6a247 join_muted:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantJoinByInvite#5cdada77 invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionExportedInviteDelete#5a50fca4 invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionExportedInviteRevoke#410a134e invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionExportedInviteEdit#e90ebb59 prev_invite:ExportedChatInvite new_invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantVolume#3e7f6847 participant:GroupCallParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeHistoryTTL#6e941a38 prev_value:int new_value:int = ChannelAdminLogEventAction;\nchannelAdminLogEvent#1fad68cd id:long date:int user_id:long action:ChannelAdminLogEventAction = ChannelAdminLogEvent;\nchannels.adminLogResults#ed8af74d events:Vector chats:Vector users:Vector = channels.AdminLogResults;\nchannelAdminLogEventsFilter#ea107ae4 flags:# join:flags.0?true leave:flags.1?true invite:flags.2?true ban:flags.3?true unban:flags.4?true kick:flags.5?true unkick:flags.6?true promote:flags.7?true demote:flags.8?true info:flags.9?true settings:flags.10?true pinned:flags.11?true edit:flags.12?true delete:flags.13?true group_call:flags.14?true invites:flags.15?true = ChannelAdminLogEventsFilter;\npopularContact#5ce14175 client_id:long importers:int = PopularContact;\nmessages.favedStickersNotModified#9e8fa6d3 = messages.FavedStickers;\nmessages.favedStickers#2cb51097 hash:long packs:Vector stickers:Vector = messages.FavedStickers;\nrecentMeUrlUnknown#46e1d13d url:string = RecentMeUrl;\nrecentMeUrlUser#b92c09e2 url:string user_id:long = RecentMeUrl;\nrecentMeUrlChat#b2da71d2 url:string chat_id:long = RecentMeUrl;\nrecentMeUrlChatInvite#eb49081d url:string chat_invite:ChatInvite = RecentMeUrl;\nrecentMeUrlStickerSet#bc0a57dc url:string set:StickerSetCovered = RecentMeUrl;\nhelp.recentMeUrls#e0310d7 urls:Vector chats:Vector users:Vector = help.RecentMeUrls;\ninputSingleMedia#1cc6e91f flags:# media:InputMedia random_id:long message:string entities:flags.0?Vector = InputSingleMedia;\nwebAuthorization#a6f8f452 hash:long bot_id:long domain:string browser:string platform:string date_created:int date_active:int ip:string region:string = WebAuthorization;\naccount.webAuthorizations#ed56c9fc authorizations:Vector users:Vector = account.WebAuthorizations;\ninputMessageID#a676a322 id:int = InputMessage;\ninputMessageReplyTo#bad88395 id:int = InputMessage;\ninputMessagePinned#86872538 = InputMessage;\ninputMessageCallbackQuery#acfa1a7e id:int query_id:long = InputMessage;\ninputDialogPeer#fcaafeb7 peer:InputPeer = InputDialogPeer;\ninputDialogPeerFolder#64600527 folder_id:int = InputDialogPeer;\ndialogPeer#e56dbf05 peer:Peer = DialogPeer;\ndialogPeerFolder#514519e2 folder_id:int = DialogPeer;\nmessages.foundStickerSetsNotModified#d54b65d = messages.FoundStickerSets;\nmessages.foundStickerSets#8af09dd2 hash:long sets:Vector = messages.FoundStickerSets;\nfileHash#6242c773 offset:int limit:int hash:bytes = FileHash;\ninputClientProxy#75588b3f address:string port:int = InputClientProxy;\nhelp.termsOfServiceUpdateEmpty#e3309f7f expires:int = help.TermsOfServiceUpdate;\nhelp.termsOfServiceUpdate#28ecf961 expires:int terms_of_service:help.TermsOfService = help.TermsOfServiceUpdate;\ninputSecureFileUploaded#3334b0f0 id:long parts:int md5_checksum:string file_hash:bytes secret:bytes = InputSecureFile;\ninputSecureFile#5367e5be id:long access_hash:long = InputSecureFile;\nsecureFileEmpty#64199744 = SecureFile;\nsecureFile#e0277a62 id:long access_hash:long size:int dc_id:int date:int file_hash:bytes secret:bytes = SecureFile;\nsecureData#8aeabec3 data:bytes data_hash:bytes secret:bytes = SecureData;\nsecurePlainPhone#7d6099dd phone:string = SecurePlainData;\nsecurePlainEmail#21ec5a5f email:string = SecurePlainData;\nsecureValueTypePersonalDetails#9d2a81e3 = SecureValueType;\nsecureValueTypePassport#3dac6a00 = SecureValueType;\nsecureValueTypeDriverLicense#6e425c4 = SecureValueType;\nsecureValueTypeIdentityCard#a0d0744b = SecureValueType;\nsecureValueTypeInternalPassport#99a48f23 = SecureValueType;\nsecureValueTypeAddress#cbe31e26 = SecureValueType;\nsecureValueTypeUtilityBill#fc36954e = SecureValueType;\nsecureValueTypeBankStatement#89137c0d = SecureValueType;\nsecureValueTypeRentalAgreement#8b883488 = SecureValueType;\nsecureValueTypePassportRegistration#99e3806a = SecureValueType;\nsecureValueTypeTemporaryRegistration#ea02ec33 = SecureValueType;\nsecureValueTypePhone#b320aadb = SecureValueType;\nsecureValueTypeEmail#8e3ca7ee = SecureValueType;\nsecureValue#187fa0ca flags:# type:SecureValueType data:flags.0?SecureData front_side:flags.1?SecureFile reverse_side:flags.2?SecureFile selfie:flags.3?SecureFile translation:flags.6?Vector files:flags.4?Vector plain_data:flags.5?SecurePlainData hash:bytes = SecureValue;\ninputSecureValue#db21d0a7 flags:# type:SecureValueType data:flags.0?SecureData front_side:flags.1?InputSecureFile reverse_side:flags.2?InputSecureFile selfie:flags.3?InputSecureFile translation:flags.6?Vector files:flags.4?Vector plain_data:flags.5?SecurePlainData = InputSecureValue;\nsecureValueHash#ed1ecdb0 type:SecureValueType hash:bytes = SecureValueHash;\nsecureValueErrorData#e8a40bd9 type:SecureValueType data_hash:bytes field:string text:string = SecureValueError;\nsecureValueErrorFrontSide#be3dfa type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorReverseSide#868a2aa5 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorSelfie#e537ced6 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorFile#7a700873 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorFiles#666220e9 type:SecureValueType file_hash:Vector text:string = SecureValueError;\nsecureValueError#869d758f type:SecureValueType hash:bytes text:string = SecureValueError;\nsecureValueErrorTranslationFile#a1144770 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorTranslationFiles#34636dd8 type:SecureValueType file_hash:Vector text:string = SecureValueError;\nsecureCredentialsEncrypted#33f0ea47 data:bytes hash:bytes secret:bytes = SecureCredentialsEncrypted;\naccount.authorizationForm#ad2e1cd8 flags:# required_types:Vector values:Vector errors:Vector users:Vector privacy_policy_url:flags.0?string = account.AuthorizationForm;\naccount.sentEmailCode#811f854f email_pattern:string length:int = account.SentEmailCode;\nhelp.deepLinkInfoEmpty#66afa166 = help.DeepLinkInfo;\nhelp.deepLinkInfo#6a4ee832 flags:# update_app:flags.0?true message:string entities:flags.1?Vector = help.DeepLinkInfo;\nsavedPhoneContact#1142bd56 phone:string first_name:string last_name:string date:int = SavedContact;\naccount.takeout#4dba4501 id:long = account.Takeout;\npasswordKdfAlgoUnknown#d45ab096 = PasswordKdfAlgo;\npasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow#3a912d4a salt1:bytes salt2:bytes g:int p:bytes = PasswordKdfAlgo;\nsecurePasswordKdfAlgoUnknown#4a8537 = SecurePasswordKdfAlgo;\nsecurePasswordKdfAlgoPBKDF2HMACSHA512iter100000#bbf2dda0 salt:bytes = SecurePasswordKdfAlgo;\nsecurePasswordKdfAlgoSHA512#86471d92 salt:bytes = SecurePasswordKdfAlgo;\nsecureSecretSettings#1527bcac secure_algo:SecurePasswordKdfAlgo secure_secret:bytes secure_secret_id:long = SecureSecretSettings;\ninputCheckPasswordEmpty#9880f658 = InputCheckPasswordSRP;\ninputCheckPasswordSRP#d27ff082 srp_id:long A:bytes M1:bytes = InputCheckPasswordSRP;\nsecureRequiredType#829d99da flags:# native_names:flags.0?true selfie_required:flags.1?true translation_required:flags.2?true type:SecureValueType = SecureRequiredType;\nsecureRequiredTypeOneOf#27477b4 types:Vector = SecureRequiredType;\nhelp.passportConfigNotModified#bfb9f457 = help.PassportConfig;\nhelp.passportConfig#a098d6af hash:int countries_langs:DataJSON = help.PassportConfig;\ninputAppEvent#1d1b1245 time:double type:string peer:long data:JSONValue = InputAppEvent;\njsonObjectValue#c0de1bd9 key:string value:JSONValue = JSONObjectValue;\njsonNull#3f6d7b68 = JSONValue;\njsonBool#c7345e6a value:Bool = JSONValue;\njsonNumber#2be0dfa4 value:double = JSONValue;\njsonString#b71e767a value:string = JSONValue;\njsonArray#f7444763 value:Vector = JSONValue;\njsonObject#99c1d49d value:Vector = JSONValue;\npageTableCell#34566b6a flags:# header:flags.0?true align_center:flags.3?true align_right:flags.4?true valign_middle:flags.5?true valign_bottom:flags.6?true text:flags.7?RichText colspan:flags.1?int rowspan:flags.2?int = PageTableCell;\npageTableRow#e0c0c5e5 cells:Vector = PageTableRow;\npageCaption#6f747657 text:RichText credit:RichText = PageCaption;\npageListItemText#b92fb6cd text:RichText = PageListItem;\npageListItemBlocks#25e073fc blocks:Vector = PageListItem;\npageListOrderedItemText#5e068047 num:string text:RichText = PageListOrderedItem;\npageListOrderedItemBlocks#98dd8936 num:string blocks:Vector = PageListOrderedItem;\npageRelatedArticle#b390dc08 flags:# url:string webpage_id:long title:flags.0?string description:flags.1?string photo_id:flags.2?long author:flags.3?string published_date:flags.4?int = PageRelatedArticle;\npage#98657f0d flags:# part:flags.0?true rtl:flags.1?true v2:flags.2?true url:string blocks:Vector photos:Vector documents:Vector views:flags.3?int = Page;\nhelp.supportName#8c05f1c9 name:string = help.SupportName;\nhelp.userInfoEmpty#f3ae2eed = help.UserInfo;\nhelp.userInfo#1eb3758 message:string entities:Vector author:string date:int = help.UserInfo;\npollAnswer#6ca9c2e9 text:string option:bytes = PollAnswer;\npoll#86e18161 id:long flags:# closed:flags.0?true public_voters:flags.1?true multiple_choice:flags.2?true quiz:flags.3?true question:string answers:Vector close_period:flags.4?int close_date:flags.5?int = Poll;\npollAnswerVoters#3b6ddad2 flags:# chosen:flags.0?true correct:flags.1?true option:bytes voters:int = PollAnswerVoters;\npollResults#dcb82ea3 flags:# min:flags.0?true results:flags.1?Vector total_voters:flags.2?int recent_voters:flags.3?Vector solution:flags.4?string solution_entities:flags.4?Vector = PollResults;\nchatOnlines#f041e250 onlines:int = ChatOnlines;\nstatsURL#47a971e0 url:string = StatsURL;\nchatAdminRights#5fb224d5 flags:# change_info:flags.0?true post_messages:flags.1?true edit_messages:flags.2?true delete_messages:flags.3?true ban_users:flags.4?true invite_users:flags.5?true pin_messages:flags.7?true add_admins:flags.9?true anonymous:flags.10?true manage_call:flags.11?true other:flags.12?true = ChatAdminRights;\nchatBannedRights#9f120418 flags:# view_messages:flags.0?true send_messages:flags.1?true send_media:flags.2?true send_stickers:flags.3?true send_gifs:flags.4?true send_games:flags.5?true send_inline:flags.6?true embed_links:flags.7?true send_polls:flags.8?true change_info:flags.10?true invite_users:flags.15?true pin_messages:flags.17?true until_date:int = ChatBannedRights;\ninputWallPaper#e630b979 id:long access_hash:long = InputWallPaper;\ninputWallPaperSlug#72091c80 slug:string = InputWallPaper;\ninputWallPaperNoFile#967a462e id:long = InputWallPaper;\naccount.wallPapersNotModified#1c199183 = account.WallPapers;\naccount.wallPapers#cdc3858c hash:long wallpapers:Vector = account.WallPapers;\ncodeSettings#debebe83 flags:# allow_flashcall:flags.0?true current_number:flags.1?true allow_app_hash:flags.4?true = CodeSettings;\nwallPaperSettings#1dc1bca4 flags:# blur:flags.1?true motion:flags.2?true background_color:flags.0?int second_background_color:flags.4?int third_background_color:flags.5?int fourth_background_color:flags.6?int intensity:flags.3?int rotation:flags.4?int = WallPaperSettings;\nautoDownloadSettings#e04232f3 flags:# disabled:flags.0?true video_preload_large:flags.1?true audio_preload_next:flags.2?true phonecalls_less_data:flags.3?true photo_size_max:int video_size_max:int file_size_max:int video_upload_maxbitrate:int = AutoDownloadSettings;\naccount.autoDownloadSettings#63cacf26 low:AutoDownloadSettings medium:AutoDownloadSettings high:AutoDownloadSettings = account.AutoDownloadSettings;\nemojiKeyword#d5b3b9f9 keyword:string emoticons:Vector = EmojiKeyword;\nemojiKeywordDeleted#236df622 keyword:string emoticons:Vector = EmojiKeyword;\nemojiKeywordsDifference#5cc761bd lang_code:string from_version:int version:int keywords:Vector = EmojiKeywordsDifference;\nemojiURL#a575739d url:string = EmojiURL;\nemojiLanguage#b3fb5361 lang_code:string = EmojiLanguage;\nfolder#ff544e65 flags:# autofill_new_broadcasts:flags.0?true autofill_public_groups:flags.1?true autofill_new_correspondents:flags.2?true id:int title:string photo:flags.3?ChatPhoto = Folder;\ninputFolderPeer#fbd2c296 peer:InputPeer folder_id:int = InputFolderPeer;\nfolderPeer#e9baa668 peer:Peer folder_id:int = FolderPeer;\nmessages.searchCounter#e844ebff flags:# inexact:flags.1?true filter:MessagesFilter count:int = messages.SearchCounter;\nurlAuthResultRequest#92d33a0e flags:# request_write_access:flags.0?true bot:User domain:string = UrlAuthResult;\nurlAuthResultAccepted#8f8c0e4e url:string = UrlAuthResult;\nurlAuthResultDefault#a9d6db1f = UrlAuthResult;\nchannelLocationEmpty#bfb5ad8b = ChannelLocation;\nchannelLocation#209b82db geo_point:GeoPoint address:string = ChannelLocation;\npeerLocated#ca461b5d peer:Peer expires:int distance:int = PeerLocated;\npeerSelfLocated#f8ec284b expires:int = PeerLocated;\nrestrictionReason#d072acb4 platform:string reason:string text:string = RestrictionReason;\ninputTheme#3c5693e9 id:long access_hash:long = InputTheme;\ninputThemeSlug#f5890df1 slug:string = InputTheme;\ntheme#e802b8dc 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?ThemeSettings installs_count:flags.4?int = Theme;\naccount.themesNotModified#f41eb622 = account.Themes;\naccount.themes#9a3d8c6d hash:long themes:Vector = account.Themes;\nauth.loginToken#629f1980 expires:int token:bytes = auth.LoginToken;\nauth.loginTokenMigrateTo#68e9916 dc_id:int token:bytes = auth.LoginToken;\nauth.loginTokenSuccess#390d5c5e authorization:auth.Authorization = auth.LoginToken;\naccount.contentSettings#57e28221 flags:# sensitive_enabled:flags.0?true sensitive_can_change:flags.1?true = account.ContentSettings;\nmessages.inactiveChats#a927fec5 dates:Vector chats:Vector users:Vector = messages.InactiveChats;\nbaseThemeClassic#c3a12462 = BaseTheme;\nbaseThemeDay#fbd81688 = BaseTheme;\nbaseThemeNight#b7b31ea8 = BaseTheme;\nbaseThemeTinted#6d5f77ee = BaseTheme;\nbaseThemeArctic#5b11125a = BaseTheme;\ninputThemeSettings#8fde504f flags:# message_colors_animated:flags.2?true base_theme:BaseTheme accent_color:int outbox_accent_color:flags.3?int message_colors:flags.0?Vector wallpaper:flags.1?InputWallPaper wallpaper_settings:flags.1?WallPaperSettings = InputThemeSettings;\nthemeSettings#fa58b6d4 flags:# message_colors_animated:flags.2?true base_theme:BaseTheme accent_color:int outbox_accent_color:flags.3?int message_colors:flags.0?Vector wallpaper:flags.1?WallPaper = ThemeSettings;\nwebPageAttributeTheme#54b56617 flags:# documents:flags.0?Vector settings:flags.1?ThemeSettings = WebPageAttribute;\nmessageUserVote#34d247b4 user_id:long option:bytes date:int = MessageUserVote;\nmessageUserVoteInputOption#3ca5b0ec user_id:long date:int = MessageUserVote;\nmessageUserVoteMultiple#8a65e557 user_id:long options:Vector date:int = MessageUserVote;\nmessages.votesList#823f649 flags:# count:int votes:Vector users:Vector next_offset:flags.0?string = messages.VotesList;\nbankCardOpenUrl#f568028a url:string name:string = BankCardOpenUrl;\npayments.bankCardData#3e24e573 title:string open_urls:Vector = payments.BankCardData;\ndialogFilter#7438f7e8 flags:# contacts:flags.0?true non_contacts:flags.1?true groups:flags.2?true broadcasts:flags.3?true bots:flags.4?true exclude_muted:flags.11?true exclude_read:flags.12?true exclude_archived:flags.13?true id:int title:string emoticon:flags.25?string pinned_peers:Vector include_peers:Vector exclude_peers:Vector = DialogFilter;\ndialogFilterSuggested#77744d4a filter:DialogFilter description:string = DialogFilterSuggested;\nstatsDateRangeDays#b637edaf min_date:int max_date:int = StatsDateRangeDays;\nstatsAbsValueAndPrev#cb43acde current:double previous:double = StatsAbsValueAndPrev;\nstatsPercentValue#cbce2fe0 part:double total:double = StatsPercentValue;\nstatsGraphAsync#4a27eb2d token:string = StatsGraph;\nstatsGraphError#bedc9822 error:string = StatsGraph;\nstatsGraph#8ea464b6 flags:# json:DataJSON zoom_token:flags.0?string = StatsGraph;\nmessageInteractionCounters#ad4fc9bd msg_id:int views:int forwards:int = MessageInteractionCounters;\nstats.broadcastStats#bdf78394 period:StatsDateRangeDays followers:StatsAbsValueAndPrev views_per_post:StatsAbsValueAndPrev shares_per_post:StatsAbsValueAndPrev enabled_notifications:StatsPercentValue growth_graph:StatsGraph followers_graph:StatsGraph mute_graph:StatsGraph top_hours_graph:StatsGraph interactions_graph:StatsGraph iv_interactions_graph:StatsGraph views_by_source_graph:StatsGraph new_followers_by_source_graph:StatsGraph languages_graph:StatsGraph recent_message_interactions:Vector = stats.BroadcastStats;\nhelp.promoDataEmpty#98f6ac75 expires:int = help.PromoData;\nhelp.promoData#8c39793f flags:# proxy:flags.0?true expires:int peer:Peer chats:Vector users:Vector psa_type:flags.1?string psa_message:flags.2?string = help.PromoData;\nvideoSize#de33b094 flags:# type:string w:int h:int size:int video_start_ts:flags.0?double = VideoSize;\nstatsGroupTopPoster#9d04af9b user_id:long messages:int avg_chars:int = StatsGroupTopPoster;\nstatsGroupTopAdmin#d7584c87 user_id:long deleted:int kicked:int banned:int = StatsGroupTopAdmin;\nstatsGroupTopInviter#535f779d user_id:long invitations:int = StatsGroupTopInviter;\nstats.megagroupStats#ef7ff916 period:StatsDateRangeDays members:StatsAbsValueAndPrev messages:StatsAbsValueAndPrev viewers:StatsAbsValueAndPrev posters:StatsAbsValueAndPrev growth_graph:StatsGraph members_graph:StatsGraph new_members_by_source_graph:StatsGraph languages_graph:StatsGraph messages_graph:StatsGraph actions_graph:StatsGraph top_hours_graph:StatsGraph weekdays_graph:StatsGraph top_posters:Vector top_admins:Vector top_inviters:Vector users:Vector = stats.MegagroupStats;\nglobalPrivacySettings#bea2f424 flags:# archive_and_mute_new_noncontact_peers:flags.0?Bool = GlobalPrivacySettings;\nhelp.countryCode#4203c5ef flags:# country_code:string prefixes:flags.0?Vector patterns:flags.1?Vector = help.CountryCode;\nhelp.country#c3878e23 flags:# hidden:flags.0?true iso2:string default_name:string name:flags.1?string country_codes:Vector = help.Country;\nhelp.countriesListNotModified#93cc1f32 = help.CountriesList;\nhelp.countriesList#87d0759e countries:Vector hash:int = help.CountriesList;\nmessageViews#455b853d flags:# views:flags.0?int forwards:flags.1?int replies:flags.2?MessageReplies = MessageViews;\nmessages.messageViews#b6c4f543 views:Vector chats:Vector users:Vector = messages.MessageViews;\nmessages.discussionMessage#a6341782 flags:# messages:Vector max_id:flags.0?int read_inbox_max_id:flags.1?int read_outbox_max_id:flags.2?int unread_count:int chats:Vector users:Vector = messages.DiscussionMessage;\nmessageReplyHeader#a6d57763 flags:# reply_to_msg_id:int reply_to_peer_id:flags.0?Peer reply_to_top_id:flags.1?int = MessageReplyHeader;\nmessageReplies#83d60fc2 flags:# comments:flags.0?true replies:int replies_pts:int recent_repliers:flags.1?Vector channel_id:flags.0?long max_id:flags.2?int read_max_id:flags.3?int = MessageReplies;\npeerBlocked#e8fd8014 peer_id:Peer date:int = PeerBlocked;\nstats.messageStats#8999f295 views_graph:StatsGraph = stats.MessageStats;\ngroupCallDiscarded#7780bcb4 id:long access_hash:long duration:int = GroupCall;\ngroupCall#d597650c flags:# join_muted:flags.1?true can_change_join_muted:flags.2?true join_date_asc:flags.6?true schedule_start_subscribed:flags.8?true can_start_video:flags.9?true record_video_active:flags.11?true id:long access_hash:long participants_count:int title:flags.3?string stream_dc_id:flags.4?int record_start_date:flags.5?int schedule_date:flags.7?int unmuted_video_count:flags.10?int unmuted_video_limit:int version:int = GroupCall;\ninputGroupCall#d8aa840f id:long access_hash:long = InputGroupCall;\ngroupCallParticipant#eba636fe flags:# muted:flags.0?true left:flags.1?true can_self_unmute:flags.2?true just_joined:flags.4?true versioned:flags.5?true min:flags.8?true muted_by_you:flags.9?true volume_by_admin:flags.10?true self:flags.12?true video_joined:flags.15?true peer:Peer date:int active_date:flags.3?int source:int volume:flags.7?int about:flags.11?string raise_hand_rating:flags.13?long video:flags.6?GroupCallParticipantVideo presentation:flags.14?GroupCallParticipantVideo = GroupCallParticipant;\nphone.groupCall#9e727aad call:GroupCall participants:Vector participants_next_offset:string chats:Vector users:Vector = phone.GroupCall;\nphone.groupParticipants#f47751b6 count:int participants:Vector next_offset:string chats:Vector users:Vector version:int = phone.GroupParticipants;\ninlineQueryPeerTypeSameBotPM#3081ed9d = InlineQueryPeerType;\ninlineQueryPeerTypePM#833c0fac = InlineQueryPeerType;\ninlineQueryPeerTypeChat#d766c50a = InlineQueryPeerType;\ninlineQueryPeerTypeMegagroup#5ec4be43 = InlineQueryPeerType;\ninlineQueryPeerTypeBroadcast#6334ee9a = InlineQueryPeerType;\nmessages.historyImport#1662af0b id:long = messages.HistoryImport;\nmessages.historyImportParsed#5e0fb7b9 flags:# pm:flags.0?true group:flags.1?true title:flags.2?string = messages.HistoryImportParsed;\nmessages.affectedFoundMessages#ef8d3e6c pts:int pts_count:int offset:int messages:Vector = messages.AffectedFoundMessages;\nchatInviteImporter#b5cd5f4 user_id:long date:int = ChatInviteImporter;\nmessages.exportedChatInvites#bdc62dcc count:int invites:Vector users:Vector = messages.ExportedChatInvites;\nmessages.exportedChatInvite#1871be50 invite:ExportedChatInvite users:Vector = messages.ExportedChatInvite;\nmessages.exportedChatInviteReplaced#222600ef invite:ExportedChatInvite new_invite:ExportedChatInvite users:Vector = messages.ExportedChatInvite;\nmessages.chatInviteImporters#81b6b00a count:int importers:Vector users:Vector = messages.ChatInviteImporters;\nchatAdminWithInvites#f2ecef23 admin_id:long invites_count:int revoked_invites_count:int = ChatAdminWithInvites;\nmessages.chatAdminsWithInvites#b69b72d7 admins:Vector users:Vector = messages.ChatAdminsWithInvites;\nmessages.checkedHistoryImportPeer#a24de717 confirm_text:string = messages.CheckedHistoryImportPeer;\nphone.joinAsPeers#afe5623f peers:Vector chats:Vector users:Vector = phone.JoinAsPeers;\nphone.exportedGroupCallInvite#204bd158 link:string = phone.ExportedGroupCallInvite;\ngroupCallParticipantVideoSourceGroup#dcb118b7 semantics:string sources:Vector = GroupCallParticipantVideoSourceGroup;\ngroupCallParticipantVideo#67753ac8 flags:# paused:flags.0?true endpoint:string source_groups:Vector audio_source:flags.1?int = GroupCallParticipantVideo;\nstickers.suggestedShortName#85fea03f short_name:string = stickers.SuggestedShortName;\nbotCommandScopeDefault#2f6cb2ab = BotCommandScope;\nbotCommandScopeUsers#3c4f04d8 = BotCommandScope;\nbotCommandScopeChats#6fe1a881 = BotCommandScope;\nbotCommandScopeChatAdmins#b9aa606a = BotCommandScope;\nbotCommandScopePeer#db9d897d peer:InputPeer = BotCommandScope;\nbotCommandScopePeerAdmins#3fd863d1 peer:InputPeer = BotCommandScope;\nbotCommandScopePeerUser#a1321f3 peer:InputPeer user_id:InputUser = BotCommandScope;\naccount.resetPasswordFailedWait#e3779861 retry_date:int = account.ResetPasswordResult;\naccount.resetPasswordRequestedWait#e9effc7d until_date:int = account.ResetPasswordResult;\naccount.resetPasswordOk#e926d63e = account.ResetPasswordResult;\nchatTheme#ed0b5c33 emoticon:string theme:Theme dark_theme:Theme = ChatTheme;\naccount.chatThemesNotModified#e011e1c4 = account.ChatThemes;\naccount.chatThemes#fe4cbebd hash:int themes:Vector = account.ChatThemes;\nsponsoredMessage#2a3c381f flags:# random_id:bytes from_id:Peer start_param:flags.0?string message:string entities:flags.1?Vector = SponsoredMessage;\nmessages.sponsoredMessages#65a4c7d5 messages:Vector chats:Vector users:Vector = messages.SponsoredMessages;\n---functions---\ninitConnection#c1cd5ea9 {X:Type} flags:# api_id:int device_model:string system_version:string app_version:string system_lang_code:string lang_pack:string lang_code:string proxy:flags.0?InputClientProxy params:flags.1?JSONValue query:!X = X;\ninvokeWithLayer#da9b0d0d {X:Type} layer:int query:!X = X;\nauth.sendCode#a677244f phone_number:string api_id:int api_hash:string settings:CodeSettings = auth.SentCode;\nauth.signUp#80eee427 phone_number:string phone_code_hash:string first_name:string last_name:string = auth.Authorization;\nauth.signIn#bcd51581 phone_number:string phone_code_hash:string phone_code:string = auth.Authorization;\nauth.logOut#5717da40 = Bool;\nauth.resetAuthorizations#9fab0d1a = Bool;\nauth.exportAuthorization#e5bfffcd dc_id:int = auth.ExportedAuthorization;\nauth.importAuthorization#a57a7dad id:long bytes:bytes = auth.Authorization;\nauth.bindTempAuthKey#cdd42a05 perm_auth_key_id:long nonce:long expires_at:int encrypted_message:bytes = Bool;\nauth.checkPassword#d18b4d16 password:InputCheckPasswordSRP = auth.Authorization;\nauth.requestPasswordRecovery#d897bc66 = auth.PasswordRecovery;\nauth.resendCode#3ef1a9bf phone_number:string phone_code_hash:string = auth.SentCode;\nauth.cancelCode#1f040578 phone_number:string phone_code_hash:string = Bool;\nauth.dropTempAuthKeys#8e48a188 except_auth_keys:Vector = Bool;\nauth.exportLoginToken#b7e085fe api_id:int api_hash:string except_ids:Vector = auth.LoginToken;\nauth.importLoginToken#95ac5ce4 token:bytes = auth.LoginToken;\naccount.registerDevice#ec86017a flags:# no_muted:flags.0?true token_type:int token:string app_sandbox:Bool secret:bytes other_uids:Vector = Bool;\naccount.unregisterDevice#6a0d3206 token_type:int token:string other_uids:Vector = Bool;\naccount.updateNotifySettings#84be5b93 peer:InputNotifyPeer settings:InputPeerNotifySettings = Bool;\naccount.getNotifySettings#12b3ad31 peer:InputNotifyPeer = PeerNotifySettings;\naccount.updateProfile#78515775 flags:# first_name:flags.0?string last_name:flags.1?string about:flags.2?string = User;\naccount.updateStatus#6628562c offline:Bool = Bool;\naccount.getWallPapers#7967d36 hash:long = account.WallPapers;\naccount.checkUsername#2714d86c username:string = Bool;\naccount.updateUsername#3e0bdd7c username:string = User;\naccount.getPrivacy#dadbc950 key:InputPrivacyKey = account.PrivacyRules;\naccount.setPrivacy#c9f81ce8 key:InputPrivacyKey rules:Vector = account.PrivacyRules;\naccount.getAuthorizations#e320c158 = account.Authorizations;\naccount.resetAuthorization#df77f3bc hash:long = Bool;\naccount.getPassword#548a30f5 = account.Password;\naccount.getPasswordSettings#9cd4eaf9 password:InputCheckPasswordSRP = account.PasswordSettings;\naccount.updatePasswordSettings#a59b102f password:InputCheckPasswordSRP new_settings:account.PasswordInputSettings = Bool;\naccount.sendConfirmPhoneCode#1b3faa88 hash:string settings:CodeSettings = auth.SentCode;\naccount.confirmPhone#5f2178c3 phone_code_hash:string phone_code:string = Bool;\naccount.getTmpPassword#449e0b51 password:InputCheckPasswordSRP period:int = account.TmpPassword;\naccount.sendVerifyPhoneCode#a5a356f9 phone_number:string settings:CodeSettings = auth.SentCode;\naccount.confirmPasswordEmail#8fdf1920 code:string = Bool;\naccount.getContactSignUpNotification#9f07c728 = Bool;\naccount.setContactSignUpNotification#cff43f61 silent:Bool = Bool;\naccount.getNotifyExceptions#53577479 flags:# compare_sound:flags.1?true peer:flags.0?InputNotifyPeer = Updates;\naccount.uploadWallPaper#dd853661 file:InputFile mime_type:string settings:WallPaperSettings = WallPaper;\naccount.setContentSettings#b574b16b flags:# sensitive_enabled:flags.0?true = Bool;\naccount.getContentSettings#8b9b4dae = account.ContentSettings;\nusers.getUsers#d91a548 id:Vector = Vector;\nusers.getFullUser#ca30a5b1 id:InputUser = UserFull;\ncontacts.getContacts#5dd69e12 hash:long = contacts.Contacts;\ncontacts.importContacts#2c800be5 contacts:Vector = contacts.ImportedContacts;\ncontacts.deleteContacts#96a0e00 id:Vector = Updates;\ncontacts.block#68cc1411 id:InputPeer = Bool;\ncontacts.unblock#bea65d50 id:InputPeer = Bool;\ncontacts.getBlocked#f57c350f offset:int limit:int = contacts.Blocked;\ncontacts.search#11f812d8 q:string limit:int = contacts.Found;\ncontacts.resolveUsername#f93ccba3 username:string = contacts.ResolvedPeer;\ncontacts.getTopPeers#973478b6 flags:# correspondents:flags.0?true bots_pm:flags.1?true bots_inline:flags.2?true phone_calls:flags.3?true forward_users:flags.4?true forward_chats:flags.5?true groups:flags.10?true channels:flags.15?true offset:int limit:int hash:long = contacts.TopPeers;\ncontacts.addContact#e8f463d0 flags:# add_phone_privacy_exception:flags.0?true id:InputUser first_name:string last_name:string phone:string = Updates;\nmessages.getMessages#63c66506 id:Vector = messages.Messages;\nmessages.getDialogs#a0f4cb4f flags:# exclude_pinned:flags.0?true folder_id:flags.1?int offset_date:int offset_id:int offset_peer:InputPeer limit:int hash:long = messages.Dialogs;\nmessages.getHistory#4423e6c5 peer:InputPeer offset_id:int offset_date:int add_offset:int limit:int max_id:int min_id:int hash:long = messages.Messages;\nmessages.search#a0fda762 flags:# peer:InputPeer q:string from_id:flags.0?InputPeer top_msg_id:flags.1?int filter:MessagesFilter min_date:int max_date:int offset_id:int add_offset:int limit:int max_id:int min_id:int hash:long = messages.Messages;\nmessages.readHistory#e306d3a peer:InputPeer max_id:int = messages.AffectedMessages;\nmessages.deleteHistory#1c015b09 flags:# just_clear:flags.0?true revoke:flags.1?true peer:InputPeer max_id:int = messages.AffectedHistory;\nmessages.deleteMessages#e58e95d2 flags:# revoke:flags.0?true id:Vector = messages.AffectedMessages;\nmessages.receivedMessages#5a954c0 max_id:int = Vector;\nmessages.setTyping#58943ee2 flags:# peer:InputPeer top_msg_id:flags.0?int action:SendMessageAction = Bool;\nmessages.sendMessage#520c3870 flags:# no_webpage:flags.1?true silent:flags.5?true background:flags.6?true clear_draft:flags.7?true peer:InputPeer reply_to_msg_id:flags.0?int message:string random_id:long reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector schedule_date:flags.10?int = Updates;\nmessages.sendMedia#3491eba9 flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true peer:InputPeer reply_to_msg_id:flags.0?int media:InputMedia message:string random_id:long reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector schedule_date:flags.10?int = Updates;\nmessages.forwardMessages#d9fee60e 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 from_peer:InputPeer id:Vector random_id:Vector to_peer:InputPeer schedule_date:flags.10?int = Updates;\nmessages.report#8953ab4e peer:InputPeer id:Vector reason:ReportReason message:string = Bool;\nmessages.getChats#49e9528f id:Vector = messages.Chats;\nmessages.getFullChat#aeb00b34 chat_id:long = messages.ChatFull;\nmessages.editChatTitle#73783ffd chat_id:long title:string = Updates;\nmessages.editChatPhoto#35ddd674 chat_id:long photo:InputChatPhoto = Updates;\nmessages.addChatUser#f24753e3 chat_id:long user_id:InputUser fwd_limit:int = Updates;\nmessages.deleteChatUser#a2185cab flags:# revoke_history:flags.0?true chat_id:long user_id:InputUser = Updates;\nmessages.createChat#9cb126e users:Vector title:string = Updates;\nmessages.getDhConfig#26cf8950 version:int random_length:int = messages.DhConfig;\nmessages.readMessageContents#36a73f77 id:Vector = messages.AffectedMessages;\nmessages.getStickers#d5a5d3a1 emoticon:string hash:long = messages.Stickers;\nmessages.getAllStickers#b8a0a1a8 hash:long = messages.AllStickers;\nmessages.getWebPagePreview#8b68b0cc flags:# message:string entities:flags.3?Vector = MessageMedia;\nmessages.exportChatInvite#14b9bcd7 flags:# legacy_revoke_permanent:flags.2?true peer:InputPeer expire_date:flags.0?int usage_limit:flags.1?int = ExportedChatInvite;\nmessages.checkChatInvite#3eadb1bb hash:string = ChatInvite;\nmessages.importChatInvite#6c50051c hash:string = Updates;\nmessages.getStickerSet#2619a90e stickerset:InputStickerSet = messages.StickerSet;\nmessages.installStickerSet#c78fe460 stickerset:InputStickerSet archived:Bool = messages.StickerSetInstallResult;\nmessages.uninstallStickerSet#f96e55de stickerset:InputStickerSet = Bool;\nmessages.startBot#e6df7378 bot:InputUser peer:InputPeer random_id:long start_param:string = Updates;\nmessages.migrateChat#a2875319 chat_id:long = Updates;\nmessages.searchGlobal#4bc6589a flags:# folder_id:flags.0?int q:string filter:MessagesFilter min_date:int max_date:int offset_rate:int offset_peer:InputPeer offset_id:int limit:int = messages.Messages;\nmessages.getDocumentByHash#338e2464 sha256:bytes size:int mime_type:string = Document;\nmessages.getSavedGifs#5cf09635 hash:long = messages.SavedGifs;\nmessages.getInlineBotResults#514e999d flags:# bot:InputUser peer:InputPeer geo_point:flags.0?InputGeoPoint query:string offset:string = messages.BotResults;\nmessages.sendInlineBotResult#220815b0 flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true hide_via:flags.11?true peer:InputPeer reply_to_msg_id:flags.0?int random_id:long query_id:long id:string schedule_date:flags.10?int = Updates;\nmessages.editMessage#48f71778 flags:# no_webpage:flags.1?true peer:InputPeer id:int message:flags.11?string media:flags.14?InputMedia reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector schedule_date:flags.15?int = Updates;\nmessages.getBotCallbackAnswer#9342ca07 flags:# game:flags.1?true peer:InputPeer msg_id:int data:flags.0?bytes password:flags.2?InputCheckPasswordSRP = messages.BotCallbackAnswer;\nmessages.getPeerDialogs#e470bcfd peers:Vector = messages.PeerDialogs;\nmessages.saveDraft#bc39e14b flags:# no_webpage:flags.1?true reply_to_msg_id:flags.0?int peer:InputPeer message:string entities:flags.3?Vector = Bool;\nmessages.getFeaturedStickers#64780b14 hash:long = messages.FeaturedStickers;\nmessages.readFeaturedStickers#5b118126 id:Vector = Bool;\nmessages.getRecentStickers#9da9403b flags:# attached:flags.0?true hash:long = messages.RecentStickers;\nmessages.getCommonChats#e40ca104 user_id:InputUser max_id:long limit:int = messages.Chats;\nmessages.getWebPage#32ca8f91 url:string hash:int = WebPage;\nmessages.toggleDialogPin#a731e257 flags:# pinned:flags.0?true peer:InputDialogPeer = Bool;\nmessages.getPinnedDialogs#d6b94df2 folder_id:int = messages.PeerDialogs;\nmessages.uploadMedia#519bc2b1 peer:InputPeer media:InputMedia = MessageMedia;\nmessages.getFavedStickers#4f1aaa9 hash:long = messages.FavedStickers;\nmessages.faveSticker#b9ffc55b id:InputDocument unfave:Bool = Bool;\nmessages.sendMultiMedia#cc0110cb flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true peer:InputPeer reply_to_msg_id:flags.0?int multi_media:Vector schedule_date:flags.10?int = Updates;\nmessages.searchStickerSets#35705b8a flags:# exclude_featured:flags.0?true q:string hash:long = messages.FoundStickerSets;\nmessages.markDialogUnread#c286d98f flags:# unread:flags.0?true peer:InputDialogPeer = Bool;\nmessages.updatePinnedMessage#d2aaf7ec flags:# silent:flags.0?true unpin:flags.1?true pm_oneside:flags.2?true peer:InputPeer id:int = Updates;\nmessages.sendVote#10ea6184 peer:InputPeer msg_id:int options:Vector = Updates;\nmessages.getOnlines#6e2be050 peer:InputPeer = ChatOnlines;\nmessages.editChatAbout#def60797 peer:InputPeer about:string = Bool;\nmessages.editChatDefaultBannedRights#a5866b41 peer:InputPeer banned_rights:ChatBannedRights = Updates;\nmessages.getEmojiKeywordsDifference#1508b6af lang_code:string from_version:int = EmojiKeywordsDifference;\nmessages.getScheduledHistory#f516760b peer:InputPeer hash:long = messages.Messages;\nmessages.sendScheduledMessages#bd38850a peer:InputPeer id:Vector = Updates;\nmessages.deleteScheduledMessages#59ae2b16 peer:InputPeer id:Vector = Updates;\nmessages.getPollVotes#b86e380e flags:# peer:InputPeer id:int option:flags.0?bytes offset:flags.1?string limit:int = messages.VotesList;\nmessages.getDialogFilters#f19ed96d = Vector;\nmessages.getSuggestedDialogFilters#a29cd42c = Vector;\nmessages.updateDialogFilter#1ad4a04a flags:# id:int filter:flags.0?DialogFilter = Bool;\nmessages.getReplies#22ddd30c peer:InputPeer msg_id:int offset_id:int offset_date:int add_offset:int limit:int max_id:int min_id:int hash:long = messages.Messages;\nmessages.getDiscussionMessage#446972fd peer:InputPeer msg_id:int = messages.DiscussionMessage;\nmessages.readDiscussion#f731a9f4 peer:InputPeer msg_id:int read_max_id:int = Bool;\nmessages.unpinAllMessages#f025bc8b peer:InputPeer = messages.AffectedHistory;\nmessages.deleteChat#5bd0ee50 chat_id:long = Bool;\nupdates.getState#edd4882a = updates.State;\nupdates.getDifference#25939651 flags:# pts:int pts_total_limit:flags.0?int date:int qts:int = updates.Difference;\nupdates.getChannelDifference#3173d78 flags:# force:flags.0?true channel:InputChannel filter:ChannelMessagesFilter pts:int limit:int = updates.ChannelDifference;\nphotos.uploadProfilePhoto#89f30f69 flags:# file:flags.0?InputFile video:flags.1?InputFile video_start_ts:flags.2?double = photos.Photo;\nphotos.getUserPhotos#91cd32a8 user_id:InputUser offset:int max_id:long limit:int = photos.Photos;\nupload.saveFilePart#b304a621 file_id:long file_part:int bytes:bytes = Bool;\nupload.getFile#b15a9afc flags:# precise:flags.0?true cdn_supported:flags.1?true location:InputFileLocation offset:int limit:int = upload.File;\nupload.saveBigFilePart#de7b673d file_id:long file_part:int file_total_parts:int bytes:bytes = Bool;\nupload.getWebFile#24e6818d location:InputWebFileLocation offset:int limit:int = upload.WebFile;\nhelp.getConfig#c4f9186b = Config;\nhelp.getNearestDc#1fb33026 = NearestDc;\nhelp.getSupport#9cdf08cd = help.Support;\nhelp.acceptTermsOfService#ee72f79a id:DataJSON = Bool;\nhelp.getCountriesList#735787a8 lang_code:string hash:int = help.CountriesList;\nchannels.readHistory#cc104937 channel:InputChannel max_id:int = Bool;\nchannels.deleteMessages#84c1fd4e channel:InputChannel id:Vector = messages.AffectedMessages;\nchannels.getMessages#ad8c9a23 channel:InputChannel id:Vector = messages.Messages;\nchannels.getParticipants#77ced9d0 channel:InputChannel filter:ChannelParticipantsFilter offset:int limit:int hash:long = channels.ChannelParticipants;\nchannels.getParticipant#a0ab6cc6 channel:InputChannel participant:InputPeer = channels.ChannelParticipant;\nchannels.getChannels#a7f6bbb id:Vector = messages.Chats;\nchannels.getFullChannel#8736a09 channel:InputChannel = messages.ChatFull;\nchannels.createChannel#3d5fb10f flags:# broadcast:flags.0?true megagroup:flags.1?true for_import:flags.3?true title:string about:string geo_point:flags.2?InputGeoPoint address:flags.2?string = Updates;\nchannels.editAdmin#d33c8902 channel:InputChannel user_id:InputUser admin_rights:ChatAdminRights rank:string = Updates;\nchannels.editTitle#566decd0 channel:InputChannel title:string = Updates;\nchannels.editPhoto#f12e57c9 channel:InputChannel photo:InputChatPhoto = Updates;\nchannels.checkUsername#10e6bd2c channel:InputChannel username:string = Bool;\nchannels.updateUsername#3514b3de channel:InputChannel username:string = Bool;\nchannels.joinChannel#24b524c5 channel:InputChannel = Updates;\nchannels.leaveChannel#f836aa95 channel:InputChannel = Updates;\nchannels.inviteToChannel#199f3a6c channel:InputChannel users:Vector = Updates;\nchannels.deleteChannel#c0111fe3 channel:InputChannel = Updates;\nchannels.toggleSignatures#1f69b606 channel:InputChannel enabled:Bool = Updates;\nchannels.editBanned#96e6cd81 channel:InputChannel participant:InputPeer banned_rights:ChatBannedRights = Updates;\nchannels.readMessageContents#eab5dc38 channel:InputChannel id:Vector = Bool;\nchannels.togglePreHistoryHidden#eabbb94c channel:InputChannel enabled:Bool = Updates;\nchannels.getGroupsForDiscussion#f5dad378 = messages.Chats;\nchannels.setDiscussionGroup#40582bb2 broadcast:InputChannel group:InputChannel = Bool;\npayments.getPaymentForm#8a333c8d flags:# peer:InputPeer msg_id:int theme_params:flags.0?DataJSON = payments.PaymentForm;\npayments.getPaymentReceipt#2478d1cc peer:InputPeer msg_id:int = payments.PaymentReceipt;\npayments.validateRequestedInfo#db103170 flags:# save:flags.0?true peer:InputPeer msg_id:int info:PaymentRequestedInfo = payments.ValidatedRequestedInfo;\npayments.sendPaymentForm#30c3bc9d flags:# form_id:long peer:InputPeer msg_id:int requested_info_id:flags.0?string shipping_option_id:flags.1?string credentials:InputPaymentCredentials tip_amount:flags.2?long = payments.PaymentResult;\npayments.getSavedInfo#227d824b = payments.SavedInfo;\nlangpack.getLangPack#f2f2330a lang_pack:string lang_code:string = LangPackDifference;\nlangpack.getStrings#efea3803 lang_pack:string lang_code:string keys:Vector = Vector;\nlangpack.getLanguages#42c6978f lang_pack:string = Vector;\nfolders.editPeerFolders#6847d0ab folder_peers:Vector = Updates;\n`;","const { inflate } = require('pako/dist/pako_inflate');\nconst { serializeBytes } = require('../index');\n\n// CONTEST const { deflate } = require('pako/dist/pako_deflate')\n\nclass GZIPPacked {\n static CONSTRUCTOR_ID = 0x3072cfa1;\n\n static classType = 'constructor';\n\n constructor(data) {\n this.data = data;\n this.CONSTRUCTOR_ID = 0x3072cfa1;\n this.classType = 'constructor';\n }\n\n static async gzipIfSmaller(contentRelated, data) {\n if (contentRelated && data.length > 512) {\n const gzipped = await (new GZIPPacked(data)).toBytes();\n if (gzipped.length < data.length) {\n return gzipped;\n }\n }\n return data;\n }\n\n static gzip(input) {\n return Buffer.from(input);\n // TODO this usually makes it faster for large requests\n // return Buffer.from(deflate(input, { level: 9, gzip: true }))\n }\n\n static ungzip(input) {\n return Buffer.from(inflate(input));\n }\n\n static read(reader) {\n const constructor = reader.readInt(false);\n if (constructor !== GZIPPacked.CONSTRUCTOR_ID) {\n throw new Error('not equal');\n }\n return GZIPPacked.gzip(reader.tgReadBytes());\n }\n\n static async fromReader(reader) {\n return new GZIPPacked(await GZIPPacked.ungzip(reader.tgReadBytes()));\n }\n\n async toBytes() {\n const g = Buffer.alloc(4);\n g.writeUInt32LE(GZIPPacked.CONSTRUCTOR_ID, 0);\n return Buffer.concat([\n g,\n serializeBytes(await GZIPPacked.gzip(this.data)),\n ]);\n }\n}\n\nmodule.exports = GZIPPacked;\n","const TLMessage = require('./TLMessage');\n\nclass MessageContainer {\n static CONSTRUCTOR_ID = 0x73f1f8dc;\n\n static classType = 'constructor';\n\n // Maximum size in bytes for the inner payload of the container.\n // Telegram will close the connection if the payload is bigger.\n // The overhead of the container itself is subtracted.\n static MAXIMUM_SIZE = 1044456 - 8;\n\n // Maximum amount of messages that can't be sent inside a single\n // container, inclusive. Beyond this limit Telegram will respond\n // with BAD_MESSAGE 64 (invalid container).\n //\n // This limit is not 100% accurate and may in some cases be higher.\n // However, sending up to 100 requests at once in a single container\n // is a reasonable conservative value, since it could also depend on\n // other factors like size per request, but we cannot know this.\n static MAXIMUM_LENGTH = 100;\n\n constructor(messages) {\n this.CONSTRUCTOR_ID = 0x73f1f8dc;\n this.messages = messages;\n this.classType = 'constructor';\n }\n\n static fromReader(reader) {\n const messages = [];\n const length = reader.readInt();\n for (let x = 0; x < length; x++) {\n const msgId = reader.readLong();\n const seqNo = reader.readInt();\n const containerLength = reader.readInt();\n const before = reader.tellPosition();\n const obj = reader.tgReadObject();\n reader.setPosition(before + containerLength);\n const tlMessage = new TLMessage(msgId, seqNo, obj);\n messages.push(tlMessage);\n }\n return new MessageContainer(messages);\n }\n}\n\nmodule.exports = MessageContainer;\n","const { RpcError } = require('../index').constructors;\nconst GZIPPacked = require('./GZIPPacked');\n\nclass RPCResult {\n static CONSTRUCTOR_ID = 0xf35c6d01;\n\n static classType = 'constructor';\n\n constructor(reqMsgId, body, error) {\n this.CONSTRUCTOR_ID = 0xf35c6d01;\n this.reqMsgId = reqMsgId;\n this.body = body;\n this.error = error;\n this.classType = 'constructor';\n }\n\n static async fromReader(reader) {\n const msgId = reader.readLong();\n const innerCode = reader.readInt(false);\n if (innerCode === RpcError.CONSTRUCTOR_ID) {\n return new RPCResult(msgId, undefined, RpcError.fromReader(reader));\n }\n if (innerCode === GZIPPacked.CONSTRUCTOR_ID) {\n return new RPCResult(msgId, (await GZIPPacked.fromReader(reader)).data);\n }\n reader.seek(-4);\n // This reader.read() will read more than necessary, but it's okay.\n // We could make use of MessageContainer's length here, but since\n // it's not necessary we don't need to care about it.\n return new RPCResult(msgId, reader.read(), undefined);\n }\n}\n\nmodule.exports = RPCResult;\n","class TLMessage {\n static SIZE_OVERHEAD = 12;\n\n static classType = 'constructor';\n\n constructor(msgId, seqNo, obj) {\n this.msgId = msgId;\n this.seqNo = seqNo;\n this.obj = obj;\n this.classType = 'constructor';\n }\n}\n\nmodule.exports = TLMessage;\n","const TLMessage = require('./TLMessage');\nconst RPCResult = require('./RPCResult');\nconst MessageContainer = require('./MessageContainer');\nconst GZIPPacked = require('./GZIPPacked');\n\nconst coreObjects = {\n [RPCResult.CONSTRUCTOR_ID]: RPCResult,\n [GZIPPacked.CONSTRUCTOR_ID]: GZIPPacked,\n [MessageContainer.CONSTRUCTOR_ID]: MessageContainer,\n};\n\nmodule.exports = {\n TLMessage,\n RPCResult,\n MessageContainer,\n GZIPPacked,\n coreObjects,\n};\n","const snakeToCamelCase = (name) => {\n const result = name.replace(/(?:^|_)([a-z])/g, (_, g) => g.toUpperCase());\n return result.replace(/_/g, '');\n};\nconst variableSnakeToCamelCase = (str) => str.replace(\n /([-_][a-z])/g,\n (group) => group.toUpperCase()\n .replace('-', '')\n .replace('_', ''),\n);\n\nconst CORE_TYPES = new Set([\n 0xbc799737, // boolFalse#bc799737 = Bool;\n 0x997275b5, // boolTrue#997275b5 = Bool;\n 0x3fedd339, // true#3fedd339 = True;\n 0xc4b9f9bb, // error#c4b9f9bb code:int text:string = Error;\n 0x56730bcc, // null#56730bcc = Null;\n]);\nconst AUTH_KEY_TYPES = new Set([\n 0x05162463, // resPQ,\n 0x83c95aec, // p_q_inner_data\n 0xa9f55f95, // p_q_inner_data_dc\n 0x3c6a84d4, // p_q_inner_data_temp\n 0x56fddf88, // p_q_inner_data_temp_dc\n 0xd0e8075c, // server_DH_params_ok\n 0xb5890dba, // server_DH_inner_data\n 0x6643b654, // client_DH_inner_data\n 0xd712e4be, // req_DH_params\n 0xf5045f1f, // set_client_DH_params\n 0x3072cfa1, // gzip_packed\n]);\n\n// This is copy-pasted from `gramjs/Helpers.js` to not depend on TypeScript modules\nfunction makeCRCTable() {\n let c;\n const crcTable = [];\n for (let n = 0; n < 256; n++) {\n c = n;\n for (let k = 0; k < 8; k++) {\n c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));\n }\n crcTable[n] = c;\n }\n return crcTable;\n}\n\nlet crcTable;\n\nfunction crc32(buf) {\n if (!crcTable) {\n crcTable = makeCRCTable();\n }\n if (!Buffer.isBuffer(buf)) {\n buf = Buffer.from(buf);\n }\n let crc = -1;\n\n for (let index = 0; index < buf.length; index++) {\n const byte = buf[index];\n crc = crcTable[(crc ^ byte) & 0xff] ^ (crc >>> 8);\n }\n return (crc ^ (-1)) >>> 0;\n}\n\nconst findAll = (regex, str, matches = []) => {\n if (!regex.flags.includes('g')) {\n regex = new RegExp(regex.source, 'g');\n }\n\n const res = regex.exec(str);\n\n if (res) {\n matches.push(res.slice(1));\n findAll(regex, str, matches);\n }\n\n return matches;\n};\n\nconst fromLine = (line, isFunction) => {\n const match = line.match(/([\\w.]+)(?:#([0-9a-fA-F]+))?(?:\\s{?\\w+:[\\w\\d<>#.?!]+}?)*\\s=\\s([\\w\\d<>#.?]+);$/);\n if (!match) {\n // Probably \"vector#1cb5c415 {t:Type} # [ t ] = Vector t;\"\n throw new Error(`Cannot parse TLObject ${line}`);\n }\n\n const argsMatch = findAll(/({)?(\\w+):([\\w\\d<>#.?!]+)}?/, line);\n const currentConfig = {\n name: match[1],\n constructorId: parseInt(match[2], 16),\n argsConfig: {},\n subclassOfId: crc32(match[3]),\n result: match[3],\n isFunction,\n namespace: undefined,\n };\n if (!currentConfig.constructorId) {\n const hexId = '';\n let args;\n\n if (Object.values(currentConfig.argsConfig).length) {\n args = ` ${Object.keys(currentConfig.argsConfig)\n .map((arg) => arg.toString())\n .join(' ')}`;\n } else {\n args = '';\n }\n\n const representation = `${currentConfig.name}${hexId}${args} = ${currentConfig.result}`\n .replace(/(:|\\?)bytes /g, '$1string ')\n .replace(/|{|}/g, '')\n .replace(/ \\w+:flags\\.\\d+\\?true/g, '');\n\n if (currentConfig.name === 'inputMediaInvoice') {\n // eslint-disable-next-line no-empty\n if (currentConfig.name === 'inputMediaInvoice') {\n }\n }\n\n currentConfig.constructorId = crc32(Buffer.from(representation, 'utf8'));\n }\n for (const [brace, name, argType] of argsMatch) {\n if (brace === undefined) {\n currentConfig.argsConfig[variableSnakeToCamelCase(name)] = buildArgConfig(name, argType);\n }\n }\n if (currentConfig.name.includes('.')) {\n [currentConfig.namespace, currentConfig.name] = currentConfig.name.split(/\\.(.+)/);\n }\n currentConfig.name = snakeToCamelCase(currentConfig.name);\n /*\n for (const arg in currentConfig.argsConfig){\n if (currentConfig.argsConfig.hasOwnProperty(arg)){\n if (currentConfig.argsConfig[arg].flagIndicator){\n delete currentConfig.argsConfig[arg]\n }\n }\n } */\n return currentConfig;\n};\n\nfunction buildArgConfig(name, argType) {\n name = name === 'self' ? 'is_self' : name;\n // Default values\n const currentConfig = {\n isVector: false,\n isFlag: false,\n skipConstructorId: false,\n flagIndex: -1,\n flagIndicator: true,\n type: undefined,\n useVectorId: undefined,\n };\n\n // The type can be an indicator that other arguments will be flags\n if (argType !== '#') {\n currentConfig.flagIndicator = false;\n // Strip the exclamation mark always to have only the name\n currentConfig.type = argType.replace(/^!+/, '');\n\n // The type may be a flag (flags.IDX?REAL_TYPE)\n // Note that 'flags' is NOT the flags name; this\n // is determined by a previous argument\n // However, we assume that the argument will always be called 'flags'\n // @ts-ignore\n const flagMatch = currentConfig.type.match(/flags.(\\d+)\\?([\\w<>.]+)/);\n\n if (flagMatch) {\n currentConfig.isFlag = true;\n currentConfig.flagIndex = Number(flagMatch[1]);\n // Update the type to match the exact type, not the \"flagged\" one\n [, , currentConfig.type] = flagMatch;\n }\n\n // Then check if the type is a Vector\n // @ts-ignore\n const vectorMatch = currentConfig.type.match(/[Vv]ector<([\\w\\d.]+)>/);\n\n if (vectorMatch) {\n currentConfig.isVector = true;\n\n // If the type's first letter is not uppercase, then\n // it is a constructor and we use (read/write) its ID.\n // @ts-ignore\n currentConfig.useVectorId = currentConfig.type.charAt(0) === 'V';\n\n // Update the type to match the one inside the vector\n [, currentConfig.type] = vectorMatch;\n }\n\n // See use_vector_id. An example of such case is ipPort in\n // help.configSpecial\n // @ts-ignore\n if (/^[a-z]$/.test(currentConfig.type.split('.')\n .pop()\n .charAt(0))\n ) {\n currentConfig.skipConstructorId = true;\n }\n\n // The name may contain \"date\" in it, if this is the case and\n // the type is \"int\", we can safely assume that this should be\n // treated as a \"date\" object. Note that this is not a valid\n // Telegram object, but it's easier to work with\n // if (\n // this.type === 'int' &&\n // (/(\\b|_)([dr]ate|until|since)(\\b|_)/.test(name) ||\n // ['expires', 'expires_at', 'was_online'].includes(name))\n // ) {\n // this.type = 'date';\n // }\n }\n return currentConfig;\n}\n\n\nfunction* parseTl(content, layer, methods = [], ignoreIds = CORE_TYPES) {\n (methods || []).reduce((o, m) => ({\n ...o,\n [m.name]: m,\n }), {});\n const objAll = [];\n const objByName = {};\n const objByType = {};\n\n const file = content;\n\n let isFunction = false;\n\n for (let line of file.split('\\n')) {\n const commentIndex = line.indexOf('//');\n\n if (commentIndex !== -1) {\n line = line.slice(0, commentIndex);\n }\n\n line = line.trim();\n\n if (!line) {\n continue;\n }\n\n const match = line.match(/---(\\w+)---/);\n\n if (match) {\n const [, followingTypes] = match;\n isFunction = followingTypes === 'functions';\n continue;\n }\n\n try {\n const result = fromLine(line, isFunction);\n\n if (ignoreIds.has(result.constructorId)) {\n continue;\n }\n\n objAll.push(result);\n\n if (!result.isFunction) {\n if (!objByType[result.result]) {\n objByType[result.result] = [];\n }\n\n objByName[result.name] = result;\n objByType[result.result].push(result);\n }\n } catch (e) {\n if (!e.toString()\n .includes('vector#1cb5c415')) {\n throw e;\n }\n }\n }\n\n // Once all objects have been parsed, replace the\n // string type from the arguments with references\n for (const obj of objAll) {\n // console.log(obj)\n if (AUTH_KEY_TYPES.has(obj.constructorId)) {\n for (const arg in obj.argsConfig) {\n if (obj.argsConfig[arg].type === 'string') {\n obj.argsConfig[arg].type = 'bytes';\n }\n }\n }\n }\n\n for (const obj of objAll) {\n yield obj;\n }\n}\n\nfunction serializeBytes(data) {\n if (!(data instanceof Buffer)) {\n if (typeof data === 'string') {\n data = Buffer.from(data);\n } else {\n throw Error(`Bytes or str expected, not ${data.constructor.name}`);\n }\n }\n const r = [];\n let padding;\n if (data.length < 254) {\n padding = (data.length + 1) % 4;\n if (padding !== 0) {\n padding = 4 - padding;\n }\n r.push(Buffer.from([data.length]));\n r.push(data);\n } else {\n padding = data.length % 4;\n if (padding !== 0) {\n padding = 4 - padding;\n }\n r.push(Buffer.from([254, data.length % 256, (data.length >> 8) % 256, (data.length >> 16) % 256]));\n r.push(data);\n }\n r.push(Buffer.alloc(padding)\n .fill(0));\n\n return Buffer.concat(r);\n}\n\nfunction serializeDate(dt) {\n if (!dt) {\n return Buffer.alloc(4)\n .fill(0);\n }\n if (dt instanceof Date) {\n dt = Math.floor((Date.now() - dt.getTime()) / 1000);\n }\n if (typeof dt === 'number') {\n const t = Buffer.alloc(4);\n t.writeInt32LE(dt, 0);\n return t;\n }\n throw Error(`Cannot interpret \"${dt}\" as a date`);\n}\n\nmodule.exports = {\n findAll,\n parseTl,\n buildArgConfig,\n fromLine,\n CORE_TYPES,\n serializeDate,\n serializeBytes,\n snakeToCamelCase,\n variableSnakeToCamelCase,\n};\n","const api = require('./api');\nconst {\n serializeBytes,\n serializeDate,\n} = require('./generationHelpers');\n\nmodule.exports = {\n // TODO Refactor internal usages to always use `api`.\n constructors: api,\n requests: api,\n serializeBytes,\n serializeDate,\n};\n","module.exports = `resPQ#05162463 nonce:int128 server_nonce:int128 pq:string server_public_key_fingerprints:Vector = ResPQ;\np_q_inner_data#83c95aec pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 = P_Q_inner_data;\nserver_DH_params_fail#79cb045d nonce:int128 server_nonce:int128 new_nonce_hash:int128 = Server_DH_Params;\nserver_DH_params_ok#d0e8075c nonce:int128 server_nonce:int128 encrypted_answer:string = Server_DH_Params;\nserver_DH_inner_data#b5890dba nonce:int128 server_nonce:int128 g:int dh_prime:string g_a:string server_time:int = Server_DH_inner_data;\nclient_DH_inner_data#6643b654 nonce:int128 server_nonce:int128 retry_id:long g_b:string = Client_DH_Inner_Data;\ndh_gen_ok#3bcbf734 nonce:int128 server_nonce:int128 new_nonce_hash1:int128 = Set_client_DH_params_answer;\ndh_gen_retry#46dc1fb9 nonce:int128 server_nonce:int128 new_nonce_hash2:int128 = Set_client_DH_params_answer;\ndh_gen_fail#a69dae02 nonce:int128 server_nonce:int128 new_nonce_hash3:int128 = Set_client_DH_params_answer;\ndestroy_auth_key_ok#f660e1d4 = DestroyAuthKeyRes;\ndestroy_auth_key_none#0a9f2259 = DestroyAuthKeyRes;\ndestroy_auth_key_fail#ea109b13 = DestroyAuthKeyRes;\n---functions---\nreq_pq#60469778 nonce:int128 = ResPQ;\nreq_pq_multi#be7e8ef1 nonce:int128 = ResPQ;\nreq_pq_multi_new#51b410fd nonce:int128 = ResPQ;\nreq_DH_params#d712e4be nonce:int128 server_nonce:int128 p:string q:string public_key_fingerprint:long encrypted_data:string = Server_DH_Params;\nset_client_DH_params#f5045f1f nonce:int128 server_nonce:int128 encrypted_data:string = Set_client_DH_params_answer;\ndestroy_auth_key#d1435160 = DestroyAuthKeyRes;\n---types---\nmsgs_ack#62d6b459 msg_ids:Vector = MsgsAck;\nbad_msg_notification#a7eff811 bad_msg_id:long bad_msg_seqno:int error_code:int = BadMsgNotification;\nbad_server_salt#edab447b bad_msg_id:long bad_msg_seqno:int error_code:int new_server_salt:long = BadMsgNotification;\nmsgs_state_req#da69fb52 msg_ids:Vector = MsgsStateReq;\nmsgs_state_info#04deb57d req_msg_id:long info:string = MsgsStateInfo;\nmsgs_all_info#8cc0d131 msg_ids:Vector info:string = MsgsAllInfo;\nmsg_detailed_info#276d3ec6 msg_id:long answer_msg_id:long bytes:int status:int = MsgDetailedInfo;\nmsg_new_detailed_info#809db6df answer_msg_id:long bytes:int status:int = MsgDetailedInfo;\nmsg_resend_req#7d861a08 msg_ids:Vector = MsgResendReq;\nrpc_error#2144ca19 error_code:int error_message:string = RpcError;\nfuture_salt#0949d9dc valid_since:int valid_until:int salt:long = FutureSalt;\nfuture_salts#ae500895 req_msg_id:long now:int salts:vector = FutureSalts;\npong#347773c5 msg_id:long ping_id:long = Pong;\ndestroy_session_ok#e22045fc session_id:long = DestroySessionRes;\ndestroy_session_none#62d350c9 session_id:long = DestroySessionRes;\nnew_session_created#9ec20908 first_msg_id:long unique_id:long server_salt:long = NewSession;\n---functions---\nping#7abe77ec ping_id:long = Pong;\nping_delay_disconnect#f3427b8c ping_id:long disconnect_delay:int = Pong;`;","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\tid: moduleId,\n\t\tloaded: false,\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Flag the module as loaded\n\tmodule.loaded = true;\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n// expose the modules object (__webpack_modules__)\n__webpack_require__.m = __webpack_modules__;\n\n// the startup function\n__webpack_require__.x = () => {\n\t// Load entry module and return exports\n\t// This entry module depends on other loaded chunks and execution need to be delayed\n\tvar __webpack_exports__ = __webpack_require__.O(undefined, [592], () => (__webpack_require__(6514)))\n\t__webpack_exports__ = __webpack_require__.O(__webpack_exports__);\n\treturn __webpack_exports__;\n};\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.f = {};\n// This file contains only the entry chunk.\n// The chunk loading function for additional chunks\n__webpack_require__.e = (chunkId) => {\n\treturn Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => {\n\t\t__webpack_require__.f[key](chunkId, promises);\n\t\treturn promises;\n\t}, []));\n};","// This function allow to reference async chunks and sibling chunks for the entrypoint\n__webpack_require__.u = (chunkId) => {\n\t// return url for filenames based on template\n\treturn \"\" + chunkId + \".\" + \"d7ca037ed9b7d1c6792a\" + \".js\";\n};","// This function allow to reference all chunks\n__webpack_require__.miniCssF = (chunkId) => {\n\t// return url for filenames based on template\n\treturn undefined;\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","__webpack_require__.nmd = (module) => {\n\tmodule.paths = [];\n\tif (!module.children) module.children = [];\n\treturn module;\n};","var scriptUrl;\nif (__webpack_require__.g.importScripts) scriptUrl = __webpack_require__.g.location + \"\";\nvar document = __webpack_require__.g.document;\nif (!scriptUrl && document) {\n\tif (document.currentScript)\n\t\tscriptUrl = document.currentScript.src\n\tif (!scriptUrl) {\n\t\tvar scripts = document.getElementsByTagName(\"script\");\n\t\tif(scripts.length) scriptUrl = scripts[scripts.length - 1].src\n\t}\n}\n// When supporting browsers where an automatic publicPath is not supported you must specify an output.publicPath manually via configuration\n// or pass an empty string (\"\") and set the __webpack_public_path__ variable from your code to use your own logic.\nif (!scriptUrl) throw new Error(\"Automatic publicPath is not supported in this browser\");\nscriptUrl = scriptUrl.replace(/#.*$/, \"\").replace(/\\?.*$/, \"\").replace(/\\/[^\\/]+$/, \"/\");\n__webpack_require__.p = scriptUrl;","// no baseURI\n\n// object to store loaded chunks\n// \"1\" means \"already loaded\"\nvar installedChunks = {\n\t514: 1\n};\n\n// importScripts chunk loading\nvar installChunk = (data) => {\n\tvar [chunkIds, moreModules, runtime] = data;\n\tfor(var moduleId in moreModules) {\n\t\tif(__webpack_require__.o(moreModules, moduleId)) {\n\t\t\t__webpack_require__.m[moduleId] = moreModules[moduleId];\n\t\t}\n\t}\n\tif(runtime) runtime(__webpack_require__);\n\twhile(chunkIds.length)\n\t\tinstalledChunks[chunkIds.pop()] = 1;\n\tparentChunkLoadingFunction(data);\n};\n__webpack_require__.f.i = (chunkId, promises) => {\n\t// \"1\" is the signal for \"already loaded\"\n\tif(!installedChunks[chunkId]) {\n\t\tif(true) { // all chunks have JS\n\t\t\timportScripts(__webpack_require__.p + __webpack_require__.u(chunkId));\n\t\t}\n\t}\n};\n\nvar chunkLoadingGlobal = self[\"webpackChunktelegram_t\"] = self[\"webpackChunktelegram_t\"] || [];\nvar parentChunkLoadingFunction = chunkLoadingGlobal.push.bind(chunkLoadingGlobal);\nchunkLoadingGlobal.push = installChunk;\n\n// no HMR\n\n// no HMR manifest","// run startup\nvar __webpack_exports__ = __webpack_require__.x();\n"],"names":["deferred","next","API_UPDATE_THROTTLE","window","innerHeight","Math","round","API_THROTTLE_RESET_UPDATES","Set","SUPPORTED_IMAGE_CONTENT_TYPES","SUPPORTED_VIDEO_CONTENT_TYPES","SERVICE_NOTIFICATIONS_USER_ID","onTickEndCallbacks","onTickEndPrimaryCallbacks","buildCollectionByKey","collection","key","reduce","byKey","member","pick","object","keys","result","bytesToDataUri","bytes","shouldOmitPrefix","mimeType","btoa","String","fromCharCode","omitVirtualClassFields","instance","flags","CONSTRUCTOR_ID","SUBCLASS_OF_ID","className","classType","getBytes","rest","pathBytesToSvg","width","height","replace","path","len","length","i","num","buildPath","DEFAULT_THUMB_SIZE","w","h","buildApiThumbnailFromStripped","sizes","thumb","find","s","GramJs","realSizes","filter","dataUri","strippedPhotoToJpg","undefined","buildApiPhoto","photo","map","buildApiPhotoSize","id","thumbnail","photoSize","type","localMessages","chats","users","messages","documents","stickerSets","photos","webDocuments","ANIMATED_STICKER_MIME_TYPE","buildStickerFromDocument","document","stickerAttribute","attributes","attr","fileAttribute","sizeAttribute","stickerSetInfo","stickerset","emoji","alt","isAnimated","cachedThumb","thumbs","pathThumb","buildApiThumbnailFromCached","buildApiThumbnailFromPath","stickerSetId","stickerSetAccessHash","accessHash","buildStickerSet","set","archived","animated","installedDate","title","count","shortName","hasThumbnail","Boolean","buildStickerSetCovered","coveredStickerSet","stickerSet","stickerSetCovers","covers","cover","forEach","coverSticker","push","localDb","interpolateArray","data","fitCount","peak","newData","Array","springFactor","leftFiller","rightFiller","idx","floor","val","ApiMessageEntityTypes","ApiMediaFormat","getEntityTypeById","chatOrUserId","getEntityTypeByDeprecatedId","startsWith","buildPeer","userId","buildMtpPeerId","channelId","chatId","buildInputPeer","BigInt","buildInputPeerFromLocalDb","buildInputEntity","buildInputStickerSet","buildInputDocument","media","buildInputMediaDocument","inputDocument","generateRandomBigInt","readBigIntFromBuffer","generateRandomBytes","buildMessageFromUpdate","update","peerId","fromId","buildMtpMessageEntity","entity","offset","url","user","Bold","Italic","Underline","Strike","Code","Pre","language","Blockquote","TextUrl","Url","Hashtag","MentionName","isMessageWithMedia","message","webpage","buildInputContact","phone","firstName","lastName","clientId","buildChatBannedRights","bannedRights","untilDate","buildChatAdminRights","adminRights","buildShippingInfo","info","shippingAddress","buildInputPrivacyKey","privacyKey","buildInputReportReason","reason","abs","slice","isPeerUser","peer","hasOwnProperty","isPeerChat","buildApiPeerId","getApiChatIdFromMtpPeer","resolveMessageApiChatId","mtpMessage","addMessageToLocalDb","messageFullId","action","addPhotoToLocalDb","addChatToLocalDb","chat","LOCAL_MEDIA_UPLOADING_TEMP_ID","currentUserId","localMessageCounter","buildApiMessage","buildApiMessageWithChatId","isChatWithSelf","isOutgoing","out","post","fwdFrom","content","buildMessageMediaContent","sticker","poll","contact","text","buildMessageTextContent","entities","senderId","targetPeerId","isChannelPost","amount","currency","translationValues","targetUserIds","targetChatId","includes","withDuration","duration","video","join","mins","max","Number","totalAmount","domain","buildAction","replyToMsgId","replyToTopId","replyToPeerId","replyTo","isEdited","editDate","editHide","inlineButtons","keyboardButtons","keyboardPlaceholder","isKeyboardSingleUse","messageId","replyMarkup","value","markup","rows","buttons","button","receiptMsgId","placeholder","singleUse","buildReplyButtons","forwardInfo","savedFromPeerId","savedFromPeer","channelPost","channelPostId","isLinkedChannelPost","fromChatId","fromMessageId","savedFromMsgId","senderUserId","hiddenUserName","fromName","adminTitle","postAuthor","buildApiMessageForwardInfo","replies","mediaUnread","isMediaUnread","groupedId","isInAlbum","audio","shouldHideKeyboardButtons","date","views","isFromScheduled","fromScheduled","replyToMessageId","replyToChatId","replyToTopMessageId","mentioned","hasUnreadMention","isMentioned","viaBotId","comments","threadInfo","buildThreadInfo","buildApiMessageEntity","buildMessageDraft","draft","formattedText","replyingToId","ttlSeconds","buildSticker","buildPhoto","buildVideoFromDocument","buildVideo","audioAttribute","voice","thumbnailSizes","fileName","getFilenameFromDocument","buildAudio","waveform","from","buildVoice","buildApiDocument","buildDocumentFromMedia","phoneNumber","buildContact","buildPoll","results","buildPollFromMedia","webPage","buildWebPage","invoice","description","test","photoUrl","isTest","buildInvoice","buildInvoiceFromMedia","size","self","isMovSupported","videoAttr","a","gifAttr","supportsStreaming","roundMessage","isRound","isGif","mediaType","mediaSize","has","imageAttribute","timestamp","pollResults","answers","rawAnswers","answer","option","summary","isPublic","publicVoters","buildPollResults","rawResults","totalVoters","recentVoters","solution","solutionEntities","chosen","correct","voters","isChosen","isCorrect","votersCount","recentVoterIds","defaultBase","filenameAttribute","extension","split","buildNewPoll","localId","messageReplies","maxId","readMaxId","recentRepliers","apiChannelId","threadId","originChannelId","messagesCount","lastMessageId","lastReadInboxMessageId","recentReplierIds","getServerTime","serverTimeOffset","Date","now","buildApiChatFieldsFromPeerEntity","peerEntity","isSupport","isMin","min","avatarHash","buildAvatarHash","isSignaturesShown","signatures","hasPrivateLink","hasLink","username","isVerified","verified","isCallActive","callActive","isCallNotEmpty","callNotEmpty","participantsCount","membersCount","joinDate","buildApiChatPermissions","isCreator","creator","buildApiChatRestrictions","buildApiChatMigrationInfo","buildApiChatFromDialog","dialog","folderId","unreadMark","unreadCount","unreadMentionsCount","notifySettings","silent","muteUntil","readOutboxMaxId","readInboxMaxId","isMuted","getApiChatTypeFromPeerEntity","getApiChatTitleFromMtpPeer","lastReadOutboxMessageId","hasUnreadMark","draftDate","currentUserBannedRights","defaultBannedRights","isRestricted","restrictions","restrictionReason","restricted","restrictionReasons","targetReason","platform","buildApiChatRestrictionReason","Object","assign","isNotJoined","left","kicked","migratedTo","buildApiChatFromPreview","preview","withForbidden","getUserName","megagroup","getPeerKey","photoId","buildChatMember","inviterId","joinedDate","kickedByUserId","kickedBy","promotedByUserId","promotedBy","customTitle","rank","isAdmin","isOwner","buildChatMembers","participants","buildChatTypingStatus","buildApiChatFolder","channels","broadcasts","pinnedChatIds","pinnedPeers","includedChatIds","includePeers","excludedChatIds","excludePeers","buildApiChatFolderFromSuggested","buildApiChatBotCommands","botInfos","botCommands","botInfo","botId","concat","commands","mtpCommand","buildApiUserFromFull","mtpUserFull","about","commonChatsCount","pinnedMsgId","blocked","buildApiUser","fullInfo","bio","pinnedMessageId","isBlocked","botDescription","buildApiBotCommands","mtpUser","userType","bot","deleted","isSelf","mutualContact","isContact","canBeInvitedToGroup","botNochats","status","buildApiUserStatus","botInlinePlaceholder","botPlaceholder","mtpStatus","expires","wasOnline","command","buildApiWallpaper","wallpaper","slug","buildApiSession","session","isCurrent","current","isOfficialApp","officialApp","isPasswordPending","passwordPending","hash","buildPrivacyRules","rules","visibility","allowUserIds","allowChatIds","blockUserIds","blockChatIds","rule","buildApiNotifyException","showPreviews","sound","isSilent","shouldShowPreviews","buildApiCountry","country","code","hidden","iso2","defaultName","name","countryCode","prefixes","patterns","isHidden","onUpdate","sentMessageIds","updater","originRequest","connection","timeOffset","connectionState","state","shouldForceReply","buildApiMessageFromShort","selective","_entities","e","dcId","buildChatPhotoForLocalDb","localDbChatId","newProfilePhoto","some","ids","existingIds","missingIds","profilePhotoIds","setTimeout","notification","currentDate","inboxDate","buildApiMessageFromNotification","randomId","localMessage","Error","newContent","add","isAlreadySent","isScheduled","sendingState","messageUpdate","pollId","apiPoll","pollUpdate","options","stillUnreadCount","isPinned","pinned","order","dp","folderPeers","folderPeer","folder","orderedIds","replacedMembers","addedMember","deletedMemberId","messageIds","typingStatus","channel","unread","apiUserId","updatedUser","peerType","buildPrivacyKey","ApiErrors","PHONE_NUMBER_INVALID","PHONE_CODE_INVALID","PASSWORD_HASH_INVALID","PHONE_PASSWORD_FLOOD","PHONE_NUMBER_BANNED","authController","onRequestPhoneNumber","buildAuthStateUpdate","Promise","resolve","reject","onRequestCode","isCodeViaApp","onRequestPassword","hint","onRequestRegistration","onRequestQrCode","qrCode","token","onAuthError","err","errors","hours","ceil","seconds","authorizationState","provideAuthPhoneNumber","provideAuthCode","provideAuthPassword","password","provideAuthRegistration","registration","restartAuth","restartAuthWithQr","cacheApi","caches","Type","async","fetch","cacheName","isHtmlAllowed","request","Request","cache","open","response","match","contentType","headers","get","Text","Blob","blob","shouldRecreate","resolvedType","Json","json","console","warn","save","cacheData","JSON","stringify","Response","put","clear","delete","MEDIA_ENTITY_TYPES","getMimeType","fallbackMimeType","subarray","byte","toString","GramJsLogger","gramJsUpdateEventBuilder","build","client","isConnected","destroy","invokeRequest","disconnect","onSessionUpdate","sessionData","handleGramJsUpdate","handleTerminatedSession","shouldHandleUpdates","shouldThrow","invoke","updatesContainer","updates","injectUpdateEntities","isSlowMode","error","hasErrorKey","dispatchErrorUpdate","downloadMedia","args","onProgress","mediaFormat","start","end","fullSize","mediaMatch","arrayBuffer","entityType","entityId","sizeType","Stream","acceptsBuffer","progressCallback","workers","getMessageMediaMimeType","downloadStickerSetThumb","Lottie","downloadProfilePhoto","download","parsed","BlobUrl","inflate","to","parse","Progressive","buffer","parseMedia","canCache","prepared","mediaData","URL","createObjectURL","downloadMediaWithClient","uploadFile","file","updateTwoFaSettings","params","fetchCurrentUser","userFull","currentUser","_currentUserId","onCurrentUserUpdate","MAX_INT_32","fetchChats","limit","offsetDate","withPinned","lastLocalServiceMessage","offsetPeer","excludePinned","resultPinned","updateLocalDb","lastMessagesByChatId","peersByKey","preparePeers","draftsById","replyingToById","dialogs","orderedPinnedIds","lastMessage","isListed","chatIds","totalChatCount","fetchFullChat","fullChat","onlineCount","exportedInvite","slowmodeSeconds","slowmodeNextSendDate","migratedFromChatId","migratedFromMaxId","canViewParticipants","linkedChatId","hiddenPrehistory","call","inviteLink","link","members","fetchMembers","kickedMembers","bannedUsers","adminMembers","adminUsers","mtpLinkedChat","slowMode","nextSendDate","migratedFrom","maxMessageId","canViewMembers","isPreHistoryHidden","groupCallId","getFullChannelInfo","getFullChatInfo","searchChats","query","q","localPeerIds","myResults","allChats","allUsers","localChats","r","localUsers","u","globalChats","globalUsers","fetchChat","requestChatUpdate","lastLocalMessage","noLastMessage","peers","lastRemoteMessage","saveDraft","clearDraft","updateChatMutedState","settings","createChannel","broadcast","newChannel","joinChannel","deleteChatUser","deleteChat","leaveChannel","deleteChannel","createGroupChat","newChat","editChatPhoto","uploadedPhoto","inputEntity","toggleChatPinned","shouldBePinned","toggleChatArchived","fetchChatFolders","byId","fetchRecommendedChatFolders","editChatFolder","folderUpdate","emoticon","contacts","nonContacts","groups","bots","excludeArchived","excludeMuted","excludeRead","buildFilterFromApiFolder","deleteChatFolder","isActionSuccessful","recommendedChatFolders","folders","toggleDialogUnread","getChatByUsername","togglePreHistoryHidden","isEnabled","enabled","updateChatDefaultBannedRights","updateChatMemberBannedRights","participant","updateChatAdmin","updateChatTitle","updateChatAbout","toggleSignatures","memberFilter","fetchGroupsForDiscussion","setDiscussionGroup","group","migrateChat","openChatByInvite","isChannel","addChatMembers","all","deleteChatMember","viewMessages","sendMessages","sendMedia","sendStickers","sendGifs","sendGames","sendInline","embedLinks","sendPolls","changeInfo","inviteUsers","pinMessages","store","importChatInvite","File","constructor","fileBits","super","this","fetchMessages","pagination","RequestClass","msgId","c","threadInfos","fetchMessage","queue","sendMessage","replyingTo","attachment","gif","scheduledAt","noWebPage","filename","blobUrl","previewBlobUrl","quick","inputWaveform","buildUploadingMedia","buildLocalMessage","groupIndex","groupedUploads","counter","singleMediaByIndex","prevQueue","uploadMedia","inputMedia","uploadedMedia","messageMedia","fileReference","fetchInputMedia","multiMedia","values","scheduleDate","sendGroupedMedia","pollParams","quiz","question","Buffer","multipleChoice","correctAnswers","buildInputPoll","noWebpage","editMessage","mtpEntities","rescheduleMessage","lastModified","blobToFile","fetchBlob","fetchFile","patchedOnProgress","progress","isCanceled","inputFile","pinMessage","isUnpin","isOneSide","unpin","pmOneside","unpinAllMessages","deleteMessages","shouldDeleteForAll","revoke","deleteScheduledMessages","deleteHistory","just_clear","reportMessages","markMessageListRead","requestThreadInfoUpdate","markMessagesRead","topMessageResult","repliesResult","offsetId","addOffset","discussionChatId","topMessageId","firstMessageId","noTopChatsRequest","searchMessagesLocal","chatOrUser","minDate","maxDate","topMsgId","nextOffsetId","totalCount","searchMessagesGlobal","offsetRate","nextRate","fetchWebPagePreview","sendPollVote","loadPollOptionResults","shouldResetVoters","votes","vote","nextOffset","forwardMessages","fromChat","toChat","randomIds","index","isAudio","asIncomingInChatWithSelf","buildLocalForwardedMessage","fromPeer","toPeer","sil2ent","findFirstMessageIdAfterDate","fetchScheduledHistory","sendScheduledMessages","isServiceMessageWithMedia","fetchPinnedMessages","inputGifBot","fetchFullUser","input","userWithFullInfo","fetchCommonChats","commonChats","mtpChat","isFullyLoaded","fetchNearestCountry","dcInfo","fetchTopUsers","topPeers","correspondents","fetchContactList","fetchUsers","updateContact","addContact","deleteUser","fetchProfilePhotos","fetchStickerSets","allStickers","sets","fetchRecentStickers","stickers","processStickerResult","fetchFavoriteStickers","fetchFeaturedStickers","faveSticker","unfave","fetchStickers","stickerSetShortName","packs","acc","documentId","fetchAnimatedEmojis","searchStickers","fetchSavedGifs","gifs","processGifResult","installStickerSet","uninstallStickerSet","searchGifs","config","resolvedPeer","gifSearchUsername","foundGif","fetchStickersForEmoji","fetchEmojiKeywords","fromVersion","langCode","version","keywords","emojiKeyword","keyword","emoticons","checkChatUsername","setChatUsername","updatePrivateLink","EMAIL_UNCONFIRMED","EMAIL_HASH_EXPIRED","NEW_SALT_INVALID","NEW_SETTINGS_INVALID","CODE_INVALID","emailCodeController","getPasswordInfo","hasPassword","onRequestEmailCode","checkPassword","currentPassword","isCheckPassword","onError","clearPassword","updatePassword","email","newPassword","emailCodeCallback","onEmailCodeError","updateRecoveryEmail","provideRecoveryEmailCode","BETA_LANG_CODES","updateProfile","checkUsername","updateUsername","updateProfilePhoto","uploadProfilePhoto","fetchWallpapers","filteredWallpapers","wallpapers","pattern","uploadWallpaper","fetchBlockedContacts","blockedIds","blockContact","unblockContact","fetchAuthorizations","authorizations","terminateAuthorization","terminateAllAuthorizations","fetchNotificationExceptions","compareSound","fetchNotificationSettings","isMutedContactSignUpNotification","privateContactNotificationsSettings","groupNotificationsSettings","broadcastNotificationsSettings","privateSilent","privateMuteUntil","privateShowPreviews","groupSilent","groupMuteUntil","groupShowPreviews","broadcastSilent","broadcastMuteUntil","broadcastShowPreviews","hasContactJoinedNotifications","hasPrivateChatsNotifications","hasPrivateChatsMessagePreview","hasGroupNotifications","hasGroupMessagePreview","hasBroadcastNotifications","hasBroadcastMessagePreview","updateContactSignUpNotification","updateNotificationSettings","fetchLanguages","langPack","fetchLangPack","sourceLangPacks","collections","strings","reverse","fetchLangStrings","fetchPrivacySettings","registerDevice","secret","getAuthKey","getKey","tokenType","appSandbox","otherUids","unregisterDevice","setPrivacySettings","privacyRules","allowedUsers","allowedChats","blockedUsers","blockedChats","updateIsOnline","isOnline","offline","fetchContentSettings","isSensitiveEnabled","sensitiveEnabled","canChangeSensitive","sensitiveCanChange","updateContentSettings","fetchCountryList","countryList","countries","phoneCodes","array","countryCodes","isArray","sort","b","localeCompare","general","buildApiWebDocument","answerCallbackButton","fetchTopInlineBots","botsInline","fetchInlineBot","addUserToLocalDb","fetchInlineBotResults","queryId","switchPm","isGallery","gallery","help","buildApiBotInlineMediaResult","webDocument","webThumbnail","buildApiBotInlineResult","sendInlineBotResult","resultId","startBot","startParam","buildShippingOptions","shippingOptions","prices","ac","cur","label","validateRequestedInfo","requestInfo","shouldSave","sendPaymentForm","formId","requestedInfoId","shippingOptionId","credentials","getPaymentForm","form","canSaveCredentials","passwordMissing","providerId","nativeProvider","nativeParams","savedInfo","nameRequested","phoneRequested","emailRequested","shippingAddressRequested","flexible","phoneToProvider","emailToProvider","mapedPrices","nativeData","needCardholderName","need_cardholder_name","needCountry","need_country","needZip","need_zip","publishableKey","publishable_key","buildPaymentForm","getReceipt","receipt","shipping","credentialsTitle","shippingPrices","shippingMethod","buildReceipt","initApi","_onUpdate","initialArgs","initUpdater","handleUpdate","initAuth","initChats","initMessages","initUsers","initStickers","initManagement","initTwoFaSettings","userAgent","sessions","TelegramClient","process","deviceModel","navigator","systemVersion","appVersion","useWSS","additionalDcsDisabled","testServers","addEventHandler","phoneCode","firstAndLastNames","initialMethod","getSessionData","initClient","flushUpdatesOnTickEnd","schedulerFn","fn","waiting","_args","throttleWith","callback","isPrimary","then","currentCallbacks","currentPrimaryCallbacks","cb","throttleId","pendingUpdates","currentThrottleId","currentUpdates","flushUpdatesThrottled","ms","shouldRunFirst","interval","isPending","setInterval","clearInterval","throttle","random","onerror","sendToOrigin","addEventListener","callbackState","Map","postMessage","onmessage","callbackArgs","lastArg","ArrayBuffer","fnName","methods","callApi","require","crypto","little","signed","randBuffer","bytesNumber","bigInt","subtract","pow","toSignedLittleBuffer","big","number","bigNumber","byteArray","shiftRight","and","readBufferFromBigInt","bitLength","lesser","below","hex","padStart","l","reminder","randomBytes","sha1","shaSum","createHash","digest","crcTable","module","exports","generateRandomLong","mod","n","m","crc32","buf","k","makeCRCTable","isBuffer","crc","generateKeyDataFromNonce","serverNonce","newNonce","hash1","hash2","hash3","iv","sha256","bigIntMod","remainder","modExp","one","x","greater","zero","leastSignificantBit","divide","eq","multiply","getRandomInt","sleep","getByteArray","integer","bits","byteLength","convertToLittle","alloc","writeUInt32BE","bufferXor","res","createDeferred","promise","_resolve","constructors","checkPrimeAndGood","primeBytes","g","equals","numBytesForHash","bigNumForHash","isGoodModExpFirst","modexp","prime","diff","xor","computeHash","algo","salt1","salt2","salt","iterations","pbkdf2","pbkdf2sha512","computeCheck","currentAlgo","PasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow","pwHash","p","B","srp_B","isGoodLarge","pForHash","gForHash","bForHash","gX","kgX","aForHash","A","generateAndCheckRandom","gB","ux","aUx","S","K","pSha","gSha","salt1Sha","salt2Sha","M1","InputCheckPasswordSRP","srpId","computeDigest","JPEG_HEADER","JPEG_FOOTER","_raiseCastFail","target","getMessageId","getInputPeer","allowSelf","checkHash","User","InputPeerSelf","InputPeerUser","Chat","ChatEmpty","ChatForbidden","InputPeerChat","Channel","TypeError","InputPeerChannel","ChannelForbidden","InputUser","InputChannel","UserEmpty","InputPeerEmpty","UserFull","ChatFull","PeerChat","getDisplayName","getAppropriatedPartSize","fileSize","stripped","header","getDC","downloadDC","ipAddress","port","pwd","Api","newAlgo","newSettings","newPasswordHash","newSecureSettings","codeLength","os","Logger","MemorySession","Helpers","utils","Session","LAYER","requests","MTProtoSender","ConnectionTCPObfuscated","authFlow","checkAuthorization","downloadFile","WEBDOCUMENT_REQUEST_PART_SIZE","sizeTypes","apiId","apiHash","opts","DEFAULT_OPTIONS","_useIPV6","useIPV6","baseLogger","_log","floodSleepLimit","_eventBuilders","_phoneCodeHash","parseInt","_requestRetries","requestRetries","_connectionRetries","connectionRetries","_retryDelay","retryDelay","proxy","_proxy","_timeout","timeout","_autoReconnect","autoReconnect","_connection","_floodWaitedRequests","_initWith","InvokeWithLayer","layer","InitConnection","release","systemLangCode","_config","phoneCodeHashes","_exportedSenderPromises","_exportedSenderReleaseTimeouts","_additionalDcsDisabled","_loopStarted","_reconnecting","_destroyed","_initSession","_sender","logger","retries","delay","connectTimeout","authKeyCallback","_authKeyCallback","bind","updateCallback","_handleUpdate","isMainSender","userDisconnected","_user_connected","_disconnected","serverAddress","connect","setAuthKey","authKey","send","GetConfig","_updateLoop","load","setDC","attempts","PingDelayDisconnect","pingId","MIN_SAFE_INTEGER","MAX_SAFE_INTEGER","disconnectDelay","race","getTime","_lastRequest","GetState","sender","newDc","DC","setKey","dc","_authenticated","auth","ExportAuthorization","req","ImportAuthorization","shouldReconnect","existingSender","_connectSender","_createExportedSender","isConnecting","_borrowExportedSender","clearTimeout","onConnectionBreak","_cleanupExportedSender","getSender","inputLocation","messageOrMedia","Message","MessageMediaWebPage","WebPage","MessageMediaPhoto","Photo","_downloadPhoto","MessageMediaDocument","Document","_downloadDocument","MessageMediaContact","_downloadContact","WebDocument","WebDocumentNoProxy","_downloadWebDocument","isBig","loc","chatPhoto","UserProfilePhoto","ChatPhoto","InputPeerPhotoFileLocation","thumbVersion","InputStickerSetThumb","InputStickerSetID","thumbDcId","_pickFileSize","indexOf","_downloadCachedPhotoSize","PhotoStrippedSize","PhotoSizeEmpty","PhotoCachedSize","InputPhotoFileLocation","thumbSize","doc","InputDocumentFileLocation","buff","downloaded","upload","GetWebFile","location","InputWebFileLocation","attempt","sendWithInvokeSupport","ServerError","FloodWaitError","FloodTestPhoneWaitError","PhoneMigrateError","NetworkMigrateError","UserMigrateError","_switchDC","MsgWaitError","isReady","GetUsers","InputUserSelf","authParams","apiCredentials","fileParams","event","Updates","UpdatesCombined","_processUpdate","UpdateShort","others","_dispatchUpdate","ptsDate","builder","times","pause","Infinity","sequentialUpdates","DEFAULT_INITIAL_METHOD","me","botAuthToken","signInBot","signInUser","signInUserWithQrCode","phoneCodeHash","sendCodeResult","sendCode","forceSMS","termsOfService","isRegistrationRequired","signInWithPassword","isScanningComplete","inputPromise","exceptIds","updatePromise","result2","authorization","migratedResult","sendResult","resendResult","passwordSrpResult","passwordSrpCheck","computePasswordSrpCheck","ONE_MB","Foreman","maxWorkers","requestWorker","activeWorkers","releaseWorker","partSizeKb","partSize","partsCount","foreman","promises","hasEnded","isPrecise","offsetMemo","precise","buffers","totalLength","fileId","isLarge","partCount","fileToBuffer","sendingParts","j","jMemo","bytesMemo","filePart","fileTotalParts","parts","md5Checksum","BinaryReader","AuthKey","_key","_hash","reader","auxHash","readLong","read","keyId","writeUInt8","shaData","other","cipher","createCipheriv","encrypt","Factorizator","neq","temp","pq","y","randBetween","minus","ys","condition","gcd","IGE","AESIGE","ige","decryptIge","cipherText","decrypt","encryptIge","plainText","padding","i2abLow","uint8","Uint8Array","int","i2abBig","ab2iLow","ab","Uint32Array","ab2iBig","isBigEndian","i2ab","ab2i","AES","getWords","Counter","initialValue","setBytes","_counter","increment","CTR","_remainingCounter","_remainingCounterIndex","_aes","encrypted","Hash","algorithm","subtle","createDecipheriv","getRandomValues","passwordKey","importKey","deriveBits","s2i","str","pos","charCodeAt","right","ReadCancelledError","TypeNotFoundError","invalidConstructorId","remaining","alert","InvalidChecksumError","checksum","validChecksum","InvalidBufferError","payload","readInt32LE","SecurityError","BadMessageError","errorMessage","ErrorMessages","CdnFileTamperedError","RPCError","_fmtRequest","InvalidDCError","BadRequestError","UnauthorizedError","ForbiddenError","NotFoundError","AuthKeyError","FloodError","TimedOutError","capture","SlowModeWaitError","FileMigrateError","EmailUnconfirmedError","rpcErrorRe","Common","RPCBaseErrors","RPCErrorList","RPCMessageToError","rpcError","msgRegex","Cls","EventBuilder","types","func","blacklistChats","resolved","NewMessage","Raw","StopPropagation","_queue","canGet","resolveGet","canPush","resolvePush","returned","pop","coreObjects","tlobjects","stream","_last","readByte","readInt","readUInt32LE","readLargeInt","readFloat","readFloatLE","readDouble","readDoubleLE","getBuffer","tgReadBytes","firstByte","tgReadString","tgReadBool","tgReadDate","tgReadObject","constructorId","clazz","seek","tellPosition","setPosition","fromReader","tgReadVector","close","position","_stream","write","getValue","_level","level","isBrowser","browser","__nwjs","colors","debug","messageFormat","canSend","levels","stack","format","toISOString","toUpperCase","color","log","MessageContainer","TLMessage","BinaryWriter","USE_INVOKE_AFTER_WITH","_state","_pendingStates","_ready","setReady","append","after","catch","finally","extend","states","batch","MAXIMUM_LENGTH","shift","SIZE_OVERHEAD","MAXIMUM_SIZE","afterId","writeDataAsMessage","unshift","writeUInt32LE","writeInt32LE","containerId","rejectAll","requestState","Mutex","mutex","WebSocketClient","closeError","disconnectedCallback","closed","readData","thisTime","canRead","toReturn","resolveRead","getWebSocketLink","ip","website","onopen","receive","onclose","wasClean","runExclusive","PromisedWebSockets","MessagePacker","AsyncQueue","tl","events","extensions","helpers","PUBLIC_KEYS","fingerprint","_serverKeys","keyInfo","doAuthentication","nonce","resPQ","factorize","pBuffer","qBuffer","pqInnerData","targetFingerprint","targetKey","serverPublicKeyFingerprints","dataWithPadding","dataPadReversed","encryptedData","tempKey","shaDigestKeyWithData","dataWithHash","aesEncrypted","tempKeyXor","keyAesEncrypted","keyAesEncryptedInt","greaterOrEquals","encryptedDataBuffer","serverDhParams","publicKeyFingerprint","sh","nnh","newNonceHash","encryptedAnswer","plainTextAnswer","serverDhInner","dhPrime","ga","gA","serverTime","gb","gab","clientDhInner","retryId","clientDdhInnerHashed","clientDhEncrypted","dhGen","nonceTypes","nonceNumber","calcNewNonceHash","MTProtoState","loggers","body","_getNewMsgId","recv","MtProtoPlainSender","RPCResult","GZIPPacked","RequestState","MsgsAck","MsgsStateInfo","Pong","UpdateConnectionState","UpdateServerTimeOffset","BadServerSalt","BadMsgNotification","MsgDetailedInfo","MsgNewDetailedInfo","NewSessionCreated","FutureSalts","MsgsStateReq","MsgResendReq","MsgsAllInfo","LogOut","_dcId","_retries","_delay","_connectTimeout","_updateCallback","_autoReconnectCallback","autoReconnectCallback","_isMainSender","_onConnectionBreak","_send_loop_handle","_recv_loop_handle","_send_queue","_pending_state","_pending_ack","_last_acks","_handlers","_handleRPCResult","_handleContainer","_handleGzipPacked","_handlePong","_handleBadServerSalt","_handleBadNotification","_handleDetailedInfo","_handleNewDetailedInfo","_handleNewSessionCreated","_handleAck","_handleFutureSalts","_handleStateForgotten","_handleMsgAll","force","_connect","connected","disconnected","_disconnect","plain","_sendLoop","_recvLoop","ack","msgIds","encryptMessageData","reconnect","decryptMessageData","broken","_processMessage","obj","handler","_popStates","toPop","reqMsgId","readResult","innerMessage","pong","newTimeOffset","updateTimeOffset","badSalt","badMsgId","newServerSalt","badMsg","errorCode","_sequence","answerMsgId","serverSalt","repeat","_reconnect","reset","newConnection","_ip","_port","_testServers","InvokeAfterMsg","_lastMsgId","updateMessageId","msgKey","sha256a","sha256b","contentRelated","seqNo","_getSeqNo","gzipIfSmaller","waitForKey","_calcKey","ourKey","remoteMsgId","remoteSequence","containerLen","nanoseconds","newMsgId","shiftLeft","or","correctMsgId","bad","old","pending","Connection","_connected","_sendTask","_recvTask","_codec","_obfuscation","_sendArray","_recvArray","socket","disconnectCallback","PacketCodecClass","_initConn","fromCallback","_send","_recv","tag","encodedPacket","encodePacket","readPacket","PacketCodec","_conn","ObfuscatedConnection","ObfuscatedIO","AbridgedPacketCodec","props","obfuscateTag","ConnectionTCPAbridged","initHeader","_encrypt","encryptor","_decrypt","decryptor","packetCodec","ok","toJSON","randomReversed","encryptKey","encryptIv","decryptKey","decryptIv","readExactly","ConnectionTCPFull","MTProtoPlainSender","StorageSession","CACHE_NAME","_storageKey","cached","_sessionData","_callback","_authKeys","mainDcId","hashes","skipOnUpdate","_serverAddress","idb","_delete","del","_fetchFromCache","_saveToCache","localStorage","removeItem","getItem","setItem","_takeoutId","_updateStates","_authKey","sessionInfo","_sessionString","_loadFromSessionString","skipUpdateStorage","_updateStorage","asHex","mainDcIdStr","mainDcKey","StringSession","decode","readUInt8","serverAddressLen","readInt16BE","dcBuffer","addressBuffer","addressLengthBuffer","writeInt16BE","portBuffer","encode","Memory","CacheApiSession","LocalStorageSession","IdbSession","CallbackSession","api","sub","parseTl","serializeBytes","serializeDate","tlContent","schemeContent","CACHING_SUPPORTED","CACHE_KEY","extractParams","fileContent","f","functions","d","isFunction","argToBytes","writeDoubleLE","getArgFromReader","arg","isVector","useVectorId","flagIndicator","skipConstructorId","createClasses","classesType","classes","classParams","subclassOfId","argsConfig","namespace","fullName","VirtualClass","argName","isFlag","flagIndex","idForBytes","flagCalculate","boxed","charAt","definitions","fromCache","jsonCache","loadFromCache","constructorParamsApi","functionParamsApi","constructorParamsSchema","functionParamsSchema","loadFromTlSchemas","obj1","obj2","mergeWithNamespaces","buildApiFromTlSchema","gzipped","toBytes","gzip","ungzip","containerLength","before","tlMessage","RpcError","innerCode","snakeToCamelCase","_","variableSnakeToCamelCase","CORE_TYPES","AUTH_KEY_TYPES","findAll","regex","matches","RegExp","source","exec","fromLine","line","argsMatch","currentConfig","hexId","representation","brace","argType","buildArgConfig","flagMatch","vectorMatch","ignoreIds","o","objAll","objByName","objByType","commentIndex","trim","followingTypes","dt","fill","t","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","loaded","__webpack_modules__","__webpack_exports__","O","chunkIds","priority","notFulfilled","fulfilled","every","splice","getter","__esModule","definition","defineProperty","enumerable","chunkId","miniCssF","globalThis","Function","prop","prototype","Symbol","toStringTag","nmd","paths","children","scriptUrl","importScripts","currentScript","src","scripts","getElementsByTagName","installedChunks","chunkLoadingGlobal","parentChunkLoadingFunction","moreModules","runtime"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/524.57eea32f15dc5514a3eb.js b/dist/524.632897f7413c1c081b04.js similarity index 99% rename from dist/524.57eea32f15dc5514a3eb.js rename to dist/524.632897f7413c1c081b04.js index 48e160f6..2383103d 100644 --- a/dist/524.57eea32f15dc5514a3eb.js +++ b/dist/524.632897f7413c1c081b04.js @@ -1,2 +1,2 @@ (()=>{"use strict";const e="tt-media-progressive",t="tt-assets",s=("undefined"!=typeof window&&window.innerHeight,Math.round(425),new Set(["newMessage","newScheduledMessage","deleteMessages","deleteScheduledMessages","deleteHistory"]),new Set(["image/png","image/gif","image/jpeg"])),n=new Set(["video/mp4"]);new Set([...s,...n]),new Set(["AU","BD","CA","CO","EG","HN","IE","IN","JO","MX","MY","NI","NZ","PH","PK","SA","SV","US"]);const a=e=>new Promise((t=>{setTimeout((()=>t()),e)})),i=524288,o=new Map;async function r(e){const s=await async function(s,n){try{return await Promise.race([a(3e3).then((()=>Promise.reject(new Error("TIMEOUT")))),(async()=>{const s=await self.caches.open(t),n=await s.match(e.request);return{cache:s,cached:n}})()])}catch(e){return void console.error(e)}}(),{cache:n,cached:i}=s||{};if(n&&i){if(i.ok)return i;await n.delete(e.request)}const o=await fetch(e.request);return o.ok&&n&&n.put(e.request,o.clone()),o}var c,d;self.addEventListener("message",(e=>{const{type:t,messageId:s,result:n}=e.data;if("partResponse"===t){const e=o.get(s);e&&e.resolve(n)}})),(d=c||(c={})).True="1",d.False="0";let l=(new Date).valueOf();const u=new Set,f={};function g(e){return e.custom.from_id?e.custom.from_id:e.custom.chat_id||e.custom.channel_id?`-${e.custom.chat_id||e.custom.channel_id}`:void 0}function p(e){if(e.custom.msg_id)return parseInt(e.custom.msg_id,10)}async function w(){const e=new URL(self.registration.scope).origin;return(await self.clients.matchAll({type:"window"})).filter((t=>new URL(t.url).origin===e))}async function m(e){const t=(await w())[0];t&&t.postMessage({type:"playNotificationSound",payload:{id:e}})}function h({chatId:e,messageId:t,body:s,title:n,icon:a}){const i=(new Date).valueOf()-l<1e3,o={body:s,data:{chatId:e,messageId:t,count:1},icon:a||"icon-192x192.png",badge:"icon-192x192.png",tag:String(i?0:e||0),vibrate:[200,100,200]};return Promise.all([m(String(t)||e||""),self.registration.showNotification(n,o)])}async function y(e,t){const{chatId:s,messageId:n}=t;if(s&&(e.postMessage({type:"focusMessage",payload:{chatId:s,messageId:n}}),!e.focused))try{await e.focus()}catch(e){}}self.onsync=()=>{l=(new Date).valueOf()};const I=/[0-9a-f]{20}.*\.(js|css|woff2?|svg|png|jpg|jpeg|json|wasm)$/;self.addEventListener("install",(e=>{e.waitUntil(self.skipWaiting())})),self.addEventListener("activate",(e=>{e.waitUntil(Promise.race([a(3e3),Promise.all([self.caches.delete(t),self.clients.claim()])]))})),self.addEventListener("fetch",(t=>{const{url:s}=t.request;return s.includes("/progressive/")?(t.respondWith(async function(t){const{url:s}=t.request,n=t.request.headers.get("range"),r=/^bytes=(\d+)-(\d+)?$/g.exec(n||""),c=Number(r[1]);let d=Number(r[2]);if((!d||d-c+1>i)&&(d=c+i-1),0===c&&1===d){const e=t.request.url.match(/fileSize=(\d+)&mimeType=([\w/]+)/),s=e&&Number(e[1]),n=null==e?void 0:e[2];if(s&&n)return new Response(new Uint8Array(2).buffer,{status:206,statusText:"Partial Content",headers:[["Content-Range",`bytes 0-1/${s}`],["Accept-Ranges","bytes"],["Content-Length","2"],["Content-Type",n]]})}const l=`${s}?start=${c}&end=${d}`,[u,f]=await async function(t){const s=await self.caches.open(e);return Promise.all([s.match(`${t}&type=arrayBuffer`).then((e=>e?e.arrayBuffer():void 0)),s.match(`${t}&type=headers`).then((e=>e?e.json():void 0))])}(l);if(u)return new Response(u,{status:206,statusText:"Partial Content",headers:f});let g;try{g=await async function(e,t){if(!e.clientId)return;const s=await self.clients.get(e.clientId);if(!s)return;const n=(e=>{let t;do{t=String(Math.random()).replace("0.","id")}while(e.hasOwnProperty(t));return t})(o),i={},r=Promise.race([a(6e4).then((()=>Promise.reject(new Error("ERROR_PART_TIMEOUT")))),new Promise(((e,t)=>{Object.assign(i,{resolve:e,reject:t})}))]);return o.set(n,i),r.catch((()=>{})).finally((()=>{o.delete(n)})),s.postMessage({type:"requestPart",messageId:n,params:t}),r}(t,{url:s,start:c,end:d})}catch(e){}if(!g)return new Response("",{status:500,statusText:"Failed to fetch progressive part"});const{arrayBuffer:p,fullSize:w,mimeType:m}=g,h=Math.min(d-c+1,p.byteLength);d=c+h-1;const y=p.slice(0,h),I=[["Content-Range",`bytes ${c}-${d}/${w}`],["Accept-Ranges","bytes"],["Content-Length",String(h)],["Content-Type",m]];return h<=524288&&d<2097151&&async function(t,s,n){const a=await self.caches.open(e);Promise.all([a.put(new Request(`${t}&type=arrayBuffer`),new Response(s)),a.put(new Request(`${t}&type=headers`),new Response(JSON.stringify(n)))])}(l,y,I),new Response(y,{status:206,statusText:"Partial Content",headers:I})}(t)),!0):!(!s.startsWith("http")||!s.match(I)||(t.respondWith(r(t)),0))})),self.addEventListener("push",(function(e){const t=function(e){try{return e.data.json()}catch(e){return}}(e);if(!t||t.mute===c.True)return;const s=function(e){return{chatId:g(e),messageId:p(e),title:e.title||"Telegram WebZ",body:e.description}}(t);u.has(s.messageId)?u.delete(s.messageId):e.waitUntil(h(s))})),self.addEventListener("notificationclick",(function(e){const t=self.registration.scope;e.notification.close();const{data:s}=e.notification;e.waitUntil((async()=>{const e=await w();if(await Promise.all(e.map((e=>(f[e.id]=s,y(e,s))))),self.clients.openWindow&&!(e.length>0)){f[0]=s;try{const e=await self.clients.openWindow(t);e&&(f[e.id]=s)}catch(e){}}})())})),self.addEventListener("message",(function(e){if(!e.data)return;const t=e.source;if("clientReady"===e.data.type){const s=f[t.id]||f[0];s&&(delete f[t.id],delete f[0],e.waitUntil(y(t,s)))}if("newMessageNotification"===e.data.type){const t=e.data.payload;u.add(t.messageId),e.waitUntil(h(t))}"closeMessageNotifications"===e.data.type&&e.waitUntil(async function({chatId:e,lastReadInboxMessageId:t}){const s=await self.registration.getNotifications(),n=t||Number.MAX_VALUE;s.forEach((t=>{("0"===t.tag||t.data.chatId===e&&t.data.messageId<=n)&&t.close()}))}(e.data.payload))}))})(); -//# sourceMappingURL=524.57eea32f15dc5514a3eb.js.map \ No newline at end of file +//# sourceMappingURL=524.632897f7413c1c081b04.js.map \ No newline at end of file diff --git a/dist/524.57eea32f15dc5514a3eb.js.map b/dist/524.632897f7413c1c081b04.js.map similarity index 99% rename from dist/524.57eea32f15dc5514a3eb.js.map rename to dist/524.632897f7413c1c081b04.js.map index 6ea31c98..9323d2ca 100644 --- a/dist/524.57eea32f15dc5514a3eb.js.map +++ b/dist/524.632897f7413c1c081b04.js.map @@ -1 +1 @@ -{"version":3,"file":"524.57eea32f15dc5514a3eb.js","mappings":"mBAAO,MA6BMA,EAA+B,uBAI/BC,EAAmB,YAkGnBC,GA5FyB,oBAAXC,QAA0BA,OAAOC,YAgEzBC,KAAKC,MAAM,KACJ,IAAIC,IAAI,CAChD,aAAc,sBAAuB,iBAAkB,0BAA2B,kBA0BvC,IAAIA,IAAI,CACnD,YAAa,YAAa,gBAGfC,EAAgC,IAAID,IAAI,CACnD,cAGwC,IAAIA,IAAI,IAC7CL,KACAM,IAUyC,IAAID,IAAI,CAAC,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,OC/BtJ,MAAME,EAASC,GAAe,IAAIC,SAAeC,IACtDC,YAAW,IAAMD,KAAWF,MCjGxBI,EAAoB,OAIpBC,EAAgB,IAAIC,ICpBnBC,eAAeC,EAAiBC,GACrC,MAAMC,QA0BRH,eAA8BI,EAAsBC,GAClD,IACE,aAAaX,QAAQY,KAAK,CACxBd,EAhCgB,KAgCDe,MAAK,IAAMb,QAAQc,OAAO,IAAIC,MAAM,cA7BjBT,WACpC,MAAMU,QAAcC,KAAKC,OAAOC,KAAK7B,GAC/B8B,QAAeJ,EAAMK,MAAMb,EAAEc,SAEnC,MAAO,CAAEN,MAAAA,EAAOI,OAA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EAASnJ,EAAEmJ,OACjB,GAAoB,gBAAhBnJ,EAAE8B,KAAKH,KAAwB,CAEjC,MAAMG,EAAOO,EAAY8G,EAAOzF,KAAOrB,EAAY,GAC/CP,WACKO,EAAY8G,EAAOzF,WACnBrB,EAAY,GACnBrC,EAAE+E,UAAUL,EAAiByE,EAAQrH,KAGzC,GAAoB,2BAAhB9B,EAAE8B,KAAKH,KAAmC,CAE5C,MAAM6G,EAAiCxI,EAAE8B,KAAK8B,QAE9CxB,EAAmBgH,IAAIZ,EAAa5G,WACpC5B,EAAE+E,UAAUlB,EAAiB2E,IAGX,8BAAhBxI,EAAE8B,KAAKH,MACT3B,EAAE+E,UA5HNjF,gBAAkC,OAChCgE,EADgC,uBAEhCuF,IAEA,MAAMC,QAAsB7I,KAAKwC,aAAasG,mBACxCC,EAAgBH,GAA0B5D,OAAOgE,UACvDH,EAAcI,SAASlB,KAEE,MAArBA,EAAalE,KACTkE,EAAa1G,KAAKgC,SAAWA,GAAU0E,EAAa1G,KAAKF,WAAa4H,IAE1EhB,EAAaK,WAiHHc,CAAmB3J,EAAE8B,KAAK8B,c","sources":["webpack://telegram-t/./src/config.ts","webpack://telegram-t/./src/util/schedulers.ts","webpack://telegram-t/./src/serviceWorker/progressive.ts","webpack://telegram-t/./src/serviceWorker/assetCache.ts","webpack://telegram-t/./src/serviceWorker/pushNotification.ts","webpack://telegram-t/./src/serviceWorker.ts","webpack://telegram-t/./src/util/generateIdFor.ts"],"sourcesContent":["export const PAGE_TITLE = 'Telegram';\nexport const INACTIVE_MARKER = ' [Inactive]';\n\nexport const APP_NAME = process.env.APP_NAME || 'Telegram WebZ';\nexport const APP_VERSION = process.env.APP_VERSION || 'dev';\n\nexport const DEBUG = (\n process.env.APP_ENV !== 'production' && process.env.APP_ENV !== 'perf' && process.env.APP_ENV !== 'test'\n);\nexport const DEBUG_MORE = false;\n\nexport const IS_TEST = process.env.APP_ENV === 'test';\nexport const IS_PERF = process.env.APP_ENV === 'perf';\n\nexport const DEBUG_ALERT_MSG = 'Shoot!\\nSomething went wrong, please see the error details in Dev Tools Console.';\nexport const DEBUG_GRAMJS = false;\n\nexport const SESSION_USER_KEY = 'user_auth';\nexport const LEGACY_SESSION_KEY = 'GramJs:sessionId';\n\nexport const GLOBAL_STATE_CACHE_DISABLED = false;\nexport const GLOBAL_STATE_CACHE_KEY = 'tt-global-state';\nexport const GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT = 30;\nexport const GLOBAL_STATE_CACHE_USER_LIST_LIMIT = 5000;\n\nexport const MEDIA_CACHE_DISABLED = false;\nexport const MEDIA_CACHE_NAME = 'tt-media';\nexport const MEDIA_CACHE_NAME_AVATARS = 'tt-media-avatars';\nexport const MEDIA_PROGRESSIVE_CACHE_DISABLED = false;\nexport const MEDIA_PROGRESSIVE_CACHE_NAME = 'tt-media-progressive';\nexport const MEDIA_CACHE_MAX_BYTES = 512 * 1024; // 512 KB\nexport const CUSTOM_BG_CACHE_NAME = 'tt-custom-bg';\nexport const LANG_CACHE_NAME = 'tt-lang-packs-v6';\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_SENSITIVE_AREA = 750;\nexport const MESSAGE_LIST_SLICE = isBigScreen ? 60 : 40;\nexport const MESSAGE_LIST_VIEWPORT_LIMIT = MESSAGE_LIST_SLICE * 2;\n\nexport const CHAT_HEIGHT_PX = 72;\nexport const CHAT_LIST_SLICE = isBigScreen ? 30 : 25;\nexport const CHAT_LIST_LOAD_SLICE = 100;\nexport const SHARED_MEDIA_SLICE = 42;\nexport const MESSAGE_SEARCH_SLICE = 42;\nexport const GLOBAL_SEARCH_SLICE = 20;\nexport const MEMBERS_SLICE = 30;\nexport const MEMBERS_LOAD_SLICE = 200;\nexport const PINNED_MESSAGES_LIMIT = 50;\nexport const BLOCKED_LIST_LIMIT = 100;\nexport const PROFILE_PHOTOS_LIMIT = 40;\nexport const PROFILE_SENSITIVE_AREA = 500;\nexport const COMMON_CHATS_LIMIT = 100;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 20;\nexport const ALL_CHATS_PRELOAD_DISABLED = false;\n\nexport const DEFAULT_VOLUME = 1;\nexport const DEFAULT_PLAYBACK_RATE = 1;\n\nexport const ANIMATION_LEVEL_MIN = 0;\nexport const ANIMATION_LEVEL_MED = 1;\nexport const ANIMATION_LEVEL_MAX = 2;\nexport const ANIMATION_LEVEL_DEFAULT = ANIMATION_LEVEL_MAX;\n\nexport const DEFAULT_MESSAGE_TEXT_SIZE_PX = 16;\nexport const IOS_DEFAULT_MESSAGE_TEXT_SIZE_PX = 17;\nexport const MACOS_DEFAULT_MESSAGE_TEXT_SIZE_PX = 15;\n\nexport const DRAFT_DEBOUNCE = 10000; // 10s\n\nexport const EDITABLE_INPUT_ID = 'editable-message-text';\nexport const EDITABLE_INPUT_MODAL_ID = 'editable-message-text-modal';\n\n// Screen width where Pinned Message / Audio Player in the Middle Header can be safely displayed\nexport const SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1440; // px\n// Screen width where Pinned Message / Audio Player in the Middle Header shouldn't collapse with ChatInfo\nexport const SAFE_SCREEN_WIDTH_FOR_CHAT_INFO = 1150; // px\n\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1275; // px\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN = 925; // px\nexport const MOBILE_SCREEN_MAX_WIDTH = 600; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH = 950; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT = 450; // px\n\nexport const LOCAL_MESSAGE_ID_BASE = 1e9;\nexport const TMP_CHAT_ID = '0';\n\nexport const ANIMATION_END_DELAY = 100;\n\nexport const FAST_SMOOTH_MAX_DISTANCE = 1500;\nexport const FAST_SMOOTH_MIN_DURATION = 250;\nexport const FAST_SMOOTH_MAX_DURATION = 600;\nexport const FAST_SMOOTH_SHORT_TRANSITION_MAX_DISTANCE = 500; // px\n\n// Average duration of message sending animation\nexport const API_UPDATE_THROTTLE = Math.round((FAST_SMOOTH_MIN_DURATION + FAST_SMOOTH_MAX_DURATION) / 2);\nexport const API_THROTTLE_RESET_UPDATES = new Set([\n 'newMessage', 'newScheduledMessage', 'deleteMessages', 'deleteScheduledMessages', 'deleteHistory',\n]);\n\nexport const STICKER_SIZE_INLINE_DESKTOP_FACTOR = 13;\nexport const STICKER_SIZE_INLINE_MOBILE_FACTOR = 11;\nexport const STICKER_SIZE_AUTH = 160;\nexport const STICKER_SIZE_AUTH_MOBILE = 120;\nexport const STICKER_SIZE_PICKER = 64;\nexport const STICKER_SIZE_GENERAL_SETTINGS = 48;\nexport const STICKER_SIZE_PICKER_HEADER = 32;\nexport const STICKER_SIZE_SEARCH = 64;\nexport const STICKER_SIZE_MODAL = 64;\nexport const STICKER_SIZE_TWO_FA = 160;\nexport const STICKER_SIZE_DISCUSSION_GROUPS = 140;\nexport const STICKER_SIZE_FOLDER_SETTINGS = 80;\nexport const STICKER_SIZE_INLINE_BOT_RESULT = 100;\nexport const RECENT_STICKERS_LIMIT = 20;\nexport const MEMOJI_STICKER_ID = 'MEMOJI_STICKER';\n\nexport const BASE_EMOJI_KEYWORD_LANG = 'en';\n\nexport const MENU_TRANSITION_DURATION = 200;\nexport const SLIDE_TRANSITION_DURATION = 450;\n\nexport const VIDEO_MOV_TYPE = 'video/quicktime';\n\nexport const SUPPORTED_IMAGE_CONTENT_TYPES = new Set([\n 'image/png', 'image/gif', 'image/jpeg',\n]);\n\nexport const SUPPORTED_VIDEO_CONTENT_TYPES = new Set([\n 'video/mp4', // video/quicktime added dynamically in environment.ts\n]);\n\nexport const CONTENT_TYPES_WITH_PREVIEW = new Set([\n ...SUPPORTED_IMAGE_CONTENT_TYPES,\n ...SUPPORTED_VIDEO_CONTENT_TYPES,\n]);\n\n// eslint-disable-next-line max-len\nexport const RE_LINK_TEMPLATE = '((ftp|https?):\\\\/\\\\/)?((www\\\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\\\.[a-zA-Z0-9()]{1,63})\\\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)';\nexport const RE_MENTION_TEMPLATE = '(@[\\\\w\\\\d_-]+)';\nexport const RE_TG_LINK = /^tg:(\\/\\/)?([?=&\\d\\w_-]+)?/gm;\nexport const RE_TME_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/)/gm;\n\n// eslint-disable-next-line max-len\nexport const COUNTRIES_WITH_12H_TIME_FORMAT = new Set(['AU', 'BD', 'CA', 'CO', 'EG', 'HN', 'IE', 'IN', 'JO', 'MX', 'MY', 'NI', 'NZ', 'PH', 'PK', 'SA', 'SV', 'US']);\n\n// MTProto constants\nexport const SERVICE_NOTIFICATIONS_USER_ID = '777000';\nexport const REPLIES_USER_ID = '1271266957'; // TODO For Test connection ID must be equal to 708513\nexport const ALL_FOLDER_ID = 0;\nexport const ARCHIVED_FOLDER_ID = 1;\nexport const DELETED_COMMENTS_CHANNEL_ID = '-777';\nexport const MAX_MEDIA_FILES_FOR_ALBUM = 10;\nexport const MAX_ACTIVE_PINNED_CHATS = 5;\nexport const SCHEDULED_WHEN_ONLINE = 0x7FFFFFFE;\nexport const DEFAULT_LANG_CODE = 'en';\nexport const DEFAULT_LANG_PACK = 'android';\nexport const LANG_PACKS = ['android', 'ios', 'tdesktop', 'macos'] as const;\nexport const TIPS_USERNAME = 'TelegramTips';\nexport const LOCALIZED_TIPS = ['ar', 'pt-br', 'id', 'it', 'ko', 'ms', 'pl', 'es', 'tr'];\nexport const FEEDBACK_URL = 'https://bugs.telegram.org/?tag_ids=41&sort=time';\nexport const LIGHT_THEME_BG_COLOR = '#A2AF8E';\nexport const DARK_THEME_BG_COLOR = '#0F0F0F';\nexport const DARK_THEME_PATTERN_COLOR = '#0a0a0a8c';\nexport const DEFAULT_PATTERN_COLOR = 'rgba(90, 110, 70, 0.6)';\n","type Scheduler =\n typeof requestAnimationFrame\n | typeof onTickEnd\n | typeof runNow;\n\nexport function debounce(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n shouldRunLast = true,\n) {\n let waitingTimeout: number | undefined;\n\n return (...args: Parameters) => {\n if (waitingTimeout) {\n clearTimeout(waitingTimeout);\n waitingTimeout = undefined;\n } else if (shouldRunFirst) {\n // @ts-ignore\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n waitingTimeout = self.setTimeout(() => {\n if (shouldRunLast) {\n // @ts-ignore\n fn(...args);\n }\n\n waitingTimeout = undefined;\n }, ms);\n };\n}\n\nexport function throttle(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n) {\n let interval: number | undefined;\n let isPending: boolean;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n isPending = true;\n args = _args;\n\n if (!interval) {\n if (shouldRunFirst) {\n isPending = false;\n // @ts-ignore\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n interval = self.setInterval(() => {\n if (!isPending) {\n // eslint-disable-next-line no-restricted-globals\n self.clearInterval(interval!);\n interval = undefined;\n return;\n }\n\n isPending = false;\n // @ts-ignore\n fn(...args);\n }, ms);\n }\n };\n}\n\nexport function throttleWithRaf(fn: F) {\n return throttleWith(fastRaf, fn);\n}\n\nexport function throttleWithPrimaryRaf(fn: F) {\n return throttleWith(fastRafPrimary, fn);\n}\n\nexport function throttleWithTickEnd(fn: F) {\n return throttleWith(onTickEnd, fn);\n}\n\nexport function throttleWithNow(fn: F) {\n return throttleWith(runNow, fn);\n}\n\nexport function throttleWith(schedulerFn: Scheduler, fn: F) {\n let waiting = false;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n args = _args;\n\n if (!waiting) {\n waiting = true;\n\n schedulerFn(() => {\n waiting = false;\n // @ts-ignore\n fn(...args);\n });\n }\n };\n}\n\nexport function onIdle(cb: NoneToVoidFunction) {\n // eslint-disable-next-line no-restricted-globals\n if (self.requestIdleCallback) {\n // eslint-disable-next-line no-restricted-globals\n self.requestIdleCallback(cb);\n } else {\n onTickEnd(cb);\n }\n}\n\nfunction runNow(fn: NoneToVoidFunction) {\n fn();\n}\n\nexport const pause = (ms: number) => new Promise((resolve) => {\n setTimeout(() => resolve(), ms);\n});\n\nexport function rafPromise() {\n return new Promise((resolve) => {\n fastRaf(resolve);\n });\n}\n\nlet fastRafCallbacks: NoneToVoidFunction[] | undefined;\nlet fastRafPrimaryCallbacks: NoneToVoidFunction[] | undefined;\n\n// May result in an immediate execution if called from another `requestAnimationFrame` callback\nexport function fastRaf(callback: NoneToVoidFunction, isPrimary = false) {\n if (!fastRafCallbacks) {\n fastRafCallbacks = isPrimary ? [] : [callback];\n fastRafPrimaryCallbacks = isPrimary ? [callback] : [];\n\n requestAnimationFrame(() => {\n const currentCallbacks = fastRafCallbacks!;\n const currentPrimaryCallbacks = fastRafPrimaryCallbacks!;\n fastRafCallbacks = undefined;\n fastRafPrimaryCallbacks = undefined;\n currentPrimaryCallbacks.forEach((cb) => cb());\n currentCallbacks.forEach((cb) => cb());\n });\n } else if (isPrimary) {\n fastRafPrimaryCallbacks!.push(callback);\n } else {\n fastRafCallbacks.push(callback);\n }\n}\n\nexport function fastRafPrimary(callback: NoneToVoidFunction) {\n fastRaf(callback, true);\n}\n\nlet onTickEndCallbacks: NoneToVoidFunction[] | undefined;\nlet onTickEndPrimaryCallbacks: NoneToVoidFunction[] | undefined;\n\nexport function onTickEnd(callback: NoneToVoidFunction, isPrimary = false) {\n if (!onTickEndCallbacks) {\n onTickEndCallbacks = isPrimary ? [] : [callback];\n onTickEndPrimaryCallbacks = isPrimary ? [callback] : [];\n\n Promise.resolve().then(() => {\n const currentCallbacks = onTickEndCallbacks!;\n const currentPrimaryCallbacks = onTickEndPrimaryCallbacks!;\n onTickEndCallbacks = undefined;\n onTickEndPrimaryCallbacks = undefined;\n currentPrimaryCallbacks.forEach((cb) => cb());\n currentCallbacks.forEach((cb) => cb());\n });\n } else if (isPrimary) {\n onTickEndPrimaryCallbacks!.push(callback);\n } else {\n onTickEndCallbacks.push(callback);\n }\n}\n\nexport function onTickEndPrimary(callback: NoneToVoidFunction) {\n onTickEnd(callback, true);\n}\n\nlet beforeUnloadCallbacks: NoneToVoidFunction[] | undefined;\n\nexport function onBeforeUnload(callback: NoneToVoidFunction, isLast = false) {\n if (!beforeUnloadCallbacks) {\n beforeUnloadCallbacks = [];\n // eslint-disable-next-line no-restricted-globals\n self.addEventListener('beforeunload', () => {\n beforeUnloadCallbacks!.forEach((cb) => cb());\n });\n }\n\n if (isLast) {\n beforeUnloadCallbacks.push(callback);\n } else {\n beforeUnloadCallbacks.unshift(callback);\n }\n\n return () => {\n beforeUnloadCallbacks = beforeUnloadCallbacks!.filter((cb) => cb !== callback);\n };\n}\n","import { pause } from '../util/schedulers';\nimport generateIdFor from '../util/generateIdFor';\nimport {\n DEBUG,\n MEDIA_CACHE_MAX_BYTES,\n MEDIA_PROGRESSIVE_CACHE_DISABLED,\n MEDIA_PROGRESSIVE_CACHE_NAME,\n} from '../config';\n\ndeclare const self: ServiceWorkerGlobalScope;\n\ntype PartInfo = {\n type: 'PartInfo';\n arrayBuffer: ArrayBuffer;\n mimeType: 'string';\n fullSize: number;\n};\n\ntype RequestStates = {\n resolve: (response: PartInfo) => void;\n reject: () => void;\n};\n\nconst MB = 1024 * 1024;\nconst DEFAULT_PART_SIZE = 0.5 * MB;\nconst MAX_END_TO_CACHE = 2 * MB - 1; // We only cache the first 2 MB of each file\nconst PART_TIMEOUT = 60000;\n\nconst requestStates = new Map();\n\nexport async function respondForProgressive(e: FetchEvent) {\n const { url } = e.request;\n const range = e.request.headers.get('range');\n const bytes = /^bytes=(\\d+)-(\\d+)?$/g.exec(range || '')!;\n const start = Number(bytes[1]);\n const originalEnd = Number(bytes[2]);\n\n let end = originalEnd;\n if (!end || (end - start + 1) > DEFAULT_PART_SIZE) {\n end = start + DEFAULT_PART_SIZE - 1;\n }\n\n // Optimization for Safari\n if (start === 0 && end === 1) {\n const match = e.request.url.match(/fileSize=(\\d+)&mimeType=([\\w/]+)/);\n const fileSize = match && Number(match[1]);\n const mimeType = match?.[2];\n\n if (fileSize && mimeType) {\n return new Response(new Uint8Array(2).buffer, {\n status: 206,\n statusText: 'Partial Content',\n headers: [\n ['Content-Range', `bytes 0-1/${fileSize}`],\n ['Accept-Ranges', 'bytes'],\n ['Content-Length', '2'],\n ['Content-Type', mimeType],\n ],\n });\n }\n }\n\n const cacheKey = `${url}?start=${start}&end=${end}`;\n const [cachedArrayBuffer, cachedHeaders] = !MEDIA_PROGRESSIVE_CACHE_DISABLED ? await fetchFromCache(cacheKey) : [];\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log(\n `FETCH PROGRESSIVE ${cacheKey} (request: ${start}-${originalEnd}) CACHED: ${Boolean(cachedArrayBuffer)}`,\n );\n }\n\n if (cachedArrayBuffer) {\n return new Response(cachedArrayBuffer, {\n status: 206,\n statusText: 'Partial Content',\n headers: cachedHeaders,\n });\n }\n\n let partInfo;\n try {\n partInfo = await requestPart(e, { url, start, end });\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('FETCH PROGRESSIVE', err);\n }\n }\n\n if (!partInfo) {\n return new Response('', {\n status: 500,\n statusText: 'Failed to fetch progressive part',\n });\n }\n\n const { arrayBuffer, fullSize, mimeType } = partInfo;\n\n const partSize = Math.min(end - start + 1, arrayBuffer.byteLength);\n end = start + partSize - 1;\n const arrayBufferPart = arrayBuffer.slice(0, partSize);\n const headers = [\n ['Content-Range', `bytes ${start}-${end}/${fullSize}`],\n ['Accept-Ranges', 'bytes'],\n ['Content-Length', String(partSize)],\n ['Content-Type', mimeType],\n ];\n\n if (!MEDIA_PROGRESSIVE_CACHE_DISABLED && partSize <= MEDIA_CACHE_MAX_BYTES && end < MAX_END_TO_CACHE) {\n saveToCache(cacheKey, arrayBufferPart, headers);\n }\n\n return new Response(arrayBufferPart, {\n status: 206,\n statusText: 'Partial Content',\n headers,\n });\n}\n\n// We can not cache 206 responses: https://github.com/GoogleChrome/workbox/issues/1644#issuecomment-638741359\nasync function fetchFromCache(cacheKey: string) {\n const cache = await self.caches.open(MEDIA_PROGRESSIVE_CACHE_NAME);\n\n return Promise.all([\n cache.match(`${cacheKey}&type=arrayBuffer`).then((r) => (r ? r.arrayBuffer() : undefined)),\n cache.match(`${cacheKey}&type=headers`).then((r) => (r ? r.json() : undefined)),\n ]);\n}\n\nasync function saveToCache(cacheKey: string, arrayBuffer: ArrayBuffer, headers: HeadersInit) {\n const cache = await self.caches.open(MEDIA_PROGRESSIVE_CACHE_NAME);\n\n return Promise.all([\n cache.put(new Request(`${cacheKey}&type=arrayBuffer`), new Response(arrayBuffer)),\n cache.put(new Request(`${cacheKey}&type=headers`), new Response(JSON.stringify(headers))),\n ]);\n}\n\nasync function requestPart(\n e: FetchEvent,\n params: { url: string; start: number; end: number },\n): Promise {\n if (!e.clientId) {\n return undefined;\n }\n\n // eslint-disable-next-line no-restricted-globals\n const client = await self.clients.get(e.clientId);\n if (!client) {\n return undefined;\n }\n\n const messageId = generateIdFor(requestStates);\n const requestState = {} as RequestStates;\n\n const promise = Promise.race([\n pause(PART_TIMEOUT).then(() => Promise.reject(new Error('ERROR_PART_TIMEOUT'))),\n new Promise((resolve, reject) => {\n Object.assign(requestState, { resolve, reject });\n }),\n ]);\n\n requestStates.set(messageId, requestState);\n promise\n .catch(() => undefined)\n .finally(() => {\n requestStates.delete(messageId);\n });\n\n client.postMessage({\n type: 'requestPart',\n messageId,\n params,\n });\n\n return promise;\n}\n\nself.addEventListener('message', (e) => {\n const { type, messageId, result } = e.data as {\n type: string;\n messageId: string;\n result: PartInfo;\n };\n\n if (type === 'partResponse') {\n const requestState = requestStates.get(messageId);\n if (requestState) {\n requestState.resolve(result);\n }\n }\n});\n","import { ASSET_CACHE_NAME } from '../config';\nimport { pause } from '../util/schedulers';\n\ndeclare const self: ServiceWorkerGlobalScope;\n\n// An attempt to fix freezing UI on iOS\nconst CACHE_TIMEOUT = 3000;\n\nexport async function respondWithCache(e: FetchEvent) {\n const cacheResult = await withTimeout(async () => {\n const cache = await self.caches.open(ASSET_CACHE_NAME);\n const cached = await cache.match(e.request);\n\n return { cache, cached };\n }, CACHE_TIMEOUT);\n\n const { cache, cached } = cacheResult || {};\n\n if (cache && cached) {\n if (cached.ok) {\n return cached;\n } else {\n await cache.delete(e.request);\n }\n }\n\n const remote = await fetch(e.request);\n\n if (remote.ok && cache) {\n cache.put(e.request, remote.clone());\n }\n\n return remote;\n}\n\nasync function withTimeout(cb: () => Promise, timeout: number) {\n try {\n return await Promise.race([\n pause(timeout).then(() => Promise.reject(new Error('TIMEOUT'))),\n cb(),\n ]);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(err);\n return undefined;\n }\n}\n\nexport function clearAssetCache() {\n return self.caches.delete(ASSET_CACHE_NAME);\n}\n","import { APP_NAME, DEBUG } from '../config';\n\ndeclare const self: ServiceWorkerGlobalScope;\n\nenum Boolean {\n True = '1',\n False = '0',\n}\n\ntype PushData = {\n custom: {\n msg_id?: string;\n channel_id?: string;\n chat_id?: string;\n from_id?: string;\n };\n mute: Boolean;\n badge: Boolean;\n loc_key: string;\n loc_args: string[];\n random_id: number;\n title: string;\n description: string;\n};\n\ntype NotificationData = {\n messageId?: number;\n chatId?: string;\n title: string;\n body: string;\n icon?: string;\n};\n\ntype CloseNotificationData = {\n lastReadInboxMessageId?: number;\n chatId: string;\n};\n\nlet lastSyncAt = new Date().valueOf();\nconst shownNotifications = new Set();\nconst clickBuffer: Record = {};\n\nfunction getPushData(e: PushEvent | Notification): PushData | undefined {\n try {\n return e.data.json();\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[SW] Unable to parse push notification data', e.data);\n }\n return undefined;\n }\n}\n\nfunction getChatId(data: PushData) {\n if (data.custom.from_id) {\n return data.custom.from_id;\n }\n\n // Chats and channels have “negative” IDs\n if (data.custom.chat_id || data.custom.channel_id) {\n return `-${data.custom.chat_id || data.custom.channel_id}`;\n }\n\n return undefined;\n}\n\nfunction getMessageId(data: PushData) {\n if (!data.custom.msg_id) return undefined;\n return parseInt(data.custom.msg_id, 10);\n}\n\nfunction getNotificationData(data: PushData): NotificationData {\n return {\n chatId: getChatId(data),\n messageId: getMessageId(data),\n title: data.title || APP_NAME,\n body: data.description,\n };\n}\n\nasync function getClients() {\n const appUrl = new URL(self.registration.scope).origin;\n const clients = await self.clients.matchAll({ type: 'window' }) as WindowClient[];\n return clients.filter((client) => {\n return new URL(client.url).origin === appUrl;\n });\n}\n\nasync function playNotificationSound(id: string) {\n const clients = await getClients();\n const client = clients[0];\n if (!client) return;\n client.postMessage({\n type: 'playNotificationSound',\n payload: { id },\n });\n}\n\nfunction showNotification({\n chatId,\n messageId,\n body,\n title,\n icon,\n}: NotificationData) {\n const isFirstBatch = new Date().valueOf() - lastSyncAt < 1000;\n const tag = String(isFirstBatch ? 0 : chatId || 0);\n const options: NotificationOptions = {\n body,\n data: {\n chatId,\n messageId,\n count: 1,\n },\n icon: icon || 'icon-192x192.png',\n badge: 'icon-192x192.png',\n tag,\n vibrate: [200, 100, 200],\n };\n\n return Promise.all([\n playNotificationSound(String(messageId) || chatId || ''),\n self.registration.showNotification(title, options),\n ]);\n}\n\nasync function closeNotifications({\n chatId,\n lastReadInboxMessageId,\n}: CloseNotificationData) {\n const notifications = await self.registration.getNotifications();\n const lastMessageId = lastReadInboxMessageId || Number.MAX_VALUE;\n notifications.forEach((notification) => {\n if (\n notification.tag === '0'\n || (notification.data.chatId === chatId && notification.data.messageId <= lastMessageId)\n ) {\n notification.close();\n }\n });\n}\n\nexport function handlePush(e: PushEvent) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[SW] Push received event', e);\n if (e.data) {\n // eslint-disable-next-line no-console\n console.log('[SW] Push received with data', e.data.json());\n }\n }\n\n const data = getPushData(e);\n\n // Do not show muted notifications\n if (!data || data.mute === Boolean.True) return;\n\n const notification = getNotificationData(data);\n\n // Dont show already triggered notification\n if (shownNotifications.has(notification.messageId)) {\n shownNotifications.delete(notification.messageId);\n return;\n }\n\n e.waitUntil(showNotification(notification));\n}\n\nasync function focusChatMessage(client: WindowClient, data: { chatId?: string; messageId?: number }) {\n const {\n chatId,\n messageId,\n } = data;\n if (!chatId) return;\n client.postMessage({\n type: 'focusMessage',\n payload: {\n chatId,\n messageId,\n },\n });\n if (!client.focused) {\n // Catch \"focus not allowed\" DOM Exceptions\n try {\n await client.focus();\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('[SW] ', error);\n }\n }\n }\n}\n\nexport function handleNotificationClick(e: NotificationEvent) {\n const appUrl = self.registration.scope;\n e.notification.close(); // Android needs explicit close.\n const { data } = e.notification;\n const notifyClients = async () => {\n const clients = await getClients();\n await Promise.all(clients.map((client) => {\n clickBuffer[client.id] = data;\n return focusChatMessage(client, data);\n }));\n if (!self.clients.openWindow || clients.length > 0) return undefined;\n // Store notification data for default client (fix for android)\n clickBuffer[0] = data;\n // If there is no opened client we need to open one and wait until it is fully loaded\n try {\n const newClient = await self.clients.openWindow(appUrl);\n if (newClient) {\n // Store notification data until client is fully loaded\n clickBuffer[newClient.id] = data;\n }\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('[SW] ', error);\n }\n }\n return undefined;\n };\n e.waitUntil(notifyClients());\n}\n\nexport function handleClientMessage(e: ExtendableMessageEvent) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[SW] New message from client', e);\n }\n if (!e.data) return;\n const source = e.source as WindowClient;\n if (e.data.type === 'clientReady') {\n // focus on chat message when client is fully ready\n const data = clickBuffer[source.id] || clickBuffer[0];\n if (data) {\n delete clickBuffer[source.id];\n delete clickBuffer[0];\n e.waitUntil(focusChatMessage(source, data));\n }\n }\n if (e.data.type === 'newMessageNotification') {\n // store messageId for already shown notification\n const notification: NotificationData = e.data.payload;\n // mark this notification as shown if it was handled locally\n shownNotifications.add(notification.messageId);\n e.waitUntil(showNotification(notification));\n }\n\n if (e.data.type === 'closeMessageNotifications') {\n e.waitUntil(closeNotifications(e.data.payload));\n }\n}\n\nself.onsync = () => {\n lastSyncAt = new Date().valueOf();\n};\n","import { DEBUG } from './config';\nimport { respondForProgressive } from './serviceWorker/progressive';\nimport { respondWithCache, clearAssetCache } from './serviceWorker/assetCache';\nimport { handlePush, handleNotificationClick, handleClientMessage } from './serviceWorker/pushNotification';\nimport { pause } from './util/schedulers';\n\ndeclare const self: ServiceWorkerGlobalScope;\n\nconst ASSET_CACHE_PATTERN = /[0-9a-f]{20}.*\\.(js|css|woff2?|svg|png|jpg|jpeg|json|wasm)$/;\nconst ACTIVATE_TIMEOUT = 3000;\n\nself.addEventListener('install', (e) => {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('ServiceWorker installed');\n }\n\n // Activate worker immediately\n e.waitUntil(self.skipWaiting());\n});\n\nself.addEventListener('activate', (e) => {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('ServiceWorker activated');\n }\n\n e.waitUntil(\n Promise.race([\n // An attempt to fix freezing UI on iOS\n pause(ACTIVATE_TIMEOUT),\n Promise.all([\n clearAssetCache(),\n // Become available to all pages\n self.clients.claim(),\n ]),\n ]),\n );\n});\n\n// eslint-disable-next-line no-restricted-globals\nself.addEventListener('fetch', (e: FetchEvent) => {\n const { url } = e.request;\n\n if (url.includes('/progressive/')) {\n e.respondWith(respondForProgressive(e));\n return true;\n }\n\n if (url.startsWith('http') && url.match(ASSET_CACHE_PATTERN)) {\n e.respondWith(respondWithCache(e));\n return true;\n }\n\n return false;\n});\n\nself.addEventListener('push', handlePush);\nself.addEventListener('notificationclick', handleNotificationClick);\nself.addEventListener('message', handleClientMessage);\n","export default (store: AnyLiteral) => {\n let id;\n\n do {\n id = String(Math.random()).replace('0.', 'id');\n } while (store.hasOwnProperty(id));\n\n return id;\n};\n"],"names":["MEDIA_PROGRESSIVE_CACHE_NAME","ASSET_CACHE_NAME","SUPPORTED_IMAGE_CONTENT_TYPES","window","innerHeight","Math","round","Set","SUPPORTED_VIDEO_CONTENT_TYPES","pause","ms","Promise","resolve","setTimeout","DEFAULT_PART_SIZE","requestStates","Map","async","respondWithCache","e","cacheResult","cb","timeout","race","then","reject","Error","cache","self","caches","open","cached","match","request","err","console","error","withTimeout","ok","delete","remote","fetch","put","clone","Boolean","addEventListener","type","messageId","result","data","requestState","get","lastSyncAt","Date","valueOf","shownNotifications","clickBuffer","getChatId","custom","from_id","chat_id","channel_id","getMessageId","msg_id","parseInt","getClients","appUrl","URL","registration","scope","origin","clients","matchAll","filter","client","url","playNotificationSound","id","postMessage","payload","showNotification","chatId","body","title","icon","isFirstBatch","options","count","badge","tag","String","vibrate","all","focusChatMessage","focused","focus","onsync","ASSET_CACHE_PATTERN","waitUntil","skipWaiting","claim","includes","respondWith","range","headers","bytes","exec","start","Number","end","fileSize","mimeType","Response","Uint8Array","buffer","status","statusText","cacheKey","cachedArrayBuffer","cachedHeaders","r","arrayBuffer","undefined","json","fetchFromCache","partInfo","params","clientId","store","random","replace","hasOwnProperty","generateIdFor","promise","Object","assign","set","catch","finally","requestPart","fullSize","partSize","min","byteLength","arrayBufferPart","slice","Request","JSON","stringify","saveToCache","respondForProgressive","startsWith","getPushData","mute","True","notification","process","description","getNotificationData","has","close","map","openWindow","length","newClient","notifyClients","source","add","lastReadInboxMessageId","notifications","getNotifications","lastMessageId","MAX_VALUE","forEach","closeNotifications"],"sourceRoot":""} \ No newline at end of file +{"version":3,"file":"524.632897f7413c1c081b04.js","mappings":"mBAAO,MA6BMA,EAA+B,uBAI/BC,EAAmB,YAkGnBC,GA5FyB,oBAAXC,QAA0BA,OAAOC,YAgEzBC,KAAKC,MAAM,KACJ,IAAIC,IAAI,CAChD,aAAc,sBAAuB,i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,EAAa1G,KAAKgC,SAAWA,GAAU0E,EAAa1G,KAAKF,WAAa4H,IAE1EhB,EAAaK,WAiHHc,CAAmB3J,EAAE8B,KAAK8B,c","sources":["webpack://telegram-t/./src/config.ts","webpack://telegram-t/./src/util/schedulers.ts","webpack://telegram-t/./src/serviceWorker/progressive.ts","webpack://telegram-t/./src/serviceWorker/assetCache.ts","webpack://telegram-t/./src/serviceWorker/pushNotification.ts","webpack://telegram-t/./src/serviceWorker.ts","webpack://telegram-t/./src/util/generateIdFor.ts"],"sourcesContent":["export const PAGE_TITLE = 'Telegram';\nexport const INACTIVE_MARKER = ' [Inactive]';\n\nexport const APP_NAME = process.env.APP_NAME || 'Telegram WebZ';\nexport const APP_VERSION = process.env.APP_VERSION || 'dev';\n\nexport const DEBUG = (\n process.env.APP_ENV !== 'production' && process.env.APP_ENV !== 'perf' && process.env.APP_ENV !== 'test'\n);\nexport const DEBUG_MORE = false;\n\nexport const IS_TEST = process.env.APP_ENV === 'test';\nexport const IS_PERF = process.env.APP_ENV === 'perf';\n\nexport const DEBUG_ALERT_MSG = 'Shoot!\\nSomething went wrong, please see the error details in Dev Tools Console.';\nexport const DEBUG_GRAMJS = false;\n\nexport const SESSION_USER_KEY = 'user_auth';\nexport const LEGACY_SESSION_KEY = 'GramJs:sessionId';\n\nexport const GLOBAL_STATE_CACHE_DISABLED = false;\nexport const GLOBAL_STATE_CACHE_KEY = 'tt-global-state';\nexport const GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT = 30;\nexport const GLOBAL_STATE_CACHE_USER_LIST_LIMIT = 5000;\n\nexport const MEDIA_CACHE_DISABLED = false;\nexport const MEDIA_CACHE_NAME = 'tt-media';\nexport const MEDIA_CACHE_NAME_AVATARS = 'tt-media-avatars';\nexport const MEDIA_PROGRESSIVE_CACHE_DISABLED = false;\nexport const MEDIA_PROGRESSIVE_CACHE_NAME = 'tt-media-progressive';\nexport const MEDIA_CACHE_MAX_BYTES = 512 * 1024; // 512 KB\nexport const CUSTOM_BG_CACHE_NAME = 'tt-custom-bg';\nexport const LANG_CACHE_NAME = 'tt-lang-packs-v6';\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_SENSITIVE_AREA = 750;\nexport const MESSAGE_LIST_SLICE = isBigScreen ? 60 : 40;\nexport const MESSAGE_LIST_VIEWPORT_LIMIT = MESSAGE_LIST_SLICE * 2;\n\nexport const CHAT_HEIGHT_PX = 72;\nexport const CHAT_LIST_SLICE = isBigScreen ? 30 : 25;\nexport const CHAT_LIST_LOAD_SLICE = 100;\nexport const SHARED_MEDIA_SLICE = 42;\nexport const MESSAGE_SEARCH_SLICE = 42;\nexport const GLOBAL_SEARCH_SLICE = 20;\nexport const MEMBERS_SLICE = 30;\nexport const MEMBERS_LOAD_SLICE = 200;\nexport const PINNED_MESSAGES_LIMIT = 50;\nexport const BLOCKED_LIST_LIMIT = 100;\nexport const PROFILE_PHOTOS_LIMIT = 40;\nexport const PROFILE_SENSITIVE_AREA = 500;\nexport const COMMON_CHATS_LIMIT = 100;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 20;\nexport const ALL_CHATS_PRELOAD_DISABLED = false;\n\nexport const DEFAULT_VOLUME = 1;\nexport const DEFAULT_PLAYBACK_RATE = 1;\n\nexport const ANIMATION_LEVEL_MIN = 0;\nexport const ANIMATION_LEVEL_MED = 1;\nexport const ANIMATION_LEVEL_MAX = 2;\nexport const ANIMATION_LEVEL_DEFAULT = ANIMATION_LEVEL_MAX;\n\nexport const DEFAULT_MESSAGE_TEXT_SIZE_PX = 16;\nexport const IOS_DEFAULT_MESSAGE_TEXT_SIZE_PX = 17;\nexport const MACOS_DEFAULT_MESSAGE_TEXT_SIZE_PX = 15;\n\nexport const DRAFT_DEBOUNCE = 10000; // 10s\n\nexport const EDITABLE_INPUT_ID = 'editable-message-text';\nexport const EDITABLE_INPUT_MODAL_ID = 'editable-message-text-modal';\n\n// Screen width where Pinned Message / Audio Player in the Middle Header can be safely displayed\nexport const SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1440; // px\n// Screen width where Pinned Message / Audio Player in the Middle Header shouldn't collapse with ChatInfo\nexport const SAFE_SCREEN_WIDTH_FOR_CHAT_INFO = 1150; // px\n\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1275; // px\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN = 925; // px\nexport const MOBILE_SCREEN_MAX_WIDTH = 600; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH = 950; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT = 450; // px\n\nexport const LOCAL_MESSAGE_ID_BASE = 1e9;\nexport const TMP_CHAT_ID = '0';\n\nexport const ANIMATION_END_DELAY = 100;\n\nexport const FAST_SMOOTH_MAX_DISTANCE = 1500;\nexport const FAST_SMOOTH_MIN_DURATION = 250;\nexport const FAST_SMOOTH_MAX_DURATION = 600;\nexport const FAST_SMOOTH_SHORT_TRANSITION_MAX_DISTANCE = 500; // px\n\n// Average duration of message sending animation\nexport const API_UPDATE_THROTTLE = Math.round((FAST_SMOOTH_MIN_DURATION + FAST_SMOOTH_MAX_DURATION) / 2);\nexport const API_THROTTLE_RESET_UPDATES = new Set([\n 'newMessage', 'newScheduledMessage', 'deleteMessages', 'deleteScheduledMessages', 'deleteHistory',\n]);\n\nexport const STICKER_SIZE_INLINE_DESKTOP_FACTOR = 13;\nexport const STICKER_SIZE_INLINE_MOBILE_FACTOR = 11;\nexport const STICKER_SIZE_AUTH = 160;\nexport const STICKER_SIZE_AUTH_MOBILE = 120;\nexport const STICKER_SIZE_PICKER = 64;\nexport const STICKER_SIZE_GENERAL_SETTINGS = 48;\nexport const STICKER_SIZE_PICKER_HEADER = 32;\nexport const STICKER_SIZE_SEARCH = 64;\nexport const STICKER_SIZE_MODAL = 64;\nexport const STICKER_SIZE_TWO_FA = 160;\nexport const STICKER_SIZE_DISCUSSION_GROUPS = 140;\nexport const STICKER_SIZE_FOLDER_SETTINGS = 80;\nexport const STICKER_SIZE_INLINE_BOT_RESULT = 100;\nexport const RECENT_STICKERS_LIMIT = 20;\nexport const MEMOJI_STICKER_ID = 'MEMOJI_STICKER';\n\nexport const BASE_EMOJI_KEYWORD_LANG = 'en';\n\nexport const MENU_TRANSITION_DURATION = 200;\nexport const SLIDE_TRANSITION_DURATION = 450;\n\nexport const VIDEO_MOV_TYPE = 'video/quicktime';\n\nexport const SUPPORTED_IMAGE_CONTENT_TYPES = new Set([\n 'image/png', 'image/gif', 'image/jpeg',\n]);\n\nexport const SUPPORTED_VIDEO_CONTENT_TYPES = new Set([\n 'video/mp4', // video/quicktime added dynamically in environment.ts\n]);\n\nexport const CONTENT_TYPES_WITH_PREVIEW = new Set([\n ...SUPPORTED_IMAGE_CONTENT_TYPES,\n ...SUPPORTED_VIDEO_CONTENT_TYPES,\n]);\n\n// eslint-disable-next-line max-len\nexport const RE_LINK_TEMPLATE = '((ftp|https?):\\\\/\\\\/)?((www\\\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\\\.[a-zA-Z0-9()]{1,63})\\\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)';\nexport const RE_MENTION_TEMPLATE = '(@[\\\\w\\\\d_-]+)';\nexport const RE_TG_LINK = /^tg:(\\/\\/)?([?=&\\d\\w_-]+)?/gm;\nexport const RE_TME_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/)/gm;\n\n// eslint-disable-next-line max-len\nexport const COUNTRIES_WITH_12H_TIME_FORMAT = new Set(['AU', 'BD', 'CA', 'CO', 'EG', 'HN', 'IE', 'IN', 'JO', 'MX', 'MY', 'NI', 'NZ', 'PH', 'PK', 'SA', 'SV', 'US']);\n\n// MTProto constants\nexport const SERVICE_NOTIFICATIONS_USER_ID = '777000';\nexport const REPLIES_USER_ID = '1271266957'; // TODO For Test connection ID must be equal to 708513\nexport const ALL_FOLDER_ID = 0;\nexport const ARCHIVED_FOLDER_ID = 1;\nexport const DELETED_COMMENTS_CHANNEL_ID = '-777';\nexport const MAX_MEDIA_FILES_FOR_ALBUM = 10;\nexport const MAX_ACTIVE_PINNED_CHATS = 5;\nexport const SCHEDULED_WHEN_ONLINE = 0x7FFFFFFE;\nexport const DEFAULT_LANG_CODE = 'en';\nexport const DEFAULT_LANG_PACK = 'android';\nexport const LANG_PACKS = ['android', 'ios', 'tdesktop', 'macos'] as const;\nexport const TIPS_USERNAME = 'TelegramTips';\nexport const LOCALIZED_TIPS = ['ar', 'pt-br', 'id', 'it', 'ko', 'ms', 'pl', 'es', 'tr'];\nexport const FEEDBACK_URL = 'https://bugs.telegram.org/?tag_ids=41&sort=time';\nexport const LIGHT_THEME_BG_COLOR = '#A2AF8E';\nexport const DARK_THEME_BG_COLOR = '#0F0F0F';\nexport const DARK_THEME_PATTERN_COLOR = '#0a0a0a8c';\nexport const DEFAULT_PATTERN_COLOR = 'rgba(90, 110, 70, 0.6)';\n","type Scheduler =\n typeof requestAnimationFrame\n | typeof onTickEnd\n | typeof runNow;\n\nexport function debounce(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n shouldRunLast = true,\n) {\n let waitingTimeout: number | undefined;\n\n return (...args: Parameters) => {\n if (waitingTimeout) {\n clearTimeout(waitingTimeout);\n waitingTimeout = undefined;\n } else if (shouldRunFirst) {\n // @ts-ignore\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n waitingTimeout = self.setTimeout(() => {\n if (shouldRunLast) {\n // @ts-ignore\n fn(...args);\n }\n\n waitingTimeout = undefined;\n }, ms);\n };\n}\n\nexport function throttle(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n) {\n let interval: number | undefined;\n let isPending: boolean;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n isPending = true;\n args = _args;\n\n if (!interval) {\n if (shouldRunFirst) {\n isPending = false;\n // @ts-ignore\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n interval = self.setInterval(() => {\n if (!isPending) {\n // eslint-disable-next-line no-restricted-globals\n self.clearInterval(interval!);\n interval = undefined;\n return;\n }\n\n isPending = false;\n // @ts-ignore\n fn(...args);\n }, ms);\n }\n };\n}\n\nexport function throttleWithRaf(fn: F) {\n return throttleWith(fastRaf, fn);\n}\n\nexport function throttleWithPrimaryRaf(fn: F) {\n return throttleWith(fastRafPrimary, fn);\n}\n\nexport function throttleWithTickEnd(fn: F) {\n return throttleWith(onTickEnd, fn);\n}\n\nexport function throttleWithNow(fn: F) {\n return throttleWith(runNow, fn);\n}\n\nexport function throttleWith(schedulerFn: Scheduler, fn: F) {\n let waiting = false;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n args = _args;\n\n if (!waiting) {\n waiting = true;\n\n schedulerFn(() => {\n waiting = false;\n // @ts-ignore\n fn(...args);\n });\n }\n };\n}\n\nexport function onIdle(cb: NoneToVoidFunction) {\n // eslint-disable-next-line no-restricted-globals\n if (self.requestIdleCallback) {\n // eslint-disable-next-line no-restricted-globals\n self.requestIdleCallback(cb);\n } else {\n onTickEnd(cb);\n }\n}\n\nfunction runNow(fn: NoneToVoidFunction) {\n fn();\n}\n\nexport const pause = (ms: number) => new Promise((resolve) => {\n setTimeout(() => resolve(), ms);\n});\n\nexport function rafPromise() {\n return new Promise((resolve) => {\n fastRaf(resolve);\n });\n}\n\nlet fastRafCallbacks: NoneToVoidFunction[] | undefined;\nlet fastRafPrimaryCallbacks: NoneToVoidFunction[] | undefined;\n\n// May result in an immediate execution if called from another `requestAnimationFrame` callback\nexport function fastRaf(callback: NoneToVoidFunction, isPrimary = false) {\n if (!fastRafCallbacks) {\n fastRafCallbacks = isPrimary ? [] : [callback];\n fastRafPrimaryCallbacks = isPrimary ? [callback] : [];\n\n requestAnimationFrame(() => {\n const currentCallbacks = fastRafCallbacks!;\n const currentPrimaryCallbacks = fastRafPrimaryCallbacks!;\n fastRafCallbacks = undefined;\n fastRafPrimaryCallbacks = undefined;\n currentPrimaryCallbacks.forEach((cb) => cb());\n currentCallbacks.forEach((cb) => cb());\n });\n } else if (isPrimary) {\n fastRafPrimaryCallbacks!.push(callback);\n } else {\n fastRafCallbacks.push(callback);\n }\n}\n\nexport function fastRafPrimary(callback: NoneToVoidFunction) {\n fastRaf(callback, true);\n}\n\nlet onTickEndCallbacks: NoneToVoidFunction[] | undefined;\nlet onTickEndPrimaryCallbacks: NoneToVoidFunction[] | undefined;\n\nexport function onTickEnd(callback: NoneToVoidFunction, isPrimary = false) {\n if (!onTickEndCallbacks) {\n onTickEndCallbacks = isPrimary ? [] : [callback];\n onTickEndPrimaryCallbacks = isPrimary ? [callback] : [];\n\n Promise.resolve().then(() => {\n const currentCallbacks = onTickEndCallbacks!;\n const currentPrimaryCallbacks = onTickEndPrimaryCallbacks!;\n onTickEndCallbacks = undefined;\n onTickEndPrimaryCallbacks = undefined;\n currentPrimaryCallbacks.forEach((cb) => cb());\n currentCallbacks.forEach((cb) => cb());\n });\n } else if (isPrimary) {\n onTickEndPrimaryCallbacks!.push(callback);\n } else {\n onTickEndCallbacks.push(callback);\n }\n}\n\nexport function onTickEndPrimary(callback: NoneToVoidFunction) {\n onTickEnd(callback, true);\n}\n\nlet beforeUnloadCallbacks: NoneToVoidFunction[] | undefined;\n\nexport function onBeforeUnload(callback: NoneToVoidFunction, isLast = false) {\n if (!beforeUnloadCallbacks) {\n beforeUnloadCallbacks = [];\n // eslint-disable-next-line no-restricted-globals\n self.addEventListener('beforeunload', () => {\n beforeUnloadCallbacks!.forEach((cb) => cb());\n });\n }\n\n if (isLast) {\n beforeUnloadCallbacks.push(callback);\n } else {\n beforeUnloadCallbacks.unshift(callback);\n }\n\n return () => {\n beforeUnloadCallbacks = beforeUnloadCallbacks!.filter((cb) => cb !== callback);\n };\n}\n","import { pause } from '../util/schedulers';\nimport generateIdFor from '../util/generateIdFor';\nimport {\n DEBUG,\n MEDIA_CACHE_MAX_BYTES,\n MEDIA_PROGRESSIVE_CACHE_DISABLED,\n MEDIA_PROGRESSIVE_CACHE_NAME,\n} from '../config';\n\ndeclare const self: ServiceWorkerGlobalScope;\n\ntype PartInfo = {\n type: 'PartInfo';\n arrayBuffer: ArrayBuffer;\n mimeType: 'string';\n fullSize: number;\n};\n\ntype RequestStates = {\n resolve: (response: PartInfo) => void;\n reject: () => void;\n};\n\nconst MB = 1024 * 1024;\nconst DEFAULT_PART_SIZE = 0.5 * MB;\nconst MAX_END_TO_CACHE = 2 * MB - 1; // We only cache the first 2 MB of each file\nconst PART_TIMEOUT = 60000;\n\nconst requestStates = new Map();\n\nexport async function respondForProgressive(e: FetchEvent) {\n const { url } = e.request;\n const range = e.request.headers.get('range');\n const bytes = /^bytes=(\\d+)-(\\d+)?$/g.exec(range || '')!;\n const start = Number(bytes[1]);\n const originalEnd = Number(bytes[2]);\n\n let end = originalEnd;\n if (!end || (end - start + 1) > DEFAULT_PART_SIZE) {\n end = start + DEFAULT_PART_SIZE - 1;\n }\n\n // Optimization for Safari\n if (start === 0 && end === 1) {\n const match = e.request.url.match(/fileSize=(\\d+)&mimeType=([\\w/]+)/);\n const fileSize = match && Number(match[1]);\n const mimeType = match?.[2];\n\n if (fileSize && mimeType) {\n return new Response(new Uint8Array(2).buffer, {\n status: 206,\n statusText: 'Partial Content',\n headers: [\n ['Content-Range', `bytes 0-1/${fileSize}`],\n ['Accept-Ranges', 'bytes'],\n ['Content-Length', '2'],\n ['Content-Type', mimeType],\n ],\n });\n }\n }\n\n const cacheKey = `${url}?start=${start}&end=${end}`;\n const [cachedArrayBuffer, cachedHeaders] = !MEDIA_PROGRESSIVE_CACHE_DISABLED ? await fetchFromCache(cacheKey) : [];\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log(\n `FETCH PROGRESSIVE ${cacheKey} (request: ${start}-${originalEnd}) CACHED: ${Boolean(cachedArrayBuffer)}`,\n );\n }\n\n if (cachedArrayBuffer) {\n return new Response(cachedArrayBuffer, {\n status: 206,\n statusText: 'Partial Content',\n headers: cachedHeaders,\n });\n }\n\n let partInfo;\n try {\n partInfo = await requestPart(e, { url, start, end });\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('FETCH PROGRESSIVE', err);\n }\n }\n\n if (!partInfo) {\n return new Response('', {\n status: 500,\n statusText: 'Failed to fetch progressive part',\n });\n }\n\n const { arrayBuffer, fullSize, mimeType } = partInfo;\n\n const partSize = Math.min(end - start + 1, arrayBuffer.byteLength);\n end = start + partSize - 1;\n const arrayBufferPart = arrayBuffer.slice(0, partSize);\n const headers = [\n ['Content-Range', `bytes ${start}-${end}/${fullSize}`],\n ['Accept-Ranges', 'bytes'],\n ['Content-Length', String(partSize)],\n ['Content-Type', mimeType],\n ];\n\n if (!MEDIA_PROGRESSIVE_CACHE_DISABLED && partSize <= MEDIA_CACHE_MAX_BYTES && end < MAX_END_TO_CACHE) {\n saveToCache(cacheKey, arrayBufferPart, headers);\n }\n\n return new Response(arrayBufferPart, {\n status: 206,\n statusText: 'Partial Content',\n headers,\n });\n}\n\n// We can not cache 206 responses: https://github.com/GoogleChrome/workbox/issues/1644#issuecomment-638741359\nasync function fetchFromCache(cacheKey: string) {\n const cache = await self.caches.open(MEDIA_PROGRESSIVE_CACHE_NAME);\n\n return Promise.all([\n cache.match(`${cacheKey}&type=arrayBuffer`).then((r) => (r ? r.arrayBuffer() : undefined)),\n cache.match(`${cacheKey}&type=headers`).then((r) => (r ? r.json() : undefined)),\n ]);\n}\n\nasync function saveToCache(cacheKey: string, arrayBuffer: ArrayBuffer, headers: HeadersInit) {\n const cache = await self.caches.open(MEDIA_PROGRESSIVE_CACHE_NAME);\n\n return Promise.all([\n cache.put(new Request(`${cacheKey}&type=arrayBuffer`), new Response(arrayBuffer)),\n cache.put(new Request(`${cacheKey}&type=headers`), new Response(JSON.stringify(headers))),\n ]);\n}\n\nasync function requestPart(\n e: FetchEvent,\n params: { url: string; start: number; end: number },\n): Promise {\n if (!e.clientId) {\n return undefined;\n }\n\n // eslint-disable-next-line no-restricted-globals\n const client = await self.clients.get(e.clientId);\n if (!client) {\n return undefined;\n }\n\n const messageId = generateIdFor(requestStates);\n const requestState = {} as RequestStates;\n\n const promise = Promise.race([\n pause(PART_TIMEOUT).then(() => Promise.reject(new Error('ERROR_PART_TIMEOUT'))),\n new Promise((resolve, reject) => {\n Object.assign(requestState, { resolve, reject });\n }),\n ]);\n\n requestStates.set(messageId, requestState);\n promise\n .catch(() => undefined)\n .finally(() => {\n requestStates.delete(messageId);\n });\n\n client.postMessage({\n type: 'requestPart',\n messageId,\n params,\n });\n\n return promise;\n}\n\nself.addEventListener('message', (e) => {\n const { type, messageId, result } = e.data as {\n type: string;\n messageId: string;\n result: PartInfo;\n };\n\n if (type === 'partResponse') {\n const requestState = requestStates.get(messageId);\n if (requestState) {\n requestState.resolve(result);\n }\n }\n});\n","import { ASSET_CACHE_NAME } from '../config';\nimport { pause } from '../util/schedulers';\n\ndeclare const self: ServiceWorkerGlobalScope;\n\n// An attempt to fix freezing UI on iOS\nconst CACHE_TIMEOUT = 3000;\n\nexport async function respondWithCache(e: FetchEvent) {\n const cacheResult = await withTimeout(async () => {\n const cache = await self.caches.open(ASSET_CACHE_NAME);\n const cached = await cache.match(e.request);\n\n return { cache, cached };\n }, CACHE_TIMEOUT);\n\n const { cache, cached } = cacheResult || {};\n\n if (cache && cached) {\n if (cached.ok) {\n return cached;\n } else {\n await cache.delete(e.request);\n }\n }\n\n const remote = await fetch(e.request);\n\n if (remote.ok && cache) {\n cache.put(e.request, remote.clone());\n }\n\n return remote;\n}\n\nasync function withTimeout(cb: () => Promise, timeout: number) {\n try {\n return await Promise.race([\n pause(timeout).then(() => Promise.reject(new Error('TIMEOUT'))),\n cb(),\n ]);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(err);\n return undefined;\n }\n}\n\nexport function clearAssetCache() {\n return self.caches.delete(ASSET_CACHE_NAME);\n}\n","import { APP_NAME, DEBUG } from '../config';\n\ndeclare const self: ServiceWorkerGlobalScope;\n\nenum Boolean {\n True = '1',\n False = '0',\n}\n\ntype PushData = {\n custom: {\n msg_id?: string;\n channel_id?: string;\n chat_id?: string;\n from_id?: string;\n };\n mute: Boolean;\n badge: Boolean;\n loc_key: string;\n loc_args: string[];\n random_id: number;\n title: string;\n description: string;\n};\n\ntype NotificationData = {\n messageId?: number;\n chatId?: string;\n title: string;\n body: string;\n icon?: string;\n};\n\ntype CloseNotificationData = {\n lastReadInboxMessageId?: number;\n chatId: string;\n};\n\nlet lastSyncAt = new Date().valueOf();\nconst shownNotifications = new Set();\nconst clickBuffer: Record = {};\n\nfunction getPushData(e: PushEvent | Notification): PushData | undefined {\n try {\n return e.data.json();\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[SW] Unable to parse push notification data', e.data);\n }\n return undefined;\n }\n}\n\nfunction getChatId(data: PushData) {\n if (data.custom.from_id) {\n return data.custom.from_id;\n }\n\n // Chats and channels have “negative” IDs\n if (data.custom.chat_id || data.custom.channel_id) {\n return `-${data.custom.chat_id || data.custom.channel_id}`;\n }\n\n return undefined;\n}\n\nfunction getMessageId(data: PushData) {\n if (!data.custom.msg_id) return undefined;\n return parseInt(data.custom.msg_id, 10);\n}\n\nfunction getNotificationData(data: PushData): NotificationData {\n return {\n chatId: getChatId(data),\n messageId: getMessageId(data),\n title: data.title || APP_NAME,\n body: data.description,\n };\n}\n\nasync function getClients() {\n const appUrl = new URL(self.registration.scope).origin;\n const clients = await self.clients.matchAll({ type: 'window' }) as WindowClient[];\n return clients.filter((client) => {\n return new URL(client.url).origin === appUrl;\n });\n}\n\nasync function playNotificationSound(id: string) {\n const clients = await getClients();\n const client = clients[0];\n if (!client) return;\n client.postMessage({\n type: 'playNotificationSound',\n payload: { id },\n });\n}\n\nfunction showNotification({\n chatId,\n messageId,\n body,\n title,\n icon,\n}: NotificationData) {\n const isFirstBatch = new Date().valueOf() - lastSyncAt < 1000;\n const tag = String(isFirstBatch ? 0 : chatId || 0);\n const options: NotificationOptions = {\n body,\n data: {\n chatId,\n messageId,\n count: 1,\n },\n icon: icon || 'icon-192x192.png',\n badge: 'icon-192x192.png',\n tag,\n vibrate: [200, 100, 200],\n };\n\n return Promise.all([\n playNotificationSound(String(messageId) || chatId || ''),\n self.registration.showNotification(title, options),\n ]);\n}\n\nasync function closeNotifications({\n chatId,\n lastReadInboxMessageId,\n}: CloseNotificationData) {\n const notifications = await self.registration.getNotifications();\n const lastMessageId = lastReadInboxMessageId || Number.MAX_VALUE;\n notifications.forEach((notification) => {\n if (\n notification.tag === '0'\n || (notification.data.chatId === chatId && notification.data.messageId <= lastMessageId)\n ) {\n notification.close();\n }\n });\n}\n\nexport function handlePush(e: PushEvent) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[SW] Push received event', e);\n if (e.data) {\n // eslint-disable-next-line no-console\n console.log('[SW] Push received with data', e.data.json());\n }\n }\n\n const data = getPushData(e);\n\n // Do not show muted notifications\n if (!data || data.mute === Boolean.True) return;\n\n const notification = getNotificationData(data);\n\n // Dont show already triggered notification\n if (shownNotifications.has(notification.messageId)) {\n shownNotifications.delete(notification.messageId);\n return;\n }\n\n e.waitUntil(showNotification(notification));\n}\n\nasync function focusChatMessage(client: WindowClient, data: { chatId?: string; messageId?: number }) {\n const {\n chatId,\n messageId,\n } = data;\n if (!chatId) return;\n client.postMessage({\n type: 'focusMessage',\n payload: {\n chatId,\n messageId,\n },\n });\n if (!client.focused) {\n // Catch \"focus not allowed\" DOM Exceptions\n try {\n await client.focus();\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('[SW] ', error);\n }\n }\n }\n}\n\nexport function handleNotificationClick(e: NotificationEvent) {\n const appUrl = self.registration.scope;\n e.notification.close(); // Android needs explicit close.\n const { data } = e.notification;\n const notifyClients = async () => {\n const clients = await getClients();\n await Promise.all(clients.map((client) => {\n clickBuffer[client.id] = data;\n return focusChatMessage(client, data);\n }));\n if (!self.clients.openWindow || clients.length > 0) return undefined;\n // Store notification data for default client (fix for android)\n clickBuffer[0] = data;\n // If there is no opened client we need to open one and wait until it is fully loaded\n try {\n const newClient = await self.clients.openWindow(appUrl);\n if (newClient) {\n // Store notification data until client is fully loaded\n clickBuffer[newClient.id] = data;\n }\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('[SW] ', error);\n }\n }\n return undefined;\n };\n e.waitUntil(notifyClients());\n}\n\nexport function handleClientMessage(e: ExtendableMessageEvent) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[SW] New message from client', e);\n }\n if (!e.data) return;\n const source = e.source as WindowClient;\n if (e.data.type === 'clientReady') {\n // focus on chat message when client is fully ready\n const data = clickBuffer[source.id] || clickBuffer[0];\n if (data) {\n delete clickBuffer[source.id];\n delete clickBuffer[0];\n e.waitUntil(focusChatMessage(source, data));\n }\n }\n if (e.data.type === 'newMessageNotification') {\n // store messageId for already shown notification\n const notification: NotificationData = e.data.payload;\n // mark this notification as shown if it was handled locally\n shownNotifications.add(notification.messageId);\n e.waitUntil(showNotification(notification));\n }\n\n if (e.data.type === 'closeMessageNotifications') {\n e.waitUntil(closeNotifications(e.data.payload));\n }\n}\n\nself.onsync = () => {\n lastSyncAt = new Date().valueOf();\n};\n","import { DEBUG } from './config';\nimport { respondForProgressive } from './serviceWorker/progressive';\nimport { respondWithCache, clearAssetCache } from './serviceWorker/assetCache';\nimport { handlePush, handleNotificationClick, handleClientMessage } from './serviceWorker/pushNotification';\nimport { pause } from './util/schedulers';\n\ndeclare const self: ServiceWorkerGlobalScope;\n\nconst ASSET_CACHE_PATTERN = /[0-9a-f]{20}.*\\.(js|css|woff2?|svg|png|jpg|jpeg|json|wasm)$/;\nconst ACTIVATE_TIMEOUT = 3000;\n\nself.addEventListener('install', (e) => {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('ServiceWorker installed');\n }\n\n // Activate worker immediately\n e.waitUntil(self.skipWaiting());\n});\n\nself.addEventListener('activate', (e) => {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('ServiceWorker activated');\n }\n\n e.waitUntil(\n Promise.race([\n // An attempt to fix freezing UI on iOS\n pause(ACTIVATE_TIMEOUT),\n Promise.all([\n clearAssetCache(),\n // Become available to all pages\n self.clients.claim(),\n ]),\n ]),\n );\n});\n\n// eslint-disable-next-line no-restricted-globals\nself.addEventListener('fetch', (e: FetchEvent) => {\n const { url } = e.request;\n\n if (url.includes('/progressive/')) {\n e.respondWith(respondForProgressive(e));\n return true;\n }\n\n if (url.startsWith('http') && url.match(ASSET_CACHE_PATTERN)) {\n e.respondWith(respondWithCache(e));\n return true;\n }\n\n return false;\n});\n\nself.addEventListener('push', handlePush);\nself.addEventListener('notificationclick', handleNotificationClick);\nself.addEventListener('message', handleClientMessage);\n","export default (store: AnyLiteral) => {\n let id;\n\n do {\n id = String(Math.random()).replace('0.', 'id');\n } while (store.hasOwnProperty(id));\n\n return id;\n};\n"],"names":["MEDIA_PROGRESSIVE_CACHE_NAME","ASSET_CACHE_NAME","SUPPORTED_IMAGE_CONTENT_TYPES","window","innerHeight","Math","round","Set","SUPPORTED_VIDEO_CONTENT_TYPES","pause","ms","Promise","resolve","setTimeout","DEFAULT_PART_SIZE","requestStates","Map","async","respondWithCache","e","cacheResult","cb","timeout","race","then","reject","Error","cache","self","caches","open","cached","match","request","err","console","error","withTimeout","ok","delete","remote","fetch","put","clone","Boolean","addEventListener","type","messageId","result","data","requestState","get","lastSyncAt","Date","valueOf","shownNotifications","clickBuffer","getChatId","custom","from_id","chat_id","channel_id","getMessageId","msg_id","parseInt","getClients","appUrl","URL","registration","scope","origin","clients","matchAll","filter","client","url","playNotificationSound","id","postMessage","payload","showNotification","chatId","body","title","icon","isFirstBatch","options","count","badge","tag","String","vibrate","all","focusChatMessage","focused","focus","onsync","ASSET_CACHE_PATTERN","waitUntil","skipWaiting","claim","includes","respondWith","range","headers","bytes","exec","start","Number","end","fileSize","mimeType","Response","Uint8Array","buffer","status","statusText","cacheKey","cachedArrayBuffer","cachedHeaders","r","arrayBuffer","undefined","json","fetchFromCache","partInfo","params","clientId","store","random","replace","hasOwnProperty","generateIdFor","promise","Object","assign","set","catch","finally","requestPart","fullSize","partSize","min","byteLength","arrayBufferPart","slice","Request","JSON","stringify","saveToCache","respondForProgressive","startsWith","getPushData","mute","True","notification","process","description","getNotificationData","has","close","map","openWindow","length","newClient","notifyClients","source","add","lastReadInboxMessageId","notifications","getNotifications","lastMessageId","MAX_VALUE","forEach","closeNotifications"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/index.html b/dist/index.html index fd07209a..446ad5aa 100644 --- a/dist/index.html +++ b/dist/index.html @@ -1 +1 @@ -Telegram
\ No newline at end of file +Telegram
\ No newline at end of file diff --git a/dist/main.385008a5f5d046ca97cd.js.map b/dist/main.385008a5f5d046ca97cd.js.map deleted file mode 100644 index 3aae7ba3..00000000 --- a/dist/main.385008a5f5d046ca97cd.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"main.385008a5f5d046ca97cd.js","mappings":"uBACIA,EADAC,ECAAC,EACAC,ECwCAC,EASAC,E,wFChCJ,IAAIC,EACJ,MAAMC,EAAgB,IAAIC,IACpBC,EAA0B,IAAID,IAI7B,SAASE,EAAQC,EAAuBC,GAe7C,OAdKN,IACCO,EAAAA,IAEFC,QAAQC,IAAI,yBAGdT,EAAS,IAAIU,OAAO,IAAIC,IAAI,mBA6ChC,SAA2BN,GACzBL,EAAOY,iBAAiB,WAAW,EAAGC,KAAAA,MACpC,GAAkB,WAAdA,EAAKC,KACPT,EAASQ,EAAKE,aACT,GAAkB,mBAAdF,EAAKC,KAA2B,CACzC,MAAME,EAAef,EAAcgB,IAAIJ,EAAKK,WACxCF,IACEH,EAAKM,MACPH,EAAaI,OAAOP,E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Q,CAAC,gBACtC,CAAC9H,EAAWC,KAA2BC,EAAAA,EAAAA,IAAKD,EAAS,CAAC,gBAFxD,EA9C4C,EAAGoxB,UAAAA,EAAW8qD,WAAAA,MACxD,MAAOC,EAAYC,IAAgBlI,EAAAA,EAAAA,IAAQ,GAc3C,IAZAjnE,EAAAA,EAAAA,KAAU,MACRu9D,EAAAA,EAAAA,KfRF7zE,EeS6B,KACzBulF,IACAr9E,SAASX,MAAS,GAAE8Q,EAAAA,KAAaC,EAAAA,KAEjCmtE,OAED,CAACF,EAAYE,IAIZD,EACF,OAAO,mBAAC,GAAD,MAGT,GAAI/qD,EACF,OAAQA,GACN,IAAK,oCACL,IAAK,6BACL,IAAK,iCACL,IAAK,qCACL,IAAK,+BACH,OAAO,mBAAC,GAAD,MACT,IAAK,2BACL,IAAK,4BACL,IAAK,+BACL,IAAK,0BACH,OAAO6qD,KAIb,OAAOtW,EAAAA,EAAAA,KAAiB,GAAQsW,KAAe,mBAAC,GAAD,SC1C7CtmF,EAAAA,IAEFC,QAAQC,IAAI,aAGdsH,EAAAA,EAAAA,MAAcguB,OAEVx1B,EAAAA,IAEFC,QAAQC,IAAI,4BAGdwmF,EAAAA,EAAAA,OACE,mBAAC,GAAD,MACAx9E,SAAS42E,eAAe,SAGtB9/E,EAAAA,IAEFC,QAAQC,IAAI,6BAGdgJ,SAAS7I,iBAAiB,YAAY,KAEpCJ,QAAQqC,KAAK,gBAAgB2wB,EAAAA,EAAAA,W","sources":["webpack://telegram-t/webpack/runtime/create fake namespace object","webpack://telegram-t/webpack/runtime/load script","webpack://telegram-t/webpack/runtime/css loading","webpack://telegram-t/./src/api/gramjs/worker/provider.ts","webpack://telegram-t/./src/api/types/media.ts","webpack://telegram-t/./src/api/types/messages.ts","webpack://telegram-t/./src/lib/punycode.js","webpack://telegram-t/./src/components/common/SafeLink.tsx","webpack://telegram-t/./src/components/common/helpers/documentInfo.ts","webpack://telegram-t/./src/components/common/helpers/parseEmojiOnlyString.ts","webpack://telegram-t/./src/components/common/UserLink.tsx","webpack://telegram-t/./src/components/common/MessageLink.tsx","webpack://telegram-t/./src/components/common/ChatLink.tsx","webpack://telegram-t/./src/components/common/helpers/renderActionMessageText.tsx","webpack://telegram-t/./src/components/common/helpers/renderText.tsx","webpack://telegram-t/./src/components/middle/helpers/preventMessageInputBlur.ts","webpack://telegram-t/./src/components/middle/message/MentionLink.tsx","webpack://telegram-t/./src/components/ui/Button.tsx","webpack://telegram-t/./src/components/ui/Checkbox.tsx","webpack://telegram-t/./src/components/ui/DropdownMenu.tsx","webpack://telegram-t/./src/components/ui/InputText.tsx","webpack://telegram-t/./src/components/ui/Link.tsx","webpack://telegram-t/./src/components/ui/Loading.tsx","webpack://telegram-t/./src/components/ui/Menu.tsx","webpack://telegram-t/./src/components/ui/MenuItem.tsx","webpack://telegram-t/./src/components/ui/RippleEffect.tsx","webpack://telegram-t/./src/components/ui/Spinner.tsx","webpack://telegram-t/./src/config.ts","webpack://telegram-t/./src/hooks/useEffectWithPrevDeps.ts","webpack://telegram-t/./src/hooks/useFlag.ts","webpack://telegram-t/./src/hooks/useForceUpdate.ts","webpack://telegram-t/./src/hooks/useHeavyAnimationCheck.ts","webpack://telegram-t/./src/hooks/useHistoryBack.ts","webpack://telegram-t/./src/hooks/useKeyboardListNavigation.ts","webpack://telegram-t/./src/hooks/useLang.ts","webpack://telegram-t/./src/hooks/useModuleLoader.ts","webpack://telegram-t/./src/hooks/useOnChange.ts","webpack://telegram-t/./src/hooks/usePrevious.ts","webpack://telegram-t/./src/hooks/useShowTransition.ts","webpack://telegram-t/./src/hooks/useVirtualBackdrop.ts","webpack://telegram-t/./src/lib/teact/dom-events.ts","webpack://telegram-t/./src/lib/teact/teact-dom.ts","webpack://telegram-t/./src/lib/teact/teact.ts","webpack://telegram-t/./src/lib/teact/teactn.tsx","webpack://telegram-t/./src/lib/twemojiRegex.js","webpack://telegram-t/./src/modules/actions/api/initial.ts","webpack://telegram-t/./src/modules/actions/api/settings.ts","webpack://telegram-t/./src/modules/actions/apiUpdaters/initial.ts","webpack://telegram-t/./src/modules/actions/ui/initial.ts","webpack://telegram-t/./src/modules/actions/ui/settings.ts","webpack://telegram-t/./src/modules/helpers/chats.ts","webpack://telegram-t/./src/modules/helpers/messages.ts","webpack://telegram-t/./src/modules/helpers/messageMedia.ts","webpack://telegram-t/./src/modules/helpers/localSearch.ts","webpack://telegram-t/./src/modules/helpers/payments.ts","webpack://telegram-t/./src/modules/helpers/users.ts","webpack://telegram-t/./src/modules/reducers/chats.ts","webpack://telegram-t/./src/modules/reducers/messages.ts","webpack://telegram-t/./src/modules/reducers/symbols.ts","webpack://telegram-t/./src/modules/reducers/users.ts","webpack://telegram-t/./src/modules/reducers/globalSearch.ts","webpack://telegram-t/./src/modules/reducers/localSearch.ts","webpack://telegram-t/./src/modules/reducers/management.ts","webpack://telegram-t/./src/modules/reducers/settings.ts","webpack://telegram-t/./src/modules/reducers/twoFaSettings.ts","webpack://telegram-t/./src/modules/reducers/payments.ts","webpack://telegram-t/./src/modules/selectors/users.ts","webpack://telegram-t/./src/modules/selectors/settings.ts","webpack://telegram-t/./src/modules/selectors/chats.ts","webpack://telegram-t/./src/modules/selectors/symbols.ts","webpack://telegram-t/./src/modules/selectors/messages.ts","webpack://telegram-t/./src/modules/selectors/localSearch.ts","webpack://telegram-t/./src/modules/selectors/management.ts","webpack://telegram-t/./src/modules/selectors/ui.ts","webpack://telegram-t/./src/modules/selectors/globalSearch.ts","webpack://telegram-t/./src/modules/selectors/payments.ts","webpack://telegram-t/./src/types/index.ts","webpack://telegram-t/./src/util/animation.ts","webpack://telegram-t/./src/util/appBadge.ts","webpack://telegram-t/./src/util/arePropsShallowEqual.ts","webpack://telegram-t/./src/util/buildClassName.ts","webpack://telegram-t/./src/util/cacheApi.ts","webpack://telegram-t/./src/util/captureEscKeyListener.ts","webpack://telegram-t/./src/util/captureKeyboardListeners.ts","webpack://telegram-t/./src/util/dateFormat.ts","webpack://telegram-t/./src/util/emoji.ts","webpack://telegram-t/./src/util/environmentWebp.ts","webpack://telegram-t/./src/util/environmentSystemTheme.ts","webpack://telegram-t/./src/util/environment.ts","webpack://telegram-t/./src/util/files.ts","webpack://telegram-t/./src/util/formatCurrency.ts","webpack://telegram-t/./src/util/generateIdFor.ts","webpack://telegram-t/./src/util/getReadableErrorText.ts","webpack://telegram-t/./src/util/handleError.ts","webpack://telegram-t/./src/util/iteratees.ts","webpack://telegram-t/./src/util/langProvider.ts","webpack://telegram-t/./src/util/callbacks.ts","webpack://telegram-t/./src/util/oggToWav.ts","webpack://telegram-t/./src/util/mediaLoader.ts","webpack://telegram-t/./src/util/memo.ts","webpack://telegram-t/./src/util/moduleLoader.ts","webpack://telegram-t/./src/util/notifications.ts","webpack://telegram-t/./src/util/phoneNumber.ts","webpack://telegram-t/./src/util/routing.ts","webpack://telegram-t/./src/util/schedulers.ts","webpack://telegram-t/./src/util/searchWords.ts","webpack://telegram-t/./src/util/serverTime.ts","webpack://telegram-t/./node_modules/idb-keyval/dist/esm/index.js","webpack://telegram-t/./node_modules/safari-14-idb-fix/dist/esm/index.js","webpack://telegram-t/./src/util/sessions.ts","webpack://telegram-t/./src/util/switchTheme.ts","webpack://telegram-t/./src/util/textFormat.ts","webpack://telegram-t/./src/util/trimText.ts","webpack://telegram-t/./src/util/webpToPng.ts","webpack://telegram-t/./src/util/websync.ts","webpack://telegram-t/./src/util/windowSize.ts","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/publicPath","webpack://telegram-t/webpack/runtime/jsonp chunk loading","webpack://telegram-t/./src/util/setupServiceWorker.ts","webpack://telegram-t/./src/global/initial.ts","webpack://telegram-t/./src/global/cache.ts","webpack://telegram-t/./src/global/index.ts","webpack://telegram-t/./src/util/activeTabMonitor.ts","webpack://telegram-t/./src/util/fonts.ts","webpack://telegram-t/./src/components/common/UiLoader.tsx","webpack://telegram-t/./src/hooks/useLangString.ts","webpack://telegram-t/./src/components/auth/helpers/getSuggestedLanguage.ts","webpack://telegram-t/./src/components/auth/CountryCodeInput.tsx","webpack://telegram-t/./src/components/auth/AuthPhoneNumber.tsx","webpack://telegram-t/./src/components/auth/AuthCode.async.tsx","webpack://telegram-t/./src/components/auth/AuthPassword.async.tsx","webpack://telegram-t/./src/components/auth/AuthRegister.async.tsx","webpack://telegram-t/./node_modules/qr-creator/dist/qr-creator.es6.min.js","webpack://telegram-t/./src/components/auth/AuthQrCode.tsx","webpack://telegram-t/./src/components/auth/Auth.tsx","webpack://telegram-t/./src/components/main/Main.async.tsx","webpack://telegram-t/./src/components/main/AppInactive.tsx","webpack://telegram-t/./src/App.tsx","webpack://telegram-t/./src/index.tsx"],"sourcesContent":["var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__);\nvar leafPrototypes;\n// create a fake namespace object\n// mode & 1: value is a module id, require it\n// mode & 2: merge all properties of value into the ns\n// mode & 4: return value when already ns object\n// mode & 16: return value when it's Promise-like\n// mode & 8|1: behave like require\n__webpack_require__.t = function(value, mode) {\n\tif(mode & 1) value = this(value);\n\tif(mode & 8) return value;\n\tif(typeof value === 'object' && value) {\n\t\tif((mode & 4) && value.__esModule) return value;\n\t\tif((mode & 16) && typeof value.then === 'function') return value;\n\t}\n\tvar ns = Object.create(null);\n\t__webpack_require__.r(ns);\n\tvar def = {};\n\tleafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];\n\tfor(var current = mode & 2 && value; typeof current == 'object' && !~leafPrototypes.indexOf(current); current = getProto(current)) {\n\t\tObject.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key])));\n\t}\n\tdef['default'] = () => (value);\n\t__webpack_require__.d(ns, def);\n\treturn ns;\n};","var inProgress = {};\nvar dataWebpackPrefix = \"telegram-t:\";\n// loadScript function to load a script via script tag\n__webpack_require__.l = (url, done, key, chunkId) => {\n\tif(inProgress[url]) { inProgress[url].push(done); return; }\n\tvar script, needAttach;\n\tif(key !== undefined) {\n\t\tvar scripts = document.getElementsByTagName(\"script\");\n\t\tfor(var i = 0; i < scripts.length; i++) {\n\t\t\tvar s = scripts[i];\n\t\t\tif(s.getAttribute(\"src\") == url || s.getAttribute(\"data-webpack\") == dataWebpackPrefix + key) { script = s; break; }\n\t\t}\n\t}\n\tif(!script) {\n\t\tneedAttach = true;\n\t\tscript = document.createElement('script');\n\n\t\tscript.charset = 'utf-8';\n\t\tscript.timeout = 120;\n\t\tif (__webpack_require__.nc) {\n\t\t\tscript.setAttribute(\"nonce\", __webpack_require__.nc);\n\t\t}\n\t\tscript.setAttribute(\"data-webpack\", dataWebpackPrefix + key);\n\t\tscript.src = url;\n\t}\n\tinProgress[url] = [done];\n\tvar onScriptComplete = (prev, event) => {\n\t\t// avoid mem leaks in IE.\n\t\tscript.onerror = script.onload = null;\n\t\tclearTimeout(timeout);\n\t\tvar doneFns = inProgress[url];\n\t\tdelete inProgress[url];\n\t\tscript.parentNode && script.parentNode.removeChild(script);\n\t\tdoneFns && doneFns.forEach((fn) => (fn(event)));\n\t\tif(prev) return prev(event);\n\t}\n\t;\n\tvar timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), 120000);\n\tscript.onerror = onScriptComplete.bind(null, script.onerror);\n\tscript.onload = onScriptComplete.bind(null, script.onload);\n\tneedAttach && document.head.appendChild(script);\n};","var createStylesheet = (chunkId, fullhref, resolve, reject) => {\n\tvar linkTag = document.createElement(\"link\");\n\n\tlinkTag.rel = \"stylesheet\";\n\tlinkTag.type = \"text/css\";\n\tvar onLinkComplete = (event) => {\n\t\t// avoid mem leaks.\n\t\tlinkTag.onerror = linkTag.onload = null;\n\t\tif (event.type === 'load') {\n\t\t\tresolve();\n\t\t} else {\n\t\t\tvar errorType = event && (event.type === 'load' ? 'missing' : event.type);\n\t\t\tvar realHref = event && event.target && event.target.href || fullhref;\n\t\t\tvar err = new Error(\"Loading CSS chunk \" + chunkId + \" failed.\\n(\" + realHref + \")\");\n\t\t\terr.code = \"CSS_CHUNK_LOAD_FAILED\";\n\t\t\terr.type = errorType;\n\t\t\terr.request = realHref;\n\t\t\tlinkTag.parentNode.removeChild(linkTag)\n\t\t\treject(err);\n\t\t}\n\t}\n\tlinkTag.onerror = linkTag.onload = onLinkComplete;\n\tlinkTag.href = fullhref;\n\n\tdocument.head.appendChild(linkTag);\n\treturn linkTag;\n};\nvar findStylesheet = (href, fullhref) => {\n\tvar existingLinkTags = document.getElementsByTagName(\"link\");\n\tfor(var i = 0; i < existingLinkTags.length; i++) {\n\t\tvar tag = existingLinkTags[i];\n\t\tvar dataHref = tag.getAttribute(\"data-href\") || tag.getAttribute(\"href\");\n\t\tif(tag.rel === \"stylesheet\" && (dataHref === href || dataHref === fullhref)) return tag;\n\t}\n\tvar existingStyleTags = document.getElementsByTagName(\"style\");\n\tfor(var i = 0; i < existingStyleTags.length; i++) {\n\t\tvar tag = existingStyleTags[i];\n\t\tvar dataHref = tag.getAttribute(\"data-href\");\n\t\tif(dataHref === href || dataHref === fullhref) return tag;\n\t}\n};\nvar loadStylesheet = (chunkId) => {\n\treturn new Promise((resolve, reject) => {\n\t\tvar href = __webpack_require__.miniCssF(chunkId);\n\t\tvar fullhref = __webpack_require__.p + href;\n\t\tif(findStylesheet(href, fullhref)) return resolve();\n\t\tcreateStylesheet(chunkId, fullhref, resolve, reject);\n\t});\n}\n// object to store loaded CSS chunks\nvar installedCssChunks = {\n\t179: 0\n};\n\n__webpack_require__.f.miniCss = (chunkId, promises) => {\n\tvar cssChunks = {\"133\":1,\"306\":1,\"325\":1,\"472\":1,\"701\":1};\n\tif(installedCssChunks[chunkId]) promises.push(installedCssChunks[chunkId]);\n\telse if(installedCssChunks[chunkId] !== 0 && cssChunks[chunkId]) {\n\t\tpromises.push(installedCssChunks[chunkId] = loadStylesheet(chunkId).then(() => {\n\t\t\tinstalledCssChunks[chunkId] = 0;\n\t\t}, (e) => {\n\t\t\tdelete installedCssChunks[chunkId];\n\t\t\tthrow e;\n\t\t}));\n\t}\n};\n\n// no hmr","import { ApiInitialArgs, ApiOnProgress, OnApiUpdate } from '../../types';\nimport { Methods, MethodArgs, MethodResponse } from '../methods/types';\nimport { WorkerMessageEvent, ThenArg, OriginRequest } from './types';\n\nimport { DEBUG } from '../../../config';\nimport generateIdFor from '../../../util/generateIdFor';\nimport { pause } from '../../../util/schedulers';\n\ntype RequestStates = {\n messageId: string;\n resolve: Function;\n reject: Function;\n callback?: AnyToVoidFunction;\n};\n\nconst HEALTH_CHECK_TIMEOUT = 150;\nconst HEALTH_CHECK_MIN_DELAY = 5 * 1000; // 5 sec\n\nlet worker: Worker;\nconst requestStates = new Map();\nconst requestStatesByCallback = new Map();\n\n// TODO Re-use `util/WorkerConnector.ts`\n\nexport function initApi(onUpdate: OnApiUpdate, initialArgs: ApiInitialArgs) {\n if (!worker) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START LOAD WORKER');\n }\n\n worker = new Worker(new URL('./worker.ts', import.meta.url));\n subscribeToWorker(onUpdate);\n\n if (initialArgs.platform === 'iOS') {\n setupIosHealthCheck();\n }\n }\n\n return makeRequest({\n type: 'initApi',\n args: [initialArgs],\n });\n}\n\nexport function callApi(fnName: T, ...args: MethodArgs) {\n if (!worker) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('API is not initialized');\n }\n\n return undefined;\n }\n\n return makeRequest({\n type: 'callMethod',\n name: fnName,\n args,\n }) as MethodResponse;\n}\n\nexport function cancelApiProgress(progressCallback: ApiOnProgress) {\n progressCallback.isCanceled = true;\n\n const { messageId } = requestStatesByCallback.get(progressCallback) || {};\n if (!messageId) {\n return;\n }\n\n worker.postMessage({\n type: 'cancelProgress',\n messageId,\n });\n}\n\nfunction subscribeToWorker(onUpdate: OnApiUpdate) {\n worker.addEventListener('message', ({ data }: WorkerMessageEvent) => {\n if (data.type === 'update') {\n onUpdate(data.update);\n } else if (data.type === 'methodResponse') {\n const requestState = requestStates.get(data.messageId);\n if (requestState) {\n if (data.error) {\n requestState.reject(data.error);\n } else {\n requestState.resolve(data.response);\n }\n }\n } else if (data.type === 'methodCallback') {\n requestStates.get(data.messageId)?.callback?.(...data.callbackArgs);\n } else if (data.type === 'unhandledError') {\n throw data.error;\n }\n });\n}\n\nfunction makeRequest(message: OriginRequest) {\n const messageId = generateIdFor(requestStates);\n const payload: OriginRequest = {\n messageId,\n ...message,\n };\n\n const requestState = { messageId } as RequestStates;\n\n // Re-wrap type because of `postMessage`\n const promise: Promise>> = new Promise((resolve, reject) => {\n Object.assign(requestState, { resolve, reject });\n });\n\n if (('args' in payload) && typeof payload.args[1] === 'function') {\n const callback = payload.args.pop() as AnyToVoidFunction;\n requestState.callback = callback;\n requestStatesByCallback.set(callback, requestState);\n }\n\n requestStates.set(messageId, requestState);\n promise\n .catch(() => undefined)\n .finally(() => {\n requestStates.delete(messageId);\n\n if (requestState.callback) {\n requestStatesByCallback.delete(requestState.callback);\n }\n });\n\n worker.postMessage(payload);\n\n return promise;\n}\n\nconst startedAt = Date.now();\n\n// Workaround for iOS sometimes stops interacting with worker\nfunction setupIosHealthCheck() {\n window.addEventListener('focus', async () => {\n try {\n await Promise.race([\n makeRequest({ type: 'ping' }),\n pause(HEALTH_CHECK_TIMEOUT).then(() => Promise.reject(new Error('HEALTH_CHECK_TIMEOUT'))),\n ]);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(err);\n\n if (Date.now() - startedAt >= HEALTH_CHECK_MIN_DELAY) {\n window.location.reload();\n }\n }\n });\n}\n","// We cache avatars as Data URI for faster initial load\n// and messages media as Blob for smaller size.\n\nexport enum ApiMediaFormat {\n BlobUrl,\n Lottie,\n Progressive,\n Stream,\n}\n\nexport type ApiParsedMedia = string | Blob | AnyLiteral | ArrayBuffer;\nexport type ApiPreparedMedia = string | AnyLiteral;\nexport type ApiMediaFormatToPrepared = T extends ApiMediaFormat.Lottie ? AnyLiteral : string;\n","export interface ApiDimensions {\n width: number;\n height: number;\n}\n\nexport interface ApiPhotoSize extends ApiDimensions {\n type: 's' | 'm' | 'x' | 'y' | 'z';\n}\n\nexport interface ApiThumbnail extends ApiDimensions {\n dataUri: string;\n}\n\nexport interface ApiPhoto {\n id: string;\n thumbnail?: ApiThumbnail;\n sizes: ApiPhotoSize[];\n blobUrl?: string;\n}\n\nexport interface ApiSticker {\n id: string;\n stickerSetId: string;\n stickerSetAccessHash?: string;\n emoji?: string;\n isAnimated: boolean;\n width?: number;\n height?: number;\n thumbnail?: ApiThumbnail;\n isPreloadedGlobally?: boolean;\n}\n\nexport interface ApiStickerSet {\n archived?: true;\n isAnimated?: true;\n installedDate?: number;\n id: string;\n accessHash: string;\n title: string;\n hasThumbnail?: boolean;\n count: number;\n stickers?: ApiSticker[];\n packs?: Record;\n covers?: ApiSticker[];\n shortName: string;\n}\n\nexport interface ApiVideo {\n id: string;\n mimeType: string;\n duration: number;\n fileName: string;\n width?: number;\n height?: number;\n supportsStreaming?: boolean;\n isRound?: boolean;\n isGif?: boolean;\n thumbnail?: ApiThumbnail;\n blobUrl?: string;\n size: number;\n}\n\nexport interface ApiAudio {\n 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 duration: number;\n waveform?: number[];\n}\n\nexport interface ApiDocument {\n id?: string;\n fileName: string;\n size: number;\n timestamp?: number;\n mimeType: string;\n thumbnail?: ApiThumbnail;\n previewBlobUrl?: string;\n mediaType?: 'photo' | 'video';\n mediaSize?: ApiDimensions;\n}\n\nexport interface ApiContact {\n firstName: string;\n lastName: string;\n phoneNumber: string;\n userId: string;\n}\n\nexport interface ApiPollAnswer {\n text: string;\n option: string;\n}\n\nexport interface ApiPollResult {\n isChosen?: true;\n isCorrect?: true;\n option: string;\n votersCount: number;\n}\n\nexport interface ApiPoll {\n id: string;\n summary: {\n closed?: true;\n isPublic?: true;\n multipleChoice?: true;\n quiz?: true;\n question: string;\n answers: ApiPollAnswer[];\n closePeriod?: number;\n closeDate?: number;\n };\n results: {\n results?: ApiPollResult[];\n totalVoters?: number;\n recentVoterIds?: string[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n}\n\nexport interface ApiInvoice {\n text: string;\n title: string;\n photoUrl?: string;\n amount: number;\n currency: string;\n receiptMsgId?: number;\n isTest?: boolean;\n}\n\nexport type ApiNewPoll = {\n summary: ApiPoll['summary'];\n quiz?: {\n correctAnswers: string[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n};\n\nexport interface ApiAction {\n text: string;\n targetUserIds?: string[];\n targetChatId?: string;\n type: 'historyClear' | 'contactSignUp' | 'chatCreate' | 'other';\n photo?: ApiPhoto;\n amount?: number;\n currency?: string;\n translationValues: string[];\n}\n\nexport interface ApiWebPage {\n id: number;\n url: string;\n displayUrl: string;\n type?: string;\n siteName?: string;\n title?: string;\n description?: string;\n photo?: ApiPhoto;\n duration?: number;\n document?: ApiDocument;\n video?: ApiVideo;\n}\n\nexport interface ApiMessageForwardInfo {\n isChannelPost: boolean;\n channelPostId?: number;\n isLinkedChannelPost?: boolean;\n fromChatId?: string;\n senderUserId?: string;\n fromMessageId?: number;\n hiddenUserName?: string;\n adminTitle?: string;\n}\n\nexport interface ApiMessageEntity {\n type: string;\n offset: number;\n length: number;\n userId?: string;\n url?: string;\n}\n\nexport enum ApiMessageEntityTypes {\n Bold = 'MessageEntityBold',\n Blockquote = 'MessageEntityBlockquote',\n BotCommand = 'MessageEntityBotCommand',\n Cashtag = 'MessageEntityCashtag',\n Code = 'MessageEntityCode',\n Email = 'MessageEntityEmail',\n Hashtag = 'MessageEntityHashtag',\n Italic = 'MessageEntityItalic',\n MentionName = 'MessageEntityMentionName',\n Mention = 'MessageEntityMention',\n Phone = 'MessageEntityPhone',\n Pre = 'MessageEntityPre',\n Strike = 'MessageEntityStrike',\n TextUrl = 'MessageEntityTextUrl',\n Url = 'MessageEntityUrl',\n Underline = 'MessageEntityUnderline',\n Unknown = 'MessageEntityUnknown',\n}\n\nexport interface ApiFormattedText {\n text: string;\n entities?: ApiMessageEntity[];\n}\n\nexport interface ApiMessage {\n id: number;\n chatId: string;\n content: {\n text?: ApiFormattedText;\n photo?: ApiPhoto;\n video?: ApiVideo;\n document?: ApiDocument;\n sticker?: ApiSticker;\n contact?: ApiContact;\n poll?: ApiPoll;\n action?: ApiAction;\n webPage?: ApiWebPage;\n audio?: ApiAudio;\n voice?: ApiVoice;\n invoice?: ApiInvoice;\n };\n date: number;\n isOutgoing: boolean;\n senderId?: string;\n replyToChatId?: string;\n replyToMessageId?: number;\n replyToTopMessageId?: number;\n sendingState?: 'messageSendingStatePending' | 'messageSendingStateFailed';\n forwardInfo?: ApiMessageForwardInfo;\n isDeleting?: boolean;\n previousLocalId?: number;\n views?: number;\n isEdited?: boolean;\n 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}\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 interface ApiKeyboardButton {\n type: 'command' | 'url' | 'callback' | 'requestPoll' | 'buy' | 'NOT_SUPPORTED';\n text: string;\n messageId: number;\n value?: string;\n}\n\nexport type ApiKeyboardButtons = ApiKeyboardButton[][];\nexport type ApiReplyKeyboard = {\n keyboardPlaceholder?: string;\n isKeyboardSingleUse?: boolean;\n} & {\n [K in 'inlineButtons' | 'keyboardButtons']?: ApiKeyboardButtons;\n};\n\nexport type ApiMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'voice' | 'profilePhoto';\nexport type ApiGlobalMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'voice';\n\nexport type ApiReportReason = 'spam' | 'violence' | 'pornography' | 'childAbuse'\n| 'copyright' | 'geoIrrelevant' | 'fake' | 'other';\n\nexport const MAIN_THREAD_ID = -1;\n\n// `Symbol` can not be transferred from worker\nexport const MESSAGE_DELETED = 'MESSAGE_DELETED';\n","/* eslint-disable no-nested-ternary */\n/* eslint-disable no-bitwise */\n\nconst utf16 = {\n // The utf16-class is necessary to convert from javascripts internal character representation to unicode and back.\n decode: (input) => {\n const output = [];\n let i = 0;\n const len = input.length;\n let value;\n let extra;\n\n while (i < len) {\n value = input.charCodeAt(i++);\n if ((value & 0xf800) === 0xd800) {\n extra = input.charCodeAt(i++);\n if ((value & 0xfc00) !== 0xd800 || (extra & 0xfc00) !== 0xdc00) {\n throw new RangeError('UTF-16(decode): Illegal UTF-16 sequence');\n }\n value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;\n }\n output.push(value);\n }\n return output;\n },\n encode: (input) => {\n const output = [];\n let i = 0;\n const len = input.length;\n let value;\n\n while (i < len) {\n value = input[i++];\n if ((value & 0xf800) === 0xd800) {\n throw new RangeError('UTF-16(encode): Illegal UTF-16 value');\n }\n if (value > 0xffff) {\n value -= 0x10000;\n output.push(String.fromCharCode(((value >>> 10) & 0x3ff) | 0xd800));\n value = 0xdc00 | (value & 0x3ff);\n }\n output.push(String.fromCharCode(value));\n }\n return output.join('');\n },\n};\n\n// Default parameters\nconst initial_n = 0x80;\nconst initial_bias = 72;\nconst delimiter = '\\x2D';\nconst base = 36;\nconst damp = 700;\nconst tmin = 1;\nconst tmax = 26;\nconst skew = 38;\nconst maxint = 0x7fffffff;\n\n// decode_digit(cp) returns the numeric value of a basic code\n// point (for use in representing integers) in the range 0 to\n// base-1, or base if cp is does not represent a value.\n\nfunction decode_digit(cp) {\n return cp - 48 < 10 ? cp - 22 : cp - 65 < 26 ? cp - 65 : cp - 97 < 26 ? cp - 97 : base;\n}\n\n// ** Bias adaptation function **\nfunction adapt(delta, numpoints, firsttime) {\n let k;\n delta = firsttime ? Math.floor(delta / damp) : delta >> 1;\n delta += Math.floor(delta / numpoints);\n\n for (k = 0; delta > ((base - tmin) * tmax) >> 1; k += base) {\n delta = Math.floor(delta / (base - tmin));\n }\n return Math.floor(k + ((base - tmin + 1) * delta) / (delta + skew));\n}\n\n// Main decode\nfunction decode(input, preserveCase) {\n // Dont use utf16\n const output = [];\n const case_flags = [];\n const input_length = input.length;\n\n let n; let out; let i; let bias; let basic; let j; let ic; let oldi; let w; let k; let digit; let t; let len;\n\n // Initialize the state:\n\n n = initial_n;\n i = 0;\n bias = initial_bias;\n\n // Handle the basic code points: Let basic be the number of input code\n // points before the last delimiter, or 0 if there is none, then\n // copy the first basic code points to the output.\n\n basic = input.lastIndexOf(delimiter);\n if (basic < 0) basic = 0;\n\n for (j = 0; j < basic; ++j) {\n if (preserveCase) case_flags[output.length] = input.charCodeAt(j) - 65 < 26;\n if (input.charCodeAt(j) >= 0x80) {\n throw new RangeError('Illegal input >= 0x80');\n }\n output.push(input.charCodeAt(j));\n }\n\n // Main decoding loop: Start just after the last delimiter if any\n // basic code points were copied; start at the beginning otherwise.\n\n for (ic = basic > 0 ? basic + 1 : 0; ic < input_length;) {\n // ic is the index of the next character to be consumed,\n\n // Decode a generalized variable-length integer into delta,\n // which gets added to i. The overflow checking is easier\n // if we increase i as we go, then subtract off its starting\n // value at the end to obtain delta.\n for (oldi = i, w = 1, k = base; ; k += base) {\n if (ic >= input_length) {\n throw RangeError('punycode_bad_input(1)');\n }\n digit = decode_digit(input.charCodeAt(ic++));\n\n if (digit >= base) {\n throw RangeError('punycode_bad_input(2)');\n }\n if (digit > Math.floor((maxint - i) / w)) {\n throw RangeError('punycode_overflow(1)');\n }\n i += digit * w;\n t = k <= bias ? tmin : k >= bias + tmax ? tmax : k - bias;\n if (digit < t) {\n break;\n }\n if (w > Math.floor(maxint / (base - t))) {\n throw RangeError('punycode_overflow(2)');\n }\n w *= base - t;\n }\n\n out = output.length + 1;\n bias = adapt(i - oldi, out, oldi === 0);\n\n // i was supposed to wrap around from out to 0,\n // incrementing n each time, so we'll fix that now:\n if (Math.floor(i / out) > maxint - n) {\n throw RangeError('punycode_overflow(3)');\n }\n n += Math.floor(i / out);\n i %= out;\n\n // Insert n at position i of the output:\n // Case of last character determines uppercase flag:\n if (preserveCase) {\n case_flags.splice(i, 0, input.charCodeAt(ic - 1) - 65 < 26);\n }\n\n output.splice(i, 0, n);\n i++;\n }\n if (preserveCase) {\n for (i = 0, len = output.length; i < len; i++) {\n if (case_flags[i]) {\n output[i] = String.fromCharCode(output[i])\n .toUpperCase()\n .charCodeAt(0);\n }\n }\n }\n return utf16.encode(output);\n}\n\nfunction toUnicode(domain) {\n const domain_array = domain.split('.');\n const out = [];\n for (let i = 0; i < domain_array.length; ++i) {\n const s = domain_array[i];\n out.push(s.match(/^xn--/) ? decode(s.slice(4)) : s);\n }\n return out.join('.');\n}\n\nexport default toUnicode;\n","import React, { FC, memo, useCallback } from '../../lib/teact/teact';\nimport { getDispatch } from '../../lib/teact/teactn';\nimport convertPunycode from '../../lib/punycode';\n\nimport {\n DEBUG, RE_TG_LINK, RE_TME_LINK,\n} from '../../config';\nimport buildClassName from '../../util/buildClassName';\n\ntype OwnProps = {\n url?: string;\n text: string;\n className?: string;\n children?: any;\n isRtl?: boolean;\n};\n\nconst SafeLink: FC = ({\n url,\n text,\n className,\n children,\n isRtl,\n}) => {\n const { toggleSafeLinkModal, openTelegramLink } = getDispatch();\n\n const content = children || text;\n const isNotSafe = url !== content;\n\n const handleClick = useCallback((e: React.MouseEvent) => {\n if (\n e.ctrlKey || e.altKey || e.shiftKey || e.metaKey\n || !url || (!url.match(RE_TME_LINK) && !url.match(RE_TG_LINK))\n ) {\n if (isNotSafe) {\n toggleSafeLinkModal({ url });\n\n e.preventDefault();\n return false;\n }\n\n return true;\n }\n\n e.preventDefault();\n openTelegramLink({ url });\n\n return false;\n }, [isNotSafe, openTelegramLink, toggleSafeLinkModal, url]);\n\n if (!url) {\n return undefined;\n }\n\n const classNames = buildClassName(\n className || 'text-entity-link',\n text.length > 50 && 'long-word-break-all',\n );\n\n return (\n \n {content}\n \n );\n};\n\nfunction ensureProtocol(url?: string) {\n if (!url) {\n return undefined;\n }\n\n return url.includes('://') ? url : `https://${url}`;\n}\n\nfunction getDomain(url?: string) {\n if (!url) {\n return undefined;\n }\n\n const href = ensureProtocol(url);\n if (!href) {\n return undefined;\n }\n\n try {\n let decodedHref = decodeURI(href);\n\n const match = decodedHref.match(/^https?:\\/\\/([^/:?#]+)(?:[/:?#]|$)/i);\n if (!match) {\n return undefined;\n }\n const domain = match[1];\n decodedHref = decodedHref.replace(domain, convertPunycode(domain));\n\n return decodedHref;\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('SafeLink.getDecodedUrl error ', url, error);\n }\n }\n\n return undefined;\n}\n\nexport default memo(SafeLink);\n","import { ApiDocument } from '../../../api/types';\n\nconst ONE_GIGABYTE = 1024 * 1024 * 1024;\nconst ONE_MEGABYTE = 1024 * 1024;\n\nexport function getFileSizeString(bytes: number) {\n if (bytes > (ONE_GIGABYTE / 2)) {\n return `${(bytes / ONE_GIGABYTE).toFixed(1)} GB`;\n }\n if (bytes > (ONE_MEGABYTE / 2)) {\n return `${(bytes / ONE_MEGABYTE).toFixed(1)} MB`;\n }\n return `${(bytes / (1024)).toFixed(1)} KB`;\n}\n\nexport function getDocumentExtension(document: ApiDocument) {\n const { fileName, mimeType } = document;\n\n return getFileExtension(fileName, mimeType);\n}\n\nexport function getFileExtension(fileName: string, mimeType: string) {\n if (fileName && fileName.indexOf('.') !== -1) {\n return fileName.split('.').pop();\n } else {\n return mimeType.split('/').pop();\n }\n}\n\nexport function getColorFromExtension(extension: string) {\n switch (extension) {\n case 'apk':\n case 'xls':\n case 'xlsx':\n return 'green';\n case 'zip':\n case 'rar':\n case '7z':\n case 'tar':\n case 'gz':\n case 'ppt':\n case 'pptx':\n return 'orange';\n case 'pdf':\n case 'xps':\n return 'red';\n default:\n return 'default';\n }\n}\n\nexport function getDocumentHasPreview(document: ApiDocument) {\n return Boolean(document.previewBlobUrl || document.thumbnail);\n}\n","// @ts-ignore\nimport twemojiRegex from '../../../lib/twemojiRegex';\n\nconst DETECT_UP_TO = 3;\nconst MAX_LENGTH = DETECT_UP_TO * 8; // Maximum 8 per one emoji.\nconst RE_EMOJI_ONLY = new RegExp(`^(?:${twemojiRegex.source})+$`, '');\n\nexport default (text: string): number | false => {\n if (text.length > MAX_LENGTH) {\n return false;\n }\n\n const isEmojiOnly = Boolean(text.match(RE_EMOJI_ONLY));\n if (!isEmojiOnly) {\n return false;\n }\n\n let emojiCount = 0;\n while (twemojiRegex.exec(text)) {\n emojiCount++;\n\n if (emojiCount > DETECT_UP_TO) {\n twemojiRegex.lastIndex = 0;\n return false;\n }\n }\n\n return emojiCount;\n};\n","import React, { FC, useCallback } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiChat, ApiUser } from '../../api/types';\n\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\n\nimport Link from '../ui/Link';\n\ntype OwnProps = {\n className?: string;\n sender?: ApiUser | ApiChat;\n children: any;\n};\n\ntype DispatchProps = Pick;\n\nconst UserLink: FC = ({\n className, sender, openUserInfo, children,\n}) => {\n const handleClick = useCallback(() => {\n if (sender) {\n openUserInfo({ id: sender.id });\n }\n }, [sender, openUserInfo]);\n\n if (!sender) {\n return children;\n }\n\n return (\n {children}\n );\n};\n\nexport default withGlobal(\n undefined,\n (setGlobal, actions): DispatchProps => pick(actions, ['openUserInfo']),\n)(UserLink);\n","import React, { FC, useCallback } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiMessage } from '../../api/types';\n\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\n\nimport Link from '../ui/Link';\n\ntype OwnProps = {\n className?: string;\n message?: ApiMessage;\n children: any;\n};\n\ntype DispatchProps = Pick;\n\nconst MessageLink: FC = ({\n className, message, children, focusMessage,\n}) => {\n const handleMessageClick = useCallback((): void => {\n if (message) {\n focusMessage({ chatId: message.chatId, messageId: message.id });\n }\n }, [focusMessage, message]);\n\n if (!message) {\n return children;\n }\n\n return (\n {children}\n );\n};\n\nexport default withGlobal(\n undefined,\n (setGlobal, actions): DispatchProps => pick(actions, ['focusMessage']),\n)(MessageLink);\n","import React, { FC, useCallback } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\n\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\n\nimport Link from '../ui/Link';\n\ntype OwnProps = {\n className?: string;\n chatId?: string;\n children: any;\n};\n\ntype DispatchProps = Pick;\n\nconst ChatLink: FC = ({\n className, chatId, openChat, children,\n}) => {\n const handleClick = useCallback(() => {\n if (chatId) {\n openChat({ id: chatId });\n }\n }, [chatId, openChat]);\n\n if (!chatId) {\n return children;\n }\n\n return (\n {children}\n );\n};\n\nexport default withGlobal(\n undefined,\n (setGlobal, actions): DispatchProps => pick(actions, ['openChat']),\n)(ChatLink);\n","import React from '../../../lib/teact/teact';\n\nimport { ApiChat, ApiMessage, ApiUser } from '../../../api/types';\nimport { LangFn } from '../../../hooks/useLang';\nimport {\n getChatTitle,\n getMessageContent,\n getMessageSummaryText,\n getUserFullName,\n isUserId,\n} from '../../../modules/helpers';\nimport trimText from '../../../util/trimText';\nimport { formatCurrency } from '../../../util/formatCurrency';\nimport { TextPart } from './renderMessageText';\nimport renderText from './renderText';\n\nimport UserLink from '../UserLink';\nimport MessageLink from '../MessageLink';\nimport ChatLink from '../ChatLink';\n\ninterface ActionMessageTextOptions {\n maxTextLength?: number;\n asPlain?: boolean;\n isEmbedded?: boolean;\n}\n\nconst NBSP = '\\u00A0';\n\nexport function renderActionMessageText(\n lang: LangFn,\n message: ApiMessage,\n actionOrigin?: ApiUser | ApiChat,\n targetUsers?: ApiUser[],\n targetMessage?: ApiMessage,\n targetChatId?: string,\n options: ActionMessageTextOptions = {},\n) {\n if (!message.content.action) {\n return [];\n }\n const {\n text, translationValues, amount, currency,\n } = message.content.action;\n const content: TextPart[] = [];\n const textOptions: ActionMessageTextOptions = { ...options, maxTextLength: 32 };\n const translationKey = text === 'Chat.Service.Group.UpdatedPinnedMessage1' && !targetMessage\n ? 'Message.PinnedGenericMessage'\n : text;\n\n let unprocessed = lang(translationKey, translationValues && translationValues.length ? translationValues : undefined);\n let processed: TextPart[];\n\n if (unprocessed.includes('%payment_amount%')) {\n processed = processPlaceholder(\n unprocessed,\n '%payment_amount%',\n formatCurrency(amount!, currency, lang.code),\n );\n unprocessed = processed.pop() as string;\n content.push(...processed);\n }\n\n processed = processPlaceholder(\n unprocessed,\n '%action_origin%',\n actionOrigin\n ? (!options.isEmbedded && renderOriginContent(lang, actionOrigin, options.asPlain)) || NBSP\n : 'User',\n );\n\n unprocessed = processed.pop() as string;\n content.push(...processed);\n\n processed = processPlaceholder(\n unprocessed,\n '%target_user%',\n targetUsers\n ? targetUsers.map((user) => renderUserContent(user, options.asPlain)).filter(Boolean as any)\n : 'User',\n );\n\n unprocessed = processed.pop() as string;\n content.push(...processed);\n\n processed = processPlaceholder(\n unprocessed,\n '%message%',\n targetMessage\n ? renderMessageContent(lang, targetMessage, textOptions)\n : 'a message',\n );\n unprocessed = processed.pop() as string;\n content.push(...processed);\n\n processed = processPlaceholder(\n unprocessed,\n '%product%',\n targetMessage\n ? renderProductContent(targetMessage)\n : 'a product',\n );\n unprocessed = processed.pop() as string;\n content.push(...processed);\n\n processed = processPlaceholder(\n unprocessed,\n '%target_chat%',\n targetChatId\n ? renderMigratedContent(targetChatId, options.asPlain)\n : 'another chat',\n );\n content.push(...processed);\n\n if (options.asPlain) {\n return content.join('').trim();\n }\n\n return content;\n}\n\nfunction renderProductContent(message: ApiMessage) {\n return message.content && message.content.invoice\n ? message.content.invoice.title\n : 'a product';\n}\n\nfunction renderMessageContent(lang: LangFn, message: ApiMessage, options: ActionMessageTextOptions = {}) {\n const text = getMessageSummaryText(lang, message);\n const {\n photo, video, document, sticker,\n } = getMessageContent(message);\n\n const { maxTextLength, isEmbedded, asPlain } = options;\n\n const showQuotes = isEmbedded && text && !photo && !video && !document && !sticker;\n let messageText = trimText(text as string, maxTextLength)!;\n\n if (isEmbedded) {\n if (photo) {\n messageText = 'a photo';\n } else if (video) {\n messageText = video.isGif ? 'a GIF' : 'a video';\n } else if (document) {\n messageText = 'a document';\n } else if (sticker) {\n messageText = text;\n }\n }\n\n if (asPlain) {\n return showQuotes ? `«${messageText}»` : messageText;\n }\n\n if (showQuotes) {\n return (\n \n «\n {renderText(messageText)}\n »\n \n );\n }\n\n return (\n {renderText(messageText)}\n );\n}\n\nfunction renderOriginContent(lang: LangFn, origin: ApiUser | ApiChat, asPlain?: boolean) {\n return isUserId(origin.id)\n ? renderUserContent(origin as ApiUser, asPlain)\n : renderChatContent(lang, origin as ApiChat, asPlain);\n}\n\nfunction renderUserContent(sender: ApiUser, asPlain?: boolean): string | TextPart | undefined {\n const text = trimText(getUserFullName(sender));\n\n if (asPlain) {\n return text;\n }\n\n return {sender && renderText(text!)};\n}\n\nfunction renderChatContent(lang: LangFn, chat: ApiChat, asPlain?: boolean): string | TextPart | undefined {\n const text = trimText(getChatTitle(lang, chat));\n\n if (asPlain) {\n return text;\n }\n\n return {chat && renderText(text!)};\n}\n\nfunction renderMigratedContent(chatId: string, asPlain?: boolean): string | TextPart | undefined {\n const text = 'another chat';\n\n if (asPlain) {\n return text;\n }\n\n return {text};\n}\n\nfunction processPlaceholder(text: string, placeholder: string, replaceValue?: TextPart | TextPart[]): TextPart[] {\n const placeholderPosition = text.indexOf(placeholder);\n if (placeholderPosition < 0 || !replaceValue) {\n return [text];\n }\n\n const content: TextPart[] = [];\n content.push(text.substring(0, placeholderPosition));\n if (Array.isArray(replaceValue)) {\n replaceValue.forEach((value, index) => {\n content.push(value);\n if (index + 1 < replaceValue.length) {\n content.push(', ');\n }\n });\n } else {\n content.push(replaceValue);\n }\n content.push(text.substring(placeholderPosition + placeholder.length));\n\n return content;\n}\n","import React from '../../../lib/teact/teact';\nimport EMOJI_REGEX, { removeVS16s } from '../../../lib/twemojiRegex';\n\nimport { RE_LINK_TEMPLATE, RE_MENTION_TEMPLATE } from '../../../config';\nimport { IS_EMOJI_SUPPORTED } from '../../../util/environment';\nimport { fixNonStandardEmoji, nativeToUnified } from '../../../util/emoji';\nimport buildClassName from '../../../util/buildClassName';\n\nimport MentionLink from '../../middle/message/MentionLink';\nimport SafeLink from '../SafeLink';\n\ntype TextPart = string | Element;\n\nconst RE_LETTER_OR_DIGIT = /^[\\d\\wа-яё]$/i;\nconst SIMPLE_MARKDOWN_REGEX = /(\\*\\*|__).+?\\1/g;\n\nexport default function renderText(\n part: TextPart,\n filters: Array<(\n 'escape_html' | 'hq_emoji' | 'emoji' | 'emoji_html' | 'br' | 'br_html' | 'highlight' | 'links' |\n 'simple_markdown' | 'simple_markdown_html'\n )> = ['emoji'],\n params?: { highlight: string | undefined },\n): TextPart[] {\n if (typeof part !== 'string') {\n return [part];\n }\n\n return filters.reduce((text, filter) => {\n switch (filter) {\n case 'escape_html':\n return escapeHtml(text);\n\n case 'hq_emoji':\n EMOJI_REGEX.lastIndex = 0;\n return replaceEmojis(text, 'big', 'jsx');\n\n case 'emoji':\n EMOJI_REGEX.lastIndex = 0;\n return replaceEmojis(text, 'small', 'jsx');\n\n case 'emoji_html':\n EMOJI_REGEX.lastIndex = 0;\n return replaceEmojis(text, 'small', 'html');\n\n case 'br':\n return addLineBreaks(text, 'jsx');\n\n case 'br_html':\n return addLineBreaks(text, 'html');\n\n case 'highlight':\n return addHighlight(text, params!.highlight);\n\n case 'links':\n return addLinks(text);\n\n case 'simple_markdown':\n return replaceSimpleMarkdown(text, 'jsx');\n\n case 'simple_markdown_html':\n return replaceSimpleMarkdown(text, 'html');\n }\n\n return text;\n }, [part] as TextPart[]);\n}\n\nfunction escapeHtml(textParts: TextPart[]): TextPart[] {\n const divEl = document.createElement('div');\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n divEl.innerText = part;\n\n return [...result, divEl.innerHTML];\n }, [] as TextPart[]);\n}\n\nfunction replaceEmojis(textParts: TextPart[], size: 'big' | 'small', type: 'jsx' | 'html'): TextPart[] {\n if (IS_EMOJI_SUPPORTED) {\n return textParts;\n }\n\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n part = fixNonStandardEmoji(part);\n const parts = part.split(EMOJI_REGEX);\n const emojis = part.match(EMOJI_REGEX) || [];\n result.push(parts[0]);\n\n return emojis.reduce((emojiResult: TextPart[], emoji, i) => {\n const code = nativeToUnified(removeVS16s(emoji));\n if (!code) return emojiResult;\n const className = buildClassName(\n 'emoji',\n size === 'small' && 'emoji-small',\n );\n if (type === 'jsx') {\n emojiResult.push(\n ,\n );\n }\n if (type === 'html') {\n emojiResult.push(\n // For preventing extra spaces in html\n // eslint-disable-next-line max-len\n `\"${emoji}\"`,\n );\n }\n\n const index = i * 2 + 2;\n if (parts[index]) {\n emojiResult.push(parts[index]);\n }\n\n return emojiResult;\n }, result);\n }, [] as TextPart[]);\n}\n\nfunction addLineBreaks(textParts: TextPart[], type: 'jsx' | 'html'): TextPart[] {\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n return [...result, ...part\n .split(/\\r\\n|\\r|\\n/g)\n .reduce((parts: TextPart[], line: string, i, source) => {\n // This adds non-breaking space if line was indented with spaces, to preserve the indentation\n const trimmedLine = line.trimLeft();\n const indentLength = line.length - trimmedLine.length;\n parts.push(String.fromCharCode(160).repeat(indentLength) + trimmedLine);\n\n if (i !== source.length - 1) {\n parts.push(\n type === 'jsx' ?
: '
',\n );\n }\n\n return parts;\n }, [])];\n }, [] as TextPart[]);\n}\n\nfunction addHighlight(textParts: TextPart[], highlight: string | undefined): TextPart[] {\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string' || !highlight) {\n return [...result, part];\n }\n\n const lowerCaseText = part.toLowerCase();\n const queryPosition = lowerCaseText.indexOf(highlight.toLowerCase());\n const nextSymbol = lowerCaseText[queryPosition + highlight.length];\n if (queryPosition < 0 || (nextSymbol && nextSymbol.match(RE_LETTER_OR_DIGIT))) {\n return [...result, part];\n }\n\n const newParts: TextPart[] = [];\n newParts.push(part.substring(0, queryPosition));\n newParts.push(\n \n {part.substring(queryPosition, queryPosition + highlight.length)}\n ,\n );\n newParts.push(part.substring(queryPosition + highlight.length));\n\n return [...result, ...newParts];\n }, [] as TextPart[]);\n}\n\nconst RE_LINK = new RegExp(`${RE_LINK_TEMPLATE}|${RE_MENTION_TEMPLATE}`, 'ig');\n\nfunction addLinks(textParts: TextPart[]): TextPart[] {\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n const links = part.match(RE_LINK);\n if (!links || !links.length) {\n return [...result, part];\n }\n\n const content: TextPart[] = [];\n\n let nextLink = links.shift();\n let lastIndex = 0;\n while (nextLink) {\n const index = part.indexOf(nextLink, lastIndex);\n content.push(part.substring(lastIndex, index));\n if (nextLink.startsWith('@')) {\n content.push(\n \n {nextLink}\n ,\n );\n } else {\n if (nextLink.endsWith('?')) {\n nextLink = nextLink.slice(0, nextLink.length - 1);\n }\n\n content.push(\n ,\n );\n }\n lastIndex = index + nextLink.length;\n nextLink = links.shift();\n }\n content.push(part.substring(lastIndex));\n\n return [...result, ...content];\n }, [] as TextPart[]);\n}\n\nfunction replaceSimpleMarkdown(textParts: TextPart[], type: 'jsx' | 'html'): TextPart[] {\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n const parts = part.split(SIMPLE_MARKDOWN_REGEX);\n const entities = part.match(SIMPLE_MARKDOWN_REGEX) || [];\n result.push(parts[0]);\n\n return entities.reduce((entityResult: TextPart[], entity, i) => {\n if (type === 'jsx') {\n entityResult.push(\n entity.startsWith('**')\n ? {entity.replace(/\\*\\*/g, '')}\n : {entity.replace(/__/g, '')},\n );\n } else {\n entityResult.push(\n entity.startsWith('**')\n ? `${entity.replace(/\\*\\*/g, '')}`\n : `${entity.replace(/__/g, '')}`,\n );\n }\n\n const index = i * 2 + 2;\n if (parts[index]) {\n entityResult.push(parts[index]);\n }\n\n return entityResult;\n }, result);\n }, [] as TextPart[]);\n}\n","import React from '../../../lib/teact/teact';\n\nimport { EDITABLE_INPUT_ID } from '../../../config';\nimport { IS_IOS } from '../../../util/environment';\n\nexport function preventMessageInputBlur(e: React.MouseEvent, withBubbling = false) {\n if (\n IS_IOS\n || !document.activeElement\n || document.activeElement.id !== EDITABLE_INPUT_ID\n || (!withBubbling && e.target !== e.currentTarget)\n ) {\n return;\n }\n\n e.preventDefault();\n}\n\nexport function preventMessageInputBlurWithBubbling(e: React.MouseEvent) {\n preventMessageInputBlur(e, true);\n}\n","import React, { FC } from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiChat, ApiUser } from '../../../api/types';\n\nimport { pick } from '../../../util/iteratees';\nimport { selectUser } from '../../../modules/selectors';\n\ntype OwnProps = {\n userId?: string;\n username?: string;\n children: any;\n};\n\ntype StateProps = {\n userOrChat?: ApiUser | ApiChat;\n};\n\ntype DispatchProps = Pick;\n\nconst MentionLink: FC = ({\n username,\n userOrChat,\n children,\n openChat,\n openChatByUsername,\n}) => {\n const handleClick = () => {\n if (userOrChat) {\n openChat({ id: userOrChat.id });\n } else if (username) {\n openChatByUsername({ username: username.substring(1) });\n }\n };\n\n return (\n \n {children}\n \n );\n};\n\nexport default withGlobal(\n (global, { userId }): StateProps => {\n return {\n userOrChat: userId ? selectUser(global, userId) : undefined,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['openChat', 'openChatByUsername']),\n)(MentionLink);\n","import { MouseEvent as ReactMouseEvent, RefObject } from 'react';\n\nimport React, {\n FC, useRef, useCallback, useState,\n} from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport Spinner from './Spinner';\nimport RippleEffect from './RippleEffect';\n\nimport './Button.scss';\n\nexport type OwnProps = {\n ref?: RefObject;\n type?: 'button' | 'submit' | 'reset';\n children: any;\n size?: 'default' | 'smaller' | 'tiny';\n color?: 'primary' | 'secondary' | 'gray' | 'danger' | 'translucent' | 'translucent-white' | 'dark';\n backgroundImage?: string;\n className?: string;\n round?: boolean;\n pill?: boolean;\n fluid?: boolean;\n isText?: boolean;\n isLoading?: boolean;\n ariaLabel?: string;\n href?: string;\n download?: string;\n disabled?: boolean;\n ripple?: boolean;\n faded?: boolean;\n tabIndex?: number;\n isRtl?: boolean;\n withClickPropagation?: boolean;\n onClick?: (e: ReactMouseEvent) => void;\n onContextMenu?: (e: ReactMouseEvent) => void;\n onMouseDown?: (e: ReactMouseEvent) => void;\n onMouseEnter?: NoneToVoidFunction;\n onMouseLeave?: NoneToVoidFunction;\n onFocus?: NoneToVoidFunction;\n};\n\n// Longest animation duration;\nconst CLICKED_TIMEOUT = 400;\n\nconst Button: FC = ({\n ref,\n type = 'button',\n onClick,\n onContextMenu,\n onMouseDown,\n onMouseEnter,\n onMouseLeave,\n onFocus,\n children,\n size = 'default',\n color = 'primary',\n backgroundImage,\n className,\n round,\n pill,\n fluid,\n isText,\n isLoading,\n ariaLabel,\n href,\n download,\n disabled,\n ripple,\n faded,\n tabIndex,\n isRtl,\n withClickPropagation,\n}) => {\n // eslint-disable-next-line no-null/no-null\n let elementRef = useRef(null);\n if (ref) {\n elementRef = ref;\n }\n\n const [isClicked, setIsClicked] = useState(false);\n\n const fullClassName = buildClassName(\n 'Button',\n className,\n size,\n color,\n round && 'round',\n pill && 'pill',\n fluid && 'fluid',\n disabled && 'disabled',\n isText && 'text',\n isLoading && 'loading',\n ripple && 'has-ripple',\n faded && 'faded',\n isClicked && 'clicked',\n backgroundImage && 'with-image',\n );\n\n const handleClick = useCallback((e: ReactMouseEvent) => {\n if (!disabled && onClick) {\n onClick(e);\n }\n\n setIsClicked(true);\n setTimeout(() => {\n setIsClicked(false);\n }, CLICKED_TIMEOUT);\n }, [disabled, onClick]);\n\n const handleMouseDown = useCallback((e: ReactMouseEvent) => {\n if (!withClickPropagation) e.preventDefault();\n if (!disabled && onMouseDown) {\n onMouseDown(e);\n }\n }, [onMouseDown, disabled, withClickPropagation]);\n\n if (href) {\n return (\n }\n className={fullClassName}\n href={href}\n title={ariaLabel}\n download={download}\n tabIndex={tabIndex}\n dir={isRtl ? 'rtl' : undefined}\n >\n {children}\n {!disabled && ripple && (\n \n )}\n \n );\n }\n\n return (\n // eslint-disable-next-line react/button-has-type\n }\n type={type}\n className={fullClassName}\n onClick={handleClick}\n onContextMenu={onContextMenu}\n onMouseDown={handleMouseDown}\n onMouseEnter={onMouseEnter && !disabled ? onMouseEnter : undefined}\n onMouseLeave={onMouseLeave && !disabled ? onMouseLeave : undefined}\n onFocus={onFocus && !disabled ? onFocus : undefined}\n aria-label={ariaLabel}\n title={ariaLabel}\n tabIndex={tabIndex}\n dir={isRtl ? 'rtl' : undefined}\n // @ts-ignore\n style={backgroundImage ? `background-image: url(${backgroundImage})` : undefined}\n >\n {isLoading ? (\n
\n Please wait...\n \n
\n ) : children }\n {!disabled && ripple && (\n \n )}\n \n );\n};\n\nexport default Button;\n","import { ChangeEvent } from 'react';\nimport React, { FC, memo, useCallback } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\nimport renderText from '../common/helpers/renderText';\n\nimport Spinner from './Spinner';\n\nimport './Checkbox.scss';\n\ntype OwnProps = {\n id?: string;\n name?: string;\n value?: string;\n label: string;\n subLabel?: string;\n checked: boolean;\n disabled?: boolean;\n round?: boolean;\n blocking?: boolean;\n isLoading?: boolean;\n withCheckedCallback?: boolean;\n onChange?: (e: ChangeEvent) => void;\n onCheck?: (isChecked: boolean) => void;\n};\n\nconst Checkbox: FC = ({\n id,\n name,\n value,\n label,\n subLabel,\n checked,\n disabled,\n round,\n blocking,\n isLoading,\n onChange,\n onCheck,\n}) => {\n const lang = useLang();\n const handleChange = useCallback((event: ChangeEvent) => {\n if (onChange) {\n onChange(event);\n }\n\n if (onCheck) {\n onCheck(event.currentTarget.checked);\n }\n }, [onChange, onCheck]);\n\n const className = buildClassName(\n 'Checkbox',\n disabled && 'disabled',\n round && 'round',\n isLoading && 'loading',\n blocking && 'blocking',\n );\n\n return (\n \n );\n};\n\nexport default memo(Checkbox);\n","import React, { FC, useState, useRef } from '../../lib/teact/teact';\n\nimport Menu from './Menu';\n\nimport './DropdownMenu.scss';\n\ntype OwnProps = {\n className?: string;\n trigger: FC<{ onTrigger: () => void; isOpen?: boolean }>;\n positionX?: 'left' | 'right';\n positionY?: 'top' | 'bottom';\n footer?: string;\n forceOpen?: boolean;\n onOpen?: NoneToVoidFunction;\n onClose?: NoneToVoidFunction;\n children: any;\n};\n\nconst DropdownMenu: FC = ({\n trigger,\n className,\n children,\n positionX = 'left',\n positionY = 'top',\n footer,\n forceOpen,\n onOpen,\n onClose,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const menuRef = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const dropdownRef = useRef(null);\n const [isOpen, setIsOpen] = useState(false);\n\n const toggleIsOpen = () => {\n setIsOpen(!isOpen);\n if (isOpen) {\n if (onClose) onClose();\n } else if (onOpen) onOpen();\n };\n\n const handleKeyDown = (e: React.KeyboardEvent) => {\n const menu = menuRef.current;\n\n if (!isOpen || e.keyCode !== 40 || !menu) {\n return;\n }\n\n const focusedElement = document.activeElement;\n const elementChildren = Array.from(menu.children);\n\n if (!focusedElement || elementChildren.indexOf(focusedElement) === -1) {\n (elementChildren[0] as HTMLElement).focus();\n }\n };\n\n const handleClose = () => {\n setIsOpen(false);\n if (onClose) onClose();\n };\n\n return (\n \n {trigger({ onTrigger: toggleIsOpen, isOpen })}\n\n \n {children}\n \n \n );\n};\n\nexport default DropdownMenu;\n","import { ChangeEvent, FormEvent, RefObject } from 'react';\nimport React, { FC, memo } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\ntype OwnProps = {\n ref?: RefObject;\n id?: string;\n className?: string;\n value?: string;\n label?: string;\n error?: string;\n success?: string;\n disabled?: boolean;\n readOnly?: boolean;\n placeholder?: string;\n autoComplete?: string;\n maxLength?: number;\n inputMode?: 'text' | 'none' | 'tel' | 'url' | 'email' | 'numeric' | 'decimal' | 'search';\n onChange?: (e: ChangeEvent) => void;\n onInput?: (e: FormEvent) => void;\n onKeyPress?: (e: React.KeyboardEvent) => void;\n onKeyDown?: (e: React.KeyboardEvent) => void;\n onBlur?: (e: React.FocusEvent) => void;\n onPaste?: (e: React.ClipboardEvent) => void;\n};\n\nconst InputText: FC = ({\n ref,\n id,\n className,\n value,\n label,\n error,\n success,\n disabled,\n readOnly,\n placeholder,\n autoComplete,\n inputMode,\n maxLength,\n onChange,\n onInput,\n onKeyPress,\n onKeyDown,\n onBlur,\n onPaste,\n}) => {\n const lang = useLang();\n const labelText = error || success || label;\n const fullClassName = buildClassName(\n 'input-group',\n value && 'touched',\n error ? 'error' : success && 'success',\n disabled && 'disabled',\n readOnly && 'disabled',\n labelText && 'with-label',\n className,\n );\n\n return (\n
\n \n {labelText && (\n \n )}\n
\n );\n};\n\nexport default memo(InputText);\n","import React, { FC, useCallback } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport './Link.scss';\n\ntype OwnProps = {\n children: any;\n className?: string;\n isRtl?: boolean;\n onClick?: (e: React.MouseEvent) => void;\n};\n\nconst Link: FC = ({\n children, className, isRtl, onClick,\n}) => {\n const handleClick = useCallback((e: React.MouseEvent) => {\n e.preventDefault();\n onClick!(e);\n }, [onClick]);\n\n return (\n \n {children}\n \n );\n};\n\nexport default Link;\n","import React, { FC, memo } from '../../lib/teact/teact';\n\nimport Spinner from './Spinner';\n\nimport './Loading.scss';\n\ntype OwnProps = {\n color?: 'blue' | 'white' | 'black';\n};\n\nconst Loading: FC = ({ color = 'blue' }) => {\n return (\n
\n \n
\n );\n};\n\nexport default memo(Loading);\n","import { RefObject } from 'react';\nimport React, { FC, useEffect, useRef } from '../../lib/teact/teact';\n\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useKeyboardListNavigation from '../../hooks/useKeyboardListNavigation';\nimport useVirtualBackdrop from '../../hooks/useVirtualBackdrop';\nimport useEffectWithPrevDeps from '../../hooks/useEffectWithPrevDeps';\nimport captureEscKeyListener from '../../util/captureEscKeyListener';\nimport buildClassName from '../../util/buildClassName';\nimport { dispatchHeavyAnimationEvent } from '../../hooks/useHeavyAnimationCheck';\nimport useHistoryBack from '../../hooks/useHistoryBack';\nimport { preventMessageInputBlurWithBubbling } from '../middle/helpers/preventMessageInputBlur';\n\nimport './Menu.scss';\n\ntype OwnProps = {\n ref?: RefObject;\n containerRef?: RefObject;\n isOpen: boolean;\n className?: string;\n style?: string;\n menuStyle?: string;\n positionX?: 'left' | 'right';\n positionY?: 'top' | 'bottom';\n autoClose?: boolean;\n shouldSkipTransition?: boolean;\n footer?: string;\n noCloseOnBackdrop?: boolean;\n onKeyDown?: (e: React.KeyboardEvent) => void;\n onCloseAnimationEnd?: () => void;\n onClose?: () => void;\n onMouseEnter?: (e: React.MouseEvent) => void;\n onMouseLeave?: (e: React.MouseEvent) => void;\n children: any;\n};\n\nconst ANIMATION_DURATION = 200;\n\nconst Menu: FC = ({\n ref,\n containerRef,\n isOpen,\n className,\n style,\n menuStyle,\n children,\n positionX = 'left',\n positionY = 'top',\n autoClose = false,\n footer,\n noCloseOnBackdrop = false,\n onCloseAnimationEnd,\n onClose,\n onMouseEnter,\n onMouseLeave,\n shouldSkipTransition,\n}) => {\n // eslint-disable-next-line no-null/no-null\n let menuRef = useRef(null);\n if (ref) {\n menuRef = ref;\n }\n const backdropContainerRef = containerRef || menuRef;\n\n const {\n transitionClassNames,\n } = useShowTransition(\n isOpen,\n onCloseAnimationEnd,\n shouldSkipTransition,\n undefined,\n shouldSkipTransition,\n );\n\n useEffect(\n () => (isOpen && onClose ? captureEscKeyListener(onClose) : undefined),\n [isOpen, onClose],\n );\n\n useHistoryBack(isOpen, onClose, undefined, undefined, autoClose);\n\n useEffectWithPrevDeps(([prevIsOpen]) => {\n if (prevIsOpen !== undefined) {\n dispatchHeavyAnimationEvent(ANIMATION_DURATION);\n }\n }, [isOpen]);\n\n const handleKeyDown = useKeyboardListNavigation(menuRef, isOpen, autoClose ? onClose : undefined, undefined, true);\n\n useVirtualBackdrop(\n isOpen,\n backdropContainerRef,\n noCloseOnBackdrop ? undefined : onClose,\n );\n\n const bubbleClassName = buildClassName(\n 'bubble menu-container custom-scroll',\n positionY,\n positionX,\n footer && 'with-footer',\n transitionClassNames,\n );\n\n return (\n \n {isOpen && (\n // This only prevents click events triggering on underlying elements\n
\n )}\n \n {children}\n {footer &&
{footer}
}\n
\n \n );\n};\n\nexport default Menu;\n","import React, { FC, useCallback } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\nimport './MenuItem.scss';\n\ntype OnClickHandler = (e: React.SyntheticEvent) => void;\n\ntype OwnProps = {\n icon?: string;\n className?: string;\n children: any;\n onClick?: OnClickHandler;\n href?: string;\n download?: string;\n disabled?: boolean;\n destructive?: boolean;\n ariaLabel?: string;\n};\n\nconst MenuItem: FC = (props) => {\n const {\n icon,\n className,\n children,\n onClick,\n href,\n download,\n disabled,\n destructive,\n ariaLabel,\n } = props;\n\n const lang = useLang();\n const handleClick = useCallback((e: React.MouseEvent) => {\n if (disabled || !onClick) {\n e.stopPropagation();\n e.preventDefault();\n\n return;\n }\n\n onClick(e);\n }, [disabled, onClick]);\n\n const handleKeyDown = useCallback((e: React.KeyboardEvent) => {\n if (e.keyCode !== 13 && e.keyCode !== 32) {\n return;\n }\n\n if (disabled || !onClick) {\n e.stopPropagation();\n e.preventDefault();\n\n return;\n }\n\n onClick(e);\n }, [disabled, onClick]);\n\n const fullClassName = buildClassName(\n 'MenuItem',\n className,\n disabled && 'disabled',\n destructive && 'destructive',\n );\n\n const content = (\n <>\n {icon && (\n \n )}\n {children}\n \n );\n\n if (href) {\n return (\n \n {content}\n \n );\n }\n\n return (\n \n {content}\n \n );\n};\n\nexport default MenuItem;\n","import React, {\n FC, useCallback, useMemo, useState, memo,\n} from '../../lib/teact/teact';\nimport { debounce } from '../../util/schedulers';\n\nimport './RippleEffect.scss';\n\ninterface Ripple {\n x: number;\n y: number;\n size: number;\n}\n\nconst ANIMATION_DURATION_MS = 700;\n\nconst RippleEffect: FC = () => {\n const [ripples, setRipples] = useState([]);\n\n const cleanUpDebounced = useMemo(() => {\n return debounce(() => {\n setRipples([]);\n }, ANIMATION_DURATION_MS, false);\n }, []);\n\n const handleMouseDown = useCallback((e: React.MouseEvent) => {\n if (e.button !== 0) {\n return;\n }\n\n const container = e.currentTarget as HTMLDivElement;\n const position = container.getBoundingClientRect() as DOMRect;\n\n const rippleSize = container.offsetWidth / 2;\n\n setRipples([\n ...ripples,\n {\n x: e.clientX - position.x - (rippleSize / 2),\n y: e.clientY - position.y - (rippleSize / 2),\n size: rippleSize,\n },\n ]);\n\n requestAnimationFrame(() => {\n cleanUpDebounced();\n });\n }, [ripples, cleanUpDebounced]);\n\n return (\n
\n {ripples.map(({ x, y, size }) => (\n \n ))}\n
\n );\n};\n\nexport default memo(RippleEffect);\n","import React, { FC } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport './Spinner.scss';\n\nconst Spinner: FC<{\n color?: 'blue' | 'white' | 'black' | 'green' | 'gray';\n withBackground?: boolean;\n}> = ({\n color = 'blue',\n withBackground,\n}) => {\n return (\n
\n
\n
\n );\n};\n\nexport default Spinner;\n","export const PAGE_TITLE = 'Telegram';\nexport const INACTIVE_MARKER = ' [Inactive]';\n\nexport const APP_NAME = process.env.APP_NAME || 'Telegram WebZ';\nexport const APP_VERSION = process.env.APP_VERSION || 'dev';\n\nexport const DEBUG = (\n process.env.APP_ENV !== 'production' && process.env.APP_ENV !== 'perf' && process.env.APP_ENV !== 'test'\n);\nexport const DEBUG_MORE = false;\n\nexport const IS_TEST = process.env.APP_ENV === 'test';\nexport const IS_PERF = process.env.APP_ENV === 'perf';\n\nexport const DEBUG_ALERT_MSG = 'Shoot!\\nSomething went wrong, please see the error details in Dev Tools Console.';\nexport const DEBUG_GRAMJS = false;\n\nexport const SESSION_USER_KEY = 'user_auth';\nexport const LEGACY_SESSION_KEY = 'GramJs:sessionId';\n\nexport const GLOBAL_STATE_CACHE_DISABLED = false;\nexport const GLOBAL_STATE_CACHE_KEY = 'tt-global-state';\nexport const GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT = 30;\nexport const GLOBAL_STATE_CACHE_USER_LIST_LIMIT = 5000;\n\nexport const MEDIA_CACHE_DISABLED = false;\nexport const MEDIA_CACHE_NAME = 'tt-media';\nexport const MEDIA_CACHE_NAME_AVATARS = 'tt-media-avatars';\nexport const MEDIA_PROGRESSIVE_CACHE_DISABLED = false;\nexport const MEDIA_PROGRESSIVE_CACHE_NAME = 'tt-media-progressive';\nexport const MEDIA_CACHE_MAX_BYTES = 512 * 1024; // 512 KB\nexport const CUSTOM_BG_CACHE_NAME = 'tt-custom-bg';\nexport const LANG_CACHE_NAME = 'tt-lang-packs-v6';\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_SENSITIVE_AREA = 750;\nexport const MESSAGE_LIST_SLICE = isBigScreen ? 60 : 40;\nexport const MESSAGE_LIST_VIEWPORT_LIMIT = MESSAGE_LIST_SLICE * 2;\n\nexport const CHAT_HEIGHT_PX = 72;\nexport const CHAT_LIST_SLICE = isBigScreen ? 30 : 25;\nexport const CHAT_LIST_LOAD_SLICE = 100;\nexport const SHARED_MEDIA_SLICE = 42;\nexport const MESSAGE_SEARCH_SLICE = 42;\nexport const GLOBAL_SEARCH_SLICE = 20;\nexport const MEMBERS_SLICE = 30;\nexport const MEMBERS_LOAD_SLICE = 200;\nexport const PINNED_MESSAGES_LIMIT = 50;\nexport const BLOCKED_LIST_LIMIT = 100;\nexport const PROFILE_PHOTOS_LIMIT = 40;\nexport const PROFILE_SENSITIVE_AREA = 500;\nexport const COMMON_CHATS_LIMIT = 100;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 20;\nexport const ALL_CHATS_PRELOAD_DISABLED = false;\n\nexport const DEFAULT_VOLUME = 1;\nexport const DEFAULT_PLAYBACK_RATE = 1;\n\nexport const ANIMATION_LEVEL_MIN = 0;\nexport const ANIMATION_LEVEL_MED = 1;\nexport const ANIMATION_LEVEL_MAX = 2;\nexport const ANIMATION_LEVEL_DEFAULT = ANIMATION_LEVEL_MAX;\n\nexport const DEFAULT_MESSAGE_TEXT_SIZE_PX = 16;\nexport const IOS_DEFAULT_MESSAGE_TEXT_SIZE_PX = 17;\nexport const MACOS_DEFAULT_MESSAGE_TEXT_SIZE_PX = 15;\n\nexport const DRAFT_DEBOUNCE = 10000; // 10s\n\nexport const EDITABLE_INPUT_ID = 'editable-message-text';\nexport const EDITABLE_INPUT_MODAL_ID = 'editable-message-text-modal';\n\n// Screen width where Pinned Message / Audio Player in the Middle Header can be safely displayed\nexport const SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1440; // px\n// Screen width where Pinned Message / Audio Player in the Middle Header shouldn't collapse with ChatInfo\nexport const SAFE_SCREEN_WIDTH_FOR_CHAT_INFO = 1150; // px\n\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1275; // px\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN = 925; // px\nexport const MOBILE_SCREEN_MAX_WIDTH = 600; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH = 950; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT = 450; // px\n\nexport const LOCAL_MESSAGE_ID_BASE = 1e9;\nexport const TMP_CHAT_ID = '0';\n\nexport const ANIMATION_END_DELAY = 100;\n\nexport const FAST_SMOOTH_MAX_DISTANCE = 1500;\nexport const FAST_SMOOTH_MIN_DURATION = 250;\nexport const FAST_SMOOTH_MAX_DURATION = 600;\nexport const FAST_SMOOTH_SHORT_TRANSITION_MAX_DISTANCE = 500; // px\n\n// Average duration of message sending animation\nexport const API_UPDATE_THROTTLE = Math.round((FAST_SMOOTH_MIN_DURATION + FAST_SMOOTH_MAX_DURATION) / 2);\nexport const API_THROTTLE_RESET_UPDATES = new Set([\n 'newMessage', 'newScheduledMessage', 'deleteMessages', 'deleteScheduledMessages', 'deleteHistory',\n]);\n\nexport const STICKER_SIZE_INLINE_DESKTOP_FACTOR = 13;\nexport const STICKER_SIZE_INLINE_MOBILE_FACTOR = 11;\nexport const STICKER_SIZE_AUTH = 160;\nexport const STICKER_SIZE_AUTH_MOBILE = 120;\nexport const STICKER_SIZE_PICKER = 64;\nexport const STICKER_SIZE_GENERAL_SETTINGS = 48;\nexport const STICKER_SIZE_PICKER_HEADER = 32;\nexport const STICKER_SIZE_SEARCH = 64;\nexport const STICKER_SIZE_MODAL = 64;\nexport const STICKER_SIZE_TWO_FA = 160;\nexport const STICKER_SIZE_DISCUSSION_GROUPS = 140;\nexport const STICKER_SIZE_FOLDER_SETTINGS = 80;\nexport const STICKER_SIZE_INLINE_BOT_RESULT = 100;\nexport const RECENT_STICKERS_LIMIT = 20;\nexport const MEMOJI_STICKER_ID = 'MEMOJI_STICKER';\n\nexport const BASE_EMOJI_KEYWORD_LANG = 'en';\n\nexport const MENU_TRANSITION_DURATION = 200;\nexport const SLIDE_TRANSITION_DURATION = 450;\n\nexport const VIDEO_MOV_TYPE = 'video/quicktime';\n\nexport const SUPPORTED_IMAGE_CONTENT_TYPES = new Set([\n 'image/png', 'image/gif', 'image/jpeg',\n]);\n\nexport const SUPPORTED_VIDEO_CONTENT_TYPES = new Set([\n 'video/mp4', // video/quicktime added dynamically in environment.ts\n]);\n\nexport const CONTENT_TYPES_WITH_PREVIEW = new Set([\n ...SUPPORTED_IMAGE_CONTENT_TYPES,\n ...SUPPORTED_VIDEO_CONTENT_TYPES,\n]);\n\n// eslint-disable-next-line max-len\nexport const RE_LINK_TEMPLATE = '((ftp|https?):\\\\/\\\\/)?((www\\\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\\\.[a-zA-Z0-9()]{1,63})\\\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)';\nexport const RE_MENTION_TEMPLATE = '(@[\\\\w\\\\d_-]+)';\nexport const RE_TG_LINK = /^tg:(\\/\\/)?([?=&\\d\\w_-]+)?/gm;\nexport const RE_TME_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/)/gm;\n\n// eslint-disable-next-line max-len\nexport const COUNTRIES_WITH_12H_TIME_FORMAT = new Set(['AU', 'BD', 'CA', 'CO', 'EG', 'HN', 'IE', 'IN', 'JO', 'MX', 'MY', 'NI', 'NZ', 'PH', 'PK', 'SA', 'SV', 'US']);\n\n// MTProto constants\nexport const SERVICE_NOTIFICATIONS_USER_ID = '777000';\nexport const REPLIES_USER_ID = '1271266957'; // TODO For Test connection ID must be equal to 708513\nexport const ALL_FOLDER_ID = 0;\nexport const ARCHIVED_FOLDER_ID = 1;\nexport const DELETED_COMMENTS_CHANNEL_ID = '-777';\nexport const MAX_MEDIA_FILES_FOR_ALBUM = 10;\nexport const MAX_ACTIVE_PINNED_CHATS = 5;\nexport const SCHEDULED_WHEN_ONLINE = 0x7FFFFFFE;\nexport const DEFAULT_LANG_CODE = 'en';\nexport const DEFAULT_LANG_PACK = 'android';\nexport const LANG_PACKS = ['android', 'ios', 'tdesktop', 'macos'] as const;\nexport const TIPS_USERNAME = 'TelegramTips';\nexport const LOCALIZED_TIPS = ['ar', 'pt-br', 'id', 'it', 'ko', 'ms', 'pl', 'es', 'tr'];\nexport const FEEDBACK_URL = 'https://bugs.telegram.org/?tag_ids=41&sort=time';\nexport const LIGHT_THEME_BG_COLOR = '#A2AF8E';\nexport const DARK_THEME_BG_COLOR = '#0F0F0F';\nexport const DARK_THEME_PATTERN_COLOR = '#0a0a0a8c';\nexport const DEFAULT_PATTERN_COLOR = 'rgba(90, 110, 70, 0.6)';\n","import { useEffect } from '../lib/teact/teact';\nimport usePrevious from './usePrevious';\n\nexport default (cb: (args: PT) => void, dependencies: T, debugKey?: string) => {\n const prevDeps = usePrevious(dependencies);\n return useEffect(() => {\n // @ts-ignore (workaround for \"could be instantiated with a different subtype\" issue)\n return cb(prevDeps || []);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, dependencies, debugKey);\n};\n","import { useCallback, useState } from '../lib/teact/teact';\n\nexport default (initial = false): [boolean, AnyToVoidFunction, AnyToVoidFunction] => {\n const [value, setValue] = useState(initial);\n\n const setTrue = useCallback(() => {\n setValue(true);\n }, []);\n\n const setFalse = useCallback(() => {\n setValue(false);\n }, []);\n\n return [value, setTrue, setFalse];\n};\n","import { useCallback, useState } from '../lib/teact/teact';\n\nexport default () => {\n const [, setTrigger] = useState(false);\n\n return useCallback(() => {\n setTrigger((trigger) => !trigger);\n }, []);\n};\n","import { useEffect } from '../lib/teact/teact';\n\nexport const ANIMATION_START_EVENT = 'tt-event-heavy-animation-start';\nexport const ANIMATION_END_EVENT = 'tt-event-heavy-animation-end';\n\nlet timeout: number | undefined;\nlet isAnimating = false;\n\nexport const dispatchHeavyAnimationEvent = (duration?: number) => {\n if (!isAnimating) {\n isAnimating = true;\n document.dispatchEvent(new Event(ANIMATION_START_EVENT));\n }\n\n if (timeout) {\n clearTimeout(timeout);\n timeout = undefined;\n }\n\n if (duration) {\n timeout = window.setTimeout(() => {\n isAnimating = false;\n document.dispatchEvent(new Event(ANIMATION_END_EVENT));\n timeout = undefined;\n }, duration);\n }\n\n return () => {\n isAnimating = false;\n document.dispatchEvent(new Event(ANIMATION_END_EVENT));\n };\n};\n\nexport default (\n handleAnimationStart: AnyToVoidFunction,\n handleAnimationEnd: AnyToVoidFunction,\n) => {\n useEffect(() => {\n if (isAnimating) {\n handleAnimationStart();\n }\n\n document.addEventListener(ANIMATION_START_EVENT, handleAnimationStart);\n document.addEventListener(ANIMATION_END_EVENT, handleAnimationEnd);\n\n return () => {\n document.removeEventListener(ANIMATION_END_EVENT, handleAnimationEnd);\n document.removeEventListener(ANIMATION_START_EVENT, handleAnimationStart);\n };\n }, [handleAnimationEnd, handleAnimationStart]);\n};\n","import { useCallback, useEffect, useRef } from '../lib/teact/teact';\n\nimport { IS_IOS } from '../util/environment';\nimport usePrevious from './usePrevious';\nimport { getDispatch } from '../lib/teact/teactn';\nimport { areSortedArraysEqual } from '../util/iteratees';\n\ntype HistoryState = {\n currentIndex: number;\n nextStateIndexToReplace: number;\n isHistoryAltered: boolean;\n isDisabled: boolean;\n isEdge: boolean;\n currentIndexes: number[];\n};\n\n// Carefully selected by swiping and observing visual changes\n// TODO: may be different on other devices such as iPad, maybe take dpi into account?\nconst SAFARI_EDGE_BACK_GESTURE_LIMIT = 300;\nconst SAFARI_EDGE_BACK_GESTURE_DURATION = 350;\nexport const LOCATION_HASH = window.location.hash;\nconst PATH_BASE = `${window.location.pathname}${window.location.search}`;\n\nconst historyState: HistoryState = {\n currentIndex: 0,\n nextStateIndexToReplace: -1,\n isHistoryAltered: false,\n isDisabled: false,\n isEdge: false,\n currentIndexes: [],\n};\n\nexport const disableHistoryBack = () => {\n historyState.isDisabled = true;\n};\n\nconst handleTouchStart = (event: TouchEvent) => {\n const x = event.touches[0].pageX;\n\n if (x <= SAFARI_EDGE_BACK_GESTURE_LIMIT || x >= window.innerWidth - SAFARI_EDGE_BACK_GESTURE_LIMIT) {\n historyState.isEdge = true;\n }\n};\n\nconst handleTouchEnd = () => {\n if (historyState.isEdge) {\n setTimeout(() => {\n historyState.isEdge = false;\n }, SAFARI_EDGE_BACK_GESTURE_DURATION);\n }\n};\n\nif (IS_IOS) {\n window.addEventListener('touchstart', handleTouchStart);\n window.addEventListener('touchend', handleTouchEnd);\n window.addEventListener('popstate', handleTouchEnd);\n}\n\nwindow.history.replaceState({ index: historyState.currentIndex }, '', PATH_BASE);\n\nexport default function useHistoryBack(\n isActive: boolean | undefined,\n onBack: ((noDisableAnimation: boolean) => void) | undefined,\n onForward?: (state: any) => void,\n currentState?: any,\n shouldReplaceNext = false,\n hashes?: string[],\n) {\n const indexRef = useRef(-1);\n const isForward = useRef(false);\n const prevIsActive = usePrevious(isActive);\n const isClosed = useRef(true);\n const indexHashRef = useRef<{ index: number; hash: string }[]>([]);\n const prevHashes = usePrevious(hashes);\n const isHashChangedFromEvent = useRef(false);\n\n const handleChange = useCallback((isForceClose = false) => {\n if (!hashes) {\n if (isActive && !isForceClose) {\n isClosed.current = false;\n\n if (isForward.current) {\n isForward.current = false;\n historyState.currentIndexes.push(indexRef.current);\n } else {\n setTimeout(() => {\n const index = ++historyState.currentIndex;\n\n historyState.currentIndexes.push(index);\n\n window.history[(\n (\n historyState.currentIndexes.includes(historyState.nextStateIndexToReplace - 1)\n && window.history.state.index !== 0\n && historyState.nextStateIndexToReplace === index\n && !shouldReplaceNext\n )\n ? 'replaceState'\n : 'pushState'\n )]({\n index,\n state: currentState,\n }, '');\n\n indexRef.current = index;\n\n if (shouldReplaceNext) {\n historyState.nextStateIndexToReplace = historyState.currentIndex + 1;\n }\n }, 0);\n }\n }\n\n if ((isForceClose || !isActive) && !isClosed.current) {\n if ((indexRef.current === historyState.currentIndex || !shouldReplaceNext)) {\n historyState.isHistoryAltered = true;\n window.history.back();\n\n setTimeout(() => {\n historyState.nextStateIndexToReplace = -1;\n }, 400);\n }\n historyState.currentIndexes.splice(historyState.currentIndexes.indexOf(indexRef.current), 1);\n\n isClosed.current = true;\n }\n } else {\n const prev = prevHashes || [];\n if (prev.length < hashes.length) {\n setTimeout(() => {\n const index = ++historyState.currentIndex;\n historyState.currentIndexes.push(index);\n\n window.history.pushState({\n index,\n state: currentState,\n }, '', `#${hashes[hashes.length - 1]}`);\n\n indexHashRef.current.push({\n index,\n hash: hashes[hashes.length - 1],\n });\n }, 0);\n } else {\n const delta = prev.length - hashes.length;\n if (isHashChangedFromEvent.current) {\n isHashChangedFromEvent.current = false;\n } else {\n if (hashes.length !== indexHashRef.current.length) {\n if (delta > 0) {\n const last = indexHashRef.current[indexHashRef.current.length - delta - 1];\n let realDelta = delta;\n if (last) {\n const indexLast = historyState.currentIndexes.findIndex(\n (l) => l === last.index,\n );\n realDelta = historyState.currentIndexes.length - indexLast - 1;\n }\n historyState.isHistoryAltered = true;\n window.history.go(-realDelta);\n const removed = indexHashRef.current.splice(indexHashRef.current.length - delta - 1, delta);\n removed.forEach(({ index }) => {\n historyState.currentIndexes.splice(historyState.currentIndexes.indexOf(index), 1);\n });\n }\n }\n\n if (hashes.length > 0) {\n setTimeout(() => {\n const index = ++historyState.currentIndex;\n historyState.currentIndexes[historyState.currentIndexes.length - 1] = index;\n\n window.history.replaceState({\n index,\n state: currentState,\n }, '', `${PATH_BASE}#${hashes[hashes.length - 1]}`);\n\n indexHashRef.current[indexHashRef.current.length - 1] = {\n index,\n hash: hashes[hashes.length - 1],\n };\n }, 0);\n }\n }\n }\n }\n }, [currentState, hashes, isActive, prevHashes, shouldReplaceNext]);\n\n useEffect(() => {\n const handlePopState = (event: PopStateEvent) => {\n if (historyState.isHistoryAltered) {\n setTimeout(() => {\n historyState.isHistoryAltered = false;\n }, 0);\n return;\n }\n const { index: i } = event.state;\n const index = i || 0;\n try {\n const currIndex = hashes ? indexHashRef.current[indexHashRef.current.length - 1].index : indexRef.current;\n\n const prev = historyState.currentIndexes[historyState.currentIndexes.indexOf(currIndex) - 1];\n\n if (historyState.isDisabled) return;\n\n if ((!isClosed.current && (index === 0 || index === prev)) || (hashes && (index === 0 || index === prev))) {\n if (hashes) {\n isHashChangedFromEvent.current = true;\n indexHashRef.current.pop();\n }\n\n historyState.currentIndexes.splice(historyState.currentIndexes.indexOf(currIndex), 1);\n\n if (onBack) {\n if (historyState.isEdge) {\n getDispatch()\n .disableHistoryAnimations();\n }\n onBack(!historyState.isEdge);\n isClosed.current = true;\n }\n } else if (index === currIndex && isClosed.current && onForward && !hashes) {\n isForward.current = true;\n if (historyState.isEdge) {\n getDispatch()\n .disableHistoryAnimations();\n }\n onForward(event.state.state);\n }\n } catch (e) {\n // Forward navigation for hashed is not supported\n }\n };\n\n const hasChanged = hashes\n ? (!prevHashes || !areSortedArraysEqual(prevHashes, hashes))\n : prevIsActive !== isActive;\n\n if (!historyState.isDisabled && hasChanged) {\n handleChange();\n }\n\n window.addEventListener('popstate', handlePopState);\n return () => window.removeEventListener('popstate', handlePopState);\n }, [\n currentState, handleChange, hashes, isActive, onBack, onForward, prevHashes, prevIsActive, shouldReplaceNext,\n ]);\n\n return {\n forceClose: () => handleChange(true),\n };\n}\n","import { RefObject } from 'react';\nimport { useState, useCallback, useEffect } from '../lib/teact/teact';\n\nexport default (\n elementRef: RefObject,\n isOpen: boolean,\n onSelectWithEnter?: (index: number) => void,\n itemSelector?: string,\n noCaptureFocus?: boolean,\n) => {\n const [focusedIndex, setFocusedIndex] = useState(-1);\n\n useEffect(() => {\n setFocusedIndex(-1);\n\n const element = elementRef.current;\n if (isOpen && element && !noCaptureFocus) {\n element.tabIndex = -1;\n element.focus();\n }\n }, [elementRef, isOpen, noCaptureFocus]);\n\n const handleKeyDown = useCallback((e: React.KeyboardEvent) => {\n const element = elementRef.current;\n\n if (!element) {\n return;\n }\n\n if (e.keyCode === 13 && onSelectWithEnter) {\n onSelectWithEnter(focusedIndex);\n return;\n }\n\n if (e.keyCode !== 38 && e.keyCode !== 40) {\n return;\n }\n\n const focusedElement = document.activeElement;\n const elementChildren = Array.from(itemSelector ? element.querySelectorAll(itemSelector) : element.children);\n\n let newIndex = (focusedElement && elementChildren.indexOf(focusedElement)) || focusedIndex;\n\n if (e.keyCode === 38 && newIndex > 0) {\n newIndex--;\n } else if (e.keyCode === 40 && newIndex < elementChildren.length - 1) {\n newIndex++;\n } else if (elementChildren.length === 1) {\n newIndex = 0;\n } else {\n return;\n }\n\n const item = elementChildren[newIndex] as HTMLElement;\n if (item) {\n setFocusedIndex(newIndex);\n item.focus();\n }\n }, [elementRef, onSelectWithEnter, itemSelector, focusedIndex]);\n\n return handleKeyDown;\n};\n","import * as langProvider from '../util/langProvider';\nimport useForceUpdate from './useForceUpdate';\nimport useOnChange from './useOnChange';\n\nexport type LangFn = typeof langProvider.getTranslation;\n\nexport default (): LangFn => {\n const forceUpdate = useForceUpdate();\n\n useOnChange(() => {\n return langProvider.addCallback(forceUpdate);\n }, [forceUpdate]);\n\n return langProvider.getTranslation;\n};\n","import { useEffect } from '../lib/teact/teact';\n\nimport {\n BundleModules, Bundles, getModuleFromMemory, loadModule, addLoadListener,\n} from '../util/moduleLoader';\n\nimport useForceUpdate from './useForceUpdate';\n\nexport default >(\n bundleName: B, moduleName: M, noLoad = false, autoUpdate = false,\n) => {\n const module = getModuleFromMemory(bundleName, moduleName);\n const forceUpdate = useForceUpdate();\n\n if (autoUpdate) {\n // Use effect and cleanup for listener removal\n addLoadListener(forceUpdate);\n }\n\n useEffect(() => {\n if (!noLoad && !module) {\n loadModule(bundleName, moduleName).then(forceUpdate);\n }\n }, [bundleName, forceUpdate, module, moduleName, noLoad]);\n\n return module;\n};\n","import usePrevious from './usePrevious';\n\nexport default (cb: (args: PT) => void, dependencies: T) => {\n const prevDeps = usePrevious(dependencies);\n if (!prevDeps || dependencies.some((d, i) => d !== prevDeps[i])) {\n // @ts-ignore (workaround for \"could be instantiated with a different subtype\" issue)\n cb(prevDeps || []);\n }\n};\n","import { useRef } from '../lib/teact/teact';\n\nfunction usePrevious(next: T): T | undefined;\nfunction usePrevious(next: T, shouldSkipUndefined: true): Exclude | undefined;\nfunction usePrevious(next: T, shouldSkipUndefined?: boolean): Exclude | undefined;\nfunction usePrevious(next: T, shouldSkipUndefined?: boolean) {\n const ref = useRef();\n const { current } = ref;\n if (!shouldSkipUndefined || next !== undefined) {\n ref.current = next;\n }\n\n return current;\n}\n\nexport default usePrevious;\n","import { useRef, useState } from '../lib/teact/teact';\nimport buildClassName from '../util/buildClassName';\n\nconst CLOSE_DURATION = 350;\n\nexport default (\n isOpen = false,\n onCloseTransitionEnd?: () => void,\n noOpenTransition = false,\n className: string | false = 'fast',\n noCloseTransition = false,\n) => {\n const [isClosed, setIsClosed] = useState(!isOpen);\n const closeTimeoutRef = useRef();\n // СSS class should be added in a separate tick to turn on CSS transition.\n const [hasOpenClassName, setHasOpenClassName] = useState(isOpen && noOpenTransition);\n\n if (isOpen) {\n setIsClosed(false);\n setHasOpenClassName(true);\n\n if (closeTimeoutRef.current) {\n window.clearTimeout(closeTimeoutRef.current);\n closeTimeoutRef.current = undefined;\n }\n } else {\n setHasOpenClassName(false);\n\n if (!isClosed && !closeTimeoutRef.current) {\n closeTimeoutRef.current = window.setTimeout(() => {\n setIsClosed(true);\n\n if (onCloseTransitionEnd) {\n onCloseTransitionEnd();\n }\n\n closeTimeoutRef.current = undefined;\n }, noCloseTransition ? 0 : CLOSE_DURATION);\n }\n }\n\n // `noCloseTransition`, when set to true, should remove the open class immediately\n const shouldHaveOpenClassName = hasOpenClassName && !(noCloseTransition && !isOpen);\n const isClosing = Boolean(closeTimeoutRef.current);\n const shouldRender = isOpen || isClosing;\n const transitionClassNames = buildClassName(\n className && 'opacity-transition',\n className,\n shouldHaveOpenClassName && 'open',\n shouldRender && 'shown',\n isClosing && 'closing',\n );\n\n return {\n shouldRender,\n transitionClassNames,\n };\n};\n","import { RefObject } from 'react';\nimport { useEffect } from '../lib/teact/teact';\n\nconst BACKDROP_CLASSNAME = 'backdrop';\n\n// This effect implements closing menus by clicking outside of them\n// without adding extra elements to the DOM\nexport default function useVirtualBackdrop(\n isOpen: boolean,\n menuRef: RefObject,\n onClose?: () => void | undefined,\n) {\n useEffect(() => {\n const handleEvent = (e: Event) => {\n const menu = menuRef.current;\n const target = e.target as HTMLElement | null;\n if (!menu || !target) {\n return;\n }\n\n if (\n !menu.contains(e.target as Node | null)\n || target.classList.contains(BACKDROP_CLASSNAME)\n ) {\n e.preventDefault();\n e.stopPropagation();\n if (onClose) {\n onClose();\n }\n }\n };\n\n if (isOpen && onClose) {\n document.addEventListener('mousedown', handleEvent);\n }\n\n return () => {\n document.removeEventListener('mousedown', handleEvent);\n };\n }, [isOpen, menuRef, onClose]);\n}\n","import { DEBUG } from '../../config';\n\ntype Handler = (e: Event) => void;\n\nconst NON_BUBBLEABLE_EVENTS = new Set(['scroll', 'mouseenter', 'mouseleave']);\n\nconst delegationRegistry: Record> = {};\nconst delegatedEventsByElement = new Map>();\nconst documentEventCounters: Record = {};\n\nexport function addEventListener(element: HTMLElement, propName: string, handler: Handler, asCapture = false) {\n const eventName = resolveEventName(propName, element);\n if (canUseEventDelegation(eventName, element, asCapture)) {\n addDelegatedListener(eventName, element, handler);\n } else {\n element.addEventListener(eventName, handler, asCapture);\n }\n}\n\nexport function removeEventListener(element: HTMLElement, propName: string, handler: Handler, asCapture = false) {\n const eventName = resolveEventName(propName, element);\n if (canUseEventDelegation(eventName, element, asCapture)) {\n removeDelegatedListener(eventName, element);\n } else {\n element.removeEventListener(eventName, handler, asCapture);\n }\n}\n\nfunction resolveEventName(propName: string, element: HTMLElement) {\n const eventName = propName\n .replace(/^on/, '')\n .replace(/Capture$/, '').toLowerCase();\n\n if (eventName === 'change' && element.tagName !== 'SELECT') {\n // React behavior repeated here.\n // https://stackoverflow.com/questions/38256332/in-react-whats-the-difference-between-onchange-and-oninput\n return 'input';\n }\n\n if (eventName === 'doubleclick') {\n return 'dblclick';\n }\n\n // Replace focus/blur by their \"bubbleable\" versions\n if (eventName === 'focus') {\n return 'focusin';\n }\n\n if (eventName === 'blur') {\n return 'focusout';\n }\n\n return eventName;\n}\n\nfunction canUseEventDelegation(realEventName: string, element: HTMLElement, asCapture: boolean) {\n return (\n !asCapture\n && !NON_BUBBLEABLE_EVENTS.has(realEventName)\n && element.tagName !== 'VIDEO'\n && element.tagName !== 'IFRAME'\n );\n}\n\nfunction addDelegatedListener(eventName: string, element: HTMLElement, handler: Handler) {\n if (!documentEventCounters[eventName]) {\n documentEventCounters[eventName] = 0;\n document.addEventListener(eventName, handleEvent);\n }\n\n resolveDelegationRegistryForName(eventName).set(element, handler);\n resolveDelegatedEventsForElement(element).add(eventName);\n documentEventCounters[eventName]++;\n}\n\nfunction removeDelegatedListener(eventName: string, element: HTMLElement) {\n documentEventCounters[eventName]--;\n if (!documentEventCounters[eventName]) {\n // Synchronous deletion on 0 will cause perf degradation in the case of 1 element\n // which is not a real case, so it's ok to do it this way\n document.removeEventListener(eventName, handleEvent);\n }\n\n delegationRegistry[eventName].delete(element);\n delegatedEventsByElement.get(element)!.delete(eventName);\n}\n\nexport function removeAllDelegatedListeners(element: HTMLElement) {\n const eventNames = delegatedEventsByElement.get(element);\n if (!eventNames) {\n return;\n }\n\n eventNames.forEach((eventName) => removeDelegatedListener(eventName, element));\n delegatedEventsByElement.delete(element);\n}\n\nfunction handleEvent(realEvent: Event) {\n const events = delegationRegistry[realEvent.type];\n\n if (events) {\n let furtherCallsPrevented = false;\n let current: HTMLElement = realEvent.target as HTMLElement;\n\n const stopPropagation = () => {\n furtherCallsPrevented = true;\n };\n\n const preventDefault = () => {\n realEvent.preventDefault();\n };\n\n // Proxy is a simplest way to provide an access to the event property\n const event = new Proxy(realEvent, {\n get(target, p) {\n if (p === 'currentTarget') {\n return current;\n }\n if (p === 'stopPropagation' || p === 'stopImmediatePropagation') {\n return stopPropagation;\n }\n if (p === 'preventDefault') {\n // \"this\" is changed to proxy and one can't call methods via it\n return preventDefault;\n }\n return Reflect.get(target, p);\n },\n });\n\n // This can also be limited by teact root\n while (current && current !== document.body) {\n const handler = events.get(current);\n if (handler) {\n handler(event);\n if (furtherCallsPrevented) {\n return;\n }\n }\n\n current = current.parentNode as HTMLElement;\n }\n }\n}\n\nfunction resolveDelegationRegistryForName(eventName: string) {\n if (!delegationRegistry[eventName]) {\n delegationRegistry[eventName] = new Map();\n }\n\n return delegationRegistry[eventName];\n}\n\nfunction resolveDelegatedEventsForElement(element: HTMLElement) {\n const existing = delegatedEventsByElement.get(element);\n if (existing) {\n return existing;\n }\n\n const newSet = new Set();\n delegatedEventsByElement.set(element, newSet);\n\n return newSet;\n}\n\nif (DEBUG) {\n document.addEventListener('dblclick', () => {\n // eslint-disable-next-line no-console\n console.log('DELEGATED EVENTS', { delegationRegistry, delegatedEventsByElement, documentEventCounters });\n });\n}\n","import {\n hasElementChanged,\n isComponentElement,\n isEmptyElement,\n isRealElement,\n isTextElement,\n mountComponent,\n renderComponent,\n unmountTree,\n getTarget,\n setTarget,\n VirtualElement,\n VirtualElementComponent,\n VirtualRealElement,\n} from './teact';\nimport generateIdFor from '../../util/generateIdFor';\nimport { DEBUG } from '../../config';\nimport { addEventListener, removeEventListener } from './dom-events';\n\ntype VirtualDomHead = {\n children: [VirtualElement] | [];\n};\n\nconst FILTERED_ATTRIBUTES = new Set(['key', 'ref', 'teactFastList', 'teactOrderKey']);\nconst HTML_ATTRIBUTES = new Set(['dir']);\nconst MAPPED_ATTRIBUTES: { [k: string]: string } = {\n autoPlay: 'autoplay',\n autoComplete: 'autocomplete',\n};\nconst INDEX_KEY_PREFIX = '__indexKey#';\n\nconst headsByElement: Record = {};\n// eslint-disable-next-line @typescript-eslint/naming-convention\nlet DEBUG_virtualTreeSize = 1;\n\nfunction render($element?: VirtualElement, parentEl?: HTMLElement | null) {\n if (!parentEl) {\n return undefined;\n }\n\n let headId = parentEl.getAttribute('data-teact-head-id');\n if (!headId) {\n headId = generateIdFor(headsByElement);\n headsByElement[headId] = { children: [] };\n parentEl.setAttribute('data-teact-head-id', headId);\n }\n\n const $head = headsByElement[headId];\n $head.children = [renderWithVirtual(parentEl, $head.children[0], $element, $head, 0) as VirtualElement];\n\n if (process.env.APP_ENV === 'perf') {\n DEBUG_virtualTreeSize = 0;\n DEBUG_addToVirtualTreeSize($head);\n\n return DEBUG_virtualTreeSize;\n }\n\n return undefined;\n}\n\nfunction renderWithVirtual(\n parentEl: HTMLElement,\n $current: VirtualElement | undefined,\n $new: VirtualElement | undefined,\n $parent: VirtualRealElement | VirtualDomHead,\n index: number,\n {\n skipComponentUpdate = false,\n forceIndex = false,\n fragment,\n moveDirection,\n }: {\n skipComponentUpdate?: boolean;\n forceIndex?: boolean;\n fragment?: DocumentFragment;\n moveDirection?: 'up' | 'down';\n } = {},\n) {\n if (\n !skipComponentUpdate\n && $current && $new\n && isComponentElement($current) && isComponentElement($new)\n && !hasElementChanged($current, $new)\n ) {\n $new = updateComponent($current, $new);\n }\n\n // Parent element may have changed, so we need to update the listener closure.\n if (!skipComponentUpdate && $new && isComponentElement($new) && $new.componentInstance.isMounted) {\n setupComponentUpdateListener($new, $parent, index, parentEl);\n }\n\n if ($current === $new) {\n return $new;\n }\n\n if (!$current && $new) {\n if (isComponentElement($new)) {\n $new = initComponent($new, $parent, index, parentEl);\n }\n\n const node = createNode($new);\n setTarget($new, node);\n\n if (forceIndex && parentEl.childNodes[index]) {\n parentEl.insertBefore(node, parentEl.childNodes[index]);\n } else {\n (fragment || parentEl).appendChild(node);\n }\n } else if ($current && !$new) {\n parentEl.removeChild(getTarget($current)!);\n unmountTree($current);\n } else if ($current && $new) {\n if (hasElementChanged($current, $new)) {\n if (isComponentElement($new)) {\n $new = initComponent($new, $parent, index, parentEl);\n }\n\n const node = createNode($new);\n setTarget($new, node);\n parentEl.replaceChild(node, getTarget($current)!);\n unmountTree($current);\n } else {\n const areComponents = isComponentElement($current) && isComponentElement($new);\n\n if (!areComponents) {\n setTarget($new, getTarget($current)!);\n }\n\n if (isRealElement($current) && isRealElement($new)) {\n if (moveDirection) {\n const node = getTarget($current)!;\n const nextSibling = parentEl.childNodes[moveDirection === 'up' ? index : index + 1];\n\n if (nextSibling) {\n parentEl.insertBefore(node, nextSibling);\n } else {\n (fragment || parentEl).appendChild(node);\n }\n }\n\n if (!areComponents) {\n updateAttributes($current, $new, getTarget($current) as HTMLElement);\n }\n\n $new.children = renderChildren(\n $current,\n $new,\n areComponents ? parentEl : getTarget($current) as HTMLElement,\n );\n }\n }\n }\n\n return $new;\n}\n\nfunction initComponent(\n $element: VirtualElementComponent, $parent: VirtualRealElement | VirtualDomHead, index: number, parentEl: HTMLElement,\n) {\n if (!isComponentElement($element)) {\n return $element;\n }\n\n const { componentInstance } = $element;\n\n if (!componentInstance.isMounted) {\n $element = mountComponent(componentInstance);\n setupComponentUpdateListener($element, $parent, index, parentEl);\n\n const $firstChild = $element.children[0];\n if (isComponentElement($firstChild)) {\n $element.children = [initComponent($firstChild, $element, 0, parentEl)];\n }\n\n componentInstance.isMounted = true;\n }\n\n return $element;\n}\n\nfunction updateComponent($current: VirtualElementComponent, $new: VirtualElementComponent) {\n $current.componentInstance.props = $new.componentInstance.props;\n\n return renderComponent($current.componentInstance);\n}\n\nfunction setupComponentUpdateListener(\n $element: VirtualElementComponent, $parent: VirtualRealElement | VirtualDomHead, index: number, parentEl: HTMLElement,\n) {\n const { componentInstance } = $element;\n\n componentInstance.onUpdate = () => {\n $parent.children[index] = renderWithVirtual(\n parentEl,\n $parent.children[index],\n componentInstance.$element,\n $parent,\n index,\n { skipComponentUpdate: true },\n ) as VirtualElementComponent;\n };\n}\n\nfunction createNode($element: VirtualElement): Node {\n if (isEmptyElement($element)) {\n return document.createTextNode('');\n }\n\n if (isTextElement($element)) {\n return document.createTextNode($element.value);\n }\n\n if (isComponentElement($element)) {\n return createNode($element.children[0] as VirtualElement);\n }\n\n const { tag, props, children = [] } = $element;\n const element = document.createElement(tag);\n\n if (typeof props.ref === 'object') {\n props.ref.current = element;\n }\n\n Object.keys(props).forEach((key) => {\n addAttribute(element, key, props[key]);\n });\n\n $element.children = children.map(($child, i) => (\n renderWithVirtual(element, undefined, $child, $element, i) as VirtualElement\n ));\n\n return element;\n}\n\nfunction renderChildren(\n $current: VirtualRealElement, $new: VirtualRealElement, currentEl: HTMLElement,\n) {\n if ($new.props.teactFastList) {\n return renderFastListChildren($current, $new, currentEl);\n }\n\n const maxLength = Math.max($current.children.length, $new.children.length);\n const newChildren = [];\n const fragment = $new.children.length > $current.children.length + 1 ? document.createDocumentFragment() : undefined;\n\n for (let i = 0; i < maxLength; i++) {\n const $newChild = renderWithVirtual(\n currentEl,\n $current.children[i],\n $new.children[i],\n $new,\n i,\n i >= $current.children.length ? { fragment } : undefined,\n );\n\n if ($newChild) {\n newChildren.push($newChild);\n }\n }\n\n if (fragment) {\n currentEl.appendChild(fragment);\n }\n\n return newChildren;\n}\n\nfunction renderFastListChildren($current: VirtualRealElement, $new: VirtualRealElement, currentEl: HTMLElement) {\n const newKeys = new Set(\n $new.children.map(($newChild) => {\n const key = 'props' in $newChild && $newChild.props.key;\n\n if (DEBUG && isRealElement($newChild) && !key) {\n // eslint-disable-next-line no-console\n console.warn('Missing `key` in `teactFastList`');\n }\n\n return key;\n }),\n );\n\n let currentRemainingIndex = 0;\n const remainingByKey = $current.children\n .reduce((acc, $currentChild, i) => {\n let key = 'props' in $currentChild ? $currentChild.props.key : undefined;\n\n // First we handle removed children\n if (key && !newKeys.has(key)) {\n renderWithVirtual(currentEl, $currentChild, undefined, $new, -1);\n\n return acc;\n } else if (!key) {\n const $newChild = $new.children[i];\n const newChildKey = ($newChild && 'props' in $newChild) ? $newChild.props.key : undefined;\n // If a non-key element remains at the same index we preserve it with a virtual `key`\n if ($newChild && !newChildKey) {\n key = `${INDEX_KEY_PREFIX}${i}`;\n } else {\n renderWithVirtual(currentEl, $currentChild, undefined, $new, -1);\n\n return acc;\n }\n }\n\n // Then we build up info about remaining children\n acc[key] = {\n $element: $currentChild,\n index: currentRemainingIndex++,\n order: 'props' in $currentChild ? $currentChild.props.teactOrderKey : undefined,\n };\n return acc;\n }, {} as Record);\n\n let newChildren: VirtualElement[] = [];\n\n let fragmentQueue: VirtualElement[] | undefined;\n let fragmentIndex: number | undefined;\n\n let currentPreservedIndex = 0;\n\n $new.children.forEach(($newChild, i) => {\n const key = 'props' in $newChild ? $newChild.props.key : `${INDEX_KEY_PREFIX}${i}`;\n const currentChildInfo = remainingByKey[key];\n\n if (!currentChildInfo) {\n // All new nodes are queued to be inserted with fragments if possible.\n if (!fragmentQueue) {\n fragmentQueue = [];\n fragmentIndex = i;\n }\n\n fragmentQueue.push($newChild);\n return;\n }\n\n if (fragmentQueue) {\n newChildren = newChildren.concat(flushFragmentQueue(fragmentQueue, fragmentIndex!, currentEl, $new));\n fragmentIndex = undefined;\n fragmentQueue = undefined;\n }\n\n // This is a \"magic\" `teactOrderKey` property that tells us the element is updated\n const order = 'props' in $newChild ? $newChild.props.teactOrderKey : undefined;\n const shouldMoveNode = currentChildInfo.index !== currentPreservedIndex && currentChildInfo.order !== order;\n const isMovingDown = shouldMoveNode && currentPreservedIndex > currentChildInfo.index;\n\n // When the node goes down, preserved indexing actually breaks, so the \"magic\" should help.\n if (!shouldMoveNode || isMovingDown) {\n currentPreservedIndex++;\n }\n\n newChildren.push(\n renderWithVirtual(currentEl, currentChildInfo.$element, $newChild, $new, i, {\n forceIndex: true,\n ...(shouldMoveNode && {\n moveDirection: isMovingDown ? 'down' : 'up',\n }),\n })!,\n );\n });\n\n if (fragmentQueue) {\n newChildren = newChildren.concat(flushFragmentQueue(fragmentQueue, fragmentIndex!, currentEl, $new));\n }\n\n return newChildren;\n}\n\nfunction flushFragmentQueue(\n fragmentQueue: VirtualElement[], fragmentIndex: number, parentEl: HTMLElement, $parent: VirtualRealElement,\n) {\n if (fragmentQueue.length === 1) {\n return [renderWithVirtual(parentEl, undefined, fragmentQueue[0], $parent, fragmentIndex, { forceIndex: true })!];\n } else if (fragmentQueue.length > 1) {\n const fragment = document.createDocumentFragment();\n const newChildren = fragmentQueue.map(($fragmentChild) => (\n renderWithVirtual(parentEl, undefined, $fragmentChild, $parent, fragmentIndex!, { fragment })!\n ));\n\n if (parentEl.childNodes[fragmentIndex]) {\n parentEl.insertBefore(fragment, parentEl.childNodes[fragmentIndex]);\n } else {\n parentEl.appendChild(fragment);\n }\n\n return newChildren;\n }\n\n throw new Error('Unexpected input');\n}\n\nfunction updateAttributes($current: VirtualRealElement, $new: VirtualRealElement, element: HTMLElement) {\n const currentKeys = Object.keys($current.props);\n const newKeys = Object.keys($new.props);\n\n currentKeys.forEach((key) => {\n if ($current.props[key] !== undefined && $new.props[key] === undefined) {\n removeAttribute(element, key, $current.props[key]);\n }\n });\n\n newKeys.forEach((key) => {\n if ($new.props[key] === undefined) {\n return;\n }\n\n if ($current.props[key] !== $new.props[key]) {\n if ($current.props[key] === undefined) {\n addAttribute(element, key, $new.props[key]);\n } else {\n updateAttribute(element, key, $current.props[key], $new.props[key]);\n }\n }\n });\n}\n\nfunction addAttribute(element: HTMLElement, key: string, value: any) {\n if (value === undefined) {\n return;\n }\n\n // An optimization attempt\n if (key === 'className') {\n element.className = value;\n // An optimization attempt\n } else if (key === 'value') {\n (element as HTMLInputElement).value = value;\n } else if (key === 'style') {\n element.style.cssText = value;\n } else if (key.startsWith('on')) {\n addEventListener(element, key, value, key.endsWith('Capture'));\n } else if (key.startsWith('data-') || HTML_ATTRIBUTES.has(key)) {\n element.setAttribute(key, value);\n } else if (!FILTERED_ATTRIBUTES.has(key)) {\n (element as any)[MAPPED_ATTRIBUTES[key] || key] = value;\n }\n}\n\nfunction removeAttribute(element: HTMLElement, key: string, value: any) {\n if (key === 'className') {\n element.className = '';\n } else if (key === 'value') {\n (element as HTMLInputElement).value = '';\n } else if (key === 'style') {\n element.style.cssText = '';\n } else if (key.startsWith('on')) {\n removeEventListener(element, key, value, key.endsWith('Capture'));\n } else if (key.startsWith('data-') || HTML_ATTRIBUTES.has(key)) {\n element.removeAttribute(key);\n } else if (!FILTERED_ATTRIBUTES.has(key)) {\n delete (element as any)[MAPPED_ATTRIBUTES[key] || key];\n }\n}\n\nfunction updateAttribute(element: HTMLElement, key: string, oldValue: any, newValue: any) {\n if (key === 'value') {\n // Removing and adding value causes a cursor jump\n (element as HTMLInputElement).value = newValue !== undefined ? newValue : '';\n } else {\n removeAttribute(element, key, oldValue);\n addAttribute(element, key, newValue);\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/naming-convention\nfunction DEBUG_addToVirtualTreeSize($current: VirtualRealElement | VirtualDomHead) {\n DEBUG_virtualTreeSize += $current.children.length;\n\n $current.children.forEach(($child) => {\n if (isRealElement($child)) {\n DEBUG_addToVirtualTreeSize($child);\n }\n });\n}\n\nexport default { render };\n","import { DEBUG, DEBUG_MORE } from '../../config';\nimport {\n fastRaf, fastRafPrimary, onTickEnd, onTickEndPrimary, throttleWithPrimaryRaf, throttleWithRaf,\n} from '../../util/schedulers';\nimport { flatten, orderBy } from '../../util/iteratees';\nimport arePropsShallowEqual, { getUnequalProps } from '../../util/arePropsShallowEqual';\nimport { handleError } from '../../util/handleError';\nimport { removeAllDelegatedListeners } from './dom-events';\n\nexport type Props = AnyLiteral;\nexport type FC

= (props: P) => any;\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport type FC_withDebug = FC & {\n DEBUG_contentComponentName?: string;\n};\n\nexport enum VirtualElementTypesEnum {\n Empty,\n Text,\n Tag,\n Component,\n}\n\ninterface VirtualElementEmpty {\n type: VirtualElementTypesEnum.Empty;\n target?: Node;\n}\n\ninterface VirtualElementText {\n type: VirtualElementTypesEnum.Text;\n target?: Node;\n value: string;\n}\n\nexport interface VirtualElementTag {\n type: VirtualElementTypesEnum.Tag;\n target?: Node;\n tag: string;\n props: Props;\n children: VirtualElementChildren;\n}\n\nexport interface VirtualElementComponent {\n type: VirtualElementTypesEnum.Component;\n componentInstance: ComponentInstance;\n props: Props;\n children: VirtualElementChildren;\n}\n\nexport type StateHookSetter = (newValue: ((current: T) => T) | T) => void;\n\ninterface ComponentInstance {\n $element: VirtualElementComponent;\n Component: FC;\n name: string;\n props: Props;\n renderedValue?: any;\n isMounted: boolean;\n hooks: {\n state: {\n cursor: number;\n byCursor: {\n value: any;\n nextValue: any;\n setter: StateHookSetter;\n }[];\n };\n effects: {\n cursor: number;\n byCursor: {\n effect: () => void;\n dependencies?: any[];\n cleanup?: Function;\n }[];\n };\n memos: {\n cursor: number;\n byCursor: {\n current: any;\n dependencies: any[];\n }[];\n };\n };\n prepareForFrame?: () => void;\n forceUpdate?: () => void;\n onUpdate?: () => void;\n}\n\nexport type VirtualElement =\n VirtualElementEmpty\n | VirtualElementText\n | VirtualElementTag\n | VirtualElementComponent;\nexport type VirtualRealElement =\n VirtualElementTag\n | VirtualElementComponent;\nexport type VirtualElementChildren = VirtualElement[];\n\nconst Fragment = Symbol('Fragment');\n\nlet renderingInstance: ComponentInstance;\n\nexport function isEmptyElement($element: VirtualElement): $element is VirtualElementEmpty {\n return $element.type === VirtualElementTypesEnum.Empty;\n}\n\nexport function isTextElement($element: VirtualElement): $element is VirtualElementText {\n return $element.type === VirtualElementTypesEnum.Text;\n}\n\nexport function isTagElement($element: VirtualElement): $element is VirtualElementTag {\n return $element.type === VirtualElementTypesEnum.Tag;\n}\n\nexport function isComponentElement($element: VirtualElement): $element is VirtualElementComponent {\n return $element.type === VirtualElementTypesEnum.Component;\n}\n\nexport function isRealElement($element: VirtualElement): $element is VirtualRealElement {\n return isTagElement($element) || isComponentElement($element);\n}\n\nfunction createElement(\n source: string | FC | typeof Fragment,\n props: Props,\n ...children: any[]\n): VirtualRealElement | VirtualElementChildren {\n if (!props) {\n props = {};\n }\n\n children = flatten(children);\n\n if (source === Fragment) {\n return children;\n } else if (typeof source === 'function') {\n return createComponentInstance(source, props, children);\n } else {\n return buildTagElement(source, props, children);\n }\n}\n\nfunction createComponentInstance(Component: FC, props: Props, children: any[]): VirtualElementComponent {\n let parsedChildren: any | any[] | undefined;\n if (children.length === 0) {\n parsedChildren = undefined;\n } else if (children.length === 1) {\n [parsedChildren] = children;\n } else {\n parsedChildren = children;\n }\n\n const componentInstance: ComponentInstance = {\n $element: {} as VirtualElementComponent,\n Component,\n name: Component.name,\n props: {\n ...props,\n ...(parsedChildren && { children: parsedChildren }),\n },\n isMounted: false,\n hooks: {\n state: {\n cursor: 0,\n byCursor: [],\n },\n effects: {\n cursor: 0,\n byCursor: [],\n },\n memos: {\n cursor: 0,\n byCursor: [],\n },\n },\n };\n\n componentInstance.$element = buildComponentElement(componentInstance);\n\n return componentInstance.$element;\n}\n\nfunction buildComponentElement(\n componentInstance: ComponentInstance,\n children: VirtualElementChildren = [],\n): VirtualElementComponent {\n const { props } = componentInstance;\n\n return {\n componentInstance,\n type: VirtualElementTypesEnum.Component,\n props,\n children,\n };\n}\n\nfunction buildTagElement(tag: string, props: Props, children: any[]): VirtualElementTag {\n return {\n type: VirtualElementTypesEnum.Tag,\n tag,\n props,\n children: dropEmptyTail(children).map(buildChildElement),\n };\n}\n\n// We only need placeholders in the middle of collection (to ensure other elements order).\nfunction dropEmptyTail(children: any[]) {\n let i = children.length - 1;\n\n for (; i >= 0; i--) {\n if (!isEmptyPlaceholder(children[i])) {\n break;\n }\n }\n\n return i + 1 < children.length ? children.slice(0, i + 1) : children;\n}\n\nfunction isEmptyPlaceholder(child: any) {\n // eslint-disable-next-line no-null/no-null\n return child === false || child === null || child === undefined;\n}\n\nfunction buildChildElement(child: any): VirtualElement {\n if (isEmptyPlaceholder(child)) {\n return buildEmptyElement();\n } else if (isRealElement(child)) {\n return child;\n } else {\n return buildTextElement(child);\n }\n}\n\nfunction buildTextElement(value: any): VirtualElementText {\n return {\n type: VirtualElementTypesEnum.Text,\n value: String(value),\n };\n}\n\nfunction buildEmptyElement(): VirtualElementEmpty {\n return { type: VirtualElementTypesEnum.Empty };\n}\n\n// eslint-disable-next-line @typescript-eslint/naming-convention\nconst DEBUG_components: AnyLiteral = {};\n\ndocument.addEventListener('dblclick', () => {\n // eslint-disable-next-line no-console\n console.log('COMPONENTS', orderBy(Object.values(DEBUG_components), 'renderCount', 'desc'));\n});\n\nexport function renderComponent(componentInstance: ComponentInstance) {\n renderingInstance = componentInstance;\n componentInstance.hooks.state.cursor = 0;\n componentInstance.hooks.effects.cursor = 0;\n componentInstance.hooks.memos.cursor = 0;\n\n const { Component, props } = componentInstance;\n let newRenderedValue;\n\n try {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n let DEBUG_startAt: number | undefined;\n if (DEBUG) {\n const componentName = componentInstance.name;\n if (!DEBUG_components[componentName]) {\n DEBUG_components[componentName] = {\n componentName,\n renderCount: 0,\n renderTimes: [],\n };\n }\n\n if (DEBUG_MORE) {\n if (componentName !== 'TeactMemoWrapper' && componentName !== 'TeactNContainer') {\n // eslint-disable-next-line no-console\n console.log(`[Teact] Render ${componentName}`);\n }\n }\n\n DEBUG_startAt = performance.now();\n }\n\n newRenderedValue = Component(props);\n\n if (DEBUG) {\n const renderTime = performance.now() - DEBUG_startAt!;\n const componentName = componentInstance.name;\n if (renderTime > 7) {\n // eslint-disable-next-line no-console\n console.warn(`[Teact] Slow component render: ${componentName}, ${Math.round(renderTime)} ms`);\n }\n DEBUG_components[componentName].renderTimes.push(renderTime);\n DEBUG_components[componentName].renderCount++;\n }\n } catch (err) {\n handleError(err);\n\n newRenderedValue = componentInstance.renderedValue;\n }\n\n if (componentInstance.isMounted && newRenderedValue === componentInstance.renderedValue) {\n return componentInstance.$element;\n }\n\n componentInstance.renderedValue = newRenderedValue;\n\n const newChild = buildChildElement(newRenderedValue);\n componentInstance.$element = buildComponentElement(componentInstance, [newChild]);\n\n return componentInstance.$element;\n}\n\nexport function hasElementChanged($old: VirtualElement, $new: VirtualElement) {\n if (typeof $old !== typeof $new) {\n return true;\n } else if ($old.type !== $new.type) {\n return true;\n } else if (isTextElement($old) && isTextElement($new)) {\n return $old.value !== $new.value;\n } else if (isTagElement($old) && isTagElement($new)) {\n return ($old.tag !== $new.tag) || ($old.props.key !== $new.props.key);\n } else if (isComponentElement($old) && isComponentElement($new)) {\n return (\n $old.componentInstance.Component !== $new.componentInstance.Component\n ) || (\n $old.props.key !== $new.props.key\n );\n }\n\n return false;\n}\n\nexport function unmountTree($element: VirtualElement) {\n if (!isRealElement($element)) {\n return;\n }\n\n if (isComponentElement($element)) {\n unmountComponent($element.componentInstance);\n } else if ($element.target) {\n removeAllDelegatedListeners($element.target as HTMLElement);\n // Trying to help GC\n // eslint-disable-next-line no-null/no-null\n $element.target = null as any;\n }\n\n $element.children.forEach(unmountTree);\n}\n\nexport function mountComponent(componentInstance: ComponentInstance) {\n renderComponent(componentInstance);\n componentInstance.isMounted = true;\n return componentInstance.$element;\n}\n\nfunction unmountComponent(componentInstance: ComponentInstance) {\n if (!componentInstance.isMounted) {\n return;\n }\n\n componentInstance.hooks.memos.byCursor.forEach((hook) => {\n // eslint-disable-next-line no-null/no-null\n hook.current = null;\n });\n\n componentInstance.hooks.effects.byCursor.forEach(({ cleanup }) => {\n if (typeof cleanup === 'function') {\n try {\n cleanup();\n } catch (err) {\n handleError(err);\n }\n }\n });\n\n componentInstance.isMounted = false;\n\n helpGc(componentInstance);\n}\n\n// We need to remove all references to DOM objects. We also clean all other references, just in case.\nfunction helpGc(componentInstance: ComponentInstance) {\n /* eslint-disable no-null/no-null */\n\n componentInstance.hooks.effects.byCursor.forEach((hook) => {\n hook.cleanup = null as any;\n hook.effect = null as any;\n hook.dependencies = null as any;\n });\n\n componentInstance.hooks.state.byCursor.forEach((hook) => {\n hook.value = null as any;\n hook.nextValue = null as any;\n hook.setter = null as any;\n });\n\n componentInstance.hooks.memos.byCursor.forEach((hook) => {\n hook.dependencies = null as any;\n });\n\n componentInstance.hooks = null as any;\n componentInstance.$element = null as any;\n componentInstance.renderedValue = null as any;\n componentInstance.Component = null as any;\n componentInstance.props = null as any;\n componentInstance.forceUpdate = null as any;\n componentInstance.onUpdate = null as any;\n\n /* eslint-enable no-null/no-null */\n}\n\nfunction prepareComponentForFrame(componentInstance: ComponentInstance) {\n if (!componentInstance.isMounted) {\n return;\n }\n\n componentInstance.hooks.state.byCursor.forEach((hook) => {\n hook.value = hook.nextValue;\n });\n\n componentInstance.prepareForFrame = throttleWithPrimaryRaf(() => prepareComponentForFrame(componentInstance));\n componentInstance.forceUpdate = throttleWithRaf(() => forceUpdateComponent(componentInstance));\n}\n\nfunction forceUpdateComponent(componentInstance: ComponentInstance) {\n if (!componentInstance.isMounted || !componentInstance.onUpdate) {\n return;\n }\n\n const currentElement = componentInstance.$element;\n\n renderComponent(componentInstance);\n\n if (componentInstance.$element !== currentElement) {\n componentInstance.onUpdate();\n }\n}\n\nexport function getTarget($element: VirtualElement): Node | undefined {\n if (isComponentElement($element)) {\n return getTarget($element.children[0]);\n } else {\n return $element.target;\n }\n}\n\nexport function setTarget($element: VirtualElement, target: Node) {\n if (isComponentElement($element)) {\n setTarget($element.children[0], target);\n } else {\n $element.target = target;\n }\n}\n\nexport function useState(initial?: T): [T, StateHookSetter] {\n const { cursor, byCursor } = renderingInstance.hooks.state;\n\n if (byCursor[cursor] === undefined) {\n byCursor[cursor] = {\n value: initial,\n nextValue: initial,\n setter: ((componentInstance) => (newValue: ((current: T) => T) | T) => {\n if (byCursor[cursor].nextValue !== newValue) {\n byCursor[cursor].nextValue = typeof newValue === 'function'\n ? (newValue as (current: T) => T)(byCursor[cursor].value)\n : newValue;\n\n if (!componentInstance.prepareForFrame || !componentInstance.forceUpdate) {\n componentInstance.prepareForFrame = throttleWithPrimaryRaf(\n () => prepareComponentForFrame(componentInstance),\n );\n componentInstance.forceUpdate = throttleWithRaf(\n () => forceUpdateComponent(componentInstance),\n );\n }\n\n componentInstance.prepareForFrame();\n componentInstance.forceUpdate();\n\n if (DEBUG_MORE) {\n if (componentInstance.name !== 'TeactNContainer') {\n // eslint-disable-next-line no-console\n console.log(\n '[Teact.useState]',\n componentInstance.name,\n // `componentInstance.Component` may be set to `null` by GC helper\n componentInstance.Component && (componentInstance.Component as FC_withDebug).DEBUG_contentComponentName\n ? `> ${(componentInstance.Component as FC_withDebug).DEBUG_contentComponentName}`\n : '',\n `Forced update at cursor #${cursor}, next value: `,\n byCursor[cursor].nextValue,\n );\n }\n }\n }\n })(renderingInstance),\n };\n }\n\n renderingInstance.hooks.state.cursor++;\n\n return [\n byCursor[cursor].value,\n byCursor[cursor].setter,\n ];\n}\n\nfunction useLayoutEffectBase(\n schedulerFn: typeof onTickEnd | typeof requestAnimationFrame,\n primarySchedulerFn: typeof onTickEnd | typeof requestAnimationFrame,\n effect: () => Function | void,\n dependencies?: any[],\n debugKey?: string,\n) {\n const { cursor, byCursor } = renderingInstance.hooks.effects;\n const componentInstance = renderingInstance;\n\n function execCleanup() {\n if (!componentInstance.isMounted) {\n return;\n }\n\n const { cleanup } = byCursor[cursor];\n if (typeof cleanup === 'function') {\n try {\n cleanup();\n } catch (err) {\n handleError(err);\n }\n }\n }\n\n function exec() {\n if (!componentInstance.isMounted) {\n return;\n }\n\n byCursor[cursor].cleanup = effect() as Function;\n }\n\n if (byCursor[cursor] !== undefined && dependencies && byCursor[cursor].dependencies) {\n if (dependencies.some((dependency, i) => dependency !== byCursor[cursor].dependencies![i])) {\n if (debugKey) {\n const causedBy = dependencies.reduce((res, newValue, i) => {\n const prevValue = byCursor[cursor].dependencies![i];\n if (newValue !== prevValue) {\n res.push(`${i}: ${prevValue} => ${newValue}`);\n }\n\n return res;\n }, []);\n\n // eslint-disable-next-line no-console\n console.log(\n '[Teact]',\n debugKey,\n 'Effect caused by dependencies.',\n causedBy.join(', '),\n );\n }\n\n primarySchedulerFn(execCleanup);\n schedulerFn(exec);\n }\n } else {\n primarySchedulerFn(execCleanup);\n schedulerFn(exec);\n }\n\n byCursor[cursor] = {\n effect,\n dependencies,\n cleanup: byCursor[cursor] ? byCursor[cursor].cleanup : undefined,\n };\n\n renderingInstance.hooks.effects.cursor++;\n}\n\nexport function useEffect(effect: () => Function | void, dependencies?: any[], debugKey?: string) {\n return useLayoutEffectBase(fastRaf, fastRafPrimary, effect, dependencies, debugKey);\n}\n\nexport function useLayoutEffect(effect: () => Function | void, dependencies?: any[], debugKey?: string) {\n return useLayoutEffectBase(onTickEnd, onTickEndPrimary, effect, dependencies, debugKey);\n}\n\nexport function useMemo(resolver: () => T, dependencies: any[], debugKey?: string): T {\n const { cursor, byCursor } = renderingInstance.hooks.memos;\n let { current } = byCursor[cursor] || {};\n\n if (\n byCursor[cursor] === undefined\n || dependencies.some((dependency, i) => dependency !== byCursor[cursor].dependencies[i])\n ) {\n if (DEBUG && debugKey) {\n // eslint-disable-next-line no-console\n console.log(\n `[Teact.useMemo] ${renderingInstance.name} (${debugKey}): Update is caused by:`,\n byCursor[cursor]\n ? getUnequalProps(dependencies, byCursor[cursor].dependencies).join(', ')\n : '[first render]',\n );\n }\n\n current = resolver();\n }\n\n byCursor[cursor] = {\n current,\n dependencies,\n };\n\n renderingInstance.hooks.memos.cursor++;\n\n return current;\n}\n\nexport function useCallback(newCallback: F, dependencies: any[]): F {\n // eslint-disable-next-line react-hooks/exhaustive-deps\n return useMemo(() => newCallback, dependencies);\n}\n\nexport function useRef(initial: T): { current: T };\nexport function useRef(): { current: T | undefined }; // TT way (empty is `undefined`)\nexport function useRef(initial: null): { current: T | null }; // React way (empty is `null`)\n// eslint-disable-next-line no-null/no-null\nexport function useRef(initial?: T | null) {\n return useMemo(() => ({\n current: initial,\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }), []);\n}\n\nexport function memo(Component: T, areEqual = arePropsShallowEqual, debugKey?: string) {\n return function TeactMemoWrapper(props: Props) {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n const propsRef = useRef(props);\n const renderedRef = useRef();\n\n if (!renderedRef.current || (propsRef.current && !areEqual(propsRef.current, props))) {\n if (DEBUG && debugKey) {\n // eslint-disable-next-line no-console\n console.log(\n `[Teact.memo] ${Component.name} (${debugKey}): Update is caused by:`,\n getUnequalProps(propsRef.current!, props).join(', '),\n );\n }\n\n propsRef.current = props;\n renderedRef.current = createElement(Component, props) as VirtualElementComponent;\n }\n\n return renderedRef.current;\n } as T;\n}\n\n// We need to keep it here for JSX.\nexport default {\n createElement,\n Fragment,\n};\n","import React, {\n FC, FC_withDebug, Props, useEffect, useState,\n} from './teact';\n\nimport { DEBUG, DEBUG_MORE } from '../../config';\nimport useForceUpdate from '../../hooks/useForceUpdate';\nimport generateIdFor from '../../util/generateIdFor';\nimport { throttleWithRaf } from '../../util/schedulers';\nimport arePropsShallowEqual, { getUnequalProps } from '../../util/arePropsShallowEqual';\nimport { orderBy } from '../../util/iteratees';\nimport { GlobalState, GlobalActions, ActionTypes } from '../../global/types';\nimport { handleError } from '../../util/handleError';\n\nexport default React;\n\ntype ActionPayload = AnyLiteral;\n\ntype Reducer = (\n global: GlobalState,\n actions: GlobalActions,\n payload: any,\n) => GlobalState | void;\n\ntype MapStateToProps = ((global: GlobalState, ownProps: OwnProps) => AnyLiteral | null);\ntype MapActionsToProps = ((setGlobal: Function, actions: GlobalActions) => Partial | null);\n\nlet currentGlobal = {} as GlobalState;\n\nconst reducers: Record = {};\nconst callbacks: Function[] = [updateContainers];\nconst actions = {} as GlobalActions;\nconst containers = new Map;\n mapReducersToProps: MapActionsToProps;\n ownProps: Props;\n mappedProps?: Props;\n forceUpdate: Function;\n areMappedPropsChanged: boolean;\n DEBUG_updates: number;\n DEBUG_componentName: string;\n}>();\n\nfunction runCallbacks() {\n callbacks.forEach((cb) => cb(currentGlobal));\n}\n\nconst runCallbacksThrottled = throttleWithRaf(runCallbacks);\n\n// `noThrottle = true` is used as a workaround for iOS gesture history navigation\nexport function setGlobal(newGlobal?: GlobalState, noThrottle = false) {\n if (typeof newGlobal === 'object' && newGlobal !== currentGlobal) {\n currentGlobal = newGlobal;\n if (!noThrottle) {\n runCallbacksThrottled();\n } else {\n runCallbacks();\n }\n }\n}\n\nexport function getGlobal() {\n return currentGlobal;\n}\n\nexport function getDispatch() {\n return actions;\n}\n\nfunction onDispatch(name: string, payload?: ActionPayload, noThrottle?: boolean) {\n if (reducers[name]) {\n reducers[name].forEach((reducer) => {\n const newGlobal = reducer(currentGlobal, actions, payload);\n if (newGlobal) {\n setGlobal(newGlobal, noThrottle);\n }\n });\n }\n}\n\nfunction updateContainers() {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n let DEBUG_startAt: number | undefined;\n if (DEBUG) {\n DEBUG_startAt = performance.now();\n }\n\n // eslint-disable-next-line no-restricted-syntax\n for (const container of containers.values()) {\n const {\n mapStateToProps, mapReducersToProps, ownProps, mappedProps, forceUpdate,\n } = container;\n\n let newMappedProps;\n\n try {\n newMappedProps = {\n ...mapStateToProps(currentGlobal, ownProps),\n ...mapReducersToProps(setGlobal, actions),\n };\n } catch (err) {\n handleError(err);\n\n return;\n }\n\n if (DEBUG) {\n if (Object.values(newMappedProps).some(Number.isNaN)) {\n // eslint-disable-next-line no-console\n console.warn(\n // eslint-disable-next-line max-len\n `[TeactN] Some of \\`${container.DEBUG_componentName}\\` mappers contain NaN values. This may cause redundant updates because of incorrect equality check.`,\n );\n }\n }\n\n if (Object.keys(newMappedProps).length && !arePropsShallowEqual(mappedProps!, newMappedProps)) {\n if (DEBUG_MORE) {\n // eslint-disable-next-line no-console\n console.log(\n '[TeactN] Will update',\n container.DEBUG_componentName,\n 'caused by',\n getUnequalProps(mappedProps!, newMappedProps).join(', '),\n );\n }\n\n container.mappedProps = newMappedProps;\n container.areMappedPropsChanged = true;\n container.DEBUG_updates++;\n\n forceUpdate();\n }\n }\n\n if (DEBUG) {\n const updateTime = performance.now() - DEBUG_startAt!;\n if (updateTime > 7) {\n // eslint-disable-next-line no-console\n console.warn(`[TeactN] Slow containers update: ${Math.round(updateTime)} ms`);\n }\n }\n}\n\nexport function addReducer(name: ActionTypes, reducer: Reducer) {\n if (!reducers[name]) {\n reducers[name] = [];\n\n actions[name] = (payload?: ActionPayload, noThrottle = false) => {\n onDispatch(name, payload, noThrottle);\n };\n }\n\n reducers[name].push(reducer);\n}\n\nexport function addCallback(cb: Function) {\n callbacks.push(cb);\n}\n\nexport function removeCallback(cb: Function) {\n const index = callbacks.indexOf(cb);\n if (index !== -1) {\n callbacks.splice(index, 1);\n }\n}\n\nexport function withGlobal(\n mapStateToProps: MapStateToProps = () => ({}),\n mapReducersToProps: MapActionsToProps = () => ({}),\n) {\n return (Component: FC) => {\n return function TeactNContainer(props: OwnProps) {\n (TeactNContainer as FC_withDebug).DEBUG_contentComponentName = Component.name;\n\n const [id] = useState(generateIdFor(containers));\n const forceUpdate = useForceUpdate();\n\n useEffect(() => {\n return () => {\n containers.delete(id);\n };\n }, [id]);\n\n let container = containers.get(id);\n if (!container) {\n container = {\n mapStateToProps,\n mapReducersToProps,\n ownProps: props,\n areMappedPropsChanged: false,\n forceUpdate,\n DEBUG_updates: 0,\n DEBUG_componentName: Component.name,\n };\n\n containers.set(id, container);\n }\n\n if (container.areMappedPropsChanged) {\n container.areMappedPropsChanged = false;\n }\n\n if (!container.mappedProps || !arePropsShallowEqual(container.ownProps, props)) {\n container.ownProps = props;\n\n try {\n container.mappedProps = {\n ...mapStateToProps(currentGlobal, props),\n ...mapReducersToProps(setGlobal, actions),\n };\n } catch (err) {\n handleError(err);\n }\n }\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return ;\n };\n };\n}\n\nif (DEBUG) {\n (window as any).getGlobal = getGlobal;\n\n document.addEventListener('dblclick', () => {\n // eslint-disable-next-line no-console\n console.log(\n 'GLOBAL CONTAINERS',\n orderBy(\n Array.from(containers.values())\n .map(({ DEBUG_componentName, DEBUG_updates }) => ({ DEBUG_componentName, DEBUG_updates })),\n 'DEBUG_updates',\n 'desc',\n ),\n );\n });\n}\n","// Copyright Twitter Inc. Licensed under MIT\n// https://github.com/twitter/twemoji-parser/blob/master/LICENSE.md\n// Version 2c193ce 28.05.2021\n\nconst vs16RegExp = /\\uFE0F/g;\n// avoid using a string literal like '\\u200D' here because minifiers expand it inline\nconst zeroWidthJoiner = String.fromCharCode(0x200d);\n\nexport function removeVS16s(rawEmoji) {\n return rawEmoji.indexOf(zeroWidthJoiner) < 0 ? rawEmoji.replace(vs16RegExp, '') : rawEmoji;\n}\n\n// This file is generated by source/emoji/scripts/generate.sh\n// eslint-disable-next-line max-len\nexport default /(?:\\ud83d\\udc68\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83e\\uddd1\\ud83c[\\udffc-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83e\\uddd1\\ud83c[\\udffb\\udffd-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83e\\uddd1\\ud83c[\\udffb\\udffc\\udffe\\udfff]|\\ud83e\\uddd1\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udffd\\udfff]|\\ud83e\\uddd1\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udffe]|\\ud83d\\udc68\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffb\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffc-\\udfff]|\\ud83d\\udc68\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffc\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb\\udffd-\\udfff]|\\ud83d\\udc68\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffd\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb\\udffc\\udffe\\udfff]|\\ud83d\\udc68\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffe\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udffd\\udfff]|\\ud83d\\udc68\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udfff\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udffe]|\\ud83d\\udc69\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffb\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffc-\\udfff]|\\ud83d\\udc69\\ud83c\\udffb\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc69\\ud83c[\\udffc-\\udfff]|\\ud83d\\udc69\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffc\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb\\udffd-\\udfff]|\\ud83d\\udc69\\ud83c\\udffc\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc69\\ud83c[\\udffb\\udffd-\\udfff]|\\ud83d\\udc69\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffd\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb\\udffc\\udffe\\udfff]|\\ud83d\\udc69\\ud83c\\udffd\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc69\\ud83c[\\udffb\\udffc\\udffe\\udfff]|\\ud83d\\udc69\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffe\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udffd\\udfff]|\\ud83d\\udc69\\ud83c\\udffe\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udffd\\udfff]|\\ud83d\\udc69\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udfff\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udffe]|\\ud83d\\udc69\\ud83c\\udfff\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udffe]|\\ud83e\\uddd1\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83e\\uddd1\\ud83c[\\udffc-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffb\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83e\\uddd1\\ud83c[\\udffb\\udffd-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffc\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83e\\uddd1\\ud83c[\\udffb\\udffc\\udffe\\udfff]|\\ud83e\\uddd1\\ud83c\\udffd\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udffd\\udfff]|\\ud83e\\uddd1\\ud83c\\udffe\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udffe]|\\ud83e\\uddd1\\ud83c\\udfff\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68|\\ud83d\\udc69\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d[\\udc68\\udc69]|\\ud83d\\udc68\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68|\\ud83d\\udc69\\u200d\\u2764\\ufe0f\\u200d\\ud83d[\\udc68\\udc69]|\\ud83e\\uddd1\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1|\\ud83d\\udc6b\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc6c\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc6d\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc8f\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc91\\ud83c[\\udffb-\\udfff]|\\ud83d[\\udc6b-\\udc6d\\udc8f\\udc91])|(?:\\ud83d[\\udc68\\udc69]|\\ud83e\\uddd1)(?:\\ud83c[\\udffb-\\udfff])?\\u200d(?:\\u2695\\ufe0f|\\u2696\\ufe0f|\\u2708\\ufe0f|\\ud83c[\\udf3e\\udf73\\udf7c\\udf84\\udf93\\udfa4\\udfa8\\udfeb\\udfed]|\\ud83d[\\udcbb\\udcbc\\udd27\\udd2c\\ude80\\ude92]|\\ud83e[\\uddaf-\\uddb3\\uddbc\\uddbd])|(?:\\ud83c[\\udfcb\\udfcc]|\\ud83d[\\udd74\\udd75]|\\u26f9)((?:\\ud83c[\\udffb-\\udfff]|\\ufe0f)\\u200d[\\u2640\\u2642]\\ufe0f)|(?:\\ud83c[\\udfc3\\udfc4\\udfca]|\\ud83d[\\udc6e\\udc70\\udc71\\udc73\\udc77\\udc81\\udc82\\udc86\\udc87\\ude45-\\ude47\\ude4b\\ude4d\\ude4e\\udea3\\udeb4-\\udeb6]|\\ud83e[\\udd26\\udd35\\udd37-\\udd39\\udd3d\\udd3e\\uddb8\\uddb9\\uddcd-\\uddcf\\uddd4\\uddd6-\\udddd])(?:\\ud83c[\\udffb-\\udfff])?\\u200d[\\u2640\\u2642]\\ufe0f|(?:\\ud83d\\udc68\\u200d\\ud83d\\udc68\\u200d\\ud83d\\udc66\\u200d\\ud83d\\udc66|\\ud83d\\udc68\\u200d\\ud83d\\udc68\\u200d\\ud83d\\udc67\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc68\\u200d\\ud83d\\udc69\\u200d\\ud83d\\udc66\\u200d\\ud83d\\udc66|\\ud83d\\udc68\\u200d\\ud83d\\udc69\\u200d\\ud83d\\udc67\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc69\\u200d\\ud83d\\udc69\\u200d\\ud83d\\udc66\\u200d\\ud83d\\udc66|\\ud83d\\udc69\\u200d\\ud83d\\udc69\\u200d\\ud83d\\udc67\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc68\\u200d\\ud83d\\udc66\\u200d\\ud83d\\udc66|\\ud83d\\udc68\\u200d\\ud83d\\udc67\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc68\\u200d\\ud83d\\udc68\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc68\\u200d\\ud83d\\udc69\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc69\\u200d\\ud83d\\udc66\\u200d\\ud83d\\udc66|\\ud83d\\udc69\\u200d\\ud83d\\udc67\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc69\\u200d\\ud83d\\udc69\\u200d\\ud83d[\\udc66\\udc67]|\\ud83c\\udff3\\ufe0f\\u200d\\u26a7\\ufe0f|\\ud83c\\udff3\\ufe0f\\u200d\\ud83c\\udf08|\\ud83d\\ude36\\u200d\\ud83c\\udf2b\\ufe0f|\\u2764\\ufe0f\\u200d\\ud83d\\udd25|\\u2764\\ufe0f\\u200d\\ud83e\\ude79|\\ud83c\\udff4\\u200d\\u2620\\ufe0f|\\ud83d\\udc15\\u200d\\ud83e\\uddba|\\ud83d\\udc3b\\u200d\\u2744\\ufe0f|\\ud83d\\udc41\\u200d\\ud83d\\udde8|\\ud83d\\udc68\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc69\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc6f\\u200d\\u2640\\ufe0f|\\ud83d\\udc6f\\u200d\\u2642\\ufe0f|\\ud83d\\ude2e\\u200d\\ud83d\\udca8|\\ud83d\\ude35\\u200d\\ud83d\\udcab|\\ud83e\\udd3c\\u200d\\u2640\\ufe0f|\\ud83e\\udd3c\\u200d\\u2642\\ufe0f|\\ud83e\\uddde\\u200d\\u2640\\ufe0f|\\ud83e\\uddde\\u200d\\u2642\\ufe0f|\\ud83e\\udddf\\u200d\\u2640\\ufe0f|\\ud83e\\udddf\\u200d\\u2642\\ufe0f|\\ud83d\\udc08\\u200d\\u2b1b)|[#*0-9]\\ufe0f?\\u20e3|(?:[©®\\u2122\\u265f]\\ufe0f)|(?:\\ud83c[\\udc04\\udd70\\udd71\\udd7e\\udd7f\\ude02\\ude1a\\ude2f\\ude37\\udf21\\udf24-\\udf2c\\udf36\\udf7d\\udf96\\udf97\\udf99-\\udf9b\\udf9e\\udf9f\\udfcd\\udfce\\udfd4-\\udfdf\\udff3\\udff5\\udff7]|\\ud83d[\\udc3f\\udc41\\udcfd\\udd49\\udd4a\\udd6f\\udd70\\udd73\\udd76-\\udd79\\udd87\\udd8a-\\udd8d\\udda5\\udda8\\uddb1\\uddb2\\uddbc\\uddc2-\\uddc4\\uddd1-\\uddd3\\udddc-\\uddde\\udde1\\udde3\\udde8\\uddef\\uddf3\\uddfa\\udecb\\udecd-\\udecf\\udee0-\\udee5\\udee9\\udef0\\udef3]|[\\u203c\\u2049\\u2139\\u2194-\\u2199\\u21a9\\u21aa\\u231a\\u231b\\u2328\\u23cf\\u23ed-\\u23ef\\u23f1\\u23f2\\u23f8-\\u23fa\\u24c2\\u25aa\\u25ab\\u25b6\\u25c0\\u25fb-\\u25fe\\u2600-\\u2604\\u260e\\u2611\\u2614\\u2615\\u2618\\u2620\\u2622\\u2623\\u2626\\u262a\\u262e\\u262f\\u2638-\\u263a\\u2640\\u2642\\u2648-\\u2653\\u2660\\u2663\\u2665\\u2666\\u2668\\u267b\\u267f\\u2692-\\u2697\\u2699\\u269b\\u269c\\u26a0\\u26a1\\u26a7\\u26aa\\u26ab\\u26b0\\u26b1\\u26bd\\u26be\\u26c4\\u26c5\\u26c8\\u26cf\\u26d1\\u26d3\\u26d4\\u26e9\\u26ea\\u26f0-\\u26f5\\u26f8\\u26fa\\u26fd\\u2702\\u2708\\u2709\\u270f\\u2712\\u2714\\u2716\\u271d\\u2721\\u2733\\u2734\\u2744\\u2747\\u2757\\u2763\\u2764\\u27a1\\u2934\\u2935\\u2b05-\\u2b07\\u2b1b\\u2b1c\\u2b50\\u2b55\\u3030\\u303d\\u3297\\u3299])(?:\\ufe0f|(?!\\ufe0e))|(?:(?:\\ud83c[\\udfcb\\udfcc]|\\ud83d[\\udd74\\udd75\\udd90]|[\\u261d\\u26f7\\u26f9\\u270c\\u270d])(?:\\ufe0f|(?!\\ufe0e))|(?:\\ud83c[\\udf85\\udfc2-\\udfc4\\udfc7\\udfca]|\\ud83d[\\udc42\\udc43\\udc46-\\udc50\\udc66-\\udc69\\udc6e\\udc70-\\udc78\\udc7c\\udc81-\\udc83\\udc85-\\udc87\\udcaa\\udd7a\\udd95\\udd96\\ude45-\\ude47\\ude4b-\\ude4f\\udea3\\udeb4-\\udeb6\\udec0\\udecc]|\\ud83e[\\udd0c\\udd0f\\udd18-\\udd1c\\udd1e\\udd1f\\udd26\\udd30-\\udd39\\udd3d\\udd3e\\udd77\\uddb5\\uddb6\\uddb8\\uddb9\\uddbb\\uddcd-\\uddcf\\uddd1-\\udddd]|[\\u270a\\u270b]))(?:\\ud83c[\\udffb-\\udfff])?|(?:\\ud83c\\udff4\\udb40\\udc67\\udb40\\udc62\\udb40\\udc65\\udb40\\udc6e\\udb40\\udc67\\udb40\\udc7f|\\ud83c\\udff4\\udb40\\udc67\\udb40\\udc62\\udb40\\udc73\\udb40\\udc63\\udb40\\udc74\\udb40\\udc7f|\\ud83c\\udff4\\udb40\\udc67\\udb40\\udc62\\udb40\\udc77\\udb40\\udc6c\\udb40\\udc73\\udb40\\udc7f|\\ud83c\\udde6\\ud83c[\\udde8-\\uddec\\uddee\\uddf1\\uddf2\\uddf4\\uddf6-\\uddfa\\uddfc\\uddfd\\uddff]|\\ud83c\\udde7\\ud83c[\\udde6\\udde7\\udde9-\\uddef\\uddf1-\\uddf4\\uddf6-\\uddf9\\uddfb\\uddfc\\uddfe\\uddff]|\\ud83c\\udde8\\ud83c[\\udde6\\udde8\\udde9\\uddeb-\\uddee\\uddf0-\\uddf5\\uddf7\\uddfa-\\uddff]|\\ud83c\\udde9\\ud83c[\\uddea\\uddec\\uddef\\uddf0\\uddf2\\uddf4\\uddff]|\\ud83c\\uddea\\ud83c[\\udde6\\udde8\\uddea\\uddec\\udded\\uddf7-\\uddfa]|\\ud83c\\uddeb\\ud83c[\\uddee-\\uddf0\\uddf2\\uddf4\\uddf7]|\\ud83c\\uddec\\ud83c[\\udde6\\udde7\\udde9-\\uddee\\uddf1-\\uddf3\\uddf5-\\uddfa\\uddfc\\uddfe]|\\ud83c\\udded\\ud83c[\\uddf0\\uddf2\\uddf3\\uddf7\\uddf9\\uddfa]|\\ud83c\\uddee\\ud83c[\\udde8-\\uddea\\uddf1-\\uddf4\\uddf6-\\uddf9]|\\ud83c\\uddef\\ud83c[\\uddea\\uddf2\\uddf4\\uddf5]|\\ud83c\\uddf0\\ud83c[\\uddea\\uddec-\\uddee\\uddf2\\uddf3\\uddf5\\uddf7\\uddfc\\uddfe\\uddff]|\\ud83c\\uddf1\\ud83c[\\udde6-\\udde8\\uddee\\uddf0\\uddf7-\\uddfb\\uddfe]|\\ud83c\\uddf2\\ud83c[\\udde6\\udde8-\\udded\\uddf0-\\uddff]|\\ud83c\\uddf3\\ud83c[\\udde6\\udde8\\uddea-\\uddec\\uddee\\uddf1\\uddf4\\uddf5\\uddf7\\uddfa\\uddff]|\\ud83c\\uddf4\\ud83c\\uddf2|\\ud83c\\uddf5\\ud83c[\\udde6\\uddea-\\udded\\uddf0-\\uddf3\\uddf7-\\uddf9\\uddfc\\uddfe]|\\ud83c\\uddf6\\ud83c\\udde6|\\ud83c\\uddf7\\ud83c[\\uddea\\uddf4\\uddf8\\uddfa\\uddfc]|\\ud83c\\uddf8\\ud83c[\\udde6-\\uddea\\uddec-\\uddf4\\uddf7-\\uddf9\\uddfb\\uddfd-\\uddff]|\\ud83c\\uddf9\\ud83c[\\udde6\\udde8\\udde9\\uddeb-\\udded\\uddef-\\uddf4\\uddf7\\uddf9\\uddfb\\uddfc\\uddff]|\\ud83c\\uddfa\\ud83c[\\udde6\\uddec\\uddf2\\uddf3\\uddf8\\uddfe\\uddff]|\\ud83c\\uddfb\\ud83c[\\udde6\\udde8\\uddea\\uddec\\uddee\\uddf3\\uddfa]|\\ud83c\\uddfc\\ud83c[\\uddeb\\uddf8]|\\ud83c\\uddfd\\ud83c\\uddf0|\\ud83c\\uddfe\\ud83c[\\uddea\\uddf9]|\\ud83c\\uddff\\ud83c[\\udde6\\uddf2\\uddfc]|\\ud83c[\\udccf\\udd8e\\udd91-\\udd9a\\udde6-\\uddff\\ude01\\ude32-\\ude36\\ude38-\\ude3a\\ude50\\ude51\\udf00-\\udf20\\udf2d-\\udf35\\udf37-\\udf7c\\udf7e-\\udf84\\udf86-\\udf93\\udfa0-\\udfc1\\udfc5\\udfc6\\udfc8\\udfc9\\udfcf-\\udfd3\\udfe0-\\udff0\\udff4\\udff8-\\udfff]|\\ud83d[\\udc00-\\udc3e\\udc40\\udc44\\udc45\\udc51-\\udc65\\udc6a\\udc6f\\udc79-\\udc7b\\udc7d-\\udc80\\udc84\\udc88-\\udc8e\\udc90\\udc92-\\udca9\\udcab-\\udcfc\\udcff-\\udd3d\\udd4b-\\udd4e\\udd50-\\udd67\\udda4\\uddfb-\\ude44\\ude48-\\ude4a\\ude80-\\udea2\\udea4-\\udeb3\\udeb7-\\udebf\\udec1-\\udec5\\uded0-\\uded2\\uded5-\\uded7\\udeeb\\udeec\\udef4-\\udefc\\udfe0-\\udfeb]|\\ud83e[\\udd0d\\udd0e\\udd10-\\udd17\\udd1d\\udd20-\\udd25\\udd27-\\udd2f\\udd3a\\udd3c\\udd3f-\\udd45\\udd47-\\udd76\\udd78\\udd7a-\\uddb4\\uddb7\\uddba\\uddbc-\\uddcb\\uddd0\\uddde-\\uddff\\ude70-\\ude74\\ude78-\\ude7a\\ude80-\\ude86\\ude90-\\udea8\\udeb0-\\udeb6\\udec0-\\udec2\\uded0-\\uded6]|[\\u23e9-\\u23ec\\u23f0\\u23f3\\u267e\\u26ce\\u2705\\u2728\\u274c\\u274e\\u2753-\\u2755\\u2795-\\u2797\\u27b0\\u27bf\\ue50a])|\\ufe0f/g;\n","import {\n addReducer, getDispatch, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { initApi, callApi } from '../../../api/gramjs';\nimport { GlobalState } from '../../../global/types';\n\nimport {\n LANG_CACHE_NAME,\n CUSTOM_BG_CACHE_NAME,\n MEDIA_CACHE_NAME,\n MEDIA_CACHE_NAME_AVATARS,\n MEDIA_PROGRESSIVE_CACHE_NAME,\n IS_TEST,\n} from '../../../config';\nimport { IS_MOV_SUPPORTED, PLATFORM_ENV } from '../../../util/environment';\nimport { unsubscribe } from '../../../util/notifications';\nimport * as cacheApi from '../../../util/cacheApi';\nimport { updateAppBadge } from '../../../util/appBadge';\nimport {\n storeSession,\n loadStoredSession,\n clearStoredSession,\n importLegacySession,\n clearLegacySessions,\n} from '../../../util/sessions';\nimport { forceWebsync } from '../../../util/websync';\n\naddReducer('initApi', (global: GlobalState, actions) => {\n (async () => {\n if (!IS_TEST) {\n await importLegacySession();\n void clearLegacySessions();\n }\n\n void initApi(actions.apiUpdate, {\n userAgent: navigator.userAgent,\n platform: PLATFORM_ENV,\n sessionData: loadStoredSession(),\n isTest: window.location.search.includes('test'),\n isMovSupported: IS_MOV_SUPPORTED,\n });\n })();\n});\n\naddReducer('setAuthPhoneNumber', (global, actions, payload) => {\n const { phoneNumber } = payload!;\n\n void callApi('provideAuthPhoneNumber', phoneNumber.replace(/[^\\d]/g, ''));\n\n return {\n ...global,\n authIsLoading: true,\n authError: undefined,\n };\n});\n\naddReducer('setAuthCode', (global, actions, payload) => {\n const { code } = payload!;\n\n void callApi('provideAuthCode', code);\n\n return {\n ...global,\n authIsLoading: true,\n authError: undefined,\n };\n});\n\naddReducer('setAuthPassword', (global, actions, payload) => {\n const { password } = payload!;\n\n void callApi('provideAuthPassword', password);\n\n return {\n ...global,\n authIsLoading: true,\n authError: undefined,\n };\n});\n\naddReducer('uploadProfilePhoto', (global, actions, payload) => {\n const { file } = payload!;\n\n void callApi('uploadProfilePhoto', file);\n});\n\naddReducer('signUp', (global, actions, payload) => {\n const { firstName, lastName } = payload!;\n\n void callApi('provideAuthRegistration', { firstName, lastName });\n\n return {\n ...global,\n authIsLoading: true,\n authError: undefined,\n };\n});\n\naddReducer('returnToAuthPhoneNumber', (global) => {\n void callApi('restartAuth');\n\n return {\n ...global,\n authError: undefined,\n };\n});\n\naddReducer('goToAuthQrCode', (global) => {\n void callApi('restartAuthWithQr');\n\n return {\n ...global,\n authIsLoadingQrCode: true,\n authError: undefined,\n };\n});\n\naddReducer('saveSession', (global, actions, payload) => {\n const { sessionData } = payload;\n\n if (sessionData) {\n storeSession(payload.sessionData, global.currentUserId);\n } else {\n clearStoredSession();\n }\n});\n\naddReducer('signOut', () => {\n (async () => {\n try {\n await unsubscribe();\n await callApi('destroy');\n await forceWebsync(false);\n } catch (err) {\n // Do nothing\n }\n\n getDispatch().reset();\n })();\n});\n\naddReducer('reset', () => {\n clearStoredSession();\n\n void cacheApi.clear(MEDIA_CACHE_NAME);\n void cacheApi.clear(MEDIA_CACHE_NAME_AVATARS);\n void cacheApi.clear(MEDIA_PROGRESSIVE_CACHE_NAME);\n void cacheApi.clear(CUSTOM_BG_CACHE_NAME);\n\n const langCachePrefix = LANG_CACHE_NAME.replace(/\\d+$/, '');\n const langCacheVersion = (LANG_CACHE_NAME.match(/\\d+$/) || [0])[0];\n for (let i = 0; i < langCacheVersion; i++) {\n void cacheApi.clear(`${langCachePrefix}${i === 0 ? '' : i}`);\n }\n\n void clearLegacySessions();\n\n updateAppBadge(0);\n\n getDispatch().init();\n});\n\naddReducer('disconnect', () => {\n (async () => {\n await callApi('disconnect');\n })();\n});\n\naddReducer('loadNearestCountry', (global) => {\n if (global.connectionState !== 'connectionStateReady') {\n return;\n }\n\n (async () => {\n const authNearestCountry = await callApi('fetchNearestCountry');\n\n setGlobal({\n ...getGlobal(),\n authNearestCountry,\n });\n })();\n});\n\naddReducer('setDeviceToken', (global, actions, deviceToken) => {\n setGlobal({\n ...global,\n push: {\n deviceToken,\n subscribedAt: Date.now(),\n },\n });\n});\n\naddReducer('deleteDeviceToken', (global) => {\n const newGlobal = { ...global };\n delete newGlobal.push;\n setGlobal(newGlobal);\n});\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\nimport {\n ApiPrivacyKey, PrivacyVisibility, ProfileEditProgress, InputPrivacyRules, InputPrivacyContact,\n UPLOADING_WALLPAPER_SLUG,\n} from '../../../types';\n\nimport { COUNTRIES_WITH_12H_TIME_FORMAT } from '../../../config';\nimport { callApi } from '../../../api/gramjs';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport { subscribe, unsubscribe } from '../../../util/notifications';\nimport { setTimeFormat } from '../../../util/langProvider';\nimport { selectUser } from '../../selectors';\nimport {\n addUsers, addBlockedContact, updateChats, updateUser, removeBlockedContact, replaceSettings, updateNotifySettings,\n addNotifyExceptions,\n} from '../../reducers';\nimport { isUserId } from '../../helpers';\n\naddReducer('updateProfile', (global, actions, payload) => {\n const {\n photo, firstName, lastName, bio: about, username,\n } = payload!;\n\n (async () => {\n const { currentUserId } = global;\n if (!currentUserId) {\n return;\n }\n\n setGlobal({\n ...getGlobal(),\n profileEdit: {\n progress: ProfileEditProgress.InProgress,\n },\n });\n\n if (photo) {\n await callApi('updateProfilePhoto', photo);\n }\n\n if (firstName || lastName || about) {\n const result = await callApi('updateProfile', { firstName, lastName, about });\n if (result) {\n global = getGlobal();\n const currentUser = currentUserId && selectUser(global, currentUserId);\n\n if (currentUser) {\n setGlobal(updateUser(\n global,\n currentUser.id,\n {\n firstName,\n lastName,\n fullInfo: {\n ...currentUser.fullInfo,\n bio: about,\n },\n },\n ));\n }\n }\n }\n\n if (username) {\n const result = await callApi('updateUsername', username);\n if (result && currentUserId) {\n setGlobal(updateUser(getGlobal(), currentUserId, { username }));\n }\n }\n\n setGlobal({\n ...getGlobal(),\n profileEdit: {\n progress: ProfileEditProgress.Complete,\n },\n });\n })();\n});\n\naddReducer('checkUsername', (global, actions, payload) => {\n const { username } = payload!;\n\n (async () => {\n // No need to check the username if profile update is already in progress\n if (global.profileEdit && global.profileEdit.progress === ProfileEditProgress.InProgress) {\n return;\n }\n\n setGlobal({\n ...global,\n profileEdit: {\n progress: global.profileEdit ? global.profileEdit.progress : ProfileEditProgress.Idle,\n isUsernameAvailable: undefined,\n },\n });\n\n const isUsernameAvailable = await callApi('checkUsername', username);\n\n global = getGlobal();\n setGlobal({\n ...global,\n profileEdit: {\n ...global.profileEdit!,\n isUsernameAvailable,\n },\n });\n })();\n});\n\naddReducer('loadWallpapers', () => {\n (async () => {\n const result = await callApi('fetchWallpapers');\n if (!result) {\n return;\n }\n\n const global = getGlobal();\n setGlobal({\n ...global,\n settings: {\n ...global.settings,\n loadedWallpapers: result.wallpapers,\n },\n });\n })();\n});\n\naddReducer('uploadWallpaper', (global, actions, payload) => {\n const file = payload;\n const previewBlobUrl = URL.createObjectURL(file);\n\n setGlobal({\n ...global,\n settings: {\n ...global.settings,\n loadedWallpapers: [\n {\n slug: UPLOADING_WALLPAPER_SLUG,\n document: {\n fileName: '',\n size: file.size,\n mimeType: file.type,\n previewBlobUrl,\n },\n },\n ...(global.settings.loadedWallpapers || []),\n ],\n },\n });\n\n (async () => {\n const result = await callApi('uploadWallpaper', file);\n if (!result) {\n return;\n }\n\n const { wallpaper } = result;\n\n global = getGlobal();\n if (!global.settings.loadedWallpapers) {\n return;\n }\n\n const firstWallpaper = global.settings.loadedWallpapers[0];\n if (!firstWallpaper || firstWallpaper.slug !== UPLOADING_WALLPAPER_SLUG) {\n return;\n }\n\n const withLocalMedia = {\n ...wallpaper,\n document: {\n ...wallpaper.document,\n previewBlobUrl,\n },\n };\n\n setGlobal({\n ...global,\n settings: {\n ...global.settings,\n loadedWallpapers: [\n withLocalMedia,\n ...global.settings.loadedWallpapers.slice(1),\n ],\n },\n });\n })();\n});\n\naddReducer('loadBlockedContacts', () => {\n (async () => {\n const result = await callApi('fetchBlockedContacts');\n\n if (!result) {\n return;\n }\n\n let newGlobal = getGlobal();\n\n if (result.users?.length) {\n newGlobal = addUsers(newGlobal, buildCollectionByKey(result.users, 'id'));\n }\n if (result.chats?.length) {\n newGlobal = updateChats(newGlobal, buildCollectionByKey(result.chats, 'id'));\n }\n\n newGlobal = {\n ...newGlobal,\n blocked: {\n ...newGlobal.blocked,\n ids: [...(newGlobal.blocked.ids || []), ...result.blockedIds],\n totalCount: result.totalCount,\n },\n };\n\n setGlobal(newGlobal);\n })();\n});\n\naddReducer('blockContact', (global, actions, payload) => {\n const { contactId, accessHash } = payload!;\n\n (async () => {\n const result = await callApi('blockContact', contactId, accessHash);\n if (!result) {\n return;\n }\n\n const newGlobal = getGlobal();\n\n setGlobal(addBlockedContact(newGlobal, contactId));\n })();\n});\n\naddReducer('unblockContact', (global, actions, payload) => {\n const { contactId } = payload!;\n let accessHash: string | undefined;\n const isPrivate = isUserId(contactId);\n\n if (isPrivate) {\n const user = selectUser(global, contactId);\n if (!user) {\n return;\n }\n\n accessHash = user.accessHash;\n }\n\n (async () => {\n const result = await callApi('unblockContact', contactId, accessHash);\n if (!result) {\n return;\n }\n\n const newGlobal = getGlobal();\n\n setGlobal(removeBlockedContact(newGlobal, contactId));\n })();\n});\n\naddReducer('loadAuthorizations', () => {\n (async () => {\n const result = await callApi('fetchAuthorizations');\n if (!result) {\n return;\n }\n\n setGlobal({\n ...getGlobal(),\n activeSessions: result,\n });\n })();\n});\n\naddReducer('terminateAuthorization', (global, actions, payload) => {\n const { hash } = payload!;\n\n (async () => {\n const result = await callApi('terminateAuthorization', hash);\n if (!result) {\n return;\n }\n\n const newGlobal = getGlobal();\n\n setGlobal({\n ...newGlobal,\n activeSessions: newGlobal.activeSessions.filter((session) => session.hash !== hash),\n });\n })();\n});\n\naddReducer('terminateAllAuthorizations', () => {\n (async () => {\n const result = await callApi('terminateAllAuthorizations');\n if (!result) {\n return;\n }\n\n const global = getGlobal();\n\n setGlobal({\n ...global,\n activeSessions: global.activeSessions.filter((session) => session.isCurrent),\n });\n })();\n});\n\naddReducer('loadNotificationExceptions', (global) => {\n const { serverTimeOffset } = global;\n\n (async () => {\n const result = await callApi('fetchNotificationExceptions', { serverTimeOffset });\n if (!result) {\n return;\n }\n\n setGlobal(addNotifyExceptions(getGlobal(), result));\n })();\n});\n\naddReducer('loadNotificationSettings', (global) => {\n const { serverTimeOffset } = global;\n (async () => {\n const result = await callApi('fetchNotificationSettings', {\n serverTimeOffset,\n });\n if (!result) {\n return;\n }\n\n setGlobal(replaceSettings(getGlobal(), result));\n })();\n});\n\naddReducer('updateNotificationSettings', (global, actions, payload) => {\n const { peerType, isSilent, shouldShowPreviews } = payload!;\n\n (async () => {\n const result = await callApi('updateNotificationSettings', peerType, { isSilent, shouldShowPreviews });\n\n if (!result) {\n return;\n }\n\n setGlobal(updateNotifySettings(getGlobal(), peerType, isSilent, shouldShowPreviews));\n })();\n});\n\naddReducer('updateWebNotificationSettings', (global, actions, payload) => {\n (async () => {\n setGlobal(replaceSettings(getGlobal(), payload));\n const newGlobal = getGlobal();\n const { hasPushNotifications, hasWebNotifications } = newGlobal.settings.byKey;\n if (hasWebNotifications && hasPushNotifications) {\n await subscribe();\n } else {\n await unsubscribe();\n }\n })();\n});\n\naddReducer('updateContactSignUpNotification', (global, actions, payload) => {\n const { isSilent } = payload!;\n\n (async () => {\n const result = await callApi('updateContactSignUpNotification', isSilent);\n if (!result) {\n return;\n }\n\n setGlobal(replaceSettings(getGlobal(), { hasContactJoinedNotifications: !isSilent }));\n })();\n});\n\naddReducer('loadLanguages', () => {\n (async () => {\n const result = await callApi('fetchLanguages');\n if (!result) {\n return;\n }\n\n setGlobal(replaceSettings(getGlobal(), { languages: result }));\n })();\n});\n\naddReducer('loadPrivacySettings', () => {\n (async () => {\n const [\n phoneNumberSettings, lastSeenSettings, profilePhotoSettings, forwardsSettings, chatInviteSettings,\n ] = await Promise.all([\n callApi('fetchPrivacySettings', 'phoneNumber'),\n callApi('fetchPrivacySettings', 'lastSeen'),\n callApi('fetchPrivacySettings', 'profilePhoto'),\n callApi('fetchPrivacySettings', 'forwards'),\n callApi('fetchPrivacySettings', 'chatInvite'),\n ]);\n\n if (\n !phoneNumberSettings || !lastSeenSettings || !profilePhotoSettings || !forwardsSettings || !chatInviteSettings\n ) {\n return;\n }\n\n const global = getGlobal();\n\n global.settings.privacy.phoneNumber = phoneNumberSettings;\n global.settings.privacy.lastSeen = lastSeenSettings;\n global.settings.privacy.profilePhoto = profilePhotoSettings;\n global.settings.privacy.forwards = forwardsSettings;\n global.settings.privacy.chatInvite = chatInviteSettings;\n\n setGlobal(global);\n })();\n});\n\naddReducer('setPrivacyVisibility', (global, actions, payload) => {\n const { privacyKey, visibility } = payload!;\n\n const {\n privacy: { [privacyKey as ApiPrivacyKey]: settings },\n } = global.settings;\n\n if (!settings) {\n return;\n }\n\n const rules = buildInputPrivacyRules(global, {\n visibility,\n allowedIds: [...settings.allowUserIds, ...settings.allowChatIds],\n deniedIds: [...settings.blockUserIds, ...settings.blockChatIds],\n });\n\n (async () => {\n const result = await callApi('setPrivacySettings', privacyKey, rules);\n\n if (result) {\n const newGlobal = getGlobal();\n\n newGlobal.settings.privacy[privacyKey as ApiPrivacyKey] = result;\n\n setGlobal(newGlobal);\n }\n })();\n});\n\naddReducer('setPrivacySettings', (global, actions, payload) => {\n const { privacyKey, isAllowList, contactsIds } = payload!;\n const {\n privacy: { [privacyKey as ApiPrivacyKey]: settings },\n } = global.settings;\n\n if (!settings) {\n return;\n }\n\n const rules = buildInputPrivacyRules(global, {\n visibility: settings.visibility,\n allowedIds: isAllowList ? contactsIds : [...settings.allowUserIds, ...settings.allowChatIds],\n deniedIds: !isAllowList ? contactsIds : [...settings.blockUserIds, ...settings.blockChatIds],\n });\n\n (async () => {\n const result = await callApi('setPrivacySettings', privacyKey, rules);\n\n if (result) {\n const newGlobal = getGlobal();\n\n newGlobal.settings.privacy[privacyKey as ApiPrivacyKey] = result;\n\n setGlobal(newGlobal);\n }\n })();\n});\n\nfunction buildInputPrivacyRules(global: GlobalState, {\n visibility,\n allowedIds,\n deniedIds,\n}: {\n visibility: PrivacyVisibility;\n allowedIds: string[];\n deniedIds: string[];\n}): InputPrivacyRules {\n const {\n users: { byId: usersById },\n chats: { byId: chatsById },\n } = global;\n\n const rules: InputPrivacyRules = {\n visibility,\n };\n let users: InputPrivacyContact[];\n let chats: InputPrivacyContact[];\n\n const collectUsers = (userId: string) => {\n if (!isUserId(userId)) {\n return undefined;\n }\n const { id, accessHash } = usersById[userId] || {};\n if (!id) {\n return undefined;\n }\n\n return { id, accessHash };\n };\n\n const collectChats = (userId: string) => {\n if (isUserId(userId)) {\n return undefined;\n }\n const chat = chatsById[userId];\n\n return chat ? { id: chat.id } : undefined;\n };\n\n if (visibility === 'contacts' || visibility === 'nobody') {\n users = allowedIds.map(collectUsers).filter(Boolean) as InputPrivacyContact[];\n chats = allowedIds.map(collectChats).filter(Boolean) as InputPrivacyContact[];\n\n if (users.length > 0) {\n rules.allowedUsers = users;\n }\n if (chats.length > 0) {\n rules.allowedChats = chats;\n }\n }\n\n if (visibility === 'everybody' || visibility === 'contacts') {\n users = deniedIds.map(collectUsers).filter(Boolean) as InputPrivacyContact[];\n chats = deniedIds.map(collectChats).filter(Boolean) as InputPrivacyContact[];\n\n if (users.length > 0) {\n rules.blockedUsers = users;\n }\n if (chats.length > 0) {\n rules.blockedChats = chats;\n }\n }\n\n return rules;\n}\n\naddReducer('updateIsOnline', (global, actions, payload) => {\n callApi('updateIsOnline', payload);\n});\n\naddReducer('loadContentSettings', () => {\n (async () => {\n const result = await callApi('fetchContentSettings');\n if (!result) return;\n\n setGlobal(replaceSettings(getGlobal(), result));\n })();\n});\n\naddReducer('updateContentSettings', (global, actions, payload) => {\n (async () => {\n setGlobal(replaceSettings(getGlobal(), { isSensitiveEnabled: payload }));\n\n const result = await callApi('updateContentSettings', payload);\n if (!result) {\n setGlobal(replaceSettings(getGlobal(), { isSensitiveEnabled: !payload }));\n }\n })();\n});\n\naddReducer('loadCountryList', (global, actions, payload = {}) => {\n let { langCode } = payload;\n if (!langCode) langCode = global.settings.byKey.language;\n\n (async () => {\n const countryList = await callApi('fetchCountryList', { langCode });\n if (!countryList) return;\n\n setGlobal({\n ...getGlobal(),\n countryList,\n });\n })();\n});\n\naddReducer('ensureTimeFormat', (global, actions) => {\n if (global.authNearestCountry) {\n const timeFormat = COUNTRIES_WITH_12H_TIME_FORMAT.has(global.authNearestCountry.toUpperCase()) ? '12h' : '24h';\n actions.setSettingOption({ timeFormat });\n setTimeFormat(timeFormat);\n }\n\n (async () => {\n if (getGlobal().settings.byKey.wasTimeFormatSetManually) {\n return;\n }\n\n const nearestCountryCode = await callApi('fetchNearestCountry');\n if (nearestCountryCode) {\n const timeFormat = COUNTRIES_WITH_12H_TIME_FORMAT.has(nearestCountryCode.toUpperCase()) ? '12h' : '24h';\n actions.setSettingOption({ timeFormat });\n setTimeFormat(timeFormat);\n }\n })();\n});\n","import {\n addReducer, getDispatch, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\n\nimport {\n ApiUpdate,\n ApiUpdateAuthorizationState,\n ApiUpdateAuthorizationError,\n ApiUpdateConnectionState,\n ApiUpdateSession,\n ApiUpdateCurrentUser, ApiUpdateServerTimeOffset,\n} from '../../../api/types';\nimport { DEBUG, SESSION_USER_KEY } from '../../../config';\nimport { subscribe } from '../../../util/notifications';\nimport { updateUser } from '../../reducers';\nimport { setLanguage } from '../../../util/langProvider';\nimport { selectNotifySettings } from '../../selectors';\nimport { forceWebsync } from '../../../util/websync';\nimport { getShippingError } from '../../../util/getReadableErrorText';\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n if (DEBUG) {\n if (update['@type'] !== 'updateUserStatus' && update['@type'] !== 'updateServerTimeOffset') {\n // eslint-disable-next-line no-console\n console.log('[GramJs] UPDATE', update['@type'], { update });\n }\n }\n\n switch (update['@type']) {\n case 'updateApiReady':\n onUpdateApiReady(global);\n break;\n\n case 'updateAuthorizationState':\n onUpdateAuthorizationState(update);\n break;\n\n case 'updateAuthorizationError':\n onUpdateAuthorizationError(update);\n break;\n\n case 'updateConnectionState':\n onUpdateConnectionState(update);\n break;\n\n case 'updateSession':\n onUpdateSession(update);\n break;\n\n case 'updateServerTimeOffset':\n onUpdateServerTimeOffset(update);\n break;\n\n case 'updateCurrentUser':\n onUpdateCurrentUser(update);\n break;\n\n case 'error': {\n if (update.error.message === 'SESSION_REVOKED') {\n actions.signOut();\n }\n\n const paymentShippingError = getShippingError(update.error);\n if (paymentShippingError) {\n actions.addPaymentError({ error: paymentShippingError });\n } else if (actions.showDialog) {\n actions.showDialog({ data: { ...update.error, hasErrorKey: true } });\n }\n\n break;\n }\n }\n});\n\nfunction onUpdateApiReady(global: GlobalState) {\n const { hasWebNotifications, hasPushNotifications } = selectNotifySettings(global);\n if (hasWebNotifications && hasPushNotifications) {\n void subscribe();\n }\n void setLanguage(global.settings.byKey.language);\n}\n\nfunction onUpdateAuthorizationState(update: ApiUpdateAuthorizationState) {\n let global = getGlobal();\n\n const wasAuthReady = global.authState === 'authorizationStateReady';\n const authState = update.authorizationState;\n\n setGlobal({\n ...global,\n authState,\n authIsLoading: false,\n });\n\n global = getGlobal();\n\n switch (authState) {\n case 'authorizationStateLoggingOut':\n void forceWebsync(false);\n\n setGlobal({\n ...global,\n isLoggingOut: true,\n });\n break;\n case 'authorizationStateWaitCode':\n setGlobal({\n ...global,\n authIsCodeViaApp: update.isCodeViaApp,\n });\n break;\n case 'authorizationStateWaitPassword':\n setGlobal({\n ...global,\n authHint: update.hint,\n });\n break;\n case 'authorizationStateWaitQrCode':\n setGlobal({\n ...global,\n authIsLoadingQrCode: false,\n authQrCode: update.qrCode,\n });\n break;\n case 'authorizationStateReady': {\n if (wasAuthReady) {\n break;\n }\n\n void forceWebsync(true);\n\n setGlobal({\n ...global,\n isLoggingOut: false,\n lastSyncTime: Date.now(),\n });\n\n break;\n }\n }\n}\n\nfunction onUpdateAuthorizationError(update: ApiUpdateAuthorizationError) {\n setGlobal({\n ...getGlobal(),\n authError: update.message,\n });\n}\n\nfunction onUpdateConnectionState(update: ApiUpdateConnectionState) {\n const { connectionState } = update;\n const global = getGlobal();\n\n setGlobal({\n ...global,\n connectionState,\n });\n\n if (connectionState === 'connectionStateReady' && global.authState === 'authorizationStateReady') {\n getDispatch().sync();\n } else if (connectionState === 'connectionStateBroken') {\n getDispatch().signOut();\n }\n}\n\nfunction onUpdateSession(update: ApiUpdateSession) {\n const { sessionData } = update;\n const { authRememberMe, authState } = getGlobal();\n const isEmpty = !sessionData || !sessionData.mainDcId;\n\n if (!authRememberMe || authState !== 'authorizationStateReady' || isEmpty) {\n return;\n }\n\n getDispatch().saveSession({ sessionData });\n}\n\nfunction onUpdateServerTimeOffset(update: ApiUpdateServerTimeOffset) {\n const global = getGlobal();\n\n if (global.serverTimeOffset === update.serverTimeOffset) {\n return;\n }\n\n setGlobal({\n ...global,\n serverTimeOffset: update.serverTimeOffset,\n });\n}\n\nfunction onUpdateCurrentUser(update: ApiUpdateCurrentUser) {\n const { currentUser } = update;\n\n setGlobal({\n ...updateUser(getGlobal(), currentUser.id, currentUser),\n currentUserId: currentUser.id,\n });\n\n updateSessionUserId(currentUser.id);\n}\n\nfunction updateSessionUserId(currentUserId: string) {\n const sessionUserAuth = localStorage.getItem(SESSION_USER_KEY);\n if (!sessionUserAuth) return;\n\n const userAuth = JSON.parse(sessionUserAuth);\n userAuth.id = currentUserId;\n\n localStorage.setItem(SESSION_USER_KEY, JSON.stringify(userAuth));\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { ANIMATION_LEVEL_MAX } from '../../../config';\nimport {\n IS_ANDROID, IS_IOS, IS_MAC_OS, IS_TOUCH_ENV,\n} from '../../../util/environment';\nimport { setLanguage } from '../../../util/langProvider';\nimport switchTheme from '../../../util/switchTheme';\nimport { selectTheme } from '../../selectors';\nimport { startWebsync } from '../../../util/websync';\n\nconst HISTORY_ANIMATION_DURATION = 450;\n\nsubscribeToSystemThemeChange();\n\naddReducer('init', (global) => {\n const { animationLevel, messageTextSize, language } = global.settings.byKey;\n const theme = selectTheme(global);\n\n void setLanguage(language, undefined, true);\n\n document.documentElement.style.setProperty(\n '--composer-text-size', `${Math.max(messageTextSize, IS_IOS ? 16 : 15)}px`,\n );\n document.documentElement.style.setProperty('--message-meta-height', `${Math.floor(messageTextSize * 1.3125)}px`);\n document.documentElement.style.setProperty('--message-text-size', `${messageTextSize}px`);\n document.documentElement.setAttribute('data-message-text-size', messageTextSize.toString());\n document.body.classList.add('initial');\n document.body.classList.add(`animation-level-${animationLevel}`);\n document.body.classList.add(IS_TOUCH_ENV ? 'is-touch-env' : 'is-pointer-env');\n switchTheme(theme, animationLevel === ANIMATION_LEVEL_MAX);\n startWebsync();\n\n if (IS_IOS) {\n document.body.classList.add('is-ios');\n } else if (IS_ANDROID) {\n document.body.classList.add('is-android');\n } else if (IS_MAC_OS) {\n document.body.classList.add('is-macos');\n }\n});\n\naddReducer('setIsUiReady', (global, actions, payload) => {\n const { uiReadyState } = payload!;\n\n if (uiReadyState === 2) {\n document.body.classList.remove('initial');\n }\n\n return {\n ...global,\n uiReadyState,\n };\n});\n\naddReducer('setAuthPhoneNumber', (global, actions, payload) => {\n const { phoneNumber } = payload!;\n\n return {\n ...global,\n authPhoneNumber: phoneNumber,\n };\n});\n\naddReducer('setAuthRememberMe', (global, actions, payload) => {\n return {\n ...global,\n authRememberMe: Boolean(payload),\n };\n});\n\naddReducer('clearAuthError', (global) => {\n return {\n ...global,\n authError: undefined,\n };\n});\n\naddReducer('disableHistoryAnimations', () => {\n setTimeout(() => {\n setGlobal({\n ...getGlobal(),\n shouldSkipHistoryAnimations: false,\n });\n document.body.classList.remove('no-animate');\n }, HISTORY_ANIMATION_DURATION);\n\n setGlobal({\n ...getGlobal(),\n shouldSkipHistoryAnimations: true,\n }, true);\n});\n\nfunction subscribeToSystemThemeChange() {\n function handleSystemThemeChange() {\n const currentThemeMatch = document.documentElement.className.match(/theme-(\\w+)/);\n const currentTheme = currentThemeMatch ? currentThemeMatch[1] : 'light';\n const global = getGlobal();\n const nextTheme = selectTheme(global);\n const { animationLevel } = global.settings.byKey;\n\n if (nextTheme !== currentTheme) {\n switchTheme(nextTheme, animationLevel === ANIMATION_LEVEL_MAX);\n // Force-update component containers\n setGlobal({ ...global });\n }\n }\n\n const mql = window.matchMedia('(prefers-color-scheme: dark)');\n if (typeof mql.addEventListener === 'function') {\n mql.addEventListener('change', handleSystemThemeChange);\n } else if (typeof mql.addListener === 'function') {\n mql.addListener(handleSystemThemeChange);\n }\n}\n","import { addReducer } from '../../../lib/teact/teactn';\nimport { ISettings, IThemeSettings, ThemeKey } from '../../../types';\nimport { replaceSettings, replaceThemeSettings } from '../../reducers';\n\naddReducer('setSettingOption', (global, actions, payload?: Partial) => {\n return replaceSettings(global, payload);\n});\n\naddReducer('setThemeSettings', (global, actions, payload: { theme: ThemeKey } & Partial) => {\n const { theme, ...settings } = payload;\n\n return replaceThemeSettings(global, theme, settings);\n});\n","import {\n ApiChat,\n ApiUser,\n ApiChatBannedRights,\n ApiChatAdminRights,\n ApiChatFolder,\n MAIN_THREAD_ID,\n} from '../../api/types';\n\nimport { NotifyException, NotifySettings } from '../../types';\nimport { LangFn } from '../../hooks/useLang';\n\nimport { ARCHIVED_FOLDER_ID, REPLIES_USER_ID } from '../../config';\nimport { orderBy } from '../../util/iteratees';\nimport { getUserFirstOrLastName } from './users';\nimport { formatDateToString, formatTime } from '../../util/dateFormat';\n\nconst FOREVER_BANNED_DATE = Date.now() / 1000 + 31622400; // 366 days\n\nconst VERIFIED_PRIORITY_BASE = 3e9;\nconst PINNED_PRIORITY_BASE = 3e8;\n\nexport function isUserId(entityId: string) {\n // Workaround for old-fashioned IDs stored locally\n if (typeof entityId === 'number') {\n return entityId > 0;\n }\n\n return !entityId.startsWith('-');\n}\n\nexport function isChatGroup(chat: ApiChat) {\n return isChatBasicGroup(chat) || isChatSuperGroup(chat);\n}\n\nexport function isChatBasicGroup(chat: ApiChat) {\n return chat.type === 'chatTypeBasicGroup';\n}\n\nexport function isChatSuperGroup(chat: ApiChat) {\n return chat.type === 'chatTypeSuperGroup';\n}\n\nexport function isChatChannel(chat: ApiChat) {\n return chat.type === 'chatTypeChannel';\n}\n\nexport function isCommonBoxChat(chat: ApiChat) {\n return chat.type === 'chatTypePrivate' || chat.type === 'chatTypeBasicGroup';\n}\n\nexport function isChatWithRepliesBot(chatId: string) {\n return chatId === REPLIES_USER_ID;\n}\n\nexport function getChatTypeString(chat: ApiChat) {\n switch (chat.type) {\n case 'chatTypePrivate':\n return 'PrivateChat';\n case 'chatTypeBasicGroup':\n case 'chatTypeSuperGroup':\n return 'AccDescrGroup';\n case 'chatTypeChannel':\n return 'AccDescrChannel';\n default:\n return 'Chat';\n }\n}\n\nexport function getPrivateChatUserId(chat: ApiChat) {\n if (chat.type !== 'chatTypePrivate' && chat.type !== 'chatTypeSecret') {\n return undefined;\n }\n return chat.id;\n}\n\n// TODO Get rid of `user`\nexport function getChatTitle(lang: LangFn, chat: ApiChat, user?: ApiUser, isSelf = false) {\n if (isSelf || (user && chat.id === user.id && user.isSelf)) {\n return lang('SavedMessages');\n }\n return chat.title || lang('HiddenName');\n}\n\nexport function getChatDescription(chat: ApiChat) {\n if (!chat.fullInfo) {\n return undefined;\n }\n return chat.fullInfo.about;\n}\n\nexport function getChatLink(chat: ApiChat) {\n const { username } = chat;\n if (username) {\n return `https://t.me/${username}`;\n }\n\n const { inviteLink } = chat.fullInfo || {};\n\n return inviteLink;\n}\n\nexport function getChatAvatarHash(\n owner: ApiChat | ApiUser,\n size: 'normal' | 'big' = 'normal',\n) {\n if (!owner.avatarHash) {\n return undefined;\n }\n\n switch (size) {\n case 'big':\n return `profile${owner.id}?${owner.avatarHash}`;\n default:\n return `avatar${owner.id}?${owner.avatarHash}`;\n }\n}\n\nexport function isChatSummaryOnly(chat: ApiChat) {\n return !chat.lastMessage;\n}\n\nexport function isChatAdmin(chat: ApiChat) {\n return Boolean(chat.adminRights);\n}\n\nexport function getHasAdminRight(chat: ApiChat, key: keyof ApiChatAdminRights) {\n return chat.adminRights ? chat.adminRights[key] : false;\n}\n\nexport function isUserRightBanned(chat: ApiChat, key: keyof ApiChatBannedRights) {\n return Boolean(\n (chat.currentUserBannedRights?.[key])\n || (chat.defaultBannedRights?.[key]),\n );\n}\n\nexport function getCanPostInChat(chat: ApiChat, threadId: number) {\n if (threadId !== MAIN_THREAD_ID) {\n return true;\n }\n\n if (chat.isRestricted || chat.migratedTo || chat.isNotJoined || isChatWithRepliesBot(chat.id)) {\n return false;\n }\n\n if (chat.isCreator) {\n return true;\n }\n\n if (isUserId(chat.id)) {\n return true;\n }\n\n if (isChatChannel(chat)) {\n return getHasAdminRight(chat, 'postMessages');\n }\n\n return isChatAdmin(chat) || !isUserRightBanned(chat, 'sendMessages');\n}\n\nexport interface IAllowedAttachmentOptions {\n canAttachMedia: boolean;\n canAttachPolls: boolean;\n canSendStickers: boolean;\n canSendGifs: boolean;\n canAttachEmbedLinks: boolean;\n}\n\nexport function getAllowedAttachmentOptions(chat?: ApiChat, isChatWithBot = false): IAllowedAttachmentOptions {\n if (!chat) {\n return {\n canAttachMedia: false,\n canAttachPolls: false,\n canSendStickers: false,\n canSendGifs: false,\n canAttachEmbedLinks: false,\n };\n }\n\n const isAdmin = isChatAdmin(chat);\n\n return {\n canAttachMedia: isAdmin || !isUserRightBanned(chat, 'sendMedia'),\n canAttachPolls: (isAdmin || !isUserRightBanned(chat, 'sendPolls')) && (!isUserId(chat.id) || isChatWithBot),\n canSendStickers: isAdmin || !isUserRightBanned(chat, 'sendStickers'),\n canSendGifs: isAdmin || !isUserRightBanned(chat, 'sendGifs'),\n canAttachEmbedLinks: isAdmin || !isUserRightBanned(chat, 'embedLinks'),\n };\n}\n\nexport function getMessageSendingRestrictionReason(\n lang: LangFn,\n currentUserBannedRights?: ApiChatBannedRights,\n defaultBannedRights?: ApiChatBannedRights,\n) {\n if (currentUserBannedRights?.sendMessages) {\n const { untilDate } = currentUserBannedRights;\n return untilDate && untilDate < FOREVER_BANNED_DATE\n ? lang(\n 'Channel.Persmission.Denied.SendMessages.Until',\n lang(\n 'formatDateAtTime',\n [formatDateToString(new Date(untilDate * 1000), lang.code), formatTime(untilDate * 1000, lang)],\n ),\n )\n : lang('Channel.Persmission.Denied.SendMessages.Forever');\n }\n\n if (defaultBannedRights?.sendMessages) {\n return lang('Channel.Persmission.Denied.SendMessages.DefaultRestrictedText');\n }\n\n return undefined;\n}\n\nexport function getChatSlowModeOptions(chat?: ApiChat) {\n if (!chat || !chat.fullInfo) {\n return undefined;\n }\n\n return chat.fullInfo.slowMode;\n}\n\nexport function getChatOrder(chat: ApiChat) {\n return Math.max(\n chat.joinDate || 0,\n chat.draftDate || 0,\n chat.lastMessage ? chat.lastMessage.date : 0,\n );\n}\n\nexport function isChatArchived(chat: ApiChat) {\n return chat.folderId === ARCHIVED_FOLDER_ID;\n}\n\nexport function selectIsChatMuted(\n chat: ApiChat, notifySettings: NotifySettings, notifyExceptions: Record = {},\n) {\n // If this chat is in exceptions they take precedence\n if (notifyExceptions[chat.id] && notifyExceptions[chat.id].isMuted !== undefined) {\n return notifyExceptions[chat.id].isMuted;\n }\n\n return (\n chat.isMuted\n || (isUserId(chat.id) && !notifySettings.hasPrivateChatsNotifications)\n || (isChatChannel(chat) && !notifySettings.hasBroadcastNotifications)\n || (isChatGroup(chat) && !notifySettings.hasGroupNotifications)\n );\n}\n\nexport function selectShouldShowMessagePreview(\n chat: ApiChat, notifySettings: NotifySettings, notifyExceptions: Record = {},\n) {\n const {\n hasPrivateChatsMessagePreview = true,\n hasBroadcastMessagePreview = true,\n hasGroupMessagePreview = true,\n } = notifySettings;\n // If this chat is in exceptions they take precedence\n if (notifyExceptions[chat.id] && notifyExceptions[chat.id].shouldShowPreviews !== undefined) {\n return notifyExceptions[chat.id].shouldShowPreviews;\n }\n\n return (isUserId(chat.id) && hasPrivateChatsMessagePreview)\n || (isChatChannel(chat) && hasBroadcastMessagePreview)\n || (isChatGroup(chat) && hasGroupMessagePreview);\n}\n\nexport function getCanDeleteChat(chat: ApiChat) {\n return isChatBasicGroup(chat) || ((isChatSuperGroup(chat) || isChatChannel(chat)) && chat.isCreator);\n}\n\nexport function prepareFolderListIds(\n chatsById: Record,\n usersById: Record,\n folder: ApiChatFolder,\n notifySettings: NotifySettings,\n notifyExceptions?: Record,\n chatIdsCache?: string[],\n) {\n const excludedChatIds = folder.excludedChatIds ? new Set(folder.excludedChatIds) : undefined;\n const includedChatIds = folder.excludedChatIds ? new Set(folder.includedChatIds) : undefined;\n const pinnedChatIds = folder.excludedChatIds ? new Set(folder.pinnedChatIds) : undefined;\n const listIds = (chatIdsCache || Object.keys(chatsById))\n .filter((id) => {\n return filterChatFolder(\n chatsById[id],\n folder,\n usersById,\n notifySettings,\n notifyExceptions,\n excludedChatIds,\n includedChatIds,\n pinnedChatIds,\n );\n });\n\n return [listIds, folder.pinnedChatIds] as const;\n}\n\nfunction filterChatFolder(\n chat: ApiChat,\n folder: ApiChatFolder,\n usersById: Record,\n notifySettings: NotifySettings,\n notifyExceptions?: Record,\n excludedChatIds?: Set,\n includedChatIds?: Set,\n pinnedChatIds?: Set,\n) {\n if (!chat.isListed) {\n return false;\n }\n\n if (excludedChatIds && excludedChatIds.has(chat.id)) {\n return false;\n }\n\n if (includedChatIds && includedChatIds.has(chat.id)) {\n return true;\n }\n\n if (pinnedChatIds && pinnedChatIds.has(chat.id)) {\n return true;\n }\n\n if (isChatArchived(chat) && folder.excludeArchived) {\n return false;\n }\n\n if (folder.excludeMuted && !chat.unreadMentionsCount && selectIsChatMuted(chat, notifySettings, notifyExceptions)) {\n return false;\n }\n\n if (!chat.unreadCount && !chat.unreadMentionsCount && !chat.hasUnreadMark && folder.excludeRead) {\n return false;\n }\n\n if (isUserId(chat.id)) {\n const privateChatUser = usersById[chat.id];\n\n const isChatWithBot = privateChatUser && privateChatUser.type === 'userTypeBot';\n if (isChatWithBot) {\n if (folder.bots) {\n return true;\n }\n } else {\n if (folder.contacts && privateChatUser && privateChatUser.isContact) {\n return true;\n }\n\n if (folder.nonContacts && privateChatUser && !privateChatUser.isContact) {\n return true;\n }\n }\n } else if (isChatGroup(chat)) {\n return !!folder.groups;\n } else if (isChatChannel(chat)) {\n return !!folder.channels;\n }\n\n return false;\n}\n\nexport function prepareChatList(\n chatsById: Record,\n listIds: string[],\n orderedPinnedIds?: string[],\n folderType: 'all' | 'archived' | 'folder' = 'all',\n) {\n function chatFilter(chat?: ApiChat) {\n if (!chat || !chat.lastMessage || chat.migratedTo) {\n return false;\n }\n\n switch (folderType) {\n case 'all':\n if (isChatArchived(chat)) {\n return false;\n }\n break;\n case 'archived':\n if (!isChatArchived(chat)) {\n return false;\n }\n break;\n }\n\n return !chat.isRestricted && !chat.isNotJoined;\n }\n\n const listedChats = listIds\n .map((id) => chatsById[id])\n .filter(chatFilter);\n\n const listIdsSet = new Set(listIds);\n const pinnedChats = orderedPinnedIds\n ? (\n orderedPinnedIds\n .map((id) => chatsById[id])\n .filter(chatFilter)\n .filter((chat) => listIdsSet.has(chat.id))\n )\n : [];\n\n const otherChats = orderBy(\n orderedPinnedIds\n ? listedChats.filter((chat) => !orderedPinnedIds.includes(chat.id))\n : listedChats,\n getChatOrder,\n 'desc',\n );\n\n return {\n pinnedChats,\n otherChats,\n };\n}\n\nexport function getFolderUnreadDialogs(\n chatsById: Record,\n usersById: Record,\n folder: ApiChatFolder,\n chatIdsCache: string[],\n notifySettings: NotifySettings,\n notifyExceptions?: Record,\n) {\n const [listIds] = prepareFolderListIds(chatsById, usersById, folder, notifySettings, notifyExceptions, chatIdsCache);\n\n const listedChats = listIds\n .map((id) => chatsById[id])\n .filter((chat) => (chat?.lastMessage && !chat.isRestricted && !chat.isNotJoined));\n\n const unreadDialogsCount = listedChats\n .reduce((total, chat) => (chat.unreadCount || chat.hasUnreadMark ? total + 1 : total), 0);\n\n const hasActiveDialogs = listedChats.some((chat) => (\n chat.unreadMentionsCount\n || (!selectIsChatMuted(chat, notifySettings, notifyExceptions) && (chat.unreadCount || chat.hasUnreadMark))\n ));\n\n return {\n unreadDialogsCount,\n hasActiveDialogs,\n };\n}\n\nexport function getFolderDescriptionText(\n lang: LangFn,\n chatsById: Record,\n usersById: Record,\n folder: ApiChatFolder,\n chatIdsCache: string[],\n notifySettings: NotifySettings,\n notifyExceptions?: Record,\n) {\n const {\n id, title, emoticon, description, pinnedChatIds,\n excludedChatIds, includedChatIds,\n excludeArchived, excludeMuted, excludeRead,\n ...filters\n } = folder;\n\n // If folder has multiple additive filters or uses include/exclude lists,\n // we display folder chats count\n if (\n Object.values(filters).filter(Boolean).length > 1\n || (excludedChatIds?.length)\n || (includedChatIds?.length)\n ) {\n const length = getFolderChatsCount(chatsById, usersById, folder, chatIdsCache, notifySettings, notifyExceptions);\n return lang('Chats', length);\n }\n\n // Otherwise, we return a short description of a single filter\n if (filters.bots) {\n return lang('FilterBots');\n } else if (filters.groups) {\n return lang('FilterGroups');\n } else if (filters.channels) {\n return lang('FilterChannels');\n } else if (filters.contacts) {\n return lang('FilterContacts');\n } else if (filters.nonContacts) {\n return lang('FilterNonContacts');\n } else {\n return undefined;\n }\n}\n\nfunction getFolderChatsCount(\n chatsById: Record,\n usersById: Record,\n folder: ApiChatFolder,\n chatIdsCache: string[],\n notifySettings: NotifySettings,\n notifyExceptions?: Record,\n) {\n const [listIds, pinnedIds] = prepareFolderListIds(\n chatsById, usersById, folder, notifySettings, notifyExceptions, chatIdsCache,\n );\n const { pinnedChats, otherChats } = prepareChatList(chatsById, listIds, pinnedIds, 'folder');\n return pinnedChats.length + otherChats.length;\n}\n\nexport function getMessageSenderName(lang: LangFn, chatId: string, sender?: ApiUser) {\n if (!sender || isUserId(chatId)) {\n return undefined;\n }\n\n if (sender.isSelf) {\n return lang('FromYou');\n }\n\n return getUserFirstOrLastName(sender);\n}\n\nexport function sortChatIds(\n chatIds: string[],\n chatsById: Record,\n shouldPrioritizeVerified = false,\n priorityIds?: string[],\n) {\n return orderBy(chatIds, (id) => {\n const chat = chatsById[id];\n if (!chat) {\n return 0;\n }\n\n let priority = 0;\n\n if (chat.lastMessage) {\n priority += chat.lastMessage.date;\n }\n\n if (shouldPrioritizeVerified && chat.isVerified) {\n priority += VERIFIED_PRIORITY_BASE; // ~100 years in seconds\n }\n\n if (priorityIds && priorityIds.includes(id)) {\n priority = Date.now() + PINNED_PRIORITY_BASE + (priorityIds.length - priorityIds.indexOf(id));\n }\n\n return priority;\n }, 'desc');\n}\n","import {\n ApiChat, ApiMessage, ApiMessageEntityTypes, ApiUser,\n} from '../../api/types';\nimport { LangFn } from '../../hooks/useLang';\n\nimport { LOCAL_MESSAGE_ID_BASE, SERVICE_NOTIFICATIONS_USER_ID, RE_LINK_TEMPLATE } from '../../config';\nimport { getUserFullName } from './users';\nimport { isWebpSupported, IS_OPUS_SUPPORTED } from '../../util/environment';\nimport { getChatTitle, isUserId } from './chats';\nimport parseEmojiOnlyString from '../../components/common/helpers/parseEmojiOnlyString';\n\nconst CONTENT_NOT_SUPPORTED = 'The message is not supported on this version of Telegram';\nconst RE_LINK = new RegExp(RE_LINK_TEMPLATE, 'i');\nconst TRUNCATED_SUMMARY_LENGTH = 80;\n\nexport type MessageKey = `msg${string}-${number}`;\n\nexport function getMessageKey(message: ApiMessage): MessageKey {\n const { chatId, id } = message;\n\n return buildMessageKey(chatId, id);\n}\n\nexport function buildMessageKey(chatId: string, msgId: number): MessageKey {\n return `msg${chatId}-${msgId}`;\n}\n\nexport function parseMessageKey(key: MessageKey) {\n const match = key.match(/^msg(-?\\d+)-(\\d+)/)!;\n\n return { chatId: match[1], messageId: Number(match[2]) };\n}\n\nexport function getMessageOriginalId(message: ApiMessage) {\n return message.previousLocalId || message.id;\n}\n\nexport function getMessageSummaryText(lang: LangFn, message: ApiMessage, noEmoji = false) {\n const {\n text, photo, video, audio, voice, document, sticker, contact, poll, invoice,\n } = message.content;\n\n const truncatedText = text && text.text.substr(0, TRUNCATED_SUMMARY_LENGTH);\n\n if (message.groupedId) {\n return `${noEmoji ? '' : '🖼 '}${truncatedText || lang('lng_in_dlg_album')}`;\n }\n\n if (photo) {\n return `${noEmoji ? '' : '🖼 '}${truncatedText || lang('AttachPhoto')}`;\n }\n\n if (video) {\n return `${noEmoji ? '' : '📹 '}${truncatedText || lang(video.isGif ? 'AttachGif' : 'AttachVideo')}`;\n }\n\n if (sticker) {\n return `${sticker.emoji || ''} ${lang('AttachSticker')}`.trim();\n }\n\n if (audio) {\n return `${noEmoji ? '' : '🎧 '}${getMessageAudioCaption(message) || lang('AttachMusic')}`;\n }\n\n if (voice) {\n return `${noEmoji ? '' : '🎤 '}${truncatedText || lang('AttachAudio')}`;\n }\n\n if (document) {\n return `${noEmoji ? '' : '📎 '}${truncatedText || document.fileName}`;\n }\n\n if (contact) {\n return lang('AttachContact');\n }\n\n if (poll) {\n return `${noEmoji ? '' : '📊 '}${poll.summary.question}`;\n }\n\n if (invoice) {\n return 'Invoice';\n }\n\n if (text) {\n return truncatedText;\n }\n\n return CONTENT_NOT_SUPPORTED;\n}\n\nexport function getMessageText(message: ApiMessage) {\n const {\n text, sticker, photo, video, audio, voice, document, poll, webPage, contact, invoice,\n } = message.content;\n\n if (text) {\n return text.text;\n }\n\n if (sticker || photo || video || audio || voice || document || contact || poll || webPage || invoice) {\n return undefined;\n }\n\n return CONTENT_NOT_SUPPORTED;\n}\n\nexport function getMessageCustomShape(message: ApiMessage): boolean | number {\n const {\n text, sticker, photo, video, audio, voice, document, poll, webPage, contact,\n } = message.content;\n\n if (sticker || (video?.isRound)) {\n return true;\n }\n\n if (!text || photo || video || audio || voice || document || poll || webPage || contact) {\n return false;\n }\n\n // This is a \"dual-intent\" method used to limit calls of `parseEmojiOnlyString`.\n return parseEmojiOnlyString(text.text) || false;\n}\n\nexport function getMessageSingleEmoji(message: ApiMessage) {\n const { text } = message.content;\n if (!(text && text.text.length <= 6)) {\n return undefined;\n }\n\n if (getMessageCustomShape(message) !== 1) {\n return undefined;\n }\n\n return text.text;\n}\n\nexport function getFirstLinkInMessage(message: ApiMessage) {\n const { text } = message.content;\n\n let match: RegExpMatchArray | null | undefined;\n if (text?.entities) {\n let link = text.entities.find((entity) => entity.type === ApiMessageEntityTypes.TextUrl);\n if (link) {\n match = link.url!.match(RE_LINK);\n }\n\n if (!match) {\n link = text.entities.find((entity) => entity.type === ApiMessageEntityTypes.Url);\n if (link) {\n const { offset, length } = link;\n match = text.text.substring(offset, offset + length).match(RE_LINK);\n }\n }\n }\n\n if (!match && text) {\n match = text.text.match(RE_LINK);\n }\n\n if (!match) {\n return undefined;\n }\n\n return {\n url: match[0],\n domain: match[3],\n };\n}\n\nexport function matchLinkInMessageText(message: ApiMessage) {\n const { text } = message.content;\n const match = text && text.text.match(RE_LINK);\n\n if (!match) {\n return undefined;\n }\n\n return {\n url: match[0],\n domain: match[3],\n };\n}\n\nexport function isOwnMessage(message: ApiMessage) {\n return message.isOutgoing;\n}\n\nexport function isReplyMessage(message: ApiMessage) {\n return Boolean(message.replyToMessageId);\n}\n\nexport function isForwardedMessage(message: ApiMessage) {\n return Boolean(message.forwardInfo);\n}\n\nexport function isActionMessage(message: ApiMessage) {\n return !!message.content.action;\n}\n\nexport function isServiceNotificationMessage(message: ApiMessage) {\n return message.chatId === SERVICE_NOTIFICATIONS_USER_ID && Math.round(message.id) !== message.id;\n}\n\nexport function isAnonymousOwnMessage(message: ApiMessage) {\n return Boolean(message.senderId) && !isUserId(message.senderId!) && isOwnMessage(message);\n}\n\nexport function getSenderTitle(lang: LangFn, sender: ApiUser | ApiChat) {\n return isUserId(sender.id) ? getUserFullName(sender as ApiUser) : getChatTitle(lang, sender as ApiChat);\n}\n\nexport function getSendingState(message: ApiMessage) {\n if (!message.sendingState) {\n return 'succeeded';\n }\n\n return message.sendingState === 'messageSendingStateFailed' ? 'failed' : 'pending';\n}\n\nexport function isMessageLocal(message: ApiMessage) {\n return message.id >= LOCAL_MESSAGE_ID_BASE;\n}\n\nexport function isHistoryClearMessage(message: ApiMessage) {\n return message.content.action && message.content.action.type === 'historyClear';\n}\n\nexport function getMessageAudioCaption(message: ApiMessage) {\n const { audio, text } = message.content;\n\n return (audio && [audio.title, audio.performer].filter(Boolean).join(' — ')) || (text?.text);\n}\n\nexport function getMessageContentFilename(message: ApiMessage) {\n const { content } = message;\n\n const video = content.webPage ? content.webPage.video : content.video;\n const photo = content.webPage ? content.webPage.photo : content.photo;\n const document = content.webPage ? content.webPage.document : content.document;\n if (document) {\n return document.fileName;\n }\n\n if (video) {\n return video.fileName;\n }\n\n if (content.sticker) {\n const extension = content.sticker.isAnimated ? 'tgs' : isWebpSupported() ? 'webp' : 'png';\n return `${content.sticker.id}.${extension}`;\n }\n\n if (content.audio) {\n return content.audio.fileName;\n }\n\n const baseFilename = getMessageKey(message);\n\n if (photo) {\n return `${baseFilename}.jpg`;\n }\n\n if (content.voice) {\n return IS_OPUS_SUPPORTED ? `${baseFilename}.ogg` : `${baseFilename}.wav`;\n }\n\n return baseFilename;\n}\n","import {\n ApiAudio, ApiMediaFormat, ApiMessage, ApiMessageSearchType, ApiPhoto, ApiVideo, ApiDimensions,\n} from '../../api/types';\n\nimport { IS_OPUS_SUPPORTED, IS_PROGRESSIVE_SUPPORTED, IS_SAFARI } from '../../util/environment';\nimport { getMessageKey, isMessageLocal, matchLinkInMessageText } from './messages';\nimport { getDocumentHasPreview } from '../../components/common/helpers/documentInfo';\n\ntype Target =\n 'micro'\n | 'pictogram'\n | 'inline'\n | 'viewerPreview'\n | 'viewerFull'\n | 'download';\n\nexport function getMessageContent(message: ApiMessage) {\n return message.content;\n}\n\nexport function hasMessageMedia(message: ApiMessage) {\n return Boolean((\n getMessagePhoto(message)\n || getMessageVideo(message)\n || getMessageDocument(message)\n || getMessageSticker(message)\n || getMessageContact(message)\n || getMessagePoll(message)\n || getMessageAction(message)\n || getMessageAudio(message)\n || getMessageVoice(message)\n ));\n}\n\nexport function getMessagePhoto(message: ApiMessage) {\n return message.content.photo;\n}\n\nexport function getMessageVideo(message: ApiMessage) {\n return message.content.video;\n}\n\nexport function getMessageRoundVideo(message: ApiMessage) {\n const { video } = message.content;\n\n return video?.isRound ? video : undefined;\n}\n\nexport function getMessageAction(message: ApiMessage) {\n return message.content.action;\n}\n\nexport function getMessageAudio(message: ApiMessage) {\n return message.content.audio;\n}\n\nexport function getMessageVoice(message: ApiMessage) {\n return message.content.voice;\n}\n\nexport function getMessageSticker(message: ApiMessage) {\n return message.content.sticker;\n}\n\nexport function getMessageDocument(message: ApiMessage) {\n return message.content.document;\n}\n\nexport function isMessageDocumentPhoto(message: ApiMessage) {\n const document = getMessageDocument(message);\n return document ? document.mediaType === 'photo' : undefined;\n}\n\nexport function isMessageDocumentVideo(message: ApiMessage) {\n const document = getMessageDocument(message);\n return document ? document.mediaType === 'video' : undefined;\n}\n\nexport function getMessageContact(message: ApiMessage) {\n return message.content.contact;\n}\n\nexport function getMessagePoll(message: ApiMessage) {\n return message.content.poll;\n}\n\nexport function getMessageInvoice(message: ApiMessage) {\n return message.content.invoice;\n}\n\nexport function getMessageWebPage(message: ApiMessage) {\n return message.content.webPage;\n}\n\nexport function getMessageWebPagePhoto(message: ApiMessage) {\n return getMessageWebPage(message)?.photo;\n}\n\nexport function getMessageWebPageDocument(message: ApiMessage) {\n return getMessageWebPage(message)?.document;\n}\n\nexport function getMessageWebPageVideo(message: ApiMessage): ApiVideo | undefined {\n return getMessageWebPage(message)?.video;\n}\n\nexport function getMessageMediaThumbnail(message: ApiMessage) {\n const media = getMessagePhoto(message)\n || getMessageVideo(message)\n || getMessageDocument(message)\n || getMessageSticker(message)\n || getMessageWebPagePhoto(message)\n || getMessageWebPageVideo(message);\n\n if (!media) {\n return undefined;\n }\n\n return media.thumbnail;\n}\n\nexport function getMessageMediaThumbDataUri(message: ApiMessage) {\n return getMessageMediaThumbnail(message)?.dataUri;\n}\n\nexport function getMessageMediaHash(\n message: ApiMessage,\n target: Target,\n) {\n const {\n photo, video, sticker, audio, voice, document,\n } = message.content;\n const webPagePhoto = getMessageWebPagePhoto(message);\n const webPageVideo = getMessageWebPageVideo(message);\n\n const messageVideo = video || webPageVideo;\n const messagePhoto = photo || webPagePhoto;\n\n if (!(messagePhoto || messageVideo || sticker || audio || voice || document)) {\n return undefined;\n }\n\n const base = getMessageKey(message);\n\n if (messageVideo) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n return `${base}?size=m`;\n case 'inline':\n return !hasMessageLocalBlobUrl(message) ? getVideoOrAudioBaseHash(messageVideo, base) : undefined;\n case 'viewerPreview':\n return `${base}?size=m`;\n case 'viewerFull':\n return getVideoOrAudioBaseHash(messageVideo, base);\n case 'download':\n return `${base}?download`;\n }\n }\n\n if (messagePhoto) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n return `${base}?size=m`;\n case 'inline':\n return !hasMessageLocalBlobUrl(message) ? `${base}?size=x` : undefined;\n case 'viewerPreview':\n return `${base}?size=x`;\n case 'viewerFull':\n case 'download':\n return `${base}?size=z`;\n }\n }\n\n if (document) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n case 'inline':\n case 'viewerPreview':\n if (!getDocumentHasPreview(document) || hasMessageLocalBlobUrl(message)) {\n return undefined;\n }\n\n return `${base}?size=m`;\n case 'viewerFull':\n case 'download':\n return base;\n }\n }\n\n if (sticker) {\n switch (target) {\n case 'micro':\n return undefined;\n case 'pictogram':\n return `${base}?size=m`;\n case 'inline':\n return base;\n case 'download':\n return `${base}?download`;\n }\n }\n\n if (audio) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n return getAudioHasCover(audio) ? `${base}?size=m` : undefined;\n case 'inline':\n return getVideoOrAudioBaseHash(audio, base);\n case 'download':\n return `${base}?download`;\n }\n }\n\n if (voice) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n return undefined;\n case 'inline':\n return base;\n case 'download':\n return `${base}?download`;\n }\n }\n\n return undefined;\n}\n\nfunction getVideoOrAudioBaseHash(media: ApiAudio | ApiVideo, base: string) {\n if (IS_PROGRESSIVE_SUPPORTED && IS_SAFARI) {\n return `${base}?fileSize=${media.size}&mimeType=${media.mimeType}`;\n }\n\n return base;\n}\n\nexport function getAudioHasCover(media: ApiAudio) {\n return media.thumbnailSizes && media.thumbnailSizes.length > 0;\n}\n\nexport function getMessageMediaFormat(\n message: ApiMessage, target: Target,\n): Exclude;\nexport function getMessageMediaFormat(message: ApiMessage, target: Target, canBeLottie: true): ApiMediaFormat;\nexport function getMessageMediaFormat(\n message: ApiMessage, target: Target,\n): ApiMediaFormat {\n const {\n sticker, video, audio, voice,\n } = message.content;\n\n const fullVideo = video || getMessageWebPageVideo(message);\n\n if (sticker && target === 'inline' && sticker.isAnimated) {\n return ApiMediaFormat.Lottie;\n } else if (fullVideo && IS_PROGRESSIVE_SUPPORTED && (\n target === 'viewerFull' || target === 'inline'\n )) {\n return ApiMediaFormat.Progressive;\n } else if (audio || voice) {\n // Safari\n if (voice && !IS_OPUS_SUPPORTED) {\n return ApiMediaFormat.BlobUrl;\n }\n\n return ApiMediaFormat.Progressive;\n }\n\n return ApiMediaFormat.BlobUrl;\n}\n\nexport function getMessageFileName(message: ApiMessage) {\n const {\n photo, video, document,\n } = message.content;\n const webPagePhoto = getMessageWebPagePhoto(message);\n const webPageVideo = getMessageWebPageVideo(message);\n\n if (photo || webPagePhoto) {\n return `photo${message.date}.jpeg`;\n }\n\n const { fileName } = video || webPageVideo || document || {};\n\n return fileName;\n}\n\nexport function getMessageFileSize(message: ApiMessage) {\n const { video, document } = message.content;\n const webPageVideo = getMessageWebPageVideo(message);\n const { size } = video || webPageVideo || document || {};\n\n return size;\n}\n\nexport function hasMessageLocalBlobUrl(message: ApiMessage) {\n const { photo, video, document } = message.content;\n\n return (photo?.blobUrl) || (video?.blobUrl) || (document?.previewBlobUrl);\n}\n\nexport function getChatMediaMessageIds(\n messages: Record, listedIds: number[], isFromSharedMedia = false,\n) {\n const ids = getMessageContentIds(messages, listedIds, isFromSharedMedia ? 'media' : 'inlineMedia');\n\n return isFromSharedMedia ? ids.reverse() : ids;\n}\n\nexport function getPhotoFullDimensions(photo: ApiPhoto): ApiDimensions | undefined {\n return (\n photo.sizes.find((size) => size.type === 'z')\n || photo.sizes.find((size) => size.type === 'y')\n || getPhotoInlineDimensions(photo)\n );\n}\n\nexport function getPhotoInlineDimensions(photo: ApiPhoto): ApiDimensions | undefined {\n return (\n photo.sizes.find((size) => size.type === 'x')\n || photo.sizes.find((size) => size.type === 'm')\n || photo.sizes.find((size) => size.type === 's')\n || photo.thumbnail\n );\n}\n\nexport function getVideoDimensions(video: ApiVideo): ApiDimensions | undefined {\n if (video.width && video.height) {\n return video as ApiDimensions;\n }\n\n return undefined;\n}\n\nexport function getMediaTransferState(message: ApiMessage, progress?: number, isLoadNeeded = false) {\n const isUploading = isMessageLocal(message);\n const isTransferring = isUploading || isLoadNeeded;\n const transferProgress = Number(progress);\n\n return {\n isUploading, isTransferring, transferProgress,\n };\n}\n\nexport function getMessageContentIds(\n messages: Record, messageIds: number[], contentType: ApiMessageSearchType | 'inlineMedia',\n) {\n let validator: Function;\n\n switch (contentType) {\n case 'media':\n validator = (message: ApiMessage) => {\n const video = getMessageVideo(message);\n return getMessagePhoto(message) || (video && !video.isRound && !video.isGif);\n };\n break;\n\n case 'documents':\n validator = getMessageDocument;\n break;\n\n case 'links':\n validator = (message: ApiMessage) => getMessageWebPage(message) || matchLinkInMessageText(message);\n break;\n\n case 'audio':\n validator = getMessageAudio;\n break;\n\n case 'voice':\n validator = (message: ApiMessage) => {\n const video = getMessageVideo(message);\n return getMessageVoice(message) || (video && video.isRound);\n };\n break;\n\n case 'inlineMedia':\n validator = (message: ApiMessage) => {\n const video = getMessageVideo(message);\n return (\n getMessagePhoto(message)\n || (video && !video.isRound && !video.isGif)\n || isMessageDocumentPhoto(message)\n || isMessageDocumentVideo(message)\n );\n };\n break;\n\n default:\n return [] as Array;\n }\n\n return messageIds.reduce((result, messageId) => {\n if (messages[messageId] && validator(messages[messageId])) {\n result.push(messageId);\n }\n\n return result;\n }, [] as Array);\n}\n\nexport function getMediaDuration(message: ApiMessage) {\n const { audio, voice, video } = getMessageContent(message);\n const media = audio || voice || video || getMessageWebPageVideo(message);\n if (!media) {\n return undefined;\n }\n\n return media.duration;\n}\n","export function buildChatThreadKey(chatId: string, threadId: number) {\n return `${chatId}_${threadId}`;\n}\n","import { ApiFieldError } from '../../api/types';\n\nconst STRIPE_ERRORS: Record = {\n missing_payment_information: {\n field: 'cardNumber',\n message: 'Incorrect card number',\n },\n invalid_number: {\n field: 'cardNumber',\n message: 'Incorrect card number',\n },\n number: {\n field: 'cardNumber',\n message: 'Incorrect card number',\n },\n exp_year: {\n field: 'expiry',\n message: 'Incorrect year',\n },\n exp_month: {\n field: 'expiry',\n message: 'Incorrect month',\n },\n invalid_expiry_year: {\n field: 'expiry',\n message: 'Incorrect year',\n },\n invalid_expiry_month: {\n field: 'expiry',\n message: 'Incorrect month',\n },\n cvc: {\n field: 'cvv',\n message: 'Incorrect CVV',\n },\n invalid_cvc: {\n field: 'cvv',\n message: 'Incorrect CVV',\n },\n};\n\nexport function getStripeError(error: {\n code: string;\n message: string;\n param?: string;\n}) {\n const { message: description, code, param } = error;\n const { field, message } = param ? STRIPE_ERRORS[param] : STRIPE_ERRORS[code];\n\n return { field, message, description };\n}\n","import { ApiChat, ApiUser } from '../../api/types';\n\nimport { SERVICE_NOTIFICATIONS_USER_ID } from '../../config';\nimport { formatFullDate, formatTime } from '../../util/dateFormat';\nimport { orderBy } from '../../util/iteratees';\nimport { LangFn } from '../../hooks/useLang';\nimport { getServerTime } from '../../util/serverTime';\n\nconst USER_COLOR_KEYS = [1, 8, 5, 2, 7, 4, 6];\n\nexport function getUserFirstOrLastName(user?: ApiUser) {\n if (!user) {\n return undefined;\n }\n\n switch (user.type) {\n case 'userTypeBot':\n case 'userTypeRegular': {\n return user.firstName || user.lastName;\n }\n\n case 'userTypeDeleted':\n case 'userTypeUnknown': {\n return 'Deleted';\n }\n\n default:\n return undefined;\n }\n}\n\nexport function getUserFullName(user?: ApiUser) {\n if (!user) {\n return undefined;\n }\n\n if (isDeletedUser(user)) {\n return 'Deleted account';\n }\n\n switch (user.type) {\n case 'userTypeBot':\n case 'userTypeRegular': {\n if (user.firstName && user.lastName) {\n return `${user.firstName} ${user.lastName}`;\n }\n\n if (user.firstName) {\n return user.firstName;\n }\n\n if (user.lastName) {\n return user.lastName;\n }\n\n break;\n }\n\n case 'userTypeDeleted':\n case 'userTypeUnknown': {\n return 'Deleted account';\n }\n }\n\n return undefined;\n}\n\nexport function getUserStatus(lang: LangFn, user: ApiUser, serverTimeOffset: number) {\n if (user.id === SERVICE_NOTIFICATIONS_USER_ID) {\n return lang('ServiceNotifications').toLowerCase();\n }\n\n if (user.type && user.type === 'userTypeBot') {\n return lang('Bot');\n }\n\n if (!user.status) {\n return '';\n }\n\n switch (user.status.type) {\n case 'userStatusEmpty': {\n return lang('ALongTimeAgo');\n }\n\n case 'userStatusLastMonth': {\n return lang('WithinAMonth');\n }\n\n case 'userStatusLastWeek': {\n return lang('WithinAWeek');\n }\n\n case 'userStatusOffline': {\n const { wasOnline } = user.status;\n\n if (!wasOnline) return lang('LastSeen.Offline');\n\n const now = new Date(new Date().getTime() + serverTimeOffset * 1000);\n const wasOnlineDate = new Date(wasOnline * 1000);\n\n if (wasOnlineDate >= now) {\n return lang('LastSeen.JustNow');\n }\n\n const diff = new Date(now.getTime() - wasOnlineDate.getTime());\n\n // within a minute\n if (diff.getTime() / 1000 < 60) {\n return lang('LastSeen.JustNow');\n }\n\n // within an hour\n if (diff.getTime() / 1000 < 60 * 60) {\n const minutes = Math.floor(diff.getTime() / 1000 / 60);\n return lang('LastSeen.MinutesAgo', minutes);\n }\n\n // today\n const today = new Date();\n today.setHours(0, 0, 0, 0);\n const serverToday = new Date(today.getTime() + serverTimeOffset * 1000);\n if (wasOnlineDate > serverToday) {\n // up to 6 hours ago\n if (diff.getTime() / 1000 < 6 * 60 * 60) {\n const hours = Math.floor(diff.getTime() / 1000 / 60 / 60);\n return lang('LastSeen.HoursAgo', hours);\n }\n\n // other\n return lang('LastSeen.TodayAt', formatTime(wasOnlineDate, lang));\n }\n\n // yesterday\n const yesterday = new Date();\n yesterday.setDate(now.getDate() - 1);\n yesterday.setHours(0, 0, 0, 0);\n const serverYesterday = new Date(yesterday.getTime() + serverTimeOffset * 1000);\n if (wasOnlineDate > serverYesterday) {\n return lang('LastSeen.YesterdayAt', formatTime(wasOnlineDate, lang));\n }\n\n return lang('LastSeen.AtDate', formatFullDate(lang, wasOnlineDate));\n }\n\n case 'userStatusOnline': {\n return lang('Online');\n }\n\n case 'userStatusRecently': {\n return lang('Lately');\n }\n\n default:\n return undefined;\n }\n}\n\nexport function isUserOnline(user: ApiUser) {\n const { id, status, type } = user;\n\n if (!status) {\n return false;\n }\n\n if (id === SERVICE_NOTIFICATIONS_USER_ID) {\n return false;\n }\n\n return status.type === 'userStatusOnline' && type !== 'userTypeBot';\n}\n\nexport function isDeletedUser(user: ApiUser) {\n if (!user.status || user.type === 'userTypeBot' || user.id === SERVICE_NOTIFICATIONS_USER_ID) {\n return false;\n }\n\n return user.type === 'userTypeDeleted'\n || user.type === 'userTypeUnknown';\n}\n\nexport function isUserBot(user: ApiUser) {\n return user.type === 'userTypeBot';\n}\n\nexport function getCanAddContact(user: ApiUser) {\n return !user.isContact && !isUserBot(user);\n}\n\nexport function sortUserIds(\n userIds: string[],\n usersById: Record,\n priorityIds?: string[],\n serverTimeOffset = 0,\n) {\n return orderBy(userIds, (id) => {\n const now = getServerTime(serverTimeOffset);\n\n if (priorityIds && priorityIds.includes(id)) {\n // Assuming that online status expiration date can't be as far as two days from now,\n // this should place prioritized on top of the list.\n // Then we subtract index of `id` in `priorityIds` to preserve selected order\n return now + (48 * 60 * 60) - (priorityIds.length - priorityIds.indexOf(id));\n }\n\n const user = usersById[id];\n if (!user || !user.status) {\n return 0;\n }\n\n if (user.status.type === 'userStatusOnline') {\n return user.status.expires;\n } else if (user.status.type === 'userStatusOffline' && user.status.wasOnline) {\n return user.status.wasOnline;\n }\n\n switch (user.status.type) {\n case 'userStatusRecently':\n return now - 60 * 60 * 24;\n case 'userStatusLastWeek':\n return now - 60 * 60 * 24 * 7;\n case 'userStatusLastMonth':\n return now - 60 * 60 * 24 * 7 * 30;\n default:\n return 0;\n }\n }, 'desc');\n}\n\nexport function getUserIdDividend(userId: string) {\n // Workaround for old-fashioned IDs stored locally\n if (typeof userId === 'number') {\n return Math.abs(userId);\n }\n\n return Math.abs(Number(userId));\n}\n\n// eslint-disable-next-line max-len\n// https://github.com/telegramdesktop/tdesktop/blob/371510cfe23b0bd226de8c076bc49248fbe40c26/Telegram/SourceFiles/data/data_peer.cpp#L53\nexport function getUserColorKey(peer: ApiUser | ApiChat | undefined) {\n const index = peer ? getUserIdDividend(peer.id) % 7 : 0;\n\n return USER_COLOR_KEYS[index];\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiChat, ApiPhoto } from '../../api/types';\n\nimport { ARCHIVED_FOLDER_ID } from '../../config';\nimport { omit } from '../../util/iteratees';\nimport { selectChatListType } from '../selectors';\n\nexport function replaceChatListIds(\n global: GlobalState,\n type: 'active' | 'archived',\n newIds: string[] | undefined,\n): GlobalState {\n return {\n ...global,\n chats: {\n ...global.chats,\n listIds: {\n ...global.chats.listIds,\n [type]: newIds,\n },\n },\n };\n}\n\nexport function updateChatListIds(global: GlobalState, type: 'active' | 'archived', idsUpdate: string[]): GlobalState {\n const { [type]: listIds } = global.chats.listIds;\n const newIds = listIds?.length\n ? idsUpdate.filter((id) => !listIds.includes(id))\n : idsUpdate;\n\n if (listIds && !newIds.length) {\n return global;\n }\n\n return replaceChatListIds(global, type, [\n ...(listIds || []),\n ...newIds,\n ]);\n}\n\nexport function replaceChats(global: GlobalState, newById: Record): GlobalState {\n return {\n ...global,\n chats: {\n ...global.chats,\n byId: newById,\n },\n };\n}\n\n// @optimization Don't spread/unspread global for each element, do it in a batch\nfunction getUpdatedChat(\n global: GlobalState, chatId: string, chatUpdate: Partial, photo?: ApiPhoto,\n): ApiChat {\n const { byId } = global.chats;\n const chat = byId[chatId];\n const shouldOmitMinInfo = chatUpdate.isMin && chat && !chat.isMin;\n const updatedChat = {\n ...chat,\n ...(shouldOmitMinInfo ? omit(chatUpdate, ['isMin', 'accessHash']) : chatUpdate),\n ...(photo && { photos: [photo, ...(chat.photos || [])] }),\n };\n\n if (!updatedChat.id || !updatedChat.type) {\n return updatedChat;\n }\n\n return updatedChat;\n}\n\nexport function updateChat(\n global: GlobalState, chatId: string, chatUpdate: Partial, photo?: ApiPhoto,\n): GlobalState {\n const { byId } = global.chats;\n\n const updatedChat = getUpdatedChat(global, chatId, chatUpdate, photo);\n\n return replaceChats(global, {\n ...byId,\n [chatId]: updatedChat,\n });\n}\n\nexport function updateChats(global: GlobalState, updatedById: Record): GlobalState {\n const updatedChats = Object.keys(updatedById).reduce>((acc, id) => {\n const updatedChat = getUpdatedChat(global, id, updatedById[id]);\n if (updatedChat) {\n acc[id] = updatedChat;\n }\n return acc;\n }, {});\n\n global = replaceChats(global, {\n ...global.chats.byId,\n ...updatedChats,\n });\n\n return global;\n}\n\n// @optimization Allows to avoid redundant updates which cause a lot of renders\nexport function addChats(global: GlobalState, addedById: Record): GlobalState {\n const { byId } = global.chats;\n let isAdded = false;\n\n const addedChats = Object.keys(addedById).reduce>((acc, id) => {\n if (!byId[id] || (byId[id].isMin && !addedById[id].isMin)) {\n const updatedChat = getUpdatedChat(global, id, addedById[id]);\n if (updatedChat) {\n acc[id] = updatedChat;\n\n if (!isAdded) {\n isAdded = true;\n }\n }\n }\n return acc;\n }, {});\n\n if (isAdded) {\n global = replaceChats(global, {\n ...global.chats.byId,\n ...addedChats,\n });\n }\n\n return global;\n}\n\nexport function updateChatListType(\n global: GlobalState,\n chatId: string,\n folderId?: number,\n): GlobalState {\n const listType = folderId === ARCHIVED_FOLDER_ID ? 'archived' : 'active';\n\n let currentListIds = global.chats.listIds;\n (Object.keys(currentListIds) as Array).forEach((listTypeKey) => {\n const currentFolderList = currentListIds[listTypeKey] || [];\n if (listTypeKey === listType && !currentFolderList.includes(chatId)) {\n currentListIds = {\n ...currentListIds,\n [listTypeKey]: [...currentFolderList, chatId],\n };\n } else if (listTypeKey !== listType && currentFolderList.includes(chatId)) {\n currentListIds = {\n ...currentListIds,\n [listTypeKey]: currentFolderList.filter((id) => id !== chatId),\n };\n }\n });\n\n global = {\n ...global,\n chats: {\n ...global.chats,\n listIds: currentListIds,\n },\n };\n\n global = updateChat(global, chatId, { folderId: folderId || undefined });\n\n return global;\n}\n\nexport function updateChatListSecondaryInfo(\n global: GlobalState,\n type: 'active' | 'archived',\n info: {\n orderedPinnedIds?: string[];\n totalChatCount: number;\n },\n): GlobalState {\n const totalCountKey = type === 'active' ? 'all' : 'archived';\n\n return {\n ...global,\n chats: {\n ...global.chats,\n ...(info.orderedPinnedIds && {\n orderedPinnedIds: {\n ...global.chats.orderedPinnedIds,\n [type]: info.orderedPinnedIds,\n },\n }),\n totalCount: {\n ...global.chats.totalCount,\n [totalCountKey]: info.totalChatCount,\n },\n isFullyLoaded: {\n ...global.chats.isFullyLoaded,\n [type]: false,\n },\n },\n };\n}\n\nexport function leaveChat(global: GlobalState, leftChatId: string): GlobalState {\n const listType = selectChatListType(global, leftChatId);\n if (!listType) {\n return global;\n }\n\n const { [listType]: listIds } = global.chats.listIds;\n\n if (listIds) {\n global = replaceChatListIds(global, listType, listIds.filter((listId) => listId !== leftChatId));\n }\n\n global = updateChat(global, leftChatId, { isNotJoined: true });\n\n return global;\n}\n","import {\n GlobalState, MessageList, MessageListType, Thread,\n} from '../../global/types';\nimport { ApiMessage, ApiThreadInfo, MAIN_THREAD_ID } from '../../api/types';\nimport { FocusDirection } from '../../types';\n\nimport {\n IS_TEST, MESSAGE_LIST_SLICE, MESSAGE_LIST_VIEWPORT_LIMIT, TMP_CHAT_ID,\n} from '../../config';\nimport {\n selectListedIds,\n selectChatMessages,\n selectViewportIds,\n selectOutlyingIds,\n selectPinnedIds,\n selectThreadInfo,\n selectMessageIdsByGroupId,\n selectScheduledMessages,\n selectScheduledIds,\n selectCurrentMessageIds,\n selectChatMessage,\n selectCurrentMessageList,\n} from '../selectors';\nimport {\n areSortedArraysEqual, omit, pickTruthy, unique,\n} from '../../util/iteratees';\n\ntype MessageStoreSections = {\n byId: Record;\n threadsById: Record;\n};\n\nexport function updateCurrentMessageList(\n global: GlobalState,\n chatId: string | undefined,\n threadId: number = MAIN_THREAD_ID,\n type: MessageListType = 'thread',\n shouldReplaceHistory?: boolean,\n): GlobalState {\n const { messageLists } = global.messages;\n let newMessageLists: MessageList[] = messageLists;\n if (shouldReplaceHistory || IS_TEST) {\n newMessageLists = chatId ? [{ chatId, threadId, type }] : [];\n } else if (chatId) {\n const last = messageLists[messageLists.length - 1];\n if (!last || last.chatId !== chatId || last.threadId !== threadId || last.type !== type) {\n if (last && last.chatId === TMP_CHAT_ID) {\n newMessageLists = [...messageLists.slice(0, -1), { chatId, threadId, type }];\n } else {\n newMessageLists = [...messageLists, { chatId, threadId, type }];\n }\n }\n } else {\n newMessageLists = messageLists.slice(0, -1);\n }\n\n return {\n ...global,\n messages: {\n ...global.messages,\n messageLists: newMessageLists,\n },\n };\n}\n\nfunction replaceChatMessages(global: GlobalState, chatId: string, newById: Record): GlobalState {\n return updateMessageStore(global, chatId, {\n byId: newById,\n });\n}\n\nfunction updateThread(\n global: GlobalState, chatId: string, threadId: number, threadUpdate: Partial,\n): GlobalState {\n const current = global.messages.byChatId[chatId];\n\n return updateMessageStore(global, chatId, {\n threadsById: {\n ...(current?.threadsById),\n [threadId]: {\n ...(current?.threadsById[threadId]),\n ...threadUpdate,\n },\n },\n });\n}\n\nfunction updateMessageStore(\n global: GlobalState, chatId: string, update: Partial,\n): GlobalState {\n const current = global.messages.byChatId[chatId] || { byId: {}, threadsById: {} };\n\n return {\n ...global,\n messages: {\n ...global.messages,\n byChatId: {\n ...global.messages.byChatId,\n [chatId]: {\n ...current,\n ...update,\n },\n },\n },\n };\n}\n\nexport function replaceThreadParam(\n global: GlobalState, chatId: string, threadId: number, paramName: T, newValue: Thread[T] | undefined,\n) {\n return updateThread(global, chatId, threadId, { [paramName]: newValue });\n}\n\nexport function addMessages(\n global: GlobalState, messages: ApiMessage[],\n): GlobalState {\n const addedByChatId = messages.reduce((messagesByChatId, message: ApiMessage) => {\n if (!messagesByChatId[message.chatId]) {\n messagesByChatId[message.chatId] = {};\n }\n messagesByChatId[message.chatId][message.id] = message;\n\n return messagesByChatId;\n }, {} as Record>);\n\n Object.keys(addedByChatId).forEach((chatId) => {\n global = addChatMessagesById(global, chatId, addedByChatId[chatId]);\n });\n\n return global;\n}\n\nexport function addChatMessagesById(\n global: GlobalState, chatId: string, newById: Record,\n): GlobalState {\n const byId = selectChatMessages(global, chatId);\n\n if (byId && Object.keys(newById).every((newId) => Boolean(byId[Number(newId)]))) {\n return global;\n }\n\n return replaceChatMessages(global, chatId, {\n ...newById,\n ...byId,\n });\n}\n\nexport function updateChatMessage(\n global: GlobalState, chatId: string, messageId: number, messageUpdate: Partial,\n): GlobalState {\n const byId = selectChatMessages(global, chatId) || {};\n const message = byId[messageId];\n const updatedMessage = {\n ...message,\n ...messageUpdate,\n };\n\n if (!updatedMessage.id) {\n return global;\n }\n\n return replaceChatMessages(global, chatId, {\n ...byId,\n [messageId]: updatedMessage,\n });\n}\n\nexport function updateScheduledMessage(\n global: GlobalState, chatId: string, messageId: number, messageUpdate: Partial,\n): GlobalState {\n const byId = selectScheduledMessages(global, chatId) || {};\n const message = byId[messageId];\n const updatedMessage = {\n ...message,\n ...messageUpdate,\n };\n\n if (!updatedMessage.id) {\n return global;\n }\n\n return replaceScheduledMessages(global, chatId, {\n ...byId,\n [messageId]: updatedMessage,\n });\n}\n\nexport function deleteChatMessages(\n global: GlobalState,\n chatId: string,\n messageIds: number[],\n): GlobalState {\n const byId = selectChatMessages(global, chatId);\n if (!byId) {\n return global;\n }\n const newById = omit(byId, messageIds);\n const deletedForwardedPosts = Object.values(pickTruthy(byId, messageIds)).filter(\n ({ forwardInfo }) => forwardInfo?.isLinkedChannelPost,\n );\n\n const threadIds = Object.keys(global.messages.byChatId[chatId].threadsById).map(Number);\n threadIds.forEach((threadId) => {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n\n let listedIds = selectListedIds(global, chatId, threadId);\n let outlyingIds = selectOutlyingIds(global, chatId, threadId);\n let viewportIds = selectViewportIds(global, chatId, threadId);\n let pinnedIds = selectPinnedIds(global, chatId);\n let newMessageCount = threadInfo?.messagesCount;\n\n messageIds.forEach((messageId) => {\n if (listedIds && listedIds.includes(messageId)) {\n listedIds = listedIds.filter((id) => id !== messageId);\n if (newMessageCount !== undefined) newMessageCount -= 1;\n }\n\n if (outlyingIds && outlyingIds.includes(messageId)) {\n outlyingIds = outlyingIds.filter((id) => id !== messageId);\n }\n\n if (viewportIds && viewportIds.includes(messageId)) {\n viewportIds = viewportIds.filter((id) => id !== messageId);\n }\n\n if (pinnedIds && pinnedIds.includes(messageId)) {\n pinnedIds = pinnedIds.filter((id) => id !== messageId);\n }\n });\n\n global = replaceThreadParam(global, chatId, threadId, 'listedIds', listedIds);\n global = replaceThreadParam(global, chatId, threadId, 'outlyingIds', outlyingIds);\n global = replaceThreadParam(global, chatId, threadId, 'viewportIds', viewportIds);\n global = replaceThreadParam(global, chatId, threadId, 'pinnedIds', pinnedIds);\n\n if (threadInfo && newMessageCount !== undefined) {\n global = replaceThreadParam(global, chatId, threadId, 'threadInfo', {\n ...threadInfo,\n messagesCount: newMessageCount,\n });\n }\n });\n\n if (deletedForwardedPosts.length) {\n const currentMessageList = selectCurrentMessageList(global);\n const canDeleteCurrentThread = currentMessageList && currentMessageList.chatId === chatId\n && currentMessageList.type === 'thread';\n const currentThreadId = currentMessageList?.threadId;\n\n deletedForwardedPosts.forEach((message) => {\n const { fromChatId, fromMessageId } = message.forwardInfo!;\n const originalPost = selectChatMessage(global, fromChatId!, fromMessageId!);\n\n if (canDeleteCurrentThread && currentThreadId === fromMessageId) {\n global = updateCurrentMessageList(global, chatId);\n }\n if (originalPost) {\n global = updateChatMessage(global, fromChatId!, fromMessageId!, { threadInfo: undefined });\n }\n });\n }\n\n global = replaceChatMessages(global, chatId, newById);\n\n return global;\n}\n\nexport function deleteChatScheduledMessages(\n global: GlobalState,\n chatId: string,\n messageIds: number[],\n): GlobalState {\n const byId = selectScheduledMessages(global, chatId);\n if (!byId) {\n return global;\n }\n const newById = omit(byId, messageIds);\n\n let scheduledIds = selectScheduledIds(global, chatId);\n if (scheduledIds) {\n messageIds.forEach((messageId) => {\n if (scheduledIds!.includes(messageId)) {\n scheduledIds = scheduledIds!.filter((id) => id !== messageId);\n }\n });\n global = replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'scheduledIds', scheduledIds);\n }\n\n global = replaceScheduledMessages(global, chatId, newById);\n\n return global;\n}\n\nexport function updateListedIds(\n global: GlobalState,\n chatId: string,\n threadId: number,\n idsUpdate: number[],\n): GlobalState {\n const listedIds = selectListedIds(global, chatId, threadId);\n const newIds = listedIds?.length\n ? idsUpdate.filter((id) => !listedIds.includes(id))\n : idsUpdate;\n\n if (listedIds && !newIds.length) {\n return global;\n }\n\n return replaceThreadParam(global, chatId, threadId, 'listedIds', orderHistoryIds([\n ...(listedIds || []),\n ...newIds,\n ]));\n}\n\nexport function updateOutlyingIds(\n global: GlobalState,\n chatId: string,\n threadId: number,\n idsUpdate: number[],\n): GlobalState {\n const outlyingIds = selectOutlyingIds(global, chatId, threadId);\n const newIds = outlyingIds?.length\n ? idsUpdate.filter((id) => !outlyingIds.includes(id))\n : idsUpdate;\n\n if (outlyingIds && !newIds.length) {\n return global;\n }\n\n return replaceThreadParam(global, chatId, threadId, 'outlyingIds', orderHistoryIds([\n ...(outlyingIds || []),\n ...newIds,\n ]));\n}\n\nfunction orderHistoryIds(listedIds: number[]) {\n return listedIds.sort((a, b) => a - b);\n}\n\nexport function addViewportId(\n global: GlobalState,\n chatId: string,\n threadId: number,\n newId: number,\n): GlobalState {\n const viewportIds = selectViewportIds(global, chatId, threadId) || [];\n if (viewportIds.includes(newId)) {\n return global;\n }\n\n const newIds = orderHistoryIds([\n ...(\n viewportIds.length < MESSAGE_LIST_VIEWPORT_LIMIT\n ? viewportIds\n : viewportIds.slice(-(MESSAGE_LIST_SLICE / 2))\n ),\n newId,\n ]);\n\n return replaceThreadParam(global, chatId, threadId, 'viewportIds', newIds);\n}\n\nexport function safeReplaceViewportIds(\n global: GlobalState,\n chatId: string,\n threadId: number,\n newViewportIds: number[],\n): GlobalState {\n const currentIds = selectViewportIds(global, chatId, threadId) || [];\n const newIds = orderHistoryIds(newViewportIds);\n\n return replaceThreadParam(\n global,\n chatId,\n threadId,\n 'viewportIds',\n areSortedArraysEqual(currentIds, newIds) ? currentIds : newIds,\n );\n}\n\nexport function updateThreadInfo(\n global: GlobalState, chatId: string, threadId: number, update: Partial | undefined,\n): GlobalState {\n const newThreadInfo = {\n ...(selectThreadInfo(global, chatId, threadId) as ApiThreadInfo),\n ...update,\n };\n\n if (!newThreadInfo.threadId) {\n return global;\n }\n\n return replaceThreadParam(global, chatId, threadId, 'threadInfo', newThreadInfo);\n}\n\nexport function updateThreadInfos(\n global: GlobalState, chatId: string, updates: Partial[],\n): GlobalState {\n updates.forEach((update) => {\n global = updateThreadInfo(global, update.chatId!, update.threadId!, update);\n });\n\n return global;\n}\n\nexport function replaceScheduledMessages(\n global: GlobalState, chatId: string, newById: Record,\n): GlobalState {\n return updateScheduledMessages(global, chatId, {\n byId: newById,\n });\n}\n\nfunction updateScheduledMessages(\n global: GlobalState, chatId: string, update: Partial<{ byId: Record }>,\n): GlobalState {\n const current = global.scheduledMessages.byChatId[chatId] || { byId: {}, hash: 0 };\n\n return {\n ...global,\n scheduledMessages: {\n byChatId: {\n ...global.scheduledMessages.byChatId,\n [chatId]: {\n ...current,\n ...update,\n },\n },\n },\n };\n}\n\nexport function updateFocusedMessage(\n global: GlobalState, chatId?: string, messageId?: number, noHighlight = false, isResizingContainer = false,\n): GlobalState {\n return {\n ...global,\n focusedMessage: {\n ...global.focusedMessage,\n chatId,\n messageId,\n noHighlight,\n isResizingContainer,\n },\n };\n}\n\nexport function updateFocusDirection(\n global: GlobalState, direction?: FocusDirection,\n): GlobalState {\n return {\n ...global,\n focusedMessage: {\n ...global.focusedMessage,\n direction,\n },\n };\n}\n\nexport function enterMessageSelectMode(\n global: GlobalState,\n chatId: string,\n messageId?: number | number[],\n): GlobalState {\n const messageIds = messageId ? Array.prototype.concat([], messageId) : [];\n return {\n ...global,\n selectedMessages: {\n chatId,\n messageIds,\n },\n };\n}\n\nexport function toggleMessageSelection(\n global: GlobalState,\n chatId: string,\n threadId: number,\n messageListType: MessageListType,\n messageId: number,\n groupedId?: string,\n childMessageIds?: number[],\n withShift = false,\n): GlobalState {\n const { selectedMessages: oldSelectedMessages } = global;\n if (groupedId) {\n childMessageIds = selectMessageIdsByGroupId(global, chatId, groupedId);\n }\n const selectedMessageIds = childMessageIds || [messageId];\n if (!oldSelectedMessages) {\n return enterMessageSelectMode(global, chatId, selectedMessageIds);\n }\n\n const { messageIds } = oldSelectedMessages;\n\n let newMessageIds;\n const newSelectedMessageIds = selectedMessageIds.filter((id) => !messageIds.includes(id));\n if (newSelectedMessageIds && !newSelectedMessageIds.length) {\n newMessageIds = messageIds.filter((id) => !selectedMessageIds.includes(id));\n } else if (withShift && messageIds.length) {\n const viewportIds = selectCurrentMessageIds(global, chatId, threadId, messageListType)!;\n const prevIndex = viewportIds.indexOf(messageIds[messageIds.length - 1]);\n const currentIndex = viewportIds.indexOf(messageId);\n const from = Math.min(prevIndex, currentIndex);\n const to = Math.max(prevIndex, currentIndex);\n const slice = viewportIds.slice(from, to + 1);\n newMessageIds = unique([...messageIds, ...slice]);\n } else {\n newMessageIds = [...messageIds, ...newSelectedMessageIds];\n }\n\n if (!newMessageIds.length) {\n return exitMessageSelectMode(global);\n }\n\n return {\n ...global,\n selectedMessages: {\n ...oldSelectedMessages,\n messageIds: newMessageIds,\n },\n };\n}\n\nexport function exitMessageSelectMode(global: GlobalState): GlobalState {\n return {\n ...global,\n selectedMessages: undefined,\n };\n}\n\nexport function updateThreadUnreadFromForwardedMessage(\n global: GlobalState,\n originMessage: ApiMessage,\n chatId: string,\n lastMessageId: number,\n isDeleting?: boolean,\n) {\n const { channelPostId, fromChatId } = originMessage.forwardInfo || {};\n if (channelPostId && fromChatId) {\n const threadInfoOld = selectThreadInfo(global, chatId, channelPostId);\n if (threadInfoOld) {\n global = replaceThreadParam(global, chatId, channelPostId, 'threadInfo', {\n ...threadInfoOld,\n lastMessageId,\n messagesCount: threadInfoOld.messagesCount + (isDeleting ? -1 : 1),\n });\n }\n }\n return global;\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiSticker, ApiStickerSet, ApiVideo } from '../../api/types';\nimport { buildCollectionByKey, unique } from '../../util/iteratees';\nimport { selectStickersForEmoji } from '../selectors';\n\nexport function updateStickerSets(\n global: GlobalState,\n category: 'added' | 'featured' | 'search',\n hash: string,\n sets: ApiStickerSet[],\n resultIds?: string[],\n): GlobalState {\n const updatedSets = sets.map((stickerSet) => {\n const existing = global.stickers.setsById[stickerSet.id];\n if (!existing) {\n return stickerSet;\n }\n\n return {\n ...existing,\n ...stickerSet,\n };\n });\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n setsById: {\n ...global.stickers.setsById,\n ...buildCollectionByKey(updatedSets, 'id'),\n },\n [category]: {\n ...global.stickers[category],\n hash,\n ...(\n category === 'search'\n ? { resultIds }\n : { setIds: sets.map(({ id }) => id) }\n ),\n },\n },\n };\n}\n\nexport function updateStickerSet(\n global: GlobalState, stickerSetId: string, update: Partial,\n): GlobalState {\n const currentStickerSet = global.stickers.setsById[stickerSetId] || {};\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n setsById: {\n ...global.stickers.setsById,\n [stickerSetId]: {\n ...currentStickerSet,\n ...update,\n },\n },\n },\n };\n}\n\nexport function updateGifSearch(\n global: GlobalState, isNew: boolean, results: ApiVideo[], nextOffset?: string,\n): GlobalState {\n const { results: currentResults } = global.gifs.search;\n\n let newResults!: ApiVideo[];\n if (isNew || !currentResults) {\n newResults = results;\n } else {\n const currentIds = new Set(currentResults.map((gif) => gif.id));\n newResults = [\n ...currentResults,\n ...results.filter((gif) => !currentIds.has(gif.id)),\n ];\n }\n\n return {\n ...global,\n gifs: {\n ...global.gifs,\n search: {\n ...global.gifs.search,\n offset: nextOffset,\n results: newResults,\n },\n },\n };\n}\n\nexport function replaceAnimatedEmojis(global: GlobalState, stickerSet: ApiStickerSet): GlobalState {\n return {\n ...global,\n animatedEmojis: stickerSet,\n };\n}\n\nexport function updateStickersForEmoji(\n global: GlobalState, emoji: string, remoteStickers?: ApiSticker[], hash?: string,\n): GlobalState {\n const localStickers = selectStickersForEmoji(global, emoji);\n const allStickers = [...localStickers, ...(remoteStickers || [])];\n const uniqueIds = unique(allStickers.map(({ id }) => id));\n const byId = buildCollectionByKey(allStickers, 'id');\n const stickers = uniqueIds.map((id) => byId[id]);\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n forEmoji: {\n emoji,\n stickers,\n hash,\n },\n },\n };\n}\n\nexport function rebuildStickersForEmoji(global: GlobalState): GlobalState {\n const { emoji, stickers, hash } = global.stickers.forEmoji || {};\n if (!emoji) {\n return global;\n }\n\n return updateStickersForEmoji(global, emoji, stickers, hash);\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiUser } from '../../api/types';\n\nimport { omit } from '../../util/iteratees';\nimport { MEMO_EMPTY_ARRAY } from '../../util/memo';\n\nexport function replaceUsers(global: GlobalState, newById: Record): GlobalState {\n return {\n ...global,\n users: {\n ...global.users,\n byId: newById,\n },\n };\n}\n\n// @optimization Don't spread/unspread global for each element, do it in a batch\nfunction getUpdatedUser(global: GlobalState, userId: string, userUpdate: Partial): ApiUser {\n const { byId } = global.users;\n const user = byId[userId];\n const shouldOmitMinInfo = userUpdate.isMin && user && !user.isMin;\n\n const updatedUser = {\n ...user,\n ...(shouldOmitMinInfo ? omit(userUpdate, ['isMin', 'accessHash']) : userUpdate),\n };\n\n if (!updatedUser.id || !updatedUser.type) {\n return user;\n }\n\n return updatedUser;\n}\n\nfunction updateContactList(global: GlobalState, updatedUsers: ApiUser[]): GlobalState {\n const { userIds: contactUserIds } = global.contactList || {};\n\n if (!contactUserIds) return global;\n\n const newContactUserIds = updatedUsers\n .filter((user) => user?.isContact && !contactUserIds.includes(user.id))\n .map((user) => user.id);\n\n if (newContactUserIds.length === 0) return global;\n\n return {\n ...global,\n contactList: {\n userIds: [\n ...newContactUserIds,\n ...contactUserIds,\n ],\n },\n };\n}\n\nexport function updateUser(global: GlobalState, userId: string, userUpdate: Partial): GlobalState {\n const { byId } = global.users;\n\n const updatedUser = getUpdatedUser(global, userId, userUpdate);\n\n global = updateContactList(global, [updatedUser]);\n\n return replaceUsers(global, {\n ...byId,\n [userId]: updatedUser,\n });\n}\n\nexport function updateUsers(global: GlobalState, updatedById: Record): GlobalState {\n const updatedUsers = Object.keys(updatedById).reduce>((acc, id) => {\n const updatedUser = getUpdatedUser(global, id, updatedById[id]);\n if (updatedUser) {\n acc[id] = updatedUser;\n }\n return acc;\n }, {});\n\n global = updateContactList(global, Object.values(updatedUsers));\n\n global = replaceUsers(global, {\n ...global.users.byId,\n ...updatedUsers,\n });\n\n return global;\n}\n\n// @optimization Allows to avoid redundant updates which cause a lot of renders\nexport function addUsers(global: GlobalState, addedById: Record): GlobalState {\n const { byId } = global.users;\n let isAdded = false;\n\n const addedUsers = Object.keys(addedById).reduce>((acc, id) => {\n if (!byId[id] || (byId[id].isMin && !addedById[id].isMin)) {\n const updatedUser = getUpdatedUser(global, id, addedById[id]);\n if (updatedUser) {\n acc[id] = updatedUser;\n\n if (!isAdded) {\n isAdded = true;\n }\n }\n }\n return acc;\n }, {});\n\n if (isAdded) {\n global = replaceUsers(global, {\n ...global.users.byId,\n ...addedUsers,\n });\n\n global = updateContactList(global, Object.values(addedUsers));\n }\n\n return global;\n}\n\nexport function updateSelectedUserId(global: GlobalState, selectedId?: string): GlobalState {\n if (global.users.selectedId === selectedId) {\n return global;\n }\n\n return {\n ...global,\n users: {\n ...global.users,\n selectedId,\n },\n };\n}\n\nexport function deleteUser(global: GlobalState, userId: string): GlobalState {\n const { byId } = global.users;\n const { userIds } = global.contactList || {};\n delete byId[userId];\n\n global = {\n ...global,\n contactList: {\n userIds: userIds ? userIds.filter((id) => id !== userId) : MEMO_EMPTY_ARRAY,\n },\n };\n\n return replaceUsers(global, byId);\n}\n\nexport function updateUserSearch(\n global: GlobalState,\n searchStatePartial: Partial,\n) {\n return {\n ...global,\n userSearch: {\n ...global.userSearch,\n ...searchStatePartial,\n },\n };\n}\n\nexport function updateUserSearchFetchingStatus(\n global: GlobalState, newState: boolean,\n) {\n return updateUserSearch(global, {\n fetchingStatus: newState,\n });\n}\n\nexport function updateUserBlockedState(global: GlobalState, userId: string, isBlocked: boolean) {\n const { byId } = global.users;\n const user = byId[userId];\n if (!user || !user.fullInfo) {\n return global;\n }\n\n return updateUser(global, userId, {\n ...user,\n fullInfo: {\n ...user.fullInfo,\n isBlocked,\n },\n });\n}\n","import { GlobalState } from '../../global/types';\nimport { GlobalSearchContent } from '../../types';\nimport { ApiGlobalMessageSearchType, ApiMessage } from '../../api/types';\nimport { areSortedArraysEqual } from '../../util/iteratees';\n\nconst getComplexKey = (message: ApiMessage) => `${message.chatId}_${message.id}`;\n\nexport function updateGlobalSearch(\n global: GlobalState,\n searchStatePartial: Partial,\n) {\n return {\n ...global,\n globalSearch: {\n ...global.globalSearch,\n ...searchStatePartial,\n },\n };\n}\n\nexport function updateGlobalSearchContent(\n global: GlobalState,\n currentContent: GlobalSearchContent | undefined,\n): GlobalState {\n return updateGlobalSearch(global, { currentContent });\n}\n\nexport function updateGlobalSearchResults(\n global: GlobalState,\n newFoundMessages: ApiMessage[],\n totalCount: number,\n type: ApiGlobalMessageSearchType,\n nextRate?: number,\n): GlobalState {\n const { resultsByType } = global.globalSearch || {};\n const newFoundMessagesById = newFoundMessages.reduce((result, message) => {\n result[getComplexKey(message)] = message;\n\n return result;\n }, {} as Record);\n const foundIdsForType = resultsByType?.[type]?.foundIds;\n\n if (foundIdsForType !== undefined\n && Object.keys(newFoundMessagesById).every(\n (newId) => foundIdsForType.includes(getComplexKey(newFoundMessagesById[newId])),\n )\n ) {\n return updateGlobalSearchFetchingStatus(global, { messages: false });\n }\n\n const prevFoundIds = foundIdsForType || [];\n const newFoundIds = newFoundMessages.map((message) => getComplexKey(message));\n const foundIds = Array.prototype.concat(prevFoundIds, newFoundIds);\n const foundOrPrevFoundIds = areSortedArraysEqual(prevFoundIds, foundIds) ? prevFoundIds : foundIds;\n\n global = updateGlobalSearchFetchingStatus(global, { messages: false });\n\n return updateGlobalSearch(global, {\n resultsByType: {\n ...(global.globalSearch || {}).resultsByType,\n [type]: {\n totalCount,\n nextOffsetId: nextRate,\n foundIds: foundOrPrevFoundIds,\n },\n },\n });\n}\n\nexport function updateGlobalSearchFetchingStatus(\n global: GlobalState, newState: { chats?: boolean; messages?: boolean },\n) {\n return updateGlobalSearch(global, {\n fetchingStatus: {\n ...global.globalSearch.fetchingStatus,\n ...newState,\n },\n });\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiMessageSearchType } from '../../api/types';\n\nimport { areSortedArraysEqual, unique } from '../../util/iteratees';\nimport { SharedMediaType } from '../../types';\nimport { buildChatThreadKey } from '../helpers';\n\ninterface TextSearchParams {\n isActive: boolean;\n query?: string;\n results?: {\n totalCount?: number;\n nextOffsetId?: number;\n foundIds?: number[];\n };\n}\n\ninterface MediaSearchParams {\n currentType?: SharedMediaType;\n resultsByType?: Partial>;\n}\n\nfunction replaceLocalTextSearch(\n global: GlobalState,\n chatThreadKey: string,\n searchParams: TextSearchParams,\n): GlobalState {\n return {\n ...global,\n localTextSearch: {\n byChatThreadKey: {\n ...global.localTextSearch.byChatThreadKey,\n [chatThreadKey]: searchParams,\n },\n },\n };\n}\n\nexport function updateLocalTextSearch(\n global: GlobalState,\n chatId: string,\n threadId: number,\n isActive: boolean,\n query?: string,\n): GlobalState {\n const chatThreadKey = buildChatThreadKey(chatId, threadId);\n\n return replaceLocalTextSearch(global, chatThreadKey, {\n ...global.localTextSearch.byChatThreadKey[chatThreadKey],\n isActive,\n query,\n });\n}\n\nexport function replaceLocalTextSearchResults(\n global: GlobalState,\n chatId: string,\n threadId: number,\n foundIds?: number[],\n totalCount?: number,\n nextOffsetId?: number,\n): GlobalState {\n const chatThreadKey = buildChatThreadKey(chatId, threadId);\n\n return replaceLocalTextSearch(global, chatThreadKey, {\n ...global.localTextSearch.byChatThreadKey[chatThreadKey],\n results: {\n foundIds,\n totalCount,\n nextOffsetId,\n },\n });\n}\n\nexport function updateLocalTextSearchResults(\n global: GlobalState,\n chatId: string,\n threadId: number,\n newFoundIds: number[],\n totalCount?: number,\n nextOffsetId?: number,\n): GlobalState {\n const chatThreadKey = buildChatThreadKey(chatId, threadId);\n const { results } = global.localTextSearch.byChatThreadKey[chatThreadKey] || {};\n const prevFoundIds = (results?.foundIds) || [];\n const foundIds = orderFoundIds(unique(Array.prototype.concat(prevFoundIds, newFoundIds)));\n const foundOrPrevFoundIds = areSortedArraysEqual(prevFoundIds, foundIds) ? prevFoundIds : foundIds;\n\n return replaceLocalTextSearchResults(global, chatId, threadId, foundOrPrevFoundIds, totalCount, nextOffsetId);\n}\n\nfunction replaceLocalMediaSearch(\n global: GlobalState,\n chatId: string,\n searchParams: MediaSearchParams,\n): GlobalState {\n return {\n ...global,\n localMediaSearch: {\n byChatId: {\n ...global.localMediaSearch.byChatId,\n [chatId]: searchParams,\n },\n },\n };\n}\n\nexport function updateLocalMediaSearchType(\n global: GlobalState,\n chatId: string,\n currentType: SharedMediaType | undefined,\n): GlobalState {\n return replaceLocalMediaSearch(global, chatId, {\n ...global.localMediaSearch.byChatId[chatId],\n currentType,\n });\n}\n\nexport function replaceLocalMediaSearchResults(\n global: GlobalState,\n chatId: string,\n type: ApiMessageSearchType,\n foundIds?: number[],\n totalCount?: number,\n nextOffsetId?: number,\n): GlobalState {\n return replaceLocalMediaSearch(global, chatId, {\n ...global.localMediaSearch.byChatId[chatId],\n resultsByType: {\n ...(global.localMediaSearch.byChatId[chatId] || {}).resultsByType,\n [type]: {\n foundIds,\n totalCount,\n nextOffsetId,\n },\n },\n });\n}\n\nexport function updateLocalMediaSearchResults(\n global: GlobalState,\n chatId: string,\n type: SharedMediaType,\n newFoundIds: number[],\n totalCount?: number,\n nextOffsetId?: number,\n): GlobalState {\n const { resultsByType } = global.localMediaSearch.byChatId[chatId] || {};\n const prevFoundIds = resultsByType?.[type] ? resultsByType[type]!.foundIds : [];\n const foundIds = orderFoundIds(unique(Array.prototype.concat(prevFoundIds, newFoundIds)));\n const foundOrPrevFoundIds = areSortedArraysEqual(prevFoundIds, foundIds) ? prevFoundIds : foundIds;\n\n return replaceLocalMediaSearchResults(global, chatId, type, foundOrPrevFoundIds, totalCount, nextOffsetId);\n}\n\nfunction orderFoundIds(listedIds: number[]) {\n return listedIds.sort((a, b) => a - b);\n}\n","import { GlobalState } from '../../global/types';\nimport { ManagementProgress } from '../../types';\n\ninterface ManagementState {\n isActive: boolean;\n isUsernameAvailable?: boolean;\n error?: string;\n}\n\nexport function updateManagementProgress(global: GlobalState, progress: ManagementProgress): GlobalState {\n return {\n ...global,\n management: {\n ...global.management,\n progress,\n },\n };\n}\n\nexport function updateManagement(global: GlobalState, chatId: string, update: Partial): GlobalState {\n return {\n ...global,\n management: {\n ...global.management,\n byChatId: {\n ...global.management.byChatId,\n [chatId]: {\n ...(global.management.byChatId[chatId] || {}),\n ...update,\n },\n },\n },\n };\n}\n","import { GlobalState } from '../../global/types';\nimport {\n ISettings, IThemeSettings, ThemeKey, NotifyException,\n} from '../../types';\nimport { ApiNotifyException } from '../../api/types';\nimport { updateUserBlockedState } from './users';\n\nexport function replaceSettings(global: GlobalState, newSettings?: Partial): GlobalState {\n return {\n ...global,\n settings: {\n ...global.settings,\n byKey: {\n ...global.settings.byKey,\n ...newSettings,\n },\n },\n };\n}\n\nexport function replaceThemeSettings(\n global: GlobalState, theme: ThemeKey, newSettings?: Partial,\n): GlobalState {\n return {\n ...global,\n settings: {\n ...global.settings,\n themes: {\n ...global.settings.themes,\n [theme]: {\n ...(global.settings.themes[theme] || {}),\n ...newSettings,\n },\n },\n },\n };\n}\n\nexport function addNotifyExceptions(\n global: GlobalState, notifyExceptions: ApiNotifyException[],\n): GlobalState {\n notifyExceptions.forEach((notifyException) => {\n const { chatId, ...exceptionData } = notifyException;\n global = addNotifyException(global, chatId, exceptionData);\n });\n\n return global;\n}\n\nexport function addNotifyException(\n global: GlobalState, id: string, notifyException: NotifyException,\n): GlobalState {\n return {\n ...global,\n settings: {\n ...global.settings,\n notifyExceptions: {\n ...global.settings.notifyExceptions,\n [id]: notifyException,\n },\n },\n };\n}\n\nexport function updateNotifySettings(\n global: GlobalState, peerType: 'contact' | 'group' | 'broadcast', isSilent?: boolean, shouldShowPreviews?: boolean,\n) {\n switch (peerType) {\n case 'contact':\n return replaceSettings(global, {\n ...(typeof isSilent !== 'undefined' && { hasPrivateChatsNotifications: !isSilent }),\n ...(typeof shouldShowPreviews !== 'undefined' && { hasPrivateChatsMessagePreview: shouldShowPreviews }),\n });\n case 'group':\n return replaceSettings(global, {\n ...(typeof isSilent !== 'undefined' && { hasGroupNotifications: !isSilent }),\n ...(typeof shouldShowPreviews !== 'undefined' && { hasGroupMessagePreview: shouldShowPreviews }),\n });\n case 'broadcast':\n return replaceSettings(global, {\n ...(typeof isSilent !== 'undefined' && { hasBroadcastNotifications: !isSilent }),\n ...(typeof shouldShowPreviews !== 'undefined' && { hasBroadcastMessagePreview: shouldShowPreviews }),\n });\n\n default:\n return undefined;\n }\n}\n\nexport function addBlockedContact(global: GlobalState, contactId: string): GlobalState {\n global = updateUserBlockedState(global, contactId, true);\n\n return {\n ...global,\n blocked: {\n ...global.blocked,\n ids: [contactId, ...global.blocked.ids],\n totalCount: global.blocked.totalCount + 1,\n },\n };\n}\n\nexport function removeBlockedContact(global: GlobalState, contactId: string): GlobalState {\n global = updateUserBlockedState(global, contactId, false);\n\n return {\n ...global,\n blocked: {\n ...global.blocked,\n ids: global.blocked.ids.filter((id) => id !== contactId),\n totalCount: global.blocked.totalCount - 1,\n },\n };\n}\n","import { GlobalState } from '../../global/types';\n\nexport function updateTwoFaSettings(\n global: GlobalState,\n update: GlobalState['twoFaSettings'],\n): GlobalState {\n return {\n ...global,\n twoFaSettings: {\n ...global.twoFaSettings,\n ...update,\n },\n };\n}\n","import { GlobalState } from '../../global/types';\nimport { ShippingOption, PaymentStep } from '../../types';\nimport { ApiMessage, ApiPaymentForm, ApiReceipt } from '../../api/types';\n\nexport function updateShippingOptions(\n global: GlobalState,\n shippingOptions: ShippingOption[],\n): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n shippingOptions,\n },\n };\n}\n\nexport function setRequestInfoId(global: GlobalState, id: string): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n requestId: id,\n },\n };\n}\n\nexport function setPaymentStep(global: GlobalState, step: PaymentStep): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n step,\n },\n };\n}\n\nexport function setInvoiceMessageInfo(global: GlobalState, message: ApiMessage): GlobalState {\n if (!message.content || !message.content.invoice) {\n return global;\n }\n const {\n title,\n text,\n amount,\n currency,\n isTest,\n photoUrl,\n } = message.content.invoice;\n return {\n ...global,\n payment: {\n ...global.payment,\n invoiceContent: {\n title,\n text,\n photoUrl,\n amount,\n currency,\n isTest,\n },\n },\n };\n}\n\nexport function setStripeCardInfo(global: GlobalState, cardInfo: { type: string; id: string }): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n stripeCredentials: {\n ...cardInfo,\n },\n },\n };\n}\n\nexport function setPaymentForm(global: GlobalState, form: ApiPaymentForm): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n ...form,\n },\n };\n}\n\nexport function setReceipt(\n global: GlobalState,\n receipt?: ApiReceipt,\n message?: ApiMessage,\n): GlobalState {\n if (!receipt || !message) {\n return {\n ...global,\n payment: {\n ...global.payment,\n receipt: undefined,\n },\n };\n }\n\n const { invoice: messageInvoice } = message.content;\n const { photoUrl, text, title } = (messageInvoice || {});\n\n return {\n ...global,\n payment: {\n ...global.payment,\n receipt: {\n ...receipt,\n photoUrl,\n text,\n title,\n },\n },\n };\n}\n\nexport function clearPayment(global: GlobalState): GlobalState {\n return {\n ...global,\n payment: {},\n };\n}\n\nexport function closeInvoice(global: GlobalState): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n isPaymentModalOpen: false,\n },\n };\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiChat, ApiUser } from '../../api/types';\n\nexport function selectUser(global: GlobalState, userId: string): ApiUser | undefined {\n return global.users.byId[userId];\n}\n\nexport function selectIsUserBlocked(global: GlobalState, userId: string) {\n const user = selectUser(global, userId);\n\n return user?.fullInfo?.isBlocked;\n}\n\n// Slow, not to be used in `withGlobal`\nexport function selectUserByUsername(global: GlobalState, username: string) {\n const usernameLowered = username.toLowerCase();\n return Object.values(global.users.byId).find(\n (user) => user.username.toLowerCase() === usernameLowered,\n );\n}\n\nexport function selectIsUserOrChatContact(global: GlobalState, userOrChat: ApiUser | ApiChat) {\n return global.contactList && global.contactList.userIds.includes(userOrChat.id);\n}\n","import { GlobalState } from '../../global/types';\n\nexport function selectNotifySettings(global: GlobalState) {\n return global.settings.byKey;\n}\n\nexport function selectNotifyExceptions(global: GlobalState) {\n return global.settings.notifyExceptions;\n}\n","import { ApiChat, MAIN_THREAD_ID } from '../../api/types';\nimport { GlobalState } from '../../global/types';\n\nimport {\n getPrivateChatUserId, isChatChannel, isUserId, isHistoryClearMessage, isUserBot, isUserOnline, selectIsChatMuted,\n} from '../helpers';\nimport { selectUser } from './users';\nimport {\n ALL_FOLDER_ID, ARCHIVED_FOLDER_ID, MEMBERS_LOAD_SLICE, SERVICE_NOTIFICATIONS_USER_ID,\n} from '../../config';\nimport { selectNotifyExceptions, selectNotifySettings } from './settings';\n\nexport function selectChat(global: GlobalState, chatId: string): ApiChat | undefined {\n return global.chats.byId[chatId];\n}\n\nexport function selectChatUser(global: GlobalState, chat: ApiChat) {\n const userId = getPrivateChatUserId(chat);\n if (!userId) {\n return false;\n }\n\n return selectUser(global, userId);\n}\n\nexport function selectIsChatWithSelf(global: GlobalState, chatId: string) {\n return chatId === global.currentUserId;\n}\n\nexport function selectIsChatWithBot(global: GlobalState, chat: ApiChat) {\n const user = selectChatUser(global, chat);\n return user && isUserBot(user);\n}\n\nexport function selectSupportChat(global: GlobalState) {\n return Object.values(global.chats.byId).find(({ isSupport }: ApiChat) => isSupport);\n}\n\nexport function selectChatOnlineCount(global: GlobalState, chat: ApiChat) {\n if (isUserId(chat.id) || isChatChannel(chat) || !chat.fullInfo) {\n return undefined;\n }\n\n if (!chat.fullInfo.members || chat.fullInfo.members.length === MEMBERS_LOAD_SLICE) {\n return chat.fullInfo.onlineCount;\n }\n\n return chat.fullInfo.members.reduce((onlineCount, { userId }) => {\n if (global.users.byId[userId] && isUserOnline(global.users.byId[userId]) && userId !== global.currentUserId) {\n return onlineCount + 1;\n }\n\n return onlineCount;\n }, 0);\n}\n\nexport function selectChatBot(global: GlobalState, chatId: string) {\n const chat = selectChat(global, chatId);\n const userId = chat && getPrivateChatUserId(chat);\n const user = userId && selectUser(global, userId);\n if (!user || !isUserBot(user)) {\n return undefined;\n }\n\n return user;\n}\n\nexport function selectIsChatBotNotStarted(global: GlobalState, chatId: string) {\n const chat = selectChat(global, chatId);\n const bot = selectChatBot(global, chatId);\n if (!chat || !bot) {\n return false;\n }\n\n if (chat.lastMessage && isHistoryClearMessage(chat.lastMessage)) {\n return true;\n }\n\n const messageInfo = global.messages.byChatId[chatId];\n if (!messageInfo) {\n return false;\n }\n\n const { listedIds } = messageInfo.threadsById[MAIN_THREAD_ID] || {};\n return listedIds && !listedIds.length;\n}\n\nexport function selectAreActiveChatsLoaded(global: GlobalState): boolean {\n return Boolean(global.chats.listIds.active);\n}\n\nexport function selectIsChatListed(global: GlobalState, chatId: string, type?: 'active' | 'archived'): boolean {\n const { listIds } = global.chats;\n if (type) {\n const targetList = listIds[type];\n return Boolean(targetList && targetList.includes(chatId));\n }\n\n return Object.values(listIds).some((list) => list && list.includes(chatId));\n}\n\nexport function selectChatListType(global: GlobalState, chatId: string): 'active' | 'archived' | undefined {\n const chat = selectChat(global, chatId);\n if (!chat || !selectIsChatListed(global, chatId)) {\n return undefined;\n }\n\n return chat.folderId === ARCHIVED_FOLDER_ID ? 'archived' : 'active';\n}\n\nexport function selectChatFolder(global: GlobalState, folderId: number) {\n return global.chatFolders.byId[folderId];\n}\n\nexport function selectTotalChatCount(global: GlobalState, listType: 'active' | 'archived'): number {\n const { totalCount } = global.chats;\n const allChatsCount = totalCount.all;\n const archivedChatsCount = totalCount.archived || 0;\n\n if (listType === 'archived') {\n return archivedChatsCount;\n }\n\n return allChatsCount ? allChatsCount - archivedChatsCount : 0;\n}\n\nexport function selectIsChatPinned(global: GlobalState, chatId: string, folderId = ALL_FOLDER_ID): boolean {\n const { active, archived } = global.chats.orderedPinnedIds;\n\n if (folderId === ALL_FOLDER_ID) {\n return !!active && active.includes(chatId);\n }\n\n if (folderId === ARCHIVED_FOLDER_ID) {\n return !!archived && archived.includes(chatId);\n }\n\n const { byId: chatFoldersById } = global.chatFolders;\n\n const { pinnedChatIds } = chatFoldersById[folderId] || {};\n return !!pinnedChatIds && pinnedChatIds.includes(chatId);\n}\n\n// Slow, not to be used in `withGlobal`\nexport function selectChatByUsername(global: GlobalState, username: string) {\n const usernameLowered = username.toLowerCase();\n return Object.values(global.chats.byId).find(\n (chat) => chat.username && chat.username.toLowerCase() === usernameLowered,\n );\n}\n\n// Slow, not to be used in `withGlobal`\nexport function selectCountNotMutedUnread(global: GlobalState) {\n const activeChatIds = global.chats.listIds.active;\n if (!activeChatIds) {\n return 0;\n }\n\n const chats = global.chats.byId;\n const notifySettings = selectNotifySettings(global);\n const notifyExceptions = selectNotifyExceptions(global);\n\n return activeChatIds.reduce((acc, chatId) => {\n const chat = chats[chatId];\n\n if (\n chat\n && chat.unreadCount\n && chat.isListed\n && !chat.isNotJoined\n && !chat.isRestricted\n && (chat.unreadMentionsCount || !selectIsChatMuted(chat, notifySettings, notifyExceptions))\n ) {\n return acc + chat.unreadCount;\n }\n\n return acc;\n }, 0);\n}\n\nexport function selectIsServiceChatReady(global: GlobalState) {\n return Boolean(selectChat(global, SERVICE_NOTIFICATIONS_USER_ID));\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiSticker } from '../../api/types';\n\nexport function selectIsStickerFavorite(global: GlobalState, sticker: ApiSticker) {\n const { stickers } = global.stickers.favorite;\n return stickers && stickers.some(({ id }) => id === sticker.id);\n}\n\nexport function selectCurrentStickerSearch(global: GlobalState) {\n return global.stickers.search;\n}\n\nexport function selectCurrentGifSearch(global: GlobalState) {\n return global.gifs.search;\n}\n\nexport function selectStickerSet(global: GlobalState, id: string) {\n return global.stickers.setsById[id];\n}\n\nexport function selectStickerSetByShortName(global: GlobalState, shortName: string) {\n return Object.values(global.stickers.setsById).find((l) => l.shortName.toLowerCase() === shortName.toLowerCase());\n}\n\nexport function selectStickersForEmoji(global: GlobalState, emoji: string) {\n const stickerSets = Object.values(global.stickers.setsById);\n let stickersForEmoji: ApiSticker[] = [];\n stickerSets.forEach(({ packs }) => {\n if (!packs) {\n return;\n }\n const stickers = packs[emoji];\n if (stickers) {\n stickersForEmoji = stickersForEmoji.concat(stickers);\n }\n });\n return stickersForEmoji;\n}\n\nexport function selectAnimatedEmoji(global: GlobalState, emoji: string) {\n const { animatedEmojis } = global;\n if (!animatedEmojis || !animatedEmojis.stickers) {\n return undefined;\n }\n\n // Some emojis (❤️ for example) with a service symbol 'VARIATION SELECTOR-16' are not recognized as animated\n const cleanedEmoji = emoji.replace('\\ufe0f', '');\n\n return animatedEmojis.stickers.find((sticker) => sticker.emoji === emoji || sticker.emoji === cleanedEmoji);\n}\n","import { GlobalState, MessageListType, Thread } from '../../global/types';\nimport {\n ApiChat,\n ApiMessage,\n ApiMessageOutgoingStatus,\n ApiUser,\n MAIN_THREAD_ID,\n} from '../../api/types';\n\nimport { LOCAL_MESSAGE_ID_BASE, SERVICE_NOTIFICATIONS_USER_ID } from '../../config';\nimport {\n selectChat, selectIsChatWithBot, selectIsChatWithSelf,\n} from './chats';\nimport { selectIsUserOrChatContact, selectUser } from './users';\nimport {\n getSendingState,\n isChatChannel,\n isMessageLocal,\n isUserId,\n isForwardedMessage,\n getCanPostInChat,\n isUserRightBanned,\n getHasAdminRight,\n isChatBasicGroup,\n isCommonBoxChat,\n isServiceNotificationMessage,\n isOwnMessage,\n isActionMessage,\n isChatGroup,\n isChatSuperGroup,\n getMessageVideo,\n getMessageWebPageVideo,\n getMessagePhoto,\n getMessageAudio,\n getMessageVoice,\n getMessageDocument,\n getMessageWebPagePhoto,\n} from '../helpers';\nimport { findLast } from '../../util/iteratees';\nimport { selectIsStickerFavorite } from './symbols';\nimport { getServerTime } from '../../util/serverTime';\nimport { MEMO_EMPTY_ARRAY } from '../../util/memo';\n\nconst MESSAGE_EDIT_ALLOWED_TIME = 172800; // 48 hours\n\nexport function selectCurrentMessageList(global: GlobalState) {\n const { messageLists } = global.messages;\n\n if (messageLists.length) {\n return messageLists[messageLists.length - 1];\n }\n\n return undefined;\n}\n\nexport function selectCurrentChat(global: GlobalState) {\n const { chatId } = selectCurrentMessageList(global) || {};\n\n return chatId ? selectChat(global, chatId) : undefined;\n}\n\nexport function selectChatMessages(global: GlobalState, chatId: string) {\n return global.messages.byChatId[chatId]?.byId;\n}\n\nexport function selectScheduledMessages(global: GlobalState, chatId: string) {\n return global.scheduledMessages.byChatId[chatId]?.byId;\n}\n\nexport function selectThreadParam(\n global: GlobalState,\n chatId: string,\n threadId: number,\n key: K,\n) {\n const messageInfo = global.messages.byChatId[chatId];\n if (!messageInfo) {\n return undefined;\n }\n\n const thread = messageInfo.threadsById[threadId];\n if (!thread) {\n return undefined;\n }\n\n return thread[key];\n}\n\nexport function selectListedIds(global: GlobalState, chatId: string, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'listedIds');\n}\n\nexport function selectOutlyingIds(global: GlobalState, chatId: string, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'outlyingIds');\n}\n\nexport function selectCurrentMessageIds(\n global: GlobalState, chatId: string, threadId: number, messageListType: MessageListType,\n) {\n switch (messageListType) {\n case 'thread':\n return selectViewportIds(global, chatId, threadId);\n case 'pinned':\n return selectPinnedIds(global, chatId);\n case 'scheduled':\n return selectScheduledIds(global, chatId);\n }\n\n return undefined;\n}\n\nexport function selectViewportIds(global: GlobalState, chatId: string, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'viewportIds');\n}\n\nexport function selectPinnedIds(global: GlobalState, chatId: string) {\n return selectThreadParam(global, chatId, MAIN_THREAD_ID, 'pinnedIds');\n}\n\nexport function selectScheduledIds(global: GlobalState, chatId: string) {\n return selectThreadParam(global, chatId, MAIN_THREAD_ID, 'scheduledIds');\n}\n\nexport function selectScrollOffset(global: GlobalState, chatId: string, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'scrollOffset');\n}\n\nexport function selectReplyingToId(global: GlobalState, chatId: string, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'replyingToId');\n}\n\nexport function selectEditingId(global: GlobalState, chatId: string, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'editingId');\n}\n\nexport function selectEditingScheduledId(global: GlobalState, chatId: string) {\n return selectThreadParam(global, chatId, MAIN_THREAD_ID, 'editingScheduledId');\n}\n\nexport function selectDraft(global: GlobalState, chatId: string, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'draft');\n}\n\nexport function selectNoWebPage(global: GlobalState, chatId: string, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'noWebPage');\n}\n\nexport function selectThreadInfo(global: GlobalState, chatId: string, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'threadInfo');\n}\n\nexport function selectFirstMessageId(global: GlobalState, chatId: string, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'firstMessageId');\n}\n\nexport function selectReplyStack(global: GlobalState, chatId: string, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'replyStack');\n}\n\nexport function selectThreadOriginChat(global: GlobalState, chatId: string, threadId: number) {\n if (threadId === MAIN_THREAD_ID) {\n return selectChat(global, chatId);\n }\n\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n if (!threadInfo) {\n return undefined;\n }\n\n return selectChat(global, threadInfo.originChannelId || chatId);\n}\n\nexport function selectThreadTopMessageId(global: GlobalState, chatId: string, threadId: number) {\n if (threadId === MAIN_THREAD_ID) {\n return undefined;\n }\n\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n if (!threadInfo) {\n return undefined;\n }\n\n return threadInfo.topMessageId;\n}\n\nexport function selectThreadByMessage(global: GlobalState, chatId: string, message: ApiMessage) {\n const messageInfo = global.messages.byChatId[chatId];\n if (!messageInfo) {\n return undefined;\n }\n\n const { replyToMessageId, replyToTopMessageId } = message;\n if (!replyToMessageId && !replyToTopMessageId) {\n return undefined;\n }\n\n return Object.values(messageInfo.threadsById).find((thread) => {\n return thread.threadInfo && (\n (replyToMessageId && replyToMessageId === thread.threadInfo.topMessageId)\n || (replyToTopMessageId && replyToTopMessageId === thread.threadInfo.topMessageId)\n );\n });\n}\n\nexport function isMessageInCurrentMessageList(global: GlobalState, chatId: string, message: ApiMessage) {\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return false;\n }\n\n const { threadInfo } = selectThreadByMessage(global, chatId, message) || {};\n return (\n chatId === currentMessageList.chatId\n && (\n (currentMessageList.threadId === MAIN_THREAD_ID)\n || (threadInfo && currentMessageList.threadId === threadInfo.threadId)\n )\n );\n}\n\nexport function selectIsViewportNewest(global: GlobalState, chatId: string, threadId: number) {\n const viewportIds = selectViewportIds(global, chatId, threadId);\n if (!viewportIds || !viewportIds.length) {\n return true;\n }\n\n let lastMessageId: number;\n\n if (threadId === MAIN_THREAD_ID) {\n const chat = selectChat(global, chatId);\n if (!chat || !chat.lastMessage) {\n return true;\n }\n\n lastMessageId = chat.lastMessage.id;\n } else {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n if (!threadInfo || !threadInfo.lastMessageId) {\n return undefined;\n }\n\n lastMessageId = threadInfo.lastMessageId;\n }\n\n // Edge case: outgoing `lastMessage` is updated with a delay to optimize animation\n if (lastMessageId >= LOCAL_MESSAGE_ID_BASE && !selectChatMessage(global, chatId, lastMessageId)) {\n return true;\n }\n\n return viewportIds[viewportIds.length - 1] >= lastMessageId;\n}\n\nexport function selectChatMessage(global: GlobalState, chatId: string, messageId: number) {\n const chatMessages = selectChatMessages(global, chatId);\n\n return chatMessages ? chatMessages[messageId] : undefined;\n}\n\nexport function selectScheduledMessage(global: GlobalState, chatId: string, messageId: number) {\n const chatMessages = selectScheduledMessages(global, chatId);\n\n return chatMessages ? chatMessages[messageId] : undefined;\n}\n\nexport function selectEditingMessage(\n global: GlobalState, chatId: string, threadId: number, messageListType: MessageListType,\n) {\n if (messageListType === 'scheduled') {\n const messageId = selectEditingScheduledId(global, chatId);\n return messageId ? selectScheduledMessage(global, chatId, messageId) : undefined;\n } else {\n const messageId = selectEditingId(global, chatId, threadId);\n return messageId ? selectChatMessage(global, chatId, messageId) : undefined;\n }\n}\n\nexport function selectChatMessageByPollId(global: GlobalState, pollId: string) {\n let messageWithPoll: ApiMessage | undefined;\n\n // eslint-disable-next-line no-restricted-syntax\n for (const chatMessages of Object.values(global.messages.byChatId)) {\n const { byId } = chatMessages;\n messageWithPoll = Object.values(byId).find((message) => {\n return message.content.poll && message.content.poll.id === pollId;\n });\n if (messageWithPoll) {\n break;\n }\n }\n\n return messageWithPoll;\n}\n\nexport function selectFocusedMessageId(global: GlobalState, chatId: string) {\n const { chatId: focusedChatId, messageId } = global.focusedMessage || {};\n\n return focusedChatId === chatId ? messageId : undefined;\n}\n\nexport function selectIsMessageFocused(global: GlobalState, message: ApiMessage) {\n const focusedId = selectFocusedMessageId(global, message.chatId);\n\n return focusedId ? focusedId === message.id || focusedId === message.previousLocalId : false;\n}\n\nexport function selectIsMessageUnread(global: GlobalState, message: ApiMessage) {\n const { lastReadOutboxMessageId } = selectChat(global, message.chatId) || {};\n return isMessageLocal(message) || !lastReadOutboxMessageId || lastReadOutboxMessageId < message.id;\n}\n\nexport function selectOutgoingStatus(\n global: GlobalState, message: ApiMessage, isScheduledList = false,\n): ApiMessageOutgoingStatus {\n if (!selectIsMessageUnread(global, message) && !isScheduledList) {\n return 'read';\n }\n\n return getSendingState(message);\n}\n\nexport function selectSender(global: GlobalState, message: ApiMessage): ApiUser | ApiChat | undefined {\n const { senderId } = message;\n if (!senderId) {\n return undefined;\n }\n\n return isUserId(senderId) ? selectUser(global, senderId) : selectChat(global, senderId);\n}\n\nexport function selectForwardedSender(global: GlobalState, message: ApiMessage): ApiUser | ApiChat | undefined {\n const { forwardInfo } = message;\n if (!forwardInfo) {\n return undefined;\n }\n\n if (forwardInfo.isChannelPost && forwardInfo.fromChatId) {\n return selectChat(global, forwardInfo.fromChatId);\n } else if (forwardInfo.senderUserId) {\n return selectUser(global, forwardInfo.senderUserId) || selectChat(global, forwardInfo.senderUserId);\n }\n\n return undefined;\n}\n\nexport function selectAllowedMessageActions(global: GlobalState, message: ApiMessage, threadId: number) {\n const chat = selectChat(global, message.chatId);\n if (!chat || chat.isRestricted) {\n return {};\n }\n\n const isPrivate = isUserId(chat.id);\n const isChatWithSelf = selectIsChatWithSelf(global, message.chatId);\n const isBasicGroup = isChatBasicGroup(chat);\n const isSuperGroup = isChatSuperGroup(chat);\n const isChannel = isChatChannel(chat);\n const isLocal = isMessageLocal(message);\n const isServiceNotification = isServiceNotificationMessage(message);\n const isOwn = isOwnMessage(message);\n const isAction = isActionMessage(message);\n const { content } = message;\n\n const canEditMessagesIndefinitely = isChatWithSelf\n || (isSuperGroup && getHasAdminRight(chat, 'pinMessages'))\n || (isChannel && getHasAdminRight(chat, 'editMessages'));\n const isMessageEditable = (\n (\n canEditMessagesIndefinitely\n || getServerTime(global.serverTimeOffset) - message.date < MESSAGE_EDIT_ALLOWED_TIME\n ) && !(\n content.sticker || content.contact || content.poll || content.action || content.audio\n || (content.video?.isRound)\n )\n && !isForwardedMessage(message)\n && !message.viaBotId\n );\n\n const canReply = !isLocal && !isServiceNotification && getCanPostInChat(chat, threadId);\n\n const hasPinPermission = isPrivate || (\n chat.isCreator\n || (!isChannel && !isUserRightBanned(chat, 'pinMessages'))\n || getHasAdminRight(chat, 'pinMessages')\n );\n\n let canPin = !isLocal && !isServiceNotification && !isAction && hasPinPermission;\n let canUnpin = false;\n\n const pinnedMessageIds = selectPinnedIds(global, chat.id);\n\n if (canPin) {\n canUnpin = Boolean(pinnedMessageIds && pinnedMessageIds.includes(message.id));\n canPin = !canUnpin;\n }\n\n const canDelete = !isLocal && !isServiceNotification && (\n isPrivate\n || isOwn\n || isBasicGroup\n || chat.isCreator\n || getHasAdminRight(chat, 'deleteMessages')\n );\n\n const canReport = !isPrivate && !isOwn;\n\n const canDeleteForAll = canDelete && (\n (isPrivate && !isChatWithSelf)\n || (isBasicGroup && (\n isOwn || getHasAdminRight(chat, 'deleteMessages') || chat.isCreator\n ))\n );\n\n const canEdit = !isLocal && !isAction && isMessageEditable && (\n isOwn\n || (isChannel && (chat.isCreator || getHasAdminRight(chat, 'editMessages')))\n );\n\n const canForward = !isLocal && !isAction;\n\n const hasSticker = Boolean(message.content.sticker);\n const hasFavoriteSticker = hasSticker && selectIsStickerFavorite(global, message.content.sticker!);\n const canFaveSticker = !isAction && hasSticker && !hasFavoriteSticker;\n const canUnfaveSticker = !isAction && hasFavoriteSticker;\n const canCopy = !isAction;\n const canCopyLink = !isAction && (isChannel || isSuperGroup);\n const canSelect = !isAction;\n\n const canDownload = Boolean(content.webPage?.document || content.webPage?.video || content.webPage?.photo\n || content.audio || content.voice || content.photo || content.video || content.document || content.sticker);\n\n const noOptions = [\n canReply,\n canEdit,\n canPin,\n canUnpin,\n canReport,\n canDelete,\n canDeleteForAll,\n canForward,\n canFaveSticker,\n canUnfaveSticker,\n canCopy,\n canCopyLink,\n canSelect,\n canDownload,\n ].every((ability) => !ability);\n\n return {\n noOptions,\n canReply,\n canEdit,\n canPin,\n canUnpin,\n canReport,\n canDelete,\n canDeleteForAll,\n canForward,\n canFaveSticker,\n canUnfaveSticker,\n canCopy,\n canCopyLink,\n canSelect,\n canDownload,\n };\n}\n\n// This selector always returns a new object which can not be safely used in shallow-equal checks\nexport function selectCanDeleteSelectedMessages(global: GlobalState) {\n const { messageIds: selectedMessageIds } = global.selectedMessages || {};\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n const chatMessages = chatId && selectChatMessages(global, chatId);\n if (!chatMessages || !selectedMessageIds || !threadId) {\n return {};\n }\n\n const messageActions = selectedMessageIds\n .map((id) => chatMessages[id] && selectAllowedMessageActions(global, chatMessages[id], threadId))\n .filter(Boolean);\n\n return {\n canDelete: messageActions.every((actions) => actions.canDelete),\n canDeleteForAll: messageActions.every((actions) => actions.canDeleteForAll),\n };\n}\n\nexport function selectCanReportSelectedMessages(global: GlobalState) {\n const { messageIds: selectedMessageIds } = global.selectedMessages || {};\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n const chatMessages = chatId && selectChatMessages(global, chatId);\n if (!chatMessages || !selectedMessageIds || !threadId) {\n return false;\n }\n\n const messageActions = selectedMessageIds\n .map((id) => chatMessages[id] && selectAllowedMessageActions(global, chatMessages[id], threadId))\n .filter(Boolean);\n\n return messageActions.every((actions) => actions.canReport);\n}\n\nexport function selectCanDownloadSelectedMessages(global: GlobalState) {\n const { messageIds: selectedMessageIds } = global.selectedMessages || {};\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n const chatMessages = chatId && selectChatMessages(global, chatId);\n if (!chatMessages || !selectedMessageIds || !threadId) {\n return false;\n }\n\n const messageActions = selectedMessageIds\n .map((id) => chatMessages[id] && selectAllowedMessageActions(global, chatMessages[id], threadId))\n .filter(Boolean);\n\n return messageActions.some((actions) => actions.canDownload);\n}\n\nexport function selectIsDownloading(global: GlobalState, message: ApiMessage) {\n const activeInChat = global.activeDownloads.byChatId[message.chatId];\n return activeInChat ? activeInChat.includes(message.id) : false;\n}\n\nexport function selectActiveDownloadIds(global: GlobalState, chatId: string) {\n return global.activeDownloads.byChatId[chatId] || MEMO_EMPTY_ARRAY;\n}\n\nexport function selectUploadProgress(global: GlobalState, message: ApiMessage) {\n return global.fileUploads.byMessageLocalId[message.previousLocalId || message.id]?.progress;\n}\n\nexport function selectRealLastReadId(global: GlobalState, chatId: string, threadId: number) {\n if (threadId === MAIN_THREAD_ID) {\n const chat = selectChat(global, chatId);\n if (!chat) {\n return undefined;\n }\n\n // `lastReadInboxMessageId` is empty for new chats\n if (!chat.lastReadInboxMessageId) {\n return undefined;\n }\n\n if (!chat.lastMessage) {\n return chat.lastReadInboxMessageId;\n }\n\n if (isMessageLocal(chat.lastMessage)) {\n return chat.lastMessage.id;\n }\n\n // Some previously read messages may be deleted\n return Math.min(chat.lastMessage.id, chat.lastReadInboxMessageId);\n } else {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n if (!threadInfo) {\n return undefined;\n }\n\n if (!threadInfo.lastReadInboxMessageId) {\n return threadInfo.topMessageId;\n }\n\n // Some previously read messages may be deleted\n return Math.min(threadInfo.lastReadInboxMessageId, threadInfo.lastMessageId || Infinity);\n }\n}\n\nexport function selectFirstUnreadId(global: GlobalState, chatId: string, threadId: number) {\n const chat = selectChat(global, chatId);\n\n if (threadId === MAIN_THREAD_ID) {\n if (!chat) {\n return undefined;\n }\n } else {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n if (!threadInfo\n || (threadInfo.lastMessageId !== undefined && threadInfo.lastMessageId === threadInfo.lastReadInboxMessageId)) {\n return undefined;\n }\n }\n\n const outlyingIds = selectOutlyingIds(global, chatId, threadId);\n const listedIds = selectListedIds(global, chatId, threadId);\n const byId = selectChatMessages(global, chatId);\n if (!byId || !(outlyingIds || listedIds)) {\n return undefined;\n }\n\n const lastReadId = selectRealLastReadId(global, chatId, threadId);\n if (!lastReadId && chat && chat.isNotJoined) {\n return undefined;\n }\n\n const lastReadServiceNotificationId = chatId === SERVICE_NOTIFICATIONS_USER_ID\n ? global.serviceNotifications.reduce((max, notification) => {\n return !notification.isUnread && notification.id > max ? notification.id : max;\n }, -1)\n : -1;\n\n function findAfterLastReadId(listIds: number[]) {\n if (!lastReadId) {\n return listIds[0];\n }\n\n return listIds.find((id) => {\n return (\n id > lastReadId\n && byId[id]\n && (!byId[id].isOutgoing || byId[id].isFromScheduled)\n && id > lastReadServiceNotificationId\n );\n });\n }\n\n if (outlyingIds) {\n const found = findAfterLastReadId(outlyingIds);\n if (found) {\n return found;\n }\n }\n\n if (listedIds) {\n const found = findAfterLastReadId(listedIds);\n if (found) {\n return found;\n }\n }\n\n return undefined;\n}\n\nexport function selectIsPollResultsOpen(global: GlobalState) {\n const { pollResults } = global;\n return Boolean(pollResults.messageId);\n}\n\nexport function selectIsForwardModalOpen(global: GlobalState) {\n const { forwardMessages } = global;\n return Boolean(forwardMessages.isModalShown);\n}\n\nexport function selectCommonBoxChatId(global: GlobalState, messageId: number) {\n const fromLastMessage = Object.values(global.chats.byId).find((chat) => (\n isCommonBoxChat(chat) && chat.lastMessage && chat.lastMessage.id === messageId\n ));\n if (fromLastMessage) {\n return fromLastMessage.id;\n }\n\n const { byChatId } = global.messages;\n return Object.keys(byChatId).find((chatId) => {\n const chat = selectChat(global, chatId);\n return chat && isCommonBoxChat(chat) && byChatId[chat.id].byId[messageId];\n });\n}\n\nexport function selectIsInSelectMode(global: GlobalState) {\n const { selectedMessages } = global;\n\n return Boolean(selectedMessages);\n}\n\nexport function selectIsMessageSelected(global: GlobalState, messageId: number) {\n const { messageIds } = global.selectedMessages || {};\n if (!messageIds) {\n return false;\n }\n\n return messageIds.includes(messageId);\n}\n\nexport function selectForwardedMessageIdsByGroupId(global: GlobalState, chatId: string, groupedId: string) {\n const chatMessages = selectChatMessages(global, chatId);\n if (!chatMessages) {\n return undefined;\n }\n\n return Object.values(chatMessages)\n .filter((message) => message.groupedId === groupedId && message.forwardInfo)\n .map(({ forwardInfo }) => forwardInfo!.fromMessageId);\n}\n\nexport function selectMessageIdsByGroupId(global: GlobalState, chatId: string, groupedId: string) {\n const chatMessages = selectChatMessages(global, chatId);\n if (!chatMessages) {\n return undefined;\n }\n\n return Object.keys(chatMessages)\n .map(Number)\n .filter((id) => chatMessages[id].groupedId === groupedId);\n}\n\nexport function selectIsDocumentGroupSelected(global: GlobalState, chatId: string, groupedId: string) {\n const { messageIds: selectedIds } = global.selectedMessages || {};\n if (!selectedIds) {\n return false;\n }\n\n const groupIds = selectMessageIdsByGroupId(global, chatId, groupedId);\n return groupIds && groupIds.every((id) => selectedIds.includes(id));\n}\n\nexport function selectSelectedMessagesCount(global: GlobalState) {\n const { messageIds } = global.selectedMessages || {};\n\n return messageIds ? messageIds.length : 0;\n}\n\nexport function selectNewestMessageWithBotKeyboardButtons(\n global: GlobalState, chatId: string,\n): ApiMessage | undefined {\n const chat = selectChat(global, chatId);\n if (!chat) {\n return undefined;\n }\n\n if (!selectIsChatWithBot(global, chat)) {\n return undefined;\n }\n\n const chatMessages = selectChatMessages(global, chatId);\n const viewportIds = selectViewportIds(global, chatId, MAIN_THREAD_ID);\n if (!chatMessages || !viewportIds) {\n return undefined;\n }\n\n const messageId = findLast(viewportIds, (id) => {\n return !chatMessages[id].isOutgoing && Boolean(chatMessages[id].keyboardButtons);\n });\n\n const replyHideMessageId = findLast(viewportIds, (id) => {\n return Boolean(chatMessages[id].shouldHideKeyboardButtons);\n });\n\n if (messageId && replyHideMessageId && replyHideMessageId > messageId) {\n return undefined;\n }\n\n return messageId ? chatMessages[messageId] : undefined;\n}\n\nexport function selectCanAutoLoadMedia(\n global: GlobalState, message: ApiMessage, chat: ApiChat, sender?: ApiChat | ApiUser,\n) {\n const isPhoto = Boolean(getMessagePhoto(message) || getMessageWebPagePhoto(message));\n const isVideo = Boolean(getMessageVideo(message) || getMessageWebPageVideo(message));\n const isFile = Boolean(getMessageAudio(message) || getMessageVoice(message) || getMessageDocument(message));\n\n const {\n canAutoLoadPhotoFromContacts,\n canAutoLoadPhotoInPrivateChats,\n canAutoLoadPhotoInGroups,\n canAutoLoadPhotoInChannels,\n canAutoLoadVideoFromContacts,\n canAutoLoadVideoInPrivateChats,\n canAutoLoadVideoInGroups,\n canAutoLoadVideoInChannels,\n canAutoLoadFileFromContacts,\n canAutoLoadFileInPrivateChats,\n canAutoLoadFileInGroups,\n canAutoLoadFileInChannels,\n } = global.settings.byKey;\n\n if (isPhoto) {\n return canAutoLoadMedia({\n global,\n chat,\n sender,\n canAutoLoadMediaFromContacts: canAutoLoadPhotoFromContacts,\n canAutoLoadMediaInPrivateChats: canAutoLoadPhotoInPrivateChats,\n canAutoLoadMediaInGroups: canAutoLoadPhotoInGroups,\n canAutoLoadMediaInChannels: canAutoLoadPhotoInChannels,\n });\n }\n\n if (isVideo) {\n return canAutoLoadMedia({\n global,\n chat,\n sender,\n canAutoLoadMediaFromContacts: canAutoLoadVideoFromContacts,\n canAutoLoadMediaInPrivateChats: canAutoLoadVideoInPrivateChats,\n canAutoLoadMediaInGroups: canAutoLoadVideoInGroups,\n canAutoLoadMediaInChannels: canAutoLoadVideoInChannels,\n });\n }\n\n if (isFile) {\n return canAutoLoadMedia({\n global,\n chat,\n sender,\n canAutoLoadMediaFromContacts: canAutoLoadFileFromContacts,\n canAutoLoadMediaInPrivateChats: canAutoLoadFileInPrivateChats,\n canAutoLoadMediaInGroups: canAutoLoadFileInGroups,\n canAutoLoadMediaInChannels: canAutoLoadFileInChannels,\n });\n }\n\n return true;\n}\n\nfunction canAutoLoadMedia({\n global,\n chat,\n sender,\n canAutoLoadMediaFromContacts,\n canAutoLoadMediaInPrivateChats,\n canAutoLoadMediaInGroups,\n canAutoLoadMediaInChannels,\n}: {\n global: GlobalState;\n chat: ApiChat;\n canAutoLoadMediaFromContacts: boolean;\n canAutoLoadMediaInPrivateChats: boolean;\n canAutoLoadMediaInGroups: boolean;\n canAutoLoadMediaInChannels: boolean;\n sender?: ApiChat | ApiUser;\n}) {\n const isMediaFromContact = Boolean(sender && (\n sender.id === global.currentUserId || selectIsUserOrChatContact(global, sender)\n ));\n\n return Boolean(\n (isMediaFromContact && canAutoLoadMediaFromContacts)\n || (!isMediaFromContact && canAutoLoadMediaInPrivateChats && isUserId(chat.id))\n || (canAutoLoadMediaInGroups && isChatGroup(chat))\n || (canAutoLoadMediaInChannels && isChatChannel(chat)),\n );\n}\n\nexport function selectCanAutoPlayMedia(global: GlobalState, message: ApiMessage) {\n const video = getMessageVideo(message) || getMessageWebPageVideo(message);\n if (!video) {\n return undefined;\n }\n\n const {\n canAutoPlayVideos,\n canAutoPlayGifs,\n } = global.settings.byKey;\n\n const asGif = video.isGif || video.isRound;\n\n return (canAutoPlayVideos && !asGif) || (canAutoPlayGifs && asGif);\n}\n\nexport function selectShouldLoopStickers(global: GlobalState) {\n return global.settings.byKey.shouldLoopStickers;\n}\n\nexport function selectLastServiceNotification(global: GlobalState) {\n const { serviceNotifications } = global;\n const maxId = Math.max(...serviceNotifications.map(({ id }) => id));\n\n return serviceNotifications.find(({ id }) => id === maxId);\n}\n","import { GlobalState } from '../../global/types';\nimport { selectCurrentMessageList } from './messages';\nimport { buildChatThreadKey } from '../helpers';\n\nexport function selectCurrentTextSearch(global: GlobalState) {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n const chatThreadKey = buildChatThreadKey(chatId, threadId);\n const currentSearch = global.localTextSearch.byChatThreadKey[chatThreadKey];\n if (!currentSearch || !currentSearch.isActive) {\n return undefined;\n }\n\n return currentSearch;\n}\n\nexport function selectCurrentMediaSearchPeerId(global: GlobalState) {\n const { byChatId } = global.localMediaSearch;\n const { chatId } = selectCurrentMessageList(global) || {};\n const currentProfileUserId = global.users.selectedId;\n\n return currentProfileUserId && byChatId[currentProfileUserId] ? currentProfileUserId : chatId;\n}\n\nexport function selectCurrentMediaSearch(global: GlobalState) {\n const peerId = selectCurrentMediaSearchPeerId(global);\n if (!peerId) {\n return undefined;\n }\n\n return global.localMediaSearch.byChatId[peerId];\n}\n","import { GlobalState } from '../../global/types';\n\nimport { selectCurrentMessageList } from './messages';\nimport { selectChat } from './chats';\nimport { isChatGroup, isUserId } from '../helpers';\n\nexport function selectManagement(global: GlobalState, chatId: string) {\n return global.management.byChatId[chatId];\n}\n\nexport function selectCurrentManagement(global: GlobalState) {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n const currentManagement = global.management.byChatId[chatId];\n if (!currentManagement || !currentManagement.isActive) {\n return undefined;\n }\n\n return currentManagement;\n}\n\nexport function selectCurrentManagementType(global: GlobalState) {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n if (isUserId(chatId)) {\n return 'user';\n }\n\n const chat = selectChat(global, chatId);\n if (!chat) {\n return undefined;\n }\n\n if (isChatGroup(chat)) {\n return 'group';\n }\n\n return 'channel';\n}\n","import { GlobalState } from '../../global/types';\nimport { NewChatMembersProgress, RightColumnContent } from '../../types';\n\nimport { getSystemTheme, IS_SINGLE_COLUMN_LAYOUT } from '../../util/environment';\nimport { selectCurrentMessageList, selectIsPollResultsOpen } from './messages';\nimport { selectCurrentTextSearch } from './localSearch';\nimport { selectCurrentStickerSearch, selectCurrentGifSearch } from './symbols';\nimport { selectAreActiveChatsLoaded } from './chats';\nimport { selectCurrentManagement } from './management';\n\nexport function selectIsMediaViewerOpen(global: GlobalState) {\n const { mediaViewer } = global;\n return Boolean(mediaViewer.messageId || mediaViewer.avatarOwnerId);\n}\n\nexport function selectRightColumnContentKey(global: GlobalState) {\n const {\n users,\n isChatInfoShown,\n newChatMembersProgress,\n } = global;\n\n const isAddingChatMembersShown = newChatMembersProgress !== NewChatMembersProgress.Closed;\n const isPollResults = selectIsPollResultsOpen(global);\n const isSearch = Boolean(!IS_SINGLE_COLUMN_LAYOUT && selectCurrentTextSearch(global));\n const isManagement = selectCurrentManagement(global);\n const stickerSearch = selectCurrentStickerSearch(global);\n const isStickerSearch = stickerSearch.query !== undefined;\n const gifSearch = selectCurrentGifSearch(global);\n const isGifSearch = gifSearch.query !== undefined;\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n const currentProfileUserId = users.selectedId;\n const areActiveChatsLoaded = selectAreActiveChatsLoaded(global);\n const isUserInfo = Boolean(currentProfileUserId && areActiveChatsLoaded);\n const isChatShown = Boolean(currentChatId && areActiveChatsLoaded);\n const isChatInfo = isChatShown && isChatInfoShown;\n\n return isPollResults ? (\n RightColumnContent.PollResults\n ) : isSearch ? (\n RightColumnContent.Search\n ) : isManagement ? (\n RightColumnContent.Management\n ) : isStickerSearch ? (\n RightColumnContent.StickerSearch\n ) : isGifSearch ? (\n RightColumnContent.GifSearch\n ) : isAddingChatMembersShown ? (\n RightColumnContent.AddingMembers\n ) : isUserInfo ? (\n RightColumnContent.UserInfo\n ) : isChatInfo ? (\n RightColumnContent.ChatInfo\n ) : undefined;\n}\n\nexport function selectIsRightColumnShown(global: GlobalState) {\n return selectRightColumnContentKey(global) !== undefined;\n}\n\nexport function selectTheme(global: GlobalState) {\n const { theme, shouldUseSystemTheme } = global.settings.byKey;\n\n return shouldUseSystemTheme ? getSystemTheme() : theme;\n}\n","import { GlobalState } from '../../global/types';\n\nexport function selectCurrentGlobalSearchQuery(global: GlobalState) {\n return global.globalSearch.query;\n}\n","import { GlobalState } from '../../global/types';\n\nexport function selectPaymentChatId(global: GlobalState) {\n return global.payment.chatId;\n}\n\nexport function selectPaymentMessageId(global: GlobalState) {\n return global.payment.messageId;\n}\n\nexport function selectPaymentFormId(global: GlobalState) {\n return global.payment.formId;\n}\n\nexport function selectPaymentRequestId(global: GlobalState) {\n return global.payment.requestId;\n}\n\nexport function selectProviderPublishableKey(global: GlobalState) {\n return global.payment.nativeParams ? global.payment.nativeParams.publishableKey : undefined;\n}\n\nexport function selectStripeCredentials(global: GlobalState) {\n return global.payment.stripeCredentials;\n}\n","import {\n ApiBotInlineMediaResult, ApiBotInlineResult, ApiBotInlineSwitchPm,\n ApiLanguage, ApiMessage, ApiShippingAddress, ApiStickerSet,\n} from '../api/types';\n\nexport enum LoadMoreDirection {\n Backwards,\n Forwards,\n Around,\n}\n\nexport enum FocusDirection {\n Up,\n Down,\n Static,\n}\n\nexport interface IAlbum {\n albumId: string;\n messages: ApiMessage[];\n mainMessage: ApiMessage;\n}\n\nexport type ThemeKey = 'light' | 'dark';\n\nexport interface IThemeSettings {\n background?: string;\n backgroundColor?: string;\n patternColor?: string;\n isBlurred?: boolean;\n}\n\nexport type NotifySettings = {\n hasPrivateChatsNotifications?: boolean;\n hasPrivateChatsMessagePreview?: boolean;\n hasGroupNotifications?: boolean;\n hasGroupMessagePreview?: boolean;\n hasBroadcastNotifications?: boolean;\n hasBroadcastMessagePreview?: boolean;\n hasContactJoinedNotifications?: boolean;\n hasWebNotifications: boolean;\n hasPushNotifications: boolean;\n notificationSoundVolume: number;\n};\n\nexport type LangCode = (\n 'en' | 'ar' | 'be' | 'ca' | 'nl' | 'fr' | 'de' | 'id' | 'it' | 'ko' | 'ms' | 'fa' | 'pl' | 'pt-br' | 'ru' | 'es'\n | 'tr' | 'uk' | 'uz'\n);\n\nexport type TimeFormat = '24h' | '12h';\n\nexport interface ISettings extends NotifySettings, Record {\n theme: ThemeKey;\n shouldUseSystemTheme: boolean;\n messageTextSize: number;\n animationLevel: 0 | 1 | 2;\n messageSendKeyCombo: 'enter' | 'ctrl-enter';\n canAutoLoadPhotoFromContacts: boolean;\n canAutoLoadPhotoInPrivateChats: boolean;\n canAutoLoadPhotoInGroups: boolean;\n canAutoLoadPhotoInChannels: boolean;\n canAutoLoadVideoFromContacts: boolean;\n canAutoLoadVideoInPrivateChats: boolean;\n canAutoLoadVideoInGroups: boolean;\n canAutoLoadVideoInChannels: boolean;\n canAutoLoadFileFromContacts: boolean;\n canAutoLoadFileInPrivateChats: boolean;\n canAutoLoadFileInGroups: boolean;\n canAutoLoadFileInChannels: boolean;\n autoLoadFileMaxSizeMb: number;\n canAutoPlayGifs: boolean;\n canAutoPlayVideos: boolean;\n shouldSuggestStickers: boolean;\n shouldLoopStickers: boolean;\n hasPassword?: boolean;\n languages?: ApiLanguage[];\n language: LangCode;\n isSensitiveEnabled?: boolean;\n canChangeSensitive?: boolean;\n timeFormat: TimeFormat;\n wasTimeFormatSetManually: boolean;\n}\n\nexport interface ApiPrivacySettings {\n visibility: PrivacyVisibility;\n allowUserIds: string[];\n allowChatIds: string[];\n blockUserIds: string[];\n blockChatIds: string[];\n}\n\nexport interface InputPrivacyContact {\n id: string;\n accessHash?: string;\n}\n\nexport interface InputPrivacyRules {\n visibility: PrivacyVisibility;\n allowedUsers?: InputPrivacyContact[];\n allowedChats?: InputPrivacyContact[];\n blockedUsers?: InputPrivacyContact[];\n blockedChats?: InputPrivacyContact[];\n}\n\nexport type IAnchorPosition = {\n x: number;\n y: number;\n};\n\nexport interface ShippingOption {\n id: string;\n title: string;\n amount: number;\n prices: Price[];\n}\n\nexport interface Price {\n label: string;\n amount: number;\n}\n\nexport interface Invoice {\n currency?: string;\n emailRequested?: boolean;\n emailToProvider?: boolean;\n flexible?: boolean;\n nameRequested?: boolean;\n phoneRequested?: boolean;\n phoneToProvider?: boolean;\n prices?: Price[];\n shippingAddressRequested?: boolean;\n test?: boolean;\n}\n\nexport interface Receipt {\n currency: string;\n prices: Price[];\n info?: {\n shippingAddress?: ApiShippingAddress;\n phone?: string;\n name?: string;\n };\n totalAmount: number;\n credentialsTitle: string;\n shippingPrices?: Price[];\n shippingMethod?: string;\n photoUrl?: string;\n text?: string;\n title?: string;\n}\n\nexport enum SettingsScreens {\n Main,\n EditProfile,\n Notifications,\n DataStorage,\n Language,\n General,\n GeneralChatBackground,\n GeneralChatBackgroundColor,\n Privacy,\n PrivacyPhoneNumber,\n PrivacyLastSeen,\n PrivacyProfilePhoto,\n PrivacyForwarding,\n PrivacyGroupChats,\n PrivacyPhoneNumberAllowedContacts,\n PrivacyPhoneNumberDeniedContacts,\n PrivacyLastSeenAllowedContacts,\n PrivacyLastSeenDeniedContacts,\n PrivacyProfilePhotoAllowedContacts,\n PrivacyProfilePhotoDeniedContacts,\n PrivacyForwardingAllowedContacts,\n PrivacyForwardingDeniedContacts,\n PrivacyGroupChatsAllowedContacts,\n PrivacyGroupChatsDeniedContacts,\n PrivacyActiveSessions,\n PrivacyBlockedUsers,\n Folders,\n FoldersCreateFolder,\n FoldersEditFolder,\n FoldersEditFolderFromChatList,\n FoldersIncludedChats,\n FoldersIncludedChatsFromChatList,\n FoldersExcludedChats,\n FoldersExcludedChatsFromChatList,\n TwoFaDisabled,\n TwoFaNewPassword,\n TwoFaNewPasswordConfirm,\n TwoFaNewPasswordHint,\n TwoFaNewPasswordEmail,\n TwoFaNewPasswordEmailCode,\n TwoFaEnabled,\n TwoFaChangePasswordCurrent,\n TwoFaChangePasswordNew,\n TwoFaChangePasswordConfirm,\n TwoFaChangePasswordHint,\n TwoFaTurnOff,\n TwoFaRecoveryEmailCurrentPassword,\n TwoFaRecoveryEmail,\n TwoFaRecoveryEmailCode,\n TwoFaCongratulations,\n}\n\nexport type StickerSetOrRecent = Pick;\n\nexport enum LeftColumnContent {\n ChatList,\n GlobalSearch,\n Settings,\n Contacts,\n Archived,\n NewChannelStep1,\n NewChannelStep2,\n NewGroupStep1,\n NewGroupStep2,\n}\n\nexport enum GlobalSearchContent {\n ChatList,\n Media,\n Links,\n Files,\n Music,\n Voice,\n}\n\nexport enum RightColumnContent {\n ChatInfo,\n UserInfo,\n Search,\n Management,\n StickerSearch,\n GifSearch,\n PollResults,\n AddingMembers,\n}\n\nexport enum MediaViewerOrigin {\n Inline,\n ScheduledInline,\n SharedMedia,\n ProfileAvatar,\n SettingsAvatar,\n MiddleHeaderAvatar,\n Album,\n ScheduledAlbum,\n SearchResult,\n}\n\nexport enum AudioOrigin {\n Inline,\n SharedMedia,\n Search,\n}\n\nexport enum ChatCreationProgress {\n Idle,\n InProgress,\n Complete,\n Error,\n}\n\nexport enum ProfileEditProgress {\n Idle,\n InProgress,\n Complete,\n Error,\n}\n\nexport enum ManagementProgress {\n Idle,\n InProgress,\n Complete,\n Error,\n}\n\nexport enum NewChatMembersProgress {\n Closed,\n InProgress,\n Loading,\n}\n\nexport type ProfileTabType = 'members' | 'commonChats' | 'media' | 'documents' | 'links' | 'audio' | 'voice';\nexport type SharedMediaType = 'media' | 'documents' | 'links' | 'audio' | 'voice';\nexport type ApiPrivacyKey = 'phoneNumber' | 'lastSeen' | 'profilePhoto' | 'forwards' | 'chatInvite';\nexport type PrivacyVisibility = 'everybody' | 'contacts' | 'nonContacts' | 'nobody';\n\nexport enum ProfileState {\n Profile,\n SharedMedia,\n MemberList,\n}\n\nexport enum PaymentStep {\n ShippingInfo,\n Shipping,\n PaymentInfo,\n Checkout,\n}\n\nexport const UPLOADING_WALLPAPER_SLUG = 'UPLOADING_WALLPAPER_SLUG';\n\nexport enum ManagementScreens {\n Initial,\n ChatPrivacyType,\n Discussion,\n ChannelSubscribers,\n GroupType,\n GroupPermissions,\n GroupRemovedUsers,\n GroupUserPermissionsCreate,\n GroupUserPermissions,\n ChatAdministrators,\n GroupRecentActions,\n ChatAdminRights,\n GroupMembers,\n}\n\nexport type ManagementType = 'user' | 'group' | 'channel';\n\nexport type NotifyException = {\n isMuted: boolean;\n isSilent?: boolean;\n shouldShowPreviews?: boolean;\n};\n\nexport type EmojiKeywords = {\n isLoading?: boolean;\n version: number;\n keywords: Record;\n};\n\nexport type InlineBotSettings = {\n id: string;\n help?: string;\n query?: string;\n offset?: string;\n canLoadMore?: boolean;\n results?: (ApiBotInlineResult | ApiBotInlineMediaResult)[];\n isGallery?: boolean;\n switchPm?: ApiBotInlineSwitchPm;\n};\n","import { fastRaf } from './schedulers';\n\ninterface AnimationInstance {\n isCancelled: boolean;\n}\n\nlet currentInstance: AnimationInstance | undefined;\n\nexport function animateSingle(tick: Function, instance?: AnimationInstance) {\n if (!instance) {\n if (currentInstance && !currentInstance.isCancelled) {\n currentInstance.isCancelled = true;\n }\n\n instance = { isCancelled: false };\n currentInstance = instance;\n }\n\n fastRaf(() => {\n if (!instance!.isCancelled && tick()) {\n animateSingle(tick, instance);\n }\n });\n}\n\nexport function animate(tick: Function) {\n fastRaf(() => {\n if (tick()) {\n animate(tick);\n }\n });\n}\n","import { DEBUG } from '../config';\n\nexport function updateAppBadge(unreadCount: number) {\n if (typeof window.navigator.setAppBadge !== 'function') {\n return;\n }\n\n window.navigator.setAppBadge(unreadCount).catch((err) => {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n });\n}\n","export default function arePropsShallowEqual(currentProps: AnyLiteral, newProps: AnyLiteral) {\n if (currentProps === newProps) {\n return true;\n }\n\n const currentKeys = Object.keys(currentProps);\n const currentKeysLength = currentKeys.length;\n const newKeysLength = Object.keys(newProps).length;\n\n if (currentKeysLength !== newKeysLength) {\n return false;\n }\n\n if (currentKeysLength === 0) {\n return true;\n }\n\n for (let i = 0; i < currentKeysLength; i++) {\n const prop = currentKeys[i];\n if (currentProps[prop] !== newProps[prop]) {\n return false;\n }\n }\n\n return true;\n}\n\nexport function getUnequalProps(currentProps: AnyLiteral, newProps: AnyLiteral) {\n const currentKeys = Object.keys(currentProps);\n const currentKeysLength = currentKeys.length;\n const newKeysLength = Object.keys(newProps).length;\n\n if (currentKeysLength !== newKeysLength) {\n return ['%LENGTH%'];\n }\n\n return currentKeys.reduce((res, prop) => {\n if (currentProps[prop] !== newProps[prop]) {\n res.push(`${prop}: ${currentProps[prop]} => ${newProps[prop]}`);\n }\n\n return res;\n }, [] as string[]);\n}\n","type Parts = (string | false | undefined)[];\n\nexport default (...parts: Parts) => {\n return parts.filter(Boolean).join(' ');\n};\n","// eslint-disable-next-line no-restricted-globals\nconst cacheApi = self.caches;\n\nexport enum Type {\n Text,\n Blob,\n Json,\n}\n\nexport async function fetch(\n cacheName: string, key: string, type: Type, isHtmlAllowed = false,\n) {\n if (!cacheApi) {\n return undefined;\n }\n\n try {\n // To avoid the error \"Request scheme 'webdocument' is unsupported\"\n const request = new Request(key.replace(/:/g, '_'));\n const cache = await cacheApi.open(cacheName);\n const response = await cache.match(request);\n if (!response) {\n return undefined;\n }\n\n const contentType = response.headers.get('Content-Type');\n\n switch (type) {\n case Type.Text:\n return await response.text();\n case Type.Blob: {\n // Ignore deprecated data-uri avatars\n if (key.startsWith('avatar') && contentType && contentType.startsWith('text')) {\n return undefined;\n }\n\n const blob = await response.blob();\n\n // Safari does not return correct Content-Type header for webp images.\n if (key.startsWith('sticker')) {\n return new Blob([blob], { type: 'image/webp' });\n }\n\n const shouldRecreate = !blob.type || (!isHtmlAllowed && blob.type.includes('html'));\n // iOS Safari fails to preserve `type` in cache\n let resolvedType = blob.type || contentType;\n\n if (!(shouldRecreate && resolvedType)) {\n return blob;\n }\n\n // Prevent HTML-in-video attacks (for files that were cached before fix)\n if (!isHtmlAllowed) {\n resolvedType = resolvedType.replace(/html/gi, '');\n }\n\n return new Blob([blob], { type: resolvedType });\n }\n case Type.Json:\n return await response.json();\n default:\n return undefined;\n }\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n\nexport async function save(cacheName: string, key: string, data: AnyLiteral | Blob | string) {\n if (!cacheApi) {\n return undefined;\n }\n\n try {\n const cacheData = typeof data === 'string' || data instanceof Blob ? data : JSON.stringify(data);\n // To avoid the error \"Request scheme 'webdocument' is unsupported\"\n const request = new Request(key.replace(/:/g, '_'));\n const response = new Response(cacheData);\n const cache = await cacheApi.open(cacheName);\n return await cache.put(request, response);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n\nexport async function clear(cacheName: string) {\n try {\n if (!cacheApi) {\n return undefined;\n }\n\n return await cacheApi.delete(cacheName);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n","import captureKeyboardListener from './captureKeyboardListeners';\n\ntype IHandlerFunction = () => void;\n\nexport default function captureEscKeyListener(handler: IHandlerFunction) {\n return captureKeyboardListener({ onEsc: handler });\n}\n","type HandlerName = 'onEnter' | 'onBackspace' | 'onDelete' | 'onEsc' | 'onUp' | 'onDown' | 'onLeft' | 'onRight'\n| 'onTab';\ntype Handler = (e: KeyboardEvent) => void;\ntype CaptureOptions = Partial>;\n\nconst keyToHandlerName: Record = {\n Enter: 'onEnter',\n Backspace: 'onBackspace',\n Delete: 'onDelete',\n Esc: 'onEsc',\n Escape: 'onEsc',\n ArrowUp: 'onUp',\n ArrowDown: 'onDown',\n ArrowLeft: 'onLeft',\n ArrowRight: 'onRight',\n Tab: 'onTab',\n};\n\nconst handlers: Record = {\n onEnter: [],\n onDelete: [],\n onBackspace: [],\n onEsc: [],\n onUp: [],\n onDown: [],\n onLeft: [],\n onRight: [],\n onTab: [],\n};\n\nexport default function captureKeyboardListeners(options: CaptureOptions) {\n if (!hasActiveHandlers()) {\n document.addEventListener('keydown', handleKeyDown, true);\n }\n\n (Object.keys(options) as Array).forEach((handlerName) => {\n const handler = options[handlerName];\n if (!handler) {\n return;\n }\n\n const currentEventHandlers = handlers[handlerName];\n if (currentEventHandlers) {\n currentEventHandlers.push(handler);\n }\n });\n\n return () => {\n releaseKeyboardListener(options);\n };\n}\n\nfunction hasActiveHandlers() {\n return Object.values(handlers).some((keyHandlers) => Boolean(keyHandlers.length));\n}\n\nfunction handleKeyDown(e: KeyboardEvent) {\n const handlerName = keyToHandlerName[e.key];\n if (!handlerName) {\n return;\n }\n\n const { length } = handlers[handlerName];\n if (!length) {\n return;\n }\n e.stopPropagation();\n\n const handler = handlers[handlerName][length - 1];\n handler!(e);\n}\n\nfunction releaseKeyboardListener(options: CaptureOptions) {\n (Object.keys(options) as Array).forEach((handlerName) => {\n const handler = options[handlerName];\n const currentEventHandlers = handlers[handlerName];\n if (currentEventHandlers) {\n const index = currentEventHandlers.findIndex((cb) => cb === handler);\n if (index !== -1) {\n currentEventHandlers.splice(index, 1);\n }\n }\n });\n\n if (!hasActiveHandlers()) {\n document.removeEventListener('keydown', handleKeyDown, false);\n }\n}\n","import { LangFn } from '../hooks/useLang';\n\nconst WEEKDAYS_FULL = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];\nconst MONTHS_FULL = [\n 'January', 'February', 'March', 'April', 'May', 'June',\n 'July', 'August', 'September', 'October', 'November', 'December',\n];\n\nconst MONTHS_FULL_LOWERCASE = MONTHS_FULL.map((month) => month.toLowerCase());\nconst MIN_SEARCH_YEAR = 2015;\nconst MAX_DAY_IN_MONTH = 31;\nconst MAX_MONTH_IN_YEAR = 12;\nexport const MILLISECONDS_IN_DAY = 24 * 60 * 60 * 1000;\n\nexport function getDayStart(datetime: number | Date) {\n const date = new Date(datetime);\n date.setHours(0, 0, 0, 0);\n return date;\n}\n\nexport function getDayStartAt(datetime: number | Date) {\n return getDayStart(datetime).getTime();\n}\n\nexport function toYearMonth(timestamp: number) {\n const date = new Date(timestamp * 1000);\n return `${date.getFullYear()}-${date.getMonth()}`;\n}\n\nfunction toIsoString(date: Date) {\n return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;\n}\n\n// @optimization `toLocaleTimeString` is avoided because of bad performance\nexport function formatTime(datetime: number | Date, lang: LangFn) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n const timeFormat = lang.timeFormat || '24h';\n\n let hours = date.getHours();\n let marker = '';\n if (timeFormat === '12h') {\n marker = hours >= 12 ? ' PM' : ' AM';\n hours = hours > 12 ? hours % 12 : hours;\n }\n\n return `${String(hours).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}${marker}`;\n}\n\nexport function formatPastTimeShort(lang: LangFn, datetime: number | Date) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n\n const today = getDayStart(new Date());\n if (date >= today) {\n return formatTime(date, lang);\n }\n\n const weekAgo = new Date(today);\n weekAgo.setDate(today.getDate() - 7);\n if (date >= weekAgo) {\n return lang(`Weekday.Short${WEEKDAYS_FULL[date.getDay()]}`);\n }\n\n const withYear = date.getFullYear() !== today.getFullYear();\n const format = (\n lang(withYear ? 'formatDateScheduleYear' : 'formatDateSchedule')\n || (withYear ? 'd MMM yyyy' : 'd MMM')\n );\n\n return formatDate(lang, date, format);\n}\n\nexport function formatFullDate(lang: LangFn, datetime: number | Date) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n const format = lang('formatterYearMax') || 'dd.MM.yyyy';\n\n return formatDate(lang, date, format);\n}\n\nexport function formatMonthAndYear(lang: LangFn, date: Date, isShort = false) {\n const format = lang(isShort ? 'formatterMonthYear2' : 'formatterMonthYear') || 'MMM yyyy';\n\n return formatDate(lang, date, format);\n}\n\nexport function formatHumanDate(\n lang: LangFn,\n datetime: number | Date,\n isShort = false,\n noWeekdays = false,\n isUpperFirst?: boolean,\n) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n\n const today = getDayStart(new Date());\n\n if (!noWeekdays) {\n if (toIsoString(date) === toIsoString(today)) {\n return (isUpperFirst || !isShort ? upperFirst : lowerFirst)(lang('Weekday.Today'));\n }\n\n const yesterday = new Date(today);\n yesterday.setDate(today.getDate() - 1);\n if (toIsoString(date) === toIsoString(yesterday)) {\n return (isUpperFirst || !isShort ? upperFirst : lowerFirst)(lang('Weekday.Yesterday'));\n }\n\n const weekAgo = new Date(today);\n const weekAhead = new Date(today);\n weekAgo.setDate(today.getDate() - 7);\n weekAhead.setDate(today.getDate() + 7);\n if (date >= weekAgo && date <= weekAhead) {\n const weekDay = WEEKDAYS_FULL[date.getDay()];\n const weekDayString = isShort ? lang(`Weekday.Short${weekDay}`) : lang(`Weekday.${weekDay}`);\n\n return (isUpperFirst || !isShort ? upperFirst : lowerFirst)(weekDayString);\n }\n }\n\n const withYear = date.getFullYear() !== today.getFullYear();\n const formatKey = isShort\n ? (withYear ? 'formatDateScheduleYear' : 'formatDateSchedule')\n : (withYear ? 'chatFullDate' : 'chatDate');\n const format = lang(formatKey) || 'd MMMM yyyy';\n\n return (isUpperFirst || !isShort ? upperFirst : lowerFirst)(formatDate(lang, date, format));\n}\n\nfunction formatDate(lang: LangFn, date: Date, format: string) {\n const day = date.getDate();\n const monthIndex = date.getMonth();\n\n return format\n .replace('LLLL', lang(MONTHS_FULL[monthIndex]))\n .replace('MMMM', lang(`Month.Gen${MONTHS_FULL[monthIndex]}`))\n .replace('MMM', lang(`Month.Short${MONTHS_FULL[monthIndex]}`))\n .replace('MM', String(monthIndex + 1).padStart(2, '0'))\n .replace('dd', String(day).padStart(2, '0'))\n .replace('d', String(day))\n .replace('yyyy', String(date.getFullYear()));\n}\n\nexport function formatMediaDateTime(\n lang: LangFn,\n datetime: number | Date,\n isUpperFirst?: boolean,\n) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n\n return `${formatHumanDate(lang, date, true, undefined, isUpperFirst)}, ${formatTime(date, lang)}`;\n}\n\nexport function formatMediaDuration(duration: number, maxValue?: number) {\n const hours = Math.floor(duration / 3600);\n const minutes = Math.floor((duration % 3600) / 60);\n const seconds = Math.floor(duration % 3600 % 60);\n\n const maxHours = maxValue ? Math.floor(maxValue / 3600) : 0;\n const maxMinutes = maxValue ? Math.floor((maxValue % 3600) / 60) : 0;\n let string = '';\n if (hours > 0 || maxHours > 0) {\n string += `${String(hours).padStart(2, '0')}:`;\n string += `${String(minutes).padStart(2, '0')}:`;\n } else if (maxMinutes >= 10) {\n string += `${String(minutes).padStart(2, '0')}:`;\n } else {\n string += `${String(minutes)}:`;\n }\n string += String(seconds).padStart(2, '0');\n\n return string;\n}\n\nexport function formatVoiceRecordDuration(durationInMs: number) {\n const parts = [];\n\n let milliseconds = durationInMs % 1000;\n durationInMs -= milliseconds;\n milliseconds = Math.floor(milliseconds / 10);\n\n durationInMs = Math.floor(durationInMs / 1000);\n const seconds = durationInMs % 60;\n durationInMs -= seconds;\n\n durationInMs = Math.floor(durationInMs / 60);\n const minutes = durationInMs % 60;\n durationInMs -= minutes;\n\n durationInMs = Math.floor(durationInMs / 60);\n const hours = durationInMs % 60;\n\n if (hours > 0) {\n parts.push(String(hours).padStart(2, '0'));\n }\n parts.push(String(minutes).padStart(hours > 0 ? 2 : 1, '0'));\n parts.push(String(seconds).padStart(2, '0'));\n\n return `${parts.join(':')},${String(milliseconds).padStart(2, '0')}`;\n}\n\nexport function formatDateToString(date: Date, locale = 'en-US') {\n return date.toLocaleString(\n locale,\n {\n year: 'numeric',\n month: 'short',\n day: 'numeric',\n },\n );\n}\n\nfunction isValidDate(day: number, month: number, year = 2021): boolean {\n if (month > (MAX_MONTH_IN_YEAR - 1) || day > MAX_DAY_IN_MONTH) {\n return false;\n }\n const date = new Date(year, month, day);\n return !Number.isNaN(date.getTime()) && date.getDate() === day;\n}\n\nexport function parseDateString(query = ''): string | undefined {\n const matchStringDate = query.match(/\\d{1,2}\\s[a-zA-Z]{3,}/);\n const matchEuropeStringDate = query.match(/[a-zA-Z]{3,}\\s\\d{1,2}/);\n const matchNumberDate = query.match(/\\d{1,2}[./-]\\d{1,2}([./-]\\d{2,4})?/);\n if (!matchStringDate && !matchNumberDate && !matchEuropeStringDate) {\n return undefined;\n }\n\n if (matchNumberDate) {\n const [date, month, year] = query.split(/[./-]/).map(Number);\n return !(year && year < MIN_SEARCH_YEAR) && isValidDate(date, month - 1, year || undefined)\n ? `${year ? `${year}-` : ''}${String(month).padStart(2, '0')}-${String(date).padStart(2, '0')}`\n : undefined;\n }\n\n const dateParts = query.split(' ');\n const date = matchStringDate ? dateParts[0] : dateParts[1];\n const month = (matchStringDate ? dateParts[1] : dateParts[0]).toLowerCase();\n const monthIndex = MONTHS_FULL_LOWERCASE.findIndex((item) => item.startsWith(month));\n\n return monthIndex !== -1 && isValidDate(Number(date), monthIndex)\n ? `${String(monthIndex + 1).padStart(2, '0')}-${String(date).padStart(2, '0')}`\n : undefined;\n}\n\nexport function timestampPlusDay(timestamp: number) {\n return timestamp + MILLISECONDS_IN_DAY / 1000;\n}\n\nfunction lowerFirst(str: string) {\n return `${str[0].toLowerCase()}${str.slice(1)}`;\n}\n\nfunction upperFirst(str: string) {\n return `${str[0].toUpperCase()}${str.slice(1)}`;\n}\n","import EMOJI_REGEX from '../lib/twemojiRegex';\n\n// Due to the fact that emoji from Apple do not contain some characters, it is necessary to remove them from emoji-data\n// https://github.com/iamcal/emoji-data/issues/136\nconst EXCLUDE_EMOJIS = ['female_sign', 'male_sign', 'medical_symbol'];\n\nconst ISO_FLAGS_OFFSET = 127397;\n\nexport type EmojiRawData = typeof import('emoji-data-ios/emoji-data.json');\nexport type EmojiModule = { default: EmojiRawData };\n\nexport type EmojiData = {\n categories: Array;\n emojis: Record;\n};\n\n// Non-standard variations of emojis, used on some devices\nconst EMOJI_EXCEPTIONS: [string | RegExp, string][] = [\n [/\\u{1f3f3}\\u200d\\u{1f308}/gu, '\\u{1f3f3}\\ufe0f\\u200d\\u{1f308}'], // 🏳‍🌈\n [/\\u{1f3f3}\\u200d\\u26a7\\ufe0f/gu, '\\u{1f3f3}\\ufe0f\\u200d\\u26a7\\ufe0f'], // 🏳️‍⚧️\n [/\\u{1f937}\\u200d\\u2642/gu, '\\u{1f937}\\u200d\\u2642\\ufe0f'], // 🤷‍♂️\n];\n\nfunction unifiedToNative(unified: string) {\n const unicodes = unified.split('-');\n const codePoints = unicodes.map((i) => parseInt(i, 16));\n\n return String.fromCodePoint(...codePoints);\n}\n\nexport function fixNonStandardEmoji(text: string) {\n // Non-standard sequences typically parsed as separate emojis, so no need to fix text without any\n if (!text.match(EMOJI_REGEX)) return text;\n // eslint-disable-next-line no-restricted-syntax\n for (const [regex, replacement] of EMOJI_EXCEPTIONS) {\n text = text.replace(regex, replacement);\n }\n\n return text;\n}\n\nexport function nativeToUnified(emoji: string) {\n let code;\n\n if (emoji.length === 1) {\n code = emoji.charCodeAt(0).toString(16).padStart(4, '0');\n } else {\n const pairs = [];\n for (let i = 0; i < emoji.length; i++) {\n if (emoji.charCodeAt(i) >= 0xd800 && emoji.charCodeAt(i) <= 0xdbff) {\n if (emoji.charCodeAt(i + 1) >= 0xdc00 && emoji.charCodeAt(i + 1) <= 0xdfff) {\n pairs.push(\n (emoji.charCodeAt(i) - 0xd800) * 0x400\n + (emoji.charCodeAt(i + 1) - 0xdc00) + 0x10000,\n );\n }\n } else if (emoji.charCodeAt(i) < 0xd800 || emoji.charCodeAt(i) > 0xdfff) {\n pairs.push(emoji.charCodeAt(i));\n }\n }\n\n code = pairs.map((x) => x.toString(16).padStart(4, '0')).join('-');\n }\n\n return code;\n}\n\nexport function uncompressEmoji(data: EmojiRawData): EmojiData {\n const emojiData: EmojiData = { categories: [], emojis: {} };\n\n for (let i = 0; i < data.length; i += 2) {\n const category = {\n id: data[i][0],\n name: data[i][1],\n emojis: [],\n } as EmojiCategory;\n\n for (let j = 0; j < data[i + 1].length; j++) {\n const emojiRaw = data[i + 1][j];\n if (!EXCLUDE_EMOJIS.includes(emojiRaw[1][0])) {\n category.emojis.push(emojiRaw[1][0]);\n emojiData.emojis[emojiRaw[1][0]] = {\n id: emojiRaw[1][0],\n names: emojiRaw[1] as string[],\n native: unifiedToNative(emojiRaw[0] as string),\n image: (emojiRaw[0] as string).toLowerCase(),\n };\n }\n }\n\n emojiData.categories.push(category);\n }\n\n return emojiData;\n}\n\nexport function isoToEmoji(iso: string) {\n const code = iso.toUpperCase();\n\n if (!/^[A-Z]{2}$/.test(code)) return iso;\n const codePoints = [...code].map((c) => c.codePointAt(0)! + ISO_FLAGS_OFFSET);\n return String.fromCodePoint(...codePoints);\n}\n","let isWebpSupportedCache: boolean | undefined;\n\nexport function isWebpSupported() {\n return Boolean(isWebpSupportedCache);\n}\n\nfunction testWebp(): Promise {\n return new Promise((resolve) => {\n const webp = new Image();\n // eslint-disable-next-line max-len\n webp.src = 'data:image/webp;base64,UklGRjoAAABXRUJQVlA4IC4AAACyAgCdASoCAAIALmk0mk0iIiIiIgBoSygABc6WWgAA/veff/0PP8bA//LwYAAA';\n const handleLoadOrError = () => {\n resolve(webp.height === 2);\n };\n webp.onload = handleLoadOrError;\n webp.onerror = handleLoadOrError;\n });\n}\n\ntestWebp().then((hasWebp) => {\n isWebpSupportedCache = hasWebp;\n});\n","import { ThemeKey } from '../types';\n\nlet systemThemeCache: ThemeKey = (\n window.matchMedia?.('(prefers-color-scheme: dark)').matches\n) ? 'dark' : 'light';\n\nexport function getSystemTheme() {\n return systemThemeCache;\n}\n\nfunction handleSystemThemeChange(e: MediaQueryListEventMap['change']) {\n systemThemeCache = e.matches ? 'dark' : 'light';\n}\n\nconst mql = window.matchMedia('(prefers-color-scheme: dark)');\nif (typeof mql.addEventListener === 'function') {\n mql.addEventListener('change', handleSystemThemeChange);\n} else if (typeof mql.addListener === 'function') {\n mql.addListener(handleSystemThemeChange);\n}\n","import {\n MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN,\n MOBILE_SCREEN_MAX_WIDTH,\n MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT,\n MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH,\n IS_TEST,\n SUPPORTED_VIDEO_CONTENT_TYPES,\n VIDEO_MOV_TYPE,\n} from '../config';\n\nexport * from './environmentWebp';\n\nexport * from './environmentSystemTheme';\n\nexport function getPlatform() {\n const { userAgent, platform } = window.navigator;\n const macosPlatforms = ['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'];\n const windowsPlatforms = ['Win32', 'Win64', 'Windows', 'WinCE'];\n const iosPlatforms = ['iPhone', 'iPad', 'iPod'];\n let os: 'macOS' | 'iOS' | 'Windows' | 'Android' | 'Linux' | undefined;\n\n if (macosPlatforms.indexOf(platform) !== -1) {\n os = 'macOS';\n } else if (iosPlatforms.indexOf(platform) !== -1) {\n os = 'iOS';\n } else if (windowsPlatforms.indexOf(platform) !== -1) {\n os = 'Windows';\n } else if (/Android/.test(userAgent)) {\n os = 'Android';\n } else if (/Linux/.test(platform)) {\n os = 'Linux';\n }\n\n return os;\n}\n\nexport const PLATFORM_ENV = getPlatform();\nexport const IS_MAC_OS = PLATFORM_ENV === 'macOS';\nexport const IS_IOS = PLATFORM_ENV === 'iOS';\nexport const IS_ANDROID = PLATFORM_ENV === 'Android';\nexport const IS_SAFARI = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);\nexport const IS_PWA = window.matchMedia('(display-mode: standalone)').matches\n|| (window.navigator as any).standalone\n|| document.referrer.includes('android-app://');\n\nexport const IS_TOUCH_ENV = window.matchMedia('(pointer: coarse)').matches;\n// Keep in mind the landscape orientation\nexport const IS_SINGLE_COLUMN_LAYOUT = window.innerWidth <= MOBILE_SCREEN_MAX_WIDTH || (\n window.innerWidth <= MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH && window.innerHeight <= MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT\n);\n// Special layout, 1 column while chat opened, 2 columns while collapsed\nexport const IS_TABLET_COLUMN_LAYOUT = !IS_SINGLE_COLUMN_LAYOUT && (\n window.innerWidth <= MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN\n);\nexport const IS_VOICE_RECORDING_SUPPORTED = Boolean(\n navigator.mediaDevices && 'getUserMedia' in navigator.mediaDevices && (\n window.AudioContext || (window as any).webkitAudioContext\n ),\n);\nexport const IS_SMOOTH_SCROLL_SUPPORTED = 'scrollBehavior' in document.documentElement.style;\nexport const IS_EMOJI_SUPPORTED = PLATFORM_ENV && (IS_MAC_OS || IS_IOS);\nexport const IS_SERVICE_WORKER_SUPPORTED = 'serviceWorker' in navigator;\n// TODO Consider failed service worker\nexport const IS_PROGRESSIVE_SUPPORTED = IS_SERVICE_WORKER_SUPPORTED;\nexport const IS_STREAMING_SUPPORTED = 'MediaSource' in window;\nexport const IS_OPUS_SUPPORTED = Boolean((new Audio()).canPlayType('audio/ogg; codecs=opus'));\nexport const IS_CANVAS_FILTER_SUPPORTED = (\n !IS_TEST && 'filter' in (document.createElement('canvas').getContext('2d') || {})\n);\nexport const LAYERS_ANIMATION_NAME = IS_ANDROID ? 'slide-fade' : IS_IOS ? 'slide-layers' : 'push-slide';\n\nconst TEST_VIDEO = document.createElement('video');\nexport const IS_MOV_SUPPORTED = Boolean(\n TEST_VIDEO.canPlayType(VIDEO_MOV_TYPE).replace('no', '')\n || IS_IOS, // IOS reports '', but still plays .mov files\n);\n\nif (IS_MOV_SUPPORTED) SUPPORTED_VIDEO_CONTENT_TYPES.add(VIDEO_MOV_TYPE);\n\nexport const DPR = window.devicePixelRatio || 1;\n\nexport const MASK_IMAGE_DISABLED = true;\n","import { pause } from './schedulers';\n\n// Polyfill for Safari: `File` is not available in web worker\nif (typeof File === 'undefined') {\n // eslint-disable-next-line no-global-assign, no-restricted-globals, func-names\n self.File = class extends Blob {\n name: string;\n\n constructor(fileBits: BlobPart[], fileName: string, options?: FilePropertyBag) {\n if (options) {\n const { type, ...rest } = options;\n super(fileBits, { type });\n Object.assign(this, rest);\n } else {\n super(fileBits);\n }\n\n this.name = fileName;\n }\n } as typeof File;\n}\n\nexport function dataUriToBlob(dataUri: string) {\n const arr = dataUri.split(',');\n const mime = arr[0].match(/:(.*?);/)![1];\n const bstr = atob(arr[1]);\n let n = bstr.length;\n const u8arr = new Uint8Array(n);\n\n while (n--) {\n u8arr[n] = bstr.charCodeAt(n);\n }\n\n return new Blob([u8arr], { type: mime });\n}\n\nexport function blobToDataUri(blob: Blob): Promise {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n\n reader.onload = (e: ProgressEvent) => {\n const { result } = e.target || {};\n if (typeof result === 'string') {\n resolve(result);\n }\n\n reject(new Error('Failed to read blob'));\n };\n\n reader.onerror = reject;\n reader.readAsDataURL(blob);\n });\n}\n\nexport function blobToFile(blob: Blob, fileName: string) {\n return new File([blob], fileName, {\n lastModified: Date.now(),\n type: blob.type,\n });\n}\n\nexport function preloadImage(url: string): Promise {\n return new Promise((resolve, reject) => {\n const img = new Image();\n img.onload = () => resolve(img);\n img.onerror = reject;\n img.src = url;\n });\n}\n\nexport function preloadVideo(url: string): Promise {\n return new Promise((resolve, reject) => {\n const video = document.createElement('video');\n video.volume = 0;\n video.onloadedmetadata = () => resolve(video);\n video.onerror = reject;\n video.src = url;\n });\n}\n\nexport async function createPosterForVideo(url: string): Promise {\n const video = await preloadVideo(url);\n\n return Promise.race([\n pause(2000) as Promise,\n new Promise((resolve, reject) => {\n video.onseeked = () => {\n if (!video.videoWidth || !video.videoHeight) {\n resolve(undefined);\n }\n\n const canvas = document.createElement('canvas');\n canvas.width = video.videoWidth;\n canvas.height = video.videoHeight;\n const ctx = canvas.getContext('2d')!;\n ctx.drawImage(video, 0, 0);\n resolve(canvas.toDataURL('image/jpeg'));\n };\n video.onerror = reject;\n video.currentTime = Math.min(video.duration, 1);\n }),\n ]);\n}\n\nexport async function fetchBlob(blobUrl: string) {\n const response = await fetch(blobUrl);\n return response.blob();\n}\n\nexport async function fetchFile(blobUrl: string, fileName: string) {\n const blob = await fetchBlob(blobUrl);\n return blobToFile(blob, fileName);\n}\n\nexport function imgToCanvas(img: HTMLImageElement) {\n const canvas = document.createElement('canvas');\n canvas.width = img.width;\n canvas.height = img.height;\n\n const ctx = canvas.getContext('2d')!;\n ctx.drawImage(img, 0, 0);\n\n return canvas;\n}\n","import { LangCode } from '../types';\n\nexport function formatCurrency(totalPrice: number, currency?: string, locale: LangCode = 'en') {\n return new Intl.NumberFormat(locale, {\n style: 'currency',\n currency,\n }).format(currency === 'JPY' ? totalPrice : totalPrice / 100);\n}\n","export default (store: AnyLiteral) => {\n let id;\n\n do {\n id = String(Math.random()).replace('0.', 'id');\n } while (store.hasOwnProperty(id));\n\n return id;\n};\n","import { ApiError, ApiFieldError } from '../api/types';\n\nconst READABLE_ERROR_MESSAGES: Record = {\n CHAT_RESTRICTED: 'You can\\'t send messages in this chat, you were restricted',\n CHAT_WRITE_FORBIDDEN: 'You can\\'t write in this chat',\n CHAT_SEND_POLL_FORBIDDEN: 'You can\\'t create polls in this chat',\n CHAT_SEND_STICKERS_FORBIDDEN: 'You can\\'t send stickers in this chat',\n CHAT_SEND_GIFS_FORBIDDEN: 'You can\\'t send gifs in this chat',\n CHAT_SEND_MEDIA_FORBIDDEN: 'You can\\'t send media in this chat',\n CHAT_LINK_EXISTS: 'The chat is public, you can\\'t hide the history to new users',\n // eslint-disable-next-line max-len\n SLOWMODE_WAIT_X: 'Slowmode is enabled in this chat: you must wait for the specified number of seconds before sending another message to the chat.',\n USER_BANNED_IN_CHANNEL: 'You\\'re banned from sending messages in supergroups / channels',\n USER_IS_BLOCKED: 'You were blocked by this user',\n YOU_BLOCKED_USER: 'You blocked this user',\n IMAGE_PROCESS_FAILED: 'Failure while processing image',\n MEDIA_EMPTY: 'The provided media object is invalid',\n MEDIA_INVALID: 'Media invalid',\n PHOTO_EXT_INVALID: 'The extension of the photo is invalid',\n PHOTO_INVALID_DIMENSIONS: 'The photo dimensions are invalid',\n PHOTO_SAVE_FILE_INVALID: 'Internal issues, try again later',\n // eslint-disable-next-line max-len\n MESSAGE_DELETE_FORBIDDEN: 'You can\\'t delete one of the messages you tried to delete, most likely because it is a service message.',\n MESSAGE_POLL_CLOSED: 'Poll closed',\n MESSAGE_EDIT_TIME_EXPIRED: 'You can\\'t edit this message anymore.',\n CHAT_ADMIN_REQUIRED: 'You must be an admin in this chat to do this',\n PINNED_DIALOGS_TOO_MUCH: 'Sorry, you can only pin 5 chats to the top',\n DIALOG_FILTERS_TOO_MUCH: 'Sorry, you can\\'t have more than 10 folders',\n CHANNEL_PRIVATE: 'This channel is private',\n MEDIA_CAPTION_TOO_LONG: 'The provided caption is too long',\n ADDRESS_STREET_LINE1_INVALID: 'The address you provided is not valid',\n ADDRESS_STREET_LINE2_INVALID: 'The address you provided is not valid',\n ADDRESS_CITY_INVALID: 'The city you provided is not valid',\n ADDRESS_COUNTRY_INVALID: 'The country you provided is not valid',\n ADDRESS_POSTCODE_INVALID: 'The postcode you provided is not valid',\n ADDRESS_STATE_INVALID: 'The state you provided is not valid',\n REQ_INFO_NAME_INVALID: 'The name you provided is not valid',\n REQ_INFO_PHONE_INVALID: 'The phone you provided is not valid',\n REQ_INFO_EMAIL_INVALID: 'The email you provided is not valid',\n // TODO Bring back after fixing the weird bug\n // CHANNEL_INVALID: 'An error occurred. Please try again later',\n LINK_NOT_MODIFIED: 'This discussion is already linked to the channel',\n MESSAGE_TOO_LONG: 'Message is too long',\n\n // Non-API errors\n SERVICE_WORKER_DISABLED: 'Service Worker is disabled. Please reload the page without holding key.',\n // eslint-disable-next-line max-len\n MESSAGE_TOO_LONG_PLEASE_REMOVE_CHARACTERS: 'The provided message is too long. Please remove {EXTRA_CHARS_COUNT} character{PLURAL_S}.',\n // eslint-disable-next-line max-len\n FRESH_RESET_AUTHORISATION_FORBIDDEN: 'You can’t logout other sessions if less than 24 hours have passed since you logged on the current session',\n\n BOTS_TOO_MUCH: 'There are too many bots in this chat/channel',\n BOT_GROUPS_BLOCKED: 'This bot can\\'t be added to groups',\n USERS_TOO_MUCH: 'The maximum number of users has been exceeded',\n USER_CHANNELS_TOO_MUCH: 'One of the users you tried to add is already in too many channels/supergroups',\n USER_KICKED: 'This user was kicked from this supergroup/channel',\n USER_NOT_MUTUAL_CONTACT: 'The provided user is not a mutual contact',\n USER_PRIVACY_RESTRICTED: 'The user\\'s privacy settings do not allow you to do this',\n INVITE_HASH_EMPTY: 'The invite hash is empty',\n INVITE_HASH_EXPIRED: 'The invite link has expired',\n INVITE_HASH_INVALID: 'The invite hash is invalid',\n CHANNELS_TOO_MUCH: 'You have joined too many channels/supergroups',\n USER_ALREADY_PARTICIPANT: 'You already in the group',\n SCHEDULE_DATE_INVALID: 'Invalid schedule date provided',\n WALLPAPER_DIMENSIONS_INVALID: 'The wallpaper dimensions are invalid, please select another file',\n};\n\nexport const SHIPPING_ERRORS: Record = {\n ADDRESS_STREET_LINE1_INVALID: {\n field: 'streetLine1',\n message: 'Incorrect street address',\n },\n ADDRESS_STREET_LINE2_INVALID: {\n field: 'streetLine2',\n message: 'Incorrect street address',\n },\n ADDRESS_CITY_INVALID: {\n field: 'city',\n message: 'Incorrect city',\n },\n ADDRESS_COUNTRY_INVALID: {\n field: 'countryIso2',\n message: 'Incorrect country',\n },\n ADDRESS_POSTCODE_INVALID: {\n field: 'postCode',\n message: 'Incorrect post code',\n },\n ADDRESS_STATE_INVALID: {\n field: 'state',\n message: 'Incorrect state',\n },\n REQ_INFO_NAME_INVALID: {\n field: 'fullName',\n message: 'Incorrect name',\n },\n REQ_INFO_PHONE_INVALID: {\n field: 'phone',\n message: 'Incorrect phone',\n },\n REQ_INFO_EMAIL_INVALID: {\n field: 'email',\n message: 'Incorrect email',\n },\n};\n\nexport default function getReadableErrorText(error: ApiError) {\n const { message, isSlowMode, textParams } = error;\n // Currently, Telegram API doesn't return `SLOWMODE_WAIT_X` error as described in the docs\n if (isSlowMode) {\n const extraPartIndex = message.indexOf(' (caused by');\n return extraPartIndex > 0 ? message.substring(0, extraPartIndex) : message;\n }\n let errorMessage = READABLE_ERROR_MESSAGES[message];\n if (errorMessage && textParams) {\n errorMessage = Object.keys(textParams).reduce((acc, current) => {\n return acc.replace(current, textParams[current]);\n }, errorMessage as string);\n }\n return errorMessage;\n}\n\nexport function getShippingError(error: ApiError): ApiFieldError | undefined {\n return SHIPPING_ERRORS[error.message];\n}\n","import { DEBUG_ALERT_MSG } from '../config';\nimport { throttle } from './schedulers';\n\nwindow.addEventListener('error', handleErrorEvent);\nwindow.addEventListener('unhandledrejection', handleErrorEvent);\n\n// eslint-disable-next-line prefer-destructuring\nconst APP_ENV = process.env.APP_ENV;\n\nfunction handleErrorEvent(e: ErrorEvent | PromiseRejectionEvent) {\n e.preventDefault();\n\n handleError(e instanceof ErrorEvent ? e.error : e.reason);\n}\n\nconst throttledAlert = throttle(window.alert, 1000);\n\nexport function handleError(err: Error) {\n // eslint-disable-next-line no-console\n console.error(err);\n\n if (APP_ENV === 'development' || APP_ENV === 'staging') {\n throttledAlert(`${DEBUG_ALERT_MSG}\\n\\n${(err?.message) || err}\\n${err?.stack}`);\n }\n}\n","type CollectionByKey = Record;\n\ntype OrderDirection = 'asc' | 'desc';\n\ninterface OrderCallback {\n (member: T): any;\n}\n\nexport function buildCollectionByKey(collection: T[], key: keyof T) {\n return collection.reduce((byKey: CollectionByKey, member: T) => {\n byKey[member[key]] = member;\n\n return byKey;\n }, {});\n}\n\nexport function mapValues(\n byKey: CollectionByKey,\n callback: (member: M, key: string, index: number, originalByKey: CollectionByKey) => R,\n): CollectionByKey {\n return Object.keys(byKey).reduce((newByKey: CollectionByKey, key, index) => {\n newByKey[key] = callback(byKey[key], key, index, byKey);\n return newByKey;\n }, {});\n}\n\nexport function pick(object: T, keys: K[]) {\n return keys.reduce((result, key) => {\n result[key] = object[key];\n return result;\n }, {} as Pick);\n}\n\nexport function pickTruthy(object: T, keys: K[]) {\n return keys.reduce((result, key) => {\n if (object[key]) {\n result[key] = object[key];\n }\n\n return result;\n }, {} as Pick);\n}\n\nexport function omit(object: T, keys: K[]) {\n const stringKeys = new Set(keys.map(String));\n const savedKeys = Object.keys(object)\n .filter((key) => !stringKeys.has(key)) as Array>;\n\n return pick(object, savedKeys);\n}\n\nexport function orderBy(\n collection: T[],\n orderKey: (keyof T) | OrderCallback | ((keyof T) | OrderCallback)[],\n mode: OrderDirection | [OrderDirection, OrderDirection] = 'asc',\n): T[] {\n return collection.sort((a, b) => {\n if (Array.isArray(orderKey)) {\n const [mode1, mode2] = Array.isArray(mode) ? mode : [mode, mode];\n const [orderKey1, orderKey2] = orderKey;\n\n let aValue1;\n let bValue1;\n\n if (typeof orderKey1 === 'function') {\n aValue1 = orderKey1(a) || 0;\n bValue1 = orderKey1(b) || 0;\n } else if (typeof orderKey1 === 'string') {\n aValue1 = a[orderKey1] || 0;\n bValue1 = b[orderKey1] || 0;\n }\n\n if (aValue1 !== bValue1) {\n return mode1 === 'asc' ? aValue1 - bValue1 : bValue1 - aValue1;\n } else {\n let aValue2;\n let bValue2;\n\n if (typeof orderKey2 === 'function') {\n aValue2 = orderKey2(a) || 0;\n bValue2 = orderKey2(b) || 0;\n } else if (typeof orderKey2 === 'string') {\n aValue2 = a[orderKey2] || 0;\n bValue2 = b[orderKey2] || 0;\n }\n\n return mode2 === 'asc' ? aValue2 - bValue2 : bValue2 - aValue2;\n }\n }\n\n let aValue;\n let bValue;\n\n if (typeof orderKey === 'function') {\n aValue = orderKey(a) || 0;\n bValue = orderKey(b) || 0;\n } else if (typeof orderKey === 'string') {\n aValue = a[orderKey] || 0;\n bValue = b[orderKey] || 0;\n }\n\n return mode === 'asc' ? aValue - bValue : bValue - aValue;\n });\n}\n\nexport function flatten(array: any[]) {\n return array.reduce((result, member) => {\n if (Array.isArray(member)) {\n return result.concat(member);\n } else {\n result.push(member);\n return result;\n }\n }, []);\n}\n\nexport function unique(array: T[]): T[] {\n return Array.from(new Set(array));\n}\n\nexport function compact(array: any[]) {\n return array.filter(Boolean);\n}\n\nexport function areSortedArraysEqual(array1: any[], array2: any[]) {\n if (array1.length !== array2.length) {\n return false;\n }\n\n return array1.every((item, i) => item === array2[i]);\n}\n\nexport function areSortedArraysIntersecting(array1: any[], array2: any[]) {\n return array1[0] <= array2[array2.length - 1] && array1[array1.length - 1] >= array2[0];\n}\n\nexport function findIntersectionWithSet(array: T[], set: Set): T[] {\n return array.filter((a) => set.has(a));\n}\n\nexport function split(array: any[], chunkSize: number) {\n const result = [];\n for (let i = 0; i < array.length; i += chunkSize) {\n result.push(array.slice(i, i + chunkSize));\n }\n\n return result;\n}\n\nexport function cloneDeep(value: T): T {\n if (typeof value !== 'object') {\n return value;\n }\n\n if (Array.isArray(value)) {\n return value.map(cloneDeep) as typeof value;\n }\n\n return Object.keys(value).reduce((acc, key) => {\n acc[key as keyof T] = cloneDeep(value[key as keyof T]);\n return acc;\n }, {} as T);\n}\n\n/**\n * Returns the index of the last element in the array where predicate is true, and -1 otherwise.\n *\n * @param array The source array to search in\n * @param predicate find calls predicate once for each element of the array, in descending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.\n */\nexport function findLast(array: Array, predicate: (value: T, index: number, obj: T[]) => boolean): T | undefined {\n let cursor = array.length;\n\n while (cursor--) {\n if (predicate(array[cursor], cursor, array)) {\n return array[cursor];\n }\n }\n\n return undefined;\n}\n","import { getGlobal } from '../lib/teact/teactn';\n\nimport { ApiLangPack, ApiLangString } from '../api/types';\nimport { LangCode, TimeFormat } from '../types';\n\nimport {\n DEFAULT_LANG_CODE, DEFAULT_LANG_PACK, LANG_CACHE_NAME, LANG_PACKS,\n} from '../config';\nimport * as cacheApi from './cacheApi';\nimport { callApi } from '../api/gramjs';\nimport { createCallbackManager } from './callbacks';\nimport { formatInteger } from './textFormat';\n\ninterface LangFn {\n (key: string, value?: any, format?: 'i'): any;\n\n isRtl?: boolean;\n code?: LangCode;\n timeFormat?: TimeFormat;\n}\n\nconst SUBSTITUTION_REGEX = /%\\d?\\$?[sdf@]/g;\nconst PLURAL_OPTIONS = ['value', 'zeroValue', 'oneValue', 'twoValue', 'fewValue', 'manyValue', 'otherValue'] as const;\nconst PLURAL_RULES = {\n /* eslint-disable max-len */\n en: (n: number) => (n !== 1 ? 6 : 2),\n ar: (n: number) => (n === 0 ? 1 : n === 1 ? 2 : n === 2 ? 3 : n % 100 >= 3 && n % 100 <= 10 ? 4 : n % 100 >= 11 ? 5 : 6),\n ca: (n: number) => (n !== 1 ? 6 : 2),\n de: (n: number) => (n !== 1 ? 6 : 2),\n es: (n: number) => (n !== 1 ? 6 : 2),\n fa: (n: number) => (n > 1 ? 6 : 2),\n fr: (n: number) => (n > 1 ? 6 : 2),\n id: () => 0,\n it: (n: number) => (n !== 1 ? 6 : 2),\n ko: () => 0,\n ms: () => 0,\n nl: (n: number) => (n !== 1 ? 6 : 2),\n pl: (n: number) => (n === 1 ? 2 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 4 : 5),\n pt_BR: (n: number) => (n > 1 ? 6 : 2),\n ru: (n: number) => (n % 10 === 1 && n % 100 !== 11 ? 2 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 4 : 5),\n tr: (n: number) => (n > 1 ? 6 : 2),\n uk: (n: number) => (n % 10 === 1 && n % 100 !== 11 ? 2 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 4 : 5),\n uz: (n: number) => (n > 1 ? 6 : 2),\n /* eslint-enable max-len */\n};\n\nconst cache = new Map();\n\nlet langPack: ApiLangPack | undefined;\nlet fallbackLangPack: ApiLangPack | undefined;\n\nconst {\n addCallback,\n removeCallback,\n runCallbacks,\n} = createCallbackManager();\n\nexport { addCallback, removeCallback };\n\nlet currentLangCode: string | undefined;\nlet currentTimeFormat: TimeFormat | undefined;\n\nexport const getTranslation: LangFn = (key: string, value?: any, format?: 'i') => {\n if (value !== undefined) {\n const cacheValue = Array.isArray(value) ? JSON.stringify(value) : value;\n const cached = cache.get(`${key}_${cacheValue}_${format}`);\n if (cached) {\n return cached;\n }\n }\n\n if (!langPack && !fallbackLangPack) {\n return key;\n }\n\n const langString = (langPack?.[key]) || (fallbackLangPack?.[key]);\n if (!langString) {\n if (!fallbackLangPack) {\n void importFallbackLangPack();\n }\n\n return key;\n }\n\n return processTranslation(langString, key, value, format);\n};\n\nexport async function getTranslationForLangString(langCode: string, key: string) {\n let translateString: ApiLangString | undefined = await cacheApi.fetch(\n LANG_CACHE_NAME,\n `${DEFAULT_LANG_PACK}_${langCode}_${key}`,\n cacheApi.Type.Json,\n );\n\n if (!translateString) {\n translateString = await fetchRemoteString(DEFAULT_LANG_PACK, langCode, key);\n }\n\n return processTranslation(translateString, key);\n}\n\nexport async function setLanguage(langCode: LangCode, callback?: NoneToVoidFunction, withFallback = false) {\n if (langPack && langCode === currentLangCode) {\n if (callback) {\n callback();\n }\n\n return;\n }\n\n let newLangPack = await cacheApi.fetch(LANG_CACHE_NAME, langCode, cacheApi.Type.Json);\n if (!newLangPack) {\n if (withFallback) {\n await importFallbackLangPack();\n }\n\n newLangPack = await fetchRemote(langCode);\n if (!newLangPack) {\n return;\n }\n }\n\n cache.clear();\n\n currentLangCode = langCode;\n langPack = newLangPack;\n document.documentElement.lang = langCode;\n\n const { languages, timeFormat } = getGlobal().settings.byKey;\n const langInfo = languages?.find((l) => l.langCode === langCode);\n getTranslation.isRtl = Boolean(langInfo?.rtl);\n getTranslation.code = langCode;\n getTranslation.timeFormat = timeFormat;\n\n if (callback) {\n callback();\n }\n\n runCallbacks();\n}\n\nexport function setTimeFormat(timeFormat: TimeFormat) {\n if (timeFormat && timeFormat === currentTimeFormat) {\n return;\n }\n\n currentTimeFormat = timeFormat;\n getTranslation.timeFormat = timeFormat;\n\n runCallbacks();\n}\n\nasync function importFallbackLangPack() {\n if (fallbackLangPack) {\n return;\n }\n\n fallbackLangPack = (await import('./fallbackLangPack')).default;\n runCallbacks();\n}\n\nasync function fetchRemote(langCode: string): Promise {\n const remote = await callApi('fetchLangPack', { sourceLangPacks: LANG_PACKS, langCode });\n if (remote) {\n await cacheApi.save(LANG_CACHE_NAME, langCode, remote.langPack);\n return remote.langPack;\n }\n\n return undefined;\n}\n\nasync function fetchRemoteString(\n remoteLangPack: typeof LANG_PACKS[number], langCode: string, key: string,\n): Promise {\n const remote = await callApi('fetchLangStrings', {\n langPack: remoteLangPack,\n langCode,\n keys: [key],\n });\n\n if (remote?.length) {\n await cacheApi.save(LANG_CACHE_NAME, `${remoteLangPack}_${langCode}_${key}`, remote[0]);\n\n return remote[0];\n }\n\n return undefined;\n}\n\nfunction getPluralOption(amount: number) {\n const langCode = currentLangCode || DEFAULT_LANG_CODE;\n const optionIndex = PLURAL_RULES[langCode as keyof typeof PLURAL_RULES]\n ? PLURAL_RULES[langCode as keyof typeof PLURAL_RULES](amount)\n : 0;\n\n return PLURAL_OPTIONS[optionIndex];\n}\n\nfunction processTemplate(template: string, value: any) {\n value = Array.isArray(value) ? value : [value];\n const translationSlices = template.split(SUBSTITUTION_REGEX);\n const initialValue = translationSlices.shift();\n\n return translationSlices.reduce((result, str, index) => {\n return `${result}${String(value[index] || '')}${str}`;\n }, initialValue || '');\n}\n\nfunction processTranslation(langString: ApiLangString | undefined, key: string, value?: any, format?: 'i') {\n const template = langString ? langString[typeof value === 'number' ? getPluralOption(value) : 'value'] : undefined;\n if (!template || !template.trim()) {\n const parts = key.split('.');\n\n return parts[parts.length - 1];\n }\n\n if (value !== undefined) {\n const formattedValue = format === 'i' ? formatInteger(value) : value;\n const result = processTemplate(template, formattedValue);\n const cacheValue = Array.isArray(value) ? JSON.stringify(value) : value;\n cache.set(`${key}_${cacheValue}_${format}`, result);\n return result;\n }\n\n return template;\n}\n","export function createCallbackManager() {\n const callbacks: AnyToVoidFunction[] = [];\n\n function addCallback(cb: AnyToVoidFunction) {\n callbacks.push(cb);\n\n return () => {\n removeCallback(cb);\n };\n }\n\n function removeCallback(cb: AnyToVoidFunction) {\n const index = callbacks.indexOf(cb);\n if (index !== -1) {\n callbacks.splice(index, 1);\n }\n }\n\n function runCallbacks(...args: any[]) {\n callbacks.forEach((callback) => {\n callback(...args);\n });\n }\n\n return {\n runCallbacks,\n addCallback,\n removeCallback,\n };\n}\n","const SAMPLE_RATE = 48000;\nconst BIT_DEPTH = 16;\n\nexport async function oggToWav(opusData: Blob): Promise {\n const arrayBuffer = await new Response(opusData).arrayBuffer();\n\n return new Promise((resolve) => {\n const typedArray = new Uint8Array(arrayBuffer);\n\n let decoderWorker: Worker | undefined = new Worker(\n new URL('opus-recorder/dist/decoderWorker.min.js', import.meta.url),\n );\n let wavWorker: Worker | undefined = new Worker(new URL('opus-recorder/dist/waveWorker.min.js', import.meta.url));\n\n decoderWorker.onmessage = (e) => {\n // eslint-disable-next-line no-null/no-null\n if (e.data === null) {\n // `null` means decoder is finished\n wavWorker!.postMessage({ command: 'done' });\n } else {\n // `e.data` contains decoded buffers as float32 values\n wavWorker!.postMessage(\n {\n command: 'encode',\n buffers: e.data,\n },\n e.data.map(({ buffer }: Float32Array) => buffer),\n );\n }\n };\n\n wavWorker.onmessage = (e) => {\n if (e.data.message === 'page') {\n resolve(new Blob([e.data.page], { type: 'audio/wav' }));\n\n decoderWorker!.terminate();\n decoderWorker = undefined;\n wavWorker!.terminate();\n wavWorker = undefined;\n }\n };\n\n wavWorker.postMessage({\n command: 'init',\n wavBitDepth: BIT_DEPTH,\n wavSampleRate: SAMPLE_RATE,\n });\n\n decoderWorker.postMessage({\n command: 'init',\n decoderSampleRate: SAMPLE_RATE,\n outputBufferSampleRate: SAMPLE_RATE,\n });\n\n decoderWorker.postMessage({\n command: 'decode',\n pages: typedArray,\n }, [typedArray.buffer]);\n });\n}\n","import {\n ApiMediaFormat,\n ApiMediaFormatToPrepared,\n ApiOnProgress,\n ApiParsedMedia,\n ApiPreparedMedia,\n} from '../api/types';\n\nimport {\n DEBUG, MEDIA_CACHE_DISABLED, MEDIA_CACHE_NAME, MEDIA_CACHE_NAME_AVATARS,\n} from '../config';\nimport { callApi, cancelApiProgress } from '../api/gramjs';\nimport * as cacheApi from './cacheApi';\nimport { fetchBlob } from './files';\nimport { IS_OPUS_SUPPORTED, IS_PROGRESSIVE_SUPPORTED, isWebpSupported } from './environment';\nimport { oggToWav } from './oggToWav';\nimport { webpToPng } from './webpToPng';\n\nconst asCacheApiType = {\n [ApiMediaFormat.BlobUrl]: cacheApi.Type.Blob,\n [ApiMediaFormat.Lottie]: cacheApi.Type.Json,\n [ApiMediaFormat.Progressive]: undefined,\n [ApiMediaFormat.Stream]: undefined,\n};\n\nconst PROGRESSIVE_URL_PREFIX = './progressive/';\n\nconst memoryCache = new Map();\nconst fetchPromises = new Map>();\nconst progressCallbacks = new Map>();\nconst cancellableCallbacks = new Map();\n\nexport function fetch(\n url: string,\n mediaFormat: T,\n isHtmlAllowed = false,\n onProgress?: ApiOnProgress,\n callbackUniqueId?: string,\n): Promise> {\n if (mediaFormat === ApiMediaFormat.Progressive) {\n return (\n IS_PROGRESSIVE_SUPPORTED\n ? getProgressive(url)\n : fetch(url, ApiMediaFormat.BlobUrl, isHtmlAllowed, onProgress, callbackUniqueId)\n ) as Promise>;\n }\n\n if (!fetchPromises.has(url)) {\n const promise = fetchFromCacheOrRemote(url, mediaFormat, isHtmlAllowed)\n .catch((err) => {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n\n return undefined;\n })\n .finally(() => {\n fetchPromises.delete(url);\n progressCallbacks.delete(url);\n cancellableCallbacks.delete(url);\n });\n\n fetchPromises.set(url, promise);\n }\n\n if (onProgress && callbackUniqueId) {\n let activeCallbacks = progressCallbacks.get(url);\n if (!activeCallbacks) {\n activeCallbacks = new Map();\n progressCallbacks.set(url, activeCallbacks);\n }\n activeCallbacks.set(callbackUniqueId, onProgress);\n }\n\n return fetchPromises.get(url) as Promise>;\n}\n\nexport function getFromMemory(url: string) {\n return memoryCache.get(url) as ApiMediaFormatToPrepared;\n}\n\nexport function cancelProgress(progressCallback: ApiOnProgress) {\n progressCallbacks.forEach((map, url) => {\n map.forEach((callback) => {\n if (callback === progressCallback) {\n const parentCallback = cancellableCallbacks.get(url);\n if (!parentCallback) return;\n\n cancelApiProgress(parentCallback);\n cancellableCallbacks.delete(url);\n progressCallbacks.delete(url);\n }\n });\n });\n}\n\nexport function removeCallback(url: string, callbackUniqueId: string) {\n const callbacks = progressCallbacks.get(url);\n if (!callbacks) return;\n callbacks.delete(callbackUniqueId);\n}\n\nfunction getProgressive(url: string) {\n const progressiveUrl = `${PROGRESSIVE_URL_PREFIX}${url}`;\n\n memoryCache.set(url, progressiveUrl);\n\n return Promise.resolve(progressiveUrl);\n}\n\nasync function fetchFromCacheOrRemote(\n url: string, mediaFormat: ApiMediaFormat, isHtmlAllowed: boolean,\n) {\n if (!MEDIA_CACHE_DISABLED) {\n const cacheName = url.startsWith('avatar') ? MEDIA_CACHE_NAME_AVATARS : MEDIA_CACHE_NAME;\n const cached = await cacheApi.fetch(cacheName, url, asCacheApiType[mediaFormat]!, isHtmlAllowed);\n\n if (cached) {\n let media = cached;\n\n if (cached.type === 'audio/ogg' && !IS_OPUS_SUPPORTED) {\n media = await oggToWav(media);\n }\n\n if (cached.type === 'image/webp' && !isWebpSupported() && media) {\n const mediaPng = await webpToPng(url, media);\n if (mediaPng) {\n media = mediaPng;\n }\n }\n\n const prepared = prepareMedia(media);\n\n memoryCache.set(url, prepared);\n\n return prepared;\n }\n }\n\n if (mediaFormat === ApiMediaFormat.Stream) {\n const mediaSource = new MediaSource();\n const streamUrl = URL.createObjectURL(mediaSource);\n let isOpen = false;\n\n mediaSource.addEventListener('sourceopen', () => {\n if (isOpen) {\n return;\n }\n isOpen = true;\n\n const sourceBuffer = mediaSource.addSourceBuffer('audio/mpeg');\n\n const onProgress = makeOnProgress(url, mediaSource, sourceBuffer);\n cancellableCallbacks.set(url, onProgress);\n\n void callApi('downloadMedia', { url, mediaFormat }, onProgress);\n });\n\n memoryCache.set(url, streamUrl);\n return streamUrl;\n }\n\n const onProgress = makeOnProgress(url);\n cancellableCallbacks.set(url, onProgress);\n\n const remote = await callApi('downloadMedia', { url, mediaFormat, isHtmlAllowed }, onProgress);\n if (!remote) {\n throw new Error(`Failed to fetch media ${url}`);\n }\n\n let { prepared, mimeType } = remote;\n\n if (mimeType === 'audio/ogg' && !IS_OPUS_SUPPORTED) {\n const blob = await fetchBlob(prepared as string);\n URL.revokeObjectURL(prepared as string);\n const media = await oggToWav(blob);\n prepared = prepareMedia(media);\n mimeType = media.type;\n }\n\n if (mimeType === 'image/webp' && !isWebpSupported()) {\n const blob = await fetchBlob(prepared as string);\n URL.revokeObjectURL(prepared as string);\n const media = await webpToPng(url, blob);\n if (media) {\n prepared = prepareMedia(media);\n }\n }\n\n memoryCache.set(url, prepared);\n\n return prepared;\n}\n\nfunction makeOnProgress(url: string, mediaSource?: MediaSource, sourceBuffer?: SourceBuffer) {\n const onProgress: ApiOnProgress = (progress: number, arrayBuffer: ArrayBuffer) => {\n progressCallbacks.get(url)?.forEach((callback) => {\n callback(progress);\n if (callback.isCanceled) onProgress.isCanceled = true;\n });\n\n if (progress === 1) {\n mediaSource?.endOfStream();\n }\n\n if (!arrayBuffer) {\n return;\n }\n\n sourceBuffer?.appendBuffer(arrayBuffer);\n };\n\n return onProgress;\n}\n\nfunction prepareMedia(mediaData: ApiParsedMedia): ApiPreparedMedia {\n if (mediaData instanceof Blob) {\n return URL.createObjectURL(mediaData);\n }\n\n return mediaData;\n}\n\nif (IS_PROGRESSIVE_SUPPORTED) {\n navigator.serviceWorker.addEventListener('message', async (e) => {\n const { type, messageId, params } = e.data as {\n type: string;\n messageId: string;\n params: { url: string; start: number; end: number };\n };\n\n if (type !== 'requestPart') {\n return;\n }\n\n const result = await callApi('downloadMedia', { mediaFormat: ApiMediaFormat.Progressive, ...params });\n if (!result) {\n return;\n }\n\n const { arrayBuffer, mimeType, fullSize } = result;\n\n navigator.serviceWorker.controller!.postMessage({\n type: 'partResponse',\n messageId,\n result: {\n arrayBuffer,\n mimeType,\n fullSize,\n },\n }, [arrayBuffer!]);\n });\n}\n","export const MEMO_EMPTY_ARRAY = [];\n","import { DEBUG } from '../config';\n\nexport enum Bundles {\n Auth,\n Main,\n Extra,\n}\n\ninterface ImportedBundles {\n [Bundles.Auth]: typeof import('../bundles/auth');\n [Bundles.Main]: typeof import('../bundles/main');\n [Bundles.Extra]: typeof import('../bundles/extra');\n}\n\ntype BundlePromises = {\n [K in keyof ImportedBundles]: Promise\n};\n\nexport type BundleModules = keyof ImportedBundles[B];\n\nconst LOAD_PROMISES: Partial = {};\nconst MEMORY_CACHE: Partial = {};\n\nexport async function loadModule>(bundleName: B, moduleName: M) {\n if (!LOAD_PROMISES[bundleName]) {\n switch (bundleName) {\n case Bundles.Auth:\n LOAD_PROMISES[Bundles.Auth] = import('../bundles/auth');\n break;\n case Bundles.Main:\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START LOAD MAIN BUNDLE');\n }\n\n LOAD_PROMISES[Bundles.Main] = import('../bundles/main');\n break;\n case Bundles.Extra:\n LOAD_PROMISES[Bundles.Extra] = import('../bundles/extra');\n break;\n }\n\n (LOAD_PROMISES[bundleName] as Promise).then(handleBundleLoad);\n }\n\n const bundle = (await LOAD_PROMISES[bundleName]) as unknown as ImportedBundles[B];\n\n if (!MEMORY_CACHE[bundleName]) {\n MEMORY_CACHE[bundleName] = bundle;\n }\n\n return getModuleFromMemory(bundleName, moduleName);\n}\n\nexport function getModuleFromMemory>(bundleName: B, moduleName: M) {\n const bundle = MEMORY_CACHE[bundleName] as ImportedBundles[B];\n\n if (!bundle) {\n return undefined;\n }\n\n return bundle[moduleName];\n}\n\nconst listeners: NoneToVoidFunction[] = [];\n\nexport function addLoadListener(listener: NoneToVoidFunction) {\n if (!listeners.includes(listener)) {\n listeners.push(listener);\n }\n}\n\nfunction handleBundleLoad() {\n listeners.forEach((listener) => {\n listener();\n });\n}\n","import { callApi } from '../api/gramjs';\nimport {\n ApiChat, ApiMediaFormat, ApiMessage, ApiUser,\n} from '../api/types';\nimport { renderActionMessageText } from '../components/common/helpers/renderActionMessageText';\nimport { DEBUG, IS_TEST } from '../config';\nimport { getDispatch, getGlobal, setGlobal } from '../lib/teact/teactn';\nimport {\n getChatAvatarHash,\n getChatTitle,\n getMessageAction,\n getMessageSenderName,\n getMessageSummaryText,\n getPrivateChatUserId,\n isActionMessage,\n isChatChannel,\n selectIsChatMuted, selectShouldShowMessagePreview,\n} from '../modules/helpers';\nimport { getTranslation } from './langProvider';\nimport { addNotifyExceptions, replaceSettings } from '../modules/reducers';\nimport {\n selectChatMessage, selectNotifyExceptions, selectNotifySettings, selectUser,\n} from '../modules/selectors';\nimport { IS_SERVICE_WORKER_SUPPORTED } from './environment';\nimport * as mediaLoader from './mediaLoader';\nimport { debounce } from './schedulers';\n\nfunction getDeviceToken(subscription: PushSubscription) {\n const data = subscription.toJSON();\n return JSON.stringify({\n endpoint: data.endpoint,\n keys: data.keys,\n });\n}\n\nfunction checkIfPushSupported() {\n if (!IS_SERVICE_WORKER_SUPPORTED) return false;\n if (!('showNotification' in ServiceWorkerRegistration.prototype)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('[PUSH] Push notifications aren\\'t supported.');\n }\n return false;\n }\n\n // Check the current Notification permission.\n // If its denied, it's a permanent block until the\n // user changes the permission\n if (Notification.permission === 'denied') {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('[PUSH] The user has blocked push notifications.');\n }\n return false;\n }\n\n // Check if push messaging is supported\n if (!('PushManager' in window)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('[PUSH] Push messaging isn\\'t supported.');\n }\n return false;\n }\n return true;\n}\n\nfunction checkIfNotificationsSupported() {\n // Let's check if the browser supports notifications\n if (!('Notification' in window)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('[PUSH] This browser does not support desktop notification');\n }\n return false;\n }\n\n if (Notification.permission === 'denied' as NotificationPermission) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('[PUSH] The user has blocked push notifications.');\n }\n return false;\n }\n return true;\n}\n\nconst expirationTime = 12 * 60 * 60 * 1000; // 12 hours\n// Notification id is removed from soundPlayed cache after 3 seconds\nconst soundPlayedDelay = 3 * 1000;\nconst soundPlayedIds = new Set();\n\nexport async function playNotifySound(id?: string, volume?: number) {\n if (id !== undefined && soundPlayedIds.has(id)) return;\n const { notificationSoundVolume } = selectNotifySettings(getGlobal());\n const currentVolume = volume ? volume / 10 : notificationSoundVolume / 10;\n if (currentVolume === 0) return;\n\n const audio = new Audio('./notification.mp3');\n audio.volume = currentVolume;\n audio.setAttribute('mozaudiochannel', 'notification');\n if (id !== undefined) {\n audio.addEventListener('ended', () => {\n soundPlayedIds.add(id);\n }, { once: true });\n\n setTimeout(() => {\n soundPlayedIds.delete(id);\n }, soundPlayedDelay);\n }\n\n try {\n await audio.play();\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('[PUSH] Unable to play notification sound');\n }\n }\n}\n\nexport const playNotifySoundDebounced = debounce(playNotifySound, 1000, true, false);\n\nfunction checkIfShouldResubscribe(subscription: PushSubscription | null) {\n const global = getGlobal();\n if (!global.push || !subscription) return true;\n if (getDeviceToken(subscription) !== global.push.deviceToken) return true;\n return Date.now() - global.push.subscribedAt > expirationTime;\n}\n\nasync function requestPermission() {\n if (!('Notification' in window)) return;\n if (!['granted', 'denied'].includes(Notification.permission)) {\n await Notification.requestPermission();\n }\n}\n\nasync function unsubscribeFromPush(subscription: PushSubscription | null) {\n const global = getGlobal();\n const dispatch = getDispatch();\n if (subscription) {\n try {\n const deviceToken = getDeviceToken(subscription);\n await callApi('unregisterDevice', deviceToken);\n await subscription.unsubscribe();\n dispatch.deleteDeviceToken();\n return;\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[PUSH] Unable to unsubscribe from push.', error);\n }\n }\n }\n if (global.push) {\n await callApi('unregisterDevice', global.push.deviceToken);\n dispatch.deleteDeviceToken();\n }\n}\n\nexport async function unsubscribe() {\n if (!checkIfPushSupported()) return;\n const serviceWorkerRegistration = await navigator.serviceWorker.ready;\n const subscription = await serviceWorkerRegistration.pushManager.getSubscription();\n await unsubscribeFromPush(subscription);\n}\n\n// Indicates if notification settings are loaded from the api\nlet areSettingsLoaded = false;\n\n// Load notification settings from the api\nasync function loadNotificationSettings() {\n if (areSettingsLoaded) return selectNotifySettings(getGlobal());\n const [resultSettings, resultExceptions] = await Promise.all([\n callApi('fetchNotificationSettings', {\n serverTimeOffset: getGlobal().serverTimeOffset,\n }),\n callApi('fetchNotificationExceptions', {\n serverTimeOffset: getGlobal().serverTimeOffset,\n }),\n ]);\n if (!resultSettings) return selectNotifySettings(getGlobal());\n\n let global = replaceSettings(getGlobal(), resultSettings);\n if (resultExceptions) {\n global = addNotifyExceptions(global, resultExceptions);\n }\n setGlobal(global);\n areSettingsLoaded = true;\n return selectNotifySettings(global);\n}\n\nexport async function subscribe() {\n if (!checkIfPushSupported()) {\n // Ask for notification permissions only if service worker notifications are not supported\n // As pushManager.subscribe automatically triggers permission popup\n await requestPermission();\n return;\n }\n const serviceWorkerRegistration = await navigator.serviceWorker.ready;\n let subscription = await serviceWorkerRegistration.pushManager.getSubscription();\n if (!checkIfShouldResubscribe(subscription)) return;\n await unsubscribeFromPush(subscription);\n try {\n subscription = await serviceWorkerRegistration.pushManager.subscribe({\n userVisibleOnly: true,\n });\n const deviceToken = getDeviceToken(subscription);\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[PUSH] Received push subscription: ', deviceToken);\n }\n await callApi('registerDevice', deviceToken);\n getDispatch()\n .setDeviceToken(deviceToken);\n } catch (error) {\n if (Notification.permission === 'denied' as NotificationPermission) {\n // The user denied the notification permission which\n // means we failed to subscribe and the user will need\n // to manually change the notification permission to\n // subscribe to push messages\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('[PUSH] The user has blocked push notifications.');\n }\n } else if (DEBUG) {\n // A problem occurred with the subscription, this can\n // often be down to an issue or lack of the gcm_sender_id\n // and / or gcm_user_visible_only\n // eslint-disable-next-line no-console\n console.log('[PUSH] Unable to subscribe to push.', error);\n\n // Request permissions and fall back to local notifications\n // if pushManager.subscribe was aborted due to invalid VAPID key.\n if (error.code === DOMException.ABORT_ERR) {\n await requestPermission();\n }\n }\n }\n}\n\nfunction checkIfShouldNotify(chat: ApiChat) {\n if (!areSettingsLoaded) return false;\n const global = getGlobal();\n const isMuted = selectIsChatMuted(chat, selectNotifySettings(global), selectNotifyExceptions(global));\n if (isMuted || chat.isNotJoined || !chat.isListed) {\n return false;\n }\n\n return !document.hasFocus();\n}\n\nfunction getNotificationContent(chat: ApiChat, message: ApiMessage) {\n const global = getGlobal();\n const {\n senderId,\n replyToMessageId,\n } = message;\n\n const messageSender = senderId ? selectUser(global, senderId) : undefined;\n const messageAction = getMessageAction(message as ApiMessage);\n const actionTargetMessage = messageAction && replyToMessageId\n ? selectChatMessage(global, chat.id, replyToMessageId)\n : undefined;\n const {\n targetUserIds: actionTargetUserIds,\n targetChatId: actionTargetChatId,\n } = messageAction || {};\n\n const actionTargetUsers = actionTargetUserIds\n ? actionTargetUserIds.map((userId) => selectUser(global, userId))\n .filter(Boolean as any)\n : undefined;\n const privateChatUserId = getPrivateChatUserId(chat);\n const privateChatUser = privateChatUserId ? selectUser(global, privateChatUserId) : undefined;\n\n let body: string;\n if (selectShouldShowMessagePreview(chat, selectNotifySettings(global), selectNotifyExceptions(global))) {\n if (isActionMessage(message)) {\n const actionOrigin = chat && (isChatChannel(chat) || message.senderId === message.chatId)\n ? chat\n : messageSender;\n body = renderActionMessageText(\n getTranslation,\n message,\n actionOrigin,\n actionTargetUsers,\n actionTargetMessage,\n actionTargetChatId,\n { asPlain: true },\n ) as string;\n } else {\n const senderName = getMessageSenderName(getTranslation, chat.id, messageSender);\n const summary = getMessageSummaryText(getTranslation, message);\n\n body = senderName ? `${senderName}: ${summary}` : summary;\n }\n } else {\n body = 'New message';\n }\n\n return {\n title: getChatTitle(getTranslation, chat, privateChatUser),\n body,\n };\n}\n\nasync function getAvatar(chat: ApiChat) {\n const imageHash = getChatAvatarHash(chat);\n if (!imageHash) return undefined;\n let mediaData = mediaLoader.getFromMemory(imageHash);\n if (!mediaData) {\n await mediaLoader.fetch(imageHash, ApiMediaFormat.BlobUrl);\n mediaData = mediaLoader.getFromMemory(imageHash);\n }\n return mediaData;\n}\n\nexport async function notifyAboutNewMessage({\n chat,\n message,\n}: { chat: ApiChat; message: Partial }) {\n const { hasWebNotifications } = await loadNotificationSettings();\n if (!checkIfShouldNotify(chat)) return;\n if (!hasWebNotifications) {\n // only play sound if web notifications are disabled\n playNotifySoundDebounced(String(message.id) || chat.id);\n return;\n }\n if (!checkIfNotificationsSupported()) return;\n if (!message.id) return;\n\n const {\n title,\n body,\n } = getNotificationContent(chat, message as ApiMessage);\n\n const icon = await getAvatar(chat);\n\n if (checkIfPushSupported()) {\n if (navigator.serviceWorker?.controller) {\n // notify service worker about new message notification\n navigator.serviceWorker.controller.postMessage({\n type: 'newMessageNotification',\n payload: {\n title,\n body,\n icon,\n chatId: chat.id,\n messageId: message.id,\n },\n });\n }\n } else {\n const dispatch = getDispatch();\n const options: NotificationOptions = {\n body,\n icon,\n badge: icon,\n tag: String(message.id),\n };\n\n if ('vibrate' in navigator) {\n options.vibrate = [200, 100, 200];\n }\n\n const notification = new Notification(title, options);\n\n notification.onclick = () => {\n notification.close();\n dispatch.focusMessage({\n chatId: chat.id,\n messageId: message.id,\n });\n if (window.focus) {\n window.focus();\n }\n };\n\n // Play sound when notification is displayed\n notification.onshow = () => {\n playNotifySoundDebounced(String(message.id) || chat.id);\n };\n }\n}\n\nexport function closeMessageNotifications(payload: { chatId: string; lastReadInboxMessageId?: number }) {\n if (IS_TEST || !navigator.serviceWorker?.controller) return;\n navigator.serviceWorker.controller.postMessage({\n type: 'closeMessageNotifications',\n payload,\n });\n}\n\n// Notify service worker that client is fully loaded\nexport function notifyClientReady() {\n if (!navigator.serviceWorker?.controller) return;\n navigator.serviceWorker.controller.postMessage({\n type: 'clientReady',\n });\n}\n","import { ApiCountryCode } from '../api/types';\nimport { flatten } from './iteratees';\n\nconst PATTERN_PLACEHOLDER = 'X';\nconst DEFAULT_PATTERN = 'XXX XXX XXX XXX';\n\nexport function getCountryCodesByIso(phoneCodeList: ApiCountryCode[], iso: string) {\n return phoneCodeList.filter((country) => country.iso2 === iso);\n}\n\nexport function getCountryFromPhoneNumber(phoneCodeList: ApiCountryCode[], input = '') {\n let phoneNumber = input.replace(/[^\\d+]+/g, '');\n if (phoneNumber.startsWith('+')) {\n phoneNumber = phoneNumber.substr(1);\n }\n\n const possibleCountries = phoneCodeList\n .filter((country) => phoneNumber.startsWith(country.countryCode));\n const codesWithPrefix: { code: string; country: ApiCountryCode }[] = flatten(possibleCountries\n .map((country) => (country.prefixes || ['']).map((prefix) => {\n return {\n code: `${country.countryCode}${prefix}`,\n country,\n };\n })));\n\n const bestMatches = codesWithPrefix\n .filter(({ code }) => phoneNumber.startsWith(code))\n .sort((a, b) => a.code.length - b.code.length);\n\n return bestMatches[bestMatches.length - 1]?.country;\n}\n\nexport function formatPhoneNumber(input: string, country?: ApiCountryCode) {\n let phoneNumber = input.replace(/[^\\d]+/g, '');\n if (country) {\n phoneNumber = phoneNumber.substr(country.countryCode.length);\n } else if (input.startsWith('+')) {\n return input;\n }\n const pattern = getBestPattern(phoneNumber, country?.patterns);\n\n const result: string[] = []; // Result character array\n let j = 0; // Position inside pattern\n for (let i = 0; i < phoneNumber.length; i++) {\n while (pattern[j] !== PATTERN_PLACEHOLDER && j < pattern.length) {\n result.push(pattern[j]);\n if (pattern[j] === phoneNumber[i]) { // If pattern contains digits, move input position too\n i++;\n if (i === phoneNumber.length) break; // But don't overdo it, or it will insert full pattern unexpectedly\n }\n j++;\n }\n\n result.push(phoneNumber[i]); // For placeholder characters, setting current input digit\n j++;\n }\n\n return result.join('');\n}\n\nfunction getBestPattern(numberWithoutCode: string, patterns?: string[]) {\n if (!patterns || patterns.length === 0) return DEFAULT_PATTERN;\n if (patterns.length === 1) return patterns[0];\n\n const defaultPattern = patterns.find((pattern) => pattern.startsWith(PATTERN_PLACEHOLDER)) || DEFAULT_PATTERN;\n\n const bestMatches = patterns.filter((pattern) => {\n const stripped = pattern.replace(/[^\\dX]+/g, '');\n if (stripped.startsWith(PATTERN_PLACEHOLDER)) return false; // Don't consider default number format here\n for (let i = 0; i < numberWithoutCode.length; i++) {\n if (i > stripped.length - 1 || (stripped[i] !== PATTERN_PLACEHOLDER && stripped[i] !== numberWithoutCode[i])) {\n return false;\n }\n }\n return true;\n });\n\n // Playing it safe: if not sure, use default for that region\n return bestMatches.length === 1 ? bestMatches[0] : defaultPattern;\n}\n\nexport function formatPhoneNumberWithCode(phoneCodeList: ApiCountryCode[], phoneNumber: string) {\n const numberWithPlus = phoneNumber.startsWith('+') ? phoneNumber : `+${phoneNumber}`;\n const country = getCountryFromPhoneNumber(phoneCodeList, numberWithPlus);\n if (!country) {\n return numberWithPlus;\n }\n return `+${country.countryCode} ${formatPhoneNumber(numberWithPlus, country)}`;\n}\n","import { MessageList, MessageListType } from '../global/types';\nimport { MAIN_THREAD_ID } from '../api/types';\n\nexport const createMessageHash = (messageList: MessageList): string => (\n messageList.chatId.toString()\n + (messageList.type !== 'thread' ? `_${messageList.type}`\n : (messageList.threadId !== -1 ? `_${messageList.threadId}` : ''))\n);\n\nexport const parseLocationHash = (value: string): MessageList | undefined => {\n if (!value) return undefined;\n\n const [chatId, typeOrThreadId] = value.replace(/^#/, '').split('_');\n\n if (!chatId) return undefined;\n\n const isType = ['thread', 'pinned', 'scheduled'].includes(typeOrThreadId);\n\n return {\n chatId,\n type: !!typeOrThreadId && isType ? (typeOrThreadId as MessageListType) : 'thread',\n threadId: !!typeOrThreadId && !isType ? Number(typeOrThreadId) : MAIN_THREAD_ID,\n };\n};\n","type Scheduler =\n typeof requestAnimationFrame\n | typeof onTickEnd\n | typeof runNow;\n\nexport function debounce(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n shouldRunLast = true,\n) {\n let waitingTimeout: number | undefined;\n\n return (...args: Parameters) => {\n if (waitingTimeout) {\n clearTimeout(waitingTimeout);\n waitingTimeout = undefined;\n } else if (shouldRunFirst) {\n // @ts-ignore\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n waitingTimeout = self.setTimeout(() => {\n if (shouldRunLast) {\n // @ts-ignore\n fn(...args);\n }\n\n waitingTimeout = undefined;\n }, ms);\n };\n}\n\nexport function throttle(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n) {\n let interval: number | undefined;\n let isPending: boolean;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n isPending = true;\n args = _args;\n\n if (!interval) {\n if (shouldRunFirst) {\n isPending = false;\n // @ts-ignore\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n interval = self.setInterval(() => {\n if (!isPending) {\n // eslint-disable-next-line no-restricted-globals\n self.clearInterval(interval!);\n interval = undefined;\n return;\n }\n\n isPending = false;\n // @ts-ignore\n fn(...args);\n }, ms);\n }\n };\n}\n\nexport function throttleWithRaf(fn: F) {\n return throttleWith(fastRaf, fn);\n}\n\nexport function throttleWithPrimaryRaf(fn: F) {\n return throttleWith(fastRafPrimary, fn);\n}\n\nexport function throttleWithTickEnd(fn: F) {\n return throttleWith(onTickEnd, fn);\n}\n\nexport function throttleWithNow(fn: F) {\n return throttleWith(runNow, fn);\n}\n\nexport function throttleWith(schedulerFn: Scheduler, fn: F) {\n let waiting = false;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n args = _args;\n\n if (!waiting) {\n waiting = true;\n\n schedulerFn(() => {\n waiting = false;\n // @ts-ignore\n fn(...args);\n });\n }\n };\n}\n\nexport function onIdle(cb: NoneToVoidFunction) {\n // eslint-disable-next-line no-restricted-globals\n if (self.requestIdleCallback) {\n // eslint-disable-next-line no-restricted-globals\n self.requestIdleCallback(cb);\n } else {\n onTickEnd(cb);\n }\n}\n\nfunction runNow(fn: NoneToVoidFunction) {\n fn();\n}\n\nexport const pause = (ms: number) => new Promise((resolve) => {\n setTimeout(() => resolve(), ms);\n});\n\nexport function rafPromise() {\n return new Promise((resolve) => {\n fastRaf(resolve);\n });\n}\n\nlet fastRafCallbacks: NoneToVoidFunction[] | undefined;\nlet fastRafPrimaryCallbacks: NoneToVoidFunction[] | undefined;\n\n// May result in an immediate execution if called from another `requestAnimationFrame` callback\nexport function fastRaf(callback: NoneToVoidFunction, isPrimary = false) {\n if (!fastRafCallbacks) {\n fastRafCallbacks = isPrimary ? [] : [callback];\n fastRafPrimaryCallbacks = isPrimary ? [callback] : [];\n\n requestAnimationFrame(() => {\n const currentCallbacks = fastRafCallbacks!;\n const currentPrimaryCallbacks = fastRafPrimaryCallbacks!;\n fastRafCallbacks = undefined;\n fastRafPrimaryCallbacks = undefined;\n currentPrimaryCallbacks.forEach((cb) => cb());\n currentCallbacks.forEach((cb) => cb());\n });\n } else if (isPrimary) {\n fastRafPrimaryCallbacks!.push(callback);\n } else {\n fastRafCallbacks.push(callback);\n }\n}\n\nexport function fastRafPrimary(callback: NoneToVoidFunction) {\n fastRaf(callback, true);\n}\n\nlet onTickEndCallbacks: NoneToVoidFunction[] | undefined;\nlet onTickEndPrimaryCallbacks: NoneToVoidFunction[] | undefined;\n\nexport function onTickEnd(callback: NoneToVoidFunction, isPrimary = false) {\n if (!onTickEndCallbacks) {\n onTickEndCallbacks = isPrimary ? [] : [callback];\n onTickEndPrimaryCallbacks = isPrimary ? [callback] : [];\n\n Promise.resolve().then(() => {\n const currentCallbacks = onTickEndCallbacks!;\n const currentPrimaryCallbacks = onTickEndPrimaryCallbacks!;\n onTickEndCallbacks = undefined;\n onTickEndPrimaryCallbacks = undefined;\n currentPrimaryCallbacks.forEach((cb) => cb());\n currentCallbacks.forEach((cb) => cb());\n });\n } else if (isPrimary) {\n onTickEndPrimaryCallbacks!.push(callback);\n } else {\n onTickEndCallbacks.push(callback);\n }\n}\n\nexport function onTickEndPrimary(callback: NoneToVoidFunction) {\n onTickEnd(callback, true);\n}\n\nlet beforeUnloadCallbacks: NoneToVoidFunction[] | undefined;\n\nexport function onBeforeUnload(callback: NoneToVoidFunction, isLast = false) {\n if (!beforeUnloadCallbacks) {\n beforeUnloadCallbacks = [];\n // eslint-disable-next-line no-restricted-globals\n self.addEventListener('beforeunload', () => {\n beforeUnloadCallbacks!.forEach((cb) => cb());\n });\n }\n\n if (isLast) {\n beforeUnloadCallbacks.push(callback);\n } else {\n beforeUnloadCallbacks.unshift(callback);\n }\n\n return () => {\n beforeUnloadCallbacks = beforeUnloadCallbacks!.filter((cb) => cb !== callback);\n };\n}\n","let RE_NOT_LETTER: RegExp;\n\ntry {\n RE_NOT_LETTER = new RegExp('[^\\\\p{L}\\\\p{M}]+', 'ui');\n} catch (e) {\n // Support for older versions of firefox\n RE_NOT_LETTER = new RegExp('[^\\\\wа-яё]+', 'i');\n}\n\nexport default function searchWords(haystack: string, needle: string) {\n if (!haystack || !needle) {\n return false;\n }\n\n const haystackWords = haystack.toLowerCase().split(RE_NOT_LETTER);\n const needleWords = needle.toLowerCase().split(RE_NOT_LETTER);\n\n return needleWords.every((needleWord) => (\n haystackWords.some((haystackWord) => haystackWord.startsWith(needleWord))\n ));\n}\n","export const getServerTime = (serverTimeOffset: number) => {\n return Math.floor(Date.now() / 1000) + serverTimeOffset;\n};\n","import safariFix from 'safari-14-idb-fix';\n\nfunction promisifyRequest(request) {\n return new Promise((resolve, reject) => {\n // @ts-ignore - file size hacks\n request.oncomplete = request.onsuccess = () => resolve(request.result);\n // @ts-ignore - file size hacks\n request.onabort = request.onerror = () => reject(request.error);\n });\n}\nfunction createStore(dbName, storeName) {\n const dbp = safariFix().then(() => {\n const request = indexedDB.open(dbName);\n request.onupgradeneeded = () => request.result.createObjectStore(storeName);\n return promisifyRequest(request);\n });\n return (txMode, callback) => dbp.then((db) => callback(db.transaction(storeName, txMode).objectStore(storeName)));\n}\nlet defaultGetStoreFunc;\nfunction defaultGetStore() {\n if (!defaultGetStoreFunc) {\n defaultGetStoreFunc = createStore('keyval-store', 'keyval');\n }\n return defaultGetStoreFunc;\n}\n/**\n * Get a value by its key.\n *\n * @param key\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction get(key, customStore = defaultGetStore()) {\n return customStore('readonly', (store) => promisifyRequest(store.get(key)));\n}\n/**\n * Set a value with a key.\n *\n * @param key\n * @param value\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction set(key, value, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.put(value, key);\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Set multiple values at once. This is faster than calling set() multiple times.\n * It's also atomic – if one of the pairs can't be added, none will be added.\n *\n * @param entries Array of entries, where each entry is an array of `[key, value]`.\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction setMany(entries, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n entries.forEach((entry) => store.put(entry[1], entry[0]));\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Get multiple values by their keys\n *\n * @param keys\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction getMany(keys, customStore = defaultGetStore()) {\n return customStore('readonly', (store) => Promise.all(keys.map((key) => promisifyRequest(store.get(key)))));\n}\n/**\n * Update a value. This lets you see the old value and update it as an atomic operation.\n *\n * @param key\n * @param updater A callback that takes the old value and returns a new value.\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction update(key, updater, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => \n // Need to create the promise manually.\n // If I try to chain promises, the transaction closes in browsers\n // that use a promise polyfill (IE10/11).\n new Promise((resolve, reject) => {\n store.get(key).onsuccess = function () {\n try {\n store.put(updater(this.result), key);\n resolve(promisifyRequest(store.transaction));\n }\n catch (err) {\n reject(err);\n }\n };\n }));\n}\n/**\n * Delete a particular key from the store.\n *\n * @param key\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction del(key, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.delete(key);\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Clear all values in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction clear(customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.clear();\n return promisifyRequest(store.transaction);\n });\n}\nfunction eachCursor(customStore, callback) {\n return customStore('readonly', (store) => {\n // This would be store.getAllKeys(), but it isn't supported by Edge or Safari.\n // And openKeyCursor isn't supported by Safari.\n store.openCursor().onsuccess = function () {\n if (!this.result)\n return;\n callback(this.result);\n this.result.continue();\n };\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Get all keys in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction keys(customStore = defaultGetStore()) {\n const items = [];\n return eachCursor(customStore, (cursor) => items.push(cursor.key)).then(() => items);\n}\n/**\n * Get all values in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction values(customStore = defaultGetStore()) {\n const items = [];\n return eachCursor(customStore, (cursor) => items.push(cursor.value)).then(() => items);\n}\n/**\n * Get all entries in the store. Each entry is an array of `[key, value]`.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction entries(customStore = defaultGetStore()) {\n const items = [];\n return eachCursor(customStore, (cursor) => items.push([cursor.key, cursor.value])).then(() => items);\n}\n\nexport { clear, createStore, del, entries, get, getMany, keys, promisifyRequest, set, setMany, update, values };\n","/**\n * https://bugs.webkit.org/show_bug.cgi?id=226547\n * Safari has a horrible bug where IDB requests can hang while the browser is starting up.\n * The only solution is to keep nudging it until it's awake.\n * This probably creates garbage, but garbage is better than totally failing.\n */\nfunction idbReady() {\n const isSafari = !navigator.userAgentData &&\n /Safari\\//.test(navigator.userAgent) &&\n !/Chrom(e|ium)\\//.test(navigator.userAgent);\n // No point putting other browsers or older versions of Safari through this mess.\n if (!isSafari || !indexedDB.databases)\n return Promise.resolve();\n let intervalId;\n return new Promise((resolve) => {\n const tryIdb = () => indexedDB.databases().finally(resolve);\n intervalId = setInterval(tryIdb, 100);\n tryIdb();\n }).finally(() => clearInterval(intervalId));\n}\n\nexport default idbReady;\n","import * as idb from 'idb-keyval';\n\nimport { ApiSessionData } from '../api/types';\n\nimport { DEBUG, LEGACY_SESSION_KEY, SESSION_USER_KEY } from '../config';\nimport * as cacheApi from './cacheApi';\n\nconst DC_IDS = [1, 2, 3, 4, 5];\n\nexport function hasStoredSession(withLegacy = false) {\n if (withLegacy && localStorage.getItem(LEGACY_SESSION_KEY)) {\n return true;\n }\n\n const userAuthJson = localStorage.getItem(SESSION_USER_KEY);\n if (!userAuthJson) return false;\n\n try {\n const userAuth = JSON.parse(userAuthJson);\n return Boolean(userAuth && userAuth.id && userAuth.dcID);\n } catch (err) {\n // Do nothing.\n return false;\n }\n}\n\nexport function storeSession(sessionData: ApiSessionData, currentUserId?: string) {\n const { mainDcId, keys, hashes } = sessionData;\n\n localStorage.setItem(SESSION_USER_KEY, JSON.stringify({ dcID: mainDcId, id: currentUserId }));\n localStorage.setItem('dc', String(mainDcId));\n Object.keys(keys).map(Number).forEach((dcId) => {\n localStorage.setItem(`dc${dcId}_auth_key`, JSON.stringify(keys[dcId]));\n });\n\n if (hashes) {\n Object.keys(hashes).map(Number).forEach((dcId) => {\n localStorage.setItem(`dc${dcId}_hash`, JSON.stringify(hashes[dcId]));\n });\n }\n}\n\nexport function clearStoredSession() {\n [\n SESSION_USER_KEY,\n 'dc',\n ...DC_IDS.map((dcId) => `dc${dcId}_auth_key`),\n ...DC_IDS.map((dcId) => `dc${dcId}_hash`),\n ].forEach((key) => {\n localStorage.removeItem(key);\n });\n}\n\nexport function loadStoredSession(): ApiSessionData | undefined {\n if (!hasStoredSession()) {\n return undefined;\n }\n\n const userAuth = JSON.parse(localStorage.getItem(SESSION_USER_KEY)!);\n const mainDcId = Number(userAuth.dcID);\n const keys: Record = {};\n const hashes: Record = {};\n\n DC_IDS.forEach((dcId) => {\n try {\n const key = localStorage.getItem(`dc${dcId}_auth_key`);\n if (key) {\n keys[dcId] = JSON.parse(key);\n }\n\n const hash = localStorage.getItem(`dc${dcId}_hash`);\n if (hash) {\n hashes[dcId] = JSON.parse(hash);\n }\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('Failed to load stored session', err);\n }\n // Do nothing.\n }\n });\n\n if (!Object.keys(keys).length) return undefined;\n\n return {\n mainDcId,\n keys,\n hashes,\n };\n}\n\nexport async function importLegacySession() {\n const sessionId = localStorage.getItem(LEGACY_SESSION_KEY);\n if (!sessionId) return;\n\n const sessionJson = await idb.get(`GramJs:${sessionId}`);\n try {\n const sessionData = JSON.parse(sessionJson) as ApiSessionData;\n storeSession(sessionData);\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('Failed to load legacy session', err);\n }\n // Do nothing.\n }\n}\n\n// Remove previously created IndexedDB and cache API sessions\nexport async function clearLegacySessions() {\n localStorage.removeItem(LEGACY_SESSION_KEY);\n\n const idbKeys = await idb.keys();\n\n await Promise.all>([\n cacheApi.clear('GramJs'),\n ...idbKeys\n .filter((k) => typeof k === 'string' && k.startsWith('GramJs:GramJs-session-'))\n .map((k) => idb.del(k)),\n ]);\n}\n\nexport function importTestSession() {\n const sessionJson = process.env.TEST_SESSION!;\n try {\n const sessionData = JSON.parse(sessionJson) as ApiSessionData & { userId: string };\n storeSession(sessionData, sessionData.userId);\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('Failed to load test session', err);\n }\n // Do nothing.\n }\n}\n","import { ISettings } from '../types';\n\nimport { animateSingle } from './animation';\n\nimport themeColors from '../styles/themes.json';\n\ntype RGBAColor = {\n r: number;\n g: number;\n b: number;\n a?: number;\n};\n\nlet isInitialized = false;\n\nconst HEX_COLOR_REGEX = /^#?([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})?$/i;\nconst DURATION_MS = 200;\nconst ENABLE_ANIMATION_DELAY_MS = 500;\nconst RGB_VARIABLES = new Set([\n '--color-primary-shade',\n '--color-text-secondary',\n]);\n\nconst lerp = (start: number, end: number, interpolationRatio: number) => {\n return (1 - interpolationRatio) * start + interpolationRatio * end;\n};\n\nconst colors = (Object.keys(themeColors) as Array).map((property) => ({\n property,\n colors: [hexToRgb(themeColors[property][0]), hexToRgb(themeColors[property][1])],\n}));\n\nexport default (theme: ISettings['theme'], withAnimation: boolean) => {\n const isDarkTheme = theme === 'dark';\n const shouldAnimate = isInitialized && withAnimation;\n const startIndex = isDarkTheme ? 0 : 1;\n const endIndex = isDarkTheme ? 1 : 0;\n const startAt = Date.now();\n const themeColorTag = document.querySelector('meta[name=\"theme-color\"]');\n\n document.documentElement.classList.remove(`theme-${isDarkTheme ? 'light' : 'dark'}`);\n if (isInitialized) {\n document.documentElement.classList.add('no-animations');\n }\n document.documentElement.classList.add(`theme-${theme}`);\n if (themeColorTag) {\n themeColorTag.setAttribute('content', isDarkTheme ? '#212121' : '#fff');\n }\n\n setTimeout(() => {\n document.documentElement.classList.remove('no-animations');\n }, ENABLE_ANIMATION_DELAY_MS);\n\n isInitialized = true;\n\n if (shouldAnimate) {\n animateSingle(() => {\n const t = Math.min((Date.now() - startAt) / DURATION_MS, 1);\n\n applyColorAnimationStep(startIndex, endIndex, transition(t));\n\n return t < 1;\n });\n } else {\n applyColorAnimationStep(startIndex, endIndex);\n }\n};\n\nfunction transition(t: number) {\n return 1 - ((1 - t) ** 3.5);\n}\n\nfunction hexToRgb(hex: string): RGBAColor {\n const result = HEX_COLOR_REGEX.exec(hex)!;\n\n return {\n r: parseInt(result[1], 16),\n g: parseInt(result[2], 16),\n b: parseInt(result[3], 16),\n a: result[4] !== undefined ? parseInt(result[4], 16) : undefined,\n };\n}\n\nfunction applyColorAnimationStep(startIndex: number, endIndex: number, interpolationRatio: number = 1) {\n colors.forEach(({ property, colors: propertyColors }) => {\n const r = Math.round(lerp(propertyColors[startIndex].r, propertyColors[endIndex].r, interpolationRatio));\n const g = Math.round(lerp(propertyColors[startIndex].g, propertyColors[endIndex].g, interpolationRatio));\n const b = Math.round(lerp(propertyColors[startIndex].b, propertyColors[endIndex].b, interpolationRatio));\n const a = propertyColors[startIndex].a !== undefined\n ? Math.round(lerp(propertyColors[startIndex].a!, propertyColors[endIndex].a!, interpolationRatio))\n : undefined;\n\n document.documentElement.style.setProperty(property, a !== undefined\n ? `rgba(${r},${g},${b},${a / 255})`\n : `rgb(${r},${g},${b})`);\n\n if (RGB_VARIABLES.has(property)) {\n document.documentElement.style.setProperty(`${property}-rgb`, `${r},${g},${b}`);\n }\n });\n}\n","import EMOJI_REGEX from '../lib/twemojiRegex';\nimport { fixNonStandardEmoji } from './emoji';\n\nexport function formatInteger(value: number) {\n return String(value).replace(/\\d(?=(\\d{3})+$)/g, '$& ');\n}\n\nfunction formatFixedNumber(number: number) {\n const fixed = String(number.toFixed(1));\n if (fixed.substr(-2) === '.0') {\n return Math.round(number);\n }\n\n return number.toFixed(1).replace('.', ',');\n}\n\nexport function formatIntegerCompact(views: number) {\n if (views < 1e3) {\n return views;\n }\n\n if (views < 1e6) {\n return `${formatFixedNumber(views / 1e3)}K`;\n }\n\n return `${formatFixedNumber(views / 1e6)}M`;\n}\n\nexport function getFirstLetters(phrase: string, count = 2) {\n return phrase\n .replace(/[.,!@#$%^&*()_+=\\-`~[\\]/\\\\{}:\"|<>?]+/gi, '')\n .trim()\n .split(/\\s+/)\n .slice(0, count)\n .map((word: string) => {\n if (!word.length) return '';\n word = fixNonStandardEmoji(word);\n const emojis = word.match(EMOJI_REGEX);\n if (emojis && word.startsWith(emojis[0])) {\n return emojis[0];\n }\n return word.match(/./u)![0].toUpperCase();\n })\n .join('');\n}\n","const DEFAULT_MAX_TEXT_LENGTH = 30;\n\nexport default function trimText(text: string | undefined, length = DEFAULT_MAX_TEXT_LENGTH) {\n if (!text || text.length <= length) {\n return text;\n }\n\n return `${text.substr(0, length)}...`;\n}\n","import { isWebpSupported } from './environment';\nimport { dataUriToBlob, blobToDataUri } from './files';\nimport { pause } from './schedulers';\n\nconst WORKER_INITIALIZATION_TIMEOUT = 2000;\n\nlet canvas: HTMLCanvasElement;\nlet worker: IWebpWorker;\n\nexport const EMPTY_IMAGE_DATA_URI = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk'\n + 'YAAAAAYAAjCB0C8AAAAASUVORK5CYII=';\n\nexport async function webpToPng(url: string, blob: Blob): Promise {\n initWebpWorker();\n\n while (!worker.wasmReady) {\n await pause(WORKER_INITIALIZATION_TIMEOUT);\n }\n\n const { result, width, height } = await getDecodePromise(url, blob);\n if (!width || !height) {\n return undefined;\n }\n\n return createPng({ result, width, height });\n}\n\nexport async function webpToPngBase64(key: string, dataUri: string): Promise {\n if (isWebpSupported() || dataUri.substr(0, 15) !== 'data:image/webp') {\n return dataUri;\n }\n\n initWebpWorker();\n\n const pngBlob = await webpToPng(key, dataUriToBlob(dataUri));\n\n if (!pngBlob) {\n throw new Error(`Can't convert webp to png. Url: ${dataUri}`);\n }\n\n return blobToDataUri(pngBlob);\n}\n\nfunction initWebpWorker() {\n if (!worker) {\n worker = new Worker(new URL('../lib/webp/webp_wasm.worker.js', import.meta.url)) as IWebpWorker;\n worker.wasmReady = false;\n worker.onmessage = handleLibWebpMessage;\n }\n}\n\nfunction createPng({ result, width, height }: TEncodedImage): Promise {\n if (!canvas) {\n canvas = document.createElement('canvas');\n }\n\n return new Promise((resolve) => {\n const img = new ImageData(result, width, height);\n\n canvas.width = width;\n canvas.height = height;\n const ctx = canvas.getContext('2d')!;\n ctx.putImageData(img, 0, 0);\n\n canvas.toBlob((blob) => {\n resolve(blob ?? undefined);\n }, 'image/png', 1);\n });\n}\n\nfunction handleLibWebpMessage(e: MessageEvent) {\n const { id } = e.data;\n switch (e.data.type) {\n case 'initialized': {\n worker.wasmReady = true;\n break;\n }\n\n case 'result': {\n if (worker.requests.has(id)) {\n const resolve = worker.requests.get(id)!;\n\n worker.requests.delete(id);\n resolve(e.data!);\n }\n break;\n }\n }\n}\n\nfunction getDecodePromise(url: string, blob: Blob): Promise {\n return new Promise((resolve) => {\n if (!worker.requests) {\n worker.requests = new Map();\n }\n\n worker.requests.set(url, resolve);\n worker.postMessage({ id: url, blob });\n });\n}\n","import { APP_VERSION, DEBUG } from '../config';\nimport { getGlobal } from '../lib/teact/teactn';\nimport { hasStoredSession } from './sessions';\n\nconst WEBSYNC_URLS = [\n 't.me',\n 'telegram.me',\n].map((domain) => `//${domain}/_websync_?`);\nconst WEBSYNC_VERSION = `${APP_VERSION} Z`;\nconst WEBSYNC_KEY = 'tgme_sync';\nconst WEBSYNC_TIMEOUT = 86400;\n\nconst getTs = () => {\n return Math.floor(Number(new Date()) / 1000);\n};\n\nconst saveSync = (authed: boolean) => {\n const ts = getTs();\n localStorage.setItem(WEBSYNC_KEY, JSON.stringify({\n canRedirect: authed,\n ts,\n }));\n};\n\nlet lastTimeout: NodeJS.Timeout | undefined;\n\nexport const forceWebsync = (authed: boolean) => {\n const currentTs = getTs();\n\n const { canRedirect, ts } = JSON.parse(localStorage.getItem(WEBSYNC_KEY) || '{}');\n\n if (canRedirect !== authed || ts + WEBSYNC_TIMEOUT <= currentTs) {\n return Promise.all(WEBSYNC_URLS.map((url) => {\n return new Promise((resolve, reject) => {\n const script = document.createElement('script');\n\n const removeElement = () => !!document.body.removeChild(script);\n\n script.src = url + new URLSearchParams({\n authed: Number(authed).toString(),\n version: WEBSYNC_VERSION,\n });\n\n document.body.appendChild(script);\n\n script.onload = () => {\n saveSync(authed);\n removeElement();\n if (lastTimeout) {\n clearTimeout(lastTimeout);\n lastTimeout = undefined;\n }\n startWebsync();\n resolve();\n };\n\n script.onerror = () => {\n removeElement();\n reject();\n };\n });\n }));\n } else {\n return Promise.resolve();\n }\n};\n\nexport function startWebsync() {\n if (DEBUG) {\n return;\n }\n\n if (lastTimeout !== undefined) return;\n const currentTs = getTs();\n\n const { ts } = JSON.parse(localStorage.getItem(WEBSYNC_KEY) || '{}');\n\n const timeout = WEBSYNC_TIMEOUT - (currentTs - ts);\n\n lastTimeout = setTimeout(() => {\n const { authState } = getGlobal();\n\n const authed = authState === 'authorizationStateReady' || hasStoredSession(true);\n forceWebsync(authed);\n }, Math.max(0, timeout * 1000));\n}\n","import { throttle } from './schedulers';\nimport {\n MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT,\n MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH,\n MOBILE_SCREEN_MAX_WIDTH,\n} from '../config';\nimport { IS_IOS, IS_SINGLE_COLUMN_LAYOUT } from './environment';\n\ntype IDimensions = {\n width: number;\n height: number;\n};\n\nconst IS_LANDSCAPE = IS_SINGLE_COLUMN_LAYOUT && isLandscape();\n\nconst initialHeight = window.innerHeight;\nlet windowSize = updateSizes();\nlet isRefreshDisabled = false;\n\nfunction disableRefresh() {\n isRefreshDisabled = true;\n}\n\nfunction enableRefresh() {\n isRefreshDisabled = false;\n}\n\nconst handleResize = throttle(() => {\n windowSize = updateSizes();\n\n if (!isRefreshDisabled && (\n isMobileScreen() !== IS_SINGLE_COLUMN_LAYOUT\n || (IS_SINGLE_COLUMN_LAYOUT && IS_LANDSCAPE !== isLandscape())\n )) {\n window.location.reload();\n }\n}, 250, true);\n\nwindow.addEventListener('orientationchange', handleResize);\nif (IS_IOS) {\n window.visualViewport.addEventListener('resize', handleResize);\n} else {\n window.addEventListener('resize', handleResize);\n}\n\nexport function updateSizes(): IDimensions {\n let height: number;\n if (IS_IOS) {\n height = window.visualViewport.height + window.visualViewport.pageTop;\n } else {\n height = window.innerHeight;\n }\n const vh = height * 0.01;\n\n document.documentElement.style.setProperty('--vh', `${vh}px`);\n\n return {\n width: window.innerWidth,\n height: window.innerHeight,\n };\n}\n\nfunction isMobileScreen() {\n return windowSize.width <= MOBILE_SCREEN_MAX_WIDTH || (\n windowSize.width <= MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH && windowSize.height <= MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT\n );\n}\n\nfunction isLandscape() {\n if (IS_IOS) {\n return window.matchMedia('(orientation: landscape)').matches;\n }\n\n // eslint-disable-next-line max-len\n // Source: https://web.archive.org/web/20160509220835/http://blog.abouthalf.com/development/orientation-media-query-challenges-in-android-browsers/\n // Feature is marked as deprecated now, but it is still supported\n // https://developer.mozilla.org/en-US/docs/Web/CSS/@media/device-aspect-ratio#browser_compatibility\n return window.matchMedia('screen and (min-device-aspect-ratio: 1/1) and (orientation: landscape)').matches;\n}\n\nexport default {\n get: () => windowSize,\n getIsKeyboardVisible: () => initialHeight > windowSize.height,\n disableRefresh,\n enableRefresh,\n};\n","// 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\t// no module.id needed\n\t\t// no module.loaded needed\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// 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","// 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\n__webpack_require__.u = (chunkId) => {\n\t// return url for filenames based on template\n\treturn \"\" + chunkId + \".\" + {\"99\":\"f03a947e6e336feffec8\",\"133\":\"aae91a1c7ca8928cb720\",\"161\":\"286d0207d962142ad548\",\"306\":\"abed97b181f73c2c1aa8\",\"325\":\"d8a67d9617f2e13de2dc\",\"354\":\"f579d864cf3b32d15240\",\"472\":\"21e5264f606f2b525030\",\"501\":\"72ce4b6e27f459e194cd\",\"514\":\"89d97ccb086a4c539d1a\",\"524\":\"57eea32f15dc5514a3eb\",\"536\":\"55dc7dd4ab42a2c9f037\",\"701\":\"0c52bb0aaf1cd79c0b70\",\"745\":\"9316c5c2b711c39a20a5\",\"915\":\"13af1c4ab9a00d84ac23\",\"941\":\"a1bb68030d234cd6f825\",\"993\":\"f0aad9f6787f211b4e51\"}[chunkId] + \".js\";\n};","// This function allow to reference all chunks\n__webpack_require__.miniCssF = (chunkId) => {\n\t// return url for filenames based on template\n\treturn \"\" + chunkId + \".\" + {\"133\":\"aae91a1c7ca8928cb720\",\"306\":\"abed97b181f73c2c1aa8\",\"325\":\"d8a67d9617f2e13de2dc\",\"472\":\"21e5264f606f2b525030\",\"701\":\"0c52bb0aaf1cd79c0b70\"}[chunkId] + \".css\";\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};","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;","__webpack_require__.b = document.baseURI || self.location.href;\n\n// object to store loaded and loading chunks\n// undefined = chunk not loaded, null = chunk preloaded/prefetched\n// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded\nvar installedChunks = {\n\t179: 0\n};\n\n__webpack_require__.f.j = (chunkId, promises) => {\n\t\t// JSONP chunk loading for javascript\n\t\tvar installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;\n\t\tif(installedChunkData !== 0) { // 0 means \"already installed\".\n\n\t\t\t// a Promise means \"currently loading\".\n\t\t\tif(installedChunkData) {\n\t\t\t\tpromises.push(installedChunkData[2]);\n\t\t\t} else {\n\t\t\t\tif(true) { // all chunks have JS\n\t\t\t\t\t// setup Promise in chunk cache\n\t\t\t\t\tvar promise = new Promise((resolve, reject) => (installedChunkData = installedChunks[chunkId] = [resolve, reject]));\n\t\t\t\t\tpromises.push(installedChunkData[2] = promise);\n\n\t\t\t\t\t// start chunk loading\n\t\t\t\t\tvar url = __webpack_require__.p + __webpack_require__.u(chunkId);\n\t\t\t\t\t// create error before stack unwound to get useful stacktrace later\n\t\t\t\t\tvar error = new Error();\n\t\t\t\t\tvar loadingEnded = (event) => {\n\t\t\t\t\t\tif(__webpack_require__.o(installedChunks, chunkId)) {\n\t\t\t\t\t\t\tinstalledChunkData = installedChunks[chunkId];\n\t\t\t\t\t\t\tif(installedChunkData !== 0) installedChunks[chunkId] = undefined;\n\t\t\t\t\t\t\tif(installedChunkData) {\n\t\t\t\t\t\t\t\tvar errorType = event && (event.type === 'load' ? 'missing' : event.type);\n\t\t\t\t\t\t\t\tvar realSrc = event && event.target && event.target.src;\n\t\t\t\t\t\t\t\terror.message = 'Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';\n\t\t\t\t\t\t\t\terror.name = 'ChunkLoadError';\n\t\t\t\t\t\t\t\terror.type = errorType;\n\t\t\t\t\t\t\t\terror.request = realSrc;\n\t\t\t\t\t\t\t\tinstalledChunkData[1](error);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t\t__webpack_require__.l(url, loadingEnded, \"chunk-\" + chunkId, chunkId);\n\t\t\t\t} else installedChunks[chunkId] = 0;\n\t\t\t}\n\t\t}\n};\n\n// no prefetching\n\n// no preloaded\n\n// no HMR\n\n// no HMR manifest\n\n// no on chunks loaded\n\n// install a JSONP callback for chunk loading\nvar webpackJsonpCallback = (parentChunkLoadingFunction, data) => {\n\tvar [chunkIds, moreModules, runtime] = data;\n\t// add \"moreModules\" to the modules object,\n\t// then flag all \"chunkIds\" as loaded and fire callback\n\tvar moduleId, chunkId, i = 0;\n\tif(chunkIds.some((id) => (installedChunks[id] !== 0))) {\n\t\tfor(moduleId in moreModules) {\n\t\t\tif(__webpack_require__.o(moreModules, moduleId)) {\n\t\t\t\t__webpack_require__.m[moduleId] = moreModules[moduleId];\n\t\t\t}\n\t\t}\n\t\tif(runtime) var result = runtime(__webpack_require__);\n\t}\n\tif(parentChunkLoadingFunction) parentChunkLoadingFunction(data);\n\tfor(;i < chunkIds.length; i++) {\n\t\tchunkId = chunkIds[i];\n\t\tif(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {\n\t\t\tinstalledChunks[chunkId][0]();\n\t\t}\n\t\tinstalledChunks[chunkIds[i]] = 0;\n\t}\n\n}\n\nvar chunkLoadingGlobal = self[\"webpackChunktelegram_t\"] = self[\"webpackChunktelegram_t\"] || [];\nchunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));\nchunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));","import { DEBUG } from '../config';\nimport { getDispatch } from '../lib/teact/teactn';\nimport { IS_ANDROID, IS_IOS, IS_SERVICE_WORKER_SUPPORTED } from './environment';\nimport { notifyClientReady, playNotifySoundDebounced } from './notifications';\n\ntype WorkerAction = {\n type: string;\n payload: Record;\n};\n\nfunction handleWorkerMessage(e: MessageEvent) {\n const action: WorkerAction = e.data;\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[SW] Message from worker', action);\n }\n if (!action.type) return;\n const dispatch = getDispatch();\n switch (action.type) {\n case 'focusMessage':\n if (dispatch.focusMessage) {\n dispatch.focusMessage(action.payload);\n }\n break;\n case 'playNotificationSound':\n playNotifySoundDebounced(action.payload.id);\n break;\n }\n}\n\nfunction subscribeToWorker() {\n navigator.serviceWorker.removeEventListener('message', handleWorkerMessage);\n navigator.serviceWorker.addEventListener('message', handleWorkerMessage);\n // Notify web worker that client is ready to receive messages\n notifyClientReady();\n}\n\nif (IS_SERVICE_WORKER_SUPPORTED) {\n window.addEventListener('load', async () => {\n try {\n await navigator.serviceWorker.register(new URL('../serviceWorker.ts', import.meta.url));\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[SW] ServiceWorker registered');\n }\n\n await navigator.serviceWorker.ready;\n\n if (navigator.serviceWorker.controller) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[SW] ServiceWorker ready');\n }\n subscribeToWorker();\n } else {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('[SW] ServiceWorker not available');\n }\n\n if (!IS_IOS && !IS_ANDROID) {\n getDispatch().showDialog({ data: { message: 'SERVICE_WORKER_DISABLED', hasErrorKey: true } });\n }\n }\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('[SW] ServiceWorker registration failed: ', err);\n }\n }\n });\n window.addEventListener('focus', async () => {\n await navigator.serviceWorker.ready;\n subscribeToWorker();\n });\n}\n","import { GlobalState } from './types';\nimport { NewChatMembersProgress } from '../types';\n\nimport {\n ANIMATION_LEVEL_DEFAULT, DARK_THEME_PATTERN_COLOR, DEFAULT_MESSAGE_TEXT_SIZE_PX, DEFAULT_PATTERN_COLOR,\n DEFAULT_PLAYBACK_RATE,\n DEFAULT_VOLUME,\n IOS_DEFAULT_MESSAGE_TEXT_SIZE_PX, MACOS_DEFAULT_MESSAGE_TEXT_SIZE_PX,\n} from '../config';\nimport { IS_IOS, IS_MAC_OS } from '../util/environment';\n\nexport const INITIAL_STATE: GlobalState = {\n isLeftColumnShown: true,\n isChatInfoShown: false,\n newChatMembersProgress: NewChatMembersProgress.Closed,\n uiReadyState: 0,\n serverTimeOffset: 0,\n\n authRememberMe: true,\n countryList: {\n phoneCodes: [],\n general: [],\n },\n\n blocked: {\n ids: [],\n totalCount: 0,\n },\n\n users: {\n byId: {},\n },\n\n chats: {\n listIds: {},\n isFullyLoaded: {},\n orderedPinnedIds: {},\n totalCount: {},\n byId: {},\n },\n\n messages: {\n byChatId: {},\n messageLists: [],\n },\n\n scheduledMessages: {\n byChatId: {},\n },\n\n chatFolders: {\n byId: {},\n activeChatFolder: 0,\n },\n\n fileUploads: {\n byMessageLocalId: {},\n },\n\n recentEmojis: ['grinning', 'kissing_heart', 'christmas_tree', 'brain', 'trophy'],\n\n stickers: {\n setsById: {},\n added: {},\n recent: {\n stickers: [],\n },\n favorite: {\n stickers: [],\n },\n greeting: {\n stickers: [],\n },\n featured: {\n setIds: [],\n },\n search: {},\n forEmoji: {},\n },\n\n emojiKeywords: {},\n\n gifs: {\n saved: {},\n search: {},\n },\n\n inlineBots: {\n isLoading: false,\n byUsername: {},\n },\n\n globalSearch: {},\n\n userSearch: {},\n\n localTextSearch: {\n byChatThreadKey: {},\n },\n\n localMediaSearch: {\n byChatId: {},\n },\n\n management: {\n byChatId: {},\n },\n\n topPeers: {},\n\n topInlineBots: {},\n\n mediaViewer: {},\n\n audioPlayer: {\n volume: DEFAULT_VOLUME,\n playbackRate: DEFAULT_PLAYBACK_RATE,\n isMuted: false,\n },\n\n forwardMessages: {},\n\n pollResults: {},\n\n payment: {},\n\n notifications: [],\n\n dialogs: [],\n\n activeSessions: [],\n\n settings: {\n byKey: {\n theme: 'light',\n shouldUseSystemTheme: true,\n messageTextSize: IS_IOS\n ? IOS_DEFAULT_MESSAGE_TEXT_SIZE_PX\n : (IS_MAC_OS ? MACOS_DEFAULT_MESSAGE_TEXT_SIZE_PX : DEFAULT_MESSAGE_TEXT_SIZE_PX),\n animationLevel: ANIMATION_LEVEL_DEFAULT,\n messageSendKeyCombo: 'enter',\n canAutoLoadPhotoFromContacts: true,\n canAutoLoadPhotoInPrivateChats: true,\n canAutoLoadPhotoInGroups: true,\n canAutoLoadPhotoInChannels: true,\n canAutoLoadVideoFromContacts: true,\n canAutoLoadVideoInPrivateChats: true,\n canAutoLoadVideoInGroups: true,\n canAutoLoadVideoInChannels: true,\n canAutoLoadFileFromContacts: false,\n canAutoLoadFileInPrivateChats: false,\n canAutoLoadFileInGroups: false,\n canAutoLoadFileInChannels: false,\n autoLoadFileMaxSizeMb: 10,\n hasWebNotifications: true,\n hasPushNotifications: true,\n notificationSoundVolume: 5,\n canAutoPlayGifs: true,\n canAutoPlayVideos: true,\n shouldSuggestStickers: true,\n shouldLoopStickers: true,\n language: 'en',\n timeFormat: '24h',\n wasTimeFormatSetManually: false,\n },\n themes: {\n light: {\n isBlurred: true,\n patternColor: DEFAULT_PATTERN_COLOR,\n },\n dark: {\n isBlurred: true,\n patternColor: DARK_THEME_PATTERN_COLOR,\n },\n },\n privacy: {},\n notifyExceptions: {},\n },\n\n twoFaSettings: {},\n\n shouldShowContextMenuHint: true,\n\n activeDownloads: {\n byChatId: {},\n },\n\n serviceNotifications: [],\n};\n","import {\n addCallback, addReducer, getGlobal, removeCallback,\n} from '../lib/teact/teactn';\n\nimport { GlobalState } from './types';\nimport { MAIN_THREAD_ID } from '../api/types';\n\nimport { onBeforeUnload, onIdle, throttle } from '../util/schedulers';\nimport {\n DEBUG,\n GLOBAL_STATE_CACHE_DISABLED,\n GLOBAL_STATE_CACHE_KEY,\n GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT,\n MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN,\n GLOBAL_STATE_CACHE_USER_LIST_LIMIT,\n DEFAULT_VOLUME,\n DEFAULT_PLAYBACK_RATE,\n} from '../config';\nimport { IS_SINGLE_COLUMN_LAYOUT } from '../util/environment';\nimport { ANIMATION_END_EVENT, ANIMATION_START_EVENT } from '../hooks/useHeavyAnimationCheck';\nimport { pick } from '../util/iteratees';\nimport { selectCurrentMessageList } from '../modules/selectors';\nimport { hasStoredSession } from '../util/sessions';\nimport { INITIAL_STATE } from './initial';\nimport { parseLocationHash } from '../util/routing';\nimport { LOCATION_HASH } from '../hooks/useHistoryBack';\nimport { isUserId } from '../modules/helpers';\n\nconst UPDATE_THROTTLE = 5000;\n\nconst updateCacheThrottled = throttle(() => onIdle(updateCache), UPDATE_THROTTLE, false);\n\nlet isCaching = false;\nlet isHeavyAnimating = false;\nlet unsubscribeFromBeforeUnload: NoneToVoidFunction | undefined;\n\nsetupHeavyAnimationListeners();\n\nexport function initCache() {\n if (GLOBAL_STATE_CACHE_DISABLED) {\n return;\n }\n\n addReducer('saveSession', () => {\n if (isCaching) {\n return;\n }\n\n setupCaching();\n });\n\n addReducer('reset', () => {\n localStorage.removeItem(GLOBAL_STATE_CACHE_KEY);\n\n if (!isCaching) {\n return;\n }\n\n clearCaching();\n });\n}\n\nexport function loadCache(initialState: GlobalState): GlobalState | undefined {\n if (GLOBAL_STATE_CACHE_DISABLED) {\n return undefined;\n }\n\n if (hasStoredSession(true)) {\n setupCaching();\n\n return readCache(initialState);\n } else {\n clearCaching();\n\n return undefined;\n }\n}\n\nfunction setupCaching() {\n isCaching = true;\n unsubscribeFromBeforeUnload = onBeforeUnload(updateCache, true);\n window.addEventListener('blur', updateCache);\n addCallback(updateCacheThrottled);\n}\n\nfunction clearCaching() {\n isCaching = false;\n removeCallback(updateCacheThrottled);\n window.removeEventListener('blur', updateCache);\n if (unsubscribeFromBeforeUnload) {\n unsubscribeFromBeforeUnload();\n }\n}\n\nfunction readCache(initialState: GlobalState): GlobalState {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.time('global-state-cache-read');\n }\n\n const json = localStorage.getItem(GLOBAL_STATE_CACHE_KEY);\n const cached = json ? JSON.parse(json) as GlobalState : undefined;\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.timeEnd('global-state-cache-read');\n }\n\n if (cached) {\n migrateCache(cached, initialState);\n }\n\n const newState = {\n ...initialState,\n ...cached,\n };\n\n const parsedMessageList = !IS_SINGLE_COLUMN_LAYOUT ? parseLocationHash(LOCATION_HASH) : undefined;\n\n return {\n ...newState,\n messages: {\n ...newState.messages,\n messageLists: parsedMessageList ? [parsedMessageList] : [],\n },\n };\n}\n\nfunction migrateCache(cached: GlobalState, initialState: GlobalState) {\n if ('shouldAutoDownloadMediaFromContacts' in cached.settings.byKey) {\n const {\n shouldAutoDownloadMediaFromContacts,\n shouldAutoDownloadMediaInPrivateChats,\n shouldAutoDownloadMediaInGroups,\n shouldAutoDownloadMediaInChannels,\n shouldAutoPlayVideos,\n shouldAutoPlayGifs,\n ...rest\n } = cached.settings.byKey;\n\n cached.settings.byKey = {\n ...rest,\n canAutoLoadPhotoFromContacts: shouldAutoDownloadMediaFromContacts,\n canAutoLoadVideoFromContacts: shouldAutoDownloadMediaFromContacts,\n canAutoLoadPhotoInPrivateChats: shouldAutoDownloadMediaInPrivateChats,\n canAutoLoadVideoInPrivateChats: shouldAutoDownloadMediaInPrivateChats,\n canAutoLoadPhotoInGroups: shouldAutoDownloadMediaInGroups,\n canAutoLoadVideoInGroups: shouldAutoDownloadMediaInGroups,\n canAutoLoadPhotoInChannels: shouldAutoDownloadMediaInChannels,\n canAutoLoadVideoInChannels: shouldAutoDownloadMediaInChannels,\n canAutoPlayVideos: shouldAutoPlayVideos,\n canAutoPlayGifs: shouldAutoPlayGifs,\n };\n }\n\n cached.settings.byKey = {\n ...initialState.settings.byKey,\n ...cached.settings.byKey,\n };\n\n cached.settings.themes = {\n ...initialState.settings.themes,\n ...cached.settings.themes,\n };\n\n cached.chatFolders = {\n ...initialState.chatFolders,\n ...cached.chatFolders,\n };\n\n if (!cached.stickers.greeting) {\n cached.stickers.greeting = initialState.stickers.greeting;\n }\n\n if (!cached.activeDownloads) {\n cached.activeDownloads = {\n byChatId: {},\n };\n }\n\n if (!cached.serviceNotifications) {\n cached.serviceNotifications = [];\n }\n\n if (cached.audioPlayer.volume === undefined) {\n cached.audioPlayer.volume = DEFAULT_VOLUME;\n }\n\n if (cached.audioPlayer.playbackRate === undefined) {\n cached.audioPlayer.playbackRate = DEFAULT_PLAYBACK_RATE;\n }\n}\n\nfunction updateCache() {\n if (!isCaching || isHeavyAnimating) {\n return;\n }\n\n const global = getGlobal();\n\n if (global.isLoggingOut) {\n return;\n }\n\n const reducedGlobal: GlobalState = {\n ...INITIAL_STATE,\n ...pick(global, [\n 'authState',\n 'authPhoneNumber',\n 'authRememberMe',\n 'authNearestCountry',\n 'currentUserId',\n 'contactList',\n 'topPeers',\n 'topInlineBots',\n 'recentEmojis',\n 'push',\n 'shouldShowContextMenuHint',\n 'leftColumnWidth',\n 'serviceNotifications',\n ]),\n audioPlayer: {\n volume: global.audioPlayer.volume,\n playbackRate: global.audioPlayer.playbackRate,\n isMuted: global.audioPlayer.isMuted,\n },\n isChatInfoShown: reduceShowChatInfo(global),\n users: reduceUsers(global),\n chats: reduceChats(global),\n messages: reduceMessages(global),\n globalSearch: {\n recentlyFoundChatIds: global.globalSearch.recentlyFoundChatIds,\n },\n settings: reduceSettings(global),\n chatFolders: reduceChatFolders(global),\n };\n\n const json = JSON.stringify(reducedGlobal);\n localStorage.setItem(GLOBAL_STATE_CACHE_KEY, json);\n}\n\nfunction reduceShowChatInfo(global: GlobalState): boolean {\n return window.innerWidth > MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN\n ? global.isChatInfoShown\n : false;\n}\n\nfunction reduceUsers(global: GlobalState): GlobalState['users'] {\n const { users: { byId, selectedId } } = global;\n const idsToSave = [\n ...(global.chats.listIds.active || []).slice(0, GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT).filter(isUserId),\n ...Object.keys(byId),\n ].slice(0, GLOBAL_STATE_CACHE_USER_LIST_LIMIT);\n\n return {\n byId: pick(byId, idsToSave),\n selectedId: window.innerWidth > MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN ? selectedId : undefined,\n };\n}\n\nfunction reduceChats(global: GlobalState): GlobalState['chats'] {\n const chatIdsToSave = [\n ...(global.chats.listIds.active || []).slice(0, GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT),\n ];\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n\n return {\n ...global.chats,\n byId: pick(global.chats.byId, currentChatId ? [...chatIdsToSave, currentChatId] : chatIdsToSave),\n listIds: {\n active: chatIdsToSave,\n },\n isFullyLoaded: {},\n orderedPinnedIds: {\n active: global.chats.orderedPinnedIds.active,\n },\n };\n}\n\nfunction reduceMessages(global: GlobalState): GlobalState['messages'] {\n const byChatId: GlobalState['messages']['byChatId'] = {};\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n\n const chatIdsToSave = [\n ...(global.chats.listIds.active || []).slice(0, GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT),\n ...(currentChatId ? [currentChatId] : []),\n ];\n chatIdsToSave.forEach((chatId) => {\n const current = global.messages.byChatId[chatId];\n if (!current) {\n return;\n }\n\n const mainThread = current.threadsById[MAIN_THREAD_ID];\n if (!mainThread || !mainThread.viewportIds) {\n return;\n }\n\n byChatId[chatId] = {\n byId: pick(current.byId, mainThread.viewportIds),\n threadsById: {\n [MAIN_THREAD_ID]: mainThread,\n },\n };\n });\n\n return {\n byChatId,\n messageLists: [],\n };\n}\n\nfunction reduceSettings(global: GlobalState): GlobalState['settings'] {\n const { byKey, themes } = global.settings;\n\n return {\n byKey,\n themes,\n privacy: {},\n notifyExceptions: {},\n };\n}\n\nfunction reduceChatFolders(global: GlobalState): GlobalState['chatFolders'] {\n return {\n ...global.chatFolders,\n activeChatFolder: 0,\n };\n}\n\nfunction setupHeavyAnimationListeners() {\n document.addEventListener(ANIMATION_START_EVENT, () => {\n isHeavyAnimating = true;\n });\n document.addEventListener(ANIMATION_END_EVENT, () => {\n isHeavyAnimating = false;\n });\n}\n","import { addReducer } from '../lib/teact/teactn';\n\nimport { INITIAL_STATE } from './initial';\nimport { initCache, loadCache } from './cache';\nimport { cloneDeep } from '../util/iteratees';\n\ninitCache();\n\naddReducer('init', () => {\n const initial = cloneDeep(INITIAL_STATE);\n return loadCache(initial) || initial;\n});\n","const STORAGE_KEY = 'tt-active-tab';\nconst INTERVAL = 2000;\n\nconst tabKey = String(Date.now() + Math.random());\n\nlocalStorage.setItem(STORAGE_KEY, tabKey);\n\nlet callback: NoneToVoidFunction;\n\nconst interval = window.setInterval(() => {\n if (callback && localStorage.getItem(STORAGE_KEY) !== tabKey) {\n callback();\n clearInterval(interval);\n }\n}, INTERVAL);\n\nexport function addActiveTabChangeListener(_callback: NoneToVoidFunction) {\n callback = _callback;\n}\n","const SITE_FONTS = ['400 1em Roboto', '500 1em Roboto'];\n\nexport default function preloadFonts() {\n if ('fonts' in document) {\n return Promise.all(SITE_FONTS.map((font) => document.fonts.load(font)));\n }\n\n return undefined;\n}\n","import React, { FC, useEffect } from '../../lib/teact/teact';\nimport { getGlobal, withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiMediaFormat } from '../../api/types';\nimport { GlobalActions, GlobalState } from '../../global/types';\n\nimport { getChatAvatarHash } from '../../modules/helpers/chats'; // Direct import for better module splitting\nimport useFlag from '../../hooks/useFlag';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport { pause } from '../../util/schedulers';\nimport { preloadImage } from '../../util/files';\nimport preloadFonts from '../../util/fonts';\nimport * as mediaLoader from '../../util/mediaLoader';\nimport { Bundles, loadModule } from '../../util/moduleLoader';\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\n\nimport './UiLoader.scss';\n\n// @ts-ignore\nimport telegramLogoPath from '../../assets/telegram-logo.svg';\n// @ts-ignore\nimport monkeyPath from '../../assets/monkey.svg';\nimport { selectIsRightColumnShown, selectTheme } from '../../modules/selectors';\n\ntype OwnProps = {\n page: 'main' | 'authCode' | 'authPassword' | 'authPhoneNumber' | 'authQrCode';\n children: any;\n};\n\ntype StateProps = Pick & {\n hasCustomBackground?: boolean;\n hasCustomBackgroundColor: boolean;\n isRightColumnShown?: boolean;\n leftColumnWidth?: number;\n};\n\ntype DispatchProps = Pick;\n\nconst MAX_PRELOAD_DELAY = 700;\nconst SECOND_STATE_DELAY = 1000;\nconst AVATARS_TO_PRELOAD = 10;\n\nfunction preloadAvatars() {\n const { listIds, byId } = getGlobal().chats;\n if (!listIds.active) {\n return undefined;\n }\n\n return Promise.all(listIds.active.slice(0, AVATARS_TO_PRELOAD).map((chatId) => {\n const chat = byId[chatId];\n if (!chat) {\n return undefined;\n }\n\n const avatarHash = getChatAvatarHash(chat);\n if (!avatarHash) {\n return undefined;\n }\n\n return mediaLoader.fetch(avatarHash, ApiMediaFormat.BlobUrl);\n }));\n}\n\nconst preloadTasks = {\n main: () => Promise.all([\n loadModule(Bundles.Main, 'Main')\n .then(preloadFonts),\n preloadAvatars(),\n ]),\n authPhoneNumber: () => Promise.all([\n preloadFonts(),\n preloadImage(telegramLogoPath),\n ]),\n authCode: () => preloadImage(monkeyPath),\n authPassword: () => preloadImage(monkeyPath),\n authQrCode: preloadFonts,\n};\n\nconst UiLoader: FC = ({\n page,\n children,\n hasCustomBackground,\n hasCustomBackgroundColor,\n isRightColumnShown,\n shouldSkipHistoryAnimations,\n leftColumnWidth,\n setIsUiReady,\n}) => {\n const [isReady, markReady] = useFlag();\n const {\n shouldRender: shouldRenderMask, transitionClassNames,\n } = useShowTransition(!isReady, undefined, true);\n\n useEffect(() => {\n let timeout: number | undefined;\n\n const safePreload = async () => {\n try {\n await preloadTasks[page]();\n } catch (err) {\n // Do nothing\n }\n };\n\n Promise.race([\n pause(MAX_PRELOAD_DELAY),\n safePreload(),\n ]).then(() => {\n markReady();\n setIsUiReady({ uiReadyState: 1 });\n\n timeout = window.setTimeout(() => {\n setIsUiReady({ uiReadyState: 2 });\n }, SECOND_STATE_DELAY);\n });\n\n return () => {\n if (timeout) {\n clearTimeout(timeout);\n timeout = undefined;\n }\n\n setIsUiReady({ uiReadyState: 0 });\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n return (\n

\n {children}\n {shouldRenderMask && !shouldSkipHistoryAnimations && (\n
\n {page === 'main' ? (\n <>\n \n \n {isRightColumnShown &&
}\n \n ) : (\n
\n )}\n
\n )}\n
\n );\n};\n\nexport default withGlobal(\n (global): StateProps => {\n const theme = selectTheme(global);\n const { background, backgroundColor } = global.settings.themes[theme] || {};\n\n return {\n shouldSkipHistoryAnimations: global.shouldSkipHistoryAnimations,\n uiReadyState: global.uiReadyState,\n hasCustomBackground: Boolean(background),\n hasCustomBackgroundColor: Boolean(backgroundColor),\n isRightColumnShown: selectIsRightColumnShown(global),\n leftColumnWidth: global.leftColumnWidth,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['setIsUiReady']),\n)(UiLoader);\n","import * as langProvider from '../util/langProvider';\nimport { useState } from '../lib/teact/teact';\n\nexport default (langCode: string | undefined, key: string): string | undefined => {\n const [translation, setTranslation] = useState();\n\n if (langCode) {\n langProvider\n .getTranslationForLangString(langCode, key)\n .then(setTranslation);\n }\n\n return translation;\n};\n","import { LangCode } from '../../../types';\n\nexport function getSuggestedLanguage() {\n let suggestedLanguage = navigator.language;\n\n if (suggestedLanguage && suggestedLanguage !== 'pt-br') {\n suggestedLanguage = suggestedLanguage.substr(0, 2);\n }\n\n return suggestedLanguage as LangCode;\n}\n","import React, {\n FC, useState, memo, useCallback, useRef,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiCountryCode } from '../../api/types';\n\nimport { ANIMATION_END_DELAY } from '../../config';\nimport searchWords from '../../util/searchWords';\nimport buildClassName from '../../util/buildClassName';\nimport renderText from '../common/helpers/renderText';\nimport useLang from '../../hooks/useLang';\nimport { isoToEmoji } from '../../util/emoji';\nimport useOnChange from '../../hooks/useOnChange';\n\nimport DropdownMenu from '../ui/DropdownMenu';\nimport MenuItem from '../ui/MenuItem';\nimport Spinner from '../ui/Spinner';\n\nimport './CountryCodeInput.scss';\n\ntype StateProps = {\n phoneCodeList: ApiCountryCode[];\n};\n\ntype OwnProps = {\n id: string;\n value?: ApiCountryCode;\n isLoading?: boolean;\n onChange: (value: ApiCountryCode) => void;\n};\n\nconst MENU_HIDING_DURATION = 200 + ANIMATION_END_DELAY;\nconst SELECT_TIMEOUT = 50;\n\nconst CountryCodeInput: FC = ({\n id,\n value,\n isLoading,\n onChange,\n phoneCodeList,\n}) => {\n const lang = useLang();\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef(null);\n\n const [filter, setFilter] = useState();\n const [filteredList, setFilteredList] = useState([]);\n\n const updateFilter = useCallback((filterValue?: string) => {\n setFilter(filterValue);\n setFilteredList(getFilteredList(phoneCodeList, filterValue));\n }, [phoneCodeList]);\n\n useOnChange(([prevPhoneCodeList]) => {\n if (prevPhoneCodeList?.length === 0 && phoneCodeList.length > 0) {\n updateFilter(filter);\n }\n }, [phoneCodeList, updateFilter]);\n\n const handleChange = useCallback((country: ApiCountryCode) => {\n onChange(country);\n\n setTimeout(() => updateFilter(undefined), MENU_HIDING_DURATION);\n }, [onChange, updateFilter]);\n\n const handleInput = useCallback((e: React.FormEvent) => {\n updateFilter(e.currentTarget.value);\n }, [updateFilter]);\n\n const handleInputKeyDown = useCallback((e: React.KeyboardEvent) => {\n if (e.keyCode !== 8) {\n return;\n }\n\n const target = e.currentTarget;\n if (value && filter === undefined) {\n target.value = '';\n }\n\n updateFilter(target.value);\n }, [filter, updateFilter, value]);\n\n const CodeInput: FC<{ onTrigger: () => void; isOpen?: boolean }> = ({ onTrigger, isOpen }) => {\n const handleTrigger = () => {\n if (isOpen) {\n return;\n }\n\n setTimeout(() => {\n inputRef.current!.select();\n }, SELECT_TIMEOUT);\n\n onTrigger();\n\n const formEl = document.getElementById('auth-phone-number-form')!;\n formEl.scrollTo({ top: formEl.scrollHeight, behavior: 'smooth' });\n };\n\n const handleCodeInput = (e: React.FormEvent) => {\n handleInput(e);\n handleTrigger();\n };\n\n const inputValue = filter ?? (value?.name || value?.defaultName || '');\n\n return (\n
\n \n \n {isLoading ? (\n \n ) : (\n \n )}\n
\n );\n };\n\n return (\n \n {filteredList\n .map((country: ApiCountryCode) => (\n handleChange(country)}\n >\n {renderText(isoToEmoji(country.iso2), ['hq_emoji'])}\n {country.name || country.defaultName}\n {country.countryCode}\n \n ))}\n {!filteredList.length && (\n \n {lang('lng_country_none')}\n \n )}\n \n );\n};\n\nfunction getFilteredList(countryList: ApiCountryCode[], filter = ''): ApiCountryCode[] {\n const filtered = filter.length\n ? countryList.filter((country) => (\n searchWords(country.defaultName, filter) || (country.name && searchWords(country.name, filter))\n )) : countryList;\n return filtered;\n}\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { countryList: { phoneCodes: phoneCodeList } } = global;\n return {\n phoneCodeList,\n };\n },\n)(CountryCodeInput));\n","import { ChangeEvent } from 'react';\n\n// @ts-ignore\nimport monkeyPath from '../../assets/monkey.svg';\n\nimport React, {\n FC, memo, useCallback, useEffect, useLayoutEffect, useRef, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions, GlobalState } from '../../global/types';\nimport { LangCode } from '../../types';\nimport { ApiCountryCode } from '../../api/types';\n\nimport { IS_SAFARI, IS_TOUCH_ENV } from '../../util/environment';\nimport { preloadImage } from '../../util/files';\nimport preloadFonts from '../../util/fonts';\nimport { pick } from '../../util/iteratees';\nimport { formatPhoneNumber, getCountryCodesByIso, getCountryFromPhoneNumber } from '../../util/phoneNumber';\nimport { setLanguage } from '../../util/langProvider';\nimport useLang from '../../hooks/useLang';\nimport useFlag from '../../hooks/useFlag';\nimport useLangString from '../../hooks/useLangString';\nimport { getSuggestedLanguage } from './helpers/getSuggestedLanguage';\n\nimport Button from '../ui/Button';\nimport Checkbox from '../ui/Checkbox';\nimport InputText from '../ui/InputText';\nimport Loading from '../ui/Loading';\nimport CountryCodeInput from './CountryCodeInput';\n\ntype StateProps = Pick & {\n language?: LangCode;\n phoneCodeList: ApiCountryCode[];\n};\ntype DispatchProps = Pick;\n\nconst MIN_NUMBER_LENGTH = 7;\n\nlet isPreloadInitiated = false;\n\nconst AuthPhoneNumber: FC = ({\n connectionState,\n authState,\n authPhoneNumber,\n authIsLoading,\n authIsLoadingQrCode,\n authError,\n authRememberMe,\n authNearestCountry,\n phoneCodeList,\n language,\n setAuthPhoneNumber,\n setAuthRememberMe,\n loadNearestCountry,\n loadCountryList,\n clearAuthError,\n goToAuthQrCode,\n setSettingOption,\n}) => {\n const lang = useLang();\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef(null);\n const suggestedLanguage = getSuggestedLanguage();\n\n const continueText = useLangString(suggestedLanguage, 'ContinueOnThisLanguage');\n const [country, setCountry] = useState();\n const [phoneNumber, setPhoneNumber] = useState();\n const [isTouched, setIsTouched] = useState(false);\n const [lastSelection, setLastSelection] = useState<[number, number] | undefined>();\n const [isLoading, markIsLoading, unmarkIsLoading] = useFlag();\n\n const fullNumber = country ? `+${country.countryCode} ${phoneNumber || ''}` : phoneNumber;\n const canSubmit = fullNumber && fullNumber.replace(/[^\\d]+/g, '').length >= MIN_NUMBER_LENGTH;\n\n useEffect(() => {\n if (!IS_TOUCH_ENV) {\n inputRef.current!.focus();\n }\n }, [country]);\n\n useEffect(() => {\n if (connectionState === 'connectionStateReady' && !authNearestCountry) {\n loadNearestCountry();\n }\n }, [connectionState, authNearestCountry, loadNearestCountry]);\n\n useEffect(() => {\n if (connectionState === 'connectionStateReady') {\n loadCountryList({ langCode: language });\n }\n }, [connectionState, language, loadCountryList]);\n\n useEffect(() => {\n if (authNearestCountry && phoneCodeList && !country && !isTouched) {\n setCountry(getCountryCodesByIso(phoneCodeList, authNearestCountry)[0]);\n }\n }, [country, authNearestCountry, isTouched, phoneCodeList]);\n\n const parseFullNumber = useCallback((newFullNumber: string) => {\n if (!newFullNumber.length) {\n setPhoneNumber('');\n }\n\n const suggestedCountry = phoneCodeList && getCountryFromPhoneNumber(phoneCodeList, newFullNumber);\n\n // Any phone numbers should be allowed, in some cases ignoring formatting\n const selectedCountry = !country\n || (suggestedCountry && suggestedCountry.iso2 !== country.iso2)\n || (!suggestedCountry && newFullNumber.length)\n ? suggestedCountry\n : country;\n\n if (!country || !selectedCountry || (selectedCountry && selectedCountry.iso2 !== country.iso2)) {\n setCountry(selectedCountry);\n }\n setPhoneNumber(formatPhoneNumber(newFullNumber, selectedCountry));\n }, [phoneCodeList, country]);\n\n const handleLangChange = useCallback(() => {\n markIsLoading();\n\n void setLanguage(suggestedLanguage, () => {\n unmarkIsLoading();\n\n setSettingOption({ language: suggestedLanguage });\n });\n }, [markIsLoading, setSettingOption, suggestedLanguage, unmarkIsLoading]);\n\n useEffect(() => {\n if (phoneNumber === undefined && authPhoneNumber) {\n parseFullNumber(authPhoneNumber);\n }\n }, [authPhoneNumber, phoneNumber, parseFullNumber]);\n\n useLayoutEffect(() => {\n if (inputRef.current && lastSelection) {\n inputRef.current.setSelectionRange(...lastSelection);\n }\n }, [lastSelection]);\n\n const isJustPastedRef = useRef(false);\n const handlePaste = useCallback(() => {\n isJustPastedRef.current = true;\n requestAnimationFrame(() => {\n isJustPastedRef.current = false;\n });\n }, []);\n\n const handleCountryChange = useCallback((value: ApiCountryCode) => {\n setCountry(value);\n setPhoneNumber('');\n }, []);\n\n const handlePhoneNumberChange = useCallback((e: ChangeEvent) => {\n if (authError) {\n clearAuthError();\n }\n\n // This is for further screens. We delay it until user input to speed up the initial loading.\n if (!isPreloadInitiated) {\n isPreloadInitiated = true;\n preloadFonts();\n void preloadImage(monkeyPath);\n }\n\n const { value, selectionStart, selectionEnd } = e.target;\n setLastSelection(\n selectionStart && selectionEnd && selectionEnd < value.length\n ? [selectionStart, selectionEnd]\n : undefined,\n );\n\n setIsTouched(true);\n\n const shouldFixSafariAutoComplete = (\n IS_SAFARI && country && fullNumber !== undefined\n && value.length - fullNumber.length > 1 && !isJustPastedRef.current\n );\n parseFullNumber(shouldFixSafariAutoComplete ? `${country!.countryCode} ${value}` : value);\n }, [authError, clearAuthError, country, fullNumber, parseFullNumber]);\n\n const handleKeepSessionChange = useCallback((e: ChangeEvent) => {\n setAuthRememberMe(e.target.checked);\n }, [setAuthRememberMe]);\n\n function handleSubmit(event: React.FormEvent) {\n event.preventDefault();\n\n if (authIsLoading) {\n return;\n }\n\n if (canSubmit) {\n setAuthPhoneNumber({ phoneNumber: fullNumber });\n }\n }\n\n const isAuthReady = authState === 'authorizationStateWaitPhoneNumber';\n\n return (\n
\n
\n
\n

Telegram

\n

{lang('StartText')}

\n
\n \n \n \n {canSubmit && (\n isAuthReady ? (\n \n ) : (\n \n )\n )}\n {isAuthReady && (\n \n )}\n {suggestedLanguage && suggestedLanguage !== language && continueText && (\n \n )}\n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n settings: { byKey: { language } },\n countryList: { phoneCodes: phoneCodeList },\n } = global;\n\n return {\n ...pick(global, [\n 'connectionState',\n 'authState',\n 'authPhoneNumber',\n 'authIsLoading',\n 'authIsLoadingQrCode',\n 'authError',\n 'authRememberMe',\n 'authNearestCountry',\n ]),\n language,\n phoneCodeList,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'setAuthPhoneNumber',\n 'setAuthRememberMe',\n 'clearAuthError',\n 'loadNearestCountry',\n 'loadCountryList',\n 'goToAuthQrCode',\n 'setSettingOption',\n ]),\n)(AuthPhoneNumber));\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst AuthCodeAsync: FC = () => {\n const AuthCode = useModuleLoader(Bundles.Auth, 'AuthCode');\n\n return AuthCode ? : ;\n};\n\nexport default memo(AuthCodeAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst AuthPasswordAsync: FC = () => {\n const AuthPassword = useModuleLoader(Bundles.Auth, 'AuthPassword');\n\n return AuthPassword ? : ;\n};\n\nexport default memo(AuthPasswordAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst AuthRegisterAsync: FC = () => {\n const AuthRegister = useModuleLoader(Bundles.Auth, 'AuthRegister');\n\n return AuthRegister ? : ;\n};\n\nexport default memo(AuthRegisterAsync);\n","/*\n jquery-qrcode v0.14.0 - https://larsjung.de/jquery-qrcode/ */\n'use strict';let G=null;class H{}H.render=function(w,B){G(w,B)};self.QrCreator=H;\n(function(w){function B(t,c,a,e){var b={},h=w(a,c);h.u(t);h.J();e=e||0;var r=h.h(),d=h.h()+2*e;b.text=t;b.level=c;b.version=a;b.O=d;b.a=function(b,a){b-=e;a-=e;return 0>b||b>=r||0>a||a>=r?!1:h.a(b,a)};return b}function C(t,c,a,e,b,h,r,d,g,x){function u(b,a,f,c,d,r,g){b?(t.lineTo(a+r,f+g),t.arcTo(a,f,c,d,h)):t.lineTo(a,f)}r?t.moveTo(c+h,a):t.moveTo(c,a);u(d,e,a,e,b,-h,0);u(g,e,b,c,b,0,-h);u(x,c,b,c,a,h,0);u(r,c,a,e,a,0,h)}function z(t,c,a,e,b,h,r,d,g,x){function u(b,a,c,d){t.moveTo(b+c,a);t.lineTo(b,\na);t.lineTo(b,a+d);t.arcTo(b,a,b+c,a,h)}r&&u(c,a,h,h);d&&u(e,a,-h,h);g&&u(e,b,-h,-h);x&&u(c,b,h,-h)}function A(t,c){var a=c.fill;if(\"string\"===typeof a)t.fillStyle=a;else{var e=a.type,b=a.colorStops;a=a.position.map((b)=>Math.round(b*c.size));if(\"linear-gradient\"===e)var h=t.createLinearGradient.apply(t,a);else if(\"radial-gradient\"===e)h=t.createRadialGradient.apply(t,a);else throw Error(\"Unsupported fill\");b.forEach(([b,a])=>{h.addColorStop(b,a)});t.fillStyle=h}}function y(t,c){a:{var a=c.text,e=\nc.v,b=c.N,h=c.K,r=c.P;b=Math.max(1,b||1);for(h=Math.min(40,h||40);b<=h;b+=1)try{var d=B(a,e,b,r);break a}catch(J){}d=void 0}if(!d)return null;a=t.getContext(\"2d\");c.background&&(a.fillStyle=c.background,a.fillRect(c.left,c.top,c.size,c.size));e=d.O;h=c.size/e;a.beginPath();for(r=0;r>>7-b%8&1)},put:function(b,h){for(var a=0;a>>h-a-1&1))},f:function(){return a},m:function(b){var h=Math.floor(a/8);c.length<=h&&c.push(0);b&&(c[h]|=128>>>a%8);a+=1}};return e}function C(c,a){function e(b,h){for(var a=-1;7>=a;a+=1)if(!(-1>=b+a||d<=b+a))for(var c=-1;7>=c;c+=1)-1>=h+c||d<=h+c||(r[b+a][h+c]=0<=a&&6>=a&&(0==c||6==c)||0<=c&&6>=c&&(0==a||6==a)||2<=a&&4>=a&&2<=c&&4>=c?!0:!1)}function b(b,a){for(var f=d=4*c+17,k=Array(f),m=0;m<\nf;m+=1){k[m]=Array(f);for(var p=0;p=n;n+=1)for(var l=-2;2>=l;l+=1)r[p+n][q+l]=-2==n||2==n||-2==l||2==l||0==n&&0==l}for(f=8;fk;k+=1)m=!b&&1==(f>>k&1),r[6>k?k:8>k?k+1:d-15+k][8]=m,r[8][8>k?d-k-1:9>k?15-k:14-k]=m;r[d-8][8]=!b;if(7<=\nc){f=y.A(c);for(k=0;18>k;k+=1)m=!b&&1==(f>>k&1),r[Math.floor(k/3)][k%3+d-8-3]=m;for(k=0;18>k;k+=1)m=!b&&1==(f>>k&1),r[k%3+d-8-3][Math.floor(k/3)]=m}if(null==g){b=t.I(c,h);f=B();for(k=0;k8*m)throw Error(\"code length overflow. (\"+f.f()+\">\"+8*m+\")\");for(f.f()+4<=8*m&&f.put(0,4);0!=f.f()%8;)f.m(!1);for(;!(f.f()>=8*m);){f.put(236,8);if(f.f()>=8*m)break;f.put(17,8)}var u=0;m=k=0;p=Array(b.length);\nq=Array(b.length);for(n=0;nn;n+=1)null==r[k][q-n]&&(l=!1,p>>m&1)),a(k,q-n)&&(l=!l),r[k][q-n]=l,--m,-1==m&&(p+=1,m=7));k+=f;if(0>k||d<=k){k-=f;f=-f;break}}}var h=A[a],r=null,d=0,g=null,x=[],u={u:function(b){b=w(b);x.push(b);g=null},a:function(b,a){if(0>b||d<=b||0>a||d<=a)throw Error(b+\",\"+a);return r[b][a]},h:function(){return d},J:function(){for(var a=0,h=0,c=0;8>c;c+=1){b(!0,c);var d=y.D(u);if(0==c||a>d)a=d,h=c}b(!1,h)}};return u}\nfunction z(c,a){if(\"undefined\"==typeof c.length)throw Error(c.length+\"/\"+a);var e=function(){for(var b=0;bb.b()-a.b())return b;for(var c=v.g(b.c(0))-v.g(a.c(0)),h=Array(b.b()),\ng=0;gb?a.push(b):2048>b?a.push(192|b>>6,128|b&63):55296>b||57344<=b?a.push(224|b>>12,128|b>>6&63,128|b&63):(e++,b=65536+((b&1023)<<10|c.charCodeAt(e)&1023),a.push(240|b>>18,128|b>>12&63,128|b>>6&63,128|b&63))}return a};var A={L:1,M:0,Q:3,H:2},y=function(){function c(b){for(var a=0;0!=b;)a+=1,b>>>=1;return a}var a=[[],[6,18],\n[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],\n[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],e={w:function(b){for(var a=b<<10;0<=c(a)-c(1335);)a^=1335<a||40a?8:16},D:function(b){for(var a=b.h(),c=0,\nd=0;d=p;p+=1)if(!(0>d+p||a<=d+p))for(var q=-1;1>=q;q+=1)0>g+q||a<=g+q||(0!=p||0!=q)&&t==b.a(d+p,g+q)&&(e+=1);5e;e+=1)c[e]=1<e;e+=1)c[e]=c[e-4]^c[e-5]^c[e-6]^c[e-8];for(e=0;255>e;e+=1)a[c[e]]=e;return{g:function(b){if(1>b)throw Error(\"glog(\"+b+\")\");return a[b]},i:function(b){for(;0>b;)b+=255;for(;256<=b;)b-=255;return c[b]}}}(),t=function(){function c(b,c){switch(c){case A.L:return a[4*\n(b-1)];case A.M:return a[4*(b-1)+1];case A.Q:return a[4*(b-1)+2];case A.H:return a[4*(b-1)+3]}}var a=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,\n2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12,7,37,13],[5,122,98,1,123,99],[7,73,\n45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,\n151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],\n[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],\n[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]],e={I:function(b,a){var e=c(b,a);if(\"undefined\"==\ntypeof e)throw Error(\"bad rs block @ typeNumber:\"+b+\"/errorCorrectLevel:\"+a);b=e.length/3;a=[];for(var d=0;d & {\n language?: LangCode;\n};\ntype DispatchProps = Pick;\n\nconst DATA_PREFIX = 'tg://login?token=';\n\nconst AuthCode: FC = ({\n connectionState,\n authState,\n authQrCode,\n language,\n returnToAuthPhoneNumber,\n setSettingOption,\n}) => {\n const suggestedLanguage = getSuggestedLanguage();\n const lang = useLang();\n // eslint-disable-next-line no-null/no-null\n const qrCodeRef = useRef(null);\n const continueText = useLangString(suggestedLanguage, 'ContinueOnThisLanguage');\n const [isLoading, markIsLoading, unmarkIsLoading] = useFlag();\n\n useEffect(() => {\n if (!authQrCode || connectionState !== 'connectionStateReady') {\n return;\n }\n\n const container = qrCodeRef.current!;\n\n container.innerHTML = '';\n container.classList.remove('pre-animate');\n\n QrCreator.render({\n text: `${DATA_PREFIX}${authQrCode.token}`,\n radius: 0.5,\n ecLevel: 'M',\n fill: '#4E96D4',\n size: 280,\n }, container);\n }, [connectionState, authQrCode]);\n\n const handleLangChange = useCallback(() => {\n markIsLoading();\n\n void setLanguage(suggestedLanguage, () => {\n unmarkIsLoading();\n\n setSettingOption({ language: suggestedLanguage });\n });\n }, [markIsLoading, setSettingOption, suggestedLanguage, unmarkIsLoading]);\n\n const isAuthReady = authState === 'authorizationStateWaitQrCode';\n\n return (\n
\n
\n {authQrCode ? (\n
\n ) : (\n
\n )}\n

{lang('Login.QR.Title')}

\n
    \n
  1. {lang('Login.QR.Help1')}
  2. \n
  3. {renderText(lang('Login.QR.Help2'), ['simple_markdown'])}
  4. \n
  5. {lang('Login.QR.Help3')}
  6. \n
\n {isAuthReady && (\n \n )}\n {suggestedLanguage && suggestedLanguage !== language && continueText && (\n \n )}\n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n connectionState, authState, authQrCode, settings: { byKey: { language } },\n } = global;\n\n return {\n connectionState,\n authState,\n authQrCode,\n language,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'returnToAuthPhoneNumber', 'setSettingOption',\n ]),\n)(AuthCode));\n","import React, { FC, useEffect, memo } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions, GlobalState } from '../../global/types';\n\nimport '../../modules/actions/initial';\nimport { pick } from '../../util/iteratees';\nimport { PLATFORM_ENV } from '../../util/environment';\nimport windowSize from '../../util/windowSize';\nimport useHistoryBack from '../../hooks/useHistoryBack';\n\nimport UiLoader from '../common/UiLoader';\nimport AuthPhoneNumber from './AuthPhoneNumber';\nimport AuthCode from './AuthCode.async';\nimport AuthPassword from './AuthPassword.async';\nimport AuthRegister from './AuthRegister.async';\nimport AuthQrCode from './AuthQrCode';\n\nimport './Auth.scss';\n\ntype StateProps = Pick;\ntype DispatchProps = Pick;\n\nconst Auth: FC = ({\n authState, reset, initApi, returnToAuthPhoneNumber, goToAuthQrCode,\n}) => {\n useEffect(() => {\n reset();\n initApi();\n }, [reset, initApi]);\n\n const isMobile = PLATFORM_ENV === 'iOS' || PLATFORM_ENV === 'Android';\n\n const handleChangeAuthorizationMethod = () => {\n if (!isMobile) {\n goToAuthQrCode();\n } else {\n returnToAuthPhoneNumber();\n }\n };\n\n useHistoryBack(\n (!isMobile && authState === 'authorizationStateWaitPhoneNumber')\n || (isMobile && authState === 'authorizationStateWaitQrCode'), handleChangeAuthorizationMethod,\n );\n\n // Prevent refresh when rotating device\n useEffect(() => {\n windowSize.disableRefresh();\n\n return () => {\n windowSize.enableRefresh();\n };\n }, []);\n\n switch (authState) {\n case 'authorizationStateWaitCode':\n return ;\n case 'authorizationStateWaitPassword':\n return ;\n case 'authorizationStateWaitRegistration':\n return ;\n case 'authorizationStateWaitPhoneNumber':\n return ;\n case 'authorizationStateWaitQrCode':\n return ;\n default:\n return isMobile\n ? \n : ;\n }\n};\n\nexport default memo(withGlobal(\n (global): StateProps => pick(global, ['authState']),\n (global, actions): DispatchProps => pick(actions, ['reset', 'initApi', 'returnToAuthPhoneNumber', 'goToAuthQrCode']),\n)(Auth));\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst MainAsync: FC = () => {\n const Main = useModuleLoader(Bundles.Main, 'Main');\n\n return Main ?
: undefined;\n};\n\nexport default memo(MainAsync);\n","import React, { FC } from '../../lib/teact/teact';\n\nimport Button from '../ui/Button';\n\nimport appInactivePath from '../../assets/app-inactive.png';\nimport './AppInactive.scss';\n\nconst AppInactive: FC = () => {\n const handleReload = () => {\n window.location.reload();\n };\n\n return (\n
\n
\n \"\"\n

Such error, many tabs

\n
\n Telegram supports only one active tab with the app.\n
\n Please reload this page to continue using this tab or close it.\n
\n
\n \n
\n
\n
\n );\n};\n\nexport default AppInactive;\n","import { FC, useEffect } from './lib/teact/teact';\nimport React, { withGlobal } from './lib/teact/teactn';\n\nimport { GlobalActions, GlobalState } from './global/types';\n\nimport { INACTIVE_MARKER, PAGE_TITLE } from './config';\nimport { pick } from './util/iteratees';\nimport { updateSizes } from './util/windowSize';\nimport { addActiveTabChangeListener } from './util/activeTabMonitor';\nimport useFlag from './hooks/useFlag';\n\nimport Auth from './components/auth/Auth';\nimport UiLoader from './components/common/UiLoader';\nimport Main from './components/main/Main.async';\nimport AppInactive from './components/main/AppInactive';\nimport { hasStoredSession } from './util/sessions';\n// import Test from './components/test/TestNoRedundancy';\n\ntype StateProps = Pick;\ntype DispatchProps = Pick;\n\nconst App: FC = ({ authState, disconnect }) => {\n const [isInactive, markInactive] = useFlag(false);\n\n useEffect(() => {\n updateSizes();\n addActiveTabChangeListener(() => {\n disconnect();\n document.title = `${PAGE_TITLE}${INACTIVE_MARKER}`;\n\n markInactive();\n });\n }, [disconnect, markInactive]);\n\n // return ;\n\n if (isInactive) {\n return ;\n }\n\n if (authState) {\n switch (authState) {\n case 'authorizationStateWaitPhoneNumber':\n case 'authorizationStateWaitCode':\n case 'authorizationStateWaitPassword':\n case 'authorizationStateWaitRegistration':\n case 'authorizationStateWaitQrCode':\n return ;\n case 'authorizationStateClosed':\n case 'authorizationStateClosing':\n case 'authorizationStateLoggingOut':\n case 'authorizationStateReady':\n return renderMain();\n }\n }\n\n return hasStoredSession(true) ? renderMain() : ;\n};\n\nfunction renderMain() {\n return (\n \n
\n \n );\n}\n\nexport default withGlobal(\n (global): StateProps => pick(global, ['authState']),\n (setGlobal, actions): DispatchProps => pick(actions, ['disconnect']),\n)(App);\n","import './util/handleError';\nimport './util/setupServiceWorker';\n\nimport React, { getDispatch, getGlobal } from './lib/teact/teactn';\nimport TeactDOM from './lib/teact/teact-dom';\n\nimport './global';\n\nimport { DEBUG } from './config';\n\nimport App from './App';\n\nimport './styles/index.scss';\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> INIT');\n}\n\ngetDispatch().init();\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START INITIAL RENDER');\n}\n\nTeactDOM.render(\n ,\n document.getElementById('root'),\n);\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH INITIAL RENDER');\n}\n\ndocument.addEventListener('dblclick', () => {\n // eslint-disable-next-line no-console\n console.warn('GLOBAL STATE', getGlobal());\n});\n"],"names":["leafPrototypes","getProto","inProgress","dataWebpackPrefix","loadStylesheet","installedCssChunks","worker","requestStates","Map","requestStatesByCallback","initApi","onUpdate","initialArgs","DEBUG","console","log","Worker","URL","addEventListener","data","type","update","requestState","get","messageId","error","reject","resolve","response","callback","callbackArgs","subscribeToWorker","platform","window","async","Promise","race","makeRequest","pause","then","Error","err","Date","now","startedAt","location","reload","args","callApi","fnName","name","warn","cancelApiProgress","progressCallback","isCanceled","postMessage","message","generateIdFor","payload","promise","Object","assign","pop","set","catch","finally","delete","ApiMediaFormat","ApiMessageEntityTypes","MAIN_THREAD_ID","MESSAGE_DELETED","base","maxint","adapt","delta","numpoints","firsttime","k","Math","floor","decode","input","preserveCase","output","case_flags","input_length","length","n","out","i","bias","basic","j","ic","oldi","w","digit","t","len","lastIndexOf","charCodeAt","RangeError","push","cp","splice","String","fromCharCode","toUpperCase","value","join","utf16","ensureProtocol","url","includes","getDomain","href","decodedHref","decodeURI","match","domain","replace","domain_array","split","s","slice","convertPunycode","memo","text","className","children","isRtl","toggleSafeLinkModal","openTelegramLink","getDispatch","content","isNotSafe","handleClick","useCallback","e","ctrlKey","altKey","shiftKey","metaKey","RE_TME_LINK","RE_TG_LINK","preventDefault","classNames","buildClassName","title","target","rel","onClick","dir","getFileSizeString","bytes","ONE_GIGABYTE","toFixed","ONE_MEGABYTE","getDocumentExtension","document","fileName","mimeType","getFileExtension","indexOf","getColorFromExtension","extension","getDocumentHasPreview","Boolean","previewBlobUrl","thumbnail","RE_EMOJI_ONLY","RegExp","twemojiRegex","DETECT_UP_TO","emojiCount","withGlobal","undefined","setGlobal","actions","pick","sender","openUserInfo","id","Link","focusMessage","handleMessageClick","chatId","openChat","renderActionMessageText","lang","actionOrigin","targetUsers","targetMessage","targetChatId","options","action","translationValues","amount","currency","textOptions","maxTextLength","processed","unprocessed","processPlaceholder","formatCurrency","code","isEmbedded","origin","asPlain","isUserId","renderUserContent","chat","trimText","getChatTitle","renderText","renderChatContent","renderOriginContent","map","user","filter","getMessageSummaryText","photo","video","sticker","getMessageContent","showQuotes","messageText","isGif","renderMessageContent","invoice","renderProductContent","renderMigratedContent","trim","getUserFullName","placeholder","replaceValue","placeholderPosition","substring","Array","isArray","forEach","index","RE_LETTER_OR_DIGIT","SIMPLE_MARKDOWN_REGEX","part","filters","params","reduce","textParts","divEl","createElement","result","innerText","innerHTML","escapeHtml","EMOJI_REGEX","replaceEmojis","addLineBreaks","highlight","lowerCaseText","toLowerCase","queryPosition","nextSymbol","newParts","links","RE_LINK","nextLink","shift","lastIndex","startsWith","username","endsWith","addLinks","replaceSimpleMarkdown","size","IS_EMOJI_SUPPORTED","parts","fixNonStandardEmoji","emojis","emojiResult","emoji","nativeToUnified","removeVS16s","src","alt","line","source","trimmedLine","trimLeft","indentLength","repeat","RE_LINK_TEMPLATE","RE_MENTION_TEMPLATE","entities","entityResult","entity","preventMessageInputBlur","withBubbling","IS_IOS","activeElement","EDITABLE_INPUT_ID","currentTarget","preventMessageInputBlurWithBubbling","global","userId","userOrChat","selectUser","openChatByUsername","ref","onContextMenu","onMouseDown","onMouseEnter","onMouseLeave","onFocus","color","backgroundImage","round","pill","fluid","isText","isLoading","ariaLabel","download","disabled","ripple","faded","tabIndex","withClickPropagation","elementRef","useRef","isClicked","setIsClicked","useState","fullClassName","setTimeout","handleMouseDown","style","label","subLabel","checked","blocking","onChange","onCheck","useLang","handleChange","event","trigger","positionX","positionY","footer","forceOpen","onOpen","onClose","menuRef","dropdownRef","isOpen","setIsOpen","onKeyDown","menu","current","keyCode","focusedElement","elementChildren","from","focus","onTrigger","containerRef","autoClose","shouldSkipTransition","success","readOnly","autoComplete","inputMode","maxLength","onInput","onKeyPress","onBlur","onPaste","labelText","htmlFor","withBackground","menuStyle","noCloseOnBackdrop","onCloseAnimationEnd","backdropContainerRef","transitionClassNames","useShowTransition","useEffect","captureEscKeyListener","useHistoryBack","useEffectWithPrevDeps","prevIsOpen","dispatchHeavyAnimationEvent","handleKeyDown","useKeyboardListNavigation","useVirtualBackdrop","bubbleClassName","props","icon","destructive","stopPropagation","role","ripples","setRipples","cleanUpDebounced","useMemo","debounce","button","container","position","getBoundingClientRect","rippleSize","offsetWidth","x","clientX","y","clientY","requestAnimationFrame","PAGE_TITLE","INACTIVE_MARKER","APP_NAME","process","APP_VERSION","DEBUG_MORE","IS_TEST","DEBUG_ALERT_MSG","SESSION_USER_KEY","LEGACY_SESSION_KEY","GLOBAL_STATE_CACHE_DISABLED","GLOBAL_STATE_CACHE_KEY","GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT","GLOBAL_STATE_CACHE_USER_LIST_LIMIT","MEDIA_CACHE_DISABLED","MEDIA_CACHE_NAME","MEDIA_CACHE_NAME_AVATARS","MEDIA_PROGRESSIVE_CACHE_NAME","CUSTOM_BG_CACHE_NAME","LANG_CACHE_NAME","AUTODOWNLOAD_FILESIZE_MB_LIMITS","isBigScreen","innerHeight","MIN_PASSWORD_LENGTH","MESSAGE_LIST_SENSITIVE_AREA","MESSAGE_LIST_SLICE","MESSAGE_LIST_VIEWPORT_LIMIT","CHAT_HEIGHT_PX","CHAT_LIST_SLICE","CHAT_LIST_LOAD_SLICE","SHARED_MEDIA_SLICE","MESSAGE_SEARCH_SLICE","GLOBAL_SEARCH_SLICE","MEMBERS_SLICE","MEMBERS_LOAD_SLICE","PROFILE_SENSITIVE_AREA","TOP_CHAT_MESSAGES_PRELOAD_LIMIT","ALL_CHATS_PRELOAD_DISABLED","DEFAULT_VOLUME","DEFAULT_PLAYBACK_RATE","ANIMATION_LEVEL_MIN","ANIMATION_LEVEL_MAX","ANIMATION_LEVEL_DEFAULT","DEFAULT_MESSAGE_TEXT_SIZE_PX","IOS_DEFAULT_MESSAGE_TEXT_SIZE_PX","MACOS_DEFAULT_MESSAGE_TEXT_SIZE_PX","DRAFT_DEBOUNCE","EDITABLE_INPUT_MODAL_ID","SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN","SAFE_SCREEN_WIDTH_FOR_CHAT_INFO","MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN","MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN","MOBILE_SCREEN_MAX_WIDTH","MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH","MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT","LOCAL_MESSAGE_ID_BASE","TMP_CHAT_ID","ANIMATION_END_DELAY","FAST_SMOOTH_MAX_DISTANCE","FAST_SMOOTH_MIN_DURATION","FAST_SMOOTH_MAX_DURATION","FAST_SMOOTH_SHORT_TRANSITION_MAX_DISTANCE","STICKER_SIZE_INLINE_DESKTOP_FACTOR","Set","STICKER_SIZE_INLINE_MOBILE_FACTOR","STICKER_SIZE_AUTH","STICKER_SIZE_AUTH_MOBILE","STICKER_SIZE_PICKER","STICKER_SIZE_GENERAL_SETTINGS","STICKER_SIZE_PICKER_HEADER","STICKER_SIZE_SEARCH","STICKER_SIZE_MODAL","STICKER_SIZE_TWO_FA","STICKER_SIZE_DISCUSSION_GROUPS","STICKER_SIZE_FOLDER_SETTINGS","STICKER_SIZE_INLINE_BOT_RESULT","MEMOJI_STICKER_ID","BASE_EMOJI_KEYWORD_LANG","MENU_TRANSITION_DURATION","SLIDE_TRANSITION_DURATION","VIDEO_MOV_TYPE","SUPPORTED_IMAGE_CONTENT_TYPES","SUPPORTED_VIDEO_CONTENT_TYPES","CONTENT_TYPES_WITH_PREVIEW","COUNTRIES_WITH_12H_TIME_FORMAT","SERVICE_NOTIFICATIONS_USER_ID","REPLIES_USER_ID","ALL_FOLDER_ID","ARCHIVED_FOLDER_ID","MAX_MEDIA_FILES_FOR_ALBUM","MAX_ACTIVE_PINNED_CHATS","SCHEDULED_WHEN_ONLINE","DEFAULT_LANG_CODE","DEFAULT_LANG_PACK","LANG_PACKS","TIPS_USERNAME","LOCALIZED_TIPS","FEEDBACK_URL","LIGHT_THEME_BG_COLOR","DARK_THEME_BG_COLOR","DARK_THEME_PATTERN_COLOR","DEFAULT_PATTERN_COLOR","cb","dependencies","debugKey","prevDeps","usePrevious","initial","setValue","setTrigger","ANIMATION_START_EVENT","ANIMATION_END_EVENT","timeout","isAnimating","duration","dispatchEvent","Event","clearTimeout","handleAnimationStart","handleAnimationEnd","removeEventListener","LOCATION_HASH","hash","PATH_BASE","pathname","search","historyState","currentIndex","nextStateIndexToReplace","isHistoryAltered","isDisabled","isEdge","currentIndexes","disableHistoryBack","handleTouchEnd","isActive","onBack","onForward","currentState","shouldReplaceNext","hashes","indexRef","isForward","prevIsActive","isClosed","indexHashRef","prevHashes","isHashChangedFromEvent","isForceClose","prev","history","pushState","state","last","realDelta","indexLast","findIndex","l","go","replaceState","back","handlePopState","currIndex","disableHistoryAnimations","hasChanged","areSortedArraysEqual","forceClose","touches","pageX","innerWidth","onSelectWithEnter","itemSelector","noCaptureFocus","focusedIndex","setFocusedIndex","element","querySelectorAll","newIndex","item","forceUpdate","useForceUpdate","useOnChange","langProvider","bundleName","moduleName","noLoad","autoUpdate","module","getModuleFromMemory","addLoadListener","loadModule","some","d","next","shouldSkipUndefined","onCloseTransitionEnd","noOpenTransition","noCloseTransition","setIsClosed","closeTimeoutRef","hasOpenClassName","setHasOpenClassName","shouldHaveOpenClassName","isClosing","shouldRender","handleEvent","contains","classList","NON_BUBBLEABLE_EVENTS","delegationRegistry","delegatedEventsByElement","documentEventCounters","propName","handler","asCapture","eventName","resolveEventName","canUseEventDelegation","resolveDelegationRegistryForName","existing","newSet","resolveDelegatedEventsForElement","add","addDelegatedListener","removeDelegatedListener","tagName","realEventName","has","removeAllDelegatedListeners","eventNames","realEvent","events","furtherCallsPrevented","Proxy","p","Reflect","body","parentNode","FILTERED_ATTRIBUTES","HTML_ATTRIBUTES","MAPPED_ATTRIBUTES","autoPlay","headsByElement","renderWithVirtual","parentEl","$current","$new","$parent","skipComponentUpdate","forceIndex","fragment","moveDirection","isComponentElement","hasElementChanged","componentInstance","renderComponent","updateComponent","isMounted","setupComponentUpdateListener","initComponent","node","createNode","setTarget","childNodes","insertBefore","appendChild","removeChild","getTarget","unmountTree","replaceChild","areComponents","isRealElement","nextSibling","currentKeys","keys","newKeys","key","removeAttribute","addAttribute","oldValue","newValue","updateAttribute","updateAttributes","currentEl","teactFastList","$newChild","currentRemainingIndex","remainingByKey","acc","$currentChild","newChildKey","$element","order","teactOrderKey","fragmentQueue","fragmentIndex","newChildren","currentPreservedIndex","currentChildInfo","concat","flushFragmentQueue","shouldMoveNode","isMovingDown","renderFastListChildren","max","createDocumentFragment","renderChildren","mountComponent","$firstChild","isEmptyElement","createTextNode","isTextElement","tag","$child","$fragmentChild","cssText","setAttribute","render","headId","getAttribute","$head","VirtualElementTypesEnum","Fragment","Symbol","renderingInstance","Empty","Text","isTagElement","Tag","Component","flatten","parsedChildren","hooks","cursor","byCursor","effects","memos","buildComponentElement","createComponentInstance","dropEmptyTail","buildChildElement","buildTagElement","isEmptyPlaceholder","child","DEBUG_components","newRenderedValue","DEBUG_startAt","componentName","renderCount","renderTimes","performance","renderTime","handleError","renderedValue","newChild","$old","hook","cleanup","effect","nextValue","setter","helpGc","prepareComponentForFrame","prepareForFrame","throttleWithPrimaryRaf","throttleWithRaf","forceUpdateComponent","currentElement","DEBUG_contentComponentName","useLayoutEffectBase","schedulerFn","primarySchedulerFn","execCleanup","exec","dependency","causedBy","res","prevValue","fastRaf","fastRafPrimary","useLayoutEffect","onTickEnd","onTickEndPrimary","resolver","getUnequalProps","newCallback","areEqual","arePropsShallowEqual","propsRef","renderedRef","orderBy","values","React","currentGlobal","reducers","callbacks","containers","mapStateToProps","mapReducersToProps","ownProps","mappedProps","newMappedProps","Number","isNaN","DEBUG_componentName","areMappedPropsChanged","DEBUG_updates","updateTime","runCallbacks","runCallbacksThrottled","newGlobal","noThrottle","getGlobal","addReducer","reducer","onDispatch","addCallback","removeCallback","TeactNContainer","vs16RegExp","zeroWidthJoiner","rawEmoji","importLegacySession","clearLegacySessions","apiUpdate","userAgent","navigator","PLATFORM_ENV","sessionData","loadStoredSession","isTest","isMovSupported","IS_MOV_SUPPORTED","phoneNumber","authIsLoading","authError","password","file","firstName","lastName","authIsLoadingQrCode","storeSession","currentUserId","clearStoredSession","unsubscribe","forceWebsync","reset","cacheApi","langCachePrefix","langCacheVersion","updateAppBadge","init","connectionState","authNearestCountry","deviceToken","subscribedAt","buildInputPrivacyRules","visibility","allowedIds","deniedIds","users","byId","usersById","chats","chatsById","rules","collectUsers","accessHash","collectChats","allowedUsers","allowedChats","blockedUsers","blockedChats","bio","about","profileEdit","progress","ProfileEditProgress","currentUser","updateUser","fullInfo","isUsernameAvailable","settings","loadedWallpapers","wallpapers","createObjectURL","slug","UPLOADING_WALLPAPER_SLUG","wallpaper","firstWallpaper","withLocalMedia","addUsers","buildCollectionByKey","updateChats","blocked","ids","blockedIds","totalCount","contactId","addBlockedContact","removeBlockedContact","activeSessions","session","isCurrent","serverTimeOffset","addNotifyExceptions","replaceSettings","peerType","isSilent","shouldShowPreviews","updateNotifySettings","hasPushNotifications","hasWebNotifications","byKey","subscribe","hasContactJoinedNotifications","languages","phoneNumberSettings","lastSeenSettings","profilePhotoSettings","forwardsSettings","chatInviteSettings","all","privacy","lastSeen","profilePhoto","forwards","chatInvite","privacyKey","allowUserIds","allowChatIds","blockUserIds","blockChatIds","isAllowList","contactsIds","isSensitiveEnabled","langCode","language","countryList","timeFormat","setSettingOption","setTimeFormat","wasTimeFormatSetManually","nearestCountryCode","selectNotifySettings","setLanguage","onUpdateApiReady","wasAuthReady","authState","authorizationState","isLoggingOut","authIsCodeViaApp","isCodeViaApp","authHint","hint","authQrCode","qrCode","lastSyncTime","onUpdateAuthorizationState","onUpdateAuthorizationError","sync","signOut","onUpdateConnectionState","authRememberMe","isEmpty","mainDcId","saveSession","onUpdateSession","onUpdateServerTimeOffset","sessionUserAuth","localStorage","getItem","userAuth","JSON","parse","setItem","stringify","updateSessionUserId","onUpdateCurrentUser","paymentShippingError","getShippingError","addPaymentError","showDialog","hasErrorKey","handleSystemThemeChange","currentThemeMatch","documentElement","currentTheme","nextTheme","selectTheme","animationLevel","switchTheme","mql","matchMedia","addListener","subscribeToSystemThemeChange","messageTextSize","theme","setProperty","toString","IS_TOUCH_ENV","startWebsync","IS_ANDROID","IS_MAC_OS","uiReadyState","remove","authPhoneNumber","shouldSkipHistoryAnimations","replaceThemeSettings","FOREVER_BANNED_DATE","entityId","isChatGroup","isChatBasicGroup","isChatSuperGroup","isChatChannel","isCommonBoxChat","isChatWithRepliesBot","getChatTypeString","getPrivateChatUserId","isSelf","getChatDescription","getChatLink","inviteLink","getChatAvatarHash","owner","avatarHash","isChatSummaryOnly","lastMessage","isChatAdmin","adminRights","getHasAdminRight","isUserRightBanned","currentUserBannedRights","defaultBannedRights","getCanPostInChat","threadId","isRestricted","migratedTo","isNotJoined","isCreator","getAllowedAttachmentOptions","isChatWithBot","canAttachMedia","canAttachPolls","canSendStickers","canSendGifs","canAttachEmbedLinks","isAdmin","getMessageSendingRestrictionReason","sendMessages","untilDate","formatDateToString","formatTime","getChatSlowModeOptions","slowMode","getChatOrder","joinDate","draftDate","date","isChatArchived","folderId","selectIsChatMuted","notifySettings","notifyExceptions","isMuted","hasPrivateChatsNotifications","hasBroadcastNotifications","hasGroupNotifications","selectShouldShowMessagePreview","hasPrivateChatsMessagePreview","hasBroadcastMessagePreview","hasGroupMessagePreview","getCanDeleteChat","prepareFolderListIds","folder","chatIdsCache","excludedChatIds","includedChatIds","pinnedChatIds","isListed","excludeArchived","excludeMuted","unreadMentionsCount","unreadCount","hasUnreadMark","excludeRead","privateChatUser","bots","contacts","isContact","nonContacts","groups","channels","filterChatFolder","prepareChatList","listIds","orderedPinnedIds","folderType","chatFilter","listedChats","listIdsSet","pinnedChats","otherChats","getFolderUnreadDialogs","unreadDialogsCount","total","hasActiveDialogs","getFolderDescriptionText","emoticon","description","pinnedIds","getFolderChatsCount","getMessageSenderName","getUserFirstOrLastName","sortChatIds","chatIds","shouldPrioritizeVerified","priorityIds","priority","isVerified","CONTENT_NOT_SUPPORTED","getMessageKey","msgId","buildMessageKey","parseMessageKey","getMessageOriginalId","previousLocalId","noEmoji","audio","voice","contact","poll","truncatedText","substr","groupedId","performer","getMessageAudioCaption","summary","question","getMessageText","webPage","getMessageCustomShape","isRound","parseEmojiOnlyString","getMessageSingleEmoji","getFirstLinkInMessage","link","find","offset","isOwnMessage","isOutgoing","isReplyMessage","replyToMessageId","isForwardedMessage","forwardInfo","isActionMessage","isServiceNotificationMessage","isAnonymousOwnMessage","senderId","getSenderTitle","getSendingState","sendingState","isMessageLocal","isHistoryClearMessage","getMessageContentFilename","isAnimated","isWebpSupported","baseFilename","IS_OPUS_SUPPORTED","hasMessageMedia","getMessagePhoto","getMessageVideo","getMessageDocument","getMessageSticker","getMessageContact","getMessagePoll","getMessageAction","getMessageAudio","getMessageVoice","getMessageRoundVideo","isMessageDocumentPhoto","mediaType","isMessageDocumentVideo","getMessageInvoice","getMessageWebPage","getMessageWebPagePhoto","getMessageWebPageVideo","getMessageMediaThumbDataUri","media","getMessageMediaThumbnail","dataUri","getMessageMediaHash","webPagePhoto","webPageVideo","messageVideo","messagePhoto","hasMessageLocalBlobUrl","getVideoOrAudioBaseHash","getAudioHasCover","IS_PROGRESSIVE_SUPPORTED","IS_SAFARI","thumbnailSizes","getMessageMediaFormat","fullVideo","getMessageFileName","getMessageFileSize","blobUrl","getChatMediaMessageIds","messages","listedIds","isFromSharedMedia","getMessageContentIds","reverse","getPhotoFullDimensions","sizes","getPhotoInlineDimensions","getVideoDimensions","width","height","getMediaTransferState","isLoadNeeded","isUploading","isTransferring","transferProgress","messageIds","contentType","validator","matchLinkInMessageText","getMediaDuration","buildChatThreadKey","STRIPE_ERRORS","missing_payment_information","field","invalid_number","number","exp_year","exp_month","invalid_expiry_year","invalid_expiry_month","cvc","invalid_cvc","getStripeError","param","USER_COLOR_KEYS","isDeletedUser","getUserStatus","status","wasOnline","getTime","wasOnlineDate","diff","today","setHours","yesterday","setDate","getDate","formatFullDate","isUserOnline","isUserBot","getCanAddContact","sortUserIds","userIds","getServerTime","expires","getUserIdDividend","abs","getUserColorKey","peer","replaceChatListIds","newIds","updateChatListIds","idsUpdate","replaceChats","newById","getUpdatedChat","chatUpdate","shouldOmitMinInfo","isMin","updatedChat","omit","photos","updateChat","updatedById","updatedChats","addChats","addedById","isAdded","addedChats","updateChatListType","listType","currentListIds","listTypeKey","currentFolderList","updateChatListSecondaryInfo","info","totalCountKey","totalChatCount","isFullyLoaded","leaveChat","leftChatId","selectChatListType","listId","updateCurrentMessageList","shouldReplaceHistory","messageLists","newMessageLists","replaceChatMessages","updateMessageStore","byChatId","threadsById","replaceThreadParam","paramName","threadUpdate","updateThread","addMessages","addedByChatId","messagesByChatId","addChatMessagesById","selectChatMessages","every","newId","updateChatMessage","messageUpdate","updatedMessage","updateScheduledMessage","selectScheduledMessages","replaceScheduledMessages","deleteChatMessages","deletedForwardedPosts","pickTruthy","isLinkedChannelPost","threadInfo","selectThreadInfo","selectListedIds","outlyingIds","selectOutlyingIds","viewportIds","selectViewportIds","selectPinnedIds","newMessageCount","messagesCount","currentMessageList","selectCurrentMessageList","canDeleteCurrentThread","currentThreadId","fromChatId","fromMessageId","originalPost","selectChatMessage","deleteChatScheduledMessages","scheduledIds","selectScheduledIds","updateListedIds","orderHistoryIds","updateOutlyingIds","sort","a","b","addViewportId","safeReplaceViewportIds","newViewportIds","currentIds","updateThreadInfo","newThreadInfo","updateThreadInfos","updates","scheduledMessages","updateScheduledMessages","updateFocusedMessage","noHighlight","isResizingContainer","focusedMessage","updateFocusDirection","direction","enterMessageSelectMode","selectedMessages","prototype","toggleMessageSelection","messageListType","childMessageIds","withShift","oldSelectedMessages","selectMessageIdsByGroupId","selectedMessageIds","newMessageIds","newSelectedMessageIds","selectCurrentMessageIds","prevIndex","min","to","unique","exitMessageSelectMode","updateThreadUnreadFromForwardedMessage","originMessage","lastMessageId","isDeleting","channelPostId","threadInfoOld","updateStickerSets","category","sets","resultIds","updatedSets","stickerSet","stickers","setsById","setIds","updateStickerSet","stickerSetId","currentStickerSet","updateGifSearch","isNew","results","nextOffset","currentResults","gifs","newResults","gif","replaceAnimatedEmojis","animatedEmojis","updateStickersForEmoji","remoteStickers","allStickers","selectStickersForEmoji","uniqueIds","forEmoji","rebuildStickersForEmoji","replaceUsers","getUpdatedUser","userUpdate","updatedUser","updateContactList","updatedUsers","contactUserIds","contactList","newContactUserIds","updateUsers","addedUsers","updateSelectedUserId","selectedId","deleteUser","MEMO_EMPTY_ARRAY","updateUserSearch","searchStatePartial","userSearch","updateUserSearchFetchingStatus","newState","fetchingStatus","updateUserBlockedState","isBlocked","getComplexKey","updateGlobalSearch","globalSearch","updateGlobalSearchContent","currentContent","updateGlobalSearchResults","newFoundMessages","nextRate","resultsByType","newFoundMessagesById","foundIdsForType","foundIds","updateGlobalSearchFetchingStatus","prevFoundIds","newFoundIds","foundOrPrevFoundIds","nextOffsetId","replaceLocalTextSearch","chatThreadKey","searchParams","localTextSearch","byChatThreadKey","updateLocalTextSearch","query","replaceLocalTextSearchResults","updateLocalTextSearchResults","orderFoundIds","replaceLocalMediaSearch","localMediaSearch","updateLocalMediaSearchType","currentType","updateLocalMediaSearchResults","replaceLocalMediaSearchResults","updateManagementProgress","management","updateManagement","newSettings","themes","notifyException","exceptionData","addNotifyException","updateTwoFaSettings","twoFaSettings","updateShippingOptions","shippingOptions","payment","setRequestInfoId","requestId","setPaymentStep","step","setInvoiceMessageInfo","photoUrl","invoiceContent","setStripeCardInfo","cardInfo","stripeCredentials","setPaymentForm","form","setReceipt","receipt","messageInvoice","clearPayment","closeInvoice","isPaymentModalOpen","selectIsUserBlocked","selectNotifyExceptions","selectChat","selectChatUser","selectIsChatWithSelf","selectIsChatWithBot","selectSupportChat","isSupport","selectChatOnlineCount","members","onlineCount","selectChatBot","selectIsChatBotNotStarted","bot","messageInfo","selectAreActiveChatsLoaded","active","selectIsChatListed","targetList","list","selectChatFolder","chatFolders","selectIsChatPinned","archived","chatFoldersById","selectChatByUsername","usernameLowered","selectCountNotMutedUnread","activeChatIds","selectIsServiceChatReady","selectCurrentStickerSearch","selectCurrentGifSearch","selectStickerSet","selectStickerSetByShortName","shortName","stickerSets","stickersForEmoji","packs","selectAnimatedEmoji","cleanedEmoji","selectCurrentChat","selectThreadParam","thread","selectScrollOffset","selectReplyingToId","selectEditingId","selectEditingScheduledId","selectDraft","selectNoWebPage","selectFirstMessageId","selectReplyStack","selectThreadOriginChat","originChannelId","selectThreadTopMessageId","topMessageId","selectThreadByMessage","replyToTopMessageId","isMessageInCurrentMessageList","selectIsViewportNewest","chatMessages","selectScheduledMessage","selectEditingMessage","selectChatMessageByPollId","pollId","messageWithPoll","selectFocusedMessageId","focusedChatId","selectIsMessageFocused","focusedId","selectOutgoingStatus","isScheduledList","lastReadOutboxMessageId","selectIsMessageUnread","selectSender","selectForwardedSender","isChannelPost","senderUserId","selectAllowedMessageActions","isPrivate","isChatWithSelf","isBasicGroup","isSuperGroup","isChannel","isLocal","isServiceNotification","isOwn","isAction","isMessageEditable","viaBotId","canReply","hasPinPermission","canPin","canUnpin","pinnedMessageIds","canDelete","canReport","canDeleteForAll","canEdit","canForward","hasSticker","hasFavoriteSticker","favorite","selectIsStickerFavorite","canFaveSticker","canUnfaveSticker","canCopy","canCopyLink","canSelect","canDownload","noOptions","ability","selectCanDeleteSelectedMessages","messageActions","selectCanReportSelectedMessages","selectCanDownloadSelectedMessages","selectIsDownloading","activeInChat","activeDownloads","selectActiveDownloadIds","selectUploadProgress","fileUploads","byMessageLocalId","selectRealLastReadId","lastReadInboxMessageId","Infinity","selectFirstUnreadId","lastReadId","lastReadServiceNotificationId","serviceNotifications","notification","isUnread","findAfterLastReadId","isFromScheduled","found","selectIsForwardModalOpen","forwardMessages","isModalShown","selectCommonBoxChatId","fromLastMessage","selectIsInSelectMode","selectIsMessageSelected","selectForwardedMessageIdsByGroupId","selectIsDocumentGroupSelected","selectedIds","groupIds","selectSelectedMessagesCount","selectNewestMessageWithBotKeyboardButtons","findLast","keyboardButtons","replyHideMessageId","shouldHideKeyboardButtons","selectCanAutoLoadMedia","isPhoto","isVideo","isFile","canAutoLoadPhotoFromContacts","canAutoLoadPhotoInPrivateChats","canAutoLoadPhotoInGroups","canAutoLoadPhotoInChannels","canAutoLoadVideoFromContacts","canAutoLoadVideoInPrivateChats","canAutoLoadVideoInGroups","canAutoLoadVideoInChannels","canAutoLoadFileFromContacts","canAutoLoadFileInPrivateChats","canAutoLoadFileInGroups","canAutoLoadFileInChannels","canAutoLoadMedia","canAutoLoadMediaFromContacts","canAutoLoadMediaInPrivateChats","canAutoLoadMediaInGroups","canAutoLoadMediaInChannels","isMediaFromContact","selectIsUserOrChatContact","selectCanAutoPlayMedia","canAutoPlayVideos","canAutoPlayGifs","asGif","selectShouldLoopStickers","shouldLoopStickers","selectLastServiceNotification","maxId","selectCurrentTextSearch","currentSearch","selectCurrentMediaSearchPeerId","currentProfileUserId","selectCurrentMediaSearch","peerId","selectManagement","selectCurrentManagementType","selectIsMediaViewerOpen","mediaViewer","avatarOwnerId","selectRightColumnContentKey","isChatInfoShown","newChatMembersProgress","isAddingChatMembersShown","NewChatMembersProgress","isPollResults","pollResults","selectIsPollResultsOpen","isSearch","IS_SINGLE_COLUMN_LAYOUT","isManagement","currentManagement","selectCurrentManagement","isStickerSearch","isGifSearch","currentChatId","areActiveChatsLoaded","isUserInfo","isChatInfo","RightColumnContent","selectIsRightColumnShown","shouldUseSystemTheme","getSystemTheme","selectCurrentGlobalSearchQuery","selectPaymentChatId","selectPaymentMessageId","selectPaymentFormId","formId","selectPaymentRequestId","selectProviderPublishableKey","nativeParams","publishableKey","selectStripeCredentials","LoadMoreDirection","FocusDirection","SettingsScreens","LeftColumnContent","GlobalSearchContent","MediaViewerOrigin","AudioOrigin","ChatCreationProgress","ManagementProgress","ProfileState","PaymentStep","ManagementScreens","currentInstance","animateSingle","tick","instance","isCancelled","animate","setAppBadge","currentProps","newProps","currentKeysLength","prop","self","caches","Type","fetch","cacheName","isHtmlAllowed","request","Request","cache","open","headers","Blob","blob","shouldRecreate","resolvedType","Json","json","save","cacheData","Response","put","clear","captureKeyboardListener","onEsc","keyToHandlerName","Enter","Backspace","Delete","Esc","Escape","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Tab","handlers","onEnter","onDelete","onBackspace","onUp","onDown","onLeft","onRight","onTab","captureKeyboardListeners","hasActiveHandlers","handlerName","currentEventHandlers","releaseKeyboardListener","keyHandlers","WEEKDAYS_FULL","MONTHS_FULL","MONTHS_FULL_LOWERCASE","month","getDayStart","datetime","getDayStartAt","toYearMonth","timestamp","getFullYear","getMonth","toIsoString","hours","getHours","marker","padStart","getMinutes","formatPastTimeShort","weekAgo","getDay","withYear","format","formatDate","formatMonthAndYear","isShort","formatHumanDate","noWeekdays","isUpperFirst","upperFirst","lowerFirst","weekAhead","weekDay","day","monthIndex","formatMediaDateTime","formatMediaDuration","maxValue","minutes","seconds","maxHours","maxMinutes","string","formatVoiceRecordDuration","durationInMs","milliseconds","locale","toLocaleString","year","isValidDate","MAX_MONTH_IN_YEAR","parseDateString","matchStringDate","matchEuropeStringDate","matchNumberDate","dateParts","timestampPlusDay","MILLISECONDS_IN_DAY","str","EXCLUDE_EMOJIS","EMOJI_EXCEPTIONS","unifiedToNative","unified","codePoints","parseInt","fromCodePoint","regex","replacement","pairs","uncompressEmoji","emojiData","categories","emojiRaw","names","native","image","isoToEmoji","iso","test","c","codePointAt","isWebpSupportedCache","webp","Image","handleLoadOrError","onload","onerror","hasWebp","systemThemeCache","matches","os","getPlatform","IS_PWA","standalone","referrer","IS_TABLET_COLUMN_LAYOUT","IS_VOICE_RECORDING_SUPPORTED","mediaDevices","AudioContext","webkitAudioContext","IS_SERVICE_WORKER_SUPPORTED","Audio","canPlayType","IS_CANVAS_FILTER_SUPPORTED","getContext","LAYERS_ANIMATION_NAME","TEST_VIDEO","DPR","devicePixelRatio","MASK_IMAGE_DISABLED","dataUriToBlob","arr","mime","bstr","atob","u8arr","Uint8Array","blobToDataUri","reader","FileReader","readAsDataURL","blobToFile","File","lastModified","preloadImage","img","preloadVideo","volume","onloadedmetadata","createPosterForVideo","onseeked","videoWidth","videoHeight","canvas","drawImage","toDataURL","currentTime","fetchBlob","imgToCanvas","constructor","fileBits","rest","super","this","totalPrice","Intl","NumberFormat","store","random","hasOwnProperty","READABLE_ERROR_MESSAGES","CHAT_RESTRICTED","CHAT_WRITE_FORBIDDEN","CHAT_SEND_POLL_FORBIDDEN","CHAT_SEND_STICKERS_FORBIDDEN","CHAT_SEND_GIFS_FORBIDDEN","CHAT_SEND_MEDIA_FORBIDDEN","CHAT_LINK_EXISTS","SLOWMODE_WAIT_X","USER_BANNED_IN_CHANNEL","USER_IS_BLOCKED","YOU_BLOCKED_USER","IMAGE_PROCESS_FAILED","MEDIA_EMPTY","MEDIA_INVALID","PHOTO_EXT_INVALID","PHOTO_INVALID_DIMENSIONS","PHOTO_SAVE_FILE_INVALID","MESSAGE_DELETE_FORBIDDEN","MESSAGE_POLL_CLOSED","MESSAGE_EDIT_TIME_EXPIRED","CHAT_ADMIN_REQUIRED","PINNED_DIALOGS_TOO_MUCH","DIALOG_FILTERS_TOO_MUCH","CHANNEL_PRIVATE","MEDIA_CAPTION_TOO_LONG","ADDRESS_STREET_LINE1_INVALID","ADDRESS_STREET_LINE2_INVALID","ADDRESS_CITY_INVALID","ADDRESS_COUNTRY_INVALID","ADDRESS_POSTCODE_INVALID","ADDRESS_STATE_INVALID","REQ_INFO_NAME_INVALID","REQ_INFO_PHONE_INVALID","REQ_INFO_EMAIL_INVALID","LINK_NOT_MODIFIED","MESSAGE_TOO_LONG","SERVICE_WORKER_DISABLED","MESSAGE_TOO_LONG_PLEASE_REMOVE_CHARACTERS","FRESH_RESET_AUTHORISATION_FORBIDDEN","BOTS_TOO_MUCH","BOT_GROUPS_BLOCKED","USERS_TOO_MUCH","USER_CHANNELS_TOO_MUCH","USER_KICKED","USER_NOT_MUTUAL_CONTACT","USER_PRIVACY_RESTRICTED","INVITE_HASH_EMPTY","INVITE_HASH_EXPIRED","INVITE_HASH_INVALID","CHANNELS_TOO_MUCH","USER_ALREADY_PARTICIPANT","SCHEDULE_DATE_INVALID","WALLPAPER_DIMENSIONS_INVALID","SHIPPING_ERRORS","getReadableErrorText","isSlowMode","textParams","extraPartIndex","errorMessage","handleErrorEvent","ErrorEvent","reason","throttle","alert","collection","member","mapValues","newByKey","object","stringKeys","orderKey","mode","mode1","mode2","orderKey1","orderKey2","aValue1","bValue1","aValue2","bValue2","aValue","bValue","array","compact","array1","array2","areSortedArraysIntersecting","findIntersectionWithSet","chunkSize","cloneDeep","predicate","SUBSTITUTION_REGEX","PLURAL_OPTIONS","PLURAL_RULES","en","ar","ca","de","es","fa","fr","it","ko","ms","nl","pl","pt_BR","ru","tr","uk","uz","langPack","fallbackLangPack","createCallbackManager","currentLangCode","currentTimeFormat","getTranslation","cacheValue","cached","langString","processTranslation","importFallbackLangPack","getTranslationForLangString","translateString","remoteLangPack","remote","fetchRemoteString","withFallback","newLangPack","sourceLangPacks","fetchRemote","langInfo","rtl","default","template","optionIndex","getPluralOption","translationSlices","initialValue","processTemplate","formatInteger","SAMPLE_RATE","oggToWav","opusData","arrayBuffer","typedArray","decoderWorker","wavWorker","onmessage","command","buffers","buffer","page","terminate","wavBitDepth","wavSampleRate","decoderSampleRate","outputBufferSampleRate","pages","asCacheApiType","memoryCache","fetchPromises","progressCallbacks","cancellableCallbacks","mediaFormat","onProgress","callbackUniqueId","progressiveUrl","getProgressive","mediaPng","webpToPng","prepared","prepareMedia","mediaSource","MediaSource","streamUrl","sourceBuffer","addSourceBuffer","makeOnProgress","revokeObjectURL","fetchFromCacheOrRemote","activeCallbacks","getFromMemory","cancelProgress","parentCallback","endOfStream","appendBuffer","mediaData","serviceWorker","fullSize","controller","Bundles","LOAD_PROMISES","MEMORY_CACHE","Auth","Main","Extra","handleBundleLoad","bundle","listeners","listener","getDeviceToken","subscription","toJSON","endpoint","checkIfPushSupported","ServiceWorkerRegistration","Notification","permission","soundPlayedIds","playNotifySound","notificationSoundVolume","currentVolume","once","play","playNotifySoundDebounced","requestPermission","unsubscribeFromPush","dispatch","deleteDeviceToken","serviceWorkerRegistration","ready","pushManager","getSubscription","areSettingsLoaded","checkIfShouldResubscribe","userVisibleOnly","setDeviceToken","DOMException","ABORT_ERR","notifyAboutNewMessage","resultSettings","resultExceptions","loadNotificationSettings","hasFocus","checkIfShouldNotify","messageSender","messageAction","actionTargetMessage","targetUserIds","actionTargetUserIds","actionTargetChatId","actionTargetUsers","privateChatUserId","senderName","getNotificationContent","imageHash","mediaLoader","getAvatar","badge","vibrate","onclick","close","onshow","closeMessageNotifications","notifyClientReady","PATTERN_PLACEHOLDER","DEFAULT_PATTERN","getCountryCodesByIso","phoneCodeList","country","iso2","getCountryFromPhoneNumber","possibleCountries","countryCode","bestMatches","prefixes","prefix","formatPhoneNumber","pattern","numberWithoutCode","patterns","defaultPattern","stripped","getBestPattern","formatPhoneNumberWithCode","numberWithPlus","createMessageHash","messageList","parseLocationHash","typeOrThreadId","isType","fn","shouldRunFirst","shouldRunLast","waitingTimeout","interval","isPending","_args","setInterval","clearInterval","throttleWith","waiting","onIdle","requestIdleCallback","rafPromise","fastRafCallbacks","fastRafPrimaryCallbacks","onTickEndCallbacks","onTickEndPrimaryCallbacks","beforeUnloadCallbacks","isPrimary","currentCallbacks","currentPrimaryCallbacks","onBeforeUnload","isLast","unshift","RE_NOT_LETTER","searchWords","haystack","needle","haystackWords","needleWord","haystackWord","promisifyRequest","oncomplete","onsuccess","onabort","defaultGetStoreFunc","defaultGetStore","dbName","storeName","dbp","userAgentData","indexedDB","databases","intervalId","tryIdb","onupgradeneeded","createObjectStore","txMode","db","transaction","objectStore","createStore","DC_IDS","hasStoredSession","withLegacy","userAuthJson","dcID","dcId","removeItem","sessionId","sessionJson","customStore","idb","idbKeys","items","openCursor","continue","eachCursor","isInitialized","HEX_COLOR_REGEX","RGB_VARIABLES","lerp","start","end","interpolationRatio","colors","themeColors","property","hexToRgb","withAnimation","isDarkTheme","shouldAnimate","startIndex","endIndex","startAt","themeColorTag","querySelector","applyColorAnimationStep","transition","hex","r","g","propertyColors","formatFixedNumber","formatIntegerCompact","views","getFirstLetters","phrase","count","word","EMPTY_IMAGE_DATA_URI","initWebpWorker","wasmReady","requests","getDecodePromise","ImageData","putImageData","toBlob","createPng","webpToPngBase64","pngBlob","handleLibWebpMessage","WEBSYNC_URLS","WEBSYNC_VERSION","WEBSYNC_KEY","getTs","lastTimeout","authed","currentTs","canRedirect","ts","script","removeElement","URLSearchParams","version","saveSync","IS_LANDSCAPE","isLandscape","initialHeight","windowSize","updateSizes","isRefreshDisabled","handleResize","visualViewport","pageTop","vh","getIsKeyboardVisible","disableRefresh","enableRefresh","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","exports","__webpack_modules__","call","m","getter","__esModule","getPrototypeOf","obj","ns","create","def","getOwnPropertyNames","definition","o","defineProperty","enumerable","f","chunkId","promises","u","miniCssF","globalThis","Function","done","needAttach","scripts","getElementsByTagName","charset","nc","onScriptComplete","doneFns","bind","head","toStringTag","scriptUrl","importScripts","currentScript","fullhref","existingLinkTags","dataHref","existingStyleTags","findStylesheet","linkTag","errorType","realHref","createStylesheet","miniCss","baseURI","installedChunks","installedChunkData","realSrc","webpackJsonpCallback","parentChunkLoadingFunction","chunkIds","moreModules","runtime","chunkLoadingGlobal","handleWorkerMessage","register","INITIAL_STATE","isLeftColumnShown","phoneCodes","general","activeChatFolder","recentEmojis","added","recent","greeting","featured","emojiKeywords","saved","inlineBots","byUsername","topPeers","topInlineBots","audioPlayer","playbackRate","notifications","dialogs","messageSendKeyCombo","autoLoadFileMaxSizeMb","shouldSuggestStickers","light","isBlurred","patternColor","dark","shouldShowContextMenuHint","updateCacheThrottled","updateCache","unsubscribeFromBeforeUnload","isCaching","isHeavyAnimating","setupCaching","clearCaching","reducedGlobal","reduceShowChatInfo","reduceUsers","reduceChats","reduceMessages","recentlyFoundChatIds","reduceSettings","reduceChatFolders","idsToSave","chatIdsToSave","mainThread","initialState","time","timeEnd","shouldAutoDownloadMediaFromContacts","shouldAutoDownloadMediaInPrivateChats","shouldAutoDownloadMediaInGroups","shouldAutoDownloadMediaInChannels","shouldAutoPlayVideos","shouldAutoPlayGifs","migrateCache","parsedMessageList","readCache","loadCache","STORAGE_KEY","tabKey","SITE_FONTS","preloadFonts","font","fonts","load","preloadAvatars","preloadTasks","main","telegramLogoPath","authCode","monkeyPath","authPassword","background","backgroundColor","hasCustomBackground","hasCustomBackgroundColor","isRightColumnShown","leftColumnWidth","setIsUiReady","isReady","markReady","useFlag","shouldRenderMask","safePreload","translation","setTranslation","getSuggestedLanguage","suggestedLanguage","MENU_HIDING_DURATION","inputRef","setFilter","filteredList","setFilteredList","updateFilter","filterValue","defaultName","getFilteredList","prevPhoneCodeList","handleInput","handleInputKeyDown","DropdownMenu","handleTrigger","select","formEl","getElementById","scrollTo","top","scrollHeight","behavior","inputValue","Spinner","MenuItem","isPreloadInitiated","setAuthPhoneNumber","setAuthRememberMe","loadNearestCountry","loadCountryList","clearAuthError","goToAuthQrCode","continueText","useLangString","setCountry","setPhoneNumber","isTouched","setIsTouched","lastSelection","setLastSelection","markIsLoading","unmarkIsLoading","fullNumber","canSubmit","parseFullNumber","newFullNumber","suggestedCountry","selectedCountry","handleLangChange","setSelectionRange","isJustPastedRef","handlePaste","handleCountryChange","handlePhoneNumberChange","selectionStart","selectionEnd","shouldFixSafariAutoComplete","handleKeepSessionChange","isAuthReady","onSubmit","InputText","Checkbox","Button","Loading","AuthCode","useModuleLoader","AuthPassword","AuthRegister","G","H","B","QrCreator","h","J","level","O","C","lineTo","arcTo","moveTo","z","v","N","K","P","fillStyle","fillRect","left","beginPath","q","D","E","R","I","F","fill","colorStops","createLinearGradient","apply","createRadialGradient","addColorStop","A","minVersion","maxVersion","ecLevel","radius","quiet","HTMLCanvasElement","clearRect","write","S","multiply","L","M","Q","returnToAuthPhoneNumber","qrCodeRef","token","isMobile","AuthQrCode","appInactivePath","renderMain","disconnect","isInactive","markInactive","TeactDOM"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/main.385008a5f5d046ca97cd.js b/dist/main.4f9a89db11e14d2fa319.js similarity index 74% rename from dist/main.385008a5f5d046ca97cd.js rename to dist/main.4f9a89db11e14d2fa319.js index 6bdb63bb..080a2264 100644 --- a/dist/main.385008a5f5d046ca97cd.js +++ b/dist/main.4f9a89db11e14d2fa319.js @@ -1,2 +1,2 @@ -(()=>{"use strict";var e,t,n,r,o,d,u={1226:(e,t,n)=>{n.d(t,{t9:()=>c,u3:()=>l,g8:()=>i});var r=n(3716),o=n(6926),d=n(9118);let u;const a=new Map,s=new Map;function i(e,t){return u||(r.eM&&console.log(">>> START LOAD WORKER"),u=new Worker(new URL(n.p+n.u(514),n.b)),function(e){u.addEventListener("message",(({data:t})=>{if("update"===t.type)e(t.update);else if("methodResponse"===t.type){const e=a.get(t.messageId);e&&(t.error?e.reject(t.error):e.resolve(t.response))}else if("methodCallback"===t.type){var n,r;null===(n=a.get(t.messageId))||void 0===n||null===(r=n.callback)||void 0===r||r.call(n,...t.callbackArgs)}else if("unhandledError"===t.type)throw t.error}))}(e),"iOS"===t.platform&&window.addEventListener("focus",(async()=>{try{await Promise.race([f({type:"ping"}),(0,d.wO)(150).then((()=>Promise.reject(new Error("HEALTH_CHECK_TIMEOUT"))))])}catch(e){console.error(e),Date.now()-h>=5e3&&window.location.reload()}}))),f({type:"initApi",args:[t]})}function c(e,...t){if(u)return f({type:"callMethod",name:e,args:t});r.eM&&console.warn("API is not initialized")}function l(e){e.isCanceled=!0;const{messageId:t}=s.get(e)||{};t&&u.postMessage({type:"cancelProgress",messageId:t})}function f(e){const t=(0,o.Z)(a),n={messageId:t,...e},r={messageId:t},d=new Promise(((e,t)=>{Object.assign(r,{resolve:e,reject:t})}));if("args"in n&&"function"==typeof n.args[1]){const e=n.args.pop();r.callback=e,s.set(e,r)}return a.set(t,r),d.catch((()=>{})).finally((()=>{a.delete(t),r.callback&&s.delete(r.callback)})),u.postMessage(n),d}const h=Date.now()},6137:(e,t,n)=>{n.d(t,{Vv:()=>r.Vv,_f:()=>r._f,_Q:()=>r._Q,IU:()=>o.I});var r=n(4746),o=n(9077)},9077:(e,t,n)=>{let r;n.d(t,{I:()=>r}),function(e){e[e.BlobUrl=0]="BlobUrl",e[e.Lottie=1]="Lottie",e[e.Progressive=2]="Progressive",e[e.Stream=3]="Stream"}(r||(r={}))},4746:(e,t,n)=>{let r;n.d(t,{Vv:()=>r,_f:()=>o,_Q:()=>d}),function(e){e.Bold="MessageEntityBold",e.Blockquote="MessageEntityBlockquote",e.BotCommand="MessageEntityBotCommand",e.Cashtag="MessageEntityCashtag",e.Code="MessageEntityCode",e.Email="MessageEntityEmail",e.Hashtag="MessageEntityHashtag",e.Italic="MessageEntityItalic",e.MentionName="MessageEntityMentionName",e.Mention="MessageEntityMention",e.Phone="MessageEntityPhone",e.Pre="MessageEntityPre",e.Strike="MessageEntityStrike",e.TextUrl="MessageEntityTextUrl",e.Url="MessageEntityUrl",e.Underline="MessageEntityUnderline",e.Unknown="MessageEntityUnknown"}(r||(r={}));const o=-1,d="MESSAGE_DELETED"},88:(e,t,n)=>{n.d(t,{Z:()=>h});var r=n(4050),o=n(5116);const d=36,u=2147483647;function a(e,t,n){let r;for(e=n?Math.floor(e/700):e>>1,e+=Math.floor(e/t),r=0;e>455;r+=d)e=Math.floor(e/35);return Math.floor(r+36*e/(e+38))}function s(e,t){const n=[],r=[],o=e.length;let s,i,c,l,f,h,m,p,g,y,v,b,w;for(s=128,c=0,l=72,f=e.lastIndexOf("-"),f<0&&(f=0),h=0;h=128)throw new RangeError("Illegal input >= 0x80");n.push(e.charCodeAt(h))}for(m=f>0?f+1:0;m=o)throw RangeError("punycode_bad_input(1)");if(v=(I=e.charCodeAt(m++))-48<10?I-22:I-65<26?I-65:I-97<26?I-97:d,v>=d)throw RangeError("punycode_bad_input(2)");if(v>Math.floor((u-c)/g))throw RangeError("punycode_overflow(1)");if(c+=v*g,b=y<=l?1:y>=l+26?26:y-l,vMath.floor(u/(d-b)))throw RangeError("punycode_overflow(2)");g*=d-b}if(i=n.length+1,l=a(c-p,i,0===p),Math.floor(c/i)>u-s)throw RangeError("punycode_overflow(3)");s+=Math.floor(c/i),c%=i,t&&r.splice(c,0,e.charCodeAt(m-1)-65<26),n.splice(c,0,s),c++}var I;if(t)for(c=0,w=n.length;c{const t=[];let n=0;const r=e.length;let o;for(;n65535&&(o-=65536,t.push(String.fromCharCode(o>>>10&1023|55296)),o=56320|1023&o),t.push(String.fromCharCode(o))}return t.join("")})(n)}var i=n(3716),c=n(6752);function l(e){if(e)return e.includes("://")?e:`https://${e}`}function f(e){if(!e)return;const t=l(e);if(t)try{let e=decodeURI(t);const n=e.match(/^https?:\/\/([^/:?#]+)(?:[/:?#]|$)/i);if(!n)return;const r=n[1];return e=e.replace(r,function(e){const t=e.split("."),n=[];for(let e=0;e{const{toggleSafeLinkModal:a,openTelegramLink:s}=(0,o.uC)(),h=d||t,m=e!==h,p=(0,r.I4)((t=>t.ctrlKey||t.altKey||t.shiftKey||t.metaKey||!e||!e.match(i.FS)&&!e.match(i.g$)?!m||(a({url:e}),t.preventDefault(),!1):(t.preventDefault(),s({url:e}),!1)),[m,s,a,e]);if(!e)return;const g=(0,c.Z)(n||"text-entity-link",t.length>50&&"long-word-break-all");return r.ZP.createElement("a",{href:l(e),title:f(e),target:"_blank",rel:"noopener noreferrer",className:g,onClick:p,dir:u?"rtl":"auto"},h)}))},5376:(e,t,n)=>{n.d(t,{yW:()=>r,K2:()=>o,mD:()=>d,Oh:()=>u,v6:()=>a});function r(e){return e>536870912?`${(e/1073741824).toFixed(1)} GB`:e>524288?`${(e/1048576).toFixed(1)} MB`:`${(e/1024).toFixed(1)} KB`}function o(e){const{fileName:t,mimeType:n}=e;return d(t,n)}function d(e,t){return e&&-1!==e.indexOf(".")?e.split(".").pop():t.split("/").pop()}function u(e){switch(e){case"apk":case"xls":case"xlsx":return"green";case"zip":case"rar":case"7z":case"tar":case"gz":case"ppt":case"pptx":return"orange";case"pdf":case"xps":return"red";default:return"default"}}function a(e){return Boolean(e.previewBlobUrl||e.thumbnail)}},4784:(e,t,n)=>{n.d(t,{Z:()=>d});var r=n(3681);const o=new RegExp(`^(?:${r.Z.source})+$`,""),d=e=>{if(e.length>24)return!1;if(!Boolean(e.match(o)))return!1;let t=0;for(;r.Z.exec(e);)if(t++,t>3)return r.Z.lastIndex=0,!1;return t}},2864:(e,t,n)=>{n.d(t,{D:()=>p});var r=n(4050),o=n(2858),d=n(8035),u=n(9937),a=n(2340),s=n(5116),i=n(782),c=n(6752),l=n(8033);const f=(0,s.c$)(void 0,((e,t)=>(0,i.ei)(t,["openUserInfo"])))((({className:e,sender:t,openUserInfo:n,children:o})=>{const d=(0,r.I4)((()=>{t&&n({id:t.id})}),[t,n]);return t?r.ZP.createElement(l.Z,{className:(0,c.Z)("UserLink",e),onClick:d},o):o})),h=(0,s.c$)(void 0,((e,t)=>(0,i.ei)(t,["focusMessage"])))((({className:e,message:t,children:n,focusMessage:o})=>{const d=(0,r.I4)((()=>{t&&o({chatId:t.chatId,messageId:t.id})}),[o,t]);return t?r.ZP.createElement(l.Z,{className:(0,c.Z)("MessageLink",e),onClick:d},n):n})),m=(0,s.c$)(void 0,((e,t)=>(0,i.ei)(t,["openChat"])))((({className:e,chatId:t,openChat:n,children:o})=>{const d=(0,r.I4)((()=>{t&&n({id:t})}),[t,n]);return t?r.ZP.createElement(l.Z,{className:(0,c.Z)("ChatLink",e),onClick:d},o):o}));function p(e,t,n,s,i,c,l={}){if(!t.content.action)return[];const{text:f,translationValues:p,amount:v,currency:b}=t.content.action,w=[],I={...l,maxTextLength:32};let C,S=e("Chat.Service.Group.UpdatedPinnedMessage1"!==f||i?f:"Message.PinnedGenericMessage",p&&p.length?p:void 0);return S.includes("%payment_amount%")&&(C=y(S,"%payment_amount%",(0,u.x)(v,b,e.code)),S=C.pop(),w.push(...C)),C=y(S,"%action_origin%",n?!l.isEmbedded&&function(e,t,n){return(0,o.YC)(t.id)?g(t,n):function(e,t,n){const u=(0,d.Z)((0,o.U)(e,t));return n?u:r.ZP.createElement(m,{className:"action-link",chatId:t.id},t&&(0,a.Z)(u))}(e,t,n)}(e,n,l.asPlain)||" ":"User"),S=C.pop(),w.push(...C),C=y(S,"%target_user%",s?s.map((e=>g(e,l.asPlain))).filter(Boolean):"User"),S=C.pop(),w.push(...C),C=y(S,"%message%",i?function(e,t,n={}){const u=(0,o.MK)(e,t),{photo:s,video:i,document:c,sticker:l}=(0,o.qp)(t),{maxTextLength:f,isEmbedded:m,asPlain:p}=n,g=m&&u&&!s&&!i&&!c&&!l;let y=(0,d.Z)(u,f);return m&&(s?y="a photo":i?y=i.isGif?"a GIF":"a video":c?y="a document":l&&(y=u)),p?g?`«${y}»`:y:g?r.ZP.createElement("span",null,"«",r.ZP.createElement(h,{className:"action-link",message:t},(0,a.Z)(y)),"»"):r.ZP.createElement(h,{className:"action-link",message:t},(0,a.Z)(y))}(e,i,I):"a message"),S=C.pop(),w.push(...C),C=y(S,"%product%",i?function(e){return e.content&&e.content.invoice?e.content.invoice.title:"a product"}(i):"a product"),S=C.pop(),w.push(...C),C=y(S,"%target_chat%",c?function(e,t){const n="another chat";return t?n:r.ZP.createElement(m,{className:"action-link",chatId:e},n)}(c,l.asPlain):"another chat"),w.push(...C),l.asPlain?w.join("").trim():w}function g(e,t){const n=(0,d.Z)((0,o.Js)(e));return t?n:r.ZP.createElement(f,{className:"action-link",sender:e},e&&(0,a.Z)(n))}function y(e,t,n){const r=e.indexOf(t);if(r<0||!n)return[e];const o=[];return o.push(e.substring(0,r)),Array.isArray(n)?n.forEach(((e,t)=>{o.push(e),t+1{n.d(t,{Z:()=>h});var r=n(4050),o=n(3681),d=n(3716),u=n(7361),a=n(4284),s=n(6752),i=n(7373),c=n(88);const l=/^[\d\wа-яё]$/i,f=/(\*\*|__).+?\1/g;function h(e,t=["emoji"],n){return"string"!=typeof e?[e]:t.reduce(((e,t)=>{switch(t){case"escape_html":return function(e){const t=document.createElement("div");return e.reduce(((e,n)=>"string"!=typeof n?[...e,n]:(t.innerText=n,[...e,t.innerHTML])),[])}(e);case"hq_emoji":return o.Z.lastIndex=0,m(e,"big","jsx");case"emoji":return o.Z.lastIndex=0,m(e,"small","jsx");case"emoji_html":return o.Z.lastIndex=0,m(e,"small","html");case"br":return p(e,"jsx");case"br_html":return p(e,"html");case"highlight":return d=e,u=n.highlight,d.reduce(((e,t)=>{if("string"!=typeof t||!u)return[...e,t];const n=t.toLowerCase(),o=n.indexOf(u.toLowerCase()),d=n[o+u.length];if(o<0||d&&d.match(l))return[...e,t];const a=[];return a.push(t.substring(0,o)),a.push(r.ZP.createElement("span",{className:"matching-text-highlight"},t.substring(o,o+u.length))),a.push(t.substring(o+u.length)),[...e,...a]}),[]);case"links":return function(e){return e.reduce(((e,t)=>{if("string"!=typeof t)return[...e,t];const n=t.match(g);if(!n||!n.length)return[...e,t];const o=[];let d=n.shift(),u=0;for(;d;){const e=t.indexOf(d,u);o.push(t.substring(u,e)),d.startsWith("@")?o.push(r.ZP.createElement(i.Z,{username:d},d)):(d.endsWith("?")&&(d=d.slice(0,d.length-1)),o.push(r.ZP.createElement(c.Z,{text:d,url:d}))),u=e+d.length,d=n.shift()}return o.push(t.substring(u)),[...e,...o]}),[])}(e);case"simple_markdown":return y(e,"jsx");case"simple_markdown_html":return y(e,"html")}var d,u;return e}),[e])}function m(e,t,n){return u.op?e:e.reduce(((e,d)=>{if("string"!=typeof d)return[...e,d];const u=(d=(0,a.g6)(d)).split(o.Z),i=d.match(o.Z)||[];return e.push(u[0]),i.reduce(((e,d,i)=>{const c=(0,a.U_)((0,o.l)(d));if(!c)return e;const l=(0,s.Z)("emoji","small"===t&&"emoji-small");"jsx"===n&&e.push(r.ZP.createElement("img",{className:l,src:`./img-apple-${"big"===t?"160":"64"}/${c}.png`,alt:d})),"html"===n&&e.push(`${d}`);const f=2*i+2;return u[f]&&e.push(u[f]),e}),e)}),[])}function p(e,t){return e.reduce(((e,n)=>"string"!=typeof n?[...e,n]:[...e,...n.split(/\r\n|\r|\n/g).reduce(((e,n,o,d)=>{const u=n.trimLeft(),a=n.length-u.length;return e.push(String.fromCharCode(160).repeat(a)+u),o!==d.length-1&&e.push("jsx"===t?r.ZP.createElement("br",null):"
"),e}),[])]),[])}const g=new RegExp(`${d.FM}|${d.uW}`,"ig");function y(e,t){return e.reduce(((e,n)=>{if("string"!=typeof n)return[...e,n];const o=n.split(f),d=n.match(f)||[];return e.push(o[0]),d.reduce(((e,n,d)=>{"jsx"===t?e.push(n.startsWith("**")?r.ZP.createElement("b",null,n.replace(/\*\*/g,"")):r.ZP.createElement("i",null,n.replace(/__/g,""))):e.push(n.startsWith("**")?`${n.replace(/\*\*/g,"")}`:`${n.replace(/__/g,"")}`);const u=2*d+2;return o[u]&&e.push(o[u]),e}),e)}),[])}},386:(e,t,n)=>{n.d(t,{q:()=>d,b:()=>u});var r=n(3716),o=n(7361);function d(e,t=!1){o.cj||!document.activeElement||document.activeElement.id!==r.R2||!t&&e.target!==e.currentTarget||e.preventDefault()}function u(e){d(e,!0)}},7373:(e,t,n)=>{n.d(t,{Z:()=>a});var r=n(4050),o=n(5116),d=n(782),u=n(8085);const a=(0,o.c$)(((e,{userId:t})=>({userOrChat:t?(0,u.dy)(e,t):void 0})),((e,t)=>(0,d.ei)(t,["openChat","openChatByUsername"])))((({username:e,userOrChat:t,children:n,openChat:o,openChatByUsername:d})=>r.ZP.createElement("a",{onClick:()=>{t?o({id:t.id}):e&&d({username:e.substring(1)})},className:"text-entity-link",dir:"auto"},n)))},231:(e,t,n)=>{n.d(t,{Z:()=>a});var r=n(4050),o=n(6752),d=n(9204),u=n(8512);const a=({ref:e,type:t="button",onClick:n,onContextMenu:a,onMouseDown:s,onMouseEnter:i,onMouseLeave:c,onFocus:l,children:f,size:h="default",color:m="primary",backgroundImage:p,className:g,round:y,pill:v,fluid:b,isText:w,isLoading:I,ariaLabel:C,href:S,download:E,disabled:P,ripple:M,faded:A,tabIndex:k,isRtl:T,withClickPropagation:N})=>{let L=(0,r.sO)(null);e&&(L=e);const[R,D]=(0,r.eJ)(!1),O=(0,o.Z)("Button",g,h,m,y&&"round",v&&"pill",b&&"fluid",P&&"disabled",w&&"text",I&&"loading",M&&"has-ripple",A&&"faded",R&&"clicked",p&&"with-image"),x=(0,r.I4)((e=>{!P&&n&&n(e),D(!0),setTimeout((()=>{D(!1)}),400)}),[P,n]),_=(0,r.I4)((e=>{N||e.preventDefault(),!P&&s&&s(e)}),[s,P,N]);return S?r.ZP.createElement("a",{ref:L,className:O,href:S,title:C,download:E,tabIndex:k,dir:T?"rtl":void 0},f,!P&&M&&r.ZP.createElement(u.Z,null)):r.ZP.createElement("button",{ref:L,type:t,className:O,onClick:x,onContextMenu:a,onMouseDown:_,onMouseEnter:i&&!P?i:void 0,onMouseLeave:c&&!P?c:void 0,onFocus:l&&!P?l:void 0,"aria-label":C,title:C,tabIndex:k,dir:T?"rtl":void 0,style:p?`background-image: url(${p})`:void 0},I?r.ZP.createElement("div",null,r.ZP.createElement("span",{dir:T?"auto":void 0},"Please wait..."),r.ZP.createElement(d.Z,{color:w?"blue":"white"})):f,!P&&M&&r.ZP.createElement(u.Z,null))}},4605:(e,t,n)=>{n.d(t,{Z:()=>s});var r=n(4050),o=n(6752),d=n(9107),u=n(2340),a=n(9204);const s=(0,r.X$)((({id:e,name:t,value:n,label:s,subLabel:i,checked:c,disabled:l,round:f,blocking:h,isLoading:m,onChange:p,onCheck:g})=>{const y=(0,d.Z)(),v=(0,r.I4)((e=>{p&&p(e),g&&g(e.currentTarget.checked)}),[p,g]),b=(0,o.Z)("Checkbox",l&&"disabled",f&&"round",m&&"loading",h&&"blocking");return r.ZP.createElement("label",{className:b,dir:y.isRtl?"rtl":void 0},r.ZP.createElement("input",{type:"checkbox",id:e,name:t,value:n,checked:c,disabled:l,onChange:v}),r.ZP.createElement("div",{className:"Checkbox-main"},r.ZP.createElement("span",{className:"label",dir:"auto"},(0,u.Z)(s)),i&&r.ZP.createElement("span",{className:"subLabel",dir:"auto"},(0,u.Z)(i))),m&&r.ZP.createElement(a.Z,null))}))},3106:(e,t,n)=>{n.d(t,{Z:()=>d});var r=n(4050),o=n(2328);const d=({trigger:e,className:t,children:n,positionX:d="left",positionY:u="top",footer:a,forceOpen:s,onOpen:i,onClose:c})=>{const l=(0,r.sO)(null),f=(0,r.sO)(null),[h,m]=(0,r.eJ)(!1);return r.ZP.createElement("div",{ref:f,className:`DropdownMenu ${t||""}`,onKeyDown:e=>{const t=l.current;if(!h||40!==e.keyCode||!t)return;const n=document.activeElement,r=Array.from(t.children);n&&-1!==r.indexOf(n)||r[0].focus()}},e({onTrigger:()=>{m(!h),h?c&&c():i&&i()},isOpen:h}),r.ZP.createElement(o.Z,{ref:l,containerRef:f,isOpen:h||!!s,className:t||"",positionX:d,positionY:u,footer:a,autoClose:!0,onClose:()=>{m(!1),c&&c()},shouldSkipTransition:s},n))}},7687:(e,t,n)=>{n.d(t,{Z:()=>u});var r=n(4050),o=n(6752),d=n(9107);const u=(0,r.X$)((({ref:e,id:t,className:n,value:u,label:a,error:s,success:i,disabled:c,readOnly:l,placeholder:f,autoComplete:h,inputMode:m,maxLength:p,onChange:g,onInput:y,onKeyPress:v,onKeyDown:b,onBlur:w,onPaste:I})=>{const C=(0,d.Z)(),S=s||i||a,E=(0,o.Z)("input-group",u&&"touched",s?"error":i&&"success",c&&"disabled",l&&"disabled",S&&"with-label",n);return r.ZP.createElement("div",{className:E,dir:C.isRtl?"rtl":void 0},r.ZP.createElement("input",{ref:e,className:"form-control",type:"text",id:t,dir:"auto",value:u||"",placeholder:f,maxLength:p,autoComplete:h,inputMode:m,disabled:c,readOnly:l,onChange:g,onInput:y,onKeyPress:v,onKeyDown:b,onBlur:w,onPaste:I}),S&&r.ZP.createElement("label",{htmlFor:t},S))}))},8033:(e,t,n)=>{n.d(t,{Z:()=>d});var r=n(4050),o=n(6752);const d=({children:e,className:t,isRtl:n,onClick:d})=>{const u=(0,r.I4)((e=>{e.preventDefault(),d(e)}),[d]);return r.ZP.createElement("a",{href:"#",className:(0,o.Z)("Link",t),dir:n?"rtl":"auto",onClick:d?u:void 0},e)}},4288:(e,t,n)=>{n.d(t,{Z:()=>d});var r=n(4050),o=n(9204);const d=(0,r.X$)((({color:e="blue"})=>r.ZP.createElement("div",{className:"Loading"},r.ZP.createElement(o.Z,{color:e,withBackground:"white"===e}))))},2328:(e,t,n)=>{n.d(t,{Z:()=>h});var r=n(4050),o=n(1212),d=n(2313),u=n(8758),a=n(274),s=n(3989),i=n(6752),c=n(8674),l=n(6590),f=n(386);const h=({ref:e,containerRef:t,isOpen:n,className:h,style:m,menuStyle:p,children:g,positionX:y="left",positionY:v="top",autoClose:b=!1,footer:w,noCloseOnBackdrop:I=!1,onCloseAnimationEnd:C,onClose:S,onMouseEnter:E,onMouseLeave:P,shouldSkipTransition:M})=>{let A=(0,r.sO)(null);e&&(A=e);const k=t||A,{transitionClassNames:T}=(0,o.Z)(n,C,M,void 0,M);(0,r.d4)((()=>n&&S?(0,s.Z)(S):void 0),[n,S]),(0,l.ZP)(n,S,void 0,void 0,b),(0,a.Z)((([e])=>{void 0!==e&&(0,c.YW)(200)}),[n]);const N=(0,d.Z)(A,n,b?S:void 0,void 0,!0);(0,u.Z)(n,k,I?void 0:S);const L=(0,i.Z)("bubble menu-container custom-scroll",v,y,w&&"with-footer",T);return r.ZP.createElement("div",{className:(0,i.Z)("Menu no-selection",h),onKeyDown:n?N:void 0,onMouseEnter:E,onMouseLeave:n?P:void 0,style:m},n&&r.ZP.createElement("div",{className:"backdrop",onMouseDown:f.b}),r.ZP.createElement("div",{ref:A,className:L,style:`transform-origin: ${v} ${y};${p||""}`,onClick:b?S:void 0},g,w&&r.ZP.createElement("div",{className:"footer"},w)))}},8964:(e,t,n)=>{n.d(t,{Z:()=>u});var r=n(4050),o=n(6752),d=n(9107);const u=e=>{const{icon:t,className:n,children:u,onClick:a,href:s,download:i,disabled:c,destructive:l,ariaLabel:f}=e,h=(0,d.Z)(),m=(0,r.I4)((e=>{if(c||!a)return e.stopPropagation(),void e.preventDefault();a(e)}),[c,a]),p=(0,r.I4)((e=>{if(13===e.keyCode||32===e.keyCode)return c||!a?(e.stopPropagation(),void e.preventDefault()):void a(e)}),[c,a]),g=(0,o.Z)("MenuItem",n,c&&"disabled",l&&"destructive"),y=r.ZP.createElement(r.ZP.Fragment,null,t&&r.ZP.createElement("i",{className:`icon-${t}`,"data-char":t.startsWith("char-")?t.replace("char-",""):void 0}),u);return s?r.ZP.createElement("a",{tabIndex:0,className:g,href:s,download:i,"aria-label":f,title:f,target:s.startsWith(window.location.origin)?"_self":"_blank",rel:"noopener noreferrer",dir:h.isRtl?"rtl":void 0,onClick:a},y):r.ZP.createElement("div",{role:"button",tabIndex:0,className:g,onClick:m,onKeyDown:p,"aria-label":f,title:f,dir:h.isRtl?"rtl":void 0},y)}},8512:(e,t,n)=>{n.d(t,{Z:()=>d});var r=n(4050),o=n(9118);const d=(0,r.X$)((()=>{const[e,t]=(0,r.eJ)([]),n=(0,r.Ye)((()=>(0,o.Ds)((()=>{t([])}),700,!1)),[]),d=(0,r.I4)((r=>{if(0!==r.button)return;const o=r.currentTarget,d=o.getBoundingClientRect(),u=o.offsetWidth/2;t([...e,{x:r.clientX-d.x-u/2,y:r.clientY-d.y-u/2,size:u}]),requestAnimationFrame((()=>{n()}))}),[e,n]);return r.ZP.createElement("div",{className:"ripple-container",onMouseDown:d},e.map((({x:e,y:t,size:n})=>r.ZP.createElement("span",{style:`left: ${e}px; top: ${t}px; width: ${n}px; height: ${n}px;`}))))}))},9204:(e,t,n)=>{n.d(t,{Z:()=>d});var r=n(4050),o=n(6752);const d=({color:e="blue",withBackground:t})=>r.ZP.createElement("div",{className:(0,o.Z)("Spinner",e,t&&"with-background")},r.ZP.createElement("div",null))},3716:(e,t,n)=>{n.d(t,{Ti:()=>r,ou:()=>o,iC:()=>d,Ji:()=>u,eM:()=>a,ZT:()=>s,Cg:()=>i,S:()=>c,b_:()=>l,Vx:()=>f,sd:()=>h,Uh:()=>m,gJ:()=>p,lO:()=>g,Cy:()=>y,lW:()=>v,SG:()=>b,lF:()=>w,fo:()=>I,ee:()=>C,by:()=>S,lo:()=>P,gZ:()=>M,hT:()=>A,YQ:()=>k,rS:()=>T,t_:()=>N,Ov:()=>L,EN:()=>R,pn:()=>D,Hk:()=>O,Vk:()=>x,mo:()=>_,qU:()=>Z,ul:()=>F,NM:()=>B,Qx:()=>$,mw:()=>U,oB:()=>j,zy:()=>W,CX:()=>V,xS:()=>G,b6:()=>H,AR:()=>z,r_:()=>Q,R2:()=>K,nY:()=>J,QU:()=>q,jT:()=>Y,_m:()=>X,ks:()=>ee,l3:()=>te,u_:()=>ne,rO:()=>re,AE:()=>oe,AJ:()=>de,fK:()=>ue,V$:()=>ae,bK:()=>se,ck:()=>ie,xn:()=>ce,K7:()=>le,w7:()=>fe,z7:()=>he,qp:()=>me,Q:()=>pe,Mw:()=>ge,DC:()=>ye,Y7:()=>ve,yK:()=>be,K2:()=>we,bM:()=>Ie,ku:()=>Ce,zq:()=>Se,n:()=>Ee,pR:()=>Pe,kU:()=>Me,Y:()=>Ae,Ng:()=>ke,oG:()=>Te,wG:()=>Ne,dI:()=>Le,FM:()=>Re,uW:()=>De,g$:()=>Oe,FS:()=>xe,FD:()=>_e,aw:()=>Ze,FV:()=>Fe,Nf:()=>Be,WS:()=>$e,DU:()=>Ue,EG:()=>je,t4:()=>We,sR:()=>Ve,$O:()=>Ge,Bg:()=>He,vi:()=>ze,Db:()=>Qe,mU:()=>Ke,p3:()=>Je,It:()=>qe,Vv:()=>Ye,g:()=>Xe});const r="Telegram",o=" [Inactive]",d="Telegram WebZ",u="1.22.1",a=!1,s=!1,i=!1,c="Shoot!\nSomething went wrong, please see the error details in Dev Tools Console.",l="user_auth",f="GramJs:sessionId",h=!1,m="tt-global-state",p=30,g=5e3,y=!1,v="tt-media",b="tt-media-avatars",w="tt-media-progressive",I="tt-custom-bg",C="tt-lang-packs-v6",S=[1,5,10,50,100,500],E="undefined"!=typeof window&&window.innerHeight>=900,P=1,M=750,A=E?60:40,k=2*A,T=72,N=E?30:25,L=100,R=42,D=42,O=20,x=30,_=200,Z=500,F=20,B=!1,$=1,U=1,j=0,W=2,V=W,G=16,H=17,z=15,Q=1e4,K="editable-message-text",J="editable-message-text-modal",q=1440,Y=1150,X=1275,ee=925,te=600,ne=950,re=450,oe=1e9,de="0",ue=100,ae=1500,se=250,ie=600,ce=500,le=(Math.round((se+ie)/2),new Set(["newMessage","newScheduledMessage","deleteMessages","deleteScheduledMessages","deleteHistory"]),13),fe=11,he=160,me=120,pe=64,ge=48,ye=32,ve=64,be=64,we=160,Ie=140,Ce=80,Se=100,Ee="MEMOJI_STICKER",Pe="en",Me=200,Ae=450,ke="video/quicktime",Te=new Set(["image/png","image/gif","image/jpeg"]),Ne=new Set(["video/mp4"]),Le=new Set([...Te,...Ne]),Re="((ftp|https?):\\/\\/)?((www\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\.[a-zA-Z0-9()]{1,63})\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)",De="(@[\\w\\d_-]+)",Oe=/^tg:(\/\/)?([?=&\d\w_-]+)?/gm,xe=/^(?:https?:\/\/)?(?:t\.me\/)/gm,_e=new Set(["AU","BD","CA","CO","EG","HN","IE","IN","JO","MX","MY","NI","NZ","PH","PK","SA","SV","US"]),Ze="777000",Fe="1271266957",Be=0,$e=1,Ue=10,je=5,We=2147483646,Ve="en",Ge="android",He=["android","ios","tdesktop","macos"],ze="TelegramTips",Qe=["ar","pt-br","id","it","ko","ms","pl","es","tr"],Ke="https://bugs.telegram.org/?tag_ids=41&sort=time",Je="#A2AF8E",qe="#0F0F0F",Ye="#0a0a0a8c",Xe="rgba(90, 110, 70, 0.6)"},274:(e,t,n)=>{n.d(t,{Z:()=>d});var r=n(4050),o=n(7204);const d=(e,t,n)=>{const d=(0,o.Z)(t);return(0,r.d4)((()=>e(d||[])),t,n)}},706:(e,t,n)=>{n.d(t,{Z:()=>o});var r=n(4050);const o=(e=!1)=>{const[t,n]=(0,r.eJ)(e);return[t,(0,r.I4)((()=>{n(!0)}),[]),(0,r.I4)((()=>{n(!1)}),[])]}},5326:(e,t,n)=>{n.d(t,{Z:()=>o});var r=n(4050);const o=()=>{const[,e]=(0,r.eJ)(!1);return(0,r.I4)((()=>{e((e=>!e))}),[])}},8674:(e,t,n)=>{n.d(t,{_L:()=>o,OV:()=>d,YW:()=>s,ZP:()=>i});var r=n(4050);const o="tt-event-heavy-animation-start",d="tt-event-heavy-animation-end";let u,a=!1;const s=e=>(a||(a=!0,document.dispatchEvent(new Event(o))),u&&(clearTimeout(u),u=void 0),e&&(u=window.setTimeout((()=>{a=!1,document.dispatchEvent(new Event(d)),u=void 0}),e)),()=>{a=!1,document.dispatchEvent(new Event(d))}),i=(e,t)=>{(0,r.d4)((()=>(a&&e(),document.addEventListener(o,e),document.addEventListener(d,t),()=>{document.removeEventListener(d,t),document.removeEventListener(o,e)})),[t,e])}},6590:(e,t,n)=>{n.d(t,{Oy:()=>s,Wv:()=>l,ZP:()=>h});var r=n(4050),o=n(7361),d=n(7204),u=n(5116),a=n(782);const s=window.location.hash,i=`${window.location.pathname}${window.location.search}`,c={currentIndex:0,nextStateIndexToReplace:-1,isHistoryAltered:!1,isDisabled:!1,isEdge:!1,currentIndexes:[]},l=()=>{c.isDisabled=!0},f=()=>{c.isEdge&&setTimeout((()=>{c.isEdge=!1}),350)};function h(e,t,n,o,s=!1,l){const f=(0,r.sO)(-1),h=(0,r.sO)(!1),m=(0,d.Z)(e),p=(0,r.sO)(!0),g=(0,r.sO)([]),y=(0,d.Z)(l),v=(0,r.sO)(!1),b=(0,r.I4)(((t=!1)=>{if(l){const e=y||[];if(e.length{const e=++c.currentIndex;c.currentIndexes.push(e),window.history.pushState({index:e,state:o},"",`#${l[l.length-1]}`),g.current.push({index:e,hash:l[l.length-1]})}),0);else{const t=e.length-l.length;if(v.current)v.current=!1;else{if(l.length!==g.current.length&&t>0){const e=g.current[g.current.length-t-1];let n=t;if(e){const t=c.currentIndexes.findIndex((t=>t===e.index));n=c.currentIndexes.length-t-1}c.isHistoryAltered=!0,window.history.go(-n),g.current.splice(g.current.length-t-1,t).forEach((({index:e})=>{c.currentIndexes.splice(c.currentIndexes.indexOf(e),1)}))}l.length>0&&setTimeout((()=>{const e=++c.currentIndex;c.currentIndexes[c.currentIndexes.length-1]=e,window.history.replaceState({index:e,state:o},"",`${i}#${l[l.length-1]}`),g.current[g.current.length-1]={index:e,hash:l[l.length-1]}}),0)}}}else e&&!t&&(p.current=!1,h.current?(h.current=!1,c.currentIndexes.push(f.current)):setTimeout((()=>{const e=++c.currentIndex;c.currentIndexes.push(e),window.history[c.currentIndexes.includes(c.nextStateIndexToReplace-1)&&0!==window.history.state.index&&c.nextStateIndexToReplace===e&&!s?"replaceState":"pushState"]({index:e,state:o},""),f.current=e,s&&(c.nextStateIndexToReplace=c.currentIndex+1)}),0)),!t&&e||p.current||(f.current!==c.currentIndex&&s||(c.isHistoryAltered=!0,window.history.back(),setTimeout((()=>{c.nextStateIndexToReplace=-1}),400)),c.currentIndexes.splice(c.currentIndexes.indexOf(f.current),1),p.current=!0)}),[o,l,e,y,s]);return(0,r.d4)((()=>{const r=e=>{if(c.isHistoryAltered)return void setTimeout((()=>{c.isHistoryAltered=!1}),0);const{index:r}=e.state,o=r||0;try{const r=l?g.current[g.current.length-1].index:f.current,d=c.currentIndexes[c.currentIndexes.indexOf(r)-1];if(c.isDisabled)return;!p.current&&(0===o||o===d)||l&&(0===o||o===d)?(l&&(v.current=!0,g.current.pop()),c.currentIndexes.splice(c.currentIndexes.indexOf(r),1),t&&(c.isEdge&&(0,u.uC)().disableHistoryAnimations(),t(!c.isEdge),p.current=!0)):o===r&&p.current&&n&&!l&&(h.current=!0,c.isEdge&&(0,u.uC)().disableHistoryAnimations(),n(e.state.state))}catch(e){}},o=l?!y||!(0,a.et)(y,l):m!==e;return!c.isDisabled&&o&&b(),window.addEventListener("popstate",r),()=>window.removeEventListener("popstate",r)}),[o,b,l,e,t,n,y,m,s]),{forceClose:()=>b(!0)}}o.cj&&(window.addEventListener("touchstart",(e=>{const t=e.touches[0].pageX;(t<=300||t>=window.innerWidth-300)&&(c.isEdge=!0)})),window.addEventListener("touchend",f),window.addEventListener("popstate",f)),window.history.replaceState({index:c.currentIndex},"",i)},2313:(e,t,n)=>{n.d(t,{Z:()=>o});var r=n(4050);const o=(e,t,n,o,d)=>{const[u,a]=(0,r.eJ)(-1);return(0,r.d4)((()=>{a(-1);const n=e.current;t&&n&&!d&&(n.tabIndex=-1,n.focus())}),[e,t,d]),(0,r.I4)((t=>{const r=e.current;if(!r)return;if(13===t.keyCode&&n)return void n(u);if(38!==t.keyCode&&40!==t.keyCode)return;const d=document.activeElement,s=Array.from(o?r.querySelectorAll(o):r.children);let i=d&&s.indexOf(d)||u;if(38===t.keyCode&&i>0)i--;else if(40===t.keyCode&&i{n.d(t,{Z:()=>u});var r=n(663),o=n(5326),d=n(9290);const u=()=>{const e=(0,o.Z)();return(0,d.Z)((()=>r.ll(e)),[e]),r.i0}},8778:(e,t,n)=>{n.d(t,{Z:()=>u});var r=n(4050),o=n(9203),d=n(5326);const u=(e,t,n=!1,u=!1)=>{const a=(0,o.o5)(e,t),s=(0,d.Z)();return u&&(0,o.Qt)(s),(0,r.d4)((()=>{n||a||(0,o.$y)(e,t).then(s)}),[e,s,a,t,n]),a}},9290:(e,t,n)=>{n.d(t,{Z:()=>o});var r=n(7204);const o=(e,t)=>{const n=(0,r.Z)(t);n&&!t.some(((e,t)=>e!==n[t]))||e(n||[])}},7204:(e,t,n)=>{n.d(t,{Z:()=>o});var r=n(4050);const o=function(e,t){const n=(0,r.sO)(),{current:o}=n;return t&&void 0===e||(n.current=e),o}},1212:(e,t,n)=>{n.d(t,{Z:()=>d});var r=n(4050),o=n(6752);const d=(e=!1,t,n=!1,d="fast",u=!1)=>{const[a,s]=(0,r.eJ)(!e),i=(0,r.sO)(),[c,l]=(0,r.eJ)(e&&n);e?(s(!1),l(!0),i.current&&(window.clearTimeout(i.current),i.current=void 0)):(l(!1),a||i.current||(i.current=window.setTimeout((()=>{s(!0),t&&t(),i.current=void 0}),u?0:350)));const f=c&&!(u&&!e),h=Boolean(i.current),m=e||h;return{shouldRender:m,transitionClassNames:(0,o.Z)(d&&"opacity-transition",d,f&&"open",m&&"shown",h&&"closing")}}},8758:(e,t,n)=>{n.d(t,{Z:()=>o});var r=n(4050);function o(e,t,n){(0,r.d4)((()=>{const r=e=>{const r=t.current,o=e.target;r&&o&&(r.contains(e.target)&&!o.classList.contains("backdrop")||(e.preventDefault(),e.stopPropagation(),n&&n()))};return e&&n&&document.addEventListener("mousedown",r),()=>{document.removeEventListener("mousedown",r)}}),[e,t,n])}},5247:(e,t,n)=>{n.d(t,{Oo:()=>s,xg:()=>i,lQ:()=>h});var r=n(3716);const o=new Set(["scroll","mouseenter","mouseleave"]),d={},u=new Map,a={};function s(e,t,n,r=!1){const o=c(t,e);l(o,e,r)?function(e,t,n){a[e]||(a[e]=0,document.addEventListener(e,m)),function(e){return d[e]||(d[e]=new Map),d[e]}(e).set(t,n),function(e){const t=u.get(e);if(t)return t;const n=new Set;return u.set(e,n),n}(t).add(e),a[e]++}(o,e,n):e.addEventListener(o,n,r)}function i(e,t,n,r=!1){const o=c(t,e);l(o,e,r)?f(o,e):e.removeEventListener(o,n,r)}function c(e,t){const n=e.replace(/^on/,"").replace(/Capture$/,"").toLowerCase();return"change"===n&&"SELECT"!==t.tagName?"input":"doubleclick"===n?"dblclick":"focus"===n?"focusin":"blur"===n?"focusout":n}function l(e,t,n){return!n&&!o.has(e)&&"VIDEO"!==t.tagName&&"IFRAME"!==t.tagName}function f(e,t){a[e]--,a[e]||document.removeEventListener(e,m),d[e].delete(t),u.get(t).delete(e)}function h(e){const t=u.get(e);t&&(t.forEach((t=>f(t,e))),u.delete(e))}function m(e){const t=d[e.type];if(t){let n=!1,r=e.target;const o=()=>{n=!0},d=()=>{e.preventDefault()},u=new Proxy(e,{get:(e,t)=>"currentTarget"===t?r:"stopPropagation"===t||"stopImmediatePropagation"===t?o:"preventDefault"===t?d:Reflect.get(e,t)});for(;r&&r!==document.body;){const e=t.get(r);if(e&&(e(u),n))return;r=r.parentNode}}}r.eM&&document.addEventListener("dblclick",(()=>{console.log("DELEGATED EVENTS",{delegationRegistry:d,delegatedEventsByElement:u,documentEventCounters:a})}))},2916:(e,t,n)=>{n.d(t,{Z:()=>v});var r=n(4050),o=n(6926),d=n(3716),u=n(5247);const a=new Set(["key","ref","teactFastList","teactOrderKey"]),s=new Set(["dir"]),i={autoPlay:"autoplay",autoComplete:"autocomplete"},c={};function l(e,t,n,o,u,{skipComponentUpdate:a=!1,forceIndex:s=!1,fragment:i,moveDirection:c}={}){if(!a&&t&&n&&(0,r.op)(t)&&(0,r.op)(n)&&!(0,r.k)(t,n)&&(n=function(e,t){return e.componentInstance.props=t.componentInstance.props,(0,r.SO)(e.componentInstance)}(t,n)),!a&&n&&(0,r.op)(n)&&n.componentInstance.isMounted&&h(n,o,u,e),t===n)return n;if(!t&&n){(0,r.op)(n)&&(n=f(n,o,u,e));const t=m(n);(0,r.CD)(n,t),s&&e.childNodes[u]?e.insertBefore(t,e.childNodes[u]):(i||e).appendChild(t)}else if(t&&!n)e.removeChild((0,r.U9)(t)),(0,r.Zb)(t);else if(t&&n)if((0,r.k)(t,n)){(0,r.op)(n)&&(n=f(n,o,u,e));const d=m(n);(0,r.CD)(n,d),e.replaceChild(d,(0,r.U9)(t)),(0,r.Zb)(t)}else{const o=(0,r.op)(t)&&(0,r.op)(n);if(o||(0,r.CD)(n,(0,r.U9)(t)),(0,r.O_)(t)&&(0,r.O_)(n)){if(c){const n=(0,r.U9)(t),o=e.childNodes["up"===c?u:u+1];o?e.insertBefore(n,o):(i||e).appendChild(n)}o||function(e,t,n){const r=Object.keys(e.props),o=Object.keys(t.props);r.forEach((r=>{void 0!==e.props[r]&&void 0===t.props[r]&&y(n,r,e.props[r])})),o.forEach((r=>{void 0!==t.props[r]&&e.props[r]!==t.props[r]&&(void 0===e.props[r]?g(n,r,t.props[r]):function(e,t,n,r){"value"===t?e.value=void 0!==r?r:"":(y(e,t,n),g(e,t,r))}(n,r,e.props[r],t.props[r]))}))}(t,n,(0,r.U9)(t)),n.children=function(e,t,n){if(t.props.teactFastList)return function(e,t,n){const o=new Set(t.children.map((e=>{const t="props"in e&&e.props.key;return d.eM&&(0,r.O_)(e)&&!t&&console.warn("Missing `key` in `teactFastList`"),t})));let u=0;const a=e.children.reduce(((e,r,d)=>{let a="props"in r?r.props.key:void 0;if(a&&!o.has(a))return l(n,r,void 0,t,-1),e;if(!a){const o=t.children[d],u=o&&"props"in o?o.props.key:void 0;if(!o||u)return l(n,r,void 0,t,-1),e;a=`__indexKey#${d}`}return e[a]={$element:r,index:u++,order:"props"in r?r.props.teactOrderKey:void 0},e}),{});let s,i,c=[],f=0;return t.children.forEach(((e,r)=>{const o="props"in e?e.props.key:`__indexKey#${r}`,d=a[o];if(!d)return s||(s=[],i=r),void s.push(e);s&&(c=c.concat(p(s,i,n,t)),i=void 0,s=void 0);const u="props"in e?e.props.teactOrderKey:void 0,h=d.index!==f&&d.order!==u,m=h&&f>d.index;h&&!m||f++,c.push(l(n,d.$element,e,t,r,{forceIndex:!0,...h&&{moveDirection:m?"down":"up"}}))})),s&&(c=c.concat(p(s,i,n,t))),c}(e,t,n);const o=Math.max(e.children.length,t.children.length),u=[],a=t.children.length>e.children.length+1?document.createDocumentFragment():void 0;for(let r=0;r=e.children.length?{fragment:a}:void 0);o&&u.push(o)}return a&&n.appendChild(a),u}(t,n,o?e:(0,r.U9)(t))}}return n}function f(e,t,n,o){if(!(0,r.op)(e))return e;const{componentInstance:d}=e;if(!d.isMounted){h(e=(0,r.Hb)(d),t,n,o);const u=e.children[0];(0,r.op)(u)&&(e.children=[f(u,e,0,o)]),d.isMounted=!0}return e}function h(e,t,n,r){const{componentInstance:o}=e;o.onUpdate=()=>{t.children[n]=l(r,t.children[n],o.$element,t,n,{skipComponentUpdate:!0})}}function m(e){if((0,r.V2)(e))return document.createTextNode("");if((0,r.iB)(e))return document.createTextNode(e.value);if((0,r.op)(e))return m(e.children[0]);const{tag:t,props:n,children:o=[]}=e,d=document.createElement(t);return"object"==typeof n.ref&&(n.ref.current=d),Object.keys(n).forEach((e=>{g(d,e,n[e])})),e.children=o.map(((t,n)=>l(d,void 0,t,e,n))),d}function p(e,t,n,r){if(1===e.length)return[l(n,void 0,e[0],r,t,{forceIndex:!0})];if(e.length>1){const o=document.createDocumentFragment(),d=e.map((e=>l(n,void 0,e,r,t,{fragment:o})));return n.childNodes[t]?n.insertBefore(o,n.childNodes[t]):n.appendChild(o),d}throw new Error("Unexpected input")}function g(e,t,n){void 0!==n&&("className"===t?e.className=n:"value"===t?e.value=n:"style"===t?e.style.cssText=n:t.startsWith("on")?(0,u.Oo)(e,t,n,t.endsWith("Capture")):t.startsWith("data-")||s.has(t)?e.setAttribute(t,n):a.has(t)||(e[i[t]||t]=n))}function y(e,t,n){"className"===t?e.className="":"value"===t?e.value="":"style"===t?e.style.cssText="":t.startsWith("on")?(0,u.xg)(e,t,n,t.endsWith("Capture")):t.startsWith("data-")||s.has(t)?e.removeAttribute(t):a.has(t)||delete e[i[t]||t]}const v={render:function(e,t){if(!t)return;let n=t.getAttribute("data-teact-head-id");n||(n=(0,o.Z)(c),c[n]={children:[]},t.setAttribute("data-teact-head-id",n));const r=c[n];r.children=[l(t,r.children[0],e,r,0)]}}},4050:(e,t,n)=>{n.d(t,{V2:()=>f,iB:()=>h,op:()=>p,O_:()=>g,SO:()=>S,k:()=>E,Zb:()=>P,Hb:()=>M,U9:()=>T,CD:()=>N,eJ:()=>L,d4:()=>D,bt:()=>O,Ye:()=>x,I4:()=>_,sO:()=>Z,X$:()=>F,ZP:()=>B});var r=n(3716),o=n(9118),d=n(782),u=n(275),a=n(3592),s=n(5247);let i;!function(e){e[e.Empty=0]="Empty",e[e.Text=1]="Text",e[e.Tag=2]="Tag",e[e.Component=3]="Component"}(i||(i={}));const c=Symbol("Fragment");let l;function f(e){return e.type===i.Empty}function h(e){return e.type===i.Text}function m(e){return e.type===i.Tag}function p(e){return e.type===i.Component}function g(e){return m(e)||p(e)}function y(e,t,...n){return t||(t={}),n=(0,d.xH)(n),e===c?n:"function"==typeof e?function(e,t,n){let r;0===n.length?r=void 0:1===n.length?[r]=n:r=n;const o={$element:{},Component:e,name:e.name,props:{...t,...r&&{children:r}},isMounted:!1,hooks:{state:{cursor:0,byCursor:[]},effects:{cursor:0,byCursor:[]},memos:{cursor:0,byCursor:[]}}};return o.$element=v(o),o.$element}(e,t,n):function(e,t,n){return{type:i.Tag,tag:e,props:t,children:b(n).map(I)}}(e,t,n)}function v(e,t=[]){const{props:n}=e;return{componentInstance:e,type:i.Component,props:n,children:t}}function b(e){let t=e.length-1;for(;t>=0&&w(e[t]);t--);return t+17&&console.warn(`[Teact] Slow component render: ${n}, ${Math.round(t)} ms`),C[n].renderTimes.push(t),C[n].renderCount++}}catch(t){(0,a.S)(t),o=e.renderedValue}if(e.isMounted&&o===e.renderedValue)return e.$element;e.renderedValue=o;const d=I(o);return e.$element=v(e,[d]),e.$element}function E(e,t){return typeof e!=typeof t||e.type!==t.type||(h(e)&&h(t)?e.value!==t.value:m(e)&&m(t)?e.tag!==t.tag||e.props.key!==t.props.key:!(!p(e)||!p(t)||e.componentInstance.Component===t.componentInstance.Component&&e.props.key===t.props.key))}function P(e){var t;g(e)&&(p(e)?(t=e.componentInstance).isMounted&&(t.hooks.memos.byCursor.forEach((e=>{e.current=null})),t.hooks.effects.byCursor.forEach((({cleanup:e})=>{if("function"==typeof e)try{e()}catch(e){(0,a.S)(e)}})),t.isMounted=!1,function(e){e.hooks.effects.byCursor.forEach((e=>{e.cleanup=null,e.effect=null,e.dependencies=null})),e.hooks.state.byCursor.forEach((e=>{e.value=null,e.nextValue=null,e.setter=null})),e.hooks.memos.byCursor.forEach((e=>{e.dependencies=null})),e.hooks=null,e.$element=null,e.renderedValue=null,e.Component=null,e.props=null,e.forceUpdate=null,e.onUpdate=null}(t)):e.target&&((0,s.lQ)(e.target),e.target=null),e.children.forEach(P))}function M(e){return S(e),e.isMounted=!0,e.$element}function A(e){e.isMounted&&(e.hooks.state.byCursor.forEach((e=>{e.value=e.nextValue})),e.prepareForFrame=(0,o.wT)((()=>A(e))),e.forceUpdate=(0,o.mS)((()=>k(e))))}function k(e){if(!e.isMounted||!e.onUpdate)return;const t=e.$element;S(e),e.$element!==t&&e.onUpdate()}function T(e){return p(e)?T(e.children[0]):e.target}function N(e,t){p(e)?N(e.children[0],t):e.target=t}function L(e){const{cursor:t,byCursor:n}=l.hooks.state;var d;return void 0===n[t]&&(n[t]={value:e,nextValue:e,setter:(d=l,e=>{n[t].nextValue!==e&&(n[t].nextValue="function"==typeof e?e(n[t].value):e,d.prepareForFrame&&d.forceUpdate||(d.prepareForFrame=(0,o.wT)((()=>A(d))),d.forceUpdate=(0,o.mS)((()=>k(d)))),d.prepareForFrame(),d.forceUpdate(),r.ZT&&"TeactNContainer"!==d.name&&console.log("[Teact.useState]",d.name,d.Component&&d.Component.DEBUG_contentComponentName?`> ${d.Component.DEBUG_contentComponentName}`:"",`Forced update at cursor #${t}, next value: `,n[t].nextValue))})}),l.hooks.state.cursor++,[n[t].value,n[t].setter]}function R(e,t,n,r,o){const{cursor:d,byCursor:u}=l.hooks.effects,s=l;function i(){if(!s.isMounted)return;const{cleanup:e}=u[d];if("function"==typeof e)try{e()}catch(e){(0,a.S)(e)}}function c(){s.isMounted&&(u[d].cleanup=n())}if(void 0!==u[d]&&r&&u[d].dependencies){if(r.some(((e,t)=>e!==u[d].dependencies[t]))){if(o){const e=r.reduce(((e,t,n)=>{const r=u[d].dependencies[n];return t!==r&&e.push(`${n}: ${r} => ${t}`),e}),[]);console.log("[Teact]",o,"Effect caused by dependencies.",e.join(", "))}t(i),e(c)}}else t(i),e(c);u[d]={effect:n,dependencies:r,cleanup:u[d]?u[d].cleanup:void 0},l.hooks.effects.cursor++}function D(e,t,n){return R(o.T2,o.D0,e,t,n)}function O(e,t,n){return R(o.R3,o.zD,e,t,n)}function x(e,t,n){const{cursor:o,byCursor:d}=l.hooks.memos;let{current:a}=d[o]||{};return(void 0===d[o]||t.some(((e,t)=>e!==d[o].dependencies[t])))&&(r.eM&&n&&console.log(`[Teact.useMemo] ${l.name} (${n}): Update is caused by:`,d[o]?(0,u.c)(t,d[o].dependencies).join(", "):"[first render]"),a=e()),d[o]={current:a,dependencies:t},l.hooks.memos.cursor++,a}function _(e,t){return x((()=>e),t)}function Z(e){return x((()=>({current:e})),[])}function F(e,t=u.Z,n){return function(o){const d=Z(o),a=Z();return(!a.current||d.current&&!t(d.current,o))&&(r.eM&&n&&console.log(`[Teact.memo] ${e.name} (${n}): Update is caused by:`,(0,u.c)(d.current,o).join(", ")),d.current=o,a.current=y(e,o)),a.current}}document.addEventListener("dblclick",(()=>{console.log("COMPONENTS",(0,d.Xo)(Object.values(C),"renderCount","desc"))}));const B={createElement:y,Fragment:c}},5116:(e,t,n)=>{n.d(t,{ZP:()=>f,R3:()=>w,Rd:()=>I,uC:()=>C,Q6:()=>S,ll:()=>E,Iq:()=>P,c$:()=>M});var r=n(4050),o=n(3716),d=n(5326),u=n(6926),a=n(9118),s=n(275),i=n(782),c=n(3592);function l(){return(l=Object.assign||function(e){for(var t=1;t7&&console.warn(`[TeactN] Slow containers update: ${Math.round(t)} ms`)}}],g={},y=new Map;function v(){p.forEach((e=>e(h)))}const b=(0,a.mS)(v);function w(e,t=!1){"object"==typeof e&&e!==h&&(h=e,t?v():b())}function I(){return h}function C(){return g}function S(e,t){m[e]||(m[e]=[],g[e]=(t,n=!1)=>{!function(e,t,n){m[e]&&m[e].forEach((e=>{const r=e(h,g,t);r&&w(r,n)}))}(e,t,n)}),m[e].push(t)}function E(e){p.push(e)}function P(e){const t=p.indexOf(e);-1!==t&&p.splice(t,1)}function M(e=(()=>({})),t=(()=>({}))){return n=>function o(a){o.DEBUG_contentComponentName=n.name;const[i]=(0,r.eJ)((0,u.Z)(y)),f=(0,d.Z)();(0,r.d4)((()=>()=>{y.delete(i)}),[i]);let m=y.get(i);if(m||(m={mapStateToProps:e,mapReducersToProps:t,ownProps:a,areMappedPropsChanged:!1,forceUpdate:f,DEBUG_updates:0,DEBUG_componentName:n.name},y.set(i,m)),m.areMappedPropsChanged&&(m.areMappedPropsChanged=!1),!m.mappedProps||!(0,s.Z)(m.ownProps,a)){m.ownProps=a;try{m.mappedProps={...e(h,a),...t(w,g)}}catch(e){(0,c.S)(e)}}return r.ZP.createElement(n,l({},m.mappedProps,a))}}o.eM&&(window.getGlobal=I,document.addEventListener("dblclick",(()=>{console.log("GLOBAL CONTAINERS",(0,i.Xo)(Array.from(y.values()).map((({DEBUG_componentName:e,DEBUG_updates:t})=>({DEBUG_componentName:e,DEBUG_updates:t}))),"DEBUG_updates","desc"))})))},3681:(e,t,n)=>{n.d(t,{l:()=>d,Z:()=>u});const r=/\uFE0F/g,o=String.fromCharCode(8205);function d(e){return e.indexOf(o)<0?e.replace(r,""):e}const u=/(?:\ud83d\udc68\ud83c\udffb\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc68\ud83c\udffc\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc68\ud83c\udffd\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc68\ud83c\udffe\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc68\ud83c\udfff\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffb\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffb\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffc\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffc\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffd\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffd\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffe\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffe\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udfff\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udfff\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udffb\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83e\uddd1\ud83c[\udffc-\udfff]|\ud83e\uddd1\ud83c\udffc\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83e\uddd1\ud83c[\udffb\udffd-\udfff]|\ud83e\uddd1\ud83c\udffd\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83e\uddd1\ud83c[\udffb\udffc\udffe\udfff]|\ud83e\uddd1\ud83c\udffe\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83e\uddd1\ud83c[\udffb-\udffd\udfff]|\ud83e\uddd1\ud83c\udfff\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83e\uddd1\ud83c[\udffb-\udffe]|\ud83d\udc68\ud83c\udffb\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc68\ud83c\udffb\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffc-\udfff]|\ud83d\udc68\ud83c\udffc\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc68\ud83c\udffc\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb\udffd-\udfff]|\ud83d\udc68\ud83c\udffd\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc68\ud83c\udffd\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb\udffc\udffe\udfff]|\ud83d\udc68\ud83c\udffe\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc68\ud83c\udffe\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb-\udffd\udfff]|\ud83d\udc68\ud83c\udfff\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc68\ud83c\udfff\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb-\udffe]|\ud83d\udc69\ud83c\udffb\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffb\u200d\u2764\ufe0f\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffb\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffc-\udfff]|\ud83d\udc69\ud83c\udffb\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffc-\udfff]|\ud83d\udc69\ud83c\udffc\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffc\u200d\u2764\ufe0f\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffc\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb\udffd-\udfff]|\ud83d\udc69\ud83c\udffc\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffb\udffd-\udfff]|\ud83d\udc69\ud83c\udffd\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffd\u200d\u2764\ufe0f\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffd\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb\udffc\udffe\udfff]|\ud83d\udc69\ud83c\udffd\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffb\udffc\udffe\udfff]|\ud83d\udc69\ud83c\udffe\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffe\u200d\u2764\ufe0f\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffe\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb-\udffd\udfff]|\ud83d\udc69\ud83c\udffe\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffb-\udffd\udfff]|\ud83d\udc69\ud83c\udfff\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udfff\u200d\u2764\ufe0f\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udfff\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb-\udffe]|\ud83d\udc69\ud83c\udfff\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffb-\udffe]|\ud83e\uddd1\ud83c\udffb\u200d\u2764\ufe0f\u200d\ud83e\uddd1\ud83c[\udffc-\udfff]|\ud83e\uddd1\ud83c\udffb\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udffc\u200d\u2764\ufe0f\u200d\ud83e\uddd1\ud83c[\udffb\udffd-\udfff]|\ud83e\uddd1\ud83c\udffc\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udffd\u200d\u2764\ufe0f\u200d\ud83e\uddd1\ud83c[\udffb\udffc\udffe\udfff]|\ud83e\uddd1\ud83c\udffd\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udffe\u200d\u2764\ufe0f\u200d\ud83e\uddd1\ud83c[\udffb-\udffd\udfff]|\ud83e\uddd1\ud83c\udffe\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udfff\u200d\u2764\ufe0f\u200d\ud83e\uddd1\ud83c[\udffb-\udffe]|\ud83e\uddd1\ud83c\udfff\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83d\udc68\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68|\ud83d\udc69\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d[\udc68\udc69]|\ud83d\udc68\u200d\u2764\ufe0f\u200d\ud83d\udc68|\ud83d\udc69\u200d\u2764\ufe0f\u200d\ud83d[\udc68\udc69]|\ud83e\uddd1\u200d\ud83e\udd1d\u200d\ud83e\uddd1|\ud83d\udc6b\ud83c[\udffb-\udfff]|\ud83d\udc6c\ud83c[\udffb-\udfff]|\ud83d\udc6d\ud83c[\udffb-\udfff]|\ud83d\udc8f\ud83c[\udffb-\udfff]|\ud83d\udc91\ud83c[\udffb-\udfff]|\ud83d[\udc6b-\udc6d\udc8f\udc91])|(?:\ud83d[\udc68\udc69]|\ud83e\uddd1)(?:\ud83c[\udffb-\udfff])?\u200d(?:\u2695\ufe0f|\u2696\ufe0f|\u2708\ufe0f|\ud83c[\udf3e\udf73\udf7c\udf84\udf93\udfa4\udfa8\udfeb\udfed]|\ud83d[\udcbb\udcbc\udd27\udd2c\ude80\ude92]|\ud83e[\uddaf-\uddb3\uddbc\uddbd])|(?:\ud83c[\udfcb\udfcc]|\ud83d[\udd74\udd75]|\u26f9)((?:\ud83c[\udffb-\udfff]|\ufe0f)\u200d[\u2640\u2642]\ufe0f)|(?:\ud83c[\udfc3\udfc4\udfca]|\ud83d[\udc6e\udc70\udc71\udc73\udc77\udc81\udc82\udc86\udc87\ude45-\ude47\ude4b\ude4d\ude4e\udea3\udeb4-\udeb6]|\ud83e[\udd26\udd35\udd37-\udd39\udd3d\udd3e\uddb8\uddb9\uddcd-\uddcf\uddd4\uddd6-\udddd])(?:\ud83c[\udffb-\udfff])?\u200d[\u2640\u2642]\ufe0f|(?:\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc68\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d[\udc66\udc67]|\ud83c\udff3\ufe0f\u200d\u26a7\ufe0f|\ud83c\udff3\ufe0f\u200d\ud83c\udf08|\ud83d\ude36\u200d\ud83c\udf2b\ufe0f|\u2764\ufe0f\u200d\ud83d\udd25|\u2764\ufe0f\u200d\ud83e\ude79|\ud83c\udff4\u200d\u2620\ufe0f|\ud83d\udc15\u200d\ud83e\uddba|\ud83d\udc3b\u200d\u2744\ufe0f|\ud83d\udc41\u200d\ud83d\udde8|\ud83d\udc68\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\ud83d[\udc66\udc67]|\ud83d\udc6f\u200d\u2640\ufe0f|\ud83d\udc6f\u200d\u2642\ufe0f|\ud83d\ude2e\u200d\ud83d\udca8|\ud83d\ude35\u200d\ud83d\udcab|\ud83e\udd3c\u200d\u2640\ufe0f|\ud83e\udd3c\u200d\u2642\ufe0f|\ud83e\uddde\u200d\u2640\ufe0f|\ud83e\uddde\u200d\u2642\ufe0f|\ud83e\udddf\u200d\u2640\ufe0f|\ud83e\udddf\u200d\u2642\ufe0f|\ud83d\udc08\u200d\u2b1b)|[#*0-9]\ufe0f?\u20e3|(?:[©®\u2122\u265f]\ufe0f)|(?:\ud83c[\udc04\udd70\udd71\udd7e\udd7f\ude02\ude1a\ude2f\ude37\udf21\udf24-\udf2c\udf36\udf7d\udf96\udf97\udf99-\udf9b\udf9e\udf9f\udfcd\udfce\udfd4-\udfdf\udff3\udff5\udff7]|\ud83d[\udc3f\udc41\udcfd\udd49\udd4a\udd6f\udd70\udd73\udd76-\udd79\udd87\udd8a-\udd8d\udda5\udda8\uddb1\uddb2\uddbc\uddc2-\uddc4\uddd1-\uddd3\udddc-\uddde\udde1\udde3\udde8\uddef\uddf3\uddfa\udecb\udecd-\udecf\udee0-\udee5\udee9\udef0\udef3]|[\u203c\u2049\u2139\u2194-\u2199\u21a9\u21aa\u231a\u231b\u2328\u23cf\u23ed-\u23ef\u23f1\u23f2\u23f8-\u23fa\u24c2\u25aa\u25ab\u25b6\u25c0\u25fb-\u25fe\u2600-\u2604\u260e\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262a\u262e\u262f\u2638-\u263a\u2640\u2642\u2648-\u2653\u2660\u2663\u2665\u2666\u2668\u267b\u267f\u2692-\u2697\u2699\u269b\u269c\u26a0\u26a1\u26a7\u26aa\u26ab\u26b0\u26b1\u26bd\u26be\u26c4\u26c5\u26c8\u26cf\u26d1\u26d3\u26d4\u26e9\u26ea\u26f0-\u26f5\u26f8\u26fa\u26fd\u2702\u2708\u2709\u270f\u2712\u2714\u2716\u271d\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u2764\u27a1\u2934\u2935\u2b05-\u2b07\u2b1b\u2b1c\u2b50\u2b55\u3030\u303d\u3297\u3299])(?:\ufe0f|(?!\ufe0e))|(?:(?:\ud83c[\udfcb\udfcc]|\ud83d[\udd74\udd75\udd90]|[\u261d\u26f7\u26f9\u270c\u270d])(?:\ufe0f|(?!\ufe0e))|(?:\ud83c[\udf85\udfc2-\udfc4\udfc7\udfca]|\ud83d[\udc42\udc43\udc46-\udc50\udc66-\udc69\udc6e\udc70-\udc78\udc7c\udc81-\udc83\udc85-\udc87\udcaa\udd7a\udd95\udd96\ude45-\ude47\ude4b-\ude4f\udea3\udeb4-\udeb6\udec0\udecc]|\ud83e[\udd0c\udd0f\udd18-\udd1c\udd1e\udd1f\udd26\udd30-\udd39\udd3d\udd3e\udd77\uddb5\uddb6\uddb8\uddb9\uddbb\uddcd-\uddcf\uddd1-\udddd]|[\u270a\u270b]))(?:\ud83c[\udffb-\udfff])?|(?:\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc65\udb40\udc6e\udb40\udc67\udb40\udc7f|\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc73\udb40\udc63\udb40\udc74\udb40\udc7f|\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc77\udb40\udc6c\udb40\udc73\udb40\udc7f|\ud83c\udde6\ud83c[\udde8-\uddec\uddee\uddf1\uddf2\uddf4\uddf6-\uddfa\uddfc\uddfd\uddff]|\ud83c\udde7\ud83c[\udde6\udde7\udde9-\uddef\uddf1-\uddf4\uddf6-\uddf9\uddfb\uddfc\uddfe\uddff]|\ud83c\udde8\ud83c[\udde6\udde8\udde9\uddeb-\uddee\uddf0-\uddf5\uddf7\uddfa-\uddff]|\ud83c\udde9\ud83c[\uddea\uddec\uddef\uddf0\uddf2\uddf4\uddff]|\ud83c\uddea\ud83c[\udde6\udde8\uddea\uddec\udded\uddf7-\uddfa]|\ud83c\uddeb\ud83c[\uddee-\uddf0\uddf2\uddf4\uddf7]|\ud83c\uddec\ud83c[\udde6\udde7\udde9-\uddee\uddf1-\uddf3\uddf5-\uddfa\uddfc\uddfe]|\ud83c\udded\ud83c[\uddf0\uddf2\uddf3\uddf7\uddf9\uddfa]|\ud83c\uddee\ud83c[\udde8-\uddea\uddf1-\uddf4\uddf6-\uddf9]|\ud83c\uddef\ud83c[\uddea\uddf2\uddf4\uddf5]|\ud83c\uddf0\ud83c[\uddea\uddec-\uddee\uddf2\uddf3\uddf5\uddf7\uddfc\uddfe\uddff]|\ud83c\uddf1\ud83c[\udde6-\udde8\uddee\uddf0\uddf7-\uddfb\uddfe]|\ud83c\uddf2\ud83c[\udde6\udde8-\udded\uddf0-\uddff]|\ud83c\uddf3\ud83c[\udde6\udde8\uddea-\uddec\uddee\uddf1\uddf4\uddf5\uddf7\uddfa\uddff]|\ud83c\uddf4\ud83c\uddf2|\ud83c\uddf5\ud83c[\udde6\uddea-\udded\uddf0-\uddf3\uddf7-\uddf9\uddfc\uddfe]|\ud83c\uddf6\ud83c\udde6|\ud83c\uddf7\ud83c[\uddea\uddf4\uddf8\uddfa\uddfc]|\ud83c\uddf8\ud83c[\udde6-\uddea\uddec-\uddf4\uddf7-\uddf9\uddfb\uddfd-\uddff]|\ud83c\uddf9\ud83c[\udde6\udde8\udde9\uddeb-\udded\uddef-\uddf4\uddf7\uddf9\uddfb\uddfc\uddff]|\ud83c\uddfa\ud83c[\udde6\uddec\uddf2\uddf3\uddf8\uddfe\uddff]|\ud83c\uddfb\ud83c[\udde6\udde8\uddea\uddec\uddee\uddf3\uddfa]|\ud83c\uddfc\ud83c[\uddeb\uddf8]|\ud83c\uddfd\ud83c\uddf0|\ud83c\uddfe\ud83c[\uddea\uddf9]|\ud83c\uddff\ud83c[\udde6\uddf2\uddfc]|\ud83c[\udccf\udd8e\udd91-\udd9a\udde6-\uddff\ude01\ude32-\ude36\ude38-\ude3a\ude50\ude51\udf00-\udf20\udf2d-\udf35\udf37-\udf7c\udf7e-\udf84\udf86-\udf93\udfa0-\udfc1\udfc5\udfc6\udfc8\udfc9\udfcf-\udfd3\udfe0-\udff0\udff4\udff8-\udfff]|\ud83d[\udc00-\udc3e\udc40\udc44\udc45\udc51-\udc65\udc6a\udc6f\udc79-\udc7b\udc7d-\udc80\udc84\udc88-\udc8e\udc90\udc92-\udca9\udcab-\udcfc\udcff-\udd3d\udd4b-\udd4e\udd50-\udd67\udda4\uddfb-\ude44\ude48-\ude4a\ude80-\udea2\udea4-\udeb3\udeb7-\udebf\udec1-\udec5\uded0-\uded2\uded5-\uded7\udeeb\udeec\udef4-\udefc\udfe0-\udfeb]|\ud83e[\udd0d\udd0e\udd10-\udd17\udd1d\udd20-\udd25\udd27-\udd2f\udd3a\udd3c\udd3f-\udd45\udd47-\udd76\udd78\udd7a-\uddb4\uddb7\uddba\uddbc-\uddcb\uddd0\uddde-\uddff\ude70-\ude74\ude78-\ude7a\ude80-\ude86\ude90-\udea8\udeb0-\udeb6\udec0-\udec2\uded0-\uded6]|[\u23e9-\u23ec\u23f0\u23f3\u267e\u26ce\u2705\u2728\u274c\u274e\u2753-\u2755\u2795-\u2797\u27b0\u27bf\ue50a])|\ufe0f/g},1363:(e,t,n)=>{var r=n(5116),o=n(1226),d=n(3716),u=n(7361),a=n(8406),s=n(9524),i=n(7358),c=n(4688),l=n(1622);(0,r.Q6)("initApi",((e,t)=>{(async()=>{d.Cg||(await(0,c.Qw)(),(0,c.f3)()),(0,o.g8)(t.apiUpdate,{userAgent:navigator.userAgent,platform:u.Lt,sessionData:(0,c.K8)(),isTest:window.location.search.includes("test"),isMovSupported:u.pA})})()})),(0,r.Q6)("setAuthPhoneNumber",((e,t,n)=>{const{phoneNumber:r}=n;return(0,o.t9)("provideAuthPhoneNumber",r.replace(/[^\d]/g,"")),{...e,authIsLoading:!0,authError:void 0}})),(0,r.Q6)("setAuthCode",((e,t,n)=>{const{code:r}=n;return(0,o.t9)("provideAuthCode",r),{...e,authIsLoading:!0,authError:void 0}})),(0,r.Q6)("setAuthPassword",((e,t,n)=>{const{password:r}=n;return(0,o.t9)("provideAuthPassword",r),{...e,authIsLoading:!0,authError:void 0}})),(0,r.Q6)("uploadProfilePhoto",((e,t,n)=>{const{file:r}=n;(0,o.t9)("uploadProfilePhoto",r)})),(0,r.Q6)("signUp",((e,t,n)=>{const{firstName:r,lastName:d}=n;return(0,o.t9)("provideAuthRegistration",{firstName:r,lastName:d}),{...e,authIsLoading:!0,authError:void 0}})),(0,r.Q6)("returnToAuthPhoneNumber",(e=>((0,o.t9)("restartAuth"),{...e,authError:void 0}))),(0,r.Q6)("goToAuthQrCode",(e=>((0,o.t9)("restartAuthWithQr"),{...e,authIsLoadingQrCode:!0,authError:void 0}))),(0,r.Q6)("saveSession",((e,t,n)=>{const{sessionData:r}=n;r?(0,c.wX)(n.sessionData,e.currentUserId):(0,c.jv)()})),(0,r.Q6)("signOut",(()=>{(async()=>{try{await(0,a.r1)(),await(0,o.t9)("destroy"),await(0,l.I)(!1)}catch(e){}(0,r.uC)().reset()})()})),(0,r.Q6)("reset",(()=>{(0,c.jv)(),s.clear(d.lW),s.clear(d.SG),s.clear(d.lF),s.clear(d.fo);const e=d.ee.replace(/\d+$/,""),t=(d.ee.match(/\d+$/)||[0])[0];for(let n=0;n{(async()=>{await(0,o.t9)("disconnect")})()})),(0,r.Q6)("loadNearestCountry",(e=>{"connectionStateReady"===e.connectionState&&(async()=>{const e=await(0,o.t9)("fetchNearestCountry");(0,r.R3)({...(0,r.Rd)(),authNearestCountry:e})})()})),(0,r.Q6)("setDeviceToken",((e,t,n)=>{(0,r.R3)({...e,push:{deviceToken:n,subscribedAt:Date.now()}})})),(0,r.Q6)("deleteDeviceToken",(e=>{const t={...e};delete t.push,(0,r.R3)(t)}))},9667:(e,t,n)=>{var r=n(5116),o=n(1713),d=n(3716),u=n(1226),a=n(782),s=n(8406),i=n(663),c=n(8085),l=n(1752),f=n(2858);function h(e,{visibility:t,allowedIds:n,deniedIds:r}){const{users:{byId:o},chats:{byId:d}}=e,u={visibility:t};let a,s;const i=e=>{if(!(0,f.YC)(e))return;const{id:t,accessHash:n}=o[e]||{};return t?{id:t,accessHash:n}:void 0},c=e=>{if((0,f.YC)(e))return;const t=d[e];return t?{id:t.id}:void 0};return"contacts"!==t&&"nobody"!==t||(a=n.map(i).filter(Boolean),s=n.map(c).filter(Boolean),a.length>0&&(u.allowedUsers=a),s.length>0&&(u.allowedChats=s)),"everybody"!==t&&"contacts"!==t||(a=r.map(i).filter(Boolean),s=r.map(c).filter(Boolean),a.length>0&&(u.blockedUsers=a),s.length>0&&(u.blockedChats=s)),u}(0,r.Q6)("updateProfile",((e,t,n)=>{const{photo:d,firstName:a,lastName:s,bio:i,username:f}=n;(async()=>{const{currentUserId:t}=e;if(t){if((0,r.R3)({...(0,r.Rd)(),profileEdit:{progress:o.rN.InProgress}}),d&&await(0,u.t9)("updateProfilePhoto",d),(a||s||i)&&await(0,u.t9)("updateProfile",{firstName:a,lastName:s,about:i})){e=(0,r.Rd)();const n=t&&(0,c.dy)(e,t);n&&(0,r.R3)((0,l.Nq)(e,n.id,{firstName:a,lastName:s,fullInfo:{...n.fullInfo,bio:i}}))}f&&await(0,u.t9)("updateUsername",f)&&t&&(0,r.R3)((0,l.Nq)((0,r.Rd)(),t,{username:f})),(0,r.R3)({...(0,r.Rd)(),profileEdit:{progress:o.rN.Complete}})}})()})),(0,r.Q6)("checkUsername",((e,t,n)=>{const{username:d}=n;(async()=>{if(e.profileEdit&&e.profileEdit.progress===o.rN.InProgress)return;(0,r.R3)({...e,profileEdit:{progress:e.profileEdit?e.profileEdit.progress:o.rN.Idle,isUsernameAvailable:void 0}});const t=await(0,u.t9)("checkUsername",d);e=(0,r.Rd)(),(0,r.R3)({...e,profileEdit:{...e.profileEdit,isUsernameAvailable:t}})})()})),(0,r.Q6)("loadWallpapers",(()=>{(async()=>{const e=await(0,u.t9)("fetchWallpapers");if(!e)return;const t=(0,r.Rd)();(0,r.R3)({...t,settings:{...t.settings,loadedWallpapers:e.wallpapers}})})()})),(0,r.Q6)("uploadWallpaper",((e,t,n)=>{const d=n,a=URL.createObjectURL(d);(0,r.R3)({...e,settings:{...e.settings,loadedWallpapers:[{slug:o.mp,document:{fileName:"",size:d.size,mimeType:d.type,previewBlobUrl:a}},...e.settings.loadedWallpapers||[]]}}),(async()=>{const t=await(0,u.t9)("uploadWallpaper",d);if(!t)return;const{wallpaper:n}=t;if(!(e=(0,r.Rd)()).settings.loadedWallpapers)return;const s=e.settings.loadedWallpapers[0];if(!s||s.slug!==o.mp)return;const i={...n,document:{...n.document,previewBlobUrl:a}};(0,r.R3)({...e,settings:{...e.settings,loadedWallpapers:[i,...e.settings.loadedWallpapers.slice(1)]}})})()})),(0,r.Q6)("loadBlockedContacts",(()=>{(async()=>{var e,t;const n=await(0,u.t9)("fetchBlockedContacts");if(!n)return;let o=(0,r.Rd)();null!==(e=n.users)&&void 0!==e&&e.length&&(o=(0,l.Sh)(o,(0,a.ee)(n.users,"id"))),null!==(t=n.chats)&&void 0!==t&&t.length&&(o=(0,l.GL)(o,(0,a.ee)(n.chats,"id"))),o={...o,blocked:{...o.blocked,ids:[...o.blocked.ids||[],...n.blockedIds],totalCount:n.totalCount}},(0,r.R3)(o)})()})),(0,r.Q6)("blockContact",((e,t,n)=>{const{contactId:o,accessHash:d}=n;(async()=>{if(!await(0,u.t9)("blockContact",o,d))return;const e=(0,r.Rd)();(0,r.R3)((0,l.O4)(e,o))})()})),(0,r.Q6)("unblockContact",((e,t,n)=>{const{contactId:o}=n;let d;if((0,f.YC)(o)){const t=(0,c.dy)(e,o);if(!t)return;d=t.accessHash}(async()=>{if(!await(0,u.t9)("unblockContact",o,d))return;const e=(0,r.Rd)();(0,r.R3)((0,l.rB)(e,o))})()})),(0,r.Q6)("loadAuthorizations",(()=>{(async()=>{const e=await(0,u.t9)("fetchAuthorizations");e&&(0,r.R3)({...(0,r.Rd)(),activeSessions:e})})()})),(0,r.Q6)("terminateAuthorization",((e,t,n)=>{const{hash:o}=n;(async()=>{if(!await(0,u.t9)("terminateAuthorization",o))return;const e=(0,r.Rd)();(0,r.R3)({...e,activeSessions:e.activeSessions.filter((e=>e.hash!==o))})})()})),(0,r.Q6)("terminateAllAuthorizations",(()=>{(async()=>{if(!await(0,u.t9)("terminateAllAuthorizations"))return;const e=(0,r.Rd)();(0,r.R3)({...e,activeSessions:e.activeSessions.filter((e=>e.isCurrent))})})()})),(0,r.Q6)("loadNotificationExceptions",(e=>{const{serverTimeOffset:t}=e;(async()=>{const e=await(0,u.t9)("fetchNotificationExceptions",{serverTimeOffset:t});e&&(0,r.R3)((0,l.aJ)((0,r.Rd)(),e))})()})),(0,r.Q6)("loadNotificationSettings",(e=>{const{serverTimeOffset:t}=e;(async()=>{const e=await(0,u.t9)("fetchNotificationSettings",{serverTimeOffset:t});e&&(0,r.R3)((0,l.BI)((0,r.Rd)(),e))})()})),(0,r.Q6)("updateNotificationSettings",((e,t,n)=>{const{peerType:o,isSilent:d,shouldShowPreviews:a}=n;(async()=>{await(0,u.t9)("updateNotificationSettings",o,{isSilent:d,shouldShowPreviews:a})&&(0,r.R3)((0,l.HN)((0,r.Rd)(),o,d,a))})()})),(0,r.Q6)("updateWebNotificationSettings",((e,t,n)=>{(async()=>{(0,r.R3)((0,l.BI)((0,r.Rd)(),n));const e=(0,r.Rd)(),{hasPushNotifications:t,hasWebNotifications:o}=e.settings.byKey;o&&t?await(0,s.Ld)():await(0,s.r1)()})()})),(0,r.Q6)("updateContactSignUpNotification",((e,t,n)=>{const{isSilent:o}=n;(async()=>{await(0,u.t9)("updateContactSignUpNotification",o)&&(0,r.R3)((0,l.BI)((0,r.Rd)(),{hasContactJoinedNotifications:!o}))})()})),(0,r.Q6)("loadLanguages",(()=>{(async()=>{const e=await(0,u.t9)("fetchLanguages");e&&(0,r.R3)((0,l.BI)((0,r.Rd)(),{languages:e}))})()})),(0,r.Q6)("loadPrivacySettings",(()=>{(async()=>{const[e,t,n,o,d]=await Promise.all([(0,u.t9)("fetchPrivacySettings","phoneNumber"),(0,u.t9)("fetchPrivacySettings","lastSeen"),(0,u.t9)("fetchPrivacySettings","profilePhoto"),(0,u.t9)("fetchPrivacySettings","forwards"),(0,u.t9)("fetchPrivacySettings","chatInvite")]);if(!(e&&t&&n&&o&&d))return;const a=(0,r.Rd)();a.settings.privacy.phoneNumber=e,a.settings.privacy.lastSeen=t,a.settings.privacy.profilePhoto=n,a.settings.privacy.forwards=o,a.settings.privacy.chatInvite=d,(0,r.R3)(a)})()})),(0,r.Q6)("setPrivacyVisibility",((e,t,n)=>{const{privacyKey:o,visibility:d}=n,{privacy:{[o]:a}}=e.settings;if(!a)return;const s=h(e,{visibility:d,allowedIds:[...a.allowUserIds,...a.allowChatIds],deniedIds:[...a.blockUserIds,...a.blockChatIds]});(async()=>{const e=await(0,u.t9)("setPrivacySettings",o,s);if(e){const t=(0,r.Rd)();t.settings.privacy[o]=e,(0,r.R3)(t)}})()})),(0,r.Q6)("setPrivacySettings",((e,t,n)=>{const{privacyKey:o,isAllowList:d,contactsIds:a}=n,{privacy:{[o]:s}}=e.settings;if(!s)return;const i=h(e,{visibility:s.visibility,allowedIds:d?a:[...s.allowUserIds,...s.allowChatIds],deniedIds:d?[...s.blockUserIds,...s.blockChatIds]:a});(async()=>{const e=await(0,u.t9)("setPrivacySettings",o,i);if(e){const t=(0,r.Rd)();t.settings.privacy[o]=e,(0,r.R3)(t)}})()})),(0,r.Q6)("updateIsOnline",((e,t,n)=>{(0,u.t9)("updateIsOnline",n)})),(0,r.Q6)("loadContentSettings",(()=>{(async()=>{const e=await(0,u.t9)("fetchContentSettings");e&&(0,r.R3)((0,l.BI)((0,r.Rd)(),e))})()})),(0,r.Q6)("updateContentSettings",((e,t,n)=>{(async()=>{(0,r.R3)((0,l.BI)((0,r.Rd)(),{isSensitiveEnabled:n})),await(0,u.t9)("updateContentSettings",n)||(0,r.R3)((0,l.BI)((0,r.Rd)(),{isSensitiveEnabled:!n}))})()})),(0,r.Q6)("loadCountryList",((e,t,n={})=>{let{langCode:o}=n;o||(o=e.settings.byKey.language),(async()=>{const e=await(0,u.t9)("fetchCountryList",{langCode:o});e&&(0,r.R3)({...(0,r.Rd)(),countryList:e})})()})),(0,r.Q6)("ensureTimeFormat",((e,t)=>{if(e.authNearestCountry){const n=d.FD.has(e.authNearestCountry.toUpperCase())?"12h":"24h";t.setSettingOption({timeFormat:n}),(0,i.qf)(n)}(async()=>{if((0,r.Rd)().settings.byKey.wasTimeFormatSetManually)return;const e=await(0,u.t9)("fetchNearestCountry");if(e){const n=d.FD.has(e.toUpperCase())?"12h":"24h";t.setSettingOption({timeFormat:n}),(0,i.qf)(n)}})()}))},4907:(e,t,n)=>{var r=n(5116),o=n(3716),d=n(8406),u=n(1752),a=n(663),s=n(8085),i=n(1622),c=n(1947);(0,r.Q6)("apiUpdate",((e,t,n)=>{switch(o.eM&&"updateUserStatus"!==n["@type"]&&"updateServerTimeOffset"!==n["@type"]&&console.log("[GramJs] UPDATE",n["@type"],{update:n}),n["@type"]){case"updateApiReady":!function(e){const{hasWebNotifications:t,hasPushNotifications:n}=(0,s.dZ)(e);t&&n&&(0,d.Ld)(),(0,a.m0)(e.settings.byKey.language)}(e);break;case"updateAuthorizationState":!function(e){let t=(0,r.Rd)();const n="authorizationStateReady"===t.authState,o=e.authorizationState;switch((0,r.R3)({...t,authState:o,authIsLoading:!1}),t=(0,r.Rd)(),o){case"authorizationStateLoggingOut":(0,i.I)(!1),(0,r.R3)({...t,isLoggingOut:!0});break;case"authorizationStateWaitCode":(0,r.R3)({...t,authIsCodeViaApp:e.isCodeViaApp});break;case"authorizationStateWaitPassword":(0,r.R3)({...t,authHint:e.hint});break;case"authorizationStateWaitQrCode":(0,r.R3)({...t,authIsLoadingQrCode:!1,authQrCode:e.qrCode});break;case"authorizationStateReady":if(n)break;(0,i.I)(!0),(0,r.R3)({...t,isLoggingOut:!1,lastSyncTime:Date.now()})}}(n);break;case"updateAuthorizationError":!function(e){(0,r.R3)({...(0,r.Rd)(),authError:e.message})}(n);break;case"updateConnectionState":!function(e){const{connectionState:t}=e,n=(0,r.Rd)();(0,r.R3)({...n,connectionState:t}),"connectionStateReady"===t&&"authorizationStateReady"===n.authState?(0,r.uC)().sync():"connectionStateBroken"===t&&(0,r.uC)().signOut()}(n);break;case"updateSession":!function(e){const{sessionData:t}=e,{authRememberMe:n,authState:o}=(0,r.Rd)(),d=!t||!t.mainDcId;n&&"authorizationStateReady"===o&&!d&&(0,r.uC)().saveSession({sessionData:t})}(n);break;case"updateServerTimeOffset":!function(e){const t=(0,r.Rd)();t.serverTimeOffset!==e.serverTimeOffset&&(0,r.R3)({...t,serverTimeOffset:e.serverTimeOffset})}(n);break;case"updateCurrentUser":!function(e){const{currentUser:t}=e;(0,r.R3)({...(0,u.Nq)((0,r.Rd)(),t.id,t),currentUserId:t.id}),function(e){const t=localStorage.getItem(o.b_);if(!t)return;const n=JSON.parse(t);n.id=e,localStorage.setItem(o.b_,JSON.stringify(n))}(t.id)}(n);break;case"error":{"SESSION_REVOKED"===n.error.message&&t.signOut();const e=(0,c.J_)(n.error);e?t.addPaymentError({error:e}):t.showDialog&&t.showDialog({data:{...n.error,hasErrorKey:!0}});break}}}))},7895:(e,t,n)=>{var r=n(5116),o=n(3716),d=n(7361),u=n(663),a=n(6917),s=n(8085),i=n(1622);!function(){function e(){const e=document.documentElement.className.match(/theme-(\w+)/),t=e?e[1]:"light",n=(0,r.Rd)(),d=(0,s.Pu)(n),{animationLevel:u}=n.settings.byKey;d!==t&&((0,a.Z)(d,u===o.zy),(0,r.R3)({...n}))}const t=window.matchMedia("(prefers-color-scheme: dark)");"function"==typeof t.addEventListener?t.addEventListener("change",e):"function"==typeof t.addListener&&t.addListener(e)}(),(0,r.Q6)("init",(e=>{const{animationLevel:t,messageTextSize:n,language:r}=e.settings.byKey,c=(0,s.Pu)(e);(0,u.m0)(r,void 0,!0),document.documentElement.style.setProperty("--composer-text-size",`${Math.max(n,d.cj?16:15)}px`),document.documentElement.style.setProperty("--message-meta-height",`${Math.floor(1.3125*n)}px`),document.documentElement.style.setProperty("--message-text-size",`${n}px`),document.documentElement.setAttribute("data-message-text-size",n.toString()),document.body.classList.add("initial"),document.body.classList.add(`animation-level-${t}`),document.body.classList.add(d.$b?"is-touch-env":"is-pointer-env"),(0,a.Z)(c,t===o.zy),(0,i.p)(),d.cj?document.body.classList.add("is-ios"):d.wZ?document.body.classList.add("is-android"):d.jm&&document.body.classList.add("is-macos")})),(0,r.Q6)("setIsUiReady",((e,t,n)=>{const{uiReadyState:r}=n;return 2===r&&document.body.classList.remove("initial"),{...e,uiReadyState:r}})),(0,r.Q6)("setAuthPhoneNumber",((e,t,n)=>{const{phoneNumber:r}=n;return{...e,authPhoneNumber:r}})),(0,r.Q6)("setAuthRememberMe",((e,t,n)=>({...e,authRememberMe:Boolean(n)}))),(0,r.Q6)("clearAuthError",(e=>({...e,authError:void 0}))),(0,r.Q6)("disableHistoryAnimations",(()=>{setTimeout((()=>{(0,r.R3)({...(0,r.Rd)(),shouldSkipHistoryAnimations:!1}),document.body.classList.remove("no-animate")}),450),(0,r.R3)({...(0,r.Rd)(),shouldSkipHistoryAnimations:!0},!0)}))},3781:(e,t,n)=>{var r=n(5116),o=n(1752);(0,r.Q6)("setSettingOption",((e,t,n)=>(0,o.BI)(e,n))),(0,r.Q6)("setThemeSettings",((e,t,n)=>{const{theme:r,...d}=n;return(0,o.lr)(e,r,d)}))},8332:(e,t,n)=>{n.d(t,{YC:()=>i,Bf:()=>c,G9:()=>l,ZV:()=>f,eA:()=>h,Ru:()=>m,pK:()=>p,l6:()=>g,zX:()=>y,U:()=>v,GM:()=>b,hu:()=>w,RT:()=>I,Hp:()=>C,Nl:()=>S,VE:()=>E,Mg:()=>P,Qm:()=>M,H5:()=>A,q8:()=>k,Hd:()=>T,OE:()=>N,pE:()=>L,i4:()=>R,Sm:()=>D,cc:()=>O,P4:()=>x,O:()=>_,Fu:()=>Z,SB:()=>F,zF:()=>B,ih:()=>$});var r=n(6137),o=n(3716),d=n(782),u=n(5527),a=n(790);const s=Date.now()/1e3+31622400;function i(e){return"number"==typeof e?e>0:!e.startsWith("-")}function c(e){return l(e)||f(e)}function l(e){return"chatTypeBasicGroup"===e.type}function f(e){return"chatTypeSuperGroup"===e.type}function h(e){return"chatTypeChannel"===e.type}function m(e){return"chatTypePrivate"===e.type||"chatTypeBasicGroup"===e.type}function p(e){return e===o.FV}function g(e){switch(e.type){case"chatTypePrivate":return"PrivateChat";case"chatTypeBasicGroup":case"chatTypeSuperGroup":return"AccDescrGroup";case"chatTypeChannel":return"AccDescrChannel";default:return"Chat"}}function y(e){if("chatTypePrivate"===e.type||"chatTypeSecret"===e.type)return e.id}function v(e,t,n,r=!1){return r||n&&t.id===n.id&&n.isSelf?e("SavedMessages"):t.title||e("HiddenName")}function b(e){if(e.fullInfo)return e.fullInfo.about}function w(e){const{username:t}=e;if(t)return`https://t.me/${t}`;const{inviteLink:n}=e.fullInfo||{};return n}function I(e,t="normal"){if(e.avatarHash)switch(t){case"big":return`profile${e.id}?${e.avatarHash}`;default:return`avatar${e.id}?${e.avatarHash}`}}function C(e){return!e.lastMessage}function S(e){return Boolean(e.adminRights)}function E(e,t){return!!e.adminRights&&e.adminRights[t]}function P(e,t){var n,r;return Boolean((null===(n=e.currentUserBannedRights)||void 0===n?void 0:n[t])||(null===(r=e.defaultBannedRights)||void 0===r?void 0:r[t]))}function M(e,t){return t!==r._f||!(e.isRestricted||e.migratedTo||e.isNotJoined||p(e.id))&&(!!e.isCreator||!!i(e.id)||(h(e)?E(e,"postMessages"):S(e)||!P(e,"sendMessages")))}function A(e,t=!1){if(!e)return{canAttachMedia:!1,canAttachPolls:!1,canSendStickers:!1,canSendGifs:!1,canAttachEmbedLinks:!1};const n=S(e);return{canAttachMedia:n||!P(e,"sendMedia"),canAttachPolls:(n||!P(e,"sendPolls"))&&(!i(e.id)||t),canSendStickers:n||!P(e,"sendStickers"),canSendGifs:n||!P(e,"sendGifs"),canAttachEmbedLinks:n||!P(e,"embedLinks")}}function k(e,t,n){if(null!=t&&t.sendMessages){const{untilDate:n}=t;return n&&nfunction(e,t,n,r,o,d,u,a){if(!e.isListed)return!1;if(d&&d.has(e.id))return!1;if(u&&u.has(e.id))return!0;if(a&&a.has(e.id))return!0;if(L(e)&&t.excludeArchived)return!1;if(t.excludeMuted&&!e.unreadMentionsCount&&R(e,r,o))return!1;if(!e.unreadCount&&!e.unreadMentionsCount&&!e.hasUnreadMark&&t.excludeRead)return!1;if(i(e.id)){const r=n[e.id];if(r&&"userTypeBot"===r.type){if(t.bots)return!0}else{if(t.contacts&&r&&r.isContact)return!0;if(t.nonContacts&&r&&!r.isContact)return!0}}else{if(c(e))return!!t.groups;if(h(e))return!!t.channels}return!1}(e[d],n,t,r,o,u,a,s))),n.pinnedChatIds]}function _(e,t,n,r="all"){function o(e){if(!e||!e.lastMessage||e.migratedTo)return!1;switch(r){case"all":if(L(e))return!1;break;case"archived":if(!L(e))return!1}return!e.isRestricted&&!e.isNotJoined}const u=t.map((t=>e[t])).filter(o),a=new Set(t);return{pinnedChats:n?n.map((t=>e[t])).filter(o).filter((e=>a.has(e.id))):[],otherChats:(0,d.Xo)(n?u.filter((e=>!n.includes(e.id))):u,N,"desc")}}function Z(e,t,n,r,o,d){const[u]=x(e,t,n,o,d,r),a=u.map((t=>e[t])).filter((e=>(null==e?void 0:e.lastMessage)&&!e.isRestricted&&!e.isNotJoined));return{unreadDialogsCount:a.reduce(((e,t)=>t.unreadCount||t.hasUnreadMark?e+1:e),0),hasActiveDialogs:a.some((e=>e.unreadMentionsCount||!R(e,o,d)&&(e.unreadCount||e.hasUnreadMark)))}}function F(e,t,n,r,o,d,u){const{id:a,title:s,emoticon:i,description:c,pinnedChatIds:l,excludedChatIds:f,includedChatIds:h,excludeArchived:m,excludeMuted:p,excludeRead:g,...y}=r;return Object.values(y).filter(Boolean).length>1||null!=f&&f.length||null!=h&&h.length?e("Chats",function(e,t,n,r,o,d){const[u,a]=x(e,t,n,o,d,r),{pinnedChats:s,otherChats:i}=_(e,u,a,"folder");return s.length+i.length}(t,n,r,o,d,u)):y.bots?e("FilterBots"):y.groups?e("FilterGroups"):y.channels?e("FilterChannels"):y.contacts?e("FilterContacts"):y.nonContacts?e("FilterNonContacts"):void 0}function B(e,t,n){if(n&&!i(t))return n.isSelf?e("FromYou"):(0,u.Vl)(n)}function $(e,t,n=!1,r){return(0,d.Xo)(e,(e=>{const o=t[e];if(!o)return 0;let d=0;return o.lastMessage&&(d+=o.lastMessage.date),n&&o.isVerified&&(d+=3e9),r&&r.includes(e)&&(d=Date.now()+3e8+(r.length-r.indexOf(e))),d}),"desc")}},2858:(e,t,n)=>{n.d(t,{uw:()=>ie,H5:()=>o.H5,MR:()=>q,kw:()=>r.kw,cc:()=>o.cc,Qm:()=>o.Qm,RT:()=>o.RT,GM:()=>o.GM,hu:()=>o.hu,N0:()=>ne,OE:()=>o.OE,Hd:()=>o.Hd,U:()=>o.U,l6:()=>o.l6,T7:()=>v,SB:()=>o.SB,Fu:()=>o.Fu,VE:()=>o.VE,XV:()=>se,Sc:()=>ue,N5:()=>_,oP:()=>Z,qp:()=>L,w6:()=>T,R5:()=>ae,$D:()=>g,aE:()=>$,ep:()=>X,c0:()=>ee,eO:()=>V,Tp:()=>l,kG:()=>Y,Ti:()=>K,DH:()=>Q,KK:()=>h,O$:()=>D,t9:()=>W,Y5:()=>x,zF:()=>o.zF,q8:()=>o.q8,_O:()=>y,bf:()=>B,MK:()=>m,UD:()=>p,b7:()=>O,kd:()=>F,s1:()=>G,F$:()=>H,Cg:()=>z,bV:()=>re,HV:()=>oe,zX:()=>o.zX,OU:()=>P,RI:()=>M,Ow:()=>le,Rs:()=>r.Rs,Vl:()=>r.Vl,Js:()=>r.Js,db:()=>r.db,Tq:()=>r.Tq,jC:()=>de,BM:()=>te,u8:()=>R,Lo:()=>C,Ul:()=>E,Nl:()=>o.Nl,pE:()=>o.pE,G9:()=>o.G9,eA:()=>o.eA,Bf:()=>o.Bf,Hp:()=>o.Hp,ZV:()=>o.ZV,pK:()=>o.pK,Ru:()=>o.Ru,NB:()=>r.NB,MF:()=>I,CD:()=>k,rl:()=>U,hC:()=>j,CI:()=>A,B4:()=>b,ss:()=>w,jM:()=>S,cS:()=>r.cS,YC:()=>o.YC,kM:()=>r.kM,Mg:()=>o.Mg,Ak:()=>f,O:()=>o.O,P4:()=>o.P4,i4:()=>o.i4,Sm:()=>o.Sm,ih:()=>o.ih,Z0:()=>r.Z0});var r=n(5527),o=n(8332),d=n(6137),u=n(3716),a=n(7361),s=n(4784);const i="The message is not supported on this version of Telegram",c=new RegExp(u.FM,"i");function l(e){const{chatId:t,id:n}=e;return function(e,t){return`msg${e}-${t}`}(t,n)}function f(e){const t=e.match(/^msg(-?\d+)-(\d+)/);return{chatId:t[1],messageId:Number(t[2])}}function h(e){return e.previousLocalId||e.id}function m(e,t,n=!1){const{text:r,photo:o,video:d,audio:u,voice:a,document:s,sticker:c,contact:l,poll:f,invoice:h}=t.content,m=r&&r.text.substr(0,80);return t.groupedId?`${n?"":"🖼 "}${m||e("lng_in_dlg_album")}`:o?`${n?"":"🖼 "}${m||e("AttachPhoto")}`:d?`${n?"":"📹 "}${m||e(d.isGif?"AttachGif":"AttachVideo")}`:c?`${c.emoji||""} ${e("AttachSticker")}`.trim():u?`${n?"":"🎧 "}${function(e){const{audio:t,text:n}=e.content;return t&&[t.title,t.performer].filter(Boolean).join(" — ")||(null==n?void 0:n.text)}(t)||e("AttachMusic")}`:a?`${n?"":"🎤 "}${m||e("AttachAudio")}`:s?`${n?"":"📎 "}${m||s.fileName}`:l?e("AttachContact"):f?`${n?"":"📊 "}${f.summary.question}`:h?"Invoice":r?m:i}function p(e){const{text:t,sticker:n,photo:r,video:o,audio:d,voice:u,document:a,poll:s,webPage:c,contact:l,invoice:f}=e.content;return t?t.text:n||r||o||d||u||a||l||s||c||f?void 0:i}function g(e){const{text:t,sticker:n,photo:r,video:o,audio:d,voice:u,document:a,poll:i,webPage:c,contact:l}=e.content;return!!(n||null!=o&&o.isRound)||!(!t||r||o||d||u||a||i||c||l)&&((0,s.Z)(t.text)||!1)}function y(e){const{text:t}=e.content;if(t&&t.text.length<=6&&1===g(e))return t.text}function v(e){const{text:t}=e.content;let n;if(null!=t&&t.entities){let e=t.entities.find((e=>e.type===d.Vv.TextUrl));if(e&&(n=e.url.match(c)),!n&&(e=t.entities.find((e=>e.type===d.Vv.Url)),e)){const{offset:r,length:o}=e;n=t.text.substring(r,r+o).match(c)}}if(!n&&t&&(n=t.text.match(c)),n)return{url:n[0],domain:n[3]}}function b(e){return e.isOutgoing}function w(e){return Boolean(e.replyToMessageId)}function I(e){return Boolean(e.forwardInfo)}function C(e){return!!e.content.action}function S(e){return e.chatId===u.aw&&Math.round(e.id)!==e.id}function E(e){return Boolean(e.senderId)&&!(0,o.YC)(e.senderId)&&b(e)}function P(e,t){return(0,o.YC)(t.id)?(0,r.Js)(t):(0,o.U)(e,t)}function M(e){return e.sendingState?"messageSendingStateFailed"===e.sendingState?"failed":"pending":"succeeded"}function A(e){return e.id>=u.AE}function k(e){return e.content.action&&"historyClear"===e.content.action.type}function T(e){const{content:t}=e,n=t.webPage?t.webPage.video:t.video,r=t.webPage?t.webPage.photo:t.photo,o=t.webPage?t.webPage.document:t.document;if(o)return o.fileName;if(n)return n.fileName;if(t.sticker){const e=t.sticker.isAnimated?"tgs":(0,a.on)()?"webp":"png";return`${t.sticker.id}.${e}`}if(t.audio)return t.audio.fileName;const d=l(e);return r?`${d}.jpg`:t.voice?a.m5?`${d}.ogg`:`${d}.wav`:d}var N=n(5376);function L(e){return e.content}function R(e){return Boolean(D(e)||O(e)||$(e)||B(e)||function(e){return e.content.contact}(e)||W(e)||_(e)||Z(e)||F(e))}function D(e){return e.content.photo}function O(e){return e.content.video}function x(e){const{video:t}=e.content;return null!=t&&t.isRound?t:void 0}function _(e){return e.content.action}function Z(e){return e.content.audio}function F(e){return e.content.voice}function B(e){return e.content.sticker}function $(e){return e.content.document}function U(e){const t=$(e);return t?"photo"===t.mediaType:void 0}function j(e){const t=$(e);return t?"video"===t.mediaType:void 0}function W(e){return e.content.poll}function V(e){return e.content.invoice}function G(e){return e.content.webPage}function H(e){var t;return null===(t=G(e))||void 0===t?void 0:t.photo}function z(e){var t;return null===(t=G(e))||void 0===t?void 0:t.video}function Q(e){var t;return null===(t=function(e){const t=D(e)||O(e)||$(e)||B(e)||H(e)||z(e);if(t)return t.thumbnail}(e))||void 0===t?void 0:t.dataUri}function K(e,t){const{photo:n,video:r,sticker:o,audio:d,voice:u,document:a}=e.content,s=H(e),i=z(e),c=r||i,f=n||s;if(!(f||c||o||d||u||a))return;const h=l(e);if(c)switch(t){case"micro":case"pictogram":return`${h}?size=m`;case"inline":return te(e)?void 0:J(c,h);case"viewerPreview":return`${h}?size=m`;case"viewerFull":return J(c,h);case"download":return`${h}?download`}if(f)switch(t){case"micro":case"pictogram":return`${h}?size=m`;case"inline":return te(e)?void 0:`${h}?size=x`;case"viewerPreview":return`${h}?size=x`;case"viewerFull":case"download":return`${h}?size=z`}if(a)switch(t){case"micro":case"pictogram":case"inline":case"viewerPreview":if(!(0,N.v6)(a)||te(e))return;return`${h}?size=m`;case"viewerFull":case"download":return h}if(o)switch(t){case"micro":return;case"pictogram":return`${h}?size=m`;case"inline":return h;case"download":return`${h}?download`}if(d)switch(t){case"micro":case"pictogram":return q(d)?`${h}?size=m`:void 0;case"inline":return J(d,h);case"download":return`${h}?download`}if(u)switch(t){case"micro":case"pictogram":return;case"inline":return h;case"download":return`${h}?download`}}function J(e,t){return a.I_&&a.s$?`${t}?fileSize=${e.size}&mimeType=${e.mimeType}`:t}function q(e){return e.thumbnailSizes&&e.thumbnailSizes.length>0}function Y(e,t){const{sticker:n,video:r,audio:o,voice:u}=e.content,s=r||z(e);return n&&"inline"===t&&n.isAnimated?d.IU.Lottie:s&&a.I_&&("viewerFull"===t||"inline"===t)?d.IU.Progressive:o||u?u&&!a.m5?d.IU.BlobUrl:d.IU.Progressive:d.IU.BlobUrl}function X(e){const{photo:t,video:n,document:r}=e.content,o=H(e),d=z(e);if(t||o)return`photo${e.date}.jpeg`;const{fileName:u}=n||d||r||{};return u}function ee(e){const{video:t,document:n}=e.content,r=z(e),{size:o}=t||r||n||{};return o}function te(e){const{photo:t,video:n,document:r}=e.content;return(null==t?void 0:t.blobUrl)||(null==n?void 0:n.blobUrl)||(null==r?void 0:r.previewBlobUrl)}function ne(e,t,n=!1){const r=ae(e,t,n?"media":"inlineMedia");return n?r.reverse():r}function re(e){return e.sizes.find((e=>"z"===e.type))||e.sizes.find((e=>"y"===e.type))||oe(e)}function oe(e){return e.sizes.find((e=>"x"===e.type))||e.sizes.find((e=>"m"===e.type))||e.sizes.find((e=>"s"===e.type))||e.thumbnail}function de(e){if(e.width&&e.height)return e}function ue(e,t,n=!1){const r=A(e);return{isUploading:r,isTransferring:r||n,transferProgress:Number(t)}}function ae(e,t,n){let r;switch(n){case"media":r=e=>{const t=O(e);return D(e)||t&&!t.isRound&&!t.isGif};break;case"documents":r=$;break;case"links":r=e=>G(e)||function(e){const{text:t}=e.content,n=t&&t.text.match(c);if(n)return{url:n[0],domain:n[3]}}(e);break;case"audio":r=Z;break;case"voice":r=e=>{const t=O(e);return F(e)||t&&t.isRound};break;case"inlineMedia":r=e=>{const t=O(e);return D(e)||t&&!t.isRound&&!t.isGif||U(e)||j(e)};break;default:return[]}return t.reduce(((t,n)=>(e[n]&&r(e[n])&&t.push(n),t)),[])}function se(e){const{audio:t,voice:n,video:r}=L(e),o=t||n||r||z(e);if(o)return o.duration}function ie(e,t){return`${e}_${t}`}const ce={missing_payment_information:{field:"cardNumber",message:"Incorrect card number"},invalid_number:{field:"cardNumber",message:"Incorrect card number"},number:{field:"cardNumber",message:"Incorrect card number"},exp_year:{field:"expiry",message:"Incorrect year"},exp_month:{field:"expiry",message:"Incorrect month"},invalid_expiry_year:{field:"expiry",message:"Incorrect year"},invalid_expiry_month:{field:"expiry",message:"Incorrect month"},cvc:{field:"cvv",message:"Incorrect CVV"},invalid_cvc:{field:"cvv",message:"Incorrect CVV"}};function le(e){const{message:t,code:n,param:r}=e,{field:o,message:d}=r?ce[r]:ce[n];return{field:o,message:d,description:t}}},5527:(e,t,n)=>{n.d(t,{Vl:()=>s,Js:()=>i,Tq:()=>c,kM:()=>l,NB:()=>f,cS:()=>h,kw:()=>m,Z0:()=>p,db:()=>g,Rs:()=>y});var r=n(3716),o=n(790),d=n(782),u=n(2267);const a=[1,8,5,2,7,4,6];function s(e){if(e)switch(e.type){case"userTypeBot":case"userTypeRegular":return e.firstName||e.lastName;case"userTypeDeleted":case"userTypeUnknown":return"Deleted";default:return}}function i(e){if(e){if(f(e))return"Deleted account";switch(e.type){case"userTypeBot":case"userTypeRegular":if(e.firstName&&e.lastName)return`${e.firstName} ${e.lastName}`;if(e.firstName)return e.firstName;if(e.lastName)return e.lastName;break;case"userTypeDeleted":case"userTypeUnknown":return"Deleted account"}}}function c(e,t,n){if(t.id===r.aw)return e("ServiceNotifications").toLowerCase();if(t.type&&"userTypeBot"===t.type)return e("Bot");if(!t.status)return"";switch(t.status.type){case"userStatusEmpty":return e("ALongTimeAgo");case"userStatusLastMonth":return e("WithinAMonth");case"userStatusLastWeek":return e("WithinAWeek");case"userStatusOffline":{const{wasOnline:r}=t.status;if(!r)return e("LastSeen.Offline");const d=new Date((new Date).getTime()+1e3*n),u=new Date(1e3*r);if(u>=d)return e("LastSeen.JustNow");const a=new Date(d.getTime()-u.getTime());if(a.getTime()/1e3<60)return e("LastSeen.JustNow");if(a.getTime()/1e3<3600)return e("LastSeen.MinutesAgo",Math.floor(a.getTime()/1e3/60));const s=new Date;if(s.setHours(0,0,0,0),u>new Date(s.getTime()+1e3*n))return a.getTime()/1e3<21600?e("LastSeen.HoursAgo",Math.floor(a.getTime()/1e3/60/60)):e("LastSeen.TodayAt",(0,o.mr)(u,e));const i=new Date;return i.setDate(d.getDate()-1),i.setHours(0,0,0,0),u>new Date(i.getTime()+1e3*n)?e("LastSeen.YesterdayAt",(0,o.mr)(u,e)):e("LastSeen.AtDate",(0,o.Tu)(e,u))}case"userStatusOnline":return e("Online");case"userStatusRecently":return e("Lately");default:return}}function l(e){const{id:t,status:n,type:o}=e;return!!n&&t!==r.aw&&"userStatusOnline"===n.type&&"userTypeBot"!==o}function f(e){return!(!e.status||"userTypeBot"===e.type||e.id===r.aw||"userTypeDeleted"!==e.type&&"userTypeUnknown"!==e.type)}function h(e){return"userTypeBot"===e.type}function m(e){return!e.isContact&&!h(e)}function p(e,t,n,r=0){return(0,d.Xo)(e,(e=>{const o=(0,u.b)(r);if(n&&n.includes(e))return o+172800-(n.length-n.indexOf(e));const d=t[e];if(!d||!d.status)return 0;if("userStatusOnline"===d.status.type)return d.status.expires;if("userStatusOffline"===d.status.type&&d.status.wasOnline)return d.status.wasOnline;switch(d.status.type){case"userStatusRecently":return o-86400;case"userStatusLastWeek":return o-604800;case"userStatusLastMonth":return o-18144e3;default:return 0}}),"desc")}function g(e){return"number"==typeof e?Math.abs(e):Math.abs(Number(e))}function y(e){const t=e?g(e.id)%7:0;return a[t]}},1752:(e,t,n)=>{n.d(t,{O4:()=>Me,c_:()=>C,fZ:()=>f,m6:()=>I,aK:()=>Ee,aJ:()=>Se,Sh:()=>X,$S:()=>N,bp:()=>_e,WY:()=>Ze,K4:()=>P,bV:()=>M,h8:()=>te,M6:()=>Z,i9:()=>B,Dd:()=>p,vy:()=>H,rB:()=>Ae,g_:()=>V,Mg:()=>u,SL:()=>s,Pb:()=>he,w3:()=>O,BI:()=>Ie,lr:()=>Ce,pf:()=>w,s5:()=>Q,y9:()=>L,nA:()=>Re,_7:()=>Oe,Q$:()=>Le,Dq:()=>xe,vT:()=>Ne,QH:()=>De,Ob:()=>F,a4:()=>c,B1:()=>a,vv:()=>m,Pi:()=>h,cY:()=>S,GL:()=>l,Wy:()=>y,wV:()=>_,cq:()=>x,rq:()=>W,No:()=>ue,Og:()=>ae,xv:()=>ie,px:()=>se,xj:()=>A,c1:()=>ye,z5:()=>ge,qr:()=>fe,dx:()=>me,fw:()=>we,H9:()=>be,HN:()=>Pe,ff:()=>k,P4:()=>E,x1:()=>ee,TM:()=>Te,Rg:()=>j,z3:()=>U,IM:()=>G,Xg:()=>R,j6:()=>D,lG:()=>$,IE:()=>ke,Nq:()=>q,Lm:()=>ne,Q3:()=>re,eD:()=>Y});var r=n(3716),o=n(782),d=n(8085);function u(e,t,n){return{...e,chats:{...e.chats,listIds:{...e.chats.listIds,[t]:n}}}}function a(e,t,n){const{[t]:r}=e.chats.listIds,o=null!=r&&r.length?n.filter((e=>!r.includes(e))):n;return r&&!o.length?e:u(e,t,[...r||[],...o])}function s(e,t){return{...e,chats:{...e.chats,byId:t}}}function i(e,t,n,r){const{byId:d}=e.chats,u=d[t],a=n.isMin&&u&&!u.isMin,s={...u,...a?(0,o.CE)(n,["isMin","accessHash"]):n,...r&&{photos:[r,...u.photos||[]]}};return s.id&&s.type,s}function c(e,t,n,r){const{byId:o}=e.chats;return s(e,{...o,[t]:i(e,t,n,r)})}function l(e,t){const n=Object.keys(t).reduce(((n,r)=>{const o=i(e,r,t[r]);return o&&(n[r]=o),n}),{});return e=s(e,{...e.chats.byId,...n})}function f(e,t){const{byId:n}=e.chats;let r=!1;const o=Object.keys(t).reduce(((o,d)=>{if(!n[d]||n[d].isMin&&!t[d].isMin){const n=i(e,d,t[d]);n&&(o[d]=n,r||(r=!0))}return o}),{});return r&&(e=s(e,{...e.chats.byId,...o})),e}function h(e,t,n){const o=n===r.WS?"archived":"active";let d=e.chats.listIds;return Object.keys(d).forEach((e=>{const n=d[e]||[];e!==o||n.includes(t)?e!==o&&n.includes(t)&&(d={...d,[e]:n.filter((e=>e!==t))}):d={...d,[e]:[...n,t]}})),c(e={...e,chats:{...e.chats,listIds:d}},t,{folderId:n||void 0})}function m(e,t,n){const r="active"===t?"all":"archived";return{...e,chats:{...e.chats,...n.orderedPinnedIds&&{orderedPinnedIds:{...e.chats.orderedPinnedIds,[t]:n.orderedPinnedIds}},totalCount:{...e.chats.totalCount,[r]:n.totalChatCount},isFullyLoaded:{...e.chats.isFullyLoaded,[t]:!1}}}}function p(e,t){const n=(0,d.Ek)(e,t);if(!n)return e;const{[n]:r}=e.chats.listIds;return r&&(e=u(e,n,r.filter((e=>e!==t)))),c(e,t,{isNotJoined:!0})}var g=n(6137);function y(e,t,n=g._f,o="thread",d){const{messageLists:u}=e.messages;let a=u;if(d||r.Cg)a=t?[{chatId:t,threadId:n,type:o}]:[];else if(t){const e=u[u.length-1];e&&e.chatId===t&&e.threadId===n&&e.type===o||(a=e&&e.chatId===r.AJ?[...u.slice(0,-1),{chatId:t,threadId:n,type:o}]:[...u,{chatId:t,threadId:n,type:o}])}else a=u.slice(0,-1);return{...e,messages:{...e.messages,messageLists:a}}}function v(e,t,n){return b(e,t,{byId:n})}function b(e,t,n){const r=e.messages.byChatId[t]||{byId:{},threadsById:{}};return{...e,messages:{...e.messages,byChatId:{...e.messages.byChatId,[t]:{...r,...n}}}}}function w(e,t,n,r,o){return function(e,t,n,r){const o=e.messages.byChatId[t];return b(e,t,{threadsById:{...null==o?void 0:o.threadsById,[n]:{...null==o?void 0:o.threadsById[n],...r}}})}(e,t,n,{[r]:o})}function I(e,t){const n=t.reduce(((e,t)=>(e[t.chatId]||(e[t.chatId]={}),e[t.chatId][t.id]=t,e)),{});return Object.keys(n).forEach((t=>{e=C(e,t,n[t])})),e}function C(e,t,n){const r=(0,d.Zw)(e,t);return r&&Object.keys(n).every((e=>Boolean(r[Number(e)])))?e:v(e,t,{...n,...r})}function S(e,t,n,r){const o=(0,d.Zw)(e,t)||{},u={...o[n],...r};return u.id?v(e,t,{...o,[n]:u}):e}function E(e,t,n,r){const o=(0,d.Fn)(e,t)||{},u={...o[n],...r};return u.id?O(e,t,{...o,[n]:u}):e}function P(e,t,n){const r=(0,d.Zw)(e,t);if(!r)return e;const u=(0,o.CE)(r,n),a=Object.values((0,o.q0)(r,n)).filter((({forwardInfo:e})=>null==e?void 0:e.isLinkedChannelPost));if(Object.keys(e.messages.byChatId[t].threadsById).map(Number).forEach((r=>{const o=(0,d.tZ)(e,t,r);let u=(0,d.gb)(e,t,r),a=(0,d.qC)(e,t,r),s=(0,d.Cb)(e,t,r),i=(0,d.KB)(e,t),c=null==o?void 0:o.messagesCount;n.forEach((e=>{u&&u.includes(e)&&(u=u.filter((t=>t!==e)),void 0!==c&&(c-=1)),a&&a.includes(e)&&(a=a.filter((t=>t!==e))),s&&s.includes(e)&&(s=s.filter((t=>t!==e))),i&&i.includes(e)&&(i=i.filter((t=>t!==e)))})),e=w(e,t,r,"listedIds",u),e=w(e,t,r,"outlyingIds",a),e=w(e,t,r,"viewportIds",s),e=w(e,t,r,"pinnedIds",i),o&&void 0!==c&&(e=w(e,t,r,"threadInfo",{...o,messagesCount:c}))})),a.length){const n=(0,d.Bt)(e),r=n&&n.chatId===t&&"thread"===n.type,o=null==n?void 0:n.threadId;a.forEach((n=>{const{fromChatId:u,fromMessageId:a}=n.forwardInfo,s=(0,d.hj)(e,u,a);r&&o===a&&(e=y(e,t)),s&&(e=S(e,u,a,{threadInfo:void 0}))}))}return e=v(e,t,u)}function M(e,t,n){const r=(0,d.Fn)(e,t);if(!r)return e;const u=(0,o.CE)(r,n);let a=(0,d.qy)(e,t);return a&&(n.forEach((e=>{a.includes(e)&&(a=a.filter((t=>t!==e)))})),e=w(e,t,g._f,"scheduledIds",a)),O(e,t,u)}function A(e,t,n,r){const o=(0,d.gb)(e,t,n),u=null!=o&&o.length?r.filter((e=>!o.includes(e))):r;return o&&!u.length?e:w(e,t,n,"listedIds",T([...o||[],...u]))}function k(e,t,n,r){const o=(0,d.qC)(e,t,n),u=null!=o&&o.length?r.filter((e=>!o.includes(e))):r;return o&&!u.length?e:w(e,t,n,"outlyingIds",T([...o||[],...u]))}function T(e){return e.sort(((e,t)=>e-t))}function N(e,t,n,o){const u=(0,d.Cb)(e,t,n)||[];return u.includes(o)?e:w(e,t,n,"viewportIds",T([...u.length{e=R(e,t.chatId,t.threadId,t)})),e}function O(e,t,n){return function(e,t,n){const r=e.scheduledMessages.byChatId[t]||{byId:{},hash:0};return{...e,scheduledMessages:{byChatId:{...e.scheduledMessages.byChatId,[t]:{...r,...n}}}}}(e,t,{byId:n})}function x(e,t,n,r=!1,o=!1){return{...e,focusedMessage:{...e.focusedMessage,chatId:t,messageId:n,noHighlight:r,isResizingContainer:o}}}function _(e,t){return{...e,focusedMessage:{...e.focusedMessage,direction:t}}}function Z(e,t,n){return{...e,selectedMessages:{chatId:t,messageIds:n?Array.prototype.concat([],n):[]}}}function F(e,t,n,r,u,a,s,i=!1){const{selectedMessages:c}=e;a&&(s=(0,d.xH)(e,t,a));const l=s||[u];if(!c)return Z(e,t,l);const{messageIds:f}=c;let h;const m=l.filter((e=>!f.includes(e)));if(m&&!m.length)h=f.filter((e=>!l.includes(e)));else if(i&&f.length){const a=(0,d.$W)(e,t,n,r),s=a.indexOf(f[f.length-1]),i=a.indexOf(u),c=Math.min(s,i),l=Math.max(s,i),m=a.slice(c,l+1);h=(0,o.Tw)([...f,...m])}else h=[...f,...m];return h.length?{...e,selectedMessages:{...c,messageIds:h}}:B(e)}function B(e){return{...e,selectedMessages:void 0}}function $(e,t,n,r,o){const{channelPostId:u,fromChatId:a}=t.forwardInfo||{};if(u&&a){const t=(0,d.tZ)(e,n,u);t&&(e=w(e,n,u,"threadInfo",{...t,lastMessageId:r,messagesCount:t.messagesCount+(o?-1:1)}))}return e}function U(e,t,n,r,d){const u=r.map((t=>{const n=e.stickers.setsById[t.id];return n?{...n,...t}:t}));return{...e,stickers:{...e.stickers,setsById:{...e.stickers.setsById,...(0,o.ee)(u,"id")},[t]:{...e.stickers[t],hash:n,..."search"===t?{resultIds:d}:{setIds:r.map((({id:e})=>e))}}}}}function j(e,t,n){const r=e.stickers.setsById[t]||{};return{...e,stickers:{...e.stickers,setsById:{...e.stickers.setsById,[t]:{...r,...n}}}}}function W(e,t,n,r){const{results:o}=e.gifs.search;let d;if(t||!o)d=n;else{const e=new Set(o.map((e=>e.id)));d=[...o,...n.filter((t=>!e.has(t.id)))]}return{...e,gifs:{...e.gifs,search:{...e.gifs.search,offset:r,results:d}}}}function V(e,t){return{...e,animatedEmojis:t}}function G(e,t,n,r){const u=[...(0,d.Pk)(e,t),...n||[]],a=(0,o.Tw)(u.map((({id:e})=>e))),s=(0,o.ee)(u,"id"),i=a.map((e=>s[e]));return{...e,stickers:{...e.stickers,forEmoji:{emoji:t,stickers:i,hash:r}}}}function H(e){const{emoji:t,stickers:n,hash:r}=e.stickers.forEmoji||{};return t?G(e,t,n,r):e}var z=n(735);function Q(e,t){return{...e,users:{...e.users,byId:t}}}function K(e,t,n){const{byId:r}=e.users,d=r[t],u=n.isMin&&d&&!d.isMin,a={...d,...u?(0,o.CE)(n,["isMin","accessHash"]):n};return a.id&&a.type?a:d}function J(e,t){const{userIds:n}=e.contactList||{};if(!n)return e;const r=t.filter((e=>(null==e?void 0:e.isContact)&&!n.includes(e.id))).map((e=>e.id));return 0===r.length?e:{...e,contactList:{userIds:[...r,...n]}}}function q(e,t,n){const{byId:r}=e.users,o=K(e,t,n);return Q(e=J(e,[o]),{...r,[t]:o})}function Y(e,t){const n=Object.keys(t).reduce(((n,r)=>{const o=K(e,r,t[r]);return o&&(n[r]=o),n}),{});return e=Q(e=J(e,Object.values(n)),{...e.users.byId,...n})}function X(e,t){const{byId:n}=e.users;let r=!1;const o=Object.keys(t).reduce(((o,d)=>{if(!n[d]||n[d].isMin&&!t[d].isMin){const n=K(e,d,t[d]);n&&(o[d]=n,r||(r=!0))}return o}),{});return r&&(e=J(e=Q(e,{...e.users.byId,...o}),Object.values(o))),e}function ee(e,t){return e.users.selectedId===t?e:{...e,users:{...e.users,selectedId:t}}}function te(e,t){const{byId:n}=e.users,{userIds:r}=e.contactList||{};return delete n[t],Q(e={...e,contactList:{userIds:r?r.filter((e=>e!==t)):z.D}},n)}function ne(e,t){return{...e,userSearch:{...e.userSearch,...t}}}function re(e,t){return ne(e,{fetchingStatus:t})}function oe(e,t,n){const{byId:r}=e.users,o=r[t];return o&&o.fullInfo?q(e,t,{...o,fullInfo:{...o.fullInfo,isBlocked:n}}):e}const de=e=>`${e.chatId}_${e.id}`;function ue(e,t){return{...e,globalSearch:{...e.globalSearch,...t}}}function ae(e,t){return ue(e,{currentContent:t})}function se(e,t,n,r,d){var u;const{resultsByType:a}=e.globalSearch||{},s=t.reduce(((e,t)=>(e[de(t)]=t,e)),{}),i=null==a||null===(u=a[r])||void 0===u?void 0:u.foundIds;if(void 0!==i&&Object.keys(s).every((e=>i.includes(de(s[e])))))return ie(e,{messages:!1});const c=i||[],l=t.map((e=>de(e))),f=Array.prototype.concat(c,l),h=(0,o.et)(c,f)?c:f;return ue(e=ie(e,{messages:!1}),{resultsByType:{...(e.globalSearch||{}).resultsByType,[r]:{totalCount:n,nextOffsetId:d,foundIds:h}}})}function ie(e,t){return ue(e,{fetchingStatus:{...e.globalSearch.fetchingStatus,...t}})}var ce=n(2858);function le(e,t,n){return{...e,localTextSearch:{byChatThreadKey:{...e.localTextSearch.byChatThreadKey,[t]:n}}}}function fe(e,t,n,r,o){const d=(0,ce.uw)(t,n);return le(e,d,{...e.localTextSearch.byChatThreadKey[d],isActive:r,query:o})}function he(e,t,n,r,o,d){const u=(0,ce.uw)(t,n);return le(e,u,{...e.localTextSearch.byChatThreadKey[u],results:{foundIds:r,totalCount:o,nextOffsetId:d}})}function me(e,t,n,r,d,u){const a=(0,ce.uw)(t,n),{results:s}=e.localTextSearch.byChatThreadKey[a]||{},i=(null==s?void 0:s.foundIds)||[],c=ve((0,o.Tw)(Array.prototype.concat(i,r)));return he(e,t,n,(0,o.et)(i,c)?i:c,d,u)}function pe(e,t,n){return{...e,localMediaSearch:{byChatId:{...e.localMediaSearch.byChatId,[t]:n}}}}function ge(e,t,n){return pe(e,t,{...e.localMediaSearch.byChatId[t],currentType:n})}function ye(e,t,n,r,d,u){const{resultsByType:a}=e.localMediaSearch.byChatId[t]||{},s=null!=a&&a[n]?a[n].foundIds:[],i=ve((0,o.Tw)(Array.prototype.concat(s,r)));return function(e,t,n,r,o,d){return pe(e,t,{...e.localMediaSearch.byChatId[t],resultsByType:{...(e.localMediaSearch.byChatId[t]||{}).resultsByType,[n]:{foundIds:r,totalCount:o,nextOffsetId:d}}})}(e,t,n,(0,o.et)(s,i)?s:i,d,u)}function ve(e){return e.sort(((e,t)=>e-t))}function be(e,t){return{...e,management:{...e.management,progress:t}}}function we(e,t,n){return{...e,management:{...e.management,byChatId:{...e.management.byChatId,[t]:{...e.management.byChatId[t]||{},...n}}}}}function Ie(e,t){return{...e,settings:{...e.settings,byKey:{...e.settings.byKey,...t}}}}function Ce(e,t,n){return{...e,settings:{...e.settings,themes:{...e.settings.themes,[t]:{...e.settings.themes[t]||{},...n}}}}}function Se(e,t){return t.forEach((t=>{const{chatId:n,...r}=t;e=Ee(e,n,r)})),e}function Ee(e,t,n){return{...e,settings:{...e.settings,notifyExceptions:{...e.settings.notifyExceptions,[t]:n}}}}function Pe(e,t,n,r){switch(t){case"contact":return Ie(e,{...void 0!==n&&{hasPrivateChatsNotifications:!n},...void 0!==r&&{hasPrivateChatsMessagePreview:r}});case"group":return Ie(e,{...void 0!==n&&{hasGroupNotifications:!n},...void 0!==r&&{hasGroupMessagePreview:r}});case"broadcast":return Ie(e,{...void 0!==n&&{hasBroadcastNotifications:!n},...void 0!==r&&{hasBroadcastMessagePreview:r}});default:return}}function Me(e,t){return e=oe(e,t,!0),{...e,blocked:{...e.blocked,ids:[t,...e.blocked.ids],totalCount:e.blocked.totalCount+1}}}function Ae(e,t){return e=oe(e,t,!1),{...e,blocked:{...e.blocked,ids:e.blocked.ids.filter((e=>e!==t)),totalCount:e.blocked.totalCount-1}}}function ke(e,t){return{...e,twoFaSettings:{...e.twoFaSettings,...t}}}function Te(e,t){return{...e,payment:{...e.payment,shippingOptions:t}}}function Ne(e,t){return{...e,payment:{...e.payment,requestId:t}}}function Le(e,t){return{...e,payment:{...e.payment,step:t}}}function Re(e,t){if(!t.content||!t.content.invoice)return e;const{title:n,text:r,amount:o,currency:d,isTest:u,photoUrl:a}=t.content.invoice;return{...e,payment:{...e.payment,invoiceContent:{title:n,text:r,photoUrl:a,amount:o,currency:d,isTest:u}}}}function De(e,t){return{...e,payment:{...e.payment,stripeCredentials:{...t}}}}function Oe(e,t){return{...e,payment:{...e.payment,...t}}}function xe(e,t,n){if(!t||!n)return{...e,payment:{...e.payment,receipt:void 0}};const{invoice:r}=n.content,{photoUrl:o,text:d,title:u}=r||{};return{...e,payment:{...e.payment,receipt:{...t,photoUrl:o,text:d,title:u}}}}function _e(e){return{...e,payment:{}}}function Ze(e){return{...e,payment:{...e.payment,isPaymentModalOpen:!1}}}},8085:(e,t,n)=>{n.d(t,{hg:()=>ue,xs:()=>Ce,_k:()=>ye,zB:()=>O,g4:()=>w,bH:()=>xe,__:()=>Ze,xl:()=>ve,Nu:()=>we,nB:()=>be,Z1:()=>f,IK:()=>v,DI:()=>P,Mw:()=>S,Ek:()=>C,hj:()=>se,ZB:()=>le,Zw:()=>B,YK:()=>y,Dg:()=>h,X5:()=>Ae,A1:()=>M,jr:()=>F,yN:()=>N,JX:()=>Ke,pP:()=>Ve,we:()=>je,og:()=>Ue,$W:()=>V,Bt:()=>Z,y5:()=>T,n5:()=>$e,Ms:()=>Y,_$:()=>J,kK:()=>ce,wU:()=>q,yZ:()=>te,It:()=>Pe,G$:()=>fe,y8:()=>Ne,cv:()=>ge,pk:()=>b,N:()=>I,ep:()=>E,xo:()=>p,FM:()=>m,a6:()=>Re,te:()=>Ie,Ev:()=>Me,CA:()=>ke,zQ:()=>Ge,_X:()=>he,vk:()=>Te,Jf:()=>ze,UW:()=>A,s4:()=>i,b9:()=>ae,VF:()=>Be,gb:()=>j,aW:()=>We,xH:()=>Le,FT:()=>Oe,tV:()=>X,NJ:()=>l,dZ:()=>c,dT:()=>me,qC:()=>W,gx:()=>Je,eh:()=>Ye,Mz:()=>qe,sp:()=>Xe,KB:()=>H,$$:()=>et,rd:()=>Ee,p9:()=>ne,Yy:()=>K,Wq:()=>He,qy:()=>z,Tm:()=>ie,Fn:()=>$,Vt:()=>Q,D7:()=>De,Ur:()=>pe,yB:()=>Fe,Ny:()=>L,E_:()=>R,Pk:()=>D,i3:()=>tt,P_:()=>g,Pu:()=>Qe,Db:()=>de,tZ:()=>ee,Cm:()=>re,qS:()=>oe,uZ:()=>Se,dy:()=>s,Cb:()=>G});var r=n(1713),o=n(7361),d=n(6137),u=n(3716),a=n(2858);function s(e,t){return e.users.byId[t]}function i(e,t){var n;const r=s(e,t);return null==r||null===(n=r.fullInfo)||void 0===n?void 0:n.isBlocked}function c(e){return e.settings.byKey}function l(e){return e.settings.notifyExceptions}function f(e,t){return e.chats.byId[t]}function h(e,t){const n=(0,a.zX)(t);return!!n&&s(e,n)}function m(e,t){return t===e.currentUserId}function p(e,t){const n=h(e,t);return n&&(0,a.cS)(n)}function g(e){return Object.values(e.chats.byId).find((({isSupport:e})=>e))}function y(e,t){if(!(0,a.YC)(t.id)&&!(0,a.eA)(t)&&t.fullInfo)return t.fullInfo.members&&t.fullInfo.members.length!==u.mo?t.fullInfo.members.reduce(((t,{userId:n})=>e.users.byId[n]&&(0,a.kM)(e.users.byId[n])&&n!==e.currentUserId?t+1:t),0):t.fullInfo.onlineCount}function v(e,t){const n=f(e,t),r=n&&(0,a.zX)(n),o=r&&s(e,r);if(o&&(0,a.cS)(o))return o}function b(e,t){const n=f(e,t),r=v(e,t);if(!n||!r)return!1;if(n.lastMessage&&(0,a.CD)(n.lastMessage))return!0;const o=e.messages.byChatId[t];if(!o)return!1;const{listedIds:u}=o.threadsById[d._f]||{};return u&&!u.length}function w(e){return Boolean(e.chats.listIds.active)}function I(e,t,n){const{listIds:r}=e.chats;if(n){const e=r[n];return Boolean(e&&e.includes(t))}return Object.values(r).some((e=>e&&e.includes(t)))}function C(e,t){const n=f(e,t);if(n&&I(e,t))return n.folderId===u.WS?"archived":"active"}function S(e,t){return e.chatFolders.byId[t]}function E(e,t,n=u.Nf){const{active:r,archived:o}=e.chats.orderedPinnedIds;if(n===u.Nf)return!!r&&r.includes(t);if(n===u.WS)return!!o&&o.includes(t);const{byId:d}=e.chatFolders,{pinnedChatIds:a}=d[n]||{};return!!a&&a.includes(t)}function P(e,t){const n=t.toLowerCase();return Object.values(e.chats.byId).find((e=>e.username&&e.username.toLowerCase()===n))}function M(e){const t=e.chats.listIds.active;if(!t)return 0;const n=e.chats.byId,r=c(e),o=l(e);return t.reduce(((e,t)=>{const d=n[t];return!(d&&d.unreadCount&&d.isListed)||d.isNotJoined||d.isRestricted||!d.unreadMentionsCount&&(0,a.i4)(d,r,o)?e:e+d.unreadCount}),0)}function A(e){return Boolean(f(e,u.aw))}var k=n(782);function T(e){return e.stickers.search}function N(e){return e.gifs.search}function L(e,t){return e.stickers.setsById[t]}function R(e,t){return Object.values(e.stickers.setsById).find((e=>e.shortName.toLowerCase()===t.toLowerCase()))}function D(e,t){const n=Object.values(e.stickers.setsById);let r=[];return n.forEach((({packs:e})=>{if(!e)return;const n=e[t];n&&(r=r.concat(n))})),r}function O(e,t){const{animatedEmojis:n}=e;if(!n||!n.stickers)return;const r=t.replace("️","");return n.stickers.find((e=>e.emoji===t||e.emoji===r))}var x=n(2267),_=n(735);function Z(e){const{messageLists:t}=e.messages;if(t.length)return t[t.length-1]}function F(e){const{chatId:t}=Z(e)||{};return t?f(e,t):void 0}function B(e,t){var n;return null===(n=e.messages.byChatId[t])||void 0===n?void 0:n.byId}function $(e,t){var n;return null===(n=e.scheduledMessages.byChatId[t])||void 0===n?void 0:n.byId}function U(e,t,n,r){const o=e.messages.byChatId[t];if(!o)return;const d=o.threadsById[n];return d?d[r]:void 0}function j(e,t,n){return U(e,t,n,"listedIds")}function W(e,t,n){return U(e,t,n,"outlyingIds")}function V(e,t,n,r){switch(r){case"thread":return G(e,t,n);case"pinned":return H(e,t);case"scheduled":return z(e,t)}}function G(e,t,n){return U(e,t,n,"viewportIds")}function H(e,t){return U(e,t,d._f,"pinnedIds")}function z(e,t){return U(e,t,d._f,"scheduledIds")}function Q(e,t,n){return U(e,t,n,"scrollOffset")}function K(e,t,n){return U(e,t,n,"replyingToId")}function J(e,t,n){return U(e,t,n,"editingId")}function q(e,t){return U(e,t,d._f,"editingScheduledId")}function Y(e,t,n){return U(e,t,n,"draft")}function X(e,t,n){return U(e,t,n,"noWebPage")}function ee(e,t,n){return U(e,t,n,"threadInfo")}function te(e,t,n){return U(e,t,n,"firstMessageId")}function ne(e,t,n){return U(e,t,n,"replyStack")}function re(e,t,n){if(n===d._f)return f(e,t);const r=ee(e,t,n);return r?f(e,r.originChannelId||t):void 0}function oe(e,t,n){if(n===d._f)return;const r=ee(e,t,n);return r?r.topMessageId:void 0}function de(e,t,n){const r=e.messages.byChatId[t];if(!r)return;const{replyToMessageId:o,replyToTopMessageId:d}=n;return o||d?Object.values(r.threadsById).find((e=>e.threadInfo&&(o&&o===e.threadInfo.topMessageId||d&&d===e.threadInfo.topMessageId))):void 0}function ue(e,t,n){const r=Z(e);if(!r)return!1;const{threadInfo:o}=de(e,t,n)||{};return t===r.chatId&&(r.threadId===d._f||o&&r.threadId===o.threadId)}function ae(e,t,n){const r=G(e,t,n);if(!r||!r.length)return!0;let o;if(n===d._f){const n=f(e,t);if(!n||!n.lastMessage)return!0;o=n.lastMessage.id}else{const r=ee(e,t,n);if(!r||!r.lastMessageId)return;o=r.lastMessageId}return o>=u.AE&&!se(e,t,o)||r[r.length-1]>=o}function se(e,t,n){const r=B(e,t);return r?r[n]:void 0}function ie(e,t,n){const r=$(e,t);return r?r[n]:void 0}function ce(e,t,n,r){if("scheduled"===r){const n=q(e,t);return n?ie(e,t,n):void 0}{const r=J(e,t,n);return r?se(e,t,r):void 0}}function le(e,t){let n;for(const r of Object.values(e.messages.byChatId)){const{byId:e}=r;if(n=Object.values(e).find((e=>e.content.poll&&e.content.poll.id===t)),n)break}return n}function fe(e,t){const{chatId:n,messageId:r}=e.focusedMessage||{};return n===t?r:void 0}function he(e,t){const n=fe(e,t.chatId);return!!n&&(n===t.id||n===t.previousLocalId)}function me(e,t,n=!1){return function(e,t){const{lastReadOutboxMessageId:n}=f(e,t.chatId)||{};return(0,a.CI)(t)||!n||ne===t.id))}(e,t.content.sticker),O=!b&&R&&!D,_=!b&&D,Z=!b,F=!b&&(p||h),B=!b,$=Boolean((null===(o=w.webPage)||void 0===o?void 0:o.document)||(null===(d=w.webPage)||void 0===d?void 0:d.video)||(null===(u=w.webPage)||void 0===u?void 0:u.photo)||w.audio||w.voice||w.photo||w.video||w.document||w.sticker);return{noOptions:[C,N,E,P,k,A,T,L,O,_,Z,F,B,$].every((e=>!e)),canReply:C,canEdit:N,canPin:E,canUnpin:P,canReport:k,canDelete:A,canDeleteForAll:T,canForward:L,canFaveSticker:O,canUnfaveSticker:_,canCopy:Z,canCopyLink:F,canSelect:B,canDownload:$}}function ve(e){const{messageIds:t}=e.selectedMessages||{},{chatId:n,threadId:r}=Z(e)||{},o=n&&B(e,n);if(!o||!t||!r)return{};const d=t.map((t=>o[t]&&ye(e,o[t],r))).filter(Boolean);return{canDelete:d.every((e=>e.canDelete)),canDeleteForAll:d.every((e=>e.canDeleteForAll))}}function be(e){const{messageIds:t}=e.selectedMessages||{},{chatId:n,threadId:r}=Z(e)||{},o=n&&B(e,n);return!!(o&&t&&r)&&t.map((t=>o[t]&&ye(e,o[t],r))).filter(Boolean).every((e=>e.canReport))}function we(e){const{messageIds:t}=e.selectedMessages||{},{chatId:n,threadId:r}=Z(e)||{},o=n&&B(e,n);return!!(o&&t&&r)&&t.map((t=>o[t]&&ye(e,o[t],r))).filter(Boolean).some((e=>e.canDownload))}function Ie(e,t){const n=e.activeDownloads.byChatId[t.chatId];return!!n&&n.includes(t.id)}function Ce(e,t){return e.activeDownloads.byChatId[t]||_.D}function Se(e,t){var n;return null===(n=e.fileUploads.byMessageLocalId[t.previousLocalId||t.id])||void 0===n?void 0:n.progress}function Ee(e,t,n){if(n===d._f){const n=f(e,t);if(!n)return;if(!n.lastReadInboxMessageId)return;return n.lastMessage?(0,a.CI)(n.lastMessage)?n.lastMessage.id:Math.min(n.lastMessage.id,n.lastReadInboxMessageId):n.lastReadInboxMessageId}{const r=ee(e,t,n);if(!r)return;return r.lastReadInboxMessageId?Math.min(r.lastReadInboxMessageId,r.lastMessageId||1/0):r.topMessageId}}function Pe(e,t,n){const r=f(e,t);if(n===d._f){if(!r)return}else{const r=ee(e,t,n);if(!r||void 0!==r.lastMessageId&&r.lastMessageId===r.lastReadInboxMessageId)return}const o=W(e,t,n),a=j(e,t,n),s=B(e,t);if(!s||!o&&!a)return;const i=Ee(e,t,n);if(!i&&r&&r.isNotJoined)return;const c=t===u.aw?e.serviceNotifications.reduce(((e,t)=>!t.isUnread&&t.id>e?t.id:e),-1):-1;function l(e){return i?e.find((e=>e>i&&s[e]&&(!s[e].isOutgoing||s[e].isFromScheduled)&&e>c)):e[0]}if(o){const e=l(o);if(e)return e}if(a){const e=l(a);if(e)return e}}function Me(e){const{forwardMessages:t}=e;return Boolean(t.isModalShown)}function Ae(e,t){const n=Object.values(e.chats.byId).find((e=>(0,a.Ru)(e)&&e.lastMessage&&e.lastMessage.id===t));if(n)return n.id;const{byChatId:r}=e.messages;return Object.keys(r).find((n=>{const o=f(e,n);return o&&(0,a.Ru)(o)&&r[o.id].byId[t]}))}function ke(e){const{selectedMessages:t}=e;return Boolean(t)}function Te(e,t){const{messageIds:n}=e.selectedMessages||{};return!!n&&n.includes(t)}function Ne(e,t,n){const r=B(e,t);if(r)return Object.values(r).filter((e=>e.groupedId===n&&e.forwardInfo)).map((({forwardInfo:e})=>e.fromMessageId))}function Le(e,t,n){const r=B(e,t);if(r)return Object.keys(r).map(Number).filter((e=>r[e].groupedId===n))}function Re(e,t,n){const{messageIds:r}=e.selectedMessages||{};if(!r)return!1;const o=Le(e,t,n);return o&&o.every((e=>r.includes(e)))}function De(e){const{messageIds:t}=e.selectedMessages||{};return t?t.length:0}function Oe(e,t){const n=f(e,t);if(!n)return;if(!p(e,n))return;const r=B(e,t),o=G(e,t,d._f);if(!r||!o)return;const u=(0,k.dF)(o,(e=>!r[e].isOutgoing&&Boolean(r[e].keyboardButtons))),a=(0,k.dF)(o,(e=>Boolean(r[e].shouldHideKeyboardButtons)));return u&&a&&a>u?void 0:u?r[u]:void 0}function xe(e,t,n,r){const o=Boolean((0,a.O$)(t)||(0,a.F$)(t)),d=Boolean((0,a.b7)(t)||(0,a.Cg)(t)),u=Boolean((0,a.oP)(t)||(0,a.kd)(t)||(0,a.aE)(t)),{canAutoLoadPhotoFromContacts:s,canAutoLoadPhotoInPrivateChats:i,canAutoLoadPhotoInGroups:c,canAutoLoadPhotoInChannels:l,canAutoLoadVideoFromContacts:f,canAutoLoadVideoInPrivateChats:h,canAutoLoadVideoInGroups:m,canAutoLoadVideoInChannels:p,canAutoLoadFileFromContacts:g,canAutoLoadFileInPrivateChats:y,canAutoLoadFileInGroups:v,canAutoLoadFileInChannels:b}=e.settings.byKey;return o?_e({global:e,chat:n,sender:r,canAutoLoadMediaFromContacts:s,canAutoLoadMediaInPrivateChats:i,canAutoLoadMediaInGroups:c,canAutoLoadMediaInChannels:l}):d?_e({global:e,chat:n,sender:r,canAutoLoadMediaFromContacts:f,canAutoLoadMediaInPrivateChats:h,canAutoLoadMediaInGroups:m,canAutoLoadMediaInChannels:p}):!u||_e({global:e,chat:n,sender:r,canAutoLoadMediaFromContacts:g,canAutoLoadMediaInPrivateChats:y,canAutoLoadMediaInGroups:v,canAutoLoadMediaInChannels:b})}function _e({global:e,chat:t,sender:n,canAutoLoadMediaFromContacts:r,canAutoLoadMediaInPrivateChats:o,canAutoLoadMediaInGroups:d,canAutoLoadMediaInChannels:u}){const s=Boolean(n&&(n.id===e.currentUserId||function(e,t){return e.contactList&&e.contactList.userIds.includes(t.id)}(e,n)));return Boolean(s&&r||!s&&o&&(0,a.YC)(t.id)||d&&(0,a.Bf)(t)||u&&(0,a.eA)(t))}function Ze(e,t){const n=(0,a.b7)(t)||(0,a.Cg)(t);if(!n)return;const{canAutoPlayVideos:r,canAutoPlayGifs:o}=e.settings.byKey,d=n.isGif||n.isRound;return r&&!d||o&&d}function Fe(e){return e.settings.byKey.shouldLoopStickers}function Be(e){const{serviceNotifications:t}=e,n=Math.max(...t.map((({id:e})=>e)));return t.find((({id:e})=>e===n))}function $e(e){const{chatId:t,threadId:n}=Z(e)||{};if(!t||!n)return;const r=(0,a.uw)(t,n),o=e.localTextSearch.byChatThreadKey[r];return o&&o.isActive?o:void 0}function Ue(e){const{byChatId:t}=e.localMediaSearch,{chatId:n}=Z(e)||{},r=e.users.selectedId;return r&&t[r]?r:n}function je(e){const t=Ue(e);if(t)return e.localMediaSearch.byChatId[t]}function We(e,t){return e.management.byChatId[t]}function Ve(e){const{chatId:t,threadId:n}=Z(e)||{};if(!t||!n)return;if((0,a.YC)(t))return"user";const r=f(e,t);return r?(0,a.Bf)(r)?"group":"channel":void 0}function Ge(e){const{mediaViewer:t}=e;return Boolean(t.messageId||t.avatarOwnerId)}function He(e){const{users:t,isChatInfoShown:n,newChatMembersProgress:d}=e,u=d!==r.WB.Closed,a=function(e){const{pollResults:t}=e;return Boolean(t.messageId)}(e),s=Boolean(!o.wB&&$e(e)),i=function(e){const{chatId:t,threadId:n}=Z(e)||{};if(!t||!n)return;const r=e.management.byChatId[t];return r&&r.isActive?r:void 0}(e),c=void 0!==T(e).query,l=void 0!==N(e).query,{chatId:f}=Z(e)||{},h=t.selectedId,m=w(e),p=Boolean(h&&m),g=Boolean(f&&m)&&n;return a?r.qt.PollResults:s?r.qt.Search:i?r.qt.Management:c?r.qt.StickerSearch:l?r.qt.GifSearch:u?r.qt.AddingMembers:p?r.qt.UserInfo:g?r.qt.ChatInfo:void 0}function ze(e){return void 0!==He(e)}function Qe(e){const{theme:t,shouldUseSystemTheme:n}=e.settings.byKey;return n?(0,o.vn)():t}function Ke(e){return e.globalSearch.query}function Je(e){return e.payment.chatId}function qe(e){return e.payment.messageId}function Ye(e){return e.payment.formId}function Xe(e){return e.payment.requestId}function et(e){return e.payment.nativeParams?e.payment.nativeParams.publishableKey:void 0}function tt(e){return e.payment.stripeCredentials}},1713:(e,t,n)=>{let r,o,d,u,a,s,i,c,l,f,h,m,p,g;n.d(t,{Uq:()=>r,fo:()=>o,MT:()=>d,du:()=>u,nJ:()=>a,qt:()=>s,bZ:()=>i,Cr:()=>c,Nh:()=>l,rN:()=>f,wv:()=>h,WB:()=>m,vi:()=>p,KB:()=>g,mp:()=>y,u1:()=>v}),function(e){e[e.Backwards=0]="Backwards",e[e.Forwards=1]="Forwards",e[e.Around=2]="Around"}(r||(r={})),function(e){e[e.Up=0]="Up",e[e.Down=1]="Down",e[e.Static=2]="Static"}(o||(o={})),function(e){e[e.Main=0]="Main",e[e.EditProfile=1]="EditProfile",e[e.Notifications=2]="Notifications",e[e.DataStorage=3]="DataStorage",e[e.Language=4]="Language",e[e.General=5]="General",e[e.GeneralChatBackground=6]="GeneralChatBackground",e[e.GeneralChatBackgroundColor=7]="GeneralChatBackgroundColor",e[e.Privacy=8]="Privacy",e[e.PrivacyPhoneNumber=9]="PrivacyPhoneNumber",e[e.PrivacyLastSeen=10]="PrivacyLastSeen",e[e.PrivacyProfilePhoto=11]="PrivacyProfilePhoto",e[e.PrivacyForwarding=12]="PrivacyForwarding",e[e.PrivacyGroupChats=13]="PrivacyGroupChats",e[e.PrivacyPhoneNumberAllowedContacts=14]="PrivacyPhoneNumberAllowedContacts",e[e.PrivacyPhoneNumberDeniedContacts=15]="PrivacyPhoneNumberDeniedContacts",e[e.PrivacyLastSeenAllowedContacts=16]="PrivacyLastSeenAllowedContacts",e[e.PrivacyLastSeenDeniedContacts=17]="PrivacyLastSeenDeniedContacts",e[e.PrivacyProfilePhotoAllowedContacts=18]="PrivacyProfilePhotoAllowedContacts",e[e.PrivacyProfilePhotoDeniedContacts=19]="PrivacyProfilePhotoDeniedContacts",e[e.PrivacyForwardingAllowedContacts=20]="PrivacyForwardingAllowedContacts",e[e.PrivacyForwardingDeniedContacts=21]="PrivacyForwardingDeniedContacts",e[e.PrivacyGroupChatsAllowedContacts=22]="PrivacyGroupChatsAllowedContacts",e[e.PrivacyGroupChatsDeniedContacts=23]="PrivacyGroupChatsDeniedContacts",e[e.PrivacyActiveSessions=24]="PrivacyActiveSessions",e[e.PrivacyBlockedUsers=25]="PrivacyBlockedUsers",e[e.Folders=26]="Folders",e[e.FoldersCreateFolder=27]="FoldersCreateFolder",e[e.FoldersEditFolder=28]="FoldersEditFolder",e[e.FoldersEditFolderFromChatList=29]="FoldersEditFolderFromChatList",e[e.FoldersIncludedChats=30]="FoldersIncludedChats",e[e.FoldersIncludedChatsFromChatList=31]="FoldersIncludedChatsFromChatList",e[e.FoldersExcludedChats=32]="FoldersExcludedChats",e[e.FoldersExcludedChatsFromChatList=33]="FoldersExcludedChatsFromChatList",e[e.TwoFaDisabled=34]="TwoFaDisabled",e[e.TwoFaNewPassword=35]="TwoFaNewPassword",e[e.TwoFaNewPasswordConfirm=36]="TwoFaNewPasswordConfirm",e[e.TwoFaNewPasswordHint=37]="TwoFaNewPasswordHint",e[e.TwoFaNewPasswordEmail=38]="TwoFaNewPasswordEmail",e[e.TwoFaNewPasswordEmailCode=39]="TwoFaNewPasswordEmailCode",e[e.TwoFaEnabled=40]="TwoFaEnabled",e[e.TwoFaChangePasswordCurrent=41]="TwoFaChangePasswordCurrent",e[e.TwoFaChangePasswordNew=42]="TwoFaChangePasswordNew",e[e.TwoFaChangePasswordConfirm=43]="TwoFaChangePasswordConfirm",e[e.TwoFaChangePasswordHint=44]="TwoFaChangePasswordHint",e[e.TwoFaTurnOff=45]="TwoFaTurnOff",e[e.TwoFaRecoveryEmailCurrentPassword=46]="TwoFaRecoveryEmailCurrentPassword",e[e.TwoFaRecoveryEmail=47]="TwoFaRecoveryEmail",e[e.TwoFaRecoveryEmailCode=48]="TwoFaRecoveryEmailCode",e[e.TwoFaCongratulations=49]="TwoFaCongratulations"}(d||(d={})),function(e){e[e.ChatList=0]="ChatList",e[e.GlobalSearch=1]="GlobalSearch",e[e.Settings=2]="Settings",e[e.Contacts=3]="Contacts",e[e.Archived=4]="Archived",e[e.NewChannelStep1=5]="NewChannelStep1",e[e.NewChannelStep2=6]="NewChannelStep2",e[e.NewGroupStep1=7]="NewGroupStep1",e[e.NewGroupStep2=8]="NewGroupStep2"}(u||(u={})),function(e){e[e.ChatList=0]="ChatList",e[e.Media=1]="Media",e[e.Links=2]="Links",e[e.Files=3]="Files",e[e.Music=4]="Music",e[e.Voice=5]="Voice"}(a||(a={})),function(e){e[e.ChatInfo=0]="ChatInfo",e[e.UserInfo=1]="UserInfo",e[e.Search=2]="Search",e[e.Management=3]="Management",e[e.StickerSearch=4]="StickerSearch",e[e.GifSearch=5]="GifSearch",e[e.PollResults=6]="PollResults",e[e.AddingMembers=7]="AddingMembers"}(s||(s={})),function(e){e[e.Inline=0]="Inline",e[e.ScheduledInline=1]="ScheduledInline",e[e.SharedMedia=2]="SharedMedia",e[e.ProfileAvatar=3]="ProfileAvatar",e[e.SettingsAvatar=4]="SettingsAvatar",e[e.MiddleHeaderAvatar=5]="MiddleHeaderAvatar",e[e.Album=6]="Album",e[e.ScheduledAlbum=7]="ScheduledAlbum",e[e.SearchResult=8]="SearchResult"}(i||(i={})),function(e){e[e.Inline=0]="Inline",e[e.SharedMedia=1]="SharedMedia",e[e.Search=2]="Search"}(c||(c={})),function(e){e[e.Idle=0]="Idle",e[e.InProgress=1]="InProgress",e[e.Complete=2]="Complete",e[e.Error=3]="Error"}(l||(l={})),function(e){e[e.Idle=0]="Idle",e[e.InProgress=1]="InProgress",e[e.Complete=2]="Complete",e[e.Error=3]="Error"}(f||(f={})),function(e){e[e.Idle=0]="Idle",e[e.InProgress=1]="InProgress",e[e.Complete=2]="Complete",e[e.Error=3]="Error"}(h||(h={})),function(e){e[e.Closed=0]="Closed",e[e.InProgress=1]="InProgress",e[e.Loading=2]="Loading"}(m||(m={})),function(e){e[e.Profile=0]="Profile",e[e.SharedMedia=1]="SharedMedia",e[e.MemberList=2]="MemberList"}(p||(p={})),function(e){e[e.ShippingInfo=0]="ShippingInfo",e[e.Shipping=1]="Shipping",e[e.PaymentInfo=2]="PaymentInfo",e[e.Checkout=3]="Checkout"}(g||(g={}));const y="UPLOADING_WALLPAPER_SLUG";let v;!function(e){e[e.Initial=0]="Initial",e[e.ChatPrivacyType=1]="ChatPrivacyType",e[e.Discussion=2]="Discussion",e[e.ChannelSubscribers=3]="ChannelSubscribers",e[e.GroupType=4]="GroupType",e[e.GroupPermissions=5]="GroupPermissions",e[e.GroupRemovedUsers=6]="GroupRemovedUsers",e[e.GroupUserPermissionsCreate=7]="GroupUserPermissionsCreate",e[e.GroupUserPermissions=8]="GroupUserPermissions",e[e.ChatAdministrators=9]="ChatAdministrators",e[e.GroupRecentActions=10]="GroupRecentActions",e[e.ChatAdminRights=11]="ChatAdminRights",e[e.GroupMembers=12]="GroupMembers"}(v||(v={}))},9933:(e,t,n)=>{n.d(t,{c:()=>d,j:()=>u});var r=n(9118);let o;function d(e,t){t||(o&&!o.isCancelled&&(o.isCancelled=!0),o=t={isCancelled:!1}),(0,r.T2)((()=>{!t.isCancelled&&e()&&d(e,t)}))}function u(e){(0,r.T2)((()=>{e()&&u(e)}))}},7358:(e,t,n)=>{n.d(t,{w:()=>o});var r=n(3716);function o(e){"function"==typeof window.navigator.setAppBadge&&window.navigator.setAppBadge(e).catch((e=>{r.eM&&console.error(e)}))}},275:(e,t,n)=>{function r(e,t){if(e===t)return!0;const n=Object.keys(e),r=n.length;if(r!==Object.keys(t).length)return!1;if(0===r)return!0;for(let o=0;o(e[r]!==t[r]&&n.push(`${r}: ${e[r]} => ${t[r]}`),n)),[])}n.d(t,{Z:()=>r,c:()=>o})},6752:(e,t,n)=>{n.d(t,{Z:()=>r});const r=(...e)=>e.filter(Boolean).join(" ")},9524:(e,t,n)=>{n.d(t,{Type:()=>o,fetch:()=>d,save:()=>u,clear:()=>a});const r=self.caches;let o;async function d(e,t,n,d=!1){if(r)try{const u=new Request(t.replace(/:/g,"_")),a=await r.open(e),s=await a.match(u);if(!s)return;const i=s.headers.get("Content-Type");switch(n){case o.Text:return await s.text();case o.Blob:{if(t.startsWith("avatar")&&i&&i.startsWith("text"))return;const e=await s.blob();if(t.startsWith("sticker"))return new Blob([e],{type:"image/webp"});const n=!e.type||!d&&e.type.includes("html");let r=e.type||i;return n&&r?(d||(r=r.replace(/html/gi,"")),new Blob([e],{type:r})):e}case o.Json:return await s.json();default:return}}catch(e){return void console.warn(e)}}async function u(e,t,n){if(r)try{const o="string"==typeof n||n instanceof Blob?n:JSON.stringify(n),d=new Request(t.replace(/:/g,"_")),u=new Response(o),a=await r.open(e);return await a.put(d,u)}catch(e){return void console.warn(e)}}async function a(e){try{if(!r)return;return await r.delete(e)}catch(e){return void console.warn(e)}}!function(e){e[e.Text=0]="Text",e[e.Blob=1]="Blob",e[e.Json=2]="Json"}(o||(o={}))},3989:(e,t,n)=>{n.d(t,{Z:()=>o});var r=n(517);function o(e){return(0,r.Z)({onEsc:e})}},517:(e,t,n)=>{n.d(t,{Z:()=>d});const r={Enter:"onEnter",Backspace:"onBackspace",Delete:"onDelete",Esc:"onEsc",Escape:"onEsc",ArrowUp:"onUp",ArrowDown:"onDown",ArrowLeft:"onLeft",ArrowRight:"onRight",Tab:"onTab"},o={onEnter:[],onDelete:[],onBackspace:[],onEsc:[],onUp:[],onDown:[],onLeft:[],onRight:[],onTab:[]};function d(e){return u()||document.addEventListener("keydown",a,!0),Object.keys(e).forEach((t=>{const n=e[t];if(!n)return;const r=o[t];r&&r.push(n)})),()=>{!function(e){Object.keys(e).forEach((t=>{const n=e[t],r=o[t];if(r){const e=r.findIndex((e=>e===n));-1!==e&&r.splice(e,1)}})),u()||document.removeEventListener("keydown",a,!1)}(e)}}function u(){return Object.values(o).some((e=>Boolean(e.length)))}function a(e){const t=r[e.key];if(!t)return;const{length:n}=o[t];n&&(e.stopPropagation(),(0,o[t][n-1])(e))}},790:(e,t,n)=>{n.d(t,{$Y:()=>u,_F:()=>a,kj:()=>s,mr:()=>c,VX:()=>l,Tu:()=>f,np:()=>h,j1:()=>m,ZK:()=>g,k9:()=>y,rM:()=>v,xH:()=>b,xk:()=>I,IS:()=>C});const r=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],o=["January","February","March","April","May","June","July","August","September","October","November","December"],d=o.map((e=>e.toLowerCase()));function u(e){const t=new Date(e);return t.setHours(0,0,0,0),t}function a(e){return u(e).getTime()}function s(e){const t=new Date(1e3*e);return`${t.getFullYear()}-${t.getMonth()}`}function i(e){return`${e.getFullYear()}-${e.getMonth()+1}-${e.getDate()}`}function c(e,t){const n="number"==typeof e?new Date(e):e,r=t.timeFormat||"24h";let o=n.getHours(),d="";return"12h"===r&&(d=o>=12?" PM":" AM",o=o>12?o%12:o),`${String(o).padStart(2,"0")}:${String(n.getMinutes()).padStart(2,"0")}${d}`}function l(e,t){const n="number"==typeof t?new Date(t):t,o=u(new Date);if(n>=o)return c(n,e);const d=new Date(o);if(d.setDate(o.getDate()-7),n>=d)return e(`Weekday.Short${r[n.getDay()]}`);const a=n.getFullYear()!==o.getFullYear(),s=e(a?"formatDateScheduleYear":"formatDateSchedule")||(a?"d MMM yyyy":"d MMM");return p(e,n,s)}function f(e,t){const n="number"==typeof t?new Date(t):t,r=e("formatterYearMax")||"dd.MM.yyyy";return p(e,n,r)}function h(e,t,n=!1){const r=e(n?"formatterMonthYear2":"formatterMonthYear")||"MMM yyyy";return p(e,t,r)}function m(e,t,n=!1,o=!1,d){const a="number"==typeof t?new Date(t):t,s=u(new Date);if(!o){if(i(a)===i(s))return(d||!n?E:S)(e("Weekday.Today"));const t=new Date(s);if(t.setDate(s.getDate()-1),i(a)===i(t))return(d||!n?E:S)(e("Weekday.Yesterday"));const o=new Date(s),u=new Date(s);if(o.setDate(s.getDate()-7),u.setDate(s.getDate()+7),a>=o&&a<=u){const t=r[a.getDay()];return(d||!n?E:S)(e(n?`Weekday.Short${t}`:`Weekday.${t}`))}}const c=a.getFullYear()!==s.getFullYear(),l=e(n?c?"formatDateScheduleYear":"formatDateSchedule":c?"chatFullDate":"chatDate")||"d MMMM yyyy";return(d||!n?E:S)(p(e,a,l))}function p(e,t,n){const r=t.getDate(),d=t.getMonth();return n.replace("LLLL",e(o[d])).replace("MMMM",e(`Month.Gen${o[d]}`)).replace("MMM",e(`Month.Short${o[d]}`)).replace("MM",String(d+1).padStart(2,"0")).replace("dd",String(r).padStart(2,"0")).replace("d",String(r)).replace("yyyy",String(t.getFullYear()))}function g(e,t,n){const r="number"==typeof t?new Date(t):t;return`${m(e,r,!0,void 0,n)}, ${c(r,e)}`}function y(e,t){const n=Math.floor(e/3600),r=Math.floor(e%3600/60),o=Math.floor(e%3600%60),d=t?Math.floor(t/3600):0,u=t?Math.floor(t%3600/60):0;let a="";return n>0||d>0?(a+=`${String(n).padStart(2,"0")}:`,a+=`${String(r).padStart(2,"0")}:`):a+=u>=10?`${String(r).padStart(2,"0")}:`:`${String(r)}:`,a+=String(o).padStart(2,"0"),a}function v(e){const t=[];let n=e%1e3;e-=n,n=Math.floor(n/10);const r=(e=Math.floor(e/1e3))%60;e-=r;const o=(e=Math.floor(e/60))%60;e-=o;const d=(e=Math.floor(e/60))%60;return d>0&&t.push(String(d).padStart(2,"0")),t.push(String(o).padStart(d>0?2:1,"0")),t.push(String(r).padStart(2,"0")),`${t.join(":")},${String(n).padStart(2,"0")}`}function b(e,t="en-US"){return e.toLocaleString(t,{year:"numeric",month:"short",day:"numeric"})}function w(e,t,n=2021){if(t>11||e>31)return!1;const r=new Date(n,t,e);return!Number.isNaN(r.getTime())&&r.getDate()===e}function I(e=""){const t=e.match(/\d{1,2}\s[a-zA-Z]{3,}/),n=e.match(/[a-zA-Z]{3,}\s\d{1,2}/),r=e.match(/\d{1,2}[./-]\d{1,2}([./-]\d{2,4})?/);if(!t&&!r&&!n)return;if(r){const[t,n,r]=e.split(/[./-]/).map(Number);return r&&r<2015||!w(t,n-1,r||void 0)?void 0:`${r?`${r}-`:""}${String(n).padStart(2,"0")}-${String(t).padStart(2,"0")}`}const o=e.split(" "),u=t?o[0]:o[1],a=(t?o[1]:o[0]).toLowerCase(),s=d.findIndex((e=>e.startsWith(a)));return-1!==s&&w(Number(u),s)?`${String(s+1).padStart(2,"0")}-${String(u).padStart(2,"0")}`:void 0}function C(e){return e+86400}function S(e){return`${e[0].toLowerCase()}${e.slice(1)}`}function E(e){return`${e[0].toUpperCase()}${e.slice(1)}`}},4284:(e,t,n)=>{n.d(t,{g6:()=>a,U_:()=>s,NM:()=>i,Wg:()=>c});var r=n(3681);const o=["female_sign","male_sign","medical_symbol"],d=[[/\u{1f3f3}\u200d\u{1f308}/gu,"🏳️‍🌈"],[/\u{1f3f3}\u200d\u26a7\ufe0f/gu,"🏳️‍⚧️"],[/\u{1f937}\u200d\u2642/gu,"🤷‍♂️"]];function u(e){const t=e.split("-").map((e=>parseInt(e,16)));return String.fromCodePoint(...t)}function a(e){if(!e.match(r.Z))return e;for(const[t,n]of d)e=e.replace(t,n);return e}function s(e){let t;if(1===e.length)t=e.charCodeAt(0).toString(16).padStart(4,"0");else{const n=[];for(let t=0;t=55296&&e.charCodeAt(t)<=56319?e.charCodeAt(t+1)>=56320&&e.charCodeAt(t+1)<=57343&&n.push(1024*(e.charCodeAt(t)-55296)+(e.charCodeAt(t+1)-56320)+65536):(e.charCodeAt(t)<55296||e.charCodeAt(t)>57343)&&n.push(e.charCodeAt(t));t=n.map((e=>e.toString(16).padStart(4,"0"))).join("-")}return t}function i(e){const t={categories:[],emojis:{}};for(let n=0;ne.codePointAt(0)+127397));return String.fromCodePoint(...n)}},7361:(e,t,n)=>{n.d(t,{cL:()=>N,wZ:()=>p,vX:()=>M,op:()=>C,cj:()=>m,jm:()=>h,pA:()=>T,m5:()=>P,I_:()=>E,fl:()=>y,s$:()=>g,Mc:()=>S,wB:()=>b,p7:()=>w,$b:()=>v,mh:()=>I,s0:()=>A,aZ:()=>L,Lt:()=>f,vn:()=>i,on:()=>d});var r=n(3716);let o;function d(){return Boolean(o)}var u,a;new Promise((e=>{const t=new Image;t.src="data:image/webp;base64,UklGRjoAAABXRUJQVlA4IC4AAACyAgCdASoCAAIALmk0mk0iIiIiIgBoSygABc6WWgAA/veff/0PP8bA//LwYAAA";const n=()=>{e(2===t.height)};t.onload=n,t.onerror=n})).then((e=>{o=e}));let s=null!==(u=(a=window).matchMedia)&&void 0!==u&&u.call(a,"(prefers-color-scheme: dark)").matches?"dark":"light";function i(){return s}function c(e){s=e.matches?"dark":"light"}const l=window.matchMedia("(prefers-color-scheme: dark)");"function"==typeof l.addEventListener?l.addEventListener("change",c):"function"==typeof l.addListener&&l.addListener(c);const f=function(){const{userAgent:e,platform:t}=window.navigator;let n;return-1!==["Macintosh","MacIntel","MacPPC","Mac68K"].indexOf(t)?n="macOS":-1!==["iPhone","iPad","iPod"].indexOf(t)?n="iOS":-1!==["Win32","Win64","Windows","WinCE"].indexOf(t)?n="Windows":/Android/.test(e)?n="Android":/Linux/.test(t)&&(n="Linux"),n}(),h="macOS"===f,m="iOS"===f,p="Android"===f,g=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),y=window.matchMedia("(display-mode: standalone)").matches||window.navigator.standalone||document.referrer.includes("android-app://"),v=window.matchMedia("(pointer: coarse)").matches,b=window.innerWidth<=r.l3||window.innerWidth<=r.u_&&window.innerHeight<=r.rO,w=!b&&window.innerWidth<=r.ks,I=Boolean(navigator.mediaDevices&&"getUserMedia"in navigator.mediaDevices&&(window.AudioContext||window.webkitAudioContext)),C=(document.documentElement.style,f&&(h||m)),S="serviceWorker"in navigator,E=S,P=(window,Boolean((new Audio).canPlayType("audio/ogg; codecs=opus"))),M=!r.Cg&&"filter"in(document.createElement("canvas").getContext("2d")||{}),A=p?"slide-fade":m?"slide-layers":"push-slide",k=document.createElement("video"),T=Boolean(k.canPlayType(r.Ng).replace("no","")||m);T&&r.wG.add(r.Ng);const N=window.devicePixelRatio||1,L=!0},1394:(e,t,n)=>{n.d(t,{A9:()=>d,YJ:()=>u,hl:()=>a,pt:()=>s,jj:()=>i,ud:()=>c,gm:()=>l,ao:()=>f});var r=n(9118);function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function d(e){const t=e.split(","),n=t[0].match(/:(.*?);/)[1],r=atob(t[1]);let o=r.length;const d=new Uint8Array(o);for(;o--;)d[o]=r.charCodeAt(o);return new Blob([d],{type:n})}function u(e){return new Promise(((t,n)=>{const r=new FileReader;r.onload=e=>{const{result:r}=e.target||{};"string"==typeof r&&t(r),n(new Error("Failed to read blob"))},r.onerror=n,r.readAsDataURL(e)}))}function a(e,t){return new File([e],t,{lastModified:Date.now(),type:e.type})}function s(e){return new Promise(((t,n)=>{const r=new Image;r.onload=()=>t(r),r.onerror=n,r.src=e}))}function i(e){return new Promise(((t,n)=>{const r=document.createElement("video");r.volume=0,r.onloadedmetadata=()=>t(r),r.onerror=n,r.src=e}))}async function c(e){const t=await i(e);return Promise.race([(0,r.wO)(2e3),new Promise(((e,n)=>{t.onseeked=()=>{t.videoWidth&&t.videoHeight||e(void 0);const n=document.createElement("canvas");n.width=t.videoWidth,n.height=t.videoHeight,n.getContext("2d").drawImage(t,0,0),e(n.toDataURL("image/jpeg"))},t.onerror=n,t.currentTime=Math.min(t.duration,1)}))])}async function l(e){return(await fetch(e)).blob()}function f(e){const t=document.createElement("canvas");return t.width=e.width,t.height=e.height,t.getContext("2d").drawImage(e,0,0),t}"undefined"==typeof File&&(self.File=class extends Blob{constructor(e,t,n){if(n){const{type:t,...r}=n;super(e,{type:t}),o(this,"name",void 0),Object.assign(this,r)}else super(e),o(this,"name",void 0);this.name=t}})},9937:(e,t,n)=>{function r(e,t,n="en"){return new Intl.NumberFormat(n,{style:"currency",currency:t}).format("JPY"===t?e:e/100)}n.d(t,{x:()=>r})},6926:(e,t,n)=>{n.d(t,{Z:()=>r});const r=e=>{let t;do{t=String(Math.random()).replace("0.","id")}while(e.hasOwnProperty(t));return t}},1947:(e,t,n)=>{n.d(t,{ZP:()=>d,J_:()=>u});const r={CHAT_RESTRICTED:"You can't send messages in this chat, you were restricted",CHAT_WRITE_FORBIDDEN:"You can't write in this chat",CHAT_SEND_POLL_FORBIDDEN:"You can't create polls in this chat",CHAT_SEND_STICKERS_FORBIDDEN:"You can't send stickers in this chat",CHAT_SEND_GIFS_FORBIDDEN:"You can't send gifs in this chat",CHAT_SEND_MEDIA_FORBIDDEN:"You can't send media in this chat",CHAT_LINK_EXISTS:"The chat is public, you can't hide the history to new users",SLOWMODE_WAIT_X:"Slowmode is enabled in this chat: you must wait for the specified number of seconds before sending another message to the chat.",USER_BANNED_IN_CHANNEL:"You're banned from sending messages in supergroups / channels",USER_IS_BLOCKED:"You were blocked by this user",YOU_BLOCKED_USER:"You blocked this user",IMAGE_PROCESS_FAILED:"Failure while processing image",MEDIA_EMPTY:"The provided media object is invalid",MEDIA_INVALID:"Media invalid",PHOTO_EXT_INVALID:"The extension of the photo is invalid",PHOTO_INVALID_DIMENSIONS:"The photo dimensions are invalid",PHOTO_SAVE_FILE_INVALID:"Internal issues, try again later",MESSAGE_DELETE_FORBIDDEN:"You can't delete one of the messages you tried to delete, most likely because it is a service message.",MESSAGE_POLL_CLOSED:"Poll closed",MESSAGE_EDIT_TIME_EXPIRED:"You can't edit this message anymore.",CHAT_ADMIN_REQUIRED:"You must be an admin in this chat to do this",PINNED_DIALOGS_TOO_MUCH:"Sorry, you can only pin 5 chats to the top",DIALOG_FILTERS_TOO_MUCH:"Sorry, you can't have more than 10 folders",CHANNEL_PRIVATE:"This channel is private",MEDIA_CAPTION_TOO_LONG:"The provided caption is too long",ADDRESS_STREET_LINE1_INVALID:"The address you provided is not valid",ADDRESS_STREET_LINE2_INVALID:"The address you provided is not valid",ADDRESS_CITY_INVALID:"The city you provided is not valid",ADDRESS_COUNTRY_INVALID:"The country you provided is not valid",ADDRESS_POSTCODE_INVALID:"The postcode you provided is not valid",ADDRESS_STATE_INVALID:"The state you provided is not valid",REQ_INFO_NAME_INVALID:"The name you provided is not valid",REQ_INFO_PHONE_INVALID:"The phone you provided is not valid",REQ_INFO_EMAIL_INVALID:"The email you provided is not valid",LINK_NOT_MODIFIED:"This discussion is already linked to the channel",MESSAGE_TOO_LONG:"Message is too long",SERVICE_WORKER_DISABLED:"Service Worker is disabled. Please reload the page without holding key.",MESSAGE_TOO_LONG_PLEASE_REMOVE_CHARACTERS:"The provided message is too long. Please remove {EXTRA_CHARS_COUNT} character{PLURAL_S}.",FRESH_RESET_AUTHORISATION_FORBIDDEN:"You can’t logout other sessions if less than 24 hours have passed since you logged on the current session",BOTS_TOO_MUCH:"There are too many bots in this chat/channel",BOT_GROUPS_BLOCKED:"This bot can't be added to groups",USERS_TOO_MUCH:"The maximum number of users has been exceeded",USER_CHANNELS_TOO_MUCH:"One of the users you tried to add is already in too many channels/supergroups",USER_KICKED:"This user was kicked from this supergroup/channel",USER_NOT_MUTUAL_CONTACT:"The provided user is not a mutual contact",USER_PRIVACY_RESTRICTED:"The user's privacy settings do not allow you to do this",INVITE_HASH_EMPTY:"The invite hash is empty",INVITE_HASH_EXPIRED:"The invite link has expired",INVITE_HASH_INVALID:"The invite hash is invalid",CHANNELS_TOO_MUCH:"You have joined too many channels/supergroups",USER_ALREADY_PARTICIPANT:"You already in the group",SCHEDULE_DATE_INVALID:"Invalid schedule date provided",WALLPAPER_DIMENSIONS_INVALID:"The wallpaper dimensions are invalid, please select another file"},o={ADDRESS_STREET_LINE1_INVALID:{field:"streetLine1",message:"Incorrect street address"},ADDRESS_STREET_LINE2_INVALID:{field:"streetLine2",message:"Incorrect street address"},ADDRESS_CITY_INVALID:{field:"city",message:"Incorrect city"},ADDRESS_COUNTRY_INVALID:{field:"countryIso2",message:"Incorrect country"},ADDRESS_POSTCODE_INVALID:{field:"postCode",message:"Incorrect post code"},ADDRESS_STATE_INVALID:{field:"state",message:"Incorrect state"},REQ_INFO_NAME_INVALID:{field:"fullName",message:"Incorrect name"},REQ_INFO_PHONE_INVALID:{field:"phone",message:"Incorrect phone"},REQ_INFO_EMAIL_INVALID:{field:"email",message:"Incorrect email"}};function d(e){const{message:t,isSlowMode:n,textParams:o}=e;if(n){const e=t.indexOf(" (caused by");return e>0?t.substring(0,e):t}let d=r[t];return d&&o&&(d=Object.keys(o).reduce(((e,t)=>e.replace(t,o[t])),d)),d}function u(e){return o[e.message]}},3592:(e,t,n)=>{n.d(t,{S:()=>d}),n(3716);var r=n(9118);function o(e){e.preventDefault(),d(e instanceof ErrorEvent?e.error:e.reason)}function d(e){console.error(e)}window.addEventListener("error",o),window.addEventListener("unhandledrejection",o),(0,r.P2)(window.alert,1e3)},782:(e,t,n)=>{function r(e,t){return e.reduce(((e,n)=>(e[n[t]]=n,e)),{})}function o(e,t){return Object.keys(e).reduce(((n,r,o)=>(n[r]=t(e[r],r,o,e),n)),{})}function d(e,t){return t.reduce(((t,n)=>(t[n]=e[n],t)),{})}function u(e,t){return t.reduce(((t,n)=>(e[n]&&(t[n]=e[n]),t)),{})}function a(e,t){const n=new Set(t.map(String));return d(e,Object.keys(e).filter((e=>!n.has(e))))}function s(e,t,n="asc"){return e.sort(((e,r)=>{if(Array.isArray(t)){const[o,d]=Array.isArray(n)?n:[n,n],[u,a]=t;let s,i;if("function"==typeof u?(s=u(e)||0,i=u(r)||0):"string"==typeof u&&(s=e[u]||0,i=r[u]||0),s!==i)return"asc"===o?s-i:i-s;{let t,n;return"function"==typeof a?(t=a(e)||0,n=a(r)||0):"string"==typeof a&&(t=e[a]||0,n=r[a]||0),"asc"===d?t-n:n-t}}let o,d;return"function"==typeof t?(o=t(e)||0,d=t(r)||0):"string"==typeof t&&(o=e[t]||0,d=r[t]||0),"asc"===n?o-d:d-o}))}function i(e){return e.reduce(((e,t)=>Array.isArray(t)?e.concat(t):(e.push(t),e)),[])}function c(e){return Array.from(new Set(e))}function l(e){return e.filter(Boolean)}function f(e,t){return e.length===t.length&&e.every(((e,n)=>e===t[n]))}function h(e,t){return e[0]<=t[t.length-1]&&e[e.length-1]>=t[0]}function m(e,t){return e.filter((e=>t.has(e)))}function p(e,t){const n=[];for(let r=0;r(t[n]=g(e[n]),t)),{})}function y(e,t){let n=e.length;for(;n--;)if(t(e[n],n,e))return e[n]}n.d(t,{ee:()=>r,Q8:()=>o,ei:()=>d,q0:()=>u,CE:()=>a,Xo:()=>s,xH:()=>i,Tw:()=>c,oA:()=>l,et:()=>f,YE:()=>h,eL:()=>m,Vl:()=>p,Xh:()=>g,dF:()=>y})},663:(e,t,n)=>{n.d(t,{ll:()=>m,i0:()=>b,Pn:()=>w,m0:()=>I,qf:()=>C});var r=n(5116),o=n(3716),d=n(9524),u=n(1226),a=n(2155);const s=/%\d?\$?[sdf@]/g,i=["value","zeroValue","oneValue","twoValue","fewValue","manyValue","otherValue"],c={en:e=>1!==e?6:2,ar:e=>0===e?1:1===e?2:2===e?3:e%100>=3&&e%100<=10?4:e%100>=11?5:6,ca:e=>1!==e?6:2,de:e=>1!==e?6:2,es:e=>1!==e?6:2,fa:e=>e>1?6:2,fr:e=>e>1?6:2,id:()=>0,it:e=>1!==e?6:2,ko:()=>0,ms:()=>0,nl:e=>1!==e?6:2,pl:e=>1===e?2:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?4:5,pt_BR:e=>e>1?6:2,ru:e=>e%10==1&&e%100!=11?2:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?4:5,tr:e=>e>1?6:2,uk:e=>e%10==1&&e%100!=11?2:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?4:5,uz:e=>e>1?6:2},l=new Map;let f,h;const{addCallback:m,removeCallback:p,runCallbacks:g}=function(){const e=[];function t(t){const n=e.indexOf(t);-1!==n&&e.splice(n,1)}return{runCallbacks:function(...t){e.forEach((e=>{e(...t)}))},addCallback:function(n){return e.push(n),()=>{t(n)}},removeCallback:t}}();let y,v;const b=(e,t,n)=>{var r,o;if(void 0!==t){const r=Array.isArray(t)?JSON.stringify(t):t,o=l.get(`${e}_${r}_${n}`);if(o)return o}if(!f&&!h)return e;const d=(null===(r=f)||void 0===r?void 0:r[e])||(null===(o=h)||void 0===o?void 0:o[e]);return d?E(d,e,t,n):(h||S(),e)};async function w(e,t){let n=await d.fetch(o.ee,`${o.$O}_${e}_${t}`,d.Type.Json);return n||(n=await async function(e,t,n){const r=await(0,u.t9)("fetchLangStrings",{langPack:e,langCode:t,keys:[n]});if(null!=r&&r.length)return await d.save(o.ee,`${e}_${t}_${n}`,r[0]),r[0]}(o.$O,e,t)),E(n,t)}async function I(e,t,n=!1){if(f&&e===y)return void(t&&t());let a=await d.fetch(o.ee,e,d.Type.Json);if(!a&&(n&&await S(),a=await async function(e){const t=await(0,u.t9)("fetchLangPack",{sourceLangPacks:o.Bg,langCode:e});if(t)return await d.save(o.ee,e,t.langPack),t.langPack}(e),!a))return;l.clear(),y=e,f=a,document.documentElement.lang=e;const{languages:s,timeFormat:i}=(0,r.Rd)().settings.byKey,c=null==s?void 0:s.find((t=>t.langCode===e));b.isRtl=Boolean(null==c?void 0:c.rtl),b.code=e,b.timeFormat=i,t&&t(),g()}function C(e){e&&e===v||(v=e,b.timeFormat=e,g())}async function S(){h||(h=(await n.e(915).then(n.bind(n,1915))).default,g())}function E(e,t,n,r){const d=e?e["number"==typeof n?function(e){const t=y||o.sR,n=c[t]?c[t](e):0;return i[n]}(n):"value"]:void 0;if(!d||!d.trim()){const e=t.split(".");return e[e.length-1]}if(void 0!==n){const e=function(e,t){t=Array.isArray(t)?t:[t];const n=e.split(s),r=n.shift();return n.reduce(((e,n,r)=>`${e}${String(t[r]||"")}${n}`),r||"")}(d,"i"===r?(0,a.kh)(n):n),o=Array.isArray(n)?JSON.stringify(n):n;return l.set(`${t}_${o}_${r}`,e),e}return d}},647:(e,t,n)=>{n.d(t,{cC:()=>b,he:()=>y,UV:()=>v,Iq:()=>w});var r=n(6137),o=n(3716),d=n(1226),u=n(9524),a=n(1394),s=n(7361);const i=48e3;async function c(e){const t=await new Response(e).arrayBuffer();return new Promise((e=>{const r=new Uint8Array(t);let o=new Worker(new URL(n.p+n.u(745),n.b)),d=new Worker(new URL(n.p+n.u(993),n.b));o.onmessage=e=>{null===e.data?d.postMessage({command:"done"}):d.postMessage({command:"encode",buffers:e.data},e.data.map((({buffer:e})=>e)))},d.onmessage=t=>{"page"===t.data.message&&(e(new Blob([t.data.page],{type:"audio/wav"})),o.terminate(),o=void 0,d.terminate(),d=void 0)},d.postMessage({command:"init",wavBitDepth:16,wavSampleRate:i}),o.postMessage({command:"init",decoderSampleRate:i,outputBufferSampleRate:i}),o.postMessage({command:"decode",pages:r},[r.buffer])}))}var l=n(862);const f={[r.IU.BlobUrl]:u.Type.Blob,[r.IU.Lottie]:u.Type.Json,[r.IU.Progressive]:void 0,[r.IU.Stream]:void 0},h=new Map,m=new Map,p=new Map,g=new Map;function y(e,t,n=!1,i,v){if(t===r.IU.Progressive)return s.I_?function(e){const t=`./progressive/${e}`;return h.set(e,t),Promise.resolve(t)}(e):y(e,r.IU.BlobUrl,n,i,v);if(!m.has(e)){const i=async function(e,t,n){if(!o.Cy){const r=e.startsWith("avatar")?o.SG:o.lW,d=await u.fetch(r,e,f[t],n);if(d){let t=d;if("audio/ogg"!==d.type||s.m5||(t=await c(t)),"image/webp"===d.type&&!(0,s.on)()&&t){const n=await(0,l._y)(e,t);n&&(t=n)}const n=C(t);return h.set(e,n),n}}if(t===r.IU.Stream){const n=new MediaSource,r=URL.createObjectURL(n);let o=!1;return n.addEventListener("sourceopen",(()=>{if(o)return;o=!0;const r=n.addSourceBuffer("audio/mpeg"),u=I(e,n,r);g.set(e,u),(0,d.t9)("downloadMedia",{url:e,mediaFormat:t},u)})),h.set(e,r),r}const i=I(e);g.set(e,i);const m=await(0,d.t9)("downloadMedia",{url:e,mediaFormat:t,isHtmlAllowed:n},i);if(!m)throw new Error(`Failed to fetch media ${e}`);let{prepared:p,mimeType:y}=m;if("audio/ogg"===y&&!s.m5){const e=await(0,a.gm)(p);URL.revokeObjectURL(p);const t=await c(e);p=C(t),y=t.type}if("image/webp"===y&&!(0,s.on)()){const t=await(0,a.gm)(p);URL.revokeObjectURL(p);const n=await(0,l._y)(e,t);n&&(p=C(n))}return h.set(e,p),p}(e,t,n).catch((e=>{o.eM&&console.warn(e)})).finally((()=>{m.delete(e),p.delete(e),g.delete(e)}));m.set(e,i)}if(i&&v){let t=p.get(e);t||(t=new Map,p.set(e,t)),t.set(v,i)}return m.get(e)}function v(e){return h.get(e)}function b(e){p.forEach(((t,n)=>{t.forEach((t=>{if(t===e){const e=g.get(n);if(!e)return;(0,d.u3)(e),g.delete(n),p.delete(n)}}))}))}function w(e,t){const n=p.get(e);n&&n.delete(t)}function I(e,t,n){const r=(o,d)=>{var u;null===(u=p.get(e))||void 0===u||u.forEach((e=>{e(o),e.isCanceled&&(r.isCanceled=!0)})),1===o&&(null==t||t.endOfStream()),d&&(null==n||n.appendBuffer(d))};return r}function C(e){return e instanceof Blob?URL.createObjectURL(e):e}s.I_&&navigator.serviceWorker.addEventListener("message",(async e=>{const{type:t,messageId:n,params:o}=e.data;if("requestPart"!==t)return;const u=await(0,d.t9)("downloadMedia",{mediaFormat:r.IU.Progressive,...o});if(!u)return;const{arrayBuffer:a,mimeType:s,fullSize:i}=u;navigator.serviceWorker.controller.postMessage({type:"partResponse",messageId:n,result:{arrayBuffer:a,mimeType:s,fullSize:i}},[a])}))},735:(e,t,n)=>{n.d(t,{D:()=>r});const r=[]},9203:(e,t,n)=>{n.d(t,{gl:()=>o,$y:()=>a,o5:()=>s,Qt:()=>c});var r=n(3716);let o;!function(e){e[e.Auth=0]="Auth",e[e.Main=1]="Main",e[e.Extra=2]="Extra"}(o||(o={}));const d={},u={};async function a(e,t){if(!d[e]){switch(e){case o.Auth:d[o.Auth]=n.e(133).then(n.bind(n,1133));break;case o.Main:r.eM&&console.log(">>> START LOAD MAIN BUNDLE"),d[o.Main]=Promise.all([n.e(306),n.e(325)]).then(n.bind(n,325));break;case o.Extra:d[o.Extra]=Promise.all([n.e(306),n.e(701)]).then(n.bind(n,9701))}d[e].then(l)}const a=await d[e];return u[e]||(u[e]=a),s(e,t)}function s(e,t){const n=u[e];if(n)return n[t]}const i=[];function c(e){i.includes(e)||i.push(e)}function l(){i.forEach((e=>{e()}))}},8406:(e,t,n)=>{n.d(t,{q3:()=>v,Nz:()=>b,r1:()=>C,Ld:()=>E,zP:()=>P,Vr:()=>M,KC:()=>A});var r=n(1226),o=n(6137),d=n(2864),u=n(3716),a=n(5116),s=n(2858),i=n(663),c=n(1752),l=n(8085),f=n(7361),h=n(647),m=n(9118);function p(e){const t=e.toJSON();return JSON.stringify({endpoint:t.endpoint,keys:t.keys})}function g(){return!!f.Mc&&("showNotification"in ServiceWorkerRegistration.prototype?"denied"===Notification.permission?(u.eM&&console.warn("[PUSH] The user has blocked push notifications."),!1):"PushManager"in window||(u.eM&&console.warn("[PUSH] Push messaging isn't supported."),!1):(u.eM&&console.warn("[PUSH] Push notifications aren't supported."),!1))}const y=new Set;async function v(e,t){if(void 0!==e&&y.has(e))return;const{notificationSoundVolume:n}=(0,l.dZ)((0,a.Rd)()),r=t?t/10:n/10;if(0===r)return;const o=new Audio("./notification.mp3");o.volume=r,o.setAttribute("mozaudiochannel","notification"),void 0!==e&&(o.addEventListener("ended",(()=>{y.add(e)}),{once:!0}),setTimeout((()=>{y.delete(e)}),3e3));try{await o.play()}catch(e){u.eM&&console.warn("[PUSH] Unable to play notification sound")}}const b=(0,m.Ds)(v,1e3,!0,!1);async function w(){"Notification"in window&&(["granted","denied"].includes(Notification.permission)||await Notification.requestPermission())}async function I(e){const t=(0,a.Rd)(),n=(0,a.uC)();if(e)try{const t=p(e);return await(0,r.t9)("unregisterDevice",t),await e.unsubscribe(),void n.deleteDeviceToken()}catch(e){u.eM&&console.log("[PUSH] Unable to unsubscribe from push.",e)}t.push&&(await(0,r.t9)("unregisterDevice",t.push.deviceToken),n.deleteDeviceToken())}async function C(){if(!g())return;const e=await navigator.serviceWorker.ready,t=await e.pushManager.getSubscription();await I(t)}let S=!1;async function E(){if(!g())return void await w();const e=await navigator.serviceWorker.ready;let t=await e.pushManager.getSubscription();if(function(e){const t=(0,a.Rd)();return!t.push||!e||p(e)!==t.push.deviceToken||Date.now()-t.push.subscribedAt>432e5}(t)){await I(t);try{t=await e.pushManager.subscribe({userVisibleOnly:!0});const n=p(t);u.eM&&console.log("[PUSH] Received push subscription: ",n),await(0,r.t9)("registerDevice",n),(0,a.uC)().setDeviceToken(n)}catch(e){"denied"===Notification.permission?u.eM&&console.warn("[PUSH] The user has blocked push notifications."):u.eM&&(console.log("[PUSH] Unable to subscribe to push.",e),e.code===DOMException.ABORT_ERR&&await w())}}}async function P({chat:e,message:t}){const{hasWebNotifications:n}=await async function(){if(S)return(0,l.dZ)((0,a.Rd)());const[e,t]=await Promise.all([(0,r.t9)("fetchNotificationSettings",{serverTimeOffset:(0,a.Rd)().serverTimeOffset}),(0,r.t9)("fetchNotificationExceptions",{serverTimeOffset:(0,a.Rd)().serverTimeOffset})]);if(!e)return(0,l.dZ)((0,a.Rd)());let n=(0,c.BI)((0,a.Rd)(),e);return t&&(n=(0,c.aJ)(n,t)),(0,a.R3)(n),S=!0,(0,l.dZ)(n)}();if(!function(e){if(!S)return!1;const t=(0,a.Rd)();return!((0,s.i4)(e,(0,l.dZ)(t),(0,l.NJ)(t))||e.isNotJoined||!e.isListed||document.hasFocus())}(e))return;if(!n)return void b(String(t.id)||e.id);if(!("Notification"in window?"denied"!==Notification.permission||(u.eM&&console.warn("[PUSH] The user has blocked push notifications."),0):(u.eM&&console.warn("[PUSH] This browser does not support desktop notification"),0)))return;if(!t.id)return;const{title:f,body:m}=function(e,t){const n=(0,a.Rd)(),{senderId:r,replyToMessageId:o}=t,u=r?(0,l.dy)(n,r):void 0,c=(0,s.N5)(t),f=c&&o?(0,l.hj)(n,e.id,o):void 0,{targetUserIds:h,targetChatId:m}=c||{},p=h?h.map((e=>(0,l.dy)(n,e))).filter(Boolean):void 0,g=(0,s.zX)(e),y=g?(0,l.dy)(n,g):void 0;let v;if((0,s.Sm)(e,(0,l.dZ)(n),(0,l.NJ)(n)))if((0,s.Lo)(t)){const n=e&&((0,s.eA)(e)||t.senderId===t.chatId)?e:u;v=(0,d.D)(i.i0,t,n,p,f,m,{asPlain:!0})}else{const n=(0,s.zF)(i.i0,e.id,u),r=(0,s.MK)(i.i0,t);v=n?`${n}: ${r}`:r}else v="New message";return{title:(0,s.U)(i.i0,e,y),body:v}}(e,t),p=await async function(e){const t=(0,s.RT)(e);if(!t)return;let n=h.UV(t);return n||(await h.he(t,o.IU.BlobUrl),n=h.UV(t)),n}(e);if(g()){var y;null!==(y=navigator.serviceWorker)&&void 0!==y&&y.controller&&navigator.serviceWorker.controller.postMessage({type:"newMessageNotification",payload:{title:f,body:m,icon:p,chatId:e.id,messageId:t.id}})}else{const n=(0,a.uC)(),r={body:m,icon:p,badge:p,tag:String(t.id)};"vibrate"in navigator&&(r.vibrate=[200,100,200]);const o=new Notification(f,r);o.onclick=()=>{o.close(),n.focusMessage({chatId:e.id,messageId:t.id}),window.focus&&window.focus()},o.onshow=()=>{b(String(t.id)||e.id)}}}function M(e){var t;!u.Cg&&null!==(t=navigator.serviceWorker)&&void 0!==t&&t.controller&&navigator.serviceWorker.controller.postMessage({type:"closeMessageNotifications",payload:e})}function A(){var e;null!==(e=navigator.serviceWorker)&&void 0!==e&&e.controller&&navigator.serviceWorker.controller.postMessage({type:"clientReady"})}},6272:(e,t,n)=>{n.d(t,{U9:()=>u,g3:()=>a,un:()=>s,WZ:()=>i});var r=n(782);const o="X",d="XXX XXX XXX XXX";function u(e,t){return e.filter((e=>e.iso2===t))}function a(e,t=""){var n;let o=t.replace(/[^\d+]+/g,"");o.startsWith("+")&&(o=o.substr(1));const d=e.filter((e=>o.startsWith(e.countryCode))),u=(0,r.xH)(d.map((e=>(e.prefixes||[""]).map((t=>({code:`${e.countryCode}${t}`,country:e})))))).filter((({code:e})=>o.startsWith(e))).sort(((e,t)=>e.code.length-t.code.length));return null===(n=u[u.length-1])||void 0===n?void 0:n.country}function s(e,t){let n=e.replace(/[^\d]+/g,"");if(t)n=n.substr(t.countryCode.length);else if(e.startsWith("+"))return e;const r=function(e,t){if(!t||0===t.length)return d;if(1===t.length)return t[0];const n=t.find((e=>e.startsWith(o)))||d,r=t.filter((t=>{const n=t.replace(/[^\dX]+/g,"");if(n.startsWith(o))return!1;for(let t=0;tn.length-1||n[t]!==o&&n[t]!==e[t])return!1;return!0}));return 1===r.length?r[0]:n}(n,null==t?void 0:t.patterns),u=[];let a=0;for(let e=0;e{n.d(t,{q:()=>o,V:()=>d});var r=n(6137);const o=e=>e.chatId.toString()+("thread"!==e.type?`_${e.type}`:-1!==e.threadId?`_${e.threadId}`:""),d=e=>{if(!e)return;const[t,n]=e.replace(/^#/,"").split("_");if(!t)return;const o=["thread","pinned","scheduled"].includes(n);return{chatId:t,type:n&&o?n:"thread",threadId:n&&!o?Number(n):r._f}}},9118:(e,t,n)=>{function r(e,t,n=!0,r=!0){let o;return(...d)=>{o?(clearTimeout(o),o=void 0):n&&e(...d),o=self.setTimeout((()=>{r&&e(...d),o=void 0}),t)}}function o(e,t,n=!0){let r,o,d;return(...u)=>{o=!0,d=u,r||(n&&(o=!1,e(...d)),r=self.setInterval((()=>{if(!o)return self.clearInterval(r),void(r=void 0);o=!1,e(...d)}),t))}}function d(e){return a(g,e)}function u(e){return a(y,e)}function a(e,t){let n,r=!1;return(...o)=>{n=o,r||(r=!0,e((()=>{r=!1,t(...n)})))}}function s(e){self.requestIdleCallback?self.requestIdleCallback(e):v(e)}n.d(t,{Ds:()=>r,P2:()=>o,mS:()=>d,wT:()=>u,Q8:()=>s,wO:()=>i,Pn:()=>c,T2:()=>g,D0:()=>y,R3:()=>v,zD:()=>b,Gq:()=>w});const i=e=>new Promise((t=>{setTimeout((()=>t()),e)}));function c(){return new Promise((e=>{g(e)}))}let l,f,h,m,p;function g(e,t=!1){l?t?f.push(e):l.push(e):(l=t?[]:[e],f=t?[e]:[],requestAnimationFrame((()=>{const e=l,t=f;l=void 0,f=void 0,t.forEach((e=>e())),e.forEach((e=>e()))})))}function y(e){g(e,!0)}function v(e,t=!1){h?t?m.push(e):h.push(e):(h=t?[]:[e],m=t?[e]:[],Promise.resolve().then((()=>{const e=h,t=m;h=void 0,m=void 0,t.forEach((e=>e())),e.forEach((e=>e()))})))}function b(e){v(e,!0)}function w(e,t=!1){return p||(p=[],self.addEventListener("beforeunload",(()=>{p.forEach((e=>e()))}))),t?p.push(e):p.unshift(e),()=>{p=p.filter((t=>t!==e))}}},5765:(e,t,n)=>{let r;n.d(t,{Z:()=>o});try{r=new RegExp("[^\\p{L}\\p{M}]+","ui")}catch(e){r=new RegExp("[^\\wа-яё]+","i")}function o(e,t){if(!e||!t)return!1;const n=e.toLowerCase().split(r);return t.toLowerCase().split(r).every((e=>n.some((t=>t.startsWith(e)))))}},2267:(e,t,n)=>{n.d(t,{b:()=>r});const r=e=>Math.floor(Date.now()/1e3)+e},4688:(e,t,n)=>{n.d(t,{f3:()=>m,jv:()=>l,ti:()=>i,Qw:()=>h,K8:()=>f,wX:()=>c});function r(e){return new Promise(((t,n)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>n(e.error)}))}let o;function d(){return o||(o=function(e,t){const n=function(){if(navigator.userAgentData||!/Safari\//.test(navigator.userAgent)||/Chrom(e|ium)\//.test(navigator.userAgent)||!indexedDB.databases)return Promise.resolve();let e;return new Promise((t=>{const n=()=>indexedDB.databases().finally(t);e=setInterval(n,100),n()})).finally((()=>clearInterval(e)))}().then((()=>{const e=indexedDB.open("keyval-store");return e.onupgradeneeded=()=>e.result.createObjectStore(t),r(e)}));return(e,r)=>n.then((n=>r(n.transaction(t,e).objectStore(t))))}(0,"keyval")),o}var u=n(3716),a=n(9524);const s=[1,2,3,4,5];function i(e=!1){if(e&&localStorage.getItem(u.Vx))return!0;const t=localStorage.getItem(u.b_);if(!t)return!1;try{const e=JSON.parse(t);return Boolean(e&&e.id&&e.dcID)}catch(e){return!1}}function c(e,t){const{mainDcId:n,keys:r,hashes:o}=e;localStorage.setItem(u.b_,JSON.stringify({dcID:n,id:t})),localStorage.setItem("dc",String(n)),Object.keys(r).map(Number).forEach((e=>{localStorage.setItem(`dc${e}_auth_key`,JSON.stringify(r[e]))})),o&&Object.keys(o).map(Number).forEach((e=>{localStorage.setItem(`dc${e}_hash`,JSON.stringify(o[e]))}))}function l(){[u.b_,"dc",...s.map((e=>`dc${e}_auth_key`)),...s.map((e=>`dc${e}_hash`))].forEach((e=>{localStorage.removeItem(e)}))}function f(){if(!i())return;const e=JSON.parse(localStorage.getItem(u.b_)),t=Number(e.dcID),n={},r={};return s.forEach((e=>{try{const t=localStorage.getItem(`dc${e}_auth_key`);t&&(n[e]=JSON.parse(t));const o=localStorage.getItem(`dc${e}_hash`);o&&(r[e]=JSON.parse(o))}catch(e){u.eM&&console.warn("Failed to load stored session",e)}})),Object.keys(n).length?{mainDcId:t,keys:n,hashes:r}:void 0}async function h(){const e=localStorage.getItem(u.Vx);if(!e)return;const t=await function(e,t=d()){return t("readonly",(t=>r(t.get(e))))}(`GramJs:${e}`);try{c(JSON.parse(t))}catch(e){u.eM&&console.warn("Failed to load legacy session",e)}}async function m(){localStorage.removeItem(u.Vx);const e=await function(e=d()){const t=[];return function(e,t){return e("readonly",(e=>(e.openCursor().onsuccess=function(){this.result&&(t(this.result),this.result.continue())},r(e.transaction))))}(e,(e=>t.push(e.key))).then((()=>t))}();await Promise.all([a.clear("GramJs"),...e.filter((e=>"string"==typeof e&&e.startsWith("GramJs:GramJs-session-"))).map((e=>function(e,t=d()){return t("readwrite",(t=>(t.delete(e),r(t.transaction))))}(e)))])}},6917:(e,t,n)=>{n.d(t,{Z:()=>c});var r=n(9933);const o=JSON.parse('{"--color-primary":["#3390EC","#8774E1"],"--color-primary-opacity":["#50A2E980","#8378DB80"],"--color-primary-shade":["#4a95d6","#7b71c6"],"--color-background":["#FFFFFF","#212121"],"--color-background-secondary":["#f4f4f5","#0F0F0F"],"--color-background-secondary-accent":["#E4E4E5","#100f10"],"--color-background-own":["#EEFFDE","#8774E1"],"--color-background-own-apple":["#DCF8C5","#8774E1"],"--color-background-selected":["#F4F4F5","#2C2C2C"],"--color-background-own-selected":["#d0ffac","#6549d4"],"--color-chat-hover":["#F4F4F5","#2C2C2C"],"--color-chat-active":["#3390EC","#8774E1"],"--color-item-active":["#ededed","#292929"],"--color-text":["#000000","#FFFFFF"],"--color-text-secondary":["#707579","#AAAAAA"],"--color-text-secondary-apple":["#8E8E92","#AAAAAA"],"--color-borders":["#DADCE0","#303030"],"--color-borders-input":["#DADCE0","#5B5B5A"],"--color-dividers":["#C8C6CC","#404040"],"--color-links":["#3390EC","#8774E1"],"--color-gray":["#C4C9CC","#717579"],"--color-pinned":["#C4C9CC","#707579"],"--color-default-shadow":["#72727240","#1010109c"],"--color-light-shadow":["#7272722B","#00000040"],"--color-green":["#00C73E","#8774E1"],"--color-text-meta-colored":["#4DCD5E","#8378DB"],"--color-reply-hover":["#F4F4F4","#272727"],"--color-reply-active":["#E8E9E9","#2E2F2F"],"--color-reply-own-hover":["#D9F5CE","#7d6bca"],"--color-reply-own-hover-apple":["#cbefb7","#7d6bca"],"--color-reply-own-active":["#C5ECBE","#7264b6"],"--color-reply-own-active-apple":["#bae6a8","#7264b6"],"--color-accent-own":["#45AF54","#FFFFFF"],"--color-message-meta-own":["#4FAE4EFF","#FFFFFF88"],"--color-own-links":["#3390EC","#FFFFFF"],"--color-code":["#4a729a","#8774E1"],"--color-code-own":["#3c7940","#FFFFFF"],"--color-code-bg":["#70757914","#ffffff26"],"--color-code-own-bg":["#70757914","#ffffff26"],"--color-composer-button":["#707579CC","#AAAAAACC"]}');let d=!1;const u=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i,a=new Set(["--color-primary-shade","--color-text-secondary"]),s=(e,t,n)=>(1-n)*e+n*t,i=Object.keys(o).map((e=>({property:e,colors:[l(o[e][0]),l(o[e][1])]}))),c=(e,t)=>{const n="dark"===e,o=d&&t,u=n?0:1,a=n?1:0,s=Date.now(),i=document.querySelector('meta[name="theme-color"]');document.documentElement.classList.remove("theme-"+(n?"light":"dark")),d&&document.documentElement.classList.add("no-animations"),document.documentElement.classList.add(`theme-${e}`),i&&i.setAttribute("content",n?"#212121":"#fff"),setTimeout((()=>{document.documentElement.classList.remove("no-animations")}),500),d=!0,o?(0,r.c)((()=>{const e=Math.min((Date.now()-s)/200,1);return f(u,a,function(e){return 1-(1-e)**3.5}(e)),e<1})):f(u,a)};function l(e){const t=u.exec(e);return{r:parseInt(t[1],16),g:parseInt(t[2],16),b:parseInt(t[3],16),a:void 0!==t[4]?parseInt(t[4],16):void 0}}function f(e,t,n=1){i.forEach((({property:r,colors:o})=>{const d=Math.round(s(o[e].r,o[t].r,n)),u=Math.round(s(o[e].g,o[t].g,n)),i=Math.round(s(o[e].b,o[t].b,n)),c=void 0!==o[e].a?Math.round(s(o[e].a,o[t].a,n)):void 0;document.documentElement.style.setProperty(r,void 0!==c?`rgba(${d},${u},${i},${c/255})`:`rgb(${d},${u},${i})`),a.has(r)&&document.documentElement.style.setProperty(`${r}-rgb`,`${d},${u},${i}`)}))}},2155:(e,t,n)=>{n.d(t,{kh:()=>d,bi:()=>a,Xv:()=>s});var r=n(3681),o=n(4284);function d(e){return String(e).replace(/\d(?=(\d{3})+$)/g,"$& ")}function u(e){return".0"===String(e.toFixed(1)).substr(-2)?Math.round(e):e.toFixed(1).replace(".",",")}function a(e){return e<1e3?e:e<1e6?`${u(e/1e3)}K`:`${u(e/1e6)}M`}function s(e,t=2){return e.replace(/[.,!@#$%^&*()_+=\-`~[\]/\\{}:"|<>?]+/gi,"").trim().split(/\s+/).slice(0,t).map((e=>{if(!e.length)return"";const t=(e=(0,o.g6)(e)).match(r.Z);return t&&e.startsWith(t[0])?t[0]:e.match(/./u)[0].toUpperCase()})).join("")}},8035:(e,t,n)=>{function r(e,t=30){return!e||e.length<=t?e:`${e.substr(0,t)}...`}n.d(t,{Z:()=>r})},862:(e,t,n)=>{n.d(t,{Hu:()=>s,_y:()=>i,p6:()=>c});var r=n(7361),o=n(1394),d=n(9118);let u,a;const s="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";async function i(e,t){for(l();!a.wasmReady;)await(0,d.wO)(2e3);const{result:n,width:r,height:o}=await function(e,t){return new Promise((n=>{a.requests||(a.requests=new Map),a.requests.set(e,n),a.postMessage({id:e,blob:t})}))}(e,t);if(r&&o)return function({result:e,width:t,height:n}){return u||(u=document.createElement("canvas")),new Promise((r=>{const o=new ImageData(e,t,n);u.width=t,u.height=n,u.getContext("2d").putImageData(o,0,0),u.toBlob((e=>{r(null!=e?e:void 0)}),"image/png",1)}))}({result:n,width:r,height:o})}async function c(e,t){if((0,r.on)()||"data:image/webp"!==t.substr(0,15))return t;l();const n=await i(e,(0,o.A9)(t));if(!n)throw new Error(`Can't convert webp to png. Url: ${t}`);return(0,o.YJ)(n)}function l(){a||(a=new Worker(new URL(n.p+n.u(536),n.b)),a.wasmReady=!1,a.onmessage=f)}function f(e){const{id:t}=e.data;switch(e.data.type){case"initialized":a.wasmReady=!0;break;case"result":if(a.requests.has(t)){const n=a.requests.get(t);a.requests.delete(t),n(e.data)}}}},1622:(e,t,n)=>{n.d(t,{I:()=>l,p:()=>f});var r=n(3716),o=n(5116),d=n(4688);const u=["t.me","telegram.me"].map((e=>`//${e}/_websync_?`)),a=`${r.Ji} Z`,s="tgme_sync",i=()=>Math.floor(Number(new Date)/1e3);let c;const l=e=>{const t=i(),{canRedirect:n,ts:r}=JSON.parse(localStorage.getItem(s)||"{}");return n!==e||r+86400<=t?Promise.all(u.map((t=>new Promise(((n,r)=>{const o=document.createElement("script"),d=()=>!!document.body.removeChild(o);o.src=t+new URLSearchParams({authed:Number(e).toString(),version:a}),document.body.appendChild(o),o.onload=()=>{(e=>{const t=i();localStorage.setItem(s,JSON.stringify({canRedirect:e,ts:t}))})(e),d(),c&&(clearTimeout(c),c=void 0),f(),n()},o.onerror=()=>{d(),r()}}))))):Promise.resolve()};function f(){if(r.eM)return;if(void 0!==c)return;const e=i(),{ts:t}=JSON.parse(localStorage.getItem(s)||"{}"),n=86400-(e-t);c=setTimeout((()=>{const{authState:e}=(0,o.Rd)(),t="authorizationStateReady"===e||(0,d.ti)(!0);l(t)}),Math.max(0,1e3*n))}},3858:(e,t,n)=>{n.d(t,{z:()=>l,Z:()=>h});var r=n(9118),o=n(3716),d=n(7361);const u=d.wB&&f(),a=window.innerHeight;let s=l(),i=!1;const c=(0,r.P2)((()=>{s=l(),!i&&((s.width<=o.l3||s.width<=o.u_&&s.height<=o.rO)!==d.wB||d.wB&&u!==f())&&window.location.reload()}),250,!0);function l(){let e;e=d.cj?window.visualViewport.height+window.visualViewport.pageTop:window.innerHeight;const t=.01*e;return document.documentElement.style.setProperty("--vh",`${t}px`),{width:window.innerWidth,height:window.innerHeight}}function f(){return d.cj?window.matchMedia("(orientation: landscape)").matches:window.matchMedia("screen and (min-device-aspect-ratio: 1/1) and (orientation: landscape)").matches}window.addEventListener("orientationchange",c),d.cj?window.visualViewport.addEventListener("resize",c):window.addEventListener("resize",c);const h={get:()=>s,getIsKeyboardVisible:()=>a>s.height,disableRefresh:function(){i=!0},enableRefresh:function(){i=!1}}},5359:(e,t,n)=>{e.exports=n.p+"app-inactive.bc7953c2dfebcabce2c4..png"},2162:(e,t,n)=>{e.exports=n.p+"monkey.a3d5fcdc50b18dc55695..svg"},4128:(e,t,n)=>{e.exports=n.p+"telegram-logo.1b2bb5b107f046ea9325..svg"}},a={};function s(e){var t=a[e];if(void 0!==t)return t.exports;var n=a[e]={exports:{}};return u[e].call(n.exports,n,n.exports,s),n.exports}s.m=u,s.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return s.d(t,{a:t}),t},t=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,s.t=function(n,r){if(1&r&&(n=this(n)),8&r)return n;if("object"==typeof n&&n){if(4&r&&n.__esModule)return n;if(16&r&&"function"==typeof n.then)return n}var o=Object.create(null);s.r(o);var d={};e=e||[null,t({}),t([]),t(t)];for(var u=2&r&&n;"object"==typeof u&&!~e.indexOf(u);u=t(u))Object.getOwnPropertyNames(u).forEach((e=>d[e]=()=>n[e]));return d.default=()=>n,s.d(o,d),o},s.d=(e,t)=>{for(var n in t)s.o(t,n)&&!s.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},s.f={},s.e=e=>Promise.all(Object.keys(s.f).reduce(((t,n)=>(s.f[n](e,t),t)),[])),s.u=e=>e+"."+{99:"f03a947e6e336feffec8",133:"aae91a1c7ca8928cb720",161:"286d0207d962142ad548",306:"abed97b181f73c2c1aa8",325:"d8a67d9617f2e13de2dc",354:"f579d864cf3b32d15240",472:"21e5264f606f2b525030",501:"72ce4b6e27f459e194cd",514:"89d97ccb086a4c539d1a",524:"57eea32f15dc5514a3eb",536:"55dc7dd4ab42a2c9f037",701:"0c52bb0aaf1cd79c0b70",745:"9316c5c2b711c39a20a5",915:"13af1c4ab9a00d84ac23",941:"a1bb68030d234cd6f825",993:"f0aad9f6787f211b4e51"}[e]+".js",s.miniCssF=e=>e+"."+{133:"aae91a1c7ca8928cb720",306:"abed97b181f73c2c1aa8",325:"d8a67d9617f2e13de2dc",472:"21e5264f606f2b525030",701:"0c52bb0aaf1cd79c0b70"}[e]+".css",s.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),s.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n={},r="telegram-t:",s.l=(e,t,o,d)=>{if(n[e])n[e].push(t);else{var u,a;if(void 0!==o)for(var i=document.getElementsByTagName("script"),c=0;c{u.onerror=u.onload=null,clearTimeout(h);var o=n[e];if(delete n[e],u.parentNode&&u.parentNode.removeChild(u),o&&o.forEach((e=>e(r))),t)return t(r)},h=setTimeout(f.bind(null,void 0,{type:"timeout",target:u}),12e4);u.onerror=f.bind(null,u.onerror),u.onload=f.bind(null,u.onload),a&&document.head.appendChild(u)}},s.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{var e;s.g.importScripts&&(e=s.g.location+"");var t=s.g.document;if(!e&&t&&(t.currentScript&&(e=t.currentScript.src),!e)){var n=t.getElementsByTagName("script");n.length&&(e=n[n.length-1].src)}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),s.p=e})(),o=e=>new Promise(((t,n)=>{var r=s.miniCssF(e),o=s.p+r;if(((e,t)=>{for(var n=document.getElementsByTagName("link"),r=0;r{var o=document.createElement("link");o.rel="stylesheet",o.type="text/css",o.onerror=o.onload=d=>{if(o.onerror=o.onload=null,"load"===d.type)n();else{var u=d&&("load"===d.type?"missing":d.type),a=d&&d.target&&d.target.href||t,s=new Error("Loading CSS chunk "+e+" failed.\n("+a+")");s.code="CSS_CHUNK_LOAD_FAILED",s.type=u,s.request=a,o.parentNode.removeChild(o),r(s)}},o.href=t,document.head.appendChild(o)})(e,o,t,n)})),d={179:0},s.f.miniCss=(e,t)=>{d[e]?t.push(d[e]):0!==d[e]&&{133:1,306:1,325:1,472:1,701:1}[e]&&t.push(d[e]=o(e).then((()=>{d[e]=0}),(t=>{throw delete d[e],t})))},(()=>{s.b=document.baseURI||self.location.href;var e={179:0};s.f.j=(t,n)=>{var r=s.o(e,t)?e[t]:void 0;if(0!==r)if(r)n.push(r[2]);else{var o=new Promise(((n,o)=>r=e[t]=[n,o]));n.push(r[2]=o);var d=s.p+s.u(t),u=new Error;s.l(d,(n=>{if(s.o(e,t)&&(0!==(r=e[t])&&(e[t]=void 0),r)){var o=n&&("load"===n.type?"missing":n.type),d=n&&n.target&&n.target.src;u.message="Loading chunk "+t+" failed.\n("+o+": "+d+")",u.name="ChunkLoadError",u.type=o,u.request=d,r[1](u)}}),"chunk-"+t,t)}};var t=(t,n)=>{var r,o,[d,u,a]=n,i=0;if(d.some((t=>0!==e[t]))){for(r in u)s.o(u,r)&&(s.m[r]=u[r]);a&&a(s)}for(t&&t(n);i{s(3592);var e=s(3716),t=s(5116),n=s(7361),r=s(8406);function o(n){const o=n.data;if(e.eM&&console.log("[SW] Message from worker",o),!o.type)return;const d=(0,t.uC)();switch(o.type){case"focusMessage":d.focusMessage&&d.focusMessage(o.payload);break;case"playNotificationSound":(0,r.Nz)(o.payload.id)}}function d(){navigator.serviceWorker.removeEventListener("message",o),navigator.serviceWorker.addEventListener("message",o),(0,r.KC)()}n.Mc&&(window.addEventListener("load",(async()=>{try{await navigator.serviceWorker.register(new URL(s.p+s.u(524),s.b)),e.eM&&console.log("[SW] ServiceWorker registered"),await navigator.serviceWorker.ready,navigator.serviceWorker.controller?(e.eM&&console.log("[SW] ServiceWorker ready"),d()):(e.eM&&console.error("[SW] ServiceWorker not available"),n.cj||n.wZ||(0,t.uC)().showDialog({data:{message:"SERVICE_WORKER_DISABLED",hasErrorKey:!0}}))}catch(t){e.eM&&console.error("[SW] ServiceWorker registration failed: ",t)}})),window.addEventListener("focus",(async()=>{await navigator.serviceWorker.ready,d()})));var u=s(2916);const a={isLeftColumnShown:!0,isChatInfoShown:!1,newChatMembersProgress:s(1713).WB.Closed,uiReadyState:0,serverTimeOffset:0,authRememberMe:!0,countryList:{phoneCodes:[],general:[]},blocked:{ids:[],totalCount:0},users:{byId:{}},chats:{listIds:{},isFullyLoaded:{},orderedPinnedIds:{},totalCount:{},byId:{}},messages:{byChatId:{},messageLists:[]},scheduledMessages:{byChatId:{}},chatFolders:{byId:{},activeChatFolder:0},fileUploads:{byMessageLocalId:{}},recentEmojis:["grinning","kissing_heart","christmas_tree","brain","trophy"],stickers:{setsById:{},added:{},recent:{stickers:[]},favorite:{stickers:[]},greeting:{stickers:[]},featured:{setIds:[]},search:{},forEmoji:{}},emojiKeywords:{},gifs:{saved:{},search:{}},inlineBots:{isLoading:!1,byUsername:{}},globalSearch:{},userSearch:{},localTextSearch:{byChatThreadKey:{}},localMediaSearch:{byChatId:{}},management:{byChatId:{}},topPeers:{},topInlineBots:{},mediaViewer:{},audioPlayer:{volume:e.Qx,playbackRate:e.mw,isMuted:!1},forwardMessages:{},pollResults:{},payment:{},notifications:[],dialogs:[],activeSessions:[],settings:{byKey:{theme:"light",shouldUseSystemTheme:!0,messageTextSize:n.cj?e.b6:n.jm?e.AR:e.xS,animationLevel:e.CX,messageSendKeyCombo:"enter",canAutoLoadPhotoFromContacts:!0,canAutoLoadPhotoInPrivateChats:!0,canAutoLoadPhotoInGroups:!0,canAutoLoadPhotoInChannels:!0,canAutoLoadVideoFromContacts:!0,canAutoLoadVideoInPrivateChats:!0,canAutoLoadVideoInGroups:!0,canAutoLoadVideoInChannels:!0,canAutoLoadFileFromContacts:!1,canAutoLoadFileInPrivateChats:!1,canAutoLoadFileInGroups:!1,canAutoLoadFileInChannels:!1,autoLoadFileMaxSizeMb:10,hasWebNotifications:!0,hasPushNotifications:!0,notificationSoundVolume:5,canAutoPlayGifs:!0,canAutoPlayVideos:!0,shouldSuggestStickers:!0,shouldLoopStickers:!0,language:"en",timeFormat:"24h",wasTimeFormatSetManually:!1},themes:{light:{isBlurred:!0,patternColor:e.g},dark:{isBlurred:!0,patternColor:e.Vv}},privacy:{},notifyExceptions:{}},twoFaSettings:{},shouldShowContextMenuHint:!0,activeDownloads:{byChatId:{}},serviceNotifications:[]};var i=s(6137),c=s(9118),l=s(8674),f=s(782),h=s(8085),m=s(4688),p=s(5780),g=s(6590),y=s(2858);const v=(0,c.P2)((()=>(0,c.Q8)(E)),5e3,!1);let b,w=!1,I=!1;function C(){w=!0,b=(0,c.Gq)(E,!0),window.addEventListener("blur",E),(0,t.ll)(v)}function S(){w=!1,(0,t.Iq)(v),window.removeEventListener("blur",E),b&&b()}function E(){if(!w||I)return;const n=(0,t.Rd)();if(n.isLoggingOut)return;const r={...a,...(0,f.ei)(n,["authState","authPhoneNumber","authRememberMe","authNearestCountry","currentUserId","contactList","topPeers","topInlineBots","recentEmojis","push","shouldShowContextMenuHint","leftColumnWidth","serviceNotifications"]),audioPlayer:{volume:n.audioPlayer.volume,playbackRate:n.audioPlayer.playbackRate,isMuted:n.audioPlayer.isMuted},isChatInfoShown:P(n),users:M(n),chats:A(n),messages:k(n),globalSearch:{recentlyFoundChatIds:n.globalSearch.recentlyFoundChatIds},settings:T(n),chatFolders:N(n)},o=JSON.stringify(r);localStorage.setItem(e.Uh,o)}function P(t){return window.innerWidth>e._m&&t.isChatInfoShown}function M(t){const{users:{byId:n,selectedId:r}}=t,o=[...(t.chats.listIds.active||[]).slice(0,e.gJ).filter(y.YC),...Object.keys(n)].slice(0,e.lO);return{byId:(0,f.ei)(n,o),selectedId:window.innerWidth>e._m?r:void 0}}function A(t){const n=[...(t.chats.listIds.active||[]).slice(0,e.gJ)],{chatId:r}=(0,h.Bt)(t)||{};return{...t.chats,byId:(0,f.ei)(t.chats.byId,r?[...n,r]:n),listIds:{active:n},isFullyLoaded:{},orderedPinnedIds:{active:t.chats.orderedPinnedIds.active}}}function k(t){const n={},{chatId:r}=(0,h.Bt)(t)||{};return[...(t.chats.listIds.active||[]).slice(0,e.gJ),...r?[r]:[]].forEach((e=>{const r=t.messages.byChatId[e];if(!r)return;const o=r.threadsById[i._f];o&&o.viewportIds&&(n[e]={byId:(0,f.ei)(r.byId,o.viewportIds),threadsById:{[i._f]:o}})})),{byChatId:n,messageLists:[]}}function T(e){const{byKey:t,themes:n}=e.settings;return{byKey:t,themes:n,privacy:{},notifyExceptions:{}}}function N(e){return{...e.chatFolders,activeChatFolder:0}}document.addEventListener(l._L,(()=>{I=!0})),document.addEventListener(l.OV,(()=>{I=!1})),e.sd||((0,t.Q6)("saveSession",(()=>{w||C()})),(0,t.Q6)("reset",(()=>{localStorage.removeItem(e.Uh),w&&S()}))),(0,t.Q6)("init",(()=>{const t=(0,f.Xh)(a);return function(t){if(!e.sd)return(0,m.ti)(!0)?(C(),function(t){e.eM&&console.time("global-state-cache-read");const r=localStorage.getItem(e.Uh),o=r?JSON.parse(r):void 0;e.eM&&console.timeEnd("global-state-cache-read"),o&&function(t,n){if("shouldAutoDownloadMediaFromContacts"in t.settings.byKey){const{shouldAutoDownloadMediaFromContacts:e,shouldAutoDownloadMediaInPrivateChats:n,shouldAutoDownloadMediaInGroups:r,shouldAutoDownloadMediaInChannels:o,shouldAutoPlayVideos:d,shouldAutoPlayGifs:u,...a}=t.settings.byKey;t.settings.byKey={...a,canAutoLoadPhotoFromContacts:e,canAutoLoadVideoFromContacts:e,canAutoLoadPhotoInPrivateChats:n,canAutoLoadVideoInPrivateChats:n,canAutoLoadPhotoInGroups:r,canAutoLoadVideoInGroups:r,canAutoLoadPhotoInChannels:o,canAutoLoadVideoInChannels:o,canAutoPlayVideos:d,canAutoPlayGifs:u}}t.settings.byKey={...n.settings.byKey,...t.settings.byKey},t.settings.themes={...n.settings.themes,...t.settings.themes},t.chatFolders={...n.chatFolders,...t.chatFolders},t.stickers.greeting||(t.stickers.greeting=n.stickers.greeting),t.activeDownloads||(t.activeDownloads={byChatId:{}}),t.serviceNotifications||(t.serviceNotifications=[]),void 0===t.audioPlayer.volume&&(t.audioPlayer.volume=e.Qx),void 0===t.audioPlayer.playbackRate&&(t.audioPlayer.playbackRate=e.mw)}(o,t);const d={...t,...o},u=n.wB?void 0:(0,p.V)(g.Oy);return{...d,messages:{...d.messages,messageLists:u?[u]:[]}}}(t)):void S()}(t)||t}));var L=s(4050),R=s(3858);const D="tt-active-tab",O=String(Date.now()+Math.random());let x;localStorage.setItem(D,O);const _=window.setInterval((()=>{x&&localStorage.getItem(D)!==O&&(x(),clearInterval(_))}),2e3);var Z=s(706),F=(s(7895),s(3781),s(1363),s(9667),s(4907),s(8332)),B=s(1212),$=s(1394);const U=["400 1em Roboto","500 1em Roboto"];function j(){if("fonts"in document)return Promise.all(U.map((e=>document.fonts.load(e))))}var W=s(647),V=s(9203),G=s(6752),H=s(4128),z=s(2162);function Q(){const{listIds:e,byId:n}=(0,t.Rd)().chats;if(e.active)return Promise.all(e.active.slice(0,10).map((e=>{const t=n[e];if(!t)return;const r=(0,F.RT)(t);return r?W.he(r,i.IU.BlobUrl):void 0})))}const K={main:()=>Promise.all([(0,V.$y)(V.gl.Main,"Main").then(j),Q()]),authPhoneNumber:()=>Promise.all([j(),(0,$.pt)(H)]),authCode:()=>(0,$.pt)(z),authPassword:()=>(0,$.pt)(z),authQrCode:j},J=(0,t.c$)((e=>{const t=(0,h.Pu)(e),{background:n,backgroundColor:r}=e.settings.themes[t]||{};return{shouldSkipHistoryAnimations:e.shouldSkipHistoryAnimations,uiReadyState:e.uiReadyState,hasCustomBackground:Boolean(n),hasCustomBackgroundColor:Boolean(r),isRightColumnShown:(0,h.Jf)(e),leftColumnWidth:e.leftColumnWidth}}),((e,t)=>(0,f.ei)(t,["setIsUiReady"])))((({page:e,children:t,hasCustomBackground:n,hasCustomBackgroundColor:r,isRightColumnShown:o,shouldSkipHistoryAnimations:d,leftColumnWidth:u,setIsUiReady:a})=>{const[s,i]=(0,Z.Z)(),{shouldRender:l,transitionClassNames:f}=(0,B.Z)(!s,void 0,!0);return(0,L.d4)((()=>{let t;return Promise.race([(0,c.wO)(700),(async()=>{try{await K[e]()}catch(e){}})()]).then((()=>{i(),a({uiReadyState:1}),t=window.setTimeout((()=>{a({uiReadyState:2})}),1e3)})),()=>{t&&(clearTimeout(t),t=void 0),a({uiReadyState:0})}}),[]),L.ZP.createElement("div",{id:"UiLoader"},t,l&&!d&&L.ZP.createElement("div",{className:(0,G.Z)("mask",f)},"main"===e?L.ZP.createElement(L.ZP.Fragment,null,L.ZP.createElement("div",{className:"left",style:u?`width: ${u}px`:void 0}),L.ZP.createElement("div",{className:(0,G.Z)("middle",n&&"custom-bg-image",r&&"custom-bg-color",o&&"with-right-column")}),o&&L.ZP.createElement("div",{className:"right"})):L.ZP.createElement("div",{className:"blank"})))}));var q=s(6272),Y=s(663),X=s(9107);const ee=(e,t)=>{const[n,r]=(0,L.eJ)();return e&&Y.Pn(e,t).then(r),n};function te(){let e=navigator.language;return e&&"pt-br"!==e&&(e=e.substr(0,2)),e}var ne=s(231),re=s(4605),oe=s(7687),de=s(4288),ue=s(5765),ae=s(2340),se=s(4284),ie=s(9290),ce=s(3106),le=s(8964),fe=s(9204);const he=200+e.fK,me=(0,L.X$)((0,t.c$)((e=>{const{countryList:{phoneCodes:t}}=e;return{phoneCodeList:t}}))((({id:e,value:t,isLoading:n,onChange:r,phoneCodeList:o})=>{const d=(0,X.Z)(),u=(0,L.sO)(null),[a,s]=(0,L.eJ)(),[i,c]=(0,L.eJ)([]),l=(0,L.I4)((e=>{s(e),c(function(e,t=""){return t.length?e.filter((e=>(0,ue.Z)(e.defaultName,t)||e.name&&(0,ue.Z)(e.name,t))):e}(o,e))}),[o]);(0,ie.Z)((([e])=>{0===(null==e?void 0:e.length)&&o.length>0&&l(a)}),[o,l]);const f=(0,L.I4)((e=>{r(e),setTimeout((()=>l(void 0)),he)}),[r,l]),h=(0,L.I4)((e=>{l(e.currentTarget.value)}),[l]),m=(0,L.I4)((e=>{if(8!==e.keyCode)return;const n=e.currentTarget;t&&void 0===a&&(n.value=""),l(n.value)}),[a,l,t]);return L.ZP.createElement(ce.Z,{className:"CountryCodeInput",trigger:({onTrigger:r,isOpen:o})=>{const s=()=>{if(o)return;setTimeout((()=>{u.current.select()}),50),r();const e=document.getElementById("auth-phone-number-form");e.scrollTo({top:e.scrollHeight,behavior:"smooth"})},i=null!=a?a:(null==t?void 0:t.name)||(null==t?void 0:t.defaultName)||"";return L.ZP.createElement("div",{className:(0,G.Z)("input-group",t&&"touched")},L.ZP.createElement("input",{ref:u,className:(0,G.Z)("form-control",o&&"focus"),type:"text",id:e,value:i,autoComplete:"off",onClick:s,onFocus:s,onInput:e=>{h(e),s()},onKeyDown:m}),L.ZP.createElement("label",null,d("Login.SelectCountry.Title")),n?L.ZP.createElement(fe.Z,{color:"black"}):L.ZP.createElement("i",{onClick:s,className:(0,G.Z)("css-icon-down",o&&"open")}))}},i.map((e=>L.ZP.createElement(le.Z,{key:e.iso2,className:t&&e.iso2===t.iso2?"selected":"",onClick:()=>f(e)},L.ZP.createElement("span",{className:"country-flag"},(0,ae.Z)((0,se.Wg)(e.iso2),["hq_emoji"])),L.ZP.createElement("span",{className:"country-name"},e.name||e.defaultName),L.ZP.createElement("span",{className:"country-code"},e.countryCode)))),!i.length&&L.ZP.createElement(le.Z,{key:"no-results",className:"no-results",disabled:!0},L.ZP.createElement("span",null,d("lng_country_none"))))})));let pe=!1;const ge=(0,L.X$)((0,t.c$)((e=>{const{settings:{byKey:{language:t}},countryList:{phoneCodes:n}}=e;return{...(0,f.ei)(e,["connectionState","authState","authPhoneNumber","authIsLoading","authIsLoadingQrCode","authError","authRememberMe","authNearestCountry"]),language:t,phoneCodeList:n}}),((e,t)=>(0,f.ei)(t,["setAuthPhoneNumber","setAuthRememberMe","clearAuthError","loadNearestCountry","loadCountryList","goToAuthQrCode","setSettingOption"])))((({connectionState:e,authState:t,authPhoneNumber:r,authIsLoading:o,authIsLoadingQrCode:d,authError:u,authRememberMe:a,authNearestCountry:s,phoneCodeList:i,language:c,setAuthPhoneNumber:l,setAuthRememberMe:f,loadNearestCountry:h,loadCountryList:m,clearAuthError:p,goToAuthQrCode:g,setSettingOption:y})=>{const v=(0,X.Z)(),b=(0,L.sO)(null),w=te(),I=ee(w,"ContinueOnThisLanguage"),[C,S]=(0,L.eJ)(),[E,P]=(0,L.eJ)(),[M,A]=(0,L.eJ)(!1),[k,T]=(0,L.eJ)(),[N,R,D]=(0,Z.Z)(),O=C?`+${C.countryCode} ${E||""}`:E,x=O&&O.replace(/[^\d]+/g,"").length>=7;(0,L.d4)((()=>{n.$b||b.current.focus()}),[C]),(0,L.d4)((()=>{"connectionStateReady"!==e||s||h()}),[e,s,h]),(0,L.d4)((()=>{"connectionStateReady"===e&&m({langCode:c})}),[e,c,m]),(0,L.d4)((()=>{s&&i&&!C&&!M&&S((0,q.U9)(i,s)[0])}),[C,s,M,i]);const _=(0,L.I4)((e=>{e.length||P("");const t=i&&(0,q.g3)(i,e),n=!C||t&&t.iso2!==C.iso2||!t&&e.length?t:C;(!C||!n||n&&n.iso2!==C.iso2)&&S(n),P((0,q.un)(e,n))}),[i,C]),F=(0,L.I4)((()=>{R(),(0,Y.m0)(w,(()=>{D(),y({language:w})}))}),[R,y,w,D]);(0,L.d4)((()=>{void 0===E&&r&&_(r)}),[r,E,_]),(0,L.bt)((()=>{b.current&&k&&b.current.setSelectionRange(...k)}),[k]);const B=(0,L.sO)(!1),U=(0,L.I4)((()=>{B.current=!0,requestAnimationFrame((()=>{B.current=!1}))}),[]),W=(0,L.I4)((e=>{S(e),P("")}),[]),V=(0,L.I4)((e=>{u&&p(),pe||(pe=!0,j(),(0,$.pt)(z));const{value:t,selectionStart:r,selectionEnd:o}=e.target;T(r&&o&&o1&&!B.current;_(d?`${C.countryCode} ${t}`:t)}),[u,p,C,O,_]),G=(0,L.I4)((e=>{f(e.target.checked)}),[f]),H="authorizationStateWaitPhoneNumber"===t;return L.ZP.createElement("div",{id:"auth-phone-number-form",className:"custom-scroll"},L.ZP.createElement("div",{className:"auth-form"},L.ZP.createElement("div",{id:"logo"}),L.ZP.createElement("h2",null,"Telegram"),L.ZP.createElement("p",{className:"note"},v("StartText")),L.ZP.createElement("form",{action:"",onSubmit:function(e){e.preventDefault(),o||x&&l({phoneNumber:O})}},L.ZP.createElement(me,{id:"sign-in-phone-code",value:C,isLoading:!s&&!C,onChange:W}),L.ZP.createElement(oe.Z,{ref:b,id:"sign-in-phone-number",label:v("Login.PhonePlaceholder"),value:O,error:u&&v(u),inputMode:"tel",onChange:V,onPaste:n.s$?U:void 0}),L.ZP.createElement(re.Z,{id:"sign-in-keep-session",label:"Keep me signed in",checked:Boolean(a),onChange:G}),x&&(H?L.ZP.createElement(ne.Z,{type:"submit",ripple:!0,isLoading:o},v("Login.Next")):L.ZP.createElement(de.Z,null)),H&&L.ZP.createElement(ne.Z,{isText:!0,ripple:!0,isLoading:d,onClick:g},v("Login.QR.Login")),w&&w!==c&&I&&L.ZP.createElement(ne.Z,{isText:!0,isLoading:N,onClick:F},I))))})));var ye=s(8778);const ve=(0,L.X$)((()=>{const e=(0,ye.Z)(V.gl.Auth,"AuthCode");return e?L.ZP.createElement(e,null):L.ZP.createElement(de.Z,null)})),be=(0,L.X$)((()=>{const e=(0,ye.Z)(V.gl.Auth,"AuthPassword");return e?L.ZP.createElement(e,null):L.ZP.createElement(de.Z,null)})),we=(0,L.X$)((()=>{const e=(0,ye.Z)(V.gl.Auth,"AuthRegister");return e?L.ZP.createElement(e,null):L.ZP.createElement(de.Z,null)}));let Ie=null;class Ce{}Ce.render=function(e,t){Ie(e,t)},self.QrCreator=Ce,function(e){function t(t,n,r,o){var d={},u=e(r,n);u.u(t),u.J(),o=o||0;var a=u.h(),s=u.h()+2*o;return d.text=t,d.level=n,d.version=r,d.O=s,d.a=function(e,t){return t-=o,!(0>(e-=o)||e>=a||0>t||t>=a)&&u.a(e,t)},d}function n(e,t,n,r,o,d,u,a,s,i){function c(t,n,r,o,u,a,s){t?(e.lineTo(n+a,r+s),e.arcTo(n,r,o,u,d)):e.lineTo(n,r)}u?e.moveTo(t+d,n):e.moveTo(t,n),c(a,r,n,r,o,-d,0),c(s,r,o,t,o,0,-d),c(i,t,o,t,n,d,0),c(u,t,n,r,n,0,d)}function r(e,t,n,r,o,d,u,a,s,i){function c(t,n,r,o){e.moveTo(t+r,n),e.lineTo(t,n),e.lineTo(t,n+o),e.arcTo(t,n,t+r,n,d)}u&&c(t,n,d,d),a&&c(r,n,-d,d),s&&c(r,o,-d,-d),i&&c(t,o,d,-d)}function o(e,o){e:{var d=o.text,u=o.v,a=o.N,s=o.K,i=o.P;for(a=Math.max(1,a||1),s=Math.min(40,s||40);a<=s;a+=1)try{var c=t(d,u,a,i);break e}catch(e){}c=void 0}if(!c)return null;for(d=e.getContext("2d"),o.background&&(d.fillStyle=o.background,d.fillRect(o.left,o.top,o.size,o.size)),u=c.O,s=o.size/u,d.beginPath(),i=0;iMath.round(e*t.size))),"linear-gradient"===r)var d=e.createLinearGradient.apply(e,n);else{if("radial-gradient"!==r)throw Error("Unsupported fill");d=e.createRadialGradient.apply(e,n)}o.forEach((([e,t])=>{d.addColorStop(e,t)})),e.fillStyle=d}}(d,o),d.fill(),e}var d={minVersion:1,maxVersion:40,ecLevel:"L",left:0,top:0,size:200,fill:"#000",background:null,text:"no text",radius:.5,quiet:0};Ie=function(e,t){var n={};Object.assign(n,d,e),n.N=n.minVersion,n.K=n.maxVersion,n.v=n.ecLevel,n.left=n.left,n.top=n.top,n.size=n.size,n.fill=n.fill,n.background=n.background,n.text=n.text,n.R=n.radius,n.P=n.quiet,t instanceof HTMLCanvasElement?(t.width===n.size&&t.height===n.size||(t.width=n.size,t.height=n.size),t.getContext("2d").clearRect(0,0,t.width,t.height),o(t,n)):((e=document.createElement("canvas")).width=n.size,e.height=n.size,n=o(e,n),t.appendChild(n))}}(function(){function e(o,u){function a(e,t){for(var n=-1;7>=n;n+=1)if(!(-1>=e+n||l<=e+n))for(var r=-1;7>=r;r+=1)-1>=t+r||l<=t+r||(c[e+n][t+r]=0<=n&&6>=n&&(0==r||6==r)||0<=r&&6>=r&&(0==n||6==n)||2<=n&&4>=n&&2<=r&&4>=r)}function s(e,n){for(var u=l=4*o+17,s=Array(u),m=0;m=y;y+=1)for(var v=-2;2>=v;v+=1)c[p+y][g+v]=-2==y||2==y||-2==v||2==v||0==y&&0==v}for(u=8;us;s+=1)m=!e&&1==(u>>s&1),c[6>s?s:8>s?s+1:l-15+s][8]=m,c[8][8>s?l-s-1:9>s?15-s:14-s]=m;if(c[l-8][8]=!e,7<=o){for(u=r.A(o),s=0;18>s;s+=1)m=!e&&1==(u>>s&1),c[Math.floor(s/3)][s%3+l-8-3]=m;for(s=0;18>s;s+=1)m=!e&&1==(u>>s&1),c[s%3+l-8-3][Math.floor(s/3)]=m}if(null==f){for(e=d.I(o,i),u=function(){var e=[],t=0,n={B:function(){return e},c:function(t){return 1==(e[Math.floor(t/8)]>>>7-t%8&1)},put:function(e,t){for(var r=0;r>>t-r-1&1))},f:function(){return t},m:function(n){var r=Math.floor(t/8);e.length<=r&&e.push(0),n&&(e[r]|=128>>>t%8),t+=1}};return n}(),s=0;s8*m)throw Error("code length overflow. ("+u.f()+">"+8*m+")");for(u.f()+4<=8*m&&u.put(0,4);0!=u.f()%8;)u.m(!1);for(;!(u.f()>=8*m||(u.put(236,8),u.f()>=8*m));)u.put(17,8);var b=0;for(m=s=0,p=Array(e.length),g=Array(e.length),y=0;yy;y+=1)null==c[s][g-y]&&(v=!1,p>>m&1)),n(s,g-y)&&(v=!v),c[s][g-y]=v,-1==--m&&(p+=1,m=7));if(0>(s+=u)||l<=s){s-=u,u=-u;break}}}var i=n[u],c=null,l=0,f=null,h=[],m={u:function(t){t=function(t){var n=e.s(t);return{S:function(){return 4},b:function(){return n.length},write:function(e){for(var t=0;te||l<=e||0>t||l<=t)throw Error(e+","+t);return c[e][t]},h:function(){return l},J:function(){for(var e=0,t=0,n=0;8>n;n+=1){s(!0,n);var o=r.D(m);(0==n||e>o)&&(e=o,t=n)}s(!1,t)}};return m}function t(e,n){if(void 0===e.length)throw Error(e.length+"/"+n);var r=function(){for(var t=0;td.b()-e.b())return d;for(var n=o.g(d.c(0))-o.g(e.c(0)),r=Array(d.b()),u=0;ur?t.push(r):2048>r?t.push(192|r>>6,128|63&r):55296>r||57344<=r?t.push(224|r>>12,128|r>>6&63,128|63&r):(n++,r=65536+((1023&r)<<10|1023&e.charCodeAt(n)),t.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r))}return t};var n={L:1,M:0,Q:3,H:2},r=function(){function e(e){for(var t=0;0!=e;)t+=1,e>>>=1;return t}var n=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]];return{w:function(t){for(var n=t<<10;0<=e(n)-e(1335);)n^=1335<t||40t?8:16},D:function(e){for(var t=e.h(),n=0,r=0;r=a;a+=1)if(!(0>r+a||t<=r+a))for(var s=-1;1>=s;s+=1)0>o+s||t<=o+s||(0!=a||0!=s)&&u==e.a(r+a,o+s)&&(d+=1);5n;n+=1)e[n]=1<n;n+=1)e[n]=e[n-4]^e[n-5]^e[n-6]^e[n-8];for(n=0;255>n;n+=1)t[e[n]]=n;return{g:function(e){if(1>e)throw Error("glog("+e+")");return t[e]},i:function(t){for(;0>t;)t+=255;for(;256<=t;)t-=255;return e[t]}}}(),d=function(){function e(e,r){switch(r){case n.L:return t[4*(e-1)];case n.M:return t[4*(e-1)+1];case n.Q:return t[4*(e-1)+2];case n.H:return t[4*(e-1)+3]}}var t=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12,7,37,13],[5,122,98,1,123,99],[7,73,45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]];return{I:function(t,n){var r=e(t,n);if(void 0===r)throw Error("bad rs block @ typeNumber:"+t+"/errorCorrectLevel:"+n);t=r.length/3,n=[];for(var o=0;o{const{connectionState:t,authState:n,authQrCode:r,settings:{byKey:{language:o}}}=e;return{connectionState:t,authState:n,authQrCode:r,language:o}}),((e,t)=>(0,f.ei)(t,["returnToAuthPhoneNumber","setSettingOption"])))((({connectionState:e,authState:t,authQrCode:n,language:r,returnToAuthPhoneNumber:o,setSettingOption:d})=>{const u=te(),a=(0,X.Z)(),s=(0,L.sO)(null),i=ee(u,"ContinueOnThisLanguage"),[c,l,f]=(0,Z.Z)();(0,L.d4)((()=>{if(!n||"connectionStateReady"!==e)return;const t=s.current;t.innerHTML="",t.classList.remove("pre-animate"),Se.render({text:`tg://login?token=${n.token}`,radius:.5,ecLevel:"M",fill:"#4E96D4",size:280},t)}),[e,n]);const h=(0,L.I4)((()=>{l(),(0,Y.m0)(u,(()=>{f(),d({language:u})}))}),[l,d,u,f]),m="authorizationStateWaitQrCode"===t;return L.ZP.createElement("div",{id:"auth-qr-form",className:"custom-scroll"},L.ZP.createElement("div",{className:"auth-form qr"},n?L.ZP.createElement("div",{key:"qr-container",className:"qr-container pre-animate",ref:s}):L.ZP.createElement("div",{key:"qr-loading",className:"qr-loading"},L.ZP.createElement(de.Z,null)),L.ZP.createElement("h3",null,a("Login.QR.Title")),L.ZP.createElement("ol",null,L.ZP.createElement("li",null,L.ZP.createElement("span",null,a("Login.QR.Help1"))),L.ZP.createElement("li",null,L.ZP.createElement("span",null,(0,ae.Z)(a("Login.QR.Help2"),["simple_markdown"]))),L.ZP.createElement("li",null,L.ZP.createElement("span",null,a("Login.QR.Help3")))),m&&L.ZP.createElement(ne.Z,{isText:!0,onClick:o},a("Login.QR.Cancel")),u&&u!==r&&i&&L.ZP.createElement(ne.Z,{isText:!0,isLoading:c,onClick:h},i)))}))),Pe=(0,L.X$)((0,t.c$)((e=>(0,f.ei)(e,["authState"])),((e,t)=>(0,f.ei)(t,["reset","initApi","returnToAuthPhoneNumber","goToAuthQrCode"])))((({authState:e,reset:t,initApi:r,returnToAuthPhoneNumber:o,goToAuthQrCode:d})=>{(0,L.d4)((()=>{t(),r()}),[t,r]);const u="iOS"===n.Lt||"Android"===n.Lt;switch((0,g.ZP)(!u&&"authorizationStateWaitPhoneNumber"===e||u&&"authorizationStateWaitQrCode"===e,(()=>{u?o():d()})),(0,L.d4)((()=>(R.Z.disableRefresh(),()=>{R.Z.enableRefresh()})),[]),e){case"authorizationStateWaitCode":return L.ZP.createElement(J,{page:"authCode",key:"authCode"},L.ZP.createElement(ve,null));case"authorizationStateWaitPassword":return L.ZP.createElement(J,{page:"authPassword",key:"authPassword"},L.ZP.createElement(be,null));case"authorizationStateWaitRegistration":return L.ZP.createElement(we,null);case"authorizationStateWaitPhoneNumber":return L.ZP.createElement(J,{page:"authPhoneNumber",key:"authPhoneNumber"},L.ZP.createElement(ge,null));case"authorizationStateWaitQrCode":return L.ZP.createElement(J,{page:"authQrCode",key:"authQrCode"},L.ZP.createElement(Ee,null));default:return u?L.ZP.createElement(J,{page:"authPhoneNumber",key:"authPhoneNumber"},L.ZP.createElement(ge,null)):L.ZP.createElement(J,{page:"authQrCode",key:"authQrCode"},L.ZP.createElement(Ee,null))}}))),Me=(0,L.X$)((()=>{const e=(0,ye.Z)(V.gl.Main,"Main");return e?L.ZP.createElement(e,null):void 0}));var Ae=s(5359);const ke=()=>L.ZP.createElement("div",{id:"AppInactive"},L.ZP.createElement("div",{className:"content"},L.ZP.createElement("img",{src:Ae,alt:""}),L.ZP.createElement("h3",{className:"title"},"Such error, many tabs"),L.ZP.createElement("div",{className:"description"},"Telegram supports only one active tab with the app.",L.ZP.createElement("br",null),"Please reload this page to continue using this tab or close it."),L.ZP.createElement("div",{className:"actions"},L.ZP.createElement(ne.Z,{isText:!0,ripple:!0,onClick:()=>{window.location.reload()}},"Reload app"))));function Te(){return t.ZP.createElement(J,{page:"main",key:"main"},t.ZP.createElement(Me,null))}const Ne=(0,t.c$)((e=>(0,f.ei)(e,["authState"])),((e,t)=>(0,f.ei)(t,["disconnect"])))((({authState:n,disconnect:r})=>{const[o,d]=(0,Z.Z)(!1);if((0,L.d4)((()=>{(0,R.z)(),x=()=>{r(),document.title=`${e.Ti}${e.ou}`,d()}}),[r,d]),o)return t.ZP.createElement(ke,null);if(n)switch(n){case"authorizationStateWaitPhoneNumber":case"authorizationStateWaitCode":case"authorizationStateWaitPassword":case"authorizationStateWaitRegistration":case"authorizationStateWaitQrCode":return t.ZP.createElement(Pe,null);case"authorizationStateClosed":case"authorizationStateClosing":case"authorizationStateLoggingOut":case"authorizationStateReady":return Te()}return(0,m.ti)(!0)?Te():t.ZP.createElement(Pe,null)}));e.eM&&console.log(">>> INIT"),(0,t.uC)().init(),e.eM&&console.log(">>> START INITIAL RENDER"),u.Z.render(t.ZP.createElement(Ne,null),document.getElementById("root")),e.eM&&console.log(">>> FINISH INITIAL RENDER"),document.addEventListener("dblclick",(()=>{console.warn("GLOBAL STATE",(0,t.Rd)())}))})()})(); -//# sourceMappingURL=main.385008a5f5d046ca97cd.js.map \ No newline at end of file +(()=>{"use strict";var e,t,n,r,o,d,u={1226:(e,t,n)=>{n.d(t,{t9:()=>c,u3:()=>l,g8:()=>i});var r=n(3716),o=n(6926),d=n(9118);let u;const a=new Map,s=new Map;function i(e,t){return u||(r.eM&&console.log(">>> START LOAD WORKER"),u=new Worker(new URL(n.p+n.u(514),n.b)),function(e){u.addEventListener("message",(({data:t})=>{if("update"===t.type)e(t.update);else if("methodResponse"===t.type){const e=a.get(t.messageId);e&&(t.error?e.reject(t.error):e.resolve(t.response))}else if("methodCallback"===t.type){var n,r;null===(n=a.get(t.messageId))||void 0===n||null===(r=n.callback)||void 0===r||r.call(n,...t.callbackArgs)}else if("unhandledError"===t.type)throw t.error}))}(e),"iOS"===t.platform&&window.addEventListener("focus",(async()=>{try{await Promise.race([f({type:"ping"}),(0,d.wO)(150).then((()=>Promise.reject(new Error("HEALTH_CHECK_TIMEOUT"))))])}catch(e){console.error(e),Date.now()-h>=5e3&&window.location.reload()}}))),f({type:"initApi",args:[t]})}function c(e,...t){if(u)return f({type:"callMethod",name:e,args:t});r.eM&&console.warn("API is not initialized")}function l(e){e.isCanceled=!0;const{messageId:t}=s.get(e)||{};t&&u.postMessage({type:"cancelProgress",messageId:t})}function f(e){const t=(0,o.Z)(a),n={messageId:t,...e},r={messageId:t},d=new Promise(((e,t)=>{Object.assign(r,{resolve:e,reject:t})}));if("args"in n&&"function"==typeof n.args[1]){const e=n.args.pop();r.callback=e,s.set(e,r)}return a.set(t,r),d.catch((()=>{})).finally((()=>{a.delete(t),r.callback&&s.delete(r.callback)})),u.postMessage(n),d}const h=Date.now()},6137:(e,t,n)=>{n.d(t,{Vv:()=>r.Vv,_f:()=>r._f,_Q:()=>r._Q,IU:()=>o.I});var r=n(4746),o=n(9077)},9077:(e,t,n)=>{let r;n.d(t,{I:()=>r}),function(e){e[e.BlobUrl=0]="BlobUrl",e[e.Lottie=1]="Lottie",e[e.Progressive=2]="Progressive",e[e.Stream=3]="Stream"}(r||(r={}))},4746:(e,t,n)=>{let r;n.d(t,{Vv:()=>r,_f:()=>o,_Q:()=>d}),function(e){e.Bold="MessageEntityBold",e.Blockquote="MessageEntityBlockquote",e.BotCommand="MessageEntityBotCommand",e.Cashtag="MessageEntityCashtag",e.Code="MessageEntityCode",e.Email="MessageEntityEmail",e.Hashtag="MessageEntityHashtag",e.Italic="MessageEntityItalic",e.MentionName="MessageEntityMentionName",e.Mention="MessageEntityMention",e.Phone="MessageEntityPhone",e.Pre="MessageEntityPre",e.Strike="MessageEntityStrike",e.TextUrl="MessageEntityTextUrl",e.Url="MessageEntityUrl",e.Underline="MessageEntityUnderline",e.Unknown="MessageEntityUnknown"}(r||(r={}));const o=-1,d="MESSAGE_DELETED"},88:(e,t,n)=>{n.d(t,{Z:()=>h});var r=n(4050),o=n(5116);const d=36,u=2147483647;function a(e,t,n){let r;for(e=n?Math.floor(e/700):e>>1,e+=Math.floor(e/t),r=0;e>455;r+=d)e=Math.floor(e/35);return Math.floor(r+36*e/(e+38))}function s(e,t){const n=[],r=[],o=e.length;let s,i,c,l,f,h,m,p,g,y,v,b,w;for(s=128,c=0,l=72,f=e.lastIndexOf("-"),f<0&&(f=0),h=0;h=128)throw new RangeError("Illegal input >= 0x80");n.push(e.charCodeAt(h))}for(m=f>0?f+1:0;m=o)throw RangeError("punycode_bad_input(1)");if(v=(I=e.charCodeAt(m++))-48<10?I-22:I-65<26?I-65:I-97<26?I-97:d,v>=d)throw RangeError("punycode_bad_input(2)");if(v>Math.floor((u-c)/g))throw RangeError("punycode_overflow(1)");if(c+=v*g,b=y<=l?1:y>=l+26?26:y-l,vMath.floor(u/(d-b)))throw RangeError("punycode_overflow(2)");g*=d-b}if(i=n.length+1,l=a(c-p,i,0===p),Math.floor(c/i)>u-s)throw RangeError("punycode_overflow(3)");s+=Math.floor(c/i),c%=i,t&&r.splice(c,0,e.charCodeAt(m-1)-65<26),n.splice(c,0,s),c++}var I;if(t)for(c=0,w=n.length;c{const t=[];let n=0;const r=e.length;let o;for(;n65535&&(o-=65536,t.push(String.fromCharCode(o>>>10&1023|55296)),o=56320|1023&o),t.push(String.fromCharCode(o))}return t.join("")})(n)}var i=n(3716),c=n(6752);function l(e){if(e)return e.includes("://")?e:`https://${e}`}function f(e){if(!e)return;const t=l(e);if(t)try{let e=decodeURI(t);const n=e.match(/^https?:\/\/([^/:?#]+)(?:[/:?#]|$)/i);if(!n)return;const r=n[1];return e=e.replace(r,function(e){const t=e.split("."),n=[];for(let e=0;e{const{toggleSafeLinkModal:a,openTelegramLink:s}=(0,o.uC)(),h=d||t,m=e!==h,p=(0,r.I4)((t=>t.ctrlKey||t.altKey||t.shiftKey||t.metaKey||!e||!e.match(i.FS)&&!e.match(i.g$)?!m||(a({url:e}),t.preventDefault(),!1):(t.preventDefault(),s({url:e}),!1)),[m,s,a,e]);if(!e)return;const g=(0,c.Z)(n||"text-entity-link",t.length>50&&"long-word-break-all");return r.ZP.createElement("a",{href:l(e),title:f(e),target:"_blank",rel:"noopener noreferrer",className:g,onClick:p,dir:u?"rtl":"auto"},h)}))},5376:(e,t,n)=>{n.d(t,{yW:()=>r,K2:()=>o,mD:()=>d,Oh:()=>u,v6:()=>a});function r(e){return e>536870912?`${(e/1073741824).toFixed(1)} GB`:e>524288?`${(e/1048576).toFixed(1)} MB`:`${(e/1024).toFixed(1)} KB`}function o(e){const{fileName:t,mimeType:n}=e;return d(t,n)}function d(e,t){return e&&-1!==e.indexOf(".")?e.split(".").pop():t.split("/").pop()}function u(e){switch(e){case"apk":case"xls":case"xlsx":return"green";case"zip":case"rar":case"7z":case"tar":case"gz":case"ppt":case"pptx":return"orange";case"pdf":case"xps":return"red";default:return"default"}}function a(e){return Boolean(e.previewBlobUrl||e.thumbnail)}},4784:(e,t,n)=>{n.d(t,{Z:()=>d});var r=n(3681);const o=new RegExp(`^(?:${r.Z.source})+$`,""),d=e=>{if(e.length>24)return!1;if(!Boolean(e.match(o)))return!1;let t=0;for(;r.Z.exec(e);)if(t++,t>3)return r.Z.lastIndex=0,!1;return t}},2864:(e,t,n)=>{n.d(t,{D:()=>p});var r=n(4050),o=n(2858),d=n(8035),u=n(9937),a=n(2340),s=n(5116),i=n(782),c=n(6752),l=n(8033);const f=(0,s.c$)(void 0,((e,t)=>(0,i.ei)(t,["openUserInfo"])))((({className:e,sender:t,openUserInfo:n,children:o})=>{const d=(0,r.I4)((()=>{t&&n({id:t.id})}),[t,n]);return t?r.ZP.createElement(l.Z,{className:(0,c.Z)("UserLink",e),onClick:d},o):o})),h=(0,s.c$)(void 0,((e,t)=>(0,i.ei)(t,["focusMessage"])))((({className:e,message:t,children:n,focusMessage:o})=>{const d=(0,r.I4)((()=>{t&&o({chatId:t.chatId,messageId:t.id})}),[o,t]);return t?r.ZP.createElement(l.Z,{className:(0,c.Z)("MessageLink",e),onClick:d},n):n})),m=(0,s.c$)(void 0,((e,t)=>(0,i.ei)(t,["openChat"])))((({className:e,chatId:t,openChat:n,children:o})=>{const d=(0,r.I4)((()=>{t&&n({id:t})}),[t,n]);return t?r.ZP.createElement(l.Z,{className:(0,c.Z)("ChatLink",e),onClick:d},o):o}));function p(e,t,n,s,i,c,l={}){if(!t.content.action)return[];const{text:f,translationValues:p,amount:v,currency:b}=t.content.action,w=[],I={...l,maxTextLength:32};let C,S=e("Chat.Service.Group.UpdatedPinnedMessage1"!==f||i?f:"Message.PinnedGenericMessage",p&&p.length?p:void 0);return S.includes("%payment_amount%")&&(C=y(S,"%payment_amount%",(0,u.x)(v,b,e.code)),S=C.pop(),w.push(...C)),C=y(S,"%action_origin%",n?!l.isEmbedded&&function(e,t,n){return(0,o.YC)(t.id)?g(t,n):function(e,t,n){const u=(0,d.Z)((0,o.U)(e,t));return n?u:r.ZP.createElement(m,{className:"action-link",chatId:t.id},t&&(0,a.Z)(u))}(e,t,n)}(e,n,l.asPlain)||" ":"User"),S=C.pop(),w.push(...C),C=y(S,"%target_user%",s?s.map((e=>g(e,l.asPlain))).filter(Boolean):"User"),S=C.pop(),w.push(...C),C=y(S,"%message%",i?function(e,t,n={}){const u=(0,o.MK)(e,t),{photo:s,video:i,document:c,sticker:l}=(0,o.qp)(t),{maxTextLength:f,isEmbedded:m,asPlain:p}=n,g=m&&u&&!s&&!i&&!c&&!l;let y=(0,d.Z)(u,f);return m&&(s?y="a photo":i?y=i.isGif?"a GIF":"a video":c?y="a document":l&&(y=u)),p?g?`«${y}»`:y:g?r.ZP.createElement("span",null,"«",r.ZP.createElement(h,{className:"action-link",message:t},(0,a.Z)(y)),"»"):r.ZP.createElement(h,{className:"action-link",message:t},(0,a.Z)(y))}(e,i,I):"a message"),S=C.pop(),w.push(...C),C=y(S,"%product%",i?function(e){return e.content&&e.content.invoice?e.content.invoice.title:"a product"}(i):"a product"),S=C.pop(),w.push(...C),C=y(S,"%target_chat%",c?function(e,t){const n="another chat";return t?n:r.ZP.createElement(m,{className:"action-link",chatId:e},n)}(c,l.asPlain):"another chat"),w.push(...C),l.asPlain?w.join("").trim():w}function g(e,t){const n=(0,d.Z)((0,o.Js)(e));return t?n:r.ZP.createElement(f,{className:"action-link",sender:e},e&&(0,a.Z)(n))}function y(e,t,n){const r=e.indexOf(t);if(r<0||!n)return[e];const o=[];return o.push(e.substring(0,r)),Array.isArray(n)?n.forEach(((e,t)=>{o.push(e),t+1{n.d(t,{Z:()=>h});var r=n(4050),o=n(3681),d=n(3716),u=n(7361),a=n(4284),s=n(6752),i=n(7373),c=n(88);const l=/^[\d\wа-яё]$/i,f=/(\*\*|__).+?\1/g;function h(e,t=["emoji"],n){return"string"!=typeof e?[e]:t.reduce(((e,t)=>{switch(t){case"escape_html":return function(e){const t=document.createElement("div");return e.reduce(((e,n)=>"string"!=typeof n?[...e,n]:(t.innerText=n,[...e,t.innerHTML])),[])}(e);case"hq_emoji":return o.Z.lastIndex=0,m(e,"big","jsx");case"emoji":return o.Z.lastIndex=0,m(e,"small","jsx");case"emoji_html":return o.Z.lastIndex=0,m(e,"small","html");case"br":return p(e,"jsx");case"br_html":return p(e,"html");case"highlight":return d=e,u=n.highlight,d.reduce(((e,t)=>{if("string"!=typeof t||!u)return[...e,t];const n=t.toLowerCase(),o=n.indexOf(u.toLowerCase()),d=n[o+u.length];if(o<0||d&&d.match(l))return[...e,t];const a=[];return a.push(t.substring(0,o)),a.push(r.ZP.createElement("span",{className:"matching-text-highlight"},t.substring(o,o+u.length))),a.push(t.substring(o+u.length)),[...e,...a]}),[]);case"links":return function(e){return e.reduce(((e,t)=>{if("string"!=typeof t)return[...e,t];const n=t.match(g);if(!n||!n.length)return[...e,t];const o=[];let d=n.shift(),u=0;for(;d;){const e=t.indexOf(d,u);o.push(t.substring(u,e)),d.startsWith("@")?o.push(r.ZP.createElement(i.Z,{username:d},d)):(d.endsWith("?")&&(d=d.slice(0,d.length-1)),o.push(r.ZP.createElement(c.Z,{text:d,url:d}))),u=e+d.length,d=n.shift()}return o.push(t.substring(u)),[...e,...o]}),[])}(e);case"simple_markdown":return y(e,"jsx");case"simple_markdown_html":return y(e,"html")}var d,u;return e}),[e])}function m(e,t,n){return u.op?e:e.reduce(((e,d)=>{if("string"!=typeof d)return[...e,d];const u=(d=(0,a.g6)(d)).split(o.Z),i=d.match(o.Z)||[];return e.push(u[0]),i.reduce(((e,d,i)=>{const c=(0,a.U_)((0,o.l)(d));if(!c)return e;const l=(0,s.Z)("emoji","small"===t&&"emoji-small");"jsx"===n&&e.push(r.ZP.createElement("img",{className:l,src:`./img-apple-${"big"===t?"160":"64"}/${c}.png`,alt:d})),"html"===n&&e.push(`${d}`);const f=2*i+2;return u[f]&&e.push(u[f]),e}),e)}),[])}function p(e,t){return e.reduce(((e,n)=>"string"!=typeof n?[...e,n]:[...e,...n.split(/\r\n|\r|\n/g).reduce(((e,n,o,d)=>{const u=n.trimLeft(),a=n.length-u.length;return e.push(String.fromCharCode(160).repeat(a)+u),o!==d.length-1&&e.push("jsx"===t?r.ZP.createElement("br",null):"
"),e}),[])]),[])}const g=new RegExp(`${d.FM}|${d.uW}`,"ig");function y(e,t){return e.reduce(((e,n)=>{if("string"!=typeof n)return[...e,n];const o=n.split(f),d=n.match(f)||[];return e.push(o[0]),d.reduce(((e,n,d)=>{"jsx"===t?e.push(n.startsWith("**")?r.ZP.createElement("b",null,n.replace(/\*\*/g,"")):r.ZP.createElement("i",null,n.replace(/__/g,""))):e.push(n.startsWith("**")?`${n.replace(/\*\*/g,"")}`:`${n.replace(/__/g,"")}`);const u=2*d+2;return o[u]&&e.push(o[u]),e}),e)}),[])}},386:(e,t,n)=>{n.d(t,{q:()=>d,b:()=>u});var r=n(3716),o=n(7361);function d(e,t=!1){o.cj||!document.activeElement||document.activeElement.id!==r.R2||!t&&e.target!==e.currentTarget||e.preventDefault()}function u(e){d(e,!0)}},7373:(e,t,n)=>{n.d(t,{Z:()=>a});var r=n(4050),o=n(5116),d=n(782),u=n(8085);const a=(0,o.c$)(((e,{userId:t})=>({userOrChat:t?(0,u.dy)(e,t):void 0})),((e,t)=>(0,d.ei)(t,["openChat","openChatByUsername"])))((({username:e,userOrChat:t,children:n,openChat:o,openChatByUsername:d})=>r.ZP.createElement("a",{onClick:()=>{t?o({id:t.id}):e&&d({username:e.substring(1)})},className:"text-entity-link",dir:"auto"},n)))},231:(e,t,n)=>{n.d(t,{Z:()=>a});var r=n(4050),o=n(6752),d=n(9204),u=n(8512);const a=({ref:e,type:t="button",onClick:n,onContextMenu:a,onMouseDown:s,onMouseEnter:i,onMouseLeave:c,onFocus:l,children:f,size:h="default",color:m="primary",backgroundImage:p,className:g,round:y,pill:v,fluid:b,isText:w,isLoading:I,ariaLabel:C,href:S,download:E,disabled:P,ripple:M,faded:A,tabIndex:k,isRtl:T,withClickPropagation:N})=>{let L=(0,r.sO)(null);e&&(L=e);const[R,D]=(0,r.eJ)(!1),O=(0,o.Z)("Button",g,h,m,y&&"round",v&&"pill",b&&"fluid",P&&"disabled",w&&"text",I&&"loading",M&&"has-ripple",A&&"faded",R&&"clicked",p&&"with-image"),x=(0,r.I4)((e=>{!P&&n&&n(e),D(!0),setTimeout((()=>{D(!1)}),400)}),[P,n]),_=(0,r.I4)((e=>{N||e.preventDefault(),!P&&s&&s(e)}),[s,P,N]);return S?r.ZP.createElement("a",{ref:L,className:O,href:S,title:C,download:E,tabIndex:k,dir:T?"rtl":void 0},f,!P&&M&&r.ZP.createElement(u.Z,null)):r.ZP.createElement("button",{ref:L,type:t,className:O,onClick:x,onContextMenu:a,onMouseDown:_,onMouseEnter:i&&!P?i:void 0,onMouseLeave:c&&!P?c:void 0,onFocus:l&&!P?l:void 0,"aria-label":C,title:C,tabIndex:k,dir:T?"rtl":void 0,style:p?`background-image: url(${p})`:void 0},I?r.ZP.createElement("div",null,r.ZP.createElement("span",{dir:T?"auto":void 0},"Please wait..."),r.ZP.createElement(d.Z,{color:w?"blue":"white"})):f,!P&&M&&r.ZP.createElement(u.Z,null))}},4605:(e,t,n)=>{n.d(t,{Z:()=>s});var r=n(4050),o=n(6752),d=n(9107),u=n(2340),a=n(9204);const s=(0,r.X$)((({id:e,name:t,value:n,label:s,subLabel:i,checked:c,disabled:l,round:f,blocking:h,isLoading:m,onChange:p,onCheck:g})=>{const y=(0,d.Z)(),v=(0,r.I4)((e=>{p&&p(e),g&&g(e.currentTarget.checked)}),[p,g]),b=(0,o.Z)("Checkbox",l&&"disabled",f&&"round",m&&"loading",h&&"blocking");return r.ZP.createElement("label",{className:b,dir:y.isRtl?"rtl":void 0},r.ZP.createElement("input",{type:"checkbox",id:e,name:t,value:n,checked:c,disabled:l,onChange:v}),r.ZP.createElement("div",{className:"Checkbox-main"},r.ZP.createElement("span",{className:"label",dir:"auto"},(0,u.Z)(s)),i&&r.ZP.createElement("span",{className:"subLabel",dir:"auto"},(0,u.Z)(i))),m&&r.ZP.createElement(a.Z,null))}))},3106:(e,t,n)=>{n.d(t,{Z:()=>d});var r=n(4050),o=n(2328);const d=({trigger:e,className:t,children:n,positionX:d="left",positionY:u="top",footer:a,forceOpen:s,onOpen:i,onClose:c})=>{const l=(0,r.sO)(null),f=(0,r.sO)(null),[h,m]=(0,r.eJ)(!1);return r.ZP.createElement("div",{ref:f,className:`DropdownMenu ${t||""}`,onKeyDown:e=>{const t=l.current;if(!h||40!==e.keyCode||!t)return;const n=document.activeElement,r=Array.from(t.children);n&&-1!==r.indexOf(n)||r[0].focus()}},e({onTrigger:()=>{m(!h),h?c&&c():i&&i()},isOpen:h}),r.ZP.createElement(o.Z,{ref:l,containerRef:f,isOpen:h||!!s,className:t||"",positionX:d,positionY:u,footer:a,autoClose:!0,onClose:()=>{m(!1),c&&c()},shouldSkipTransition:s},n))}},7687:(e,t,n)=>{n.d(t,{Z:()=>u});var r=n(4050),o=n(6752),d=n(9107);const u=(0,r.X$)((({ref:e,id:t,className:n,value:u,label:a,error:s,success:i,disabled:c,readOnly:l,placeholder:f,autoComplete:h,inputMode:m,maxLength:p,onChange:g,onInput:y,onKeyPress:v,onKeyDown:b,onBlur:w,onPaste:I})=>{const C=(0,d.Z)(),S=s||i||a,E=(0,o.Z)("input-group",u&&"touched",s?"error":i&&"success",c&&"disabled",l&&"disabled",S&&"with-label",n);return r.ZP.createElement("div",{className:E,dir:C.isRtl?"rtl":void 0},r.ZP.createElement("input",{ref:e,className:"form-control",type:"text",id:t,dir:"auto",value:u||"",placeholder:f,maxLength:p,autoComplete:h,inputMode:m,disabled:c,readOnly:l,onChange:g,onInput:y,onKeyPress:v,onKeyDown:b,onBlur:w,onPaste:I}),S&&r.ZP.createElement("label",{htmlFor:t},S))}))},8033:(e,t,n)=>{n.d(t,{Z:()=>d});var r=n(4050),o=n(6752);const d=({children:e,className:t,isRtl:n,onClick:d})=>{const u=(0,r.I4)((e=>{e.preventDefault(),d(e)}),[d]);return r.ZP.createElement("a",{href:"#",className:(0,o.Z)("Link",t),dir:n?"rtl":"auto",onClick:d?u:void 0},e)}},4288:(e,t,n)=>{n.d(t,{Z:()=>d});var r=n(4050),o=n(9204);const d=(0,r.X$)((({color:e="blue"})=>r.ZP.createElement("div",{className:"Loading"},r.ZP.createElement(o.Z,{color:e,withBackground:"white"===e}))))},2328:(e,t,n)=>{n.d(t,{Z:()=>h});var r=n(4050),o=n(1212),d=n(2313),u=n(8758),a=n(274),s=n(3989),i=n(6752),c=n(8674),l=n(6590),f=n(386);const h=({ref:e,containerRef:t,isOpen:n,className:h,style:m,menuStyle:p,children:g,positionX:y="left",positionY:v="top",autoClose:b=!1,footer:w,noCloseOnBackdrop:I=!1,onCloseAnimationEnd:C,onClose:S,onMouseEnter:E,onMouseLeave:P,shouldSkipTransition:M})=>{let A=(0,r.sO)(null);e&&(A=e);const k=t||A,{transitionClassNames:T}=(0,o.Z)(n,C,M,void 0,M);(0,r.d4)((()=>n&&S?(0,s.Z)(S):void 0),[n,S]),(0,l.ZP)(n,S,void 0,void 0,b),(0,a.Z)((([e])=>{void 0!==e&&(0,c.YW)(200)}),[n]);const N=(0,d.Z)(A,n,b?S:void 0,void 0,!0);(0,u.Z)(n,k,I?void 0:S);const L=(0,i.Z)("bubble menu-container custom-scroll",v,y,w&&"with-footer",T);return r.ZP.createElement("div",{className:(0,i.Z)("Menu no-selection",h),onKeyDown:n?N:void 0,onMouseEnter:E,onMouseLeave:n?P:void 0,style:m},n&&r.ZP.createElement("div",{className:"backdrop",onMouseDown:f.b}),r.ZP.createElement("div",{ref:A,className:L,style:`transform-origin: ${v} ${y};${p||""}`,onClick:b?S:void 0},g,w&&r.ZP.createElement("div",{className:"footer"},w)))}},8964:(e,t,n)=>{n.d(t,{Z:()=>u});var r=n(4050),o=n(6752),d=n(9107);const u=e=>{const{icon:t,className:n,children:u,onClick:a,href:s,download:i,disabled:c,destructive:l,ariaLabel:f}=e,h=(0,d.Z)(),m=(0,r.I4)((e=>{if(c||!a)return e.stopPropagation(),void e.preventDefault();a(e)}),[c,a]),p=(0,r.I4)((e=>{if(13===e.keyCode||32===e.keyCode)return c||!a?(e.stopPropagation(),void e.preventDefault()):void a(e)}),[c,a]),g=(0,o.Z)("MenuItem",n,c&&"disabled",l&&"destructive"),y=r.ZP.createElement(r.ZP.Fragment,null,t&&r.ZP.createElement("i",{className:`icon-${t}`,"data-char":t.startsWith("char-")?t.replace("char-",""):void 0}),u);return s?r.ZP.createElement("a",{tabIndex:0,className:g,href:s,download:i,"aria-label":f,title:f,target:s.startsWith(window.location.origin)?"_self":"_blank",rel:"noopener noreferrer",dir:h.isRtl?"rtl":void 0,onClick:a},y):r.ZP.createElement("div",{role:"button",tabIndex:0,className:g,onClick:m,onKeyDown:p,"aria-label":f,title:f,dir:h.isRtl?"rtl":void 0},y)}},8512:(e,t,n)=>{n.d(t,{Z:()=>d});var r=n(4050),o=n(9118);const d=(0,r.X$)((()=>{const[e,t]=(0,r.eJ)([]),n=(0,r.Ye)((()=>(0,o.Ds)((()=>{t([])}),700,!1)),[]),d=(0,r.I4)((r=>{if(0!==r.button)return;const o=r.currentTarget,d=o.getBoundingClientRect(),u=o.offsetWidth/2;t([...e,{x:r.clientX-d.x-u/2,y:r.clientY-d.y-u/2,size:u}]),requestAnimationFrame((()=>{n()}))}),[e,n]);return r.ZP.createElement("div",{className:"ripple-container",onMouseDown:d},e.map((({x:e,y:t,size:n})=>r.ZP.createElement("span",{style:`left: ${e}px; top: ${t}px; width: ${n}px; height: ${n}px;`}))))}))},9204:(e,t,n)=>{n.d(t,{Z:()=>d});var r=n(4050),o=n(6752);const d=({color:e="blue",withBackground:t})=>r.ZP.createElement("div",{className:(0,o.Z)("Spinner",e,t&&"with-background")},r.ZP.createElement("div",null))},3716:(e,t,n)=>{n.d(t,{Ti:()=>r,ou:()=>o,iC:()=>d,Ji:()=>u,eM:()=>a,ZT:()=>s,Cg:()=>i,S:()=>c,b_:()=>l,Vx:()=>f,sd:()=>h,Uh:()=>m,gJ:()=>p,lO:()=>g,Cy:()=>y,lW:()=>v,SG:()=>b,lF:()=>w,fo:()=>I,ee:()=>C,by:()=>S,lo:()=>P,gZ:()=>M,hT:()=>A,YQ:()=>k,rS:()=>T,t_:()=>N,Ov:()=>L,EN:()=>R,pn:()=>D,Hk:()=>O,Vk:()=>x,mo:()=>_,qU:()=>Z,ul:()=>F,NM:()=>B,Qx:()=>$,mw:()=>U,oB:()=>j,zy:()=>W,CX:()=>V,xS:()=>G,b6:()=>H,AR:()=>z,r_:()=>Q,R2:()=>K,nY:()=>J,QU:()=>q,jT:()=>Y,_m:()=>X,ks:()=>ee,l3:()=>te,u_:()=>ne,rO:()=>re,AE:()=>oe,AJ:()=>de,fK:()=>ue,V$:()=>ae,bK:()=>se,ck:()=>ie,xn:()=>ce,K7:()=>le,w7:()=>fe,z7:()=>he,qp:()=>me,Q:()=>pe,Mw:()=>ge,DC:()=>ye,Y7:()=>ve,yK:()=>be,K2:()=>we,bM:()=>Ie,ku:()=>Ce,zq:()=>Se,n:()=>Ee,pR:()=>Pe,kU:()=>Me,Y:()=>Ae,Ng:()=>ke,oG:()=>Te,wG:()=>Ne,dI:()=>Le,FM:()=>Re,uW:()=>De,g$:()=>Oe,FS:()=>xe,FD:()=>_e,aw:()=>Ze,FV:()=>Fe,Nf:()=>Be,WS:()=>$e,DU:()=>Ue,EG:()=>je,t4:()=>We,sR:()=>Ve,$O:()=>Ge,Bg:()=>He,vi:()=>ze,Db:()=>Qe,mU:()=>Ke,p3:()=>Je,It:()=>qe,Vv:()=>Ye,g:()=>Xe});const r="Telegram",o=" [Inactive]",d="Telegram WebZ",u="1.22.2",a=!1,s=!1,i=!1,c="Shoot!\nSomething went wrong, please see the error details in Dev Tools Console.",l="user_auth",f="GramJs:sessionId",h=!1,m="tt-global-state",p=30,g=5e3,y=!1,v="tt-media",b="tt-media-avatars",w="tt-media-progressive",I="tt-custom-bg",C="tt-lang-packs-v6",S=[1,5,10,50,100,500],E="undefined"!=typeof window&&window.innerHeight>=900,P=1,M=750,A=E?60:40,k=2*A,T=72,N=E?30:25,L=100,R=42,D=42,O=20,x=30,_=200,Z=500,F=20,B=!1,$=1,U=1,j=0,W=2,V=W,G=16,H=17,z=15,Q=1e4,K="editable-message-text",J="editable-message-text-modal",q=1440,Y=1150,X=1275,ee=925,te=600,ne=950,re=450,oe=1e9,de="0",ue=100,ae=1500,se=250,ie=600,ce=500,le=(Math.round((se+ie)/2),new Set(["newMessage","newScheduledMessage","deleteMessages","deleteScheduledMessages","deleteHistory"]),13),fe=11,he=160,me=120,pe=64,ge=48,ye=32,ve=64,be=64,we=160,Ie=140,Ce=80,Se=100,Ee="MEMOJI_STICKER",Pe="en",Me=200,Ae=450,ke="video/quicktime",Te=new Set(["image/png","image/gif","image/jpeg"]),Ne=new Set(["video/mp4"]),Le=new Set([...Te,...Ne]),Re="((ftp|https?):\\/\\/)?((www\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\.[a-zA-Z0-9()]{1,63})\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)",De="(@[\\w\\d_-]+)",Oe=/^tg:(\/\/)?([?=&\d\w_-]+)?/gm,xe=/^(?:https?:\/\/)?(?:t\.me\/)/gm,_e=new Set(["AU","BD","CA","CO","EG","HN","IE","IN","JO","MX","MY","NI","NZ","PH","PK","SA","SV","US"]),Ze="777000",Fe="1271266957",Be=0,$e=1,Ue=10,je=5,We=2147483646,Ve="en",Ge="android",He=["android","ios","tdesktop","macos"],ze="TelegramTips",Qe=["ar","pt-br","id","it","ko","ms","pl","es","tr"],Ke="https://bugs.telegram.org/?tag_ids=41&sort=time",Je="#A2AF8E",qe="#0F0F0F",Ye="#0a0a0a8c",Xe="rgba(90, 110, 70, 0.6)"},274:(e,t,n)=>{n.d(t,{Z:()=>d});var r=n(4050),o=n(7204);const d=(e,t,n)=>{const d=(0,o.Z)(t);return(0,r.d4)((()=>e(d||[])),t,n)}},706:(e,t,n)=>{n.d(t,{Z:()=>o});var r=n(4050);const o=(e=!1)=>{const[t,n]=(0,r.eJ)(e);return[t,(0,r.I4)((()=>{n(!0)}),[]),(0,r.I4)((()=>{n(!1)}),[])]}},5326:(e,t,n)=>{n.d(t,{Z:()=>o});var r=n(4050);const o=()=>{const[,e]=(0,r.eJ)(!1);return(0,r.I4)((()=>{e((e=>!e))}),[])}},8674:(e,t,n)=>{n.d(t,{_L:()=>o,OV:()=>d,YW:()=>s,ZP:()=>i});var r=n(4050);const o="tt-event-heavy-animation-start",d="tt-event-heavy-animation-end";let u,a=!1;const s=e=>(a||(a=!0,document.dispatchEvent(new Event(o))),u&&(clearTimeout(u),u=void 0),e&&(u=window.setTimeout((()=>{a=!1,document.dispatchEvent(new Event(d)),u=void 0}),e)),()=>{a=!1,document.dispatchEvent(new Event(d))}),i=(e,t)=>{(0,r.d4)((()=>(a&&e(),document.addEventListener(o,e),document.addEventListener(d,t),()=>{document.removeEventListener(d,t),document.removeEventListener(o,e)})),[t,e])}},6590:(e,t,n)=>{n.d(t,{Oy:()=>s,Wv:()=>l,ZP:()=>h});var r=n(4050),o=n(7361),d=n(7204),u=n(5116),a=n(782);const s=window.location.hash,i=`${window.location.pathname}${window.location.search}`,c={currentIndex:0,nextStateIndexToReplace:-1,isHistoryAltered:!1,isDisabled:!1,isEdge:!1,currentIndexes:[]},l=()=>{c.isDisabled=!0},f=()=>{c.isEdge&&setTimeout((()=>{c.isEdge=!1}),350)};function h(e,t,n,o,s=!1,l){const f=(0,r.sO)(-1),h=(0,r.sO)(!1),m=(0,d.Z)(e),p=(0,r.sO)(!0),g=(0,r.sO)([]),y=(0,d.Z)(l),v=(0,r.sO)(!1),b=(0,r.I4)(((t=!1)=>{if(l){const e=y||[];if(e.length{const e=++c.currentIndex;c.currentIndexes.push(e),window.history.pushState({index:e,state:o},"",`#${l[l.length-1]}`),g.current.push({index:e,hash:l[l.length-1]})}),0);else{const t=e.length-l.length;if(v.current)v.current=!1;else{if(l.length!==g.current.length&&t>0){const e=g.current[g.current.length-t-1];let n=t;if(e){const t=c.currentIndexes.findIndex((t=>t===e.index));n=c.currentIndexes.length-t-1}c.isHistoryAltered=!0,window.history.go(-n),g.current.splice(g.current.length-t-1,t).forEach((({index:e})=>{c.currentIndexes.splice(c.currentIndexes.indexOf(e),1)}))}l.length>0&&setTimeout((()=>{const e=++c.currentIndex;c.currentIndexes[c.currentIndexes.length-1]=e,window.history.replaceState({index:e,state:o},"",`${i}#${l[l.length-1]}`),g.current[g.current.length-1]={index:e,hash:l[l.length-1]}}),0)}}}else e&&!t&&(p.current=!1,h.current?(h.current=!1,c.currentIndexes.push(f.current)):setTimeout((()=>{const e=++c.currentIndex;c.currentIndexes.push(e),window.history[c.currentIndexes.includes(c.nextStateIndexToReplace-1)&&0!==window.history.state.index&&c.nextStateIndexToReplace===e&&!s?"replaceState":"pushState"]({index:e,state:o},""),f.current=e,s&&(c.nextStateIndexToReplace=c.currentIndex+1)}),0)),!t&&e||p.current||(f.current!==c.currentIndex&&s||(c.isHistoryAltered=!0,window.history.back(),setTimeout((()=>{c.nextStateIndexToReplace=-1}),400)),c.currentIndexes.splice(c.currentIndexes.indexOf(f.current),1),p.current=!0)}),[o,l,e,y,s]);return(0,r.d4)((()=>{const r=e=>{if(c.isHistoryAltered)return void setTimeout((()=>{c.isHistoryAltered=!1}),0);const{index:r}=e.state,o=r||0;try{const r=l?g.current[g.current.length-1].index:f.current,d=c.currentIndexes[c.currentIndexes.indexOf(r)-1];if(c.isDisabled)return;!p.current&&(0===o||o===d)||l&&(0===o||o===d)?(l&&(v.current=!0,g.current.pop()),c.currentIndexes.splice(c.currentIndexes.indexOf(r),1),t&&(c.isEdge&&(0,u.uC)().disableHistoryAnimations(),t(!c.isEdge),p.current=!0)):o===r&&p.current&&n&&!l&&(h.current=!0,c.isEdge&&(0,u.uC)().disableHistoryAnimations(),n(e.state.state))}catch(e){}},o=l?!y||!(0,a.et)(y,l):m!==e;return!c.isDisabled&&o&&b(),window.addEventListener("popstate",r),()=>window.removeEventListener("popstate",r)}),[o,b,l,e,t,n,y,m,s]),{forceClose:()=>b(!0)}}o.cj&&(window.addEventListener("touchstart",(e=>{const t=e.touches[0].pageX;(t<=300||t>=window.innerWidth-300)&&(c.isEdge=!0)})),window.addEventListener("touchend",f),window.addEventListener("popstate",f)),window.history.replaceState({index:c.currentIndex},"",i)},2313:(e,t,n)=>{n.d(t,{Z:()=>o});var r=n(4050);const o=(e,t,n,o,d)=>{const[u,a]=(0,r.eJ)(-1);return(0,r.d4)((()=>{a(-1);const n=e.current;t&&n&&!d&&(n.tabIndex=-1,n.focus())}),[e,t,d]),(0,r.I4)((t=>{const r=e.current;if(!r)return;if(13===t.keyCode&&n)return void n(u);if(38!==t.keyCode&&40!==t.keyCode)return;const d=document.activeElement,s=Array.from(o?r.querySelectorAll(o):r.children);let i=d&&s.indexOf(d)||u;if(38===t.keyCode&&i>0)i--;else if(40===t.keyCode&&i{n.d(t,{Z:()=>u});var r=n(663),o=n(5326),d=n(9290);const u=()=>{const e=(0,o.Z)();return(0,d.Z)((()=>r.ll(e)),[e]),r.i0}},8778:(e,t,n)=>{n.d(t,{Z:()=>u});var r=n(4050),o=n(9203),d=n(5326);const u=(e,t,n=!1,u=!1)=>{const a=(0,o.o5)(e,t),s=(0,d.Z)();return u&&(0,o.Qt)(s),(0,r.d4)((()=>{n||a||(0,o.$y)(e,t).then(s)}),[e,s,a,t,n]),a}},9290:(e,t,n)=>{n.d(t,{Z:()=>o});var r=n(7204);const o=(e,t)=>{const n=(0,r.Z)(t);n&&!t.some(((e,t)=>e!==n[t]))||e(n||[])}},7204:(e,t,n)=>{n.d(t,{Z:()=>o});var r=n(4050);const o=function(e,t){const n=(0,r.sO)(),{current:o}=n;return t&&void 0===e||(n.current=e),o}},1212:(e,t,n)=>{n.d(t,{Z:()=>d});var r=n(4050),o=n(6752);const d=(e=!1,t,n=!1,d="fast",u=!1)=>{const[a,s]=(0,r.eJ)(!e),i=(0,r.sO)(),[c,l]=(0,r.eJ)(e&&n);e?(s(!1),l(!0),i.current&&(window.clearTimeout(i.current),i.current=void 0)):(l(!1),a||i.current||(i.current=window.setTimeout((()=>{s(!0),t&&t(),i.current=void 0}),u?0:350)));const f=c&&!(u&&!e),h=Boolean(i.current),m=e||h;return{shouldRender:m,transitionClassNames:(0,o.Z)(d&&"opacity-transition",d,f&&"open",m&&"shown",h&&"closing")}}},8758:(e,t,n)=>{n.d(t,{Z:()=>o});var r=n(4050);function o(e,t,n){(0,r.d4)((()=>{const r=e=>{const r=t.current,o=e.target;r&&o&&(r.contains(e.target)&&!o.classList.contains("backdrop")||(e.preventDefault(),e.stopPropagation(),n&&n()))};return e&&n&&document.addEventListener("mousedown",r),()=>{document.removeEventListener("mousedown",r)}}),[e,t,n])}},5247:(e,t,n)=>{n.d(t,{Oo:()=>s,xg:()=>i,lQ:()=>h});var r=n(3716);const o=new Set(["scroll","mouseenter","mouseleave"]),d={},u=new Map,a={};function s(e,t,n,r=!1){const o=c(t,e);l(o,e,r)?function(e,t,n){a[e]||(a[e]=0,document.addEventListener(e,m)),function(e){return d[e]||(d[e]=new Map),d[e]}(e).set(t,n),function(e){const t=u.get(e);if(t)return t;const n=new Set;return u.set(e,n),n}(t).add(e),a[e]++}(o,e,n):e.addEventListener(o,n,r)}function i(e,t,n,r=!1){const o=c(t,e);l(o,e,r)?f(o,e):e.removeEventListener(o,n,r)}function c(e,t){const n=e.replace(/^on/,"").replace(/Capture$/,"").toLowerCase();return"change"===n&&"SELECT"!==t.tagName?"input":"doubleclick"===n?"dblclick":"focus"===n?"focusin":"blur"===n?"focusout":n}function l(e,t,n){return!n&&!o.has(e)&&"VIDEO"!==t.tagName&&"IFRAME"!==t.tagName}function f(e,t){a[e]--,a[e]||document.removeEventListener(e,m),d[e].delete(t),u.get(t).delete(e)}function h(e){const t=u.get(e);t&&(t.forEach((t=>f(t,e))),u.delete(e))}function m(e){const t=d[e.type];if(t){let n=!1,r=e.target;const o=()=>{n=!0},d=()=>{e.preventDefault()},u=new Proxy(e,{get:(e,t)=>"currentTarget"===t?r:"stopPropagation"===t||"stopImmediatePropagation"===t?o:"preventDefault"===t?d:Reflect.get(e,t)});for(;r&&r!==document.body;){const e=t.get(r);if(e&&(e(u),n))return;r=r.parentNode}}}r.eM&&document.addEventListener("dblclick",(()=>{console.log("DELEGATED EVENTS",{delegationRegistry:d,delegatedEventsByElement:u,documentEventCounters:a})}))},2916:(e,t,n)=>{n.d(t,{Z:()=>v});var r=n(4050),o=n(6926),d=n(3716),u=n(5247);const a=new Set(["key","ref","teactFastList","teactOrderKey"]),s=new Set(["dir"]),i={autoPlay:"autoplay",autoComplete:"autocomplete"},c={};function l(e,t,n,o,u,{skipComponentUpdate:a=!1,forceIndex:s=!1,fragment:i,moveDirection:c}={}){if(!a&&t&&n&&(0,r.op)(t)&&(0,r.op)(n)&&!(0,r.k)(t,n)&&(n=function(e,t){return e.componentInstance.props=t.componentInstance.props,(0,r.SO)(e.componentInstance)}(t,n)),!a&&n&&(0,r.op)(n)&&n.componentInstance.isMounted&&h(n,o,u,e),t===n)return n;if(!t&&n){(0,r.op)(n)&&(n=f(n,o,u,e));const t=m(n);(0,r.CD)(n,t),s&&e.childNodes[u]?e.insertBefore(t,e.childNodes[u]):(i||e).appendChild(t)}else if(t&&!n)e.removeChild((0,r.U9)(t)),(0,r.Zb)(t);else if(t&&n)if((0,r.k)(t,n)){(0,r.op)(n)&&(n=f(n,o,u,e));const d=m(n);(0,r.CD)(n,d),e.replaceChild(d,(0,r.U9)(t)),(0,r.Zb)(t)}else{const o=(0,r.op)(t)&&(0,r.op)(n);if(o||(0,r.CD)(n,(0,r.U9)(t)),(0,r.O_)(t)&&(0,r.O_)(n)){if(c){const n=(0,r.U9)(t),o=e.childNodes["up"===c?u:u+1];o?e.insertBefore(n,o):(i||e).appendChild(n)}o||function(e,t,n){const r=Object.keys(e.props),o=Object.keys(t.props);r.forEach((r=>{void 0!==e.props[r]&&void 0===t.props[r]&&y(n,r,e.props[r])})),o.forEach((r=>{void 0!==t.props[r]&&e.props[r]!==t.props[r]&&(void 0===e.props[r]?g(n,r,t.props[r]):function(e,t,n,r){"value"===t?e.value=void 0!==r?r:"":(y(e,t,n),g(e,t,r))}(n,r,e.props[r],t.props[r]))}))}(t,n,(0,r.U9)(t)),n.children=function(e,t,n){if(t.props.teactFastList)return function(e,t,n){const o=new Set(t.children.map((e=>{const t="props"in e&&e.props.key;return d.eM&&(0,r.O_)(e)&&!t&&console.warn("Missing `key` in `teactFastList`"),t})));let u=0;const a=e.children.reduce(((e,r,d)=>{let a="props"in r?r.props.key:void 0;if(a&&!o.has(a))return l(n,r,void 0,t,-1),e;if(!a){const o=t.children[d],u=o&&"props"in o?o.props.key:void 0;if(!o||u)return l(n,r,void 0,t,-1),e;a=`__indexKey#${d}`}return e[a]={$element:r,index:u++,order:"props"in r?r.props.teactOrderKey:void 0},e}),{});let s,i,c=[],f=0;return t.children.forEach(((e,r)=>{const o="props"in e?e.props.key:`__indexKey#${r}`,d=a[o];if(!d)return s||(s=[],i=r),void s.push(e);s&&(c=c.concat(p(s,i,n,t)),i=void 0,s=void 0);const u="props"in e?e.props.teactOrderKey:void 0,h=d.index!==f&&d.order!==u,m=h&&f>d.index;h&&!m||f++,c.push(l(n,d.$element,e,t,r,{forceIndex:!0,...h&&{moveDirection:m?"down":"up"}}))})),s&&(c=c.concat(p(s,i,n,t))),c}(e,t,n);const o=Math.max(e.children.length,t.children.length),u=[],a=t.children.length>e.children.length+1?document.createDocumentFragment():void 0;for(let r=0;r=e.children.length?{fragment:a}:void 0);o&&u.push(o)}return a&&n.appendChild(a),u}(t,n,o?e:(0,r.U9)(t))}}return n}function f(e,t,n,o){if(!(0,r.op)(e))return e;const{componentInstance:d}=e;if(!d.isMounted){h(e=(0,r.Hb)(d),t,n,o);const u=e.children[0];(0,r.op)(u)&&(e.children=[f(u,e,0,o)]),d.isMounted=!0}return e}function h(e,t,n,r){const{componentInstance:o}=e;o.onUpdate=()=>{t.children[n]=l(r,t.children[n],o.$element,t,n,{skipComponentUpdate:!0})}}function m(e){if((0,r.V2)(e))return document.createTextNode("");if((0,r.iB)(e))return document.createTextNode(e.value);if((0,r.op)(e))return m(e.children[0]);const{tag:t,props:n,children:o=[]}=e,d=document.createElement(t);return"object"==typeof n.ref&&(n.ref.current=d),Object.keys(n).forEach((e=>{g(d,e,n[e])})),e.children=o.map(((t,n)=>l(d,void 0,t,e,n))),d}function p(e,t,n,r){if(1===e.length)return[l(n,void 0,e[0],r,t,{forceIndex:!0})];if(e.length>1){const o=document.createDocumentFragment(),d=e.map((e=>l(n,void 0,e,r,t,{fragment:o})));return n.childNodes[t]?n.insertBefore(o,n.childNodes[t]):n.appendChild(o),d}throw new Error("Unexpected input")}function g(e,t,n){void 0!==n&&("className"===t?e.className=n:"value"===t?e.value=n:"style"===t?e.style.cssText=n:t.startsWith("on")?(0,u.Oo)(e,t,n,t.endsWith("Capture")):t.startsWith("data-")||s.has(t)?e.setAttribute(t,n):a.has(t)||(e[i[t]||t]=n))}function y(e,t,n){"className"===t?e.className="":"value"===t?e.value="":"style"===t?e.style.cssText="":t.startsWith("on")?(0,u.xg)(e,t,n,t.endsWith("Capture")):t.startsWith("data-")||s.has(t)?e.removeAttribute(t):a.has(t)||delete e[i[t]||t]}const v={render:function(e,t){if(!t)return;let n=t.getAttribute("data-teact-head-id");n||(n=(0,o.Z)(c),c[n]={children:[]},t.setAttribute("data-teact-head-id",n));const r=c[n];r.children=[l(t,r.children[0],e,r,0)]}}},4050:(e,t,n)=>{n.d(t,{V2:()=>f,iB:()=>h,op:()=>p,O_:()=>g,SO:()=>S,k:()=>E,Zb:()=>P,Hb:()=>M,U9:()=>T,CD:()=>N,eJ:()=>L,d4:()=>D,bt:()=>O,Ye:()=>x,I4:()=>_,sO:()=>Z,X$:()=>F,ZP:()=>B});var r=n(3716),o=n(9118),d=n(782),u=n(275),a=n(3592),s=n(5247);let i;!function(e){e[e.Empty=0]="Empty",e[e.Text=1]="Text",e[e.Tag=2]="Tag",e[e.Component=3]="Component"}(i||(i={}));const c=Symbol("Fragment");let l;function f(e){return e.type===i.Empty}function h(e){return e.type===i.Text}function m(e){return e.type===i.Tag}function p(e){return e.type===i.Component}function g(e){return m(e)||p(e)}function y(e,t,...n){return t||(t={}),n=(0,d.xH)(n),e===c?n:"function"==typeof e?function(e,t,n){let r;0===n.length?r=void 0:1===n.length?[r]=n:r=n;const o={$element:{},Component:e,name:e.name,props:{...t,...r&&{children:r}},isMounted:!1,hooks:{state:{cursor:0,byCursor:[]},effects:{cursor:0,byCursor:[]},memos:{cursor:0,byCursor:[]}}};return o.$element=v(o),o.$element}(e,t,n):function(e,t,n){return{type:i.Tag,tag:e,props:t,children:b(n).map(I)}}(e,t,n)}function v(e,t=[]){const{props:n}=e;return{componentInstance:e,type:i.Component,props:n,children:t}}function b(e){let t=e.length-1;for(;t>=0&&w(e[t]);t--);return t+17&&console.warn(`[Teact] Slow component render: ${n}, ${Math.round(t)} ms`),C[n].renderTimes.push(t),C[n].renderCount++}}catch(t){(0,a.S)(t),o=e.renderedValue}if(e.isMounted&&o===e.renderedValue)return e.$element;e.renderedValue=o;const d=I(o);return e.$element=v(e,[d]),e.$element}function E(e,t){return typeof e!=typeof t||e.type!==t.type||(h(e)&&h(t)?e.value!==t.value:m(e)&&m(t)?e.tag!==t.tag||e.props.key!==t.props.key:!(!p(e)||!p(t)||e.componentInstance.Component===t.componentInstance.Component&&e.props.key===t.props.key))}function P(e){var t;g(e)&&(p(e)?(t=e.componentInstance).isMounted&&(t.hooks.memos.byCursor.forEach((e=>{e.current=null})),t.hooks.effects.byCursor.forEach((({cleanup:e})=>{if("function"==typeof e)try{e()}catch(e){(0,a.S)(e)}})),t.isMounted=!1,function(e){e.hooks.effects.byCursor.forEach((e=>{e.cleanup=null,e.effect=null,e.dependencies=null})),e.hooks.state.byCursor.forEach((e=>{e.value=null,e.nextValue=null,e.setter=null})),e.hooks.memos.byCursor.forEach((e=>{e.dependencies=null})),e.hooks=null,e.$element=null,e.renderedValue=null,e.Component=null,e.props=null,e.forceUpdate=null,e.onUpdate=null}(t)):e.target&&((0,s.lQ)(e.target),e.target=null),e.children.forEach(P))}function M(e){return S(e),e.isMounted=!0,e.$element}function A(e){e.isMounted&&(e.hooks.state.byCursor.forEach((e=>{e.value=e.nextValue})),e.prepareForFrame=(0,o.wT)((()=>A(e))),e.forceUpdate=(0,o.mS)((()=>k(e))))}function k(e){if(!e.isMounted||!e.onUpdate)return;const t=e.$element;S(e),e.$element!==t&&e.onUpdate()}function T(e){return p(e)?T(e.children[0]):e.target}function N(e,t){p(e)?N(e.children[0],t):e.target=t}function L(e){const{cursor:t,byCursor:n}=l.hooks.state;var d;return void 0===n[t]&&(n[t]={value:e,nextValue:e,setter:(d=l,e=>{n[t].nextValue!==e&&(n[t].nextValue="function"==typeof e?e(n[t].value):e,d.prepareForFrame&&d.forceUpdate||(d.prepareForFrame=(0,o.wT)((()=>A(d))),d.forceUpdate=(0,o.mS)((()=>k(d)))),d.prepareForFrame(),d.forceUpdate(),r.ZT&&"TeactNContainer"!==d.name&&console.log("[Teact.useState]",d.name,d.Component&&d.Component.DEBUG_contentComponentName?`> ${d.Component.DEBUG_contentComponentName}`:"",`Forced update at cursor #${t}, next value: `,n[t].nextValue))})}),l.hooks.state.cursor++,[n[t].value,n[t].setter]}function R(e,t,n,r,o){const{cursor:d,byCursor:u}=l.hooks.effects,s=l;function i(){if(!s.isMounted)return;const{cleanup:e}=u[d];if("function"==typeof e)try{e()}catch(e){(0,a.S)(e)}}function c(){s.isMounted&&(u[d].cleanup=n())}if(void 0!==u[d]&&r&&u[d].dependencies){if(r.some(((e,t)=>e!==u[d].dependencies[t]))){if(o){const e=r.reduce(((e,t,n)=>{const r=u[d].dependencies[n];return t!==r&&e.push(`${n}: ${r} => ${t}`),e}),[]);console.log("[Teact]",o,"Effect caused by dependencies.",e.join(", "))}t(i),e(c)}}else t(i),e(c);u[d]={effect:n,dependencies:r,cleanup:u[d]?u[d].cleanup:void 0},l.hooks.effects.cursor++}function D(e,t,n){return R(o.T2,o.D0,e,t,n)}function O(e,t,n){return R(o.R3,o.zD,e,t,n)}function x(e,t,n){const{cursor:o,byCursor:d}=l.hooks.memos;let{current:a}=d[o]||{};return(void 0===d[o]||t.some(((e,t)=>e!==d[o].dependencies[t])))&&(r.eM&&n&&console.log(`[Teact.useMemo] ${l.name} (${n}): Update is caused by:`,d[o]?(0,u.c)(t,d[o].dependencies).join(", "):"[first render]"),a=e()),d[o]={current:a,dependencies:t},l.hooks.memos.cursor++,a}function _(e,t){return x((()=>e),t)}function Z(e){return x((()=>({current:e})),[])}function F(e,t=u.Z,n){return function(o){const d=Z(o),a=Z();return(!a.current||d.current&&!t(d.current,o))&&(r.eM&&n&&console.log(`[Teact.memo] ${e.name} (${n}): Update is caused by:`,(0,u.c)(d.current,o).join(", ")),d.current=o,a.current=y(e,o)),a.current}}document.addEventListener("dblclick",(()=>{console.log("COMPONENTS",(0,d.Xo)(Object.values(C),"renderCount","desc"))}));const B={createElement:y,Fragment:c}},5116:(e,t,n)=>{n.d(t,{ZP:()=>f,R3:()=>w,Rd:()=>I,uC:()=>C,Q6:()=>S,ll:()=>E,Iq:()=>P,c$:()=>M});var r=n(4050),o=n(3716),d=n(5326),u=n(6926),a=n(9118),s=n(275),i=n(782),c=n(3592);function l(){return(l=Object.assign||function(e){for(var t=1;t7&&console.warn(`[TeactN] Slow containers update: ${Math.round(t)} ms`)}}],g={},y=new Map;function v(){p.forEach((e=>e(h)))}const b=(0,a.mS)(v);function w(e,t=!1){"object"==typeof e&&e!==h&&(h=e,t?v():b())}function I(){return h}function C(){return g}function S(e,t){m[e]||(m[e]=[],g[e]=(t,n=!1)=>{!function(e,t,n){m[e]&&m[e].forEach((e=>{const r=e(h,g,t);r&&w(r,n)}))}(e,t,n)}),m[e].push(t)}function E(e){p.push(e)}function P(e){const t=p.indexOf(e);-1!==t&&p.splice(t,1)}function M(e=(()=>({})),t=(()=>({}))){return n=>function o(a){o.DEBUG_contentComponentName=n.name;const[i]=(0,r.eJ)((0,u.Z)(y)),f=(0,d.Z)();(0,r.d4)((()=>()=>{y.delete(i)}),[i]);let m=y.get(i);if(m||(m={mapStateToProps:e,mapReducersToProps:t,ownProps:a,areMappedPropsChanged:!1,forceUpdate:f,DEBUG_updates:0,DEBUG_componentName:n.name},y.set(i,m)),m.areMappedPropsChanged&&(m.areMappedPropsChanged=!1),!m.mappedProps||!(0,s.Z)(m.ownProps,a)){m.ownProps=a;try{m.mappedProps={...e(h,a),...t(w,g)}}catch(e){(0,c.S)(e)}}return r.ZP.createElement(n,l({},m.mappedProps,a))}}o.eM&&(window.getGlobal=I,document.addEventListener("dblclick",(()=>{console.log("GLOBAL CONTAINERS",(0,i.Xo)(Array.from(y.values()).map((({DEBUG_componentName:e,DEBUG_updates:t})=>({DEBUG_componentName:e,DEBUG_updates:t}))),"DEBUG_updates","desc"))})))},3681:(e,t,n)=>{n.d(t,{l:()=>d,Z:()=>u});const r=/\uFE0F/g,o=String.fromCharCode(8205);function d(e){return e.indexOf(o)<0?e.replace(r,""):e}const u=/(?:\ud83d\udc68\ud83c\udffb\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc68\ud83c\udffc\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc68\ud83c\udffd\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc68\ud83c\udffe\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc68\ud83c\udfff\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffb\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffb\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffc\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffc\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffd\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffd\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffe\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffe\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udfff\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udfff\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udffb\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83e\uddd1\ud83c[\udffc-\udfff]|\ud83e\uddd1\ud83c\udffc\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83e\uddd1\ud83c[\udffb\udffd-\udfff]|\ud83e\uddd1\ud83c\udffd\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83e\uddd1\ud83c[\udffb\udffc\udffe\udfff]|\ud83e\uddd1\ud83c\udffe\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83e\uddd1\ud83c[\udffb-\udffd\udfff]|\ud83e\uddd1\ud83c\udfff\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83e\uddd1\ud83c[\udffb-\udffe]|\ud83d\udc68\ud83c\udffb\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc68\ud83c\udffb\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffc-\udfff]|\ud83d\udc68\ud83c\udffc\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc68\ud83c\udffc\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb\udffd-\udfff]|\ud83d\udc68\ud83c\udffd\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc68\ud83c\udffd\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb\udffc\udffe\udfff]|\ud83d\udc68\ud83c\udffe\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc68\ud83c\udffe\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb-\udffd\udfff]|\ud83d\udc68\ud83c\udfff\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc68\ud83c\udfff\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb-\udffe]|\ud83d\udc69\ud83c\udffb\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffb\u200d\u2764\ufe0f\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffb\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffc-\udfff]|\ud83d\udc69\ud83c\udffb\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffc-\udfff]|\ud83d\udc69\ud83c\udffc\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffc\u200d\u2764\ufe0f\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffc\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb\udffd-\udfff]|\ud83d\udc69\ud83c\udffc\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffb\udffd-\udfff]|\ud83d\udc69\ud83c\udffd\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffd\u200d\u2764\ufe0f\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffd\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb\udffc\udffe\udfff]|\ud83d\udc69\ud83c\udffd\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffb\udffc\udffe\udfff]|\ud83d\udc69\ud83c\udffe\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffe\u200d\u2764\ufe0f\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffe\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb-\udffd\udfff]|\ud83d\udc69\ud83c\udffe\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffb-\udffd\udfff]|\ud83d\udc69\ud83c\udfff\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udfff\u200d\u2764\ufe0f\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udfff\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb-\udffe]|\ud83d\udc69\ud83c\udfff\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffb-\udffe]|\ud83e\uddd1\ud83c\udffb\u200d\u2764\ufe0f\u200d\ud83e\uddd1\ud83c[\udffc-\udfff]|\ud83e\uddd1\ud83c\udffb\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udffc\u200d\u2764\ufe0f\u200d\ud83e\uddd1\ud83c[\udffb\udffd-\udfff]|\ud83e\uddd1\ud83c\udffc\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udffd\u200d\u2764\ufe0f\u200d\ud83e\uddd1\ud83c[\udffb\udffc\udffe\udfff]|\ud83e\uddd1\ud83c\udffd\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udffe\u200d\u2764\ufe0f\u200d\ud83e\uddd1\ud83c[\udffb-\udffd\udfff]|\ud83e\uddd1\ud83c\udffe\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udfff\u200d\u2764\ufe0f\u200d\ud83e\uddd1\ud83c[\udffb-\udffe]|\ud83e\uddd1\ud83c\udfff\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83d\udc68\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68|\ud83d\udc69\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d[\udc68\udc69]|\ud83d\udc68\u200d\u2764\ufe0f\u200d\ud83d\udc68|\ud83d\udc69\u200d\u2764\ufe0f\u200d\ud83d[\udc68\udc69]|\ud83e\uddd1\u200d\ud83e\udd1d\u200d\ud83e\uddd1|\ud83d\udc6b\ud83c[\udffb-\udfff]|\ud83d\udc6c\ud83c[\udffb-\udfff]|\ud83d\udc6d\ud83c[\udffb-\udfff]|\ud83d\udc8f\ud83c[\udffb-\udfff]|\ud83d\udc91\ud83c[\udffb-\udfff]|\ud83d[\udc6b-\udc6d\udc8f\udc91])|(?:\ud83d[\udc68\udc69]|\ud83e\uddd1)(?:\ud83c[\udffb-\udfff])?\u200d(?:\u2695\ufe0f|\u2696\ufe0f|\u2708\ufe0f|\ud83c[\udf3e\udf73\udf7c\udf84\udf93\udfa4\udfa8\udfeb\udfed]|\ud83d[\udcbb\udcbc\udd27\udd2c\ude80\ude92]|\ud83e[\uddaf-\uddb3\uddbc\uddbd])|(?:\ud83c[\udfcb\udfcc]|\ud83d[\udd74\udd75]|\u26f9)((?:\ud83c[\udffb-\udfff]|\ufe0f)\u200d[\u2640\u2642]\ufe0f)|(?:\ud83c[\udfc3\udfc4\udfca]|\ud83d[\udc6e\udc70\udc71\udc73\udc77\udc81\udc82\udc86\udc87\ude45-\ude47\ude4b\ude4d\ude4e\udea3\udeb4-\udeb6]|\ud83e[\udd26\udd35\udd37-\udd39\udd3d\udd3e\uddb8\uddb9\uddcd-\uddcf\uddd4\uddd6-\udddd])(?:\ud83c[\udffb-\udfff])?\u200d[\u2640\u2642]\ufe0f|(?:\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc68\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d[\udc66\udc67]|\ud83c\udff3\ufe0f\u200d\u26a7\ufe0f|\ud83c\udff3\ufe0f\u200d\ud83c\udf08|\ud83d\ude36\u200d\ud83c\udf2b\ufe0f|\u2764\ufe0f\u200d\ud83d\udd25|\u2764\ufe0f\u200d\ud83e\ude79|\ud83c\udff4\u200d\u2620\ufe0f|\ud83d\udc15\u200d\ud83e\uddba|\ud83d\udc3b\u200d\u2744\ufe0f|\ud83d\udc41\u200d\ud83d\udde8|\ud83d\udc68\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\ud83d[\udc66\udc67]|\ud83d\udc6f\u200d\u2640\ufe0f|\ud83d\udc6f\u200d\u2642\ufe0f|\ud83d\ude2e\u200d\ud83d\udca8|\ud83d\ude35\u200d\ud83d\udcab|\ud83e\udd3c\u200d\u2640\ufe0f|\ud83e\udd3c\u200d\u2642\ufe0f|\ud83e\uddde\u200d\u2640\ufe0f|\ud83e\uddde\u200d\u2642\ufe0f|\ud83e\udddf\u200d\u2640\ufe0f|\ud83e\udddf\u200d\u2642\ufe0f|\ud83d\udc08\u200d\u2b1b)|[#*0-9]\ufe0f?\u20e3|(?:[©®\u2122\u265f]\ufe0f)|(?:\ud83c[\udc04\udd70\udd71\udd7e\udd7f\ude02\ude1a\ude2f\ude37\udf21\udf24-\udf2c\udf36\udf7d\udf96\udf97\udf99-\udf9b\udf9e\udf9f\udfcd\udfce\udfd4-\udfdf\udff3\udff5\udff7]|\ud83d[\udc3f\udc41\udcfd\udd49\udd4a\udd6f\udd70\udd73\udd76-\udd79\udd87\udd8a-\udd8d\udda5\udda8\uddb1\uddb2\uddbc\uddc2-\uddc4\uddd1-\uddd3\udddc-\uddde\udde1\udde3\udde8\uddef\uddf3\uddfa\udecb\udecd-\udecf\udee0-\udee5\udee9\udef0\udef3]|[\u203c\u2049\u2139\u2194-\u2199\u21a9\u21aa\u231a\u231b\u2328\u23cf\u23ed-\u23ef\u23f1\u23f2\u23f8-\u23fa\u24c2\u25aa\u25ab\u25b6\u25c0\u25fb-\u25fe\u2600-\u2604\u260e\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262a\u262e\u262f\u2638-\u263a\u2640\u2642\u2648-\u2653\u2660\u2663\u2665\u2666\u2668\u267b\u267f\u2692-\u2697\u2699\u269b\u269c\u26a0\u26a1\u26a7\u26aa\u26ab\u26b0\u26b1\u26bd\u26be\u26c4\u26c5\u26c8\u26cf\u26d1\u26d3\u26d4\u26e9\u26ea\u26f0-\u26f5\u26f8\u26fa\u26fd\u2702\u2708\u2709\u270f\u2712\u2714\u2716\u271d\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u2764\u27a1\u2934\u2935\u2b05-\u2b07\u2b1b\u2b1c\u2b50\u2b55\u3030\u303d\u3297\u3299])(?:\ufe0f|(?!\ufe0e))|(?:(?:\ud83c[\udfcb\udfcc]|\ud83d[\udd74\udd75\udd90]|[\u261d\u26f7\u26f9\u270c\u270d])(?:\ufe0f|(?!\ufe0e))|(?:\ud83c[\udf85\udfc2-\udfc4\udfc7\udfca]|\ud83d[\udc42\udc43\udc46-\udc50\udc66-\udc69\udc6e\udc70-\udc78\udc7c\udc81-\udc83\udc85-\udc87\udcaa\udd7a\udd95\udd96\ude45-\ude47\ude4b-\ude4f\udea3\udeb4-\udeb6\udec0\udecc]|\ud83e[\udd0c\udd0f\udd18-\udd1c\udd1e\udd1f\udd26\udd30-\udd39\udd3d\udd3e\udd77\uddb5\uddb6\uddb8\uddb9\uddbb\uddcd-\uddcf\uddd1-\udddd]|[\u270a\u270b]))(?:\ud83c[\udffb-\udfff])?|(?:\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc65\udb40\udc6e\udb40\udc67\udb40\udc7f|\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc73\udb40\udc63\udb40\udc74\udb40\udc7f|\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc77\udb40\udc6c\udb40\udc73\udb40\udc7f|\ud83c\udde6\ud83c[\udde8-\uddec\uddee\uddf1\uddf2\uddf4\uddf6-\uddfa\uddfc\uddfd\uddff]|\ud83c\udde7\ud83c[\udde6\udde7\udde9-\uddef\uddf1-\uddf4\uddf6-\uddf9\uddfb\uddfc\uddfe\uddff]|\ud83c\udde8\ud83c[\udde6\udde8\udde9\uddeb-\uddee\uddf0-\uddf5\uddf7\uddfa-\uddff]|\ud83c\udde9\ud83c[\uddea\uddec\uddef\uddf0\uddf2\uddf4\uddff]|\ud83c\uddea\ud83c[\udde6\udde8\uddea\uddec\udded\uddf7-\uddfa]|\ud83c\uddeb\ud83c[\uddee-\uddf0\uddf2\uddf4\uddf7]|\ud83c\uddec\ud83c[\udde6\udde7\udde9-\uddee\uddf1-\uddf3\uddf5-\uddfa\uddfc\uddfe]|\ud83c\udded\ud83c[\uddf0\uddf2\uddf3\uddf7\uddf9\uddfa]|\ud83c\uddee\ud83c[\udde8-\uddea\uddf1-\uddf4\uddf6-\uddf9]|\ud83c\uddef\ud83c[\uddea\uddf2\uddf4\uddf5]|\ud83c\uddf0\ud83c[\uddea\uddec-\uddee\uddf2\uddf3\uddf5\uddf7\uddfc\uddfe\uddff]|\ud83c\uddf1\ud83c[\udde6-\udde8\uddee\uddf0\uddf7-\uddfb\uddfe]|\ud83c\uddf2\ud83c[\udde6\udde8-\udded\uddf0-\uddff]|\ud83c\uddf3\ud83c[\udde6\udde8\uddea-\uddec\uddee\uddf1\uddf4\uddf5\uddf7\uddfa\uddff]|\ud83c\uddf4\ud83c\uddf2|\ud83c\uddf5\ud83c[\udde6\uddea-\udded\uddf0-\uddf3\uddf7-\uddf9\uddfc\uddfe]|\ud83c\uddf6\ud83c\udde6|\ud83c\uddf7\ud83c[\uddea\uddf4\uddf8\uddfa\uddfc]|\ud83c\uddf8\ud83c[\udde6-\uddea\uddec-\uddf4\uddf7-\uddf9\uddfb\uddfd-\uddff]|\ud83c\uddf9\ud83c[\udde6\udde8\udde9\uddeb-\udded\uddef-\uddf4\uddf7\uddf9\uddfb\uddfc\uddff]|\ud83c\uddfa\ud83c[\udde6\uddec\uddf2\uddf3\uddf8\uddfe\uddff]|\ud83c\uddfb\ud83c[\udde6\udde8\uddea\uddec\uddee\uddf3\uddfa]|\ud83c\uddfc\ud83c[\uddeb\uddf8]|\ud83c\uddfd\ud83c\uddf0|\ud83c\uddfe\ud83c[\uddea\uddf9]|\ud83c\uddff\ud83c[\udde6\uddf2\uddfc]|\ud83c[\udccf\udd8e\udd91-\udd9a\udde6-\uddff\ude01\ude32-\ude36\ude38-\ude3a\ude50\ude51\udf00-\udf20\udf2d-\udf35\udf37-\udf7c\udf7e-\udf84\udf86-\udf93\udfa0-\udfc1\udfc5\udfc6\udfc8\udfc9\udfcf-\udfd3\udfe0-\udff0\udff4\udff8-\udfff]|\ud83d[\udc00-\udc3e\udc40\udc44\udc45\udc51-\udc65\udc6a\udc6f\udc79-\udc7b\udc7d-\udc80\udc84\udc88-\udc8e\udc90\udc92-\udca9\udcab-\udcfc\udcff-\udd3d\udd4b-\udd4e\udd50-\udd67\udda4\uddfb-\ude44\ude48-\ude4a\ude80-\udea2\udea4-\udeb3\udeb7-\udebf\udec1-\udec5\uded0-\uded2\uded5-\uded7\udeeb\udeec\udef4-\udefc\udfe0-\udfeb]|\ud83e[\udd0d\udd0e\udd10-\udd17\udd1d\udd20-\udd25\udd27-\udd2f\udd3a\udd3c\udd3f-\udd45\udd47-\udd76\udd78\udd7a-\uddb4\uddb7\uddba\uddbc-\uddcb\uddd0\uddde-\uddff\ude70-\ude74\ude78-\ude7a\ude80-\ude86\ude90-\udea8\udeb0-\udeb6\udec0-\udec2\uded0-\uded6]|[\u23e9-\u23ec\u23f0\u23f3\u267e\u26ce\u2705\u2728\u274c\u274e\u2753-\u2755\u2795-\u2797\u27b0\u27bf\ue50a])|\ufe0f/g},1363:(e,t,n)=>{var r=n(5116),o=n(1226),d=n(3716),u=n(7361),a=n(8406),s=n(9524),i=n(7358),c=n(4688),l=n(1622);(0,r.Q6)("initApi",((e,t)=>{(async()=>{d.Cg||(await(0,c.Qw)(),(0,c.f3)()),(0,o.g8)(t.apiUpdate,{userAgent:navigator.userAgent,platform:u.Lt,sessionData:(0,c.K8)(),isTest:window.location.search.includes("test"),isMovSupported:u.pA})})()})),(0,r.Q6)("setAuthPhoneNumber",((e,t,n)=>{const{phoneNumber:r}=n;return(0,o.t9)("provideAuthPhoneNumber",r.replace(/[^\d]/g,"")),{...e,authIsLoading:!0,authError:void 0}})),(0,r.Q6)("setAuthCode",((e,t,n)=>{const{code:r}=n;return(0,o.t9)("provideAuthCode",r),{...e,authIsLoading:!0,authError:void 0}})),(0,r.Q6)("setAuthPassword",((e,t,n)=>{const{password:r}=n;return(0,o.t9)("provideAuthPassword",r),{...e,authIsLoading:!0,authError:void 0}})),(0,r.Q6)("uploadProfilePhoto",((e,t,n)=>{const{file:r}=n;(0,o.t9)("uploadProfilePhoto",r)})),(0,r.Q6)("signUp",((e,t,n)=>{const{firstName:r,lastName:d}=n;return(0,o.t9)("provideAuthRegistration",{firstName:r,lastName:d}),{...e,authIsLoading:!0,authError:void 0}})),(0,r.Q6)("returnToAuthPhoneNumber",(e=>((0,o.t9)("restartAuth"),{...e,authError:void 0}))),(0,r.Q6)("goToAuthQrCode",(e=>((0,o.t9)("restartAuthWithQr"),{...e,authIsLoadingQrCode:!0,authError:void 0}))),(0,r.Q6)("saveSession",((e,t,n)=>{const{sessionData:r}=n;r?(0,c.wX)(n.sessionData,e.currentUserId):(0,c.jv)()})),(0,r.Q6)("signOut",(()=>{(async()=>{try{await(0,a.r1)(),await(0,o.t9)("destroy"),await(0,l.I)(!1)}catch(e){}(0,r.uC)().reset()})()})),(0,r.Q6)("reset",(()=>{(0,c.jv)(),s.clear(d.lW),s.clear(d.SG),s.clear(d.lF),s.clear(d.fo);const e=d.ee.replace(/\d+$/,""),t=(d.ee.match(/\d+$/)||[0])[0];for(let n=0;n{(async()=>{await(0,o.t9)("disconnect")})()})),(0,r.Q6)("loadNearestCountry",(e=>{"connectionStateReady"===e.connectionState&&(async()=>{const e=await(0,o.t9)("fetchNearestCountry");(0,r.R3)({...(0,r.Rd)(),authNearestCountry:e})})()})),(0,r.Q6)("setDeviceToken",((e,t,n)=>{(0,r.R3)({...e,push:{deviceToken:n,subscribedAt:Date.now()}})})),(0,r.Q6)("deleteDeviceToken",(e=>{const t={...e};delete t.push,(0,r.R3)(t)}))},9667:(e,t,n)=>{var r=n(5116),o=n(1713),d=n(3716),u=n(1226),a=n(782),s=n(8406),i=n(663),c=n(8085),l=n(1752),f=n(2858);function h(e,{visibility:t,allowedIds:n,deniedIds:r}){const{users:{byId:o},chats:{byId:d}}=e,u={visibility:t};let a,s;const i=e=>{if(!(0,f.YC)(e))return;const{id:t,accessHash:n}=o[e]||{};return t?{id:t,accessHash:n}:void 0},c=e=>{if((0,f.YC)(e))return;const t=d[e];return t?{id:t.id}:void 0};return"contacts"!==t&&"nobody"!==t||(a=n.map(i).filter(Boolean),s=n.map(c).filter(Boolean),a.length>0&&(u.allowedUsers=a),s.length>0&&(u.allowedChats=s)),"everybody"!==t&&"contacts"!==t||(a=r.map(i).filter(Boolean),s=r.map(c).filter(Boolean),a.length>0&&(u.blockedUsers=a),s.length>0&&(u.blockedChats=s)),u}(0,r.Q6)("updateProfile",((e,t,n)=>{const{photo:d,firstName:a,lastName:s,bio:i,username:f}=n;(async()=>{const{currentUserId:t}=e;if(t){if((0,r.R3)({...(0,r.Rd)(),profileEdit:{progress:o.rN.InProgress}}),d&&await(0,u.t9)("updateProfilePhoto",d),(a||s||i)&&await(0,u.t9)("updateProfile",{firstName:a,lastName:s,about:i})){e=(0,r.Rd)();const n=t&&(0,c.dy)(e,t);n&&(0,r.R3)((0,l.Nq)(e,n.id,{firstName:a,lastName:s,fullInfo:{...n.fullInfo,bio:i}}))}f&&await(0,u.t9)("updateUsername",f)&&t&&(0,r.R3)((0,l.Nq)((0,r.Rd)(),t,{username:f})),(0,r.R3)({...(0,r.Rd)(),profileEdit:{progress:o.rN.Complete}})}})()})),(0,r.Q6)("checkUsername",((e,t,n)=>{const{username:d}=n;(async()=>{if(e.profileEdit&&e.profileEdit.progress===o.rN.InProgress)return;(0,r.R3)({...e,profileEdit:{progress:e.profileEdit?e.profileEdit.progress:o.rN.Idle,isUsernameAvailable:void 0}});const t=await(0,u.t9)("checkUsername",d);e=(0,r.Rd)(),(0,r.R3)({...e,profileEdit:{...e.profileEdit,isUsernameAvailable:t}})})()})),(0,r.Q6)("loadWallpapers",(()=>{(async()=>{const e=await(0,u.t9)("fetchWallpapers");if(!e)return;const t=(0,r.Rd)();(0,r.R3)({...t,settings:{...t.settings,loadedWallpapers:e.wallpapers}})})()})),(0,r.Q6)("uploadWallpaper",((e,t,n)=>{const d=n,a=URL.createObjectURL(d);(0,r.R3)({...e,settings:{...e.settings,loadedWallpapers:[{slug:o.mp,document:{fileName:"",size:d.size,mimeType:d.type,previewBlobUrl:a}},...e.settings.loadedWallpapers||[]]}}),(async()=>{const t=await(0,u.t9)("uploadWallpaper",d);if(!t)return;const{wallpaper:n}=t;if(!(e=(0,r.Rd)()).settings.loadedWallpapers)return;const s=e.settings.loadedWallpapers[0];if(!s||s.slug!==o.mp)return;const i={...n,document:{...n.document,previewBlobUrl:a}};(0,r.R3)({...e,settings:{...e.settings,loadedWallpapers:[i,...e.settings.loadedWallpapers.slice(1)]}})})()})),(0,r.Q6)("loadBlockedContacts",(()=>{(async()=>{var e,t;const n=await(0,u.t9)("fetchBlockedContacts");if(!n)return;let o=(0,r.Rd)();null!==(e=n.users)&&void 0!==e&&e.length&&(o=(0,l.Sh)(o,(0,a.ee)(n.users,"id"))),null!==(t=n.chats)&&void 0!==t&&t.length&&(o=(0,l.GL)(o,(0,a.ee)(n.chats,"id"))),o={...o,blocked:{...o.blocked,ids:[...o.blocked.ids||[],...n.blockedIds],totalCount:n.totalCount}},(0,r.R3)(o)})()})),(0,r.Q6)("blockContact",((e,t,n)=>{const{contactId:o,accessHash:d}=n;(async()=>{if(!await(0,u.t9)("blockContact",o,d))return;const e=(0,r.Rd)();(0,r.R3)((0,l.O4)(e,o))})()})),(0,r.Q6)("unblockContact",((e,t,n)=>{const{contactId:o}=n;let d;if((0,f.YC)(o)){const t=(0,c.dy)(e,o);if(!t)return;d=t.accessHash}(async()=>{if(!await(0,u.t9)("unblockContact",o,d))return;const e=(0,r.Rd)();(0,r.R3)((0,l.rB)(e,o))})()})),(0,r.Q6)("loadAuthorizations",(()=>{(async()=>{const e=await(0,u.t9)("fetchAuthorizations");e&&(0,r.R3)({...(0,r.Rd)(),activeSessions:e})})()})),(0,r.Q6)("terminateAuthorization",((e,t,n)=>{const{hash:o}=n;(async()=>{if(!await(0,u.t9)("terminateAuthorization",o))return;const e=(0,r.Rd)();(0,r.R3)({...e,activeSessions:e.activeSessions.filter((e=>e.hash!==o))})})()})),(0,r.Q6)("terminateAllAuthorizations",(()=>{(async()=>{if(!await(0,u.t9)("terminateAllAuthorizations"))return;const e=(0,r.Rd)();(0,r.R3)({...e,activeSessions:e.activeSessions.filter((e=>e.isCurrent))})})()})),(0,r.Q6)("loadNotificationExceptions",(e=>{const{serverTimeOffset:t}=e;(async()=>{const e=await(0,u.t9)("fetchNotificationExceptions",{serverTimeOffset:t});e&&(0,r.R3)((0,l.aJ)((0,r.Rd)(),e))})()})),(0,r.Q6)("loadNotificationSettings",(e=>{const{serverTimeOffset:t}=e;(async()=>{const e=await(0,u.t9)("fetchNotificationSettings",{serverTimeOffset:t});e&&(0,r.R3)((0,l.BI)((0,r.Rd)(),e))})()})),(0,r.Q6)("updateNotificationSettings",((e,t,n)=>{const{peerType:o,isSilent:d,shouldShowPreviews:a}=n;(async()=>{await(0,u.t9)("updateNotificationSettings",o,{isSilent:d,shouldShowPreviews:a})&&(0,r.R3)((0,l.HN)((0,r.Rd)(),o,d,a))})()})),(0,r.Q6)("updateWebNotificationSettings",((e,t,n)=>{(async()=>{(0,r.R3)((0,l.BI)((0,r.Rd)(),n));const e=(0,r.Rd)(),{hasPushNotifications:t,hasWebNotifications:o}=e.settings.byKey;o&&t?await(0,s.Ld)():await(0,s.r1)()})()})),(0,r.Q6)("updateContactSignUpNotification",((e,t,n)=>{const{isSilent:o}=n;(async()=>{await(0,u.t9)("updateContactSignUpNotification",o)&&(0,r.R3)((0,l.BI)((0,r.Rd)(),{hasContactJoinedNotifications:!o}))})()})),(0,r.Q6)("loadLanguages",(()=>{(async()=>{const e=await(0,u.t9)("fetchLanguages");e&&(0,r.R3)((0,l.BI)((0,r.Rd)(),{languages:e}))})()})),(0,r.Q6)("loadPrivacySettings",(()=>{(async()=>{const[e,t,n,o,d]=await Promise.all([(0,u.t9)("fetchPrivacySettings","phoneNumber"),(0,u.t9)("fetchPrivacySettings","lastSeen"),(0,u.t9)("fetchPrivacySettings","profilePhoto"),(0,u.t9)("fetchPrivacySettings","forwards"),(0,u.t9)("fetchPrivacySettings","chatInvite")]);if(!(e&&t&&n&&o&&d))return;const a=(0,r.Rd)();a.settings.privacy.phoneNumber=e,a.settings.privacy.lastSeen=t,a.settings.privacy.profilePhoto=n,a.settings.privacy.forwards=o,a.settings.privacy.chatInvite=d,(0,r.R3)(a)})()})),(0,r.Q6)("setPrivacyVisibility",((e,t,n)=>{const{privacyKey:o,visibility:d}=n,{privacy:{[o]:a}}=e.settings;if(!a)return;const s=h(e,{visibility:d,allowedIds:[...a.allowUserIds,...a.allowChatIds],deniedIds:[...a.blockUserIds,...a.blockChatIds]});(async()=>{const e=await(0,u.t9)("setPrivacySettings",o,s);if(e){const t=(0,r.Rd)();t.settings.privacy[o]=e,(0,r.R3)(t)}})()})),(0,r.Q6)("setPrivacySettings",((e,t,n)=>{const{privacyKey:o,isAllowList:d,contactsIds:a}=n,{privacy:{[o]:s}}=e.settings;if(!s)return;const i=h(e,{visibility:s.visibility,allowedIds:d?a:[...s.allowUserIds,...s.allowChatIds],deniedIds:d?[...s.blockUserIds,...s.blockChatIds]:a});(async()=>{const e=await(0,u.t9)("setPrivacySettings",o,i);if(e){const t=(0,r.Rd)();t.settings.privacy[o]=e,(0,r.R3)(t)}})()})),(0,r.Q6)("updateIsOnline",((e,t,n)=>{(0,u.t9)("updateIsOnline",n)})),(0,r.Q6)("loadContentSettings",(()=>{(async()=>{const e=await(0,u.t9)("fetchContentSettings");e&&(0,r.R3)((0,l.BI)((0,r.Rd)(),e))})()})),(0,r.Q6)("updateContentSettings",((e,t,n)=>{(async()=>{(0,r.R3)((0,l.BI)((0,r.Rd)(),{isSensitiveEnabled:n})),await(0,u.t9)("updateContentSettings",n)||(0,r.R3)((0,l.BI)((0,r.Rd)(),{isSensitiveEnabled:!n}))})()})),(0,r.Q6)("loadCountryList",((e,t,n={})=>{let{langCode:o}=n;o||(o=e.settings.byKey.language),(async()=>{const e=await(0,u.t9)("fetchCountryList",{langCode:o});e&&(0,r.R3)({...(0,r.Rd)(),countryList:e})})()})),(0,r.Q6)("ensureTimeFormat",((e,t)=>{if(e.authNearestCountry){const n=d.FD.has(e.authNearestCountry.toUpperCase())?"12h":"24h";t.setSettingOption({timeFormat:n}),(0,i.qf)(n)}(async()=>{if((0,r.Rd)().settings.byKey.wasTimeFormatSetManually)return;const e=await(0,u.t9)("fetchNearestCountry");if(e){const n=d.FD.has(e.toUpperCase())?"12h":"24h";t.setSettingOption({timeFormat:n}),(0,i.qf)(n)}})()}))},4907:(e,t,n)=>{var r=n(5116),o=n(3716),d=n(8406),u=n(1752),a=n(663),s=n(8085),i=n(1622),c=n(1947);(0,r.Q6)("apiUpdate",((e,t,n)=>{switch(o.eM&&"updateUserStatus"!==n["@type"]&&"updateServerTimeOffset"!==n["@type"]&&console.log("[GramJs] UPDATE",n["@type"],{update:n}),n["@type"]){case"updateApiReady":!function(e){const{hasWebNotifications:t,hasPushNotifications:n}=(0,s.dZ)(e);t&&n&&(0,d.Ld)(),(0,a.m0)(e.settings.byKey.language)}(e);break;case"updateAuthorizationState":!function(e){let t=(0,r.Rd)();const n="authorizationStateReady"===t.authState,o=e.authorizationState;switch((0,r.R3)({...t,authState:o,authIsLoading:!1}),t=(0,r.Rd)(),o){case"authorizationStateLoggingOut":(0,i.I)(!1),(0,r.R3)({...t,isLoggingOut:!0});break;case"authorizationStateWaitCode":(0,r.R3)({...t,authIsCodeViaApp:e.isCodeViaApp});break;case"authorizationStateWaitPassword":(0,r.R3)({...t,authHint:e.hint});break;case"authorizationStateWaitQrCode":(0,r.R3)({...t,authIsLoadingQrCode:!1,authQrCode:e.qrCode});break;case"authorizationStateReady":if(n)break;(0,i.I)(!0),(0,r.R3)({...t,isLoggingOut:!1,lastSyncTime:Date.now()})}}(n);break;case"updateAuthorizationError":!function(e){(0,r.R3)({...(0,r.Rd)(),authError:e.message})}(n);break;case"updateConnectionState":!function(e){const{connectionState:t}=e,n=(0,r.Rd)();(0,r.R3)({...n,connectionState:t}),"connectionStateReady"===t&&"authorizationStateReady"===n.authState?(0,r.uC)().sync():"connectionStateBroken"===t&&(0,r.uC)().signOut()}(n);break;case"updateSession":!function(e){const{sessionData:t}=e,{authRememberMe:n,authState:o}=(0,r.Rd)(),d=!t||!t.mainDcId;n&&"authorizationStateReady"===o&&!d&&(0,r.uC)().saveSession({sessionData:t})}(n);break;case"updateServerTimeOffset":!function(e){const t=(0,r.Rd)();t.serverTimeOffset!==e.serverTimeOffset&&(0,r.R3)({...t,serverTimeOffset:e.serverTimeOffset})}(n);break;case"updateCurrentUser":!function(e){const{currentUser:t}=e;(0,r.R3)({...(0,u.Nq)((0,r.Rd)(),t.id,t),currentUserId:t.id}),function(e){const t=localStorage.getItem(o.b_);if(!t)return;const n=JSON.parse(t);n.id=e,localStorage.setItem(o.b_,JSON.stringify(n))}(t.id)}(n);break;case"error":{"SESSION_REVOKED"===n.error.message&&t.signOut();const e=(0,c.J_)(n.error);e?t.addPaymentError({error:e}):t.showDialog&&t.showDialog({data:{...n.error,hasErrorKey:!0}});break}}}))},7895:(e,t,n)=>{var r=n(5116),o=n(3716),d=n(7361),u=n(663),a=n(6917),s=n(8085),i=n(1622);!function(){function e(){const e=document.documentElement.className.match(/theme-(\w+)/),t=e?e[1]:"light",n=(0,r.Rd)(),d=(0,s.Pu)(n),{animationLevel:u}=n.settings.byKey;d!==t&&((0,a.Z)(d,u===o.zy),(0,r.R3)({...n}))}const t=window.matchMedia("(prefers-color-scheme: dark)");"function"==typeof t.addEventListener?t.addEventListener("change",e):"function"==typeof t.addListener&&t.addListener(e)}(),(0,r.Q6)("init",(e=>{const{animationLevel:t,messageTextSize:n,language:r}=e.settings.byKey,c=(0,s.Pu)(e);(0,u.m0)(r,void 0,!0),document.documentElement.style.setProperty("--composer-text-size",`${Math.max(n,d.cj?16:15)}px`),document.documentElement.style.setProperty("--message-meta-height",`${Math.floor(1.3125*n)}px`),document.documentElement.style.setProperty("--message-text-size",`${n}px`),document.documentElement.setAttribute("data-message-text-size",n.toString()),document.body.classList.add("initial"),document.body.classList.add(`animation-level-${t}`),document.body.classList.add(d.$b?"is-touch-env":"is-pointer-env"),(0,a.Z)(c,t===o.zy),(0,i.p)(),d.cj?document.body.classList.add("is-ios"):d.wZ?document.body.classList.add("is-android"):d.jm&&document.body.classList.add("is-macos")})),(0,r.Q6)("setIsUiReady",((e,t,n)=>{const{uiReadyState:r}=n;return 2===r&&document.body.classList.remove("initial"),{...e,uiReadyState:r}})),(0,r.Q6)("setAuthPhoneNumber",((e,t,n)=>{const{phoneNumber:r}=n;return{...e,authPhoneNumber:r}})),(0,r.Q6)("setAuthRememberMe",((e,t,n)=>({...e,authRememberMe:Boolean(n)}))),(0,r.Q6)("clearAuthError",(e=>({...e,authError:void 0}))),(0,r.Q6)("disableHistoryAnimations",(()=>{setTimeout((()=>{(0,r.R3)({...(0,r.Rd)(),shouldSkipHistoryAnimations:!1}),document.body.classList.remove("no-animate")}),450),(0,r.R3)({...(0,r.Rd)(),shouldSkipHistoryAnimations:!0},!0)}))},3781:(e,t,n)=>{var r=n(5116),o=n(1752);(0,r.Q6)("setSettingOption",((e,t,n)=>(0,o.BI)(e,n))),(0,r.Q6)("setThemeSettings",((e,t,n)=>{const{theme:r,...d}=n;return(0,o.lr)(e,r,d)}))},8332:(e,t,n)=>{n.d(t,{YC:()=>i,Bf:()=>c,G9:()=>l,ZV:()=>f,eA:()=>h,Ru:()=>m,pK:()=>p,l6:()=>g,zX:()=>y,U:()=>v,GM:()=>b,hu:()=>w,RT:()=>I,Hp:()=>C,Nl:()=>S,VE:()=>E,Mg:()=>P,Qm:()=>M,H5:()=>A,q8:()=>k,Hd:()=>T,OE:()=>N,pE:()=>L,i4:()=>R,Sm:()=>D,cc:()=>O,P4:()=>x,O:()=>_,Fu:()=>Z,SB:()=>F,zF:()=>B,ih:()=>$});var r=n(6137),o=n(3716),d=n(782),u=n(5527),a=n(790);const s=Date.now()/1e3+31622400;function i(e){return"number"==typeof e?e>0:!e.startsWith("-")}function c(e){return l(e)||f(e)}function l(e){return"chatTypeBasicGroup"===e.type}function f(e){return"chatTypeSuperGroup"===e.type}function h(e){return"chatTypeChannel"===e.type}function m(e){return"chatTypePrivate"===e.type||"chatTypeBasicGroup"===e.type}function p(e){return e===o.FV}function g(e){switch(e.type){case"chatTypePrivate":return"PrivateChat";case"chatTypeBasicGroup":case"chatTypeSuperGroup":return"AccDescrGroup";case"chatTypeChannel":return"AccDescrChannel";default:return"Chat"}}function y(e){if("chatTypePrivate"===e.type||"chatTypeSecret"===e.type)return e.id}function v(e,t,n,r=!1){return r||n&&t.id===n.id&&n.isSelf?e("SavedMessages"):t.title||e("HiddenName")}function b(e){if(e.fullInfo)return e.fullInfo.about}function w(e){const{username:t}=e;if(t)return`https://t.me/${t}`;const{inviteLink:n}=e.fullInfo||{};return n}function I(e,t="normal"){if(e.avatarHash)switch(t){case"big":return`profile${e.id}?${e.avatarHash}`;default:return`avatar${e.id}?${e.avatarHash}`}}function C(e){return!e.lastMessage}function S(e){return Boolean(e.adminRights)}function E(e,t){return!!e.adminRights&&e.adminRights[t]}function P(e,t){var n,r;return Boolean((null===(n=e.currentUserBannedRights)||void 0===n?void 0:n[t])||(null===(r=e.defaultBannedRights)||void 0===r?void 0:r[t]))}function M(e,t){return t!==r._f||!(e.isRestricted||e.migratedTo||e.isNotJoined||p(e.id))&&(!!e.isCreator||!!i(e.id)||(h(e)?E(e,"postMessages"):S(e)||!P(e,"sendMessages")))}function A(e,t=!1){if(!e)return{canAttachMedia:!1,canAttachPolls:!1,canSendStickers:!1,canSendGifs:!1,canAttachEmbedLinks:!1};const n=S(e);return{canAttachMedia:n||!P(e,"sendMedia"),canAttachPolls:(n||!P(e,"sendPolls"))&&(!i(e.id)||t),canSendStickers:n||!P(e,"sendStickers"),canSendGifs:n||!P(e,"sendGifs"),canAttachEmbedLinks:n||!P(e,"embedLinks")}}function k(e,t,n){if(null!=t&&t.sendMessages){const{untilDate:n}=t;return n&&nfunction(e,t,n,r,o,d,u,a){if(!e.isListed)return!1;if(d&&d.has(e.id))return!1;if(u&&u.has(e.id))return!0;if(a&&a.has(e.id))return!0;if(L(e)&&t.excludeArchived)return!1;if(t.excludeMuted&&!e.unreadMentionsCount&&R(e,r,o))return!1;if(!e.unreadCount&&!e.unreadMentionsCount&&!e.hasUnreadMark&&t.excludeRead)return!1;if(i(e.id)){const r=n[e.id];if(r&&"userTypeBot"===r.type){if(t.bots)return!0}else{if(t.contacts&&r&&r.isContact)return!0;if(t.nonContacts&&r&&!r.isContact)return!0}}else{if(c(e))return!!t.groups;if(h(e))return!!t.channels}return!1}(e[d],n,t,r,o,u,a,s))),n.pinnedChatIds]}function _(e,t,n,r="all"){function o(e){if(!e||!e.lastMessage||e.migratedTo)return!1;switch(r){case"all":if(L(e))return!1;break;case"archived":if(!L(e))return!1}return!e.isRestricted&&!e.isNotJoined}const u=t.map((t=>e[t])).filter(o),a=new Set(t);return{pinnedChats:n?n.map((t=>e[t])).filter(o).filter((e=>a.has(e.id))):[],otherChats:(0,d.Xo)(n?u.filter((e=>!n.includes(e.id))):u,N,"desc")}}function Z(e,t,n,r,o,d){const[u]=x(e,t,n,o,d,r),a=u.map((t=>e[t])).filter((e=>(null==e?void 0:e.lastMessage)&&!e.isRestricted&&!e.isNotJoined));return{unreadDialogsCount:a.reduce(((e,t)=>t.unreadCount||t.hasUnreadMark?e+1:e),0),hasActiveDialogs:a.some((e=>e.unreadMentionsCount||!R(e,o,d)&&(e.unreadCount||e.hasUnreadMark)))}}function F(e,t,n,r,o,d,u){const{id:a,title:s,emoticon:i,description:c,pinnedChatIds:l,excludedChatIds:f,includedChatIds:h,excludeArchived:m,excludeMuted:p,excludeRead:g,...y}=r;return Object.values(y).filter(Boolean).length>1||null!=f&&f.length||null!=h&&h.length?e("Chats",function(e,t,n,r,o,d){const[u,a]=x(e,t,n,o,d,r),{pinnedChats:s,otherChats:i}=_(e,u,a,"folder");return s.length+i.length}(t,n,r,o,d,u)):y.bots?e("FilterBots"):y.groups?e("FilterGroups"):y.channels?e("FilterChannels"):y.contacts?e("FilterContacts"):y.nonContacts?e("FilterNonContacts"):void 0}function B(e,t,n){if(n&&!i(t))return n.isSelf?e("FromYou"):(0,u.Vl)(n)}function $(e,t,n=!1,r){return(0,d.Xo)(e,(e=>{const o=t[e];if(!o)return 0;let d=0;return o.lastMessage&&(d+=o.lastMessage.date),n&&o.isVerified&&(d+=3e9),r&&r.includes(e)&&(d=Date.now()+3e8+(r.length-r.indexOf(e))),d}),"desc")}},2858:(e,t,n)=>{n.d(t,{uw:()=>ie,H5:()=>o.H5,MR:()=>q,kw:()=>r.kw,cc:()=>o.cc,Qm:()=>o.Qm,RT:()=>o.RT,GM:()=>o.GM,hu:()=>o.hu,N0:()=>ne,OE:()=>o.OE,Hd:()=>o.Hd,U:()=>o.U,l6:()=>o.l6,T7:()=>v,SB:()=>o.SB,Fu:()=>o.Fu,VE:()=>o.VE,XV:()=>se,Sc:()=>ue,N5:()=>_,oP:()=>Z,qp:()=>L,w6:()=>T,R5:()=>ae,$D:()=>g,aE:()=>$,ep:()=>X,c0:()=>ee,eO:()=>V,Tp:()=>l,kG:()=>Y,Ti:()=>K,DH:()=>Q,KK:()=>h,O$:()=>D,t9:()=>W,Y5:()=>x,zF:()=>o.zF,q8:()=>o.q8,_O:()=>y,bf:()=>B,MK:()=>m,UD:()=>p,b7:()=>O,kd:()=>F,s1:()=>G,F$:()=>H,Cg:()=>z,bV:()=>re,HV:()=>oe,zX:()=>o.zX,OU:()=>P,RI:()=>M,Ow:()=>le,Rs:()=>r.Rs,Vl:()=>r.Vl,Js:()=>r.Js,db:()=>r.db,Tq:()=>r.Tq,jC:()=>de,BM:()=>te,u8:()=>R,Lo:()=>C,Ul:()=>E,Nl:()=>o.Nl,pE:()=>o.pE,G9:()=>o.G9,eA:()=>o.eA,Bf:()=>o.Bf,Hp:()=>o.Hp,ZV:()=>o.ZV,pK:()=>o.pK,Ru:()=>o.Ru,NB:()=>r.NB,MF:()=>I,CD:()=>k,rl:()=>U,hC:()=>j,CI:()=>A,B4:()=>b,ss:()=>w,jM:()=>S,cS:()=>r.cS,YC:()=>o.YC,kM:()=>r.kM,Mg:()=>o.Mg,Ak:()=>f,O:()=>o.O,P4:()=>o.P4,i4:()=>o.i4,Sm:()=>o.Sm,ih:()=>o.ih,Z0:()=>r.Z0});var r=n(5527),o=n(8332),d=n(6137),u=n(3716),a=n(7361),s=n(4784);const i="The message is not supported on this version of Telegram",c=new RegExp(u.FM,"i");function l(e){const{chatId:t,id:n}=e;return function(e,t){return`msg${e}-${t}`}(t,n)}function f(e){const t=e.match(/^msg(-?\d+)-(\d+)/);return{chatId:t[1],messageId:Number(t[2])}}function h(e){return e.previousLocalId||e.id}function m(e,t,n=!1){const{text:r,photo:o,video:d,audio:u,voice:a,document:s,sticker:c,contact:l,poll:f,invoice:h}=t.content,m=r&&r.text.substr(0,80);return t.groupedId?`${n?"":"🖼 "}${m||e("lng_in_dlg_album")}`:o?`${n?"":"🖼 "}${m||e("AttachPhoto")}`:d?`${n?"":"📹 "}${m||e(d.isGif?"AttachGif":"AttachVideo")}`:c?`${c.emoji||""} ${e("AttachSticker")}`.trim():u?`${n?"":"🎧 "}${function(e){const{audio:t,text:n}=e.content;return t&&[t.title,t.performer].filter(Boolean).join(" — ")||(null==n?void 0:n.text)}(t)||e("AttachMusic")}`:a?`${n?"":"🎤 "}${m||e("AttachAudio")}`:s?`${n?"":"📎 "}${m||s.fileName}`:l?e("AttachContact"):f?`${n?"":"📊 "}${f.summary.question}`:h?"Invoice":r?m:i}function p(e){const{text:t,sticker:n,photo:r,video:o,audio:d,voice:u,document:a,poll:s,webPage:c,contact:l,invoice:f}=e.content;return t?t.text:n||r||o||d||u||a||l||s||c||f?void 0:i}function g(e){const{text:t,sticker:n,photo:r,video:o,audio:d,voice:u,document:a,poll:i,webPage:c,contact:l}=e.content;return!!(n||null!=o&&o.isRound)||!(!t||r||o||d||u||a||i||c||l)&&((0,s.Z)(t.text)||!1)}function y(e){const{text:t}=e.content;if(t&&t.text.length<=6&&1===g(e))return t.text}function v(e){const{text:t}=e.content;let n;if(null!=t&&t.entities){let e=t.entities.find((e=>e.type===d.Vv.TextUrl));if(e&&(n=e.url.match(c)),!n&&(e=t.entities.find((e=>e.type===d.Vv.Url)),e)){const{offset:r,length:o}=e;n=t.text.substring(r,r+o).match(c)}}if(!n&&t&&(n=t.text.match(c)),n)return{url:n[0],domain:n[3]}}function b(e){return e.isOutgoing}function w(e){return Boolean(e.replyToMessageId)}function I(e){return Boolean(e.forwardInfo)}function C(e){return!!e.content.action}function S(e){return e.chatId===u.aw&&Math.round(e.id)!==e.id}function E(e){return Boolean(e.senderId)&&!(0,o.YC)(e.senderId)&&b(e)}function P(e,t){return(0,o.YC)(t.id)?(0,r.Js)(t):(0,o.U)(e,t)}function M(e){return e.sendingState?"messageSendingStateFailed"===e.sendingState?"failed":"pending":"succeeded"}function A(e){return e.id>=u.AE}function k(e){return e.content.action&&"historyClear"===e.content.action.type}function T(e){const{content:t}=e,n=t.webPage?t.webPage.video:t.video,r=t.webPage?t.webPage.photo:t.photo,o=t.webPage?t.webPage.document:t.document;if(o)return o.fileName;if(n)return n.fileName;if(t.sticker){const e=t.sticker.isAnimated?"tgs":(0,a.on)()?"webp":"png";return`${t.sticker.id}.${e}`}if(t.audio)return t.audio.fileName;const d=l(e);return r?`${d}.jpg`:t.voice?a.m5?`${d}.ogg`:`${d}.wav`:d}var N=n(5376);function L(e){return e.content}function R(e){return Boolean(D(e)||O(e)||$(e)||B(e)||function(e){return e.content.contact}(e)||W(e)||_(e)||Z(e)||F(e))}function D(e){return e.content.photo}function O(e){return e.content.video}function x(e){const{video:t}=e.content;return null!=t&&t.isRound?t:void 0}function _(e){return e.content.action}function Z(e){return e.content.audio}function F(e){return e.content.voice}function B(e){return e.content.sticker}function $(e){return e.content.document}function U(e){const t=$(e);return t?"photo"===t.mediaType:void 0}function j(e){const t=$(e);return t?"video"===t.mediaType:void 0}function W(e){return e.content.poll}function V(e){return e.content.invoice}function G(e){return e.content.webPage}function H(e){var t;return null===(t=G(e))||void 0===t?void 0:t.photo}function z(e){var t;return null===(t=G(e))||void 0===t?void 0:t.video}function Q(e){var t;return null===(t=function(e){const t=D(e)||O(e)||$(e)||B(e)||H(e)||z(e);if(t)return t.thumbnail}(e))||void 0===t?void 0:t.dataUri}function K(e,t){const{photo:n,video:r,sticker:o,audio:d,voice:u,document:a}=e.content,s=H(e),i=z(e),c=r||i,f=n||s;if(!(f||c||o||d||u||a))return;const h=l(e);if(c)switch(t){case"micro":case"pictogram":return`${h}?size=m`;case"inline":return te(e)?void 0:J(c,h);case"viewerPreview":return`${h}?size=m`;case"viewerFull":return J(c,h);case"download":return`${h}?download`}if(f)switch(t){case"micro":case"pictogram":return`${h}?size=m`;case"inline":return te(e)?void 0:`${h}?size=x`;case"viewerPreview":return`${h}?size=x`;case"viewerFull":case"download":return`${h}?size=z`}if(a)switch(t){case"micro":case"pictogram":case"inline":case"viewerPreview":if(!(0,N.v6)(a)||te(e))return;return`${h}?size=m`;case"viewerFull":case"download":return h}if(o)switch(t){case"micro":return;case"pictogram":return`${h}?size=m`;case"inline":return h;case"download":return`${h}?download`}if(d)switch(t){case"micro":case"pictogram":return q(d)?`${h}?size=m`:void 0;case"inline":return J(d,h);case"download":return`${h}?download`}if(u)switch(t){case"micro":case"pictogram":return;case"inline":return h;case"download":return`${h}?download`}}function J(e,t){return a.I_&&a.s$?`${t}?fileSize=${e.size}&mimeType=${e.mimeType}`:t}function q(e){return e.thumbnailSizes&&e.thumbnailSizes.length>0}function Y(e,t){const{sticker:n,video:r,audio:o,voice:u}=e.content,s=r||z(e);return n&&"inline"===t&&n.isAnimated?d.IU.Lottie:s&&a.I_&&("viewerFull"===t||"inline"===t)?d.IU.Progressive:o||u?u&&!a.m5?d.IU.BlobUrl:d.IU.Progressive:d.IU.BlobUrl}function X(e){const{photo:t,video:n,document:r}=e.content,o=H(e),d=z(e);if(t||o)return`photo${e.date}.jpeg`;const{fileName:u}=n||d||r||{};return u}function ee(e){const{video:t,document:n}=e.content,r=z(e),{size:o}=t||r||n||{};return o}function te(e){const{photo:t,video:n,document:r}=e.content;return(null==t?void 0:t.blobUrl)||(null==n?void 0:n.blobUrl)||(null==r?void 0:r.previewBlobUrl)}function ne(e,t,n=!1){const r=ae(e,t,n?"media":"inlineMedia");return n?r.reverse():r}function re(e){return e.sizes.find((e=>"z"===e.type))||e.sizes.find((e=>"y"===e.type))||oe(e)}function oe(e){return e.sizes.find((e=>"x"===e.type))||e.sizes.find((e=>"m"===e.type))||e.sizes.find((e=>"s"===e.type))||e.thumbnail}function de(e){if(e.width&&e.height)return e}function ue(e,t,n=!1){const r=A(e);return{isUploading:r,isTransferring:r||n,transferProgress:Number(t)}}function ae(e,t,n){let r;switch(n){case"media":r=e=>{const t=O(e);return D(e)||t&&!t.isRound&&!t.isGif};break;case"documents":r=$;break;case"links":r=e=>G(e)||function(e){const{text:t}=e.content,n=t&&t.text.match(c);if(n)return{url:n[0],domain:n[3]}}(e);break;case"audio":r=Z;break;case"voice":r=e=>{const t=O(e);return F(e)||t&&t.isRound};break;case"inlineMedia":r=e=>{const t=O(e);return D(e)||t&&!t.isRound&&!t.isGif||U(e)||j(e)};break;default:return[]}return t.reduce(((t,n)=>(e[n]&&r(e[n])&&t.push(n),t)),[])}function se(e){const{audio:t,voice:n,video:r}=L(e),o=t||n||r||z(e);if(o)return o.duration}function ie(e,t){return`${e}_${t}`}const ce={missing_payment_information:{field:"cardNumber",message:"Incorrect card number"},invalid_number:{field:"cardNumber",message:"Incorrect card number"},number:{field:"cardNumber",message:"Incorrect card number"},exp_year:{field:"expiry",message:"Incorrect year"},exp_month:{field:"expiry",message:"Incorrect month"},invalid_expiry_year:{field:"expiry",message:"Incorrect year"},invalid_expiry_month:{field:"expiry",message:"Incorrect month"},cvc:{field:"cvv",message:"Incorrect CVV"},invalid_cvc:{field:"cvv",message:"Incorrect CVV"}};function le(e){const{message:t,code:n,param:r}=e,{field:o,message:d}=r?ce[r]:ce[n];return{field:o,message:d,description:t}}},5527:(e,t,n)=>{n.d(t,{Vl:()=>s,Js:()=>i,Tq:()=>c,kM:()=>l,NB:()=>f,cS:()=>h,kw:()=>m,Z0:()=>p,db:()=>g,Rs:()=>y});var r=n(3716),o=n(790),d=n(782),u=n(2267);const a=[1,8,5,2,7,4,6];function s(e){if(e)switch(e.type){case"userTypeBot":case"userTypeRegular":return e.firstName||e.lastName;case"userTypeDeleted":case"userTypeUnknown":return"Deleted";default:return}}function i(e){if(e){if(f(e))return"Deleted account";switch(e.type){case"userTypeBot":case"userTypeRegular":if(e.firstName&&e.lastName)return`${e.firstName} ${e.lastName}`;if(e.firstName)return e.firstName;if(e.lastName)return e.lastName;break;case"userTypeDeleted":case"userTypeUnknown":return"Deleted account"}}}function c(e,t,n){if(t.id===r.aw)return e("ServiceNotifications").toLowerCase();if(t.type&&"userTypeBot"===t.type)return e("Bot");if(!t.status)return"";switch(t.status.type){case"userStatusEmpty":return e("ALongTimeAgo");case"userStatusLastMonth":return e("WithinAMonth");case"userStatusLastWeek":return e("WithinAWeek");case"userStatusOffline":{const{wasOnline:r}=t.status;if(!r)return e("LastSeen.Offline");const d=new Date((new Date).getTime()+1e3*n),u=new Date(1e3*r);if(u>=d)return e("LastSeen.JustNow");const a=new Date(d.getTime()-u.getTime());if(a.getTime()/1e3<60)return e("LastSeen.JustNow");if(a.getTime()/1e3<3600)return e("LastSeen.MinutesAgo",Math.floor(a.getTime()/1e3/60));const s=new Date;if(s.setHours(0,0,0,0),u>new Date(s.getTime()+1e3*n))return a.getTime()/1e3<21600?e("LastSeen.HoursAgo",Math.floor(a.getTime()/1e3/60/60)):e("LastSeen.TodayAt",(0,o.mr)(u,e));const i=new Date;return i.setDate(d.getDate()-1),i.setHours(0,0,0,0),u>new Date(i.getTime()+1e3*n)?e("LastSeen.YesterdayAt",(0,o.mr)(u,e)):e("LastSeen.AtDate",(0,o.Tu)(e,u))}case"userStatusOnline":return e("Online");case"userStatusRecently":return e("Lately");default:return}}function l(e){const{id:t,status:n,type:o}=e;return!!n&&t!==r.aw&&"userStatusOnline"===n.type&&"userTypeBot"!==o}function f(e){return!(!e.status||"userTypeBot"===e.type||e.id===r.aw||"userTypeDeleted"!==e.type&&"userTypeUnknown"!==e.type)}function h(e){return"userTypeBot"===e.type}function m(e){return!e.isContact&&!h(e)}function p(e,t,n,r=0){return(0,d.Xo)(e,(e=>{const o=(0,u.b)(r);if(n&&n.includes(e))return o+172800-(n.length-n.indexOf(e));const d=t[e];if(!d||!d.status)return 0;if("userStatusOnline"===d.status.type)return d.status.expires;if("userStatusOffline"===d.status.type&&d.status.wasOnline)return d.status.wasOnline;switch(d.status.type){case"userStatusRecently":return o-86400;case"userStatusLastWeek":return o-604800;case"userStatusLastMonth":return o-18144e3;default:return 0}}),"desc")}function g(e){return"number"==typeof e?Math.abs(e):Math.abs(Number(e))}function y(e){const t=e?g(e.id)%7:0;return a[t]}},1752:(e,t,n)=>{n.d(t,{O4:()=>Me,c_:()=>C,fZ:()=>f,m6:()=>I,aK:()=>Ee,aJ:()=>Se,Sh:()=>X,$S:()=>N,bp:()=>_e,WY:()=>Ze,K4:()=>P,bV:()=>M,h8:()=>te,M6:()=>Z,i9:()=>B,Dd:()=>p,vy:()=>H,rB:()=>Ae,g_:()=>V,Mg:()=>u,SL:()=>s,Pb:()=>he,w3:()=>O,BI:()=>Ie,lr:()=>Ce,pf:()=>w,s5:()=>Q,y9:()=>L,nA:()=>Re,_7:()=>Oe,Q$:()=>Le,Dq:()=>xe,vT:()=>Ne,QH:()=>De,Ob:()=>F,a4:()=>c,B1:()=>a,vv:()=>m,Pi:()=>h,cY:()=>S,GL:()=>l,Wy:()=>y,wV:()=>_,cq:()=>x,rq:()=>W,No:()=>ue,Og:()=>ae,xv:()=>ie,px:()=>se,xj:()=>A,c1:()=>ye,z5:()=>ge,qr:()=>fe,dx:()=>me,fw:()=>we,H9:()=>be,HN:()=>Pe,ff:()=>k,P4:()=>E,x1:()=>ee,TM:()=>Te,Rg:()=>j,z3:()=>U,IM:()=>G,Xg:()=>R,j6:()=>D,lG:()=>$,IE:()=>ke,Nq:()=>q,Lm:()=>ne,Q3:()=>re,eD:()=>Y});var r=n(3716),o=n(782),d=n(8085);function u(e,t,n){return{...e,chats:{...e.chats,listIds:{...e.chats.listIds,[t]:n}}}}function a(e,t,n){const{[t]:r}=e.chats.listIds,o=null!=r&&r.length?n.filter((e=>!r.includes(e))):n;return r&&!o.length?e:u(e,t,[...r||[],...o])}function s(e,t){return{...e,chats:{...e.chats,byId:t}}}function i(e,t,n,r){const{byId:d}=e.chats,u=d[t],a=n.isMin&&u&&!u.isMin,s={...u,...a?(0,o.CE)(n,["isMin","accessHash"]):n,...r&&{photos:[r,...u.photos||[]]}};return s.id&&s.type,s}function c(e,t,n,r){const{byId:o}=e.chats;return s(e,{...o,[t]:i(e,t,n,r)})}function l(e,t){const n=Object.keys(t).reduce(((n,r)=>{const o=i(e,r,t[r]);return o&&(n[r]=o),n}),{});return e=s(e,{...e.chats.byId,...n})}function f(e,t){const{byId:n}=e.chats;let r=!1;const o=Object.keys(t).reduce(((o,d)=>{if(!n[d]||n[d].isMin&&!t[d].isMin){const n=i(e,d,t[d]);n&&(o[d]=n,r||(r=!0))}return o}),{});return r&&(e=s(e,{...e.chats.byId,...o})),e}function h(e,t,n){const o=n===r.WS?"archived":"active";let d=e.chats.listIds;return Object.keys(d).forEach((e=>{const n=d[e]||[];e!==o||n.includes(t)?e!==o&&n.includes(t)&&(d={...d,[e]:n.filter((e=>e!==t))}):d={...d,[e]:[...n,t]}})),c(e={...e,chats:{...e.chats,listIds:d}},t,{folderId:n||void 0})}function m(e,t,n){const r="active"===t?"all":"archived";return{...e,chats:{...e.chats,...n.orderedPinnedIds&&{orderedPinnedIds:{...e.chats.orderedPinnedIds,[t]:n.orderedPinnedIds}},totalCount:{...e.chats.totalCount,[r]:n.totalChatCount},isFullyLoaded:{...e.chats.isFullyLoaded,[t]:!1}}}}function p(e,t){const n=(0,d.Ek)(e,t);if(!n)return e;const{[n]:r}=e.chats.listIds;return r&&(e=u(e,n,r.filter((e=>e!==t)))),c(e,t,{isNotJoined:!0})}var g=n(6137);function y(e,t,n=g._f,o="thread",d){const{messageLists:u}=e.messages;let a=u;if(d||r.Cg)a=t?[{chatId:t,threadId:n,type:o}]:[];else if(t){const e=u[u.length-1];e&&e.chatId===t&&e.threadId===n&&e.type===o||(a=e&&e.chatId===r.AJ?[...u.slice(0,-1),{chatId:t,threadId:n,type:o}]:[...u,{chatId:t,threadId:n,type:o}])}else a=u.slice(0,-1);return{...e,messages:{...e.messages,messageLists:a}}}function v(e,t,n){return b(e,t,{byId:n})}function b(e,t,n){const r=e.messages.byChatId[t]||{byId:{},threadsById:{}};return{...e,messages:{...e.messages,byChatId:{...e.messages.byChatId,[t]:{...r,...n}}}}}function w(e,t,n,r,o){return function(e,t,n,r){const o=e.messages.byChatId[t];return b(e,t,{threadsById:{...null==o?void 0:o.threadsById,[n]:{...null==o?void 0:o.threadsById[n],...r}}})}(e,t,n,{[r]:o})}function I(e,t){const n=t.reduce(((e,t)=>(e[t.chatId]||(e[t.chatId]={}),e[t.chatId][t.id]=t,e)),{});return Object.keys(n).forEach((t=>{e=C(e,t,n[t])})),e}function C(e,t,n){const r=(0,d.Zw)(e,t);return r&&Object.keys(n).every((e=>Boolean(r[Number(e)])))?e:v(e,t,{...n,...r})}function S(e,t,n,r){const o=(0,d.Zw)(e,t)||{},u={...o[n],...r};return u.id?v(e,t,{...o,[n]:u}):e}function E(e,t,n,r){const o=(0,d.Fn)(e,t)||{},u={...o[n],...r};return u.id?O(e,t,{...o,[n]:u}):e}function P(e,t,n){const r=(0,d.Zw)(e,t);if(!r)return e;const u=(0,o.CE)(r,n),a=Object.values((0,o.q0)(r,n)).filter((({forwardInfo:e})=>null==e?void 0:e.isLinkedChannelPost));if(Object.keys(e.messages.byChatId[t].threadsById).map(Number).forEach((r=>{const o=(0,d.tZ)(e,t,r);let u=(0,d.gb)(e,t,r),a=(0,d.qC)(e,t,r),s=(0,d.Cb)(e,t,r),i=(0,d.KB)(e,t),c=null==o?void 0:o.messagesCount;n.forEach((e=>{u&&u.includes(e)&&(u=u.filter((t=>t!==e)),void 0!==c&&(c-=1)),a&&a.includes(e)&&(a=a.filter((t=>t!==e))),s&&s.includes(e)&&(s=s.filter((t=>t!==e))),i&&i.includes(e)&&(i=i.filter((t=>t!==e)))})),e=w(e,t,r,"listedIds",u),e=w(e,t,r,"outlyingIds",a),e=w(e,t,r,"viewportIds",s),e=w(e,t,r,"pinnedIds",i),o&&void 0!==c&&(e=w(e,t,r,"threadInfo",{...o,messagesCount:c}))})),a.length){const n=(0,d.Bt)(e),r=n&&n.chatId===t&&"thread"===n.type,o=null==n?void 0:n.threadId;a.forEach((n=>{const{fromChatId:u,fromMessageId:a}=n.forwardInfo,s=(0,d.hj)(e,u,a);r&&o===a&&(e=y(e,t)),s&&(e=S(e,u,a,{threadInfo:void 0}))}))}return e=v(e,t,u)}function M(e,t,n){const r=(0,d.Fn)(e,t);if(!r)return e;const u=(0,o.CE)(r,n);let a=(0,d.qy)(e,t);return a&&(n.forEach((e=>{a.includes(e)&&(a=a.filter((t=>t!==e)))})),e=w(e,t,g._f,"scheduledIds",a)),O(e,t,u)}function A(e,t,n,r){const o=(0,d.gb)(e,t,n),u=null!=o&&o.length?r.filter((e=>!o.includes(e))):r;return o&&!u.length?e:w(e,t,n,"listedIds",T([...o||[],...u]))}function k(e,t,n,r){const o=(0,d.qC)(e,t,n),u=null!=o&&o.length?r.filter((e=>!o.includes(e))):r;return o&&!u.length?e:w(e,t,n,"outlyingIds",T([...o||[],...u]))}function T(e){return e.sort(((e,t)=>e-t))}function N(e,t,n,o){const u=(0,d.Cb)(e,t,n)||[];return u.includes(o)?e:w(e,t,n,"viewportIds",T([...u.length{e=R(e,t.chatId,t.threadId,t)})),e}function O(e,t,n){return function(e,t,n){const r=e.scheduledMessages.byChatId[t]||{byId:{},hash:0};return{...e,scheduledMessages:{byChatId:{...e.scheduledMessages.byChatId,[t]:{...r,...n}}}}}(e,t,{byId:n})}function x(e,t,n,r=!1,o=!1){return{...e,focusedMessage:{...e.focusedMessage,chatId:t,messageId:n,noHighlight:r,isResizingContainer:o}}}function _(e,t){return{...e,focusedMessage:{...e.focusedMessage,direction:t}}}function Z(e,t,n){return{...e,selectedMessages:{chatId:t,messageIds:n?Array.prototype.concat([],n):[]}}}function F(e,t,n,r,u,a,s,i=!1){const{selectedMessages:c}=e;a&&(s=(0,d.xH)(e,t,a));const l=s||[u];if(!c)return Z(e,t,l);const{messageIds:f}=c;let h;const m=l.filter((e=>!f.includes(e)));if(m&&!m.length)h=f.filter((e=>!l.includes(e)));else if(i&&f.length){const a=(0,d.$W)(e,t,n,r),s=a.indexOf(f[f.length-1]),i=a.indexOf(u),c=Math.min(s,i),l=Math.max(s,i),m=a.slice(c,l+1);h=(0,o.Tw)([...f,...m])}else h=[...f,...m];return h.length?{...e,selectedMessages:{...c,messageIds:h}}:B(e)}function B(e){return{...e,selectedMessages:void 0}}function $(e,t,n,r,o){const{channelPostId:u,fromChatId:a}=t.forwardInfo||{};if(u&&a){const t=(0,d.tZ)(e,n,u);t&&(e=w(e,n,u,"threadInfo",{...t,lastMessageId:r,messagesCount:t.messagesCount+(o?-1:1)}))}return e}function U(e,t,n,r,d){const u=r.map((t=>{const n=e.stickers.setsById[t.id];return n?{...n,...t}:t}));return{...e,stickers:{...e.stickers,setsById:{...e.stickers.setsById,...(0,o.ee)(u,"id")},[t]:{...e.stickers[t],hash:n,..."search"===t?{resultIds:d}:{setIds:r.map((({id:e})=>e))}}}}}function j(e,t,n){const r=e.stickers.setsById[t]||{};return{...e,stickers:{...e.stickers,setsById:{...e.stickers.setsById,[t]:{...r,...n}}}}}function W(e,t,n,r){const{results:o}=e.gifs.search;let d;if(t||!o)d=n;else{const e=new Set(o.map((e=>e.id)));d=[...o,...n.filter((t=>!e.has(t.id)))]}return{...e,gifs:{...e.gifs,search:{...e.gifs.search,offset:r,results:d}}}}function V(e,t){return{...e,animatedEmojis:t}}function G(e,t,n,r){const u=[...(0,d.Pk)(e,t),...n||[]],a=(0,o.Tw)(u.map((({id:e})=>e))),s=(0,o.ee)(u,"id"),i=a.map((e=>s[e]));return{...e,stickers:{...e.stickers,forEmoji:{emoji:t,stickers:i,hash:r}}}}function H(e){const{emoji:t,stickers:n,hash:r}=e.stickers.forEmoji||{};return t?G(e,t,n,r):e}var z=n(735);function Q(e,t){return{...e,users:{...e.users,byId:t}}}function K(e,t,n){const{byId:r}=e.users,d=r[t],u=n.isMin&&d&&!d.isMin,a={...d,...u?(0,o.CE)(n,["isMin","accessHash"]):n};return a.id&&a.type?a:d}function J(e,t){const{userIds:n}=e.contactList||{};if(!n)return e;const r=t.filter((e=>(null==e?void 0:e.isContact)&&!n.includes(e.id))).map((e=>e.id));return 0===r.length?e:{...e,contactList:{userIds:[...r,...n]}}}function q(e,t,n){const{byId:r}=e.users,o=K(e,t,n);return Q(e=J(e,[o]),{...r,[t]:o})}function Y(e,t){const n=Object.keys(t).reduce(((n,r)=>{const o=K(e,r,t[r]);return o&&(n[r]=o),n}),{});return e=Q(e=J(e,Object.values(n)),{...e.users.byId,...n})}function X(e,t){const{byId:n}=e.users;let r=!1;const o=Object.keys(t).reduce(((o,d)=>{if(!n[d]||n[d].isMin&&!t[d].isMin){const n=K(e,d,t[d]);n&&(o[d]=n,r||(r=!0))}return o}),{});return r&&(e=J(e=Q(e,{...e.users.byId,...o}),Object.values(o))),e}function ee(e,t){return e.users.selectedId===t?e:{...e,users:{...e.users,selectedId:t}}}function te(e,t){const{byId:n}=e.users,{userIds:r}=e.contactList||{};return delete n[t],Q(e={...e,contactList:{userIds:r?r.filter((e=>e!==t)):z.D}},n)}function ne(e,t){return{...e,userSearch:{...e.userSearch,...t}}}function re(e,t){return ne(e,{fetchingStatus:t})}function oe(e,t,n){const{byId:r}=e.users,o=r[t];return o&&o.fullInfo?q(e,t,{...o,fullInfo:{...o.fullInfo,isBlocked:n}}):e}const de=e=>`${e.chatId}_${e.id}`;function ue(e,t){return{...e,globalSearch:{...e.globalSearch,...t}}}function ae(e,t){return ue(e,{currentContent:t})}function se(e,t,n,r,d){var u;const{resultsByType:a}=e.globalSearch||{},s=t.reduce(((e,t)=>(e[de(t)]=t,e)),{}),i=null==a||null===(u=a[r])||void 0===u?void 0:u.foundIds;if(void 0!==i&&Object.keys(s).every((e=>i.includes(de(s[e])))))return ie(e,{messages:!1});const c=i||[],l=t.map((e=>de(e))),f=Array.prototype.concat(c,l),h=(0,o.et)(c,f)?c:f;return ue(e=ie(e,{messages:!1}),{resultsByType:{...(e.globalSearch||{}).resultsByType,[r]:{totalCount:n,nextOffsetId:d,foundIds:h}}})}function ie(e,t){return ue(e,{fetchingStatus:{...e.globalSearch.fetchingStatus,...t}})}var ce=n(2858);function le(e,t,n){return{...e,localTextSearch:{byChatThreadKey:{...e.localTextSearch.byChatThreadKey,[t]:n}}}}function fe(e,t,n,r,o){const d=(0,ce.uw)(t,n);return le(e,d,{...e.localTextSearch.byChatThreadKey[d],isActive:r,query:o})}function he(e,t,n,r,o,d){const u=(0,ce.uw)(t,n);return le(e,u,{...e.localTextSearch.byChatThreadKey[u],results:{foundIds:r,totalCount:o,nextOffsetId:d}})}function me(e,t,n,r,d,u){const a=(0,ce.uw)(t,n),{results:s}=e.localTextSearch.byChatThreadKey[a]||{},i=(null==s?void 0:s.foundIds)||[],c=ve((0,o.Tw)(Array.prototype.concat(i,r)));return he(e,t,n,(0,o.et)(i,c)?i:c,d,u)}function pe(e,t,n){return{...e,localMediaSearch:{byChatId:{...e.localMediaSearch.byChatId,[t]:n}}}}function ge(e,t,n){return pe(e,t,{...e.localMediaSearch.byChatId[t],currentType:n})}function ye(e,t,n,r,d,u){const{resultsByType:a}=e.localMediaSearch.byChatId[t]||{},s=null!=a&&a[n]?a[n].foundIds:[],i=ve((0,o.Tw)(Array.prototype.concat(s,r)));return function(e,t,n,r,o,d){return pe(e,t,{...e.localMediaSearch.byChatId[t],resultsByType:{...(e.localMediaSearch.byChatId[t]||{}).resultsByType,[n]:{foundIds:r,totalCount:o,nextOffsetId:d}}})}(e,t,n,(0,o.et)(s,i)?s:i,d,u)}function ve(e){return e.sort(((e,t)=>e-t))}function be(e,t){return{...e,management:{...e.management,progress:t}}}function we(e,t,n){return{...e,management:{...e.management,byChatId:{...e.management.byChatId,[t]:{...e.management.byChatId[t]||{},...n}}}}}function Ie(e,t){return{...e,settings:{...e.settings,byKey:{...e.settings.byKey,...t}}}}function Ce(e,t,n){return{...e,settings:{...e.settings,themes:{...e.settings.themes,[t]:{...e.settings.themes[t]||{},...n}}}}}function Se(e,t){return t.forEach((t=>{const{chatId:n,...r}=t;e=Ee(e,n,r)})),e}function Ee(e,t,n){return{...e,settings:{...e.settings,notifyExceptions:{...e.settings.notifyExceptions,[t]:n}}}}function Pe(e,t,n,r){switch(t){case"contact":return Ie(e,{...void 0!==n&&{hasPrivateChatsNotifications:!n},...void 0!==r&&{hasPrivateChatsMessagePreview:r}});case"group":return Ie(e,{...void 0!==n&&{hasGroupNotifications:!n},...void 0!==r&&{hasGroupMessagePreview:r}});case"broadcast":return Ie(e,{...void 0!==n&&{hasBroadcastNotifications:!n},...void 0!==r&&{hasBroadcastMessagePreview:r}});default:return}}function Me(e,t){return e=oe(e,t,!0),{...e,blocked:{...e.blocked,ids:[t,...e.blocked.ids],totalCount:e.blocked.totalCount+1}}}function Ae(e,t){return e=oe(e,t,!1),{...e,blocked:{...e.blocked,ids:e.blocked.ids.filter((e=>e!==t)),totalCount:e.blocked.totalCount-1}}}function ke(e,t){return{...e,twoFaSettings:{...e.twoFaSettings,...t}}}function Te(e,t){return{...e,payment:{...e.payment,shippingOptions:t}}}function Ne(e,t){return{...e,payment:{...e.payment,requestId:t}}}function Le(e,t){return{...e,payment:{...e.payment,step:t}}}function Re(e,t){if(!t.content||!t.content.invoice)return e;const{title:n,text:r,amount:o,currency:d,isTest:u,photoUrl:a}=t.content.invoice;return{...e,payment:{...e.payment,invoiceContent:{title:n,text:r,photoUrl:a,amount:o,currency:d,isTest:u}}}}function De(e,t){return{...e,payment:{...e.payment,stripeCredentials:{...t}}}}function Oe(e,t){return{...e,payment:{...e.payment,...t}}}function xe(e,t,n){if(!t||!n)return{...e,payment:{...e.payment,receipt:void 0}};const{invoice:r}=n.content,{photoUrl:o,text:d,title:u}=r||{};return{...e,payment:{...e.payment,receipt:{...t,photoUrl:o,text:d,title:u}}}}function _e(e){return{...e,payment:{}}}function Ze(e){return{...e,payment:{...e.payment,isPaymentModalOpen:!1}}}},8085:(e,t,n)=>{n.d(t,{hg:()=>ue,xs:()=>Ce,_k:()=>ye,zB:()=>O,g4:()=>w,bH:()=>xe,__:()=>Ze,xl:()=>ve,Nu:()=>we,nB:()=>be,Z1:()=>f,IK:()=>v,DI:()=>P,Mw:()=>S,Ek:()=>C,hj:()=>se,ZB:()=>le,Zw:()=>B,YK:()=>y,Dg:()=>h,X5:()=>Ae,A1:()=>M,jr:()=>F,yN:()=>N,JX:()=>Ke,pP:()=>Ve,we:()=>je,og:()=>Ue,$W:()=>V,Bt:()=>Z,y5:()=>T,n5:()=>$e,Ms:()=>Y,_$:()=>J,kK:()=>ce,wU:()=>q,yZ:()=>te,It:()=>Pe,G$:()=>fe,y8:()=>Ne,cv:()=>ge,pk:()=>b,N:()=>I,ep:()=>E,xo:()=>p,FM:()=>m,a6:()=>Re,te:()=>Ie,Ev:()=>Me,CA:()=>ke,zQ:()=>Ge,_X:()=>he,vk:()=>Te,Jf:()=>ze,UW:()=>A,s4:()=>i,b9:()=>ae,VF:()=>Be,gb:()=>j,aW:()=>We,xH:()=>Le,FT:()=>Oe,tV:()=>X,NJ:()=>l,dZ:()=>c,dT:()=>me,qC:()=>W,gx:()=>Je,eh:()=>Ye,Mz:()=>qe,sp:()=>Xe,KB:()=>H,$$:()=>et,rd:()=>Ee,p9:()=>ne,Yy:()=>K,Wq:()=>He,qy:()=>z,Tm:()=>ie,Fn:()=>$,Vt:()=>Q,D7:()=>De,Ur:()=>pe,yB:()=>Fe,Ny:()=>L,E_:()=>R,Pk:()=>D,i3:()=>tt,P_:()=>g,Pu:()=>Qe,Db:()=>de,tZ:()=>ee,Cm:()=>re,qS:()=>oe,uZ:()=>Se,dy:()=>s,Cb:()=>G});var r=n(1713),o=n(7361),d=n(6137),u=n(3716),a=n(2858);function s(e,t){return e.users.byId[t]}function i(e,t){var n;const r=s(e,t);return null==r||null===(n=r.fullInfo)||void 0===n?void 0:n.isBlocked}function c(e){return e.settings.byKey}function l(e){return e.settings.notifyExceptions}function f(e,t){return e.chats.byId[t]}function h(e,t){const n=(0,a.zX)(t);return!!n&&s(e,n)}function m(e,t){return t===e.currentUserId}function p(e,t){const n=h(e,t);return n&&(0,a.cS)(n)}function g(e){return Object.values(e.chats.byId).find((({isSupport:e})=>e))}function y(e,t){if(!(0,a.YC)(t.id)&&!(0,a.eA)(t)&&t.fullInfo)return t.fullInfo.members&&t.fullInfo.members.length!==u.mo?t.fullInfo.members.reduce(((t,{userId:n})=>e.users.byId[n]&&(0,a.kM)(e.users.byId[n])&&n!==e.currentUserId?t+1:t),0):t.fullInfo.onlineCount}function v(e,t){const n=f(e,t),r=n&&(0,a.zX)(n),o=r&&s(e,r);if(o&&(0,a.cS)(o))return o}function b(e,t){const n=f(e,t),r=v(e,t);if(!n||!r)return!1;if(n.lastMessage&&(0,a.CD)(n.lastMessage))return!0;const o=e.messages.byChatId[t];if(!o)return!1;const{listedIds:u}=o.threadsById[d._f]||{};return u&&!u.length}function w(e){return Boolean(e.chats.listIds.active)}function I(e,t,n){const{listIds:r}=e.chats;if(n){const e=r[n];return Boolean(e&&e.includes(t))}return Object.values(r).some((e=>e&&e.includes(t)))}function C(e,t){const n=f(e,t);if(n&&I(e,t))return n.folderId===u.WS?"archived":"active"}function S(e,t){return e.chatFolders.byId[t]}function E(e,t,n=u.Nf){const{active:r,archived:o}=e.chats.orderedPinnedIds;if(n===u.Nf)return!!r&&r.includes(t);if(n===u.WS)return!!o&&o.includes(t);const{byId:d}=e.chatFolders,{pinnedChatIds:a}=d[n]||{};return!!a&&a.includes(t)}function P(e,t){const n=t.toLowerCase();return Object.values(e.chats.byId).find((e=>e.username&&e.username.toLowerCase()===n))}function M(e){const t=e.chats.listIds.active;if(!t)return 0;const n=e.chats.byId,r=c(e),o=l(e);return t.reduce(((e,t)=>{const d=n[t];return!(d&&d.unreadCount&&d.isListed)||d.isNotJoined||d.isRestricted||!d.unreadMentionsCount&&(0,a.i4)(d,r,o)?e:e+d.unreadCount}),0)}function A(e){return Boolean(f(e,u.aw))}var k=n(782);function T(e){return e.stickers.search}function N(e){return e.gifs.search}function L(e,t){return e.stickers.setsById[t]}function R(e,t){return Object.values(e.stickers.setsById).find((e=>e.shortName.toLowerCase()===t.toLowerCase()))}function D(e,t){const n=Object.values(e.stickers.setsById);let r=[];return n.forEach((({packs:e})=>{if(!e)return;const n=e[t];n&&(r=r.concat(n))})),r}function O(e,t){const{animatedEmojis:n}=e;if(!n||!n.stickers)return;const r=t.replace("️","");return n.stickers.find((e=>e.emoji===t||e.emoji===r))}var x=n(2267),_=n(735);function Z(e){const{messageLists:t}=e.messages;if(t.length)return t[t.length-1]}function F(e){const{chatId:t}=Z(e)||{};return t?f(e,t):void 0}function B(e,t){var n;return null===(n=e.messages.byChatId[t])||void 0===n?void 0:n.byId}function $(e,t){var n;return null===(n=e.scheduledMessages.byChatId[t])||void 0===n?void 0:n.byId}function U(e,t,n,r){const o=e.messages.byChatId[t];if(!o)return;const d=o.threadsById[n];return d?d[r]:void 0}function j(e,t,n){return U(e,t,n,"listedIds")}function W(e,t,n){return U(e,t,n,"outlyingIds")}function V(e,t,n,r){switch(r){case"thread":return G(e,t,n);case"pinned":return H(e,t);case"scheduled":return z(e,t)}}function G(e,t,n){return U(e,t,n,"viewportIds")}function H(e,t){return U(e,t,d._f,"pinnedIds")}function z(e,t){return U(e,t,d._f,"scheduledIds")}function Q(e,t,n){return U(e,t,n,"scrollOffset")}function K(e,t,n){return U(e,t,n,"replyingToId")}function J(e,t,n){return U(e,t,n,"editingId")}function q(e,t){return U(e,t,d._f,"editingScheduledId")}function Y(e,t,n){return U(e,t,n,"draft")}function X(e,t,n){return U(e,t,n,"noWebPage")}function ee(e,t,n){return U(e,t,n,"threadInfo")}function te(e,t,n){return U(e,t,n,"firstMessageId")}function ne(e,t,n){return U(e,t,n,"replyStack")}function re(e,t,n){if(n===d._f)return f(e,t);const r=ee(e,t,n);return r?f(e,r.originChannelId||t):void 0}function oe(e,t,n){if(n===d._f)return;const r=ee(e,t,n);return r?r.topMessageId:void 0}function de(e,t,n){const r=e.messages.byChatId[t];if(!r)return;const{replyToMessageId:o,replyToTopMessageId:d}=n;return o||d?Object.values(r.threadsById).find((e=>e.threadInfo&&(o&&o===e.threadInfo.topMessageId||d&&d===e.threadInfo.topMessageId))):void 0}function ue(e,t,n){const r=Z(e);if(!r)return!1;const{threadInfo:o}=de(e,t,n)||{};return t===r.chatId&&(r.threadId===d._f||o&&r.threadId===o.threadId)}function ae(e,t,n){const r=G(e,t,n);if(!r||!r.length)return!0;let o;if(n===d._f){const n=f(e,t);if(!n||!n.lastMessage)return!0;o=n.lastMessage.id}else{const r=ee(e,t,n);if(!r||!r.lastMessageId)return;o=r.lastMessageId}return o>=u.AE&&!se(e,t,o)||r[r.length-1]>=o}function se(e,t,n){const r=B(e,t);return r?r[n]:void 0}function ie(e,t,n){const r=$(e,t);return r?r[n]:void 0}function ce(e,t,n,r){if("scheduled"===r){const n=q(e,t);return n?ie(e,t,n):void 0}{const r=J(e,t,n);return r?se(e,t,r):void 0}}function le(e,t){let n;for(const r of Object.values(e.messages.byChatId)){const{byId:e}=r;if(n=Object.values(e).find((e=>e.content.poll&&e.content.poll.id===t)),n)break}return n}function fe(e,t){const{chatId:n,messageId:r}=e.focusedMessage||{};return n===t?r:void 0}function he(e,t){const n=fe(e,t.chatId);return!!n&&(n===t.id||n===t.previousLocalId)}function me(e,t,n=!1){return function(e,t){const{lastReadOutboxMessageId:n}=f(e,t.chatId)||{};return(0,a.CI)(t)||!n||ne===t.id))}(e,t.content.sticker),O=!b&&R&&!D,_=!b&&D,Z=!b,F=!b&&(p||h),B=!b,$=Boolean((null===(o=w.webPage)||void 0===o?void 0:o.document)||(null===(d=w.webPage)||void 0===d?void 0:d.video)||(null===(u=w.webPage)||void 0===u?void 0:u.photo)||w.audio||w.voice||w.photo||w.video||w.document||w.sticker);return{noOptions:[C,N,E,P,k,A,T,L,O,_,Z,F,B,$].every((e=>!e)),canReply:C,canEdit:N,canPin:E,canUnpin:P,canReport:k,canDelete:A,canDeleteForAll:T,canForward:L,canFaveSticker:O,canUnfaveSticker:_,canCopy:Z,canCopyLink:F,canSelect:B,canDownload:$}}function ve(e){const{messageIds:t}=e.selectedMessages||{},{chatId:n,threadId:r}=Z(e)||{},o=n&&B(e,n);if(!o||!t||!r)return{};const d=t.map((t=>o[t]&&ye(e,o[t],r))).filter(Boolean);return{canDelete:d.every((e=>e.canDelete)),canDeleteForAll:d.every((e=>e.canDeleteForAll))}}function be(e){const{messageIds:t}=e.selectedMessages||{},{chatId:n,threadId:r}=Z(e)||{},o=n&&B(e,n);return!!(o&&t&&r)&&t.map((t=>o[t]&&ye(e,o[t],r))).filter(Boolean).every((e=>e.canReport))}function we(e){const{messageIds:t}=e.selectedMessages||{},{chatId:n,threadId:r}=Z(e)||{},o=n&&B(e,n);return!!(o&&t&&r)&&t.map((t=>o[t]&&ye(e,o[t],r))).filter(Boolean).some((e=>e.canDownload))}function Ie(e,t){const n=e.activeDownloads.byChatId[t.chatId];return!!n&&n.includes(t.id)}function Ce(e,t){return e.activeDownloads.byChatId[t]||_.D}function Se(e,t){var n;return null===(n=e.fileUploads.byMessageLocalId[t.previousLocalId||t.id])||void 0===n?void 0:n.progress}function Ee(e,t,n){if(n===d._f){const n=f(e,t);if(!n)return;if(!n.lastReadInboxMessageId)return;return n.lastMessage?(0,a.CI)(n.lastMessage)?n.lastMessage.id:Math.min(n.lastMessage.id,n.lastReadInboxMessageId):n.lastReadInboxMessageId}{const r=ee(e,t,n);if(!r)return;return r.lastReadInboxMessageId?Math.min(r.lastReadInboxMessageId,r.lastMessageId||1/0):r.topMessageId}}function Pe(e,t,n){const r=f(e,t);if(n===d._f){if(!r)return}else{const r=ee(e,t,n);if(!r||void 0!==r.lastMessageId&&r.lastMessageId===r.lastReadInboxMessageId)return}const o=W(e,t,n),a=j(e,t,n),s=B(e,t);if(!s||!o&&!a)return;const i=Ee(e,t,n);if(!i&&r&&r.isNotJoined)return;const c=t===u.aw?e.serviceNotifications.reduce(((e,t)=>!t.isUnread&&t.id>e?t.id:e),-1):-1;function l(e){return i?e.find((e=>e>i&&s[e]&&(!s[e].isOutgoing||s[e].isFromScheduled)&&e>c)):e[0]}if(o){const e=l(o);if(e)return e}if(a){const e=l(a);if(e)return e}}function Me(e){const{forwardMessages:t}=e;return Boolean(t.isModalShown)}function Ae(e,t){const n=Object.values(e.chats.byId).find((e=>(0,a.Ru)(e)&&e.lastMessage&&e.lastMessage.id===t));if(n)return n.id;const{byChatId:r}=e.messages;return Object.keys(r).find((n=>{const o=f(e,n);return o&&(0,a.Ru)(o)&&r[o.id].byId[t]}))}function ke(e){const{selectedMessages:t}=e;return Boolean(t)}function Te(e,t){const{messageIds:n}=e.selectedMessages||{};return!!n&&n.includes(t)}function Ne(e,t,n){const r=B(e,t);if(r)return Object.values(r).filter((e=>e.groupedId===n&&e.forwardInfo)).map((({forwardInfo:e})=>e.fromMessageId))}function Le(e,t,n){const r=B(e,t);if(r)return Object.keys(r).map(Number).filter((e=>r[e].groupedId===n))}function Re(e,t,n){const{messageIds:r}=e.selectedMessages||{};if(!r)return!1;const o=Le(e,t,n);return o&&o.every((e=>r.includes(e)))}function De(e){const{messageIds:t}=e.selectedMessages||{};return t?t.length:0}function Oe(e,t){const n=f(e,t);if(!n)return;if(!p(e,n))return;const r=B(e,t),o=G(e,t,d._f);if(!r||!o)return;const u=(0,k.dF)(o,(e=>!r[e].isOutgoing&&Boolean(r[e].keyboardButtons))),a=(0,k.dF)(o,(e=>Boolean(r[e].shouldHideKeyboardButtons)));return u&&a&&a>u?void 0:u?r[u]:void 0}function xe(e,t,n,r){const o=Boolean((0,a.O$)(t)||(0,a.F$)(t)),d=Boolean((0,a.b7)(t)||(0,a.Cg)(t)),u=Boolean((0,a.oP)(t)||(0,a.kd)(t)||(0,a.aE)(t)),{canAutoLoadPhotoFromContacts:s,canAutoLoadPhotoInPrivateChats:i,canAutoLoadPhotoInGroups:c,canAutoLoadPhotoInChannels:l,canAutoLoadVideoFromContacts:f,canAutoLoadVideoInPrivateChats:h,canAutoLoadVideoInGroups:m,canAutoLoadVideoInChannels:p,canAutoLoadFileFromContacts:g,canAutoLoadFileInPrivateChats:y,canAutoLoadFileInGroups:v,canAutoLoadFileInChannels:b}=e.settings.byKey;return o?_e({global:e,chat:n,sender:r,canAutoLoadMediaFromContacts:s,canAutoLoadMediaInPrivateChats:i,canAutoLoadMediaInGroups:c,canAutoLoadMediaInChannels:l}):d?_e({global:e,chat:n,sender:r,canAutoLoadMediaFromContacts:f,canAutoLoadMediaInPrivateChats:h,canAutoLoadMediaInGroups:m,canAutoLoadMediaInChannels:p}):!u||_e({global:e,chat:n,sender:r,canAutoLoadMediaFromContacts:g,canAutoLoadMediaInPrivateChats:y,canAutoLoadMediaInGroups:v,canAutoLoadMediaInChannels:b})}function _e({global:e,chat:t,sender:n,canAutoLoadMediaFromContacts:r,canAutoLoadMediaInPrivateChats:o,canAutoLoadMediaInGroups:d,canAutoLoadMediaInChannels:u}){const s=Boolean(n&&(n.id===e.currentUserId||function(e,t){return e.contactList&&e.contactList.userIds.includes(t.id)}(e,n)));return Boolean(s&&r||!s&&o&&(0,a.YC)(t.id)||d&&(0,a.Bf)(t)||u&&(0,a.eA)(t))}function Ze(e,t){const n=(0,a.b7)(t)||(0,a.Cg)(t);if(!n)return;const{canAutoPlayVideos:r,canAutoPlayGifs:o}=e.settings.byKey,d=n.isGif||n.isRound;return r&&!d||o&&d}function Fe(e){return e.settings.byKey.shouldLoopStickers}function Be(e){const{serviceNotifications:t}=e,n=Math.max(...t.map((({id:e})=>e)));return t.find((({id:e})=>e===n))}function $e(e){const{chatId:t,threadId:n}=Z(e)||{};if(!t||!n)return;const r=(0,a.uw)(t,n),o=e.localTextSearch.byChatThreadKey[r];return o&&o.isActive?o:void 0}function Ue(e){const{byChatId:t}=e.localMediaSearch,{chatId:n}=Z(e)||{},r=e.users.selectedId;return r&&t[r]?r:n}function je(e){const t=Ue(e);if(t)return e.localMediaSearch.byChatId[t]}function We(e,t){return e.management.byChatId[t]}function Ve(e){const{chatId:t,threadId:n}=Z(e)||{};if(!t||!n)return;if((0,a.YC)(t))return"user";const r=f(e,t);return r?(0,a.Bf)(r)?"group":"channel":void 0}function Ge(e){const{mediaViewer:t}=e;return Boolean(t.messageId||t.avatarOwnerId)}function He(e){const{users:t,isChatInfoShown:n,newChatMembersProgress:d}=e,u=d!==r.WB.Closed,a=function(e){const{pollResults:t}=e;return Boolean(t.messageId)}(e),s=Boolean(!o.wB&&$e(e)),i=function(e){const{chatId:t,threadId:n}=Z(e)||{};if(!t||!n)return;const r=e.management.byChatId[t];return r&&r.isActive?r:void 0}(e),c=void 0!==T(e).query,l=void 0!==N(e).query,{chatId:f}=Z(e)||{},h=t.selectedId,m=w(e),p=Boolean(h&&m),g=Boolean(f&&m)&&n;return a?r.qt.PollResults:s?r.qt.Search:i?r.qt.Management:c?r.qt.StickerSearch:l?r.qt.GifSearch:u?r.qt.AddingMembers:p?r.qt.UserInfo:g?r.qt.ChatInfo:void 0}function ze(e){return void 0!==He(e)}function Qe(e){const{theme:t,shouldUseSystemTheme:n}=e.settings.byKey;return n?(0,o.vn)():t}function Ke(e){return e.globalSearch.query}function Je(e){return e.payment.chatId}function qe(e){return e.payment.messageId}function Ye(e){return e.payment.formId}function Xe(e){return e.payment.requestId}function et(e){return e.payment.nativeParams?e.payment.nativeParams.publishableKey:void 0}function tt(e){return e.payment.stripeCredentials}},1713:(e,t,n)=>{let r,o,d,u,a,s,i,c,l,f,h,m,p,g;n.d(t,{Uq:()=>r,fo:()=>o,MT:()=>d,du:()=>u,nJ:()=>a,qt:()=>s,bZ:()=>i,Cr:()=>c,Nh:()=>l,rN:()=>f,wv:()=>h,WB:()=>m,vi:()=>p,KB:()=>g,mp:()=>y,u1:()=>v}),function(e){e[e.Backwards=0]="Backwards",e[e.Forwards=1]="Forwards",e[e.Around=2]="Around"}(r||(r={})),function(e){e[e.Up=0]="Up",e[e.Down=1]="Down",e[e.Static=2]="Static"}(o||(o={})),function(e){e[e.Main=0]="Main",e[e.EditProfile=1]="EditProfile",e[e.Notifications=2]="Notifications",e[e.DataStorage=3]="DataStorage",e[e.Language=4]="Language",e[e.General=5]="General",e[e.GeneralChatBackground=6]="GeneralChatBackground",e[e.GeneralChatBackgroundColor=7]="GeneralChatBackgroundColor",e[e.Privacy=8]="Privacy",e[e.PrivacyPhoneNumber=9]="PrivacyPhoneNumber",e[e.PrivacyLastSeen=10]="PrivacyLastSeen",e[e.PrivacyProfilePhoto=11]="PrivacyProfilePhoto",e[e.PrivacyForwarding=12]="PrivacyForwarding",e[e.PrivacyGroupChats=13]="PrivacyGroupChats",e[e.PrivacyPhoneNumberAllowedContacts=14]="PrivacyPhoneNumberAllowedContacts",e[e.PrivacyPhoneNumberDeniedContacts=15]="PrivacyPhoneNumberDeniedContacts",e[e.PrivacyLastSeenAllowedContacts=16]="PrivacyLastSeenAllowedContacts",e[e.PrivacyLastSeenDeniedContacts=17]="PrivacyLastSeenDeniedContacts",e[e.PrivacyProfilePhotoAllowedContacts=18]="PrivacyProfilePhotoAllowedContacts",e[e.PrivacyProfilePhotoDeniedContacts=19]="PrivacyProfilePhotoDeniedContacts",e[e.PrivacyForwardingAllowedContacts=20]="PrivacyForwardingAllowedContacts",e[e.PrivacyForwardingDeniedContacts=21]="PrivacyForwardingDeniedContacts",e[e.PrivacyGroupChatsAllowedContacts=22]="PrivacyGroupChatsAllowedContacts",e[e.PrivacyGroupChatsDeniedContacts=23]="PrivacyGroupChatsDeniedContacts",e[e.PrivacyActiveSessions=24]="PrivacyActiveSessions",e[e.PrivacyBlockedUsers=25]="PrivacyBlockedUsers",e[e.Folders=26]="Folders",e[e.FoldersCreateFolder=27]="FoldersCreateFolder",e[e.FoldersEditFolder=28]="FoldersEditFolder",e[e.FoldersEditFolderFromChatList=29]="FoldersEditFolderFromChatList",e[e.FoldersIncludedChats=30]="FoldersIncludedChats",e[e.FoldersIncludedChatsFromChatList=31]="FoldersIncludedChatsFromChatList",e[e.FoldersExcludedChats=32]="FoldersExcludedChats",e[e.FoldersExcludedChatsFromChatList=33]="FoldersExcludedChatsFromChatList",e[e.TwoFaDisabled=34]="TwoFaDisabled",e[e.TwoFaNewPassword=35]="TwoFaNewPassword",e[e.TwoFaNewPasswordConfirm=36]="TwoFaNewPasswordConfirm",e[e.TwoFaNewPasswordHint=37]="TwoFaNewPasswordHint",e[e.TwoFaNewPasswordEmail=38]="TwoFaNewPasswordEmail",e[e.TwoFaNewPasswordEmailCode=39]="TwoFaNewPasswordEmailCode",e[e.TwoFaEnabled=40]="TwoFaEnabled",e[e.TwoFaChangePasswordCurrent=41]="TwoFaChangePasswordCurrent",e[e.TwoFaChangePasswordNew=42]="TwoFaChangePasswordNew",e[e.TwoFaChangePasswordConfirm=43]="TwoFaChangePasswordConfirm",e[e.TwoFaChangePasswordHint=44]="TwoFaChangePasswordHint",e[e.TwoFaTurnOff=45]="TwoFaTurnOff",e[e.TwoFaRecoveryEmailCurrentPassword=46]="TwoFaRecoveryEmailCurrentPassword",e[e.TwoFaRecoveryEmail=47]="TwoFaRecoveryEmail",e[e.TwoFaRecoveryEmailCode=48]="TwoFaRecoveryEmailCode",e[e.TwoFaCongratulations=49]="TwoFaCongratulations"}(d||(d={})),function(e){e[e.ChatList=0]="ChatList",e[e.GlobalSearch=1]="GlobalSearch",e[e.Settings=2]="Settings",e[e.Contacts=3]="Contacts",e[e.Archived=4]="Archived",e[e.NewChannelStep1=5]="NewChannelStep1",e[e.NewChannelStep2=6]="NewChannelStep2",e[e.NewGroupStep1=7]="NewGroupStep1",e[e.NewGroupStep2=8]="NewGroupStep2"}(u||(u={})),function(e){e[e.ChatList=0]="ChatList",e[e.Media=1]="Media",e[e.Links=2]="Links",e[e.Files=3]="Files",e[e.Music=4]="Music",e[e.Voice=5]="Voice"}(a||(a={})),function(e){e[e.ChatInfo=0]="ChatInfo",e[e.UserInfo=1]="UserInfo",e[e.Search=2]="Search",e[e.Management=3]="Management",e[e.StickerSearch=4]="StickerSearch",e[e.GifSearch=5]="GifSearch",e[e.PollResults=6]="PollResults",e[e.AddingMembers=7]="AddingMembers"}(s||(s={})),function(e){e[e.Inline=0]="Inline",e[e.ScheduledInline=1]="ScheduledInline",e[e.SharedMedia=2]="SharedMedia",e[e.ProfileAvatar=3]="ProfileAvatar",e[e.SettingsAvatar=4]="SettingsAvatar",e[e.MiddleHeaderAvatar=5]="MiddleHeaderAvatar",e[e.Album=6]="Album",e[e.ScheduledAlbum=7]="ScheduledAlbum",e[e.SearchResult=8]="SearchResult"}(i||(i={})),function(e){e[e.Inline=0]="Inline",e[e.SharedMedia=1]="SharedMedia",e[e.Search=2]="Search"}(c||(c={})),function(e){e[e.Idle=0]="Idle",e[e.InProgress=1]="InProgress",e[e.Complete=2]="Complete",e[e.Error=3]="Error"}(l||(l={})),function(e){e[e.Idle=0]="Idle",e[e.InProgress=1]="InProgress",e[e.Complete=2]="Complete",e[e.Error=3]="Error"}(f||(f={})),function(e){e[e.Idle=0]="Idle",e[e.InProgress=1]="InProgress",e[e.Complete=2]="Complete",e[e.Error=3]="Error"}(h||(h={})),function(e){e[e.Closed=0]="Closed",e[e.InProgress=1]="InProgress",e[e.Loading=2]="Loading"}(m||(m={})),function(e){e[e.Profile=0]="Profile",e[e.SharedMedia=1]="SharedMedia",e[e.MemberList=2]="MemberList"}(p||(p={})),function(e){e[e.ShippingInfo=0]="ShippingInfo",e[e.Shipping=1]="Shipping",e[e.PaymentInfo=2]="PaymentInfo",e[e.Checkout=3]="Checkout"}(g||(g={}));const y="UPLOADING_WALLPAPER_SLUG";let v;!function(e){e[e.Initial=0]="Initial",e[e.ChatPrivacyType=1]="ChatPrivacyType",e[e.Discussion=2]="Discussion",e[e.ChannelSubscribers=3]="ChannelSubscribers",e[e.GroupType=4]="GroupType",e[e.GroupPermissions=5]="GroupPermissions",e[e.GroupRemovedUsers=6]="GroupRemovedUsers",e[e.GroupUserPermissionsCreate=7]="GroupUserPermissionsCreate",e[e.GroupUserPermissions=8]="GroupUserPermissions",e[e.ChatAdministrators=9]="ChatAdministrators",e[e.GroupRecentActions=10]="GroupRecentActions",e[e.ChatAdminRights=11]="ChatAdminRights",e[e.GroupMembers=12]="GroupMembers"}(v||(v={}))},9933:(e,t,n)=>{n.d(t,{c:()=>d,j:()=>u});var r=n(9118);let o;function d(e,t){t||(o&&!o.isCancelled&&(o.isCancelled=!0),o=t={isCancelled:!1}),(0,r.T2)((()=>{!t.isCancelled&&e()&&d(e,t)}))}function u(e){(0,r.T2)((()=>{e()&&u(e)}))}},7358:(e,t,n)=>{n.d(t,{w:()=>o});var r=n(3716);function o(e){"function"==typeof window.navigator.setAppBadge&&window.navigator.setAppBadge(e).catch((e=>{r.eM&&console.error(e)}))}},275:(e,t,n)=>{function r(e,t){if(e===t)return!0;const n=Object.keys(e),r=n.length;if(r!==Object.keys(t).length)return!1;if(0===r)return!0;for(let o=0;o(e[r]!==t[r]&&n.push(`${r}: ${e[r]} => ${t[r]}`),n)),[])}n.d(t,{Z:()=>r,c:()=>o})},6752:(e,t,n)=>{n.d(t,{Z:()=>r});const r=(...e)=>e.filter(Boolean).join(" ")},9524:(e,t,n)=>{n.d(t,{Type:()=>o,fetch:()=>d,save:()=>u,clear:()=>a});const r=self.caches;let o;async function d(e,t,n,d=!1){if(r)try{const u=new Request(t.replace(/:/g,"_")),a=await r.open(e),s=await a.match(u);if(!s)return;const i=s.headers.get("Content-Type");switch(n){case o.Text:return await s.text();case o.Blob:{if(t.startsWith("avatar")&&i&&i.startsWith("text"))return;const e=await s.blob();if(t.startsWith("sticker"))return new Blob([e],{type:"image/webp"});const n=!e.type||!d&&e.type.includes("html");let r=e.type||i;return n&&r?(d||(r=r.replace(/html/gi,"")),new Blob([e],{type:r})):e}case o.Json:return await s.json();default:return}}catch(e){return void console.warn(e)}}async function u(e,t,n){if(r)try{const o="string"==typeof n||n instanceof Blob?n:JSON.stringify(n),d=new Request(t.replace(/:/g,"_")),u=new Response(o),a=await r.open(e);return await a.put(d,u)}catch(e){return void console.warn(e)}}async function a(e){try{if(!r)return;return await r.delete(e)}catch(e){return void console.warn(e)}}!function(e){e[e.Text=0]="Text",e[e.Blob=1]="Blob",e[e.Json=2]="Json"}(o||(o={}))},3989:(e,t,n)=>{n.d(t,{Z:()=>o});var r=n(517);function o(e){return(0,r.Z)({onEsc:e})}},517:(e,t,n)=>{n.d(t,{Z:()=>d});const r={Enter:"onEnter",Backspace:"onBackspace",Delete:"onDelete",Esc:"onEsc",Escape:"onEsc",ArrowUp:"onUp",ArrowDown:"onDown",ArrowLeft:"onLeft",ArrowRight:"onRight",Tab:"onTab"},o={onEnter:[],onDelete:[],onBackspace:[],onEsc:[],onUp:[],onDown:[],onLeft:[],onRight:[],onTab:[]};function d(e){return u()||document.addEventListener("keydown",a,!0),Object.keys(e).forEach((t=>{const n=e[t];if(!n)return;const r=o[t];r&&r.push(n)})),()=>{!function(e){Object.keys(e).forEach((t=>{const n=e[t],r=o[t];if(r){const e=r.findIndex((e=>e===n));-1!==e&&r.splice(e,1)}})),u()||document.removeEventListener("keydown",a,!1)}(e)}}function u(){return Object.values(o).some((e=>Boolean(e.length)))}function a(e){const t=r[e.key];if(!t)return;const{length:n}=o[t];n&&(e.stopPropagation(),(0,o[t][n-1])(e))}},790:(e,t,n)=>{n.d(t,{$Y:()=>u,_F:()=>a,kj:()=>s,mr:()=>c,VX:()=>l,Tu:()=>f,np:()=>h,j1:()=>m,ZK:()=>g,k9:()=>y,rM:()=>v,xH:()=>b,xk:()=>I,IS:()=>C});const r=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],o=["January","February","March","April","May","June","July","August","September","October","November","December"],d=o.map((e=>e.toLowerCase()));function u(e){const t=new Date(e);return t.setHours(0,0,0,0),t}function a(e){return u(e).getTime()}function s(e){const t=new Date(1e3*e);return`${t.getFullYear()}-${t.getMonth()}`}function i(e){return`${e.getFullYear()}-${e.getMonth()+1}-${e.getDate()}`}function c(e,t){const n="number"==typeof e?new Date(e):e,r=t.timeFormat||"24h";let o=n.getHours(),d="";return"12h"===r&&(d=o>=12?" PM":" AM",o=o>12?o%12:o),`${String(o).padStart(2,"0")}:${String(n.getMinutes()).padStart(2,"0")}${d}`}function l(e,t){const n="number"==typeof t?new Date(t):t,o=u(new Date);if(n>=o)return c(n,e);const d=new Date(o);if(d.setDate(o.getDate()-7),n>=d)return e(`Weekday.Short${r[n.getDay()]}`);const a=n.getFullYear()!==o.getFullYear(),s=e(a?"formatDateScheduleYear":"formatDateSchedule")||(a?"d MMM yyyy":"d MMM");return p(e,n,s)}function f(e,t){const n="number"==typeof t?new Date(t):t,r=e("formatterYearMax")||"dd.MM.yyyy";return p(e,n,r)}function h(e,t,n=!1){const r=e(n?"formatterMonthYear2":"formatterMonthYear")||"MMM yyyy";return p(e,t,r)}function m(e,t,n=!1,o=!1,d){const a="number"==typeof t?new Date(t):t,s=u(new Date);if(!o){if(i(a)===i(s))return(d||!n?E:S)(e("Weekday.Today"));const t=new Date(s);if(t.setDate(s.getDate()-1),i(a)===i(t))return(d||!n?E:S)(e("Weekday.Yesterday"));const o=new Date(s),u=new Date(s);if(o.setDate(s.getDate()-7),u.setDate(s.getDate()+7),a>=o&&a<=u){const t=r[a.getDay()];return(d||!n?E:S)(e(n?`Weekday.Short${t}`:`Weekday.${t}`))}}const c=a.getFullYear()!==s.getFullYear(),l=e(n?c?"formatDateScheduleYear":"formatDateSchedule":c?"chatFullDate":"chatDate")||"d MMMM yyyy";return(d||!n?E:S)(p(e,a,l))}function p(e,t,n){const r=t.getDate(),d=t.getMonth();return n.replace("LLLL",e(o[d])).replace("MMMM",e(`Month.Gen${o[d]}`)).replace("MMM",e(`Month.Short${o[d]}`)).replace("MM",String(d+1).padStart(2,"0")).replace("dd",String(r).padStart(2,"0")).replace("d",String(r)).replace("yyyy",String(t.getFullYear()))}function g(e,t,n){const r="number"==typeof t?new Date(t):t;return`${m(e,r,!0,void 0,n)}, ${c(r,e)}`}function y(e,t){const n=Math.floor(e/3600),r=Math.floor(e%3600/60),o=Math.floor(e%3600%60),d=t?Math.floor(t/3600):0,u=t?Math.floor(t%3600/60):0;let a="";return n>0||d>0?(a+=`${String(n).padStart(2,"0")}:`,a+=`${String(r).padStart(2,"0")}:`):a+=u>=10?`${String(r).padStart(2,"0")}:`:`${String(r)}:`,a+=String(o).padStart(2,"0"),a}function v(e){const t=[];let n=e%1e3;e-=n,n=Math.floor(n/10);const r=(e=Math.floor(e/1e3))%60;e-=r;const o=(e=Math.floor(e/60))%60;e-=o;const d=(e=Math.floor(e/60))%60;return d>0&&t.push(String(d).padStart(2,"0")),t.push(String(o).padStart(d>0?2:1,"0")),t.push(String(r).padStart(2,"0")),`${t.join(":")},${String(n).padStart(2,"0")}`}function b(e,t="en-US"){return e.toLocaleString(t,{year:"numeric",month:"short",day:"numeric"})}function w(e,t,n=2021){if(t>11||e>31)return!1;const r=new Date(n,t,e);return!Number.isNaN(r.getTime())&&r.getDate()===e}function I(e=""){const t=e.match(/\d{1,2}\s[a-zA-Z]{3,}/),n=e.match(/[a-zA-Z]{3,}\s\d{1,2}/),r=e.match(/\d{1,2}[./-]\d{1,2}([./-]\d{2,4})?/);if(!t&&!r&&!n)return;if(r){const[t,n,r]=e.split(/[./-]/).map(Number);return r&&r<2015||!w(t,n-1,r||void 0)?void 0:`${r?`${r}-`:""}${String(n).padStart(2,"0")}-${String(t).padStart(2,"0")}`}const o=e.split(" "),u=t?o[0]:o[1],a=(t?o[1]:o[0]).toLowerCase(),s=d.findIndex((e=>e.startsWith(a)));return-1!==s&&w(Number(u),s)?`${String(s+1).padStart(2,"0")}-${String(u).padStart(2,"0")}`:void 0}function C(e){return e+86400}function S(e){return`${e[0].toLowerCase()}${e.slice(1)}`}function E(e){return`${e[0].toUpperCase()}${e.slice(1)}`}},4284:(e,t,n)=>{n.d(t,{g6:()=>a,U_:()=>s,NM:()=>i,Wg:()=>c});var r=n(3681);const o=["female_sign","male_sign","medical_symbol"],d=[[/\u{1f3f3}\u200d\u{1f308}/gu,"🏳️‍🌈"],[/\u{1f3f3}\u200d\u26a7\ufe0f/gu,"🏳️‍⚧️"],[/\u{1f937}\u200d\u2642/gu,"🤷‍♂️"]];function u(e){const t=e.split("-").map((e=>parseInt(e,16)));return String.fromCodePoint(...t)}function a(e){if(!e.match(r.Z))return e;for(const[t,n]of d)e=e.replace(t,n);return e}function s(e){let t;if(1===e.length)t=e.charCodeAt(0).toString(16).padStart(4,"0");else{const n=[];for(let t=0;t=55296&&e.charCodeAt(t)<=56319?e.charCodeAt(t+1)>=56320&&e.charCodeAt(t+1)<=57343&&n.push(1024*(e.charCodeAt(t)-55296)+(e.charCodeAt(t+1)-56320)+65536):(e.charCodeAt(t)<55296||e.charCodeAt(t)>57343)&&n.push(e.charCodeAt(t));t=n.map((e=>e.toString(16).padStart(4,"0"))).join("-")}return t}function i(e){const t={categories:[],emojis:{}};for(let n=0;ne.codePointAt(0)+127397));return String.fromCodePoint(...n)}},7361:(e,t,n)=>{n.d(t,{cL:()=>N,wZ:()=>p,vX:()=>M,op:()=>C,cj:()=>m,jm:()=>h,pA:()=>T,m5:()=>P,I_:()=>E,fl:()=>y,s$:()=>g,Mc:()=>S,wB:()=>b,p7:()=>w,$b:()=>v,mh:()=>I,s0:()=>A,aZ:()=>L,Lt:()=>f,vn:()=>i,on:()=>d});var r=n(3716);let o;function d(){return Boolean(o)}var u,a;new Promise((e=>{const t=new Image;t.src="data:image/webp;base64,UklGRjoAAABXRUJQVlA4IC4AAACyAgCdASoCAAIALmk0mk0iIiIiIgBoSygABc6WWgAA/veff/0PP8bA//LwYAAA";const n=()=>{e(2===t.height)};t.onload=n,t.onerror=n})).then((e=>{o=e}));let s=null!==(u=(a=window).matchMedia)&&void 0!==u&&u.call(a,"(prefers-color-scheme: dark)").matches?"dark":"light";function i(){return s}function c(e){s=e.matches?"dark":"light"}const l=window.matchMedia("(prefers-color-scheme: dark)");"function"==typeof l.addEventListener?l.addEventListener("change",c):"function"==typeof l.addListener&&l.addListener(c);const f=function(){const{userAgent:e,platform:t}=window.navigator;let n;return-1!==["Macintosh","MacIntel","MacPPC","Mac68K"].indexOf(t)?n="macOS":-1!==["iPhone","iPad","iPod"].indexOf(t)?n="iOS":-1!==["Win32","Win64","Windows","WinCE"].indexOf(t)?n="Windows":/Android/.test(e)?n="Android":/Linux/.test(t)&&(n="Linux"),n}(),h="macOS"===f,m="iOS"===f,p="Android"===f,g=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),y=window.matchMedia("(display-mode: standalone)").matches||window.navigator.standalone||document.referrer.includes("android-app://"),v=window.matchMedia("(pointer: coarse)").matches,b=window.innerWidth<=r.l3||window.innerWidth<=r.u_&&window.innerHeight<=r.rO,w=!b&&window.innerWidth<=r.ks,I=Boolean(navigator.mediaDevices&&"getUserMedia"in navigator.mediaDevices&&(window.AudioContext||window.webkitAudioContext)),C=(document.documentElement.style,f&&(h||m)),S="serviceWorker"in navigator,E=S,P=(window,Boolean((new Audio).canPlayType("audio/ogg; codecs=opus"))),M=!r.Cg&&"filter"in(document.createElement("canvas").getContext("2d")||{}),A=p?"slide-fade":m?"slide-layers":"push-slide",k=document.createElement("video"),T=Boolean(k.canPlayType(r.Ng).replace("no","")||m);T&&r.wG.add(r.Ng);const N=window.devicePixelRatio||1,L=!0},1394:(e,t,n)=>{n.d(t,{A9:()=>d,YJ:()=>u,hl:()=>a,pt:()=>s,jj:()=>i,ud:()=>c,gm:()=>l,ao:()=>f});var r=n(9118);function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function d(e){const t=e.split(","),n=t[0].match(/:(.*?);/)[1],r=atob(t[1]);let o=r.length;const d=new Uint8Array(o);for(;o--;)d[o]=r.charCodeAt(o);return new Blob([d],{type:n})}function u(e){return new Promise(((t,n)=>{const r=new FileReader;r.onload=e=>{const{result:r}=e.target||{};"string"==typeof r&&t(r),n(new Error("Failed to read blob"))},r.onerror=n,r.readAsDataURL(e)}))}function a(e,t){return new File([e],t,{lastModified:Date.now(),type:e.type})}function s(e){return new Promise(((t,n)=>{const r=new Image;r.onload=()=>t(r),r.onerror=n,r.src=e}))}function i(e){return new Promise(((t,n)=>{const r=document.createElement("video");r.volume=0,r.onloadedmetadata=()=>t(r),r.onerror=n,r.src=e}))}async function c(e){const t=await i(e);return Promise.race([(0,r.wO)(2e3),new Promise(((e,n)=>{t.onseeked=()=>{t.videoWidth&&t.videoHeight||e(void 0);const n=document.createElement("canvas");n.width=t.videoWidth,n.height=t.videoHeight,n.getContext("2d").drawImage(t,0,0),e(n.toDataURL("image/jpeg"))},t.onerror=n,t.currentTime=Math.min(t.duration,1)}))])}async function l(e){return(await fetch(e)).blob()}function f(e){const t=document.createElement("canvas");return t.width=e.width,t.height=e.height,t.getContext("2d").drawImage(e,0,0),t}"undefined"==typeof File&&(self.File=class extends Blob{constructor(e,t,n){if(n){const{type:t,...r}=n;super(e,{type:t}),o(this,"name",void 0),Object.assign(this,r)}else super(e),o(this,"name",void 0);this.name=t}})},9937:(e,t,n)=>{function r(e,t,n="en"){return new Intl.NumberFormat(n,{style:"currency",currency:t}).format("JPY"===t?e:e/100)}n.d(t,{x:()=>r})},6926:(e,t,n)=>{n.d(t,{Z:()=>r});const r=e=>{let t;do{t=String(Math.random()).replace("0.","id")}while(e.hasOwnProperty(t));return t}},1947:(e,t,n)=>{n.d(t,{ZP:()=>d,J_:()=>u});const r={CHAT_RESTRICTED:"You can't send messages in this chat, you were restricted",CHAT_WRITE_FORBIDDEN:"You can't write in this chat",CHAT_SEND_POLL_FORBIDDEN:"You can't create polls in this chat",CHAT_SEND_STICKERS_FORBIDDEN:"You can't send stickers in this chat",CHAT_SEND_GIFS_FORBIDDEN:"You can't send gifs in this chat",CHAT_SEND_MEDIA_FORBIDDEN:"You can't send media in this chat",CHAT_LINK_EXISTS:"The chat is public, you can't hide the history to new users",SLOWMODE_WAIT_X:"Slowmode is enabled in this chat: you must wait for the specified number of seconds before sending another message to the chat.",USER_BANNED_IN_CHANNEL:"You're banned from sending messages in supergroups / channels",USER_IS_BLOCKED:"You were blocked by this user",YOU_BLOCKED_USER:"You blocked this user",IMAGE_PROCESS_FAILED:"Failure while processing image",MEDIA_EMPTY:"The provided media object is invalid",MEDIA_INVALID:"Media invalid",PHOTO_EXT_INVALID:"The extension of the photo is invalid",PHOTO_INVALID_DIMENSIONS:"The photo dimensions are invalid",PHOTO_SAVE_FILE_INVALID:"Internal issues, try again later",MESSAGE_DELETE_FORBIDDEN:"You can't delete one of the messages you tried to delete, most likely because it is a service message.",MESSAGE_POLL_CLOSED:"Poll closed",MESSAGE_EDIT_TIME_EXPIRED:"You can't edit this message anymore.",CHAT_ADMIN_REQUIRED:"You must be an admin in this chat to do this",PINNED_DIALOGS_TOO_MUCH:"Sorry, you can only pin 5 chats to the top",DIALOG_FILTERS_TOO_MUCH:"Sorry, you can't have more than 10 folders",CHANNEL_PRIVATE:"This channel is private",MEDIA_CAPTION_TOO_LONG:"The provided caption is too long",ADDRESS_STREET_LINE1_INVALID:"The address you provided is not valid",ADDRESS_STREET_LINE2_INVALID:"The address you provided is not valid",ADDRESS_CITY_INVALID:"The city you provided is not valid",ADDRESS_COUNTRY_INVALID:"The country you provided is not valid",ADDRESS_POSTCODE_INVALID:"The postcode you provided is not valid",ADDRESS_STATE_INVALID:"The state you provided is not valid",REQ_INFO_NAME_INVALID:"The name you provided is not valid",REQ_INFO_PHONE_INVALID:"The phone you provided is not valid",REQ_INFO_EMAIL_INVALID:"The email you provided is not valid",LINK_NOT_MODIFIED:"This discussion is already linked to the channel",MESSAGE_TOO_LONG:"Message is too long",SERVICE_WORKER_DISABLED:"Service Worker is disabled. Please reload the page without holding key.",MESSAGE_TOO_LONG_PLEASE_REMOVE_CHARACTERS:"The provided message is too long. Please remove {EXTRA_CHARS_COUNT} character{PLURAL_S}.",FRESH_RESET_AUTHORISATION_FORBIDDEN:"You can’t logout other sessions if less than 24 hours have passed since you logged on the current session",BOTS_TOO_MUCH:"There are too many bots in this chat/channel",BOT_GROUPS_BLOCKED:"This bot can't be added to groups",USERS_TOO_MUCH:"The maximum number of users has been exceeded",USER_CHANNELS_TOO_MUCH:"One of the users you tried to add is already in too many channels/supergroups",USER_KICKED:"This user was kicked from this supergroup/channel",USER_NOT_MUTUAL_CONTACT:"The provided user is not a mutual contact",USER_PRIVACY_RESTRICTED:"The user's privacy settings do not allow you to do this",INVITE_HASH_EMPTY:"The invite hash is empty",INVITE_HASH_EXPIRED:"The invite link has expired",INVITE_HASH_INVALID:"The invite hash is invalid",CHANNELS_TOO_MUCH:"You have joined too many channels/supergroups",USER_ALREADY_PARTICIPANT:"You already in the group",SCHEDULE_DATE_INVALID:"Invalid schedule date provided",WALLPAPER_DIMENSIONS_INVALID:"The wallpaper dimensions are invalid, please select another file"},o={ADDRESS_STREET_LINE1_INVALID:{field:"streetLine1",message:"Incorrect street address"},ADDRESS_STREET_LINE2_INVALID:{field:"streetLine2",message:"Incorrect street address"},ADDRESS_CITY_INVALID:{field:"city",message:"Incorrect city"},ADDRESS_COUNTRY_INVALID:{field:"countryIso2",message:"Incorrect country"},ADDRESS_POSTCODE_INVALID:{field:"postCode",message:"Incorrect post code"},ADDRESS_STATE_INVALID:{field:"state",message:"Incorrect state"},REQ_INFO_NAME_INVALID:{field:"fullName",message:"Incorrect name"},REQ_INFO_PHONE_INVALID:{field:"phone",message:"Incorrect phone"},REQ_INFO_EMAIL_INVALID:{field:"email",message:"Incorrect email"}};function d(e){const{message:t,isSlowMode:n,textParams:o}=e;if(n){const e=t.indexOf(" (caused by");return e>0?t.substring(0,e):t}let d=r[t];return d&&o&&(d=Object.keys(o).reduce(((e,t)=>e.replace(t,o[t])),d)),d}function u(e){return o[e.message]}},3592:(e,t,n)=>{n.d(t,{S:()=>d}),n(3716);var r=n(9118);function o(e){e.preventDefault(),d(e instanceof ErrorEvent?e.error:e.reason)}function d(e){console.error(e)}window.addEventListener("error",o),window.addEventListener("unhandledrejection",o),(0,r.P2)(window.alert,1e3)},782:(e,t,n)=>{function r(e,t){return e.reduce(((e,n)=>(e[n[t]]=n,e)),{})}function o(e,t){return Object.keys(e).reduce(((n,r,o)=>(n[r]=t(e[r],r,o,e),n)),{})}function d(e,t){return t.reduce(((t,n)=>(t[n]=e[n],t)),{})}function u(e,t){return t.reduce(((t,n)=>(e[n]&&(t[n]=e[n]),t)),{})}function a(e,t){const n=new Set(t.map(String));return d(e,Object.keys(e).filter((e=>!n.has(e))))}function s(e,t,n="asc"){return e.sort(((e,r)=>{if(Array.isArray(t)){const[o,d]=Array.isArray(n)?n:[n,n],[u,a]=t;let s,i;if("function"==typeof u?(s=u(e)||0,i=u(r)||0):"string"==typeof u&&(s=e[u]||0,i=r[u]||0),s!==i)return"asc"===o?s-i:i-s;{let t,n;return"function"==typeof a?(t=a(e)||0,n=a(r)||0):"string"==typeof a&&(t=e[a]||0,n=r[a]||0),"asc"===d?t-n:n-t}}let o,d;return"function"==typeof t?(o=t(e)||0,d=t(r)||0):"string"==typeof t&&(o=e[t]||0,d=r[t]||0),"asc"===n?o-d:d-o}))}function i(e){return e.reduce(((e,t)=>Array.isArray(t)?e.concat(t):(e.push(t),e)),[])}function c(e){return Array.from(new Set(e))}function l(e){return e.filter(Boolean)}function f(e,t){return e.length===t.length&&e.every(((e,n)=>e===t[n]))}function h(e,t){return e[0]<=t[t.length-1]&&e[e.length-1]>=t[0]}function m(e,t){return e.filter((e=>t.has(e)))}function p(e,t){const n=[];for(let r=0;r(t[n]=g(e[n]),t)),{})}function y(e,t){let n=e.length;for(;n--;)if(t(e[n],n,e))return e[n]}n.d(t,{ee:()=>r,Q8:()=>o,ei:()=>d,q0:()=>u,CE:()=>a,Xo:()=>s,xH:()=>i,Tw:()=>c,oA:()=>l,et:()=>f,YE:()=>h,eL:()=>m,Vl:()=>p,Xh:()=>g,dF:()=>y})},663:(e,t,n)=>{n.d(t,{ll:()=>m,i0:()=>b,Pn:()=>w,m0:()=>I,qf:()=>C});var r=n(5116),o=n(3716),d=n(9524),u=n(1226),a=n(2155);const s=/%\d?\$?[sdf@]/g,i=["value","zeroValue","oneValue","twoValue","fewValue","manyValue","otherValue"],c={en:e=>1!==e?6:2,ar:e=>0===e?1:1===e?2:2===e?3:e%100>=3&&e%100<=10?4:e%100>=11?5:6,ca:e=>1!==e?6:2,de:e=>1!==e?6:2,es:e=>1!==e?6:2,fa:e=>e>1?6:2,fr:e=>e>1?6:2,id:()=>0,it:e=>1!==e?6:2,ko:()=>0,ms:()=>0,nl:e=>1!==e?6:2,pl:e=>1===e?2:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?4:5,pt_BR:e=>e>1?6:2,ru:e=>e%10==1&&e%100!=11?2:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?4:5,tr:e=>e>1?6:2,uk:e=>e%10==1&&e%100!=11?2:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?4:5,uz:e=>e>1?6:2},l=new Map;let f,h;const{addCallback:m,removeCallback:p,runCallbacks:g}=function(){const e=[];function t(t){const n=e.indexOf(t);-1!==n&&e.splice(n,1)}return{runCallbacks:function(...t){e.forEach((e=>{e(...t)}))},addCallback:function(n){return e.push(n),()=>{t(n)}},removeCallback:t}}();let y,v;const b=(e,t,n)=>{var r,o;if(void 0!==t){const r=Array.isArray(t)?JSON.stringify(t):t,o=l.get(`${e}_${r}_${n}`);if(o)return o}if(!f&&!h)return e;const d=(null===(r=f)||void 0===r?void 0:r[e])||(null===(o=h)||void 0===o?void 0:o[e]);return d?E(d,e,t,n):(h||S(),e)};async function w(e,t){let n=await d.fetch(o.ee,`${o.$O}_${e}_${t}`,d.Type.Json);return n||(n=await async function(e,t,n){const r=await(0,u.t9)("fetchLangStrings",{langPack:e,langCode:t,keys:[n]});if(null!=r&&r.length)return await d.save(o.ee,`${e}_${t}_${n}`,r[0]),r[0]}(o.$O,e,t)),E(n,t)}async function I(e,t,n=!1){if(f&&e===y)return void(t&&t());let a=await d.fetch(o.ee,e,d.Type.Json);if(!a&&(n&&await S(),a=await async function(e){const t=await(0,u.t9)("fetchLangPack",{sourceLangPacks:o.Bg,langCode:e});if(t)return await d.save(o.ee,e,t.langPack),t.langPack}(e),!a))return;l.clear(),y=e,f=a,document.documentElement.lang=e;const{languages:s,timeFormat:i}=(0,r.Rd)().settings.byKey,c=null==s?void 0:s.find((t=>t.langCode===e));b.isRtl=Boolean(null==c?void 0:c.rtl),b.code=e,b.timeFormat=i,t&&t(),g()}function C(e){e&&e===v||(v=e,b.timeFormat=e,g())}async function S(){h||(h=(await n.e(915).then(n.bind(n,1915))).default,g())}function E(e,t,n,r){const d=e?e["number"==typeof n?function(e){const t=y||o.sR,n=c[t]?c[t](e):0;return i[n]}(n):"value"]:void 0;if(!d||!d.trim()){const e=t.split(".");return e[e.length-1]}if(void 0!==n){const e=function(e,t){t=Array.isArray(t)?t:[t];const n=e.split(s),r=n.shift();return n.reduce(((e,n,r)=>`${e}${String(t[r]||"")}${n}`),r||"")}(d,"i"===r?(0,a.kh)(n):n),o=Array.isArray(n)?JSON.stringify(n):n;return l.set(`${t}_${o}_${r}`,e),e}return d}},647:(e,t,n)=>{n.d(t,{cC:()=>b,he:()=>y,UV:()=>v,Iq:()=>w});var r=n(6137),o=n(3716),d=n(1226),u=n(9524),a=n(1394),s=n(7361);const i=48e3;async function c(e){const t=await new Response(e).arrayBuffer();return new Promise((e=>{const r=new Uint8Array(t);let o=new Worker(new URL(n.p+n.u(745),n.b)),d=new Worker(new URL(n.p+n.u(993),n.b));o.onmessage=e=>{null===e.data?d.postMessage({command:"done"}):d.postMessage({command:"encode",buffers:e.data},e.data.map((({buffer:e})=>e)))},d.onmessage=t=>{"page"===t.data.message&&(e(new Blob([t.data.page],{type:"audio/wav"})),o.terminate(),o=void 0,d.terminate(),d=void 0)},d.postMessage({command:"init",wavBitDepth:16,wavSampleRate:i}),o.postMessage({command:"init",decoderSampleRate:i,outputBufferSampleRate:i}),o.postMessage({command:"decode",pages:r},[r.buffer])}))}var l=n(862);const f={[r.IU.BlobUrl]:u.Type.Blob,[r.IU.Lottie]:u.Type.Json,[r.IU.Progressive]:void 0,[r.IU.Stream]:void 0},h=new Map,m=new Map,p=new Map,g=new Map;function y(e,t,n=!1,i,v){if(t===r.IU.Progressive)return s.I_?function(e){const t=`./progressive/${e}`;return h.set(e,t),Promise.resolve(t)}(e):y(e,r.IU.BlobUrl,n,i,v);if(!m.has(e)){const i=async function(e,t,n){if(!o.Cy){const r=e.startsWith("avatar")?o.SG:o.lW,d=await u.fetch(r,e,f[t],n);if(d){let t=d;if("audio/ogg"!==d.type||s.m5||(t=await c(t)),"image/webp"===d.type&&!(0,s.on)()&&t){const n=await(0,l._y)(e,t);n&&(t=n)}const n=C(t);return h.set(e,n),n}}if(t===r.IU.Stream){const n=new MediaSource,r=URL.createObjectURL(n);let o=!1;return n.addEventListener("sourceopen",(()=>{if(o)return;o=!0;const r=n.addSourceBuffer("audio/mpeg"),u=I(e,n,r);g.set(e,u),(0,d.t9)("downloadMedia",{url:e,mediaFormat:t},u)})),h.set(e,r),r}const i=I(e);g.set(e,i);const m=await(0,d.t9)("downloadMedia",{url:e,mediaFormat:t,isHtmlAllowed:n},i);if(!m)throw new Error(`Failed to fetch media ${e}`);let{prepared:p,mimeType:y}=m;if("audio/ogg"===y&&!s.m5){const e=await(0,a.gm)(p);URL.revokeObjectURL(p);const t=await c(e);p=C(t),y=t.type}if("image/webp"===y&&!(0,s.on)()){const t=await(0,a.gm)(p);URL.revokeObjectURL(p);const n=await(0,l._y)(e,t);n&&(p=C(n))}return h.set(e,p),p}(e,t,n).catch((e=>{o.eM&&console.warn(e)})).finally((()=>{m.delete(e),p.delete(e),g.delete(e)}));m.set(e,i)}if(i&&v){let t=p.get(e);t||(t=new Map,p.set(e,t)),t.set(v,i)}return m.get(e)}function v(e){return h.get(e)}function b(e){p.forEach(((t,n)=>{t.forEach((t=>{if(t===e){const e=g.get(n);if(!e)return;(0,d.u3)(e),g.delete(n),p.delete(n)}}))}))}function w(e,t){const n=p.get(e);n&&n.delete(t)}function I(e,t,n){const r=(o,d)=>{var u;null===(u=p.get(e))||void 0===u||u.forEach((e=>{e(o),e.isCanceled&&(r.isCanceled=!0)})),1===o&&(null==t||t.endOfStream()),d&&(null==n||n.appendBuffer(d))};return r}function C(e){return e instanceof Blob?URL.createObjectURL(e):e}s.I_&&navigator.serviceWorker.addEventListener("message",(async e=>{const{type:t,messageId:n,params:o}=e.data;if("requestPart"!==t)return;const u=await(0,d.t9)("downloadMedia",{mediaFormat:r.IU.Progressive,...o});if(!u)return;const{arrayBuffer:a,mimeType:s,fullSize:i}=u;navigator.serviceWorker.controller.postMessage({type:"partResponse",messageId:n,result:{arrayBuffer:a,mimeType:s,fullSize:i}},[a])}))},735:(e,t,n)=>{n.d(t,{D:()=>r});const r=[]},9203:(e,t,n)=>{n.d(t,{gl:()=>o,$y:()=>a,o5:()=>s,Qt:()=>c});var r=n(3716);let o;!function(e){e[e.Auth=0]="Auth",e[e.Main=1]="Main",e[e.Extra=2]="Extra"}(o||(o={}));const d={},u={};async function a(e,t){if(!d[e]){switch(e){case o.Auth:d[o.Auth]=n.e(133).then(n.bind(n,1133));break;case o.Main:r.eM&&console.log(">>> START LOAD MAIN BUNDLE"),d[o.Main]=Promise.all([n.e(306),n.e(325)]).then(n.bind(n,325));break;case o.Extra:d[o.Extra]=Promise.all([n.e(306),n.e(701)]).then(n.bind(n,9701))}d[e].then(l)}const a=await d[e];return u[e]||(u[e]=a),s(e,t)}function s(e,t){const n=u[e];if(n)return n[t]}const i=[];function c(e){i.includes(e)||i.push(e)}function l(){i.forEach((e=>{e()}))}},8406:(e,t,n)=>{n.d(t,{q3:()=>v,Nz:()=>b,r1:()=>C,Ld:()=>E,zP:()=>P,Vr:()=>M,KC:()=>A});var r=n(1226),o=n(6137),d=n(2864),u=n(3716),a=n(5116),s=n(2858),i=n(663),c=n(1752),l=n(8085),f=n(7361),h=n(647),m=n(9118);function p(e){const t=e.toJSON();return JSON.stringify({endpoint:t.endpoint,keys:t.keys})}function g(){return!!f.Mc&&("showNotification"in ServiceWorkerRegistration.prototype?"denied"===Notification.permission?(u.eM&&console.warn("[PUSH] The user has blocked push notifications."),!1):"PushManager"in window||(u.eM&&console.warn("[PUSH] Push messaging isn't supported."),!1):(u.eM&&console.warn("[PUSH] Push notifications aren't supported."),!1))}const y=new Set;async function v(e,t){if(void 0!==e&&y.has(e))return;const{notificationSoundVolume:n}=(0,l.dZ)((0,a.Rd)()),r=t?t/10:n/10;if(0===r)return;const o=new Audio("./notification.mp3");o.volume=r,o.setAttribute("mozaudiochannel","notification"),void 0!==e&&(o.addEventListener("ended",(()=>{y.add(e)}),{once:!0}),setTimeout((()=>{y.delete(e)}),3e3));try{await o.play()}catch(e){u.eM&&console.warn("[PUSH] Unable to play notification sound")}}const b=(0,m.Ds)(v,1e3,!0,!1);async function w(){"Notification"in window&&(["granted","denied"].includes(Notification.permission)||await Notification.requestPermission())}async function I(e){const t=(0,a.Rd)(),n=(0,a.uC)();if(e)try{const t=p(e);return await(0,r.t9)("unregisterDevice",t),await e.unsubscribe(),void n.deleteDeviceToken()}catch(e){u.eM&&console.log("[PUSH] Unable to unsubscribe from push.",e)}t.push&&(await(0,r.t9)("unregisterDevice",t.push.deviceToken),n.deleteDeviceToken())}async function C(){if(!g())return;const e=await navigator.serviceWorker.ready,t=await e.pushManager.getSubscription();await I(t)}let S=!1;async function E(){if(!g())return void await w();const e=await navigator.serviceWorker.ready;let t=await e.pushManager.getSubscription();if(function(e){const t=(0,a.Rd)();return!t.push||!e||p(e)!==t.push.deviceToken||Date.now()-t.push.subscribedAt>432e5}(t)){await I(t);try{t=await e.pushManager.subscribe({userVisibleOnly:!0});const n=p(t);u.eM&&console.log("[PUSH] Received push subscription: ",n),await(0,r.t9)("registerDevice",n),(0,a.uC)().setDeviceToken(n)}catch(e){"denied"===Notification.permission?u.eM&&console.warn("[PUSH] The user has blocked push notifications."):u.eM&&(console.log("[PUSH] Unable to subscribe to push.",e),e.code===DOMException.ABORT_ERR&&await w())}}}async function P({chat:e,message:t}){const{hasWebNotifications:n}=await async function(){if(S)return(0,l.dZ)((0,a.Rd)());const[e,t]=await Promise.all([(0,r.t9)("fetchNotificationSettings",{serverTimeOffset:(0,a.Rd)().serverTimeOffset}),(0,r.t9)("fetchNotificationExceptions",{serverTimeOffset:(0,a.Rd)().serverTimeOffset})]);if(!e)return(0,l.dZ)((0,a.Rd)());let n=(0,c.BI)((0,a.Rd)(),e);return t&&(n=(0,c.aJ)(n,t)),(0,a.R3)(n),S=!0,(0,l.dZ)(n)}();if(!function(e){if(!S)return!1;const t=(0,a.Rd)();return!((0,s.i4)(e,(0,l.dZ)(t),(0,l.NJ)(t))||e.isNotJoined||!e.isListed||document.hasFocus())}(e))return;const f="Notification"in window?"denied"!==Notification.permission||(u.eM&&console.warn("[PUSH] The user has blocked push notifications."),!1):(u.eM&&console.warn("[PUSH] This browser does not support desktop notification"),!1);if(!n||!f)return void b(String(t.id)||e.id);if(!f)return;if(!t.id)return;const{title:m,body:p}=function(e,t){const n=(0,a.Rd)(),{senderId:r,replyToMessageId:o}=t,u=r?(0,l.dy)(n,r):void 0,c=(0,s.N5)(t),f=c&&o?(0,l.hj)(n,e.id,o):void 0,{targetUserIds:h,targetChatId:m}=c||{},p=h?h.map((e=>(0,l.dy)(n,e))).filter(Boolean):void 0,g=(0,s.zX)(e),y=g?(0,l.dy)(n,g):void 0;let v;if((0,s.Sm)(e,(0,l.dZ)(n),(0,l.NJ)(n)))if((0,s.Lo)(t)){const n=e&&((0,s.eA)(e)||t.senderId===t.chatId)?e:u;v=(0,d.D)(i.i0,t,n,p,f,m,{asPlain:!0})}else{const n=(0,s.zF)(i.i0,e.id,u),r=(0,s.MK)(i.i0,t);v=n?`${n}: ${r}`:r}else v="New message";return{title:(0,s.U)(i.i0,e,y),body:v}}(e,t),y=await async function(e){const t=(0,s.RT)(e);if(!t)return;let n=h.UV(t);return n||(await h.he(t,o.IU.BlobUrl),n=h.UV(t)),n}(e);if(g()){var v;null!==(v=navigator.serviceWorker)&&void 0!==v&&v.controller&&navigator.serviceWorker.controller.postMessage({type:"newMessageNotification",payload:{title:m,body:p,icon:y,chatId:e.id,messageId:t.id}})}else{const n=(0,a.uC)(),r={body:p,icon:y,badge:y,tag:String(t.id)};"vibrate"in navigator&&(r.vibrate=[200,100,200]);const o=new Notification(m,r);o.onclick=()=>{o.close(),n.focusMessage({chatId:e.id,messageId:t.id}),window.focus&&window.focus()},o.onshow=()=>{b(String(t.id)||e.id)}}}function M(e){var t;!u.Cg&&null!==(t=navigator.serviceWorker)&&void 0!==t&&t.controller&&navigator.serviceWorker.controller.postMessage({type:"closeMessageNotifications",payload:e})}function A(){var e;null!==(e=navigator.serviceWorker)&&void 0!==e&&e.controller&&navigator.serviceWorker.controller.postMessage({type:"clientReady"})}},6272:(e,t,n)=>{n.d(t,{U9:()=>u,g3:()=>a,un:()=>s,WZ:()=>i});var r=n(782);const o="X",d="XXX XXX XXX XXX";function u(e,t){return e.filter((e=>e.iso2===t))}function a(e,t=""){var n;let o=t.replace(/[^\d+]+/g,"");o.startsWith("+")&&(o=o.substr(1));const d=e.filter((e=>o.startsWith(e.countryCode))),u=(0,r.xH)(d.map((e=>(e.prefixes||[""]).map((t=>({code:`${e.countryCode}${t}`,country:e})))))).filter((({code:e})=>o.startsWith(e))).sort(((e,t)=>e.code.length-t.code.length));return null===(n=u[u.length-1])||void 0===n?void 0:n.country}function s(e,t){let n=e.replace(/[^\d]+/g,"");if(t)n=n.substr(t.countryCode.length);else if(e.startsWith("+"))return e;const r=function(e,t){if(!t||0===t.length)return d;if(1===t.length)return t[0];const n=t.find((e=>e.startsWith(o)))||d,r=t.filter((t=>{const n=t.replace(/[^\dX]+/g,"");if(n.startsWith(o))return!1;for(let t=0;tn.length-1||n[t]!==o&&n[t]!==e[t])return!1;return!0}));return 1===r.length?r[0]:n}(n,null==t?void 0:t.patterns),u=[];let a=0;for(let e=0;e{n.d(t,{q:()=>o,V:()=>d});var r=n(6137);const o=e=>e.chatId.toString()+("thread"!==e.type?`_${e.type}`:-1!==e.threadId?`_${e.threadId}`:""),d=e=>{if(!e)return;const[t,n]=e.replace(/^#/,"").split("_");if(!t)return;const o=["thread","pinned","scheduled"].includes(n);return{chatId:t,type:n&&o?n:"thread",threadId:n&&!o?Number(n):r._f}}},9118:(e,t,n)=>{function r(e,t,n=!0,r=!0){let o;return(...d)=>{o?(clearTimeout(o),o=void 0):n&&e(...d),o=self.setTimeout((()=>{r&&e(...d),o=void 0}),t)}}function o(e,t,n=!0){let r,o,d;return(...u)=>{o=!0,d=u,r||(n&&(o=!1,e(...d)),r=self.setInterval((()=>{if(!o)return self.clearInterval(r),void(r=void 0);o=!1,e(...d)}),t))}}function d(e){return a(g,e)}function u(e){return a(y,e)}function a(e,t){let n,r=!1;return(...o)=>{n=o,r||(r=!0,e((()=>{r=!1,t(...n)})))}}function s(e){self.requestIdleCallback?self.requestIdleCallback(e):v(e)}n.d(t,{Ds:()=>r,P2:()=>o,mS:()=>d,wT:()=>u,Q8:()=>s,wO:()=>i,Pn:()=>c,T2:()=>g,D0:()=>y,R3:()=>v,zD:()=>b,Gq:()=>w});const i=e=>new Promise((t=>{setTimeout((()=>t()),e)}));function c(){return new Promise((e=>{g(e)}))}let l,f,h,m,p;function g(e,t=!1){l?t?f.push(e):l.push(e):(l=t?[]:[e],f=t?[e]:[],requestAnimationFrame((()=>{const e=l,t=f;l=void 0,f=void 0,t.forEach((e=>e())),e.forEach((e=>e()))})))}function y(e){g(e,!0)}function v(e,t=!1){h?t?m.push(e):h.push(e):(h=t?[]:[e],m=t?[e]:[],Promise.resolve().then((()=>{const e=h,t=m;h=void 0,m=void 0,t.forEach((e=>e())),e.forEach((e=>e()))})))}function b(e){v(e,!0)}function w(e,t=!1){return p||(p=[],self.addEventListener("beforeunload",(()=>{p.forEach((e=>e()))}))),t?p.push(e):p.unshift(e),()=>{p=p.filter((t=>t!==e))}}},5765:(e,t,n)=>{let r;n.d(t,{Z:()=>o});try{r=new RegExp("[^\\p{L}\\p{M}]+","ui")}catch(e){r=new RegExp("[^\\wа-яё]+","i")}function o(e,t){if(!e||!t)return!1;const n=e.toLowerCase().split(r);return t.toLowerCase().split(r).every((e=>n.some((t=>t.startsWith(e)))))}},2267:(e,t,n)=>{n.d(t,{b:()=>r});const r=e=>Math.floor(Date.now()/1e3)+e},4688:(e,t,n)=>{n.d(t,{f3:()=>m,jv:()=>l,ti:()=>i,Qw:()=>h,K8:()=>f,wX:()=>c});function r(e){return new Promise(((t,n)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>n(e.error)}))}let o;function d(){return o||(o=function(e,t){const n=function(){if(navigator.userAgentData||!/Safari\//.test(navigator.userAgent)||/Chrom(e|ium)\//.test(navigator.userAgent)||!indexedDB.databases)return Promise.resolve();let e;return new Promise((t=>{const n=()=>indexedDB.databases().finally(t);e=setInterval(n,100),n()})).finally((()=>clearInterval(e)))}().then((()=>{const e=indexedDB.open("keyval-store");return e.onupgradeneeded=()=>e.result.createObjectStore(t),r(e)}));return(e,r)=>n.then((n=>r(n.transaction(t,e).objectStore(t))))}(0,"keyval")),o}var u=n(3716),a=n(9524);const s=[1,2,3,4,5];function i(e=!1){if(e&&localStorage.getItem(u.Vx))return!0;const t=localStorage.getItem(u.b_);if(!t)return!1;try{const e=JSON.parse(t);return Boolean(e&&e.id&&e.dcID)}catch(e){return!1}}function c(e,t){const{mainDcId:n,keys:r,hashes:o}=e;localStorage.setItem(u.b_,JSON.stringify({dcID:n,id:t})),localStorage.setItem("dc",String(n)),Object.keys(r).map(Number).forEach((e=>{localStorage.setItem(`dc${e}_auth_key`,JSON.stringify(r[e]))})),o&&Object.keys(o).map(Number).forEach((e=>{localStorage.setItem(`dc${e}_hash`,JSON.stringify(o[e]))}))}function l(){[u.b_,"dc",...s.map((e=>`dc${e}_auth_key`)),...s.map((e=>`dc${e}_hash`))].forEach((e=>{localStorage.removeItem(e)}))}function f(){if(!i())return;const e=JSON.parse(localStorage.getItem(u.b_)),t=Number(e.dcID),n={},r={};return s.forEach((e=>{try{const t=localStorage.getItem(`dc${e}_auth_key`);t&&(n[e]=JSON.parse(t));const o=localStorage.getItem(`dc${e}_hash`);o&&(r[e]=JSON.parse(o))}catch(e){u.eM&&console.warn("Failed to load stored session",e)}})),Object.keys(n).length?{mainDcId:t,keys:n,hashes:r}:void 0}async function h(){const e=localStorage.getItem(u.Vx);if(!e)return;const t=await function(e,t=d()){return t("readonly",(t=>r(t.get(e))))}(`GramJs:${e}`);try{c(JSON.parse(t))}catch(e){u.eM&&console.warn("Failed to load legacy session",e)}}async function m(){localStorage.removeItem(u.Vx);const e=await function(e=d()){const t=[];return function(e,t){return e("readonly",(e=>(e.openCursor().onsuccess=function(){this.result&&(t(this.result),this.result.continue())},r(e.transaction))))}(e,(e=>t.push(e.key))).then((()=>t))}();await Promise.all([a.clear("GramJs"),...e.filter((e=>"string"==typeof e&&e.startsWith("GramJs:GramJs-session-"))).map((e=>function(e,t=d()){return t("readwrite",(t=>(t.delete(e),r(t.transaction))))}(e)))])}},6917:(e,t,n)=>{n.d(t,{Z:()=>c});var r=n(9933);const o=JSON.parse('{"--color-primary":["#3390EC","#8774E1"],"--color-primary-opacity":["#50A2E980","#8378DB80"],"--color-primary-shade":["#4a95d6","#7b71c6"],"--color-background":["#FFFFFF","#212121"],"--color-background-secondary":["#f4f4f5","#0F0F0F"],"--color-background-secondary-accent":["#E4E4E5","#100f10"],"--color-background-own":["#EEFFDE","#8774E1"],"--color-background-own-apple":["#DCF8C5","#8774E1"],"--color-background-selected":["#F4F4F5","#2C2C2C"],"--color-background-own-selected":["#d0ffac","#6549d4"],"--color-chat-hover":["#F4F4F5","#2C2C2C"],"--color-chat-active":["#3390EC","#8774E1"],"--color-item-active":["#ededed","#292929"],"--color-text":["#000000","#FFFFFF"],"--color-text-secondary":["#707579","#AAAAAA"],"--color-text-secondary-apple":["#8E8E92","#AAAAAA"],"--color-borders":["#DADCE0","#303030"],"--color-borders-input":["#DADCE0","#5B5B5A"],"--color-dividers":["#C8C6CC","#404040"],"--color-links":["#3390EC","#8774E1"],"--color-gray":["#C4C9CC","#717579"],"--color-pinned":["#C4C9CC","#707579"],"--color-default-shadow":["#72727240","#1010109c"],"--color-light-shadow":["#7272722B","#00000040"],"--color-green":["#00C73E","#8774E1"],"--color-text-meta-colored":["#4DCD5E","#8378DB"],"--color-reply-hover":["#F4F4F4","#272727"],"--color-reply-active":["#E8E9E9","#2E2F2F"],"--color-reply-own-hover":["#D9F5CE","#7d6bca"],"--color-reply-own-hover-apple":["#cbefb7","#7d6bca"],"--color-reply-own-active":["#C5ECBE","#7264b6"],"--color-reply-own-active-apple":["#bae6a8","#7264b6"],"--color-accent-own":["#45AF54","#FFFFFF"],"--color-message-meta-own":["#4FAE4EFF","#FFFFFF88"],"--color-own-links":["#3390EC","#FFFFFF"],"--color-code":["#4a729a","#8774E1"],"--color-code-own":["#3c7940","#FFFFFF"],"--color-code-bg":["#70757914","#ffffff26"],"--color-code-own-bg":["#70757914","#ffffff26"],"--color-composer-button":["#707579CC","#AAAAAACC"]}');let d=!1;const u=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i,a=new Set(["--color-primary-shade","--color-text-secondary"]),s=(e,t,n)=>(1-n)*e+n*t,i=Object.keys(o).map((e=>({property:e,colors:[l(o[e][0]),l(o[e][1])]}))),c=(e,t)=>{const n="dark"===e,o=d&&t,u=n?0:1,a=n?1:0,s=Date.now(),i=document.querySelector('meta[name="theme-color"]');document.documentElement.classList.remove("theme-"+(n?"light":"dark")),d&&document.documentElement.classList.add("no-animations"),document.documentElement.classList.add(`theme-${e}`),i&&i.setAttribute("content",n?"#212121":"#fff"),setTimeout((()=>{document.documentElement.classList.remove("no-animations")}),500),d=!0,o?(0,r.c)((()=>{const e=Math.min((Date.now()-s)/200,1);return f(u,a,function(e){return 1-(1-e)**3.5}(e)),e<1})):f(u,a)};function l(e){const t=u.exec(e);return{r:parseInt(t[1],16),g:parseInt(t[2],16),b:parseInt(t[3],16),a:void 0!==t[4]?parseInt(t[4],16):void 0}}function f(e,t,n=1){i.forEach((({property:r,colors:o})=>{const d=Math.round(s(o[e].r,o[t].r,n)),u=Math.round(s(o[e].g,o[t].g,n)),i=Math.round(s(o[e].b,o[t].b,n)),c=void 0!==o[e].a?Math.round(s(o[e].a,o[t].a,n)):void 0;document.documentElement.style.setProperty(r,void 0!==c?`rgba(${d},${u},${i},${c/255})`:`rgb(${d},${u},${i})`),a.has(r)&&document.documentElement.style.setProperty(`${r}-rgb`,`${d},${u},${i}`)}))}},2155:(e,t,n)=>{n.d(t,{kh:()=>d,bi:()=>a,Xv:()=>s});var r=n(3681),o=n(4284);function d(e){return String(e).replace(/\d(?=(\d{3})+$)/g,"$& ")}function u(e){return".0"===String(e.toFixed(1)).substr(-2)?Math.round(e):e.toFixed(1).replace(".",",")}function a(e){return e<1e3?e:e<1e6?`${u(e/1e3)}K`:`${u(e/1e6)}M`}function s(e,t=2){return e.replace(/[.,!@#$%^&*()_+=\-`~[\]/\\{}:"|<>?]+/gi,"").trim().split(/\s+/).slice(0,t).map((e=>{if(!e.length)return"";const t=(e=(0,o.g6)(e)).match(r.Z);return t&&e.startsWith(t[0])?t[0]:e.match(/./u)[0].toUpperCase()})).join("")}},8035:(e,t,n)=>{function r(e,t=30){return!e||e.length<=t?e:`${e.substr(0,t)}...`}n.d(t,{Z:()=>r})},862:(e,t,n)=>{n.d(t,{Hu:()=>s,_y:()=>i,p6:()=>c});var r=n(7361),o=n(1394),d=n(9118);let u,a;const s="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";async function i(e,t){for(l();!a.wasmReady;)await(0,d.wO)(2e3);const{result:n,width:r,height:o}=await function(e,t){return new Promise((n=>{a.requests||(a.requests=new Map),a.requests.set(e,n),a.postMessage({id:e,blob:t})}))}(e,t);if(r&&o)return function({result:e,width:t,height:n}){return u||(u=document.createElement("canvas")),new Promise((r=>{const o=new ImageData(e,t,n);u.width=t,u.height=n,u.getContext("2d").putImageData(o,0,0),u.toBlob((e=>{r(null!=e?e:void 0)}),"image/png",1)}))}({result:n,width:r,height:o})}async function c(e,t){if((0,r.on)()||"data:image/webp"!==t.substr(0,15))return t;l();const n=await i(e,(0,o.A9)(t));if(!n)throw new Error(`Can't convert webp to png. Url: ${t}`);return(0,o.YJ)(n)}function l(){a||(a=new Worker(new URL(n.p+n.u(536),n.b)),a.wasmReady=!1,a.onmessage=f)}function f(e){const{id:t}=e.data;switch(e.data.type){case"initialized":a.wasmReady=!0;break;case"result":if(a.requests.has(t)){const n=a.requests.get(t);a.requests.delete(t),n(e.data)}}}},1622:(e,t,n)=>{n.d(t,{I:()=>l,p:()=>f});var r=n(3716),o=n(5116),d=n(4688);const u=["t.me","telegram.me"].map((e=>`//${e}/_websync_?`)),a=`${r.Ji} Z`,s="tgme_sync",i=()=>Math.floor(Number(new Date)/1e3);let c;const l=e=>{const t=i(),{canRedirect:n,ts:r}=JSON.parse(localStorage.getItem(s)||"{}");return n!==e||r+86400<=t?Promise.all(u.map((t=>new Promise(((n,r)=>{const o=document.createElement("script"),d=()=>!!document.body.removeChild(o);o.src=t+new URLSearchParams({authed:Number(e).toString(),version:a}),document.body.appendChild(o),o.onload=()=>{(e=>{const t=i();localStorage.setItem(s,JSON.stringify({canRedirect:e,ts:t}))})(e),d(),c&&(clearTimeout(c),c=void 0),f(),n()},o.onerror=()=>{d(),r()}}))))):Promise.resolve()};function f(){if(r.eM)return;if(void 0!==c)return;const e=i(),{ts:t}=JSON.parse(localStorage.getItem(s)||"{}"),n=86400-(e-t);c=setTimeout((()=>{const{authState:e}=(0,o.Rd)(),t="authorizationStateReady"===e||(0,d.ti)(!0);l(t)}),Math.max(0,1e3*n))}},3858:(e,t,n)=>{n.d(t,{z:()=>l,Z:()=>h});var r=n(9118),o=n(3716),d=n(7361);const u=d.wB&&f(),a=window.innerHeight;let s=l(),i=!1;const c=(0,r.P2)((()=>{s=l(),!i&&((s.width<=o.l3||s.width<=o.u_&&s.height<=o.rO)!==d.wB||d.wB&&u!==f())&&window.location.reload()}),250,!0);function l(){let e;e=d.cj?window.visualViewport.height+window.visualViewport.pageTop:window.innerHeight;const t=.01*e;return document.documentElement.style.setProperty("--vh",`${t}px`),{width:window.innerWidth,height:window.innerHeight}}function f(){return d.cj?window.matchMedia("(orientation: landscape)").matches:window.matchMedia("screen and (min-device-aspect-ratio: 1/1) and (orientation: landscape)").matches}window.addEventListener("orientationchange",c),d.cj?window.visualViewport.addEventListener("resize",c):window.addEventListener("resize",c);const h={get:()=>s,getIsKeyboardVisible:()=>a>s.height,disableRefresh:function(){i=!0},enableRefresh:function(){i=!1}}},5359:(e,t,n)=>{e.exports=n.p+"app-inactive.bc7953c2dfebcabce2c4..png"},2162:(e,t,n)=>{e.exports=n.p+"monkey.a3d5fcdc50b18dc55695..svg"},4128:(e,t,n)=>{e.exports=n.p+"telegram-logo.1b2bb5b107f046ea9325..svg"}},a={};function s(e){var t=a[e];if(void 0!==t)return t.exports;var n=a[e]={exports:{}};return u[e].call(n.exports,n,n.exports,s),n.exports}s.m=u,s.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return s.d(t,{a:t}),t},t=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,s.t=function(n,r){if(1&r&&(n=this(n)),8&r)return n;if("object"==typeof n&&n){if(4&r&&n.__esModule)return n;if(16&r&&"function"==typeof n.then)return n}var o=Object.create(null);s.r(o);var d={};e=e||[null,t({}),t([]),t(t)];for(var u=2&r&&n;"object"==typeof u&&!~e.indexOf(u);u=t(u))Object.getOwnPropertyNames(u).forEach((e=>d[e]=()=>n[e]));return d.default=()=>n,s.d(o,d),o},s.d=(e,t)=>{for(var n in t)s.o(t,n)&&!s.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},s.f={},s.e=e=>Promise.all(Object.keys(s.f).reduce(((t,n)=>(s.f[n](e,t),t)),[])),s.u=e=>e+"."+{99:"f03a947e6e336feffec8",133:"aae91a1c7ca8928cb720",161:"286d0207d962142ad548",306:"abed97b181f73c2c1aa8",325:"d8a67d9617f2e13de2dc",354:"959e19f0ca3e2bb07043",472:"21e5264f606f2b525030",501:"72ce4b6e27f459e194cd",514:"3cef19392d72a10cf6ea",524:"632897f7413c1c081b04",536:"55dc7dd4ab42a2c9f037",701:"0c52bb0aaf1cd79c0b70",745:"9316c5c2b711c39a20a5",915:"13af1c4ab9a00d84ac23",941:"a1bb68030d234cd6f825",993:"f0aad9f6787f211b4e51"}[e]+".js",s.miniCssF=e=>e+"."+{133:"aae91a1c7ca8928cb720",306:"abed97b181f73c2c1aa8",325:"d8a67d9617f2e13de2dc",472:"21e5264f606f2b525030",701:"0c52bb0aaf1cd79c0b70"}[e]+".css",s.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),s.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n={},r="telegram-t:",s.l=(e,t,o,d)=>{if(n[e])n[e].push(t);else{var u,a;if(void 0!==o)for(var i=document.getElementsByTagName("script"),c=0;c{u.onerror=u.onload=null,clearTimeout(h);var o=n[e];if(delete n[e],u.parentNode&&u.parentNode.removeChild(u),o&&o.forEach((e=>e(r))),t)return t(r)},h=setTimeout(f.bind(null,void 0,{type:"timeout",target:u}),12e4);u.onerror=f.bind(null,u.onerror),u.onload=f.bind(null,u.onload),a&&document.head.appendChild(u)}},s.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{var e;s.g.importScripts&&(e=s.g.location+"");var t=s.g.document;if(!e&&t&&(t.currentScript&&(e=t.currentScript.src),!e)){var n=t.getElementsByTagName("script");n.length&&(e=n[n.length-1].src)}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),s.p=e})(),o=e=>new Promise(((t,n)=>{var r=s.miniCssF(e),o=s.p+r;if(((e,t)=>{for(var n=document.getElementsByTagName("link"),r=0;r{var o=document.createElement("link");o.rel="stylesheet",o.type="text/css",o.onerror=o.onload=d=>{if(o.onerror=o.onload=null,"load"===d.type)n();else{var u=d&&("load"===d.type?"missing":d.type),a=d&&d.target&&d.target.href||t,s=new Error("Loading CSS chunk "+e+" failed.\n("+a+")");s.code="CSS_CHUNK_LOAD_FAILED",s.type=u,s.request=a,o.parentNode.removeChild(o),r(s)}},o.href=t,document.head.appendChild(o)})(e,o,t,n)})),d={179:0},s.f.miniCss=(e,t)=>{d[e]?t.push(d[e]):0!==d[e]&&{133:1,306:1,325:1,472:1,701:1}[e]&&t.push(d[e]=o(e).then((()=>{d[e]=0}),(t=>{throw delete d[e],t})))},(()=>{s.b=document.baseURI||self.location.href;var e={179:0};s.f.j=(t,n)=>{var r=s.o(e,t)?e[t]:void 0;if(0!==r)if(r)n.push(r[2]);else{var o=new Promise(((n,o)=>r=e[t]=[n,o]));n.push(r[2]=o);var d=s.p+s.u(t),u=new Error;s.l(d,(n=>{if(s.o(e,t)&&(0!==(r=e[t])&&(e[t]=void 0),r)){var o=n&&("load"===n.type?"missing":n.type),d=n&&n.target&&n.target.src;u.message="Loading chunk "+t+" failed.\n("+o+": "+d+")",u.name="ChunkLoadError",u.type=o,u.request=d,r[1](u)}}),"chunk-"+t,t)}};var t=(t,n)=>{var r,o,[d,u,a]=n,i=0;if(d.some((t=>0!==e[t]))){for(r in u)s.o(u,r)&&(s.m[r]=u[r]);a&&a(s)}for(t&&t(n);i{s(3592);var e=s(3716),t=s(5116),n=s(7361),r=s(8406);function o(n){const o=n.data;if(e.eM&&console.log("[SW] Message from worker",o),!o.type)return;const d=(0,t.uC)();switch(o.type){case"focusMessage":d.focusMessage&&d.focusMessage(o.payload);break;case"playNotificationSound":(0,r.Nz)(o.payload.id)}}function d(){navigator.serviceWorker.removeEventListener("message",o),navigator.serviceWorker.addEventListener("message",o),(0,r.KC)()}n.Mc&&(window.addEventListener("load",(async()=>{try{await navigator.serviceWorker.register(new URL(s.p+s.u(524),s.b)),e.eM&&console.log("[SW] ServiceWorker registered"),await navigator.serviceWorker.ready,navigator.serviceWorker.controller?(e.eM&&console.log("[SW] ServiceWorker ready"),d()):(e.eM&&console.error("[SW] ServiceWorker not available"),n.cj||n.wZ||(0,t.uC)().showDialog({data:{message:"SERVICE_WORKER_DISABLED",hasErrorKey:!0}}))}catch(t){e.eM&&console.error("[SW] ServiceWorker registration failed: ",t)}})),window.addEventListener("focus",(async()=>{await navigator.serviceWorker.ready,d()})));var u=s(2916);const a={isLeftColumnShown:!0,isChatInfoShown:!1,newChatMembersProgress:s(1713).WB.Closed,uiReadyState:0,serverTimeOffset:0,authRememberMe:!0,countryList:{phoneCodes:[],general:[]},blocked:{ids:[],totalCount:0},users:{byId:{}},chats:{listIds:{},isFullyLoaded:{},orderedPinnedIds:{},totalCount:{},byId:{}},messages:{byChatId:{},messageLists:[]},scheduledMessages:{byChatId:{}},chatFolders:{byId:{},activeChatFolder:0},fileUploads:{byMessageLocalId:{}},recentEmojis:["grinning","kissing_heart","christmas_tree","brain","trophy"],stickers:{setsById:{},added:{},recent:{stickers:[]},favorite:{stickers:[]},greeting:{stickers:[]},featured:{setIds:[]},search:{},forEmoji:{}},emojiKeywords:{},gifs:{saved:{},search:{}},inlineBots:{isLoading:!1,byUsername:{}},globalSearch:{},userSearch:{},localTextSearch:{byChatThreadKey:{}},localMediaSearch:{byChatId:{}},management:{byChatId:{}},topPeers:{},topInlineBots:{},mediaViewer:{},audioPlayer:{volume:e.Qx,playbackRate:e.mw,isMuted:!1},forwardMessages:{},pollResults:{},payment:{},notifications:[],dialogs:[],activeSessions:[],settings:{byKey:{theme:"light",shouldUseSystemTheme:!0,messageTextSize:n.cj?e.b6:n.jm?e.AR:e.xS,animationLevel:e.CX,messageSendKeyCombo:"enter",canAutoLoadPhotoFromContacts:!0,canAutoLoadPhotoInPrivateChats:!0,canAutoLoadPhotoInGroups:!0,canAutoLoadPhotoInChannels:!0,canAutoLoadVideoFromContacts:!0,canAutoLoadVideoInPrivateChats:!0,canAutoLoadVideoInGroups:!0,canAutoLoadVideoInChannels:!0,canAutoLoadFileFromContacts:!1,canAutoLoadFileInPrivateChats:!1,canAutoLoadFileInGroups:!1,canAutoLoadFileInChannels:!1,autoLoadFileMaxSizeMb:10,hasWebNotifications:!0,hasPushNotifications:!0,notificationSoundVolume:5,canAutoPlayGifs:!0,canAutoPlayVideos:!0,shouldSuggestStickers:!0,shouldLoopStickers:!0,language:"en",timeFormat:"24h",wasTimeFormatSetManually:!1},themes:{light:{isBlurred:!0,patternColor:e.g},dark:{isBlurred:!0,patternColor:e.Vv}},privacy:{},notifyExceptions:{}},twoFaSettings:{},shouldShowContextMenuHint:!0,activeDownloads:{byChatId:{}},serviceNotifications:[]};var i=s(6137),c=s(9118),l=s(8674),f=s(782),h=s(8085),m=s(4688),p=s(5780),g=s(6590),y=s(2858);const v=(0,c.P2)((()=>(0,c.Q8)(E)),5e3,!1);let b,w=!1,I=!1;function C(){w=!0,b=(0,c.Gq)(E,!0),window.addEventListener("blur",E),(0,t.ll)(v)}function S(){w=!1,(0,t.Iq)(v),window.removeEventListener("blur",E),b&&b()}function E(){if(!w||I)return;const n=(0,t.Rd)();if(n.isLoggingOut)return;const r={...a,...(0,f.ei)(n,["authState","authPhoneNumber","authRememberMe","authNearestCountry","currentUserId","contactList","topPeers","topInlineBots","recentEmojis","push","shouldShowContextMenuHint","leftColumnWidth","serviceNotifications"]),audioPlayer:{volume:n.audioPlayer.volume,playbackRate:n.audioPlayer.playbackRate,isMuted:n.audioPlayer.isMuted},isChatInfoShown:P(n),users:M(n),chats:A(n),messages:k(n),globalSearch:{recentlyFoundChatIds:n.globalSearch.recentlyFoundChatIds},settings:T(n),chatFolders:N(n)},o=JSON.stringify(r);localStorage.setItem(e.Uh,o)}function P(t){return window.innerWidth>e._m&&t.isChatInfoShown}function M(t){const{users:{byId:n,selectedId:r}}=t,o=[...(t.chats.listIds.active||[]).slice(0,e.gJ).filter(y.YC),...Object.keys(n)].slice(0,e.lO);return{byId:(0,f.ei)(n,o),selectedId:window.innerWidth>e._m?r:void 0}}function A(t){const n=[...(t.chats.listIds.active||[]).slice(0,e.gJ)],{chatId:r}=(0,h.Bt)(t)||{};return{...t.chats,byId:(0,f.ei)(t.chats.byId,r?[...n,r]:n),listIds:{active:n},isFullyLoaded:{},orderedPinnedIds:{active:t.chats.orderedPinnedIds.active}}}function k(t){const n={},{chatId:r}=(0,h.Bt)(t)||{};return[...(t.chats.listIds.active||[]).slice(0,e.gJ),...r?[r]:[]].forEach((e=>{const r=t.messages.byChatId[e];if(!r)return;const o=r.threadsById[i._f];o&&o.viewportIds&&(n[e]={byId:(0,f.ei)(r.byId,o.viewportIds),threadsById:{[i._f]:o}})})),{byChatId:n,messageLists:[]}}function T(e){const{byKey:t,themes:n}=e.settings;return{byKey:t,themes:n,privacy:{},notifyExceptions:{}}}function N(e){return{...e.chatFolders,activeChatFolder:0}}document.addEventListener(l._L,(()=>{I=!0})),document.addEventListener(l.OV,(()=>{I=!1})),e.sd||((0,t.Q6)("saveSession",(()=>{w||C()})),(0,t.Q6)("reset",(()=>{localStorage.removeItem(e.Uh),w&&S()}))),(0,t.Q6)("init",(()=>{const t=(0,f.Xh)(a);return function(t){if(!e.sd)return(0,m.ti)(!0)?(C(),function(t){e.eM&&console.time("global-state-cache-read");const r=localStorage.getItem(e.Uh),o=r?JSON.parse(r):void 0;e.eM&&console.timeEnd("global-state-cache-read"),o&&function(t,n){if("shouldAutoDownloadMediaFromContacts"in t.settings.byKey){const{shouldAutoDownloadMediaFromContacts:e,shouldAutoDownloadMediaInPrivateChats:n,shouldAutoDownloadMediaInGroups:r,shouldAutoDownloadMediaInChannels:o,shouldAutoPlayVideos:d,shouldAutoPlayGifs:u,...a}=t.settings.byKey;t.settings.byKey={...a,canAutoLoadPhotoFromContacts:e,canAutoLoadVideoFromContacts:e,canAutoLoadPhotoInPrivateChats:n,canAutoLoadVideoInPrivateChats:n,canAutoLoadPhotoInGroups:r,canAutoLoadVideoInGroups:r,canAutoLoadPhotoInChannels:o,canAutoLoadVideoInChannels:o,canAutoPlayVideos:d,canAutoPlayGifs:u}}t.settings.byKey={...n.settings.byKey,...t.settings.byKey},t.settings.themes={...n.settings.themes,...t.settings.themes},t.chatFolders={...n.chatFolders,...t.chatFolders},t.stickers.greeting||(t.stickers.greeting=n.stickers.greeting),t.activeDownloads||(t.activeDownloads={byChatId:{}}),t.serviceNotifications||(t.serviceNotifications=[]),void 0===t.audioPlayer.volume&&(t.audioPlayer.volume=e.Qx),void 0===t.audioPlayer.playbackRate&&(t.audioPlayer.playbackRate=e.mw)}(o,t);const d={...t,...o},u=n.wB?void 0:(0,p.V)(g.Oy);return{...d,messages:{...d.messages,messageLists:u?[u]:[]}}}(t)):void S()}(t)||t}));var L=s(4050),R=s(3858);const D="tt-active-tab",O=String(Date.now()+Math.random());let x;localStorage.setItem(D,O);const _=window.setInterval((()=>{x&&localStorage.getItem(D)!==O&&(x(),clearInterval(_))}),2e3);var Z=s(706),F=(s(7895),s(3781),s(1363),s(9667),s(4907),s(8332)),B=s(1212),$=s(1394);const U=["400 1em Roboto","500 1em Roboto"];function j(){if("fonts"in document)return Promise.all(U.map((e=>document.fonts.load(e))))}var W=s(647),V=s(9203),G=s(6752),H=s(4128),z=s(2162);function Q(){const{listIds:e,byId:n}=(0,t.Rd)().chats;if(e.active)return Promise.all(e.active.slice(0,10).map((e=>{const t=n[e];if(!t)return;const r=(0,F.RT)(t);return r?W.he(r,i.IU.BlobUrl):void 0})))}const K={main:()=>Promise.all([(0,V.$y)(V.gl.Main,"Main").then(j),Q()]),authPhoneNumber:()=>Promise.all([j(),(0,$.pt)(H)]),authCode:()=>(0,$.pt)(z),authPassword:()=>(0,$.pt)(z),authQrCode:j},J=(0,t.c$)((e=>{const t=(0,h.Pu)(e),{background:n,backgroundColor:r}=e.settings.themes[t]||{};return{shouldSkipHistoryAnimations:e.shouldSkipHistoryAnimations,uiReadyState:e.uiReadyState,hasCustomBackground:Boolean(n),hasCustomBackgroundColor:Boolean(r),isRightColumnShown:(0,h.Jf)(e),leftColumnWidth:e.leftColumnWidth}}),((e,t)=>(0,f.ei)(t,["setIsUiReady"])))((({page:e,children:t,hasCustomBackground:n,hasCustomBackgroundColor:r,isRightColumnShown:o,shouldSkipHistoryAnimations:d,leftColumnWidth:u,setIsUiReady:a})=>{const[s,i]=(0,Z.Z)(),{shouldRender:l,transitionClassNames:f}=(0,B.Z)(!s,void 0,!0);return(0,L.d4)((()=>{let t;return Promise.race([(0,c.wO)(700),(async()=>{try{await K[e]()}catch(e){}})()]).then((()=>{i(),a({uiReadyState:1}),t=window.setTimeout((()=>{a({uiReadyState:2})}),1e3)})),()=>{t&&(clearTimeout(t),t=void 0),a({uiReadyState:0})}}),[]),L.ZP.createElement("div",{id:"UiLoader"},t,l&&!d&&L.ZP.createElement("div",{className:(0,G.Z)("mask",f)},"main"===e?L.ZP.createElement(L.ZP.Fragment,null,L.ZP.createElement("div",{className:"left",style:u?`width: ${u}px`:void 0}),L.ZP.createElement("div",{className:(0,G.Z)("middle",n&&"custom-bg-image",r&&"custom-bg-color",o&&"with-right-column")}),o&&L.ZP.createElement("div",{className:"right"})):L.ZP.createElement("div",{className:"blank"})))}));var q=s(6272),Y=s(663),X=s(9107);const ee=(e,t)=>{const[n,r]=(0,L.eJ)();return e&&Y.Pn(e,t).then(r),n};function te(){let e=navigator.language;return e&&"pt-br"!==e&&(e=e.substr(0,2)),e}var ne=s(231),re=s(4605),oe=s(7687),de=s(4288),ue=s(5765),ae=s(2340),se=s(4284),ie=s(9290),ce=s(3106),le=s(8964),fe=s(9204);const he=200+e.fK,me=(0,L.X$)((0,t.c$)((e=>{const{countryList:{phoneCodes:t}}=e;return{phoneCodeList:t}}))((({id:e,value:t,isLoading:n,onChange:r,phoneCodeList:o})=>{const d=(0,X.Z)(),u=(0,L.sO)(null),[a,s]=(0,L.eJ)(),[i,c]=(0,L.eJ)([]),l=(0,L.I4)((e=>{s(e),c(function(e,t=""){return t.length?e.filter((e=>(0,ue.Z)(e.defaultName,t)||e.name&&(0,ue.Z)(e.name,t))):e}(o,e))}),[o]);(0,ie.Z)((([e])=>{0===(null==e?void 0:e.length)&&o.length>0&&l(a)}),[o,l]);const f=(0,L.I4)((e=>{r(e),setTimeout((()=>l(void 0)),he)}),[r,l]),h=(0,L.I4)((e=>{l(e.currentTarget.value)}),[l]),m=(0,L.I4)((e=>{if(8!==e.keyCode)return;const n=e.currentTarget;t&&void 0===a&&(n.value=""),l(n.value)}),[a,l,t]);return L.ZP.createElement(ce.Z,{className:"CountryCodeInput",trigger:({onTrigger:r,isOpen:o})=>{const s=()=>{if(o)return;setTimeout((()=>{u.current.select()}),50),r();const e=document.getElementById("auth-phone-number-form");e.scrollTo({top:e.scrollHeight,behavior:"smooth"})},i=null!=a?a:(null==t?void 0:t.name)||(null==t?void 0:t.defaultName)||"";return L.ZP.createElement("div",{className:(0,G.Z)("input-group",t&&"touched")},L.ZP.createElement("input",{ref:u,className:(0,G.Z)("form-control",o&&"focus"),type:"text",id:e,value:i,autoComplete:"off",onClick:s,onFocus:s,onInput:e=>{h(e),s()},onKeyDown:m}),L.ZP.createElement("label",null,d("Login.SelectCountry.Title")),n?L.ZP.createElement(fe.Z,{color:"black"}):L.ZP.createElement("i",{onClick:s,className:(0,G.Z)("css-icon-down",o&&"open")}))}},i.map((e=>L.ZP.createElement(le.Z,{key:e.iso2,className:t&&e.iso2===t.iso2?"selected":"",onClick:()=>f(e)},L.ZP.createElement("span",{className:"country-flag"},(0,ae.Z)((0,se.Wg)(e.iso2),["hq_emoji"])),L.ZP.createElement("span",{className:"country-name"},e.name||e.defaultName),L.ZP.createElement("span",{className:"country-code"},e.countryCode)))),!i.length&&L.ZP.createElement(le.Z,{key:"no-results",className:"no-results",disabled:!0},L.ZP.createElement("span",null,d("lng_country_none"))))})));let pe=!1;const ge=(0,L.X$)((0,t.c$)((e=>{const{settings:{byKey:{language:t}},countryList:{phoneCodes:n}}=e;return{...(0,f.ei)(e,["connectionState","authState","authPhoneNumber","authIsLoading","authIsLoadingQrCode","authError","authRememberMe","authNearestCountry"]),language:t,phoneCodeList:n}}),((e,t)=>(0,f.ei)(t,["setAuthPhoneNumber","setAuthRememberMe","clearAuthError","loadNearestCountry","loadCountryList","goToAuthQrCode","setSettingOption"])))((({connectionState:e,authState:t,authPhoneNumber:r,authIsLoading:o,authIsLoadingQrCode:d,authError:u,authRememberMe:a,authNearestCountry:s,phoneCodeList:i,language:c,setAuthPhoneNumber:l,setAuthRememberMe:f,loadNearestCountry:h,loadCountryList:m,clearAuthError:p,goToAuthQrCode:g,setSettingOption:y})=>{const v=(0,X.Z)(),b=(0,L.sO)(null),w=te(),I=ee(w,"ContinueOnThisLanguage"),[C,S]=(0,L.eJ)(),[E,P]=(0,L.eJ)(),[M,A]=(0,L.eJ)(!1),[k,T]=(0,L.eJ)(),[N,R,D]=(0,Z.Z)(),O=C?`+${C.countryCode} ${E||""}`:E,x=O&&O.replace(/[^\d]+/g,"").length>=7;(0,L.d4)((()=>{n.$b||b.current.focus()}),[C]),(0,L.d4)((()=>{"connectionStateReady"!==e||s||h()}),[e,s,h]),(0,L.d4)((()=>{"connectionStateReady"===e&&m({langCode:c})}),[e,c,m]),(0,L.d4)((()=>{s&&i&&!C&&!M&&S((0,q.U9)(i,s)[0])}),[C,s,M,i]);const _=(0,L.I4)((e=>{e.length||P("");const t=i&&(0,q.g3)(i,e),n=!C||t&&t.iso2!==C.iso2||!t&&e.length?t:C;(!C||!n||n&&n.iso2!==C.iso2)&&S(n),P((0,q.un)(e,n))}),[i,C]),F=(0,L.I4)((()=>{R(),(0,Y.m0)(w,(()=>{D(),y({language:w})}))}),[R,y,w,D]);(0,L.d4)((()=>{void 0===E&&r&&_(r)}),[r,E,_]),(0,L.bt)((()=>{b.current&&k&&b.current.setSelectionRange(...k)}),[k]);const B=(0,L.sO)(!1),U=(0,L.I4)((()=>{B.current=!0,requestAnimationFrame((()=>{B.current=!1}))}),[]),W=(0,L.I4)((e=>{S(e),P("")}),[]),V=(0,L.I4)((e=>{u&&p(),pe||(pe=!0,j(),(0,$.pt)(z));const{value:t,selectionStart:r,selectionEnd:o}=e.target;T(r&&o&&o1&&!B.current;_(d?`${C.countryCode} ${t}`:t)}),[u,p,C,O,_]),G=(0,L.I4)((e=>{f(e.target.checked)}),[f]),H="authorizationStateWaitPhoneNumber"===t;return L.ZP.createElement("div",{id:"auth-phone-number-form",className:"custom-scroll"},L.ZP.createElement("div",{className:"auth-form"},L.ZP.createElement("div",{id:"logo"}),L.ZP.createElement("h2",null,"Telegram"),L.ZP.createElement("p",{className:"note"},v("StartText")),L.ZP.createElement("form",{action:"",onSubmit:function(e){e.preventDefault(),o||x&&l({phoneNumber:O})}},L.ZP.createElement(me,{id:"sign-in-phone-code",value:C,isLoading:!s&&!C,onChange:W}),L.ZP.createElement(oe.Z,{ref:b,id:"sign-in-phone-number",label:v("Login.PhonePlaceholder"),value:O,error:u&&v(u),inputMode:"tel",onChange:V,onPaste:n.s$?U:void 0}),L.ZP.createElement(re.Z,{id:"sign-in-keep-session",label:"Keep me signed in",checked:Boolean(a),onChange:G}),x&&(H?L.ZP.createElement(ne.Z,{type:"submit",ripple:!0,isLoading:o},v("Login.Next")):L.ZP.createElement(de.Z,null)),H&&L.ZP.createElement(ne.Z,{isText:!0,ripple:!0,isLoading:d,onClick:g},v("Login.QR.Login")),w&&w!==c&&I&&L.ZP.createElement(ne.Z,{isText:!0,isLoading:N,onClick:F},I))))})));var ye=s(8778);const ve=(0,L.X$)((()=>{const e=(0,ye.Z)(V.gl.Auth,"AuthCode");return e?L.ZP.createElement(e,null):L.ZP.createElement(de.Z,null)})),be=(0,L.X$)((()=>{const e=(0,ye.Z)(V.gl.Auth,"AuthPassword");return e?L.ZP.createElement(e,null):L.ZP.createElement(de.Z,null)})),we=(0,L.X$)((()=>{const e=(0,ye.Z)(V.gl.Auth,"AuthRegister");return e?L.ZP.createElement(e,null):L.ZP.createElement(de.Z,null)}));let Ie=null;class Ce{}Ce.render=function(e,t){Ie(e,t)},self.QrCreator=Ce,function(e){function t(t,n,r,o){var d={},u=e(r,n);u.u(t),u.J(),o=o||0;var a=u.h(),s=u.h()+2*o;return d.text=t,d.level=n,d.version=r,d.O=s,d.a=function(e,t){return t-=o,!(0>(e-=o)||e>=a||0>t||t>=a)&&u.a(e,t)},d}function n(e,t,n,r,o,d,u,a,s,i){function c(t,n,r,o,u,a,s){t?(e.lineTo(n+a,r+s),e.arcTo(n,r,o,u,d)):e.lineTo(n,r)}u?e.moveTo(t+d,n):e.moveTo(t,n),c(a,r,n,r,o,-d,0),c(s,r,o,t,o,0,-d),c(i,t,o,t,n,d,0),c(u,t,n,r,n,0,d)}function r(e,t,n,r,o,d,u,a,s,i){function c(t,n,r,o){e.moveTo(t+r,n),e.lineTo(t,n),e.lineTo(t,n+o),e.arcTo(t,n,t+r,n,d)}u&&c(t,n,d,d),a&&c(r,n,-d,d),s&&c(r,o,-d,-d),i&&c(t,o,d,-d)}function o(e,o){e:{var d=o.text,u=o.v,a=o.N,s=o.K,i=o.P;for(a=Math.max(1,a||1),s=Math.min(40,s||40);a<=s;a+=1)try{var c=t(d,u,a,i);break e}catch(e){}c=void 0}if(!c)return null;for(d=e.getContext("2d"),o.background&&(d.fillStyle=o.background,d.fillRect(o.left,o.top,o.size,o.size)),u=c.O,s=o.size/u,d.beginPath(),i=0;iMath.round(e*t.size))),"linear-gradient"===r)var d=e.createLinearGradient.apply(e,n);else{if("radial-gradient"!==r)throw Error("Unsupported fill");d=e.createRadialGradient.apply(e,n)}o.forEach((([e,t])=>{d.addColorStop(e,t)})),e.fillStyle=d}}(d,o),d.fill(),e}var d={minVersion:1,maxVersion:40,ecLevel:"L",left:0,top:0,size:200,fill:"#000",background:null,text:"no text",radius:.5,quiet:0};Ie=function(e,t){var n={};Object.assign(n,d,e),n.N=n.minVersion,n.K=n.maxVersion,n.v=n.ecLevel,n.left=n.left,n.top=n.top,n.size=n.size,n.fill=n.fill,n.background=n.background,n.text=n.text,n.R=n.radius,n.P=n.quiet,t instanceof HTMLCanvasElement?(t.width===n.size&&t.height===n.size||(t.width=n.size,t.height=n.size),t.getContext("2d").clearRect(0,0,t.width,t.height),o(t,n)):((e=document.createElement("canvas")).width=n.size,e.height=n.size,n=o(e,n),t.appendChild(n))}}(function(){function e(o,u){function a(e,t){for(var n=-1;7>=n;n+=1)if(!(-1>=e+n||l<=e+n))for(var r=-1;7>=r;r+=1)-1>=t+r||l<=t+r||(c[e+n][t+r]=0<=n&&6>=n&&(0==r||6==r)||0<=r&&6>=r&&(0==n||6==n)||2<=n&&4>=n&&2<=r&&4>=r)}function s(e,n){for(var u=l=4*o+17,s=Array(u),m=0;m=y;y+=1)for(var v=-2;2>=v;v+=1)c[p+y][g+v]=-2==y||2==y||-2==v||2==v||0==y&&0==v}for(u=8;us;s+=1)m=!e&&1==(u>>s&1),c[6>s?s:8>s?s+1:l-15+s][8]=m,c[8][8>s?l-s-1:9>s?15-s:14-s]=m;if(c[l-8][8]=!e,7<=o){for(u=r.A(o),s=0;18>s;s+=1)m=!e&&1==(u>>s&1),c[Math.floor(s/3)][s%3+l-8-3]=m;for(s=0;18>s;s+=1)m=!e&&1==(u>>s&1),c[s%3+l-8-3][Math.floor(s/3)]=m}if(null==f){for(e=d.I(o,i),u=function(){var e=[],t=0,n={B:function(){return e},c:function(t){return 1==(e[Math.floor(t/8)]>>>7-t%8&1)},put:function(e,t){for(var r=0;r>>t-r-1&1))},f:function(){return t},m:function(n){var r=Math.floor(t/8);e.length<=r&&e.push(0),n&&(e[r]|=128>>>t%8),t+=1}};return n}(),s=0;s8*m)throw Error("code length overflow. ("+u.f()+">"+8*m+")");for(u.f()+4<=8*m&&u.put(0,4);0!=u.f()%8;)u.m(!1);for(;!(u.f()>=8*m||(u.put(236,8),u.f()>=8*m));)u.put(17,8);var b=0;for(m=s=0,p=Array(e.length),g=Array(e.length),y=0;yy;y+=1)null==c[s][g-y]&&(v=!1,p>>m&1)),n(s,g-y)&&(v=!v),c[s][g-y]=v,-1==--m&&(p+=1,m=7));if(0>(s+=u)||l<=s){s-=u,u=-u;break}}}var i=n[u],c=null,l=0,f=null,h=[],m={u:function(t){t=function(t){var n=e.s(t);return{S:function(){return 4},b:function(){return n.length},write:function(e){for(var t=0;te||l<=e||0>t||l<=t)throw Error(e+","+t);return c[e][t]},h:function(){return l},J:function(){for(var e=0,t=0,n=0;8>n;n+=1){s(!0,n);var o=r.D(m);(0==n||e>o)&&(e=o,t=n)}s(!1,t)}};return m}function t(e,n){if(void 0===e.length)throw Error(e.length+"/"+n);var r=function(){for(var t=0;td.b()-e.b())return d;for(var n=o.g(d.c(0))-o.g(e.c(0)),r=Array(d.b()),u=0;ur?t.push(r):2048>r?t.push(192|r>>6,128|63&r):55296>r||57344<=r?t.push(224|r>>12,128|r>>6&63,128|63&r):(n++,r=65536+((1023&r)<<10|1023&e.charCodeAt(n)),t.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r))}return t};var n={L:1,M:0,Q:3,H:2},r=function(){function e(e){for(var t=0;0!=e;)t+=1,e>>>=1;return t}var n=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]];return{w:function(t){for(var n=t<<10;0<=e(n)-e(1335);)n^=1335<t||40t?8:16},D:function(e){for(var t=e.h(),n=0,r=0;r=a;a+=1)if(!(0>r+a||t<=r+a))for(var s=-1;1>=s;s+=1)0>o+s||t<=o+s||(0!=a||0!=s)&&u==e.a(r+a,o+s)&&(d+=1);5n;n+=1)e[n]=1<n;n+=1)e[n]=e[n-4]^e[n-5]^e[n-6]^e[n-8];for(n=0;255>n;n+=1)t[e[n]]=n;return{g:function(e){if(1>e)throw Error("glog("+e+")");return t[e]},i:function(t){for(;0>t;)t+=255;for(;256<=t;)t-=255;return e[t]}}}(),d=function(){function e(e,r){switch(r){case n.L:return t[4*(e-1)];case n.M:return t[4*(e-1)+1];case n.Q:return t[4*(e-1)+2];case n.H:return t[4*(e-1)+3]}}var t=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12,7,37,13],[5,122,98,1,123,99],[7,73,45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]];return{I:function(t,n){var r=e(t,n);if(void 0===r)throw Error("bad rs block @ typeNumber:"+t+"/errorCorrectLevel:"+n);t=r.length/3,n=[];for(var o=0;o{const{connectionState:t,authState:n,authQrCode:r,settings:{byKey:{language:o}}}=e;return{connectionState:t,authState:n,authQrCode:r,language:o}}),((e,t)=>(0,f.ei)(t,["returnToAuthPhoneNumber","setSettingOption"])))((({connectionState:e,authState:t,authQrCode:n,language:r,returnToAuthPhoneNumber:o,setSettingOption:d})=>{const u=te(),a=(0,X.Z)(),s=(0,L.sO)(null),i=ee(u,"ContinueOnThisLanguage"),[c,l,f]=(0,Z.Z)();(0,L.d4)((()=>{if(!n||"connectionStateReady"!==e)return;const t=s.current;t.innerHTML="",t.classList.remove("pre-animate"),Se.render({text:`tg://login?token=${n.token}`,radius:.5,ecLevel:"M",fill:"#4E96D4",size:280},t)}),[e,n]);const h=(0,L.I4)((()=>{l(),(0,Y.m0)(u,(()=>{f(),d({language:u})}))}),[l,d,u,f]),m="authorizationStateWaitQrCode"===t;return L.ZP.createElement("div",{id:"auth-qr-form",className:"custom-scroll"},L.ZP.createElement("div",{className:"auth-form qr"},n?L.ZP.createElement("div",{key:"qr-container",className:"qr-container pre-animate",ref:s}):L.ZP.createElement("div",{key:"qr-loading",className:"qr-loading"},L.ZP.createElement(de.Z,null)),L.ZP.createElement("h3",null,a("Login.QR.Title")),L.ZP.createElement("ol",null,L.ZP.createElement("li",null,L.ZP.createElement("span",null,a("Login.QR.Help1"))),L.ZP.createElement("li",null,L.ZP.createElement("span",null,(0,ae.Z)(a("Login.QR.Help2"),["simple_markdown"]))),L.ZP.createElement("li",null,L.ZP.createElement("span",null,a("Login.QR.Help3")))),m&&L.ZP.createElement(ne.Z,{isText:!0,onClick:o},a("Login.QR.Cancel")),u&&u!==r&&i&&L.ZP.createElement(ne.Z,{isText:!0,isLoading:c,onClick:h},i)))}))),Pe=(0,L.X$)((0,t.c$)((e=>(0,f.ei)(e,["authState"])),((e,t)=>(0,f.ei)(t,["reset","initApi","returnToAuthPhoneNumber","goToAuthQrCode"])))((({authState:e,reset:t,initApi:r,returnToAuthPhoneNumber:o,goToAuthQrCode:d})=>{(0,L.d4)((()=>{t(),r()}),[t,r]);const u="iOS"===n.Lt||"Android"===n.Lt;switch((0,g.ZP)(!u&&"authorizationStateWaitPhoneNumber"===e||u&&"authorizationStateWaitQrCode"===e,(()=>{u?o():d()})),(0,L.d4)((()=>(R.Z.disableRefresh(),()=>{R.Z.enableRefresh()})),[]),e){case"authorizationStateWaitCode":return L.ZP.createElement(J,{page:"authCode",key:"authCode"},L.ZP.createElement(ve,null));case"authorizationStateWaitPassword":return L.ZP.createElement(J,{page:"authPassword",key:"authPassword"},L.ZP.createElement(be,null));case"authorizationStateWaitRegistration":return L.ZP.createElement(we,null);case"authorizationStateWaitPhoneNumber":return L.ZP.createElement(J,{page:"authPhoneNumber",key:"authPhoneNumber"},L.ZP.createElement(ge,null));case"authorizationStateWaitQrCode":return L.ZP.createElement(J,{page:"authQrCode",key:"authQrCode"},L.ZP.createElement(Ee,null));default:return u?L.ZP.createElement(J,{page:"authPhoneNumber",key:"authPhoneNumber"},L.ZP.createElement(ge,null)):L.ZP.createElement(J,{page:"authQrCode",key:"authQrCode"},L.ZP.createElement(Ee,null))}}))),Me=(0,L.X$)((()=>{const e=(0,ye.Z)(V.gl.Main,"Main");return e?L.ZP.createElement(e,null):void 0}));var Ae=s(5359);const ke=()=>L.ZP.createElement("div",{id:"AppInactive"},L.ZP.createElement("div",{className:"content"},L.ZP.createElement("img",{src:Ae,alt:""}),L.ZP.createElement("h3",{className:"title"},"Such error, many tabs"),L.ZP.createElement("div",{className:"description"},"Telegram supports only one active tab with the app.",L.ZP.createElement("br",null),"Please reload this page to continue using this tab or close it."),L.ZP.createElement("div",{className:"actions"},L.ZP.createElement(ne.Z,{isText:!0,ripple:!0,onClick:()=>{window.location.reload()}},"Reload app"))));function Te(){return t.ZP.createElement(J,{page:"main",key:"main"},t.ZP.createElement(Me,null))}const Ne=(0,t.c$)((e=>(0,f.ei)(e,["authState"])),((e,t)=>(0,f.ei)(t,["disconnect"])))((({authState:n,disconnect:r})=>{const[o,d]=(0,Z.Z)(!1);if((0,L.d4)((()=>{(0,R.z)(),x=()=>{r(),document.title=`${e.Ti}${e.ou}`,d()}}),[r,d]),o)return t.ZP.createElement(ke,null);if(n)switch(n){case"authorizationStateWaitPhoneNumber":case"authorizationStateWaitCode":case"authorizationStateWaitPassword":case"authorizationStateWaitRegistration":case"authorizationStateWaitQrCode":return t.ZP.createElement(Pe,null);case"authorizationStateClosed":case"authorizationStateClosing":case"authorizationStateLoggingOut":case"authorizationStateReady":return Te()}return(0,m.ti)(!0)?Te():t.ZP.createElement(Pe,null)}));e.eM&&console.log(">>> INIT"),(0,t.uC)().init(),e.eM&&console.log(">>> START INITIAL RENDER"),u.Z.render(t.ZP.createElement(Ne,null),document.getElementById("root")),e.eM&&console.log(">>> FINISH INITIAL RENDER"),document.addEventListener("dblclick",(()=>{console.warn("GLOBAL STATE",(0,t.Rd)())}))})()})(); +//# sourceMappingURL=main.4f9a89db11e14d2fa319.js.map \ No newline at end of file diff --git a/dist/main.4f9a89db11e14d2fa319.js.map b/dist/main.4f9a89db11e14d2fa319.js.map new file mode 100644 index 00000000..2fb49284 --- /dev/null +++ b/dist/main.4f9a89db11e14d2fa319.js.map @@ -0,0 +1 @@ +{"version":3,"file":"main.4f9a89db11e14d2fa319.js","mappings":"uBACIA,EADAC,ECAAC,EACAC,ECwCAC,EASAC,E,wFChCJ,IAAIC,EACJ,MAAMC,EAAgB,IAAIC,IACpBC,EAA0B,IAAID,IAI7B,SAASE,EAAQC,EAAuBC,GAe7C,OAdKN,IACCO,EAAAA,IAEFC,QAAQC,IAAI,yBAGdT,EAAS,IAAIU,OAAO,IAAIC,IAAI,mBA6ChC,SAA2BN,GACzBL,EAAOY,iBAAiB,WAAW,EAAGC,KAAAA,MACpC,GAAkB,WAAdA,EAAKC,KACPT,EAASQ,EAAKE,aACT,GAAkB,mBAAdF,EAAKC,KAA2B,CACzC,MAAME,EAAef,EAAcgB,IAAIJ,EAAKK,WACxCF,IACEH,EAAKM,MACPH,EAAaI,OAAOP,EAAKM,OAEzBH,EAAaK,QAAQR,EAAKS,gBAGzB,GAAkB,mBAAdT,EAAKC,KAA2B,SACzC,UAAAb,EAAcgB,IAAIJ,EAAKK,kBAAvB,mBAAmCK,gBAAnC,mBAAiDV,EAAKW,mBACjD,GAAkB,mBAAdX,EAAKC,KACd,MAAMD,EAAKM,SA5DbM,CAAkBpB,GAEW,QAAzBC,EAAYoB,UAuGlBC,OAAOf,iBAAiB,SAASgB,UAC/B,UACQC,QAAQC,KAAK,CACjBC,EAAY,CAAEjB,KAAM,UACpBkB,E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,EAAYE,IAIZD,EACF,OAAO,mBAAC,GAAD,MAGT,GAAIhrD,EACF,OAAQA,GACN,IAAK,oCACL,IAAK,6BACL,IAAK,iCACL,IAAK,qCACL,IAAK,+BACH,OAAO,mBAAC,GAAD,MACT,IAAK,2BACL,IAAK,4BACL,IAAK,+BACL,IAAK,0BACH,OAAO8qD,KAIb,OAAOtW,EAAAA,EAAAA,KAAiB,GAAQsW,KAAe,mBAAC,GAAD,SC1C7CvmF,EAAAA,IAEFC,QAAQC,IAAI,aAGdsH,EAAAA,EAAAA,MAAcguB,OAEVx1B,EAAAA,IAEFC,QAAQC,IAAI,4BAGdymF,EAAAA,EAAAA,OACE,mBAAC,GAAD,MACAz9E,SAAS62E,eAAe,SAGtB//E,EAAAA,IAEFC,QAAQC,IAAI,6BAGdgJ,SAAS7I,iBAAiB,YAAY,KAEpCJ,QAAQqC,KAAK,gBAAgB2wB,EAAAA,EAAAA,W","sources":["webpack://telegram-t/webpack/runtime/create fake namespace object","webpack://telegram-t/webpack/runtime/load script","webpack://telegram-t/webpack/runtime/css loading","webpack://telegram-t/./src/api/gramjs/worker/provider.ts","webpack://telegram-t/./src/api/types/media.ts","webpack://telegram-t/./src/api/types/messages.ts","webpack://telegram-t/./src/lib/punycode.js","webpack://telegram-t/./src/components/common/SafeLink.tsx","webpack://telegram-t/./src/components/common/helpers/documentInfo.ts","webpack://telegram-t/./src/components/common/helpers/parseEmojiOnlyString.ts","webpack://telegram-t/./src/components/common/UserLink.tsx","webpack://telegram-t/./src/components/common/MessageLink.tsx","webpack://telegram-t/./src/components/common/ChatLink.tsx","webpack://telegram-t/./src/components/common/helpers/renderActionMessageText.tsx","webpack://telegram-t/./src/components/common/helpers/renderText.tsx","webpack://telegram-t/./src/components/middle/helpers/preventMessageInputBlur.ts","webpack://telegram-t/./src/components/middle/message/MentionLink.tsx","webpack://telegram-t/./src/components/ui/Button.tsx","webpack://telegram-t/./src/components/ui/Checkbox.tsx","webpack://telegram-t/./src/components/ui/DropdownMenu.tsx","webpack://telegram-t/./src/components/ui/InputText.tsx","webpack://telegram-t/./src/components/ui/Link.tsx","webpack://telegram-t/./src/components/ui/Loading.tsx","webpack://telegram-t/./src/components/ui/Menu.tsx","webpack://telegram-t/./src/components/ui/MenuItem.tsx","webpack://telegram-t/./src/components/ui/RippleEffect.tsx","webpack://telegram-t/./src/components/ui/Spinner.tsx","webpack://telegram-t/./src/config.ts","webpack://telegram-t/./src/hooks/useEffectWithPrevDeps.ts","webpack://telegram-t/./src/hooks/useFlag.ts","webpack://telegram-t/./src/hooks/useForceUpdate.ts","webpack://telegram-t/./src/hooks/useHeavyAnimationCheck.ts","webpack://telegram-t/./src/hooks/useHistoryBack.ts","webpack://telegram-t/./src/hooks/useKeyboardListNavigation.ts","webpack://telegram-t/./src/hooks/useLang.ts","webpack://telegram-t/./src/hooks/useModuleLoader.ts","webpack://telegram-t/./src/hooks/useOnChange.ts","webpack://telegram-t/./src/hooks/usePrevious.ts","webpack://telegram-t/./src/hooks/useShowTransition.ts","webpack://telegram-t/./src/hooks/useVirtualBackdrop.ts","webpack://telegram-t/./src/lib/teact/dom-events.ts","webpack://telegram-t/./src/lib/teact/teact-dom.ts","webpack://telegram-t/./src/lib/teact/teact.ts","webpack://telegram-t/./src/lib/teact/teactn.tsx","webpack://telegram-t/./src/lib/twemojiRegex.js","webpack://telegram-t/./src/modules/actions/api/initial.ts","webpack://telegram-t/./src/modules/actions/api/settings.ts","webpack://telegram-t/./src/modules/actions/apiUpdaters/initial.ts","webpack://telegram-t/./src/modules/actions/ui/initial.ts","webpack://telegram-t/./src/modules/actions/ui/settings.ts","webpack://telegram-t/./src/modules/helpers/chats.ts","webpack://telegram-t/./src/modules/helpers/messages.ts","webpack://telegram-t/./src/modules/helpers/messageMedia.ts","webpack://telegram-t/./src/modules/helpers/localSearch.ts","webpack://telegram-t/./src/modules/helpers/payments.ts","webpack://telegram-t/./src/modules/helpers/users.ts","webpack://telegram-t/./src/modules/reducers/chats.ts","webpack://telegram-t/./src/modules/reducers/messages.ts","webpack://telegram-t/./src/modules/reducers/symbols.ts","webpack://telegram-t/./src/modules/reducers/users.ts","webpack://telegram-t/./src/modules/reducers/globalSearch.ts","webpack://telegram-t/./src/modules/reducers/localSearch.ts","webpack://telegram-t/./src/modules/reducers/management.ts","webpack://telegram-t/./src/modules/reducers/settings.ts","webpack://telegram-t/./src/modules/reducers/twoFaSettings.ts","webpack://telegram-t/./src/modules/reducers/payments.ts","webpack://telegram-t/./src/modules/selectors/users.ts","webpack://telegram-t/./src/modules/selectors/settings.ts","webpack://telegram-t/./src/modules/selectors/chats.ts","webpack://telegram-t/./src/modules/selectors/symbols.ts","webpack://telegram-t/./src/modules/selectors/messages.ts","webpack://telegram-t/./src/modules/selectors/localSearch.ts","webpack://telegram-t/./src/modules/selectors/management.ts","webpack://telegram-t/./src/modules/selectors/ui.ts","webpack://telegram-t/./src/modules/selectors/globalSearch.ts","webpack://telegram-t/./src/modules/selectors/payments.ts","webpack://telegram-t/./src/types/index.ts","webpack://telegram-t/./src/util/animation.ts","webpack://telegram-t/./src/util/appBadge.ts","webpack://telegram-t/./src/util/arePropsShallowEqual.ts","webpack://telegram-t/./src/util/buildClassName.ts","webpack://telegram-t/./src/util/cacheApi.ts","webpack://telegram-t/./src/util/captureEscKeyListener.ts","webpack://telegram-t/./src/util/captureKeyboardListeners.ts","webpack://telegram-t/./src/util/dateFormat.ts","webpack://telegram-t/./src/util/emoji.ts","webpack://telegram-t/./src/util/environmentWebp.ts","webpack://telegram-t/./src/util/environmentSystemTheme.ts","webpack://telegram-t/./src/util/environment.ts","webpack://telegram-t/./src/util/files.ts","webpack://telegram-t/./src/util/formatCurrency.ts","webpack://telegram-t/./src/util/generateIdFor.ts","webpack://telegram-t/./src/util/getReadableErrorText.ts","webpack://telegram-t/./src/util/handleError.ts","webpack://telegram-t/./src/util/iteratees.ts","webpack://telegram-t/./src/util/langProvider.ts","webpack://telegram-t/./src/util/callbacks.ts","webpack://telegram-t/./src/util/oggToWav.ts","webpack://telegram-t/./src/util/mediaLoader.ts","webpack://telegram-t/./src/util/memo.ts","webpack://telegram-t/./src/util/moduleLoader.ts","webpack://telegram-t/./src/util/notifications.ts","webpack://telegram-t/./src/util/phoneNumber.ts","webpack://telegram-t/./src/util/routing.ts","webpack://telegram-t/./src/util/schedulers.ts","webpack://telegram-t/./src/util/searchWords.ts","webpack://telegram-t/./src/util/serverTime.ts","webpack://telegram-t/./node_modules/idb-keyval/dist/esm/index.js","webpack://telegram-t/./node_modules/safari-14-idb-fix/dist/esm/index.js","webpack://telegram-t/./src/util/sessions.ts","webpack://telegram-t/./src/util/switchTheme.ts","webpack://telegram-t/./src/util/textFormat.ts","webpack://telegram-t/./src/util/trimText.ts","webpack://telegram-t/./src/util/webpToPng.ts","webpack://telegram-t/./src/util/websync.ts","webpack://telegram-t/./src/util/windowSize.ts","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/publicPath","webpack://telegram-t/webpack/runtime/jsonp chunk loading","webpack://telegram-t/./src/util/setupServiceWorker.ts","webpack://telegram-t/./src/global/initial.ts","webpack://telegram-t/./src/global/cache.ts","webpack://telegram-t/./src/global/index.ts","webpack://telegram-t/./src/util/activeTabMonitor.ts","webpack://telegram-t/./src/util/fonts.ts","webpack://telegram-t/./src/components/common/UiLoader.tsx","webpack://telegram-t/./src/hooks/useLangString.ts","webpack://telegram-t/./src/components/auth/helpers/getSuggestedLanguage.ts","webpack://telegram-t/./src/components/auth/CountryCodeInput.tsx","webpack://telegram-t/./src/components/auth/AuthPhoneNumber.tsx","webpack://telegram-t/./src/components/auth/AuthCode.async.tsx","webpack://telegram-t/./src/components/auth/AuthPassword.async.tsx","webpack://telegram-t/./src/components/auth/AuthRegister.async.tsx","webpack://telegram-t/./node_modules/qr-creator/dist/qr-creator.es6.min.js","webpack://telegram-t/./src/components/auth/AuthQrCode.tsx","webpack://telegram-t/./src/components/auth/Auth.tsx","webpack://telegram-t/./src/components/main/Main.async.tsx","webpack://telegram-t/./src/components/main/AppInactive.tsx","webpack://telegram-t/./src/App.tsx","webpack://telegram-t/./src/index.tsx"],"sourcesContent":["var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__);\nvar leafPrototypes;\n// create a fake namespace object\n// mode & 1: value is a module id, require it\n// mode & 2: merge all properties of value into the ns\n// mode & 4: return value when already ns object\n// mode & 16: return value when it's Promise-like\n// mode & 8|1: behave like require\n__webpack_require__.t = function(value, mode) {\n\tif(mode & 1) value = this(value);\n\tif(mode & 8) return value;\n\tif(typeof value === 'object' && value) {\n\t\tif((mode & 4) && value.__esModule) return value;\n\t\tif((mode & 16) && typeof value.then === 'function') return value;\n\t}\n\tvar ns = Object.create(null);\n\t__webpack_require__.r(ns);\n\tvar def = {};\n\tleafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];\n\tfor(var current = mode & 2 && value; typeof current == 'object' && !~leafPrototypes.indexOf(current); current = getProto(current)) {\n\t\tObject.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key])));\n\t}\n\tdef['default'] = () => (value);\n\t__webpack_require__.d(ns, def);\n\treturn ns;\n};","var inProgress = {};\nvar dataWebpackPrefix = \"telegram-t:\";\n// loadScript function to load a script via script tag\n__webpack_require__.l = (url, done, key, chunkId) => {\n\tif(inProgress[url]) { inProgress[url].push(done); return; }\n\tvar script, needAttach;\n\tif(key !== undefined) {\n\t\tvar scripts = document.getElementsByTagName(\"script\");\n\t\tfor(var i = 0; i < scripts.length; i++) {\n\t\t\tvar s = scripts[i];\n\t\t\tif(s.getAttribute(\"src\") == url || s.getAttribute(\"data-webpack\") == dataWebpackPrefix + key) { script = s; break; }\n\t\t}\n\t}\n\tif(!script) {\n\t\tneedAttach = true;\n\t\tscript = document.createElement('script');\n\n\t\tscript.charset = 'utf-8';\n\t\tscript.timeout = 120;\n\t\tif (__webpack_require__.nc) {\n\t\t\tscript.setAttribute(\"nonce\", __webpack_require__.nc);\n\t\t}\n\t\tscript.setAttribute(\"data-webpack\", dataWebpackPrefix + key);\n\t\tscript.src = url;\n\t}\n\tinProgress[url] = [done];\n\tvar onScriptComplete = (prev, event) => {\n\t\t// avoid mem leaks in IE.\n\t\tscript.onerror = script.onload = null;\n\t\tclearTimeout(timeout);\n\t\tvar doneFns = inProgress[url];\n\t\tdelete inProgress[url];\n\t\tscript.parentNode && script.parentNode.removeChild(script);\n\t\tdoneFns && doneFns.forEach((fn) => (fn(event)));\n\t\tif(prev) return prev(event);\n\t}\n\t;\n\tvar timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), 120000);\n\tscript.onerror = onScriptComplete.bind(null, script.onerror);\n\tscript.onload = onScriptComplete.bind(null, script.onload);\n\tneedAttach && document.head.appendChild(script);\n};","var createStylesheet = (chunkId, fullhref, resolve, reject) => {\n\tvar linkTag = document.createElement(\"link\");\n\n\tlinkTag.rel = \"stylesheet\";\n\tlinkTag.type = \"text/css\";\n\tvar onLinkComplete = (event) => {\n\t\t// avoid mem leaks.\n\t\tlinkTag.onerror = linkTag.onload = null;\n\t\tif (event.type === 'load') {\n\t\t\tresolve();\n\t\t} else {\n\t\t\tvar errorType = event && (event.type === 'load' ? 'missing' : event.type);\n\t\t\tvar realHref = event && event.target && event.target.href || fullhref;\n\t\t\tvar err = new Error(\"Loading CSS chunk \" + chunkId + \" failed.\\n(\" + realHref + \")\");\n\t\t\terr.code = \"CSS_CHUNK_LOAD_FAILED\";\n\t\t\terr.type = errorType;\n\t\t\terr.request = realHref;\n\t\t\tlinkTag.parentNode.removeChild(linkTag)\n\t\t\treject(err);\n\t\t}\n\t}\n\tlinkTag.onerror = linkTag.onload = onLinkComplete;\n\tlinkTag.href = fullhref;\n\n\tdocument.head.appendChild(linkTag);\n\treturn linkTag;\n};\nvar findStylesheet = (href, fullhref) => {\n\tvar existingLinkTags = document.getElementsByTagName(\"link\");\n\tfor(var i = 0; i < existingLinkTags.length; i++) {\n\t\tvar tag = existingLinkTags[i];\n\t\tvar dataHref = tag.getAttribute(\"data-href\") || tag.getAttribute(\"href\");\n\t\tif(tag.rel === \"stylesheet\" && (dataHref === href || dataHref === fullhref)) return tag;\n\t}\n\tvar existingStyleTags = document.getElementsByTagName(\"style\");\n\tfor(var i = 0; i < existingStyleTags.length; i++) {\n\t\tvar tag = existingStyleTags[i];\n\t\tvar dataHref = tag.getAttribute(\"data-href\");\n\t\tif(dataHref === href || dataHref === fullhref) return tag;\n\t}\n};\nvar loadStylesheet = (chunkId) => {\n\treturn new Promise((resolve, reject) => {\n\t\tvar href = __webpack_require__.miniCssF(chunkId);\n\t\tvar fullhref = __webpack_require__.p + href;\n\t\tif(findStylesheet(href, fullhref)) return resolve();\n\t\tcreateStylesheet(chunkId, fullhref, resolve, reject);\n\t});\n}\n// object to store loaded CSS chunks\nvar installedCssChunks = {\n\t179: 0\n};\n\n__webpack_require__.f.miniCss = (chunkId, promises) => {\n\tvar cssChunks = {\"133\":1,\"306\":1,\"325\":1,\"472\":1,\"701\":1};\n\tif(installedCssChunks[chunkId]) promises.push(installedCssChunks[chunkId]);\n\telse if(installedCssChunks[chunkId] !== 0 && cssChunks[chunkId]) {\n\t\tpromises.push(installedCssChunks[chunkId] = loadStylesheet(chunkId).then(() => {\n\t\t\tinstalledCssChunks[chunkId] = 0;\n\t\t}, (e) => {\n\t\t\tdelete installedCssChunks[chunkId];\n\t\t\tthrow e;\n\t\t}));\n\t}\n};\n\n// no hmr","import { ApiInitialArgs, ApiOnProgress, OnApiUpdate } from '../../types';\nimport { Methods, MethodArgs, MethodResponse } from '../methods/types';\nimport { WorkerMessageEvent, ThenArg, OriginRequest } from './types';\n\nimport { DEBUG } from '../../../config';\nimport generateIdFor from '../../../util/generateIdFor';\nimport { pause } from '../../../util/schedulers';\n\ntype RequestStates = {\n messageId: string;\n resolve: Function;\n reject: Function;\n callback?: AnyToVoidFunction;\n};\n\nconst HEALTH_CHECK_TIMEOUT = 150;\nconst HEALTH_CHECK_MIN_DELAY = 5 * 1000; // 5 sec\n\nlet worker: Worker;\nconst requestStates = new Map();\nconst requestStatesByCallback = new Map();\n\n// TODO Re-use `util/WorkerConnector.ts`\n\nexport function initApi(onUpdate: OnApiUpdate, initialArgs: ApiInitialArgs) {\n if (!worker) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START LOAD WORKER');\n }\n\n worker = new Worker(new URL('./worker.ts', import.meta.url));\n subscribeToWorker(onUpdate);\n\n if (initialArgs.platform === 'iOS') {\n setupIosHealthCheck();\n }\n }\n\n return makeRequest({\n type: 'initApi',\n args: [initialArgs],\n });\n}\n\nexport function callApi(fnName: T, ...args: MethodArgs) {\n if (!worker) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('API is not initialized');\n }\n\n return undefined;\n }\n\n return makeRequest({\n type: 'callMethod',\n name: fnName,\n args,\n }) as MethodResponse;\n}\n\nexport function cancelApiProgress(progressCallback: ApiOnProgress) {\n progressCallback.isCanceled = true;\n\n const { messageId } = requestStatesByCallback.get(progressCallback) || {};\n if (!messageId) {\n return;\n }\n\n worker.postMessage({\n type: 'cancelProgress',\n messageId,\n });\n}\n\nfunction subscribeToWorker(onUpdate: OnApiUpdate) {\n worker.addEventListener('message', ({ data }: WorkerMessageEvent) => {\n if (data.type === 'update') {\n onUpdate(data.update);\n } else if (data.type === 'methodResponse') {\n const requestState = requestStates.get(data.messageId);\n if (requestState) {\n if (data.error) {\n requestState.reject(data.error);\n } else {\n requestState.resolve(data.response);\n }\n }\n } else if (data.type === 'methodCallback') {\n requestStates.get(data.messageId)?.callback?.(...data.callbackArgs);\n } else if (data.type === 'unhandledError') {\n throw data.error;\n }\n });\n}\n\nfunction makeRequest(message: OriginRequest) {\n const messageId = generateIdFor(requestStates);\n const payload: OriginRequest = {\n messageId,\n ...message,\n };\n\n const requestState = { messageId } as RequestStates;\n\n // Re-wrap type because of `postMessage`\n const promise: Promise>> = new Promise((resolve, reject) => {\n Object.assign(requestState, { resolve, reject });\n });\n\n if (('args' in payload) && typeof payload.args[1] === 'function') {\n const callback = payload.args.pop() as AnyToVoidFunction;\n requestState.callback = callback;\n requestStatesByCallback.set(callback, requestState);\n }\n\n requestStates.set(messageId, requestState);\n promise\n .catch(() => undefined)\n .finally(() => {\n requestStates.delete(messageId);\n\n if (requestState.callback) {\n requestStatesByCallback.delete(requestState.callback);\n }\n });\n\n worker.postMessage(payload);\n\n return promise;\n}\n\nconst startedAt = Date.now();\n\n// Workaround for iOS sometimes stops interacting with worker\nfunction setupIosHealthCheck() {\n window.addEventListener('focus', async () => {\n try {\n await Promise.race([\n makeRequest({ type: 'ping' }),\n pause(HEALTH_CHECK_TIMEOUT).then(() => Promise.reject(new Error('HEALTH_CHECK_TIMEOUT'))),\n ]);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(err);\n\n if (Date.now() - startedAt >= HEALTH_CHECK_MIN_DELAY) {\n window.location.reload();\n }\n }\n });\n}\n","// We cache avatars as Data URI for faster initial load\n// and messages media as Blob for smaller size.\n\nexport enum ApiMediaFormat {\n BlobUrl,\n Lottie,\n Progressive,\n Stream,\n}\n\nexport type ApiParsedMedia = string | Blob | AnyLiteral | ArrayBuffer;\nexport type ApiPreparedMedia = string | AnyLiteral;\nexport type ApiMediaFormatToPrepared = T extends ApiMediaFormat.Lottie ? AnyLiteral : string;\n","export interface ApiDimensions {\n width: number;\n height: number;\n}\n\nexport interface ApiPhotoSize extends ApiDimensions {\n type: 's' | 'm' | 'x' | 'y' | 'z';\n}\n\nexport interface ApiThumbnail extends ApiDimensions {\n dataUri: string;\n}\n\nexport interface ApiPhoto {\n id: string;\n thumbnail?: ApiThumbnail;\n sizes: ApiPhotoSize[];\n blobUrl?: string;\n}\n\nexport interface ApiSticker {\n id: string;\n stickerSetId: string;\n stickerSetAccessHash?: string;\n emoji?: string;\n isAnimated: boolean;\n width?: number;\n height?: number;\n thumbnail?: ApiThumbnail;\n isPreloadedGlobally?: boolean;\n}\n\nexport interface ApiStickerSet {\n archived?: true;\n isAnimated?: true;\n installedDate?: number;\n id: string;\n accessHash: string;\n title: string;\n hasThumbnail?: boolean;\n count: number;\n stickers?: ApiSticker[];\n packs?: Record;\n covers?: ApiSticker[];\n shortName: string;\n}\n\nexport interface ApiVideo {\n id: string;\n mimeType: string;\n duration: number;\n fileName: string;\n width?: number;\n height?: number;\n supportsStreaming?: boolean;\n isRound?: boolean;\n isGif?: boolean;\n thumbnail?: ApiThumbnail;\n blobUrl?: string;\n size: number;\n}\n\nexport interface ApiAudio {\n 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 duration: number;\n waveform?: number[];\n}\n\nexport interface ApiDocument {\n id?: string;\n fileName: string;\n size: number;\n timestamp?: number;\n mimeType: string;\n thumbnail?: ApiThumbnail;\n previewBlobUrl?: string;\n mediaType?: 'photo' | 'video';\n mediaSize?: ApiDimensions;\n}\n\nexport interface ApiContact {\n firstName: string;\n lastName: string;\n phoneNumber: string;\n userId: string;\n}\n\nexport interface ApiPollAnswer {\n text: string;\n option: string;\n}\n\nexport interface ApiPollResult {\n isChosen?: true;\n isCorrect?: true;\n option: string;\n votersCount: number;\n}\n\nexport interface ApiPoll {\n id: string;\n summary: {\n closed?: true;\n isPublic?: true;\n multipleChoice?: true;\n quiz?: true;\n question: string;\n answers: ApiPollAnswer[];\n closePeriod?: number;\n closeDate?: number;\n };\n results: {\n results?: ApiPollResult[];\n totalVoters?: number;\n recentVoterIds?: string[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n}\n\nexport interface ApiInvoice {\n text: string;\n title: string;\n photoUrl?: string;\n amount: number;\n currency: string;\n receiptMsgId?: number;\n isTest?: boolean;\n}\n\nexport type ApiNewPoll = {\n summary: ApiPoll['summary'];\n quiz?: {\n correctAnswers: string[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n};\n\nexport interface ApiAction {\n text: string;\n targetUserIds?: string[];\n targetChatId?: string;\n type: 'historyClear' | 'contactSignUp' | 'chatCreate' | 'other';\n photo?: ApiPhoto;\n amount?: number;\n currency?: string;\n translationValues: string[];\n}\n\nexport interface ApiWebPage {\n id: number;\n url: string;\n displayUrl: string;\n type?: string;\n siteName?: string;\n title?: string;\n description?: string;\n photo?: ApiPhoto;\n duration?: number;\n document?: ApiDocument;\n video?: ApiVideo;\n}\n\nexport interface ApiMessageForwardInfo {\n isChannelPost: boolean;\n channelPostId?: number;\n isLinkedChannelPost?: boolean;\n fromChatId?: string;\n senderUserId?: string;\n fromMessageId?: number;\n hiddenUserName?: string;\n adminTitle?: string;\n}\n\nexport interface ApiMessageEntity {\n type: string;\n offset: number;\n length: number;\n userId?: string;\n url?: string;\n}\n\nexport enum ApiMessageEntityTypes {\n Bold = 'MessageEntityBold',\n Blockquote = 'MessageEntityBlockquote',\n BotCommand = 'MessageEntityBotCommand',\n Cashtag = 'MessageEntityCashtag',\n Code = 'MessageEntityCode',\n Email = 'MessageEntityEmail',\n Hashtag = 'MessageEntityHashtag',\n Italic = 'MessageEntityItalic',\n MentionName = 'MessageEntityMentionName',\n Mention = 'MessageEntityMention',\n Phone = 'MessageEntityPhone',\n Pre = 'MessageEntityPre',\n Strike = 'MessageEntityStrike',\n TextUrl = 'MessageEntityTextUrl',\n Url = 'MessageEntityUrl',\n Underline = 'MessageEntityUnderline',\n Unknown = 'MessageEntityUnknown',\n}\n\nexport interface ApiFormattedText {\n text: string;\n entities?: ApiMessageEntity[];\n}\n\nexport interface ApiMessage {\n id: number;\n chatId: string;\n content: {\n text?: ApiFormattedText;\n photo?: ApiPhoto;\n video?: ApiVideo;\n document?: ApiDocument;\n sticker?: ApiSticker;\n contact?: ApiContact;\n poll?: ApiPoll;\n action?: ApiAction;\n webPage?: ApiWebPage;\n audio?: ApiAudio;\n voice?: ApiVoice;\n invoice?: ApiInvoice;\n };\n date: number;\n isOutgoing: boolean;\n senderId?: string;\n replyToChatId?: string;\n replyToMessageId?: number;\n replyToTopMessageId?: number;\n sendingState?: 'messageSendingStatePending' | 'messageSendingStateFailed';\n forwardInfo?: ApiMessageForwardInfo;\n isDeleting?: boolean;\n previousLocalId?: number;\n views?: number;\n isEdited?: boolean;\n 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}\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 interface ApiKeyboardButton {\n type: 'command' | 'url' | 'callback' | 'requestPoll' | 'buy' | 'NOT_SUPPORTED';\n text: string;\n messageId: number;\n value?: string;\n}\n\nexport type ApiKeyboardButtons = ApiKeyboardButton[][];\nexport type ApiReplyKeyboard = {\n keyboardPlaceholder?: string;\n isKeyboardSingleUse?: boolean;\n} & {\n [K in 'inlineButtons' | 'keyboardButtons']?: ApiKeyboardButtons;\n};\n\nexport type ApiMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'voice' | 'profilePhoto';\nexport type ApiGlobalMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'voice';\n\nexport type ApiReportReason = 'spam' | 'violence' | 'pornography' | 'childAbuse'\n| 'copyright' | 'geoIrrelevant' | 'fake' | 'other';\n\nexport const MAIN_THREAD_ID = -1;\n\n// `Symbol` can not be transferred from worker\nexport const MESSAGE_DELETED = 'MESSAGE_DELETED';\n","/* eslint-disable no-nested-ternary */\n/* eslint-disable no-bitwise */\n\nconst utf16 = {\n // The utf16-class is necessary to convert from javascripts internal character representation to unicode and back.\n decode: (input) => {\n const output = [];\n let i = 0;\n const len = input.length;\n let value;\n let extra;\n\n while (i < len) {\n value = input.charCodeAt(i++);\n if ((value & 0xf800) === 0xd800) {\n extra = input.charCodeAt(i++);\n if ((value & 0xfc00) !== 0xd800 || (extra & 0xfc00) !== 0xdc00) {\n throw new RangeError('UTF-16(decode): Illegal UTF-16 sequence');\n }\n value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;\n }\n output.push(value);\n }\n return output;\n },\n encode: (input) => {\n const output = [];\n let i = 0;\n const len = input.length;\n let value;\n\n while (i < len) {\n value = input[i++];\n if ((value & 0xf800) === 0xd800) {\n throw new RangeError('UTF-16(encode): Illegal UTF-16 value');\n }\n if (value > 0xffff) {\n value -= 0x10000;\n output.push(String.fromCharCode(((value >>> 10) & 0x3ff) | 0xd800));\n value = 0xdc00 | (value & 0x3ff);\n }\n output.push(String.fromCharCode(value));\n }\n return output.join('');\n },\n};\n\n// Default parameters\nconst initial_n = 0x80;\nconst initial_bias = 72;\nconst delimiter = '\\x2D';\nconst base = 36;\nconst damp = 700;\nconst tmin = 1;\nconst tmax = 26;\nconst skew = 38;\nconst maxint = 0x7fffffff;\n\n// decode_digit(cp) returns the numeric value of a basic code\n// point (for use in representing integers) in the range 0 to\n// base-1, or base if cp is does not represent a value.\n\nfunction decode_digit(cp) {\n return cp - 48 < 10 ? cp - 22 : cp - 65 < 26 ? cp - 65 : cp - 97 < 26 ? cp - 97 : base;\n}\n\n// ** Bias adaptation function **\nfunction adapt(delta, numpoints, firsttime) {\n let k;\n delta = firsttime ? Math.floor(delta / damp) : delta >> 1;\n delta += Math.floor(delta / numpoints);\n\n for (k = 0; delta > ((base - tmin) * tmax) >> 1; k += base) {\n delta = Math.floor(delta / (base - tmin));\n }\n return Math.floor(k + ((base - tmin + 1) * delta) / (delta + skew));\n}\n\n// Main decode\nfunction decode(input, preserveCase) {\n // Dont use utf16\n const output = [];\n const case_flags = [];\n const input_length = input.length;\n\n let n; let out; let i; let bias; let basic; let j; let ic; let oldi; let w; let k; let digit; let t; let len;\n\n // Initialize the state:\n\n n = initial_n;\n i = 0;\n bias = initial_bias;\n\n // Handle the basic code points: Let basic be the number of input code\n // points before the last delimiter, or 0 if there is none, then\n // copy the first basic code points to the output.\n\n basic = input.lastIndexOf(delimiter);\n if (basic < 0) basic = 0;\n\n for (j = 0; j < basic; ++j) {\n if (preserveCase) case_flags[output.length] = input.charCodeAt(j) - 65 < 26;\n if (input.charCodeAt(j) >= 0x80) {\n throw new RangeError('Illegal input >= 0x80');\n }\n output.push(input.charCodeAt(j));\n }\n\n // Main decoding loop: Start just after the last delimiter if any\n // basic code points were copied; start at the beginning otherwise.\n\n for (ic = basic > 0 ? basic + 1 : 0; ic < input_length;) {\n // ic is the index of the next character to be consumed,\n\n // Decode a generalized variable-length integer into delta,\n // which gets added to i. The overflow checking is easier\n // if we increase i as we go, then subtract off its starting\n // value at the end to obtain delta.\n for (oldi = i, w = 1, k = base; ; k += base) {\n if (ic >= input_length) {\n throw RangeError('punycode_bad_input(1)');\n }\n digit = decode_digit(input.charCodeAt(ic++));\n\n if (digit >= base) {\n throw RangeError('punycode_bad_input(2)');\n }\n if (digit > Math.floor((maxint - i) / w)) {\n throw RangeError('punycode_overflow(1)');\n }\n i += digit * w;\n t = k <= bias ? tmin : k >= bias + tmax ? tmax : k - bias;\n if (digit < t) {\n break;\n }\n if (w > Math.floor(maxint / (base - t))) {\n throw RangeError('punycode_overflow(2)');\n }\n w *= base - t;\n }\n\n out = output.length + 1;\n bias = adapt(i - oldi, out, oldi === 0);\n\n // i was supposed to wrap around from out to 0,\n // incrementing n each time, so we'll fix that now:\n if (Math.floor(i / out) > maxint - n) {\n throw RangeError('punycode_overflow(3)');\n }\n n += Math.floor(i / out);\n i %= out;\n\n // Insert n at position i of the output:\n // Case of last character determines uppercase flag:\n if (preserveCase) {\n case_flags.splice(i, 0, input.charCodeAt(ic - 1) - 65 < 26);\n }\n\n output.splice(i, 0, n);\n i++;\n }\n if (preserveCase) {\n for (i = 0, len = output.length; i < len; i++) {\n if (case_flags[i]) {\n output[i] = String.fromCharCode(output[i])\n .toUpperCase()\n .charCodeAt(0);\n }\n }\n }\n return utf16.encode(output);\n}\n\nfunction toUnicode(domain) {\n const domain_array = domain.split('.');\n const out = [];\n for (let i = 0; i < domain_array.length; ++i) {\n const s = domain_array[i];\n out.push(s.match(/^xn--/) ? decode(s.slice(4)) : s);\n }\n return out.join('.');\n}\n\nexport default toUnicode;\n","import React, { FC, memo, useCallback } from '../../lib/teact/teact';\nimport { getDispatch } from '../../lib/teact/teactn';\nimport convertPunycode from '../../lib/punycode';\n\nimport {\n DEBUG, RE_TG_LINK, RE_TME_LINK,\n} from '../../config';\nimport buildClassName from '../../util/buildClassName';\n\ntype OwnProps = {\n url?: string;\n text: string;\n className?: string;\n children?: any;\n isRtl?: boolean;\n};\n\nconst SafeLink: FC = ({\n url,\n text,\n className,\n children,\n isRtl,\n}) => {\n const { toggleSafeLinkModal, openTelegramLink } = getDispatch();\n\n const content = children || text;\n const isNotSafe = url !== content;\n\n const handleClick = useCallback((e: React.MouseEvent) => {\n if (\n e.ctrlKey || e.altKey || e.shiftKey || e.metaKey\n || !url || (!url.match(RE_TME_LINK) && !url.match(RE_TG_LINK))\n ) {\n if (isNotSafe) {\n toggleSafeLinkModal({ url });\n\n e.preventDefault();\n return false;\n }\n\n return true;\n }\n\n e.preventDefault();\n openTelegramLink({ url });\n\n return false;\n }, [isNotSafe, openTelegramLink, toggleSafeLinkModal, url]);\n\n if (!url) {\n return undefined;\n }\n\n const classNames = buildClassName(\n className || 'text-entity-link',\n text.length > 50 && 'long-word-break-all',\n );\n\n return (\n \n {content}\n \n );\n};\n\nfunction ensureProtocol(url?: string) {\n if (!url) {\n return undefined;\n }\n\n return url.includes('://') ? url : `https://${url}`;\n}\n\nfunction getDomain(url?: string) {\n if (!url) {\n return undefined;\n }\n\n const href = ensureProtocol(url);\n if (!href) {\n return undefined;\n }\n\n try {\n let decodedHref = decodeURI(href);\n\n const match = decodedHref.match(/^https?:\\/\\/([^/:?#]+)(?:[/:?#]|$)/i);\n if (!match) {\n return undefined;\n }\n const domain = match[1];\n decodedHref = decodedHref.replace(domain, convertPunycode(domain));\n\n return decodedHref;\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('SafeLink.getDecodedUrl error ', url, error);\n }\n }\n\n return undefined;\n}\n\nexport default memo(SafeLink);\n","import { ApiDocument } from '../../../api/types';\n\nconst ONE_GIGABYTE = 1024 * 1024 * 1024;\nconst ONE_MEGABYTE = 1024 * 1024;\n\nexport function getFileSizeString(bytes: number) {\n if (bytes > (ONE_GIGABYTE / 2)) {\n return `${(bytes / ONE_GIGABYTE).toFixed(1)} GB`;\n }\n if (bytes > (ONE_MEGABYTE / 2)) {\n return `${(bytes / ONE_MEGABYTE).toFixed(1)} MB`;\n }\n return `${(bytes / (1024)).toFixed(1)} KB`;\n}\n\nexport function getDocumentExtension(document: ApiDocument) {\n const { fileName, mimeType } = document;\n\n return getFileExtension(fileName, mimeType);\n}\n\nexport function getFileExtension(fileName: string, mimeType: string) {\n if (fileName && fileName.indexOf('.') !== -1) {\n return fileName.split('.').pop();\n } else {\n return mimeType.split('/').pop();\n }\n}\n\nexport function getColorFromExtension(extension: string) {\n switch (extension) {\n case 'apk':\n case 'xls':\n case 'xlsx':\n return 'green';\n case 'zip':\n case 'rar':\n case '7z':\n case 'tar':\n case 'gz':\n case 'ppt':\n case 'pptx':\n return 'orange';\n case 'pdf':\n case 'xps':\n return 'red';\n default:\n return 'default';\n }\n}\n\nexport function getDocumentHasPreview(document: ApiDocument) {\n return Boolean(document.previewBlobUrl || document.thumbnail);\n}\n","// @ts-ignore\nimport twemojiRegex from '../../../lib/twemojiRegex';\n\nconst DETECT_UP_TO = 3;\nconst MAX_LENGTH = DETECT_UP_TO * 8; // Maximum 8 per one emoji.\nconst RE_EMOJI_ONLY = new RegExp(`^(?:${twemojiRegex.source})+$`, '');\n\nexport default (text: string): number | false => {\n if (text.length > MAX_LENGTH) {\n return false;\n }\n\n const isEmojiOnly = Boolean(text.match(RE_EMOJI_ONLY));\n if (!isEmojiOnly) {\n return false;\n }\n\n let emojiCount = 0;\n while (twemojiRegex.exec(text)) {\n emojiCount++;\n\n if (emojiCount > DETECT_UP_TO) {\n twemojiRegex.lastIndex = 0;\n return false;\n }\n }\n\n return emojiCount;\n};\n","import React, { FC, useCallback } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiChat, ApiUser } from '../../api/types';\n\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\n\nimport Link from '../ui/Link';\n\ntype OwnProps = {\n className?: string;\n sender?: ApiUser | ApiChat;\n children: any;\n};\n\ntype DispatchProps = Pick;\n\nconst UserLink: FC = ({\n className, sender, openUserInfo, children,\n}) => {\n const handleClick = useCallback(() => {\n if (sender) {\n openUserInfo({ id: sender.id });\n }\n }, [sender, openUserInfo]);\n\n if (!sender) {\n return children;\n }\n\n return (\n {children}\n );\n};\n\nexport default withGlobal(\n undefined,\n (setGlobal, actions): DispatchProps => pick(actions, ['openUserInfo']),\n)(UserLink);\n","import React, { FC, useCallback } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\nimport { ApiMessage } from '../../api/types';\n\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\n\nimport Link from '../ui/Link';\n\ntype OwnProps = {\n className?: string;\n message?: ApiMessage;\n children: any;\n};\n\ntype DispatchProps = Pick;\n\nconst MessageLink: FC = ({\n className, message, children, focusMessage,\n}) => {\n const handleMessageClick = useCallback((): void => {\n if (message) {\n focusMessage({ chatId: message.chatId, messageId: message.id });\n }\n }, [focusMessage, message]);\n\n if (!message) {\n return children;\n }\n\n return (\n {children}\n );\n};\n\nexport default withGlobal(\n undefined,\n (setGlobal, actions): DispatchProps => pick(actions, ['focusMessage']),\n)(MessageLink);\n","import React, { FC, useCallback } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../global/types';\n\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\n\nimport Link from '../ui/Link';\n\ntype OwnProps = {\n className?: string;\n chatId?: string;\n children: any;\n};\n\ntype DispatchProps = Pick;\n\nconst ChatLink: FC = ({\n className, chatId, openChat, children,\n}) => {\n const handleClick = useCallback(() => {\n if (chatId) {\n openChat({ id: chatId });\n }\n }, [chatId, openChat]);\n\n if (!chatId) {\n return children;\n }\n\n return (\n {children}\n );\n};\n\nexport default withGlobal(\n undefined,\n (setGlobal, actions): DispatchProps => pick(actions, ['openChat']),\n)(ChatLink);\n","import React from '../../../lib/teact/teact';\n\nimport { ApiChat, ApiMessage, ApiUser } from '../../../api/types';\nimport { LangFn } from '../../../hooks/useLang';\nimport {\n getChatTitle,\n getMessageContent,\n getMessageSummaryText,\n getUserFullName,\n isUserId,\n} from '../../../modules/helpers';\nimport trimText from '../../../util/trimText';\nimport { formatCurrency } from '../../../util/formatCurrency';\nimport { TextPart } from './renderMessageText';\nimport renderText from './renderText';\n\nimport UserLink from '../UserLink';\nimport MessageLink from '../MessageLink';\nimport ChatLink from '../ChatLink';\n\ninterface ActionMessageTextOptions {\n maxTextLength?: number;\n asPlain?: boolean;\n isEmbedded?: boolean;\n}\n\nconst NBSP = '\\u00A0';\n\nexport function renderActionMessageText(\n lang: LangFn,\n message: ApiMessage,\n actionOrigin?: ApiUser | ApiChat,\n targetUsers?: ApiUser[],\n targetMessage?: ApiMessage,\n targetChatId?: string,\n options: ActionMessageTextOptions = {},\n) {\n if (!message.content.action) {\n return [];\n }\n const {\n text, translationValues, amount, currency,\n } = message.content.action;\n const content: TextPart[] = [];\n const textOptions: ActionMessageTextOptions = { ...options, maxTextLength: 32 };\n const translationKey = text === 'Chat.Service.Group.UpdatedPinnedMessage1' && !targetMessage\n ? 'Message.PinnedGenericMessage'\n : text;\n\n let unprocessed = lang(translationKey, translationValues && translationValues.length ? translationValues : undefined);\n let processed: TextPart[];\n\n if (unprocessed.includes('%payment_amount%')) {\n processed = processPlaceholder(\n unprocessed,\n '%payment_amount%',\n formatCurrency(amount!, currency, lang.code),\n );\n unprocessed = processed.pop() as string;\n content.push(...processed);\n }\n\n processed = processPlaceholder(\n unprocessed,\n '%action_origin%',\n actionOrigin\n ? (!options.isEmbedded && renderOriginContent(lang, actionOrigin, options.asPlain)) || NBSP\n : 'User',\n );\n\n unprocessed = processed.pop() as string;\n content.push(...processed);\n\n processed = processPlaceholder(\n unprocessed,\n '%target_user%',\n targetUsers\n ? targetUsers.map((user) => renderUserContent(user, options.asPlain)).filter(Boolean as any)\n : 'User',\n );\n\n unprocessed = processed.pop() as string;\n content.push(...processed);\n\n processed = processPlaceholder(\n unprocessed,\n '%message%',\n targetMessage\n ? renderMessageContent(lang, targetMessage, textOptions)\n : 'a message',\n );\n unprocessed = processed.pop() as string;\n content.push(...processed);\n\n processed = processPlaceholder(\n unprocessed,\n '%product%',\n targetMessage\n ? renderProductContent(targetMessage)\n : 'a product',\n );\n unprocessed = processed.pop() as string;\n content.push(...processed);\n\n processed = processPlaceholder(\n unprocessed,\n '%target_chat%',\n targetChatId\n ? renderMigratedContent(targetChatId, options.asPlain)\n : 'another chat',\n );\n content.push(...processed);\n\n if (options.asPlain) {\n return content.join('').trim();\n }\n\n return content;\n}\n\nfunction renderProductContent(message: ApiMessage) {\n return message.content && message.content.invoice\n ? message.content.invoice.title\n : 'a product';\n}\n\nfunction renderMessageContent(lang: LangFn, message: ApiMessage, options: ActionMessageTextOptions = {}) {\n const text = getMessageSummaryText(lang, message);\n const {\n photo, video, document, sticker,\n } = getMessageContent(message);\n\n const { maxTextLength, isEmbedded, asPlain } = options;\n\n const showQuotes = isEmbedded && text && !photo && !video && !document && !sticker;\n let messageText = trimText(text as string, maxTextLength)!;\n\n if (isEmbedded) {\n if (photo) {\n messageText = 'a photo';\n } else if (video) {\n messageText = video.isGif ? 'a GIF' : 'a video';\n } else if (document) {\n messageText = 'a document';\n } else if (sticker) {\n messageText = text;\n }\n }\n\n if (asPlain) {\n return showQuotes ? `«${messageText}»` : messageText;\n }\n\n if (showQuotes) {\n return (\n \n «\n {renderText(messageText)}\n »\n \n );\n }\n\n return (\n {renderText(messageText)}\n );\n}\n\nfunction renderOriginContent(lang: LangFn, origin: ApiUser | ApiChat, asPlain?: boolean) {\n return isUserId(origin.id)\n ? renderUserContent(origin as ApiUser, asPlain)\n : renderChatContent(lang, origin as ApiChat, asPlain);\n}\n\nfunction renderUserContent(sender: ApiUser, asPlain?: boolean): string | TextPart | undefined {\n const text = trimText(getUserFullName(sender));\n\n if (asPlain) {\n return text;\n }\n\n return {sender && renderText(text!)};\n}\n\nfunction renderChatContent(lang: LangFn, chat: ApiChat, asPlain?: boolean): string | TextPart | undefined {\n const text = trimText(getChatTitle(lang, chat));\n\n if (asPlain) {\n return text;\n }\n\n return {chat && renderText(text!)};\n}\n\nfunction renderMigratedContent(chatId: string, asPlain?: boolean): string | TextPart | undefined {\n const text = 'another chat';\n\n if (asPlain) {\n return text;\n }\n\n return {text};\n}\n\nfunction processPlaceholder(text: string, placeholder: string, replaceValue?: TextPart | TextPart[]): TextPart[] {\n const placeholderPosition = text.indexOf(placeholder);\n if (placeholderPosition < 0 || !replaceValue) {\n return [text];\n }\n\n const content: TextPart[] = [];\n content.push(text.substring(0, placeholderPosition));\n if (Array.isArray(replaceValue)) {\n replaceValue.forEach((value, index) => {\n content.push(value);\n if (index + 1 < replaceValue.length) {\n content.push(', ');\n }\n });\n } else {\n content.push(replaceValue);\n }\n content.push(text.substring(placeholderPosition + placeholder.length));\n\n return content;\n}\n","import React from '../../../lib/teact/teact';\nimport EMOJI_REGEX, { removeVS16s } from '../../../lib/twemojiRegex';\n\nimport { RE_LINK_TEMPLATE, RE_MENTION_TEMPLATE } from '../../../config';\nimport { IS_EMOJI_SUPPORTED } from '../../../util/environment';\nimport { fixNonStandardEmoji, nativeToUnified } from '../../../util/emoji';\nimport buildClassName from '../../../util/buildClassName';\n\nimport MentionLink from '../../middle/message/MentionLink';\nimport SafeLink from '../SafeLink';\n\ntype TextPart = string | Element;\n\nconst RE_LETTER_OR_DIGIT = /^[\\d\\wа-яё]$/i;\nconst SIMPLE_MARKDOWN_REGEX = /(\\*\\*|__).+?\\1/g;\n\nexport default function renderText(\n part: TextPart,\n filters: Array<(\n 'escape_html' | 'hq_emoji' | 'emoji' | 'emoji_html' | 'br' | 'br_html' | 'highlight' | 'links' |\n 'simple_markdown' | 'simple_markdown_html'\n )> = ['emoji'],\n params?: { highlight: string | undefined },\n): TextPart[] {\n if (typeof part !== 'string') {\n return [part];\n }\n\n return filters.reduce((text, filter) => {\n switch (filter) {\n case 'escape_html':\n return escapeHtml(text);\n\n case 'hq_emoji':\n EMOJI_REGEX.lastIndex = 0;\n return replaceEmojis(text, 'big', 'jsx');\n\n case 'emoji':\n EMOJI_REGEX.lastIndex = 0;\n return replaceEmojis(text, 'small', 'jsx');\n\n case 'emoji_html':\n EMOJI_REGEX.lastIndex = 0;\n return replaceEmojis(text, 'small', 'html');\n\n case 'br':\n return addLineBreaks(text, 'jsx');\n\n case 'br_html':\n return addLineBreaks(text, 'html');\n\n case 'highlight':\n return addHighlight(text, params!.highlight);\n\n case 'links':\n return addLinks(text);\n\n case 'simple_markdown':\n return replaceSimpleMarkdown(text, 'jsx');\n\n case 'simple_markdown_html':\n return replaceSimpleMarkdown(text, 'html');\n }\n\n return text;\n }, [part] as TextPart[]);\n}\n\nfunction escapeHtml(textParts: TextPart[]): TextPart[] {\n const divEl = document.createElement('div');\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n divEl.innerText = part;\n\n return [...result, divEl.innerHTML];\n }, [] as TextPart[]);\n}\n\nfunction replaceEmojis(textParts: TextPart[], size: 'big' | 'small', type: 'jsx' | 'html'): TextPart[] {\n if (IS_EMOJI_SUPPORTED) {\n return textParts;\n }\n\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n part = fixNonStandardEmoji(part);\n const parts = part.split(EMOJI_REGEX);\n const emojis = part.match(EMOJI_REGEX) || [];\n result.push(parts[0]);\n\n return emojis.reduce((emojiResult: TextPart[], emoji, i) => {\n const code = nativeToUnified(removeVS16s(emoji));\n if (!code) return emojiResult;\n const className = buildClassName(\n 'emoji',\n size === 'small' && 'emoji-small',\n );\n if (type === 'jsx') {\n emojiResult.push(\n ,\n );\n }\n if (type === 'html') {\n emojiResult.push(\n // For preventing extra spaces in html\n // eslint-disable-next-line max-len\n `\"${emoji}\"`,\n );\n }\n\n const index = i * 2 + 2;\n if (parts[index]) {\n emojiResult.push(parts[index]);\n }\n\n return emojiResult;\n }, result);\n }, [] as TextPart[]);\n}\n\nfunction addLineBreaks(textParts: TextPart[], type: 'jsx' | 'html'): TextPart[] {\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n return [...result, ...part\n .split(/\\r\\n|\\r|\\n/g)\n .reduce((parts: TextPart[], line: string, i, source) => {\n // This adds non-breaking space if line was indented with spaces, to preserve the indentation\n const trimmedLine = line.trimLeft();\n const indentLength = line.length - trimmedLine.length;\n parts.push(String.fromCharCode(160).repeat(indentLength) + trimmedLine);\n\n if (i !== source.length - 1) {\n parts.push(\n type === 'jsx' ?
: '
',\n );\n }\n\n return parts;\n }, [])];\n }, [] as TextPart[]);\n}\n\nfunction addHighlight(textParts: TextPart[], highlight: string | undefined): TextPart[] {\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string' || !highlight) {\n return [...result, part];\n }\n\n const lowerCaseText = part.toLowerCase();\n const queryPosition = lowerCaseText.indexOf(highlight.toLowerCase());\n const nextSymbol = lowerCaseText[queryPosition + highlight.length];\n if (queryPosition < 0 || (nextSymbol && nextSymbol.match(RE_LETTER_OR_DIGIT))) {\n return [...result, part];\n }\n\n const newParts: TextPart[] = [];\n newParts.push(part.substring(0, queryPosition));\n newParts.push(\n \n {part.substring(queryPosition, queryPosition + highlight.length)}\n ,\n );\n newParts.push(part.substring(queryPosition + highlight.length));\n\n return [...result, ...newParts];\n }, [] as TextPart[]);\n}\n\nconst RE_LINK = new RegExp(`${RE_LINK_TEMPLATE}|${RE_MENTION_TEMPLATE}`, 'ig');\n\nfunction addLinks(textParts: TextPart[]): TextPart[] {\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n const links = part.match(RE_LINK);\n if (!links || !links.length) {\n return [...result, part];\n }\n\n const content: TextPart[] = [];\n\n let nextLink = links.shift();\n let lastIndex = 0;\n while (nextLink) {\n const index = part.indexOf(nextLink, lastIndex);\n content.push(part.substring(lastIndex, index));\n if (nextLink.startsWith('@')) {\n content.push(\n \n {nextLink}\n ,\n );\n } else {\n if (nextLink.endsWith('?')) {\n nextLink = nextLink.slice(0, nextLink.length - 1);\n }\n\n content.push(\n ,\n );\n }\n lastIndex = index + nextLink.length;\n nextLink = links.shift();\n }\n content.push(part.substring(lastIndex));\n\n return [...result, ...content];\n }, [] as TextPart[]);\n}\n\nfunction replaceSimpleMarkdown(textParts: TextPart[], type: 'jsx' | 'html'): TextPart[] {\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string') {\n return [...result, part];\n }\n\n const parts = part.split(SIMPLE_MARKDOWN_REGEX);\n const entities = part.match(SIMPLE_MARKDOWN_REGEX) || [];\n result.push(parts[0]);\n\n return entities.reduce((entityResult: TextPart[], entity, i) => {\n if (type === 'jsx') {\n entityResult.push(\n entity.startsWith('**')\n ? {entity.replace(/\\*\\*/g, '')}\n : {entity.replace(/__/g, '')},\n );\n } else {\n entityResult.push(\n entity.startsWith('**')\n ? `${entity.replace(/\\*\\*/g, '')}`\n : `${entity.replace(/__/g, '')}`,\n );\n }\n\n const index = i * 2 + 2;\n if (parts[index]) {\n entityResult.push(parts[index]);\n }\n\n return entityResult;\n }, result);\n }, [] as TextPart[]);\n}\n","import React from '../../../lib/teact/teact';\n\nimport { EDITABLE_INPUT_ID } from '../../../config';\nimport { IS_IOS } from '../../../util/environment';\n\nexport function preventMessageInputBlur(e: React.MouseEvent, withBubbling = false) {\n if (\n IS_IOS\n || !document.activeElement\n || document.activeElement.id !== EDITABLE_INPUT_ID\n || (!withBubbling && e.target !== e.currentTarget)\n ) {\n return;\n }\n\n e.preventDefault();\n}\n\nexport function preventMessageInputBlurWithBubbling(e: React.MouseEvent) {\n preventMessageInputBlur(e, true);\n}\n","import React, { FC } from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport { ApiChat, ApiUser } from '../../../api/types';\n\nimport { pick } from '../../../util/iteratees';\nimport { selectUser } from '../../../modules/selectors';\n\ntype OwnProps = {\n userId?: string;\n username?: string;\n children: any;\n};\n\ntype StateProps = {\n userOrChat?: ApiUser | ApiChat;\n};\n\ntype DispatchProps = Pick;\n\nconst MentionLink: FC = ({\n username,\n userOrChat,\n children,\n openChat,\n openChatByUsername,\n}) => {\n const handleClick = () => {\n if (userOrChat) {\n openChat({ id: userOrChat.id });\n } else if (username) {\n openChatByUsername({ username: username.substring(1) });\n }\n };\n\n return (\n \n {children}\n \n );\n};\n\nexport default withGlobal(\n (global, { userId }): StateProps => {\n return {\n userOrChat: userId ? selectUser(global, userId) : undefined,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['openChat', 'openChatByUsername']),\n)(MentionLink);\n","import { MouseEvent as ReactMouseEvent, RefObject } from 'react';\n\nimport React, {\n FC, useRef, useCallback, useState,\n} from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport Spinner from './Spinner';\nimport RippleEffect from './RippleEffect';\n\nimport './Button.scss';\n\nexport type OwnProps = {\n ref?: RefObject;\n type?: 'button' | 'submit' | 'reset';\n children: any;\n size?: 'default' | 'smaller' | 'tiny';\n color?: 'primary' | 'secondary' | 'gray' | 'danger' | 'translucent' | 'translucent-white' | 'dark';\n backgroundImage?: string;\n className?: string;\n round?: boolean;\n pill?: boolean;\n fluid?: boolean;\n isText?: boolean;\n isLoading?: boolean;\n ariaLabel?: string;\n href?: string;\n download?: string;\n disabled?: boolean;\n ripple?: boolean;\n faded?: boolean;\n tabIndex?: number;\n isRtl?: boolean;\n withClickPropagation?: boolean;\n onClick?: (e: ReactMouseEvent) => void;\n onContextMenu?: (e: ReactMouseEvent) => void;\n onMouseDown?: (e: ReactMouseEvent) => void;\n onMouseEnter?: NoneToVoidFunction;\n onMouseLeave?: NoneToVoidFunction;\n onFocus?: NoneToVoidFunction;\n};\n\n// Longest animation duration;\nconst CLICKED_TIMEOUT = 400;\n\nconst Button: FC = ({\n ref,\n type = 'button',\n onClick,\n onContextMenu,\n onMouseDown,\n onMouseEnter,\n onMouseLeave,\n onFocus,\n children,\n size = 'default',\n color = 'primary',\n backgroundImage,\n className,\n round,\n pill,\n fluid,\n isText,\n isLoading,\n ariaLabel,\n href,\n download,\n disabled,\n ripple,\n faded,\n tabIndex,\n isRtl,\n withClickPropagation,\n}) => {\n // eslint-disable-next-line no-null/no-null\n let elementRef = useRef(null);\n if (ref) {\n elementRef = ref;\n }\n\n const [isClicked, setIsClicked] = useState(false);\n\n const fullClassName = buildClassName(\n 'Button',\n className,\n size,\n color,\n round && 'round',\n pill && 'pill',\n fluid && 'fluid',\n disabled && 'disabled',\n isText && 'text',\n isLoading && 'loading',\n ripple && 'has-ripple',\n faded && 'faded',\n isClicked && 'clicked',\n backgroundImage && 'with-image',\n );\n\n const handleClick = useCallback((e: ReactMouseEvent) => {\n if (!disabled && onClick) {\n onClick(e);\n }\n\n setIsClicked(true);\n setTimeout(() => {\n setIsClicked(false);\n }, CLICKED_TIMEOUT);\n }, [disabled, onClick]);\n\n const handleMouseDown = useCallback((e: ReactMouseEvent) => {\n if (!withClickPropagation) e.preventDefault();\n if (!disabled && onMouseDown) {\n onMouseDown(e);\n }\n }, [onMouseDown, disabled, withClickPropagation]);\n\n if (href) {\n return (\n }\n className={fullClassName}\n href={href}\n title={ariaLabel}\n download={download}\n tabIndex={tabIndex}\n dir={isRtl ? 'rtl' : undefined}\n >\n {children}\n {!disabled && ripple && (\n \n )}\n \n );\n }\n\n return (\n // eslint-disable-next-line react/button-has-type\n }\n type={type}\n className={fullClassName}\n onClick={handleClick}\n onContextMenu={onContextMenu}\n onMouseDown={handleMouseDown}\n onMouseEnter={onMouseEnter && !disabled ? onMouseEnter : undefined}\n onMouseLeave={onMouseLeave && !disabled ? onMouseLeave : undefined}\n onFocus={onFocus && !disabled ? onFocus : undefined}\n aria-label={ariaLabel}\n title={ariaLabel}\n tabIndex={tabIndex}\n dir={isRtl ? 'rtl' : undefined}\n // @ts-ignore\n style={backgroundImage ? `background-image: url(${backgroundImage})` : undefined}\n >\n {isLoading ? (\n
\n Please wait...\n \n
\n ) : children }\n {!disabled && ripple && (\n \n )}\n \n );\n};\n\nexport default Button;\n","import { ChangeEvent } from 'react';\nimport React, { FC, memo, useCallback } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\nimport renderText from '../common/helpers/renderText';\n\nimport Spinner from './Spinner';\n\nimport './Checkbox.scss';\n\ntype OwnProps = {\n id?: string;\n name?: string;\n value?: string;\n label: string;\n subLabel?: string;\n checked: boolean;\n disabled?: boolean;\n round?: boolean;\n blocking?: boolean;\n isLoading?: boolean;\n withCheckedCallback?: boolean;\n onChange?: (e: ChangeEvent) => void;\n onCheck?: (isChecked: boolean) => void;\n};\n\nconst Checkbox: FC = ({\n id,\n name,\n value,\n label,\n subLabel,\n checked,\n disabled,\n round,\n blocking,\n isLoading,\n onChange,\n onCheck,\n}) => {\n const lang = useLang();\n const handleChange = useCallback((event: ChangeEvent) => {\n if (onChange) {\n onChange(event);\n }\n\n if (onCheck) {\n onCheck(event.currentTarget.checked);\n }\n }, [onChange, onCheck]);\n\n const className = buildClassName(\n 'Checkbox',\n disabled && 'disabled',\n round && 'round',\n isLoading && 'loading',\n blocking && 'blocking',\n );\n\n return (\n \n );\n};\n\nexport default memo(Checkbox);\n","import React, { FC, useState, useRef } from '../../lib/teact/teact';\n\nimport Menu from './Menu';\n\nimport './DropdownMenu.scss';\n\ntype OwnProps = {\n className?: string;\n trigger: FC<{ onTrigger: () => void; isOpen?: boolean }>;\n positionX?: 'left' | 'right';\n positionY?: 'top' | 'bottom';\n footer?: string;\n forceOpen?: boolean;\n onOpen?: NoneToVoidFunction;\n onClose?: NoneToVoidFunction;\n children: any;\n};\n\nconst DropdownMenu: FC = ({\n trigger,\n className,\n children,\n positionX = 'left',\n positionY = 'top',\n footer,\n forceOpen,\n onOpen,\n onClose,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const menuRef = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const dropdownRef = useRef(null);\n const [isOpen, setIsOpen] = useState(false);\n\n const toggleIsOpen = () => {\n setIsOpen(!isOpen);\n if (isOpen) {\n if (onClose) onClose();\n } else if (onOpen) onOpen();\n };\n\n const handleKeyDown = (e: React.KeyboardEvent) => {\n const menu = menuRef.current;\n\n if (!isOpen || e.keyCode !== 40 || !menu) {\n return;\n }\n\n const focusedElement = document.activeElement;\n const elementChildren = Array.from(menu.children);\n\n if (!focusedElement || elementChildren.indexOf(focusedElement) === -1) {\n (elementChildren[0] as HTMLElement).focus();\n }\n };\n\n const handleClose = () => {\n setIsOpen(false);\n if (onClose) onClose();\n };\n\n return (\n \n {trigger({ onTrigger: toggleIsOpen, isOpen })}\n\n \n {children}\n \n
\n );\n};\n\nexport default DropdownMenu;\n","import { ChangeEvent, FormEvent, RefObject } from 'react';\nimport React, { FC, memo } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\ntype OwnProps = {\n ref?: RefObject;\n id?: string;\n className?: string;\n value?: string;\n label?: string;\n error?: string;\n success?: string;\n disabled?: boolean;\n readOnly?: boolean;\n placeholder?: string;\n autoComplete?: string;\n maxLength?: number;\n inputMode?: 'text' | 'none' | 'tel' | 'url' | 'email' | 'numeric' | 'decimal' | 'search';\n onChange?: (e: ChangeEvent) => void;\n onInput?: (e: FormEvent) => void;\n onKeyPress?: (e: React.KeyboardEvent) => void;\n onKeyDown?: (e: React.KeyboardEvent) => void;\n onBlur?: (e: React.FocusEvent) => void;\n onPaste?: (e: React.ClipboardEvent) => void;\n};\n\nconst InputText: FC = ({\n ref,\n id,\n className,\n value,\n label,\n error,\n success,\n disabled,\n readOnly,\n placeholder,\n autoComplete,\n inputMode,\n maxLength,\n onChange,\n onInput,\n onKeyPress,\n onKeyDown,\n onBlur,\n onPaste,\n}) => {\n const lang = useLang();\n const labelText = error || success || label;\n const fullClassName = buildClassName(\n 'input-group',\n value && 'touched',\n error ? 'error' : success && 'success',\n disabled && 'disabled',\n readOnly && 'disabled',\n labelText && 'with-label',\n className,\n );\n\n return (\n
\n \n {labelText && (\n \n )}\n
\n );\n};\n\nexport default memo(InputText);\n","import React, { FC, useCallback } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport './Link.scss';\n\ntype OwnProps = {\n children: any;\n className?: string;\n isRtl?: boolean;\n onClick?: (e: React.MouseEvent) => void;\n};\n\nconst Link: FC = ({\n children, className, isRtl, onClick,\n}) => {\n const handleClick = useCallback((e: React.MouseEvent) => {\n e.preventDefault();\n onClick!(e);\n }, [onClick]);\n\n return (\n \n {children}\n \n );\n};\n\nexport default Link;\n","import React, { FC, memo } from '../../lib/teact/teact';\n\nimport Spinner from './Spinner';\n\nimport './Loading.scss';\n\ntype OwnProps = {\n color?: 'blue' | 'white' | 'black';\n};\n\nconst Loading: FC = ({ color = 'blue' }) => {\n return (\n
\n \n
\n );\n};\n\nexport default memo(Loading);\n","import { RefObject } from 'react';\nimport React, { FC, useEffect, useRef } from '../../lib/teact/teact';\n\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useKeyboardListNavigation from '../../hooks/useKeyboardListNavigation';\nimport useVirtualBackdrop from '../../hooks/useVirtualBackdrop';\nimport useEffectWithPrevDeps from '../../hooks/useEffectWithPrevDeps';\nimport captureEscKeyListener from '../../util/captureEscKeyListener';\nimport buildClassName from '../../util/buildClassName';\nimport { dispatchHeavyAnimationEvent } from '../../hooks/useHeavyAnimationCheck';\nimport useHistoryBack from '../../hooks/useHistoryBack';\nimport { preventMessageInputBlurWithBubbling } from '../middle/helpers/preventMessageInputBlur';\n\nimport './Menu.scss';\n\ntype OwnProps = {\n ref?: RefObject;\n containerRef?: RefObject;\n isOpen: boolean;\n className?: string;\n style?: string;\n menuStyle?: string;\n positionX?: 'left' | 'right';\n positionY?: 'top' | 'bottom';\n autoClose?: boolean;\n shouldSkipTransition?: boolean;\n footer?: string;\n noCloseOnBackdrop?: boolean;\n onKeyDown?: (e: React.KeyboardEvent) => void;\n onCloseAnimationEnd?: () => void;\n onClose?: () => void;\n onMouseEnter?: (e: React.MouseEvent) => void;\n onMouseLeave?: (e: React.MouseEvent) => void;\n children: any;\n};\n\nconst ANIMATION_DURATION = 200;\n\nconst Menu: FC = ({\n ref,\n containerRef,\n isOpen,\n className,\n style,\n menuStyle,\n children,\n positionX = 'left',\n positionY = 'top',\n autoClose = false,\n footer,\n noCloseOnBackdrop = false,\n onCloseAnimationEnd,\n onClose,\n onMouseEnter,\n onMouseLeave,\n shouldSkipTransition,\n}) => {\n // eslint-disable-next-line no-null/no-null\n let menuRef = useRef(null);\n if (ref) {\n menuRef = ref;\n }\n const backdropContainerRef = containerRef || menuRef;\n\n const {\n transitionClassNames,\n } = useShowTransition(\n isOpen,\n onCloseAnimationEnd,\n shouldSkipTransition,\n undefined,\n shouldSkipTransition,\n );\n\n useEffect(\n () => (isOpen && onClose ? captureEscKeyListener(onClose) : undefined),\n [isOpen, onClose],\n );\n\n useHistoryBack(isOpen, onClose, undefined, undefined, autoClose);\n\n useEffectWithPrevDeps(([prevIsOpen]) => {\n if (prevIsOpen !== undefined) {\n dispatchHeavyAnimationEvent(ANIMATION_DURATION);\n }\n }, [isOpen]);\n\n const handleKeyDown = useKeyboardListNavigation(menuRef, isOpen, autoClose ? onClose : undefined, undefined, true);\n\n useVirtualBackdrop(\n isOpen,\n backdropContainerRef,\n noCloseOnBackdrop ? undefined : onClose,\n );\n\n const bubbleClassName = buildClassName(\n 'bubble menu-container custom-scroll',\n positionY,\n positionX,\n footer && 'with-footer',\n transitionClassNames,\n );\n\n return (\n \n {isOpen && (\n // This only prevents click events triggering on underlying elements\n
\n )}\n \n {children}\n {footer &&
{footer}
}\n
\n
\n );\n};\n\nexport default Menu;\n","import React, { FC, useCallback } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\nimport './MenuItem.scss';\n\ntype OnClickHandler = (e: React.SyntheticEvent) => void;\n\ntype OwnProps = {\n icon?: string;\n className?: string;\n children: any;\n onClick?: OnClickHandler;\n href?: string;\n download?: string;\n disabled?: boolean;\n destructive?: boolean;\n ariaLabel?: string;\n};\n\nconst MenuItem: FC = (props) => {\n const {\n icon,\n className,\n children,\n onClick,\n href,\n download,\n disabled,\n destructive,\n ariaLabel,\n } = props;\n\n const lang = useLang();\n const handleClick = useCallback((e: React.MouseEvent) => {\n if (disabled || !onClick) {\n e.stopPropagation();\n e.preventDefault();\n\n return;\n }\n\n onClick(e);\n }, [disabled, onClick]);\n\n const handleKeyDown = useCallback((e: React.KeyboardEvent) => {\n if (e.keyCode !== 13 && e.keyCode !== 32) {\n return;\n }\n\n if (disabled || !onClick) {\n e.stopPropagation();\n e.preventDefault();\n\n return;\n }\n\n onClick(e);\n }, [disabled, onClick]);\n\n const fullClassName = buildClassName(\n 'MenuItem',\n className,\n disabled && 'disabled',\n destructive && 'destructive',\n );\n\n const content = (\n <>\n {icon && (\n \n )}\n {children}\n \n );\n\n if (href) {\n return (\n \n {content}\n \n );\n }\n\n return (\n \n {content}\n
\n );\n};\n\nexport default MenuItem;\n","import React, {\n FC, useCallback, useMemo, useState, memo,\n} from '../../lib/teact/teact';\nimport { debounce } from '../../util/schedulers';\n\nimport './RippleEffect.scss';\n\ninterface Ripple {\n x: number;\n y: number;\n size: number;\n}\n\nconst ANIMATION_DURATION_MS = 700;\n\nconst RippleEffect: FC = () => {\n const [ripples, setRipples] = useState([]);\n\n const cleanUpDebounced = useMemo(() => {\n return debounce(() => {\n setRipples([]);\n }, ANIMATION_DURATION_MS, false);\n }, []);\n\n const handleMouseDown = useCallback((e: React.MouseEvent) => {\n if (e.button !== 0) {\n return;\n }\n\n const container = e.currentTarget as HTMLDivElement;\n const position = container.getBoundingClientRect() as DOMRect;\n\n const rippleSize = container.offsetWidth / 2;\n\n setRipples([\n ...ripples,\n {\n x: e.clientX - position.x - (rippleSize / 2),\n y: e.clientY - position.y - (rippleSize / 2),\n size: rippleSize,\n },\n ]);\n\n requestAnimationFrame(() => {\n cleanUpDebounced();\n });\n }, [ripples, cleanUpDebounced]);\n\n return (\n
\n {ripples.map(({ x, y, size }) => (\n \n ))}\n
\n );\n};\n\nexport default memo(RippleEffect);\n","import React, { FC } from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport './Spinner.scss';\n\nconst Spinner: FC<{\n color?: 'blue' | 'white' | 'black' | 'green' | 'gray';\n withBackground?: boolean;\n}> = ({\n color = 'blue',\n withBackground,\n}) => {\n return (\n
\n
\n
\n );\n};\n\nexport default Spinner;\n","export const PAGE_TITLE = 'Telegram';\nexport const INACTIVE_MARKER = ' [Inactive]';\n\nexport const APP_NAME = process.env.APP_NAME || 'Telegram WebZ';\nexport const APP_VERSION = process.env.APP_VERSION || 'dev';\n\nexport const DEBUG = (\n process.env.APP_ENV !== 'production' && process.env.APP_ENV !== 'perf' && process.env.APP_ENV !== 'test'\n);\nexport const DEBUG_MORE = false;\n\nexport const IS_TEST = process.env.APP_ENV === 'test';\nexport const IS_PERF = process.env.APP_ENV === 'perf';\n\nexport const DEBUG_ALERT_MSG = 'Shoot!\\nSomething went wrong, please see the error details in Dev Tools Console.';\nexport const DEBUG_GRAMJS = false;\n\nexport const SESSION_USER_KEY = 'user_auth';\nexport const LEGACY_SESSION_KEY = 'GramJs:sessionId';\n\nexport const GLOBAL_STATE_CACHE_DISABLED = false;\nexport const GLOBAL_STATE_CACHE_KEY = 'tt-global-state';\nexport const GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT = 30;\nexport const GLOBAL_STATE_CACHE_USER_LIST_LIMIT = 5000;\n\nexport const MEDIA_CACHE_DISABLED = false;\nexport const MEDIA_CACHE_NAME = 'tt-media';\nexport const MEDIA_CACHE_NAME_AVATARS = 'tt-media-avatars';\nexport const MEDIA_PROGRESSIVE_CACHE_DISABLED = false;\nexport const MEDIA_PROGRESSIVE_CACHE_NAME = 'tt-media-progressive';\nexport const MEDIA_CACHE_MAX_BYTES = 512 * 1024; // 512 KB\nexport const CUSTOM_BG_CACHE_NAME = 'tt-custom-bg';\nexport const LANG_CACHE_NAME = 'tt-lang-packs-v6';\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_SENSITIVE_AREA = 750;\nexport const MESSAGE_LIST_SLICE = isBigScreen ? 60 : 40;\nexport const MESSAGE_LIST_VIEWPORT_LIMIT = MESSAGE_LIST_SLICE * 2;\n\nexport const CHAT_HEIGHT_PX = 72;\nexport const CHAT_LIST_SLICE = isBigScreen ? 30 : 25;\nexport const CHAT_LIST_LOAD_SLICE = 100;\nexport const SHARED_MEDIA_SLICE = 42;\nexport const MESSAGE_SEARCH_SLICE = 42;\nexport const GLOBAL_SEARCH_SLICE = 20;\nexport const MEMBERS_SLICE = 30;\nexport const MEMBERS_LOAD_SLICE = 200;\nexport const PINNED_MESSAGES_LIMIT = 50;\nexport const BLOCKED_LIST_LIMIT = 100;\nexport const PROFILE_PHOTOS_LIMIT = 40;\nexport const PROFILE_SENSITIVE_AREA = 500;\nexport const COMMON_CHATS_LIMIT = 100;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 20;\nexport const ALL_CHATS_PRELOAD_DISABLED = false;\n\nexport const DEFAULT_VOLUME = 1;\nexport const DEFAULT_PLAYBACK_RATE = 1;\n\nexport const ANIMATION_LEVEL_MIN = 0;\nexport const ANIMATION_LEVEL_MED = 1;\nexport const ANIMATION_LEVEL_MAX = 2;\nexport const ANIMATION_LEVEL_DEFAULT = ANIMATION_LEVEL_MAX;\n\nexport const DEFAULT_MESSAGE_TEXT_SIZE_PX = 16;\nexport const IOS_DEFAULT_MESSAGE_TEXT_SIZE_PX = 17;\nexport const MACOS_DEFAULT_MESSAGE_TEXT_SIZE_PX = 15;\n\nexport const DRAFT_DEBOUNCE = 10000; // 10s\n\nexport const EDITABLE_INPUT_ID = 'editable-message-text';\nexport const EDITABLE_INPUT_MODAL_ID = 'editable-message-text-modal';\n\n// Screen width where Pinned Message / Audio Player in the Middle Header can be safely displayed\nexport const SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1440; // px\n// Screen width where Pinned Message / Audio Player in the Middle Header shouldn't collapse with ChatInfo\nexport const SAFE_SCREEN_WIDTH_FOR_CHAT_INFO = 1150; // px\n\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1275; // px\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN = 925; // px\nexport const MOBILE_SCREEN_MAX_WIDTH = 600; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH = 950; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT = 450; // px\n\nexport const LOCAL_MESSAGE_ID_BASE = 1e9;\nexport const TMP_CHAT_ID = '0';\n\nexport const ANIMATION_END_DELAY = 100;\n\nexport const FAST_SMOOTH_MAX_DISTANCE = 1500;\nexport const FAST_SMOOTH_MIN_DURATION = 250;\nexport const FAST_SMOOTH_MAX_DURATION = 600;\nexport const FAST_SMOOTH_SHORT_TRANSITION_MAX_DISTANCE = 500; // px\n\n// Average duration of message sending animation\nexport const API_UPDATE_THROTTLE = Math.round((FAST_SMOOTH_MIN_DURATION + FAST_SMOOTH_MAX_DURATION) / 2);\nexport const API_THROTTLE_RESET_UPDATES = new Set([\n 'newMessage', 'newScheduledMessage', 'deleteMessages', 'deleteScheduledMessages', 'deleteHistory',\n]);\n\nexport const STICKER_SIZE_INLINE_DESKTOP_FACTOR = 13;\nexport const STICKER_SIZE_INLINE_MOBILE_FACTOR = 11;\nexport const STICKER_SIZE_AUTH = 160;\nexport const STICKER_SIZE_AUTH_MOBILE = 120;\nexport const STICKER_SIZE_PICKER = 64;\nexport const STICKER_SIZE_GENERAL_SETTINGS = 48;\nexport const STICKER_SIZE_PICKER_HEADER = 32;\nexport const STICKER_SIZE_SEARCH = 64;\nexport const STICKER_SIZE_MODAL = 64;\nexport const STICKER_SIZE_TWO_FA = 160;\nexport const STICKER_SIZE_DISCUSSION_GROUPS = 140;\nexport const STICKER_SIZE_FOLDER_SETTINGS = 80;\nexport const STICKER_SIZE_INLINE_BOT_RESULT = 100;\nexport const RECENT_STICKERS_LIMIT = 20;\nexport const MEMOJI_STICKER_ID = 'MEMOJI_STICKER';\n\nexport const BASE_EMOJI_KEYWORD_LANG = 'en';\n\nexport const MENU_TRANSITION_DURATION = 200;\nexport const SLIDE_TRANSITION_DURATION = 450;\n\nexport const VIDEO_MOV_TYPE = 'video/quicktime';\n\nexport const SUPPORTED_IMAGE_CONTENT_TYPES = new Set([\n 'image/png', 'image/gif', 'image/jpeg',\n]);\n\nexport const SUPPORTED_VIDEO_CONTENT_TYPES = new Set([\n 'video/mp4', // video/quicktime added dynamically in environment.ts\n]);\n\nexport const CONTENT_TYPES_WITH_PREVIEW = new Set([\n ...SUPPORTED_IMAGE_CONTENT_TYPES,\n ...SUPPORTED_VIDEO_CONTENT_TYPES,\n]);\n\n// eslint-disable-next-line max-len\nexport const RE_LINK_TEMPLATE = '((ftp|https?):\\\\/\\\\/)?((www\\\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\\\.[a-zA-Z0-9()]{1,63})\\\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)';\nexport const RE_MENTION_TEMPLATE = '(@[\\\\w\\\\d_-]+)';\nexport const RE_TG_LINK = /^tg:(\\/\\/)?([?=&\\d\\w_-]+)?/gm;\nexport const RE_TME_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/)/gm;\n\n// eslint-disable-next-line max-len\nexport const COUNTRIES_WITH_12H_TIME_FORMAT = new Set(['AU', 'BD', 'CA', 'CO', 'EG', 'HN', 'IE', 'IN', 'JO', 'MX', 'MY', 'NI', 'NZ', 'PH', 'PK', 'SA', 'SV', 'US']);\n\n// MTProto constants\nexport const SERVICE_NOTIFICATIONS_USER_ID = '777000';\nexport const REPLIES_USER_ID = '1271266957'; // TODO For Test connection ID must be equal to 708513\nexport const ALL_FOLDER_ID = 0;\nexport const ARCHIVED_FOLDER_ID = 1;\nexport const DELETED_COMMENTS_CHANNEL_ID = '-777';\nexport const MAX_MEDIA_FILES_FOR_ALBUM = 10;\nexport const MAX_ACTIVE_PINNED_CHATS = 5;\nexport const SCHEDULED_WHEN_ONLINE = 0x7FFFFFFE;\nexport const DEFAULT_LANG_CODE = 'en';\nexport const DEFAULT_LANG_PACK = 'android';\nexport const LANG_PACKS = ['android', 'ios', 'tdesktop', 'macos'] as const;\nexport const TIPS_USERNAME = 'TelegramTips';\nexport const LOCALIZED_TIPS = ['ar', 'pt-br', 'id', 'it', 'ko', 'ms', 'pl', 'es', 'tr'];\nexport const FEEDBACK_URL = 'https://bugs.telegram.org/?tag_ids=41&sort=time';\nexport const LIGHT_THEME_BG_COLOR = '#A2AF8E';\nexport const DARK_THEME_BG_COLOR = '#0F0F0F';\nexport const DARK_THEME_PATTERN_COLOR = '#0a0a0a8c';\nexport const DEFAULT_PATTERN_COLOR = 'rgba(90, 110, 70, 0.6)';\n","import { useEffect } from '../lib/teact/teact';\nimport usePrevious from './usePrevious';\n\nexport default (cb: (args: PT) => void, dependencies: T, debugKey?: string) => {\n const prevDeps = usePrevious(dependencies);\n return useEffect(() => {\n // @ts-ignore (workaround for \"could be instantiated with a different subtype\" issue)\n return cb(prevDeps || []);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, dependencies, debugKey);\n};\n","import { useCallback, useState } from '../lib/teact/teact';\n\nexport default (initial = false): [boolean, AnyToVoidFunction, AnyToVoidFunction] => {\n const [value, setValue] = useState(initial);\n\n const setTrue = useCallback(() => {\n setValue(true);\n }, []);\n\n const setFalse = useCallback(() => {\n setValue(false);\n }, []);\n\n return [value, setTrue, setFalse];\n};\n","import { useCallback, useState } from '../lib/teact/teact';\n\nexport default () => {\n const [, setTrigger] = useState(false);\n\n return useCallback(() => {\n setTrigger((trigger) => !trigger);\n }, []);\n};\n","import { useEffect } from '../lib/teact/teact';\n\nexport const ANIMATION_START_EVENT = 'tt-event-heavy-animation-start';\nexport const ANIMATION_END_EVENT = 'tt-event-heavy-animation-end';\n\nlet timeout: number | undefined;\nlet isAnimating = false;\n\nexport const dispatchHeavyAnimationEvent = (duration?: number) => {\n if (!isAnimating) {\n isAnimating = true;\n document.dispatchEvent(new Event(ANIMATION_START_EVENT));\n }\n\n if (timeout) {\n clearTimeout(timeout);\n timeout = undefined;\n }\n\n if (duration) {\n timeout = window.setTimeout(() => {\n isAnimating = false;\n document.dispatchEvent(new Event(ANIMATION_END_EVENT));\n timeout = undefined;\n }, duration);\n }\n\n return () => {\n isAnimating = false;\n document.dispatchEvent(new Event(ANIMATION_END_EVENT));\n };\n};\n\nexport default (\n handleAnimationStart: AnyToVoidFunction,\n handleAnimationEnd: AnyToVoidFunction,\n) => {\n useEffect(() => {\n if (isAnimating) {\n handleAnimationStart();\n }\n\n document.addEventListener(ANIMATION_START_EVENT, handleAnimationStart);\n document.addEventListener(ANIMATION_END_EVENT, handleAnimationEnd);\n\n return () => {\n document.removeEventListener(ANIMATION_END_EVENT, handleAnimationEnd);\n document.removeEventListener(ANIMATION_START_EVENT, handleAnimationStart);\n };\n }, [handleAnimationEnd, handleAnimationStart]);\n};\n","import { useCallback, useEffect, useRef } from '../lib/teact/teact';\n\nimport { IS_IOS } from '../util/environment';\nimport usePrevious from './usePrevious';\nimport { getDispatch } from '../lib/teact/teactn';\nimport { areSortedArraysEqual } from '../util/iteratees';\n\ntype HistoryState = {\n currentIndex: number;\n nextStateIndexToReplace: number;\n isHistoryAltered: boolean;\n isDisabled: boolean;\n isEdge: boolean;\n currentIndexes: number[];\n};\n\n// Carefully selected by swiping and observing visual changes\n// TODO: may be different on other devices such as iPad, maybe take dpi into account?\nconst SAFARI_EDGE_BACK_GESTURE_LIMIT = 300;\nconst SAFARI_EDGE_BACK_GESTURE_DURATION = 350;\nexport const LOCATION_HASH = window.location.hash;\nconst PATH_BASE = `${window.location.pathname}${window.location.search}`;\n\nconst historyState: HistoryState = {\n currentIndex: 0,\n nextStateIndexToReplace: -1,\n isHistoryAltered: false,\n isDisabled: false,\n isEdge: false,\n currentIndexes: [],\n};\n\nexport const disableHistoryBack = () => {\n historyState.isDisabled = true;\n};\n\nconst handleTouchStart = (event: TouchEvent) => {\n const x = event.touches[0].pageX;\n\n if (x <= SAFARI_EDGE_BACK_GESTURE_LIMIT || x >= window.innerWidth - SAFARI_EDGE_BACK_GESTURE_LIMIT) {\n historyState.isEdge = true;\n }\n};\n\nconst handleTouchEnd = () => {\n if (historyState.isEdge) {\n setTimeout(() => {\n historyState.isEdge = false;\n }, SAFARI_EDGE_BACK_GESTURE_DURATION);\n }\n};\n\nif (IS_IOS) {\n window.addEventListener('touchstart', handleTouchStart);\n window.addEventListener('touchend', handleTouchEnd);\n window.addEventListener('popstate', handleTouchEnd);\n}\n\nwindow.history.replaceState({ index: historyState.currentIndex }, '', PATH_BASE);\n\nexport default function useHistoryBack(\n isActive: boolean | undefined,\n onBack: ((noDisableAnimation: boolean) => void) | undefined,\n onForward?: (state: any) => void,\n currentState?: any,\n shouldReplaceNext = false,\n hashes?: string[],\n) {\n const indexRef = useRef(-1);\n const isForward = useRef(false);\n const prevIsActive = usePrevious(isActive);\n const isClosed = useRef(true);\n const indexHashRef = useRef<{ index: number; hash: string }[]>([]);\n const prevHashes = usePrevious(hashes);\n const isHashChangedFromEvent = useRef(false);\n\n const handleChange = useCallback((isForceClose = false) => {\n if (!hashes) {\n if (isActive && !isForceClose) {\n isClosed.current = false;\n\n if (isForward.current) {\n isForward.current = false;\n historyState.currentIndexes.push(indexRef.current);\n } else {\n setTimeout(() => {\n const index = ++historyState.currentIndex;\n\n historyState.currentIndexes.push(index);\n\n window.history[(\n (\n historyState.currentIndexes.includes(historyState.nextStateIndexToReplace - 1)\n && window.history.state.index !== 0\n && historyState.nextStateIndexToReplace === index\n && !shouldReplaceNext\n )\n ? 'replaceState'\n : 'pushState'\n )]({\n index,\n state: currentState,\n }, '');\n\n indexRef.current = index;\n\n if (shouldReplaceNext) {\n historyState.nextStateIndexToReplace = historyState.currentIndex + 1;\n }\n }, 0);\n }\n }\n\n if ((isForceClose || !isActive) && !isClosed.current) {\n if ((indexRef.current === historyState.currentIndex || !shouldReplaceNext)) {\n historyState.isHistoryAltered = true;\n window.history.back();\n\n setTimeout(() => {\n historyState.nextStateIndexToReplace = -1;\n }, 400);\n }\n historyState.currentIndexes.splice(historyState.currentIndexes.indexOf(indexRef.current), 1);\n\n isClosed.current = true;\n }\n } else {\n const prev = prevHashes || [];\n if (prev.length < hashes.length) {\n setTimeout(() => {\n const index = ++historyState.currentIndex;\n historyState.currentIndexes.push(index);\n\n window.history.pushState({\n index,\n state: currentState,\n }, '', `#${hashes[hashes.length - 1]}`);\n\n indexHashRef.current.push({\n index,\n hash: hashes[hashes.length - 1],\n });\n }, 0);\n } else {\n const delta = prev.length - hashes.length;\n if (isHashChangedFromEvent.current) {\n isHashChangedFromEvent.current = false;\n } else {\n if (hashes.length !== indexHashRef.current.length) {\n if (delta > 0) {\n const last = indexHashRef.current[indexHashRef.current.length - delta - 1];\n let realDelta = delta;\n if (last) {\n const indexLast = historyState.currentIndexes.findIndex(\n (l) => l === last.index,\n );\n realDelta = historyState.currentIndexes.length - indexLast - 1;\n }\n historyState.isHistoryAltered = true;\n window.history.go(-realDelta);\n const removed = indexHashRef.current.splice(indexHashRef.current.length - delta - 1, delta);\n removed.forEach(({ index }) => {\n historyState.currentIndexes.splice(historyState.currentIndexes.indexOf(index), 1);\n });\n }\n }\n\n if (hashes.length > 0) {\n setTimeout(() => {\n const index = ++historyState.currentIndex;\n historyState.currentIndexes[historyState.currentIndexes.length - 1] = index;\n\n window.history.replaceState({\n index,\n state: currentState,\n }, '', `${PATH_BASE}#${hashes[hashes.length - 1]}`);\n\n indexHashRef.current[indexHashRef.current.length - 1] = {\n index,\n hash: hashes[hashes.length - 1],\n };\n }, 0);\n }\n }\n }\n }\n }, [currentState, hashes, isActive, prevHashes, shouldReplaceNext]);\n\n useEffect(() => {\n const handlePopState = (event: PopStateEvent) => {\n if (historyState.isHistoryAltered) {\n setTimeout(() => {\n historyState.isHistoryAltered = false;\n }, 0);\n return;\n }\n const { index: i } = event.state;\n const index = i || 0;\n try {\n const currIndex = hashes ? indexHashRef.current[indexHashRef.current.length - 1].index : indexRef.current;\n\n const prev = historyState.currentIndexes[historyState.currentIndexes.indexOf(currIndex) - 1];\n\n if (historyState.isDisabled) return;\n\n if ((!isClosed.current && (index === 0 || index === prev)) || (hashes && (index === 0 || index === prev))) {\n if (hashes) {\n isHashChangedFromEvent.current = true;\n indexHashRef.current.pop();\n }\n\n historyState.currentIndexes.splice(historyState.currentIndexes.indexOf(currIndex), 1);\n\n if (onBack) {\n if (historyState.isEdge) {\n getDispatch()\n .disableHistoryAnimations();\n }\n onBack(!historyState.isEdge);\n isClosed.current = true;\n }\n } else if (index === currIndex && isClosed.current && onForward && !hashes) {\n isForward.current = true;\n if (historyState.isEdge) {\n getDispatch()\n .disableHistoryAnimations();\n }\n onForward(event.state.state);\n }\n } catch (e) {\n // Forward navigation for hashed is not supported\n }\n };\n\n const hasChanged = hashes\n ? (!prevHashes || !areSortedArraysEqual(prevHashes, hashes))\n : prevIsActive !== isActive;\n\n if (!historyState.isDisabled && hasChanged) {\n handleChange();\n }\n\n window.addEventListener('popstate', handlePopState);\n return () => window.removeEventListener('popstate', handlePopState);\n }, [\n currentState, handleChange, hashes, isActive, onBack, onForward, prevHashes, prevIsActive, shouldReplaceNext,\n ]);\n\n return {\n forceClose: () => handleChange(true),\n };\n}\n","import { RefObject } from 'react';\nimport { useState, useCallback, useEffect } from '../lib/teact/teact';\n\nexport default (\n elementRef: RefObject,\n isOpen: boolean,\n onSelectWithEnter?: (index: number) => void,\n itemSelector?: string,\n noCaptureFocus?: boolean,\n) => {\n const [focusedIndex, setFocusedIndex] = useState(-1);\n\n useEffect(() => {\n setFocusedIndex(-1);\n\n const element = elementRef.current;\n if (isOpen && element && !noCaptureFocus) {\n element.tabIndex = -1;\n element.focus();\n }\n }, [elementRef, isOpen, noCaptureFocus]);\n\n const handleKeyDown = useCallback((e: React.KeyboardEvent) => {\n const element = elementRef.current;\n\n if (!element) {\n return;\n }\n\n if (e.keyCode === 13 && onSelectWithEnter) {\n onSelectWithEnter(focusedIndex);\n return;\n }\n\n if (e.keyCode !== 38 && e.keyCode !== 40) {\n return;\n }\n\n const focusedElement = document.activeElement;\n const elementChildren = Array.from(itemSelector ? element.querySelectorAll(itemSelector) : element.children);\n\n let newIndex = (focusedElement && elementChildren.indexOf(focusedElement)) || focusedIndex;\n\n if (e.keyCode === 38 && newIndex > 0) {\n newIndex--;\n } else if (e.keyCode === 40 && newIndex < elementChildren.length - 1) {\n newIndex++;\n } else if (elementChildren.length === 1) {\n newIndex = 0;\n } else {\n return;\n }\n\n const item = elementChildren[newIndex] as HTMLElement;\n if (item) {\n setFocusedIndex(newIndex);\n item.focus();\n }\n }, [elementRef, onSelectWithEnter, itemSelector, focusedIndex]);\n\n return handleKeyDown;\n};\n","import * as langProvider from '../util/langProvider';\nimport useForceUpdate from './useForceUpdate';\nimport useOnChange from './useOnChange';\n\nexport type LangFn = typeof langProvider.getTranslation;\n\nexport default (): LangFn => {\n const forceUpdate = useForceUpdate();\n\n useOnChange(() => {\n return langProvider.addCallback(forceUpdate);\n }, [forceUpdate]);\n\n return langProvider.getTranslation;\n};\n","import { useEffect } from '../lib/teact/teact';\n\nimport {\n BundleModules, Bundles, getModuleFromMemory, loadModule, addLoadListener,\n} from '../util/moduleLoader';\n\nimport useForceUpdate from './useForceUpdate';\n\nexport default >(\n bundleName: B, moduleName: M, noLoad = false, autoUpdate = false,\n) => {\n const module = getModuleFromMemory(bundleName, moduleName);\n const forceUpdate = useForceUpdate();\n\n if (autoUpdate) {\n // Use effect and cleanup for listener removal\n addLoadListener(forceUpdate);\n }\n\n useEffect(() => {\n if (!noLoad && !module) {\n loadModule(bundleName, moduleName).then(forceUpdate);\n }\n }, [bundleName, forceUpdate, module, moduleName, noLoad]);\n\n return module;\n};\n","import usePrevious from './usePrevious';\n\nexport default (cb: (args: PT) => void, dependencies: T) => {\n const prevDeps = usePrevious(dependencies);\n if (!prevDeps || dependencies.some((d, i) => d !== prevDeps[i])) {\n // @ts-ignore (workaround for \"could be instantiated with a different subtype\" issue)\n cb(prevDeps || []);\n }\n};\n","import { useRef } from '../lib/teact/teact';\n\nfunction usePrevious(next: T): T | undefined;\nfunction usePrevious(next: T, shouldSkipUndefined: true): Exclude | undefined;\nfunction usePrevious(next: T, shouldSkipUndefined?: boolean): Exclude | undefined;\nfunction usePrevious(next: T, shouldSkipUndefined?: boolean) {\n const ref = useRef();\n const { current } = ref;\n if (!shouldSkipUndefined || next !== undefined) {\n ref.current = next;\n }\n\n return current;\n}\n\nexport default usePrevious;\n","import { useRef, useState } from '../lib/teact/teact';\nimport buildClassName from '../util/buildClassName';\n\nconst CLOSE_DURATION = 350;\n\nexport default (\n isOpen = false,\n onCloseTransitionEnd?: () => void,\n noOpenTransition = false,\n className: string | false = 'fast',\n noCloseTransition = false,\n) => {\n const [isClosed, setIsClosed] = useState(!isOpen);\n const closeTimeoutRef = useRef();\n // СSS class should be added in a separate tick to turn on CSS transition.\n const [hasOpenClassName, setHasOpenClassName] = useState(isOpen && noOpenTransition);\n\n if (isOpen) {\n setIsClosed(false);\n setHasOpenClassName(true);\n\n if (closeTimeoutRef.current) {\n window.clearTimeout(closeTimeoutRef.current);\n closeTimeoutRef.current = undefined;\n }\n } else {\n setHasOpenClassName(false);\n\n if (!isClosed && !closeTimeoutRef.current) {\n closeTimeoutRef.current = window.setTimeout(() => {\n setIsClosed(true);\n\n if (onCloseTransitionEnd) {\n onCloseTransitionEnd();\n }\n\n closeTimeoutRef.current = undefined;\n }, noCloseTransition ? 0 : CLOSE_DURATION);\n }\n }\n\n // `noCloseTransition`, when set to true, should remove the open class immediately\n const shouldHaveOpenClassName = hasOpenClassName && !(noCloseTransition && !isOpen);\n const isClosing = Boolean(closeTimeoutRef.current);\n const shouldRender = isOpen || isClosing;\n const transitionClassNames = buildClassName(\n className && 'opacity-transition',\n className,\n shouldHaveOpenClassName && 'open',\n shouldRender && 'shown',\n isClosing && 'closing',\n );\n\n return {\n shouldRender,\n transitionClassNames,\n };\n};\n","import { RefObject } from 'react';\nimport { useEffect } from '../lib/teact/teact';\n\nconst BACKDROP_CLASSNAME = 'backdrop';\n\n// This effect implements closing menus by clicking outside of them\n// without adding extra elements to the DOM\nexport default function useVirtualBackdrop(\n isOpen: boolean,\n menuRef: RefObject,\n onClose?: () => void | undefined,\n) {\n useEffect(() => {\n const handleEvent = (e: Event) => {\n const menu = menuRef.current;\n const target = e.target as HTMLElement | null;\n if (!menu || !target) {\n return;\n }\n\n if (\n !menu.contains(e.target as Node | null)\n || target.classList.contains(BACKDROP_CLASSNAME)\n ) {\n e.preventDefault();\n e.stopPropagation();\n if (onClose) {\n onClose();\n }\n }\n };\n\n if (isOpen && onClose) {\n document.addEventListener('mousedown', handleEvent);\n }\n\n return () => {\n document.removeEventListener('mousedown', handleEvent);\n };\n }, [isOpen, menuRef, onClose]);\n}\n","import { DEBUG } from '../../config';\n\ntype Handler = (e: Event) => void;\n\nconst NON_BUBBLEABLE_EVENTS = new Set(['scroll', 'mouseenter', 'mouseleave']);\n\nconst delegationRegistry: Record> = {};\nconst delegatedEventsByElement = new Map>();\nconst documentEventCounters: Record = {};\n\nexport function addEventListener(element: HTMLElement, propName: string, handler: Handler, asCapture = false) {\n const eventName = resolveEventName(propName, element);\n if (canUseEventDelegation(eventName, element, asCapture)) {\n addDelegatedListener(eventName, element, handler);\n } else {\n element.addEventListener(eventName, handler, asCapture);\n }\n}\n\nexport function removeEventListener(element: HTMLElement, propName: string, handler: Handler, asCapture = false) {\n const eventName = resolveEventName(propName, element);\n if (canUseEventDelegation(eventName, element, asCapture)) {\n removeDelegatedListener(eventName, element);\n } else {\n element.removeEventListener(eventName, handler, asCapture);\n }\n}\n\nfunction resolveEventName(propName: string, element: HTMLElement) {\n const eventName = propName\n .replace(/^on/, '')\n .replace(/Capture$/, '').toLowerCase();\n\n if (eventName === 'change' && element.tagName !== 'SELECT') {\n // React behavior repeated here.\n // https://stackoverflow.com/questions/38256332/in-react-whats-the-difference-between-onchange-and-oninput\n return 'input';\n }\n\n if (eventName === 'doubleclick') {\n return 'dblclick';\n }\n\n // Replace focus/blur by their \"bubbleable\" versions\n if (eventName === 'focus') {\n return 'focusin';\n }\n\n if (eventName === 'blur') {\n return 'focusout';\n }\n\n return eventName;\n}\n\nfunction canUseEventDelegation(realEventName: string, element: HTMLElement, asCapture: boolean) {\n return (\n !asCapture\n && !NON_BUBBLEABLE_EVENTS.has(realEventName)\n && element.tagName !== 'VIDEO'\n && element.tagName !== 'IFRAME'\n );\n}\n\nfunction addDelegatedListener(eventName: string, element: HTMLElement, handler: Handler) {\n if (!documentEventCounters[eventName]) {\n documentEventCounters[eventName] = 0;\n document.addEventListener(eventName, handleEvent);\n }\n\n resolveDelegationRegistryForName(eventName).set(element, handler);\n resolveDelegatedEventsForElement(element).add(eventName);\n documentEventCounters[eventName]++;\n}\n\nfunction removeDelegatedListener(eventName: string, element: HTMLElement) {\n documentEventCounters[eventName]--;\n if (!documentEventCounters[eventName]) {\n // Synchronous deletion on 0 will cause perf degradation in the case of 1 element\n // which is not a real case, so it's ok to do it this way\n document.removeEventListener(eventName, handleEvent);\n }\n\n delegationRegistry[eventName].delete(element);\n delegatedEventsByElement.get(element)!.delete(eventName);\n}\n\nexport function removeAllDelegatedListeners(element: HTMLElement) {\n const eventNames = delegatedEventsByElement.get(element);\n if (!eventNames) {\n return;\n }\n\n eventNames.forEach((eventName) => removeDelegatedListener(eventName, element));\n delegatedEventsByElement.delete(element);\n}\n\nfunction handleEvent(realEvent: Event) {\n const events = delegationRegistry[realEvent.type];\n\n if (events) {\n let furtherCallsPrevented = false;\n let current: HTMLElement = realEvent.target as HTMLElement;\n\n const stopPropagation = () => {\n furtherCallsPrevented = true;\n };\n\n const preventDefault = () => {\n realEvent.preventDefault();\n };\n\n // Proxy is a simplest way to provide an access to the event property\n const event = new Proxy(realEvent, {\n get(target, p) {\n if (p === 'currentTarget') {\n return current;\n }\n if (p === 'stopPropagation' || p === 'stopImmediatePropagation') {\n return stopPropagation;\n }\n if (p === 'preventDefault') {\n // \"this\" is changed to proxy and one can't call methods via it\n return preventDefault;\n }\n return Reflect.get(target, p);\n },\n });\n\n // This can also be limited by teact root\n while (current && current !== document.body) {\n const handler = events.get(current);\n if (handler) {\n handler(event);\n if (furtherCallsPrevented) {\n return;\n }\n }\n\n current = current.parentNode as HTMLElement;\n }\n }\n}\n\nfunction resolveDelegationRegistryForName(eventName: string) {\n if (!delegationRegistry[eventName]) {\n delegationRegistry[eventName] = new Map();\n }\n\n return delegationRegistry[eventName];\n}\n\nfunction resolveDelegatedEventsForElement(element: HTMLElement) {\n const existing = delegatedEventsByElement.get(element);\n if (existing) {\n return existing;\n }\n\n const newSet = new Set();\n delegatedEventsByElement.set(element, newSet);\n\n return newSet;\n}\n\nif (DEBUG) {\n document.addEventListener('dblclick', () => {\n // eslint-disable-next-line no-console\n console.log('DELEGATED EVENTS', { delegationRegistry, delegatedEventsByElement, documentEventCounters });\n });\n}\n","import {\n hasElementChanged,\n isComponentElement,\n isEmptyElement,\n isRealElement,\n isTextElement,\n mountComponent,\n renderComponent,\n unmountTree,\n getTarget,\n setTarget,\n VirtualElement,\n VirtualElementComponent,\n VirtualRealElement,\n} from './teact';\nimport generateIdFor from '../../util/generateIdFor';\nimport { DEBUG } from '../../config';\nimport { addEventListener, removeEventListener } from './dom-events';\n\ntype VirtualDomHead = {\n children: [VirtualElement] | [];\n};\n\nconst FILTERED_ATTRIBUTES = new Set(['key', 'ref', 'teactFastList', 'teactOrderKey']);\nconst HTML_ATTRIBUTES = new Set(['dir']);\nconst MAPPED_ATTRIBUTES: { [k: string]: string } = {\n autoPlay: 'autoplay',\n autoComplete: 'autocomplete',\n};\nconst INDEX_KEY_PREFIX = '__indexKey#';\n\nconst headsByElement: Record = {};\n// eslint-disable-next-line @typescript-eslint/naming-convention\nlet DEBUG_virtualTreeSize = 1;\n\nfunction render($element?: VirtualElement, parentEl?: HTMLElement | null) {\n if (!parentEl) {\n return undefined;\n }\n\n let headId = parentEl.getAttribute('data-teact-head-id');\n if (!headId) {\n headId = generateIdFor(headsByElement);\n headsByElement[headId] = { children: [] };\n parentEl.setAttribute('data-teact-head-id', headId);\n }\n\n const $head = headsByElement[headId];\n $head.children = [renderWithVirtual(parentEl, $head.children[0], $element, $head, 0) as VirtualElement];\n\n if (process.env.APP_ENV === 'perf') {\n DEBUG_virtualTreeSize = 0;\n DEBUG_addToVirtualTreeSize($head);\n\n return DEBUG_virtualTreeSize;\n }\n\n return undefined;\n}\n\nfunction renderWithVirtual(\n parentEl: HTMLElement,\n $current: VirtualElement | undefined,\n $new: VirtualElement | undefined,\n $parent: VirtualRealElement | VirtualDomHead,\n index: number,\n {\n skipComponentUpdate = false,\n forceIndex = false,\n fragment,\n moveDirection,\n }: {\n skipComponentUpdate?: boolean;\n forceIndex?: boolean;\n fragment?: DocumentFragment;\n moveDirection?: 'up' | 'down';\n } = {},\n) {\n if (\n !skipComponentUpdate\n && $current && $new\n && isComponentElement($current) && isComponentElement($new)\n && !hasElementChanged($current, $new)\n ) {\n $new = updateComponent($current, $new);\n }\n\n // Parent element may have changed, so we need to update the listener closure.\n if (!skipComponentUpdate && $new && isComponentElement($new) && $new.componentInstance.isMounted) {\n setupComponentUpdateListener($new, $parent, index, parentEl);\n }\n\n if ($current === $new) {\n return $new;\n }\n\n if (!$current && $new) {\n if (isComponentElement($new)) {\n $new = initComponent($new, $parent, index, parentEl);\n }\n\n const node = createNode($new);\n setTarget($new, node);\n\n if (forceIndex && parentEl.childNodes[index]) {\n parentEl.insertBefore(node, parentEl.childNodes[index]);\n } else {\n (fragment || parentEl).appendChild(node);\n }\n } else if ($current && !$new) {\n parentEl.removeChild(getTarget($current)!);\n unmountTree($current);\n } else if ($current && $new) {\n if (hasElementChanged($current, $new)) {\n if (isComponentElement($new)) {\n $new = initComponent($new, $parent, index, parentEl);\n }\n\n const node = createNode($new);\n setTarget($new, node);\n parentEl.replaceChild(node, getTarget($current)!);\n unmountTree($current);\n } else {\n const areComponents = isComponentElement($current) && isComponentElement($new);\n\n if (!areComponents) {\n setTarget($new, getTarget($current)!);\n }\n\n if (isRealElement($current) && isRealElement($new)) {\n if (moveDirection) {\n const node = getTarget($current)!;\n const nextSibling = parentEl.childNodes[moveDirection === 'up' ? index : index + 1];\n\n if (nextSibling) {\n parentEl.insertBefore(node, nextSibling);\n } else {\n (fragment || parentEl).appendChild(node);\n }\n }\n\n if (!areComponents) {\n updateAttributes($current, $new, getTarget($current) as HTMLElement);\n }\n\n $new.children = renderChildren(\n $current,\n $new,\n areComponents ? parentEl : getTarget($current) as HTMLElement,\n );\n }\n }\n }\n\n return $new;\n}\n\nfunction initComponent(\n $element: VirtualElementComponent, $parent: VirtualRealElement | VirtualDomHead, index: number, parentEl: HTMLElement,\n) {\n if (!isComponentElement($element)) {\n return $element;\n }\n\n const { componentInstance } = $element;\n\n if (!componentInstance.isMounted) {\n $element = mountComponent(componentInstance);\n setupComponentUpdateListener($element, $parent, index, parentEl);\n\n const $firstChild = $element.children[0];\n if (isComponentElement($firstChild)) {\n $element.children = [initComponent($firstChild, $element, 0, parentEl)];\n }\n\n componentInstance.isMounted = true;\n }\n\n return $element;\n}\n\nfunction updateComponent($current: VirtualElementComponent, $new: VirtualElementComponent) {\n $current.componentInstance.props = $new.componentInstance.props;\n\n return renderComponent($current.componentInstance);\n}\n\nfunction setupComponentUpdateListener(\n $element: VirtualElementComponent, $parent: VirtualRealElement | VirtualDomHead, index: number, parentEl: HTMLElement,\n) {\n const { componentInstance } = $element;\n\n componentInstance.onUpdate = () => {\n $parent.children[index] = renderWithVirtual(\n parentEl,\n $parent.children[index],\n componentInstance.$element,\n $parent,\n index,\n { skipComponentUpdate: true },\n ) as VirtualElementComponent;\n };\n}\n\nfunction createNode($element: VirtualElement): Node {\n if (isEmptyElement($element)) {\n return document.createTextNode('');\n }\n\n if (isTextElement($element)) {\n return document.createTextNode($element.value);\n }\n\n if (isComponentElement($element)) {\n return createNode($element.children[0] as VirtualElement);\n }\n\n const { tag, props, children = [] } = $element;\n const element = document.createElement(tag);\n\n if (typeof props.ref === 'object') {\n props.ref.current = element;\n }\n\n Object.keys(props).forEach((key) => {\n addAttribute(element, key, props[key]);\n });\n\n $element.children = children.map(($child, i) => (\n renderWithVirtual(element, undefined, $child, $element, i) as VirtualElement\n ));\n\n return element;\n}\n\nfunction renderChildren(\n $current: VirtualRealElement, $new: VirtualRealElement, currentEl: HTMLElement,\n) {\n if ($new.props.teactFastList) {\n return renderFastListChildren($current, $new, currentEl);\n }\n\n const maxLength = Math.max($current.children.length, $new.children.length);\n const newChildren = [];\n const fragment = $new.children.length > $current.children.length + 1 ? document.createDocumentFragment() : undefined;\n\n for (let i = 0; i < maxLength; i++) {\n const $newChild = renderWithVirtual(\n currentEl,\n $current.children[i],\n $new.children[i],\n $new,\n i,\n i >= $current.children.length ? { fragment } : undefined,\n );\n\n if ($newChild) {\n newChildren.push($newChild);\n }\n }\n\n if (fragment) {\n currentEl.appendChild(fragment);\n }\n\n return newChildren;\n}\n\nfunction renderFastListChildren($current: VirtualRealElement, $new: VirtualRealElement, currentEl: HTMLElement) {\n const newKeys = new Set(\n $new.children.map(($newChild) => {\n const key = 'props' in $newChild && $newChild.props.key;\n\n if (DEBUG && isRealElement($newChild) && !key) {\n // eslint-disable-next-line no-console\n console.warn('Missing `key` in `teactFastList`');\n }\n\n return key;\n }),\n );\n\n let currentRemainingIndex = 0;\n const remainingByKey = $current.children\n .reduce((acc, $currentChild, i) => {\n let key = 'props' in $currentChild ? $currentChild.props.key : undefined;\n\n // First we handle removed children\n if (key && !newKeys.has(key)) {\n renderWithVirtual(currentEl, $currentChild, undefined, $new, -1);\n\n return acc;\n } else if (!key) {\n const $newChild = $new.children[i];\n const newChildKey = ($newChild && 'props' in $newChild) ? $newChild.props.key : undefined;\n // If a non-key element remains at the same index we preserve it with a virtual `key`\n if ($newChild && !newChildKey) {\n key = `${INDEX_KEY_PREFIX}${i}`;\n } else {\n renderWithVirtual(currentEl, $currentChild, undefined, $new, -1);\n\n return acc;\n }\n }\n\n // Then we build up info about remaining children\n acc[key] = {\n $element: $currentChild,\n index: currentRemainingIndex++,\n order: 'props' in $currentChild ? $currentChild.props.teactOrderKey : undefined,\n };\n return acc;\n }, {} as Record);\n\n let newChildren: VirtualElement[] = [];\n\n let fragmentQueue: VirtualElement[] | undefined;\n let fragmentIndex: number | undefined;\n\n let currentPreservedIndex = 0;\n\n $new.children.forEach(($newChild, i) => {\n const key = 'props' in $newChild ? $newChild.props.key : `${INDEX_KEY_PREFIX}${i}`;\n const currentChildInfo = remainingByKey[key];\n\n if (!currentChildInfo) {\n // All new nodes are queued to be inserted with fragments if possible.\n if (!fragmentQueue) {\n fragmentQueue = [];\n fragmentIndex = i;\n }\n\n fragmentQueue.push($newChild);\n return;\n }\n\n if (fragmentQueue) {\n newChildren = newChildren.concat(flushFragmentQueue(fragmentQueue, fragmentIndex!, currentEl, $new));\n fragmentIndex = undefined;\n fragmentQueue = undefined;\n }\n\n // This is a \"magic\" `teactOrderKey` property that tells us the element is updated\n const order = 'props' in $newChild ? $newChild.props.teactOrderKey : undefined;\n const shouldMoveNode = currentChildInfo.index !== currentPreservedIndex && currentChildInfo.order !== order;\n const isMovingDown = shouldMoveNode && currentPreservedIndex > currentChildInfo.index;\n\n // When the node goes down, preserved indexing actually breaks, so the \"magic\" should help.\n if (!shouldMoveNode || isMovingDown) {\n currentPreservedIndex++;\n }\n\n newChildren.push(\n renderWithVirtual(currentEl, currentChildInfo.$element, $newChild, $new, i, {\n forceIndex: true,\n ...(shouldMoveNode && {\n moveDirection: isMovingDown ? 'down' : 'up',\n }),\n })!,\n );\n });\n\n if (fragmentQueue) {\n newChildren = newChildren.concat(flushFragmentQueue(fragmentQueue, fragmentIndex!, currentEl, $new));\n }\n\n return newChildren;\n}\n\nfunction flushFragmentQueue(\n fragmentQueue: VirtualElement[], fragmentIndex: number, parentEl: HTMLElement, $parent: VirtualRealElement,\n) {\n if (fragmentQueue.length === 1) {\n return [renderWithVirtual(parentEl, undefined, fragmentQueue[0], $parent, fragmentIndex, { forceIndex: true })!];\n } else if (fragmentQueue.length > 1) {\n const fragment = document.createDocumentFragment();\n const newChildren = fragmentQueue.map(($fragmentChild) => (\n renderWithVirtual(parentEl, undefined, $fragmentChild, $parent, fragmentIndex!, { fragment })!\n ));\n\n if (parentEl.childNodes[fragmentIndex]) {\n parentEl.insertBefore(fragment, parentEl.childNodes[fragmentIndex]);\n } else {\n parentEl.appendChild(fragment);\n }\n\n return newChildren;\n }\n\n throw new Error('Unexpected input');\n}\n\nfunction updateAttributes($current: VirtualRealElement, $new: VirtualRealElement, element: HTMLElement) {\n const currentKeys = Object.keys($current.props);\n const newKeys = Object.keys($new.props);\n\n currentKeys.forEach((key) => {\n if ($current.props[key] !== undefined && $new.props[key] === undefined) {\n removeAttribute(element, key, $current.props[key]);\n }\n });\n\n newKeys.forEach((key) => {\n if ($new.props[key] === undefined) {\n return;\n }\n\n if ($current.props[key] !== $new.props[key]) {\n if ($current.props[key] === undefined) {\n addAttribute(element, key, $new.props[key]);\n } else {\n updateAttribute(element, key, $current.props[key], $new.props[key]);\n }\n }\n });\n}\n\nfunction addAttribute(element: HTMLElement, key: string, value: any) {\n if (value === undefined) {\n return;\n }\n\n // An optimization attempt\n if (key === 'className') {\n element.className = value;\n // An optimization attempt\n } else if (key === 'value') {\n (element as HTMLInputElement).value = value;\n } else if (key === 'style') {\n element.style.cssText = value;\n } else if (key.startsWith('on')) {\n addEventListener(element, key, value, key.endsWith('Capture'));\n } else if (key.startsWith('data-') || HTML_ATTRIBUTES.has(key)) {\n element.setAttribute(key, value);\n } else if (!FILTERED_ATTRIBUTES.has(key)) {\n (element as any)[MAPPED_ATTRIBUTES[key] || key] = value;\n }\n}\n\nfunction removeAttribute(element: HTMLElement, key: string, value: any) {\n if (key === 'className') {\n element.className = '';\n } else if (key === 'value') {\n (element as HTMLInputElement).value = '';\n } else if (key === 'style') {\n element.style.cssText = '';\n } else if (key.startsWith('on')) {\n removeEventListener(element, key, value, key.endsWith('Capture'));\n } else if (key.startsWith('data-') || HTML_ATTRIBUTES.has(key)) {\n element.removeAttribute(key);\n } else if (!FILTERED_ATTRIBUTES.has(key)) {\n delete (element as any)[MAPPED_ATTRIBUTES[key] || key];\n }\n}\n\nfunction updateAttribute(element: HTMLElement, key: string, oldValue: any, newValue: any) {\n if (key === 'value') {\n // Removing and adding value causes a cursor jump\n (element as HTMLInputElement).value = newValue !== undefined ? newValue : '';\n } else {\n removeAttribute(element, key, oldValue);\n addAttribute(element, key, newValue);\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/naming-convention\nfunction DEBUG_addToVirtualTreeSize($current: VirtualRealElement | VirtualDomHead) {\n DEBUG_virtualTreeSize += $current.children.length;\n\n $current.children.forEach(($child) => {\n if (isRealElement($child)) {\n DEBUG_addToVirtualTreeSize($child);\n }\n });\n}\n\nexport default { render };\n","import { DEBUG, DEBUG_MORE } from '../../config';\nimport {\n fastRaf, fastRafPrimary, onTickEnd, onTickEndPrimary, throttleWithPrimaryRaf, throttleWithRaf,\n} from '../../util/schedulers';\nimport { flatten, orderBy } from '../../util/iteratees';\nimport arePropsShallowEqual, { getUnequalProps } from '../../util/arePropsShallowEqual';\nimport { handleError } from '../../util/handleError';\nimport { removeAllDelegatedListeners } from './dom-events';\n\nexport type Props = AnyLiteral;\nexport type FC

= (props: P) => any;\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport type FC_withDebug = FC & {\n DEBUG_contentComponentName?: string;\n};\n\nexport enum VirtualElementTypesEnum {\n Empty,\n Text,\n Tag,\n Component,\n}\n\ninterface VirtualElementEmpty {\n type: VirtualElementTypesEnum.Empty;\n target?: Node;\n}\n\ninterface VirtualElementText {\n type: VirtualElementTypesEnum.Text;\n target?: Node;\n value: string;\n}\n\nexport interface VirtualElementTag {\n type: VirtualElementTypesEnum.Tag;\n target?: Node;\n tag: string;\n props: Props;\n children: VirtualElementChildren;\n}\n\nexport interface VirtualElementComponent {\n type: VirtualElementTypesEnum.Component;\n componentInstance: ComponentInstance;\n props: Props;\n children: VirtualElementChildren;\n}\n\nexport type StateHookSetter = (newValue: ((current: T) => T) | T) => void;\n\ninterface ComponentInstance {\n $element: VirtualElementComponent;\n Component: FC;\n name: string;\n props: Props;\n renderedValue?: any;\n isMounted: boolean;\n hooks: {\n state: {\n cursor: number;\n byCursor: {\n value: any;\n nextValue: any;\n setter: StateHookSetter;\n }[];\n };\n effects: {\n cursor: number;\n byCursor: {\n effect: () => void;\n dependencies?: any[];\n cleanup?: Function;\n }[];\n };\n memos: {\n cursor: number;\n byCursor: {\n current: any;\n dependencies: any[];\n }[];\n };\n };\n prepareForFrame?: () => void;\n forceUpdate?: () => void;\n onUpdate?: () => void;\n}\n\nexport type VirtualElement =\n VirtualElementEmpty\n | VirtualElementText\n | VirtualElementTag\n | VirtualElementComponent;\nexport type VirtualRealElement =\n VirtualElementTag\n | VirtualElementComponent;\nexport type VirtualElementChildren = VirtualElement[];\n\nconst Fragment = Symbol('Fragment');\n\nlet renderingInstance: ComponentInstance;\n\nexport function isEmptyElement($element: VirtualElement): $element is VirtualElementEmpty {\n return $element.type === VirtualElementTypesEnum.Empty;\n}\n\nexport function isTextElement($element: VirtualElement): $element is VirtualElementText {\n return $element.type === VirtualElementTypesEnum.Text;\n}\n\nexport function isTagElement($element: VirtualElement): $element is VirtualElementTag {\n return $element.type === VirtualElementTypesEnum.Tag;\n}\n\nexport function isComponentElement($element: VirtualElement): $element is VirtualElementComponent {\n return $element.type === VirtualElementTypesEnum.Component;\n}\n\nexport function isRealElement($element: VirtualElement): $element is VirtualRealElement {\n return isTagElement($element) || isComponentElement($element);\n}\n\nfunction createElement(\n source: string | FC | typeof Fragment,\n props: Props,\n ...children: any[]\n): VirtualRealElement | VirtualElementChildren {\n if (!props) {\n props = {};\n }\n\n children = flatten(children);\n\n if (source === Fragment) {\n return children;\n } else if (typeof source === 'function') {\n return createComponentInstance(source, props, children);\n } else {\n return buildTagElement(source, props, children);\n }\n}\n\nfunction createComponentInstance(Component: FC, props: Props, children: any[]): VirtualElementComponent {\n let parsedChildren: any | any[] | undefined;\n if (children.length === 0) {\n parsedChildren = undefined;\n } else if (children.length === 1) {\n [parsedChildren] = children;\n } else {\n parsedChildren = children;\n }\n\n const componentInstance: ComponentInstance = {\n $element: {} as VirtualElementComponent,\n Component,\n name: Component.name,\n props: {\n ...props,\n ...(parsedChildren && { children: parsedChildren }),\n },\n isMounted: false,\n hooks: {\n state: {\n cursor: 0,\n byCursor: [],\n },\n effects: {\n cursor: 0,\n byCursor: [],\n },\n memos: {\n cursor: 0,\n byCursor: [],\n },\n },\n };\n\n componentInstance.$element = buildComponentElement(componentInstance);\n\n return componentInstance.$element;\n}\n\nfunction buildComponentElement(\n componentInstance: ComponentInstance,\n children: VirtualElementChildren = [],\n): VirtualElementComponent {\n const { props } = componentInstance;\n\n return {\n componentInstance,\n type: VirtualElementTypesEnum.Component,\n props,\n children,\n };\n}\n\nfunction buildTagElement(tag: string, props: Props, children: any[]): VirtualElementTag {\n return {\n type: VirtualElementTypesEnum.Tag,\n tag,\n props,\n children: dropEmptyTail(children).map(buildChildElement),\n };\n}\n\n// We only need placeholders in the middle of collection (to ensure other elements order).\nfunction dropEmptyTail(children: any[]) {\n let i = children.length - 1;\n\n for (; i >= 0; i--) {\n if (!isEmptyPlaceholder(children[i])) {\n break;\n }\n }\n\n return i + 1 < children.length ? children.slice(0, i + 1) : children;\n}\n\nfunction isEmptyPlaceholder(child: any) {\n // eslint-disable-next-line no-null/no-null\n return child === false || child === null || child === undefined;\n}\n\nfunction buildChildElement(child: any): VirtualElement {\n if (isEmptyPlaceholder(child)) {\n return buildEmptyElement();\n } else if (isRealElement(child)) {\n return child;\n } else {\n return buildTextElement(child);\n }\n}\n\nfunction buildTextElement(value: any): VirtualElementText {\n return {\n type: VirtualElementTypesEnum.Text,\n value: String(value),\n };\n}\n\nfunction buildEmptyElement(): VirtualElementEmpty {\n return { type: VirtualElementTypesEnum.Empty };\n}\n\n// eslint-disable-next-line @typescript-eslint/naming-convention\nconst DEBUG_components: AnyLiteral = {};\n\ndocument.addEventListener('dblclick', () => {\n // eslint-disable-next-line no-console\n console.log('COMPONENTS', orderBy(Object.values(DEBUG_components), 'renderCount', 'desc'));\n});\n\nexport function renderComponent(componentInstance: ComponentInstance) {\n renderingInstance = componentInstance;\n componentInstance.hooks.state.cursor = 0;\n componentInstance.hooks.effects.cursor = 0;\n componentInstance.hooks.memos.cursor = 0;\n\n const { Component, props } = componentInstance;\n let newRenderedValue;\n\n try {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n let DEBUG_startAt: number | undefined;\n if (DEBUG) {\n const componentName = componentInstance.name;\n if (!DEBUG_components[componentName]) {\n DEBUG_components[componentName] = {\n componentName,\n renderCount: 0,\n renderTimes: [],\n };\n }\n\n if (DEBUG_MORE) {\n if (componentName !== 'TeactMemoWrapper' && componentName !== 'TeactNContainer') {\n // eslint-disable-next-line no-console\n console.log(`[Teact] Render ${componentName}`);\n }\n }\n\n DEBUG_startAt = performance.now();\n }\n\n newRenderedValue = Component(props);\n\n if (DEBUG) {\n const renderTime = performance.now() - DEBUG_startAt!;\n const componentName = componentInstance.name;\n if (renderTime > 7) {\n // eslint-disable-next-line no-console\n console.warn(`[Teact] Slow component render: ${componentName}, ${Math.round(renderTime)} ms`);\n }\n DEBUG_components[componentName].renderTimes.push(renderTime);\n DEBUG_components[componentName].renderCount++;\n }\n } catch (err) {\n handleError(err);\n\n newRenderedValue = componentInstance.renderedValue;\n }\n\n if (componentInstance.isMounted && newRenderedValue === componentInstance.renderedValue) {\n return componentInstance.$element;\n }\n\n componentInstance.renderedValue = newRenderedValue;\n\n const newChild = buildChildElement(newRenderedValue);\n componentInstance.$element = buildComponentElement(componentInstance, [newChild]);\n\n return componentInstance.$element;\n}\n\nexport function hasElementChanged($old: VirtualElement, $new: VirtualElement) {\n if (typeof $old !== typeof $new) {\n return true;\n } else if ($old.type !== $new.type) {\n return true;\n } else if (isTextElement($old) && isTextElement($new)) {\n return $old.value !== $new.value;\n } else if (isTagElement($old) && isTagElement($new)) {\n return ($old.tag !== $new.tag) || ($old.props.key !== $new.props.key);\n } else if (isComponentElement($old) && isComponentElement($new)) {\n return (\n $old.componentInstance.Component !== $new.componentInstance.Component\n ) || (\n $old.props.key !== $new.props.key\n );\n }\n\n return false;\n}\n\nexport function unmountTree($element: VirtualElement) {\n if (!isRealElement($element)) {\n return;\n }\n\n if (isComponentElement($element)) {\n unmountComponent($element.componentInstance);\n } else if ($element.target) {\n removeAllDelegatedListeners($element.target as HTMLElement);\n // Trying to help GC\n // eslint-disable-next-line no-null/no-null\n $element.target = null as any;\n }\n\n $element.children.forEach(unmountTree);\n}\n\nexport function mountComponent(componentInstance: ComponentInstance) {\n renderComponent(componentInstance);\n componentInstance.isMounted = true;\n return componentInstance.$element;\n}\n\nfunction unmountComponent(componentInstance: ComponentInstance) {\n if (!componentInstance.isMounted) {\n return;\n }\n\n componentInstance.hooks.memos.byCursor.forEach((hook) => {\n // eslint-disable-next-line no-null/no-null\n hook.current = null;\n });\n\n componentInstance.hooks.effects.byCursor.forEach(({ cleanup }) => {\n if (typeof cleanup === 'function') {\n try {\n cleanup();\n } catch (err) {\n handleError(err);\n }\n }\n });\n\n componentInstance.isMounted = false;\n\n helpGc(componentInstance);\n}\n\n// We need to remove all references to DOM objects. We also clean all other references, just in case.\nfunction helpGc(componentInstance: ComponentInstance) {\n /* eslint-disable no-null/no-null */\n\n componentInstance.hooks.effects.byCursor.forEach((hook) => {\n hook.cleanup = null as any;\n hook.effect = null as any;\n hook.dependencies = null as any;\n });\n\n componentInstance.hooks.state.byCursor.forEach((hook) => {\n hook.value = null as any;\n hook.nextValue = null as any;\n hook.setter = null as any;\n });\n\n componentInstance.hooks.memos.byCursor.forEach((hook) => {\n hook.dependencies = null as any;\n });\n\n componentInstance.hooks = null as any;\n componentInstance.$element = null as any;\n componentInstance.renderedValue = null as any;\n componentInstance.Component = null as any;\n componentInstance.props = null as any;\n componentInstance.forceUpdate = null as any;\n componentInstance.onUpdate = null as any;\n\n /* eslint-enable no-null/no-null */\n}\n\nfunction prepareComponentForFrame(componentInstance: ComponentInstance) {\n if (!componentInstance.isMounted) {\n return;\n }\n\n componentInstance.hooks.state.byCursor.forEach((hook) => {\n hook.value = hook.nextValue;\n });\n\n componentInstance.prepareForFrame = throttleWithPrimaryRaf(() => prepareComponentForFrame(componentInstance));\n componentInstance.forceUpdate = throttleWithRaf(() => forceUpdateComponent(componentInstance));\n}\n\nfunction forceUpdateComponent(componentInstance: ComponentInstance) {\n if (!componentInstance.isMounted || !componentInstance.onUpdate) {\n return;\n }\n\n const currentElement = componentInstance.$element;\n\n renderComponent(componentInstance);\n\n if (componentInstance.$element !== currentElement) {\n componentInstance.onUpdate();\n }\n}\n\nexport function getTarget($element: VirtualElement): Node | undefined {\n if (isComponentElement($element)) {\n return getTarget($element.children[0]);\n } else {\n return $element.target;\n }\n}\n\nexport function setTarget($element: VirtualElement, target: Node) {\n if (isComponentElement($element)) {\n setTarget($element.children[0], target);\n } else {\n $element.target = target;\n }\n}\n\nexport function useState(initial?: T): [T, StateHookSetter] {\n const { cursor, byCursor } = renderingInstance.hooks.state;\n\n if (byCursor[cursor] === undefined) {\n byCursor[cursor] = {\n value: initial,\n nextValue: initial,\n setter: ((componentInstance) => (newValue: ((current: T) => T) | T) => {\n if (byCursor[cursor].nextValue !== newValue) {\n byCursor[cursor].nextValue = typeof newValue === 'function'\n ? (newValue as (current: T) => T)(byCursor[cursor].value)\n : newValue;\n\n if (!componentInstance.prepareForFrame || !componentInstance.forceUpdate) {\n componentInstance.prepareForFrame = throttleWithPrimaryRaf(\n () => prepareComponentForFrame(componentInstance),\n );\n componentInstance.forceUpdate = throttleWithRaf(\n () => forceUpdateComponent(componentInstance),\n );\n }\n\n componentInstance.prepareForFrame();\n componentInstance.forceUpdate();\n\n if (DEBUG_MORE) {\n if (componentInstance.name !== 'TeactNContainer') {\n // eslint-disable-next-line no-console\n console.log(\n '[Teact.useState]',\n componentInstance.name,\n // `componentInstance.Component` may be set to `null` by GC helper\n componentInstance.Component && (componentInstance.Component as FC_withDebug).DEBUG_contentComponentName\n ? `> ${(componentInstance.Component as FC_withDebug).DEBUG_contentComponentName}`\n : '',\n `Forced update at cursor #${cursor}, next value: `,\n byCursor[cursor].nextValue,\n );\n }\n }\n }\n })(renderingInstance),\n };\n }\n\n renderingInstance.hooks.state.cursor++;\n\n return [\n byCursor[cursor].value,\n byCursor[cursor].setter,\n ];\n}\n\nfunction useLayoutEffectBase(\n schedulerFn: typeof onTickEnd | typeof requestAnimationFrame,\n primarySchedulerFn: typeof onTickEnd | typeof requestAnimationFrame,\n effect: () => Function | void,\n dependencies?: any[],\n debugKey?: string,\n) {\n const { cursor, byCursor } = renderingInstance.hooks.effects;\n const componentInstance = renderingInstance;\n\n function execCleanup() {\n if (!componentInstance.isMounted) {\n return;\n }\n\n const { cleanup } = byCursor[cursor];\n if (typeof cleanup === 'function') {\n try {\n cleanup();\n } catch (err) {\n handleError(err);\n }\n }\n }\n\n function exec() {\n if (!componentInstance.isMounted) {\n return;\n }\n\n byCursor[cursor].cleanup = effect() as Function;\n }\n\n if (byCursor[cursor] !== undefined && dependencies && byCursor[cursor].dependencies) {\n if (dependencies.some((dependency, i) => dependency !== byCursor[cursor].dependencies![i])) {\n if (debugKey) {\n const causedBy = dependencies.reduce((res, newValue, i) => {\n const prevValue = byCursor[cursor].dependencies![i];\n if (newValue !== prevValue) {\n res.push(`${i}: ${prevValue} => ${newValue}`);\n }\n\n return res;\n }, []);\n\n // eslint-disable-next-line no-console\n console.log(\n '[Teact]',\n debugKey,\n 'Effect caused by dependencies.',\n causedBy.join(', '),\n );\n }\n\n primarySchedulerFn(execCleanup);\n schedulerFn(exec);\n }\n } else {\n primarySchedulerFn(execCleanup);\n schedulerFn(exec);\n }\n\n byCursor[cursor] = {\n effect,\n dependencies,\n cleanup: byCursor[cursor] ? byCursor[cursor].cleanup : undefined,\n };\n\n renderingInstance.hooks.effects.cursor++;\n}\n\nexport function useEffect(effect: () => Function | void, dependencies?: any[], debugKey?: string) {\n return useLayoutEffectBase(fastRaf, fastRafPrimary, effect, dependencies, debugKey);\n}\n\nexport function useLayoutEffect(effect: () => Function | void, dependencies?: any[], debugKey?: string) {\n return useLayoutEffectBase(onTickEnd, onTickEndPrimary, effect, dependencies, debugKey);\n}\n\nexport function useMemo(resolver: () => T, dependencies: any[], debugKey?: string): T {\n const { cursor, byCursor } = renderingInstance.hooks.memos;\n let { current } = byCursor[cursor] || {};\n\n if (\n byCursor[cursor] === undefined\n || dependencies.some((dependency, i) => dependency !== byCursor[cursor].dependencies[i])\n ) {\n if (DEBUG && debugKey) {\n // eslint-disable-next-line no-console\n console.log(\n `[Teact.useMemo] ${renderingInstance.name} (${debugKey}): Update is caused by:`,\n byCursor[cursor]\n ? getUnequalProps(dependencies, byCursor[cursor].dependencies).join(', ')\n : '[first render]',\n );\n }\n\n current = resolver();\n }\n\n byCursor[cursor] = {\n current,\n dependencies,\n };\n\n renderingInstance.hooks.memos.cursor++;\n\n return current;\n}\n\nexport function useCallback(newCallback: F, dependencies: any[]): F {\n // eslint-disable-next-line react-hooks/exhaustive-deps\n return useMemo(() => newCallback, dependencies);\n}\n\nexport function useRef(initial: T): { current: T };\nexport function useRef(): { current: T | undefined }; // TT way (empty is `undefined`)\nexport function useRef(initial: null): { current: T | null }; // React way (empty is `null`)\n// eslint-disable-next-line no-null/no-null\nexport function useRef(initial?: T | null) {\n return useMemo(() => ({\n current: initial,\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }), []);\n}\n\nexport function memo(Component: T, areEqual = arePropsShallowEqual, debugKey?: string) {\n return function TeactMemoWrapper(props: Props) {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n const propsRef = useRef(props);\n const renderedRef = useRef();\n\n if (!renderedRef.current || (propsRef.current && !areEqual(propsRef.current, props))) {\n if (DEBUG && debugKey) {\n // eslint-disable-next-line no-console\n console.log(\n `[Teact.memo] ${Component.name} (${debugKey}): Update is caused by:`,\n getUnequalProps(propsRef.current!, props).join(', '),\n );\n }\n\n propsRef.current = props;\n renderedRef.current = createElement(Component, props) as VirtualElementComponent;\n }\n\n return renderedRef.current;\n } as T;\n}\n\n// We need to keep it here for JSX.\nexport default {\n createElement,\n Fragment,\n};\n","import React, {\n FC, FC_withDebug, Props, useEffect, useState,\n} from './teact';\n\nimport { DEBUG, DEBUG_MORE } from '../../config';\nimport useForceUpdate from '../../hooks/useForceUpdate';\nimport generateIdFor from '../../util/generateIdFor';\nimport { throttleWithRaf } from '../../util/schedulers';\nimport arePropsShallowEqual, { getUnequalProps } from '../../util/arePropsShallowEqual';\nimport { orderBy } from '../../util/iteratees';\nimport { GlobalState, GlobalActions, ActionTypes } from '../../global/types';\nimport { handleError } from '../../util/handleError';\n\nexport default React;\n\ntype ActionPayload = AnyLiteral;\n\ntype Reducer = (\n global: GlobalState,\n actions: GlobalActions,\n payload: any,\n) => GlobalState | void;\n\ntype MapStateToProps = ((global: GlobalState, ownProps: OwnProps) => AnyLiteral | null);\ntype MapActionsToProps = ((setGlobal: Function, actions: GlobalActions) => Partial | null);\n\nlet currentGlobal = {} as GlobalState;\n\nconst reducers: Record = {};\nconst callbacks: Function[] = [updateContainers];\nconst actions = {} as GlobalActions;\nconst containers = new Map;\n mapReducersToProps: MapActionsToProps;\n ownProps: Props;\n mappedProps?: Props;\n forceUpdate: Function;\n areMappedPropsChanged: boolean;\n DEBUG_updates: number;\n DEBUG_componentName: string;\n}>();\n\nfunction runCallbacks() {\n callbacks.forEach((cb) => cb(currentGlobal));\n}\n\nconst runCallbacksThrottled = throttleWithRaf(runCallbacks);\n\n// `noThrottle = true` is used as a workaround for iOS gesture history navigation\nexport function setGlobal(newGlobal?: GlobalState, noThrottle = false) {\n if (typeof newGlobal === 'object' && newGlobal !== currentGlobal) {\n currentGlobal = newGlobal;\n if (!noThrottle) {\n runCallbacksThrottled();\n } else {\n runCallbacks();\n }\n }\n}\n\nexport function getGlobal() {\n return currentGlobal;\n}\n\nexport function getDispatch() {\n return actions;\n}\n\nfunction onDispatch(name: string, payload?: ActionPayload, noThrottle?: boolean) {\n if (reducers[name]) {\n reducers[name].forEach((reducer) => {\n const newGlobal = reducer(currentGlobal, actions, payload);\n if (newGlobal) {\n setGlobal(newGlobal, noThrottle);\n }\n });\n }\n}\n\nfunction updateContainers() {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n let DEBUG_startAt: number | undefined;\n if (DEBUG) {\n DEBUG_startAt = performance.now();\n }\n\n // eslint-disable-next-line no-restricted-syntax\n for (const container of containers.values()) {\n const {\n mapStateToProps, mapReducersToProps, ownProps, mappedProps, forceUpdate,\n } = container;\n\n let newMappedProps;\n\n try {\n newMappedProps = {\n ...mapStateToProps(currentGlobal, ownProps),\n ...mapReducersToProps(setGlobal, actions),\n };\n } catch (err) {\n handleError(err);\n\n return;\n }\n\n if (DEBUG) {\n if (Object.values(newMappedProps).some(Number.isNaN)) {\n // eslint-disable-next-line no-console\n console.warn(\n // eslint-disable-next-line max-len\n `[TeactN] Some of \\`${container.DEBUG_componentName}\\` mappers contain NaN values. This may cause redundant updates because of incorrect equality check.`,\n );\n }\n }\n\n if (Object.keys(newMappedProps).length && !arePropsShallowEqual(mappedProps!, newMappedProps)) {\n if (DEBUG_MORE) {\n // eslint-disable-next-line no-console\n console.log(\n '[TeactN] Will update',\n container.DEBUG_componentName,\n 'caused by',\n getUnequalProps(mappedProps!, newMappedProps).join(', '),\n );\n }\n\n container.mappedProps = newMappedProps;\n container.areMappedPropsChanged = true;\n container.DEBUG_updates++;\n\n forceUpdate();\n }\n }\n\n if (DEBUG) {\n const updateTime = performance.now() - DEBUG_startAt!;\n if (updateTime > 7) {\n // eslint-disable-next-line no-console\n console.warn(`[TeactN] Slow containers update: ${Math.round(updateTime)} ms`);\n }\n }\n}\n\nexport function addReducer(name: ActionTypes, reducer: Reducer) {\n if (!reducers[name]) {\n reducers[name] = [];\n\n actions[name] = (payload?: ActionPayload, noThrottle = false) => {\n onDispatch(name, payload, noThrottle);\n };\n }\n\n reducers[name].push(reducer);\n}\n\nexport function addCallback(cb: Function) {\n callbacks.push(cb);\n}\n\nexport function removeCallback(cb: Function) {\n const index = callbacks.indexOf(cb);\n if (index !== -1) {\n callbacks.splice(index, 1);\n }\n}\n\nexport function withGlobal(\n mapStateToProps: MapStateToProps = () => ({}),\n mapReducersToProps: MapActionsToProps = () => ({}),\n) {\n return (Component: FC) => {\n return function TeactNContainer(props: OwnProps) {\n (TeactNContainer as FC_withDebug).DEBUG_contentComponentName = Component.name;\n\n const [id] = useState(generateIdFor(containers));\n const forceUpdate = useForceUpdate();\n\n useEffect(() => {\n return () => {\n containers.delete(id);\n };\n }, [id]);\n\n let container = containers.get(id);\n if (!container) {\n container = {\n mapStateToProps,\n mapReducersToProps,\n ownProps: props,\n areMappedPropsChanged: false,\n forceUpdate,\n DEBUG_updates: 0,\n DEBUG_componentName: Component.name,\n };\n\n containers.set(id, container);\n }\n\n if (container.areMappedPropsChanged) {\n container.areMappedPropsChanged = false;\n }\n\n if (!container.mappedProps || !arePropsShallowEqual(container.ownProps, props)) {\n container.ownProps = props;\n\n try {\n container.mappedProps = {\n ...mapStateToProps(currentGlobal, props),\n ...mapReducersToProps(setGlobal, actions),\n };\n } catch (err) {\n handleError(err);\n }\n }\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return ;\n };\n };\n}\n\nif (DEBUG) {\n (window as any).getGlobal = getGlobal;\n\n document.addEventListener('dblclick', () => {\n // eslint-disable-next-line no-console\n console.log(\n 'GLOBAL CONTAINERS',\n orderBy(\n Array.from(containers.values())\n .map(({ DEBUG_componentName, DEBUG_updates }) => ({ DEBUG_componentName, DEBUG_updates })),\n 'DEBUG_updates',\n 'desc',\n ),\n );\n });\n}\n","// Copyright Twitter Inc. Licensed under MIT\n// https://github.com/twitter/twemoji-parser/blob/master/LICENSE.md\n// Version 2c193ce 28.05.2021\n\nconst vs16RegExp = /\\uFE0F/g;\n// avoid using a string literal like '\\u200D' here because minifiers expand it inline\nconst zeroWidthJoiner = String.fromCharCode(0x200d);\n\nexport function removeVS16s(rawEmoji) {\n return rawEmoji.indexOf(zeroWidthJoiner) < 0 ? rawEmoji.replace(vs16RegExp, '') : rawEmoji;\n}\n\n// This file is generated by source/emoji/scripts/generate.sh\n// eslint-disable-next-line max-len\nexport default /(?:\\ud83d\\udc68\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83e\\uddd1\\ud83c[\\udffc-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83e\\uddd1\\ud83c[\\udffb\\udffd-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83e\\uddd1\\ud83c[\\udffb\\udffc\\udffe\\udfff]|\\ud83e\\uddd1\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udffd\\udfff]|\\ud83e\\uddd1\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udffe]|\\ud83d\\udc68\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffb\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffc-\\udfff]|\\ud83d\\udc68\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffc\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb\\udffd-\\udfff]|\\ud83d\\udc68\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffd\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb\\udffc\\udffe\\udfff]|\\ud83d\\udc68\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udffe\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udffd\\udfff]|\\ud83d\\udc68\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\ud83c\\udfff\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udffe]|\\ud83d\\udc69\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffb\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffc-\\udfff]|\\ud83d\\udc69\\ud83c\\udffb\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc69\\ud83c[\\udffc-\\udfff]|\\ud83d\\udc69\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffc\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb\\udffd-\\udfff]|\\ud83d\\udc69\\ud83c\\udffc\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc69\\ud83c[\\udffb\\udffd-\\udfff]|\\ud83d\\udc69\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffd\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb\\udffc\\udffe\\udfff]|\\ud83d\\udc69\\ud83c\\udffd\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc69\\ud83c[\\udffb\\udffc\\udffe\\udfff]|\\ud83d\\udc69\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udffe\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udffd\\udfff]|\\ud83d\\udc69\\ud83c\\udffe\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udffd\\udfff]|\\ud83d\\udc69\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc69\\ud83c\\udfff\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc68\\ud83c[\\udffb-\\udffe]|\\ud83d\\udc69\\ud83c\\udfff\\u200d\\ud83e\\udd1d\\u200d\\ud83d\\udc69\\ud83c[\\udffb-\\udffe]|\\ud83e\\uddd1\\ud83c\\udffb\\u200d\\u2764\\ufe0f\\u200d\\ud83e\\uddd1\\ud83c[\\udffc-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffb\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffc\\u200d\\u2764\\ufe0f\\u200d\\ud83e\\uddd1\\ud83c[\\udffb\\udffd-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffc\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffd\\u200d\\u2764\\ufe0f\\u200d\\ud83e\\uddd1\\ud83c[\\udffb\\udffc\\udffe\\udfff]|\\ud83e\\uddd1\\ud83c\\udffd\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\ud83c\\udffe\\u200d\\u2764\\ufe0f\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udffd\\udfff]|\\ud83e\\uddd1\\ud83c\\udffe\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83e\\uddd1\\ud83c\\udfff\\u200d\\u2764\\ufe0f\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udffe]|\\ud83e\\uddd1\\ud83c\\udfff\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc68\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d\\udc68|\\ud83d\\udc69\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc8b\\u200d\\ud83d[\\udc68\\udc69]|\\ud83d\\udc68\\u200d\\u2764\\ufe0f\\u200d\\ud83d\\udc68|\\ud83d\\udc69\\u200d\\u2764\\ufe0f\\u200d\\ud83d[\\udc68\\udc69]|\\ud83e\\uddd1\\u200d\\ud83e\\udd1d\\u200d\\ud83e\\uddd1|\\ud83d\\udc6b\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc6c\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc6d\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc8f\\ud83c[\\udffb-\\udfff]|\\ud83d\\udc91\\ud83c[\\udffb-\\udfff]|\\ud83d[\\udc6b-\\udc6d\\udc8f\\udc91])|(?:\\ud83d[\\udc68\\udc69]|\\ud83e\\uddd1)(?:\\ud83c[\\udffb-\\udfff])?\\u200d(?:\\u2695\\ufe0f|\\u2696\\ufe0f|\\u2708\\ufe0f|\\ud83c[\\udf3e\\udf73\\udf7c\\udf84\\udf93\\udfa4\\udfa8\\udfeb\\udfed]|\\ud83d[\\udcbb\\udcbc\\udd27\\udd2c\\ude80\\ude92]|\\ud83e[\\uddaf-\\uddb3\\uddbc\\uddbd])|(?:\\ud83c[\\udfcb\\udfcc]|\\ud83d[\\udd74\\udd75]|\\u26f9)((?:\\ud83c[\\udffb-\\udfff]|\\ufe0f)\\u200d[\\u2640\\u2642]\\ufe0f)|(?:\\ud83c[\\udfc3\\udfc4\\udfca]|\\ud83d[\\udc6e\\udc70\\udc71\\udc73\\udc77\\udc81\\udc82\\udc86\\udc87\\ude45-\\ude47\\ude4b\\ude4d\\ude4e\\udea3\\udeb4-\\udeb6]|\\ud83e[\\udd26\\udd35\\udd37-\\udd39\\udd3d\\udd3e\\uddb8\\uddb9\\uddcd-\\uddcf\\uddd4\\uddd6-\\udddd])(?:\\ud83c[\\udffb-\\udfff])?\\u200d[\\u2640\\u2642]\\ufe0f|(?:\\ud83d\\udc68\\u200d\\ud83d\\udc68\\u200d\\ud83d\\udc66\\u200d\\ud83d\\udc66|\\ud83d\\udc68\\u200d\\ud83d\\udc68\\u200d\\ud83d\\udc67\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc68\\u200d\\ud83d\\udc69\\u200d\\ud83d\\udc66\\u200d\\ud83d\\udc66|\\ud83d\\udc68\\u200d\\ud83d\\udc69\\u200d\\ud83d\\udc67\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc69\\u200d\\ud83d\\udc69\\u200d\\ud83d\\udc66\\u200d\\ud83d\\udc66|\\ud83d\\udc69\\u200d\\ud83d\\udc69\\u200d\\ud83d\\udc67\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc68\\u200d\\ud83d\\udc66\\u200d\\ud83d\\udc66|\\ud83d\\udc68\\u200d\\ud83d\\udc67\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc68\\u200d\\ud83d\\udc68\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc68\\u200d\\ud83d\\udc69\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc69\\u200d\\ud83d\\udc66\\u200d\\ud83d\\udc66|\\ud83d\\udc69\\u200d\\ud83d\\udc67\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc69\\u200d\\ud83d\\udc69\\u200d\\ud83d[\\udc66\\udc67]|\\ud83c\\udff3\\ufe0f\\u200d\\u26a7\\ufe0f|\\ud83c\\udff3\\ufe0f\\u200d\\ud83c\\udf08|\\ud83d\\ude36\\u200d\\ud83c\\udf2b\\ufe0f|\\u2764\\ufe0f\\u200d\\ud83d\\udd25|\\u2764\\ufe0f\\u200d\\ud83e\\ude79|\\ud83c\\udff4\\u200d\\u2620\\ufe0f|\\ud83d\\udc15\\u200d\\ud83e\\uddba|\\ud83d\\udc3b\\u200d\\u2744\\ufe0f|\\ud83d\\udc41\\u200d\\ud83d\\udde8|\\ud83d\\udc68\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc69\\u200d\\ud83d[\\udc66\\udc67]|\\ud83d\\udc6f\\u200d\\u2640\\ufe0f|\\ud83d\\udc6f\\u200d\\u2642\\ufe0f|\\ud83d\\ude2e\\u200d\\ud83d\\udca8|\\ud83d\\ude35\\u200d\\ud83d\\udcab|\\ud83e\\udd3c\\u200d\\u2640\\ufe0f|\\ud83e\\udd3c\\u200d\\u2642\\ufe0f|\\ud83e\\uddde\\u200d\\u2640\\ufe0f|\\ud83e\\uddde\\u200d\\u2642\\ufe0f|\\ud83e\\udddf\\u200d\\u2640\\ufe0f|\\ud83e\\udddf\\u200d\\u2642\\ufe0f|\\ud83d\\udc08\\u200d\\u2b1b)|[#*0-9]\\ufe0f?\\u20e3|(?:[©®\\u2122\\u265f]\\ufe0f)|(?:\\ud83c[\\udc04\\udd70\\udd71\\udd7e\\udd7f\\ude02\\ude1a\\ude2f\\ude37\\udf21\\udf24-\\udf2c\\udf36\\udf7d\\udf96\\udf97\\udf99-\\udf9b\\udf9e\\udf9f\\udfcd\\udfce\\udfd4-\\udfdf\\udff3\\udff5\\udff7]|\\ud83d[\\udc3f\\udc41\\udcfd\\udd49\\udd4a\\udd6f\\udd70\\udd73\\udd76-\\udd79\\udd87\\udd8a-\\udd8d\\udda5\\udda8\\uddb1\\uddb2\\uddbc\\uddc2-\\uddc4\\uddd1-\\uddd3\\udddc-\\uddde\\udde1\\udde3\\udde8\\uddef\\uddf3\\uddfa\\udecb\\udecd-\\udecf\\udee0-\\udee5\\udee9\\udef0\\udef3]|[\\u203c\\u2049\\u2139\\u2194-\\u2199\\u21a9\\u21aa\\u231a\\u231b\\u2328\\u23cf\\u23ed-\\u23ef\\u23f1\\u23f2\\u23f8-\\u23fa\\u24c2\\u25aa\\u25ab\\u25b6\\u25c0\\u25fb-\\u25fe\\u2600-\\u2604\\u260e\\u2611\\u2614\\u2615\\u2618\\u2620\\u2622\\u2623\\u2626\\u262a\\u262e\\u262f\\u2638-\\u263a\\u2640\\u2642\\u2648-\\u2653\\u2660\\u2663\\u2665\\u2666\\u2668\\u267b\\u267f\\u2692-\\u2697\\u2699\\u269b\\u269c\\u26a0\\u26a1\\u26a7\\u26aa\\u26ab\\u26b0\\u26b1\\u26bd\\u26be\\u26c4\\u26c5\\u26c8\\u26cf\\u26d1\\u26d3\\u26d4\\u26e9\\u26ea\\u26f0-\\u26f5\\u26f8\\u26fa\\u26fd\\u2702\\u2708\\u2709\\u270f\\u2712\\u2714\\u2716\\u271d\\u2721\\u2733\\u2734\\u2744\\u2747\\u2757\\u2763\\u2764\\u27a1\\u2934\\u2935\\u2b05-\\u2b07\\u2b1b\\u2b1c\\u2b50\\u2b55\\u3030\\u303d\\u3297\\u3299])(?:\\ufe0f|(?!\\ufe0e))|(?:(?:\\ud83c[\\udfcb\\udfcc]|\\ud83d[\\udd74\\udd75\\udd90]|[\\u261d\\u26f7\\u26f9\\u270c\\u270d])(?:\\ufe0f|(?!\\ufe0e))|(?:\\ud83c[\\udf85\\udfc2-\\udfc4\\udfc7\\udfca]|\\ud83d[\\udc42\\udc43\\udc46-\\udc50\\udc66-\\udc69\\udc6e\\udc70-\\udc78\\udc7c\\udc81-\\udc83\\udc85-\\udc87\\udcaa\\udd7a\\udd95\\udd96\\ude45-\\ude47\\ude4b-\\ude4f\\udea3\\udeb4-\\udeb6\\udec0\\udecc]|\\ud83e[\\udd0c\\udd0f\\udd18-\\udd1c\\udd1e\\udd1f\\udd26\\udd30-\\udd39\\udd3d\\udd3e\\udd77\\uddb5\\uddb6\\uddb8\\uddb9\\uddbb\\uddcd-\\uddcf\\uddd1-\\udddd]|[\\u270a\\u270b]))(?:\\ud83c[\\udffb-\\udfff])?|(?:\\ud83c\\udff4\\udb40\\udc67\\udb40\\udc62\\udb40\\udc65\\udb40\\udc6e\\udb40\\udc67\\udb40\\udc7f|\\ud83c\\udff4\\udb40\\udc67\\udb40\\udc62\\udb40\\udc73\\udb40\\udc63\\udb40\\udc74\\udb40\\udc7f|\\ud83c\\udff4\\udb40\\udc67\\udb40\\udc62\\udb40\\udc77\\udb40\\udc6c\\udb40\\udc73\\udb40\\udc7f|\\ud83c\\udde6\\ud83c[\\udde8-\\uddec\\uddee\\uddf1\\uddf2\\uddf4\\uddf6-\\uddfa\\uddfc\\uddfd\\uddff]|\\ud83c\\udde7\\ud83c[\\udde6\\udde7\\udde9-\\uddef\\uddf1-\\uddf4\\uddf6-\\uddf9\\uddfb\\uddfc\\uddfe\\uddff]|\\ud83c\\udde8\\ud83c[\\udde6\\udde8\\udde9\\uddeb-\\uddee\\uddf0-\\uddf5\\uddf7\\uddfa-\\uddff]|\\ud83c\\udde9\\ud83c[\\uddea\\uddec\\uddef\\uddf0\\uddf2\\uddf4\\uddff]|\\ud83c\\uddea\\ud83c[\\udde6\\udde8\\uddea\\uddec\\udded\\uddf7-\\uddfa]|\\ud83c\\uddeb\\ud83c[\\uddee-\\uddf0\\uddf2\\uddf4\\uddf7]|\\ud83c\\uddec\\ud83c[\\udde6\\udde7\\udde9-\\uddee\\uddf1-\\uddf3\\uddf5-\\uddfa\\uddfc\\uddfe]|\\ud83c\\udded\\ud83c[\\uddf0\\uddf2\\uddf3\\uddf7\\uddf9\\uddfa]|\\ud83c\\uddee\\ud83c[\\udde8-\\uddea\\uddf1-\\uddf4\\uddf6-\\uddf9]|\\ud83c\\uddef\\ud83c[\\uddea\\uddf2\\uddf4\\uddf5]|\\ud83c\\uddf0\\ud83c[\\uddea\\uddec-\\uddee\\uddf2\\uddf3\\uddf5\\uddf7\\uddfc\\uddfe\\uddff]|\\ud83c\\uddf1\\ud83c[\\udde6-\\udde8\\uddee\\uddf0\\uddf7-\\uddfb\\uddfe]|\\ud83c\\uddf2\\ud83c[\\udde6\\udde8-\\udded\\uddf0-\\uddff]|\\ud83c\\uddf3\\ud83c[\\udde6\\udde8\\uddea-\\uddec\\uddee\\uddf1\\uddf4\\uddf5\\uddf7\\uddfa\\uddff]|\\ud83c\\uddf4\\ud83c\\uddf2|\\ud83c\\uddf5\\ud83c[\\udde6\\uddea-\\udded\\uddf0-\\uddf3\\uddf7-\\uddf9\\uddfc\\uddfe]|\\ud83c\\uddf6\\ud83c\\udde6|\\ud83c\\uddf7\\ud83c[\\uddea\\uddf4\\uddf8\\uddfa\\uddfc]|\\ud83c\\uddf8\\ud83c[\\udde6-\\uddea\\uddec-\\uddf4\\uddf7-\\uddf9\\uddfb\\uddfd-\\uddff]|\\ud83c\\uddf9\\ud83c[\\udde6\\udde8\\udde9\\uddeb-\\udded\\uddef-\\uddf4\\uddf7\\uddf9\\uddfb\\uddfc\\uddff]|\\ud83c\\uddfa\\ud83c[\\udde6\\uddec\\uddf2\\uddf3\\uddf8\\uddfe\\uddff]|\\ud83c\\uddfb\\ud83c[\\udde6\\udde8\\uddea\\uddec\\uddee\\uddf3\\uddfa]|\\ud83c\\uddfc\\ud83c[\\uddeb\\uddf8]|\\ud83c\\uddfd\\ud83c\\uddf0|\\ud83c\\uddfe\\ud83c[\\uddea\\uddf9]|\\ud83c\\uddff\\ud83c[\\udde6\\uddf2\\uddfc]|\\ud83c[\\udccf\\udd8e\\udd91-\\udd9a\\udde6-\\uddff\\ude01\\ude32-\\ude36\\ude38-\\ude3a\\ude50\\ude51\\udf00-\\udf20\\udf2d-\\udf35\\udf37-\\udf7c\\udf7e-\\udf84\\udf86-\\udf93\\udfa0-\\udfc1\\udfc5\\udfc6\\udfc8\\udfc9\\udfcf-\\udfd3\\udfe0-\\udff0\\udff4\\udff8-\\udfff]|\\ud83d[\\udc00-\\udc3e\\udc40\\udc44\\udc45\\udc51-\\udc65\\udc6a\\udc6f\\udc79-\\udc7b\\udc7d-\\udc80\\udc84\\udc88-\\udc8e\\udc90\\udc92-\\udca9\\udcab-\\udcfc\\udcff-\\udd3d\\udd4b-\\udd4e\\udd50-\\udd67\\udda4\\uddfb-\\ude44\\ude48-\\ude4a\\ude80-\\udea2\\udea4-\\udeb3\\udeb7-\\udebf\\udec1-\\udec5\\uded0-\\uded2\\uded5-\\uded7\\udeeb\\udeec\\udef4-\\udefc\\udfe0-\\udfeb]|\\ud83e[\\udd0d\\udd0e\\udd10-\\udd17\\udd1d\\udd20-\\udd25\\udd27-\\udd2f\\udd3a\\udd3c\\udd3f-\\udd45\\udd47-\\udd76\\udd78\\udd7a-\\uddb4\\uddb7\\uddba\\uddbc-\\uddcb\\uddd0\\uddde-\\uddff\\ude70-\\ude74\\ude78-\\ude7a\\ude80-\\ude86\\ude90-\\udea8\\udeb0-\\udeb6\\udec0-\\udec2\\uded0-\\uded6]|[\\u23e9-\\u23ec\\u23f0\\u23f3\\u267e\\u26ce\\u2705\\u2728\\u274c\\u274e\\u2753-\\u2755\\u2795-\\u2797\\u27b0\\u27bf\\ue50a])|\\ufe0f/g;\n","import {\n addReducer, getDispatch, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { initApi, callApi } from '../../../api/gramjs';\nimport { GlobalState } from '../../../global/types';\n\nimport {\n LANG_CACHE_NAME,\n CUSTOM_BG_CACHE_NAME,\n MEDIA_CACHE_NAME,\n MEDIA_CACHE_NAME_AVATARS,\n MEDIA_PROGRESSIVE_CACHE_NAME,\n IS_TEST,\n} from '../../../config';\nimport { IS_MOV_SUPPORTED, PLATFORM_ENV } from '../../../util/environment';\nimport { unsubscribe } from '../../../util/notifications';\nimport * as cacheApi from '../../../util/cacheApi';\nimport { updateAppBadge } from '../../../util/appBadge';\nimport {\n storeSession,\n loadStoredSession,\n clearStoredSession,\n importLegacySession,\n clearLegacySessions,\n} from '../../../util/sessions';\nimport { forceWebsync } from '../../../util/websync';\n\naddReducer('initApi', (global: GlobalState, actions) => {\n (async () => {\n if (!IS_TEST) {\n await importLegacySession();\n void clearLegacySessions();\n }\n\n void initApi(actions.apiUpdate, {\n userAgent: navigator.userAgent,\n platform: PLATFORM_ENV,\n sessionData: loadStoredSession(),\n isTest: window.location.search.includes('test'),\n isMovSupported: IS_MOV_SUPPORTED,\n });\n })();\n});\n\naddReducer('setAuthPhoneNumber', (global, actions, payload) => {\n const { phoneNumber } = payload!;\n\n void callApi('provideAuthPhoneNumber', phoneNumber.replace(/[^\\d]/g, ''));\n\n return {\n ...global,\n authIsLoading: true,\n authError: undefined,\n };\n});\n\naddReducer('setAuthCode', (global, actions, payload) => {\n const { code } = payload!;\n\n void callApi('provideAuthCode', code);\n\n return {\n ...global,\n authIsLoading: true,\n authError: undefined,\n };\n});\n\naddReducer('setAuthPassword', (global, actions, payload) => {\n const { password } = payload!;\n\n void callApi('provideAuthPassword', password);\n\n return {\n ...global,\n authIsLoading: true,\n authError: undefined,\n };\n});\n\naddReducer('uploadProfilePhoto', (global, actions, payload) => {\n const { file } = payload!;\n\n void callApi('uploadProfilePhoto', file);\n});\n\naddReducer('signUp', (global, actions, payload) => {\n const { firstName, lastName } = payload!;\n\n void callApi('provideAuthRegistration', { firstName, lastName });\n\n return {\n ...global,\n authIsLoading: true,\n authError: undefined,\n };\n});\n\naddReducer('returnToAuthPhoneNumber', (global) => {\n void callApi('restartAuth');\n\n return {\n ...global,\n authError: undefined,\n };\n});\n\naddReducer('goToAuthQrCode', (global) => {\n void callApi('restartAuthWithQr');\n\n return {\n ...global,\n authIsLoadingQrCode: true,\n authError: undefined,\n };\n});\n\naddReducer('saveSession', (global, actions, payload) => {\n const { sessionData } = payload;\n\n if (sessionData) {\n storeSession(payload.sessionData, global.currentUserId);\n } else {\n clearStoredSession();\n }\n});\n\naddReducer('signOut', () => {\n (async () => {\n try {\n await unsubscribe();\n await callApi('destroy');\n await forceWebsync(false);\n } catch (err) {\n // Do nothing\n }\n\n getDispatch().reset();\n })();\n});\n\naddReducer('reset', () => {\n clearStoredSession();\n\n void cacheApi.clear(MEDIA_CACHE_NAME);\n void cacheApi.clear(MEDIA_CACHE_NAME_AVATARS);\n void cacheApi.clear(MEDIA_PROGRESSIVE_CACHE_NAME);\n void cacheApi.clear(CUSTOM_BG_CACHE_NAME);\n\n const langCachePrefix = LANG_CACHE_NAME.replace(/\\d+$/, '');\n const langCacheVersion = (LANG_CACHE_NAME.match(/\\d+$/) || [0])[0];\n for (let i = 0; i < langCacheVersion; i++) {\n void cacheApi.clear(`${langCachePrefix}${i === 0 ? '' : i}`);\n }\n\n void clearLegacySessions();\n\n updateAppBadge(0);\n\n getDispatch().init();\n});\n\naddReducer('disconnect', () => {\n (async () => {\n await callApi('disconnect');\n })();\n});\n\naddReducer('loadNearestCountry', (global) => {\n if (global.connectionState !== 'connectionStateReady') {\n return;\n }\n\n (async () => {\n const authNearestCountry = await callApi('fetchNearestCountry');\n\n setGlobal({\n ...getGlobal(),\n authNearestCountry,\n });\n })();\n});\n\naddReducer('setDeviceToken', (global, actions, deviceToken) => {\n setGlobal({\n ...global,\n push: {\n deviceToken,\n subscribedAt: Date.now(),\n },\n });\n});\n\naddReducer('deleteDeviceToken', (global) => {\n const newGlobal = { ...global };\n delete newGlobal.push;\n setGlobal(newGlobal);\n});\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\nimport {\n ApiPrivacyKey, PrivacyVisibility, ProfileEditProgress, InputPrivacyRules, InputPrivacyContact,\n UPLOADING_WALLPAPER_SLUG,\n} from '../../../types';\n\nimport { COUNTRIES_WITH_12H_TIME_FORMAT } from '../../../config';\nimport { callApi } from '../../../api/gramjs';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport { subscribe, unsubscribe } from '../../../util/notifications';\nimport { setTimeFormat } from '../../../util/langProvider';\nimport { selectUser } from '../../selectors';\nimport {\n addUsers, addBlockedContact, updateChats, updateUser, removeBlockedContact, replaceSettings, updateNotifySettings,\n addNotifyExceptions,\n} from '../../reducers';\nimport { isUserId } from '../../helpers';\n\naddReducer('updateProfile', (global, actions, payload) => {\n const {\n photo, firstName, lastName, bio: about, username,\n } = payload!;\n\n (async () => {\n const { currentUserId } = global;\n if (!currentUserId) {\n return;\n }\n\n setGlobal({\n ...getGlobal(),\n profileEdit: {\n progress: ProfileEditProgress.InProgress,\n },\n });\n\n if (photo) {\n await callApi('updateProfilePhoto', photo);\n }\n\n if (firstName || lastName || about) {\n const result = await callApi('updateProfile', { firstName, lastName, about });\n if (result) {\n global = getGlobal();\n const currentUser = currentUserId && selectUser(global, currentUserId);\n\n if (currentUser) {\n setGlobal(updateUser(\n global,\n currentUser.id,\n {\n firstName,\n lastName,\n fullInfo: {\n ...currentUser.fullInfo,\n bio: about,\n },\n },\n ));\n }\n }\n }\n\n if (username) {\n const result = await callApi('updateUsername', username);\n if (result && currentUserId) {\n setGlobal(updateUser(getGlobal(), currentUserId, { username }));\n }\n }\n\n setGlobal({\n ...getGlobal(),\n profileEdit: {\n progress: ProfileEditProgress.Complete,\n },\n });\n })();\n});\n\naddReducer('checkUsername', (global, actions, payload) => {\n const { username } = payload!;\n\n (async () => {\n // No need to check the username if profile update is already in progress\n if (global.profileEdit && global.profileEdit.progress === ProfileEditProgress.InProgress) {\n return;\n }\n\n setGlobal({\n ...global,\n profileEdit: {\n progress: global.profileEdit ? global.profileEdit.progress : ProfileEditProgress.Idle,\n isUsernameAvailable: undefined,\n },\n });\n\n const isUsernameAvailable = await callApi('checkUsername', username);\n\n global = getGlobal();\n setGlobal({\n ...global,\n profileEdit: {\n ...global.profileEdit!,\n isUsernameAvailable,\n },\n });\n })();\n});\n\naddReducer('loadWallpapers', () => {\n (async () => {\n const result = await callApi('fetchWallpapers');\n if (!result) {\n return;\n }\n\n const global = getGlobal();\n setGlobal({\n ...global,\n settings: {\n ...global.settings,\n loadedWallpapers: result.wallpapers,\n },\n });\n })();\n});\n\naddReducer('uploadWallpaper', (global, actions, payload) => {\n const file = payload;\n const previewBlobUrl = URL.createObjectURL(file);\n\n setGlobal({\n ...global,\n settings: {\n ...global.settings,\n loadedWallpapers: [\n {\n slug: UPLOADING_WALLPAPER_SLUG,\n document: {\n fileName: '',\n size: file.size,\n mimeType: file.type,\n previewBlobUrl,\n },\n },\n ...(global.settings.loadedWallpapers || []),\n ],\n },\n });\n\n (async () => {\n const result = await callApi('uploadWallpaper', file);\n if (!result) {\n return;\n }\n\n const { wallpaper } = result;\n\n global = getGlobal();\n if (!global.settings.loadedWallpapers) {\n return;\n }\n\n const firstWallpaper = global.settings.loadedWallpapers[0];\n if (!firstWallpaper || firstWallpaper.slug !== UPLOADING_WALLPAPER_SLUG) {\n return;\n }\n\n const withLocalMedia = {\n ...wallpaper,\n document: {\n ...wallpaper.document,\n previewBlobUrl,\n },\n };\n\n setGlobal({\n ...global,\n settings: {\n ...global.settings,\n loadedWallpapers: [\n withLocalMedia,\n ...global.settings.loadedWallpapers.slice(1),\n ],\n },\n });\n })();\n});\n\naddReducer('loadBlockedContacts', () => {\n (async () => {\n const result = await callApi('fetchBlockedContacts');\n\n if (!result) {\n return;\n }\n\n let newGlobal = getGlobal();\n\n if (result.users?.length) {\n newGlobal = addUsers(newGlobal, buildCollectionByKey(result.users, 'id'));\n }\n if (result.chats?.length) {\n newGlobal = updateChats(newGlobal, buildCollectionByKey(result.chats, 'id'));\n }\n\n newGlobal = {\n ...newGlobal,\n blocked: {\n ...newGlobal.blocked,\n ids: [...(newGlobal.blocked.ids || []), ...result.blockedIds],\n totalCount: result.totalCount,\n },\n };\n\n setGlobal(newGlobal);\n })();\n});\n\naddReducer('blockContact', (global, actions, payload) => {\n const { contactId, accessHash } = payload!;\n\n (async () => {\n const result = await callApi('blockContact', contactId, accessHash);\n if (!result) {\n return;\n }\n\n const newGlobal = getGlobal();\n\n setGlobal(addBlockedContact(newGlobal, contactId));\n })();\n});\n\naddReducer('unblockContact', (global, actions, payload) => {\n const { contactId } = payload!;\n let accessHash: string | undefined;\n const isPrivate = isUserId(contactId);\n\n if (isPrivate) {\n const user = selectUser(global, contactId);\n if (!user) {\n return;\n }\n\n accessHash = user.accessHash;\n }\n\n (async () => {\n const result = await callApi('unblockContact', contactId, accessHash);\n if (!result) {\n return;\n }\n\n const newGlobal = getGlobal();\n\n setGlobal(removeBlockedContact(newGlobal, contactId));\n })();\n});\n\naddReducer('loadAuthorizations', () => {\n (async () => {\n const result = await callApi('fetchAuthorizations');\n if (!result) {\n return;\n }\n\n setGlobal({\n ...getGlobal(),\n activeSessions: result,\n });\n })();\n});\n\naddReducer('terminateAuthorization', (global, actions, payload) => {\n const { hash } = payload!;\n\n (async () => {\n const result = await callApi('terminateAuthorization', hash);\n if (!result) {\n return;\n }\n\n const newGlobal = getGlobal();\n\n setGlobal({\n ...newGlobal,\n activeSessions: newGlobal.activeSessions.filter((session) => session.hash !== hash),\n });\n })();\n});\n\naddReducer('terminateAllAuthorizations', () => {\n (async () => {\n const result = await callApi('terminateAllAuthorizations');\n if (!result) {\n return;\n }\n\n const global = getGlobal();\n\n setGlobal({\n ...global,\n activeSessions: global.activeSessions.filter((session) => session.isCurrent),\n });\n })();\n});\n\naddReducer('loadNotificationExceptions', (global) => {\n const { serverTimeOffset } = global;\n\n (async () => {\n const result = await callApi('fetchNotificationExceptions', { serverTimeOffset });\n if (!result) {\n return;\n }\n\n setGlobal(addNotifyExceptions(getGlobal(), result));\n })();\n});\n\naddReducer('loadNotificationSettings', (global) => {\n const { serverTimeOffset } = global;\n (async () => {\n const result = await callApi('fetchNotificationSettings', {\n serverTimeOffset,\n });\n if (!result) {\n return;\n }\n\n setGlobal(replaceSettings(getGlobal(), result));\n })();\n});\n\naddReducer('updateNotificationSettings', (global, actions, payload) => {\n const { peerType, isSilent, shouldShowPreviews } = payload!;\n\n (async () => {\n const result = await callApi('updateNotificationSettings', peerType, { isSilent, shouldShowPreviews });\n\n if (!result) {\n return;\n }\n\n setGlobal(updateNotifySettings(getGlobal(), peerType, isSilent, shouldShowPreviews));\n })();\n});\n\naddReducer('updateWebNotificationSettings', (global, actions, payload) => {\n (async () => {\n setGlobal(replaceSettings(getGlobal(), payload));\n const newGlobal = getGlobal();\n const { hasPushNotifications, hasWebNotifications } = newGlobal.settings.byKey;\n if (hasWebNotifications && hasPushNotifications) {\n await subscribe();\n } else {\n await unsubscribe();\n }\n })();\n});\n\naddReducer('updateContactSignUpNotification', (global, actions, payload) => {\n const { isSilent } = payload!;\n\n (async () => {\n const result = await callApi('updateContactSignUpNotification', isSilent);\n if (!result) {\n return;\n }\n\n setGlobal(replaceSettings(getGlobal(), { hasContactJoinedNotifications: !isSilent }));\n })();\n});\n\naddReducer('loadLanguages', () => {\n (async () => {\n const result = await callApi('fetchLanguages');\n if (!result) {\n return;\n }\n\n setGlobal(replaceSettings(getGlobal(), { languages: result }));\n })();\n});\n\naddReducer('loadPrivacySettings', () => {\n (async () => {\n const [\n phoneNumberSettings, lastSeenSettings, profilePhotoSettings, forwardsSettings, chatInviteSettings,\n ] = await Promise.all([\n callApi('fetchPrivacySettings', 'phoneNumber'),\n callApi('fetchPrivacySettings', 'lastSeen'),\n callApi('fetchPrivacySettings', 'profilePhoto'),\n callApi('fetchPrivacySettings', 'forwards'),\n callApi('fetchPrivacySettings', 'chatInvite'),\n ]);\n\n if (\n !phoneNumberSettings || !lastSeenSettings || !profilePhotoSettings || !forwardsSettings || !chatInviteSettings\n ) {\n return;\n }\n\n const global = getGlobal();\n\n global.settings.privacy.phoneNumber = phoneNumberSettings;\n global.settings.privacy.lastSeen = lastSeenSettings;\n global.settings.privacy.profilePhoto = profilePhotoSettings;\n global.settings.privacy.forwards = forwardsSettings;\n global.settings.privacy.chatInvite = chatInviteSettings;\n\n setGlobal(global);\n })();\n});\n\naddReducer('setPrivacyVisibility', (global, actions, payload) => {\n const { privacyKey, visibility } = payload!;\n\n const {\n privacy: { [privacyKey as ApiPrivacyKey]: settings },\n } = global.settings;\n\n if (!settings) {\n return;\n }\n\n const rules = buildInputPrivacyRules(global, {\n visibility,\n allowedIds: [...settings.allowUserIds, ...settings.allowChatIds],\n deniedIds: [...settings.blockUserIds, ...settings.blockChatIds],\n });\n\n (async () => {\n const result = await callApi('setPrivacySettings', privacyKey, rules);\n\n if (result) {\n const newGlobal = getGlobal();\n\n newGlobal.settings.privacy[privacyKey as ApiPrivacyKey] = result;\n\n setGlobal(newGlobal);\n }\n })();\n});\n\naddReducer('setPrivacySettings', (global, actions, payload) => {\n const { privacyKey, isAllowList, contactsIds } = payload!;\n const {\n privacy: { [privacyKey as ApiPrivacyKey]: settings },\n } = global.settings;\n\n if (!settings) {\n return;\n }\n\n const rules = buildInputPrivacyRules(global, {\n visibility: settings.visibility,\n allowedIds: isAllowList ? contactsIds : [...settings.allowUserIds, ...settings.allowChatIds],\n deniedIds: !isAllowList ? contactsIds : [...settings.blockUserIds, ...settings.blockChatIds],\n });\n\n (async () => {\n const result = await callApi('setPrivacySettings', privacyKey, rules);\n\n if (result) {\n const newGlobal = getGlobal();\n\n newGlobal.settings.privacy[privacyKey as ApiPrivacyKey] = result;\n\n setGlobal(newGlobal);\n }\n })();\n});\n\nfunction buildInputPrivacyRules(global: GlobalState, {\n visibility,\n allowedIds,\n deniedIds,\n}: {\n visibility: PrivacyVisibility;\n allowedIds: string[];\n deniedIds: string[];\n}): InputPrivacyRules {\n const {\n users: { byId: usersById },\n chats: { byId: chatsById },\n } = global;\n\n const rules: InputPrivacyRules = {\n visibility,\n };\n let users: InputPrivacyContact[];\n let chats: InputPrivacyContact[];\n\n const collectUsers = (userId: string) => {\n if (!isUserId(userId)) {\n return undefined;\n }\n const { id, accessHash } = usersById[userId] || {};\n if (!id) {\n return undefined;\n }\n\n return { id, accessHash };\n };\n\n const collectChats = (userId: string) => {\n if (isUserId(userId)) {\n return undefined;\n }\n const chat = chatsById[userId];\n\n return chat ? { id: chat.id } : undefined;\n };\n\n if (visibility === 'contacts' || visibility === 'nobody') {\n users = allowedIds.map(collectUsers).filter(Boolean) as InputPrivacyContact[];\n chats = allowedIds.map(collectChats).filter(Boolean) as InputPrivacyContact[];\n\n if (users.length > 0) {\n rules.allowedUsers = users;\n }\n if (chats.length > 0) {\n rules.allowedChats = chats;\n }\n }\n\n if (visibility === 'everybody' || visibility === 'contacts') {\n users = deniedIds.map(collectUsers).filter(Boolean) as InputPrivacyContact[];\n chats = deniedIds.map(collectChats).filter(Boolean) as InputPrivacyContact[];\n\n if (users.length > 0) {\n rules.blockedUsers = users;\n }\n if (chats.length > 0) {\n rules.blockedChats = chats;\n }\n }\n\n return rules;\n}\n\naddReducer('updateIsOnline', (global, actions, payload) => {\n callApi('updateIsOnline', payload);\n});\n\naddReducer('loadContentSettings', () => {\n (async () => {\n const result = await callApi('fetchContentSettings');\n if (!result) return;\n\n setGlobal(replaceSettings(getGlobal(), result));\n })();\n});\n\naddReducer('updateContentSettings', (global, actions, payload) => {\n (async () => {\n setGlobal(replaceSettings(getGlobal(), { isSensitiveEnabled: payload }));\n\n const result = await callApi('updateContentSettings', payload);\n if (!result) {\n setGlobal(replaceSettings(getGlobal(), { isSensitiveEnabled: !payload }));\n }\n })();\n});\n\naddReducer('loadCountryList', (global, actions, payload = {}) => {\n let { langCode } = payload;\n if (!langCode) langCode = global.settings.byKey.language;\n\n (async () => {\n const countryList = await callApi('fetchCountryList', { langCode });\n if (!countryList) return;\n\n setGlobal({\n ...getGlobal(),\n countryList,\n });\n })();\n});\n\naddReducer('ensureTimeFormat', (global, actions) => {\n if (global.authNearestCountry) {\n const timeFormat = COUNTRIES_WITH_12H_TIME_FORMAT.has(global.authNearestCountry.toUpperCase()) ? '12h' : '24h';\n actions.setSettingOption({ timeFormat });\n setTimeFormat(timeFormat);\n }\n\n (async () => {\n if (getGlobal().settings.byKey.wasTimeFormatSetManually) {\n return;\n }\n\n const nearestCountryCode = await callApi('fetchNearestCountry');\n if (nearestCountryCode) {\n const timeFormat = COUNTRIES_WITH_12H_TIME_FORMAT.has(nearestCountryCode.toUpperCase()) ? '12h' : '24h';\n actions.setSettingOption({ timeFormat });\n setTimeFormat(timeFormat);\n }\n })();\n});\n","import {\n addReducer, getDispatch, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\n\nimport {\n ApiUpdate,\n ApiUpdateAuthorizationState,\n ApiUpdateAuthorizationError,\n ApiUpdateConnectionState,\n ApiUpdateSession,\n ApiUpdateCurrentUser, ApiUpdateServerTimeOffset,\n} from '../../../api/types';\nimport { DEBUG, SESSION_USER_KEY } from '../../../config';\nimport { subscribe } from '../../../util/notifications';\nimport { updateUser } from '../../reducers';\nimport { setLanguage } from '../../../util/langProvider';\nimport { selectNotifySettings } from '../../selectors';\nimport { forceWebsync } from '../../../util/websync';\nimport { getShippingError } from '../../../util/getReadableErrorText';\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n if (DEBUG) {\n if (update['@type'] !== 'updateUserStatus' && update['@type'] !== 'updateServerTimeOffset') {\n // eslint-disable-next-line no-console\n console.log('[GramJs] UPDATE', update['@type'], { update });\n }\n }\n\n switch (update['@type']) {\n case 'updateApiReady':\n onUpdateApiReady(global);\n break;\n\n case 'updateAuthorizationState':\n onUpdateAuthorizationState(update);\n break;\n\n case 'updateAuthorizationError':\n onUpdateAuthorizationError(update);\n break;\n\n case 'updateConnectionState':\n onUpdateConnectionState(update);\n break;\n\n case 'updateSession':\n onUpdateSession(update);\n break;\n\n case 'updateServerTimeOffset':\n onUpdateServerTimeOffset(update);\n break;\n\n case 'updateCurrentUser':\n onUpdateCurrentUser(update);\n break;\n\n case 'error': {\n if (update.error.message === 'SESSION_REVOKED') {\n actions.signOut();\n }\n\n const paymentShippingError = getShippingError(update.error);\n if (paymentShippingError) {\n actions.addPaymentError({ error: paymentShippingError });\n } else if (actions.showDialog) {\n actions.showDialog({ data: { ...update.error, hasErrorKey: true } });\n }\n\n break;\n }\n }\n});\n\nfunction onUpdateApiReady(global: GlobalState) {\n const { hasWebNotifications, hasPushNotifications } = selectNotifySettings(global);\n if (hasWebNotifications && hasPushNotifications) {\n void subscribe();\n }\n void setLanguage(global.settings.byKey.language);\n}\n\nfunction onUpdateAuthorizationState(update: ApiUpdateAuthorizationState) {\n let global = getGlobal();\n\n const wasAuthReady = global.authState === 'authorizationStateReady';\n const authState = update.authorizationState;\n\n setGlobal({\n ...global,\n authState,\n authIsLoading: false,\n });\n\n global = getGlobal();\n\n switch (authState) {\n case 'authorizationStateLoggingOut':\n void forceWebsync(false);\n\n setGlobal({\n ...global,\n isLoggingOut: true,\n });\n break;\n case 'authorizationStateWaitCode':\n setGlobal({\n ...global,\n authIsCodeViaApp: update.isCodeViaApp,\n });\n break;\n case 'authorizationStateWaitPassword':\n setGlobal({\n ...global,\n authHint: update.hint,\n });\n break;\n case 'authorizationStateWaitQrCode':\n setGlobal({\n ...global,\n authIsLoadingQrCode: false,\n authQrCode: update.qrCode,\n });\n break;\n case 'authorizationStateReady': {\n if (wasAuthReady) {\n break;\n }\n\n void forceWebsync(true);\n\n setGlobal({\n ...global,\n isLoggingOut: false,\n lastSyncTime: Date.now(),\n });\n\n break;\n }\n }\n}\n\nfunction onUpdateAuthorizationError(update: ApiUpdateAuthorizationError) {\n setGlobal({\n ...getGlobal(),\n authError: update.message,\n });\n}\n\nfunction onUpdateConnectionState(update: ApiUpdateConnectionState) {\n const { connectionState } = update;\n const global = getGlobal();\n\n setGlobal({\n ...global,\n connectionState,\n });\n\n if (connectionState === 'connectionStateReady' && global.authState === 'authorizationStateReady') {\n getDispatch().sync();\n } else if (connectionState === 'connectionStateBroken') {\n getDispatch().signOut();\n }\n}\n\nfunction onUpdateSession(update: ApiUpdateSession) {\n const { sessionData } = update;\n const { authRememberMe, authState } = getGlobal();\n const isEmpty = !sessionData || !sessionData.mainDcId;\n\n if (!authRememberMe || authState !== 'authorizationStateReady' || isEmpty) {\n return;\n }\n\n getDispatch().saveSession({ sessionData });\n}\n\nfunction onUpdateServerTimeOffset(update: ApiUpdateServerTimeOffset) {\n const global = getGlobal();\n\n if (global.serverTimeOffset === update.serverTimeOffset) {\n return;\n }\n\n setGlobal({\n ...global,\n serverTimeOffset: update.serverTimeOffset,\n });\n}\n\nfunction onUpdateCurrentUser(update: ApiUpdateCurrentUser) {\n const { currentUser } = update;\n\n setGlobal({\n ...updateUser(getGlobal(), currentUser.id, currentUser),\n currentUserId: currentUser.id,\n });\n\n updateSessionUserId(currentUser.id);\n}\n\nfunction updateSessionUserId(currentUserId: string) {\n const sessionUserAuth = localStorage.getItem(SESSION_USER_KEY);\n if (!sessionUserAuth) return;\n\n const userAuth = JSON.parse(sessionUserAuth);\n userAuth.id = currentUserId;\n\n localStorage.setItem(SESSION_USER_KEY, JSON.stringify(userAuth));\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { ANIMATION_LEVEL_MAX } from '../../../config';\nimport {\n IS_ANDROID, IS_IOS, IS_MAC_OS, IS_TOUCH_ENV,\n} from '../../../util/environment';\nimport { setLanguage } from '../../../util/langProvider';\nimport switchTheme from '../../../util/switchTheme';\nimport { selectTheme } from '../../selectors';\nimport { startWebsync } from '../../../util/websync';\n\nconst HISTORY_ANIMATION_DURATION = 450;\n\nsubscribeToSystemThemeChange();\n\naddReducer('init', (global) => {\n const { animationLevel, messageTextSize, language } = global.settings.byKey;\n const theme = selectTheme(global);\n\n void setLanguage(language, undefined, true);\n\n document.documentElement.style.setProperty(\n '--composer-text-size', `${Math.max(messageTextSize, IS_IOS ? 16 : 15)}px`,\n );\n document.documentElement.style.setProperty('--message-meta-height', `${Math.floor(messageTextSize * 1.3125)}px`);\n document.documentElement.style.setProperty('--message-text-size', `${messageTextSize}px`);\n document.documentElement.setAttribute('data-message-text-size', messageTextSize.toString());\n document.body.classList.add('initial');\n document.body.classList.add(`animation-level-${animationLevel}`);\n document.body.classList.add(IS_TOUCH_ENV ? 'is-touch-env' : 'is-pointer-env');\n switchTheme(theme, animationLevel === ANIMATION_LEVEL_MAX);\n startWebsync();\n\n if (IS_IOS) {\n document.body.classList.add('is-ios');\n } else if (IS_ANDROID) {\n document.body.classList.add('is-android');\n } else if (IS_MAC_OS) {\n document.body.classList.add('is-macos');\n }\n});\n\naddReducer('setIsUiReady', (global, actions, payload) => {\n const { uiReadyState } = payload!;\n\n if (uiReadyState === 2) {\n document.body.classList.remove('initial');\n }\n\n return {\n ...global,\n uiReadyState,\n };\n});\n\naddReducer('setAuthPhoneNumber', (global, actions, payload) => {\n const { phoneNumber } = payload!;\n\n return {\n ...global,\n authPhoneNumber: phoneNumber,\n };\n});\n\naddReducer('setAuthRememberMe', (global, actions, payload) => {\n return {\n ...global,\n authRememberMe: Boolean(payload),\n };\n});\n\naddReducer('clearAuthError', (global) => {\n return {\n ...global,\n authError: undefined,\n };\n});\n\naddReducer('disableHistoryAnimations', () => {\n setTimeout(() => {\n setGlobal({\n ...getGlobal(),\n shouldSkipHistoryAnimations: false,\n });\n document.body.classList.remove('no-animate');\n }, HISTORY_ANIMATION_DURATION);\n\n setGlobal({\n ...getGlobal(),\n shouldSkipHistoryAnimations: true,\n }, true);\n});\n\nfunction subscribeToSystemThemeChange() {\n function handleSystemThemeChange() {\n const currentThemeMatch = document.documentElement.className.match(/theme-(\\w+)/);\n const currentTheme = currentThemeMatch ? currentThemeMatch[1] : 'light';\n const global = getGlobal();\n const nextTheme = selectTheme(global);\n const { animationLevel } = global.settings.byKey;\n\n if (nextTheme !== currentTheme) {\n switchTheme(nextTheme, animationLevel === ANIMATION_LEVEL_MAX);\n // Force-update component containers\n setGlobal({ ...global });\n }\n }\n\n const mql = window.matchMedia('(prefers-color-scheme: dark)');\n if (typeof mql.addEventListener === 'function') {\n mql.addEventListener('change', handleSystemThemeChange);\n } else if (typeof mql.addListener === 'function') {\n mql.addListener(handleSystemThemeChange);\n }\n}\n","import { addReducer } from '../../../lib/teact/teactn';\nimport { ISettings, IThemeSettings, ThemeKey } from '../../../types';\nimport { replaceSettings, replaceThemeSettings } from '../../reducers';\n\naddReducer('setSettingOption', (global, actions, payload?: Partial) => {\n return replaceSettings(global, payload);\n});\n\naddReducer('setThemeSettings', (global, actions, payload: { theme: ThemeKey } & Partial) => {\n const { theme, ...settings } = payload;\n\n return replaceThemeSettings(global, theme, settings);\n});\n","import {\n ApiChat,\n ApiUser,\n ApiChatBannedRights,\n ApiChatAdminRights,\n ApiChatFolder,\n MAIN_THREAD_ID,\n} from '../../api/types';\n\nimport { NotifyException, NotifySettings } from '../../types';\nimport { LangFn } from '../../hooks/useLang';\n\nimport { ARCHIVED_FOLDER_ID, REPLIES_USER_ID } from '../../config';\nimport { orderBy } from '../../util/iteratees';\nimport { getUserFirstOrLastName } from './users';\nimport { formatDateToString, formatTime } from '../../util/dateFormat';\n\nconst FOREVER_BANNED_DATE = Date.now() / 1000 + 31622400; // 366 days\n\nconst VERIFIED_PRIORITY_BASE = 3e9;\nconst PINNED_PRIORITY_BASE = 3e8;\n\nexport function isUserId(entityId: string) {\n // Workaround for old-fashioned IDs stored locally\n if (typeof entityId === 'number') {\n return entityId > 0;\n }\n\n return !entityId.startsWith('-');\n}\n\nexport function isChatGroup(chat: ApiChat) {\n return isChatBasicGroup(chat) || isChatSuperGroup(chat);\n}\n\nexport function isChatBasicGroup(chat: ApiChat) {\n return chat.type === 'chatTypeBasicGroup';\n}\n\nexport function isChatSuperGroup(chat: ApiChat) {\n return chat.type === 'chatTypeSuperGroup';\n}\n\nexport function isChatChannel(chat: ApiChat) {\n return chat.type === 'chatTypeChannel';\n}\n\nexport function isCommonBoxChat(chat: ApiChat) {\n return chat.type === 'chatTypePrivate' || chat.type === 'chatTypeBasicGroup';\n}\n\nexport function isChatWithRepliesBot(chatId: string) {\n return chatId === REPLIES_USER_ID;\n}\n\nexport function getChatTypeString(chat: ApiChat) {\n switch (chat.type) {\n case 'chatTypePrivate':\n return 'PrivateChat';\n case 'chatTypeBasicGroup':\n case 'chatTypeSuperGroup':\n return 'AccDescrGroup';\n case 'chatTypeChannel':\n return 'AccDescrChannel';\n default:\n return 'Chat';\n }\n}\n\nexport function getPrivateChatUserId(chat: ApiChat) {\n if (chat.type !== 'chatTypePrivate' && chat.type !== 'chatTypeSecret') {\n return undefined;\n }\n return chat.id;\n}\n\n// TODO Get rid of `user`\nexport function getChatTitle(lang: LangFn, chat: ApiChat, user?: ApiUser, isSelf = false) {\n if (isSelf || (user && chat.id === user.id && user.isSelf)) {\n return lang('SavedMessages');\n }\n return chat.title || lang('HiddenName');\n}\n\nexport function getChatDescription(chat: ApiChat) {\n if (!chat.fullInfo) {\n return undefined;\n }\n return chat.fullInfo.about;\n}\n\nexport function getChatLink(chat: ApiChat) {\n const { username } = chat;\n if (username) {\n return `https://t.me/${username}`;\n }\n\n const { inviteLink } = chat.fullInfo || {};\n\n return inviteLink;\n}\n\nexport function getChatAvatarHash(\n owner: ApiChat | ApiUser,\n size: 'normal' | 'big' = 'normal',\n) {\n if (!owner.avatarHash) {\n return undefined;\n }\n\n switch (size) {\n case 'big':\n return `profile${owner.id}?${owner.avatarHash}`;\n default:\n return `avatar${owner.id}?${owner.avatarHash}`;\n }\n}\n\nexport function isChatSummaryOnly(chat: ApiChat) {\n return !chat.lastMessage;\n}\n\nexport function isChatAdmin(chat: ApiChat) {\n return Boolean(chat.adminRights);\n}\n\nexport function getHasAdminRight(chat: ApiChat, key: keyof ApiChatAdminRights) {\n return chat.adminRights ? chat.adminRights[key] : false;\n}\n\nexport function isUserRightBanned(chat: ApiChat, key: keyof ApiChatBannedRights) {\n return Boolean(\n (chat.currentUserBannedRights?.[key])\n || (chat.defaultBannedRights?.[key]),\n );\n}\n\nexport function getCanPostInChat(chat: ApiChat, threadId: number) {\n if (threadId !== MAIN_THREAD_ID) {\n return true;\n }\n\n if (chat.isRestricted || chat.migratedTo || chat.isNotJoined || isChatWithRepliesBot(chat.id)) {\n return false;\n }\n\n if (chat.isCreator) {\n return true;\n }\n\n if (isUserId(chat.id)) {\n return true;\n }\n\n if (isChatChannel(chat)) {\n return getHasAdminRight(chat, 'postMessages');\n }\n\n return isChatAdmin(chat) || !isUserRightBanned(chat, 'sendMessages');\n}\n\nexport interface IAllowedAttachmentOptions {\n canAttachMedia: boolean;\n canAttachPolls: boolean;\n canSendStickers: boolean;\n canSendGifs: boolean;\n canAttachEmbedLinks: boolean;\n}\n\nexport function getAllowedAttachmentOptions(chat?: ApiChat, isChatWithBot = false): IAllowedAttachmentOptions {\n if (!chat) {\n return {\n canAttachMedia: false,\n canAttachPolls: false,\n canSendStickers: false,\n canSendGifs: false,\n canAttachEmbedLinks: false,\n };\n }\n\n const isAdmin = isChatAdmin(chat);\n\n return {\n canAttachMedia: isAdmin || !isUserRightBanned(chat, 'sendMedia'),\n canAttachPolls: (isAdmin || !isUserRightBanned(chat, 'sendPolls')) && (!isUserId(chat.id) || isChatWithBot),\n canSendStickers: isAdmin || !isUserRightBanned(chat, 'sendStickers'),\n canSendGifs: isAdmin || !isUserRightBanned(chat, 'sendGifs'),\n canAttachEmbedLinks: isAdmin || !isUserRightBanned(chat, 'embedLinks'),\n };\n}\n\nexport function getMessageSendingRestrictionReason(\n lang: LangFn,\n currentUserBannedRights?: ApiChatBannedRights,\n defaultBannedRights?: ApiChatBannedRights,\n) {\n if (currentUserBannedRights?.sendMessages) {\n const { untilDate } = currentUserBannedRights;\n return untilDate && untilDate < FOREVER_BANNED_DATE\n ? lang(\n 'Channel.Persmission.Denied.SendMessages.Until',\n lang(\n 'formatDateAtTime',\n [formatDateToString(new Date(untilDate * 1000), lang.code), formatTime(untilDate * 1000, lang)],\n ),\n )\n : lang('Channel.Persmission.Denied.SendMessages.Forever');\n }\n\n if (defaultBannedRights?.sendMessages) {\n return lang('Channel.Persmission.Denied.SendMessages.DefaultRestrictedText');\n }\n\n return undefined;\n}\n\nexport function getChatSlowModeOptions(chat?: ApiChat) {\n if (!chat || !chat.fullInfo) {\n return undefined;\n }\n\n return chat.fullInfo.slowMode;\n}\n\nexport function getChatOrder(chat: ApiChat) {\n return Math.max(\n chat.joinDate || 0,\n chat.draftDate || 0,\n chat.lastMessage ? chat.lastMessage.date : 0,\n );\n}\n\nexport function isChatArchived(chat: ApiChat) {\n return chat.folderId === ARCHIVED_FOLDER_ID;\n}\n\nexport function selectIsChatMuted(\n chat: ApiChat, notifySettings: NotifySettings, notifyExceptions: Record = {},\n) {\n // If this chat is in exceptions they take precedence\n if (notifyExceptions[chat.id] && notifyExceptions[chat.id].isMuted !== undefined) {\n return notifyExceptions[chat.id].isMuted;\n }\n\n return (\n chat.isMuted\n || (isUserId(chat.id) && !notifySettings.hasPrivateChatsNotifications)\n || (isChatChannel(chat) && !notifySettings.hasBroadcastNotifications)\n || (isChatGroup(chat) && !notifySettings.hasGroupNotifications)\n );\n}\n\nexport function selectShouldShowMessagePreview(\n chat: ApiChat, notifySettings: NotifySettings, notifyExceptions: Record = {},\n) {\n const {\n hasPrivateChatsMessagePreview = true,\n hasBroadcastMessagePreview = true,\n hasGroupMessagePreview = true,\n } = notifySettings;\n // If this chat is in exceptions they take precedence\n if (notifyExceptions[chat.id] && notifyExceptions[chat.id].shouldShowPreviews !== undefined) {\n return notifyExceptions[chat.id].shouldShowPreviews;\n }\n\n return (isUserId(chat.id) && hasPrivateChatsMessagePreview)\n || (isChatChannel(chat) && hasBroadcastMessagePreview)\n || (isChatGroup(chat) && hasGroupMessagePreview);\n}\n\nexport function getCanDeleteChat(chat: ApiChat) {\n return isChatBasicGroup(chat) || ((isChatSuperGroup(chat) || isChatChannel(chat)) && chat.isCreator);\n}\n\nexport function prepareFolderListIds(\n chatsById: Record,\n usersById: Record,\n folder: ApiChatFolder,\n notifySettings: NotifySettings,\n notifyExceptions?: Record,\n chatIdsCache?: string[],\n) {\n const excludedChatIds = folder.excludedChatIds ? new Set(folder.excludedChatIds) : undefined;\n const includedChatIds = folder.excludedChatIds ? new Set(folder.includedChatIds) : undefined;\n const pinnedChatIds = folder.excludedChatIds ? new Set(folder.pinnedChatIds) : undefined;\n const listIds = (chatIdsCache || Object.keys(chatsById))\n .filter((id) => {\n return filterChatFolder(\n chatsById[id],\n folder,\n usersById,\n notifySettings,\n notifyExceptions,\n excludedChatIds,\n includedChatIds,\n pinnedChatIds,\n );\n });\n\n return [listIds, folder.pinnedChatIds] as const;\n}\n\nfunction filterChatFolder(\n chat: ApiChat,\n folder: ApiChatFolder,\n usersById: Record,\n notifySettings: NotifySettings,\n notifyExceptions?: Record,\n excludedChatIds?: Set,\n includedChatIds?: Set,\n pinnedChatIds?: Set,\n) {\n if (!chat.isListed) {\n return false;\n }\n\n if (excludedChatIds && excludedChatIds.has(chat.id)) {\n return false;\n }\n\n if (includedChatIds && includedChatIds.has(chat.id)) {\n return true;\n }\n\n if (pinnedChatIds && pinnedChatIds.has(chat.id)) {\n return true;\n }\n\n if (isChatArchived(chat) && folder.excludeArchived) {\n return false;\n }\n\n if (folder.excludeMuted && !chat.unreadMentionsCount && selectIsChatMuted(chat, notifySettings, notifyExceptions)) {\n return false;\n }\n\n if (!chat.unreadCount && !chat.unreadMentionsCount && !chat.hasUnreadMark && folder.excludeRead) {\n return false;\n }\n\n if (isUserId(chat.id)) {\n const privateChatUser = usersById[chat.id];\n\n const isChatWithBot = privateChatUser && privateChatUser.type === 'userTypeBot';\n if (isChatWithBot) {\n if (folder.bots) {\n return true;\n }\n } else {\n if (folder.contacts && privateChatUser && privateChatUser.isContact) {\n return true;\n }\n\n if (folder.nonContacts && privateChatUser && !privateChatUser.isContact) {\n return true;\n }\n }\n } else if (isChatGroup(chat)) {\n return !!folder.groups;\n } else if (isChatChannel(chat)) {\n return !!folder.channels;\n }\n\n return false;\n}\n\nexport function prepareChatList(\n chatsById: Record,\n listIds: string[],\n orderedPinnedIds?: string[],\n folderType: 'all' | 'archived' | 'folder' = 'all',\n) {\n function chatFilter(chat?: ApiChat) {\n if (!chat || !chat.lastMessage || chat.migratedTo) {\n return false;\n }\n\n switch (folderType) {\n case 'all':\n if (isChatArchived(chat)) {\n return false;\n }\n break;\n case 'archived':\n if (!isChatArchived(chat)) {\n return false;\n }\n break;\n }\n\n return !chat.isRestricted && !chat.isNotJoined;\n }\n\n const listedChats = listIds\n .map((id) => chatsById[id])\n .filter(chatFilter);\n\n const listIdsSet = new Set(listIds);\n const pinnedChats = orderedPinnedIds\n ? (\n orderedPinnedIds\n .map((id) => chatsById[id])\n .filter(chatFilter)\n .filter((chat) => listIdsSet.has(chat.id))\n )\n : [];\n\n const otherChats = orderBy(\n orderedPinnedIds\n ? listedChats.filter((chat) => !orderedPinnedIds.includes(chat.id))\n : listedChats,\n getChatOrder,\n 'desc',\n );\n\n return {\n pinnedChats,\n otherChats,\n };\n}\n\nexport function getFolderUnreadDialogs(\n chatsById: Record,\n usersById: Record,\n folder: ApiChatFolder,\n chatIdsCache: string[],\n notifySettings: NotifySettings,\n notifyExceptions?: Record,\n) {\n const [listIds] = prepareFolderListIds(chatsById, usersById, folder, notifySettings, notifyExceptions, chatIdsCache);\n\n const listedChats = listIds\n .map((id) => chatsById[id])\n .filter((chat) => (chat?.lastMessage && !chat.isRestricted && !chat.isNotJoined));\n\n const unreadDialogsCount = listedChats\n .reduce((total, chat) => (chat.unreadCount || chat.hasUnreadMark ? total + 1 : total), 0);\n\n const hasActiveDialogs = listedChats.some((chat) => (\n chat.unreadMentionsCount\n || (!selectIsChatMuted(chat, notifySettings, notifyExceptions) && (chat.unreadCount || chat.hasUnreadMark))\n ));\n\n return {\n unreadDialogsCount,\n hasActiveDialogs,\n };\n}\n\nexport function getFolderDescriptionText(\n lang: LangFn,\n chatsById: Record,\n usersById: Record,\n folder: ApiChatFolder,\n chatIdsCache: string[],\n notifySettings: NotifySettings,\n notifyExceptions?: Record,\n) {\n const {\n id, title, emoticon, description, pinnedChatIds,\n excludedChatIds, includedChatIds,\n excludeArchived, excludeMuted, excludeRead,\n ...filters\n } = folder;\n\n // If folder has multiple additive filters or uses include/exclude lists,\n // we display folder chats count\n if (\n Object.values(filters).filter(Boolean).length > 1\n || (excludedChatIds?.length)\n || (includedChatIds?.length)\n ) {\n const length = getFolderChatsCount(chatsById, usersById, folder, chatIdsCache, notifySettings, notifyExceptions);\n return lang('Chats', length);\n }\n\n // Otherwise, we return a short description of a single filter\n if (filters.bots) {\n return lang('FilterBots');\n } else if (filters.groups) {\n return lang('FilterGroups');\n } else if (filters.channels) {\n return lang('FilterChannels');\n } else if (filters.contacts) {\n return lang('FilterContacts');\n } else if (filters.nonContacts) {\n return lang('FilterNonContacts');\n } else {\n return undefined;\n }\n}\n\nfunction getFolderChatsCount(\n chatsById: Record,\n usersById: Record,\n folder: ApiChatFolder,\n chatIdsCache: string[],\n notifySettings: NotifySettings,\n notifyExceptions?: Record,\n) {\n const [listIds, pinnedIds] = prepareFolderListIds(\n chatsById, usersById, folder, notifySettings, notifyExceptions, chatIdsCache,\n );\n const { pinnedChats, otherChats } = prepareChatList(chatsById, listIds, pinnedIds, 'folder');\n return pinnedChats.length + otherChats.length;\n}\n\nexport function getMessageSenderName(lang: LangFn, chatId: string, sender?: ApiUser) {\n if (!sender || isUserId(chatId)) {\n return undefined;\n }\n\n if (sender.isSelf) {\n return lang('FromYou');\n }\n\n return getUserFirstOrLastName(sender);\n}\n\nexport function sortChatIds(\n chatIds: string[],\n chatsById: Record,\n shouldPrioritizeVerified = false,\n priorityIds?: string[],\n) {\n return orderBy(chatIds, (id) => {\n const chat = chatsById[id];\n if (!chat) {\n return 0;\n }\n\n let priority = 0;\n\n if (chat.lastMessage) {\n priority += chat.lastMessage.date;\n }\n\n if (shouldPrioritizeVerified && chat.isVerified) {\n priority += VERIFIED_PRIORITY_BASE; // ~100 years in seconds\n }\n\n if (priorityIds && priorityIds.includes(id)) {\n priority = Date.now() + PINNED_PRIORITY_BASE + (priorityIds.length - priorityIds.indexOf(id));\n }\n\n return priority;\n }, 'desc');\n}\n","import {\n ApiChat, ApiMessage, ApiMessageEntityTypes, ApiUser,\n} from '../../api/types';\nimport { LangFn } from '../../hooks/useLang';\n\nimport { LOCAL_MESSAGE_ID_BASE, SERVICE_NOTIFICATIONS_USER_ID, RE_LINK_TEMPLATE } from '../../config';\nimport { getUserFullName } from './users';\nimport { isWebpSupported, IS_OPUS_SUPPORTED } from '../../util/environment';\nimport { getChatTitle, isUserId } from './chats';\nimport parseEmojiOnlyString from '../../components/common/helpers/parseEmojiOnlyString';\n\nconst CONTENT_NOT_SUPPORTED = 'The message is not supported on this version of Telegram';\nconst RE_LINK = new RegExp(RE_LINK_TEMPLATE, 'i');\nconst TRUNCATED_SUMMARY_LENGTH = 80;\n\nexport type MessageKey = `msg${string}-${number}`;\n\nexport function getMessageKey(message: ApiMessage): MessageKey {\n const { chatId, id } = message;\n\n return buildMessageKey(chatId, id);\n}\n\nexport function buildMessageKey(chatId: string, msgId: number): MessageKey {\n return `msg${chatId}-${msgId}`;\n}\n\nexport function parseMessageKey(key: MessageKey) {\n const match = key.match(/^msg(-?\\d+)-(\\d+)/)!;\n\n return { chatId: match[1], messageId: Number(match[2]) };\n}\n\nexport function getMessageOriginalId(message: ApiMessage) {\n return message.previousLocalId || message.id;\n}\n\nexport function getMessageSummaryText(lang: LangFn, message: ApiMessage, noEmoji = false) {\n const {\n text, photo, video, audio, voice, document, sticker, contact, poll, invoice,\n } = message.content;\n\n const truncatedText = text && text.text.substr(0, TRUNCATED_SUMMARY_LENGTH);\n\n if (message.groupedId) {\n return `${noEmoji ? '' : '🖼 '}${truncatedText || lang('lng_in_dlg_album')}`;\n }\n\n if (photo) {\n return `${noEmoji ? '' : '🖼 '}${truncatedText || lang('AttachPhoto')}`;\n }\n\n if (video) {\n return `${noEmoji ? '' : '📹 '}${truncatedText || lang(video.isGif ? 'AttachGif' : 'AttachVideo')}`;\n }\n\n if (sticker) {\n return `${sticker.emoji || ''} ${lang('AttachSticker')}`.trim();\n }\n\n if (audio) {\n return `${noEmoji ? '' : '🎧 '}${getMessageAudioCaption(message) || lang('AttachMusic')}`;\n }\n\n if (voice) {\n return `${noEmoji ? '' : '🎤 '}${truncatedText || lang('AttachAudio')}`;\n }\n\n if (document) {\n return `${noEmoji ? '' : '📎 '}${truncatedText || document.fileName}`;\n }\n\n if (contact) {\n return lang('AttachContact');\n }\n\n if (poll) {\n return `${noEmoji ? '' : '📊 '}${poll.summary.question}`;\n }\n\n if (invoice) {\n return 'Invoice';\n }\n\n if (text) {\n return truncatedText;\n }\n\n return CONTENT_NOT_SUPPORTED;\n}\n\nexport function getMessageText(message: ApiMessage) {\n const {\n text, sticker, photo, video, audio, voice, document, poll, webPage, contact, invoice,\n } = message.content;\n\n if (text) {\n return text.text;\n }\n\n if (sticker || photo || video || audio || voice || document || contact || poll || webPage || invoice) {\n return undefined;\n }\n\n return CONTENT_NOT_SUPPORTED;\n}\n\nexport function getMessageCustomShape(message: ApiMessage): boolean | number {\n const {\n text, sticker, photo, video, audio, voice, document, poll, webPage, contact,\n } = message.content;\n\n if (sticker || (video?.isRound)) {\n return true;\n }\n\n if (!text || photo || video || audio || voice || document || poll || webPage || contact) {\n return false;\n }\n\n // This is a \"dual-intent\" method used to limit calls of `parseEmojiOnlyString`.\n return parseEmojiOnlyString(text.text) || false;\n}\n\nexport function getMessageSingleEmoji(message: ApiMessage) {\n const { text } = message.content;\n if (!(text && text.text.length <= 6)) {\n return undefined;\n }\n\n if (getMessageCustomShape(message) !== 1) {\n return undefined;\n }\n\n return text.text;\n}\n\nexport function getFirstLinkInMessage(message: ApiMessage) {\n const { text } = message.content;\n\n let match: RegExpMatchArray | null | undefined;\n if (text?.entities) {\n let link = text.entities.find((entity) => entity.type === ApiMessageEntityTypes.TextUrl);\n if (link) {\n match = link.url!.match(RE_LINK);\n }\n\n if (!match) {\n link = text.entities.find((entity) => entity.type === ApiMessageEntityTypes.Url);\n if (link) {\n const { offset, length } = link;\n match = text.text.substring(offset, offset + length).match(RE_LINK);\n }\n }\n }\n\n if (!match && text) {\n match = text.text.match(RE_LINK);\n }\n\n if (!match) {\n return undefined;\n }\n\n return {\n url: match[0],\n domain: match[3],\n };\n}\n\nexport function matchLinkInMessageText(message: ApiMessage) {\n const { text } = message.content;\n const match = text && text.text.match(RE_LINK);\n\n if (!match) {\n return undefined;\n }\n\n return {\n url: match[0],\n domain: match[3],\n };\n}\n\nexport function isOwnMessage(message: ApiMessage) {\n return message.isOutgoing;\n}\n\nexport function isReplyMessage(message: ApiMessage) {\n return Boolean(message.replyToMessageId);\n}\n\nexport function isForwardedMessage(message: ApiMessage) {\n return Boolean(message.forwardInfo);\n}\n\nexport function isActionMessage(message: ApiMessage) {\n return !!message.content.action;\n}\n\nexport function isServiceNotificationMessage(message: ApiMessage) {\n return message.chatId === SERVICE_NOTIFICATIONS_USER_ID && Math.round(message.id) !== message.id;\n}\n\nexport function isAnonymousOwnMessage(message: ApiMessage) {\n return Boolean(message.senderId) && !isUserId(message.senderId!) && isOwnMessage(message);\n}\n\nexport function getSenderTitle(lang: LangFn, sender: ApiUser | ApiChat) {\n return isUserId(sender.id) ? getUserFullName(sender as ApiUser) : getChatTitle(lang, sender as ApiChat);\n}\n\nexport function getSendingState(message: ApiMessage) {\n if (!message.sendingState) {\n return 'succeeded';\n }\n\n return message.sendingState === 'messageSendingStateFailed' ? 'failed' : 'pending';\n}\n\nexport function isMessageLocal(message: ApiMessage) {\n return message.id >= LOCAL_MESSAGE_ID_BASE;\n}\n\nexport function isHistoryClearMessage(message: ApiMessage) {\n return message.content.action && message.content.action.type === 'historyClear';\n}\n\nexport function getMessageAudioCaption(message: ApiMessage) {\n const { audio, text } = message.content;\n\n return (audio && [audio.title, audio.performer].filter(Boolean).join(' — ')) || (text?.text);\n}\n\nexport function getMessageContentFilename(message: ApiMessage) {\n const { content } = message;\n\n const video = content.webPage ? content.webPage.video : content.video;\n const photo = content.webPage ? content.webPage.photo : content.photo;\n const document = content.webPage ? content.webPage.document : content.document;\n if (document) {\n return document.fileName;\n }\n\n if (video) {\n return video.fileName;\n }\n\n if (content.sticker) {\n const extension = content.sticker.isAnimated ? 'tgs' : isWebpSupported() ? 'webp' : 'png';\n return `${content.sticker.id}.${extension}`;\n }\n\n if (content.audio) {\n return content.audio.fileName;\n }\n\n const baseFilename = getMessageKey(message);\n\n if (photo) {\n return `${baseFilename}.jpg`;\n }\n\n if (content.voice) {\n return IS_OPUS_SUPPORTED ? `${baseFilename}.ogg` : `${baseFilename}.wav`;\n }\n\n return baseFilename;\n}\n","import {\n ApiAudio, ApiMediaFormat, ApiMessage, ApiMessageSearchType, ApiPhoto, ApiVideo, ApiDimensions,\n} from '../../api/types';\n\nimport { IS_OPUS_SUPPORTED, IS_PROGRESSIVE_SUPPORTED, IS_SAFARI } from '../../util/environment';\nimport { getMessageKey, isMessageLocal, matchLinkInMessageText } from './messages';\nimport { getDocumentHasPreview } from '../../components/common/helpers/documentInfo';\n\ntype Target =\n 'micro'\n | 'pictogram'\n | 'inline'\n | 'viewerPreview'\n | 'viewerFull'\n | 'download';\n\nexport function getMessageContent(message: ApiMessage) {\n return message.content;\n}\n\nexport function hasMessageMedia(message: ApiMessage) {\n return Boolean((\n getMessagePhoto(message)\n || getMessageVideo(message)\n || getMessageDocument(message)\n || getMessageSticker(message)\n || getMessageContact(message)\n || getMessagePoll(message)\n || getMessageAction(message)\n || getMessageAudio(message)\n || getMessageVoice(message)\n ));\n}\n\nexport function getMessagePhoto(message: ApiMessage) {\n return message.content.photo;\n}\n\nexport function getMessageVideo(message: ApiMessage) {\n return message.content.video;\n}\n\nexport function getMessageRoundVideo(message: ApiMessage) {\n const { video } = message.content;\n\n return video?.isRound ? video : undefined;\n}\n\nexport function getMessageAction(message: ApiMessage) {\n return message.content.action;\n}\n\nexport function getMessageAudio(message: ApiMessage) {\n return message.content.audio;\n}\n\nexport function getMessageVoice(message: ApiMessage) {\n return message.content.voice;\n}\n\nexport function getMessageSticker(message: ApiMessage) {\n return message.content.sticker;\n}\n\nexport function getMessageDocument(message: ApiMessage) {\n return message.content.document;\n}\n\nexport function isMessageDocumentPhoto(message: ApiMessage) {\n const document = getMessageDocument(message);\n return document ? document.mediaType === 'photo' : undefined;\n}\n\nexport function isMessageDocumentVideo(message: ApiMessage) {\n const document = getMessageDocument(message);\n return document ? document.mediaType === 'video' : undefined;\n}\n\nexport function getMessageContact(message: ApiMessage) {\n return message.content.contact;\n}\n\nexport function getMessagePoll(message: ApiMessage) {\n return message.content.poll;\n}\n\nexport function getMessageInvoice(message: ApiMessage) {\n return message.content.invoice;\n}\n\nexport function getMessageWebPage(message: ApiMessage) {\n return message.content.webPage;\n}\n\nexport function getMessageWebPagePhoto(message: ApiMessage) {\n return getMessageWebPage(message)?.photo;\n}\n\nexport function getMessageWebPageDocument(message: ApiMessage) {\n return getMessageWebPage(message)?.document;\n}\n\nexport function getMessageWebPageVideo(message: ApiMessage): ApiVideo | undefined {\n return getMessageWebPage(message)?.video;\n}\n\nexport function getMessageMediaThumbnail(message: ApiMessage) {\n const media = getMessagePhoto(message)\n || getMessageVideo(message)\n || getMessageDocument(message)\n || getMessageSticker(message)\n || getMessageWebPagePhoto(message)\n || getMessageWebPageVideo(message);\n\n if (!media) {\n return undefined;\n }\n\n return media.thumbnail;\n}\n\nexport function getMessageMediaThumbDataUri(message: ApiMessage) {\n return getMessageMediaThumbnail(message)?.dataUri;\n}\n\nexport function getMessageMediaHash(\n message: ApiMessage,\n target: Target,\n) {\n const {\n photo, video, sticker, audio, voice, document,\n } = message.content;\n const webPagePhoto = getMessageWebPagePhoto(message);\n const webPageVideo = getMessageWebPageVideo(message);\n\n const messageVideo = video || webPageVideo;\n const messagePhoto = photo || webPagePhoto;\n\n if (!(messagePhoto || messageVideo || sticker || audio || voice || document)) {\n return undefined;\n }\n\n const base = getMessageKey(message);\n\n if (messageVideo) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n return `${base}?size=m`;\n case 'inline':\n return !hasMessageLocalBlobUrl(message) ? getVideoOrAudioBaseHash(messageVideo, base) : undefined;\n case 'viewerPreview':\n return `${base}?size=m`;\n case 'viewerFull':\n return getVideoOrAudioBaseHash(messageVideo, base);\n case 'download':\n return `${base}?download`;\n }\n }\n\n if (messagePhoto) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n return `${base}?size=m`;\n case 'inline':\n return !hasMessageLocalBlobUrl(message) ? `${base}?size=x` : undefined;\n case 'viewerPreview':\n return `${base}?size=x`;\n case 'viewerFull':\n case 'download':\n return `${base}?size=z`;\n }\n }\n\n if (document) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n case 'inline':\n case 'viewerPreview':\n if (!getDocumentHasPreview(document) || hasMessageLocalBlobUrl(message)) {\n return undefined;\n }\n\n return `${base}?size=m`;\n case 'viewerFull':\n case 'download':\n return base;\n }\n }\n\n if (sticker) {\n switch (target) {\n case 'micro':\n return undefined;\n case 'pictogram':\n return `${base}?size=m`;\n case 'inline':\n return base;\n case 'download':\n return `${base}?download`;\n }\n }\n\n if (audio) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n return getAudioHasCover(audio) ? `${base}?size=m` : undefined;\n case 'inline':\n return getVideoOrAudioBaseHash(audio, base);\n case 'download':\n return `${base}?download`;\n }\n }\n\n if (voice) {\n switch (target) {\n case 'micro':\n case 'pictogram':\n return undefined;\n case 'inline':\n return base;\n case 'download':\n return `${base}?download`;\n }\n }\n\n return undefined;\n}\n\nfunction getVideoOrAudioBaseHash(media: ApiAudio | ApiVideo, base: string) {\n if (IS_PROGRESSIVE_SUPPORTED && IS_SAFARI) {\n return `${base}?fileSize=${media.size}&mimeType=${media.mimeType}`;\n }\n\n return base;\n}\n\nexport function getAudioHasCover(media: ApiAudio) {\n return media.thumbnailSizes && media.thumbnailSizes.length > 0;\n}\n\nexport function getMessageMediaFormat(\n message: ApiMessage, target: Target,\n): Exclude;\nexport function getMessageMediaFormat(message: ApiMessage, target: Target, canBeLottie: true): ApiMediaFormat;\nexport function getMessageMediaFormat(\n message: ApiMessage, target: Target,\n): ApiMediaFormat {\n const {\n sticker, video, audio, voice,\n } = message.content;\n\n const fullVideo = video || getMessageWebPageVideo(message);\n\n if (sticker && target === 'inline' && sticker.isAnimated) {\n return ApiMediaFormat.Lottie;\n } else if (fullVideo && IS_PROGRESSIVE_SUPPORTED && (\n target === 'viewerFull' || target === 'inline'\n )) {\n return ApiMediaFormat.Progressive;\n } else if (audio || voice) {\n // Safari\n if (voice && !IS_OPUS_SUPPORTED) {\n return ApiMediaFormat.BlobUrl;\n }\n\n return ApiMediaFormat.Progressive;\n }\n\n return ApiMediaFormat.BlobUrl;\n}\n\nexport function getMessageFileName(message: ApiMessage) {\n const {\n photo, video, document,\n } = message.content;\n const webPagePhoto = getMessageWebPagePhoto(message);\n const webPageVideo = getMessageWebPageVideo(message);\n\n if (photo || webPagePhoto) {\n return `photo${message.date}.jpeg`;\n }\n\n const { fileName } = video || webPageVideo || document || {};\n\n return fileName;\n}\n\nexport function getMessageFileSize(message: ApiMessage) {\n const { video, document } = message.content;\n const webPageVideo = getMessageWebPageVideo(message);\n const { size } = video || webPageVideo || document || {};\n\n return size;\n}\n\nexport function hasMessageLocalBlobUrl(message: ApiMessage) {\n const { photo, video, document } = message.content;\n\n return (photo?.blobUrl) || (video?.blobUrl) || (document?.previewBlobUrl);\n}\n\nexport function getChatMediaMessageIds(\n messages: Record, listedIds: number[], isFromSharedMedia = false,\n) {\n const ids = getMessageContentIds(messages, listedIds, isFromSharedMedia ? 'media' : 'inlineMedia');\n\n return isFromSharedMedia ? ids.reverse() : ids;\n}\n\nexport function getPhotoFullDimensions(photo: ApiPhoto): ApiDimensions | undefined {\n return (\n photo.sizes.find((size) => size.type === 'z')\n || photo.sizes.find((size) => size.type === 'y')\n || getPhotoInlineDimensions(photo)\n );\n}\n\nexport function getPhotoInlineDimensions(photo: ApiPhoto): ApiDimensions | undefined {\n return (\n photo.sizes.find((size) => size.type === 'x')\n || photo.sizes.find((size) => size.type === 'm')\n || photo.sizes.find((size) => size.type === 's')\n || photo.thumbnail\n );\n}\n\nexport function getVideoDimensions(video: ApiVideo): ApiDimensions | undefined {\n if (video.width && video.height) {\n return video as ApiDimensions;\n }\n\n return undefined;\n}\n\nexport function getMediaTransferState(message: ApiMessage, progress?: number, isLoadNeeded = false) {\n const isUploading = isMessageLocal(message);\n const isTransferring = isUploading || isLoadNeeded;\n const transferProgress = Number(progress);\n\n return {\n isUploading, isTransferring, transferProgress,\n };\n}\n\nexport function getMessageContentIds(\n messages: Record, messageIds: number[], contentType: ApiMessageSearchType | 'inlineMedia',\n) {\n let validator: Function;\n\n switch (contentType) {\n case 'media':\n validator = (message: ApiMessage) => {\n const video = getMessageVideo(message);\n return getMessagePhoto(message) || (video && !video.isRound && !video.isGif);\n };\n break;\n\n case 'documents':\n validator = getMessageDocument;\n break;\n\n case 'links':\n validator = (message: ApiMessage) => getMessageWebPage(message) || matchLinkInMessageText(message);\n break;\n\n case 'audio':\n validator = getMessageAudio;\n break;\n\n case 'voice':\n validator = (message: ApiMessage) => {\n const video = getMessageVideo(message);\n return getMessageVoice(message) || (video && video.isRound);\n };\n break;\n\n case 'inlineMedia':\n validator = (message: ApiMessage) => {\n const video = getMessageVideo(message);\n return (\n getMessagePhoto(message)\n || (video && !video.isRound && !video.isGif)\n || isMessageDocumentPhoto(message)\n || isMessageDocumentVideo(message)\n );\n };\n break;\n\n default:\n return [] as Array;\n }\n\n return messageIds.reduce((result, messageId) => {\n if (messages[messageId] && validator(messages[messageId])) {\n result.push(messageId);\n }\n\n return result;\n }, [] as Array);\n}\n\nexport function getMediaDuration(message: ApiMessage) {\n const { audio, voice, video } = getMessageContent(message);\n const media = audio || voice || video || getMessageWebPageVideo(message);\n if (!media) {\n return undefined;\n }\n\n return media.duration;\n}\n","export function buildChatThreadKey(chatId: string, threadId: number) {\n return `${chatId}_${threadId}`;\n}\n","import { ApiFieldError } from '../../api/types';\n\nconst STRIPE_ERRORS: Record = {\n missing_payment_information: {\n field: 'cardNumber',\n message: 'Incorrect card number',\n },\n invalid_number: {\n field: 'cardNumber',\n message: 'Incorrect card number',\n },\n number: {\n field: 'cardNumber',\n message: 'Incorrect card number',\n },\n exp_year: {\n field: 'expiry',\n message: 'Incorrect year',\n },\n exp_month: {\n field: 'expiry',\n message: 'Incorrect month',\n },\n invalid_expiry_year: {\n field: 'expiry',\n message: 'Incorrect year',\n },\n invalid_expiry_month: {\n field: 'expiry',\n message: 'Incorrect month',\n },\n cvc: {\n field: 'cvv',\n message: 'Incorrect CVV',\n },\n invalid_cvc: {\n field: 'cvv',\n message: 'Incorrect CVV',\n },\n};\n\nexport function getStripeError(error: {\n code: string;\n message: string;\n param?: string;\n}) {\n const { message: description, code, param } = error;\n const { field, message } = param ? STRIPE_ERRORS[param] : STRIPE_ERRORS[code];\n\n return { field, message, description };\n}\n","import { ApiChat, ApiUser } from '../../api/types';\n\nimport { SERVICE_NOTIFICATIONS_USER_ID } from '../../config';\nimport { formatFullDate, formatTime } from '../../util/dateFormat';\nimport { orderBy } from '../../util/iteratees';\nimport { LangFn } from '../../hooks/useLang';\nimport { getServerTime } from '../../util/serverTime';\n\nconst USER_COLOR_KEYS = [1, 8, 5, 2, 7, 4, 6];\n\nexport function getUserFirstOrLastName(user?: ApiUser) {\n if (!user) {\n return undefined;\n }\n\n switch (user.type) {\n case 'userTypeBot':\n case 'userTypeRegular': {\n return user.firstName || user.lastName;\n }\n\n case 'userTypeDeleted':\n case 'userTypeUnknown': {\n return 'Deleted';\n }\n\n default:\n return undefined;\n }\n}\n\nexport function getUserFullName(user?: ApiUser) {\n if (!user) {\n return undefined;\n }\n\n if (isDeletedUser(user)) {\n return 'Deleted account';\n }\n\n switch (user.type) {\n case 'userTypeBot':\n case 'userTypeRegular': {\n if (user.firstName && user.lastName) {\n return `${user.firstName} ${user.lastName}`;\n }\n\n if (user.firstName) {\n return user.firstName;\n }\n\n if (user.lastName) {\n return user.lastName;\n }\n\n break;\n }\n\n case 'userTypeDeleted':\n case 'userTypeUnknown': {\n return 'Deleted account';\n }\n }\n\n return undefined;\n}\n\nexport function getUserStatus(lang: LangFn, user: ApiUser, serverTimeOffset: number) {\n if (user.id === SERVICE_NOTIFICATIONS_USER_ID) {\n return lang('ServiceNotifications').toLowerCase();\n }\n\n if (user.type && user.type === 'userTypeBot') {\n return lang('Bot');\n }\n\n if (!user.status) {\n return '';\n }\n\n switch (user.status.type) {\n case 'userStatusEmpty': {\n return lang('ALongTimeAgo');\n }\n\n case 'userStatusLastMonth': {\n return lang('WithinAMonth');\n }\n\n case 'userStatusLastWeek': {\n return lang('WithinAWeek');\n }\n\n case 'userStatusOffline': {\n const { wasOnline } = user.status;\n\n if (!wasOnline) return lang('LastSeen.Offline');\n\n const now = new Date(new Date().getTime() + serverTimeOffset * 1000);\n const wasOnlineDate = new Date(wasOnline * 1000);\n\n if (wasOnlineDate >= now) {\n return lang('LastSeen.JustNow');\n }\n\n const diff = new Date(now.getTime() - wasOnlineDate.getTime());\n\n // within a minute\n if (diff.getTime() / 1000 < 60) {\n return lang('LastSeen.JustNow');\n }\n\n // within an hour\n if (diff.getTime() / 1000 < 60 * 60) {\n const minutes = Math.floor(diff.getTime() / 1000 / 60);\n return lang('LastSeen.MinutesAgo', minutes);\n }\n\n // today\n const today = new Date();\n today.setHours(0, 0, 0, 0);\n const serverToday = new Date(today.getTime() + serverTimeOffset * 1000);\n if (wasOnlineDate > serverToday) {\n // up to 6 hours ago\n if (diff.getTime() / 1000 < 6 * 60 * 60) {\n const hours = Math.floor(diff.getTime() / 1000 / 60 / 60);\n return lang('LastSeen.HoursAgo', hours);\n }\n\n // other\n return lang('LastSeen.TodayAt', formatTime(wasOnlineDate, lang));\n }\n\n // yesterday\n const yesterday = new Date();\n yesterday.setDate(now.getDate() - 1);\n yesterday.setHours(0, 0, 0, 0);\n const serverYesterday = new Date(yesterday.getTime() + serverTimeOffset * 1000);\n if (wasOnlineDate > serverYesterday) {\n return lang('LastSeen.YesterdayAt', formatTime(wasOnlineDate, lang));\n }\n\n return lang('LastSeen.AtDate', formatFullDate(lang, wasOnlineDate));\n }\n\n case 'userStatusOnline': {\n return lang('Online');\n }\n\n case 'userStatusRecently': {\n return lang('Lately');\n }\n\n default:\n return undefined;\n }\n}\n\nexport function isUserOnline(user: ApiUser) {\n const { id, status, type } = user;\n\n if (!status) {\n return false;\n }\n\n if (id === SERVICE_NOTIFICATIONS_USER_ID) {\n return false;\n }\n\n return status.type === 'userStatusOnline' && type !== 'userTypeBot';\n}\n\nexport function isDeletedUser(user: ApiUser) {\n if (!user.status || user.type === 'userTypeBot' || user.id === SERVICE_NOTIFICATIONS_USER_ID) {\n return false;\n }\n\n return user.type === 'userTypeDeleted'\n || user.type === 'userTypeUnknown';\n}\n\nexport function isUserBot(user: ApiUser) {\n return user.type === 'userTypeBot';\n}\n\nexport function getCanAddContact(user: ApiUser) {\n return !user.isContact && !isUserBot(user);\n}\n\nexport function sortUserIds(\n userIds: string[],\n usersById: Record,\n priorityIds?: string[],\n serverTimeOffset = 0,\n) {\n return orderBy(userIds, (id) => {\n const now = getServerTime(serverTimeOffset);\n\n if (priorityIds && priorityIds.includes(id)) {\n // Assuming that online status expiration date can't be as far as two days from now,\n // this should place prioritized on top of the list.\n // Then we subtract index of `id` in `priorityIds` to preserve selected order\n return now + (48 * 60 * 60) - (priorityIds.length - priorityIds.indexOf(id));\n }\n\n const user = usersById[id];\n if (!user || !user.status) {\n return 0;\n }\n\n if (user.status.type === 'userStatusOnline') {\n return user.status.expires;\n } else if (user.status.type === 'userStatusOffline' && user.status.wasOnline) {\n return user.status.wasOnline;\n }\n\n switch (user.status.type) {\n case 'userStatusRecently':\n return now - 60 * 60 * 24;\n case 'userStatusLastWeek':\n return now - 60 * 60 * 24 * 7;\n case 'userStatusLastMonth':\n return now - 60 * 60 * 24 * 7 * 30;\n default:\n return 0;\n }\n }, 'desc');\n}\n\nexport function getUserIdDividend(userId: string) {\n // Workaround for old-fashioned IDs stored locally\n if (typeof userId === 'number') {\n return Math.abs(userId);\n }\n\n return Math.abs(Number(userId));\n}\n\n// eslint-disable-next-line max-len\n// https://github.com/telegramdesktop/tdesktop/blob/371510cfe23b0bd226de8c076bc49248fbe40c26/Telegram/SourceFiles/data/data_peer.cpp#L53\nexport function getUserColorKey(peer: ApiUser | ApiChat | undefined) {\n const index = peer ? getUserIdDividend(peer.id) % 7 : 0;\n\n return USER_COLOR_KEYS[index];\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiChat, ApiPhoto } from '../../api/types';\n\nimport { ARCHIVED_FOLDER_ID } from '../../config';\nimport { omit } from '../../util/iteratees';\nimport { selectChatListType } from '../selectors';\n\nexport function replaceChatListIds(\n global: GlobalState,\n type: 'active' | 'archived',\n newIds: string[] | undefined,\n): GlobalState {\n return {\n ...global,\n chats: {\n ...global.chats,\n listIds: {\n ...global.chats.listIds,\n [type]: newIds,\n },\n },\n };\n}\n\nexport function updateChatListIds(global: GlobalState, type: 'active' | 'archived', idsUpdate: string[]): GlobalState {\n const { [type]: listIds } = global.chats.listIds;\n const newIds = listIds?.length\n ? idsUpdate.filter((id) => !listIds.includes(id))\n : idsUpdate;\n\n if (listIds && !newIds.length) {\n return global;\n }\n\n return replaceChatListIds(global, type, [\n ...(listIds || []),\n ...newIds,\n ]);\n}\n\nexport function replaceChats(global: GlobalState, newById: Record): GlobalState {\n return {\n ...global,\n chats: {\n ...global.chats,\n byId: newById,\n },\n };\n}\n\n// @optimization Don't spread/unspread global for each element, do it in a batch\nfunction getUpdatedChat(\n global: GlobalState, chatId: string, chatUpdate: Partial, photo?: ApiPhoto,\n): ApiChat {\n const { byId } = global.chats;\n const chat = byId[chatId];\n const shouldOmitMinInfo = chatUpdate.isMin && chat && !chat.isMin;\n const updatedChat = {\n ...chat,\n ...(shouldOmitMinInfo ? omit(chatUpdate, ['isMin', 'accessHash']) : chatUpdate),\n ...(photo && { photos: [photo, ...(chat.photos || [])] }),\n };\n\n if (!updatedChat.id || !updatedChat.type) {\n return updatedChat;\n }\n\n return updatedChat;\n}\n\nexport function updateChat(\n global: GlobalState, chatId: string, chatUpdate: Partial, photo?: ApiPhoto,\n): GlobalState {\n const { byId } = global.chats;\n\n const updatedChat = getUpdatedChat(global, chatId, chatUpdate, photo);\n\n return replaceChats(global, {\n ...byId,\n [chatId]: updatedChat,\n });\n}\n\nexport function updateChats(global: GlobalState, updatedById: Record): GlobalState {\n const updatedChats = Object.keys(updatedById).reduce>((acc, id) => {\n const updatedChat = getUpdatedChat(global, id, updatedById[id]);\n if (updatedChat) {\n acc[id] = updatedChat;\n }\n return acc;\n }, {});\n\n global = replaceChats(global, {\n ...global.chats.byId,\n ...updatedChats,\n });\n\n return global;\n}\n\n// @optimization Allows to avoid redundant updates which cause a lot of renders\nexport function addChats(global: GlobalState, addedById: Record): GlobalState {\n const { byId } = global.chats;\n let isAdded = false;\n\n const addedChats = Object.keys(addedById).reduce>((acc, id) => {\n if (!byId[id] || (byId[id].isMin && !addedById[id].isMin)) {\n const updatedChat = getUpdatedChat(global, id, addedById[id]);\n if (updatedChat) {\n acc[id] = updatedChat;\n\n if (!isAdded) {\n isAdded = true;\n }\n }\n }\n return acc;\n }, {});\n\n if (isAdded) {\n global = replaceChats(global, {\n ...global.chats.byId,\n ...addedChats,\n });\n }\n\n return global;\n}\n\nexport function updateChatListType(\n global: GlobalState,\n chatId: string,\n folderId?: number,\n): GlobalState {\n const listType = folderId === ARCHIVED_FOLDER_ID ? 'archived' : 'active';\n\n let currentListIds = global.chats.listIds;\n (Object.keys(currentListIds) as Array).forEach((listTypeKey) => {\n const currentFolderList = currentListIds[listTypeKey] || [];\n if (listTypeKey === listType && !currentFolderList.includes(chatId)) {\n currentListIds = {\n ...currentListIds,\n [listTypeKey]: [...currentFolderList, chatId],\n };\n } else if (listTypeKey !== listType && currentFolderList.includes(chatId)) {\n currentListIds = {\n ...currentListIds,\n [listTypeKey]: currentFolderList.filter((id) => id !== chatId),\n };\n }\n });\n\n global = {\n ...global,\n chats: {\n ...global.chats,\n listIds: currentListIds,\n },\n };\n\n global = updateChat(global, chatId, { folderId: folderId || undefined });\n\n return global;\n}\n\nexport function updateChatListSecondaryInfo(\n global: GlobalState,\n type: 'active' | 'archived',\n info: {\n orderedPinnedIds?: string[];\n totalChatCount: number;\n },\n): GlobalState {\n const totalCountKey = type === 'active' ? 'all' : 'archived';\n\n return {\n ...global,\n chats: {\n ...global.chats,\n ...(info.orderedPinnedIds && {\n orderedPinnedIds: {\n ...global.chats.orderedPinnedIds,\n [type]: info.orderedPinnedIds,\n },\n }),\n totalCount: {\n ...global.chats.totalCount,\n [totalCountKey]: info.totalChatCount,\n },\n isFullyLoaded: {\n ...global.chats.isFullyLoaded,\n [type]: false,\n },\n },\n };\n}\n\nexport function leaveChat(global: GlobalState, leftChatId: string): GlobalState {\n const listType = selectChatListType(global, leftChatId);\n if (!listType) {\n return global;\n }\n\n const { [listType]: listIds } = global.chats.listIds;\n\n if (listIds) {\n global = replaceChatListIds(global, listType, listIds.filter((listId) => listId !== leftChatId));\n }\n\n global = updateChat(global, leftChatId, { isNotJoined: true });\n\n return global;\n}\n","import {\n GlobalState, MessageList, MessageListType, Thread,\n} from '../../global/types';\nimport { ApiMessage, ApiThreadInfo, MAIN_THREAD_ID } from '../../api/types';\nimport { FocusDirection } from '../../types';\n\nimport {\n IS_TEST, MESSAGE_LIST_SLICE, MESSAGE_LIST_VIEWPORT_LIMIT, TMP_CHAT_ID,\n} from '../../config';\nimport {\n selectListedIds,\n selectChatMessages,\n selectViewportIds,\n selectOutlyingIds,\n selectPinnedIds,\n selectThreadInfo,\n selectMessageIdsByGroupId,\n selectScheduledMessages,\n selectScheduledIds,\n selectCurrentMessageIds,\n selectChatMessage,\n selectCurrentMessageList,\n} from '../selectors';\nimport {\n areSortedArraysEqual, omit, pickTruthy, unique,\n} from '../../util/iteratees';\n\ntype MessageStoreSections = {\n byId: Record;\n threadsById: Record;\n};\n\nexport function updateCurrentMessageList(\n global: GlobalState,\n chatId: string | undefined,\n threadId: number = MAIN_THREAD_ID,\n type: MessageListType = 'thread',\n shouldReplaceHistory?: boolean,\n): GlobalState {\n const { messageLists } = global.messages;\n let newMessageLists: MessageList[] = messageLists;\n if (shouldReplaceHistory || IS_TEST) {\n newMessageLists = chatId ? [{ chatId, threadId, type }] : [];\n } else if (chatId) {\n const last = messageLists[messageLists.length - 1];\n if (!last || last.chatId !== chatId || last.threadId !== threadId || last.type !== type) {\n if (last && last.chatId === TMP_CHAT_ID) {\n newMessageLists = [...messageLists.slice(0, -1), { chatId, threadId, type }];\n } else {\n newMessageLists = [...messageLists, { chatId, threadId, type }];\n }\n }\n } else {\n newMessageLists = messageLists.slice(0, -1);\n }\n\n return {\n ...global,\n messages: {\n ...global.messages,\n messageLists: newMessageLists,\n },\n };\n}\n\nfunction replaceChatMessages(global: GlobalState, chatId: string, newById: Record): GlobalState {\n return updateMessageStore(global, chatId, {\n byId: newById,\n });\n}\n\nfunction updateThread(\n global: GlobalState, chatId: string, threadId: number, threadUpdate: Partial,\n): GlobalState {\n const current = global.messages.byChatId[chatId];\n\n return updateMessageStore(global, chatId, {\n threadsById: {\n ...(current?.threadsById),\n [threadId]: {\n ...(current?.threadsById[threadId]),\n ...threadUpdate,\n },\n },\n });\n}\n\nfunction updateMessageStore(\n global: GlobalState, chatId: string, update: Partial,\n): GlobalState {\n const current = global.messages.byChatId[chatId] || { byId: {}, threadsById: {} };\n\n return {\n ...global,\n messages: {\n ...global.messages,\n byChatId: {\n ...global.messages.byChatId,\n [chatId]: {\n ...current,\n ...update,\n },\n },\n },\n };\n}\n\nexport function replaceThreadParam(\n global: GlobalState, chatId: string, threadId: number, paramName: T, newValue: Thread[T] | undefined,\n) {\n return updateThread(global, chatId, threadId, { [paramName]: newValue });\n}\n\nexport function addMessages(\n global: GlobalState, messages: ApiMessage[],\n): GlobalState {\n const addedByChatId = messages.reduce((messagesByChatId, message: ApiMessage) => {\n if (!messagesByChatId[message.chatId]) {\n messagesByChatId[message.chatId] = {};\n }\n messagesByChatId[message.chatId][message.id] = message;\n\n return messagesByChatId;\n }, {} as Record>);\n\n Object.keys(addedByChatId).forEach((chatId) => {\n global = addChatMessagesById(global, chatId, addedByChatId[chatId]);\n });\n\n return global;\n}\n\nexport function addChatMessagesById(\n global: GlobalState, chatId: string, newById: Record,\n): GlobalState {\n const byId = selectChatMessages(global, chatId);\n\n if (byId && Object.keys(newById).every((newId) => Boolean(byId[Number(newId)]))) {\n return global;\n }\n\n return replaceChatMessages(global, chatId, {\n ...newById,\n ...byId,\n });\n}\n\nexport function updateChatMessage(\n global: GlobalState, chatId: string, messageId: number, messageUpdate: Partial,\n): GlobalState {\n const byId = selectChatMessages(global, chatId) || {};\n const message = byId[messageId];\n const updatedMessage = {\n ...message,\n ...messageUpdate,\n };\n\n if (!updatedMessage.id) {\n return global;\n }\n\n return replaceChatMessages(global, chatId, {\n ...byId,\n [messageId]: updatedMessage,\n });\n}\n\nexport function updateScheduledMessage(\n global: GlobalState, chatId: string, messageId: number, messageUpdate: Partial,\n): GlobalState {\n const byId = selectScheduledMessages(global, chatId) || {};\n const message = byId[messageId];\n const updatedMessage = {\n ...message,\n ...messageUpdate,\n };\n\n if (!updatedMessage.id) {\n return global;\n }\n\n return replaceScheduledMessages(global, chatId, {\n ...byId,\n [messageId]: updatedMessage,\n });\n}\n\nexport function deleteChatMessages(\n global: GlobalState,\n chatId: string,\n messageIds: number[],\n): GlobalState {\n const byId = selectChatMessages(global, chatId);\n if (!byId) {\n return global;\n }\n const newById = omit(byId, messageIds);\n const deletedForwardedPosts = Object.values(pickTruthy(byId, messageIds)).filter(\n ({ forwardInfo }) => forwardInfo?.isLinkedChannelPost,\n );\n\n const threadIds = Object.keys(global.messages.byChatId[chatId].threadsById).map(Number);\n threadIds.forEach((threadId) => {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n\n let listedIds = selectListedIds(global, chatId, threadId);\n let outlyingIds = selectOutlyingIds(global, chatId, threadId);\n let viewportIds = selectViewportIds(global, chatId, threadId);\n let pinnedIds = selectPinnedIds(global, chatId);\n let newMessageCount = threadInfo?.messagesCount;\n\n messageIds.forEach((messageId) => {\n if (listedIds && listedIds.includes(messageId)) {\n listedIds = listedIds.filter((id) => id !== messageId);\n if (newMessageCount !== undefined) newMessageCount -= 1;\n }\n\n if (outlyingIds && outlyingIds.includes(messageId)) {\n outlyingIds = outlyingIds.filter((id) => id !== messageId);\n }\n\n if (viewportIds && viewportIds.includes(messageId)) {\n viewportIds = viewportIds.filter((id) => id !== messageId);\n }\n\n if (pinnedIds && pinnedIds.includes(messageId)) {\n pinnedIds = pinnedIds.filter((id) => id !== messageId);\n }\n });\n\n global = replaceThreadParam(global, chatId, threadId, 'listedIds', listedIds);\n global = replaceThreadParam(global, chatId, threadId, 'outlyingIds', outlyingIds);\n global = replaceThreadParam(global, chatId, threadId, 'viewportIds', viewportIds);\n global = replaceThreadParam(global, chatId, threadId, 'pinnedIds', pinnedIds);\n\n if (threadInfo && newMessageCount !== undefined) {\n global = replaceThreadParam(global, chatId, threadId, 'threadInfo', {\n ...threadInfo,\n messagesCount: newMessageCount,\n });\n }\n });\n\n if (deletedForwardedPosts.length) {\n const currentMessageList = selectCurrentMessageList(global);\n const canDeleteCurrentThread = currentMessageList && currentMessageList.chatId === chatId\n && currentMessageList.type === 'thread';\n const currentThreadId = currentMessageList?.threadId;\n\n deletedForwardedPosts.forEach((message) => {\n const { fromChatId, fromMessageId } = message.forwardInfo!;\n const originalPost = selectChatMessage(global, fromChatId!, fromMessageId!);\n\n if (canDeleteCurrentThread && currentThreadId === fromMessageId) {\n global = updateCurrentMessageList(global, chatId);\n }\n if (originalPost) {\n global = updateChatMessage(global, fromChatId!, fromMessageId!, { threadInfo: undefined });\n }\n });\n }\n\n global = replaceChatMessages(global, chatId, newById);\n\n return global;\n}\n\nexport function deleteChatScheduledMessages(\n global: GlobalState,\n chatId: string,\n messageIds: number[],\n): GlobalState {\n const byId = selectScheduledMessages(global, chatId);\n if (!byId) {\n return global;\n }\n const newById = omit(byId, messageIds);\n\n let scheduledIds = selectScheduledIds(global, chatId);\n if (scheduledIds) {\n messageIds.forEach((messageId) => {\n if (scheduledIds!.includes(messageId)) {\n scheduledIds = scheduledIds!.filter((id) => id !== messageId);\n }\n });\n global = replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'scheduledIds', scheduledIds);\n }\n\n global = replaceScheduledMessages(global, chatId, newById);\n\n return global;\n}\n\nexport function updateListedIds(\n global: GlobalState,\n chatId: string,\n threadId: number,\n idsUpdate: number[],\n): GlobalState {\n const listedIds = selectListedIds(global, chatId, threadId);\n const newIds = listedIds?.length\n ? idsUpdate.filter((id) => !listedIds.includes(id))\n : idsUpdate;\n\n if (listedIds && !newIds.length) {\n return global;\n }\n\n return replaceThreadParam(global, chatId, threadId, 'listedIds', orderHistoryIds([\n ...(listedIds || []),\n ...newIds,\n ]));\n}\n\nexport function updateOutlyingIds(\n global: GlobalState,\n chatId: string,\n threadId: number,\n idsUpdate: number[],\n): GlobalState {\n const outlyingIds = selectOutlyingIds(global, chatId, threadId);\n const newIds = outlyingIds?.length\n ? idsUpdate.filter((id) => !outlyingIds.includes(id))\n : idsUpdate;\n\n if (outlyingIds && !newIds.length) {\n return global;\n }\n\n return replaceThreadParam(global, chatId, threadId, 'outlyingIds', orderHistoryIds([\n ...(outlyingIds || []),\n ...newIds,\n ]));\n}\n\nfunction orderHistoryIds(listedIds: number[]) {\n return listedIds.sort((a, b) => a - b);\n}\n\nexport function addViewportId(\n global: GlobalState,\n chatId: string,\n threadId: number,\n newId: number,\n): GlobalState {\n const viewportIds = selectViewportIds(global, chatId, threadId) || [];\n if (viewportIds.includes(newId)) {\n return global;\n }\n\n const newIds = orderHistoryIds([\n ...(\n viewportIds.length < MESSAGE_LIST_VIEWPORT_LIMIT\n ? viewportIds\n : viewportIds.slice(-(MESSAGE_LIST_SLICE / 2))\n ),\n newId,\n ]);\n\n return replaceThreadParam(global, chatId, threadId, 'viewportIds', newIds);\n}\n\nexport function safeReplaceViewportIds(\n global: GlobalState,\n chatId: string,\n threadId: number,\n newViewportIds: number[],\n): GlobalState {\n const currentIds = selectViewportIds(global, chatId, threadId) || [];\n const newIds = orderHistoryIds(newViewportIds);\n\n return replaceThreadParam(\n global,\n chatId,\n threadId,\n 'viewportIds',\n areSortedArraysEqual(currentIds, newIds) ? currentIds : newIds,\n );\n}\n\nexport function updateThreadInfo(\n global: GlobalState, chatId: string, threadId: number, update: Partial | undefined,\n): GlobalState {\n const newThreadInfo = {\n ...(selectThreadInfo(global, chatId, threadId) as ApiThreadInfo),\n ...update,\n };\n\n if (!newThreadInfo.threadId) {\n return global;\n }\n\n return replaceThreadParam(global, chatId, threadId, 'threadInfo', newThreadInfo);\n}\n\nexport function updateThreadInfos(\n global: GlobalState, chatId: string, updates: Partial[],\n): GlobalState {\n updates.forEach((update) => {\n global = updateThreadInfo(global, update.chatId!, update.threadId!, update);\n });\n\n return global;\n}\n\nexport function replaceScheduledMessages(\n global: GlobalState, chatId: string, newById: Record,\n): GlobalState {\n return updateScheduledMessages(global, chatId, {\n byId: newById,\n });\n}\n\nfunction updateScheduledMessages(\n global: GlobalState, chatId: string, update: Partial<{ byId: Record }>,\n): GlobalState {\n const current = global.scheduledMessages.byChatId[chatId] || { byId: {}, hash: 0 };\n\n return {\n ...global,\n scheduledMessages: {\n byChatId: {\n ...global.scheduledMessages.byChatId,\n [chatId]: {\n ...current,\n ...update,\n },\n },\n },\n };\n}\n\nexport function updateFocusedMessage(\n global: GlobalState, chatId?: string, messageId?: number, noHighlight = false, isResizingContainer = false,\n): GlobalState {\n return {\n ...global,\n focusedMessage: {\n ...global.focusedMessage,\n chatId,\n messageId,\n noHighlight,\n isResizingContainer,\n },\n };\n}\n\nexport function updateFocusDirection(\n global: GlobalState, direction?: FocusDirection,\n): GlobalState {\n return {\n ...global,\n focusedMessage: {\n ...global.focusedMessage,\n direction,\n },\n };\n}\n\nexport function enterMessageSelectMode(\n global: GlobalState,\n chatId: string,\n messageId?: number | number[],\n): GlobalState {\n const messageIds = messageId ? Array.prototype.concat([], messageId) : [];\n return {\n ...global,\n selectedMessages: {\n chatId,\n messageIds,\n },\n };\n}\n\nexport function toggleMessageSelection(\n global: GlobalState,\n chatId: string,\n threadId: number,\n messageListType: MessageListType,\n messageId: number,\n groupedId?: string,\n childMessageIds?: number[],\n withShift = false,\n): GlobalState {\n const { selectedMessages: oldSelectedMessages } = global;\n if (groupedId) {\n childMessageIds = selectMessageIdsByGroupId(global, chatId, groupedId);\n }\n const selectedMessageIds = childMessageIds || [messageId];\n if (!oldSelectedMessages) {\n return enterMessageSelectMode(global, chatId, selectedMessageIds);\n }\n\n const { messageIds } = oldSelectedMessages;\n\n let newMessageIds;\n const newSelectedMessageIds = selectedMessageIds.filter((id) => !messageIds.includes(id));\n if (newSelectedMessageIds && !newSelectedMessageIds.length) {\n newMessageIds = messageIds.filter((id) => !selectedMessageIds.includes(id));\n } else if (withShift && messageIds.length) {\n const viewportIds = selectCurrentMessageIds(global, chatId, threadId, messageListType)!;\n const prevIndex = viewportIds.indexOf(messageIds[messageIds.length - 1]);\n const currentIndex = viewportIds.indexOf(messageId);\n const from = Math.min(prevIndex, currentIndex);\n const to = Math.max(prevIndex, currentIndex);\n const slice = viewportIds.slice(from, to + 1);\n newMessageIds = unique([...messageIds, ...slice]);\n } else {\n newMessageIds = [...messageIds, ...newSelectedMessageIds];\n }\n\n if (!newMessageIds.length) {\n return exitMessageSelectMode(global);\n }\n\n return {\n ...global,\n selectedMessages: {\n ...oldSelectedMessages,\n messageIds: newMessageIds,\n },\n };\n}\n\nexport function exitMessageSelectMode(global: GlobalState): GlobalState {\n return {\n ...global,\n selectedMessages: undefined,\n };\n}\n\nexport function updateThreadUnreadFromForwardedMessage(\n global: GlobalState,\n originMessage: ApiMessage,\n chatId: string,\n lastMessageId: number,\n isDeleting?: boolean,\n) {\n const { channelPostId, fromChatId } = originMessage.forwardInfo || {};\n if (channelPostId && fromChatId) {\n const threadInfoOld = selectThreadInfo(global, chatId, channelPostId);\n if (threadInfoOld) {\n global = replaceThreadParam(global, chatId, channelPostId, 'threadInfo', {\n ...threadInfoOld,\n lastMessageId,\n messagesCount: threadInfoOld.messagesCount + (isDeleting ? -1 : 1),\n });\n }\n }\n return global;\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiSticker, ApiStickerSet, ApiVideo } from '../../api/types';\nimport { buildCollectionByKey, unique } from '../../util/iteratees';\nimport { selectStickersForEmoji } from '../selectors';\n\nexport function updateStickerSets(\n global: GlobalState,\n category: 'added' | 'featured' | 'search',\n hash: string,\n sets: ApiStickerSet[],\n resultIds?: string[],\n): GlobalState {\n const updatedSets = sets.map((stickerSet) => {\n const existing = global.stickers.setsById[stickerSet.id];\n if (!existing) {\n return stickerSet;\n }\n\n return {\n ...existing,\n ...stickerSet,\n };\n });\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n setsById: {\n ...global.stickers.setsById,\n ...buildCollectionByKey(updatedSets, 'id'),\n },\n [category]: {\n ...global.stickers[category],\n hash,\n ...(\n category === 'search'\n ? { resultIds }\n : { setIds: sets.map(({ id }) => id) }\n ),\n },\n },\n };\n}\n\nexport function updateStickerSet(\n global: GlobalState, stickerSetId: string, update: Partial,\n): GlobalState {\n const currentStickerSet = global.stickers.setsById[stickerSetId] || {};\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n setsById: {\n ...global.stickers.setsById,\n [stickerSetId]: {\n ...currentStickerSet,\n ...update,\n },\n },\n },\n };\n}\n\nexport function updateGifSearch(\n global: GlobalState, isNew: boolean, results: ApiVideo[], nextOffset?: string,\n): GlobalState {\n const { results: currentResults } = global.gifs.search;\n\n let newResults!: ApiVideo[];\n if (isNew || !currentResults) {\n newResults = results;\n } else {\n const currentIds = new Set(currentResults.map((gif) => gif.id));\n newResults = [\n ...currentResults,\n ...results.filter((gif) => !currentIds.has(gif.id)),\n ];\n }\n\n return {\n ...global,\n gifs: {\n ...global.gifs,\n search: {\n ...global.gifs.search,\n offset: nextOffset,\n results: newResults,\n },\n },\n };\n}\n\nexport function replaceAnimatedEmojis(global: GlobalState, stickerSet: ApiStickerSet): GlobalState {\n return {\n ...global,\n animatedEmojis: stickerSet,\n };\n}\n\nexport function updateStickersForEmoji(\n global: GlobalState, emoji: string, remoteStickers?: ApiSticker[], hash?: string,\n): GlobalState {\n const localStickers = selectStickersForEmoji(global, emoji);\n const allStickers = [...localStickers, ...(remoteStickers || [])];\n const uniqueIds = unique(allStickers.map(({ id }) => id));\n const byId = buildCollectionByKey(allStickers, 'id');\n const stickers = uniqueIds.map((id) => byId[id]);\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n forEmoji: {\n emoji,\n stickers,\n hash,\n },\n },\n };\n}\n\nexport function rebuildStickersForEmoji(global: GlobalState): GlobalState {\n const { emoji, stickers, hash } = global.stickers.forEmoji || {};\n if (!emoji) {\n return global;\n }\n\n return updateStickersForEmoji(global, emoji, stickers, hash);\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiUser } from '../../api/types';\n\nimport { omit } from '../../util/iteratees';\nimport { MEMO_EMPTY_ARRAY } from '../../util/memo';\n\nexport function replaceUsers(global: GlobalState, newById: Record): GlobalState {\n return {\n ...global,\n users: {\n ...global.users,\n byId: newById,\n },\n };\n}\n\n// @optimization Don't spread/unspread global for each element, do it in a batch\nfunction getUpdatedUser(global: GlobalState, userId: string, userUpdate: Partial): ApiUser {\n const { byId } = global.users;\n const user = byId[userId];\n const shouldOmitMinInfo = userUpdate.isMin && user && !user.isMin;\n\n const updatedUser = {\n ...user,\n ...(shouldOmitMinInfo ? omit(userUpdate, ['isMin', 'accessHash']) : userUpdate),\n };\n\n if (!updatedUser.id || !updatedUser.type) {\n return user;\n }\n\n return updatedUser;\n}\n\nfunction updateContactList(global: GlobalState, updatedUsers: ApiUser[]): GlobalState {\n const { userIds: contactUserIds } = global.contactList || {};\n\n if (!contactUserIds) return global;\n\n const newContactUserIds = updatedUsers\n .filter((user) => user?.isContact && !contactUserIds.includes(user.id))\n .map((user) => user.id);\n\n if (newContactUserIds.length === 0) return global;\n\n return {\n ...global,\n contactList: {\n userIds: [\n ...newContactUserIds,\n ...contactUserIds,\n ],\n },\n };\n}\n\nexport function updateUser(global: GlobalState, userId: string, userUpdate: Partial): GlobalState {\n const { byId } = global.users;\n\n const updatedUser = getUpdatedUser(global, userId, userUpdate);\n\n global = updateContactList(global, [updatedUser]);\n\n return replaceUsers(global, {\n ...byId,\n [userId]: updatedUser,\n });\n}\n\nexport function updateUsers(global: GlobalState, updatedById: Record): GlobalState {\n const updatedUsers = Object.keys(updatedById).reduce>((acc, id) => {\n const updatedUser = getUpdatedUser(global, id, updatedById[id]);\n if (updatedUser) {\n acc[id] = updatedUser;\n }\n return acc;\n }, {});\n\n global = updateContactList(global, Object.values(updatedUsers));\n\n global = replaceUsers(global, {\n ...global.users.byId,\n ...updatedUsers,\n });\n\n return global;\n}\n\n// @optimization Allows to avoid redundant updates which cause a lot of renders\nexport function addUsers(global: GlobalState, addedById: Record): GlobalState {\n const { byId } = global.users;\n let isAdded = false;\n\n const addedUsers = Object.keys(addedById).reduce>((acc, id) => {\n if (!byId[id] || (byId[id].isMin && !addedById[id].isMin)) {\n const updatedUser = getUpdatedUser(global, id, addedById[id]);\n if (updatedUser) {\n acc[id] = updatedUser;\n\n if (!isAdded) {\n isAdded = true;\n }\n }\n }\n return acc;\n }, {});\n\n if (isAdded) {\n global = replaceUsers(global, {\n ...global.users.byId,\n ...addedUsers,\n });\n\n global = updateContactList(global, Object.values(addedUsers));\n }\n\n return global;\n}\n\nexport function updateSelectedUserId(global: GlobalState, selectedId?: string): GlobalState {\n if (global.users.selectedId === selectedId) {\n return global;\n }\n\n return {\n ...global,\n users: {\n ...global.users,\n selectedId,\n },\n };\n}\n\nexport function deleteUser(global: GlobalState, userId: string): GlobalState {\n const { byId } = global.users;\n const { userIds } = global.contactList || {};\n delete byId[userId];\n\n global = {\n ...global,\n contactList: {\n userIds: userIds ? userIds.filter((id) => id !== userId) : MEMO_EMPTY_ARRAY,\n },\n };\n\n return replaceUsers(global, byId);\n}\n\nexport function updateUserSearch(\n global: GlobalState,\n searchStatePartial: Partial,\n) {\n return {\n ...global,\n userSearch: {\n ...global.userSearch,\n ...searchStatePartial,\n },\n };\n}\n\nexport function updateUserSearchFetchingStatus(\n global: GlobalState, newState: boolean,\n) {\n return updateUserSearch(global, {\n fetchingStatus: newState,\n });\n}\n\nexport function updateUserBlockedState(global: GlobalState, userId: string, isBlocked: boolean) {\n const { byId } = global.users;\n const user = byId[userId];\n if (!user || !user.fullInfo) {\n return global;\n }\n\n return updateUser(global, userId, {\n ...user,\n fullInfo: {\n ...user.fullInfo,\n isBlocked,\n },\n });\n}\n","import { GlobalState } from '../../global/types';\nimport { GlobalSearchContent } from '../../types';\nimport { ApiGlobalMessageSearchType, ApiMessage } from '../../api/types';\nimport { areSortedArraysEqual } from '../../util/iteratees';\n\nconst getComplexKey = (message: ApiMessage) => `${message.chatId}_${message.id}`;\n\nexport function updateGlobalSearch(\n global: GlobalState,\n searchStatePartial: Partial,\n) {\n return {\n ...global,\n globalSearch: {\n ...global.globalSearch,\n ...searchStatePartial,\n },\n };\n}\n\nexport function updateGlobalSearchContent(\n global: GlobalState,\n currentContent: GlobalSearchContent | undefined,\n): GlobalState {\n return updateGlobalSearch(global, { currentContent });\n}\n\nexport function updateGlobalSearchResults(\n global: GlobalState,\n newFoundMessages: ApiMessage[],\n totalCount: number,\n type: ApiGlobalMessageSearchType,\n nextRate?: number,\n): GlobalState {\n const { resultsByType } = global.globalSearch || {};\n const newFoundMessagesById = newFoundMessages.reduce((result, message) => {\n result[getComplexKey(message)] = message;\n\n return result;\n }, {} as Record);\n const foundIdsForType = resultsByType?.[type]?.foundIds;\n\n if (foundIdsForType !== undefined\n && Object.keys(newFoundMessagesById).every(\n (newId) => foundIdsForType.includes(getComplexKey(newFoundMessagesById[newId])),\n )\n ) {\n return updateGlobalSearchFetchingStatus(global, { messages: false });\n }\n\n const prevFoundIds = foundIdsForType || [];\n const newFoundIds = newFoundMessages.map((message) => getComplexKey(message));\n const foundIds = Array.prototype.concat(prevFoundIds, newFoundIds);\n const foundOrPrevFoundIds = areSortedArraysEqual(prevFoundIds, foundIds) ? prevFoundIds : foundIds;\n\n global = updateGlobalSearchFetchingStatus(global, { messages: false });\n\n return updateGlobalSearch(global, {\n resultsByType: {\n ...(global.globalSearch || {}).resultsByType,\n [type]: {\n totalCount,\n nextOffsetId: nextRate,\n foundIds: foundOrPrevFoundIds,\n },\n },\n });\n}\n\nexport function updateGlobalSearchFetchingStatus(\n global: GlobalState, newState: { chats?: boolean; messages?: boolean },\n) {\n return updateGlobalSearch(global, {\n fetchingStatus: {\n ...global.globalSearch.fetchingStatus,\n ...newState,\n },\n });\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiMessageSearchType } from '../../api/types';\n\nimport { areSortedArraysEqual, unique } from '../../util/iteratees';\nimport { SharedMediaType } from '../../types';\nimport { buildChatThreadKey } from '../helpers';\n\ninterface TextSearchParams {\n isActive: boolean;\n query?: string;\n results?: {\n totalCount?: number;\n nextOffsetId?: number;\n foundIds?: number[];\n };\n}\n\ninterface MediaSearchParams {\n currentType?: SharedMediaType;\n resultsByType?: Partial>;\n}\n\nfunction replaceLocalTextSearch(\n global: GlobalState,\n chatThreadKey: string,\n searchParams: TextSearchParams,\n): GlobalState {\n return {\n ...global,\n localTextSearch: {\n byChatThreadKey: {\n ...global.localTextSearch.byChatThreadKey,\n [chatThreadKey]: searchParams,\n },\n },\n };\n}\n\nexport function updateLocalTextSearch(\n global: GlobalState,\n chatId: string,\n threadId: number,\n isActive: boolean,\n query?: string,\n): GlobalState {\n const chatThreadKey = buildChatThreadKey(chatId, threadId);\n\n return replaceLocalTextSearch(global, chatThreadKey, {\n ...global.localTextSearch.byChatThreadKey[chatThreadKey],\n isActive,\n query,\n });\n}\n\nexport function replaceLocalTextSearchResults(\n global: GlobalState,\n chatId: string,\n threadId: number,\n foundIds?: number[],\n totalCount?: number,\n nextOffsetId?: number,\n): GlobalState {\n const chatThreadKey = buildChatThreadKey(chatId, threadId);\n\n return replaceLocalTextSearch(global, chatThreadKey, {\n ...global.localTextSearch.byChatThreadKey[chatThreadKey],\n results: {\n foundIds,\n totalCount,\n nextOffsetId,\n },\n });\n}\n\nexport function updateLocalTextSearchResults(\n global: GlobalState,\n chatId: string,\n threadId: number,\n newFoundIds: number[],\n totalCount?: number,\n nextOffsetId?: number,\n): GlobalState {\n const chatThreadKey = buildChatThreadKey(chatId, threadId);\n const { results } = global.localTextSearch.byChatThreadKey[chatThreadKey] || {};\n const prevFoundIds = (results?.foundIds) || [];\n const foundIds = orderFoundIds(unique(Array.prototype.concat(prevFoundIds, newFoundIds)));\n const foundOrPrevFoundIds = areSortedArraysEqual(prevFoundIds, foundIds) ? prevFoundIds : foundIds;\n\n return replaceLocalTextSearchResults(global, chatId, threadId, foundOrPrevFoundIds, totalCount, nextOffsetId);\n}\n\nfunction replaceLocalMediaSearch(\n global: GlobalState,\n chatId: string,\n searchParams: MediaSearchParams,\n): GlobalState {\n return {\n ...global,\n localMediaSearch: {\n byChatId: {\n ...global.localMediaSearch.byChatId,\n [chatId]: searchParams,\n },\n },\n };\n}\n\nexport function updateLocalMediaSearchType(\n global: GlobalState,\n chatId: string,\n currentType: SharedMediaType | undefined,\n): GlobalState {\n return replaceLocalMediaSearch(global, chatId, {\n ...global.localMediaSearch.byChatId[chatId],\n currentType,\n });\n}\n\nexport function replaceLocalMediaSearchResults(\n global: GlobalState,\n chatId: string,\n type: ApiMessageSearchType,\n foundIds?: number[],\n totalCount?: number,\n nextOffsetId?: number,\n): GlobalState {\n return replaceLocalMediaSearch(global, chatId, {\n ...global.localMediaSearch.byChatId[chatId],\n resultsByType: {\n ...(global.localMediaSearch.byChatId[chatId] || {}).resultsByType,\n [type]: {\n foundIds,\n totalCount,\n nextOffsetId,\n },\n },\n });\n}\n\nexport function updateLocalMediaSearchResults(\n global: GlobalState,\n chatId: string,\n type: SharedMediaType,\n newFoundIds: number[],\n totalCount?: number,\n nextOffsetId?: number,\n): GlobalState {\n const { resultsByType } = global.localMediaSearch.byChatId[chatId] || {};\n const prevFoundIds = resultsByType?.[type] ? resultsByType[type]!.foundIds : [];\n const foundIds = orderFoundIds(unique(Array.prototype.concat(prevFoundIds, newFoundIds)));\n const foundOrPrevFoundIds = areSortedArraysEqual(prevFoundIds, foundIds) ? prevFoundIds : foundIds;\n\n return replaceLocalMediaSearchResults(global, chatId, type, foundOrPrevFoundIds, totalCount, nextOffsetId);\n}\n\nfunction orderFoundIds(listedIds: number[]) {\n return listedIds.sort((a, b) => a - b);\n}\n","import { GlobalState } from '../../global/types';\nimport { ManagementProgress } from '../../types';\n\ninterface ManagementState {\n isActive: boolean;\n isUsernameAvailable?: boolean;\n error?: string;\n}\n\nexport function updateManagementProgress(global: GlobalState, progress: ManagementProgress): GlobalState {\n return {\n ...global,\n management: {\n ...global.management,\n progress,\n },\n };\n}\n\nexport function updateManagement(global: GlobalState, chatId: string, update: Partial): GlobalState {\n return {\n ...global,\n management: {\n ...global.management,\n byChatId: {\n ...global.management.byChatId,\n [chatId]: {\n ...(global.management.byChatId[chatId] || {}),\n ...update,\n },\n },\n },\n };\n}\n","import { GlobalState } from '../../global/types';\nimport {\n ISettings, IThemeSettings, ThemeKey, NotifyException,\n} from '../../types';\nimport { ApiNotifyException } from '../../api/types';\nimport { updateUserBlockedState } from './users';\n\nexport function replaceSettings(global: GlobalState, newSettings?: Partial): GlobalState {\n return {\n ...global,\n settings: {\n ...global.settings,\n byKey: {\n ...global.settings.byKey,\n ...newSettings,\n },\n },\n };\n}\n\nexport function replaceThemeSettings(\n global: GlobalState, theme: ThemeKey, newSettings?: Partial,\n): GlobalState {\n return {\n ...global,\n settings: {\n ...global.settings,\n themes: {\n ...global.settings.themes,\n [theme]: {\n ...(global.settings.themes[theme] || {}),\n ...newSettings,\n },\n },\n },\n };\n}\n\nexport function addNotifyExceptions(\n global: GlobalState, notifyExceptions: ApiNotifyException[],\n): GlobalState {\n notifyExceptions.forEach((notifyException) => {\n const { chatId, ...exceptionData } = notifyException;\n global = addNotifyException(global, chatId, exceptionData);\n });\n\n return global;\n}\n\nexport function addNotifyException(\n global: GlobalState, id: string, notifyException: NotifyException,\n): GlobalState {\n return {\n ...global,\n settings: {\n ...global.settings,\n notifyExceptions: {\n ...global.settings.notifyExceptions,\n [id]: notifyException,\n },\n },\n };\n}\n\nexport function updateNotifySettings(\n global: GlobalState, peerType: 'contact' | 'group' | 'broadcast', isSilent?: boolean, shouldShowPreviews?: boolean,\n) {\n switch (peerType) {\n case 'contact':\n return replaceSettings(global, {\n ...(typeof isSilent !== 'undefined' && { hasPrivateChatsNotifications: !isSilent }),\n ...(typeof shouldShowPreviews !== 'undefined' && { hasPrivateChatsMessagePreview: shouldShowPreviews }),\n });\n case 'group':\n return replaceSettings(global, {\n ...(typeof isSilent !== 'undefined' && { hasGroupNotifications: !isSilent }),\n ...(typeof shouldShowPreviews !== 'undefined' && { hasGroupMessagePreview: shouldShowPreviews }),\n });\n case 'broadcast':\n return replaceSettings(global, {\n ...(typeof isSilent !== 'undefined' && { hasBroadcastNotifications: !isSilent }),\n ...(typeof shouldShowPreviews !== 'undefined' && { hasBroadcastMessagePreview: shouldShowPreviews }),\n });\n\n default:\n return undefined;\n }\n}\n\nexport function addBlockedContact(global: GlobalState, contactId: string): GlobalState {\n global = updateUserBlockedState(global, contactId, true);\n\n return {\n ...global,\n blocked: {\n ...global.blocked,\n ids: [contactId, ...global.blocked.ids],\n totalCount: global.blocked.totalCount + 1,\n },\n };\n}\n\nexport function removeBlockedContact(global: GlobalState, contactId: string): GlobalState {\n global = updateUserBlockedState(global, contactId, false);\n\n return {\n ...global,\n blocked: {\n ...global.blocked,\n ids: global.blocked.ids.filter((id) => id !== contactId),\n totalCount: global.blocked.totalCount - 1,\n },\n };\n}\n","import { GlobalState } from '../../global/types';\n\nexport function updateTwoFaSettings(\n global: GlobalState,\n update: GlobalState['twoFaSettings'],\n): GlobalState {\n return {\n ...global,\n twoFaSettings: {\n ...global.twoFaSettings,\n ...update,\n },\n };\n}\n","import { GlobalState } from '../../global/types';\nimport { ShippingOption, PaymentStep } from '../../types';\nimport { ApiMessage, ApiPaymentForm, ApiReceipt } from '../../api/types';\n\nexport function updateShippingOptions(\n global: GlobalState,\n shippingOptions: ShippingOption[],\n): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n shippingOptions,\n },\n };\n}\n\nexport function setRequestInfoId(global: GlobalState, id: string): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n requestId: id,\n },\n };\n}\n\nexport function setPaymentStep(global: GlobalState, step: PaymentStep): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n step,\n },\n };\n}\n\nexport function setInvoiceMessageInfo(global: GlobalState, message: ApiMessage): GlobalState {\n if (!message.content || !message.content.invoice) {\n return global;\n }\n const {\n title,\n text,\n amount,\n currency,\n isTest,\n photoUrl,\n } = message.content.invoice;\n return {\n ...global,\n payment: {\n ...global.payment,\n invoiceContent: {\n title,\n text,\n photoUrl,\n amount,\n currency,\n isTest,\n },\n },\n };\n}\n\nexport function setStripeCardInfo(global: GlobalState, cardInfo: { type: string; id: string }): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n stripeCredentials: {\n ...cardInfo,\n },\n },\n };\n}\n\nexport function setPaymentForm(global: GlobalState, form: ApiPaymentForm): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n ...form,\n },\n };\n}\n\nexport function setReceipt(\n global: GlobalState,\n receipt?: ApiReceipt,\n message?: ApiMessage,\n): GlobalState {\n if (!receipt || !message) {\n return {\n ...global,\n payment: {\n ...global.payment,\n receipt: undefined,\n },\n };\n }\n\n const { invoice: messageInvoice } = message.content;\n const { photoUrl, text, title } = (messageInvoice || {});\n\n return {\n ...global,\n payment: {\n ...global.payment,\n receipt: {\n ...receipt,\n photoUrl,\n text,\n title,\n },\n },\n };\n}\n\nexport function clearPayment(global: GlobalState): GlobalState {\n return {\n ...global,\n payment: {},\n };\n}\n\nexport function closeInvoice(global: GlobalState): GlobalState {\n return {\n ...global,\n payment: {\n ...global.payment,\n isPaymentModalOpen: false,\n },\n };\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiChat, ApiUser } from '../../api/types';\n\nexport function selectUser(global: GlobalState, userId: string): ApiUser | undefined {\n return global.users.byId[userId];\n}\n\nexport function selectIsUserBlocked(global: GlobalState, userId: string) {\n const user = selectUser(global, userId);\n\n return user?.fullInfo?.isBlocked;\n}\n\n// Slow, not to be used in `withGlobal`\nexport function selectUserByUsername(global: GlobalState, username: string) {\n const usernameLowered = username.toLowerCase();\n return Object.values(global.users.byId).find(\n (user) => user.username.toLowerCase() === usernameLowered,\n );\n}\n\nexport function selectIsUserOrChatContact(global: GlobalState, userOrChat: ApiUser | ApiChat) {\n return global.contactList && global.contactList.userIds.includes(userOrChat.id);\n}\n","import { GlobalState } from '../../global/types';\n\nexport function selectNotifySettings(global: GlobalState) {\n return global.settings.byKey;\n}\n\nexport function selectNotifyExceptions(global: GlobalState) {\n return global.settings.notifyExceptions;\n}\n","import { ApiChat, MAIN_THREAD_ID } from '../../api/types';\nimport { GlobalState } from '../../global/types';\n\nimport {\n getPrivateChatUserId, isChatChannel, isUserId, isHistoryClearMessage, isUserBot, isUserOnline, selectIsChatMuted,\n} from '../helpers';\nimport { selectUser } from './users';\nimport {\n ALL_FOLDER_ID, ARCHIVED_FOLDER_ID, MEMBERS_LOAD_SLICE, SERVICE_NOTIFICATIONS_USER_ID,\n} from '../../config';\nimport { selectNotifyExceptions, selectNotifySettings } from './settings';\n\nexport function selectChat(global: GlobalState, chatId: string): ApiChat | undefined {\n return global.chats.byId[chatId];\n}\n\nexport function selectChatUser(global: GlobalState, chat: ApiChat) {\n const userId = getPrivateChatUserId(chat);\n if (!userId) {\n return false;\n }\n\n return selectUser(global, userId);\n}\n\nexport function selectIsChatWithSelf(global: GlobalState, chatId: string) {\n return chatId === global.currentUserId;\n}\n\nexport function selectIsChatWithBot(global: GlobalState, chat: ApiChat) {\n const user = selectChatUser(global, chat);\n return user && isUserBot(user);\n}\n\nexport function selectSupportChat(global: GlobalState) {\n return Object.values(global.chats.byId).find(({ isSupport }: ApiChat) => isSupport);\n}\n\nexport function selectChatOnlineCount(global: GlobalState, chat: ApiChat) {\n if (isUserId(chat.id) || isChatChannel(chat) || !chat.fullInfo) {\n return undefined;\n }\n\n if (!chat.fullInfo.members || chat.fullInfo.members.length === MEMBERS_LOAD_SLICE) {\n return chat.fullInfo.onlineCount;\n }\n\n return chat.fullInfo.members.reduce((onlineCount, { userId }) => {\n if (global.users.byId[userId] && isUserOnline(global.users.byId[userId]) && userId !== global.currentUserId) {\n return onlineCount + 1;\n }\n\n return onlineCount;\n }, 0);\n}\n\nexport function selectChatBot(global: GlobalState, chatId: string) {\n const chat = selectChat(global, chatId);\n const userId = chat && getPrivateChatUserId(chat);\n const user = userId && selectUser(global, userId);\n if (!user || !isUserBot(user)) {\n return undefined;\n }\n\n return user;\n}\n\nexport function selectIsChatBotNotStarted(global: GlobalState, chatId: string) {\n const chat = selectChat(global, chatId);\n const bot = selectChatBot(global, chatId);\n if (!chat || !bot) {\n return false;\n }\n\n if (chat.lastMessage && isHistoryClearMessage(chat.lastMessage)) {\n return true;\n }\n\n const messageInfo = global.messages.byChatId[chatId];\n if (!messageInfo) {\n return false;\n }\n\n const { listedIds } = messageInfo.threadsById[MAIN_THREAD_ID] || {};\n return listedIds && !listedIds.length;\n}\n\nexport function selectAreActiveChatsLoaded(global: GlobalState): boolean {\n return Boolean(global.chats.listIds.active);\n}\n\nexport function selectIsChatListed(global: GlobalState, chatId: string, type?: 'active' | 'archived'): boolean {\n const { listIds } = global.chats;\n if (type) {\n const targetList = listIds[type];\n return Boolean(targetList && targetList.includes(chatId));\n }\n\n return Object.values(listIds).some((list) => list && list.includes(chatId));\n}\n\nexport function selectChatListType(global: GlobalState, chatId: string): 'active' | 'archived' | undefined {\n const chat = selectChat(global, chatId);\n if (!chat || !selectIsChatListed(global, chatId)) {\n return undefined;\n }\n\n return chat.folderId === ARCHIVED_FOLDER_ID ? 'archived' : 'active';\n}\n\nexport function selectChatFolder(global: GlobalState, folderId: number) {\n return global.chatFolders.byId[folderId];\n}\n\nexport function selectTotalChatCount(global: GlobalState, listType: 'active' | 'archived'): number {\n const { totalCount } = global.chats;\n const allChatsCount = totalCount.all;\n const archivedChatsCount = totalCount.archived || 0;\n\n if (listType === 'archived') {\n return archivedChatsCount;\n }\n\n return allChatsCount ? allChatsCount - archivedChatsCount : 0;\n}\n\nexport function selectIsChatPinned(global: GlobalState, chatId: string, folderId = ALL_FOLDER_ID): boolean {\n const { active, archived } = global.chats.orderedPinnedIds;\n\n if (folderId === ALL_FOLDER_ID) {\n return !!active && active.includes(chatId);\n }\n\n if (folderId === ARCHIVED_FOLDER_ID) {\n return !!archived && archived.includes(chatId);\n }\n\n const { byId: chatFoldersById } = global.chatFolders;\n\n const { pinnedChatIds } = chatFoldersById[folderId] || {};\n return !!pinnedChatIds && pinnedChatIds.includes(chatId);\n}\n\n// Slow, not to be used in `withGlobal`\nexport function selectChatByUsername(global: GlobalState, username: string) {\n const usernameLowered = username.toLowerCase();\n return Object.values(global.chats.byId).find(\n (chat) => chat.username && chat.username.toLowerCase() === usernameLowered,\n );\n}\n\n// Slow, not to be used in `withGlobal`\nexport function selectCountNotMutedUnread(global: GlobalState) {\n const activeChatIds = global.chats.listIds.active;\n if (!activeChatIds) {\n return 0;\n }\n\n const chats = global.chats.byId;\n const notifySettings = selectNotifySettings(global);\n const notifyExceptions = selectNotifyExceptions(global);\n\n return activeChatIds.reduce((acc, chatId) => {\n const chat = chats[chatId];\n\n if (\n chat\n && chat.unreadCount\n && chat.isListed\n && !chat.isNotJoined\n && !chat.isRestricted\n && (chat.unreadMentionsCount || !selectIsChatMuted(chat, notifySettings, notifyExceptions))\n ) {\n return acc + chat.unreadCount;\n }\n\n return acc;\n }, 0);\n}\n\nexport function selectIsServiceChatReady(global: GlobalState) {\n return Boolean(selectChat(global, SERVICE_NOTIFICATIONS_USER_ID));\n}\n","import { GlobalState } from '../../global/types';\nimport { ApiSticker } from '../../api/types';\n\nexport function selectIsStickerFavorite(global: GlobalState, sticker: ApiSticker) {\n const { stickers } = global.stickers.favorite;\n return stickers && stickers.some(({ id }) => id === sticker.id);\n}\n\nexport function selectCurrentStickerSearch(global: GlobalState) {\n return global.stickers.search;\n}\n\nexport function selectCurrentGifSearch(global: GlobalState) {\n return global.gifs.search;\n}\n\nexport function selectStickerSet(global: GlobalState, id: string) {\n return global.stickers.setsById[id];\n}\n\nexport function selectStickerSetByShortName(global: GlobalState, shortName: string) {\n return Object.values(global.stickers.setsById).find((l) => l.shortName.toLowerCase() === shortName.toLowerCase());\n}\n\nexport function selectStickersForEmoji(global: GlobalState, emoji: string) {\n const stickerSets = Object.values(global.stickers.setsById);\n let stickersForEmoji: ApiSticker[] = [];\n stickerSets.forEach(({ packs }) => {\n if (!packs) {\n return;\n }\n const stickers = packs[emoji];\n if (stickers) {\n stickersForEmoji = stickersForEmoji.concat(stickers);\n }\n });\n return stickersForEmoji;\n}\n\nexport function selectAnimatedEmoji(global: GlobalState, emoji: string) {\n const { animatedEmojis } = global;\n if (!animatedEmojis || !animatedEmojis.stickers) {\n return undefined;\n }\n\n // Some emojis (❤️ for example) with a service symbol 'VARIATION SELECTOR-16' are not recognized as animated\n const cleanedEmoji = emoji.replace('\\ufe0f', '');\n\n return animatedEmojis.stickers.find((sticker) => sticker.emoji === emoji || sticker.emoji === cleanedEmoji);\n}\n","import { GlobalState, MessageListType, Thread } from '../../global/types';\nimport {\n ApiChat,\n ApiMessage,\n ApiMessageOutgoingStatus,\n ApiUser,\n MAIN_THREAD_ID,\n} from '../../api/types';\n\nimport { LOCAL_MESSAGE_ID_BASE, SERVICE_NOTIFICATIONS_USER_ID } from '../../config';\nimport {\n selectChat, selectIsChatWithBot, selectIsChatWithSelf,\n} from './chats';\nimport { selectIsUserOrChatContact, selectUser } from './users';\nimport {\n getSendingState,\n isChatChannel,\n isMessageLocal,\n isUserId,\n isForwardedMessage,\n getCanPostInChat,\n isUserRightBanned,\n getHasAdminRight,\n isChatBasicGroup,\n isCommonBoxChat,\n isServiceNotificationMessage,\n isOwnMessage,\n isActionMessage,\n isChatGroup,\n isChatSuperGroup,\n getMessageVideo,\n getMessageWebPageVideo,\n getMessagePhoto,\n getMessageAudio,\n getMessageVoice,\n getMessageDocument,\n getMessageWebPagePhoto,\n} from '../helpers';\nimport { findLast } from '../../util/iteratees';\nimport { selectIsStickerFavorite } from './symbols';\nimport { getServerTime } from '../../util/serverTime';\nimport { MEMO_EMPTY_ARRAY } from '../../util/memo';\n\nconst MESSAGE_EDIT_ALLOWED_TIME = 172800; // 48 hours\n\nexport function selectCurrentMessageList(global: GlobalState) {\n const { messageLists } = global.messages;\n\n if (messageLists.length) {\n return messageLists[messageLists.length - 1];\n }\n\n return undefined;\n}\n\nexport function selectCurrentChat(global: GlobalState) {\n const { chatId } = selectCurrentMessageList(global) || {};\n\n return chatId ? selectChat(global, chatId) : undefined;\n}\n\nexport function selectChatMessages(global: GlobalState, chatId: string) {\n return global.messages.byChatId[chatId]?.byId;\n}\n\nexport function selectScheduledMessages(global: GlobalState, chatId: string) {\n return global.scheduledMessages.byChatId[chatId]?.byId;\n}\n\nexport function selectThreadParam(\n global: GlobalState,\n chatId: string,\n threadId: number,\n key: K,\n) {\n const messageInfo = global.messages.byChatId[chatId];\n if (!messageInfo) {\n return undefined;\n }\n\n const thread = messageInfo.threadsById[threadId];\n if (!thread) {\n return undefined;\n }\n\n return thread[key];\n}\n\nexport function selectListedIds(global: GlobalState, chatId: string, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'listedIds');\n}\n\nexport function selectOutlyingIds(global: GlobalState, chatId: string, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'outlyingIds');\n}\n\nexport function selectCurrentMessageIds(\n global: GlobalState, chatId: string, threadId: number, messageListType: MessageListType,\n) {\n switch (messageListType) {\n case 'thread':\n return selectViewportIds(global, chatId, threadId);\n case 'pinned':\n return selectPinnedIds(global, chatId);\n case 'scheduled':\n return selectScheduledIds(global, chatId);\n }\n\n return undefined;\n}\n\nexport function selectViewportIds(global: GlobalState, chatId: string, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'viewportIds');\n}\n\nexport function selectPinnedIds(global: GlobalState, chatId: string) {\n return selectThreadParam(global, chatId, MAIN_THREAD_ID, 'pinnedIds');\n}\n\nexport function selectScheduledIds(global: GlobalState, chatId: string) {\n return selectThreadParam(global, chatId, MAIN_THREAD_ID, 'scheduledIds');\n}\n\nexport function selectScrollOffset(global: GlobalState, chatId: string, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'scrollOffset');\n}\n\nexport function selectReplyingToId(global: GlobalState, chatId: string, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'replyingToId');\n}\n\nexport function selectEditingId(global: GlobalState, chatId: string, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'editingId');\n}\n\nexport function selectEditingScheduledId(global: GlobalState, chatId: string) {\n return selectThreadParam(global, chatId, MAIN_THREAD_ID, 'editingScheduledId');\n}\n\nexport function selectDraft(global: GlobalState, chatId: string, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'draft');\n}\n\nexport function selectNoWebPage(global: GlobalState, chatId: string, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'noWebPage');\n}\n\nexport function selectThreadInfo(global: GlobalState, chatId: string, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'threadInfo');\n}\n\nexport function selectFirstMessageId(global: GlobalState, chatId: string, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'firstMessageId');\n}\n\nexport function selectReplyStack(global: GlobalState, chatId: string, threadId: number) {\n return selectThreadParam(global, chatId, threadId, 'replyStack');\n}\n\nexport function selectThreadOriginChat(global: GlobalState, chatId: string, threadId: number) {\n if (threadId === MAIN_THREAD_ID) {\n return selectChat(global, chatId);\n }\n\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n if (!threadInfo) {\n return undefined;\n }\n\n return selectChat(global, threadInfo.originChannelId || chatId);\n}\n\nexport function selectThreadTopMessageId(global: GlobalState, chatId: string, threadId: number) {\n if (threadId === MAIN_THREAD_ID) {\n return undefined;\n }\n\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n if (!threadInfo) {\n return undefined;\n }\n\n return threadInfo.topMessageId;\n}\n\nexport function selectThreadByMessage(global: GlobalState, chatId: string, message: ApiMessage) {\n const messageInfo = global.messages.byChatId[chatId];\n if (!messageInfo) {\n return undefined;\n }\n\n const { replyToMessageId, replyToTopMessageId } = message;\n if (!replyToMessageId && !replyToTopMessageId) {\n return undefined;\n }\n\n return Object.values(messageInfo.threadsById).find((thread) => {\n return thread.threadInfo && (\n (replyToMessageId && replyToMessageId === thread.threadInfo.topMessageId)\n || (replyToTopMessageId && replyToTopMessageId === thread.threadInfo.topMessageId)\n );\n });\n}\n\nexport function isMessageInCurrentMessageList(global: GlobalState, chatId: string, message: ApiMessage) {\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return false;\n }\n\n const { threadInfo } = selectThreadByMessage(global, chatId, message) || {};\n return (\n chatId === currentMessageList.chatId\n && (\n (currentMessageList.threadId === MAIN_THREAD_ID)\n || (threadInfo && currentMessageList.threadId === threadInfo.threadId)\n )\n );\n}\n\nexport function selectIsViewportNewest(global: GlobalState, chatId: string, threadId: number) {\n const viewportIds = selectViewportIds(global, chatId, threadId);\n if (!viewportIds || !viewportIds.length) {\n return true;\n }\n\n let lastMessageId: number;\n\n if (threadId === MAIN_THREAD_ID) {\n const chat = selectChat(global, chatId);\n if (!chat || !chat.lastMessage) {\n return true;\n }\n\n lastMessageId = chat.lastMessage.id;\n } else {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n if (!threadInfo || !threadInfo.lastMessageId) {\n return undefined;\n }\n\n lastMessageId = threadInfo.lastMessageId;\n }\n\n // Edge case: outgoing `lastMessage` is updated with a delay to optimize animation\n if (lastMessageId >= LOCAL_MESSAGE_ID_BASE && !selectChatMessage(global, chatId, lastMessageId)) {\n return true;\n }\n\n return viewportIds[viewportIds.length - 1] >= lastMessageId;\n}\n\nexport function selectChatMessage(global: GlobalState, chatId: string, messageId: number) {\n const chatMessages = selectChatMessages(global, chatId);\n\n return chatMessages ? chatMessages[messageId] : undefined;\n}\n\nexport function selectScheduledMessage(global: GlobalState, chatId: string, messageId: number) {\n const chatMessages = selectScheduledMessages(global, chatId);\n\n return chatMessages ? chatMessages[messageId] : undefined;\n}\n\nexport function selectEditingMessage(\n global: GlobalState, chatId: string, threadId: number, messageListType: MessageListType,\n) {\n if (messageListType === 'scheduled') {\n const messageId = selectEditingScheduledId(global, chatId);\n return messageId ? selectScheduledMessage(global, chatId, messageId) : undefined;\n } else {\n const messageId = selectEditingId(global, chatId, threadId);\n return messageId ? selectChatMessage(global, chatId, messageId) : undefined;\n }\n}\n\nexport function selectChatMessageByPollId(global: GlobalState, pollId: string) {\n let messageWithPoll: ApiMessage | undefined;\n\n // eslint-disable-next-line no-restricted-syntax\n for (const chatMessages of Object.values(global.messages.byChatId)) {\n const { byId } = chatMessages;\n messageWithPoll = Object.values(byId).find((message) => {\n return message.content.poll && message.content.poll.id === pollId;\n });\n if (messageWithPoll) {\n break;\n }\n }\n\n return messageWithPoll;\n}\n\nexport function selectFocusedMessageId(global: GlobalState, chatId: string) {\n const { chatId: focusedChatId, messageId } = global.focusedMessage || {};\n\n return focusedChatId === chatId ? messageId : undefined;\n}\n\nexport function selectIsMessageFocused(global: GlobalState, message: ApiMessage) {\n const focusedId = selectFocusedMessageId(global, message.chatId);\n\n return focusedId ? focusedId === message.id || focusedId === message.previousLocalId : false;\n}\n\nexport function selectIsMessageUnread(global: GlobalState, message: ApiMessage) {\n const { lastReadOutboxMessageId } = selectChat(global, message.chatId) || {};\n return isMessageLocal(message) || !lastReadOutboxMessageId || lastReadOutboxMessageId < message.id;\n}\n\nexport function selectOutgoingStatus(\n global: GlobalState, message: ApiMessage, isScheduledList = false,\n): ApiMessageOutgoingStatus {\n if (!selectIsMessageUnread(global, message) && !isScheduledList) {\n return 'read';\n }\n\n return getSendingState(message);\n}\n\nexport function selectSender(global: GlobalState, message: ApiMessage): ApiUser | ApiChat | undefined {\n const { senderId } = message;\n if (!senderId) {\n return undefined;\n }\n\n return isUserId(senderId) ? selectUser(global, senderId) : selectChat(global, senderId);\n}\n\nexport function selectForwardedSender(global: GlobalState, message: ApiMessage): ApiUser | ApiChat | undefined {\n const { forwardInfo } = message;\n if (!forwardInfo) {\n return undefined;\n }\n\n if (forwardInfo.isChannelPost && forwardInfo.fromChatId) {\n return selectChat(global, forwardInfo.fromChatId);\n } else if (forwardInfo.senderUserId) {\n return selectUser(global, forwardInfo.senderUserId) || selectChat(global, forwardInfo.senderUserId);\n }\n\n return undefined;\n}\n\nexport function selectAllowedMessageActions(global: GlobalState, message: ApiMessage, threadId: number) {\n const chat = selectChat(global, message.chatId);\n if (!chat || chat.isRestricted) {\n return {};\n }\n\n const isPrivate = isUserId(chat.id);\n const isChatWithSelf = selectIsChatWithSelf(global, message.chatId);\n const isBasicGroup = isChatBasicGroup(chat);\n const isSuperGroup = isChatSuperGroup(chat);\n const isChannel = isChatChannel(chat);\n const isLocal = isMessageLocal(message);\n const isServiceNotification = isServiceNotificationMessage(message);\n const isOwn = isOwnMessage(message);\n const isAction = isActionMessage(message);\n const { content } = message;\n\n const canEditMessagesIndefinitely = isChatWithSelf\n || (isSuperGroup && getHasAdminRight(chat, 'pinMessages'))\n || (isChannel && getHasAdminRight(chat, 'editMessages'));\n const isMessageEditable = (\n (\n canEditMessagesIndefinitely\n || getServerTime(global.serverTimeOffset) - message.date < MESSAGE_EDIT_ALLOWED_TIME\n ) && !(\n content.sticker || content.contact || content.poll || content.action || content.audio\n || (content.video?.isRound)\n )\n && !isForwardedMessage(message)\n && !message.viaBotId\n );\n\n const canReply = !isLocal && !isServiceNotification && getCanPostInChat(chat, threadId);\n\n const hasPinPermission = isPrivate || (\n chat.isCreator\n || (!isChannel && !isUserRightBanned(chat, 'pinMessages'))\n || getHasAdminRight(chat, 'pinMessages')\n );\n\n let canPin = !isLocal && !isServiceNotification && !isAction && hasPinPermission;\n let canUnpin = false;\n\n const pinnedMessageIds = selectPinnedIds(global, chat.id);\n\n if (canPin) {\n canUnpin = Boolean(pinnedMessageIds && pinnedMessageIds.includes(message.id));\n canPin = !canUnpin;\n }\n\n const canDelete = !isLocal && !isServiceNotification && (\n isPrivate\n || isOwn\n || isBasicGroup\n || chat.isCreator\n || getHasAdminRight(chat, 'deleteMessages')\n );\n\n const canReport = !isPrivate && !isOwn;\n\n const canDeleteForAll = canDelete && (\n (isPrivate && !isChatWithSelf)\n || (isBasicGroup && (\n isOwn || getHasAdminRight(chat, 'deleteMessages') || chat.isCreator\n ))\n );\n\n const canEdit = !isLocal && !isAction && isMessageEditable && (\n isOwn\n || (isChannel && (chat.isCreator || getHasAdminRight(chat, 'editMessages')))\n );\n\n const canForward = !isLocal && !isAction;\n\n const hasSticker = Boolean(message.content.sticker);\n const hasFavoriteSticker = hasSticker && selectIsStickerFavorite(global, message.content.sticker!);\n const canFaveSticker = !isAction && hasSticker && !hasFavoriteSticker;\n const canUnfaveSticker = !isAction && hasFavoriteSticker;\n const canCopy = !isAction;\n const canCopyLink = !isAction && (isChannel || isSuperGroup);\n const canSelect = !isAction;\n\n const canDownload = Boolean(content.webPage?.document || content.webPage?.video || content.webPage?.photo\n || content.audio || content.voice || content.photo || content.video || content.document || content.sticker);\n\n const noOptions = [\n canReply,\n canEdit,\n canPin,\n canUnpin,\n canReport,\n canDelete,\n canDeleteForAll,\n canForward,\n canFaveSticker,\n canUnfaveSticker,\n canCopy,\n canCopyLink,\n canSelect,\n canDownload,\n ].every((ability) => !ability);\n\n return {\n noOptions,\n canReply,\n canEdit,\n canPin,\n canUnpin,\n canReport,\n canDelete,\n canDeleteForAll,\n canForward,\n canFaveSticker,\n canUnfaveSticker,\n canCopy,\n canCopyLink,\n canSelect,\n canDownload,\n };\n}\n\n// This selector always returns a new object which can not be safely used in shallow-equal checks\nexport function selectCanDeleteSelectedMessages(global: GlobalState) {\n const { messageIds: selectedMessageIds } = global.selectedMessages || {};\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n const chatMessages = chatId && selectChatMessages(global, chatId);\n if (!chatMessages || !selectedMessageIds || !threadId) {\n return {};\n }\n\n const messageActions = selectedMessageIds\n .map((id) => chatMessages[id] && selectAllowedMessageActions(global, chatMessages[id], threadId))\n .filter(Boolean);\n\n return {\n canDelete: messageActions.every((actions) => actions.canDelete),\n canDeleteForAll: messageActions.every((actions) => actions.canDeleteForAll),\n };\n}\n\nexport function selectCanReportSelectedMessages(global: GlobalState) {\n const { messageIds: selectedMessageIds } = global.selectedMessages || {};\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n const chatMessages = chatId && selectChatMessages(global, chatId);\n if (!chatMessages || !selectedMessageIds || !threadId) {\n return false;\n }\n\n const messageActions = selectedMessageIds\n .map((id) => chatMessages[id] && selectAllowedMessageActions(global, chatMessages[id], threadId))\n .filter(Boolean);\n\n return messageActions.every((actions) => actions.canReport);\n}\n\nexport function selectCanDownloadSelectedMessages(global: GlobalState) {\n const { messageIds: selectedMessageIds } = global.selectedMessages || {};\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n const chatMessages = chatId && selectChatMessages(global, chatId);\n if (!chatMessages || !selectedMessageIds || !threadId) {\n return false;\n }\n\n const messageActions = selectedMessageIds\n .map((id) => chatMessages[id] && selectAllowedMessageActions(global, chatMessages[id], threadId))\n .filter(Boolean);\n\n return messageActions.some((actions) => actions.canDownload);\n}\n\nexport function selectIsDownloading(global: GlobalState, message: ApiMessage) {\n const activeInChat = global.activeDownloads.byChatId[message.chatId];\n return activeInChat ? activeInChat.includes(message.id) : false;\n}\n\nexport function selectActiveDownloadIds(global: GlobalState, chatId: string) {\n return global.activeDownloads.byChatId[chatId] || MEMO_EMPTY_ARRAY;\n}\n\nexport function selectUploadProgress(global: GlobalState, message: ApiMessage) {\n return global.fileUploads.byMessageLocalId[message.previousLocalId || message.id]?.progress;\n}\n\nexport function selectRealLastReadId(global: GlobalState, chatId: string, threadId: number) {\n if (threadId === MAIN_THREAD_ID) {\n const chat = selectChat(global, chatId);\n if (!chat) {\n return undefined;\n }\n\n // `lastReadInboxMessageId` is empty for new chats\n if (!chat.lastReadInboxMessageId) {\n return undefined;\n }\n\n if (!chat.lastMessage) {\n return chat.lastReadInboxMessageId;\n }\n\n if (isMessageLocal(chat.lastMessage)) {\n return chat.lastMessage.id;\n }\n\n // Some previously read messages may be deleted\n return Math.min(chat.lastMessage.id, chat.lastReadInboxMessageId);\n } else {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n if (!threadInfo) {\n return undefined;\n }\n\n if (!threadInfo.lastReadInboxMessageId) {\n return threadInfo.topMessageId;\n }\n\n // Some previously read messages may be deleted\n return Math.min(threadInfo.lastReadInboxMessageId, threadInfo.lastMessageId || Infinity);\n }\n}\n\nexport function selectFirstUnreadId(global: GlobalState, chatId: string, threadId: number) {\n const chat = selectChat(global, chatId);\n\n if (threadId === MAIN_THREAD_ID) {\n if (!chat) {\n return undefined;\n }\n } else {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n if (!threadInfo\n || (threadInfo.lastMessageId !== undefined && threadInfo.lastMessageId === threadInfo.lastReadInboxMessageId)) {\n return undefined;\n }\n }\n\n const outlyingIds = selectOutlyingIds(global, chatId, threadId);\n const listedIds = selectListedIds(global, chatId, threadId);\n const byId = selectChatMessages(global, chatId);\n if (!byId || !(outlyingIds || listedIds)) {\n return undefined;\n }\n\n const lastReadId = selectRealLastReadId(global, chatId, threadId);\n if (!lastReadId && chat && chat.isNotJoined) {\n return undefined;\n }\n\n const lastReadServiceNotificationId = chatId === SERVICE_NOTIFICATIONS_USER_ID\n ? global.serviceNotifications.reduce((max, notification) => {\n return !notification.isUnread && notification.id > max ? notification.id : max;\n }, -1)\n : -1;\n\n function findAfterLastReadId(listIds: number[]) {\n if (!lastReadId) {\n return listIds[0];\n }\n\n return listIds.find((id) => {\n return (\n id > lastReadId\n && byId[id]\n && (!byId[id].isOutgoing || byId[id].isFromScheduled)\n && id > lastReadServiceNotificationId\n );\n });\n }\n\n if (outlyingIds) {\n const found = findAfterLastReadId(outlyingIds);\n if (found) {\n return found;\n }\n }\n\n if (listedIds) {\n const found = findAfterLastReadId(listedIds);\n if (found) {\n return found;\n }\n }\n\n return undefined;\n}\n\nexport function selectIsPollResultsOpen(global: GlobalState) {\n const { pollResults } = global;\n return Boolean(pollResults.messageId);\n}\n\nexport function selectIsForwardModalOpen(global: GlobalState) {\n const { forwardMessages } = global;\n return Boolean(forwardMessages.isModalShown);\n}\n\nexport function selectCommonBoxChatId(global: GlobalState, messageId: number) {\n const fromLastMessage = Object.values(global.chats.byId).find((chat) => (\n isCommonBoxChat(chat) && chat.lastMessage && chat.lastMessage.id === messageId\n ));\n if (fromLastMessage) {\n return fromLastMessage.id;\n }\n\n const { byChatId } = global.messages;\n return Object.keys(byChatId).find((chatId) => {\n const chat = selectChat(global, chatId);\n return chat && isCommonBoxChat(chat) && byChatId[chat.id].byId[messageId];\n });\n}\n\nexport function selectIsInSelectMode(global: GlobalState) {\n const { selectedMessages } = global;\n\n return Boolean(selectedMessages);\n}\n\nexport function selectIsMessageSelected(global: GlobalState, messageId: number) {\n const { messageIds } = global.selectedMessages || {};\n if (!messageIds) {\n return false;\n }\n\n return messageIds.includes(messageId);\n}\n\nexport function selectForwardedMessageIdsByGroupId(global: GlobalState, chatId: string, groupedId: string) {\n const chatMessages = selectChatMessages(global, chatId);\n if (!chatMessages) {\n return undefined;\n }\n\n return Object.values(chatMessages)\n .filter((message) => message.groupedId === groupedId && message.forwardInfo)\n .map(({ forwardInfo }) => forwardInfo!.fromMessageId);\n}\n\nexport function selectMessageIdsByGroupId(global: GlobalState, chatId: string, groupedId: string) {\n const chatMessages = selectChatMessages(global, chatId);\n if (!chatMessages) {\n return undefined;\n }\n\n return Object.keys(chatMessages)\n .map(Number)\n .filter((id) => chatMessages[id].groupedId === groupedId);\n}\n\nexport function selectIsDocumentGroupSelected(global: GlobalState, chatId: string, groupedId: string) {\n const { messageIds: selectedIds } = global.selectedMessages || {};\n if (!selectedIds) {\n return false;\n }\n\n const groupIds = selectMessageIdsByGroupId(global, chatId, groupedId);\n return groupIds && groupIds.every((id) => selectedIds.includes(id));\n}\n\nexport function selectSelectedMessagesCount(global: GlobalState) {\n const { messageIds } = global.selectedMessages || {};\n\n return messageIds ? messageIds.length : 0;\n}\n\nexport function selectNewestMessageWithBotKeyboardButtons(\n global: GlobalState, chatId: string,\n): ApiMessage | undefined {\n const chat = selectChat(global, chatId);\n if (!chat) {\n return undefined;\n }\n\n if (!selectIsChatWithBot(global, chat)) {\n return undefined;\n }\n\n const chatMessages = selectChatMessages(global, chatId);\n const viewportIds = selectViewportIds(global, chatId, MAIN_THREAD_ID);\n if (!chatMessages || !viewportIds) {\n return undefined;\n }\n\n const messageId = findLast(viewportIds, (id) => {\n return !chatMessages[id].isOutgoing && Boolean(chatMessages[id].keyboardButtons);\n });\n\n const replyHideMessageId = findLast(viewportIds, (id) => {\n return Boolean(chatMessages[id].shouldHideKeyboardButtons);\n });\n\n if (messageId && replyHideMessageId && replyHideMessageId > messageId) {\n return undefined;\n }\n\n return messageId ? chatMessages[messageId] : undefined;\n}\n\nexport function selectCanAutoLoadMedia(\n global: GlobalState, message: ApiMessage, chat: ApiChat, sender?: ApiChat | ApiUser,\n) {\n const isPhoto = Boolean(getMessagePhoto(message) || getMessageWebPagePhoto(message));\n const isVideo = Boolean(getMessageVideo(message) || getMessageWebPageVideo(message));\n const isFile = Boolean(getMessageAudio(message) || getMessageVoice(message) || getMessageDocument(message));\n\n const {\n canAutoLoadPhotoFromContacts,\n canAutoLoadPhotoInPrivateChats,\n canAutoLoadPhotoInGroups,\n canAutoLoadPhotoInChannels,\n canAutoLoadVideoFromContacts,\n canAutoLoadVideoInPrivateChats,\n canAutoLoadVideoInGroups,\n canAutoLoadVideoInChannels,\n canAutoLoadFileFromContacts,\n canAutoLoadFileInPrivateChats,\n canAutoLoadFileInGroups,\n canAutoLoadFileInChannels,\n } = global.settings.byKey;\n\n if (isPhoto) {\n return canAutoLoadMedia({\n global,\n chat,\n sender,\n canAutoLoadMediaFromContacts: canAutoLoadPhotoFromContacts,\n canAutoLoadMediaInPrivateChats: canAutoLoadPhotoInPrivateChats,\n canAutoLoadMediaInGroups: canAutoLoadPhotoInGroups,\n canAutoLoadMediaInChannels: canAutoLoadPhotoInChannels,\n });\n }\n\n if (isVideo) {\n return canAutoLoadMedia({\n global,\n chat,\n sender,\n canAutoLoadMediaFromContacts: canAutoLoadVideoFromContacts,\n canAutoLoadMediaInPrivateChats: canAutoLoadVideoInPrivateChats,\n canAutoLoadMediaInGroups: canAutoLoadVideoInGroups,\n canAutoLoadMediaInChannels: canAutoLoadVideoInChannels,\n });\n }\n\n if (isFile) {\n return canAutoLoadMedia({\n global,\n chat,\n sender,\n canAutoLoadMediaFromContacts: canAutoLoadFileFromContacts,\n canAutoLoadMediaInPrivateChats: canAutoLoadFileInPrivateChats,\n canAutoLoadMediaInGroups: canAutoLoadFileInGroups,\n canAutoLoadMediaInChannels: canAutoLoadFileInChannels,\n });\n }\n\n return true;\n}\n\nfunction canAutoLoadMedia({\n global,\n chat,\n sender,\n canAutoLoadMediaFromContacts,\n canAutoLoadMediaInPrivateChats,\n canAutoLoadMediaInGroups,\n canAutoLoadMediaInChannels,\n}: {\n global: GlobalState;\n chat: ApiChat;\n canAutoLoadMediaFromContacts: boolean;\n canAutoLoadMediaInPrivateChats: boolean;\n canAutoLoadMediaInGroups: boolean;\n canAutoLoadMediaInChannels: boolean;\n sender?: ApiChat | ApiUser;\n}) {\n const isMediaFromContact = Boolean(sender && (\n sender.id === global.currentUserId || selectIsUserOrChatContact(global, sender)\n ));\n\n return Boolean(\n (isMediaFromContact && canAutoLoadMediaFromContacts)\n || (!isMediaFromContact && canAutoLoadMediaInPrivateChats && isUserId(chat.id))\n || (canAutoLoadMediaInGroups && isChatGroup(chat))\n || (canAutoLoadMediaInChannels && isChatChannel(chat)),\n );\n}\n\nexport function selectCanAutoPlayMedia(global: GlobalState, message: ApiMessage) {\n const video = getMessageVideo(message) || getMessageWebPageVideo(message);\n if (!video) {\n return undefined;\n }\n\n const {\n canAutoPlayVideos,\n canAutoPlayGifs,\n } = global.settings.byKey;\n\n const asGif = video.isGif || video.isRound;\n\n return (canAutoPlayVideos && !asGif) || (canAutoPlayGifs && asGif);\n}\n\nexport function selectShouldLoopStickers(global: GlobalState) {\n return global.settings.byKey.shouldLoopStickers;\n}\n\nexport function selectLastServiceNotification(global: GlobalState) {\n const { serviceNotifications } = global;\n const maxId = Math.max(...serviceNotifications.map(({ id }) => id));\n\n return serviceNotifications.find(({ id }) => id === maxId);\n}\n","import { GlobalState } from '../../global/types';\nimport { selectCurrentMessageList } from './messages';\nimport { buildChatThreadKey } from '../helpers';\n\nexport function selectCurrentTextSearch(global: GlobalState) {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n const chatThreadKey = buildChatThreadKey(chatId, threadId);\n const currentSearch = global.localTextSearch.byChatThreadKey[chatThreadKey];\n if (!currentSearch || !currentSearch.isActive) {\n return undefined;\n }\n\n return currentSearch;\n}\n\nexport function selectCurrentMediaSearchPeerId(global: GlobalState) {\n const { byChatId } = global.localMediaSearch;\n const { chatId } = selectCurrentMessageList(global) || {};\n const currentProfileUserId = global.users.selectedId;\n\n return currentProfileUserId && byChatId[currentProfileUserId] ? currentProfileUserId : chatId;\n}\n\nexport function selectCurrentMediaSearch(global: GlobalState) {\n const peerId = selectCurrentMediaSearchPeerId(global);\n if (!peerId) {\n return undefined;\n }\n\n return global.localMediaSearch.byChatId[peerId];\n}\n","import { GlobalState } from '../../global/types';\n\nimport { selectCurrentMessageList } from './messages';\nimport { selectChat } from './chats';\nimport { isChatGroup, isUserId } from '../helpers';\n\nexport function selectManagement(global: GlobalState, chatId: string) {\n return global.management.byChatId[chatId];\n}\n\nexport function selectCurrentManagement(global: GlobalState) {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n const currentManagement = global.management.byChatId[chatId];\n if (!currentManagement || !currentManagement.isActive) {\n return undefined;\n }\n\n return currentManagement;\n}\n\nexport function selectCurrentManagementType(global: GlobalState) {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n if (isUserId(chatId)) {\n return 'user';\n }\n\n const chat = selectChat(global, chatId);\n if (!chat) {\n return undefined;\n }\n\n if (isChatGroup(chat)) {\n return 'group';\n }\n\n return 'channel';\n}\n","import { GlobalState } from '../../global/types';\nimport { NewChatMembersProgress, RightColumnContent } from '../../types';\n\nimport { getSystemTheme, IS_SINGLE_COLUMN_LAYOUT } from '../../util/environment';\nimport { selectCurrentMessageList, selectIsPollResultsOpen } from './messages';\nimport { selectCurrentTextSearch } from './localSearch';\nimport { selectCurrentStickerSearch, selectCurrentGifSearch } from './symbols';\nimport { selectAreActiveChatsLoaded } from './chats';\nimport { selectCurrentManagement } from './management';\n\nexport function selectIsMediaViewerOpen(global: GlobalState) {\n const { mediaViewer } = global;\n return Boolean(mediaViewer.messageId || mediaViewer.avatarOwnerId);\n}\n\nexport function selectRightColumnContentKey(global: GlobalState) {\n const {\n users,\n isChatInfoShown,\n newChatMembersProgress,\n } = global;\n\n const isAddingChatMembersShown = newChatMembersProgress !== NewChatMembersProgress.Closed;\n const isPollResults = selectIsPollResultsOpen(global);\n const isSearch = Boolean(!IS_SINGLE_COLUMN_LAYOUT && selectCurrentTextSearch(global));\n const isManagement = selectCurrentManagement(global);\n const stickerSearch = selectCurrentStickerSearch(global);\n const isStickerSearch = stickerSearch.query !== undefined;\n const gifSearch = selectCurrentGifSearch(global);\n const isGifSearch = gifSearch.query !== undefined;\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n const currentProfileUserId = users.selectedId;\n const areActiveChatsLoaded = selectAreActiveChatsLoaded(global);\n const isUserInfo = Boolean(currentProfileUserId && areActiveChatsLoaded);\n const isChatShown = Boolean(currentChatId && areActiveChatsLoaded);\n const isChatInfo = isChatShown && isChatInfoShown;\n\n return isPollResults ? (\n RightColumnContent.PollResults\n ) : isSearch ? (\n RightColumnContent.Search\n ) : isManagement ? (\n RightColumnContent.Management\n ) : isStickerSearch ? (\n RightColumnContent.StickerSearch\n ) : isGifSearch ? (\n RightColumnContent.GifSearch\n ) : isAddingChatMembersShown ? (\n RightColumnContent.AddingMembers\n ) : isUserInfo ? (\n RightColumnContent.UserInfo\n ) : isChatInfo ? (\n RightColumnContent.ChatInfo\n ) : undefined;\n}\n\nexport function selectIsRightColumnShown(global: GlobalState) {\n return selectRightColumnContentKey(global) !== undefined;\n}\n\nexport function selectTheme(global: GlobalState) {\n const { theme, shouldUseSystemTheme } = global.settings.byKey;\n\n return shouldUseSystemTheme ? getSystemTheme() : theme;\n}\n","import { GlobalState } from '../../global/types';\n\nexport function selectCurrentGlobalSearchQuery(global: GlobalState) {\n return global.globalSearch.query;\n}\n","import { GlobalState } from '../../global/types';\n\nexport function selectPaymentChatId(global: GlobalState) {\n return global.payment.chatId;\n}\n\nexport function selectPaymentMessageId(global: GlobalState) {\n return global.payment.messageId;\n}\n\nexport function selectPaymentFormId(global: GlobalState) {\n return global.payment.formId;\n}\n\nexport function selectPaymentRequestId(global: GlobalState) {\n return global.payment.requestId;\n}\n\nexport function selectProviderPublishableKey(global: GlobalState) {\n return global.payment.nativeParams ? global.payment.nativeParams.publishableKey : undefined;\n}\n\nexport function selectStripeCredentials(global: GlobalState) {\n return global.payment.stripeCredentials;\n}\n","import {\n ApiBotInlineMediaResult, ApiBotInlineResult, ApiBotInlineSwitchPm,\n ApiLanguage, ApiMessage, ApiShippingAddress, ApiStickerSet,\n} from '../api/types';\n\nexport enum LoadMoreDirection {\n Backwards,\n Forwards,\n Around,\n}\n\nexport enum FocusDirection {\n Up,\n Down,\n Static,\n}\n\nexport interface IAlbum {\n albumId: string;\n messages: ApiMessage[];\n mainMessage: ApiMessage;\n}\n\nexport type ThemeKey = 'light' | 'dark';\n\nexport interface IThemeSettings {\n background?: string;\n backgroundColor?: string;\n patternColor?: string;\n isBlurred?: boolean;\n}\n\nexport type NotifySettings = {\n hasPrivateChatsNotifications?: boolean;\n hasPrivateChatsMessagePreview?: boolean;\n hasGroupNotifications?: boolean;\n hasGroupMessagePreview?: boolean;\n hasBroadcastNotifications?: boolean;\n hasBroadcastMessagePreview?: boolean;\n hasContactJoinedNotifications?: boolean;\n hasWebNotifications: boolean;\n hasPushNotifications: boolean;\n notificationSoundVolume: number;\n};\n\nexport type LangCode = (\n 'en' | 'ar' | 'be' | 'ca' | 'nl' | 'fr' | 'de' | 'id' | 'it' | 'ko' | 'ms' | 'fa' | 'pl' | 'pt-br' | 'ru' | 'es'\n | 'tr' | 'uk' | 'uz'\n);\n\nexport type TimeFormat = '24h' | '12h';\n\nexport interface ISettings extends NotifySettings, Record {\n theme: ThemeKey;\n shouldUseSystemTheme: boolean;\n messageTextSize: number;\n animationLevel: 0 | 1 | 2;\n messageSendKeyCombo: 'enter' | 'ctrl-enter';\n canAutoLoadPhotoFromContacts: boolean;\n canAutoLoadPhotoInPrivateChats: boolean;\n canAutoLoadPhotoInGroups: boolean;\n canAutoLoadPhotoInChannels: boolean;\n canAutoLoadVideoFromContacts: boolean;\n canAutoLoadVideoInPrivateChats: boolean;\n canAutoLoadVideoInGroups: boolean;\n canAutoLoadVideoInChannels: boolean;\n canAutoLoadFileFromContacts: boolean;\n canAutoLoadFileInPrivateChats: boolean;\n canAutoLoadFileInGroups: boolean;\n canAutoLoadFileInChannels: boolean;\n autoLoadFileMaxSizeMb: number;\n canAutoPlayGifs: boolean;\n canAutoPlayVideos: boolean;\n shouldSuggestStickers: boolean;\n shouldLoopStickers: boolean;\n hasPassword?: boolean;\n languages?: ApiLanguage[];\n language: LangCode;\n isSensitiveEnabled?: boolean;\n canChangeSensitive?: boolean;\n timeFormat: TimeFormat;\n wasTimeFormatSetManually: boolean;\n}\n\nexport interface ApiPrivacySettings {\n visibility: PrivacyVisibility;\n allowUserIds: string[];\n allowChatIds: string[];\n blockUserIds: string[];\n blockChatIds: string[];\n}\n\nexport interface InputPrivacyContact {\n id: string;\n accessHash?: string;\n}\n\nexport interface InputPrivacyRules {\n visibility: PrivacyVisibility;\n allowedUsers?: InputPrivacyContact[];\n allowedChats?: InputPrivacyContact[];\n blockedUsers?: InputPrivacyContact[];\n blockedChats?: InputPrivacyContact[];\n}\n\nexport type IAnchorPosition = {\n x: number;\n y: number;\n};\n\nexport interface ShippingOption {\n id: string;\n title: string;\n amount: number;\n prices: Price[];\n}\n\nexport interface Price {\n label: string;\n amount: number;\n}\n\nexport interface Invoice {\n currency?: string;\n emailRequested?: boolean;\n emailToProvider?: boolean;\n flexible?: boolean;\n nameRequested?: boolean;\n phoneRequested?: boolean;\n phoneToProvider?: boolean;\n prices?: Price[];\n shippingAddressRequested?: boolean;\n test?: boolean;\n}\n\nexport interface Receipt {\n currency: string;\n prices: Price[];\n info?: {\n shippingAddress?: ApiShippingAddress;\n phone?: string;\n name?: string;\n };\n totalAmount: number;\n credentialsTitle: string;\n shippingPrices?: Price[];\n shippingMethod?: string;\n photoUrl?: string;\n text?: string;\n title?: string;\n}\n\nexport enum SettingsScreens {\n Main,\n EditProfile,\n Notifications,\n DataStorage,\n Language,\n General,\n GeneralChatBackground,\n GeneralChatBackgroundColor,\n Privacy,\n PrivacyPhoneNumber,\n PrivacyLastSeen,\n PrivacyProfilePhoto,\n PrivacyForwarding,\n PrivacyGroupChats,\n PrivacyPhoneNumberAllowedContacts,\n PrivacyPhoneNumberDeniedContacts,\n PrivacyLastSeenAllowedContacts,\n PrivacyLastSeenDeniedContacts,\n PrivacyProfilePhotoAllowedContacts,\n PrivacyProfilePhotoDeniedContacts,\n PrivacyForwardingAllowedContacts,\n PrivacyForwardingDeniedContacts,\n PrivacyGroupChatsAllowedContacts,\n PrivacyGroupChatsDeniedContacts,\n PrivacyActiveSessions,\n PrivacyBlockedUsers,\n Folders,\n FoldersCreateFolder,\n FoldersEditFolder,\n FoldersEditFolderFromChatList,\n FoldersIncludedChats,\n FoldersIncludedChatsFromChatList,\n FoldersExcludedChats,\n FoldersExcludedChatsFromChatList,\n TwoFaDisabled,\n TwoFaNewPassword,\n TwoFaNewPasswordConfirm,\n TwoFaNewPasswordHint,\n TwoFaNewPasswordEmail,\n TwoFaNewPasswordEmailCode,\n TwoFaEnabled,\n TwoFaChangePasswordCurrent,\n TwoFaChangePasswordNew,\n TwoFaChangePasswordConfirm,\n TwoFaChangePasswordHint,\n TwoFaTurnOff,\n TwoFaRecoveryEmailCurrentPassword,\n TwoFaRecoveryEmail,\n TwoFaRecoveryEmailCode,\n TwoFaCongratulations,\n}\n\nexport type StickerSetOrRecent = Pick;\n\nexport enum LeftColumnContent {\n ChatList,\n GlobalSearch,\n Settings,\n Contacts,\n Archived,\n NewChannelStep1,\n NewChannelStep2,\n NewGroupStep1,\n NewGroupStep2,\n}\n\nexport enum GlobalSearchContent {\n ChatList,\n Media,\n Links,\n Files,\n Music,\n Voice,\n}\n\nexport enum RightColumnContent {\n ChatInfo,\n UserInfo,\n Search,\n Management,\n StickerSearch,\n GifSearch,\n PollResults,\n AddingMembers,\n}\n\nexport enum MediaViewerOrigin {\n Inline,\n ScheduledInline,\n SharedMedia,\n ProfileAvatar,\n SettingsAvatar,\n MiddleHeaderAvatar,\n Album,\n ScheduledAlbum,\n SearchResult,\n}\n\nexport enum AudioOrigin {\n Inline,\n SharedMedia,\n Search,\n}\n\nexport enum ChatCreationProgress {\n Idle,\n InProgress,\n Complete,\n Error,\n}\n\nexport enum ProfileEditProgress {\n Idle,\n InProgress,\n Complete,\n Error,\n}\n\nexport enum ManagementProgress {\n Idle,\n InProgress,\n Complete,\n Error,\n}\n\nexport enum NewChatMembersProgress {\n Closed,\n InProgress,\n Loading,\n}\n\nexport type ProfileTabType = 'members' | 'commonChats' | 'media' | 'documents' | 'links' | 'audio' | 'voice';\nexport type SharedMediaType = 'media' | 'documents' | 'links' | 'audio' | 'voice';\nexport type ApiPrivacyKey = 'phoneNumber' | 'lastSeen' | 'profilePhoto' | 'forwards' | 'chatInvite';\nexport type PrivacyVisibility = 'everybody' | 'contacts' | 'nonContacts' | 'nobody';\n\nexport enum ProfileState {\n Profile,\n SharedMedia,\n MemberList,\n}\n\nexport enum PaymentStep {\n ShippingInfo,\n Shipping,\n PaymentInfo,\n Checkout,\n}\n\nexport const UPLOADING_WALLPAPER_SLUG = 'UPLOADING_WALLPAPER_SLUG';\n\nexport enum ManagementScreens {\n Initial,\n ChatPrivacyType,\n Discussion,\n ChannelSubscribers,\n GroupType,\n GroupPermissions,\n GroupRemovedUsers,\n GroupUserPermissionsCreate,\n GroupUserPermissions,\n ChatAdministrators,\n GroupRecentActions,\n ChatAdminRights,\n GroupMembers,\n}\n\nexport type ManagementType = 'user' | 'group' | 'channel';\n\nexport type NotifyException = {\n isMuted: boolean;\n isSilent?: boolean;\n shouldShowPreviews?: boolean;\n};\n\nexport type EmojiKeywords = {\n isLoading?: boolean;\n version: number;\n keywords: Record;\n};\n\nexport type InlineBotSettings = {\n id: string;\n help?: string;\n query?: string;\n offset?: string;\n canLoadMore?: boolean;\n results?: (ApiBotInlineResult | ApiBotInlineMediaResult)[];\n isGallery?: boolean;\n switchPm?: ApiBotInlineSwitchPm;\n};\n","import { fastRaf } from './schedulers';\n\ninterface AnimationInstance {\n isCancelled: boolean;\n}\n\nlet currentInstance: AnimationInstance | undefined;\n\nexport function animateSingle(tick: Function, instance?: AnimationInstance) {\n if (!instance) {\n if (currentInstance && !currentInstance.isCancelled) {\n currentInstance.isCancelled = true;\n }\n\n instance = { isCancelled: false };\n currentInstance = instance;\n }\n\n fastRaf(() => {\n if (!instance!.isCancelled && tick()) {\n animateSingle(tick, instance);\n }\n });\n}\n\nexport function animate(tick: Function) {\n fastRaf(() => {\n if (tick()) {\n animate(tick);\n }\n });\n}\n","import { DEBUG } from '../config';\n\nexport function updateAppBadge(unreadCount: number) {\n if (typeof window.navigator.setAppBadge !== 'function') {\n return;\n }\n\n window.navigator.setAppBadge(unreadCount).catch((err) => {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n });\n}\n","export default function arePropsShallowEqual(currentProps: AnyLiteral, newProps: AnyLiteral) {\n if (currentProps === newProps) {\n return true;\n }\n\n const currentKeys = Object.keys(currentProps);\n const currentKeysLength = currentKeys.length;\n const newKeysLength = Object.keys(newProps).length;\n\n if (currentKeysLength !== newKeysLength) {\n return false;\n }\n\n if (currentKeysLength === 0) {\n return true;\n }\n\n for (let i = 0; i < currentKeysLength; i++) {\n const prop = currentKeys[i];\n if (currentProps[prop] !== newProps[prop]) {\n return false;\n }\n }\n\n return true;\n}\n\nexport function getUnequalProps(currentProps: AnyLiteral, newProps: AnyLiteral) {\n const currentKeys = Object.keys(currentProps);\n const currentKeysLength = currentKeys.length;\n const newKeysLength = Object.keys(newProps).length;\n\n if (currentKeysLength !== newKeysLength) {\n return ['%LENGTH%'];\n }\n\n return currentKeys.reduce((res, prop) => {\n if (currentProps[prop] !== newProps[prop]) {\n res.push(`${prop}: ${currentProps[prop]} => ${newProps[prop]}`);\n }\n\n return res;\n }, [] as string[]);\n}\n","type Parts = (string | false | undefined)[];\n\nexport default (...parts: Parts) => {\n return parts.filter(Boolean).join(' ');\n};\n","// eslint-disable-next-line no-restricted-globals\nconst cacheApi = self.caches;\n\nexport enum Type {\n Text,\n Blob,\n Json,\n}\n\nexport async function fetch(\n cacheName: string, key: string, type: Type, isHtmlAllowed = false,\n) {\n if (!cacheApi) {\n return undefined;\n }\n\n try {\n // To avoid the error \"Request scheme 'webdocument' is unsupported\"\n const request = new Request(key.replace(/:/g, '_'));\n const cache = await cacheApi.open(cacheName);\n const response = await cache.match(request);\n if (!response) {\n return undefined;\n }\n\n const contentType = response.headers.get('Content-Type');\n\n switch (type) {\n case Type.Text:\n return await response.text();\n case Type.Blob: {\n // Ignore deprecated data-uri avatars\n if (key.startsWith('avatar') && contentType && contentType.startsWith('text')) {\n return undefined;\n }\n\n const blob = await response.blob();\n\n // Safari does not return correct Content-Type header for webp images.\n if (key.startsWith('sticker')) {\n return new Blob([blob], { type: 'image/webp' });\n }\n\n const shouldRecreate = !blob.type || (!isHtmlAllowed && blob.type.includes('html'));\n // iOS Safari fails to preserve `type` in cache\n let resolvedType = blob.type || contentType;\n\n if (!(shouldRecreate && resolvedType)) {\n return blob;\n }\n\n // Prevent HTML-in-video attacks (for files that were cached before fix)\n if (!isHtmlAllowed) {\n resolvedType = resolvedType.replace(/html/gi, '');\n }\n\n return new Blob([blob], { type: resolvedType });\n }\n case Type.Json:\n return await response.json();\n default:\n return undefined;\n }\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n\nexport async function save(cacheName: string, key: string, data: AnyLiteral | Blob | string) {\n if (!cacheApi) {\n return undefined;\n }\n\n try {\n const cacheData = typeof data === 'string' || data instanceof Blob ? data : JSON.stringify(data);\n // To avoid the error \"Request scheme 'webdocument' is unsupported\"\n const request = new Request(key.replace(/:/g, '_'));\n const response = new Response(cacheData);\n const cache = await cacheApi.open(cacheName);\n return await cache.put(request, response);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n\nexport async function clear(cacheName: string) {\n try {\n if (!cacheApi) {\n return undefined;\n }\n\n return await cacheApi.delete(cacheName);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n","import captureKeyboardListener from './captureKeyboardListeners';\n\ntype IHandlerFunction = () => void;\n\nexport default function captureEscKeyListener(handler: IHandlerFunction) {\n return captureKeyboardListener({ onEsc: handler });\n}\n","type HandlerName = 'onEnter' | 'onBackspace' | 'onDelete' | 'onEsc' | 'onUp' | 'onDown' | 'onLeft' | 'onRight'\n| 'onTab';\ntype Handler = (e: KeyboardEvent) => void;\ntype CaptureOptions = Partial>;\n\nconst keyToHandlerName: Record = {\n Enter: 'onEnter',\n Backspace: 'onBackspace',\n Delete: 'onDelete',\n Esc: 'onEsc',\n Escape: 'onEsc',\n ArrowUp: 'onUp',\n ArrowDown: 'onDown',\n ArrowLeft: 'onLeft',\n ArrowRight: 'onRight',\n Tab: 'onTab',\n};\n\nconst handlers: Record = {\n onEnter: [],\n onDelete: [],\n onBackspace: [],\n onEsc: [],\n onUp: [],\n onDown: [],\n onLeft: [],\n onRight: [],\n onTab: [],\n};\n\nexport default function captureKeyboardListeners(options: CaptureOptions) {\n if (!hasActiveHandlers()) {\n document.addEventListener('keydown', handleKeyDown, true);\n }\n\n (Object.keys(options) as Array).forEach((handlerName) => {\n const handler = options[handlerName];\n if (!handler) {\n return;\n }\n\n const currentEventHandlers = handlers[handlerName];\n if (currentEventHandlers) {\n currentEventHandlers.push(handler);\n }\n });\n\n return () => {\n releaseKeyboardListener(options);\n };\n}\n\nfunction hasActiveHandlers() {\n return Object.values(handlers).some((keyHandlers) => Boolean(keyHandlers.length));\n}\n\nfunction handleKeyDown(e: KeyboardEvent) {\n const handlerName = keyToHandlerName[e.key];\n if (!handlerName) {\n return;\n }\n\n const { length } = handlers[handlerName];\n if (!length) {\n return;\n }\n e.stopPropagation();\n\n const handler = handlers[handlerName][length - 1];\n handler!(e);\n}\n\nfunction releaseKeyboardListener(options: CaptureOptions) {\n (Object.keys(options) as Array).forEach((handlerName) => {\n const handler = options[handlerName];\n const currentEventHandlers = handlers[handlerName];\n if (currentEventHandlers) {\n const index = currentEventHandlers.findIndex((cb) => cb === handler);\n if (index !== -1) {\n currentEventHandlers.splice(index, 1);\n }\n }\n });\n\n if (!hasActiveHandlers()) {\n document.removeEventListener('keydown', handleKeyDown, false);\n }\n}\n","import { LangFn } from '../hooks/useLang';\n\nconst WEEKDAYS_FULL = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];\nconst MONTHS_FULL = [\n 'January', 'February', 'March', 'April', 'May', 'June',\n 'July', 'August', 'September', 'October', 'November', 'December',\n];\n\nconst MONTHS_FULL_LOWERCASE = MONTHS_FULL.map((month) => month.toLowerCase());\nconst MIN_SEARCH_YEAR = 2015;\nconst MAX_DAY_IN_MONTH = 31;\nconst MAX_MONTH_IN_YEAR = 12;\nexport const MILLISECONDS_IN_DAY = 24 * 60 * 60 * 1000;\n\nexport function getDayStart(datetime: number | Date) {\n const date = new Date(datetime);\n date.setHours(0, 0, 0, 0);\n return date;\n}\n\nexport function getDayStartAt(datetime: number | Date) {\n return getDayStart(datetime).getTime();\n}\n\nexport function toYearMonth(timestamp: number) {\n const date = new Date(timestamp * 1000);\n return `${date.getFullYear()}-${date.getMonth()}`;\n}\n\nfunction toIsoString(date: Date) {\n return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;\n}\n\n// @optimization `toLocaleTimeString` is avoided because of bad performance\nexport function formatTime(datetime: number | Date, lang: LangFn) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n const timeFormat = lang.timeFormat || '24h';\n\n let hours = date.getHours();\n let marker = '';\n if (timeFormat === '12h') {\n marker = hours >= 12 ? ' PM' : ' AM';\n hours = hours > 12 ? hours % 12 : hours;\n }\n\n return `${String(hours).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}${marker}`;\n}\n\nexport function formatPastTimeShort(lang: LangFn, datetime: number | Date) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n\n const today = getDayStart(new Date());\n if (date >= today) {\n return formatTime(date, lang);\n }\n\n const weekAgo = new Date(today);\n weekAgo.setDate(today.getDate() - 7);\n if (date >= weekAgo) {\n return lang(`Weekday.Short${WEEKDAYS_FULL[date.getDay()]}`);\n }\n\n const withYear = date.getFullYear() !== today.getFullYear();\n const format = (\n lang(withYear ? 'formatDateScheduleYear' : 'formatDateSchedule')\n || (withYear ? 'd MMM yyyy' : 'd MMM')\n );\n\n return formatDate(lang, date, format);\n}\n\nexport function formatFullDate(lang: LangFn, datetime: number | Date) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n const format = lang('formatterYearMax') || 'dd.MM.yyyy';\n\n return formatDate(lang, date, format);\n}\n\nexport function formatMonthAndYear(lang: LangFn, date: Date, isShort = false) {\n const format = lang(isShort ? 'formatterMonthYear2' : 'formatterMonthYear') || 'MMM yyyy';\n\n return formatDate(lang, date, format);\n}\n\nexport function formatHumanDate(\n lang: LangFn,\n datetime: number | Date,\n isShort = false,\n noWeekdays = false,\n isUpperFirst?: boolean,\n) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n\n const today = getDayStart(new Date());\n\n if (!noWeekdays) {\n if (toIsoString(date) === toIsoString(today)) {\n return (isUpperFirst || !isShort ? upperFirst : lowerFirst)(lang('Weekday.Today'));\n }\n\n const yesterday = new Date(today);\n yesterday.setDate(today.getDate() - 1);\n if (toIsoString(date) === toIsoString(yesterday)) {\n return (isUpperFirst || !isShort ? upperFirst : lowerFirst)(lang('Weekday.Yesterday'));\n }\n\n const weekAgo = new Date(today);\n const weekAhead = new Date(today);\n weekAgo.setDate(today.getDate() - 7);\n weekAhead.setDate(today.getDate() + 7);\n if (date >= weekAgo && date <= weekAhead) {\n const weekDay = WEEKDAYS_FULL[date.getDay()];\n const weekDayString = isShort ? lang(`Weekday.Short${weekDay}`) : lang(`Weekday.${weekDay}`);\n\n return (isUpperFirst || !isShort ? upperFirst : lowerFirst)(weekDayString);\n }\n }\n\n const withYear = date.getFullYear() !== today.getFullYear();\n const formatKey = isShort\n ? (withYear ? 'formatDateScheduleYear' : 'formatDateSchedule')\n : (withYear ? 'chatFullDate' : 'chatDate');\n const format = lang(formatKey) || 'd MMMM yyyy';\n\n return (isUpperFirst || !isShort ? upperFirst : lowerFirst)(formatDate(lang, date, format));\n}\n\nfunction formatDate(lang: LangFn, date: Date, format: string) {\n const day = date.getDate();\n const monthIndex = date.getMonth();\n\n return format\n .replace('LLLL', lang(MONTHS_FULL[monthIndex]))\n .replace('MMMM', lang(`Month.Gen${MONTHS_FULL[monthIndex]}`))\n .replace('MMM', lang(`Month.Short${MONTHS_FULL[monthIndex]}`))\n .replace('MM', String(monthIndex + 1).padStart(2, '0'))\n .replace('dd', String(day).padStart(2, '0'))\n .replace('d', String(day))\n .replace('yyyy', String(date.getFullYear()));\n}\n\nexport function formatMediaDateTime(\n lang: LangFn,\n datetime: number | Date,\n isUpperFirst?: boolean,\n) {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n\n return `${formatHumanDate(lang, date, true, undefined, isUpperFirst)}, ${formatTime(date, lang)}`;\n}\n\nexport function formatMediaDuration(duration: number, maxValue?: number) {\n const hours = Math.floor(duration / 3600);\n const minutes = Math.floor((duration % 3600) / 60);\n const seconds = Math.floor(duration % 3600 % 60);\n\n const maxHours = maxValue ? Math.floor(maxValue / 3600) : 0;\n const maxMinutes = maxValue ? Math.floor((maxValue % 3600) / 60) : 0;\n let string = '';\n if (hours > 0 || maxHours > 0) {\n string += `${String(hours).padStart(2, '0')}:`;\n string += `${String(minutes).padStart(2, '0')}:`;\n } else if (maxMinutes >= 10) {\n string += `${String(minutes).padStart(2, '0')}:`;\n } else {\n string += `${String(minutes)}:`;\n }\n string += String(seconds).padStart(2, '0');\n\n return string;\n}\n\nexport function formatVoiceRecordDuration(durationInMs: number) {\n const parts = [];\n\n let milliseconds = durationInMs % 1000;\n durationInMs -= milliseconds;\n milliseconds = Math.floor(milliseconds / 10);\n\n durationInMs = Math.floor(durationInMs / 1000);\n const seconds = durationInMs % 60;\n durationInMs -= seconds;\n\n durationInMs = Math.floor(durationInMs / 60);\n const minutes = durationInMs % 60;\n durationInMs -= minutes;\n\n durationInMs = Math.floor(durationInMs / 60);\n const hours = durationInMs % 60;\n\n if (hours > 0) {\n parts.push(String(hours).padStart(2, '0'));\n }\n parts.push(String(minutes).padStart(hours > 0 ? 2 : 1, '0'));\n parts.push(String(seconds).padStart(2, '0'));\n\n return `${parts.join(':')},${String(milliseconds).padStart(2, '0')}`;\n}\n\nexport function formatDateToString(date: Date, locale = 'en-US') {\n return date.toLocaleString(\n locale,\n {\n year: 'numeric',\n month: 'short',\n day: 'numeric',\n },\n );\n}\n\nfunction isValidDate(day: number, month: number, year = 2021): boolean {\n if (month > (MAX_MONTH_IN_YEAR - 1) || day > MAX_DAY_IN_MONTH) {\n return false;\n }\n const date = new Date(year, month, day);\n return !Number.isNaN(date.getTime()) && date.getDate() === day;\n}\n\nexport function parseDateString(query = ''): string | undefined {\n const matchStringDate = query.match(/\\d{1,2}\\s[a-zA-Z]{3,}/);\n const matchEuropeStringDate = query.match(/[a-zA-Z]{3,}\\s\\d{1,2}/);\n const matchNumberDate = query.match(/\\d{1,2}[./-]\\d{1,2}([./-]\\d{2,4})?/);\n if (!matchStringDate && !matchNumberDate && !matchEuropeStringDate) {\n return undefined;\n }\n\n if (matchNumberDate) {\n const [date, month, year] = query.split(/[./-]/).map(Number);\n return !(year && year < MIN_SEARCH_YEAR) && isValidDate(date, month - 1, year || undefined)\n ? `${year ? `${year}-` : ''}${String(month).padStart(2, '0')}-${String(date).padStart(2, '0')}`\n : undefined;\n }\n\n const dateParts = query.split(' ');\n const date = matchStringDate ? dateParts[0] : dateParts[1];\n const month = (matchStringDate ? dateParts[1] : dateParts[0]).toLowerCase();\n const monthIndex = MONTHS_FULL_LOWERCASE.findIndex((item) => item.startsWith(month));\n\n return monthIndex !== -1 && isValidDate(Number(date), monthIndex)\n ? `${String(monthIndex + 1).padStart(2, '0')}-${String(date).padStart(2, '0')}`\n : undefined;\n}\n\nexport function timestampPlusDay(timestamp: number) {\n return timestamp + MILLISECONDS_IN_DAY / 1000;\n}\n\nfunction lowerFirst(str: string) {\n return `${str[0].toLowerCase()}${str.slice(1)}`;\n}\n\nfunction upperFirst(str: string) {\n return `${str[0].toUpperCase()}${str.slice(1)}`;\n}\n","import EMOJI_REGEX from '../lib/twemojiRegex';\n\n// Due to the fact that emoji from Apple do not contain some characters, it is necessary to remove them from emoji-data\n// https://github.com/iamcal/emoji-data/issues/136\nconst EXCLUDE_EMOJIS = ['female_sign', 'male_sign', 'medical_symbol'];\n\nconst ISO_FLAGS_OFFSET = 127397;\n\nexport type EmojiRawData = typeof import('emoji-data-ios/emoji-data.json');\nexport type EmojiModule = { default: EmojiRawData };\n\nexport type EmojiData = {\n categories: Array;\n emojis: Record;\n};\n\n// Non-standard variations of emojis, used on some devices\nconst EMOJI_EXCEPTIONS: [string | RegExp, string][] = [\n [/\\u{1f3f3}\\u200d\\u{1f308}/gu, '\\u{1f3f3}\\ufe0f\\u200d\\u{1f308}'], // 🏳‍🌈\n [/\\u{1f3f3}\\u200d\\u26a7\\ufe0f/gu, '\\u{1f3f3}\\ufe0f\\u200d\\u26a7\\ufe0f'], // 🏳️‍⚧️\n [/\\u{1f937}\\u200d\\u2642/gu, '\\u{1f937}\\u200d\\u2642\\ufe0f'], // 🤷‍♂️\n];\n\nfunction unifiedToNative(unified: string) {\n const unicodes = unified.split('-');\n const codePoints = unicodes.map((i) => parseInt(i, 16));\n\n return String.fromCodePoint(...codePoints);\n}\n\nexport function fixNonStandardEmoji(text: string) {\n // Non-standard sequences typically parsed as separate emojis, so no need to fix text without any\n if (!text.match(EMOJI_REGEX)) return text;\n // eslint-disable-next-line no-restricted-syntax\n for (const [regex, replacement] of EMOJI_EXCEPTIONS) {\n text = text.replace(regex, replacement);\n }\n\n return text;\n}\n\nexport function nativeToUnified(emoji: string) {\n let code;\n\n if (emoji.length === 1) {\n code = emoji.charCodeAt(0).toString(16).padStart(4, '0');\n } else {\n const pairs = [];\n for (let i = 0; i < emoji.length; i++) {\n if (emoji.charCodeAt(i) >= 0xd800 && emoji.charCodeAt(i) <= 0xdbff) {\n if (emoji.charCodeAt(i + 1) >= 0xdc00 && emoji.charCodeAt(i + 1) <= 0xdfff) {\n pairs.push(\n (emoji.charCodeAt(i) - 0xd800) * 0x400\n + (emoji.charCodeAt(i + 1) - 0xdc00) + 0x10000,\n );\n }\n } else if (emoji.charCodeAt(i) < 0xd800 || emoji.charCodeAt(i) > 0xdfff) {\n pairs.push(emoji.charCodeAt(i));\n }\n }\n\n code = pairs.map((x) => x.toString(16).padStart(4, '0')).join('-');\n }\n\n return code;\n}\n\nexport function uncompressEmoji(data: EmojiRawData): EmojiData {\n const emojiData: EmojiData = { categories: [], emojis: {} };\n\n for (let i = 0; i < data.length; i += 2) {\n const category = {\n id: data[i][0],\n name: data[i][1],\n emojis: [],\n } as EmojiCategory;\n\n for (let j = 0; j < data[i + 1].length; j++) {\n const emojiRaw = data[i + 1][j];\n if (!EXCLUDE_EMOJIS.includes(emojiRaw[1][0])) {\n category.emojis.push(emojiRaw[1][0]);\n emojiData.emojis[emojiRaw[1][0]] = {\n id: emojiRaw[1][0],\n names: emojiRaw[1] as string[],\n native: unifiedToNative(emojiRaw[0] as string),\n image: (emojiRaw[0] as string).toLowerCase(),\n };\n }\n }\n\n emojiData.categories.push(category);\n }\n\n return emojiData;\n}\n\nexport function isoToEmoji(iso: string) {\n const code = iso.toUpperCase();\n\n if (!/^[A-Z]{2}$/.test(code)) return iso;\n const codePoints = [...code].map((c) => c.codePointAt(0)! + ISO_FLAGS_OFFSET);\n return String.fromCodePoint(...codePoints);\n}\n","let isWebpSupportedCache: boolean | undefined;\n\nexport function isWebpSupported() {\n return Boolean(isWebpSupportedCache);\n}\n\nfunction testWebp(): Promise {\n return new Promise((resolve) => {\n const webp = new Image();\n // eslint-disable-next-line max-len\n webp.src = 'data:image/webp;base64,UklGRjoAAABXRUJQVlA4IC4AAACyAgCdASoCAAIALmk0mk0iIiIiIgBoSygABc6WWgAA/veff/0PP8bA//LwYAAA';\n const handleLoadOrError = () => {\n resolve(webp.height === 2);\n };\n webp.onload = handleLoadOrError;\n webp.onerror = handleLoadOrError;\n });\n}\n\ntestWebp().then((hasWebp) => {\n isWebpSupportedCache = hasWebp;\n});\n","import { ThemeKey } from '../types';\n\nlet systemThemeCache: ThemeKey = (\n window.matchMedia?.('(prefers-color-scheme: dark)').matches\n) ? 'dark' : 'light';\n\nexport function getSystemTheme() {\n return systemThemeCache;\n}\n\nfunction handleSystemThemeChange(e: MediaQueryListEventMap['change']) {\n systemThemeCache = e.matches ? 'dark' : 'light';\n}\n\nconst mql = window.matchMedia('(prefers-color-scheme: dark)');\nif (typeof mql.addEventListener === 'function') {\n mql.addEventListener('change', handleSystemThemeChange);\n} else if (typeof mql.addListener === 'function') {\n mql.addListener(handleSystemThemeChange);\n}\n","import {\n MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN,\n MOBILE_SCREEN_MAX_WIDTH,\n MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT,\n MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH,\n IS_TEST,\n SUPPORTED_VIDEO_CONTENT_TYPES,\n VIDEO_MOV_TYPE,\n} from '../config';\n\nexport * from './environmentWebp';\n\nexport * from './environmentSystemTheme';\n\nexport function getPlatform() {\n const { userAgent, platform } = window.navigator;\n const macosPlatforms = ['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'];\n const windowsPlatforms = ['Win32', 'Win64', 'Windows', 'WinCE'];\n const iosPlatforms = ['iPhone', 'iPad', 'iPod'];\n let os: 'macOS' | 'iOS' | 'Windows' | 'Android' | 'Linux' | undefined;\n\n if (macosPlatforms.indexOf(platform) !== -1) {\n os = 'macOS';\n } else if (iosPlatforms.indexOf(platform) !== -1) {\n os = 'iOS';\n } else if (windowsPlatforms.indexOf(platform) !== -1) {\n os = 'Windows';\n } else if (/Android/.test(userAgent)) {\n os = 'Android';\n } else if (/Linux/.test(platform)) {\n os = 'Linux';\n }\n\n return os;\n}\n\nexport const PLATFORM_ENV = getPlatform();\nexport const IS_MAC_OS = PLATFORM_ENV === 'macOS';\nexport const IS_IOS = PLATFORM_ENV === 'iOS';\nexport const IS_ANDROID = PLATFORM_ENV === 'Android';\nexport const IS_SAFARI = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);\nexport const IS_PWA = window.matchMedia('(display-mode: standalone)').matches\n|| (window.navigator as any).standalone\n|| document.referrer.includes('android-app://');\n\nexport const IS_TOUCH_ENV = window.matchMedia('(pointer: coarse)').matches;\n// Keep in mind the landscape orientation\nexport const IS_SINGLE_COLUMN_LAYOUT = window.innerWidth <= MOBILE_SCREEN_MAX_WIDTH || (\n window.innerWidth <= MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH && window.innerHeight <= MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT\n);\n// Special layout, 1 column while chat opened, 2 columns while collapsed\nexport const IS_TABLET_COLUMN_LAYOUT = !IS_SINGLE_COLUMN_LAYOUT && (\n window.innerWidth <= MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN\n);\nexport const IS_VOICE_RECORDING_SUPPORTED = Boolean(\n navigator.mediaDevices && 'getUserMedia' in navigator.mediaDevices && (\n window.AudioContext || (window as any).webkitAudioContext\n ),\n);\nexport const IS_SMOOTH_SCROLL_SUPPORTED = 'scrollBehavior' in document.documentElement.style;\nexport const IS_EMOJI_SUPPORTED = PLATFORM_ENV && (IS_MAC_OS || IS_IOS);\nexport const IS_SERVICE_WORKER_SUPPORTED = 'serviceWorker' in navigator;\n// TODO Consider failed service worker\nexport const IS_PROGRESSIVE_SUPPORTED = IS_SERVICE_WORKER_SUPPORTED;\nexport const IS_STREAMING_SUPPORTED = 'MediaSource' in window;\nexport const IS_OPUS_SUPPORTED = Boolean((new Audio()).canPlayType('audio/ogg; codecs=opus'));\nexport const IS_CANVAS_FILTER_SUPPORTED = (\n !IS_TEST && 'filter' in (document.createElement('canvas').getContext('2d') || {})\n);\nexport const LAYERS_ANIMATION_NAME = IS_ANDROID ? 'slide-fade' : IS_IOS ? 'slide-layers' : 'push-slide';\n\nconst TEST_VIDEO = document.createElement('video');\nexport const IS_MOV_SUPPORTED = Boolean(\n TEST_VIDEO.canPlayType(VIDEO_MOV_TYPE).replace('no', '')\n || IS_IOS, // IOS reports '', but still plays .mov files\n);\n\nif (IS_MOV_SUPPORTED) SUPPORTED_VIDEO_CONTENT_TYPES.add(VIDEO_MOV_TYPE);\n\nexport const DPR = window.devicePixelRatio || 1;\n\nexport const MASK_IMAGE_DISABLED = true;\n","import { pause } from './schedulers';\n\n// Polyfill for Safari: `File` is not available in web worker\nif (typeof File === 'undefined') {\n // eslint-disable-next-line no-global-assign, no-restricted-globals, func-names\n self.File = class extends Blob {\n name: string;\n\n constructor(fileBits: BlobPart[], fileName: string, options?: FilePropertyBag) {\n if (options) {\n const { type, ...rest } = options;\n super(fileBits, { type });\n Object.assign(this, rest);\n } else {\n super(fileBits);\n }\n\n this.name = fileName;\n }\n } as typeof File;\n}\n\nexport function dataUriToBlob(dataUri: string) {\n const arr = dataUri.split(',');\n const mime = arr[0].match(/:(.*?);/)![1];\n const bstr = atob(arr[1]);\n let n = bstr.length;\n const u8arr = new Uint8Array(n);\n\n while (n--) {\n u8arr[n] = bstr.charCodeAt(n);\n }\n\n return new Blob([u8arr], { type: mime });\n}\n\nexport function blobToDataUri(blob: Blob): Promise {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n\n reader.onload = (e: ProgressEvent) => {\n const { result } = e.target || {};\n if (typeof result === 'string') {\n resolve(result);\n }\n\n reject(new Error('Failed to read blob'));\n };\n\n reader.onerror = reject;\n reader.readAsDataURL(blob);\n });\n}\n\nexport function blobToFile(blob: Blob, fileName: string) {\n return new File([blob], fileName, {\n lastModified: Date.now(),\n type: blob.type,\n });\n}\n\nexport function preloadImage(url: string): Promise {\n return new Promise((resolve, reject) => {\n const img = new Image();\n img.onload = () => resolve(img);\n img.onerror = reject;\n img.src = url;\n });\n}\n\nexport function preloadVideo(url: string): Promise {\n return new Promise((resolve, reject) => {\n const video = document.createElement('video');\n video.volume = 0;\n video.onloadedmetadata = () => resolve(video);\n video.onerror = reject;\n video.src = url;\n });\n}\n\nexport async function createPosterForVideo(url: string): Promise {\n const video = await preloadVideo(url);\n\n return Promise.race([\n pause(2000) as Promise,\n new Promise((resolve, reject) => {\n video.onseeked = () => {\n if (!video.videoWidth || !video.videoHeight) {\n resolve(undefined);\n }\n\n const canvas = document.createElement('canvas');\n canvas.width = video.videoWidth;\n canvas.height = video.videoHeight;\n const ctx = canvas.getContext('2d')!;\n ctx.drawImage(video, 0, 0);\n resolve(canvas.toDataURL('image/jpeg'));\n };\n video.onerror = reject;\n video.currentTime = Math.min(video.duration, 1);\n }),\n ]);\n}\n\nexport async function fetchBlob(blobUrl: string) {\n const response = await fetch(blobUrl);\n return response.blob();\n}\n\nexport async function fetchFile(blobUrl: string, fileName: string) {\n const blob = await fetchBlob(blobUrl);\n return blobToFile(blob, fileName);\n}\n\nexport function imgToCanvas(img: HTMLImageElement) {\n const canvas = document.createElement('canvas');\n canvas.width = img.width;\n canvas.height = img.height;\n\n const ctx = canvas.getContext('2d')!;\n ctx.drawImage(img, 0, 0);\n\n return canvas;\n}\n","import { LangCode } from '../types';\n\nexport function formatCurrency(totalPrice: number, currency?: string, locale: LangCode = 'en') {\n return new Intl.NumberFormat(locale, {\n style: 'currency',\n currency,\n }).format(currency === 'JPY' ? totalPrice : totalPrice / 100);\n}\n","export default (store: AnyLiteral) => {\n let id;\n\n do {\n id = String(Math.random()).replace('0.', 'id');\n } while (store.hasOwnProperty(id));\n\n return id;\n};\n","import { ApiError, ApiFieldError } from '../api/types';\n\nconst READABLE_ERROR_MESSAGES: Record = {\n CHAT_RESTRICTED: 'You can\\'t send messages in this chat, you were restricted',\n CHAT_WRITE_FORBIDDEN: 'You can\\'t write in this chat',\n CHAT_SEND_POLL_FORBIDDEN: 'You can\\'t create polls in this chat',\n CHAT_SEND_STICKERS_FORBIDDEN: 'You can\\'t send stickers in this chat',\n CHAT_SEND_GIFS_FORBIDDEN: 'You can\\'t send gifs in this chat',\n CHAT_SEND_MEDIA_FORBIDDEN: 'You can\\'t send media in this chat',\n CHAT_LINK_EXISTS: 'The chat is public, you can\\'t hide the history to new users',\n // eslint-disable-next-line max-len\n SLOWMODE_WAIT_X: 'Slowmode is enabled in this chat: you must wait for the specified number of seconds before sending another message to the chat.',\n USER_BANNED_IN_CHANNEL: 'You\\'re banned from sending messages in supergroups / channels',\n USER_IS_BLOCKED: 'You were blocked by this user',\n YOU_BLOCKED_USER: 'You blocked this user',\n IMAGE_PROCESS_FAILED: 'Failure while processing image',\n MEDIA_EMPTY: 'The provided media object is invalid',\n MEDIA_INVALID: 'Media invalid',\n PHOTO_EXT_INVALID: 'The extension of the photo is invalid',\n PHOTO_INVALID_DIMENSIONS: 'The photo dimensions are invalid',\n PHOTO_SAVE_FILE_INVALID: 'Internal issues, try again later',\n // eslint-disable-next-line max-len\n MESSAGE_DELETE_FORBIDDEN: 'You can\\'t delete one of the messages you tried to delete, most likely because it is a service message.',\n MESSAGE_POLL_CLOSED: 'Poll closed',\n MESSAGE_EDIT_TIME_EXPIRED: 'You can\\'t edit this message anymore.',\n CHAT_ADMIN_REQUIRED: 'You must be an admin in this chat to do this',\n PINNED_DIALOGS_TOO_MUCH: 'Sorry, you can only pin 5 chats to the top',\n DIALOG_FILTERS_TOO_MUCH: 'Sorry, you can\\'t have more than 10 folders',\n CHANNEL_PRIVATE: 'This channel is private',\n MEDIA_CAPTION_TOO_LONG: 'The provided caption is too long',\n ADDRESS_STREET_LINE1_INVALID: 'The address you provided is not valid',\n ADDRESS_STREET_LINE2_INVALID: 'The address you provided is not valid',\n ADDRESS_CITY_INVALID: 'The city you provided is not valid',\n ADDRESS_COUNTRY_INVALID: 'The country you provided is not valid',\n ADDRESS_POSTCODE_INVALID: 'The postcode you provided is not valid',\n ADDRESS_STATE_INVALID: 'The state you provided is not valid',\n REQ_INFO_NAME_INVALID: 'The name you provided is not valid',\n REQ_INFO_PHONE_INVALID: 'The phone you provided is not valid',\n REQ_INFO_EMAIL_INVALID: 'The email you provided is not valid',\n // TODO Bring back after fixing the weird bug\n // CHANNEL_INVALID: 'An error occurred. Please try again later',\n LINK_NOT_MODIFIED: 'This discussion is already linked to the channel',\n MESSAGE_TOO_LONG: 'Message is too long',\n\n // Non-API errors\n SERVICE_WORKER_DISABLED: 'Service Worker is disabled. Please reload the page without holding key.',\n // eslint-disable-next-line max-len\n MESSAGE_TOO_LONG_PLEASE_REMOVE_CHARACTERS: 'The provided message is too long. Please remove {EXTRA_CHARS_COUNT} character{PLURAL_S}.',\n // eslint-disable-next-line max-len\n FRESH_RESET_AUTHORISATION_FORBIDDEN: 'You can’t logout other sessions if less than 24 hours have passed since you logged on the current session',\n\n BOTS_TOO_MUCH: 'There are too many bots in this chat/channel',\n BOT_GROUPS_BLOCKED: 'This bot can\\'t be added to groups',\n USERS_TOO_MUCH: 'The maximum number of users has been exceeded',\n USER_CHANNELS_TOO_MUCH: 'One of the users you tried to add is already in too many channels/supergroups',\n USER_KICKED: 'This user was kicked from this supergroup/channel',\n USER_NOT_MUTUAL_CONTACT: 'The provided user is not a mutual contact',\n USER_PRIVACY_RESTRICTED: 'The user\\'s privacy settings do not allow you to do this',\n INVITE_HASH_EMPTY: 'The invite hash is empty',\n INVITE_HASH_EXPIRED: 'The invite link has expired',\n INVITE_HASH_INVALID: 'The invite hash is invalid',\n CHANNELS_TOO_MUCH: 'You have joined too many channels/supergroups',\n USER_ALREADY_PARTICIPANT: 'You already in the group',\n SCHEDULE_DATE_INVALID: 'Invalid schedule date provided',\n WALLPAPER_DIMENSIONS_INVALID: 'The wallpaper dimensions are invalid, please select another file',\n};\n\nexport const SHIPPING_ERRORS: Record = {\n ADDRESS_STREET_LINE1_INVALID: {\n field: 'streetLine1',\n message: 'Incorrect street address',\n },\n ADDRESS_STREET_LINE2_INVALID: {\n field: 'streetLine2',\n message: 'Incorrect street address',\n },\n ADDRESS_CITY_INVALID: {\n field: 'city',\n message: 'Incorrect city',\n },\n ADDRESS_COUNTRY_INVALID: {\n field: 'countryIso2',\n message: 'Incorrect country',\n },\n ADDRESS_POSTCODE_INVALID: {\n field: 'postCode',\n message: 'Incorrect post code',\n },\n ADDRESS_STATE_INVALID: {\n field: 'state',\n message: 'Incorrect state',\n },\n REQ_INFO_NAME_INVALID: {\n field: 'fullName',\n message: 'Incorrect name',\n },\n REQ_INFO_PHONE_INVALID: {\n field: 'phone',\n message: 'Incorrect phone',\n },\n REQ_INFO_EMAIL_INVALID: {\n field: 'email',\n message: 'Incorrect email',\n },\n};\n\nexport default function getReadableErrorText(error: ApiError) {\n const { message, isSlowMode, textParams } = error;\n // Currently, Telegram API doesn't return `SLOWMODE_WAIT_X` error as described in the docs\n if (isSlowMode) {\n const extraPartIndex = message.indexOf(' (caused by');\n return extraPartIndex > 0 ? message.substring(0, extraPartIndex) : message;\n }\n let errorMessage = READABLE_ERROR_MESSAGES[message];\n if (errorMessage && textParams) {\n errorMessage = Object.keys(textParams).reduce((acc, current) => {\n return acc.replace(current, textParams[current]);\n }, errorMessage as string);\n }\n return errorMessage;\n}\n\nexport function getShippingError(error: ApiError): ApiFieldError | undefined {\n return SHIPPING_ERRORS[error.message];\n}\n","import { DEBUG_ALERT_MSG } from '../config';\nimport { throttle } from './schedulers';\n\nwindow.addEventListener('error', handleErrorEvent);\nwindow.addEventListener('unhandledrejection', handleErrorEvent);\n\n// eslint-disable-next-line prefer-destructuring\nconst APP_ENV = process.env.APP_ENV;\n\nfunction handleErrorEvent(e: ErrorEvent | PromiseRejectionEvent) {\n e.preventDefault();\n\n handleError(e instanceof ErrorEvent ? e.error : e.reason);\n}\n\nconst throttledAlert = throttle(window.alert, 1000);\n\nexport function handleError(err: Error) {\n // eslint-disable-next-line no-console\n console.error(err);\n\n if (APP_ENV === 'development' || APP_ENV === 'staging') {\n throttledAlert(`${DEBUG_ALERT_MSG}\\n\\n${(err?.message) || err}\\n${err?.stack}`);\n }\n}\n","type CollectionByKey = Record;\n\ntype OrderDirection = 'asc' | 'desc';\n\ninterface OrderCallback {\n (member: T): any;\n}\n\nexport function buildCollectionByKey(collection: T[], key: keyof T) {\n return collection.reduce((byKey: CollectionByKey, member: T) => {\n byKey[member[key]] = member;\n\n return byKey;\n }, {});\n}\n\nexport function mapValues(\n byKey: CollectionByKey,\n callback: (member: M, key: string, index: number, originalByKey: CollectionByKey) => R,\n): CollectionByKey {\n return Object.keys(byKey).reduce((newByKey: CollectionByKey, key, index) => {\n newByKey[key] = callback(byKey[key], key, index, byKey);\n return newByKey;\n }, {});\n}\n\nexport function pick(object: T, keys: K[]) {\n return keys.reduce((result, key) => {\n result[key] = object[key];\n return result;\n }, {} as Pick);\n}\n\nexport function pickTruthy(object: T, keys: K[]) {\n return keys.reduce((result, key) => {\n if (object[key]) {\n result[key] = object[key];\n }\n\n return result;\n }, {} as Pick);\n}\n\nexport function omit(object: T, keys: K[]) {\n const stringKeys = new Set(keys.map(String));\n const savedKeys = Object.keys(object)\n .filter((key) => !stringKeys.has(key)) as Array>;\n\n return pick(object, savedKeys);\n}\n\nexport function orderBy(\n collection: T[],\n orderKey: (keyof T) | OrderCallback | ((keyof T) | OrderCallback)[],\n mode: OrderDirection | [OrderDirection, OrderDirection] = 'asc',\n): T[] {\n return collection.sort((a, b) => {\n if (Array.isArray(orderKey)) {\n const [mode1, mode2] = Array.isArray(mode) ? mode : [mode, mode];\n const [orderKey1, orderKey2] = orderKey;\n\n let aValue1;\n let bValue1;\n\n if (typeof orderKey1 === 'function') {\n aValue1 = orderKey1(a) || 0;\n bValue1 = orderKey1(b) || 0;\n } else if (typeof orderKey1 === 'string') {\n aValue1 = a[orderKey1] || 0;\n bValue1 = b[orderKey1] || 0;\n }\n\n if (aValue1 !== bValue1) {\n return mode1 === 'asc' ? aValue1 - bValue1 : bValue1 - aValue1;\n } else {\n let aValue2;\n let bValue2;\n\n if (typeof orderKey2 === 'function') {\n aValue2 = orderKey2(a) || 0;\n bValue2 = orderKey2(b) || 0;\n } else if (typeof orderKey2 === 'string') {\n aValue2 = a[orderKey2] || 0;\n bValue2 = b[orderKey2] || 0;\n }\n\n return mode2 === 'asc' ? aValue2 - bValue2 : bValue2 - aValue2;\n }\n }\n\n let aValue;\n let bValue;\n\n if (typeof orderKey === 'function') {\n aValue = orderKey(a) || 0;\n bValue = orderKey(b) || 0;\n } else if (typeof orderKey === 'string') {\n aValue = a[orderKey] || 0;\n bValue = b[orderKey] || 0;\n }\n\n return mode === 'asc' ? aValue - bValue : bValue - aValue;\n });\n}\n\nexport function flatten(array: any[]) {\n return array.reduce((result, member) => {\n if (Array.isArray(member)) {\n return result.concat(member);\n } else {\n result.push(member);\n return result;\n }\n }, []);\n}\n\nexport function unique(array: T[]): T[] {\n return Array.from(new Set(array));\n}\n\nexport function compact(array: any[]) {\n return array.filter(Boolean);\n}\n\nexport function areSortedArraysEqual(array1: any[], array2: any[]) {\n if (array1.length !== array2.length) {\n return false;\n }\n\n return array1.every((item, i) => item === array2[i]);\n}\n\nexport function areSortedArraysIntersecting(array1: any[], array2: any[]) {\n return array1[0] <= array2[array2.length - 1] && array1[array1.length - 1] >= array2[0];\n}\n\nexport function findIntersectionWithSet(array: T[], set: Set): T[] {\n return array.filter((a) => set.has(a));\n}\n\nexport function split(array: any[], chunkSize: number) {\n const result = [];\n for (let i = 0; i < array.length; i += chunkSize) {\n result.push(array.slice(i, i + chunkSize));\n }\n\n return result;\n}\n\nexport function cloneDeep(value: T): T {\n if (typeof value !== 'object') {\n return value;\n }\n\n if (Array.isArray(value)) {\n return value.map(cloneDeep) as typeof value;\n }\n\n return Object.keys(value).reduce((acc, key) => {\n acc[key as keyof T] = cloneDeep(value[key as keyof T]);\n return acc;\n }, {} as T);\n}\n\n/**\n * Returns the index of the last element in the array where predicate is true, and -1 otherwise.\n *\n * @param array The source array to search in\n * @param predicate find calls predicate once for each element of the array, in descending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.\n */\nexport function findLast(array: Array, predicate: (value: T, index: number, obj: T[]) => boolean): T | undefined {\n let cursor = array.length;\n\n while (cursor--) {\n if (predicate(array[cursor], cursor, array)) {\n return array[cursor];\n }\n }\n\n return undefined;\n}\n","import { getGlobal } from '../lib/teact/teactn';\n\nimport { ApiLangPack, ApiLangString } from '../api/types';\nimport { LangCode, TimeFormat } from '../types';\n\nimport {\n DEFAULT_LANG_CODE, DEFAULT_LANG_PACK, LANG_CACHE_NAME, LANG_PACKS,\n} from '../config';\nimport * as cacheApi from './cacheApi';\nimport { callApi } from '../api/gramjs';\nimport { createCallbackManager } from './callbacks';\nimport { formatInteger } from './textFormat';\n\ninterface LangFn {\n (key: string, value?: any, format?: 'i'): any;\n\n isRtl?: boolean;\n code?: LangCode;\n timeFormat?: TimeFormat;\n}\n\nconst SUBSTITUTION_REGEX = /%\\d?\\$?[sdf@]/g;\nconst PLURAL_OPTIONS = ['value', 'zeroValue', 'oneValue', 'twoValue', 'fewValue', 'manyValue', 'otherValue'] as const;\nconst PLURAL_RULES = {\n /* eslint-disable max-len */\n en: (n: number) => (n !== 1 ? 6 : 2),\n ar: (n: number) => (n === 0 ? 1 : n === 1 ? 2 : n === 2 ? 3 : n % 100 >= 3 && n % 100 <= 10 ? 4 : n % 100 >= 11 ? 5 : 6),\n ca: (n: number) => (n !== 1 ? 6 : 2),\n de: (n: number) => (n !== 1 ? 6 : 2),\n es: (n: number) => (n !== 1 ? 6 : 2),\n fa: (n: number) => (n > 1 ? 6 : 2),\n fr: (n: number) => (n > 1 ? 6 : 2),\n id: () => 0,\n it: (n: number) => (n !== 1 ? 6 : 2),\n ko: () => 0,\n ms: () => 0,\n nl: (n: number) => (n !== 1 ? 6 : 2),\n pl: (n: number) => (n === 1 ? 2 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 4 : 5),\n pt_BR: (n: number) => (n > 1 ? 6 : 2),\n ru: (n: number) => (n % 10 === 1 && n % 100 !== 11 ? 2 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 4 : 5),\n tr: (n: number) => (n > 1 ? 6 : 2),\n uk: (n: number) => (n % 10 === 1 && n % 100 !== 11 ? 2 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 4 : 5),\n uz: (n: number) => (n > 1 ? 6 : 2),\n /* eslint-enable max-len */\n};\n\nconst cache = new Map();\n\nlet langPack: ApiLangPack | undefined;\nlet fallbackLangPack: ApiLangPack | undefined;\n\nconst {\n addCallback,\n removeCallback,\n runCallbacks,\n} = createCallbackManager();\n\nexport { addCallback, removeCallback };\n\nlet currentLangCode: string | undefined;\nlet currentTimeFormat: TimeFormat | undefined;\n\nexport const getTranslation: LangFn = (key: string, value?: any, format?: 'i') => {\n if (value !== undefined) {\n const cacheValue = Array.isArray(value) ? JSON.stringify(value) : value;\n const cached = cache.get(`${key}_${cacheValue}_${format}`);\n if (cached) {\n return cached;\n }\n }\n\n if (!langPack && !fallbackLangPack) {\n return key;\n }\n\n const langString = (langPack?.[key]) || (fallbackLangPack?.[key]);\n if (!langString) {\n if (!fallbackLangPack) {\n void importFallbackLangPack();\n }\n\n return key;\n }\n\n return processTranslation(langString, key, value, format);\n};\n\nexport async function getTranslationForLangString(langCode: string, key: string) {\n let translateString: ApiLangString | undefined = await cacheApi.fetch(\n LANG_CACHE_NAME,\n `${DEFAULT_LANG_PACK}_${langCode}_${key}`,\n cacheApi.Type.Json,\n );\n\n if (!translateString) {\n translateString = await fetchRemoteString(DEFAULT_LANG_PACK, langCode, key);\n }\n\n return processTranslation(translateString, key);\n}\n\nexport async function setLanguage(langCode: LangCode, callback?: NoneToVoidFunction, withFallback = false) {\n if (langPack && langCode === currentLangCode) {\n if (callback) {\n callback();\n }\n\n return;\n }\n\n let newLangPack = await cacheApi.fetch(LANG_CACHE_NAME, langCode, cacheApi.Type.Json);\n if (!newLangPack) {\n if (withFallback) {\n await importFallbackLangPack();\n }\n\n newLangPack = await fetchRemote(langCode);\n if (!newLangPack) {\n return;\n }\n }\n\n cache.clear();\n\n currentLangCode = langCode;\n langPack = newLangPack;\n document.documentElement.lang = langCode;\n\n const { languages, timeFormat } = getGlobal().settings.byKey;\n const langInfo = languages?.find((l) => l.langCode === langCode);\n getTranslation.isRtl = Boolean(langInfo?.rtl);\n getTranslation.code = langCode;\n getTranslation.timeFormat = timeFormat;\n\n if (callback) {\n callback();\n }\n\n runCallbacks();\n}\n\nexport function setTimeFormat(timeFormat: TimeFormat) {\n if (timeFormat && timeFormat === currentTimeFormat) {\n return;\n }\n\n currentTimeFormat = timeFormat;\n getTranslation.timeFormat = timeFormat;\n\n runCallbacks();\n}\n\nasync function importFallbackLangPack() {\n if (fallbackLangPack) {\n return;\n }\n\n fallbackLangPack = (await import('./fallbackLangPack')).default;\n runCallbacks();\n}\n\nasync function fetchRemote(langCode: string): Promise {\n const remote = await callApi('fetchLangPack', { sourceLangPacks: LANG_PACKS, langCode });\n if (remote) {\n await cacheApi.save(LANG_CACHE_NAME, langCode, remote.langPack);\n return remote.langPack;\n }\n\n return undefined;\n}\n\nasync function fetchRemoteString(\n remoteLangPack: typeof LANG_PACKS[number], langCode: string, key: string,\n): Promise {\n const remote = await callApi('fetchLangStrings', {\n langPack: remoteLangPack,\n langCode,\n keys: [key],\n });\n\n if (remote?.length) {\n await cacheApi.save(LANG_CACHE_NAME, `${remoteLangPack}_${langCode}_${key}`, remote[0]);\n\n return remote[0];\n }\n\n return undefined;\n}\n\nfunction getPluralOption(amount: number) {\n const langCode = currentLangCode || DEFAULT_LANG_CODE;\n const optionIndex = PLURAL_RULES[langCode as keyof typeof PLURAL_RULES]\n ? PLURAL_RULES[langCode as keyof typeof PLURAL_RULES](amount)\n : 0;\n\n return PLURAL_OPTIONS[optionIndex];\n}\n\nfunction processTemplate(template: string, value: any) {\n value = Array.isArray(value) ? value : [value];\n const translationSlices = template.split(SUBSTITUTION_REGEX);\n const initialValue = translationSlices.shift();\n\n return translationSlices.reduce((result, str, index) => {\n return `${result}${String(value[index] || '')}${str}`;\n }, initialValue || '');\n}\n\nfunction processTranslation(langString: ApiLangString | undefined, key: string, value?: any, format?: 'i') {\n const template = langString ? langString[typeof value === 'number' ? getPluralOption(value) : 'value'] : undefined;\n if (!template || !template.trim()) {\n const parts = key.split('.');\n\n return parts[parts.length - 1];\n }\n\n if (value !== undefined) {\n const formattedValue = format === 'i' ? formatInteger(value) : value;\n const result = processTemplate(template, formattedValue);\n const cacheValue = Array.isArray(value) ? JSON.stringify(value) : value;\n cache.set(`${key}_${cacheValue}_${format}`, result);\n return result;\n }\n\n return template;\n}\n","export function createCallbackManager() {\n const callbacks: AnyToVoidFunction[] = [];\n\n function addCallback(cb: AnyToVoidFunction) {\n callbacks.push(cb);\n\n return () => {\n removeCallback(cb);\n };\n }\n\n function removeCallback(cb: AnyToVoidFunction) {\n const index = callbacks.indexOf(cb);\n if (index !== -1) {\n callbacks.splice(index, 1);\n }\n }\n\n function runCallbacks(...args: any[]) {\n callbacks.forEach((callback) => {\n callback(...args);\n });\n }\n\n return {\n runCallbacks,\n addCallback,\n removeCallback,\n };\n}\n","const SAMPLE_RATE = 48000;\nconst BIT_DEPTH = 16;\n\nexport async function oggToWav(opusData: Blob): Promise {\n const arrayBuffer = await new Response(opusData).arrayBuffer();\n\n return new Promise((resolve) => {\n const typedArray = new Uint8Array(arrayBuffer);\n\n let decoderWorker: Worker | undefined = new Worker(\n new URL('opus-recorder/dist/decoderWorker.min.js', import.meta.url),\n );\n let wavWorker: Worker | undefined = new Worker(new URL('opus-recorder/dist/waveWorker.min.js', import.meta.url));\n\n decoderWorker.onmessage = (e) => {\n // eslint-disable-next-line no-null/no-null\n if (e.data === null) {\n // `null` means decoder is finished\n wavWorker!.postMessage({ command: 'done' });\n } else {\n // `e.data` contains decoded buffers as float32 values\n wavWorker!.postMessage(\n {\n command: 'encode',\n buffers: e.data,\n },\n e.data.map(({ buffer }: Float32Array) => buffer),\n );\n }\n };\n\n wavWorker.onmessage = (e) => {\n if (e.data.message === 'page') {\n resolve(new Blob([e.data.page], { type: 'audio/wav' }));\n\n decoderWorker!.terminate();\n decoderWorker = undefined;\n wavWorker!.terminate();\n wavWorker = undefined;\n }\n };\n\n wavWorker.postMessage({\n command: 'init',\n wavBitDepth: BIT_DEPTH,\n wavSampleRate: SAMPLE_RATE,\n });\n\n decoderWorker.postMessage({\n command: 'init',\n decoderSampleRate: SAMPLE_RATE,\n outputBufferSampleRate: SAMPLE_RATE,\n });\n\n decoderWorker.postMessage({\n command: 'decode',\n pages: typedArray,\n }, [typedArray.buffer]);\n });\n}\n","import {\n ApiMediaFormat,\n ApiMediaFormatToPrepared,\n ApiOnProgress,\n ApiParsedMedia,\n ApiPreparedMedia,\n} from '../api/types';\n\nimport {\n DEBUG, MEDIA_CACHE_DISABLED, MEDIA_CACHE_NAME, MEDIA_CACHE_NAME_AVATARS,\n} from '../config';\nimport { callApi, cancelApiProgress } from '../api/gramjs';\nimport * as cacheApi from './cacheApi';\nimport { fetchBlob } from './files';\nimport { IS_OPUS_SUPPORTED, IS_PROGRESSIVE_SUPPORTED, isWebpSupported } from './environment';\nimport { oggToWav } from './oggToWav';\nimport { webpToPng } from './webpToPng';\n\nconst asCacheApiType = {\n [ApiMediaFormat.BlobUrl]: cacheApi.Type.Blob,\n [ApiMediaFormat.Lottie]: cacheApi.Type.Json,\n [ApiMediaFormat.Progressive]: undefined,\n [ApiMediaFormat.Stream]: undefined,\n};\n\nconst PROGRESSIVE_URL_PREFIX = './progressive/';\n\nconst memoryCache = new Map();\nconst fetchPromises = new Map>();\nconst progressCallbacks = new Map>();\nconst cancellableCallbacks = new Map();\n\nexport function fetch(\n url: string,\n mediaFormat: T,\n isHtmlAllowed = false,\n onProgress?: ApiOnProgress,\n callbackUniqueId?: string,\n): Promise> {\n if (mediaFormat === ApiMediaFormat.Progressive) {\n return (\n IS_PROGRESSIVE_SUPPORTED\n ? getProgressive(url)\n : fetch(url, ApiMediaFormat.BlobUrl, isHtmlAllowed, onProgress, callbackUniqueId)\n ) as Promise>;\n }\n\n if (!fetchPromises.has(url)) {\n const promise = fetchFromCacheOrRemote(url, mediaFormat, isHtmlAllowed)\n .catch((err) => {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n\n return undefined;\n })\n .finally(() => {\n fetchPromises.delete(url);\n progressCallbacks.delete(url);\n cancellableCallbacks.delete(url);\n });\n\n fetchPromises.set(url, promise);\n }\n\n if (onProgress && callbackUniqueId) {\n let activeCallbacks = progressCallbacks.get(url);\n if (!activeCallbacks) {\n activeCallbacks = new Map();\n progressCallbacks.set(url, activeCallbacks);\n }\n activeCallbacks.set(callbackUniqueId, onProgress);\n }\n\n return fetchPromises.get(url) as Promise>;\n}\n\nexport function getFromMemory(url: string) {\n return memoryCache.get(url) as ApiMediaFormatToPrepared;\n}\n\nexport function cancelProgress(progressCallback: ApiOnProgress) {\n progressCallbacks.forEach((map, url) => {\n map.forEach((callback) => {\n if (callback === progressCallback) {\n const parentCallback = cancellableCallbacks.get(url);\n if (!parentCallback) return;\n\n cancelApiProgress(parentCallback);\n cancellableCallbacks.delete(url);\n progressCallbacks.delete(url);\n }\n });\n });\n}\n\nexport function removeCallback(url: string, callbackUniqueId: string) {\n const callbacks = progressCallbacks.get(url);\n if (!callbacks) return;\n callbacks.delete(callbackUniqueId);\n}\n\nfunction getProgressive(url: string) {\n const progressiveUrl = `${PROGRESSIVE_URL_PREFIX}${url}`;\n\n memoryCache.set(url, progressiveUrl);\n\n return Promise.resolve(progressiveUrl);\n}\n\nasync function fetchFromCacheOrRemote(\n url: string, mediaFormat: ApiMediaFormat, isHtmlAllowed: boolean,\n) {\n if (!MEDIA_CACHE_DISABLED) {\n const cacheName = url.startsWith('avatar') ? MEDIA_CACHE_NAME_AVATARS : MEDIA_CACHE_NAME;\n const cached = await cacheApi.fetch(cacheName, url, asCacheApiType[mediaFormat]!, isHtmlAllowed);\n\n if (cached) {\n let media = cached;\n\n if (cached.type === 'audio/ogg' && !IS_OPUS_SUPPORTED) {\n media = await oggToWav(media);\n }\n\n if (cached.type === 'image/webp' && !isWebpSupported() && media) {\n const mediaPng = await webpToPng(url, media);\n if (mediaPng) {\n media = mediaPng;\n }\n }\n\n const prepared = prepareMedia(media);\n\n memoryCache.set(url, prepared);\n\n return prepared;\n }\n }\n\n if (mediaFormat === ApiMediaFormat.Stream) {\n const mediaSource = new MediaSource();\n const streamUrl = URL.createObjectURL(mediaSource);\n let isOpen = false;\n\n mediaSource.addEventListener('sourceopen', () => {\n if (isOpen) {\n return;\n }\n isOpen = true;\n\n const sourceBuffer = mediaSource.addSourceBuffer('audio/mpeg');\n\n const onProgress = makeOnProgress(url, mediaSource, sourceBuffer);\n cancellableCallbacks.set(url, onProgress);\n\n void callApi('downloadMedia', { url, mediaFormat }, onProgress);\n });\n\n memoryCache.set(url, streamUrl);\n return streamUrl;\n }\n\n const onProgress = makeOnProgress(url);\n cancellableCallbacks.set(url, onProgress);\n\n const remote = await callApi('downloadMedia', { url, mediaFormat, isHtmlAllowed }, onProgress);\n if (!remote) {\n throw new Error(`Failed to fetch media ${url}`);\n }\n\n let { prepared, mimeType } = remote;\n\n if (mimeType === 'audio/ogg' && !IS_OPUS_SUPPORTED) {\n const blob = await fetchBlob(prepared as string);\n URL.revokeObjectURL(prepared as string);\n const media = await oggToWav(blob);\n prepared = prepareMedia(media);\n mimeType = media.type;\n }\n\n if (mimeType === 'image/webp' && !isWebpSupported()) {\n const blob = await fetchBlob(prepared as string);\n URL.revokeObjectURL(prepared as string);\n const media = await webpToPng(url, blob);\n if (media) {\n prepared = prepareMedia(media);\n }\n }\n\n memoryCache.set(url, prepared);\n\n return prepared;\n}\n\nfunction makeOnProgress(url: string, mediaSource?: MediaSource, sourceBuffer?: SourceBuffer) {\n const onProgress: ApiOnProgress = (progress: number, arrayBuffer: ArrayBuffer) => {\n progressCallbacks.get(url)?.forEach((callback) => {\n callback(progress);\n if (callback.isCanceled) onProgress.isCanceled = true;\n });\n\n if (progress === 1) {\n mediaSource?.endOfStream();\n }\n\n if (!arrayBuffer) {\n return;\n }\n\n sourceBuffer?.appendBuffer(arrayBuffer);\n };\n\n return onProgress;\n}\n\nfunction prepareMedia(mediaData: ApiParsedMedia): ApiPreparedMedia {\n if (mediaData instanceof Blob) {\n return URL.createObjectURL(mediaData);\n }\n\n return mediaData;\n}\n\nif (IS_PROGRESSIVE_SUPPORTED) {\n navigator.serviceWorker.addEventListener('message', async (e) => {\n const { type, messageId, params } = e.data as {\n type: string;\n messageId: string;\n params: { url: string; start: number; end: number };\n };\n\n if (type !== 'requestPart') {\n return;\n }\n\n const result = await callApi('downloadMedia', { mediaFormat: ApiMediaFormat.Progressive, ...params });\n if (!result) {\n return;\n }\n\n const { arrayBuffer, mimeType, fullSize } = result;\n\n navigator.serviceWorker.controller!.postMessage({\n type: 'partResponse',\n messageId,\n result: {\n arrayBuffer,\n mimeType,\n fullSize,\n },\n }, [arrayBuffer!]);\n });\n}\n","export const MEMO_EMPTY_ARRAY = [];\n","import { DEBUG } from '../config';\n\nexport enum Bundles {\n Auth,\n Main,\n Extra,\n}\n\ninterface ImportedBundles {\n [Bundles.Auth]: typeof import('../bundles/auth');\n [Bundles.Main]: typeof import('../bundles/main');\n [Bundles.Extra]: typeof import('../bundles/extra');\n}\n\ntype BundlePromises = {\n [K in keyof ImportedBundles]: Promise\n};\n\nexport type BundleModules = keyof ImportedBundles[B];\n\nconst LOAD_PROMISES: Partial = {};\nconst MEMORY_CACHE: Partial = {};\n\nexport async function loadModule>(bundleName: B, moduleName: M) {\n if (!LOAD_PROMISES[bundleName]) {\n switch (bundleName) {\n case Bundles.Auth:\n LOAD_PROMISES[Bundles.Auth] = import('../bundles/auth');\n break;\n case Bundles.Main:\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START LOAD MAIN BUNDLE');\n }\n\n LOAD_PROMISES[Bundles.Main] = import('../bundles/main');\n break;\n case Bundles.Extra:\n LOAD_PROMISES[Bundles.Extra] = import('../bundles/extra');\n break;\n }\n\n (LOAD_PROMISES[bundleName] as Promise).then(handleBundleLoad);\n }\n\n const bundle = (await LOAD_PROMISES[bundleName]) as unknown as ImportedBundles[B];\n\n if (!MEMORY_CACHE[bundleName]) {\n MEMORY_CACHE[bundleName] = bundle;\n }\n\n return getModuleFromMemory(bundleName, moduleName);\n}\n\nexport function getModuleFromMemory>(bundleName: B, moduleName: M) {\n const bundle = MEMORY_CACHE[bundleName] as ImportedBundles[B];\n\n if (!bundle) {\n return undefined;\n }\n\n return bundle[moduleName];\n}\n\nconst listeners: NoneToVoidFunction[] = [];\n\nexport function addLoadListener(listener: NoneToVoidFunction) {\n if (!listeners.includes(listener)) {\n listeners.push(listener);\n }\n}\n\nfunction handleBundleLoad() {\n listeners.forEach((listener) => {\n listener();\n });\n}\n","import { callApi } from '../api/gramjs';\nimport {\n ApiChat, ApiMediaFormat, ApiMessage, ApiUser,\n} from '../api/types';\nimport { renderActionMessageText } from '../components/common/helpers/renderActionMessageText';\nimport { DEBUG, IS_TEST } from '../config';\nimport { getDispatch, getGlobal, setGlobal } from '../lib/teact/teactn';\nimport {\n getChatAvatarHash,\n getChatTitle,\n getMessageAction,\n getMessageSenderName,\n getMessageSummaryText,\n getPrivateChatUserId,\n isActionMessage,\n isChatChannel,\n selectIsChatMuted, selectShouldShowMessagePreview,\n} from '../modules/helpers';\nimport { getTranslation } from './langProvider';\nimport { addNotifyExceptions, replaceSettings } from '../modules/reducers';\nimport {\n selectChatMessage, selectNotifyExceptions, selectNotifySettings, selectUser,\n} from '../modules/selectors';\nimport { IS_SERVICE_WORKER_SUPPORTED } from './environment';\nimport * as mediaLoader from './mediaLoader';\nimport { debounce } from './schedulers';\n\nfunction getDeviceToken(subscription: PushSubscription) {\n const data = subscription.toJSON();\n return JSON.stringify({\n endpoint: data.endpoint,\n keys: data.keys,\n });\n}\n\nfunction checkIfPushSupported() {\n if (!IS_SERVICE_WORKER_SUPPORTED) return false;\n if (!('showNotification' in ServiceWorkerRegistration.prototype)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('[PUSH] Push notifications aren\\'t supported.');\n }\n return false;\n }\n\n // Check the current Notification permission.\n // If its denied, it's a permanent block until the\n // user changes the permission\n if (Notification.permission === 'denied') {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('[PUSH] The user has blocked push notifications.');\n }\n return false;\n }\n\n // Check if push messaging is supported\n if (!('PushManager' in window)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('[PUSH] Push messaging isn\\'t supported.');\n }\n return false;\n }\n return true;\n}\n\nfunction checkIfNotificationsSupported() {\n // Let's check if the browser supports notifications\n if (!('Notification' in window)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('[PUSH] This browser does not support desktop notification');\n }\n return false;\n }\n\n if (Notification.permission === 'denied' as NotificationPermission) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('[PUSH] The user has blocked push notifications.');\n }\n return false;\n }\n return true;\n}\n\nconst expirationTime = 12 * 60 * 60 * 1000; // 12 hours\n// Notification id is removed from soundPlayed cache after 3 seconds\nconst soundPlayedDelay = 3 * 1000;\nconst soundPlayedIds = new Set();\n\nexport async function playNotifySound(id?: string, volume?: number) {\n if (id !== undefined && soundPlayedIds.has(id)) return;\n const { notificationSoundVolume } = selectNotifySettings(getGlobal());\n const currentVolume = volume ? volume / 10 : notificationSoundVolume / 10;\n if (currentVolume === 0) return;\n\n const audio = new Audio('./notification.mp3');\n audio.volume = currentVolume;\n audio.setAttribute('mozaudiochannel', 'notification');\n if (id !== undefined) {\n audio.addEventListener('ended', () => {\n soundPlayedIds.add(id);\n }, { once: true });\n\n setTimeout(() => {\n soundPlayedIds.delete(id);\n }, soundPlayedDelay);\n }\n\n try {\n await audio.play();\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('[PUSH] Unable to play notification sound');\n }\n }\n}\n\nexport const playNotifySoundDebounced = debounce(playNotifySound, 1000, true, false);\n\nfunction checkIfShouldResubscribe(subscription: PushSubscription | null) {\n const global = getGlobal();\n if (!global.push || !subscription) return true;\n if (getDeviceToken(subscription) !== global.push.deviceToken) return true;\n return Date.now() - global.push.subscribedAt > expirationTime;\n}\n\nasync function requestPermission() {\n if (!('Notification' in window)) return;\n if (!['granted', 'denied'].includes(Notification.permission)) {\n await Notification.requestPermission();\n }\n}\n\nasync function unsubscribeFromPush(subscription: PushSubscription | null) {\n const global = getGlobal();\n const dispatch = getDispatch();\n if (subscription) {\n try {\n const deviceToken = getDeviceToken(subscription);\n await callApi('unregisterDevice', deviceToken);\n await subscription.unsubscribe();\n dispatch.deleteDeviceToken();\n return;\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[PUSH] Unable to unsubscribe from push.', error);\n }\n }\n }\n if (global.push) {\n await callApi('unregisterDevice', global.push.deviceToken);\n dispatch.deleteDeviceToken();\n }\n}\n\nexport async function unsubscribe() {\n if (!checkIfPushSupported()) return;\n const serviceWorkerRegistration = await navigator.serviceWorker.ready;\n const subscription = await serviceWorkerRegistration.pushManager.getSubscription();\n await unsubscribeFromPush(subscription);\n}\n\n// Indicates if notification settings are loaded from the api\nlet areSettingsLoaded = false;\n\n// Load notification settings from the api\nasync function loadNotificationSettings() {\n if (areSettingsLoaded) return selectNotifySettings(getGlobal());\n const [resultSettings, resultExceptions] = await Promise.all([\n callApi('fetchNotificationSettings', {\n serverTimeOffset: getGlobal().serverTimeOffset,\n }),\n callApi('fetchNotificationExceptions', {\n serverTimeOffset: getGlobal().serverTimeOffset,\n }),\n ]);\n if (!resultSettings) return selectNotifySettings(getGlobal());\n\n let global = replaceSettings(getGlobal(), resultSettings);\n if (resultExceptions) {\n global = addNotifyExceptions(global, resultExceptions);\n }\n setGlobal(global);\n areSettingsLoaded = true;\n return selectNotifySettings(global);\n}\n\nexport async function subscribe() {\n if (!checkIfPushSupported()) {\n // Ask for notification permissions only if service worker notifications are not supported\n // As pushManager.subscribe automatically triggers permission popup\n await requestPermission();\n return;\n }\n const serviceWorkerRegistration = await navigator.serviceWorker.ready;\n let subscription = await serviceWorkerRegistration.pushManager.getSubscription();\n if (!checkIfShouldResubscribe(subscription)) return;\n await unsubscribeFromPush(subscription);\n try {\n subscription = await serviceWorkerRegistration.pushManager.subscribe({\n userVisibleOnly: true,\n });\n const deviceToken = getDeviceToken(subscription);\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[PUSH] Received push subscription: ', deviceToken);\n }\n await callApi('registerDevice', deviceToken);\n getDispatch()\n .setDeviceToken(deviceToken);\n } catch (error) {\n if (Notification.permission === 'denied' as NotificationPermission) {\n // The user denied the notification permission which\n // means we failed to subscribe and the user will need\n // to manually change the notification permission to\n // subscribe to push messages\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('[PUSH] The user has blocked push notifications.');\n }\n } else if (DEBUG) {\n // A problem occurred with the subscription, this can\n // often be down to an issue or lack of the gcm_sender_id\n // and / or gcm_user_visible_only\n // eslint-disable-next-line no-console\n console.log('[PUSH] Unable to subscribe to push.', error);\n\n // Request permissions and fall back to local notifications\n // if pushManager.subscribe was aborted due to invalid VAPID key.\n if (error.code === DOMException.ABORT_ERR) {\n await requestPermission();\n }\n }\n }\n}\n\nfunction checkIfShouldNotify(chat: ApiChat) {\n if (!areSettingsLoaded) return false;\n const global = getGlobal();\n const isMuted = selectIsChatMuted(chat, selectNotifySettings(global), selectNotifyExceptions(global));\n if (isMuted || chat.isNotJoined || !chat.isListed) {\n return false;\n }\n\n return !document.hasFocus();\n}\n\nfunction getNotificationContent(chat: ApiChat, message: ApiMessage) {\n const global = getGlobal();\n const {\n senderId,\n replyToMessageId,\n } = message;\n\n const messageSender = senderId ? selectUser(global, senderId) : undefined;\n const messageAction = getMessageAction(message as ApiMessage);\n const actionTargetMessage = messageAction && replyToMessageId\n ? selectChatMessage(global, chat.id, replyToMessageId)\n : undefined;\n const {\n targetUserIds: actionTargetUserIds,\n targetChatId: actionTargetChatId,\n } = messageAction || {};\n\n const actionTargetUsers = actionTargetUserIds\n ? actionTargetUserIds.map((userId) => selectUser(global, userId))\n .filter(Boolean as any)\n : undefined;\n const privateChatUserId = getPrivateChatUserId(chat);\n const privateChatUser = privateChatUserId ? selectUser(global, privateChatUserId) : undefined;\n\n let body: string;\n if (selectShouldShowMessagePreview(chat, selectNotifySettings(global), selectNotifyExceptions(global))) {\n if (isActionMessage(message)) {\n const actionOrigin = chat && (isChatChannel(chat) || message.senderId === message.chatId)\n ? chat\n : messageSender;\n body = renderActionMessageText(\n getTranslation,\n message,\n actionOrigin,\n actionTargetUsers,\n actionTargetMessage,\n actionTargetChatId,\n { asPlain: true },\n ) as string;\n } else {\n const senderName = getMessageSenderName(getTranslation, chat.id, messageSender);\n const summary = getMessageSummaryText(getTranslation, message);\n\n body = senderName ? `${senderName}: ${summary}` : summary;\n }\n } else {\n body = 'New message';\n }\n\n return {\n title: getChatTitle(getTranslation, chat, privateChatUser),\n body,\n };\n}\n\nasync function getAvatar(chat: ApiChat) {\n const imageHash = getChatAvatarHash(chat);\n if (!imageHash) return undefined;\n let mediaData = mediaLoader.getFromMemory(imageHash);\n if (!mediaData) {\n await mediaLoader.fetch(imageHash, ApiMediaFormat.BlobUrl);\n mediaData = mediaLoader.getFromMemory(imageHash);\n }\n return mediaData;\n}\n\nexport async function notifyAboutNewMessage({\n chat,\n message,\n}: { chat: ApiChat; message: Partial }) {\n const { hasWebNotifications } = await loadNotificationSettings();\n if (!checkIfShouldNotify(chat)) return;\n const areNotificationsSupported = checkIfNotificationsSupported();\n if (!hasWebNotifications || !areNotificationsSupported) {\n // only play sound if web notifications are disabled\n playNotifySoundDebounced(String(message.id) || chat.id);\n return;\n }\n if (!areNotificationsSupported) return;\n if (!message.id) return;\n\n const {\n title,\n body,\n } = getNotificationContent(chat, message as ApiMessage);\n\n const icon = await getAvatar(chat);\n\n if (checkIfPushSupported()) {\n if (navigator.serviceWorker?.controller) {\n // notify service worker about new message notification\n navigator.serviceWorker.controller.postMessage({\n type: 'newMessageNotification',\n payload: {\n title,\n body,\n icon,\n chatId: chat.id,\n messageId: message.id,\n },\n });\n }\n } else {\n const dispatch = getDispatch();\n const options: NotificationOptions = {\n body,\n icon,\n badge: icon,\n tag: String(message.id),\n };\n\n if ('vibrate' in navigator) {\n options.vibrate = [200, 100, 200];\n }\n\n const notification = new Notification(title, options);\n\n notification.onclick = () => {\n notification.close();\n dispatch.focusMessage({\n chatId: chat.id,\n messageId: message.id,\n });\n if (window.focus) {\n window.focus();\n }\n };\n\n // Play sound when notification is displayed\n notification.onshow = () => {\n playNotifySoundDebounced(String(message.id) || chat.id);\n };\n }\n}\n\nexport function closeMessageNotifications(payload: { chatId: string; lastReadInboxMessageId?: number }) {\n if (IS_TEST || !navigator.serviceWorker?.controller) return;\n navigator.serviceWorker.controller.postMessage({\n type: 'closeMessageNotifications',\n payload,\n });\n}\n\n// Notify service worker that client is fully loaded\nexport function notifyClientReady() {\n if (!navigator.serviceWorker?.controller) return;\n navigator.serviceWorker.controller.postMessage({\n type: 'clientReady',\n });\n}\n","import { ApiCountryCode } from '../api/types';\nimport { flatten } from './iteratees';\n\nconst PATTERN_PLACEHOLDER = 'X';\nconst DEFAULT_PATTERN = 'XXX XXX XXX XXX';\n\nexport function getCountryCodesByIso(phoneCodeList: ApiCountryCode[], iso: string) {\n return phoneCodeList.filter((country) => country.iso2 === iso);\n}\n\nexport function getCountryFromPhoneNumber(phoneCodeList: ApiCountryCode[], input = '') {\n let phoneNumber = input.replace(/[^\\d+]+/g, '');\n if (phoneNumber.startsWith('+')) {\n phoneNumber = phoneNumber.substr(1);\n }\n\n const possibleCountries = phoneCodeList\n .filter((country) => phoneNumber.startsWith(country.countryCode));\n const codesWithPrefix: { code: string; country: ApiCountryCode }[] = flatten(possibleCountries\n .map((country) => (country.prefixes || ['']).map((prefix) => {\n return {\n code: `${country.countryCode}${prefix}`,\n country,\n };\n })));\n\n const bestMatches = codesWithPrefix\n .filter(({ code }) => phoneNumber.startsWith(code))\n .sort((a, b) => a.code.length - b.code.length);\n\n return bestMatches[bestMatches.length - 1]?.country;\n}\n\nexport function formatPhoneNumber(input: string, country?: ApiCountryCode) {\n let phoneNumber = input.replace(/[^\\d]+/g, '');\n if (country) {\n phoneNumber = phoneNumber.substr(country.countryCode.length);\n } else if (input.startsWith('+')) {\n return input;\n }\n const pattern = getBestPattern(phoneNumber, country?.patterns);\n\n const result: string[] = []; // Result character array\n let j = 0; // Position inside pattern\n for (let i = 0; i < phoneNumber.length; i++) {\n while (pattern[j] !== PATTERN_PLACEHOLDER && j < pattern.length) {\n result.push(pattern[j]);\n if (pattern[j] === phoneNumber[i]) { // If pattern contains digits, move input position too\n i++;\n if (i === phoneNumber.length) break; // But don't overdo it, or it will insert full pattern unexpectedly\n }\n j++;\n }\n\n result.push(phoneNumber[i]); // For placeholder characters, setting current input digit\n j++;\n }\n\n return result.join('');\n}\n\nfunction getBestPattern(numberWithoutCode: string, patterns?: string[]) {\n if (!patterns || patterns.length === 0) return DEFAULT_PATTERN;\n if (patterns.length === 1) return patterns[0];\n\n const defaultPattern = patterns.find((pattern) => pattern.startsWith(PATTERN_PLACEHOLDER)) || DEFAULT_PATTERN;\n\n const bestMatches = patterns.filter((pattern) => {\n const stripped = pattern.replace(/[^\\dX]+/g, '');\n if (stripped.startsWith(PATTERN_PLACEHOLDER)) return false; // Don't consider default number format here\n for (let i = 0; i < numberWithoutCode.length; i++) {\n if (i > stripped.length - 1 || (stripped[i] !== PATTERN_PLACEHOLDER && stripped[i] !== numberWithoutCode[i])) {\n return false;\n }\n }\n return true;\n });\n\n // Playing it safe: if not sure, use default for that region\n return bestMatches.length === 1 ? bestMatches[0] : defaultPattern;\n}\n\nexport function formatPhoneNumberWithCode(phoneCodeList: ApiCountryCode[], phoneNumber: string) {\n const numberWithPlus = phoneNumber.startsWith('+') ? phoneNumber : `+${phoneNumber}`;\n const country = getCountryFromPhoneNumber(phoneCodeList, numberWithPlus);\n if (!country) {\n return numberWithPlus;\n }\n return `+${country.countryCode} ${formatPhoneNumber(numberWithPlus, country)}`;\n}\n","import { MessageList, MessageListType } from '../global/types';\nimport { MAIN_THREAD_ID } from '../api/types';\n\nexport const createMessageHash = (messageList: MessageList): string => (\n messageList.chatId.toString()\n + (messageList.type !== 'thread' ? `_${messageList.type}`\n : (messageList.threadId !== -1 ? `_${messageList.threadId}` : ''))\n);\n\nexport const parseLocationHash = (value: string): MessageList | undefined => {\n if (!value) return undefined;\n\n const [chatId, typeOrThreadId] = value.replace(/^#/, '').split('_');\n\n if (!chatId) return undefined;\n\n const isType = ['thread', 'pinned', 'scheduled'].includes(typeOrThreadId);\n\n return {\n chatId,\n type: !!typeOrThreadId && isType ? (typeOrThreadId as MessageListType) : 'thread',\n threadId: !!typeOrThreadId && !isType ? Number(typeOrThreadId) : MAIN_THREAD_ID,\n };\n};\n","type Scheduler =\n typeof requestAnimationFrame\n | typeof onTickEnd\n | typeof runNow;\n\nexport function debounce(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n shouldRunLast = true,\n) {\n let waitingTimeout: number | undefined;\n\n return (...args: Parameters) => {\n if (waitingTimeout) {\n clearTimeout(waitingTimeout);\n waitingTimeout = undefined;\n } else if (shouldRunFirst) {\n // @ts-ignore\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n waitingTimeout = self.setTimeout(() => {\n if (shouldRunLast) {\n // @ts-ignore\n fn(...args);\n }\n\n waitingTimeout = undefined;\n }, ms);\n };\n}\n\nexport function throttle(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n) {\n let interval: number | undefined;\n let isPending: boolean;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n isPending = true;\n args = _args;\n\n if (!interval) {\n if (shouldRunFirst) {\n isPending = false;\n // @ts-ignore\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n interval = self.setInterval(() => {\n if (!isPending) {\n // eslint-disable-next-line no-restricted-globals\n self.clearInterval(interval!);\n interval = undefined;\n return;\n }\n\n isPending = false;\n // @ts-ignore\n fn(...args);\n }, ms);\n }\n };\n}\n\nexport function throttleWithRaf(fn: F) {\n return throttleWith(fastRaf, fn);\n}\n\nexport function throttleWithPrimaryRaf(fn: F) {\n return throttleWith(fastRafPrimary, fn);\n}\n\nexport function throttleWithTickEnd(fn: F) {\n return throttleWith(onTickEnd, fn);\n}\n\nexport function throttleWithNow(fn: F) {\n return throttleWith(runNow, fn);\n}\n\nexport function throttleWith(schedulerFn: Scheduler, fn: F) {\n let waiting = false;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n args = _args;\n\n if (!waiting) {\n waiting = true;\n\n schedulerFn(() => {\n waiting = false;\n // @ts-ignore\n fn(...args);\n });\n }\n };\n}\n\nexport function onIdle(cb: NoneToVoidFunction) {\n // eslint-disable-next-line no-restricted-globals\n if (self.requestIdleCallback) {\n // eslint-disable-next-line no-restricted-globals\n self.requestIdleCallback(cb);\n } else {\n onTickEnd(cb);\n }\n}\n\nfunction runNow(fn: NoneToVoidFunction) {\n fn();\n}\n\nexport const pause = (ms: number) => new Promise((resolve) => {\n setTimeout(() => resolve(), ms);\n});\n\nexport function rafPromise() {\n return new Promise((resolve) => {\n fastRaf(resolve);\n });\n}\n\nlet fastRafCallbacks: NoneToVoidFunction[] | undefined;\nlet fastRafPrimaryCallbacks: NoneToVoidFunction[] | undefined;\n\n// May result in an immediate execution if called from another `requestAnimationFrame` callback\nexport function fastRaf(callback: NoneToVoidFunction, isPrimary = false) {\n if (!fastRafCallbacks) {\n fastRafCallbacks = isPrimary ? [] : [callback];\n fastRafPrimaryCallbacks = isPrimary ? [callback] : [];\n\n requestAnimationFrame(() => {\n const currentCallbacks = fastRafCallbacks!;\n const currentPrimaryCallbacks = fastRafPrimaryCallbacks!;\n fastRafCallbacks = undefined;\n fastRafPrimaryCallbacks = undefined;\n currentPrimaryCallbacks.forEach((cb) => cb());\n currentCallbacks.forEach((cb) => cb());\n });\n } else if (isPrimary) {\n fastRafPrimaryCallbacks!.push(callback);\n } else {\n fastRafCallbacks.push(callback);\n }\n}\n\nexport function fastRafPrimary(callback: NoneToVoidFunction) {\n fastRaf(callback, true);\n}\n\nlet onTickEndCallbacks: NoneToVoidFunction[] | undefined;\nlet onTickEndPrimaryCallbacks: NoneToVoidFunction[] | undefined;\n\nexport function onTickEnd(callback: NoneToVoidFunction, isPrimary = false) {\n if (!onTickEndCallbacks) {\n onTickEndCallbacks = isPrimary ? [] : [callback];\n onTickEndPrimaryCallbacks = isPrimary ? [callback] : [];\n\n Promise.resolve().then(() => {\n const currentCallbacks = onTickEndCallbacks!;\n const currentPrimaryCallbacks = onTickEndPrimaryCallbacks!;\n onTickEndCallbacks = undefined;\n onTickEndPrimaryCallbacks = undefined;\n currentPrimaryCallbacks.forEach((cb) => cb());\n currentCallbacks.forEach((cb) => cb());\n });\n } else if (isPrimary) {\n onTickEndPrimaryCallbacks!.push(callback);\n } else {\n onTickEndCallbacks.push(callback);\n }\n}\n\nexport function onTickEndPrimary(callback: NoneToVoidFunction) {\n onTickEnd(callback, true);\n}\n\nlet beforeUnloadCallbacks: NoneToVoidFunction[] | undefined;\n\nexport function onBeforeUnload(callback: NoneToVoidFunction, isLast = false) {\n if (!beforeUnloadCallbacks) {\n beforeUnloadCallbacks = [];\n // eslint-disable-next-line no-restricted-globals\n self.addEventListener('beforeunload', () => {\n beforeUnloadCallbacks!.forEach((cb) => cb());\n });\n }\n\n if (isLast) {\n beforeUnloadCallbacks.push(callback);\n } else {\n beforeUnloadCallbacks.unshift(callback);\n }\n\n return () => {\n beforeUnloadCallbacks = beforeUnloadCallbacks!.filter((cb) => cb !== callback);\n };\n}\n","let RE_NOT_LETTER: RegExp;\n\ntry {\n RE_NOT_LETTER = new RegExp('[^\\\\p{L}\\\\p{M}]+', 'ui');\n} catch (e) {\n // Support for older versions of firefox\n RE_NOT_LETTER = new RegExp('[^\\\\wа-яё]+', 'i');\n}\n\nexport default function searchWords(haystack: string, needle: string) {\n if (!haystack || !needle) {\n return false;\n }\n\n const haystackWords = haystack.toLowerCase().split(RE_NOT_LETTER);\n const needleWords = needle.toLowerCase().split(RE_NOT_LETTER);\n\n return needleWords.every((needleWord) => (\n haystackWords.some((haystackWord) => haystackWord.startsWith(needleWord))\n ));\n}\n","export const getServerTime = (serverTimeOffset: number) => {\n return Math.floor(Date.now() / 1000) + serverTimeOffset;\n};\n","import safariFix from 'safari-14-idb-fix';\n\nfunction promisifyRequest(request) {\n return new Promise((resolve, reject) => {\n // @ts-ignore - file size hacks\n request.oncomplete = request.onsuccess = () => resolve(request.result);\n // @ts-ignore - file size hacks\n request.onabort = request.onerror = () => reject(request.error);\n });\n}\nfunction createStore(dbName, storeName) {\n const dbp = safariFix().then(() => {\n const request = indexedDB.open(dbName);\n request.onupgradeneeded = () => request.result.createObjectStore(storeName);\n return promisifyRequest(request);\n });\n return (txMode, callback) => dbp.then((db) => callback(db.transaction(storeName, txMode).objectStore(storeName)));\n}\nlet defaultGetStoreFunc;\nfunction defaultGetStore() {\n if (!defaultGetStoreFunc) {\n defaultGetStoreFunc = createStore('keyval-store', 'keyval');\n }\n return defaultGetStoreFunc;\n}\n/**\n * Get a value by its key.\n *\n * @param key\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction get(key, customStore = defaultGetStore()) {\n return customStore('readonly', (store) => promisifyRequest(store.get(key)));\n}\n/**\n * Set a value with a key.\n *\n * @param key\n * @param value\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction set(key, value, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.put(value, key);\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Set multiple values at once. This is faster than calling set() multiple times.\n * It's also atomic – if one of the pairs can't be added, none will be added.\n *\n * @param entries Array of entries, where each entry is an array of `[key, value]`.\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction setMany(entries, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n entries.forEach((entry) => store.put(entry[1], entry[0]));\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Get multiple values by their keys\n *\n * @param keys\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction getMany(keys, customStore = defaultGetStore()) {\n return customStore('readonly', (store) => Promise.all(keys.map((key) => promisifyRequest(store.get(key)))));\n}\n/**\n * Update a value. This lets you see the old value and update it as an atomic operation.\n *\n * @param key\n * @param updater A callback that takes the old value and returns a new value.\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction update(key, updater, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => \n // Need to create the promise manually.\n // If I try to chain promises, the transaction closes in browsers\n // that use a promise polyfill (IE10/11).\n new Promise((resolve, reject) => {\n store.get(key).onsuccess = function () {\n try {\n store.put(updater(this.result), key);\n resolve(promisifyRequest(store.transaction));\n }\n catch (err) {\n reject(err);\n }\n };\n }));\n}\n/**\n * Delete a particular key from the store.\n *\n * @param key\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction del(key, customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.delete(key);\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Clear all values in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction clear(customStore = defaultGetStore()) {\n return customStore('readwrite', (store) => {\n store.clear();\n return promisifyRequest(store.transaction);\n });\n}\nfunction eachCursor(customStore, callback) {\n return customStore('readonly', (store) => {\n // This would be store.getAllKeys(), but it isn't supported by Edge or Safari.\n // And openKeyCursor isn't supported by Safari.\n store.openCursor().onsuccess = function () {\n if (!this.result)\n return;\n callback(this.result);\n this.result.continue();\n };\n return promisifyRequest(store.transaction);\n });\n}\n/**\n * Get all keys in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction keys(customStore = defaultGetStore()) {\n const items = [];\n return eachCursor(customStore, (cursor) => items.push(cursor.key)).then(() => items);\n}\n/**\n * Get all values in the store.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction values(customStore = defaultGetStore()) {\n const items = [];\n return eachCursor(customStore, (cursor) => items.push(cursor.value)).then(() => items);\n}\n/**\n * Get all entries in the store. Each entry is an array of `[key, value]`.\n *\n * @param customStore Method to get a custom store. Use with caution (see the docs).\n */\nfunction entries(customStore = defaultGetStore()) {\n const items = [];\n return eachCursor(customStore, (cursor) => items.push([cursor.key, cursor.value])).then(() => items);\n}\n\nexport { clear, createStore, del, entries, get, getMany, keys, promisifyRequest, set, setMany, update, values };\n","/**\n * https://bugs.webkit.org/show_bug.cgi?id=226547\n * Safari has a horrible bug where IDB requests can hang while the browser is starting up.\n * The only solution is to keep nudging it until it's awake.\n * This probably creates garbage, but garbage is better than totally failing.\n */\nfunction idbReady() {\n const isSafari = !navigator.userAgentData &&\n /Safari\\//.test(navigator.userAgent) &&\n !/Chrom(e|ium)\\//.test(navigator.userAgent);\n // No point putting other browsers or older versions of Safari through this mess.\n if (!isSafari || !indexedDB.databases)\n return Promise.resolve();\n let intervalId;\n return new Promise((resolve) => {\n const tryIdb = () => indexedDB.databases().finally(resolve);\n intervalId = setInterval(tryIdb, 100);\n tryIdb();\n }).finally(() => clearInterval(intervalId));\n}\n\nexport default idbReady;\n","import * as idb from 'idb-keyval';\n\nimport { ApiSessionData } from '../api/types';\n\nimport { DEBUG, LEGACY_SESSION_KEY, SESSION_USER_KEY } from '../config';\nimport * as cacheApi from './cacheApi';\n\nconst DC_IDS = [1, 2, 3, 4, 5];\n\nexport function hasStoredSession(withLegacy = false) {\n if (withLegacy && localStorage.getItem(LEGACY_SESSION_KEY)) {\n return true;\n }\n\n const userAuthJson = localStorage.getItem(SESSION_USER_KEY);\n if (!userAuthJson) return false;\n\n try {\n const userAuth = JSON.parse(userAuthJson);\n return Boolean(userAuth && userAuth.id && userAuth.dcID);\n } catch (err) {\n // Do nothing.\n return false;\n }\n}\n\nexport function storeSession(sessionData: ApiSessionData, currentUserId?: string) {\n const { mainDcId, keys, hashes } = sessionData;\n\n localStorage.setItem(SESSION_USER_KEY, JSON.stringify({ dcID: mainDcId, id: currentUserId }));\n localStorage.setItem('dc', String(mainDcId));\n Object.keys(keys).map(Number).forEach((dcId) => {\n localStorage.setItem(`dc${dcId}_auth_key`, JSON.stringify(keys[dcId]));\n });\n\n if (hashes) {\n Object.keys(hashes).map(Number).forEach((dcId) => {\n localStorage.setItem(`dc${dcId}_hash`, JSON.stringify(hashes[dcId]));\n });\n }\n}\n\nexport function clearStoredSession() {\n [\n SESSION_USER_KEY,\n 'dc',\n ...DC_IDS.map((dcId) => `dc${dcId}_auth_key`),\n ...DC_IDS.map((dcId) => `dc${dcId}_hash`),\n ].forEach((key) => {\n localStorage.removeItem(key);\n });\n}\n\nexport function loadStoredSession(): ApiSessionData | undefined {\n if (!hasStoredSession()) {\n return undefined;\n }\n\n const userAuth = JSON.parse(localStorage.getItem(SESSION_USER_KEY)!);\n const mainDcId = Number(userAuth.dcID);\n const keys: Record = {};\n const hashes: Record = {};\n\n DC_IDS.forEach((dcId) => {\n try {\n const key = localStorage.getItem(`dc${dcId}_auth_key`);\n if (key) {\n keys[dcId] = JSON.parse(key);\n }\n\n const hash = localStorage.getItem(`dc${dcId}_hash`);\n if (hash) {\n hashes[dcId] = JSON.parse(hash);\n }\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('Failed to load stored session', err);\n }\n // Do nothing.\n }\n });\n\n if (!Object.keys(keys).length) return undefined;\n\n return {\n mainDcId,\n keys,\n hashes,\n };\n}\n\nexport async function importLegacySession() {\n const sessionId = localStorage.getItem(LEGACY_SESSION_KEY);\n if (!sessionId) return;\n\n const sessionJson = await idb.get(`GramJs:${sessionId}`);\n try {\n const sessionData = JSON.parse(sessionJson) as ApiSessionData;\n storeSession(sessionData);\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('Failed to load legacy session', err);\n }\n // Do nothing.\n }\n}\n\n// Remove previously created IndexedDB and cache API sessions\nexport async function clearLegacySessions() {\n localStorage.removeItem(LEGACY_SESSION_KEY);\n\n const idbKeys = await idb.keys();\n\n await Promise.all>([\n cacheApi.clear('GramJs'),\n ...idbKeys\n .filter((k) => typeof k === 'string' && k.startsWith('GramJs:GramJs-session-'))\n .map((k) => idb.del(k)),\n ]);\n}\n\nexport function importTestSession() {\n const sessionJson = process.env.TEST_SESSION!;\n try {\n const sessionData = JSON.parse(sessionJson) as ApiSessionData & { userId: string };\n storeSession(sessionData, sessionData.userId);\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('Failed to load test session', err);\n }\n // Do nothing.\n }\n}\n","import { ISettings } from '../types';\n\nimport { animateSingle } from './animation';\n\nimport themeColors from '../styles/themes.json';\n\ntype RGBAColor = {\n r: number;\n g: number;\n b: number;\n a?: number;\n};\n\nlet isInitialized = false;\n\nconst HEX_COLOR_REGEX = /^#?([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})?$/i;\nconst DURATION_MS = 200;\nconst ENABLE_ANIMATION_DELAY_MS = 500;\nconst RGB_VARIABLES = new Set([\n '--color-primary-shade',\n '--color-text-secondary',\n]);\n\nconst lerp = (start: number, end: number, interpolationRatio: number) => {\n return (1 - interpolationRatio) * start + interpolationRatio * end;\n};\n\nconst colors = (Object.keys(themeColors) as Array).map((property) => ({\n property,\n colors: [hexToRgb(themeColors[property][0]), hexToRgb(themeColors[property][1])],\n}));\n\nexport default (theme: ISettings['theme'], withAnimation: boolean) => {\n const isDarkTheme = theme === 'dark';\n const shouldAnimate = isInitialized && withAnimation;\n const startIndex = isDarkTheme ? 0 : 1;\n const endIndex = isDarkTheme ? 1 : 0;\n const startAt = Date.now();\n const themeColorTag = document.querySelector('meta[name=\"theme-color\"]');\n\n document.documentElement.classList.remove(`theme-${isDarkTheme ? 'light' : 'dark'}`);\n if (isInitialized) {\n document.documentElement.classList.add('no-animations');\n }\n document.documentElement.classList.add(`theme-${theme}`);\n if (themeColorTag) {\n themeColorTag.setAttribute('content', isDarkTheme ? '#212121' : '#fff');\n }\n\n setTimeout(() => {\n document.documentElement.classList.remove('no-animations');\n }, ENABLE_ANIMATION_DELAY_MS);\n\n isInitialized = true;\n\n if (shouldAnimate) {\n animateSingle(() => {\n const t = Math.min((Date.now() - startAt) / DURATION_MS, 1);\n\n applyColorAnimationStep(startIndex, endIndex, transition(t));\n\n return t < 1;\n });\n } else {\n applyColorAnimationStep(startIndex, endIndex);\n }\n};\n\nfunction transition(t: number) {\n return 1 - ((1 - t) ** 3.5);\n}\n\nfunction hexToRgb(hex: string): RGBAColor {\n const result = HEX_COLOR_REGEX.exec(hex)!;\n\n return {\n r: parseInt(result[1], 16),\n g: parseInt(result[2], 16),\n b: parseInt(result[3], 16),\n a: result[4] !== undefined ? parseInt(result[4], 16) : undefined,\n };\n}\n\nfunction applyColorAnimationStep(startIndex: number, endIndex: number, interpolationRatio: number = 1) {\n colors.forEach(({ property, colors: propertyColors }) => {\n const r = Math.round(lerp(propertyColors[startIndex].r, propertyColors[endIndex].r, interpolationRatio));\n const g = Math.round(lerp(propertyColors[startIndex].g, propertyColors[endIndex].g, interpolationRatio));\n const b = Math.round(lerp(propertyColors[startIndex].b, propertyColors[endIndex].b, interpolationRatio));\n const a = propertyColors[startIndex].a !== undefined\n ? Math.round(lerp(propertyColors[startIndex].a!, propertyColors[endIndex].a!, interpolationRatio))\n : undefined;\n\n document.documentElement.style.setProperty(property, a !== undefined\n ? `rgba(${r},${g},${b},${a / 255})`\n : `rgb(${r},${g},${b})`);\n\n if (RGB_VARIABLES.has(property)) {\n document.documentElement.style.setProperty(`${property}-rgb`, `${r},${g},${b}`);\n }\n });\n}\n","import EMOJI_REGEX from '../lib/twemojiRegex';\nimport { fixNonStandardEmoji } from './emoji';\n\nexport function formatInteger(value: number) {\n return String(value).replace(/\\d(?=(\\d{3})+$)/g, '$& ');\n}\n\nfunction formatFixedNumber(number: number) {\n const fixed = String(number.toFixed(1));\n if (fixed.substr(-2) === '.0') {\n return Math.round(number);\n }\n\n return number.toFixed(1).replace('.', ',');\n}\n\nexport function formatIntegerCompact(views: number) {\n if (views < 1e3) {\n return views;\n }\n\n if (views < 1e6) {\n return `${formatFixedNumber(views / 1e3)}K`;\n }\n\n return `${formatFixedNumber(views / 1e6)}M`;\n}\n\nexport function getFirstLetters(phrase: string, count = 2) {\n return phrase\n .replace(/[.,!@#$%^&*()_+=\\-`~[\\]/\\\\{}:\"|<>?]+/gi, '')\n .trim()\n .split(/\\s+/)\n .slice(0, count)\n .map((word: string) => {\n if (!word.length) return '';\n word = fixNonStandardEmoji(word);\n const emojis = word.match(EMOJI_REGEX);\n if (emojis && word.startsWith(emojis[0])) {\n return emojis[0];\n }\n return word.match(/./u)![0].toUpperCase();\n })\n .join('');\n}\n","const DEFAULT_MAX_TEXT_LENGTH = 30;\n\nexport default function trimText(text: string | undefined, length = DEFAULT_MAX_TEXT_LENGTH) {\n if (!text || text.length <= length) {\n return text;\n }\n\n return `${text.substr(0, length)}...`;\n}\n","import { isWebpSupported } from './environment';\nimport { dataUriToBlob, blobToDataUri } from './files';\nimport { pause } from './schedulers';\n\nconst WORKER_INITIALIZATION_TIMEOUT = 2000;\n\nlet canvas: HTMLCanvasElement;\nlet worker: IWebpWorker;\n\nexport const EMPTY_IMAGE_DATA_URI = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk'\n + 'YAAAAAYAAjCB0C8AAAAASUVORK5CYII=';\n\nexport async function webpToPng(url: string, blob: Blob): Promise {\n initWebpWorker();\n\n while (!worker.wasmReady) {\n await pause(WORKER_INITIALIZATION_TIMEOUT);\n }\n\n const { result, width, height } = await getDecodePromise(url, blob);\n if (!width || !height) {\n return undefined;\n }\n\n return createPng({ result, width, height });\n}\n\nexport async function webpToPngBase64(key: string, dataUri: string): Promise {\n if (isWebpSupported() || dataUri.substr(0, 15) !== 'data:image/webp') {\n return dataUri;\n }\n\n initWebpWorker();\n\n const pngBlob = await webpToPng(key, dataUriToBlob(dataUri));\n\n if (!pngBlob) {\n throw new Error(`Can't convert webp to png. Url: ${dataUri}`);\n }\n\n return blobToDataUri(pngBlob);\n}\n\nfunction initWebpWorker() {\n if (!worker) {\n worker = new Worker(new URL('../lib/webp/webp_wasm.worker.js', import.meta.url)) as IWebpWorker;\n worker.wasmReady = false;\n worker.onmessage = handleLibWebpMessage;\n }\n}\n\nfunction createPng({ result, width, height }: TEncodedImage): Promise {\n if (!canvas) {\n canvas = document.createElement('canvas');\n }\n\n return new Promise((resolve) => {\n const img = new ImageData(result, width, height);\n\n canvas.width = width;\n canvas.height = height;\n const ctx = canvas.getContext('2d')!;\n ctx.putImageData(img, 0, 0);\n\n canvas.toBlob((blob) => {\n resolve(blob ?? undefined);\n }, 'image/png', 1);\n });\n}\n\nfunction handleLibWebpMessage(e: MessageEvent) {\n const { id } = e.data;\n switch (e.data.type) {\n case 'initialized': {\n worker.wasmReady = true;\n break;\n }\n\n case 'result': {\n if (worker.requests.has(id)) {\n const resolve = worker.requests.get(id)!;\n\n worker.requests.delete(id);\n resolve(e.data!);\n }\n break;\n }\n }\n}\n\nfunction getDecodePromise(url: string, blob: Blob): Promise {\n return new Promise((resolve) => {\n if (!worker.requests) {\n worker.requests = new Map();\n }\n\n worker.requests.set(url, resolve);\n worker.postMessage({ id: url, blob });\n });\n}\n","import { APP_VERSION, DEBUG } from '../config';\nimport { getGlobal } from '../lib/teact/teactn';\nimport { hasStoredSession } from './sessions';\n\nconst WEBSYNC_URLS = [\n 't.me',\n 'telegram.me',\n].map((domain) => `//${domain}/_websync_?`);\nconst WEBSYNC_VERSION = `${APP_VERSION} Z`;\nconst WEBSYNC_KEY = 'tgme_sync';\nconst WEBSYNC_TIMEOUT = 86400;\n\nconst getTs = () => {\n return Math.floor(Number(new Date()) / 1000);\n};\n\nconst saveSync = (authed: boolean) => {\n const ts = getTs();\n localStorage.setItem(WEBSYNC_KEY, JSON.stringify({\n canRedirect: authed,\n ts,\n }));\n};\n\nlet lastTimeout: NodeJS.Timeout | undefined;\n\nexport const forceWebsync = (authed: boolean) => {\n const currentTs = getTs();\n\n const { canRedirect, ts } = JSON.parse(localStorage.getItem(WEBSYNC_KEY) || '{}');\n\n if (canRedirect !== authed || ts + WEBSYNC_TIMEOUT <= currentTs) {\n return Promise.all(WEBSYNC_URLS.map((url) => {\n return new Promise((resolve, reject) => {\n const script = document.createElement('script');\n\n const removeElement = () => !!document.body.removeChild(script);\n\n script.src = url + new URLSearchParams({\n authed: Number(authed).toString(),\n version: WEBSYNC_VERSION,\n });\n\n document.body.appendChild(script);\n\n script.onload = () => {\n saveSync(authed);\n removeElement();\n if (lastTimeout) {\n clearTimeout(lastTimeout);\n lastTimeout = undefined;\n }\n startWebsync();\n resolve();\n };\n\n script.onerror = () => {\n removeElement();\n reject();\n };\n });\n }));\n } else {\n return Promise.resolve();\n }\n};\n\nexport function startWebsync() {\n if (DEBUG) {\n return;\n }\n\n if (lastTimeout !== undefined) return;\n const currentTs = getTs();\n\n const { ts } = JSON.parse(localStorage.getItem(WEBSYNC_KEY) || '{}');\n\n const timeout = WEBSYNC_TIMEOUT - (currentTs - ts);\n\n lastTimeout = setTimeout(() => {\n const { authState } = getGlobal();\n\n const authed = authState === 'authorizationStateReady' || hasStoredSession(true);\n forceWebsync(authed);\n }, Math.max(0, timeout * 1000));\n}\n","import { throttle } from './schedulers';\nimport {\n MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT,\n MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH,\n MOBILE_SCREEN_MAX_WIDTH,\n} from '../config';\nimport { IS_IOS, IS_SINGLE_COLUMN_LAYOUT } from './environment';\n\ntype IDimensions = {\n width: number;\n height: number;\n};\n\nconst IS_LANDSCAPE = IS_SINGLE_COLUMN_LAYOUT && isLandscape();\n\nconst initialHeight = window.innerHeight;\nlet windowSize = updateSizes();\nlet isRefreshDisabled = false;\n\nfunction disableRefresh() {\n isRefreshDisabled = true;\n}\n\nfunction enableRefresh() {\n isRefreshDisabled = false;\n}\n\nconst handleResize = throttle(() => {\n windowSize = updateSizes();\n\n if (!isRefreshDisabled && (\n isMobileScreen() !== IS_SINGLE_COLUMN_LAYOUT\n || (IS_SINGLE_COLUMN_LAYOUT && IS_LANDSCAPE !== isLandscape())\n )) {\n window.location.reload();\n }\n}, 250, true);\n\nwindow.addEventListener('orientationchange', handleResize);\nif (IS_IOS) {\n window.visualViewport.addEventListener('resize', handleResize);\n} else {\n window.addEventListener('resize', handleResize);\n}\n\nexport function updateSizes(): IDimensions {\n let height: number;\n if (IS_IOS) {\n height = window.visualViewport.height + window.visualViewport.pageTop;\n } else {\n height = window.innerHeight;\n }\n const vh = height * 0.01;\n\n document.documentElement.style.setProperty('--vh', `${vh}px`);\n\n return {\n width: window.innerWidth,\n height: window.innerHeight,\n };\n}\n\nfunction isMobileScreen() {\n return windowSize.width <= MOBILE_SCREEN_MAX_WIDTH || (\n windowSize.width <= MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH && windowSize.height <= MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT\n );\n}\n\nfunction isLandscape() {\n if (IS_IOS) {\n return window.matchMedia('(orientation: landscape)').matches;\n }\n\n // eslint-disable-next-line max-len\n // Source: https://web.archive.org/web/20160509220835/http://blog.abouthalf.com/development/orientation-media-query-challenges-in-android-browsers/\n // Feature is marked as deprecated now, but it is still supported\n // https://developer.mozilla.org/en-US/docs/Web/CSS/@media/device-aspect-ratio#browser_compatibility\n return window.matchMedia('screen and (min-device-aspect-ratio: 1/1) and (orientation: landscape)').matches;\n}\n\nexport default {\n get: () => windowSize,\n getIsKeyboardVisible: () => initialHeight > windowSize.height,\n disableRefresh,\n enableRefresh,\n};\n","// 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\t// no module.id needed\n\t\t// no module.loaded needed\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// 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","// 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\n__webpack_require__.u = (chunkId) => {\n\t// return url for filenames based on template\n\treturn \"\" + chunkId + \".\" + {\"99\":\"f03a947e6e336feffec8\",\"133\":\"aae91a1c7ca8928cb720\",\"161\":\"286d0207d962142ad548\",\"306\":\"abed97b181f73c2c1aa8\",\"325\":\"d8a67d9617f2e13de2dc\",\"354\":\"959e19f0ca3e2bb07043\",\"472\":\"21e5264f606f2b525030\",\"501\":\"72ce4b6e27f459e194cd\",\"514\":\"3cef19392d72a10cf6ea\",\"524\":\"632897f7413c1c081b04\",\"536\":\"55dc7dd4ab42a2c9f037\",\"701\":\"0c52bb0aaf1cd79c0b70\",\"745\":\"9316c5c2b711c39a20a5\",\"915\":\"13af1c4ab9a00d84ac23\",\"941\":\"a1bb68030d234cd6f825\",\"993\":\"f0aad9f6787f211b4e51\"}[chunkId] + \".js\";\n};","// This function allow to reference all chunks\n__webpack_require__.miniCssF = (chunkId) => {\n\t// return url for filenames based on template\n\treturn \"\" + chunkId + \".\" + {\"133\":\"aae91a1c7ca8928cb720\",\"306\":\"abed97b181f73c2c1aa8\",\"325\":\"d8a67d9617f2e13de2dc\",\"472\":\"21e5264f606f2b525030\",\"701\":\"0c52bb0aaf1cd79c0b70\"}[chunkId] + \".css\";\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};","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;","__webpack_require__.b = document.baseURI || self.location.href;\n\n// object to store loaded and loading chunks\n// undefined = chunk not loaded, null = chunk preloaded/prefetched\n// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded\nvar installedChunks = {\n\t179: 0\n};\n\n__webpack_require__.f.j = (chunkId, promises) => {\n\t\t// JSONP chunk loading for javascript\n\t\tvar installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;\n\t\tif(installedChunkData !== 0) { // 0 means \"already installed\".\n\n\t\t\t// a Promise means \"currently loading\".\n\t\t\tif(installedChunkData) {\n\t\t\t\tpromises.push(installedChunkData[2]);\n\t\t\t} else {\n\t\t\t\tif(true) { // all chunks have JS\n\t\t\t\t\t// setup Promise in chunk cache\n\t\t\t\t\tvar promise = new Promise((resolve, reject) => (installedChunkData = installedChunks[chunkId] = [resolve, reject]));\n\t\t\t\t\tpromises.push(installedChunkData[2] = promise);\n\n\t\t\t\t\t// start chunk loading\n\t\t\t\t\tvar url = __webpack_require__.p + __webpack_require__.u(chunkId);\n\t\t\t\t\t// create error before stack unwound to get useful stacktrace later\n\t\t\t\t\tvar error = new Error();\n\t\t\t\t\tvar loadingEnded = (event) => {\n\t\t\t\t\t\tif(__webpack_require__.o(installedChunks, chunkId)) {\n\t\t\t\t\t\t\tinstalledChunkData = installedChunks[chunkId];\n\t\t\t\t\t\t\tif(installedChunkData !== 0) installedChunks[chunkId] = undefined;\n\t\t\t\t\t\t\tif(installedChunkData) {\n\t\t\t\t\t\t\t\tvar errorType = event && (event.type === 'load' ? 'missing' : event.type);\n\t\t\t\t\t\t\t\tvar realSrc = event && event.target && event.target.src;\n\t\t\t\t\t\t\t\terror.message = 'Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';\n\t\t\t\t\t\t\t\terror.name = 'ChunkLoadError';\n\t\t\t\t\t\t\t\terror.type = errorType;\n\t\t\t\t\t\t\t\terror.request = realSrc;\n\t\t\t\t\t\t\t\tinstalledChunkData[1](error);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t\t__webpack_require__.l(url, loadingEnded, \"chunk-\" + chunkId, chunkId);\n\t\t\t\t} else installedChunks[chunkId] = 0;\n\t\t\t}\n\t\t}\n};\n\n// no prefetching\n\n// no preloaded\n\n// no HMR\n\n// no HMR manifest\n\n// no on chunks loaded\n\n// install a JSONP callback for chunk loading\nvar webpackJsonpCallback = (parentChunkLoadingFunction, data) => {\n\tvar [chunkIds, moreModules, runtime] = data;\n\t// add \"moreModules\" to the modules object,\n\t// then flag all \"chunkIds\" as loaded and fire callback\n\tvar moduleId, chunkId, i = 0;\n\tif(chunkIds.some((id) => (installedChunks[id] !== 0))) {\n\t\tfor(moduleId in moreModules) {\n\t\t\tif(__webpack_require__.o(moreModules, moduleId)) {\n\t\t\t\t__webpack_require__.m[moduleId] = moreModules[moduleId];\n\t\t\t}\n\t\t}\n\t\tif(runtime) var result = runtime(__webpack_require__);\n\t}\n\tif(parentChunkLoadingFunction) parentChunkLoadingFunction(data);\n\tfor(;i < chunkIds.length; i++) {\n\t\tchunkId = chunkIds[i];\n\t\tif(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {\n\t\t\tinstalledChunks[chunkId][0]();\n\t\t}\n\t\tinstalledChunks[chunkIds[i]] = 0;\n\t}\n\n}\n\nvar chunkLoadingGlobal = self[\"webpackChunktelegram_t\"] = self[\"webpackChunktelegram_t\"] || [];\nchunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));\nchunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));","import { DEBUG } from '../config';\nimport { getDispatch } from '../lib/teact/teactn';\nimport { IS_ANDROID, IS_IOS, IS_SERVICE_WORKER_SUPPORTED } from './environment';\nimport { notifyClientReady, playNotifySoundDebounced } from './notifications';\n\ntype WorkerAction = {\n type: string;\n payload: Record;\n};\n\nfunction handleWorkerMessage(e: MessageEvent) {\n const action: WorkerAction = e.data;\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[SW] Message from worker', action);\n }\n if (!action.type) return;\n const dispatch = getDispatch();\n switch (action.type) {\n case 'focusMessage':\n if (dispatch.focusMessage) {\n dispatch.focusMessage(action.payload);\n }\n break;\n case 'playNotificationSound':\n playNotifySoundDebounced(action.payload.id);\n break;\n }\n}\n\nfunction subscribeToWorker() {\n navigator.serviceWorker.removeEventListener('message', handleWorkerMessage);\n navigator.serviceWorker.addEventListener('message', handleWorkerMessage);\n // Notify web worker that client is ready to receive messages\n notifyClientReady();\n}\n\nif (IS_SERVICE_WORKER_SUPPORTED) {\n window.addEventListener('load', async () => {\n try {\n await navigator.serviceWorker.register(new URL('../serviceWorker.ts', import.meta.url));\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[SW] ServiceWorker registered');\n }\n\n await navigator.serviceWorker.ready;\n\n if (navigator.serviceWorker.controller) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[SW] ServiceWorker ready');\n }\n subscribeToWorker();\n } else {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('[SW] ServiceWorker not available');\n }\n\n if (!IS_IOS && !IS_ANDROID) {\n getDispatch().showDialog({ data: { message: 'SERVICE_WORKER_DISABLED', hasErrorKey: true } });\n }\n }\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('[SW] ServiceWorker registration failed: ', err);\n }\n }\n });\n window.addEventListener('focus', async () => {\n await navigator.serviceWorker.ready;\n subscribeToWorker();\n });\n}\n","import { GlobalState } from './types';\nimport { NewChatMembersProgress } from '../types';\n\nimport {\n ANIMATION_LEVEL_DEFAULT, DARK_THEME_PATTERN_COLOR, DEFAULT_MESSAGE_TEXT_SIZE_PX, DEFAULT_PATTERN_COLOR,\n DEFAULT_PLAYBACK_RATE,\n DEFAULT_VOLUME,\n IOS_DEFAULT_MESSAGE_TEXT_SIZE_PX, MACOS_DEFAULT_MESSAGE_TEXT_SIZE_PX,\n} from '../config';\nimport { IS_IOS, IS_MAC_OS } from '../util/environment';\n\nexport const INITIAL_STATE: GlobalState = {\n isLeftColumnShown: true,\n isChatInfoShown: false,\n newChatMembersProgress: NewChatMembersProgress.Closed,\n uiReadyState: 0,\n serverTimeOffset: 0,\n\n authRememberMe: true,\n countryList: {\n phoneCodes: [],\n general: [],\n },\n\n blocked: {\n ids: [],\n totalCount: 0,\n },\n\n users: {\n byId: {},\n },\n\n chats: {\n listIds: {},\n isFullyLoaded: {},\n orderedPinnedIds: {},\n totalCount: {},\n byId: {},\n },\n\n messages: {\n byChatId: {},\n messageLists: [],\n },\n\n scheduledMessages: {\n byChatId: {},\n },\n\n chatFolders: {\n byId: {},\n activeChatFolder: 0,\n },\n\n fileUploads: {\n byMessageLocalId: {},\n },\n\n recentEmojis: ['grinning', 'kissing_heart', 'christmas_tree', 'brain', 'trophy'],\n\n stickers: {\n setsById: {},\n added: {},\n recent: {\n stickers: [],\n },\n favorite: {\n stickers: [],\n },\n greeting: {\n stickers: [],\n },\n featured: {\n setIds: [],\n },\n search: {},\n forEmoji: {},\n },\n\n emojiKeywords: {},\n\n gifs: {\n saved: {},\n search: {},\n },\n\n inlineBots: {\n isLoading: false,\n byUsername: {},\n },\n\n globalSearch: {},\n\n userSearch: {},\n\n localTextSearch: {\n byChatThreadKey: {},\n },\n\n localMediaSearch: {\n byChatId: {},\n },\n\n management: {\n byChatId: {},\n },\n\n topPeers: {},\n\n topInlineBots: {},\n\n mediaViewer: {},\n\n audioPlayer: {\n volume: DEFAULT_VOLUME,\n playbackRate: DEFAULT_PLAYBACK_RATE,\n isMuted: false,\n },\n\n forwardMessages: {},\n\n pollResults: {},\n\n payment: {},\n\n notifications: [],\n\n dialogs: [],\n\n activeSessions: [],\n\n settings: {\n byKey: {\n theme: 'light',\n shouldUseSystemTheme: true,\n messageTextSize: IS_IOS\n ? IOS_DEFAULT_MESSAGE_TEXT_SIZE_PX\n : (IS_MAC_OS ? MACOS_DEFAULT_MESSAGE_TEXT_SIZE_PX : DEFAULT_MESSAGE_TEXT_SIZE_PX),\n animationLevel: ANIMATION_LEVEL_DEFAULT,\n messageSendKeyCombo: 'enter',\n canAutoLoadPhotoFromContacts: true,\n canAutoLoadPhotoInPrivateChats: true,\n canAutoLoadPhotoInGroups: true,\n canAutoLoadPhotoInChannels: true,\n canAutoLoadVideoFromContacts: true,\n canAutoLoadVideoInPrivateChats: true,\n canAutoLoadVideoInGroups: true,\n canAutoLoadVideoInChannels: true,\n canAutoLoadFileFromContacts: false,\n canAutoLoadFileInPrivateChats: false,\n canAutoLoadFileInGroups: false,\n canAutoLoadFileInChannels: false,\n autoLoadFileMaxSizeMb: 10,\n hasWebNotifications: true,\n hasPushNotifications: true,\n notificationSoundVolume: 5,\n canAutoPlayGifs: true,\n canAutoPlayVideos: true,\n shouldSuggestStickers: true,\n shouldLoopStickers: true,\n language: 'en',\n timeFormat: '24h',\n wasTimeFormatSetManually: false,\n },\n themes: {\n light: {\n isBlurred: true,\n patternColor: DEFAULT_PATTERN_COLOR,\n },\n dark: {\n isBlurred: true,\n patternColor: DARK_THEME_PATTERN_COLOR,\n },\n },\n privacy: {},\n notifyExceptions: {},\n },\n\n twoFaSettings: {},\n\n shouldShowContextMenuHint: true,\n\n activeDownloads: {\n byChatId: {},\n },\n\n serviceNotifications: [],\n};\n","import {\n addCallback, addReducer, getGlobal, removeCallback,\n} from '../lib/teact/teactn';\n\nimport { GlobalState } from './types';\nimport { MAIN_THREAD_ID } from '../api/types';\n\nimport { onBeforeUnload, onIdle, throttle } from '../util/schedulers';\nimport {\n DEBUG,\n GLOBAL_STATE_CACHE_DISABLED,\n GLOBAL_STATE_CACHE_KEY,\n GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT,\n MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN,\n GLOBAL_STATE_CACHE_USER_LIST_LIMIT,\n DEFAULT_VOLUME,\n DEFAULT_PLAYBACK_RATE,\n} from '../config';\nimport { IS_SINGLE_COLUMN_LAYOUT } from '../util/environment';\nimport { ANIMATION_END_EVENT, ANIMATION_START_EVENT } from '../hooks/useHeavyAnimationCheck';\nimport { pick } from '../util/iteratees';\nimport { selectCurrentMessageList } from '../modules/selectors';\nimport { hasStoredSession } from '../util/sessions';\nimport { INITIAL_STATE } from './initial';\nimport { parseLocationHash } from '../util/routing';\nimport { LOCATION_HASH } from '../hooks/useHistoryBack';\nimport { isUserId } from '../modules/helpers';\n\nconst UPDATE_THROTTLE = 5000;\n\nconst updateCacheThrottled = throttle(() => onIdle(updateCache), UPDATE_THROTTLE, false);\n\nlet isCaching = false;\nlet isHeavyAnimating = false;\nlet unsubscribeFromBeforeUnload: NoneToVoidFunction | undefined;\n\nsetupHeavyAnimationListeners();\n\nexport function initCache() {\n if (GLOBAL_STATE_CACHE_DISABLED) {\n return;\n }\n\n addReducer('saveSession', () => {\n if (isCaching) {\n return;\n }\n\n setupCaching();\n });\n\n addReducer('reset', () => {\n localStorage.removeItem(GLOBAL_STATE_CACHE_KEY);\n\n if (!isCaching) {\n return;\n }\n\n clearCaching();\n });\n}\n\nexport function loadCache(initialState: GlobalState): GlobalState | undefined {\n if (GLOBAL_STATE_CACHE_DISABLED) {\n return undefined;\n }\n\n if (hasStoredSession(true)) {\n setupCaching();\n\n return readCache(initialState);\n } else {\n clearCaching();\n\n return undefined;\n }\n}\n\nfunction setupCaching() {\n isCaching = true;\n unsubscribeFromBeforeUnload = onBeforeUnload(updateCache, true);\n window.addEventListener('blur', updateCache);\n addCallback(updateCacheThrottled);\n}\n\nfunction clearCaching() {\n isCaching = false;\n removeCallback(updateCacheThrottled);\n window.removeEventListener('blur', updateCache);\n if (unsubscribeFromBeforeUnload) {\n unsubscribeFromBeforeUnload();\n }\n}\n\nfunction readCache(initialState: GlobalState): GlobalState {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.time('global-state-cache-read');\n }\n\n const json = localStorage.getItem(GLOBAL_STATE_CACHE_KEY);\n const cached = json ? JSON.parse(json) as GlobalState : undefined;\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.timeEnd('global-state-cache-read');\n }\n\n if (cached) {\n migrateCache(cached, initialState);\n }\n\n const newState = {\n ...initialState,\n ...cached,\n };\n\n const parsedMessageList = !IS_SINGLE_COLUMN_LAYOUT ? parseLocationHash(LOCATION_HASH) : undefined;\n\n return {\n ...newState,\n messages: {\n ...newState.messages,\n messageLists: parsedMessageList ? [parsedMessageList] : [],\n },\n };\n}\n\nfunction migrateCache(cached: GlobalState, initialState: GlobalState) {\n if ('shouldAutoDownloadMediaFromContacts' in cached.settings.byKey) {\n const {\n shouldAutoDownloadMediaFromContacts,\n shouldAutoDownloadMediaInPrivateChats,\n shouldAutoDownloadMediaInGroups,\n shouldAutoDownloadMediaInChannels,\n shouldAutoPlayVideos,\n shouldAutoPlayGifs,\n ...rest\n } = cached.settings.byKey;\n\n cached.settings.byKey = {\n ...rest,\n canAutoLoadPhotoFromContacts: shouldAutoDownloadMediaFromContacts,\n canAutoLoadVideoFromContacts: shouldAutoDownloadMediaFromContacts,\n canAutoLoadPhotoInPrivateChats: shouldAutoDownloadMediaInPrivateChats,\n canAutoLoadVideoInPrivateChats: shouldAutoDownloadMediaInPrivateChats,\n canAutoLoadPhotoInGroups: shouldAutoDownloadMediaInGroups,\n canAutoLoadVideoInGroups: shouldAutoDownloadMediaInGroups,\n canAutoLoadPhotoInChannels: shouldAutoDownloadMediaInChannels,\n canAutoLoadVideoInChannels: shouldAutoDownloadMediaInChannels,\n canAutoPlayVideos: shouldAutoPlayVideos,\n canAutoPlayGifs: shouldAutoPlayGifs,\n };\n }\n\n cached.settings.byKey = {\n ...initialState.settings.byKey,\n ...cached.settings.byKey,\n };\n\n cached.settings.themes = {\n ...initialState.settings.themes,\n ...cached.settings.themes,\n };\n\n cached.chatFolders = {\n ...initialState.chatFolders,\n ...cached.chatFolders,\n };\n\n if (!cached.stickers.greeting) {\n cached.stickers.greeting = initialState.stickers.greeting;\n }\n\n if (!cached.activeDownloads) {\n cached.activeDownloads = {\n byChatId: {},\n };\n }\n\n if (!cached.serviceNotifications) {\n cached.serviceNotifications = [];\n }\n\n if (cached.audioPlayer.volume === undefined) {\n cached.audioPlayer.volume = DEFAULT_VOLUME;\n }\n\n if (cached.audioPlayer.playbackRate === undefined) {\n cached.audioPlayer.playbackRate = DEFAULT_PLAYBACK_RATE;\n }\n}\n\nfunction updateCache() {\n if (!isCaching || isHeavyAnimating) {\n return;\n }\n\n const global = getGlobal();\n\n if (global.isLoggingOut) {\n return;\n }\n\n const reducedGlobal: GlobalState = {\n ...INITIAL_STATE,\n ...pick(global, [\n 'authState',\n 'authPhoneNumber',\n 'authRememberMe',\n 'authNearestCountry',\n 'currentUserId',\n 'contactList',\n 'topPeers',\n 'topInlineBots',\n 'recentEmojis',\n 'push',\n 'shouldShowContextMenuHint',\n 'leftColumnWidth',\n 'serviceNotifications',\n ]),\n audioPlayer: {\n volume: global.audioPlayer.volume,\n playbackRate: global.audioPlayer.playbackRate,\n isMuted: global.audioPlayer.isMuted,\n },\n isChatInfoShown: reduceShowChatInfo(global),\n users: reduceUsers(global),\n chats: reduceChats(global),\n messages: reduceMessages(global),\n globalSearch: {\n recentlyFoundChatIds: global.globalSearch.recentlyFoundChatIds,\n },\n settings: reduceSettings(global),\n chatFolders: reduceChatFolders(global),\n };\n\n const json = JSON.stringify(reducedGlobal);\n localStorage.setItem(GLOBAL_STATE_CACHE_KEY, json);\n}\n\nfunction reduceShowChatInfo(global: GlobalState): boolean {\n return window.innerWidth > MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN\n ? global.isChatInfoShown\n : false;\n}\n\nfunction reduceUsers(global: GlobalState): GlobalState['users'] {\n const { users: { byId, selectedId } } = global;\n const idsToSave = [\n ...(global.chats.listIds.active || []).slice(0, GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT).filter(isUserId),\n ...Object.keys(byId),\n ].slice(0, GLOBAL_STATE_CACHE_USER_LIST_LIMIT);\n\n return {\n byId: pick(byId, idsToSave),\n selectedId: window.innerWidth > MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN ? selectedId : undefined,\n };\n}\n\nfunction reduceChats(global: GlobalState): GlobalState['chats'] {\n const chatIdsToSave = [\n ...(global.chats.listIds.active || []).slice(0, GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT),\n ];\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n\n return {\n ...global.chats,\n byId: pick(global.chats.byId, currentChatId ? [...chatIdsToSave, currentChatId] : chatIdsToSave),\n listIds: {\n active: chatIdsToSave,\n },\n isFullyLoaded: {},\n orderedPinnedIds: {\n active: global.chats.orderedPinnedIds.active,\n },\n };\n}\n\nfunction reduceMessages(global: GlobalState): GlobalState['messages'] {\n const byChatId: GlobalState['messages']['byChatId'] = {};\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n\n const chatIdsToSave = [\n ...(global.chats.listIds.active || []).slice(0, GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT),\n ...(currentChatId ? [currentChatId] : []),\n ];\n chatIdsToSave.forEach((chatId) => {\n const current = global.messages.byChatId[chatId];\n if (!current) {\n return;\n }\n\n const mainThread = current.threadsById[MAIN_THREAD_ID];\n if (!mainThread || !mainThread.viewportIds) {\n return;\n }\n\n byChatId[chatId] = {\n byId: pick(current.byId, mainThread.viewportIds),\n threadsById: {\n [MAIN_THREAD_ID]: mainThread,\n },\n };\n });\n\n return {\n byChatId,\n messageLists: [],\n };\n}\n\nfunction reduceSettings(global: GlobalState): GlobalState['settings'] {\n const { byKey, themes } = global.settings;\n\n return {\n byKey,\n themes,\n privacy: {},\n notifyExceptions: {},\n };\n}\n\nfunction reduceChatFolders(global: GlobalState): GlobalState['chatFolders'] {\n return {\n ...global.chatFolders,\n activeChatFolder: 0,\n };\n}\n\nfunction setupHeavyAnimationListeners() {\n document.addEventListener(ANIMATION_START_EVENT, () => {\n isHeavyAnimating = true;\n });\n document.addEventListener(ANIMATION_END_EVENT, () => {\n isHeavyAnimating = false;\n });\n}\n","import { addReducer } from '../lib/teact/teactn';\n\nimport { INITIAL_STATE } from './initial';\nimport { initCache, loadCache } from './cache';\nimport { cloneDeep } from '../util/iteratees';\n\ninitCache();\n\naddReducer('init', () => {\n const initial = cloneDeep(INITIAL_STATE);\n return loadCache(initial) || initial;\n});\n","const STORAGE_KEY = 'tt-active-tab';\nconst INTERVAL = 2000;\n\nconst tabKey = String(Date.now() + Math.random());\n\nlocalStorage.setItem(STORAGE_KEY, tabKey);\n\nlet callback: NoneToVoidFunction;\n\nconst interval = window.setInterval(() => {\n if (callback && localStorage.getItem(STORAGE_KEY) !== tabKey) {\n callback();\n clearInterval(interval);\n }\n}, INTERVAL);\n\nexport function addActiveTabChangeListener(_callback: NoneToVoidFunction) {\n callback = _callback;\n}\n","const SITE_FONTS = ['400 1em Roboto', '500 1em Roboto'];\n\nexport default function preloadFonts() {\n if ('fonts' in document) {\n return Promise.all(SITE_FONTS.map((font) => document.fonts.load(font)));\n }\n\n return undefined;\n}\n","import React, { FC, useEffect } from '../../lib/teact/teact';\nimport { getGlobal, withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiMediaFormat } from '../../api/types';\nimport { GlobalActions, GlobalState } from '../../global/types';\n\nimport { getChatAvatarHash } from '../../modules/helpers/chats'; // Direct import for better module splitting\nimport useFlag from '../../hooks/useFlag';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport { pause } from '../../util/schedulers';\nimport { preloadImage } from '../../util/files';\nimport preloadFonts from '../../util/fonts';\nimport * as mediaLoader from '../../util/mediaLoader';\nimport { Bundles, loadModule } from '../../util/moduleLoader';\nimport { pick } from '../../util/iteratees';\nimport buildClassName from '../../util/buildClassName';\n\nimport './UiLoader.scss';\n\n// @ts-ignore\nimport telegramLogoPath from '../../assets/telegram-logo.svg';\n// @ts-ignore\nimport monkeyPath from '../../assets/monkey.svg';\nimport { selectIsRightColumnShown, selectTheme } from '../../modules/selectors';\n\ntype OwnProps = {\n page: 'main' | 'authCode' | 'authPassword' | 'authPhoneNumber' | 'authQrCode';\n children: any;\n};\n\ntype StateProps = Pick & {\n hasCustomBackground?: boolean;\n hasCustomBackgroundColor: boolean;\n isRightColumnShown?: boolean;\n leftColumnWidth?: number;\n};\n\ntype DispatchProps = Pick;\n\nconst MAX_PRELOAD_DELAY = 700;\nconst SECOND_STATE_DELAY = 1000;\nconst AVATARS_TO_PRELOAD = 10;\n\nfunction preloadAvatars() {\n const { listIds, byId } = getGlobal().chats;\n if (!listIds.active) {\n return undefined;\n }\n\n return Promise.all(listIds.active.slice(0, AVATARS_TO_PRELOAD).map((chatId) => {\n const chat = byId[chatId];\n if (!chat) {\n return undefined;\n }\n\n const avatarHash = getChatAvatarHash(chat);\n if (!avatarHash) {\n return undefined;\n }\n\n return mediaLoader.fetch(avatarHash, ApiMediaFormat.BlobUrl);\n }));\n}\n\nconst preloadTasks = {\n main: () => Promise.all([\n loadModule(Bundles.Main, 'Main')\n .then(preloadFonts),\n preloadAvatars(),\n ]),\n authPhoneNumber: () => Promise.all([\n preloadFonts(),\n preloadImage(telegramLogoPath),\n ]),\n authCode: () => preloadImage(monkeyPath),\n authPassword: () => preloadImage(monkeyPath),\n authQrCode: preloadFonts,\n};\n\nconst UiLoader: FC = ({\n page,\n children,\n hasCustomBackground,\n hasCustomBackgroundColor,\n isRightColumnShown,\n shouldSkipHistoryAnimations,\n leftColumnWidth,\n setIsUiReady,\n}) => {\n const [isReady, markReady] = useFlag();\n const {\n shouldRender: shouldRenderMask, transitionClassNames,\n } = useShowTransition(!isReady, undefined, true);\n\n useEffect(() => {\n let timeout: number | undefined;\n\n const safePreload = async () => {\n try {\n await preloadTasks[page]();\n } catch (err) {\n // Do nothing\n }\n };\n\n Promise.race([\n pause(MAX_PRELOAD_DELAY),\n safePreload(),\n ]).then(() => {\n markReady();\n setIsUiReady({ uiReadyState: 1 });\n\n timeout = window.setTimeout(() => {\n setIsUiReady({ uiReadyState: 2 });\n }, SECOND_STATE_DELAY);\n });\n\n return () => {\n if (timeout) {\n clearTimeout(timeout);\n timeout = undefined;\n }\n\n setIsUiReady({ uiReadyState: 0 });\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n return (\n

\n {children}\n {shouldRenderMask && !shouldSkipHistoryAnimations && (\n
\n {page === 'main' ? (\n <>\n \n \n {isRightColumnShown &&
}\n \n ) : (\n
\n )}\n
\n )}\n
\n );\n};\n\nexport default withGlobal(\n (global): StateProps => {\n const theme = selectTheme(global);\n const { background, backgroundColor } = global.settings.themes[theme] || {};\n\n return {\n shouldSkipHistoryAnimations: global.shouldSkipHistoryAnimations,\n uiReadyState: global.uiReadyState,\n hasCustomBackground: Boolean(background),\n hasCustomBackgroundColor: Boolean(backgroundColor),\n isRightColumnShown: selectIsRightColumnShown(global),\n leftColumnWidth: global.leftColumnWidth,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, ['setIsUiReady']),\n)(UiLoader);\n","import * as langProvider from '../util/langProvider';\nimport { useState } from '../lib/teact/teact';\n\nexport default (langCode: string | undefined, key: string): string | undefined => {\n const [translation, setTranslation] = useState();\n\n if (langCode) {\n langProvider\n .getTranslationForLangString(langCode, key)\n .then(setTranslation);\n }\n\n return translation;\n};\n","import { LangCode } from '../../../types';\n\nexport function getSuggestedLanguage() {\n let suggestedLanguage = navigator.language;\n\n if (suggestedLanguage && suggestedLanguage !== 'pt-br') {\n suggestedLanguage = suggestedLanguage.substr(0, 2);\n }\n\n return suggestedLanguage as LangCode;\n}\n","import React, {\n FC, useState, memo, useCallback, useRef,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiCountryCode } from '../../api/types';\n\nimport { ANIMATION_END_DELAY } from '../../config';\nimport searchWords from '../../util/searchWords';\nimport buildClassName from '../../util/buildClassName';\nimport renderText from '../common/helpers/renderText';\nimport useLang from '../../hooks/useLang';\nimport { isoToEmoji } from '../../util/emoji';\nimport useOnChange from '../../hooks/useOnChange';\n\nimport DropdownMenu from '../ui/DropdownMenu';\nimport MenuItem from '../ui/MenuItem';\nimport Spinner from '../ui/Spinner';\n\nimport './CountryCodeInput.scss';\n\ntype StateProps = {\n phoneCodeList: ApiCountryCode[];\n};\n\ntype OwnProps = {\n id: string;\n value?: ApiCountryCode;\n isLoading?: boolean;\n onChange: (value: ApiCountryCode) => void;\n};\n\nconst MENU_HIDING_DURATION = 200 + ANIMATION_END_DELAY;\nconst SELECT_TIMEOUT = 50;\n\nconst CountryCodeInput: FC = ({\n id,\n value,\n isLoading,\n onChange,\n phoneCodeList,\n}) => {\n const lang = useLang();\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef(null);\n\n const [filter, setFilter] = useState();\n const [filteredList, setFilteredList] = useState([]);\n\n const updateFilter = useCallback((filterValue?: string) => {\n setFilter(filterValue);\n setFilteredList(getFilteredList(phoneCodeList, filterValue));\n }, [phoneCodeList]);\n\n useOnChange(([prevPhoneCodeList]) => {\n if (prevPhoneCodeList?.length === 0 && phoneCodeList.length > 0) {\n updateFilter(filter);\n }\n }, [phoneCodeList, updateFilter]);\n\n const handleChange = useCallback((country: ApiCountryCode) => {\n onChange(country);\n\n setTimeout(() => updateFilter(undefined), MENU_HIDING_DURATION);\n }, [onChange, updateFilter]);\n\n const handleInput = useCallback((e: React.FormEvent) => {\n updateFilter(e.currentTarget.value);\n }, [updateFilter]);\n\n const handleInputKeyDown = useCallback((e: React.KeyboardEvent) => {\n if (e.keyCode !== 8) {\n return;\n }\n\n const target = e.currentTarget;\n if (value && filter === undefined) {\n target.value = '';\n }\n\n updateFilter(target.value);\n }, [filter, updateFilter, value]);\n\n const CodeInput: FC<{ onTrigger: () => void; isOpen?: boolean }> = ({ onTrigger, isOpen }) => {\n const handleTrigger = () => {\n if (isOpen) {\n return;\n }\n\n setTimeout(() => {\n inputRef.current!.select();\n }, SELECT_TIMEOUT);\n\n onTrigger();\n\n const formEl = document.getElementById('auth-phone-number-form')!;\n formEl.scrollTo({ top: formEl.scrollHeight, behavior: 'smooth' });\n };\n\n const handleCodeInput = (e: React.FormEvent) => {\n handleInput(e);\n handleTrigger();\n };\n\n const inputValue = filter ?? (value?.name || value?.defaultName || '');\n\n return (\n
\n \n \n {isLoading ? (\n \n ) : (\n \n )}\n
\n );\n };\n\n return (\n \n {filteredList\n .map((country: ApiCountryCode) => (\n handleChange(country)}\n >\n {renderText(isoToEmoji(country.iso2), ['hq_emoji'])}\n {country.name || country.defaultName}\n {country.countryCode}\n \n ))}\n {!filteredList.length && (\n \n {lang('lng_country_none')}\n \n )}\n \n );\n};\n\nfunction getFilteredList(countryList: ApiCountryCode[], filter = ''): ApiCountryCode[] {\n const filtered = filter.length\n ? countryList.filter((country) => (\n searchWords(country.defaultName, filter) || (country.name && searchWords(country.name, filter))\n )) : countryList;\n return filtered;\n}\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { countryList: { phoneCodes: phoneCodeList } } = global;\n return {\n phoneCodeList,\n };\n },\n)(CountryCodeInput));\n","import { ChangeEvent } from 'react';\n\n// @ts-ignore\nimport monkeyPath from '../../assets/monkey.svg';\n\nimport React, {\n FC, memo, useCallback, useEffect, useLayoutEffect, useRef, useState,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions, GlobalState } from '../../global/types';\nimport { LangCode } from '../../types';\nimport { ApiCountryCode } from '../../api/types';\n\nimport { IS_SAFARI, IS_TOUCH_ENV } from '../../util/environment';\nimport { preloadImage } from '../../util/files';\nimport preloadFonts from '../../util/fonts';\nimport { pick } from '../../util/iteratees';\nimport { formatPhoneNumber, getCountryCodesByIso, getCountryFromPhoneNumber } from '../../util/phoneNumber';\nimport { setLanguage } from '../../util/langProvider';\nimport useLang from '../../hooks/useLang';\nimport useFlag from '../../hooks/useFlag';\nimport useLangString from '../../hooks/useLangString';\nimport { getSuggestedLanguage } from './helpers/getSuggestedLanguage';\n\nimport Button from '../ui/Button';\nimport Checkbox from '../ui/Checkbox';\nimport InputText from '../ui/InputText';\nimport Loading from '../ui/Loading';\nimport CountryCodeInput from './CountryCodeInput';\n\ntype StateProps = Pick & {\n language?: LangCode;\n phoneCodeList: ApiCountryCode[];\n};\ntype DispatchProps = Pick;\n\nconst MIN_NUMBER_LENGTH = 7;\n\nlet isPreloadInitiated = false;\n\nconst AuthPhoneNumber: FC = ({\n connectionState,\n authState,\n authPhoneNumber,\n authIsLoading,\n authIsLoadingQrCode,\n authError,\n authRememberMe,\n authNearestCountry,\n phoneCodeList,\n language,\n setAuthPhoneNumber,\n setAuthRememberMe,\n loadNearestCountry,\n loadCountryList,\n clearAuthError,\n goToAuthQrCode,\n setSettingOption,\n}) => {\n const lang = useLang();\n // eslint-disable-next-line no-null/no-null\n const inputRef = useRef(null);\n const suggestedLanguage = getSuggestedLanguage();\n\n const continueText = useLangString(suggestedLanguage, 'ContinueOnThisLanguage');\n const [country, setCountry] = useState();\n const [phoneNumber, setPhoneNumber] = useState();\n const [isTouched, setIsTouched] = useState(false);\n const [lastSelection, setLastSelection] = useState<[number, number] | undefined>();\n const [isLoading, markIsLoading, unmarkIsLoading] = useFlag();\n\n const fullNumber = country ? `+${country.countryCode} ${phoneNumber || ''}` : phoneNumber;\n const canSubmit = fullNumber && fullNumber.replace(/[^\\d]+/g, '').length >= MIN_NUMBER_LENGTH;\n\n useEffect(() => {\n if (!IS_TOUCH_ENV) {\n inputRef.current!.focus();\n }\n }, [country]);\n\n useEffect(() => {\n if (connectionState === 'connectionStateReady' && !authNearestCountry) {\n loadNearestCountry();\n }\n }, [connectionState, authNearestCountry, loadNearestCountry]);\n\n useEffect(() => {\n if (connectionState === 'connectionStateReady') {\n loadCountryList({ langCode: language });\n }\n }, [connectionState, language, loadCountryList]);\n\n useEffect(() => {\n if (authNearestCountry && phoneCodeList && !country && !isTouched) {\n setCountry(getCountryCodesByIso(phoneCodeList, authNearestCountry)[0]);\n }\n }, [country, authNearestCountry, isTouched, phoneCodeList]);\n\n const parseFullNumber = useCallback((newFullNumber: string) => {\n if (!newFullNumber.length) {\n setPhoneNumber('');\n }\n\n const suggestedCountry = phoneCodeList && getCountryFromPhoneNumber(phoneCodeList, newFullNumber);\n\n // Any phone numbers should be allowed, in some cases ignoring formatting\n const selectedCountry = !country\n || (suggestedCountry && suggestedCountry.iso2 !== country.iso2)\n || (!suggestedCountry && newFullNumber.length)\n ? suggestedCountry\n : country;\n\n if (!country || !selectedCountry || (selectedCountry && selectedCountry.iso2 !== country.iso2)) {\n setCountry(selectedCountry);\n }\n setPhoneNumber(formatPhoneNumber(newFullNumber, selectedCountry));\n }, [phoneCodeList, country]);\n\n const handleLangChange = useCallback(() => {\n markIsLoading();\n\n void setLanguage(suggestedLanguage, () => {\n unmarkIsLoading();\n\n setSettingOption({ language: suggestedLanguage });\n });\n }, [markIsLoading, setSettingOption, suggestedLanguage, unmarkIsLoading]);\n\n useEffect(() => {\n if (phoneNumber === undefined && authPhoneNumber) {\n parseFullNumber(authPhoneNumber);\n }\n }, [authPhoneNumber, phoneNumber, parseFullNumber]);\n\n useLayoutEffect(() => {\n if (inputRef.current && lastSelection) {\n inputRef.current.setSelectionRange(...lastSelection);\n }\n }, [lastSelection]);\n\n const isJustPastedRef = useRef(false);\n const handlePaste = useCallback(() => {\n isJustPastedRef.current = true;\n requestAnimationFrame(() => {\n isJustPastedRef.current = false;\n });\n }, []);\n\n const handleCountryChange = useCallback((value: ApiCountryCode) => {\n setCountry(value);\n setPhoneNumber('');\n }, []);\n\n const handlePhoneNumberChange = useCallback((e: ChangeEvent) => {\n if (authError) {\n clearAuthError();\n }\n\n // This is for further screens. We delay it until user input to speed up the initial loading.\n if (!isPreloadInitiated) {\n isPreloadInitiated = true;\n preloadFonts();\n void preloadImage(monkeyPath);\n }\n\n const { value, selectionStart, selectionEnd } = e.target;\n setLastSelection(\n selectionStart && selectionEnd && selectionEnd < value.length\n ? [selectionStart, selectionEnd]\n : undefined,\n );\n\n setIsTouched(true);\n\n const shouldFixSafariAutoComplete = (\n IS_SAFARI && country && fullNumber !== undefined\n && value.length - fullNumber.length > 1 && !isJustPastedRef.current\n );\n parseFullNumber(shouldFixSafariAutoComplete ? `${country!.countryCode} ${value}` : value);\n }, [authError, clearAuthError, country, fullNumber, parseFullNumber]);\n\n const handleKeepSessionChange = useCallback((e: ChangeEvent) => {\n setAuthRememberMe(e.target.checked);\n }, [setAuthRememberMe]);\n\n function handleSubmit(event: React.FormEvent) {\n event.preventDefault();\n\n if (authIsLoading) {\n return;\n }\n\n if (canSubmit) {\n setAuthPhoneNumber({ phoneNumber: fullNumber });\n }\n }\n\n const isAuthReady = authState === 'authorizationStateWaitPhoneNumber';\n\n return (\n
\n
\n
\n

Telegram

\n

{lang('StartText')}

\n
\n \n \n \n {canSubmit && (\n isAuthReady ? (\n \n ) : (\n \n )\n )}\n {isAuthReady && (\n \n )}\n {suggestedLanguage && suggestedLanguage !== language && continueText && (\n \n )}\n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n settings: { byKey: { language } },\n countryList: { phoneCodes: phoneCodeList },\n } = global;\n\n return {\n ...pick(global, [\n 'connectionState',\n 'authState',\n 'authPhoneNumber',\n 'authIsLoading',\n 'authIsLoadingQrCode',\n 'authError',\n 'authRememberMe',\n 'authNearestCountry',\n ]),\n language,\n phoneCodeList,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'setAuthPhoneNumber',\n 'setAuthRememberMe',\n 'clearAuthError',\n 'loadNearestCountry',\n 'loadCountryList',\n 'goToAuthQrCode',\n 'setSettingOption',\n ]),\n)(AuthPhoneNumber));\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst AuthCodeAsync: FC = () => {\n const AuthCode = useModuleLoader(Bundles.Auth, 'AuthCode');\n\n return AuthCode ? : ;\n};\n\nexport default memo(AuthCodeAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst AuthPasswordAsync: FC = () => {\n const AuthPassword = useModuleLoader(Bundles.Auth, 'AuthPassword');\n\n return AuthPassword ? : ;\n};\n\nexport default memo(AuthPasswordAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst AuthRegisterAsync: FC = () => {\n const AuthRegister = useModuleLoader(Bundles.Auth, 'AuthRegister');\n\n return AuthRegister ? : ;\n};\n\nexport default memo(AuthRegisterAsync);\n","/*\n jquery-qrcode v0.14.0 - https://larsjung.de/jquery-qrcode/ */\n'use strict';let G=null;class H{}H.render=function(w,B){G(w,B)};self.QrCreator=H;\n(function(w){function B(t,c,a,e){var b={},h=w(a,c);h.u(t);h.J();e=e||0;var r=h.h(),d=h.h()+2*e;b.text=t;b.level=c;b.version=a;b.O=d;b.a=function(b,a){b-=e;a-=e;return 0>b||b>=r||0>a||a>=r?!1:h.a(b,a)};return b}function C(t,c,a,e,b,h,r,d,g,x){function u(b,a,f,c,d,r,g){b?(t.lineTo(a+r,f+g),t.arcTo(a,f,c,d,h)):t.lineTo(a,f)}r?t.moveTo(c+h,a):t.moveTo(c,a);u(d,e,a,e,b,-h,0);u(g,e,b,c,b,0,-h);u(x,c,b,c,a,h,0);u(r,c,a,e,a,0,h)}function z(t,c,a,e,b,h,r,d,g,x){function u(b,a,c,d){t.moveTo(b+c,a);t.lineTo(b,\na);t.lineTo(b,a+d);t.arcTo(b,a,b+c,a,h)}r&&u(c,a,h,h);d&&u(e,a,-h,h);g&&u(e,b,-h,-h);x&&u(c,b,h,-h)}function A(t,c){var a=c.fill;if(\"string\"===typeof a)t.fillStyle=a;else{var e=a.type,b=a.colorStops;a=a.position.map((b)=>Math.round(b*c.size));if(\"linear-gradient\"===e)var h=t.createLinearGradient.apply(t,a);else if(\"radial-gradient\"===e)h=t.createRadialGradient.apply(t,a);else throw Error(\"Unsupported fill\");b.forEach(([b,a])=>{h.addColorStop(b,a)});t.fillStyle=h}}function y(t,c){a:{var a=c.text,e=\nc.v,b=c.N,h=c.K,r=c.P;b=Math.max(1,b||1);for(h=Math.min(40,h||40);b<=h;b+=1)try{var d=B(a,e,b,r);break a}catch(J){}d=void 0}if(!d)return null;a=t.getContext(\"2d\");c.background&&(a.fillStyle=c.background,a.fillRect(c.left,c.top,c.size,c.size));e=d.O;h=c.size/e;a.beginPath();for(r=0;r>>7-b%8&1)},put:function(b,h){for(var a=0;a>>h-a-1&1))},f:function(){return a},m:function(b){var h=Math.floor(a/8);c.length<=h&&c.push(0);b&&(c[h]|=128>>>a%8);a+=1}};return e}function C(c,a){function e(b,h){for(var a=-1;7>=a;a+=1)if(!(-1>=b+a||d<=b+a))for(var c=-1;7>=c;c+=1)-1>=h+c||d<=h+c||(r[b+a][h+c]=0<=a&&6>=a&&(0==c||6==c)||0<=c&&6>=c&&(0==a||6==a)||2<=a&&4>=a&&2<=c&&4>=c?!0:!1)}function b(b,a){for(var f=d=4*c+17,k=Array(f),m=0;m<\nf;m+=1){k[m]=Array(f);for(var p=0;p=n;n+=1)for(var l=-2;2>=l;l+=1)r[p+n][q+l]=-2==n||2==n||-2==l||2==l||0==n&&0==l}for(f=8;fk;k+=1)m=!b&&1==(f>>k&1),r[6>k?k:8>k?k+1:d-15+k][8]=m,r[8][8>k?d-k-1:9>k?15-k:14-k]=m;r[d-8][8]=!b;if(7<=\nc){f=y.A(c);for(k=0;18>k;k+=1)m=!b&&1==(f>>k&1),r[Math.floor(k/3)][k%3+d-8-3]=m;for(k=0;18>k;k+=1)m=!b&&1==(f>>k&1),r[k%3+d-8-3][Math.floor(k/3)]=m}if(null==g){b=t.I(c,h);f=B();for(k=0;k8*m)throw Error(\"code length overflow. (\"+f.f()+\">\"+8*m+\")\");for(f.f()+4<=8*m&&f.put(0,4);0!=f.f()%8;)f.m(!1);for(;!(f.f()>=8*m);){f.put(236,8);if(f.f()>=8*m)break;f.put(17,8)}var u=0;m=k=0;p=Array(b.length);\nq=Array(b.length);for(n=0;nn;n+=1)null==r[k][q-n]&&(l=!1,p>>m&1)),a(k,q-n)&&(l=!l),r[k][q-n]=l,--m,-1==m&&(p+=1,m=7));k+=f;if(0>k||d<=k){k-=f;f=-f;break}}}var h=A[a],r=null,d=0,g=null,x=[],u={u:function(b){b=w(b);x.push(b);g=null},a:function(b,a){if(0>b||d<=b||0>a||d<=a)throw Error(b+\",\"+a);return r[b][a]},h:function(){return d},J:function(){for(var a=0,h=0,c=0;8>c;c+=1){b(!0,c);var d=y.D(u);if(0==c||a>d)a=d,h=c}b(!1,h)}};return u}\nfunction z(c,a){if(\"undefined\"==typeof c.length)throw Error(c.length+\"/\"+a);var e=function(){for(var b=0;bb.b()-a.b())return b;for(var c=v.g(b.c(0))-v.g(a.c(0)),h=Array(b.b()),\ng=0;gb?a.push(b):2048>b?a.push(192|b>>6,128|b&63):55296>b||57344<=b?a.push(224|b>>12,128|b>>6&63,128|b&63):(e++,b=65536+((b&1023)<<10|c.charCodeAt(e)&1023),a.push(240|b>>18,128|b>>12&63,128|b>>6&63,128|b&63))}return a};var A={L:1,M:0,Q:3,H:2},y=function(){function c(b){for(var a=0;0!=b;)a+=1,b>>>=1;return a}var a=[[],[6,18],\n[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],\n[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],e={w:function(b){for(var a=b<<10;0<=c(a)-c(1335);)a^=1335<a||40a?8:16},D:function(b){for(var a=b.h(),c=0,\nd=0;d=p;p+=1)if(!(0>d+p||a<=d+p))for(var q=-1;1>=q;q+=1)0>g+q||a<=g+q||(0!=p||0!=q)&&t==b.a(d+p,g+q)&&(e+=1);5e;e+=1)c[e]=1<e;e+=1)c[e]=c[e-4]^c[e-5]^c[e-6]^c[e-8];for(e=0;255>e;e+=1)a[c[e]]=e;return{g:function(b){if(1>b)throw Error(\"glog(\"+b+\")\");return a[b]},i:function(b){for(;0>b;)b+=255;for(;256<=b;)b-=255;return c[b]}}}(),t=function(){function c(b,c){switch(c){case A.L:return a[4*\n(b-1)];case A.M:return a[4*(b-1)+1];case A.Q:return a[4*(b-1)+2];case A.H:return a[4*(b-1)+3]}}var a=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,\n2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12,7,37,13],[5,122,98,1,123,99],[7,73,\n45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,\n151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],\n[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],\n[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]],e={I:function(b,a){var e=c(b,a);if(\"undefined\"==\ntypeof e)throw Error(\"bad rs block @ typeNumber:\"+b+\"/errorCorrectLevel:\"+a);b=e.length/3;a=[];for(var d=0;d & {\n language?: LangCode;\n};\ntype DispatchProps = Pick;\n\nconst DATA_PREFIX = 'tg://login?token=';\n\nconst AuthCode: FC = ({\n connectionState,\n authState,\n authQrCode,\n language,\n returnToAuthPhoneNumber,\n setSettingOption,\n}) => {\n const suggestedLanguage = getSuggestedLanguage();\n const lang = useLang();\n // eslint-disable-next-line no-null/no-null\n const qrCodeRef = useRef(null);\n const continueText = useLangString(suggestedLanguage, 'ContinueOnThisLanguage');\n const [isLoading, markIsLoading, unmarkIsLoading] = useFlag();\n\n useEffect(() => {\n if (!authQrCode || connectionState !== 'connectionStateReady') {\n return;\n }\n\n const container = qrCodeRef.current!;\n\n container.innerHTML = '';\n container.classList.remove('pre-animate');\n\n QrCreator.render({\n text: `${DATA_PREFIX}${authQrCode.token}`,\n radius: 0.5,\n ecLevel: 'M',\n fill: '#4E96D4',\n size: 280,\n }, container);\n }, [connectionState, authQrCode]);\n\n const handleLangChange = useCallback(() => {\n markIsLoading();\n\n void setLanguage(suggestedLanguage, () => {\n unmarkIsLoading();\n\n setSettingOption({ language: suggestedLanguage });\n });\n }, [markIsLoading, setSettingOption, suggestedLanguage, unmarkIsLoading]);\n\n const isAuthReady = authState === 'authorizationStateWaitQrCode';\n\n return (\n
\n
\n {authQrCode ? (\n
\n ) : (\n
\n )}\n

{lang('Login.QR.Title')}

\n
    \n
  1. {lang('Login.QR.Help1')}
  2. \n
  3. {renderText(lang('Login.QR.Help2'), ['simple_markdown'])}
  4. \n
  5. {lang('Login.QR.Help3')}
  6. \n
\n {isAuthReady && (\n \n )}\n {suggestedLanguage && suggestedLanguage !== language && continueText && (\n \n )}\n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n connectionState, authState, authQrCode, settings: { byKey: { language } },\n } = global;\n\n return {\n connectionState,\n authState,\n authQrCode,\n language,\n };\n },\n (setGlobal, actions): DispatchProps => pick(actions, [\n 'returnToAuthPhoneNumber', 'setSettingOption',\n ]),\n)(AuthCode));\n","import React, { FC, useEffect, memo } from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { GlobalActions, GlobalState } from '../../global/types';\n\nimport '../../modules/actions/initial';\nimport { pick } from '../../util/iteratees';\nimport { PLATFORM_ENV } from '../../util/environment';\nimport windowSize from '../../util/windowSize';\nimport useHistoryBack from '../../hooks/useHistoryBack';\n\nimport UiLoader from '../common/UiLoader';\nimport AuthPhoneNumber from './AuthPhoneNumber';\nimport AuthCode from './AuthCode.async';\nimport AuthPassword from './AuthPassword.async';\nimport AuthRegister from './AuthRegister.async';\nimport AuthQrCode from './AuthQrCode';\n\nimport './Auth.scss';\n\ntype StateProps = Pick;\ntype DispatchProps = Pick;\n\nconst Auth: FC = ({\n authState, reset, initApi, returnToAuthPhoneNumber, goToAuthQrCode,\n}) => {\n useEffect(() => {\n reset();\n initApi();\n }, [reset, initApi]);\n\n const isMobile = PLATFORM_ENV === 'iOS' || PLATFORM_ENV === 'Android';\n\n const handleChangeAuthorizationMethod = () => {\n if (!isMobile) {\n goToAuthQrCode();\n } else {\n returnToAuthPhoneNumber();\n }\n };\n\n useHistoryBack(\n (!isMobile && authState === 'authorizationStateWaitPhoneNumber')\n || (isMobile && authState === 'authorizationStateWaitQrCode'), handleChangeAuthorizationMethod,\n );\n\n // Prevent refresh when rotating device\n useEffect(() => {\n windowSize.disableRefresh();\n\n return () => {\n windowSize.enableRefresh();\n };\n }, []);\n\n switch (authState) {\n case 'authorizationStateWaitCode':\n return ;\n case 'authorizationStateWaitPassword':\n return ;\n case 'authorizationStateWaitRegistration':\n return ;\n case 'authorizationStateWaitPhoneNumber':\n return ;\n case 'authorizationStateWaitQrCode':\n return ;\n default:\n return isMobile\n ? \n : ;\n }\n};\n\nexport default memo(withGlobal(\n (global): StateProps => pick(global, ['authState']),\n (global, actions): DispatchProps => pick(actions, ['reset', 'initApi', 'returnToAuthPhoneNumber', 'goToAuthQrCode']),\n)(Auth));\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst MainAsync: FC = () => {\n const Main = useModuleLoader(Bundles.Main, 'Main');\n\n return Main ?
: undefined;\n};\n\nexport default memo(MainAsync);\n","import React, { FC } from '../../lib/teact/teact';\n\nimport Button from '../ui/Button';\n\nimport appInactivePath from '../../assets/app-inactive.png';\nimport './AppInactive.scss';\n\nconst AppInactive: FC = () => {\n const handleReload = () => {\n window.location.reload();\n };\n\n return (\n
\n
\n \"\"\n

Such error, many tabs

\n
\n Telegram supports only one active tab with the app.\n
\n Please reload this page to continue using this tab or close it.\n
\n
\n \n
\n
\n
\n );\n};\n\nexport default AppInactive;\n","import { FC, useEffect } from './lib/teact/teact';\nimport React, { withGlobal } from './lib/teact/teactn';\n\nimport { GlobalActions, GlobalState } from './global/types';\n\nimport { INACTIVE_MARKER, PAGE_TITLE } from './config';\nimport { pick } from './util/iteratees';\nimport { updateSizes } from './util/windowSize';\nimport { addActiveTabChangeListener } from './util/activeTabMonitor';\nimport useFlag from './hooks/useFlag';\n\nimport Auth from './components/auth/Auth';\nimport UiLoader from './components/common/UiLoader';\nimport Main from './components/main/Main.async';\nimport AppInactive from './components/main/AppInactive';\nimport { hasStoredSession } from './util/sessions';\n// import Test from './components/test/TestNoRedundancy';\n\ntype StateProps = Pick;\ntype DispatchProps = Pick;\n\nconst App: FC = ({ authState, disconnect }) => {\n const [isInactive, markInactive] = useFlag(false);\n\n useEffect(() => {\n updateSizes();\n addActiveTabChangeListener(() => {\n disconnect();\n document.title = `${PAGE_TITLE}${INACTIVE_MARKER}`;\n\n markInactive();\n });\n }, [disconnect, markInactive]);\n\n // return ;\n\n if (isInactive) {\n return ;\n }\n\n if (authState) {\n switch (authState) {\n case 'authorizationStateWaitPhoneNumber':\n case 'authorizationStateWaitCode':\n case 'authorizationStateWaitPassword':\n case 'authorizationStateWaitRegistration':\n case 'authorizationStateWaitQrCode':\n return ;\n case 'authorizationStateClosed':\n case 'authorizationStateClosing':\n case 'authorizationStateLoggingOut':\n case 'authorizationStateReady':\n return renderMain();\n }\n }\n\n return hasStoredSession(true) ? renderMain() : ;\n};\n\nfunction renderMain() {\n return (\n \n
\n \n );\n}\n\nexport default withGlobal(\n (global): StateProps => pick(global, ['authState']),\n (setGlobal, actions): DispatchProps => pick(actions, ['disconnect']),\n)(App);\n","import './util/handleError';\nimport './util/setupServiceWorker';\n\nimport React, { getDispatch, getGlobal } from './lib/teact/teactn';\nimport TeactDOM from './lib/teact/teact-dom';\n\nimport './global';\n\nimport { DEBUG } from './config';\n\nimport App from './App';\n\nimport './styles/index.scss';\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> INIT');\n}\n\ngetDispatch().init();\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START INITIAL RENDER');\n}\n\nTeactDOM.render(\n ,\n document.getElementById('root'),\n);\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH INITIAL RENDER');\n}\n\ndocument.addEventListener('dblclick', () => {\n // eslint-disable-next-line no-console\n console.warn('GLOBAL STATE', getGlobal());\n});\n"],"names":["leafPrototypes","getProto","inProgress","dataWebpackPrefix","loadStylesheet","installedCssChunks","worker","requestStates","Map","requestStatesByCallback","initApi","onUpdate","initialArgs","DEBUG","console","log","Worker","URL","addEventListener","data","type","update","requestState","get","messageId","error","reject","resolve","response","callback","callbackArgs","subscribeToWorker","platform","window","async","Promise","race","makeRequest","pause","then","Error","err","Date","now","startedAt","location","reload","args","callApi","fnName","name","warn","cancelApiProgress","progressCallback","isCanceled","postMessage","message","generateIdFor","payload","promise","Object","assign","pop","set","catch","finally","delete","ApiMediaFormat","ApiMessageEntityTypes","MAIN_THREAD_ID","MESSAGE_DELETED","base","maxint","adapt","delta","numpoints","firsttime","k","Math","floor","decode","input","preserveCase","output","case_flags","input_length","length","n","out","i","bias","basic","j","ic","oldi","w","digit","t","len","lastIndexOf","charCodeAt","RangeError","push","cp","splice","String","fromCharCode","toUpperCase","value","join","utf16","ensureProtocol","url","includes","getDomain","href","decodedHref","decodeURI","match","domain","replace","domain_array","split","s","slice","convertPunycode","memo","text","className","children","isRtl","toggleSafeLinkModal","openTelegramLink","getDispatch","content","isNotSafe","handleClick","useCallback","e","ctrlKey","altKey","shiftKey","metaKey","RE_TME_LINK","RE_TG_LINK","preventDefault","classNames","buildClassName","title","target","rel","onClick","dir","getFileSizeString","bytes","ONE_GIGABYTE","toFixed","ONE_MEGABYTE","getDocumentExtension","document","fileName","mimeType","getFileExtension","indexOf","getColorFromExtension","extension","getDocumentHasPreview","Boolean","previewBlobUrl","thumbnail","RE_EMOJI_ONLY","RegExp","twemojiRegex","DETECT_UP_TO","emojiCount","withGlobal","undefined","setGlobal","actions","pick","sender","openUserInfo","id","Link","focusMessage","handleMessageClick","chatId","openChat","renderActionMessageText","lang","actionOrigin","targetUsers","targetMessage","targetChatId","options","action","translationValues","amount","currency","textOptions","maxTextLength","processed","unprocessed","processPlaceholder","formatCurrency","code","isEmbedded","origin","asPlain","isUserId","renderUserContent","chat","trimText","getChatTitle","renderText","renderChatContent","renderOriginContent","map","user","filter","getMessageSummaryText","photo","video","sticker","getMessageContent","showQuotes","messageText","isGif","renderMessageContent","invoice","renderProductContent","renderMigratedContent","trim","getUserFullName","placeholder","replaceValue","placeholderPosition","substring","Array","isArray","forEach","index","RE_LETTER_OR_DIGIT","SIMPLE_MARKDOWN_REGEX","part","filters","params","reduce","textParts","divEl","createElement","result","innerText","innerHTML","escapeHtml","EMOJI_REGEX","replaceEmojis","addLineBreaks","highlight","lowerCaseText","toLowerCase","queryPosition","nextSymbol","newParts","links","RE_LINK","nextLink","shift","lastIndex","startsWith","username","endsWith","addLinks","replaceSimpleMarkdown","size","IS_EMOJI_SUPPORTED","parts","fixNonStandardEmoji","emojis","emojiResult","emoji","nativeToUnified","removeVS16s","src","alt","line","source","trimmedLine","trimLeft","indentLength","repeat","RE_LINK_TEMPLATE","RE_MENTION_TEMPLATE","entities","entityResult","entity","preventMessageInputBlur","withBubbling","IS_IOS","activeElement","EDITABLE_INPUT_ID","currentTarget","preventMessageInputBlurWithBubbling","global","userId","userOrChat","selectUser","openChatByUsername","ref","onContextMenu","onMouseDown","onMouseEnter","onMouseLeave","onFocus","color","backgroundImage","round","pill","fluid","isText","isLoading","ariaLabel","download","disabled","ripple","faded","tabIndex","withClickPropagation","elementRef","useRef","isClicked","setIsClicked","useState","fullClassName","setTimeout","handleMouseDown","style","label","subLabel","checked","blocking","onChange","onCheck","useLang","handleChange","event","trigger","positionX","positionY","footer","forceOpen","onOpen","onClose","menuRef","dropdownRef","isOpen","setIsOpen","onKeyDown","menu","current","keyCode","focusedElement","elementChildren","from","focus","onTrigger","containerRef","autoClose","shouldSkipTransition","success","readOnly","autoComplete","inputMode","maxLength","onInput","onKeyPress","onBlur","onPaste","labelText","htmlFor","withBackground","menuStyle","noCloseOnBackdrop","onCloseAnimationEnd","backdropContainerRef","transitionClassNames","useShowTransition","useEffect","captureEscKeyListener","useHistoryBack","useEffectWithPrevDeps","prevIsOpen","dispatchHeavyAnimationEvent","handleKeyDown","useKeyboardListNavigation","useVirtualBackdrop","bubbleClassName","props","icon","destructive","stopPropagation","role","ripples","setRipples","cleanUpDebounced","useMemo","debounce","button","container","position","getBoundingClientRect","rippleSize","offsetWidth","x","clientX","y","clientY","requestAnimationFrame","PAGE_TITLE","INACTIVE_MARKER","APP_NAME","process","APP_VERSION","DEBUG_MORE","IS_TEST","DEBUG_ALERT_MSG","SESSION_USER_KEY","LEGACY_SESSION_KEY","GLOBAL_STATE_CACHE_DISABLED","GLOBAL_STATE_CACHE_KEY","GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT","GLOBAL_STATE_CACHE_USER_LIST_LIMIT","MEDIA_CACHE_DISABLED","MEDIA_CACHE_NAME","MEDIA_CACHE_NAME_AVATARS","MEDIA_PROGRESSIVE_CACHE_NAME","CUSTOM_BG_CACHE_NAME","LANG_CACHE_NAME","AUTODOWNLOAD_FILESIZE_MB_LIMITS","isBigScreen","innerHeight","MIN_PASSWORD_LENGTH","MESSAGE_LIST_SENSITIVE_AREA","MESSAGE_LIST_SLICE","MESSAGE_LIST_VIEWPORT_LIMIT","CHAT_HEIGHT_PX","CHAT_LIST_SLICE","CHAT_LIST_LOAD_SLICE","SHARED_MEDIA_SLICE","MESSAGE_SEARCH_SLICE","GLOBAL_SEARCH_SLICE","MEMBERS_SLICE","MEMBERS_LOAD_SLICE","PROFILE_SENSITIVE_AREA","TOP_CHAT_MESSAGES_PRELOAD_LIMIT","ALL_CHATS_PRELOAD_DISABLED","DEFAULT_VOLUME","DEFAULT_PLAYBACK_RATE","ANIMATION_LEVEL_MIN","ANIMATION_LEVEL_MAX","ANIMATION_LEVEL_DEFAULT","DEFAULT_MESSAGE_TEXT_SIZE_PX","IOS_DEFAULT_MESSAGE_TEXT_SIZE_PX","MACOS_DEFAULT_MESSAGE_TEXT_SIZE_PX","DRAFT_DEBOUNCE","EDITABLE_INPUT_MODAL_ID","SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN","SAFE_SCREEN_WIDTH_FOR_CHAT_INFO","MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN","MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN","MOBILE_SCREEN_MAX_WIDTH","MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH","MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT","LOCAL_MESSAGE_ID_BASE","TMP_CHAT_ID","ANIMATION_END_DELAY","FAST_SMOOTH_MAX_DISTANCE","FAST_SMOOTH_MIN_DURATION","FAST_SMOOTH_MAX_DURATION","FAST_SMOOTH_SHORT_TRANSITION_MAX_DISTANCE","STICKER_SIZE_INLINE_DESKTOP_FACTOR","Set","STICKER_SIZE_INLINE_MOBILE_FACTOR","STICKER_SIZE_AUTH","STICKER_SIZE_AUTH_MOBILE","STICKER_SIZE_PICKER","STICKER_SIZE_GENERAL_SETTINGS","STICKER_SIZE_PICKER_HEADER","STICKER_SIZE_SEARCH","STICKER_SIZE_MODAL","STICKER_SIZE_TWO_FA","STICKER_SIZE_DISCUSSION_GROUPS","STICKER_SIZE_FOLDER_SETTINGS","STICKER_SIZE_INLINE_BOT_RESULT","MEMOJI_STICKER_ID","BASE_EMOJI_KEYWORD_LANG","MENU_TRANSITION_DURATION","SLIDE_TRANSITION_DURATION","VIDEO_MOV_TYPE","SUPPORTED_IMAGE_CONTENT_TYPES","SUPPORTED_VIDEO_CONTENT_TYPES","CONTENT_TYPES_WITH_PREVIEW","COUNTRIES_WITH_12H_TIME_FORMAT","SERVICE_NOTIFICATIONS_USER_ID","REPLIES_USER_ID","ALL_FOLDER_ID","ARCHIVED_FOLDER_ID","MAX_MEDIA_FILES_FOR_ALBUM","MAX_ACTIVE_PINNED_CHATS","SCHEDULED_WHEN_ONLINE","DEFAULT_LANG_CODE","DEFAULT_LANG_PACK","LANG_PACKS","TIPS_USERNAME","LOCALIZED_TIPS","FEEDBACK_URL","LIGHT_THEME_BG_COLOR","DARK_THEME_BG_COLOR","DARK_THEME_PATTERN_COLOR","DEFAULT_PATTERN_COLOR","cb","dependencies","debugKey","prevDeps","usePrevious","initial","setValue","setTrigger","ANIMATION_START_EVENT","ANIMATION_END_EVENT","timeout","isAnimating","duration","dispatchEvent","Event","clearTimeout","handleAnimationStart","handleAnimationEnd","removeEventListener","LOCATION_HASH","hash","PATH_BASE","pathname","search","historyState","currentIndex","nextStateIndexToReplace","isHistoryAltered","isDisabled","isEdge","currentIndexes","disableHistoryBack","handleTouchEnd","isActive","onBack","onForward","currentState","shouldReplaceNext","hashes","indexRef","isForward","prevIsActive","isClosed","indexHashRef","prevHashes","isHashChangedFromEvent","isForceClose","prev","history","pushState","state","last","realDelta","indexLast","findIndex","l","go","replaceState","back","handlePopState","currIndex","disableHistoryAnimations","hasChanged","areSortedArraysEqual","forceClose","touches","pageX","innerWidth","onSelectWithEnter","itemSelector","noCaptureFocus","focusedIndex","setFocusedIndex","element","querySelectorAll","newIndex","item","forceUpdate","useForceUpdate","useOnChange","langProvider","bundleName","moduleName","noLoad","autoUpdate","module","getModuleFromMemory","addLoadListener","loadModule","some","d","next","shouldSkipUndefined","onCloseTransitionEnd","noOpenTransition","noCloseTransition","setIsClosed","closeTimeoutRef","hasOpenClassName","setHasOpenClassName","shouldHaveOpenClassName","isClosing","shouldRender","handleEvent","contains","classList","NON_BUBBLEABLE_EVENTS","delegationRegistry","delegatedEventsByElement","documentEventCounters","propName","handler","asCapture","eventName","resolveEventName","canUseEventDelegation","resolveDelegationRegistryForName","existing","newSet","resolveDelegatedEventsForElement","add","addDelegatedListener","removeDelegatedListener","tagName","realEventName","has","removeAllDelegatedListeners","eventNames","realEvent","events","furtherCallsPrevented","Proxy","p","Reflect","body","parentNode","FILTERED_ATTRIBUTES","HTML_ATTRIBUTES","MAPPED_ATTRIBUTES","autoPlay","headsByElement","renderWithVirtual","parentEl","$current","$new","$parent","skipComponentUpdate","forceIndex","fragment","moveDirection","isComponentElement","hasElementChanged","componentInstance","renderComponent","updateComponent","isMounted","setupComponentUpdateListener","initComponent","node","createNode","setTarget","childNodes","insertBefore","appendChild","removeChild","getTarget","unmountTree","replaceChild","areComponents","isRealElement","nextSibling","currentKeys","keys","newKeys","key","removeAttribute","addAttribute","oldValue","newValue","updateAttribute","updateAttributes","currentEl","teactFastList","$newChild","currentRemainingIndex","remainingByKey","acc","$currentChild","newChildKey","$element","order","teactOrderKey","fragmentQueue","fragmentIndex","newChildren","currentPreservedIndex","currentChildInfo","concat","flushFragmentQueue","shouldMoveNode","isMovingDown","renderFastListChildren","max","createDocumentFragment","renderChildren","mountComponent","$firstChild","isEmptyElement","createTextNode","isTextElement","tag","$child","$fragmentChild","cssText","setAttribute","render","headId","getAttribute","$head","VirtualElementTypesEnum","Fragment","Symbol","renderingInstance","Empty","Text","isTagElement","Tag","Component","flatten","parsedChildren","hooks","cursor","byCursor","effects","memos","buildComponentElement","createComponentInstance","dropEmptyTail","buildChildElement","buildTagElement","isEmptyPlaceholder","child","DEBUG_components","newRenderedValue","DEBUG_startAt","componentName","renderCount","renderTimes","performance","renderTime","handleError","renderedValue","newChild","$old","hook","cleanup","effect","nextValue","setter","helpGc","prepareComponentForFrame","prepareForFrame","throttleWithPrimaryRaf","throttleWithRaf","forceUpdateComponent","currentElement","DEBUG_contentComponentName","useLayoutEffectBase","schedulerFn","primarySchedulerFn","execCleanup","exec","dependency","causedBy","res","prevValue","fastRaf","fastRafPrimary","useLayoutEffect","onTickEnd","onTickEndPrimary","resolver","getUnequalProps","newCallback","areEqual","arePropsShallowEqual","propsRef","renderedRef","orderBy","values","React","currentGlobal","reducers","callbacks","containers","mapStateToProps","mapReducersToProps","ownProps","mappedProps","newMappedProps","Number","isNaN","DEBUG_componentName","areMappedPropsChanged","DEBUG_updates","updateTime","runCallbacks","runCallbacksThrottled","newGlobal","noThrottle","getGlobal","addReducer","reducer","onDispatch","addCallback","removeCallback","TeactNContainer","vs16RegExp","zeroWidthJoiner","rawEmoji","importLegacySession","clearLegacySessions","apiUpdate","userAgent","navigator","PLATFORM_ENV","sessionData","loadStoredSession","isTest","isMovSupported","IS_MOV_SUPPORTED","phoneNumber","authIsLoading","authError","password","file","firstName","lastName","authIsLoadingQrCode","storeSession","currentUserId","clearStoredSession","unsubscribe","forceWebsync","reset","cacheApi","langCachePrefix","langCacheVersion","updateAppBadge","init","connectionState","authNearestCountry","deviceToken","subscribedAt","buildInputPrivacyRules","visibility","allowedIds","deniedIds","users","byId","usersById","chats","chatsById","rules","collectUsers","accessHash","collectChats","allowedUsers","allowedChats","blockedUsers","blockedChats","bio","about","profileEdit","progress","ProfileEditProgress","currentUser","updateUser","fullInfo","isUsernameAvailable","settings","loadedWallpapers","wallpapers","createObjectURL","slug","UPLOADING_WALLPAPER_SLUG","wallpaper","firstWallpaper","withLocalMedia","addUsers","buildCollectionByKey","updateChats","blocked","ids","blockedIds","totalCount","contactId","addBlockedContact","removeBlockedContact","activeSessions","session","isCurrent","serverTimeOffset","addNotifyExceptions","replaceSettings","peerType","isSilent","shouldShowPreviews","updateNotifySettings","hasPushNotifications","hasWebNotifications","byKey","subscribe","hasContactJoinedNotifications","languages","phoneNumberSettings","lastSeenSettings","profilePhotoSettings","forwardsSettings","chatInviteSettings","all","privacy","lastSeen","profilePhoto","forwards","chatInvite","privacyKey","allowUserIds","allowChatIds","blockUserIds","blockChatIds","isAllowList","contactsIds","isSensitiveEnabled","langCode","language","countryList","timeFormat","setSettingOption","setTimeFormat","wasTimeFormatSetManually","nearestCountryCode","selectNotifySettings","setLanguage","onUpdateApiReady","wasAuthReady","authState","authorizationState","isLoggingOut","authIsCodeViaApp","isCodeViaApp","authHint","hint","authQrCode","qrCode","lastSyncTime","onUpdateAuthorizationState","onUpdateAuthorizationError","sync","signOut","onUpdateConnectionState","authRememberMe","isEmpty","mainDcId","saveSession","onUpdateSession","onUpdateServerTimeOffset","sessionUserAuth","localStorage","getItem","userAuth","JSON","parse","setItem","stringify","updateSessionUserId","onUpdateCurrentUser","paymentShippingError","getShippingError","addPaymentError","showDialog","hasErrorKey","handleSystemThemeChange","currentThemeMatch","documentElement","currentTheme","nextTheme","selectTheme","animationLevel","switchTheme","mql","matchMedia","addListener","subscribeToSystemThemeChange","messageTextSize","theme","setProperty","toString","IS_TOUCH_ENV","startWebsync","IS_ANDROID","IS_MAC_OS","uiReadyState","remove","authPhoneNumber","shouldSkipHistoryAnimations","replaceThemeSettings","FOREVER_BANNED_DATE","entityId","isChatGroup","isChatBasicGroup","isChatSuperGroup","isChatChannel","isCommonBoxChat","isChatWithRepliesBot","getChatTypeString","getPrivateChatUserId","isSelf","getChatDescription","getChatLink","inviteLink","getChatAvatarHash","owner","avatarHash","isChatSummaryOnly","lastMessage","isChatAdmin","adminRights","getHasAdminRight","isUserRightBanned","currentUserBannedRights","defaultBannedRights","getCanPostInChat","threadId","isRestricted","migratedTo","isNotJoined","isCreator","getAllowedAttachmentOptions","isChatWithBot","canAttachMedia","canAttachPolls","canSendStickers","canSendGifs","canAttachEmbedLinks","isAdmin","getMessageSendingRestrictionReason","sendMessages","untilDate","formatDateToString","formatTime","getChatSlowModeOptions","slowMode","getChatOrder","joinDate","draftDate","date","isChatArchived","folderId","selectIsChatMuted","notifySettings","notifyExceptions","isMuted","hasPrivateChatsNotifications","hasBroadcastNotifications","hasGroupNotifications","selectShouldShowMessagePreview","hasPrivateChatsMessagePreview","hasBroadcastMessagePreview","hasGroupMessagePreview","getCanDeleteChat","prepareFolderListIds","folder","chatIdsCache","excludedChatIds","includedChatIds","pinnedChatIds","isListed","excludeArchived","excludeMuted","unreadMentionsCount","unreadCount","hasUnreadMark","excludeRead","privateChatUser","bots","contacts","isContact","nonContacts","groups","channels","filterChatFolder","prepareChatList","listIds","orderedPinnedIds","folderType","chatFilter","listedChats","listIdsSet","pinnedChats","otherChats","getFolderUnreadDialogs","unreadDialogsCount","total","hasActiveDialogs","getFolderDescriptionText","emoticon","description","pinnedIds","getFolderChatsCount","getMessageSenderName","getUserFirstOrLastName","sortChatIds","chatIds","shouldPrioritizeVerified","priorityIds","priority","isVerified","CONTENT_NOT_SUPPORTED","getMessageKey","msgId","buildMessageKey","parseMessageKey","getMessageOriginalId","previousLocalId","noEmoji","audio","voice","contact","poll","truncatedText","substr","groupedId","performer","getMessageAudioCaption","summary","question","getMessageText","webPage","getMessageCustomShape","isRound","parseEmojiOnlyString","getMessageSingleEmoji","getFirstLinkInMessage","link","find","offset","isOwnMessage","isOutgoing","isReplyMessage","replyToMessageId","isForwardedMessage","forwardInfo","isActionMessage","isServiceNotificationMessage","isAnonymousOwnMessage","senderId","getSenderTitle","getSendingState","sendingState","isMessageLocal","isHistoryClearMessage","getMessageContentFilename","isAnimated","isWebpSupported","baseFilename","IS_OPUS_SUPPORTED","hasMessageMedia","getMessagePhoto","getMessageVideo","getMessageDocument","getMessageSticker","getMessageContact","getMessagePoll","getMessageAction","getMessageAudio","getMessageVoice","getMessageRoundVideo","isMessageDocumentPhoto","mediaType","isMessageDocumentVideo","getMessageInvoice","getMessageWebPage","getMessageWebPagePhoto","getMessageWebPageVideo","getMessageMediaThumbDataUri","media","getMessageMediaThumbnail","dataUri","getMessageMediaHash","webPagePhoto","webPageVideo","messageVideo","messagePhoto","hasMessageLocalBlobUrl","getVideoOrAudioBaseHash","getAudioHasCover","IS_PROGRESSIVE_SUPPORTED","IS_SAFARI","thumbnailSizes","getMessageMediaFormat","fullVideo","getMessageFileName","getMessageFileSize","blobUrl","getChatMediaMessageIds","messages","listedIds","isFromSharedMedia","getMessageContentIds","reverse","getPhotoFullDimensions","sizes","getPhotoInlineDimensions","getVideoDimensions","width","height","getMediaTransferState","isLoadNeeded","isUploading","isTransferring","transferProgress","messageIds","contentType","validator","matchLinkInMessageText","getMediaDuration","buildChatThreadKey","STRIPE_ERRORS","missing_payment_information","field","invalid_number","number","exp_year","exp_month","invalid_expiry_year","invalid_expiry_month","cvc","invalid_cvc","getStripeError","param","USER_COLOR_KEYS","isDeletedUser","getUserStatus","status","wasOnline","getTime","wasOnlineDate","diff","today","setHours","yesterday","setDate","getDate","formatFullDate","isUserOnline","isUserBot","getCanAddContact","sortUserIds","userIds","getServerTime","expires","getUserIdDividend","abs","getUserColorKey","peer","replaceChatListIds","newIds","updateChatListIds","idsUpdate","replaceChats","newById","getUpdatedChat","chatUpdate","shouldOmitMinInfo","isMin","updatedChat","omit","photos","updateChat","updatedById","updatedChats","addChats","addedById","isAdded","addedChats","updateChatListType","listType","currentListIds","listTypeKey","currentFolderList","updateChatListSecondaryInfo","info","totalCountKey","totalChatCount","isFullyLoaded","leaveChat","leftChatId","selectChatListType","listId","updateCurrentMessageList","shouldReplaceHistory","messageLists","newMessageLists","replaceChatMessages","updateMessageStore","byChatId","threadsById","replaceThreadParam","paramName","threadUpdate","updateThread","addMessages","addedByChatId","messagesByChatId","addChatMessagesById","selectChatMessages","every","newId","updateChatMessage","messageUpdate","updatedMessage","updateScheduledMessage","selectScheduledMessages","replaceScheduledMessages","deleteChatMessages","deletedForwardedPosts","pickTruthy","isLinkedChannelPost","threadInfo","selectThreadInfo","selectListedIds","outlyingIds","selectOutlyingIds","viewportIds","selectViewportIds","selectPinnedIds","newMessageCount","messagesCount","currentMessageList","selectCurrentMessageList","canDeleteCurrentThread","currentThreadId","fromChatId","fromMessageId","originalPost","selectChatMessage","deleteChatScheduledMessages","scheduledIds","selectScheduledIds","updateListedIds","orderHistoryIds","updateOutlyingIds","sort","a","b","addViewportId","safeReplaceViewportIds","newViewportIds","currentIds","updateThreadInfo","newThreadInfo","updateThreadInfos","updates","scheduledMessages","updateScheduledMessages","updateFocusedMessage","noHighlight","isResizingContainer","focusedMessage","updateFocusDirection","direction","enterMessageSelectMode","selectedMessages","prototype","toggleMessageSelection","messageListType","childMessageIds","withShift","oldSelectedMessages","selectMessageIdsByGroupId","selectedMessageIds","newMessageIds","newSelectedMessageIds","selectCurrentMessageIds","prevIndex","min","to","unique","exitMessageSelectMode","updateThreadUnreadFromForwardedMessage","originMessage","lastMessageId","isDeleting","channelPostId","threadInfoOld","updateStickerSets","category","sets","resultIds","updatedSets","stickerSet","stickers","setsById","setIds","updateStickerSet","stickerSetId","currentStickerSet","updateGifSearch","isNew","results","nextOffset","currentResults","gifs","newResults","gif","replaceAnimatedEmojis","animatedEmojis","updateStickersForEmoji","remoteStickers","allStickers","selectStickersForEmoji","uniqueIds","forEmoji","rebuildStickersForEmoji","replaceUsers","getUpdatedUser","userUpdate","updatedUser","updateContactList","updatedUsers","contactUserIds","contactList","newContactUserIds","updateUsers","addedUsers","updateSelectedUserId","selectedId","deleteUser","MEMO_EMPTY_ARRAY","updateUserSearch","searchStatePartial","userSearch","updateUserSearchFetchingStatus","newState","fetchingStatus","updateUserBlockedState","isBlocked","getComplexKey","updateGlobalSearch","globalSearch","updateGlobalSearchContent","currentContent","updateGlobalSearchResults","newFoundMessages","nextRate","resultsByType","newFoundMessagesById","foundIdsForType","foundIds","updateGlobalSearchFetchingStatus","prevFoundIds","newFoundIds","foundOrPrevFoundIds","nextOffsetId","replaceLocalTextSearch","chatThreadKey","searchParams","localTextSearch","byChatThreadKey","updateLocalTextSearch","query","replaceLocalTextSearchResults","updateLocalTextSearchResults","orderFoundIds","replaceLocalMediaSearch","localMediaSearch","updateLocalMediaSearchType","currentType","updateLocalMediaSearchResults","replaceLocalMediaSearchResults","updateManagementProgress","management","updateManagement","newSettings","themes","notifyException","exceptionData","addNotifyException","updateTwoFaSettings","twoFaSettings","updateShippingOptions","shippingOptions","payment","setRequestInfoId","requestId","setPaymentStep","step","setInvoiceMessageInfo","photoUrl","invoiceContent","setStripeCardInfo","cardInfo","stripeCredentials","setPaymentForm","form","setReceipt","receipt","messageInvoice","clearPayment","closeInvoice","isPaymentModalOpen","selectIsUserBlocked","selectNotifyExceptions","selectChat","selectChatUser","selectIsChatWithSelf","selectIsChatWithBot","selectSupportChat","isSupport","selectChatOnlineCount","members","onlineCount","selectChatBot","selectIsChatBotNotStarted","bot","messageInfo","selectAreActiveChatsLoaded","active","selectIsChatListed","targetList","list","selectChatFolder","chatFolders","selectIsChatPinned","archived","chatFoldersById","selectChatByUsername","usernameLowered","selectCountNotMutedUnread","activeChatIds","selectIsServiceChatReady","selectCurrentStickerSearch","selectCurrentGifSearch","selectStickerSet","selectStickerSetByShortName","shortName","stickerSets","stickersForEmoji","packs","selectAnimatedEmoji","cleanedEmoji","selectCurrentChat","selectThreadParam","thread","selectScrollOffset","selectReplyingToId","selectEditingId","selectEditingScheduledId","selectDraft","selectNoWebPage","selectFirstMessageId","selectReplyStack","selectThreadOriginChat","originChannelId","selectThreadTopMessageId","topMessageId","selectThreadByMessage","replyToTopMessageId","isMessageInCurrentMessageList","selectIsViewportNewest","chatMessages","selectScheduledMessage","selectEditingMessage","selectChatMessageByPollId","pollId","messageWithPoll","selectFocusedMessageId","focusedChatId","selectIsMessageFocused","focusedId","selectOutgoingStatus","isScheduledList","lastReadOutboxMessageId","selectIsMessageUnread","selectSender","selectForwardedSender","isChannelPost","senderUserId","selectAllowedMessageActions","isPrivate","isChatWithSelf","isBasicGroup","isSuperGroup","isChannel","isLocal","isServiceNotification","isOwn","isAction","isMessageEditable","viaBotId","canReply","hasPinPermission","canPin","canUnpin","pinnedMessageIds","canDelete","canReport","canDeleteForAll","canEdit","canForward","hasSticker","hasFavoriteSticker","favorite","selectIsStickerFavorite","canFaveSticker","canUnfaveSticker","canCopy","canCopyLink","canSelect","canDownload","noOptions","ability","selectCanDeleteSelectedMessages","messageActions","selectCanReportSelectedMessages","selectCanDownloadSelectedMessages","selectIsDownloading","activeInChat","activeDownloads","selectActiveDownloadIds","selectUploadProgress","fileUploads","byMessageLocalId","selectRealLastReadId","lastReadInboxMessageId","Infinity","selectFirstUnreadId","lastReadId","lastReadServiceNotificationId","serviceNotifications","notification","isUnread","findAfterLastReadId","isFromScheduled","found","selectIsForwardModalOpen","forwardMessages","isModalShown","selectCommonBoxChatId","fromLastMessage","selectIsInSelectMode","selectIsMessageSelected","selectForwardedMessageIdsByGroupId","selectIsDocumentGroupSelected","selectedIds","groupIds","selectSelectedMessagesCount","selectNewestMessageWithBotKeyboardButtons","findLast","keyboardButtons","replyHideMessageId","shouldHideKeyboardButtons","selectCanAutoLoadMedia","isPhoto","isVideo","isFile","canAutoLoadPhotoFromContacts","canAutoLoadPhotoInPrivateChats","canAutoLoadPhotoInGroups","canAutoLoadPhotoInChannels","canAutoLoadVideoFromContacts","canAutoLoadVideoInPrivateChats","canAutoLoadVideoInGroups","canAutoLoadVideoInChannels","canAutoLoadFileFromContacts","canAutoLoadFileInPrivateChats","canAutoLoadFileInGroups","canAutoLoadFileInChannels","canAutoLoadMedia","canAutoLoadMediaFromContacts","canAutoLoadMediaInPrivateChats","canAutoLoadMediaInGroups","canAutoLoadMediaInChannels","isMediaFromContact","selectIsUserOrChatContact","selectCanAutoPlayMedia","canAutoPlayVideos","canAutoPlayGifs","asGif","selectShouldLoopStickers","shouldLoopStickers","selectLastServiceNotification","maxId","selectCurrentTextSearch","currentSearch","selectCurrentMediaSearchPeerId","currentProfileUserId","selectCurrentMediaSearch","peerId","selectManagement","selectCurrentManagementType","selectIsMediaViewerOpen","mediaViewer","avatarOwnerId","selectRightColumnContentKey","isChatInfoShown","newChatMembersProgress","isAddingChatMembersShown","NewChatMembersProgress","isPollResults","pollResults","selectIsPollResultsOpen","isSearch","IS_SINGLE_COLUMN_LAYOUT","isManagement","currentManagement","selectCurrentManagement","isStickerSearch","isGifSearch","currentChatId","areActiveChatsLoaded","isUserInfo","isChatInfo","RightColumnContent","selectIsRightColumnShown","shouldUseSystemTheme","getSystemTheme","selectCurrentGlobalSearchQuery","selectPaymentChatId","selectPaymentMessageId","selectPaymentFormId","formId","selectPaymentRequestId","selectProviderPublishableKey","nativeParams","publishableKey","selectStripeCredentials","LoadMoreDirection","FocusDirection","SettingsScreens","LeftColumnContent","GlobalSearchContent","MediaViewerOrigin","AudioOrigin","ChatCreationProgress","ManagementProgress","ProfileState","PaymentStep","ManagementScreens","currentInstance","animateSingle","tick","instance","isCancelled","animate","setAppBadge","currentProps","newProps","currentKeysLength","prop","self","caches","Type","fetch","cacheName","isHtmlAllowed","request","Request","cache","open","headers","Blob","blob","shouldRecreate","resolvedType","Json","json","save","cacheData","Response","put","clear","captureKeyboardListener","onEsc","keyToHandlerName","Enter","Backspace","Delete","Esc","Escape","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Tab","handlers","onEnter","onDelete","onBackspace","onUp","onDown","onLeft","onRight","onTab","captureKeyboardListeners","hasActiveHandlers","handlerName","currentEventHandlers","releaseKeyboardListener","keyHandlers","WEEKDAYS_FULL","MONTHS_FULL","MONTHS_FULL_LOWERCASE","month","getDayStart","datetime","getDayStartAt","toYearMonth","timestamp","getFullYear","getMonth","toIsoString","hours","getHours","marker","padStart","getMinutes","formatPastTimeShort","weekAgo","getDay","withYear","format","formatDate","formatMonthAndYear","isShort","formatHumanDate","noWeekdays","isUpperFirst","upperFirst","lowerFirst","weekAhead","weekDay","day","monthIndex","formatMediaDateTime","formatMediaDuration","maxValue","minutes","seconds","maxHours","maxMinutes","string","formatVoiceRecordDuration","durationInMs","milliseconds","locale","toLocaleString","year","isValidDate","MAX_MONTH_IN_YEAR","parseDateString","matchStringDate","matchEuropeStringDate","matchNumberDate","dateParts","timestampPlusDay","MILLISECONDS_IN_DAY","str","EXCLUDE_EMOJIS","EMOJI_EXCEPTIONS","unifiedToNative","unified","codePoints","parseInt","fromCodePoint","regex","replacement","pairs","uncompressEmoji","emojiData","categories","emojiRaw","names","native","image","isoToEmoji","iso","test","c","codePointAt","isWebpSupportedCache","webp","Image","handleLoadOrError","onload","onerror","hasWebp","systemThemeCache","matches","os","getPlatform","IS_PWA","standalone","referrer","IS_TABLET_COLUMN_LAYOUT","IS_VOICE_RECORDING_SUPPORTED","mediaDevices","AudioContext","webkitAudioContext","IS_SERVICE_WORKER_SUPPORTED","Audio","canPlayType","IS_CANVAS_FILTER_SUPPORTED","getContext","LAYERS_ANIMATION_NAME","TEST_VIDEO","DPR","devicePixelRatio","MASK_IMAGE_DISABLED","dataUriToBlob","arr","mime","bstr","atob","u8arr","Uint8Array","blobToDataUri","reader","FileReader","readAsDataURL","blobToFile","File","lastModified","preloadImage","img","preloadVideo","volume","onloadedmetadata","createPosterForVideo","onseeked","videoWidth","videoHeight","canvas","drawImage","toDataURL","currentTime","fetchBlob","imgToCanvas","constructor","fileBits","rest","super","this","totalPrice","Intl","NumberFormat","store","random","hasOwnProperty","READABLE_ERROR_MESSAGES","CHAT_RESTRICTED","CHAT_WRITE_FORBIDDEN","CHAT_SEND_POLL_FORBIDDEN","CHAT_SEND_STICKERS_FORBIDDEN","CHAT_SEND_GIFS_FORBIDDEN","CHAT_SEND_MEDIA_FORBIDDEN","CHAT_LINK_EXISTS","SLOWMODE_WAIT_X","USER_BANNED_IN_CHANNEL","USER_IS_BLOCKED","YOU_BLOCKED_USER","IMAGE_PROCESS_FAILED","MEDIA_EMPTY","MEDIA_INVALID","PHOTO_EXT_INVALID","PHOTO_INVALID_DIMENSIONS","PHOTO_SAVE_FILE_INVALID","MESSAGE_DELETE_FORBIDDEN","MESSAGE_POLL_CLOSED","MESSAGE_EDIT_TIME_EXPIRED","CHAT_ADMIN_REQUIRED","PINNED_DIALOGS_TOO_MUCH","DIALOG_FILTERS_TOO_MUCH","CHANNEL_PRIVATE","MEDIA_CAPTION_TOO_LONG","ADDRESS_STREET_LINE1_INVALID","ADDRESS_STREET_LINE2_INVALID","ADDRESS_CITY_INVALID","ADDRESS_COUNTRY_INVALID","ADDRESS_POSTCODE_INVALID","ADDRESS_STATE_INVALID","REQ_INFO_NAME_INVALID","REQ_INFO_PHONE_INVALID","REQ_INFO_EMAIL_INVALID","LINK_NOT_MODIFIED","MESSAGE_TOO_LONG","SERVICE_WORKER_DISABLED","MESSAGE_TOO_LONG_PLEASE_REMOVE_CHARACTERS","FRESH_RESET_AUTHORISATION_FORBIDDEN","BOTS_TOO_MUCH","BOT_GROUPS_BLOCKED","USERS_TOO_MUCH","USER_CHANNELS_TOO_MUCH","USER_KICKED","USER_NOT_MUTUAL_CONTACT","USER_PRIVACY_RESTRICTED","INVITE_HASH_EMPTY","INVITE_HASH_EXPIRED","INVITE_HASH_INVALID","CHANNELS_TOO_MUCH","USER_ALREADY_PARTICIPANT","SCHEDULE_DATE_INVALID","WALLPAPER_DIMENSIONS_INVALID","SHIPPING_ERRORS","getReadableErrorText","isSlowMode","textParams","extraPartIndex","errorMessage","handleErrorEvent","ErrorEvent","reason","throttle","alert","collection","member","mapValues","newByKey","object","stringKeys","orderKey","mode","mode1","mode2","orderKey1","orderKey2","aValue1","bValue1","aValue2","bValue2","aValue","bValue","array","compact","array1","array2","areSortedArraysIntersecting","findIntersectionWithSet","chunkSize","cloneDeep","predicate","SUBSTITUTION_REGEX","PLURAL_OPTIONS","PLURAL_RULES","en","ar","ca","de","es","fa","fr","it","ko","ms","nl","pl","pt_BR","ru","tr","uk","uz","langPack","fallbackLangPack","createCallbackManager","currentLangCode","currentTimeFormat","getTranslation","cacheValue","cached","langString","processTranslation","importFallbackLangPack","getTranslationForLangString","translateString","remoteLangPack","remote","fetchRemoteString","withFallback","newLangPack","sourceLangPacks","fetchRemote","langInfo","rtl","default","template","optionIndex","getPluralOption","translationSlices","initialValue","processTemplate","formatInteger","SAMPLE_RATE","oggToWav","opusData","arrayBuffer","typedArray","decoderWorker","wavWorker","onmessage","command","buffers","buffer","page","terminate","wavBitDepth","wavSampleRate","decoderSampleRate","outputBufferSampleRate","pages","asCacheApiType","memoryCache","fetchPromises","progressCallbacks","cancellableCallbacks","mediaFormat","onProgress","callbackUniqueId","progressiveUrl","getProgressive","mediaPng","webpToPng","prepared","prepareMedia","mediaSource","MediaSource","streamUrl","sourceBuffer","addSourceBuffer","makeOnProgress","revokeObjectURL","fetchFromCacheOrRemote","activeCallbacks","getFromMemory","cancelProgress","parentCallback","endOfStream","appendBuffer","mediaData","serviceWorker","fullSize","controller","Bundles","LOAD_PROMISES","MEMORY_CACHE","Auth","Main","Extra","handleBundleLoad","bundle","listeners","listener","getDeviceToken","subscription","toJSON","endpoint","checkIfPushSupported","ServiceWorkerRegistration","Notification","permission","soundPlayedIds","playNotifySound","notificationSoundVolume","currentVolume","once","play","playNotifySoundDebounced","requestPermission","unsubscribeFromPush","dispatch","deleteDeviceToken","serviceWorkerRegistration","ready","pushManager","getSubscription","areSettingsLoaded","checkIfShouldResubscribe","userVisibleOnly","setDeviceToken","DOMException","ABORT_ERR","notifyAboutNewMessage","resultSettings","resultExceptions","loadNotificationSettings","hasFocus","checkIfShouldNotify","areNotificationsSupported","messageSender","messageAction","actionTargetMessage","targetUserIds","actionTargetUserIds","actionTargetChatId","actionTargetUsers","privateChatUserId","senderName","getNotificationContent","imageHash","mediaLoader","getAvatar","badge","vibrate","onclick","close","onshow","closeMessageNotifications","notifyClientReady","PATTERN_PLACEHOLDER","DEFAULT_PATTERN","getCountryCodesByIso","phoneCodeList","country","iso2","getCountryFromPhoneNumber","possibleCountries","countryCode","bestMatches","prefixes","prefix","formatPhoneNumber","pattern","numberWithoutCode","patterns","defaultPattern","stripped","getBestPattern","formatPhoneNumberWithCode","numberWithPlus","createMessageHash","messageList","parseLocationHash","typeOrThreadId","isType","fn","shouldRunFirst","shouldRunLast","waitingTimeout","interval","isPending","_args","setInterval","clearInterval","throttleWith","waiting","onIdle","requestIdleCallback","rafPromise","fastRafCallbacks","fastRafPrimaryCallbacks","onTickEndCallbacks","onTickEndPrimaryCallbacks","beforeUnloadCallbacks","isPrimary","currentCallbacks","currentPrimaryCallbacks","onBeforeUnload","isLast","unshift","RE_NOT_LETTER","searchWords","haystack","needle","haystackWords","needleWord","haystackWord","promisifyRequest","oncomplete","onsuccess","onabort","defaultGetStoreFunc","defaultGetStore","dbName","storeName","dbp","userAgentData","indexedDB","databases","intervalId","tryIdb","onupgradeneeded","createObjectStore","txMode","db","transaction","objectStore","createStore","DC_IDS","hasStoredSession","withLegacy","userAuthJson","dcID","dcId","removeItem","sessionId","sessionJson","customStore","idb","idbKeys","items","openCursor","continue","eachCursor","isInitialized","HEX_COLOR_REGEX","RGB_VARIABLES","lerp","start","end","interpolationRatio","colors","themeColors","property","hexToRgb","withAnimation","isDarkTheme","shouldAnimate","startIndex","endIndex","startAt","themeColorTag","querySelector","applyColorAnimationStep","transition","hex","r","g","propertyColors","formatFixedNumber","formatIntegerCompact","views","getFirstLetters","phrase","count","word","EMPTY_IMAGE_DATA_URI","initWebpWorker","wasmReady","requests","getDecodePromise","ImageData","putImageData","toBlob","createPng","webpToPngBase64","pngBlob","handleLibWebpMessage","WEBSYNC_URLS","WEBSYNC_VERSION","WEBSYNC_KEY","getTs","lastTimeout","authed","currentTs","canRedirect","ts","script","removeElement","URLSearchParams","version","saveSync","IS_LANDSCAPE","isLandscape","initialHeight","windowSize","updateSizes","isRefreshDisabled","handleResize","visualViewport","pageTop","vh","getIsKeyboardVisible","disableRefresh","enableRefresh","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","exports","__webpack_modules__","call","m","getter","__esModule","getPrototypeOf","obj","ns","create","def","getOwnPropertyNames","definition","o","defineProperty","enumerable","f","chunkId","promises","u","miniCssF","globalThis","Function","done","needAttach","scripts","getElementsByTagName","charset","nc","onScriptComplete","doneFns","bind","head","toStringTag","scriptUrl","importScripts","currentScript","fullhref","existingLinkTags","dataHref","existingStyleTags","findStylesheet","linkTag","errorType","realHref","createStylesheet","miniCss","baseURI","installedChunks","installedChunkData","realSrc","webpackJsonpCallback","parentChunkLoadingFunction","chunkIds","moreModules","runtime","chunkLoadingGlobal","handleWorkerMessage","register","INITIAL_STATE","isLeftColumnShown","phoneCodes","general","activeChatFolder","recentEmojis","added","recent","greeting","featured","emojiKeywords","saved","inlineBots","byUsername","topPeers","topInlineBots","audioPlayer","playbackRate","notifications","dialogs","messageSendKeyCombo","autoLoadFileMaxSizeMb","shouldSuggestStickers","light","isBlurred","patternColor","dark","shouldShowContextMenuHint","updateCacheThrottled","updateCache","unsubscribeFromBeforeUnload","isCaching","isHeavyAnimating","setupCaching","clearCaching","reducedGlobal","reduceShowChatInfo","reduceUsers","reduceChats","reduceMessages","recentlyFoundChatIds","reduceSettings","reduceChatFolders","idsToSave","chatIdsToSave","mainThread","initialState","time","timeEnd","shouldAutoDownloadMediaFromContacts","shouldAutoDownloadMediaInPrivateChats","shouldAutoDownloadMediaInGroups","shouldAutoDownloadMediaInChannels","shouldAutoPlayVideos","shouldAutoPlayGifs","migrateCache","parsedMessageList","readCache","loadCache","STORAGE_KEY","tabKey","SITE_FONTS","preloadFonts","font","fonts","load","preloadAvatars","preloadTasks","main","telegramLogoPath","authCode","monkeyPath","authPassword","background","backgroundColor","hasCustomBackground","hasCustomBackgroundColor","isRightColumnShown","leftColumnWidth","setIsUiReady","isReady","markReady","useFlag","shouldRenderMask","safePreload","translation","setTranslation","getSuggestedLanguage","suggestedLanguage","MENU_HIDING_DURATION","inputRef","setFilter","filteredList","setFilteredList","updateFilter","filterValue","defaultName","getFilteredList","prevPhoneCodeList","handleInput","handleInputKeyDown","DropdownMenu","handleTrigger","select","formEl","getElementById","scrollTo","top","scrollHeight","behavior","inputValue","Spinner","MenuItem","isPreloadInitiated","setAuthPhoneNumber","setAuthRememberMe","loadNearestCountry","loadCountryList","clearAuthError","goToAuthQrCode","continueText","useLangString","setCountry","setPhoneNumber","isTouched","setIsTouched","lastSelection","setLastSelection","markIsLoading","unmarkIsLoading","fullNumber","canSubmit","parseFullNumber","newFullNumber","suggestedCountry","selectedCountry","handleLangChange","setSelectionRange","isJustPastedRef","handlePaste","handleCountryChange","handlePhoneNumberChange","selectionStart","selectionEnd","shouldFixSafariAutoComplete","handleKeepSessionChange","isAuthReady","onSubmit","InputText","Checkbox","Button","Loading","AuthCode","useModuleLoader","AuthPassword","AuthRegister","G","H","B","QrCreator","h","J","level","O","C","lineTo","arcTo","moveTo","z","v","N","K","P","fillStyle","fillRect","left","beginPath","q","D","E","R","I","F","fill","colorStops","createLinearGradient","apply","createRadialGradient","addColorStop","A","minVersion","maxVersion","ecLevel","radius","quiet","HTMLCanvasElement","clearRect","write","S","multiply","L","M","Q","returnToAuthPhoneNumber","qrCodeRef","token","isMobile","AuthQrCode","appInactivePath","renderMain","disconnect","isInactive","markInactive","TeactDOM"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/report.html b/dist/report.html index 21e31934..0bb2dd9f 100644 --- a/dist/report.html +++ b/dist/report.html @@ -3,7 +3,7 @@ - telegram-t [19 Nov 2021 at 21:06] + telegram-t [20 Nov 2021 at 12:19]