From b393b3cad19ad9dae26387f351025d91731ba0c9 Mon Sep 17 00:00:00 2001 From: Alexander Zinchuk Date: Thu, 13 Jan 2022 14:55:00 +0100 Subject: [PATCH] [Build] --- .patch-version | 2 +- ...54.44bc53595e49ca5bc9f9.js => 354.47391222364a22307e69.js} | 2 +- ...3595e49ca5bc9f9.js.map => 354.47391222364a22307e69.js.map} | 2 +- ...24.80c446dcb25355f04b36.js => 524.95e29e37c83dea5150d6.js} | 2 +- ...6dcb25355f04b36.js.map => 524.95e29e37c83dea5150d6.js.map} | 2 +- ...7.77459230580aafa8639a.css => 87.74a4d72480e8214a0dde.css} | 2 +- ...30580aafa8639a.css.map => 87.74a4d72480e8214a0dde.css.map} | 2 +- dist/87.74a4d72480e8214a0dde.js | 2 ++ dist/87.74a4d72480e8214a0dde.js.map | 1 + dist/87.77459230580aafa8639a.js | 2 -- dist/87.77459230580aafa8639a.js.map | 1 - ...27.04b93a71a7d051ccd448.js => 927.151d396500bf8aa6cf1e.js} | 4 ++-- ...a71a7d051ccd448.js.map => 927.151d396500bf8aa6cf1e.js.map} | 2 +- dist/index.html | 2 +- dist/main.694bb1485bda2f2e118a.js | 2 ++ dist/main.694bb1485bda2f2e118a.js.map | 1 + dist/main.e8d33405b37130f28896.js | 2 -- dist/main.e8d33405b37130f28896.js.map | 1 - dist/report.html | 4 ++-- 19 files changed, 19 insertions(+), 19 deletions(-) rename dist/{354.44bc53595e49ca5bc9f9.js => 354.47391222364a22307e69.js} (97%) rename dist/{354.44bc53595e49ca5bc9f9.js.map => 354.47391222364a22307e69.js.map} (99%) rename dist/{524.80c446dcb25355f04b36.js => 524.95e29e37c83dea5150d6.js} (99%) rename dist/{524.80c446dcb25355f04b36.js.map => 524.95e29e37c83dea5150d6.js.map} (99%) rename dist/{87.77459230580aafa8639a.css => 87.74a4d72480e8214a0dde.css} (99%) rename dist/{87.77459230580aafa8639a.css.map => 87.74a4d72480e8214a0dde.css.map} (99%) create mode 100644 dist/87.74a4d72480e8214a0dde.js create mode 100644 dist/87.74a4d72480e8214a0dde.js.map delete mode 100644 dist/87.77459230580aafa8639a.js delete mode 100644 dist/87.77459230580aafa8639a.js.map rename dist/{927.04b93a71a7d051ccd448.js => 927.151d396500bf8aa6cf1e.js} (99%) rename dist/{927.04b93a71a7d051ccd448.js.map => 927.151d396500bf8aa6cf1e.js.map} (99%) create mode 100644 dist/main.694bb1485bda2f2e118a.js create mode 100644 dist/main.694bb1485bda2f2e118a.js.map delete mode 100644 dist/main.e8d33405b37130f28896.js delete mode 100644 dist/main.e8d33405b37130f28896.js.map diff --git a/.patch-version b/.patch-version index b8626c4c..7ed6ff82 100644 --- a/.patch-version +++ b/.patch-version @@ -1 +1 @@ -4 +5 diff --git a/dist/354.44bc53595e49ca5bc9f9.js b/dist/354.47391222364a22307e69.js similarity index 97% rename from dist/354.44bc53595e49ca5bc9f9.js rename to dist/354.47391222364a22307e69.js index 7674c63e..f83635dd 100644 --- a/dist/354.44bc53595e49ca5bc9f9.js +++ b/dist/354.47391222364a22307e69.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"]),t=new Set(["video/mp4"]);new Set([...e,...t]),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 r=new Map;function n(e,t){t?postMessage(e,t):postMessage(e)}let a;self.importScripts("rlottie-wasm.js");const s=new Promise((e=>{Module.onRuntimeInitialized=()=>{a={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,t,r,n,i,c){a||await s;const d=JSON.stringify(t),l=allocate(intArrayFromString(d),"i8",0),m=a.init(),u=a.loadFromData(m,l);a.resize(m,r,r),o.set(e,{imgSize:r,reduceFactor:i,handle:m}),c(Math.ceil(u/i))},changeData:async function(e,t,r){a||await s;const n=JSON.stringify(t),{reduceFactor:i,handle:c}=o.get(e),d=allocate(intArrayFromString(n),"i8",0),l=a.loadFromData(c,d);r(Math.ceil(l/i))},renderFrames:async function(e,t,r,n){a||await s;const{imgSize:i,reduceFactor:c,handle:d}=o.get(e);for(let e=t;e<=r;e++){const t=e*c;a.render(d,t);const r=a.buffer(d),s=Module.HEAPU8.subarray(r,r+i*i*4);n(e,new Uint8ClampedArray(s).buffer)}},destroy:function(e){const t=o.get(e);a.destroy(t.handle),o.delete(e)}},onmessage=async e=>{const{data:t}=e;switch(t.type){case"callMethod":{const{messageId:e,name:a,args:s}=t;try{if(e){const t=(...t)=>{const r=t[t.length-1];n({type:"methodCallback",messageId:e,callbackArgs:t},r instanceof ArrayBuffer?[r]:void 0)};r.set(e,t),s.push(t)}const[t,o]=await i[a](...s)||[];e&&n({type:"methodResponse",messageId:e,response:t},o)}catch(t){e&&n({type:"methodResponse",messageId:e,error:{message:t.message}})}e&&r.delete(e);break}case"cancelProgress":{const e=r.get(t.messageId);e&&(e.isCanceled=!0);break}}}})(); -//# sourceMappingURL=354.44bc53595e49ca5bc9f9.js.map \ No newline at end of file +//# sourceMappingURL=354.47391222364a22307e69.js.map \ No newline at end of file diff --git a/dist/354.44bc53595e49ca5bc9f9.js.map b/dist/354.47391222364a22307e69.js.map similarity index 99% rename from dist/354.44bc53595e49ca5bc9f9.js.map rename to dist/354.47391222364a22307e69.js.map index 7a27c36a..79357c3f 100644 --- a/dist/354.44bc53595e49ca5bc9f9.js.map +++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A,IACV,MAAM,KAAEnB,GAASL,EAEjB,OAAQK,EAAKN,MACX,IAAK,aAAc,CACjB,MAAM,UAAEyD,EAAF,KAAaC,EAAb,KAAmBC,GAASrD,EAClC,IACE,GAAImD,EAAW,CACb,MAAMG,EAAW,IAAIC,KACnB,MAAMC,EAAUD,EAAaA,EAAaE,OAAS,GAEnDhE,EAAa,CACXC,KAAM,iBACNyD,UAAAA,EACAI,aAAAA,GACCC,aAAmBE,YAAc,CAACF,QAAWG,IAGlD7D,EAAcoC,IAAIiB,EAAWG,GAE7BD,EAAKO,KAAKN,GAGZ,MAAOO,EAAU5D,SAAuBiB,EAAIkC,MAASC,IAAU,GAE3DF,GACF1D,EACE,CACEC,KAAM,iBACNyD,UAAAA,EACAU,SAAAA,GAEF5D,GAGJ,MAAOT,GAMH2D,GACF1D,EAAa,CACXC,KAAM,iBACNyD,UAAAA,EACA3D,MAAO,CAAEG,QAASH,EAAMG,WAK1BwD,GACFrD,EAAcmD,OAAOE,GAGvB,MAEF,IAAK,iBAAkB,CACrB,MAAMG,EAAWxD,EAAcuC,IAAIrC,EAAKmD,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-v7';\nexport const ASSET_CACHE_NAME = 'tt-assets';\nexport const AUTODOWNLOAD_FILESIZE_MB_LIMITS = [1, 5, 10, 50, 100, 500];\n\nexport const DOWNLOAD_WORKERS = 16;\nexport const UPLOAD_WORKERS = 16;\n\nconst isBigScreen = typeof window !== 'undefined' && window.innerHeight >= 900;\n\nexport const MIN_PASSWORD_LENGTH = 1;\n\nexport const MESSAGE_LIST_SLICE = isBigScreen ? 60 : 40;\nexport const MESSAGE_LIST_VIEWPORT_LIMIT = MESSAGE_LIST_SLICE * 2;\n\nexport const CHAT_HEIGHT_PX = 72;\nexport const CHAT_LIST_SLICE = isBigScreen ? 30 : 25;\nexport const CHAT_LIST_LOAD_SLICE = 100;\nexport const SHARED_MEDIA_SLICE = 42;\nexport const MESSAGE_SEARCH_SLICE = 42;\nexport const GLOBAL_SEARCH_SLICE = 20;\nexport const MEMBERS_SLICE = 30;\nexport const MEMBERS_LOAD_SLICE = 200;\nexport const PINNED_MESSAGES_LIMIT = 50;\nexport const BLOCKED_LIST_LIMIT = 100;\nexport const PROFILE_PHOTOS_LIMIT = 40;\nexport const PROFILE_SENSITIVE_AREA = 500;\nexport const COMMON_CHATS_LIMIT = 100;\nexport const GROUP_CALL_PARTICIPANTS_LIMIT = 100;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 20;\nexport const ALL_CHATS_PRELOAD_DISABLED = false;\n\nexport const SPONSORED_MESSAGE_CACHE_MS = 300000; // 5 min\n\nexport const DEFAULT_VOLUME = 1;\nexport const DEFAULT_PLAYBACK_RATE = 1;\n\nexport const ANIMATION_LEVEL_MIN = 0;\nexport const ANIMATION_LEVEL_MED = 1;\nexport const ANIMATION_LEVEL_MAX = 2;\nexport const ANIMATION_LEVEL_DEFAULT = ANIMATION_LEVEL_MAX;\n\nexport const DEFAULT_MESSAGE_TEXT_SIZE_PX = 16;\nexport const IOS_DEFAULT_MESSAGE_TEXT_SIZE_PX = 17;\nexport const MACOS_DEFAULT_MESSAGE_TEXT_SIZE_PX = 15;\n\nexport const DRAFT_DEBOUNCE = 10000; // 10s\nexport const SEND_MESSAGE_ACTION_INTERVAL = 3000; // 3s\n\nexport const EDITABLE_INPUT_ID = 'editable-message-text';\nexport const EDITABLE_INPUT_MODAL_ID = 'editable-message-text-modal';\n\n// Screen width where Pinned Message / Audio Player in the Middle Header can be safely displayed\nexport const SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1440; // px\n// Screen width where Pinned Message / Audio Player in the Middle Header shouldn't collapse with ChatInfo\nexport const SAFE_SCREEN_WIDTH_FOR_CHAT_INFO = 1150; // px\n\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1275; // px\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN = 925; // px\nexport const MOBILE_SCREEN_MAX_WIDTH = 600; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH = 950; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT = 450; // px\n\nexport const LOCAL_MESSAGE_ID_BASE = 1e9;\nexport const TMP_CHAT_ID = '0';\n\nexport const ANIMATION_END_DELAY = 100;\n\nexport const FAST_SMOOTH_MAX_DISTANCE = 1500;\nexport const FAST_SMOOTH_MIN_DURATION = 250;\nexport const FAST_SMOOTH_MAX_DURATION = 600;\nexport const FAST_SMOOTH_SHORT_TRANSITION_MAX_DISTANCE = 500; // px\n\n// Average duration of message sending animation\nexport const API_UPDATE_THROTTLE = Math.round((FAST_SMOOTH_MIN_DURATION + FAST_SMOOTH_MAX_DURATION) / 2);\nexport const API_THROTTLE_RESET_UPDATES = new Set([\n 'newMessage', 'newScheduledMessage', 'deleteMessages', 'deleteScheduledMessages', 'deleteHistory',\n]);\n\nexport const STICKER_SIZE_INLINE_DESKTOP_FACTOR = 13;\nexport const STICKER_SIZE_INLINE_MOBILE_FACTOR = 11;\nexport const STICKER_SIZE_AUTH = 160;\nexport const STICKER_SIZE_AUTH_MOBILE = 120;\nexport const STICKER_SIZE_PICKER = 64;\nexport const STICKER_SIZE_GENERAL_SETTINGS = 48;\nexport const STICKER_SIZE_PICKER_HEADER = 32;\nexport const STICKER_SIZE_SEARCH = 64;\nexport const STICKER_SIZE_MODAL = 64;\nexport const STICKER_SIZE_TWO_FA = 160;\nexport const STICKER_SIZE_DISCUSSION_GROUPS = 140;\nexport const STICKER_SIZE_FOLDER_SETTINGS = 80;\nexport const STICKER_SIZE_INLINE_BOT_RESULT = 100;\nexport const RECENT_STICKERS_LIMIT = 20;\nexport const MEMOJI_STICKER_ID = 'MEMOJI_STICKER';\n\nexport const BASE_EMOJI_KEYWORD_LANG = 'en';\n\nexport const MENU_TRANSITION_DURATION = 200;\nexport const SLIDE_TRANSITION_DURATION = 450;\n\nexport const VIDEO_MOV_TYPE = 'video/quicktime';\n\nexport const SUPPORTED_IMAGE_CONTENT_TYPES = new Set([\n 'image/png', 'image/gif', 'image/jpeg',\n]);\n\nexport const SUPPORTED_VIDEO_CONTENT_TYPES = new Set([\n 'video/mp4', // video/quicktime added dynamically in environment.ts\n]);\n\nexport const CONTENT_TYPES_WITH_PREVIEW = new Set([\n ...SUPPORTED_IMAGE_CONTENT_TYPES,\n ...SUPPORTED_VIDEO_CONTENT_TYPES,\n]);\n\nexport const CONTENT_NOT_SUPPORTED = 'The message is not supported on this version of Telegram.';\n\n// eslint-disable-next-line max-len\nexport const RE_LINK_TEMPLATE = '((ftp|https?):\\\\/\\\\/)?((www\\\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\\\.[a-zA-Z0-9()]{1,63})\\\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)';\nexport const RE_MENTION_TEMPLATE = '(@[\\\\w\\\\d_-]+)';\nexport const RE_TG_LINK = /^tg:(\\/\\/)?([?=&\\d\\w_-]+)?/gm;\nexport const RE_TME_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/)/gm;\n\n// eslint-disable-next-line max-len\nexport const COUNTRIES_WITH_12H_TIME_FORMAT = new Set(['AU', 'BD', 'CA', 'CO', 'EG', 'HN', 'IE', 'IN', 'JO', 'MX', 'MY', 'NI', 'NZ', 'PH', 'PK', 'SA', 'SV', 'US']);\n\n// MTProto constants\nexport const SERVICE_NOTIFICATIONS_USER_ID = '777000';\nexport const REPLIES_USER_ID = '1271266957'; // TODO For Test connection ID must be equal to 708513\nexport const ALL_FOLDER_ID = 0;\nexport const ARCHIVED_FOLDER_ID = 1;\nexport const DELETED_COMMENTS_CHANNEL_ID = '-777';\nexport const MAX_MEDIA_FILES_FOR_ALBUM = 10;\nexport const MAX_ACTIVE_PINNED_CHATS = 5;\nexport const SCHEDULED_WHEN_ONLINE = 0x7FFFFFFE;\nexport const DEFAULT_LANG_CODE = 'en';\nexport const DEFAULT_LANG_PACK = 'android';\nexport const LANG_PACKS = ['android', 'ios', 'tdesktop', 'macos'] as const;\nexport const TIPS_USERNAME = 'TelegramTips';\nexport const LOCALIZED_TIPS = ['ar', 'pt-br', 'id', 'it', 'ko', 'ms', 'pl', 'es', 'tr'];\nexport const FEEDBACK_URL = 'https://bugs.telegram.org/?tag_ids=41&sort=time';\nexport const LIGHT_THEME_BG_COLOR = '#A2AF8E';\nexport const DARK_THEME_BG_COLOR = '#0F0F0F';\nexport const DARK_THEME_PATTERN_COLOR = '#0a0a0a8c';\nexport const DEFAULT_PATTERN_COLOR = 'rgba(90, 110, 70, 0.6)';\n// TODO Get values from `getConfig` method once it's available\nexport const SEEN_BY_MEMBERS_CHAT_MAX = 50;\nexport const SEEN_BY_MEMBERS_EXPIRE = 604680; // One week - 2 min\n\n// Group calls\nexport const GROUP_CALL_VOLUME_MULTIPLIER = 100;\nexport const GROUP_CALL_DEFAULT_VOLUME = 100 * GROUP_CALL_VOLUME_MULTIPLIER;\nexport const ENABLE_THUMBNAIL_VIDEO = false;\n","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 changeData(\n key: string,\n animationData: AnyLiteral,\n onInit: CancellableCallback,\n) {\n if (!rLottieApi) {\n await rLottieApiPromise;\n }\n\n const json = JSON.stringify(animationData);\n const { reduceFactor, handle } = renderers.get(key)!;\n\n const stringOnWasmHeap = allocate(intArrayFromString(json), 'i8', 0);\n const framesCount = rLottieApi.loadFromData(handle, stringOnWasmHeap);\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 changeData,\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","changeData","get","renderFrames","fromIndex","toIndex","onProgress","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.47391222364a22307e69.js","mappings":"mBAuCsC,oBAAXA,QAA0BA,OAAOC,YAmEzBC,KAAKC,MAAM,KACJ,IAAIC,IAAI,CAChD,aAAc,sBAAuB,iBAAkB,0BAA2B,kBA5G7E,MAsIMC,EAAgC,IAAID,IAAI,CACnD,YAAa,YAAa,eAGfE,EAAgC,IAAIF,IAAI,CACnD,cAGwC,IAAIA,IAAI,IAC7CC,KACAC,IAYyC,IAAIF,IAAI,CAAC,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,OC7E3JG,KAAKC,QAAWC,IAEdC,QAAQC,MAAMF,GACdG,EAAa,CAAEC,KAAM,iBAAkBF,MAAO,CAAEG,QAASL,EAAEE,MAAMG,SAAW,mCAG9EP,KAAKQ,iBAAiB,sBAAuBN,IAE3CC,QAAQC,MAAMF,GACdG,EAAa,CAAEC,KAAM,iBAAkBF,MAAO,CAAEG,QAASL,EAAEO,OAAOF,SAAW,qCAjFjF,MAAMG,EAAgB,IAAIC,IAqF1B,SAASN,EAAaO,EAAyBC,GACzCA,EACFC,YAAYF,EAAMC,GAElBC,YAAYF,GCnFhB,IAAIG,EAFJf,KAAKgB,cAAc,mBAGnB,MAAMC,EAAoB,IAAIC,SAAeC,IAC3CC,OAAOC,qBAAuB,KAC5BN,EAAa,CACXO,KAAMF,OAAOG,MAAM,cAAe,GAAI,IACtCC,QAASJ,OAAOG,MAAM,iBAAkB,GAAI,CAAC,WAC7CE,OAAQL,OAAOG,MAAM,gBAAiB,GAAI,CAAC,SAAU,SAAU,WAC/DG,OAAQN,OAAOG,MAAM,gBAAiB,SAAU,CAAC,WACjDI,OAAQP,OAAOG,MAAM,gBAAiB,GAAI,CAAC,SAAU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QoC,EAAShB,QAE5Bf,EAAUgC,OAAO7B,KD1FjB8B,UAAY/B,MAAAA,IACV,MAAM,KAAEnB,GAASL,EAEjB,OAAQK,EAAKN,MACX,IAAK,aAAc,CACjB,MAAM,UAAEyD,EAAF,KAAaC,EAAb,KAAmBC,GAASrD,EAClC,IACE,GAAImD,EAAW,CACb,MAAMG,EAAW,IAAIC,KACnB,MAAMC,EAAUD,EAAaA,EAAaE,OAAS,GAEnDhE,EAAa,CACXC,KAAM,iBACNyD,UAAAA,EACAI,aAAAA,GACCC,aAAmBE,YAAc,CAACF,QAAWG,IAGlD7D,EAAcoC,IAAIiB,EAAWG,GAE7BD,EAAKO,KAAKN,GAGZ,MAAOO,EAAU5D,SAAuBiB,EAAIkC,MAASC,IAAU,GAE3DF,GACF1D,EACE,CACEC,KAAM,iBACNyD,UAAAA,EACAU,SAAAA,GAEF5D,GAGJ,MAAOT,GAMH2D,GACF1D,EAAa,CACXC,KAAM,iBACNyD,UAAAA,EACA3D,MAAO,CAAEG,QAASH,EAAMG,WAK1BwD,GACFrD,EAAcmD,OAAOE,GAGvB,MAEF,IAAK,iBAAkB,CACrB,MAAMG,EAAWxD,EAAcuC,IAAIrC,EAAKmD,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-v7';\nexport const ASSET_CACHE_NAME = 'tt-assets';\nexport const AUTODOWNLOAD_FILESIZE_MB_LIMITS = [1, 5, 10, 50, 100, 500];\n\nexport const DOWNLOAD_WORKERS = 16;\nexport const UPLOAD_WORKERS = 16;\n\nconst isBigScreen = typeof window !== 'undefined' && window.innerHeight >= 900;\n\nexport const MIN_PASSWORD_LENGTH = 1;\n\nexport const MESSAGE_LIST_SLICE = isBigScreen ? 60 : 40;\nexport const MESSAGE_LIST_VIEWPORT_LIMIT = MESSAGE_LIST_SLICE * 2;\n\nexport const CHAT_HEIGHT_PX = 72;\nexport const CHAT_LIST_SLICE = isBigScreen ? 30 : 25;\nexport const CHAT_LIST_LOAD_SLICE = 100;\nexport const SHARED_MEDIA_SLICE = 42;\nexport const MESSAGE_SEARCH_SLICE = 42;\nexport const GLOBAL_SEARCH_SLICE = 20;\nexport const MEMBERS_SLICE = 30;\nexport const MEMBERS_LOAD_SLICE = 200;\nexport const PINNED_MESSAGES_LIMIT = 50;\nexport const BLOCKED_LIST_LIMIT = 100;\nexport const PROFILE_PHOTOS_LIMIT = 40;\nexport const PROFILE_SENSITIVE_AREA = 500;\nexport const COMMON_CHATS_LIMIT = 100;\nexport const GROUP_CALL_PARTICIPANTS_LIMIT = 100;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 20;\nexport const ALL_CHATS_PRELOAD_DISABLED = false;\n\nexport const SPONSORED_MESSAGE_CACHE_MS = 300000; // 5 min\n\nexport const DEFAULT_VOLUME = 1;\nexport const DEFAULT_PLAYBACK_RATE = 1;\n\nexport const ANIMATION_LEVEL_MIN = 0;\nexport const ANIMATION_LEVEL_MED = 1;\nexport const ANIMATION_LEVEL_MAX = 2;\nexport const ANIMATION_LEVEL_DEFAULT = ANIMATION_LEVEL_MAX;\n\nexport const DEFAULT_MESSAGE_TEXT_SIZE_PX = 16;\nexport const IOS_DEFAULT_MESSAGE_TEXT_SIZE_PX = 17;\nexport const MACOS_DEFAULT_MESSAGE_TEXT_SIZE_PX = 15;\n\nexport const DRAFT_DEBOUNCE = 10000; // 10s\nexport const SEND_MESSAGE_ACTION_INTERVAL = 3000; // 3s\n\nexport const EDITABLE_INPUT_ID = 'editable-message-text';\nexport const EDITABLE_INPUT_MODAL_ID = 'editable-message-text-modal';\n\n// Screen width where Pinned Message / Audio Player in the Middle Header can be safely displayed\nexport const SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1440; // px\n// Screen width where Pinned Message / Audio Player in the Middle Header shouldn't collapse with ChatInfo\nexport const SAFE_SCREEN_WIDTH_FOR_CHAT_INFO = 1150; // px\n\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1275; // px\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN = 925; // px\nexport const MOBILE_SCREEN_MAX_WIDTH = 600; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH = 950; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT = 450; // px\n\nexport const LOCAL_MESSAGE_ID_BASE = 1e9;\nexport const TMP_CHAT_ID = '0';\n\nexport const ANIMATION_END_DELAY = 100;\n\nexport const FAST_SMOOTH_MAX_DISTANCE = 1500;\nexport const FAST_SMOOTH_MIN_DURATION = 250;\nexport const FAST_SMOOTH_MAX_DURATION = 600;\nexport const FAST_SMOOTH_SHORT_TRANSITION_MAX_DISTANCE = 500; // px\n\n// Average duration of message sending animation\nexport const API_UPDATE_THROTTLE = Math.round((FAST_SMOOTH_MIN_DURATION + FAST_SMOOTH_MAX_DURATION) / 2);\nexport const API_THROTTLE_RESET_UPDATES = new Set([\n 'newMessage', 'newScheduledMessage', 'deleteMessages', 'deleteScheduledMessages', 'deleteHistory',\n]);\n\nexport const STICKER_SIZE_INLINE_DESKTOP_FACTOR = 13;\nexport const STICKER_SIZE_INLINE_MOBILE_FACTOR = 11;\nexport const STICKER_SIZE_AUTH = 160;\nexport const STICKER_SIZE_AUTH_MOBILE = 120;\nexport const STICKER_SIZE_PICKER = 64;\nexport const STICKER_SIZE_GENERAL_SETTINGS = 48;\nexport const STICKER_SIZE_PICKER_HEADER = 32;\nexport const STICKER_SIZE_SEARCH = 64;\nexport const STICKER_SIZE_MODAL = 64;\nexport const STICKER_SIZE_TWO_FA = 160;\nexport const STICKER_SIZE_DISCUSSION_GROUPS = 140;\nexport const STICKER_SIZE_FOLDER_SETTINGS = 80;\nexport const STICKER_SIZE_INLINE_BOT_RESULT = 100;\nexport const RECENT_STICKERS_LIMIT = 20;\nexport const MEMOJI_STICKER_ID = 'MEMOJI_STICKER';\n\nexport const BASE_EMOJI_KEYWORD_LANG = 'en';\n\nexport const MENU_TRANSITION_DURATION = 200;\nexport const SLIDE_TRANSITION_DURATION = 450;\n\nexport const VIDEO_MOV_TYPE = 'video/quicktime';\n\nexport const SUPPORTED_IMAGE_CONTENT_TYPES = new Set([\n 'image/png', 'image/gif', 'image/jpeg',\n]);\n\nexport const SUPPORTED_VIDEO_CONTENT_TYPES = new Set([\n 'video/mp4', // video/quicktime added dynamically in environment.ts\n]);\n\nexport const CONTENT_TYPES_WITH_PREVIEW = new Set([\n ...SUPPORTED_IMAGE_CONTENT_TYPES,\n ...SUPPORTED_VIDEO_CONTENT_TYPES,\n]);\n\nexport const CONTENT_NOT_SUPPORTED = 'The message is not supported on this version of Telegram.';\n\n// eslint-disable-next-line max-len\nexport const RE_LINK_TEMPLATE = '((ftp|https?):\\\\/\\\\/)?((www\\\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\\\.[a-zA-Z0-9()]{1,63})\\\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)';\nexport const RE_MENTION_TEMPLATE = '(@[\\\\w\\\\d_-]+)';\nexport const RE_TG_LINK = /^tg:(\\/\\/)?([?=&\\d\\w_-]+)?/gm;\nexport const RE_TME_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/)/gm;\n\n// eslint-disable-next-line max-len\nexport const COUNTRIES_WITH_12H_TIME_FORMAT = new Set(['AU', 'BD', 'CA', 'CO', 'EG', 'HN', 'IE', 'IN', 'JO', 'MX', 'MY', 'NI', 'NZ', 'PH', 'PK', 'SA', 'SV', 'US']);\n\n// MTProto constants\nexport const SERVICE_NOTIFICATIONS_USER_ID = '777000';\nexport const REPLIES_USER_ID = '1271266957'; // TODO For Test connection ID must be equal to 708513\nexport const ALL_FOLDER_ID = 0;\nexport const ARCHIVED_FOLDER_ID = 1;\nexport const DELETED_COMMENTS_CHANNEL_ID = '-777';\nexport const MAX_MEDIA_FILES_FOR_ALBUM = 10;\nexport const MAX_ACTIVE_PINNED_CHATS = 5;\nexport const SCHEDULED_WHEN_ONLINE = 0x7FFFFFFE;\nexport const DEFAULT_LANG_CODE = 'en';\nexport const DEFAULT_LANG_PACK = 'android';\nexport const LANG_PACKS = ['android', 'ios', 'tdesktop', 'macos'] as const;\nexport const TIPS_USERNAME = 'TelegramTips';\nexport const LOCALIZED_TIPS = ['ar', 'pt-br', 'id', 'it', 'ko', 'ms', 'pl', 'es', 'tr'];\nexport const FEEDBACK_URL = 'https://bugs.telegram.org/?tag_ids=41&sort=time';\nexport const LIGHT_THEME_BG_COLOR = '#A2AF8E';\nexport const DARK_THEME_BG_COLOR = '#0F0F0F';\nexport const DARK_THEME_PATTERN_COLOR = '#0a0a0a8c';\nexport const DEFAULT_PATTERN_COLOR = 'rgba(90, 110, 70, 0.6)';\n// TODO Get values from `getConfig` method once it's available\nexport const SEEN_BY_MEMBERS_CHAT_MAX = 50;\nexport const SEEN_BY_MEMBERS_EXPIRE = 604680; // One week - 2 min\n\n// Group calls\nexport const GROUP_CALL_VOLUME_MULTIPLIER = 100;\nexport const GROUP_CALL_DEFAULT_VOLUME = 100 * GROUP_CALL_VOLUME_MULTIPLIER;\nexport const ENABLE_THUMBNAIL_VIDEO = false;\n","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 changeData(\n key: string,\n animationData: AnyLiteral,\n onInit: CancellableCallback,\n) {\n if (!rLottieApi) {\n await rLottieApiPromise;\n }\n\n const json = JSON.stringify(animationData);\n const { reduceFactor, handle } = renderers.get(key)!;\n\n const stringOnWasmHeap = allocate(intArrayFromString(json), 'i8', 0);\n const framesCount = rLottieApi.loadFromData(handle, stringOnWasmHeap);\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 changeData,\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","changeData","get","renderFrames","fromIndex","toIndex","onProgress","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/524.80c446dcb25355f04b36.js b/dist/524.95e29e37c83dea5150d6.js similarity index 99% rename from dist/524.80c446dcb25355f04b36.js rename to dist/524.95e29e37c83dea5150d6.js index 5a8e206a..f9b3fc13 100644 --- a/dist/524.80c446dcb25355f04b36.js +++ b/dist/524.95e29e37c83dea5150d6.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.80c446dcb25355f04b36.js.map \ No newline at end of file +//# sourceMappingURL=524.95e29e37c83dea5150d6.js.map \ No newline at end of file diff --git a/dist/524.80c446dcb25355f04b36.js.map b/dist/524.95e29e37c83dea5150d6.js.map similarity index 99% rename from dist/524.80c446dcb25355f04b36.js.map rename to dist/524.95e29e37c83dea5150d6.js.map index 660b3de0..e7768d59 100644 --- a/dist/524.80c446dcb25355f04b36.js.map +++ b/dist/524.95e29e37c83dea5150d6.js.map @@ -1 +1 @@ -{"version":3,"file":"524.80c446dcb25355f04b36.js","mappings":"mBAAO,MA6BMA,EAA+B,uBAI/BC,EAAmB,YAqGnBC,GA/FyB,oBAAXC,QAA0BA,OAAOC,YAmEzBC,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,IAYyC,IAAID,IAAI,CAAC,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,OCzCtJ,MAAME,EAASC,GAAe,IAAIC,SAAeC,IACtDC,YAAW,IAAMD,KAAWF,MC5FxBI,EAAoB,OAIpBC,EAAgB,IAAIC,ICpBnBC,eAAeC,EAAiBC,GACrC,MAAMC,QA0BRH,eAA8BI,EAAsBC,GAClD,IACE,aAAaX,QAAQY,KAAK,CACxBd,EAhCg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xI,KAAK2C,QAAQ2F,WAAWhG,GAC5CkG,IAEF5G,EAAY4G,EAAUvF,IAAM5B,GAE9B,MAAOb,OAQCiI,OCpKdzI,KAAKiB,iBAAiB,WDuKf,SAA6B1B,GAKlC,IAAKA,EAAE8B,KAAM,OACb,MAAMqH,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-v7';\nexport const ASSET_CACHE_NAME = 'tt-assets';\nexport const AUTODOWNLOAD_FILESIZE_MB_LIMITS = [1, 5, 10, 50, 100, 500];\n\nexport const DOWNLOAD_WORKERS = 16;\nexport const UPLOAD_WORKERS = 16;\n\nconst isBigScreen = typeof window !== 'undefined' && window.innerHeight >= 900;\n\nexport const MIN_PASSWORD_LENGTH = 1;\n\nexport const MESSAGE_LIST_SLICE = isBigScreen ? 60 : 40;\nexport const MESSAGE_LIST_VIEWPORT_LIMIT = MESSAGE_LIST_SLICE * 2;\n\nexport const CHAT_HEIGHT_PX = 72;\nexport const CHAT_LIST_SLICE = isBigScreen ? 30 : 25;\nexport const CHAT_LIST_LOAD_SLICE = 100;\nexport const SHARED_MEDIA_SLICE = 42;\nexport const MESSAGE_SEARCH_SLICE = 42;\nexport const GLOBAL_SEARCH_SLICE = 20;\nexport const MEMBERS_SLICE = 30;\nexport const MEMBERS_LOAD_SLICE = 200;\nexport const PINNED_MESSAGES_LIMIT = 50;\nexport const BLOCKED_LIST_LIMIT = 100;\nexport const PROFILE_PHOTOS_LIMIT = 40;\nexport const PROFILE_SENSITIVE_AREA = 500;\nexport const COMMON_CHATS_LIMIT = 100;\nexport const GROUP_CALL_PARTICIPANTS_LIMIT = 100;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 20;\nexport const ALL_CHATS_PRELOAD_DISABLED = false;\n\nexport const SPONSORED_MESSAGE_CACHE_MS = 300000; // 5 min\n\nexport const DEFAULT_VOLUME = 1;\nexport const DEFAULT_PLAYBACK_RATE = 1;\n\nexport const ANIMATION_LEVEL_MIN = 0;\nexport const ANIMATION_LEVEL_MED = 1;\nexport const ANIMATION_LEVEL_MAX = 2;\nexport const ANIMATION_LEVEL_DEFAULT = ANIMATION_LEVEL_MAX;\n\nexport const DEFAULT_MESSAGE_TEXT_SIZE_PX = 16;\nexport const IOS_DEFAULT_MESSAGE_TEXT_SIZE_PX = 17;\nexport const MACOS_DEFAULT_MESSAGE_TEXT_SIZE_PX = 15;\n\nexport const DRAFT_DEBOUNCE = 10000; // 10s\nexport const SEND_MESSAGE_ACTION_INTERVAL = 3000; // 3s\n\nexport const EDITABLE_INPUT_ID = 'editable-message-text';\nexport const EDITABLE_INPUT_MODAL_ID = 'editable-message-text-modal';\n\n// Screen width where Pinned Message / Audio Player in the Middle Header can be safely displayed\nexport const SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1440; // px\n// Screen width where Pinned Message / Audio Player in the Middle Header shouldn't collapse with ChatInfo\nexport const SAFE_SCREEN_WIDTH_FOR_CHAT_INFO = 1150; // px\n\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1275; // px\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN = 925; // px\nexport const MOBILE_SCREEN_MAX_WIDTH = 600; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH = 950; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT = 450; // px\n\nexport const LOCAL_MESSAGE_ID_BASE = 1e9;\nexport const TMP_CHAT_ID = '0';\n\nexport const ANIMATION_END_DELAY = 100;\n\nexport const FAST_SMOOTH_MAX_DISTANCE = 1500;\nexport const FAST_SMOOTH_MIN_DURATION = 250;\nexport const FAST_SMOOTH_MAX_DURATION = 600;\nexport const FAST_SMOOTH_SHORT_TRANSITION_MAX_DISTANCE = 500; // px\n\n// Average duration of message sending animation\nexport const API_UPDATE_THROTTLE = Math.round((FAST_SMOOTH_MIN_DURATION + FAST_SMOOTH_MAX_DURATION) / 2);\nexport const API_THROTTLE_RESET_UPDATES = new Set([\n 'newMessage', 'newScheduledMessage', 'deleteMessages', 'deleteScheduledMessages', 'deleteHistory',\n]);\n\nexport const STICKER_SIZE_INLINE_DESKTOP_FACTOR = 13;\nexport const STICKER_SIZE_INLINE_MOBILE_FACTOR = 11;\nexport const STICKER_SIZE_AUTH = 160;\nexport const STICKER_SIZE_AUTH_MOBILE = 120;\nexport const STICKER_SIZE_PICKER = 64;\nexport const STICKER_SIZE_GENERAL_SETTINGS = 48;\nexport const STICKER_SIZE_PICKER_HEADER = 32;\nexport const STICKER_SIZE_SEARCH = 64;\nexport const STICKER_SIZE_MODAL = 64;\nexport const STICKER_SIZE_TWO_FA = 160;\nexport const STICKER_SIZE_DISCUSSION_GROUPS = 140;\nexport const STICKER_SIZE_FOLDER_SETTINGS = 80;\nexport const STICKER_SIZE_INLINE_BOT_RESULT = 100;\nexport const RECENT_STICKERS_LIMIT = 20;\nexport const MEMOJI_STICKER_ID = 'MEMOJI_STICKER';\n\nexport const BASE_EMOJI_KEYWORD_LANG = 'en';\n\nexport const MENU_TRANSITION_DURATION = 200;\nexport const SLIDE_TRANSITION_DURATION = 450;\n\nexport const VIDEO_MOV_TYPE = 'video/quicktime';\n\nexport const SUPPORTED_IMAGE_CONTENT_TYPES = new Set([\n 'image/png', 'image/gif', 'image/jpeg',\n]);\n\nexport const SUPPORTED_VIDEO_CONTENT_TYPES = new Set([\n 'video/mp4', // video/quicktime added dynamically in environment.ts\n]);\n\nexport const CONTENT_TYPES_WITH_PREVIEW = new Set([\n ...SUPPORTED_IMAGE_CONTENT_TYPES,\n ...SUPPORTED_VIDEO_CONTENT_TYPES,\n]);\n\nexport const CONTENT_NOT_SUPPORTED = 'The message is not supported on this version of Telegram.';\n\n// eslint-disable-next-line max-len\nexport const RE_LINK_TEMPLATE = '((ftp|https?):\\\\/\\\\/)?((www\\\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\\\.[a-zA-Z0-9()]{1,63})\\\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)';\nexport const RE_MENTION_TEMPLATE = '(@[\\\\w\\\\d_-]+)';\nexport const RE_TG_LINK = /^tg:(\\/\\/)?([?=&\\d\\w_-]+)?/gm;\nexport const RE_TME_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/)/gm;\n\n// eslint-disable-next-line max-len\nexport const COUNTRIES_WITH_12H_TIME_FORMAT = new Set(['AU', 'BD', 'CA', 'CO', 'EG', 'HN', 'IE', 'IN', 'JO', 'MX', 'MY', 'NI', 'NZ', 'PH', 'PK', 'SA', 'SV', 'US']);\n\n// MTProto constants\nexport const SERVICE_NOTIFICATIONS_USER_ID = '777000';\nexport const REPLIES_USER_ID = '1271266957'; // TODO For Test connection ID must be equal to 708513\nexport const ALL_FOLDER_ID = 0;\nexport const ARCHIVED_FOLDER_ID = 1;\nexport const DELETED_COMMENTS_CHANNEL_ID = '-777';\nexport const MAX_MEDIA_FILES_FOR_ALBUM = 10;\nexport const MAX_ACTIVE_PINNED_CHATS = 5;\nexport const SCHEDULED_WHEN_ONLINE = 0x7FFFFFFE;\nexport const DEFAULT_LANG_CODE = 'en';\nexport const DEFAULT_LANG_PACK = 'android';\nexport const LANG_PACKS = ['android', 'ios', 'tdesktop', 'macos'] as const;\nexport const TIPS_USERNAME = 'TelegramTips';\nexport const LOCALIZED_TIPS = ['ar', 'pt-br', 'id', 'it', 'ko', 'ms', 'pl', 'es', 'tr'];\nexport const FEEDBACK_URL = 'https://bugs.telegram.org/?tag_ids=41&sort=time';\nexport const LIGHT_THEME_BG_COLOR = '#A2AF8E';\nexport const DARK_THEME_BG_COLOR = '#0F0F0F';\nexport const DARK_THEME_PATTERN_COLOR = '#0a0a0a8c';\nexport const DEFAULT_PATTERN_COLOR = 'rgba(90, 110, 70, 0.6)';\n// TODO Get values from `getConfig` method once it's available\nexport const SEEN_BY_MEMBERS_CHAT_MAX = 50;\nexport const SEEN_BY_MEMBERS_EXPIRE = 604680; // One week - 2 min\n\n// Group calls\nexport const GROUP_CALL_VOLUME_MULTIPLIER = 100;\nexport const GROUP_CALL_DEFAULT_VOLUME = 100 * GROUP_CALL_VOLUME_MULTIPLIER;\nexport const ENABLE_THUMBNAIL_VIDEO = false;\n","type Scheduler =\n typeof requestAnimationFrame\n | typeof onTickEnd\n | typeof runNow;\n\nexport function debounce(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n shouldRunLast = true,\n) {\n let waitingTimeout: number | undefined;\n\n return (...args: Parameters) => {\n if (waitingTimeout) {\n clearTimeout(waitingTimeout);\n waitingTimeout = undefined;\n } else if (shouldRunFirst) {\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n waitingTimeout = self.setTimeout(() => {\n if (shouldRunLast) {\n fn(...args);\n }\n\n waitingTimeout = undefined;\n }, ms);\n };\n}\n\nexport function throttle(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n) {\n let interval: number | undefined;\n let isPending: boolean;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n isPending = true;\n args = _args;\n\n if (!interval) {\n if (shouldRunFirst) {\n isPending = false;\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n interval = self.setInterval(() => {\n if (!isPending) {\n // eslint-disable-next-line no-restricted-globals\n self.clearInterval(interval!);\n interval = undefined;\n return;\n }\n\n isPending = false;\n fn(...args);\n }, ms);\n }\n };\n}\n\nexport function throttleWithRaf(fn: F) {\n return throttleWith(fastRaf, fn);\n}\n\nexport function throttleWithPrimaryRaf(fn: F) {\n return throttleWith(fastRafPrimary, fn);\n}\n\nexport function throttleWithTickEnd(fn: F) {\n return throttleWith(onTickEnd, fn);\n}\n\nexport function throttleWithNow(fn: F) {\n return throttleWith(runNow, fn);\n}\n\nexport function throttleWith(schedulerFn: Scheduler, fn: F) {\n let waiting = false;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n args = _args;\n\n if (!waiting) {\n waiting = true;\n\n schedulerFn(() => {\n waiting = false;\n fn(...args);\n });\n }\n };\n}\n\nexport function onIdle(cb: NoneToVoidFunction, timeout?: number) {\n // eslint-disable-next-line no-restricted-globals\n if (self.requestIdleCallback) {\n // eslint-disable-next-line no-restricted-globals\n self.requestIdleCallback(cb, { timeout });\n } else {\n onTickEnd(cb);\n }\n}\n\nfunction runNow(fn: NoneToVoidFunction) {\n fn();\n}\n\nexport const pause = (ms: number) => new Promise((resolve) => {\n setTimeout(() => resolve(), ms);\n});\n\nexport function rafPromise() {\n return new Promise((resolve) => {\n fastRaf(resolve);\n });\n}\n\nlet fastRafCallbacks: NoneToVoidFunction[] | undefined;\nlet fastRafPrimaryCallbacks: NoneToVoidFunction[] | undefined;\n\n// May result in an immediate execution if called from another `requestAnimationFrame` callback\nexport function fastRaf(callback: NoneToVoidFunction, isPrimary = false) {\n if (!fastRafCallbacks) {\n fastRafCallbacks = isPrimary ? [] : [callback];\n fastRafPrimaryCallbacks = isPrimary ? [callback] : [];\n\n requestAnimationFrame(() => {\n const currentCallbacks = fastRafCallbacks!;\n const currentPrimaryCallbacks = fastRafPrimaryCallbacks!;\n fastRafCallbacks = undefined;\n fastRafPrimaryCallbacks = undefined;\n currentPrimaryCallbacks.forEach((cb) => cb());\n currentCallbacks.forEach((cb) => cb());\n });\n } else if (isPrimary) {\n fastRafPrimaryCallbacks!.push(callback);\n } else {\n fastRafCallbacks.push(callback);\n }\n}\n\nexport function fastRafPrimary(callback: NoneToVoidFunction) {\n fastRaf(callback, true);\n}\n\nlet onTickEndCallbacks: NoneToVoidFunction[] | undefined;\nlet onTickEndPrimaryCallbacks: NoneToVoidFunction[] | undefined;\n\nexport function onTickEnd(callback: NoneToVoidFunction, isPrimary = false) {\n if (!onTickEndCallbacks) {\n onTickEndCallbacks = isPrimary ? [] : [callback];\n onTickEndPrimaryCallbacks = isPrimary ? [callback] : [];\n\n Promise.resolve().then(() => {\n const currentCallbacks = onTickEndCallbacks!;\n const currentPrimaryCallbacks = onTickEndPrimaryCallbacks!;\n onTickEndCallbacks = undefined;\n onTickEndPrimaryCallbacks = undefined;\n currentPrimaryCallbacks.forEach((cb) => cb());\n currentCallbacks.forEach((cb) => cb());\n });\n } else if (isPrimary) {\n onTickEndPrimaryCallbacks!.push(callback);\n } else {\n onTickEndCallbacks.push(callback);\n }\n}\n\nexport function onTickEndPrimary(callback: NoneToVoidFunction) {\n onTickEnd(callback, true);\n}\n\nlet beforeUnloadCallbacks: NoneToVoidFunction[] | undefined;\n\nexport function onBeforeUnload(callback: NoneToVoidFunction, isLast = false) {\n if (!beforeUnloadCallbacks) {\n beforeUnloadCallbacks = [];\n // eslint-disable-next-line no-restricted-globals\n self.addEventListener('beforeunload', () => {\n beforeUnloadCallbacks!.forEach((cb) => cb());\n });\n }\n\n if (isLast) {\n beforeUnloadCallbacks.push(callback);\n } else {\n beforeUnloadCallbacks.unshift(callback);\n }\n\n return () => {\n beforeUnloadCallbacks = beforeUnloadCallbacks!.filter((cb) => cb !== callback);\n };\n}\n","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, DEBUG_MORE } 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_MORE) {\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.95e29e37c83dea5150d6.js","mappings":"mBAAO,MA6BMA,EAA+B,uBAI/BC,EAAmB,YAqGnBC,GA/FyB,oBAAXC,QAA0BA,OAAOC,YAmEzBC,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,IAYyC,IAAID,IAAI,CAAC,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,OCzCtJ,MAAME,EAASC,GAAe,IAAIC,SAAeC,IACtDC,YAAW,IAAMD,KAAWF,MC5FxBI,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,OAAAA,IA0BdV,KAEF,MAA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B,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-v7';\nexport const ASSET_CACHE_NAME = 'tt-assets';\nexport const AUTODOWNLOAD_FILESIZE_MB_LIMITS = [1, 5, 10, 50, 100, 500];\n\nexport const DOWNLOAD_WORKERS = 16;\nexport const UPLOAD_WORKERS = 16;\n\nconst isBigScreen = typeof window !== 'undefined' && window.innerHeight >= 900;\n\nexport const MIN_PASSWORD_LENGTH = 1;\n\nexport const MESSAGE_LIST_SLICE = isBigScreen ? 60 : 40;\nexport const MESSAGE_LIST_VIEWPORT_LIMIT = MESSAGE_LIST_SLICE * 2;\n\nexport const CHAT_HEIGHT_PX = 72;\nexport const CHAT_LIST_SLICE = isBigScreen ? 30 : 25;\nexport const CHAT_LIST_LOAD_SLICE = 100;\nexport const SHARED_MEDIA_SLICE = 42;\nexport const MESSAGE_SEARCH_SLICE = 42;\nexport const GLOBAL_SEARCH_SLICE = 20;\nexport const MEMBERS_SLICE = 30;\nexport const MEMBERS_LOAD_SLICE = 200;\nexport const PINNED_MESSAGES_LIMIT = 50;\nexport const BLOCKED_LIST_LIMIT = 100;\nexport const PROFILE_PHOTOS_LIMIT = 40;\nexport const PROFILE_SENSITIVE_AREA = 500;\nexport const COMMON_CHATS_LIMIT = 100;\nexport const GROUP_CALL_PARTICIPANTS_LIMIT = 100;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 20;\nexport const ALL_CHATS_PRELOAD_DISABLED = false;\n\nexport const SPONSORED_MESSAGE_CACHE_MS = 300000; // 5 min\n\nexport const DEFAULT_VOLUME = 1;\nexport const DEFAULT_PLAYBACK_RATE = 1;\n\nexport const ANIMATION_LEVEL_MIN = 0;\nexport const ANIMATION_LEVEL_MED = 1;\nexport const ANIMATION_LEVEL_MAX = 2;\nexport const ANIMATION_LEVEL_DEFAULT = ANIMATION_LEVEL_MAX;\n\nexport const DEFAULT_MESSAGE_TEXT_SIZE_PX = 16;\nexport const IOS_DEFAULT_MESSAGE_TEXT_SIZE_PX = 17;\nexport const MACOS_DEFAULT_MESSAGE_TEXT_SIZE_PX = 15;\n\nexport const DRAFT_DEBOUNCE = 10000; // 10s\nexport const SEND_MESSAGE_ACTION_INTERVAL = 3000; // 3s\n\nexport const EDITABLE_INPUT_ID = 'editable-message-text';\nexport const EDITABLE_INPUT_MODAL_ID = 'editable-message-text-modal';\n\n// Screen width where Pinned Message / Audio Player in the Middle Header can be safely displayed\nexport const SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1440; // px\n// Screen width where Pinned Message / Audio Player in the Middle Header shouldn't collapse with ChatInfo\nexport const SAFE_SCREEN_WIDTH_FOR_CHAT_INFO = 1150; // px\n\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1275; // px\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN = 925; // px\nexport const MOBILE_SCREEN_MAX_WIDTH = 600; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH = 950; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT = 450; // px\n\nexport const LOCAL_MESSAGE_ID_BASE = 1e9;\nexport const TMP_CHAT_ID = '0';\n\nexport const ANIMATION_END_DELAY = 100;\n\nexport const FAST_SMOOTH_MAX_DISTANCE = 1500;\nexport const FAST_SMOOTH_MIN_DURATION = 250;\nexport const FAST_SMOOTH_MAX_DURATION = 600;\nexport const FAST_SMOOTH_SHORT_TRANSITION_MAX_DISTANCE = 500; // px\n\n// Average duration of message sending animation\nexport const API_UPDATE_THROTTLE = Math.round((FAST_SMOOTH_MIN_DURATION + FAST_SMOOTH_MAX_DURATION) / 2);\nexport const API_THROTTLE_RESET_UPDATES = new Set([\n 'newMessage', 'newScheduledMessage', 'deleteMessages', 'deleteScheduledMessages', 'deleteHistory',\n]);\n\nexport const STICKER_SIZE_INLINE_DESKTOP_FACTOR = 13;\nexport const STICKER_SIZE_INLINE_MOBILE_FACTOR = 11;\nexport const STICKER_SIZE_AUTH = 160;\nexport const STICKER_SIZE_AUTH_MOBILE = 120;\nexport const STICKER_SIZE_PICKER = 64;\nexport const STICKER_SIZE_GENERAL_SETTINGS = 48;\nexport const STICKER_SIZE_PICKER_HEADER = 32;\nexport const STICKER_SIZE_SEARCH = 64;\nexport const STICKER_SIZE_MODAL = 64;\nexport const STICKER_SIZE_TWO_FA = 160;\nexport const STICKER_SIZE_DISCUSSION_GROUPS = 140;\nexport const STICKER_SIZE_FOLDER_SETTINGS = 80;\nexport const STICKER_SIZE_INLINE_BOT_RESULT = 100;\nexport const RECENT_STICKERS_LIMIT = 20;\nexport const MEMOJI_STICKER_ID = 'MEMOJI_STICKER';\n\nexport const BASE_EMOJI_KEYWORD_LANG = 'en';\n\nexport const MENU_TRANSITION_DURATION = 200;\nexport const SLIDE_TRANSITION_DURATION = 450;\n\nexport const VIDEO_MOV_TYPE = 'video/quicktime';\n\nexport const SUPPORTED_IMAGE_CONTENT_TYPES = new Set([\n 'image/png', 'image/gif', 'image/jpeg',\n]);\n\nexport const SUPPORTED_VIDEO_CONTENT_TYPES = new Set([\n 'video/mp4', // video/quicktime added dynamically in environment.ts\n]);\n\nexport const CONTENT_TYPES_WITH_PREVIEW = new Set([\n ...SUPPORTED_IMAGE_CONTENT_TYPES,\n ...SUPPORTED_VIDEO_CONTENT_TYPES,\n]);\n\nexport const CONTENT_NOT_SUPPORTED = 'The message is not supported on this version of Telegram.';\n\n// eslint-disable-next-line max-len\nexport const RE_LINK_TEMPLATE = '((ftp|https?):\\\\/\\\\/)?((www\\\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\\\.[a-zA-Z0-9()]{1,63})\\\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)';\nexport const RE_MENTION_TEMPLATE = '(@[\\\\w\\\\d_-]+)';\nexport const RE_TG_LINK = /^tg:(\\/\\/)?([?=&\\d\\w_-]+)?/gm;\nexport const RE_TME_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/)/gm;\n\n// eslint-disable-next-line max-len\nexport const COUNTRIES_WITH_12H_TIME_FORMAT = new Set(['AU', 'BD', 'CA', 'CO', 'EG', 'HN', 'IE', 'IN', 'JO', 'MX', 'MY', 'NI', 'NZ', 'PH', 'PK', 'SA', 'SV', 'US']);\n\n// MTProto constants\nexport const SERVICE_NOTIFICATIONS_USER_ID = '777000';\nexport const REPLIES_USER_ID = '1271266957'; // TODO For Test connection ID must be equal to 708513\nexport const ALL_FOLDER_ID = 0;\nexport const ARCHIVED_FOLDER_ID = 1;\nexport const DELETED_COMMENTS_CHANNEL_ID = '-777';\nexport const MAX_MEDIA_FILES_FOR_ALBUM = 10;\nexport const MAX_ACTIVE_PINNED_CHATS = 5;\nexport const SCHEDULED_WHEN_ONLINE = 0x7FFFFFFE;\nexport const DEFAULT_LANG_CODE = 'en';\nexport const DEFAULT_LANG_PACK = 'android';\nexport const LANG_PACKS = ['android', 'ios', 'tdesktop', 'macos'] as const;\nexport const TIPS_USERNAME = 'TelegramTips';\nexport const LOCALIZED_TIPS = ['ar', 'pt-br', 'id', 'it', 'ko', 'ms', 'pl', 'es', 'tr'];\nexport const FEEDBACK_URL = 'https://bugs.telegram.org/?tag_ids=41&sort=time';\nexport const LIGHT_THEME_BG_COLOR = '#A2AF8E';\nexport const DARK_THEME_BG_COLOR = '#0F0F0F';\nexport const DARK_THEME_PATTERN_COLOR = '#0a0a0a8c';\nexport const DEFAULT_PATTERN_COLOR = 'rgba(90, 110, 70, 0.6)';\n// TODO Get values from `getConfig` method once it's available\nexport const SEEN_BY_MEMBERS_CHAT_MAX = 50;\nexport const SEEN_BY_MEMBERS_EXPIRE = 604680; // One week - 2 min\n\n// Group calls\nexport const GROUP_CALL_VOLUME_MULTIPLIER = 100;\nexport const GROUP_CALL_DEFAULT_VOLUME = 100 * GROUP_CALL_VOLUME_MULTIPLIER;\nexport const ENABLE_THUMBNAIL_VIDEO = false;\n","type Scheduler =\n typeof requestAnimationFrame\n | typeof onTickEnd\n | typeof runNow;\n\nexport function debounce(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n shouldRunLast = true,\n) {\n let waitingTimeout: number | undefined;\n\n return (...args: Parameters) => {\n if (waitingTimeout) {\n clearTimeout(waitingTimeout);\n waitingTimeout = undefined;\n } else if (shouldRunFirst) {\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n waitingTimeout = self.setTimeout(() => {\n if (shouldRunLast) {\n fn(...args);\n }\n\n waitingTimeout = undefined;\n }, ms);\n };\n}\n\nexport function throttle(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n) {\n let interval: number | undefined;\n let isPending: boolean;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n isPending = true;\n args = _args;\n\n if (!interval) {\n if (shouldRunFirst) {\n isPending = false;\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n interval = self.setInterval(() => {\n if (!isPending) {\n // eslint-disable-next-line no-restricted-globals\n self.clearInterval(interval!);\n interval = undefined;\n return;\n }\n\n isPending = false;\n fn(...args);\n }, ms);\n }\n };\n}\n\nexport function throttleWithRaf(fn: F) {\n return throttleWith(fastRaf, fn);\n}\n\nexport function throttleWithPrimaryRaf(fn: F) {\n return throttleWith(fastRafPrimary, fn);\n}\n\nexport function throttleWithTickEnd(fn: F) {\n return throttleWith(onTickEnd, fn);\n}\n\nexport function throttleWithNow(fn: F) {\n return throttleWith(runNow, fn);\n}\n\nexport function throttleWith(schedulerFn: Scheduler, fn: F) {\n let waiting = false;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n args = _args;\n\n if (!waiting) {\n waiting = true;\n\n schedulerFn(() => {\n waiting = false;\n fn(...args);\n });\n }\n };\n}\n\nexport function onIdle(cb: NoneToVoidFunction, timeout?: number) {\n // eslint-disable-next-line no-restricted-globals\n if (self.requestIdleCallback) {\n // eslint-disable-next-line no-restricted-globals\n self.requestIdleCallback(cb, { timeout });\n } else {\n onTickEnd(cb);\n }\n}\n\nfunction runNow(fn: NoneToVoidFunction) {\n fn();\n}\n\nexport const pause = (ms: number) => new Promise((resolve) => {\n setTimeout(() => resolve(), ms);\n});\n\nexport function rafPromise() {\n return new Promise((resolve) => {\n fastRaf(resolve);\n });\n}\n\nlet fastRafCallbacks: NoneToVoidFunction[] | undefined;\nlet fastRafPrimaryCallbacks: NoneToVoidFunction[] | undefined;\n\n// May result in an immediate execution if called from another `requestAnimationFrame` callback\nexport function fastRaf(callback: NoneToVoidFunction, isPrimary = false) {\n if (!fastRafCallbacks) {\n fastRafCallbacks = isPrimary ? [] : [callback];\n fastRafPrimaryCallbacks = isPrimary ? [callback] : [];\n\n requestAnimationFrame(() => {\n const currentCallbacks = fastRafCallbacks!;\n const currentPrimaryCallbacks = fastRafPrimaryCallbacks!;\n fastRafCallbacks = undefined;\n fastRafPrimaryCallbacks = undefined;\n currentPrimaryCallbacks.forEach((cb) => cb());\n currentCallbacks.forEach((cb) => cb());\n });\n } else if (isPrimary) {\n fastRafPrimaryCallbacks!.push(callback);\n } else {\n fastRafCallbacks.push(callback);\n }\n}\n\nexport function fastRafPrimary(callback: NoneToVoidFunction) {\n fastRaf(callback, true);\n}\n\nlet onTickEndCallbacks: NoneToVoidFunction[] | undefined;\nlet onTickEndPrimaryCallbacks: NoneToVoidFunction[] | undefined;\n\nexport function onTickEnd(callback: NoneToVoidFunction, isPrimary = false) {\n if (!onTickEndCallbacks) {\n onTickEndCallbacks = isPrimary ? [] : [callback];\n onTickEndPrimaryCallbacks = isPrimary ? [callback] : [];\n\n Promise.resolve().then(() => {\n const currentCallbacks = onTickEndCallbacks!;\n const currentPrimaryCallbacks = onTickEndPrimaryCallbacks!;\n onTickEndCallbacks = undefined;\n onTickEndPrimaryCallbacks = undefined;\n currentPrimaryCallbacks.forEach((cb) => cb());\n currentCallbacks.forEach((cb) => cb());\n });\n } else if (isPrimary) {\n onTickEndPrimaryCallbacks!.push(callback);\n } else {\n onTickEndCallbacks.push(callback);\n }\n}\n\nexport function onTickEndPrimary(callback: NoneToVoidFunction) {\n onTickEnd(callback, true);\n}\n\nlet beforeUnloadCallbacks: NoneToVoidFunction[] | undefined;\n\nexport function onBeforeUnload(callback: NoneToVoidFunction, isLast = false) {\n if (!beforeUnloadCallbacks) {\n beforeUnloadCallbacks = [];\n // eslint-disable-next-line no-restricted-globals\n self.addEventListener('beforeunload', () => {\n beforeUnloadCallbacks!.forEach((cb) => cb());\n });\n }\n\n if (isLast) {\n beforeUnloadCallbacks.push(callback);\n } else {\n beforeUnloadCallbacks.unshift(callback);\n }\n\n return () => {\n beforeUnloadCallbacks = beforeUnloadCallbacks!.filter((cb) => cb !== callback);\n };\n}\n","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, DEBUG_MORE } 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_MORE) {\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/87.77459230580aafa8639a.css b/dist/87.74a4d72480e8214a0dde.css similarity index 99% rename from dist/87.77459230580aafa8639a.css rename to dist/87.74a4d72480e8214a0dde.css index c59e19bd..3d3f689a 100644 --- a/dist/87.77459230580aafa8639a.css +++ b/dist/87.74a4d72480e8214a0dde.css @@ -35,4 +35,4 @@ #RightColumn{position:absolute;top:0;right:0;width:var(--right-column-width);height:100%;transform:translate3d(var(--right-column-width), 0, 0);background:var(--color-background);border-left:1px solid var(--color-borders);z-index:var(--z-right-column);transition:transform var(--layer-transition)}body.animation-level-0 #RightColumn{transition:none}#RightColumn:not(:hover) .chat-item-clickable:not(.picker-list-item):nth-child(n+18){display:none !important}@media(max-width: 1275px){#RightColumn{box-shadow:0 .25rem .5rem .125rem var(--color-default-shadow);border-left:none}}@media(max-width: 600px){#RightColumn{width:100vw;transform:translate3d(110vw, 0, 0)}}@supports(padding-right: env(safe-area-inset-right)){#RightColumn{padding-right:env(safe-area-inset-right)}}#RightColumn>.Transition{height:calc(100% - var(--header-height));overflow:hidden}#RightColumn .Management .section>.ChatInfo{padding:0 1.5rem;margin:1rem 0;text-align:center}#RightColumn .Management .section>.ChatInfo .Avatar{margin:0 auto .5rem}#RightColumn .Management .section>.ChatInfo .Avatar.no-photo{cursor:default !important}#RightColumn .Management .section>.ChatInfo .title{display:flex;justify-content:center;align-items:center}#RightColumn .Management .section>.ChatInfo .title h3{font-weight:500;font-size:1.25rem;line-height:2rem;white-space:pre-wrap;word-break:break-word}#RightColumn .Management .section>.ChatInfo .title .VerifiedIcon{margin-left:.25rem;margin-bottom:.5rem}#RightColumn .Management .section>.ChatInfo .title .emoji{width:1.5rem;height:1.5rem;background-size:1.5rem}#RightColumn .Management .section>.ChatInfo .status{font-size:.875rem;color:#868e96}#RightColumn-wrapper{position:absolute;top:0;left:0;right:0;bottom:0;z-index:var(--z-right-column);overflow:hidden;visibility:hidden;pointer-events:none}@media(max-width: 1275px){#RightColumn-wrapper{position:fixed}}#RightColumn-wrapper.is-hidden{display:none}#RightColumn-wrapper .overlay-backdrop{position:absolute;top:0;right:0;bottom:0;left:0;z-index:-1;background:#000;opacity:0}@media(max-width: 600px){#RightColumn-wrapper .overlay-backdrop{transition:opacity var(--layer-transition)}body.animation-level-0 #RightColumn-wrapper .overlay-backdrop{transition:none}}#Main.right-column-open #RightColumn-wrapper,body.animating-right-column #RightColumn-wrapper{visibility:visible}@media(max-width: 600px){#Main.right-column-open #RightColumn-wrapper .overlay-backdrop{opacity:var(--layer-blackout-opacity)}}#Main.right-column-open #RightColumn-wrapper #RightColumn{pointer-events:auto;transform:translate3d(0, 0, 0)} #Main{height:100%;text-align:left;overflow:hidden}@media(min-width: 1276px){#Main{position:relative}}@media(max-width: 600px){#Main{height:calc(var(--vh, 1vh) * 100)}}@media(min-width: 926px){#Main{display:grid;grid-template-columns:auto 1fr;grid-template-rows:100%}}.has-group-call-header{--group-call-header-height: 2rem}.has-group-call-header #LeftColumn,.has-group-call-header #MiddleColumn,.has-group-call-header #RightColumn-wrapper{height:calc(100% - 2rem);margin-top:2rem}#LeftColumn{min-width:12rem;width:33vw;max-width:26.5rem;height:100%;position:relative}#LeftColumn>div{height:100%;overflow:hidden}@media(max-width: 600px){#LeftColumn{height:calc(var(--vh, 1vh) * 100)}}@media(min-width: 926px){#LeftColumn{max-width:40vw}}@media(min-width: 1276px){#LeftColumn{width:25vw;max-width:33vw}}@media(max-width: 925px){#LeftColumn{position:fixed;left:0;top:0;height:calc(var(--vh, 1vh) * 100);width:26.5rem !important;transform:translate3d(-5rem, 0, 0);transition:transform var(--layer-transition)}body.animation-level-0 #LeftColumn{transition:none}#LeftColumn::after{content:"";display:block;position:absolute;left:0;top:0;right:0;bottom:0;background:#000;opacity:var(--layer-blackout-opacity);transition:opacity var(--layer-transition);z-index:1}body.animation-level-0 #LeftColumn::after{transition:none}body.is-android #LeftColumn::after{display:none}body.is-android .middle-column-shown #LeftColumn::after{display:block}#Main:not(.middle-column-open) #LeftColumn{transform:translate3d(0, 0, 0)}#Main:not(.middle-column-open) #LeftColumn::after{opacity:0;pointer-events:none}#Main.history-animation-disabled #LeftColumn{transition:none}#Main.history-animation-disabled #LeftColumn:after{transition:none}}@media(max-width: 600px){#LeftColumn{max-width:none;width:100vw !important;transform:translate3d(-20vw, 0, 0)}@supports(left: env(safe-area-inset-left)){#LeftColumn{left:env(safe-area-inset-left) !important;width:calc(100vw - env(safe-area-inset-left))}}}@media(max-width: 600px){#RightColumn{height:calc(var(--vh, 1vh) * 100 + 1px)}}#Main.history-animation-disabled #RightColumn{transition:none}#Main.history-animation-disabled #RightColumn .overlay-backdrop{transition:none}#Main.history-animation-disabled .overlay-backdrop{transition:none}#MiddleColumn{border-left:1px solid var(--color-borders)}@media(max-width: 925px){#MiddleColumn{max-width:none;position:fixed;left:0;top:0;bottom:0;right:0;transform:translate3d(0, 0, 0);transition:transform var(--layer-transition)}body.animation-level-0 #MiddleColumn{transition:none}#Main:not(.middle-column-open) #MiddleColumn{transform:translate3d(26.5rem, 0, 0)}}@media(max-width: 600px){#MiddleColumn{border-left:none}#Main:not(.middle-column-open) #MiddleColumn{transform:translate3d(100vw, 0, 0)}#Main.right-column-open #MiddleColumn{transform:translate3d(-20vw, 0, 0)}}#Main.history-animation-disabled #MiddleColumn{transition:none}#Main.history-animation-disabled #MiddleColumn:after{transition:none}body.is-android.animation-level-1{--layer-transition: 250ms ease-in-out}body.is-android.animation-level-1 #LeftColumn,body.is-android.animation-level-1 #MiddleColumn,body.is-android.animation-level-1 #RightColumn{transition:transform var(--layer-transition),opacity var(--layer-transition)}body.is-android.animation-level-1 #Main:not(.middle-column-shown) #MiddleColumn{display:none}body.is-android.animation-level-1 #Main:not(.middle-column-open) #MiddleColumn{transform:translate3d(10vw, 0, 0);opacity:0}body.is-android.animation-level-1 #Main.middle-column-open #LeftColumn{transform:translate3d(0, 0, 0);opacity:0}body.is-android.animation-level-1 #Main:not(.right-column-shown) #RightColumn{display:none}body.is-android.animation-level-1 #Main:not(.right-column-open) #RightColumn{transform:translate3d(10vw, 0, 0);opacity:0}body.is-android.animation-level-1 #Main.right-column-open #MiddleColumn{transform:translate3d(0, 0, 0);opacity:0} -/*# sourceMappingURL=87.77459230580aafa8639a.css.map*/ \ No newline at end of file +/*# sourceMappingURL=87.74a4d72480e8214a0dde.css.map*/ \ No newline at end of file diff --git a/dist/87.77459230580aafa8639a.css.map b/dist/87.74a4d72480e8214a0dde.css.map similarity index 99% rename from dist/87.77459230580aafa8639a.css.map rename to dist/87.74a4d72480e8214a0dde.css.map index 926ceb31..53b14e89 100644 --- a/dist/87.77459230580aafa8639a.css.map +++ b/dist/87.74a4d72480e8214a0dde.css.map @@ -1 +1 @@ -{"version":3,"file":"87.77459230580aafa8639a.css","mappings":"AAEA,gBACE,kBAEA,oCACE,kBAEA,2HACE,eACA,eACA,sBACA,6CACA,0BACA,oBAGF,uFACE,kBACA,OACA,WAGF,4CACE,eAGF,2CACE,aAGF,+CACE,yBAEA,uDACE,qEAGF,sDACE,qEAIJ,iDACE,gBAEA,iHACE,gBAKN,gCACE,iBACA,cACA,iBACA,6BACA,qBACA,iBACA,WACA,kBACA,mBACA,gBACA,kBACA,cAGF,0CACE,cACA,kBAGF,8BACE,gBACA,2CAEA,gBCpEF,+BDgEA,8BC/DE,mBAGA,mBDsEA,wIACE,2B;AEnFN,iBACE,cACA,aACA,mBACA,qBACA,eACA,+BACA,2CAEA,0BACE,wBAGF,6BACE,gCACA,gBACA,iBACA,6BACA,mBAGF,yBACE,6BACE,6B;ACvBN,eACE,kBACA,WACA,YACA,2BAEA,4DAEA,sCACE,0BACA,UAEA,wBAEA,+CACE,UAIJ,wBACE,wBAEA,yBAHF,wBAKI,kCACA,6BAKF,oCACE,WACA,cACA,kBACA,WACA,YACA,YACA,aACA,WAKF,6CACE,kBACA,YACA,aACA,WACA,cAKF,gFAEE,kBAIA,0DACE,iCAGF,gDACE,0CAKF,0CACE,iCAGF,oDACE,0C;AC1ER,iBACE,YACA,kBACA,aACA,sBACA,gBACA,UAEA,2CACE,kBACA,YACA,WAGF,6BACE,OACA,gBACA,gCAEA,uCACE,8BAIJ,8BACE,YACA,aACA,sBACA,gBAEA,gDACE,gBACA,6BAEA,2DACE,SAIJ,uCACE,2BACA,sBACA,mBACA,gBACA,UAGF,mCACE,cACA,qBACA,sBAEA,wCACE,mBACA,oBAIJ,0CACE,OACA,gBAIJ,+FACE,YACA,gBAGF,6BACE,kBACA,YACA,UACA,WACA,c;AC1EJ,SACE,YAGF,aACE,4BACA,oCACA,aACA,mBACA,cACA,yCAEA,gBACE,gBACA,kBACA,gBACA,qBACA,kBAGF,0BACE,oBACA,+BAEA,yBAJF,0BAKI,6BAIJ,yBAzBF,aA0BI,eAGF,6BACE,aACA,cAEA,2CACE,mB;ACtCN,aACE,aACA,iBACA,oBACA,uBAEA,oCACE,2BAGF,qBACE,cACA,eAGF,4BACE,6CACA,2DACA,0CACA,2CAIA,oCACE,WACA,YAEA,sCACE,mBACA,qBAIJ,8BACE,kBACA,oBACA,oBAEA,wCACE,kBAIJ,+EACE,UACA,mBACA,uEAGF,yLAIE,UACA,qBAIJ,4BACE,kBACA,iBAEA,kDACE,kBACA,2BACA,SACA,YACA,WACA,eACA,kBAGF,gHACE,mBAGF,2CACE,UACA,kBAEA,kBACA,mCACA,aACA,2BACA,8DACA,WACA,eACA,oBACA,eACA,iDAEA,wDACE,gBACA,0EACE,gBAKN,yKAGE,UACA,mBAKF,sCACE,6CAGF,qDACE,iCACA,iBACA,iBACA,iBACA,sBACA,sBACA,kCAIJ,qBACE,aACA,uBACA,sBACA,cACA,gBACA,kBACA,gBACA,eACA,kDAEA,2BACE,wDAGF,iDAfF,qBAgBI,iBAGF,yCACE,cACA,gBACA,6BACA,iBACA,mBACA,gBACA,uBAEA,qDACE,8BACA,qBAIJ,+BACE,4BACA,kCACA,mBACA,mBACA,gBACA,uBACA,mBAEA,2CACE,8BACA,qB;ACxKR,kBACE,kBACA,SACA,OACA,QACA,gBACA,gBACA,+CACA,aACA,mBACA,8BACA,mBACA,qCACA,mCACA,WACA,eAEA,0BACE,WACA,cACA,kBACA,eACA,OACA,QACA,eACA,uDAGF,4BACE,aAGF,yBACE,oCACE,2BAIJ,wBACE,aACA,sBAEA,+BACE,kBACA,wBAGF,sCACE,iBACA,kCAIJ,2BACE,aACA,mBACA,mBAEA,mCACE,sBAEA,+CACE,WACA,YAGF,qDACE,cACA,eACA,6CAKN,wBACE,cACA,qBACA,gBACA,kBACA,WAKJ,0BACE,wDACE,8C;ACPJ,cACE,aACA,mBACA,WACA,+CACA,mCACA,oCACA,kBACA,+BAEA,mDAVF,cAWI,oDACA,yDAGF,yBAfF,cAgBI,cACA,kBAEA,mDAnBJ,cAoBM,mDACA,uDAIJ,0BACE,WAGA,YAEA,8BACE,aACA,mBACA,WAIJ,2BACE,oBACA,mBACA,kBAEA,yBALF,2BAMI,eAGF,yCACE,kBACA,eACA,kBACA,sBACA,iBACA,oBACA,gBACA,kBAEA,kBACA,aACA,cAEA,6BACA,WACA,oBAEA,gDACE,gCAKN,iCACE,YACA,gBAGF,kEACE,2BAGF,4BACE,aACA,mBACA,yBACA,iBACA,cAGE,qLAGE,2BAIJ,iDACE,2CACE,+BACA,6CAEA,mEACE,mEAKN,0BA1BF,4BA2BI,+BACA,6CAEA,oDACE,mEP5LN,oIOkMI,oBAIJ,iDACE,8GAEE,UAEA,8JACE,WA3MN,4HAEE,kBACA,SACA,OACA,QACA,gBACA,uDAEA,aACA,2BACA,sBACA,oBACA,mCAEA,4IACE,WACA,cACA,kBACA,eACA,OACA,QACA,eACA,uDAGF,sKACE,gBACA,sBAGF,mDA/BF,4HAgCI,qDACA,uDAIJ,sDACE,mBACA,aACA,qBAEA,8DACE,gBACA,YAGF,8DACE,sBAGF,oEACE,iBAIJ,8DACE,YACA,cACA,iBAEA,sEACE,YACA,eAGF,4EACE,eAIJ,iFACE,aA2IA,0BACE,iEACE,wDAKN,oHAEE,mDAEA,kKACE,eAIJ,iBACE,gBACA,mBACA,qBACA,gBACA,SACA,gBACA,uBACA,uBAEA,4DAEE,oBACA,gBAGF,yBAhBF,iBAiBI,cACA,gBACA,wBAGF,0BACE,yCACE,kDAKN,wBACE,eACA,aACA,mBAEA,8BACE,aACA,sBACA,uBACA,YACA,gBAGF,+BACE,aACA,mBAEA,6CACE,cACA,eACA,mBACA,kBAIJ,gCACE,aACA,uBAGF,qCACE,uBACA,gBACA,uBAEA,0BACE,6DACE,kDAMR,sBACE,qBAEA,wBACA,yBACA,oBAGF,mDACE,kBACA,qBACA,SACA,kCACA,gBACA,mBACA,uBACA,qBAEA,uEACE,oBAGF,iEACE,2BAGF,2EACE,iBAIJ,8BACE,aACA,cAGF,2CACE,aACA,mBACA,iBACA,eACA,2BACA,mCAGE,oFACE,aAIJ,0BAdF,2CAeI,+BACA,+DAEA,mEACE,mEAKJ,gEACE,gBAGF,mDACE,cAGF,sDACE,kBACA,OACA,QACA,SACA,mCACA,oCACA,uDACA,+BACA,+DAEA,8DACE,WACA,cACA,kBACA,eACA,OACA,QACA,eACA,uDAGF,2EACE,aACA,gBACA,OAEA,yFACE,eAIJ,0BAhCF,sDAiCI,+BACA,+DAEA,8EACI,qDAMV,mCACE,aACA,cACA,oBACA,uBACA,eACA,qBACA,kDACA,kBACA,gBACA,eAEA,yCACE,wDAGF,0DACE,kBACA,eACA,iBACA,cACA,kBACA,gBAEA,2FACE,eACA,cACA,uBACA,gCAGF,yFACE,8CACA,kBACA,sBACA,sCAGF,sFACE,kBACA,OACA,MACA,cACA,gCACA,uBACA,sBACA,sCAIJ,iDACE,gBACA,4BACA,mBACA,gBAEA,iDANF,iDAOI,iBAGF,wDACE,gBACA,kBACA,iBACA,YACA,2BACA,sBACA,gBACA,mBAEA,oEACE,mBAIJ,mDACE,kBACA,qBACA,gBACA,mBACA,gBACA,uBACA,SAEA,+DACE,mBAKN,gDACE,WACA,YAGF,uCACE,cACA,eACA,iBACA,qBACA,4BACA,mBACA,cAEA,qDACE,gBAKN,6BACE,cACA,iBACA,aACA,mBACA,yBAGE,8DACE,2BACA,UAMJ,wFACE,mBAEA,kGACE,qBAKN,yBAjiBA,sEAEE,kBACA,SACA,OACA,QACA,gBACA,uDAEA,aACA,2BACA,sBACA,oBACA,mCAEA,sFACE,WACA,cACA,kBACA,eACA,OACA,QACA,eACA,uDAGF,gHACE,gBACA,sBAGF,mDA/BF,sEAgCI,qDACA,uDAIJ,2BACE,mBACA,aACA,qBAEA,mCACE,gBACA,YAGF,mCACE,sBAGF,yCACE,iBAIJ,mCACE,YACA,cACA,iBAEA,2CACE,YACA,eAGF,iDACE,eAIJ,sDACE,cA8dJ,mBACE,KACE,UAEF,GACE,W;AC9iBJ,iBACE,aACA,mBACA,yDACA,qBACA,2BACA,0CACA,kDACA,kBACA,gBACA,eACA,cAGE,0DACE,aAIJ,+BACE,gBACA,cACA,SACA,yCACA,iDAEA,uCACE,aACA,YACA,eAGF,+CACE,0BAGF,wCACE,cAIJ,yBACE,WACA,cACA,kBACA,aACA,gBACA,cACA,UACA,+BACA,kBAGF,uBACE,oCAGF,wBACE,qCAGF,gCACE,yDAGF,+BACE,gBACA,0BACA,aACA,8BAEA,8CACE,mBACA,gBACA,uBACA,sBACA,OACA,cAGF,iCACE,mBACA,gBACA,uBACA,gBACA,gBACA,OAEA,wCACE,aACA,aAIJ,sCACE,8DACA,+DACA,sCAIJ,0CACE,0BACA,YAGF,iCACE,WACA,YACA,iBACA,qBACA,mBACA,cAEA,uCACE,mBAIJ,8BACE,8BACA,gCACA,aACA,+BACA,uBACA,WACA,qCACA,sDAEA,sCACE,gBAGF,8CACE,oBAGF,4CACE,4BAGF,6CACE,gBACA,0B;AC/IN,aACE,kBACA,eACA,SACA,QACA,aACA,mBACA,gCACA,sBACA,iBACA,WACA,eACA,eACA,gEAEA,uFAGE,iBACA,mBAGF,2BACE,sBAIA,uCACE,oBAIJ,4BACE,6BAGF,gCACE,gBACA,uBACA,qBAGF,gCACE,oBACA,qBACA,mBACA,kBACA,eAGF,mCACE,6CACA,gBAGF,mEAEE,0BACA,0BACA,sBACA,sBACA,UACA,cACA,aACA,UACA,gBACA,6BAEA,qHACE,uBAIJ,qFAEE,sBACA,YACA,6BAGF,+GAEE,cAGF,4CACE,eACA,eAGF,yBACE,QAGF,gDACE,oCAGF,oCACE,uBACA,oBACA,sBAEA,iDACE,8BAIJ,6DACE,gBAGF,kEACE,iBAIA,qCACE,SAEF,yCACE,QAMJ,6DACE,WACA,aACA,cAGF,6DACE,YAGF,6DACE,YAGF,6DACE,Y;AC7IF,wBACE,eAGF,kBACE,oB;ACNJ,SACE,aACA,mBACA,eAEA,qBACE,eAGF,iBACE,mBAGF,uBACE,cACA,eACA,mBACA,gBAEA,qCACE,eACA,iBACA,qBACA,gBAGF,sCACE,iBACA,6B;AC5BN,YACE,aACA,qBACA,qBAEA,uBACE,gBAGF,8BACE,sBAGF,+BACE,kBACA,mBACA,cACA,wBACA,cACA,gBACA,kBACA,iBAEA,2CACE,oBACA,uBACA,iBAIJ,gCACE,kBACA,QACA,YACA,WACA,YACA,+BACA,8BACA,oBACA,iBACA,kBAEA,sCACE,8BAGF,gDACE,gBAGF,wCACE,UACA,qCACA,qBACA,uBACA,6BAIJ,+BACE,YACA,mBAGF,gCACE,kBAGF,8BACE,kBACA,QACA,cACA,gBACA,sBACA,iBACA,+BAEA,qBACA,yBACA,sBAIF,uBACE,WACA,YACA,kBACA,WACA,YACA,sDACA,oBACA,wBAGF,4BACE,iBACA,qBACA,2BACA,UAIA,qCACE,8BAGF,mCACE,0BAKN,iCACE,aACA,gB;AClHF,MACE,gBACA,mBAEA,yBAJF,MAKI,gBAGF,qBACE,gBACA,oBACA,iBACA,sBAGF,0CAEE,6BACA,kBAGF,iBACE,oBACA,aACA,mBACA,oBAGF,yBACE,2BACA,kBAGF,oBACE,mBACA,oBAGF,6BAEE,qBAEA,mDACE,qBAGF,+CACE,qBACA,mBAKA,gJACE,aACA,yCAEA,gMACE,4CAGF,oMACE,qCAIJ,4IACE,cACA,qCAMF,wMACE,iCAIJ,+CACE,aAMA,sCACE,aACA,sCAEA,mDACE,qCAMR,mBAEE,0CAEA,+BACE,2CAGF,gCAEE,2CACA,4CACE,2CAKN,0BACE,oBACA,mBACA,2BACA,oBACA,mBACA,gBAEA,kCACE,yCACA,eACA,uBAEA,+CACE,6CAGF,oDACE,iBAKN,sBACE,iBACA,iBACA,qBAEA,+BACE,yBAEA,wDACE,0BAIJ,0BACE,oBAIJ,+BACE,4BACA,iBACA,eACA,qBACA,2CAGF,sBACE,kCACA,yCACE,2BAIJ,wCAEE,mBACA,qBAGF,cACE,oBACA,eAEA,2BACE,0BACA,mDAIJ,cACE,sB;AC3LJ,SACE,kBACA,sBACA,qBACA,yDACA,qBACA,gBACA,kBAEA,iBACE,WACA,cACA,kBACA,MACA,SACA,OACA,cACA,+BACA,sBAGF,cACE,aACA,sBACA,uBAGF,sBACE,oBACA,iCAEA,sFACE,6DAGF,mCACE,WACA,YACA,aACA,2BAEA,uCACE,WACA,YAKN,iCACE,4BACA,8BAGF,2BACE,aACA,mBAEA,yCACE,QACA,mBAGF,wCACE,QACA,cAIA,kDACE,wBASF,kMACE,WACA,qBACA,iCACA,cACA,YAKN,oEAGE,sBACA,eAGF,oBACE,0BACA,gBACA,sBAGF,qBACE,gBACA,sBAGF,2BACE,iBACA,gBAEA,uCACE,qBAIJ,kBACE,6BAEA,0BACE,UACA,Q;ACvHJ,gBACE,0BACA,gBAGF,sBACE,kBAGE,+CACE,eACA,aAEA,yBAJF,+CAKI,cAIJ,kDACE,kBACA,MACA,qBACA,cACA,oCACA,kDACA,wBACA,gBAEA,uDACE,kB;AC9BV,OACE,kBACA,gBAEA,mCACE,mCAGF,0BACE,sBAEA,sDACE,oBACA,qCACA,sCAMF,0HACE,oBAKF,uJACE,2BACA,iB;AC5BN,YACE,kBACA,YACA,aACA,eAEA,+BACE,YACA,aACA,kBACA,gBAGF,2BACE,kBACA,OACA,MACA,kBACA,gBAGF,sBACE,kBACA,MACA,OACA,WACA,YACA,oBAGF,6BACE,YACA,iBACA,eACA,mBACA,qBAGF,kKAGE,a;ACzCJ,eACE,aACA,sBAEA,oBACE,aACA,mBAGF,uBACE,OACA,WACA,eACA,gCACA,kDACA,gBACA,oBAEA,+BACE,WACA,oCACA,UAEA,kBACA,MACA,OACA,QACA,SACA,kDACA,uBACA,yBAGF,6BACE,2CAEA,qCACE,WAIJ,qCACE,cAGF,oCACE,eAGF,yBACE,kBACA,kBACA,eACA,aACA,cAEA,0CACE,iBACA,YACA,cACA,yBAKN,0CACE,6BAGF,yCACE,gBAEA,uDACE,wDAGF,sDACE,yD;AC7EN,eACE,4CACA,uCAEA,aACA,WACA,mBACA,yCACA,6BACA,0BACA,mCACA,6DACA,2DACA,mBACA,gBACA,iBACA,0BACA,mBACA,eACA,4CACA,gEAEA,sCACE,2BAGF,8CACE,WACA,cACA,kBACA,kBACA,gBACA,eACA,eACA,gCACA,yDACA,UACA,oCAEA,gEACE,oBAGF,qEACE,2BAIJ,6BACE,kBACA,YACA,cACA,YACA,gBACA,uBACA,gCACA,uBACA,WACA,gCAEA,UACA,4BAEA,wBAfF,6BAgBI,sBAGF,mCACE,iCAGF,4CACE,UAGF,oCACE,uBACA,kBACA,kBACA,OACA,WACA,kBACA,eACA,cAGF,2CACE,eACA,kDACE,aAIJ,oDACE,cACA,iBACA,cAGF,sKAIE,aAIJ,qBACE,8BAEA,oDACE,UAGF,6BACE,2CAIJ,mHAKE,0CAGF,qDACE,iCAGF,sCACE,sBAGF,sCACE,yBAGF,6OAKE,wBAGF,sCACE,aAGF,8BACE,oBACA,iBACA,0BAGF,0BACE,yBACA,iBAGF,gCACE,oBACA,mBACA,wBACA,8BAEA,wCACE,uBACA,yCACA,oBACA,UACA,gBAEA,+CACE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,gBAEA,mEACE,oBAGF,4EACE,uCACA,wCAOA,wPACE,gBAEA,sQACE,WACA,cACA,eACA,sBACA,gBACA,oCACA,kBASA,kSACE,mCACA,qCAEA,gTACE,mCACA,2CAaV,4OACE,4CAIA,4PACE,yDACA,gDAKN,uDACE,iBAGF,+CACE,qDAIA,2DACE,aACA,yBAEA,4EACE,WAMR,oCACE,kBAEA,4DACE,kBACA,UAIJ,iCACE,kBACA,OACA,cACA,aACA,cACA,sBACA,kBACA,wCAEA,aACA,mBACA,uBAEA,WACA,eAEA,UACA,oBACA,4CAEA,8CACE,kBACA,UACA,SACA,mBAGF,6CACE,uBAIJ,iBACE,mBAIA,wDACE,gCAIA,+EACE,gCAKF,gFACE,6BAOR,sKAME,qDACA,uDACA,2DACA,6DAGF,8BACE,kCAGF,aACE,gBAEA,6BACE,2BAIJ,SACE,wDACA,yDACA,2DACA,4DAGE,sDACE,iEAGF,4DACE,8DACA,iEAGF,sDACE,8DAGF,iCACE,iEAEA,+DACE,+BAMJ,gDACE,kEAGF,sDACE,+DACA,kEAGF,gDACE,+DAGF,2BACE,kEAEA,yDACE,gCACA,6BAQF,wNAEE,+BACA,gCAKF,gLAGE,mBAIJ,+QAIE,4BACA,6BAGF,qEACE,qBAIJ,gCACE,kBACA,SACA,WACA,gCAEA,UACA,4BAEA,wBATF,gCAUI,sBAGF,mHAGE,4CAMF,oGACE,UAIJ,oCACE,WAGF,0CACE,YAGF,wBACE,WACA,UACA,kBAIJ,8CACE,cCvmBF,iBACE,kBACA,2BAEA,yBAJF,iBAKI,gCAEA,uEAEE,gCAIF,kDAbJ,iBAcM,sCACA,yCACE,sCAEF,8BACE,uCAIJ,mCACE,6BAEA,2GAEE,+BAIF,iDATF,mCAUI,mCACA,2DACE,qCAEF,gDACE,uCAMR,qBACE,2BACA,yBAGF,+BACE,SACA,sBACA,mBACA,mBACA,kBACA,uBAGF,mCACE,uBAKA,sGACE,kBACA,YACA,uBACA,YACA,iBACA,8CACA,qBACA,qBAEA,4KACE,kDACA,gBAGF,0KACE,WAGF,0KACE,aAGF,oVAEE,UAGF,0KACE,aAKF,wHACE,WACA,qBACA,sBAMJ,4CACE,WACA,cACA,WAGF,kDACE,oBACA,0BACA,oBAEA,iEACE,oBAMJ,4DACE,qCAEA,kEACE,gCAKN,oCACE,yCAEA,gDACE,8CAGF,mDACE,YAIJ,0CACE,mBACA,qBACA,kBAGF,gCACE,mBACA,gBACA,uBACA,yDACA,gBACA,oBACA,0BACA,uBACA,aAEA,6CACE,gBACA,uBAGF,yFACE,eAEA,qGACE,YAIJ,yCACE,0BAGF,yCACE,0BAGF,yCACE,0BAGF,yCACE,0BAGF,yCACE,0BAGF,yCACE,0BAGF,yCACE,0BAGF,kEACE,0BAGF,sCACE,kBAGF,qCACE,qBACA,gBAGF,0CACE,oBAGF,6CACE,OACA,iBACA,iBACA,gBACA,iBACA,mBACA,6CAEA,0DACE,0BAKN,4BACE,iDAGF,iGACE,mCAGF,sCACE,+BAEA,yGACE,WACA,qBACA,iCACA,YAIJ,kDACE,wBAGF,+DACE,qBAGF,kDACE,aAGF,+BACE,gBACA,kBACA,kBACA,eACA,gBACA,0BAEA,uCACE,6BAGF,4CACE,gBAGF,kDACE,eAKF,iEACE,wBAMA,2DACE,yBACA,UACA,8BAKN,0BACE,yBAGE,4CACE,kDAIJ,8CACE,oBAMF,8IAEE,sBACA,uBAIJ,uBACE,yBAEA,4CACE,iBAIJ,uBACE,gBACA,wCAEA,yBAJF,uBAKI,iBAGF,4CACE,kBAIA,8DACE,yBAKN,2CACE,qBACA,cACA,wBACA,kBACA,sBACA,2BAEA,sDACE,wDACA,kBAIJ,yDACE,kDACA,mDACA,4DAGF,mCACE,4BACA,6BAGF,yCACE,6BAEA,uEACE,oBACA,kBACA,YACA,4BACA,8BACA,gBACA,yCACA,4CAEA,oFACE,kBAIJ,sDACE,mBAOJ,0DACE,aACA,uBACA,mBAEA,kFACE,eAEA,wGACE,yBAKN,8DACE,sBAGF,gdAME,oBACA,qBAEA,4vBACE,sBAIJ,oEACE,sBAGF,sTAIE,mBACA,wBAEA,8fACE,yBAKJ,4HAEE,sBAEA,gOACE,sBAIJ,8DACE,aACA,mBACA,uBAEA,oFACE,WACA,mBACA,+CAIJ,gIACE,kBACA,aACA,mBACA,uBACA,WACA,WACA,yBAEA,wJACE,UAGF,4JACE,aACA,mBACA,uBACA,eACA,gBACA,kBACA,2BAGF,4MACE,6BAEA,wPACE,UAKN,8DACE,iBAGF,kEACE,iBAGF,sKAEE,2BACA,WACA,iBACA,kBACA,cACA,aACA,UACA,kBACA,qBACA,qBACA,gEAGF,wGACE,0BACA,oBACA,oBAIJ,8BACE,gBACA,gBACA,aACA,eACA,qBAEA,2CACE,mBACA,wBAEA,uDACE,kBAIJ,uCACE,eAGF,6CACE,aACA,uBACA,2BACA,cAEA,+CACE,gBAGF,8DACE,kBACA,4CAEA,yBAJF,8DAKI,8BAGF,yBARF,8DASI,kBACA,UACA,8BAKN,4CACE,mBAGF,2CACE,cACA,eACA,cAEA,uDACE,MACA,OACA,SACA,QAIJ,qCACE,qBACA,kBAEA,gDACE,wDACA,kBAKF,uDACE,gBACA,4EACA,iEACE,+HAGF,oEACE,iBAKN,2CACE,eACA,iBAEA,0DACE,YAGF,yDACE,gBACA,kBAGF,+DACE,gBAGF,kDACE,WACA,YAIJ,2CACE,eACA,iBACA,gBAEA,wDACE,mBAGF,+DACE,gBAGF,kDACE,WACA,YACA,qBAIJ,2CACE,eACA,mBACA,gBAEA,wDACE,kBAGF,+DACE,gBAGF,kDACE,WACA,YACA,qBAIJ,iDACE,wCACA,0CAGF,2CACE,4CACA,8CAEA,0DACE,mBAEA,2EACE,mBAEA,yBAHF,2EAII,cACA,UACA,gCAOV,mBAmCE,8DACA,+DACA,iEACA,kEArCA,+HAIE,oBAGF,uDACE,kBACA,kBACA,qBAEA,+DACE,WACA,cACA,kBACA,MACA,SACA,YACA,UACA,+BACA,kBAGF,gEACE,6BAEA,wEACE,UACA,aAUN,gCACE,oBACA,gCAIJ,qBACE,qBAGF,kBACE,oCACA,gCACA,sBACA,eACA,qBAEA,2EACE,qCAIJ,mCACE,wBACA,gCACA,qBACA,SACA,gBACA,kBACA,uhB;AC7wBF,kBACE,mEACA,sEAEA,mBACA,oBAEA,0BACE,aAGF,oCACE,iBACA,sCACA,gDACA,2B;ACfJ,iBACE,WACA,YACA,aACA,mBACA,uBACA,kBAEA,0BACE,oBACA,sBACA,mBACA,gCACA,cACA,oBACA,qBACA,WAGF,wBACE,gBACA,gBAGF,8BACE,mBACA,gBAGF,0BACE,mBACA,aACA,YACA,eAEA,qCACE,aACA,Y;ACrCN,sBACE,YACA,aACA,mBACA,uBACA,mBAEA,cACE,mBACA,sBAGF,mBACE,sBACA,gCACA,gBACA,oBACA,qBACA,WACA,+BAEA,gBACE,oBAIJ,eACE,eACA,qBACA,kBACA,uBACA,0BAGF,kBACE,SACA,UACA,gBACA,uBACA,8BAGF,kBACE,kBACA,UACA,gBACA,uBACA,gBACA,yCAEA,WACE,wBACA,C;AClDN,aACE,OACA,WACA,oBAEA,gBACA,kBACA,gBAGA,6CzBJA,+ByBNF,azBOI,mBAGA,mByBEF,oCACE,2BAGF,iCACE,sIAGF,wBApBF,aAqBI,gEACA,mBAEA,gCACE,gEACA,uBAIJ,uDA9BF,aA+BI,mEACA,mCACE,kBACA,+CAEA,2EACE,4BAKN,yCACE,aAGF,iCACE,WACA,0CACA,gBACA,cACA,aACA,yBACA,sBACA,6BAEA,wDACE,4BAGF,yBAdF,iCAeI,YACA,wBAEA,UAIJ,yBACE,gBAEA,uCACE,mBAIJ,yDACE,gBAEA,qFACE,uBAEA,yBAHF,qFAII,uBAGF,iHACE,uBAKN,yBACE,+BACE,gBACA,6CACE,sBAEA,uDACE,yEACE,4DAOV,kDAEE,kBAEA,UACA,mBACA,+CAEA,wEACE,qBACA,UAKF,wEACE,eAGF,kEACE,WACA,kBACA,eACA,kBACA,WACA,YACA,gBACA,WAEA,UACA,4CAEA,gHACE,2BAKF,0GACE,k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iBAGF,+BACE,aACA,mBAGF,oCACE,mBAGF,kCACE,OACA,WACA,YACA,qBACA,kDACA,sCACA,mCACA,2BACA,gBACA,oBAEA,wCACE,WACA,wCACA,sCAIJ,0CACE,oB;AC/CN,yBACE,gBACA,wDAEA,mEACE,aAGF,oCACE,oBAGF,gDACE,2BAGF,6BACE,aACA,mBACA,sBACA,qBAGF,qCACE,cACA,2BACA,aACA,gBACA,wBACA,UACA,kBAEA,yBATF,qCAUI,gB;ACjCN,gBACE,gBACA,wDAsBA,qCApBA,uCACE,2BAGF,0DACE,aAGF,2BACE,oBAIF,oBACE,aACA,mBACA,sBACA,qBAKF,yCACE,kBAGF,4BACE,cACA,2BACA,aACA,gBACA,wBACA,UACA,kBAEA,yBATF,4BAUI,gBAIJ,yBACE,YACA,mCACA,gCAEA,iCACE,UACA,cAGF,iDACE,aAGF,gFAEE,OACA,eACA,gBAGF,qCACE,mBACA,uBAGF,2CACE,gBACA,mBACA,uB;ACvEN,UACE,qBAEA,oDACE,kBACA,mBACA,SAEA,uDALF,oDAMI,oCAGF,yBATF,oDAUI,oBAGF,4DACE,eAEA,yBAHF,4DAII,YAIJ,kEACE,UAIJ,wBACE,kBAGF,+BACE,KACE,WACA,mBAGF,GACE,aACA,oBAIJ,kBACE,cACA,kBAEA,+BACE,mCAGF,yBARF,kBASI,eACA,iBAGF,kGAGE,kBAIA,qIAEE,2BAIJ,yBACE,kBACA,UAEA,+DACE,mCAIJ,4BACE,kBACA,UACA,0BAIA,kCACE,iCAGF,+EAEE,0CAKF,8CACE,iCAGF,yEAEE,0CAKF,8EAEE,0CAGF,mCACE,iCAIJ,8BACE,kCAIA,8UACE,kCAKN,0BACE,UAGF,wEACE,wDAGF,qCACE,eACA,gBACA,kBAEA,mJAGE,kBAGF,8CACE,uBAGF,iDACE,iCAGF,kGACE,0CAGF,iDACE,kCAIA,yDACE,iCAGF,2HACE,0CAKF,gEACE,iCAGF,uHACE,0CAMR,iBACE,YACA,4BACA,mCACA,4CACA,6BACA,iDACA,kBACA,UAEA,+BACE,kBACA,kBACA,gBACA,eACA,eACA,yBACA,0BAEA,uCACE,6BAIJ,yBAxBF,iBAyBI,iCAIJ,uBACE,aAEA,gCACE,kBACA,uBACA,qBAGF,+BACE,cACA,2BACA,aACA,cACA,SACA,UACA,oBAEA,2DACE,mCAGF,uCACE,kBAGF,yBAjBF,+BAkBI,eACA,gBAEA,uCACE,wBAIJ,4CACE,sCAGA,0GACE,yCAIJ,yDACE,WACA,kBACA,WACA,cACA,8CACA,uBACA,YACA,aACA,kBACA,qCACA,mEACA,yBAZF,yDAaI,UACA,aAKN,oCACE,YACA,gBAGF,wCACE,qBACA,kBACA,mBACA,cACA,0BACA,sGAEA,+CACE,WACA,aACA,cACA,8BACA,sBACA,kBACA,QACA,qBACA,gBACA,mDAGF,yBArBF,wCAsBI,gBACA,sBAKN,wCAEE,kBAEA,oEACE,qIACA,gBACA,kBACA,iFACA,uBACA,mBACA,0CAEA,4LAEE,gHAGF,wFACE,gBACA,kBAIA,4OACE,aAIJ,kGACE,oBAIJ,4JAEE,kBACA,gCACA,oBACA,uBACA,mBACA,mBACA,0CACA,kEACA,YACA,mBACA,gBACA,uBACA,eAGF,gFACE,uBACA,OAGF,8FACE,QAGF,4EACE,oCACA,eACA,qBAEA,8QACE,qCAIJ,sDACE,kBACA,MACA,OACA,UACA,oBACA,YACA,uBACA,mBAIJ,oBACE,YAEA,kCACE,gBACA,kCACA,uBACA,2BACA,2BACA,8BACA,kBACA,iBACA,mBACA,wEACA,qBAUA,6BARA,yBAbF,kCAcI,gBACA,oBACA,iBACA,0EACA,eAKF,yDACE,2BAIJ,8EAEE,kEAEA,yBAJF,8EAKI,qEAKF,mDACE,eACA,gBAMF,+KACE,kBAIJ,2BACE,cACA,eACA,kBACA,iBACA,oBAKF,kCACE,eACA,mBACA,iBAGF,sCACE,gBACA,eAIJ,kBACE,kBACA,0BACA,OACA,WACA,mCACA,4CACA,gBACA,iBAEA,kBACA,gBAGA,iDAEA,UACA,6BACA,wBACA,6E9BneA,+B8BgdF,kB9B/cI,mBAGA,mB8BieF,8BACE,aAGF,uBACE,UACA,wBAGF,2BACE,cAIJ,sCACE,KACE,UAEF,GACE,Y;AChgBJ,kBACE,kBACA,MACA,OACA,SACA,QACA,gBACA,WACA,+CAEA,yBACE,WACA,kBACA,MACA,OACA,SACA,QACA,+CACA,2BACA,4BACA,sBAEA,4DACE,uEAGF,gDACE,gBAGF,sCACE,yDAEA,yBAHF,sCAII,0DAKN,gEACE,UAGF,0CACE,qDACA,YACA,qBAGF,kDACE,kBAGF,sCACE,gDACE,6BACA,gBACA,mBACA,6BACA,6CAGF,4GACE,kCAKF,sCADF,4GAEI,iCAGF,sCALF,4GAMI,kCAKN,cACE,aACA,uBACA,YACA,kBACA,UACA,YAEA,yBARF,cASI,iBAGF,+BACE,wDAEA,aACA,sBACA,mBACA,WACA,YACA,kBACA,gBAEA,2CACE,WACA,YACA,gBAEA,+CACE,aACA,sBACA,mBAMJ,wCACE,WACA,aACA,4CACA,mCACA,kCACA,kBACA,iDAKF,yCACE,kCACA,kGAEA,iDACE,mCACA,8CAIA,wIACE,2BAKN,+EACE,UACA,4CAEA,6HACE,2BAIJ,gCACE,UACA,mBACA,gHAEA,uDACE,2BAIJ,2EACE,oBAIA,6DACE,SAGF,qDACE,6FACA,yDAEA,6DACE,sCAIJ,2DACE,yBAEA,yBAHF,2DAII,0BAIJ,uGACE,UAGF,4CACE,qBACA,qBAKN,kCACE,oBACA,8CAEA,iEACE,UACA,4CAEA,wFACE,2BAIJ,yDACE,2BAGF,8CACE,kDACA,oBAEA,6EACE,UAKN,oCACE,WACA,0CACA,eACA,kBACA,aACA,qBACA,+BAEA,+BACA,uDAEA,2DACE,2BAGF,0BAhBF,oCAiBI,6CAEA,4DACE,mEAIJ,yBAxBF,oCAyBI,gBAEA,6DACE,wGAIJ,uDACE,sDACE,2CACA,MAEA,4EACE,iCAKN,4CACE,WACA,kBACA,eACA,OACA,QACA,WACA,qJACA,U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,2CACA,8BAEA,6CAEA,oCACE,gBAKA,qFACE,wBAIJ,0BAxBF,aAyBI,8DACA,kBAGF,yBA7BF,aA8BI,YACA,oCAGF,qDAlCF,aAmCI,0CAGF,yBACE,yCACA,gBAGF,4CACE,iBACA,cACA,kBAEA,oDACE,oBAEA,6DACE,0BAIJ,mDACE,aACA,uBACA,mBAEA,sDACE,gBACA,kBACA,iBACA,qBACA,sBAGF,iEACE,mBACA,oBAGF,0DACE,aACA,cACA,uBAIJ,oDACE,kBACA,cAKN,qBACE,kBACA,MACA,OACA,QACA,SACA,8BACA,gBACA,kBACA,oBAEA,0BAXF,qBAYI,gBAGF,+BACE,aAGF,uCACE,kBACA,MACA,QACA,SACA,OACA,WACA,gBACA,UAEA,yBAVF,uCAWI,2CAEA,8DACE,iBAKN,8FACE,mBAIA,yBACE,+DACE,uCAIJ,0DACE,oBACA,+B;AC3IN,MACE,YACA,gBACA,gBAEA,0BALF,MAMI,mBAGF,yBATF,MAUI,mCAGF,yBAbF,MAcI,aACA,+BACA,yBAIJ,uBACE,iCACA,oHACE,yBACA,gBAIJ,YACE,gBACA,WACA,kBACA,YACA,kBAEA,gBACE,YACA,gBAGF,yBAZF,YAaI,mCAGF,yBAhBF,YAiBI,gBAGF,0BApBF,YAqBI,WACA,gBAGF,yBAzBF,YA0BI,eACA,OACA,MACA,kCACA,yBAEA,mCACA,6CAEA,mCACE,gBAGF,mBACE,WACA,cACA,kBACA,OACA,MACA,QACA,SACA,gBACA,sCACA,2CACA,UAEA,0CACE,gBAIF,mCACE,aAGF,wDACE,cAIJ,2CACE,+BAEA,kDACE,UACA,oBAIJ,6CACE,gBAEA,mDACE,iBAKN,yBApFF,YAqFI,eACA,uBACA,mCAEA,2CAzFJ,YA0FM,0CACA,gDAMJ,yBADF,aAEI,yCAGF,8CACE,gBAEA,gEACE,gBAKN,mDACE,gBAGF,cACE,2CAEA,yBAHF,cAII,eACA,eACA,OACA,MACA,SACA,QAEA,+BACA,6CAEA,qCACE,gBAGF,6CACE,sCAIJ,yBAvBF,cAwBI,iBAEA,6CACE,mCAGF,sCACE,oCAIJ,+CACE,gBAEA,qDACE,gBAKN,kCACE,sCAEA,6IACE,6EAIA,gFACE,aAKF,+EACE,kCACA,UAKF,uEACE,+BACA,UAKF,8EACE,aAKF,6EACE,kCACA,UAKF,wEACE,+BACA,U","sources":["webpack://telegram-t/./src/components/left/main/LeftMainHeader.scss","webpack://telegram-t/./src/styles/_mixins.scss","webpack://telegram-t/./src/components/left/ConnectionState.scss","webpack://telegram-t/./src/components/left/NewChatButton.scss","webpack://telegram-t/./src/components/left/main/LeftMain.scss","webpack://telegram-t/./src/components/left/LeftColumn.scss","webpack://telegram-t/./src/components/middle/AudioPlayer.scss","webpack://telegram-t/./src/components/calls/group/GroupCallTopPane.scss","webpack://telegram-t/./src/components/middle/MiddleHeader.scss","webpack://telegram-t/./src/components/common/EmbeddedMessage.scss","webpack://telegram-t/./src/components/middle/message/MessageMeta.scss","webpack://telegram-t/./src/components/middle/message/Sticker.scss","webpack://telegram-t/./src/components/middle/message/Contact.scss","webpack://telegram-t/./src/components/middle/message/PollOption.scss","webpack://telegram-t/./src/components/middle/message/Poll.scss","webpack://telegram-t/./src/components/middle/message/WebPage.scss","webpack://telegram-t/./src/components/middle/message/Invoice.scss","webpack://telegram-t/./src/components/middle/message/Album.scss","webpack://telegram-t/./src/components/middle/message/RoundVideo.scss","webpack://telegram-t/./src/components/middle/message/InlineButtons.scss","webpack://telegram-t/./src/components/middle/message/CommentButton.scss","webpack://telegram-t/./src/components/middle/message/Message.scss","webpack://telegram-t/./src/components/middle/message/_message-content.scss","webpack://telegram-t/./src/components/middle/message/SponsoredMessage.scss","webpack://telegram-t/./src/components/middle/ContactGreeting.scss","webpack://telegram-t/./src/components/middle/NoMessages.scss","webpack://telegram-t/./src/components/middle/MessageList.scss","webpack://telegram-t/./src/components/middle/ScrollDownButton.scss","webpack://telegram-t/./src/components/middle/composer/BotKeyboardMenu.scss","webpack://telegram-t/./src/components/middle/composer/ComposerEmbeddedMessage.scss","webpack://telegram-t/./src/components/middle/composer/WebPagePreview.scss","webpack://telegram-t/./src/components/middle/composer/Composer.scss","webpack://telegram-t/./src/components/middle/MiddleColumn.scss","webpack://telegram-t/./src/components/right/RightHeader.scss","webpack://telegram-t/./src/components/right/Profile.scss","webpack://telegram-t/./src/components/right/AddChatMembers.scss","webpack://telegram-t/./src/components/right/RightColumn.scss","webpack://telegram-t/./src/components/main/Main.scss"],"sourcesContent":["@import '../../../styles/mixins';\n\n#LeftMainHeader {\n position: relative;\n\n .animated-menu-icon {\n position: absolute;\n\n &, &::before, &::after {\n width: 1.125rem;\n height: 0.125rem;\n border-radius: 0.125rem;\n background-color: var(--color-text-secondary);\n transition: transform .25s;\n transform: rotate(0);\n }\n\n &::before, &::after {\n position: absolute;\n left: 0;\n content: '';\n }\n\n &::before {\n top: -0.3125rem;\n }\n\n &::after {\n top: 0.3125rem;\n }\n\n &.state-back {\n transform: rotate(180deg);\n\n &::before {\n transform: rotate(45deg) scaleX(0.75) translate(0.375rem, -0.1875rem);\n }\n\n &::after {\n transform: rotate(-45deg) scaleX(0.75) translate(0.375rem, 0.1875rem);\n }\n }\n\n &.no-animation {\n transition: none;\n\n &::before, &::after {\n transition: none;\n }\n }\n }\n\n .archived-badge {\n min-width: 1.5rem;\n height: 1.5rem;\n margin-left: auto;\n background: var(--color-gray);\n border-radius: 0.75rem;\n padding: 0 .45rem;\n color: white;\n font-size: 0.875rem;\n line-height: 1.5rem;\n font-weight: 500;\n text-align: center;\n flex-shrink: 0;\n }\n\n [dir=rtl] .archived-badge {\n margin-left: 0;\n margin-right: auto;\n }\n\n .Menu .bubble {\n min-width: 17rem;\n max-height: calc(100 * var(--vh) - 3.75rem);\n\n overflow-y: auto;\n @include overflow-y-overlay();\n }\n\n // @optimization\n @include while-transition() {\n .Menu .bubble {\n transition: none !important;\n }\n }\n}\n","// @optimization\n@mixin while-transition() {\n .Transition > div:not(.Transition__slide--active) &, body.animating-right-column & {\n @content;\n }\n}\n\n@mixin overflow-y-overlay() {\n @supports (overflow-y: overlay) {\n overflow-y: overlay;\n\n //Workaround for Android <= 9\n overflow-x: hidden;\n }\n}\n\n@mixin reset-range() {\n input[type=\"range\"] {\n -webkit-appearance: none;\n display: block;\n width: 100%;\n height: 0.75rem;\n margin-bottom: 0.5rem;\n background: transparent;\n\n &:focus {\n outline: none;\n }\n\n &::-ms-track {\n width: 100%;\n cursor: pointer;\n\n background: transparent;\n border-color: transparent;\n color: transparent;\n }\n\n &::-webkit-slider-thumb {\n -webkit-appearance: none;\n }\n\n &::-moz-slider-thumb {\n -moz-appearance: none;\n }\n\n &::-webkit-slider-runnable-track {\n cursor: pointer;\n }\n\n &::-moz-range-track, &::-moz-range-progress {\n cursor: pointer;\n }\n }\n}\n","#ConnectionState {\n flex: 0 0 auto;\n display: flex;\n align-items: center;\n margin: 0 0.5rem 0.5rem;\n padding: 0.75rem;\n background: var(--color-yellow);\n border-radius: var(--border-radius-default);\n\n > .Spinner {\n --spinner-size: 1.75rem;\n }\n\n > .state-text {\n color: var(--color-text-lighter);\n font-weight: 500;\n line-height: 2rem;\n margin-inline-start: 1.875rem;\n white-space: nowrap;\n }\n\n @media (max-width: 950px) {\n > .state-text {\n margin-inline-start: 1.25rem;\n }\n }\n}\n",".NewChatButton {\n position: absolute;\n right: 1rem;\n bottom: 1rem;\n transform: translateY(5rem);\n\n transition: transform .25s cubic-bezier(0.34, 1.56, 0.64, 1);\n\n body.animation-level-0 & {\n transform: none !important;\n opacity: 0;\n\n transition: opacity .15s;\n\n &.revealed {\n opacity: 1;\n }\n }\n\n &.revealed {\n transform: translateY(0);\n\n @media (max-width: 600px) {\n // Force rendering in the composite layer to fix the z-index rendering issue\n transform: translate3d(0,0,10px);\n transform-style: preserve-3d;\n }\n }\n\n &.menu-is-open {\n &::before {\n content: '';\n display: block;\n position: absolute;\n top: -13rem;\n left: -11rem;\n right: -1rem;\n bottom: -1rem;\n z-index: -1;\n }\n }\n\n .is-touch-env & {\n .Menu > .backdrop {\n position: absolute;\n left: -100vw;\n right: -100vw;\n top: -100vh;\n bottom: -100vh;\n }\n }\n\n > .Button {\n .icon-new-chat-filled,\n .icon-close {\n position: absolute;\n }\n\n &:not(.active) {\n .icon-new-chat-filled {\n animation: grow-icon .4s ease-out;\n }\n\n .icon-close {\n animation: hide-icon .4s forwards ease-out;\n }\n }\n\n &.active {\n .icon-close {\n animation: grow-icon .4s ease-out;\n }\n\n .icon-new-chat-filled {\n animation: hide-icon .4s forwards ease-out;\n }\n }\n }\n}\n","#LeftColumn-main {\n height: 100%;\n position: relative;\n display: flex;\n flex-direction: column;\n overflow: hidden;\n z-index: 1;\n\n .connection-state-wrapper {\n position: absolute;\n top: 3.75rem;\n width: 100%;\n }\n\n > .Transition {\n flex: 1;\n overflow: hidden;\n transition: transform 300ms ease;\n\n &.pull-down {\n transform: translateY(3.75rem);\n }\n }\n\n .ChatFolders {\n height: 100%;\n display: flex;\n flex-direction: column;\n overflow: hidden;\n\n .tabs-placeholder {\n height: 2.625rem;\n transition: height 150ms ease;\n\n &:not(.open) {\n height: 0;\n }\n }\n\n .TabList {\n justify-content: flex-start;\n padding-left: .5625rem;\n padding-bottom: 1px;\n border-bottom: 0;\n z-index: 1;\n }\n\n .Tab {\n flex: 0 0 auto;\n padding-left: 0.625rem;\n padding-right: 0.625rem;\n\n > span {\n padding-left: 0.5rem;\n padding-right: 0.5rem;\n }\n }\n\n > .Transition {\n flex: 1;\n overflow: hidden;\n }\n }\n\n .RecentContacts, .LeftSearch, .search-content {\n height: 100%;\n overflow-y: auto;\n }\n\n .btn-update {\n position: absolute;\n bottom: 1rem;\n left: 1rem;\n right: 1rem;\n margin: 0 auto;\n }\n}\n","#NewChat {\n height: 100%;\n}\n\n.left-header {\n height: var(--header-height);\n padding: 0.375rem 1rem .5rem 0.8125rem;\n display: flex;\n align-items: center;\n flex-shrink: 0;\n background-color: var(--color-background);\n\n h3 {\n margin-bottom: 0;\n font-size: 1.25rem;\n font-weight: 500;\n margin-left: 1.375rem;\n margin-right: auto;\n }\n\n .SearchInput {\n margin-left: 0.875rem;\n max-width: calc(100% - 3.25rem);\n\n @media (max-width: 600px) {\n max-width: calc(100% - 3rem);\n }\n }\n\n @media (max-width: 600px) {\n padding: 0.5rem;\n }\n\n .Button.smaller {\n width: 2.5rem;\n height: 2.5rem;\n\n + .DropdownMenu {\n margin-left: .25rem;\n }\n }\n}\n",".AudioPlayer {\n display: flex;\n margin-left: auto;\n margin-top: -.25rem;\n margin-bottom: -.25rem;\n\n body.animation-level-0 & {\n transition: none !important;\n }\n\n > .Button {\n flex-shrink: 0;\n margin: .125rem;\n }\n\n > .player-button {\n --color-text-secondary: var(--color-primary);\n --color-text-secondary-rgb: var(--color-primary-shade-rgb);\n --color-primary-shade: var(--color-green);\n --color-white: var(--color-background-own);\n }\n\n .player-button {\n &.smaller {\n width: 3rem;\n height: 3rem;\n\n i {\n font-size: 1.625rem;\n margin-top: -.025rem;\n }\n }\n\n i {\n position: absolute;\n font-size: 1.9375rem;\n margin-top: -.05rem;\n\n &.icon-play {\n margin-left: .1rem;\n }\n }\n\n .icon-play, .icon-pause {\n opacity: 1;\n transform: scale(1);\n transition: opacity .4s, transform .6s cubic-bezier(0.34, 1.56, 0.64, 1);\n }\n\n &.play .icon-pause,\n &.pause .icon-play,\n &.loading .icon-play,\n &.loading .icon-pause {\n opacity: 0;\n transform: scale(.5);\n }\n }\n\n .volume-button {\n position: relative;\n overflow: visible;\n\n .volume-slider-spacer {\n position: absolute;\n transform: translateY(100%);\n bottom: 0;\n height: 1rem;\n width: 8rem;\n cursor: default;\n visibility: hidden;\n }\n\n &:hover .volume-slider-spacer, .volume-slider-spacer:hover {\n visibility: visible;\n }\n\n .volume-slider {\n opacity: 0;\n visibility: hidden;\n\n position: absolute;\n background: var(--color-background);\n bottom: -1rem;\n transform: translateY(100%);\n transition: opacity 0.2s ease-in-out, visibility 0.2s ease-in-out;\n width: 8rem;\n padding: 0.75rem;\n border-radius: 0.5rem;\n cursor: default;\n box-shadow: 0 1px 2px var(--color-default-shadow);\n\n .RangeSlider {\n margin-bottom: 0;\n input[type=range] {\n margin-bottom: 0;\n }\n }\n }\n\n &:hover .volume-slider,\n .volume-slider:hover,\n .volume-slider-spacer:hover + .volume-slider {\n opacity: 1;\n visibility: visible;\n }\n }\n\n .playback-button {\n &.applied {\n --color-text-secondary: var(--color-primary);\n }\n\n .playback-button-inner {\n transition: 0.2s color ease-in-out;\n font-size: 0.75rem;\n font-weight: bold;\n border: 2px solid;\n border-radius: 0.375rem;\n padding: 0.15rem 0.25rem;\n font-variant-numeric: tabular-nums;\n }\n }\n\n &-content {\n display: flex;\n justify-content: center;\n flex-direction: column;\n flex-shrink: 1;\n padding: 0 .5rem;\n position: relative;\n overflow: hidden;\n cursor: pointer;\n border-radius: var(--border-radius-messages-small);\n\n &:hover {\n background-color: var(--color-interactive-element-hover);\n }\n\n @media (min-width: 1440px) and (max-width: 1500px) {\n max-width: 14rem;\n }\n\n .AudioPlayer & .title {\n display: block;\n font-weight: 500;\n font-size: 0.875rem !important;\n line-height: 1rem;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n\n body.is-ios & {\n font-size: .9375rem !important;\n line-height: 1.125rem;\n }\n }\n\n .subtitle {\n font-size: 0.85rem !important;\n color: var(--color-text-secondary);\n line-height: 0.85rem;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n margin: .125rem 0 0;\n\n body.is-ios & {\n font-size: .9375rem !important;\n line-height: 1.125rem;\n }\n }\n }\n}\n",".GroupCallTopPane {\n position: absolute;\n top: 100%;\n left: 0;\n right: 0;\n height: 2.875rem;\n overflow: hidden;\n box-shadow: 0 2px 2px var(--color-light-shadow);\n display: flex;\n flex-direction: row;\n justify-content: space-between;\n align-items: center;\n padding: 0.375rem 0.5rem 0.375rem 0.75rem;\n background: var(--color-background);\n z-index: -1;\n cursor: pointer;\n\n &::before {\n content: \"\";\n display: block;\n position: absolute;\n top: -.1875rem;\n left: 0;\n right: 0;\n height: .125rem;\n box-shadow: 0 .125rem .125rem var(--color-light-shadow);\n }\n\n &.is-hidden {\n display: none;\n }\n\n @media (max-width: 600px) {\n &.has-pinned-offset {\n top: calc(100% + 2.875rem);\n }\n }\n\n .info {\n display: flex;\n flex-direction: column;\n\n .title {\n font-size: 0.875rem;\n color: var(--color-text);\n }\n\n .participants {\n font-size: 0.75rem;\n color: var(--color-text-secondary);\n }\n }\n\n .avatars {\n display: flex;\n flex-direction: row;\n align-items: center;\n\n .Avatar {\n margin: 0 0 0 -0.75rem;\n\n &:first-child {\n width: 2rem;\n height: 2rem;\n }\n\n &:not(:first-child) {\n width: 2.25rem;\n height: 2.25rem;\n border: 0.125rem solid var(--color-background);\n }\n }\n }\n\n .join {\n height: 1.5rem;\n border-radius: 1.5rem;\n font-weight: 500;\n padding: 1rem 1rem;\n width: auto;\n }\n}\n\n\n@media (min-width: 1440px) {\n #Main.right-column-open .MiddleHeader .GroupCallTopPane {\n width: calc(100% - var(--right-column-width));\n }\n}\n","@import '../../styles/mixins';\n\n@mixin mobile-header-styles() {\n .HeaderPinnedMessage-wrapper,\n .AudioPlayer {\n position: absolute;\n top: 100%;\n left: 0;\n right: 0;\n height: 2.875rem;\n box-shadow: 0 .125rem .125rem var(--color-light-shadow);\n\n display: flex;\n flex-direction: row-reverse;\n padding: 0.375rem 0.5rem;\n padding-left: 0.75rem;\n background: var(--color-background);\n\n &::before {\n content: \"\";\n display: block;\n position: absolute;\n top: -.1875rem;\n left: 0;\n right: 0;\n height: .125rem;\n box-shadow: 0 .125rem .125rem var(--color-light-shadow);\n }\n\n .HeaderPinnedMessage {\n max-width: unset;\n margin-top: -0.1875rem;\n }\n\n @supports (padding-left: env(safe-area-inset-left)) {\n padding-left: #{\"max(0.75rem, env(safe-area-inset-left))\"};\n padding-right: #{\"max(0.5rem, env(safe-area-inset-right))\"};\n }\n }\n\n .AudioPlayer {\n flex-direction: row;\n margin-top: 0;\n padding: 0.25rem 0.5rem;\n\n &-content {\n padding: 0 0.5rem;\n flex-grow: 1\n }\n\n > .Button {\n margin: -.0625rem 0 0;\n }\n\n > .player-close {\n margin-left: auto;\n }\n }\n\n .HeaderPinnedMessage {\n flex-grow: 1;\n padding-top: 0;\n padding-bottom: 0;\n\n &::before {\n top: 0.125rem;\n bottom: 0.125rem;\n }\n\n .message-text {\n max-width: none;\n }\n }\n\n .HeaderPinnedMessage-wrapper.full-width {\n display: none;\n }\n}\n\n.MiddleHeader {\n display: flex;\n align-items: center;\n width: 100%;\n box-shadow: 0 2px 2px var(--color-light-shadow);\n background: var(--color-background);\n padding: .5rem .8125rem .5rem 1.5rem;\n position: relative;\n z-index: var(--z-middle-header);\n\n @supports (padding-left: env(safe-area-inset-left)) {\n padding-left: #{\"max(1.5rem, env(safe-area-inset-left))\"};\n padding-right: #{\"max(.8125rem, env(safe-area-inset-right))\"};\n }\n\n @media (max-width: 600px) {\n padding: 0.5rem;\n position: relative;\n\n @supports (padding-left: env(safe-area-inset-left)) {\n padding-left: #{\"max(.5rem, env(safe-area-inset-left))\"};\n padding-right: #{\"max(.5rem, env(safe-area-inset-right))\"};\n }\n }\n\n .Transition {\n width: 100%;\n // https://dfmcphee.com/flex-items-and-min-width-0/\n // https://stackoverflow.com/questions/36247140/why-dont-flex-items-shrink-past-content-size\n min-width: 0;\n\n > div {\n display: flex;\n align-items: center;\n width: 100%;\n }\n }\n\n .back-button {\n margin-left: -0.5rem;\n margin-right: 0.5rem;\n position: relative;\n\n @media (max-width: 600px) {\n margin-left: 0;\n }\n\n .unread-count {\n min-width: 1.25rem;\n height: 1.25rem;\n padding: 0 0.375rem;\n border-radius: 0.625rem;\n font-size: 0.75rem;\n line-height: 1.25rem;\n font-weight: 500;\n text-align: center;\n\n position: absolute;\n top: -0.25rem;\n right: -0.5rem;\n\n background: var(--color-gray);\n color: white;\n pointer-events: none;\n\n &.active {\n background: var(--color-primary);\n }\n }\n }\n\n .chat-info-wrapper {\n flex-grow: 1;\n overflow: hidden;\n }\n\n body.animation-level-0 & .HeaderPinnedMessage-wrapper {\n transition: none !important;\n }\n\n .header-tools {\n display: flex;\n align-items: center;\n justify-content: flex-end;\n margin-left: auto;\n flex-shrink: 0;\n\n body.animation-level-0 & {\n &,\n .AudioPlayer,\n .HeaderActions {\n transition: none !important;\n }\n }\n\n @media (min-width: 1276px) and (max-width: 1439px) {\n .HeaderActions {\n transform: translate3d(0, 0, 0);\n transition: transform var(--layer-transition);\n\n #Main.right-column-open & {\n transform: translate3d(calc(var(--right-column-width) * -1), 0, 0);\n }\n }\n }\n\n @media (min-width: 1440px) {\n transform: translate3d(0, 0, 0);\n transition: transform var(--layer-transition);\n\n #Main.right-column-open & {\n transform: translate3d(calc(var(--right-column-width) * -1), 0, 0);\n }\n }\n\n // @optimization\n @include while-transition() {\n pointer-events: none;\n }\n }\n\n @media (min-width: 1276px) and (max-width: 1439px) {\n &:not(.tools-stacked) .HeaderPinnedMessage-wrapper,\n &:not(.tools-stacked) .AudioPlayer {\n opacity: 1;\n\n #Main.right-column-open & {\n opacity: 0;\n }\n }\n }\n\n &.tools-stacked .AudioPlayer {\n @include mobile-header-styles();\n\n @media (min-width: 1150px) {\n #Main.right-column-open & {\n padding-right: calc(0.5rem + var(--right-column-width));\n }\n }\n }\n\n &.tools-stacked.animated .HeaderPinnedMessage-wrapper,\n &.tools-stacked.animated .AudioPlayer {\n animation: fade-in var(--layer-transition) forwards;\n\n body.animation-level-0 & {\n animation: none;\n }\n }\n\n h3 {\n font-weight: 500;\n font-size: 1.125rem;\n line-height: 1.375rem;\n white-space: pre;\n margin: 0;\n overflow: hidden;\n text-overflow: ellipsis;\n unicode-bidi: plaintext;\n\n body.is-ios &,\n body.is-macos & {\n font-size: 1.0625rem;\n font-weight: 600;\n }\n\n @media (max-width: 600px) {\n display: block;\n overflow: hidden;\n text-overflow: ellipsis;\n }\n\n @media (min-width: 1275px) {\n #Main.right-column-open & {\n max-width: calc(100% - var(--right-column-width));\n }\n }\n }\n\n .ChatInfo {\n cursor: pointer;\n display: flex;\n align-items: center;\n\n .info {\n display: flex;\n flex-direction: column;\n justify-content: center;\n flex-grow: 1;\n overflow: hidden;\n }\n\n .title {\n display: flex;\n align-items: center;\n\n .VerifiedIcon {\n width: 1.25rem;\n height: 1.25rem;\n margin-left: 0.25rem;\n margin-top: 0.05rem;\n }\n }\n\n .status {\n display: flex;\n unicode-bidi: plaintext;\n }\n\n .user-status {\n unicode-bidi: plaintext;\n overflow: hidden;\n text-overflow: ellipsis;\n\n @media (min-width: 1275px) {\n #Main.right-column-open & {\n max-width: calc(100% - var(--right-column-width));\n }\n }\n }\n }\n\n .Avatar {\n margin-right: .625rem;\n // TODO For some reason webpack imports `Audio.scss` second time when loading calls bundle\n width: 2.5rem !important;\n height: 2.5rem !important;\n font-size: 1.0625rem;\n }\n\n .status, .typing-status {\n font-size: 0.875rem;\n line-height: 1.125rem;\n margin: 0;\n color: var(--color-text-secondary);\n overflow: hidden;\n white-space: nowrap;\n text-overflow: ellipsis;\n display: inline-block;\n\n .ellipsis {\n display: inline-flex;\n }\n\n &.online {\n color: var(--color-primary);\n }\n\n .font-emoji {\n line-height: 1rem;\n }\n }\n\n .Button.smaller {\n width: 2.5rem;\n height: 2.5rem;\n }\n\n .HeaderPinnedMessage-wrapper {\n display: flex;\n align-items: center;\n margin-left: auto;\n cursor: default;\n flex-direction: row-reverse;\n background: var(--color-background);\n\n body.animation-level-1 & {\n .ripple-container {\n display: none;\n }\n }\n\n @media (min-width: 1276px) {\n transform: translate3d(0, 0, 0);\n transition: opacity 0.15s ease, transform var(--layer-transition);\n\n #Main.right-column-open & {\n transform: translate3d(calc(var(--right-column-width) * -1), 0, 0);\n }\n }\n\n\n .HeaderPinnedMessage {\n min-width: 16rem;\n }\n\n > .Button {\n flex-shrink: 0;\n }\n\n &.full-width {\n position: absolute;\n left: 0;\n right: 0;\n top: 100%;\n background: var(--color-background);\n padding: .25rem .8125rem .25rem 1rem;\n box-shadow: 0 .125rem .125rem var(--color-light-shadow);\n transform: translate3d(0, 0, 0);\n transition: opacity 0.15s ease, transform var(--layer-transition);\n\n &::before {\n content: \"\";\n display: block;\n position: absolute;\n top: -.1875rem;\n left: 0;\n right: 0;\n height: .125rem;\n box-shadow: 0 .125rem .125rem var(--color-light-shadow);\n }\n\n .HeaderPinnedMessage {\n margin-top: 0;\n margin-bottom: 0;\n flex: 1;\n\n .message-text {\n max-width: none;\n }\n }\n\n @media (min-width: 1276px) {\n transform: translate3d(0, 0, 0);\n transition: opacity 0.15s ease, transform var(--layer-transition);\n\n #Main.right-column-open & {\n padding-left: calc(var(--right-column-width) + 1rem);\n }\n }\n }\n }\n\n .HeaderPinnedMessage {\n display: flex;\n flex-shrink: 1;\n margin-top: -0.25rem;\n margin-bottom: -0.25rem;\n padding: 0.25rem;\n padding-left: 0.375rem;\n border-radius: var(--border-radius-messages-small);\n position: relative;\n overflow: hidden;\n cursor: pointer;\n\n &:hover {\n background-color: var(--color-interactive-element-hover);\n }\n\n .pinned-message-border {\n position: relative;\n height: 2.25rem;\n margin: 0.125rem 0;\n width: 0.125rem;\n min-width: 0.125rem;\n overflow: hidden;\n\n .pinned-message-border-wrapper-1 {\n height: 2.25rem;\n width: 0.125rem;\n border-radius: 0.0625rem;\n background: var(--color-primary);\n }\n\n .pinned-message-border-wrapper {\n background-color: var(--color-primary-opacity);\n position: relative;\n will-change: transform;\n transition: transform .25s ease-in-out;\n }\n\n .pinned-message-border-mark {\n position: absolute;\n left: 0;\n top: 0;\n width: 0.125rem;\n background: var(--color-primary);\n border-radius: 0.0625rem;\n will-change: transform;\n transition: transform .25s ease-in-out;\n }\n }\n\n .message-text {\n overflow: hidden;\n margin-inline-start: 0.375rem;\n margin-top: 0.125rem;\n max-width: 15rem;\n\n @media (min-width: 1440px) and (max-width: 1500px) {\n max-width: 14rem;\n }\n\n .title {\n font-weight: 500;\n font-size: 0.875rem;\n line-height: 1rem;\n height: 1rem;\n color: var(--color-primary);\n margin-bottom: 0.125rem;\n white-space: pre;\n text-align: initial;\n\n body.is-ios & {\n font-size: .9375rem;\n }\n }\n\n p {\n font-size: 0.875rem;\n line-height: 1.125rem;\n height: 1.125rem;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n margin: 0;\n\n body.is-ios & {\n font-size: .9375rem;\n }\n }\n }\n\n .emoji-small {\n width: 1rem;\n height: 1rem;\n }\n\n & > img {\n width: 2.25rem;\n height: 2.25rem;\n object-fit: cover;\n border-radius: 0.25rem;\n margin-inline-start: 0.375rem;\n margin-top: 0.125rem;\n flex-shrink: 0;\n\n & + .message-text {\n max-width: 12rem;\n }\n }\n }\n\n .HeaderActions {\n flex-shrink: 0;\n margin-left: auto;\n display: flex;\n align-items: center;\n justify-content: flex-end;\n\n .toggle-right-pane-button {\n &.active {\n color: var(--color-primary);\n opacity: 1;\n }\n }\n }\n\n .HeaderPinnedMessage-wrapper, .HeaderActions {\n .Button {\n margin-left: 0.25rem;\n\n &.tiny {\n margin-right: .625rem;\n }\n }\n }\n\n @media (max-width: 600px) {\n @include mobile-header-styles();\n }\n}\n\n@keyframes fade-in {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n",".EmbeddedMessage {\n display: flex;\n align-items: center;\n font-size: calc(var(--message-text-size, 1rem) - .125rem);\n line-height: 1.125rem;\n margin: 0 -0.25rem .0625rem;\n padding: .1875rem 0.25rem .1875rem .4375rem;\n border-radius: var(--border-radius-messages-small);\n position: relative;\n overflow: hidden;\n cursor: pointer;\n direction: ltr;\n\n body.animation-level-1 & {\n .ripple-container {\n display: none;\n }\n }\n\n .custom-shape & {\n max-width: 15rem;\n padding: 0.5rem;\n margin: 0;\n background-color: var(--background-color);\n box-shadow: 0 1px 2px var(--color-default-shadow);\n\n &::before {\n left: .625rem;\n top: .625rem;\n bottom: .625rem;\n }\n\n img:not(.emoji) {\n margin-inline-start: .5rem;\n }\n\n &:dir(rtl) {\n padding: 0.5rem;\n }\n }\n\n &::before {\n content: '';\n display: block;\n position: absolute;\n top: .3125rem;\n bottom: .3125rem;\n left: .3125rem;\n width: 2px;\n background: var(--accent-color);\n border-radius: 2px;\n }\n\n &:hover {\n background-color: var(--hover-color);\n }\n\n &:active {\n background-color: var(--active-color);\n }\n\n .message-title {\n font-size: calc(var(--message-text-size, 1rem) - .125rem);\n }\n\n .message-text {\n overflow: hidden;\n margin-inline-start: 0.5rem;\n display: flex;\n flex-direction: column-reverse;\n\n .message-title {\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n margin-bottom: 0.125rem;\n flex: 1;\n display: block;\n }\n\n p {\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n height: 1.125rem;\n margin-bottom: 0;\n flex: 1;\n\n &::after {\n content: none;\n display: none;\n }\n }\n\n .emoji {\n width: calc(1.125 * var(--message-text-size, 1rem)) !important;\n height: calc(1.125 * var(--message-text-size, 1rem)) !important;\n vertical-align: text-bottom !important;\n }\n }\n\n .embedded-action-message {\n color: var(--accent-color);\n opacity: 0.75;\n }\n\n img:not(.emoji) {\n width: 2rem;\n height: 2rem;\n object-fit: cover;\n border-radius: .25rem;\n margin-left: .25rem;\n flex-shrink: 0;\n\n &.round {\n border-radius: 1rem;\n }\n }\n\n &.inside-input {\n padding-inline-start: 0.5625rem;\n margin: 0 0 -.125rem -0.1875rem;\n display: grid;\n grid-template-columns: auto 1fr;\n grid-template-rows: 1fr;\n width: 100%;\n --accent-color: var(--color-primary);\n --hover-color: var(--color-interactive-element-hover);\n\n &::before {\n bottom: .3125rem;\n }\n\n img:not(.emoji) {\n margin-left: .125rem;\n }\n\n .message-text {\n margin-inline-start: .375rem;\n }\n\n .message-title {\n font-weight: 500;\n color: var(--accent-color);\n }\n }\n}\n",".MessageMeta {\n position: absolute;\n height: 1.25rem;\n bottom: 0;\n right: 0;\n display: flex;\n align-items: center;\n background: rgba(#999999, 0.6);\n border-radius: .625rem;\n padding: 0 .25rem;\n color: white;\n cursor: pointer;\n max-width: 100%;\n user-select: none;\n\n .message-time,\n .message-signature,\n .message-views {\n font-size: .75rem;\n white-space: nowrap;\n }\n\n .message-time {\n margin-right: .1875rem;\n }\n\n body.is-ios & {\n .message-time {\n margin-right: .25rem;\n }\n }\n\n .message-views {\n margin-inline-start: .1875rem;\n }\n\n .message-signature {\n overflow: hidden;\n text-overflow: ellipsis;\n margin-right: 0.375rem;\n }\n\n .icon-channelviews {\n margin-left: 0.125rem;\n margin-right: 0.375rem;\n font-size: 1.125rem;\n position: relative;\n top: -0.0625rem;\n }\n\n .has-solid-background & {\n color: rgba(var(--color-text-meta-rgb), 0.75);\n background: none;\n }\n\n .media:not(.text) &,\n .Message .custom-shape & {\n background: rgba(0, 0, 0, 0.2);\n --color-accent-own: white;\n --color-accent: white;\n color: white !important;\n opacity: 1;\n bottom: .25rem;\n right: .25rem;\n left: auto;\n height: 1.125rem;\n padding: 0 .3125rem 0 .375rem;\n\n .MessageOutgoingStatus i {\n background: transparent;\n }\n }\n\n .media:not(.text):dir(rtl) &,\n .Message .custom-shape:dir(rtl) & {\n right: auto !important;\n left: .25rem;\n padding: 0 .375rem 0 .3125rem;\n }\n\n .is-forwarded.media:not(.text):dir(rtl) &,\n .Message .is-forwarded.custom-shape:dir(rtl) & {\n left: .8125rem;\n }\n\n .is-forwarded.media:not(.text) & {\n bottom: 0.935rem;\n right: 0.8125rem;\n }\n\n .emoji-only & {\n right: 0;\n }\n\n .Message.own .has-solid-background & {\n color: var(--color-message-meta-own);\n }\n\n .MessageOutgoingStatus {\n margin-left: -.1875rem;\n font-size: 1.1875rem;\n border-radius: .625rem;\n\n .Message.own & {\n color: var(--color-accent-own);\n }\n }\n\n .message-content.has-replies:not(.custom-shape) & {\n bottom: 3.375rem;\n }\n\n .message-content.has-replies.text:not(.custom-shape) & {\n bottom: 3.4375rem;\n }\n\n &[dir=\"rtl\"] {\n .message-views {\n order: 10;\n }\n .icon-channelviews {\n order: 9;\n }\n }\n}\n\n.Message:not(.own) {\n .custom-shape .reply-message + .MessageMeta {\n right: auto;\n left: 13.2rem;\n bottom: 0.25rem;\n }\n\n .emoji-only-1 .reply-message + .MessageMeta {\n left: 2.5rem;\n }\n\n .emoji-only-2 .reply-message + .MessageMeta {\n left: 5.5rem;\n }\n\n .emoji-only-3 .reply-message + .MessageMeta {\n left: 6.5rem;\n }\n}\n",".Sticker {\n &:not(.inactive) {\n cursor: pointer;\n }\n\n &.inactive {\n pointer-events: none;\n }\n}\n",".Contact {\n display: flex;\n align-items: center;\n padding: 0.25rem;\n\n &.interactive {\n cursor: pointer;\n }\n\n .Avatar {\n margin-right: 0.8rem;\n }\n\n .contact-info {\n padding: 0.5rem;\n padding-left: 0;\n white-space: nowrap;\n overflow: hidden;\n\n .contact-name {\n font-size: 1rem;\n line-height: 1rem;\n margin-bottom: 0.25rem;\n font-weight: 500;\n }\n\n .contact-phone {\n line-height: 1rem;\n color: var(--secondary-color);\n }\n }\n}\n\n\n",".PollOption {\n display: flex;\n flex-flow: row nowrap;\n margin-bottom: 0.75rem;\n\n &:last-child {\n margin-bottom: 0;\n }\n\n .poll-option-text {\n word-break: break-word;\n }\n\n .poll-option-share {\n position: relative;\n margin-top: .125rem;\n width: 1.75rem;\n margin-inline-end: .5rem;\n flex-shrink: 0;\n font-weight: 500;\n font-size: .875rem;\n text-align: right;\n\n &.limit-width {\n display: inline-flex;\n justify-content: center;\n font-size: .75rem;\n }\n }\n\n .poll-option-chosen {\n position: absolute;\n right: 0;\n bottom: -5px;\n width: 1rem;\n height: 1rem;\n background: var(--accent-color);\n color: var(--background-color);\n border-radius: .5rem;\n font-size: .75rem;\n text-align: center;\n\n &.wrong {\n background: var(--color-error);\n }\n\n .is-forwarded & > i {\n margin-left: 1px;\n }\n\n &.animate {\n opacity: 0;\n animation-name: PollOptionIconAnimate;\n animation-delay: .09s;\n animation-duration: .3s;\n animation-fill-mode: forwards;\n }\n }\n\n .poll-option-right {\n flex-grow: 1;\n line-height: 1.5rem;\n }\n\n .poll-option-answer {\n position: relative;\n }\n\n .poll-option-line {\n position: relative;\n width: 0;\n height: 0.25rem;\n min-width: 0.5rem;\n border-radius: 0.125rem;\n margin-top: 0.5rem;\n background: var(--accent-color);\n\n transform-origin: 0 0;\n transition: transform .3s;\n transition-delay: .09s;\n\n }\n\n .poll-line {\n width: 30px;\n height: 35px;\n position: absolute;\n left: -27px;\n bottom: -5px;\n transition: stroke-dashoffset .3s, stroke-dasharray .3s;\n stroke-dashoffset: 0;\n stroke-dasharray: 0, 200%\n }\n\n .poll-line path {\n stroke-width: 4px;\n stroke-linecap: round;\n stroke: var(--accent-color);\n fill:none\n }\n\n .wrong {\n .poll-option-line {\n background: var(--color-error);\n }\n\n .poll-line path {\n stroke: var(--color-error);\n }\n }\n}\n\n@keyframes PollOptionIconAnimate {\n 0% { opacity: 0 }\n 100% { opacity: 1 }\n}\n",".Poll {\n min-width: 15rem;\n text-align: initial;\n\n @media (max-width: 600px) {\n min-width: 50vw;\n }\n\n .poll-question {\n font-weight: 500;\n line-height: 1.25rem;\n margin: 0.125rem 0;\n word-break: break-word;\n }\n\n .poll-type,\n .poll-voters-count {\n color: var(--secondary-color);\n font-size: 0.875rem;\n }\n\n .poll-type {\n margin-bottom: 0.5rem;\n display: flex;\n align-items: center;\n min-height: 1.375rem;\n }\n\n .poll-voters-count {\n margin: .4375rem 0 1.125rem;\n text-align: center;\n }\n\n .poll-answers {\n padding-top: 0.25rem;\n padding-bottom: 1rem;\n }\n\n .Checkbox,\n .Radio {\n padding-left: 2.25rem;\n\n &:last-child {\n margin-bottom: .75rem;\n }\n\n &.disabled {\n opacity: 1 !important;\n cursor: not-allowed;\n }\n\n .Checkbox-main,\n .Radio-main {\n &::before {\n left: 0.125rem;\n background-color: var(--background-color);\n\n .theme-dark & {\n --color-borders: var(--color-borders-input);\n }\n\n .Message.own & {\n --color-borders: var(--accent-color);\n }\n }\n\n &::after {\n left: 0.4375rem;\n background-color: var(--accent-color);\n }\n }\n\n input:checked ~ .Radio-main,\n input:checked ~ .Checkbox-main {\n &::before {\n border-color: var(--accent-color);\n }\n }\n\n .Spinner {\n left: 0.125rem;\n }\n }\n\n .Checkbox {\n .Checkbox-main {\n &::after {\n left: 0.125rem;\n background-color: var(--color-primary);\n\n .Message.own & {\n background-color: var(--accent-color);\n }\n }\n }\n }\n\n .Spinner > div {\n // gray spinner\n background-image: var(--spinner-gray-data);\n\n .theme-dark & {\n background-image: var(--spinner-white-data);\n }\n\n .Message.own & {\n // green spinner\n background-image: var(--spinner-green-data);\n .theme-dark & {\n background-image: var(--spinner-white-data);\n }\n }\n }\n\n .poll-recent-voters {\n display: inline-flex;\n align-items: center;\n vertical-align: text-bottom;\n margin-left: .875rem;\n margin-right: .5rem;\n margin-top: -2px;\n\n .Avatar {\n border: .0625rem solid var(--color-white);\n margin-right: 0;\n box-sizing: content-box;\n\n .Message.own & {\n border: .0625rem solid var(--secondary-color);\n }\n\n &:not(:first-child) {\n margin-left: -3px;\n }\n }\n }\n\n .poll-countdown {\n margin-left: auto;\n font-size: .75rem;\n transition: color .2s;\n\n &.hurry-up {\n color: var(--color-error);\n\n .poll-countdown-progress {\n stroke: var(--color-error);\n }\n }\n\n svg {\n vertical-align: -3px;\n }\n }\n\n .poll-countdown-progress {\n stroke: var(--color-primary);\n fill: transparent;\n stroke-width: 2;\n stroke-linecap: round;\n transition: stroke-dashoffset 2s, stroke .2s;\n }\n\n .poll-quiz-help {\n margin: -.625rem 0 -.625rem auto;\n .Message:not(.own) & {\n color: var(--color-primary);\n }\n }\n\n .poll-results,\n .poll-answers {\n padding-top: 0.25rem;\n padding-bottom: 0.5rem;\n }\n\n .Button {\n text-transform: none;\n font-size: 1rem;\n\n .Message.own & {\n color: var(--accent-color);\n --color-primary-shade-rgb: var(--color-accent-own);\n }\n }\n\n > .Button {\n margin-bottom: .625rem;\n }\n}\n",".WebPage {\n margin-top: 0.25rem;\n margin-bottom: 0.125rem;\n padding-left: .625rem;\n font-size: calc(var(--message-text-size, 1rem) - .125rem);\n line-height: 1.125rem;\n max-width: 29rem;\n position: relative;\n\n &::before {\n content: '';\n display: block;\n position: absolute;\n top: 0;\n bottom: 0;\n left: 0;\n width: .125rem;\n background: var(--accent-color);\n border-radius: .125rem;\n }\n\n &-text {\n display: flex;\n flex-direction: column;\n align-items: flex-start;\n }\n\n .media-inner {\n margin: 0 !important;\n margin-bottom: 0.375rem !important;\n\n &, & img, &.small-image img {\n border-radius: var(--border-radius-messages-small) !important;\n }\n\n &.square-image {\n width: 5rem;\n height: 5rem;\n min-height: 0;\n margin-bottom: 0 !important;\n\n img {\n width: 100%;\n height: 100%;\n }\n }\n }\n\n &.with-video .media-inner{\n margin-top: 0.5rem !important;\n margin-bottom: 1rem !important;\n }\n\n &.with-square-photo {\n display: flex;\n margin-bottom: 1rem;\n\n .WebPage-text {\n order: 1;\n padding-right: 1rem;\n }\n\n .media-inner {\n order: 2;\n flex-shrink: 0;\n }\n\n &:dir(rtl) {\n .WebPage-text {\n padding-inline-end: 1rem;\n }\n }\n }\n\n &:not(.with-square-photo) {\n .site-name,\n .site-title,\n .site-description {\n &:last-child::after {\n content: '';\n display: inline-block;\n width: var(--meta-safe-area-size);\n height: 0.75rem;\n float: right;\n }\n }\n }\n\n .site-name,\n .site-description,\n .site-title {\n word-break: break-word;\n max-width: 100%;\n }\n\n .site-name {\n color: var(--accent-color);\n font-weight: 500;\n margin-bottom: 0.125rem;\n }\n\n .site-title {\n font-weight: 500;\n margin-bottom: 0.125rem;\n }\n\n .site-description {\n line-height: 1.25;\n margin-bottom: 0;\n\n body.is-ios & {\n line-height: 1.125rem;\n }\n }\n\n &:dir(rtl) {\n padding-inline-start: .625rem;\n\n &::before {\n left: auto;\n right: 0;\n }\n }\n}\n\n\n",".Invoice {\n .title {\n color: var(--accent-color);\n font-weight: 500;\n }\n\n .description {\n position: relative;\n\n &.has-image {\n .invoice-image {\n max-width: 100%;\n height: 20rem;\n\n @media (max-width: 600px) {\n height: 10rem;\n }\n }\n\n .description-text {\n position: absolute;\n top: 0;\n padding: .25rem .5rem;\n margin: .25rem;\n background-color: rgba(90, 110, 70, 0.6);\n border-radius: var(--border-radius-messages-small);\n color: var(--color-text);\n font-weight: 500;\n\n span {\n margin-left: .5rem;\n }\n }\n }\n\n }\n}\n",".Album {\n position: relative;\n overflow: hidden;\n\n .message-content.media.text & {\n margin: -0.3125rem -0.5rem 0.3125rem;\n }\n\n .forwarded-message & {\n margin-bottom: .125rem;\n\n .message-content.media.text & {\n margin: 0 0 0.3125rem;\n --border-bottom-left-radius: inherit;\n --border-bottom-right-radius: inherit;\n }\n }\n\n &,\n .message-content.media.text & {\n > .album-item-select-wrapper .media-inner {\n margin: 0 !important;\n }\n }\n\n > .album-item-select-wrapper .media-inner {\n &, & img, & video {\n border-radius: 0 !important;\n object-fit: cover;\n }\n }\n}\n",".RoundVideo {\n position: relative;\n width: 15rem;\n height: 15rem;\n cursor: pointer;\n\n .thumbnail-wrapper {\n width: 15rem;\n height: 15rem;\n border-radius: 50%;\n overflow: hidden;\n }\n\n .video-wrapper {\n position: absolute;\n left: 0;\n top: 0;\n border-radius: 50%;\n overflow: hidden;\n }\n\n .progress {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n pointer-events: none;\n }\n\n .progress-circle {\n stroke: white;\n fill: transparent;\n stroke-width: 4;\n stroke-opacity: .35;\n stroke-linecap: round;\n }\n\n video::-internal-media-controls-cast-button,\n video::-webkit-media-controls,\n video::-webkit-media-controls-start-playback-button {\n display: none;\n }\n}\n",".InlineButtons {\n display: flex;\n flex-direction: column;\n\n .row {\n display: flex;\n flex-direction: row;\n }\n\n .Button {\n flex: 1;\n width: auto;\n margin: 0.125rem;\n background: var(--pattern-color);\n border-radius: var(--border-radius-messages-small);\n font-weight: 500;\n text-transform: none;\n\n &::before {\n content: '';\n background-color: var(--color-white);\n opacity: 0;\n\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n border-radius: var(--border-radius-messages-small);\n z-index: var(--z-below);\n transition: opacity 200ms;\n }\n\n &:hover {\n background: var(--pattern-color) !important;\n\n &::before {\n opacity: .4;\n }\n }\n\n &:first-of-type {\n margin-left: 0;\n }\n\n &:last-of-type {\n margin-right: 0;\n }\n\n i {\n font-size: .875rem;\n position: absolute;\n right: .1875rem;\n top: .1875rem;\n display: block;\n\n &.icon-arrow-right {\n font-size: .75rem;\n top: .125rem;\n right: .125rem;\n transform: rotate(-45deg);\n }\n }\n }\n\n .row:first-of-type .Button {\n margin-top: 0.25rem !important;\n }\n\n .row:last-of-type .Button {\n margin-bottom: 0;\n\n &:first-of-type {\n border-bottom-left-radius: var(--border-radius-messages);\n }\n\n &:last-of-type {\n border-bottom-right-radius: var(--border-radius-messages);\n }\n }\n}\n",".CommentButton {\n --background-color: var(--color-background);\n --hover-color: var(--color-chat-hover);\n\n display: flex;\n width: 100%;\n align-items: center;\n padding: .5625rem .25rem .5625rem .625rem;\n padding-inline-start: .625rem;\n padding-inline-end: .25rem;\n background: var(--background-color);\n border-bottom-right-radius: var(--border-bottom-right-radius);\n border-bottom-left-radius: var(--border-bottom-left-radius);\n font-size: .9375rem;\n font-weight: 500;\n line-height: 2rem;\n color: var(--accent-color);\n white-space: nowrap;\n cursor: pointer;\n transition: background-color .15s, color .15s;\n user-select: none;\n\n body.animation-level-0 & {\n transition: none !important;\n }\n\n .Message .has-appendix &::before {\n content: '';\n display: block;\n position: absolute;\n bottom: -.1875rem;\n left: -.5625rem;\n width: .5625rem;\n height: 1.25rem;\n background-position: bottom left;\n background-image: url('data:image/svg+xml,%3Csvg width=\"9\" height=\"20\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\"%3E%3Cdefs%3E%3Cfilter x=\"-50%25\" y=\"-14.7%25\" width=\"200%25\" height=\"141.2%25\" filterUnits=\"objectBoundingBox\" id=\"a\"%3E%3CfeOffset dy=\"1\" in=\"SourceAlpha\" result=\"shadowOffsetOuter1\"/%3E%3CfeGaussianBlur stdDeviation=\"1\" in=\"shadowOffsetOuter1\" result=\"shadowBlurOuter1\"/%3E%3CfeColorMatrix values=\"0 0 0 0 0.0621962482 0 0 0 0 0.138574144 0 0 0 0 0.185037364 0 0 0 0.15 0\" in=\"shadowBlurOuter1\"/%3E%3C/filter%3E%3Cpath d=\"M3 17h6V0c-.193 2.84-.876 5.767-2.05 8.782-.904 2.325-2.446 4.485-4.625 6.48A1 1 0 003 17z\" id=\"b\"/%3E%3C/defs%3E%3Cg fill=\"none\" fill-rule=\"evenodd\"%3E%3Cuse fill=\"%23000\" filter=\"url(%23a)\" xlink:href=\"%23b\"/%3E%3Cuse fill=\"%23FFF\" xlink:href=\"%23b\"/%3E%3C/g%3E%3C/svg%3E');\n opacity: 0;\n transition: opacity .15s, filter .15s;\n\n .theme-dark #root & {\n filter: invert(.83);\n }\n\n body.animation-level-0 & {\n transition: none !important;\n }\n }\n\n .custom-shape & {\n position: absolute;\n right: -3rem;\n width: 2.25rem;\n bottom: 3rem;\n height: 3.375rem;\n border-radius: 1.375rem;\n padding: 0.375rem .3125rem .25rem;\n align-items: flex-start;\n color: white;\n background-color: rgba(0, 0, 0, .2);\n\n opacity: 0;\n transition: opacity .2s ease;\n\n @media (pointer: coarse) {\n opacity: 1 !important;\n }\n\n &:hover {\n background-color: rgba(0, 0, 0, .28);\n }\n\n .Message:hover & {\n opacity: 1;\n }\n\n &::after {\n content: attr(data-cnt);\n position: absolute;\n bottom: -.0625rem;\n left: 0;\n width: 100%;\n text-align: center;\n font-size: 12px;\n display: block;\n }\n\n &[data-cnt=\"0\"] {\n height: 2.25rem;\n &::after {\n display: none;\n }\n }\n\n .icon-comments-sticker {\n display: block;\n font-size: 1.5rem;\n margin: 0 auto;\n }\n\n .recent-repliers,\n .icon-comments,\n .label,\n .icon-next {\n display: none;\n }\n }\n\n &:hover {\n background: var(--hover-color);\n\n .Message .has-appendix &::before {\n opacity: 1;\n }\n\n .Avatar {\n border-color: var(--hover-color) !important;\n }\n }\n\n .is-forwarded &,\n .audio &,\n .voice &,\n .poll &,\n .text & {\n border-top: 1px solid var(--color-borders);\n }\n\n .message-content.has-solid-background & {\n margin: .375rem -.5rem -.375rem;\n }\n\n .message-content.voice & {\n margin-bottom: -.5rem;\n }\n\n .message-content.audio & {\n margin-bottom: -.8125rem;\n }\n\n .message-content.audio &,\n .message-content.voice &,\n .message-content.poll &,\n .message-content.has-solid-background.text &,\n .message-content.has-solid-background.is-forwarded & {\n width: calc(100% + 1rem);\n }\n\n .icon-comments-sticker {\n display: none;\n }\n\n .icon-comments {\n font-size: 1.5625rem;\n line-height: 2rem;\n margin-inline-end: .875rem;\n }\n\n .icon-next {\n margin-inline-start: auto;\n font-size: 1.5rem;\n }\n\n .recent-repliers {\n display: inline-flex;\n align-items: center;\n margin-inline-end: .5rem;\n margin-inline-start: -.125rem;\n\n .Avatar {\n transition: border .15s;\n border: 2px solid var(--color-background);\n margin-inline-end: 0;\n z-index: 3;\n overflow: hidden;\n\n .emoji {\n width: 1rem;\n background-size: 1rem;\n }\n\n + .Avatar {\n z-index: 2;\n\n + .Avatar {\n z-index: 1;\n }\n }\n\n &:not(:first-child) {\n margin-inline-start: -.75rem;\n }\n }\n }\n\n &.has-unread .label {\n position: relative;\n\n &::after {\n content: '';\n display: inline-block;\n width: .5rem;\n height: .5rem;\n border-radius: 50%;\n background: var(--accent-color);\n margin-inline-start: \t.75rem;\n }\n }\n\n &.disabled {\n cursor: default;\n pointer-events: none;\n }\n}\n","// General styles\n.Message {\n display: flex;\n align-items: flex-end;\n margin-bottom: 0.375rem;\n position: relative;\n\n --background-color: var(--color-background);\n --hover-color: var(--color-reply-hover);\n --active-color: var(--color-reply-active);\n --max-width: 29rem;\n --accent-color: var(--color-primary);\n --accent-shade-color: var(--color-primary-shade);\n --secondary-color: var(--color-text-secondary);\n --meta-safe-area-base: 2.25rem;\n --meta-safe-author-width: 0px;\n --meta-safe-area-extra-width: 0px;\n --meta-safe-area-size: calc(var(--meta-safe-area-base) + var(--meta-safe-author-width) + var(--meta-safe-area-extra-width));\n --deleting-translate-x: -50%;\n --select-message-scale: 0.9;\n\n @media (min-width: 1921px) {\n --max-width: calc(30vw - 1rem);\n }\n\n &.is-swiped {\n transform: translateX(-2.5rem) !important;\n }\n\n &.is-protected {\n user-select: none;\n }\n\n > .Avatar,\n > .message-content-wrapper {\n opacity: 1;\n transform: scale(1) translateX(0);\n transition: transform var(--select-transition);\n\n body.animation-level-0 & {\n transition: none !important;\n }\n }\n\n > .Avatar {\n position: absolute;\n bottom: 0;\n left: 0;\n\n @media (max-width: 600px) {\n width: 2.5rem;\n height: 2.5rem;\n }\n }\n\n &.last-in-group {\n margin-bottom: 0.625rem;\n }\n\n &.last-in-list {\n // Forcing extra space which is taken by the appendix and causes incorrect container height calculation.\n // This value is accurately crafted as a minimum possible.\n margin-bottom: 0.375rem;\n }\n\n &.is-in-selection-mode {\n body.is-android & {\n .can-select-text {\n z-index: var(--z-message-select-control);\n }\n\n // Prevent media viewer from opening\n .media-inner {\n pointer-events: none;\n }\n }\n }\n\n &.has-inline-buttons {\n .message-content {\n border-bottom-right-radius: var(--border-radius-messages-small);\n }\n }\n\n &:not(.own) {\n padding-left: 2.5rem;\n\n .no-avatars &, &.is-thread-top {\n padding-left: 0;\n }\n\n @media (max-width: 600px) {\n padding-left: 2.875rem;\n\n .no-avatars &, &.is-thread-top {\n padding-left: 0.25rem;\n }\n }\n }\n\n &.own {\n flex-direction: row-reverse;\n --background-color: var(--color-background-own);\n --hover-color: var(--color-reply-own-hover);\n --active-color: var(--color-reply-own-active);\n --max-width: 30rem;\n --accent-color: var(--color-accent-own);\n --accent-shade-color: var(--color-green);\n --secondary-color: var(--color-accent-own);\n --color-code: var(--color-code-own);\n --color-code-bg: var(--color-code-own-bg);\n --color-links: var(--color-own-links);\n --meta-safe-area-base: 3.5rem;\n --deleting-translate-x: 50%;\n --color-text-green: var(--color-accent-own);\n\n @media (min-width: 1921px) {\n --max-width: 30vw;\n }\n\n body.is-ios &,\n body.is-macos & {\n --color-background-own: var(--color-background-own-apple);\n --color-reply-own-hover: var(--color-reply-own-hover-apple);\n --color-reply-own-active: var(--color-reply-own-active-apple);\n }\n\n @media (max-width: 600px) {\n padding-right: 0.25rem;\n }\n }\n\n &.is-deleting {\n > .Avatar,\n > .message-content-wrapper {\n transition: opacity .2s ease, transform .2s ease-in;\n opacity: 0;\n transform: scale(0.3) translateX(var(--deleting-translate-x));\n transform-origin: bottom;\n }\n }\n\n &.has-views {\n --meta-safe-area-extra-width: 4rem;\n }\n\n &.was-edited {\n --meta-safe-area-extra-width: 2.5rem;\n\n &.has-views {\n --meta-safe-area-extra-width: 7.5rem;\n }\n\n html[lang=ru] & {\n --meta-safe-area-extra-width: 3.5rem;\n\n &.has-views {\n --meta-safe-area-extra-width: 8.5rem;\n }\n }\n }\n\n .select-mode-active & {\n cursor: pointer;\n\n @media (min-width: 600px) {\n user-select: none;\n }\n\n &:not(.own) {\n > .Avatar,\n > .message-content-wrapper {\n transform: translateX(2.5rem);\n }\n }\n\n &:not(.is-album)::after {\n content: \"\";\n position: absolute;\n top: -0.25rem;\n bottom: -0.25rem;\n left: -4rem;\n right: -4rem;\n z-index: var(--z-message-select-area);\n }\n\n &.is-album,\n &.is-in-document-group {\n .message-select-control {\n pointer-events: unset;\n }\n }\n\n .message-select-control {\n opacity: 1;\n }\n }\n\n &.is-selected {\n .message-select-control {\n background: var(--color-green);\n\n &.group-select {\n background: transparent;\n\n &.is-selected {\n background: var(--color-green);\n }\n }\n }\n }\n\n .File.file-is-selected {\n .message-select-control {\n background: var(--color-green);\n }\n }\n\n &.is-in-document-group .File.file-is-selected .file-icon,\n &.has-menu-open.is-in-document-group .File .file-icon {\n --background-color: var(--color-background-selected);\n }\n\n &.own.is-in-document-group .File.file-is-selected .file-icon,\n &.own.has-menu-open.is-in-document-group .File .file-icon {\n --background-color: var(--color-background-own-selected);\n }\n\n .Audio .message-select-control {\n left: 1.0625rem;\n top: 1.375rem;\n }\n\n html.theme-dark &.own .Audio .toggle-play:not(.with-image) + .media-loading {\n .ProgressSpinner {\n background-image: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTUiIGhlaWdodD0iMTUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTguMjE4IDcuNWw1LjYzMy01LjYzM2EuNTA4LjUwOCAwIDEwLS43MTgtLjcxOEw3LjUgNi43ODIgMS44NjcgMS4xNDlhLjUwOC41MDggMCAxMC0uNzE4LjcxOEw2Ljc4MiA3LjVsLTUuNjMzIDUuNjMzYS41MDguNTA4IDAgMTAuNzE4LjcxOEw3LjUgOC4yMThsNS42MzMgNS42MzNhLjUwNi41MDYgMCAwMC43MTggMCAuNTA4LjUwOCAwIDAwMC0uNzE4TDguMjE4IDcuNXoiIGZpbGw9IiNGRkYiIGZpbGwtcnVsZT0ibm9uemVybyIgc3Ryb2tlPSIjODA3QkQ1IiBzdHJva2UtbGluZWpvaW49InJvdW5kIi8+PC9zdmc+);\n background-position: center;\n background-size: 1rem;\n\n circle {\n stroke: var(--background-color);\n }\n }\n }\n\n\n .File {\n position: relative;\n\n .message-select-control {\n position: absolute;\n top: 2rem;\n left: 2rem;\n z-index: 2;\n }\n }\n\n .album-item-select-wrapper {\n .Message.own & {\n background: var(--color-background-own);\n }\n\n .message-select-control {\n position: absolute;\n top: 0.438rem;\n right: 0.438rem;\n left: unset;\n }\n\n img, video {\n transition: transform var(--select-transition), opacity ease 300ms;\n }\n\n &.is-selected {\n .message-select-control {\n background: var(--color-green);\n }\n\n img, video {\n transform: scale(var(--select-message-scale));\n }\n }\n\n }\n\n &.is-selected, &.is-forwarding {\n .message-select-control {\n background: var(--color-green);\n }\n\n .Menu .bubble {\n transition: none !important;\n }\n }\n\n &.is-in-document-group {\n &:not(.first-in-document-group) {\n &::before {\n top: 0 !important;\n }\n\n .message-content {\n box-shadow: none;\n border-top-left-radius: 0 !important;\n border-top-right-radius: 0 !important;\n }\n\n .forwarded-message::before {\n top: -1.5rem;\n }\n }\n\n &:not(.last-in-document-group) {\n margin-bottom: 0;\n\n &::before {\n bottom: 0 !important;\n }\n\n .message-content {\n border-bottom-left-radius: 0 !important;\n border-bottom-right-radius: 0 !important;\n }\n }\n\n &.is-in-selection-mode {\n .Audio:not(.audio-is-selected),\n .File:not(.file-is-selected) {\n .message-select-control:not(.group-select) {\n background: white;\n\n &::after {\n content: '';\n width: 1.25rem;\n height: 1.25rem;\n border-radius: 0.688rem;\n background: white;\n border: 0.125rem rgba(0, 0, 0, 0.2) solid;\n position: absolute;\n }\n }\n }\n\n &.own {\n .message-content {\n .Audio:not(.audio-is-selected),\n .File:not(.file-is-selected) {\n .message-select-control:not(.group-select) {\n background: var(--background-color);\n border-color: var(--background-color);\n\n &::after {\n background: var(--background-color);\n border-color: var(--color-message-meta-own);\n }\n }\n }\n }\n }\n\n }\n\n &.focused,\n &.has-menu-open,\n &.is-forwarding,\n &.is-selected {\n .message-content {\n background: var(--color-background-selected);\n }\n\n &.own {\n .message-content {\n --background-color: var(--color-background-own-selected);\n background: var(--color-background-own-selected);\n }\n }\n }\n\n .message-content-wrapper {\n width: 17.1875rem;\n }\n\n .message-content {\n transition: background-color var(--select-transition);\n }\n\n &.own {\n .message-content-wrapper {\n display: flex;\n justify-content: flex-end;\n\n .message-content {\n width: 100%;\n }\n }\n }\n }\n\n .album-item-select-wrapper {\n position: absolute;\n\n .message-select-control {\n position: absolute;\n z-index: 2;\n }\n }\n\n .message-select-control {\n position: absolute;\n left: 0;\n bottom: 0.25rem;\n width: 1.5rem;\n height: 1.5rem;\n border: 2px solid white;\n border-radius: 50%;\n z-index: var(--z-message-select-control);\n\n display: flex;\n align-items: center;\n justify-content: center;\n\n color: white;\n font-size: 1rem;\n\n opacity: 0;\n pointer-events: none;\n transition: opacity var(--select-transition);\n\n .icon-select {\n position: absolute;\n left: -3px;\n top: -3px;\n font-size: 1.625rem;\n }\n\n .theme-dark & {\n border-color: #ffffff80;\n }\n }\n\n .Avatar {\n margin-right: 0.3rem;\n }\n\n &.is-in-document-group {\n .message-content.document {\n padding: .25rem .5rem !important;\n }\n\n &.last-in-document-group {\n .message-content.document {\n padding-bottom: .5rem !important\n }\n }\n\n &.first-in-document-group {\n .message-content.document {\n padding-top: .5rem !important\n }\n }\n }\n}\n\n// Border-radius styles\n.message-content,\n.Album,\n.media-inner,\n.message-content.media .media-inner img,\n.message-content.media .media-inner video,\n.message-content.custom-shape .media-inner img {\n border-top-left-radius: var(--border-top-left-radius);\n border-top-right-radius: var(--border-top-right-radius);\n border-bottom-left-radius: var(--border-bottom-left-radius);\n border-bottom-right-radius: var(--border-bottom-right-radius);\n}\n\n.media-inner video.full-media {\n background: transparent !important;\n}\n\n.media-inner {\n overflow: hidden;\n\n &.small-image img {\n border-radius: 0 !important;\n }\n}\n\n.Message {\n --border-top-left-radius: var(--border-radius-messages);\n --border-top-right-radius: var(--border-radius-messages);\n --border-bottom-left-radius: var(--border-radius-messages);\n --border-bottom-right-radius: var(--border-radius-messages);\n\n &:not(.own) {\n &.first-in-group:not(.last-in-group) {\n --border-bottom-left-radius: var(--border-radius-messages-small);\n }\n\n &:not(.first-in-group):not(.last-in-group) {\n --border-top-left-radius: var(--border-radius-messages-small);\n --border-bottom-left-radius: var(--border-radius-messages-small);\n }\n\n &.last-in-group:not(.first-in-group) {\n --border-top-left-radius: var(--border-radius-messages-small);\n }\n\n &.last-in-group {\n --border-bottom-left-radius: var(--border-radius-messages-small);\n\n .message-content.has-appendix {\n --border-bottom-left-radius: 0;\n }\n }\n }\n\n &.own {\n &.first-in-group:not(.last-in-group) {\n --border-bottom-right-radius: var(--border-radius-messages-small);\n }\n\n &:not(.first-in-group):not(.last-in-group) {\n --border-top-right-radius: var(--border-radius-messages-small);\n --border-bottom-right-radius: var(--border-radius-messages-small);\n }\n\n &.last-in-group:not(.first-in-group) {\n --border-top-right-radius: var(--border-radius-messages-small);\n }\n\n &.last-in-group {\n --border-bottom-right-radius: var(--border-radius-messages-small);\n\n .message-content.has-appendix {\n --border-bottom-right-radius: 0;\n border-bottom-right-radius: 0;\n }\n }\n }\n\n .message-content {\n &.has-replies:not(.custom-shape),\n &.text {\n .media-inner,\n .Album {\n --border-bottom-left-radius: 0;\n --border-bottom-right-radius: 0;\n }\n }\n\n &.is-reply .EmbeddedMessage {\n & + .Album,\n & + .Audio,\n & + .File {\n margin-top: .375rem;\n }\n }\n\n &:not(.custom-shape).is-reply .media-inner,\n &:not(.custom-shape).is-reply .Album,\n &:not(.custom-shape).force-sender-name .Album,\n &:not(.is-forwarded) .message-title ~ .media-inner {\n --border-top-left-radius: 0;\n --border-top-right-radius: 0;\n }\n\n &.is-forwarded .content-inner .message-title {\n margin-bottom: 0.25rem;\n }\n }\n\n .message-action-button {\n position: absolute;\n bottom: 0;\n color: white;\n background-color: rgba(0, 0, 0, .2);\n\n opacity: 0;\n transition: opacity .2s ease;\n\n @media (pointer: coarse) {\n opacity: 1 !important;\n }\n\n &:hover,\n &:active,\n &:focus {\n background-color: rgba(0, 0, 0, .28) !important;\n }\n }\n\n &:hover,\n &[data-is-document-group-hover] {\n .message-action-button {\n opacity: 1;\n }\n }\n\n &.own .message-action-button {\n left: -3rem;\n }\n\n &:not(.own) .message-action-button {\n right: -3rem;\n }\n\n .bottom-marker {\n height: 1px;\n width: 1px;\n visibility: hidden;\n }\n}\n\n.Message .custom-shape .message-action-button {\n bottom: .25rem;\n}\n\n@import 'message-content';\n",".message-content {\n position: relative;\n max-width: var(--max-width);\n\n @media (max-width: 600px) {\n max-width: calc(100vw - 6.25rem);\n\n .Message.own &,\n .MessageList.no-avatars & {\n max-width: calc(100vw - 3.75rem);\n }\n\n // Workaround for sass function override - we should use CSS min() here\n @supports (max-width: #{\"min(29rem, 100vw - 6.25rem)\"}) {\n max-width: #{\"min(29rem, 100vw - 6.25rem)\"};\n .MessageList.no-avatars & {\n max-width: #{\"min(29rem, 100vw - 3.75rem)\"};\n }\n .Message.own & {\n max-width: #{\"min(30rem, 100vw - 3.75rem)\"};\n }\n }\n\n &.has-action-button {\n max-width: calc(100vw - 7rem);\n\n .Message.own &,\n .MessageList.no-avatars & {\n max-width: calc(100vw - 4.5rem);\n }\n\n // Workaround for sass function override - we should use CSS min() here\n @supports (max-width: #{\"min(29rem, 100vw - 5.5rem)\"}) {\n max-width: #{\"min(29rem, 100vw - 7rem)\"};\n .MessageList.no-avatars & {\n max-width: #{\"min(29rem, 100vw - 4.5rem)\"};\n }\n .Message.own & {\n max-width: #{\"min(30rem, 100vw - 4.5rem)\"};\n }\n }\n }\n }\n\n img {\n -webkit-touch-callout: none;\n -webkit-user-select: none;\n }\n\n .text-content {\n margin: 0;\n word-break: break-word;\n line-height: 1.3125;\n text-align: initial;\n display: flow-root;\n unicode-bidi: plaintext;\n }\n\n .text-entity-link {\n unicode-bidi: plaintext;\n }\n\n &:not(.custom-shape) .text-content,\n &.document {\n & > .MessageMeta {\n position: relative;\n top: .375rem;\n bottom: auto !important;\n float: right;\n line-height: 1.35;\n height: calc(var(--message-meta-height, 1rem));\n margin-left: .4375rem;\n margin-right: -.5rem;\n\n .MessageOutgoingStatus .Transition {\n max-height: calc(var(--message-meta-height, 1rem));\n overflow: hidden;\n }\n\n html[data-message-text-size=\"12\"] & {\n top: .25rem;\n }\n\n html[data-message-text-size=\"17\"] & {\n top: .4375rem;\n }\n\n html[data-message-text-size=\"18\"] &,\n html[data-message-text-size=\"19\"] & {\n top: .5rem;\n }\n\n html[data-message-text-size=\"20\"] & {\n top: .5625rem;\n }\n }\n\n &:dir(rtl) {\n & > .MessageMeta {\n float: left;\n margin-left: -.25rem;\n margin-right: .4375rem;\n }\n }\n }\n\n &.document:not(.text) {\n &::after {\n content: \"\";\n display: block;\n clear: both;\n }\n\n & > .MessageMeta {\n top: auto !important;\n bottom: -.5rem !important;\n margin-top: -.25rem;\n\n &:not([dir=rtl]) {\n margin-top: -1.25rem;\n }\n }\n }\n\n .theme-dark .Message.own & {\n .text-entity-link {\n text-decoration: underline !important;\n\n &:hover {\n text-decoration: none !important;\n }\n }\n }\n\n &:not(.custom-shape) {\n font-size: var(--message-text-size, 1rem);\n\n body.is-ios & {\n font-size: var(--message-text-size, 1.0625rem);\n }\n\n & > .content-inner {\n min-width: 0;\n }\n }\n\n .matching-text-highlight {\n background: #CAE3F7;\n border-radius: 0.25rem;\n padding: 0 0.125rem;\n }\n\n .message-title {\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n font-size: calc(var(--message-text-size, 1rem) - .125rem);\n font-weight: 500;\n line-height: 1.25rem;\n color: var(--accent-color);\n unicode-bidi: plaintext;\n display: flex;\n\n & > .interactive {\n overflow: hidden;\n text-overflow: ellipsis;\n }\n\n &.interactive, & > .interactive {\n cursor: pointer;\n\n &:hover {\n opacity: 0.85;\n }\n }\n\n & > .color-1 {\n color: var(--color-user-1);\n }\n\n & > .color-2 {\n color: var(--color-user-2);\n }\n\n & > .color-4 {\n color: var(--color-user-4);\n }\n\n & > .color-5 {\n color: var(--color-user-5);\n }\n\n & > .color-6 {\n color: var(--color-user-6);\n }\n\n & > .color-7 {\n color: var(--color-user-7);\n }\n\n & > .color-8 {\n color: var(--color-user-8);\n }\n\n .theme-dark .Message.own & > .color-1 {\n color: var(--accent-color);\n }\n\n & + .File {\n margin-top: .25rem;\n }\n\n .via {\n padding-right: .25rem;\n font-weight: 400;\n }\n\n span + .via {\n padding-left: .25rem;\n }\n\n .admin-title {\n flex: 1;\n margin-left: 1rem;\n text-align: right;\n font-weight: 400;\n font-size: 0.75rem;\n margin-top: -0.1rem;\n color: rgba(var(--color-text-meta-rgb), 0.75);\n\n .Message.own & {\n color: var(--accent-color);\n }\n }\n }\n\n &.has-shadow {\n box-shadow: 0 1px 2px var(--color-default-shadow);\n }\n\n &.has-solid-background, &.has-background, .is-album & {\n background: var(--background-color);\n }\n\n &.has-solid-background {\n padding: .3125rem .5rem .375rem;\n\n .forwarded-message > .text-content:not(.with-meta):last-child::after {\n content: '';\n display: inline-block;\n width: var(--meta-safe-area-size);\n height: 1rem;\n }\n }\n\n body.is-ios &.has-solid-background {\n padding-bottom: 0.4375rem;\n }\n\n body.is-ios .Message.own &.has-solid-background {\n padding-left: 0.625rem;\n }\n\n &:not(.has-appendix) .svg-appendix {\n display: none;\n }\n\n .svg-appendix {\n overflow: hidden;\n position: absolute;\n bottom: -.0625rem;\n width: .5625rem;\n height: 1.125rem;\n font-size: 1rem !important;\n\n .corner {\n fill: var(--background-color);\n }\n\n .Message.own & {\n right: -.551rem; // This value is correct. Safari fix\n }\n\n .Message:not(.own) & {\n left: -.562rem; // This value is correct. Safari fix\n }\n }\n\n &[data-has-custom-appendix] {\n .svg-appendix .corner {\n fill: var(--appendix-bg);\n }\n }\n\n &.has-appendix-thumb {\n .Message & {\n .svg-appendix {\n --background-color: #ccc;\n opacity: 1;\n transition: opacity 500ms ease;\n }\n }\n }\n\n &.document {\n padding: .5rem !important;\n\n .File {\n .theme-dark & {\n --color-primary: var(--color-selection-highlight);\n }\n }\n\n .File + .text-content {\n margin-top: .3125rem;\n }\n }\n\n &.voice,\n &.audio {\n .message-title,\n .Embedded {\n margin-top: -.1875rem;\n margin-bottom: .1875rem;\n }\n }\n\n &.voice {\n padding: .5rem !important;\n\n .Voice + .text-content {\n margin-top: .5rem;\n }\n }\n\n &.audio {\n min-width: 20rem;\n padding: .5rem .5rem .8125rem !important;\n\n @media (max-width: 600px) {\n min-width: 17rem;\n }\n\n .Audio + .text-content {\n margin-top: .25rem;\n }\n\n &:not(.has-replies) {\n .Audio + .text-content {\n margin-bottom: -0.4375rem;\n }\n }\n }\n\n &:not(.custom-shape) .emoji {\n display: inline-block;\n width: 1.25rem;\n background-size: 1.25rem;\n color: transparent;\n margin-inline-end: 1px;\n vertical-align: text-bottom;\n\n &::selection {\n background-color: var(--color-selection-highlight-emoji);\n color: transparent;\n }\n }\n\n &:not(.custom-shape) .text-content .emoji {\n width: calc(1.25 * var(--message-text-size, 1rem));\n height: calc(1.25 * var(--message-text-size, 1rem));\n background-size: calc(1.25 * var(--message-text-size, 1rem));\n }\n\n .no-media-corners {\n --border-top-left-radius: 0;\n --border-top-right-radius: 0;\n }\n\n &.custom-shape.is-via-bot {\n font-size: inherit !important;\n\n .content-inner > .message-title {\n display: inline-flex;\n position: relative;\n top: .125rem;\n max-width: calc(100% - 3rem);\n margin-left: calc(100% - 3rem);\n padding: 0 .5rem;\n background-color: var(--background-color);\n border-radius: var(--border-radius-messages);\n\n .Message.own & {\n margin-left: -3rem;\n }\n }\n\n .media-inner {\n margin-top: 0.375rem;\n }\n }\n\n}\n\n.message-content.media, .WebPage {\n .media-inner {\n display: flex;\n justify-content: center;\n align-items: center;\n\n &.interactive {\n cursor: pointer;\n\n &.dark video {\n background-color: #232323;\n }\n }\n }\n\n &.round.is-reply {\n width: auto !important;\n }\n\n &.force-sender-name .media-inner,\n &.force-sender-name .Album,\n &.text .media-inner,\n &.is-via-bot .media-inner,\n &.is-reply .media-inner,\n &.is-reply .Album {\n margin-left: -0.5rem;\n margin-right: -0.5rem;\n\n body.is-ios .Message.own & {\n margin-left: -0.625rem;\n }\n }\n\n &.text .media-inner {\n margin-top: -0.3125rem;\n }\n\n &.is-reply .media-inner,\n &.force-sender-name .Album,\n &.is-reply .Album,\n .message-title ~ .media-inner {\n margin-top: 0.375rem;\n margin-bottom: -0.375rem;\n\n body.is-ios .Message.own & {\n margin-bottom: -0.4375rem;\n }\n }\n\n // Moved below .is-reply to overwrite its styles\n &.text .media-inner,\n &.text .Album {\n margin-bottom: 0.375rem;\n\n body.is-ios .Message.own & {\n margin-bottom: 0.375rem;\n }\n }\n\n .media-loading {\n display: flex;\n align-items: center;\n justify-content: center;\n\n &:not(.open) {\n opacity: 0.5;\n transform: scale(0);\n transition: opacity .3s ease, transform .3s ease;\n }\n }\n\n .icon-large-play, .icon-download {\n position: absolute;\n display: flex;\n align-items: center;\n justify-content: center;\n color: #fff;\n opacity: 0.7;\n transition: opacity 150ms;\n\n &:hover {\n opacity: 1;\n }\n\n &:before {\n display: flex;\n align-items: center;\n justify-content: center;\n width: 3.375rem;\n height: 3.375rem;\n border-radius: 50%;\n background: rgba(black, 0.25);\n }\n\n &.opacity-transition {\n transition: opacity .15s ease;\n\n &:not(.open) {\n opacity: 0;\n }\n }\n }\n\n .icon-download {\n font-size: 1.5rem;\n }\n\n .icon-large-play {\n font-size: 2.5rem;\n }\n\n .message-media-duration,\n .message-transfer-progress {\n background: rgba(0, 0, 0, .25);\n color: #fff;\n font-size: 0.75rem;\n position: absolute;\n left: .1875rem;\n top: .1875rem;\n z-index: 1;\n padding: 0 .375rem;\n border-radius: .75rem;\n line-height: 1.125rem;\n user-select: none;\n }\n\n .message-media-duration .icon-muted {\n vertical-align: -.1875rem;\n margin-left: .375rem;\n font-size: 1.0625rem;\n }\n}\n\n.message-content.custom-shape {\n line-height: 1.2;\n font-size: 10rem;\n display: flex;\n flex-wrap: wrap;\n align-items: flex-end;\n\n &.has-comments {\n min-height: 5.25rem;\n margin-top: 0 !important;\n\n &.has-replies {\n min-height: 6.5rem;\n }\n }\n\n &.is-reply {\n max-width: 100%;\n }\n\n .reply-message {\n display: flex;\n align-items: flex-start;\n flex-direction: row-reverse;\n direction: ltr;\n\n > p {\n margin-bottom: 0;\n }\n\n .EmbeddedMessage {\n margin-left: 0.5rem;\n border-radius: var(--border-radius-messages);\n\n @media (max-width: 600px) {\n max-width: calc(90vw - 13rem);\n }\n\n @media (max-width: 340px) {\n margin-left: -1rem;\n z-index: 1;\n max-width: calc(90vw - 12rem);\n }\n }\n }\n\n .text-content {\n margin-bottom: 1rem;\n }\n\n .media-inner {\n line-height: 1;\n font-size: 1rem;\n flex-shrink: 0;\n\n .full-media {\n top: 0;\n left: 0;\n bottom: 0;\n right: 0;\n }\n }\n\n .emoji {\n display: inline-block;\n color: transparent;\n\n &::selection {\n background-color: var(--color-selection-highlight-emoji);\n color: transparent;\n }\n }\n\n &.emoji-only {\n .text-content {\n margin-bottom: 0;\n text-shadow: 1px 1px 0 white, -1px -1px 0 white, -1px 1px 0 white, 1px -1px 0 white;\n img.emoji {\n filter: drop-shadow(1px 1px 0 white) drop-shadow(-1px 1px 0 white) drop-shadow(1px -1px 0 white) drop-shadow(-1px -1px 0 white);\n }\n\n .MessageMeta {\n text-shadow: none;\n }\n }\n }\n\n &.emoji-only-1 {\n min-width: 8rem;\n font-size: 4.5rem;\n\n .content-inner {\n height: 7rem;\n }\n\n .text-content {\n line-height: 1.5;\n text-align: center;\n }\n\n .Message.was-edited & {\n min-width: 10rem;\n }\n\n .emoji {\n width: 5rem;\n height: 5rem;\n }\n }\n\n &.emoji-only-2 {\n font-size: 4rem;\n margin-top: .5rem;\n min-width: 10rem;\n\n &.has-comments {\n margin-top: 1.25rem;\n }\n\n .Message.was-edited & {\n min-width: 12rem;\n }\n\n .emoji {\n width: 4rem;\n height: 4rem;\n margin-right: 0.375rem;\n }\n }\n\n &.emoji-only-3 {\n font-size: 3rem;\n margin-top: 1.75rem;\n min-width: 12rem;\n\n &.has-comments {\n margin-top: 2.5rem;\n }\n\n .Message.was-edited & {\n min-width: 14rem;\n }\n\n .emoji {\n width: 3rem;\n height: 3rem;\n margin-right: 0.375rem;\n }\n }\n\n .Message:not(.own) & {\n --hover-color: var(--color-reply-hover);\n --active-color: var(--color-reply-active);\n }\n\n .Message.own & {\n --hover-color: var(--color-reply-own-hover);\n --active-color: var(--color-reply-own-active);\n\n .reply-message {\n flex-direction: row;\n\n .EmbeddedMessage {\n margin-right: 0.5rem;\n\n @media (max-width: 340px) {\n margin-left: 0;\n z-index: 1;\n max-width: calc(90vw - 11.5rem);\n }\n }\n }\n }\n}\n\n.forwarded-message {\n .message-content.contact &,\n .message-content.voice &,\n .message-content.poll & {\n // MessageOutgoingStatus's icon needs more space\n margin-bottom: 0.5rem;\n }\n\n .message-content:not(.custom-shape) & {\n position: relative;\n margin-top: 0.25rem;\n padding-left: 0.625rem;\n\n &::before {\n content: '';\n display: block;\n position: absolute;\n top: 0;\n bottom: 0;\n left: 0.05rem;\n width: 2px;\n background: var(--accent-color);\n border-radius: 2px;\n }\n\n &:dir(rtl) {\n padding-inline-start: 0.625rem;\n\n &::before {\n left: auto;\n right: 0.05rem;\n }\n }\n }\n\n --border-top-left-radius: var(--border-radius-messages-small);\n --border-top-right-radius: var(--border-radius-messages-small);\n --border-bottom-left-radius: var(--border-radius-messages-small);\n --border-bottom-right-radius: var(--border-radius-messages-small);\n\n > .media-inner {\n margin: 0 !important;\n margin-bottom: 0.25rem !important;\n }\n}\n\n.long-word-break-all {\n word-break: break-all;\n}\n\n.text-entity-link {\n color: var(--color-links) !important;\n text-decoration: none !important;\n word-break: break-word;\n cursor: pointer;\n unicode-bidi: initial;\n\n &:hover, &:active, &:visited {\n text-decoration: underline !important;\n }\n}\n\n.text-entity-code, .text-entity-pre {\n color: var(--color-code);\n background: var(--color-code-bg);\n white-space: pre-wrap;\n margin: 0;\n padding: 1px 2px;\n border-radius: 4px;\n font-size: calc(var(--message-text-size, 1rem) - 0.0625rem);\n}\n",".SponsoredMessage {\n --border-top-left-radius: var(--border-radius-messages) !important;\n --border-bottom-left-radius: var(--border-radius-messages) !important;\n\n margin-top: -.5rem;\n margin-bottom: .5rem;\n\n &::before {\n display: none;\n }\n\n &__button.secondary {\n margin-top: .5rem;\n border: 1px solid var(--color-primary);\n border-radius: var(--border-radius-default-tiny);\n color: var(--color-primary);\n }\n}\n",".ContactGreeting {\n width: 100%;\n height: 100%;\n display: flex;\n align-items: center;\n justify-content: center;\n text-align: center;\n\n .wrapper {\n display: inline-flex;\n flex-direction: column;\n align-items: center;\n background: var(--pattern-color);\n width: 14.5rem;\n padding: .75rem 1rem;\n border-radius: 1.5rem;\n color: #fff;\n }\n\n .title {\n font-weight: 500;\n margin-bottom: 0;\n }\n\n .description {\n font-size: .9375rem;\n margin-bottom: 0;\n }\n\n .sticker {\n margin: 2rem 0 1rem;\n height: 10rem;\n width: 10rem;\n cursor: pointer;\n\n .thumbnail {\n height: 10rem;\n width: 10rem;\n }\n }\n}\n",".NoMessages {\n width: 100%;\n height: 100%;\n display: flex;\n align-items: center;\n justify-content: center;\n\n .icon {\n font-size: 5rem;\n margin: 0 auto 1rem;\n }\n\n .wrapper {\n display: inline-flex;\n flex-direction: column;\n background: var(--pattern-color);\n max-width: 20rem;\n padding: .75rem 1rem;\n border-radius: 1.5rem;\n color: #fff;\n\n &[dir=rtl] {\n text-align: right;\n }\n }\n\n .title {\n font-weight: 500;\n font-size: 1rem;\n margin-bottom: .25rem;\n text-align: center;\n unicode-bidi: plaintext;\n }\n\n .description {\n font-size: .9375rem;\n margin: 0;\n padding: 0;\n list-style: none;\n unicode-bidi: plaintext;\n }\n\n .list-checkmarks {\n font-size: .9375rem;\n margin: .25rem 0 0;\n padding: 0;\n list-style: none;\n unicode-bidi: plaintext;\n line-height: 1.8;\n\n li::before {\n content: '✓';\n margin-inline-end: .5rem;\n }\n }\n}\n","@import '../../styles/mixins';\n\n.MessageList {\n flex: 1;\n width: 100%;\n margin-bottom: .5rem;\n\n overflow: scroll;\n overflow-x: hidden;\n overflow-y: auto;\n @include overflow-y-overlay();\n\n transition: transform var(--layer-transition);\n\n body.animation-level-0 & {\n transition: none !important;\n }\n\n .mask-image-enabled & {\n mask-image: linear-gradient(to top, transparent 0, #000 0.5rem);\n }\n\n @media (pointer: coarse) {\n user-select: none;\n touch-callout: none;\n\n &.select-mode-active {\n user-select: auto;\n touch-callout: default;\n }\n }\n\n @supports (padding-bottom: env(safe-area-inset-bottom)) {\n transition: bottom 150ms ease-out, transform var(--layer-transition);\n body.keyboard-visible & {\n position: relative;\n bottom: calc(0px - env(safe-area-inset-bottom));\n\n body.keyboard-visible.animation-level-0 & {\n transition: none !important;\n }\n }\n }\n\n &.no-avatars .Message > .Avatar {\n display: none;\n }\n\n .messages-container {\n width: 100%;\n max-width: var(--messages-container-width);\n min-height: 100%;\n margin: 0 auto;\n display: flex;\n justify-content: flex-end;\n flex-direction: column;\n padding: 1rem 1rem 0 1.125rem;\n\n .force-messages-scroll & {\n margin-top: 100vh !important;\n }\n\n @media (max-width: 600px) {\n width: 100vw;\n padding: 2.75rem 0.5rem 0;\n // Patch for an issue on Android when rotating device\n margin: 0;\n }\n }\n\n &.no-composer {\n margin-bottom: 0;\n\n .last-in-list {\n margin-bottom: 1rem;\n }\n }\n\n &.select-mode-active, &.type-pinned {\n margin-bottom: 0;\n\n .last-in-list {\n margin-bottom: 5.625rem;\n\n @media (max-width: 600px) {\n margin-bottom: 4.25rem;\n }\n\n &.ActionMessage {\n padding-bottom: 0.125rem;\n }\n }\n }\n\n @media (max-width: 600px) {\n &.with-bottom-shift {\n margin-bottom: 0;\n .last-in-list {\n margin-bottom: 4.25rem;\n\n @supports (padding-bottom: env(safe-area-inset-bottom)) {\n body:not(.keyboard-visible) & {\n margin-bottom: calc(4.25rem + env(safe-area-inset-bottom));\n }\n }\n }\n }\n }\n\n .Message,\n .ActionMessage {\n position: relative;\n\n opacity: 1;\n transform: scale(1);\n transition: opacity .2s ease, transform .2s ease;\n\n &:not(.open) {\n transform: scale(0.8);\n opacity: 0;\n }\n\n // Restore stacking context\n // https://developer.mozilla.org/ru/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context\n &.open.shown {\n transform: none;\n }\n\n &::before {\n content: \"\";\n position: absolute;\n top: -0.1875rem;\n bottom: -0.1875rem;\n left: -50vw;\n right: -50vw;\n background: black;\n z-index: -1;\n\n opacity: 0;\n transition: opacity var(--select-transition);\n\n body.animation-level-0 & {\n transition: none !important;\n }\n }\n\n &:not(.last-in-group) {\n &::before {\n bottom: -0.1875rem;\n }\n }\n\n &:not(.first-in-group) {\n &::before {\n top: -0.1875rem;\n }\n }\n\n &.focused::before {\n // @optimization\n transition: none !important;\n }\n\n &.focused,\n &.is-forwarding,\n &.is-selected,\n &.has-menu-open {\n &::before {\n opacity: 0.1;\n\n .theme-dark & {\n opacity: .6;\n }\n }\n }\n }\n\n > .empty {\n width: 100%;\n height: 100%;\n display: flex;\n align-items: center;\n justify-content: center;\n\n & > span {\n max-width: 80%;\n text-align: left;\n }\n\n .text-entity-link {\n color: inherit !important;\n text-decoration: underline;\n\n &:hover, &:focus {\n text-decoration: none;\n }\n }\n }\n\n .sticky-date,\n .local-action-message,\n .ActionMessage,\n .empty {\n text-align: center;\n user-select: none;\n\n > span {\n display: inline-block;\n background: var(--pattern-color);\n color: white;\n font-size: calc(var(--message-text-size, 1rem) - .0625rem);\n font-weight: 500;\n line-height: 1.75;\n padding: 0 .5rem;\n border-radius: var(--border-radius-messages);\n word-break: break-word;\n\n body.is-ios &,\n body.is-macos & {\n font-size: calc(var(--message-text-size, 1rem) - .125rem);\n line-height: calc(var(--message-text-size, 1rem) + .5rem);\n }\n\n .emoji-small {\n vertical-align: text-bottom;\n width: calc(1.25 * var(--message-text-size, 1rem));\n height: calc(1.25 * var(--message-text-size, 1rem));\n background-size: calc(1.25 * var(--message-text-size, 1rem));\n }\n }\n }\n\n .sticky-date {\n margin-top: 1rem;\n margin-bottom: 1rem;\n z-index: var(--z-sticky-date);\n pointer-events: none;\n opacity: 1;\n transition: opacity .3s ease;\n\n body:not(.is-scrolling-messages) &.stuck {\n opacity: 0;\n\n span {\n pointer-events: none;\n }\n }\n\n body.animation-level-0 & {\n transition: none;\n }\n\n &.interactive {\n cursor: pointer;\n }\n\n span {\n pointer-events: auto;\n }\n }\n\n &.scrolled:not(.is-animating) .sticky-date {\n position: sticky;\n top: 0.625rem;\n }\n\n &.is-animating {\n overflow: hidden;\n }\n\n &.is-animating .message-select-control {\n display: none !important;\n }\n\n .has-header-tools & .sticky-date {\n top: 3.75rem !important;\n }\n\n .local-action-message,\n .ActionMessage {\n margin-top: 0.5rem;\n margin-bottom: 0.5rem;\n }\n\n .ActionMessage {\n .action-link {\n cursor: pointer;\n\n &:hover {\n text-decoration: underline;\n }\n }\n }\n\n .sticky-date + .ActionMessage {\n margin-top: -0.5rem;\n }\n\n @media (min-width: 1276px) {\n width: 100%;\n transform: translate3d(0, 0, 0);\n transition: transform var(--layer-transition);\n\n .messages-container {\n width: calc(100% - var(--right-column-width));\n }\n\n body.animation-level-0 & {\n transition: none;\n }\n\n #Main.right-column-open & {\n transform: translate3d(calc(var(--right-column-width) / -2), 0, 0);\n }\n\n body:not(.animating-right-column) #Main.right-column-open &.select-mode-active,\n #Main.right-column-open &:not(.select-mode-active),\n body.animating-right-column &:not(.select-mode-active) {\n width: calc(100% - var(--right-column-width));\n\n .messages-container {\n width: 100%;\n }\n }\n }\n\n @media (max-width: 600px) {\n transition: transform var(--layer-transition);\n\n body.enable-symbol-menu-transforms & {\n transform: translate3d(0, 0, 0);\n }\n\n body.is-symbol-menu-open & {\n transform: translate3d(0, calc(-1 * (var(--symbol-menu-height) + var(--symbol-menu-footer-height))), 0);\n }\n }\n\n .animating > div > & {\n &::-webkit-scrollbar {\n width: 0;\n }\n\n /* Styles for Firefox */\n @supports (scrollbar-width: none) {\n padding-right: .6875rem;\n scrollbar-width: none;\n }\n }\n}\n",".ScrollDownButton {\n --base-bottom-pos: 6rem;\n\n position: absolute;\n bottom: var(--base-bottom-pos);\n right: 1rem;\n opacity: 0;\n transform: translateY(4.5rem);\n transition: transform .25s cubic-bezier(0.34, 1.56, 0.64, 1), opacity .2s ease;\n z-index: var(--z-scroll-down-button);\n pointer-events: none;\n\n @supports (right: env(safe-area-inset-right)) {\n right: #{\"max(1rem, env(safe-area-inset-right))\"};\n }\n\n body.animation-level-0 & {\n transform: none !important;\n\n transition: opacity .15s;\n }\n\n @media (max-width: 600px) {\n right: 0.5rem;\n bottom: 4.5rem;\n\n @supports (padding-bottom: env(safe-area-inset-bottom)) {\n body:not(.keyboard-visible) & {\n bottom: calc(4.5rem + env(safe-area-inset-bottom));\n }\n }\n }\n\n &-inner {\n display: flex;\n flex-direction: column;\n align-items: center;\n\n > .Button {\n box-shadow: 0 1px 2px var(--color-default-shadow);\n color: var(--color-composer-button);\n\n i {\n font-size: 1.75rem;\n }\n }\n\n @media (min-width: 1276px) {\n transform: translateX(0);\n\n transition: transform var(--layer-transition);\n\n body.animation-level-0 & {\n transition: none !important;\n }\n\n #Main.right-column-open & {\n transform: translateX(calc(-1 * var(--right-column-width)));\n }\n }\n\n @media (max-width: 600px) {\n > .Button {\n width: 2.875rem;\n height: 2.875rem;\n }\n }\n }\n\n &.revealed {\n transform: translateY(0);\n opacity: 1;\n pointer-events: all;\n\n &.no-composer:not(.with-extra-shift) {\n transform: translateY(4rem);\n }\n }\n\n .unread-count {\n min-width: 1.5rem;\n height: 1.5rem;\n padding: 0 .45rem;\n border-radius: 0.75rem;\n font-size: 0.875rem;\n line-height: 1.5rem;\n font-weight: 500;\n text-align: center;\n\n position: absolute;\n top: -0.3rem;\n right: -0.3rem;\n\n background: var(--color-green);\n color: white;\n\n pointer-events: none;\n\n @media (max-width: 600px) {\n top: -0.7rem;\n right: auto;\n }\n }\n\n @media (max-width: 600px) {\n body.is-symbol-menu-open & {\n bottom: calc(var(--base-bottom-pos) + var(--symbol-menu-height) + var(--symbol-menu-footer-height));\n }\n }\n}\n",".BotKeyboardMenu {\n .bubble {\n width: 100% !important;\n max-width: 27rem;\n border-radius: var(--border-radius-default-small);\n }\n\n .content {\n display: flex;\n flex-direction: column;\n padding: .1875rem .625rem;\n max-height: 80vh;\n overflow: auto;\n\n @media (max-width: 600px) {\n max-height: 75vh;\n }\n\n .row {\n display: flex;\n flex-direction: row;\n }\n\n .row + .row {\n margin-top: .375rem;\n }\n\n .Button {\n flex: 1;\n width: auto;\n height: auto;\n min-height: 3.0625rem;\n border-radius: var(--border-radius-messages-small);\n border: 2px solid var(--color-primary);\n background: var(--color-background);\n color: var(--color-primary);\n font-weight: 500;\n text-transform: none;\n\n &:hover {\n color: #fff;\n border-color: var(--color-primary-shade);\n background: var(--color-primary-shade);\n }\n }\n\n .Button + .Button {\n margin-left: .375rem;\n }\n }\n}\n",".ComposerEmbeddedMessage {\n height: 2.625rem;\n transition: height 150ms ease-out, opacity 150ms ease-out;\n\n .select-mode-active + .middle-column-footer & {\n display: none;\n }\n\n &:not(.open) {\n height: 0 !important;\n }\n\n body.animation-level-0 & {\n transition: none !important;\n }\n\n & > div {\n display: flex;\n align-items: center;\n padding-right: 0.625rem;\n padding-top: 0.1875rem;\n }\n\n & > div > .Button {\n flex-shrink: 0;\n background: none !important;\n width: 3.5rem;\n height: 2.875rem;\n margin: 0 -0.0625rem 0 0;\n padding: 0;\n align-self: center;\n\n @media (max-width: 600px) {\n width: 2.875rem;\n }\n }\n}\n",".WebPagePreview {\n height: 2.625rem;\n transition: height 150ms ease-out, opacity 150ms ease-out;\n\n body.animation-level-0 & {\n transition: none !important;\n }\n\n .select-mode-active + .middle-column-footer & {\n display: none;\n }\n\n &:not(.open) {\n height: 0 !important;\n }\n\n // TODO Remove duplication with `.ComposerEmbeddedMessage`\n & > div {\n display: flex;\n align-items: center;\n padding-right: 0.625rem;\n padding-top: 0.1875rem;\n }\n\n --accent-color: var(--color-primary);\n\n .ComposerEmbeddedMessage + & {\n margin-top: 0.75rem;\n }\n\n & > div > .Button {\n flex-shrink: 0;\n background: none !important;\n width: 3.5rem;\n height: 2.875rem;\n margin: 0 -0.0625rem 0 0;\n padding: 0;\n align-self: center;\n\n @media (max-width: 600px) {\n width: 2.875rem;\n }\n }\n\n .WebPage {\n flex-grow: 1;\n margin: 0.1875rem 0 0.1875rem 0.125rem;\n max-width: calc(100% - 3.375rem);\n\n &::before {\n top: .1rem;\n bottom: .05rem;\n }\n\n &.with-video .media-inner { // TODO add support for video in previews in composer\n display: none;\n }\n\n .site-title,\n .site-description {\n flex: 1;\n max-width: 100%;\n max-height: 1rem;\n }\n\n .site-title {\n margin-top: .125rem;\n margin-bottom: 0.1875rem;\n }\n\n .site-description {\n overflow: hidden;\n white-space: nowrap;\n text-overflow: ellipsis;\n }\n }\n}\n","@import '../../../styles/mixins';\n\n.Composer {\n align-items: flex-end;\n\n .select-mode-active + .middle-column-footer & {\n position: absolute;\n padding-right: 2rem;\n bottom: 0;\n\n @supports (padding-bottom: env(safe-area-inset-bottom)) {\n bottom: env(safe-area-inset-bottom);\n }\n\n @media (max-width: 600px) {\n padding-right: 1rem;\n }\n\n &::before {\n right: 2.125rem;\n\n @media (max-width: 600px) {\n right: 1rem;\n }\n }\n\n .svg-appendix {\n opacity: 0;\n }\n }\n\n .form-control {\n --border-width: 0;\n }\n\n @keyframes show-send-as-button {\n from {\n width: 1rem;\n transform: scale(0);\n }\n\n to {\n width: 3.5rem;\n transform: scale(1);\n }\n }\n\n > .Button {\n flex-shrink: 0;\n margin-left: .5rem;\n\n &:not(.danger) {\n color: var(--color-composer-button);\n }\n\n @media (max-width: 600px) {\n width: 2.875rem;\n height: 2.875rem;\n }\n\n .icon-send,\n .icon-microphone-alt,\n .icon-check {\n position: absolute;\n }\n\n &:not(:active):not(:focus):not(:hover) {\n .icon-send,\n .icon-check {\n color: var(--color-primary);\n }\n }\n\n &.cancel {\n position: relative;\n z-index: 1;\n\n &:hover, &.active {\n background: var(--color-chat-hover);\n }\n }\n\n &.recording {\n position: relative;\n z-index: 0;\n transition: box-shadow .1s;\n }\n\n &.send {\n .icon-send {\n animation: grow-icon .4s ease-out;\n }\n\n .icon-microphone-alt,\n .icon-check {\n animation: hide-icon .4s forwards ease-out;\n }\n }\n\n &.record {\n .icon-microphone-alt {\n animation: grow-icon .4s ease-out;\n }\n\n .icon-send,\n .icon-check {\n animation: hide-icon .4s forwards ease-out;\n }\n }\n\n &.edit {\n .icon-send,\n .icon-microphone-alt {\n animation: hide-icon .4s forwards ease-out;\n }\n\n .icon-check {\n animation: grow-icon .4s ease-out;\n }\n }\n\n &.not-ready > i {\n animation-duration: 0ms !important;\n }\n\n body.animation-level-0 &, body.animation-level-1 & {\n .icon-send, .icon-microphone-alt, .icon-check {\n animation-duration: 0ms !important;\n }\n }\n }\n\n .send-as-button {\n z-index: 1;\n }\n\n body:not(.animation-level-0) & .send-as-button.appear-animation {\n animation: 0.25s ease-in-out forwards show-send-as-button;\n }\n\n .mobile-symbol-menu-button {\n width: 2.875rem;\n height: 2.875rem;\n position: relative;\n\n .icon-smile,\n .icon-keyboard,\n .Spinner {\n position: absolute;\n }\n\n .Spinner {\n --spinner-size: 1.5rem;\n }\n\n .icon-smile {\n animation: grow-icon .4s ease-out;\n }\n\n .icon-keyboard, .Spinner {\n animation: hide-icon .4s forwards ease-out;\n }\n\n &.not-ready > i {\n animation-duration: 0ms !important;\n }\n\n &.is-loading {\n .Spinner {\n animation: grow-icon .4s ease-out;\n }\n\n .icon-keyboard, .icon-smile {\n animation: hide-icon .4s forwards ease-out;\n }\n }\n\n &.menu-opened {\n .icon-keyboard {\n animation: grow-icon .4s ease-out;\n }\n\n .icon-smile, .Spinner {\n animation: hide-icon .4s forwards ease-out;\n }\n }\n }\n}\n\n#message-compose {\n flex-grow: 1;\n max-width: calc(100% - 4rem);\n background: var(--color-background);\n border-radius: var(--border-radius-messages);\n border-bottom-right-radius: 0;\n box-shadow: 0 1px 2px var(--color-default-shadow);\n position: relative;\n z-index: 1;\n\n .svg-appendix {\n position: absolute;\n bottom: -.1875rem;\n right: -.551rem; // This value is correct. Safari fix\n width: .5625rem;\n height: 1.25rem;\n transition: opacity 200ms;\n font-size: 1rem !important;\n\n .corner {\n fill: var(--color-background);\n }\n }\n\n @media (max-width: 600px) {\n max-width: calc(100% - 3.375rem);\n }\n}\n\n.message-input-wrapper {\n display: flex;\n\n > .Spinner {\n align-self: center;\n --spinner-size: 1.5rem;\n margin-right: -.5rem;\n }\n\n > .Button {\n flex-shrink: 0;\n background: none !important;\n width: 3.5rem;\n height: 3.5rem;\n margin: 0;\n padding: 0;\n align-self: flex-end;\n\n &:not(.faded):not(.activated) {\n color: var(--color-composer-button);\n }\n\n + .Button {\n margin-left: -1rem;\n }\n\n @media (max-width: 600px) {\n width: 2.875rem;\n height: 2.875rem;\n\n + .Button {\n margin-left: -0.6875rem;\n }\n }\n\n &.bot-commands {\n color: var(--color-primary) !important;\n\n // SymbolMenu button should be accessible if BotCommandsMenu opened\n body.is-touch-env &.activated + .Button.mobile-symbol-menu-button {\n z-index: calc(var(--z-menu-backdrop) + 1);\n }\n }\n\n &.scheduled-button i::after {\n content: '';\n position: absolute;\n top: .75rem;\n right: .875rem;\n border: .1875rem solid var(--color-background);\n box-sizing: content-box;\n width: .5rem;\n height: .5rem;\n border-radius: 50%;\n background: var(--color-green-darker);\n box-shadow: -.375rem -.25rem 0 -.1875rem var(--color-background);\n @media (max-width: 600px) {\n top: .5rem;\n right: .5rem;\n }\n }\n }\n\n > .input-group {\n flex-grow: 1;\n margin-bottom: 0;\n }\n\n .recording-state {\n display: inline-block;\n position: relative;\n line-height: 3.5rem;\n height: 3.5rem;\n padding: 0 3.125rem 0 1rem;\n font-family: \"Roboto\", -apple-system, BlinkMacSystemFont, \"Apple Color Emoji\", \"Helvetica Neue\", sans-serif;\n\n &::after {\n content: '';\n width: .75rem;\n height: .75rem;\n background: var(--color-error);\n border-radius: .375rem;\n position: absolute;\n top: 50%;\n margin-top: -.375rem;\n right: 1.3125rem;\n animation: recording-blink-like-macos 1.5s infinite;\n }\n\n @media (max-width: 600px) {\n height: 2.875rem;\n line-height: 2.875rem;\n }\n }\n}\n\n#message-input-text,\n#caption-input-text {\n position: relative;\n\n .form-control {\n padding: calc((3.25rem - var(--composer-text-size, 1rem) * 1.375) / 2 - var(--border-width, 0) * 2) calc(.9rem - var(--border-width));\n overflow: hidden;\n line-height: 1.375;\n font-family: Roboto, -apple-system, \"Apple Color Emoji\", \"Helvetica Neue\", sans-serif;\n unicode-bidi: plaintext;\n text-align: initial;\n font-size: var(--composer-text-size, 1rem);\n\n body.is-ios &,\n body.is-macos & {\n font-family: system-ui, -apple-system, BlinkMacSystemFont, \"Roboto\", \"Apple Color Emoji\", \"Helvetica Neue\", sans-serif;\n }\n\n &.overflown {\n overflow-y: auto;\n overflow-x: hidden;\n }\n\n &.touched, &:focus {\n & + .placeholder-text {\n display: none;\n }\n }\n\n &.focus-disabled {\n pointer-events: none;\n }\n }\n\n .forced-placeholder,\n .placeholder-text {\n position: absolute;\n color: var(--color-placeholders);\n pointer-events: none;\n unicode-bidi: plaintext;\n text-align: initial;\n line-height: 1.3125;\n font-size: var(--composer-text-size, 1rem);\n top: calc((3.25rem - var(--composer-text-size, 1rem) * 1.375) / 2);\n bottom: auto;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n max-width: 100%;\n }\n\n .forced-placeholder {\n z-index: var(--z-below);\n left: 0;\n }\n\n &[dir=rtl] .placeholder-text {\n right: 0;\n }\n\n .text-entity-link {\n color: var(--color-links) !important;\n cursor: default;\n text-decoration: none;\n\n &:hover, &:active, &:visited {\n text-decoration: underline !important;\n }\n }\n\n .clone {\n position: absolute;\n top: 0;\n left: 0;\n opacity: 0;\n pointer-events: none;\n z-index: -10;\n unicode-bidi: plaintext;\n text-align: initial;\n }\n}\n\n#message-input-text {\n flex-grow: 1;\n\n .form-control {\n margin-bottom: 0;\n background: transparent !important;\n border: none !important;\n border-radius: 0 !important;\n box-shadow: none !important;\n caret-color: var(--color-text);\n min-height: 3.5rem;\n max-height: 26rem;\n line-height: 1.3125;\n padding: calc((3.5rem - var(--composer-text-size, 1rem) * 1.3125) / 2) 0;\n white-space: pre-wrap;\n\n @media (max-width: 600px) {\n height: 2.875rem;\n min-height: 2.875rem;\n max-height: 16rem;\n padding: calc((2.875rem - var(--composer-text-size, 1rem) * 1.3125) / 2) 0;\n overflow: auto;\n }\n\n transition: height 100ms ease;\n\n body.animation-level-0 & {\n transition: none !important;\n }\n }\n\n .forced-placeholder,\n .placeholder-text {\n top: calc((3.5rem - var(--composer-text-size, 1rem) * 1.3125) / 2);\n\n @media (max-width: 600px) {\n top: calc((2.875rem - var(--composer-text-size, 1rem) * 1.3125) / 2);\n }\n }\n\n &:not(:only-child) {\n .form-control {\n padding-left: 0;\n padding-right: 0;\n }\n }\n\n .ComposerEmbeddedMessage + .message-input-wrapper &,\n .WebPagePreview + .message-input-wrapper & {\n .form-control.overflown {\n margin-top: 0.75rem;\n }\n }\n\n .emoji {\n width: 1.25rem;\n height: 1.25rem;\n margin: 0 1px -5px;\n vertical-align: 0;\n pointer-events: none;\n }\n}\n\n#caption-input-text {\n .form-control {\n height: 3.25rem;\n min-height: 3.25rem;\n max-height: 15rem;\n }\n\n .placeholder-text {\n bottom: .8125rem;\n left: .90625rem;\n }\n}\n\n.composer-tooltip {\n position: absolute;\n bottom: calc(100% + .5rem);\n left: 0;\n width: 100%;\n background: var(--color-background);\n border-radius: var(--border-radius-messages);\n padding: 0.5rem 0;\n max-height: 15rem;\n\n overflow-x: hidden;\n overflow-y: auto;\n @include overflow-y-overlay();\n\n box-shadow: 0 1px 2px var(--color-default-shadow);\n\n opacity: 0;\n transform: translateY(1.5rem);\n transform-origin: bottom;\n transition: opacity var(--layer-transition), transform var(--layer-transition);\n\n &:not(.shown) {\n display: none;\n }\n\n &.open {\n opacity: 1;\n transform: translateY(0);\n }\n\n .Loading {\n margin: 1rem 0;\n }\n}\n\n@keyframes recording-blink-like-macos {\n from {\n opacity: 1;\n }\n to {\n opacity: .3;\n }\n}\n","#middle-column-bg {\n position: absolute;\n top: 0;\n left: 0;\n bottom: 0;\n right: 0;\n overflow: hidden;\n z-index: -1;\n background-color: var(--theme-background-color);\n\n &::after {\n content: \"\";\n position: absolute;\n top: 0;\n left: 0;\n bottom: 0;\n right: 0;\n background-color: var(--theme-background-color);\n background-position: center;\n background-repeat: no-repeat;\n background-size: cover;\n\n body:not(.animation-level-0) #root & {\n transition: transform var(--layer-transition), background .2s !important;\n }\n\n body.animation-level-0 & {\n transition: none;\n }\n\n .theme-light & {\n background-image: url('../../assets/chat-bg.jpg');\n\n @media (max-width: 600px) {\n background-image: url('../../assets/chat-bg-mobile.jpg');\n }\n }\n }\n\n .custom-bg-color:not(.custom-bg-image) &::after {\n opacity: 0;\n }\n\n .custom-bg-image &::after {\n background-image: var(--custom-background) !important;\n filter: none;\n transform: scale(1.1);\n }\n\n .custom-bg-image.blurred &::after {\n filter: blur(12px);\n }\n\n @media screen and (min-width: 1276px) {\n body.animation-level-2 &::after {\n margin: -16rem -5rem -20rem 0;\n overflow: hidden;\n transform: scale(1);\n transform-origin: left center;\n transition: transform var(--layer-transition);\n }\n\n body.animation-level-2 #Main.right-column-open #MiddleColumn:not(.custom-bg-image) &::after {\n transform: scale(0.67) !important;\n }\n }\n\n body.animation-level-2 #Main.right-column-open #MiddleColumn:not(.custom-bg-image) &::after {\n @media screen and (min-width: 1921px) {\n transform: scale(0.8) !important;\n }\n\n @media screen and (min-width: 2600px) {\n transform: scale(0.95) !important;\n }\n }\n}\n\n#MiddleColumn {\n display: flex;\n justify-content: center;\n height: 100%;\n position: relative;\n z-index: 1;\n min-width: 0;\n\n @media (max-width: 600px) {\n overflow: hidden;\n }\n\n .messages-layout {\n --slide-transition: 450ms cubic-bezier(0.25, 1, 0.5, 1);\n\n display: flex;\n flex-direction: column;\n align-items: center;\n width: 100%;\n height: 100%;\n position: relative;\n overflow: hidden;\n\n > .Transition {\n width: 100%;\n height: 100%;\n overflow: hidden;\n\n > div {\n display: flex;\n flex-direction: column;\n align-items: center;\n }\n }\n }\n\n .messaging-disabled {\n &-inner {\n width: 100%;\n padding: 1rem;\n border-radius: var(--border-radius-messages);\n background: var(--color-background);\n color: var(--color-text-secondary);\n text-align: center;\n box-shadow: 0 1px 2px var(--color-default-shadow);\n }\n }\n\n .Composer {\n #message-compose {\n transform: scaleX(1) translateX(0);\n transition: transform var(--select-transition), border-bottom-right-radius var(--select-transition);\n\n &::before {\n transform: scaleX(-1) translateX(0);\n transition: transform var(--select-transition);\n }\n\n body.animation-level-0 & {\n &, &::before {\n transition: none !important;\n }\n }\n }\n\n .message-input-wrapper, &::before {\n opacity: 1;\n transition: opacity var(--select-transition);\n\n body.animation-level-0 & {\n transition: none !important;\n }\n }\n\n > .Button {\n opacity: 1;\n transform: scale(1);\n transition: opacity var(--select-transition), transform var(--select-transition), background-color 0.15s, color 0.15s;\n\n body.animation-level-0 & {\n transition: none !important;\n }\n }\n\n &.hover-disabled, &:not(.shown) {\n pointer-events: none;\n }\n\n &:not(.shown) {\n .ComposerEmbeddedMessage {\n height: 0;\n }\n\n #message-compose {\n transform: scaleX(var(--composer-hidden-scale, 1)) translateX(var(--composer-translate-x, 0));\n border-bottom-right-radius: var(--border-radius-messages);\n\n &::before {\n transform: scaleX(-1) translateX(200%);\n }\n }\n\n #editable-message-text {\n height: 3.5rem !important;\n\n @media (max-width: 600px) {\n height: 2.5rem !important;\n }\n }\n\n .message-input-wrapper, &::before {\n opacity: 0;\n }\n\n > .Button {\n opacity: 0 !important;\n transform: scale(0.5);\n }\n }\n }\n\n .messaging-disabled {\n transform: scaleX(1);\n transition: transform var(--select-transition);\n\n .messaging-disabled-inner span {\n opacity: 1;\n transition: opacity var(--select-transition);\n\n body.animation-level-0 & {\n transition: none !important;\n }\n }\n\n body.animation-level-0 & {\n transition: none !important;\n }\n\n &:not(.shown) {\n transform: scaleX(var(--composer-hidden-scale, 1));\n pointer-events: none;\n\n .messaging-disabled-inner span {\n opacity: 0;\n }\n }\n }\n\n .middle-column-footer {\n width: 100%;\n max-width: var(--messages-container-width);\n padding: 0 1rem;\n position: relative;\n display: flex;\n align-items: flex-end;\n z-index: var(--z-middle-footer);\n\n transform: translate3d(0, 0, 0);\n transition: top 200ms, transform var(--layer-transition);\n\n body.animation-level-0 & {\n transition: none !important;\n }\n\n @media (min-width: 1276px) {\n width: calc(100% - var(--right-column-width));\n\n #Main.right-column-open & {\n transform: translate3d(calc(var(--right-column-width) / -2), 0, 0);\n }\n }\n\n @media (max-width: 600px) {\n padding: 0 0.5rem;\n\n body.is-symbol-menu-open & {\n transform: translate3d(0, calc(-1 * (var(--symbol-menu-height) + var(--symbol-menu-footer-height))), 0);\n }\n }\n\n @supports (padding-bottom: env(safe-area-inset-bottom)) {\n &:not(.no-composer) {\n padding-bottom: env(safe-area-inset-bottom);\n top: 0;\n\n body.keyboard-visible & {\n top: env(safe-area-inset-bottom);\n }\n }\n }\n\n &::before {\n content: \"\";\n position: absolute;\n top: -.5625rem;\n left: 0;\n right: 0;\n height: 1px;\n background: linear-gradient(90deg, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.4) 2%, rgba(255, 255, 255, 0.4) 98%, rgba(255, 255, 255, 0) 100%);\n opacity: 0;\n transition: opacity 350ms ease;\n\n @media (max-width: 600px) {\n left: -2%;\n right: -2%;\n }\n }\n\n &.with-notch::before {\n opacity: 1;\n }\n\n html.theme-dark &::before {\n background: linear-gradient(90deg, rgba(127, 127, 127, 0) 0%, rgba(127, 127, 127, 0.4) 2%, rgba(127, 127, 127, 0.4) 98%, rgba(127, 127, 127, 0) 100%);\n }\n }\n}\n\n/* Common styles for message list fade-out shadow */\n.Composer,\n.MessageSelectToolbar,\n.messaging-disabled {\n margin-bottom: 1.25rem;\n\n @media (max-width: 600px) {\n margin-bottom: 0.5rem;\n }\n}\n\n.Composer,\n.MessageSelectToolbar,\n.unpin-all-button,\n.join-subscribe-button,\n.messaging-disabled {\n width: 100%;\n display: flex;\n justify-content: center;\n position: relative;\n}\n\n.MessageSelectToolbar-inner,\n.unpin-all-button,\n.join-subscribe-button,\n.messaging-disabled {\n .mask-image-disabled & {\n box-shadow: 0 .25rem .5rem .125rem var(--color-default-shadow);\n border-radius: var(--border-radius-messages);\n }\n}\n\n.middle-column-footer-button-container {\n width: 100%;\n display: flex;\n justify-content: center;\n position: absolute;\n padding-bottom: 1.25rem;\n\n .unpin-all-button {\n text-transform: capitalize;\n color: var(--color-black);\n\n @media (hover: hover) {\n &:hover {\n .icon-unpin {\n color: var(--color-white);\n }\n }\n }\n\n @media (max-width: 600px) {\n &:active, &:focus {\n .icon-unpin {\n color: var(--color-white);\n }\n }\n }\n\n .icon-unpin {\n margin-inline-start: -0.4375rem;\n margin-inline-end: .75rem;\n color: var(--color-text-secondary);\n font-size: 1.5rem;\n transition: color .15s\n }\n }\n\n .join-subscribe-button,\n .unpin-all-button {\n height: 3.5rem;\n transform: scaleX(1);\n transition: transform var(--select-transition), background-color .15s, color .15s;\n\n .select-mode-active + .middle-column-footer & {\n box-shadow: none;\n transform: scaleX(var(--unpin-hidden-scale));\n }\n\n @media (max-width: 600px) {\n height: 2.5rem;\n }\n }\n\n @media (max-width: 600px) {\n padding-bottom: 0.75rem;\n\n @supports (padding-bottom: env(safe-area-inset-bottom)) {\n padding-bottom: calc(.75rem + env(safe-area-inset-bottom));\n }\n }\n\n .mask-image-disabled &::before {\n background: unset;\n }\n}\n",".RightHeader {\n display: flex;\n align-items: center;\n height: var(--header-height);\n padding: 0.5rem .8125rem;\n pointer-events: auto;\n\n @media (max-width: 600px) {\n padding: 0.5rem;\n }\n\n .close-button {\n flex-shrink: 0;\n }\n\n > .Transition {\n flex: 1;\n height: 100%;\n\n > div {\n display: flex;\n align-items: center;\n }\n }\n\n h3 {\n margin-bottom: 0;\n font-size: 1.25rem;\n font-weight: 500;\n margin-left: 1.375rem;\n }\n\n .tools {\n display: flex;\n margin-left: auto;\n }\n\n .SearchInput {\n margin-left: 1rem;\n\n @media (min-width: 600px) {\n margin-right: 1rem;\n }\n }\n\n .DropdownMenu {\n margin-left: auto;\n }\n}\n","@import '../../styles/mixins';\n\n.Profile {\n height: 100%;\n display: flex;\n flex-direction: column;\n\n overflow-x: hidden;\n overflow-y: scroll;\n @include overflow-y-overlay();\n\n > .profile-info > .ChatInfo {\n grid-area: chat_info;\n\n .status.online {\n color: var(--color-primary);\n }\n }\n\n > .profile-info > .ChatExtra {\n padding: .875rem .5rem .5rem;\n box-shadow: inset 0 -.0625rem 0 0 var(--color-background-secondary-accent);\n border-bottom: .625rem solid var(--color-background-secondary);\n\n .narrow {\n margin-bottom: 0;\n }\n\n .inactive.no-selection {\n user-select: auto;\n -webkit-user-select: auto !important;\n }\n\n .Switcher {\n margin-left: auto;\n }\n [dir=rtl] {\n .Switcher {\n margin-left: 0;\n margin-right: auto;\n }\n }\n }\n\n .FloatingActionButton {\n z-index: 1;\n }\n}\n\n.shared-media {\n display: flex;\n flex-direction: column-reverse;\n\n .TabList {\n background: var(--color-background);\n top: -1px;\n z-index: 1;\n\n .Tab {\n padding: 1rem .75rem;\n\n span {\n white-space: nowrap;\n }\n\n i {\n bottom: -1rem;\n }\n }\n }\n\n .Transition {\n flex: 1;\n }\n\n .content {\n &.empty-list {\n height: 100%;\n padding-top: 5rem;\n display: flex;\n align-items: flex-start;\n justify-content: center;\n\n .Spinner {\n --spinner-size: 2.75rem;\n }\n }\n\n &.media-list {\n display: grid;\n grid-template-columns: repeat(3, 1fr);\n grid-auto-rows: 1fr;\n grid-gap: .0625rem;\n }\n\n &.documents-list {\n padding: 1.25rem;\n\n & .File + .File {\n margin-top: 1.25rem;\n }\n }\n\n &.links-list {\n padding: 1.25rem;\n\n .ProgressSpinner,\n .message-transfer-progress {\n display: none;\n }\n }\n\n &.audio-list,\n &.voice-list {\n padding: 1.25rem;\n\n & .Audio {\n .media-loading {\n top: 0;\n left: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n }\n\n & + .Audio {\n margin-top: 1.6875rem;\n }\n }\n }\n\n &.commonChats-list,\n &.members-list {\n padding: 0.5rem 1rem;\n\n @media (max-width: 600px) {\n padding: .5rem 0;\n .ListItem.chat-item-clickable {\n margin: 0;\n }\n }\n }\n }\n}\n",".AddChatMembers {\n height: 100%;\n overflow: hidden;\n position: relative;\n\n &-inner {\n height: 100%;\n overflow: hidden;\n }\n}\n","#RightColumn {\n position: absolute;\n top: 0;\n right: 0;\n width: var(--right-column-width);\n height: 100%;\n transform: translate3d(var(--right-column-width), 0, 0);\n background: var(--color-background);\n border-left: 1px solid var(--color-borders);\n z-index: var(--z-right-column);\n\n transition: transform var(--layer-transition);\n\n body.animation-level-0 & {\n transition: none;\n }\n\n // @optimization\n &:not(:hover) {\n .chat-item-clickable:not(.picker-list-item):nth-child(n + 18) {\n display: none !important;\n }\n }\n\n @media (max-width: 1275px) {\n box-shadow: 0 .25rem .5rem .125rem var(--color-default-shadow);\n border-left: none;\n }\n\n @media (max-width: 600px) {\n width: 100vw;\n transform: translate3d(110vw, 0, 0);\n }\n\n @supports (padding-right: env(safe-area-inset-right)) {\n padding-right: env(safe-area-inset-right);\n }\n\n > .Transition {\n height: calc(100% - var(--header-height));\n overflow: hidden;\n }\n\n .Management .section > .ChatInfo {\n padding: 0 1.5rem;\n margin: 1rem 0;\n text-align: center;\n\n .Avatar {\n margin: 0 auto .5rem;\n\n &.no-photo {\n cursor: default !important;\n }\n }\n\n .title {\n display: flex;\n justify-content: center;\n align-items: center;\n\n h3 {\n font-weight: 500;\n font-size: 1.25rem;\n line-height: 2rem;\n white-space: pre-wrap;\n word-break: break-word;\n }\n\n .VerifiedIcon {\n margin-left: 0.25rem;\n margin-bottom: .5rem;\n }\n\n .emoji {\n width: 1.5rem;\n height: 1.5rem;\n background-size: 1.5rem;\n }\n }\n\n .status {\n font-size: 0.875rem;\n color: #868e96;\n }\n }\n}\n\n#RightColumn-wrapper {\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n z-index: var(--z-right-column);\n overflow: hidden;\n visibility: hidden;\n pointer-events: none;\n\n @media (max-width: 1275px) {\n position: fixed;\n }\n\n &.is-hidden {\n display: none;\n }\n\n .overlay-backdrop {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n z-index: -1;\n background: black;\n opacity: 0;\n\n @media (max-width: 600px) {\n transition: opacity var(--layer-transition);\n\n body.animation-level-0 & {\n transition: none;\n }\n }\n }\n\n #Main.right-column-open &, body.animating-right-column & {\n visibility: visible;\n }\n\n #Main.right-column-open & {\n @media (max-width: 600px) {\n .overlay-backdrop {\n opacity: var(--layer-blackout-opacity);\n }\n }\n\n #RightColumn {\n pointer-events: auto;\n transform: translate3d(0, 0, 0);\n }\n }\n}\n","#Main {\n height: 100%;\n text-align: left;\n overflow: hidden;\n\n @media (min-width: 1276px) {\n position: relative;\n }\n\n @media (max-width: 600px) {\n height: calc(var(--vh, 1vh) * 100);\n }\n\n @media (min-width: 926px) {\n display: grid;\n grid-template-columns: auto 1fr;\n grid-template-rows: 100%;\n }\n}\n\n.has-group-call-header {\n --group-call-header-height: 2rem;\n #LeftColumn, #MiddleColumn, #RightColumn-wrapper {\n height: calc(100% - 2rem);\n margin-top: 2rem;\n }\n}\n\n#LeftColumn {\n min-width: 12rem;\n width: 33vw;\n max-width: 26.5rem;\n height: 100%;\n position: relative;\n\n & > div {\n height: 100%;\n overflow: hidden;\n }\n\n @media (max-width: 600px) {\n height: calc(var(--vh, 1vh) * 100);\n }\n\n @media (min-width: 926px) {\n max-width: 40vw;\n }\n\n @media (min-width: 1276px) {\n width: 25vw;\n max-width: 33vw;\n }\n\n @media (max-width: 925px) {\n position: fixed;\n left: 0;\n top: 0;\n height: calc(var(--vh, 1vh) * 100);\n width: 26.5rem !important;\n\n transform: translate3d(-5rem, 0, 0);\n transition: transform var(--layer-transition);\n\n body.animation-level-0 & {\n transition: none;\n }\n\n &::after {\n content: '';\n display: block;\n position: absolute;\n left: 0;\n top: 0;\n right: 0;\n bottom: 0;\n background: black;\n opacity: var(--layer-blackout-opacity);\n transition: opacity var(--layer-transition);\n z-index: 1;\n\n body.animation-level-0 & {\n transition: none;\n }\n\n // @optimization\n body.is-android & {\n display: none;\n }\n\n body.is-android .middle-column-shown & {\n display: block;\n }\n }\n\n #Main:not(.middle-column-open) & {\n transform: translate3d(0, 0, 0);\n\n &::after {\n opacity: 0;\n pointer-events: none;\n }\n }\n\n #Main.history-animation-disabled & {\n transition: none;\n\n &:after {\n transition: none;\n }\n }\n }\n\n @media (max-width: 600px) {\n max-width: none;\n width: 100vw !important;\n transform: translate3d(-20vw, 0, 0);\n\n @supports (left: env(safe-area-inset-left)) {\n left: env(safe-area-inset-left) !important;\n width: calc(100vw - env(safe-area-inset-left));\n }\n }\n}\n\n#RightColumn {\n @media (max-width: 600px) {\n height: calc(var(--vh, 1vh) * 100 + 1px);\n }\n\n #Main.history-animation-disabled & {\n transition: none;\n\n .overlay-backdrop {\n transition: none;\n }\n }\n}\n\n#Main.history-animation-disabled .overlay-backdrop {\n transition: none;\n}\n\n#MiddleColumn {\n border-left: 1px solid var(--color-borders);\n\n @media (max-width: 925px) {\n max-width: none;\n position: fixed;\n left: 0;\n top: 0;\n bottom: 0;\n right: 0;\n\n transform: translate3d(0, 0, 0);\n transition: transform var(--layer-transition);\n\n body.animation-level-0 & {\n transition: none;\n }\n\n #Main:not(.middle-column-open) & {\n transform: translate3d(26.5rem, 0, 0);\n }\n }\n\n @media (max-width: 600px) {\n border-left: none;\n\n #Main:not(.middle-column-open) & {\n transform: translate3d(100vw, 0, 0);\n }\n\n #Main.right-column-open & {\n transform: translate3d(-20vw, 0, 0);\n }\n }\n\n #Main.history-animation-disabled & {\n transition: none;\n\n &:after {\n transition: none;\n }\n }\n}\n\nbody.is-android.animation-level-1 {\n --layer-transition: 250ms ease-in-out;\n\n #LeftColumn, #MiddleColumn, #RightColumn {\n transition: transform var(--layer-transition), opacity var(--layer-transition);\n }\n\n #Main:not(.middle-column-shown) {\n #MiddleColumn {\n display: none;\n }\n }\n\n #Main:not(.middle-column-open) {\n #MiddleColumn {\n transform: translate3d(10vw, 0, 0);\n opacity: 0;\n }\n }\n\n #Main.middle-column-open {\n #LeftColumn {\n transform: translate3d(0, 0, 0);\n opacity: 0;\n }\n }\n\n #Main:not(.right-column-shown) {\n #RightColumn {\n display: none;\n }\n }\n\n #Main:not(.right-column-open) {\n #RightColumn {\n transform: translate3d(10vw, 0, 0);\n opacity: 0;\n }\n }\n\n #Main.right-column-open {\n #MiddleColumn {\n transform: translate3d(0, 0, 0);\n opacity: 0;\n }\n }\n}\n"],"names":[],"sourceRoot":""} \ No newline at end of file +{"version":3,"file":"87.74a4d72480e8214a0dde.css","mappings":"AAEA,gBACE,kBAEA,oCACE,kBAEA,2HACE,eACA,eACA,sBACA,6CACA,0BACA,oBAGF,uFACE,kBACA,OACA,WAGF,4CACE,eAGF,2CACE,aAGF,+CACE,yBAEA,uDACE,qEAGF,sDACE,qEAIJ,iDACE,gBAEA,iHACE,gBAKN,gCACE,iBACA,cACA,iBACA,6BACA,qBACA,iBACA,WACA,kBACA,mBACA,gBACA,kBACA,cAGF,0CACE,cACA,kBAGF,8BACE,gBACA,2CAEA,gBCpEF,+BDgEA,8BC/DE,mBAGA,mBDsEA,wIACE,2B;AEnFN,iBACE,cACA,aACA,mBACA,qBACA,eACA,+BACA,2CAEA,0BACE,wBAGF,6BACE,gCACA,gBACA,iBACA,6BACA,mBAGF,yBACE,6BACE,6B;ACvBN,eACE,kBACA,WACA,YACA,2BAEA,4DAEA,sCACE,0BACA,UAEA,wBAEA,+CACE,UAIJ,wBACE,wBAEA,yBAHF,wBAKI,kCACA,6BAKF,oCACE,WACA,cACA,kBACA,WACA,YACA,YACA,aACA,WAKF,6CACE,kBACA,YACA,aACA,WACA,cAKF,gFAEE,kBAIA,0DACE,iCAGF,gDACE,0CAKF,0CACE,iCAGF,oDACE,0C;AC1ER,iBACE,YACA,kBACA,aACA,sBACA,gBACA,UAEA,2CACE,kBACA,YACA,WAGF,6BACE,OACA,gBACA,gCAEA,uCACE,8BAIJ,8BACE,YACA,aACA,sBACA,gBAEA,gDACE,gBACA,6BAEA,2DACE,SAIJ,uCACE,2BACA,sBACA,mBACA,gBACA,UAGF,mCACE,cACA,qBACA,sBAEA,wCACE,mBACA,oBAIJ,0CACE,OACA,gBAIJ,+FACE,YACA,gBAGF,6BACE,kBACA,YACA,UACA,WACA,c;AC1EJ,SACE,YAGF,aACE,4BACA,oCACA,aACA,mBACA,cACA,yCAEA,gBACE,gBACA,kBACA,gBACA,qBACA,kBAGF,0BACE,oBACA,+BAEA,yBAJF,0BAKI,6BAIJ,yBAzBF,aA0BI,eAGF,6BACE,aACA,cAEA,2CACE,mB;ACtCN,aACE,aACA,iBACA,oBACA,uBAEA,oCACE,2BAGF,qBACE,cACA,eAGF,4BACE,6CACA,2DACA,0CACA,2CAIA,oCACE,WACA,YAEA,sCACE,mBACA,qBAIJ,8BACE,kBACA,oBACA,oBAEA,wCACE,kBAIJ,+EACE,UACA,mBACA,uEAGF,yLAIE,UACA,qBAIJ,4BACE,kBACA,iBAEA,kDACE,kBACA,2BACA,SACA,YACA,WACA,eACA,kBAGF,gHACE,mBAGF,2CACE,UACA,kBAEA,kBACA,mCACA,aACA,2BACA,8DACA,WACA,eACA,oBACA,eACA,iDAEA,wDACE,gBACA,0EACE,gBAKN,yKAGE,UACA,mBAKF,sCACE,6CAGF,qDACE,iCACA,iBACA,iBACA,iBACA,sBACA,sBACA,kCAIJ,qBACE,aACA,uBACA,sBACA,cACA,gBACA,kBACA,gBACA,eACA,kDAEA,2BACE,wDAGF,iDAfF,qBAgBI,iBAGF,yCACE,cACA,gBACA,6BACA,iBACA,mBACA,gBACA,uBAEA,qDACE,8BACA,qBAIJ,+BACE,4BACA,kCACA,mBACA,mBACA,gBACA,uBACA,mBAEA,2CACE,8BACA,qB;ACxKR,kBACE,kBACA,SACA,OACA,QACA,gBACA,gBACA,+CACA,aACA,mBACA,8BACA,mBACA,qCACA,mCACA,WACA,eAEA,0BACE,WACA,cACA,kBACA,eACA,OACA,QACA,eACA,uDAGF,4BACE,aAGF,yBACE,oCACE,2BAIJ,wBACE,aACA,sBAEA,+BACE,kBACA,wBAGF,sCACE,iBACA,kCAIJ,2BACE,aACA,mBACA,mBAEA,mCACE,sBAEA,+CACE,WACA,YAGF,qDACE,cACA,eACA,6CAKN,wBACE,cACA,qBACA,gBACA,kBACA,WAKJ,0BACE,wDACE,8C;ACPJ,cACE,aACA,mBACA,WACA,+CACA,mCACA,oCACA,kBACA,+BAEA,mDAVF,cAWI,oDACA,yDAGF,yBAfF,cAgBI,cACA,kBAEA,mDAnBJ,cAoBM,mDACA,uDAIJ,0BACE,WAGA,YAEA,8BACE,aACA,mBACA,WAIJ,2BACE,oBACA,mBACA,kBAEA,yBALF,2BAMI,eAGF,yCACE,kBACA,eACA,kBACA,sBACA,iBACA,oBACA,gBACA,kBAEA,kBACA,aACA,cAEA,6BACA,WACA,oBAEA,gDACE,gCAKN,iCACE,YACA,gBAGF,kEACE,2BAGF,4BACE,aACA,mBACA,yBACA,iBACA,cAGE,qLAGE,2BAIJ,iDACE,2CACE,+BACA,6CAEA,mEACE,mEAKN,0BA1BF,4BA2BI,+BACA,6CAEA,oDACE,mEP5LN,oIOkMI,oBAIJ,iDACE,8GAEE,UAEA,8JACE,WA3MN,4HAEE,kBACA,SACA,OACA,QACA,gBACA,uDAEA,aACA,2BACA,sBACA,oBACA,mCAEA,4IACE,WACA,cACA,kBACA,eACA,OACA,QACA,eACA,uDAGF,sKACE,gBACA,sBAGF,mDA/BF,4HAgCI,qDACA,uDAIJ,sDACE,mBACA,aACA,qBAEA,8DACE,gBACA,YAGF,8DACE,sBAGF,oEACE,iBAIJ,8DACE,YACA,cACA,iBAEA,sEACE,YACA,eAGF,4EACE,eAIJ,iFACE,aA2IA,0BACE,iEACE,wDAKN,oHAEE,mDAEA,kKACE,eAIJ,iBACE,gBACA,mBACA,qBACA,gBACA,SACA,gBACA,uBACA,uBAEA,4DAEE,oBACA,gBAGF,yBAhBF,iBAiBI,cACA,gBACA,wBAGF,0BACE,yCACE,kDAKN,wBACE,eACA,aACA,mBAEA,8BACE,aACA,sBACA,uBACA,YACA,gBAGF,+BACE,aACA,mBAEA,6CACE,cACA,eACA,mBACA,kBAIJ,gCACE,aACA,uBAGF,qCACE,uBACA,gBACA,uBAEA,0BACE,6DACE,kDAMR,sBACE,qBAEA,wBACA,yBACA,oBAGF,mDACE,kBACA,qBACA,SACA,kCACA,gBACA,mBACA,uBACA,qBAEA,uEACE,oBAGF,iEACE,2BAGF,2EACE,iBAIJ,8BACE,aACA,cAGF,2CACE,aACA,mBACA,iBACA,eACA,2BACA,mCAGE,oFACE,aAIJ,0BAdF,2CAeI,+BACA,+DAEA,mEACE,mEAKJ,gEACE,gBAGF,mDACE,cAGF,sDACE,kBACA,OACA,QACA,SACA,mCACA,oCACA,uDACA,+BACA,+DAEA,8DACE,WACA,cACA,kBACA,eACA,OACA,QACA,eACA,uDAGF,2EACE,aACA,gBACA,OAEA,yFACE,eAIJ,0BAhCF,sDAiCI,+BACA,+DAEA,8EACI,qDAMV,mCACE,aACA,cACA,oBACA,uBACA,eACA,qBACA,kDACA,kBACA,gBACA,eAEA,yCACE,wDAGF,0DACE,kBACA,eACA,iBACA,cACA,kBACA,gBAEA,2FACE,eACA,cACA,uBACA,gCAGF,yFACE,8CACA,kBACA,sBACA,sCAGF,sFACE,kBACA,OACA,MACA,cACA,gCACA,uBACA,sBACA,sCAIJ,iDACE,gBACA,4BACA,mBACA,gBAEA,iDANF,iDAOI,iBAGF,wDACE,gBACA,kBACA,iBACA,YACA,2BACA,sBACA,gBACA,mBAEA,oEACE,mBAIJ,mDACE,kBACA,qBACA,gBACA,mBACA,gBACA,uBACA,SAEA,+DACE,mBAKN,gDACE,WACA,YAGF,uCACE,cACA,eACA,iBACA,qBACA,4BACA,mBACA,cAEA,qDACE,gBAKN,6BACE,cACA,iBACA,aACA,mBACA,yBAGE,8DACE,2BACA,UAMJ,wFACE,mBAEA,kGACE,qBAKN,yBAjiBA,sEAEE,kBACA,SACA,OACA,QACA,gBACA,uDAEA,aACA,2BACA,sBACA,oBACA,mCAEA,sFACE,WACA,cACA,kBACA,eACA,OACA,QACA,eACA,uDAGF,gHACE,gBACA,sBAGF,mDA/BF,sEAgCI,qDACA,uDAIJ,2BACE,mBACA,aACA,qBAEA,mCACE,gBACA,YAGF,mCACE,sBAGF,yCACE,iBAIJ,mCACE,YACA,cACA,iBAEA,2CACE,YACA,eAGF,iDACE,eAIJ,sDACE,cA8dJ,mBACE,KACE,UAEF,GACE,W;AC9iBJ,iBACE,aACA,mBACA,yDACA,qBACA,2BACA,0CACA,kDACA,kBACA,gBACA,eACA,cAGE,0DACE,aAIJ,+BACE,gBACA,cACA,SACA,yCACA,iDAEA,uCACE,aACA,YACA,eAGF,+CACE,0BAGF,wCACE,cAIJ,yBACE,WACA,cACA,kBACA,aACA,gBACA,cACA,UACA,+BACA,kBAGF,uBACE,oCAGF,wBACE,qCAGF,gCACE,yDAGF,+BACE,gBACA,0BACA,aACA,8BAEA,8CACE,mBACA,gBACA,uBACA,sBACA,OACA,cAGF,iCACE,mBACA,gBACA,uBACA,gBACA,gBACA,OAEA,wCACE,aACA,aAIJ,sCACE,8DACA,+DACA,sCAIJ,0CACE,0BACA,YAGF,iCACE,WACA,YACA,iBACA,qBACA,mBACA,cAEA,uCACE,mBAIJ,8BACE,8BACA,gCACA,aACA,+BACA,uBACA,WACA,qCACA,sDAEA,sCACE,gBAGF,8CACE,oBAGF,4CACE,4BAGF,6CACE,gBACA,0B;AC/IN,aACE,kBACA,eACA,SACA,QACA,aACA,mBACA,gCACA,sBACA,iBACA,WACA,eACA,eACA,gEAEA,uFAGE,iBACA,mBAGF,2BACE,sBAIA,uCACE,oBAIJ,4BACE,6BAGF,gCACE,gBACA,uBACA,qBAGF,gCACE,oBACA,qBACA,mBACA,kBACA,eAGF,mCACE,6CACA,gBAGF,mEAEE,0BACA,0BACA,sBACA,sBACA,UACA,cACA,aACA,UACA,gBACA,6BAEA,qHACE,uBAIJ,qFAEE,sBACA,YACA,6BAGF,+GAEE,cAGF,4CACE,eACA,eAGF,yBACE,QAGF,gDACE,oCAGF,oCACE,uBACA,oBACA,sBAEA,iDACE,8BAIJ,6DACE,gBAGF,kEACE,iBAIA,qCACE,SAEF,yCACE,QAMJ,6DACE,WACA,aACA,cAGF,6DACE,YAGF,6DACE,YAGF,6DACE,Y;AC7IF,wBACE,eAGF,kBACE,oB;ACNJ,SACE,aACA,mBACA,eAEA,qBACE,eAGF,iBACE,mBAGF,uBACE,cACA,eACA,mBACA,gBAEA,qCACE,eACA,iBACA,qBACA,gBAGF,sCACE,iBACA,6B;AC5BN,YACE,aACA,qBACA,qBAEA,uBACE,gBAGF,8BACE,sBAGF,+BACE,kBACA,mBACA,cACA,wBACA,cACA,gBACA,kBACA,iBAEA,2CACE,oBACA,uBACA,iBAIJ,gCACE,kBACA,QACA,YACA,WACA,YACA,+BACA,8BACA,oBACA,iBACA,kBAEA,sCACE,8BAGF,gDACE,gBAGF,wCACE,UACA,qCACA,qBACA,uBACA,6BAIJ,+BACE,YACA,mBAGF,gCACE,kBAGF,8BACE,kBACA,QACA,cACA,gBACA,sBACA,iBACA,+BAEA,qBACA,yBACA,sBAIF,uBACE,WACA,YACA,kBACA,WACA,YACA,sDACA,oBACA,wBAGF,4BACE,iBACA,qBACA,2BACA,UAIA,qCACE,8BAGF,mCACE,0BAKN,iCACE,aACA,gB;AClHF,MACE,gBACA,mBAEA,yBAJF,MAKI,gBAGF,qBACE,gBACA,oBACA,iBACA,sBAGF,0CAEE,6BACA,kBAGF,iBACE,oBACA,aACA,mBACA,oBAGF,yBACE,2BACA,kBAGF,oBACE,mBACA,oBAGF,6BAEE,qBAEA,mDACE,qBAGF,+CACE,qBACA,mBAKA,gJACE,aACA,yCAEA,gMACE,4CAGF,oMACE,qCAIJ,4IACE,cACA,qCAMF,wMACE,iCAIJ,+CACE,aAMA,sCACE,aACA,sCAEA,mDACE,qCAMR,mBAEE,0CAEA,+BACE,2CAGF,gCAEE,2CACA,4CACE,2CAKN,0BACE,oBACA,mBACA,2BACA,oBACA,mBACA,gBAEA,kCACE,yCACA,eACA,uBAEA,+CACE,6CAGF,oDACE,iBAKN,sBACE,iBACA,iBACA,qBAEA,+BACE,yBAEA,wDACE,0BAIJ,0BACE,oBAIJ,+BACE,4BACA,iBACA,eACA,qBACA,2CAGF,sBACE,kCACA,yCACE,2BAIJ,wCAEE,mBACA,qBAGF,cACE,oBACA,eAEA,2BACE,0BACA,mDAIJ,cACE,sB;AC3LJ,SACE,kBACA,sBACA,qBACA,yDACA,qBACA,gBACA,kBAEA,iBACE,WACA,cACA,kBACA,MACA,SACA,OACA,cACA,+BACA,sBAGF,cACE,aACA,sBACA,uBAGF,sBACE,oBACA,iCAEA,sFACE,6DAGF,mCACE,WACA,YACA,aACA,2BAEA,uCACE,WACA,YAKN,iCACE,4BACA,8BAGF,2BACE,aACA,mBAEA,yCACE,QACA,mBAGF,wCACE,QACA,cAIA,kDACE,wBASF,kMACE,WACA,qBACA,iCACA,cACA,YAKN,oEAGE,sBACA,eAGF,oBACE,0BACA,gBACA,sBAGF,qBACE,gBACA,sBAGF,2BACE,iBACA,gBAEA,uCACE,qBAIJ,kBACE,6BAEA,0BACE,UACA,Q;ACvHJ,gBACE,0BACA,gBAGF,sBACE,kBAGE,+CACE,eACA,aAEA,yBAJF,+CAKI,cAIJ,kDACE,kBACA,MACA,qBACA,cACA,oCACA,kDACA,wBACA,gBAEA,uDACE,kB;AC9BV,OACE,kBACA,gBAEA,mCACE,mCAGF,0BACE,sBAEA,sDACE,oBACA,qCACA,sCAMF,0HACE,oBAKF,uJACE,2BACA,iB;AC5BN,YACE,kBACA,YACA,aACA,eAEA,+BACE,YACA,aACA,kBACA,gBAGF,2BACE,kBACA,OACA,MACA,kBACA,gBAGF,sBACE,kBACA,MACA,OACA,WACA,YACA,oBAGF,6BACE,YACA,iBACA,eACA,mBACA,qBAGF,kKAGE,a;ACzCJ,eACE,aACA,sBAEA,oBACE,aACA,mBAGF,uBACE,OACA,WACA,eACA,gCACA,kDACA,gBACA,oBAEA,+BACE,WACA,oCACA,UAEA,kBACA,MACA,OACA,QACA,SACA,kDACA,uBACA,yBAGF,6BACE,2CAEA,qCACE,WAIJ,qCACE,cAGF,oCACE,eAGF,yBACE,kBACA,kBACA,eACA,aACA,cAEA,0CACE,iBACA,YACA,cACA,yBAKN,0CACE,6BAGF,yCACE,gBAEA,uDACE,wDAGF,sDACE,yD;AC7EN,eACE,4CACA,uCAEA,aACA,WACA,mBACA,yCACA,6BACA,0BACA,mCACA,6DACA,2DACA,mBACA,gBACA,iBACA,0BACA,mBACA,eACA,4CACA,gEAEA,sCACE,2BAGF,8CACE,WACA,cACA,kBACA,kBACA,gBACA,eACA,eACA,gCACA,yDACA,UACA,oCAEA,gEACE,oBAGF,qEACE,2BAIJ,6BACE,kBACA,YACA,cACA,YACA,gBACA,uBACA,gCACA,uBACA,WACA,gCAEA,UACA,4BAEA,wBAfF,6BAgBI,sBAGF,mCACE,iCAGF,4CACE,UAGF,oCACE,uBACA,kBACA,kBACA,OACA,WAC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A,sEACE,8BAON,wDACE,8BAIJ,6HAEE,qDAGF,qIAEE,yDAGF,wCACE,eACA,aAIA,kGACE,yDACA,2BACA,qBAEA,yGACE,+BAMN,eACE,kBAEA,uCACE,kBACA,SACA,UACA,UAKF,iDACE,uCAGF,4DACE,kBACA,YACA,cACA,WAGF,kFACE,iEAIA,wEACE,8BAGF,0GACE,6CAOJ,4FACE,8BAGF,wEACE,2BAMA,oEACE,iBAGF,6EACE,gBACA,oCACA,qCAGF,uFACE,YAIJ,2DACE,gBAEA,mEACE,oBAGF,4EACE,uCACA,wCAOA,wPACE,gBAEA,sQACE,WACA,cACA,eACA,sBACA,gBACA,oCACA,kBASA,kSACE,mCACA,qCAEA,gTACE,mCACA,2CAaV,4OACE,4CAIA,4PACE,yDACA,gDAKN,uDACE,iBAGF,+CACE,qDAIA,2DACE,aACA,yBAEA,4EACE,WAMR,oCACE,kBAEA,4DACE,kBACA,UAIJ,iCACE,kBACA,OACA,cACA,aACA,cACA,sBACA,kBACA,wCAEA,aACA,mBACA,uBAEA,WACA,eAEA,UACA,oBACA,4CAEA,8CACE,kBACA,UACA,SACA,mBAGF,6CACE,uBAIJ,iBACE,mBAIA,wDACE,gCAIA,+EACE,gCAKF,gFACE,6BAOR,sKAME,qDACA,uDACA,2DACA,6DAGF,8BACE,kCAGF,aACE,gBAEA,6BACE,2BAIJ,SACE,wDACA,yDACA,2DACA,4DAGE,sDACE,iEAGF,4DACE,8DACA,iEAGF,sDACE,8DAGF,iCACE,iEAEA,+DACE,+BAMJ,gDACE,kEAGF,sDACE,+DACA,kEAGF,gDACE,+DAGF,2BACE,kEAEA,yDACE,gCACA,6BAQF,wNAEE,+BACA,gCAKF,gLAGE,mBAIJ,+QAIE,4BACA,6BAGF,qEACE,qBAIJ,gCACE,kBACA,SACA,WACA,gCAEA,UACA,4BAEA,wBATF,gCAUI,sBAGF,mHAGE,4CAMF,oGACE,UAIJ,oCACE,WAGF,0CACE,YAGF,wBACE,WACA,UACA,kBAIJ,8CACE,cCvmBF,iBACE,kBACA,2BAEA,yBAJF,iBAKI,gCAEA,uEAEE,gCAIF,kDAbJ,iBAcM,sCACA,yCACE,sCAEF,8BACE,uCAIJ,mCACE,6BAEA,2GAEE,+BAIF,iDATF,mCAUI,mCACA,2DACE,qCAEF,gDACE,uCAMR,qBACE,2BACA,yBAGF,+BACE,SACA,sBACA,mBACA,mBACA,kBACA,uBAGF,mCACE,uBAKA,sGACE,kBACA,YACA,uBACA,YACA,iBACA,8CACA,qBACA,qBAEA,4KACE,kDACA,gBAGF,0KACE,WAGF,0KACE,aAGF,oVAEE,UAGF,0KACE,aAKF,wHACE,WACA,qBACA,sBAMJ,4CACE,WACA,cACA,WAGF,kDACE,oBACA,0BACA,oBAEA,iEACE,oBAMJ,4DACE,qCAEA,kEACE,gCAKN,oCACE,yCAEA,gDACE,8CAGF,mDACE,YAIJ,0CACE,mBACA,qBACA,kBAGF,gCACE,mBACA,gBACA,uBACA,yDACA,gBACA,oBACA,0BACA,uBACA,aAEA,6CACE,gBACA,uBAGF,yFACE,eAEA,qGACE,YAIJ,yCACE,0BAGF,yCACE,0BAGF,yCACE,0BAGF,yCACE,0BAGF,yCACE,0BAGF,yCACE,0BAGF,yCACE,0BAGF,kEACE,0BAGF,sCACE,kBAGF,qCACE,qBACA,gBAGF,0CACE,oBAGF,6CACE,OACA,iBACA,iBACA,gBACA,iBACA,mBACA,6CAEA,0DACE,0BAKN,4BACE,iDAGF,iGACE,mCAGF,sCACE,+BAEA,yGACE,WACA,qBACA,iCACA,YAIJ,kDACE,wBAGF,+DACE,qBAGF,kDACE,aAGF,+BACE,gBACA,kBACA,kBACA,eACA,gBACA,0BAEA,uCACE,6BAGF,4CACE,gBAGF,kDACE,eAKF,iEACE,wBAMA,2DACE,yBACA,UACA,8BAKN,0BACE,yBAGE,4CACE,kDAIJ,8CACE,oBAMF,8IAEE,sBACA,uBAIJ,uBACE,yBAEA,4CACE,iBAIJ,uBACE,gBACA,wCAEA,yBAJF,uBAKI,iBAGF,4CACE,kBAIA,8DACE,yBAKN,2CACE,qBACA,cACA,wBACA,kBACA,sBACA,2BAEA,sDACE,wDACA,kBAIJ,yDACE,kDACA,mDACA,4DAGF,mCACE,4BACA,6BAGF,yCACE,6BAEA,uEACE,oBACA,kBACA,YACA,4BACA,8BACA,gBACA,yCACA,4CAEA,oFACE,kBAIJ,sDACE,mBAOJ,0DACE,aACA,uBACA,mBAEA,kFACE,eAEA,wGACE,yBAKN,8DACE,sBAGF,gdAME,oBACA,qBAEA,4vBACE,sBAIJ,oEACE,sBAGF,sTAIE,mBACA,wBAEA,8fACE,yBAKJ,4HAEE,sBAEA,gOACE,sBAIJ,8DACE,aACA,mBACA,uBAEA,oFACE,WACA,mBACA,+CAIJ,gIACE,kBACA,aACA,mBACA,uBACA,WACA,WACA,yBAEA,wJACE,UAGF,4JACE,aACA,mBACA,uBACA,eACA,gBACA,kBACA,2BAGF,4MACE,6BAEA,wPACE,UAKN,8DACE,iBAGF,kEACE,iBAGF,sKAEE,2BACA,WACA,iBACA,kBACA,cACA,aACA,UACA,kBACA,qBACA,qBACA,gEAGF,wGACE,0BACA,oBACA,oBAIJ,8BACE,gBACA,gBACA,aACA,eACA,qBAEA,2CACE,mBACA,wBAEA,uDACE,kBAIJ,uCACE,eAGF,6CACE,aACA,uBACA,2BACA,cAEA,+CACE,gBAGF,8DACE,kBACA,4CAEA,yBAJF,8DAKI,8BAGF,yBARF,8DASI,kBACA,UACA,8BAKN,4CACE,mBAGF,2CACE,cACA,eACA,cAEA,uDACE,MACA,OACA,SACA,QAIJ,qCACE,qBACA,kBAEA,gDACE,wDACA,kBAKF,uDACE,gBACA,4EACA,iEACE,+HAGF,oEACE,iBAKN,2CACE,eACA,iBAEA,0DACE,YAGF,yDACE,gBACA,kBAGF,+DACE,gBAGF,kDACE,WACA,YAIJ,2CACE,eACA,iBACA,gBAEA,wDACE,mBAGF,+DACE,gBAGF,kDACE,WACA,YACA,qBAIJ,2CACE,eACA,mBACA,gBAEA,wDACE,kBAGF,+DACE,gBAGF,kDACE,WACA,YACA,qBAIJ,iDACE,wCACA,0CAGF,2CACE,4CACA,8CAEA,0DACE,mBAEA,2EACE,mBAEA,yBAHF,2EAII,cACA,UACA,gCAOV,mBAmCE,8DACA,+DACA,iEACA,kEArCA,+HAIE,oBAGF,uDACE,kBACA,kBACA,qBAEA,+DACE,WACA,cACA,kBACA,MACA,SACA,YACA,UACA,+BACA,kBAGF,gEACE,6BAEA,wEACE,UACA,aAUN,gCACE,oBACA,gCAIJ,qBACE,qBAGF,kBACE,oCACA,gCACA,sBACA,eACA,qBAEA,2EACE,qCAIJ,mCACE,wBACA,gCACA,qBACA,SACA,gBACA,kBACA,uhB;AC7wBF,kBACE,mEACA,sEAEA,mBACA,oBAEA,0BACE,aAGF,oCACE,iBACA,sCACA,gDACA,2B;ACfJ,iBACE,WACA,YACA,aACA,mBACA,uBACA,kBAEA,0BACE,oBACA,sBACA,mBACA,gCACA,cACA,oBACA,qBACA,WAGF,wBACE,gBACA,gBAGF,8BACE,mBACA,gBAGF,0BACE,mBACA,aACA,YACA,eAEA,qCACE,aACA,Y;ACrCN,sBACE,YACA,aACA,mBACA,uBACA,mBAEA,cACE,mBACA,sBAGF,mBACE,sBACA,gCACA,gBACA,oBACA,qBACA,WACA,+BAEA,gBACE,oBAIJ,eACE,eACA,qBACA,kBACA,uBACA,0BAGF,kBACE,SACA,UACA,gBACA,uBACA,8BAGF,kBACE,kBACA,UACA,gBACA,uBACA,gBACA,yCAEA,WACE,wBACA,C;AClDN,aACE,OACA,WACA,oBAEA,gBACA,kBACA,gBAGA,6CzBJA,+ByBNF,azBOI,mBAGA,mByBEF,oCACE,2BAGF,iCACE,sIAGF,wBApBF,aAqBI,gEACA,mBAEA,gCACE,gEACA,uBAIJ,uDA9BF,aA+BI,mEACA,mCACE,kBACA,+CAEA,2EACE,4BAKN,yCACE,aAGF,iCACE,WACA,0CACA,gBACA,cACA,aACA,yBACA,sBACA,6BAEA,wDACE,4BAGF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A,6CAEA,+CACE,2BAGF,gDACE,4DAIJ,yBACE,gCACE,eACA,iBAKN,2BACE,wBACA,UACA,mBAEA,8DACE,2BAIJ,gCACE,iBACA,cACA,iBACA,qBACA,kBACA,mBACA,gBACA,kBAEA,kBACA,YACA,cAEA,8BACA,WAEA,oBAEA,yBAnBF,gCAoBI,YACA,YAIJ,yBACE,2CACE,oG;ACzGJ,yBACE,sBACA,gBACA,iDAGF,0BACE,aACA,sBACA,yBACA,gBACA,cAEA,yBAPF,0BAQI,iBAGF,+BACE,aACA,mBAGF,oCACE,mBAGF,kCACE,OACA,WACA,YACA,qBACA,kDACA,sCACA,mCACA,2BACA,gBACA,oBAEA,wCACE,WACA,wCACA,sCAIJ,0CACE,oB;AC/CN,yBACE,gBACA,wDAEA,mEACE,aAGF,oCACE,oBAGF,gDACE,2BAGF,6BACE,aACA,mBACA,sBACA,qBAGF,qCACE,cACA,2BACA,aACA,gBACA,wBACA,UACA,kBAEA,yBATF,qCAUI,gB;ACjCN,gBACE,gBACA,wDAsBA,qCApBA,uCACE,2BAGF,0DACE,aAGF,2BACE,oBAIF,oBACE,aACA,mBACA,sBACA,qBAKF,yCACE,kBAGF,4BACE,cACA,2BACA,aACA,gBACA,wBACA,UACA,kBAEA,yBATF,4BAUI,gBAIJ,yBACE,YACA,mCACA,gCAEA,iCACE,UACA,cAGF,iDACE,aAGF,gFAEE,OACA,eACA,gBAGF,qCACE,mBACA,uBAGF,2CACE,gBACA,mBACA,uB;ACvEN,UACE,qBAEA,oDACE,kBACA,mBACA,SAEA,uDALF,oDAMI,oCAGF,yBATF,oDAUI,oBAGF,4DACE,eAEA,yBAHF,4DAII,YAIJ,kEACE,UAIJ,wBACE,kBAGF,+BACE,KACE,WACA,mBAGF,GACE,aACA,oBAIJ,kBACE,cACA,kBAEA,+BACE,mCAGF,yBARF,kBASI,eACA,iBAGF,kGAGE,kBAIA,qIAEE,2BAIJ,yBACE,kBACA,UAEA,+DACE,mCAIJ,4BACE,kBACA,UACA,0BAIA,kCACE,iCAGF,+EAEE,0CAKF,8CACE,iCAGF,yEAEE,0CAKF,8EAEE,0CAGF,mCACE,iCAIJ,8BACE,kCAIA,8UACE,kCAKN,0BACE,UAGF,wEACE,wDAGF,qCACE,eACA,gBACA,kBAEA,mJAGE,kBAGF,8CACE,uBAGF,iDACE,iCAGF,kGACE,0CAGF,iDACE,kCAIA,yDACE,iCAGF,2HACE,0CAKF,gEACE,iCAGF,uHACE,0CAMR,iBACE,YACA,4BACA,mCACA,4CACA,6BACA,iDACA,kBACA,UAEA,+BACE,kBACA,kBACA,gBACA,eACA,eACA,yBACA,0BAEA,uCACE,6BAIJ,yBAxBF,iBAyBI,iCAIJ,uBACE,aAEA,gCACE,kBACA,uBACA,qBAGF,+BACE,cACA,2BACA,aACA,cACA,SACA,UACA,oBAEA,2DACE,mCAGF,uCACE,kBAGF,yBAjBF,+BAkBI,eACA,gBAEA,uCACE,wBAIJ,4CACE,sCAGA,0GACE,yCAIJ,yDACE,WACA,kBACA,WACA,cACA,8CACA,uBACA,YACA,aACA,kBACA,qCACA,mEACA,yBAZF,yDAaI,UACA,aAKN,oCACE,YACA,gBAGF,wCACE,qBACA,kBACA,mBACA,cACA,0BACA,sGAEA,+CACE,WACA,aACA,cACA,8BACA,sBACA,kBACA,QACA,qBACA,gBACA,mDAGF,yBArBF,wCAsBI,gBACA,sBAKN,wCAEE,kBAEA,oEACE,qIACA,gBACA,kBACA,iFACA,uBACA,mBACA,0CAEA,4LAEE,gHAGF,wFACE,gBACA,kBAIA,4OACE,aAIJ,kGACE,oBAIJ,4JAEE,kBACA,gCACA,oBACA,uBACA,mBACA,mBACA,0CACA,kEACA,YACA,mBACA,gBACA,uBACA,eAGF,gFACE,uBACA,OAGF,8FACE,QAGF,4EACE,oCACA,eACA,qBAEA,8QACE,qCAIJ,sDACE,kBACA,MACA,OACA,UACA,oBACA,YACA,uBACA,mBAIJ,oBACE,YAEA,kCACE,gBACA,kCACA,uBACA,2BACA,2BACA,8BACA,kBACA,iBACA,mBACA,wEACA,qBAUA,6BARA,yBAbF,kCAcI,gBACA,oBACA,iBACA,0EACA,eAKF,yDACE,2BAIJ,8EAEE,kEAEA,yBAJF,8EAKI,qEAKF,mDACE,eACA,gBAMF,+KACE,kBAIJ,2BACE,cACA,eACA,kBACA,iBACA,oBAKF,kCACE,eACA,mBACA,iBAGF,sCACE,gBACA,eAIJ,kBACE,kBACA,0BACA,OACA,WACA,mCACA,4CACA,gBACA,iBAEA,kBACA,gBAGA,iDAEA,UACA,6BACA,wBACA,6E9BneA,+B8BgdF,kB9B/cI,mBAGA,mB8BieF,8BACE,aAGF,uBACE,UACA,wBAGF,2BACE,cAIJ,sCACE,KACE,UAEF,GACE,Y;AChgBJ,kBACE,kBACA,MACA,OACA,SACA,QACA,gBACA,WACA,+CAEA,yBACE,WACA,kBACA,MACA,OACA,SACA,QACA,+CACA,2BACA,4BACA,sBAEA,4DACE,uEAGF,gDACE,gBAGF,sCACE,yDAEA,yBAHF,sCAII,0DAKN,gEACE,UAGF,0CACE,qDACA,YACA,qBAGF,kDACE,kBAGF,sCACE,gDACE,6BACA,gBACA,mBACA,6BACA,6CAGF,4GACE,kCAKF,sCADF,4GAEI,iCAGF,sCALF,4GAMI,kCAKN,cACE,aACA,uBACA,YACA,kBACA,UACA,YAEA,yBARF,cASI,iBAGF,+BACE,wDAEA,aACA,sBACA,mBACA,WACA,YACA,kBACA,gBAEA,2CACE,WACA,YACA,gBAEA,+CACE,aACA,sBACA,mBAMJ,wCACE,WACA,aACA,4CACA,mCACA,kCACA,kBACA,iDAKF,yCACE,kCACA,kGAEA,iDACE,mCACA,8CAIA,wIACE,2BAKN,+EACE,UACA,4CAEA,6HACE,2BAIJ,gCACE,UACA,mBACA,gHAEA,uDACE,2BAIJ,2EACE,oBAIA,6DACE,SAGF,qDACE,6FACA,yDAEA,6DACE,sCAIJ,2DACE,yBAEA,yBAHF,2DAII,0BAIJ,uGACE,UAGF,4CACE,qBACA,qBAKN,kCACE,oB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aACA,uBACA,uBAEA,2CACE,wBAIJ,kCACE,aACA,qCACA,mBACA,kBAGF,sCACE,gBAEA,kDACE,mBAIJ,kCACE,gBAEA,gHAEE,aAIJ,oEAEE,gBAGE,gHACE,MACA,OACA,aACA,mBACA,uBAGF,gGACE,qBAKN,4EAEE,mBAEA,yBAJF,4EAKI,gBACA,wIACE,U;AC1IV,gBACE,YACA,gBACA,kBAEA,sBACE,YACA,gB;ACPJ,aACE,kBACA,MACA,QACA,gCACA,YACA,uDACA,mCACA,2CACA,8BAEA,6CAEA,oCACE,gBAKA,qFACE,wBAIJ,0BAxBF,aAyBI,8DACA,kBAGF,yBA7BF,aA8BI,YACA,oCAGF,qDAlCF,aAmCI,0CAGF,yBACE,yCACA,gBAGF,4CACE,iBACA,cACA,kBAEA,oDACE,oBAEA,6DACE,0BAIJ,mDACE,aACA,uBACA,mBAEA,sDACE,gBACA,kBACA,iBACA,qBACA,sBAGF,iEACE,mBACA,oBAGF,0DACE,aACA,cACA,uBAIJ,oDACE,kBACA,cAKN,qBACE,kBACA,MACA,OACA,QACA,SACA,8BACA,gBACA,kBACA,oBAEA,0BAXF,qBAYI,gBAGF,+BACE,aAGF,uCACE,kBACA,MACA,QACA,SACA,OACA,WACA,gBACA,UAEA,yBAVF,uCAWI,2CAEA,8DACE,iBAKN,8FACE,mBAIA,yBACE,+DACE,uCAIJ,0DACE,oBACA,+B;AC3IN,MACE,YACA,gBACA,gBAEA,0BALF,MAMI,mBAGF,yBATF,MAUI,mCAGF,yBAbF,MAcI,aACA,+BACA,yBAIJ,uBACE,iCACA,oHACE,yBACA,gBAIJ,YACE,gBACA,WACA,kBACA,YACA,kBAEA,gBACE,YACA,gBAGF,yBAZF,YAaI,mCAGF,yBAhBF,YAiBI,gBAGF,0BApBF,YAqBI,WACA,gBAGF,yBAzBF,YA0BI,eACA,OACA,MACA,kCACA,yBAEA,mCACA,6CAEA,mCACE,gBAGF,mBACE,WACA,cACA,kBACA,OACA,MACA,QACA,SACA,gBACA,sCACA,2CACA,UAEA,0CACE,gBAIF,mCACE,aAGF,wDACE,cAIJ,2CACE,+BAEA,kDACE,UACA,oBAIJ,6CACE,gBAEA,mDACE,iBAKN,yBApFF,YAqFI,eACA,uBACA,mCAEA,2CAzFJ,YA0FM,0CACA,gDAMJ,yBADF,aAEI,yCAGF,8CACE,gBAEA,gEACE,gBAKN,mDACE,gBAGF,cACE,2CAEA,yBAHF,cAII,eACA,eACA,OACA,MACA,SACA,QAEA,+BACA,6CAEA,qCACE,gBAGF,6CACE,sCAIJ,yBAvBF,cAwBI,iBAEA,6CACE,mCAGF,sCACE,oCAIJ,+CACE,gBAEA,qDACE,gBAKN,kCACE,sCAEA,6IACE,6EAIA,gFACE,aAKF,+EACE,kCACA,UAKF,uEACE,+BACA,UAKF,8EACE,aAKF,6EACE,kCACA,UAKF,wEACE,+BACA,U","sources":["webpack://telegram-t/./src/components/left/main/LeftMainHeader.scss","webpack://telegram-t/./src/styles/_mixins.scss","webpack://telegram-t/./src/components/left/ConnectionState.scss","webpack://telegram-t/./src/components/left/NewChatButton.scss","webpack://telegram-t/./src/components/left/main/LeftMain.scss","webpack://telegram-t/./src/components/left/LeftColumn.scss","webpack://telegram-t/./src/components/middle/AudioPlayer.scss","webpack://telegram-t/./src/components/calls/group/GroupCallTopPane.scss","webpack://telegram-t/./src/components/middle/MiddleHeader.scss","webpack://telegram-t/./src/components/common/EmbeddedMessage.scss","webpack://telegram-t/./src/components/middle/message/MessageMeta.scss","webpack://telegram-t/./src/components/middle/message/Sticker.scss","webpack://telegram-t/./src/components/middle/message/Contact.scss","webpack://telegram-t/./src/components/middle/message/PollOption.scss","webpack://telegram-t/./src/components/middle/message/Poll.scss","webpack://telegram-t/./src/components/middle/message/WebPage.scss","webpack://telegram-t/./src/components/middle/message/Invoice.scss","webpack://telegram-t/./src/components/middle/message/Album.scss","webpack://telegram-t/./src/components/middle/message/RoundVideo.scss","webpack://telegram-t/./src/components/middle/message/InlineButtons.scss","webpack://telegram-t/./src/components/middle/message/CommentButton.scss","webpack://telegram-t/./src/components/middle/message/Message.scss","webpack://telegram-t/./src/components/middle/message/_message-content.scss","webpack://telegram-t/./src/components/middle/message/SponsoredMessage.scss","webpack://telegram-t/./src/components/middle/ContactGreeting.scss","webpack://telegram-t/./src/components/middle/NoMessages.scss","webpack://telegram-t/./src/components/middle/MessageList.scss","webpack://telegram-t/./src/components/middle/ScrollDownButton.scss","webpack://telegram-t/./src/components/middle/composer/BotKeyboardMenu.scss","webpack://telegram-t/./src/components/middle/composer/ComposerEmbeddedMessage.scss","webpack://telegram-t/./src/components/middle/composer/WebPagePreview.scss","webpack://telegram-t/./src/components/middle/composer/Composer.scss","webpack://telegram-t/./src/components/middle/MiddleColumn.scss","webpack://telegram-t/./src/components/right/RightHeader.scss","webpack://telegram-t/./src/components/right/Profile.scss","webpack://telegram-t/./src/components/right/AddChatMembers.scss","webpack://telegram-t/./src/components/right/RightColumn.scss","webpack://telegram-t/./src/components/main/Main.scss"],"sourcesContent":["@import '../../../styles/mixins';\n\n#LeftMainHeader {\n position: relative;\n\n .animated-menu-icon {\n position: absolute;\n\n &, &::before, &::after {\n width: 1.125rem;\n height: 0.125rem;\n border-radius: 0.125rem;\n background-color: var(--color-text-secondary);\n transition: transform .25s;\n transform: rotate(0);\n }\n\n &::before, &::after {\n position: absolute;\n left: 0;\n content: '';\n }\n\n &::before {\n top: -0.3125rem;\n }\n\n &::after {\n top: 0.3125rem;\n }\n\n &.state-back {\n transform: rotate(180deg);\n\n &::before {\n transform: rotate(45deg) scaleX(0.75) translate(0.375rem, -0.1875rem);\n }\n\n &::after {\n transform: rotate(-45deg) scaleX(0.75) translate(0.375rem, 0.1875rem);\n }\n }\n\n &.no-animation {\n transition: none;\n\n &::before, &::after {\n transition: none;\n }\n }\n }\n\n .archived-badge {\n min-width: 1.5rem;\n height: 1.5rem;\n margin-left: auto;\n background: var(--color-gray);\n border-radius: 0.75rem;\n padding: 0 .45rem;\n color: white;\n font-size: 0.875rem;\n line-height: 1.5rem;\n font-weight: 500;\n text-align: center;\n flex-shrink: 0;\n }\n\n [dir=rtl] .archived-badge {\n margin-left: 0;\n margin-right: auto;\n }\n\n .Menu .bubble {\n min-width: 17rem;\n max-height: calc(100 * var(--vh) - 3.75rem);\n\n overflow-y: auto;\n @include overflow-y-overlay();\n }\n\n // @optimization\n @include while-transition() {\n .Menu .bubble {\n transition: none !important;\n }\n }\n}\n","// @optimization\n@mixin while-transition() {\n .Transition > div:not(.Transition__slide--active) &, body.animating-right-column & {\n @content;\n }\n}\n\n@mixin overflow-y-overlay() {\n @supports (overflow-y: overlay) {\n overflow-y: overlay;\n\n //Workaround for Android <= 9\n overflow-x: hidden;\n }\n}\n\n@mixin reset-range() {\n input[type=\"range\"] {\n -webkit-appearance: none;\n display: block;\n width: 100%;\n height: 0.75rem;\n margin-bottom: 0.5rem;\n background: transparent;\n\n &:focus {\n outline: none;\n }\n\n &::-ms-track {\n width: 100%;\n cursor: pointer;\n\n background: transparent;\n border-color: transparent;\n color: transparent;\n }\n\n &::-webkit-slider-thumb {\n -webkit-appearance: none;\n }\n\n &::-moz-slider-thumb {\n -moz-appearance: none;\n }\n\n &::-webkit-slider-runnable-track {\n cursor: pointer;\n }\n\n &::-moz-range-track, &::-moz-range-progress {\n cursor: pointer;\n }\n }\n}\n","#ConnectionState {\n flex: 0 0 auto;\n display: flex;\n align-items: center;\n margin: 0 0.5rem 0.5rem;\n padding: 0.75rem;\n background: var(--color-yellow);\n border-radius: var(--border-radius-default);\n\n > .Spinner {\n --spinner-size: 1.75rem;\n }\n\n > .state-text {\n color: var(--color-text-lighter);\n font-weight: 500;\n line-height: 2rem;\n margin-inline-start: 1.875rem;\n white-space: nowrap;\n }\n\n @media (max-width: 950px) {\n > .state-text {\n margin-inline-start: 1.25rem;\n }\n }\n}\n",".NewChatButton {\n position: absolute;\n right: 1rem;\n bottom: 1rem;\n transform: translateY(5rem);\n\n transition: transform .25s cubic-bezier(0.34, 1.56, 0.64, 1);\n\n body.animation-level-0 & {\n transform: none !important;\n opacity: 0;\n\n transition: opacity .15s;\n\n &.revealed {\n opacity: 1;\n }\n }\n\n &.revealed {\n transform: translateY(0);\n\n @media (max-width: 600px) {\n // Force rendering in the composite layer to fix the z-index rendering issue\n transform: translate3d(0,0,10px);\n transform-style: preserve-3d;\n }\n }\n\n &.menu-is-open {\n &::before {\n content: '';\n display: block;\n position: absolute;\n top: -13rem;\n left: -11rem;\n right: -1rem;\n bottom: -1rem;\n z-index: -1;\n }\n }\n\n .is-touch-env & {\n .Menu > .backdrop {\n position: absolute;\n left: -100vw;\n right: -100vw;\n top: -100vh;\n bottom: -100vh;\n }\n }\n\n > .Button {\n .icon-new-chat-filled,\n .icon-close {\n position: absolute;\n }\n\n &:not(.active) {\n .icon-new-chat-filled {\n animation: grow-icon .4s ease-out;\n }\n\n .icon-close {\n animation: hide-icon .4s forwards ease-out;\n }\n }\n\n &.active {\n .icon-close {\n animation: grow-icon .4s ease-out;\n }\n\n .icon-new-chat-filled {\n animation: hide-icon .4s forwards ease-out;\n }\n }\n }\n}\n","#LeftColumn-main {\n height: 100%;\n position: relative;\n display: flex;\n flex-direction: column;\n overflow: hidden;\n z-index: 1;\n\n .connection-state-wrapper {\n position: absolute;\n top: 3.75rem;\n width: 100%;\n }\n\n > .Transition {\n flex: 1;\n overflow: hidden;\n transition: transform 300ms ease;\n\n &.pull-down {\n transform: translateY(3.75rem);\n }\n }\n\n .ChatFolders {\n height: 100%;\n display: flex;\n flex-direction: column;\n overflow: hidden;\n\n .tabs-placeholder {\n height: 2.625rem;\n transition: height 150ms ease;\n\n &:not(.open) {\n height: 0;\n }\n }\n\n .TabList {\n justify-content: flex-start;\n padding-left: .5625rem;\n padding-bottom: 1px;\n border-bottom: 0;\n z-index: 1;\n }\n\n .Tab {\n flex: 0 0 auto;\n padding-left: 0.625rem;\n padding-right: 0.625rem;\n\n > span {\n padding-left: 0.5rem;\n padding-right: 0.5rem;\n }\n }\n\n > .Transition {\n flex: 1;\n overflow: hidden;\n }\n }\n\n .RecentContacts, .LeftSearch, .search-content {\n height: 100%;\n overflow-y: auto;\n }\n\n .btn-update {\n position: absolute;\n bottom: 1rem;\n left: 1rem;\n right: 1rem;\n margin: 0 auto;\n }\n}\n","#NewChat {\n height: 100%;\n}\n\n.left-header {\n height: var(--header-height);\n padding: 0.375rem 1rem .5rem 0.8125rem;\n display: flex;\n align-items: center;\n flex-shrink: 0;\n background-color: var(--color-background);\n\n h3 {\n margin-bottom: 0;\n font-size: 1.25rem;\n font-weight: 500;\n margin-left: 1.375rem;\n margin-right: auto;\n }\n\n .SearchInput {\n margin-left: 0.875rem;\n max-width: calc(100% - 3.25rem);\n\n @media (max-width: 600px) {\n max-width: calc(100% - 3rem);\n }\n }\n\n @media (max-width: 600px) {\n padding: 0.5rem;\n }\n\n .Button.smaller {\n width: 2.5rem;\n height: 2.5rem;\n\n + .DropdownMenu {\n margin-left: .25rem;\n }\n }\n}\n",".AudioPlayer {\n display: flex;\n margin-left: auto;\n margin-top: -.25rem;\n margin-bottom: -.25rem;\n\n body.animation-level-0 & {\n transition: none !important;\n }\n\n > .Button {\n flex-shrink: 0;\n margin: .125rem;\n }\n\n > .player-button {\n --color-text-secondary: var(--color-primary);\n --color-text-secondary-rgb: var(--color-primary-shade-rgb);\n --color-primary-shade: var(--color-green);\n --color-white: var(--color-background-own);\n }\n\n .player-button {\n &.smaller {\n width: 3rem;\n height: 3rem;\n\n i {\n font-size: 1.625rem;\n margin-top: -.025rem;\n }\n }\n\n i {\n position: absolute;\n font-size: 1.9375rem;\n margin-top: -.05rem;\n\n &.icon-play {\n margin-left: .1rem;\n }\n }\n\n .icon-play, .icon-pause {\n opacity: 1;\n transform: scale(1);\n transition: opacity .4s, transform .6s cubic-bezier(0.34, 1.56, 0.64, 1);\n }\n\n &.play .icon-pause,\n &.pause .icon-play,\n &.loading .icon-play,\n &.loading .icon-pause {\n opacity: 0;\n transform: scale(.5);\n }\n }\n\n .volume-button {\n position: relative;\n overflow: visible;\n\n .volume-slider-spacer {\n position: absolute;\n transform: translateY(100%);\n bottom: 0;\n height: 1rem;\n width: 8rem;\n cursor: default;\n visibility: hidden;\n }\n\n &:hover .volume-slider-spacer, .volume-slider-spacer:hover {\n visibility: visible;\n }\n\n .volume-slider {\n opacity: 0;\n visibility: hidden;\n\n position: absolute;\n background: var(--color-background);\n bottom: -1rem;\n transform: translateY(100%);\n transition: opacity 0.2s ease-in-out, visibility 0.2s ease-in-out;\n width: 8rem;\n padding: 0.75rem;\n border-radius: 0.5rem;\n cursor: default;\n box-shadow: 0 1px 2px var(--color-default-shadow);\n\n .RangeSlider {\n margin-bottom: 0;\n input[type=range] {\n margin-bottom: 0;\n }\n }\n }\n\n &:hover .volume-slider,\n .volume-slider:hover,\n .volume-slider-spacer:hover + .volume-slider {\n opacity: 1;\n visibility: visible;\n }\n }\n\n .playback-button {\n &.applied {\n --color-text-secondary: var(--color-primary);\n }\n\n .playback-button-inner {\n transition: 0.2s color ease-in-out;\n font-size: 0.75rem;\n font-weight: bold;\n border: 2px solid;\n border-radius: 0.375rem;\n padding: 0.15rem 0.25rem;\n font-variant-numeric: tabular-nums;\n }\n }\n\n &-content {\n display: flex;\n justify-content: center;\n flex-direction: column;\n flex-shrink: 1;\n padding: 0 .5rem;\n position: relative;\n overflow: hidden;\n cursor: pointer;\n border-radius: var(--border-radius-messages-small);\n\n &:hover {\n background-color: var(--color-interactive-element-hover);\n }\n\n @media (min-width: 1440px) and (max-width: 1500px) {\n max-width: 14rem;\n }\n\n .AudioPlayer & .title {\n display: block;\n font-weight: 500;\n font-size: 0.875rem !important;\n line-height: 1rem;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n\n body.is-ios & {\n font-size: .9375rem !important;\n line-height: 1.125rem;\n }\n }\n\n .subtitle {\n font-size: 0.85rem !important;\n color: var(--color-text-secondary);\n line-height: 0.85rem;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n margin: .125rem 0 0;\n\n body.is-ios & {\n font-size: .9375rem !important;\n line-height: 1.125rem;\n }\n }\n }\n}\n",".GroupCallTopPane {\n position: absolute;\n top: 100%;\n left: 0;\n right: 0;\n height: 2.875rem;\n overflow: hidden;\n box-shadow: 0 2px 2px var(--color-light-shadow);\n display: flex;\n flex-direction: row;\n justify-content: space-between;\n align-items: center;\n padding: 0.375rem 0.5rem 0.375rem 0.75rem;\n background: var(--color-background);\n z-index: -1;\n cursor: pointer;\n\n &::before {\n content: \"\";\n display: block;\n position: absolute;\n top: -.1875rem;\n left: 0;\n right: 0;\n height: .125rem;\n box-shadow: 0 .125rem .125rem var(--color-light-shadow);\n }\n\n &.is-hidden {\n display: none;\n }\n\n @media (max-width: 600px) {\n &.has-pinned-offset {\n top: calc(100% + 2.875rem);\n }\n }\n\n .info {\n display: flex;\n flex-direction: column;\n\n .title {\n font-size: 0.875rem;\n color: var(--color-text);\n }\n\n .participants {\n font-size: 0.75rem;\n color: var(--color-text-secondary);\n }\n }\n\n .avatars {\n display: flex;\n flex-direction: row;\n align-items: center;\n\n .Avatar {\n margin: 0 0 0 -0.75rem;\n\n &:first-child {\n width: 2rem;\n height: 2rem;\n }\n\n &:not(:first-child) {\n width: 2.25rem;\n height: 2.25rem;\n border: 0.125rem solid var(--color-background);\n }\n }\n }\n\n .join {\n height: 1.5rem;\n border-radius: 1.5rem;\n font-weight: 500;\n padding: 1rem 1rem;\n width: auto;\n }\n}\n\n\n@media (min-width: 1440px) {\n #Main.right-column-open .MiddleHeader .GroupCallTopPane {\n width: calc(100% - var(--right-column-width));\n }\n}\n","@import '../../styles/mixins';\n\n@mixin mobile-header-styles() {\n .HeaderPinnedMessage-wrapper,\n .AudioPlayer {\n position: absolute;\n top: 100%;\n left: 0;\n right: 0;\n height: 2.875rem;\n box-shadow: 0 .125rem .125rem var(--color-light-shadow);\n\n display: flex;\n flex-direction: row-reverse;\n padding: 0.375rem 0.5rem;\n padding-left: 0.75rem;\n background: var(--color-background);\n\n &::before {\n content: \"\";\n display: block;\n position: absolute;\n top: -.1875rem;\n left: 0;\n right: 0;\n height: .125rem;\n box-shadow: 0 .125rem .125rem var(--color-light-shadow);\n }\n\n .HeaderPinnedMessage {\n max-width: unset;\n margin-top: -0.1875rem;\n }\n\n @supports (padding-left: env(safe-area-inset-left)) {\n padding-left: #{\"max(0.75rem, env(safe-area-inset-left))\"};\n padding-right: #{\"max(0.5rem, env(safe-area-inset-right))\"};\n }\n }\n\n .AudioPlayer {\n flex-direction: row;\n margin-top: 0;\n padding: 0.25rem 0.5rem;\n\n &-content {\n padding: 0 0.5rem;\n flex-grow: 1\n }\n\n > .Button {\n margin: -.0625rem 0 0;\n }\n\n > .player-close {\n margin-left: auto;\n }\n }\n\n .HeaderPinnedMessage {\n flex-grow: 1;\n padding-top: 0;\n padding-bottom: 0;\n\n &::before {\n top: 0.125rem;\n bottom: 0.125rem;\n }\n\n .message-text {\n max-width: none;\n }\n }\n\n .HeaderPinnedMessage-wrapper.full-width {\n display: none;\n }\n}\n\n.MiddleHeader {\n display: flex;\n align-items: center;\n width: 100%;\n box-shadow: 0 2px 2px var(--color-light-shadow);\n background: var(--color-background);\n padding: .5rem .8125rem .5rem 1.5rem;\n position: relative;\n z-index: var(--z-middle-header);\n\n @supports (padding-left: env(safe-area-inset-left)) {\n padding-left: #{\"max(1.5rem, env(safe-area-inset-left))\"};\n padding-right: #{\"max(.8125rem, env(safe-area-inset-right))\"};\n }\n\n @media (max-width: 600px) {\n padding: 0.5rem;\n position: relative;\n\n @supports (padding-left: env(safe-area-inset-left)) {\n padding-left: #{\"max(.5rem, env(safe-area-inset-left))\"};\n padding-right: #{\"max(.5rem, env(safe-area-inset-right))\"};\n }\n }\n\n .Transition {\n width: 100%;\n // https://dfmcphee.com/flex-items-and-min-width-0/\n // https://stackoverflow.com/questions/36247140/why-dont-flex-items-shrink-past-content-size\n min-width: 0;\n\n > div {\n display: flex;\n align-items: center;\n width: 100%;\n }\n }\n\n .back-button {\n margin-left: -0.5rem;\n margin-right: 0.5rem;\n position: relative;\n\n @media (max-width: 600px) {\n margin-left: 0;\n }\n\n .unread-count {\n min-width: 1.25rem;\n height: 1.25rem;\n padding: 0 0.375rem;\n border-radius: 0.625rem;\n font-size: 0.75rem;\n line-height: 1.25rem;\n font-weight: 500;\n text-align: center;\n\n position: absolute;\n top: -0.25rem;\n right: -0.5rem;\n\n background: var(--color-gray);\n color: white;\n pointer-events: none;\n\n &.active {\n background: var(--color-primary);\n }\n }\n }\n\n .chat-info-wrapper {\n flex-grow: 1;\n overflow: hidden;\n }\n\n body.animation-level-0 & .HeaderPinnedMessage-wrapper {\n transition: none !important;\n }\n\n .header-tools {\n display: flex;\n align-items: center;\n justify-content: flex-end;\n margin-left: auto;\n flex-shrink: 0;\n\n body.animation-level-0 & {\n &,\n .AudioPlayer,\n .HeaderActions {\n transition: none !important;\n }\n }\n\n @media (min-width: 1276px) and (max-width: 1439px) {\n .HeaderActions {\n transform: translate3d(0, 0, 0);\n transition: transform var(--layer-transition);\n\n #Main.right-column-open & {\n transform: translate3d(calc(var(--right-column-width) * -1), 0, 0);\n }\n }\n }\n\n @media (min-width: 1440px) {\n transform: translate3d(0, 0, 0);\n transition: transform var(--layer-transition);\n\n #Main.right-column-open & {\n transform: translate3d(calc(var(--right-column-width) * -1), 0, 0);\n }\n }\n\n // @optimization\n @include while-transition() {\n pointer-events: none;\n }\n }\n\n @media (min-width: 1276px) and (max-width: 1439px) {\n &:not(.tools-stacked) .HeaderPinnedMessage-wrapper,\n &:not(.tools-stacked) .AudioPlayer {\n opacity: 1;\n\n #Main.right-column-open & {\n opacity: 0;\n }\n }\n }\n\n &.tools-stacked .AudioPlayer {\n @include mobile-header-styles();\n\n @media (min-width: 1150px) {\n #Main.right-column-open & {\n padding-right: calc(0.5rem + var(--right-column-width));\n }\n }\n }\n\n &.tools-stacked.animated .HeaderPinnedMessage-wrapper,\n &.tools-stacked.animated .AudioPlayer {\n animation: fade-in var(--layer-transition) forwards;\n\n body.animation-level-0 & {\n animation: none;\n }\n }\n\n h3 {\n font-weight: 500;\n font-size: 1.125rem;\n line-height: 1.375rem;\n white-space: pre;\n margin: 0;\n overflow: hidden;\n text-overflow: ellipsis;\n unicode-bidi: plaintext;\n\n body.is-ios &,\n body.is-macos & {\n font-size: 1.0625rem;\n font-weight: 600;\n }\n\n @media (max-width: 600px) {\n display: block;\n overflow: hidden;\n text-overflow: ellipsis;\n }\n\n @media (min-width: 1275px) {\n #Main.right-column-open & {\n max-width: calc(100% - var(--right-column-width));\n }\n }\n }\n\n .ChatInfo {\n cursor: pointer;\n display: flex;\n align-items: center;\n\n .info {\n display: flex;\n flex-direction: column;\n justify-content: center;\n flex-grow: 1;\n overflow: hidden;\n }\n\n .title {\n display: flex;\n align-items: center;\n\n .VerifiedIcon {\n width: 1.25rem;\n height: 1.25rem;\n margin-left: 0.25rem;\n margin-top: 0.05rem;\n }\n }\n\n .status {\n display: flex;\n unicode-bidi: plaintext;\n }\n\n .user-status {\n unicode-bidi: plaintext;\n overflow: hidden;\n text-overflow: ellipsis;\n\n @media (min-width: 1275px) {\n #Main.right-column-open & {\n max-width: calc(100% - var(--right-column-width));\n }\n }\n }\n }\n\n .Avatar {\n margin-right: .625rem;\n // TODO For some reason webpack imports `Audio.scss` second time when loading calls bundle\n width: 2.5rem !important;\n height: 2.5rem !important;\n font-size: 1.0625rem;\n }\n\n .status, .typing-status {\n font-size: 0.875rem;\n line-height: 1.125rem;\n margin: 0;\n color: var(--color-text-secondary);\n overflow: hidden;\n white-space: nowrap;\n text-overflow: ellipsis;\n display: inline-block;\n\n .ellipsis {\n display: inline-flex;\n }\n\n &.online {\n color: var(--color-primary);\n }\n\n .font-emoji {\n line-height: 1rem;\n }\n }\n\n .Button.smaller {\n width: 2.5rem;\n height: 2.5rem;\n }\n\n .HeaderPinnedMessage-wrapper {\n display: flex;\n align-items: center;\n margin-left: auto;\n cursor: default;\n flex-direction: row-reverse;\n background: var(--color-background);\n\n body.animation-level-1 & {\n .ripple-container {\n display: none;\n }\n }\n\n @media (min-width: 1276px) {\n transform: translate3d(0, 0, 0);\n transition: opacity 0.15s ease, transform var(--layer-transition);\n\n #Main.right-column-open & {\n transform: translate3d(calc(var(--right-column-width) * -1), 0, 0);\n }\n }\n\n\n .HeaderPinnedMessage {\n min-width: 16rem;\n }\n\n > .Button {\n flex-shrink: 0;\n }\n\n &.full-width {\n position: absolute;\n left: 0;\n right: 0;\n top: 100%;\n background: var(--color-background);\n padding: .25rem .8125rem .25rem 1rem;\n box-shadow: 0 .125rem .125rem var(--color-light-shadow);\n transform: translate3d(0, 0, 0);\n transition: opacity 0.15s ease, transform var(--layer-transition);\n\n &::before {\n content: \"\";\n display: block;\n position: absolute;\n top: -.1875rem;\n left: 0;\n right: 0;\n height: .125rem;\n box-shadow: 0 .125rem .125rem var(--color-light-shadow);\n }\n\n .HeaderPinnedMessage {\n margin-top: 0;\n margin-bottom: 0;\n flex: 1;\n\n .message-text {\n max-width: none;\n }\n }\n\n @media (min-width: 1276px) {\n transform: translate3d(0, 0, 0);\n transition: opacity 0.15s ease, transform var(--layer-transition);\n\n #Main.right-column-open & {\n padding-left: calc(var(--right-column-width) + 1rem);\n }\n }\n }\n }\n\n .HeaderPinnedMessage {\n display: flex;\n flex-shrink: 1;\n margin-top: -0.25rem;\n margin-bottom: -0.25rem;\n padding: 0.25rem;\n padding-left: 0.375rem;\n border-radius: var(--border-radius-messages-small);\n position: relative;\n overflow: hidden;\n cursor: pointer;\n\n &:hover {\n background-color: var(--color-interactive-element-hover);\n }\n\n .pinned-message-border {\n position: relative;\n height: 2.25rem;\n margin: 0.125rem 0;\n width: 0.125rem;\n min-width: 0.125rem;\n overflow: hidden;\n\n .pinned-message-border-wrapper-1 {\n height: 2.25rem;\n width: 0.125rem;\n border-radius: 0.0625rem;\n background: var(--color-primary);\n }\n\n .pinned-message-border-wrapper {\n background-color: var(--color-primary-opacity);\n position: relative;\n will-change: transform;\n transition: transform .25s ease-in-out;\n }\n\n .pinned-message-border-mark {\n position: absolute;\n left: 0;\n top: 0;\n width: 0.125rem;\n background: var(--color-primary);\n border-radius: 0.0625rem;\n will-change: transform;\n transition: transform .25s ease-in-out;\n }\n }\n\n .message-text {\n overflow: hidden;\n margin-inline-start: 0.375rem;\n margin-top: 0.125rem;\n max-width: 15rem;\n\n @media (min-width: 1440px) and (max-width: 1500px) {\n max-width: 14rem;\n }\n\n .title {\n font-weight: 500;\n font-size: 0.875rem;\n line-height: 1rem;\n height: 1rem;\n color: var(--color-primary);\n margin-bottom: 0.125rem;\n white-space: pre;\n text-align: initial;\n\n body.is-ios & {\n font-size: .9375rem;\n }\n }\n\n p {\n font-size: 0.875rem;\n line-height: 1.125rem;\n height: 1.125rem;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n margin: 0;\n\n body.is-ios & {\n font-size: .9375rem;\n }\n }\n }\n\n .emoji-small {\n width: 1rem;\n height: 1rem;\n }\n\n & > img {\n width: 2.25rem;\n height: 2.25rem;\n object-fit: cover;\n border-radius: 0.25rem;\n margin-inline-start: 0.375rem;\n margin-top: 0.125rem;\n flex-shrink: 0;\n\n & + .message-text {\n max-width: 12rem;\n }\n }\n }\n\n .HeaderActions {\n flex-shrink: 0;\n margin-left: auto;\n display: flex;\n align-items: center;\n justify-content: flex-end;\n\n .toggle-right-pane-button {\n &.active {\n color: var(--color-primary);\n opacity: 1;\n }\n }\n }\n\n .HeaderPinnedMessage-wrapper, .HeaderActions {\n .Button {\n margin-left: 0.25rem;\n\n &.tiny {\n margin-right: .625rem;\n }\n }\n }\n\n @media (max-width: 600px) {\n @include mobile-header-styles();\n }\n}\n\n@keyframes fade-in {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n",".EmbeddedMessage {\n display: flex;\n align-items: center;\n font-size: calc(var(--message-text-size, 1rem) - .125rem);\n line-height: 1.125rem;\n margin: 0 -0.25rem .0625rem;\n padding: .1875rem 0.25rem .1875rem .4375rem;\n border-radius: var(--border-radius-messages-small);\n position: relative;\n overflow: hidden;\n cursor: pointer;\n direction: ltr;\n\n body.animation-level-1 & {\n .ripple-container {\n display: none;\n }\n }\n\n .custom-shape & {\n max-width: 15rem;\n padding: 0.5rem;\n margin: 0;\n background-color: var(--background-color);\n box-shadow: 0 1px 2px var(--color-default-shadow);\n\n &::before {\n left: .625rem;\n top: .625rem;\n bottom: .625rem;\n }\n\n img:not(.emoji) {\n margin-inline-start: .5rem;\n }\n\n &:dir(rtl) {\n padding: 0.5rem;\n }\n }\n\n &::before {\n content: '';\n display: block;\n position: absolute;\n top: .3125rem;\n bottom: .3125rem;\n left: .3125rem;\n width: 2px;\n background: var(--accent-color);\n border-radius: 2px;\n }\n\n &:hover {\n background-color: var(--hover-color);\n }\n\n &:active {\n background-color: var(--active-color);\n }\n\n .message-title {\n font-size: calc(var(--message-text-size, 1rem) - .125rem);\n }\n\n .message-text {\n overflow: hidden;\n margin-inline-start: 0.5rem;\n display: flex;\n flex-direction: column-reverse;\n\n .message-title {\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n margin-bottom: 0.125rem;\n flex: 1;\n display: block;\n }\n\n p {\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n height: 1.125rem;\n margin-bottom: 0;\n flex: 1;\n\n &::after {\n content: none;\n display: none;\n }\n }\n\n .emoji {\n width: calc(1.125 * var(--message-text-size, 1rem)) !important;\n height: calc(1.125 * var(--message-text-size, 1rem)) !important;\n vertical-align: text-bottom !important;\n }\n }\n\n .embedded-action-message {\n color: var(--accent-color);\n opacity: 0.75;\n }\n\n img:not(.emoji) {\n width: 2rem;\n height: 2rem;\n object-fit: cover;\n border-radius: .25rem;\n margin-left: .25rem;\n flex-shrink: 0;\n\n &.round {\n border-radius: 1rem;\n }\n }\n\n &.inside-input {\n padding-inline-start: 0.5625rem;\n margin: 0 0 -.125rem -0.1875rem;\n display: grid;\n grid-template-columns: auto 1fr;\n grid-template-rows: 1fr;\n width: 100%;\n --accent-color: var(--color-primary);\n --hover-color: var(--color-interactive-element-hover);\n\n &::before {\n bottom: .3125rem;\n }\n\n img:not(.emoji) {\n margin-left: .125rem;\n }\n\n .message-text {\n margin-inline-start: .375rem;\n }\n\n .message-title {\n font-weight: 500;\n color: var(--accent-color);\n }\n }\n}\n",".MessageMeta {\n position: absolute;\n height: 1.25rem;\n bottom: 0;\n right: 0;\n display: flex;\n align-items: center;\n background: rgba(#999999, 0.6);\n border-radius: .625rem;\n padding: 0 .25rem;\n color: white;\n cursor: pointer;\n max-width: 100%;\n user-select: none;\n\n .message-time,\n .message-signature,\n .message-views {\n font-size: .75rem;\n white-space: nowrap;\n }\n\n .message-time {\n margin-right: .1875rem;\n }\n\n body.is-ios & {\n .message-time {\n margin-right: .25rem;\n }\n }\n\n .message-views {\n margin-inline-start: .1875rem;\n }\n\n .message-signature {\n overflow: hidden;\n text-overflow: ellipsis;\n margin-right: 0.375rem;\n }\n\n .icon-channelviews {\n margin-left: 0.125rem;\n margin-right: 0.375rem;\n font-size: 1.125rem;\n position: relative;\n top: -0.0625rem;\n }\n\n .has-solid-background & {\n color: rgba(var(--color-text-meta-rgb), 0.75);\n background: none;\n }\n\n .media:not(.text) &,\n .Message .custom-shape & {\n background: rgba(0, 0, 0, 0.2);\n --color-accent-own: white;\n --color-accent: white;\n color: white !important;\n opacity: 1;\n bottom: .25rem;\n right: .25rem;\n left: auto;\n height: 1.125rem;\n padding: 0 .3125rem 0 .375rem;\n\n .MessageOutgoingStatus i {\n background: transparent;\n }\n }\n\n .media:not(.text):dir(rtl) &,\n .Message .custom-shape:dir(rtl) & {\n right: auto !important;\n left: .25rem;\n padding: 0 .375rem 0 .3125rem;\n }\n\n .is-forwarded.media:not(.text):dir(rtl) &,\n .Message .is-forwarded.custom-shape:dir(rtl) & {\n left: .8125rem;\n }\n\n .is-forwarded.media:not(.text) & {\n bottom: 0.935rem;\n right: 0.8125rem;\n }\n\n .emoji-only & {\n right: 0;\n }\n\n .Message.own .has-solid-background & {\n color: var(--color-message-meta-own);\n }\n\n .MessageOutgoingStatus {\n margin-left: -.1875rem;\n font-size: 1.1875rem;\n border-radius: .625rem;\n\n .Message.own & {\n color: var(--color-accent-own);\n }\n }\n\n .message-content.has-replies:not(.custom-shape) & {\n bottom: 3.375rem;\n }\n\n .message-content.has-replies.text:not(.custom-shape) & {\n bottom: 3.4375rem;\n }\n\n &[dir=\"rtl\"] {\n .message-views {\n order: 10;\n }\n .icon-channelviews {\n order: 9;\n }\n }\n}\n\n.Message:not(.own) {\n .custom-shape .reply-message + .MessageMeta {\n right: auto;\n left: 13.2rem;\n bottom: 0.25rem;\n }\n\n .emoji-only-1 .reply-message + .MessageMeta {\n left: 2.5rem;\n }\n\n .emoji-only-2 .reply-message + .MessageMeta {\n left: 5.5rem;\n }\n\n .emoji-only-3 .reply-message + .MessageMeta {\n left: 6.5rem;\n }\n}\n",".Sticker {\n &:not(.inactive) {\n cursor: pointer;\n }\n\n &.inactive {\n pointer-events: none;\n }\n}\n",".Contact {\n display: flex;\n align-items: center;\n padding: 0.25rem;\n\n &.interactive {\n cursor: pointer;\n }\n\n .Avatar {\n margin-right: 0.8rem;\n }\n\n .contact-info {\n padding: 0.5rem;\n padding-left: 0;\n white-space: nowrap;\n overflow: hidden;\n\n .contact-name {\n font-size: 1rem;\n line-height: 1rem;\n margin-bottom: 0.25rem;\n font-weight: 500;\n }\n\n .contact-phone {\n line-height: 1rem;\n color: var(--secondary-color);\n }\n }\n}\n\n\n",".PollOption {\n display: flex;\n flex-flow: row nowrap;\n margin-bottom: 0.75rem;\n\n &:last-child {\n margin-bottom: 0;\n }\n\n .poll-option-text {\n word-break: break-word;\n }\n\n .poll-option-share {\n position: relative;\n margin-top: .125rem;\n width: 1.75rem;\n margin-inline-end: .5rem;\n flex-shrink: 0;\n font-weight: 500;\n font-size: .875rem;\n text-align: right;\n\n &.limit-width {\n display: inline-flex;\n justify-content: center;\n font-size: .75rem;\n }\n }\n\n .poll-option-chosen {\n position: absolute;\n right: 0;\n bottom: -5px;\n width: 1rem;\n height: 1rem;\n background: var(--accent-color);\n color: var(--background-color);\n border-radius: .5rem;\n font-size: .75rem;\n text-align: center;\n\n &.wrong {\n background: var(--color-error);\n }\n\n .is-forwarded & > i {\n margin-left: 1px;\n }\n\n &.animate {\n opacity: 0;\n animation-name: PollOptionIconAnimate;\n animation-delay: .09s;\n animation-duration: .3s;\n animation-fill-mode: forwards;\n }\n }\n\n .poll-option-right {\n flex-grow: 1;\n line-height: 1.5rem;\n }\n\n .poll-option-answer {\n position: relative;\n }\n\n .poll-option-line {\n position: relative;\n width: 0;\n height: 0.25rem;\n min-width: 0.5rem;\n border-radius: 0.125rem;\n margin-top: 0.5rem;\n background: var(--accent-color);\n\n transform-origin: 0 0;\n transition: transform .3s;\n transition-delay: .09s;\n\n }\n\n .poll-line {\n width: 30px;\n height: 35px;\n position: absolute;\n left: -27px;\n bottom: -5px;\n transition: stroke-dashoffset .3s, stroke-dasharray .3s;\n stroke-dashoffset: 0;\n stroke-dasharray: 0, 200%\n }\n\n .poll-line path {\n stroke-width: 4px;\n stroke-linecap: round;\n stroke: var(--accent-color);\n fill:none\n }\n\n .wrong {\n .poll-option-line {\n background: var(--color-error);\n }\n\n .poll-line path {\n stroke: var(--color-error);\n }\n }\n}\n\n@keyframes PollOptionIconAnimate {\n 0% { opacity: 0 }\n 100% { opacity: 1 }\n}\n",".Poll {\n min-width: 15rem;\n text-align: initial;\n\n @media (max-width: 600px) {\n min-width: 50vw;\n }\n\n .poll-question {\n font-weight: 500;\n line-height: 1.25rem;\n margin: 0.125rem 0;\n word-break: break-word;\n }\n\n .poll-type,\n .poll-voters-count {\n color: var(--secondary-color);\n font-size: 0.875rem;\n }\n\n .poll-type {\n margin-bottom: 0.5rem;\n display: flex;\n align-items: center;\n min-height: 1.375rem;\n }\n\n .poll-voters-count {\n margin: .4375rem 0 1.125rem;\n text-align: center;\n }\n\n .poll-answers {\n padding-top: 0.25rem;\n padding-bottom: 1rem;\n }\n\n .Checkbox,\n .Radio {\n padding-left: 2.25rem;\n\n &:last-child {\n margin-bottom: .75rem;\n }\n\n &.disabled {\n opacity: 1 !important;\n cursor: not-allowed;\n }\n\n .Checkbox-main,\n .Radio-main {\n &::before {\n left: 0.125rem;\n background-color: var(--background-color);\n\n .theme-dark & {\n --color-borders: var(--color-borders-input);\n }\n\n .Message.own & {\n --color-borders: var(--accent-color);\n }\n }\n\n &::after {\n left: 0.4375rem;\n background-color: var(--accent-color);\n }\n }\n\n input:checked ~ .Radio-main,\n input:checked ~ .Checkbox-main {\n &::before {\n border-color: var(--accent-color);\n }\n }\n\n .Spinner {\n left: 0.125rem;\n }\n }\n\n .Checkbox {\n .Checkbox-main {\n &::after {\n left: 0.125rem;\n background-color: var(--color-primary);\n\n .Message.own & {\n background-color: var(--accent-color);\n }\n }\n }\n }\n\n .Spinner > div {\n // gray spinner\n background-image: var(--spinner-gray-data);\n\n .theme-dark & {\n background-image: var(--spinner-white-data);\n }\n\n .Message.own & {\n // green spinner\n background-image: var(--spinner-green-data);\n .theme-dark & {\n background-image: var(--spinner-white-data);\n }\n }\n }\n\n .poll-recent-voters {\n display: inline-flex;\n align-items: center;\n vertical-align: text-bottom;\n margin-left: .875rem;\n margin-right: .5rem;\n margin-top: -2px;\n\n .Avatar {\n border: .0625rem solid var(--color-white);\n margin-right: 0;\n box-sizing: content-box;\n\n .Message.own & {\n border: .0625rem solid var(--secondary-color);\n }\n\n &:not(:first-child) {\n margin-left: -3px;\n }\n }\n }\n\n .poll-countdown {\n margin-left: auto;\n font-size: .75rem;\n transition: color .2s;\n\n &.hurry-up {\n color: var(--color-error);\n\n .poll-countdown-progress {\n stroke: var(--color-error);\n }\n }\n\n svg {\n vertical-align: -3px;\n }\n }\n\n .poll-countdown-progress {\n stroke: var(--color-primary);\n fill: transparent;\n stroke-width: 2;\n stroke-linecap: round;\n transition: stroke-dashoffset 2s, stroke .2s;\n }\n\n .poll-quiz-help {\n margin: -.625rem 0 -.625rem auto;\n .Message:not(.own) & {\n color: var(--color-primary);\n }\n }\n\n .poll-results,\n .poll-answers {\n padding-top: 0.25rem;\n padding-bottom: 0.5rem;\n }\n\n .Button {\n text-transform: none;\n font-size: 1rem;\n\n .Message.own & {\n color: var(--accent-color);\n --color-primary-shade-rgb: var(--color-accent-own);\n }\n }\n\n > .Button {\n margin-bottom: .625rem;\n }\n}\n",".WebPage {\n margin-top: 0.25rem;\n margin-bottom: 0.125rem;\n padding-left: .625rem;\n font-size: calc(var(--message-text-size, 1rem) - .125rem);\n line-height: 1.125rem;\n max-width: 29rem;\n position: relative;\n\n &::before {\n content: '';\n display: block;\n position: absolute;\n top: 0;\n bottom: 0;\n left: 0;\n width: .125rem;\n background: var(--accent-color);\n border-radius: .125rem;\n }\n\n &-text {\n display: flex;\n flex-direction: column;\n align-items: flex-start;\n }\n\n .media-inner {\n margin: 0 !important;\n margin-bottom: 0.375rem !important;\n\n &, & img, &.small-image img {\n border-radius: var(--border-radius-messages-small) !important;\n }\n\n &.square-image {\n width: 5rem;\n height: 5rem;\n min-height: 0;\n margin-bottom: 0 !important;\n\n img {\n width: 100%;\n height: 100%;\n }\n }\n }\n\n &.with-video .media-inner{\n margin-top: 0.5rem !important;\n margin-bottom: 1rem !important;\n }\n\n &.with-square-photo {\n display: flex;\n margin-bottom: 1rem;\n\n .WebPage-text {\n order: 1;\n padding-right: 1rem;\n }\n\n .media-inner {\n order: 2;\n flex-shrink: 0;\n }\n\n &:dir(rtl) {\n .WebPage-text {\n padding-inline-end: 1rem;\n }\n }\n }\n\n &:not(.with-square-photo) {\n .site-name,\n .site-title,\n .site-description {\n &:last-child::after {\n content: '';\n display: inline-block;\n width: var(--meta-safe-area-size);\n height: 0.75rem;\n float: right;\n }\n }\n }\n\n .site-name,\n .site-description,\n .site-title {\n word-break: break-word;\n max-width: 100%;\n }\n\n .site-name {\n color: var(--accent-color);\n font-weight: 500;\n margin-bottom: 0.125rem;\n }\n\n .site-title {\n font-weight: 500;\n margin-bottom: 0.125rem;\n }\n\n .site-description {\n line-height: 1.25;\n margin-bottom: 0;\n\n body.is-ios & {\n line-height: 1.125rem;\n }\n }\n\n &:dir(rtl) {\n padding-inline-start: .625rem;\n\n &::before {\n left: auto;\n right: 0;\n }\n }\n}\n\n\n",".Invoice {\n .title {\n color: var(--accent-color);\n font-weight: 500;\n }\n\n .description {\n position: relative;\n\n &.has-image {\n .invoice-image {\n max-width: 100%;\n height: 20rem;\n\n @media (max-width: 600px) {\n height: 10rem;\n }\n }\n\n .description-text {\n position: absolute;\n top: 0;\n padding: .25rem .5rem;\n margin: .25rem;\n background-color: rgba(90, 110, 70, 0.6);\n border-radius: var(--border-radius-messages-small);\n color: var(--color-text);\n font-weight: 500;\n\n span {\n margin-left: .5rem;\n }\n }\n }\n\n }\n}\n",".Album {\n position: relative;\n overflow: hidden;\n\n .message-content.media.text & {\n margin: -0.3125rem -0.5rem 0.3125rem;\n }\n\n .forwarded-message & {\n margin-bottom: .125rem;\n\n .message-content.media.text & {\n margin: 0 0 0.3125rem;\n --border-bottom-left-radius: inherit;\n --border-bottom-right-radius: inherit;\n }\n }\n\n &,\n .message-content.media.text & {\n > .album-item-select-wrapper .media-inner {\n margin: 0 !important;\n }\n }\n\n > .album-item-select-wrapper .media-inner {\n &, & img, & video {\n border-radius: 0 !important;\n object-fit: cover;\n }\n }\n}\n",".RoundVideo {\n position: relative;\n width: 15rem;\n height: 15rem;\n cursor: pointer;\n\n .thumbnail-wrapper {\n width: 15rem;\n height: 15rem;\n border-radius: 50%;\n overflow: hidden;\n }\n\n .video-wrapper {\n position: absolute;\n left: 0;\n top: 0;\n border-radius: 50%;\n overflow: hidden;\n }\n\n .progress {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n pointer-events: none;\n }\n\n .progress-circle {\n stroke: white;\n fill: transparent;\n stroke-width: 4;\n stroke-opacity: .35;\n stroke-linecap: round;\n }\n\n video::-internal-media-controls-cast-button,\n video::-webkit-media-controls,\n video::-webkit-media-controls-start-playback-button {\n display: none;\n }\n}\n",".InlineButtons {\n display: flex;\n flex-direction: column;\n\n .row {\n display: flex;\n flex-direction: row;\n }\n\n .Button {\n flex: 1;\n width: auto;\n margin: 0.125rem;\n background: var(--pattern-color);\n border-radius: var(--border-radius-messages-small);\n font-weight: 500;\n text-transform: none;\n\n &::before {\n content: '';\n background-color: var(--color-white);\n opacity: 0;\n\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n border-radius: var(--border-radius-messages-small);\n z-index: var(--z-below);\n transition: opacity 200ms;\n }\n\n &:hover {\n background: var(--pattern-color) !important;\n\n &::before {\n opacity: .4;\n }\n }\n\n &:first-of-type {\n margin-left: 0;\n }\n\n &:last-of-type {\n margin-right: 0;\n }\n\n i {\n font-size: .875rem;\n position: absolute;\n right: .1875rem;\n top: .1875rem;\n display: block;\n\n &.icon-arrow-right {\n font-size: .75rem;\n top: .125rem;\n right: .125rem;\n transform: rotate(-45deg);\n }\n }\n }\n\n .row:first-of-type .Button {\n margin-top: 0.25rem !important;\n }\n\n .row:last-of-type .Button {\n margin-bottom: 0;\n\n &:first-of-type {\n border-bottom-left-radius: var(--border-radius-messages);\n }\n\n &:last-of-type {\n border-bottom-right-radius: var(--border-radius-messages);\n }\n }\n}\n",".CommentButton {\n --background-color: var(--color-background);\n --hover-color: var(--color-chat-hover);\n\n display: flex;\n width: 100%;\n align-items: center;\n padding: .5625rem .25rem .5625rem .625rem;\n padding-inline-start: .625rem;\n padding-inline-end: .25rem;\n background: var(--background-color);\n border-bottom-right-radius: var(--border-bottom-right-radius);\n border-bottom-left-radius: var(--border-bottom-left-radius);\n font-size: .9375rem;\n font-weight: 500;\n line-height: 2rem;\n color: var(--accent-color);\n white-space: nowrap;\n cursor: pointer;\n transition: background-color .15s, color .15s;\n user-select: none;\n\n body.animation-level-0 & {\n transition: none !important;\n }\n\n .Message .has-appendix &::before {\n content: '';\n display: block;\n position: absolute;\n bottom: -.1875rem;\n left: -.5625rem;\n width: .5625rem;\n height: 1.25rem;\n background-position: bottom left;\n background-image: url('data:image/svg+xml,%3Csvg width=\"9\" height=\"20\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\"%3E%3Cdefs%3E%3Cfilter x=\"-50%25\" y=\"-14.7%25\" width=\"200%25\" height=\"141.2%25\" filterUnits=\"objectBoundingBox\" id=\"a\"%3E%3CfeOffset dy=\"1\" in=\"SourceAlpha\" result=\"shadowOffsetOuter1\"/%3E%3CfeGaussianBlur stdDeviation=\"1\" in=\"shadowOffsetOuter1\" result=\"shadowBlurOuter1\"/%3E%3CfeColorMatrix values=\"0 0 0 0 0.0621962482 0 0 0 0 0.138574144 0 0 0 0 0.185037364 0 0 0 0.15 0\" in=\"shadowBlurOuter1\"/%3E%3C/filter%3E%3Cpath d=\"M3 17h6V0c-.193 2.84-.876 5.767-2.05 8.782-.904 2.325-2.446 4.485-4.625 6.48A1 1 0 003 17z\" id=\"b\"/%3E%3C/defs%3E%3Cg fill=\"none\" fill-rule=\"evenodd\"%3E%3Cuse fill=\"%23000\" filter=\"url(%23a)\" xlink:href=\"%23b\"/%3E%3Cuse fill=\"%23FFF\" xlink:href=\"%23b\"/%3E%3C/g%3E%3C/svg%3E');\n opacity: 0;\n transition: opacity .15s, filter .15s;\n\n .theme-dark #root & {\n filter: invert(.83);\n }\n\n body.animation-level-0 & {\n transition: none !important;\n }\n }\n\n .custom-shape & {\n position: absolute;\n right: -3rem;\n width: 2.25rem;\n bottom: 3rem;\n height: 3.375rem;\n border-radius: 1.375rem;\n padding: 0.375rem .3125rem .25rem;\n align-items: flex-start;\n color: white;\n background-color: rgba(0, 0, 0, .2);\n\n opacity: 0;\n transition: opacity .2s ease;\n\n @media (pointer: coarse) {\n opacity: 1 !important;\n }\n\n &:hover {\n background-color: rgba(0, 0, 0, .28);\n }\n\n .Message:hover & {\n opacity: 1;\n }\n\n &::after {\n content: attr(data-cnt);\n position: absolute;\n bottom: -.0625rem;\n left: 0;\n width: 100%;\n text-align: center;\n font-size: 12px;\n display: block;\n }\n\n &[data-cnt=\"0\"] {\n height: 2.25rem;\n &::after {\n display: none;\n }\n }\n\n .icon-comments-sticker {\n display: block;\n font-size: 1.5rem;\n margin: 0 auto;\n }\n\n .recent-repliers,\n .icon-comments,\n .label,\n .icon-next {\n display: none;\n }\n }\n\n &:hover {\n background: var(--hover-color);\n\n .Message .has-appendix &::before {\n opacity: 1;\n }\n\n .Avatar {\n border-color: var(--hover-color) !important;\n }\n }\n\n .is-forwarded &,\n .audio &,\n .voice &,\n .poll &,\n .text & {\n border-top: 1px solid var(--color-borders);\n }\n\n .message-content.has-solid-background & {\n margin: .375rem -.5rem -.375rem;\n }\n\n .message-content.voice & {\n margin-bottom: -.5rem;\n }\n\n .message-content.audio & {\n margin-bottom: -.8125rem;\n }\n\n .message-content.audio &,\n .message-content.voice &,\n .message-content.poll &,\n .message-content.has-solid-background.text &,\n .message-content.has-solid-background.is-forwarded & {\n width: calc(100% + 1rem);\n }\n\n .icon-comments-sticker {\n display: none;\n }\n\n .icon-comments {\n font-size: 1.5625rem;\n line-height: 2rem;\n margin-inline-end: .875rem;\n }\n\n .icon-next {\n margin-inline-start: auto;\n font-size: 1.5rem;\n }\n\n .recent-repliers {\n display: inline-flex;\n align-items: center;\n margin-inline-end: .5rem;\n margin-inline-start: -.125rem;\n\n .Avatar {\n transition: border .15s;\n border: 2px solid var(--color-background);\n margin-inline-end: 0;\n z-index: 3;\n overflow: hidden;\n\n .emoji {\n width: 1rem;\n background-size: 1rem;\n }\n\n + .Avatar {\n z-index: 2;\n\n + .Avatar {\n z-index: 1;\n }\n }\n\n &:not(:first-child) {\n margin-inline-start: -.75rem;\n }\n }\n }\n\n &.has-unread .label {\n position: relative;\n\n &::after {\n content: '';\n display: inline-block;\n width: .5rem;\n height: .5rem;\n border-radius: 50%;\n background: var(--accent-color);\n margin-inline-start: \t.75rem;\n }\n }\n\n &.disabled {\n cursor: default;\n pointer-events: none;\n }\n}\n","// General styles\n.Message {\n display: flex;\n align-items: flex-end;\n margin-bottom: 0.375rem;\n position: relative;\n\n --background-color: var(--color-background);\n --hover-color: var(--color-reply-hover);\n --active-color: var(--color-reply-active);\n --max-width: 29rem;\n --accent-color: var(--color-primary);\n --accent-shade-color: var(--color-primary-shade);\n --secondary-color: var(--color-text-secondary);\n --meta-safe-area-base: 2.25rem;\n --meta-safe-author-width: 0px;\n --meta-safe-area-extra-width: 0px;\n --meta-safe-area-size: calc(var(--meta-safe-area-base) + var(--meta-safe-author-width) + var(--meta-safe-area-extra-width));\n --deleting-translate-x: -50%;\n --select-message-scale: 0.9;\n\n @media (min-width: 1921px) {\n --max-width: calc(30vw - 1rem);\n }\n\n &.is-swiped {\n transform: translateX(-2.5rem) !important;\n }\n\n &.is-protected {\n user-select: none;\n }\n\n > .Avatar,\n > .message-content-wrapper {\n opacity: 1;\n transform: scale(1) translateX(0);\n transition: transform var(--select-transition);\n\n body.animation-level-0 & {\n transition: none !important;\n }\n }\n\n > .Avatar {\n position: absolute;\n bottom: 0;\n left: 0;\n\n @media (max-width: 600px) {\n width: 2.5rem;\n height: 2.5rem;\n }\n }\n\n &.last-in-group {\n margin-bottom: 0.625rem;\n }\n\n &.last-in-list {\n // Forcing extra space which is taken by the appendix and causes incorrect container height calculation.\n // This value is accurately crafted as a minimum possible.\n margin-bottom: 0.375rem;\n }\n\n &.is-in-selection-mode {\n body.is-android & {\n .can-select-text {\n z-index: var(--z-message-select-control);\n }\n\n // Prevent media viewer from opening\n .media-inner {\n pointer-events: none;\n }\n }\n }\n\n &.has-inline-buttons {\n .message-content {\n border-bottom-right-radius: var(--border-radius-messages-small);\n }\n }\n\n &:not(.own) {\n padding-left: 2.5rem;\n\n .no-avatars &, &.is-thread-top {\n padding-left: 0;\n }\n\n @media (max-width: 600px) {\n padding-left: 2.875rem;\n\n .no-avatars &, &.is-thread-top {\n padding-left: 0.25rem;\n }\n }\n }\n\n &.own {\n flex-direction: row-reverse;\n --background-color: var(--color-background-own);\n --hover-color: var(--color-reply-own-hover);\n --active-color: var(--color-reply-own-active);\n --max-width: 30rem;\n --accent-color: var(--color-accent-own);\n --accent-shade-color: var(--color-green);\n --secondary-color: var(--color-accent-own);\n --color-code: var(--color-code-own);\n --color-code-bg: var(--color-code-own-bg);\n --color-links: var(--color-own-links);\n --meta-safe-area-base: 3.5rem;\n --deleting-translate-x: 50%;\n --color-text-green: var(--color-accent-own);\n\n @media (min-width: 1921px) {\n --max-width: 30vw;\n }\n\n body.is-ios &,\n body.is-macos & {\n --color-background-own: var(--color-background-own-apple);\n --color-reply-own-hover: var(--color-reply-own-hover-apple);\n --color-reply-own-active: var(--color-reply-own-active-apple);\n }\n\n @media (max-width: 600px) {\n padding-right: 0.25rem;\n }\n }\n\n &.is-deleting {\n > .Avatar,\n > .message-content-wrapper {\n transition: opacity .2s ease, transform .2s ease-in;\n opacity: 0;\n transform: scale(0.3) translateX(var(--deleting-translate-x));\n transform-origin: bottom;\n }\n }\n\n &.has-views {\n --meta-safe-area-extra-width: 4rem;\n }\n\n &.was-edited {\n --meta-safe-area-extra-width: 2.5rem;\n\n &.has-views {\n --meta-safe-area-extra-width: 7.5rem;\n }\n\n html[lang=ru] & {\n --meta-safe-area-extra-width: 3.5rem;\n\n &.has-views {\n --meta-safe-area-extra-width: 8.5rem;\n }\n }\n }\n\n .select-mode-active & {\n cursor: pointer;\n\n @media (min-width: 600px) {\n user-select: none;\n }\n\n &:not(.own) {\n > .Avatar,\n > .message-content-wrapper {\n transform: translateX(2.5rem);\n }\n }\n\n &:not(.is-album)::after {\n content: \"\";\n position: absolute;\n top: -0.25rem;\n bottom: -0.25rem;\n left: -4rem;\n right: -4rem;\n z-index: var(--z-message-select-area);\n }\n\n &.is-album,\n &.is-in-document-group {\n .message-select-control {\n pointer-events: unset;\n }\n }\n\n .message-select-control {\n opacity: 1;\n }\n }\n\n &.is-selected {\n .message-select-control {\n background: var(--color-green);\n\n &.group-select {\n background: transparent;\n\n &.is-selected {\n background: var(--color-green);\n }\n }\n }\n }\n\n .File.file-is-selected {\n .message-select-control {\n background: var(--color-green);\n }\n }\n\n &.is-in-document-group .File.file-is-selected .file-icon,\n &.has-menu-open.is-in-document-group .File .file-icon {\n --background-color: var(--color-background-selected);\n }\n\n &.own.is-in-document-group .File.file-is-selected .file-icon,\n &.own.has-menu-open.is-in-document-group .File .file-icon {\n --background-color: var(--color-background-own-selected);\n }\n\n .Audio .message-select-control {\n left: 1.0625rem;\n top: 1.375rem;\n }\n\n html.theme-dark &.own .Audio .toggle-play:not(.with-image) + .media-loading {\n .ProgressSpinner {\n background-image: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTUiIGhlaWdodD0iMTUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTguMjE4IDcuNWw1LjYzMy01LjYzM2EuNTA4LjUwOCAwIDEwLS43MTgtLjcxOEw3LjUgNi43ODIgMS44NjcgMS4xNDlhLjUwOC41MDggMCAxMC0uNzE4LjcxOEw2Ljc4MiA3LjVsLTUuNjMzIDUuNjMzYS41MDguNTA4IDAgMTAuNzE4LjcxOEw3LjUgOC4yMThsNS42MzMgNS42MzNhLjUwNi41MDYgMCAwMC43MTggMCAuNTA4LjUwOCAwIDAwMC0uNzE4TDguMjE4IDcuNXoiIGZpbGw9IiNGRkYiIGZpbGwtcnVsZT0ibm9uemVybyIgc3Ryb2tlPSIjODA3QkQ1IiBzdHJva2UtbGluZWpvaW49InJvdW5kIi8+PC9zdmc+);\n background-position: center;\n background-size: 1rem;\n\n circle {\n stroke: var(--background-color);\n }\n }\n }\n\n\n .File {\n position: relative;\n\n .message-select-control {\n position: absolute;\n top: 2rem;\n left: 2rem;\n z-index: 2;\n }\n }\n\n .album-item-select-wrapper {\n .Message.own & {\n background: var(--color-background-own);\n }\n\n .message-select-control {\n position: absolute;\n top: 0.438rem;\n right: 0.438rem;\n left: unset;\n }\n\n img, video {\n transition: transform var(--select-transition), opacity ease 300ms;\n }\n\n &.is-selected {\n .message-select-control {\n background: var(--color-green);\n }\n\n img, video {\n transform: scale(var(--select-message-scale));\n }\n }\n\n }\n\n &.is-selected, &.is-forwarding {\n .message-select-control {\n background: var(--color-green);\n }\n\n .Menu .bubble {\n transition: none !important;\n }\n }\n\n &.is-in-document-group {\n &:not(.first-in-document-group) {\n &::before {\n top: 0 !important;\n }\n\n .message-content {\n box-shadow: none;\n border-top-left-radius: 0 !important;\n border-top-right-radius: 0 !important;\n }\n\n .forwarded-message::before {\n top: -1.5rem;\n }\n }\n\n &:not(.last-in-document-group) {\n margin-bottom: 0;\n\n &::before {\n bottom: 0 !important;\n }\n\n .message-content {\n border-bottom-left-radius: 0 !important;\n border-bottom-right-radius: 0 !important;\n }\n }\n\n &.is-in-selection-mode {\n .Audio:not(.audio-is-selected),\n .File:not(.file-is-selected) {\n .message-select-control:not(.group-select) {\n background: white;\n\n &::after {\n content: '';\n width: 1.25rem;\n height: 1.25rem;\n border-radius: 0.688rem;\n background: white;\n border: 0.125rem rgba(0, 0, 0, 0.2) solid;\n position: absolute;\n }\n }\n }\n\n &.own {\n .message-content {\n .Audio:not(.audio-is-selected),\n .File:not(.file-is-selected) {\n .message-select-control:not(.group-select) {\n background: var(--background-color);\n border-color: var(--background-color);\n\n &::after {\n background: var(--background-color);\n border-color: var(--color-message-meta-own);\n }\n }\n }\n }\n }\n\n }\n\n &.focused,\n &.has-menu-open,\n &.is-forwarding,\n &.is-selected {\n .message-content {\n background: var(--color-background-selected);\n }\n\n &.own {\n .message-content {\n --background-color: var(--color-background-own-selected);\n background: var(--color-background-own-selected);\n }\n }\n }\n\n .message-content-wrapper {\n width: 17.1875rem;\n }\n\n .message-content {\n transition: background-color var(--select-transition);\n }\n\n &.own {\n .message-content-wrapper {\n display: flex;\n justify-content: flex-end;\n\n .message-content {\n width: 100%;\n }\n }\n }\n }\n\n .album-item-select-wrapper {\n position: absolute;\n\n .message-select-control {\n position: absolute;\n z-index: 2;\n }\n }\n\n .message-select-control {\n position: absolute;\n left: 0;\n bottom: 0.25rem;\n width: 1.5rem;\n height: 1.5rem;\n border: 2px solid white;\n border-radius: 50%;\n z-index: var(--z-message-select-control);\n\n display: flex;\n align-items: center;\n justify-content: center;\n\n color: white;\n font-size: 1rem;\n\n opacity: 0;\n pointer-events: none;\n transition: opacity var(--select-transition);\n\n .icon-select {\n position: absolute;\n left: -3px;\n top: -3px;\n font-size: 1.625rem;\n }\n\n .theme-dark & {\n border-color: #ffffff80;\n }\n }\n\n .Avatar {\n margin-right: 0.3rem;\n }\n\n &.is-in-document-group {\n .message-content.document {\n padding: .25rem .5rem !important;\n }\n\n &.last-in-document-group {\n .message-content.document {\n padding-bottom: .5rem !important\n }\n }\n\n &.first-in-document-group {\n .message-content.document {\n padding-top: .5rem !important\n }\n }\n }\n}\n\n// Border-radius styles\n.message-content,\n.Album,\n.media-inner,\n.message-content.media .media-inner img,\n.message-content.media .media-inner video,\n.message-content.custom-shape .media-inner img {\n border-top-left-radius: var(--border-top-left-radius);\n border-top-right-radius: var(--border-top-right-radius);\n border-bottom-left-radius: var(--border-bottom-left-radius);\n border-bottom-right-radius: var(--border-bottom-right-radius);\n}\n\n.media-inner video.full-media {\n background: transparent !important;\n}\n\n.media-inner {\n overflow: hidden;\n\n &.small-image img {\n border-radius: 0 !important;\n }\n}\n\n.Message {\n --border-top-left-radius: var(--border-radius-messages);\n --border-top-right-radius: var(--border-radius-messages);\n --border-bottom-left-radius: var(--border-radius-messages);\n --border-bottom-right-radius: var(--border-radius-messages);\n\n &:not(.own) {\n &.first-in-group:not(.last-in-group) {\n --border-bottom-left-radius: var(--border-radius-messages-small);\n }\n\n &:not(.first-in-group):not(.last-in-group) {\n --border-top-left-radius: var(--border-radius-messages-small);\n --border-bottom-left-radius: var(--border-radius-messages-small);\n }\n\n &.last-in-group:not(.first-in-group) {\n --border-top-left-radius: var(--border-radius-messages-small);\n }\n\n &.last-in-group {\n --border-bottom-left-radius: var(--border-radius-messages-small);\n\n .message-content.has-appendix {\n --border-bottom-left-radius: 0;\n }\n }\n }\n\n &.own {\n &.first-in-group:not(.last-in-group) {\n --border-bottom-right-radius: var(--border-radius-messages-small);\n }\n\n &:not(.first-in-group):not(.last-in-group) {\n --border-top-right-radius: var(--border-radius-messages-small);\n --border-bottom-right-radius: var(--border-radius-messages-small);\n }\n\n &.last-in-group:not(.first-in-group) {\n --border-top-right-radius: var(--border-radius-messages-small);\n }\n\n &.last-in-group {\n --border-bottom-right-radius: var(--border-radius-messages-small);\n\n .message-content.has-appendix {\n --border-bottom-right-radius: 0;\n border-bottom-right-radius: 0;\n }\n }\n }\n\n .message-content {\n &.has-replies:not(.custom-shape),\n &.text {\n .media-inner,\n .Album {\n --border-bottom-left-radius: 0;\n --border-bottom-right-radius: 0;\n }\n }\n\n &.is-reply .EmbeddedMessage {\n & + .Album,\n & + .Audio,\n & + .File {\n margin-top: .375rem;\n }\n }\n\n &:not(.custom-shape).is-reply .media-inner,\n &:not(.custom-shape).is-reply .Album,\n &:not(.custom-shape).force-sender-name .Album,\n &:not(.is-forwarded) .message-title ~ .media-inner {\n --border-top-left-radius: 0;\n --border-top-right-radius: 0;\n }\n\n &.is-forwarded .content-inner .message-title {\n margin-bottom: 0.25rem;\n }\n }\n\n .message-action-button {\n position: absolute;\n bottom: 0;\n color: white;\n background-color: rgba(0, 0, 0, .2);\n\n opacity: 0;\n transition: opacity .2s ease;\n\n @media (pointer: coarse) {\n opacity: 1 !important;\n }\n\n &:hover,\n &:active,\n &:focus {\n background-color: rgba(0, 0, 0, .28) !important;\n }\n }\n\n &:hover,\n &[data-is-document-group-hover] {\n .message-action-button {\n opacity: 1;\n }\n }\n\n &.own .message-action-button {\n left: -3rem;\n }\n\n &:not(.own) .message-action-button {\n right: -3rem;\n }\n\n .bottom-marker {\n height: 1px;\n width: 1px;\n visibility: hidden;\n }\n}\n\n.Message .custom-shape .message-action-button {\n bottom: .25rem;\n}\n\n@import 'message-content';\n",".message-content {\n position: relative;\n max-width: var(--max-width);\n\n @media (max-width: 600px) {\n max-width: calc(100vw - 6.25rem);\n\n .Message.own &,\n .MessageList.no-avatars & {\n max-width: calc(100vw - 3.75rem);\n }\n\n // Workaround for sass function override - we should use CSS min() here\n @supports (max-width: #{\"min(29rem, 100vw - 6.25rem)\"}) {\n max-width: #{\"min(29rem, 100vw - 6.25rem)\"};\n .MessageList.no-avatars & {\n max-width: #{\"min(29rem, 100vw - 3.75rem)\"};\n }\n .Message.own & {\n max-width: #{\"min(30rem, 100vw - 3.75rem)\"};\n }\n }\n\n &.has-action-button {\n max-width: calc(100vw - 7rem);\n\n .Message.own &,\n .MessageList.no-avatars & {\n max-width: calc(100vw - 4.5rem);\n }\n\n // Workaround for sass function override - we should use CSS min() here\n @supports (max-width: #{\"min(29rem, 100vw - 5.5rem)\"}) {\n max-width: #{\"min(29rem, 100vw - 7rem)\"};\n .MessageList.no-avatars & {\n max-width: #{\"min(29rem, 100vw - 4.5rem)\"};\n }\n .Message.own & {\n max-width: #{\"min(30rem, 100vw - 4.5rem)\"};\n }\n }\n }\n }\n\n img {\n -webkit-touch-callout: none;\n -webkit-user-select: none;\n }\n\n .text-content {\n margin: 0;\n word-break: break-word;\n line-height: 1.3125;\n text-align: initial;\n display: flow-root;\n unicode-bidi: plaintext;\n }\n\n .text-entity-link {\n unicode-bidi: plaintext;\n }\n\n &:not(.custom-shape) .text-content,\n &.document {\n & > .MessageMeta {\n position: relative;\n top: .375rem;\n bottom: auto !important;\n float: right;\n line-height: 1.35;\n height: calc(var(--message-meta-height, 1rem));\n margin-left: .4375rem;\n margin-right: -.5rem;\n\n .MessageOutgoingStatus .Transition {\n max-height: calc(var(--message-meta-height, 1rem));\n overflow: hidden;\n }\n\n html[data-message-text-size=\"12\"] & {\n top: .25rem;\n }\n\n html[data-message-text-size=\"17\"] & {\n top: .4375rem;\n }\n\n html[data-message-text-size=\"18\"] &,\n html[data-message-text-size=\"19\"] & {\n top: .5rem;\n }\n\n html[data-message-text-size=\"20\"] & {\n top: .5625rem;\n }\n }\n\n &:dir(rtl) {\n & > .MessageMeta {\n float: left;\n margin-left: -.25rem;\n margin-right: .4375rem;\n }\n }\n }\n\n &.document:not(.text) {\n &::after {\n content: \"\";\n display: block;\n clear: both;\n }\n\n & > .MessageMeta {\n top: auto !important;\n bottom: -.5rem !important;\n margin-top: -.25rem;\n\n &:not([dir=rtl]) {\n margin-top: -1.25rem;\n }\n }\n }\n\n .theme-dark .Message.own & {\n .text-entity-link {\n text-decoration: underline !important;\n\n &:hover {\n text-decoration: none !important;\n }\n }\n }\n\n &:not(.custom-shape) {\n font-size: var(--message-text-size, 1rem);\n\n body.is-ios & {\n font-size: var(--message-text-size, 1.0625rem);\n }\n\n & > .content-inner {\n min-width: 0;\n }\n }\n\n .matching-text-highlight {\n background: #CAE3F7;\n border-radius: 0.25rem;\n padding: 0 0.125rem;\n }\n\n .message-title {\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n font-size: calc(var(--message-text-size, 1rem) - .125rem);\n font-weight: 500;\n line-height: 1.25rem;\n color: var(--accent-color);\n unicode-bidi: plaintext;\n display: flex;\n\n & > .interactive {\n overflow: hidden;\n text-overflow: ellipsis;\n }\n\n &.interactive, & > .interactive {\n cursor: pointer;\n\n &:hover {\n opacity: 0.85;\n }\n }\n\n & > .color-1 {\n color: var(--color-user-1);\n }\n\n & > .color-2 {\n color: var(--color-user-2);\n }\n\n & > .color-4 {\n color: var(--color-user-4);\n }\n\n & > .color-5 {\n color: var(--color-user-5);\n }\n\n & > .color-6 {\n color: var(--color-user-6);\n }\n\n & > .color-7 {\n color: var(--color-user-7);\n }\n\n & > .color-8 {\n color: var(--color-user-8);\n }\n\n .theme-dark .Message.own & > .color-1 {\n color: var(--accent-color);\n }\n\n & + .File {\n margin-top: .25rem;\n }\n\n .via {\n padding-right: .25rem;\n font-weight: 400;\n }\n\n span + .via {\n padding-left: .25rem;\n }\n\n .admin-title {\n flex: 1;\n margin-left: 1rem;\n text-align: right;\n font-weight: 400;\n font-size: 0.75rem;\n margin-top: -0.1rem;\n color: rgba(var(--color-text-meta-rgb), 0.75);\n\n .Message.own & {\n color: var(--accent-color);\n }\n }\n }\n\n &.has-shadow {\n box-shadow: 0 1px 2px var(--color-default-shadow);\n }\n\n &.has-solid-background, &.has-background, .is-album & {\n background: var(--background-color);\n }\n\n &.has-solid-background {\n padding: .3125rem .5rem .375rem;\n\n .forwarded-message > .text-content:not(.with-meta):last-child::after {\n content: '';\n display: inline-block;\n width: var(--meta-safe-area-size);\n height: 1rem;\n }\n }\n\n body.is-ios &.has-solid-background {\n padding-bottom: 0.4375rem;\n }\n\n body.is-ios .Message.own &.has-solid-background {\n padding-left: 0.625rem;\n }\n\n &:not(.has-appendix) .svg-appendix {\n display: none;\n }\n\n .svg-appendix {\n overflow: hidden;\n position: absolute;\n bottom: -.0625rem;\n width: .5625rem;\n height: 1.125rem;\n font-size: 1rem !important;\n\n .corner {\n fill: var(--background-color);\n }\n\n .Message.own & {\n right: -.551rem; // This value is correct. Safari fix\n }\n\n .Message:not(.own) & {\n left: -.562rem; // This value is correct. Safari fix\n }\n }\n\n &[data-has-custom-appendix] {\n .svg-appendix .corner {\n fill: var(--appendix-bg);\n }\n }\n\n &.has-appendix-thumb {\n .Message & {\n .svg-appendix {\n --background-color: #ccc;\n opacity: 1;\n transition: opacity 500ms ease;\n }\n }\n }\n\n &.document {\n padding: .5rem !important;\n\n .File {\n .theme-dark & {\n --color-primary: var(--color-selection-highlight);\n }\n }\n\n .File + .text-content {\n margin-top: .3125rem;\n }\n }\n\n &.voice,\n &.audio {\n .message-title,\n .Embedded {\n margin-top: -.1875rem;\n margin-bottom: .1875rem;\n }\n }\n\n &.voice {\n padding: .5rem !important;\n\n .Voice + .text-content {\n margin-top: .5rem;\n }\n }\n\n &.audio {\n min-width: 20rem;\n padding: .5rem .5rem .8125rem !important;\n\n @media (max-width: 600px) {\n min-width: 17rem;\n }\n\n .Audio + .text-content {\n margin-top: .25rem;\n }\n\n &:not(.has-replies) {\n .Audio + .text-content {\n margin-bottom: -0.4375rem;\n }\n }\n }\n\n &:not(.custom-shape) .emoji {\n display: inline-block;\n width: 1.25rem;\n background-size: 1.25rem;\n color: transparent;\n margin-inline-end: 1px;\n vertical-align: text-bottom;\n\n &::selection {\n background-color: var(--color-selection-highlight-emoji);\n color: transparent;\n }\n }\n\n &:not(.custom-shape) .text-content .emoji {\n width: calc(1.25 * var(--message-text-size, 1rem));\n height: calc(1.25 * var(--message-text-size, 1rem));\n background-size: calc(1.25 * var(--message-text-size, 1rem));\n }\n\n .no-media-corners {\n --border-top-left-radius: 0;\n --border-top-right-radius: 0;\n }\n\n &.custom-shape.is-via-bot {\n font-size: inherit !important;\n\n .content-inner > .message-title {\n display: inline-flex;\n position: relative;\n top: .125rem;\n max-width: calc(100% - 3rem);\n margin-left: calc(100% - 3rem);\n padding: 0 .5rem;\n background-color: var(--background-color);\n border-radius: var(--border-radius-messages);\n\n .Message.own & {\n margin-left: -3rem;\n }\n }\n\n .media-inner {\n margin-top: 0.375rem;\n }\n }\n\n}\n\n.message-content.media, .WebPage {\n .media-inner {\n display: flex;\n justify-content: center;\n align-items: center;\n\n &.interactive {\n cursor: pointer;\n\n &.dark video {\n background-color: #232323;\n }\n }\n }\n\n &.round.is-reply {\n width: auto !important;\n }\n\n &.force-sender-name .media-inner,\n &.force-sender-name .Album,\n &.text .media-inner,\n &.is-via-bot .media-inner,\n &.is-reply .media-inner,\n &.is-reply .Album {\n margin-left: -0.5rem;\n margin-right: -0.5rem;\n\n body.is-ios .Message.own & {\n margin-left: -0.625rem;\n }\n }\n\n &.text .media-inner {\n margin-top: -0.3125rem;\n }\n\n &.is-reply .media-inner,\n &.force-sender-name .Album,\n &.is-reply .Album,\n .message-title ~ .media-inner {\n margin-top: 0.375rem;\n margin-bottom: -0.375rem;\n\n body.is-ios .Message.own & {\n margin-bottom: -0.4375rem;\n }\n }\n\n // Moved below .is-reply to overwrite its styles\n &.text .media-inner,\n &.text .Album {\n margin-bottom: 0.375rem;\n\n body.is-ios .Message.own & {\n margin-bottom: 0.375rem;\n }\n }\n\n .media-loading {\n display: flex;\n align-items: center;\n justify-content: center;\n\n &:not(.open) {\n opacity: 0.5;\n transform: scale(0);\n transition: opacity .3s ease, transform .3s ease;\n }\n }\n\n .icon-large-play, .icon-download {\n position: absolute;\n display: flex;\n align-items: center;\n justify-content: center;\n color: #fff;\n opacity: 0.7;\n transition: opacity 150ms;\n\n &:hover {\n opacity: 1;\n }\n\n &:before {\n display: flex;\n align-items: center;\n justify-content: center;\n width: 3.375rem;\n height: 3.375rem;\n border-radius: 50%;\n background: rgba(black, 0.25);\n }\n\n &.opacity-transition {\n transition: opacity .15s ease;\n\n &:not(.open) {\n opacity: 0;\n }\n }\n }\n\n .icon-download {\n font-size: 1.5rem;\n }\n\n .icon-large-play {\n font-size: 2.5rem;\n }\n\n .message-media-duration,\n .message-transfer-progress {\n background: rgba(0, 0, 0, .25);\n color: #fff;\n font-size: 0.75rem;\n position: absolute;\n left: .1875rem;\n top: .1875rem;\n z-index: 1;\n padding: 0 .375rem;\n border-radius: .75rem;\n line-height: 1.125rem;\n user-select: none;\n }\n\n .message-media-duration .icon-muted {\n vertical-align: -.1875rem;\n margin-left: .375rem;\n font-size: 1.0625rem;\n }\n}\n\n.message-content.custom-shape {\n line-height: 1.2;\n font-size: 10rem;\n display: flex;\n flex-wrap: wrap;\n align-items: flex-end;\n\n &.has-comments {\n min-height: 5.25rem;\n margin-top: 0 !important;\n\n &.has-replies {\n min-height: 6.5rem;\n }\n }\n\n &.is-reply {\n max-width: 100%;\n }\n\n .reply-message {\n display: flex;\n align-items: flex-start;\n flex-direction: row-reverse;\n direction: ltr;\n\n > p {\n margin-bottom: 0;\n }\n\n .EmbeddedMessage {\n margin-left: 0.5rem;\n border-radius: var(--border-radius-messages);\n\n @media (max-width: 600px) {\n max-width: calc(90vw - 13rem);\n }\n\n @media (max-width: 340px) {\n margin-left: -1rem;\n z-index: 1;\n max-width: calc(90vw - 12rem);\n }\n }\n }\n\n .text-content {\n margin-bottom: 1rem;\n }\n\n .media-inner {\n line-height: 1;\n font-size: 1rem;\n flex-shrink: 0;\n\n .full-media {\n top: 0;\n left: 0;\n bottom: 0;\n right: 0;\n }\n }\n\n .emoji {\n display: inline-block;\n color: transparent;\n\n &::selection {\n background-color: var(--color-selection-highlight-emoji);\n color: transparent;\n }\n }\n\n &.emoji-only {\n .text-content {\n margin-bottom: 0;\n text-shadow: 1px 1px 0 white, -1px -1px 0 white, -1px 1px 0 white, 1px -1px 0 white;\n img.emoji {\n filter: drop-shadow(1px 1px 0 white) drop-shadow(-1px 1px 0 white) drop-shadow(1px -1px 0 white) drop-shadow(-1px -1px 0 white);\n }\n\n .MessageMeta {\n text-shadow: none;\n }\n }\n }\n\n &.emoji-only-1 {\n min-width: 8rem;\n font-size: 4.5rem;\n\n .content-inner {\n height: 7rem;\n }\n\n .text-content {\n line-height: 1.5;\n text-align: center;\n }\n\n .Message.was-edited & {\n min-width: 10rem;\n }\n\n .emoji {\n width: 5rem;\n height: 5rem;\n }\n }\n\n &.emoji-only-2 {\n font-size: 4rem;\n margin-top: .5rem;\n min-width: 10rem;\n\n &.has-comments {\n margin-top: 1.25rem;\n }\n\n .Message.was-edited & {\n min-width: 12rem;\n }\n\n .emoji {\n width: 4rem;\n height: 4rem;\n margin-right: 0.375rem;\n }\n }\n\n &.emoji-only-3 {\n font-size: 3rem;\n margin-top: 1.75rem;\n min-width: 12rem;\n\n &.has-comments {\n margin-top: 2.5rem;\n }\n\n .Message.was-edited & {\n min-width: 14rem;\n }\n\n .emoji {\n width: 3rem;\n height: 3rem;\n margin-right: 0.375rem;\n }\n }\n\n .Message:not(.own) & {\n --hover-color: var(--color-reply-hover);\n --active-color: var(--color-reply-active);\n }\n\n .Message.own & {\n --hover-color: var(--color-reply-own-hover);\n --active-color: var(--color-reply-own-active);\n\n .reply-message {\n flex-direction: row;\n\n .EmbeddedMessage {\n margin-right: 0.5rem;\n\n @media (max-width: 340px) {\n margin-left: 0;\n z-index: 1;\n max-width: calc(90vw - 11.5rem);\n }\n }\n }\n }\n}\n\n.forwarded-message {\n .message-content.contact &,\n .message-content.voice &,\n .message-content.poll & {\n // MessageOutgoingStatus's icon needs more space\n margin-bottom: 0.5rem;\n }\n\n .message-content:not(.custom-shape) & {\n position: relative;\n margin-top: 0.25rem;\n padding-left: 0.625rem;\n\n &::before {\n content: '';\n display: block;\n position: absolute;\n top: 0;\n bottom: 0;\n left: 0.05rem;\n width: 2px;\n background: var(--accent-color);\n border-radius: 2px;\n }\n\n &:dir(rtl) {\n padding-inline-start: 0.625rem;\n\n &::before {\n left: auto;\n right: 0.05rem;\n }\n }\n }\n\n --border-top-left-radius: var(--border-radius-messages-small);\n --border-top-right-radius: var(--border-radius-messages-small);\n --border-bottom-left-radius: var(--border-radius-messages-small);\n --border-bottom-right-radius: var(--border-radius-messages-small);\n\n > .media-inner {\n margin: 0 !important;\n margin-bottom: 0.25rem !important;\n }\n}\n\n.long-word-break-all {\n word-break: break-all;\n}\n\n.text-entity-link {\n color: var(--color-links) !important;\n text-decoration: none !important;\n word-break: break-word;\n cursor: pointer;\n unicode-bidi: initial;\n\n &:hover, &:active, &:visited {\n text-decoration: underline !important;\n }\n}\n\n.text-entity-code, .text-entity-pre {\n color: var(--color-code);\n background: var(--color-code-bg);\n white-space: pre-wrap;\n margin: 0;\n padding: 1px 2px;\n border-radius: 4px;\n font-size: calc(var(--message-text-size, 1rem) - 0.0625rem);\n}\n",".SponsoredMessage {\n --border-top-left-radius: var(--border-radius-messages) !important;\n --border-bottom-left-radius: var(--border-radius-messages) !important;\n\n margin-top: -.5rem;\n margin-bottom: .5rem;\n\n &::before {\n display: none;\n }\n\n &__button.secondary {\n margin-top: .5rem;\n border: 1px solid var(--color-primary);\n border-radius: var(--border-radius-default-tiny);\n color: var(--color-primary);\n }\n}\n",".ContactGreeting {\n width: 100%;\n height: 100%;\n display: flex;\n align-items: center;\n justify-content: center;\n text-align: center;\n\n .wrapper {\n display: inline-flex;\n flex-direction: column;\n align-items: center;\n background: var(--pattern-color);\n width: 14.5rem;\n padding: .75rem 1rem;\n border-radius: 1.5rem;\n color: #fff;\n }\n\n .title {\n font-weight: 500;\n margin-bottom: 0;\n }\n\n .description {\n font-size: .9375rem;\n margin-bottom: 0;\n }\n\n .sticker {\n margin: 2rem 0 1rem;\n height: 10rem;\n width: 10rem;\n cursor: pointer;\n\n .thumbnail {\n height: 10rem;\n width: 10rem;\n }\n }\n}\n",".NoMessages {\n width: 100%;\n height: 100%;\n display: flex;\n align-items: center;\n justify-content: center;\n\n .icon {\n font-size: 5rem;\n margin: 0 auto 1rem;\n }\n\n .wrapper {\n display: inline-flex;\n flex-direction: column;\n background: var(--pattern-color);\n max-width: 20rem;\n padding: .75rem 1rem;\n border-radius: 1.5rem;\n color: #fff;\n\n &[dir=rtl] {\n text-align: right;\n }\n }\n\n .title {\n font-weight: 500;\n font-size: 1rem;\n margin-bottom: .25rem;\n text-align: center;\n unicode-bidi: plaintext;\n }\n\n .description {\n font-size: .9375rem;\n margin: 0;\n padding: 0;\n list-style: none;\n unicode-bidi: plaintext;\n }\n\n .list-checkmarks {\n font-size: .9375rem;\n margin: .25rem 0 0;\n padding: 0;\n list-style: none;\n unicode-bidi: plaintext;\n line-height: 1.8;\n\n li::before {\n content: '✓';\n margin-inline-end: .5rem;\n }\n }\n}\n","@import '../../styles/mixins';\n\n.MessageList {\n flex: 1;\n width: 100%;\n margin-bottom: .5rem;\n\n overflow: scroll;\n overflow-x: hidden;\n overflow-y: auto;\n @include overflow-y-overlay();\n\n transition: transform var(--layer-transition);\n\n body.animation-level-0 & {\n transition: none !important;\n }\n\n .mask-image-enabled & {\n mask-image: linear-gradient(to top, transparent 0, #000 0.5rem);\n }\n\n @media (pointer: coarse) {\n user-select: none;\n touch-callout: none;\n\n &.select-mode-active {\n user-select: auto;\n touch-callout: default;\n }\n }\n\n @supports (padding-bottom: env(safe-area-inset-bottom)) {\n transition: bottom 150ms ease-out, transform var(--layer-transition);\n body.keyboard-visible & {\n position: relative;\n bottom: calc(0px - env(safe-area-inset-bottom));\n\n body.keyboard-visible.animation-level-0 & {\n transition: none !important;\n }\n }\n }\n\n &.no-avatars .Message > .Avatar {\n display: none;\n }\n\n .messages-container {\n width: 100%;\n max-width: var(--messages-container-width);\n min-height: 100%;\n margin: 0 auto;\n display: flex;\n justify-content: flex-end;\n flex-direction: column;\n padding: 1rem 1rem 0 1.125rem;\n\n .force-messages-scroll & {\n margin-top: 100vh !important;\n }\n\n @media (max-width: 600px) {\n width: 100vw;\n padding: 2.75rem 0.5rem 0;\n // Patch for an issue on Android when rotating device\n margin: 0;\n }\n }\n\n &.no-composer {\n margin-bottom: 0;\n\n .last-in-list {\n margin-bottom: 1rem;\n }\n }\n\n &.select-mode-active, &.type-pinned {\n margin-bottom: 0;\n\n .last-in-list {\n margin-bottom: 5.625rem;\n\n @media (max-width: 600px) {\n margin-bottom: 4.25rem;\n }\n\n &.ActionMessage {\n padding-bottom: 0.125rem;\n }\n }\n }\n\n @media (max-width: 600px) {\n &.with-bottom-shift {\n margin-bottom: 0;\n .last-in-list {\n margin-bottom: 4.25rem;\n\n @supports (padding-bottom: env(safe-area-inset-bottom)) {\n body:not(.keyboard-visible) & {\n margin-bottom: calc(4.25rem + env(safe-area-inset-bottom));\n }\n }\n }\n }\n }\n\n .Message,\n .ActionMessage {\n position: relative;\n\n opacity: 1;\n transform: scale(1);\n transition: opacity .2s ease, transform .2s ease;\n\n &:not(.open) {\n transform: scale(0.8);\n opacity: 0;\n }\n\n // Restore stacking context\n // https://developer.mozilla.org/ru/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context\n &.open.shown {\n transform: none;\n }\n\n &::before {\n content: \"\";\n position: absolute;\n top: -0.1875rem;\n bottom: -0.1875rem;\n left: -50vw;\n right: -50vw;\n background: black;\n z-index: -1;\n\n opacity: 0;\n transition: opacity var(--select-transition);\n\n body.animation-level-0 & {\n transition: none !important;\n }\n }\n\n &:not(.last-in-group) {\n &::before {\n bottom: -0.1875rem;\n }\n }\n\n &:not(.first-in-group) {\n &::before {\n top: -0.1875rem;\n }\n }\n\n &.focused::before {\n // @optimization\n transition: none !important;\n }\n\n &.focused,\n &.is-forwarding,\n &.is-selected,\n &.has-menu-open {\n &::before {\n opacity: 0.1;\n\n .theme-dark & {\n opacity: .6;\n }\n }\n }\n }\n\n > .empty {\n width: 100%;\n height: 100%;\n display: flex;\n align-items: center;\n justify-content: center;\n\n & > span {\n max-width: 80%;\n text-align: left;\n }\n\n .text-entity-link {\n color: inherit !important;\n text-decoration: underline;\n\n &:hover, &:focus {\n text-decoration: none;\n }\n }\n }\n\n .sticky-date,\n .local-action-message,\n .ActionMessage,\n .empty {\n text-align: center;\n user-select: none;\n\n > span {\n display: inline-block;\n background: var(--pattern-color);\n color: white;\n font-size: calc(var(--message-text-size, 1rem) - .0625rem);\n font-weight: 500;\n line-height: 1.75;\n padding: 0 .5rem;\n border-radius: var(--border-radius-messages);\n word-break: break-word;\n\n body.is-ios &,\n body.is-macos & {\n font-size: calc(var(--message-text-size, 1rem) - .125rem);\n line-height: calc(var(--message-text-size, 1rem) + .5rem);\n }\n\n .emoji-small {\n vertical-align: text-bottom;\n width: calc(1.25 * var(--message-text-size, 1rem));\n height: calc(1.25 * var(--message-text-size, 1rem));\n background-size: calc(1.25 * var(--message-text-size, 1rem));\n }\n }\n }\n\n .sticky-date {\n margin-top: 1rem;\n margin-bottom: 1rem;\n z-index: var(--z-sticky-date);\n pointer-events: none;\n opacity: 1;\n transition: opacity .3s ease;\n\n body:not(.is-scrolling-messages) &.stuck {\n opacity: 0;\n\n span {\n pointer-events: none;\n }\n }\n\n body.animation-level-0 & {\n transition: none;\n }\n\n &.interactive {\n cursor: pointer;\n }\n\n span {\n pointer-events: auto;\n }\n }\n\n &.scrolled:not(.is-animating) .sticky-date {\n position: sticky;\n top: 0.625rem;\n }\n\n &.is-animating {\n overflow: hidden;\n }\n\n &.is-animating .message-select-control {\n display: none !important;\n }\n\n .has-header-tools & .sticky-date {\n top: 3.75rem !important;\n }\n\n .local-action-message,\n .ActionMessage {\n margin-top: 0.5rem;\n margin-bottom: 0.5rem;\n }\n\n .ActionMessage {\n .action-link {\n cursor: pointer;\n\n &:hover {\n text-decoration: underline;\n }\n }\n }\n\n .sticky-date + .ActionMessage {\n margin-top: -0.5rem;\n }\n\n @media (min-width: 1276px) {\n width: 100%;\n transform: translate3d(0, 0, 0);\n transition: transform var(--layer-transition);\n\n .messages-container {\n width: calc(100% - var(--right-column-width));\n }\n\n body.animation-level-0 & {\n transition: none;\n }\n\n #Main.right-column-open & {\n transform: translate3d(calc(var(--right-column-width) / -2), 0, 0);\n }\n\n body:not(.animating-right-column) #Main.right-column-open &.select-mode-active,\n #Main.right-column-open &:not(.select-mode-active),\n body.animating-right-column &:not(.select-mode-active) {\n width: calc(100% - var(--right-column-width));\n\n .messages-container {\n width: 100%;\n }\n }\n }\n\n @media (max-width: 600px) {\n transition: transform var(--layer-transition);\n\n body.enable-symbol-menu-transforms & {\n transform: translate3d(0, 0, 0);\n }\n\n body.is-symbol-menu-open & {\n transform: translate3d(0, calc(-1 * (var(--symbol-menu-height) + var(--symbol-menu-footer-height))), 0);\n }\n }\n\n .animating > div > & {\n &::-webkit-scrollbar {\n width: 0;\n }\n\n /* Styles for Firefox */\n @supports (scrollbar-width: none) {\n padding-right: .6875rem;\n scrollbar-width: none;\n }\n }\n}\n",".ScrollDownButton {\n --base-bottom-pos: 6rem;\n\n position: absolute;\n bottom: var(--base-bottom-pos);\n right: 1rem;\n opacity: 0;\n transform: translateY(4.5rem);\n transition: transform .25s cubic-bezier(0.34, 1.56, 0.64, 1), opacity .2s ease;\n z-index: var(--z-scroll-down-button);\n pointer-events: none;\n\n @supports (right: env(safe-area-inset-right)) {\n right: #{\"max(1rem, env(safe-area-inset-right))\"};\n }\n\n body.animation-level-0 & {\n transform: none !important;\n\n transition: opacity .15s;\n }\n\n @media (max-width: 600px) {\n right: 0.5rem;\n bottom: 4.5rem;\n\n @supports (padding-bottom: env(safe-area-inset-bottom)) {\n body:not(.keyboard-visible) & {\n bottom: calc(4.5rem + env(safe-area-inset-bottom));\n }\n }\n }\n\n &-inner {\n display: flex;\n flex-direction: column;\n align-items: center;\n\n > .Button {\n box-shadow: 0 1px 2px var(--color-default-shadow);\n color: var(--color-composer-button);\n\n i {\n font-size: 1.75rem;\n }\n }\n\n @media (min-width: 1276px) {\n transform: translateX(0);\n\n transition: transform var(--layer-transition);\n\n body.animation-level-0 & {\n transition: none !important;\n }\n\n #Main.right-column-open & {\n transform: translateX(calc(-1 * var(--right-column-width)));\n }\n }\n\n @media (max-width: 600px) {\n > .Button {\n width: 2.875rem;\n height: 2.875rem;\n }\n }\n }\n\n &.revealed {\n transform: translateY(0);\n opacity: 1;\n pointer-events: all;\n\n &.no-composer:not(.with-extra-shift) {\n transform: translateY(4rem);\n }\n }\n\n .unread-count {\n min-width: 1.5rem;\n height: 1.5rem;\n padding: 0 .45rem;\n border-radius: 0.75rem;\n font-size: 0.875rem;\n line-height: 1.5rem;\n font-weight: 500;\n text-align: center;\n\n position: absolute;\n top: -0.3rem;\n right: -0.3rem;\n\n background: var(--color-green);\n color: white;\n\n pointer-events: none;\n\n @media (max-width: 600px) {\n top: -0.7rem;\n right: auto;\n }\n }\n\n @media (max-width: 600px) {\n body.is-symbol-menu-open & {\n bottom: calc(var(--base-bottom-pos) + var(--symbol-menu-height) + var(--symbol-menu-footer-height));\n }\n }\n}\n",".BotKeyboardMenu {\n .bubble {\n width: 100% !important;\n max-width: 27rem;\n border-radius: var(--border-radius-default-small);\n }\n\n .content {\n display: flex;\n flex-direction: column;\n padding: .1875rem .625rem;\n max-height: 80vh;\n overflow: auto;\n\n @media (max-width: 600px) {\n max-height: 75vh;\n }\n\n .row {\n display: flex;\n flex-direction: row;\n }\n\n .row + .row {\n margin-top: .375rem;\n }\n\n .Button {\n flex: 1;\n width: auto;\n height: auto;\n min-height: 3.0625rem;\n border-radius: var(--border-radius-messages-small);\n border: 2px solid var(--color-primary);\n background: var(--color-background);\n color: var(--color-primary);\n font-weight: 500;\n text-transform: none;\n\n &:hover {\n color: #fff;\n border-color: var(--color-primary-shade);\n background: var(--color-primary-shade);\n }\n }\n\n .Button + .Button {\n margin-left: .375rem;\n }\n }\n}\n",".ComposerEmbeddedMessage {\n height: 2.625rem;\n transition: height 150ms ease-out, opacity 150ms ease-out;\n\n .select-mode-active + .middle-column-footer & {\n display: none;\n }\n\n &:not(.open) {\n height: 0 !important;\n }\n\n body.animation-level-0 & {\n transition: none !important;\n }\n\n & > div {\n display: flex;\n align-items: center;\n padding-right: 0.625rem;\n padding-top: 0.1875rem;\n }\n\n & > div > .Button {\n flex-shrink: 0;\n background: none !important;\n width: 3.5rem;\n height: 2.875rem;\n margin: 0 -0.0625rem 0 0;\n padding: 0;\n align-self: center;\n\n @media (max-width: 600px) {\n width: 2.875rem;\n }\n }\n}\n",".WebPagePreview {\n height: 2.625rem;\n transition: height 150ms ease-out, opacity 150ms ease-out;\n\n body.animation-level-0 & {\n transition: none !important;\n }\n\n .select-mode-active + .middle-column-footer & {\n display: none;\n }\n\n &:not(.open) {\n height: 0 !important;\n }\n\n // TODO Remove duplication with `.ComposerEmbeddedMessage`\n & > div {\n display: flex;\n align-items: center;\n padding-right: 0.625rem;\n padding-top: 0.1875rem;\n }\n\n --accent-color: var(--color-primary);\n\n .ComposerEmbeddedMessage + & {\n margin-top: 0.75rem;\n }\n\n & > div > .Button {\n flex-shrink: 0;\n background: none !important;\n width: 3.5rem;\n height: 2.875rem;\n margin: 0 -0.0625rem 0 0;\n padding: 0;\n align-self: center;\n\n @media (max-width: 600px) {\n width: 2.875rem;\n }\n }\n\n .WebPage {\n flex-grow: 1;\n margin: 0.1875rem 0 0.1875rem 0.125rem;\n max-width: calc(100% - 3.375rem);\n\n &::before {\n top: .1rem;\n bottom: .05rem;\n }\n\n &.with-video .media-inner { // TODO add support for video in previews in composer\n display: none;\n }\n\n .site-title,\n .site-description {\n flex: 1;\n max-width: 100%;\n max-height: 1rem;\n }\n\n .site-title {\n margin-top: .125rem;\n margin-bottom: 0.1875rem;\n }\n\n .site-description {\n overflow: hidden;\n white-space: nowrap;\n text-overflow: ellipsis;\n }\n }\n}\n","@import '../../../styles/mixins';\n\n.Composer {\n align-items: flex-end;\n\n .select-mode-active + .middle-column-footer & {\n position: absolute;\n padding-right: 2rem;\n bottom: 0;\n\n @supports (padding-bottom: env(safe-area-inset-bottom)) {\n bottom: env(safe-area-inset-bottom);\n }\n\n @media (max-width: 600px) {\n padding-right: 1rem;\n }\n\n &::before {\n right: 2.125rem;\n\n @media (max-width: 600px) {\n right: 1rem;\n }\n }\n\n .svg-appendix {\n opacity: 0;\n }\n }\n\n .form-control {\n --border-width: 0;\n }\n\n @keyframes show-send-as-button {\n from {\n width: 1rem;\n transform: scale(0);\n }\n\n to {\n width: 3.5rem;\n transform: scale(1);\n }\n }\n\n > .Button {\n flex-shrink: 0;\n margin-left: .5rem;\n\n &:not(.danger) {\n color: var(--color-composer-button);\n }\n\n @media (max-width: 600px) {\n width: 2.875rem;\n height: 2.875rem;\n }\n\n .icon-send,\n .icon-microphone-alt,\n .icon-check {\n position: absolute;\n }\n\n &:not(:active):not(:focus):not(:hover) {\n .icon-send,\n .icon-check {\n color: var(--color-primary);\n }\n }\n\n &.cancel {\n position: relative;\n z-index: 1;\n\n &:hover, &.active {\n background: var(--color-chat-hover);\n }\n }\n\n &.recording {\n position: relative;\n z-index: 0;\n transition: box-shadow .1s;\n }\n\n &.send {\n .icon-send {\n animation: grow-icon .4s ease-out;\n }\n\n .icon-microphone-alt,\n .icon-check {\n animation: hide-icon .4s forwards ease-out;\n }\n }\n\n &.record {\n .icon-microphone-alt {\n animation: grow-icon .4s ease-out;\n }\n\n .icon-send,\n .icon-check {\n animation: hide-icon .4s forwards ease-out;\n }\n }\n\n &.edit {\n .icon-send,\n .icon-microphone-alt {\n animation: hide-icon .4s forwards ease-out;\n }\n\n .icon-check {\n animation: grow-icon .4s ease-out;\n }\n }\n\n &.not-ready > i {\n animation-duration: 0ms !important;\n }\n\n body.animation-level-0 &, body.animation-level-1 & {\n .icon-send, .icon-microphone-alt, .icon-check {\n animation-duration: 0ms !important;\n }\n }\n }\n\n .send-as-button {\n z-index: 1;\n }\n\n body:not(.animation-level-0) & .send-as-button.appear-animation {\n animation: 0.25s ease-in-out forwards show-send-as-button;\n }\n\n .mobile-symbol-menu-button {\n width: 2.875rem;\n height: 2.875rem;\n position: relative;\n\n .icon-smile,\n .icon-keyboard,\n .Spinner {\n position: absolute;\n }\n\n .Spinner {\n --spinner-size: 1.5rem;\n }\n\n .icon-smile {\n animation: grow-icon .4s ease-out;\n }\n\n .icon-keyboard, .Spinner {\n animation: hide-icon .4s forwards ease-out;\n }\n\n &.not-ready > i {\n animation-duration: 0ms !important;\n }\n\n &.is-loading {\n .Spinner {\n animation: grow-icon .4s ease-out;\n }\n\n .icon-keyboard, .icon-smile {\n animation: hide-icon .4s forwards ease-out;\n }\n }\n\n &.menu-opened {\n .icon-keyboard {\n animation: grow-icon .4s ease-out;\n }\n\n .icon-smile, .Spinner {\n animation: hide-icon .4s forwards ease-out;\n }\n }\n }\n}\n\n#message-compose {\n flex-grow: 1;\n max-width: calc(100% - 4rem);\n background: var(--color-background);\n border-radius: var(--border-radius-messages);\n border-bottom-right-radius: 0;\n box-shadow: 0 1px 2px var(--color-default-shadow);\n position: relative;\n z-index: 1;\n\n .svg-appendix {\n position: absolute;\n bottom: -.1875rem;\n right: -.551rem; // This value is correct. Safari fix\n width: .5625rem;\n height: 1.25rem;\n transition: opacity 200ms;\n font-size: 1rem !important;\n\n .corner {\n fill: var(--color-background);\n }\n }\n\n @media (max-width: 600px) {\n max-width: calc(100% - 3.375rem);\n }\n}\n\n.message-input-wrapper {\n display: flex;\n\n > .Spinner {\n align-self: center;\n --spinner-size: 1.5rem;\n margin-right: -.5rem;\n }\n\n > .Button {\n flex-shrink: 0;\n background: none !important;\n width: 3.5rem;\n height: 3.5rem;\n margin: 0;\n padding: 0;\n align-self: flex-end;\n\n &:not(.faded):not(.activated) {\n color: var(--color-composer-button);\n }\n\n + .Button {\n margin-left: -1rem;\n }\n\n @media (max-width: 600px) {\n width: 2.875rem;\n height: 2.875rem;\n\n + .Button {\n margin-left: -0.6875rem;\n }\n }\n\n &.bot-commands {\n color: var(--color-primary) !important;\n\n // SymbolMenu button should be accessible if BotCommandsMenu opened\n body.is-touch-env &.activated + .Button.mobile-symbol-menu-button {\n z-index: calc(var(--z-menu-backdrop) + 1);\n }\n }\n\n &.scheduled-button i::after {\n content: '';\n position: absolute;\n top: .75rem;\n right: .875rem;\n border: .1875rem solid var(--color-background);\n box-sizing: content-box;\n width: .5rem;\n height: .5rem;\n border-radius: 50%;\n background: var(--color-green-darker);\n box-shadow: -.375rem -.25rem 0 -.1875rem var(--color-background);\n @media (max-width: 600px) {\n top: .5rem;\n right: .5rem;\n }\n }\n }\n\n > .input-group {\n flex-grow: 1;\n margin-bottom: 0;\n }\n\n .recording-state {\n display: inline-block;\n position: relative;\n line-height: 3.5rem;\n height: 3.5rem;\n padding: 0 3.125rem 0 1rem;\n font-family: \"Roboto\", -apple-system, BlinkMacSystemFont, \"Apple Color Emoji\", \"Helvetica Neue\", sans-serif;\n\n &::after {\n content: '';\n width: .75rem;\n height: .75rem;\n background: var(--color-error);\n border-radius: .375rem;\n position: absolute;\n top: 50%;\n margin-top: -.375rem;\n right: 1.3125rem;\n animation: recording-blink-like-macos 1.5s infinite;\n }\n\n @media (max-width: 600px) {\n height: 2.875rem;\n line-height: 2.875rem;\n }\n }\n}\n\n#message-input-text,\n#caption-input-text {\n position: relative;\n\n .form-control {\n padding: calc((3.25rem - var(--composer-text-size, 1rem) * 1.375) / 2 - var(--border-width, 0) * 2) calc(.9rem - var(--border-width));\n overflow: hidden;\n line-height: 1.375;\n font-family: Roboto, -apple-system, \"Apple Color Emoji\", \"Helvetica Neue\", sans-serif;\n unicode-bidi: plaintext;\n text-align: initial;\n font-size: var(--composer-text-size, 1rem);\n\n body.is-ios &,\n body.is-macos & {\n font-family: system-ui, -apple-system, BlinkMacSystemFont, \"Roboto\", \"Apple Color Emoji\", \"Helvetica Neue\", sans-serif;\n }\n\n &.overflown {\n overflow-y: auto;\n overflow-x: hidden;\n }\n\n &.touched, &:focus {\n & + .placeholder-text {\n display: none;\n }\n }\n\n &.focus-disabled {\n pointer-events: none;\n }\n }\n\n .forced-placeholder,\n .placeholder-text {\n position: absolute;\n color: var(--color-placeholders);\n pointer-events: none;\n unicode-bidi: plaintext;\n text-align: initial;\n line-height: 1.3125;\n font-size: var(--composer-text-size, 1rem);\n top: calc((3.25rem - var(--composer-text-size, 1rem) * 1.375) / 2);\n bottom: auto;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n max-width: 100%;\n }\n\n .forced-placeholder {\n z-index: var(--z-below);\n left: 0;\n }\n\n &[dir=rtl] .placeholder-text {\n right: 0;\n }\n\n .text-entity-link {\n color: var(--color-links) !important;\n cursor: default;\n text-decoration: none;\n\n &:hover, &:active, &:visited {\n text-decoration: underline !important;\n }\n }\n\n .clone {\n position: absolute;\n top: 0;\n left: 0;\n opacity: 0;\n pointer-events: none;\n z-index: -10;\n unicode-bidi: plaintext;\n text-align: initial;\n }\n}\n\n#message-input-text {\n flex-grow: 1;\n\n .form-control {\n margin-bottom: 0;\n background: transparent !important;\n border: none !important;\n border-radius: 0 !important;\n box-shadow: none !important;\n caret-color: var(--color-text);\n min-height: 3.5rem;\n max-height: 26rem;\n line-height: 1.3125;\n padding: calc((3.5rem - var(--composer-text-size, 1rem) * 1.3125) / 2) 0;\n white-space: pre-wrap;\n\n @media (max-width: 600px) {\n height: 2.875rem;\n min-height: 2.875rem;\n max-height: 16rem;\n padding: calc((2.875rem - var(--composer-text-size, 1rem) * 1.3125) / 2) 0;\n overflow: auto;\n }\n\n transition: height 100ms ease;\n\n body.animation-level-0 & {\n transition: none !important;\n }\n }\n\n .forced-placeholder,\n .placeholder-text {\n top: calc((3.5rem - var(--composer-text-size, 1rem) * 1.3125) / 2);\n\n @media (max-width: 600px) {\n top: calc((2.875rem - var(--composer-text-size, 1rem) * 1.3125) / 2);\n }\n }\n\n &:not(:only-child) {\n .form-control {\n padding-left: 0;\n padding-right: 0;\n }\n }\n\n .ComposerEmbeddedMessage + .message-input-wrapper &,\n .WebPagePreview + .message-input-wrapper & {\n .form-control.overflown {\n margin-top: 0.75rem;\n }\n }\n\n .emoji {\n width: 1.25rem;\n height: 1.25rem;\n margin: 0 1px -5px;\n vertical-align: 0;\n pointer-events: none;\n }\n}\n\n#caption-input-text {\n .form-control {\n height: 3.25rem;\n min-height: 3.25rem;\n max-height: 15rem;\n }\n\n .placeholder-text {\n bottom: .8125rem;\n left: .90625rem;\n }\n}\n\n.composer-tooltip {\n position: absolute;\n bottom: calc(100% + .5rem);\n left: 0;\n width: 100%;\n background: var(--color-background);\n border-radius: var(--border-radius-messages);\n padding: 0.5rem 0;\n max-height: 15rem;\n\n overflow-x: hidden;\n overflow-y: auto;\n @include overflow-y-overlay();\n\n box-shadow: 0 1px 2px var(--color-default-shadow);\n\n opacity: 0;\n transform: translateY(1.5rem);\n transform-origin: bottom;\n transition: opacity var(--layer-transition), transform var(--layer-transition);\n\n &:not(.shown) {\n display: none;\n }\n\n &.open {\n opacity: 1;\n transform: translateY(0);\n }\n\n .Loading {\n margin: 1rem 0;\n }\n}\n\n@keyframes recording-blink-like-macos {\n from {\n opacity: 1;\n }\n to {\n opacity: .3;\n }\n}\n","#middle-column-bg {\n position: absolute;\n top: 0;\n left: 0;\n bottom: 0;\n right: 0;\n overflow: hidden;\n z-index: -1;\n background-color: var(--theme-background-color);\n\n &::after {\n content: \"\";\n position: absolute;\n top: 0;\n left: 0;\n bottom: 0;\n right: 0;\n background-color: var(--theme-background-color);\n background-position: center;\n background-repeat: no-repeat;\n background-size: cover;\n\n body:not(.animation-level-0) #root & {\n transition: transform var(--layer-transition), background .2s !important;\n }\n\n body.animation-level-0 & {\n transition: none;\n }\n\n .theme-light & {\n background-image: url('../../assets/chat-bg.jpg');\n\n @media (max-width: 600px) {\n background-image: url('../../assets/chat-bg-mobile.jpg');\n }\n }\n }\n\n .custom-bg-color:not(.custom-bg-image) &::after {\n opacity: 0;\n }\n\n .custom-bg-image &::after {\n background-image: var(--custom-background) !important;\n filter: none;\n transform: scale(1.1);\n }\n\n .custom-bg-image.blurred &::after {\n filter: blur(12px);\n }\n\n @media screen and (min-width: 1276px) {\n body.animation-level-2 &::after {\n margin: -16rem -5rem -20rem 0;\n overflow: hidden;\n transform: scale(1);\n transform-origin: left center;\n transition: transform var(--layer-transition);\n }\n\n body.animation-level-2 #Main.right-column-open #MiddleColumn:not(.custom-bg-image) &::after {\n transform: scale(0.67) !important;\n }\n }\n\n body.animation-level-2 #Main.right-column-open #MiddleColumn:not(.custom-bg-image) &::after {\n @media screen and (min-width: 1921px) {\n transform: scale(0.8) !important;\n }\n\n @media screen and (min-width: 2600px) {\n transform: scale(0.95) !important;\n }\n }\n}\n\n#MiddleColumn {\n display: flex;\n justify-content: center;\n height: 100%;\n position: relative;\n z-index: 1;\n min-width: 0;\n\n @media (max-width: 600px) {\n overflow: hidden;\n }\n\n .messages-layout {\n --slide-transition: 450ms cubic-bezier(0.25, 1, 0.5, 1);\n\n display: flex;\n flex-direction: column;\n align-items: center;\n width: 100%;\n height: 100%;\n position: relative;\n overflow: hidden;\n\n > .Transition {\n width: 100%;\n height: 100%;\n overflow: hidden;\n\n > div {\n display: flex;\n flex-direction: column;\n align-items: center;\n }\n }\n }\n\n .messaging-disabled {\n &-inner {\n width: 100%;\n padding: 1rem;\n border-radius: var(--border-radius-messages);\n background: var(--color-background);\n color: var(--color-text-secondary);\n text-align: center;\n box-shadow: 0 1px 2px var(--color-default-shadow);\n }\n }\n\n .Composer {\n #message-compose {\n transform: scaleX(1) translateX(0);\n transition: transform var(--select-transition), border-bottom-right-radius var(--select-transition);\n\n &::before {\n transform: scaleX(-1) translateX(0);\n transition: transform var(--select-transition);\n }\n\n body.animation-level-0 & {\n &, &::before {\n transition: none !important;\n }\n }\n }\n\n .message-input-wrapper, &::before {\n opacity: 1;\n transition: opacity var(--select-transition);\n\n body.animation-level-0 & {\n transition: none !important;\n }\n }\n\n > .Button {\n opacity: 1;\n transform: scale(1);\n transition: opacity var(--select-transition), transform var(--select-transition), background-color 0.15s, color 0.15s;\n\n body.animation-level-0 & {\n transition: none !important;\n }\n }\n\n &.hover-disabled, &:not(.shown) {\n pointer-events: none;\n }\n\n &:not(.shown) {\n .ComposerEmbeddedMessage {\n height: 0;\n }\n\n #message-compose {\n transform: scaleX(var(--composer-hidden-scale, 1)) translateX(var(--composer-translate-x, 0));\n border-bottom-right-radius: var(--border-radius-messages);\n\n &::before {\n transform: scaleX(-1) translateX(200%);\n }\n }\n\n #editable-message-text {\n height: 3.5rem !important;\n\n @media (max-width: 600px) {\n height: 2.5rem !important;\n }\n }\n\n .message-input-wrapper, &::before {\n opacity: 0;\n }\n\n > .Button {\n opacity: 0 !important;\n transform: scale(0.5);\n }\n }\n }\n\n .messaging-disabled {\n transform: scaleX(1);\n transition: transform var(--select-transition);\n\n .messaging-disabled-inner span {\n opacity: 1;\n transition: opacity var(--select-transition);\n\n body.animation-level-0 & {\n transition: none !important;\n }\n }\n\n body.animation-level-0 & {\n transition: none !important;\n }\n\n &:not(.shown) {\n transform: scaleX(var(--composer-hidden-scale, 1));\n pointer-events: none;\n\n .messaging-disabled-inner span {\n opacity: 0;\n }\n }\n }\n\n .middle-column-footer {\n width: 100%;\n max-width: var(--messages-container-width);\n padding: 0 1rem;\n position: relative;\n display: flex;\n align-items: flex-end;\n z-index: var(--z-middle-footer);\n\n transform: translate3d(0, 0, 0);\n transition: top 200ms, transform var(--layer-transition);\n\n body.animation-level-0 & {\n transition: none !important;\n }\n\n @media (min-width: 1276px) {\n width: calc(100% - var(--right-column-width));\n\n #Main.right-column-open & {\n transform: translate3d(calc(var(--right-column-width) / -2), 0, 0);\n }\n }\n\n @media (max-width: 600px) {\n padding: 0 0.5rem;\n\n body.is-symbol-menu-open & {\n transform: translate3d(0, calc(-1 * (var(--symbol-menu-height) + var(--symbol-menu-footer-height))), 0);\n }\n }\n\n @supports (padding-bottom: env(safe-area-inset-bottom)) {\n &:not(.no-composer) {\n padding-bottom: env(safe-area-inset-bottom);\n top: 0;\n\n body.keyboard-visible & {\n top: env(safe-area-inset-bottom);\n }\n }\n }\n\n &::before {\n content: \"\";\n position: absolute;\n top: -.5625rem;\n left: 0;\n right: 0;\n height: 1px;\n background: linear-gradient(90deg, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.4) 2%, rgba(255, 255, 255, 0.4) 98%, rgba(255, 255, 255, 0) 100%);\n opacity: 0;\n transition: opacity 350ms ease;\n\n @media (max-width: 600px) {\n left: -2%;\n right: -2%;\n }\n }\n\n &.with-notch::before {\n opacity: 1;\n }\n\n html.theme-dark &::before {\n background: linear-gradient(90deg, rgba(127, 127, 127, 0) 0%, rgba(127, 127, 127, 0.4) 2%, rgba(127, 127, 127, 0.4) 98%, rgba(127, 127, 127, 0) 100%);\n }\n }\n}\n\n/* Common styles for message list fade-out shadow */\n.Composer,\n.MessageSelectToolbar,\n.messaging-disabled {\n margin-bottom: 1.25rem;\n\n @media (max-width: 600px) {\n margin-bottom: 0.5rem;\n }\n}\n\n.Composer,\n.MessageSelectToolbar,\n.unpin-all-button,\n.join-subscribe-button,\n.messaging-disabled {\n width: 100%;\n display: flex;\n justify-content: center;\n position: relative;\n}\n\n.MessageSelectToolbar-inner,\n.unpin-all-button,\n.join-subscribe-button,\n.messaging-disabled {\n .mask-image-disabled & {\n box-shadow: 0 .25rem .5rem .125rem var(--color-default-shadow);\n border-radius: var(--border-radius-messages);\n }\n}\n\n.middle-column-footer-button-container {\n width: 100%;\n display: flex;\n justify-content: center;\n position: absolute;\n padding-bottom: 1.25rem;\n\n .unpin-all-button {\n text-transform: capitalize;\n color: var(--color-black);\n\n @media (hover: hover) {\n &:hover {\n .icon-unpin {\n color: var(--color-white);\n }\n }\n }\n\n @media (max-width: 600px) {\n &:active, &:focus {\n .icon-unpin {\n color: var(--color-white);\n }\n }\n }\n\n .icon-unpin {\n margin-inline-start: -0.4375rem;\n margin-inline-end: .75rem;\n color: var(--color-text-secondary);\n font-size: 1.5rem;\n transition: color .15s\n }\n }\n\n .join-subscribe-button,\n .unpin-all-button {\n height: 3.5rem;\n transform: scaleX(1);\n transition: transform var(--select-transition), background-color .15s, color .15s;\n\n .select-mode-active + .middle-column-footer & {\n box-shadow: none;\n transform: scaleX(var(--unpin-hidden-scale));\n }\n\n @media (max-width: 600px) {\n height: 2.5rem;\n }\n }\n\n @media (max-width: 600px) {\n padding-bottom: 0.75rem;\n\n @supports (padding-bottom: env(safe-area-inset-bottom)) {\n padding-bottom: calc(.75rem + env(safe-area-inset-bottom));\n }\n }\n\n .mask-image-disabled &::before {\n background: unset;\n }\n}\n",".RightHeader {\n display: flex;\n align-items: center;\n height: var(--header-height);\n padding: 0.5rem .8125rem;\n pointer-events: auto;\n\n @media (max-width: 600px) {\n padding: 0.5rem;\n }\n\n .close-button {\n flex-shrink: 0;\n }\n\n > .Transition {\n flex: 1;\n height: 100%;\n\n > div {\n display: flex;\n align-items: center;\n }\n }\n\n h3 {\n margin-bottom: 0;\n font-size: 1.25rem;\n font-weight: 500;\n margin-left: 1.375rem;\n }\n\n .tools {\n display: flex;\n margin-left: auto;\n }\n\n .SearchInput {\n margin-left: 1rem;\n\n @media (min-width: 600px) {\n margin-right: 1rem;\n }\n }\n\n .DropdownMenu {\n margin-left: auto;\n }\n}\n","@import '../../styles/mixins';\n\n.Profile {\n height: 100%;\n display: flex;\n flex-direction: column;\n\n overflow-x: hidden;\n overflow-y: scroll;\n @include overflow-y-overlay();\n\n > .profile-info > .ChatInfo {\n grid-area: chat_info;\n\n .status.online {\n color: var(--color-primary);\n }\n }\n\n > .profile-info > .ChatExtra {\n padding: .875rem .5rem .5rem;\n box-shadow: inset 0 -.0625rem 0 0 var(--color-background-secondary-accent);\n border-bottom: .625rem solid var(--color-background-secondary);\n\n .narrow {\n margin-bottom: 0;\n }\n\n .inactive.no-selection {\n user-select: auto;\n -webkit-user-select: auto !important;\n }\n\n .Switcher {\n margin-left: auto;\n }\n [dir=rtl] {\n .Switcher {\n margin-left: 0;\n margin-right: auto;\n }\n }\n }\n\n .FloatingActionButton {\n z-index: 1;\n }\n}\n\n.shared-media {\n display: flex;\n flex-direction: column-reverse;\n\n .TabList {\n background: var(--color-background);\n top: -1px;\n z-index: 1;\n\n .Tab {\n padding: 1rem .75rem;\n\n span {\n white-space: nowrap;\n }\n\n i {\n bottom: -1rem;\n }\n }\n }\n\n .Transition {\n flex: 1;\n }\n\n .content {\n &.empty-list {\n height: 100%;\n padding-top: 5rem;\n display: flex;\n align-items: flex-start;\n justify-content: center;\n\n .Spinner {\n --spinner-size: 2.75rem;\n }\n }\n\n &.media-list {\n display: grid;\n grid-template-columns: repeat(3, 1fr);\n grid-auto-rows: 1fr;\n grid-gap: .0625rem;\n }\n\n &.documents-list {\n padding: 1.25rem;\n\n & .File + .File {\n margin-top: 1.25rem;\n }\n }\n\n &.links-list {\n padding: 1.25rem;\n\n .ProgressSpinner,\n .message-transfer-progress {\n display: none;\n }\n }\n\n &.audio-list,\n &.voice-list {\n padding: 1.25rem;\n\n & .Audio {\n .media-loading {\n top: 0;\n left: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n }\n\n & + .Audio {\n margin-top: 1.6875rem;\n }\n }\n }\n\n &.commonChats-list,\n &.members-list {\n padding: 0.5rem 1rem;\n\n @media (max-width: 600px) {\n padding: .5rem 0;\n .ListItem.chat-item-clickable {\n margin: 0;\n }\n }\n }\n }\n}\n",".AddChatMembers {\n height: 100%;\n overflow: hidden;\n position: relative;\n\n &-inner {\n height: 100%;\n overflow: hidden;\n }\n}\n","#RightColumn {\n position: absolute;\n top: 0;\n right: 0;\n width: var(--right-column-width);\n height: 100%;\n transform: translate3d(var(--right-column-width), 0, 0);\n background: var(--color-background);\n border-left: 1px solid var(--color-borders);\n z-index: var(--z-right-column);\n\n transition: transform var(--layer-transition);\n\n body.animation-level-0 & {\n transition: none;\n }\n\n // @optimization\n &:not(:hover) {\n .chat-item-clickable:not(.picker-list-item):nth-child(n + 18) {\n display: none !important;\n }\n }\n\n @media (max-width: 1275px) {\n box-shadow: 0 .25rem .5rem .125rem var(--color-default-shadow);\n border-left: none;\n }\n\n @media (max-width: 600px) {\n width: 100vw;\n transform: translate3d(110vw, 0, 0);\n }\n\n @supports (padding-right: env(safe-area-inset-right)) {\n padding-right: env(safe-area-inset-right);\n }\n\n > .Transition {\n height: calc(100% - var(--header-height));\n overflow: hidden;\n }\n\n .Management .section > .ChatInfo {\n padding: 0 1.5rem;\n margin: 1rem 0;\n text-align: center;\n\n .Avatar {\n margin: 0 auto .5rem;\n\n &.no-photo {\n cursor: default !important;\n }\n }\n\n .title {\n display: flex;\n justify-content: center;\n align-items: center;\n\n h3 {\n font-weight: 500;\n font-size: 1.25rem;\n line-height: 2rem;\n white-space: pre-wrap;\n word-break: break-word;\n }\n\n .VerifiedIcon {\n margin-left: 0.25rem;\n margin-bottom: .5rem;\n }\n\n .emoji {\n width: 1.5rem;\n height: 1.5rem;\n background-size: 1.5rem;\n }\n }\n\n .status {\n font-size: 0.875rem;\n color: #868e96;\n }\n }\n}\n\n#RightColumn-wrapper {\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n z-index: var(--z-right-column);\n overflow: hidden;\n visibility: hidden;\n pointer-events: none;\n\n @media (max-width: 1275px) {\n position: fixed;\n }\n\n &.is-hidden {\n display: none;\n }\n\n .overlay-backdrop {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n z-index: -1;\n background: black;\n opacity: 0;\n\n @media (max-width: 600px) {\n transition: opacity var(--layer-transition);\n\n body.animation-level-0 & {\n transition: none;\n }\n }\n }\n\n #Main.right-column-open &, body.animating-right-column & {\n visibility: visible;\n }\n\n #Main.right-column-open & {\n @media (max-width: 600px) {\n .overlay-backdrop {\n opacity: var(--layer-blackout-opacity);\n }\n }\n\n #RightColumn {\n pointer-events: auto;\n transform: translate3d(0, 0, 0);\n }\n }\n}\n","#Main {\n height: 100%;\n text-align: left;\n overflow: hidden;\n\n @media (min-width: 1276px) {\n position: relative;\n }\n\n @media (max-width: 600px) {\n height: calc(var(--vh, 1vh) * 100);\n }\n\n @media (min-width: 926px) {\n display: grid;\n grid-template-columns: auto 1fr;\n grid-template-rows: 100%;\n }\n}\n\n.has-group-call-header {\n --group-call-header-height: 2rem;\n #LeftColumn, #MiddleColumn, #RightColumn-wrapper {\n height: calc(100% - 2rem);\n margin-top: 2rem;\n }\n}\n\n#LeftColumn {\n min-width: 12rem;\n width: 33vw;\n max-width: 26.5rem;\n height: 100%;\n position: relative;\n\n & > div {\n height: 100%;\n overflow: hidden;\n }\n\n @media (max-width: 600px) {\n height: calc(var(--vh, 1vh) * 100);\n }\n\n @media (min-width: 926px) {\n max-width: 40vw;\n }\n\n @media (min-width: 1276px) {\n width: 25vw;\n max-width: 33vw;\n }\n\n @media (max-width: 925px) {\n position: fixed;\n left: 0;\n top: 0;\n height: calc(var(--vh, 1vh) * 100);\n width: 26.5rem !important;\n\n transform: translate3d(-5rem, 0, 0);\n transition: transform var(--layer-transition);\n\n body.animation-level-0 & {\n transition: none;\n }\n\n &::after {\n content: '';\n display: block;\n position: absolute;\n left: 0;\n top: 0;\n right: 0;\n bottom: 0;\n background: black;\n opacity: var(--layer-blackout-opacity);\n transition: opacity var(--layer-transition);\n z-index: 1;\n\n body.animation-level-0 & {\n transition: none;\n }\n\n // @optimization\n body.is-android & {\n display: none;\n }\n\n body.is-android .middle-column-shown & {\n display: block;\n }\n }\n\n #Main:not(.middle-column-open) & {\n transform: translate3d(0, 0, 0);\n\n &::after {\n opacity: 0;\n pointer-events: none;\n }\n }\n\n #Main.history-animation-disabled & {\n transition: none;\n\n &:after {\n transition: none;\n }\n }\n }\n\n @media (max-width: 600px) {\n max-width: none;\n width: 100vw !important;\n transform: translate3d(-20vw, 0, 0);\n\n @supports (left: env(safe-area-inset-left)) {\n left: env(safe-area-inset-left) !important;\n width: calc(100vw - env(safe-area-inset-left));\n }\n }\n}\n\n#RightColumn {\n @media (max-width: 600px) {\n height: calc(var(--vh, 1vh) * 100 + 1px);\n }\n\n #Main.history-animation-disabled & {\n transition: none;\n\n .overlay-backdrop {\n transition: none;\n }\n }\n}\n\n#Main.history-animation-disabled .overlay-backdrop {\n transition: none;\n}\n\n#MiddleColumn {\n border-left: 1px solid var(--color-borders);\n\n @media (max-width: 925px) {\n max-width: none;\n position: fixed;\n left: 0;\n top: 0;\n bottom: 0;\n right: 0;\n\n transform: translate3d(0, 0, 0);\n transition: transform var(--layer-transition);\n\n body.animation-level-0 & {\n transition: none;\n }\n\n #Main:not(.middle-column-open) & {\n transform: translate3d(26.5rem, 0, 0);\n }\n }\n\n @media (max-width: 600px) {\n border-left: none;\n\n #Main:not(.middle-column-open) & {\n transform: translate3d(100vw, 0, 0);\n }\n\n #Main.right-column-open & {\n transform: translate3d(-20vw, 0, 0);\n }\n }\n\n #Main.history-animation-disabled & {\n transition: none;\n\n &:after {\n transition: none;\n }\n }\n}\n\nbody.is-android.animation-level-1 {\n --layer-transition: 250ms ease-in-out;\n\n #LeftColumn, #MiddleColumn, #RightColumn {\n transition: transform var(--layer-transition), opacity var(--layer-transition);\n }\n\n #Main:not(.middle-column-shown) {\n #MiddleColumn {\n display: none;\n }\n }\n\n #Main:not(.middle-column-open) {\n #MiddleColumn {\n transform: translate3d(10vw, 0, 0);\n opacity: 0;\n }\n }\n\n #Main.middle-column-open {\n #LeftColumn {\n transform: translate3d(0, 0, 0);\n opacity: 0;\n }\n }\n\n #Main:not(.right-column-shown) {\n #RightColumn {\n display: none;\n }\n }\n\n #Main:not(.right-column-open) {\n #RightColumn {\n transform: translate3d(10vw, 0, 0);\n opacity: 0;\n }\n }\n\n #Main.right-column-open {\n #MiddleColumn {\n transform: translate3d(0, 0, 0);\n opacity: 0;\n }\n }\n}\n"],"names":[],"sourceRoot":""} \ No newline at end of file diff --git a/dist/87.74a4d72480e8214a0dde.js b/dist/87.74a4d72480e8214a0dde.js new file mode 100644 index 00000000..a707652f --- /dev/null +++ b/dist/87.74a4d72480e8214a0dde.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunktelegram_t=self.webpackChunktelegram_t||[]).push([[87],{4087:(e,t,s)=>{s.r(t),s.d(t,{Main:()=>xo});var n=s(5116),a=s(3716),o=s(4050),r=(s(7895),s(307)),i=s(1638),c=s(735),d=s(2858);function l(e){const{chatId:t,threadId:s}=(0,i.Bt)(e)||{};return t&&s?(e=(0,r.qr)(e,t,s,!1),e=(0,r.Pb)(e,t,s,void 0)):e}(0,n.Q6)("openLocalTextSearch",(e=>{const{chatId:t,threadId:s}=(0,i.Bt)(e)||{};if(t&&s)return(0,r.qr)(e,t,s,!0)})),(0,n.Q6)("closeLocalTextSearch",l),(0,n.Q6)("setLocalTextSearchQuery",((e,t,s)=>{const{chatId:n,threadId:a}=(0,i.Bt)(e)||{};if(!n||!a)return;const{query:o}=s,l=(0,d.uw)(n,a),{query:u}=e.localTextSearch.byChatThreadKey[l]||{};return o!==u&&(e=(0,r.Pb)(e,n,a,c.D)),(0,r.qr)(e,n,a,!0,o)})),(0,n.Q6)("setLocalMediaSearchType",((e,t,s)=>{const{chatId:n}=(0,i.Bt)(e)||{};if(!n)return;const{mediaType:a}=s;return(0,r.z5)(e,n,a)})),(0,n.Q6)("openChat",((e,t,s)=>{const{id:a,threadId:o=-1,type:c="thread",shouldReplaceHistory:d=!1}=s,u=(0,i.Bt)(e);return u&&u.chatId===a&&u.threadId===o&&u.type===c||(e=(0,r.pf)(e,a,o,"replyStack",[]),e=l(e=(0,r.i9)(e)),e={...e,messages:{...e.messages,contentToBeScheduled:void 0},...a!==e.forwardMessages.toChatId&&{forwardMessages:{}}},(0,n.R3)(e)),(0,r.Wy)(e,a,o,c,d)})),(0,n.Q6)("openPreviousChat",(e=>(0,r.Wy)(e,void 0))),(0,n.Q6)("openChatWithInfo",((e,t,s)=>{(0,n.R3)({...e,isChatInfoShown:!0}),t.openChat(s)})),(0,n.Q6)("resetChatCreation",(e=>({...e,chatCreation:void 0}))),(0,n.Q6)("setNewChatMembersDialogState",((e,t,s)=>({...e,newChatMembersProgress:s}))),(0,n.Q6)("openNextChat",((e,t,s)=>{const{targetIndexDelta:n,orderedIds:a}=s,{chatId:o}=(0,i.Bt)(e)||{};if(!o)return void t.openChat({id:a[0]});const r=a.indexOf(o);if(-1===r)return;const c=a[r+n];t.openChat({id:c,shouldReplaceHistory:!0})}));var u=s(6137),m=s(1713),h=s(7361),g=s(782),p=s(2267),f=s(3099);const I=a.ck+a.fK;let v;(0,n.Q6)("setScrollOffset",((e,t,s)=>{const{chatId:n,threadId:a,scrollOffset:o}=s;return(0,r.pf)(e,n,a,"scrollOffset",o)})),(0,n.Q6)("setReplyingToId",((e,t,s)=>{const{messageId:n}=s,a=(0,i.Bt)(e);if(!a)return;const{chatId:o,threadId:c}=a;return(0,r.pf)(e,o,c,"replyingToId",n)})),(0,n.Q6)("setEditingId",((e,t,s)=>{const{messageId:n}=s,a=(0,i.Bt)(e);if(!a)return;const{chatId:o,threadId:c,type:d}=a,l="scheduled"===d?"editingScheduledId":"editingId";return(0,r.pf)(e,o,c,l,n)})),(0,n.Q6)("editLastMessage",(e=>{const{chatId:t,threadId:s}=(0,i.Bt)(e)||{};if(!t||!s)return;const n=(0,i.Zw)(e,t),a=(0,i.Cb)(e,t,s);if(!n||!a)return;const o=(0,g.dF)(a,(t=>Boolean(n[t]&&(0,i._k)(e,n[t],s).canEdit)));return o?(0,r.pf)(e,t,s,"editingId",o):void 0})),(0,n.Q6)("replyToNextMessage",((e,t,s)=>{const{targetIndexDelta:n}=s,{chatId:a,threadId:o}=(0,i.Bt)(e)||{};if(!a||!o)return;const r=(0,i.Zw)(e,a),c=(0,i.Cb)(e,a,o);if(!r||!c)return;const d=(0,i.Yy)(e,a,o);let l;if((0,i.b9)(e,a,o)&&d){const e=Object.keys(r),t=e.indexOf(d.toString())+n;l=t<=e.length+1&&t>=0?Number(e[t]):void 0}else if(o===u._f){var m;const t=(0,i.Z1)(e,a);l=null==t||null===(m=t.lastMessage)||void 0===m?void 0:m.id}else{const t=(0,i.tZ)(e,a,o);l=null==t?void 0:t.lastMessageId}t.setReplyingToId({messageId:l}),t.focusMessage({chatId:a,threadId:o,messageId:l})})),(0,n.Q6)("openMediaViewer",((e,t,s)=>{const{chatId:n,threadId:a,messageId:o,avatarOwnerId:r,profilePhotoIndex:i,origin:c}=s;return{...e,mediaViewer:{chatId:n,threadId:a,messageId:o,avatarOwnerId:r,profilePhotoIndex:i,origin:c},forwardMessages:{}}})),(0,n.Q6)("closeMediaViewer",(e=>({...e,mediaViewer:{}}))),(0,n.Q6)("openAudioPlayer",((e,t,s)=>{const{chatId:n,threadId:a,messageId:o,origin:r,volume:i,playbackRate:c,isMuted:d}=s;return{...e,audioPlayer:{chatId:n,threadId:a,messageId:o,origin:null!=r?r:e.audioPlayer.origin,volume:null!=i?i:e.audioPlayer.volume,playbackRate:c||e.audioPlayer.playbackRate,isMuted:d||e.audioPlayer.isMuted}}})),(0,n.Q6)("setAudioPlayerVolume",((e,t,s)=>{const{volume:n}=s;return{...e,audioPlayer:{...e.audioPlayer,volume:n}}})),(0,n.Q6)("setAudioPlayerPlaybackRate",((e,t,s)=>{const{playbackRate:n}=s;return{...e,audioPlayer:{...e.audioPlayer,playbackRate:n}}})),(0,n.Q6)("setAudioPlayerMuted",((e,t,s)=>{const{isMuted:n}=s;return{...e,audioPlayer:{...e.audioPlayer,isMuted:n}}})),(0,n.Q6)("setAudioPlayerOrigin",((e,t,s)=>{const{origin:n}=s;return{...e,audioPlayer:{...e.audioPlayer,origin:n}}})),(0,n.Q6)("closeAudioPlayer",(e=>({...e,audioPlayer:{volume:e.audioPlayer.volume,playbackRate:e.audioPlayer.playbackRate,isMuted:e.audioPlayer.isMuted}}))),(0,n.Q6)("openPollResults",((e,t,s)=>{const{chatId:a,messageId:o}=s;(0,i.Jf)(e)?a===e.pollResults.chatId&&o===e.pollResults.messageId||(0,n.R3)({...e,pollResults:{chatId:a,messageId:o,voters:{}}}):window.setTimeout((()=>{const e=(0,n.Rd)();(0,n.R3)({...e,pollResults:{chatId:a,messageId:o,voters:{}}})}),450)})),(0,n.Q6)("closePollResults",(e=>{(0,n.R3)({...e,pollResults:{}})})),(0,n.Q6)("focusLastMessage",((e,t)=>{const s=(0,i.Bt)(e);if(!s)return;const{chatId:n,threadId:a}=s;let o;if(a===u._f){var r;const t=(0,i.Z1)(e,n);o=null==t||null===(r=t.lastMessage)||void 0===r?void 0:r.id}else{const t=(0,i.tZ)(e,n,a);o=null==t?void 0:t.lastMessageId}o&&t.focusMessage({chatId:n,threadId:a,messageId:o,noHighlight:!0})})),(0,n.Q6)("focusNextReply",((e,t)=>{const s=(0,i.Bt)(e);if(!s)return;const{chatId:a,threadId:o}=s,c=(0,i.p9)(e,a,o);if(c&&0!==c.length){const s=c.pop();e=(0,r.pf)(e,a,o,"replyStack",[...c]),(0,n.R3)(e),t.focusMessage({chatId:a,threadId:o,messageId:s})}else t.focusLastMessage()})),(0,n.Q6)("focusMessage",((e,t,s)=>{const{chatId:a,threadId:o=u._f,messageListType:c="thread",noHighlight:d,groupedId:l,groupedChatId:h,replyMessageId:g,isResizingContainer:p}=s;let{messageId:f}=s;if(void 0!==l){const t=(0,i.y8)(e,h,l);null!=t&&t.length&&([f]=t)}const y=(0,i.Bt)(e),Z=!y||a!==y.chatId||o!==y.threadId||c!==y.type;if(v&&(clearTimeout(v),v=void 0),v=window.setTimeout((()=>{let e=(0,n.Rd)();e=(0,r.cq)(e),e=(0,r.wV)(e),(0,n.R3)(e)}),d?I:1500),e=(0,r.cq)(e,a,f,d,p),e=(0,r.wV)(e,void 0),g){const t=(0,i.p9)(e,a,o)||[];e=(0,r.pf)(e,a,o,"replyStack",[...t,g])}Z&&(e=(0,r.wV)(e,m.fo.Static));const P=(0,i.Cb)(e,a,o);if(P&&P.includes(f))return(0,n.R3)(e),void t.openChat({id:a,threadId:o});if(Z&&(e=(0,r.pf)(e,a,o,"viewportIds",void 0)),e=(0,r.pf)(e,a,o,"outlyingIds",void 0),P&&!Z){const t=f>P[0]?m.fo.Down:m.fo.Up;e=(0,r.wV)(e,t)}(0,n.R3)(e),t.openChat({id:a,threadId:o}),t.loadViewportMessages()})),(0,n.Q6)("openForwardMenu",((e,t,s)=>{const{fromChatId:n,messageIds:a,groupedId:o}=s;let r;return o&&(r=(0,i.xH)(e,n,o)),{...e,forwardMessages:{fromChatId:n,messageIds:r||a,isModalShown:!0}}})),(0,n.Q6)("exitForwardMode",(e=>{(0,n.R3)({...e,forwardMessages:{}})})),(0,n.Q6)("setForwardChatId",((e,t,s)=>{const{id:a}=s;(0,n.R3)({...e,forwardMessages:{...e.forwardMessages,toChatId:a,isModalShown:!1}}),t.openChat({id:a}),t.closeMediaViewer(),t.exitMessageSelectMode()})),(0,n.Q6)("openForwardMenuForSelectedMessages",((e,t)=>{if(!e.selectedMessages)return;const{chatId:s,messageIds:n}=e.selectedMessages;t.openForwardMenu({fromChatId:s,messageIds:n})})),(0,n.Q6)("cancelMessageMediaDownload",((e,t,s)=>{const{message:a}=s,o=e.activeDownloads.byChatId[a.chatId];o&&o.length&&(0,n.R3)({...e,activeDownloads:{byChatId:{...e.activeDownloads.byChatId,[a.chatId]:o.filter((e=>e!==a.id))}}})})),(0,n.Q6)("downloadMessageMedia",((e,t,s)=>{const{message:a}=s;a&&(0,n.R3)({...e,activeDownloads:{byChatId:{...e.activeDownloads.byChatId,[a.chatId]:[...e.activeDownloads.byChatId[a.chatId]||[],a.id]}}})})),(0,n.Q6)("downloadSelectedMessages",((e,t)=>{if(!e.selectedMessages)return;const{chatId:s,messageIds:n}=e.selectedMessages,{threadId:a}=(0,i.Bt)(e)||{},o=(0,i.Zw)(e,s);o&&a&&n.map((e=>o[e])).filter((t=>(0,i._k)(e,t,a).canDownload)).forEach((e=>t.downloadMessageMedia({message:e})))})),(0,n.Q6)("enterMessageSelectMode",((e,t,s)=>{const{messageId:n}=s||{},a=(0,i.jr)(e);return a?(0,r.M6)(e,a.id,n):e})),(0,n.Q6)("toggleMessageSelection",((e,t,s)=>{const{messageId:a,groupedId:o,childMessageIds:c,withShift:d}=s,l=(0,i.Bt)(e);if(!l)return;const{chatId:u,threadId:m,type:g}=l;e=(0,r.Ob)(e,u,m,g,a,o,c,d),(0,n.R3)(e),e.shouldShowContextMenuHint&&(t.disableContextMenuHint(),t.showNotification({message:`To **edit** or **reply**, close this menu. Then ${h.$b?"long tap":"right click"} on a message.`}))})),(0,n.Q6)("disableContextMenuHint",(e=>{if(e.shouldShowContextMenuHint)return{...e,shouldShowContextMenuHint:!1}})),(0,n.Q6)("exitMessageSelectMode",r.i9),(0,n.Q6)("openPollModal",(e=>({...e,isPollModalOpen:!0}))),(0,n.Q6)("closePollModal",(e=>({...e,isPollModalOpen:!1}))),(0,n.Q6)("checkVersionNotification",((e,t)=>{const s=a.Ji.split(".").slice(0,2).join("."),{serviceNotifications:n}=e;if(n.find((({version:e})=>e===s)))return;const o={chatId:a.aw,date:(0,p.b)(e.serverTimeOffset),content:{text:(0,f.Z)('**Telegram Web Z was updated to version 1.28**\n\n👏 **Harder**\n• Support for join requests in groups and channels.\n• Support for more service messages.\n\n🤩 **Better**\n• Easier to select and adjust left column width.\n• Redundant single quotes removed in Spanish and French translations.\n• Support for hotkeys on non-qwerty keyboards.\n• Use Ctrl+Shift+F or Ctrl+F (in PWA mode) to open global or local search.\n• Chat: "Add to folder..." only appears for users with folders.\n• Support for `start` parameter in `tg://resolve` links.\n\n💪 **Stronger**\n• Fixed focusing on messages in a chat that was previously open.\n• Fixed missing stickers in sticker suggestions.\n• Fixed opening chats from user mentions.\n• Fixed various glitches when appearing as a channel in public groups.\n• Removed redundant download and forward options in chats with protected content.\n')},isOutgoing:!1};t.createServiceNotification({message:o,version:s})})),(0,n.Q6)("createServiceNotification",((e,t,s)=>{var o;const{message:r,version:c}=s,{serviceNotifications:d}=e,l=(0,i.Z1)(e,a.aw),u=Math.max((null===(o=l.lastMessage)||void 0===o?void 0:o.id)||0,...d.map((({id:e})=>e))),m=(d.length+1)/1e3,h=Math.floor(u)+m;r.id=h;const g={id:h,message:r,version:c,isUnread:!0};(0,n.R3)({...e,serviceNotifications:[...d.slice(-1e3),g]}),t.apiUpdate({"@type":"newMessage",id:r.id,chatId:r.chatId,message:r})})),(0,n.Q6)("openSeenByModal",((e,t,s)=>{const{chatId:n,messageId:a}=s;return{...e,seenByModal:{chatId:n,messageId:a}}})),(0,n.Q6)("closeSeenByModal",(e=>({...e,seenByModal:void 0}))),(0,n.Q6)("setGlobalSearchQuery",((e,t,s)=>{const{query:n}=s,{chatId:a}=e.globalSearch;return(0,r.No)(e,{globalResults:{},localResults:{},resultsByType:void 0,...n?{fetchingStatus:{chats:!a,messages:!0}}:{fetchingStatus:void 0},query:n})})),(0,n.Q6)("addRecentlyFoundChatId",((e,t,s)=>{const{id:n}=s,{recentlyFoundChatIds:a}=e.globalSearch;if(!a)return(0,r.No)(e,{recentlyFoundChatIds:[n]});const o=a.filter((e=>e!==n));return o.unshift(n),o.length>10&&o.pop(),(0,r.No)(e,{recentlyFoundChatIds:o})})),(0,n.Q6)("clearRecentlyFoundChats",(e=>(0,r.No)(e,{recentlyFoundChatIds:void 0}))),(0,n.Q6)("setGlobalSearchContent",((e,t,s)=>{const{content:n}=s;return(0,r.Og)(e,n)})),(0,n.Q6)("setGlobalSearchChatId",((e,t,s)=>{const{id:n}=s;return(0,r.No)(e,{chatId:n,query:void 0,resultsByType:void 0})})),(0,n.Q6)("setStickerSearchQuery",((e,t,s)=>{const{query:n}=s;return{...e,stickers:{...e.stickers,search:{query:n,resultIds:void 0}}}})),(0,n.Q6)("setGifSearchQuery",((e,t,s)=>{const{query:n}=s;return{...e,gifs:{...e.gifs,search:{query:n,offsetId:void 0,results:void 0}}}})),(0,n.Q6)("openUserInfo",((e,t,s)=>{const{id:n}=s;t.openChat({id:n})})),(0,n.Q6)("openChat",(e=>(0,r.x1)(e,void 0))),(0,n.Q6)("setUserSearchQuery",((e,t,s)=>{const{query:n}=s;return(0,r.Lm)(e,{globalUserIds:void 0,localUserIds:void 0,fetchingStatus:Boolean(n),query:n})})),s(3781);var y=s(1947),Z=s(6926);(0,n.Q6)("toggleChatInfo",(e=>({...e,isChatInfoShown:!e.isChatInfoShown}))),(0,n.Q6)("setLeftColumnWidth",((e,t,s)=>({...e,leftColumnWidth:s}))),(0,n.Q6)("resetLeftColumnWidth",(e=>({...e,leftColumnWidth:void 0}))),(0,n.Q6)("toggleManagement",(e=>{const{chatId:t}=(0,i.Bt)(e)||{};if(t)return{...e,management:{byChatId:{...e.management.byChatId,[t]:{...e.management.byChatId[t],isActive:!(e.management.byChatId[t]||{}).isActive}}}}})),(0,n.Q6)("closeManagement",(e=>{const{chatId:t}=(0,i.Bt)(e)||{};if(t)return{...e,management:{byChatId:{...e.management.byChatId,[t]:{...e.management.byChatId[t],isActive:!1}}}}})),(0,n.Q6)("openChat",(e=>{if(h.wB||h.p7)return{...e,isLeftColumnShown:0===e.messages.messageLists.length}})),(0,n.Q6)("toggleLeftColumn",(e=>({...e,isLeftColumnShown:!e.isLeftColumnShown}))),(0,n.Q6)("addRecentEmoji",((e,t,s)=>{const{emoji:n}=s,{recentEmojis:a}=e;if(!a)return{...e,recentEmojis:[n]};const o=a.filter((e=>e!==n));return o.unshift(n),o.length>18&&o.pop(),{...e,recentEmojis:o}})),(0,n.Q6)("addRecentSticker",((e,t,s)=>{const{sticker:n}=s,{recent:a}=e.stickers;if(!a)return{...e,stickers:{...e.stickers,recent:{hash:"0",stickers:[n]}}};const o=a.stickers.filter((e=>e.id!==n.id));return o.unshift(n),{...e,stickers:{...e.stickers,recent:{...a,stickers:o}}}})),(0,n.Q6)("showNotification",((e,t,s)=>{const n=s;n.localId=(0,Z.Z)({});const a=[...e.notifications],o=a.findIndex((e=>e.message===n.message));return-1!==o&&a.splice(o,1),a.push(n),{...e,notifications:a}})),(0,n.Q6)("dismissNotification",((e,t,s)=>{const n=e.notifications.filter((({localId:e})=>e!==s.localId));return{...e,notifications:n}})),(0,n.Q6)("showDialog",((e,t,s)=>{const{data:n}=s;if("message"in n&&n.hasErrorKey&&!(0,y.ZP)(n))return e;const a=[...e.dialogs];if("message"in n){const e=a.findIndex((e=>e.message===n.message));-1!==e&&a.splice(e,1)}return a.push(n),{...e,dialogs:a}})),(0,n.Q6)("dismissDialog",(e=>{const t=[...e.dialogs];return t.pop(),{...e,dialogs:t}})),(0,n.Q6)("toggleSafeLinkModal",((e,t,s)=>{const{url:n}=s;return{...e,safeLinkModalUrl:n}})),(0,n.Q6)("openHistoryCalendar",((e,t,s)=>{const{selectedAt:n}=s;return{...e,historyCalendarSelectedAt:n}})),(0,n.Q6)("closeHistoryCalendar",(e=>({...e,historyCalendarSelectedAt:void 0}))),(0,n.Q6)("openPaymentModal",((e,t,s)=>{const{chatId:n,messageId:a}=s;return{...e,payment:{...e.payment,chatId:n,messageId:a,isPaymentModalOpen:!0}}})),(0,n.Q6)("closePaymentModal",(e=>{const t=(0,r.bp)(e);return(0,r.WY)(t)})),(0,n.Q6)("addPaymentError",((e,t,s)=>{const{error:n}=s;return{...e,payment:{...e.payment,error:n}}})),s(1689),s(1363),s(6204);var P=s(1226),C=s(9118);const w=new Map,b=(0,C.Ds)((e=>e()),500,!1);async function S(e,t,s,o,c=!1,d=!1){const l=e.id;let u;switch(o){case m.Uq.Backwards:u=void 0;break;case m.Uq.Around:u=-(Math.round(a.hT/2)+1);break;case m.Uq.Forwards:u=-(a.hT+1)}const h=await(0,P.t9)("fetchMessages",{chat:(0,i.Cm)((0,n.Rd)(),l,t),offsetId:s,addOffset:u,limit:a.hT,threadId:t});if(!h)return;const{messages:p,users:f,chats:I,threadInfos:v}=h;let y=(0,n.Rd)();const Z=l===a.aw?y.serviceNotifications.map((({message:e})=>e)):[],C=[].concat(p,Z),w=(0,g.ee)(C,"id"),b=Object.keys(w).map(Number);y=(0,r.c_)(y,l,w),y=c?(0,r.ff)(y,l,t,b):(0,r.xj)(y,l,t,b),y=(0,r.Sh)(y,(0,g.ee)(f,"id")),y=(0,r.fZ)(y,(0,g.ee)(I,"id")),y=(0,r.j6)(y,l,v);let S=(0,i.gb)(y,l,t);const M=(0,i.qC)(y,l,t);if(c&&S&&M&&(M.length&&!(0,g.YE)(S,M)||(y=(0,r.xj)(y,l,t,M),S=(0,i.gb)(y,l,t),y=(0,r.pf)(y,l,t,"outlyingIds",void 0),c=!1)),!d){const e=c?M:S,{newViewportIds:n}=E(e,s,o);y=(0,r.y9)(y,l,t,n)}(0,n.R3)(y)}function E(e,t,s){const{length:n}=e,o=t?function(e,t){return te[e.length-1]?e.length-1:e.findIndex(((s,n)=>s===t||st))}(e,t):-1,r=s===m.Uq.Backwards?o:o+1||n,i=r-a.hT,c=r+a.hT-1,d=e.slice(Math.max(0,i),c+1);let l,u;switch(s){case m.Uq.Backwards:l=r>0,u=i>=0;break;case m.Uq.Forwards:l=r0,u=d.length===a.hT}return{newViewportIds:d,areSomeLocal:l,areAllLocal:u}}async function M(e){let t;const s=e.attachment?(e,a)=>{w.has(a)||(t=a,w.set(a,s));const o=(0,n.Rd)();(0,n.R3)({...o,fileUploads:{byMessageLocalId:{...o.fileUploads.byMessageLocalId,[a]:{progress:e}}}})}:void 0;(e.replyingTo||h.cj)&&await(0,C.Pn)();const a=(0,n.Rd)();e.serverTimeOffset=a.serverTimeOffset;const o=(0,i.Bt)(a);if(!o)return;const{threadId:r}=o;e.replyingTo||r===u._f||(e.replyingTo=(0,i.qS)(a,e.chat.id,r)),await(0,P.t9)("sendMessage",e,s),s&&t&&w.delete(t)}(0,n.Q6)("loadViewportMessages",((e,t,s)=>{const{direction:n=m.Uq.Around,isBudgetPreload:o=!1}=s||{};let{chatId:c,threadId:d}=s||{};if(!c){const t=(0,i.Bt)(e);if(!t)return;c=t.chatId,d=t.threadId}const l=(0,i.Z1)(e,c);if(!l||l.isRestricted)return;const u=(0,i.Cb)(e,c,d),h=(0,i.gb)(e,c,d),g=(0,i.qC)(e,c,d);if(u&&u.length&&n!==m.Uq.Around){const s=n===m.Uq.Backwards?u[0]:u[u.length-1],a=Boolean(g),i=a?g:h,{newViewportIds:p,areSomeLocal:f,areAllLocal:I}=E(i,s,n);if(f&&(e=(0,r.y9)(e,c,d,p)),async function(e,t,s,n,a,o,r,i){t||await S(a,o,i,r,s,n),n||(await Promise.resolve(),e.loadViewportMessages({chatId:a.id,threadId:o,direction:r,isBudgetPreload:!0}))}(t,I,a,o,l,d,n,s),o)return}else{const t=(0,i.G$)(e,c)||(0,i.rd)(e,c,d),s=Boolean(t&&h&&!h.includes(t)),n=(s?g:h)||[],{newViewportIds:u,areSomeLocal:p,areAllLocal:f}=E(n,t,m.Uq.Around);p&&u.length>=a.hT&&(e=(0,r.y9)(e,c,d,u)),f||S(l,d,t,m.Uq.Around,s,o)}return e})),(0,n.Q6)("loadMessage",((e,t,s)=>{const{chatId:a,messageId:o,replyOriginForId:c,threadUpdate:d}=s,l=(0,i.Z1)(e,a);l&&(async()=>{const e=await async function(e,t,s){const a=await(0,P.t9)("fetchMessage",{chat:e,messageId:t});if(!a)return;if(a===u._Q){if(s){let t=(0,n.Rd)();const a=(0,i.hj)(t,e.id,s);t=(0,r.cY)(t,e.id,s,{...a,replyToMessageId:void 0}),(0,n.R3)(t)}return}let o=(0,n.Rd)();return o=(0,r.cY)(o,e.id,t,a.message),o=(0,r.Sh)(o,(0,g.ee)(a.users,"id")),(0,n.R3)(o),a.message}(l,o,c);if(e&&d){const{lastMessageId:t,isDeleting:s}=d;(0,n.R3)((0,r.lG)((0,n.Rd)(),e,a,t,s))}})()})),(0,n.Q6)("sendMessage",((e,t,s)=>{const n=(0,i.Bt)(e);if(!n)return;const{chatId:o,threadId:r,type:c}=n;if("scheduled"===c&&!s.scheduledAt)return{...e,messages:{...e.messages,contentToBeScheduled:s}};const d=(0,i.Z1)(e,o),l={...s,chat:d,replyingTo:(0,i.Yy)(e,o,r),noWebPage:(0,i.tV)(e,o,r),sendAs:(0,i._5)(e,o)};t.setReplyingToId({messageId:void 0}),t.clearWebPagePreview({chatId:o,threadId:r,value:!1});const u=!s.attachments||s.attachments.length<=1,m=!u&&s.attachments&&s.attachments.length>1;if(u){const{attachments:e,...t}=l;M({...t,attachment:e?e[0]:void 0})}else if(m){const{text:e,entities:t,attachments:s,...n}=l,o=(0,g.Vl)(s,a.DU);for(let s=0;s0?i:void 0}),r.forEach((e=>{M({...n,attachment:e,groupedId:i})}))}}else{const{text:e,entities:t,attachments:s,replyingTo:n,...a}=l;e&&M({...a,text:e,entities:t,replyingTo:n}),s.forEach((e=>{M({...a,attachment:e})}))}})),(0,n.Q6)("editMessage",((e,t,s)=>{const{serverTimeOffset:n}=e,{text:a,entities:o}=s,r=(0,i.Bt)(e);if(!r)return;const{chatId:c,threadId:d,type:l}=r,u=(0,i.Z1)(e,c),m=(0,i.kK)(e,c,d,l);u&&m&&((0,P.t9)("editMessage",{chat:u,message:m,text:a,entities:o,noWebPage:(0,i.tV)(e,c,d),serverTimeOffset:n}),t.setEditingId({messageId:void 0}))})),(0,n.Q6)("cancelSendingMessage",((e,t,s)=>{const{chatId:n,messageId:a}=s,o=(0,i.hj)(e,n,a),r=o&&w.get(o.previousLocalId||o.id);r&&(0,P.u3)(r),t.apiUpdate({"@type":"deleteMessages",ids:[a],chatId:n})})),(0,n.Q6)("saveDraft",((e,t,s)=>{const{chatId:n,threadId:a,draft:o}=s;if(!o)return;const{text:c,entities:d}=o,l=(0,i.Z1)(e,n);return a===u._f&&(0,P.t9)("saveDraft",{chat:l,text:c,entities:d,replyToMsgId:(0,i.Yy)(e,n,a)}),e=(0,r.pf)(e,n,a,"draft",o),(0,r.a4)(e,n,{draftDate:Math.round(Date.now()/1e3)})})),(0,n.Q6)("clearDraft",((e,t,s)=>{const{chatId:n,threadId:a,localOnly:o}=s;if(!(0,i.Ms)(e,n,a))return;const c=(0,i.Z1)(e,n);return o||a!==u._f||(0,P.t9)("clearDraft",c),e=(0,r.pf)(e,n,a,"draft",void 0),(0,r.a4)(e,n,{draftDate:void 0})})),(0,n.Q6)("toggleMessageWebPage",((e,t,s)=>{const{chatId:n,threadId:a,noWebPage:o}=s;return(0,r.pf)(e,n,a,"noWebPage",o)})),(0,n.Q6)("pinMessage",((e,t,s)=>{const n=(0,i.jr)(e);if(!n)return;const{messageId:a,isUnpin:o,isOneSide:r,isSilent:c}=s;(0,P.t9)("pinMessage",{chat:n,messageId:a,isUnpin:o,isOneSide:r,isSilent:c})})),(0,n.Q6)("unpinAllMessages",((e,t,s)=>{const a=(0,i.Z1)(e,s.chatId);a&&async function(e){await(0,P.t9)("unpinAllMessages",{chat:e});let t=(0,n.Rd)();t=(0,r.pf)(t,e.id,u._f,"pinnedIds",[]),(0,n.R3)(t)}(a)})),(0,n.Q6)("deleteMessages",((e,t,s)=>{const{messageIds:n,shouldDeleteForAll:a}=s,o=(0,i.Bt)(e);if(!o)return;const{chatId:r,threadId:c}=o,d=(0,i.Z1)(e,r);(0,P.t9)("deleteMessages",{chat:d,messageIds:n,shouldDeleteForAll:a});const l=(0,i._$)(e,r,c);n.includes(l)&&t.setEditingId({messageId:void 0})})),(0,n.Q6)("deleteScheduledMessages",((e,t,s)=>{const{messageIds:n}=s,a=(0,i.Bt)(e);if(!a)return;const{chatId:o}=a,r=(0,i.Z1)(e,o);(0,P.t9)("deleteScheduledMessages",{chat:r,messageIds:n});const c=(0,i.wU)(e,o);n.includes(c)&&t.setEditingId({messageId:void 0})})),(0,n.Q6)("deleteHistory",((e,t,s)=>{(async()=>{var n;const{chatId:a,shouldDeleteForAll:o}=s,r=(0,i.Z1)(e,a);if(!r)return;const c=null===(n=r.lastMessage)||void 0===n?void 0:n.id;await(0,P.t9)("deleteHistory",{chat:r,shouldDeleteForAll:o,maxId:c});const d=(0,i.Bt)(e);d&&d.chatId===a&&t.openChat({id:void 0})})()})),(0,n.Q6)("reportMessages",((e,t,s)=>{(async()=>{const{messageIds:n,reason:a,description:o}=s,r=(0,i.Bt)(e);if(!r)return;const{chatId:c}=r,d=(0,i.Z1)(e,c),l=await(0,P.t9)("reportMessages",{peer:d,messageIds:n,reason:a,description:o});t.showNotification({message:l?"Thank you! Your report will be reviewed by our team.":"Error occured while submiting report. Please, try again later."})})()})),(0,n.Q6)("sendMessageAction",((e,t,s)=>{(async()=>{const{action:t,chatId:n,threadId:a}=s;if(n===e.currentUserId)return;const o=(0,i.Z1)(e,n);o&&await(0,P.t9)("sendMessageAction",{peer:o,threadId:a,action:t})})()})),(0,n.Q6)("markMessageListRead",((e,t,s)=>{const{serverTimeOffset:n}=e,o=(0,i.Bt)(e);if(!o)return;const{chatId:c,threadId:d}=o,l=(0,i.Cm)(e,c,d);if(!l)return;const{maxId:m}=s;if(b((()=>{(0,P.t9)("markMessageListRead",{serverTimeOffset:n,chat:l,threadId:d,maxId:m})})),d!==u._f)return;c===a.aw&&(e={...e,serviceNotifications:e.serviceNotifications.map((e=>e.isUnread&&e.id<=m?{...e,isUnread:!1}:e))});const h=(0,i.Cb)(e,c,d),g=(0,i.It)(e,c,d);if(!h||!g||!l.unreadCount)return e;const p=function(e,t,s){let n=0;for(let a=0,o=e.length;a=t&&e[a]<=s&&n++,!(e[a]>=s));a++);return n}(h,g,m);return p?(0,r.a4)(e,c,{lastReadInboxMessageId:m,unreadCount:Math.max(0,l.unreadCount-p)}):e})),(0,n.Q6)("markMessagesRead",((e,t,s)=>{const n=(0,i.jr)(e);if(!n)return;const{messageIds:a}=s;(0,P.t9)("markMessagesRead",{chat:n,messageIds:a})})),(0,n.Q6)("loadWebPagePreview",((e,t,s)=>{const{text:a}=s;!async function(e){const t=await(0,P.t9)("fetchWebPagePreview",{message:e});(0,n.R3)({...(0,n.Rd)(),webPagePreview:t})}(a)})),(0,n.Q6)("clearWebPagePreview",(e=>{if(e.webPagePreview)return{...e,webPagePreview:void 0}})),(0,n.Q6)("sendPollVote",((e,t,s)=>{const{chatId:n,messageId:a,options:o}=s,r=(0,i.Z1)(e,n);r&&(0,P.t9)("sendPollVote",{chat:r,messageId:a,options:o})})),(0,n.Q6)("loadPollOptionResults",((e,t,s)=>{const{chat:a,messageId:o,option:i,offset:c,limit:d,shouldResetVoters:l}=s;!async function(e,t,s,a,o,i){const c=await(0,P.t9)("loadPollOptionResults",{chat:e,messageId:t,option:s,offset:a,limit:o});if(!c)return;let d=(0,n.Rd)();d=(0,r.Sh)(d,(0,g.ee)(c.users,"id"));const{voters:l}=d.pollResults;(0,n.R3)({...d,pollResults:{...d.pollResults,voters:{...l,[s]:(0,g.Tw)([...!i&&l&&l[s]?l[s]:[],...c&&c.users.map((e=>e.id))])},offsets:{...d.pollResults.offsets?d.pollResults.offsets:{},[s]:c.nextOffset||""}}})}(a,o,i,c,d,l)})),(0,n.Q6)("forwardMessages",((e,t,s)=>{const{fromChatId:a,messageIds:o,toChatId:r}=e.forwardMessages,c=a?(0,i.Z1)(e,a):void 0,l=r?(0,i.Z1)(e,r):void 0,u=a&&o?o.sort(((e,t)=>e-t)).map((t=>(0,i.hj)(e,a,t))).filter(Boolean):void 0;if(!c||!l||!u)return;const{isSilent:m,scheduledAt:h}=s,g=(0,i._5)(e,r),p=u.filter((e=>!(0,d.jM)(e)));p.length&&(0,P.t9)("forwardMessages",{fromChat:c,toChat:l,messages:p,serverTimeOffset:(0,n.Rd)().serverTimeOffset,isSilent:m,scheduledAt:h,sendAs:g}),u.filter((e=>(0,d.jM)(e))).forEach((e=>{const{text:t,entities:s}=e.content.text||{},{sticker:n,poll:a}=e.content;M({chat:l,text:t,entities:s,sticker:n,poll:a,isSilent:m,scheduledAt:h,sendAs:g})})),(0,n.R3)({...(0,n.Rd)(),forwardMessages:{}})})),(0,n.Q6)("loadScheduledHistory",((e,t,s)=>{const{chatId:a}=s,o=(0,i.Z1)(e,a);o&&async function(e){const t=await(0,P.t9)("fetchScheduledHistory",{chat:e});if(!t)return;const{messages:s}=t,a=(0,g.ee)(s,"id"),o=Object.keys(a).map(Number).sort(((e,t)=>t-e));let i=(0,n.Rd)();i=(0,r.w3)(i,e.id,a),i=(0,r.pf)(i,e.id,u._f,"scheduledIds",o),(0,n.R3)(i)}(o)})),(0,n.Q6)("sendScheduledMessages",((e,t,s)=>{const{chatId:n,id:a}=s,o=(0,i.Z1)(e,n);o&&(0,P.t9)("sendScheduledMessages",{chat:o,ids:[a]})})),(0,n.Q6)("rescheduleMessage",((e,t,s)=>{const{chatId:n,messageId:a,scheduledAt:o}=s,r=(0,i.Z1)(e,n),c=r&&(0,i.Tm)(e,r.id,a);r&&c&&(0,P.t9)("rescheduleMessage",{chat:r,message:c,scheduledAt:o})})),(0,n.Q6)("requestThreadInfoUpdate",((e,t,s)=>{const{chatId:n,threadId:a}=s,o=(0,i.Cm)(e,n,a);o&&(0,P.t9)("requestThreadInfoUpdate",{chat:o,threadId:a})})),(0,n.Q6)("loadPinnedMessages",((e,t,s)=>{const{chatId:a}=s,o=(0,i.Z1)(e,a);o&&async function(e){const t=await(0,P.t9)("fetchPinnedMessages",{chat:e});if(!t)return;const{messages:s,chats:a,users:o}=t,i=(0,g.ee)(s,"id"),c=Object.keys(i).map(Number).sort(((e,t)=>t-e));let d=(0,n.Rd)();d=(0,r.c_)(d,e.id,i),d=(0,r.pf)(d,e.id,u._f,"pinnedIds",c),d=(0,r.Sh)(d,(0,g.ee)(o,"id")),d=(0,r.fZ)(d,(0,g.ee)(a,"id")),(0,n.R3)(d)}(o)})),(0,n.Q6)("loadSeenBy",((e,t,s)=>{const{chatId:a,messageId:o}=s,c=(0,i.Z1)(e,a);c&&(async()=>{const e=await(0,P.t9)("fetchSeenBy",{chat:c,messageId:o});e&&(0,n.R3)((0,r.cY)((0,n.Rd)(),a,o,{seenByUserIds:e}))})()})),(0,n.Q6)("saveDefaultSendAs",((e,t,s)=>{const{chatId:n,sendAsId:a}=s,o=(0,i.Z1)(e,n),c=(0,i.Z1)(e,a)||(0,i.dy)(e,a);if(o&&c)return(0,P.t9)("saveDefaultSendAs",{sendAs:c,chat:o}),(0,r.a4)(e,n,{fullInfo:{...o.fullInfo,sendAsId:a}})})),(0,n.Q6)("loadSendAs",((e,t,s)=>{const{chatId:a}=s,o=(0,i.Z1)(e,a);o&&(async()=>{const t=await(0,P.t9)("fetchSendAs",{chat:o});if(!t)return e=(0,r.a4)(e,a,{sendAsIds:[]}),void(0,n.R3)(e);e=(0,n.Rd)(),e=(0,r.Sh)(e,(0,g.ee)(t.users,"id")),e=(0,r.fZ)(e,(0,g.ee)(t.chats,"id")),e=(0,r.a4)(e,a,{sendAsIds:t.ids}),(0,n.R3)(e)})()})),(0,n.Q6)("loadSponsoredMessages",((e,t,s)=>{const{chatId:a}=s,o=(0,i.Z1)(e,a);o&&(async()=>{const e=await(0,P.t9)("fetchSponsoredMessages",{chat:o});if(!e)return;let t=(0,r.Fn)((0,n.Rd)(),a,e.messages[0]);t=(0,r.Sh)(t,(0,g.ee)(e.users,"id")),t=(0,r.fZ)(t,(0,g.ee)(e.chats,"id")),(0,n.R3)(t)})()})),(0,n.Q6)("viewSponsoredMessage",((e,t,s)=>{const{chatId:n}=s,a=(0,i.Z1)(e,n),o=(0,i.fS)(e,n);a&&o&&(0,P.t9)("viewSponsoredMessage",{chat:a,random:o.randomId})}));var k=s(5765);const R=(0,C.P2)((e=>e()),500,!1);async function T(e,t){const s=await(0,P.t9)("searchGifs",{query:e,offset:t});s&&(0,n.R3)((0,r.rq)((0,n.Rd)(),!t,s.gifs,s.nextOffset))}(0,n.Q6)("loadStickerSets",(e=>{const{hash:t}=e.stickers.added||{};!async function(e){const t=await(0,P.t9)("fetchStickerSets",{hash:e});t&&(0,n.R3)((0,r.z3)((0,n.Rd)(),"added",t.hash,t.sets))}(t)})),(0,n.Q6)("loadAddedStickers",((e,t)=>{const{setIds:s}=e.stickers.added;s&&s.length&&(async()=>{for(let e=0;e0&&await(0,C.wO)(200)})()})),(0,n.Q6)("loadRecentStickers",(e=>{const{hash:t}=e.stickers.recent||{};!async function(e){const t=await(0,P.t9)("fetchRecentStickers",{hash:e});if(!t)return;const s=(0,n.Rd)();(0,n.R3)({...s,stickers:{...s.stickers,recent:t}})}(t)})),(0,n.Q6)("loadFavoriteStickers",(e=>{const{hash:t}=e.stickers.favorite||{};!async function(e){const t=await(0,P.t9)("fetchFavoriteStickers",{hash:e});if(!t)return;const s=(0,n.Rd)();(0,n.R3)({...s,stickers:{...s.stickers,favorite:t}})}(t)})),(0,n.Q6)("loadGreetingStickers",(e=>{const{hash:t}=e.stickers.greeting||{};(async()=>{const e=await(0,P.t9)("fetchStickersForEmoji",{emoji:"👋⭐️",hash:t});if(!e)return;const s=(0,n.Rd)();(0,n.R3)({...s,stickers:{...s.stickers,greeting:{hash:e.hash,stickers:e.stickers.filter((e=>"👋"===e.emoji))}}})})()})),(0,n.Q6)("loadFeaturedStickers",(e=>{const{hash:t}=e.stickers.featured||{};!async function(e){const t=await(0,P.t9)("fetchFeaturedStickers",{hash:e});t&&(0,n.R3)((0,r.z3)((0,n.Rd)(),"featured",t.hash,t.sets))}(t)})),(0,n.Q6)("loadStickers",((e,t,s)=>{const{stickerSetId:a,stickerSetShortName:o}=s;let{stickerSetAccessHash:c}=s;if(!c&&!o){const t=(0,i.Ny)(e,a);if(!t)return;c=t.accessHash}!async function(e,t,s){const a=await(0,P.t9)("fetchStickers",{stickerSetShortName:s,stickerSetId:e,accessHash:t});if(!a)return;const{set:o,stickers:i,packs:c}=a;let d=(0,n.Rd)();d=(0,r.Rg)(d,o.id,{...o,stickers:i,packs:c});const l=d.stickers.forEmoji.emoji;l&&c[l]&&(d=(0,r.vy)(d)),(0,n.R3)(d)}(a,c,o)})),(0,n.Q6)("loadAnimatedEmojis",(()=>{!async function(){const e=await(0,P.t9)("fetchAnimatedEmojis");if(!e)return;const{set:t,stickers:s}=e;(0,n.R3)((0,r.g_)((0,n.Rd)(),{...t,stickers:s}))}()})),(0,n.Q6)("loadSavedGifs",(e=>{const{hash:t}=e.gifs.saved;!async function(e){const t=await(0,P.t9)("fetchSavedGifs",{hash:e});if(!t)return;const s=(0,n.Rd)();(0,n.R3)({...s,gifs:{...s.gifs,saved:t}})}(t)})),(0,n.Q6)("faveSticker",((e,t,s)=>{const{sticker:n}=s;n&&(0,P.t9)("faveSticker",{sticker:n})})),(0,n.Q6)("unfaveSticker",((e,t,s)=>{const{sticker:a}=s;a&&function(e){const t=(0,n.Rd)();(0,n.R3)({...t,stickers:{...t.stickers,favorite:{...t.stickers.favorite,stickers:t.stickers.favorite.stickers.filter((({id:t})=>t!==e.id))}}}),(0,P.t9)("faveSticker",{sticker:e,unfave:!0})}(a)})),(0,n.Q6)("toggleStickerSet",((e,t,s)=>{const{stickerSetId:n}=s,a=(0,i.Ny)(e,n);if(!a)return;const{accessHash:o,installedDate:r}=a;(0,P.t9)(r?"uninstallStickerSet":"installStickerSet",{stickerSetId:n,accessHash:o})})),(0,n.Q6)("loadEmojiKeywords",((e,t,s)=>{var a;const{language:o}=s;let r=e.emojiKeywords[o];null!==(a=r)&&void 0!==a&&a.isLoading||((0,n.R3)({...e,emojiKeywords:{...e.emojiKeywords,[o]:{...r,isLoading:!0}}}),(async()=>{var t;const s=await(0,P.t9)("fetchEmojiKeywords",{language:o,fromVersion:r?r.version:0});e=(0,n.Rd)(),r=e.emojiKeywords[o],s?(0,n.R3)({...e,emojiKeywords:{...e.emojiKeywords,[o]:{isLoading:!1,version:s.version,keywords:{...null===(t=r)||void 0===t?void 0:t.keywords,...s.keywords}}}}):(0,n.R3)({...e,emojiKeywords:{...e.emojiKeywords,[o]:{...r,isLoading:!1}}})})())})),(0,n.Q6)("setStickerSearchQuery",((e,t,s)=>{const{query:a}=s;a&&R((()=>{!async function(e,t){const s=await(0,P.t9)("searchStickers",{query:e,hash:void 0});if(!s)return;const a=(0,n.Rd)(),{setsById:o,added:i}=a.stickers,c=s.sets.map((({id:e})=>e));i.setIds&&i.setIds.forEach((t=>{if(!c.includes(t)){const{title:s}=o[t]||{};s&&(0,k.Z)(s,e)&&c.unshift(t)}})),(0,n.R3)((0,r.z3)(a,"search",s.hash,s.sets,c))}(a)}))})),(0,n.Q6)("setGifSearchQuery",((e,t,s)=>{const{query:n}=s;"string"==typeof n&&R((()=>{T(n)}))})),(0,n.Q6)("searchMoreGifs",(e=>{const{query:t,offset:s}=e.gifs.search;"string"==typeof t&&R((()=>{T(t,s)}))})),(0,n.Q6)("loadStickersForEmoji",((e,t,s)=>{const{emoji:a}=s,{hash:o}=e.stickers.forEmoji;R((()=>{!async function(e,t){let s=(0,n.Rd)();(0,n.R3)({...s,stickers:{...s.stickers,forEmoji:{...s.stickers.forEmoji,emoji:e}}});const a=await(0,P.t9)("fetchStickersForEmoji",{emoji:e,hash:t});s=(0,n.Rd)(),a&&s.stickers.forEmoji.emoji===e&&(s=(0,r.IM)(s,e,a.stickers,a.hash),(0,n.R3)(s))}(a,o)}))})),(0,n.Q6)("clearStickersForEmoji",(e=>({...e,stickers:{...e.stickers,forEmoji:{}}}))),(0,n.Q6)("openStickerSetShortName",((e,t,s)=>{const{stickerSetShortName:n}=s;return{...e,openedStickerSetShortName:n}}));var N=s(790);const B=(0,C.P2)((e=>e()),500,!1);async function A(e="",t,s,o,c,d){let l;if(o){const n=await(0,P.t9)("searchMessagesLocal",{chatOrUser:o,query:e,type:t,limit:a.Hk,offsetId:s,minDate:d,maxDate:c});if(n){const{messages:e,users:t,totalCount:s,nextOffsetId:a}=n;l={messages:e,users:t,chats:[],totalCount:s,nextRate:a}}}else l=await(0,P.t9)("searchMessagesGlobal",{query:e,offsetRate:s,limit:a.Hk,type:t,maxDate:c,minDate:d});let u=(0,n.Rd)();const m=(0,i.JX)(u);if(!l||""!==e&&e!==m)return void(0,n.R3)((0,r.xv)(u,{messages:!1}));const{messages:h,users:p,chats:f,totalCount:I,nextRate:v}=l;f.length&&(u=(0,r.fZ)(u,(0,g.ee)(f,"id"))),p.length&&(u=(0,r.Sh)(u,(0,g.ee)(p,"id"))),h.length&&(u=(0,r.m6)(u,h)),u=(0,r.px)(u,h,I,t,v),(0,n.R3)(u)}(0,n.Q6)("setGlobalSearchQuery",((e,t,s)=>{const{chatId:a}=e.globalSearch,{query:o}=s;o&&!a&&B((()=>{!async function(e){const t=await(0,P.t9)("searchChats",{query:e});let s=(0,n.Rd)();const a=(0,i.JX)(s);if(!t||!a||e!==a)return void(0,n.R3)((0,r.xv)(s,{chats:!1}));const{localChats:o,localUsers:c,globalChats:d,globalUsers:l}=t;(o.length||d.length)&&(s=(0,r.fZ)(s,(0,g.ee)([...o,...d],"id"))),(c.length||l.length)&&(s=(0,r.Sh)(s,(0,g.ee)([...c,...l],"id"))),s=(0,r.xv)(s,{chats:!1}),s=(0,r.No)(s,{localResults:{chatIds:o.map((({id:e})=>e)),userIds:c.map((({id:e})=>e))},globalResults:{...s.globalSearch.globalResults,chatIds:d.map((({id:e})=>e)),userIds:l.map((({id:e})=>e))}}),(0,n.R3)(s)}(o)}))})),(0,n.Q6)("setGlobalSearchDate",((e,t,s)=>{const{date:a}=s,o=a?(0,N.IS)(a):a,c=(0,r.No)(e,{date:a,query:"",resultsByType:{...e.globalSearch.resultsByType,text:{totalCount:void 0,foundIds:[],nextOffsetId:0}}});(0,n.R3)(c);const{chatId:d}=e.globalSearch;A("","text",void 0,d?(0,i.Z1)(e,d):void 0,o,a)})),(0,n.Q6)("searchMessagesGlobal",((e,t,s)=>{var n;const{query:a,resultsByType:o,chatId:r,date:c}=e.globalSearch,d=c?(0,N.IS)(c):c,{type:l}=s;A(a,l,null==o||null===(n=o[l])||void 0===n?void 0:n.nextOffsetId,r?(0,i.Z1)(e,r):void 0,d,c)})),(0,n.Q6)("searchTextMessagesLocal",(e=>{const{chatId:t,threadId:s}=(0,i.Bt)(e)||{},o=t?(0,i.Z1)(e,t):void 0,c=(0,i.n5)(e);if(!o||!c||!s)return;const{query:d,results:l}=c,m=null==l?void 0:l.nextOffsetId;let h;if(s!==u._f){const n=(0,i.tZ)(e,t,s);h=null==n?void 0:n.topMessageId}!async function(e,t,s,o,c){const d=await(0,P.t9)("searchMessagesLocal",{chatOrUser:e,type:"text",query:o,topMessageId:s,limit:a.pn,offsetId:c});if(!d)return;const{messages:l,users:u,totalCount:m,nextOffsetId:h}=d,p=(0,g.ee)(l,"id"),f=Object.keys(p).map(Number);let I=(0,n.Rd)();const v=(0,i.n5)(I);!v||o&&o!==v.query||(I=(0,r.c_)(I,e.id,p),I=(0,r.Sh)(I,(0,g.ee)(u,"id")),I=(0,r.dx)(I,e.id,t,f,m,h),(0,n.R3)(I))}(o,s,h,d,m)})),(0,n.Q6)("searchMediaMessagesLocal",(e=>{const t=(0,i.og)(e),s=t?e.users.byId[t]||e.chats.byId[t]:void 0,o=(0,i.we)(e);if(!s||!o)return;const{currentType:c,resultsByType:d}=o,l=c&&d&&d[c],u=null==l?void 0:l.nextOffsetId;c&&async function(e,t,s){const o=await(0,P.t9)("searchMessagesLocal",{chatOrUser:e,type:t,limit:a.EN,offsetId:s});if(!o)return;const{messages:c,users:d,totalCount:l,nextOffsetId:u}=o,m=(0,g.ee)(c,"id"),h=Object.keys(m).map(Number);let p=(0,n.Rd)();(0,i.we)(p)&&(p=(0,r.c_)(p,e.id,m),p=(0,r.Sh)(p,(0,g.ee)(d,"id")),p=(0,r.c1)(p,e.id,t,h,l,u),(0,n.R3)(p))}(s,c,u)})),(0,n.Q6)("searchMessagesByDate",((e,t,s)=>{const{timestamp:a}=s,{chatId:o}=(0,i.Bt)(e)||{};if(!o)return;const r=(0,i.Z1)(e,o);r&&async function(e,t){const s=await(0,P.t9)("findFirstMessageIdAfterDate",{chat:e,timestamp:t});s&&(0,n.uC)().focusMessage({chatId:e.id,messageId:s})}(r,a)})),(0,n.Q6)("checkPublicLink",((e,t,s)=>{const{chatId:a}=(0,i.Bt)(e)||{};if(!a)return;if(e.management.progress===m.wv.InProgress)return;const{username:o}=s;(async()=>{e=(0,r.H9)(e,m.wv.InProgress),e=(0,r.fw)(e,a,{isUsernameAvailable:void 0}),(0,n.R3)(e);const t=await(0,P.t9)("checkChatUsername",{username:o});e=(0,n.Rd)(),e=(0,r.H9)(e,t?m.wv.Complete:m.wv.Error),e=(0,r.fw)(e,a,{isUsernameAvailable:t}),(0,n.R3)(e)})()})),(0,n.Q6)("updatePublicLink",((e,t,s)=>{const{chatId:a}=(0,i.Bt)(e)||{};let o=a&&(0,i.Z1)(e,a);if(!a||!o)return;const{username:c}=s;(async()=>{if(e=(0,r.H9)(e,m.wv.InProgress),(0,n.R3)(e),(0,d.G9)(o)){if(o=await(0,P.t9)("migrateChat",o),!o)return;t.openChat({id:o.id})}const s=await(0,P.t9)("setChatUsername",{chat:o,username:c});e=(0,n.Rd)(),e=(0,r.H9)(e,s?m.wv.Complete:m.wv.Error),e=(0,r.fw)(e,a,{isUsernameAvailable:void 0}),(0,n.R3)(e)})()})),(0,n.Q6)("updatePrivateLink",(e=>{const{chatId:t}=(0,i.Bt)(e)||{},s=t&&(0,i.Z1)(e,t);t&&s&&(0,P.t9)("updatePrivateLink",{chat:s})}));var x=s(7358);async function L(){const e=await(0,P.t9)("fetchChats",{limit:a.Ov,archived:!0,withPinned:!0,serverTimeOffset:(0,n.Rd)().serverTimeOffset});if(!e)return;let t=(0,n.Rd)();t=(0,r.eD)(t,(0,g.ee)(e.users,"id")),t=(0,r.zn)(t,e.userStatusesById),t=(0,r.GL)(t,(0,g.ee)(e.chats,"id")),t=(0,r.Mg)(t,"archived",e.chatIds),t=(0,r.vv)(t,"archived",e),(0,n.R3)(t)}async function O(){let e=(0,n.Rd)();const{recentlyFoundChatIds:t}=e.globalSearch,{userIds:s}=e.contactList||{};if(!(s&&s.length||t&&t.length))return;const a=[...t||[],...s||[]].map((t=>(0,i.dy)(e,t))).filter(Boolean),o=await(0,P.t9)("fetchUsers",{users:a});if(!o)return;const{users:c,userStatusesById:d}=o;e=(0,n.Rd)(),e=(0,r.eD)(e,(0,g.ee)(c,"id")),e=(0,r.zn)(e,d),(0,n.R3)(e)}function F(e){return(0,P.t9)("fetchMessages",{chat:e,threadId:u._f,offsetId:e.lastReadInboxMessageId,addOffset:-(Math.round(a.hT/2)+1),limit:a.hT})}(0,n.Q6)("sync",((e,t)=>{!async function(e){a.eM&&console.log(">>> START SYNC"),await(0,P.t9)("fetchCurrentUser");const t=await async function(){var e;let t=(0,n.Rd)();const s=await(0,P.t9)("fetchChats",{limit:a.Ov,withPinned:!0,serverTimeOffset:t.serverTimeOffset,lastLocalServiceMessage:null===(e=(0,i.VF)(t))||void 0===e?void 0:e.message});if(!s)return;t=(0,n.Rd)();const{recentlyFoundChatIds:o}=t.globalSearch,{userIds:c}=t.contactList||{},{currentUserId:l}=t,m=[...o||[],...c||[],...l?[l]:[]],h=m.map((e=>(0,i.dy)(t,e))).filter(Boolean),p=m.map((e=>(0,i.Z1)(t,e))).filter(Boolean),{chatId:f}=(0,i.Bt)(t)||{};if(f){const e=(0,i.Z1)(t,f);if(e&&!m.includes(f)&&p.push(e),(0,d.YC)(f)){const e=(0,i.dy)(t,f);e&&!m.includes(f)&&h.push(e)}}return h.push(...s.users),p.push(...s.chats),t=(0,r.ps)(t,s.userStatusesById),t=(0,r.SL)(t,(0,g.ee)(p,"id")),t=(0,r.Mg)(t,"active",s.chatIds),t=(0,r.vv)(t,"active",s),Object.keys(s.draftsById).forEach((e=>{t=(0,r.pf)(t,e,u._f,"draft",s.draftsById[e])})),Object.keys(s.replyingToById).forEach((e=>{t=(0,r.pf)(t,e,u._f,"replyingToId",s.replyingToById[e])})),(0,n.R3)(t),f&&!t.chats.byId[f]&&(0,n.uC)().openChat({id:void 0}),h}();await async function(e){let t=!1,s=e||[],o=(0,n.Rd)();const{chatId:c,threadId:d}=(0,i.Bt)(o)||{},l=Object.keys(o.messages.byChatId).reduce(((e,t)=>{const s=(0,i.Ms)(o,t,u._f);return s&&(e[t]=s),e}),{});if(c){const e=await F(o.chats.byId[c]);o=(0,n.Rd)();const{chatId:l}=(0,i.Bt)(o)||{},m=d&&(0,i.tZ)(o,c,d);if(e&&l===c){const n=o.messages.byChatId[c],i=c===a.aw?o.serviceNotifications.map((({message:e})=>e)):[],l=[].concat(e.messages,i),h=(0,g.ee)(l,"id"),p=Object.keys(h).map(Number);if(o={...o,messages:{...o.messages,byChatId:{}}},o=(0,r.c_)(o,c,h),o=(0,r.xj)(o,c,u._f,p),o=(0,r.y9)(o,c,u._f,p),d&&m&&m.originChannelId){const{originChannelId:e}=m,t=o.messages.byChatId[e],s=await F(o.chats.byId[e]);if(s){const e=(0,g.ee)(s.messages,"id"),a=Object.keys(e).map(Number);o={...o,messages:{...o.messages,byChatId:{...o.messages.byChatId,[m.originChannelId]:{byId:e,threadsById:{[u._f]:{...null==t?void 0:t.threadsById[u._f],listedIds:a,viewportIds:a,outlyingIds:void 0}}},[c]:{...o.messages.byChatId[c],threadsById:{...o.messages.byChatId[c].threadsById,[d]:{...null==n?void 0:n.threadsById[d],outlyingIds:void 0}}}}}}}}o=(0,r.GL)(o,(0,g.ee)(e.chats,"id")),o=(0,r.j6)(o,c,e.threadInfos),t=!0,s=Array.prototype.concat(s,e.users)}}t||(o={...o,messages:{...o.messages,byChatId:{}}}),Object.keys(l).forEach((e=>{o=(0,r.pf)(o,e,u._f,"draft",l[e])})),e?o=(0,r.s5)(o,(0,g.ee)(s,"id")):s&&(o=(0,r.eD)(o,(0,g.ee)(s,"id"))),(0,n.R3)(o);const{chatId:m,messageId:h}=o.audioPlayer;m&&h&&!(0,i.hj)(o,m,h)&&(0,n.uC)().closeAudioPlayer()}(t),(0,n.R3)({...(0,n.Rd)(),lastSyncTime:Date.now()}),a.eM&&console.log(">>> FINISH SYNC"),e()}(t.afterSync)})),(0,n.Q6)("afterSync",(()=>{!async function(){a.eM&&console.log(">>> START AFTER-SYNC"),await Promise.all([O(),L()]),await(0,P.t9)("fetchCurrentUser"),(0,x.w)((0,i.A1)((0,n.Rd)())),a.eM&&console.log(">>> FINISH AFTER-SYNC")}()}));const U=(0,C.Ds)((e=>e()),500,!1,!0),$=(0,C.P2)((e=>e()),500,!1);function D(e,t,s){return{...e,inlineBots:{...e.inlineBots,byUsername:{...e.inlineBots.byUsername,[t]:s}}}}function q(e,t){return{...e,inlineBots:{...e.inlineBots,isLoading:t}}}(0,n.Q6)("loadFullUser",((e,t,s)=>{const{userId:n}=s,a=(0,i.dy)(e,n);if(!a)return;const{id:o,accessHash:r}=a;U((()=>(0,P.t9)("fetchFullUser",{id:o,accessHash:r})))})),(0,n.Q6)("loadUser",((e,t,s)=>{const{userId:a}=s,o=(0,i.dy)(e,a);o&&(async()=>{const t=await(0,P.t9)("fetchUsers",{users:[o]});if(!t)return;const{users:s,userStatusesById:a}=t;e=(0,n.Rd)(),e=(0,r.eD)(e,(0,g.ee)(s,"id")),(0,n.R3)((0,r.ps)(e,{...e.users.statusesById,...a})),(0,n.R3)(e)})()})),(0,n.Q6)("loadTopUsers",(e=>{const{topPeers:{lastRequestedAt:t}}=e;(!t||(0,p.b)(e.serverTimeOffset)-t>60)&&async function(){const e=await(0,P.t9)("fetchTopUsers");if(!e)return;const{ids:t,users:s}=e;let a=(0,n.Rd)();a=(0,r.Sh)(a,(0,g.ee)(s,"id")),a={...a,topPeers:{...a.topPeers,userIds:t,lastRequestedAt:(0,p.b)(a.serverTimeOffset)}},(0,n.R3)(a)}()})),(0,n.Q6)("loadContactList",(()=>{!async function(){const e=await(0,P.t9)("fetchContactList");if(!e)return;let t=(0,r.Sh)((0,n.Rd)(),(0,g.ee)(e.users,"id"));t=(0,r.fZ)(t,(0,g.ee)(e.chats,"id"));const s=e=>e.lastName||e.firstName||"",a=new Intl.Collator("en-US"),o=e.users.sort(((e,t)=>a.compare(s(e),s(t)))).filter((e=>!e.isSelf));(0,n.R3)({...t,contactList:{userIds:o.map((e=>e.id))}})}()})),(0,n.Q6)("loadCurrentUser",(()=>{(0,P.t9)("fetchCurrentUser")})),(0,n.Q6)("loadCommonChats",(e=>{var t;const{chatId:s}=(0,i.Bt)(e)||{},a=s?(0,i.dy)(e,s):void 0;!a||(0,d.cS)(a)||null!==(t=a.commonChats)&&void 0!==t&&t.isFullyLoaded||(async()=>{var t,s;const o=null===(t=a.commonChats)||void 0===t?void 0:t.maxId,i=await(0,P.t9)("fetchCommonChats",a.id,a.accessHash,o);if(!i)return;const{chats:c,chatIds:d,isFullyLoaded:l}=i;e=(0,n.Rd)(),c.length&&(e=(0,r.fZ)(e,(0,g.ee)(c,"id"))),e=(0,r.Nq)(e,a.id,{commonChats:{maxId:d.length?d[d.length-1]:"0",ids:(0,g.Tw)(((null===(s=a.commonChats)||void 0===s?void 0:s.ids)||[]).concat(d)),isFullyLoaded:l}}),(0,n.R3)(e)})()})),(0,n.Q6)("updateContact",((e,t,s)=>{const{userId:a,isMuted:o,firstName:c,lastName:d}=s;!async function(e,t,s,a){const o=(0,n.Rd)(),c=(0,i.dy)(o,e);if(!c)return;let d;if((0,n.uC)().updateChatMutedState({chatId:e,isMuted:t}),(0,n.R3)((0,r.H9)((0,n.Rd)(),m.wv.InProgress)),c.phoneNumber)d=await(0,P.t9)("updateContact",{phone:c.phoneNumber,firstName:s,lastName:a});else{const{id:e,accessHash:t}=c;d=await(0,P.t9)("addContact",{id:e,accessHash:t,phoneNumber:"",firstName:s,lastName:a})}d&&(0,n.R3)((0,r.Nq)((0,n.Rd)(),c.id,{firstName:s,lastName:a})),(0,n.R3)((0,r.H9)((0,n.Rd)(),m.wv.Complete))}(a,o,c,d)})),(0,n.Q6)("deleteContact",((e,t,s)=>{const{userId:a}=s;!async function(e){const t=(0,n.Rd)(),s=(0,i.dy)(t,e);if(!s)return;const{id:a,accessHash:o}=s;await(0,P.t9)("deleteContact",{id:a,accessHash:o})}(a)})),(0,n.Q6)("loadProfilePhotos",((e,t,s)=>{const{profileId:a}=s,o=(0,d.YC)(a),c=o?(0,i.dy)(e,a):void 0,l=o?void 0:(0,i.Z1)(e,a);(c||l)&&(async()=>{const e=await(0,P.t9)("fetchProfilePhotos",c,l);if(!e||!e.photos)return;let t=(0,n.Rd)();o?t=(0,r.Nq)(t,a,{photos:e.photos}):(t=(0,r.Sh)(t,(0,g.ee)(e.users,"id")),t=(0,r.a4)(t,a,{photos:e.photos})),(0,n.R3)(t)})()})),(0,n.Q6)("setUserSearchQuery",((e,t,s)=>{const{query:a}=s;a&&$((()=>{!async function(e){const t=await(0,P.t9)("searchChats",{query:e});let s=(0,n.Rd)();const a=s.userSearch.query;if(!t||!a||e!==a)return void(0,n.R3)((0,r.Q3)(s,!1));const{localUsers:o,globalUsers:i}=t;let c,d;o.length&&(s=(0,r.Sh)(s,(0,g.ee)(o,"id")),c=o.map((({id:e})=>e))),i.length&&(s=(0,r.Sh)(s,(0,g.ee)(i,"id")),d=i.map((({id:e})=>e))),s=(0,r.Q3)(s,!1),s=(0,r.Lm)(s,{localUserIds:c,globalUserIds:d}),(0,n.R3)(s)}(a)}))})),(0,n.Q6)("addContact",((e,t,s)=>{const{userId:n}=s,a=(0,i.dy)(e,n);a&&(0,P.t9)("addContact",(0,g.ei)(a,["id","accessHash","firstName","lastName","phoneNumber"]))}));const Q=(0,C.Ds)((e=>e()),500,!1);async function G(e,t,s,n,a){await(0,P.t9)("sendMessage",{chat:e,text:s,replyingTo:n,sendAs:a})}(0,n.Q6)("clickInlineButton",((e,t,s)=>{const{button:o}=s;switch(o.type){case"command":t.sendBotCommand({command:o.value});break;case"url":o.value.match(a.FS)||o.value.match(a.g$)?t.openTelegramLink({url:o.value}):t.toggleSafeLinkModal({url:o.value});break;case"callback":{const t=(0,i.jr)(e);if(!t)return;!async function(e,t,s){const a=await(0,P.t9)("answerCallbackButton",{chatId:e.id,accessHash:e.accessHash,messageId:t,data:s});if(!a)return;const{showDialog:o,showNotification:r,toggleSafeLinkModal:i}=(0,n.uC)(),{message:c,alert:d,url:l}=a;d?o({data:{message:c||"Error"}}):c?r({message:c}):l&&i({url:l})}(t,o.messageId,o.value);break}case"requestPoll":t.openPollModal();break;case"requestSelfContact":{const s=e.currentUserId?(0,i.dy)(e,e.currentUserId):void 0;if(!s)return;t.showDialog({data:{phoneNumber:s.phoneNumber,firstName:s.firstName,lastName:s.lastName,userId:s.id}});break}case"buy":{const s=(0,i.jr)(e),{messageId:n,value:a}=o;if(!s)return;a?t.getReceipt({receiptMessageId:a,chatId:s.id,messageId:n}):(t.getPaymentForm({chat:s,messageId:n}),t.setInvoiceMessageInfo((0,i.hj)(e,s.id,n)),t.openPaymentModal({chatId:s.id,messageId:n}));break}}})),(0,n.Q6)("sendBotCommand",((e,t,s)=>{const{command:n,chatId:a}=s,{currentUserId:o}=e,r=a?(0,i.Z1)(e,a):(0,i.jr)(e),c=(0,i.Bt)(e);if(!o||!r||!c)return;const{threadId:d}=c;t.setReplyingToId({messageId:void 0}),t.clearWebPagePreview({chatId:r.id,threadId:d,value:!1}),G(r,0,n,(0,i.Yy)(e,r.id,d),(0,i._5)(e,a))})),(0,n.Q6)("restartBot",((e,t,s)=>{const{chatId:a}=s,{currentUserId:o}=e,c=(0,i.jr)(e),d=o&&(0,i.IK)(e,a);o&&c&&d&&(async()=>{await(0,P.t9)("unblockContact",d.id,d.accessHash)&&((0,n.R3)((0,r.rB)((0,n.Rd)(),d.id)),G(c,0,"/start",void 0,(0,i._5)(e,a)))})()})),(0,n.Q6)("loadTopInlineBots",(e=>{const{lastRequestedAt:t}=e.topInlineBots;t&&(0,p.b)(e.serverTimeOffset)-t<60||(async()=>{const t=await(0,P.t9)("fetchTopInlineBots");if(!t)return;const{ids:s,users:a}=t;let o=(0,n.Rd)();o=(0,r.Sh)(o,(0,g.ee)(a,"id")),o={...o,topInlineBots:{...o.topInlineBots,userIds:s,lastRequestedAt:(0,p.b)(e.serverTimeOffset)}},(0,n.R3)(o)})()})),(0,n.Q6)("queryInlineBot",((e,t,s)=>{const{chatId:a,username:o,query:c,offset:d}=s;(async()=>{let t=e.inlineBots.byUsername[o];if(!1!==t){if(void 0===t){const{user:s,chat:a}=await(0,P.t9)("fetchInlineBot",{username:o})||{};if(e=(0,n.Rd)(),!s||!a)return void(0,n.R3)(D(e,o,!1));e=(0,r.Sh)(e,{[s.id]:s}),e=(0,r.fZ)(e,{[a.id]:a}),t={id:s.id,query:"",offset:"",switchPm:void 0,canLoadMore:!0,results:[]},e=D(e,o,t),(0,n.R3)(e)}(c!==t.query||t.canLoadMore)&&Q((()=>{!async function({username:e,inlineBotData:t,chatId:s,query:a,offset:o}){let r=(0,n.Rd)();const c=(0,i.dy)(r,t.id),d=(0,i.Z1)(r,s);if(!c||!d)return;const l=t.query!==a;r=q(r,!0),r=D(r,e,{...t,query:a,...l&&{offset:void 0,results:[]}}),(0,n.R3)(r);const u=await(0,P.t9)("fetchInlineBotResults",{bot:c,chat:d,query:a,offset:l?void 0:o}),m=r.inlineBots.byUsername[e];if(r=q((0,n.Rd)(),!1),!u||!m||a!==m.query)return void(0,n.R3)(r);const h=new Set((m.results||[]).map((e=>e.id))),g=u.results.filter((e=>!h.has(e.id)));r=D(r,e,{...m,help:u.help,...g.length&&{isGallery:u.isGallery},...u.switchPm&&{switchPm:u.switchPm},canLoadMore:u.results.length>0&&Boolean(u.nextOffset),results:""===m.offset||m.offset===u.nextOffset?u.results:(m.results||[]).concat(g),offset:g.length?u.nextOffset:""}),(0,n.R3)(r)}({username:o,inlineBotData:t,chatId:a,query:c,offset:d})}))}})()})),(0,n.Q6)("sendInlineBotResult",((e,t,s)=>{const{id:n,queryId:a}=s,o=(0,i.Bt)(e);if(!o||!n)return;const{chatId:r,threadId:c}=o,d=(0,i.Z1)(e,r);t.setReplyingToId({messageId:void 0}),t.clearWebPagePreview({chatId:r,threadId:c,value:!1}),(0,P.t9)("sendInlineBotResult",{chat:d,resultId:n,queryId:a,replyingTo:(0,i.Yy)(e,r,c),sendAs:(0,i._5)(e,r)})})),(0,n.Q6)("resetInlineBot",((e,t,s)=>{const{username:a}=s;let o=e.inlineBots.byUsername[a];o&&(o={id:o.id,query:"",offset:"",switchPm:void 0,canLoadMore:!0,results:[]},(0,n.R3)(D(e,a,o)))})),(0,n.Q6)("startBot",((e,t,s)=>{const{botId:n,param:a}=s,o=(0,i.dy)(e,n);o&&(async()=>{await(0,P.t9)("startBot",{bot:o,startParam:a})})()})),s(9667),(0,n.Q6)("loadPasswordInfo",(()=>{(async()=>{const e=await(0,P.t9)("getPasswordInfo");if(!e)return;let t=(0,n.Rd)();t=(0,r.BI)(t,{hasPassword:e.hasPassword}),t=(0,r.IE)(t,{hint:e.hint}),(0,n.R3)(t)})()})),(0,n.Q6)("checkPassword",((e,t,s)=>{const{currentPassword:a,onSuccess:o}=s;(0,n.R3)((0,r.IE)(e,{isLoading:!0,error:void 0})),(async()=>{const e=await(0,P.t9)("checkPassword",a);(0,n.R3)((0,r.IE)((0,n.Rd)(),{isLoading:!1})),e&&o()})()})),(0,n.Q6)("clearPassword",((e,t,s)=>{const{currentPassword:a,onSuccess:o}=s;(0,n.R3)((0,r.IE)(e,{isLoading:!0,error:void 0})),(async()=>{const e=await(0,P.t9)("clearPassword",a);(0,n.R3)((0,r.IE)((0,n.Rd)(),{isLoading:!1})),e&&o()})()})),(0,n.Q6)("updatePassword",((e,t,s)=>{const{currentPassword:a,password:o,hint:i,email:c,onSuccess:d}=s;(0,n.R3)((0,r.IE)(e,{isLoading:!0,error:void 0})),(async()=>{const e=await(0,P.t9)("updatePassword",a,o,i,c);(0,n.R3)((0,r.IE)((0,n.Rd)(),{isLoading:!1})),e&&d()})()})),(0,n.Q6)("updateRecoveryEmail",((e,t,s)=>{const{currentPassword:a,email:o,onSuccess:i}=s;(0,n.R3)((0,r.IE)(e,{isLoading:!0,error:void 0})),(async()=>{const e=await(0,P.t9)("updateRecoveryEmail",a,o);(0,n.R3)((0,r.IE)((0,n.Rd)(),{isLoading:!1,waitingEmailCodeLength:void 0})),e&&i()})()})),(0,n.Q6)("provideTwoFaEmailCode",((e,t,s)=>{const{code:n}=s;(0,P.t9)("provideRecoveryEmailCode",n)})),(0,n.Q6)("clearTwoFaError",(e=>(0,r.IE)(e,{error:void 0}))),(0,n.Q6)("validateRequestedInfo",((e,t,s)=>{const{requestInfo:a,saveInfo:o}=s,c=(0,i.gx)(e),d=c&&(0,i.Z1)(e,c),l=(0,i.Mz)(e);d&&l&&async function(e,t,s,a){const o=await(0,P.t9)("validateRequestedInfo",{chat:e,messageId:t,requestInfo:s,shouldSave:a});if(!o)return;const{id:i,shippingOptions:c}=o;if(!i)return;let d=(0,r.vT)((0,n.Rd)(),i);c?(d=(0,r.TM)(d,c),d=(0,r.Q$)(d,m.KB.Shipping)):d=(0,r.Q$)(d,m.KB.PaymentInfo),(0,n.R3)(d)}(d,l,a,o)})),(0,n.Q6)("getPaymentForm",((e,t,s)=>{const{chat:a,messageId:o}=s;a&&o&&async function(e,t){const s=await(0,P.t9)("getPaymentForm",{chat:e,messageId:t});if(!s)return;let a=(0,r._7)((0,n.Rd)(),s),o=m.KB.PaymentInfo;a.payment.invoice&&(a.payment.invoice.shippingAddressRequested||a.payment.invoice.nameRequested||a.payment.invoice.phoneRequested||a.payment.invoice.emailRequested)&&(o=m.KB.ShippingInfo),a=(0,r.Q$)(a,o),(0,n.R3)(a)}(a,o)})),(0,n.Q6)("getReceipt",((e,t,s)=>{const{receiptMessageId:a,chatId:o,messageId:c}=s,d=o&&(0,i.Z1)(e,o);c&&a&&d&&async function(e,t,s){const a=await(0,P.t9)("getReceipt",e,s);if(!a)return;let o=(0,n.Rd)();const c=(0,i.hj)(o,e.id,t);o=(0,r.Dq)(o,a,c),(0,n.R3)(o)}(d,c,a)})),(0,n.Q6)("clearPaymentError",(e=>{(0,n.R3)({...e,payment:{...e.payment,error:void 0}})})),(0,n.Q6)("clearReceipt",(e=>{(0,n.R3)({...e,payment:{...e.payment,receipt:void 0}})})),(0,n.Q6)("sendCredentialsInfo",((e,t,s)=>{const a=(0,i.$$)(e);if(!a)return;const{credentials:o}=s,{data:c}=o;!async function(e,t){const s=function(e){const t=Object.keys(e).map((t=>`${t}=${e[t]}`)).join("&");return t.length>0?`?${t}`:""}({"card[number]":e.cardNumber,"card[exp_month]":e.expiryMonth,"card[exp_year]":e.expiryYear,"card[cvc]":e.cvv,"card[address_zip]":e.zip,"card[address_country]":e.country}),a=await fetch(`https://api.stripe.com/v1/tokens${s}`,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/x-www-form-urlencoded",Authorization:`Bearer ${t}`}}),o=await a.json();if(o.error){const e=(0,d.Ow)(o.error),t=(0,n.Rd)();return void(0,n.R3)({...t,payment:{...t.payment,error:{...e}}})}let i=(0,r.QH)((0,n.Rd)(),{type:o.type,id:o.id});i=(0,r.Q$)(i,m.KB.Checkout),(0,n.R3)(i)}(c,a)})),(0,n.Q6)("sendPaymentForm",((e,t,s)=>{const{shippingOptionId:a,saveCredentials:o}=s,c=(0,i.gx)(e),d=c&&(0,i.Z1)(e,c),l=(0,i.Mz)(e),u=(0,i.eh)(e),m=(0,i.sp)(e),h=(0,i.$$)(e),g=(0,i.i3)(e);d&&l&&h&&u&&async function(e,t,s,a,o,i){if(await(0,P.t9)("sendPaymentForm",{chat:e,messageId:t,formId:s,credentials:a,requestedInfoId:o,shippingOptionId:i})){const e=(0,r.bp)((0,n.Rd)());(0,n.R3)((0,r.WY)(e))}}(d,l,u,{save:o,data:g},m,a)})),(0,n.Q6)("setPaymentStep",((e,t,s={})=>(0,r.Q$)(e,s.step||m.KB.ShippingInfo))),(0,n.Q6)("setInvoiceMessageInfo",((e,t,s)=>(0,r.nA)(e,s))),s(4907);var j=s(8406);const H=(0,C.P2)((e=>e()),500,!0);(0,n.Q6)("apiUpdate",((e,t,s)=>{switch(s["@type"]){case"updateChat":{s.noTopChatsRequest||(0,i.N)(e,s.id)||t.loadTopChats();const a=(0,r.a4)(e,s.id,s.chat,s.newProfilePhoto);(0,n.R3)(a),H((()=>(0,x.w)((0,i.A1)((0,n.Rd)())))),s.chat.id&&(0,j.Vr)({chatId:s.chat.id,lastReadInboxMessageId:s.chat.lastReadInboxMessageId});break}case"updateChatJoin":{const a=(0,i.Ek)(e,s.id);if(!a)break;e=(0,r.B1)(e,a,[s.id]),e=(0,r.a4)(e,s.id,{isNotJoined:!1}),(0,n.R3)(e);const o=(0,i.Z1)(e,s.id);o&&t.requestChatUpdate({chatId:o.id});break}case"updateChatLeave":(0,n.R3)((0,r.Dd)(e,s.id));break;case"updateChatInbox":(0,n.R3)((0,r.a4)(e,s.id,s.chat)),H((()=>(0,x.w)((0,i.A1)((0,n.Rd)()))));break;case"updateChatTypingStatus":{const{id:t,typingStatus:a}=s;(0,n.R3)((0,r.a4)(e,t,{typingStatus:a})),setTimeout((()=>{const e=(0,n.Rd)(),s=(0,i.Z1)(e,t);s&&a&&s.typingStatus&&s.typingStatus.timestamp===a.timestamp&&(0,n.R3)((0,r.a4)(e,t,{typingStatus:void 0}))}),6e3);break}case"newMessage":{const{message:a}=s,{chatId:o,threadId:c,type:d}=(0,i.Bt)(e)||{};if(a.senderId===e.currentUserId&&!a.isFromScheduled)return;const l=(0,i.Z1)(e,s.chatId);if(!l)return;"thread"===d&&c===u._f&&s.chatId===o?setTimeout((()=>{t.requestChatUpdate({chatId:s.chatId})}),1500):(0,n.R3)((0,r.a4)(e,s.chatId,{unreadCount:l.unreadCount?l.unreadCount+1:1,...s.message.hasUnreadMention&&{unreadMentionsCount:l.unreadMentionsCount?l.unreadMentionsCount+1:1}})),(0,x.w)((0,i.A1)((0,n.Rd)())),(0,j.zP)({chat:l,message:a});break}case"updateCommonBoxMessages":case"updateChannelMessages":{const{ids:t,messageUpdate:a}=s;if(!1!==a.hasUnreadMention)return;t.forEach((t=>{const n="channelId"in s?s.channelId:(0,i.X5)(e,t),a=(0,i.Z1)(e,n);null!=a&&a.unreadMentionsCount&&(e=(0,r.a4)(e,n,{unreadMentionsCount:a.unreadMentionsCount-1}))})),(0,n.R3)(e);break}case"updateChatFullInfo":{const{fullInfo:t}=s,a=e.chats.byId[s.id];if(!a)return;(0,n.R3)((0,r.a4)(e,s.id,{fullInfo:{...a.fullInfo,...t}}));break}case"updatePinnedChatIds":{const{ids:t,folderId:o}=s,r=o===a.WS?"archived":"active";e={...e,chats:{...e.chats,orderedPinnedIds:{...e.chats.orderedPinnedIds,[r]:t.length?t:void 0}}},(0,n.R3)(e);break}case"updateChatPinned":{const{id:t,isPinned:o}=s,r=(0,i.Ek)(e,t);if(r){const{[r]:s}=e.chats.orderedPinnedIds;let n=s||[];if(o){if(!n.includes(t)){if("active"===r&&n.length>=a.EG){const t=e.chats.listIds.active;n=n.filter((e=>t&&t.includes(e)))}n=[t,...n]}}else n=n.filter((e=>e!==t));e={...e,chats:{...e.chats,orderedPinnedIds:{...e.chats.orderedPinnedIds,[r]:n.length?n:void 0}}}}(0,n.R3)(e);break}case"updateChatListType":{const{id:t,folderId:a}=s;(0,n.R3)((0,r.Pi)(e,t,a));break}case"updateChatFolder":{const{id:t,folder:a}=s,{byId:o,orderedIds:r}=e.chatFolders,i=a?{...o,[t]:a}:(0,g.ei)(o,Object.keys(o).map(Number).filter((e=>e!==t))),c=a?r&&r.includes(t)?r:[...r||[],t]:r?r.filter((e=>e!==t)):void 0;(0,n.R3)({...e,chatFolders:{...e.chatFolders,byId:i,orderedIds:c}});break}case"updateChatFoldersOrder":{const{orderedIds:t}=s;(0,n.R3)({...e,chatFolders:{...e.chatFolders,orderedIds:t}});break}case"updateRecommendedChatFolders":{const{folders:t}=s;(0,n.R3)({...e,chatFolders:{...e.chatFolders,recommended:t}});break}case"updateChatMembers":{var o;const t=e.chats.byId[s.id],{replacedMembers:a,addedMember:i,deletedMemberId:c}=s;if(!t)return;let d=!1,l=null!==(o=t.fullInfo)&&void 0!==o&&o.members?[...t.fullInfo.members]:[];if(a)l=a,d=!0;else if(i)l.length&&l.some((e=>e.userId===i.userId))||(l.push(i),d=!0);else if(l.length&&c){const e=l.findIndex((e=>e.userId===c));e>-1&&(l.slice(e,1),d=!0)}if(d){const a=l.filter((({isOwner:e,isAdmin:t})=>e||t));(0,n.R3)((0,r.a4)(e,s.id,{membersCount:l.length,fullInfo:{...t.fullInfo,members:l,adminMembers:a}}))}break}case"deleteProfilePhotos":{const{chatId:t,ids:a}=s,o=e.chats.byId[t];null!=o&&o.photos&&(0,n.R3)((0,r.a4)(e,t,{photos:o.photos.filter((e=>!a.includes(e.id)))}));break}case"draftMessage":{const{chatId:t,formattedText:a,date:o,replyingToId:i}=s;e.chats.byId[t]&&(e=(0,r.pf)(e,t,u._f,"draft",a),e=(0,r.pf)(e,t,u._f,"replyingToId",i),e=(0,r.a4)(e,t,{draftDate:o}),(0,n.R3)(e));break}case"showInvite":{const{data:e}=s;t.showDialog({data:e});break}}}));const _=350;function z(e,t,s,n,a=!1){const o=a?(0,i.Tm)(e,t,s):(0,i.hj)(e,t,s);if(o&&n.content){const{photo:e,video:t,sticker:s,document:a}=(0,d.qp)(o);e&&n.content.photo?(n.content.photo.blobUrl=e.blobUrl,n.content.photo.thumbnail=e.thumbnail):t&&n.content.video?n.content.video.blobUrl=t.blobUrl:s&&n.content.sticker?n.content.sticker.isPreloadedGlobally=s.isPreloadedGlobally:a&&n.content.document&&(n.content.document.previewBlobUrl=a.previewBlobUrl)}return a?(0,r.P4)(e,t,s,n):(0,r.cY)(e,t,s,n)}function V(e,t,s,n){const{chatId:a}=s,{threadInfo:o}=(0,i.Db)(e,a,s)||{};if(!o&&s.replyToMessageId){const o=(0,i.hj)(e,a,s.replyToMessageId);o?e=(0,r.lG)(e,o,a,s.id,n):t.loadMessage({chatId:a,messageId:s.replyToMessageId,threadUpdate:{isDeleting:n,lastMessageId:s.id}})}return e}function K(e,t,s){const{id:n,chatId:a}=s,{threadInfo:o,firstMessageId:c}=(0,i.Db)(e,a,s)||{},l=(0,i.Z1)(e,a),m=(null==l?void 0:l.unreadCount)&&!(0,i.gb)(e,a,u._f);if(e=V(e,t,s),o&&(!c&&(0,d.CI)(s)||(e=(0,r.xj)(e,a,o.threadId,[n]),(0,i.b9)(e,a,o.threadId)&&(e=(0,r.$S)(e,a,o.threadId,n),c||(e=(0,r.pf)(e,a,o.threadId,"firstMessageId",s.id)))),e=(0,r.pf)(e,a,o.threadId,"threadInfo",{...o,lastMessageId:s.id,messagesCount:o.messagesCount+1})),m)return e;if(e=(0,r.xj)(e,a,u._f,[n]),(0,i.b9)(e,a,u._f)){const t=(0,i.It)(e,a,u._f),s=(0,r.$S)(e,a,u._f,n),o=(0,i.Cb)(s,a,u._f);t&&!o.includes(t)||(e=s)}return e}function Y(e,t,s,n=!1){var a;const{chats:o}=e,i=null===(a=o.byId[t])||void 0===a?void 0:a.lastMessage;return!i||n||i.id===s.id||i.id===s.previousLocalId||s.id>i.id?(0,r.a4)(e,t,{lastMessage:s}):e}function W(e,t){const s=(0,i.Zw)(e,t),n=(0,i.gb)(e,t,u._f);if(!s||!n)return;let a=n.length;for(;a--;){const e=s[n[a]];if(!e.isDeleting)return e}}function X(e,t,s,a){if(e){t.forEach((t=>{const s=W(a=(0,r.cY)(a,e,t,{isDeleting:!0}),e);s&&(a=Y(a,e,s,!0))})),(0,n.R3)(a),s.requestChatUpdate({chatId:e});const o=[];return t.forEach((t=>{const n=(0,i.hj)(a,e,t);if(!n)return;a=V(a,s,n,!0);const{threadInfo:r}=(0,i.Db)(a,e,n)||{};r&&o.push(r.threadId)})),(0,n.R3)(a),void setTimeout((()=>{(0,n.R3)((0,r.K4)((0,n.Rd)(),e,t)),(0,g.Tw)(o).forEach((t=>{s.requestThreadInfoUpdate({chatId:e,threadId:t})}))}),_)}const o=[];t.forEach((e=>{const t=(0,i.X5)(a,e);if(t){o.push(t);const s=W(a=(0,r.cY)(a,t,e,{isDeleting:!0}),t);s&&(a=Y(a,t,s,!0)),setTimeout((()=>{(0,n.R3)((0,r.K4)((0,n.Rd)(),t,[e]))}),_)}})),(0,n.R3)(a),(0,g.Tw)(o).forEach((e=>{s.requestChatUpdate({chatId:e})}))}(0,n.Q6)("apiUpdate",((e,t,s)=>{switch(s["@type"]){case"newMessage":{const{chatId:o,id:c,message:l,shouldForceReply:m}=s;e=K(e=z(e,o,c,l),t,l),l.threadInfo&&(e=(0,r.Xg)(e,l.threadInfo.chatId,l.threadInfo.threadId,l.threadInfo)),(0,n.R3)(e);const h=(0,i.hj)(e,o,c);if((0,i.hg)(e,o,l)){var a;if(l.isOutgoing&&(null===(a=l.content)||void 0===a||!a.action)){const s=(0,i.Bt)(e);s&&t.focusMessage({chatId:o,threadId:s.threadId,messageId:l.id,noHighlight:!0,isResizingContainer:!0})}const{threadInfo:s}=(0,i.Db)(e,o,l)||{};s&&t.requestThreadInfoUpdate({chatId:o,threadId:s.threadId}),(0,d.CI)(l)||setTimeout((()=>{let e=(0,n.Rd)();m&&(e=(0,r.pf)(e,o,u._f,"replyingToId",c)),(0,n.R3)(Y(e,o,h))}),_)}else(0,n.R3)(Y((0,n.Rd)(),o,h));(0,i.N)(e,o)||t.loadTopChats();break}case"newScheduledMessage":{const{chatId:t,id:a,message:o}=s;e=z(e,t,a,o,!0);const c=(0,i.qy)(e,t)||[];e=(0,r.pf)(e,t,u._f,"scheduledIds",(0,g.Tw)([...c,a])),(0,n.R3)(e);break}case"updateMessage":{var o,c;const{chatId:a,id:d,message:l}=s;if(!(0,i.hj)(e,a,d))return;e=z(e,a,d,l);const m=(0,i.hj)(e,a,d);l.threadInfo&&(e=(0,r.Xg)(e,l.threadInfo.chatId,l.threadInfo.threadId,l.threadInfo)),e=Y(e,a,m),(0,n.R3)(e);const h=(0,i.Z1)(e,a);h&&!l.isOutgoing&&(null===(o=h.lastMessage)||void 0===o?void 0:o.id)===l.id&&(0,i.xo)(e,h)&&(0,i.hg)(e,a,l)&&(0,i.b9)(e,a,(null===(c=l.threadInfo)||void 0===c?void 0:c.threadId)||u._f)&&t.focusLastMessage();break}case"updateScheduledMessage":{const{chatId:t,id:a,message:o}=s;if(!(0,i.Tm)(e,t,a))return;e=z(e,t,a,o,!0);const c=Object.keys((0,i.Fn)(e,t)||{}).map(Number).sort(((e,t)=>t-e));e=(0,r.pf)(e,t,u._f,"scheduledIds",c),(0,n.R3)(e);break}case"updateMessageSendSucceeded":{const{chatId:a,localId:o,message:c}=s;e=K(e,t,c);const d=(0,i.hj)(e,a,o);e=(0,r.K4)(e,a,[o]),c.isScheduled&&(e=(0,r.bV)(e,a,[o])),e=(0,r.cY)(e,a,c.id,{...d,...c,previousLocalId:o});const l=(0,i.hj)(e,a,c.id);e=Y(e,a,l);const u=(0,i.Db)(e,a,c);null!=u&&u.threadInfo&&(t.markMessageListRead({maxId:c.id}),e=(0,r.pf)(e,a,u.threadInfo.threadId,"threadInfo",{...u.threadInfo,lastMessageId:c.id,lastReadInboxMessageId:c.id})),(0,n.R3)(e);break}case"updateScheduledMessageSendSucceeded":{const{chatId:t,localId:a,message:o}=s,c=(0,i.qy)(e,t)||[];e=(0,r.pf)(e,t,u._f,"scheduledIds",[...c,o.id]);const d=(0,i.Tm)(e,t,a);e=(0,r.bV)(e,t,[a]),e=(0,r.P4)(e,t,o.id,{...d,...o,previousLocalId:a}),(0,n.R3)(e);break}case"updatePinnedIds":{const{chatId:t,isPinned:a,messageIds:o}=s,c=(0,i.KB)(e,t)||[],d=a?[...c,...o].sort(((e,t)=>t-e)):c.filter((e=>!o.includes(e)));(0,n.R3)((0,r.pf)(e,t,u._f,"pinnedIds",d));break}case"updateThreadInfo":{const{chatId:t,threadId:a,threadInfo:o,firstMessageId:c}=s,d={...(0,i.tZ)(e,t,a),...o};if(!d.threadId)return;e=(0,r.Xg)(e,t,a,d),c&&(e=(0,r.pf)(e,t,a,"firstMessageId",c)),(0,n.R3)(e);break}case"resetMessages":{const{id:a}=s,o=(0,i.Zw)(e,a);o&&!(0,d.YC)(a)&&(e=(0,r.K4)(e,a,Object.keys(o).map(Number)),(0,n.R3)(e),t.loadFullChat({chatId:a,force:!0}));break}case"deleteMessages":{const{ids:n,chatId:a}=s;X(a,n,t,e);break}case"deleteScheduledMessages":{const{ids:t,chatId:a}=s;!function(e,t,s,a){e&&(t.forEach((t=>{a=(0,r.P4)(a,e,t,{isDeleting:!0})})),(0,n.R3)(a),setTimeout((()=>{a=(0,r.bV)((0,n.Rd)(),e,t);const s=(0,i.Fn)(a,e);a=(0,r.pf)(a,e,u._f,"scheduledIds",Object.keys(s||{}).map(Number)),(0,n.R3)(a)}),_))}(a,t,0,e);break}case"deleteHistory":{const{chatId:n}=s,a=e.messages.byChatId[n];a?X(n,Object.keys(a.byId).map(Number),t,e):t.requestChatUpdate({chatId:n});break}case"updateCommonBoxMessages":{const{ids:t,messageUpdate:a}=s;t.forEach((t=>{const s=(0,i.X5)(e,t);s&&(e=(0,r.cY)(e,s,t,a))})),(0,n.R3)(e);break}case"updateChannelMessages":{const{channelId:t,ids:a,messageUpdate:o}=s;a.forEach((s=>{e=(0,r.cY)(e,t,s,o)})),(0,n.R3)(e);break}case"updateMessagePoll":{const{pollId:t,pollUpdate:a}=s,o=(0,i.ZB)(e,t);if(null!=o&&o.content.poll){const t={...o.content.poll,...a},{results:s}=t.results||{};if(s&&!s.some((e=>e.isChosen))){const{results:e}=o.content.poll.results,n=e&&e.filter((e=>e.isChosen));n&&n.forEach((e=>{const n=s.findIndex((t=>t.option===e.option));n>=0&&(t.results.results[n].isChosen=!0)}))}(0,n.R3)((0,r.cY)(e,o.chatId,o.id,{content:{...o.content,poll:t}}))}break}case"updateMessagePollVote":{const{pollId:t,userId:a,options:o}=s,c=(0,i.ZB)(e,t);if(!c||!c.content.poll||!c.content.poll.results)break;const{poll:d}=c.content,{recentVoterIds:l,totalVoters:u,results:m}=d.results,h=l?[...l]:[],g=u?u+1:1,p=m?[...m]:[];h.push(a),o.forEach((t=>{const s=p.find((e=>e.option===t)),n=p.findIndex((e=>e.option===t)),o=s?{...s}:{option:t,votersCount:0};o.votersCount+=1,a===e.currentUserId&&(o.isChosen=!0),n?p[n]=o:p.push(o)})),(0,n.R3)((0,r.cY)(e,c.chatId,c.id,{content:{...c.content,poll:{...d,results:{...d.results,recentVoterIds:h,totalVoters:g,results:p}}}}));break}case"updateServiceNotification":{const{message:n}=s;(0,i.UW)(e)&&t.createServiceNotification({message:n});break}}}));const J=(0,C.P2)((function(){const e=(0,n.Rd)();(0,n.R3)((0,r.ps)(e,{...e.users.statusesById,...ee})),ee={}}),3e3,!0);let ee={};(0,n.Q6)("apiUpdate",((e,t,s)=>{switch(s["@type"]){case"deleteContact":return(0,r.GK)(e,s.id);case"updateUser":return(0,r.Nq)(e,s.id,s.user);case"updateUserStatus":return n=s.userId,a=s.status,ee[n]=a,void J();case"updateUserFullInfo":{const{id:t,fullInfo:n}=s,a=e.users.byId[t];if(!a)return;return(0,r.Nq)(e,t,{fullInfo:{...a.fullInfo,...n}})}}var n,a})),(0,n.Q6)("apiUpdate",((e,t,s)=>{switch(s["@type"]){case"updateStickerSet":return(0,r.Rg)(e,s.id,s.stickerSet)}})),(0,n.Q6)("apiUpdate",((e,t,s)=>{switch(s["@type"]){case"updatePeerBlocked":return s.isBlocked?(0,r.O4)((0,n.Rd)(),s.id):(0,r.rB)((0,n.Rd)(),s.id);case"updateResetContactList":(0,n.R3)({...(0,n.Rd)(),contactList:{userIds:[]}});break;case"updateFavoriteStickers":t.loadFavoriteStickers();break;case"updatePrivacy":e.settings.privacy[s.key]=s.rules}})),(0,n.Q6)("apiUpdate",((e,t,s)=>{switch(s["@type"]){case"updateNotifySettings":return(0,r.HN)(e,s.peerType,s.isSilent,s.shouldShowPreviews);case"updateNotifyExceptions":{const{chatId:t,isMuted:a,isSilent:o,shouldShowPreviews:i}=s;e.chats.byId[t]&&(e=(0,r.a4)(e,t,{isMuted:a})),(0,n.R3)((0,r.aK)(e,t,{isMuted:a,isSilent:o,shouldShowPreviews:i}));break}}})),(0,n.Q6)("apiUpdate",((e,t,s)=>{switch(s["@type"]){case"updateTwoFaStateWaitCode":return{...e,twoFaSettings:{...e.twoFaSettings,isLoading:!1,waitingEmailCodeLength:s.length}};case"updateTwoFaError":return{...e,twoFaSettings:{...e.twoFaSettings,error:s.message}}}}));var te=s(4446);(0,n.Q6)("apiUpdate",((e,t,s)=>{switch(s["@type"]){case"updateGroupCall":return"discarded"===s.call.connectionState?e.groupCalls.activeGroupCallId?void t.leaveGroupCall({shouldRemove:!0}):(0,te.dc)(e,s.call.id):(0,te.AH)(e,s.call.id,(0,g.CE)(s.call,["connectionState"]),void 0,s.call.participantsCount);case"updateGroupCallChatId":{const t=(0,i.Z1)(e,s.chatId);return t&&(e=(0,r.a4)(e,s.chatId,{fullInfo:{...t.fullInfo,groupCallId:s.call.id}})),e}case"updateGroupCallParticipants":{const{groupCallId:t,participants:a,nextOffset:o}=s,{currentUserId:r}=e;return e=(0,n.Rd)(),a.forEach((s=>{s.id&&(e=(0,te.B6)(e,t,s.id,s,!!o||r===s.id))})),o&&(e=(0,te.AH)(e,t,{nextOffset:o})),e}}}));var se=s(8674),ne=s(6752),ae=s(1279),oe=s(3551),re=s(3227),ie=s(3858),ce=s(1212),de=s(5332);function le(e){(0,o.d4)((()=>(0,C.Gq)(e)),[e])}var ue=s(9290);const me=document.querySelector('meta[name="viewport"]'),he=(null==me?void 0:me.getAttribute("content"))||"";function ge(e){e.preventDefault()}var pe=s(6590),fe=s(3989),Ie=s(7529),ve=s(3455),ye=s(706),Ze=s(2255);function Pe(){const[e,t]=(0,o.eJ)(window.navigator.onLine);return(0,o.d4)((()=>{function e(){t(window.navigator.onLine)}return window.addEventListener("online",e),window.addEventListener("offline",e),()=>{window.removeEventListener("offline",e),window.removeEventListener("online",e)}}),[]),e}var Ce=s(9107),we=s(6917),be=s(7926),Se=s(3106),Ee=s(8964),Me=s(231),ke=s(9589),Re=s(9187),Te=s(3321);const Ne=[0,1,2],Be=(0,o.X$)((0,n.c$)((e=>{const{query:t,fetchingStatus:s,chatId:n,date:a}=e.globalSearch,{currentUserId:o}=e,{byId:r}=e.chats,{animationLevel:c}=e.settings.byKey;return{searchQuery:t,isLoading:!!s&&Boolean(s.chats||s.messages),currentUserId:o,chatsById:r,globalSearchChatId:n,searchDate:a,theme:(0,i.Pu)(e),animationLevel:c}}))((({content:e,contactsFilter:t,onSearchQuery:s,onSelectSettings:r,onSelectContacts:i,onSelectArchived:c,onReset:l,searchQuery:u,isLoading:g,shouldSkipTransition:p,currentUserId:f,globalSearchChatId:I,searchDate:v,theme:y,animationLevel:Z,chatsById:P})=>{const{openChat:C,openTipsChat:w,setGlobalSearchDate:b,setSettingOption:S,setGlobalSearchChatId:E}=(0,n.uC)(),M=(0,Ce.Z)(),k=e===m.du.ChatList,R=(0,o.Ye)((()=>v?(0,N.xH)(new Date(1e3*v)):void 0),[v]),T=(0,o.Ye)((()=>k&&P?Object.values(P).reduce(((e,t)=>(0,d.pE)(t)&&t.unreadCount?e+1:e),0):0),[k,P]),B="web.telegram.org"===window.location.hostname,A=(0,o.Ye)((()=>({onTrigger:e,isOpen:t})=>o.ZP.createElement(Me.Z,{round:!0,ripple:k&&!h.wB,size:"smaller",color:"translucent",className:t?"active":"",onClick:k?e:()=>l(),ariaLabel:k?M("AccDescrOpenMenu2"):"Return to chat list"},o.ZP.createElement("div",{className:(0,ne.Z)("animated-menu-icon",!k&&"state-back",p&&"no-animation")}))),[k,M,l,p]),x=(0,o.I4)((()=>{u||s("")}),[u,s]),L=(0,o.I4)((()=>{C({id:f,shouldReplaceHistory:!0})}),[f,C]),O=(0,o.I4)((e=>{e.stopPropagation();const t="light"===y?"dark":"light";S({theme:t}),S({shouldUseSystemTheme:!1}),(0,we.Z)(t,Z===a.zy)}),[Z,S,y]),F=(0,o.I4)((e=>{e.stopPropagation();const t=0===Z?2:0;Ne.forEach(((e,s)=>{document.body.classList.toggle(`animation-level-${s}`,t===s)})),S({animationLevel:t})}),[Z,S]),U=Boolean(I)||e===m.du.GlobalSearch||e===m.du.Contacts,$=e===m.du.Contacts?M("SearchFriends"):M("Search");return o.ZP.createElement("div",{className:"LeftMainHeader"},o.ZP.createElement("div",{id:"LeftMainHeader",className:"left-header"},o.ZP.createElement(Se.Z,{trigger:A,footer:`${a.iC} ${a.Ji}`},o.ZP.createElement(Ee.Z,{icon:"saved-messages",onClick:L},M("SavedMessages")),o.ZP.createElement(Ee.Z,{icon:"archive",onClick:c},o.ZP.createElement("span",{className:"menu-item-name"},M("ArchivedChats")),T>0&&o.ZP.createElement("div",{className:"archived-badge"},T)),o.ZP.createElement(Ee.Z,{icon:"user",onClick:i},M("Contacts")),o.ZP.createElement(Ee.Z,{icon:"settings",onClick:r},M("Settings")),o.ZP.createElement(Ee.Z,{icon:"darkmode",onClick:O},o.ZP.createElement("span",{className:"menu-item-name"},M("lng_menu_night_mode")),o.ZP.createElement(Te.Z,{id:"darkmode",label:M("dark"===y?"lng_settings_disable_night_theme":"lng_settings_enable_night_theme"),checked:"dark"===y,noAnimation:!0})),o.ZP.createElement(Ee.Z,{icon:"animations",onClick:F},o.ZP.createElement("span",{className:"menu-item-name capitalize"},M("Appearance.Animations").toLowerCase()),o.ZP.createElement(Te.Z,{id:"animations",label:"Toggle Animations",checked:Z>0})),o.ZP.createElement(Ee.Z,{icon:"help",onClick:()=>{w({langCode:M.code})}},M("TelegramFeatures")),o.ZP.createElement(Ee.Z,{icon:"bug",href:a.mU},"Report Bug"),B&&o.ZP.createElement(o.ZP.Fragment,null,o.ZP.createElement(Ee.Z,{icon:"char-K",href:"https://web.telegram.org/k/",onClick:()=>{(0,be.L)("K"),(0,pe.Wv)()}},"Switch to K Version"),o.ZP.createElement(Ee.Z,{icon:"char-W",href:"https://web.telegram.org/?legacy=1",onClick:pe.Wv},"Switch to Old Version"))),o.ZP.createElement(ke.Z,{inputId:"telegram-search-input",parentContainerClassName:"LeftSearch",className:I||v?"with-picker-item":"",value:t||u,focused:U,isLoading:g,placeholder:$,autoComplete:"off",canClose:Boolean(I||v),onChange:s,onReset:l,onFocus:x},R&&o.ZP.createElement(Re.Z,{icon:"calendar",title:R,canClose:!0,isMinimized:Boolean(I),className:"search-date",onClick:b,clickArg:{date:void 0}}),I&&o.ZP.createElement(Re.Z,{chatOrUserId:I,onClick:E,canClose:!0,clickArg:{id:void 0}}))))})));var Ae=s(9204);const xe=(0,o.X$)((()=>{const e=(0,Ce.Z)();return o.ZP.createElement("div",{id:"ConnectionState",dir:e.isRtl?"rtl":void 0},o.ZP.createElement(Ae.Z,{color:"black"}),o.ZP.createElement("div",{className:"state-text"},e("WaitingForNetwork")))}));var Le=s(1174),Oe=s(6071),Fe=s(3133),Ue=s(1080);const $e=(0,o.X$)((0,n.c$)((e=>{const{chats:{listIds:t,byId:s},users:{byId:n},chatFolders:{byId:a,orderedIds:o,activeChatFolder:r},currentUserId:c,lastSyncTime:d,shouldSkipHistoryAnimations:l}=e;return{allListIds:t,chatsById:s,usersById:n,chatFoldersById:a,orderedFolderIds:o,lastSyncTime:d,notifySettings:(0,i.dZ)(e),notifyExceptions:(0,i.NJ)(e),activeChatFolder:r,currentUserId:c,shouldSkipHistoryAnimations:l}}))((({allListIds:e,chatsById:t,usersById:s,chatFoldersById:r,notifySettings:i,notifyExceptions:c,orderedFolderIds:l,activeChatFolder:u,currentUserId:m,lastSyncTime:p,shouldSkipHistoryAnimations:f,foldersDispatch:I,onScreenSelect:v})=>{const{loadChatFolders:y,setActiveChatFolder:Z,openChat:P}=(0,n.uC)(),C=(0,o.sO)(null),w=(0,Ce.Z)();(0,o.d4)((()=>{p&&y()}),[p,y]);const b=(0,o.Ye)((()=>l?l.map((e=>r[e]||{})).filter(Boolean):void 0),[r,l]),S=((n,a,r)=>{const l=(0,Oe.Z)(3e3,!0),[u,m]=(0,o.eJ)(),[h,p,f]=(0,ye.Z)();return(0,se.ZP)(p,f),(0,ue.Z)((()=>{h||l((()=>{m((()=>{if(!b||!b.length)return;const n=b.map((n=>{const{unreadDialogsCount:a,hasActiveDialogs:o}=(0,d.Fu)(e,t,s,n,i,c)||{};return{id:n.id,badgeCount:a,isBadgeActive:o}}));return(0,g.ee)(n,"id")})())}))}),r.concat([h])),u})(0,0,[b,e,t,s,i,c]),E=(0,o.Ye)((()=>{if(b&&b.length)return[{title:"en"===w.code?"All":w("FilterAllChats"),id:a.Nf},...b.map((e=>({title:e.title,...null==S?void 0:S[e.id]})))]}),[b,S,w]),M=(0,o.I4)((e=>{Z(e,{forceOnHeavyAnimation:!0})}),[Z]);(0,o.d4)((()=>{E&&E.length&&u>=E.length&&Z(0)}),[u,E,Z]),(0,o.d4)((()=>{if(C.current&&h.$b&&E&&E.length)return(0,Le.s)(C.current,{selectorToPreventScroll:".chat-list",onSwipe:(e,t)=>t===Le.e.Left?(Z(Math.min(u+1,E.length-1),{forceOnHeavyAnimation:!0}),!0):t===Le.e.Right&&(Z(Math.max(0,u-1),{forceOnHeavyAnimation:!0}),!0)})}),[u,E,Z]);const k=(0,o.sO)();k.current=0!==u,(0,o.d4)((()=>k.current?(0,fe.Z)((()=>{k.current&&Z(0)})):void 0),[u,Z]),(0,pe.ZP)(0!==u,(()=>Z(0,{forceOnHeavyAnimation:!0}))),(0,o.d4)((()=>{const e=e=>{if(e.ctrlKey&&e.shiftKey&&e.code.startsWith("Digit")&&E){const[,t]=e.code.match(/Digit(\d)/)||[];if(!t)return;if("0"===t)return void P({id:m,shouldReplaceHistory:!0});const s=Number(t)-1;if(s>E.length-1)return;Z(s,{forceOnHeavyAnimation:!0}),e.preventDefault()}};return document.addEventListener("keydown",e,!0),()=>{document.removeEventListener("keydown",e,!0)}}));const{shouldRender:R,transitionClassNames:T}=(0,ce.Z)(!l,void 0,!0);function N(e){const t=Object.values(r).find((({id:e})=>e===E[u].id));return t&&0!==u?o.ZP.createElement(Ue.Z,{folderType:"folder",folderId:t.id,isActive:e,onScreenSelect:v,foldersDispatch:I}):o.ZP.createElement(Ue.Z,{folderType:"all",isActive:e,foldersDispatch:I,onScreenSelect:v})}return o.ZP.createElement("div",{className:"ChatFolders"},null!=E&&E.length?o.ZP.createElement(Fe.Z,{tabs:E,activeTab:u,onSwitchTab:M}):R?o.ZP.createElement("div",{className:(0,ne.Z)("tabs-placeholder",T)}):void 0,o.ZP.createElement(Ze.Z,{ref:C,name:f?"none":w.isRtl?"slide-optimized-rtl":"slide-optimized",activeKey:u,renderCount:E?E.length:void 0},N))})));var De=s(9203),qe=s(8778),Qe=s(4288);const Ge=(0,o.X$)((e=>{const t=(0,qe.Z)(De.gl.Extra,"LeftSearch");return t?o.ZP.createElement(t,e):o.ZP.createElement(Qe.Z,null)})),je=(0,o.X$)((e=>{const t=(0,qe.Z)(De.gl.Extra,"ContactList");return t?o.ZP.createElement(t,e):o.ZP.createElement(Qe.Z,null)}));var He=s(2328);let _e;const ze=(0,o.X$)((({isShown:e,onNewPrivateChat:t,onNewChannel:s,onNewGroup:n})=>{const[a,r]=(0,o.eJ)(!1);(0,o.d4)((()=>{e||r(!1)}),[e]);const i=(0,Ce.Z)(),c=(0,ne.Z)("NewChatButton",e&&"revealed",a&&"menu-is-open"),d=(0,o.I4)((()=>{_e&&(clearTimeout(_e),_e=void 0)}),[]),l=(0,o.I4)((()=>{_e&&(clearTimeout(_e),_e=void 0),_e=window.setTimeout((()=>{r(!1)}),750)}),[]);return o.ZP.createElement("div",{className:c,onMouseEnter:d,onMouseLeave:l},o.ZP.createElement(Me.Z,{round:!0,color:"primary",className:a?"active":"",onClick:()=>{r(!a)},ariaLabel:i(a?"Close":"NewMessageTitle"),tabIndex:-1},o.ZP.createElement("i",{className:"icon-new-chat-filled"}),o.ZP.createElement("i",{className:"icon-close"})),o.ZP.createElement(He.Z,{isOpen:a,positionX:"right",positionY:"bottom",autoClose:!0,onClose:()=>{r(!1)}},o.ZP.createElement(Ee.Z,{icon:"channel",onClick:s},i("NewChannel")),o.ZP.createElement(Ee.Z,{icon:"group",onClick:n},i("NewGroup")),o.ZP.createElement(Ee.Z,{icon:"user",onClick:t},i("NewMessageTitle"))))}));var Ve=s(126);const Ke=Object.keys(m.du).length/2;let Ye;const We=(0,n.c$)((e=>(0,g.ei)(e,["connectionState"])))((({content:e,searchQuery:t,searchDate:s,contactsFilter:n,shouldSkipTransition:a,foldersDispatch:r,onSearchQuery:i,onContentChange:c,onScreenSelect:d,onReset:l,connectionState:u})=>{const[g,p]=(0,o.eJ)(h.$b),f=!Pe()||"connectionStateConnecting"===u,I=(0,o.sO)(!1),v=(0,o.I4)((()=>{c(m.du.Settings)}),[c]),y=(0,o.I4)((()=>{c(m.du.Contacts)}),[c]),Z=(0,o.I4)((()=>{c(m.du.NewChannelStep1)}),[c]),P=(0,o.I4)((()=>{c(m.du.NewGroupStep1)}),[c]),C=(0,o.I4)((()=>{c(m.du.Archived)}),[c]),w=(0,o.I4)((()=>{e===m.du.ChatList&&(I.current=!0,p(!0))}),[e]),b=(0,o.I4)((()=>{I.current=!1,Ye&&(clearTimeout(Ye),Ye=void 0),Ye=window.setTimeout((()=>{I.current||p(!1)}),250)}),[]);(0,o.d4)((()=>{let t;return e!==m.du.ChatList?t=window.setTimeout((()=>{p(!1)}),250):(I.current||h.$b)&&p(!0),()=>{t&&(clearTimeout(t),t=void 0)}}),[e]);const[S,E,M]=function(){const[e,t]=(0,ye.Z)(!1);(0,o.d4)((()=>{const e=window.setTimeout(t,2592e5);return()=>{clearTimeout(e)}}),[t]);const{shouldRender:s,transitionClassNames:n}=(0,ce.Z)(e);return[s,n,()=>{window.location.reload()}]}(),k=(0,Ce.Z)();return o.ZP.createElement("div",{id:"LeftColumn-main",onMouseEnter:h.$b?void 0:w,onMouseLeave:h.$b?void 0:b},o.ZP.createElement(Be,{content:e,contactsFilter:n,onSearchQuery:i,onSelectSettings:v,onSelectContacts:y,onSelectArchived:C,onReset:l,shouldSkipTransition:a}),o.ZP.createElement(Ve.Z,{isOpen:f,isCustom:!0,className:"connection-state-wrapper opacity-transition slow"},(()=>o.ZP.createElement(xe,null))),o.ZP.createElement(Ze.Z,{name:a?"none":"zoom-fade",renderCount:Ke,activeKey:e,shouldCleanup:!0,cleanupExceptionKey:m.du.ChatList,className:f?"pull-down":void 0},(a=>{switch(e){case m.du.ChatList:return o.ZP.createElement($e,{onScreenSelect:d,foldersDispatch:r});case m.du.GlobalSearch:return o.ZP.createElement(Ge,{searchQuery:t,searchDate:s,isActive:a,onReset:l});case m.du.Contacts:return o.ZP.createElement(je,{filter:n,isActive:a,onReset:l});default:return}})),S&&o.ZP.createElement(Me.Z,{fluid:!0,pill:!0,className:(0,ne.Z)("btn-update",E),onClick:M},k("lng_update_telegram")),o.ZP.createElement(ze,{isShown:g,onNewPrivateChat:y,onNewChannel:Z,onNewGroup:P}))})),Xe=(0,o.X$)((e=>{const t=(0,qe.Z)(De.gl.Extra,"Settings");return t?o.ZP.createElement(t,e):o.ZP.createElement(Qe.Z,null)})),Je=(0,o.X$)((e=>{const t=(0,qe.Z)(De.gl.Extra,"NewChat");return t?o.ZP.createElement(t,e):o.ZP.createElement(Qe.Z,null)})),et=(0,o.X$)((e=>{const t=(0,qe.Z)(De.gl.Extra,"ArchivedChats");return t?o.ZP.createElement(t,e):o.ZP.createElement(Qe.Z,null)}));var tt;!function(e){e[e.Main=0]="Main",e[e.Settings=1]="Settings",e[e.Archived=2]="Archived",e[e.NewGroup=3]="NewGroup",e[e.NewChannel=4]="NewChannel"}(tt||(tt={}));const st=Object.keys(tt).length/2,nt=(0,o.X$)((0,n.c$)((e=>{const{globalSearch:{query:t,date:s},chatFolders:{activeChatFolder:n},shouldSkipHistoryAnimations:a,leftColumnWidth:o}=e;return{searchQuery:t,searchDate:s,activeChatFolder:n,shouldSkipHistoryAnimations:a,leftColumnWidth:o}}))((({searchQuery:e,searchDate:t,activeChatFolder:s,shouldSkipHistoryAnimations:a,leftColumnWidth:r})=>{const{setGlobalSearchQuery:i,setGlobalSearchChatId:c,resetChatCreation:d,setGlobalSearchDate:l,loadPasswordInfo:u,clearTwoFaError:g,setLeftColumnWidth:p,resetLeftColumnWidth:f}=(0,n.uC)(),I=(0,o.sO)(null),[v,y]=(0,o.eJ)(m.du.ChatList),[Z,P]=(0,o.eJ)(m.MT.Main),[C,w]=(0,o.eJ)(""),[b,S]=(0,ve.ZP)(),[E,M]=(0,o.eJ)(0);let k=tt.Main;switch(v){case m.du.Archived:k=tt.Archived;break;case m.du.Settings:k=tt.Settings;break;case m.du.NewChannelStep1:case m.du.NewChannelStep2:k=tt.NewChannel;break;case m.du.NewGroupStep1:case m.du.NewGroupStep2:k=tt.NewGroup}const R=(0,o.I4)((e=>{if(v!==m.du.NewGroupStep2||e)if(v!==m.du.NewChannelStep2||e){if(v===m.du.NewGroupStep1){const e=document.getElementById("new-group-picker-search");e&&e.blur()}if(v===m.du.Settings)switch(Z){case m.MT.EditProfile:case m.MT.Folders:case m.MT.General:case m.MT.Notifications:case m.MT.DataStorage:case m.MT.Privacy:case m.MT.Language:return void P(m.MT.Main);case m.MT.GeneralChatBackground:return void P(m.MT.General);case m.MT.GeneralChatBackgroundColor:return void P(m.MT.GeneralChatBackground);case m.MT.PrivacyPhoneNumber:case m.MT.PrivacyLastSeen:case m.MT.PrivacyProfilePhoto:case m.MT.PrivacyForwarding:case m.MT.PrivacyGroupChats:case m.MT.PrivacyActiveSessions:case m.MT.PrivacyBlockedUsers:case m.MT.TwoFaDisabled:case m.MT.TwoFaEnabled:case m.MT.TwoFaCongratulations:return void P(m.MT.Privacy);case m.MT.PrivacyPhoneNumberAllowedContacts:case m.MT.PrivacyPhoneNumberDeniedContacts:return void P(m.MT.PrivacyPhoneNumber);case m.MT.PrivacyLastSeenAllowedContacts:case m.MT.PrivacyLastSeenDeniedContacts:return void P(m.MT.PrivacyLastSeen);case m.MT.PrivacyProfilePhotoAllowedContacts:case m.MT.PrivacyProfilePhotoDeniedContacts:return void P(m.MT.PrivacyProfilePhoto);case m.MT.PrivacyForwardingAllowedContacts:case m.MT.PrivacyForwardingDeniedContacts:return void P(m.MT.PrivacyForwarding);case m.MT.PrivacyGroupChatsAllowedContacts:case m.MT.PrivacyGroupChatsDeniedContacts:return void P(m.MT.PrivacyGroupChats);case m.MT.TwoFaNewPassword:return void P(m.MT.TwoFaDisabled);case m.MT.TwoFaNewPasswordConfirm:return void P(m.MT.TwoFaNewPassword);case m.MT.TwoFaNewPasswordHint:return void P(m.MT.TwoFaNewPasswordConfirm);case m.MT.TwoFaNewPasswordEmail:return void P(m.MT.TwoFaNewPasswordHint);case m.MT.TwoFaNewPasswordEmailCode:return void P(m.MT.TwoFaNewPasswordEmail);case m.MT.TwoFaChangePasswordCurrent:case m.MT.TwoFaTurnOff:case m.MT.TwoFaRecoveryEmailCurrentPassword:return void P(m.MT.TwoFaEnabled);case m.MT.TwoFaChangePasswordNew:return void P(m.MT.TwoFaChangePasswordCurrent);case m.MT.TwoFaChangePasswordConfirm:return void P(m.MT.TwoFaChangePasswordNew);case m.MT.TwoFaChangePasswordHint:return void P(m.MT.TwoFaChangePasswordConfirm);case m.MT.TwoFaRecoveryEmail:return void P(m.MT.TwoFaRecoveryEmailCurrentPassword);case m.MT.TwoFaRecoveryEmailCode:return void P(m.MT.TwoFaRecoveryEmail);case m.MT.FoldersCreateFolder:case m.MT.FoldersEditFolder:return void P(m.MT.Folders);case m.MT.FoldersIncludedChatsFromChatList:case m.MT.FoldersExcludedChatsFromChatList:return void P(m.MT.FoldersEditFolderFromChatList);case m.MT.FoldersEditFolderFromChatList:return y(m.du.ChatList),void P(m.MT.Main)}v!==m.du.ChatList||0!==s?(y(m.du.ChatList),w(""),i({query:""}),l({date:void 0}),c({id:void 0}),d(),setTimeout((()=>{M(Date.now())}),250)):y(m.du.GlobalSearch)}else y(m.du.NewChannelStep1);else y(m.du.NewGroupStep1)}),[v,s,Z,i,l,c,d]),T=(0,o.I4)((t=>{v!==m.du.Contacts?(y(m.du.GlobalSearch),t!==e&&i({query:t})):w(t)}),[v,e,i]);(0,o.d4)((()=>v!==m.du.ChatList||0===s?(0,fe.Z)((()=>R())):void 0),[s,v,R]),(0,o.d4)((()=>{if(v!==m.du.GlobalSearch)return document.addEventListener("keydown",e,!1),()=>{document.removeEventListener("keydown",e,!1)};function e(e){(h.jm&&e.metaKey||!h.jm&&e.ctrlKey)&&e.shiftKey&&"f"===(0,Ie.Z)(e)&&(e.preventDefault(),y(m.du.GlobalSearch))}}),[v]),(0,o.d4)((()=>{g(),Z===m.MT.Privacy&&u()}),[g,u,Z]);const{initResize:N,resetResize:B,handleMouseUp:A}=((e,t,s,n)=>{const[a,r,i]=(0,ye.Z)(),[c,d]=(0,o.eJ)(),[l,u]=(0,o.eJ)();(0,o.d4)((()=>{e.current&&n&&(e.current.style.width=`${n}px`)}),[e,n]);const m=()=>{document.body.classList.remove("no-selection","cursor-ew-resize")};return(0,o.d4)((()=>{if(!a)return;const s=t=>{const s=Math.ceil(l+t.clientX-c);e.current.style.width=`${s}px`},n=()=>{m(),document.removeEventListener("mousemove",s,!1),document.removeEventListener("mouseup",n,!1),document.removeEventListener("blur",n,!1),t(e.current.offsetWidth),i()};document.addEventListener("mousemove",s,!1),document.addEventListener("mouseup",n,!1),document.addEventListener("blur",n,!1)}),[l,c,e,t,a,i]),{initResize:t=>{document.body.classList.add("no-selection","cursor-ew-resize"),d(t.clientX),u(e.current.offsetWidth),r()},resetResize:t=>{t.preventDefault(),e.current.style.width="",s()},handleMouseUp:m}})(I,p,f,r),x=e=>{y(m.du.Settings),P(e)};return o.ZP.createElement("div",{id:"LeftColumn",ref:I},o.ZP.createElement(Ze.Z,{name:a?"none":h.s0,renderCount:st,activeKey:k,shouldCleanup:!0,cleanupExceptionKey:tt.Main},(s=>{switch(k){case tt.Archived:return o.ZP.createElement(et,{isActive:s,onReset:R,onContentChange:y});case tt.Settings:return o.ZP.createElement(Xe,{isActive:s,currentScreen:Z,foldersState:b,foldersDispatch:S,onScreenSelect:x,onReset:R,shouldSkipTransition:a});case tt.NewChannel:return o.ZP.createElement(Je,{key:E,isActive:s,isChannel:!0,content:v,onContentChange:y,onReset:R});case tt.NewGroup:return o.ZP.createElement(Je,{key:E,isActive:s,content:v,onContentChange:y,onReset:R});default:return o.ZP.createElement(We,{content:v,searchQuery:e,searchDate:t,contactsFilter:C,foldersDispatch:S,onContentChange:y,onSearchQuery:T,onScreenSelect:x,onReset:R,shouldSkipTransition:a})}})),o.ZP.createElement("div",{className:"resize-handle",onMouseDown:N,onMouseUp:A,onDoubleClick:B}))})));var at=s(2420),ot=s(5780),rt=s(9524),it=s(1394);const ct=()=>{const[e,t]=(0,o.eJ)(ie.Z.get());return(0,o.d4)((()=>{const e=(0,C.P2)((()=>{t(ie.Z.get())}),250,!1);return window.addEventListener("resize",e),()=>{window.removeEventListener("resize",e)}}),[]),e};var dt=s(2678),lt=s(7204),ut=s(5326);const mt=728;var ht=s(3570),gt=s(5790),pt=s(8360),ft=s(2155),It=s(6058),vt=s(8799);const yt=(0,o.X$)((e=>{const{isOpen:t}=e,s=(0,qe.Z)(De.gl.Extra,"HeaderMenuContainer",!t);return s?o.ZP.createElement(s,e):void 0})),Zt=(0,o.X$)((0,n.c$)(((e,{chatId:t,threadId:s,messageListType:n})=>{var a;const o=(0,i.Z1)(e,t),r=Boolean(o&&(0,d.eA)(o));if(!o||o.isRestricted||(0,i.CA)(e))return{noMenu:!0};const c=(0,i.IK)(e,t),l=(0,i.FM)(e,t),m="thread"===n&&s===u._f,g="thread"===n&&s!==u._f,p=(0,i.Jf)(e),f=Boolean(c&&(0,i.s4)(e,c.id)),I=!f&&Boolean((0,i.pk)(e,t)),v=Boolean(m&&(r||(0,d.ZV)(o))&&o.isNotJoined);return{noMenu:!1,isChannel:r,isRightColumnShown:p,canStartBot:I,canRestartBot:f,canSubscribe:v,canSearch:m||g,canCall:h.Bi&&(0,d.YC)(o.id)&&!l&&!c,canMute:m&&!l&&!v,canLeave:m&&!v,canEnterVoiceChat:h.Bi&&o.isCallActive,canCreateVoiceChat:h.Bi&&!o.isCallActive&&((null===(a=o.adminRights)||void 0===a?void 0:a.manageCall)||o.isCreator&&(0,d.G9)(o))}}))((({chatId:e,threadId:t,noMenu:s,isChannel:a,canStartBot:r,canRestartBot:i,canSubscribe:c,canSearch:d,canCall:l,canMute:u,canLeave:m,canEnterVoiceChat:g,canCreateVoiceChat:p,isRightColumnShown:f,canExpandActions:I})=>{const{joinChannel:v,sendBotCommand:y,openLocalTextSearch:Z,restartBot:P,openCallFallbackConfirm:C}=(0,n.uC)(),w=(0,o.sO)(null),[b,S]=(0,o.eJ)(!1),[E,M]=(0,o.eJ)(void 0),k=(0,o.I4)((()=>{S(!0);const e=w.current.getBoundingClientRect();M({x:e.right,y:e.bottom})}),[]),R=(0,o.I4)((()=>{S(!1)}),[]),T=(0,o.I4)((()=>{M(void 0)}),[]),N=(0,o.I4)((()=>{v({chatId:e})}),[v,e]),B=(0,o.I4)((()=>{y({command:"/start"})}),[y]),A=(0,o.I4)((()=>{P({chatId:e})}),[e,P]),x=(0,o.I4)((()=>{Z(),h.wB?document.querySelector("#MobileSearch input").focus():setTimeout((()=>{const e=document.querySelector(".RightHeader .SearchInput input");e&&e.focus()}),400)}),[Z]);(0,o.d4)((()=>{if(d)return document.addEventListener("keydown",e,!1),()=>{document.removeEventListener("keydown",e,!1)};function e(e){h.fl&&(h.jm&&e.metaKey||!h.jm&&e.ctrlKey)&&!e.shiftKey&&"f"===(0,Ie.Z)(e)&&(e.preventDefault(),x())}}),[d,x]);const L=(0,Ce.Z)();return o.ZP.createElement("div",{className:"HeaderActions"},!h.wB&&o.ZP.createElement(o.ZP.Fragment,null,I&&c&&o.ZP.createElement(Me.Z,{size:"tiny",ripple:!0,fluid:!0,onClick:N},L(a?"ProfileJoinChannel":"ProfileJoinGroup")),I&&r&&o.ZP.createElement(Me.Z,{size:"tiny",ripple:!0,fluid:!0,onClick:B},L("BotStart")),I&&i&&o.ZP.createElement(Me.Z,{size:"tiny",ripple:!0,fluid:!0,onClick:A},L("BotRestart")),d&&o.ZP.createElement(Me.Z,{round:!0,ripple:f,color:"translucent",size:"smaller",onClick:x,ariaLabel:"Search in this chat"},o.ZP.createElement("i",{className:"icon-search"})),l&&o.ZP.createElement(Me.Z,{round:!0,color:"translucent",size:"smaller",onClick:C,ariaLabel:"Call"},o.ZP.createElement("i",{className:"icon-phone"}))),o.ZP.createElement(Me.Z,{ref:w,className:b?"active":"",round:!0,ripple:!h.wB,size:"smaller",color:"translucent",disabled:s,ariaLabel:"More actions",onClick:k},o.ZP.createElement("i",{className:"icon-more"})),E&&o.ZP.createElement(yt,{chatId:e,threadId:t,isOpen:b,anchor:E,withExtraActions:h.wB||!I,isChannel:a,canStartBot:r,canRestartBot:i,canSubscribe:c,canSearch:d,canCall:l,canMute:u,canLeave:m,canEnterVoiceChat:g,canCreateVoiceChat:p,onSubscribeChannel:N,onSearchClick:x,onClose:R,onCloseAnimationEnd:T}))})));var Pt=s(4399),Ct=s(2340),wt=s(6202),bt=s(862);function St(e){var t;const s=e&&(0,d.DH)(e),n=null==e||null===(t=e.content)||void 0===t?void 0:t.sticker,r=s&&n&&!(0,h.on)()&&s.includes("image/webp"),[i,c]=(0,o.eJ)(bt.Hu),l=null==e?void 0:e.id;return(0,o.bt)((()=>{r&&(0,bt.p6)(`b64-${l}`,s).then(c).catch((e=>{a.eM&&console.error(e)}))}),[l,r,s]),r?i:s}var Et=s(7551),Mt=s(8512);function kt(e,t,s,n,a){return`M${e},${t+a}a${a},${a},0,0,1,\n ${s},0v${n-2*a}a${a},${a},0,0,1,${-s},0Z`}const Rt=(0,o.X$)((({count:e,index:t})=>{const s=(0,o.sO)(null),n=(0,o.Ye)((()=>function(e,t){const s=e-t-1,n=function(e){let t=8;return 1===e?t=36:2===e?t=17:3===e?t=11:(4===e||e>3)&&(t=7.5),t}(e),a=function(e,t){let s=36;return 1===e?s=36:2===e?s=17:3===e?s=1===t?12:11:(4===e||e>3)&&(s=7.5),s}(e,s),o=function(e,t){return e<=3?36:t*e+2*(e-1)}(e,n),r=`clipPath${e}`;return{markHeight:a,clipPath:function(e,t,s){let n="";if(3===s)n=kt(0,0,2,t,1)+kt(0,12,2,t+1,1)+kt(0,25,2,t,1);else for(let e=0;e\n \n `}(r,n,e),markTranslateY:function(e,t,s){return 1===s?0:2===s?0===e?0:t+2:3===s?0===e?0:1===e?12:25:(t+2)*e}(s,n,e),trackTranslateY:function(e,t,s,n){return t<=4||e<=1?0:e>=t-2?n-36:(s+4)/2+(e-2)*(s+2)}(s,e,n,o),trackHeight:o,clipPathId:r}}(e,t)),[e,t]);if((0,o.d4)((()=>{if(!s.current)return;const{trackHeight:e,trackTranslateY:t,markHeight:a,markTranslateY:o,clipPathId:r,clipPath:i}=n,c=s.current.firstElementChild;if(null!=s&&s.current){const n=s.current,{style:d}=n;d.height=`${e}px`,d.transform=`translateY(-${t}px)`,d.clipPath=`url("#${r}")`;const l=n.querySelector("svg"),u=n.querySelector("div"),m=n.querySelector("defs");l||c&&(c.innerHTML=` ${i} `),m&&(m.innerHTML=i),u&&(u.style.height=`${a}px`,u.style.transform=`translateY(${o}px)`)}}),[n]),1===e)return o.ZP.createElement("div",{className:"pinned-message-border"},o.ZP.createElement("div",{className:"pinned-message-border-wrapper-1",ref:s}));const{trackHeight:a,trackTranslateY:r,markHeight:i,markTranslateY:c,clipPathId:d}=n;return o.ZP.createElement("div",{className:(0,ne.Z)("pinned-message-border",e>4&&"pinned-message-border-mask")},o.ZP.createElement("div",{className:"pinned-message-border-wrapper",ref:s,style:`clip-path: url("#${d}"); width: 2px;\n height: ${a}px; transform: translateY(-${r}px);`},o.ZP.createElement("span",null),o.ZP.createElement("div",{className:"pinned-message-border-mark",style:`height: ${i}px; transform: translateY(${c}px);`})))})),Tt=(0,o.X$)((({message:e,count:t,index:s,customTitle:n,className:a,onUnpinMessage:r,onClick:i,onAllPinnedClick:c})=>{const l=(0,Ce.Z)(),u=St(e),m=(0,wt.Z)((0,d.Ti)(e,"pictogram")),h=(0,d.MK)(l,e,Boolean(u)),[g,p,f]=(0,ye.Z)(),I=(0,o.I4)((()=>{f(),r&&r(e.id)}),[f,r,e.id]);return o.ZP.createElement("div",{className:(0,ne.Z)("HeaderPinnedMessage-wrapper",a)},t>1&&o.ZP.createElement(Me.Z,{round:!0,size:"smaller",color:"translucent",className:"pin-list-button",ariaLabel:l("EventLogFilterPinnedMessages"),onClick:c},o.ZP.createElement("i",{className:"icon-pin-list"})),r&&o.ZP.createElement(Me.Z,{round:!0,size:"smaller",color:"translucent",ariaLabel:l("UnpinMessageAlertTitle"),className:"unpin-button",onClick:p},o.ZP.createElement("i",{className:"icon-close"})),o.ZP.createElement(Et.Z,{isOpen:g,onClose:f,text:"Would you like to unpin this message?",confirmLabel:"Unpin",confirmHandler:I}),o.ZP.createElement("div",{className:"HeaderPinnedMessage",onClick:i,dir:l.isRtl?"rtl":void 0},o.ZP.createElement(Rt,{count:t,index:s}),u&&function(e,t){const{width:s,height:n}=(0,Pt.W7)();return o.ZP.createElement("img",{src:t||e,width:s,height:n,alt:""})}(u,m),o.ZP.createElement("div",{className:"message-text"},o.ZP.createElement("div",{className:"title",dir:"auto"},n||`${l("PinnedMessage")} ${s>0?"#"+(t-s):""}`),o.ZP.createElement("p",{dir:"auto"},(0,Ct.Z)(h))),o.ZP.createElement(Mt.Z,null)))}));var Nt=s(647),Bt=s(396),At=s(4532),xt=s(3186),Lt=s(663);function Ot(e,t,s="image/png"){const n=e instanceof Blob?URL.createObjectURL(e):e,a=new Image;return new Promise((o=>{a.onload=()=>{Ft(a,a.width*t,a.height*t,s).then((e=>URL.createObjectURL(e))).then(o).finally((()=>{e instanceof Blob&&URL.revokeObjectURL(n)}))},a.src=n}))}async function Ft(e,t,s,n="image/png"){if(!("createImageBitmap"in window))return Ut(e,t,s,void 0,n);try{const a=await window.createImageBitmap(e,{resizeWidth:t,resizeHeight:s,resizeQuality:"high"});if(a.height!==s||a.width!==t)throw new Error("Image bitmap resize not supported!");return await new Promise((e=>{const t=document.createElement("canvas");t.width=a.width,t.height=a.height;const s=t.getContext("bitmaprenderer");s?s.transferFromImageBitmap(a):t.getContext("2d").drawImage(a,0,0),t.toBlob(e,n)}))}catch(a){return Ut(e,t,s,void 0,n)}}function Ut(e,t,s,n=.5,a="image/png"){const o=document.createElement("canvas"),r=o.getContext("2d"),i=document.createElement("canvas"),c=i.getContext("2d");if(o.width=t,o.height=s,e.width*n>t){const s=1/n;let a={width:Math.floor(e.width*n),height:Math.floor(e.height*n)};for(i.width=a.width,i.height=a.height,c.drawImage(e,0,0,a.width,a.height);a.width*n>t;)a={width:Math.floor(a.width*n),height:Math.floor(a.height*n)},c.drawImage(i,0,0,a.width*s,a.height*s,0,0,a.width,a.height);r.drawImage(i,0,0,a.width,a.height,0,0,o.width,o.height)}else r.drawImage(e,0,0,o.width,o.height);return new Promise((e=>{o.toBlob(e,a)}))}var $t=s(4524);const Dt={width:200,height:200},qt=115,Qt=(e,t,s)=>{const{audio:n,voice:a}=(0,d.qp)(e),r=n?n.title||n.fileName:a?"Voice message":"",i=n&&n.performer||t&&(0,d.OU)(Lt.i0,t),c=s&&(0,d.U)(Lt.i0,s)||"Telegram",l=n&&(0,d.MR)(n)&&(0,d.Ti)(e,"pictogram"),u=t&&(0,d.RT)(t,"big"),m=n&&l||a&&u,h=(0,wt.Z)(m),g=(0,o.Ye)((()=>function(e,t,s){if(!s)return Dt;if(e){if(!e.thumbnailSizes||0===e.thumbnailSizes.length)return;return e.thumbnailSizes.find((e=>"m"===e.type))||e.thumbnailSizes[0]}return t?Pt.vY:void 0}(n,a,h)),[n,h,a]),{result:p}=((e,t,s)=>{const[n,a]=(0,o.eJ)(!1),[r,i]=(0,o.eJ)(),[c,d]=(0,o.eJ)(s);return(0,o.d4)((()=>{a(!0);let e=!1;return function(e,t){if(!e)return Promise.resolve($t);if(!t)return function(e,t,s,n="image/png"){const a=e instanceof Blob?URL.createObjectURL(e):e,o=new Image;return new Promise((r=>{o.onload=()=>{Ft(o,t,s,n).then((e=>URL.createObjectURL(e))).then(r).finally((()=>{e instanceof Blob&&URL.revokeObjectURL(a)}))},o.src=a}))}(e,qt,qt);const s=Math.min(t.width,t.height);return s{e||(a(!1),d(t))}),(t=>{e||(a(!1),i(t))})),()=>{e=!0}}),t),{isLoading:n,error:r,result:c}})(0,[h,g],$t);return(0,o.Ye)((()=>(0,At.Of)({title:r,artist:i,album:c,artwork:[{src:p}]})),[c,i,r,p])};var Gt=s(8051);const jt=(0,n.c$)(((e,{message:t})=>{const s=(0,i.Ur)(e,t),n=(0,i.Z1)(e,t.chatId),{volume:a,playbackRate:o,isMuted:r}=e.audioPlayer;return{sender:s,chat:n,volume:a,playbackRate:o,isMuted:r}}))((({message:e,className:t,noUi:s,sender:a,chat:r,volume:i,playbackRate:c,isMuted:l})=>{const{setAudioPlayerVolume:u,setAudioPlayerPlaybackRate:m,setAudioPlayerMuted:g,focusMessage:p,closeAudioPlayer:f}=(0,n.uC)(),I=(0,Ce.Z)(),{audio:v,voice:y,video:Z}=(0,d.qp)(e),P=Boolean(y||Z),C=a?(0,d.OU)(I,a):void 0,w=Nt.UV((0,d.Ti)(e,"inline")),b=Qt(e,a,r),{playPause:S,stop:E,isPlaying:M,requestNextTrack:k,requestPreviousTrack:R,isFirst:T,isLast:N,setVolume:B,toggleMuted:A,setPlaybackRate:x}=(0,xt.Z)((0,Bt.An)(e),(0,d.XV)(e),P?"voice":"audio",w,void 0,b,void 0,!0,void 0,void 0,(0,d.CI)(e),!0),L=P&&M;(0,o.d4)((()=>{if(L)return ie.Z.disableRefresh(),()=>{ie.Z.enableRefresh()}}),[L]);const O=(0,o.I4)((()=>{p({chatId:e.chatId,messageId:e.id})}),[p,e.chatId,e.id]),F=(0,o.I4)((()=>{M&&S(),f(),(0,At.Ay)(),E()}),[f,M,S,E]),U=(0,o.I4)((e=>{u({volume:e/100}),g({isMuted:!1}),B(e/100)}),[g,u,B]),$=(0,o.I4)((()=>{h.$b&&!h.cj||(A(),g({isMuted:!l}))}),[l,g,A]),D=(0,o.I4)((()=>{1===c?(x(1.8),m({playbackRate:1.8})):(x(1),m({playbackRate:1}))}),[c,m,x]),q=(0,o.Ye)((()=>0===i||l?"icon-muted":i<.3?"icon-volume-1":i<.6?"icon-volume-2":"icon-volume-3"),[i,l]);if(!s)return o.ZP.createElement("div",{className:(0,ne.Z)("AudioPlayer",t),dir:I.isRtl?"rtl":void 0},o.ZP.createElement(Me.Z,{round:!0,ripple:!h.wB,color:"translucent",size:"smaller",className:"player-button",disabled:T(),onClick:R,ariaLabel:"Previous track"},o.ZP.createElement("i",{className:"icon-skip-previous"})),o.ZP.createElement(Me.Z,{round:!0,ripple:!h.wB,color:"translucent",size:"smaller",className:(0,ne.Z)("toggle-play","player-button",M?"pause":"play"),onClick:S,ariaLabel:M?"Pause audio":"Play audio"},o.ZP.createElement("i",{className:"icon-play"}),o.ZP.createElement("i",{className:"icon-pause"})),o.ZP.createElement(Me.Z,{round:!0,ripple:!h.wB,color:"translucent",size:"smaller",className:"player-button",disabled:N(),onClick:k,ariaLabel:"Next track"},o.ZP.createElement("i",{className:"icon-skip-next"})),o.ZP.createElement("div",{className:"AudioPlayer-content",onClick:O},v?function(e){const{title:t,performer:s,fileName:n}=e;return o.ZP.createElement(o.ZP.Fragment,null,o.ZP.createElement("div",{className:"title",dir:"auto"},(0,Ct.Z)(t||n)),s&&o.ZP.createElement("div",{className:"subtitle",dir:"auto"},(0,Ct.Z)(s)))}(v):function(e,t){return o.ZP.createElement(o.ZP.Fragment,null,o.ZP.createElement("div",{className:"title",dir:"auto"},t&&(0,Ct.Z)(t)),o.ZP.createElement("div",{className:"subtitle",dir:"auto"},e))}(I("AttachAudio"),C),o.ZP.createElement(Mt.Z,null)),o.ZP.createElement(Me.Z,{round:!0,className:"player-button volume-button",color:"translucent",size:"smaller",ariaLabel:"Volume",withClickPropagation:!0},o.ZP.createElement("i",{className:q,onClick:$}),!h.cj&&o.ZP.createElement(o.ZP.Fragment,null,o.ZP.createElement("div",{className:"volume-slider-spacer"}),o.ZP.createElement("div",{className:"volume-slider"},o.ZP.createElement(Gt.Z,{value:l?0:100*i,onChange:U})))),P&&o.ZP.createElement(Me.Z,{round:!0,className:(0,ne.Z)("playback-button",1!==c&&"applied"),color:"translucent",size:"smaller",ariaLabel:"Playback Rate",ripple:!h.wB,onClick:D},o.ZP.createElement("span",{className:"playback-button-inner"},"2Х")),o.ZP.createElement(Me.Z,{round:!0,className:"player-close",color:"translucent",size:"smaller",onClick:F,ariaLabel:"Close player"},o.ZP.createElement("i",{className:"icon-close"})))}));var Ht=s(2607),_t=s(172);const zt=(0,o.X$)((0,n.c$)(((e,{chatId:t})=>{const s=(0,i.Z1)(e,t),n=(0,Ht.Bj)(e,t);return{groupCall:n,usersById:e.users.byId,chatsById:e.chats.byId,activeGroupCallId:e.groupCalls.activeGroupCallId,isActive:(n?n.participantsCount>0&&n.isLoaded:s&&s.isCallNotEmpty&&s.isCallActive)&&e.groupCalls.activeGroupCallId!==(null==n?void 0:n.id)}}))((({chatId:e,isActive:t,groupCall:s,hasPinnedOffset:a,usersById:r,chatsById:i})=>{const{joinGroupCall:c,subscribeToGroupCallUpdates:d}=(0,n.uC)(),l=(0,Ce.Z)(),u=(0,o.I4)((()=>{c({chatId:e})}),[c,e]),m=null==s?void 0:s.participants,h=(0,o.Ye)((()=>m?Object.values(m).filter(((e,t)=>t<3)).map((({id:e,isUser:t})=>{if(t){if(!r[e])return;return{user:r[e]}}if(i[e])return{chat:i[e]}})).filter(Boolean):[]),[i,m,r]);if((0,o.d4)((()=>{if(null!=s&&s.id&&(t||!s.isLoaded))return d({id:s.id,subscribed:!0}),()=>{d({id:s.id,subscribed:!1})}}),[null==s?void 0:s.id,null==s?void 0:s.isLoaded,t,d]),s)return o.ZP.createElement("div",{className:(0,ne.Z)("GroupCallTopPane",a&&"has-pinned-offset",!t&&"is-hidden"),onClick:u},o.ZP.createElement("div",{className:"info"},o.ZP.createElement("span",{className:"title"},l("VoipGroupVoiceChat")),o.ZP.createElement("span",{className:"participants"},l("Participants",s.participantsCount||0,"i"))),o.ZP.createElement("div",{className:"avatars"},h.map((e=>{if(e)return e.user?o.ZP.createElement(_t.Z,{key:e.user.id,user:e.user}):o.ZP.createElement(_t.Z,{key:e.chat.id,chat:e.chat})}))),o.ZP.createElement(Me.Z,{round:!0,className:"join"},l("VoipChatJoin")))}))),Vt=(0,o.X$)((0,n.c$)(((e,{chatId:t,threadId:s,messageListType:n})=>{const{isLeftColumnShown:a,lastSyncTime:o,shouldSkipHistoryAnimations:r}=e,{byId:c}=e.chats,d=(0,i.Z1)(e,t),{typingStatus:l}=d||{},{chatId:m,messageId:h}=e.audioPlayer,g=m&&h?(0,i.hj)(e,m,h):void 0;let p;if("pinned"===n){const s=(0,i.KB)(e,t);p=null==s?void 0:s.length}else if("scheduled"===n){const s=(0,i.qy)(e,t);p=null==s?void 0:s.length}else if("thread"===n&&s!==u._f){const n=(0,i.tZ)(e,t,s);p=(null==n?void 0:n.messagesCount)||0}const f={typingStatus:l,isLeftColumnShown:a,isRightColumnShown:(0,i.Jf)(e),isSelectModeActive:(0,i.CA)(e),audioMessage:g,chat:d,chatsById:c,messagesCount:p,isChatWithSelf:(0,i.FM)(e,t),isChatWithBot:d&&(0,i.xo)(e,d),lastSyncTime:o,shouldSkipHistoryAnimations:r,currentTransitionKey:Math.max(0,e.messages.messageLists.length-1),connectionState:e.connectionState},I=(0,i.Zw)(e,t);if("thread"!==n||!I)return f;if(Object.assign(f,{messagesById:I}),s!==u._f){const n=(0,i.qS)(e,t,s),a=n?(0,i.hj)(e,t,n):void 0,o=a?(0,i.cv)(e,a):void 0;return{...f,pinnedMessageIds:n,canUnpin:!1,topMessageSender:o}}const v=(0,i.KB)(e,t);if(null!=v&&v.length){const t=I[v[0]],{canUnpin:n}=t&&(0,i._k)(e,t,s)||{};return{...f,pinnedMessageIds:v,canUnpin:n}}return f}))((({chatId:e,threadId:t,messageListType:s,isReady:r,pinnedMessageIds:c,messagesById:l,canUnpin:m,topMessageSender:g,typingStatus:p,isSelectModeActive:f,isLeftColumnShown:I,isRightColumnShown:v,audioMessage:y,chat:Z,chatsById:P,messagesCount:C,isChatWithSelf:w,isChatWithBot:b,lastSyncTime:S,shouldSkipHistoryAnimations:E,currentTransitionKey:M,connectionState:k})=>{const{openChatWithInfo:R,pinMessage:T,focusMessage:N,openChat:B,openPreviousChat:A,loadPinnedMessages:x,toggleLeftColumn:L,exitMessageSelectMode:O}=(0,n.uC)(),F=(0,Ce.Z)(),U=(0,o.sO)(!0),[$,D]=(0,o.eJ)(0),q=Array.isArray(c)?c[$]:c,Q=l&&q?l[q]:void 0,G=Array.isArray(c)?c.length:c?1:void 0,j=Z&&(0,d.U)(F,Z).length,H=g?(0,d.OU)(F,g):void 0;(0,o.d4)((()=>{t===u._f&&S&&r&&x({chatId:e})}),[e,x,S,t,r]),(0,o.d4)((()=>{D(0)}),[c]),(0,gt.Z)(e,q,Q);const{width:_}=ct(),z=_<=a.ks,V=h.p7&&I,K=(0,o.sO)(null),Y=(0,o.sO)(!0),W=(0,o.I4)((()=>{R({id:e})}),[R,e]),X=(0,o.I4)((t=>{T({chatId:e,messageId:t,isUnpin:!0})}),[T,e]),J=(0,o.I4)((()=>{if(Q){N({chatId:Q.chatId,threadId:t,messageId:Q.id});const e=(0,ht.Z)(G||1,$+1);D(e)}}),[Q,N,t,G,$]),ee=(0,o.I4)((()=>{B({id:e,threadId:u._f,type:"pinned"})}),[B,e]),te=(0,o.I4)((()=>{setTimeout((()=>{U.current=!0}),450)}),[]),se=(0,o.I4)((e=>{if(U.current){if(U.current=!1,h.wB){const e=document.getElementById(a.R2);e&&e.blur()}if(f)return O(),void te();if(t===u._f&&"thread"===s&&0===M)return h.wB||V?(e.stopPropagation(),B({id:void 0})):L(),void te();A(),te()}}),[t,s,M,f,A,V,B,L,O,te]),ae=(0,o.Ye)((()=>{if(z&&P)return(0,i.A1)((0,n.Rd)())||void 0}),[z,P]),oe=_>=a.ks&&_a.l3&&_30),re=oe||_>a._m&&_{const e=K.current;if(e)return re&&Ie?void(v||oe?(Y.current&&(e.classList.add("tools-stacked","animated"),Y.current=!1),setTimeout((()=>{e.classList.remove("animated")}),350)):(e.classList.remove("tools-stacked"),Y.current=!0)):(e.classList.remove("tools-stacked","animated"),void(Y.current=!0))}),[re,Ie,oe,v]);const ve=(!Pe()||"connectionStateConnecting"===k)&&(h.wB||h.p7&&!V);function ye(){return ve?o.ZP.createElement(o.ZP.Fragment,null,we(),o.ZP.createElement("h3",null,F("WaitingForNetwork"))):"thread"===s&&t===u._f?o.ZP.createElement(o.ZP.Fragment,null,(z||M>0)&&we(V,!0),o.ZP.createElement("div",{className:"chat-info-wrapper",onClick:W},(0,d.YC)(e)?o.ZP.createElement(It.Z,{userId:e,typingStatus:p,withFullInfo:b,withMediaViewer:!0,withUpdatingStatus:!0,noRtl:!0}):o.ZP.createElement(vt.Z,{chatId:e,typingStatus:p,noRtl:!0,withMediaViewer:!0,withFullInfo:!0,withUpdatingStatus:!0}))):"thread"===s?o.ZP.createElement(o.ZP.Fragment,null,we(),o.ZP.createElement("h3",null,F("CommentsCount",C,"i"))):"pinned"===s?o.ZP.createElement(o.ZP.Fragment,null,we(),o.ZP.createElement("h3",null,F("PinnedMessagesCount",C,"i"))):"scheduled"===s?o.ZP.createElement(o.ZP.Fragment,null,we(),o.ZP.createElement("h3",null,w?F("Reminders"):F("messages",C,"i"))):void 0}function we(e=!1,t=!1){return o.ZP.createElement("div",{className:"back-button"},o.ZP.createElement(Me.Z,{round:!0,size:"smaller",color:"translucent",onClick:se,ariaLabel:F(e?"Close":"Back")},o.ZP.createElement("div",{className:(0,ne.Z)("animated-close-icon",!e&&"state-back")})),t&&ae&&o.ZP.createElement("div",{className:"unread-count active"},(0,ft.bi)(ae)))}const be=Boolean(ie&&le);return o.ZP.createElement("div",{className:"MiddleHeader",ref:K},o.ZP.createElement(Ze.Z,{name:E?"none":"slide-fade",activeKey:ve?1/0:M},ye),o.ZP.createElement(zt,{hasPinnedOffset:ue&&!!he||ie&&!!le,chatId:e}),ue&&he&&o.ZP.createElement(Tt,{key:e,message:he,count:ge||0,index:$,customTitle:fe,className:(0,ne.Z)(me,be&&"full-width"),onUnpinMessage:pe?X:void 0,onClick:J,onAllPinnedClick:ee}),o.ZP.createElement("div",{className:"header-tools"},be&&o.ZP.createElement(jt,{key:(0,d.Tp)(le),message:le,className:de}),o.ZP.createElement(Zt,{chatId:e,threadId:t,messageListType:s,canExpandActions:!be})))})));var Kt=s(2645),Yt=s(274);function Wt(e){return"albumId"in e}function Xt(e,t){let s,n=[],a={originalDate:e[0].date,datetime:Number((0,N.$Y)(1e3*e[0].date)),senderGroups:[n]};const o=[a];return e.forEach(((r,i)=>{r.isInAlbum?s?(s.messages.push(r),r.content.text&&(s.mainMessage=r)):s={albumId:r.groupedId,messages:[r],mainMessage:r}:n.push(r);const c=e[i+1];if(!s||c&&c.groupedId&&c.groupedId===s.albumId||(n.push(s),s=void 0),c){const e=Number((0,N.$Y)(1e3*c.date));a.datetime!==e?(a={originalDate:c.date,datetime:e,senderGroups:[]},o.push(a),n=[],a.senderGroups.push(n)):(c.id===t||r.senderId!==c.senderId||r.isOutgoing!==c.isOutgoing||(0,d.Lo)(r)||(0,d.Lo)(c)||r.forwardInfo&&c.forwardInfo&&(r.forwardInfo.senderUserId!==c.forwardInfo.senderUserId||r.forwardInfo.fromChatId!==c.forwardInfo.fromChatId||r.forwardInfo.hiddenUserName!==c.forwardInfo.hiddenUserName)||r.inlineButtons||c.inlineButtons||c.date-r.date>600)&&(n=[],a.senderGroups.push(n))}})),o}var Jt=s(386),es=s(2202);var ts=s(7675),ss=s(539),ns=s(3657);const as=h.wZ?1e3:350,os=h.wB?300:500;var rs=s(7240),is=s(935);function cs(e){return"number"==typeof e}function ds(e,t){return e?t?238:175:t?238:100}function ls(e,t){const s=(0,d.B4)(e),n=(0,d.MF)(e),a=(0,d.O$)(e)||(0,d.F$)(e),o=(0,d.b7)(e),r=Boolean((0,d.F$)(e)),{width:i,height:c}=a?(0,Pt.Eh)(a,s,n,r,t):(0,Pt.GC)(o,s,n,t),l=ds(Boolean((0,d.UD)(e)));let u=1;ie+t),t)}function ms(e,t,s){return es?s:e}function hs(e){const t={width:0,height:0};return e.forEach((({dimensions:e,sides:s})=>{2&s&&(t.width=e.width+e.x),4&s&&(t.height=e.height+e.y)})),t}function gs(e,t,s,n){const a=n.messages.map((e=>{const t=ls(e);return t.width/t.height})),o=function(e){return e.map((e=>e>1.2?"w":e<.8?"n":"q")).join("")}(a),r=function(e){return e.reduce(((e,t)=>t+e),1)/e.length}(a),i=a.length,c=a.some((e=>e>2)),d=(0,Pt.kc)(e,t,!1,s)-(t?2.5:0)*Pt.Gw;let l;const u={ratios:a,proportions:o,averageRatio:r,maxWidth:d,minWidth:100,maxHeight:d,spacing:2};return l=i>=5||c?function({ratios:e,averageRatio:t,maxWidth:s,minWidth:n,spacing:a,maxHeight:o=4*s/3}){const r=function(e,t){return e.map((e=>t>1.1?ms(e,1,2.75):ms(e,.6667,1)))}(e,t),i=e.length,c=new Array(i),d=[],l=e=>{const t=[];let n=0;e.forEach((e=>{t.push(((e,t)=>{const n=us(r.slice(e,e+t),0);return(s-(t-1)*a)/n})(n,e)),n+=e})),d.push({lineCounts:e,heights:t})};for(let e=1;e!==i;++e){const t=i-e;e<=3&&t<=3&&l([e,t])}for(let e=1;e!==i-1;++e)for(let s=1;s!==i-e;++s){const n=i-e-s;e<=3&&s<=(t<.85?4:3)&&n<=3&&l([e,s,n])}for(let e=1;e!==i-1;++e)for(let t=1;t!==i-e;++t)for(let s=1;s!==i-e-t;++s){const n=i-e-t-s;e<=3&&t<=3&&s<=3&&n<=4&&l([e,t,s,n])}let u,m=0;for(let e=0;e{for(let e=1;e!==r;++e)if(s[e-1]>s[e])return 1.5;return 1})(),h=Math.abs(i-o)*c*l;(!u||h1.4&&t[1]-t[0]<.2?function(e){const{ratios:t,maxWidth:s,spacing:n,maxHeight:a}=e,o=Math.round(Math.min(s/t[0],Math.min(s/t[1],(a-n)/2)));return[{dimensions:{x:0,y:0,width:s,height:o},sides:11},{dimensions:{x:0,y:o+n,width:s,height:o},sides:14}]}(e):"ww"===s||"qq"===s?function(e){const{ratios:t,maxWidth:s,spacing:n,maxHeight:a}=e,o=(s-n)/2,r=Math.round(Math.min(o/t[0],Math.min(o/t[1],a)));return[{dimensions:{x:0,y:0,width:o,height:r},sides:13},{dimensions:{x:o+n,y:0,width:o,height:r},sides:7}]}(e):function(e){const{ratios:t,minWidth:s,maxWidth:n,spacing:a,maxHeight:o}=e,r=Math.round(1.5*s),i=Math.min(Math.round(Math.max(.4*(n-a),(n-a)/t[0]/(1/t[0]+1/t[1]))),n-a-r),c=n-i-a,d=Math.min(o,Math.round(Math.min(c/t[0],i/t[1])));return[{dimensions:{x:0,y:0,width:c,height:d},sides:13},{dimensions:{x:c+a,y:0,width:i,height:d},sides:7}]}(e)}(u):3===i?function(e){const{proportions:t}=e;return"n"===t[0]?function(e){const{maxHeight:t,spacing:s,ratios:n,maxWidth:a,minWidth:o}=e,r=t,i=Math.round(Math.min((t-s)/2,n[1]*(a-s)/(n[2]+n[1]))),c=r-i-s,d=Math.max(o,Math.round(Math.min((a-s)/2,Math.min(i*n[2],c*n[1])))),l=Math.min(Math.round(r*n[0]),a-s-d);return[{dimensions:{x:0,y:0,width:l,height:r},sides:13},{dimensions:{x:l+s,y:0,width:d,height:c},sides:3},{dimensions:{x:l+s,y:c+s,width:d,height:i},sides:6}]}(e):function(e){const{maxWidth:t,ratios:s,maxHeight:n,spacing:a}=e,o=t,r=Math.round(Math.min(o/s[0],.66*(n-a))),i=(t-a)/2,c=Math.min(n-r-a,Math.round(Math.min(i/s[1],i/s[2])));return[{dimensions:{x:0,y:0,width:o,height:r},sides:11},{dimensions:{x:0,y:r+a,width:i,height:c},sides:12},{dimensions:{x:i+a,y:r+a,width:o-i-a,height:c},sides:6}]}(e)}(u):function(e){const{proportions:t}=e;return"w"===t[0]?function({maxWidth:e,ratios:t,spacing:s,maxHeight:n,minWidth:a}){const o=e,r=Math.round(Math.min(o/t[0],.66*(n-s))),i=Math.round((e-2*s)/(t[1]+t[2]+t[3])),c=Math.max(a,Math.round(Math.min(.4*(e-2*s),i*t[1]))),d=Math.round(Math.max(Math.max(a,.33*(e-2*s)),i*t[3])),l=o-c-d-2*s,u=Math.min(n-r-s,i);return[{dimensions:{x:0,y:0,width:o,height:r},sides:11},{dimensions:{x:0,y:r+s,width:c,height:u},sides:12},{dimensions:{x:c+s,y:r+s,width:l,height:u},sides:4},{dimensions:{x:c+s+l+s,y:r+s,width:d,height:u},sides:6}]}(e):function({maxHeight:e,ratios:t,maxWidth:s,spacing:n,minWidth:a}){const o=e,r=Math.round(Math.min(o*t[0],.6*(s-n))),i=Math.round((e-2*n)/(1/t[1]+1/t[2]+1/t[3])),c=Math.round(i/t[1]),d=Math.round(i/t[2]),l=o-c-d-2*n,u=Math.max(a,Math.min(s-r-n,i));return[{dimensions:{x:0,y:0,width:r,height:o},sides:13},{dimensions:{x:r+n,y:0,width:u,height:c},sides:3},{dimensions:{x:r+n,y:c+n,width:u,height:d},sides:2},{dimensions:{x:r+n,y:c+d+2*n,width:u,height:l},sides:6}]}(e)}(u),{layout:l,containerStyle:hs(l)}}let ps;function fs(e){return ps||(ps=document.createElement("span"),ps.style.font=h.cj?'400 12px system-ui, -apple-system, BlinkMacSystemFont, "Roboto", "Apple Color Emoji", "Helvetica Neue", sans-serif':'400 12px "Roboto", -apple-system, "Apple Color Emoji", BlinkMacSystemFont, "Helvetica Neue", sans-serif',ps.style.whiteSpace="nowrap",ps.style.position="absolute",ps.style.left="-999px",ps.style.opacity=".01",document.body.appendChild(ps)),ps.innerHTML=e,ps.offsetWidth}function Is(e,t,s,n,a,r){(0,o.bt)((()=>{if(s&&e.current){const t=e.current.closest(".MessageList");(0,ss.Z)(t,e.current,a?"end":"centerOrTop",20,void 0!==n?1e3:void 0,n,void 0,r)}}),[e,t,s,n,a,r])}var vs=s(8005);const ys=(0,o.X$)((e=>{const{isOpen:t}=e,s=(0,qe.Z)(De.gl.Extra,"ContextMenuContainer",!t);return s?o.ZP.createElement(s,e):void 0})),Zs=(0,o.X$)((0,n.c$)(((e,{message:t})=>{const{byId:s}=e.users,n=t.senderId,{targetUserIds:a,targetChatId:o}=t.content.action||{},r=t.replyToMessageId,c=r?(0,i.hj)(e,t.chatId,r):void 0,l=(0,i._X)(e,t),{direction:u,noHighlight:m}=l&&e.focusedMessage||{},h=(0,i.Z1)(e,t.chatId);return{usersById:s,sender:h&&((0,d.eA)(h)||n===t.chatId)?h:n?(0,i.dy)(e,n):void 0,targetChatId:o,targetUserIds:a,targetMessage:c,isFocused:l,...l&&{focusDirection:u,noFocusHighlight:m}}}))((({message:e,observeIntersection:t,isEmbedded:s,appearanceOrder:n=0,isLastInList:a,usersById:r,sender:i,targetUserIds:c,targetMessage:d,targetChatId:l,isFocused:u,focusDirection:m,noFocusHighlight:h})=>{const g=(0,o.sO)(null);(0,ns._N)(g,t),(0,gt.Z)(e.chatId,e.replyToMessageId,d),Is(g,e.chatId,u,m,h);const p=(0,Ce.Z)(),f=n<=0,[I,v]=(0,ye.Z)(f);(0,o.d4)((()=>{f||setTimeout(v,10*n)}),[n,v,f]);const{transitionClassNames:y}=(0,ce.Z)(I,void 0,f,!1),Z=(0,o.Ye)((()=>c?c.map((e=>null==r?void 0:r[e])).filter(Boolean):void 0),[c,r]),P=(0,vs.D)(p,e,i,Z,d,l,s?{isEmbedded:!0,asPlain:!0}:void 0),{isContextMenuOpen:C,contextMenuPosition:w,handleBeforeContextMenu:b,handleContextMenu:S,handleContextMenuClose:E,handleContextMenuHide:M}=(0,rs.Z)(g),k=void 0!==w;if(s)return o.ZP.createElement("span",{className:"embedded-action-message"},(0,Ct.Z)(P));const R=(0,ne.Z)("ActionMessage message-list-item",u&&!h&&"focused",k&&"has-menu-open",a&&"last-in-list",y);return o.ZP.createElement("div",{ref:g,id:`message${e.id}`,className:R,"data-message-id":e.id,onMouseDown:e=>{(0,Jt.q)(e),b(e)},onContextMenu:S},o.ZP.createElement("span",null,P),w&&o.ZP.createElement(ys,{isOpen:C,anchor:w,message:e,messageListType:"thread",onClose:E,onCloseAnimationEnd:M}))}))),Ps=({className:e,message:t,sender:s,title:n,customText:a,isProtected:r,observeIntersection:i,onClick:c})=>{const l=(0,o.sO)(null),u=(0,ns.Op)(l,i),m=(0,wt.Z)(t&&(0,d.Ti)(t,"pictogram"),!u),h=t&&`sticker-reply-thumb${t.id}`,g=St(t),p=Boolean(t&&(0,d.Y5)(t)),f=(0,Ce.Z)(),I=s&&(0,d.OU)(f,s);return o.ZP.createElement("div",{ref:l,className:(0,ne.Z)("EmbeddedMessage",e),onClick:t?c:void 0},g&&function(e,t,s,n,a){const{width:r,height:i}=(0,Pt.W7)();return o.ZP.createElement(o.ZP.Fragment,null,o.ZP.createElement("img",{id:e,src:s||t,width:r,height:i,alt:"",className:n?"round":"",draggable:!a}),a&&o.ZP.createElement("span",{className:"protector"}))}(h,g,m,p,r),o.ZP.createElement("div",{className:"message-text"},o.ZP.createElement("p",{dir:"auto"},t?(0,d.Lo)(t)?o.ZP.createElement(Zs,{message:t,isEmbedded:!0}):(0,Ct.Z)((0,d.MK)(f,t,Boolean(g))):a||" "),o.ZP.createElement("div",{className:"message-title",dir:"auto"},(0,Ct.Z)(I||n||" "))))};var Cs=s(2535),ws=s(4752),bs=s(8018);const Ss=(0,o.X$)((({message:e,outgoingStatus:t,signature:s,onClick:n})=>{const a=(0,Ce.Z)(),[r,i]=(0,ye.Z)(),c=(0,o.Ye)((()=>{if(!r)return;const t=(0,N.SA)(1e3*e.date,a.code),s=e.isEdited&&(0,N.SA)(1e3*e.editDate,a.code),n=e.forwardInfo&&(0,N.SA)(1e3*e.forwardInfo.date,a.code);let o=t;return s&&(o+="\n",o+=a("lng_edited_date").replace("{date}",s)),n&&(o+="\n",o+=a("lng_forwarded_date").replace("{date}",n)),o}),[r,a,e]);return o.ZP.createElement("span",{className:"MessageMeta",dir:a.isRtl?"rtl":"ltr",onClick:n},Boolean(e.views)&&o.ZP.createElement(o.ZP.Fragment,null,o.ZP.createElement("span",{className:"message-views"},(0,ft.bi)(e.views)),o.ZP.createElement("i",{className:"icon-channelviews"})),s&&o.ZP.createElement("span",{className:"message-signature"},(0,Ct.Z)(s)),o.ZP.createElement("span",{className:"message-time",title:c,onMouseEnter:i},e.isEdited&&`${a("EditedMessage")} `,(0,N.mr)(1e3*e.date,a)),t&&o.ZP.createElement(bs.Z,{status:t}))}));var Es=s(692),Ms=s(7799),ks=s(4851);const Rs=({message:e,observeIntersection:t,observeIntersectionForPlaying:s,shouldLoop:n,lastSyncTime:r})=>{const i=(0,o.sO)(null),[c,l,u]=(0,ye.Z)(),m=e.content.sticker,{isAnimated:h,stickerSetId:g}=m,p=g===a.n,f=(0,ns.Op)(i,t),I=(0,ns.Op)(i,s),v=m.isPreloadedGlobally?`sticker${m.id}`:(0,d.Ti)(e,"inline"),y=St(e),Z=(0,wt.Z)(v,!f,(0,d.kG)(e,"inline",!0),r),P=Boolean(Z),[C,w]=(0,ye.Z)(P),b=h?C:P,S=(0,Es.Z)(b),{width:E,height:M}=(0,Pt.Wr)(m),k=(0,ne.Z)("thumbnail",!y&&"empty"),R=(0,ne.Z)("Sticker media-inner",p&&"inactive");return o.ZP.createElement("div",{ref:i,className:R,onClick:p?void 0:l},!b&&o.ZP.createElement("img",{id:`sticker-thumb-${e.id}`,src:y,width:E,height:M,alt:"",className:k}),!h&&o.ZP.createElement("img",{id:`sticker-${e.id}`,src:Z,width:E,height:M,alt:"",className:(0,ne.Z)("full-media",S)}),h&&P&&o.ZP.createElement(Ms.Z,{key:v,className:(0,ne.Z)("full-media",S),id:v,animationData:Z,size:E,play:I,noLoop:!n,onLoad:w}),o.ZP.createElement(ks.Z,{isOpen:c,fromSticker:m,onClose:u}))};var Ts=s(7854),Ns=s(2566),Bs=s(5866);function As(e,t){return(0,Bs.Z)((0,d.DH)(e),Boolean(t),h.wB&&!h.vX)}const xs={dark:{outgoing:"rgb(135,116,225)",incoming:"rgb(33,33,33)"},light:{outgoing:"rgb(238,255,222)",incoming:"rgb(255,255,255)"}};var Ls=s(9196);const Os=({id:e,message:t,observeIntersection:s,noAvatars:n,canAutoLoad:a,isInSelectMode:r,isSelected:i,uploadProgress:c,size:l="inline",dimensions:u,nonInteractive:m,shouldAffectAppendix:h,isDownloading:g,isProtected:p,theme:f,onClick:I,onCancelUpload:v})=>{const y=(0,o.sO)(null),Z=((0,d.O$)(t)||(0,d.F$)(t)).blobUrl,P=(0,ns.Op)(y,s),[C,w]=(0,o.eJ)(a),b=C&&P,{mediaData:S,loadProgress:E}=(0,Ns.Z)((0,d.Ti)(t,l),!b),M=Z||S,k=As(t,M),{loadProgress:R}=(0,Ns.Z)((0,d.Ti)(t,"download"),!g),{isUploading:T,isTransferring:N,transferProgress:B}=(0,d.Sc)(t,c||(g?R:E),b&&!M),A=!1===(0,lt.Z)(C),x=(0,Es.Z)(M),{shouldRender:L,transitionClassNames:O}=(0,ce.Z)(N,void 0,A,"slow"),{shouldRender:F,transitionClassNames:U}=(0,ce.Z)(!M&&!C),$=(0,o.I4)((()=>{T?v&&v(t):M?I&&I(t.id):w((e=>!e))}),[M,T,t,v,I]),D=(0,d.B4)(t);(0,o.bt)((()=>{if(!h)return;const e=y.current.closest(".message-content");M?function(e,t,s,n,a){return n?Promise.resolve(xs[a||"light"][t?"outgoing":"incoming"]):async function(e,t){const s=new Image;s.src=e,s.width||await new Promise((e=>{s.onload=e}));const n=document.createElement("canvas"),a=n.getContext("2d");n.width=s.width,n.height=s.height,a.drawImage(s,0,0,s.width,s.height);const o=t?s.width-1:0,r=s.height-1;return`rgba(${Array.from(a.getImageData(o,r,1,1).data).join(",")})`}(e,t)}(M,D,0,i,f).then((t=>{e.style.setProperty("--appendix-bg",t),e.setAttribute("data-has-custom-appendix","")})):e.classList.add("has-appendix-thumb")}),[M,D,h,r,i,f]);const{width:q,height:Q,isSmall:G}=u||ls(t,n),j=(0,ne.Z)("media-inner",!T&&!m&&"interactive",G&&"small-image",q===Q&&"square-image"),H=u?`width: ${q}px; height: ${Q}px; left: ${u.x}px; top: ${u.y}px;`:"";return o.ZP.createElement("div",{id:e,ref:y,className:j,style:H,onClick:T?void 0:$},o.ZP.createElement("canvas",{ref:k,className:"thumbnail",style:`width: ${q}px; height: ${Q}px`}),o.ZP.createElement("img",{src:M,className:`full-media ${x}`,width:q,height:Q,alt:"",draggable:!p}),p&&o.ZP.createElement("span",{className:"protector"}),L&&!F&&o.ZP.createElement("div",{className:`media-loading ${O}`},o.ZP.createElement(Ls.Z,{progress:B,onClick:T?$:void 0})),F&&o.ZP.createElement("i",{className:(0,ne.Z)("icon-download",U)}),N&&o.ZP.createElement("span",{className:"message-transfer-progress"},Math.round(100*B),"%"))};var Fs=s(2019),Us=s(6898),$s=s(4753);function Ds(e,t){var s;const n=(0,o.sO)(null===(s=e.current)||void 0===s?void 0:s.paused),a=(0,o.sO)();a.current=t;const r=(0,o.I4)((()=>{e.current&&(n.current=!e.current.paused,n.current&&e.current.pause())}),[e]),i=(0,o.I4)((()=>{e.current&&n.current&&a.current&&document.body.contains(e.current)&&(0,$s.Z)(e.current)}),[e]),c=(0,o.I4)((()=>{(0,C.T2)(i)}),[i]);(0,de.Z)(r,c),(0,se.ZP)(r,i)}function qs(){return(qs=Object.assign||function(e){for(var t=1;t{var I;const v=(0,o.sO)(null),y=(0,o.sO)(null),Z=(0,d.b7)(t)||(0,d.Cg)(t),P=Z.blobUrl,C=(0,ns.Op)(v,s),[w,b]=(0,o.eJ)(r),S=Boolean(w&&C&&l),[E,M]=(0,o.eJ)(i),k=(0,wt.Z)((0,d.Ti)(t,"pictogram"),!(C&&l),(0,d.kG)(t,"pictogram"),l),R=(0,Es.Z)(k),{mediaData:T,loadProgress:B}=(0,Ns.Z)((0,d.Ti)(t,"inline"),!S,(0,d.kG)(t,"inline"),l),A=P||T,x=Boolean(C&&A),L=As(t,k),{loadProgress:O}=(0,Ns.Z)((0,d.Ti)(t,"download"),!p,u.IU.BlobUrl,l),{isBuffered:F,bufferingHandlers:U}=(0,Fs.Z)(!r),{isUploading:$,isTransferring:D,transferProgress:q}=(0,d.Sc)(t,c||(p?O:B),S&&!F||p),Q=!1===(0,lt.Z)(w),{shouldRender:G,transitionClassNames:j}=(0,ce.Z)(D,void 0,Q),{shouldRender:H,transitionClassNames:_}=(0,ce.Z)(w&&!E&&!G),[z,V]=(0,o.eJ)(0),K=(0,o.I4)((e=>{V(Math.max(0,e.currentTarget.currentTime-1))}),[]),Y=(null===(I=y.current)||void 0===I?void 0:I.duration)||Z.duration||0,W=(0,d.B4)(t),X=(0,d.MF)(t),{width:J,height:ee}=m||(0,Pt.GC)(Z,W,X,a);Ds(y,x),(0,Us.Z)(y,[x]);const te=(0,o.I4)((()=>{$?g&&g(t):p?(0,n.uC)().cancelMessageMediaDownload({message:t}):A?A&&!E?(M(!0),y.current.play()):h&&h(t.id):b((e=>!e))}),[$,p,A,E,h,g,t]),se=(0,ne.Z)("media-inner dark",!$&&"interactive"),ae=m?`width: ${J}px; height: ${ee}px; left: ${m.x}px; top: ${m.y}px;`:"";return o.ZP.createElement("div",{ref:v,id:e,className:se,style:ae,onClick:$?void 0:te},o.ZP.createElement("canvas",{ref:L,className:"thumbnail",style:`width: ${J}px; height: ${ee}px;`}),o.ZP.createElement("img",{src:k,className:(0,ne.Z)("thumbnail",R),style:`width: ${J}px; height: ${ee}px;`,alt:"",draggable:!f}),x&&o.ZP.createElement("video",qs({ref:y,className:"full-media",width:J,height:ee,autoPlay:E,muted:!0,loop:!0,playsInline:!0},U,{draggable:!f,onTimeUpdate:K}),o.ZP.createElement("source",{src:A})),f&&o.ZP.createElement("span",{className:"protector"}),H&&o.ZP.createElement("i",{className:(0,ne.Z)("icon-large-play",_)}),G&&o.ZP.createElement("div",{className:(0,ne.Z)("media-loading",j)},o.ZP.createElement(Ls.Z,{progress:q,onClick:te})),!w&&o.ZP.createElement("i",{className:"icon-download"}),D?o.ZP.createElement("span",{className:"message-transfer-progress"},$||p?`${Math.round(100*q)}%`:"..."):o.ZP.createElement("div",{className:"message-media-duration"},Z.isGif?"GIF":(0,N.k9)(Math.max(Y-z,0))))};var Gs=s(6272);const js=(0,n.c$)(((e,{contact:t})=>{const{countryList:{phoneCodes:s}}=e;return{user:(0,i.dy)(e,t.userId),phoneCodeList:s}}))((({contact:e,user:t,phoneCodeList:s})=>{const{openUserInfo:a}=(0,n.uC)(),{firstName:r,lastName:i,phoneNumber:c,userId:d}=e,l=(0,o.I4)((()=>{a({id:d})}),[a,d]);return o.ZP.createElement("div",{className:(0,ne.Z)("Contact",Boolean(d)&&"interactive"),onClick:d?l:void 0},o.ZP.createElement(_t.Z,{size:"large",user:t,text:r||i}),o.ZP.createElement("div",{className:"contact-info"},o.ZP.createElement("div",{className:"contact-name"},r," ",i),o.ZP.createElement("div",{className:"contact-phone"},(0,Gs.WZ)(s,c))))}));var Hs=s(1218),_s=s(4434),zs=s(6937);function Vs(e,t){return t>0?(e/t*100).toFixed():0}const Ks=({answer:e,voteResults:t,totalVoters:s,maxVotersCount:n,correctResults:a,shouldAnimate:r})=>{const i=t&&t.find((t=>t.option===e.option)),c=0===a.length||-1!==a.indexOf(e.option),d=a.length>0&&c||(null==i?void 0:i.isChosen),l=i?Vs(i.votersCount,s||0):0,[u,m]=(0,o.eJ)(r?0:l),h=(0,o.sO)(null),g=i?Vs(i.votersCount,n||0):0,p=u{r&&m(l)}),[r,l]),(0,o.d4)((()=>{const e=h.current;if(e&&r){const t=e.firstElementChild,s=p?"":"stroke-dasharray: 100% 200%; stroke-dashoffset: -44";t?t.setAttribute("style",s):e.innerHTML=`\n \n \n `}}),[p,r]),!t||!i)return;const f=`width: ${g}%; transform:scaleX(${p?0:1})`;return o.ZP.createElement("div",{className:"PollOption",dir:"ltr"},o.ZP.createElement("div",{className:"poll-option-share "+("100"===l?"limit-width":"")},l,"%",d&&o.ZP.createElement("span",{className:(0,ne.Z)("poll-option-chosen",!c&&"wrong",r&&"animate")},o.ZP.createElement("i",{className:c?"icon-check":"icon-close"}))),o.ZP.createElement("div",{className:"poll-option-right"},o.ZP.createElement("div",{className:"poll-option-text",dir:"auto"},(0,Ct.Z)(e.text)),o.ZP.createElement("div",{className:(0,ne.Z)("poll-option-answer",d&&!c&&"wrong")},o.ZP.createElement("div",{className:"poll-option-corner",ref:h}),o.ZP.createElement("div",{className:"poll-option-line",style:f}))))},Ys=(0,o.X$)((0,n.c$)(((e,{poll:t})=>{const{recentVoterIds:s}=t.results,{serverTimeOffset:n,users:{byId:a}}=e;return s&&0!==s.length?{recentVoterIds:s,usersById:a,serverTimeOffset:n}:{}}))((({message:e,poll:t,recentVoterIds:s,usersById:a,onSendVote:r,serverTimeOffset:i})=>{const{loadMessage:c,openPollResults:d}=(0,n.uC)(),{id:l,chatId:u}=e,{summary:m,results:h}=t,[g,p]=(0,o.eJ)(!1),[f,I]=(0,o.eJ)([]),[v,y]=(0,o.eJ)(!1),[Z,P]=(0,o.eJ)(!1),[C,w]=(0,o.eJ)(!m.closed&&m.closeDate&&m.closeDate>0?Math.min(m.closeDate-Math.floor(Date.now()/1e3)+i,m.closePeriod):0),b=(0,o.sO)(null),{results:S,totalVoters:E}=h,M=S&&S.some((e=>e.isChosen)),k=!m.closed&&!M,R=!k&&m.isPublic&&Number(h.totalVoters)>0,T=k&&m.multipleChoice,B=S?Math.max(...S.map((e=>e.votersCount))):E,A=S?S.reduce(((e,t)=>(t.isCorrect&&e.push(t.option),e)),[]):[],x=m.answers.map((e=>({label:e.text,value:e.option,hidden:Boolean(m.quiz&&m.closePeriod&&C<=0)})));(0,o.d4)((()=>{g&&t.results.results&&t.results.results.some((e=>e.isChosen))&&p(!1)}),[g,t.results.results]),(0,o.d4)((()=>{C>0&&setTimeout((()=>w(C-1)),1e3);const e=b.current;if(e){const t=12*Math.PI,s=e.lastElementChild,n=e.firstElementChild;if(C<=5&&e.classList.add("hurry-up"),s&&n){const e=(m.closePeriod-C)/m.closePeriod*t;n.textContent=(0,N.k9)(C),s.firstElementChild.setAttribute("stroke-dashoffset",`-${e}`)}else e.innerHTML=`\n ${(0,N.k9)(C)}\n \n \n `}}),[C,m.closePeriod]),(0,o.d4)((()=>{m.quiz&&(C<=0||M&&!m.closed)&&c({chatId:u,messageId:l})}),[u,C,M,c,l,m.closed,m.quiz]),(0,o.d4)((()=>{let e;return m.quiz&&!m.closed&&m.closePeriod&&m.closePeriod>0&&(e=window.setTimeout((()=>{c({chatId:u,messageId:l})}),1e3*m.closePeriod)),()=>{e&&window.clearTimeout(e)}}),[k,u,c,l,m.closePeriod,m.closed,m.quiz]);const L=(0,o.Ye)((()=>s?s.reduce(((e,t)=>{const s=a[t];return s&&e.push(s),e}),[]):[]),[a,s]),O=(0,o.I4)((e=>{I([e]),p(!0),P(!0),r([e])}),[r]),F=(0,o.I4)((e=>{I(e)}),[]),U=(0,o.I4)((()=>{p(!0),P(!0),r(f)}),[r,f]),$=(0,o.I4)((()=>{d({chatId:u,messageId:l})}),[u,l,d]),D=(0,o.I4)((()=>{y(!0)}),[]),q=(0,o.I4)((()=>{y(!1),P(!1)}),[]);(0,o.d4)((()=>{Z&&M&&m.quiz&&h.results&&t.results.solution&&(h.results.find((e=>e.isChosen&&e.isCorrect))||y(!0))}),[M,Z,h.results,m.quiz,t.results.solution]);const Q=(0,Ce.Z)();return o.ZP.createElement("div",{className:"Poll",dir:Q.isRtl?"auto":"ltr"},v&&t.results.solution&&o.ZP.createElement(zs.Z,{message:(0,is.H)(t.results.solution,t.results.solutionEntities),duration:5e3,onDismiss:q,containerId:"#middle-column-portals"}),o.ZP.createElement("div",{className:"poll-question"},(0,Ct.Z)(m.question,["emoji","br"])),o.ZP.createElement("div",{className:"poll-type"},Q(function(e){return void 0===e.isPublic?" ":e.quiz?e.isPublic?"QuizPoll":"AnonymousQuizPoll":e.closed?"FinalResults":e.isPublic?"PublicPoll":"AnonymousPoll"}(m)),L.length>0&&o.ZP.createElement("div",{className:"poll-recent-voters"},L.map((e=>o.ZP.createElement(_t.Z,{size:"micro",user:e})))),C>0&&k&&o.ZP.createElement("div",{ref:b,className:"poll-countdown"}),m.quiz&&t.results.solution&&!k&&o.ZP.createElement(Me.Z,{round:!0,size:"tiny",color:"translucent",className:"poll-quiz-help",disabled:v,onClick:D,ariaLabel:"Show Solution"},o.ZP.createElement("i",{className:"icon-lamp"}))),k&&o.ZP.createElement("div",{className:"poll-answers"},T?o.ZP.createElement(Hs.Z,{options:x,onChange:F,disabled:e.isScheduled||g,loadingOptions:g?f:void 0,round:!0}):o.ZP.createElement(_s.Z,{name:`poll-${l}`,options:x,onChange:O,disabled:e.isScheduled||g,loadingOption:g?f[0]:void 0})),!k&&o.ZP.createElement("div",{className:"poll-results"},m.answers.map((function(e){return o.ZP.createElement(Ks,{key:e.option,shouldAnimate:Z,answer:e,voteResults:S,totalVoters:E,maxVotersCount:B,correctResults:A})}))),!R&&!T&&o.ZP.createElement("div",{className:"poll-voters-count"},function(e,t,s){return s?e(t?"Answer":"Vote",s,"i"):e(t?"Chat.Quiz.TotalVotesEmpty":"Chat.Poll.TotalVotesResultEmpty")}(Q,m.quiz,h.totalVoters)),T&&o.ZP.createElement(Me.Z,{isText:!0,disabled:0===f.length,size:"tiny",onClick:U},Q("PollSubmitVotes")),R&&o.ZP.createElement(Me.Z,{isText:!0,size:"tiny",onClick:$},Q("PollViewResults")))})));var Ws=s(8035),Xs=s(88);const Js=(0,o.X$)((({message:e,observeIntersection:t,noAvatars:s,canAutoLoad:n,canAutoPlay:a,inPreview:r,lastSyncTime:i,isDownloading:c=!1,isProtected:l,theme:u,onMediaClick:m,onCancelMediaTransfer:h})=>{const g=(0,d.s1)(e);let p=!1;if(null!=g&&g.photo&&!g.video){const{width:t,height:s}=ls(e);p=t===s}const f=(0,o.I4)((()=>{m()}),[m]);if(!g)return;const{siteName:I,url:v,displayUrl:y,title:Z,description:P,photo:C,video:w}=g,b=(C||w)&&m&&!p,S=(0,Ws.Z)(P,170),E=(0,ne.Z)("WebPage",p&&"with-square-photo",!C&&!w&&!r&&"without-media",w&&"with-video");return o.ZP.createElement("div",{className:E,"data-initial":(I||y)[0],dir:"auto"},C&&!w&&o.ZP.createElement(Os,{message:e,observeIntersection:t,noAvatars:s,canAutoLoad:n,size:p?"pictogram":"inline",nonInteractive:!b,onClick:b?f:void 0,onCancelUpload:h,isDownloading:c,isProtected:l,theme:u}),o.ZP.createElement("div",{className:"WebPage-text"},o.ZP.createElement(Xs.Z,{className:"site-name",url:v,text:I||y}),!r&&Z&&o.ZP.createElement("p",{className:"site-title"},(0,Ct.Z)(Z)),S&&o.ZP.createElement("p",{className:"site-description"},(0,Ct.Z)(S,["emoji","br"]))),!r&&w&&o.ZP.createElement(Qs,{message:e,observeIntersection:t,noAvatars:s,canAutoLoad:n,canAutoPlay:a,lastSyncTime:i,onClick:b?f:void 0,onCancelUpload:h,isDownloading:c,isProtected:l}))}));var en=s(9937);const tn=(0,o.X$)((({message:e})=>{const t=(0,Ce.Z)(),s=(0,d.eO)(e),{title:n,text:a,amount:r,currency:i,isTest:c,photoUrl:l}=s;return o.ZP.createElement("div",{className:"Invoice"},n&&o.ZP.createElement("p",{className:"title"},(0,Ct.Z)(n)),a&&o.ZP.createElement("p",null,(0,Ct.Z)(a,["emoji","br"])),o.ZP.createElement("div",{className:"description "+(l?"has-image":"")},l&&o.ZP.createElement("img",{className:"invoice-image",src:l,alt:""}),o.ZP.createElement("p",{className:"description-text"},(0,en.x)(r,i,t.code),c&&o.ZP.createElement("span",null,t("PaymentTestInvoice")))))}));function sn(e){return(0,o.X$)((0,n.c$)(((e,t)=>{const{message:s}=t;return{isInSelectMode:(0,i.CA)(e),isSelected:(0,i.vk)(e,s.id)}}))((t=>{const{isInSelectMode:s,isSelected:a,message:r,dimensions:i}=t,{toggleMessageSelection:c}=(0,n.uC)(),d=(0,o.I4)((e=>{e.stopPropagation(),c({messageId:r.id,withShift:null==e?void 0:e.shiftKey})}),[c,r]),l=(0,o.Ye)((()=>({...t,isInSelectMode:s,isSelected:a,dimensions:{...t.dimensions,x:0,y:0},onClick:s?void 0:t.onClick})),[t,s,a]);return o.ZP.createElement("div",{className:(0,ne.Z)("album-item-select-wrapper",a&&"is-selected"),style:i?`left: ${i.x}px; top: ${i.y}px;`:"",onClick:s?d:void 0},s&&o.ZP.createElement("div",{className:"message-select-control"},a&&o.ZP.createElement("i",{className:"icon-select"})),o.ZP.createElement(e,l))})))}const nn=sn(Os),an=sn(Qs),on=(0,n.c$)(((e,{album:t})=>{const{chatId:s}=t.mainMessage,n=(0,i.Pu)(e),a=(0,i.xs)(e,s);return{theme:n,uploadsById:e.fileUploads.byMessageLocalId,activeDownloadIds:a}}))((({album:e,observeIntersection:t,hasCustomAppendix:s,lastSyncTime:a,isOwn:r,isProtected:c,albumLayout:l,onMediaClick:u,uploadsById:m,activeDownloadIds:h,theme:g})=>{const{cancelSendingMessage:p}=(0,n.uC)(),f=e.messages.length,I=(0,o.I4)((e=>{p({chatId:e.chatId,messageId:e.id})}),[p]),{width:v,height:y}=l.containerStyle;return o.ZP.createElement("div",{className:"Album",style:`width: ${v}px; height: ${y}px;`},e.messages.map((function(e,p){const{photo:v,video:y}=(0,d.qp)(e),Z=m[e.previousLocalId||e.id],P=null==Z?void 0:Z.progress,{dimensions:C,sides:w}=l.layout[p],b=(0,i.bH)((0,n.Rd)(),e),S=(0,i.__)((0,n.Rd)(),e);if(v){const n=s&&(r?p===f-1:Boolean(8&w&&4&w));return o.ZP.createElement(nn,{id:`album-media-${e.id}`,message:e,observeIntersection:t,canAutoLoad:b,shouldAffectAppendix:n,uploadProgress:P,dimensions:C,isProtected:c,onClick:u,onCancelUpload:I,isDownloading:h.includes(e.id),theme:g})}if(y)return o.ZP.createElement(an,{id:`album-media-${e.id}`,message:e,observeIntersection:t,canAutoLoad:b,canAutoPlay:S,uploadProgress:P,lastSyncTime:a,dimensions:C,isProtected:c,onClick:u,onCancelUpload:I,isDownloading:h.includes(e.id),theme:g})})))}));function rn(){return(rn=Object.assign||function(e){for(var t=1;t{const i=(0,o.sO)(null),c=(0,o.sO)(null),l=(0,o.sO)(null),m=e.content.video,h=(0,ns.Op)(i,t),[g,p]=(0,o.eJ)(s),f=Boolean(g&&h&&a),{mediaData:I,loadProgress:v}=(0,Ns.Z)((0,d.Ti)(e,"inline"),!f,(0,d.kG)(e,"inline"),a),{loadProgress:y}=(0,Ns.Z)((0,d.Ti)(e,"download"),!r,u.IU.BlobUrl,a),Z=As(e,I),{isBuffered:P,bufferingHandlers:w}=(0,Fs.Z)(),b=g&&!P||r,S=!1===(0,lt.Z)(g),E=(0,Es.Z)(I),{shouldRender:M,transitionClassNames:k}=(0,ce.Z)(b||!P,void 0,S),[R,T]=(0,o.eJ)(!1),[B,A]=(0,o.eJ)(0);(0,o.d4)((()=>{if(!R)return;const e=Pt.Rj/2,t=2*(e-6)*Math.PI,s=t-B*t,n=l.current,a=c.current,o=a.firstElementChild;o?o.firstElementChild.setAttribute("stroke-dashoffset",s.toString()):a.innerHTML=`\n \n \n `,A(n.currentTime/n.duration)}),[R,B]);const x=Boolean(I&&h),L=()=>{T(!1),A(0),(0,$s.Z)(l.current),(0,C.T2)((()=>{c.current.innerHTML=""}))},O=(F=L,()=>{cn&&cn(),cn=F});var F;(0,o.d4)((()=>{l.current&&(x?(0,$s.Z)(l.current):l.current.pause())}),[x]),Ds(l,x),(0,Us.Z)(l,[I]);const U=(0,o.I4)((()=>{if(!I)return void p((e=>!e));if(r)return void(0,n.uC)().cancelMessageMediaDownload({message:e});const t=l.current;R?t.paused?((0,$s.Z)(t),(0,Bt.Es)()):t.pause():(O(),t.pause(),t.currentTime=0,(0,$s.Z)(t),(0,Bt.Es)(),T(!0))}),[O,R,r,I,e]),$=(0,o.I4)((e=>{const t=e.currentTarget;A(t.currentTime/t.duration)}),[]),D=(0,ne.Z)("full-media",E);return o.ZP.createElement("div",{ref:i,className:"RoundVideo media-inner",onClick:U},o.ZP.createElement("div",{className:"thumbnail-wrapper"},o.ZP.createElement("canvas",{ref:Z,className:"thumbnail",style:`width: ${Pt.Rj}px; height: ${Pt.Rj}px`})),I&&o.ZP.createElement("div",{className:"video-wrapper"},o.ZP.createElement("video",rn({ref:l,className:D,width:Pt.Rj,height:Pt.Rj,autoPlay:!0,muted:!R,loop:!R,playsInline:!0,onEnded:R?L:void 0},w,{onTimeUpdate:R?$:void 0}),o.ZP.createElement("source",{src:I}))),o.ZP.createElement("div",{className:"progress",ref:c}),M&&o.ZP.createElement("div",{className:`media-loading ${k}`},o.ZP.createElement(Ls.Z,{progress:r?y:v})),!I&&!g&&o.ZP.createElement("i",{className:"icon-download"}),o.ZP.createElement("div",{className:"message-media-duration"},R?(0,N.k9)(l.current.currentTime):(0,N.k9)(m.duration),(!R||l.current.paused)&&o.ZP.createElement("i",{className:"icon-muted"})))},ln=({message:e,onClick:t})=>{const s=(0,Ce.Z)();return o.ZP.createElement("div",{className:"InlineButtons"},e.inlineButtons.map((e=>o.ZP.createElement("div",{className:"row"},e.map((e=>o.ZP.createElement(Me.Z,{size:"tiny",ripple:!0,disabled:"NOT_SUPPORTED"===e.type,onClick:()=>t({button:e})},(0,Ct.Z)(s(e.text)),"buy"===e.type&&o.ZP.createElement("i",{className:"icon-card"}),"url"===e.type&&!e.value.match(a.FS)&&o.ZP.createElement("i",{className:"icon-arrow-right"}))))))))},un=(0,o.X$)((({threadInfo:e,disabled:t})=>{const{openChat:s}=(0,n.uC)(),a=(0,Ce.Z)(),{threadId:r,chatId:i,messagesCount:c,lastMessageId:l,lastReadInboxMessageId:u,recentReplierIds:m}=e,h=(0,o.I4)((()=>{s({id:i,threadId:r})}),[s,i,r]),g=(0,o.Ye)((()=>{if(null==m||!m.length)return;const{users:{byId:e},chats:{byId:t}}=(0,n.Rd)();return m.map((s=>(0,d.YC)(s)?e[s]:t[s])).filter(Boolean)}),[m]);if(void 0===c)return;const p=Boolean(u&&l&&u0&&o.ZP.createElement("div",{className:"recent-repliers",dir:a.isRtl?"rtl":"ltr"},g.map((e=>o.ZP.createElement(_t.Z,{key:e.id,size:"small",user:(0,d.YC)(e.id)?e:void 0,chat:(0,d.YC)(e.id)?void 0:e})))),o.ZP.createElement("div",{className:"label",dir:"auto"},c?a("Comments",c,"i"):a("LeaveAComment")),o.ZP.createElement("i",{className:"icon-next"}))})),mn="data-is-document-group-hover",hn={__html:''},gn={__html:''};function pn(e){const t=In(e.currentTarget);t&&t.setAttribute(mn,"")}function fn(e){const t=In(e.currentTarget);t&&t.removeAttribute(mn)}function In(e){let t=e;do{t=t.nextElementSibling}while(t&&!t.classList.contains("last-in-document-group"));return t}const vn=(0,o.X$)((0,n.c$)(((e,t)=>{const{focusedMessage:s,forwardMessages:n,lastSyncTime:a}=e,{message:o,album:r,withSenderName:c,withAvatar:l,threadId:u,messageListType:m}=t,{id:h,chatId:g,viaBotId:p,replyToChatId:f,replyToMessageId:I,isOutgoing:v,threadInfo:y}=o,Z=(0,i.Z1)(e,g),P=(0,i.FM)(e,g),C=(0,d.pK)(g),w=Z&&(0,d.eA)(Z),b=null==Z?void 0:Z.username,S=!P&&(0,d.Ul)(o),E=c||l||S,M=(0,i.Ur)(e,o),k=(0,i.cv)(e,o),R=p?(0,i.dy)(e,p):void 0,T=u?(0,i.qS)(e,g,u):void 0,N=o.id===T,B=I===T,A=I&&!B?(0,i.hj)(e,C&&f?f:g,I):void 0,x=A&&(0,i.Ur)(e,A),L=(0,i.uZ)(e,o),O="thread"===m&&(r?r.messages.some((t=>(0,i._X)(e,t))):(0,i._X)(e,o)),{direction:F,noHighlight:U,isResizingContainer:$}=O&&s||{},D=n.messageIds&&n.messageIds.includes(h),{query:q}=(0,i.n5)(e)||{},Q=(0,d._O)(o);let G;G=null!=r&&r.messages?r.messages.every((({id:t})=>(0,i.vk)(e,t))):(0,i.vk)(e,h);const{canReply:j}="thread"===m&&(0,i._k)(e,o,u)||{},H=(0,i.te)(e,o),_=y?(0,i.tZ)(e,y.chatId,y.threadId)||y:void 0;return{theme:(0,i.Pu)(e),chatUsername:b,forceSenderName:S,sender:E?M:void 0,originSender:k,botSender:R,shouldHideReply:B,isThreadTop:N,replyMessage:A,replyMessageSender:x,isProtected:(0,i.EV)(e,o),isFocused:O,isForwarding:D,isChatWithSelf:P,isRepliesChat:C,isChannel:w,canReply:j,lastSyncTime:a,highlight:q,isSingleEmoji:Boolean(Q),animatedEmoji:Q?(0,i.zB)(e,Q):void 0,isInSelectMode:(0,i.CA)(e),isSelected:G,isGroupSelected:!!o.groupedId&&!o.isInAlbum&&(0,i.a6)(e,g,o.groupedId),threadId:u,isDownloading:H,isPinnedList:"pinned"===m,canAutoLoadMedia:(0,i.bH)(e,o),canAutoPlayMedia:(0,i.__)(e,o),autoLoadFileMaxSizeMb:e.settings.byKey.autoLoadFileMaxSizeMb,shouldLoopStickers:(0,i.yB)(e),threadInfo:_,...v&&{outgoingStatus:(0,i.dT)(e,o,"scheduled"===m)},..."number"==typeof L&&{uploadProgress:L},...O&&{focusDirection:F,noFocusHighlight:U,isResizingContainer:$}}}))((({message:e,chatUsername:t,observeIntersectionForBottom:s,observeIntersectionForMedia:a,observeIntersectionForAnimatedStickers:r,album:i,noAvatars:c,withAvatar:l,withSenderName:g,noComments:p,appearanceOrder:f,isFirstInGroup:I,isLastInGroup:v,isFirstInDocumentGroup:y,isLastInDocumentGroup:Z,isLastInList:P,theme:C,forceSenderName:w,sender:b,originSender:S,botSender:E,isThreadTop:M,shouldHideReply:k,replyMessage:R,replyMessageSender:T,outgoingStatus:N,uploadProgress:B,isProtected:A,isFocused:x,focusDirection:L,noFocusHighlight:O,isResizingContainer:F,isForwarding:U,isChatWithSelf:$,isRepliesChat:D,isChannel:q,canReply:Q,lastSyncTime:G,highlight:j,animatedEmoji:H,isInSelectMode:_,isSelected:z,isGroupSelected:V,threadId:K,messageListType:Y,isPinnedList:W,isDownloading:X,canAutoLoadMedia:J,canAutoPlayMedia:ee,shouldLoopStickers:te,autoLoadFileMaxSizeMb:se,threadInfo:ae})=>{const{toggleMessageSelection:oe,clickInlineButton:de,disableContextMenuHint:le}=(0,n.uC)(),ue=(0,o.sO)(null),me=(0,o.sO)(null),he=(0,Ce.Z)();(0,ns._N)(me,s);const{isContextMenuOpen:ge,contextMenuPosition:pe,handleBeforeContextMenu:fe,handleContextMenu:Ie,handleContextMenuClose:ve,handleContextMenuHide:Ze}=(0,rs.Z)(ue,h.$b&&_,!0,h.wZ);(0,o.d4)((()=>{ge&&le()}),[ge,le]);const Pe=f<=0,[we,be]=(0,ye.Z)(Pe);(0,o.d4)((()=>{Pe||setTimeout(be,10*f)}),[f,be,Pe]);const{transitionClassNames:Se}=(0,ce.Z)(we,void 0,Pe,!1),{id:Ee,chatId:ke}=e,Re=(0,d.CI)(e),Te=(0,d.B4)(e),Ne="scheduled"===Y||e.isScheduled,Be=(0,d.ss)(e)&&!k,Ae=Boolean(ae)&&"thread"===Y,xe=(0,d.$D)(e),{forwardInfo:Oe,viaBotId:Fe}=e,Ue=Oe&&(!$||Ne)&&!D&&!Oe.isLinkedChannelPost&&!xe,$e=Boolean(e.groupedId)&&!e.isInAlbum,De=Boolean(i)&&i.messages.length>1,{text:qe,photo:Qe,video:Ge,audio:je,voice:He,document:_e,sticker:ze,contact:Ve,poll:Ke,webPage:Ye,invoice:We}=(0,d.qp)(e),Xe=(0,is.X)(e,j,cs(xe)),Je=void 0!==pe,et=q&&e.adminTitle||!Ue&&(null==Oe?void 0:Oe.adminTitle)||void 0,tt=(0,o.Ye)((()=>et?fs(et):void 0),[et]),st=!(Je||_||U)&&(!$e||Z),nt=q&&!Ne,at=Boolean(W||Oe&&(Oe.isChannelPost||$&&!Te||D)&&Oe.fromMessageId),ot=Oe&&($||D||!b)?S:b,rt=Oe?S:b,it=(0,o.I4)(((e,t)=>{oe({messageId:Ee,groupedId:t,...(null==e?void 0:e.shiftKey)&&{withShift:!0},...De&&{childMessageIds:i.messages.map((({id:e})=>e))}})}),[oe,Ee,De,i]),{handleMouseDown:ct,handleClick:dt,handleContextMenu:lt,handleDoubleClick:ut,handleContentDoubleClick:mt,isSwiped:ht}=function(e,t,s,a,r,i,c,d,l){const{setReplyingToId:u}=(0,n.uC)(),[m,g,p]=(0,ye.Z)();return(0,o.d4)((()=>{if(!h.$b||r||!i)return;let e;return(0,Le.s)(t.current,{selectorToPreventScroll:".MessageList",onSwipe:(t,s)=>s===Le.e.Left&&(e||(e=Date.now()),g(),!0),onRelease:()=>{e&&(u({messageId:s}),setTimeout(p,Math.max(0,150-(Date.now()-e))),e=void 0)}})}),[t,r,s,u,g,p,i]),{handleMouseDown:r?void 0:function(e){(0,Jt.q)(e),l(e)},handleClick:function(t){if(r)e(t);else if(h.wZ){const e=t.target;if(!e.classList.contains("text-content")&&!e.classList.contains("Message"))return;ie.Z.getIsKeyboardVisible()?setTimeout((()=>{d(t)}),350):d(t)}},handleContextMenu:r?c?re.Z:void 0:function(t){if(h.wZ){if(t.target.matches("a[href]"))return;t.preventDefault(),e()}else d(t)},handleDoubleClick:r?void 0:function(){u({messageId:s})},handleContentDoubleClick:h.$b?void 0:function(e){e.stopPropagation()},isSwiped:m}}(it,ue,Ee,0,Boolean(_),Boolean(Q),Boolean(A),Ie,fe),{handleAvatarClick:pt,handleSenderClick:ft,handleViaBotClick:It,handleReplyClick:vt,handleMediaClick:yt,handleAudioPlay:Zt,handleAlbumMediaClick:wt,handleMetaClick:bt,handleReadMedia:St,handleCancelUpload:Et,handleVoteSend:Mt,handleGroupForward:kt,handleForward:Rt,handleFocus:Tt,handleFocusForwarded:Nt,handleDocumentGroupSelectAll:Bt}=function(e,t,s,a,r,i,c,l,h,g,p,f,I){const{openUserInfo:v,openChat:y,showNotification:Z,focusMessage:P,openMediaViewer:C,openAudioPlayer:w,markMessagesRead:b,cancelSendingMessage:S,sendPollVote:E,openForwardMenu:M,focusMessageInComments:k}=(0,n.uC)(),{id:R,forwardInfo:T,replyToMessageId:N,replyToChatId:B,replyToTopMessageId:A,groupedId:x}=s,L=(0,o.I4)((()=>{p&&((0,d.YC)(p.id)?v({id:p.id}):y({id:p.id}))}),[p,v,y]),O=(0,o.I4)((()=>{f?c&&null!=T&&T.channelPostId?P({chatId:f.id,messageId:T.channelPostId}):(0,d.YC)(f.id)?v({id:f.id}):y({id:f.id}):Z({message:e("HidAccount")})}),[c,P,T,e,y,v,f,Z]),F=(0,o.I4)((()=>{I&&v({id:I.id})}),[I,v]),U=(0,o.I4)((()=>{P({chatId:h&&B?B:a,threadId:r,messageId:N,replyMessageId:h&&B?void 0:R})}),[P,h,B,a,r,N,R]),$=(0,o.I4)((()=>{C({chatId:a,threadId:r,messageId:R,origin:l?m.bZ.ScheduledInline:m.bZ.Inline})}),[a,r,R,C,l]),D=(0,o.I4)((()=>{w({chatId:a,messageId:R})}),[a,R,w]),q=(0,o.I4)((e=>{C({chatId:a,threadId:r,messageId:e,origin:l?m.bZ.ScheduledAlbum:m.bZ.Album})}),[a,r,C,l]),Q=(0,o.I4)((()=>{b({messageIds:[R]})}),[R,b]),G=(0,o.I4)((()=>{S({chatId:a,messageId:R})}),[S,a,R]),j=(0,o.I4)((e=>{E({chatId:a,messageId:R,options:e})}),[a,R,E]),H=(0,o.I4)((()=>{M({fromChatId:a,groupedId:x})}),[M,a,x]),_=(0,o.I4)((()=>{if(g&&g.messages){const e=g.messages.map((({id:e})=>e));M({fromChatId:a,messageIds:e})}else M({fromChatId:a,messageIds:[R]})}),[g,M,a,R]),z=(0,o.I4)((()=>{P({chatId:a,threadId:u._f,messageId:R})}),[P,a,R]),V=(0,o.I4)((()=>{i?P({chatId:T.fromChatId,groupedId:x,groupedChatId:a}):h&&B?k({chatId:B,threadId:A,messageId:T.fromMessageId}):P({chatId:T.fromChatId,messageId:T.fromMessageId})}),[i,h,B,P,T,x,a,k,A]),K=(0,o.I4)((e=>{e.stopPropagation(),t(e,x)}),[t,x]);return{handleAvatarClick:L,handleSenderClick:O,handleViaBotClick:F,handleReplyClick:U,handleMediaClick:$,handleAudioPlay:D,handleAlbumMediaClick:q,handleMetaClick:K,handleReadMedia:Q,handleCancelUpload:G,handleVoteSend:j,handleGroupForward:H,handleForward:_,handleFocus:z,handleFocusForwarded:V,handleDocumentGroupSelectAll:K}}(he,it,e,ke,K,$e,Ue,Ne,D,i,ot,rt,E),At=(0,ne.Z)("Message message-list-item",I&&"first-in-group",A&&"is-protected",v&&"last-in-group",y&&"first-in-document-group",Z&&"last-in-document-group",P&&"last-in-list",Te&&"own",Boolean(e.views)&&"has-views",e.isEdited&&"was-edited",Be&&"has-reply",Je&&"has-menu-open",x&&!O&&"focused",U&&"is-forwarding",e.isDeleting&&"is-deleting",$e&&"is-in-document-group",De&&"is-album",e.hasUnreadMention&&"has-unread-mention",z&&"is-selected",_&&"is-in-selection-mode",M&&"is-thread-top",Boolean(e.inlineButtons)&&"has-inline-buttons",ht&&"is-swiped",Se),xt=function(e,{hasReply:t,customShape:s,isLastInGroup:n,asForwarded:a,hasThread:o,forceSenderName:r,hasComments:i,hasActionButton:c}={}){const{text:l,photo:u,video:m,audio:h,voice:g,document:p,poll:f,webPage:I,contact:v}=(0,d.qp)(e),y=["message-content"],Z=u||m,P=Z&&!l,C=Boolean(e.viaBotId);return cs(s)?y.push(`emoji-only emoji-only-${s}`):l&&y.push("text"),c&&y.push("has-action-button"),s&&(y.push("custom-shape"),null!=m&&m.isRound&&y.push("round"),i&&y.push("has-comments")),u||m?y.push("media"):h?y.push("audio"):g?y.push("voice"):p?y.push("document"):v?y.push("contact"):f?y.push("poll"):I&&(y.push("web-page"),(I.photo||I.video)&&y.push("media")),a&&y.push("is-forwarded"),t&&y.push("is-reply"),o&&y.push("has-replies"),C&&y.push("is-via-bot"),r&&y.push("force-sender-name"),s||(y.push("has-shadow"),Z&&i&&y.push("has-background"),(t||a||!P||C||r)&&y.push("has-solid-background"),!n||!u&&P||y.push("has-appendix")),y.join(" ")}(e,{hasReply:Be,customShape:xe,isLastInGroup:v,asForwarded:Ue,hasThread:Ae,forceSenderName:w,hasComments:ae&&(null==ae?void 0:ae.messagesCount)>0,hasActionButton:nt||at}),Lt=ae&&(!$e||Z)&&"thread"===Y&&!p,Ot=xt.includes("has-appendix");(0,gt.Z)(D&&e.replyToChatId?e.replyToChatId:ke,Be?e.replyToMessageId:void 0,R,e.id),Is(ue,ke,x,L,O,F);let Ft,Ut="",$t=!1;const Dt=(0,o.Ye)((()=>De?gs(Te,Boolean(Ue),Boolean(c),i):void 0),[De,Te,Ue,c,i]),qt=Ue?28:0;if(De||!Qe&&!Ge)Dt&&(Ft=Math.max(ds(Boolean(qe),Lt),Dt.containerStyle.width),Ft-Dt.containerStyle.width>18&&($t=!0));else{let t;Qe?t=ls(e,c).width:Ge&&(t=Ge.isRound?Pt.Rj:ls(e,c).width),t&&(Ft=Math.max(ds(Boolean(qe),Lt),t),Ft-t>18&&($t=!0))}return Ft&&(Ut=`width: ${Ft+qt}px`),o.ZP.createElement("div",{ref:ue,id:`message${Ee}`,className:At,style:tt?`--meta-safe-author-width: ${tt}px`:void 0,"data-message-id":Ee,onMouseDown:ct,onClick:dt,onContextMenu:lt,onDoubleClick:ut,onMouseEnter:$e&&!Z?pn:void 0,onMouseLeave:$e&&!Z?fn:void 0},o.ZP.createElement("div",{ref:me,className:"bottom-marker","data-message-id":Ee,"data-last-message-id":i?i.messages[i.messages.length-1].id:void 0,"data-has-unread-mention":e.hasUnreadMention}),!$e&&o.ZP.createElement("div",{className:"message-select-control"},z&&o.ZP.createElement("i",{className:"icon-select"})),Z&&o.ZP.createElement("div",{className:(0,ne.Z)("message-select-control group-select",V&&"is-selected"),onClick:Bt},V&&o.ZP.createElement("i",{className:"icon-select"})),l&&function(){const e=ot&&(0,d.YC)(ot.id),t=ot&&e?ot:void 0,s=ot&&!e?ot:void 0,n=!ot&&Oe?Oe.hiddenUserName:void 0;return o.ZP.createElement(_t.Z,{size:"small",user:t,chat:s,text:n,lastSyncTime:G,onClick:t||s?pt:void 0})}(),o.ZP.createElement("div",{className:(0,ne.Z)("message-content-wrapper",xt.includes("text")&&"can-select-text")},o.ZP.createElement("div",{className:xt,style:Ut,dir:"auto"},Ue&&(!$e||y)&&o.ZP.createElement("div",{className:"message-title"},he("ForwardedMessage")),function(){const t=(0,ne.Z)("content-inner",Ue&&"forwarded-message",Be&&"reply-message",$t&&"no-media-corners"),s=v&&!Xe&&!Ue&&!Ae,n=!Ye&&!H&&Xe,l=(0,ne.Z)("text-content",n&&"with-meta",N&&"with-outgoing-icon");return o.ZP.createElement("div",{className:t,onDoubleClick:mt,dir:"auto"},function(){if(xe&&!Fe||!(g&&!Qe&&!Ge||Ue||Fe||w)||$e&&!y||Be&&xe)return;let t,s;return!rt||xe&&Fe?null!=Oe&&Oe.hiddenUserName&&(t=Oe.hiddenUserName):(t=(0,d.OU)(he,rt),Ue||(s=`color-${(0,d.Rs)(rt)}`)),o.ZP.createElement("div",{className:"message-title",dir:"ltr"},t?o.ZP.createElement("span",{className:(0,ne.Z)("interactive",s),onClick:ft,dir:"auto"},(0,Ct.Z)(t)):E?void 0:" ",E&&o.ZP.createElement(o.ZP.Fragment,null,o.ZP.createElement("span",{className:"via"},he("ViaBot")),o.ZP.createElement("span",{className:"interactive",onClick:It},(0,Ct.Z)(`@${E.username}`))),null!=Oe&&Oe.isLinkedChannelPost?o.ZP.createElement("span",{className:"admin-title",dir:"auto"},he("DiscussChannel")):e.adminTitle&&!q?o.ZP.createElement("span",{className:"admin-title",dir:"auto"},e.adminTitle):void 0)}(),Be&&o.ZP.createElement(Ps,{message:R,isProtected:A,sender:T,observeIntersection:a,onClick:vt}),ze&&o.ZP.createElement(Rs,{message:e,observeIntersection:a,observeIntersectionForPlaying:r,shouldLoop:te,lastSyncTime:G}),H&&o.ZP.createElement(Ts.Z,{size:"small",sticker:H,observeIntersection:a,lastSyncTime:G,forceLoadPreview:Re}),De&&o.ZP.createElement(on,{album:i,albumLayout:Dt,observeIntersection:a,isOwn:Te,isProtected:A,hasCustomAppendix:s,lastSyncTime:G,onMediaClick:wt}),!De&&Qe&&o.ZP.createElement(Os,{message:e,observeIntersection:a,noAvatars:c,canAutoLoad:J,uploadProgress:B,shouldAffectAppendix:s,onClick:yt,onCancelUpload:Et,isDownloading:X,isProtected:A,theme:C}),!De&&Ge&&Ge.isRound&&o.ZP.createElement(dn,{message:e,observeIntersection:a,canAutoLoad:J,lastSyncTime:G,isDownloading:X}),!De&&Ge&&!Ge.isRound&&o.ZP.createElement(Qs,{message:e,observeIntersection:a,noAvatars:c,canAutoLoad:J,canAutoPlay:ee,uploadProgress:B,lastSyncTime:G,onClick:yt,onCancelUpload:Et,isDownloading:X,isProtected:A}),(je||He)&&o.ZP.createElement(ws.Z,{theme:C,message:e,origin:m.Cr.Inline,uploadProgress:B,lastSyncTime:G,isSelectable:$e,isSelected:z,onPlay:Zt,onReadMedia:!He||Te&&!$?void 0:St,onCancelUpload:Et,isDownloading:X}),_e&&o.ZP.createElement(Cs.Z,{message:e,observeIntersection:a,canAutoLoad:J,autoLoadFileMaxSizeMb:se,uploadProgress:B,isSelectable:$e,isSelected:z,onMediaClick:yt,onCancelUpload:Et,isDownloading:X}),Ve&&o.ZP.createElement(js,{contact:Ve}),Ke&&o.ZP.createElement(Ys,{message:e,poll:Ke,onSendVote:Mt}),!H&&Xe&&o.ZP.createElement("p",{className:l,dir:"auto"},Xe,n&&o.ZP.createElement(Ss,{message:e,outgoingStatus:N,signature:et,onClick:bt})),Ye&&o.ZP.createElement(Js,{message:e,observeIntersection:a,noAvatars:c,canAutoLoad:J,canAutoPlay:ee,lastSyncTime:G,onMediaClick:yt,onCancelMediaTransfer:Et,isDownloading:X,isProtected:A,theme:C}),We&&o.ZP.createElement(tn,{message:e}))}(),(!$e||Z)&&!(!Ye&&!H&&Xe)&&o.ZP.createElement(Ss,{message:e,outgoingStatus:N,signature:et,onClick:bt}),st&&nt?o.ZP.createElement(Me.Z,{className:"message-action-button",color:"translucent-white",round:!0,size:"tiny",ariaLabel:he("lng_context_forward_msg"),onClick:Z?kt:Rt},o.ZP.createElement("i",{className:"icon-share-filled"})):st&&at?o.ZP.createElement(Me.Z,{className:"message-action-button",color:"translucent-white",round:!0,size:"tiny",ariaLabel:"Focus message",onClick:W?Tt:Nt},o.ZP.createElement("i",{className:"icon-arrow-right"})):void 0,Lt&&o.ZP.createElement(un,{threadInfo:ae,disabled:p}),Ot&&o.ZP.createElement("div",{className:"svg-appendix",dangerouslySetInnerHTML:Te?hn:gn})),e.inlineButtons&&o.ZP.createElement(ln,{message:e,onClick:de})),pe&&o.ZP.createElement(ys,{isOpen:ge,anchor:pe,message:e,album:i,chatUsername:t,messageListType:Y,onClose:ve,onCloseAnimationEnd:Ze}))}))),yn=(0,o.X$)((0,n.c$)(((e,{chatId:t})=>{const s=(0,i.fS)(e,t),{chatId:n,isBot:a}=s||{};return{message:s,bot:n&&a?(0,i.dy)(e,n):void 0,channel:!a&&n?(0,i.Z1)(e,n):void 0}}))((({chatId:e,message:t,containerRef:s,bot:a,channel:r})=>{const{viewSponsoredMessage:i,openChat:c,openChatByInvite:l,startBot:u,focusMessage:m}=(0,n.uC)(),h=(0,Ce.Z)(),g=(0,o.sO)(null),p=Boolean(t),{observe:f}=(0,ns.S1)({rootRef:s,debounceMs:200,threshold:1});if((0,o.d4)((()=>p?f(g.current,(t=>{t.isIntersecting&&i({chatId:e})})):void 0),[e,p,f,i]),t)return o.ZP.createElement("div",{className:"SponsoredMessage Message open",key:"sponsored-message"},o.ZP.createElement("div",{className:"message-content has-shadow has-solid-background",dir:"auto"},o.ZP.createElement("div",{className:"content-inner",dir:"auto"},o.ZP.createElement("div",{className:"message-title",dir:"ltr"},a&&(0,Ct.Z)((0,d.Js)(a)||""),r&&(0,Ct.Z)(t.chatInviteTitle||(0,d.U)(h,r,a)||"")),o.ZP.createElement("p",{className:"text-content with-meta",dir:"auto",ref:g},o.ZP.createElement("span",{className:"text-content-inner",dir:"auto"},(0,is.H)(t.text.text,t.text.entities)),o.ZP.createElement("span",{className:"MessageMeta",dir:"ltr"},o.ZP.createElement("span",{className:"message-signature"},h("SponsoredMessage")))),o.ZP.createElement(Me.Z,{color:"secondary",size:"tiny",ripple:!0,onClick:()=>{t.chatInviteHash?l({hash:t.chatInviteHash}):t.channelPostId?m({chatId:t.chatId,messageId:t.channelPostId}):(c({id:t.chatId}),t.startParam&&u({botId:t.chatId,param:t.startParam}))},className:"SponsoredMessage__button"},h(t.isBot?"Conversation.ViewBot":t.channelPostId?"Conversation.ViewPost":"Conversation.ViewChannel")))))}))),Zn=(0,o.X$)((({chatId:e,messageIds:t,messageGroups:s,isViewportNewest:r,isUnread:i,withUsers:c,noAvatars:l,containerRef:u,anchorIdRef:p,memoUnreadDividerBeforeIdRef:f,memoFirstUnreadIdRef:I,threadId:v,type:y,isReady:Z,isScrollingRef:P,isScrollPatchNeededRef:w,threadTopMessageId:b,hasLinkedChat:S,isSchedule:E,noAppearanceAnimation:M,onFabToggle:k,onNotchToggle:R})=>{const{openHistoryCalendar:T}=(0,n.uC)(),{observeIntersectionForMedia:B,observeIntersectionForReading:A,observeIntersectionForAnimatedStickers:x}=function(e,t,s){const{markMessageListRead:a,markMessagesRead:o}=(0,n.uC)(),{observe:r}=(0,ns.S1)({rootRef:t,throttleMs:as,margin:os}),{observe:i,freeze:c,unfreeze:d}=(0,ns.S1)({rootRef:t,throttleMs:150},(t=>{if("thread"!==e)return;let n=0;const r=[];t.forEach((e=>{const{isIntersecting:t,target:s}=e;if(!t)return;const{dataset:a}=s,o=Number(a.lastMessageId||a.messageId);o>n&&(n=o),a.hasUnreadMention&&r.push(o)})),s.current&&n>=s.current&&a({maxId:n}),r.length&&o({messageIds:r})}));(0,de.Z)(c,d);const{observe:l}=(0,ns.S1)({rootRef:t,throttleMs:as});return{observeIntersectionForMedia:r,observeIntersectionForReading:i,observeIntersectionForAnimatedStickers:l}}(y,u,I),{backwardsTriggerRef:L,forwardsTriggerRef:O,fabTriggerRef:F}=function(e,t,s,r,i,c,d,l,u,g){const{loadViewportMessages:p}=(0,n.uC)(),[f,I]=(0,o.Ye)((()=>"thread"===e?[(0,C.Ds)((()=>p({direction:m.Uq.Backwards})),1e3,!0,!1),(0,C.Ds)((()=>p({direction:m.Uq.Forwards})),1e3,!0,!1)]:[]),[p,s]),v=(0,o.sO)(null),y=(0,o.sO)(null),Z=(0,o.sO)(null);function P(){if(!l)return;if(!s||!s.length)return c(!1),void d(!1);if(!r)return c(!0),void d(!0);const{offsetHeight:e,scrollHeight:n,scrollTop:a}=t.current,o=Math.round(n-a-e),u=o<=1;c(i?!u:!(o<=50)),d(!u)}const{observe:w}=(0,ns.S1)({rootRef:t,margin:h.gZ},(e=>{if(!I||!f)return;if(s[0]>=a.AE)return;const t=e.find((({isIntersecting:e})=>e));if(!t)return;const{target:n}=t;"backwards-trigger"===n.className?(h.i4&&u.current&&s.length<=a.hT&&(g.current=!0),f()):"forwards-trigger"===n.className&&I()}));(0,ns._N)(v,w),(0,ns._N)(y,w);const{observe:b,freeze:S,unfreeze:E}=(0,ns.S1)({rootRef:t,margin:100},P);(0,ns._N)(Z,b);const{observe:M,freeze:k,unfreeze:R}=(0,ns.S1)({rootRef:t,margin:1},P);return(0,ns._N)(Z,M),(0,ue.Z)((()=>{l&&P()}),[l]),(0,ue.Z)((()=>{S(),k(),setTimeout((()=>{R(),E()}),250)}),[s]),{backwardsTriggerRef:v,forwardsTriggerRef:y,fabTriggerRef:Z}}(y,u,t,r,i,k,R,Z,P,w),U=(0,Ce.Z)(),$=o.ZP.createElement("div",{className:(0,ne.Z)("unread-divider","local-action-message"),key:"unread-messages"},o.ZP.createElement("span",null,U("UnreadMessages"))),D=M?0:s.reduce(((e,t)=>e+(0,g.xH)(t.senderGroups).length),0);let q=0;const Q=s.map(((e,t,s)=>{const n=e.senderGroups.map(((e,n,a)=>{if(1===e.length&&!Wt(e[0])&&(0,d.Lo)(e[0])){const r=e[0],i=n===a.length-1&&t===s.length-1;return(0,g.oA)([r.id===f.current&&$,o.ZP.createElement(Zs,{key:r.id,message:r,observeIntersection:A,appearanceOrder:D-++q,isLastInList:i})])}let r;return(0,g.xH)(e.map(((i,u)=>{const m=Wt(i)?i.mainMessage:i,h=Wt(i)?i:void 0,I=(0,d.B4)(m),Z=Wt(i),P=e[u+1];m.previousLocalId&&p.current===`message${m.previousLocalId}`&&(p.current=`message${m.id}`);const C=!Z&&m.groupedId?m.groupedId:void 0,w=P&&!Wt(P)?P.groupedId:void 0,E={isFirstInGroup:0===u,isLastInGroup:u===e.length-1,isFirstInDocumentGroup:Boolean(C&&C!==r),isLastInDocumentGroup:Boolean(C&&C!==w),isLastInList:u===e.length-1&&n===a.length-1&&t===s.length-1};r=C;const M=(0,d.KK)(m),k="scheduled"!==y?M:`${m.date}_${M}`;return(0,g.oA)([m.id===f.current&&$,o.ZP.createElement(vn,{key:k,message:m,observeIntersectionForBottom:A,observeIntersectionForMedia:B,observeIntersectionForAnimatedStickers:x,album:h,noAvatars:l,withAvatar:E.isLastInGroup&&c&&!I&&!(m.id===b),withSenderName:E.isFirstInGroup&&c&&!I,threadId:v,messageListType:y,noComments:!1===S,appearanceOrder:D-++q,isFirstInGroup:E.isFirstInGroup,isLastInGroup:E.isLastInGroup,isFirstInDocumentGroup:E.isFirstInDocumentGroup,isLastInDocumentGroup:E.isLastInDocumentGroup,isLastInList:E.isLastInList}),m.id===b&&o.ZP.createElement("div",{className:"local-action-message",key:"discussion-started"},o.ZP.createElement("span",null,U("DiscussionStarted")))])})))}));return o.ZP.createElement("div",{className:"message-date-group",key:e.datetime,onMouseDown:Jt.q,teactFastList:!0},o.ZP.createElement("div",{className:(0,ne.Z)("sticky-date",!E&&"interactive"),key:"date-header",onMouseDown:Jt.q,onClick:E?void 0:()=>T({selectedAt:e.datetime})},o.ZP.createElement("span",{dir:"auto"},E&&e.originalDate===a.t4&&U("MessageScheduledUntilOnline"),E&&e.originalDate!==a.t4&&U("MessageScheduledOn",(0,N.j1)(U,e.datetime,void 0,!0)),!E&&(0,N.j1)(U,e.datetime))),(0,g.xH)(n))}));return o.ZP.createElement("div",{className:"messages-container",teactFastList:!0},o.ZP.createElement("div",{ref:L,key:"backwards-trigger",className:"backwards-trigger"}),(0,g.xH)(Q),r&&o.ZP.createElement(yn,{key:e,chatId:e,containerRef:u}),o.ZP.createElement("div",{ref:O,key:"forwards-trigger",className:"forwards-trigger"}),o.ZP.createElement("div",{ref:F,key:"fab-trigger",className:"fab-trigger"}))}));var Pn=s(3547);const Cn=(0,o.X$)((0,n.c$)(((e,{userId:t})=>{const{stickers:s}=e.stickers.greeting,n=(0,d.db)(t)+(0,d.db)(e.currentUserId),a=null!=s&&s.length?s[n%s.length]:void 0,o=(0,i.Z1)(e,t);return o?{sticker:a,lastUnreadMessageId:o.lastMessage&&o.lastMessage.id!==o.lastReadInboxMessageId?o.lastMessage.id:void 0,connectionState:e.connectionState}:{}}))((({sticker:e,connectionState:t,lastUnreadMessageId:s})=>{const{loadGreetingStickers:a,sendMessage:r,markMessageListRead:i}=(0,n.uC)(),c=(0,Ce.Z)(),d=(0,o.sO)(null),{observe:l}=(0,ns.S1)({rootRef:d,debounceMs:200});(0,o.d4)((()=>{e||"connectionStateReady"!==t||a()}),[t,a,e]),(0,o.d4)((()=>{"connectionStateReady"===t&&s&&i({maxId:s})}),[t,i,s]);const u=(0,o.I4)((e=>{e={...e,isPreloadedGlobally:!0},r({sticker:e})}),[r]);return o.ZP.createElement("div",{className:"ContactGreeting",ref:d},o.ZP.createElement("div",{className:"wrapper"},o.ZP.createElement("p",{className:"title",dir:"auto"},c("Conversation.EmptyPlaceholder")),o.ZP.createElement("p",{className:"description",dir:"auto"},c("Conversation.GreetingText")),o.ZP.createElement("div",{className:"sticker"},e&&o.ZP.createElement(Pn.Z,{sticker:e,onClick:u,clickArg:e,observeIntersection:l,size:160,className:"large"}))))}))),wn=(0,o.X$)((({isChatWithSelf:e,type:t,isGroupChatJustCreated:s})=>{const n=(0,Ce.Z)();return"scheduled"===t?function(e){return o.ZP.createElement("div",{className:"empty"},o.ZP.createElement("span",null,e("ScheduledMessages.EmptyPlaceholder")))}(n):e?function(e){return o.ZP.createElement("div",{className:"NoMessages"},o.ZP.createElement("div",{className:"wrapper"},o.ZP.createElement("i",{className:"icon icon-cloud-download"}),o.ZP.createElement("h3",{className:"title"},e("Conversation.CloudStorageInfo.Title")),o.ZP.createElement("ul",{className:"description"},o.ZP.createElement("li",null,e("Conversation.ClousStorageInfo.Description1")),o.ZP.createElement("li",null,e("Conversation.ClousStorageInfo.Description2")),o.ZP.createElement("li",null,e("Conversation.ClousStorageInfo.Description3")),o.ZP.createElement("li",null,e("Conversation.ClousStorageInfo.Description4")))))}(n):s?function(e){return o.ZP.createElement("div",{className:"NoMessages"},o.ZP.createElement("div",{className:"wrapper",dir:e.isRtl?"rtl":void 0},o.ZP.createElement("h3",{className:"title"},e("EmptyGroupInfo.Title")),o.ZP.createElement("p",{className:"description"},e("EmptyGroupInfo.Subtitle")),o.ZP.createElement("ul",{className:"list-checkmarks"},o.ZP.createElement("li",null,e("EmptyGroupInfo.Line1")),o.ZP.createElement("li",null,e("EmptyGroupInfo.Line2")),o.ZP.createElement("li",null,e("EmptyGroupInfo.Line3")),o.ZP.createElement("li",null,e("EmptyGroupInfo.Line4")))))}(n):o.ZP.createElement("div",{className:"empty"},o.ZP.createElement("span",null,n("NoMessages")))})),bn=(0,C.Ds)((e=>e()),200,!1),Sn=(0,o.X$)((0,n.c$)(((e,{chatId:t,threadId:s,type:n})=>{const a=(0,i.Z1)(e,t);if(!a)return{};const o=(0,i.$W)(e,t,s,n),r="scheduled"===n?(0,i.Fn)(e,t):(0,i.Zw)(e,t),c=(0,i.qS)(e,t,s);if(s!==u._f&&!(r&&c&&r[c]))return{};const{isRestricted:l,restrictionReason:m,lastMessage:h}=a,g=(0,i.G$)(e,t),p=s===u._f&&!o&&!a.unreadCount&&!g&&h&&!h.groupedId,f=(0,i.IK)(e,t);let I;return(0,i.pk)(e,t)&&(I=f.fullInfo?f.fullInfo.botDescription||"NoMessages":"Updating bot info..."),{isChatLoaded:!0,isRestricted:l,restrictionReason:m,isChannelChat:(0,d.eA)(a),isGroupChat:(0,d.Bf)(a),isCreator:a.isCreator,isChatWithSelf:(0,i.FM)(e,t),isRepliesChat:(0,d.pK)(t),isBot:Boolean(f),messageIds:o,messagesById:r,firstUnreadId:(0,i.It)(e,t,s),isViewportNewest:"thread"!==n||(0,i.b9)(e,t,s),threadFirstMessageId:(0,i.yZ)(e,t,s),focusingId:g,isSelectModeActive:(0,i.CA)(e),botDescription:I,threadTopMessageId:c,hasLinkedChat:a.fullInfo&&"linkedChatId"in a.fullInfo?Boolean(a.fullInfo.linkedChatId):void 0,lastSyncTime:e.lastSyncTime,...p&&{lastMessage:h}}}))((({chatId:e,threadId:t,type:s,hasTools:r,onFabToggle:c,onNotchToggle:l,isChatLoaded:u,isChannelChat:h,isGroupChat:p,canPost:f,isReady:I,isChatWithSelf:v,isRepliesChat:y,isCreator:Z,isBot:P,messageIds:w,messagesById:b,firstUnreadId:S,isViewportNewest:E,threadFirstMessageId:M,isRestricted:k,restrictionReason:R,focusingId:T,isSelectModeActive:N,lastMessage:B,botDescription:A,threadTopMessageId:x,hasLinkedChat:L,lastSyncTime:O,withBottomShift:F})=>{var U,$,D,q,Q,G;const{loadViewportMessages:j,setScrollOffset:H,loadSponsoredMessages:_}=(0,n.uC)(),z=(0,o.sO)(null),V=(0,o.sO)("thread"===s&&(0,i.Vt)((0,n.Rd)(),e,t)||0),K=(0,o.sO)(),Y=(0,o.sO)(),W=(0,o.sO)(),X=(0,o.sO)(),J=(0,o.sO)(),ee=(0,o.sO)(),te=(0,o.sO)(!1),ae=(0,o.sO)(Boolean(B)),[oe,re]=(0,o.eJ)(),ie=Boolean(w);(0,ue.Z)((()=>{ie&&(0,C.R3)((()=>{ae.current=!1}))}),[ie]),(0,ue.Z)((()=>{X.current=S}),[S]),(0,ue.Z)((()=>{h&&I&&O&&_({chatId:e})}),[e,I,h,O]),(0,ue.Z)((()=>{ie&&(J.current=X.current)}),[ie]),(0,ue.Z)((()=>{ee.current=T}),[T]);const ce=(0,o.Ye)((()=>{if(!w||!b)return;const e=!x||w[0]&&M!==w[0]?w:[x,...w];if(!e.length)return;const t=e.map((e=>b[e])).filter(Boolean);return Xt((0,g.Xo)(t,["date","id"]),J.current)}),[w,b,M,x]),de=(0,o.Ye)((()=>{if("thread"===s)return(0,C.Ds)((()=>j({direction:m.Uq.Around})),1e3,!0,!1)}),[j,w]),{isScrolled:le,updateStickyDates:me}=function(){const[e,t]=(0,ye.Z)(!1),s=(0,es.Z)(1e3,!1);return{isScrolled:e,updateStickyDates:(0,o.I4)(((e,n)=>{t(),document.body.classList.contains("is-scrolling-messages")||(0,C.T2)((()=>{document.body.classList.add("is-scrolling-messages")})),s((()=>{(0,C.T2)((()=>{const t=document.querySelector(".stuck");t&&t.classList.remove("stuck");const s=function(e,t){const s=e.querySelectorAll(".sticky-date"),n=e.scrollTop;return Array.from(s).find((e=>{const{offsetTop:s,offsetHeight:a}=e,o=s-n;return-a<=o&&o<=(t?60:10)}))}(e,n);s&&s.classList.add("stuck"),document.body.classList.remove("is-scrolling-messages")}))}))}),[t,s])}}(),he=(0,o.sO)(),ge=(0,o.sO)(),pe=(0,o.I4)((()=>{if(te.current)return void(te.current=!1);he.current=!0;const n=z.current;ee.current||me(n,r),bn((()=>{he.current=!1,(0,C.T2)((()=>{n.parentElement&&(V.current=n.scrollHeight-n.scrollTop,"thread"===s&&H({chatId:e,threadId:t,scrollOffset:V.current}))}))}))}),[me,r,s,H,e,t]);(0,o.d4)((()=>{if(!("ResizeObserver"in window))return;const e=new ResizeObserver((([e])=>{e.target.offsetParent&&re(e.contentRect.height)}));return e.observe(z.current),()=>{e.disconnect()}}),[]);const{height:fe}=ct();(0,o.d4)((()=>{I&&(z.current.dataset.normalHeight=String(z.current.offsetHeight))}),[fe,I,f]),(0,o.d4)((()=>{if(!de||!u||k||T)return;if(w&&w[w.length-1]>=a.AE)return;const e=z.current;(!w||w.length{if(!w||!W.current)return;const e=W.current.filter((e=>w.includes(Number(e.dataset.messageId)))),t=e[1]||e[0];t&&(K.current=t.id,Y.current=t.getBoundingClientRect().top)}),[w,E,oe,r]),(0,Kt.Z)((([e,t,s])=>{const n=z.current;W.current=Array.from(n.querySelectorAll(".message-list-item"));const o=w&&e&&w[w.length-1]!==e[e.length-1],i=(null==w?void 0:w[0])!==(null==e?void 0:e[0])&&(null==w?void 0:w.length)===a.hT/2+1,c=o&&!i,d=w&&ee.current===w[w.length-1],l=E&&c&&w&&w.length{n.parentElement&&n.parentElement.classList.remove("force-messages-scroll")}),500));const{scrollTop:u,scrollHeight:m,offsetHeight:h}=n,g=V.current,p=W.current[W.current.length-1];let f=g-(s||h);c&&(f-=p?p.offsetHeight:0);const I=E&&t&&f<=20;let v;if(c&&I&&!d&&(p&&(0,C.T2)((()=>{(0,ss.Z)(n,p,"end",20)})),v=m-h,V.current=Math.max(Math.ceil(m-v),h),!l))return;const y=void 0!==s&&s!==oe,Z=K.current&&n.querySelector(`#${K.current}`),P=!Z&&J.current&&n.querySelector(".unread-divider");if(I&&y){if((0,ss.N)())return;v=m-h}else Z?(ge.current&&(ge.current=!1,(0,ts.z)(n)),v=u+(Z.getBoundingClientRect().top-(Y.current||0))):v=P?Math.min(P.offsetTop-(r?60:10),m-g):m-g;(0,ts.Z)(n,Math.ceil(v)),ee.current||(te.current=!0,(0,C.T2)((()=>{te.current=!1}))),V.current=Math.max(Math.ceil(m-v),h)}),[w,E,oe,r]),(0,Yt.Z)((([e])=>{void 0!==e&&(0,se.YW)(200+a.fK)}),[N]);const Ie=(0,Ce.Z)(),ve=Boolean(e&&(0,d.YC)(e)),Ze=Boolean(!ve&&!h||v||y),Pe=Boolean(!Ze||h),we=(0,d.YC)(e)&&!v&&!P&&(!ce&&!B&&w&&(!W.current||0===W.current.length)||1===(null==w?void 0:w.length)&&"contactSignUp"===(null==b||null===(U=b[w[0]])||void 0===U||null===($=U.content.action)||void 0===$?void 0:$.type)||"contactSignUp"===(null==B||null===(D=B.content)||void 0===D||null===(q=D.action)||void 0===q?void 0:q.type)),be=p&&Z&&1===(null==w?void 0:w.length)&&"chatCreate"===(null==b||null===(Q=b[w[0]])||void 0===Q||null===(G=Q.content.action)||void 0===G?void 0:G.type),Se=(0,ne.Z)("MessageList custom-scroll",Pe&&"no-avatars",!f&&"no-composer","pinned"===s&&"type-pinned",F&&"with-bottom-shift",N&&"select-mode-active",le&&"scrolled",!I&&"is-animating");return o.ZP.createElement("div",{ref:z,className:Se,onScroll:pe,onMouseDown:Jt.q},k?o.ZP.createElement("div",{className:"empty"},o.ZP.createElement("span",null,R?R.text:"This is a private "+(h?"channel":"chat"))):A?o.ZP.createElement("div",{className:"empty"},o.ZP.createElement("span",null,(0,Ct.Z)(Ie(A),["br","emoji","links"]))):we?o.ZP.createElement(Cn,{userId:e}):!w||ce&&!be?w&&ce||B?o.ZP.createElement(Zn,{chatId:e,messageIds:w||[B.id],messageGroups:ce||Xt([B]),isViewportNewest:Boolean(E),isUnread:Boolean(S),withUsers:Ze,noAvatars:Pe,containerRef:z,anchorIdRef:K,memoUnreadDividerBeforeIdRef:J,memoFirstUnreadIdRef:X,threadId:t,type:s,isReady:I,isScrollingRef:he,isScrollPatchNeededRef:ge,threadTopMessageId:x,hasLinkedChat:L,isSchedule:!!ce&&"scheduled"===s,noAppearanceAnimation:!ce||!ae.current,onFabToggle:c,onNotchToggle:l}):o.ZP.createElement(Qe.Z,{color:"white"}):o.ZP.createElement(wn,{chatId:e,type:s,isChatWithSelf:v,isGroupChatJustCreated:be}))}))),En=(0,o.X$)((0,n.c$)((e=>{const t=(0,i.Bt)(e);if(!t)return{};const{chatId:s,threadId:n,type:a}=t,o=(0,i.Z1)(e,s);return{messageListType:a,unreadCount:o&&n===u._f&&"thread"===a?o.unreadCount:void 0}}))((({isShown:e,canPost:t,messageListType:s,unreadCount:a,withExtraShift:r})=>{const{focusNextReply:i}=(0,n.uC)(),c=(0,Ce.Z)(),d=(0,o.sO)(null),l=(0,o.I4)((()=>{if(e)if("thread"===s)i();else{const e=d.current.parentElement.querySelector(".MessageList"),t=e.querySelectorAll(".message-list-item"),s=t[t.length-1];if(!s)return;(0,ss.Z)(e,s,"end",20)}}),[e,s,i]),u=(0,ne.Z)("ScrollDownButton",e&&"revealed",!t&&"no-composer",r&&"with-extra-shift");return o.ZP.createElement("div",{ref:d,className:u},o.ZP.createElement("div",{className:"ScrollDownButton-inner"},o.ZP.createElement(Me.Z,{color:"secondary",round:!0,onClick:l,ariaLabel:c("AccDescrPageDown")},o.ZP.createElement("i",{className:"icon-arrow-down"})),Boolean(a)&&o.ZP.createElement("div",{className:"unread-count"},(0,ft.bi)(a))))})));var Mn=s(5723);const kn=1280,Rn=/\.[^/.]+$/;async function Tn(e,t,s,n){const o=URL.createObjectURL(t),{type:r,size:i}=t;let c,d;if(a.oG.has(r))if(s){const t=await(0,it.pt)(o),{width:s,height:a}=t;if(s>kn||a>kn||"image/jpeg"!==r){const t=await Ot(o,kn/Math.max(s,a),"image/jpeg");return URL.revokeObjectURL(o),Tn(e,await(0,it.gm)(t),!0,n)}"image/jpeg"===r&&(e=e.replace(Rn,".jpg")),c={width:s,height:a}}else d=o;else if(a.wG.has(r)){const{videoWidth:e,videoHeight:t,duration:s}=await(0,it.jj)(o);c={width:e,height:t,duration:s},d=await(0,it.ud)(o)}return{blobUrl:o,filename:e,mimeType:r,size:i,quick:c,previewBlobUrl:d,...n}}var Nn=s(6391);let Bn;function An(e){Bn.focus(),e.focus()}h.cj&&(Bn=document.createElement("input"),Bn.classList.add("for-ios-autocapitalization-fix"),document.body.appendChild(Bn));var xn=s(4784),Ln=s(2400),On=s(6389);const Fn={encoderPath:s.p+"c0155344d336103c2b6a0b28cc510750.js",reuseWorker:!0},Un={type:"audio/ogg"};let $n,Dn,qn;async function Qn(){return $n||($n=s.e(161).then(s.t.bind(s,1161,23)),Dn=(await $n).default,qn=new Dn(Fn)),$n}async function Gn(e){await async function(){await Qn(),await qn.start()}();const t=Date.now();let s;const n=[],a=[];qn.ondataavailable=e=>{n.push(e)};const o=function(t,s){const n=t.sourceNode,o=n.context.createAnalyser();o.fftSize=64,n.connect(o);const r=o.frequencyBinCount,i=new Uint8Array(r);let c=!1;return function t(){if(c)return;o.getByteFrequencyData(i);const s=i.reduce(((e,t)=>e+t),0)/r/255;(t=>{a.push(255*t),e(t)})(s<.1?0:s),requestAnimationFrame(t)}(),()=>{c=!0}}(qn);return{stop:()=>new Promise(((e,r)=>{qn.onstop=()=>{e({blob:new Blob(n,Un),duration:Math.round(((s||Date.now())-t)/1e3),waveform:a})},qn.onerror=r;const i=Math.max(0,t+1e3-Date.now());setTimeout((()=>{qn.stop(),o()}),i)})),pause:()=>{const e=Math.max(0,t+1e3-Date.now());setTimeout((()=>{qn.pause(),s=Date.now(),o()}),e)}}}const jn=["image/png","image/jpeg","image/gif"];function Hn(e){const{text:t,entities:s}=e||{};if(!t)return"";const n=(0,is.H)(t,s,void 0,void 0,!0);return Array.isArray(n)?n.join(""):n}let _n,zn;var Vn=s(3575),Kn=s(9295);const Yn=document.createElement("div"),Wn=/^@([a-z0-9_]{1,32})[\u00A0\u0020]+(.*)/i,Xn=/^@([a-z0-9_]{1,32})[\u00A0\u0020]+\n{2,}/i;const Jn=(0,C.P2)((e=>e()),500,!0),ea=/^[\w@]{1,32}\s?/i,ta=(0,o.X$)((e=>{const{isOpen:t}=e,s=(0,qe.Z)(De.gl.Extra,"DeleteMessageModal",!t);return s?o.ZP.createElement(s,e):void 0}));function sa(){return(sa=Object.assign||function(e){for(var t=1;t{const s=(0,o.sO)(!1),n=(0,o.I4)((()=>{if(s.current=!0,aa)return aa=!1,void e();na&&(clearTimeout(na),na=void 0),na=window.setTimeout((()=>{s.current&&e()}),200)}),[e]),a=(0,o.I4)((()=>{s.current=!1}),[]);return o.ZP.createElement(Me.Z,sa({},t,{onMouseEnter:h.$b?void 0:n,onMouseLeave:h.$b?void 0:a,onClick:h.$b?e:void 0}))})),ra=(0,o.X$)((e=>{const{isOpen:t}=e,s=(0,qe.Z)(De.gl.Extra,"AttachMenu",!t);return s?o.ZP.createElement(s,e):void 0})),ia=(0,o.X$)((e=>{const{isOpen:t}=e,s=(0,qe.Z)(De.gl.Extra,"SymbolMenu",!t);return s?o.ZP.createElement(s,e):void 0})),ca=(0,o.X$)((e=>{const{isOpen:t}=e,s=(0,qe.Z)(De.gl.Extra,"InlineBotTooltip",!t);return s?o.ZP.createElement(s,e):void 0})),da=(0,o.X$)((e=>{const{isOpen:t}=e,s=(0,qe.Z)(De.gl.Extra,"MentionTooltip",!t);return s?o.ZP.createElement(s,e):void 0})),la=(0,o.X$)((e=>{const{isOpen:t}=e,s=(0,qe.Z)(De.gl.Extra,"CustomSendMenu",!t);return s?o.ZP.createElement(s,e):void 0})),ua=e=>{const{isOpen:t}=e,s=(0,qe.Z)(De.gl.Extra,"StickerTooltip",!t);return s?o.ZP.createElement(s,e):void 0};var ma=s(9830);const ha=(0,o.X$)((e=>{const{isOpen:t}=e,s=(0,qe.Z)(De.gl.Extra,"BotCommandTooltip",!t);return s?o.ZP.createElement(s,e):void 0}));var ga=s(6503);const pa=(0,o.X$)((0,n.c$)(((e,{messageId:t})=>{const{chatId:s}=(0,i.Bt)(e)||{};return s?{message:(0,i.hj)(e,s,t)}:{}}))((({isOpen:e,message:t,onClose:s})=>{const{clickInlineButton:a}=(0,n.uC)(),[r,i]=(0,ga.Z)(e,s),{isKeyboardSingleUse:c}=t||{},[d,l,u]=(0,ye.Z)(!0),m=()=>{u(),s()};if((0,o.d4)((()=>{l()}),[l,t]),t&&t.keyboardButtons)return o.ZP.createElement(He.Z,{isOpen:e||d,autoClose:c,positionX:"right",positionY:"bottom",onClose:m,className:"BotKeyboardMenu",onCloseAnimationEnd:m,onMouseEnter:h.$b?void 0:r,onMouseLeave:h.$b?void 0:i},o.ZP.createElement("div",{className:"content"},t.keyboardButtons.map((e=>o.ZP.createElement("div",{className:"row"},e.map((e=>o.ZP.createElement(Me.Z,{ripple:!0,disabled:"NOT_SUPPORTED"===e.type,onClick:()=>a({button:e})},e.text))))))))})));var fa=s(3616),Ia=s(7891);const va=(0,o.X$)((0,n.c$)((e=>{const{chatId:t,threadId:s,type:n}=(0,i.Bt)(e)||{};if(!t||!s||!n)return{};const{currentUserId:a,forwardMessages:{fromChatId:o,toChatId:r,messageIds:c}}=e,l=(0,i.Yy)(e,t,s),u="scheduled"===n?(0,i.wU)(e,t):(0,i._$)(e,t,s),m=e.settings.byKey.animationLevel>=1,h=r===t;let g,p;if(l?g=(0,i.hj)(e,t,l):u?g=(0,i.kK)(e,t,s,n):h&&1===c.length&&(g=(0,i.hj)(e,o,c[0])),l&&g){const{forwardInfo:s}=g,n=t===a;s&&(s.isChannelPost||n)&&(p=(0,i.cv)(e,g)),p||(p=(0,i.Ur)(e,g))}else h&&(p=(0,d.YC)(o)?(0,i.dy)(e,o):(0,i.Z1)(e,o));return{replyingToId:l,editingId:u,message:g,sender:p,shouldAnimate:m,forwardedMessagesCount:h?c.length:void 0}}))((({replyingToId:e,editingId:t,message:s,sender:a,shouldAnimate:r,forwardedMessagesCount:i})=>{const{setReplyingToId:c,setEditingId:d,focusMessage:l,exitForwardMode:u}=(0,n.uC)(),m=Boolean((e||t)&&s||a&&i),h=(0,Ia.Z)([i],i?300:void 0),{shouldRender:g,transitionClassNames:p}=(0,ce.Z)(h&&m,void 0,!r,void 0,!r),f=(0,o.I4)((()=>{e?c({messageId:void 0}):t?d({messageId:void 0}):i&&u()}),[e,t,i,c,d,u]);(0,o.d4)((()=>m?(0,fe.Z)(f):void 0),[m,f]);const I=(0,o.I4)((()=>{l({chatId:s.chatId,messageId:s.id})}),[l,s]),v=(0,ne.Z)("ComposerEmbeddedMessage",p),y=i&&i>1?`${i} forwarded messages`:void 0;if(g)return o.ZP.createElement("div",{className:v},o.ZP.createElement("div",null,o.ZP.createElement(Me.Z,{round:!0,faded:!0,color:"translucent",ariaLabel:"Cancel replying",onClick:f},o.ZP.createElement("i",{className:"icon-close"})),o.ZP.createElement(Ps,{className:"inside-input",message:s,sender:a,customText:y,title:t?"Edit Message":void 0,onClick:I})))}))),ya=(0,o.X$)((e=>{const{attachments:t}=e,s=(0,qe.Z)(De.gl.Extra,"AttachmentModal",!t.length);return s?o.ZP.createElement(s,e):void 0})),Za=(0,o.X$)((e=>{const{isOpen:t}=e,s=(0,qe.Z)(De.gl.Extra,"BotCommandMenu",!t);return s?o.ZP.createElement(s,e):void 0})),Pa=(0,o.X$)((e=>{const{isOpen:t}=e,s=(0,qe.Z)(De.gl.Extra,"PollModal",!t);return s?o.ZP.createElement(s,e):void 0})),Ca=(0,o.X$)((e=>{const{isOpen:t}=e,s=(0,qe.Z)(De.gl.Extra,"DropArea",!t);return s?o.ZP.createElement(s,e):void 0})),wa=new RegExp(a.FM,"i"),ba=(0,o.X$)((0,n.c$)(((e,{chatId:t,threadId:s})=>{const n=(0,i.tV)(e,t,s);return{theme:(0,i.Pu)(e),webPagePreview:e.webPagePreview,noWebPage:n}}))((({chatId:e,threadId:t,messageText:s,disabled:a,webPagePreview:r,noWebPage:i,theme:c})=>{const{loadWebPagePreview:d,clearWebPagePreview:l,toggleMessageWebPage:m}=(0,n.uC)(),h=(0,o.Ye)((()=>{const{text:e,entities:t}=(0,f.Z)(s),n=t&&t.find((({type:e})=>e===u.Vv.TextUrl));if(n)return n.url;const a=e.match(wa);return a?a[0]:void 0}),[s]);(0,o.d4)((()=>{h?d({text:h}):(l(),m({chatId:e,threadId:t}))}),[e,m,l,h,d,t]),(0,ue.Z)((()=>{l(),m({chatId:e,threadId:t})}),[e]);const g=Boolean(r&&s.length&&!i&&!a),{shouldRender:p,transitionClassNames:I}=(0,ce.Z)(g),v=(0,pt.Z)(r,!0);if(!p||!v)return;const{photo:y,...Z}=v,P={content:{webPage:Z}};return o.ZP.createElement("div",{className:(0,ne.Z)("WebPagePreview",I)},o.ZP.createElement("div",null,o.ZP.createElement(Me.Z,{round:!0,faded:!0,color:"translucent",ariaLabel:"Clear Webpage Preview",onClick:()=>{m({chatId:e,threadId:t,noWebPage:!0})}},o.ZP.createElement("i",{className:"icon-close"})),o.ZP.createElement(Js,{message:P,inPreview:!0,theme:c})))})));var Sa=s(2898);const Ea=(0,o.X$)((e=>{const{isOpen:t}=e,s=(0,qe.Z)(De.gl.Extra,"CalendarModal",!t);return s?o.ZP.createElement(s,e):void 0})),Ma=(0,o.X$)((e=>{const{isOpen:t}=e,s=(0,qe.Z)(De.gl.Extra,"SendAsMenu",!t);return s?o.ZP.createElement(s,e):void 0}));var ka;!function(e){e.Send="send",e.Record="record",e.Edit="edit"}(ka||(ka={}));const Ra=(0,o.X$)((0,n.c$)(((e,{chatId:t,threadId:s,messageListType:n})=>{var o,r,c,l;const m=(0,i.Z1)(e,t),h=m&&(0,i.Dg)(e,m),g=t!==a.FV?(0,i.IK)(e,t):void 0,p=Boolean(g),f=(0,i.FM)(e,t),I=p&&(0,i.FT)(e,t),v=(0,i.qy)(e,t),{language:y,shouldSuggestStickers:Z}=e.settings.byKey,P=e.emojiKeywords[a.pR],C=y!==a.pR?e.emojiKeywords[y]:void 0,w=I?I.id:void 0,b=w?(0,i.hj)(e,t,w):void 0,S=e.users.byId,E=e.chats.byId,{currentUserId:M}=e,k=null!=m&&m.fullInfo?(null==m||null===(o=m.fullInfo)||void 0===o?void 0:o.sendAsId)||M:void 0,R=k?null==S?void 0:S[k]:void 0,T=!R&&k?null==E?void 0:E[k]:void 0;return{editingMessage:(0,i.kK)(e,t,s,n),connectionState:e.connectionState,draft:(0,i.Ms)(e,t,s),chat:m,isChatWithBot:p,isChatWithSelf:f,canScheduleUntilOnline:Boolean(!f&&!p&&m&&h&&(0,d.YC)(t)&&(null===(r=(0,i.ss)(e,t))||void 0===r?void 0:r.wasOnline)),isRightColumnShown:(0,i.Jf)(e),isSelectModeActive:(0,i.CA)(e),withScheduledButton:s===u._f&&"thread"===n&&Boolean(null==v?void 0:v.length),shouldSchedule:"scheduled"===n,botKeyboardMessageId:w,botKeyboardPlaceholder:null==b?void 0:b.keyboardPlaceholder,isForwarding:t===e.forwardMessages.toChatId,isPollModalOpen:e.isPollModalOpen,stickersForEmoji:e.stickers.forEmoji.stickers,groupChatMembers:null==m||null===(c=m.fullInfo)||void 0===c?void 0:c.members,topInlineBotIds:null===(l=e.topInlineBots)||void 0===l?void 0:l.userIds,currentUserId:M,usersById:S,lastSyncTime:e.lastSyncTime,contentToBeScheduled:e.messages.contentToBeScheduled,shouldSuggestStickers:Z,recentEmojis:e.recentEmojis,baseEmojiKeywords:null==P?void 0:P.keywords,emojiKeywords:null==C?void 0:C.keywords,serverTimeOffset:e.serverTimeOffset,inlineBots:e.inlineBots.byUsername,isInlineBotLoading:e.inlineBots.isLoading,chatBotCommands:m&&m.fullInfo&&m.fullInfo.botCommands,botCommands:g&&g.fullInfo?g.fullInfo.botCommands||!1:void 0,sendAsUser:R,sendAsChat:T,sendAsId:k}}))((({dropAreaState:e,shouldSchedule:t,canScheduleUntilOnline:s,isReady:r,onDropHide:i,editingMessage:c,chatId:l,threadId:m,messageListType:g,draft:I,chat:v,connectionState:y,isChatWithBot:Z,isChatWithSelf:P,isRightColumnShown:w,isSelectModeActive:b,isForwarding:S,isPollModalOpen:E,botKeyboardMessageId:M,botKeyboardPlaceholder:k,withScheduledButton:R,stickersForEmoji:T,groupChatMembers:B,topInlineBotIds:A,currentUserId:x,usersById:L,lastSyncTime:O,contentToBeScheduled:F,shouldSuggestStickers:U,baseEmojiKeywords:$,emojiKeywords:D,serverTimeOffset:q,recentEmojis:Q,inlineBots:G,isInlineBotLoading:j,botCommands:H,chatBotCommands:_,sendAsUser:z,sendAsChat:V,sendAsId:K})=>{const{sendMessage:Y,clearDraft:W,showDialog:X,setStickerSearchQuery:J,setGifSearchQuery:ee,forwardMessages:te,openPollModal:se,closePollModal:ae,loadScheduledHistory:oe,openChat:re,addRecentEmoji:ce,sendInlineBotResult:me,loadSendAs:he}=(0,n.uC)(),ge=(0,Ce.Z)(),pe=(0,o.sO)(null),[Ie,ve]=(0,o.eJ)(""),Ze=(0,o.sO)(),Pe=(0,lt.Z)(e),[we,be,Se]=(0,ye.Z)(),[Ee,ke]=(0,o.eJ)(),{width:Re}=ie.Z.get(),Te=null==v?void 0:v.sendAsIds,Ne=(0,On.Z)(l,m),Be=(0,o.sO)(Ie);(0,o.d4)((()=>{Be.current=Ie}),[Ie]),(0,o.d4)((()=>{Ze.current=void 0}),[l]),(0,o.d4)((()=>{l&&O&&m===u._f&&r&&oe({chatId:l})}),[r,l,oe,O,m]),(0,o.d4)((()=>{l&&v&&O&&!Te&&r&&(0,d.ZV)(v)&&he({chatId:l})}),[v,l,r,O,he,Te]);const xe=(0,o.sO)(!1);(0,ue.Z)((([e,t])=>{xe.current=Boolean(l===e&&Te&&!t)}),[l,Te]),(0,o.bt)((()=>{pe.current&&(pe.current.innerHTML='')}),[]),(0,o.d4)((()=>{F&&(ke(F),be())}),[F,be]);const[Le,Oe]=(0,o.eJ)([]),[Fe,Ue,$e]=(0,ye.Z)(),[De,qe,Qe]=(0,ye.Z)(),[Ge,je,He]=(0,ye.Z)(),[_e,ze,Ve]=(0,ye.Z)(),[Ke,Ye,We]=(0,ye.Z)(),[Xe,Je,et]=(0,ye.Z)(),[tt,st]=(0,ye.Z)(),[nt,ot,rt]=(0,ye.Z)(),{startRecordingVoice:it,stopRecordingVoice:ct,pauseRecordingVoice:dt,activeVoiceRecording:ut,currentRecordTime:mt,recordButtonRef:ht,startRecordTimeRef:gt}=(()=>{const e=(0,o.sO)(null),[t,s]=(0,o.eJ)(),n=(0,o.sO)(),[a,r]=(0,o.eJ)();(0,o.d4)((()=>{h.s$&&h.mh&&Qn()}),[]);const i=(0,o.I4)((async()=>{try{const{stop:t,pause:a}=await Gn((t=>{e.current&&(n.current&&Date.now()%4==0&&(e.current.style.boxShadow=`0 0 0 ${50*(t||0)}px rgba(0,0,0,.15)`),r(Date.now()))}));n.current=Date.now(),r(Date.now()),s({stop:t,pause:a})}catch(e){console.error(e)}}),[]),c=(0,o.I4)((()=>{if(t){e.current&&(e.current.style.boxShadow="none");try{return t.pause()}catch(e){return void console.error(e)}}}),[t]),d=(0,o.I4)((()=>{if(t){s(void 0),n.current=void 0,r(void 0),e.current&&(e.current.style.boxShadow="none");try{return t.stop()}catch(e){return void console.error(e)}}}),[t]);return(0,o.d4)((()=>t?(0,fe.Z)(d):void 0),[t,d]),{startRecordingVoice:i,pauseRecordingVoice:c,stopRecordingVoice:d,activeVoiceRecording:t,currentRecordTime:a,recordButtonRef:e,startRecordTimeRef:n}})();(function(e,t,s=!1){const n=(0,o.sO)(e);(0,o.bt)((()=>{n.current=e}),[e]),(0,o.d4)((()=>{if(void 0===t)return;const e=setInterval((()=>n.current()),t);return s||n.current(),()=>clearInterval(e)}),[t,s])})((()=>{Ne({type:"recordAudio"})}),ut&&a.o_),(0,o.d4)((()=>{ut||Ne({type:"cancel"})}),[ut,Ne]);const pt=c?ka.Edit:!h.mh||ut||Ie&&!Le.length||S?ka.Send:ka.Record,ft=!t,{isMentionTooltipOpen:It,closeMentionTooltip:vt,insertMention:yt,mentionFilteredUsers:Zt}=(0,Kn.Z)(!Le.length,Ie,ve,void 0,B,A,x),{isOpen:Pt,id:wt,isGallery:bt,switchPm:St,results:Et,closeTooltip:Mt,help:kt,loadMore:Rt}=function(e,t,s,a){const[r,i,c]=(0,ye.Z)(),d=function(e){return Yn.innerHTML=e.replace(/
/g,"\n"),Yn.innerText}(s),{queryInlineBot:l,resetInlineBot:u}=(0,n.uC)(),{username:m,query:h,canShowHelp:g}=function(e){const t=e.match(Wn);return t?{username:t[1],query:t[2],canShowHelp:""===t[2]&&!e.match(Xn)}:{username:"",query:"",canShowHelp:!1}}(d),p=m.toLowerCase(),f=(0,lt.Z)(h),I=(0,lt.Z)(m),v=null==a?void 0:a[p],{id:y,switchPm:Z,offset:P,results:C,isGallery:w,help:b}=v||{};(0,o.d4)((()=>{f!==h&&c()}),[f,h,c]),(0,o.d4)((()=>{e&&p&&t&&l({chatId:t,username:p,query:h})}),[h,e,l,t,p]);const S=(0,o.I4)((()=>{l({chatId:t,username:p,query:h,offset:P})}),[P,t,h,l,p]);return(0,o.d4)((()=>{e&&y&&(Z||null!=C&&C.length)?i():c()}),[y,e,i,C,Z,c]),I!==m&&u({username:I}),{isOpen:r,closeTooltip:c,loadMore:S,username:m,id:y,isGallery:w,switchPm:Z,results:C,help:g&&b?`@${m} ${b}`:void 0}}(Boolean(!Le.length&&O),l,Ie,G),{isOpen:Tt,close:Nt,filteredBotCommands:Bt}=function(e,t,s,n){const[a,r,i]=(0,ye.Z)(),[c,d]=(0,o.eJ)(),l=(0,o.I4)((e=>{s||n?Jn((()=>{const t=(s||n||[]).filter((({command:t})=>!e||t.includes(e)));d(t&&t.length?t:void 0)})):d(void 0)}),[s,n]);return(0,o.d4)((()=>{if(e&&t.length)if(t.startsWith("/")){const e=(0,Ln._)(t.substr(1)).match(ea);l(e?e[0]:"")}else i();else i()}),[l,t,e,i]),(0,o.d4)((()=>{c&&c.length?r():i()}),[c,r,i]),{isOpen:a,close:i,filteredBotCommands:c}}(Boolean(H&&H.length||_&&_.length),Ie,H,_),{isContextMenuOpen:At,handleContextMenu:xt,handleContextMenuClose:Lt,handleContextMenuHide:Ot}=(0,rs.Z)(ht,!(pt===ka.Send&&ft)),Ft=(0,o.Ye)((()=>(0,d.H5)(v,Z)),[v,Z]),Ut=v&&(0,d.Nl)(v),$t=(0,d.Hd)(v),{isStickerTooltipOpen:Dt,closeStickerTooltip:qt}=function(e,t,s,a=!1){const r=(0,o.Ye)((()=>(0,Ln._)(t).trim()),[t]),{loadStickersForEmoji:i,clearStickersForEmoji:c}=(0,n.uC)(),d=h.op&&1===(0,xn.Z)(r)||!h.op&&Boolean(t.match(/^]*?>$/g)),l=Boolean(s)&&d;return(0,o.d4)((()=>{var t;a||(e&&d?i({emoji:h.op?r:null===(t=r.match(/alt="(.+)"/))||void 0===t?void 0:t[1]}):!l&&d||c())}),[t,d,c,i,e,a]),{isStickerTooltipOpen:l,closeStickerTooltip:c}}(Boolean(U&&Ft.canSendStickers&&!Le.length),Ie,T,!r),{isEmojiTooltipOpen:Qt,closeEmojiTooltip:Gt,filteredEmojis:jt,insertEmoji:Ht}=(0,Vn.Z)(Boolean(U&&Ft.canSendStickers&&!Le.length),Ie,Q,void 0,ve,$,D,!r),zt=(0,o.I4)(((e,t=a.R2)=>{const s=window.getSelection(),n=document.getElementById(t),o=(0,Ct.Z)(e,["escape_html","emoji_html","br_html"]).join("").replace(/\u200b+/g,"​");if(s.rangeCount){const e=s.getRangeAt(0);if((0,Nn.R)(e,t))return function(e){const t=window.getSelection();if(null!=t&&t.getRangeAt&&t.rangeCount){const s=t.getRangeAt(0);s.deleteContents();const n=s.createContextualFragment(e),a=n.lastChild;s.insertNode(n),a?(s.setStartAfter(a),s.setEndAfter(a)):s.collapse(!1),t.removeAllRanges(),t.addRange(s)}}(o),void n.dispatchEvent(new Event("input",{bubbles:!0}))}ve(`${Be.current}${o}`),requestAnimationFrame((()=>{(0,Mn.Z)(n)}))}),[]),Vt=(0,o.I4)((()=>{const e=window.getSelection();if(e.rangeCount){const t=e.getRangeAt(0);if((0,Nn.R)(t,a.R2))return void document.execCommand("delete",!1)}ve(function(e){const t=document.createElement("div");t.contentEditable="true",t.style.position="absolute",t.style.left="-10000px",t.style.top="-10000px",t.innerHTML=e,document.body.appendChild(t);let s=t.lastChild;if(s.lastChild)for(;s.lastChild;)s=s.lastChild;const n=s.textContent.length,a=document.createRange(),o=window.getSelection();a.setStart(s,n),a.setEnd(s,n),o.removeAllRanges(),o.addRange(a),document.execCommand("delete",!1);const r=t.innerHTML;return document.body.removeChild(t),r}(Be.current))}),[]),Kt=(0,o.I4)(((e=!1)=>{e||ve(""),Oe([]),qt(),Se(),ke(void 0),vt(),Gt(),h.wB?setTimeout((()=>Ve()),350):Ve()}),[qt,Se,vt,Gt,Ve]),Yt=(0,o.sO)();Yt.current=ct,(0,o.d4)((()=>()=>{Yt.current(),Kt()}),[l,Kt,Yt]);const Wt=((e,t,s,r,i)=>{const{editMessage:c}=(0,n.uC)();return(0,o.d4)((()=>{s?(t(Hn(s.content.text)),requestAnimationFrame((()=>{const e=document.getElementById(a.R2);(0,Mn.Z)(e,!0)}))):t("")}),[s,t]),(0,o.I4)((()=>{const{text:t,entities:n}=(0,f.Z)(e.current);s&&(t||(0,d.u8)(s)?(c({messageId:s.id,text:t,entities:n}),r()):i())}),[c,s,e,i,r])})(Be,ve,c,Kt,Je);((e,t,s,r,i,c,d)=>{const{saveDraft:l,clearDraft:u}=(0,n.uC)(),m=(0,o.I4)(((e,t)=>{i.current.length&&!d?l({chatId:e,threadId:t,draft:(0,f.Z)(i.current)}):u({chatId:e,threadId:t})}),[u,d,i,l]),g=(0,o.Ye)((()=>(0,C.Ds)((e=>e()),a.r_,!1)),[t]),p=(0,lt.Z)(t),I=(0,lt.Z)(s);(0,o.d4)((()=>(_n=t,zn=s,()=>{_n=void 0,zn=void 0,m(t,s)})),[t,s,m]),(0,o.d4)((()=>{t===p&&s===I||e&&(c(Hn(e)),h.$b||requestAnimationFrame((()=>{const e=document.getElementById(a.R2);(0,Mn.Z)(e,!0)})))}),[t,s,e,c,m,p,I]);const v=(0,lt.Z)(r);(0,o.d4)((()=>{t&&s&&p===t&&I===s&&v!==r&&(r.length?g((()=>{_n===t&&zn===s&&m(t,s)})):m(t,s))}),[t,r,p,v,I,g,s,m]);const y=(0,o.I4)((()=>{t&&s&&m(t,s)}),[t,s,m]);(0,de.Z)(y),le(y)})(I,l,m,Ie,Be,ve,c),((e,t,s)=>{(0,o.d4)((()=>{async function n(n){if(!n.clipboardData)return;const o=document.activeElement;if(o&&![a.R2,a.nY].includes(o.id))return;const{items:r}=n.clipboardData,i=Array.from(r).find((e=>jn.includes(e.type)&&"file"===e.kind)),c=i&&i.getAsFile(),d=n.clipboardData.getData("text").substring(0,4096);if(n.preventDefault(),c||d){if(c&&!s){const e=await Tn(c.name,c,!0);t((t=>[...t,e]))}d&&e(d,null==o?void 0:o.id)}}return document.addEventListener("paste",n,!1),()=>{document.removeEventListener("paste",n,!1)}}),[e,s,t])})(zt,Oe,c);const Xt=(0,o.I4)((async(e,t)=>{Oe(await Promise.all(e.map((e=>Tn(e.name,e,t)))))}),[]),Jt=(0,o.I4)((async(e,t)=>{Oe([...Le,...await Promise.all(e.map((e=>Tn(e.name,e,t))))])}),[Le]),es=(0,o.I4)((()=>{Oe([])}),[]),ts=(0,o.I4)((async(e=!1,t)=>{if("connectionStateReady"!==y)return;let s=Le;if(ut){const e=await ct();if(e){const{blob:t,duration:n,waveform:a}=e;s=[await Tn("wonderful-voice-message.ogg",t,!1,{voice:{duration:n,waveform:a}})]}}const{text:n,entities:o}=(0,f.Z)(Be.current);if(!s.length&&!n&&!S)return;const r=s.length?1024:4096;if((null==n?void 0:n.length)>r){const e=n.length-r;return void X({data:{message:"MESSAGE_TOO_LONG_PLEASE_REMOVE_CHARACTERS",textParams:{"{EXTRA_CHARS_COUNT}":e,"{PLURAL_S}":e>1?"s":""},hasErrorKey:!0}})}const i=document.getElementById(a.R2);if(s.length||n){if($t&&!Ut){const e=(0,p.b)(q),t=Ze.current&&Math.floor(e-Ze.current),s=$t.nextSendDate&&$t.nextSendDate>e;if(t&&t<$t.seconds||s){const n=s?$t.nextSendDate-e:$t.seconds-t;return X({data:{message:ge("SlowModeHint",(0,N.k9)(n)),isSlowMode:!0,hasErrorKey:!1}}),void i.blur()}}Y({text:n,entities:o,attachments:s,scheduledAt:t,isSilent:e})}S&&te({scheduledAt:t,isSilent:e}),Ze.current=(0,p.b)(q),W({chatId:l,localOnly:!0}),h.cj&&i===document.activeElement&&An(i),requestAnimationFrame((()=>{Kt()}))}),[y,Le,ut,S,W,l,q,Kt,ct,X,$t,Ut,Y,te,ge]),ss=(0,o.I4)((()=>{Ve(),qe()}),[Ve,qe]),ns=(0,o.I4)((()=>{Qe(),We(),ze()}),[Qe,We,ze]),as=(0,o.I4)(((e,s=!1)=>{e={...e,isPreloadedGlobally:!0},t?(ke({sticker:e}),be()):(Y({sticker:e}),requestAnimationFrame((()=>{Kt(s)})))}),[t,be,Y,Kt]),os=(0,o.I4)((e=>{t?(ke({gif:e}),be()):(Y({gif:e}),requestAnimationFrame((()=>{Kt(!0)})))}),[t,be,Y,Kt]),is=(0,o.I4)((e=>{if("connectionStateReady"!==y)return;me({id:e.id,queryId:e.queryId});const t=document.getElementById(a.R2);h.cj&&t===document.activeElement&&An(t),W({chatId:l,localOnly:!0}),requestAnimationFrame((()=>{Kt()}))}),[l,W,y,Kt,me]),cs=(0,o.I4)((()=>{W({chatId:l,localOnly:!0}),requestAnimationFrame((()=>{Kt()}))}),[l,W,Kt]),ds=(0,o.I4)((e=>{t?(ke({poll:e}),ae(),be()):(Y({poll:e}),ae())}),[ae,be,Y,t]),ls=(0,o.I4)((()=>{t?(ke({isSilent:!0}),be()):ts(!0)}),[ts,be,t]),us=(0,o.I4)(((e,t=!1)=>{const{isSilent:s,...n}=Ee||{},a=Math.round(Math.max(e.getTime(),Date.now()+6e4)/1e3)+(t?0:q);Ee&&0!==Object.keys(n).length?(Y({...Ee,scheduledAt:a}),requestAnimationFrame((()=>{Kt()}))):ts(!!s,a),Se()}),[Se,ts,Kt,Ee,Y,q]),ms=(0,o.I4)((()=>{us(new Date(1e3*a.t4),!0)}),[us]),hs=(0,o.I4)((()=>{Se(),ke(void 0)}),[Se]),gs=(0,o.I4)((e=>{"stickers"===e?(J({query:""}),ee({query:void 0})):(ee({query:""}),J({query:void 0}))}),[J,ee]),ps=(0,o.I4)((()=>{const e=document.getElementById(a.R2);h.wB&&e===document.activeElement?(e.blur(),setTimeout((()=>{Qe(),ze()}),100)):ze()}),[ze,Qe]),fs=(0,o.I4)((()=>{const e=document.getElementById(a.R2);if(!h.wB||e!==document.activeElement)return Qe(),Ve(),void Ye();e.blur(),setTimeout((()=>{Qe(),Ve(),Ye()}),100)}),[Qe,Ve,Ye]),Is=(0,o.I4)((()=>{re({id:l,threadId:m,type:"scheduled"})}),[re,l,m]);(0,o.d4)((()=>{w&&h.wB&&Ve()}),[w,Ve]),(0,o.d4)((()=>{r&&(b?ot():setTimeout((()=>{rt()}),200))}),[b,rt,ot,r]);const vs=(0,o.I4)((()=>{switch(pt){case ka.Send:t?(ut&&dt(),be()):ts();break;case ka.Record:it();break;case ka.Edit:Wt()}}),[pt,t,it,Wt,ut,be,dt,ts]),ys=pt===ka.Record&&!Ft.canAttachMedia,Zs=(0,lt.Z)(c,!0),Ps=c||Zs,Cs=new Date;Cs.setSeconds(0),Cs.setMilliseconds(0);const ws=new Date;ws.setFullYear(ws.getFullYear()+1);let bs="SendMessage";switch(pt){case ka.Edit:bs="Save edited message";break;case ka.Record:bs=ys?"Conversation.DefaultRestrictedMedia":"AccDescrVoiceMessage"}const Ss=(0,ne.Z)("Composer",!b&&"shown",nt&&"hover-disabled"),Es=(0,ne.Z)("mobile-symbol-menu-button",!r&&"not-ready",tt?_e&&"menu-opened":_e&&"is-loading"),Ms=pt===ka.Edit?Wt:t?be:ts;return o.ZP.createElement("div",{className:Ss},Ft.canAttachMedia&&r&&o.ZP.createElement(Sa.Z,{containerId:"#middle-column-portals"},o.ZP.createElement(Ca,{isOpen:e!==at.t.None,withQuick:[e,Pe].includes(at.t.QuickFile),onHide:i,onFileSelect:Xt})),o.ZP.createElement(ya,{chatId:l,threadId:m,attachments:Le,caption:Le.length?Ie:"",groupChatMembers:B,currentUserId:x,usersById:L,recentEmojis:Q,isReady:r,onCaptionUpdate:ve,baseEmojiKeywords:$,emojiKeywords:D,addRecentEmoji:ce,onSend:t?be:ts,onFileAppend:Jt,onClear:es}),o.ZP.createElement(Pa,{isOpen:Boolean(E),onClear:ae,onSend:ds}),Ps&&o.ZP.createElement(ta,{isOpen:Xe,isSchedule:"scheduled"===g,onClose:et,message:Ps}),o.ZP.createElement(Ma,{isOpen:Ke,onClose:We,chatId:l,selectedSendAsId:K,sendAsIds:Te}),o.ZP.createElement(da,{isOpen:It,onClose:vt,onInsertUserName:yt,filteredUsers:Zt,usersById:L}),o.ZP.createElement(ca,{isOpen:Pt,botId:wt,allowedAttachmentOptions:Ft,isGallery:bt,inlineBotResults:Et,switchPm:St,onSelectResult:is,loadMore:Rt,onClose:Mt}),o.ZP.createElement(ha,{isOpen:Tt,withUsername:Boolean(_),botCommands:Bt,onClick:cs,onClose:Nt}),o.ZP.createElement("div",{id:"message-compose"},o.ZP.createElement("div",{className:"svg-appendix",ref:pe}),o.ZP.createElement(va,null),o.ZP.createElement(ba,{chatId:l,threadId:m,messageText:Le.length?"":Ie,disabled:!Ft.canAttachEmbedLinks}),o.ZP.createElement("div",{className:"message-input-wrapper"},Z&&!1!==H&&!ut&&!c&&o.ZP.createElement(oa,{className:(0,ne.Z)("bot-commands",De&&"activated"),round:!0,disabled:void 0===H,color:"translucent",onActivate:ss,ariaLabel:"Open bot command keyboard"},o.ZP.createElement("i",{className:"icon-bot-commands-filled"})),!(null==Te||!Te.length)&&(z||V)&&o.ZP.createElement(Me.Z,{round:!0,color:"translucent",onClick:Ke?We:fs,ariaLabel:ge("SendMessageAsTitle"),className:(0,ne.Z)("send-as-button",xe.current&&"appear-animation")},o.ZP.createElement(_t.Z,{user:z,chat:V,size:"tiny"})),h.wB?o.ZP.createElement(Me.Z,{className:Es,round:!0,color:"translucent",onClick:_e?Ve:ps,ariaLabel:"Choose emoji, sticker or GIF"},o.ZP.createElement("i",{className:"icon-smile"}),o.ZP.createElement("i",{className:"icon-keyboard"}),_e&&!tt&&o.ZP.createElement(Ae.Z,{color:"gray"})):o.ZP.createElement(oa,{className:_e?"activated":"",round:!0,color:"translucent",onActivate:ns,ariaLabel:"Choose emoji, sticker or GIF"},o.ZP.createElement("i",{className:"icon-smile"})),o.ZP.createElement(fa.Z,{id:"message-input-text",chatId:l,threadId:m,html:Le.length?"":Ie,placeholder:ut&&Re<=600?"":k||ge("Message"),forcedPlaceholder:kt,canAutoFocus:r&&!Le.length,shouldSuppressFocus:h.wB&&_e,shouldSuppressTextFormatter:Qt||It||Pt,onUpdate:ve,onSend:Ms,onSuppressedFocus:Ve}),j&&Boolean(wt)&&o.ZP.createElement(Ae.Z,{color:"gray"}),R&&o.ZP.createElement(Me.Z,{round:!0,faded:!0,className:"scheduled-button",color:"translucent",onClick:Is,ariaLabel:"Open scheduled messages"},o.ZP.createElement("i",{className:"icon-schedule"})),M&&!ut&&!c&&o.ZP.createElement(oa,{className:Fe?"activated":"",round:!0,color:"translucent",onActivate:Ue,ariaLabel:"Open bot command keyboard"},o.ZP.createElement("i",{className:"icon-bot-command"})),!ut&&!c&&o.ZP.createElement(oa,{className:Ge?"activated":"",round:!0,color:"translucent",onActivate:je,ariaLabel:"Add an attachment"},o.ZP.createElement("i",{className:"icon-attach"})),ut&&mt&&o.ZP.createElement("span",{className:"recording-state"},(0,N.rM)(mt-gt.current)),o.ZP.createElement(ua,{chatId:l,threadId:m,isOpen:Dt,onStickerSelect:as}),o.ZP.createElement(ma.Z,{isOpen:Qt,emojis:jt,onClose:Gt,onEmojiSelect:Ht,addRecentEmoji:ce}),o.ZP.createElement(ra,{isOpen:Ge,allowedAttachmentOptions:Ft,onFileSelect:Xt,onPollCreate:se,onClose:He}),M&&o.ZP.createElement(pa,{messageId:M,isOpen:Fe,onClose:$e}),H&&o.ZP.createElement(Za,{isOpen:De,botCommands:H,onClose:Qe}),o.ZP.createElement(ia,{chatId:l,threadId:m,isOpen:_e,allowedAttachmentOptions:Ft,onLoad:st,onClose:Ve,onEmojiSelect:zt,onStickerSelect:as,onGifSelect:os,onRemoveSymbol:Vt,onSearchOpen:gs,addRecentEmoji:ce}))),ut&&o.ZP.createElement(Me.Z,{round:!0,color:"danger",className:"cancel",onClick:ct,ariaLabel:"Cancel voice recording"},o.ZP.createElement("i",{className:"icon-delete"})),o.ZP.createElement(Me.Z,{ref:ht,round:!0,color:"secondary",className:(0,ne.Z)(pt,!r&&"not-ready",ut&&"recording"),disabled:ys,ariaLabel:ge(bs),onClick:vs,onContextMenu:pt===ka.Send&&ft?xt:void 0},o.ZP.createElement("i",{className:"icon-send"}),o.ZP.createElement("i",{className:"icon-microphone-alt"}),o.ZP.createElement("i",{className:"icon-check"})),ft&&o.ZP.createElement(la,{isOpen:At,onSilentSend:P?void 0:ls,onScheduleSend:t?void 0:be,onClose:Lt,onCloseAnimationEnd:Ot}),o.ZP.createElement(Ea,{isOpen:we,withTimePicker:!0,selectedAt:Cs.getTime(),maxAt:(0,N._F)(ws),isFutureMode:!0,secondButtonLabel:s?ge("Schedule.SendWhenOnline"):void 0,onClose:hs,onSubmit:us,onSecondButtonClick:s?ms:void 0}))}))),Ta=(0,o.X$)((e=>{const{isActive:t}=e,s=(0,qe.Z)(De.gl.Extra,"MobileSearch",!t,!0);return s?o.ZP.createElement(s,e):void 0})),Na=(0,o.X$)((e=>{const{isActive:t}=e,s=(0,qe.Z)(De.gl.Extra,"MessageSelectToolbar",!t);return s?o.ZP.createElement(s,e):void 0})),Ba=(0,o.X$)((e=>{const{isOpen:t}=e,s=(0,qe.Z)(De.gl.Extra,"UnpinAllMessagesModal",!t);return s?o.ZP.createElement(s,e):void 0})),Aa=(0,o.X$)((e=>{const{isOpen:t}=e,s=(0,qe.Z)(De.gl.Extra,"PaymentModal",!t);return s?o.ZP.createElement(s,e):void 0})),xa=(0,o.X$)((e=>{const{isOpen:t}=e,s=(0,qe.Z)(De.gl.Extra,"ReceiptModal",!t);return s?o.ZP.createElement(s,e):void 0})),La=(0,o.X$)((e=>{const{isOpen:t}=e,s=(0,qe.Z)(De.gl.Extra,"SeenByModal",!t);return s?o.ZP.createElement(s,e):void 0})),Oa=h.wB?450+a.fK:void 0;function Fa(e){return"file"===e.kind&&e.type&&a.oG.has(e.type)}const Ua=(0,o.X$)((0,n.c$)((e=>{const t=(0,i.Pu)(e),{isBlurred:s,background:n,backgroundColor:a,patternColor:o}=e.settings.themes[t]||{},{messageLists:r}=e.messages,c=(0,i.Bt)(e),{isLeftColumnShown:l,chats:{listIds:m}}=e,g={theme:t,customBackground:n,backgroundColor:a,patternColor:o,isLeftColumnShown:l,isRightColumnShown:(0,i.Jf)(e),isBackgroundBlurred:s,isMobileSearchActive:Boolean(h.wB&&(0,i.n5)(e)),isSelectModeActive:(0,i.CA)(e),isPaymentModalOpen:e.payment.isPaymentModalOpen,isReceiptModalOpen:Boolean(e.payment.receipt),isSeenByModalOpen:Boolean(e.seenByModal),animationLevel:e.settings.byKey.animationLevel,currentTransitionKey:Math.max(0,e.messages.messageLists.length-1)};if(!c||!m.active)return g;const{chatId:p,threadId:f,type:I}=c,v=(0,i.Z1)(e,p),y=(0,i.IK)(e,p),Z=(0,i.KB)(e,p),{chatId:P,messageId:C}=e.audioPlayer,w=v&&(0,d.Qm)(v,f),b=(0,i.pk)(e,p),S="pinned"===I,E="scheduled"===I,M="thread"===I&&f===u._f,k=Boolean(v&&(0,d.eA)(v)),R=Boolean(v&&M&&(k||(0,d.ZV)(v))&&v.isNotJoined),T=Boolean(y&&(0,i.s4)(e,y.id)),N=!T&&b;return{...g,chatId:p,threadId:f,messageListType:I,isPrivate:(0,d.YC)(p),canPost:!S&&(!v||w)&&!b,isPinnedMessageList:S,isScheduledMessageList:E,currentUserBannedRights:null==v?void 0:v.currentUserBannedRights,defaultBannedRights:null==v?void 0:v.defaultBannedRights,hasPinnedOrAudioPlayer:f!==u._f||Boolean(!S&&(null==Z?void 0:Z.length))||Boolean(P&&C),pinnedMessagesCount:Z?Z.length:0,shouldSkipHistoryAnimations:e.shouldSkipHistoryAnimations,messageLists:r,isChannel:k,canSubscribe:R,canStartBot:N,canRestartBot:T}}))((({chatId:e,threadId:t,messageListType:s,isPrivate:r,isPinnedMessageList:i,messageLists:c,canPost:l,currentUserBannedRights:u,defaultBannedRights:m,hasPinnedOrAudioPlayer:g,pinnedMessagesCount:p,customBackground:f,theme:I,backgroundColor:v,patternColor:y,isLeftColumnShown:Z,isRightColumnShown:P,isBackgroundBlurred:C,isMobileSearchActive:w,isSelectModeActive:b,isPaymentModalOpen:S,isReceiptModalOpen:E,isSeenByModalOpen:M,animationLevel:k,shouldSkipHistoryAnimations:R,currentTransitionKey:T,isChannel:N,canSubscribe:B,canStartBot:A,canRestartBot:x})=>{const{openChat:L,unpinAllMessages:O,loadUser:F,closeLocalTextSearch:U,exitMessageSelectMode:$,closePaymentModal:D,clearReceipt:q,joinChannel:Q,sendBotCommand:G,restartBot:j}=(0,n.uC)(),{width:H}=ct(),_=(0,Ce.Z)(),[z,V]=(0,o.eJ)(at.t.None),[K,Y]=(0,o.eJ)(),[W,X]=(0,o.eJ)(),[J,ee]=(0,o.eJ)(!1),te=g&&(Ha._m&&H=a.ks&&H{e===a.oB&&i(!0)}),[e]),{isReady:r&&!d,handleOpenEnd:e!==a.oB?function(e){"transform"===e.propertyName&&e.target===e.currentTarget&&i(Boolean(n))}:void 0,handleSlideStop:e!==a.oB?function(){i(!0)}:void 0}}(k,T,ge,e);(0,o.d4)((()=>e?(0,fe.Z)((()=>{L({id:void 0})})):void 0),[e,L]),(0,ue.Z)((()=>{V(at.t.None),Y(void 0),X(void 0)}),[e]),(0,o.d4)((()=>{const{visualViewport:e}=window;if(!e)return;const t=()=>{window.visualViewport.height!==document.documentElement.clientHeight?document.body.classList.add("keyboard-visible"):document.body.classList.remove("keyboard-visible")};return e.addEventListener("resize",t),()=>{e.removeEventListener("resize",t)}}),[]),(0,o.d4)((()=>{r&&F({userId:e})}),[e,r,F]);const we=(0,o.I4)((e=>{if(h.$b)return;const{items:t}=e.dataTransfer||{},s=t&&Array.from(t).filter((e=>"text/uri-list"!==e.type)).every(Fa);V(s?at.t.QuickFile:at.t.Document)}),[]),be=(0,o.I4)((()=>{V(at.t.None)}),[]),Se=(0,o.I4)((()=>{ee(!0)}),[]),Ee=(0,o.I4)((()=>{ee(!1)}),[]),ke=(0,o.I4)((()=>{O({chatId:e}),Ee(),L({id:e})}),[O,L,Ee,e]),Re=(0,o.I4)((()=>{L({id:e})}),[L,e]),Te=(0,o.I4)((()=>{Q({chatId:e})}),[Q,e]),Ne=(0,o.I4)((()=>{G({command:"/start"})}),[G]),Be=(0,o.I4)((()=>{j({chatId:e})}),[e,j]),Ae=((e,t)=>{const[s,n]=(0,o.eJ)(t);return(0,o.d4)((()=>{t&&(t.startsWith("#")?n(t):rt.fetch(a.fo,e,rt.Type.Blob).then((e=>{const t=URL.createObjectURL(e);(0,it.pt)(t).then((()=>{n(`url(${t})`)}))})))}),[t,e]),t?s:void 0})(I,f),xe=(0,ne.Z)(le&&"has-header-tools",f&&"custom-bg-image",v&&"custom-bg-color",f&&C&&"blurred",h.aZ?"mask-image-disabled":"mask-image-enabled"),Le=(0,ne.Z)("messaging-disabled",!b&&"shown"),Oe=(0,d.q8)(_,u,m),{composerHiddenScale:Fe,toolbarHiddenScale:Ue,composerTranslateX:$e,toolbarTranslateX:De,unpinHiddenScale:qe,toolbarForUnpinHiddenScale:Qe}=(0,o.Ye)((()=>function(e,t){const s=e<=a.l3?16:32,n=function(e){if(e>a._m){const t=Math.min(Math.max(.25*e,288),424),s=Math.min(.25*e,424);return Math.min(e-t-s,mt)}if(e>a.ks){const t=Math.min(Math.max(.4*e,288),424);return Math.min(e-t,mt)}return e>mt?mt:e}(e),o=e<=a.l3?54:64,r=t?n-s-o:n-s,i=e>a.l3?Math.min(n-s,512):n-s,c=i/r,d=r/i;return{composerHiddenScale:c,toolbarHiddenScale:d,composerTranslateX:t?o/2*d:0,toolbarTranslateX:t?o/2*-1*c:0,unpinHiddenScale:i/258,toolbarForUnpinHiddenScale:258/i}}(H,de)),[de,H]),Ge=(0,ne.Z)("middle-column-footer",!de&&"no-composer",de&&W&&!b&&"with-notch");(0,pe.ZP)(se&&ae,(()=>{L({id:void 0},{forceSyncOnIOs:!0})}),void 0,void 0,void 0,(null==c?void 0:c.map(ot.q))||[]),(0,pe.ZP)(w,U),(0,pe.ZP)(b,$);const je=Boolean(!i&&!de&&Oe),He=Boolean(ce||re||ie||i),_e=Boolean(je||b||i);return o.ZP.createElement("div",{id:"MiddleColumn",className:xe,onTransitionEnd:ye,style:`\n --composer-hidden-scale: ${Fe};\n --toolbar-hidden-scale: ${Ue};\n --unpin-hidden-scale: ${qe};\n --toolbar-unpin-hidden-scale: ${Qe};\n --composer-translate-x: ${$e}px;\n --toolbar-translate-x: ${De}px;\n --pattern-color: ${y};\n --theme-background-color:\n ${v||("dark"===I?a.It:a.p3)};\n `,onClick:h.p7&&Z?Re:void 0},o.ZP.createElement("div",{id:"middle-column-bg",style:Ae?`--custom-background: ${Ae}`:void 0}),o.ZP.createElement("div",{id:"middle-column-portals"}),se&&ae&&o.ZP.createElement(o.ZP.Fragment,null,o.ZP.createElement("div",{className:"messages-layout",onDragEnter:de?we:void 0},o.ZP.createElement(Vt,{chatId:se,threadId:ae,messageListType:oe,isReady:ve}),o.ZP.createElement(Ze.Z,{name:R?"none":k===a.zy?"slide":"fade",activeKey:T,shouldCleanup:!0,cleanupExceptionKey:Ie,onStop:Pe},(()=>o.ZP.createElement(o.ZP.Fragment,null,o.ZP.createElement(Sn,{key:`${se}-${ae}-${oe}`,chatId:se,threadId:ae,type:oe,canPost:de,hasTools:le,onFabToggle:Y,onNotchToggle:X,isReady:ve,withBottomShift:He}),o.ZP.createElement("div",{className:Ge},de&&o.ZP.createElement(Ra,{chatId:se,threadId:ae,messageListType:oe,dropAreaState:z,onDropHide:be,isReady:ve}),i&&o.ZP.createElement("div",{className:"middle-column-footer-button-container",dir:_.isRtl?"rtl":void 0},o.ZP.createElement(Me.Z,{size:"tiny",fluid:!0,color:"secondary",className:"unpin-all-button",onClick:Se},o.ZP.createElement("i",{className:"icon-unpin"}),o.ZP.createElement("span",null,_("Chat.Pinned.UnpinAll",p,"i")))),je&&o.ZP.createElement("div",{className:Le},o.ZP.createElement("div",{className:"messaging-disabled-inner"},o.ZP.createElement("span",null,Oe))),h.wB&&re&&o.ZP.createElement("div",{className:"middle-column-footer-button-container",dir:_.isRtl?"rtl":void 0},o.ZP.createElement(Me.Z,{size:"tiny",fluid:!0,ripple:!0,className:"join-subscribe-button",onClick:Te},_(he?"ProfileJoinChannel":"ProfileJoinGroup"))),h.wB&&ie&&o.ZP.createElement("div",{className:"middle-column-footer-button-container",dir:_.isRtl?"rtl":void 0},o.ZP.createElement(Me.Z,{size:"tiny",fluid:!0,ripple:!0,className:"join-subscribe-button",onClick:Ne},_("BotStart"))),h.wB&&ce&&o.ZP.createElement("div",{className:"middle-column-footer-button-container",dir:_.isRtl?"rtl":void 0},o.ZP.createElement(Me.Z,{size:"tiny",fluid:!0,ripple:!0,className:"join-subscribe-button",onClick:Be},_("BotRestart"))),o.ZP.createElement(Na,{messageListType:oe,isActive:b,canPost:de}),o.ZP.createElement(Aa,{isOpen:Boolean(S),onClose:D}),o.ZP.createElement(xa,{isOpen:Boolean(E),onClose:q}),o.ZP.createElement(La,{isOpen:M}))))),o.ZP.createElement(En,{isShown:me,canPost:de,withExtraShift:_e})),h.wB&&o.ZP.createElement(Ta,{isActive:Boolean(w)})),e&&o.ZP.createElement(Ba,{isOpen:J,chatId:e,pinnedMessagesCount:p,onClose:Ee,onUnpin:ke}))}))),$a=(0,C.Ds)((e=>e()),200,!1);var Da;!function(e){e[e.Profile=0]="Profile",e[e.MemberList=1]="MemberList",e[e.SharedMedia=2]="SharedMedia",e[e.Search=3]="Search",e[e.Management=4]="Management",e[e.ManageInitial=5]="ManageInitial",e[e.ManageChannelSubscribers=6]="ManageChannelSubscribers",e[e.ManageChatAdministrators=7]="ManageChatAdministrators",e[e.ManageChatPrivacyType=8]="ManageChatPrivacyType",e[e.ManageDiscussion=9]="ManageDiscussion",e[e.ManageGroupPermissions=10]="ManageGroupPermissions",e[e.ManageGroupRemovedUsers=11]="ManageGroupRemovedUsers",e[e.ManageGroupUserPermissionsCreate=12]="ManageGroupUserPermissionsCreate",e[e.ManageGroupUserPermissions=13]="ManageGroupUserPermissions",e[e.ManageGroupRecentActions=14]="ManageGroupRecentActions",e[e.ManageGroupAdminRights=15]="ManageGroupAdminRights",e[e.ManageGroupNewAdminRights=16]="ManageGroupNewAdminRights",e[e.ManageGroupMembers=17]="ManageGroupMembers",e[e.ManageGroupAddAdmins=18]="ManageGroupAddAdmins",e[e.StickerSearch=19]="StickerSearch",e[e.GifSearch=20]="GifSearch",e[e.PollResults=21]="PollResults",e[e.AddingMembers=22]="AddingMembers"}(Da||(Da={}));const qa=(0,o.X$)((0,n.c$)(((e,{chatId:t,isProfile:s,isManagement:n})=>{const{query:a}=(0,i.n5)(e)||{},{query:o}=(0,i.y5)(e)||{},{query:r}=(0,i.yN)(e)||{},c=t?(0,i.Z1)(e,t):void 0,l=c&&(0,d.eA)(c),u=s&&t&&(0,d.YC)(t)?(0,i.dy)(e,t):void 0,m=u&&(0,d.kw)(u);return{canManage:Boolean(!n&&s&&!m&&c&&!(0,i.FM)(e,c.id)&&((0,d.YC)(c.id)||((0,d.Nl)(c)||c.isCreator)&&!c.isNotJoined)),canAddContact:m,isChannel:l,userId:null==u?void 0:u.id,messageSearchQuery:a,stickerSearchQuery:o,gifSearchQuery:r}}))((({isColumnOpen:e,isProfile:t,isSearch:s,isManagement:a,isStickerSearch:r,isGifSearch:i,isPollResults:c,isAddingChatMembers:d,profileState:l,managementScreen:u,canAddContact:g,userId:p,canManage:f,isChannel:I,onClose:v,messageSearchQuery:y,stickerSearchQuery:Z,gifSearchQuery:P,shouldSkipAnimation:C})=>{var w;const{setLocalTextSearchQuery:b,setStickerSearchQuery:S,setGifSearchQuery:E,searchTextMessagesLocal:M,toggleManagement:k,openHistoryCalendar:R,addContact:T}=(0,n.uC)(),B=(0,o.sO)(null),A=(0,o.I4)((e=>{b({query:e}),e.length&&$a(M)}),[M,b]),x=(0,o.I4)((e=>{S({query:e})}),[S]),L=(0,o.I4)((e=>{E({query:e})}),[E]),O=(0,o.I4)((()=>{T({userId:p})}),[T,p]),[F,U]=(0,o.eJ)(!e);(0,o.d4)((()=>{setTimeout((()=>{U(!e)}),300)}),[e]);const $=(0,Ce.Z)(),D=t?l===m.vi.Profile?Da.Profile:l===m.vi.SharedMedia?Da.SharedMedia:l===m.vi.MemberList?Da.MemberList:-1:s?Da.Search:c?Da.PollResults:r?Da.StickerSearch:i?Da.GifSearch:d?Da.AddingMembers:a?u===m.u1.Initial?Da.ManageInitial:u===m.u1.ChatPrivacyType?Da.ManageChatPrivacyType:u===m.u1.Discussion?Da.ManageDiscussion:u===m.u1.ChannelSubscribers?Da.ManageChannelSubscribers:u===m.u1.GroupPermissions?Da.ManageGroupPermissions:u===m.u1.ChatAdministrators?Da.ManageChatAdministrators:u===m.u1.GroupRemovedUsers?Da.ManageGroupRemovedUsers:u===m.u1.GroupUserPermissionsCreate?Da.ManageGroupUserPermissionsCreate:u===m.u1.GroupUserPermissions?Da.ManageGroupUserPermissions:u===m.u1.GroupRecentActions?Da.ManageGroupRecentActions:u===m.u1.ChatAdminRights?Da.ManageGroupAdminRights:u===m.u1.ChatNewAdminRights?Da.ManageGroupNewAdminRights:u===m.u1.GroupMembers?Da.ManageGroupMembers:u===m.u1.GroupAddAdmins?Da.ManageGroupAddAdmins:void 0:void 0,q=null!==(w=(0,pt.Z)(D,!0))&&void 0!==w?w:-1;function Q(){if(-1!==q)switch(q){case Da.PollResults:return o.ZP.createElement("h3",null,$("PollResults"));case Da.Search:return o.ZP.createElement(o.ZP.Fragment,null,o.ZP.createElement(ke.Z,{parentContainerClassName:"RightSearch",value:y,onChange:A}),o.ZP.createElement(Me.Z,{round:!0,size:"smaller",color:"translucent",onClick:()=>R({selectedAt:(0,N._F)(Date.now())}),ariaLabel:"Search messages by date"},o.ZP.createElement("i",{className:"icon-calendar"})));case Da.AddingMembers:return o.ZP.createElement("h3",null,$(I?"ChannelAddSubscribers":"GroupAddMembers"));case Da.ManageInitial:return o.ZP.createElement("h3",null,$("Edit"));case Da.ManageChatPrivacyType:return o.ZP.createElement("h3",null,$(I?"ChannelTypeHeader":"GroupTypeHeader"));case Da.ManageDiscussion:return o.ZP.createElement("h3",null,$("Discussion"));case Da.ManageChatAdministrators:return o.ZP.createElement("h3",null,$("ChannelAdministrators"));case Da.ManageGroupRecentActions:return o.ZP.createElement("h3",null,$("Group.Info.AdminLog"));case Da.ManageGroupAdminRights:return o.ZP.createElement("h3",null,$("EditAdminRights"));case Da.ManageGroupNewAdminRights:return o.ZP.createElement("h3",null,$("SetAsAdmin"));case Da.ManageGroupPermissions:return o.ZP.createElement("h3",null,$("ChannelPermissions"));case Da.ManageGroupRemovedUsers:return o.ZP.createElement("h3",null,$("ChannelBlockedUsers"));case Da.ManageGroupUserPermissionsCreate:return o.ZP.createElement("h3",null,$("ChannelAddException"));case Da.ManageGroupUserPermissions:return o.ZP.createElement("h3",null,$("UserRestrictions"));case Da.ManageGroupAddAdmins:return o.ZP.createElement("h3",null,$("Channel.Management.AddModerator"));case Da.StickerSearch:return o.ZP.createElement(ke.Z,{value:Z,placeholder:$("SearchStickersHint"),autoFocusSearch:!0,onChange:x});case Da.GifSearch:return o.ZP.createElement(ke.Z,{value:P,placeholder:$("SearchGifsTitle"),autoFocusSearch:!0,onChange:L});case Da.SharedMedia:return o.ZP.createElement("h3",null,$("SharedMedia"));case Da.ManageChannelSubscribers:return o.ZP.createElement("h3",null,$("ChannelSubscribers"));case Da.MemberList:case Da.ManageGroupMembers:return o.ZP.createElement("h3",null,$("GroupMembers"));default:return o.ZP.createElement(o.ZP.Fragment,null,o.ZP.createElement("h3",null,"Profile"),o.ZP.createElement("section",{className:"tools"},g&&o.ZP.createElement(Me.Z,{round:!0,color:"translucent",size:"smaller",ariaLabel:$("AddContact"),onClick:O},o.ZP.createElement("i",{className:"icon-add-user"})),f&&o.ZP.createElement(Me.Z,{round:!0,color:"translucent",size:"smaller",ariaLabel:$("Edit"),onClick:k},o.ZP.createElement("i",{className:"icon-edit"}))))}}const G=h.wB||D===Da.SharedMedia||D===Da.MemberList||D===Da.AddingMembers||a,j=(0,ne.Z)("animated-close-icon",G&&"state-back",(F||C)&&"no-transition");return o.ZP.createElement("div",{className:"RightHeader"},o.ZP.createElement(Me.Z,{className:"close-button",round:!0,color:"translucent",size:"smaller",onClick:v,ariaLabel:$(G?"Common.Back":"Common.Close")},o.ZP.createElement("div",{ref:B,className:j})),o.ZP.createElement(Ze.Z,{name:F||C?"none":"slide-fade",activeKey:q},Q))})));var Qa=s(91),Ga=s(7407);function ja(e,t,s,n){const[o,r]=(0,Ga.Z)(s?t:void 0,n,void 0,a.Vk);return[o,r,!(!o||!n||o[0]===n[0])]}function Ha(e,t,s,n,r,i){const c=(0,o.sO)();(0,ue.Z)((()=>{t===e&&r&&i&&(c.current=(0,d.R5)(r,i,e).reverse())}),[r,i,t,e]);const[l,u]=(0,Ga.Z)(n?s:void 0,c.current,void 0,"media"===e?a.EN:a.pn);return[l,u,!(!l||!c.current||l[0]===c.current[0])]}const _a=(0,C.P2)((e=>e()),250,!1);let za=!1;var Va=s(1273),Ka=s(1876),Ya=s(787),Wa=s(180),Xa=s(3709),Ja=s(5418),eo=s(7262),to=s(1151),so=s(2275);const no=[{type:"media",title:"SharedMediaTab2"},{type:"documents",title:"SharedFilesTab2"},{type:"links",title:"SharedLinksTab2"},{type:"audio",title:"SharedMusicTab2"},{type:"voice",title:"SharedVoiceTab2"}];function ao(e){return[`.shared-media-transition > div:only-child > .${e}-list > .scroll-item`,`.shared-media-transition > .Transition__slide--active > .${e}-list > .scroll-item`].join(", ")}const oo=(0,o.X$)((0,n.c$)(((e,{chatId:t,userId:s})=>{var n,a;const o=(0,i.Z1)(e,t),r=(0,i.Zw)(e,s||t),{currentType:c,resultsByType:l}=(0,i.we)(e)||{},{foundIds:u}=l&&c&&l[c]||{},{byId:m,statusesById:h}=e.users,{byId:g}=e.chats,p=o&&(0,d.Bf)(o),f=o&&(0,d.eA)(o),I=p||f&&(0,d.Nl)(o),v=null==o||null===(n=o.fullInfo)||void 0===n?void 0:n.members,y=I&&o&&o.fullInfo&&!o.fullInfo.canViewMembers,Z=I&&o&&((0,d.VE)(o,"inviteUsers")||o.isCreator),P=I&&o&&((0,d.VE)(o,"banUsers")||o.isCreator),C=(0,i.xs)(e,t);let w,b,S;return s?b=s:(0,d.YC)(t)&&(b=t),b&&(S=(0,i.dy)(e,b),w=S&&!S.isSelf&&!(0,d.cS)(S)),{theme:(0,i.Pu)(e),isChannel:f,resolvedUserId:b,chatMessages:r,foundIds:u,mediaSearchType:c,hasCommonChatsTab:w,hasMembersTab:I,areMembersHidden:y,canAddMembers:Z,canDeleteMembers:P,currentUserId:e.currentUserId,isRightColumnShown:(0,i.Jf)(e),isRestricted:null==o?void 0:o.isRestricted,lastSyncTime:e.lastSyncTime,serverTimeOffset:e.serverTimeOffset,activeDownloadIds:C,usersById:m,userStatusesById:h,chatsById:g,isChatProtected:null==o?void 0:o.isProtected,...I&&v&&{members:v},...w&&S&&{commonChatIds:null===(a=S.commonChats)||void 0===a?void 0:a.ids}}}))((({chatId:e,profileState:t,onProfileStateChange:s,theme:r,isChannel:i,resolvedUserId:c,currentUserId:l,chatMessages:g,foundIds:p,mediaSearchType:f,hasCommonChatsTab:I,hasMembersTab:v,areMembersHidden:y,canAddMembers:Z,canDeleteMembers:P,commonChatIds:C,members:w,usersById:b,userStatusesById:S,chatsById:E,isRightColumnShown:M,isRestricted:k,lastSyncTime:R,activeDownloadIds:T,serverTimeOffset:N,isChatProtected:B})=>{const{setLocalMediaSearchType:A,loadMoreMembers:x,loadCommonChats:L,openChat:O,searchMediaMessagesLocal:F,openMediaViewer:U,openAudioPlayer:$,openUserInfo:D,focusMessage:q,loadProfilePhotos:Q,setNewChatMembersDialogState:G}=(0,n.uC)(),j=(0,o.sO)(null),H=(0,o.sO)(null),_=(0,Ce.Z)(),[z,V]=(0,o.eJ)(0),[K,Y]=(0,o.eJ)(),W=(0,o.Ye)((()=>[...v?[{type:"members",title:i?"ChannelSubscribers":"GroupMembers"}]:[],...no,...I?[{type:"commonChats",title:"SharedGroupsTab2"}]:[]]),[I,v,i]),X=W[z].type,[J,ee,te,se]=function(e,t,s,n,a,r,i,c,l,u,m,h,g,p,f,I=0){const v="members"!==a&&r?r:a,y=(0,o.Ye)((()=>{if(i&&l&&u)return(0,d.Z0)(i.map((({userId:e})=>e)),l,u,void 0,I)}),[i,I,l,u]),Z=(0,o.Ye)((()=>{if(c&&m)return(0,d.ih)(c,m,!0)}),[m,c]),[P,C,w]=ja(0,t,f,y),[b,S,E]=Ha("media",v,n,f,h,g),[M,k,R]=Ha("documents",v,n,f,h,g),[T,N,B]=Ha("links",v,n,f,h,g),[A,x,L]=Ha("audio",v,n,f,h,g),[O,F,U]=Ha("voice",v,n,f,h,g),[$,D,q]=ja(0,s,f,Z);let Q,G,j=!1;switch(v){case"members":Q=P,G=C,j=w;break;case"commonChats":Q=$,G=D,j=q;break;case"media":Q=b,G=S,j=E;break;case"documents":Q=M,G=k,j=R;break;case"links":Q=T,G=N,j=B;break;case"audio":Q=A,G=x,j=L;break;case"voice":Q=O,G=F,j=U}return[v,Q,G,j]}(0,x,L,F,X,f,w,C,b,S,E,g,p,0,R,N),ne=W.findIndex((({type:e})=>e===J)),{handleScroll:ae}=function(e,t,s,n){(0,Yt.Z)((([s])=>{if(s&&s!==t){const s=e.current,a=s.querySelector(".TabList");s.scrollTop{za=!1}),350))}}),[t,n]),(0,Yt.Z)((([t])=>{if(s!==m.vi.Profile||s===t)return;const a=e.current;if(!a)return;const o=a.querySelector(".TabList");!o||o.offsetTop>a.scrollTop||(za=!0,(0,ss.Z)(a,a.firstElementChild,"start",void 0,2*a.offsetHeight),setTimeout((()=>{za=!1}),350),n(s))}),[s]);const a=(0,o.I4)((()=>{const s=e.current;if(!s)return;const a=s.querySelector(".TabList");if(!a)return;let o=m.vi.Profile;s.scrollTop>=a.offsetTop&&(o="members"===t?m.vi.MemberList:m.vi.SharedMedia),n(o)}),[e,n,t]);return(0,o.d4)((()=>{za||a()}),[a,t]),{handleScroll:(0,o.I4)((()=>{za||_a(a)}),[a])}}(j,X,t,s),{applyTransitionFix:oe,releaseTransitionFix:re}=function(e,t=".Transition.shared-media-transition"){return(0,o.d4)((()=>{function s(){const s=e.current,n=s.querySelector(t),a=s.querySelector(".TabList");n&&a&&(n.style.minHeight=s.offsetHeight-a.offsetHeight+"px")}return s(),window.addEventListener("resize",s,!1),()=>{window.removeEventListener("resize",s,!1)}}),[e,t]),{applyTransitionFix:(0,o.I4)((()=>{const t=e.current;if("hidden"!==t.style.overflowY){const e=t.offsetWidth-t.clientWidth;t.style.overflowY="hidden",t.style.marginRight=`${e}px`}}),[e]),releaseTransitionFix:(0,o.I4)((()=>{const t=e.current;t.style.overflowY="scroll",t.style.marginRight="0"}),[e])}}(j),[ie,ce]=(()=>{const[e,t]=(0,o.eJ)(!1);return[e,(0,o.I4)((()=>{t((e=>!e))}),[])]})(),de=(0,o.I4)((()=>{re(),ce()}),[re,ce]),le=(0,o.I4)((()=>{G(m.WB.InProgress)}),[G]);(0,o.d4)((()=>{A({mediaType:X})}),[A,X]);const ue=c||e;(0,o.d4)((()=>{R&&Q({profileId:ue})}),[Q,ue,R]);const me=(0,o.I4)((e=>{U({chatId:ue,threadId:u._f,messageId:e,origin:m.bZ.SharedMedia})}),[ue,U]),he=(0,o.I4)((e=>{$({chatId:ue,messageId:e})}),[ue,$]),ge=(0,o.I4)((e=>{D({id:e})}),[D]),pe=(0,o.I4)((e=>{q({chatId:ue,messageId:e})}),[ue,q]),fe=(0,o.I4)((()=>{Y(void 0)}),[]);let Ie;(0,o.d4)((()=>{if(H.current&&h.$b)return(0,Le.s)(H.current,{selectorToPreventScroll:".Profile",onSwipe:(e,t)=>t===Le.e.Left?(V(Math.min(z+1,W.length-1)),!0):t===Le.e.Right&&(V(Math.max(0,z-1)),!0)})}),[z,W.length]);const ve="members"===J||!v&&"media"===J;ve?Ie=M?0:1e3:ee||(Ie=a.Y);const ye=(0,Ia.Z)([e,J],Ie);function Pe(){if(!ee||!ye||!g){const e=ve&&ee&&!ye;return o.ZP.createElement("div",{className:"content empty-list"},!e&&o.ZP.createElement(Ae.Z,null))}if(!ee.length){let e;switch(J){case"members":e=y?"You have no access to group members list.":"No members found";break;case"commonChats":e=_("NoGroupsInCommon");break;case"documents":e=_("lng_media_file_empty");break;case"links":e=_("lng_media_link_empty");break;case"audio":e=_("lng_media_song_empty");break;case"voice":e=_("lng_media_audio_empty");break;default:e=_("SharedMedia.EmptyTitle")}return o.ZP.createElement("div",{className:"content empty-list"},o.ZP.createElement(eo.Z,{text:e}))}return o.ZP.createElement("div",{className:`content ${J}-list`,dir:_.isRtl&&"media"===J?"rtl":void 0,teactFastList:!0},"media"===J?ee.map((e=>g[e]&&o.ZP.createElement(Xa.Z,{key:e,message:g[e],isProtected:B||g[e].isProtected,onClick:me}))):"documents"===J?ee.map((e=>g[e]&&o.ZP.createElement(Cs.Z,{key:e,message:g[e],withDate:!0,smaller:!0,className:"scroll-item",onDateClick:pe,isDownloading:T.includes(e)}))):"links"===J?ee.map((e=>g[e]&&o.ZP.createElement(Ja.Z,{key:e,message:g[e],isProtected:B||g[e].isProtected,onMessageClick:pe}))):"audio"===J?ee.map((e=>g[e]&&o.ZP.createElement(ws.Z,{key:e,theme:r,message:g[e],origin:m.Cr.SharedMedia,date:g[e].date,lastSyncTime:R,className:"scroll-item",onPlay:he,onDateClick:pe,isDownloading:T.includes(e)}))):"voice"===J?ee.map((e=>g[e]&&o.ZP.createElement(ws.Z,{key:e,theme:r,message:g[e],senderTitle:(0,Qa.F)(_,g[e],E,b),origin:m.Cr.SharedMedia,date:g[e].date,lastSyncTime:R,className:"scroll-item",onPlay:he,onDateClick:pe,isDownloading:T.includes(e)}))):"members"===J?ee.map(((e,t)=>{return o.ZP.createElement(Ka.Z,{key:e,teactOrderKey:t,className:"chat-item-clickable scroll-item small-icon",onClick:()=>ge(e),contextActions:(s=e,s!==l&&P?[{title:_("lng_context_remove_from_group"),icon:"stop",handler:()=>{Y(s)}}]:void 0)},o.ZP.createElement(It.Z,{userId:e,forceShowSelf:!0}));var s})):"commonChats"===J?ee.map(((e,t)=>o.ZP.createElement(Ka.Z,{key:e,teactOrderKey:t,className:"chat-item-clickable scroll-item small-icon",onClick:()=>O({id:e})},o.ZP.createElement(vt.Z,{chatId:e})))):void 0)}return o.ZP.createElement(Va.Z,{ref:j,className:"Profile custom-scroll",itemSelector:ao(J),items:ye?ee:void 0,cacheBuster:ie,sensitiveArea:a.qU,preloadBackwards:ye?"members"===J?a.Vk:a.EN:0,noScrollRestoreOnTop:!0,noFastList:!0,onLoadMore:te,onScroll:ae},!se&&function(e,t){return o.ZP.createElement("div",{className:"profile-info"},o.ZP.createElement(Ya.Z,{userId:t||e}),o.ZP.createElement(Wa.Z,{chatOrUserId:t||e}))}(e,c),!k&&o.ZP.createElement("div",{className:"shared-media"},o.ZP.createElement(Ze.Z,{ref:H,name:_.isRtl?"slide-optimized-rtl":"slide-optimized",activeKey:ne,renderCount:W.length,shouldRestoreHeight:!0,className:"shared-media-transition",onStart:oe,onStop:de},Pe),o.ZP.createElement(Fe.Z,{big:!0,activeTab:z,tabs:W,onSwitchTab:V})),Z&&o.ZP.createElement(to.Z,{isShown:"members"===J,onClick:le,ariaLabel:_("lng_channel_add_users")},o.ZP.createElement("i",{className:"icon-add-user-filled"})),P&&o.ZP.createElement(so.Z,{isOpen:Boolean(K),userId:K,onClose:fe}))}))),ro=(0,o.X$)((e=>{const t=(0,qe.Z)(De.gl.Extra,"RightSearch");return t?o.ZP.createElement(t,e):o.ZP.createElement(Qe.Z,null)})),io=(0,o.X$)((e=>{const t=(0,qe.Z)(De.gl.Extra,"Management");return t?o.ZP.createElement(t,e):o.ZP.createElement(Qe.Z,null)})),co=(0,o.X$)((()=>{const e=(0,qe.Z)(De.gl.Extra,"StickerSearch");return e?o.ZP.createElement(e,null):o.ZP.createElement(Qe.Z,null)})),lo=(0,o.X$)((()=>{const e=(0,qe.Z)(De.gl.Extra,"GifSearch");return e?o.ZP.createElement(e,null):o.ZP.createElement(Qe.Z,null)})),uo=(0,o.X$)((()=>{const e=(0,qe.Z)(De.gl.Extra,"PollResults");return e?o.ZP.createElement(e,null):o.ZP.createElement(Qe.Z,null)}));var mo=s(1820);const ho=(0,o.X$)((0,n.c$)(((e,{chatId:t})=>{var s;const n=(0,i.Z1)(e,t),{userIds:a}=e.contactList||{},{byId:o}=e.chats,{currentUserId:r,newChatMembersProgress:c,connectionState:l}=e,u=n&&(0,d.eA)(n),{query:h,fetchingStatus:g,globalUserIds:p,localUserIds:f}=e.userSearch;return{isChannel:u,members:null==n||null===(s=n.fullInfo)||void 0===s?void 0:s.members,currentUserId:r,chatsById:o,localContactIds:a,searchQuery:h,isSearching:g,isLoading:c===m.WB.Loading,globalUserIds:p,localUserIds:f,connectionState:l}}))((({isChannel:e,connectionState:t,members:s,onNextStep:a,currentUserId:r,chatsById:i,localContactIds:c,isLoading:l,searchQuery:u,isSearching:m,localUserIds:h,globalUserIds:p,onClose:f,isActive:I})=>{const{setUserSearchQuery:v,loadContactList:y}=(0,n.uC)(),Z=(0,Ce.Z)(),[P,C]=(0,o.eJ)([]),w=(0,lt.Z)(P)===P;(0,o.d4)((()=>{I&&"connectionStateReady"===t&&y()}),[t,I,y]),(0,pe.ZP)(I,f);const b=(0,o.Ye)((()=>s?s.map((e=>e.userId)):[]),[s]),S=(0,o.I4)((e=>{v({query:e})}),[v]),E=(0,o.Ye)((()=>{const t=(0,n.Rd)().users.byId,s=c?(0,d.kK)(c,t,u):[];return(0,d.ih)((0,g.Tw)([...s,...h||[],...p||[]]).filter((s=>{const n=t[s];return!b.includes(s)&&s!==r&&(!n||!(0,d.cS)(n)||!e&&n.canBeInvitedToGroup)})),i)}),[c,i,u,h,p,r,b,e]),M=(0,o.I4)((()=>{P.length&&(v({query:""}),a(P))}),[P,v,a]);return o.ZP.createElement("div",{className:"AddChatMembers"},o.ZP.createElement("div",{className:"AddChatMembers-inner"},o.ZP.createElement(mo.Z,{itemIds:E,selectedIds:P,filterValue:u,filterPlaceholder:Z("lng_channel_add_users"),searchInputId:"new-members-picker-search",isLoading:m,onSelectedIdsChange:C,onFilterChange:S,noScrollRestore:w}),o.ZP.createElement(to.Z,{isShown:Boolean(P.length),disabled:l,ariaLabel:Z("lng_channel_add_users"),onClick:M},l?o.ZP.createElement(Ae.Z,{color:"white"}):o.ZP.createElement("i",{className:"icon-arrow-right"}))))}))),go=Object.keys(m.qt).length/2,po=Object.keys(m.u1).length/2;function fo(){const e=document.querySelector(".RightHeader .SearchInput input");e&&e.blur()}const Io=(0,o.X$)((0,n.c$)((e=>{const{chatId:t,threadId:s}=(0,i.Bt)(e)||{},n=(0,i.g4)(e);return{contentKey:(0,i.Wq)(e),chatId:t,threadId:s,currentProfileUserId:e.users.selectedId,isChatSelected:Boolean(t&&n),shouldSkipHistoryAnimations:e.shouldSkipHistoryAnimations}}))((({contentKey:e,chatId:t,threadId:s,currentProfileUserId:r,isChatSelected:i,shouldSkipHistoryAnimations:c})=>{var d;const{toggleChatInfo:l,toggleManagement:u,openUserInfo:h,closeLocalTextSearch:g,setStickerSearchQuery:p,setGifSearchQuery:f,closePollResults:I,addChatMembers:v,setNewChatMembersDialogState:y}=(0,n.uC)(),{width:Z}=ct(),[P,C]=(0,o.eJ)(m.vi.Profile),[w,b]=(0,o.eJ)(m.u1.Initial),[S,E]=(0,o.eJ)(),[M,k]=(0,o.eJ)(),R=P!==m.vi.Profile,T=void 0!==e,N=e===m.qt.ChatInfo||e===m.qt.UserInfo,B=e===m.qt.Search,A=e===m.qt.Management,x=e===m.qt.StickerSearch,L=e===m.qt.GifSearch,O=e===m.qt.PollResults,F=e===m.qt.AddingMembers,U=Z<=a._m,[$,D]=(0,o.eJ)(!T),q=null!==(d=(0,pt.Z)(e,!0,!i))&&void 0!==d?d:-1,Q=(0,o.I4)(((t=!0)=>{switch(e){case m.qt.AddingMembers:y(m.WB.Closed);break;case m.qt.ChatInfo:if(R&&t){C(m.vi.Profile);break}l(void 0,{forceSyncOnIOs:!0});break;case m.qt.UserInfo:if(R&&t){C(m.vi.Profile);break}h({id:void 0},{forceSyncOnIOs:!0});break;case m.qt.Management:switch(w){case m.u1.Initial:u();break;case m.u1.ChatPrivacyType:case m.u1.Discussion:case m.u1.GroupPermissions:case m.u1.GroupType:case m.u1.ChatAdministrators:case m.u1.ChannelSubscribers:case m.u1.GroupMembers:b(m.u1.Initial);break;case m.u1.GroupUserPermissionsCreate:case m.u1.GroupRemovedUsers:case m.u1.GroupUserPermissions:b(m.u1.GroupPermissions),E(void 0),k(void 0);break;case m.u1.ChatAdminRights:case m.u1.ChatNewAdminRights:case m.u1.GroupAddAdmins:case m.u1.GroupRecentActions:b(m.u1.ChatAdministrators)}break;case m.qt.Search:fo(),g();break;case m.qt.StickerSearch:fo(),p({query:void 0});break;case m.qt.GifSearch:fo(),f({query:void 0});break;case m.qt.PollResults:I()}}),[e,R,l,h,I,y,w,u,g,p,f]),G=(0,o.I4)(((e,t)=>{E(e),k(t)}),[]),j=(0,o.I4)((e=>{v({chatId:t,memberIds:e})}),[v,t]);function H(e){if(-1!==q)switch(q){case m.qt.AddingMembers:return o.ZP.createElement(ho,{chatId:t,onNextStep:j,isActive:T&&e,onClose:Q});case m.qt.ChatInfo:case m.qt.UserInfo:return o.ZP.createElement(oo,{key:r||t,chatId:t,userId:r,profileState:P,onProfileStateChange:C});case m.qt.Search:return o.ZP.createElement(ro,{chatId:t,threadId:s,onClose:Q,isActive:T&&e});case m.qt.Management:return o.ZP.createElement(io,{chatId:t,currentScreen:w,isPromotedByCurrentUser:M,selectedChatMemberId:S,onScreenSelect:b,onChatMemberSelect:G,isActive:T&&e,onClose:Q});case m.qt.StickerSearch:return o.ZP.createElement(co,{onClose:Q,isActive:T&&e});case m.qt.GifSearch:return o.ZP.createElement(lo,{onClose:Q,isActive:T&&e});case m.qt.PollResults:return o.ZP.createElement(uo,{onClose:Q,isActive:T&&e})}}return(0,o.d4)((()=>T?(0,fe.Z)(Q):void 0),[T,Q]),(0,o.d4)((()=>{setTimeout((()=>{D(!T)}),300)}),[T]),(0,o.d4)((()=>{T&&U&&Q()}),[U]),(0,Kt.Z)((([s,n])=>{(s===m.qt.ChatInfo&&e===m.qt.UserInfo||s===m.qt.UserInfo&&e===m.qt.ChatInfo||n!==t)&&(C(m.vi.Profile),b(m.u1.Initial))}),[e,t]),(0,pe.ZP)(i&&(e===m.qt.ChatInfo||e===m.qt.UserInfo||e===m.qt.Management||e===m.qt.AddingMembers),(()=>Q(!1)),l),o.ZP.createElement("div",{id:"RightColumn-wrapper",className:i?void 0:"is-hidden"},U&&o.ZP.createElement("div",{className:"overlay-backdrop",onClick:Q}),o.ZP.createElement("div",{id:"RightColumn"},o.ZP.createElement(qa,{chatId:t,isColumnOpen:T,isProfile:N,isSearch:B,isManagement:A,isStickerSearch:x,isGifSearch:L,isPollResults:O,isAddingChatMembers:F,profileState:P,managementScreen:w,onClose:Q,shouldSkipAnimation:$||c}),o.ZP.createElement(Ze.Z,{name:$||c?"none":"zoom-fade",renderCount:go+po,activeKey:A?go+w:q,shouldCleanup:!0,cleanupExceptionKey:m.qt.ChatInfo},H)))}))),vo=(0,o.X$)((({isOpen:e})=>{const t=(0,qe.Z)(De.gl.Extra,"MediaViewer",!e);return t?o.ZP.createElement(t,null):void 0}));function yo(e,t){const s=document.createElement("a");s.href=e,s.download=t;try{s.click()}catch(e){console.error(e)}}const Zo=new Set,Po=(0,o.X$)((0,n.c$)((e=>({activeDownloads:e.activeDownloads.byChatId,messages:e.messages.byChatId})))((({activeDownloads:e,messages:t})=>{const{cancelMessageMediaDownload:s}=(0,n.uC)();(0,o.d4)((()=>{Object.entries(e).forEach((([e,n])=>{n.map((s=>t[Number(e)].byId[s])).forEach((e=>{const t=(0,d.Ti)(e,"download");if(t){if(!Zo.has(t)){const n=Nt.UV(t);if(n)return Zo.delete(t),yo(n,(0,d.w6)(e)),void s({message:e});Nt.he(t,u.IU.BlobUrl,!0).then((n=>{Zo.delete(t),n&&yo(n,(0,d.w6)(e)),s({message:e})})),Zo.add(t)}}else s({message:e})}))}))}),[s,t,e])}))),Co=(0,o.X$)((({isOpen:e})=>{const t=(0,qe.Z)(De.gl.Extra,"Notifications",!e);return t?o.ZP.createElement(t,null):void 0})),wo=(0,o.X$)((({isOpen:e})=>{const t=(0,qe.Z)(De.gl.Extra,"Dialogs",!e);return t?o.ZP.createElement(t,null):void 0})),bo=(0,o.X$)((e=>{const{isOpen:t}=e,s=(0,qe.Z)(De.gl.Extra,"ForwardPicker",!t);return s?o.ZP.createElement(s,e):void 0})),So=(0,o.X$)((e=>{const{url:t}=e,s=(0,qe.Z)(De.gl.Extra,"SafeLinkModal",!t);return s?o.ZP.createElement(s,e):void 0})),Eo=(0,o.X$)((e=>{const{isOpen:t}=e,s=(0,qe.Z)(De.gl.Extra,"HistoryCalendar",!t);return s?o.ZP.createElement(s,e):void 0})),Mo=(0,o.X$)((e=>{const{groupCallId:t}=e,s=(0,qe.Z)(De.gl.Calls,"GroupCall",!t);return s?o.ZP.createElement(s,e):void 0})),ko=(0,o.X$)((e=>{const{groupCallId:t}=e,s=(0,qe.Z)(De.gl.Calls,"ActiveCallHeader",!t);return s?o.ZP.createElement(s,null):void 0})),Ro=(0,o.X$)((({isOpen:e})=>{const t=(0,qe.Z)(De.gl.Calls,"CallFallbackConfirm",!e);return t?o.ZP.createElement(t,{isOpen:e}):void 0}));let To,No=!1;function Bo(e){document.querySelectorAll('link[rel="icon"], link[rel="alternate icon"]').forEach((t=>{e?t.href.includes("favicon-unread")||(t.href=t.href.replace("favicon","favicon-unread")):t.href=t.href.replace("favicon-unread","favicon")}))}function Ao(e){document.title!==e&&(document.title=e)}const xo=(0,o.X$)((0,n.c$)((e=>{const{settings:{byKey:{animationLevel:t,language:s,wasTimeFormatSetManually:n}}}=e,{chatId:a,messageId:o}=e.audioPlayer,r=a&&o?(0,i.hj)(e,a,o):void 0;return{lastSyncTime:e.lastSyncTime,isLeftColumnShown:e.isLeftColumnShown,isRightColumnShown:(0,i.Jf)(e),isMediaViewerOpen:(0,i.zQ)(e),isForwardModalOpen:(0,i.Ev)(e),hasNotifications:Boolean(e.notifications.length),hasDialogs:Boolean(e.dialogs.length),audioMessage:r,safeLinkModalUrl:e.safeLinkModalUrl,isHistoryCalendarOpen:Boolean(e.historyCalendarSelectedAt),shouldSkipHistoryAnimations:e.shouldSkipHistoryAnimations,openedStickerSetShortName:e.openedStickerSetShortName,isServiceChatReady:(0,i.UW)(e),activeGroupCallId:e.groupCalls.activeGroupCallId,animationLevel:t,language:s,wasTimeFormatSetManually:n,isCallFallbackConfirmOpen:Boolean(e.groupCalls.isFallbackConfirmOpen),addedSetIds:e.stickers.added.setIds}}))((({lastSyncTime:e,isLeftColumnShown:t,isRightColumnShown:s,isMediaViewerOpen:r,isForwardModalOpen:c,hasNotifications:d,hasDialogs:l,audioMessage:u,activeGroupCallId:m,safeLinkModalUrl:g,isHistoryCalendarOpen:p,shouldSkipHistoryAnimations:f,openedStickerSetShortName:I,isServiceChatReady:v,animationLevel:y,language:Z,wasTimeFormatSetManually:P,isCallFallbackConfirmOpen:w,addedSetIds:b})=>{const{loadAnimatedEmojis:S,loadNotificationSettings:E,loadNotificationExceptions:M,updateIsOnline:k,loadTopInlineBots:R,loadEmojiKeywords:T,loadCountryList:N,loadStickerSets:B,loadAddedStickers:A,loadFavoriteStickers:x,ensureTimeFormat:L,openStickerSetShortName:O,checkVersionNotification:F}=(0,n.uC)(),U=Boolean(e);a.eM&&!No&&(No=!0,console.log(">>> RENDER MAIN")),(0,o.d4)((()=>{e&&(k(!0),S(),E(),M(),R(),T({language:a.pR}))}),[e,S,T,M,E,R,k]),(0,o.d4)((()=>{e&&(Z!==a.pR&&T({language:Z}),N({langCode:Z}))}),[Z,e,N,T]),(0,o.d4)((()=>{U&&(b?A():(B(),x()))}),[U,b,B,x,A]),(0,o.d4)((()=>{e&&v&&F()}),[e,v,F]),(0,o.d4)((()=>{e&&!P&&L()}),[e,P,L]),(0,o.d4)((()=>{e&&pe.Oy.startsWith("#?tgaddr=")&&(0,oe.o)(decodeURIComponent(pe.Oy.substr("#?tgaddr=".length)))}),[e]),(0,o.d4)((()=>{if(m)return ie.Z.disableRefresh(),()=>{ie.Z.enableRefresh()}}),[m]);const{transitionClassNames:$}=(0,ce.Z)(!t,void 0,!0,void 0,f),{transitionClassNames:D}=(0,ce.Z)(s,void 0,!0,void 0,f),q=(0,ne.Z)($.replace(/([\w-]+)/g,"middle-column-$1"),D.replace(/([\w-]+)/g,"right-column-$1"),f&&"history-animation-disabled");(0,ue.Z)((([e])=>{if(void 0===e||0===y)return;const t=(0,se.YW)();(0,ae.L)(document.getElementById("MiddleColumn"),t)}),[t]),(0,ue.Z)((([e])=>{if(void 0===e||0===y)return;(0,C.T2)((()=>{document.body.classList.add("animating-right-column")}));const t=(0,se.YW)();(0,ae.L)(document.getElementById("RightColumn"),(()=>{t(),(0,C.T2)((()=>{document.body.classList.remove("animating-right-column")}))}))}),[s]);const Q=(0,o.I4)((()=>{k(!1);const e=(0,i.A1)((0,n.Rd)());let t=0;clearInterval(To),To=window.setInterval((()=>{if(document.title.includes(a.ou))Bo(!1);else{if(t%2==0){const t=(0,i.A1)((0,n.Rd)())-e;t>0&&(Ao(`${t} notification${t>1?"s":""}`),Bo(!0))}else Ao(a.Ti),Bo(!1);t++}}),1e3)}),[k]),G=(0,o.I4)((()=>{k(!0),clearInterval(To),To=void 0,document.title.includes(a.ou)||Ao(a.Ti),Bo(!1)}),[k]),j=(0,o.I4)((()=>{O({stickerSetShortName:void 0})}),[O]);return(0,de.Z)(Q,G),le(Q),function(e=!1){(0,o.d4)((()=>{if(h.$b){if(!e)return null==me||me.setAttribute("content",he),h.cj&&!h.fl&&document.addEventListener("gesturestart",ge),()=>{null==me||me.setAttribute("content","width=device-width, initial-scale=1, shrink-to-fit=no"),h.cj&&!h.fl&&document.removeEventListener("gesturestart",ge)};null==me||me.setAttribute("content","width=device-width, initial-scale=1, shrink-to-fit=no, viewport-fit=cover")}}),[e])}(r),o.ZP.createElement("div",{id:"Main",className:q,onDrop:re.Z,onDragOver:re.Z},o.ZP.createElement(nt,null),o.ZP.createElement(Ua,null),o.ZP.createElement(Io,null),o.ZP.createElement(vo,{isOpen:r}),o.ZP.createElement(bo,{isOpen:c}),o.ZP.createElement(Co,{isOpen:d}),o.ZP.createElement(wo,{isOpen:l}),u&&o.ZP.createElement(jt,{key:u.id,message:u,noUi:!0}),o.ZP.createElement(So,{url:g}),o.ZP.createElement(Eo,{isOpen:p}),o.ZP.createElement(ks.Z,{isOpen:Boolean(I),onClose:j,stickerSetShortName:I}),m&&o.ZP.createElement(o.ZP.Fragment,null,o.ZP.createElement(Mo,{groupCallId:m}),o.ZP.createElement(ko,{groupCallId:m})),o.ZP.createElement(Po,null),o.ZP.createElement(Ro,{isOpen:w}))})));a.eM&&console.log(">>> FINISH LOAD MAIN BUNDLE"),(0,n.Rd)().connectionState||(0,n.uC)().initApi()},4524:(e,t,s)=>{e.exports=s.p+"telegram-logo-filled.67469f6dc5e301e8e0bd..svg"}}]); +//# sourceMappingURL=87.74a4d72480e8214a0dde.js.map \ No newline at end of file diff --git a/dist/87.74a4d72480e8214a0dde.js.map b/dist/87.74a4d72480e8214a0dde.js.map new file mode 100644 index 00000000..bbc62e8a --- /dev/null +++ b/dist/87.74a4d72480e8214a0dde.js.map @@ -0,0 +1 @@ +{"version":3,"file":"87.74a4d72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eAAgBT,IAGrC,KACLJ,MAAAA,IAAAA,GAAc62B,aAAa,UAAW,yDAClCn6C,EAAAA,KAAWs5B,EAAAA,IACbpc,SAASkH,oBAAoB,eAAgBV,KAhB/CJ,MAAAA,IAAAA,GAAc62B,aAAa,UAXE,gFA8B9B,CAACgwB,IoIiQJyjB,CAA2BnC,GAGzB,0BAAKl8F,GAAG,OAAOy3B,UAAWA,EAAW6mE,OAAQ5iC,GAAAA,EAAW6iC,WAAY7iC,GAAAA,GAClE,mBAAC,GAAD,MACA,mBAAC,GAAD,MACA,mBAAC,GAAD,MACA,mBAAC,GAAD,CAAatkC,OAAQ8kE,IACrB,mBAAC,GAAD,CAAe9kE,OAAQglE,IACvB,mBAAC,GAAD,CAAehlE,OAAQklE,IACvB,mBAAC,GAAD,CAASllE,OAAQmlE,IAChB/mD,GAAgB,mBAAC,GAAD,CAAaljB,IAAKkjB,EAAax1C,GAAImG,QAASqvC,EAAcjD,MAAI,IAC/E,mBAAC,GAAD,CAAejmC,IAAKC,IACpB,mBAAC,GAAD,CAAiB6qB,OAAQolE,IACzB,mBAAC,KAAD,CACEplE,OAAQl1B,QAAQsY,GAChBomB,QAASw9D,EACT1lF,oBAAqB8B,IAEtBwY,GACC,sCACE,mBAAC,GAAD,CAAWO,YAAaP,IACxB,mBAAC,GAAD,CAAkBO,YAAaP,KAGnC,mBAAC,GAAD,MACA,mBAAC,GAAD,CAAqBoE,OAAQslE,SCxT/Bj+E,EAAAA,IAEFC,QAAQC,IAAI,gCAGTra,EAAAA,EAAAA,MAAYwuB,kBACf7V,EAAAA,EAAAA,MAAcuhF,W","sources":["webpack://telegram-t/./src/modules/actions/ui/localSearch.ts","webpack://telegram-t/./src/modules/actions/ui/chats.ts","webpack://telegram-t/./src/modules/actions/ui/messages.ts","webpack://telegram-t/./src/versionNotification.txt","webpack://telegram-t/./src/modules/actions/ui/globalSearch.ts","webpack://telegram-t/./src/modules/actions/ui/stickerSearch.ts","webpack://telegram-t/./src/modules/actions/ui/users.ts","webpack://telegram-t/./src/modules/actions/ui/misc.ts","webpack://telegram-t/./src/modules/actions/ui/payments.ts","webpack://telegram-t/./src/modules/actions/api/messages.ts","webpack://telegram-t/./src/modules/actions/api/symbols.ts","webpack://telegram-t/./src/modules/actions/api/globalSearch.ts","webpack://telegram-t/./src/modules/actions/api/localSearch.ts","webpack://telegram-t/./src/modules/actions/api/management.ts","webpack://telegram-t/./src/modules/actions/api/sync.ts","webpack://telegram-t/./src/modules/actions/api/users.ts","webpack://telegram-t/./src/modules/reducers/bots.ts","webpack://telegram-t/./src/modules/actions/api/bots.ts","webpack://telegram-t/./src/modules/actions/api/twoFaSettings.ts","webpack://telegram-t/./src/modules/actions/api/payments.ts","webpack://telegram-t/./src/util/requestQuery.ts","webpack://telegram-t/./src/modules/actions/apiUpdaters/chats.ts","webpack://telegram-t/./src/modules/actions/apiUpdaters/messages.ts","webpack://telegram-t/./src/modules/actions/apiUpdaters/users.ts","webpack://telegram-t/./src/modules/actions/apiUpdaters/symbols.ts","webpack://telegram-t/./src/modules/actions/apiUpdaters/misc.ts","webpack://telegram-t/./src/modules/actions/apiUpdaters/settings.ts","webpack://telegram-t/./src/modules/actions/apiUpdaters/twoFaSettings.ts","webpack://telegram-t/./src/modules/actions/apiUpdaters/calls.ts","webpack://telegram-t/./src/hooks/useBeforeUnload.ts","webpack://telegram-t/./src/hooks/usePreventPinchZoomGesture.ts","webpack://telegram-t/./src/hooks/useBrowserOnline.ts","webpack://telegram-t/./src/components/left/main/LeftMainHeader.tsx","webpack://telegram-t/./src/components/left/ConnectionState.tsx","webpack://telegram-t/./src/components/left/main/ChatFolders.tsx","webpack://telegram-t/./src/hooks/useThrottledMemo.ts","webpack://telegram-t/./src/components/left/search/LeftSearch.async.tsx","webpack://telegram-t/./src/components/left/main/ContactList.async.tsx","webpack://telegram-t/./src/components/left/NewChatButton.tsx","webpack://telegram-t/./src/components/left/main/LeftMain.tsx","webpack://telegram-t/./src/components/left/settings/Settings.async.tsx","webpack://telegram-t/./src/components/left/newChat/NewChat.async.tsx","webpack://telegram-t/./src/components/left/ArchivedChats.async.tsx","webpack://telegram-t/./src/components/left/LeftColumn.tsx","webpack://telegram-t/./src/hooks/useResize.ts","webpack://telegram-t/./src/hooks/useCustomBackground.ts","webpack://telegram-t/./src/hooks/useWindowSize.ts","webpack://telegram-t/./src/components/middle/helpers/calculateMiddleFooterTransforms.ts","webpack://telegram-t/./src/components/middle/HeaderMenuContainer.async.tsx","webpack://telegram-t/./src/components/middle/HeaderActions.tsx","webpack://telegram-t/./src/hooks/useWebpThumbnail.ts","webpack://telegram-t/./src/components/middle/PinnedMessageNavigation.tsx","webpack://telegram-t/./src/components/middle/HeaderPinnedMessage.tsx","webpack://telegram-t/./src/util/imageResize.ts","webpack://telegram-t/./src/hooks/useMessageMediaMetadata.ts","webpack://telegram-t/./src/hooks/useAsync.ts","webpack://telegram-t/./src/components/middle/AudioPlayer.tsx","webpack://telegram-t/./src/components/calls/group/GroupCallTopPane.tsx","webpack://telegram-t/./src/components/middle/MiddleHeader.tsx","webpack://telegram-t/./src/components/middle/helpers/groupMessages.ts","webpack://telegram-t/./src/components/middle/hooks/useMessageObservers.ts","webpack://telegram-t/./src/components/middle/message/helpers/buildContentClassName.ts","webpack://telegram-t/./src/components/middle/message/helpers/mediaDimensions.ts","webpack://telegram-t/./src/components/middle/message/helpers/calculateAlbumLayout.ts","webpack://telegram-t/./src/components/middle/message/helpers/calculateAuthorWidth.ts","webpack://telegram-t/./src/components/middle/message/hooks/useFocusMessage.ts","webpack://telegram-t/./src/components/middle/message/ContextMenuContainer.async.tsx","webpack://telegram-t/./src/components/middle/ActionMessage.tsx","webpack://telegram-t/./src/components/common/EmbeddedMessage.tsx","webpack://telegram-t/./src/components/middle/message/MessageMeta.tsx","webpack://telegram-t/./src/components/middle/message/Sticker.tsx","webpack://telegram-t/./src/components/middle/message/hooks/useBlurredMediaThumbRef.ts","webpack://telegram-t/./src/components/middle/message/helpers/getCustomAppendixBg.ts","webpack://telegram-t/./src/components/middle/message/Photo.tsx","webpack://telegram-t/./src/components/middle/message/hooks/useVideoAutoPause.ts","webpack://telegram-t/./src/components/middle/message/Video.tsx","webpack://telegram-t/./src/components/middle/message/Contact.tsx","webpack://telegram-t/./src/components/middle/message/PollOption.tsx","webpack://telegram-t/./src/components/middle/message/Poll.tsx","webpack://telegram-t/./src/components/middle/message/WebPage.tsx","webpack://telegram-t/./src/components/middle/message/Invoice.tsx","webpack://telegram-t/./src/components/middle/message/hocs/withSelectControl.tsx","webpack://telegram-t/./src/components/middle/message/Album.tsx","webpack://telegram-t/./src/components/middle/message/RoundVideo.tsx","webpack://telegram-t/./src/components/middle/message/InlineButtons.tsx","webpack://telegram-t/./src/components/middle/message/CommentButton.tsx","webpack://telegram-t/./src/components/middle/message/Message.tsx","webpack://telegram-t/./src/components/middle/message/hooks/useOuterHandlers.ts","webpack://telegram-t/./src/components/middle/message/hooks/useInnerHandlers.ts","webpack://telegram-t/./src/components/middle/message/SponsoredMessage.tsx","webpack://telegram-t/./src/components/middle/MessageListContent.tsx","webpack://telegram-t/./src/components/middle/hooks/useScrollHooks.ts","webpack://telegram-t/./src/components/middle/ContactGreeting.tsx","webpack://telegram-t/./src/components/middle/NoMessages.tsx","webpack://telegram-t/./src/components/middle/MessageList.tsx","webpack://telegram-t/./src/components/middle/hooks/useStickyDates.ts","webpack://telegram-t/./src/components/middle/ScrollDownButton.tsx","webpack://telegram-t/./src/components/middle/composer/helpers/buildAttachment.ts","webpack://telegram-t/./src/components/middle/composer/helpers/applyIosAutoCapitalizationFix.ts","webpack://telegram-t/./src/hooks/useInterval.ts","webpack://telegram-t/./src/util/voiceRecording.ts","webpack://telegram-t/./node_modules/opus-recorder/dist/encoderWorker.min.js","webpack://telegram-t/./src/components/middle/composer/hooks/useVoiceRecording.ts","webpack://telegram-t/./src/components/middle/composer/hooks/useClipboardPaste.ts","webpack://telegram-t/./src/components/middle/composer/helpers/getMessageTextAsHtml.ts","webpack://telegram-t/./src/components/middle/composer/hooks/useDraft.ts","webpack://telegram-t/./src/components/middle/composer/hooks/useInlineBotTooltip.ts","webpack://telegram-t/./src/components/middle/composer/hooks/useBotCommandTooltip.ts","webpack://telegram-t/./src/components/common/DeleteMessageModal.async.tsx","webpack://telegram-t/./src/components/ui/ResponsiveHoverButton.tsx","webpack://telegram-t/./src/components/middle/composer/AttachMenu.async.tsx","webpack://telegram-t/./src/components/middle/composer/SymbolMenu.async.tsx","webpack://telegram-t/./src/components/middle/composer/InlineBotTooltip.async.tsx","webpack://telegram-t/./src/components/middle/composer/MentionTooltip.async.tsx","webpack://telegram-t/./src/components/middle/composer/CustomSendMenu.async.tsx","webpack://telegram-t/./src/components/middle/composer/StickerTooltip.async.tsx","webpack://telegram-t/./src/components/middle/composer/BotCommandTooltip.async.tsx","webpack://telegram-t/./src/components/middle/composer/BotKeyboardMenu.tsx","webpack://telegram-t/./src/components/middle/composer/ComposerEmbeddedMessage.tsx","webpack://telegram-t/./src/components/middle/composer/AttachmentModal.async.tsx","webpack://telegram-t/./src/components/middle/composer/BotCommandMenu.async.tsx","webpack://telegram-t/./src/components/middle/composer/PollModal.async.tsx","webpack://telegram-t/./src/components/middle/composer/DropArea.async.tsx","webpack://telegram-t/./src/components/middle/composer/WebPagePreview.tsx","webpack://telegram-t/./src/components/common/CalendarModal.async.tsx","webpack://telegram-t/./src/components/middle/composer/SendAsMenu.async.tsx","webpack://telegram-t/./src/components/middle/composer/Composer.tsx","webpack://telegram-t/./src/components/middle/composer/hooks/useStickerTooltip.ts","webpack://telegram-t/./src/util/insertHtmlInSelection.ts","webpack://telegram-t/./src/util/deleteLastCharacterOutsideSelection.ts","webpack://telegram-t/./src/components/middle/composer/hooks/useEditing.ts","webpack://telegram-t/./src/components/middle/MobileSearch.async.tsx","webpack://telegram-t/./src/components/middle/MessageSelectToolbar.async.tsx","webpack://telegram-t/./src/components/common/UnpinAllMessagesModal.async.tsx","webpack://telegram-t/./src/components/payment/PaymentModal.async.tsx","webpack://telegram-t/./src/components/payment/ReceiptModal.async.tsx","webpack://telegram-t/./src/components/common/SeenByModal.async.tsx","webpack://telegram-t/./src/components/middle/MiddleColumn.tsx","webpack://telegram-t/./src/components/right/RightHeader.tsx","webpack://telegram-t/./src/components/right/hooks/useProfileViewportIds.ts","webpack://telegram-t/./src/components/right/hooks/useProfileState.ts","webpack://telegram-t/./src/components/right/Profile.tsx","webpack://telegram-t/./src/components/right/hooks/useTransitionFixes.ts","webpack://telegram-t/./src/hooks/useCacheBuster.ts","webpack://telegram-t/./src/components/right/RightSearch.async.tsx","webpack://telegram-t/./src/components/right/management/Management.async.tsx","webpack://telegram-t/./src/components/right/StickerSearch.async.tsx","webpack://telegram-t/./src/components/right/GifSearch.async.tsx","webpack://telegram-t/./src/components/right/PollResults.async.tsx","webpack://telegram-t/./src/components/right/AddChatMembers.tsx","webpack://telegram-t/./src/components/right/RightColumn.tsx","webpack://telegram-t/./src/components/mediaViewer/MediaViewer.async.tsx","webpack://telegram-t/./src/util/download.ts","webpack://telegram-t/./src/components/main/DownloadManager.tsx","webpack://telegram-t/./src/components/main/Notifications.async.tsx","webpack://telegram-t/./src/components/main/Dialogs.async.tsx","webpack://telegram-t/./src/components/main/ForwardPicker.async.tsx","webpack://telegram-t/./src/components/main/SafeLinkModal.async.tsx","webpack://telegram-t/./src/components/main/HistoryCalendar.async.tsx","webpack://telegram-t/./src/components/calls/group/GroupCall.async.tsx","webpack://telegram-t/./src/components/calls/ActiveCallHeader.async.tsx","webpack://telegram-t/./src/components/calls/CallFallbackConfirm.async.tsx","webpack://telegram-t/./src/components/main/Main.tsx","webpack://telegram-t/./src/bundles/main.ts"],"sourcesContent":["import { addReducer } from '../../../lib/teact/teactn';\n\nimport {\n updateLocalTextSearch,\n replaceLocalTextSearchResults,\n updateLocalMediaSearchType,\n} from '../../reducers';\nimport { MEMO_EMPTY_ARRAY } from '../../../util/memo';\nimport { selectCurrentMessageList } from '../../selectors';\nimport { buildChatThreadKey } from '../../helpers';\nimport { GlobalState } from '../../../global/types';\n\naddReducer('openLocalTextSearch', (global) => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n return updateLocalTextSearch(global, chatId, threadId, true);\n});\n\naddReducer('closeLocalTextSearch', closeLocalTextSearch);\n\naddReducer('setLocalTextSearchQuery', (global, actions, payload) => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n const { query } = payload!;\n const chatThreadKey = buildChatThreadKey(chatId, threadId);\n const { query: currentQuery } = global.localTextSearch.byChatThreadKey[chatThreadKey] || {};\n\n if (query !== currentQuery) {\n global = replaceLocalTextSearchResults(global, chatId, threadId, MEMO_EMPTY_ARRAY);\n }\n\n global = updateLocalTextSearch(global, chatId, threadId, true, query);\n\n return global;\n});\n\naddReducer('setLocalMediaSearchType', (global, actions, payload) => {\n const { chatId } = selectCurrentMessageList(global) || {};\n if (!chatId) {\n return undefined;\n }\n\n const { mediaType } = payload!;\n return updateLocalMediaSearchType(global, chatId, mediaType);\n});\n\nexport function closeLocalTextSearch(global: GlobalState): GlobalState {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return global;\n }\n\n global = updateLocalTextSearch(global, chatId, threadId, false);\n global = replaceLocalTextSearchResults(global, chatId, threadId, undefined);\n return global;\n}\n","import { addReducer, setGlobal } from '../../../lib/teact/teactn';\n\nimport {\n exitMessageSelectMode, replaceThreadParam, updateCurrentMessageList,\n} from '../../reducers';\nimport { selectCurrentMessageList } from '../../selectors';\nimport { closeLocalTextSearch } from './localSearch';\n\naddReducer('openChat', (global, actions, payload) => {\n const {\n id, threadId = -1, type = 'thread', shouldReplaceHistory = false,\n } = payload!;\n\n const currentMessageList = selectCurrentMessageList(global);\n\n if (!currentMessageList\n || (\n currentMessageList.chatId !== id\n || currentMessageList.threadId !== threadId\n || currentMessageList.type !== type\n )) {\n global = replaceThreadParam(global, id, threadId, 'replyStack', []);\n global = exitMessageSelectMode(global);\n global = closeLocalTextSearch(global);\n\n global = {\n ...global,\n messages: {\n ...global.messages,\n contentToBeScheduled: undefined,\n },\n ...(id !== global.forwardMessages.toChatId && {\n forwardMessages: {},\n }),\n };\n\n setGlobal(global);\n }\n\n return updateCurrentMessageList(global, id, threadId, type, shouldReplaceHistory);\n});\n\naddReducer('openPreviousChat', (global) => {\n return updateCurrentMessageList(global, undefined);\n});\n\naddReducer('openChatWithInfo', (global, actions, payload) => {\n setGlobal({\n ...global,\n isChatInfoShown: true,\n });\n\n actions.openChat(payload);\n});\n\naddReducer('resetChatCreation', (global) => {\n return {\n ...global,\n chatCreation: undefined,\n };\n});\n\naddReducer('setNewChatMembersDialogState', (global, actions, payload) => {\n return {\n ...global,\n newChatMembersProgress: payload,\n };\n});\n\naddReducer('openNextChat', (global, actions, payload) => {\n const { targetIndexDelta, orderedIds } = payload;\n\n const { chatId } = selectCurrentMessageList(global) || {};\n\n if (!chatId) {\n actions.openChat({ id: orderedIds[0] });\n return;\n }\n\n const position = orderedIds.indexOf(chatId);\n\n if (position === -1) {\n return;\n }\n const nextId = orderedIds[position + targetIndexDelta];\n\n actions.openChat({ id: nextId, shouldReplaceHistory: true });\n});\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiMessage, MAIN_THREAD_ID } from '../../../api/types';\nimport { FocusDirection } from '../../../types';\n\nimport {\n ANIMATION_END_DELAY,\n APP_VERSION,\n FAST_SMOOTH_MAX_DURATION,\n SERVICE_NOTIFICATIONS_USER_ID,\n} from '../../../config';\nimport { IS_TOUCH_ENV } from '../../../util/environment';\nimport {\n enterMessageSelectMode,\n toggleMessageSelection,\n exitMessageSelectMode,\n replaceThreadParam,\n updateFocusDirection,\n updateFocusedMessage,\n} from '../../reducers';\nimport {\n selectCurrentChat,\n selectViewportIds,\n selectIsRightColumnShown,\n selectCurrentMessageList,\n selectChat,\n selectThreadInfo,\n selectChatMessages,\n selectAllowedMessageActions,\n selectMessageIdsByGroupId,\n selectForwardedMessageIdsByGroupId,\n selectIsViewportNewest,\n selectReplyingToId,\n selectReplyStack,\n} from '../../selectors';\nimport { findLast } from '../../../util/iteratees';\nimport { getServerTime } from '../../../util/serverTime';\n\n// @ts-ignore\nimport versionNotification from '../../../versionNotification.txt';\nimport parseMessageInput from '../../../util/parseMessageInput';\n\nconst FOCUS_DURATION = 1500;\nconst FOCUS_NO_HIGHLIGHT_DURATION = FAST_SMOOTH_MAX_DURATION + ANIMATION_END_DELAY;\nconst POLL_RESULT_OPEN_DELAY_MS = 450;\nconst SERVICE_NOTIFICATIONS_MAX_AMOUNT = 1e3;\n\nlet blurTimeout: number | undefined;\n\naddReducer('setScrollOffset', (global, actions, payload) => {\n const { chatId, threadId, scrollOffset } = payload!;\n\n return replaceThreadParam(global, chatId, threadId, 'scrollOffset', scrollOffset);\n});\n\naddReducer('setReplyingToId', (global, actions, payload) => {\n const { messageId } = payload!;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return undefined;\n }\n const { chatId, threadId } = currentMessageList;\n\n return replaceThreadParam(global, chatId, threadId, 'replyingToId', messageId);\n});\n\naddReducer('setEditingId', (global, actions, payload) => {\n const { messageId } = payload!;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return undefined;\n }\n\n const { chatId, threadId, type } = currentMessageList;\n const paramName = type === 'scheduled' ? 'editingScheduledId' : 'editingId';\n\n return replaceThreadParam(global, chatId, threadId, paramName, messageId);\n});\n\naddReducer('editLastMessage', (global) => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n const chatMessages = selectChatMessages(global, chatId);\n const viewportIds = selectViewportIds(global, chatId, threadId);\n if (!chatMessages || !viewportIds) {\n return undefined;\n }\n\n const lastOwnEditableMessageId = findLast(viewportIds, (id) => {\n return Boolean(chatMessages[id] && selectAllowedMessageActions(global, chatMessages[id], threadId).canEdit);\n });\n\n if (!lastOwnEditableMessageId) {\n return undefined;\n }\n\n return replaceThreadParam(global, chatId, threadId, 'editingId', lastOwnEditableMessageId);\n});\n\naddReducer('replyToNextMessage', (global, actions, payload) => {\n const { targetIndexDelta } = payload;\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return;\n }\n\n const chatMessages = selectChatMessages(global, chatId);\n const viewportIds = selectViewportIds(global, chatId, threadId);\n if (!chatMessages || !viewportIds) {\n return;\n }\n\n const replyingToId = selectReplyingToId(global, chatId, threadId);\n const isLatest = selectIsViewportNewest(global, chatId, threadId);\n\n let messageId: number | undefined;\n\n if (!isLatest || !replyingToId) {\n if (threadId === MAIN_THREAD_ID) {\n const chat = selectChat(global, chatId);\n\n messageId = chat?.lastMessage?.id;\n } else {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n\n messageId = threadInfo?.lastMessageId;\n }\n } else {\n const chatMessageKeys = Object.keys(chatMessages);\n const indexOfCurrent = chatMessageKeys.indexOf(replyingToId.toString());\n const newIndex = indexOfCurrent + targetIndexDelta;\n messageId = newIndex <= chatMessageKeys.length + 1 && newIndex >= 0\n ? Number(chatMessageKeys[newIndex])\n : undefined;\n }\n actions.setReplyingToId({ messageId });\n actions.focusMessage({\n chatId, threadId, messageId,\n });\n});\n\naddReducer('openMediaViewer', (global, actions, payload) => {\n const {\n chatId, threadId, messageId, avatarOwnerId, profilePhotoIndex, origin,\n } = payload!;\n\n return {\n ...global,\n mediaViewer: {\n chatId,\n threadId,\n messageId,\n avatarOwnerId,\n profilePhotoIndex,\n origin,\n },\n forwardMessages: {},\n };\n});\n\naddReducer('closeMediaViewer', (global) => {\n return {\n ...global,\n mediaViewer: {},\n };\n});\n\naddReducer('openAudioPlayer', (global, actions, payload) => {\n const {\n chatId, threadId, messageId, origin, volume, playbackRate, isMuted,\n } = payload!;\n\n return {\n ...global,\n audioPlayer: {\n chatId,\n threadId,\n messageId,\n origin: origin ?? global.audioPlayer.origin,\n volume: volume ?? global.audioPlayer.volume,\n playbackRate: playbackRate || global.audioPlayer.playbackRate,\n isMuted: isMuted || global.audioPlayer.isMuted,\n },\n };\n});\n\naddReducer('setAudioPlayerVolume', (global, actions, payload) => {\n const {\n volume,\n } = payload!;\n\n return {\n ...global,\n audioPlayer: {\n ...global.audioPlayer,\n volume,\n },\n };\n});\n\naddReducer('setAudioPlayerPlaybackRate', (global, actions, payload) => {\n const {\n playbackRate,\n } = payload!;\n\n return {\n ...global,\n audioPlayer: {\n ...global.audioPlayer,\n playbackRate,\n },\n };\n});\n\naddReducer('setAudioPlayerMuted', (global, actions, payload) => {\n const {\n isMuted,\n } = payload!;\n\n return {\n ...global,\n audioPlayer: {\n ...global.audioPlayer,\n isMuted,\n },\n };\n});\n\naddReducer('setAudioPlayerOrigin', (global, actions, payload) => {\n const {\n origin,\n } = payload!;\n\n return {\n ...global,\n audioPlayer: {\n ...global.audioPlayer,\n origin,\n },\n };\n});\n\naddReducer('closeAudioPlayer', (global) => {\n return {\n ...global,\n audioPlayer: {\n volume: global.audioPlayer.volume,\n playbackRate: global.audioPlayer.playbackRate,\n isMuted: global.audioPlayer.isMuted,\n },\n };\n});\n\naddReducer('openPollResults', (global, actions, payload) => {\n const { chatId, messageId } = payload!;\n\n const shouldOpenInstantly = selectIsRightColumnShown(global);\n\n if (!shouldOpenInstantly) {\n window.setTimeout(() => {\n const newGlobal = getGlobal();\n\n setGlobal({\n ...newGlobal,\n pollResults: {\n chatId,\n messageId,\n voters: {},\n },\n });\n }, POLL_RESULT_OPEN_DELAY_MS);\n } else if (chatId !== global.pollResults.chatId || messageId !== global.pollResults.messageId) {\n setGlobal({\n ...global,\n pollResults: {\n chatId,\n messageId,\n voters: {},\n },\n });\n }\n});\n\naddReducer('closePollResults', (global) => {\n setGlobal({\n ...global,\n pollResults: {},\n });\n});\n\naddReducer('focusLastMessage', (global, actions) => {\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n\n const { chatId, threadId } = currentMessageList;\n\n let lastMessageId: number | undefined;\n if (threadId === MAIN_THREAD_ID) {\n const chat = selectChat(global, chatId);\n\n lastMessageId = chat?.lastMessage?.id;\n } else {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n\n lastMessageId = threadInfo?.lastMessageId;\n }\n\n if (!lastMessageId) {\n return;\n }\n\n actions.focusMessage({\n chatId, threadId, messageId: lastMessageId, noHighlight: true,\n });\n});\n\naddReducer('focusNextReply', (global, actions) => {\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return undefined;\n }\n\n const { chatId, threadId } = currentMessageList;\n\n const replyStack = selectReplyStack(global, chatId, threadId);\n\n if (!replyStack || replyStack.length === 0) {\n actions.focusLastMessage();\n } else {\n const messageId = replyStack.pop();\n\n global = replaceThreadParam(global, chatId, threadId, 'replyStack', [...replyStack]);\n\n setGlobal(global);\n\n actions.focusMessage({\n chatId,\n threadId,\n messageId,\n });\n }\n\n return undefined;\n});\n\naddReducer('focusMessage', (global, actions, payload) => {\n const {\n chatId, threadId = MAIN_THREAD_ID, messageListType = 'thread', noHighlight, groupedId, groupedChatId,\n replyMessageId, isResizingContainer,\n } = payload!;\n\n let { messageId } = payload!;\n\n if (groupedId !== undefined) {\n const ids = selectForwardedMessageIdsByGroupId(global, groupedChatId, groupedId);\n if (ids?.length) {\n ([messageId] = ids);\n }\n }\n\n const currentMessageList = selectCurrentMessageList(global);\n const shouldSwitchChat = !currentMessageList || (\n chatId !== currentMessageList.chatId\n || threadId !== currentMessageList.threadId\n || messageListType !== currentMessageList.type\n );\n\n if (blurTimeout) {\n clearTimeout(blurTimeout);\n blurTimeout = undefined;\n }\n blurTimeout = window.setTimeout(() => {\n let newGlobal = getGlobal();\n newGlobal = updateFocusedMessage(newGlobal);\n newGlobal = updateFocusDirection(newGlobal);\n setGlobal(newGlobal);\n }, noHighlight ? FOCUS_NO_HIGHLIGHT_DURATION : FOCUS_DURATION);\n\n global = updateFocusedMessage(global, chatId, messageId, noHighlight, isResizingContainer);\n global = updateFocusDirection(global, undefined);\n\n if (replyMessageId) {\n const replyStack = selectReplyStack(global, chatId, threadId) || [];\n global = replaceThreadParam(global, chatId, threadId, 'replyStack', [...replyStack, replyMessageId]);\n }\n\n if (shouldSwitchChat) {\n global = updateFocusDirection(global, FocusDirection.Static);\n }\n\n const viewportIds = selectViewportIds(global, chatId, threadId);\n if (viewportIds && viewportIds.includes(messageId)) {\n setGlobal(global);\n actions.openChat({ id: chatId, threadId });\n return undefined;\n }\n\n if (shouldSwitchChat) {\n global = replaceThreadParam(global, chatId, threadId, 'viewportIds', undefined);\n }\n\n global = replaceThreadParam(global, chatId, threadId, 'outlyingIds', undefined);\n\n if (viewportIds && !shouldSwitchChat) {\n const direction = messageId > viewportIds[0] ? FocusDirection.Down : FocusDirection.Up;\n global = updateFocusDirection(global, direction);\n }\n\n setGlobal(global);\n\n actions.openChat({ id: chatId, threadId });\n actions.loadViewportMessages();\n return undefined;\n});\n\naddReducer('openForwardMenu', (global, actions, payload) => {\n const { fromChatId, messageIds, groupedId } = payload!;\n let groupedMessageIds;\n if (groupedId) {\n groupedMessageIds = selectMessageIdsByGroupId(global, fromChatId, groupedId);\n }\n return {\n ...global,\n forwardMessages: {\n fromChatId,\n messageIds: groupedMessageIds || messageIds,\n isModalShown: true,\n },\n };\n});\n\naddReducer('exitForwardMode', (global) => {\n setGlobal({\n ...global,\n forwardMessages: {},\n });\n});\n\naddReducer('setForwardChatId', (global, actions, payload) => {\n const { id } = payload!;\n\n setGlobal({\n ...global,\n forwardMessages: {\n ...global.forwardMessages,\n toChatId: id,\n isModalShown: false,\n },\n });\n\n actions.openChat({ id });\n actions.closeMediaViewer();\n actions.exitMessageSelectMode();\n});\n\naddReducer('openForwardMenuForSelectedMessages', (global, actions) => {\n if (!global.selectedMessages) {\n return;\n }\n\n const { chatId: fromChatId, messageIds } = global.selectedMessages;\n\n actions.openForwardMenu({ fromChatId, messageIds });\n});\n\naddReducer('cancelMessageMediaDownload', (global, actions, payload) => {\n const { message } = payload!;\n\n const byChatId = global.activeDownloads.byChatId[message.chatId];\n if (!byChatId || !byChatId.length) return;\n\n setGlobal({\n ...global,\n activeDownloads: {\n byChatId: {\n ...global.activeDownloads.byChatId,\n [message.chatId]: byChatId.filter((id) => id !== message.id),\n },\n },\n });\n});\n\naddReducer('downloadMessageMedia', (global, actions, payload) => {\n const { message } = payload!;\n if (!message) return;\n\n setGlobal({\n ...global,\n activeDownloads: {\n byChatId: {\n ...global.activeDownloads.byChatId,\n [message.chatId]: [...(global.activeDownloads.byChatId[message.chatId] || []), message.id],\n },\n },\n });\n});\n\naddReducer('downloadSelectedMessages', (global, actions) => {\n if (!global.selectedMessages) {\n return;\n }\n\n const { chatId, messageIds } = global.selectedMessages;\n const { threadId } = selectCurrentMessageList(global) || {};\n\n const chatMessages = selectChatMessages(global, chatId);\n if (!chatMessages || !threadId) return;\n const messages = messageIds.map((id) => chatMessages[id])\n .filter((message) => selectAllowedMessageActions(global, message, threadId).canDownload);\n messages.forEach((message) => actions.downloadMessageMedia({ message }));\n});\n\naddReducer('enterMessageSelectMode', (global, actions, payload) => {\n const { messageId } = payload || {};\n const openChat = selectCurrentChat(global);\n if (!openChat) {\n return global;\n }\n\n return enterMessageSelectMode(global, openChat.id, messageId);\n});\n\naddReducer('toggleMessageSelection', (global, actions, payload) => {\n const {\n messageId,\n groupedId,\n childMessageIds,\n withShift,\n } = payload!;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n\n const { chatId, threadId, type: messageListType } = currentMessageList;\n\n global = toggleMessageSelection(\n global, chatId, threadId, messageListType, messageId, groupedId, childMessageIds, withShift,\n );\n\n setGlobal(global);\n\n if (global.shouldShowContextMenuHint) {\n actions.disableContextMenuHint();\n actions.showNotification({\n // eslint-disable-next-line max-len\n message: `To **edit** or **reply**, close this menu. Then ${IS_TOUCH_ENV ? 'long tap' : 'right click'} on a message.`,\n });\n }\n});\n\naddReducer('disableContextMenuHint', (global) => {\n if (!global.shouldShowContextMenuHint) {\n return undefined;\n }\n\n return {\n ...global,\n shouldShowContextMenuHint: false,\n };\n});\n\naddReducer('exitMessageSelectMode', exitMessageSelectMode);\n\naddReducer('openPollModal', (global) => {\n return {\n ...global,\n isPollModalOpen: true,\n };\n});\n\naddReducer('closePollModal', (global) => {\n return {\n ...global,\n isPollModalOpen: false,\n };\n});\n\naddReducer('checkVersionNotification', (global, actions) => {\n const currentVersion = APP_VERSION.split('.').slice(0, 2).join('.');\n const { serviceNotifications } = global;\n\n if (serviceNotifications.find(({ version }) => version === currentVersion)) {\n return;\n }\n\n const message: Omit = {\n chatId: SERVICE_NOTIFICATIONS_USER_ID,\n date: getServerTime(global.serverTimeOffset),\n content: {\n text: parseMessageInput(versionNotification),\n },\n isOutgoing: false,\n };\n\n actions.createServiceNotification({\n message,\n version: currentVersion,\n });\n});\n\naddReducer('createServiceNotification', (global, actions, payload) => {\n const { message, version } = payload;\n const { serviceNotifications } = global;\n const serviceChat = selectChat(global, SERVICE_NOTIFICATIONS_USER_ID)!;\n\n const maxId = Math.max(\n serviceChat.lastMessage?.id || 0,\n ...serviceNotifications.map(({ id }) => id),\n );\n const fractionalPart = (serviceNotifications.length + 1) / SERVICE_NOTIFICATIONS_MAX_AMOUNT;\n // The fractional ID is made of the largest integer ID and an incremented fractional part\n const id = Math.floor(maxId) + fractionalPart;\n\n message.id = id;\n\n const serviceNotification = {\n id,\n message,\n version,\n isUnread: true,\n };\n\n setGlobal({\n ...global,\n serviceNotifications: [\n ...serviceNotifications.slice(-SERVICE_NOTIFICATIONS_MAX_AMOUNT),\n serviceNotification,\n ],\n });\n\n actions.apiUpdate({\n '@type': 'newMessage',\n id: message.id,\n chatId: message.chatId,\n message,\n });\n});\n\naddReducer('openSeenByModal', (global, actions, payload) => {\n const { chatId, messageId } = payload!;\n\n return {\n ...global,\n seenByModal: { chatId, messageId },\n };\n});\n\naddReducer('closeSeenByModal', (global) => {\n return {\n ...global,\n seenByModal: undefined,\n };\n});\n","export default \"**Telegram Web Z was updated to version 1.28**\\n\\n👏 **Harder**\\n• Support for join requests in groups and channels.\\n• Support for more service messages.\\n\\n🤩 **Better**\\n• Easier to select and adjust left column width.\\n• Redundant single quotes removed in Spanish and French translations.\\n• Support for hotkeys on non-qwerty keyboards.\\n• Use Ctrl+Shift+F or Ctrl+F (in PWA mode) to open global or local search.\\n• Chat: \\\"Add to folder...\\\" only appears for users with folders.\\n• Support for `start` parameter in `tg://resolve` links.\\n\\n💪 **Stronger**\\n• Fixed focusing on messages in a chat that was previously open.\\n• Fixed missing stickers in sticker suggestions.\\n• Fixed opening chats from user mentions.\\n• Fixed various glitches when appearing as a channel in public groups.\\n• Removed redundant download and forward options in chats with protected content.\\n\";","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { updateGlobalSearch, updateGlobalSearchContent } from '../../reducers';\n\nconst MAX_RECENTLY_FOUND_IDS = 10;\n\naddReducer('setGlobalSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n const { chatId } = global.globalSearch;\n\n return updateGlobalSearch(global, {\n globalResults: {},\n localResults: {},\n resultsByType: undefined,\n ...(query ? { fetchingStatus: { chats: !chatId, messages: true } } : { fetchingStatus: undefined }),\n query,\n });\n});\n\naddReducer('addRecentlyFoundChatId', (global, actions, payload) => {\n const { id } = payload!;\n const { recentlyFoundChatIds } = global.globalSearch;\n\n if (!recentlyFoundChatIds) {\n return updateGlobalSearch(global, { recentlyFoundChatIds: [id] });\n }\n\n const newRecentIds = recentlyFoundChatIds.filter((chatId) => chatId !== id);\n newRecentIds.unshift(id);\n if (newRecentIds.length > MAX_RECENTLY_FOUND_IDS) {\n newRecentIds.pop();\n }\n\n return updateGlobalSearch(global, { recentlyFoundChatIds: newRecentIds });\n});\n\naddReducer('clearRecentlyFoundChats', (global) => {\n return updateGlobalSearch(global, { recentlyFoundChatIds: undefined });\n});\n\naddReducer('setGlobalSearchContent', (global, actions, payload) => {\n const { content } = payload!;\n\n return updateGlobalSearchContent(global, content);\n});\n\naddReducer('setGlobalSearchChatId', (global, actions, payload) => {\n const { id } = payload!;\n\n return updateGlobalSearch(global, { chatId: id, query: undefined, resultsByType: undefined });\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\naddReducer('setStickerSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n search: {\n query,\n resultIds: undefined,\n },\n },\n };\n});\n\naddReducer('setGifSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n\n return {\n ...global,\n gifs: {\n ...global.gifs,\n search: {\n query,\n offsetId: undefined,\n results: undefined,\n },\n },\n };\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\n\nimport { updateSelectedUserId, updateUserSearch } from '../../reducers';\n\naddReducer('openUserInfo', (global, actions, payload) => {\n const { id } = payload!;\n\n actions.openChat({ id });\n});\n\nconst clearSelectedUserId = (global: GlobalState) => updateSelectedUserId(global, undefined);\n\naddReducer('openChat', clearSelectedUserId);\n\naddReducer('setUserSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n\n return updateUserSearch(global, {\n globalUserIds: undefined,\n localUserIds: undefined,\n fetchingStatus: Boolean(query),\n query,\n });\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\nimport { ApiError } from '../../../api/types';\n\nimport { IS_SINGLE_COLUMN_LAYOUT, IS_TABLET_COLUMN_LAYOUT } from '../../../util/environment';\nimport getReadableErrorText from '../../../util/getReadableErrorText';\nimport { selectCurrentMessageList } from '../../selectors';\nimport generateIdFor from '../../../util/generateIdFor';\n\nconst MAX_STORED_EMOJIS = 18; // Represents two rows of recent emojis\n\naddReducer('toggleChatInfo', (global) => {\n return {\n ...global,\n isChatInfoShown: !global.isChatInfoShown,\n };\n});\n\naddReducer('setLeftColumnWidth', (global, actions, payload) => {\n const leftColumnWidth = payload;\n\n return {\n ...global,\n leftColumnWidth,\n };\n});\n\naddReducer('resetLeftColumnWidth', (global) => {\n return {\n ...global,\n leftColumnWidth: undefined,\n };\n});\n\naddReducer('toggleManagement', (global): GlobalState | undefined => {\n const { chatId } = selectCurrentMessageList(global) || {};\n\n if (!chatId) {\n return undefined;\n }\n\n return {\n ...global,\n management: {\n byChatId: {\n ...global.management.byChatId,\n [chatId]: {\n ...global.management.byChatId[chatId],\n isActive: !(global.management.byChatId[chatId] || {}).isActive,\n },\n },\n },\n };\n});\n\naddReducer('closeManagement', (global): GlobalState | undefined => {\n const { chatId } = selectCurrentMessageList(global) || {};\n\n if (!chatId) {\n return undefined;\n }\n\n return {\n ...global,\n management: {\n byChatId: {\n ...global.management.byChatId,\n [chatId]: {\n ...global.management.byChatId[chatId],\n isActive: false,\n },\n },\n },\n };\n});\n\naddReducer('openChat', (global) => {\n if (!IS_SINGLE_COLUMN_LAYOUT && !IS_TABLET_COLUMN_LAYOUT) {\n return undefined;\n }\n\n return {\n ...global,\n isLeftColumnShown: global.messages.messageLists.length === 0,\n };\n});\n\naddReducer('toggleLeftColumn', (global) => {\n return {\n ...global,\n isLeftColumnShown: !global.isLeftColumnShown,\n };\n});\n\naddReducer('addRecentEmoji', (global, action, payload) => {\n const { emoji } = payload!;\n const { recentEmojis } = global;\n if (!recentEmojis) {\n return {\n ...global,\n recentEmojis: [emoji],\n };\n }\n\n const newEmojis = recentEmojis.filter((e) => e !== emoji);\n newEmojis.unshift(emoji);\n if (newEmojis.length > MAX_STORED_EMOJIS) {\n newEmojis.pop();\n }\n\n return {\n ...global,\n recentEmojis: newEmojis,\n };\n});\n\naddReducer('addRecentSticker', (global, action, payload) => {\n const { sticker } = payload!;\n const { recent } = global.stickers;\n if (!recent) {\n return {\n ...global,\n stickers: {\n ...global.stickers,\n recent: {\n hash: '0',\n stickers: [sticker],\n },\n },\n };\n }\n\n const newStickers = recent.stickers.filter((s) => s.id !== sticker.id);\n newStickers.unshift(sticker);\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n recent: {\n ...recent,\n stickers: newStickers,\n },\n },\n };\n});\n\naddReducer('showNotification', (global, actions, payload) => {\n const notification = payload!;\n notification.localId = generateIdFor({});\n\n const newNotifications = [...global.notifications];\n const existingNotificationIndex = newNotifications.findIndex((n) => n.message === notification.message);\n if (existingNotificationIndex !== -1) {\n newNotifications.splice(existingNotificationIndex, 1);\n }\n\n newNotifications.push(notification);\n\n return {\n ...global,\n notifications: newNotifications,\n };\n});\n\naddReducer('dismissNotification', (global, actions, payload) => {\n const newNotifications = global.notifications.filter(({ localId }) => localId !== payload.localId);\n\n return {\n ...global,\n notifications: newNotifications,\n };\n});\n\naddReducer('showDialog', (global, actions, payload) => {\n const { data } = payload!;\n\n // Filter out errors that we don't want to show to the user\n if ('message' in data && data.hasErrorKey && !getReadableErrorText(data)) {\n return global;\n }\n\n const newDialogs = [...global.dialogs];\n if ('message' in data) {\n const existingErrorIndex = newDialogs.findIndex((err) => (err as ApiError).message === data.message);\n if (existingErrorIndex !== -1) {\n newDialogs.splice(existingErrorIndex, 1);\n }\n }\n\n newDialogs.push(data);\n\n return {\n ...global,\n dialogs: newDialogs,\n };\n});\n\naddReducer('dismissDialog', (global) => {\n const newDialogs = [...global.dialogs];\n\n newDialogs.pop();\n\n return {\n ...global,\n dialogs: newDialogs,\n };\n});\n\naddReducer('toggleSafeLinkModal', (global, actions, payload) => {\n const { url: safeLinkModalUrl } = payload;\n\n return {\n ...global,\n safeLinkModalUrl,\n };\n});\n\naddReducer('openHistoryCalendar', (global, actions, payload) => {\n const { selectedAt } = payload;\n\n return {\n ...global,\n historyCalendarSelectedAt: selectedAt,\n };\n});\n\naddReducer('closeHistoryCalendar', (global) => {\n return {\n ...global,\n historyCalendarSelectedAt: undefined,\n };\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { clearPayment, closeInvoice } from '../../reducers';\n\naddReducer('openPaymentModal', (global, actions, payload) => {\n const { chatId, messageId } = payload;\n return {\n ...global,\n payment: {\n ...global.payment,\n chatId,\n messageId,\n isPaymentModalOpen: true,\n },\n };\n});\n\naddReducer('closePaymentModal', (global) => {\n const newGlobal = clearPayment(global);\n return closeInvoice(newGlobal);\n});\n\naddReducer('addPaymentError', (global, actions, payload) => {\n const { error } = payload!;\n\n return {\n ...global,\n payment: {\n ...global.payment,\n error,\n },\n };\n});\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport {\n ApiAttachment,\n ApiChat,\n ApiMessage,\n ApiMessageEntity,\n ApiNewPoll,\n ApiOnProgress,\n ApiSticker,\n ApiUser,\n ApiVideo,\n MAIN_THREAD_ID,\n MESSAGE_DELETED,\n} from '../../../api/types';\nimport { LoadMoreDirection } from '../../../types';\n\nimport { MAX_MEDIA_FILES_FOR_ALBUM, MESSAGE_LIST_SLICE, SERVICE_NOTIFICATIONS_USER_ID } from '../../../config';\nimport { IS_IOS } from '../../../util/environment';\nimport { callApi, cancelApiProgress } from '../../../api/gramjs';\nimport {\n areSortedArraysIntersecting, buildCollectionByKey, split, unique,\n} from '../../../util/iteratees';\nimport {\n addUsers,\n addChatMessagesById,\n replaceThreadParam,\n safeReplaceViewportIds,\n updateChatMessage,\n addChats,\n updateListedIds,\n updateOutlyingIds,\n replaceScheduledMessages,\n updateThreadInfos,\n updateChat,\n updateThreadUnreadFromForwardedMessage,\n updateSponsoredMessage,\n} from '../../reducers';\nimport {\n selectChat,\n selectChatMessage,\n selectCurrentMessageList,\n selectFocusedMessageId,\n selectCurrentChat,\n selectListedIds,\n selectOutlyingIds,\n selectViewportIds,\n selectRealLastReadId,\n selectReplyingToId,\n selectEditingId,\n selectDraft,\n selectThreadOriginChat,\n selectThreadTopMessageId,\n selectEditingScheduledId,\n selectEditingMessage,\n selectScheduledMessage,\n selectNoWebPage,\n selectFirstUnreadId,\n selectUser,\n selectSendAs,\n selectSponsoredMessage,\n} from '../../selectors';\nimport { debounce, rafPromise } from '../../../util/schedulers';\nimport { isServiceNotificationMessage } from '../../helpers';\n\nconst uploadProgressCallbacks = new Map();\n\nconst runDebouncedForMarkRead = debounce((cb) => cb(), 500, false);\n\naddReducer('loadViewportMessages', (global, actions, payload) => {\n const {\n direction = LoadMoreDirection.Around,\n isBudgetPreload = false,\n } = payload || {};\n\n let { chatId, threadId } = payload || {};\n\n if (!chatId) {\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return undefined;\n }\n\n chatId = currentMessageList.chatId;\n threadId = currentMessageList.threadId;\n }\n\n const chat = selectChat(global, chatId);\n // TODO Revise if `chat.isRestricted` check is needed\n if (!chat || chat.isRestricted) {\n return undefined;\n }\n\n const viewportIds = selectViewportIds(global, chatId, threadId);\n const listedIds = selectListedIds(global, chatId, threadId);\n const outlyingIds = selectOutlyingIds(global, chatId, threadId);\n\n if (!viewportIds || !viewportIds.length || direction === LoadMoreDirection.Around) {\n const offsetId = selectFocusedMessageId(global, chatId) || selectRealLastReadId(global, chatId, threadId);\n const isOutlying = Boolean(offsetId && listedIds && !listedIds.includes(offsetId));\n const historyIds = (isOutlying ? outlyingIds : listedIds) || [];\n const {\n newViewportIds, areSomeLocal, areAllLocal,\n } = getViewportSlice(historyIds, offsetId, LoadMoreDirection.Around);\n\n if (areSomeLocal && newViewportIds.length >= MESSAGE_LIST_SLICE) {\n global = safeReplaceViewportIds(global, chatId, threadId, newViewportIds);\n }\n\n if (!areAllLocal) {\n void loadViewportMessages(chat, threadId, offsetId, LoadMoreDirection.Around, isOutlying, isBudgetPreload);\n }\n } else {\n const offsetId = direction === LoadMoreDirection.Backwards ? viewportIds[0] : viewportIds[viewportIds.length - 1];\n const isOutlying = Boolean(outlyingIds);\n const historyIds = (isOutlying ? outlyingIds : listedIds)!;\n const {\n newViewportIds, areSomeLocal, areAllLocal,\n } = getViewportSlice(historyIds, offsetId, direction);\n\n if (areSomeLocal) {\n global = safeReplaceViewportIds(global, chatId, threadId, newViewportIds);\n }\n\n void loadWithBudget(actions, areAllLocal, isOutlying, isBudgetPreload, chat, threadId, direction, offsetId);\n\n if (isBudgetPreload) {\n return undefined;\n }\n }\n\n return global;\n});\n\nasync function loadWithBudget(\n actions: GlobalActions,\n areAllLocal: boolean, isOutlying: boolean, isBudgetPreload: boolean,\n chat: ApiChat, threadId: number, direction: LoadMoreDirection, offsetId?: number,\n) {\n if (!areAllLocal) {\n await loadViewportMessages(\n chat, threadId, offsetId, direction, isOutlying, isBudgetPreload,\n );\n }\n\n if (!isBudgetPreload) {\n // Let reducer return and update global\n await Promise.resolve();\n actions.loadViewportMessages({\n chatId: chat.id, threadId, direction, isBudgetPreload: true,\n });\n }\n}\n\naddReducer('loadMessage', (global, actions, payload) => {\n const {\n chatId, messageId, replyOriginForId, threadUpdate,\n } = payload!;\n const chat = selectChat(global, chatId);\n\n if (!chat) {\n return;\n }\n\n (async () => {\n const message = await loadMessage(chat, messageId, replyOriginForId);\n if (message && threadUpdate) {\n const { lastMessageId, isDeleting } = threadUpdate;\n\n setGlobal(updateThreadUnreadFromForwardedMessage(\n getGlobal(),\n message,\n chatId,\n lastMessageId,\n isDeleting,\n ));\n }\n })();\n});\n\naddReducer('sendMessage', (global, actions, payload) => {\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return undefined;\n }\n\n const { chatId, threadId, type } = currentMessageList;\n\n if (type === 'scheduled' && !payload.scheduledAt) {\n return {\n ...global,\n messages: {\n ...global.messages,\n contentToBeScheduled: payload,\n },\n };\n }\n\n const chat = selectChat(global, chatId)!;\n\n const params = {\n ...payload,\n chat,\n replyingTo: selectReplyingToId(global, chatId, threadId),\n noWebPage: selectNoWebPage(global, chatId, threadId),\n sendAs: selectSendAs(global, chatId),\n };\n\n actions.setReplyingToId({ messageId: undefined });\n actions.clearWebPagePreview({ chatId, threadId, value: false });\n\n const isSingle = !payload.attachments || payload.attachments.length <= 1;\n const isGrouped = !isSingle && payload.attachments && payload.attachments.length > 1;\n\n if (isSingle) {\n const { attachments, ...restParams } = params;\n sendMessage({\n ...restParams,\n attachment: attachments ? attachments[0] : undefined,\n });\n } else if (isGrouped) {\n const {\n text, entities, attachments, ...commonParams\n } = params;\n const groupedAttachments = split(attachments, MAX_MEDIA_FILES_FOR_ALBUM);\n for (let i = 0; i < groupedAttachments.length; i++) {\n const [firstAttachment, ...restAttachments] = groupedAttachments[i];\n const groupedId = `${Date.now()}${i}`;\n\n sendMessage({\n ...commonParams,\n text: i === 0 ? text : undefined,\n entities: i === 0 ? entities : undefined,\n attachment: firstAttachment,\n groupedId: restAttachments.length > 0 ? groupedId : undefined,\n });\n\n restAttachments.forEach((attachment: ApiAttachment) => {\n sendMessage({\n ...commonParams,\n attachment,\n groupedId,\n });\n });\n }\n } else {\n const {\n text, entities, attachments, replyingTo, ...commonParams\n } = params;\n\n if (text) {\n sendMessage({\n ...commonParams,\n text,\n entities,\n replyingTo,\n });\n }\n\n attachments.forEach((attachment: ApiAttachment) => {\n sendMessage({\n ...commonParams,\n attachment,\n });\n });\n }\n\n return undefined;\n});\n\naddReducer('editMessage', (global, actions, payload) => {\n const { serverTimeOffset } = global;\n const { text, entities } = payload!;\n\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n\n const { chatId, threadId, type: messageListType } = currentMessageList;\n const chat = selectChat(global, chatId);\n const message = selectEditingMessage(global, chatId, threadId, messageListType);\n if (!chat || !message) {\n return;\n }\n\n void callApi('editMessage', {\n chat, message, text, entities, noWebPage: selectNoWebPage(global, chatId, threadId), serverTimeOffset,\n });\n\n actions.setEditingId({ messageId: undefined });\n});\n\naddReducer('cancelSendingMessage', (global, actions, payload) => {\n const { chatId, messageId } = payload!;\n const message = selectChatMessage(global, chatId, messageId);\n const progressCallback = message && uploadProgressCallbacks.get(message.previousLocalId || message.id);\n if (progressCallback) {\n cancelApiProgress(progressCallback);\n }\n\n actions.apiUpdate({\n '@type': 'deleteMessages',\n ids: [messageId],\n chatId,\n });\n});\n\naddReducer('saveDraft', (global, actions, payload) => {\n const { chatId, threadId, draft } = payload!;\n if (!draft) {\n return undefined;\n }\n\n const { text, entities } = draft;\n const chat = selectChat(global, chatId)!;\n\n if (threadId === MAIN_THREAD_ID) {\n void callApi('saveDraft', {\n chat,\n text,\n entities,\n replyToMsgId: selectReplyingToId(global, chatId, threadId),\n });\n }\n\n global = replaceThreadParam(global, chatId, threadId, 'draft', draft);\n global = updateChat(global, chatId, { draftDate: Math.round(Date.now() / 1000) });\n\n return global;\n});\n\naddReducer('clearDraft', (global, actions, payload) => {\n const { chatId, threadId, localOnly } = payload!;\n if (!selectDraft(global, chatId, threadId)) {\n return undefined;\n }\n\n const chat = selectChat(global, chatId)!;\n\n if (!localOnly && threadId === MAIN_THREAD_ID) {\n void callApi('clearDraft', chat);\n }\n\n global = replaceThreadParam(global, chatId, threadId, 'draft', undefined);\n global = updateChat(global, chatId, { draftDate: undefined });\n\n return global;\n});\n\naddReducer('toggleMessageWebPage', (global, actions, payload) => {\n const { chatId, threadId, noWebPage } = payload!;\n\n return replaceThreadParam(global, chatId, threadId, 'noWebPage', noWebPage);\n});\n\naddReducer('pinMessage', (global, actions, payload) => {\n const chat = selectCurrentChat(global);\n if (!chat) {\n return;\n }\n\n const {\n messageId, isUnpin, isOneSide, isSilent,\n } = payload!;\n\n void callApi('pinMessage', {\n chat, messageId, isUnpin, isOneSide, isSilent,\n });\n});\n\naddReducer('unpinAllMessages', (global, actions, payload) => {\n const chat = selectChat(global, payload.chatId);\n if (!chat) {\n return;\n }\n\n void unpinAllMessages(chat);\n});\n\nasync function unpinAllMessages(chat: ApiChat) {\n await callApi('unpinAllMessages', { chat });\n let global = getGlobal();\n global = replaceThreadParam(global, chat.id, MAIN_THREAD_ID, 'pinnedIds', []);\n setGlobal(global);\n}\n\naddReducer('deleteMessages', (global, actions, payload) => {\n const { messageIds, shouldDeleteForAll } = payload!;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n const { chatId, threadId } = currentMessageList;\n const chat = selectChat(global, chatId)!;\n\n void callApi('deleteMessages', { chat, messageIds, shouldDeleteForAll });\n\n const editingId = selectEditingId(global, chatId, threadId);\n if (messageIds.includes(editingId)) {\n actions.setEditingId({ messageId: undefined });\n }\n});\n\naddReducer('deleteScheduledMessages', (global, actions, payload) => {\n const { messageIds } = payload!;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n\n const { chatId } = currentMessageList;\n const chat = selectChat(global, chatId)!;\n\n void callApi('deleteScheduledMessages', { chat, messageIds });\n\n const editingId = selectEditingScheduledId(global, chatId);\n if (messageIds.includes(editingId)) {\n actions.setEditingId({ messageId: undefined });\n }\n});\n\naddReducer('deleteHistory', (global, actions, payload) => {\n (async () => {\n const { chatId, shouldDeleteForAll } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n const maxId = chat.lastMessage?.id;\n\n await callApi('deleteHistory', { chat, shouldDeleteForAll, maxId });\n\n const activeChat = selectCurrentMessageList(global);\n if (activeChat && activeChat.chatId === chatId) {\n actions.openChat({ id: undefined });\n }\n })();\n});\n\naddReducer('reportMessages', (global, actions, payload) => {\n (async () => {\n const {\n messageIds, reason, description,\n } = payload!;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n\n const { chatId } = currentMessageList;\n const chat = selectChat(global, chatId)!;\n\n const result = await callApi('reportMessages', {\n peer: chat, messageIds, reason, description,\n });\n\n actions.showNotification({\n message: result\n ? 'Thank you! Your report will be reviewed by our team.'\n : 'Error occured while submiting report. Please, try again later.',\n });\n })();\n});\n\naddReducer('sendMessageAction', (global, actions, payload) => {\n (async () => {\n const { action, chatId, threadId } = payload!;\n if (chatId === global.currentUserId) return; // Message actions are disabled in Saved Messages\n\n const chat = selectChat(global, chatId)!;\n if (!chat) return;\n\n await callApi('sendMessageAction', {\n peer: chat, threadId, action,\n });\n })();\n});\n\naddReducer('markMessageListRead', (global, actions, payload) => {\n const { serverTimeOffset } = global;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return undefined;\n }\n\n const { chatId, threadId } = currentMessageList;\n const chat = selectThreadOriginChat(global, chatId, threadId);\n if (!chat) {\n return undefined;\n }\n\n const { maxId } = payload!;\n\n runDebouncedForMarkRead(() => {\n void callApi('markMessageListRead', {\n serverTimeOffset, chat, threadId, maxId,\n });\n });\n\n // TODO Support local marking read for threads\n if (threadId !== MAIN_THREAD_ID) {\n return undefined;\n }\n\n if (chatId === SERVICE_NOTIFICATIONS_USER_ID) {\n global = {\n ...global,\n serviceNotifications: global.serviceNotifications.map((notification) => {\n return notification.isUnread && notification.id <= maxId ? { ...notification, isUnread: false } : notification;\n }),\n };\n }\n\n const viewportIds = selectViewportIds(global, chatId, threadId);\n const minId = selectFirstUnreadId(global, chatId, threadId);\n if (!viewportIds || !minId || !chat.unreadCount) {\n return global;\n }\n\n const readCount = countSortedIds(viewportIds!, minId, maxId);\n if (!readCount) {\n return global;\n }\n\n return updateChat(global, chatId, {\n lastReadInboxMessageId: maxId,\n unreadCount: Math.max(0, chat.unreadCount - readCount),\n });\n});\n\naddReducer('markMessagesRead', (global, actions, payload) => {\n const chat = selectCurrentChat(global);\n if (!chat) {\n return;\n }\n\n const { messageIds } = payload!;\n\n void callApi('markMessagesRead', { chat, messageIds });\n});\n\naddReducer('loadWebPagePreview', (global, actions, payload) => {\n const { text } = payload!;\n void loadWebPagePreview(text);\n});\n\naddReducer('clearWebPagePreview', (global) => {\n if (!global.webPagePreview) {\n return undefined;\n }\n\n return {\n ...global,\n webPagePreview: undefined,\n };\n});\n\naddReducer('sendPollVote', (global, actions, payload) => {\n const { chatId, messageId, options } = payload!;\n const chat = selectChat(global, chatId);\n\n if (chat) {\n void callApi('sendPollVote', { chat, messageId, options });\n }\n});\n\naddReducer('loadPollOptionResults', (global, actions, payload) => {\n const {\n chat, messageId, option, offset, limit, shouldResetVoters,\n } = payload!;\n\n void loadPollOptionResults(chat, messageId, option, offset, limit, shouldResetVoters);\n});\n\naddReducer('forwardMessages', (global, action, payload) => {\n const { fromChatId, messageIds, toChatId } = global.forwardMessages;\n const fromChat = fromChatId ? selectChat(global, fromChatId) : undefined;\n const toChat = toChatId ? selectChat(global, toChatId) : undefined;\n const messages = fromChatId && messageIds\n ? messageIds\n .sort((a, b) => a - b)\n .map((id) => selectChatMessage(global, fromChatId, id)).filter(Boolean as any)\n : undefined;\n\n if (!fromChat || !toChat || !messages) {\n return;\n }\n\n const { isSilent, scheduledAt } = payload;\n const sendAs = selectSendAs(global, toChatId!);\n\n const realMessages = messages.filter((m) => !isServiceNotificationMessage(m));\n if (realMessages.length) {\n void callApi('forwardMessages', {\n fromChat,\n toChat,\n messages: realMessages,\n serverTimeOffset: getGlobal().serverTimeOffset,\n isSilent,\n scheduledAt,\n sendAs,\n });\n }\n\n messages\n .filter((m) => isServiceNotificationMessage(m))\n .forEach((message) => {\n const { text, entities } = message.content.text || {};\n const { sticker, poll } = message.content;\n\n void sendMessage({\n chat: toChat,\n text,\n entities,\n sticker,\n poll,\n isSilent,\n scheduledAt,\n sendAs,\n });\n });\n\n setGlobal({\n ...getGlobal(),\n forwardMessages: {},\n });\n});\n\naddReducer('loadScheduledHistory', (global, actions, payload) => {\n const { chatId } = payload;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n void loadScheduledHistory(chat);\n});\n\naddReducer('sendScheduledMessages', (global, actions, payload) => {\n const {\n chatId, id,\n } = payload!;\n\n const chat = selectChat(global, chatId);\n\n if (!chat) {\n return;\n }\n\n void callApi('sendScheduledMessages', {\n chat,\n ids: [id],\n });\n});\n\naddReducer('rescheduleMessage', (global, actions, payload) => {\n const {\n chatId, messageId, scheduledAt,\n } = payload!;\n\n const chat = selectChat(global, chatId);\n const message = chat && selectScheduledMessage(global, chat.id, messageId);\n if (!chat || !message) {\n return;\n }\n\n void callApi('rescheduleMessage', {\n chat,\n message,\n scheduledAt,\n });\n});\n\naddReducer('requestThreadInfoUpdate', (global, actions, payload) => {\n const { chatId, threadId } = payload;\n const chat = selectThreadOriginChat(global, chatId, threadId);\n if (!chat) {\n return;\n }\n\n void callApi('requestThreadInfoUpdate', { chat, threadId });\n});\n\nasync function loadWebPagePreview(message: string) {\n const webPagePreview = await callApi('fetchWebPagePreview', { message });\n\n setGlobal({\n ...getGlobal(),\n webPagePreview,\n });\n}\n\nasync function loadViewportMessages(\n chat: ApiChat,\n threadId: number,\n offsetId: number | undefined,\n direction: LoadMoreDirection,\n isOutlying = false,\n isBudgetPreload = false,\n) {\n const chatId = chat.id;\n\n let addOffset: number | undefined;\n switch (direction) {\n case LoadMoreDirection.Backwards:\n addOffset = undefined;\n break;\n case LoadMoreDirection.Around:\n addOffset = -(Math.round(MESSAGE_LIST_SLICE / 2) + 1);\n break;\n case LoadMoreDirection.Forwards:\n addOffset = -(MESSAGE_LIST_SLICE + 1);\n break;\n }\n\n const result = await callApi('fetchMessages', {\n chat: selectThreadOriginChat(getGlobal(), chatId, threadId)!,\n offsetId,\n addOffset,\n limit: MESSAGE_LIST_SLICE,\n threadId,\n });\n\n if (!result) {\n return;\n }\n\n const {\n messages, users, chats, threadInfos,\n } = result;\n\n let global = getGlobal();\n\n const localMessages = chatId === SERVICE_NOTIFICATIONS_USER_ID\n ? global.serviceNotifications.map(({ message }) => message)\n : [];\n const allMessages = ([] as ApiMessage[]).concat(messages, localMessages);\n const byId = buildCollectionByKey(allMessages, 'id');\n const ids = Object.keys(byId).map(Number);\n\n global = addChatMessagesById(global, chatId, byId);\n global = isOutlying\n ? updateOutlyingIds(global, chatId, threadId, ids)\n : updateListedIds(global, chatId, threadId, ids);\n\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = addChats(global, buildCollectionByKey(chats, 'id'));\n global = updateThreadInfos(global, chatId, threadInfos);\n\n let listedIds = selectListedIds(global, chatId, threadId);\n const outlyingIds = selectOutlyingIds(global, chatId, threadId);\n\n if (isOutlying && listedIds && outlyingIds) {\n if (!outlyingIds.length || areSortedArraysIntersecting(listedIds, outlyingIds)) {\n global = updateListedIds(global, chatId, threadId, outlyingIds);\n listedIds = selectListedIds(global, chatId, threadId);\n global = replaceThreadParam(global, chatId, threadId, 'outlyingIds', undefined);\n isOutlying = false;\n }\n }\n\n if (!isBudgetPreload) {\n const historyIds = isOutlying ? outlyingIds! : listedIds!;\n const { newViewportIds } = getViewportSlice(historyIds, offsetId, direction);\n global = safeReplaceViewportIds(global, chatId, threadId, newViewportIds!);\n }\n\n setGlobal(global);\n}\n\nasync function loadMessage(chat: ApiChat, messageId: number, replyOriginForId: number) {\n const result = await callApi('fetchMessage', { chat, messageId });\n if (!result) {\n return undefined;\n }\n\n if (result === MESSAGE_DELETED) {\n if (replyOriginForId) {\n let global = getGlobal();\n const replyMessage = selectChatMessage(global, chat.id, replyOriginForId);\n global = updateChatMessage(global, chat.id, replyOriginForId, {\n ...replyMessage,\n replyToMessageId: undefined,\n });\n setGlobal(global);\n }\n\n return undefined;\n }\n\n let global = getGlobal();\n global = updateChatMessage(global, chat.id, messageId, result.message);\n global = addUsers(global, buildCollectionByKey(result.users, 'id'));\n setGlobal(global);\n\n return result.message;\n}\n\nfunction findClosestIndex(sourceIds: number[], offsetId: number) {\n if (offsetId < sourceIds[0]) {\n return 0;\n }\n\n if (offsetId > sourceIds[sourceIds.length - 1]) {\n return sourceIds.length - 1;\n }\n\n return sourceIds.findIndex((id, i) => (\n id === offsetId\n || (id < offsetId && sourceIds[i + 1] > offsetId)\n ));\n}\n\nfunction getViewportSlice(\n sourceIds: number[],\n offsetId: number | undefined,\n direction: LoadMoreDirection,\n) {\n const { length } = sourceIds;\n const index = offsetId ? findClosestIndex(sourceIds, offsetId) : -1;\n const isBackwards = direction === LoadMoreDirection.Backwards;\n const indexForDirection = isBackwards ? index : (index + 1) || length;\n const from = indexForDirection - MESSAGE_LIST_SLICE;\n const to = indexForDirection + MESSAGE_LIST_SLICE - 1;\n const newViewportIds = sourceIds.slice(Math.max(0, from), to + 1);\n\n let areSomeLocal;\n let areAllLocal;\n switch (direction) {\n case LoadMoreDirection.Backwards:\n areSomeLocal = indexForDirection > 0;\n areAllLocal = from >= 0;\n break;\n case LoadMoreDirection.Forwards:\n areSomeLocal = indexForDirection < length;\n areAllLocal = to <= length - 1;\n break;\n case LoadMoreDirection.Around:\n default:\n areSomeLocal = newViewportIds.length > 0;\n areAllLocal = newViewportIds.length === MESSAGE_LIST_SLICE;\n break;\n }\n\n return { newViewportIds, areSomeLocal, areAllLocal };\n}\n\nasync function sendMessage(params: {\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 serverTimeOffset?: number;\n isSilent?: boolean;\n scheduledAt?: number;\n sendAs?: ApiChat | ApiUser;\n}) {\n let localId: number | undefined;\n const progressCallback = params.attachment ? (progress: number, messageLocalId: number) => {\n if (!uploadProgressCallbacks.has(messageLocalId)) {\n localId = messageLocalId;\n uploadProgressCallbacks.set(messageLocalId, progressCallback!);\n }\n\n const global = getGlobal();\n\n setGlobal({\n ...global,\n fileUploads: {\n byMessageLocalId: {\n ...global.fileUploads.byMessageLocalId,\n [messageLocalId]: { progress },\n },\n },\n });\n } : undefined;\n\n // @optimization\n if (params.replyingTo || IS_IOS) {\n await rafPromise();\n }\n\n const global = getGlobal();\n params.serverTimeOffset = global.serverTimeOffset;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n const { threadId } = currentMessageList;\n\n if (!params.replyingTo && threadId !== MAIN_THREAD_ID) {\n params.replyingTo = selectThreadTopMessageId(global, params.chat.id, threadId)!;\n }\n\n await callApi('sendMessage', params, progressCallback);\n\n if (progressCallback && localId) {\n uploadProgressCallbacks.delete(localId);\n }\n}\n\nasync function loadPollOptionResults(\n chat: ApiChat,\n messageId: number,\n option: string,\n offset?: string,\n limit?: number,\n shouldResetVoters?: boolean,\n) {\n const result = await callApi('loadPollOptionResults', {\n chat, messageId, option, offset, limit,\n });\n\n if (!result) {\n return;\n }\n\n let global = getGlobal();\n\n global = addUsers(global, buildCollectionByKey(result.users, 'id'));\n const { voters } = global.pollResults;\n\n setGlobal({\n ...global,\n pollResults: {\n ...global.pollResults,\n voters: {\n ...voters,\n [option]: unique([\n ...(!shouldResetVoters && voters && voters[option] ? voters[option] : []),\n ...(result && result.users.map((user) => user.id)),\n ]),\n },\n offsets: {\n ...(global.pollResults.offsets ? global.pollResults.offsets : {}),\n [option]: result.nextOffset || '',\n },\n },\n });\n}\n\naddReducer('loadPinnedMessages', (global, actions, payload) => {\n const { chatId } = payload;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n void loadPinnedMessages(chat);\n});\n\naddReducer('loadSeenBy', (global, actions, payload) => {\n const { chatId, messageId } = payload;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n (async () => {\n const result = await callApi('fetchSeenBy', { chat, messageId });\n if (!result) {\n return;\n }\n\n setGlobal(updateChatMessage(getGlobal(), chatId, messageId, {\n seenByUserIds: result,\n }));\n })();\n});\n\naddReducer('saveDefaultSendAs', (global, actions, payload) => {\n const { chatId, sendAsId } = payload;\n const chat = selectChat(global, chatId);\n const sendAsChat = selectChat(global, sendAsId) || selectUser(global, sendAsId);\n if (!chat || !sendAsChat) {\n return undefined;\n }\n\n void callApi('saveDefaultSendAs', { sendAs: sendAsChat, chat });\n\n return updateChat(global, chatId, {\n fullInfo: {\n ...chat.fullInfo,\n sendAsId,\n },\n });\n});\n\naddReducer('loadSendAs', (global, actions, payload) => {\n const { chatId } = payload;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n (async () => {\n const result = await callApi('fetchSendAs', { chat });\n if (!result) {\n global = updateChat(global, chatId, {\n sendAsIds: [],\n });\n setGlobal(global);\n return;\n }\n\n global = getGlobal();\n global = addUsers(global, buildCollectionByKey(result.users, 'id'));\n global = addChats(global, buildCollectionByKey(result.chats, 'id'));\n global = updateChat(global, chatId, {\n sendAsIds: result.ids,\n });\n setGlobal(global);\n })();\n});\n\nasync function loadPinnedMessages(chat: ApiChat) {\n const result = await callApi('fetchPinnedMessages', { chat });\n if (!result) {\n return;\n }\n\n const { messages, chats, users } = result;\n\n const byId = buildCollectionByKey(messages, 'id');\n const ids = Object.keys(byId).map(Number).sort((a, b) => b - a);\n\n let global = getGlobal();\n global = addChatMessagesById(global, chat.id, byId);\n global = replaceThreadParam(global, chat.id, MAIN_THREAD_ID, 'pinnedIds', ids);\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = addChats(global, buildCollectionByKey(chats, 'id'));\n setGlobal(global);\n}\n\nasync function loadScheduledHistory(chat: ApiChat) {\n const result = await callApi('fetchScheduledHistory', { chat });\n if (!result) {\n return;\n }\n\n const { messages } = result;\n\n const byId = buildCollectionByKey(messages, 'id');\n const ids = Object.keys(byId).map(Number).sort((a, b) => b - a);\n\n let global = getGlobal();\n global = replaceScheduledMessages(global, chat.id, byId);\n global = replaceThreadParam(global, chat.id, MAIN_THREAD_ID, 'scheduledIds', ids);\n setGlobal(global);\n}\n\naddReducer('loadSponsoredMessages', (global, actions, payload) => {\n const { chatId } = payload;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n (async () => {\n const result = await callApi('fetchSponsoredMessages', { chat });\n if (!result) {\n return;\n }\n\n let newGlobal = updateSponsoredMessage(getGlobal(), chatId, result.messages[0]);\n newGlobal = addUsers(newGlobal, buildCollectionByKey(result.users, 'id'));\n newGlobal = addChats(newGlobal, buildCollectionByKey(result.chats, 'id'));\n\n setGlobal(newGlobal);\n })();\n});\n\naddReducer('viewSponsoredMessage', (global, actions, payload) => {\n const { chatId } = payload;\n const chat = selectChat(global, chatId);\n const message = selectSponsoredMessage(global, chatId);\n if (!chat || !message) {\n return;\n }\n\n void callApi('viewSponsoredMessage', { chat, random: message.randomId });\n});\n\nfunction countSortedIds(ids: number[], from: number, to: number) {\n let count = 0;\n\n for (let i = 0, l = ids.length; i < l; i++) {\n if (ids[i] >= from && ids[i] <= to) {\n count++;\n }\n\n if (ids[i] >= to) {\n break;\n }\n }\n\n return count;\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiSticker } from '../../../api/types';\nimport { LangCode } from '../../../types';\nimport { callApi } from '../../../api/gramjs';\nimport { pause, throttle } from '../../../util/schedulers';\nimport {\n updateStickerSets,\n updateStickerSet,\n replaceAnimatedEmojis,\n updateGifSearch,\n updateStickersForEmoji,\n rebuildStickersForEmoji,\n} from '../../reducers';\nimport searchWords from '../../../util/searchWords';\nimport { selectStickerSet } from '../../selectors';\n\nconst ADDED_SETS_THROTTLE = 200;\nconst ADDED_SETS_THROTTLE_CHUNK = 10;\n\nconst searchThrottled = throttle((cb) => cb(), 500, false);\n\naddReducer('loadStickerSets', (global) => {\n const { hash } = global.stickers.added || {};\n void loadStickerSets(hash);\n});\n\naddReducer('loadAddedStickers', (global, actions) => {\n const { setIds: addedSetIds } = global.stickers.added;\n if (!addedSetIds || !addedSetIds.length) {\n return;\n }\n\n (async () => {\n for (let i = 0; i < addedSetIds.length; i++) {\n actions.loadStickers({ stickerSetId: addedSetIds[i] });\n\n if (i % ADDED_SETS_THROTTLE_CHUNK === 0 && i > 0) {\n await pause(ADDED_SETS_THROTTLE);\n }\n }\n })();\n});\n\naddReducer('loadRecentStickers', (global) => {\n const { hash } = global.stickers.recent || {};\n void loadRecentStickers(hash);\n});\n\naddReducer('loadFavoriteStickers', (global) => {\n const { hash } = global.stickers.favorite || {};\n void loadFavoriteStickers(hash);\n});\n\naddReducer('loadGreetingStickers', (global) => {\n const { hash } = global.stickers.greeting || {};\n\n (async () => {\n const greeting = await callApi('fetchStickersForEmoji', { emoji: '👋⭐️', hash });\n\n if (!greeting) {\n return;\n }\n\n const newGlobal = getGlobal();\n\n setGlobal({\n ...newGlobal,\n stickers: {\n ...newGlobal.stickers,\n greeting: {\n hash: greeting.hash,\n stickers: greeting.stickers.filter((sticker) => sticker.emoji === '👋'),\n },\n },\n });\n })();\n});\n\naddReducer('loadFeaturedStickers', (global) => {\n const { hash } = global.stickers.featured || {};\n void loadFeaturedStickers(hash);\n});\n\naddReducer('loadStickers', (global, actions, payload) => {\n const { stickerSetId, stickerSetShortName } = payload!;\n let { stickerSetAccessHash } = payload!;\n\n if (!stickerSetAccessHash && !stickerSetShortName) {\n const stickerSet = selectStickerSet(global, stickerSetId);\n if (!stickerSet) {\n return;\n }\n\n stickerSetAccessHash = stickerSet.accessHash;\n }\n\n void loadStickers(stickerSetId, stickerSetAccessHash, stickerSetShortName);\n});\n\naddReducer('loadAnimatedEmojis', () => {\n void loadAnimatedEmojis();\n});\n\naddReducer('loadSavedGifs', (global) => {\n const { hash } = global.gifs.saved;\n void loadSavedGifs(hash);\n});\n\naddReducer('faveSticker', (global, actions, payload) => {\n const { sticker } = payload!;\n\n if (sticker) {\n void callApi('faveSticker', { sticker });\n }\n});\n\naddReducer('unfaveSticker', (global, actions, payload) => {\n const { sticker } = payload!;\n\n if (sticker) {\n void unfaveSticker(sticker);\n }\n});\n\naddReducer('toggleStickerSet', (global, actions, payload) => {\n const { stickerSetId } = payload!;\n const stickerSet = selectStickerSet(global, stickerSetId);\n if (!stickerSet) {\n return;\n }\n\n const { accessHash, installedDate } = stickerSet;\n\n void callApi(!installedDate ? 'installStickerSet' : 'uninstallStickerSet', { stickerSetId, accessHash });\n});\n\naddReducer('loadEmojiKeywords', (global, actions, payload: { language: LangCode }) => {\n const { language } = payload;\n\n let currentEmojiKeywords = global.emojiKeywords[language];\n if (currentEmojiKeywords?.isLoading) {\n return;\n }\n\n setGlobal({\n ...global,\n emojiKeywords: {\n ...global.emojiKeywords,\n [language]: {\n ...currentEmojiKeywords,\n isLoading: true,\n },\n },\n });\n\n (async () => {\n const emojiKeywords = await callApi('fetchEmojiKeywords', {\n language,\n fromVersion: currentEmojiKeywords ? currentEmojiKeywords.version : 0,\n });\n\n global = getGlobal();\n currentEmojiKeywords = global.emojiKeywords[language];\n\n if (!emojiKeywords) {\n setGlobal({\n ...global,\n emojiKeywords: {\n ...global.emojiKeywords,\n [language]: {\n ...currentEmojiKeywords,\n isLoading: false,\n },\n },\n });\n\n return;\n }\n\n setGlobal({\n ...global,\n emojiKeywords: {\n ...global.emojiKeywords,\n [language]: {\n isLoading: false,\n version: emojiKeywords.version,\n keywords: {\n ...(currentEmojiKeywords?.keywords),\n ...emojiKeywords.keywords,\n },\n },\n },\n });\n })();\n});\n\nasync function loadStickerSets(hash?: string) {\n const addedStickers = await callApi('fetchStickerSets', { hash });\n if (!addedStickers) {\n return;\n }\n\n setGlobal(updateStickerSets(\n getGlobal(),\n 'added',\n addedStickers.hash,\n addedStickers.sets,\n ));\n}\n\nasync function loadRecentStickers(hash?: string) {\n const recentStickers = await callApi('fetchRecentStickers', { hash });\n if (!recentStickers) {\n return;\n }\n\n const global = getGlobal();\n\n setGlobal({\n ...global,\n stickers: {\n ...global.stickers,\n recent: recentStickers,\n },\n });\n}\n\nasync function loadFavoriteStickers(hash?: string) {\n const favoriteStickers = await callApi('fetchFavoriteStickers', { hash });\n if (!favoriteStickers) {\n return;\n }\n\n const global = getGlobal();\n\n setGlobal({\n ...global,\n stickers: {\n ...global.stickers,\n favorite: favoriteStickers,\n },\n });\n}\n\nasync function loadFeaturedStickers(hash?: string) {\n const featuredStickers = await callApi('fetchFeaturedStickers', { hash });\n if (!featuredStickers) {\n return;\n }\n\n setGlobal(updateStickerSets(\n getGlobal(),\n 'featured',\n featuredStickers.hash,\n featuredStickers.sets,\n ));\n}\n\nasync function loadStickers(stickerSetId: string, accessHash: string, stickerSetShortName?: string) {\n const stickerSet = await callApi(\n 'fetchStickers',\n { stickerSetShortName, stickerSetId, accessHash },\n );\n if (!stickerSet) {\n return;\n }\n\n const { set, stickers, packs } = stickerSet;\n\n let global = getGlobal();\n\n global = updateStickerSet(global, set.id, { ...set, stickers, packs });\n\n const currentEmoji = global.stickers.forEmoji.emoji;\n if (currentEmoji && packs[currentEmoji]) {\n global = rebuildStickersForEmoji(global);\n }\n\n setGlobal(global);\n}\n\nasync function loadAnimatedEmojis() {\n const stickerSet = await callApi('fetchAnimatedEmojis');\n if (!stickerSet) {\n return;\n }\n\n const { set, stickers } = stickerSet;\n\n setGlobal(replaceAnimatedEmojis(getGlobal(), { ...set, stickers }));\n}\n\nfunction unfaveSticker(sticker: ApiSticker) {\n const global = getGlobal();\n\n // Remove sticker preemptively to get instant feedback when user removes sticker\n // from favorites while in Sticker Picker\n setGlobal({\n ...global,\n stickers: {\n ...global.stickers,\n favorite: {\n ...global.stickers.favorite,\n stickers: global.stickers.favorite.stickers.filter(({ id }) => id !== sticker.id),\n },\n },\n });\n\n void callApi('faveSticker', { sticker, unfave: true });\n}\n\naddReducer('setStickerSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n\n if (query) {\n void searchThrottled(() => {\n searchStickers(query);\n });\n }\n});\n\naddReducer('setGifSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n\n if (typeof query === 'string') {\n void searchThrottled(() => {\n searchGifs(query);\n });\n }\n});\n\naddReducer('searchMoreGifs', (global) => {\n const { query, offset } = global.gifs.search;\n\n if (typeof query === 'string') {\n void searchThrottled(() => {\n searchGifs(query, offset);\n });\n }\n});\n\naddReducer('loadStickersForEmoji', (global, actions, payload) => {\n const { emoji } = payload!;\n const { hash } = global.stickers.forEmoji;\n\n void searchThrottled(() => {\n loadStickersForEmoji(emoji, hash);\n });\n});\n\naddReducer('clearStickersForEmoji', (global) => {\n return {\n ...global,\n stickers: {\n ...global.stickers,\n forEmoji: {},\n },\n };\n});\n\naddReducer('openStickerSetShortName', (global, actions, payload) => {\n const { stickerSetShortName } = payload!;\n return {\n ...global,\n openedStickerSetShortName: stickerSetShortName,\n };\n});\n\nasync function searchStickers(query: string, hash?: string) {\n const result = await callApi('searchStickers', { query, hash });\n\n if (!result) {\n return;\n }\n\n const global = getGlobal();\n const { setsById, added } = global.stickers;\n\n const resultIds = result.sets.map(({ id }) => id);\n\n if (added.setIds) {\n added.setIds.forEach((id) => {\n if (!resultIds.includes(id)) {\n const { title } = setsById[id] || {};\n if (title && searchWords(title, query)) {\n resultIds.unshift(id);\n }\n }\n });\n }\n\n setGlobal(updateStickerSets(\n global,\n 'search',\n result.hash,\n result.sets,\n resultIds,\n ));\n}\n\nasync function searchGifs(query: string, offset?: string) {\n const result = await callApi('searchGifs', { query, offset });\n if (!result) {\n return;\n }\n\n setGlobal(updateGifSearch(getGlobal(), !offset, result.gifs, result.nextOffset));\n}\n\nasync function loadSavedGifs(hash?: string) {\n const savedGifs = await callApi('fetchSavedGifs', { hash });\n if (!savedGifs) {\n return;\n }\n\n const global = getGlobal();\n\n setGlobal({\n ...global,\n gifs: {\n ...global.gifs,\n saved: savedGifs,\n },\n });\n}\n\nasync function loadStickersForEmoji(emoji: string, hash?: string) {\n let global = getGlobal();\n setGlobal({\n ...global,\n stickers: {\n ...global.stickers,\n forEmoji: {\n ...global.stickers.forEmoji,\n emoji,\n },\n },\n });\n\n const result = await callApi('fetchStickersForEmoji', { emoji, hash });\n\n global = getGlobal();\n\n if (!result || global.stickers.forEmoji.emoji !== emoji) {\n return;\n }\n\n global = updateStickersForEmoji(global, emoji, result.stickers, result.hash);\n\n setGlobal(global);\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { callApi } from '../../../api/gramjs';\nimport { ApiChat, ApiGlobalMessageSearchType } from '../../../api/types';\n\nimport {\n addChats,\n addMessages,\n addUsers,\n updateGlobalSearch,\n updateGlobalSearchFetchingStatus,\n updateGlobalSearchResults,\n} from '../../reducers';\nimport { throttle } from '../../../util/schedulers';\nimport { selectChat, selectCurrentGlobalSearchQuery } from '../../selectors';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport { GLOBAL_SEARCH_SLICE } from '../../../config';\nimport { timestampPlusDay } from '../../../util/dateFormat';\n\nconst searchThrottled = throttle((cb) => cb(), 500, false);\n\naddReducer('setGlobalSearchQuery', (global, actions, payload) => {\n const { chatId } = global.globalSearch;\n const { query } = payload!;\n\n if (query && !chatId) {\n void searchThrottled(() => {\n searchChats(query);\n });\n }\n});\n\naddReducer('setGlobalSearchDate', (global, actions, payload) => {\n const { date } = payload!;\n const maxDate = date ? timestampPlusDay(date) : date;\n const newGlobal = updateGlobalSearch(global, {\n date,\n query: '',\n resultsByType: {\n ...global.globalSearch.resultsByType,\n text: {\n totalCount: undefined,\n foundIds: [],\n nextOffsetId: 0,\n },\n },\n });\n setGlobal(newGlobal);\n const { chatId } = global.globalSearch;\n const chat = chatId ? selectChat(global, chatId) : undefined;\n searchMessagesGlobal('', 'text', undefined, chat, maxDate, date);\n});\n\naddReducer('searchMessagesGlobal', (global, actions, payload) => {\n const {\n query, resultsByType, chatId, date,\n } = global.globalSearch;\n const maxDate = date ? timestampPlusDay(date) : date;\n const { type } = payload;\n const nextOffsetId = (resultsByType?.[type as ApiGlobalMessageSearchType])?.nextOffsetId;\n\n const chat = chatId ? selectChat(global, chatId) : undefined;\n\n searchMessagesGlobal(query, type, nextOffsetId, chat, maxDate, date);\n});\n\nasync function searchChats(query: string) {\n const result = await callApi('searchChats', { query });\n\n let global = getGlobal();\n const currentSearchQuery = selectCurrentGlobalSearchQuery(global);\n if (!result || !currentSearchQuery || (query !== currentSearchQuery)) {\n setGlobal(updateGlobalSearchFetchingStatus(global, { chats: false }));\n return;\n }\n\n const {\n localChats, localUsers, globalChats, globalUsers,\n } = result;\n\n if (localChats.length || globalChats.length) {\n global = addChats(global, buildCollectionByKey([...localChats, ...globalChats], 'id'));\n }\n\n if (localUsers.length || globalUsers.length) {\n global = addUsers(global, buildCollectionByKey([...localUsers, ...globalUsers], 'id'));\n }\n\n global = updateGlobalSearchFetchingStatus(global, { chats: false });\n global = updateGlobalSearch(global, {\n localResults: {\n chatIds: localChats.map(({ id }) => id),\n userIds: localUsers.map(({ id }) => id),\n },\n globalResults: {\n ...global.globalSearch.globalResults,\n chatIds: globalChats.map(({ id }) => id),\n userIds: globalUsers.map(({ id }) => id),\n },\n });\n\n setGlobal(global);\n}\n\nasync function searchMessagesGlobal(\n query = '', type: ApiGlobalMessageSearchType, offsetRate?: number, chat?: ApiChat, maxDate?: number, minDate?: number,\n) {\n let result;\n\n if (chat) {\n const localResult = await callApi('searchMessagesLocal', {\n chatOrUser: chat,\n query,\n type,\n limit: GLOBAL_SEARCH_SLICE,\n offsetId: offsetRate,\n minDate,\n maxDate,\n });\n\n if (localResult) {\n const {\n messages, users, totalCount, nextOffsetId,\n } = localResult;\n\n result = {\n messages,\n users,\n chats: [],\n totalCount,\n nextRate: nextOffsetId,\n };\n }\n } else {\n result = await callApi('searchMessagesGlobal', {\n query,\n offsetRate,\n limit: GLOBAL_SEARCH_SLICE,\n type,\n maxDate,\n minDate,\n });\n }\n\n let global = getGlobal();\n const currentSearchQuery = selectCurrentGlobalSearchQuery(global);\n if (!result || (query !== '' && query !== currentSearchQuery)) {\n setGlobal(updateGlobalSearchFetchingStatus(global, { messages: false }));\n return;\n }\n\n const {\n messages, users, chats, totalCount, nextRate,\n } = result;\n\n if (chats.length) {\n global = addChats(global, buildCollectionByKey(chats, 'id'));\n }\n\n if (users.length) {\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n }\n\n if (messages.length) {\n global = addMessages(global, messages);\n }\n\n global = updateGlobalSearchResults(\n global,\n messages,\n totalCount,\n type,\n nextRate,\n );\n\n setGlobal(global);\n}\n","import {\n addReducer, getDispatch, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { ApiChat, ApiUser, MAIN_THREAD_ID } from '../../../api/types';\n\nimport { MESSAGE_SEARCH_SLICE, SHARED_MEDIA_SLICE } from '../../../config';\nimport { callApi } from '../../../api/gramjs';\nimport {\n selectCurrentTextSearch,\n selectCurrentMediaSearchPeerId,\n selectCurrentMediaSearch, selectCurrentMessageList, selectChat, selectThreadInfo,\n} from '../../selectors';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport {\n addChatMessagesById,\n addUsers,\n updateLocalMediaSearchResults,\n updateLocalTextSearchResults,\n} from '../../reducers';\nimport { SharedMediaType } from '../../../types';\n\naddReducer('searchTextMessagesLocal', (global) => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n const chat = chatId ? selectChat(global, chatId) : undefined;\n const currentSearch = selectCurrentTextSearch(global);\n if (!chat || !currentSearch || !threadId) {\n return;\n }\n\n const { query, results } = currentSearch;\n const offsetId = results?.nextOffsetId;\n\n let topMessageId: number | undefined;\n if (threadId !== MAIN_THREAD_ID) {\n const threadInfo = selectThreadInfo(global, chatId!, threadId);\n topMessageId = threadInfo?.topMessageId;\n }\n\n void searchTextMessages(chat, threadId, topMessageId, query, offsetId);\n});\n\naddReducer('searchMediaMessagesLocal', (global) => {\n const peerId = selectCurrentMediaSearchPeerId(global);\n const chatOrUser = peerId\n ? global.users.byId[peerId] || global.chats.byId[peerId]\n : undefined;\n const currentSearch = selectCurrentMediaSearch(global);\n\n if (!chatOrUser || !currentSearch) {\n return;\n }\n\n const { currentType: type, resultsByType } = currentSearch;\n const currentResults = type && resultsByType && resultsByType[type];\n const offsetId = currentResults?.nextOffsetId;\n\n if (!type) {\n return;\n }\n\n void searchSharedMedia(chatOrUser, type, offsetId);\n});\n\naddReducer('searchMessagesByDate', (global, actions, payload) => {\n const { timestamp } = payload!;\n\n const { chatId } = selectCurrentMessageList(global) || {};\n if (!chatId) {\n return;\n }\n\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n void searchMessagesByDate(chat, timestamp);\n});\n\nasync function searchTextMessages(\n chatOrUser: ApiChat,\n threadId: number,\n topMessageId?: number,\n query?: string,\n offsetId?: number,\n) {\n const result = await callApi('searchMessagesLocal', {\n chatOrUser,\n type: 'text',\n query,\n topMessageId,\n limit: MESSAGE_SEARCH_SLICE,\n offsetId,\n });\n\n if (!result) {\n return;\n }\n\n const {\n messages, users, totalCount, nextOffsetId,\n } = result;\n\n const byId = buildCollectionByKey(messages, 'id');\n const newFoundIds = Object.keys(byId).map(Number);\n\n let global = getGlobal();\n\n const currentSearch = selectCurrentTextSearch(global);\n if (!currentSearch || (query && query !== currentSearch.query)) {\n return;\n }\n\n global = addChatMessagesById(global, chatOrUser.id, byId);\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = updateLocalTextSearchResults(global, chatOrUser.id, threadId, newFoundIds, totalCount, nextOffsetId);\n setGlobal(global);\n}\n\nasync function searchSharedMedia(\n chatOrUser: ApiChat | ApiUser,\n type: SharedMediaType,\n offsetId?: number,\n) {\n const result = await callApi('searchMessagesLocal', {\n chatOrUser,\n type,\n limit: SHARED_MEDIA_SLICE,\n offsetId,\n });\n\n if (!result) {\n return;\n }\n\n const {\n messages, users, totalCount, nextOffsetId,\n } = result;\n\n const byId = buildCollectionByKey(messages, 'id');\n const newFoundIds = Object.keys(byId).map(Number);\n\n let global = getGlobal();\n\n const currentSearch = selectCurrentMediaSearch(global);\n if (!currentSearch) {\n return;\n }\n\n global = addChatMessagesById(global, chatOrUser.id, byId);\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = updateLocalMediaSearchResults(global, chatOrUser.id, type, newFoundIds, totalCount, nextOffsetId);\n setGlobal(global);\n}\n\n/**\n * @param timestamp start of target date in seconds\n */\nasync function searchMessagesByDate(chat: ApiChat, timestamp: number) {\n const messageId = await callApi('findFirstMessageIdAfterDate', {\n chat,\n timestamp,\n });\n\n if (!messageId) {\n return;\n }\n\n getDispatch().focusMessage({\n chatId: chat.id,\n messageId,\n });\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { ManagementProgress } from '../../../types';\nimport { callApi } from '../../../api/gramjs';\nimport { updateManagement, updateManagementProgress } from '../../reducers';\nimport { selectChat, selectCurrentMessageList } from '../../selectors';\nimport { isChatBasicGroup } from '../../helpers';\n\naddReducer('checkPublicLink', (global, actions, payload) => {\n const { chatId } = selectCurrentMessageList(global) || {};\n if (!chatId) {\n return;\n }\n\n // No need to check the username if already in progress\n if (global.management.progress === ManagementProgress.InProgress) {\n return;\n }\n\n const { username } = payload!;\n\n (async () => {\n global = updateManagementProgress(global, ManagementProgress.InProgress);\n global = updateManagement(global, chatId, { isUsernameAvailable: undefined });\n setGlobal(global);\n\n const isUsernameAvailable = await callApi('checkChatUsername', { username })!;\n\n global = getGlobal();\n global = updateManagementProgress(\n global, isUsernameAvailable ? ManagementProgress.Complete : ManagementProgress.Error,\n );\n global = updateManagement(global, chatId, { isUsernameAvailable });\n setGlobal(global);\n })();\n});\n\naddReducer('updatePublicLink', (global, actions, payload) => {\n const { chatId } = selectCurrentMessageList(global) || {};\n let chat = chatId && selectChat(global, chatId);\n if (!chatId || !chat) {\n return;\n }\n\n const { username } = payload!;\n\n (async () => {\n global = updateManagementProgress(global, ManagementProgress.InProgress);\n setGlobal(global);\n\n if (isChatBasicGroup(chat)) {\n chat = await callApi('migrateChat', chat);\n\n if (!chat) {\n return;\n }\n\n actions.openChat({ id: chat.id });\n }\n\n const result = await callApi('setChatUsername', { chat, username });\n\n global = getGlobal();\n global = updateManagementProgress(global, result ? ManagementProgress.Complete : ManagementProgress.Error);\n global = updateManagement(global, chatId, { isUsernameAvailable: undefined });\n setGlobal(global);\n })();\n});\n\naddReducer('updatePrivateLink', (global) => {\n const { chatId } = selectCurrentMessageList(global) || {};\n const chat = chatId && selectChat(global, chatId);\n if (!chatId || !chat) {\n return;\n }\n\n callApi('updatePrivateLink', { chat });\n});\n","import {\n addReducer, getGlobal, setGlobal, getDispatch,\n} from '../../../lib/teact/teactn';\n\nimport {\n ApiChat, ApiFormattedText, ApiMessage, ApiUser, MAIN_THREAD_ID,\n} from '../../../api/types';\n\nimport {\n CHAT_LIST_LOAD_SLICE, DEBUG, MESSAGE_LIST_SLICE, SERVICE_NOTIFICATIONS_USER_ID,\n} from '../../../config';\nimport { callApi } from '../../../api/gramjs';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport { updateAppBadge } from '../../../util/appBadge';\nimport {\n replaceChatListIds,\n replaceChats,\n replaceUsers,\n replaceUserStatuses,\n updateUsers,\n addUserStatuses,\n updateChats,\n updateChatListSecondaryInfo,\n updateThreadInfos,\n replaceThreadParam,\n updateListedIds,\n safeReplaceViewportIds,\n addChatMessagesById,\n} from '../../reducers';\nimport {\n selectUser,\n selectChat,\n selectCurrentMessageList,\n selectDraft,\n selectChatMessage,\n selectThreadInfo,\n selectCountNotMutedUnread,\n selectLastServiceNotification,\n} from '../../selectors';\nimport { isUserId } from '../../helpers';\n\naddReducer('sync', (global, actions) => {\n void sync(actions.afterSync);\n});\n\naddReducer('afterSync', () => {\n void afterSync();\n});\n\nasync function sync(afterSyncCallback: () => void) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START SYNC');\n }\n\n await callApi('fetchCurrentUser');\n\n // This fetches only active chats and clears archived chats, which will be fetched in `afterSync`\n const savedUsers = await loadAndReplaceChats();\n await loadAndReplaceMessages(savedUsers);\n\n setGlobal({\n ...getGlobal(),\n lastSyncTime: Date.now(),\n });\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH SYNC');\n }\n\n afterSyncCallback();\n}\n\nasync function afterSync() {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START AFTER-SYNC');\n }\n\n await Promise.all([\n loadAndUpdateUsers(),\n loadAndReplaceArchivedChats(),\n ]);\n\n await callApi('fetchCurrentUser');\n\n updateAppBadge(selectCountNotMutedUnread(getGlobal()));\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH AFTER-SYNC');\n }\n}\n\nasync function loadAndReplaceChats() {\n let global = getGlobal();\n\n const result = await callApi('fetchChats', {\n limit: CHAT_LIST_LOAD_SLICE,\n withPinned: true,\n serverTimeOffset: global.serverTimeOffset,\n lastLocalServiceMessage: selectLastServiceNotification(global)?.message,\n });\n\n if (!result) {\n return undefined;\n }\n\n global = getGlobal();\n\n const { recentlyFoundChatIds } = global.globalSearch;\n const { userIds: contactIds } = global.contactList || {};\n const { currentUserId } = global;\n\n const savedPrivateChatIds = [\n ...(recentlyFoundChatIds || []),\n ...(contactIds || []),\n ...(currentUserId ? [currentUserId] : []),\n ];\n\n const savedUsers = savedPrivateChatIds\n .map((id) => selectUser(global, id))\n .filter(Boolean as any);\n\n const savedChats = savedPrivateChatIds\n .map((id) => selectChat(global, id))\n .filter(Boolean as any);\n\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n if (currentChatId) {\n const selectedChat = selectChat(global, currentChatId);\n if (selectedChat && !savedPrivateChatIds.includes(currentChatId)) {\n savedChats.push(selectedChat);\n }\n\n if (isUserId(currentChatId)) {\n const selectedChatUser = selectUser(global, currentChatId);\n if (selectedChatUser && !savedPrivateChatIds.includes(currentChatId)) {\n savedUsers.push(selectedChatUser);\n }\n }\n }\n\n savedUsers.push(...result.users);\n savedChats.push(...result.chats);\n\n global = replaceUserStatuses(global, result.userStatusesById);\n\n global = replaceChats(global, buildCollectionByKey(savedChats, 'id'));\n global = replaceChatListIds(global, 'active', result.chatIds);\n global = updateChatListSecondaryInfo(global, 'active', result);\n\n Object.keys(result.draftsById).forEach((chatId) => {\n global = replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'draft', result.draftsById[chatId]);\n });\n\n Object.keys(result.replyingToById).forEach((chatId) => {\n global = replaceThreadParam(\n global, chatId, MAIN_THREAD_ID, 'replyingToId', result.replyingToById[chatId],\n );\n });\n\n setGlobal(global);\n\n if (currentChatId && !global.chats.byId[currentChatId]) {\n getDispatch().openChat({ id: undefined });\n }\n\n return savedUsers;\n}\n\nasync function loadAndReplaceArchivedChats() {\n const result = await callApi('fetchChats', {\n limit: CHAT_LIST_LOAD_SLICE,\n archived: true,\n withPinned: true,\n serverTimeOffset: getGlobal().serverTimeOffset,\n });\n\n if (!result) {\n return;\n }\n\n let global = getGlobal();\n\n global = updateUsers(global, buildCollectionByKey(result.users, 'id'));\n global = addUserStatuses(global, result.userStatusesById);\n\n global = updateChats(global, buildCollectionByKey(result.chats, 'id'));\n global = replaceChatListIds(global, 'archived', result.chatIds);\n global = updateChatListSecondaryInfo(global, 'archived', result);\n\n setGlobal(global);\n}\n\nasync function loadAndReplaceMessages(savedUsers?: ApiUser[]) {\n let areMessagesLoaded = false;\n let users = savedUsers || [];\n\n let global = getGlobal();\n const { chatId: currentChatId, threadId: currentThreadId } = selectCurrentMessageList(global) || {};\n\n // Memoize drafts\n const draftChatIds = Object.keys(global.messages.byChatId);\n const draftsByChatId = draftChatIds.reduce>((acc, chatId) => {\n const draft = selectDraft(global, chatId, MAIN_THREAD_ID);\n if (draft) {\n acc[chatId] = draft;\n }\n\n return acc;\n }, {});\n\n if (currentChatId) {\n const result = await loadTopMessages(global.chats.byId[currentChatId]);\n global = getGlobal();\n const { chatId: newCurrentChatId } = selectCurrentMessageList(global) || {};\n const threadInfo = currentThreadId && selectThreadInfo(global, currentChatId, currentThreadId);\n\n if (result && newCurrentChatId === currentChatId) {\n const currentMessageListInfo = global.messages.byChatId[currentChatId];\n const localMessages = currentChatId === SERVICE_NOTIFICATIONS_USER_ID\n ? global.serviceNotifications.map(({ message }) => message)\n : [];\n const allMessages = ([] as ApiMessage[]).concat(result.messages, localMessages);\n const byId = buildCollectionByKey(allMessages, 'id');\n const listedIds = Object.keys(byId).map(Number);\n\n global = {\n ...global,\n messages: {\n ...global.messages,\n byChatId: {},\n },\n };\n\n global = addChatMessagesById(global, currentChatId, byId);\n global = updateListedIds(global, currentChatId, MAIN_THREAD_ID, listedIds);\n global = safeReplaceViewportIds(global, currentChatId, MAIN_THREAD_ID, listedIds);\n\n if (currentThreadId && threadInfo && threadInfo.originChannelId) {\n const { originChannelId } = threadInfo;\n const currentMessageListInfoOrigin = global.messages.byChatId[originChannelId];\n const resultOrigin = await loadTopMessages(global.chats.byId[originChannelId]);\n if (resultOrigin) {\n const byIdOrigin = buildCollectionByKey(resultOrigin.messages, 'id');\n const listedIdsOrigin = Object.keys(byIdOrigin).map(Number);\n\n global = {\n ...global,\n messages: {\n ...global.messages,\n byChatId: {\n ...global.messages.byChatId,\n [threadInfo.originChannelId]: {\n byId: byIdOrigin,\n threadsById: {\n [MAIN_THREAD_ID]: {\n ...(currentMessageListInfoOrigin?.threadsById[MAIN_THREAD_ID]),\n listedIds: listedIdsOrigin,\n viewportIds: listedIdsOrigin,\n outlyingIds: undefined,\n },\n },\n },\n [currentChatId]: {\n ...global.messages.byChatId[currentChatId],\n threadsById: {\n ...global.messages.byChatId[currentChatId].threadsById,\n [currentThreadId]: {\n ...(currentMessageListInfo?.threadsById[currentThreadId]),\n outlyingIds: undefined,\n },\n },\n },\n },\n },\n };\n }\n }\n\n global = updateChats(global, buildCollectionByKey(result.chats, 'id'));\n global = updateThreadInfos(global, currentChatId, result.threadInfos);\n\n areMessagesLoaded = true;\n users = Array.prototype.concat(users, result.users);\n }\n }\n\n if (!areMessagesLoaded) {\n global = {\n ...global,\n messages: {\n ...global.messages,\n byChatId: {},\n },\n };\n }\n\n // Restore drafts\n Object.keys(draftsByChatId).forEach((chatId) => {\n global = replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'draft', draftsByChatId[chatId]);\n });\n\n if (savedUsers) {\n global = replaceUsers(global, buildCollectionByKey(users, 'id'));\n } else if (users) {\n // If `fetchChats` has failed for some reason, we don't have saved chats, thus we can not replace\n global = updateUsers(global, buildCollectionByKey(users, 'id'));\n }\n\n setGlobal(global);\n\n const { chatId: audioChatId, messageId: audioMessageId } = global.audioPlayer;\n if (audioChatId && audioMessageId && !selectChatMessage(global, audioChatId, audioMessageId)) {\n getDispatch().closeAudioPlayer();\n }\n}\n\nasync function loadAndUpdateUsers() {\n let global = getGlobal();\n const { recentlyFoundChatIds } = global.globalSearch;\n const { userIds: contactIds } = global.contactList || {};\n if (\n (!contactIds || !contactIds.length)\n && (!recentlyFoundChatIds || !recentlyFoundChatIds.length)\n ) {\n return;\n }\n\n const users = [\n ...(recentlyFoundChatIds || []),\n ...(contactIds || []),\n ].map((id) => selectUser(global, id)).filter(Boolean as any);\n\n const result = await callApi('fetchUsers', { users });\n if (!result) {\n return;\n }\n\n const { users: updatedUsers, userStatusesById } = result;\n\n global = getGlobal();\n global = updateUsers(global, buildCollectionByKey(updatedUsers, 'id'));\n global = addUserStatuses(global, userStatusesById);\n setGlobal(global);\n}\n\nfunction loadTopMessages(chat: ApiChat) {\n return callApi('fetchMessages', {\n chat,\n threadId: MAIN_THREAD_ID,\n offsetId: chat.lastReadInboxMessageId,\n addOffset: -(Math.round(MESSAGE_LIST_SLICE / 2) + 1),\n limit: MESSAGE_LIST_SLICE,\n });\n}\n","import {\n addReducer, getDispatch, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { ApiUser } from '../../../api/types';\nimport { ManagementProgress } from '../../../types';\n\nimport { debounce, throttle } from '../../../util/schedulers';\nimport { buildCollectionByKey, pick, unique } from '../../../util/iteratees';\nimport { isUserBot, isUserId } from '../../helpers';\nimport { callApi } from '../../../api/gramjs';\nimport { selectChat, selectCurrentMessageList, selectUser } from '../../selectors';\nimport {\n addChats, addUsers, replaceUserStatuses, updateChat, updateManagementProgress, updateUser, updateUsers,\n updateUserSearch, updateUserSearchFetchingStatus,\n} from '../../reducers';\nimport { getServerTime } from '../../../util/serverTime';\n\nconst runDebouncedForFetchFullUser = debounce((cb) => cb(), 500, false, true);\nconst TOP_PEERS_REQUEST_COOLDOWN = 60; // 1 min\nconst runThrottledForSearch = throttle((cb) => cb(), 500, false);\n\naddReducer('loadFullUser', (global, actions, payload) => {\n const { userId } = payload!;\n const user = selectUser(global, userId);\n if (!user) {\n return;\n }\n\n const { id, accessHash } = user;\n\n runDebouncedForFetchFullUser(() => callApi('fetchFullUser', { id, accessHash }));\n});\n\naddReducer('loadUser', (global, actions, payload) => {\n const { userId } = payload!;\n const user = selectUser(global, userId);\n if (!user) {\n return;\n }\n\n (async () => {\n const result = await callApi('fetchUsers', { users: [user] });\n if (!result) {\n return;\n }\n\n const { users, userStatusesById } = result;\n\n global = getGlobal();\n\n global = updateUsers(global, buildCollectionByKey(users, 'id'));\n setGlobal(replaceUserStatuses(global, {\n ...global.users.statusesById,\n ...userStatusesById,\n }));\n\n setGlobal(global);\n })();\n});\n\naddReducer('loadTopUsers', (global) => {\n const { topPeers: { lastRequestedAt } } = global;\n\n if (!lastRequestedAt || getServerTime(global.serverTimeOffset) - lastRequestedAt > TOP_PEERS_REQUEST_COOLDOWN) {\n void loadTopUsers();\n }\n});\n\naddReducer('loadContactList', () => {\n void loadContactList();\n});\n\naddReducer('loadCurrentUser', () => {\n void callApi('fetchCurrentUser');\n});\n\naddReducer('loadCommonChats', (global) => {\n const { chatId } = selectCurrentMessageList(global) || {};\n const user = chatId ? selectUser(global, chatId) : undefined;\n if (!user || isUserBot(user) || user.commonChats?.isFullyLoaded) {\n return;\n }\n\n (async () => {\n const maxId = user.commonChats?.maxId;\n const result = await callApi('fetchCommonChats', user.id, user.accessHash!, maxId);\n if (!result) {\n return;\n }\n\n const { chats, chatIds, isFullyLoaded } = result;\n\n global = getGlobal();\n if (chats.length) {\n global = addChats(global, buildCollectionByKey(chats, 'id'));\n }\n global = updateUser(global, user.id, {\n commonChats: {\n maxId: chatIds.length ? chatIds[chatIds.length - 1] : '0',\n ids: unique((user.commonChats?.ids || []).concat(chatIds)),\n isFullyLoaded,\n },\n });\n setGlobal(global);\n })();\n});\n\naddReducer('updateContact', (global, actions, payload) => {\n const {\n userId, isMuted, firstName, lastName,\n } = payload!;\n\n void updateContact(userId, isMuted, firstName, lastName);\n});\n\naddReducer('deleteContact', (global, actions, payload) => {\n const { userId } = payload!;\n\n void deleteContact(userId);\n});\n\nasync function loadTopUsers() {\n const result = await callApi('fetchTopUsers');\n if (!result) {\n return;\n }\n\n const { ids, users } = result;\n\n let global = getGlobal();\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = {\n ...global,\n topPeers: {\n ...global.topPeers,\n userIds: ids,\n lastRequestedAt: getServerTime(global.serverTimeOffset),\n },\n };\n setGlobal(global);\n}\n\nasync function loadContactList() {\n const contactList = await callApi('fetchContactList');\n if (!contactList) {\n return;\n }\n\n let global = addUsers(getGlobal(), buildCollectionByKey(contactList.users, 'id'));\n global = addChats(global, buildCollectionByKey(contactList.chats, 'id'));\n\n // Sort contact list by Last Name (or First Name), with latin names being placed first\n const getCompareString = (user: ApiUser) => (user.lastName || user.firstName || '');\n const collator = new Intl.Collator('en-US');\n\n const sortedUsers = contactList.users.sort((a, b) => (\n collator.compare(getCompareString(a), getCompareString(b))\n )).filter((user) => !user.isSelf);\n\n setGlobal({\n ...global,\n contactList: {\n userIds: sortedUsers.map((user) => user.id),\n },\n });\n}\n\nasync function updateContact(\n userId: string,\n isMuted: boolean,\n firstName: string,\n lastName?: string,\n) {\n const global = getGlobal();\n const user = selectUser(global, userId);\n if (!user) {\n return;\n }\n\n getDispatch().updateChatMutedState({ chatId: userId, isMuted });\n\n setGlobal(updateManagementProgress(getGlobal(), ManagementProgress.InProgress));\n\n let result;\n if (user.phoneNumber) {\n result = await callApi('updateContact', { phone: user.phoneNumber, firstName, lastName });\n } else {\n const { id, accessHash } = user;\n result = await callApi('addContact', {\n id,\n accessHash,\n phoneNumber: '',\n firstName,\n lastName,\n });\n }\n\n if (result) {\n setGlobal(updateUser(\n getGlobal(),\n user.id,\n {\n firstName,\n lastName,\n },\n ));\n }\n\n setGlobal(updateManagementProgress(getGlobal(), ManagementProgress.Complete));\n}\n\nasync function deleteContact(userId: string) {\n const global = getGlobal();\n const user = selectUser(global, userId);\n\n if (!user) {\n return;\n }\n\n const { id, accessHash } = user;\n\n await callApi('deleteContact', { id, accessHash });\n}\n\naddReducer('loadProfilePhotos', (global, actions, payload) => {\n const { profileId } = payload!;\n const isPrivate = isUserId(profileId);\n const user = isPrivate ? selectUser(global, profileId) : undefined;\n const chat = !isPrivate ? selectChat(global, profileId) : undefined;\n\n if (!user && !chat) {\n return;\n }\n\n (async () => {\n const result = await callApi('fetchProfilePhotos', user, chat);\n if (!result || !result.photos) {\n return;\n }\n\n let newGlobal = getGlobal();\n if (isPrivate) {\n newGlobal = updateUser(newGlobal, profileId, { photos: result.photos });\n } else {\n newGlobal = addUsers(newGlobal, buildCollectionByKey(result.users!, 'id'));\n newGlobal = updateChat(newGlobal, profileId, { photos: result.photos });\n }\n\n setGlobal(newGlobal);\n })();\n});\n\naddReducer('setUserSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n\n if (!query) return;\n\n void runThrottledForSearch(() => {\n searchUsers(query);\n });\n});\n\naddReducer('addContact', (global, actions, payload) => {\n const { userId } = payload!;\n const user = selectUser(global, userId);\n if (!user) {\n return;\n }\n\n void callApi('addContact', pick(user, ['id', 'accessHash', 'firstName', 'lastName', 'phoneNumber']));\n});\n\nasync function searchUsers(query: string) {\n const result = await callApi('searchChats', { query });\n\n let global = getGlobal();\n const currentSearchQuery = global.userSearch.query;\n\n if (!result || !currentSearchQuery || (query !== currentSearchQuery)) {\n setGlobal(updateUserSearchFetchingStatus(global, false));\n return;\n }\n\n const { localUsers, globalUsers } = result;\n\n let localUserIds;\n let globalUserIds;\n if (localUsers.length) {\n global = addUsers(global, buildCollectionByKey(localUsers, 'id'));\n localUserIds = localUsers.map(({ id }) => id);\n }\n if (globalUsers.length) {\n global = addUsers(global, buildCollectionByKey(globalUsers, 'id'));\n globalUserIds = globalUsers.map(({ id }) => id);\n }\n\n global = updateUserSearchFetchingStatus(global, false);\n global = updateUserSearch(global, { localUserIds, globalUserIds });\n\n setGlobal(global);\n}\n","import { GlobalState } from '../../global/types';\nimport { InlineBotSettings } from '../../types';\n\nexport function replaceInlineBotSettings(\n global: GlobalState, username: string, inlineBotSettings: InlineBotSettings | false,\n): GlobalState {\n return {\n ...global,\n inlineBots: {\n ...global.inlineBots,\n byUsername: {\n ...global.inlineBots.byUsername,\n [username]: inlineBotSettings,\n },\n },\n };\n}\n\nexport function replaceInlineBotsIsLoading(global: GlobalState, isLoading: boolean): GlobalState {\n return {\n ...global,\n inlineBots: {\n ...global.inlineBots,\n isLoading,\n },\n };\n}\n","import {\n addReducer, getDispatch, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { ApiChat, ApiContact, ApiUser } from '../../../api/types';\nimport { InlineBotSettings } from '../../../types';\n\nimport {\n RE_TG_LINK, RE_TME_LINK,\n} from '../../../config';\nimport { callApi } from '../../../api/gramjs';\nimport {\n selectChat, selectChatBot, selectChatMessage, selectCurrentChat, selectCurrentMessageList,\n selectReplyingToId, selectSendAs, selectUser,\n} from '../../selectors';\nimport { addChats, addUsers, removeBlockedContact } from '../../reducers';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport { debounce } from '../../../util/schedulers';\nimport { replaceInlineBotSettings, replaceInlineBotsIsLoading } from '../../reducers/bots';\nimport { getServerTime } from '../../../util/serverTime';\n\nconst TOP_PEERS_REQUEST_COOLDOWN = 60; // 1 min\nconst runDebouncedForSearch = debounce((cb) => cb(), 500, false);\n\naddReducer('clickInlineButton', (global, actions, payload) => {\n const { button } = payload;\n\n switch (button.type) {\n case 'command':\n actions.sendBotCommand({ command: button.value });\n break;\n case 'url':\n if (button.value.match(RE_TME_LINK) || button.value.match(RE_TG_LINK)) {\n actions.openTelegramLink({ url: button.value });\n } else {\n actions.toggleSafeLinkModal({ url: button.value });\n }\n break;\n case 'callback': {\n const chat = selectCurrentChat(global);\n if (!chat) {\n return;\n }\n\n void answerCallbackButton(chat, button.messageId, button.value);\n break;\n }\n case 'requestPoll':\n actions.openPollModal();\n break;\n case 'requestSelfContact': {\n const user = global.currentUserId ? selectUser(global, global.currentUserId) : undefined;\n if (!user) {\n return;\n }\n actions.showDialog({\n data: {\n phoneNumber: user.phoneNumber,\n firstName: user.firstName,\n lastName: user.lastName,\n userId: user.id,\n } as ApiContact,\n });\n break;\n }\n case 'buy': {\n const chat = selectCurrentChat(global);\n const { messageId, value } = button;\n if (!chat) {\n return;\n }\n\n if (value) {\n actions.getReceipt({ receiptMessageId: value, chatId: chat.id, messageId });\n } else {\n actions.getPaymentForm({ chat, messageId });\n actions.setInvoiceMessageInfo(selectChatMessage(global, chat.id, messageId));\n actions.openPaymentModal({ chatId: chat.id, messageId });\n }\n break;\n }\n }\n});\n\naddReducer('sendBotCommand', (global, actions, payload) => {\n const { command, chatId } = payload;\n const { currentUserId } = global;\n const chat = chatId ? selectChat(global, chatId) : selectCurrentChat(global);\n const currentMessageList = selectCurrentMessageList(global);\n\n if (!currentUserId || !chat || !currentMessageList) {\n return;\n }\n\n const { threadId } = currentMessageList;\n actions.setReplyingToId({ messageId: undefined });\n actions.clearWebPagePreview({ chatId: chat.id, threadId, value: false });\n\n void sendBotCommand(\n chat, currentUserId, command, selectReplyingToId(global, chat.id, threadId), selectSendAs(global, chatId),\n );\n});\n\naddReducer('restartBot', (global, actions, payload) => {\n const { chatId } = payload;\n const { currentUserId } = global;\n const chat = selectCurrentChat(global);\n const bot = currentUserId && selectChatBot(global, chatId);\n if (!currentUserId || !chat || !bot) {\n return;\n }\n\n (async () => {\n const result = await callApi('unblockContact', bot.id, bot.accessHash);\n if (!result) {\n return;\n }\n\n setGlobal(removeBlockedContact(getGlobal(), bot.id));\n void sendBotCommand(chat, currentUserId, '/start', undefined, selectSendAs(global, chatId));\n })();\n});\n\naddReducer('loadTopInlineBots', (global) => {\n const { lastRequestedAt } = global.topInlineBots;\n\n if (lastRequestedAt && getServerTime(global.serverTimeOffset) - lastRequestedAt < TOP_PEERS_REQUEST_COOLDOWN) {\n return;\n }\n\n (async () => {\n const result = await callApi('fetchTopInlineBots');\n if (!result) {\n return;\n }\n\n const { ids, users } = result;\n\n let newGlobal = getGlobal();\n newGlobal = addUsers(newGlobal, buildCollectionByKey(users, 'id'));\n newGlobal = {\n ...newGlobal,\n topInlineBots: {\n ...newGlobal.topInlineBots,\n userIds: ids,\n lastRequestedAt: getServerTime(global.serverTimeOffset),\n },\n };\n setGlobal(newGlobal);\n })();\n});\n\naddReducer('queryInlineBot', ((global, actions, payload) => {\n const {\n chatId, username, query, offset,\n } = payload;\n\n (async () => {\n let inlineBotData = global.inlineBots.byUsername[username];\n\n if (inlineBotData === false) {\n return;\n }\n\n if (inlineBotData === undefined) {\n const { user: inlineBot, chat } = await callApi('fetchInlineBot', { username }) || {};\n global = getGlobal();\n if (!inlineBot || !chat) {\n setGlobal(replaceInlineBotSettings(global, username, false));\n return;\n }\n\n global = addUsers(global, { [inlineBot.id]: inlineBot });\n global = addChats(global, { [chat.id]: chat });\n inlineBotData = {\n id: inlineBot.id,\n query: '',\n offset: '',\n switchPm: undefined,\n canLoadMore: true,\n results: [],\n };\n\n global = replaceInlineBotSettings(global, username, inlineBotData);\n setGlobal(global);\n }\n\n if (query === inlineBotData.query && !inlineBotData.canLoadMore) {\n return;\n }\n\n void runDebouncedForSearch(() => {\n searchInlineBot({\n username,\n inlineBotData: inlineBotData as InlineBotSettings,\n chatId,\n query,\n offset,\n });\n });\n })();\n}));\n\naddReducer('sendInlineBotResult', (global, actions, payload) => {\n const { id, queryId } = payload;\n const currentMessageList = selectCurrentMessageList(global);\n\n if (!currentMessageList || !id) {\n return;\n }\n\n const { chatId, threadId } = currentMessageList;\n\n const chat = selectChat(global, chatId)!;\n\n actions.setReplyingToId({ messageId: undefined });\n actions.clearWebPagePreview({ chatId, threadId, value: false });\n\n void callApi('sendInlineBotResult', {\n chat,\n resultId: id,\n queryId,\n replyingTo: selectReplyingToId(global, chatId, threadId),\n sendAs: selectSendAs(global, chatId),\n });\n});\n\naddReducer('resetInlineBot', (global, actions, payload) => {\n const { username } = payload;\n\n let inlineBotData = global.inlineBots.byUsername[username];\n\n if (!inlineBotData) {\n return;\n }\n\n inlineBotData = {\n id: inlineBotData.id,\n query: '',\n offset: '',\n switchPm: undefined,\n canLoadMore: true,\n results: [],\n };\n\n setGlobal(replaceInlineBotSettings(global, username, inlineBotData));\n});\n\naddReducer('startBot', (global, actions, payload) => {\n const { botId, param } = payload;\n\n const bot = selectUser(global, botId);\n if (!bot) {\n return;\n }\n\n (async () => {\n await callApi('startBot', {\n bot,\n startParam: param,\n });\n })();\n});\n\nasync function searchInlineBot({\n username,\n inlineBotData,\n chatId,\n query,\n offset,\n}: {\n username: string;\n inlineBotData: InlineBotSettings;\n chatId: string;\n query: string;\n offset?: string;\n}) {\n let global = getGlobal();\n const bot = selectUser(global, inlineBotData.id);\n const chat = selectChat(global, chatId);\n if (!bot || !chat) {\n return;\n }\n\n const shouldReplaceSettings = inlineBotData.query !== query;\n global = replaceInlineBotsIsLoading(global, true);\n global = replaceInlineBotSettings(global, username, {\n ...inlineBotData,\n query,\n ...(shouldReplaceSettings && { offset: undefined, results: [] }),\n });\n setGlobal(global);\n\n const result = await callApi('fetchInlineBotResults', {\n bot,\n chat,\n query,\n offset: shouldReplaceSettings ? undefined : offset,\n });\n\n const newInlineBotData = global.inlineBots.byUsername[username];\n global = replaceInlineBotsIsLoading(getGlobal(), false);\n if (!result || !newInlineBotData || query !== newInlineBotData.query) {\n setGlobal(global);\n return;\n }\n\n const currentIds = new Set((newInlineBotData.results || []).map((data) => data.id));\n const newResults = result.results.filter((data) => !currentIds.has(data.id));\n\n global = replaceInlineBotSettings(global, username, {\n ...newInlineBotData,\n help: result.help,\n ...(newResults.length && { isGallery: result.isGallery }),\n ...(result.switchPm && { switchPm: result.switchPm }),\n canLoadMore: result.results.length > 0 && Boolean(result.nextOffset),\n results: newInlineBotData.offset === '' || newInlineBotData.offset === result.nextOffset\n ? result.results\n : (newInlineBotData.results || []).concat(newResults),\n offset: newResults.length ? result.nextOffset : '',\n });\n\n setGlobal(global);\n}\n\nasync function sendBotCommand(\n chat: ApiChat, currentUserId: string, command: string, replyingTo?: number, sendAs?: ApiChat | ApiUser,\n) {\n await callApi('sendMessage', {\n chat,\n text: command,\n replyingTo,\n sendAs,\n });\n}\n\nasync function answerCallbackButton(chat: ApiChat, messageId: number, data: string) {\n const result = await callApi('answerCallbackButton', {\n chatId: chat.id,\n accessHash: chat.accessHash,\n messageId,\n data,\n });\n\n if (!result) {\n return;\n }\n\n const { showDialog, showNotification, toggleSafeLinkModal } = getDispatch();\n const { message, alert: isError, url } = result;\n\n if (isError) {\n showDialog({ data: { message: message || 'Error' } });\n } else if (message) {\n showNotification({ message });\n } else if (url) {\n toggleSafeLinkModal({ url });\n }\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { callApi } from '../../../api/gramjs';\nimport { replaceSettings, updateTwoFaSettings } from '../../reducers';\n\naddReducer('loadPasswordInfo', () => {\n (async () => {\n const result = await callApi('getPasswordInfo');\n if (!result) {\n return;\n }\n\n let global = getGlobal();\n global = replaceSettings(global, { hasPassword: result.hasPassword });\n global = updateTwoFaSettings(global, { hint: result.hint });\n setGlobal(global);\n })();\n});\n\naddReducer('checkPassword', (global, actions, payload) => {\n const { currentPassword, onSuccess } = payload;\n\n setGlobal(updateTwoFaSettings(global, { isLoading: true, error: undefined }));\n\n (async () => {\n const isSuccess = await callApi('checkPassword', currentPassword);\n\n setGlobal(updateTwoFaSettings(getGlobal(), { isLoading: false }));\n\n if (isSuccess) {\n onSuccess();\n }\n })();\n});\n\naddReducer('clearPassword', (global, actions, payload) => {\n const { currentPassword, onSuccess } = payload;\n\n setGlobal(updateTwoFaSettings(global, { isLoading: true, error: undefined }));\n\n (async () => {\n const isSuccess = await callApi('clearPassword', currentPassword);\n\n setGlobal(updateTwoFaSettings(getGlobal(), { isLoading: false }));\n\n if (isSuccess) {\n onSuccess();\n }\n })();\n});\n\naddReducer('updatePassword', (global, actions, payload) => {\n const {\n currentPassword, password, hint, email, onSuccess,\n } = payload;\n\n setGlobal(updateTwoFaSettings(global, { isLoading: true, error: undefined }));\n\n (async () => {\n const isSuccess = await callApi('updatePassword', currentPassword, password, hint, email);\n\n setGlobal(updateTwoFaSettings(getGlobal(), { isLoading: false }));\n\n if (isSuccess) {\n onSuccess();\n }\n })();\n});\n\naddReducer('updateRecoveryEmail', (global, actions, payload) => {\n const {\n currentPassword, email, onSuccess,\n } = payload;\n\n setGlobal(updateTwoFaSettings(global, { isLoading: true, error: undefined }));\n\n (async () => {\n const isSuccess = await callApi('updateRecoveryEmail', currentPassword, email);\n\n setGlobal(updateTwoFaSettings(getGlobal(), { isLoading: false, waitingEmailCodeLength: undefined }));\n\n if (isSuccess) {\n onSuccess();\n }\n })();\n});\n\naddReducer('provideTwoFaEmailCode', (global, actions, payload) => {\n const { code } = payload;\n\n void callApi('provideRecoveryEmailCode', code);\n});\n\naddReducer('clearTwoFaError', (global) => {\n return updateTwoFaSettings(global, { error: undefined });\n});\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { PaymentStep } from '../../../types';\nimport { ApiChat } from '../../../api/types';\n\nimport {\n selectPaymentMessageId,\n selectPaymentRequestId,\n selectProviderPublishableKey,\n selectStripeCredentials,\n selectChatMessage,\n selectPaymentChatId,\n selectChat,\n selectPaymentFormId,\n} from '../../selectors';\nimport { callApi } from '../../../api/gramjs';\nimport { getStripeError } from '../../helpers';\nimport { buildQueryString } from '../../../util/requestQuery';\n\nimport {\n updateShippingOptions,\n setPaymentStep,\n setRequestInfoId,\n setPaymentForm,\n setStripeCardInfo,\n setInvoiceMessageInfo,\n setReceipt,\n clearPayment,\n closeInvoice,\n} from '../../reducers';\n\naddReducer('validateRequestedInfo', (global, actions, payload) => {\n const { requestInfo, saveInfo } = payload;\n const chatId = selectPaymentChatId(global);\n const chat = chatId && selectChat(global, chatId);\n const messageId = selectPaymentMessageId(global);\n if (!chat || !messageId) {\n return;\n }\n void validateRequestedInfo(chat, messageId, requestInfo, saveInfo);\n});\n\nasync function validateRequestedInfo(chat: ApiChat, messageId: number, requestInfo: any, shouldSave?: true) {\n const result = await callApi('validateRequestedInfo', {\n chat, messageId, requestInfo, shouldSave,\n });\n if (!result) {\n return;\n }\n\n const { id, shippingOptions } = result;\n if (!id) {\n return;\n }\n\n let global = setRequestInfoId(getGlobal(), id);\n if (shippingOptions) {\n global = updateShippingOptions(global, shippingOptions);\n global = setPaymentStep(global, PaymentStep.Shipping);\n } else {\n global = setPaymentStep(global, PaymentStep.PaymentInfo);\n }\n setGlobal(global);\n}\n\naddReducer('getPaymentForm', (global, actions, payload) => {\n const { chat, messageId } = payload;\n if (!chat || !messageId) {\n return;\n }\n void getPaymentForm(chat, messageId);\n});\n\nasync function getPaymentForm(chat: ApiChat, messageId: number) {\n const result = await callApi('getPaymentForm', { chat, messageId });\n if (!result) {\n return;\n }\n let global = setPaymentForm(getGlobal(), result);\n let step = PaymentStep.PaymentInfo;\n if (global.payment.invoice\n && (global.payment.invoice.shippingAddressRequested\n || global.payment.invoice.nameRequested\n || global.payment.invoice.phoneRequested\n || global.payment.invoice.emailRequested)) {\n step = PaymentStep.ShippingInfo;\n }\n global = setPaymentStep(global, step);\n setGlobal(global);\n}\n\naddReducer('getReceipt', (global, actions, payload) => {\n const { receiptMessageId, chatId, messageId } = payload;\n const chat = chatId && selectChat(global, chatId);\n if (!messageId || !receiptMessageId || !chat) {\n return;\n }\n\n void getReceipt(chat, messageId, receiptMessageId);\n});\n\nasync function getReceipt(chat: ApiChat, messageId: number, receiptMessageId: number) {\n const result = await callApi('getReceipt', chat, receiptMessageId);\n if (!result) {\n return;\n }\n\n let global = getGlobal();\n const message = selectChatMessage(global, chat.id, messageId);\n global = setReceipt(global, result, message);\n setGlobal(global);\n}\n\naddReducer('clearPaymentError', (global) => {\n setGlobal({\n ...global,\n payment: {\n ...global.payment,\n error: undefined,\n },\n });\n});\n\naddReducer('clearReceipt', (global) => {\n setGlobal({\n ...global,\n payment: {\n ...global.payment,\n receipt: undefined,\n },\n });\n});\n\naddReducer('sendCredentialsInfo', (global, actions, payload) => {\n const publishableKey = selectProviderPublishableKey(global);\n if (!publishableKey) {\n return;\n }\n const { credentials } = payload;\n const { data } = credentials;\n void sendStripeCredentials(data, publishableKey);\n});\n\naddReducer('sendPaymentForm', (global, actions, payload) => {\n const { shippingOptionId, saveCredentials } = payload;\n const chatId = selectPaymentChatId(global);\n const chat = chatId && selectChat(global, chatId);\n const messageId = selectPaymentMessageId(global);\n const formId = selectPaymentFormId(global);\n const requestInfoId = selectPaymentRequestId(global);\n const publishableKey = selectProviderPublishableKey(global);\n const stripeCredentials = selectStripeCredentials(global);\n if (!chat || !messageId || !publishableKey || !formId) {\n return;\n }\n\n void sendPaymentForm(chat, messageId, formId, {\n save: saveCredentials,\n data: stripeCredentials,\n }, requestInfoId, shippingOptionId);\n});\n\nasync function sendStripeCredentials(\n data: {\n cardNumber: string;\n cardholder?: string;\n expiryMonth: string;\n expiryYear: string;\n cvv: string;\n country: string;\n zip: string;\n },\n publishableKey: string,\n) {\n const query = buildQueryString({\n 'card[number]': data.cardNumber,\n 'card[exp_month]': data.expiryMonth,\n 'card[exp_year]': data.expiryYear,\n 'card[cvc]': data.cvv,\n 'card[address_zip]': data.zip,\n 'card[address_country]': data.country,\n });\n\n const response = await fetch(`https://api.stripe.com/v1/tokens${query}`, {\n method: 'POST',\n credentials: 'same-origin',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n Authorization: `Bearer ${publishableKey}`,\n },\n });\n const result = await response.json();\n if (result.error) {\n const error = getStripeError(result.error);\n const global = getGlobal();\n setGlobal({\n ...global,\n payment: {\n ...global.payment,\n error: {\n ...error,\n },\n },\n });\n return;\n }\n let global = setStripeCardInfo(getGlobal(), {\n type: result.type,\n id: result.id,\n });\n global = setPaymentStep(global, PaymentStep.Checkout);\n setGlobal(global);\n}\n\nasync function sendPaymentForm(\n chat: ApiChat,\n messageId: number,\n formId: string,\n credentials: any,\n requestedInfoId?: string,\n shippingOptionId?: string,\n) {\n const result = await callApi('sendPaymentForm', {\n chat, messageId, formId, credentials, requestedInfoId, shippingOptionId,\n });\n if (result) {\n const global = clearPayment(getGlobal());\n setGlobal(closeInvoice(global));\n }\n}\n\naddReducer('setPaymentStep', (global, actions, payload = {}) => {\n return setPaymentStep(global, payload.step || PaymentStep.ShippingInfo);\n});\n\naddReducer('setInvoiceMessageInfo', (global, actions, payload) => {\n return setInvoiceMessageInfo(global, payload);\n});\n","export function buildQueryString(data: Record) {\n const query = Object.keys(data).map((k) => `${k}=${data[k]}`).join('&');\n return query.length > 0 ? `?${query}` : '';\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiUpdate, MAIN_THREAD_ID } from '../../../api/types';\n\nimport { ARCHIVED_FOLDER_ID, MAX_ACTIVE_PINNED_CHATS } from '../../../config';\nimport { pick } from '../../../util/iteratees';\nimport { closeMessageNotifications, notifyAboutNewMessage } from '../../../util/notifications';\nimport { updateAppBadge } from '../../../util/appBadge';\nimport {\n updateChat,\n updateChatListIds,\n updateChatListType,\n replaceThreadParam,\n leaveChat,\n} from '../../reducers';\nimport {\n selectChat,\n selectCommonBoxChatId,\n selectIsChatListed,\n selectChatListType,\n selectCurrentMessageList,\n selectCountNotMutedUnread,\n} from '../../selectors';\nimport { throttle } from '../../../util/schedulers';\n\nconst TYPING_STATUS_CLEAR_DELAY = 6000; // 6 seconds\n// Enough to animate and mark as read in Message List\nconst CURRENT_CHAT_UNREAD_DELAY = 1500;\n\nconst runThrottledForUpdateAppBadge = throttle((cb) => cb(), 500, true);\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n switch (update['@type']) {\n case 'updateChat': {\n if (!update.noTopChatsRequest && !selectIsChatListed(global, update.id)) {\n // Chat can appear in dialogs list.\n actions.loadTopChats();\n }\n\n const newGlobal = updateChat(global, update.id, update.chat, update.newProfilePhoto);\n setGlobal(newGlobal);\n\n runThrottledForUpdateAppBadge(() => updateAppBadge(selectCountNotMutedUnread(getGlobal())));\n\n if (update.chat.id) {\n closeMessageNotifications({\n chatId: update.chat.id,\n lastReadInboxMessageId: update.chat.lastReadInboxMessageId,\n });\n }\n break;\n }\n\n case 'updateChatJoin': {\n const listType = selectChatListType(global, update.id);\n if (!listType) {\n break;\n }\n\n global = updateChatListIds(global, listType, [update.id]);\n global = updateChat(global, update.id, { isNotJoined: false });\n setGlobal(global);\n\n const chat = selectChat(global, update.id);\n if (chat) {\n actions.requestChatUpdate({ chatId: chat.id });\n }\n break;\n }\n\n case 'updateChatLeave': {\n setGlobal(leaveChat(global, update.id));\n\n break;\n }\n\n case 'updateChatInbox': {\n setGlobal(updateChat(global, update.id, update.chat));\n\n runThrottledForUpdateAppBadge(() => updateAppBadge(selectCountNotMutedUnread(getGlobal())));\n\n break;\n }\n\n case 'updateChatTypingStatus': {\n const { id, typingStatus } = update;\n setGlobal(updateChat(global, id, { typingStatus }));\n\n setTimeout(() => {\n const newGlobal = getGlobal();\n const chat = selectChat(newGlobal, id);\n if (chat && typingStatus && chat.typingStatus && chat.typingStatus.timestamp === typingStatus.timestamp) {\n setGlobal(updateChat(newGlobal, id, { typingStatus: undefined }));\n }\n }, TYPING_STATUS_CLEAR_DELAY);\n\n break;\n }\n\n case 'newMessage': {\n const { message } = update;\n const { chatId: currentChatId, threadId, type: messageListType } = selectCurrentMessageList(global) || {};\n\n if (message.senderId === global.currentUserId && !message.isFromScheduled) {\n return;\n }\n\n const chat = selectChat(global, update.chatId);\n if (!chat) {\n return;\n }\n\n const isActiveChat = (\n messageListType === 'thread'\n && threadId === MAIN_THREAD_ID\n && update.chatId === currentChatId\n );\n\n if (isActiveChat) {\n setTimeout(() => {\n actions.requestChatUpdate({ chatId: update.chatId });\n }, CURRENT_CHAT_UNREAD_DELAY);\n } else {\n setGlobal(updateChat(global, update.chatId, {\n unreadCount: chat.unreadCount ? chat.unreadCount + 1 : 1,\n ...(update.message.hasUnreadMention && {\n unreadMentionsCount: chat.unreadMentionsCount ? chat.unreadMentionsCount + 1 : 1,\n }),\n }));\n }\n\n updateAppBadge(selectCountNotMutedUnread(getGlobal()));\n notifyAboutNewMessage({\n chat,\n message,\n });\n\n break;\n }\n\n case 'updateCommonBoxMessages':\n case 'updateChannelMessages': {\n const { ids, messageUpdate } = update;\n if (messageUpdate.hasUnreadMention !== false) {\n return;\n }\n\n ids.forEach((id) => {\n const chatId = ('channelId' in update ? update.channelId : selectCommonBoxChatId(global, id))!;\n const chat = selectChat(global, chatId);\n if (chat?.unreadMentionsCount) {\n global = updateChat(global, chatId, {\n unreadMentionsCount: chat.unreadMentionsCount - 1,\n });\n }\n });\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateChatFullInfo': {\n const { fullInfo } = update;\n const targetChat = global.chats.byId[update.id];\n if (!targetChat) {\n return;\n }\n\n setGlobal(updateChat(global, update.id, {\n fullInfo: {\n ...targetChat.fullInfo,\n ...fullInfo,\n },\n }));\n\n break;\n }\n\n case 'updatePinnedChatIds': {\n const { ids, folderId } = update;\n\n const listType = folderId === ARCHIVED_FOLDER_ID ? 'archived' : 'active';\n\n global = {\n ...global,\n chats: {\n ...global.chats,\n orderedPinnedIds: {\n ...global.chats.orderedPinnedIds,\n [listType]: ids.length ? ids : undefined,\n },\n },\n };\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateChatPinned': {\n const { id, isPinned } = update;\n const listType = selectChatListType(global, id);\n if (listType) {\n const { [listType]: orderedPinnedIds } = global.chats.orderedPinnedIds;\n\n let newOrderedPinnedIds = orderedPinnedIds || [];\n if (!isPinned) {\n newOrderedPinnedIds = newOrderedPinnedIds.filter((pinnedId) => pinnedId !== id);\n } else if (!newOrderedPinnedIds.includes(id)) {\n // When moving pinned chats to archive, active ordered pinned ids don't get updated\n // (to preserve chat pinned state when it returns from archive)\n // If user already has max pinned chats, we should check for orderedIds\n // that don't point to listed chats\n if (listType === 'active' && newOrderedPinnedIds.length >= MAX_ACTIVE_PINNED_CHATS) {\n const listIds = global.chats.listIds.active;\n newOrderedPinnedIds = newOrderedPinnedIds.filter((pinnedId) => listIds && listIds.includes(pinnedId));\n }\n\n newOrderedPinnedIds = [id, ...newOrderedPinnedIds];\n }\n\n global = {\n ...global,\n chats: {\n ...global.chats,\n orderedPinnedIds: {\n ...global.chats.orderedPinnedIds,\n [listType]: newOrderedPinnedIds.length ? newOrderedPinnedIds : undefined,\n },\n },\n };\n }\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateChatListType': {\n const { id, folderId } = update;\n\n setGlobal(updateChatListType(global, id, folderId));\n\n break;\n }\n\n case 'updateChatFolder': {\n const { id, folder } = update;\n const { byId: chatFoldersById, orderedIds } = global.chatFolders;\n\n const newChatFoldersById = folder\n ? { ...chatFoldersById, [id]: folder }\n : pick(\n chatFoldersById,\n Object.keys(chatFoldersById).map(Number).filter((folderId) => folderId !== id),\n );\n\n const newOrderedIds = folder\n ? orderedIds && orderedIds.includes(id) ? orderedIds : [...(orderedIds || []), id]\n : orderedIds ? orderedIds.filter((orderedId) => orderedId !== id) : undefined;\n\n setGlobal({\n ...global,\n chatFolders: {\n ...global.chatFolders,\n byId: newChatFoldersById,\n orderedIds: newOrderedIds,\n },\n });\n\n break;\n }\n\n case 'updateChatFoldersOrder': {\n const { orderedIds } = update;\n\n setGlobal({\n ...global,\n chatFolders: {\n ...global.chatFolders,\n orderedIds,\n },\n });\n\n break;\n }\n\n case 'updateRecommendedChatFolders': {\n const { folders } = update;\n\n setGlobal({\n ...global,\n chatFolders: {\n ...global.chatFolders,\n recommended: folders,\n },\n });\n\n break;\n }\n\n case 'updateChatMembers': {\n const targetChat = global.chats.byId[update.id];\n const { replacedMembers, addedMember, deletedMemberId } = update;\n if (!targetChat) {\n return;\n }\n\n let shouldUpdate = false;\n let members = targetChat.fullInfo?.members\n ? [...targetChat.fullInfo.members]\n : [];\n\n if (replacedMembers) {\n members = replacedMembers;\n shouldUpdate = true;\n } else if (addedMember) {\n if (\n !members.length\n || !members.some((m) => m.userId === addedMember.userId)\n ) {\n members.push(addedMember);\n shouldUpdate = true;\n }\n } else if (members.length && deletedMemberId) {\n const deleteIndex = members.findIndex((m) => m.userId === deletedMemberId);\n if (deleteIndex > -1) {\n members.slice(deleteIndex, 1);\n shouldUpdate = true;\n }\n }\n\n if (shouldUpdate) {\n const adminMembers = members.filter(({ isOwner, isAdmin }) => isOwner || isAdmin);\n // TODO Kicked members?\n\n setGlobal(updateChat(global, update.id, {\n membersCount: members.length,\n fullInfo: {\n ...targetChat.fullInfo,\n members,\n adminMembers,\n },\n }));\n }\n\n break;\n }\n\n case 'deleteProfilePhotos': {\n const { chatId, ids } = update;\n const chat = global.chats.byId[chatId];\n\n if (chat?.photos) {\n setGlobal(updateChat(global, chatId, {\n photos: chat.photos.filter((photo) => !ids.includes(photo.id)),\n }));\n }\n break;\n }\n\n case 'draftMessage': {\n const {\n chatId, formattedText, date, replyingToId,\n } = update;\n const chat = global.chats.byId[chatId];\n\n if (chat) {\n global = replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'draft', formattedText);\n global = replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'replyingToId', replyingToId);\n global = updateChat(global, chatId, { draftDate: date });\n\n setGlobal(global);\n }\n break;\n }\n\n case 'showInvite': {\n const { data } = update;\n\n actions.showDialog({ data });\n break;\n }\n }\n});\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport {\n ApiUpdate, ApiMessage, ApiPollResult, ApiThreadInfo, MAIN_THREAD_ID,\n} from '../../../api/types';\n\nimport { unique } from '../../../util/iteratees';\nimport {\n updateChat,\n deleteChatMessages,\n updateChatMessage,\n updateListedIds,\n addViewportId,\n updateThreadInfo,\n replaceThreadParam,\n updateScheduledMessage,\n deleteChatScheduledMessages,\n updateThreadUnreadFromForwardedMessage,\n} from '../../reducers';\nimport { GlobalActions, GlobalState } from '../../../global/types';\nimport {\n selectChatMessage,\n selectChatMessages,\n selectIsViewportNewest,\n selectListedIds,\n selectChatMessageByPollId,\n selectCommonBoxChatId,\n selectIsChatListed,\n selectThreadInfo,\n selectThreadByMessage,\n selectPinnedIds,\n selectScheduledMessage,\n selectScheduledMessages,\n isMessageInCurrentMessageList,\n selectScheduledIds,\n selectCurrentMessageList,\n selectViewportIds,\n selectFirstUnreadId,\n selectChat,\n selectIsChatWithBot,\n selectIsServiceChatReady,\n} from '../../selectors';\nimport { getMessageContent, isUserId, isMessageLocal } from '../../helpers';\n\nconst ANIMATION_DELAY = 350;\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n switch (update['@type']) {\n case 'newMessage': {\n const {\n chatId, id, message, shouldForceReply,\n } = update;\n global = updateWithLocalMedia(global, chatId, id, message);\n global = updateListedAndViewportIds(global, actions, message as ApiMessage);\n\n if (message.threadInfo) {\n global = updateThreadInfo(\n global,\n message.threadInfo.chatId,\n message.threadInfo.threadId,\n message.threadInfo,\n );\n }\n\n setGlobal(global);\n\n const newMessage = selectChatMessage(global, chatId, id)!;\n\n if (isMessageInCurrentMessageList(global, chatId, message as ApiMessage)) {\n if (message.isOutgoing && !(message.content?.action)) {\n const currentMessageList = selectCurrentMessageList(global);\n if (currentMessageList) {\n // We do not use `actions.focusLastMessage` as it may be set with a delay (see below)\n actions.focusMessage({\n chatId,\n threadId: currentMessageList.threadId,\n messageId: message.id,\n noHighlight: true,\n isResizingContainer: true,\n });\n }\n }\n\n const { threadInfo } = selectThreadByMessage(global, chatId, message as ApiMessage) || {};\n if (threadInfo) {\n actions.requestThreadInfoUpdate({ chatId, threadId: threadInfo.threadId });\n }\n\n // @perf Wait until scroll animation finishes or simply rely on delivery status update (which is itself delayed)\n if (!isMessageLocal(message as ApiMessage)) {\n setTimeout(() => {\n let delayedGlobal = getGlobal();\n if (shouldForceReply) {\n delayedGlobal = replaceThreadParam(delayedGlobal, chatId, MAIN_THREAD_ID, 'replyingToId', id);\n }\n setGlobal(updateChatLastMessage(delayedGlobal, chatId, newMessage));\n }, ANIMATION_DELAY);\n }\n } else {\n setGlobal(updateChatLastMessage(getGlobal(), chatId, newMessage));\n }\n\n // Edge case: New message in an old (not loaded) chat.\n if (!selectIsChatListed(global, chatId)) {\n actions.loadTopChats();\n }\n\n break;\n }\n\n case 'newScheduledMessage': {\n const { chatId, id, message } = update;\n\n global = updateWithLocalMedia(global, chatId, id, message, true);\n\n const scheduledIds = selectScheduledIds(global, chatId) || [];\n global = replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'scheduledIds', unique([...scheduledIds, id]));\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateMessage': {\n const { chatId, id, message } = update;\n\n const currentMessage = selectChatMessage(global, chatId, id);\n if (!currentMessage) {\n return;\n }\n\n global = updateWithLocalMedia(global, chatId, id, message);\n\n const newMessage = selectChatMessage(global, chatId, id)!;\n if (message.threadInfo) {\n global = updateThreadInfo(\n global,\n message.threadInfo.chatId,\n message.threadInfo.threadId,\n message.threadInfo,\n );\n }\n global = updateChatLastMessage(global, chatId, newMessage);\n\n setGlobal(global);\n\n // Scroll down if bot message height is changed with an updated inline keyboard.\n // A drawback: this will scroll down even if the previous scroll was not at bottom.\n const chat = selectChat(global, chatId);\n if (\n chat\n && !message.isOutgoing\n && chat.lastMessage?.id === message.id\n && selectIsChatWithBot(global, chat)\n && isMessageInCurrentMessageList(global, chatId, message as ApiMessage)\n && selectIsViewportNewest(global, chatId, message.threadInfo?.threadId || MAIN_THREAD_ID)\n ) {\n actions.focusLastMessage();\n }\n\n break;\n }\n\n case 'updateScheduledMessage': {\n const { chatId, id, message } = update;\n\n const currentMessage = selectScheduledMessage(global, chatId, id);\n if (!currentMessage) {\n return;\n }\n\n global = updateWithLocalMedia(global, chatId, id, message, true);\n const ids = Object.keys(selectScheduledMessages(global, chatId) || {}).map(Number).sort((a, b) => b - a);\n global = replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'scheduledIds', ids);\n setGlobal(global);\n\n break;\n }\n\n case 'updateMessageSendSucceeded': {\n const { chatId, localId, message } = update;\n\n global = updateListedAndViewportIds(global, actions, message as ApiMessage);\n\n const currentMessage = selectChatMessage(global, chatId, localId);\n\n global = deleteChatMessages(global, chatId, [localId]);\n\n // Edge case for \"Send When Online\"\n if (message.isScheduled) {\n global = deleteChatScheduledMessages(global, chatId, [localId]);\n }\n\n global = updateChatMessage(global, chatId, message.id, {\n ...currentMessage,\n ...message,\n previousLocalId: localId,\n });\n\n const newMessage = selectChatMessage(global, chatId, message.id)!;\n global = updateChatLastMessage(global, chatId, newMessage);\n\n const thread = selectThreadByMessage(global, chatId, message);\n // For some reason Telegram requires to manually mark outgoing thread messages read\n if (thread?.threadInfo) {\n actions.markMessageListRead({ maxId: message.id });\n\n global = replaceThreadParam(global, chatId, thread.threadInfo.threadId, 'threadInfo', {\n ...thread.threadInfo,\n lastMessageId: message.id,\n lastReadInboxMessageId: message.id,\n });\n }\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateScheduledMessageSendSucceeded': {\n const { chatId, localId, message } = update;\n const scheduledIds = selectScheduledIds(global, chatId) || [];\n global = replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'scheduledIds', [...scheduledIds, message.id]);\n\n const currentMessage = selectScheduledMessage(global, chatId, localId);\n\n global = deleteChatScheduledMessages(global, chatId, [localId]);\n global = updateScheduledMessage(global, chatId, message.id, {\n ...currentMessage,\n ...message,\n previousLocalId: localId,\n });\n\n setGlobal(global);\n break;\n }\n\n case 'updatePinnedIds': {\n const { chatId, isPinned, messageIds } = update;\n\n const currentPinnedIds = selectPinnedIds(global, chatId) || [];\n const newPinnedIds = isPinned\n ? [...currentPinnedIds, ...messageIds].sort((a, b) => b - a)\n : currentPinnedIds.filter((id) => !messageIds.includes(id));\n\n setGlobal(replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'pinnedIds', newPinnedIds));\n\n break;\n }\n\n case 'updateThreadInfo': {\n const {\n chatId, threadId, threadInfo, firstMessageId,\n } = update;\n\n const currentThreadInfo = selectThreadInfo(global, chatId, threadId);\n const newTheadInfo = {\n ...currentThreadInfo,\n ...threadInfo,\n };\n\n if (!newTheadInfo.threadId) {\n return;\n }\n\n global = updateThreadInfo(global, chatId, threadId, newTheadInfo as ApiThreadInfo);\n\n if (firstMessageId) {\n global = replaceThreadParam(global, chatId, threadId, 'firstMessageId', firstMessageId);\n }\n\n setGlobal(global);\n\n break;\n }\n\n case 'resetMessages': {\n const { id: chatId } = update;\n const messagesById = selectChatMessages(global, chatId);\n\n if (messagesById && !isUserId(chatId)) {\n global = deleteChatMessages(global, chatId, Object.keys(messagesById).map(Number));\n setGlobal(global);\n actions.loadFullChat({ chatId, force: true });\n }\n\n break;\n }\n\n case 'deleteMessages': {\n const { ids, chatId } = update;\n\n deleteMessages(chatId, ids, actions, global);\n break;\n }\n\n case 'deleteScheduledMessages': {\n const { ids, chatId } = update;\n\n deleteScheduledMessages(chatId, ids, actions, global);\n break;\n }\n\n case 'deleteHistory': {\n const { chatId } = update;\n const chatMessages = global.messages.byChatId[chatId];\n if (chatMessages) {\n const ids = Object.keys(chatMessages.byId).map(Number);\n deleteMessages(chatId, ids, actions, global);\n } else {\n actions.requestChatUpdate({ chatId });\n }\n\n break;\n }\n\n case 'updateCommonBoxMessages': {\n const { ids, messageUpdate } = update;\n\n ids.forEach((id) => {\n const chatId = selectCommonBoxChatId(global, id);\n if (chatId) {\n global = updateChatMessage(global, chatId, id, messageUpdate);\n }\n });\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateChannelMessages': {\n const { channelId, ids, messageUpdate } = update;\n\n ids.forEach((id) => {\n global = updateChatMessage(global, channelId, id, messageUpdate);\n });\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateMessagePoll': {\n const { pollId, pollUpdate } = update;\n\n const message = selectChatMessageByPollId(global, pollId);\n\n if (message?.content.poll) {\n const updatedPoll = { ...message.content.poll, ...pollUpdate };\n\n // Workaround for poll update bug: `chosen` option gets reset when someone votes after current user\n const { results: updatedResults } = updatedPoll.results || {};\n if (updatedResults && !updatedResults.some(((result) => result.isChosen))) {\n const { results } = message.content.poll.results;\n const chosenAnswers = results && results.filter((result) => result.isChosen);\n if (chosenAnswers) {\n chosenAnswers.forEach((chosenAnswer) => {\n const chosenAnswerIndex = updatedResults.findIndex((result) => result.option === chosenAnswer.option);\n if (chosenAnswerIndex >= 0) {\n updatedPoll.results.results![chosenAnswerIndex].isChosen = true;\n }\n });\n }\n }\n\n setGlobal(updateChatMessage(\n global,\n message.chatId,\n message.id,\n {\n content: {\n ...message.content,\n poll: updatedPoll,\n },\n },\n ));\n }\n break;\n }\n\n case 'updateMessagePollVote': {\n const { pollId, userId, options } = update;\n const message = selectChatMessageByPollId(global, pollId);\n if (!message || !message.content.poll || !message.content.poll.results) {\n break;\n }\n\n const { poll } = message.content;\n\n const { recentVoterIds, totalVoters, results } = poll.results;\n const newRecentVoterIds = recentVoterIds ? [...recentVoterIds] : [];\n const newTotalVoters = totalVoters ? totalVoters + 1 : 1;\n const newResults = results ? [...results] : [];\n\n newRecentVoterIds.push(userId);\n\n options.forEach((option) => {\n const targetOption = newResults.find((result) => result.option === option);\n const targetOptionIndex = newResults.findIndex((result) => result.option === option);\n const updatedOption: ApiPollResult = targetOption ? { ...targetOption } : { option, votersCount: 0 };\n\n updatedOption.votersCount += 1;\n if (userId === global.currentUserId) {\n updatedOption.isChosen = true;\n }\n\n if (targetOptionIndex) {\n newResults[targetOptionIndex] = updatedOption;\n } else {\n newResults.push(updatedOption);\n }\n });\n\n setGlobal(updateChatMessage(\n global,\n message.chatId,\n message.id,\n {\n content: {\n ...message.content,\n poll: {\n ...poll,\n results: {\n ...poll.results,\n recentVoterIds: newRecentVoterIds,\n totalVoters: newTotalVoters,\n results: newResults,\n },\n },\n },\n },\n ));\n\n break;\n }\n\n case 'updateServiceNotification': {\n const { message } = update;\n\n if (selectIsServiceChatReady(global)) {\n actions.createServiceNotification({ message });\n }\n\n break;\n }\n }\n});\n\nfunction updateWithLocalMedia(\n global: GlobalState, chatId: string, id: number, message: Partial, isScheduled = false,\n) {\n // Preserve locally uploaded media.\n const currentMessage = isScheduled\n ? selectScheduledMessage(global, chatId, id)\n : selectChatMessage(global, chatId, id);\n if (currentMessage && message.content) {\n const {\n photo, video, sticker, document,\n } = getMessageContent(currentMessage);\n if (photo && message.content.photo) {\n message.content.photo.blobUrl = photo.blobUrl;\n message.content.photo.thumbnail = photo.thumbnail;\n } else if (video && message.content.video) {\n message.content.video.blobUrl = video.blobUrl;\n } else if (sticker && message.content.sticker) {\n message.content.sticker.isPreloadedGlobally = sticker.isPreloadedGlobally;\n } else if (document && message.content.document) {\n message.content.document.previewBlobUrl = document.previewBlobUrl;\n }\n }\n\n return isScheduled\n ? updateScheduledMessage(global, chatId, id, message)\n : updateChatMessage(global, chatId, id, message);\n}\n\nfunction updateThreadUnread(global: GlobalState, actions: GlobalActions, message: ApiMessage, isDeleting?: boolean) {\n const { chatId } = message;\n\n const { threadInfo } = selectThreadByMessage(global, chatId, message) || {};\n\n if (!threadInfo && message.replyToMessageId) {\n const originMessage = selectChatMessage(global, chatId, message.replyToMessageId);\n if (originMessage) {\n global = updateThreadUnreadFromForwardedMessage(global, originMessage, chatId, message.id, isDeleting);\n } else {\n actions.loadMessage({\n chatId,\n messageId: message.replyToMessageId,\n threadUpdate: {\n isDeleting,\n lastMessageId: message.id,\n },\n });\n }\n }\n\n return global;\n}\n\nfunction updateListedAndViewportIds(global: GlobalState, actions: GlobalActions, message: ApiMessage) {\n const { id, chatId } = message;\n\n const { threadInfo, firstMessageId } = selectThreadByMessage(global, chatId, message) || {};\n\n const chat = selectChat(global, chatId);\n const isUnreadChatNotLoaded = chat?.unreadCount && !selectListedIds(global, chatId, MAIN_THREAD_ID);\n\n global = updateThreadUnread(global, actions, message);\n\n if (threadInfo) {\n if (firstMessageId || !isMessageLocal(message)) {\n global = updateListedIds(global, chatId, threadInfo.threadId, [id]);\n\n if (selectIsViewportNewest(global, chatId, threadInfo.threadId)) {\n global = addViewportId(global, chatId, threadInfo.threadId, id);\n\n if (!firstMessageId) {\n global = replaceThreadParam(global, chatId, threadInfo.threadId, 'firstMessageId', message.id);\n }\n }\n }\n\n global = replaceThreadParam(global, chatId, threadInfo.threadId, 'threadInfo', {\n ...threadInfo,\n lastMessageId: message.id,\n messagesCount: threadInfo.messagesCount + 1,\n });\n }\n\n if (isUnreadChatNotLoaded) {\n return global;\n }\n\n global = updateListedIds(global, chatId, MAIN_THREAD_ID, [id]);\n\n if (selectIsViewportNewest(global, chatId, MAIN_THREAD_ID)) {\n // Always keep the first unread message in the viewport list\n const firstUnreadId = selectFirstUnreadId(global, chatId, MAIN_THREAD_ID);\n const newGlobal = addViewportId(global, chatId, MAIN_THREAD_ID, id);\n const newViewportIds = selectViewportIds(newGlobal, chatId, MAIN_THREAD_ID);\n\n if (!firstUnreadId || newViewportIds!.includes(firstUnreadId)) {\n global = newGlobal;\n }\n }\n\n return global;\n}\n\nfunction updateChatLastMessage(\n global: GlobalState,\n chatId: string,\n message: ApiMessage,\n force = false,\n) {\n const { chats } = global;\n const currentLastMessage = chats.byId[chatId]?.lastMessage;\n\n if (currentLastMessage && !force) {\n const isSameOrNewer = (\n currentLastMessage.id === message.id || currentLastMessage.id === message.previousLocalId\n ) || message.id > currentLastMessage.id;\n\n if (!isSameOrNewer) {\n return global;\n }\n }\n\n return updateChat(global, chatId, { lastMessage: message });\n}\n\nfunction findLastMessage(global: GlobalState, chatId: string) {\n const byId = selectChatMessages(global, chatId);\n const listedIds = selectListedIds(global, chatId, MAIN_THREAD_ID);\n\n if (!byId || !listedIds) {\n return undefined;\n }\n\n let i = listedIds.length;\n while (i--) {\n const message = byId[listedIds[i]];\n if (!message.isDeleting) {\n return message;\n }\n }\n\n return undefined;\n}\n\nfunction deleteMessages(chatId: string | undefined, ids: number[], actions: GlobalActions, global: GlobalState) {\n // Channel update\n\n if (chatId) {\n ids.forEach((id) => {\n global = updateChatMessage(global, chatId, id, {\n isDeleting: true,\n });\n\n const newLastMessage = findLastMessage(global, chatId);\n if (newLastMessage) {\n global = updateChatLastMessage(global, chatId, newLastMessage, true);\n }\n });\n\n setGlobal(global);\n\n actions.requestChatUpdate({ chatId });\n\n const threadIdsToUpdate: number[] = [];\n\n ids.forEach((id) => {\n const message = selectChatMessage(global, chatId, id);\n if (!message) {\n return;\n }\n\n global = updateThreadUnread(global, actions, message, true);\n\n const { threadInfo } = selectThreadByMessage(global, chatId, message) || {};\n if (threadInfo) {\n threadIdsToUpdate.push(threadInfo.threadId);\n }\n });\n\n setGlobal(global);\n\n setTimeout(() => {\n setGlobal(deleteChatMessages(getGlobal(), chatId, ids));\n\n unique(threadIdsToUpdate).forEach((threadId) => {\n actions.requestThreadInfoUpdate({ chatId, threadId });\n });\n }, ANIMATION_DELAY);\n\n return;\n }\n\n // Common box update\n\n const chatsIdsToUpdate: string[] = [];\n\n ids.forEach((id) => {\n const commonBoxChatId = selectCommonBoxChatId(global, id);\n if (commonBoxChatId) {\n chatsIdsToUpdate.push(commonBoxChatId);\n\n global = updateChatMessage(global, commonBoxChatId, id, {\n isDeleting: true,\n });\n\n const newLastMessage = findLastMessage(global, commonBoxChatId);\n if (newLastMessage) {\n global = updateChatLastMessage(global, commonBoxChatId, newLastMessage, true);\n }\n\n setTimeout(() => {\n setGlobal(deleteChatMessages(getGlobal(), commonBoxChatId, [id]));\n }, ANIMATION_DELAY);\n }\n });\n\n setGlobal(global);\n\n unique(chatsIdsToUpdate).forEach((id) => {\n actions.requestChatUpdate({ chatId: id });\n });\n}\n\nfunction deleteScheduledMessages(\n chatId: string | undefined, ids: number[], actions: GlobalActions, global: GlobalState,\n) {\n if (!chatId) {\n return;\n }\n\n ids.forEach((id) => {\n global = updateScheduledMessage(global, chatId, id, {\n isDeleting: true,\n });\n });\n\n setGlobal(global);\n\n setTimeout(() => {\n global = deleteChatScheduledMessages(getGlobal(), chatId, ids);\n const scheduledMessages = selectScheduledMessages(global, chatId);\n global = replaceThreadParam(\n global, chatId, MAIN_THREAD_ID, 'scheduledIds', Object.keys(scheduledMessages || {}).map(Number),\n );\n setGlobal(global);\n }, ANIMATION_DELAY);\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiUpdate, ApiUserStatus } from '../../../api/types';\n\nimport { deleteContact, replaceUserStatuses, updateUser } from '../../reducers';\nimport { throttle } from '../../../util/schedulers';\n\nconst STATUS_UPDATE_THROTTLE = 3000;\n\nconst flushStatusUpdatesThrottled = throttle(flushStatusUpdates, STATUS_UPDATE_THROTTLE, true);\n\nlet pendingStatusUpdates: Record = {};\n\nfunction scheduleStatusUpdate(userId: string, statusUpdate: ApiUserStatus) {\n pendingStatusUpdates[userId] = statusUpdate;\n flushStatusUpdatesThrottled();\n}\n\nfunction flushStatusUpdates() {\n const global = getGlobal();\n\n setGlobal(replaceUserStatuses(global, {\n ...global.users.statusesById,\n ...pendingStatusUpdates,\n }));\n\n pendingStatusUpdates = {};\n}\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n switch (update['@type']) {\n case 'deleteContact': {\n return deleteContact(global, update.id);\n }\n\n case 'updateUser': {\n return updateUser(global, update.id, update.user);\n }\n\n case 'updateUserStatus': {\n // Status updates come very often so we throttle them\n scheduleStatusUpdate(update.userId, update.status);\n return undefined;\n }\n\n case 'updateUserFullInfo': {\n const { id, fullInfo } = update;\n const targetUser = global.users.byId[id];\n if (!targetUser) {\n return undefined;\n }\n\n return updateUser(global, id, {\n fullInfo: {\n ...targetUser.fullInfo,\n ...fullInfo,\n },\n });\n }\n }\n\n return undefined;\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { ApiUpdate } from '../../../api/types';\n\nimport { updateStickerSet } from '../../reducers';\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n switch (update['@type']) {\n case 'updateStickerSet': {\n return updateStickerSet(global, update.id, update.stickerSet);\n }\n }\n\n return undefined;\n});\n","import {\n addReducer, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { ApiUpdate } from '../../../api/types';\nimport { ApiPrivacyKey } from '../../../types';\n\nimport { addBlockedContact, removeBlockedContact } from '../../reducers';\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n switch (update['@type']) {\n case 'updatePeerBlocked':\n if (update.isBlocked) {\n return addBlockedContact(getGlobal(), update.id);\n } else {\n return removeBlockedContact(getGlobal(), update.id);\n }\n\n case 'updateResetContactList':\n setGlobal({\n ...getGlobal(),\n contactList: {\n userIds: [],\n },\n });\n break;\n\n case 'updateFavoriteStickers':\n actions.loadFavoriteStickers();\n break;\n\n case 'updatePrivacy':\n global.settings.privacy[update.key as ApiPrivacyKey] = update.rules;\n break;\n }\n\n return undefined;\n});\n","import { addReducer, setGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiUpdate } from '../../../api/types';\nimport { GlobalState } from '../../../global/types';\nimport { addNotifyException, updateChat, updateNotifySettings } from '../../reducers';\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate): GlobalState | undefined => {\n switch (update['@type']) {\n case 'updateNotifySettings': {\n return updateNotifySettings(global, update.peerType, update.isSilent, update.shouldShowPreviews);\n }\n\n case 'updateNotifyExceptions': {\n const {\n chatId, isMuted, isSilent, shouldShowPreviews,\n } = update;\n const chat = global.chats.byId[chatId];\n\n if (chat) {\n global = updateChat(global, chatId, { isMuted });\n }\n\n setGlobal(addNotifyException(global, chatId, { isMuted, isSilent, shouldShowPreviews }));\n break;\n }\n }\n\n return undefined;\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { ApiUpdate } from '../../../api/types';\nimport { GlobalState } from '../../../global/types';\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate): GlobalState | undefined => {\n switch (update['@type']) {\n case 'updateTwoFaStateWaitCode': {\n return {\n ...global,\n twoFaSettings: {\n ...global.twoFaSettings,\n isLoading: false,\n waitingEmailCodeLength: update.length,\n },\n };\n }\n\n case 'updateTwoFaError': {\n return {\n ...global,\n twoFaSettings: {\n ...global.twoFaSettings,\n error: update.message,\n },\n };\n }\n }\n\n return undefined;\n});\n","import { addReducer, getGlobal } from '../../../lib/teact/teactn';\nimport { ApiUpdate } from '../../../api/types';\nimport { removeGroupCall, updateGroupCall, updateGroupCallParticipant } from '../../reducers/calls';\nimport { omit } from '../../../util/iteratees';\nimport { selectChat } from '../../selectors';\nimport { updateChat } from '../../reducers';\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n switch (update['@type']) {\n case 'updateGroupCall': {\n if (update.call.connectionState === 'discarded') {\n if (global.groupCalls.activeGroupCallId) {\n actions.leaveGroupCall({ shouldRemove: true });\n return undefined;\n } else {\n return removeGroupCall(global, update.call.id);\n }\n }\n\n return updateGroupCall(global,\n update.call.id,\n omit(update.call, ['connectionState']),\n undefined,\n update.call.participantsCount);\n }\n case 'updateGroupCallChatId': {\n const chat = selectChat(global, update.chatId);\n if (chat) {\n global = updateChat(global, update.chatId, {\n fullInfo: {\n ...chat.fullInfo,\n groupCallId: update.call.id,\n },\n });\n }\n return global;\n }\n case 'updateGroupCallParticipants': {\n const { groupCallId, participants, nextOffset } = update;\n const { currentUserId } = global;\n\n // `secret-sauce` should disconnect if the participant is us but from another device\n global = getGlobal();\n participants.forEach((participant) => {\n if (participant.id) {\n global = updateGroupCallParticipant(global, groupCallId, participant.id, participant,\n !!nextOffset || currentUserId === participant.id);\n }\n });\n if (nextOffset) {\n global = updateGroupCall(global, groupCallId, {\n nextOffset,\n });\n }\n return global;\n }\n }\n\n return undefined;\n});\n","import { useEffect } from '../lib/teact/teact';\n\nimport { onBeforeUnload } from '../util/schedulers';\n\nexport default function useBeforeUnload(callback: AnyToVoidFunction) {\n useEffect(() => {\n return onBeforeUnload(callback);\n }, [callback]);\n}\n","import { useEffect } from '../lib/teact/teact';\nimport { IS_IOS, IS_PWA, IS_TOUCH_ENV } from '../util/environment';\n\nconst metaViewport = document.querySelector('meta[name=\"viewport\"]');\nconst defaultViewportContent = metaViewport?.getAttribute('content') || '';\nconst allowedZoomViewportContent = 'width=device-width, initial-scale=1, shrink-to-fit=no, viewport-fit=cover';\n\nexport default function usePreventPinchZoomGesture(isDisabled = false) {\n useEffect(() => {\n if (!IS_TOUCH_ENV) {\n return undefined;\n }\n\n if (isDisabled) {\n // Clean viewport content from values values that disable the ability to zoom a webpage\n // https://web.dev/meta-viewport/\n metaViewport?.setAttribute('content', allowedZoomViewportContent);\n return undefined;\n }\n\n metaViewport?.setAttribute('content', defaultViewportContent);\n\n // Since iOS 10 `user-scaleable=no` is disabled in Safari for iOS,\n // this is only applicable for the browser and does not apply to the PWA mode.\n // https://newbedev.com/how-do-you-disable-viewport-zooming-on-mobile-safari\n if (IS_IOS && !IS_PWA) {\n document.addEventListener('gesturestart', preventEvent);\n }\n\n return () => {\n metaViewport?.setAttribute('content', 'width=device-width, initial-scale=1, shrink-to-fit=no');\n if (IS_IOS && !IS_PWA) {\n document.removeEventListener('gesturestart', preventEvent);\n }\n };\n }, [isDisabled]);\n}\n\nfunction preventEvent(e: Event) {\n e.preventDefault();\n}\n","import { useEffect, useState } from '../lib/teact/teact';\n\nexport default function useBrowserOnline() {\n const [isOnline, setIsOnline] = useState(window.navigator.onLine);\n\n useEffect(() => {\n function handleChange() {\n setIsOnline(window.navigator.onLine);\n }\n\n window.addEventListener('online', handleChange);\n window.addEventListener('offline', handleChange);\n\n return () => {\n window.removeEventListener('offline', handleChange);\n window.removeEventListener('online', handleChange);\n };\n }, []);\n\n return isOnline;\n}\n","import React, {\n FC, useCallback, useMemo, memo,\n} from '../../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../../lib/teact/teactn';\n\nimport { LeftColumnContent, ISettings } from '../../../types';\nimport { ApiChat } from '../../../api/types';\n\nimport {\n ANIMATION_LEVEL_MAX, APP_NAME, APP_VERSION, FEEDBACK_URL,\n} from '../../../config';\nimport { IS_SINGLE_COLUMN_LAYOUT } from '../../../util/environment';\nimport buildClassName from '../../../util/buildClassName';\nimport { formatDateToString } from '../../../util/dateFormat';\nimport switchTheme from '../../../util/switchTheme';\nimport { setPermanentWebVersion } from '../../../util/permanentWebVersion';\nimport { selectTheme } from '../../../modules/selectors';\nimport { isChatArchived } from '../../../modules/helpers';\nimport useLang from '../../../hooks/useLang';\nimport { disableHistoryBack } from '../../../hooks/useHistoryBack';\n\nimport DropdownMenu from '../../ui/DropdownMenu';\nimport MenuItem from '../../ui/MenuItem';\nimport Button from '../../ui/Button';\nimport SearchInput from '../../ui/SearchInput';\nimport PickerSelectedItem from '../../common/PickerSelectedItem';\nimport Switcher from '../../ui/Switcher';\n\nimport './LeftMainHeader.scss';\n\ntype OwnProps = {\n content: LeftColumnContent;\n contactsFilter: string;\n shouldSkipTransition?: boolean;\n onSearchQuery: (query: string) => void;\n onSelectSettings: () => void;\n onSelectContacts: () => void;\n onSelectArchived: () => void;\n onReset: () => void;\n};\n\ntype StateProps = {\n searchQuery?: string;\n isLoading: boolean;\n currentUserId?: string;\n globalSearchChatId?: string;\n searchDate?: number;\n theme: ISettings['theme'];\n animationLevel: 0 | 1 | 2;\n chatsById?: Record;\n};\n\nconst ANIMATION_LEVEL_OPTIONS = [0, 1, 2];\n\nconst PRODUCTION_HOSTNAME = 'web.telegram.org';\nconst LEGACY_VERSION_URL = 'https://web.telegram.org/?legacy=1';\nconst WEBK_VERSION_URL = 'https://web.telegram.org/k/';\n\nconst LeftMainHeader: FC = ({\n content,\n contactsFilter,\n onSearchQuery,\n onSelectSettings,\n onSelectContacts,\n onSelectArchived,\n onReset,\n searchQuery,\n isLoading,\n shouldSkipTransition,\n currentUserId,\n globalSearchChatId,\n searchDate,\n theme,\n animationLevel,\n chatsById,\n}) => {\n const {\n openChat,\n openTipsChat,\n setGlobalSearchDate,\n setSettingOption, setGlobalSearchChatId,\n } = getDispatch();\n\n const lang = useLang();\n const hasMenu = content === LeftColumnContent.ChatList;\n const clearedDateSearchParam = { date: undefined };\n const clearedChatSearchParam = { id: undefined };\n const selectedSearchDate = useMemo(() => {\n return searchDate\n ? formatDateToString(new Date(searchDate * 1000))\n : undefined;\n }, [searchDate]);\n const archivedUnreadChatsCount = useMemo(() => {\n if (!hasMenu || !chatsById) {\n return 0;\n }\n\n return Object.values(chatsById).reduce((total, chat) => {\n if (!isChatArchived(chat)) {\n return total;\n }\n\n return chat.unreadCount ? total + 1 : total;\n }, 0);\n }, [hasMenu, chatsById]);\n\n const withOtherVersions = window.location.hostname === PRODUCTION_HOSTNAME;\n\n const MainButton: FC<{ onTrigger: () => void; isOpen?: boolean }> = useMemo(() => {\n return ({ onTrigger, isOpen }) => (\n onReset()}\n ariaLabel={hasMenu ? lang('AccDescrOpenMenu2') : 'Return to chat list'}\n >\n
\n \n );\n }, [hasMenu, lang, onReset, shouldSkipTransition]);\n\n const handleSearchFocus = useCallback(() => {\n if (!searchQuery) {\n onSearchQuery('');\n }\n }, [searchQuery, onSearchQuery]);\n\n const handleSelectSaved = useCallback(() => {\n openChat({ id: currentUserId, shouldReplaceHistory: true });\n }, [currentUserId, openChat]);\n\n const handleDarkModeToggle = useCallback((e: React.SyntheticEvent) => {\n e.stopPropagation();\n const newTheme = theme === 'light' ? 'dark' : 'light';\n\n setSettingOption({ theme: newTheme });\n setSettingOption({ shouldUseSystemTheme: false });\n switchTheme(newTheme, animationLevel === ANIMATION_LEVEL_MAX);\n }, [animationLevel, setSettingOption, theme]);\n\n const handleAnimationLevelChange = useCallback((e: React.SyntheticEvent) => {\n e.stopPropagation();\n\n const newLevel = animationLevel === 0 ? 2 : 0;\n ANIMATION_LEVEL_OPTIONS.forEach((_, i) => {\n document.body.classList.toggle(`animation-level-${i}`, newLevel === i);\n });\n\n setSettingOption({ animationLevel: newLevel });\n }, [animationLevel, setSettingOption]);\n\n const handleSwitchToWebK = () => {\n setPermanentWebVersion('K');\n disableHistoryBack();\n };\n\n const handleOpenTipsChat = () => {\n openTipsChat({ langCode: lang.code });\n };\n\n const isSearchFocused = (\n Boolean(globalSearchChatId)\n || content === LeftColumnContent.GlobalSearch\n || content === LeftColumnContent.Contacts\n );\n\n const searchInputPlaceholder = content === LeftColumnContent.Contacts\n ? lang('SearchFriends')\n : lang('Search');\n\n return (\n
\n
\n \n \n {lang('SavedMessages')}\n \n \n {lang('ArchivedChats')}\n {archivedUnreadChatsCount > 0 && (\n
{archivedUnreadChatsCount}
\n )}\n \n \n {lang('Contacts')}\n \n \n {lang('Settings')}\n \n \n {lang('lng_menu_night_mode')}\n \n \n \n {lang('Appearance.Animations').toLowerCase()}\n 0}\n />\n \n \n {lang('TelegramFeatures')}\n \n \n Report Bug\n \n {withOtherVersions && (\n <>\n \n Switch to K Version\n \n \n Switch to Old Version\n \n \n )}\n \n \n {selectedSearchDate && (\n \n )}\n {globalSearchChatId && (\n \n )}\n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n query: searchQuery, fetchingStatus, chatId, date,\n } = global.globalSearch;\n const { currentUserId } = global;\n const { byId: chatsById } = global.chats;\n const { animationLevel } = global.settings.byKey;\n\n return {\n searchQuery,\n isLoading: fetchingStatus ? Boolean(fetchingStatus.chats || fetchingStatus.messages) : false,\n currentUserId,\n chatsById,\n globalSearchChatId: chatId,\n searchDate: date,\n theme: selectTheme(global),\n animationLevel,\n };\n },\n)(LeftMainHeader));\n","import React, { memo, FC } from '../../lib/teact/teact';\n\nimport { GlobalState } from '../../global/types';\n\nimport useLang from '../../hooks/useLang';\n\nimport Spinner from '../ui/Spinner';\n\nimport './ConnectionState.scss';\n\ntype StateProps = Pick;\n\nconst ConnectionState: FC = () => {\n const lang = useLang();\n\n return (\n
\n \n
{lang('WaitingForNetwork')}
\n
\n );\n};\n\nexport default memo(ConnectionState);\n","import React, {\n FC, memo, useCallback, useEffect, useMemo, useRef,\n} from '../../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiChat, ApiChatFolder, ApiUser } from '../../../api/types';\nimport { GlobalState } from '../../../global/types';\nimport { NotifyException, NotifySettings, SettingsScreens } from '../../../types';\nimport { FolderEditDispatch } from '../../../hooks/reducers/useFoldersReducer';\n\nimport { IS_TOUCH_ENV } from '../../../util/environment';\nimport { ALL_FOLDER_ID } from '../../../config';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport { captureEvents, SwipeDirection } from '../../../util/captureEvents';\nimport { getFolderUnreadDialogs } from '../../../modules/helpers';\nimport { selectNotifyExceptions, selectNotifySettings } from '../../../modules/selectors';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport buildClassName from '../../../util/buildClassName';\nimport useThrottledMemo from '../../../hooks/useThrottledMemo';\nimport useLang from '../../../hooks/useLang';\nimport useHistoryBack from '../../../hooks/useHistoryBack';\nimport captureEscKeyListener from '../../../util/captureEscKeyListener';\n\nimport Transition from '../../ui/Transition';\nimport TabList from '../../ui/TabList';\nimport ChatList from './ChatList';\n\ntype OwnProps = {\n onScreenSelect: (screen: SettingsScreens) => void;\n foldersDispatch: FolderEditDispatch;\n};\n\ntype StateProps = {\n allListIds: GlobalState['chats']['listIds'];\n chatsById: Record;\n usersById: Record;\n chatFoldersById: Record;\n notifySettings: NotifySettings;\n notifyExceptions?: Record;\n orderedFolderIds?: number[];\n activeChatFolder: number;\n currentUserId?: string;\n lastSyncTime?: number;\n shouldSkipHistoryAnimations?: boolean;\n};\n\nconst INFO_THROTTLE = 3000;\nconst SAVED_MESSAGES_HOTKEY = '0';\n\nconst ChatFolders: FC = ({\n allListIds,\n chatsById,\n usersById,\n chatFoldersById,\n notifySettings,\n notifyExceptions,\n orderedFolderIds,\n activeChatFolder,\n currentUserId,\n lastSyncTime,\n shouldSkipHistoryAnimations,\n foldersDispatch,\n onScreenSelect,\n}) => {\n const {\n loadChatFolders,\n setActiveChatFolder,\n openChat,\n } = getDispatch();\n\n // eslint-disable-next-line no-null/no-null\n const transitionRef = useRef(null);\n\n const lang = useLang();\n\n useEffect(() => {\n if (lastSyncTime) {\n loadChatFolders();\n }\n }, [lastSyncTime, loadChatFolders]);\n\n const displayedFolders = useMemo(() => {\n return orderedFolderIds\n ? orderedFolderIds.map((id) => chatFoldersById[id] || {}).filter(Boolean)\n : undefined;\n }, [chatFoldersById, orderedFolderIds]);\n\n const folderCountersById = useThrottledMemo(() => {\n if (!displayedFolders || !displayedFolders.length) {\n return undefined;\n }\n\n const counters = displayedFolders.map((folder) => {\n const {\n unreadDialogsCount, hasActiveDialogs,\n } = getFolderUnreadDialogs(allListIds, chatsById, usersById, folder, notifySettings, notifyExceptions) || {};\n\n return {\n id: folder.id,\n badgeCount: unreadDialogsCount,\n isBadgeActive: hasActiveDialogs,\n };\n });\n\n return buildCollectionByKey(counters, 'id');\n }, INFO_THROTTLE, [displayedFolders, allListIds, chatsById, usersById, notifySettings, notifyExceptions]);\n\n const folderTabs = useMemo(() => {\n if (!displayedFolders || !displayedFolders.length) {\n return undefined;\n }\n\n return [\n { title: lang.code === 'en' ? 'All' : lang('FilterAllChats'), id: ALL_FOLDER_ID },\n ...displayedFolders.map((folder) => ({\n title: folder.title,\n ...(folderCountersById?.[folder.id]),\n })),\n ];\n }, [displayedFolders, folderCountersById, lang]);\n\n const handleSwitchTab = useCallback((index: number) => {\n setActiveChatFolder(index, { forceOnHeavyAnimation: true });\n }, [setActiveChatFolder]);\n\n // Prevent `activeTab` pointing at non-existing folder after update\n useEffect(() => {\n if (!folderTabs || !folderTabs.length) {\n return;\n }\n\n if (activeChatFolder >= folderTabs.length) {\n setActiveChatFolder(0);\n }\n }, [activeChatFolder, folderTabs, setActiveChatFolder]);\n\n useEffect(() => {\n if (!transitionRef.current || !IS_TOUCH_ENV || !folderTabs || !folderTabs.length) {\n return undefined;\n }\n\n return captureEvents(transitionRef.current, {\n selectorToPreventScroll: '.chat-list',\n onSwipe: ((e, direction) => {\n if (direction === SwipeDirection.Left) {\n setActiveChatFolder(Math.min(activeChatFolder + 1, folderTabs.length - 1), { forceOnHeavyAnimation: true });\n return true;\n } else if (direction === SwipeDirection.Right) {\n setActiveChatFolder(Math.max(0, activeChatFolder - 1), { forceOnHeavyAnimation: true });\n return true;\n }\n\n return false;\n }),\n });\n }, [activeChatFolder, folderTabs, setActiveChatFolder]);\n\n const isNotInAllTabRef = useRef();\n isNotInAllTabRef.current = activeChatFolder !== 0;\n useEffect(() => (isNotInAllTabRef.current ? captureEscKeyListener(() => {\n if (isNotInAllTabRef.current) {\n setActiveChatFolder(0);\n }\n }) : undefined), [activeChatFolder, setActiveChatFolder]);\n\n useHistoryBack(activeChatFolder !== 0, () => setActiveChatFolder(0, { forceOnHeavyAnimation: true }));\n\n useEffect(() => {\n const handleKeyDown = (e: KeyboardEvent) => {\n if (e.ctrlKey && e.shiftKey && e.code.startsWith('Digit') && folderTabs) {\n const [, digit] = e.code.match(/Digit(\\d)/) || [];\n if (!digit) return;\n\n if (digit === SAVED_MESSAGES_HOTKEY) {\n openChat({ id: currentUserId, shouldReplaceHistory: true });\n return;\n }\n\n const folder = Number(digit) - 1;\n if (folder > folderTabs.length - 1) return;\n\n setActiveChatFolder(folder, { forceOnHeavyAnimation: true });\n e.preventDefault();\n }\n };\n\n document.addEventListener('keydown', handleKeyDown, true);\n\n return () => {\n document.removeEventListener('keydown', handleKeyDown, true);\n };\n });\n\n const {\n shouldRender: shouldRenderPlaceholder, transitionClassNames,\n } = useShowTransition(!orderedFolderIds, undefined, true);\n\n function renderCurrentTab(isActive: boolean) {\n const activeFolder = Object.values(chatFoldersById)\n .find(({ id }) => id === folderTabs![activeChatFolder].id);\n\n if (!activeFolder || activeChatFolder === 0) {\n return (\n \n );\n }\n\n return (\n \n );\n }\n\n return (\n
\n {folderTabs?.length ? (\n \n ) : shouldRenderPlaceholder ? (\n
\n ) : undefined}\n \n {renderCurrentTab}\n \n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n chats: { listIds: allListIds, byId: chatsById },\n users: { byId: usersById },\n chatFolders: {\n byId: chatFoldersById,\n orderedIds: orderedFolderIds,\n activeChatFolder,\n },\n currentUserId,\n lastSyncTime,\n shouldSkipHistoryAnimations,\n } = global;\n\n return {\n allListIds,\n chatsById,\n usersById,\n chatFoldersById,\n orderedFolderIds,\n lastSyncTime,\n notifySettings: selectNotifySettings(global),\n notifyExceptions: selectNotifyExceptions(global),\n activeChatFolder,\n currentUserId,\n shouldSkipHistoryAnimations,\n };\n },\n)(ChatFolders));\n","import { useState } from '../lib/teact/teact';\n\nimport useThrottle from './useThrottle';\nimport useOnChange from './useOnChange';\nimport useHeavyAnimationCheck from './useHeavyAnimationCheck';\nimport useFlag from './useFlag';\n\nexport default (resolverFn: () => R, ms: number, dependencies: D) => {\n const runThrottled = useThrottle(ms, true);\n const [value, setValue] = useState();\n const [isFrozen, freeze, unfreeze] = useFlag();\n\n useHeavyAnimationCheck(freeze, unfreeze);\n\n useOnChange(() => {\n if (isFrozen) {\n return;\n }\n\n runThrottled(() => {\n setValue(resolverFn());\n });\n }, dependencies.concat([isFrozen]));\n\n return value;\n};\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { Bundles } from '../../../util/moduleLoader';\nimport { OwnProps } from './LeftSearch';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\nimport Loading from '../../ui/Loading';\n\nconst LeftSearchAsync: FC = (props) => {\n const LeftSearch = useModuleLoader(Bundles.Extra, 'LeftSearch');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return LeftSearch ? : ;\n};\n\nexport default memo(LeftSearchAsync);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { Bundles } from '../../../util/moduleLoader';\nimport { OwnProps } from './ContactList';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\nimport Loading from '../../ui/Loading';\n\nconst ContactListAsync: FC = (props) => {\n const ContactList = useModuleLoader(Bundles.Extra, 'ContactList');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return ContactList ? : ;\n};\n\nexport default memo(ContactListAsync);\n","import React, {\n FC, useCallback, useState, useEffect, memo,\n} from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\nimport Button from '../ui/Button';\nimport Menu from '../ui/Menu';\nimport MenuItem from '../ui/MenuItem';\n\nimport './NewChatButton.scss';\n\nconst MENU_CLOSE_DELAY_MS = 750;\nlet closeTimeout: number | undefined;\n\ntype OwnProps = {\n isShown: boolean;\n onNewPrivateChat: () => void;\n onNewChannel: () => void;\n onNewGroup: () => void;\n};\n\nconst NewChatButton: FC = ({\n isShown,\n onNewPrivateChat,\n onNewChannel,\n onNewGroup,\n}) => {\n const [isMenuOpen, setIsMenuOpen] = useState(false);\n\n useEffect(() => {\n if (!isShown) {\n setIsMenuOpen(false);\n }\n }, [isShown]);\n\n const lang = useLang();\n\n const fabClassName = buildClassName(\n 'NewChatButton',\n isShown && 'revealed',\n isMenuOpen && 'menu-is-open',\n );\n\n const toggleIsMenuOpen = () => {\n setIsMenuOpen(!isMenuOpen);\n };\n\n const handleClose = () => {\n setIsMenuOpen(false);\n };\n\n const handleMouseEnter = useCallback(() => {\n if (closeTimeout) {\n clearTimeout(closeTimeout);\n closeTimeout = undefined;\n }\n }, []);\n\n const handleMouseLeave = useCallback(() => {\n if (closeTimeout) {\n clearTimeout(closeTimeout);\n closeTimeout = undefined;\n }\n\n closeTimeout = window.setTimeout(() => {\n setIsMenuOpen(false);\n }, MENU_CLOSE_DELAY_MS);\n }, []);\n\n return (\n \n \n \n \n \n \n {lang('NewChannel')}\n {lang('NewGroup')}\n {lang('NewMessageTitle')}\n \n
\n );\n};\n\nexport default memo(NewChatButton);\n","import React, {\n FC, useState, useRef, useCallback, useEffect,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\nimport { LeftColumnContent, SettingsScreens } from '../../../types';\nimport { FolderEditDispatch } from '../../../hooks/reducers/useFoldersReducer';\n\nimport { IS_TOUCH_ENV } from '../../../util/environment';\nimport { pick } from '../../../util/iteratees';\nimport buildClassName from '../../../util/buildClassName';\nimport useBrowserOnline from '../../../hooks/useBrowserOnline';\nimport useFlag from '../../../hooks/useFlag';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useLang from '../../../hooks/useLang';\n\nimport Transition from '../../ui/Transition';\nimport LeftMainHeader from './LeftMainHeader';\nimport ConnectionState from '../ConnectionState';\nimport ChatFolders from './ChatFolders';\nimport LeftSearch from '../search/LeftSearch.async';\nimport ContactList from './ContactList.async';\nimport NewChatButton from '../NewChatButton';\nimport ShowTransition from '../../ui/ShowTransition';\nimport Button from '../../ui/Button';\n\nimport './LeftMain.scss';\n\ntype OwnProps = {\n content: LeftColumnContent;\n searchQuery?: string;\n searchDate?: number;\n contactsFilter: string;\n shouldSkipTransition?: boolean;\n foldersDispatch: FolderEditDispatch;\n onSearchQuery: (query: string) => void;\n onContentChange: (content: LeftColumnContent) => void;\n onScreenSelect: (screen: SettingsScreens) => void;\n onReset: () => void;\n};\n\ntype StateProps = Pick;\n\nconst TRANSITION_RENDER_COUNT = Object.keys(LeftColumnContent).length / 2;\nconst BUTTON_CLOSE_DELAY_MS = 250;\nconst APP_OUTDATED_TIMEOUT = 3 * 24 * 60 * 60 * 1000; // 3 days\n\nlet closeTimeout: number | undefined;\n\nconst LeftMain: FC = ({\n content,\n searchQuery,\n searchDate,\n contactsFilter,\n shouldSkipTransition,\n foldersDispatch,\n onSearchQuery,\n onContentChange,\n onScreenSelect,\n onReset,\n connectionState,\n}) => {\n const [isNewChatButtonShown, setIsNewChatButtonShown] = useState(IS_TOUCH_ENV);\n\n const isBrowserOnline = useBrowserOnline();\n const isConnecting = !isBrowserOnline || connectionState === 'connectionStateConnecting';\n\n const isMouseInside = useRef(false);\n\n const handleSelectSettings = useCallback(() => {\n onContentChange(LeftColumnContent.Settings);\n }, [onContentChange]);\n\n const handleSelectContacts = useCallback(() => {\n onContentChange(LeftColumnContent.Contacts);\n }, [onContentChange]);\n\n const handleSelectNewChannel = useCallback(() => {\n onContentChange(LeftColumnContent.NewChannelStep1);\n }, [onContentChange]);\n\n const handleSelectNewGroup = useCallback(() => {\n onContentChange(LeftColumnContent.NewGroupStep1);\n }, [onContentChange]);\n\n const handleSelectArchived = useCallback(() => {\n onContentChange(LeftColumnContent.Archived);\n }, [onContentChange]);\n\n const handleMouseEnter = useCallback(() => {\n if (content !== LeftColumnContent.ChatList) {\n return;\n }\n isMouseInside.current = true;\n setIsNewChatButtonShown(true);\n }, [content]);\n\n const handleMouseLeave = useCallback(() => {\n isMouseInside.current = false;\n\n if (closeTimeout) {\n clearTimeout(closeTimeout);\n closeTimeout = undefined;\n }\n\n closeTimeout = window.setTimeout(() => {\n if (!isMouseInside.current) {\n setIsNewChatButtonShown(false);\n }\n }, BUTTON_CLOSE_DELAY_MS);\n }, []);\n\n useEffect(() => {\n let autoCloseTimeout: number | undefined;\n if (content !== LeftColumnContent.ChatList) {\n autoCloseTimeout = window.setTimeout(() => {\n setIsNewChatButtonShown(false);\n }, BUTTON_CLOSE_DELAY_MS);\n } else if (isMouseInside.current || IS_TOUCH_ENV) {\n setIsNewChatButtonShown(true);\n }\n\n return () => {\n if (autoCloseTimeout) {\n clearTimeout(autoCloseTimeout);\n autoCloseTimeout = undefined;\n }\n };\n }, [content]);\n\n const [shouldRenderUpdateButton, updateButtonClassNames, handleUpdateClick] = useAppOutdatedCheck();\n\n const lang = useLang();\n\n return (\n \n \n \n {() => }\n \n \n {(isActive) => {\n switch (content) {\n case LeftColumnContent.ChatList:\n return ;\n case LeftColumnContent.GlobalSearch:\n return (\n \n );\n case LeftColumnContent.Contacts:\n return ;\n default:\n return undefined;\n }\n }}\n \n {shouldRenderUpdateButton && (\n \n {lang('lng_update_telegram')}\n \n )}\n \n
\n );\n};\n\nfunction useAppOutdatedCheck() {\n const [isAppOutdated, markIsAppOutdated] = useFlag(false);\n\n useEffect(() => {\n const timeout = window.setTimeout(markIsAppOutdated, APP_OUTDATED_TIMEOUT);\n\n return () => {\n clearTimeout(timeout);\n };\n }, [markIsAppOutdated]);\n\n const { shouldRender, transitionClassNames } = useShowTransition(isAppOutdated);\n\n const handleUpdateClick = () => {\n window.location.reload();\n };\n\n return [shouldRender, transitionClassNames, handleUpdateClick] as const;\n}\n\nexport default withGlobal(\n (global): StateProps => pick(global, ['connectionState']),\n)(LeftMain);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport { OwnProps } from './Settings';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\nimport Loading from '../../ui/Loading';\n\nconst SettingsAsync: FC = (props) => {\n const Settings = useModuleLoader(Bundles.Extra, 'Settings');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return Settings ? : ;\n};\n\nexport default memo(SettingsAsync);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport { OwnProps } from './NewChat';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\nimport Loading from '../../ui/Loading';\n\nconst NewChatAsync: FC = (props) => {\n const NewChat = useModuleLoader(Bundles.Extra, 'NewChat');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return NewChat ? : ;\n};\n\nexport default memo(NewChatAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './ArchivedChats';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst ArchivedChatsAsync: FC = (props) => {\n const ArchivedChats = useModuleLoader(Bundles.Extra, 'ArchivedChats');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return ArchivedChats ? : ;\n};\n\nexport default memo(ArchivedChatsAsync);\n","import React, {\n FC, memo, useCallback, useEffect, useRef, useState,\n} from '../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../lib/teact/teactn';\n\nimport { LeftColumnContent, SettingsScreens } from '../../types';\n\nimport { IS_MAC_OS, LAYERS_ANIMATION_NAME } from '../../util/environment';\nimport captureEscKeyListener from '../../util/captureEscKeyListener';\nimport getKeyFromEvent from '../../util/getKeyFromEvent';\nimport useFoldersReducer from '../../hooks/reducers/useFoldersReducer';\nimport { useResize } from '../../hooks/useResize';\n\nimport Transition from '../ui/Transition';\nimport LeftMain from './main/LeftMain';\nimport Settings from './settings/Settings.async';\nimport NewChat from './newChat/NewChat.async';\nimport ArchivedChats from './ArchivedChats.async';\n\nimport './LeftColumn.scss';\n\ntype StateProps = {\n searchQuery?: string;\n searchDate?: number;\n activeChatFolder: number;\n shouldSkipHistoryAnimations?: boolean;\n leftColumnWidth?: number;\n};\n\nenum ContentType {\n Main,\n // eslint-disable-next-line @typescript-eslint/no-shadow\n Settings,\n Archived,\n // eslint-disable-next-line no-shadow\n NewGroup,\n // eslint-disable-next-line no-shadow\n NewChannel,\n}\n\nconst RENDER_COUNT = Object.keys(ContentType).length / 2;\nconst RESET_TRANSITION_DELAY_MS = 250;\n\nconst LeftColumn: FC = ({\n searchQuery,\n searchDate,\n activeChatFolder,\n shouldSkipHistoryAnimations,\n leftColumnWidth,\n}) => {\n const {\n setGlobalSearchQuery,\n setGlobalSearchChatId,\n resetChatCreation,\n setGlobalSearchDate,\n loadPasswordInfo,\n clearTwoFaError,\n setLeftColumnWidth,\n resetLeftColumnWidth,\n } = getDispatch();\n\n // eslint-disable-next-line no-null/no-null\n const resizeRef = useRef(null);\n const [content, setContent] = useState(LeftColumnContent.ChatList);\n const [settingsScreen, setSettingsScreen] = useState(SettingsScreens.Main);\n const [contactsFilter, setContactsFilter] = useState('');\n const [foldersState, foldersDispatch] = useFoldersReducer();\n\n // Used to reset child components in background.\n const [lastResetTime, setLastResetTime] = useState(0);\n\n let contentType: ContentType = ContentType.Main;\n switch (content) {\n case LeftColumnContent.Archived:\n contentType = ContentType.Archived;\n break;\n case LeftColumnContent.Settings:\n contentType = ContentType.Settings;\n break;\n case LeftColumnContent.NewChannelStep1:\n case LeftColumnContent.NewChannelStep2:\n contentType = ContentType.NewChannel;\n break;\n case LeftColumnContent.NewGroupStep1:\n case LeftColumnContent.NewGroupStep2:\n contentType = ContentType.NewGroup;\n break;\n }\n\n const handleReset = useCallback((forceReturnToChatList?: boolean) => {\n if (content === LeftColumnContent.NewGroupStep2\n && !forceReturnToChatList\n ) {\n setContent(LeftColumnContent.NewGroupStep1);\n return;\n }\n\n if (content === LeftColumnContent.NewChannelStep2\n && !forceReturnToChatList\n ) {\n setContent(LeftColumnContent.NewChannelStep1);\n return;\n }\n\n if (content === LeftColumnContent.NewGroupStep1) {\n const pickerSearchInput = document.getElementById('new-group-picker-search');\n if (pickerSearchInput) {\n pickerSearchInput.blur();\n }\n }\n\n if (content === LeftColumnContent.Settings) {\n switch (settingsScreen) {\n case SettingsScreens.EditProfile:\n case SettingsScreens.Folders:\n case SettingsScreens.General:\n case SettingsScreens.Notifications:\n case SettingsScreens.DataStorage:\n case SettingsScreens.Privacy:\n case SettingsScreens.Language:\n setSettingsScreen(SettingsScreens.Main);\n return;\n\n case SettingsScreens.GeneralChatBackground:\n setSettingsScreen(SettingsScreens.General);\n return;\n case SettingsScreens.GeneralChatBackgroundColor:\n setSettingsScreen(SettingsScreens.GeneralChatBackground);\n return;\n\n case SettingsScreens.PrivacyPhoneNumber:\n case SettingsScreens.PrivacyLastSeen:\n case SettingsScreens.PrivacyProfilePhoto:\n case SettingsScreens.PrivacyForwarding:\n case SettingsScreens.PrivacyGroupChats:\n case SettingsScreens.PrivacyActiveSessions:\n case SettingsScreens.PrivacyBlockedUsers:\n case SettingsScreens.TwoFaDisabled:\n case SettingsScreens.TwoFaEnabled:\n case SettingsScreens.TwoFaCongratulations:\n setSettingsScreen(SettingsScreens.Privacy);\n return;\n case SettingsScreens.PrivacyPhoneNumberAllowedContacts:\n case SettingsScreens.PrivacyPhoneNumberDeniedContacts:\n setSettingsScreen(SettingsScreens.PrivacyPhoneNumber);\n return;\n case SettingsScreens.PrivacyLastSeenAllowedContacts:\n case SettingsScreens.PrivacyLastSeenDeniedContacts:\n setSettingsScreen(SettingsScreens.PrivacyLastSeen);\n return;\n case SettingsScreens.PrivacyProfilePhotoAllowedContacts:\n case SettingsScreens.PrivacyProfilePhotoDeniedContacts:\n setSettingsScreen(SettingsScreens.PrivacyProfilePhoto);\n return;\n case SettingsScreens.PrivacyForwardingAllowedContacts:\n case SettingsScreens.PrivacyForwardingDeniedContacts:\n setSettingsScreen(SettingsScreens.PrivacyForwarding);\n return;\n case SettingsScreens.PrivacyGroupChatsAllowedContacts:\n case SettingsScreens.PrivacyGroupChatsDeniedContacts:\n setSettingsScreen(SettingsScreens.PrivacyGroupChats);\n return;\n case SettingsScreens.TwoFaNewPassword:\n setSettingsScreen(SettingsScreens.TwoFaDisabled);\n return;\n case SettingsScreens.TwoFaNewPasswordConfirm:\n setSettingsScreen(SettingsScreens.TwoFaNewPassword);\n return;\n case SettingsScreens.TwoFaNewPasswordHint:\n setSettingsScreen(SettingsScreens.TwoFaNewPasswordConfirm);\n return;\n case SettingsScreens.TwoFaNewPasswordEmail:\n setSettingsScreen(SettingsScreens.TwoFaNewPasswordHint);\n return;\n case SettingsScreens.TwoFaNewPasswordEmailCode:\n setSettingsScreen(SettingsScreens.TwoFaNewPasswordEmail);\n return;\n case SettingsScreens.TwoFaChangePasswordCurrent:\n case SettingsScreens.TwoFaTurnOff:\n case SettingsScreens.TwoFaRecoveryEmailCurrentPassword:\n setSettingsScreen(SettingsScreens.TwoFaEnabled);\n return;\n case SettingsScreens.TwoFaChangePasswordNew:\n setSettingsScreen(SettingsScreens.TwoFaChangePasswordCurrent);\n return;\n case SettingsScreens.TwoFaChangePasswordConfirm:\n setSettingsScreen(SettingsScreens.TwoFaChangePasswordNew);\n return;\n case SettingsScreens.TwoFaChangePasswordHint:\n setSettingsScreen(SettingsScreens.TwoFaChangePasswordConfirm);\n return;\n case SettingsScreens.TwoFaRecoveryEmail:\n setSettingsScreen(SettingsScreens.TwoFaRecoveryEmailCurrentPassword);\n return;\n case SettingsScreens.TwoFaRecoveryEmailCode:\n setSettingsScreen(SettingsScreens.TwoFaRecoveryEmail);\n return;\n\n case SettingsScreens.FoldersCreateFolder:\n case SettingsScreens.FoldersEditFolder:\n setSettingsScreen(SettingsScreens.Folders);\n return;\n\n case SettingsScreens.FoldersIncludedChatsFromChatList:\n case SettingsScreens.FoldersExcludedChatsFromChatList:\n setSettingsScreen(SettingsScreens.FoldersEditFolderFromChatList);\n return;\n\n case SettingsScreens.FoldersEditFolderFromChatList:\n setContent(LeftColumnContent.ChatList);\n setSettingsScreen(SettingsScreens.Main);\n return;\n default:\n break;\n }\n }\n\n if (content === LeftColumnContent.ChatList && activeChatFolder === 0) {\n setContent(LeftColumnContent.GlobalSearch);\n return;\n }\n\n setContent(LeftColumnContent.ChatList);\n setContactsFilter('');\n setGlobalSearchQuery({ query: '' });\n setGlobalSearchDate({ date: undefined });\n setGlobalSearchChatId({ id: undefined });\n resetChatCreation();\n setTimeout(() => {\n setLastResetTime(Date.now());\n }, RESET_TRANSITION_DELAY_MS);\n }, [\n content, activeChatFolder, settingsScreen, setGlobalSearchQuery, setGlobalSearchDate, setGlobalSearchChatId,\n resetChatCreation,\n ]);\n\n const handleSearchQuery = useCallback((query: string) => {\n if (content === LeftColumnContent.Contacts) {\n setContactsFilter(query);\n return;\n }\n\n setContent(LeftColumnContent.GlobalSearch);\n\n if (query !== searchQuery) {\n setGlobalSearchQuery({ query });\n }\n }, [content, searchQuery, setGlobalSearchQuery]);\n\n useEffect(\n () => (content !== LeftColumnContent.ChatList || activeChatFolder === 0\n ? captureEscKeyListener(() => handleReset())\n : undefined),\n [activeChatFolder, content, handleReset],\n );\n\n useEffect(() => {\n if (content === LeftColumnContent.GlobalSearch) {\n return undefined;\n }\n\n function handleKeyDown(e: KeyboardEvent) {\n if (((IS_MAC_OS && e.metaKey) || (!IS_MAC_OS && e.ctrlKey)) && e.shiftKey && getKeyFromEvent(e) === 'f') {\n e.preventDefault();\n setContent(LeftColumnContent.GlobalSearch);\n }\n }\n\n document.addEventListener('keydown', handleKeyDown, false);\n\n return () => {\n document.removeEventListener('keydown', handleKeyDown, false);\n };\n }, [content]);\n\n useEffect(() => {\n clearTwoFaError();\n\n if (settingsScreen === SettingsScreens.Privacy) {\n loadPasswordInfo();\n }\n }, [clearTwoFaError, loadPasswordInfo, settingsScreen]);\n\n const {\n initResize, resetResize, handleMouseUp,\n } = useResize(resizeRef, setLeftColumnWidth, resetLeftColumnWidth, leftColumnWidth);\n\n const handleSettingsScreenSelect = (screen: SettingsScreens) => {\n setContent(LeftColumnContent.Settings);\n setSettingsScreen(screen);\n };\n\n return (\n \n \n {(isActive) => {\n switch (contentType) {\n case ContentType.Archived:\n return (\n \n );\n case ContentType.Settings:\n return (\n \n );\n case ContentType.NewChannel:\n return (\n \n );\n case ContentType.NewGroup:\n return (\n \n );\n default:\n return (\n \n );\n }\n }}\n \n \n \n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n globalSearch: {\n query,\n date,\n },\n chatFolders: {\n activeChatFolder,\n },\n shouldSkipHistoryAnimations,\n leftColumnWidth,\n } = global;\n return {\n searchQuery: query, searchDate: date, activeChatFolder, shouldSkipHistoryAnimations, leftColumnWidth,\n };\n },\n)(LeftColumn));\n","import { RefObject } from 'react';\nimport { useState, useEffect } from '../lib/teact/teact';\nimport useFlag from './useFlag';\n\nexport const useResize = (\n elementRef: RefObject,\n onResize: (width: number) => void,\n onReset: NoneToVoidFunction,\n initialWidth?: number,\n) => {\n const [isActive, markIsActive, unmarkIsActive] = useFlag();\n const [initialMouseX, setInitialMouseX] = useState();\n const [initialElementWidth, setInitialElementWidth] = useState();\n\n useEffect(() => {\n if (!elementRef.current || !initialWidth) {\n return;\n }\n\n elementRef.current.style.width = `${initialWidth}px`;\n }, [elementRef, initialWidth]);\n\n const handleMouseUp = () => {\n document.body.classList.remove('no-selection', 'cursor-ew-resize');\n };\n\n const initResize = (event: React.MouseEvent) => {\n document.body.classList.add('no-selection', 'cursor-ew-resize');\n\n setInitialMouseX(event.clientX);\n setInitialElementWidth(elementRef.current!.offsetWidth);\n markIsActive();\n };\n\n const resetResize = (event: React.MouseEvent) => {\n event.preventDefault();\n elementRef.current!.style.width = '';\n onReset();\n };\n\n useEffect(() => {\n if (!isActive) return;\n\n const handleMouseMove = (event: MouseEvent) => {\n const newWidth = Math.ceil(initialElementWidth + event.clientX - initialMouseX);\n elementRef.current!.style.width = `${newWidth}px`;\n };\n\n const stopDrag = () => {\n handleMouseUp();\n document.removeEventListener('mousemove', handleMouseMove, false);\n document.removeEventListener('mouseup', stopDrag, false);\n document.removeEventListener('blur', stopDrag, false);\n onResize(elementRef.current!.offsetWidth);\n unmarkIsActive();\n };\n\n document.addEventListener('mousemove', handleMouseMove, false);\n document.addEventListener('mouseup', stopDrag, false);\n document.addEventListener('blur', stopDrag, false);\n }, [initialElementWidth, initialMouseX, elementRef, onResize, isActive, unmarkIsActive]);\n\n return { initResize, resetResize, handleMouseUp };\n};\n","import { useEffect, useState } from '../lib/teact/teact';\n\nimport { ThemeKey } from '../types';\n\nimport { CUSTOM_BG_CACHE_NAME } from '../config';\nimport * as cacheApi from '../util/cacheApi';\nimport { preloadImage } from '../util/files';\n\nexport default (theme: ThemeKey, settingValue?: string) => {\n const [value, setValue] = useState(settingValue);\n\n useEffect(() => {\n if (!settingValue) {\n return;\n }\n\n if (settingValue.startsWith('#')) {\n setValue(settingValue);\n } else {\n cacheApi.fetch(CUSTOM_BG_CACHE_NAME, theme, cacheApi.Type.Blob)\n .then((blob) => {\n const url = URL.createObjectURL(blob);\n preloadImage(url)\n .then(() => {\n setValue(`url(${url})`);\n });\n });\n }\n }, [settingValue, theme]);\n\n return settingValue ? value : undefined;\n};\n","import { useEffect, useState } from '../lib/teact/teact';\n\nimport { throttle } from '../util/schedulers';\nimport windowSize from '../util/windowSize';\nimport { ApiDimensions } from '../api/types';\n\nconst THROTTLE = 250;\n\nexport default () => {\n const [size, setSize] = useState(windowSize.get());\n\n useEffect(() => {\n const handleResize = throttle(() => {\n setSize(windowSize.get());\n }, THROTTLE, false);\n\n window.addEventListener('resize', handleResize);\n\n return () => {\n window.removeEventListener('resize', handleResize);\n };\n }, []);\n\n return size;\n};\n","import {\n MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN,\n MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN,\n MOBILE_SCREEN_MAX_WIDTH,\n} from '../../../config';\n\nconst REM = 16; // px\nconst MAX_TOOLBAR_WIDTH = 32 * REM;\nconst MAX_MESSAGES_LIST_WIDTH = 45.5 * REM;\nconst SIDE_COLUMN_MAX_WIDTH = 26.5 * REM;\nconst MIN_LEFT_COLUMN_WIDTH = 18 * REM;\nconst UNPIN_BUTTON_WIDTH = 16.125 * REM;\n\nexport default function calculateMiddleFooterTransforms(windowWidth: number, canPost?: boolean) {\n const sidePadding = windowWidth <= MOBILE_SCREEN_MAX_WIDTH\n ? REM\n : 2 * REM;\n const messageListWidth = getMessageListWidth(windowWidth);\n const sendButtonWidth = windowWidth <= MOBILE_SCREEN_MAX_WIDTH\n ? 3.375 * REM\n : 4 * REM;\n\n const composerWidth = canPost\n ? messageListWidth - sidePadding - sendButtonWidth\n : messageListWidth - sidePadding;\n const toolbarWidth = windowWidth > MOBILE_SCREEN_MAX_WIDTH\n ? Math.min(messageListWidth - sidePadding, MAX_TOOLBAR_WIDTH)\n : messageListWidth - sidePadding;\n\n const composerHiddenScale = toolbarWidth / composerWidth;\n const toolbarHiddenScale = composerWidth / toolbarWidth;\n const unpinHiddenScale = toolbarWidth / UNPIN_BUTTON_WIDTH;\n const toolbarForUnpinHiddenScale = UNPIN_BUTTON_WIDTH / toolbarWidth;\n\n const composerTranslateX = canPost\n ? (sendButtonWidth / 2) * toolbarHiddenScale\n : 0;\n\n const toolbarTranslateX = canPost\n ? (sendButtonWidth / 2) * -1 * composerHiddenScale\n : 0;\n\n return {\n composerHiddenScale,\n toolbarHiddenScale,\n composerTranslateX,\n toolbarTranslateX,\n unpinHiddenScale,\n toolbarForUnpinHiddenScale,\n };\n}\n\nfunction getMessageListWidth(windowWidth: number) {\n if (windowWidth > MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN) {\n const leftColumnWidth = Math.min(\n Math.max(windowWidth * 0.25, MIN_LEFT_COLUMN_WIDTH),\n SIDE_COLUMN_MAX_WIDTH,\n );\n\n const rightColumnWidth = Math.min(\n windowWidth * 0.25,\n SIDE_COLUMN_MAX_WIDTH,\n );\n\n return Math.min(\n windowWidth - leftColumnWidth - rightColumnWidth,\n MAX_MESSAGES_LIST_WIDTH,\n );\n }\n\n if (windowWidth > MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN) {\n const leftColumnWidth = Math.min(\n Math.max(windowWidth * 0.4, MIN_LEFT_COLUMN_WIDTH),\n SIDE_COLUMN_MAX_WIDTH,\n );\n\n return Math.min(\n windowWidth - leftColumnWidth,\n MAX_MESSAGES_LIST_WIDTH,\n );\n }\n\n if (windowWidth > MAX_MESSAGES_LIST_WIDTH) {\n return MAX_MESSAGES_LIST_WIDTH;\n }\n\n return windowWidth;\n}\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './HeaderMenuContainer';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst HeaderMenuContainerAsync: FC = (props) => {\n const { isOpen } = props;\n const HeaderMenuContainer = useModuleLoader(Bundles.Extra, 'HeaderMenuContainer', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return HeaderMenuContainer ? : undefined;\n};\n\nexport default memo(HeaderMenuContainerAsync);\n","import React, {\n FC,\n memo,\n useRef,\n useCallback,\n useState,\n useEffect,\n} from '../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../lib/teact/teactn';\n\nimport { MessageListType } from '../../global/types';\nimport { MAIN_THREAD_ID } from '../../api/types';\nimport { IAnchorPosition } from '../../types';\n\nimport {\n ARE_CALLS_SUPPORTED, IS_MAC_OS, IS_PWA, IS_SINGLE_COLUMN_LAYOUT,\n} from '../../util/environment';\nimport getKeyFromEvent from '../../util/getKeyFromEvent';\nimport {\n isChatBasicGroup, isChatChannel, isChatSuperGroup, isUserId,\n} from '../../modules/helpers';\nimport {\n selectChat,\n selectChatBot,\n selectIsUserBlocked,\n selectIsChatBotNotStarted,\n selectIsChatWithSelf,\n selectIsInSelectMode,\n selectIsRightColumnShown,\n} from '../../modules/selectors';\nimport useLang from '../../hooks/useLang';\n\nimport Button from '../ui/Button';\nimport HeaderMenuContainer from './HeaderMenuContainer.async';\n\ninterface OwnProps {\n chatId: string;\n threadId: number;\n messageListType: MessageListType;\n canExpandActions: boolean;\n}\n\ninterface StateProps {\n noMenu?: boolean;\n isChannel?: boolean;\n isRightColumnShown?: boolean;\n canStartBot?: boolean;\n canRestartBot?: boolean;\n canSubscribe?: boolean;\n canSearch?: boolean;\n canCall?: boolean;\n canMute?: boolean;\n canLeave?: boolean;\n canEnterVoiceChat?: boolean;\n canCreateVoiceChat?: boolean;\n}\n\n// Chrome breaks layout when focusing input during transition\nconst SEARCH_FOCUS_DELAY_MS = 400;\n\nconst HeaderActions: FC = ({\n chatId,\n threadId,\n noMenu,\n isChannel,\n canStartBot,\n canRestartBot,\n canSubscribe,\n canSearch,\n canCall,\n canMute,\n canLeave,\n canEnterVoiceChat,\n canCreateVoiceChat,\n isRightColumnShown,\n canExpandActions,\n}) => {\n const {\n joinChannel,\n sendBotCommand,\n openLocalTextSearch,\n restartBot,\n openCallFallbackConfirm,\n } = getDispatch();\n\n // eslint-disable-next-line no-null/no-null\n const menuButtonRef = useRef(null);\n const [isMenuOpen, setIsMenuOpen] = useState(false);\n const [menuPosition, setMenuPosition] = useState(undefined);\n\n const handleHeaderMenuOpen = useCallback(() => {\n setIsMenuOpen(true);\n const rect = menuButtonRef.current!.getBoundingClientRect();\n setMenuPosition({ x: rect.right, y: rect.bottom });\n }, []);\n\n const handleHeaderMenuClose = useCallback(() => {\n setIsMenuOpen(false);\n }, []);\n\n const handleHeaderMenuHide = useCallback(() => {\n setMenuPosition(undefined);\n }, []);\n\n const handleSubscribeClick = useCallback(() => {\n joinChannel({ chatId });\n }, [joinChannel, chatId]);\n\n const handleStartBot = useCallback(() => {\n sendBotCommand({ command: '/start' });\n }, [sendBotCommand]);\n\n const handleRestartBot = useCallback(() => {\n restartBot({ chatId });\n }, [chatId, restartBot]);\n\n const handleSearchClick = useCallback(() => {\n openLocalTextSearch();\n\n if (IS_SINGLE_COLUMN_LAYOUT) {\n // iOS requires synchronous focus on user event.\n const searchInput = document.querySelector('#MobileSearch input')!;\n searchInput.focus();\n } else {\n setTimeout(() => {\n const searchInput = document.querySelector('.RightHeader .SearchInput input');\n if (searchInput) {\n searchInput.focus();\n }\n }, SEARCH_FOCUS_DELAY_MS);\n }\n }, [openLocalTextSearch]);\n\n useEffect(() => {\n if (!canSearch) {\n return undefined;\n }\n\n function handleKeyDown(e: KeyboardEvent) {\n if (\n IS_PWA && ((IS_MAC_OS && e.metaKey) || (!IS_MAC_OS && e.ctrlKey)) && !e.shiftKey && getKeyFromEvent(e) === 'f'\n ) {\n e.preventDefault();\n handleSearchClick();\n }\n }\n\n document.addEventListener('keydown', handleKeyDown, false);\n\n return () => {\n document.removeEventListener('keydown', handleKeyDown, false);\n };\n }, [canSearch, handleSearchClick]);\n\n const lang = useLang();\n\n return (\n
\n {!IS_SINGLE_COLUMN_LAYOUT && (\n <>\n {canExpandActions && canSubscribe && (\n \n {lang(isChannel ? 'ProfileJoinChannel' : 'ProfileJoinGroup')}\n \n )}\n {canExpandActions && canStartBot && (\n \n {lang('BotStart')}\n \n )}\n {canExpandActions && canRestartBot && (\n \n {lang('BotRestart')}\n \n )}\n {canSearch && (\n \n \n \n )}\n {canCall && (\n \n \n \n )}\n \n )}\n \n \n \n {menuPosition && (\n \n )}\n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { chatId, threadId, messageListType }): StateProps => {\n const chat = selectChat(global, chatId);\n const isChannel = Boolean(chat && isChatChannel(chat));\n\n if (!chat || chat.isRestricted || selectIsInSelectMode(global)) {\n return {\n noMenu: true,\n };\n }\n\n const bot = selectChatBot(global, chatId);\n const isChatWithSelf = selectIsChatWithSelf(global, chatId);\n const isMainThread = messageListType === 'thread' && threadId === MAIN_THREAD_ID;\n const isDiscussionThread = messageListType === 'thread' && threadId !== MAIN_THREAD_ID;\n const isRightColumnShown = selectIsRightColumnShown(global);\n\n const canRestartBot = Boolean(bot && selectIsUserBlocked(global, bot.id));\n const canStartBot = !canRestartBot && Boolean(selectIsChatBotNotStarted(global, chatId));\n const canSubscribe = Boolean(\n isMainThread && (isChannel || isChatSuperGroup(chat)) && chat.isNotJoined,\n );\n const canSearch = isMainThread || isDiscussionThread;\n const canCall = ARE_CALLS_SUPPORTED && isUserId(chat.id) && !isChatWithSelf && !bot;\n const canMute = isMainThread && !isChatWithSelf && !canSubscribe;\n const canLeave = isMainThread && !canSubscribe;\n const canEnterVoiceChat = ARE_CALLS_SUPPORTED && chat.isCallActive;\n const canCreateVoiceChat = ARE_CALLS_SUPPORTED && !chat.isCallActive\n && (chat.adminRights?.manageCall || (chat.isCreator && isChatBasicGroup(chat)));\n\n return {\n noMenu: false,\n isChannel,\n isRightColumnShown,\n canStartBot,\n canRestartBot,\n canSubscribe,\n canSearch,\n canCall,\n canMute,\n canLeave,\n canEnterVoiceChat,\n canCreateVoiceChat,\n };\n },\n)(HeaderActions));\n","import { useLayoutEffect, useState } from '../lib/teact/teact';\n\nimport { ApiMessage } from '../api/types';\n\nimport { DEBUG } from '../config';\nimport { isWebpSupported } from '../util/environment';\nimport { EMPTY_IMAGE_DATA_URI, webpToPngBase64 } from '../util/webpToPng';\nimport { getMessageMediaThumbDataUri } from '../modules/helpers';\n\nexport default function useWebpThumbnail(message?: ApiMessage) {\n const thumbDataUri = message && getMessageMediaThumbDataUri(message);\n const sticker = message?.content?.sticker;\n const shouldDecodeThumbnail = thumbDataUri && sticker && !isWebpSupported() && thumbDataUri.includes('image/webp');\n const [thumbnailDecoded, setThumbnailDecoded] = useState(EMPTY_IMAGE_DATA_URI);\n const messageId = message?.id;\n\n useLayoutEffect(() => {\n if (!shouldDecodeThumbnail) {\n return;\n }\n\n webpToPngBase64(`b64-${messageId}`, thumbDataUri!)\n .then(setThumbnailDecoded)\n .catch((err) => {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n });\n }, [messageId, shouldDecodeThumbnail, thumbDataUri]);\n\n return shouldDecodeThumbnail ? thumbnailDecoded : thumbDataUri;\n}\n","import React, {\n FC,\n useRef,\n useEffect,\n useMemo,\n memo,\n} from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\ntype OwnProps = {\n count: number;\n index: number;\n};\n\nconst BORDER_MASK_LEVEL = 4;\n\nconst PinnedMessageNavigation: FC = ({\n count, index,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef(null);\n\n const markupParams = useMemo(() => {\n return calculateMarkup(count, index);\n }, [count, index]);\n\n useEffect(() => {\n if (!containerRef.current) {\n return;\n }\n\n const {\n trackHeight,\n trackTranslateY,\n markHeight,\n markTranslateY,\n clipPathId,\n clipPath,\n } = markupParams;\n\n const firstChild = containerRef.current.firstElementChild;\n if (containerRef?.current) {\n const currentElement = containerRef.current;\n const { style } = currentElement;\n style.height = `${trackHeight}px`;\n style.transform = `translateY(-${trackTranslateY}px)`;\n style.clipPath = `url(\"#${clipPathId}\")`;\n const svg = currentElement.querySelector('svg');\n const div = currentElement.querySelector('div');\n const defs = currentElement.querySelector('defs');\n if (!svg) {\n if (firstChild) {\n firstChild.innerHTML = ` ${clipPath} `;\n }\n }\n if (defs) {\n defs.innerHTML = clipPath;\n }\n if (div) {\n div.style.height = `${markHeight}px`;\n div.style.transform = `translateY(${markTranslateY}px)`;\n }\n }\n }, [markupParams]);\n\n if (count === 1) {\n return (\n
\n \n
\n );\n }\n\n const {\n trackHeight, trackTranslateY, markHeight, markTranslateY, clipPathId,\n } = markupParams;\n\n return (\n
BORDER_MASK_LEVEL && 'pinned-message-border-mask')}>\n \n \n \n
\n \n );\n};\n\nfunction calculateMarkup(count: number, index: number) {\n const reverseIndex = count - index - 1;\n const barHeight = getBarHeight(count);\n const markHeight = getMarkHeight(count, reverseIndex);\n const trackHeight = getTrackHeight(count, barHeight);\n\n const clipPathId = `clipPath${count}`;\n const clipPath = getClipPath(clipPathId, barHeight, count);\n\n const markTranslateY = getMarkTranslateY(reverseIndex, barHeight, count);\n const trackTranslateY = getTrackTranslateY(reverseIndex, count, barHeight, trackHeight);\n return {\n markHeight,\n clipPath,\n markTranslateY,\n trackTranslateY,\n trackHeight,\n clipPathId,\n };\n}\n\nfunction getBarHeight(count: number): number {\n let barHeight = 8;\n if (count === 1) {\n barHeight = 36;\n } else if (count === 2) {\n barHeight = 17;\n } else if (count === 3) {\n barHeight = 11;\n } else if (count === 4) {\n barHeight = 7.5;\n } else if (count > 3) {\n barHeight = 7.5;\n }\n\n return barHeight;\n}\n\nfunction getMarkHeight(count: number, index: number) {\n let barHeight = 36;\n if (count === 1) {\n barHeight = 36;\n } else if (count === 2) {\n barHeight = 17;\n } else if (count === 3) {\n barHeight = index === 1 ? 12 : 11;\n } else if (count === 4) {\n barHeight = 7.5;\n } else if (count > 3) {\n barHeight = 7.5;\n }\n\n return barHeight;\n}\n\nfunction getTrackHeight(count: number, barHeight: number) {\n return count <= 3 ? 36 : barHeight * count + 2 * (count - 1);\n}\n\nfunction getClipPath(id: string, barHeight: number, count: number) {\n const radius = 1;\n\n let d = '';\n if (count === 3) {\n d = drawRect(0, 0, 2, barHeight, radius)\n + drawRect(0, 12, 2, barHeight + 1, radius)\n + drawRect(0, 25, 2, barHeight, radius);\n } else {\n for (let i = 0; i < count; i++) {\n d += drawRect(0, (barHeight + 2) * i, 2, barHeight, radius);\n }\n }\n\n return (\n `\n \n `\n );\n}\n\nfunction drawRect(x: number, y: number, width: number, height: number, radius: number) {\n return `M${x},${y + radius}a${radius},${radius},0,0,1,\n ${width},0v${height - 2 * radius}a${radius},${radius},0,0,1,${-width},0Z`;\n}\n\nfunction getMarkTranslateY(index: number, barHeight: number, count: number) {\n if (count === 1) {\n return 0;\n } else if (count === 2) {\n return index === 0 ? 0 : barHeight + 2;\n }\n\n if (count === 3) {\n if (index === 0) {\n return 0;\n } else if (index === 1) {\n return 12;\n }\n\n return 25;\n } else {\n return (barHeight + 2) * index;\n }\n}\n\nfunction getTrackTranslateY(index: number, count: number, barHeight: number, trackHeight: number) {\n if (count <= 4) {\n return 0;\n }\n\n if (index <= 1) {\n return 0;\n } else if (index >= count - 2) {\n return trackHeight - 36;\n }\n\n return (barHeight + 4) / 2 + (index - 2) * (barHeight + 2);\n}\n\nexport default memo(PinnedMessageNavigation);\n","import React, { FC, memo, useCallback } from '../../lib/teact/teact';\n\nimport { ApiMessage } from '../../api/types';\n\nimport { getPictogramDimensions } from '../common/helpers/mediaDimensions';\nimport { getMessageMediaHash, getMessageSummaryText } from '../../modules/helpers';\nimport renderText from '../common/helpers/renderText';\nimport useMedia from '../../hooks/useMedia';\nimport useWebpThumbnail from '../../hooks/useWebpThumbnail';\n\nimport ConfirmDialog from '../ui/ConfirmDialog';\nimport Button from '../ui/Button';\nimport RippleEffect from '../ui/RippleEffect';\nimport buildClassName from '../../util/buildClassName';\nimport useFlag from '../../hooks/useFlag';\nimport useLang from '../../hooks/useLang';\n\nimport PinnedMessageNavigation from './PinnedMessageNavigation';\n\ntype OwnProps = {\n message: ApiMessage;\n index: number;\n count: number;\n customTitle?: string;\n className?: string;\n onUnpinMessage?: (id: number) => void;\n onClick?: () => void;\n onAllPinnedClick?: () => void;\n};\n\nconst HeaderPinnedMessage: FC = ({\n message, count, index, customTitle, className, onUnpinMessage, onClick, onAllPinnedClick,\n}) => {\n const lang = useLang();\n const mediaThumbnail = useWebpThumbnail(message);\n const mediaBlobUrl = useMedia(getMessageMediaHash(message, 'pictogram'));\n\n const text = getMessageSummaryText(lang, message, Boolean(mediaThumbnail));\n const [isUnpinDialogOpen, openUnpinDialog, closeUnpinDialog] = useFlag();\n\n const handleUnpinMessage = useCallback(() => {\n closeUnpinDialog();\n\n if (onUnpinMessage) {\n onUnpinMessage(message.id);\n }\n }, [closeUnpinDialog, onUnpinMessage, message.id]);\n\n return (\n
\n {count > 1 && (\n \n \n \n )}\n {onUnpinMessage && (\n \n \n \n )}\n \n
\n \n {mediaThumbnail && renderPictogram(mediaThumbnail, mediaBlobUrl)}\n
\n
\n {customTitle || `${lang('PinnedMessage')} ${index > 0 ? `#${count - index}` : ''}`}\n
\n

{renderText(text)}

\n
\n\n \n
\n
\n );\n};\n\nfunction renderPictogram(thumbDataUri: string, blobUrl?: string) {\n const { width, height } = getPictogramDimensions();\n\n return (\n \"\"\n );\n}\n\nexport default memo(HeaderPinnedMessage);\n","export function scaleImage(image: string | Blob, ratio: number, outputType: string = 'image/png'): Promise {\n const url = image instanceof Blob ? URL.createObjectURL(image) : image;\n const img = new Image();\n return new Promise((resolve) => {\n img.onload = () => {\n scale(img, img.width * ratio, img.height * ratio, outputType)\n .then((blob) => URL.createObjectURL(blob))\n .then(resolve)\n .finally(() => {\n if (image instanceof Blob) {\n URL.revokeObjectURL(url); // Revoke blob url that we created\n }\n });\n };\n img.src = url;\n });\n}\n\nexport function resizeImage(\n image: string | Blob, width: number, height: number, outputType: string = 'image/png',\n): Promise {\n const url = image instanceof Blob ? URL.createObjectURL(image) : image;\n const img = new Image();\n return new Promise((resolve) => {\n img.onload = () => {\n scale(img, width, height, outputType)\n .then((blob) => URL.createObjectURL(blob))\n .then(resolve)\n .finally(() => {\n if (image instanceof Blob) {\n URL.revokeObjectURL(url); // Revoke blob url that we created\n }\n });\n };\n img.src = url;\n });\n}\n\nasync function scale(\n img: HTMLImageElement, width: number, height: number, outputType: string = 'image/png',\n) {\n // Safari does not have built-in resize method with quality control\n if ('createImageBitmap' in window) {\n try {\n const bitmap = await window.createImageBitmap(img,\n { resizeWidth: width, resizeHeight: height, resizeQuality: 'high' });\n if (bitmap.height !== height || bitmap.width !== width) {\n throw new Error('Image bitmap resize not supported!'); // FF93 added support for options, but not resize\n }\n return await new Promise((res) => {\n const canvas = document.createElement('canvas');\n canvas.width = bitmap.width;\n canvas.height = bitmap.height;\n const ctx = canvas.getContext('bitmaprenderer');\n if (ctx) {\n ctx.transferFromImageBitmap(bitmap);\n } else {\n canvas.getContext('2d')!.drawImage(bitmap, 0, 0);\n }\n canvas.toBlob(res, outputType);\n });\n } catch (e) {\n // Fallback. Firefox below 93 does not recognize `createImageBitmap` with 2 parameters\n return steppedScale(img, width, height, undefined, outputType);\n }\n } else {\n return steppedScale(img, width, height, undefined, outputType);\n }\n}\n\nfunction steppedScale(\n img: HTMLImageElement, width: number, height: number, step: number = 0.5, outputType: string = 'image/png',\n): Promise {\n const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d')!;\n const oc = document.createElement('canvas');\n const octx = oc.getContext('2d')!;\n\n canvas.width = width;\n canvas.height = height;\n\n if (img.width * step > width) { // For performance avoid unnecessary drawing\n const mul = 1 / step;\n let cur = {\n width: Math.floor(img.width * step),\n height: Math.floor(img.height * step),\n };\n\n oc.width = cur.width;\n oc.height = cur.height;\n\n octx.drawImage(img, 0, 0, cur.width, cur.height);\n\n while (cur.width * step > width) {\n cur = {\n width: Math.floor(cur.width * step),\n height: Math.floor(cur.height * step),\n };\n octx.drawImage(oc, 0, 0, cur.width * mul, cur.height * mul, 0, 0, cur.width, cur.height);\n }\n\n ctx.drawImage(oc, 0, 0, cur.width, cur.height, 0, 0, canvas.width, canvas.height);\n } else {\n ctx.drawImage(img, 0, 0, canvas.width, canvas.height);\n }\n\n return new Promise((resolve) => {\n canvas.toBlob(resolve, outputType);\n });\n}\n","import { useMemo } from '../lib/teact/teact';\n\nimport {\n ApiAudio, ApiChat, ApiMessage, ApiUser, ApiVoice,\n} from '../api/types';\n\nimport useMedia from './useMedia';\nimport { useAsync } from './useAsync';\nimport {\n getAudioHasCover, getChatAvatarHash, getChatTitle, getMessageContent, getMessageMediaHash, getSenderTitle,\n} from '../modules/helpers';\nimport { getTranslation } from '../util/langProvider';\nimport { buildMediaMetadata } from '../util/mediaSession';\nimport { scaleImage, resizeImage } from '../util/imageResize';\nimport { AVATAR_FULL_DIMENSIONS } from '../components/common/helpers/mediaDimensions';\n\n// @ts-ignore\nimport telegramLogoPath from '../assets/telegram-logo-filled.svg';\n\nconst LOGO_DIMENSIONS = { width: 200, height: 200 };\nconst MINIMAL_SIZE = 115; // spec says 100, but on Chrome 93 it's not showing\n\n// TODO Add support for video in future\nexport default (message: ApiMessage, sender?: ApiUser | ApiChat, chat?: ApiChat): MediaMetadata | undefined => {\n const { audio, voice } = getMessageContent(message);\n const title = audio ? (audio.title || audio.fileName) : voice ? 'Voice message' : '';\n const artist = (audio && audio.performer) || (sender && getSenderTitle(getTranslation, sender));\n const album = (chat && getChatTitle(getTranslation, chat)) || 'Telegram';\n\n const audioCoverHash = (audio && getAudioHasCover(audio) && getMessageMediaHash(message, 'pictogram'));\n const avatarHash = sender && getChatAvatarHash(sender, 'big');\n const hash = (audio && audioCoverHash) || (voice && avatarHash);\n const media = useMedia(hash);\n\n const size = useMemo(() => {\n return getCoverSize(audio, voice, media);\n }, [audio, media, voice]);\n const { result: url } = useAsync(() => makeGoodArtwork(media, size), [media, size], telegramLogoPath);\n return useMemo(() => {\n return buildMediaMetadata({\n title,\n artist,\n album,\n artwork: [{ src: url }],\n });\n }, [album, artist, title, url]);\n};\n\nfunction makeGoodArtwork(url?: string, size?: { width: number; height: number }): Promise {\n if (!url) return Promise.resolve(telegramLogoPath);\n if (!size) return resizeImage(url, MINIMAL_SIZE, MINIMAL_SIZE);\n const min = Math.min(size.width, size.height);\n if (min < MINIMAL_SIZE) {\n const ratio = MINIMAL_SIZE / min;\n return scaleImage(url, ratio);\n }\n return Promise.resolve(url);\n}\n\nfunction getCoverSize(audio?: ApiAudio, voice?: ApiVoice, url?: string) {\n if (!url) return LOGO_DIMENSIONS;\n if (audio) {\n if (!audio.thumbnailSizes || audio.thumbnailSizes.length === 0) return undefined;\n const preferred = audio.thumbnailSizes.find((size) => size.type === 'm');\n return preferred || audio.thumbnailSizes[0]; // Sometimes `m` is not present\n }\n\n if (voice) {\n return AVATAR_FULL_DIMENSIONS;\n }\n\n return undefined;\n}\n","import { useEffect, useState } from '../lib/teact/teact';\n\nexport const useAsync = (fn: () => Promise, deps: any[], defaultValue?: T) => {\n const [isLoading, setIsLoading] = useState(false);\n const [error, setError] = useState();\n const [result, setResult] = useState(defaultValue);\n useEffect(() => {\n setIsLoading(true);\n let wasCancelled = false;\n fn().then((res) => {\n if (wasCancelled) return;\n setIsLoading(false);\n setResult(res);\n }, (err) => {\n if (wasCancelled) return;\n setIsLoading(false);\n setError(err);\n });\n return () => {\n wasCancelled = true;\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, deps);\n return { isLoading, error, result };\n};\n","import React, {\n FC, useCallback, useEffect, useMemo,\n} from '../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../lib/teact/teactn';\n\nimport { AudioOrigin } from '../../types';\nimport {\n ApiAudio, ApiChat, ApiMessage, ApiUser,\n} from '../../api/types';\n\nimport { IS_IOS, IS_SINGLE_COLUMN_LAYOUT, IS_TOUCH_ENV } from '../../util/environment';\n\nimport * as mediaLoader from '../../util/mediaLoader';\nimport {\n getMediaDuration, getMessageContent, getMessageMediaHash, getSenderTitle, isMessageLocal,\n} from '../../modules/helpers';\nimport { selectChat, selectSender } from '../../modules/selectors';\nimport buildClassName from '../../util/buildClassName';\nimport { makeTrackId } from '../../util/audioPlayer';\nimport { clearMediaSession } from '../../util/mediaSession';\nimport windowSize from '../../util/windowSize';\nimport useAudioPlayer from '../../hooks/useAudioPlayer';\nimport useLang from '../../hooks/useLang';\nimport useMessageMediaMetadata from '../../hooks/useMessageMediaMetadata';\nimport renderText from '../common/helpers/renderText';\n\nimport RippleEffect from '../ui/RippleEffect';\nimport Button from '../ui/Button';\nimport RangeSlider from '../ui/RangeSlider';\n\nimport './AudioPlayer.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n origin?: AudioOrigin;\n className?: string;\n noUi?: boolean;\n};\n\ntype StateProps = {\n sender?: ApiChat | ApiUser;\n chat?: ApiChat;\n volume: number;\n playbackRate: number;\n isMuted: boolean;\n};\n\nconst FAST_PLAYBACK_RATE = 1.8;\n\nconst AudioPlayer: FC = ({\n message,\n className,\n noUi,\n sender,\n chat,\n volume,\n playbackRate,\n isMuted,\n}) => {\n const {\n setAudioPlayerVolume,\n setAudioPlayerPlaybackRate,\n setAudioPlayerMuted,\n focusMessage,\n closeAudioPlayer,\n } = getDispatch();\n\n const lang = useLang();\n const { audio, voice, video } = getMessageContent(message);\n const isVoice = Boolean(voice || video);\n const senderName = sender ? getSenderTitle(lang, sender) : undefined;\n const mediaData = mediaLoader.getFromMemory(getMessageMediaHash(message, 'inline')!) as (string | undefined);\n const mediaMetadata = useMessageMediaMetadata(message, sender, chat);\n\n const {\n playPause,\n stop,\n isPlaying,\n requestNextTrack,\n requestPreviousTrack,\n isFirst,\n isLast,\n setVolume,\n toggleMuted,\n setPlaybackRate,\n } = useAudioPlayer(\n makeTrackId(message),\n getMediaDuration(message)!,\n isVoice ? 'voice' : 'audio',\n mediaData,\n undefined,\n mediaMetadata,\n undefined,\n true,\n undefined,\n undefined,\n isMessageLocal(message),\n true,\n );\n\n // Prevent refresh by accidentally rotating device when listening to a voice message\n const isVoicePlaying = isVoice && isPlaying;\n useEffect(() => {\n if (!isVoicePlaying) {\n return undefined;\n }\n\n windowSize.disableRefresh();\n\n return () => {\n windowSize.enableRefresh();\n };\n }, [isVoicePlaying]);\n\n const handleClick = useCallback(() => {\n focusMessage({ chatId: message.chatId, messageId: message.id });\n }, [focusMessage, message.chatId, message.id]);\n\n const handleClose = useCallback(() => {\n if (isPlaying) {\n playPause();\n }\n closeAudioPlayer();\n clearMediaSession();\n stop();\n }, [closeAudioPlayer, isPlaying, playPause, stop]);\n\n const handleVolumeChange = useCallback((value: number) => {\n setAudioPlayerVolume({ volume: value / 100 });\n setAudioPlayerMuted({ isMuted: false });\n\n setVolume(value / 100);\n }, [setAudioPlayerMuted, setAudioPlayerVolume, setVolume]);\n\n const handleVolumeClick = useCallback(() => {\n if (IS_TOUCH_ENV && !IS_IOS) return;\n toggleMuted();\n setAudioPlayerMuted({ isMuted: !isMuted });\n }, [isMuted, setAudioPlayerMuted, toggleMuted]);\n\n const handlePlaybackClick = useCallback(() => {\n if (playbackRate === 1) {\n setPlaybackRate(FAST_PLAYBACK_RATE);\n setAudioPlayerPlaybackRate({ playbackRate: FAST_PLAYBACK_RATE });\n } else {\n setPlaybackRate(1);\n setAudioPlayerPlaybackRate({ playbackRate: 1 });\n }\n }, [playbackRate, setAudioPlayerPlaybackRate, setPlaybackRate]);\n\n const volumeIcon = useMemo(() => {\n if (volume === 0 || isMuted) return 'icon-muted';\n if (volume < 0.3) return 'icon-volume-1';\n if (volume < 0.6) return 'icon-volume-2';\n return 'icon-volume-3';\n }, [volume, isMuted]);\n\n if (noUi) {\n return undefined;\n }\n\n return (\n
\n \n \n \n \n \n \n \n \n \n \n\n
\n {audio ? renderAudio(audio) : renderVoice(lang('AttachAudio'), senderName)}\n \n
\n\n \n \n {!IS_IOS && (\n <>\n
\n
\n \n
\n \n )}\n \n\n {isVoice && (\n \n \n \n )}\n\n \n \n \n
\n );\n};\n\nfunction renderAudio(audio: ApiAudio) {\n const { title, performer, fileName } = audio;\n\n return (\n <>\n
{renderText(title || fileName)}
\n {performer && (\n
{renderText(performer)}
\n )}\n \n );\n}\n\nfunction renderVoice(subtitle: string, senderName?: string) {\n return (\n <>\n
{senderName && renderText(senderName)}
\n
{subtitle}
\n \n );\n}\n\nexport default withGlobal(\n (global, { message }): StateProps => {\n const sender = selectSender(global, message);\n const chat = selectChat(global, message.chatId);\n const { volume, playbackRate, isMuted } = global.audioPlayer;\n\n return {\n sender,\n chat,\n volume,\n playbackRate,\n isMuted,\n };\n },\n)(AudioPlayer);\n","import React, {\n FC, memo, useCallback, useEffect, useMemo,\n} from '../../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiChat, ApiGroupCall, ApiUser } from '../../../api/types';\n\nimport { selectChatGroupCall } from '../../../modules/selectors/calls';\nimport buildClassName from '../../../util/buildClassName';\nimport { selectChat } from '../../../modules/selectors';\nimport useLang from '../../../hooks/useLang';\n\nimport Button from '../../ui/Button';\nimport Avatar from '../../common/Avatar';\n\nimport './GroupCallTopPane.scss';\n\ntype OwnProps = {\n chatId: string;\n hasPinnedOffset: boolean;\n};\n\ntype StateProps = {\n groupCall?: ApiGroupCall;\n isActive: boolean;\n usersById: Record;\n chatsById: Record;\n};\n\nconst GroupCallTopPane: FC = ({\n chatId,\n isActive,\n groupCall,\n hasPinnedOffset,\n usersById,\n chatsById,\n}) => {\n const {\n joinGroupCall,\n subscribeToGroupCallUpdates,\n } = getDispatch();\n\n const lang = useLang();\n\n const handleJoinGroupCall = useCallback(() => {\n joinGroupCall({\n chatId,\n });\n }, [joinGroupCall, chatId]);\n\n const participants = groupCall?.participants;\n\n const fetchedParticipants = useMemo(() => {\n if (participants) {\n return Object.values(participants).filter((_, i) => i < 3).map(({ id, isUser }) => {\n if (isUser) {\n if (!usersById[id]) {\n return undefined;\n }\n return { user: usersById[id] };\n } else {\n if (!chatsById[id]) {\n return undefined;\n }\n return { chat: chatsById[id] };\n }\n }).filter(Boolean);\n } else return [];\n }, [chatsById, participants, usersById]);\n\n useEffect(() => {\n if (!groupCall?.id) return undefined;\n if (!isActive && groupCall.isLoaded) return undefined;\n\n subscribeToGroupCallUpdates({\n id: groupCall.id,\n subscribed: true,\n });\n\n return () => {\n subscribeToGroupCallUpdates({\n id: groupCall.id,\n subscribed: false,\n });\n };\n }, [groupCall?.id, groupCall?.isLoaded, isActive, subscribeToGroupCallUpdates]);\n\n if (!groupCall) return undefined;\n\n return (\n \n
\n {lang('VoipGroupVoiceChat')}\n {lang('Participants', groupCall.participantsCount || 0, 'i')}\n
\n
\n {fetchedParticipants.map((p) => {\n if (!p) return undefined;\n if (p.user) {\n return ;\n } else {\n return ;\n }\n })}\n
\n \n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { chatId }) => {\n const chat = selectChat(global, chatId)!;\n const groupCall = selectChatGroupCall(global, chatId);\n return {\n groupCall,\n usersById: global.users.byId,\n chatsById: global.chats.byId,\n activeGroupCallId: global.groupCalls.activeGroupCallId,\n isActive: ((!groupCall ? (chat && chat.isCallNotEmpty && chat.isCallActive)\n : (groupCall.participantsCount > 0 && groupCall.isLoaded)))\n && (global.groupCalls.activeGroupCallId !== groupCall?.id),\n };\n },\n)(GroupCallTopPane));\n","import React, {\n FC, useCallback, useMemo, memo, useEffect, useRef, useState,\n} from '../../lib/teact/teact';\nimport { getDispatch, getGlobal, withGlobal } from '../../lib/teact/teactn';\nimport cycleRestrict from '../../util/cycleRestrict';\n\nimport { MessageListType } from '../../global/types';\nimport {\n ApiMessage,\n ApiChat,\n ApiUser,\n ApiTypingStatus,\n MAIN_THREAD_ID, ApiUpdateConnectionStateType,\n} from '../../api/types';\n\nimport {\n MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN,\n MOBILE_SCREEN_MAX_WIDTH,\n EDITABLE_INPUT_ID,\n MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN,\n SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN,\n SAFE_SCREEN_WIDTH_FOR_CHAT_INFO,\n} from '../../config';\nimport { IS_SINGLE_COLUMN_LAYOUT, IS_TABLET_COLUMN_LAYOUT } from '../../util/environment';\nimport {\n isUserId,\n getMessageKey,\n getChatTitle,\n getSenderTitle,\n} from '../../modules/helpers';\nimport {\n selectChat,\n selectChatMessage,\n selectAllowedMessageActions,\n selectIsRightColumnShown,\n selectThreadTopMessageId,\n selectThreadInfo,\n selectChatMessages,\n selectPinnedIds,\n selectIsChatWithSelf,\n selectForwardedSender,\n selectScheduledIds,\n selectIsInSelectMode,\n selectIsChatWithBot,\n selectCountNotMutedUnread,\n} from '../../modules/selectors';\nimport useEnsureMessage from '../../hooks/useEnsureMessage';\nimport useWindowSize from '../../hooks/useWindowSize';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useCurrentOrPrev from '../../hooks/useCurrentOrPrev';\nimport { formatIntegerCompact } from '../../util/textFormat';\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\nimport useBrowserOnline from '../../hooks/useBrowserOnline';\n\nimport PrivateChatInfo from '../common/PrivateChatInfo';\nimport GroupChatInfo from '../common/GroupChatInfo';\nimport Transition from '../ui/Transition';\nimport Button from '../ui/Button';\nimport HeaderActions from './HeaderActions';\nimport HeaderPinnedMessage from './HeaderPinnedMessage';\nimport AudioPlayer from './AudioPlayer';\nimport GroupCallTopPane from '../calls/group/GroupCallTopPane';\n\nimport './MiddleHeader.scss';\n\nconst ANIMATION_DURATION = 350;\nconst BACK_BUTTON_INACTIVE_TIME = 450;\n\ntype OwnProps = {\n chatId: string;\n threadId: number;\n messageListType: MessageListType;\n isReady?: boolean;\n};\n\ntype StateProps = {\n chat?: ApiChat;\n pinnedMessageIds?: number[] | number;\n messagesById?: Record;\n canUnpin?: boolean;\n topMessageSender?: ApiChat | ApiUser;\n typingStatus?: ApiTypingStatus;\n isSelectModeActive?: boolean;\n isLeftColumnShown?: boolean;\n isRightColumnShown?: boolean;\n audioMessage?: ApiMessage;\n chatsById?: Record;\n messagesCount?: number;\n isChatWithSelf?: boolean;\n isChatWithBot?: boolean;\n lastSyncTime?: number;\n shouldSkipHistoryAnimations?: boolean;\n currentTransitionKey: number;\n connectionState?: ApiUpdateConnectionStateType;\n};\n\nconst MiddleHeader: FC = ({\n chatId,\n threadId,\n messageListType,\n isReady,\n pinnedMessageIds,\n messagesById,\n canUnpin,\n topMessageSender,\n typingStatus,\n isSelectModeActive,\n isLeftColumnShown,\n isRightColumnShown,\n audioMessage,\n chat,\n chatsById,\n messagesCount,\n isChatWithSelf,\n isChatWithBot,\n lastSyncTime,\n shouldSkipHistoryAnimations,\n currentTransitionKey,\n connectionState,\n}) => {\n const {\n openChatWithInfo,\n pinMessage,\n focusMessage,\n openChat,\n openPreviousChat,\n loadPinnedMessages,\n toggleLeftColumn,\n exitMessageSelectMode,\n } = getDispatch();\n\n const lang = useLang();\n const isBackButtonActive = useRef(true);\n\n const [pinnedMessageIndex, setPinnedMessageIndex] = useState(0);\n const pinnedMessageId = Array.isArray(pinnedMessageIds) ? pinnedMessageIds[pinnedMessageIndex] : pinnedMessageIds;\n const pinnedMessage = messagesById && pinnedMessageId ? messagesById[pinnedMessageId] : undefined;\n const pinnedMessagesCount = Array.isArray(pinnedMessageIds)\n ? pinnedMessageIds.length : (pinnedMessageIds ? 1 : undefined);\n const chatTitleLength = chat && getChatTitle(lang, chat).length;\n const topMessageTitle = topMessageSender ? getSenderTitle(lang, topMessageSender) : undefined;\n\n useEffect(() => {\n if (threadId === MAIN_THREAD_ID && lastSyncTime && isReady) {\n loadPinnedMessages({ chatId });\n }\n }, [chatId, loadPinnedMessages, lastSyncTime, threadId, isReady]);\n\n // Reset pinned index when switching chats and pinning/unpinning\n useEffect(() => {\n setPinnedMessageIndex(0);\n }, [pinnedMessageIds]);\n\n useEnsureMessage(chatId, pinnedMessageId, pinnedMessage);\n\n const { width: windowWidth } = useWindowSize();\n\n const isLeftColumnHideable = windowWidth <= MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN;\n const shouldShowCloseButton = IS_TABLET_COLUMN_LAYOUT && isLeftColumnShown;\n\n // eslint-disable-next-line no-null/no-null\n const componentRef = useRef(null);\n const shouldAnimateTools = useRef(true);\n\n const handleHeaderClick = useCallback(() => {\n openChatWithInfo({ id: chatId });\n }, [openChatWithInfo, chatId]);\n\n const handleUnpinMessage = useCallback((messageId: number) => {\n pinMessage({ chatId, messageId, isUnpin: true });\n }, [pinMessage, chatId]);\n\n const handlePinnedMessageClick = useCallback((): void => {\n if (pinnedMessage) {\n focusMessage({ chatId: pinnedMessage.chatId, threadId, messageId: pinnedMessage.id });\n\n const newIndex = cycleRestrict(pinnedMessagesCount || 1, pinnedMessageIndex + 1);\n setPinnedMessageIndex(newIndex);\n }\n }, [pinnedMessage, focusMessage, threadId, pinnedMessagesCount, pinnedMessageIndex]);\n\n const handleAllPinnedClick = useCallback(() => {\n openChat({ id: chatId, threadId: MAIN_THREAD_ID, type: 'pinned' });\n }, [openChat, chatId]);\n\n const setBackButtonActive = useCallback(() => {\n setTimeout(() => {\n isBackButtonActive.current = true;\n }, BACK_BUTTON_INACTIVE_TIME);\n }, []);\n\n const handleBackClick = useCallback((e: React.MouseEvent) => {\n if (!isBackButtonActive.current) return;\n\n // Workaround for missing UI when quickly clicking the Back button\n isBackButtonActive.current = false;\n if (IS_SINGLE_COLUMN_LAYOUT) {\n const messageInput = document.getElementById(EDITABLE_INPUT_ID);\n if (messageInput) {\n messageInput.blur();\n }\n }\n\n if (isSelectModeActive) {\n exitMessageSelectMode();\n setBackButtonActive();\n return;\n }\n\n if (threadId === MAIN_THREAD_ID && messageListType === 'thread' && currentTransitionKey === 0) {\n if (IS_SINGLE_COLUMN_LAYOUT || shouldShowCloseButton) {\n e.stopPropagation(); // Stop propagation to prevent chat re-opening on tablets\n openChat({ id: undefined });\n } else {\n toggleLeftColumn();\n }\n\n setBackButtonActive();\n\n return;\n }\n\n openPreviousChat();\n setBackButtonActive();\n }, [\n threadId, messageListType, currentTransitionKey, isSelectModeActive, openPreviousChat, shouldShowCloseButton,\n openChat, toggleLeftColumn, exitMessageSelectMode, setBackButtonActive,\n ]);\n\n const unreadCount = useMemo(() => {\n if (!isLeftColumnHideable || !chatsById) {\n return undefined;\n }\n\n return selectCountNotMutedUnread(getGlobal()) || undefined;\n }, [isLeftColumnHideable, chatsById]);\n\n const canToolsCollideWithChatInfo = (\n windowWidth >= MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN\n && windowWidth < SAFE_SCREEN_WIDTH_FOR_CHAT_INFO\n ) || (\n windowWidth > MOBILE_SCREEN_MAX_WIDTH\n && windowWidth < MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN\n && (!chatTitleLength || chatTitleLength > 30)\n );\n const shouldUseStackedToolsClass = canToolsCollideWithChatInfo || (\n windowWidth > MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN\n && windowWidth < SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN\n );\n\n const {\n shouldRender: shouldRenderAudioPlayer,\n transitionClassNames: audioPlayerClassNames,\n } = useShowTransition(Boolean(audioMessage));\n\n const renderingAudioMessage = useCurrentOrPrev(audioMessage);\n\n const {\n shouldRender: shouldRenderPinnedMessage,\n transitionClassNames: pinnedMessageClassNames,\n } = useShowTransition(Boolean(pinnedMessage));\n\n const renderingPinnedMessage = useCurrentOrPrev(pinnedMessage, true);\n const renderingPinnedMessagesCount = useCurrentOrPrev(pinnedMessagesCount, true);\n const renderingCanUnpin = useCurrentOrPrev(canUnpin, true);\n const renderingPinnedMessageTitle = useCurrentOrPrev(topMessageTitle);\n\n const canRevealTools = (shouldRenderPinnedMessage && renderingPinnedMessage)\n || (shouldRenderAudioPlayer && renderingAudioMessage);\n\n // Logic for transition to and from custom display of AudioPlayer/PinnedMessage on smaller screens\n useEffect(() => {\n const componentEl = componentRef.current;\n if (!componentEl) {\n return;\n }\n\n if (!shouldUseStackedToolsClass || !canRevealTools) {\n componentEl.classList.remove('tools-stacked', 'animated');\n shouldAnimateTools.current = true;\n return;\n }\n\n if (isRightColumnShown || canToolsCollideWithChatInfo) {\n if (shouldAnimateTools.current) {\n componentEl.classList.add('tools-stacked', 'animated');\n shouldAnimateTools.current = false;\n }\n\n // Remove animation class to prevent it messing up the show transitions\n setTimeout(() => {\n componentEl.classList.remove('animated');\n }, ANIMATION_DURATION);\n } else {\n componentEl.classList.remove('tools-stacked');\n shouldAnimateTools.current = true;\n }\n }, [shouldUseStackedToolsClass, canRevealTools, canToolsCollideWithChatInfo, isRightColumnShown]);\n\n const isBrowserOnline = useBrowserOnline();\n const isConnecting = (!isBrowserOnline || connectionState === 'connectionStateConnecting')\n && (IS_SINGLE_COLUMN_LAYOUT || (IS_TABLET_COLUMN_LAYOUT && !shouldShowCloseButton));\n\n function renderInfo() {\n if (isConnecting) {\n return (\n <>\n {renderBackButton()}\n

\n {lang('WaitingForNetwork')}\n

\n \n );\n }\n return (\n messageListType === 'thread' && threadId === MAIN_THREAD_ID ? (\n renderMainThreadInfo()\n ) : messageListType === 'thread' ? (\n <>\n {renderBackButton()}\n

\n {lang('CommentsCount', messagesCount, 'i')}\n

\n \n ) : messageListType === 'pinned' ? (\n <>\n {renderBackButton()}\n

\n {lang('PinnedMessagesCount', messagesCount, 'i')}\n

\n \n ) : messageListType === 'scheduled' ? (\n <>\n {renderBackButton()}\n

\n {isChatWithSelf ? lang('Reminders') : lang('messages', messagesCount, 'i')}\n

\n \n ) : undefined\n );\n }\n\n function renderMainThreadInfo() {\n return (\n <>\n {(isLeftColumnHideable || currentTransitionKey > 0) && renderBackButton(shouldShowCloseButton, true)}\n
\n {isUserId(chatId) ? (\n \n ) : (\n \n )}\n
\n \n );\n }\n\n function renderBackButton(asClose = false, withUnreadCount = false) {\n return (\n
\n \n
\n \n {withUnreadCount && unreadCount && (\n
\n {formatIntegerCompact(unreadCount)}\n
\n )}\n
\n );\n }\n\n const isAudioPlayerRendered = Boolean(shouldRenderAudioPlayer && renderingAudioMessage);\n\n return (\n
\n \n {renderInfo}\n \n\n \n\n {shouldRenderPinnedMessage && renderingPinnedMessage && (\n \n )}\n
\n {isAudioPlayerRendered && (\n \n )}\n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { chatId, threadId, messageListType }): StateProps => {\n const { isLeftColumnShown, lastSyncTime, shouldSkipHistoryAnimations } = global;\n const { byId: chatsById } = global.chats;\n const chat = selectChat(global, chatId);\n\n const { typingStatus } = chat || {};\n\n const { chatId: audioChatId, messageId: audioMessageId } = global.audioPlayer;\n const audioMessage = audioChatId && audioMessageId\n ? selectChatMessage(global, audioChatId, audioMessageId)\n : undefined;\n\n let messagesCount: number | undefined;\n if (messageListType === 'pinned') {\n const pinnedIds = selectPinnedIds(global, chatId);\n messagesCount = pinnedIds?.length;\n } else if (messageListType === 'scheduled') {\n const scheduledIds = selectScheduledIds(global, chatId);\n messagesCount = scheduledIds?.length;\n } else if (messageListType === 'thread' && threadId !== MAIN_THREAD_ID) {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n messagesCount = threadInfo?.messagesCount || 0;\n }\n\n const state: StateProps = {\n typingStatus,\n isLeftColumnShown,\n isRightColumnShown: selectIsRightColumnShown(global),\n isSelectModeActive: selectIsInSelectMode(global),\n audioMessage,\n chat,\n chatsById,\n messagesCount,\n isChatWithSelf: selectIsChatWithSelf(global, chatId),\n isChatWithBot: chat && selectIsChatWithBot(global, chat),\n lastSyncTime,\n shouldSkipHistoryAnimations,\n currentTransitionKey: Math.max(0, global.messages.messageLists.length - 1),\n connectionState: global.connectionState,\n };\n\n const messagesById = selectChatMessages(global, chatId);\n if (messageListType !== 'thread' || !messagesById) {\n return state;\n }\n\n Object.assign(state, { messagesById });\n\n if (threadId !== MAIN_THREAD_ID) {\n const pinnedMessageId = selectThreadTopMessageId(global, chatId, threadId);\n const message = pinnedMessageId ? selectChatMessage(global, chatId, pinnedMessageId) : undefined;\n const topMessageSender = message ? selectForwardedSender(global, message) : undefined;\n\n return {\n ...state,\n pinnedMessageIds: pinnedMessageId,\n canUnpin: false,\n topMessageSender,\n };\n }\n\n const pinnedMessageIds = selectPinnedIds(global, chatId);\n if (pinnedMessageIds?.length) {\n const firstPinnedMessage = messagesById[pinnedMessageIds[0]];\n const {\n canUnpin,\n } = (firstPinnedMessage && selectAllowedMessageActions(global, firstPinnedMessage, threadId)) || {};\n\n return {\n ...state,\n pinnedMessageIds,\n canUnpin,\n };\n }\n\n return state;\n },\n)(MiddleHeader));\n","import { ApiMessage } from '../../../api/types';\nimport { IAlbum } from '../../../types';\n\nimport { getDayStart } from '../../../util/dateFormat';\nimport { isActionMessage } from '../../../modules/helpers';\n\ntype SenderGroup = (ApiMessage | IAlbum)[];\n\nconst GROUP_INTERVAL_SECONDS = 600; // 10 minutes\n\nexport type MessageDateGroup = {\n originalDate: number;\n datetime: number;\n senderGroups: SenderGroup[];\n};\n\nexport function isAlbum(messageOrAlbum: ApiMessage | IAlbum): messageOrAlbum is IAlbum {\n return 'albumId' in messageOrAlbum;\n}\n\nexport function groupMessages(messages: ApiMessage[], firstUnreadId?: number) {\n let currentSenderGroup: SenderGroup = [];\n let currentDateGroup = {\n originalDate: messages[0].date,\n datetime: Number(getDayStart(messages[0].date * 1000)),\n senderGroups: [currentSenderGroup],\n };\n let currentAlbum: IAlbum | undefined;\n\n const dateGroups: MessageDateGroup[] = [currentDateGroup];\n\n messages.forEach((message, index) => {\n if (message.isInAlbum) {\n if (!currentAlbum) {\n currentAlbum = {\n albumId: message.groupedId!,\n messages: [message],\n mainMessage: message,\n };\n } else {\n currentAlbum.messages.push(message);\n if (message.content.text) {\n currentAlbum.mainMessage = message;\n }\n }\n } else {\n currentSenderGroup.push(message);\n }\n\n const nextMessage = messages[index + 1];\n\n if (\n currentAlbum\n && (!nextMessage || !nextMessage.groupedId || nextMessage.groupedId !== currentAlbum.albumId)\n ) {\n currentSenderGroup.push(currentAlbum);\n currentAlbum = undefined;\n }\n if (nextMessage) {\n const nextMessageDayStartsAt = Number(getDayStart(nextMessage.date * 1000));\n if (currentDateGroup.datetime !== nextMessageDayStartsAt) {\n currentDateGroup = {\n originalDate: nextMessage.date,\n datetime: nextMessageDayStartsAt,\n senderGroups: [],\n };\n dateGroups.push(currentDateGroup);\n\n currentSenderGroup = [];\n currentDateGroup.senderGroups.push(currentSenderGroup);\n } else if (\n nextMessage.id === firstUnreadId\n || message.senderId !== nextMessage.senderId\n || message.isOutgoing !== nextMessage.isOutgoing\n || isActionMessage(message)\n || isActionMessage(nextMessage)\n || (\n message.forwardInfo && nextMessage.forwardInfo\n && (\n message.forwardInfo.senderUserId !== nextMessage.forwardInfo.senderUserId\n || message.forwardInfo.fromChatId !== nextMessage.forwardInfo.fromChatId\n || message.forwardInfo.hiddenUserName !== nextMessage.forwardInfo.hiddenUserName\n )\n )\n || message.inlineButtons\n || nextMessage.inlineButtons\n || (nextMessage.date - message.date) > GROUP_INTERVAL_SECONDS\n ) {\n currentSenderGroup = [];\n currentDateGroup.senderGroups.push(currentSenderGroup);\n }\n }\n });\n\n return dateGroups;\n}\n","import { RefObject } from 'react';\nimport { getDispatch } from '../../../lib/teact/teactn';\n\nimport { MessageListType } from '../../../global/types';\n\nimport { IS_ANDROID, IS_SINGLE_COLUMN_LAYOUT } from '../../../util/environment';\nimport { useIntersectionObserver } from '../../../hooks/useIntersectionObserver';\nimport useBackgroundMode from '../../../hooks/useBackgroundMode';\n\nconst INTERSECTION_THROTTLE_FOR_MEDIA = IS_ANDROID ? 1000 : 350;\nconst INTERSECTION_MARGIN_FOR_MEDIA = IS_SINGLE_COLUMN_LAYOUT ? 300 : 500;\nconst INTERSECTION_THROTTLE_FOR_READING = 150;\n\nexport default function useMessageObservers(\n type: MessageListType,\n containerRef: RefObject,\n memoFirstUnreadIdRef: { current: number | undefined },\n) {\n const { markMessageListRead, markMessagesRead } = getDispatch();\n\n const {\n observe: observeIntersectionForMedia,\n } = useIntersectionObserver({\n rootRef: containerRef,\n throttleMs: INTERSECTION_THROTTLE_FOR_MEDIA,\n margin: INTERSECTION_MARGIN_FOR_MEDIA,\n });\n\n const {\n observe: observeIntersectionForReading, freeze: freezeForReading, unfreeze: unfreezeForReading,\n } = useIntersectionObserver({\n rootRef: containerRef,\n throttleMs: INTERSECTION_THROTTLE_FOR_READING,\n }, (entries) => {\n if (type !== 'thread') {\n return;\n }\n\n let maxId = 0;\n const mentionIds: number[] = [];\n\n entries.forEach((entry) => {\n const { isIntersecting, target } = entry;\n\n if (!isIntersecting) {\n return;\n }\n\n const { dataset } = target as HTMLDivElement;\n\n const messageId = Number(dataset.lastMessageId || dataset.messageId);\n if (messageId > maxId) {\n maxId = messageId;\n }\n\n if (dataset.hasUnreadMention) {\n mentionIds.push(messageId);\n }\n });\n\n if (memoFirstUnreadIdRef.current && maxId >= memoFirstUnreadIdRef.current) {\n markMessageListRead({ maxId });\n }\n\n if (mentionIds.length) {\n markMessagesRead({ messageIds: mentionIds });\n }\n });\n\n useBackgroundMode(freezeForReading, unfreezeForReading);\n\n const { observe: observeIntersectionForAnimatedStickers } = useIntersectionObserver({\n rootRef: containerRef,\n throttleMs: INTERSECTION_THROTTLE_FOR_MEDIA,\n });\n\n return {\n observeIntersectionForMedia,\n observeIntersectionForReading,\n observeIntersectionForAnimatedStickers,\n };\n}\n","import { ApiMessage } from '../../../../api/types';\n\nimport { getMessageContent } from '../../../../modules/helpers';\n\nexport function isEmojiOnlyMessage(customShape?: boolean | number) {\n return typeof customShape === 'number';\n}\n\nexport function buildContentClassName(\n message: ApiMessage,\n {\n hasReply,\n customShape,\n isLastInGroup,\n asForwarded,\n hasThread,\n forceSenderName,\n hasComments,\n hasActionButton,\n }: {\n hasReply?: boolean;\n customShape?: boolean | number;\n isLastInGroup?: boolean;\n asForwarded?: boolean;\n hasThread?: boolean;\n forceSenderName?: boolean;\n hasComments?: boolean;\n hasActionButton?: boolean;\n } = {},\n) {\n const {\n text, photo, video, audio, voice, document, poll, webPage, contact,\n } = getMessageContent(message);\n\n const classNames = ['message-content'];\n const isMedia = photo || video;\n const isMediaWithNoText = isMedia && !text;\n const isViaBot = Boolean(message.viaBotId);\n\n if (isEmojiOnlyMessage(customShape)) {\n classNames.push(`emoji-only emoji-only-${customShape}`);\n } else if (text) {\n classNames.push('text');\n }\n\n if (hasActionButton) {\n classNames.push('has-action-button');\n }\n\n if (customShape) {\n classNames.push('custom-shape');\n if (video?.isRound) {\n classNames.push('round');\n }\n\n if (hasComments) {\n classNames.push('has-comments');\n }\n }\n if (photo || video) {\n classNames.push('media');\n } else if (audio) {\n classNames.push('audio');\n } else if (voice) {\n classNames.push('voice');\n } else if (document) {\n classNames.push('document');\n } else if (contact) {\n classNames.push('contact');\n } else if (poll) {\n classNames.push('poll');\n } else if (webPage) {\n classNames.push('web-page');\n\n if (webPage.photo || webPage.video) {\n classNames.push('media');\n }\n }\n\n if (asForwarded) {\n classNames.push('is-forwarded');\n }\n\n if (hasReply) {\n classNames.push('is-reply');\n }\n\n if (hasThread) {\n classNames.push('has-replies');\n }\n\n if (isViaBot) {\n classNames.push('is-via-bot');\n }\n\n if (forceSenderName) {\n classNames.push('force-sender-name');\n }\n\n if (!customShape) {\n classNames.push('has-shadow');\n\n if (isMedia && hasComments) {\n classNames.push('has-background');\n }\n\n if (hasReply || asForwarded || !isMediaWithNoText || isViaBot || forceSenderName) {\n classNames.push('has-solid-background');\n }\n\n if (isLastInGroup && (photo || !isMediaWithNoText)) {\n classNames.push('has-appendix');\n }\n }\n\n return classNames.join(' ');\n}\n","import { ApiMessage } from '../../../../api/types';\nimport { calculateInlineImageDimensions, calculateVideoDimensions } from '../../../common/helpers/mediaDimensions';\nimport {\n getMessageText,\n getMessagePhoto,\n getMessageWebPagePhoto,\n isForwardedMessage,\n isOwnMessage,\n getMessageVideo,\n} from '../../../../modules/helpers';\n\nconst MIN_MEDIA_WIDTH = 100;\nconst MIN_MEDIA_WIDTH_WITH_COMMENTS = 238;\nconst MIN_MEDIA_WIDTH_WITH_TEXT = 175;\nconst MIN_MEDIA_WIDTH_WITH_TEXT_AND_COMMENTS = 238;\nconst MIN_MEDIA_HEIGHT = 90;\nconst SMALL_IMAGE_THRESHOLD = 12;\n\nexport function getMinMediaWidth(hasText?: boolean, hasCommentButton?: boolean) {\n return hasText\n ? (hasCommentButton ? MIN_MEDIA_WIDTH_WITH_TEXT_AND_COMMENTS : MIN_MEDIA_WIDTH_WITH_TEXT)\n : (hasCommentButton ? MIN_MEDIA_WIDTH_WITH_COMMENTS : MIN_MEDIA_WIDTH);\n}\n\nexport function calculateMediaDimensions(message: ApiMessage, noAvatars?: boolean) {\n const isOwn = isOwnMessage(message);\n const isForwarded = isForwardedMessage(message);\n const photo = getMessagePhoto(message) || getMessageWebPagePhoto(message);\n const video = getMessageVideo(message);\n\n const isWebPagePhoto = Boolean(getMessageWebPagePhoto(message));\n const { width, height } = photo\n ? calculateInlineImageDimensions(photo, isOwn, isForwarded, isWebPagePhoto, noAvatars)\n : calculateVideoDimensions(video!, isOwn, isForwarded, noAvatars);\n\n const hasText = Boolean(getMessageText(message));\n const minMediaWidth = getMinMediaWidth(hasText);\n\n let stretchFactor = 1;\n if (width < minMediaWidth && minMediaWidth - width < SMALL_IMAGE_THRESHOLD) {\n stretchFactor = minMediaWidth / width;\n }\n if (height * stretchFactor < MIN_MEDIA_HEIGHT && MIN_MEDIA_HEIGHT - height * stretchFactor < SMALL_IMAGE_THRESHOLD) {\n stretchFactor = MIN_MEDIA_HEIGHT / height;\n }\n\n const finalWidth = Math.round(width * stretchFactor);\n const finalHeight = Math.round(height * stretchFactor);\n\n return {\n width: finalWidth,\n height: finalHeight,\n isSmall: finalWidth < minMediaWidth || finalHeight < MIN_MEDIA_HEIGHT,\n };\n}\n","/* eslint-disable no-bitwise */\n// Based on\n// https://github.com/telegramdesktop/tdesktop/blob/dev/Telegram/SourceFiles/ui/grouped_layout.cpp\n// https://github.com/overtake/TelegramSwift/blob/master/Telegram-Mac/GroupedLayout.swift#L83\n\nimport { IAlbum } from '../../../../types';\nimport { ApiMessage, ApiDimensions } from '../../../../api/types';\n\nimport { getAvailableWidth, REM } from '../../../common/helpers/mediaDimensions';\nimport { calculateMediaDimensions } from './mediaDimensions';\n\nexport const AlbumRectPart = {\n None: 0,\n Top: 1,\n Right: 2,\n Bottom: 4,\n Left: 8,\n};\n\ntype IAttempt = {\n lineCounts: number[];\n heights: number[];\n};\nexport type IMediaDimensions = {\n width: number;\n height: number;\n x: number;\n y: number;\n};\ntype IMediaLayout = {\n dimensions: IMediaDimensions;\n sides: number;\n};\ntype ILayoutParams = {\n ratios: number[];\n proportions: string;\n averageRatio: number;\n maxWidth: number;\n minWidth: number;\n maxHeight: number;\n spacing: number;\n};\nexport type IAlbumLayout = {\n layout: IMediaLayout[];\n containerStyle: ApiDimensions;\n};\n\nfunction getRatios(messages: ApiMessage[]) {\n return messages.map(\n (message) => {\n const dimensions = calculateMediaDimensions(message) as ApiDimensions;\n\n return dimensions.width / dimensions.height;\n },\n );\n}\n\nfunction getProportions(ratios: number[]) {\n return ratios.map((ratio) => (ratio > 1.2 ? 'w' : (ratio < 0.8 ? 'n' : 'q'))).join('');\n}\n\nfunction getAverageRatio(ratios: number[]) {\n return ratios.reduce((result, ratio) => ratio + result, 1) / ratios.length;\n}\n\nfunction accumulate(list: number[], initValue: number) {\n return list.reduce((accumulator, item) => accumulator + item, initValue);\n}\n\nfunction clamp(num: number, low: number, high: number) {\n return num < low ? low : (num > high ? high : num);\n}\n\nfunction cropRatios(ratios: number[], averageRatio: number) {\n return ratios.map((ratio) => (averageRatio > 1.1 ? clamp(ratio, 1, 2.75) : clamp(ratio, 0.6667, 1)));\n}\n\nfunction calculateContainerSize(layout: IMediaLayout[]) {\n const styles: ApiDimensions = { width: 0, height: 0 };\n layout.forEach(({\n dimensions,\n sides,\n }) => {\n if (sides & AlbumRectPart.Right) {\n styles.width = dimensions.width + dimensions.x;\n }\n if (sides & AlbumRectPart.Bottom) {\n styles.height = dimensions.height + dimensions.y;\n }\n });\n\n return styles;\n}\n\nexport function calculateAlbumLayout(\n isOwn: boolean,\n isForwarded: boolean,\n noAvatars: boolean,\n album: IAlbum,\n): IAlbumLayout {\n const spacing = 2;\n const ratios = getRatios(album.messages);\n const proportions = getProportions(ratios);\n const averageRatio = getAverageRatio(ratios);\n const albumCount = ratios.length;\n const forceCalc = ratios.some((ratio) => ratio > 2);\n const maxWidth = getAvailableWidth(isOwn, isForwarded, false, noAvatars) - (isForwarded ? 2.5 : 0) * REM;\n const maxHeight = maxWidth;\n\n let layout;\n\n const params = {\n ratios,\n proportions,\n averageRatio,\n maxWidth,\n minWidth: 100,\n maxHeight,\n spacing,\n };\n\n if (albumCount >= 5 || forceCalc) {\n layout = layoutWithComplexLayouter(params);\n } else if (albumCount === 2) {\n layout = layoutTwo(params);\n } else if (albumCount === 3) {\n layout = layoutThree(params);\n } else {\n layout = layoutFour(params);\n }\n\n return {\n layout,\n containerStyle: calculateContainerSize(layout),\n };\n}\n\nfunction layoutWithComplexLayouter({\n ratios: originalRatios,\n averageRatio,\n maxWidth,\n minWidth,\n spacing,\n maxHeight = (4 * maxWidth) / 3,\n}: ILayoutParams) {\n const ratios = cropRatios(originalRatios, averageRatio);\n const count = originalRatios.length;\n const result = new Array(count);\n const attempts: IAttempt[] = [];\n\n const multiHeight = (offset: number, attemptCount: number) => {\n const attemptRatios = ratios.slice(offset, offset + attemptCount);\n const sum = accumulate(attemptRatios, 0);\n\n return (maxWidth - (attemptCount - 1) * spacing) / sum;\n };\n\n const pushAttempt = (lineCounts: number[]) => {\n const heights: number[] = [];\n let offset = 0;\n lineCounts.forEach((currentCount) => {\n heights.push(multiHeight(offset, currentCount));\n offset += currentCount;\n });\n\n attempts.push({\n lineCounts,\n heights,\n });\n };\n\n for (let first = 1; first !== count; ++first) {\n const second = count - first;\n if (first <= 3 && second <= 3) {\n pushAttempt([first, second]);\n }\n }\n\n for (let first = 1; first !== count - 1; ++first) {\n for (let second = 1; second !== count - first; ++second) {\n const third = count - first - second;\n if (first <= 3 && second <= (averageRatio < 0.85 ? 4 : 3) && third <= 3) {\n pushAttempt([first, second, third]);\n }\n }\n }\n\n for (let first = 1; first !== count - 1; ++first) {\n for (let second = 1; second !== count - first; ++second) {\n for (let third = 1; third !== count - first - second; ++third) {\n const fourth = count - first - second - third;\n if (first <= 3 && second <= 3 && third <= 3 && fourth <= 4) {\n pushAttempt([first, second, third, fourth]);\n }\n }\n }\n }\n\n let optimalAttempt: IAttempt | undefined;\n let optimalDiff = 0;\n for (let i = 0; i < attempts.length; i++) {\n const {\n heights,\n lineCounts,\n } = attempts[i];\n const lineCount = lineCounts.length;\n const totalHeight = accumulate(heights, 0) + spacing * (lineCount - 1);\n const minLineHeight = Math.min(...heights);\n const bad1 = minLineHeight < minWidth ? 1.5 : 1;\n const bad2 = (() => {\n for (let line = 1; line !== lineCount; ++line) {\n if (lineCounts[line - 1] > lineCounts[line]) {\n return 1.5;\n }\n }\n\n return 1;\n })();\n const diff = Math.abs(totalHeight - maxHeight) * bad1 * bad2;\n\n if (!optimalAttempt || diff < optimalDiff) {\n optimalAttempt = attempts[i];\n optimalDiff = diff;\n }\n }\n\n const optimalCounts = optimalAttempt!.lineCounts;\n const optimalHeights = optimalAttempt!.heights;\n const rowCount = optimalCounts.length;\n let index = 0;\n let y = 0;\n for (let row = 0; row !== rowCount; ++row) {\n const colCount = optimalCounts[row];\n const lineHeight = optimalHeights[row];\n const height = Math.round(lineHeight);\n let x = 0;\n\n for (let col = 0; col !== colCount; ++col) {\n const sides = AlbumRectPart.None\n | (row === 0 ? AlbumRectPart.Top : AlbumRectPart.None)\n | (row === rowCount - 1 ? AlbumRectPart.Bottom : AlbumRectPart.None)\n | (col === 0 ? AlbumRectPart.Left : AlbumRectPart.None)\n | (col === colCount - 1 ? AlbumRectPart.Right : AlbumRectPart.None);\n const ratio = ratios[index];\n const width = col === colCount - 1 ? maxWidth - x : Math.round(ratio * lineHeight);\n result[index] = {\n dimensions: {\n x,\n y,\n width,\n height,\n },\n sides,\n };\n x += width + spacing;\n ++index;\n }\n y += height + spacing;\n }\n\n return result;\n}\n\nfunction layoutTwo(params: ILayoutParams) {\n const {\n ratios,\n proportions,\n averageRatio,\n } = params;\n return proportions === 'ww' && averageRatio > 1.4 && ratios[1] - ratios[0] < 0.2\n ? layoutTwoTopBottom(params)\n : proportions === 'ww' || proportions === 'qq'\n ? layoutTwoLeftRightEqual(params)\n : layoutTwoLeftRight(params);\n}\n\nfunction layoutTwoTopBottom(params: ILayoutParams) {\n const {\n ratios,\n maxWidth,\n spacing,\n maxHeight,\n } = params;\n const height = Math.round(Math.min(maxWidth / ratios[0], Math.min(maxWidth / ratios[1], (maxHeight - spacing) / 2)));\n\n return [{\n dimensions: {\n x: 0,\n y: 0,\n width: maxWidth,\n height,\n },\n sides: AlbumRectPart.Left | AlbumRectPart.Top | AlbumRectPart.Right,\n }, {\n dimensions: {\n x: 0,\n y: height + spacing,\n width: maxWidth,\n height,\n },\n sides: AlbumRectPart.Left | AlbumRectPart.Bottom | AlbumRectPart.Right,\n }];\n}\n\nfunction layoutTwoLeftRightEqual(params: ILayoutParams) {\n const {\n ratios,\n maxWidth,\n spacing,\n maxHeight,\n } = params;\n const width = (maxWidth - spacing) / 2;\n const height = Math.round(Math.min(width / ratios[0], Math.min(width / ratios[1], maxHeight)));\n return [{\n dimensions: {\n x: 0,\n y: 0,\n width,\n height,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Left | AlbumRectPart.Bottom,\n }, {\n dimensions: {\n x: width + spacing,\n y: 0,\n width,\n height,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Right | AlbumRectPart.Bottom,\n }];\n}\n\nfunction layoutTwoLeftRight(params: ILayoutParams) {\n const {\n ratios,\n minWidth,\n maxWidth,\n spacing,\n maxHeight,\n } = params;\n const minimalWidth = Math.round(1.5 * minWidth);\n const secondWidth = Math.min(\n Math.round(\n Math.max(\n 0.4 * (maxWidth - spacing),\n (maxWidth - spacing) / ratios[0] / (1 / ratios[0] + 1 / ratios[1]),\n ),\n ),\n maxWidth - spacing - minimalWidth,\n );\n const firstWidth = maxWidth - secondWidth - spacing;\n const height = Math.min(maxHeight, Math.round(Math.min(firstWidth / ratios[0], secondWidth / ratios[1])));\n\n return [{\n dimensions: {\n x: 0,\n y: 0,\n width: firstWidth,\n height,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Left | AlbumRectPart.Bottom,\n }, {\n dimensions: {\n x: firstWidth + spacing,\n y: 0,\n width: secondWidth,\n height,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Right | AlbumRectPart.Bottom,\n }];\n}\n\nfunction layoutThree(params: ILayoutParams) {\n const { proportions } = params;\n\n return proportions[0] === 'n'\n ? layoutThreeLeftAndOther(params)\n : layoutThreeTopAndOther(params);\n}\n\nfunction layoutThreeLeftAndOther(params: ILayoutParams) {\n const {\n maxHeight,\n spacing,\n ratios,\n maxWidth,\n minWidth,\n } = params;\n const firstHeight = maxHeight;\n const thirdHeight = Math.round(\n Math.min(\n (maxHeight - spacing) / 2,\n (ratios[1] * (maxWidth - spacing)) / (ratios[2] + ratios[1]),\n ),\n );\n const secondHeight = firstHeight - thirdHeight - spacing;\n const rightWidth = Math.max(\n minWidth,\n Math.round(\n Math.min(\n (maxWidth - spacing) / 2,\n Math.min(\n thirdHeight * ratios[2],\n secondHeight * ratios[1],\n ),\n ),\n ),\n );\n const leftWidth = Math.min(Math.round(firstHeight * ratios[0]), maxWidth - spacing - rightWidth);\n\n return [{\n dimensions: {\n x: 0,\n y: 0,\n width: leftWidth,\n height: firstHeight,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Left | AlbumRectPart.Bottom,\n }, {\n dimensions: {\n x: leftWidth + spacing,\n y: 0,\n width: rightWidth,\n height: secondHeight,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Right,\n }, {\n dimensions: {\n x: leftWidth + spacing,\n y: secondHeight + spacing,\n width: rightWidth,\n height: thirdHeight,\n },\n sides: AlbumRectPart.Bottom | AlbumRectPart.Right,\n }];\n}\n\nfunction layoutThreeTopAndOther(params: ILayoutParams) {\n const {\n maxWidth,\n ratios,\n maxHeight,\n spacing,\n } = params;\n const firstWidth = maxWidth;\n const firstHeight = Math.round(Math.min(firstWidth / ratios[0], 0.66 * (maxHeight - spacing)));\n const secondWidth = (maxWidth - spacing) / 2;\n const secondHeight = Math.min(\n maxHeight - firstHeight - spacing,\n Math.round(Math.min(\n secondWidth / ratios[1],\n secondWidth / ratios[2],\n )),\n );\n const thirdWidth = firstWidth - secondWidth - spacing;\n\n return [{\n dimensions: {\n x: 0,\n y: 0,\n width: firstWidth,\n height: firstHeight,\n },\n sides: AlbumRectPart.Left | AlbumRectPart.Top | AlbumRectPart.Right,\n }, {\n dimensions: {\n x: 0,\n y: firstHeight + spacing,\n width: secondWidth,\n height: secondHeight,\n },\n sides: AlbumRectPart.Bottom | AlbumRectPart.Left,\n }, {\n dimensions: {\n x: secondWidth + spacing,\n y: firstHeight + spacing,\n width: thirdWidth,\n height: secondHeight,\n },\n sides: AlbumRectPart.Bottom | AlbumRectPart.Right,\n }];\n}\n\nfunction layoutFour(params: ILayoutParams) {\n const { proportions } = params;\n\n return proportions[0] === 'w'\n ? layoutFourTopAndOther(params)\n : layoutFourLeftAndOther(params);\n}\n\nfunction layoutFourTopAndOther({\n maxWidth,\n ratios,\n spacing,\n maxHeight,\n minWidth,\n}: ILayoutParams) {\n const w = maxWidth;\n const h0 = Math.round(Math.min(w / ratios[0], 0.66 * (maxHeight - spacing)));\n const h = Math.round((maxWidth - 2 * spacing) / (ratios[1] + ratios[2] + ratios[3]));\n const w0 = Math.max(minWidth, Math.round(Math.min(0.4 * (maxWidth - 2 * spacing), h * ratios[1])));\n const w2 = Math.round(Math.max(Math.max(minWidth, 0.33 * (maxWidth - 2 * spacing)), h * ratios[3]));\n const w1 = w - w0 - w2 - 2 * spacing;\n const h1 = Math.min(maxHeight - h0 - spacing, h);\n\n return [{\n dimensions: {\n x: 0,\n y: 0,\n width: w,\n height: h0,\n },\n sides: AlbumRectPart.Left | AlbumRectPart.Top | AlbumRectPart.Right,\n }, {\n dimensions: {\n x: 0,\n y: h0 + spacing,\n width: w0,\n height: h1,\n },\n sides: AlbumRectPart.Bottom | AlbumRectPart.Left,\n }, {\n dimensions: {\n x: w0 + spacing,\n y: h0 + spacing,\n width: w1,\n height: h1,\n },\n sides: AlbumRectPart.Bottom,\n }, {\n dimensions: {\n x: w0 + spacing + w1 + spacing,\n y: h0 + spacing,\n width: w2,\n height: h1,\n },\n sides: AlbumRectPart.Right | AlbumRectPart.Bottom,\n }];\n}\n\nfunction layoutFourLeftAndOther({\n maxHeight,\n ratios,\n maxWidth,\n spacing,\n minWidth,\n}: ILayoutParams) {\n const h = maxHeight;\n const w0 = Math.round(Math.min(h * ratios[0], 0.6 * (maxWidth - spacing)));\n const w = Math.round((maxHeight - 2 * spacing) / (1 / ratios[1] + 1 / ratios[2] + 1 / ratios[3]));\n const h0 = Math.round(w / ratios[1]);\n const h1 = Math.round(w / ratios[2]);\n const h2 = h - h0 - h1 - 2 * spacing;\n const w1 = Math.max(minWidth, Math.min(maxWidth - w0 - spacing, w));\n\n return [{\n dimensions: {\n x: 0,\n y: 0,\n width: w0,\n height: h,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Left | AlbumRectPart.Bottom,\n }, {\n dimensions: {\n x: w0 + spacing,\n y: 0,\n width: w1,\n height: h0,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Right,\n }, {\n dimensions: {\n x: w0 + spacing,\n y: h0 + spacing,\n width: w1,\n height: h1,\n },\n sides: AlbumRectPart.Right,\n }, {\n dimensions: {\n x: w0 + spacing,\n y: h0 + h1 + 2 * spacing,\n width: w1,\n height: h2,\n },\n sides: AlbumRectPart.Bottom | AlbumRectPart.Right,\n }];\n}\n","import { IS_IOS } from '../../../../util/environment';\n\nlet element: HTMLSpanElement | undefined;\n\nexport default function calculateAuthorWidth(text: string) {\n if (!element) {\n element = document.createElement('span');\n // eslint-disable-next-line max-len\n element.style.font = IS_IOS\n // eslint-disable-next-line max-len\n ? '400 12px system-ui, -apple-system, BlinkMacSystemFont, \"Roboto\", \"Apple Color Emoji\", \"Helvetica Neue\", sans-serif'\n : '400 12px \"Roboto\", -apple-system, \"Apple Color Emoji\", BlinkMacSystemFont, \"Helvetica Neue\", sans-serif';\n element.style.whiteSpace = 'nowrap';\n element.style.position = 'absolute';\n element.style.left = '-999px';\n element.style.opacity = '.01';\n document.body.appendChild(element);\n }\n\n element.innerHTML = text;\n\n return element.offsetWidth;\n}\n","import { FocusDirection } from '../../../../types';\n\nimport { useLayoutEffect } from '../../../../lib/teact/teact';\nimport fastSmoothScroll from '../../../../util/fastSmoothScroll';\n\n// This is used when the viewport was replaced.\nconst RELOCATED_FOCUS_OFFSET = 1000;\nconst FOCUS_MARGIN = 20;\n\nexport default function useFocusMessage(\n elementRef: { current: HTMLDivElement | null },\n chatId: string,\n isFocused?: boolean,\n focusDirection?: FocusDirection,\n noFocusHighlight?: boolean,\n isResizingContainer?: boolean,\n) {\n useLayoutEffect(() => {\n if (isFocused && elementRef.current) {\n const messagesContainer = elementRef.current.closest('.MessageList')!;\n\n fastSmoothScroll(\n messagesContainer,\n elementRef.current,\n // `noFocusHighlight` always called from “scroll-to-bottom” buttons\n noFocusHighlight ? 'end' : 'centerOrTop',\n FOCUS_MARGIN,\n focusDirection !== undefined ? RELOCATED_FOCUS_OFFSET : undefined,\n focusDirection,\n undefined,\n isResizingContainer,\n );\n }\n }, [elementRef, chatId, isFocused, focusDirection, noFocusHighlight, isResizingContainer]);\n}\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './ContextMenuContainer';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst ContextMenuContainerAsync: FC = (props) => {\n const { isOpen } = props;\n const ContextMenuContainer = useModuleLoader(Bundles.Extra, 'ContextMenuContainer', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return ContextMenuContainer ? : undefined;\n};\n\nexport default memo(ContextMenuContainerAsync);\n","import React, {\n FC, memo, useEffect, useMemo, useRef,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiUser, ApiMessage, ApiChat } from '../../api/types';\nimport { FocusDirection } from '../../types';\n\nimport {\n selectUser,\n selectChatMessage,\n selectIsMessageFocused,\n selectChat,\n} from '../../modules/selectors';\nimport { isChatChannel } from '../../modules/helpers';\nimport buildClassName from '../../util/buildClassName';\nimport renderText from '../common/helpers/renderText';\nimport { renderActionMessageText } from '../common/helpers/renderActionMessageText';\nimport useEnsureMessage from '../../hooks/useEnsureMessage';\nimport useContextMenuHandlers from '../../hooks/useContextMenuHandlers';\nimport { ObserveFn, useOnIntersect } from '../../hooks/useIntersectionObserver';\nimport useFocusMessage from './message/hooks/useFocusMessage';\nimport useLang from '../../hooks/useLang';\n\nimport ContextMenuContainer from './message/ContextMenuContainer.async';\nimport useFlag from '../../hooks/useFlag';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport { preventMessageInputBlur } from './helpers/preventMessageInputBlur';\n\ntype OwnProps = {\n message: ApiMessage;\n observeIntersection?: ObserveFn;\n isEmbedded?: boolean;\n appearanceOrder?: number;\n isLastInList?: boolean;\n};\n\ntype StateProps = {\n usersById: Record;\n sender?: ApiUser | ApiChat;\n targetUserIds?: string[];\n targetMessage?: ApiMessage;\n targetChatId?: string;\n isFocused: boolean;\n focusDirection?: FocusDirection;\n noFocusHighlight?: boolean;\n};\n\nconst APPEARANCE_DELAY = 10;\n\nconst ActionMessage: FC = ({\n message,\n observeIntersection,\n isEmbedded,\n appearanceOrder = 0,\n isLastInList,\n usersById,\n sender,\n targetUserIds,\n targetMessage,\n targetChatId,\n isFocused,\n focusDirection,\n noFocusHighlight,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n\n useOnIntersect(ref, observeIntersection);\n useEnsureMessage(message.chatId, message.replyToMessageId, targetMessage);\n useFocusMessage(ref, message.chatId, isFocused, focusDirection, noFocusHighlight);\n\n const lang = useLang();\n\n const noAppearanceAnimation = appearanceOrder <= 0;\n const [isShown, markShown] = useFlag(noAppearanceAnimation);\n useEffect(() => {\n if (noAppearanceAnimation) {\n return;\n }\n\n setTimeout(markShown, appearanceOrder * APPEARANCE_DELAY);\n }, [appearanceOrder, markShown, noAppearanceAnimation]);\n const { transitionClassNames } = useShowTransition(isShown, undefined, noAppearanceAnimation, false);\n\n const targetUsers = useMemo(() => {\n return targetUserIds\n ? targetUserIds.map((userId) => usersById?.[userId]).filter(Boolean as any)\n : undefined;\n }, [targetUserIds, usersById]);\n\n const content = renderActionMessageText(\n lang,\n message,\n sender,\n targetUsers,\n targetMessage,\n targetChatId,\n isEmbedded ? { isEmbedded: true, asPlain: true } : undefined,\n );\n const {\n isContextMenuOpen, contextMenuPosition,\n handleBeforeContextMenu, handleContextMenu,\n handleContextMenuClose, handleContextMenuHide,\n } = useContextMenuHandlers(ref);\n const isContextMenuShown = contextMenuPosition !== undefined;\n\n const handleMouseDown = (e: React.MouseEvent) => {\n preventMessageInputBlur(e);\n handleBeforeContextMenu(e);\n };\n\n if (isEmbedded) {\n return {renderText(content as string)};\n }\n\n const className = buildClassName(\n 'ActionMessage message-list-item',\n isFocused && !noFocusHighlight && 'focused',\n isContextMenuShown && 'has-menu-open',\n isLastInList && 'last-in-list',\n transitionClassNames,\n );\n\n return (\n \n {content}\n {contextMenuPosition && (\n \n )}\n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { message }): StateProps => {\n const { byId: usersById } = global.users;\n const userId = message.senderId;\n const { targetUserIds, targetChatId } = message.content.action || {};\n const targetMessageId = message.replyToMessageId;\n const targetMessage = targetMessageId\n ? selectChatMessage(global, message.chatId, targetMessageId)\n : undefined;\n\n const isFocused = selectIsMessageFocused(global, message);\n const { direction: focusDirection, noHighlight: noFocusHighlight } = (isFocused && global.focusedMessage) || {};\n\n const chat = selectChat(global, message.chatId);\n const sender = chat && (isChatChannel(chat) || userId === message.chatId)\n ? chat\n : userId ? selectUser(global, userId) : undefined;\n\n return {\n usersById,\n sender,\n targetChatId,\n targetUserIds,\n targetMessage,\n isFocused,\n ...(isFocused && { focusDirection, noFocusHighlight }),\n };\n },\n)(ActionMessage));\n","import React, { FC, useRef } from '../../lib/teact/teact';\n\nimport { ApiUser, ApiMessage, ApiChat } from '../../api/types';\n\nimport {\n getMessageMediaHash,\n isActionMessage,\n getMessageSummaryText,\n getSenderTitle,\n getMessageRoundVideo,\n} from '../../modules/helpers';\nimport renderText from './helpers/renderText';\nimport { getPictogramDimensions } from './helpers/mediaDimensions';\nimport buildClassName from '../../util/buildClassName';\nimport { ObserveFn, useIsIntersecting } from '../../hooks/useIntersectionObserver';\nimport useMedia from '../../hooks/useMedia';\nimport useWebpThumbnail from '../../hooks/useWebpThumbnail';\nimport useLang from '../../hooks/useLang';\n\nimport ActionMessage from '../middle/ActionMessage';\n\nimport './EmbeddedMessage.scss';\n\ntype OwnProps = {\n observeIntersection?: ObserveFn;\n className?: string;\n message?: ApiMessage;\n sender?: ApiUser | ApiChat;\n title?: string;\n customText?: string;\n isProtected?: boolean;\n onClick: NoneToVoidFunction;\n};\n\nconst NBSP = '\\u00A0';\n\nconst EmbeddedMessage: FC = ({\n className,\n message,\n sender,\n title,\n customText,\n isProtected,\n observeIntersection,\n onClick,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n\n const mediaBlobUrl = useMedia(message && getMessageMediaHash(message, 'pictogram'), !isIntersecting);\n const pictogramId = message && `sticker-reply-thumb${message.id}`;\n const mediaThumbnail = useWebpThumbnail(message);\n const isRoundVideo = Boolean(message && getMessageRoundVideo(message));\n\n const lang = useLang();\n\n const senderTitle = sender && getSenderTitle(lang, sender);\n\n return (\n \n {mediaThumbnail && renderPictogram(pictogramId, mediaThumbnail, mediaBlobUrl, isRoundVideo, isProtected)}\n
\n

\n {!message ? (\n customText || NBSP\n ) : isActionMessage(message) ? (\n \n ) : (\n renderText(getMessageSummaryText(lang, message, Boolean(mediaThumbnail)))\n )}\n

\n
{renderText(senderTitle || title || NBSP)}
\n
\n \n );\n};\n\nfunction renderPictogram(\n id: string | undefined,\n thumbDataUri: string,\n blobUrl?: string,\n isRoundVideo?: boolean,\n isProtected?: boolean,\n) {\n const { width, height } = getPictogramDimensions();\n\n return (\n <>\n \n {isProtected && }\n \n );\n}\n\nexport default EmbeddedMessage;\n","import React, {\n FC, memo, useMemo,\n} from '../../../lib/teact/teact';\n\nimport { ApiMessage, ApiMessageOutgoingStatus } from '../../../api/types';\n\nimport { formatDateTimeToString, formatTime } from '../../../util/dateFormat';\nimport { formatIntegerCompact } from '../../../util/textFormat';\n\nimport MessageOutgoingStatus from '../../common/MessageOutgoingStatus';\nimport renderText from '../../common/helpers/renderText';\nimport useLang from '../../../hooks/useLang';\nimport useFlag from '../../../hooks/useFlag';\n\nimport './MessageMeta.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n outgoingStatus?: ApiMessageOutgoingStatus;\n signature?: string;\n onClick: (e: React.MouseEvent) => void;\n};\n\nconst MessageMeta: FC = ({\n message, outgoingStatus, signature, onClick,\n}) => {\n const lang = useLang();\n const [isActivated, markActivated] = useFlag();\n\n const title = useMemo(() => {\n if (!isActivated) return undefined;\n const createDateTime = formatDateTimeToString(message.date * 1000, lang.code);\n const editDateTime = message.isEdited && formatDateTimeToString(message.editDate! * 1000, lang.code);\n const forwardedDateTime = message.forwardInfo && formatDateTimeToString(message.forwardInfo.date * 1000, lang.code);\n\n let text = createDateTime;\n if (editDateTime) {\n text += '\\n';\n text += lang('lng_edited_date').replace('{date}', editDateTime);\n }\n if (forwardedDateTime) {\n text += '\\n';\n text += lang('lng_forwarded_date').replace('{date}', forwardedDateTime);\n }\n\n return text;\n }, [isActivated, lang, message]);\n\n return (\n \n {Boolean(message.views) && (\n <>\n \n {formatIntegerCompact(message.views!)}\n \n \n \n )}\n {signature && (\n {renderText(signature)}\n )}\n \n {message.isEdited && `${lang('EditedMessage')} `}\n {formatTime(message.date * 1000, lang)}\n \n {outgoingStatus && (\n \n )}\n \n );\n};\n\nexport default memo(MessageMeta);\n","import React, { FC, useRef } from '../../../lib/teact/teact';\n\nimport { ApiMessage } from '../../../api/types';\n\nimport { MEMOJI_STICKER_ID } from '../../../config';\nimport { getStickerDimensions } from '../../common/helpers/mediaDimensions';\nimport { getMessageMediaFormat, getMessageMediaHash } from '../../../modules/helpers';\nimport buildClassName from '../../../util/buildClassName';\nimport { ObserveFn, useIsIntersecting } from '../../../hooks/useIntersectionObserver';\nimport useMedia from '../../../hooks/useMedia';\nimport useMediaTransition from '../../../hooks/useMediaTransition';\nimport useFlag from '../../../hooks/useFlag';\nimport useWebpThumbnail from '../../../hooks/useWebpThumbnail';\n\nimport AnimatedSticker from '../../common/AnimatedSticker';\nimport StickerSetModal from '../../common/StickerSetModal.async';\n\nimport './Sticker.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n observeIntersection: ObserveFn;\n observeIntersectionForPlaying: ObserveFn;\n shouldLoop?: boolean;\n lastSyncTime?: number;\n};\n\nconst Sticker: FC = ({\n message, observeIntersection, observeIntersectionForPlaying, shouldLoop, lastSyncTime,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n\n const [isModalOpen, openModal, closeModal] = useFlag();\n\n const sticker = message.content.sticker!;\n const { isAnimated, stickerSetId } = sticker;\n const isMemojiSticker = stickerSetId === MEMOJI_STICKER_ID;\n\n const shouldLoad = useIsIntersecting(ref, observeIntersection);\n const shouldPlay = useIsIntersecting(ref, observeIntersectionForPlaying);\n\n const mediaHash = sticker.isPreloadedGlobally ? `sticker${sticker.id}` : getMessageMediaHash(message, 'inline')!;\n const thumbDataUri = useWebpThumbnail(message);\n const mediaData = useMedia(\n mediaHash,\n !shouldLoad,\n getMessageMediaFormat(message, 'inline', true),\n lastSyncTime,\n );\n\n const isMediaLoaded = Boolean(mediaData);\n const [isAnimationLoaded, markAnimationLoaded] = useFlag(isMediaLoaded);\n const isMediaReady = isAnimated ? isAnimationLoaded : isMediaLoaded;\n const transitionClassNames = useMediaTransition(isMediaReady);\n\n const { width, height } = getStickerDimensions(sticker);\n const thumbClassName = buildClassName('thumbnail', !thumbDataUri && 'empty');\n\n const stickerClassName = buildClassName(\n 'Sticker media-inner',\n isMemojiSticker && 'inactive',\n );\n\n return (\n
\n {!isMediaReady && (\n \n )}\n {!isAnimated && (\n \n )}\n {isAnimated && isMediaLoaded && (\n \n )}\n \n
\n );\n};\n\nexport default Sticker;\n","import { ApiMessage } from '../../../../api/types';\n\nimport { IS_CANVAS_FILTER_SUPPORTED, IS_SINGLE_COLUMN_LAYOUT } from '../../../../util/environment';\nimport { getMessageMediaThumbDataUri } from '../../../../modules/helpers';\nimport useCanvasBlur from '../../../../hooks/useCanvasBlur';\n\nexport default function useBlurredMediaThumbRef(message: ApiMessage, fullMediaData?: string) {\n return useCanvasBlur(\n getMessageMediaThumbDataUri(message),\n Boolean(fullMediaData),\n IS_SINGLE_COLUMN_LAYOUT && !IS_CANVAS_FILTER_SUPPORTED,\n );\n}\n","import { ISettings } from '../../../../types';\n\nconst SELECTED_APPENDIX_COLORS = {\n dark: {\n outgoing: 'rgb(135,116,225)',\n incoming: 'rgb(33,33,33)',\n },\n light: {\n outgoing: 'rgb(238,255,222)',\n incoming: 'rgb(255,255,255)',\n },\n};\n\nexport default function getCustomAppendixBg(\n src: string, isOwn: boolean, inSelectMode?: boolean, isSelected?: boolean, theme?: ISettings['theme'],\n) {\n if (isSelected) {\n return Promise.resolve(SELECTED_APPENDIX_COLORS[theme || 'light'][isOwn ? 'outgoing' : 'incoming']);\n }\n return getAppendixColorFromImage(src, isOwn);\n}\n\nasync function getAppendixColorFromImage(src: string, isOwn: boolean) {\n const img = new Image();\n img.src = src;\n\n if (!img.width) {\n await new Promise((resolve) => {\n img.onload = resolve;\n });\n }\n\n const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d')!;\n\n canvas.width = img.width;\n canvas.height = img.height;\n\n ctx.drawImage(img, 0, 0, img.width, img.height);\n\n const x = isOwn ? img.width - 1 : 0;\n const y = img.height - 1;\n\n const pixel = Array.from(ctx.getImageData(x, y, 1, 1).data);\n return `rgba(${pixel.join(',')})`;\n}\n","import React, {\n FC, useCallback, useLayoutEffect, useRef, useState,\n} from '../../../lib/teact/teact';\n\nimport { ApiMessage } from '../../../api/types';\nimport { ISettings } from '../../../types';\nimport { IMediaDimensions } from './helpers/calculateAlbumLayout';\n\nimport {\n getMessagePhoto,\n getMessageWebPagePhoto,\n getMessageMediaHash,\n getMediaTransferState,\n isOwnMessage,\n} from '../../../modules/helpers';\nimport { ObserveFn, useIsIntersecting } from '../../../hooks/useIntersectionObserver';\nimport useMediaWithLoadProgress from '../../../hooks/useMediaWithLoadProgress';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useBlurredMediaThumbRef from './hooks/useBlurredMediaThumbRef';\nimport usePrevious from '../../../hooks/usePrevious';\nimport useMediaTransition from '../../../hooks/useMediaTransition';\nimport buildClassName from '../../../util/buildClassName';\nimport getCustomAppendixBg from './helpers/getCustomAppendixBg';\nimport { calculateMediaDimensions } from './helpers/mediaDimensions';\n\nimport ProgressSpinner from '../../ui/ProgressSpinner';\n\nexport type OwnProps = {\n id?: string;\n message: ApiMessage;\n observeIntersection?: ObserveFn;\n noAvatars?: boolean;\n canAutoLoad?: boolean;\n isInSelectMode?: boolean;\n isSelected?: boolean;\n uploadProgress?: number;\n size?: 'inline' | 'pictogram';\n shouldAffectAppendix?: boolean;\n dimensions?: IMediaDimensions & { isSmall?: boolean };\n nonInteractive?: boolean;\n isDownloading: boolean;\n isProtected?: boolean;\n theme: ISettings['theme'];\n onClick?: (id: number) => void;\n onCancelUpload?: (message: ApiMessage) => void;\n};\n\nconst CUSTOM_APPENDIX_ATTRIBUTE = 'data-has-custom-appendix';\n\nconst Photo: FC = ({\n id,\n message,\n observeIntersection,\n noAvatars,\n canAutoLoad,\n isInSelectMode,\n isSelected,\n uploadProgress,\n size = 'inline',\n dimensions,\n nonInteractive,\n shouldAffectAppendix,\n isDownloading,\n isProtected,\n theme,\n onClick,\n onCancelUpload,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n\n const photo = (getMessagePhoto(message) || getMessageWebPagePhoto(message))!;\n const localBlobUrl = photo.blobUrl;\n\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n\n const [isLoadAllowed, setIsLoadAllowed] = useState(canAutoLoad);\n const shouldLoad = isLoadAllowed && isIntersecting;\n const {\n mediaData, loadProgress,\n } = useMediaWithLoadProgress(getMessageMediaHash(message, size), !shouldLoad);\n const fullMediaData = localBlobUrl || mediaData;\n const thumbRef = useBlurredMediaThumbRef(message, fullMediaData);\n\n const {\n loadProgress: downloadProgress,\n } = useMediaWithLoadProgress(getMessageMediaHash(message, 'download'), !isDownloading);\n\n const {\n isUploading, isTransferring, transferProgress,\n } = getMediaTransferState(\n message,\n uploadProgress || (isDownloading ? downloadProgress : loadProgress),\n shouldLoad && !fullMediaData,\n );\n const wasLoadDisabled = usePrevious(isLoadAllowed) === false;\n\n const transitionClassNames = useMediaTransition(fullMediaData);\n const {\n shouldRender: shouldRenderSpinner,\n transitionClassNames: spinnerClassNames,\n } = useShowTransition(isTransferring, undefined, wasLoadDisabled, 'slow');\n const {\n shouldRender: shouldRenderDownloadButton,\n transitionClassNames: downloadButtonClassNames,\n } = useShowTransition(!fullMediaData && !isLoadAllowed);\n\n const handleClick = useCallback(() => {\n if (isUploading) {\n if (onCancelUpload) {\n onCancelUpload(message);\n }\n } else if (!fullMediaData) {\n setIsLoadAllowed((isAllowed) => !isAllowed);\n } else if (onClick) {\n onClick(message.id);\n }\n }, [fullMediaData, isUploading, message, onCancelUpload, onClick]);\n\n const isOwn = isOwnMessage(message);\n useLayoutEffect(() => {\n if (!shouldAffectAppendix) {\n return;\n }\n\n const contentEl = ref.current!.closest('.message-content')!;\n\n if (fullMediaData) {\n getCustomAppendixBg(fullMediaData, isOwn, isInSelectMode, isSelected, theme).then((appendixBg) => {\n contentEl.style.setProperty('--appendix-bg', appendixBg);\n contentEl.setAttribute(CUSTOM_APPENDIX_ATTRIBUTE, '');\n });\n } else {\n contentEl.classList.add('has-appendix-thumb');\n }\n }, [fullMediaData, isOwn, shouldAffectAppendix, isInSelectMode, isSelected, theme]);\n\n const { width, height, isSmall } = dimensions || calculateMediaDimensions(message, noAvatars);\n\n const className = buildClassName(\n 'media-inner',\n !isUploading && !nonInteractive && 'interactive',\n isSmall && 'small-image',\n width === height && 'square-image',\n );\n\n const style = dimensions\n ? `width: ${width}px; height: ${height}px; left: ${dimensions.x}px; top: ${dimensions.y}px;`\n : '';\n\n return (\n \n \n \n {isProtected && }\n {shouldRenderSpinner && !shouldRenderDownloadButton && (\n
\n \n
\n )}\n {shouldRenderDownloadButton && }\n {isTransferring && (\n {Math.round(transferProgress * 100)}%\n )}\n \n );\n};\n\nexport default Photo;\n","import { useCallback, useRef } from '../../../../lib/teact/teact';\n\nimport { fastRaf } from '../../../../util/schedulers';\nimport safePlay from '../../../../util/safePlay';\nimport useBackgroundMode from '../../../../hooks/useBackgroundMode';\nimport useHeavyAnimationCheck from '../../../../hooks/useHeavyAnimationCheck';\n\nexport default function useVideoAutoPause(playerRef: { current: HTMLVideoElement | null }, canPlay: boolean) {\n const wasPlaying = useRef(playerRef.current?.paused);\n const canPlayRef = useRef();\n canPlayRef.current = canPlay;\n\n const freezePlaying = useCallback(() => {\n if (!playerRef.current) {\n return;\n }\n\n wasPlaying.current = !playerRef.current.paused;\n\n if (wasPlaying.current) {\n playerRef.current.pause();\n }\n }, [playerRef]);\n\n const unfreezePlaying = useCallback(() => {\n if (\n playerRef.current && wasPlaying.current && canPlayRef.current\n // At this point HTMLVideoElement can be unmounted from the DOM\n && document.body.contains(playerRef.current)\n ) {\n safePlay(playerRef.current);\n }\n }, [playerRef]);\n\n const unfreezePlayingOnRaf = useCallback(() => {\n fastRaf(unfreezePlaying);\n }, [unfreezePlaying]);\n\n useBackgroundMode(freezePlaying, unfreezePlayingOnRaf);\n useHeavyAnimationCheck(freezePlaying, unfreezePlaying);\n}\n","import React, {\n FC, useCallback, useRef, useState,\n} from '../../../lib/teact/teact';\nimport { getDispatch } from '../../../lib/teact/teactn';\n\nimport { ApiMediaFormat, ApiMessage } from '../../../api/types';\nimport { IMediaDimensions } from './helpers/calculateAlbumLayout';\n\nimport { formatMediaDuration } from '../../../util/dateFormat';\nimport buildClassName from '../../../util/buildClassName';\nimport { calculateVideoDimensions } from '../../common/helpers/mediaDimensions';\nimport {\n getMediaTransferState,\n getMessageMediaFormat,\n getMessageMediaHash,\n getMessageVideo,\n getMessageWebPageVideo,\n isForwardedMessage,\n isOwnMessage,\n} from '../../../modules/helpers';\nimport { ObserveFn, useIsIntersecting } from '../../../hooks/useIntersectionObserver';\nimport useMediaWithLoadProgress from '../../../hooks/useMediaWithLoadProgress';\nimport useMedia from '../../../hooks/useMedia';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport usePrevious from '../../../hooks/usePrevious';\nimport useBuffering from '../../../hooks/useBuffering';\nimport useVideoCleanup from '../../../hooks/useVideoCleanup';\nimport useMediaTransition from '../../../hooks/useMediaTransition';\nimport useVideoAutoPause from './hooks/useVideoAutoPause';\nimport useBlurredMediaThumbRef from './hooks/useBlurredMediaThumbRef';\n\nimport ProgressSpinner from '../../ui/ProgressSpinner';\n\nexport type OwnProps = {\n id?: string;\n message: ApiMessage;\n observeIntersection: ObserveFn;\n noAvatars?: boolean;\n canAutoLoad?: boolean;\n canAutoPlay?: boolean;\n uploadProgress?: number;\n dimensions?: IMediaDimensions;\n lastSyncTime?: number;\n isDownloading: boolean;\n isProtected?: boolean;\n onClick?: (id: number) => void;\n onCancelUpload?: (message: ApiMessage) => void;\n};\n\nconst Video: FC = ({\n id,\n message,\n observeIntersection,\n noAvatars,\n canAutoLoad,\n canAutoPlay,\n uploadProgress,\n lastSyncTime,\n dimensions,\n onClick,\n onCancelUpload,\n isDownloading,\n isProtected,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const videoRef = useRef(null);\n\n const video = (getMessageVideo(message) || getMessageWebPageVideo(message))!;\n const localBlobUrl = video.blobUrl;\n\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n\n const [isLoadAllowed, setIsLoadAllowed] = useState(canAutoLoad);\n const shouldLoad = Boolean(isLoadAllowed && isIntersecting && lastSyncTime);\n const [isPlayAllowed, setIsPlayAllowed] = useState(canAutoPlay);\n\n const previewBlobUrl = useMedia(\n getMessageMediaHash(message, 'pictogram'),\n !(isIntersecting && lastSyncTime),\n getMessageMediaFormat(message, 'pictogram'),\n lastSyncTime,\n );\n const previewClassNames = useMediaTransition(previewBlobUrl);\n\n const { mediaData, loadProgress } = useMediaWithLoadProgress(\n getMessageMediaHash(message, 'inline'),\n !shouldLoad,\n getMessageMediaFormat(message, 'inline'),\n lastSyncTime,\n );\n const fullMediaData = localBlobUrl || mediaData;\n const isInline = Boolean(isIntersecting && fullMediaData);\n // Thumbnail is always rendered so we can only disable blur if we have preview\n const thumbRef = useBlurredMediaThumbRef(message, previewBlobUrl);\n\n const { loadProgress: downloadProgress } = useMediaWithLoadProgress(\n getMessageMediaHash(message, 'download'),\n !isDownloading,\n ApiMediaFormat.BlobUrl,\n lastSyncTime,\n );\n\n const { isBuffered, bufferingHandlers } = useBuffering(!canAutoLoad);\n const { isUploading, isTransferring, transferProgress } = getMediaTransferState(\n message,\n uploadProgress || (isDownloading ? downloadProgress : loadProgress),\n (shouldLoad && !isBuffered) || isDownloading,\n );\n const wasLoadDisabled = usePrevious(isLoadAllowed) === false;\n const {\n shouldRender: shouldRenderSpinner,\n transitionClassNames: spinnerClassNames,\n } = useShowTransition(isTransferring, undefined, wasLoadDisabled);\n const {\n shouldRender: shouldRenderPlayButton,\n transitionClassNames: playButtonClassNames,\n } = useShowTransition(isLoadAllowed && !isPlayAllowed && !shouldRenderSpinner);\n\n const [playProgress, setPlayProgress] = useState(0);\n const handleTimeUpdate = useCallback((e: React.SyntheticEvent) => {\n setPlayProgress(Math.max(0, e.currentTarget.currentTime - 1));\n }, []);\n\n const duration = (videoRef.current?.duration) || video.duration || 0;\n\n const isOwn = isOwnMessage(message);\n const isForwarded = isForwardedMessage(message);\n const { width, height } = dimensions || calculateVideoDimensions(video, isOwn, isForwarded, noAvatars);\n\n useVideoAutoPause(videoRef, isInline);\n useVideoCleanup(videoRef, [isInline]);\n\n const handleClick = useCallback(() => {\n if (isUploading) {\n if (onCancelUpload) {\n onCancelUpload(message);\n }\n } else if (isDownloading) {\n getDispatch().cancelMessageMediaDownload({ message });\n } else if (!fullMediaData) {\n setIsLoadAllowed((isAllowed) => !isAllowed);\n } else if (fullMediaData && !isPlayAllowed) {\n setIsPlayAllowed(true);\n videoRef.current!.play();\n } else if (onClick) {\n onClick(message.id);\n }\n }, [isUploading, isDownloading, fullMediaData, isPlayAllowed, onClick, onCancelUpload, message]);\n\n const className = buildClassName('media-inner dark', !isUploading && 'interactive');\n const style = dimensions\n ? `width: ${width}px; height: ${height}px; left: ${dimensions.x}px; top: ${dimensions.y}px;`\n : '';\n\n return (\n \n \n \n {isInline && (\n \n \n \n )}\n {isProtected && }\n {shouldRenderPlayButton && }\n {shouldRenderSpinner && (\n
\n \n
\n )}\n {!isLoadAllowed && (\n \n )}\n {isTransferring ? (\n \n {(isUploading || isDownloading) ? `${Math.round(transferProgress * 100)}%` : '...'}\n \n ) : (\n
\n {video.isGif ? 'GIF' : formatMediaDuration(Math.max(duration - playProgress, 0))}\n
\n )}\n \n );\n};\n\nexport default Video;\n","import React, { FC, useCallback } from '../../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiUser, ApiContact, ApiCountryCode } from '../../../api/types';\n\nimport { selectUser } from '../../../modules/selectors';\nimport { formatPhoneNumberWithCode } from '../../../util/phoneNumber';\nimport buildClassName from '../../../util/buildClassName';\n\nimport Avatar from '../../common/Avatar';\n\nimport './Contact.scss';\n\ntype OwnProps = {\n contact: ApiContact;\n};\n\ntype StateProps = {\n user?: ApiUser;\n phoneCodeList: ApiCountryCode[];\n};\n\nconst Contact: FC = ({\n contact, user, phoneCodeList,\n}) => {\n const { openUserInfo } = getDispatch();\n\n const {\n firstName,\n lastName,\n phoneNumber,\n userId,\n } = contact;\n\n const handleClick = useCallback(() => {\n openUserInfo({ id: userId });\n }, [openUserInfo, userId]);\n\n return (\n \n \n
\n
{firstName} {lastName}
\n
{formatPhoneNumberWithCode(phoneCodeList, phoneNumber)}
\n
\n \n );\n};\n\nexport default withGlobal(\n (global, { contact }): StateProps => {\n const { countryList: { phoneCodes: phoneCodeList } } = global;\n return {\n user: selectUser(global, contact.userId),\n phoneCodeList,\n };\n },\n)(Contact);\n","import React, {\n FC, useState, useEffect, useRef,\n} from '../../../lib/teact/teact';\n\nimport { ApiPollAnswer, ApiPollResult } from '../../../api/types';\n\nimport buildClassName from '../../../util/buildClassName';\nimport renderText from '../../common/helpers/renderText';\n\nimport './PollOption.scss';\n\ntype OwnProps = {\n answer: ApiPollAnswer;\n voteResults?: ApiPollResult[];\n totalVoters?: number;\n maxVotersCount?: number;\n correctResults: string[];\n shouldAnimate: boolean;\n};\n\nconst PollOption: FC = ({\n answer,\n voteResults,\n totalVoters,\n maxVotersCount,\n correctResults,\n shouldAnimate,\n}) => {\n const result = voteResults && voteResults.find((r) => r.option === answer.option);\n const correctAnswer = correctResults.length === 0 || correctResults.indexOf(answer.option) !== -1;\n const showIcon = (correctResults.length > 0 && correctAnswer) || (result?.isChosen);\n const answerPercent = result ? getPercentage(result.votersCount, totalVoters || 0) : 0;\n const [finalPercent, setFinalPercent] = useState(shouldAnimate ? 0 : answerPercent);\n // eslint-disable-next-line no-null/no-null\n const lineRef = useRef(null);\n const lineWidth = result ? getPercentage(result.votersCount, maxVotersCount || 0) : 0;\n const isAnimationDoesNotStart = finalPercent < answerPercent;\n\n useEffect(() => {\n if (shouldAnimate) {\n setFinalPercent(answerPercent);\n }\n }, [shouldAnimate, answerPercent]);\n\n useEffect(() => {\n const lineEl = lineRef.current;\n\n if (lineEl && shouldAnimate) {\n const svgEl = lineEl.firstElementChild;\n\n const style = isAnimationDoesNotStart ? '' : 'stroke-dasharray: 100% 200%; stroke-dashoffset: -44';\n if (!svgEl) {\n lineEl.innerHTML = `\n \n \n `;\n } else {\n svgEl.setAttribute('style', style);\n }\n }\n }, [isAnimationDoesNotStart, shouldAnimate]);\n\n if (!voteResults || !result) {\n return undefined;\n }\n\n const lineStyle = `width: ${lineWidth}%; transform:scaleX(${isAnimationDoesNotStart ? 0 : 1})`;\n\n return (\n
\n
\n {answerPercent}%\n {showIcon && (\n \n \n \n )}\n
\n
\n
\n {renderText(answer.text)}\n
\n
\n
\n \n
\n
\n
\n );\n};\n\nfunction getPercentage(value: number, total: number) {\n return total > 0 ? ((value / total) * 100).toFixed() : 0;\n}\n\nexport default PollOption;\n","import React, {\n FC,\n useCallback,\n useEffect,\n useState,\n memo,\n useMemo,\n useRef,\n} from '../../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../../lib/teact/teactn';\n\nimport {\n ApiMessage, ApiPoll, ApiUser, ApiPollAnswer,\n} from '../../../api/types';\n\nimport renderText from '../../common/helpers/renderText';\nimport { renderTextWithEntities } from '../../common/helpers/renderMessageText';\nimport { formatMediaDuration } from '../../../util/dateFormat';\nimport useLang, { LangFn } from '../../../hooks/useLang';\n\nimport CheckboxGroup from '../../ui/CheckboxGroup';\nimport RadioGroup from '../../ui/RadioGroup';\nimport Avatar from '../../common/Avatar';\nimport Button from '../../ui/Button';\nimport Notification from '../../ui/Notification';\nimport PollOption from './PollOption';\n\nimport './Poll.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n poll: ApiPoll;\n onSendVote: (options: string[]) => void;\n};\n\ntype StateProps = {\n recentVoterIds?: number[];\n usersById: Record;\n serverTimeOffset: number;\n};\n\nconst SOLUTION_CONTAINER_ID = '#middle-column-portals';\nconst SOLUTION_DURATION = 5000;\nconst NBSP = '\\u00A0';\n\nconst Poll: FC = ({\n message,\n poll,\n recentVoterIds,\n usersById,\n onSendVote,\n serverTimeOffset,\n}) => {\n const { loadMessage, openPollResults } = getDispatch();\n\n const { id: messageId, chatId } = message;\n const { summary, results } = poll;\n const [isSubmitting, setIsSubmitting] = useState(false);\n const [chosenOptions, setChosenOptions] = useState([]);\n const [isSolutionShown, setIsSolutionShown] = useState(false);\n const [wasSubmitted, setWasSubmitted] = useState(false);\n const [closePeriod, setClosePeriod] = useState(\n !summary.closed && summary.closeDate && summary.closeDate > 0\n ? Math.min(summary.closeDate - Math.floor(Date.now() / 1000) + serverTimeOffset, summary.closePeriod!)\n : 0,\n );\n // eslint-disable-next-line no-null/no-null\n const countdownRef = useRef(null);\n const { results: voteResults, totalVoters } = results;\n const hasVoted = voteResults && voteResults.some((r) => r.isChosen);\n const canVote = !summary.closed && !hasVoted;\n const canViewResult = !canVote && summary.isPublic && Number(results.totalVoters) > 0;\n const isMultiple = canVote && summary.multipleChoice;\n const maxVotersCount = voteResults ? Math.max(...voteResults.map((r) => r.votersCount)) : totalVoters;\n const correctResults = voteResults ? voteResults.reduce((answers: string[], r) => {\n if (r.isCorrect) {\n answers.push(r.option);\n }\n\n return answers;\n }, []) : [];\n const answers = summary.answers.map((a) => ({\n label: a.text,\n value: a.option,\n hidden: Boolean(summary.quiz && summary.closePeriod && closePeriod <= 0),\n }));\n\n useEffect(() => {\n if (\n isSubmitting\n && poll.results.results\n && poll.results.results.some((result) => result.isChosen)\n ) {\n setIsSubmitting(false);\n }\n }, [isSubmitting, poll.results.results]);\n\n useEffect(() => {\n if (closePeriod > 0) {\n setTimeout(() => setClosePeriod(closePeriod - 1), 1000);\n }\n\n const countdownEl = countdownRef.current;\n\n if (countdownEl) {\n const circumference = 6 * 2 * Math.PI;\n const svgEl = countdownEl.lastElementChild;\n const timerEl = countdownEl.firstElementChild;\n if (closePeriod <= 5) {\n countdownEl.classList.add('hurry-up');\n }\n\n if (!svgEl || !timerEl) {\n countdownEl.innerHTML = `\n ${formatMediaDuration(closePeriod)}\n \n \n `;\n } else {\n const strokeDashOffset = ((summary.closePeriod! - closePeriod) / summary.closePeriod!) * circumference;\n timerEl.textContent = formatMediaDuration(closePeriod);\n (svgEl.firstElementChild as SVGElement).setAttribute('stroke-dashoffset', `-${strokeDashOffset}`);\n }\n }\n }, [closePeriod, summary.closePeriod]);\n\n useEffect(() => {\n if (summary.quiz && (closePeriod <= 0 || (hasVoted && !summary.closed))) {\n loadMessage({ chatId, messageId });\n }\n }, [chatId, closePeriod, hasVoted, loadMessage, messageId, summary.closed, summary.quiz]);\n\n // If the client time is not synchronized, the poll must be updated after the closePeriod time has expired.\n useEffect(() => {\n let timer: number | undefined;\n\n if (summary.quiz && !summary.closed && summary.closePeriod && summary.closePeriod > 0) {\n timer = window.setTimeout(() => {\n loadMessage({ chatId, messageId });\n }, summary.closePeriod * 1000);\n }\n\n return () => {\n if (timer) {\n window.clearTimeout(timer);\n }\n };\n }, [canVote, chatId, loadMessage, messageId, summary.closePeriod, summary.closed, summary.quiz]);\n\n const recentVoters = useMemo(() => {\n return recentVoterIds ? recentVoterIds.reduce((result: ApiUser[], id) => {\n const user = usersById[id];\n if (user) {\n result.push(user);\n }\n\n return result;\n }, []) : [];\n }, [usersById, recentVoterIds]);\n\n const handleRadioChange = useCallback(\n (option: string) => {\n setChosenOptions([option]);\n setIsSubmitting(true);\n setWasSubmitted(true);\n onSendVote([option]);\n }, [onSendVote],\n );\n\n const handleCheckboxChange = useCallback(\n (options: string[]) => {\n setChosenOptions(options);\n }, [],\n );\n\n const handleVoteClick = useCallback(\n () => {\n setIsSubmitting(true);\n setWasSubmitted(true);\n onSendVote(chosenOptions);\n }, [onSendVote, chosenOptions],\n );\n\n const handleViewResultsClick = useCallback(\n () => {\n openPollResults({ chatId, messageId });\n }, [chatId, messageId, openPollResults],\n );\n\n const handleSolutionShow = useCallback(() => {\n setIsSolutionShown(true);\n }, []);\n\n const handleSolutionHide = useCallback(() => {\n setIsSolutionShown(false);\n setWasSubmitted(false);\n }, []);\n\n // Show the solution to quiz if the answer was incorrect\n useEffect(() => {\n if (wasSubmitted && hasVoted && summary.quiz && results.results && poll.results.solution) {\n const correctResult = results.results.find((r) => r.isChosen && r.isCorrect);\n if (!correctResult) {\n setIsSolutionShown(true);\n }\n }\n }, [hasVoted, wasSubmitted, results.results, summary.quiz, poll.results.solution]);\n\n const lang = useLang();\n\n function renderResultOption(answer: ApiPollAnswer) {\n return (\n \n );\n }\n\n function renderRecentVoters() {\n return (\n recentVoters.length > 0 && (\n
\n {recentVoters.map((user) => (\n \n ))}\n
\n )\n );\n }\n\n function renderSolution() {\n return (\n isSolutionShown && poll.results.solution && (\n \n )\n );\n }\n\n return (\n
\n {renderSolution()}\n
{renderText(summary.question, ['emoji', 'br'])}
\n
\n {lang(getPollTypeString(summary))}\n {renderRecentVoters()}\n {closePeriod > 0 && canVote &&
}\n {summary.quiz && poll.results.solution && !canVote && (\n \n \n \n )}\n
\n {canVote && (\n
\n {isMultiple\n ? (\n \n )\n : (\n \n )}\n
\n )}\n {!canVote && (\n
\n {summary.answers.map(renderResultOption)}\n
\n )}\n {!canViewResult && !isMultiple && (\n
{getReadableVotersCount(lang, summary.quiz, results.totalVoters)}
\n )}\n {isMultiple && (\n \n {lang('PollSubmitVotes')}\n \n )}\n {canViewResult && (\n \n {lang('PollViewResults')}\n \n )}\n
\n );\n};\n\nfunction getPollTypeString(summary: ApiPoll['summary']) {\n // When we just created the poll, some properties don't exist.\n if (typeof summary.isPublic === 'undefined') {\n return NBSP;\n }\n\n if (summary.quiz) {\n return summary.isPublic ? 'QuizPoll' : 'AnonymousQuizPoll';\n }\n\n if (summary.closed) {\n return 'FinalResults';\n }\n\n return summary.isPublic ? 'PublicPoll' : 'AnonymousPoll';\n}\n\nfunction getReadableVotersCount(lang: LangFn, isQuiz: true | undefined, count?: number) {\n if (!count) {\n return lang(isQuiz ? 'Chat.Quiz.TotalVotesEmpty' : 'Chat.Poll.TotalVotesResultEmpty');\n }\n\n return lang(isQuiz ? 'Answer' : 'Vote', count, 'i');\n}\n\nexport default memo(withGlobal(\n (global, { poll }) => {\n const { recentVoterIds } = poll.results;\n const { serverTimeOffset, users: { byId: usersById } } = global;\n if (!recentVoterIds || recentVoterIds.length === 0) {\n return {};\n }\n\n return {\n recentVoterIds,\n usersById,\n serverTimeOffset,\n };\n },\n)(Poll));\n","import React, { FC, memo, useCallback } from '../../../lib/teact/teact';\n\nimport { ApiMessage } from '../../../api/types';\nimport { ObserveFn } from '../../../hooks/useIntersectionObserver';\nimport { ISettings } from '../../../types';\n\nimport { getMessageWebPage } from '../../../modules/helpers';\nimport { calculateMediaDimensions } from './helpers/mediaDimensions';\nimport renderText from '../../common/helpers/renderText';\nimport trimText from '../../../util/trimText';\nimport buildClassName from '../../../util/buildClassName';\n\nimport SafeLink from '../../common/SafeLink';\nimport Photo from './Photo';\nimport Video from './Video';\n\nimport './WebPage.scss';\n\nconst MAX_TEXT_LENGTH = 170; // symbols\n\ntype OwnProps = {\n message: ApiMessage;\n observeIntersection?: ObserveFn;\n noAvatars?: boolean;\n canAutoLoad?: boolean;\n canAutoPlay?: boolean;\n inPreview?: boolean;\n lastSyncTime?: number;\n isDownloading?: boolean;\n isProtected?: boolean;\n theme: ISettings['theme'];\n onMediaClick?: () => void;\n onCancelMediaTransfer?: () => void;\n};\n\nconst WebPage: FC = ({\n message,\n observeIntersection,\n noAvatars,\n canAutoLoad,\n canAutoPlay,\n inPreview,\n lastSyncTime,\n isDownloading = false,\n isProtected,\n theme,\n onMediaClick,\n onCancelMediaTransfer,\n}) => {\n const webPage = getMessageWebPage(message);\n\n let isSquarePhoto = false;\n if (webPage?.photo && !webPage.video) {\n const { width, height } = calculateMediaDimensions(message);\n isSquarePhoto = width === height;\n }\n\n const handleMediaClick = useCallback(() => {\n onMediaClick!();\n }, [onMediaClick]);\n\n if (!webPage) {\n return undefined;\n }\n\n const {\n siteName,\n url,\n displayUrl,\n title,\n description,\n photo,\n video,\n } = webPage;\n const isMediaInteractive = (photo || video) && onMediaClick && !isSquarePhoto;\n const truncatedDescription = trimText(description, MAX_TEXT_LENGTH);\n\n const className = buildClassName(\n 'WebPage',\n isSquarePhoto && 'with-square-photo',\n !photo && !video && !inPreview && 'without-media',\n video && 'with-video',\n );\n\n return (\n \n {photo && !video && (\n \n )}\n
\n \n {!inPreview && title && (\n

{renderText(title)}

\n )}\n {truncatedDescription && (\n

{renderText(truncatedDescription, ['emoji', 'br'])}

\n )}\n
\n {!inPreview && video && (\n \n )}\n
\n );\n};\n\nexport default memo(WebPage);\n","import React, { FC, memo } from '../../../lib/teact/teact';\n\nimport { ApiMessage } from '../../../api/types';\n\nimport { getMessageInvoice } from '../../../modules/helpers';\nimport { formatCurrency } from '../../../util/formatCurrency';\nimport renderText from '../../common/helpers/renderText';\nimport useLang from '../../../hooks/useLang';\n\nimport './Invoice.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n};\n\nconst Invoice: FC = ({\n message,\n}) => {\n const lang = useLang();\n const invoice = getMessageInvoice(message);\n\n const {\n title,\n text,\n amount,\n currency,\n isTest,\n photoUrl,\n } = invoice!;\n\n return (\n \n {title && (\n

{renderText(title)}

\n )}\n {text && (\n

{renderText(text, ['emoji', 'br'])}

\n )}\n
\n {photoUrl && (\n \n )}\n

\n {formatCurrency(amount, currency, lang.code)}\n {isTest && {lang('PaymentTestInvoice')}}\n

\n
\n
\n );\n};\n\nexport default memo(Invoice);\n","import { MouseEvent as ReactMouseEvent } from 'react';\nimport React, {\n FC,\n useCallback,\n useMemo,\n memo,\n} from '../../../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../../../lib/teact/teactn';\n\nimport { OwnProps as PhotoProps } from '../Photo';\nimport { OwnProps as VideoProps } from '../Video';\n\nimport buildClassName from '../../../../util/buildClassName';\nimport {\n selectIsInSelectMode,\n selectIsMessageSelected,\n} from '../../../../modules/selectors';\n\ntype OwnProps =\n PhotoProps\n & VideoProps;\n\ntype StateProps = {\n isInSelectMode?: boolean;\n isSelected?: boolean;\n};\n\nexport default function withSelectControl(WrappedComponent: FC) {\n const ComponentWithSelectControl: FC = (props) => {\n const {\n isInSelectMode,\n isSelected,\n message,\n dimensions,\n } = props;\n const { toggleMessageSelection } = getDispatch();\n\n const handleMessageSelect = useCallback((e: ReactMouseEvent) => {\n e.stopPropagation();\n toggleMessageSelection({ messageId: message.id, withShift: e?.shiftKey });\n }, [toggleMessageSelection, message]);\n\n const newProps = useMemo(() => {\n return {\n ...props,\n isInSelectMode,\n isSelected,\n dimensions: {\n ...props.dimensions,\n x: 0,\n y: 0,\n },\n onClick: isInSelectMode ? undefined : props.onClick,\n };\n }, [props, isInSelectMode, isSelected]);\n\n return (\n \n {isInSelectMode && (\n
\n {isSelected && (\n \n )}\n
\n )}\n {/* eslint-disable-next-line react/jsx-props-no-spreading */}\n \n \n );\n };\n\n return memo(withGlobal(\n (global, ownProps) => {\n const { message } = ownProps;\n return {\n isInSelectMode: selectIsInSelectMode(global),\n isSelected: selectIsMessageSelected(global, message.id),\n };\n },\n )(ComponentWithSelectControl));\n}\n","import React, { FC, useCallback } from '../../../lib/teact/teact';\n\nimport { GlobalState } from '../../../global/types';\nimport { ApiMessage } from '../../../api/types';\nimport { IAlbum, ISettings } from '../../../types';\nimport { AlbumRectPart, IAlbumLayout } from './helpers/calculateAlbumLayout';\n\nimport { getMessageContent } from '../../../modules/helpers';\nimport { getDispatch, getGlobal, withGlobal } from '../../../lib/teact/teactn';\nimport withSelectControl from './hocs/withSelectControl';\nimport { ObserveFn } from '../../../hooks/useIntersectionObserver';\nimport {\n selectActiveDownloadIds,\n selectCanAutoLoadMedia,\n selectCanAutoPlayMedia,\n selectTheme,\n} from '../../../modules/selectors';\n\nimport Photo from './Photo';\nimport Video from './Video';\n\nimport './Album.scss';\n\nconst PhotoWithSelect = withSelectControl(Photo);\nconst VideoWithSelect = withSelectControl(Video);\n\ntype OwnProps = {\n album: IAlbum;\n observeIntersection: ObserveFn;\n hasCustomAppendix?: boolean;\n lastSyncTime?: number;\n isOwn: boolean;\n isProtected?: boolean;\n albumLayout: IAlbumLayout;\n onMediaClick: (messageId: number) => void;\n};\n\ntype StateProps = {\n theme: ISettings['theme'];\n uploadsById: GlobalState['fileUploads']['byMessageLocalId'];\n activeDownloadIds: number[];\n};\n\nconst Album: FC = ({\n album,\n observeIntersection,\n hasCustomAppendix,\n lastSyncTime,\n isOwn,\n isProtected,\n albumLayout,\n onMediaClick,\n uploadsById,\n activeDownloadIds,\n theme,\n}) => {\n const { cancelSendingMessage } = getDispatch();\n\n const mediaCount = album.messages.length;\n\n const handleCancelUpload = useCallback((message: ApiMessage) => {\n cancelSendingMessage({ chatId: message.chatId, messageId: message.id });\n }, [cancelSendingMessage]);\n\n function renderAlbumMessage(message: ApiMessage, index: number) {\n const { photo, video } = getMessageContent(message);\n const fileUpload = uploadsById[message.previousLocalId || message.id];\n const uploadProgress = fileUpload?.progress;\n const { dimensions, sides } = albumLayout.layout[index];\n\n // Ignoring global updates is a known drawback here\n const canAutoLoad = selectCanAutoLoadMedia(getGlobal(), message);\n const canAutoPlay = selectCanAutoPlayMedia(getGlobal(), message);\n\n if (photo) {\n const shouldAffectAppendix = hasCustomAppendix && (\n // eslint-disable-next-line no-bitwise\n (isOwn ? index === mediaCount - 1 : Boolean(sides & AlbumRectPart.Left && sides & AlbumRectPart.Bottom))\n );\n\n return (\n \n );\n } else if (video) {\n return (\n \n );\n }\n\n return undefined;\n }\n\n const { width: containerWidth, height: containerHeight } = albumLayout.containerStyle;\n\n return (\n \n {album.messages.map(renderAlbumMessage)}\n \n );\n};\n\nexport default withGlobal(\n (global, { album }): StateProps => {\n const { chatId } = album.mainMessage;\n const theme = selectTheme(global);\n const activeDownloadIds = selectActiveDownloadIds(global, chatId);\n return {\n theme,\n uploadsById: global.fileUploads.byMessageLocalId,\n activeDownloadIds,\n };\n },\n)(Album);\n","import React, {\n FC,\n useCallback,\n useEffect,\n useRef,\n useState,\n} from '../../../lib/teact/teact';\nimport { getDispatch } from '../../../lib/teact/teactn';\n\nimport { ApiMediaFormat, ApiMessage } from '../../../api/types';\n\nimport { ROUND_VIDEO_DIMENSIONS_PX } from '../../common/helpers/mediaDimensions';\nimport { getMessageMediaFormat, getMessageMediaHash } from '../../../modules/helpers';\nimport { formatMediaDuration } from '../../../util/dateFormat';\nimport buildClassName from '../../../util/buildClassName';\nimport { stopCurrentAudio } from '../../../util/audioPlayer';\nimport safePlay from '../../../util/safePlay';\nimport { fastRaf } from '../../../util/schedulers';\nimport { ObserveFn, useIsIntersecting } from '../../../hooks/useIntersectionObserver';\nimport useMediaWithLoadProgress from '../../../hooks/useMediaWithLoadProgress';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useMediaTransition from '../../../hooks/useMediaTransition';\nimport usePrevious from '../../../hooks/usePrevious';\nimport useBuffering from '../../../hooks/useBuffering';\nimport useVideoCleanup from '../../../hooks/useVideoCleanup';\nimport useVideoAutoPause from './hooks/useVideoAutoPause';\nimport useBlurredMediaThumbRef from './hooks/useBlurredMediaThumbRef';\n\nimport ProgressSpinner from '../../ui/ProgressSpinner';\n\nimport './RoundVideo.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n observeIntersection: ObserveFn;\n canAutoLoad?: boolean;\n lastSyncTime?: number;\n isDownloading?: boolean;\n};\n\nlet currentOnRelease: NoneToVoidFunction;\n\nfunction createCapture(onRelease: NoneToVoidFunction) {\n return () => {\n if (currentOnRelease) {\n currentOnRelease();\n }\n\n currentOnRelease = onRelease;\n };\n}\n\nconst RoundVideo: FC = ({\n message,\n observeIntersection,\n canAutoLoad,\n lastSyncTime,\n isDownloading,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const playingProgressRef = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const playerRef = useRef(null);\n\n const video = message.content.video!;\n\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n\n const [isLoadAllowed, setIsLoadAllowed] = useState(canAutoLoad);\n const shouldLoad = Boolean(isLoadAllowed && isIntersecting && lastSyncTime);\n const { mediaData, loadProgress } = useMediaWithLoadProgress(\n getMessageMediaHash(message, 'inline'),\n !shouldLoad,\n getMessageMediaFormat(message, 'inline'),\n lastSyncTime,\n );\n\n const { loadProgress: downloadProgress } = useMediaWithLoadProgress(\n getMessageMediaHash(message, 'download'),\n !isDownloading,\n ApiMediaFormat.BlobUrl,\n lastSyncTime,\n );\n const thumbRef = useBlurredMediaThumbRef(message, mediaData);\n\n const { isBuffered, bufferingHandlers } = useBuffering();\n const isTransferring = (isLoadAllowed && !isBuffered) || isDownloading;\n const wasLoadDisabled = usePrevious(isLoadAllowed) === false;\n\n const transitionClassNames = useMediaTransition(mediaData);\n const {\n shouldRender: shouldSpinnerRender,\n transitionClassNames: spinnerClassNames,\n } = useShowTransition(isTransferring || !isBuffered, undefined, wasLoadDisabled);\n\n const [isActivated, setIsActivated] = useState(false);\n const [progress, setProgress] = useState(0);\n\n useEffect(() => {\n if (!isActivated) {\n return;\n }\n\n const svgCenter = ROUND_VIDEO_DIMENSIONS_PX / 2;\n const svgMargin = 6;\n const circumference = (svgCenter - svgMargin) * 2 * Math.PI;\n const strokeDashOffset = circumference - progress * circumference;\n\n const playerEl = playerRef.current!;\n const playingProgressEl = playingProgressRef.current!;\n const svgEl = playingProgressEl.firstElementChild;\n\n if (!svgEl) {\n playingProgressEl.innerHTML = `\n \n \n `;\n } else {\n (svgEl.firstElementChild as SVGElement).setAttribute('stroke-dashoffset', strokeDashOffset.toString());\n }\n\n setProgress(playerEl.currentTime / playerEl.duration);\n }, [isActivated, progress]);\n\n const shouldPlay = Boolean(mediaData && isIntersecting);\n\n const stopPlaying = () => {\n setIsActivated(false);\n setProgress(0);\n safePlay(playerRef.current!);\n\n fastRaf(() => {\n playingProgressRef.current!.innerHTML = '';\n });\n };\n\n const capturePlaying = createCapture(stopPlaying);\n\n useEffect(() => {\n if (!playerRef.current) {\n return;\n }\n\n if (shouldPlay) {\n safePlay(playerRef.current);\n } else {\n playerRef.current.pause();\n }\n }, [shouldPlay]);\n\n useVideoAutoPause(playerRef, shouldPlay);\n useVideoCleanup(playerRef, [mediaData]);\n\n const handleClick = useCallback(() => {\n if (!mediaData) {\n setIsLoadAllowed((isAllowed) => !isAllowed);\n\n return;\n }\n\n if (isDownloading) {\n getDispatch().cancelMessageMediaDownload({ message });\n return;\n }\n\n const playerEl = playerRef.current!;\n if (isActivated) {\n if (playerEl.paused) {\n safePlay(playerEl);\n stopCurrentAudio();\n } else {\n playerEl.pause();\n }\n } else {\n capturePlaying();\n // Pause is a workaround for iOS Safari – otherwise it stops video after several frames\n playerEl.pause();\n playerEl.currentTime = 0;\n safePlay(playerEl);\n stopCurrentAudio();\n\n setIsActivated(true);\n }\n }, [capturePlaying, isActivated, isDownloading, mediaData, message]);\n\n const handleTimeUpdate = useCallback((e: React.UIEvent) => {\n const playerEl = e.currentTarget;\n\n setProgress(playerEl.currentTime / playerEl.duration);\n }, []);\n\n const videoClassName = buildClassName('full-media', transitionClassNames);\n\n return (\n \n
\n \n
\n {mediaData && (\n
\n {/* eslint-disable-next-line jsx-a11y/media-has-caption */}\n \n \n \n
\n )}\n
\n {shouldSpinnerRender && (\n
\n \n
\n )}\n {!mediaData && !isLoadAllowed && (\n \n )}\n
\n {isActivated ? formatMediaDuration(playerRef.current!.currentTime) : formatMediaDuration(video.duration)}\n {(!isActivated || playerRef.current!.paused) && }\n
\n
\n );\n};\n\nexport default RoundVideo;\n","import React, { FC } from '../../../lib/teact/teact';\n\nimport { ApiKeyboardButton, ApiMessage } from '../../../api/types';\n\nimport { RE_TME_LINK } from '../../../config';\nimport renderText from '../../common/helpers/renderText';\nimport useLang from '../../../hooks/useLang';\n\nimport Button from '../../ui/Button';\n\nimport './InlineButtons.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n onClick: ({ button }: { button: ApiKeyboardButton }) => void;\n};\n\nconst InlineButtons: FC = ({ message, onClick }) => {\n const lang = useLang();\n\n return (\n
\n {message.inlineButtons!.map((row) => (\n
\n {row.map((button) => (\n onClick({ button })}\n >\n {renderText(lang(button.text))}\n {button.type === 'buy' && }\n {button.type === 'url' && !button.value!.match(RE_TME_LINK) && }\n \n ))}\n
\n ))}\n
\n );\n};\n\nexport default InlineButtons;\n","import React, {\n FC, memo, useCallback, useMemo,\n} from '../../../lib/teact/teact';\nimport { getDispatch, getGlobal } from '../../../lib/teact/teactn';\n\nimport {\n ApiChat, ApiThreadInfo, ApiUser,\n} from '../../../api/types';\n\nimport { isUserId } from '../../../modules/helpers';\nimport { formatIntegerCompact } from '../../../util/textFormat';\nimport buildClassName from '../../../util/buildClassName';\nimport useLang from '../../../hooks/useLang';\n\nimport Avatar from '../../common/Avatar';\n\nimport './CommentButton.scss';\n\ntype OwnProps = {\n threadInfo: ApiThreadInfo;\n disabled?: boolean;\n};\n\nconst CommentButton: FC = ({\n threadInfo,\n disabled,\n}) => {\n const { openChat } = getDispatch();\n\n const lang = useLang();\n const {\n threadId, chatId, messagesCount, lastMessageId, lastReadInboxMessageId, recentReplierIds,\n } = threadInfo;\n\n const handleClick = useCallback(() => {\n openChat({ id: chatId, threadId });\n }, [openChat, chatId, threadId]);\n\n const recentRepliers = useMemo(() => {\n if (!recentReplierIds?.length) {\n return undefined;\n }\n\n // No need for expensive global updates on chats and users, so we avoid them\n const { users: { byId: usersById }, chats: { byId: chatsById } } = getGlobal();\n\n return recentReplierIds.map((peerId) => {\n return isUserId(peerId) ? usersById[peerId] : chatsById[peerId];\n }).filter(Boolean);\n }, [recentReplierIds]);\n\n if (messagesCount === undefined) {\n return undefined;\n }\n\n function renderRecentRepliers() {\n return (\n recentRepliers && recentRepliers.length > 0 && (\n
\n {recentRepliers.map((user) => (\n \n ))}\n
\n )\n );\n }\n\n const hasUnread = Boolean(lastReadInboxMessageId && lastMessageId && lastReadInboxMessageId < lastMessageId);\n\n return (\n \n \n {(!recentRepliers || recentRepliers.length === 0) && }\n {renderRecentRepliers()}\n
\n {messagesCount ? lang('Comments', messagesCount, 'i') : lang('LeaveAComment')}\n
\n \n \n );\n};\n\nexport default memo(CommentButton);\n","import React, {\n FC,\n memo,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n} from '../../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../../lib/teact/teactn';\n\nimport { MessageListType } from '../../../global/types';\nimport {\n ApiMessage,\n ApiMessageOutgoingStatus,\n ApiUser,\n ApiChat,\n ApiSticker,\n ApiThreadInfo,\n} from '../../../api/types';\nimport {\n AudioOrigin, FocusDirection, IAlbum, ISettings,\n} from '../../../types';\n\nimport { IS_ANDROID, IS_TOUCH_ENV } from '../../../util/environment';\nimport {\n selectChat,\n selectChatMessage,\n selectUploadProgress,\n selectIsChatWithSelf,\n selectOutgoingStatus,\n selectUser,\n selectIsMessageFocused,\n selectCurrentTextSearch,\n selectAnimatedEmoji,\n selectIsInSelectMode,\n selectIsMessageSelected,\n selectIsDocumentGroupSelected,\n selectSender,\n selectForwardedSender,\n selectThreadTopMessageId,\n selectCanAutoLoadMedia,\n selectCanAutoPlayMedia,\n selectShouldLoopStickers,\n selectTheme,\n selectAllowedMessageActions,\n selectIsDownloading,\n selectThreadInfo,\n selectIsMessageProtected,\n} from '../../../modules/selectors';\nimport {\n getMessageContent,\n isOwnMessage,\n isReplyMessage,\n isAnonymousOwnMessage,\n isMessageLocal,\n isUserId,\n isChatWithRepliesBot,\n getMessageCustomShape,\n isChatChannel,\n getMessageSingleEmoji,\n getSenderTitle,\n getUserColorKey,\n} from '../../../modules/helpers';\nimport buildClassName from '../../../util/buildClassName';\nimport useEnsureMessage from '../../../hooks/useEnsureMessage';\nimport useContextMenuHandlers from '../../../hooks/useContextMenuHandlers';\nimport { renderMessageText } from '../../common/helpers/renderMessageText';\nimport { ROUND_VIDEO_DIMENSIONS_PX } from '../../common/helpers/mediaDimensions';\nimport { buildContentClassName, isEmojiOnlyMessage } from './helpers/buildContentClassName';\nimport { getMinMediaWidth, calculateMediaDimensions } from './helpers/mediaDimensions';\nimport { calculateAlbumLayout } from './helpers/calculateAlbumLayout';\nimport renderText from '../../common/helpers/renderText';\nimport calculateAuthorWidth from './helpers/calculateAuthorWidth';\nimport { ObserveFn, useOnIntersect } from '../../../hooks/useIntersectionObserver';\nimport useLang from '../../../hooks/useLang';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useFlag from '../../../hooks/useFlag';\nimport useFocusMessage from './hooks/useFocusMessage';\nimport useOuterHandlers from './hooks/useOuterHandlers';\nimport useInnerHandlers from './hooks/useInnerHandlers';\n\nimport Button from '../../ui/Button';\nimport Avatar from '../../common/Avatar';\nimport EmbeddedMessage from '../../common/EmbeddedMessage';\nimport Document from '../../common/Document';\nimport Audio from '../../common/Audio';\nimport MessageMeta from './MessageMeta';\nimport ContextMenuContainer from './ContextMenuContainer.async';\nimport Sticker from './Sticker';\nimport AnimatedEmoji from '../../common/AnimatedEmoji';\nimport Photo from './Photo';\nimport Video from './Video';\nimport Contact from './Contact';\nimport Poll from './Poll';\nimport WebPage from './WebPage';\nimport Invoice from './Invoice';\nimport Album from './Album';\nimport RoundVideo from './RoundVideo';\nimport InlineButtons from './InlineButtons';\nimport CommentButton from './CommentButton';\n\nimport './Message.scss';\n\ntype MessagePositionProperties = {\n isFirstInGroup: boolean;\n isLastInGroup: boolean;\n isFirstInDocumentGroup: boolean;\n isLastInDocumentGroup: boolean;\n isLastInList: boolean;\n};\n\ntype OwnProps =\n {\n message: ApiMessage;\n observeIntersectionForBottom: ObserveFn;\n observeIntersectionForMedia: ObserveFn;\n observeIntersectionForAnimatedStickers: ObserveFn;\n album?: IAlbum;\n noAvatars?: boolean;\n withAvatar?: boolean;\n withSenderName?: boolean;\n threadId: number;\n messageListType: MessageListType;\n noComments: boolean;\n appearanceOrder: number;\n }\n & MessagePositionProperties;\n\ntype StateProps = {\n theme: ISettings['theme'];\n forceSenderName?: boolean;\n chatUsername?: string;\n sender?: ApiUser | ApiChat;\n originSender?: ApiUser | ApiChat;\n botSender?: ApiUser;\n isThreadTop?: boolean;\n shouldHideReply?: boolean;\n replyMessage?: ApiMessage;\n replyMessageSender?: ApiUser | ApiChat;\n outgoingStatus?: ApiMessageOutgoingStatus;\n uploadProgress?: number;\n isProtected?: boolean;\n isFocused?: boolean;\n focusDirection?: FocusDirection;\n noFocusHighlight?: boolean;\n isResizingContainer?: boolean;\n isForwarding?: boolean;\n isChatWithSelf?: boolean;\n isRepliesChat?: boolean;\n isChannel?: boolean;\n canReply?: boolean;\n lastSyncTime?: number;\n highlight?: string;\n isSingleEmoji?: boolean;\n animatedEmoji?: ApiSticker;\n isInSelectMode?: boolean;\n isSelected?: boolean;\n isGroupSelected?: boolean;\n isDownloading: boolean;\n threadId?: number;\n isPinnedList?: boolean;\n canAutoLoadMedia?: boolean;\n canAutoPlayMedia?: boolean;\n shouldLoopStickers?: boolean;\n autoLoadFileMaxSizeMb: number;\n threadInfo?: ApiThreadInfo;\n};\n\nconst NBSP = '\\u00A0';\nconst GROUP_MESSAGE_HOVER_ATTRIBUTE = 'data-is-document-group-hover';\n// eslint-disable-next-line max-len\nconst APPENDIX_OWN = { __html: '' };\n// eslint-disable-next-line max-len\nconst APPENDIX_NOT_OWN = { __html: '' };\nconst APPEARANCE_DELAY = 10;\nconst NO_MEDIA_CORNERS_THRESHOLD = 18;\n\nconst Message: FC = ({\n message,\n chatUsername,\n observeIntersectionForBottom,\n observeIntersectionForMedia,\n observeIntersectionForAnimatedStickers,\n album,\n noAvatars,\n withAvatar,\n withSenderName,\n noComments,\n appearanceOrder,\n isFirstInGroup,\n isLastInGroup,\n isFirstInDocumentGroup,\n isLastInDocumentGroup,\n isLastInList,\n theme,\n forceSenderName,\n sender,\n originSender,\n botSender,\n isThreadTop,\n shouldHideReply,\n replyMessage,\n replyMessageSender,\n outgoingStatus,\n uploadProgress,\n isProtected,\n isFocused,\n focusDirection,\n noFocusHighlight,\n isResizingContainer,\n isForwarding,\n isChatWithSelf,\n isRepliesChat,\n isChannel,\n canReply,\n lastSyncTime,\n highlight,\n animatedEmoji,\n isInSelectMode,\n isSelected,\n isGroupSelected,\n threadId,\n messageListType,\n isPinnedList,\n isDownloading,\n canAutoLoadMedia,\n canAutoPlayMedia,\n shouldLoopStickers,\n autoLoadFileMaxSizeMb,\n threadInfo,\n}) => {\n const {\n toggleMessageSelection,\n clickInlineButton,\n disableContextMenuHint,\n } = getDispatch();\n\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const bottomMarkerRef = useRef(null);\n\n const lang = useLang();\n\n useOnIntersect(bottomMarkerRef, observeIntersectionForBottom);\n\n const {\n isContextMenuOpen, contextMenuPosition,\n handleBeforeContextMenu, handleContextMenu: onContextMenu,\n handleContextMenuClose, handleContextMenuHide,\n } = useContextMenuHandlers(ref, IS_TOUCH_ENV && isInSelectMode, true, IS_ANDROID);\n\n useEffect(() => {\n if (isContextMenuOpen) {\n disableContextMenuHint();\n }\n }, [isContextMenuOpen, disableContextMenuHint]);\n\n const noAppearanceAnimation = appearanceOrder <= 0;\n const [isShown, markShown] = useFlag(noAppearanceAnimation);\n useEffect(() => {\n if (noAppearanceAnimation) {\n return;\n }\n\n setTimeout(markShown, appearanceOrder * APPEARANCE_DELAY);\n }, [appearanceOrder, markShown, noAppearanceAnimation]);\n const { transitionClassNames } = useShowTransition(isShown, undefined, noAppearanceAnimation, false);\n\n const { id: messageId, chatId } = message;\n\n const isLocal = isMessageLocal(message);\n const isOwn = isOwnMessage(message);\n const isScheduled = messageListType === 'scheduled' || message.isScheduled;\n const hasReply = isReplyMessage(message) && !shouldHideReply;\n const hasThread = Boolean(threadInfo) && messageListType === 'thread';\n const customShape = getMessageCustomShape(message);\n const { forwardInfo, viaBotId } = message;\n const asForwarded = (\n forwardInfo\n && (!isChatWithSelf || isScheduled)\n && !isRepliesChat\n && !forwardInfo.isLinkedChannelPost\n && !customShape\n );\n const isInDocumentGroup = Boolean(message.groupedId) && !message.isInAlbum;\n const isAlbum = Boolean(album) && album!.messages.length > 1;\n const {\n text, photo, video, audio, voice, document, sticker, contact, poll, webPage, invoice,\n } = getMessageContent(message);\n const textParts = renderMessageText(message, highlight, isEmojiOnlyMessage(customShape));\n const isContextMenuShown = contextMenuPosition !== undefined;\n const signature = (\n (isChannel && message.adminTitle) || (!asForwarded && forwardInfo?.adminTitle) || undefined\n );\n const metaSafeAuthorWidth = useMemo(() => {\n return signature ? calculateAuthorWidth(signature) : undefined;\n }, [signature]);\n const canShowActionButton = (\n !(isContextMenuShown || isInSelectMode || isForwarding)\n && (!isInDocumentGroup || isLastInDocumentGroup)\n );\n const canForward = isChannel && !isScheduled;\n const canFocus = Boolean(isPinnedList\n || (forwardInfo\n && (forwardInfo.isChannelPost || (isChatWithSelf && !isOwn) || isRepliesChat)\n && forwardInfo.fromMessageId\n ));\n const avatarPeer = forwardInfo && (isChatWithSelf || isRepliesChat || !sender) ? originSender : sender;\n const senderPeer = forwardInfo ? originSender : sender;\n\n const selectMessage = useCallback((e?: React.MouseEvent, groupedId?: string) => {\n toggleMessageSelection({\n messageId,\n groupedId,\n ...(e?.shiftKey && { withShift: true }),\n ...(isAlbum && { childMessageIds: album!.messages.map(({ id }) => id) }),\n });\n }, [toggleMessageSelection, messageId, isAlbum, album]);\n\n const {\n handleMouseDown,\n handleClick,\n handleContextMenu,\n handleDoubleClick,\n handleContentDoubleClick,\n isSwiped,\n } = useOuterHandlers(\n selectMessage,\n ref,\n messageId,\n isAlbum,\n Boolean(isInSelectMode),\n Boolean(canReply),\n Boolean(isProtected),\n onContextMenu,\n handleBeforeContextMenu,\n );\n\n const {\n handleAvatarClick,\n handleSenderClick,\n handleViaBotClick,\n handleReplyClick,\n handleMediaClick,\n handleAudioPlay,\n handleAlbumMediaClick,\n handleMetaClick,\n handleReadMedia,\n handleCancelUpload,\n handleVoteSend,\n handleGroupForward,\n handleForward,\n handleFocus,\n handleFocusForwarded,\n handleDocumentGroupSelectAll,\n } = useInnerHandlers(\n lang,\n selectMessage,\n message,\n chatId,\n threadId,\n isInDocumentGroup,\n asForwarded,\n isScheduled,\n isRepliesChat,\n album,\n avatarPeer,\n senderPeer,\n botSender,\n );\n\n const containerClassName = buildClassName(\n 'Message message-list-item',\n isFirstInGroup && 'first-in-group',\n isProtected && 'is-protected',\n isLastInGroup && 'last-in-group',\n isFirstInDocumentGroup && 'first-in-document-group',\n isLastInDocumentGroup && 'last-in-document-group',\n isLastInList && 'last-in-list',\n isOwn && 'own',\n Boolean(message.views) && 'has-views',\n message.isEdited && 'was-edited',\n hasReply && 'has-reply',\n isContextMenuShown && 'has-menu-open',\n isFocused && !noFocusHighlight && 'focused',\n isForwarding && 'is-forwarding',\n message.isDeleting && 'is-deleting',\n isInDocumentGroup && 'is-in-document-group',\n isAlbum && 'is-album',\n message.hasUnreadMention && 'has-unread-mention',\n isSelected && 'is-selected',\n isInSelectMode && 'is-in-selection-mode',\n isThreadTop && 'is-thread-top',\n Boolean(message.inlineButtons) && 'has-inline-buttons',\n isSwiped && 'is-swiped',\n transitionClassNames,\n );\n const contentClassName = buildContentClassName(message, {\n hasReply,\n customShape,\n isLastInGroup,\n asForwarded,\n hasThread,\n forceSenderName,\n hasComments: threadInfo && threadInfo?.messagesCount > 0,\n hasActionButton: canForward || canFocus,\n });\n const withCommentButton = (\n threadInfo && (!isInDocumentGroup || isLastInDocumentGroup) && messageListType === 'thread' && !noComments\n );\n const withAppendix = contentClassName.includes('has-appendix');\n\n useEnsureMessage(\n isRepliesChat && message.replyToChatId ? message.replyToChatId : chatId,\n hasReply ? message.replyToMessageId : undefined,\n replyMessage,\n message.id,\n );\n useFocusMessage(ref, chatId, isFocused, focusDirection, noFocusHighlight, isResizingContainer);\n\n let style = '';\n let calculatedWidth;\n let noMediaCorners = false;\n const albumLayout = useMemo(() => {\n return isAlbum ? calculateAlbumLayout(isOwn, Boolean(asForwarded), Boolean(noAvatars), album!) : undefined;\n }, [isAlbum, isOwn, asForwarded, noAvatars, album]);\n\n const extraPadding = asForwarded ? 28 : 0;\n if (!isAlbum && (photo || video)) {\n let width: number | undefined;\n if (photo) {\n width = calculateMediaDimensions(message, noAvatars).width;\n } else if (video) {\n if (video.isRound) {\n width = ROUND_VIDEO_DIMENSIONS_PX;\n } else {\n width = calculateMediaDimensions(message, noAvatars).width;\n }\n }\n\n if (width) {\n calculatedWidth = Math.max(getMinMediaWidth(Boolean(text), withCommentButton), width);\n if (calculatedWidth - width > NO_MEDIA_CORNERS_THRESHOLD) {\n noMediaCorners = true;\n }\n }\n } else if (albumLayout) {\n calculatedWidth = Math.max(getMinMediaWidth(Boolean(text), withCommentButton), albumLayout.containerStyle.width);\n if (calculatedWidth - albumLayout.containerStyle.width > NO_MEDIA_CORNERS_THRESHOLD) {\n noMediaCorners = true;\n }\n }\n\n if (calculatedWidth) {\n style = `width: ${calculatedWidth + extraPadding}px`;\n }\n\n function renderAvatar() {\n const isAvatarPeerUser = avatarPeer && isUserId(avatarPeer.id);\n const avatarUser = (avatarPeer && isAvatarPeerUser) ? avatarPeer as ApiUser : undefined;\n const avatarChat = (avatarPeer && !isAvatarPeerUser) ? avatarPeer as ApiChat : undefined;\n const hiddenName = (!avatarPeer && forwardInfo) ? forwardInfo.hiddenUserName : undefined;\n\n return (\n \n );\n }\n\n function renderContent() {\n const className = buildClassName(\n 'content-inner',\n asForwarded && 'forwarded-message',\n hasReply && 'reply-message',\n noMediaCorners && 'no-media-corners',\n );\n const hasCustomAppendix = isLastInGroup && !textParts && !asForwarded && !hasThread;\n const shouldInlineMeta = !webPage && !animatedEmoji && textParts;\n const textContentClass = buildClassName(\n 'text-content',\n shouldInlineMeta && 'with-meta',\n outgoingStatus && 'with-outgoing-icon',\n );\n\n return (\n
\n {renderSenderName()}\n {hasReply && (\n \n )}\n {sticker && (\n \n )}\n {animatedEmoji && (\n \n )}\n {isAlbum && (\n \n )}\n {!isAlbum && photo && (\n \n )}\n {!isAlbum && video && video.isRound && (\n \n )}\n {!isAlbum && video && !video.isRound && (\n \n )}\n {(audio || voice) && (\n \n )}\n {document && (\n \n )}\n {contact && (\n \n )}\n {poll && (\n \n )}\n {!animatedEmoji && textParts && (\n

\n {textParts}\n {shouldInlineMeta && (\n \n )}\n

\n )}\n {webPage && (\n \n )}\n {invoice && }\n
\n );\n }\n\n function renderSenderName() {\n const shouldRender = !(customShape && !viaBotId) && (\n (withSenderName && !photo && !video) || asForwarded || viaBotId || forceSenderName\n ) && (!isInDocumentGroup || isFirstInDocumentGroup) && !(hasReply && customShape);\n\n if (!shouldRender) {\n return undefined;\n }\n\n let senderTitle;\n let senderColor;\n if (senderPeer && !(customShape && viaBotId)) {\n senderTitle = getSenderTitle(lang, senderPeer);\n\n if (!asForwarded) {\n senderColor = `color-${getUserColorKey(senderPeer)}`;\n }\n } else if (forwardInfo?.hiddenUserName) {\n senderTitle = forwardInfo.hiddenUserName;\n }\n\n return (\n
\n {senderTitle ? (\n \n {renderText(senderTitle)}\n \n ) : !botSender ? (\n NBSP\n ) : undefined}\n {botSender && (\n <>\n {lang('ViaBot')}\n \n {renderText(`@${botSender.username}`)}\n \n \n )}\n {forwardInfo?.isLinkedChannelPost ? (\n {lang('DiscussChannel')}\n ) : message.adminTitle && !isChannel ? (\n {message.adminTitle}\n ) : undefined}\n
\n );\n }\n\n return (\n \n \n {!isInDocumentGroup && (\n
\n {isSelected && }\n
\n )}\n {isLastInDocumentGroup && (\n \n {isGroupSelected && (\n \n )}\n \n )}\n {withAvatar && renderAvatar()}\n \n \n {asForwarded && (!isInDocumentGroup || isFirstInDocumentGroup) && (\n
{lang('ForwardedMessage')}
\n )}\n {renderContent()}\n {(!isInDocumentGroup || isLastInDocumentGroup) && !(!webPage && !animatedEmoji && textParts) && (\n \n )}\n {canShowActionButton && canForward ? (\n \n \n \n ) : canShowActionButton && canFocus ? (\n \n \n \n ) : undefined}\n {withCommentButton && }\n {withAppendix && (\n
\n )}\n
\n {message.inlineButtons && (\n \n )}\n \n {contextMenuPosition && (\n \n )}\n \n );\n};\n\nfunction handleDocumentGroupMouseEnter(e: React.MouseEvent) {\n const lastGroupElement = getLastElementInDocumentGroup(e.currentTarget);\n if (lastGroupElement) {\n lastGroupElement.setAttribute(GROUP_MESSAGE_HOVER_ATTRIBUTE, '');\n }\n}\n\nfunction handleDocumentGroupMouseLeave(e: React.MouseEvent) {\n const lastGroupElement = getLastElementInDocumentGroup(e.currentTarget);\n if (lastGroupElement) {\n lastGroupElement.removeAttribute(GROUP_MESSAGE_HOVER_ATTRIBUTE);\n }\n}\n\nfunction getLastElementInDocumentGroup(element: Element) {\n let current: Element | null = element;\n\n do {\n current = current.nextElementSibling;\n } while (current && !current.classList.contains('last-in-document-group'));\n\n return current;\n}\n\nexport default memo(withGlobal(\n (global, ownProps): StateProps => {\n const { focusedMessage, forwardMessages, lastSyncTime } = global;\n const {\n message, album, withSenderName, withAvatar, threadId, messageListType,\n } = ownProps;\n const {\n id, chatId, viaBotId, replyToChatId, replyToMessageId, isOutgoing, threadInfo,\n } = message;\n\n const chat = selectChat(global, chatId);\n const isChatWithSelf = selectIsChatWithSelf(global, chatId);\n const isRepliesChat = isChatWithRepliesBot(chatId);\n const isChannel = chat && isChatChannel(chat);\n const chatUsername = chat?.username;\n\n const forceSenderName = !isChatWithSelf && isAnonymousOwnMessage(message);\n const canShowSender = withSenderName || withAvatar || forceSenderName;\n const sender = selectSender(global, message);\n const originSender = selectForwardedSender(global, message);\n const botSender = viaBotId ? selectUser(global, viaBotId) : undefined;\n\n const threadTopMessageId = threadId ? selectThreadTopMessageId(global, chatId, threadId) : undefined;\n const isThreadTop = message.id === threadTopMessageId;\n\n const shouldHideReply = replyToMessageId === threadTopMessageId;\n const replyMessage = replyToMessageId && !shouldHideReply\n ? selectChatMessage(global, isRepliesChat && replyToChatId ? replyToChatId : chatId, replyToMessageId)\n : undefined;\n const replyMessageSender = replyMessage && selectSender(global, replyMessage);\n\n const uploadProgress = selectUploadProgress(global, message);\n const isFocused = messageListType === 'thread' && (\n album\n ? album.messages.some((m) => selectIsMessageFocused(global, m))\n : selectIsMessageFocused(global, message)\n );\n\n const {\n direction: focusDirection, noHighlight: noFocusHighlight, isResizingContainer,\n } = (isFocused && focusedMessage) || {};\n\n const isForwarding = forwardMessages.messageIds && forwardMessages.messageIds.includes(id);\n\n const { query: highlight } = selectCurrentTextSearch(global) || {};\n\n const singleEmoji = getMessageSingleEmoji(message);\n let isSelected: boolean;\n\n if (album?.messages) {\n isSelected = album.messages.every(({ id: messageId }) => selectIsMessageSelected(global, messageId));\n } else {\n isSelected = selectIsMessageSelected(global, id);\n }\n\n const { canReply } = (messageListType === 'thread' && selectAllowedMessageActions(global, message, threadId)) || {};\n const isDownloading = selectIsDownloading(global, message);\n const actualThreadInfo = threadInfo\n ? selectThreadInfo(global, threadInfo.chatId, threadInfo.threadId) || threadInfo\n : undefined;\n\n return {\n theme: selectTheme(global),\n chatUsername,\n forceSenderName,\n sender: canShowSender ? sender : undefined,\n originSender,\n botSender,\n shouldHideReply,\n isThreadTop,\n replyMessage,\n replyMessageSender,\n isProtected: selectIsMessageProtected(global, message),\n isFocused,\n isForwarding,\n isChatWithSelf,\n isRepliesChat,\n isChannel,\n canReply,\n lastSyncTime,\n highlight,\n isSingleEmoji: Boolean(singleEmoji),\n animatedEmoji: singleEmoji ? selectAnimatedEmoji(global, singleEmoji) : undefined,\n isInSelectMode: selectIsInSelectMode(global),\n isSelected,\n isGroupSelected: (\n !!message.groupedId && !message.isInAlbum && selectIsDocumentGroupSelected(global, chatId, message.groupedId)\n ),\n threadId,\n isDownloading,\n isPinnedList: messageListType === 'pinned',\n canAutoLoadMedia: selectCanAutoLoadMedia(global, message),\n canAutoPlayMedia: selectCanAutoPlayMedia(global, message),\n autoLoadFileMaxSizeMb: global.settings.byKey.autoLoadFileMaxSizeMb,\n shouldLoopStickers: selectShouldLoopStickers(global),\n threadInfo: actualThreadInfo,\n ...(isOutgoing && { outgoingStatus: selectOutgoingStatus(global, message, messageListType === 'scheduled') }),\n ...(typeof uploadProgress === 'number' && { uploadProgress }),\n ...(isFocused && { focusDirection, noFocusHighlight, isResizingContainer }),\n };\n },\n)(Message));\n","import { RefObject } from 'react';\nimport React, { useEffect } from '../../../../lib/teact/teact';\nimport { getDispatch } from '../../../../lib/teact/teactn';\n\nimport { IS_ANDROID, IS_TOUCH_ENV } from '../../../../util/environment';\nimport windowSize from '../../../../util/windowSize';\nimport { captureEvents, SwipeDirection } from '../../../../util/captureEvents';\nimport useFlag from '../../../../hooks/useFlag';\nimport { preventMessageInputBlur } from '../../helpers/preventMessageInputBlur';\nimport stopEvent from '../../../../util/stopEvent';\n\nconst ANDROID_KEYBOARD_HIDE_DELAY_MS = 350;\nconst SWIPE_ANIMATION_DURATION = 150;\n\nexport default function useOuterHandlers(\n selectMessage: (e?: React.MouseEvent, groupedId?: string) => void,\n containerRef: RefObject,\n messageId: number,\n isAlbum: boolean,\n isInSelectMode: boolean,\n canReply: boolean,\n isProtected: boolean,\n onContextMenu: (e: React.MouseEvent) => void,\n handleBeforeContextMenu: (e: React.MouseEvent) => void,\n) {\n const { setReplyingToId } = getDispatch();\n\n const [isSwiped, markSwiped, unmarkSwiped] = useFlag();\n\n function handleMouseDown(e: React.MouseEvent) {\n preventMessageInputBlur(e);\n handleBeforeContextMenu(e);\n }\n\n function handleClick(e: React.MouseEvent) {\n if (isInSelectMode) {\n selectMessage(e);\n } else if (IS_ANDROID) {\n const target = e.target as HTMLDivElement;\n if (!target.classList.contains('text-content') && !target.classList.contains('Message')) {\n return;\n }\n\n if (windowSize.getIsKeyboardVisible()) {\n setTimeout(() => {\n onContextMenu(e);\n }, ANDROID_KEYBOARD_HIDE_DELAY_MS);\n } else {\n onContextMenu(e);\n }\n }\n }\n\n function handleContextMenu(e: React.MouseEvent) {\n if (IS_ANDROID) {\n if ((e.target as HTMLElement).matches('a[href]')) {\n return;\n }\n\n e.preventDefault();\n selectMessage();\n } else {\n onContextMenu(e);\n }\n }\n\n function handleContainerDoubleClick() {\n setReplyingToId({ messageId });\n }\n\n function stopPropagation(e: React.MouseEvent) {\n e.stopPropagation();\n }\n\n useEffect(() => {\n if (!IS_TOUCH_ENV || isInSelectMode || !canReply) {\n return undefined;\n }\n\n let startedAt: number | undefined;\n return captureEvents(containerRef.current!, {\n selectorToPreventScroll: '.MessageList',\n onSwipe: ((e, direction) => {\n if (direction === SwipeDirection.Left) {\n if (!startedAt) {\n startedAt = Date.now();\n }\n\n markSwiped();\n\n return true;\n }\n\n return false;\n }),\n onRelease: () => {\n if (!startedAt) {\n return;\n }\n\n setReplyingToId({ messageId });\n\n setTimeout(unmarkSwiped, Math.max(0, SWIPE_ANIMATION_DURATION - (Date.now() - startedAt)));\n startedAt = undefined;\n },\n });\n }, [containerRef, isInSelectMode, messageId, setReplyingToId, markSwiped, unmarkSwiped, canReply]);\n\n return {\n handleMouseDown: !isInSelectMode ? handleMouseDown : undefined,\n handleClick,\n handleContextMenu: !isInSelectMode ? handleContextMenu : (isProtected ? stopEvent : undefined),\n handleDoubleClick: !isInSelectMode ? handleContainerDoubleClick : undefined,\n handleContentDoubleClick: !IS_TOUCH_ENV ? stopPropagation : undefined,\n isSwiped,\n };\n}\n","import React, { useCallback } from '../../../../lib/teact/teact';\nimport { getDispatch } from '../../../../lib/teact/teactn';\n\nimport { isUserId } from '../../../../modules/helpers';\nimport { IAlbum, MediaViewerOrigin } from '../../../../types';\nimport {\n ApiChat, ApiMessage, ApiUser, MAIN_THREAD_ID,\n} from '../../../../api/types';\nimport { LangFn } from '../../../../hooks/useLang';\n\nexport default function useInnerHandlers(\n lang: LangFn,\n selectMessage: (e: React.MouseEvent, groupedId?: string) => void,\n message: ApiMessage,\n chatId: string,\n threadId: number,\n isInDocumentGroup: boolean,\n asForwarded?: boolean,\n isScheduled?: boolean,\n isChatWithRepliesBot?: boolean,\n album?: IAlbum,\n avatarPeer?: ApiUser | ApiChat,\n senderPeer?: ApiUser | ApiChat,\n botSender?: ApiUser,\n) {\n const {\n openUserInfo, openChat, showNotification, focusMessage, openMediaViewer, openAudioPlayer,\n markMessagesRead, cancelSendingMessage, sendPollVote, openForwardMenu, focusMessageInComments,\n } = getDispatch();\n\n const {\n id: messageId, forwardInfo, replyToMessageId, replyToChatId, replyToTopMessageId, groupedId,\n } = message;\n\n const handleAvatarClick = useCallback(() => {\n if (!avatarPeer) {\n return;\n }\n\n if (isUserId(avatarPeer.id)) {\n openUserInfo({ id: avatarPeer.id });\n } else {\n openChat({ id: avatarPeer.id });\n }\n }, [avatarPeer, openUserInfo, openChat]);\n\n const handleSenderClick = useCallback(() => {\n if (!senderPeer) {\n showNotification({ message: lang('HidAccount') });\n\n return;\n }\n\n if (asForwarded && forwardInfo?.channelPostId) {\n focusMessage({ chatId: senderPeer.id, messageId: forwardInfo.channelPostId });\n } else if (isUserId(senderPeer.id)) {\n openUserInfo({ id: senderPeer.id });\n } else {\n openChat({ id: senderPeer.id });\n }\n }, [\n asForwarded, focusMessage, forwardInfo, lang, openChat, openUserInfo, senderPeer, showNotification,\n ]);\n\n const handleViaBotClick = useCallback(() => {\n if (!botSender) {\n return;\n }\n\n openUserInfo({ id: botSender.id });\n }, [botSender, openUserInfo]);\n\n const handleReplyClick = useCallback((): void => {\n focusMessage({\n chatId: isChatWithRepliesBot && replyToChatId ? replyToChatId : chatId,\n threadId,\n messageId: replyToMessageId,\n replyMessageId: isChatWithRepliesBot && replyToChatId ? undefined : messageId,\n });\n }, [focusMessage, isChatWithRepliesBot, replyToChatId, chatId, threadId, replyToMessageId, messageId]);\n\n const handleMediaClick = useCallback((): void => {\n openMediaViewer({\n chatId, threadId, messageId, origin: isScheduled ? MediaViewerOrigin.ScheduledInline : MediaViewerOrigin.Inline,\n });\n }, [chatId, threadId, messageId, openMediaViewer, isScheduled]);\n\n const handleAudioPlay = useCallback((): void => {\n openAudioPlayer({ chatId, messageId });\n }, [chatId, messageId, openAudioPlayer]);\n\n const handleAlbumMediaClick = useCallback((albumMessageId: number): void => {\n openMediaViewer({\n chatId,\n threadId,\n messageId: albumMessageId,\n origin: isScheduled ? MediaViewerOrigin.ScheduledAlbum : MediaViewerOrigin.Album,\n });\n }, [chatId, threadId, openMediaViewer, isScheduled]);\n\n const handleReadMedia = useCallback((): void => {\n markMessagesRead({ messageIds: [messageId] });\n }, [messageId, markMessagesRead]);\n\n const handleCancelUpload = useCallback(() => {\n cancelSendingMessage({ chatId, messageId });\n }, [cancelSendingMessage, chatId, messageId]);\n\n const handleVoteSend = useCallback((options: string[]) => {\n sendPollVote({ chatId, messageId, options });\n }, [chatId, messageId, sendPollVote]);\n\n const handleGroupForward = useCallback(() => {\n openForwardMenu({ fromChatId: chatId, groupedId });\n }, [openForwardMenu, chatId, groupedId]);\n\n const handleForward = useCallback(() => {\n if (album && album.messages) {\n const messageIds = album.messages.map(({ id }) => id);\n openForwardMenu({ fromChatId: chatId, messageIds });\n } else {\n openForwardMenu({ fromChatId: chatId, messageIds: [messageId] });\n }\n }, [album, openForwardMenu, chatId, messageId]);\n\n const handleFocus = useCallback(() => {\n focusMessage({\n chatId, threadId: MAIN_THREAD_ID, messageId,\n });\n }, [focusMessage, chatId, messageId]);\n\n const handleFocusForwarded = useCallback(() => {\n if (isInDocumentGroup) {\n focusMessage({\n chatId: forwardInfo!.fromChatId, groupedId, groupedChatId: chatId,\n });\n return;\n }\n\n if (isChatWithRepliesBot && replyToChatId) {\n focusMessageInComments({\n chatId: replyToChatId,\n threadId: replyToTopMessageId,\n messageId: forwardInfo!.fromMessageId,\n });\n } else {\n focusMessage({\n chatId: forwardInfo!.fromChatId, messageId: forwardInfo!.fromMessageId,\n });\n }\n }, [\n isInDocumentGroup, isChatWithRepliesBot, replyToChatId, focusMessage, forwardInfo, groupedId, chatId,\n focusMessageInComments, replyToTopMessageId,\n ]);\n\n const selectWithGroupedId = useCallback((e: React.MouseEvent) => {\n e.stopPropagation();\n\n selectMessage(e, groupedId);\n }, [selectMessage, groupedId]);\n\n return {\n handleAvatarClick,\n handleSenderClick,\n handleViaBotClick,\n handleReplyClick,\n handleMediaClick,\n handleAudioPlay,\n handleAlbumMediaClick,\n handleMetaClick: selectWithGroupedId,\n handleReadMedia,\n handleCancelUpload,\n handleVoteSend,\n handleGroupForward,\n handleForward,\n handleFocus,\n handleFocusForwarded,\n handleDocumentGroupSelectAll: selectWithGroupedId,\n };\n}\n","import { RefObject } from 'react';\nimport React, {\n FC, memo, useEffect, useRef,\n} from '../../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiChat, ApiSponsoredMessage, ApiUser } from '../../../api/types';\n\nimport { renderTextWithEntities } from '../../common/helpers/renderMessageText';\nimport { selectChat, selectSponsoredMessage, selectUser } from '../../../modules/selectors';\nimport { getChatTitle, getUserFullName } from '../../../modules/helpers';\nimport renderText from '../../common/helpers/renderText';\nimport useLang from '../../../hooks/useLang';\nimport { useIntersectionObserver } from '../../../hooks/useIntersectionObserver';\n\nimport Button from '../../ui/Button';\n\nimport './SponsoredMessage.scss';\n\ntype OwnProps = {\n chatId: string;\n containerRef: RefObject;\n};\n\ntype StateProps = {\n message?: ApiSponsoredMessage;\n bot?: ApiUser;\n channel?: ApiChat;\n};\n\nconst INTERSECTION_DEBOUNCE_MS = 200;\n\nconst SponsoredMessage: FC = ({\n chatId,\n message,\n containerRef,\n bot,\n channel,\n}) => {\n const {\n viewSponsoredMessage,\n openChat,\n openChatByInvite,\n startBot,\n focusMessage,\n } = getDispatch();\n const lang = useLang();\n // eslint-disable-next-line no-null/no-null\n const contentRef = useRef(null);\n const shouldObserve = Boolean(message);\n const {\n observe: observeIntersection,\n } = useIntersectionObserver({\n rootRef: containerRef,\n debounceMs: INTERSECTION_DEBOUNCE_MS,\n threshold: 1,\n });\n\n useEffect(() => {\n return shouldObserve ? observeIntersection(contentRef.current!, (target) => {\n if (target.isIntersecting) {\n viewSponsoredMessage({ chatId });\n }\n }) : undefined;\n }, [chatId, shouldObserve, observeIntersection, viewSponsoredMessage]);\n\n if (!message) {\n return undefined;\n }\n\n const handleClick = () => {\n if (message.chatInviteHash) {\n openChatByInvite({ hash: message.chatInviteHash });\n } else if (message.channelPostId) {\n focusMessage({ chatId: message.chatId, messageId: message.channelPostId });\n } else {\n openChat({ id: message.chatId });\n\n if (message.startParam) {\n startBot({\n botId: message.chatId,\n param: message.startParam,\n });\n }\n }\n };\n\n return (\n
\n
\n
\n
\n {bot && renderText(getUserFullName(bot) || '')}\n {channel && renderText(message.chatInviteTitle || getChatTitle(lang, channel, bot) || '')}\n
\n\n

\n \n {renderTextWithEntities(message.text.text, message.text.entities)}\n \n\n \n {lang('SponsoredMessage')}\n \n

\n\n \n
\n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { chatId }): StateProps => {\n const message = selectSponsoredMessage(global, chatId);\n const { chatId: fromChatId, isBot } = message || {};\n\n return {\n message,\n bot: fromChatId && isBot ? selectUser(global, fromChatId) : undefined,\n channel: !isBot && fromChatId ? selectChat(global, fromChatId) : undefined,\n };\n },\n)(SponsoredMessage));\n","import { RefObject } from 'react';\nimport React, { FC, memo } from '../../lib/teact/teact';\n\nimport { MessageListType } from '../../global/types';\n\nimport { SCHEDULED_WHEN_ONLINE } from '../../config';\nimport buildClassName from '../../util/buildClassName';\nimport { compact, flatten } from '../../util/iteratees';\nimport { formatHumanDate } from '../../util/dateFormat';\nimport { getMessageOriginalId, isActionMessage, isOwnMessage } from '../../modules/helpers';\nimport useLang from '../../hooks/useLang';\nimport { isAlbum, MessageDateGroup } from './helpers/groupMessages';\nimport { preventMessageInputBlur } from './helpers/preventMessageInputBlur';\nimport useScrollHooks from './hooks/useScrollHooks';\nimport useMessageObservers from './hooks/useMessageObservers';\n\nimport Message from './message/Message';\nimport SponsoredMessage from './message/SponsoredMessage';\nimport ActionMessage from './ActionMessage';\nimport { getDispatch } from '../../lib/teact/teactn';\n\ninterface OwnProps {\n chatId: string;\n messageIds: number[];\n messageGroups: MessageDateGroup[];\n isViewportNewest: boolean;\n isUnread: boolean;\n withUsers: boolean;\n noAvatars: boolean;\n containerRef: RefObject;\n anchorIdRef: { current: string | undefined };\n memoUnreadDividerBeforeIdRef: { current: number | undefined };\n memoFirstUnreadIdRef: { current: number | undefined };\n threadId: number;\n type: MessageListType;\n isReady: boolean;\n isScrollingRef: { current: boolean | undefined };\n isScrollPatchNeededRef: { current: boolean | undefined };\n threadTopMessageId: number | undefined;\n hasLinkedChat: boolean | undefined;\n isSchedule: boolean;\n noAppearanceAnimation: boolean;\n onFabToggle: AnyToVoidFunction;\n onNotchToggle: AnyToVoidFunction;\n}\n\nconst UNREAD_DIVIDER_CLASS = 'unread-divider';\n\nconst MessageListContent: FC = ({\n chatId,\n messageIds,\n messageGroups,\n isViewportNewest,\n isUnread,\n withUsers,\n noAvatars,\n containerRef,\n anchorIdRef,\n memoUnreadDividerBeforeIdRef,\n memoFirstUnreadIdRef,\n threadId,\n type,\n isReady,\n isScrollingRef,\n isScrollPatchNeededRef,\n threadTopMessageId,\n hasLinkedChat,\n isSchedule,\n noAppearanceAnimation,\n onFabToggle,\n onNotchToggle,\n}) => {\n const { openHistoryCalendar } = getDispatch();\n\n const {\n observeIntersectionForMedia,\n observeIntersectionForReading,\n observeIntersectionForAnimatedStickers,\n } = useMessageObservers(type, containerRef, memoFirstUnreadIdRef);\n\n const {\n backwardsTriggerRef,\n forwardsTriggerRef,\n fabTriggerRef,\n } = useScrollHooks(\n type,\n containerRef,\n messageIds,\n isViewportNewest,\n isUnread,\n onFabToggle,\n onNotchToggle,\n isReady,\n isScrollingRef,\n isScrollPatchNeededRef,\n );\n\n const lang = useLang();\n\n const unreadDivider = (\n
\n {lang('UnreadMessages')}\n
\n );\n\n const messageCountToAnimate = noAppearanceAnimation ? 0 : messageGroups.reduce((acc, messageGroup) => {\n return acc + flatten(messageGroup.senderGroups).length;\n }, 0);\n let appearanceIndex = 0;\n\n const dateGroups = messageGroups.map((\n dateGroup: MessageDateGroup,\n dateGroupIndex: number,\n dateGroupsArray: MessageDateGroup[],\n ) => {\n const senderGroups = dateGroup.senderGroups.map((\n senderGroup,\n senderGroupIndex,\n senderGroupsArray,\n ) => {\n if (senderGroup.length === 1 && !isAlbum(senderGroup[0]) && isActionMessage(senderGroup[0])) {\n const message = senderGroup[0];\n const isLastInList = (\n senderGroupIndex === senderGroupsArray.length - 1\n && dateGroupIndex === dateGroupsArray.length - 1\n );\n\n return compact([\n message.id === memoUnreadDividerBeforeIdRef.current && unreadDivider,\n ,\n ]);\n }\n\n let currentDocumentGroupId: string | undefined;\n\n return flatten(senderGroup.map((\n messageOrAlbum,\n messageIndex,\n ) => {\n const message = isAlbum(messageOrAlbum) ? messageOrAlbum.mainMessage : messageOrAlbum;\n const album = isAlbum(messageOrAlbum) ? messageOrAlbum : undefined;\n const isOwn = isOwnMessage(message);\n const isMessageAlbum = isAlbum(messageOrAlbum);\n const nextMessage = senderGroup[messageIndex + 1];\n\n if (message.previousLocalId && anchorIdRef.current === `message${message.previousLocalId}`) {\n anchorIdRef.current = `message${message.id}`;\n }\n\n const documentGroupId = !isMessageAlbum && message.groupedId ? message.groupedId : undefined;\n const nextDocumentGroupId = nextMessage && !isAlbum(nextMessage) ? nextMessage.groupedId : undefined;\n\n const position = {\n isFirstInGroup: messageIndex === 0,\n isLastInGroup: messageIndex === senderGroup.length - 1,\n isFirstInDocumentGroup: Boolean(documentGroupId && documentGroupId !== currentDocumentGroupId),\n isLastInDocumentGroup: Boolean(documentGroupId && documentGroupId !== nextDocumentGroupId),\n isLastInList: (\n messageIndex === senderGroup.length - 1\n && senderGroupIndex === senderGroupsArray.length - 1\n && dateGroupIndex === dateGroupsArray.length - 1\n ),\n };\n\n currentDocumentGroupId = documentGroupId;\n\n const originalId = getMessageOriginalId(message);\n // Scheduled messages can have local IDs in the middle of the list,\n // and keys should be ordered, so we prefix it with a date.\n // However, this may lead to issues if server date is not synchronized with the local one.\n const key = type !== 'scheduled' ? originalId : `${message.date}_${originalId}`;\n\n return compact([\n message.id === memoUnreadDividerBeforeIdRef.current && unreadDivider,\n ,\n message.id === threadTopMessageId && (\n
\n {lang('DiscussionStarted')}\n
\n ),\n ]);\n }));\n });\n\n return (\n \n openHistoryCalendar({ selectedAt: dateGroup.datetime }) : undefined}\n >\n \n {isSchedule && dateGroup.originalDate === SCHEDULED_WHEN_ONLINE && (\n lang('MessageScheduledUntilOnline')\n )}\n {isSchedule && dateGroup.originalDate !== SCHEDULED_WHEN_ONLINE && (\n lang('MessageScheduledOn', formatHumanDate(lang, dateGroup.datetime, undefined, true))\n )}\n {!isSchedule && formatHumanDate(lang, dateGroup.datetime)}\n \n \n {flatten(senderGroups)}\n \n );\n });\n\n return (\n
\n
\n {flatten(dateGroups)}\n {isViewportNewest && }\n \n \n
\n );\n};\n\nexport default memo(MessageListContent);\n","import { RefObject } from 'react';\nimport { getDispatch } from '../../../lib/teact/teactn';\nimport { useMemo, useRef } from '../../../lib/teact/teact';\n\nimport { LoadMoreDirection } from '../../../types';\nimport { MessageListType } from '../../../global/types';\n\nimport { LOCAL_MESSAGE_ID_BASE, MESSAGE_LIST_SLICE } from '../../../config';\nimport { IS_SCROLL_PATCH_NEEDED, MESSAGE_LIST_SENSITIVE_AREA } from '../../../util/environment';\nimport { debounce } from '../../../util/schedulers';\nimport { useIntersectionObserver, useOnIntersect } from '../../../hooks/useIntersectionObserver';\nimport useOnChange from '../../../hooks/useOnChange';\n\nconst FAB_THRESHOLD = 50;\nconst NOTCH_THRESHOLD = 1; // Notch has zero height so we at least need a 1px margin to intersect\nconst TOOLS_FREEZE_TIMEOUT = 250; // Approximate message sending animation duration\n\nexport default function useScrollHooks(\n type: MessageListType,\n containerRef: RefObject,\n messageIds: number[],\n isViewportNewest: boolean,\n isUnread: boolean,\n onFabToggle: AnyToVoidFunction,\n onNotchToggle: AnyToVoidFunction,\n isReady: boolean,\n isScrollingRef: { current: boolean | undefined },\n isScrollPatchNeededRef: { current: boolean | undefined },\n) {\n const { loadViewportMessages } = getDispatch();\n\n const [loadMoreBackwards, loadMoreForwards] = useMemo(\n () => (type === 'thread' ? [\n debounce(() => loadViewportMessages({ direction: LoadMoreDirection.Backwards }), 1000, true, false),\n debounce(() => loadViewportMessages({ direction: LoadMoreDirection.Forwards }), 1000, true, false),\n ] : []),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [loadViewportMessages, messageIds],\n );\n\n // eslint-disable-next-line no-null/no-null\n const backwardsTriggerRef = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const forwardsTriggerRef = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const fabTriggerRef = useRef(null);\n\n function toggleScrollTools() {\n if (!isReady) return;\n\n if (!messageIds || !messageIds.length) {\n onFabToggle(false);\n onNotchToggle(false);\n return;\n }\n\n if (!isViewportNewest) {\n onFabToggle(true);\n onNotchToggle(true);\n return;\n }\n\n const { offsetHeight, scrollHeight, scrollTop } = containerRef.current!;\n const scrollBottom = Math.round(scrollHeight - scrollTop - offsetHeight);\n const isNearBottom = scrollBottom <= FAB_THRESHOLD;\n const isAtBottom = scrollBottom <= NOTCH_THRESHOLD;\n\n onFabToggle(isUnread ? !isAtBottom : !isNearBottom);\n onNotchToggle(!isAtBottom);\n }\n\n const {\n observe: observeIntersection,\n } = useIntersectionObserver({\n rootRef: containerRef,\n margin: MESSAGE_LIST_SENSITIVE_AREA,\n }, (entries) => {\n if (!loadMoreForwards || !loadMoreBackwards) {\n return;\n }\n\n // Loading history while sending a message can return the same message and cause ambiguity\n const isFirstMessageLocal = messageIds[0] >= LOCAL_MESSAGE_ID_BASE;\n if (isFirstMessageLocal) {\n return;\n }\n\n const triggerEntry = entries.find(({ isIntersecting }) => isIntersecting);\n if (!triggerEntry) {\n return;\n }\n\n const { target } = triggerEntry;\n\n if (target.className === 'backwards-trigger') {\n if (\n IS_SCROLL_PATCH_NEEDED && isScrollingRef.current && messageIds.length <= MESSAGE_LIST_SLICE\n ) {\n isScrollPatchNeededRef.current = true;\n }\n\n loadMoreBackwards();\n } else if (target.className === 'forwards-trigger') {\n loadMoreForwards();\n }\n });\n\n useOnIntersect(backwardsTriggerRef, observeIntersection);\n useOnIntersect(forwardsTriggerRef, observeIntersection);\n\n const {\n observe: observeIntersectionForFab,\n freeze: freezeForFab,\n unfreeze: unfreezeForFab,\n } = useIntersectionObserver({\n rootRef: containerRef,\n margin: FAB_THRESHOLD * 2,\n }, toggleScrollTools);\n\n useOnIntersect(fabTriggerRef, observeIntersectionForFab);\n\n const {\n observe: observeIntersectionForNotch,\n freeze: freezeForNotch,\n unfreeze: unfreezeForNotch,\n } = useIntersectionObserver({\n rootRef: containerRef,\n margin: NOTCH_THRESHOLD,\n }, toggleScrollTools);\n\n useOnIntersect(fabTriggerRef, observeIntersectionForNotch);\n\n useOnChange(() => {\n if (isReady) {\n toggleScrollTools();\n }\n }, [isReady]);\n\n // Workaround for FAB and notch flickering with tall incoming message\n useOnChange(() => {\n freezeForFab();\n freezeForNotch();\n\n setTimeout(() => {\n unfreezeForNotch();\n unfreezeForFab();\n }, TOOLS_FREEZE_TIMEOUT);\n }, [messageIds]);\n\n return { backwardsTriggerRef, forwardsTriggerRef, fabTriggerRef };\n}\n","import React, {\n FC, memo, useCallback, useEffect, useRef,\n} from '../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiSticker, ApiUpdateConnectionStateType } from '../../api/types';\n\nimport { selectChat } from '../../modules/selectors';\nimport { useIntersectionObserver } from '../../hooks/useIntersectionObserver';\nimport useLang from '../../hooks/useLang';\nimport { getUserIdDividend } from '../../modules/helpers';\n\nimport StickerButton from '../common/StickerButton';\n\nimport './ContactGreeting.scss';\n\ntype OwnProps = {\n userId: string;\n};\n\ntype StateProps = {\n sticker?: ApiSticker;\n lastUnreadMessageId?: number;\n connectionState?: ApiUpdateConnectionStateType;\n};\n\nconst INTERSECTION_DEBOUNCE_MS = 200;\n\nconst ContactGreeting: FC = ({\n sticker,\n connectionState,\n lastUnreadMessageId,\n}) => {\n const {\n loadGreetingStickers,\n sendMessage,\n markMessageListRead,\n } = getDispatch();\n\n const lang = useLang();\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef(null);\n const {\n observe: observeIntersection,\n } = useIntersectionObserver({\n rootRef: containerRef,\n debounceMs: INTERSECTION_DEBOUNCE_MS,\n });\n useEffect(() => {\n if (sticker || connectionState !== 'connectionStateReady') {\n return;\n }\n\n loadGreetingStickers();\n }, [connectionState, loadGreetingStickers, sticker]);\n\n useEffect(() => {\n if (connectionState === 'connectionStateReady' && lastUnreadMessageId) {\n markMessageListRead({ maxId: lastUnreadMessageId });\n }\n }, [connectionState, markMessageListRead, lastUnreadMessageId]);\n\n const handleStickerSelect = useCallback((selectedSticker: ApiSticker) => {\n selectedSticker = {\n ...selectedSticker,\n isPreloadedGlobally: true,\n };\n sendMessage({ sticker: selectedSticker });\n }, [sendMessage]);\n\n return (\n
\n
\n

{lang('Conversation.EmptyPlaceholder')}

\n

{lang('Conversation.GreetingText')}

\n\n
\n {sticker && (\n \n )}\n
\n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { userId }): StateProps => {\n const { stickers } = global.stickers.greeting;\n const dividend = getUserIdDividend(userId) + getUserIdDividend(global.currentUserId!);\n const sticker = stickers?.length ? stickers[dividend % stickers.length] : undefined;\n const chat = selectChat(global, userId);\n if (!chat) {\n return {};\n }\n\n return {\n sticker,\n lastUnreadMessageId: chat.lastMessage && chat.lastMessage.id !== chat.lastReadInboxMessageId\n ? chat.lastMessage.id\n : undefined,\n connectionState: global.connectionState,\n };\n },\n)(ContactGreeting));\n","import React, { FC, memo } from '../../lib/teact/teact';\n\nimport { MessageListType } from '../../global/types';\n\nimport useLang, { LangFn } from '../../hooks/useLang';\n\nimport './NoMessages.scss';\n\ntype OwnProps = {\n chatId: string;\n isChatWithSelf?: boolean;\n type: MessageListType;\n isGroupChatJustCreated?: boolean;\n};\n\nconst NoMessages: FC = ({\n isChatWithSelf, type, isGroupChatJustCreated,\n}) => {\n const lang = useLang();\n\n if (type === 'scheduled') {\n return renderScheduled(lang);\n }\n\n if (isChatWithSelf) {\n return renderSavedMessages(lang);\n }\n\n if (isGroupChatJustCreated) {\n return renderGroup(lang);\n }\n\n return (\n
{lang('NoMessages')}
\n );\n};\n\nfunction renderScheduled(lang: LangFn) {\n return (\n
{lang('ScheduledMessages.EmptyPlaceholder')}
\n );\n}\n\nfunction renderSavedMessages(lang: LangFn) {\n return (\n
\n
\n \n

{lang('Conversation.CloudStorageInfo.Title')}

\n
    \n
  • {lang('Conversation.ClousStorageInfo.Description1')}
  • \n
  • {lang('Conversation.ClousStorageInfo.Description2')}
  • \n
  • {lang('Conversation.ClousStorageInfo.Description3')}
  • \n
  • {lang('Conversation.ClousStorageInfo.Description4')}
  • \n
\n
\n
\n );\n}\n\nfunction renderGroup(lang: LangFn) {\n return (\n
\n
\n

{lang('EmptyGroupInfo.Title')}

\n

{lang('EmptyGroupInfo.Subtitle')}

\n
    \n
  • {lang('EmptyGroupInfo.Line1')}
  • \n
  • {lang('EmptyGroupInfo.Line2')}
  • \n
  • {lang('EmptyGroupInfo.Line3')}
  • \n
  • {lang('EmptyGroupInfo.Line4')}
  • \n
\n
\n
\n );\n}\n\nexport default memo(NoMessages);\n","import React, {\n FC, memo, useCallback, useEffect, useMemo, useRef, useState,\n} from '../../lib/teact/teact';\nimport { getDispatch, getGlobal, withGlobal } from '../../lib/teact/teactn';\n\nimport {\n ApiMessage, ApiRestrictionReason, MAIN_THREAD_ID,\n} from '../../api/types';\nimport { MessageListType } from '../../global/types';\nimport { LoadMoreDirection } from '../../types';\n\nimport { ANIMATION_END_DELAY, LOCAL_MESSAGE_ID_BASE, MESSAGE_LIST_SLICE } from '../../config';\nimport {\n selectChatMessages,\n selectIsViewportNewest,\n selectFirstUnreadId,\n selectFocusedMessageId,\n selectChat,\n selectIsInSelectMode,\n selectIsChatWithSelf,\n selectChatBot,\n selectIsChatBotNotStarted,\n selectScrollOffset,\n selectThreadTopMessageId,\n selectFirstMessageId,\n selectScheduledMessages,\n selectCurrentMessageIds,\n} from '../../modules/selectors';\nimport {\n isChatChannel,\n isUserId,\n isChatWithRepliesBot,\n isChatGroup,\n} from '../../modules/helpers';\nimport { orderBy } from '../../util/iteratees';\nimport { fastRaf, debounce, onTickEnd } from '../../util/schedulers';\nimport useLayoutEffectWithPrevDeps from '../../hooks/useLayoutEffectWithPrevDeps';\nimport useEffectWithPrevDeps from '../../hooks/useEffectWithPrevDeps';\nimport buildClassName from '../../util/buildClassName';\nimport { groupMessages } from './helpers/groupMessages';\nimport { preventMessageInputBlur } from './helpers/preventMessageInputBlur';\nimport useOnChange from '../../hooks/useOnChange';\nimport useStickyDates from './hooks/useStickyDates';\nimport { dispatchHeavyAnimationEvent } from '../../hooks/useHeavyAnimationCheck';\nimport resetScroll, { patchChromiumScroll } from '../../util/resetScroll';\nimport fastSmoothScroll, { isAnimatingScroll } from '../../util/fastSmoothScroll';\nimport renderText from '../common/helpers/renderText';\nimport useLang from '../../hooks/useLang';\nimport useWindowSize from '../../hooks/useWindowSize';\n\nimport Loading from '../ui/Loading';\nimport MessageListContent from './MessageListContent';\nimport ContactGreeting from './ContactGreeting';\nimport NoMessages from './NoMessages';\n\nimport './MessageList.scss';\n\ntype OwnProps = {\n chatId: string;\n threadId: number;\n type: MessageListType;\n canPost: boolean;\n isReady: boolean;\n onFabToggle: (shouldShow: boolean) => void;\n onNotchToggle: (shouldShow: boolean) => void;\n hasTools?: boolean;\n withBottomShift?: boolean;\n};\n\ntype StateProps = {\n isChatLoaded?: boolean;\n isChannelChat?: boolean;\n isGroupChat?: boolean;\n isChatWithSelf?: boolean;\n isRepliesChat?: boolean;\n isCreator?: boolean;\n isBot?: boolean;\n messageIds?: number[];\n messagesById?: Record;\n firstUnreadId?: number;\n isViewportNewest?: boolean;\n isRestricted?: boolean;\n restrictionReason?: ApiRestrictionReason;\n focusingId?: number;\n isSelectModeActive?: boolean;\n animationLevel?: number;\n lastMessage?: ApiMessage;\n botDescription?: string;\n threadTopMessageId?: number;\n threadFirstMessageId?: number;\n hasLinkedChat?: boolean;\n lastSyncTime?: number;\n};\n\nconst BOTTOM_THRESHOLD = 20;\nconst UNREAD_DIVIDER_TOP = 10;\nconst UNREAD_DIVIDER_TOP_WITH_TOOLS = 60;\nconst SCROLL_DEBOUNCE = 200;\nconst MESSAGE_ANIMATION_DURATION = 500;\nconst BOTTOM_FOCUS_MARGIN = 20;\nconst SELECT_MODE_ANIMATION_DURATION = 200;\nconst UNREAD_DIVIDER_CLASS = 'unread-divider';\n\nconst runDebouncedForScroll = debounce((cb) => cb(), SCROLL_DEBOUNCE, false);\n\nconst MessageList: FC = ({\n chatId,\n threadId,\n type,\n hasTools,\n onFabToggle,\n onNotchToggle,\n isChatLoaded,\n isChannelChat,\n isGroupChat,\n canPost,\n isReady,\n isChatWithSelf,\n isRepliesChat,\n isCreator,\n isBot,\n messageIds,\n messagesById,\n firstUnreadId,\n isViewportNewest,\n threadFirstMessageId,\n isRestricted,\n restrictionReason,\n focusingId,\n isSelectModeActive,\n lastMessage,\n botDescription,\n threadTopMessageId,\n hasLinkedChat,\n lastSyncTime,\n withBottomShift,\n}) => {\n const { loadViewportMessages, setScrollOffset, loadSponsoredMessages } = getDispatch();\n\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef(null);\n\n // We update local cached `scrollOffsetRef` when opening chat.\n // Then we update global version every second on scrolling.\n const scrollOffsetRef = useRef((type === 'thread' && selectScrollOffset(getGlobal(), chatId, threadId)) || 0);\n const anchorIdRef = useRef();\n const anchorTopRef = useRef();\n const listItemElementsRef = useRef();\n const memoFirstUnreadIdRef = useRef();\n const memoUnreadDividerBeforeIdRef = useRef();\n const memoFocusingIdRef = useRef();\n const isScrollTopJustUpdatedRef = useRef(false);\n const shouldAnimateAppearanceRef = useRef(Boolean(lastMessage));\n\n const [containerHeight, setContainerHeight] = useState();\n\n const areMessagesLoaded = Boolean(messageIds);\n\n useOnChange(() => {\n // We only need it first time when message list appears\n if (areMessagesLoaded) {\n onTickEnd(() => {\n shouldAnimateAppearanceRef.current = false;\n });\n }\n }, [areMessagesLoaded]);\n\n // Updated every time (to be used from intersection callback closure)\n useOnChange(() => {\n memoFirstUnreadIdRef.current = firstUnreadId;\n }, [firstUnreadId]);\n\n useOnChange(() => {\n if (isChannelChat && isReady && lastSyncTime) {\n loadSponsoredMessages({ chatId });\n }\n }, [chatId, isReady, isChannelChat, lastSyncTime]);\n\n // Updated only once when messages are loaded (as we want the unread divider to keep its position)\n useOnChange(() => {\n if (areMessagesLoaded) {\n memoUnreadDividerBeforeIdRef.current = memoFirstUnreadIdRef.current;\n }\n }, [areMessagesLoaded]);\n\n useOnChange(() => {\n memoFocusingIdRef.current = focusingId;\n }, [focusingId]);\n\n const messageGroups = useMemo(() => {\n if (!messageIds || !messagesById) {\n return undefined;\n }\n\n const viewportIds = threadTopMessageId && (!messageIds[0] || threadFirstMessageId === messageIds[0])\n ? [threadTopMessageId, ...messageIds]\n : messageIds;\n\n if (!viewportIds.length) {\n return undefined;\n }\n\n const listedMessages = viewportIds.map((id) => messagesById[id]).filter(Boolean);\n return groupMessages(orderBy(listedMessages, ['date', 'id']), memoUnreadDividerBeforeIdRef.current);\n }, [messageIds, messagesById, threadFirstMessageId, threadTopMessageId]);\n\n const loadMoreAround = useMemo(() => {\n if (type !== 'thread') {\n return undefined;\n }\n\n return debounce(() => loadViewportMessages({ direction: LoadMoreDirection.Around }), 1000, true, false);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [loadViewportMessages, messageIds]);\n\n const { isScrolled, updateStickyDates } = useStickyDates();\n\n const isScrollingRef = useRef();\n const isScrollPatchNeededRef = useRef();\n\n const handleScroll = useCallback(() => {\n if (isScrollTopJustUpdatedRef.current) {\n isScrollTopJustUpdatedRef.current = false;\n return;\n }\n\n isScrollingRef.current = true;\n\n const container = containerRef.current!;\n\n if (!memoFocusingIdRef.current) {\n updateStickyDates(container, hasTools);\n }\n\n runDebouncedForScroll(() => {\n isScrollingRef.current = false;\n\n fastRaf(() => {\n if (!container.parentElement) {\n return;\n }\n\n scrollOffsetRef.current = container.scrollHeight - container.scrollTop;\n\n if (type === 'thread') {\n setScrollOffset({ chatId, threadId, scrollOffset: scrollOffsetRef.current });\n }\n });\n });\n }, [updateStickyDates, hasTools, type, setScrollOffset, chatId, threadId]);\n\n // Container resize observer (caused by Composer reply/webpage panels)\n useEffect(() => {\n if (!('ResizeObserver' in window) || process.env.APP_ENV === 'perf') {\n return undefined;\n }\n\n const observer = new ResizeObserver(([entry]) => {\n // During animation\n if (!(entry.target as HTMLDivElement).offsetParent) {\n return;\n }\n\n setContainerHeight(entry.contentRect.height);\n });\n\n observer.observe(containerRef.current!);\n\n return () => {\n observer.disconnect();\n };\n }, []);\n\n // Memorize height for scroll animation\n const { height: windowHeight } = useWindowSize();\n\n useEffect(() => {\n if (isReady) {\n containerRef.current!.dataset.normalHeight = String(containerRef.current!.offsetHeight);\n }\n }, [windowHeight, isReady, canPost]);\n\n // Initial message loading\n useEffect(() => {\n if (!loadMoreAround || !isChatLoaded || isRestricted || focusingId) {\n return;\n }\n\n // Loading history while sending a message can return the same message and cause ambiguity\n const isLastMessageLocal = messageIds && messageIds[messageIds.length - 1] >= LOCAL_MESSAGE_ID_BASE;\n if (isLastMessageLocal) {\n return;\n }\n\n const container = containerRef.current!;\n\n if (!messageIds || (\n messageIds.length < MESSAGE_LIST_SLICE / 2\n && (container.firstElementChild as HTMLDivElement).clientHeight <= container.offsetHeight\n )) {\n loadMoreAround();\n }\n }, [isChatLoaded, messageIds, loadMoreAround, focusingId, isRestricted]);\n\n // Remember scroll position before repositioning it\n useOnChange(() => {\n if (!messageIds || !listItemElementsRef.current) {\n return;\n }\n\n const preservedItemElements = listItemElementsRef.current\n .filter((element) => messageIds.includes(Number(element.dataset.messageId)));\n\n // We avoid the very first item as it may be a partly-loaded album\n // and also because it may be removed when messages limit is reached\n const anchor = preservedItemElements[1] || preservedItemElements[0];\n if (!anchor) {\n return;\n }\n\n anchorIdRef.current = anchor.id;\n anchorTopRef.current = anchor.getBoundingClientRect().top;\n // This should match deps for `useLayoutEffectWithPrevDeps` below\n }, [messageIds, isViewportNewest, containerHeight, hasTools]);\n\n // Handles updated message list, takes care of scroll repositioning\n useLayoutEffectWithPrevDeps(([\n prevMessageIds, prevIsViewportNewest, prevContainerHeight,\n ]: [\n typeof messageIds, typeof isViewportNewest, typeof containerHeight,\n ]) => {\n const container = containerRef.current!;\n listItemElementsRef.current = Array.from(container.querySelectorAll('.message-list-item'));\n\n const hasLastMessageChanged = (\n messageIds && prevMessageIds && messageIds[messageIds.length - 1] !== prevMessageIds[prevMessageIds.length - 1]\n );\n const hasViewportShifted = (\n messageIds?.[0] !== prevMessageIds?.[0] && messageIds?.length === (MESSAGE_LIST_SLICE / 2 + 1)\n );\n const wasMessageAdded = hasLastMessageChanged && !hasViewportShifted;\n const isAlreadyFocusing = messageIds && memoFocusingIdRef.current === messageIds[messageIds.length - 1];\n\n // Add extra height when few messages to allow smooth scroll animation. Uses assumption that `parentElement`\n // is a Transition slide and its CSS class can not be reset in a declarative way.\n const shouldForceScroll = (\n isViewportNewest\n && wasMessageAdded\n && (messageIds && messageIds.length < MESSAGE_LIST_SLICE / 2)\n && !container.parentElement!.classList.contains('force-messages-scroll')\n && (container.firstElementChild as HTMLDivElement)!.clientHeight <= container.offsetHeight * 2\n );\n\n if (shouldForceScroll) {\n container.parentElement!.classList.add('force-messages-scroll');\n\n setTimeout(() => {\n if (container.parentElement) {\n container.parentElement.classList.remove('force-messages-scroll');\n }\n }, MESSAGE_ANIMATION_DURATION);\n }\n\n const { scrollTop, scrollHeight, offsetHeight } = container;\n const scrollOffset = scrollOffsetRef.current;\n const lastItemElement = listItemElementsRef.current[listItemElementsRef.current.length - 1];\n\n let bottomOffset = scrollOffset - (prevContainerHeight || offsetHeight);\n if (wasMessageAdded) {\n // If two new messages come at once (e.g. when bot responds) then the first message will update `scrollOffset`\n // right away (before animation) which creates inconsistency until the animation completes. To workaround that,\n // we calculate `isAtBottom` with a \"buffer\" of the latest message height (this is approximate).\n const lastItemHeight = lastItemElement ? lastItemElement.offsetHeight : 0;\n bottomOffset -= lastItemHeight;\n }\n const isAtBottom = isViewportNewest && prevIsViewportNewest && bottomOffset <= BOTTOM_THRESHOLD;\n\n let newScrollTop!: number;\n\n if (wasMessageAdded && isAtBottom && !isAlreadyFocusing) {\n if (lastItemElement) {\n fastRaf(() => {\n fastSmoothScroll(\n container,\n lastItemElement,\n 'end',\n BOTTOM_FOCUS_MARGIN,\n );\n });\n }\n\n newScrollTop = scrollHeight - offsetHeight;\n scrollOffsetRef.current = Math.max(Math.ceil(scrollHeight - newScrollTop), offsetHeight);\n\n // Scroll still needs to be restored after container resize\n if (!shouldForceScroll) {\n return;\n }\n }\n\n if (process.env.APP_ENV === 'perf') {\n // eslint-disable-next-line no-console\n console.time('scrollTop');\n }\n\n const isResized = prevContainerHeight !== undefined && prevContainerHeight !== containerHeight;\n const anchor = anchorIdRef.current && container.querySelector(`#${anchorIdRef.current}`);\n const unreadDivider = (\n !anchor\n && memoUnreadDividerBeforeIdRef.current\n && container.querySelector(`.${UNREAD_DIVIDER_CLASS}`)\n );\n\n if (isAtBottom && isResized) {\n if (isAnimatingScroll()) {\n return;\n }\n\n newScrollTop = scrollHeight - offsetHeight;\n } else if (anchor) {\n if (isScrollPatchNeededRef.current) {\n isScrollPatchNeededRef.current = false;\n patchChromiumScroll(container);\n }\n\n const newAnchorTop = anchor.getBoundingClientRect().top;\n newScrollTop = scrollTop + (newAnchorTop - (anchorTopRef.current || 0));\n } else if (unreadDivider) {\n newScrollTop = Math.min(\n unreadDivider.offsetTop - (hasTools ? UNREAD_DIVIDER_TOP_WITH_TOOLS : UNREAD_DIVIDER_TOP),\n scrollHeight - scrollOffset,\n );\n } else {\n newScrollTop = scrollHeight - scrollOffset;\n }\n\n resetScroll(container, Math.ceil(newScrollTop));\n\n if (!memoFocusingIdRef.current) {\n isScrollTopJustUpdatedRef.current = true;\n fastRaf(() => {\n isScrollTopJustUpdatedRef.current = false;\n });\n }\n\n scrollOffsetRef.current = Math.max(Math.ceil(scrollHeight - newScrollTop), offsetHeight);\n\n if (process.env.APP_ENV === 'perf') {\n // eslint-disable-next-line no-console\n console.timeEnd('scrollTop');\n }\n // This should match deps for `useOnChange` above\n }, [messageIds, isViewportNewest, containerHeight, hasTools]);\n\n useEffectWithPrevDeps(([prevIsSelectModeActive]) => {\n if (prevIsSelectModeActive !== undefined) {\n dispatchHeavyAnimationEvent(SELECT_MODE_ANIMATION_DURATION + ANIMATION_END_DELAY);\n }\n }, [isSelectModeActive]);\n\n const lang = useLang();\n\n const isPrivate = Boolean(chatId && isUserId(chatId));\n const withUsers = Boolean((!isPrivate && !isChannelChat) || isChatWithSelf || isRepliesChat);\n const noAvatars = Boolean(!withUsers || isChannelChat);\n const shouldRenderGreeting = isUserId(chatId) && !isChatWithSelf && !isBot\n && (\n (\n !messageGroups && !lastMessage && messageIds\n // Used to avoid flickering when deleting a greeting that has just been sent\n && (!listItemElementsRef.current || listItemElementsRef.current.length === 0)\n )\n || (messageIds?.length === 1 && messagesById?.[messageIds[0]]?.content.action?.type === 'contactSignUp')\n || (lastMessage?.content?.action?.type === 'contactSignUp')\n );\n\n const isGroupChatJustCreated = isGroupChat && isCreator\n && messageIds?.length === 1 && messagesById?.[messageIds[0]]?.content.action?.type === 'chatCreate';\n\n const className = buildClassName(\n 'MessageList custom-scroll',\n noAvatars && 'no-avatars',\n !canPost && 'no-composer',\n type === 'pinned' && 'type-pinned',\n withBottomShift && 'with-bottom-shift',\n isSelectModeActive && 'select-mode-active',\n isScrolled && 'scrolled',\n !isReady && 'is-animating',\n );\n\n return (\n \n {isRestricted ? (\n
\n \n {restrictionReason ? restrictionReason.text : `This is a private ${isChannelChat ? 'channel' : 'chat'}`}\n \n
\n ) : botDescription ? (\n
{renderText(lang(botDescription), ['br', 'emoji', 'links'])}
\n ) : shouldRenderGreeting ? (\n \n ) : messageIds && (!messageGroups || isGroupChatJustCreated) ? (\n \n ) : ((messageIds && messageGroups) || lastMessage) ? (\n \n ) : (\n \n )}\n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { chatId, threadId, type }): StateProps => {\n const chat = selectChat(global, chatId);\n if (!chat) {\n return {};\n }\n\n const messageIds = selectCurrentMessageIds(global, chatId, threadId, type);\n const messagesById = type === 'scheduled'\n ? selectScheduledMessages(global, chatId)\n : selectChatMessages(global, chatId);\n const threadTopMessageId = selectThreadTopMessageId(global, chatId, threadId);\n\n if (\n threadId !== MAIN_THREAD_ID\n && !(messagesById && threadTopMessageId && messagesById[threadTopMessageId])\n ) {\n return {};\n }\n\n const { isRestricted, restrictionReason, lastMessage } = chat;\n const focusingId = selectFocusedMessageId(global, chatId);\n\n const withLastMessageWhenPreloading = (\n threadId === MAIN_THREAD_ID\n && !messageIds && !chat.unreadCount && !focusingId && lastMessage && !lastMessage.groupedId\n );\n\n const chatBot = selectChatBot(global, chatId)!;\n let botDescription: string | undefined;\n if (selectIsChatBotNotStarted(global, chatId)) {\n if (chatBot.fullInfo) {\n botDescription = chatBot.fullInfo.botDescription || 'NoMessages';\n } else {\n botDescription = 'Updating bot info...';\n }\n }\n\n return {\n isChatLoaded: true,\n isRestricted,\n restrictionReason,\n isChannelChat: isChatChannel(chat),\n isGroupChat: isChatGroup(chat),\n isCreator: chat.isCreator,\n isChatWithSelf: selectIsChatWithSelf(global, chatId),\n isRepliesChat: isChatWithRepliesBot(chatId),\n isBot: Boolean(chatBot),\n messageIds,\n messagesById,\n firstUnreadId: selectFirstUnreadId(global, chatId, threadId),\n isViewportNewest: type !== 'thread' || selectIsViewportNewest(global, chatId, threadId),\n threadFirstMessageId: selectFirstMessageId(global, chatId, threadId),\n focusingId,\n isSelectModeActive: selectIsInSelectMode(global),\n botDescription,\n threadTopMessageId,\n hasLinkedChat: chat.fullInfo && ('linkedChatId' in chat.fullInfo)\n ? Boolean(chat.fullInfo.linkedChatId)\n : undefined,\n lastSyncTime: global.lastSyncTime,\n ...(withLastMessageWhenPreloading && { lastMessage }),\n };\n },\n)(MessageList));\n","import { useCallback } from '../../../lib/teact/teact';\n\nimport { fastRaf } from '../../../util/schedulers';\nimport useDebounce from '../../../hooks/useDebounce';\nimport useFlag from '../../../hooks/useFlag';\n\nconst DEBOUNCE = 1000;\nconst STICKY_TOP = 10;\nconst STICKY_TOP_WITH_TOOLS = 60;\n\nexport default function useStickyDates() {\n // For some reason we can not synchronously hide a sticky element (from `useLayoutEffect`) when chat opens\n // so we will add `position: sticky` only after first scroll. There would be no animation on the first show though.\n const [isScrolled, markIsScrolled] = useFlag(false);\n\n const runDebounced = useDebounce(DEBOUNCE, false);\n\n const updateStickyDates = useCallback((container: HTMLDivElement, hasTools?: boolean) => {\n markIsScrolled();\n\n if (!document.body.classList.contains('is-scrolling-messages')) {\n fastRaf(() => {\n document.body.classList.add('is-scrolling-messages');\n });\n }\n\n runDebounced(() => {\n fastRaf(() => {\n const currentStuck = document.querySelector('.stuck');\n if (currentStuck) {\n currentStuck.classList.remove('stuck');\n }\n\n const stuckDateEl = findStuckDate(container, hasTools);\n if (stuckDateEl) {\n stuckDateEl.classList.add('stuck');\n }\n\n document.body.classList.remove('is-scrolling-messages');\n });\n });\n }, [markIsScrolled, runDebounced]);\n\n return {\n isScrolled,\n updateStickyDates,\n };\n}\n\nfunction findStuckDate(container: HTMLElement, hasTools?: boolean) {\n const allElements = container.querySelectorAll('.sticky-date');\n const containerTop = container.scrollTop;\n\n return Array.from(allElements).find((el) => {\n const { offsetTop, offsetHeight } = el;\n const top = offsetTop - containerTop;\n return -offsetHeight <= top && top <= (hasTools ? STICKY_TOP_WITH_TOOLS : STICKY_TOP);\n });\n}\n","import React, {\n FC, useCallback, memo, useRef,\n} from '../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../lib/teact/teactn';\n\nimport { MessageListType } from '../../global/types';\nimport { MAIN_THREAD_ID } from '../../api/types';\n\nimport { selectChat, selectCurrentMessageList } from '../../modules/selectors';\nimport { formatIntegerCompact } from '../../util/textFormat';\nimport buildClassName from '../../util/buildClassName';\nimport fastSmoothScroll from '../../util/fastSmoothScroll';\nimport useLang from '../../hooks/useLang';\n\nimport Button from '../ui/Button';\n\nimport './ScrollDownButton.scss';\n\ntype OwnProps = {\n isShown: boolean;\n canPost?: boolean;\n withExtraShift?: boolean;\n};\n\ntype StateProps = {\n messageListType?: MessageListType;\n unreadCount?: number;\n};\n\nconst FOCUS_MARGIN = 20;\n\nconst ScrollDownButton: FC = ({\n isShown,\n canPost,\n messageListType,\n unreadCount,\n withExtraShift,\n}) => {\n const { focusNextReply } = getDispatch();\n\n const lang = useLang();\n // eslint-disable-next-line no-null/no-null\n const elementRef = useRef(null);\n\n const handleClick = useCallback(() => {\n if (!isShown) {\n return;\n }\n\n if (messageListType === 'thread') {\n focusNextReply();\n } else {\n const messagesContainer = elementRef.current!.parentElement!.querySelector('.MessageList')!;\n const messageElements = messagesContainer.querySelectorAll('.message-list-item');\n const lastMessageElement = messageElements[messageElements.length - 1];\n if (!lastMessageElement) {\n return;\n }\n\n fastSmoothScroll(messagesContainer, lastMessageElement, 'end', FOCUS_MARGIN);\n }\n }, [isShown, messageListType, focusNextReply]);\n\n const fabClassName = buildClassName(\n 'ScrollDownButton',\n isShown && 'revealed',\n !canPost && 'no-composer',\n withExtraShift && 'with-extra-shift',\n );\n\n return (\n
\n
\n \n \n \n {Boolean(unreadCount) && (\n
{formatIntegerCompact(unreadCount!)}
\n )}\n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return {};\n }\n\n const { chatId, threadId, type: messageListType } = currentMessageList;\n const chat = selectChat(global, chatId);\n\n return {\n messageListType,\n unreadCount: chat && threadId === MAIN_THREAD_ID && messageListType === 'thread' ? chat.unreadCount : undefined,\n };\n },\n)(ScrollDownButton));\n","import { ApiAttachment } from '../../../../api/types';\nimport { SUPPORTED_IMAGE_CONTENT_TYPES, SUPPORTED_VIDEO_CONTENT_TYPES } from '../../../../config';\nimport {\n preloadImage,\n preloadVideo,\n createPosterForVideo,\n fetchBlob,\n} from '../../../../util/files';\nimport { scaleImage } from '../../../../util/imageResize';\n\nconst MAX_QUICK_IMG_SIZE = 1280; // px\nconst FILE_EXT_REGEX = /\\.[^/.]+$/;\n\nexport default async function buildAttachment(\n filename: string, blob: Blob, isQuick: boolean, options?: Partial,\n): Promise {\n const blobUrl = URL.createObjectURL(blob);\n const { type: mimeType, size } = blob;\n let quick;\n let previewBlobUrl;\n\n if (SUPPORTED_IMAGE_CONTENT_TYPES.has(mimeType)) {\n if (isQuick) {\n const img = await preloadImage(blobUrl);\n const { width, height } = img;\n\n if (width > MAX_QUICK_IMG_SIZE || height > MAX_QUICK_IMG_SIZE || mimeType !== 'image/jpeg') {\n const resizedUrl = await scaleImage(blobUrl, MAX_QUICK_IMG_SIZE / Math.max(width, height), 'image/jpeg');\n URL.revokeObjectURL(blobUrl);\n const newBlob = await fetchBlob(resizedUrl);\n return buildAttachment(filename, newBlob, true, options);\n }\n\n if (mimeType === 'image/jpeg') {\n filename = filename.replace(FILE_EXT_REGEX, '.jpg');\n }\n\n quick = { width, height };\n } else {\n previewBlobUrl = blobUrl;\n }\n } else if (SUPPORTED_VIDEO_CONTENT_TYPES.has(mimeType)) {\n const { videoWidth: width, videoHeight: height, duration } = await preloadVideo(blobUrl);\n quick = { width, height, duration };\n\n previewBlobUrl = await createPosterForVideo(blobUrl);\n }\n\n return {\n blobUrl,\n filename,\n mimeType,\n size,\n quick,\n previewBlobUrl,\n ...options,\n };\n}\n","import { IS_IOS } from '../../../../util/environment';\n\nlet resetInput: HTMLInputElement;\n\nif (IS_IOS) {\n resetInput = document.createElement('input');\n resetInput.classList.add('for-ios-autocapitalization-fix');\n document.body.appendChild(resetInput);\n}\n\n// https://stackoverflow.com/a/55652503\nexport default function applyIosAutoCapitalizationFix(inputEl: HTMLElement) {\n resetInput.focus();\n inputEl.focus();\n}\n","import { useEffect, useLayoutEffect, useRef } from '../lib/teact/teact';\n\nfunction useInterval(callback: NoneToVoidFunction, delay?: number, noFirst = false) {\n const savedCallback = useRef(callback);\n\n useLayoutEffect(() => {\n savedCallback.current = callback;\n }, [callback]);\n\n useEffect(() => {\n if (delay === undefined) {\n return undefined;\n }\n\n const id = setInterval(() => savedCallback.current(), delay);\n if (!noFirst) savedCallback.current();\n\n return () => clearInterval(id);\n }, [delay, noFirst]);\n}\n\nexport default useInterval;\n","// @ts-ignore\nimport encoderPath from 'file-loader!opus-recorder/dist/encoderWorker.min';\n\nexport type Result = { blob: Blob; duration: number; waveform: number[] };\n\ninterface IOpusRecorder extends Omit {\n new(options: AnyLiteral): IOpusRecorder;\n\n start(stream?: MediaStreamAudioSourceNode): void;\n\n sourceNode: MediaStreamAudioSourceNode;\n\n ondataavailable: (typedArray: Uint8Array) => void;\n}\n\nconst MIN_RECORDING_TIME = 1000;\nconst POLYFILL_OPTIONS = { encoderPath, reuseWorker: true };\nconst BLOB_PARAMS = { type: 'audio/ogg' };\nconst FFT_SIZE = 64;\nconst MIN_VOLUME = 0.1;\n\nlet opusRecorderPromise: Promise<{ default: IOpusRecorder }>;\nlet OpusRecorder: IOpusRecorder;\nlet mediaRecorder: IOpusRecorder;\n\nexport async function init() {\n if (!opusRecorderPromise) {\n // @ts-ignore\n opusRecorderPromise = import('opus-recorder');\n OpusRecorder = (await opusRecorderPromise).default;\n mediaRecorder = new OpusRecorder(POLYFILL_OPTIONS);\n }\n\n return opusRecorderPromise;\n}\n\nexport async function start(analyzerCallback: Function) {\n await startMediaRecorder();\n\n const startedAt = Date.now();\n let pausedAt: number;\n const chunks: Uint8Array[] = [];\n const waveform: number[] = [];\n\n mediaRecorder.ondataavailable = (typedArray) => {\n chunks.push(typedArray);\n };\n\n const releaseAnalyzer = subscribeToAnalyzer(mediaRecorder, (volume: number) => {\n waveform.push(volume * 255);\n analyzerCallback(volume);\n });\n\n return {\n stop: () => new Promise((resolve, reject) => {\n mediaRecorder.onstop = () => {\n resolve({\n blob: new Blob(chunks, BLOB_PARAMS),\n duration: Math.round(((pausedAt || Date.now()) - startedAt) / 1000),\n waveform,\n });\n };\n mediaRecorder.onerror = reject;\n\n const delayStop = Math.max(0, startedAt + MIN_RECORDING_TIME - Date.now());\n setTimeout(() => {\n mediaRecorder.stop();\n releaseAnalyzer();\n }, delayStop);\n }),\n pause: () => {\n const delayStop = Math.max(0, startedAt + MIN_RECORDING_TIME - Date.now());\n setTimeout(() => {\n mediaRecorder.pause();\n pausedAt = Date.now();\n releaseAnalyzer();\n }, delayStop);\n },\n };\n}\n\nasync function startMediaRecorder() {\n await init();\n await mediaRecorder.start();\n}\n\nfunction subscribeToAnalyzer(recorder: IOpusRecorder, cb: Function) {\n const source = recorder.sourceNode;\n const analyser = source.context.createAnalyser();\n analyser.fftSize = FFT_SIZE;\n source.connect(analyser);\n\n const dataLength = analyser.frequencyBinCount;\n const dataArray = new Uint8Array(dataLength);\n let isDestroyed = false;\n\n function tick() {\n if (isDestroyed) {\n return;\n }\n\n analyser.getByteFrequencyData(dataArray);\n\n const sum = dataArray.reduce((acc, current) => acc + current, 0);\n const mean = (sum / dataLength);\n const volume = mean / 255;\n\n cb(volume < MIN_VOLUME ? 0 : volume);\n\n requestAnimationFrame(tick);\n }\n\n tick();\n\n return () => {\n isDestroyed = true;\n };\n}\n","export default __webpack_public_path__ + \"c0155344d336103c2b6a0b28cc510750.js\";","import {\n useCallback, useEffect, useRef, useState,\n} from '../../../../lib/teact/teact';\n\nimport { IS_SAFARI, IS_VOICE_RECORDING_SUPPORTED } from '../../../../util/environment';\nimport * as voiceRecording from '../../../../util/voiceRecording';\nimport captureEscKeyListener from '../../../../util/captureEscKeyListener';\n\ntype ActiveVoiceRecording = { stop: () => Promise; pause: NoneToVoidFunction } | undefined;\n\nexport default () => {\n // eslint-disable-next-line no-null/no-null\n const recordButtonRef = useRef(null);\n const [activeVoiceRecording, setActiveVoiceRecording] = useState();\n const startRecordTimeRef = useRef();\n const [currentRecordTime, setCurrentRecordTime] = useState();\n\n useEffect(() => {\n // Preloading worker fixes silent first record on iOS\n if (IS_SAFARI && IS_VOICE_RECORDING_SUPPORTED) {\n void voiceRecording.init();\n }\n }, []);\n\n const startRecordingVoice = useCallback(async () => {\n try {\n const { stop, pause } = await voiceRecording.start((tickVolume: number) => {\n if (recordButtonRef.current) {\n if (startRecordTimeRef.current && Date.now() % 4 === 0) {\n recordButtonRef.current.style.boxShadow = `0 0 0 ${(tickVolume || 0) * 50}px rgba(0,0,0,.15)`;\n }\n setCurrentRecordTime(Date.now());\n }\n });\n startRecordTimeRef.current = Date.now();\n setCurrentRecordTime(Date.now());\n\n setActiveVoiceRecording({ stop, pause });\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n }, []);\n\n const pauseRecordingVoice = useCallback(() => {\n if (!activeVoiceRecording) {\n return undefined;\n }\n\n if (recordButtonRef.current) {\n recordButtonRef.current.style.boxShadow = 'none';\n }\n try {\n return activeVoiceRecording!.pause();\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(err);\n return undefined;\n }\n }, [activeVoiceRecording]);\n\n const stopRecordingVoice = useCallback(() => {\n if (!activeVoiceRecording) {\n return undefined;\n }\n\n setActiveVoiceRecording(undefined);\n startRecordTimeRef.current = undefined;\n setCurrentRecordTime(undefined);\n if (recordButtonRef.current) {\n recordButtonRef.current.style.boxShadow = 'none';\n }\n try {\n return activeVoiceRecording!.stop();\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(err);\n return undefined;\n }\n }, [activeVoiceRecording]);\n\n useEffect(() => {\n return activeVoiceRecording ? captureEscKeyListener(stopRecordingVoice) : undefined;\n }, [activeVoiceRecording, stopRecordingVoice]);\n\n return {\n startRecordingVoice,\n pauseRecordingVoice,\n stopRecordingVoice,\n activeVoiceRecording,\n currentRecordTime,\n recordButtonRef,\n startRecordTimeRef,\n };\n};\n","import { StateHookSetter, useEffect } from '../../../../lib/teact/teact';\nimport { ApiAttachment, ApiMessage } from '../../../../api/types';\n\nimport buildAttachment from '../helpers/buildAttachment';\nimport { EDITABLE_INPUT_ID, EDITABLE_INPUT_MODAL_ID } from '../../../../config';\n\nconst CLIPBOARD_ACCEPTED_TYPES = ['image/png', 'image/jpeg', 'image/gif'];\nconst MAX_MESSAGE_LENGTH = 4096;\n\nexport default (\n insertTextAndUpdateCursor: (text: string, inputId?: string) => void,\n setAttachments: StateHookSetter,\n editedMessage: ApiMessage | undefined,\n) => {\n useEffect(() => {\n async function handlePaste(e: ClipboardEvent) {\n if (!e.clipboardData) {\n return;\n }\n\n const input = document.activeElement;\n if (input && ![EDITABLE_INPUT_ID, EDITABLE_INPUT_MODAL_ID].includes(input.id)) {\n return;\n }\n\n const { items } = e.clipboardData;\n const media = Array.from(items)\n .find((item) => CLIPBOARD_ACCEPTED_TYPES.includes(item.type) && item.kind === 'file');\n const file = media && media.getAsFile();\n const pastedText = e.clipboardData.getData('text').substring(0, MAX_MESSAGE_LENGTH);\n\n e.preventDefault();\n\n if (!file && !pastedText) {\n return;\n }\n\n if (file && !editedMessage) {\n const attachment = await buildAttachment(file.name, file, true);\n setAttachments((attachments) => [\n ...attachments,\n attachment,\n ]);\n }\n\n if (pastedText) {\n insertTextAndUpdateCursor(pastedText, input?.id);\n }\n }\n\n document.addEventListener('paste', handlePaste, false);\n\n return () => {\n document.removeEventListener('paste', handlePaste, false);\n };\n }, [insertTextAndUpdateCursor, editedMessage, setAttachments]);\n};\n","import { ApiFormattedText } from '../../../../api/types';\nimport { renderTextWithEntities } from '../../../common/helpers/renderMessageText';\n\nexport default function getMessageTextAsHtml(formattedText?: ApiFormattedText) {\n const { text, entities } = formattedText || {};\n if (!text) {\n return '';\n }\n\n const result = renderTextWithEntities(\n text,\n entities,\n undefined,\n undefined,\n true,\n );\n\n if (Array.isArray(result)) {\n return result.join('');\n }\n\n return result;\n}\n","import { useCallback, useEffect, useMemo } from '../../../../lib/teact/teact';\nimport { getDispatch } from '../../../../lib/teact/teactn';\n\nimport { ApiFormattedText, ApiMessage } from '../../../../api/types';\n\nimport { DRAFT_DEBOUNCE, EDITABLE_INPUT_ID } from '../../../../config';\nimport usePrevious from '../../../../hooks/usePrevious';\nimport { debounce } from '../../../../util/schedulers';\nimport focusEditableElement from '../../../../util/focusEditableElement';\nimport parseMessageInput from '../../../../util/parseMessageInput';\nimport getMessageTextAsHtml from '../helpers/getMessageTextAsHtml';\nimport useBackgroundMode from '../../../../hooks/useBackgroundMode';\nimport useBeforeUnload from '../../../../hooks/useBeforeUnload';\nimport { IS_TOUCH_ENV } from '../../../../util/environment';\n\n// Used to avoid running debounced callbacks when chat changes.\nlet currentChatId: string | undefined;\nlet currentThreadId: number | undefined;\n\nexport default (\n draft: ApiFormattedText | undefined,\n chatId: string,\n threadId: number,\n html: string,\n htmlRef: { current: string },\n setHtml: (html: string) => void,\n editedMessage: ApiMessage | undefined,\n) => {\n const { saveDraft, clearDraft } = getDispatch();\n\n const updateDraft = useCallback((draftChatId: string, draftThreadId: number) => {\n if (htmlRef.current.length && !editedMessage) {\n saveDraft({ chatId: draftChatId, threadId: draftThreadId, draft: parseMessageInput(htmlRef.current!) });\n } else {\n clearDraft({ chatId: draftChatId, threadId: draftThreadId });\n }\n }, [clearDraft, editedMessage, htmlRef, saveDraft]);\n\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const runDebouncedForSaveDraft = useMemo(() => debounce((cb) => cb(), DRAFT_DEBOUNCE, false), [chatId]);\n\n const prevChatId = usePrevious(chatId);\n const prevThreadId = usePrevious(threadId);\n\n // Save draft on chat change\n useEffect(() => {\n currentChatId = chatId;\n currentThreadId = threadId;\n\n return () => {\n currentChatId = undefined;\n currentThreadId = undefined;\n\n updateDraft(chatId, threadId);\n };\n }, [chatId, threadId, updateDraft]);\n\n // Restore draft on chat change\n useEffect(() => {\n if (chatId === prevChatId && threadId === prevThreadId) {\n return;\n }\n\n if (!draft) {\n return;\n }\n\n setHtml(getMessageTextAsHtml(draft));\n\n if (!IS_TOUCH_ENV) {\n requestAnimationFrame(() => {\n const messageInput = document.getElementById(EDITABLE_INPUT_ID)!;\n focusEditableElement(messageInput, true);\n });\n }\n }, [chatId, threadId, draft, setHtml, updateDraft, prevChatId, prevThreadId]);\n\n // Update draft when input changes\n const prevHtml = usePrevious(html);\n useEffect(() => {\n if (!chatId || !threadId || prevChatId !== chatId || prevThreadId !== threadId || prevHtml === html) {\n return;\n }\n\n if (html.length) {\n runDebouncedForSaveDraft(() => {\n if (currentChatId !== chatId || currentThreadId !== threadId) {\n return;\n }\n\n updateDraft(chatId, threadId);\n });\n } else {\n updateDraft(chatId, threadId);\n }\n }, [chatId, html, prevChatId, prevHtml, prevThreadId, runDebouncedForSaveDraft, threadId, updateDraft]);\n\n const handleBlur = useCallback(() => {\n if (chatId && threadId) {\n updateDraft(chatId, threadId);\n }\n }, [chatId, threadId, updateDraft]);\n\n useBackgroundMode(handleBlur);\n useBeforeUnload(handleBlur);\n};\n","import { useCallback, useEffect } from '../../../../lib/teact/teact';\nimport { getDispatch } from '../../../../lib/teact/teactn';\nimport { InlineBotSettings } from '../../../../types';\nimport useFlag from '../../../../hooks/useFlag';\nimport usePrevious from '../../../../hooks/usePrevious';\n\nconst tempEl = document.createElement('div');\nconst INLINE_BOT_QUERY_REGEXP = /^@([a-z0-9_]{1,32})[\\u00A0\\u0020]+(.*)/i;\nconst HAS_NEW_LINE = /^@([a-z0-9_]{1,32})[\\u00A0\\u0020]+\\n{2,}/i;\n\nexport default function useInlineBotTooltip(\n isAllowed: boolean,\n chatId: string,\n html: string,\n inlineBots?: Record,\n) {\n const [isOpen, markIsOpen, unmarkIsOpen] = useFlag();\n const text = getPlainText(html);\n const { queryInlineBot, resetInlineBot } = getDispatch();\n const { username, query, canShowHelp } = parseStartWithUsernameString(text);\n const usernameLowered = username.toLowerCase();\n const prevQuery = usePrevious(query);\n const prevUsername = usePrevious(username);\n const inlineBotData = inlineBots?.[usernameLowered];\n const {\n id: botId,\n switchPm,\n offset,\n results,\n isGallery,\n help,\n } = inlineBotData || {};\n\n useEffect(() => {\n if (prevQuery !== query) {\n unmarkIsOpen();\n }\n }, [prevQuery, query, unmarkIsOpen]);\n\n useEffect(() => {\n if (isAllowed && usernameLowered && chatId) {\n queryInlineBot({ chatId, username: usernameLowered, query });\n }\n }, [query, isAllowed, queryInlineBot, chatId, usernameLowered]);\n\n const loadMore = useCallback(() => {\n queryInlineBot({\n chatId, username: usernameLowered, query, offset,\n });\n }, [offset, chatId, query, queryInlineBot, usernameLowered]);\n\n useEffect(() => {\n if (isAllowed && botId && (switchPm || (results?.length))) {\n markIsOpen();\n } else {\n unmarkIsOpen();\n }\n }, [botId, isAllowed, markIsOpen, results, switchPm, unmarkIsOpen]);\n\n if (prevUsername !== username) {\n resetInlineBot({ username: prevUsername });\n }\n\n return {\n isOpen,\n closeTooltip: unmarkIsOpen,\n loadMore,\n username,\n id: botId,\n isGallery,\n switchPm,\n results,\n help: canShowHelp && help ? `@${username} ${help}` : undefined,\n };\n}\n\nfunction getPlainText(html: string) {\n tempEl.innerHTML = html.replace(/
/g, '\\n');\n\n return tempEl.innerText;\n}\n\nfunction parseStartWithUsernameString(text: string) {\n const result = text.match(INLINE_BOT_QUERY_REGEXP);\n if (!result) {\n return { username: '', query: '', canShowHelp: false };\n }\n\n return {\n username: result[1],\n query: result[2],\n canShowHelp: result[2] === '' && !text.match(HAS_NEW_LINE),\n };\n}\n","import {\n useCallback, useEffect, useState,\n} from '../../../../lib/teact/teact';\n\nimport { ApiBotCommand } from '../../../../api/types';\n\nimport { prepareForRegExp } from '../helpers/prepareForRegExp';\nimport { throttle } from '../../../../util/schedulers';\nimport useFlag from '../../../../hooks/useFlag';\n\nconst runThrottled = throttle((cb) => cb(), 500, true);\nconst RE_COMMAND = /^[\\w@]{1,32}\\s?/i;\n\nexport default function useBotCommandTooltip(\n isAllowed: boolean,\n html: string,\n botCommands?: ApiBotCommand[] | false,\n chatBotCommands?: ApiBotCommand[],\n) {\n const [isOpen, markIsOpen, unmarkIsOpen] = useFlag();\n const [filteredBotCommands, setFilteredBotCommands] = useState();\n\n const getFilteredCommands = useCallback((filter) => {\n if (!botCommands && !chatBotCommands) {\n setFilteredBotCommands(undefined);\n\n return;\n }\n\n runThrottled(() => {\n const nextFilteredBotCommands = (botCommands || chatBotCommands || [])\n .filter(({ command }) => !filter || command.includes(filter));\n setFilteredBotCommands(\n nextFilteredBotCommands && nextFilteredBotCommands.length ? nextFilteredBotCommands : undefined,\n );\n });\n }, [botCommands, chatBotCommands]);\n\n useEffect(() => {\n if (!isAllowed || !html.length) {\n unmarkIsOpen();\n return;\n }\n\n const shouldShowCommands = html.startsWith('/');\n\n if (shouldShowCommands) {\n const filter = prepareForRegExp(html.substr(1)).match(RE_COMMAND);\n getFilteredCommands(filter ? filter[0] : '');\n } else {\n unmarkIsOpen();\n }\n }, [getFilteredCommands, html, isAllowed, unmarkIsOpen]);\n\n useEffect(() => {\n if (filteredBotCommands && filteredBotCommands.length) {\n markIsOpen();\n } else {\n unmarkIsOpen();\n }\n }, [filteredBotCommands, markIsOpen, unmarkIsOpen]);\n\n return {\n isOpen,\n close: unmarkIsOpen,\n filteredBotCommands,\n };\n}\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './DeleteMessageModal';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst DeleteMessageModalAsync: FC = (props) => {\n const { isOpen } = props;\n const DeleteMessageModal = useModuleLoader(Bundles.Extra, 'DeleteMessageModal', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return DeleteMessageModal ? : undefined;\n};\n\nexport default memo(DeleteMessageModalAsync);\n","import React, {\n FC, useRef, useCallback, memo,\n} from '../../lib/teact/teact';\n\nimport { IS_TOUCH_ENV } from '../../util/environment';\n\nimport Button, { OwnProps as ButtonProps } from './Button';\n\ntype OwnProps = {\n onActivate: NoneToVoidFunction;\n} & Omit;\n\nconst BUTTON_ACTIVATE_DELAY = 200;\nlet openTimeout: number | undefined;\nlet isFirstTimeActivation = true;\n\nconst ResponsiveHoverButton: FC = ({ onActivate, ...buttonProps }) => {\n const isMouseInside = useRef(false);\n\n const handleMouseEnter = useCallback(() => {\n isMouseInside.current = true;\n\n // This is used to counter additional delay caused by asynchronous module loading\n if (isFirstTimeActivation) {\n isFirstTimeActivation = false;\n onActivate();\n return;\n }\n\n if (openTimeout) {\n clearTimeout(openTimeout);\n openTimeout = undefined;\n }\n openTimeout = window.setTimeout(() => {\n if (isMouseInside.current) {\n onActivate();\n }\n }, BUTTON_ACTIVATE_DELAY);\n }, [onActivate]);\n\n const handleMouseLeave = useCallback(() => {\n isMouseInside.current = false;\n }, []);\n\n return (\n \n );\n};\n\nexport default memo(ResponsiveHoverButton);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './AttachMenu';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst AttachMenuAsync: FC = (props) => {\n const { isOpen } = props;\n const AttachMenu = useModuleLoader(Bundles.Extra, 'AttachMenu', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return AttachMenu ? : undefined;\n};\n\nexport default memo(AttachMenuAsync);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './SymbolMenu';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst SymbolMenuAsync: FC = (props) => {\n const { isOpen } = props;\n const SymbolMenu = useModuleLoader(Bundles.Extra, 'SymbolMenu', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return SymbolMenu ? : undefined;\n};\n\nexport default memo(SymbolMenuAsync);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './InlineBotTooltip';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst InlineBotTooltipAsync: FC = (props) => {\n const { isOpen } = props;\n const InlineBotTooltip = useModuleLoader(Bundles.Extra, 'InlineBotTooltip', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return InlineBotTooltip ? : undefined;\n};\n\nexport default memo(InlineBotTooltipAsync);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './MentionTooltip';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst MentionTooltipAsync: FC = (props) => {\n const { isOpen } = props;\n const MentionTooltip = useModuleLoader(Bundles.Extra, 'MentionTooltip', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return MentionTooltip ? : undefined;\n};\n\nexport default memo(MentionTooltipAsync);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './CustomSendMenu';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst CustomSendMenuAsync: FC = (props) => {\n const { isOpen } = props;\n const CustomSend = useModuleLoader(Bundles.Extra, 'CustomSendMenu', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return CustomSend ? : undefined;\n};\n\nexport default memo(CustomSendMenuAsync);\n","import React, { FC } from '../../../lib/teact/teact';\nimport { OwnProps } from './StickerTooltip';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst StickerTooltipAsync: FC = (props) => {\n const { isOpen } = props;\n const StickerTooltip = useModuleLoader(Bundles.Extra, 'StickerTooltip', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return StickerTooltip ? : undefined;\n};\n\nexport default StickerTooltipAsync;\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './BotCommandTooltip';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst BotCommandTooltipAsync: FC = (props) => {\n const { isOpen } = props;\n const BotCommandTooltip = useModuleLoader(Bundles.Extra, 'BotCommandTooltip', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return BotCommandTooltip ? : undefined;\n};\n\nexport default memo(BotCommandTooltipAsync);\n","import React, { FC, memo, useEffect } from '../../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiMessage } from '../../../api/types';\n\nimport { IS_TOUCH_ENV } from '../../../util/environment';\nimport { selectChatMessage, selectCurrentMessageList } from '../../../modules/selectors';\nimport useMouseInside from '../../../hooks/useMouseInside';\nimport useFlag from '../../../hooks/useFlag';\n\nimport Menu from '../../ui/Menu';\nimport Button from '../../ui/Button';\n\nimport './BotKeyboardMenu.scss';\n\nexport type OwnProps = {\n isOpen: boolean;\n messageId: number;\n onClose: NoneToVoidFunction;\n};\n\ntype StateProps = {\n message?: ApiMessage;\n};\n\nconst BotKeyboardMenu: FC = ({\n isOpen, message, onClose,\n}) => {\n const { clickInlineButton } = getDispatch();\n\n const [handleMouseEnter, handleMouseLeave] = useMouseInside(isOpen, onClose);\n const { isKeyboardSingleUse } = message || {};\n const [forceOpen, markForceOpen, unmarkForceOpen] = useFlag(true);\n\n const handleClose = () => {\n unmarkForceOpen();\n onClose();\n };\n\n useEffect(() => {\n markForceOpen();\n }, [markForceOpen, message]);\n\n if (!message || !message.keyboardButtons) {\n return undefined;\n }\n\n return (\n \n
\n {message.keyboardButtons.map((row) => (\n
\n {row.map((button) => (\n clickInlineButton({ button })}\n >\n {button.text}\n \n ))}\n
\n ))}\n
\n \n );\n};\n\nexport default memo(withGlobal(\n (global, { messageId }): StateProps => {\n const { chatId } = selectCurrentMessageList(global) || {};\n if (!chatId) {\n return {};\n }\n\n return { message: selectChatMessage(global, chatId, messageId) };\n },\n)(BotKeyboardMenu));\n","import React, {\n FC, memo, useCallback, useEffect,\n} from '../../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiChat, ApiMessage, ApiUser } from '../../../api/types';\n\nimport {\n selectChat,\n selectChatMessage,\n selectSender,\n selectForwardedSender,\n selectUser,\n selectCurrentMessageList,\n selectReplyingToId,\n selectEditingId,\n selectEditingScheduledId,\n selectEditingMessage,\n} from '../../../modules/selectors';\nimport captureEscKeyListener from '../../../util/captureEscKeyListener';\nimport useAsyncRendering from '../../right/hooks/useAsyncRendering';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport buildClassName from '../../../util/buildClassName';\nimport { isUserId } from '../../../modules/helpers';\n\nimport Button from '../../ui/Button';\nimport EmbeddedMessage from '../../common/EmbeddedMessage';\n\nimport './ComposerEmbeddedMessage.scss';\n\ntype StateProps = {\n replyingToId?: number;\n editingId?: number;\n message?: ApiMessage;\n sender?: ApiUser | ApiChat;\n shouldAnimate?: boolean;\n forwardedMessagesCount?: number;\n};\n\nconst FORWARD_RENDERING_DELAY = 300;\n\nconst ComposerEmbeddedMessage: FC = ({\n replyingToId,\n editingId,\n message,\n sender,\n shouldAnimate,\n forwardedMessagesCount,\n}) => {\n const {\n setReplyingToId,\n setEditingId,\n focusMessage,\n exitForwardMode,\n } = getDispatch();\n\n const isShown = Boolean(\n ((replyingToId || editingId) && message)\n || (sender && forwardedMessagesCount),\n );\n const canAnimate = useAsyncRendering(\n [forwardedMessagesCount],\n forwardedMessagesCount ? FORWARD_RENDERING_DELAY : undefined,\n );\n\n const {\n shouldRender, transitionClassNames,\n } = useShowTransition(canAnimate && isShown, undefined, !shouldAnimate, undefined, !shouldAnimate);\n\n const clearEmbedded = useCallback(() => {\n if (replyingToId) {\n setReplyingToId({ messageId: undefined });\n } else if (editingId) {\n setEditingId({ messageId: undefined });\n } else if (forwardedMessagesCount) {\n exitForwardMode();\n }\n }, [replyingToId, editingId, forwardedMessagesCount, setReplyingToId, setEditingId, exitForwardMode]);\n\n useEffect(() => (isShown ? captureEscKeyListener(clearEmbedded) : undefined), [isShown, clearEmbedded]);\n\n const handleMessageClick = useCallback((): void => {\n focusMessage({ chatId: message!.chatId, messageId: message!.id });\n }, [focusMessage, message]);\n\n const className = buildClassName('ComposerEmbeddedMessage', transitionClassNames);\n\n const customText = forwardedMessagesCount && forwardedMessagesCount > 1\n ? `${forwardedMessagesCount} forwarded messages`\n : undefined;\n\n if (!shouldRender) {\n return undefined;\n }\n\n return (\n
\n
\n \n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { chatId, threadId, type: messageListType } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId || !messageListType) {\n return {};\n }\n\n const {\n currentUserId,\n forwardMessages: { fromChatId, toChatId, messageIds: forwardMessageIds },\n } = global;\n\n const replyingToId = selectReplyingToId(global, chatId, threadId);\n const editingId = messageListType === 'scheduled'\n ? selectEditingScheduledId(global, chatId)\n : selectEditingId(global, chatId, threadId);\n const shouldAnimate = global.settings.byKey.animationLevel >= 1;\n const isForwarding = toChatId === chatId;\n\n let message;\n if (replyingToId) {\n message = selectChatMessage(global, chatId, replyingToId);\n } else if (editingId) {\n message = selectEditingMessage(global, chatId, threadId, messageListType);\n } else if (isForwarding && forwardMessageIds!.length === 1) {\n message = selectChatMessage(global, fromChatId!, forwardMessageIds![0]);\n }\n\n let sender: ApiChat | ApiUser | undefined;\n if (replyingToId && message) {\n const { forwardInfo } = message;\n const isChatWithSelf = chatId === currentUserId;\n\n if (forwardInfo && (forwardInfo.isChannelPost || isChatWithSelf)) {\n sender = selectForwardedSender(global, message);\n }\n\n if (!sender) {\n sender = selectSender(global, message);\n }\n } else if (isForwarding) {\n sender = isUserId(fromChatId!) ? selectUser(global, fromChatId!) : selectChat(global, fromChatId!);\n }\n\n return {\n replyingToId,\n editingId,\n message,\n sender,\n shouldAnimate,\n forwardedMessagesCount: isForwarding ? forwardMessageIds!.length : undefined,\n };\n },\n)(ComposerEmbeddedMessage));\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './AttachmentModal';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst AttachmentModalAsync: FC = (props) => {\n const { attachments } = props;\n const AttachmentModal = useModuleLoader(Bundles.Extra, 'AttachmentModal', !attachments.length);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return AttachmentModal ? : undefined;\n};\n\nexport default memo(AttachmentModalAsync);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './BotCommandMenu';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst BotCommandMenuAsync: FC = (props) => {\n const { isOpen } = props;\n const BotCommandMenu = useModuleLoader(Bundles.Extra, 'BotCommandMenu', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return BotCommandMenu ? : undefined;\n};\n\nexport default memo(BotCommandMenuAsync);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './PollModal';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst PollModalAsync: FC = (props) => {\n const { isOpen } = props;\n const PollModal = useModuleLoader(Bundles.Extra, 'PollModal', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return PollModal ? : undefined;\n};\n\nexport default memo(PollModalAsync);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './DropArea';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst DropAreaAsync: FC = (props) => {\n const { isOpen } = props;\n const DropArea = useModuleLoader(Bundles.Extra, 'DropArea', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return DropArea ? : undefined;\n};\n\nexport default memo(DropAreaAsync);\nexport { DropAreaState } from './DropArea';\n","import React, {\n FC, memo, useEffect, useMemo,\n} from '../../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiMessage, ApiMessageEntityTypes, ApiWebPage } from '../../../api/types';\nimport { ISettings } from '../../../types';\n\nimport { RE_LINK_TEMPLATE } from '../../../config';\nimport { selectNoWebPage, selectTheme } from '../../../modules/selectors';\nimport parseMessageInput from '../../../util/parseMessageInput';\nimport useOnChange from '../../../hooks/useOnChange';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useCurrentOrPrev from '../../../hooks/useCurrentOrPrev';\nimport buildClassName from '../../../util/buildClassName';\n\nimport WebPage from '../message/WebPage';\nimport Button from '../../ui/Button';\n\nimport './WebPagePreview.scss';\n\ntype OwnProps = {\n chatId: string;\n threadId: number;\n messageText: string;\n disabled?: boolean;\n};\n\ntype StateProps = {\n webPagePreview?: ApiWebPage;\n noWebPage?: boolean;\n theme: ISettings['theme'];\n};\n\nconst RE_LINK = new RegExp(RE_LINK_TEMPLATE, 'i');\n\nconst WebPagePreview: FC = ({\n chatId,\n threadId,\n messageText,\n disabled,\n webPagePreview,\n noWebPage,\n theme,\n}) => {\n const {\n loadWebPagePreview,\n clearWebPagePreview,\n toggleMessageWebPage,\n } = getDispatch();\n\n const link = useMemo(() => {\n const { text, entities } = parseMessageInput(messageText);\n\n const linkEntity = entities && entities.find(({ type }) => type === ApiMessageEntityTypes.TextUrl);\n if (linkEntity) {\n return linkEntity.url;\n }\n\n const textMatch = text.match(RE_LINK);\n if (textMatch) {\n return textMatch[0];\n }\n\n return undefined;\n }, [messageText]);\n\n useEffect(() => {\n if (link) {\n loadWebPagePreview({ text: link });\n } else {\n clearWebPagePreview();\n toggleMessageWebPage({ chatId, threadId });\n }\n }, [chatId, toggleMessageWebPage, clearWebPagePreview, link, loadWebPagePreview, threadId]);\n\n useOnChange(() => {\n clearWebPagePreview();\n toggleMessageWebPage({ chatId, threadId });\n }, [chatId]);\n\n const isShown = Boolean(webPagePreview && messageText.length && !noWebPage && !disabled);\n const { shouldRender, transitionClassNames } = useShowTransition(isShown);\n\n const renderingWebPage = useCurrentOrPrev(webPagePreview, true);\n\n if (!shouldRender || !renderingWebPage) {\n return undefined;\n }\n\n const handleClearWebpagePreview = () => {\n toggleMessageWebPage({ chatId, threadId, noWebPage: true });\n };\n\n // TODO Refactor so `WebPage` can be used without message\n const { photo, ...webPageWithoutPhoto } = renderingWebPage;\n const messageStub = {\n content: {\n webPage: webPageWithoutPhoto,\n },\n } as ApiMessage;\n\n return (\n
\n
\n \n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { chatId, threadId }): StateProps => {\n const noWebPage = selectNoWebPage(global, chatId, threadId);\n return {\n theme: selectTheme(global),\n webPagePreview: global.webPagePreview,\n noWebPage,\n };\n },\n)(WebPagePreview));\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './CalendarModal';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst CalendarModalAsync: FC = (props) => {\n const { isOpen } = props;\n const CalendarModal = useModuleLoader(Bundles.Extra, 'CalendarModal', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return CalendarModal ? : undefined;\n};\n\nexport default memo(CalendarModalAsync);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './SendAsMenu';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst SendAsMenuAsync: FC = (props) => {\n const { isOpen } = props;\n const SendAsMenu = useModuleLoader(Bundles.Extra, 'SendAsMenu', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return SendAsMenu ? : undefined;\n};\n\nexport default memo(SendAsMenuAsync);\n","import React, {\n FC, memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState,\n} from '../../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalState, MessageListType } from '../../../global/types';\nimport {\n ApiAttachment,\n ApiBotInlineResult,\n ApiBotInlineMediaResult,\n ApiSticker,\n ApiVideo,\n ApiNewPoll,\n ApiMessage,\n ApiFormattedText,\n ApiChat,\n ApiChatMember,\n ApiUser,\n MAIN_THREAD_ID,\n ApiBotCommand,\n} from '../../../api/types';\nimport { InlineBotSettings } from '../../../types';\n\nimport {\n BASE_EMOJI_KEYWORD_LANG, EDITABLE_INPUT_ID, REPLIES_USER_ID, SCHEDULED_WHEN_ONLINE, SEND_MESSAGE_ACTION_INTERVAL,\n} from '../../../config';\nimport { IS_VOICE_RECORDING_SUPPORTED, IS_SINGLE_COLUMN_LAYOUT, IS_IOS } from '../../../util/environment';\nimport {\n selectChat,\n selectIsRightColumnShown,\n selectIsInSelectMode,\n selectNewestMessageWithBotKeyboardButtons,\n selectDraft,\n selectScheduledIds,\n selectEditingMessage,\n selectIsChatWithSelf,\n selectChatBot,\n selectChatUser,\n selectChatMessage,\n selectUserStatus,\n} from '../../../modules/selectors';\nimport {\n getAllowedAttachmentOptions,\n getChatSlowModeOptions,\n isUserId,\n isChatAdmin,\n isChatSuperGroup,\n} from '../../../modules/helpers';\nimport { formatMediaDuration, formatVoiceRecordDuration, getDayStartAt } from '../../../util/dateFormat';\nimport focusEditableElement from '../../../util/focusEditableElement';\nimport parseMessageInput from '../../../util/parseMessageInput';\nimport buildAttachment from './helpers/buildAttachment';\nimport renderText from '../../common/helpers/renderText';\nimport insertHtmlInSelection from '../../../util/insertHtmlInSelection';\nimport deleteLastCharacterOutsideSelection from '../../../util/deleteLastCharacterOutsideSelection';\nimport buildClassName from '../../../util/buildClassName';\nimport windowSize from '../../../util/windowSize';\nimport { isSelectionInsideInput } from './helpers/selection';\nimport applyIosAutoCapitalizationFix from './helpers/applyIosAutoCapitalizationFix';\nimport { getServerTime } from '../../../util/serverTime';\n\nimport useFlag from '../../../hooks/useFlag';\nimport usePrevious from '../../../hooks/usePrevious';\nimport useStickerTooltip from './hooks/useStickerTooltip';\nimport useContextMenuHandlers from '../../../hooks/useContextMenuHandlers';\nimport useLang from '../../../hooks/useLang';\nimport useSendMessageAction from '../../../hooks/useSendMessageAction';\nimport useInterval from '../../../hooks/useInterval';\nimport useOnChange from '../../../hooks/useOnChange';\nimport useVoiceRecording from './hooks/useVoiceRecording';\nimport useClipboardPaste from './hooks/useClipboardPaste';\nimport useDraft from './hooks/useDraft';\nimport useEditing from './hooks/useEditing';\nimport useEmojiTooltip from './hooks/useEmojiTooltip';\nimport useMentionTooltip from './hooks/useMentionTooltip';\nimport useInlineBotTooltip from './hooks/useInlineBotTooltip';\nimport useBotCommandTooltip from './hooks/useBotCommandTooltip';\n\nimport DeleteMessageModal from '../../common/DeleteMessageModal.async';\nimport Button from '../../ui/Button';\nimport ResponsiveHoverButton from '../../ui/ResponsiveHoverButton';\nimport Spinner from '../../ui/Spinner';\nimport AttachMenu from './AttachMenu.async';\nimport SymbolMenu from './SymbolMenu.async';\nimport InlineBotTooltip from './InlineBotTooltip.async';\nimport MentionTooltip from './MentionTooltip.async';\nimport CustomSendMenu from './CustomSendMenu.async';\nimport StickerTooltip from './StickerTooltip.async';\nimport EmojiTooltip from './EmojiTooltip.async';\nimport BotCommandTooltip from './BotCommandTooltip.async';\nimport BotKeyboardMenu from './BotKeyboardMenu';\nimport MessageInput from './MessageInput';\nimport ComposerEmbeddedMessage from './ComposerEmbeddedMessage';\nimport AttachmentModal from './AttachmentModal.async';\nimport BotCommandMenu from './BotCommandMenu.async';\nimport PollModal from './PollModal.async';\nimport DropArea, { DropAreaState } from './DropArea.async';\nimport WebPagePreview from './WebPagePreview';\nimport Portal from '../../ui/Portal';\nimport CalendarModal from '../../common/CalendarModal.async';\nimport SendAsMenu from './SendAsMenu.async';\nimport Avatar from '../../common/Avatar';\n\nimport './Composer.scss';\n\ntype OwnProps = {\n chatId: string;\n threadId: number;\n messageListType: MessageListType;\n dropAreaState: string;\n isReady: boolean;\n onDropHide: NoneToVoidFunction;\n};\n\ntype StateProps =\n {\n editingMessage?: ApiMessage;\n chat?: ApiChat;\n draft?: ApiFormattedText;\n isChatWithBot?: boolean;\n isChatWithSelf?: boolean;\n isRightColumnShown?: boolean;\n isSelectModeActive?: boolean;\n isForwarding?: boolean;\n isPollModalOpen?: boolean;\n botKeyboardMessageId?: number;\n botKeyboardPlaceholder?: string;\n withScheduledButton?: boolean;\n shouldSchedule?: boolean;\n canScheduleUntilOnline?: boolean;\n stickersForEmoji?: ApiSticker[];\n groupChatMembers?: ApiChatMember[];\n currentUserId?: string;\n usersById?: Record;\n recentEmojis: string[];\n lastSyncTime?: number;\n contentToBeScheduled?: GlobalState['messages']['contentToBeScheduled'];\n shouldSuggestStickers?: boolean;\n baseEmojiKeywords?: Record;\n emojiKeywords?: Record;\n serverTimeOffset: number;\n topInlineBotIds?: string[];\n isInlineBotLoading: boolean;\n inlineBots?: Record;\n botCommands?: ApiBotCommand[] | false;\n chatBotCommands?: ApiBotCommand[];\n sendAsUser?: ApiUser;\n sendAsChat?: ApiChat;\n sendAsId?: string;\n }\n & Pick;\n\nenum MainButtonState {\n Send = 'send',\n Record = 'record',\n Edit = 'edit',\n}\n\nconst VOICE_RECORDING_FILENAME = 'wonderful-voice-message.ogg';\n// When voice recording is active, composer placeholder will hide to prevent overlapping\nconst SCREEN_WIDTH_TO_HIDE_PLACEHOLDER = 600; // px\n\nconst MOBILE_KEYBOARD_HIDE_DELAY_MS = 100;\nconst SELECT_MODE_TRANSITION_MS = 200;\nconst MESSAGE_MAX_LENGTH = 4096;\nconst CAPTION_MAX_LENGTH = 1024;\nconst SENDING_ANIMATION_DURATION = 350;\n// eslint-disable-next-line max-len\nconst APPENDIX = '';\n\nconst Composer: FC = ({\n dropAreaState,\n shouldSchedule,\n canScheduleUntilOnline,\n isReady,\n onDropHide,\n editingMessage,\n chatId,\n threadId,\n messageListType,\n draft,\n chat,\n connectionState,\n isChatWithBot,\n isChatWithSelf,\n isRightColumnShown,\n isSelectModeActive,\n isForwarding,\n isPollModalOpen,\n botKeyboardMessageId,\n botKeyboardPlaceholder,\n withScheduledButton,\n stickersForEmoji,\n groupChatMembers,\n topInlineBotIds,\n currentUserId,\n usersById,\n lastSyncTime,\n contentToBeScheduled,\n shouldSuggestStickers,\n baseEmojiKeywords,\n emojiKeywords,\n serverTimeOffset,\n recentEmojis,\n inlineBots,\n isInlineBotLoading,\n botCommands,\n chatBotCommands,\n sendAsUser,\n sendAsChat,\n sendAsId,\n}) => {\n const {\n sendMessage,\n clearDraft,\n showDialog,\n setStickerSearchQuery,\n setGifSearchQuery,\n forwardMessages,\n openPollModal,\n closePollModal,\n loadScheduledHistory,\n openChat,\n addRecentEmoji,\n sendInlineBotResult,\n loadSendAs,\n } = getDispatch();\n const lang = useLang();\n\n // eslint-disable-next-line no-null/no-null\n const appendixRef = useRef(null);\n const [html, setHtml] = useState('');\n const lastMessageSendTimeSeconds = useRef();\n const prevDropAreaState = usePrevious(dropAreaState);\n const [isCalendarOpen, openCalendar, closeCalendar] = useFlag();\n const [\n scheduledMessageArgs, setScheduledMessageArgs,\n ] = useState();\n const { width: windowWidth } = windowSize.get();\n const sendAsIds = chat?.sendAsIds;\n const sendMessageAction = useSendMessageAction(chatId, threadId);\n\n // Cache for frequently updated state\n const htmlRef = useRef(html);\n useEffect(() => {\n htmlRef.current = html;\n }, [html]);\n\n useEffect(() => {\n lastMessageSendTimeSeconds.current = undefined;\n }, [chatId]);\n\n useEffect(() => {\n if (chatId && lastSyncTime && threadId === MAIN_THREAD_ID && isReady) {\n loadScheduledHistory({ chatId });\n }\n }, [isReady, chatId, loadScheduledHistory, lastSyncTime, threadId]);\n\n useEffect(() => {\n if (chatId && chat && lastSyncTime && !sendAsIds && isReady && isChatSuperGroup(chat)) {\n loadSendAs({ chatId });\n }\n }, [chat, chatId, isReady, lastSyncTime, loadSendAs, sendAsIds]);\n\n const shouldAnimateSendAsButtonRef = useRef(false);\n useOnChange(([prevChatId, prevSendAsIds]) => {\n // We only animate send-as button if `sendAsIds` was missing when opening the chat\n shouldAnimateSendAsButtonRef.current = Boolean(chatId === prevChatId && sendAsIds && !prevSendAsIds);\n }, [chatId, sendAsIds]);\n\n useLayoutEffect(() => {\n if (!appendixRef.current) return;\n\n appendixRef.current.innerHTML = APPENDIX;\n }, []);\n\n useEffect(() => {\n if (contentToBeScheduled) {\n setScheduledMessageArgs(contentToBeScheduled);\n openCalendar();\n }\n }, [contentToBeScheduled, openCalendar]);\n\n const [attachments, setAttachments] = useState([]);\n\n const [isBotKeyboardOpen, openBotKeyboard, closeBotKeyboard] = useFlag();\n const [isBotCommandMenuOpen, openBotCommandMenu, closeBotCommandMenu] = useFlag();\n const [isAttachMenuOpen, openAttachMenu, closeAttachMenu] = useFlag();\n const [isSymbolMenuOpen, openSymbolMenu, closeSymbolMenu] = useFlag();\n const [isSendAsMenuOpen, openSendAsMenu, closeSendAsMenu] = useFlag();\n const [isDeleteModalOpen, openDeleteModal, closeDeleteModal] = useFlag();\n const [isSymbolMenuLoaded, onSymbolMenuLoadingComplete] = useFlag();\n const [isHoverDisabled, disableHover, enableHover] = useFlag();\n\n const {\n startRecordingVoice,\n stopRecordingVoice,\n pauseRecordingVoice,\n activeVoiceRecording,\n currentRecordTime,\n recordButtonRef: mainButtonRef,\n startRecordTimeRef,\n } = useVoiceRecording();\n\n useInterval(() => {\n sendMessageAction({ type: 'recordAudio' });\n }, activeVoiceRecording && SEND_MESSAGE_ACTION_INTERVAL);\n\n useEffect(() => {\n if (!activeVoiceRecording) {\n sendMessageAction({ type: 'cancel' });\n }\n }, [activeVoiceRecording, sendMessageAction]);\n\n const mainButtonState = editingMessage\n ? MainButtonState.Edit\n : !IS_VOICE_RECORDING_SUPPORTED || activeVoiceRecording || (html && !attachments.length) || isForwarding\n ? MainButtonState.Send\n : MainButtonState.Record;\n const canShowCustomSendMenu = !shouldSchedule;\n\n const {\n isMentionTooltipOpen, closeMentionTooltip, insertMention, mentionFilteredUsers,\n } = useMentionTooltip(\n !attachments.length,\n html,\n setHtml,\n undefined,\n groupChatMembers,\n topInlineBotIds,\n currentUserId,\n );\n\n const {\n isOpen: isInlineBotTooltipOpen,\n id: inlineBotId,\n isGallery: isInlineBotTooltipGallery,\n switchPm: inlineBotSwitchPm,\n results: inlineBotResults,\n closeTooltip: closeInlineBotTooltip,\n help: inlineBotHelp,\n loadMore: loadMoreForInlineBot,\n } = useInlineBotTooltip(\n Boolean(!attachments.length && lastSyncTime),\n chatId,\n html,\n inlineBots,\n );\n\n const {\n isOpen: isBotCommandTooltipOpen,\n close: closeBotCommandTooltip,\n filteredBotCommands: botTooltipCommands,\n } = useBotCommandTooltip(\n Boolean((botCommands && botCommands.length) || (chatBotCommands && chatBotCommands.length)),\n html,\n botCommands,\n chatBotCommands,\n );\n\n const {\n isContextMenuOpen: isCustomSendMenuOpen,\n handleContextMenu,\n handleContextMenuClose,\n handleContextMenuHide,\n } = useContextMenuHandlers(mainButtonRef, !(mainButtonState === MainButtonState.Send && canShowCustomSendMenu));\n\n const allowedAttachmentOptions = useMemo(() => {\n return getAllowedAttachmentOptions(chat, isChatWithBot);\n }, [chat, isChatWithBot]);\n\n const isAdmin = chat && isChatAdmin(chat);\n const slowMode = getChatSlowModeOptions(chat);\n\n const { isStickerTooltipOpen, closeStickerTooltip } = useStickerTooltip(\n Boolean(shouldSuggestStickers && allowedAttachmentOptions.canSendStickers && !attachments.length),\n html,\n stickersForEmoji,\n !isReady,\n );\n const {\n isEmojiTooltipOpen, closeEmojiTooltip, filteredEmojis, insertEmoji,\n } = useEmojiTooltip(\n Boolean(shouldSuggestStickers && allowedAttachmentOptions.canSendStickers && !attachments.length),\n html,\n recentEmojis,\n undefined,\n setHtml,\n baseEmojiKeywords,\n emojiKeywords,\n !isReady,\n );\n\n const insertTextAndUpdateCursor = useCallback((text: string, inputId: string = EDITABLE_INPUT_ID) => {\n const selection = window.getSelection()!;\n const messageInput = document.getElementById(inputId)!;\n const newHtml = renderText(text, ['escape_html', 'emoji_html', 'br_html'])\n .join('')\n .replace(/\\u200b+/g, '\\u200b');\n\n if (selection.rangeCount) {\n const selectionRange = selection.getRangeAt(0);\n if (isSelectionInsideInput(selectionRange, inputId)) {\n insertHtmlInSelection(newHtml);\n messageInput.dispatchEvent(new Event('input', { bubbles: true }));\n return;\n }\n }\n\n setHtml(`${htmlRef.current!}${newHtml}`);\n\n // If selection is outside of input, set cursor at the end of input\n requestAnimationFrame(() => {\n focusEditableElement(messageInput);\n });\n }, []);\n\n const removeSymbol = useCallback(() => {\n const selection = window.getSelection()!;\n\n if (selection.rangeCount) {\n const selectionRange = selection.getRangeAt(0);\n if (isSelectionInsideInput(selectionRange, EDITABLE_INPUT_ID)) {\n document.execCommand('delete', false);\n return;\n }\n }\n\n setHtml(deleteLastCharacterOutsideSelection(htmlRef.current!));\n }, []);\n\n const resetComposer = useCallback((shouldPreserveInput = false) => {\n if (!shouldPreserveInput) {\n setHtml('');\n }\n setAttachments([]);\n closeStickerTooltip();\n closeCalendar();\n setScheduledMessageArgs(undefined);\n closeMentionTooltip();\n closeEmojiTooltip();\n\n if (IS_SINGLE_COLUMN_LAYOUT) {\n // @optimization\n setTimeout(() => closeSymbolMenu(), SENDING_ANIMATION_DURATION);\n } else {\n closeSymbolMenu();\n }\n }, [closeStickerTooltip, closeCalendar, closeMentionTooltip, closeEmojiTooltip, closeSymbolMenu]);\n\n // Handle chat change (ref is used to avoid redundant effect calls)\n const stopRecordingVoiceRef = useRef();\n stopRecordingVoiceRef.current = stopRecordingVoice;\n useEffect(() => {\n return () => {\n stopRecordingVoiceRef.current!();\n resetComposer();\n };\n }, [chatId, resetComposer, stopRecordingVoiceRef]);\n\n const handleEditComplete = useEditing(htmlRef, setHtml, editingMessage, resetComposer, openDeleteModal);\n useDraft(draft, chatId, threadId, html, htmlRef, setHtml, editingMessage);\n useClipboardPaste(insertTextAndUpdateCursor, setAttachments, editingMessage);\n\n const handleFileSelect = useCallback(async (files: File[], isQuick: boolean) => {\n setAttachments(await Promise.all(files.map((file) => buildAttachment(file.name, file, isQuick))));\n }, []);\n\n const handleAppendFiles = useCallback(async (files: File[], isQuick: boolean) => {\n setAttachments([\n ...attachments,\n ...await Promise.all(files.map((file) => buildAttachment(file.name, file, isQuick))),\n ]);\n }, [attachments]);\n\n const handleClearAttachment = useCallback(() => {\n setAttachments([]);\n }, []);\n\n const handleSend = useCallback(async (isSilent = false, scheduledAt?: number) => {\n if (connectionState !== 'connectionStateReady') {\n return;\n }\n\n let currentAttachments = attachments;\n\n if (activeVoiceRecording) {\n const record = await stopRecordingVoice();\n if (record) {\n const { blob, duration, waveform } = record;\n currentAttachments = [await buildAttachment(\n VOICE_RECORDING_FILENAME,\n blob,\n false,\n { voice: { duration, waveform } },\n )];\n }\n }\n\n const { text, entities } = parseMessageInput(htmlRef.current!);\n\n if (!currentAttachments.length && !text && !isForwarding) {\n return;\n }\n\n const maxLength = currentAttachments.length ? CAPTION_MAX_LENGTH : MESSAGE_MAX_LENGTH;\n if (text?.length > maxLength) {\n const extraLength = text.length - maxLength;\n showDialog({\n data: {\n message: 'MESSAGE_TOO_LONG_PLEASE_REMOVE_CHARACTERS',\n textParams: {\n '{EXTRA_CHARS_COUNT}': extraLength,\n '{PLURAL_S}': extraLength > 1 ? 's' : '',\n },\n hasErrorKey: true,\n },\n });\n\n return;\n }\n\n const messageInput = document.getElementById(EDITABLE_INPUT_ID)!;\n\n if (currentAttachments.length || text) {\n if (slowMode && !isAdmin) {\n const nowSeconds = getServerTime(serverTimeOffset);\n const secondsSinceLastMessage = lastMessageSendTimeSeconds.current\n && Math.floor(nowSeconds - lastMessageSendTimeSeconds.current);\n const nextSendDateNotReached = slowMode.nextSendDate && slowMode.nextSendDate > nowSeconds;\n\n if (\n (secondsSinceLastMessage && secondsSinceLastMessage < slowMode.seconds)\n || nextSendDateNotReached\n ) {\n const secondsRemaining = nextSendDateNotReached\n ? slowMode.nextSendDate! - nowSeconds\n : slowMode.seconds - secondsSinceLastMessage!;\n showDialog({\n data: {\n message: lang('SlowModeHint', formatMediaDuration(secondsRemaining)),\n isSlowMode: true,\n hasErrorKey: false,\n },\n });\n\n messageInput.blur();\n\n return;\n }\n }\n\n sendMessage({\n text,\n entities,\n attachments: currentAttachments,\n scheduledAt,\n isSilent,\n });\n }\n\n if (isForwarding) {\n forwardMessages({\n scheduledAt,\n isSilent,\n });\n }\n\n lastMessageSendTimeSeconds.current = getServerTime(serverTimeOffset);\n\n clearDraft({ chatId, localOnly: true });\n\n if (IS_IOS && messageInput === document.activeElement) {\n applyIosAutoCapitalizationFix(messageInput);\n }\n\n // Wait until message animation starts\n requestAnimationFrame(() => {\n resetComposer();\n });\n }, [\n connectionState, attachments, activeVoiceRecording, isForwarding, clearDraft, chatId, serverTimeOffset,\n resetComposer, stopRecordingVoice, showDialog, slowMode, isAdmin, sendMessage, forwardMessages, lang,\n ]);\n\n const handleActivateBotCommandMenu = useCallback(() => {\n closeSymbolMenu();\n openBotCommandMenu();\n }, [closeSymbolMenu, openBotCommandMenu]);\n\n const handleActivateSymbolMenu = useCallback(() => {\n closeBotCommandMenu();\n closeSendAsMenu();\n openSymbolMenu();\n }, [closeBotCommandMenu, closeSendAsMenu, openSymbolMenu]);\n\n const handleStickerSelect = useCallback((sticker: ApiSticker, shouldPreserveInput = false) => {\n sticker = {\n ...sticker,\n isPreloadedGlobally: true,\n };\n\n if (shouldSchedule) {\n setScheduledMessageArgs({ sticker });\n openCalendar();\n } else {\n sendMessage({ sticker });\n requestAnimationFrame(() => {\n resetComposer(shouldPreserveInput);\n });\n }\n }, [shouldSchedule, openCalendar, sendMessage, resetComposer]);\n\n const handleGifSelect = useCallback((gif: ApiVideo) => {\n if (shouldSchedule) {\n setScheduledMessageArgs({ gif });\n openCalendar();\n } else {\n sendMessage({ gif });\n requestAnimationFrame(() => {\n resetComposer(true);\n });\n }\n }, [shouldSchedule, openCalendar, sendMessage, resetComposer]);\n\n const handleInlineBotSelect = useCallback((inlineResult: ApiBotInlineResult | ApiBotInlineMediaResult) => {\n if (connectionState !== 'connectionStateReady') {\n return;\n }\n\n sendInlineBotResult({\n id: inlineResult.id,\n queryId: inlineResult.queryId,\n });\n\n const messageInput = document.getElementById(EDITABLE_INPUT_ID)!;\n if (IS_IOS && messageInput === document.activeElement) {\n applyIosAutoCapitalizationFix(messageInput);\n }\n\n clearDraft({ chatId, localOnly: true });\n requestAnimationFrame(() => {\n resetComposer();\n });\n }, [chatId, clearDraft, connectionState, resetComposer, sendInlineBotResult]);\n\n const handleBotCommandSelect = useCallback(() => {\n clearDraft({ chatId, localOnly: true });\n requestAnimationFrame(() => {\n resetComposer();\n });\n }, [chatId, clearDraft, resetComposer]);\n\n const handlePollSend = useCallback((poll: ApiNewPoll) => {\n if (shouldSchedule) {\n setScheduledMessageArgs({ poll });\n closePollModal();\n openCalendar();\n } else {\n sendMessage({ poll });\n closePollModal();\n }\n }, [closePollModal, openCalendar, sendMessage, shouldSchedule]);\n\n const handleSilentSend = useCallback(() => {\n if (shouldSchedule) {\n setScheduledMessageArgs({ isSilent: true });\n openCalendar();\n } else {\n void handleSend(true);\n }\n }, [handleSend, openCalendar, shouldSchedule]);\n\n const handleMessageSchedule = useCallback((date: Date, isWhenOnline = false) => {\n const { isSilent, ...restArgs } = scheduledMessageArgs || {};\n\n // Scheduled time can not be less than 10 seconds in future\n const scheduledAt = Math.round(Math.max(date.getTime(), Date.now() + 60 * 1000) / 1000)\n + (isWhenOnline ? 0 : serverTimeOffset);\n\n if (!scheduledMessageArgs || Object.keys(restArgs).length === 0) {\n void handleSend(!!isSilent, scheduledAt);\n } else {\n sendMessage({\n ...scheduledMessageArgs,\n scheduledAt,\n });\n requestAnimationFrame(() => {\n resetComposer();\n });\n }\n closeCalendar();\n }, [closeCalendar, handleSend, resetComposer, scheduledMessageArgs, sendMessage, serverTimeOffset]);\n\n const handleMessageScheduleUntilOnline = useCallback(() => {\n handleMessageSchedule(new Date(SCHEDULED_WHEN_ONLINE * 1000), true);\n }, [handleMessageSchedule]);\n\n const handleCloseCalendar = useCallback(() => {\n closeCalendar();\n setScheduledMessageArgs(undefined);\n }, [closeCalendar]);\n\n const handleSearchOpen = useCallback((type: 'stickers' | 'gifs') => {\n if (type === 'stickers') {\n setStickerSearchQuery({ query: '' });\n setGifSearchQuery({ query: undefined });\n } else {\n setGifSearchQuery({ query: '' });\n setStickerSearchQuery({ query: undefined });\n }\n }, [setStickerSearchQuery, setGifSearchQuery]);\n\n const handleSymbolMenuOpen = useCallback(() => {\n const messageInput = document.getElementById(EDITABLE_INPUT_ID)!;\n\n if (!IS_SINGLE_COLUMN_LAYOUT || messageInput !== document.activeElement) {\n openSymbolMenu();\n return;\n }\n\n messageInput.blur();\n setTimeout(() => {\n closeBotCommandMenu();\n openSymbolMenu();\n }, MOBILE_KEYBOARD_HIDE_DELAY_MS);\n }, [openSymbolMenu, closeBotCommandMenu]);\n\n const handleSendAsMenuOpen = useCallback(() => {\n const messageInput = document.getElementById(EDITABLE_INPUT_ID)!;\n\n if (!IS_SINGLE_COLUMN_LAYOUT || messageInput !== document.activeElement) {\n closeBotCommandMenu();\n closeSymbolMenu();\n openSendAsMenu();\n return;\n }\n\n messageInput.blur();\n setTimeout(() => {\n closeBotCommandMenu();\n closeSymbolMenu();\n openSendAsMenu();\n }, MOBILE_KEYBOARD_HIDE_DELAY_MS);\n }, [closeBotCommandMenu, closeSymbolMenu, openSendAsMenu]);\n\n const handleAllScheduledClick = useCallback(() => {\n openChat({ id: chatId, threadId, type: 'scheduled' });\n }, [openChat, chatId, threadId]);\n\n useEffect(() => {\n if (isRightColumnShown && IS_SINGLE_COLUMN_LAYOUT) {\n closeSymbolMenu();\n }\n }, [isRightColumnShown, closeSymbolMenu]);\n\n useEffect(() => {\n if (!isReady) return;\n\n if (isSelectModeActive) {\n disableHover();\n } else {\n setTimeout(() => {\n enableHover();\n }, SELECT_MODE_TRANSITION_MS);\n }\n }, [isSelectModeActive, enableHover, disableHover, isReady]);\n\n const mainButtonHandler = useCallback(() => {\n switch (mainButtonState) {\n case MainButtonState.Send:\n if (shouldSchedule) {\n if (activeVoiceRecording) {\n pauseRecordingVoice();\n }\n openCalendar();\n } else {\n void handleSend();\n }\n break;\n case MainButtonState.Record:\n void startRecordingVoice();\n break;\n case MainButtonState.Edit:\n handleEditComplete();\n break;\n default:\n break;\n }\n }, [\n mainButtonState, shouldSchedule, startRecordingVoice, handleEditComplete,\n activeVoiceRecording, openCalendar, pauseRecordingVoice, handleSend,\n ]);\n\n const areVoiceMessagesNotAllowed = mainButtonState === MainButtonState.Record\n && !allowedAttachmentOptions.canAttachMedia;\n\n const prevEditedMessage = usePrevious(editingMessage, true);\n const renderedEditedMessage = editingMessage || prevEditedMessage;\n\n const scheduledDefaultDate = new Date();\n scheduledDefaultDate.setSeconds(0);\n scheduledDefaultDate.setMilliseconds(0);\n\n const scheduledMaxDate = new Date();\n scheduledMaxDate.setFullYear(scheduledMaxDate.getFullYear() + 1);\n\n let sendButtonAriaLabel = 'SendMessage';\n switch (mainButtonState) {\n case MainButtonState.Edit:\n sendButtonAriaLabel = 'Save edited message';\n break;\n case MainButtonState.Record:\n sendButtonAriaLabel = areVoiceMessagesNotAllowed\n ? 'Conversation.DefaultRestrictedMedia'\n : 'AccDescrVoiceMessage';\n }\n\n const className = buildClassName(\n 'Composer',\n !isSelectModeActive && 'shown',\n isHoverDisabled && 'hover-disabled',\n );\n\n const symbolMenuButtonClassName = buildClassName(\n 'mobile-symbol-menu-button',\n !isReady && 'not-ready',\n isSymbolMenuLoaded\n ? (isSymbolMenuOpen && 'menu-opened')\n : (isSymbolMenuOpen && 'is-loading'),\n );\n\n const onSend = mainButtonState === MainButtonState.Edit\n ? handleEditComplete\n : (shouldSchedule ? openCalendar : handleSend);\n\n return (\n
\n {allowedAttachmentOptions.canAttachMedia && isReady && (\n \n \n \n )}\n \n \n {renderedEditedMessage && (\n \n )}\n \n \n \n \n
\n
\n \n \n
\n {isChatWithBot && botCommands !== false && !activeVoiceRecording && !editingMessage && (\n \n \n \n )}\n {!!sendAsIds?.length && (sendAsUser || sendAsChat) && (\n \n \n \n )}\n {IS_SINGLE_COLUMN_LAYOUT ? (\n \n \n \n {isSymbolMenuOpen && !isSymbolMenuLoaded && }\n \n ) : (\n \n \n \n )}\n \n {isInlineBotLoading && Boolean(inlineBotId) && (\n \n )}\n {withScheduledButton && (\n \n \n \n )}\n {botKeyboardMessageId && !activeVoiceRecording && !editingMessage && (\n \n \n \n )}\n {!activeVoiceRecording && !editingMessage && (\n \n \n \n )}\n {activeVoiceRecording && currentRecordTime && (\n \n {formatVoiceRecordDuration(currentRecordTime - startRecordTimeRef.current!)}\n \n )}\n \n \n \n {botKeyboardMessageId && (\n \n )}\n {botCommands && (\n \n )}\n \n
\n
\n {activeVoiceRecording && (\n \n \n \n )}\n \n \n \n \n \n {canShowCustomSendMenu && (\n \n )}\n \n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { chatId, threadId, messageListType }): StateProps => {\n const chat = selectChat(global, chatId);\n const chatUser = chat && selectChatUser(global, chat);\n const chatBot = chatId !== REPLIES_USER_ID ? selectChatBot(global, chatId) : undefined;\n const isChatWithBot = Boolean(chatBot);\n const isChatWithSelf = selectIsChatWithSelf(global, chatId);\n const messageWithActualBotKeyboard = isChatWithBot && selectNewestMessageWithBotKeyboardButtons(global, chatId);\n const scheduledIds = selectScheduledIds(global, chatId);\n const { language, shouldSuggestStickers } = global.settings.byKey;\n const baseEmojiKeywords = global.emojiKeywords[BASE_EMOJI_KEYWORD_LANG];\n const emojiKeywords = language !== BASE_EMOJI_KEYWORD_LANG ? global.emojiKeywords[language] : undefined;\n const botKeyboardMessageId = messageWithActualBotKeyboard ? messageWithActualBotKeyboard.id : undefined;\n const keyboardMessage = botKeyboardMessageId ? selectChatMessage(global, chatId, botKeyboardMessageId) : undefined;\n const usersById = global.users.byId;\n const chatsById = global.chats.byId;\n const { currentUserId } = global;\n const sendAsId = chat?.fullInfo ? chat?.fullInfo?.sendAsId || currentUserId : undefined;\n const sendAsUser = sendAsId ? usersById?.[sendAsId] : undefined;\n const sendAsChat = !sendAsUser && sendAsId ? chatsById?.[sendAsId] : undefined;\n\n return {\n editingMessage: selectEditingMessage(global, chatId, threadId, messageListType),\n connectionState: global.connectionState,\n draft: selectDraft(global, chatId, threadId),\n chat,\n isChatWithBot,\n isChatWithSelf,\n canScheduleUntilOnline: Boolean(\n !isChatWithSelf && !isChatWithBot && chat && chatUser\n && isUserId(chatId) && selectUserStatus(global, chatId)?.wasOnline,\n ),\n isRightColumnShown: selectIsRightColumnShown(global),\n isSelectModeActive: selectIsInSelectMode(global),\n withScheduledButton: (\n threadId === MAIN_THREAD_ID\n && messageListType === 'thread'\n && Boolean(scheduledIds?.length)\n ),\n shouldSchedule: messageListType === 'scheduled',\n botKeyboardMessageId,\n botKeyboardPlaceholder: keyboardMessage?.keyboardPlaceholder,\n isForwarding: chatId === global.forwardMessages.toChatId,\n isPollModalOpen: global.isPollModalOpen,\n stickersForEmoji: global.stickers.forEmoji.stickers,\n groupChatMembers: chat?.fullInfo?.members,\n topInlineBotIds: global.topInlineBots?.userIds,\n currentUserId,\n usersById,\n lastSyncTime: global.lastSyncTime,\n contentToBeScheduled: global.messages.contentToBeScheduled,\n shouldSuggestStickers,\n recentEmojis: global.recentEmojis,\n baseEmojiKeywords: baseEmojiKeywords?.keywords,\n emojiKeywords: emojiKeywords?.keywords,\n serverTimeOffset: global.serverTimeOffset,\n inlineBots: global.inlineBots.byUsername,\n isInlineBotLoading: global.inlineBots.isLoading,\n chatBotCommands: chat && chat.fullInfo && chat.fullInfo.botCommands,\n botCommands: chatBot && chatBot.fullInfo ? (chatBot.fullInfo.botCommands || false) : undefined,\n sendAsUser,\n sendAsChat,\n sendAsId,\n };\n },\n)(Composer));\n","import { useEffect, useMemo } from '../../../../lib/teact/teact';\nimport { getDispatch } from '../../../../lib/teact/teactn';\n\nimport { ApiSticker } from '../../../../api/types';\n\nimport { IS_EMOJI_SUPPORTED } from '../../../../util/environment';\n\nimport parseEmojiOnlyString from '../../../common/helpers/parseEmojiOnlyString';\nimport { prepareForRegExp } from '../helpers/prepareForRegExp';\n\nexport default function useStickerTooltip(\n isAllowed: boolean,\n html: string,\n stickers?: ApiSticker[],\n isDisabled = false,\n) {\n const cleanHtml = useMemo(() => prepareForRegExp(html).trim(), [html]);\n const { loadStickersForEmoji, clearStickersForEmoji } = getDispatch();\n const isSingleEmoji = (\n (IS_EMOJI_SUPPORTED && parseEmojiOnlyString(cleanHtml) === 1)\n || (!IS_EMOJI_SUPPORTED && Boolean(html.match(/^]*?>$/g)))\n );\n const hasStickers = Boolean(stickers) && isSingleEmoji;\n\n useEffect(() => {\n if (isDisabled) return;\n\n if (isAllowed && isSingleEmoji) {\n loadStickersForEmoji({\n emoji: IS_EMOJI_SUPPORTED ? cleanHtml : cleanHtml.match(/alt=\"(.+)\"/)?.[1],\n });\n } else if (hasStickers || !isSingleEmoji) {\n clearStickersForEmoji();\n }\n // We omit `hasStickers` here to prevent re-fetching after manually closing tooltip (via ).\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [html, isSingleEmoji, clearStickersForEmoji, loadStickersForEmoji, isAllowed, isDisabled]);\n\n return {\n isStickerTooltipOpen: hasStickers,\n closeStickerTooltip: clearStickersForEmoji,\n };\n}\n","export default function insertHtmlInSelection(html: string) {\n const selection = window.getSelection();\n\n if (selection?.getRangeAt && selection.rangeCount) {\n const range = selection.getRangeAt(0);\n range.deleteContents();\n\n const fragment = range.createContextualFragment(html);\n const lastInsertedNode = fragment.lastChild;\n range.insertNode(fragment);\n if (lastInsertedNode) {\n range.setStartAfter(lastInsertedNode);\n range.setEndAfter(lastInsertedNode);\n } else {\n range.collapse(false);\n }\n selection.removeAllRanges();\n selection.addRange(range);\n }\n}\n","export default function deleteLastCharacterOutsideSelection(html: string) {\n const tempInput = document.createElement('div');\n tempInput.contentEditable = 'true';\n tempInput.style.position = 'absolute';\n tempInput.style.left = '-10000px';\n tempInput.style.top = '-10000px';\n tempInput.innerHTML = html;\n document.body.appendChild(tempInput);\n let element = tempInput.lastChild!;\n\n if (element.lastChild) {\n // Selects the last and the deepest child of the element.\n while (element.lastChild) {\n element = element.lastChild;\n }\n }\n\n // Gets length of the element's content.\n const textLength = element.textContent!.length;\n const range = document.createRange();\n const selection = window.getSelection()!;\n\n // Sets selection position to the end of the element.\n range.setStart(element, textLength);\n range.setEnd(element, textLength);\n selection.removeAllRanges();\n selection.addRange(range);\n document.execCommand('delete', false);\n\n const result = tempInput.innerHTML;\n document.body.removeChild(tempInput);\n\n return result;\n}\n","import { useCallback, useEffect } from '../../../../lib/teact/teact';\nimport { getDispatch } from '../../../../lib/teact/teactn';\n\nimport { ApiMessage } from '../../../../api/types';\n\nimport { EDITABLE_INPUT_ID } from '../../../../config';\nimport parseMessageInput from '../../../../util/parseMessageInput';\nimport getMessageTextAsHtml from '../helpers/getMessageTextAsHtml';\nimport focusEditableElement from '../../../../util/focusEditableElement';\nimport { hasMessageMedia } from '../../../../modules/helpers';\n\nexport default (\n htmlRef: { current: string },\n setHtml: (html: string) => void,\n editedMessage: ApiMessage | undefined,\n resetComposer: () => void,\n openDeleteModal: () => void,\n) => {\n const { editMessage } = getDispatch();\n\n // TODO useOnChange\n // Handle editing message\n useEffect(() => {\n if (!editedMessage) {\n setHtml('');\n return;\n }\n\n setHtml(getMessageTextAsHtml(editedMessage.content.text));\n\n requestAnimationFrame(() => {\n const messageInput = document.getElementById(EDITABLE_INPUT_ID)!;\n focusEditableElement(messageInput, true);\n });\n }, [editedMessage, setHtml]);\n\n const handleEditComplete = useCallback(() => {\n const { text, entities } = parseMessageInput(htmlRef.current!);\n\n if (!editedMessage) {\n return;\n }\n\n if (!text && !hasMessageMedia(editedMessage)) {\n openDeleteModal();\n return;\n }\n\n editMessage({\n messageId: editedMessage.id,\n text,\n entities,\n });\n\n resetComposer();\n }, [editMessage, editedMessage, htmlRef, openDeleteModal, resetComposer]);\n\n return handleEditComplete;\n};\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './MobileSearch';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst MobileSearchAsync: FC = (props) => {\n const { isActive } = props;\n const MobileSearch = useModuleLoader(Bundles.Extra, 'MobileSearch', !isActive, true);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return MobileSearch ? : undefined;\n};\n\nexport default memo(MobileSearchAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\nimport { OwnProps } from './MessageSelectToolbar';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst MessageSelectToolbarAsync: FC = (props) => {\n const { isActive } = props;\n const MessageSelectToolbar = useModuleLoader(Bundles.Extra, 'MessageSelectToolbar', !isActive);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return MessageSelectToolbar ? : undefined;\n};\n\nexport default memo(MessageSelectToolbarAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './UnpinAllMessagesModal';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst UnpinAllMessagesModalAsync: FC = (props) => {\n const { isOpen } = props;\n const UnpinAllMessagesModal = useModuleLoader(Bundles.Extra, 'UnpinAllMessagesModal', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return UnpinAllMessagesModal ? : undefined;\n};\n\nexport default memo(UnpinAllMessagesModalAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './PaymentModal';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst PaymentModalAsync: FC = (props) => {\n const { isOpen } = props;\n const PaymentModal = useModuleLoader(Bundles.Extra, 'PaymentModal', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return PaymentModal ? : undefined;\n};\n\nexport default memo(PaymentModalAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './ReceiptModal';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst ReceiptModalAsync: FC = (props) => {\n const { isOpen } = props;\n const ReceiptModal = useModuleLoader(Bundles.Extra, 'ReceiptModal', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return ReceiptModal ? : undefined;\n};\n\nexport default memo(ReceiptModalAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './SeenByModal';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst SeenByModalAsync: FC = (props) => {\n const { isOpen } = props;\n const SeenByModal = useModuleLoader(Bundles.Extra, 'SeenByModal', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return SeenByModal ? : undefined;\n};\n\nexport default memo(SeenByModalAsync);\n","import React, {\n FC, useEffect, useState, memo, useMemo, useCallback,\n} from '../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiChatBannedRights, MAIN_THREAD_ID } from '../../api/types';\nimport { MessageListType, MessageList as GlobalMessageList } from '../../global/types';\nimport { ThemeKey } from '../../types';\n\nimport {\n MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN,\n MOBILE_SCREEN_MAX_WIDTH,\n MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN,\n SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN,\n SAFE_SCREEN_WIDTH_FOR_CHAT_INFO,\n ANIMATION_LEVEL_MAX,\n ANIMATION_END_DELAY,\n DARK_THEME_BG_COLOR,\n LIGHT_THEME_BG_COLOR,\n ANIMATION_LEVEL_MIN,\n SUPPORTED_IMAGE_CONTENT_TYPES,\n} from '../../config';\nimport {\n IS_SINGLE_COLUMN_LAYOUT,\n IS_TABLET_COLUMN_LAYOUT,\n IS_TOUCH_ENV,\n MASK_IMAGE_DISABLED,\n} from '../../util/environment';\nimport { DropAreaState } from './composer/DropArea';\nimport {\n selectChat,\n selectChatBot,\n selectCurrentMessageList,\n selectCurrentTextSearch,\n selectIsChatBotNotStarted,\n selectIsInSelectMode,\n selectIsRightColumnShown,\n selectIsUserBlocked,\n selectPinnedIds,\n selectTheme,\n} from '../../modules/selectors';\nimport {\n getCanPostInChat, getMessageSendingRestrictionReason, isChatChannel, isChatSuperGroup, isUserId,\n} from '../../modules/helpers';\nimport captureEscKeyListener from '../../util/captureEscKeyListener';\nimport buildClassName from '../../util/buildClassName';\nimport { createMessageHash } from '../../util/routing';\nimport useCustomBackground from '../../hooks/useCustomBackground';\nimport useWindowSize from '../../hooks/useWindowSize';\nimport usePrevDuringAnimation from '../../hooks/usePrevDuringAnimation';\nimport useLang from '../../hooks/useLang';\nimport useHistoryBack from '../../hooks/useHistoryBack';\nimport usePrevious from '../../hooks/usePrevious';\nimport useForceUpdate from '../../hooks/useForceUpdate';\nimport useOnChange from '../../hooks/useOnChange';\nimport calculateMiddleFooterTransforms from './helpers/calculateMiddleFooterTransforms';\n\nimport Transition from '../ui/Transition';\nimport MiddleHeader from './MiddleHeader';\nimport MessageList from './MessageList';\nimport ScrollDownButton from './ScrollDownButton';\nimport Composer from './composer/Composer';\nimport Button from '../ui/Button';\nimport MobileSearch from './MobileSearch.async';\nimport MessageSelectToolbar from './MessageSelectToolbar.async';\nimport UnpinAllMessagesModal from '../common/UnpinAllMessagesModal.async';\nimport PaymentModal from '../payment/PaymentModal.async';\nimport ReceiptModal from '../payment/ReceiptModal.async';\nimport SeenByModal from '../common/SeenByModal.async';\n\nimport './MiddleColumn.scss';\n\ntype StateProps = {\n chatId?: string;\n threadId?: number;\n messageListType?: MessageListType;\n isPrivate?: boolean;\n isPinnedMessageList?: boolean;\n isScheduledMessageList?: boolean;\n canPost?: boolean;\n currentUserBannedRights?: ApiChatBannedRights;\n defaultBannedRights?: ApiChatBannedRights;\n hasPinnedOrAudioPlayer?: boolean;\n pinnedMessagesCount?: number;\n theme: ThemeKey;\n customBackground?: string;\n backgroundColor?: string;\n patternColor?: string;\n isLeftColumnShown?: boolean;\n isRightColumnShown?: boolean;\n isBackgroundBlurred?: boolean;\n isMobileSearchActive?: boolean;\n isSelectModeActive?: boolean;\n isPaymentModalOpen?: boolean;\n isReceiptModalOpen?: boolean;\n isSeenByModalOpen: boolean;\n animationLevel?: number;\n shouldSkipHistoryAnimations?: boolean;\n currentTransitionKey: number;\n messageLists?: GlobalMessageList[];\n isChannel?: boolean;\n canSubscribe?: boolean;\n canStartBot?: boolean;\n canRestartBot?: boolean;\n};\n\nconst CLOSE_ANIMATION_DURATION = IS_SINGLE_COLUMN_LAYOUT ? 450 + ANIMATION_END_DELAY : undefined;\n\nfunction isImage(item: DataTransferItem) {\n return item.kind === 'file' && item.type && SUPPORTED_IMAGE_CONTENT_TYPES.has(item.type);\n}\n\nconst MiddleColumn: FC = ({\n chatId,\n threadId,\n messageListType,\n isPrivate,\n isPinnedMessageList,\n messageLists,\n canPost,\n currentUserBannedRights,\n defaultBannedRights,\n hasPinnedOrAudioPlayer,\n pinnedMessagesCount,\n customBackground,\n theme,\n backgroundColor,\n patternColor,\n isLeftColumnShown,\n isRightColumnShown,\n isBackgroundBlurred,\n isMobileSearchActive,\n isSelectModeActive,\n isPaymentModalOpen,\n isReceiptModalOpen,\n isSeenByModalOpen,\n animationLevel,\n shouldSkipHistoryAnimations,\n currentTransitionKey,\n isChannel,\n canSubscribe,\n canStartBot,\n canRestartBot,\n}) => {\n const {\n openChat,\n unpinAllMessages,\n loadUser,\n closeLocalTextSearch,\n exitMessageSelectMode,\n closePaymentModal,\n clearReceipt,\n joinChannel,\n sendBotCommand,\n restartBot,\n } = getDispatch();\n\n const { width: windowWidth } = useWindowSize();\n\n const lang = useLang();\n const [dropAreaState, setDropAreaState] = useState(DropAreaState.None);\n const [isFabShown, setIsFabShown] = useState();\n const [isNotchShown, setIsNotchShown] = useState();\n const [isUnpinModalOpen, setIsUnpinModalOpen] = useState(false);\n\n const hasTools = hasPinnedOrAudioPlayer && (\n windowWidth < MOBILE_SCREEN_MAX_WIDTH\n || (\n isRightColumnShown && windowWidth > MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN\n && windowWidth < SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN\n ) || (\n windowWidth >= MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN\n && windowWidth < SAFE_SCREEN_WIDTH_FOR_CHAT_INFO\n )\n );\n\n const renderingChatId = usePrevDuringAnimation(chatId, CLOSE_ANIMATION_DURATION);\n const renderingThreadId = usePrevDuringAnimation(threadId, CLOSE_ANIMATION_DURATION);\n const renderingMessageListType = usePrevDuringAnimation(messageListType, CLOSE_ANIMATION_DURATION);\n const renderingCanSubscribe = usePrevDuringAnimation(canSubscribe, CLOSE_ANIMATION_DURATION);\n const renderingCanStartBot = usePrevDuringAnimation(canStartBot, CLOSE_ANIMATION_DURATION);\n const renderingCanRestartBot = usePrevDuringAnimation(canRestartBot, CLOSE_ANIMATION_DURATION);\n const renderingCanPost = usePrevDuringAnimation(canPost, CLOSE_ANIMATION_DURATION)\n && !renderingCanRestartBot && !renderingCanStartBot && !renderingCanSubscribe;\n const renderingHasTools = usePrevDuringAnimation(hasTools, CLOSE_ANIMATION_DURATION);\n const renderingIsFabShown = usePrevDuringAnimation(isFabShown, CLOSE_ANIMATION_DURATION);\n const renderingIsChannel = usePrevDuringAnimation(isChannel, CLOSE_ANIMATION_DURATION);\n\n const prevTransitionKey = usePrevious(currentTransitionKey);\n\n const cleanupExceptionKey = (\n prevTransitionKey !== undefined && prevTransitionKey < currentTransitionKey ? prevTransitionKey : undefined\n );\n\n const { isReady, handleOpenEnd, handleSlideStop } = useIsReady(\n animationLevel, currentTransitionKey, prevTransitionKey, chatId,\n );\n\n useEffect(() => {\n return chatId\n ? captureEscKeyListener(() => {\n openChat({ id: undefined });\n })\n : undefined;\n }, [chatId, openChat]);\n\n useOnChange(() => {\n setDropAreaState(DropAreaState.None);\n setIsFabShown(undefined);\n setIsNotchShown(undefined);\n }, [chatId]);\n\n // Fix for mobile virtual keyboard\n useEffect(() => {\n const { visualViewport } = window as any;\n if (!visualViewport) {\n return undefined;\n }\n\n const handleResize = () => {\n if (window.visualViewport.height !== document.documentElement.clientHeight) {\n document.body.classList.add('keyboard-visible');\n } else {\n document.body.classList.remove('keyboard-visible');\n }\n };\n\n visualViewport.addEventListener('resize', handleResize);\n\n return () => {\n visualViewport.removeEventListener('resize', handleResize);\n };\n }, []);\n\n useEffect(() => {\n if (isPrivate) {\n loadUser({ userId: chatId });\n }\n }, [chatId, isPrivate, loadUser]);\n\n const handleDragEnter = useCallback((e: React.DragEvent) => {\n if (IS_TOUCH_ENV) {\n return;\n }\n\n const { items } = e.dataTransfer || {};\n const shouldDrawQuick = items && Array.from(items)\n // Filter unnecessary element for drag and drop images in Firefox (https://github.com/Ajaxy/telegram-tt/issues/49)\n // https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API/Recommended_drag_types#image\n .filter((item) => item.type !== 'text/uri-list')\n // As of September 2021, native clients suggest \"send quick, but compressed\" only for images\n .every(isImage);\n\n setDropAreaState(shouldDrawQuick ? DropAreaState.QuickFile : DropAreaState.Document);\n }, []);\n\n const handleHideDropArea = useCallback(() => {\n setDropAreaState(DropAreaState.None);\n }, []);\n\n const handleOpenUnpinModal = useCallback(() => {\n setIsUnpinModalOpen(true);\n }, []);\n\n const closeUnpinModal = useCallback(() => {\n setIsUnpinModalOpen(false);\n }, []);\n\n const handleUnpinAllMessages = useCallback(() => {\n unpinAllMessages({ chatId });\n closeUnpinModal();\n openChat({ id: chatId });\n }, [unpinAllMessages, openChat, closeUnpinModal, chatId]);\n\n const handleTabletFocus = useCallback(() => {\n openChat({ id: chatId });\n }, [openChat, chatId]);\n\n const handleSubscribeClick = useCallback(() => {\n joinChannel({ chatId });\n }, [joinChannel, chatId]);\n\n const handleStartBot = useCallback(() => {\n sendBotCommand({ command: '/start' });\n }, [sendBotCommand]);\n\n const handleRestartBot = useCallback(() => {\n restartBot({ chatId });\n }, [chatId, restartBot]);\n\n const customBackgroundValue = useCustomBackground(theme, customBackground);\n\n const className = buildClassName(\n renderingHasTools && 'has-header-tools',\n customBackground && 'custom-bg-image',\n backgroundColor && 'custom-bg-color',\n customBackground && isBackgroundBlurred && 'blurred',\n MASK_IMAGE_DISABLED ? 'mask-image-disabled' : 'mask-image-enabled',\n );\n\n const messagingDisabledClassName = buildClassName(\n 'messaging-disabled',\n !isSelectModeActive && 'shown',\n );\n\n const messageSendingRestrictionReason = getMessageSendingRestrictionReason(\n lang, currentUserBannedRights, defaultBannedRights,\n );\n\n // CSS Variables calculation doesn't work properly with transforms, so we calculate transform values in JS\n const {\n composerHiddenScale, toolbarHiddenScale,\n composerTranslateX, toolbarTranslateX,\n unpinHiddenScale, toolbarForUnpinHiddenScale,\n } = useMemo(\n () => calculateMiddleFooterTransforms(windowWidth, renderingCanPost),\n [renderingCanPost, windowWidth],\n );\n\n const footerClassName = buildClassName(\n 'middle-column-footer',\n !renderingCanPost && 'no-composer',\n renderingCanPost && isNotchShown && !isSelectModeActive && 'with-notch',\n );\n\n const closeChat = () => {\n openChat({ id: undefined }, { forceSyncOnIOs: true });\n };\n\n useHistoryBack(\n renderingChatId && renderingThreadId,\n closeChat, undefined, undefined, undefined,\n messageLists?.map(createMessageHash) || [],\n );\n\n useHistoryBack(isMobileSearchActive, closeLocalTextSearch);\n useHistoryBack(isSelectModeActive, exitMessageSelectMode);\n\n const isMessagingDisabled = Boolean(!isPinnedMessageList && !renderingCanPost && messageSendingRestrictionReason);\n const withMessageListBottomShift = Boolean(\n renderingCanRestartBot || renderingCanSubscribe || renderingCanStartBot || isPinnedMessageList,\n );\n const withExtraShift = Boolean(isMessagingDisabled || isSelectModeActive || isPinnedMessageList);\n\n return (\n \n \n
\n {renderingChatId && renderingThreadId && (\n <>\n
\n \n \n {() => (\n <>\n \n
\n {renderingCanPost && (\n \n )}\n {isPinnedMessageList && (\n
\n \n \n {lang('Chat.Pinned.UnpinAll', pinnedMessagesCount, 'i')}\n \n
\n )}\n {isMessagingDisabled && (\n
\n
\n \n {messageSendingRestrictionReason}\n \n
\n
\n )}\n {IS_SINGLE_COLUMN_LAYOUT && renderingCanSubscribe && (\n
\n \n {lang(renderingIsChannel ? 'ProfileJoinChannel' : 'ProfileJoinGroup')}\n \n
\n )}\n {IS_SINGLE_COLUMN_LAYOUT && renderingCanStartBot && (\n
\n \n {lang('BotStart')}\n \n
\n )}\n {IS_SINGLE_COLUMN_LAYOUT && renderingCanRestartBot && (\n
\n \n {lang('BotRestart')}\n \n
\n )}\n \n \n \n \n
\n \n )}\n \n\n \n
\n {IS_SINGLE_COLUMN_LAYOUT && }\n \n )}\n {chatId && (\n \n )}\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const theme = selectTheme(global);\n const {\n isBlurred: isBackgroundBlurred, background: customBackground, backgroundColor, patternColor,\n } = global.settings.themes[theme] || {};\n\n const { messageLists } = global.messages;\n const currentMessageList = selectCurrentMessageList(global);\n const { isLeftColumnShown, chats: { listIds } } = global;\n\n const state: StateProps = {\n theme,\n customBackground,\n backgroundColor,\n patternColor,\n isLeftColumnShown,\n isRightColumnShown: selectIsRightColumnShown(global),\n isBackgroundBlurred,\n isMobileSearchActive: Boolean(IS_SINGLE_COLUMN_LAYOUT && selectCurrentTextSearch(global)),\n isSelectModeActive: selectIsInSelectMode(global),\n isPaymentModalOpen: global.payment.isPaymentModalOpen,\n isReceiptModalOpen: Boolean(global.payment.receipt),\n isSeenByModalOpen: Boolean(global.seenByModal),\n animationLevel: global.settings.byKey.animationLevel,\n currentTransitionKey: Math.max(0, global.messages.messageLists.length - 1),\n };\n\n if (!currentMessageList || !listIds.active) {\n return state;\n }\n\n const { chatId, threadId, type: messageListType } = currentMessageList;\n const chat = selectChat(global, chatId);\n const bot = selectChatBot(global, chatId);\n const pinnedIds = selectPinnedIds(global, chatId);\n const { chatId: audioChatId, messageId: audioMessageId } = global.audioPlayer;\n\n const canPost = chat && getCanPostInChat(chat, threadId);\n const isBotNotStarted = selectIsChatBotNotStarted(global, chatId);\n const isPinnedMessageList = messageListType === 'pinned';\n const isScheduledMessageList = messageListType === 'scheduled';\n const isMainThread = messageListType === 'thread' && threadId === MAIN_THREAD_ID;\n const isChannel = Boolean(chat && isChatChannel(chat));\n const canSubscribe = Boolean(\n chat && isMainThread && (isChannel || isChatSuperGroup(chat)) && chat.isNotJoined,\n );\n const canRestartBot = Boolean(bot && selectIsUserBlocked(global, bot.id));\n const canStartBot = !canRestartBot && isBotNotStarted;\n\n return {\n ...state,\n chatId,\n threadId,\n messageListType,\n isPrivate: isUserId(chatId),\n canPost: !isPinnedMessageList && (!chat || canPost) && !isBotNotStarted,\n isPinnedMessageList,\n isScheduledMessageList,\n currentUserBannedRights: chat?.currentUserBannedRights,\n defaultBannedRights: chat?.defaultBannedRights,\n hasPinnedOrAudioPlayer: (\n threadId !== MAIN_THREAD_ID\n || Boolean(!isPinnedMessageList && pinnedIds?.length)\n || Boolean(audioChatId && audioMessageId)\n ),\n pinnedMessagesCount: pinnedIds ? pinnedIds.length : 0,\n shouldSkipHistoryAnimations: global.shouldSkipHistoryAnimations,\n messageLists,\n isChannel,\n canSubscribe,\n canStartBot,\n canRestartBot,\n };\n },\n)(MiddleColumn));\n\nfunction useIsReady(\n animationLevel?: number,\n currentTransitionKey?: number,\n prevTransitionKey?: number,\n chatId?: string,\n) {\n const [isReady, setIsReady] = useState(!IS_SINGLE_COLUMN_LAYOUT);\n const forceUpdate = useForceUpdate();\n\n const willSwitchMessageList = prevTransitionKey !== undefined && prevTransitionKey !== currentTransitionKey;\n if (willSwitchMessageList) {\n if (animationLevel !== ANIMATION_LEVEL_MIN) {\n setIsReady(false);\n } else {\n forceUpdate();\n }\n }\n\n useOnChange(() => {\n if (animationLevel === ANIMATION_LEVEL_MIN) {\n setIsReady(true);\n }\n }, [animationLevel]);\n\n function handleOpenEnd(e: React.TransitionEvent) {\n if (e.propertyName === 'transform' && e.target === e.currentTarget) {\n setIsReady(Boolean(chatId));\n }\n }\n\n function handleSlideStop() {\n setIsReady(true);\n }\n\n return {\n isReady: isReady && !willSwitchMessageList,\n handleOpenEnd: animationLevel !== ANIMATION_LEVEL_MIN ? handleOpenEnd : undefined,\n handleSlideStop: animationLevel !== ANIMATION_LEVEL_MIN ? handleSlideStop : undefined,\n };\n}\n","import React, {\n FC, memo, useCallback, useEffect, useRef, useState,\n} from '../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../lib/teact/teactn';\n\nimport { ManagementScreens, ProfileState } from '../../types';\n\nimport { IS_SINGLE_COLUMN_LAYOUT } from '../../util/environment';\nimport { debounce } from '../../util/schedulers';\nimport buildClassName from '../../util/buildClassName';\nimport {\n selectChat,\n selectCurrentGifSearch,\n selectCurrentStickerSearch,\n selectCurrentTextSearch,\n selectIsChatWithSelf,\n selectUser,\n} from '../../modules/selectors';\nimport {\n getCanAddContact,\n isChatAdmin,\n isChatChannel,\n isUserId,\n} from '../../modules/helpers';\nimport useCurrentOrPrev from '../../hooks/useCurrentOrPrev';\nimport useLang from '../../hooks/useLang';\n\nimport SearchInput from '../ui/SearchInput';\nimport Button from '../ui/Button';\nimport Transition from '../ui/Transition';\nimport './RightHeader.scss';\nimport { getDayStartAt } from '../../util/dateFormat';\n\ntype OwnProps = {\n chatId?: string;\n isColumnOpen?: boolean;\n isProfile?: boolean;\n isSearch?: boolean;\n isManagement?: boolean;\n isStickerSearch?: boolean;\n isGifSearch?: boolean;\n isPollResults?: boolean;\n isAddingChatMembers?: boolean;\n shouldSkipAnimation?: boolean;\n profileState?: ProfileState;\n managementScreen?: ManagementScreens;\n onClose: () => void;\n};\n\ntype StateProps = {\n canAddContact?: boolean;\n canManage?: boolean;\n isChannel?: boolean;\n userId?: string;\n messageSearchQuery?: string;\n stickerSearchQuery?: string;\n gifSearchQuery?: string;\n};\n\nconst COLUMN_CLOSE_DELAY_MS = 300;\nconst runDebouncedForSearch = debounce((cb) => cb(), 200, false);\n\nenum HeaderContent {\n Profile,\n MemberList,\n SharedMedia,\n Search,\n Management,\n ManageInitial,\n ManageChannelSubscribers,\n ManageChatAdministrators,\n ManageChatPrivacyType,\n ManageDiscussion,\n ManageGroupPermissions,\n ManageGroupRemovedUsers,\n ManageGroupUserPermissionsCreate,\n ManageGroupUserPermissions,\n ManageGroupRecentActions,\n ManageGroupAdminRights,\n ManageGroupNewAdminRights,\n ManageGroupMembers,\n ManageGroupAddAdmins,\n StickerSearch,\n GifSearch,\n PollResults,\n AddingMembers,\n}\n\nconst RightHeader: FC = ({\n isColumnOpen,\n isProfile,\n isSearch,\n isManagement,\n isStickerSearch,\n isGifSearch,\n isPollResults,\n isAddingChatMembers,\n profileState,\n managementScreen,\n canAddContact,\n userId,\n canManage,\n isChannel,\n onClose,\n messageSearchQuery,\n stickerSearchQuery,\n gifSearchQuery,\n shouldSkipAnimation,\n}) => {\n const {\n setLocalTextSearchQuery,\n setStickerSearchQuery,\n setGifSearchQuery,\n searchTextMessagesLocal,\n toggleManagement,\n openHistoryCalendar, addContact,\n } = getDispatch();\n\n // eslint-disable-next-line no-null/no-null\n const backButtonRef = useRef(null);\n\n const handleMessageSearchQueryChange = useCallback((query: string) => {\n setLocalTextSearchQuery({ query });\n\n if (query.length) {\n runDebouncedForSearch(searchTextMessagesLocal);\n }\n }, [searchTextMessagesLocal, setLocalTextSearchQuery]);\n\n const handleStickerSearchQueryChange = useCallback((query: string) => {\n setStickerSearchQuery({ query });\n }, [setStickerSearchQuery]);\n\n const handleGifSearchQueryChange = useCallback((query: string) => {\n setGifSearchQuery({ query });\n }, [setGifSearchQuery]);\n\n const handleAddContact = useCallback(() => {\n addContact({ userId });\n }, [addContact, userId]);\n\n const [shouldSkipTransition, setShouldSkipTransition] = useState(!isColumnOpen);\n\n useEffect(() => {\n setTimeout(() => {\n setShouldSkipTransition(!isColumnOpen);\n }, COLUMN_CLOSE_DELAY_MS);\n }, [isColumnOpen]);\n\n const lang = useLang();\n const contentKey = isProfile ? (\n profileState === ProfileState.Profile ? (\n HeaderContent.Profile\n ) : profileState === ProfileState.SharedMedia ? (\n HeaderContent.SharedMedia\n ) : profileState === ProfileState.MemberList ? (\n HeaderContent.MemberList\n ) : -1 // Never reached\n ) : isSearch ? (\n HeaderContent.Search\n ) : isPollResults ? (\n HeaderContent.PollResults\n ) : isStickerSearch ? (\n HeaderContent.StickerSearch\n ) : isGifSearch ? (\n HeaderContent.GifSearch\n ) : isAddingChatMembers ? (\n HeaderContent.AddingMembers\n ) : isManagement ? (\n managementScreen === ManagementScreens.Initial ? (\n HeaderContent.ManageInitial\n ) : managementScreen === ManagementScreens.ChatPrivacyType ? (\n HeaderContent.ManageChatPrivacyType\n ) : managementScreen === ManagementScreens.Discussion ? (\n HeaderContent.ManageDiscussion\n ) : managementScreen === ManagementScreens.ChannelSubscribers ? (\n HeaderContent.ManageChannelSubscribers\n ) : managementScreen === ManagementScreens.GroupPermissions ? (\n HeaderContent.ManageGroupPermissions\n ) : managementScreen === ManagementScreens.ChatAdministrators ? (\n HeaderContent.ManageChatAdministrators\n ) : managementScreen === ManagementScreens.GroupRemovedUsers ? (\n HeaderContent.ManageGroupRemovedUsers\n ) : managementScreen === ManagementScreens.GroupUserPermissionsCreate ? (\n HeaderContent.ManageGroupUserPermissionsCreate\n ) : managementScreen === ManagementScreens.GroupUserPermissions ? (\n HeaderContent.ManageGroupUserPermissions\n ) : managementScreen === ManagementScreens.GroupRecentActions ? (\n HeaderContent.ManageGroupRecentActions\n ) : managementScreen === ManagementScreens.ChatAdminRights ? (\n HeaderContent.ManageGroupAdminRights\n ) : managementScreen === ManagementScreens.ChatNewAdminRights ? (\n HeaderContent.ManageGroupNewAdminRights\n ) : managementScreen === ManagementScreens.GroupMembers ? (\n HeaderContent.ManageGroupMembers\n ) : managementScreen === ManagementScreens.GroupAddAdmins ? (\n HeaderContent.ManageGroupAddAdmins\n ) : undefined // Never reached\n ) : undefined; // When column is closed\n\n const renderingContentKey = useCurrentOrPrev(contentKey, true) ?? -1;\n\n function renderHeaderContent() {\n if (renderingContentKey === -1) {\n return undefined;\n }\n\n switch (renderingContentKey) {\n case HeaderContent.PollResults:\n return

{lang('PollResults')}

;\n case HeaderContent.Search:\n return (\n <>\n \n openHistoryCalendar({ selectedAt: getDayStartAt(Date.now()) })}\n ariaLabel=\"Search messages by date\"\n >\n \n \n \n );\n case HeaderContent.AddingMembers:\n return

{lang(isChannel ? 'ChannelAddSubscribers' : 'GroupAddMembers')}

;\n case HeaderContent.ManageInitial:\n return

{lang('Edit')}

;\n case HeaderContent.ManageChatPrivacyType:\n return

{lang(isChannel ? 'ChannelTypeHeader' : 'GroupTypeHeader')}

;\n case HeaderContent.ManageDiscussion:\n return

{lang('Discussion')}

;\n case HeaderContent.ManageChatAdministrators:\n return

{lang('ChannelAdministrators')}

;\n case HeaderContent.ManageGroupRecentActions:\n return

{lang('Group.Info.AdminLog')}

;\n case HeaderContent.ManageGroupAdminRights:\n return

{lang('EditAdminRights')}

;\n case HeaderContent.ManageGroupNewAdminRights:\n return

{lang('SetAsAdmin')}

;\n case HeaderContent.ManageGroupPermissions:\n return

{lang('ChannelPermissions')}

;\n case HeaderContent.ManageGroupRemovedUsers:\n return

{lang('ChannelBlockedUsers')}

;\n case HeaderContent.ManageGroupUserPermissionsCreate:\n return

{lang('ChannelAddException')}

;\n case HeaderContent.ManageGroupUserPermissions:\n return

{lang('UserRestrictions')}

;\n case HeaderContent.ManageGroupAddAdmins:\n return

{lang('Channel.Management.AddModerator')}

;\n case HeaderContent.StickerSearch:\n return (\n \n );\n case HeaderContent.GifSearch:\n return (\n \n );\n case HeaderContent.SharedMedia:\n return

{lang('SharedMedia')}

;\n case HeaderContent.ManageChannelSubscribers:\n return

{lang('ChannelSubscribers')}

;\n case HeaderContent.MemberList:\n case HeaderContent.ManageGroupMembers:\n return

{lang('GroupMembers')}

;\n default:\n return (\n <>\n

Profile

\n
\n {canAddContact && (\n \n \n \n )}\n {canManage && (\n \n \n \n )}\n
\n \n );\n }\n }\n\n const isBackButton = (\n IS_SINGLE_COLUMN_LAYOUT\n || contentKey === HeaderContent.SharedMedia\n || contentKey === HeaderContent.MemberList\n || contentKey === HeaderContent.AddingMembers\n || isManagement\n );\n\n const buttonClassName = buildClassName(\n 'animated-close-icon',\n isBackButton && 'state-back',\n (shouldSkipTransition || shouldSkipAnimation) && 'no-transition',\n );\n\n return (\n
\n \n
\n \n \n {renderHeaderContent}\n \n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { chatId, isProfile, isManagement }): StateProps => {\n const { query: messageSearchQuery } = selectCurrentTextSearch(global) || {};\n const { query: stickerSearchQuery } = selectCurrentStickerSearch(global) || {};\n const { query: gifSearchQuery } = selectCurrentGifSearch(global) || {};\n const chat = chatId ? selectChat(global, chatId) : undefined;\n const isChannel = chat && isChatChannel(chat);\n const user = isProfile && chatId && isUserId(chatId) ? selectUser(global, chatId) : undefined;\n\n const canAddContact = user && getCanAddContact(user);\n const canManage = Boolean(\n !isManagement\n && isProfile\n && !canAddContact\n && chat\n && !selectIsChatWithSelf(global, chat.id)\n // chat.isCreator is for Basic Groups\n && (isUserId(chat.id) || ((isChatAdmin(chat) || chat.isCreator) && !chat.isNotJoined)),\n );\n\n return {\n canManage,\n canAddContact,\n isChannel,\n userId: user?.id,\n messageSearchQuery,\n stickerSearchQuery,\n gifSearchQuery,\n };\n },\n)(RightHeader));\n","import { useMemo, useRef } from '../../../lib/teact/teact';\n\nimport {\n ApiChat, ApiChatMember, ApiMessage, ApiUser, ApiUserStatus,\n} from '../../../api/types';\nimport { ProfileTabType, SharedMediaType } from '../../../types';\n\nimport { MEMBERS_SLICE, MESSAGE_SEARCH_SLICE, SHARED_MEDIA_SLICE } from '../../../config';\nimport { getMessageContentIds, sortChatIds, sortUserIds } from '../../../modules/helpers';\nimport useOnChange from '../../../hooks/useOnChange';\nimport useInfiniteScroll from '../../../hooks/useInfiniteScroll';\n\nexport default function useProfileViewportIds(\n isRightColumnShown: boolean,\n loadMoreMembers: AnyToVoidFunction,\n loadCommonChats: AnyToVoidFunction,\n searchMessages: AnyToVoidFunction,\n tabType: ProfileTabType,\n mediaSearchType?: SharedMediaType,\n groupChatMembers?: ApiChatMember[],\n commonChatIds?: string[],\n usersById?: Record,\n userStatusesById?: Record,\n chatsById?: Record,\n chatMessages?: Record,\n foundIds?: number[],\n chatId?: string,\n lastSyncTime?: number,\n serverTimeOffset = 0,\n) {\n const resultType = tabType === 'members' || !mediaSearchType ? tabType : mediaSearchType;\n\n const memberIds = useMemo(() => {\n if (!groupChatMembers || !usersById || !userStatusesById) {\n return undefined;\n }\n\n return sortUserIds(\n groupChatMembers.map(({ userId }) => userId),\n usersById,\n userStatusesById,\n undefined,\n serverTimeOffset,\n );\n }, [groupChatMembers, serverTimeOffset, usersById, userStatusesById]);\n\n const chatIds = useMemo(() => {\n if (!commonChatIds || !chatsById) {\n return undefined;\n }\n\n return sortChatIds(commonChatIds, chatsById, true);\n }, [chatsById, commonChatIds]);\n\n const [memberViewportIds, getMoreMembers, noProfileInfoForMembers] = useInfiniteScrollForLoadableItems(\n resultType, loadMoreMembers, lastSyncTime, memberIds,\n );\n\n const [mediaViewportIds, getMoreMedia, noProfileInfoForMedia] = useInfiniteScrollForSharedMedia(\n 'media', resultType, searchMessages, lastSyncTime, chatMessages, foundIds,\n );\n\n const [documentViewportIds, getMoreDocuments, noProfileInfoForDocuments] = useInfiniteScrollForSharedMedia(\n 'documents', resultType, searchMessages, lastSyncTime, chatMessages, foundIds,\n );\n\n const [linkViewportIds, getMoreLinks, noProfileInfoForLinks] = useInfiniteScrollForSharedMedia(\n 'links', resultType, searchMessages, lastSyncTime, chatMessages, foundIds,\n );\n\n const [audioViewportIds, getMoreAudio, noProfileInfoForAudio] = useInfiniteScrollForSharedMedia(\n 'audio', resultType, searchMessages, lastSyncTime, chatMessages, foundIds,\n );\n\n const [voiceViewportIds, getMoreVoices, noProfileInfoForVoices] = useInfiniteScrollForSharedMedia(\n 'voice', resultType, searchMessages, lastSyncTime, chatMessages, foundIds,\n );\n\n const [commonChatViewportIds, getMoreCommonChats, noProfileInfoForCommonChats] = useInfiniteScrollForLoadableItems(\n resultType, loadCommonChats, lastSyncTime, chatIds,\n );\n\n let viewportIds: number[] | string[] | undefined;\n let getMore: AnyToVoidFunction | undefined;\n let noProfileInfo = false;\n\n switch (resultType) {\n case 'members':\n viewportIds = memberViewportIds;\n getMore = getMoreMembers;\n noProfileInfo = noProfileInfoForMembers;\n break;\n case 'commonChats':\n viewportIds = commonChatViewportIds;\n getMore = getMoreCommonChats;\n noProfileInfo = noProfileInfoForCommonChats;\n break;\n case 'media':\n viewportIds = mediaViewportIds;\n getMore = getMoreMedia;\n noProfileInfo = noProfileInfoForMedia;\n break;\n case 'documents':\n viewportIds = documentViewportIds;\n getMore = getMoreDocuments;\n noProfileInfo = noProfileInfoForDocuments;\n break;\n case 'links':\n viewportIds = linkViewportIds;\n getMore = getMoreLinks;\n noProfileInfo = noProfileInfoForLinks;\n break;\n case 'audio':\n viewportIds = audioViewportIds;\n getMore = getMoreAudio;\n noProfileInfo = noProfileInfoForAudio;\n break;\n case 'voice':\n viewportIds = voiceViewportIds;\n getMore = getMoreVoices;\n noProfileInfo = noProfileInfoForVoices;\n break;\n }\n\n return [resultType, viewportIds, getMore, noProfileInfo] as const;\n}\n\nfunction useInfiniteScrollForLoadableItems(\n currentResultType?: ProfileTabType,\n handleLoadMore?: AnyToVoidFunction,\n lastSyncTime?: number,\n itemIds?: string[],\n) {\n const [viewportIds, getMore] = useInfiniteScroll(\n lastSyncTime ? handleLoadMore : undefined,\n itemIds,\n undefined,\n MEMBERS_SLICE,\n );\n\n const isOnTop = !viewportIds || !itemIds || viewportIds[0] === itemIds[0];\n\n return [viewportIds, getMore, !isOnTop] as const;\n}\n\nfunction useInfiniteScrollForSharedMedia(\n forSharedMediaType: SharedMediaType,\n currentResultType?: ProfileTabType,\n handleLoadMore?: AnyToVoidFunction,\n lastSyncTime?: number,\n chatMessages?: Record,\n foundIds?: number[],\n) {\n const messageIdsRef = useRef();\n\n useOnChange(() => {\n if (currentResultType === forSharedMediaType && chatMessages && foundIds) {\n messageIdsRef.current = getMessageContentIds(\n chatMessages,\n foundIds,\n forSharedMediaType,\n ).reverse();\n }\n }, [chatMessages, foundIds, currentResultType, forSharedMediaType]);\n\n const [viewportIds, getMore] = useInfiniteScroll(\n lastSyncTime ? handleLoadMore : undefined,\n messageIdsRef.current,\n undefined,\n forSharedMediaType === 'media' ? SHARED_MEDIA_SLICE : MESSAGE_SEARCH_SLICE,\n );\n\n const isOnTop = !viewportIds || !messageIdsRef.current || viewportIds[0] === messageIdsRef.current[0];\n\n return [viewportIds, getMore, !isOnTop] as const;\n}\n","import { useCallback, useEffect } from '../../../lib/teact/teact';\n\nimport { ProfileState } from '../../../types';\n\nimport fastSmoothScroll from '../../../util/fastSmoothScroll';\nimport { throttle } from '../../../util/schedulers';\nimport useEffectWithPrevDeps from '../../../hooks/useEffectWithPrevDeps';\n\nconst TRANSITION_DURATION = 300;\nconst PROGRAMMATIC_SCROLL_TIMEOUT_MS = 350;\n\nconst runThrottledForScroll = throttle((cb) => cb(), 250, false);\n\nlet isScrollingProgrammatically = false;\n\nexport default function useProfileState(\n containerRef: { current: HTMLDivElement | null },\n tabType: string,\n profileState: ProfileState,\n onProfileStateChange: (state: ProfileState) => void,\n) {\n // Scroll to tabs if needed\n useEffectWithPrevDeps(([prevTabType]) => {\n if (prevTabType && prevTabType !== tabType) {\n const container = containerRef.current!;\n const tabsEl = container.querySelector('.TabList')!;\n if (container.scrollTop < tabsEl.offsetTop) {\n onProfileStateChange(tabType === 'members' ? ProfileState.MemberList : ProfileState.SharedMedia);\n isScrollingProgrammatically = true;\n fastSmoothScroll(container, tabsEl, 'start', undefined, undefined, undefined, TRANSITION_DURATION);\n setTimeout(() => {\n isScrollingProgrammatically = false;\n }, PROGRAMMATIC_SCROLL_TIMEOUT_MS);\n }\n }\n }, [tabType, onProfileStateChange]);\n\n // Scroll to top\n useEffectWithPrevDeps(([prevProfileState]) => {\n if (profileState !== ProfileState.Profile || profileState === prevProfileState) {\n return;\n }\n\n const container = containerRef.current;\n if (!container) {\n return;\n }\n\n const tabListEl = container.querySelector('.TabList');\n if (!tabListEl || tabListEl.offsetTop > container.scrollTop) {\n return;\n }\n\n isScrollingProgrammatically = true;\n fastSmoothScroll(\n container,\n container.firstElementChild as HTMLElement,\n 'start',\n undefined,\n container.offsetHeight * 2,\n );\n\n setTimeout(() => {\n isScrollingProgrammatically = false;\n }, PROGRAMMATIC_SCROLL_TIMEOUT_MS);\n\n onProfileStateChange(profileState);\n }, [profileState]);\n\n const determineProfileState = useCallback(() => {\n const container = containerRef.current;\n if (!container) {\n return;\n }\n\n const tabListEl = container.querySelector('.TabList');\n if (!tabListEl) {\n return;\n }\n\n let state: ProfileState = ProfileState.Profile;\n if (container.scrollTop >= tabListEl.offsetTop) {\n state = tabType === 'members'\n ? ProfileState.MemberList\n : ProfileState.SharedMedia;\n }\n\n onProfileStateChange(state);\n }, [containerRef, onProfileStateChange, tabType]);\n\n // Determine profile state when switching tabs\n useEffect(() => {\n if (isScrollingProgrammatically) {\n return;\n }\n\n determineProfileState();\n }, [determineProfileState, tabType]);\n\n // Determine profile state when scrolling\n const handleScroll = useCallback(() => {\n if (isScrollingProgrammatically) {\n return;\n }\n\n runThrottledForScroll(determineProfileState);\n }, [determineProfileState]);\n\n return { handleScroll };\n}\n","import React, {\n FC, useCallback, useEffect, useMemo, useRef, useState, memo,\n} from '../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../lib/teact/teactn';\n\nimport {\n MAIN_THREAD_ID,\n ApiMessage,\n ApiChat,\n ApiChatMember,\n ApiUser,\n ApiUserStatus,\n} from '../../api/types';\nimport {\n NewChatMembersProgress, ISettings, MediaViewerOrigin, ProfileState, ProfileTabType, SharedMediaType, AudioOrigin,\n} from '../../types';\n\nimport {\n MEMBERS_SLICE,\n PROFILE_SENSITIVE_AREA,\n SHARED_MEDIA_SLICE,\n SLIDE_TRANSITION_DURATION,\n} from '../../config';\nimport { IS_TOUCH_ENV } from '../../util/environment';\nimport {\n getHasAdminRight, isChatAdmin, isChatChannel, isChatGroup, isUserBot, isUserId,\n} from '../../modules/helpers';\nimport {\n selectChatMessages,\n selectChat,\n selectCurrentMediaSearch,\n selectIsRightColumnShown,\n selectTheme,\n selectActiveDownloadIds,\n selectUser,\n} from '../../modules/selectors';\nimport { captureEvents, SwipeDirection } from '../../util/captureEvents';\nimport { getSenderName } from '../left/search/helpers/getSenderName';\nimport useCacheBuster from '../../hooks/useCacheBuster';\nimport useProfileViewportIds from './hooks/useProfileViewportIds';\nimport useProfileState from './hooks/useProfileState';\nimport useTransitionFixes from './hooks/useTransitionFixes';\nimport useAsyncRendering from './hooks/useAsyncRendering';\nimport useLang from '../../hooks/useLang';\n\nimport Transition from '../ui/Transition';\nimport InfiniteScroll from '../ui/InfiniteScroll';\nimport TabList from '../ui/TabList';\nimport Spinner from '../ui/Spinner';\nimport ListItem from '../ui/ListItem';\nimport PrivateChatInfo from '../common/PrivateChatInfo';\nimport ProfileInfo from '../common/ProfileInfo';\nimport Document from '../common/Document';\nimport Audio from '../common/Audio';\nimport ChatExtra from '../common/ChatExtra';\nimport Media from '../common/Media';\nimport WebLink from '../common/WebLink';\nimport NothingFound from '../common/NothingFound';\nimport FloatingActionButton from '../ui/FloatingActionButton';\nimport DeleteMemberModal from './DeleteMemberModal';\nimport GroupChatInfo from '../common/GroupChatInfo';\n\nimport './Profile.scss';\n\ntype OwnProps = {\n chatId: string;\n userId?: string;\n profileState: ProfileState;\n onProfileStateChange: (state: ProfileState) => void;\n};\n\ntype StateProps = {\n theme: ISettings['theme'];\n isChannel?: boolean;\n currentUserId?: string;\n resolvedUserId?: string;\n chatMessages?: Record;\n foundIds?: number[];\n mediaSearchType?: SharedMediaType;\n hasCommonChatsTab?: boolean;\n hasMembersTab?: boolean;\n areMembersHidden?: boolean;\n canAddMembers?: boolean;\n canDeleteMembers?: boolean;\n members?: ApiChatMember[];\n commonChatIds?: string[];\n chatsById: Record;\n usersById: Record;\n userStatusesById: Record;\n isRightColumnShown: boolean;\n isRestricted?: boolean;\n lastSyncTime?: number;\n serverTimeOffset: number;\n activeDownloadIds: number[];\n isChatProtected?: boolean;\n};\n\nconst TABS = [\n { type: 'media', title: 'SharedMediaTab2' },\n { type: 'documents', title: 'SharedFilesTab2' },\n { type: 'links', title: 'SharedLinksTab2' },\n { type: 'audio', title: 'SharedMusicTab2' },\n { type: 'voice', title: 'SharedVoiceTab2' },\n];\n\nconst HIDDEN_RENDER_DELAY = 1000;\n\nconst Profile: FC = ({\n chatId,\n profileState,\n onProfileStateChange,\n theme,\n isChannel,\n resolvedUserId,\n currentUserId,\n chatMessages,\n foundIds,\n mediaSearchType,\n hasCommonChatsTab,\n hasMembersTab,\n areMembersHidden,\n canAddMembers,\n canDeleteMembers,\n commonChatIds,\n members,\n usersById,\n userStatusesById,\n chatsById,\n isRightColumnShown,\n isRestricted,\n lastSyncTime,\n activeDownloadIds,\n serverTimeOffset,\n isChatProtected,\n}) => {\n const {\n setLocalMediaSearchType,\n loadMoreMembers,\n loadCommonChats,\n openChat,\n searchMediaMessagesLocal,\n openMediaViewer,\n openAudioPlayer,\n openUserInfo,\n focusMessage,\n loadProfilePhotos,\n setNewChatMembersDialogState,\n } = getDispatch();\n\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const transitionRef = useRef(null);\n const lang = useLang();\n const [activeTab, setActiveTab] = useState(0);\n const [deletingUserId, setDeletingUserId] = useState();\n\n const tabs = useMemo(() => ([\n ...(hasMembersTab ? [{\n type: 'members', title: isChannel ? 'ChannelSubscribers' : 'GroupMembers',\n }] : []),\n ...TABS,\n ...(hasCommonChatsTab ? [{\n type: 'commonChats', title: 'SharedGroupsTab2',\n }] : []),\n ]), [hasCommonChatsTab, hasMembersTab, isChannel]);\n const tabType = tabs[activeTab].type as ProfileTabType;\n\n const [resultType, viewportIds, getMore, noProfileInfo] = useProfileViewportIds(\n isRightColumnShown, loadMoreMembers, loadCommonChats, searchMediaMessagesLocal, tabType, mediaSearchType, members,\n commonChatIds, usersById, userStatusesById, chatsById, chatMessages, foundIds, chatId, lastSyncTime,\n serverTimeOffset,\n );\n const activeKey = tabs.findIndex(({ type }) => type === resultType);\n\n const { handleScroll } = useProfileState(containerRef, tabType, profileState, onProfileStateChange);\n\n const { applyTransitionFix, releaseTransitionFix } = useTransitionFixes(containerRef);\n\n const [cacheBuster, resetCacheBuster] = useCacheBuster();\n\n const handleTransitionStop = useCallback(() => {\n releaseTransitionFix();\n resetCacheBuster();\n }, [releaseTransitionFix, resetCacheBuster]);\n\n const handleNewMemberDialogOpen = useCallback(() => {\n setNewChatMembersDialogState(NewChatMembersProgress.InProgress);\n }, [setNewChatMembersDialogState]);\n\n // Update search type when switching tabs\n useEffect(() => {\n setLocalMediaSearchType({ mediaType: tabType });\n }, [setLocalMediaSearchType, tabType]);\n\n const profileId = resolvedUserId || chatId;\n\n useEffect(() => {\n if (lastSyncTime) {\n loadProfilePhotos({ profileId });\n }\n }, [loadProfilePhotos, profileId, lastSyncTime]);\n\n const handleSelectMedia = useCallback((messageId: number) => {\n openMediaViewer({\n chatId: profileId,\n threadId: MAIN_THREAD_ID,\n messageId,\n origin: MediaViewerOrigin.SharedMedia,\n });\n }, [profileId, openMediaViewer]);\n\n const handlePlayAudio = useCallback((messageId: number) => {\n openAudioPlayer({ chatId: profileId, messageId });\n }, [profileId, openAudioPlayer]);\n\n const handleMemberClick = useCallback((id: string) => {\n openUserInfo({ id });\n }, [openUserInfo]);\n\n const handleMessageFocus = useCallback((messageId: number) => {\n focusMessage({ chatId: profileId, messageId });\n }, [profileId, focusMessage]);\n\n const handleDeleteMembersModalClose = useCallback(() => {\n setDeletingUserId(undefined);\n }, []);\n\n useEffect(() => {\n if (!transitionRef.current || !IS_TOUCH_ENV) {\n return undefined;\n }\n\n return captureEvents(transitionRef.current, {\n selectorToPreventScroll: '.Profile',\n onSwipe: ((e, direction) => {\n if (direction === SwipeDirection.Left) {\n setActiveTab(Math.min(activeTab + 1, tabs.length - 1));\n return true;\n } else if (direction === SwipeDirection.Right) {\n setActiveTab(Math.max(0, activeTab - 1));\n return true;\n }\n\n return false;\n }),\n });\n }, [activeTab, tabs.length]);\n\n let renderingDelay;\n const isFirstTab = resultType === 'members' || (!hasMembersTab && resultType === 'media');\n // @optimization Used to unparallelize rendering of message list and profile media\n if (isFirstTab) {\n renderingDelay = !isRightColumnShown ? HIDDEN_RENDER_DELAY : 0;\n // @optimization Used to delay first render of secondary tabs while animating\n } else if (!viewportIds) {\n renderingDelay = SLIDE_TRANSITION_DURATION;\n }\n const canRenderContents = useAsyncRendering([chatId, resultType], renderingDelay);\n\n function getMemberContextAction(memberId: string) {\n return memberId === currentUserId || !canDeleteMembers ? undefined : [{\n title: lang('lng_context_remove_from_group'),\n icon: 'stop',\n handler: () => {\n setDeletingUserId(memberId);\n },\n }];\n }\n\n function renderSharedMedia() {\n if (!viewportIds || !canRenderContents || !chatMessages) {\n // This is just a single-frame delay, so we do not show spinner\n const noSpinner = isFirstTab && viewportIds && !canRenderContents;\n\n return (\n
\n {!noSpinner && }\n
\n );\n }\n\n if (!viewportIds.length) {\n let text: string;\n\n switch (resultType) {\n case 'members':\n text = areMembersHidden ? 'You have no access to group members list.' : 'No members found';\n break;\n case 'commonChats':\n text = lang('NoGroupsInCommon');\n break;\n case 'documents':\n text = lang('lng_media_file_empty');\n break;\n case 'links':\n text = lang('lng_media_link_empty');\n break;\n case 'audio':\n text = lang('lng_media_song_empty');\n break;\n case 'voice':\n text = lang('lng_media_audio_empty');\n break;\n default:\n text = lang('SharedMedia.EmptyTitle');\n }\n\n return (\n
\n \n
\n );\n }\n\n return (\n \n {resultType === 'media' ? (\n (viewportIds as number[])!.map((id) => chatMessages[id] && (\n \n ))\n ) : resultType === 'documents' ? (\n (viewportIds as number[])!.map((id) => chatMessages[id] && (\n \n ))\n ) : resultType === 'links' ? (\n (viewportIds as number[])!.map((id) => chatMessages[id] && (\n \n ))\n ) : resultType === 'audio' ? (\n (viewportIds as number[])!.map((id) => chatMessages[id] && (\n \n ))\n ) : resultType === 'voice' ? (\n (viewportIds as number[])!.map((id) => chatMessages[id] && (\n \n ))\n ) : resultType === 'members' ? (\n (viewportIds as string[])!.map((id, i) => (\n handleMemberClick(id)}\n contextActions={getMemberContextAction(id)}\n >\n \n \n ))\n ) : resultType === 'commonChats' ? (\n (viewportIds as string[])!.map((id, i) => (\n openChat({ id })}\n >\n \n \n ))\n ) : undefined}\n
\n );\n }\n\n return (\n \n {!noProfileInfo && renderProfileInfo(chatId, resolvedUserId)}\n {!isRestricted && (\n \n \n {renderSharedMedia}\n \n \n
\n )}\n\n {canAddMembers && (\n \n \n \n )}\n {canDeleteMembers && (\n \n )}\n \n );\n};\n\nfunction renderProfileInfo(chatId: string, resolvedUserId?: string) {\n return (\n
\n \n \n
\n );\n}\n\nfunction buildInfiniteScrollItemSelector(resultType: string) {\n return [\n // Used on first render\n `.shared-media-transition > div:only-child > .${resultType}-list > .scroll-item`,\n // Used after transition\n `.shared-media-transition > .Transition__slide--active > .${resultType}-list > .scroll-item`,\n ].join(', ');\n}\n\nexport default memo(withGlobal(\n (global, { chatId, userId }): StateProps => {\n const chat = selectChat(global, chatId);\n\n const chatMessages = selectChatMessages(global, userId || chatId);\n const { currentType: mediaSearchType, resultsByType } = selectCurrentMediaSearch(global) || {};\n const { foundIds } = (resultsByType && mediaSearchType && resultsByType[mediaSearchType]) || {};\n\n const { byId: usersById, statusesById: userStatusesById } = global.users;\n const { byId: chatsById } = global.chats;\n\n const isGroup = chat && isChatGroup(chat);\n const isChannel = chat && isChatChannel(chat);\n const hasMembersTab = isGroup || (isChannel && isChatAdmin(chat!));\n const members = chat?.fullInfo?.members;\n const areMembersHidden = hasMembersTab && chat && chat.fullInfo && !chat.fullInfo.canViewMembers;\n const canAddMembers = hasMembersTab && chat && (getHasAdminRight(chat, 'inviteUsers') || chat.isCreator);\n const canDeleteMembers = hasMembersTab && chat && (getHasAdminRight(chat, 'banUsers') || chat.isCreator);\n\n const activeDownloadIds = selectActiveDownloadIds(global, chatId);\n\n let hasCommonChatsTab;\n let resolvedUserId;\n let user;\n if (userId) {\n resolvedUserId = userId;\n } else if (isUserId(chatId)) {\n resolvedUserId = chatId;\n }\n if (resolvedUserId) {\n user = selectUser(global, resolvedUserId);\n hasCommonChatsTab = user && !user.isSelf && !isUserBot(user);\n }\n\n return {\n theme: selectTheme(global),\n isChannel,\n resolvedUserId,\n chatMessages,\n foundIds,\n mediaSearchType,\n hasCommonChatsTab,\n hasMembersTab,\n areMembersHidden,\n canAddMembers,\n canDeleteMembers,\n currentUserId: global.currentUserId,\n isRightColumnShown: selectIsRightColumnShown(global),\n isRestricted: chat?.isRestricted,\n lastSyncTime: global.lastSyncTime,\n serverTimeOffset: global.serverTimeOffset,\n activeDownloadIds,\n usersById,\n userStatusesById,\n chatsById,\n isChatProtected: chat?.isProtected,\n ...(hasMembersTab && members && { members }),\n ...(hasCommonChatsTab && user && { commonChatIds: user.commonChats?.ids }),\n };\n },\n)(Profile));\n","import { useCallback, useEffect } from '../../../lib/teact/teact';\n\nexport default function useTransitionFixes(\n containerRef: { current: HTMLDivElement | null },\n transitionElSelector = '.Transition.shared-media-transition',\n) {\n // Set `min-height` for shared media container to prevent jumping when switching tabs\n useEffect(() => {\n function setMinHeight() {\n const container = containerRef.current!;\n const transitionEl = container.querySelector(transitionElSelector);\n const tabsEl = container.querySelector('.TabList');\n if (transitionEl && tabsEl) {\n transitionEl.style.minHeight = `${container.offsetHeight - tabsEl.offsetHeight}px`;\n }\n }\n\n setMinHeight();\n\n window.addEventListener('resize', setMinHeight, false);\n\n return () => {\n window.removeEventListener('resize', setMinHeight, false);\n };\n }, [containerRef, transitionElSelector]);\n\n // Workaround for scrollable content flickering during animation.\n const applyTransitionFix = useCallback(() => {\n const container = containerRef.current!;\n if (container.style.overflowY !== 'hidden') {\n const scrollBarWidth = container.offsetWidth - container.clientWidth;\n container.style.overflowY = 'hidden';\n container.style.marginRight = `${scrollBarWidth}px`;\n }\n }, [containerRef]);\n\n const releaseTransitionFix = useCallback(() => {\n const container = containerRef.current!;\n container.style.overflowY = 'scroll';\n container.style.marginRight = '0';\n }, [containerRef]);\n\n return { applyTransitionFix, releaseTransitionFix };\n}\n","import { useCallback, useState } from '../lib/teact/teact';\n\nexport default () => {\n const [cacheBuster, setCacheBuster] = useState(false);\n\n const updateCacheBuster = useCallback(() => {\n setCacheBuster((current) => !current);\n }, []);\n\n return [cacheBuster, updateCacheBuster] as const;\n};\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './RightSearch';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst RightSearchAsync: FC = (props) => {\n const RightSearch = useModuleLoader(Bundles.Extra, 'RightSearch');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return RightSearch ? : ;\n};\n\nexport default memo(RightSearchAsync);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport { OwnProps } from './Management';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nimport Loading from '../../ui/Loading';\n\nconst ManagementAsync: FC = (props) => {\n const Management = useModuleLoader(Bundles.Extra, 'Management');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return Management ? : ;\n};\n\nexport default memo(ManagementAsync);\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 StickerSearchAsync: FC = () => {\n const StickerSearch = useModuleLoader(Bundles.Extra, 'StickerSearch');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return StickerSearch ? : ;\n};\n\nexport default memo(StickerSearchAsync);\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 GifSearchAsync: FC = () => {\n const GifSearch = useModuleLoader(Bundles.Extra, 'GifSearch');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return GifSearch ? : ;\n};\n\nexport default memo(GifSearchAsync);\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 PollResultsAsync: FC = () => {\n const PollResults = useModuleLoader(Bundles.Extra, 'PollResults');\n\n return PollResults ? : ;\n};\n\nexport default memo(PollResultsAsync);\n","import React, {\n FC, useCallback, useMemo, memo, useState, useEffect,\n} from '../../lib/teact/teact';\nimport { getDispatch, getGlobal, withGlobal } from '../../lib/teact/teactn';\n\nimport {\n ApiChat, ApiChatMember, ApiUpdateConnectionStateType,\n} from '../../api/types';\nimport { NewChatMembersProgress } from '../../types';\n\nimport { unique } from '../../util/iteratees';\nimport { selectChat } from '../../modules/selectors';\nimport {\n filterUsersByName, isChatChannel, isUserBot, sortChatIds,\n} from '../../modules/helpers';\nimport useLang from '../../hooks/useLang';\nimport usePrevious from '../../hooks/usePrevious';\nimport useHistoryBack from '../../hooks/useHistoryBack';\n\nimport Picker from '../common/Picker';\nimport FloatingActionButton from '../ui/FloatingActionButton';\nimport Spinner from '../ui/Spinner';\n\nimport './AddChatMembers.scss';\n\nexport type OwnProps = {\n chatId: string;\n isActive: boolean;\n onNextStep: (memberIds: string[]) => void;\n onClose: NoneToVoidFunction;\n};\n\ntype StateProps = {\n connectionState?: ApiUpdateConnectionStateType;\n isChannel?: boolean;\n members?: ApiChatMember[];\n currentUserId?: string;\n chatsById: Record;\n localContactIds?: string[];\n searchQuery?: string;\n isLoading: boolean;\n isSearching?: boolean;\n localUserIds?: string[];\n globalUserIds?: string[];\n};\n\nconst AddChatMembers: FC = ({\n isChannel,\n connectionState,\n members,\n onNextStep,\n currentUserId,\n chatsById,\n localContactIds,\n isLoading,\n searchQuery,\n isSearching,\n localUserIds,\n globalUserIds,\n onClose,\n isActive,\n}) => {\n const { setUserSearchQuery, loadContactList } = getDispatch();\n\n const lang = useLang();\n const [selectedMemberIds, setSelectedMemberIds] = useState([]);\n const prevSelectedMemberIds = usePrevious(selectedMemberIds);\n const noPickerScrollRestore = prevSelectedMemberIds === selectedMemberIds;\n\n useEffect(() => {\n if (isActive && connectionState === 'connectionStateReady') {\n loadContactList();\n }\n }, [connectionState, isActive, loadContactList]);\n\n useHistoryBack(isActive, onClose);\n\n const memberIds = useMemo(() => {\n return members ? members.map((member) => member.userId) : [];\n }, [members]);\n\n const handleFilterChange = useCallback((query: string) => {\n setUserSearchQuery({ query });\n }, [setUserSearchQuery]);\n\n const displayedIds = useMemo(() => {\n // No need for expensive global updates on users, so we avoid them\n const usersById = getGlobal().users.byId;\n const filteredContactIds = localContactIds ? filterUsersByName(localContactIds, usersById, searchQuery) : [];\n\n return sortChatIds(\n unique([\n ...filteredContactIds,\n ...(localUserIds || []),\n ...(globalUserIds || []),\n ]).filter((userId) => {\n const user = usersById[userId];\n\n // The user can be added to the chat if the following conditions are met:\n // the user has not yet been added to the current chat\n // AND it is not the current user,\n // AND (it is not found (user from global search) OR it is not a bot OR it is a bot,\n // but the current chat is not a channel AND the appropriate permission is set).\n return (\n !memberIds.includes(userId)\n && userId !== currentUserId\n && (!user || !isUserBot(user) || (!isChannel && user.canBeInvitedToGroup))\n );\n }),\n chatsById,\n );\n }, [\n localContactIds, chatsById, searchQuery, localUserIds, globalUserIds, currentUserId, memberIds, isChannel,\n ]);\n\n const handleNextStep = useCallback(() => {\n if (selectedMemberIds.length) {\n setUserSearchQuery({ query: '' });\n onNextStep(selectedMemberIds);\n }\n }, [selectedMemberIds, setUserSearchQuery, onNextStep]);\n\n return (\n
\n
\n \n\n \n {isLoading ? (\n \n ) : (\n \n )}\n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { chatId }): StateProps => {\n const chat = selectChat(global, chatId);\n const { userIds: localContactIds } = global.contactList || {};\n const { byId: chatsById } = global.chats;\n const { currentUserId, newChatMembersProgress, connectionState } = global;\n const isChannel = chat && isChatChannel(chat);\n\n const {\n query: searchQuery,\n fetchingStatus,\n globalUserIds,\n localUserIds,\n } = global.userSearch;\n\n return {\n isChannel,\n members: chat?.fullInfo?.members,\n currentUserId,\n chatsById,\n localContactIds,\n searchQuery,\n isSearching: fetchingStatus,\n isLoading: newChatMembersProgress === NewChatMembersProgress.Loading,\n globalUserIds,\n localUserIds,\n connectionState,\n };\n },\n)(AddChatMembers));\n","import React, {\n FC, memo, useCallback, useEffect, useState,\n} from '../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../lib/teact/teactn';\n\nimport {\n ManagementScreens, NewChatMembersProgress, ProfileState, RightColumnContent,\n} from '../../types';\n\nimport { MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN } from '../../config';\nimport captureEscKeyListener from '../../util/captureEscKeyListener';\nimport {\n selectAreActiveChatsLoaded,\n selectCurrentMessageList,\n selectRightColumnContentKey,\n} from '../../modules/selectors';\nimport useLayoutEffectWithPrevDeps from '../../hooks/useLayoutEffectWithPrevDeps';\nimport useWindowSize from '../../hooks/useWindowSize';\nimport useCurrentOrPrev from '../../hooks/useCurrentOrPrev';\nimport useHistoryBack from '../../hooks/useHistoryBack';\n\nimport RightHeader from './RightHeader';\nimport Profile from './Profile';\nimport Transition from '../ui/Transition';\nimport RightSearch from './RightSearch.async';\nimport Management from './management/Management.async';\nimport StickerSearch from './StickerSearch.async';\nimport GifSearch from './GifSearch.async';\nimport PollResults from './PollResults.async';\nimport AddChatMembers from './AddChatMembers';\n\nimport './RightColumn.scss';\n\ntype StateProps = {\n contentKey?: RightColumnContent;\n chatId?: string;\n threadId?: number;\n currentProfileUserId?: string;\n isChatSelected: boolean;\n shouldSkipHistoryAnimations?: boolean;\n};\n\nconst COLUMN_CLOSE_DELAY_MS = 300;\nconst MAIN_SCREENS_COUNT = Object.keys(RightColumnContent).length / 2;\nconst MANAGEMENT_SCREENS_COUNT = Object.keys(ManagementScreens).length / 2;\n\nfunction blurSearchInput() {\n const searchInput = document.querySelector('.RightHeader .SearchInput input') as HTMLInputElement;\n if (searchInput) {\n searchInput.blur();\n }\n}\n\nconst RightColumn: FC = ({\n contentKey,\n chatId,\n threadId,\n currentProfileUserId,\n isChatSelected,\n shouldSkipHistoryAnimations,\n}) => {\n const {\n toggleChatInfo,\n toggleManagement,\n openUserInfo,\n closeLocalTextSearch,\n setStickerSearchQuery,\n setGifSearchQuery,\n closePollResults,\n addChatMembers,\n setNewChatMembersDialogState,\n } = getDispatch();\n\n const { width: windowWidth } = useWindowSize();\n const [profileState, setProfileState] = useState(ProfileState.Profile);\n const [managementScreen, setManagementScreen] = useState(ManagementScreens.Initial);\n const [selectedChatMemberId, setSelectedChatMemberId] = useState();\n const [isPromotedByCurrentUser, setIsPromotedByCurrentUser] = useState();\n const isScrolledDown = profileState !== ProfileState.Profile;\n\n const isOpen = contentKey !== undefined;\n const isProfile = contentKey === RightColumnContent.ChatInfo || contentKey === RightColumnContent.UserInfo;\n const isSearch = contentKey === RightColumnContent.Search;\n const isManagement = contentKey === RightColumnContent.Management;\n const isStickerSearch = contentKey === RightColumnContent.StickerSearch;\n const isGifSearch = contentKey === RightColumnContent.GifSearch;\n const isPollResults = contentKey === RightColumnContent.PollResults;\n const isAddingChatMembers = contentKey === RightColumnContent.AddingMembers;\n const isOverlaying = windowWidth <= MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN;\n\n const [shouldSkipTransition, setShouldSkipTransition] = useState(!isOpen);\n\n const renderingContentKey = useCurrentOrPrev(contentKey, true, !isChatSelected) ?? -1;\n\n const close = useCallback((shouldScrollUp = true) => {\n switch (contentKey) {\n case RightColumnContent.AddingMembers:\n setNewChatMembersDialogState(NewChatMembersProgress.Closed);\n break;\n case RightColumnContent.ChatInfo:\n if (isScrolledDown && shouldScrollUp) {\n setProfileState(ProfileState.Profile);\n break;\n }\n toggleChatInfo(undefined, { forceSyncOnIOs: true });\n break;\n case RightColumnContent.UserInfo:\n if (isScrolledDown && shouldScrollUp) {\n setProfileState(ProfileState.Profile);\n break;\n }\n openUserInfo({ id: undefined }, { forceSyncOnIOs: true });\n break;\n case RightColumnContent.Management: {\n switch (managementScreen) {\n case ManagementScreens.Initial:\n toggleManagement();\n break;\n case ManagementScreens.ChatPrivacyType:\n case ManagementScreens.Discussion:\n case ManagementScreens.GroupPermissions:\n case ManagementScreens.GroupType:\n case ManagementScreens.ChatAdministrators:\n case ManagementScreens.ChannelSubscribers:\n case ManagementScreens.GroupMembers:\n setManagementScreen(ManagementScreens.Initial);\n break;\n case ManagementScreens.GroupUserPermissionsCreate:\n case ManagementScreens.GroupRemovedUsers:\n case ManagementScreens.GroupUserPermissions:\n setManagementScreen(ManagementScreens.GroupPermissions);\n setSelectedChatMemberId(undefined);\n setIsPromotedByCurrentUser(undefined);\n break;\n case ManagementScreens.ChatAdminRights:\n case ManagementScreens.ChatNewAdminRights:\n case ManagementScreens.GroupAddAdmins:\n case ManagementScreens.GroupRecentActions:\n setManagementScreen(ManagementScreens.ChatAdministrators);\n break;\n }\n\n break;\n }\n case RightColumnContent.Search: {\n blurSearchInput();\n closeLocalTextSearch();\n break;\n }\n case RightColumnContent.StickerSearch:\n blurSearchInput();\n setStickerSearchQuery({ query: undefined });\n break;\n case RightColumnContent.GifSearch: {\n blurSearchInput();\n setGifSearchQuery({ query: undefined });\n break;\n }\n case RightColumnContent.PollResults:\n closePollResults();\n break;\n }\n }, [\n contentKey, isScrolledDown, toggleChatInfo, openUserInfo, closePollResults, setNewChatMembersDialogState,\n managementScreen, toggleManagement, closeLocalTextSearch, setStickerSearchQuery, setGifSearchQuery,\n ]);\n\n const handleSelectChatMember = useCallback((memberId, isPromoted) => {\n setSelectedChatMemberId(memberId);\n setIsPromotedByCurrentUser(isPromoted);\n }, []);\n\n const handleAppendingChatMembers = useCallback((memberIds: string[]) => {\n addChatMembers({ chatId, memberIds });\n }, [addChatMembers, chatId]);\n\n useEffect(() => (isOpen ? captureEscKeyListener(close) : undefined), [isOpen, close]);\n\n useEffect(() => {\n setTimeout(() => {\n setShouldSkipTransition(!isOpen);\n }, COLUMN_CLOSE_DELAY_MS);\n }, [isOpen]);\n\n // Close Right Column when it transforms into overlayed state on screen resize\n useEffect(() => {\n if (isOpen && isOverlaying) {\n close();\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [isOverlaying]);\n\n // We need to clear profile state and management screen state, when changing chats\n useLayoutEffectWithPrevDeps(([prevContentKey, prevChatId]) => {\n if (\n (prevContentKey === RightColumnContent.ChatInfo && contentKey === RightColumnContent.UserInfo)\n || (prevContentKey === RightColumnContent.UserInfo && contentKey === RightColumnContent.ChatInfo)\n || (prevChatId !== chatId)\n ) {\n setProfileState(ProfileState.Profile);\n setManagementScreen(ManagementScreens.Initial);\n }\n }, [contentKey, chatId]);\n\n useHistoryBack(isChatSelected && (contentKey === RightColumnContent.ChatInfo\n || contentKey === RightColumnContent.UserInfo || contentKey === RightColumnContent.Management\n || contentKey === RightColumnContent.AddingMembers),\n () => close(false), toggleChatInfo);\n\n // eslint-disable-next-line consistent-return\n function renderContent(isActive: boolean) {\n if (renderingContentKey === -1) {\n return undefined;\n }\n\n switch (renderingContentKey) {\n case RightColumnContent.AddingMembers:\n return (\n \n );\n case RightColumnContent.ChatInfo:\n case RightColumnContent.UserInfo:\n return (\n \n );\n case RightColumnContent.Search:\n return ;\n case RightColumnContent.Management:\n return (\n \n );\n\n case RightColumnContent.StickerSearch:\n return ;\n case RightColumnContent.GifSearch:\n return ;\n case RightColumnContent.PollResults:\n return ;\n }\n }\n\n return (\n \n {isOverlaying && (\n
\n )}\n
\n \n \n {renderContent}\n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n const areActiveChatsLoaded = selectAreActiveChatsLoaded(global);\n\n return {\n contentKey: selectRightColumnContentKey(global),\n chatId,\n threadId,\n currentProfileUserId: global.users.selectedId,\n isChatSelected: Boolean(chatId && areActiveChatsLoaded),\n shouldSkipHistoryAnimations: global.shouldSkipHistoryAnimations,\n };\n },\n)(RightColumn));\n","import React, { FC, memo } from '../../lib/teact/teact';\n\nimport { Bundles } from '../../util/moduleLoader';\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\ninterface OwnProps {\n isOpen: boolean;\n}\n\nconst MediaViewerAsync: FC = ({ isOpen }) => {\n const MediaViewer = useModuleLoader(Bundles.Extra, 'MediaViewer', !isOpen);\n\n return MediaViewer ? : undefined;\n};\n\nexport default memo(MediaViewerAsync);\n","export default function download(url: string, filename: string) {\n const link = document.createElement('a');\n link.href = url;\n link.download = filename;\n try {\n link.click();\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(err); // Suppress redundant \"Blob loading failed\" error popup on IOS\n }\n}\n","import { FC, memo, useEffect } from '../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../lib/teact/teactn';\n\nimport { Thread } from '../../global/types';\nimport { ApiMediaFormat, ApiMessage } from '../../api/types';\n\nimport * as mediaLoader from '../../util/mediaLoader';\nimport download from '../../util/download';\nimport {\n getMessageContentFilename, getMessageMediaHash,\n} from '../../modules/helpers';\n\ntype StateProps = {\n activeDownloads: Record;\n messages: Record;\n threadsById: Record;\n }>;\n};\n\nconst startedDownloads = new Set();\n\nconst DownloadManager: FC = ({\n activeDownloads,\n messages,\n}) => {\n const { cancelMessageMediaDownload } = getDispatch();\n\n useEffect(() => {\n Object.entries(activeDownloads).forEach(([chatId, messageIds]) => {\n const activeMessages = messageIds.map((id) => messages[Number(chatId)].byId[id]);\n activeMessages.forEach((message) => {\n const downloadHash = getMessageMediaHash(message, 'download');\n if (!downloadHash) {\n cancelMessageMediaDownload({ message });\n return;\n }\n\n if (!startedDownloads.has(downloadHash)) {\n const mediaData = mediaLoader.getFromMemory(downloadHash);\n if (mediaData) {\n startedDownloads.delete(downloadHash);\n download(mediaData, getMessageContentFilename(message));\n cancelMessageMediaDownload({ message });\n return;\n }\n\n mediaLoader.fetch(downloadHash, ApiMediaFormat.BlobUrl, true).then((result) => {\n startedDownloads.delete(downloadHash);\n if (result) {\n download(result, getMessageContentFilename(message));\n }\n cancelMessageMediaDownload({ message });\n });\n\n startedDownloads.add(downloadHash);\n }\n });\n });\n }, [\n cancelMessageMediaDownload,\n messages,\n activeDownloads,\n ]);\n\n return undefined;\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const activeDownloads = global.activeDownloads.byChatId;\n const messages = global.messages.byChatId;\n return {\n activeDownloads,\n messages,\n };\n },\n)(DownloadManager));\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst NotificationsAsync: FC = ({ isOpen }) => {\n const Notifications = useModuleLoader(Bundles.Extra, 'Notifications', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return Notifications ? : undefined;\n};\n\nexport default memo(NotificationsAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst DialogsAsync: FC = ({ isOpen }) => {\n const Dialogs = useModuleLoader(Bundles.Extra, 'Dialogs', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return Dialogs ? : undefined;\n};\n\nexport default memo(DialogsAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\nimport { OwnProps } from './ForwardPicker';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst ForwardPickerAsync: FC = (props) => {\n const { isOpen } = props;\n const ForwardPicker = useModuleLoader(Bundles.Extra, 'ForwardPicker', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return ForwardPicker ? : undefined;\n};\n\nexport default memo(ForwardPickerAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport { OwnProps } from './SafeLinkModal';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst SafeLinkModalAsync: FC = (props) => {\n const { url } = props;\n const SafeLinkModal = useModuleLoader(Bundles.Extra, 'SafeLinkModal', !url);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return SafeLinkModal ? : undefined;\n};\n\nexport default memo(SafeLinkModalAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport { OwnProps } from './HistoryCalendar';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst HistoryCalendarAsync: FC = (props) => {\n const { isOpen } = props;\n const HistoryCalendar = useModuleLoader(Bundles.Extra, 'HistoryCalendar', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return HistoryCalendar ? : undefined;\n};\n\nexport default memo(HistoryCalendarAsync);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport useModuleLoader from '../../../hooks/useModuleLoader';\nimport { Bundles } from '../../../util/moduleLoader';\nimport { OwnProps } from './GroupCall';\n\nconst GroupCallAsync: FC = (props) => {\n const { groupCallId } = props;\n const GroupCall = useModuleLoader(Bundles.Calls, 'GroupCall', !groupCallId);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return GroupCall ? : undefined;\n};\n\nexport default memo(GroupCallAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport { Bundles } from '../../util/moduleLoader';\n\ntype OwnProps = {\n groupCallId?: string;\n};\n\nconst ActiveCallHeaderAsync: FC = (props) => {\n const { groupCallId } = props;\n const ActiveCallHeader = useModuleLoader(Bundles.Calls, 'ActiveCallHeader', !groupCallId);\n\n return ActiveCallHeader ? : undefined;\n};\n\nexport default memo(ActiveCallHeaderAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport { Bundles } from '../../util/moduleLoader';\n\ntype OwnProps = {\n isOpen: boolean;\n};\n\nconst CallFallbackConfirmAsync: FC = ({ isOpen }) => {\n const CallFallbackConfirm = useModuleLoader(Bundles.Calls, 'CallFallbackConfirm', !isOpen);\n\n return CallFallbackConfirm ? : undefined;\n};\n\nexport default memo(CallFallbackConfirmAsync);\n","import React, {\n FC, useEffect, memo, useCallback,\n} from '../../lib/teact/teact';\nimport { getDispatch, getGlobal, withGlobal } from '../../lib/teact/teactn';\n\nimport { LangCode } from '../../types';\nimport { ApiMessage } from '../../api/types';\n\nimport '../../modules/actions/all';\nimport {\n BASE_EMOJI_KEYWORD_LANG, DEBUG, INACTIVE_MARKER, PAGE_TITLE,\n} from '../../config';\nimport {\n selectChatMessage,\n selectCountNotMutedUnread,\n selectIsForwardModalOpen,\n selectIsMediaViewerOpen,\n selectIsRightColumnShown,\n selectIsServiceChatReady,\n} from '../../modules/selectors';\nimport { dispatchHeavyAnimationEvent } from '../../hooks/useHeavyAnimationCheck';\nimport buildClassName from '../../util/buildClassName';\nimport { fastRaf } from '../../util/schedulers';\nimport { waitForTransitionEnd } from '../../util/cssAnimationEndListeners';\nimport { processDeepLink } from '../../util/deeplink';\nimport stopEvent from '../../util/stopEvent';\nimport windowSize from '../../util/windowSize';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useBackgroundMode from '../../hooks/useBackgroundMode';\nimport useBeforeUnload from '../../hooks/useBeforeUnload';\nimport useOnChange from '../../hooks/useOnChange';\nimport usePreventPinchZoomGesture from '../../hooks/usePreventPinchZoomGesture';\nimport { LOCATION_HASH } from '../../hooks/useHistoryBack';\n\nimport LeftColumn from '../left/LeftColumn';\nimport MiddleColumn from '../middle/MiddleColumn';\nimport RightColumn from '../right/RightColumn';\nimport MediaViewer from '../mediaViewer/MediaViewer.async';\nimport AudioPlayer from '../middle/AudioPlayer';\nimport DownloadManager from './DownloadManager';\nimport Notifications from './Notifications.async';\nimport Dialogs from './Dialogs.async';\nimport ForwardPicker from './ForwardPicker.async';\nimport SafeLinkModal from './SafeLinkModal.async';\nimport HistoryCalendar from './HistoryCalendar.async';\nimport StickerSetModal from '../common/StickerSetModal.async';\nimport GroupCall from '../calls/group/GroupCall.async';\nimport ActiveCallHeader from '../calls/ActiveCallHeader.async';\nimport CallFallbackConfirm from '../calls/CallFallbackConfirm.async';\n\nimport './Main.scss';\n\ntype StateProps = {\n lastSyncTime?: number;\n isLeftColumnShown: boolean;\n isRightColumnShown: boolean;\n isMediaViewerOpen: boolean;\n isForwardModalOpen: boolean;\n hasNotifications: boolean;\n hasDialogs: boolean;\n audioMessage?: ApiMessage;\n safeLinkModalUrl?: string;\n isHistoryCalendarOpen: boolean;\n shouldSkipHistoryAnimations?: boolean;\n openedStickerSetShortName?: string;\n activeGroupCallId?: string;\n isServiceChatReady?: boolean;\n animationLevel: number;\n language?: LangCode;\n wasTimeFormatSetManually?: boolean;\n isCallFallbackConfirmOpen: boolean;\n addedSetIds?: string[];\n};\n\nconst NOTIFICATION_INTERVAL = 1000;\n\nlet notificationInterval: number | undefined;\n\n// eslint-disable-next-line @typescript-eslint/naming-convention\nlet DEBUG_isLogged = false;\n\nconst Main: FC = ({\n lastSyncTime,\n isLeftColumnShown,\n isRightColumnShown,\n isMediaViewerOpen,\n isForwardModalOpen,\n hasNotifications,\n hasDialogs,\n audioMessage,\n activeGroupCallId,\n safeLinkModalUrl,\n isHistoryCalendarOpen,\n shouldSkipHistoryAnimations,\n openedStickerSetShortName,\n isServiceChatReady,\n animationLevel,\n language,\n wasTimeFormatSetManually,\n isCallFallbackConfirmOpen,\n addedSetIds,\n}) => {\n const {\n loadAnimatedEmojis,\n loadNotificationSettings,\n loadNotificationExceptions,\n updateIsOnline,\n loadTopInlineBots,\n loadEmojiKeywords,\n loadCountryList,\n loadStickerSets,\n loadAddedStickers,\n loadFavoriteStickers,\n ensureTimeFormat,\n openStickerSetShortName,\n checkVersionNotification,\n } = getDispatch();\n const isSynced = Boolean(lastSyncTime);\n\n if (DEBUG && !DEBUG_isLogged) {\n DEBUG_isLogged = true;\n // eslint-disable-next-line no-console\n console.log('>>> RENDER MAIN');\n }\n\n // Initial API calls\n useEffect(() => {\n if (lastSyncTime) {\n updateIsOnline(true);\n loadAnimatedEmojis();\n loadNotificationSettings();\n loadNotificationExceptions();\n loadTopInlineBots();\n loadEmojiKeywords({ language: BASE_EMOJI_KEYWORD_LANG });\n }\n }, [\n lastSyncTime, loadAnimatedEmojis, loadEmojiKeywords, loadNotificationExceptions, loadNotificationSettings,\n loadTopInlineBots, updateIsOnline,\n ]);\n\n // Language-based API calls\n useEffect(() => {\n if (lastSyncTime) {\n if (language !== BASE_EMOJI_KEYWORD_LANG) {\n loadEmojiKeywords({ language });\n }\n\n loadCountryList({ langCode: language });\n }\n }, [language, lastSyncTime, loadCountryList, loadEmojiKeywords]);\n\n // Sticker sets\n useEffect(() => {\n if (isSynced) {\n if (!addedSetIds) {\n loadStickerSets();\n loadFavoriteStickers();\n } else {\n loadAddedStickers();\n }\n }\n }, [isSynced, addedSetIds, loadStickerSets, loadFavoriteStickers, loadAddedStickers]);\n\n // Check version when service chat is ready\n useEffect(() => {\n if (lastSyncTime && isServiceChatReady) {\n checkVersionNotification();\n }\n }, [lastSyncTime, isServiceChatReady, checkVersionNotification]);\n\n // Ensure time format\n useEffect(() => {\n if (lastSyncTime && !wasTimeFormatSetManually) {\n ensureTimeFormat();\n }\n }, [lastSyncTime, wasTimeFormatSetManually, ensureTimeFormat]);\n\n // Parse deep link\n useEffect(() => {\n if (lastSyncTime && LOCATION_HASH.startsWith('#?tgaddr=')) {\n processDeepLink(decodeURIComponent(LOCATION_HASH.substr('#?tgaddr='.length)));\n }\n }, [lastSyncTime]);\n\n // Prevent refresh by accidentally rotating device when listening to a voice chat\n useEffect(() => {\n if (!activeGroupCallId) {\n return undefined;\n }\n\n windowSize.disableRefresh();\n\n return () => {\n windowSize.enableRefresh();\n };\n }, [activeGroupCallId]);\n\n const {\n transitionClassNames: middleColumnTransitionClassNames,\n } = useShowTransition(!isLeftColumnShown, undefined, true, undefined, shouldSkipHistoryAnimations);\n\n const {\n transitionClassNames: rightColumnTransitionClassNames,\n } = useShowTransition(isRightColumnShown, undefined, true, undefined, shouldSkipHistoryAnimations);\n\n const className = buildClassName(\n middleColumnTransitionClassNames.replace(/([\\w-]+)/g, 'middle-column-$1'),\n rightColumnTransitionClassNames.replace(/([\\w-]+)/g, 'right-column-$1'),\n shouldSkipHistoryAnimations && 'history-animation-disabled',\n );\n\n // Dispatch heavy transition event when opening middle column\n useOnChange(([prevIsLeftColumnShown]) => {\n if (prevIsLeftColumnShown === undefined || animationLevel === 0) {\n return;\n }\n\n const dispatchHeavyAnimationEnd = dispatchHeavyAnimationEvent();\n\n waitForTransitionEnd(document.getElementById('MiddleColumn')!, dispatchHeavyAnimationEnd);\n }, [isLeftColumnShown]);\n\n // Dispatch heavy transition event and add body class when opening right column\n useOnChange(([prevIsRightColumnShown]) => {\n if (prevIsRightColumnShown === undefined || animationLevel === 0) {\n return;\n }\n\n fastRaf(() => {\n document.body.classList.add('animating-right-column');\n });\n\n const dispatchHeavyAnimationEnd = dispatchHeavyAnimationEvent();\n\n waitForTransitionEnd(document.getElementById('RightColumn')!, () => {\n dispatchHeavyAnimationEnd();\n\n fastRaf(() => {\n document.body.classList.remove('animating-right-column');\n });\n });\n }, [isRightColumnShown]);\n\n const handleBlur = useCallback(() => {\n updateIsOnline(false);\n\n const initialUnread = selectCountNotMutedUnread(getGlobal());\n let index = 0;\n\n clearInterval(notificationInterval);\n notificationInterval = window.setInterval(() => {\n if (document.title.includes(INACTIVE_MARKER)) {\n updateIcon(false);\n return;\n }\n\n if (index % 2 === 0) {\n const newUnread = selectCountNotMutedUnread(getGlobal()) - initialUnread;\n if (newUnread > 0) {\n updatePageTitle(`${newUnread} notification${newUnread > 1 ? 's' : ''}`);\n updateIcon(true);\n }\n } else {\n updatePageTitle(PAGE_TITLE);\n updateIcon(false);\n }\n\n index++;\n }, NOTIFICATION_INTERVAL);\n }, [updateIsOnline]);\n\n const handleFocus = useCallback(() => {\n updateIsOnline(true);\n\n clearInterval(notificationInterval);\n notificationInterval = undefined;\n\n if (!document.title.includes(INACTIVE_MARKER)) {\n updatePageTitle(PAGE_TITLE);\n }\n\n updateIcon(false);\n }, [updateIsOnline]);\n\n const handleStickerSetModalClose = useCallback(() => {\n openStickerSetShortName({ stickerSetShortName: undefined });\n }, [openStickerSetShortName]);\n\n // Online status and browser tab indicators\n useBackgroundMode(handleBlur, handleFocus);\n useBeforeUnload(handleBlur);\n\n usePreventPinchZoomGesture(isMediaViewerOpen);\n\n return (\n
\n \n \n \n \n \n \n \n {audioMessage && }\n \n \n \n {activeGroupCallId && (\n <>\n \n \n \n )}\n \n \n
\n );\n};\n\nfunction updateIcon(asUnread: boolean) {\n document.querySelectorAll('link[rel=\"icon\"], link[rel=\"alternate icon\"]')\n .forEach((link) => {\n if (asUnread) {\n if (!link.href.includes('favicon-unread')) {\n link.href = link.href.replace('favicon', 'favicon-unread');\n }\n } else {\n link.href = link.href.replace('favicon-unread', 'favicon');\n }\n });\n}\n\n// For some reason setting `document.title` to the same value\n// causes increment of Chrome Dev Tools > Performance Monitor > DOM Nodes counter\nfunction updatePageTitle(nextTitle: string) {\n if (document.title !== nextTitle) {\n document.title = nextTitle;\n }\n}\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { settings: { byKey: { animationLevel, language, wasTimeFormatSetManually } } } = global;\n const { chatId: audioChatId, messageId: audioMessageId } = global.audioPlayer;\n const audioMessage = audioChatId && audioMessageId\n ? selectChatMessage(global, audioChatId, audioMessageId)\n : undefined;\n\n return {\n lastSyncTime: global.lastSyncTime,\n isLeftColumnShown: global.isLeftColumnShown,\n isRightColumnShown: selectIsRightColumnShown(global),\n isMediaViewerOpen: selectIsMediaViewerOpen(global),\n isForwardModalOpen: selectIsForwardModalOpen(global),\n hasNotifications: Boolean(global.notifications.length),\n hasDialogs: Boolean(global.dialogs.length),\n audioMessage,\n safeLinkModalUrl: global.safeLinkModalUrl,\n isHistoryCalendarOpen: Boolean(global.historyCalendarSelectedAt),\n shouldSkipHistoryAnimations: global.shouldSkipHistoryAnimations,\n openedStickerSetShortName: global.openedStickerSetShortName,\n isServiceChatReady: selectIsServiceChatReady(global),\n activeGroupCallId: global.groupCalls.activeGroupCallId,\n animationLevel,\n language,\n wasTimeFormatSetManually,\n isCallFallbackConfirmOpen: Boolean(global.groupCalls.isFallbackConfirmOpen),\n addedSetIds: global.stickers.added.setIds,\n };\n },\n)(Main));\n","import { getDispatch, getGlobal } from '../lib/teact/teactn';\n\nimport { DEBUG } from '../config';\n\nexport { default as Main } from '../components/main/Main';\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH LOAD MAIN BUNDLE');\n}\n\nif (!getGlobal().connectionState) {\n getDispatch().initApi();\n}\n"],"names":["closeLocalTextSearch","global","chatId","threadId","selectCurrentMessageList","updateLocalTextSearch","replaceLocalTextSearchResults","undefined","addReducer","actions","payload","query","chatThreadKey","buildChatThreadKey","currentQuery","localTextSearch","byChatThreadKey","MEMO_EMPTY_ARRAY","mediaType","updateLocalMediaSearchType","id","type","shouldReplaceHistory","currentMessageList","replaceThreadParam","exitMessageSelectMode","messages","contentToBeScheduled","forwardMessages","toChatId","setGlobal","updateCurrentMessageList","isChatInfoShown","openChat","chatCreation","newChatMembersProgress","targetIndexDelta","orderedIds","position","indexOf","nextId","FOCUS_NO_HIGHLIGHT_DURATION","FAST_SMOOTH_MAX_DURATION","ANIMATION_END_DELAY","blurTimeout","scrollOffset","messageId","paramName","chatMessages","selectChatMessages","viewportIds","selectViewportIds","lastOwnEditableMessageId","findLast","Boolean","selectAllowedMessageActions","canEdit","replyingToId","selectReplyingToId","selectIsViewportNewest","chatMessageKeys","Object","keys","newIndex","toString","length","Number","MAIN_THREAD_ID","chat","selectChat","lastMessage","threadInfo","selectThreadInfo","lastMessageId","setReplyingToId","focusMessage","avatarOwnerId","profilePhotoIndex","origin","mediaViewer","volume","playbackRate","isMuted","audioPlayer","selectIsRightColumnShown","pollResults","voters","window","setTimeout","newGlobal","getGlobal","noHighlight","replyStack","selectReplyStack","pop","focusLastMessage","messageListType","groupedId","groupedChatId","replyMessageId","isResizingContainer","ids","selectForwardedMessageIdsByGroupId","shouldSwitchChat","clearTimeout","updateFocusedMessage","updateFocusDirection","FocusDirection","includes","direction","loadViewportMessages","fromChatId","messageIds","groupedMessageIds","selectMessageIdsByGroupId","isModalShown","closeMediaViewer","selectedMessages","openForwardMenu","message","byChatId","activeDownloads","filter","map","canDownload","forEach","downloadMessageMedia","selectCurrentChat","enterMessageSelectMode","childMessageIds","withShift","toggleMessageSelection","shouldShowContextMenuHint","disableContextMenuHint","showNotification","IS_TOUCH_ENV","isPollModalOpen","currentVersion","APP_VERSION","slice","join","serviceNotifications","find","version","SERVICE_NOTIFICATIONS_USER_ID","date","getServerTime","serverTimeOffset","content","text","parseMessageInput","isOutgoing","createServiceNotification","serviceChat","maxId","Math","max","fractionalPart","floor","serviceNotification","isUnread","apiUpdate","seenByModal","globalSearch","updateGlobalSearch","globalResults","localResults","resultsByType","fetchingStatus","chats","recentlyFoundChatIds","newRecentIds","unshift","updateGlobalSearchContent","stickers","search","resultIds","gifs","offsetId","results","updateSelectedUserId","updateUserSearch","globalUserIds","localUserIds","leftColumnWidth","management","isActive","IS_SINGLE_COLUMN_LAYOUT","IS_TABLET_COLUMN_LAYOUT","isLeftColumnShown","messageLists","action","emoji","recentEmojis","newEmojis","e","sticker","recent","hash","newStickers","s","notification","localId","generateIdFor","newNotifications","notifications","existingNotificationIndex","findIndex","n","splice","push","data","hasErrorKey","getReadableErrorText","newDialogs","dialogs","existingErrorIndex","err","url","safeLinkModalUrl","selectedAt","historyCalendarSelectedAt","payment","isPaymentModalOpen","clearPayment","closeInvoice","error","uploadProgressCallbacks","Map","runDebouncedForMarkRead","debounce","cb","async","isOutlying","isBudgetPreload","addOffset","LoadMoreDirection","round","MESSAGE_LIST_SLICE","result","callApi","selectThreadOriginChat","limit","users","threadInfos","localMessages","allMessages","concat","byId","buildCollectionByKey","addChatMessagesById","updateOutlyingIds","updateListedIds","addUsers","addChats","updateThreadInfos","listedIds","selectListedIds","outlyingIds","selectOutlyingIds","areSortedArraysIntersecting","historyIds","newViewportIds","getViewportSlice","safeReplaceViewportIds","sourceIds","index","i","findClosestIndex","indexForDirection","from","to","areSomeLocal","areAllLocal","sendMessage","params","progressCallback","attachment","progress","messageLocalId","has","set","fileUploads","byMessageLocalId","replyingTo","IS_IOS","rafPromise","selectThreadTopMessageId","delete","isRestricted","Promise","resolve","loadWithBudget","selectFocusedMessageId","selectRealLastReadId","replyOriginForId","threadUpdate","MESSAGE_DELETED","replyMessage","selectChatMessage","updateChatMessage","replyToMessageId","loadMessage","isDeleting","updateThreadUnreadFromForwardedMessage","scheduledAt","noWebPage","selectNoWebPage","sendAs","selectSendAs","clearWebPagePreview","value","isSingle","attachments","isGrouped","restParams","entities","commonParams","groupedAttachments","split","MAX_MEDIA_FILES_FOR_ALBUM","firstAttachment","restAttachments","Date","now","selectEditingMessage","setEditingId","get","previousLocalId","cancelApiProgress","draft","replyToMsgId","updateChat","draftDate","localOnly","selectDraft","isUnpin","isOneSide","isSilent","unpinAllMessages","shouldDeleteForAll","editingId","selectEditingId","selectEditingScheduledId","activeChat","reason","description","peer","currentUserId","minId","selectFirstUnreadId","unreadCount","readCount","count","l","countSortedIds","lastReadInboxMessageId","webPagePreview","loadWebPagePreview","options","option","offset","shouldResetVoters","unique","user","offsets","nextOffset","loadPollOptionResults","fromChat","toChat","sort","a","b","realMessages","m","isServiceNotificationMessage","poll","replaceScheduledMessages","loadScheduledHistory","selectScheduledMessage","loadPinnedMessages","seenByUserIds","sendAsId","sendAsChat","selectUser","fullInfo","sendAsIds","updateSponsoredMessage","selectSponsoredMessage","random","randomId","searchThrottled","throttle","searchGifs","updateGifSearch","added","addedStickers","updateStickerSets","sets","loadStickerSets","setIds","addedSetIds","loadStickers","stickerSetId","pause","recentStickers","loadRecentStickers","favorite","favoriteStickers","loadFavoriteStickers","greeting","featured","featuredStickers","loadFeaturedStickers","stickerSetShortName","stickerSetAccessHash","stickerSet","selectStickerSet","accessHash","packs","updateStickerSet","currentEmoji","forEmoji","rebuildStickersForEmoji","replaceAnimatedEmojis","loadAnimatedEmojis","saved","savedGifs","loadSavedGifs","unfave","unfaveSticker","installedDate","language","currentEmojiKeywords","emojiKeywords","isLoading","fromVersion","keywords","searchStickers","setsById","title","searchWords","updateStickersForEmoji","loadStickersForEmoji","openedStickerSetShortName","searchMessagesGlobal","offsetRate","maxDate","minDate","localResult","chatOrUser","GLOBAL_SEARCH_SLICE","totalCount","nextOffsetId","nextRate","currentSearchQuery","selectCurrentGlobalSearchQuery","updateGlobalSearchFetchingStatus","addMessages","updateGlobalSearchResults","localChats","localUsers","globalChats","globalUsers","chatIds","userIds","searchChats","timestampPlusDay","foundIds","currentSearch","selectCurrentTextSearch","topMessageId","MESSAGE_SEARCH_SLICE","newFoundIds","updateLocalTextSearchResults","searchTextMessages","peerId","selectCurrentMediaSearchPeerId","selectCurrentMediaSearch","currentType","currentResults","SHARED_MEDIA_SLICE","updateLocalMediaSearchResults","searchSharedMedia","timestamp","getDispatch","searchMessagesByDate","ManagementProgress","username","updateManagementProgress","updateManagement","isUsernameAvailable","isChatBasicGroup","loadAndReplaceArchivedChats","CHAT_LIST_LOAD_SLICE","archived","withPinned","updateUsers","addUserStatuses","userStatusesById","updateChats","replaceChatListIds","updateChatListSecondaryInfo","loadAndUpdateUsers","contactIds","contactList","updatedUsers","loadTopMessages","afterSyncCallback","DEBUG","console","log","savedUsers","lastLocalServiceMessage","selectLastServiceNotification","savedPrivateChatIds","savedChats","currentChatId","selectedChat","isUserId","selectedChatUser","replaceUserStatuses","replaceChats","draftsById","replyingToById","loadAndReplaceChats","areMessagesLoaded","currentThreadId","draftsByChatId","reduce","acc","newCurrentChatId","currentMessageListInfo","originChannelId","currentMessageListInfoOrigin","resultOrigin","byIdOrigin","listedIdsOrigin","threadsById","Array","prototype","replaceUsers","audioChatId","audioMessageId","closeAudioPlayer","loadAndReplaceMessages","lastSyncTime","sync","afterSync","all","updateAppBadge","selectCountNotMutedUnread","runDebouncedForFetchFullUser","runThrottledForSearch","replaceInlineBotSettings","inlineBotSettings","inlineBots","byUsername","replaceInlineBotsIsLoading","userId","statusesById","topPeers","lastRequestedAt","loadTopUsers","getCompareString","lastName","firstName","collator","Intl","Collator","sortedUsers","compare","isSelf","loadContactList","isUserBot","commonChats","isFullyLoaded","updateUser","updateChatMutedState","phoneNumber","phone","updateContact","deleteContact","profileId","isPrivate","photos","userSearch","updateUserSearchFetchingStatus","searchUsers","pick","runDebouncedForSearch","sendBotCommand","command","button","match","RE_TME_LINK","RE_TG_LINK","openTelegramLink","toggleSafeLinkModal","showDialog","alert","isError","answerCallbackButton","openPollModal","getReceipt","receiptMessageId","getPaymentForm","setInvoiceMessageInfo","openPaymentModal","bot","selectChatBot","removeBlockedContact","topInlineBots","inlineBotData","inlineBot","switchPm","canLoadMore","shouldReplaceSettings","newInlineBotData","currentIds","Set","newResults","help","isGallery","searchInlineBot","queryId","resultId","botId","param","startParam","replaceSettings","hasPassword","updateTwoFaSettings","hint","currentPassword","onSuccess","isSuccess","password","email","waitingEmailCodeLength","code","requestInfo","saveInfo","selectPaymentChatId","selectPaymentMessageId","shouldSave","shippingOptions","setRequestInfoId","updateShippingOptions","setPaymentStep","PaymentStep","validateRequestedInfo","setPaymentForm","step","invoice","shippingAddressRequested","nameRequested","phoneRequested","emailRequested","setReceipt","receipt","publishableKey","selectProviderPublishableKey","credentials","k","buildQueryString","cardNumber","expiryMonth","expiryYear","cvv","zip","country","response","fetch","method","headers","Authorization","json","getStripeError","setStripeCardInfo","sendStripeCredentials","shippingOptionId","saveCredentials","formId","selectPaymentFormId","requestInfoId","selectPaymentRequestId","stripeCredentials","selectStripeCredentials","requestedInfoId","sendPaymentForm","save","runThrottledForUpdateAppBadge","update","noTopChatsRequest","selectIsChatListed","loadTopChats","newProfilePhoto","closeMessageNotifications","listType","selectChatListType","updateChatListIds","isNotJoined","requestChatUpdate","leaveChat","typingStatus","senderId","isFromScheduled","hasUnreadMention","unreadMentionsCount","notifyAboutNewMessage","messageUpdate","channelId","selectCommonBoxChatId","targetChat","folderId","ARCHIVED_FOLDER_ID","orderedPinnedIds","isPinned","newOrderedPinnedIds","MAX_ACTIVE_PINNED_CHATS","listIds","active","pinnedId","updateChatListType","folder","chatFoldersById","chatFolders","newChatFoldersById","newOrderedIds","orderedId","folders","recommended","replacedMembers","addedMember","deletedMemberId","shouldUpdate","members","some","deleteIndex","adminMembers","isOwner","isAdmin","membersCount","photo","formattedText","ANIMATION_DELAY","updateWithLocalMedia","isScheduled","currentMessage","video","document","getMessageContent","blobUrl","thumbnail","isPreloadedGlobally","previewBlobUrl","updateScheduledMessage","updateThreadUnread","selectThreadByMessage","originMessage","updateListedAndViewportIds","firstMessageId","isUnreadChatNotLoaded","isMessageLocal","addViewportId","messagesCount","firstUnreadId","updateChatLastMessage","force","currentLastMessage","findLastMessage","deleteMessages","newLastMessage","threadIdsToUpdate","deleteChatMessages","requestThreadInfoUpdate","chatsIdsToUpdate","commonBoxChatId","shouldForceReply","updateThreadInfo","newMessage","isMessageInCurrentMessageList","delayedGlobal","scheduledIds","selectScheduledIds","selectIsChatWithBot","selectScheduledMessages","deleteChatScheduledMessages","thread","markMessageListRead","currentPinnedIds","selectPinnedIds","newPinnedIds","newTheadInfo","messagesById","loadFullChat","scheduledMessages","deleteScheduledMessages","pollId","pollUpdate","selectChatMessageByPollId","updatedPoll","updatedResults","isChosen","chosenAnswers","chosenAnswer","chosenAnswerIndex","recentVoterIds","totalVoters","newRecentVoterIds","newTotalVoters","targetOption","targetOptionIndex","updatedOption","votersCount","selectIsServiceChatReady","flushStatusUpdatesThrottled","pendingStatusUpdates","statusUpdate","status","targetUser","isBlocked","addBlockedContact","settings","privacy","key","rules","updateNotifySettings","peerType","shouldShowPreviews","addNotifyException","twoFaSettings","call","connectionState","groupCalls","activeGroupCallId","leaveGroupCall","shouldRemove","removeGroupCall","updateGroupCall","omit","participantsCount","groupCallId","participants","participant","updateGroupCallParticipant","useBeforeUnload","callback","useEffect","onBeforeUnload","metaViewport","querySelector","defaultViewportContent","getAttribute","preventEvent","preventDefault","useBrowserOnline","isOnline","setIsOnline","useState","navigator","onLine","handleChange","addEventListener","removeEventListener","ANIMATION_LEVEL_OPTIONS","memo","withGlobal","searchQuery","chatsById","animationLevel","byKey","globalSearchChatId","searchDate","theme","selectTheme","contactsFilter","onSearchQuery","onSelectSettings","onSelectContacts","onSelectArchived","onReset","shouldSkipTransition","openTipsChat","setGlobalSearchDate","setSettingOption","setGlobalSearchChatId","lang","useLang","hasMenu","LeftColumnContent","selectedSearchDate","useMemo","formatDateToString","archivedUnreadChatsCount","values","total","isChatArchived","withOtherVersions","location","hostname","MainButton","onTrigger","isOpen","Button","ripple","size","color","className","onClick","ariaLabel","buildClassName","handleSearchFocus","useCallback","handleSelectSaved","handleDarkModeToggle","stopPropagation","newTheme","shouldUseSystemTheme","switchTheme","ANIMATION_LEVEL_MAX","handleAnimationLevelChange","newLevel","_","body","classList","toggle","isSearchFocused","searchInputPlaceholder","DropdownMenu","trigger","footer","APP_NAME","MenuItem","icon","Switcher","label","checked","noAnimation","toLowerCase","langCode","href","FEEDBACK_URL","setPermanentWebVersion","disableHistoryBack","SearchInput","inputId","parentContainerClassName","focused","placeholder","autoComplete","canClose","onChange","onFocus","PickerSelectedItem","isMinimized","clickArg","chatOrUserId","dir","isRtl","Spinner","allListIds","usersById","orderedFolderIds","activeChatFolder","shouldSkipHistoryAnimations","notifySettings","selectNotifySettings","notifyExceptions","selectNotifyExceptions","foldersDispatch","onScreenSelect","loadChatFolders","setActiveChatFolder","transitionRef","useRef","displayedFolders","folderCountersById","resolverFn","ms","dependencies","runThrottled","useThrottle","setValue","isFrozen","freeze","unfreeze","useFlag","useHeavyAnimationCheck","useOnChange","counters","unreadDialogsCount","hasActiveDialogs","getFolderUnreadDialogs","badgeCount","isBadgeActive","useThrottledMemo","folderTabs","ALL_FOLDER_ID","handleSwitchTab","forceOnHeavyAnimation","current","captureEvents","selectorToPreventScroll","onSwipe","SwipeDirection","min","isNotInAllTabRef","captureEscKeyListener","useHistoryBack","handleKeyDown","ctrlKey","shiftKey","startsWith","digit","shouldRender","shouldRenderPlaceholder","transitionClassNames","useShowTransition","renderCurrentTab","activeFolder","ChatList","folderType","TabList","tabs","activeTab","onSwitchTab","Transition","ref","name","activeKey","renderCount","props","LeftSearch","useModuleLoader","Bundles","Loading","ContactList","closeTimeout","isShown","onNewPrivateChat","onNewChannel","onNewGroup","isMenuOpen","setIsMenuOpen","fabClassName","handleMouseEnter","handleMouseLeave","onMouseEnter","onMouseLeave","tabIndex","Menu","positionX","positionY","autoClose","onClose","TRANSITION_RENDER_COUNT","onContentChange","isNewChatButtonShown","setIsNewChatButtonShown","isConnecting","isMouseInside","handleSelectSettings","handleSelectContacts","handleSelectNewChannel","handleSelectNewGroup","handleSelectArchived","autoCloseTimeout","shouldRenderUpdateButton","updateButtonClassNames","handleUpdateClick","isAppOutdated","markIsAppOutdated","timeout","reload","useAppOutdatedCheck","ShowTransition","isCustom","shouldCleanup","cleanupExceptionKey","fluid","pill","Settings","NewChat","ArchivedChats","ContentType","RENDER_COUNT","setGlobalSearchQuery","resetChatCreation","loadPasswordInfo","clearTwoFaError","setLeftColumnWidth","resetLeftColumnWidth","resizeRef","setContent","settingsScreen","setSettingsScreen","SettingsScreens","setContactsFilter","foldersState","useFoldersReducer","lastResetTime","setLastResetTime","contentType","Main","Archived","NewChannel","NewGroup","handleReset","forceReturnToChatList","pickerSearchInput","getElementById","blur","handleSearchQuery","IS_MAC_OS","metaKey","getKeyFromEvent","initResize","resetResize","handleMouseUp","elementRef","onResize","initialWidth","markIsActive","unmarkIsActive","initialMouseX","setInitialMouseX","initialElementWidth","setInitialElementWidth","style","width","remove","handleMouseMove","event","newWidth","ceil","clientX","stopDrag","offsetWidth","add","useResize","handleSettingsScreenSelect","screen","LAYERS_ANIMATION_NAME","currentScreen","isChannel","onMouseDown","onMouseUp","onDoubleClick","setSize","windowSize","handleResize","MAX_MESSAGES_LIST_WIDTH","HeaderMenuContainer","isChatChannel","selectIsInSelectMode","noMenu","isChatWithSelf","selectIsChatWithSelf","isMainThread","isDiscussionThread","isRightColumnShown","canRestartBot","selectIsUserBlocked","canStartBot","selectIsChatBotNotStarted","canSubscribe","isChatSuperGroup","canSearch","canCall","ARE_CALLS_SUPPORTED","canMute","canLeave","canEnterVoiceChat","isCallActive","canCreateVoiceChat","adminRights","manageCall","isCreator","canExpandActions","joinChannel","openLocalTextSearch","restartBot","openCallFallbackConfirm","menuButtonRef","menuPosition","setMenuPosition","handleHeaderMenuOpen","rect","getBoundingClientRect","x","right","y","bottom","handleHeaderMenuClose","handleHeaderMenuHide","handleSubscribeClick","handleStartBot","handleRestartBot","handleSearchClick","focus","searchInput","IS_PWA","disabled","anchor","withExtraActions","onSubscribeChannel","onSearchClick","onCloseAnimationEnd","useWebpThumbnail","thumbDataUri","getMessageMediaThumbDataUri","shouldDecodeThumbnail","isWebpSupported","thumbnailDecoded","setThumbnailDecoded","EMPTY_IMAGE_DATA_URI","useLayoutEffect","webpToPngBase64","then","catch","drawRect","height","radius","containerRef","markupParams","reverseIndex","barHeight","getBarHeight","markHeight","getMarkHeight","trackHeight","getTrackHeight","clipPathId","clipPath","d","getClipPath","markTranslateY","getMarkTranslateY","trackTranslateY","getTrackTranslateY","calculateMarkup","firstChild","firstElementChild","currentElement","transform","svg","div","defs","innerHTML","customTitle","onUnpinMessage","onAllPinnedClick","mediaThumbnail","mediaBlobUrl","useMedia","getMessageMediaHash","getMessageSummaryText","isUnpinDialogOpen","openUnpinDialog","closeUnpinDialog","handleUnpinMessage","ConfirmDialog","confirmLabel","confirmHandler","getPictogramDimensions","src","alt","renderPictogram","renderText","RippleEffect","scaleImage","image","ratio","outputType","Blob","URL","createObjectURL","img","Image","onload","scale","blob","finally","revokeObjectURL","steppedScale","bitmap","createImageBitmap","resizeWidth","resizeHeight","resizeQuality","Error","res","canvas","createElement","ctx","getContext","transferFromImageBitmap","drawImage","toBlob","oc","octx","mul","cur","LOGO_DIMENSIONS","MINIMAL_SIZE","sender","audio","voice","fileName","artist","performer","getSenderTitle","getTranslation","album","getChatTitle","audioCoverHash","getAudioHasCover","avatarHash","getChatAvatarHash","media","thumbnailSizes","AVATAR_FULL_DIMENSIONS","getCoverSize","fn","deps","defaultValue","setIsLoading","setError","setResult","wasCancelled","telegramLogoPath","resizeImage","makeGoodArtwork","useAsync","buildMediaMetadata","artwork","selectSender","noUi","setAudioPlayerVolume","setAudioPlayerPlaybackRate","setAudioPlayerMuted","isVoice","senderName","mediaData","mediaLoader","mediaMetadata","useMessageMediaMetadata","playPause","stop","isPlaying","requestNextTrack","requestPreviousTrack","isFirst","isLast","setVolume","toggleMuted","setPlaybackRate","useAudioPlayer","makeTrackId","getMediaDuration","isVoicePlaying","handleClick","handleClose","clearMediaSession","handleVolumeChange","handleVolumeClick","handlePlaybackClick","volumeIcon","renderAudio","subtitle","renderVoice","withClickPropagation","RangeSlider","groupCall","selectChatGroupCall","isLoaded","isCallNotEmpty","hasPinnedOffset","joinGroupCall","subscribeToGroupCallUpdates","handleJoinGroupCall","fetchedParticipants","isUser","subscribed","p","Avatar","audioMessage","pinnedIds","state","isSelectModeActive","isChatWithBot","currentTransitionKey","assign","pinnedMessageId","topMessageSender","selectForwardedSender","pinnedMessageIds","canUnpin","firstPinnedMessage","isReady","openChatWithInfo","pinMessage","openPreviousChat","toggleLeftColumn","isBackButtonActive","pinnedMessageIndex","setPinnedMessageIndex","isArray","pinnedMessage","pinnedMessagesCount","chatTitleLength","topMessageTitle","useEnsureMessage","windowWidth","useWindowSize","isLeftColumnHideable","MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN","shouldShowCloseButton","componentRef","shouldAnimateTools","handleHeaderClick","handlePinnedMessageClick","cycleRestrict","handleAllPinnedClick","setBackButtonActive","handleBackClick","messageInput","EDITABLE_INPUT_ID","canToolsCollideWithChatInfo","SAFE_SCREEN_WIDTH_FOR_CHAT_INFO","MOBILE_SCREEN_MAX_WIDTH","shouldUseStackedToolsClass","MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN","SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN","shouldRenderAudioPlayer","audioPlayerClassNames","renderingAudioMessage","useCurrentOrPrev","shouldRenderPinnedMessage","pinnedMessageClassNames","renderingPinnedMessage","renderingPinnedMessagesCount","renderingCanUnpin","renderingPinnedMessageTitle","canRevealTools","componentEl","renderInfo","renderBackButton","PrivateChatInfo","withFullInfo","withMediaViewer","withUpdatingStatus","noRtl","GroupChatInfo","asClose","withUnreadCount","formatIntegerCompact","isAudioPlayerRendered","Infinity","getMessageKey","isAlbum","messageOrAlbum","groupMessages","currentAlbum","currentSenderGroup","currentDateGroup","originalDate","datetime","getDayStart","senderGroups","dateGroups","isInAlbum","mainMessage","albumId","nextMessage","nextMessageDayStartsAt","isActionMessage","forwardInfo","senderUserId","hiddenUserName","inlineButtons","INTERSECTION_THROTTLE_FOR_MEDIA","IS_ANDROID","INTERSECTION_MARGIN_FOR_MEDIA","isEmojiOnlyMessage","customShape","getMinMediaWidth","hasText","hasCommentButton","calculateMediaDimensions","noAvatars","isOwn","isOwnMessage","isForwarded","isForwardedMessage","getMessagePhoto","getMessageWebPagePhoto","getMessageVideo","isWebPagePhoto","calculateInlineImageDimensions","calculateVideoDimensions","minMediaWidth","getMessageText","stretchFactor","finalWidth","finalHeight","isSmall","accumulate","list","initValue","accumulator","item","clamp","num","low","high","calculateContainerSize","layout","styles","dimensions","sides","calculateAlbumLayout","ratios","proportions","getProportions","averageRatio","getAverageRatio","albumCount","forceCalc","maxWidth","getAvailableWidth","REM","minWidth","maxHeight","spacing","originalRatios","cropRatios","attempts","pushAttempt","lineCounts","heights","currentCount","attemptCount","sum","multiHeight","first","second","third","fourth","optimalAttempt","optimalDiff","lineCount","totalHeight","bad1","bad2","line","diff","abs","optimalCounts","optimalHeights","rowCount","row","colCount","lineHeight","col","layoutWithComplexLayouter","AlbumRectPart","layoutTwoTopBottom","layoutTwoLeftRightEqual","minimalWidth","secondWidth","firstWidth","layoutTwoLeftRight","layoutTwo","firstHeight","thirdHeight","secondHeight","rightWidth","leftWidth","layoutThreeLeftAndOther","layoutThreeTopAndOther","layoutThree","w","h0","h","w0","w2","w1","h1","layoutFourTopAndOther","h2","layoutFourLeftAndOther","layoutFour","containerStyle","element","calculateAuthorWidth","font","whiteSpace","left","opacity","appendChild","useFocusMessage","isFocused","focusDirection","noFocusHighlight","messagesContainer","closest","fastSmoothScroll","ContextMenuContainer","targetUserIds","targetChatId","targetMessageId","targetMessage","selectIsMessageFocused","focusedMessage","observeIntersection","isEmbedded","appearanceOrder","isLastInList","useOnIntersect","noAppearanceAnimation","markShown","targetUsers","renderActionMessageText","asPlain","isContextMenuOpen","contextMenuPosition","handleBeforeContextMenu","handleContextMenu","handleContextMenuClose","handleContextMenuHide","useContextMenuHandlers","isContextMenuShown","preventMessageInputBlur","onContextMenu","customText","isProtected","isIntersecting","useIsIntersecting","pictogramId","isRoundVideo","getMessageRoundVideo","senderTitle","draggable","outgoingStatus","signature","isActivated","markActivated","createDateTime","formatDateTimeToString","editDateTime","isEdited","editDate","forwardedDateTime","replace","views","formatTime","MessageOutgoingStatus","observeIntersectionForPlaying","shouldLoop","isModalOpen","openModal","closeModal","isAnimated","isMemojiSticker","MEMOJI_STICKER_ID","shouldLoad","shouldPlay","mediaHash","getMessageMediaFormat","isMediaLoaded","isAnimationLoaded","markAnimationLoaded","isMediaReady","useMediaTransition","getStickerDimensions","thumbClassName","stickerClassName","AnimatedSticker","animationData","play","noLoop","onLoad","fromSticker","useBlurredMediaThumbRef","fullMediaData","useCanvasBlur","IS_CANVAS_FILTER_SUPPORTED","SELECTED_APPENDIX_COLORS","dark","outgoing","incoming","light","canAutoLoad","isInSelectMode","isSelected","uploadProgress","nonInteractive","shouldAffectAppendix","isDownloading","onCancelUpload","localBlobUrl","isLoadAllowed","setIsLoadAllowed","loadProgress","useMediaWithLoadProgress","thumbRef","downloadProgress","isUploading","isTransferring","transferProgress","getMediaTransferState","wasLoadDisabled","usePrevious","shouldRenderSpinner","spinnerClassNames","shouldRenderDownloadButton","downloadButtonClassNames","isAllowed","contentEl","inSelectMode","getImageData","getAppendixColorFromImage","getCustomAppendixBg","appendixBg","setProperty","setAttribute","ProgressSpinner","useVideoAutoPause","playerRef","canPlay","wasPlaying","paused","canPlayRef","freezePlaying","unfreezePlaying","contains","safePlay","unfreezePlayingOnRaf","fastRaf","useBackgroundMode","canAutoPlay","videoRef","getMessageWebPageVideo","isPlayAllowed","setIsPlayAllowed","previewClassNames","isInline","ApiMediaFormat","isBuffered","bufferingHandlers","useBuffering","shouldRenderPlayButton","playButtonClassNames","playProgress","setPlayProgress","handleTimeUpdate","currentTarget","currentTime","duration","useVideoCleanup","cancelMessageMediaDownload","autoPlay","muted","loop","playsInline","onTimeUpdate","isGif","formatMediaDuration","contact","countryList","phoneCodes","phoneCodeList","openUserInfo","formatPhoneNumberWithCode","getPercentage","toFixed","answer","voteResults","maxVotersCount","correctResults","shouldAnimate","r","correctAnswer","showIcon","answerPercent","finalPercent","setFinalPercent","lineRef","lineWidth","isAnimationDoesNotStart","lineEl","svgEl","lineStyle","onSendVote","openPollResults","summary","isSubmitting","setIsSubmitting","chosenOptions","setChosenOptions","isSolutionShown","setIsSolutionShown","wasSubmitted","setWasSubmitted","closePeriod","setClosePeriod","closed","closeDate","countdownRef","hasVoted","canVote","canViewResult","isPublic","isMultiple","multipleChoice","answers","isCorrect","hidden","quiz","countdownEl","circumference","PI","lastElementChild","timerEl","strokeDashOffset","textContent","timer","recentVoters","handleRadioChange","handleCheckboxChange","handleVoteClick","handleViewResultsClick","handleSolutionShow","handleSolutionHide","solution","Notification","renderTextWithEntities","solutionEntities","onDismiss","containerId","question","getPollTypeString","CheckboxGroup","loadingOptions","RadioGroup","loadingOption","isQuiz","getReadableVotersCount","isText","inPreview","onMediaClick","onCancelMediaTransfer","webPage","getMessageWebPage","isSquarePhoto","handleMediaClick","siteName","displayUrl","isMediaInteractive","truncatedDescription","trimText","SafeLink","getMessageInvoice","amount","currency","isTest","photoUrl","formatCurrency","withSelectControl","WrappedComponent","ownProps","selectIsMessageSelected","handleMessageSelect","newProps","PhotoWithSelect","Photo","VideoWithSelect","Video","activeDownloadIds","selectActiveDownloadIds","uploadsById","hasCustomAppendix","albumLayout","cancelSendingMessage","mediaCount","handleCancelUpload","containerWidth","containerHeight","fileUpload","selectCanAutoLoadMedia","selectCanAutoPlayMedia","currentOnRelease","playingProgressRef","shouldSpinnerRender","setIsActivated","setProgress","svgCenter","ROUND_VIDEO_DIMENSIONS_PX","playerEl","playingProgressEl","stopPlaying","capturePlaying","onRelease","stopCurrentAudio","videoClassName","onEnded","recentReplierIds","recentRepliers","hasUnread","GROUP_MESSAGE_HOVER_ATTRIBUTE","APPENDIX_OWN","__html","APPENDIX_NOT_OWN","handleDocumentGroupMouseEnter","lastGroupElement","getLastElementInDocumentGroup","handleDocumentGroupMouseLeave","removeAttribute","nextElementSibling","withSenderName","withAvatar","viaBotId","replyToChatId","isRepliesChat","isChatWithRepliesBot","chatUsername","forceSenderName","isAnonymousOwnMessage","canShowSender","originSender","botSender","threadTopMessageId","isThreadTop","shouldHideReply","replyMessageSender","selectUploadProgress","isForwarding","highlight","singleEmoji","getMessageSingleEmoji","every","canReply","selectIsDownloading","actualThreadInfo","selectIsMessageProtected","isSingleEmoji","animatedEmoji","selectAnimatedEmoji","isGroupSelected","selectIsDocumentGroupSelected","isPinnedList","canAutoLoadMedia","canAutoPlayMedia","autoLoadFileMaxSizeMb","shouldLoopStickers","selectShouldLoopStickers","selectOutgoingStatus","observeIntersectionForBottom","observeIntersectionForMedia","observeIntersectionForAnimatedStickers","noComments","isFirstInGroup","isLastInGroup","isFirstInDocumentGroup","isLastInDocumentGroup","clickInlineButton","bottomMarkerRef","isLocal","hasReply","isReplyMessage","hasThread","getMessageCustomShape","asForwarded","isLinkedChannelPost","isInDocumentGroup","textParts","renderMessageText","adminTitle","metaSafeAuthorWidth","canShowActionButton","canForward","canFocus","isChannelPost","fromMessageId","avatarPeer","senderPeer","selectMessage","handleMouseDown","handleDoubleClick","handleContentDoubleClick","isSwiped","markSwiped","unmarkSwiped","startedAt","target","stopEvent","matches","useOuterHandlers","handleAvatarClick","handleSenderClick","handleViaBotClick","handleReplyClick","handleAudioPlay","handleAlbumMediaClick","handleMetaClick","handleReadMedia","handleVoteSend","handleGroupForward","handleForward","handleFocus","handleFocusForwarded","handleDocumentGroupSelectAll","openMediaViewer","openAudioPlayer","markMessagesRead","sendPollVote","focusMessageInComments","replyToTopMessageId","channelPostId","MediaViewerOrigin","albumMessageId","selectWithGroupedId","useInnerHandlers","containerClassName","contentClassName","hasComments","hasActionButton","classNames","isMedia","isMediaWithNoText","isViaBot","isRound","buildContentClassName","withCommentButton","withAppendix","calculatedWidth","noMediaCorners","extraPadding","isAvatarPeerUser","avatarUser","avatarChat","hiddenName","renderAvatar","shouldInlineMeta","textContentClass","senderColor","getUserColorKey","renderSenderName","AnimatedEmoji","forceLoadPreview","Audio","AudioOrigin","isSelectable","onPlay","onReadMedia","Document","renderContent","dangerouslySetInnerHTML","isBot","channel","viewSponsoredMessage","openChatByInvite","startBot","contentRef","shouldObserve","observe","useIntersectionObserver","rootRef","debounceMs","threshold","getUserFullName","chatInviteTitle","chatInviteHash","messageGroups","isViewportNewest","withUsers","anchorIdRef","memoUnreadDividerBeforeIdRef","memoFirstUnreadIdRef","isScrollingRef","isScrollPatchNeededRef","hasLinkedChat","isSchedule","onFabToggle","onNotchToggle","openHistoryCalendar","observeIntersectionForReading","throttleMs","margin","freezeForReading","unfreezeForReading","entries","mentionIds","entry","dataset","useMessageObservers","backwardsTriggerRef","forwardsTriggerRef","fabTriggerRef","loadMoreBackwards","loadMoreForwards","toggleScrollTools","offsetHeight","scrollHeight","scrollTop","scrollBottom","isAtBottom","MESSAGE_LIST_SENSITIVE_AREA","LOCAL_MESSAGE_ID_BASE","triggerEntry","IS_SCROLL_PATCH_NEEDED","observeIntersectionForFab","freezeForFab","unfreezeForFab","FAB_THRESHOLD","observeIntersectionForNotch","freezeForNotch","unfreezeForNotch","useScrollHooks","unreadDivider","messageCountToAnimate","messageGroup","flatten","appearanceIndex","dateGroup","dateGroupIndex","dateGroupsArray","senderGroup","senderGroupIndex","senderGroupsArray","compact","currentDocumentGroupId","messageIndex","isMessageAlbum","documentGroupId","nextDocumentGroupId","originalId","getMessageOriginalId","teactFastList","SCHEDULED_WHEN_ONLINE","formatHumanDate","dividend","getUserIdDividend","lastUnreadMessageId","loadGreetingStickers","handleStickerSelect","selectedSticker","StickerButton","isGroupChatJustCreated","renderScheduled","renderSavedMessages","renderGroup","runDebouncedForScroll","selectCurrentMessageIds","restrictionReason","focusingId","withLastMessageWhenPreloading","chatBot","botDescription","isChatLoaded","isChannelChat","isGroupChat","isChatGroup","threadFirstMessageId","selectFirstMessageId","linkedChatId","hasTools","canPost","withBottomShift","setScrollOffset","loadSponsoredMessages","scrollOffsetRef","selectScrollOffset","anchorTopRef","listItemElementsRef","memoFocusingIdRef","isScrollTopJustUpdatedRef","shouldAnimateAppearanceRef","setContainerHeight","onTickEnd","listedMessages","orderBy","loadMoreAround","isScrolled","updateStickyDates","markIsScrolled","runDebounced","useDebounce","container","currentStuck","stuckDateEl","allElements","querySelectorAll","containerTop","el","offsetTop","top","findStuckDate","useStickyDates","handleScroll","parentElement","observer","ResizeObserver","offsetParent","contentRect","disconnect","windowHeight","normalHeight","String","clientHeight","preservedItemElements","useLayoutEffectWithPrevDeps","prevMessageIds","prevIsViewportNewest","prevContainerHeight","hasLastMessageChanged","hasViewportShifted","wasMessageAdded","isAlreadyFocusing","shouldForceScroll","lastItemElement","bottomOffset","newScrollTop","isResized","isAnimatingScroll","patchChromiumScroll","resetScroll","useEffectWithPrevDeps","prevIsSelectModeActive","dispatchHeavyAnimationEvent","shouldRenderGreeting","onScroll","withExtraShift","focusNextReply","messageElements","lastMessageElement","MAX_QUICK_IMG_SIZE","FILE_EXT_REGEX","buildAttachment","filename","isQuick","mimeType","quick","SUPPORTED_IMAGE_CONTENT_TYPES","preloadImage","resizedUrl","fetchBlob","SUPPORTED_VIDEO_CONTENT_TYPES","videoWidth","videoHeight","preloadVideo","createPosterForVideo","resetInput","applyIosAutoCapitalizationFix","inputEl","POLYFILL_OPTIONS","encoderPath","reuseWorker","BLOB_PARAMS","opusRecorderPromise","OpusRecorder","mediaRecorder","init","default","start","analyzerCallback","startMediaRecorder","pausedAt","chunks","waveform","ondataavailable","typedArray","releaseAnalyzer","recorder","source","sourceNode","analyser","context","createAnalyser","fftSize","connect","dataLength","frequencyBinCount","dataArray","Uint8Array","isDestroyed","tick","getByteFrequencyData","requestAnimationFrame","subscribeToAnalyzer","reject","onstop","onerror","delayStop","CLIPBOARD_ACCEPTED_TYPES","getMessageTextAsHtml","tempEl","INLINE_BOT_QUERY_REGEXP","HAS_NEW_LINE","RE_COMMAND","DeleteMessageModal","openTimeout","isFirstTimeActivation","onActivate","buttonProps","AttachMenu","SymbolMenu","InlineBotTooltip","MentionTooltip","CustomSend","StickerTooltip","BotCommandTooltip","useMouseInside","isKeyboardSingleUse","forceOpen","markForceOpen","unmarkForceOpen","keyboardButtons","forwardMessageIds","forwardedMessagesCount","exitForwardMode","canAnimate","useAsyncRendering","clearEmbedded","handleMessageClick","faded","AttachmentModal","BotCommandMenu","PollModal","DropArea","RE_LINK","RegExp","RE_LINK_TEMPLATE","messageText","toggleMessageWebPage","link","linkEntity","ApiMessageEntityTypes","textMatch","renderingWebPage","webPageWithoutPhoto","messageStub","CalendarModal","SendAsMenu","MainButtonState","chatUser","selectChatUser","REPLIES_USER_ID","messageWithActualBotKeyboard","selectNewestMessageWithBotKeyboardButtons","shouldSuggestStickers","baseEmojiKeywords","BASE_EMOJI_KEYWORD_LANG","botKeyboardMessageId","keyboardMessage","sendAsUser","editingMessage","canScheduleUntilOnline","selectUserStatus","wasOnline","withScheduledButton","shouldSchedule","botKeyboardPlaceholder","keyboardPlaceholder","stickersForEmoji","groupChatMembers","topInlineBotIds","isInlineBotLoading","chatBotCommands","botCommands","dropAreaState","onDropHide","clearDraft","setStickerSearchQuery","setGifSearchQuery","closePollModal","addRecentEmoji","sendInlineBotResult","loadSendAs","appendixRef","html","setHtml","lastMessageSendTimeSeconds","prevDropAreaState","isCalendarOpen","openCalendar","closeCalendar","scheduledMessageArgs","setScheduledMessageArgs","sendMessageAction","useSendMessageAction","htmlRef","shouldAnimateSendAsButtonRef","prevChatId","prevSendAsIds","setAttachments","isBotKeyboardOpen","openBotKeyboard","closeBotKeyboard","isBotCommandMenuOpen","openBotCommandMenu","closeBotCommandMenu","isAttachMenuOpen","openAttachMenu","closeAttachMenu","isSymbolMenuOpen","openSymbolMenu","closeSymbolMenu","isSendAsMenuOpen","openSendAsMenu","closeSendAsMenu","isDeleteModalOpen","openDeleteModal","closeDeleteModal","isSymbolMenuLoaded","onSymbolMenuLoadingComplete","isHoverDisabled","disableHover","enableHover","startRecordingVoice","stopRecordingVoice","pauseRecordingVoice","activeVoiceRecording","currentRecordTime","recordButtonRef","mainButtonRef","startRecordTimeRef","setActiveVoiceRecording","setCurrentRecordTime","IS_SAFARI","IS_VOICE_RECORDING_SUPPORTED","voiceRecording","tickVolume","boxShadow","useVoiceRecording","delay","noFirst","savedCallback","setInterval","clearInterval","useInterval","SEND_MESSAGE_ACTION_INTERVAL","mainButtonState","Edit","Send","Record","canShowCustomSendMenu","isMentionTooltipOpen","closeMentionTooltip","insertMention","mentionFilteredUsers","useMentionTooltip","isInlineBotTooltipOpen","inlineBotId","isInlineBotTooltipGallery","inlineBotSwitchPm","inlineBotResults","closeTooltip","closeInlineBotTooltip","inlineBotHelp","loadMore","loadMoreForInlineBot","markIsOpen","unmarkIsOpen","innerText","getPlainText","queryInlineBot","resetInlineBot","canShowHelp","parseStartWithUsernameString","usernameLowered","prevQuery","prevUsername","useInlineBotTooltip","isBotCommandTooltipOpen","close","closeBotCommandTooltip","filteredBotCommands","botTooltipCommands","setFilteredBotCommands","getFilteredCommands","nextFilteredBotCommands","prepareForRegExp","substr","useBotCommandTooltip","isCustomSendMenuOpen","allowedAttachmentOptions","getAllowedAttachmentOptions","isChatAdmin","slowMode","getChatSlowModeOptions","isStickerTooltipOpen","closeStickerTooltip","isDisabled","cleanHtml","trim","clearStickersForEmoji","IS_EMOJI_SUPPORTED","parseEmojiOnlyString","hasStickers","useStickerTooltip","canSendStickers","isEmojiTooltipOpen","closeEmojiTooltip","filteredEmojis","insertEmoji","useEmojiTooltip","insertTextAndUpdateCursor","selection","getSelection","newHtml","rangeCount","selectionRange","getRangeAt","isSelectionInsideInput","range","deleteContents","fragment","createContextualFragment","lastInsertedNode","lastChild","insertNode","setStartAfter","setEndAfter","collapse","removeAllRanges","addRange","insertHtmlInSelection","dispatchEvent","Event","bubbles","focusEditableElement","removeSymbol","execCommand","tempInput","contentEditable","textLength","createRange","setStart","setEnd","removeChild","deleteLastCharacterOutsideSelection","resetComposer","shouldPreserveInput","stopRecordingVoiceRef","handleEditComplete","editedMessage","editMessage","hasMessageMedia","useEditing","saveDraft","updateDraft","draftChatId","draftThreadId","runDebouncedForSaveDraft","DRAFT_DEBOUNCE","prevThreadId","prevHtml","handleBlur","useDraft","handlePaste","clipboardData","input","activeElement","EDITABLE_INPUT_MODAL_ID","items","kind","file","getAsFile","pastedText","getData","substring","useClipboardPaste","handleFileSelect","files","handleAppendFiles","handleClearAttachment","handleSend","currentAttachments","record","maxLength","extraLength","textParams","nowSeconds","secondsSinceLastMessage","nextSendDateNotReached","nextSendDate","seconds","secondsRemaining","isSlowMode","handleActivateBotCommandMenu","handleActivateSymbolMenu","handleGifSelect","gif","handleInlineBotSelect","inlineResult","handleBotCommandSelect","handlePollSend","handleSilentSend","handleMessageSchedule","isWhenOnline","restArgs","getTime","handleMessageScheduleUntilOnline","handleCloseCalendar","handleSearchOpen","handleSymbolMenuOpen","handleSendAsMenuOpen","handleAllScheduledClick","mainButtonHandler","areVoiceMessagesNotAllowed","canAttachMedia","prevEditedMessage","renderedEditedMessage","scheduledDefaultDate","setSeconds","setMilliseconds","scheduledMaxDate","setFullYear","getFullYear","sendButtonAriaLabel","symbolMenuButtonClassName","onSend","Portal","DropAreaState","withQuick","onHide","onFileSelect","caption","onCaptionUpdate","onFileAppend","onClear","selectedSendAsId","onInsertUserName","filteredUsers","onSelectResult","withUsername","canAttachEmbedLinks","MessageInput","forcedPlaceholder","canAutoFocus","shouldSuppressFocus","shouldSuppressTextFormatter","onUpdate","onSuppressedFocus","formatVoiceRecordDuration","onStickerSelect","emojis","onEmojiSelect","onPollCreate","onGifSelect","onRemoveSymbol","onSearchOpen","onSilentSend","onScheduleSend","withTimePicker","maxAt","getDayStartAt","isFutureMode","secondButtonLabel","onSubmit","onSecondButtonClick","MobileSearch","MessageSelectToolbar","UnpinAllMessagesModal","PaymentModal","ReceiptModal","SeenByModal","CLOSE_ANIMATION_DURATION","isImage","isBlurred","isBackgroundBlurred","background","customBackground","backgroundColor","patternColor","themes","isMobileSearchActive","isReceiptModalOpen","isSeenByModalOpen","getCanPostInChat","isBotNotStarted","isPinnedMessageList","isScheduledMessageList","currentUserBannedRights","defaultBannedRights","hasPinnedOrAudioPlayer","loadUser","closePaymentModal","clearReceipt","setDropAreaState","isFabShown","setIsFabShown","isNotchShown","setIsNotchShown","isUnpinModalOpen","setIsUnpinModalOpen","renderingChatId","usePrevDuringAnimation","renderingThreadId","renderingMessageListType","renderingCanSubscribe","renderingCanStartBot","renderingCanRestartBot","renderingCanPost","renderingHasTools","renderingIsFabShown","renderingIsChannel","prevTransitionKey","handleOpenEnd","handleSlideStop","setIsReady","forceUpdate","useForceUpdate","willSwitchMessageList","ANIMATION_LEVEL_MIN","propertyName","useIsReady","visualViewport","documentElement","handleDragEnter","dataTransfer","shouldDrawQuick","handleHideDropArea","handleOpenUnpinModal","closeUnpinModal","handleUnpinAllMessages","handleTabletFocus","customBackgroundValue","settingValue","cacheApi","CUSTOM_BG_CACHE_NAME","Type","useCustomBackground","MASK_IMAGE_DISABLED","messagingDisabledClassName","messageSendingRestrictionReason","getMessageSendingRestrictionReason","composerHiddenScale","toolbarHiddenScale","composerTranslateX","toolbarTranslateX","unpinHiddenScale","toolbarForUnpinHiddenScale","sidePadding","messageListWidth","rightColumnWidth","getMessageListWidth","sendButtonWidth","composerWidth","toolbarWidth","calculateMiddleFooterTransforms","footerClassName","forceSyncOnIOs","createMessageHash","isMessagingDisabled","withMessageListBottomShift","onTransitionEnd","DARK_THEME_BG_COLOR","LIGHT_THEME_BG_COLOR","onDragEnter","onStop","onUnpin","HeaderContent","isProfile","isManagement","messageSearchQuery","stickerSearchQuery","selectCurrentStickerSearch","gifSearchQuery","selectCurrentGifSearch","canAddContact","getCanAddContact","canManage","isColumnOpen","isSearch","isStickerSearch","isGifSearch","isPollResults","isAddingChatMembers","profileState","managementScreen","shouldSkipAnimation","setLocalTextSearchQuery","searchTextMessagesLocal","toggleManagement","addContact","backButtonRef","handleMessageSearchQueryChange","handleStickerSearchQueryChange","handleGifSearchQueryChange","handleAddContact","setShouldSkipTransition","contentKey","ProfileState","Profile","SharedMedia","MemberList","Search","PollResults","StickerSearch","GifSearch","AddingMembers","ManagementScreens","ManageInitial","ManageChatPrivacyType","ManageDiscussion","ManageChannelSubscribers","ManageGroupPermissions","ManageChatAdministrators","ManageGroupRemovedUsers","ManageGroupUserPermissionsCreate","ManageGroupUserPermissions","ManageGroupRecentActions","ManageGroupAdminRights","ManageGroupNewAdminRights","ManageGroupMembers","ManageGroupAddAdmins","renderingContentKey","renderHeaderContent","autoFocusSearch","isBackButton","buttonClassName","useInfiniteScrollForLoadableItems","currentResultType","handleLoadMore","itemIds","getMore","useInfiniteScroll","MEMBERS_SLICE","useInfiniteScrollForSharedMedia","forSharedMediaType","messageIdsRef","getMessageContentIds","reverse","runThrottledForScroll","isScrollingProgrammatically","TABS","buildInfiniteScrollItemSelector","resultType","mediaSearchType","isGroup","hasMembersTab","areMembersHidden","canViewMembers","canAddMembers","getHasAdminRight","canDeleteMembers","hasCommonChatsTab","resolvedUserId","isChatProtected","commonChatIds","onProfileStateChange","setLocalMediaSearchType","loadMoreMembers","loadCommonChats","searchMediaMessagesLocal","loadProfilePhotos","setNewChatMembersDialogState","setActiveTab","deletingUserId","setDeletingUserId","tabType","noProfileInfo","searchMessages","memberIds","sortUserIds","sortChatIds","memberViewportIds","getMoreMembers","noProfileInfoForMembers","mediaViewportIds","getMoreMedia","noProfileInfoForMedia","documentViewportIds","getMoreDocuments","noProfileInfoForDocuments","linkViewportIds","getMoreLinks","noProfileInfoForLinks","audioViewportIds","getMoreAudio","noProfileInfoForAudio","voiceViewportIds","getMoreVoices","noProfileInfoForVoices","commonChatViewportIds","getMoreCommonChats","noProfileInfoForCommonChats","useProfileViewportIds","prevTabType","tabsEl","prevProfileState","tabListEl","determineProfileState","useProfileState","applyTransitionFix","releaseTransitionFix","transitionElSelector","setMinHeight","transitionEl","minHeight","overflowY","scrollBarWidth","clientWidth","marginRight","useTransitionFixes","cacheBuster","resetCacheBuster","setCacheBuster","useCacheBuster","handleTransitionStop","handleNewMemberDialogOpen","NewChatMembersProgress","handleSelectMedia","handlePlayAudio","handleMemberClick","handleMessageFocus","handleDeleteMembersModalClose","renderingDelay","isFirstTab","SLIDE_TRANSITION_DURATION","canRenderContents","renderSharedMedia","noSpinner","NothingFound","Media","withDate","smaller","onDateClick","WebLink","onMessageClick","getSenderName","ListItem","teactOrderKey","contextActions","memberId","handler","forceShowSelf","InfiniteScroll","itemSelector","sensitiveArea","PROFILE_SENSITIVE_AREA","preloadBackwards","noScrollRestoreOnTop","noFastList","onLoadMore","ProfileInfo","ChatExtra","renderProfileInfo","shouldRestoreHeight","onStart","big","FloatingActionButton","DeleteMemberModal","RightSearch","Management","localContactIds","isSearching","onNextStep","setUserSearchQuery","selectedMemberIds","setSelectedMemberIds","noPickerScrollRestore","member","handleFilterChange","displayedIds","filteredContactIds","filterUsersByName","canBeInvitedToGroup","handleNextStep","Picker","selectedIds","filterValue","filterPlaceholder","searchInputId","onSelectedIdsChange","onFilterChange","noScrollRestore","MAIN_SCREENS_COUNT","RightColumnContent","MANAGEMENT_SCREENS_COUNT","blurSearchInput","areActiveChatsLoaded","selectAreActiveChatsLoaded","selectRightColumnContentKey","currentProfileUserId","selectedId","isChatSelected","toggleChatInfo","closePollResults","addChatMembers","setProfileState","setManagementScreen","selectedChatMemberId","setSelectedChatMemberId","isPromotedByCurrentUser","setIsPromotedByCurrentUser","isScrolledDown","isOverlaying","shouldScrollUp","handleSelectChatMember","isPromoted","handleAppendingChatMembers","onChatMemberSelect","prevContentKey","MediaViewer","download","click","startedDownloads","downloadHash","getMessageContentFilename","Notifications","Dialogs","ForwardPicker","SafeLinkModal","HistoryCalendar","GroupCall","ActiveCallHeader","CallFallbackConfirm","notificationInterval","DEBUG_isLogged","updateIcon","asUnread","updatePageTitle","nextTitle","wasTimeFormatSetManually","isMediaViewerOpen","selectIsMediaViewerOpen","isForwardModalOpen","selectIsForwardModalOpen","hasNotifications","hasDialogs","isHistoryCalendarOpen","isServiceChatReady","isCallFallbackConfirmOpen","isFallbackConfirmOpen","loadNotificationSettings","loadNotificationExceptions","updateIsOnline","loadTopInlineBots","loadEmojiKeywords","loadCountryList","loadAddedStickers","ensureTimeFormat","openStickerSetShortName","checkVersionNotification","isSynced","LOCATION_HASH","processDeepLink","decodeURIComponent","middleColumnTransitionClassNames","rightColumnTransitionClassNames","prevIsLeftColumnShown","dispatchHeavyAnimationEnd","waitForTransitionEnd","prevIsRightColumnShown","initialUnread","INACTIVE_MARKER","newUnread","PAGE_TITLE","handleStickerSetModalClose","usePreventPinchZoomGesture","onDrop","onDragOver","initApi"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/87.77459230580aafa8639a.js b/dist/87.77459230580aafa8639a.js deleted file mode 100644 index 8ba4cfab..00000000 --- a/dist/87.77459230580aafa8639a.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict";(self.webpackChunktelegram_t=self.webpackChunktelegram_t||[]).push([[87],{4087:(e,t,s)=>{s.r(t),s.d(t,{Main:()=>Ao});var n=s(5116),a=s(3716),o=s(4050),r=(s(7895),s(307)),i=s(1638),c=s(735),d=s(2858);function l(e){const{chatId:t,threadId:s}=(0,i.Bt)(e)||{};return t&&s?(e=(0,r.qr)(e,t,s,!1),e=(0,r.Pb)(e,t,s,void 0)):e}(0,n.Q6)("openLocalTextSearch",(e=>{const{chatId:t,threadId:s}=(0,i.Bt)(e)||{};if(t&&s)return(0,r.qr)(e,t,s,!0)})),(0,n.Q6)("closeLocalTextSearch",l),(0,n.Q6)("setLocalTextSearchQuery",((e,t,s)=>{const{chatId:n,threadId:a}=(0,i.Bt)(e)||{};if(!n||!a)return;const{query:o}=s,l=(0,d.uw)(n,a),{query:u}=e.localTextSearch.byChatThreadKey[l]||{};return o!==u&&(e=(0,r.Pb)(e,n,a,c.D)),(0,r.qr)(e,n,a,!0,o)})),(0,n.Q6)("setLocalMediaSearchType",((e,t,s)=>{const{chatId:n}=(0,i.Bt)(e)||{};if(!n)return;const{mediaType:a}=s;return(0,r.z5)(e,n,a)})),(0,n.Q6)("openChat",((e,t,s)=>{const{id:a,threadId:o=-1,type:c="thread",shouldReplaceHistory:d=!1}=s,u=(0,i.Bt)(e);return u&&u.chatId===a&&u.threadId===o&&u.type===c||(e=(0,r.pf)(e,a,o,"replyStack",[]),e=l(e=(0,r.i9)(e)),e={...e,messages:{...e.messages,contentToBeScheduled:void 0},...a!==e.forwardMessages.toChatId&&{forwardMessages:{}}},(0,n.R3)(e)),(0,r.Wy)(e,a,o,c,d)})),(0,n.Q6)("openPreviousChat",(e=>(0,r.Wy)(e,void 0))),(0,n.Q6)("openChatWithInfo",((e,t,s)=>{(0,n.R3)({...e,isChatInfoShown:!0}),t.openChat(s)})),(0,n.Q6)("resetChatCreation",(e=>({...e,chatCreation:void 0}))),(0,n.Q6)("setNewChatMembersDialogState",((e,t,s)=>({...e,newChatMembersProgress:s}))),(0,n.Q6)("openNextChat",((e,t,s)=>{const{targetIndexDelta:n,orderedIds:a}=s,{chatId:o}=(0,i.Bt)(e)||{};if(!o)return void t.openChat({id:a[0]});const r=a.indexOf(o);if(-1===r)return;const c=a[r+n];t.openChat({id:c,shouldReplaceHistory:!0})}));var u=s(6137),m=s(1713),h=s(7361),g=s(782),p=s(2267),f=s(3099);const I=a.ck+a.fK;let v;(0,n.Q6)("setScrollOffset",((e,t,s)=>{const{chatId:n,threadId:a,scrollOffset:o}=s;return(0,r.pf)(e,n,a,"scrollOffset",o)})),(0,n.Q6)("setReplyingToId",((e,t,s)=>{const{messageId:n}=s,a=(0,i.Bt)(e);if(!a)return;const{chatId:o,threadId:c}=a;return(0,r.pf)(e,o,c,"replyingToId",n)})),(0,n.Q6)("setEditingId",((e,t,s)=>{const{messageId:n}=s,a=(0,i.Bt)(e);if(!a)return;const{chatId:o,threadId:c,type:d}=a,l="scheduled"===d?"editingScheduledId":"editingId";return(0,r.pf)(e,o,c,l,n)})),(0,n.Q6)("editLastMessage",(e=>{const{chatId:t,threadId:s}=(0,i.Bt)(e)||{};if(!t||!s)return;const n=(0,i.Zw)(e,t),a=(0,i.Cb)(e,t,s);if(!n||!a)return;const o=(0,g.dF)(a,(t=>Boolean(n[t]&&(0,i._k)(e,n[t],s).canEdit)));return o?(0,r.pf)(e,t,s,"editingId",o):void 0})),(0,n.Q6)("replyToNextMessage",((e,t,s)=>{const{targetIndexDelta:n}=s,{chatId:a,threadId:o}=(0,i.Bt)(e)||{};if(!a||!o)return;const r=(0,i.Zw)(e,a),c=(0,i.Cb)(e,a,o);if(!r||!c)return;const d=(0,i.Yy)(e,a,o);let l;if((0,i.b9)(e,a,o)&&d){const e=Object.keys(r),t=e.indexOf(d.toString())+n;l=t<=e.length+1&&t>=0?Number(e[t]):void 0}else if(o===u._f){var m;const t=(0,i.Z1)(e,a);l=null==t||null===(m=t.lastMessage)||void 0===m?void 0:m.id}else{const t=(0,i.tZ)(e,a,o);l=null==t?void 0:t.lastMessageId}t.setReplyingToId({messageId:l}),t.focusMessage({chatId:a,threadId:o,messageId:l})})),(0,n.Q6)("openMediaViewer",((e,t,s)=>{const{chatId:n,threadId:a,messageId:o,avatarOwnerId:r,profilePhotoIndex:i,origin:c}=s;return{...e,mediaViewer:{chatId:n,threadId:a,messageId:o,avatarOwnerId:r,profilePhotoIndex:i,origin:c},forwardMessages:{}}})),(0,n.Q6)("closeMediaViewer",(e=>({...e,mediaViewer:{}}))),(0,n.Q6)("openAudioPlayer",((e,t,s)=>{const{chatId:n,threadId:a,messageId:o,origin:r,volume:i,playbackRate:c,isMuted:d}=s;return{...e,audioPlayer:{chatId:n,threadId:a,messageId:o,origin:null!=r?r:e.audioPlayer.origin,volume:null!=i?i:e.audioPlayer.volume,playbackRate:c||e.audioPlayer.playbackRate,isMuted:d||e.audioPlayer.isMuted}}})),(0,n.Q6)("setAudioPlayerVolume",((e,t,s)=>{const{volume:n}=s;return{...e,audioPlayer:{...e.audioPlayer,volume:n}}})),(0,n.Q6)("setAudioPlayerPlaybackRate",((e,t,s)=>{const{playbackRate:n}=s;return{...e,audioPlayer:{...e.audioPlayer,playbackRate:n}}})),(0,n.Q6)("setAudioPlayerMuted",((e,t,s)=>{const{isMuted:n}=s;return{...e,audioPlayer:{...e.audioPlayer,isMuted:n}}})),(0,n.Q6)("setAudioPlayerOrigin",((e,t,s)=>{const{origin:n}=s;return{...e,audioPlayer:{...e.audioPlayer,origin:n}}})),(0,n.Q6)("closeAudioPlayer",(e=>({...e,audioPlayer:{volume:e.audioPlayer.volume,playbackRate:e.audioPlayer.playbackRate,isMuted:e.audioPlayer.isMuted}}))),(0,n.Q6)("openPollResults",((e,t,s)=>{const{chatId:a,messageId:o}=s;(0,i.Jf)(e)?a===e.pollResults.chatId&&o===e.pollResults.messageId||(0,n.R3)({...e,pollResults:{chatId:a,messageId:o,voters:{}}}):window.setTimeout((()=>{const e=(0,n.Rd)();(0,n.R3)({...e,pollResults:{chatId:a,messageId:o,voters:{}}})}),450)})),(0,n.Q6)("closePollResults",(e=>{(0,n.R3)({...e,pollResults:{}})})),(0,n.Q6)("focusLastMessage",((e,t)=>{const s=(0,i.Bt)(e);if(!s)return;const{chatId:n,threadId:a}=s;let o;if(a===u._f){var r;const t=(0,i.Z1)(e,n);o=null==t||null===(r=t.lastMessage)||void 0===r?void 0:r.id}else{const t=(0,i.tZ)(e,n,a);o=null==t?void 0:t.lastMessageId}o&&t.focusMessage({chatId:n,threadId:a,messageId:o,noHighlight:!0})})),(0,n.Q6)("focusNextReply",((e,t)=>{const s=(0,i.Bt)(e);if(!s)return;const{chatId:a,threadId:o}=s,c=(0,i.p9)(e,a,o);if(c&&0!==c.length){const s=c.pop();e=(0,r.pf)(e,a,o,"replyStack",[...c]),(0,n.R3)(e),t.focusMessage({chatId:a,threadId:o,messageId:s})}else t.focusLastMessage()})),(0,n.Q6)("focusMessage",((e,t,s)=>{const{chatId:a,threadId:o=u._f,messageListType:c="thread",noHighlight:d,groupedId:l,groupedChatId:h,replyMessageId:g,isResizingContainer:p}=s;let{messageId:f}=s;if(void 0!==l){const t=(0,i.y8)(e,h,l);null!=t&&t.length&&([f]=t)}const y=(0,i.Bt)(e),Z=!y||a!==y.chatId||o!==y.threadId||c!==y.type;if(v&&(clearTimeout(v),v=void 0),v=window.setTimeout((()=>{let e=(0,n.Rd)();e=(0,r.cq)(e),e=(0,r.wV)(e),(0,n.R3)(e)}),d?I:1500),e=(0,r.cq)(e,a,f,d,p),e=(0,r.wV)(e,void 0),g){const t=(0,i.p9)(e,a,o)||[];e=(0,r.pf)(e,a,o,"replyStack",[...t,g])}Z&&(e=(0,r.wV)(e,m.fo.Static));const P=(0,i.Cb)(e,a,o);if(P&&P.includes(f))return(0,n.R3)(e),void t.openChat({id:a,threadId:o});if(Z&&(e=(0,r.pf)(e,a,o,"viewportIds",void 0)),e=(0,r.pf)(e,a,o,"outlyingIds",void 0),P&&!Z){const t=f>P[0]?m.fo.Down:m.fo.Up;e=(0,r.wV)(e,t)}(0,n.R3)(e),t.openChat({id:a,threadId:o}),t.loadViewportMessages()})),(0,n.Q6)("openForwardMenu",((e,t,s)=>{const{fromChatId:n,messageIds:a,groupedId:o}=s;let r;return o&&(r=(0,i.xH)(e,n,o)),{...e,forwardMessages:{fromChatId:n,messageIds:r||a,isModalShown:!0}}})),(0,n.Q6)("exitForwardMode",(e=>{(0,n.R3)({...e,forwardMessages:{}})})),(0,n.Q6)("setForwardChatId",((e,t,s)=>{const{id:a}=s;(0,n.R3)({...e,forwardMessages:{...e.forwardMessages,toChatId:a,isModalShown:!1}}),t.openChat({id:a}),t.closeMediaViewer(),t.exitMessageSelectMode()})),(0,n.Q6)("openForwardMenuForSelectedMessages",((e,t)=>{if(!e.selectedMessages)return;const{chatId:s,messageIds:n}=e.selectedMessages;t.openForwardMenu({fromChatId:s,messageIds:n})})),(0,n.Q6)("cancelMessageMediaDownload",((e,t,s)=>{const{message:a}=s,o=e.activeDownloads.byChatId[a.chatId];o&&o.length&&(0,n.R3)({...e,activeDownloads:{byChatId:{...e.activeDownloads.byChatId,[a.chatId]:o.filter((e=>e!==a.id))}}})})),(0,n.Q6)("downloadMessageMedia",((e,t,s)=>{const{message:a}=s;a&&(0,n.R3)({...e,activeDownloads:{byChatId:{...e.activeDownloads.byChatId,[a.chatId]:[...e.activeDownloads.byChatId[a.chatId]||[],a.id]}}})})),(0,n.Q6)("downloadSelectedMessages",((e,t)=>{if(!e.selectedMessages)return;const{chatId:s,messageIds:n}=e.selectedMessages,{threadId:a}=(0,i.Bt)(e)||{},o=(0,i.Zw)(e,s);o&&a&&n.map((e=>o[e])).filter((t=>(0,i._k)(e,t,a).canDownload)).forEach((e=>t.downloadMessageMedia({message:e})))})),(0,n.Q6)("enterMessageSelectMode",((e,t,s)=>{const{messageId:n}=s||{},a=(0,i.jr)(e);return a?(0,r.M6)(e,a.id,n):e})),(0,n.Q6)("toggleMessageSelection",((e,t,s)=>{const{messageId:a,groupedId:o,childMessageIds:c,withShift:d}=s,l=(0,i.Bt)(e);if(!l)return;const{chatId:u,threadId:m,type:g}=l;e=(0,r.Ob)(e,u,m,g,a,o,c,d),(0,n.R3)(e),e.shouldShowContextMenuHint&&(t.disableContextMenuHint(),t.showNotification({message:`To **edit** or **reply**, close this menu. Then ${h.$b?"long tap":"right click"} on a message.`}))})),(0,n.Q6)("disableContextMenuHint",(e=>{if(e.shouldShowContextMenuHint)return{...e,shouldShowContextMenuHint:!1}})),(0,n.Q6)("exitMessageSelectMode",r.i9),(0,n.Q6)("openPollModal",(e=>({...e,isPollModalOpen:!0}))),(0,n.Q6)("closePollModal",(e=>({...e,isPollModalOpen:!1}))),(0,n.Q6)("checkVersionNotification",((e,t)=>{const s=a.Ji.split(".").slice(0,2).join("."),{serviceNotifications:n}=e;if(n.find((({version:e})=>e===s)))return;const o={chatId:a.aw,date:(0,p.b)(e.serverTimeOffset),content:{text:(0,f.Z)('**Telegram Web Z was updated to version 1.28**\n\n👏 **Harder**\n• Support for join requests in groups and channels.\n• Support for more service messages.\n\n🤩 **Better**\n• Easier to select and adjust left column width.\n• Redundant single quotes removed in Spanish and French translations.\n• Support for hotkeys on non-qwerty keyboards.\n• Use Ctrl+Shift+F or Ctrl+F (in PWA mode) to open global or local search.\n• Chat: "Add to folder..." only appears for users with folders.\n• Support for `start` parameter in `tg://resolve` links.\n\n💪 **Stronger**\n• Fixed focusing on messages in a chat that was previously open.\n• Fixed missing stickers in sticker suggestions.\n• Fixed opening chats from user mentions.\n• Fixed various glitches when appearing as a channel in public groups.\n• Removed redundant download and forward options in chats with protected content.\n')},isOutgoing:!1};t.createServiceNotification({message:o,version:s})})),(0,n.Q6)("createServiceNotification",((e,t,s)=>{var o;const{message:r,version:c}=s,{serviceNotifications:d}=e,l=(0,i.Z1)(e,a.aw),u=Math.max((null===(o=l.lastMessage)||void 0===o?void 0:o.id)||0,...d.map((({id:e})=>e))),m=(d.length+1)/1e3,h=Math.floor(u)+m;r.id=h;const g={id:h,message:r,version:c,isUnread:!0};(0,n.R3)({...e,serviceNotifications:[...d.slice(-1e3),g]}),t.apiUpdate({"@type":"newMessage",id:r.id,chatId:r.chatId,message:r})})),(0,n.Q6)("openSeenByModal",((e,t,s)=>{const{chatId:n,messageId:a}=s;return{...e,seenByModal:{chatId:n,messageId:a}}})),(0,n.Q6)("closeSeenByModal",(e=>({...e,seenByModal:void 0}))),(0,n.Q6)("setGlobalSearchQuery",((e,t,s)=>{const{query:n}=s,{chatId:a}=e.globalSearch;return(0,r.No)(e,{globalResults:{},localResults:{},resultsByType:void 0,...n?{fetchingStatus:{chats:!a,messages:!0}}:{fetchingStatus:void 0},query:n})})),(0,n.Q6)("addRecentlyFoundChatId",((e,t,s)=>{const{id:n}=s,{recentlyFoundChatIds:a}=e.globalSearch;if(!a)return(0,r.No)(e,{recentlyFoundChatIds:[n]});const o=a.filter((e=>e!==n));return o.unshift(n),o.length>10&&o.pop(),(0,r.No)(e,{recentlyFoundChatIds:o})})),(0,n.Q6)("clearRecentlyFoundChats",(e=>(0,r.No)(e,{recentlyFoundChatIds:void 0}))),(0,n.Q6)("setGlobalSearchContent",((e,t,s)=>{const{content:n}=s;return(0,r.Og)(e,n)})),(0,n.Q6)("setGlobalSearchChatId",((e,t,s)=>{const{id:n}=s;return(0,r.No)(e,{chatId:n,query:void 0,resultsByType:void 0})})),(0,n.Q6)("setStickerSearchQuery",((e,t,s)=>{const{query:n}=s;return{...e,stickers:{...e.stickers,search:{query:n,resultIds:void 0}}}})),(0,n.Q6)("setGifSearchQuery",((e,t,s)=>{const{query:n}=s;return{...e,gifs:{...e.gifs,search:{query:n,offsetId:void 0,results:void 0}}}})),(0,n.Q6)("openUserInfo",((e,t,s)=>{const{id:n}=s;t.openChat({id:n})})),(0,n.Q6)("openChat",(e=>(0,r.x1)(e,void 0))),(0,n.Q6)("setUserSearchQuery",((e,t,s)=>{const{query:n}=s;return(0,r.Lm)(e,{globalUserIds:void 0,localUserIds:void 0,fetchingStatus:Boolean(n),query:n})})),s(3781);var y=s(1947),Z=s(6926);(0,n.Q6)("toggleChatInfo",(e=>({...e,isChatInfoShown:!e.isChatInfoShown}))),(0,n.Q6)("setLeftColumnWidth",((e,t,s)=>({...e,leftColumnWidth:s}))),(0,n.Q6)("resetLeftColumnWidth",(e=>({...e,leftColumnWidth:void 0}))),(0,n.Q6)("toggleManagement",(e=>{const{chatId:t}=(0,i.Bt)(e)||{};if(t)return{...e,management:{byChatId:{...e.management.byChatId,[t]:{...e.management.byChatId[t],isActive:!(e.management.byChatId[t]||{}).isActive}}}}})),(0,n.Q6)("closeManagement",(e=>{const{chatId:t}=(0,i.Bt)(e)||{};if(t)return{...e,management:{byChatId:{...e.management.byChatId,[t]:{...e.management.byChatId[t],isActive:!1}}}}})),(0,n.Q6)("openChat",(e=>{if(h.wB||h.p7)return{...e,isLeftColumnShown:0===e.messages.messageLists.length}})),(0,n.Q6)("toggleLeftColumn",(e=>({...e,isLeftColumnShown:!e.isLeftColumnShown}))),(0,n.Q6)("addRecentEmoji",((e,t,s)=>{const{emoji:n}=s,{recentEmojis:a}=e;if(!a)return{...e,recentEmojis:[n]};const o=a.filter((e=>e!==n));return o.unshift(n),o.length>18&&o.pop(),{...e,recentEmojis:o}})),(0,n.Q6)("addRecentSticker",((e,t,s)=>{const{sticker:n}=s,{recent:a}=e.stickers;if(!a)return{...e,stickers:{...e.stickers,recent:{hash:"0",stickers:[n]}}};const o=a.stickers.filter((e=>e.id!==n.id));return o.unshift(n),{...e,stickers:{...e.stickers,recent:{...a,stickers:o}}}})),(0,n.Q6)("showNotification",((e,t,s)=>{const n=s;n.localId=(0,Z.Z)({});const a=[...e.notifications],o=a.findIndex((e=>e.message===n.message));return-1!==o&&a.splice(o,1),a.push(n),{...e,notifications:a}})),(0,n.Q6)("dismissNotification",((e,t,s)=>{const n=e.notifications.filter((({localId:e})=>e!==s.localId));return{...e,notifications:n}})),(0,n.Q6)("showDialog",((e,t,s)=>{const{data:n}=s;if("message"in n&&n.hasErrorKey&&!(0,y.ZP)(n))return e;const a=[...e.dialogs];if("message"in n){const e=a.findIndex((e=>e.message===n.message));-1!==e&&a.splice(e,1)}return a.push(n),{...e,dialogs:a}})),(0,n.Q6)("dismissDialog",(e=>{const t=[...e.dialogs];return t.pop(),{...e,dialogs:t}})),(0,n.Q6)("toggleSafeLinkModal",((e,t,s)=>{const{url:n}=s;return{...e,safeLinkModalUrl:n}})),(0,n.Q6)("openHistoryCalendar",((e,t,s)=>{const{selectedAt:n}=s;return{...e,historyCalendarSelectedAt:n}})),(0,n.Q6)("closeHistoryCalendar",(e=>({...e,historyCalendarSelectedAt:void 0}))),(0,n.Q6)("openPaymentModal",((e,t,s)=>{const{chatId:n,messageId:a}=s;return{...e,payment:{...e.payment,chatId:n,messageId:a,isPaymentModalOpen:!0}}})),(0,n.Q6)("closePaymentModal",(e=>{const t=(0,r.bp)(e);return(0,r.WY)(t)})),(0,n.Q6)("addPaymentError",((e,t,s)=>{const{error:n}=s;return{...e,payment:{...e.payment,error:n}}})),s(1689),s(1363),s(6204);var P=s(1226),C=s(9118);const w=new Map,b=(0,C.Ds)((e=>e()),500,!1);async function S(e,t,s,o,c=!1,d=!1){const l=e.id;let u;switch(o){case m.Uq.Backwards:u=void 0;break;case m.Uq.Around:u=-(Math.round(a.hT/2)+1);break;case m.Uq.Forwards:u=-(a.hT+1)}const h=await(0,P.t9)("fetchMessages",{chat:(0,i.Cm)((0,n.Rd)(),l,t),offsetId:s,addOffset:u,limit:a.hT,threadId:t});if(!h)return;const{messages:p,users:f,chats:I,threadInfos:v}=h;let y=(0,n.Rd)();const Z=l===a.aw?y.serviceNotifications.map((({message:e})=>e)):[],C=[].concat(p,Z),w=(0,g.ee)(C,"id"),b=Object.keys(w).map(Number);y=(0,r.c_)(y,l,w),y=c?(0,r.ff)(y,l,t,b):(0,r.xj)(y,l,t,b),y=(0,r.Sh)(y,(0,g.ee)(f,"id")),y=(0,r.fZ)(y,(0,g.ee)(I,"id")),y=(0,r.j6)(y,l,v);let S=(0,i.gb)(y,l,t);const M=(0,i.qC)(y,l,t);if(c&&S&&M&&(M.length&&!(0,g.YE)(S,M)||(y=(0,r.xj)(y,l,t,M),S=(0,i.gb)(y,l,t),y=(0,r.pf)(y,l,t,"outlyingIds",void 0),c=!1)),!d){const e=c?M:S,{newViewportIds:n}=E(e,s,o);y=(0,r.y9)(y,l,t,n)}(0,n.R3)(y)}function E(e,t,s){const{length:n}=e,o=t?function(e,t){return te[e.length-1]?e.length-1:e.findIndex(((s,n)=>s===t||st))}(e,t):-1,r=s===m.Uq.Backwards?o:o+1||n,i=r-a.hT,c=r+a.hT-1,d=e.slice(Math.max(0,i),c+1);let l,u;switch(s){case m.Uq.Backwards:l=r>0,u=i>=0;break;case m.Uq.Forwards:l=r0,u=d.length===a.hT}return{newViewportIds:d,areSomeLocal:l,areAllLocal:u}}async function M(e){let t;const s=e.attachment?(e,a)=>{w.has(a)||(t=a,w.set(a,s));const o=(0,n.Rd)();(0,n.R3)({...o,fileUploads:{byMessageLocalId:{...o.fileUploads.byMessageLocalId,[a]:{progress:e}}}})}:void 0;(e.replyingTo||h.cj)&&await(0,C.Pn)();const a=(0,n.Rd)();e.serverTimeOffset=a.serverTimeOffset;const o=(0,i.Bt)(a);if(!o)return;const{threadId:r}=o;e.replyingTo||r===u._f||(e.replyingTo=(0,i.qS)(a,e.chat.id,r)),await(0,P.t9)("sendMessage",e,s),s&&t&&w.delete(t)}(0,n.Q6)("loadViewportMessages",((e,t,s)=>{const{direction:n=m.Uq.Around,isBudgetPreload:o=!1}=s||{};let{chatId:c,threadId:d}=s||{};if(!c){const t=(0,i.Bt)(e);if(!t)return;c=t.chatId,d=t.threadId}const l=(0,i.Z1)(e,c);if(!l||l.isRestricted)return;const u=(0,i.Cb)(e,c,d),h=(0,i.gb)(e,c,d),g=(0,i.qC)(e,c,d);if(u&&u.length&&n!==m.Uq.Around){const s=n===m.Uq.Backwards?u[0]:u[u.length-1],a=Boolean(g),i=a?g:h,{newViewportIds:p,areSomeLocal:f,areAllLocal:I}=E(i,s,n);if(f&&(e=(0,r.y9)(e,c,d,p)),async function(e,t,s,n,a,o,r,i){t||await S(a,o,i,r,s,n),n||(await Promise.resolve(),e.loadViewportMessages({chatId:a.id,threadId:o,direction:r,isBudgetPreload:!0}))}(t,I,a,o,l,d,n,s),o)return}else{const t=(0,i.G$)(e,c)||(0,i.rd)(e,c,d),s=Boolean(t&&h&&!h.includes(t)),n=(s?g:h)||[],{newViewportIds:u,areSomeLocal:p,areAllLocal:f}=E(n,t,m.Uq.Around);p&&u.length>=a.hT&&(e=(0,r.y9)(e,c,d,u)),f||S(l,d,t,m.Uq.Around,s,o)}return e})),(0,n.Q6)("loadMessage",((e,t,s)=>{const{chatId:a,messageId:o,replyOriginForId:c,threadUpdate:d}=s,l=(0,i.Z1)(e,a);l&&(async()=>{const e=await async function(e,t,s){const a=await(0,P.t9)("fetchMessage",{chat:e,messageId:t});if(!a)return;if(a===u._Q){if(s){let t=(0,n.Rd)();const a=(0,i.hj)(t,e.id,s);t=(0,r.cY)(t,e.id,s,{...a,replyToMessageId:void 0}),(0,n.R3)(t)}return}let o=(0,n.Rd)();return o=(0,r.cY)(o,e.id,t,a.message),o=(0,r.Sh)(o,(0,g.ee)(a.users,"id")),(0,n.R3)(o),a.message}(l,o,c);if(e&&d){const{lastMessageId:t,isDeleting:s}=d;(0,n.R3)((0,r.lG)((0,n.Rd)(),e,a,t,s))}})()})),(0,n.Q6)("sendMessage",((e,t,s)=>{const n=(0,i.Bt)(e);if(!n)return;const{chatId:o,threadId:r,type:c}=n;if("scheduled"===c&&!s.scheduledAt)return{...e,messages:{...e.messages,contentToBeScheduled:s}};const d=(0,i.Z1)(e,o),l={...s,chat:d,replyingTo:(0,i.Yy)(e,o,r),noWebPage:(0,i.tV)(e,o,r),sendAs:(0,i._5)(e,o)};t.setReplyingToId({messageId:void 0}),t.clearWebPagePreview({chatId:o,threadId:r,value:!1});const u=!s.attachments||s.attachments.length<=1,m=!u&&s.attachments&&s.attachments.length>1;if(u){const{attachments:e,...t}=l;M({...t,attachment:e?e[0]:void 0})}else if(m){const{text:e,entities:t,attachments:s,...n}=l,o=(0,g.Vl)(s,a.DU);for(let s=0;s0?i:void 0}),r.forEach((e=>{M({...n,attachment:e,groupedId:i})}))}}else{const{text:e,entities:t,attachments:s,replyingTo:n,...a}=l;e&&M({...a,text:e,entities:t,replyingTo:n}),s.forEach((e=>{M({...a,attachment:e})}))}})),(0,n.Q6)("editMessage",((e,t,s)=>{const{serverTimeOffset:n}=e,{text:a,entities:o}=s,r=(0,i.Bt)(e);if(!r)return;const{chatId:c,threadId:d,type:l}=r,u=(0,i.Z1)(e,c),m=(0,i.kK)(e,c,d,l);u&&m&&((0,P.t9)("editMessage",{chat:u,message:m,text:a,entities:o,noWebPage:(0,i.tV)(e,c,d),serverTimeOffset:n}),t.setEditingId({messageId:void 0}))})),(0,n.Q6)("cancelSendingMessage",((e,t,s)=>{const{chatId:n,messageId:a}=s,o=(0,i.hj)(e,n,a),r=o&&w.get(o.previousLocalId||o.id);r&&(0,P.u3)(r),t.apiUpdate({"@type":"deleteMessages",ids:[a],chatId:n})})),(0,n.Q6)("saveDraft",((e,t,s)=>{const{chatId:n,threadId:a,draft:o}=s;if(!o)return;const{text:c,entities:d}=o,l=(0,i.Z1)(e,n);return a===u._f&&(0,P.t9)("saveDraft",{chat:l,text:c,entities:d,replyToMsgId:(0,i.Yy)(e,n,a)}),e=(0,r.pf)(e,n,a,"draft",o),(0,r.a4)(e,n,{draftDate:Math.round(Date.now()/1e3)})})),(0,n.Q6)("clearDraft",((e,t,s)=>{const{chatId:n,threadId:a,localOnly:o}=s;if(!(0,i.Ms)(e,n,a))return;const c=(0,i.Z1)(e,n);return o||a!==u._f||(0,P.t9)("clearDraft",c),e=(0,r.pf)(e,n,a,"draft",void 0),(0,r.a4)(e,n,{draftDate:void 0})})),(0,n.Q6)("toggleMessageWebPage",((e,t,s)=>{const{chatId:n,threadId:a,noWebPage:o}=s;return(0,r.pf)(e,n,a,"noWebPage",o)})),(0,n.Q6)("pinMessage",((e,t,s)=>{const n=(0,i.jr)(e);if(!n)return;const{messageId:a,isUnpin:o,isOneSide:r,isSilent:c}=s;(0,P.t9)("pinMessage",{chat:n,messageId:a,isUnpin:o,isOneSide:r,isSilent:c})})),(0,n.Q6)("unpinAllMessages",((e,t,s)=>{const a=(0,i.Z1)(e,s.chatId);a&&async function(e){await(0,P.t9)("unpinAllMessages",{chat:e});let t=(0,n.Rd)();t=(0,r.pf)(t,e.id,u._f,"pinnedIds",[]),(0,n.R3)(t)}(a)})),(0,n.Q6)("deleteMessages",((e,t,s)=>{const{messageIds:n,shouldDeleteForAll:a}=s,o=(0,i.Bt)(e);if(!o)return;const{chatId:r,threadId:c}=o,d=(0,i.Z1)(e,r);(0,P.t9)("deleteMessages",{chat:d,messageIds:n,shouldDeleteForAll:a});const l=(0,i._$)(e,r,c);n.includes(l)&&t.setEditingId({messageId:void 0})})),(0,n.Q6)("deleteScheduledMessages",((e,t,s)=>{const{messageIds:n}=s,a=(0,i.Bt)(e);if(!a)return;const{chatId:o}=a,r=(0,i.Z1)(e,o);(0,P.t9)("deleteScheduledMessages",{chat:r,messageIds:n});const c=(0,i.wU)(e,o);n.includes(c)&&t.setEditingId({messageId:void 0})})),(0,n.Q6)("deleteHistory",((e,t,s)=>{(async()=>{var n;const{chatId:a,shouldDeleteForAll:o}=s,r=(0,i.Z1)(e,a);if(!r)return;const c=null===(n=r.lastMessage)||void 0===n?void 0:n.id;await(0,P.t9)("deleteHistory",{chat:r,shouldDeleteForAll:o,maxId:c});const d=(0,i.Bt)(e);d&&d.chatId===a&&t.openChat({id:void 0})})()})),(0,n.Q6)("reportMessages",((e,t,s)=>{(async()=>{const{messageIds:n,reason:a,description:o}=s,r=(0,i.Bt)(e);if(!r)return;const{chatId:c}=r,d=(0,i.Z1)(e,c),l=await(0,P.t9)("reportMessages",{peer:d,messageIds:n,reason:a,description:o});t.showNotification({message:l?"Thank you! Your report will be reviewed by our team.":"Error occured while submiting report. Please, try again later."})})()})),(0,n.Q6)("sendMessageAction",((e,t,s)=>{(async()=>{const{action:t,chatId:n,threadId:a}=s;if(n===e.currentUserId)return;const o=(0,i.Z1)(e,n);o&&await(0,P.t9)("sendMessageAction",{peer:o,threadId:a,action:t})})()})),(0,n.Q6)("markMessageListRead",((e,t,s)=>{const{serverTimeOffset:n}=e,o=(0,i.Bt)(e);if(!o)return;const{chatId:c,threadId:d}=o,l=(0,i.Cm)(e,c,d);if(!l)return;const{maxId:m}=s;if(b((()=>{(0,P.t9)("markMessageListRead",{serverTimeOffset:n,chat:l,threadId:d,maxId:m})})),d!==u._f)return;c===a.aw&&(e={...e,serviceNotifications:e.serviceNotifications.map((e=>e.isUnread&&e.id<=m?{...e,isUnread:!1}:e))});const h=(0,i.Cb)(e,c,d),g=(0,i.It)(e,c,d);if(!h||!g||!l.unreadCount)return e;const p=function(e,t,s){let n=0;for(let a=0,o=e.length;a=t&&e[a]<=s&&n++,!(e[a]>=s));a++);return n}(h,g,m);return p?(0,r.a4)(e,c,{lastReadInboxMessageId:m,unreadCount:Math.max(0,l.unreadCount-p)}):e})),(0,n.Q6)("markMessagesRead",((e,t,s)=>{const n=(0,i.jr)(e);if(!n)return;const{messageIds:a}=s;(0,P.t9)("markMessagesRead",{chat:n,messageIds:a})})),(0,n.Q6)("loadWebPagePreview",((e,t,s)=>{const{text:a}=s;!async function(e){const t=await(0,P.t9)("fetchWebPagePreview",{message:e});(0,n.R3)({...(0,n.Rd)(),webPagePreview:t})}(a)})),(0,n.Q6)("clearWebPagePreview",(e=>{if(e.webPagePreview)return{...e,webPagePreview:void 0}})),(0,n.Q6)("sendPollVote",((e,t,s)=>{const{chatId:n,messageId:a,options:o}=s,r=(0,i.Z1)(e,n);r&&(0,P.t9)("sendPollVote",{chat:r,messageId:a,options:o})})),(0,n.Q6)("loadPollOptionResults",((e,t,s)=>{const{chat:a,messageId:o,option:i,offset:c,limit:d,shouldResetVoters:l}=s;!async function(e,t,s,a,o,i){const c=await(0,P.t9)("loadPollOptionResults",{chat:e,messageId:t,option:s,offset:a,limit:o});if(!c)return;let d=(0,n.Rd)();d=(0,r.Sh)(d,(0,g.ee)(c.users,"id"));const{voters:l}=d.pollResults;(0,n.R3)({...d,pollResults:{...d.pollResults,voters:{...l,[s]:(0,g.Tw)([...!i&&l&&l[s]?l[s]:[],...c&&c.users.map((e=>e.id))])},offsets:{...d.pollResults.offsets?d.pollResults.offsets:{},[s]:c.nextOffset||""}}})}(a,o,i,c,d,l)})),(0,n.Q6)("forwardMessages",((e,t,s)=>{const{fromChatId:a,messageIds:o,toChatId:r}=e.forwardMessages,c=a?(0,i.Z1)(e,a):void 0,l=r?(0,i.Z1)(e,r):void 0,u=a&&o?o.sort(((e,t)=>e-t)).map((t=>(0,i.hj)(e,a,t))).filter(Boolean):void 0;if(!c||!l||!u)return;const{isSilent:m,scheduledAt:h}=s,g=(0,i._5)(e,r),p=u.filter((e=>!(0,d.jM)(e)));p.length&&(0,P.t9)("forwardMessages",{fromChat:c,toChat:l,messages:p,serverTimeOffset:(0,n.Rd)().serverTimeOffset,isSilent:m,scheduledAt:h,sendAs:g}),u.filter((e=>(0,d.jM)(e))).forEach((e=>{const{text:t,entities:s}=e.content.text||{},{sticker:n,poll:a}=e.content;M({chat:l,text:t,entities:s,sticker:n,poll:a,isSilent:m,scheduledAt:h,sendAs:g})})),(0,n.R3)({...(0,n.Rd)(),forwardMessages:{}})})),(0,n.Q6)("loadScheduledHistory",((e,t,s)=>{const{chatId:a}=s,o=(0,i.Z1)(e,a);o&&async function(e){const t=await(0,P.t9)("fetchScheduledHistory",{chat:e});if(!t)return;const{messages:s}=t,a=(0,g.ee)(s,"id"),o=Object.keys(a).map(Number).sort(((e,t)=>t-e));let i=(0,n.Rd)();i=(0,r.w3)(i,e.id,a),i=(0,r.pf)(i,e.id,u._f,"scheduledIds",o),(0,n.R3)(i)}(o)})),(0,n.Q6)("sendScheduledMessages",((e,t,s)=>{const{chatId:n,id:a}=s,o=(0,i.Z1)(e,n);o&&(0,P.t9)("sendScheduledMessages",{chat:o,ids:[a]})})),(0,n.Q6)("rescheduleMessage",((e,t,s)=>{const{chatId:n,messageId:a,scheduledAt:o}=s,r=(0,i.Z1)(e,n),c=r&&(0,i.Tm)(e,r.id,a);r&&c&&(0,P.t9)("rescheduleMessage",{chat:r,message:c,scheduledAt:o})})),(0,n.Q6)("requestThreadInfoUpdate",((e,t,s)=>{const{chatId:n,threadId:a}=s,o=(0,i.Cm)(e,n,a);o&&(0,P.t9)("requestThreadInfoUpdate",{chat:o,threadId:a})})),(0,n.Q6)("loadPinnedMessages",((e,t,s)=>{const{chatId:a}=s,o=(0,i.Z1)(e,a);o&&async function(e){const t=await(0,P.t9)("fetchPinnedMessages",{chat:e});if(!t)return;const{messages:s,chats:a,users:o}=t,i=(0,g.ee)(s,"id"),c=Object.keys(i).map(Number).sort(((e,t)=>t-e));let d=(0,n.Rd)();d=(0,r.c_)(d,e.id,i),d=(0,r.pf)(d,e.id,u._f,"pinnedIds",c),d=(0,r.Sh)(d,(0,g.ee)(o,"id")),d=(0,r.fZ)(d,(0,g.ee)(a,"id")),(0,n.R3)(d)}(o)})),(0,n.Q6)("loadSeenBy",((e,t,s)=>{const{chatId:a,messageId:o}=s,c=(0,i.Z1)(e,a);c&&(async()=>{const e=await(0,P.t9)("fetchSeenBy",{chat:c,messageId:o});e&&(0,n.R3)((0,r.cY)((0,n.Rd)(),a,o,{seenByUserIds:e}))})()})),(0,n.Q6)("saveDefaultSendAs",((e,t,s)=>{const{chatId:n,sendAsId:a}=s,o=(0,i.Z1)(e,n),c=(0,i.Z1)(e,a)||(0,i.dy)(e,a);if(o&&c)return(0,P.t9)("saveDefaultSendAs",{sendAs:c,chat:o}),(0,r.a4)(e,n,{fullInfo:{...o.fullInfo,sendAsId:a}})})),(0,n.Q6)("loadSendAs",((e,t,s)=>{const{chatId:a}=s,o=(0,i.Z1)(e,a);o&&(async()=>{const t=await(0,P.t9)("fetchSendAs",{chat:o});if(!t)return e=(0,r.a4)(e,a,{sendAsIds:[]}),void(0,n.R3)(e);e=(0,n.Rd)(),e=(0,r.Sh)(e,(0,g.ee)(t.users,"id")),e=(0,r.fZ)(e,(0,g.ee)(t.chats,"id")),e=(0,r.a4)(e,a,{sendAsIds:t.ids}),(0,n.R3)(e)})()})),(0,n.Q6)("loadSponsoredMessages",((e,t,s)=>{const{chatId:a}=s,o=(0,i.Z1)(e,a);o&&(async()=>{const e=await(0,P.t9)("fetchSponsoredMessages",{chat:o});if(!e)return;let t=(0,r.Fn)((0,n.Rd)(),a,e.messages[0]);t=(0,r.Sh)(t,(0,g.ee)(e.users,"id")),t=(0,r.fZ)(t,(0,g.ee)(e.chats,"id")),(0,n.R3)(t)})()})),(0,n.Q6)("viewSponsoredMessage",((e,t,s)=>{const{chatId:n}=s,a=(0,i.Z1)(e,n),o=(0,i.fS)(e,n);a&&o&&(0,P.t9)("viewSponsoredMessage",{chat:a,random:o.randomId})}));var k=s(5765);const R=(0,C.P2)((e=>e()),500,!1);async function T(e,t){const s=await(0,P.t9)("searchGifs",{query:e,offset:t});s&&(0,n.R3)((0,r.rq)((0,n.Rd)(),!t,s.gifs,s.nextOffset))}(0,n.Q6)("loadStickerSets",(e=>{const{hash:t}=e.stickers.added||{};!async function(e){const t=await(0,P.t9)("fetchStickerSets",{hash:e});t&&(0,n.R3)((0,r.z3)((0,n.Rd)(),"added",t.hash,t.sets))}(t)})),(0,n.Q6)("loadAddedStickers",((e,t)=>{const{setIds:s}=e.stickers.added;s&&s.length&&(async()=>{for(let e=0;e0&&await(0,C.wO)(200)})()})),(0,n.Q6)("loadRecentStickers",(e=>{const{hash:t}=e.stickers.recent||{};!async function(e){const t=await(0,P.t9)("fetchRecentStickers",{hash:e});if(!t)return;const s=(0,n.Rd)();(0,n.R3)({...s,stickers:{...s.stickers,recent:t}})}(t)})),(0,n.Q6)("loadFavoriteStickers",(e=>{const{hash:t}=e.stickers.favorite||{};!async function(e){const t=await(0,P.t9)("fetchFavoriteStickers",{hash:e});if(!t)return;const s=(0,n.Rd)();(0,n.R3)({...s,stickers:{...s.stickers,favorite:t}})}(t)})),(0,n.Q6)("loadGreetingStickers",(e=>{const{hash:t}=e.stickers.greeting||{};(async()=>{const e=await(0,P.t9)("fetchStickersForEmoji",{emoji:"👋⭐️",hash:t});if(!e)return;const s=(0,n.Rd)();(0,n.R3)({...s,stickers:{...s.stickers,greeting:{hash:e.hash,stickers:e.stickers.filter((e=>"👋"===e.emoji))}}})})()})),(0,n.Q6)("loadFeaturedStickers",(e=>{const{hash:t}=e.stickers.featured||{};!async function(e){const t=await(0,P.t9)("fetchFeaturedStickers",{hash:e});t&&(0,n.R3)((0,r.z3)((0,n.Rd)(),"featured",t.hash,t.sets))}(t)})),(0,n.Q6)("loadStickers",((e,t,s)=>{const{stickerSetId:a,stickerSetShortName:o}=s;let{stickerSetAccessHash:c}=s;if(!c&&!o){const t=(0,i.Ny)(e,a);if(!t)return;c=t.accessHash}!async function(e,t,s){const a=await(0,P.t9)("fetchStickers",{stickerSetShortName:s,stickerSetId:e,accessHash:t});if(!a)return;const{set:o,stickers:i,packs:c}=a;let d=(0,n.Rd)();d=(0,r.Rg)(d,o.id,{...o,stickers:i,packs:c});const l=d.stickers.forEmoji.emoji;l&&c[l]&&(d=(0,r.vy)(d)),(0,n.R3)(d)}(a,c,o)})),(0,n.Q6)("loadAnimatedEmojis",(()=>{!async function(){const e=await(0,P.t9)("fetchAnimatedEmojis");if(!e)return;const{set:t,stickers:s}=e;(0,n.R3)((0,r.g_)((0,n.Rd)(),{...t,stickers:s}))}()})),(0,n.Q6)("loadSavedGifs",(e=>{const{hash:t}=e.gifs.saved;!async function(e){const t=await(0,P.t9)("fetchSavedGifs",{hash:e});if(!t)return;const s=(0,n.Rd)();(0,n.R3)({...s,gifs:{...s.gifs,saved:t}})}(t)})),(0,n.Q6)("faveSticker",((e,t,s)=>{const{sticker:n}=s;n&&(0,P.t9)("faveSticker",{sticker:n})})),(0,n.Q6)("unfaveSticker",((e,t,s)=>{const{sticker:a}=s;a&&function(e){const t=(0,n.Rd)();(0,n.R3)({...t,stickers:{...t.stickers,favorite:{...t.stickers.favorite,stickers:t.stickers.favorite.stickers.filter((({id:t})=>t!==e.id))}}}),(0,P.t9)("faveSticker",{sticker:e,unfave:!0})}(a)})),(0,n.Q6)("toggleStickerSet",((e,t,s)=>{const{stickerSetId:n}=s,a=(0,i.Ny)(e,n);if(!a)return;const{accessHash:o,installedDate:r}=a;(0,P.t9)(r?"uninstallStickerSet":"installStickerSet",{stickerSetId:n,accessHash:o})})),(0,n.Q6)("loadEmojiKeywords",((e,t,s)=>{var a;const{language:o}=s;let r=e.emojiKeywords[o];null!==(a=r)&&void 0!==a&&a.isLoading||((0,n.R3)({...e,emojiKeywords:{...e.emojiKeywords,[o]:{...r,isLoading:!0}}}),(async()=>{var t;const s=await(0,P.t9)("fetchEmojiKeywords",{language:o,fromVersion:r?r.version:0});e=(0,n.Rd)(),r=e.emojiKeywords[o],s?(0,n.R3)({...e,emojiKeywords:{...e.emojiKeywords,[o]:{isLoading:!1,version:s.version,keywords:{...null===(t=r)||void 0===t?void 0:t.keywords,...s.keywords}}}}):(0,n.R3)({...e,emojiKeywords:{...e.emojiKeywords,[o]:{...r,isLoading:!1}}})})())})),(0,n.Q6)("setStickerSearchQuery",((e,t,s)=>{const{query:a}=s;a&&R((()=>{!async function(e,t){const s=await(0,P.t9)("searchStickers",{query:e,hash:void 0});if(!s)return;const a=(0,n.Rd)(),{setsById:o,added:i}=a.stickers,c=s.sets.map((({id:e})=>e));i.setIds&&i.setIds.forEach((t=>{if(!c.includes(t)){const{title:s}=o[t]||{};s&&(0,k.Z)(s,e)&&c.unshift(t)}})),(0,n.R3)((0,r.z3)(a,"search",s.hash,s.sets,c))}(a)}))})),(0,n.Q6)("setGifSearchQuery",((e,t,s)=>{const{query:n}=s;"string"==typeof n&&R((()=>{T(n)}))})),(0,n.Q6)("searchMoreGifs",(e=>{const{query:t,offset:s}=e.gifs.search;"string"==typeof t&&R((()=>{T(t,s)}))})),(0,n.Q6)("loadStickersForEmoji",((e,t,s)=>{const{emoji:a}=s,{hash:o}=e.stickers.forEmoji;R((()=>{!async function(e,t){let s=(0,n.Rd)();(0,n.R3)({...s,stickers:{...s.stickers,forEmoji:{...s.stickers.forEmoji,emoji:e}}});const a=await(0,P.t9)("fetchStickersForEmoji",{emoji:e,hash:t});s=(0,n.Rd)(),a&&s.stickers.forEmoji.emoji===e&&(s=(0,r.IM)(s,e,a.stickers,a.hash),(0,n.R3)(s))}(a,o)}))})),(0,n.Q6)("clearStickersForEmoji",(e=>({...e,stickers:{...e.stickers,forEmoji:{}}}))),(0,n.Q6)("openStickerSetShortName",((e,t,s)=>{const{stickerSetShortName:n}=s;return{...e,openedStickerSetShortName:n}}));var N=s(790);const B=(0,C.P2)((e=>e()),500,!1);async function A(e="",t,s,o,c,d){let l;if(o){const n=await(0,P.t9)("searchMessagesLocal",{chatOrUser:o,query:e,type:t,limit:a.Hk,offsetId:s,minDate:d,maxDate:c});if(n){const{messages:e,users:t,totalCount:s,nextOffsetId:a}=n;l={messages:e,users:t,chats:[],totalCount:s,nextRate:a}}}else l=await(0,P.t9)("searchMessagesGlobal",{query:e,offsetRate:s,limit:a.Hk,type:t,maxDate:c,minDate:d});let u=(0,n.Rd)();const m=(0,i.JX)(u);if(!l||""!==e&&e!==m)return void(0,n.R3)((0,r.xv)(u,{messages:!1}));const{messages:h,users:p,chats:f,totalCount:I,nextRate:v}=l;f.length&&(u=(0,r.fZ)(u,(0,g.ee)(f,"id"))),p.length&&(u=(0,r.Sh)(u,(0,g.ee)(p,"id"))),h.length&&(u=(0,r.m6)(u,h)),u=(0,r.px)(u,h,I,t,v),(0,n.R3)(u)}(0,n.Q6)("setGlobalSearchQuery",((e,t,s)=>{const{chatId:a}=e.globalSearch,{query:o}=s;o&&!a&&B((()=>{!async function(e){const t=await(0,P.t9)("searchChats",{query:e});let s=(0,n.Rd)();const a=(0,i.JX)(s);if(!t||!a||e!==a)return void(0,n.R3)((0,r.xv)(s,{chats:!1}));const{localChats:o,localUsers:c,globalChats:d,globalUsers:l}=t;(o.length||d.length)&&(s=(0,r.fZ)(s,(0,g.ee)([...o,...d],"id"))),(c.length||l.length)&&(s=(0,r.Sh)(s,(0,g.ee)([...c,...l],"id"))),s=(0,r.xv)(s,{chats:!1}),s=(0,r.No)(s,{localResults:{chatIds:o.map((({id:e})=>e)),userIds:c.map((({id:e})=>e))},globalResults:{...s.globalSearch.globalResults,chatIds:d.map((({id:e})=>e)),userIds:l.map((({id:e})=>e))}}),(0,n.R3)(s)}(o)}))})),(0,n.Q6)("setGlobalSearchDate",((e,t,s)=>{const{date:a}=s,o=a?(0,N.IS)(a):a,c=(0,r.No)(e,{date:a,query:"",resultsByType:{...e.globalSearch.resultsByType,text:{totalCount:void 0,foundIds:[],nextOffsetId:0}}});(0,n.R3)(c);const{chatId:d}=e.globalSearch;A("","text",void 0,d?(0,i.Z1)(e,d):void 0,o,a)})),(0,n.Q6)("searchMessagesGlobal",((e,t,s)=>{var n;const{query:a,resultsByType:o,chatId:r,date:c}=e.globalSearch,d=c?(0,N.IS)(c):c,{type:l}=s;A(a,l,null==o||null===(n=o[l])||void 0===n?void 0:n.nextOffsetId,r?(0,i.Z1)(e,r):void 0,d,c)})),(0,n.Q6)("searchTextMessagesLocal",(e=>{const{chatId:t,threadId:s}=(0,i.Bt)(e)||{},o=t?(0,i.Z1)(e,t):void 0,c=(0,i.n5)(e);if(!o||!c||!s)return;const{query:d,results:l}=c,m=null==l?void 0:l.nextOffsetId;let h;if(s!==u._f){const n=(0,i.tZ)(e,t,s);h=null==n?void 0:n.topMessageId}!async function(e,t,s,o,c){const d=await(0,P.t9)("searchMessagesLocal",{chatOrUser:e,type:"text",query:o,topMessageId:s,limit:a.pn,offsetId:c});if(!d)return;const{messages:l,users:u,totalCount:m,nextOffsetId:h}=d,p=(0,g.ee)(l,"id"),f=Object.keys(p).map(Number);let I=(0,n.Rd)();const v=(0,i.n5)(I);!v||o&&o!==v.query||(I=(0,r.c_)(I,e.id,p),I=(0,r.Sh)(I,(0,g.ee)(u,"id")),I=(0,r.dx)(I,e.id,t,f,m,h),(0,n.R3)(I))}(o,s,h,d,m)})),(0,n.Q6)("searchMediaMessagesLocal",(e=>{const t=(0,i.og)(e),s=t?e.users.byId[t]||e.chats.byId[t]:void 0,o=(0,i.we)(e);if(!s||!o)return;const{currentType:c,resultsByType:d}=o,l=c&&d&&d[c],u=null==l?void 0:l.nextOffsetId;c&&async function(e,t,s){const o=await(0,P.t9)("searchMessagesLocal",{chatOrUser:e,type:t,limit:a.EN,offsetId:s});if(!o)return;const{messages:c,users:d,totalCount:l,nextOffsetId:u}=o,m=(0,g.ee)(c,"id"),h=Object.keys(m).map(Number);let p=(0,n.Rd)();(0,i.we)(p)&&(p=(0,r.c_)(p,e.id,m),p=(0,r.Sh)(p,(0,g.ee)(d,"id")),p=(0,r.c1)(p,e.id,t,h,l,u),(0,n.R3)(p))}(s,c,u)})),(0,n.Q6)("searchMessagesByDate",((e,t,s)=>{const{timestamp:a}=s,{chatId:o}=(0,i.Bt)(e)||{};if(!o)return;const r=(0,i.Z1)(e,o);r&&async function(e,t){const s=await(0,P.t9)("findFirstMessageIdAfterDate",{chat:e,timestamp:t});s&&(0,n.uC)().focusMessage({chatId:e.id,messageId:s})}(r,a)})),(0,n.Q6)("checkPublicLink",((e,t,s)=>{const{chatId:a}=(0,i.Bt)(e)||{};if(!a)return;if(e.management.progress===m.wv.InProgress)return;const{username:o}=s;(async()=>{e=(0,r.H9)(e,m.wv.InProgress),e=(0,r.fw)(e,a,{isUsernameAvailable:void 0}),(0,n.R3)(e);const t=await(0,P.t9)("checkChatUsername",{username:o});e=(0,n.Rd)(),e=(0,r.H9)(e,t?m.wv.Complete:m.wv.Error),e=(0,r.fw)(e,a,{isUsernameAvailable:t}),(0,n.R3)(e)})()})),(0,n.Q6)("updatePublicLink",((e,t,s)=>{const{chatId:a}=(0,i.Bt)(e)||{};let o=a&&(0,i.Z1)(e,a);if(!a||!o)return;const{username:c}=s;(async()=>{if(e=(0,r.H9)(e,m.wv.InProgress),(0,n.R3)(e),(0,d.G9)(o)){if(o=await(0,P.t9)("migrateChat",o),!o)return;t.openChat({id:o.id})}const s=await(0,P.t9)("setChatUsername",{chat:o,username:c});e=(0,n.Rd)(),e=(0,r.H9)(e,s?m.wv.Complete:m.wv.Error),e=(0,r.fw)(e,a,{isUsernameAvailable:void 0}),(0,n.R3)(e)})()})),(0,n.Q6)("updatePrivateLink",(e=>{const{chatId:t}=(0,i.Bt)(e)||{},s=t&&(0,i.Z1)(e,t);t&&s&&(0,P.t9)("updatePrivateLink",{chat:s})}));var x=s(7358);async function L(){const e=await(0,P.t9)("fetchChats",{limit:a.Ov,archived:!0,withPinned:!0,serverTimeOffset:(0,n.Rd)().serverTimeOffset});if(!e)return;let t=(0,n.Rd)();t=(0,r.eD)(t,(0,g.ee)(e.users,"id")),t=(0,r.zn)(t,e.userStatusesById),t=(0,r.GL)(t,(0,g.ee)(e.chats,"id")),t=(0,r.Mg)(t,"archived",e.chatIds),t=(0,r.vv)(t,"archived",e),(0,n.R3)(t)}async function O(){let e=(0,n.Rd)();const{recentlyFoundChatIds:t}=e.globalSearch,{userIds:s}=e.contactList||{};if(!(s&&s.length||t&&t.length))return;const a=[...t||[],...s||[]].map((t=>(0,i.dy)(e,t))).filter(Boolean),o=await(0,P.t9)("fetchUsers",{users:a});if(!o)return;const{users:c,userStatusesById:d}=o;e=(0,n.Rd)(),e=(0,r.eD)(e,(0,g.ee)(c,"id")),e=(0,r.zn)(e,d),(0,n.R3)(e)}function F(e){return(0,P.t9)("fetchMessages",{chat:e,threadId:u._f,offsetId:e.lastReadInboxMessageId,addOffset:-(Math.round(a.hT/2)+1),limit:a.hT})}(0,n.Q6)("sync",((e,t)=>{!async function(e){a.eM&&console.log(">>> START SYNC"),await(0,P.t9)("fetchCurrentUser");const t=await async function(){var e;let t=(0,n.Rd)();const s=await(0,P.t9)("fetchChats",{limit:a.Ov,withPinned:!0,serverTimeOffset:t.serverTimeOffset,lastLocalServiceMessage:null===(e=(0,i.VF)(t))||void 0===e?void 0:e.message});if(!s)return;t=(0,n.Rd)();const{recentlyFoundChatIds:o}=t.globalSearch,{userIds:c}=t.contactList||{},{currentUserId:l}=t,m=[...o||[],...c||[],...l?[l]:[]],h=m.map((e=>(0,i.dy)(t,e))).filter(Boolean),p=m.map((e=>(0,i.Z1)(t,e))).filter(Boolean),{chatId:f}=(0,i.Bt)(t)||{};if(f){const e=(0,i.Z1)(t,f);if(e&&!m.includes(f)&&p.push(e),(0,d.YC)(f)){const e=(0,i.dy)(t,f);e&&!m.includes(f)&&h.push(e)}}return h.push(...s.users),p.push(...s.chats),t=(0,r.ps)(t,s.userStatusesById),t=(0,r.SL)(t,(0,g.ee)(p,"id")),t=(0,r.Mg)(t,"active",s.chatIds),t=(0,r.vv)(t,"active",s),Object.keys(s.draftsById).forEach((e=>{t=(0,r.pf)(t,e,u._f,"draft",s.draftsById[e])})),Object.keys(s.replyingToById).forEach((e=>{t=(0,r.pf)(t,e,u._f,"replyingToId",s.replyingToById[e])})),(0,n.R3)(t),f&&!t.chats.byId[f]&&(0,n.uC)().openChat({id:void 0}),h}();await async function(e){let t=!1,s=e||[],o=(0,n.Rd)();const{chatId:c,threadId:d}=(0,i.Bt)(o)||{},l=Object.keys(o.messages.byChatId).reduce(((e,t)=>{const s=(0,i.Ms)(o,t,u._f);return s&&(e[t]=s),e}),{});if(c){const e=await F(o.chats.byId[c]);o=(0,n.Rd)();const{chatId:l}=(0,i.Bt)(o)||{},m=d&&(0,i.tZ)(o,c,d);if(e&&l===c){const n=o.messages.byChatId[c],i=c===a.aw?o.serviceNotifications.map((({message:e})=>e)):[],l=[].concat(e.messages,i),h=(0,g.ee)(l,"id"),p=Object.keys(h).map(Number);if(o={...o,messages:{...o.messages,byChatId:{}}},o=(0,r.c_)(o,c,h),o=(0,r.xj)(o,c,u._f,p),o=(0,r.y9)(o,c,u._f,p),d&&m&&m.originChannelId){const{originChannelId:e}=m,t=o.messages.byChatId[e],s=await F(o.chats.byId[e]);if(s){const e=(0,g.ee)(s.messages,"id"),a=Object.keys(e).map(Number);o={...o,messages:{...o.messages,byChatId:{...o.messages.byChatId,[m.originChannelId]:{byId:e,threadsById:{[u._f]:{...null==t?void 0:t.threadsById[u._f],listedIds:a,viewportIds:a,outlyingIds:void 0}}},[c]:{...o.messages.byChatId[c],threadsById:{...o.messages.byChatId[c].threadsById,[d]:{...null==n?void 0:n.threadsById[d],outlyingIds:void 0}}}}}}}}o=(0,r.GL)(o,(0,g.ee)(e.chats,"id")),o=(0,r.j6)(o,c,e.threadInfos),t=!0,s=Array.prototype.concat(s,e.users)}}t||(o={...o,messages:{...o.messages,byChatId:{}}}),Object.keys(l).forEach((e=>{o=(0,r.pf)(o,e,u._f,"draft",l[e])})),e?o=(0,r.s5)(o,(0,g.ee)(s,"id")):s&&(o=(0,r.eD)(o,(0,g.ee)(s,"id"))),(0,n.R3)(o);const{chatId:m,messageId:h}=o.audioPlayer;m&&h&&!(0,i.hj)(o,m,h)&&(0,n.uC)().closeAudioPlayer()}(t),(0,n.R3)({...(0,n.Rd)(),lastSyncTime:Date.now()}),a.eM&&console.log(">>> FINISH SYNC"),e()}(t.afterSync)})),(0,n.Q6)("afterSync",(()=>{!async function(){a.eM&&console.log(">>> START AFTER-SYNC"),await Promise.all([O(),L()]),await(0,P.t9)("fetchCurrentUser"),(0,x.w)((0,i.A1)((0,n.Rd)())),a.eM&&console.log(">>> FINISH AFTER-SYNC")}()}));const U=(0,C.Ds)((e=>e()),500,!1,!0),$=(0,C.P2)((e=>e()),500,!1);function D(e,t,s){return{...e,inlineBots:{...e.inlineBots,byUsername:{...e.inlineBots.byUsername,[t]:s}}}}function q(e,t){return{...e,inlineBots:{...e.inlineBots,isLoading:t}}}(0,n.Q6)("loadFullUser",((e,t,s)=>{const{userId:n}=s,a=(0,i.dy)(e,n);if(!a)return;const{id:o,accessHash:r}=a;U((()=>(0,P.t9)("fetchFullUser",{id:o,accessHash:r})))})),(0,n.Q6)("loadUser",((e,t,s)=>{const{userId:a}=s,o=(0,i.dy)(e,a);o&&(async()=>{const t=await(0,P.t9)("fetchUsers",{users:[o]});if(!t)return;const{users:s,userStatusesById:a}=t;e=(0,n.Rd)(),e=(0,r.eD)(e,(0,g.ee)(s,"id")),(0,n.R3)((0,r.ps)(e,{...e.users.statusesById,...a})),(0,n.R3)(e)})()})),(0,n.Q6)("loadTopUsers",(e=>{const{topPeers:{lastRequestedAt:t}}=e;(!t||(0,p.b)(e.serverTimeOffset)-t>60)&&async function(){const e=await(0,P.t9)("fetchTopUsers");if(!e)return;const{ids:t,users:s}=e;let a=(0,n.Rd)();a=(0,r.Sh)(a,(0,g.ee)(s,"id")),a={...a,topPeers:{...a.topPeers,userIds:t,lastRequestedAt:(0,p.b)(a.serverTimeOffset)}},(0,n.R3)(a)}()})),(0,n.Q6)("loadContactList",(()=>{!async function(){const e=await(0,P.t9)("fetchContactList");if(!e)return;let t=(0,r.Sh)((0,n.Rd)(),(0,g.ee)(e.users,"id"));t=(0,r.fZ)(t,(0,g.ee)(e.chats,"id"));const s=e=>e.lastName||e.firstName||"",a=new Intl.Collator("en-US"),o=e.users.sort(((e,t)=>a.compare(s(e),s(t)))).filter((e=>!e.isSelf));(0,n.R3)({...t,contactList:{userIds:o.map((e=>e.id))}})}()})),(0,n.Q6)("loadCurrentUser",(()=>{(0,P.t9)("fetchCurrentUser")})),(0,n.Q6)("loadCommonChats",(e=>{var t;const{chatId:s}=(0,i.Bt)(e)||{},a=s?(0,i.dy)(e,s):void 0;!a||(0,d.cS)(a)||null!==(t=a.commonChats)&&void 0!==t&&t.isFullyLoaded||(async()=>{var t,s;const o=null===(t=a.commonChats)||void 0===t?void 0:t.maxId,i=await(0,P.t9)("fetchCommonChats",a.id,a.accessHash,o);if(!i)return;const{chats:c,chatIds:d,isFullyLoaded:l}=i;e=(0,n.Rd)(),c.length&&(e=(0,r.fZ)(e,(0,g.ee)(c,"id"))),e=(0,r.Nq)(e,a.id,{commonChats:{maxId:d.length?d[d.length-1]:"0",ids:(0,g.Tw)(((null===(s=a.commonChats)||void 0===s?void 0:s.ids)||[]).concat(d)),isFullyLoaded:l}}),(0,n.R3)(e)})()})),(0,n.Q6)("updateContact",((e,t,s)=>{const{userId:a,isMuted:o,firstName:c,lastName:d}=s;!async function(e,t,s,a){const o=(0,n.Rd)(),c=(0,i.dy)(o,e);if(!c)return;let d;if((0,n.uC)().updateChatMutedState({chatId:e,isMuted:t}),(0,n.R3)((0,r.H9)((0,n.Rd)(),m.wv.InProgress)),c.phoneNumber)d=await(0,P.t9)("updateContact",{phone:c.phoneNumber,firstName:s,lastName:a});else{const{id:e,accessHash:t}=c;d=await(0,P.t9)("addContact",{id:e,accessHash:t,phoneNumber:"",firstName:s,lastName:a})}d&&(0,n.R3)((0,r.Nq)((0,n.Rd)(),c.id,{firstName:s,lastName:a})),(0,n.R3)((0,r.H9)((0,n.Rd)(),m.wv.Complete))}(a,o,c,d)})),(0,n.Q6)("deleteContact",((e,t,s)=>{const{userId:a}=s;!async function(e){const t=(0,n.Rd)(),s=(0,i.dy)(t,e);if(!s)return;const{id:a,accessHash:o}=s;await(0,P.t9)("deleteContact",{id:a,accessHash:o})}(a)})),(0,n.Q6)("loadProfilePhotos",((e,t,s)=>{const{profileId:a}=s,o=(0,d.YC)(a),c=o?(0,i.dy)(e,a):void 0,l=o?void 0:(0,i.Z1)(e,a);(c||l)&&(async()=>{const e=await(0,P.t9)("fetchProfilePhotos",c,l);if(!e||!e.photos)return;let t=(0,n.Rd)();o?t=(0,r.Nq)(t,a,{photos:e.photos}):(t=(0,r.Sh)(t,(0,g.ee)(e.users,"id")),t=(0,r.a4)(t,a,{photos:e.photos})),(0,n.R3)(t)})()})),(0,n.Q6)("setUserSearchQuery",((e,t,s)=>{const{query:a}=s;a&&$((()=>{!async function(e){const t=await(0,P.t9)("searchChats",{query:e});let s=(0,n.Rd)();const a=s.userSearch.query;if(!t||!a||e!==a)return void(0,n.R3)((0,r.Q3)(s,!1));const{localUsers:o,globalUsers:i}=t;let c,d;o.length&&(s=(0,r.Sh)(s,(0,g.ee)(o,"id")),c=o.map((({id:e})=>e))),i.length&&(s=(0,r.Sh)(s,(0,g.ee)(i,"id")),d=i.map((({id:e})=>e))),s=(0,r.Q3)(s,!1),s=(0,r.Lm)(s,{localUserIds:c,globalUserIds:d}),(0,n.R3)(s)}(a)}))})),(0,n.Q6)("addContact",((e,t,s)=>{const{userId:n}=s,a=(0,i.dy)(e,n);a&&(0,P.t9)("addContact",(0,g.ei)(a,["id","accessHash","firstName","lastName","phoneNumber"]))}));const Q=(0,C.Ds)((e=>e()),500,!1);async function G(e,t,s,n,a){await(0,P.t9)("sendMessage",{chat:e,text:s,replyingTo:n,sendAs:a})}(0,n.Q6)("clickInlineButton",((e,t,s)=>{const{button:o}=s;switch(o.type){case"command":t.sendBotCommand({command:o.value});break;case"url":o.value.match(a.FS)||o.value.match(a.g$)?t.openTelegramLink({url:o.value}):t.toggleSafeLinkModal({url:o.value});break;case"callback":{const t=(0,i.jr)(e);if(!t)return;!async function(e,t,s){const a=await(0,P.t9)("answerCallbackButton",{chatId:e.id,accessHash:e.accessHash,messageId:t,data:s});if(!a)return;const{showDialog:o,showNotification:r,toggleSafeLinkModal:i}=(0,n.uC)(),{message:c,alert:d,url:l}=a;d?o({data:{message:c||"Error"}}):c?r({message:c}):l&&i({url:l})}(t,o.messageId,o.value);break}case"requestPoll":t.openPollModal();break;case"requestSelfContact":{const s=e.currentUserId?(0,i.dy)(e,e.currentUserId):void 0;if(!s)return;t.showDialog({data:{phoneNumber:s.phoneNumber,firstName:s.firstName,lastName:s.lastName,userId:s.id}});break}case"buy":{const s=(0,i.jr)(e),{messageId:n,value:a}=o;if(!s)return;a?t.getReceipt({receiptMessageId:a,chatId:s.id,messageId:n}):(t.getPaymentForm({chat:s,messageId:n}),t.setInvoiceMessageInfo((0,i.hj)(e,s.id,n)),t.openPaymentModal({chatId:s.id,messageId:n}));break}}})),(0,n.Q6)("sendBotCommand",((e,t,s)=>{const{command:n,chatId:a}=s,{currentUserId:o}=e,r=a?(0,i.Z1)(e,a):(0,i.jr)(e),c=(0,i.Bt)(e);if(!o||!r||!c)return;const{threadId:d}=c;t.setReplyingToId({messageId:void 0}),t.clearWebPagePreview({chatId:r.id,threadId:d,value:!1}),G(r,0,n,(0,i.Yy)(e,r.id,d),(0,i._5)(e,a))})),(0,n.Q6)("restartBot",((e,t,s)=>{const{chatId:a}=s,{currentUserId:o}=e,c=(0,i.jr)(e),d=o&&(0,i.IK)(e,a);o&&c&&d&&(async()=>{await(0,P.t9)("unblockContact",d.id,d.accessHash)&&((0,n.R3)((0,r.rB)((0,n.Rd)(),d.id)),G(c,0,"/start",void 0,(0,i._5)(e,a)))})()})),(0,n.Q6)("loadTopInlineBots",(e=>{const{lastRequestedAt:t}=e.topInlineBots;t&&(0,p.b)(e.serverTimeOffset)-t<60||(async()=>{const t=await(0,P.t9)("fetchTopInlineBots");if(!t)return;const{ids:s,users:a}=t;let o=(0,n.Rd)();o=(0,r.Sh)(o,(0,g.ee)(a,"id")),o={...o,topInlineBots:{...o.topInlineBots,userIds:s,lastRequestedAt:(0,p.b)(e.serverTimeOffset)}},(0,n.R3)(o)})()})),(0,n.Q6)("queryInlineBot",((e,t,s)=>{const{chatId:a,username:o,query:c,offset:d}=s;(async()=>{let t=e.inlineBots.byUsername[o];if(!1!==t){if(void 0===t){const{user:s,chat:a}=await(0,P.t9)("fetchInlineBot",{username:o})||{};if(e=(0,n.Rd)(),!s||!a)return void(0,n.R3)(D(e,o,!1));e=(0,r.Sh)(e,{[s.id]:s}),e=(0,r.fZ)(e,{[a.id]:a}),t={id:s.id,query:"",offset:"",switchPm:void 0,canLoadMore:!0,results:[]},e=D(e,o,t),(0,n.R3)(e)}(c!==t.query||t.canLoadMore)&&Q((()=>{!async function({username:e,inlineBotData:t,chatId:s,query:a,offset:o}){let r=(0,n.Rd)();const c=(0,i.dy)(r,t.id),d=(0,i.Z1)(r,s);if(!c||!d)return;const l=t.query!==a;r=q(r,!0),r=D(r,e,{...t,query:a,...l&&{offset:void 0,results:[]}}),(0,n.R3)(r);const u=await(0,P.t9)("fetchInlineBotResults",{bot:c,chat:d,query:a,offset:l?void 0:o}),m=r.inlineBots.byUsername[e];if(r=q((0,n.Rd)(),!1),!u||!m||a!==m.query)return void(0,n.R3)(r);const h=new Set((m.results||[]).map((e=>e.id))),g=u.results.filter((e=>!h.has(e.id)));r=D(r,e,{...m,help:u.help,...g.length&&{isGallery:u.isGallery},...u.switchPm&&{switchPm:u.switchPm},canLoadMore:u.results.length>0&&Boolean(u.nextOffset),results:""===m.offset||m.offset===u.nextOffset?u.results:(m.results||[]).concat(g),offset:g.length?u.nextOffset:""}),(0,n.R3)(r)}({username:o,inlineBotData:t,chatId:a,query:c,offset:d})}))}})()})),(0,n.Q6)("sendInlineBotResult",((e,t,s)=>{const{id:n,queryId:a}=s,o=(0,i.Bt)(e);if(!o||!n)return;const{chatId:r,threadId:c}=o,d=(0,i.Z1)(e,r);t.setReplyingToId({messageId:void 0}),t.clearWebPagePreview({chatId:r,threadId:c,value:!1}),(0,P.t9)("sendInlineBotResult",{chat:d,resultId:n,queryId:a,replyingTo:(0,i.Yy)(e,r,c),sendAs:(0,i._5)(e,r)})})),(0,n.Q6)("resetInlineBot",((e,t,s)=>{const{username:a}=s;let o=e.inlineBots.byUsername[a];o&&(o={id:o.id,query:"",offset:"",switchPm:void 0,canLoadMore:!0,results:[]},(0,n.R3)(D(e,a,o)))})),(0,n.Q6)("startBot",((e,t,s)=>{const{botId:n,param:a}=s,o=(0,i.dy)(e,n);o&&(async()=>{await(0,P.t9)("startBot",{bot:o,startParam:a})})()})),s(9667),(0,n.Q6)("loadPasswordInfo",(()=>{(async()=>{const e=await(0,P.t9)("getPasswordInfo");if(!e)return;let t=(0,n.Rd)();t=(0,r.BI)(t,{hasPassword:e.hasPassword}),t=(0,r.IE)(t,{hint:e.hint}),(0,n.R3)(t)})()})),(0,n.Q6)("checkPassword",((e,t,s)=>{const{currentPassword:a,onSuccess:o}=s;(0,n.R3)((0,r.IE)(e,{isLoading:!0,error:void 0})),(async()=>{const e=await(0,P.t9)("checkPassword",a);(0,n.R3)((0,r.IE)((0,n.Rd)(),{isLoading:!1})),e&&o()})()})),(0,n.Q6)("clearPassword",((e,t,s)=>{const{currentPassword:a,onSuccess:o}=s;(0,n.R3)((0,r.IE)(e,{isLoading:!0,error:void 0})),(async()=>{const e=await(0,P.t9)("clearPassword",a);(0,n.R3)((0,r.IE)((0,n.Rd)(),{isLoading:!1})),e&&o()})()})),(0,n.Q6)("updatePassword",((e,t,s)=>{const{currentPassword:a,password:o,hint:i,email:c,onSuccess:d}=s;(0,n.R3)((0,r.IE)(e,{isLoading:!0,error:void 0})),(async()=>{const e=await(0,P.t9)("updatePassword",a,o,i,c);(0,n.R3)((0,r.IE)((0,n.Rd)(),{isLoading:!1})),e&&d()})()})),(0,n.Q6)("updateRecoveryEmail",((e,t,s)=>{const{currentPassword:a,email:o,onSuccess:i}=s;(0,n.R3)((0,r.IE)(e,{isLoading:!0,error:void 0})),(async()=>{const e=await(0,P.t9)("updateRecoveryEmail",a,o);(0,n.R3)((0,r.IE)((0,n.Rd)(),{isLoading:!1,waitingEmailCodeLength:void 0})),e&&i()})()})),(0,n.Q6)("provideTwoFaEmailCode",((e,t,s)=>{const{code:n}=s;(0,P.t9)("provideRecoveryEmailCode",n)})),(0,n.Q6)("clearTwoFaError",(e=>(0,r.IE)(e,{error:void 0}))),(0,n.Q6)("validateRequestedInfo",((e,t,s)=>{const{requestInfo:a,saveInfo:o}=s,c=(0,i.gx)(e),d=c&&(0,i.Z1)(e,c),l=(0,i.Mz)(e);d&&l&&async function(e,t,s,a){const o=await(0,P.t9)("validateRequestedInfo",{chat:e,messageId:t,requestInfo:s,shouldSave:a});if(!o)return;const{id:i,shippingOptions:c}=o;if(!i)return;let d=(0,r.vT)((0,n.Rd)(),i);c?(d=(0,r.TM)(d,c),d=(0,r.Q$)(d,m.KB.Shipping)):d=(0,r.Q$)(d,m.KB.PaymentInfo),(0,n.R3)(d)}(d,l,a,o)})),(0,n.Q6)("getPaymentForm",((e,t,s)=>{const{chat:a,messageId:o}=s;a&&o&&async function(e,t){const s=await(0,P.t9)("getPaymentForm",{chat:e,messageId:t});if(!s)return;let a=(0,r._7)((0,n.Rd)(),s),o=m.KB.PaymentInfo;a.payment.invoice&&(a.payment.invoice.shippingAddressRequested||a.payment.invoice.nameRequested||a.payment.invoice.phoneRequested||a.payment.invoice.emailRequested)&&(o=m.KB.ShippingInfo),a=(0,r.Q$)(a,o),(0,n.R3)(a)}(a,o)})),(0,n.Q6)("getReceipt",((e,t,s)=>{const{receiptMessageId:a,chatId:o,messageId:c}=s,d=o&&(0,i.Z1)(e,o);c&&a&&d&&async function(e,t,s){const a=await(0,P.t9)("getReceipt",e,s);if(!a)return;let o=(0,n.Rd)();const c=(0,i.hj)(o,e.id,t);o=(0,r.Dq)(o,a,c),(0,n.R3)(o)}(d,c,a)})),(0,n.Q6)("clearPaymentError",(e=>{(0,n.R3)({...e,payment:{...e.payment,error:void 0}})})),(0,n.Q6)("clearReceipt",(e=>{(0,n.R3)({...e,payment:{...e.payment,receipt:void 0}})})),(0,n.Q6)("sendCredentialsInfo",((e,t,s)=>{const a=(0,i.$$)(e);if(!a)return;const{credentials:o}=s,{data:c}=o;!async function(e,t){const s=function(e){const t=Object.keys(e).map((t=>`${t}=${e[t]}`)).join("&");return t.length>0?`?${t}`:""}({"card[number]":e.cardNumber,"card[exp_month]":e.expiryMonth,"card[exp_year]":e.expiryYear,"card[cvc]":e.cvv,"card[address_zip]":e.zip,"card[address_country]":e.country}),a=await fetch(`https://api.stripe.com/v1/tokens${s}`,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/x-www-form-urlencoded",Authorization:`Bearer ${t}`}}),o=await a.json();if(o.error){const e=(0,d.Ow)(o.error),t=(0,n.Rd)();return void(0,n.R3)({...t,payment:{...t.payment,error:{...e}}})}let i=(0,r.QH)((0,n.Rd)(),{type:o.type,id:o.id});i=(0,r.Q$)(i,m.KB.Checkout),(0,n.R3)(i)}(c,a)})),(0,n.Q6)("sendPaymentForm",((e,t,s)=>{const{shippingOptionId:a,saveCredentials:o}=s,c=(0,i.gx)(e),d=c&&(0,i.Z1)(e,c),l=(0,i.Mz)(e),u=(0,i.eh)(e),m=(0,i.sp)(e),h=(0,i.$$)(e),g=(0,i.i3)(e);d&&l&&h&&u&&async function(e,t,s,a,o,i){if(await(0,P.t9)("sendPaymentForm",{chat:e,messageId:t,formId:s,credentials:a,requestedInfoId:o,shippingOptionId:i})){const e=(0,r.bp)((0,n.Rd)());(0,n.R3)((0,r.WY)(e))}}(d,l,u,{save:o,data:g},m,a)})),(0,n.Q6)("setPaymentStep",((e,t,s={})=>(0,r.Q$)(e,s.step||m.KB.ShippingInfo))),(0,n.Q6)("setInvoiceMessageInfo",((e,t,s)=>(0,r.nA)(e,s))),s(4907);var j=s(8406);const H=(0,C.P2)((e=>e()),500,!0);(0,n.Q6)("apiUpdate",((e,t,s)=>{switch(s["@type"]){case"updateChat":{s.noTopChatsRequest||(0,i.N)(e,s.id)||t.loadTopChats();const a=(0,r.a4)(e,s.id,s.chat,s.newProfilePhoto);(0,n.R3)(a),H((()=>(0,x.w)((0,i.A1)((0,n.Rd)())))),s.chat.id&&(0,j.Vr)({chatId:s.chat.id,lastReadInboxMessageId:s.chat.lastReadInboxMessageId});break}case"updateChatJoin":{const a=(0,i.Ek)(e,s.id);if(!a)break;e=(0,r.B1)(e,a,[s.id]),e=(0,r.a4)(e,s.id,{isNotJoined:!1}),(0,n.R3)(e);const o=(0,i.Z1)(e,s.id);o&&t.requestChatUpdate({chatId:o.id});break}case"updateChatLeave":(0,n.R3)((0,r.Dd)(e,s.id));break;case"updateChatInbox":(0,n.R3)((0,r.a4)(e,s.id,s.chat)),H((()=>(0,x.w)((0,i.A1)((0,n.Rd)()))));break;case"updateChatTypingStatus":{const{id:t,typingStatus:a}=s;(0,n.R3)((0,r.a4)(e,t,{typingStatus:a})),setTimeout((()=>{const e=(0,n.Rd)(),s=(0,i.Z1)(e,t);s&&a&&s.typingStatus&&s.typingStatus.timestamp===a.timestamp&&(0,n.R3)((0,r.a4)(e,t,{typingStatus:void 0}))}),6e3);break}case"newMessage":{const{message:a}=s,{chatId:o,threadId:c,type:d}=(0,i.Bt)(e)||{};if(a.senderId===e.currentUserId&&!a.isFromScheduled)return;const l=(0,i.Z1)(e,s.chatId);if(!l)return;"thread"===d&&c===u._f&&s.chatId===o?setTimeout((()=>{t.requestChatUpdate({chatId:s.chatId})}),1500):(0,n.R3)((0,r.a4)(e,s.chatId,{unreadCount:l.unreadCount?l.unreadCount+1:1,...s.message.hasUnreadMention&&{unreadMentionsCount:l.unreadMentionsCount?l.unreadMentionsCount+1:1}})),(0,x.w)((0,i.A1)((0,n.Rd)())),(0,j.zP)({chat:l,message:a});break}case"updateCommonBoxMessages":case"updateChannelMessages":{const{ids:t,messageUpdate:a}=s;if(!1!==a.hasUnreadMention)return;t.forEach((t=>{const n="channelId"in s?s.channelId:(0,i.X5)(e,t),a=(0,i.Z1)(e,n);null!=a&&a.unreadMentionsCount&&(e=(0,r.a4)(e,n,{unreadMentionsCount:a.unreadMentionsCount-1}))})),(0,n.R3)(e);break}case"updateChatFullInfo":{const{fullInfo:t}=s,a=e.chats.byId[s.id];if(!a)return;(0,n.R3)((0,r.a4)(e,s.id,{fullInfo:{...a.fullInfo,...t}}));break}case"updatePinnedChatIds":{const{ids:t,folderId:o}=s,r=o===a.WS?"archived":"active";e={...e,chats:{...e.chats,orderedPinnedIds:{...e.chats.orderedPinnedIds,[r]:t.length?t:void 0}}},(0,n.R3)(e);break}case"updateChatPinned":{const{id:t,isPinned:o}=s,r=(0,i.Ek)(e,t);if(r){const{[r]:s}=e.chats.orderedPinnedIds;let n=s||[];if(o){if(!n.includes(t)){if("active"===r&&n.length>=a.EG){const t=e.chats.listIds.active;n=n.filter((e=>t&&t.includes(e)))}n=[t,...n]}}else n=n.filter((e=>e!==t));e={...e,chats:{...e.chats,orderedPinnedIds:{...e.chats.orderedPinnedIds,[r]:n.length?n:void 0}}}}(0,n.R3)(e);break}case"updateChatListType":{const{id:t,folderId:a}=s;(0,n.R3)((0,r.Pi)(e,t,a));break}case"updateChatFolder":{const{id:t,folder:a}=s,{byId:o,orderedIds:r}=e.chatFolders,i=a?{...o,[t]:a}:(0,g.ei)(o,Object.keys(o).map(Number).filter((e=>e!==t))),c=a?r&&r.includes(t)?r:[...r||[],t]:r?r.filter((e=>e!==t)):void 0;(0,n.R3)({...e,chatFolders:{...e.chatFolders,byId:i,orderedIds:c}});break}case"updateChatFoldersOrder":{const{orderedIds:t}=s;(0,n.R3)({...e,chatFolders:{...e.chatFolders,orderedIds:t}});break}case"updateRecommendedChatFolders":{const{folders:t}=s;(0,n.R3)({...e,chatFolders:{...e.chatFolders,recommended:t}});break}case"updateChatMembers":{var o;const t=e.chats.byId[s.id],{replacedMembers:a,addedMember:i,deletedMemberId:c}=s;if(!t)return;let d=!1,l=null!==(o=t.fullInfo)&&void 0!==o&&o.members?[...t.fullInfo.members]:[];if(a)l=a,d=!0;else if(i)l.length&&l.some((e=>e.userId===i.userId))||(l.push(i),d=!0);else if(l.length&&c){const e=l.findIndex((e=>e.userId===c));e>-1&&(l.slice(e,1),d=!0)}if(d){const a=l.filter((({isOwner:e,isAdmin:t})=>e||t));(0,n.R3)((0,r.a4)(e,s.id,{membersCount:l.length,fullInfo:{...t.fullInfo,members:l,adminMembers:a}}))}break}case"deleteProfilePhotos":{const{chatId:t,ids:a}=s,o=e.chats.byId[t];null!=o&&o.photos&&(0,n.R3)((0,r.a4)(e,t,{photos:o.photos.filter((e=>!a.includes(e.id)))}));break}case"draftMessage":{const{chatId:t,formattedText:a,date:o,replyingToId:i}=s;e.chats.byId[t]&&(e=(0,r.pf)(e,t,u._f,"draft",a),e=(0,r.pf)(e,t,u._f,"replyingToId",i),e=(0,r.a4)(e,t,{draftDate:o}),(0,n.R3)(e));break}case"showInvite":{const{data:e}=s;t.showDialog({data:e});break}}}));const _=350;function z(e,t,s,n,a=!1){const o=a?(0,i.Tm)(e,t,s):(0,i.hj)(e,t,s);if(o&&n.content){const{photo:e,video:t,sticker:s,document:a}=(0,d.qp)(o);e&&n.content.photo?(n.content.photo.blobUrl=e.blobUrl,n.content.photo.thumbnail=e.thumbnail):t&&n.content.video?n.content.video.blobUrl=t.blobUrl:s&&n.content.sticker?n.content.sticker.isPreloadedGlobally=s.isPreloadedGlobally:a&&n.content.document&&(n.content.document.previewBlobUrl=a.previewBlobUrl)}return a?(0,r.P4)(e,t,s,n):(0,r.cY)(e,t,s,n)}function V(e,t,s,n){const{chatId:a}=s,{threadInfo:o}=(0,i.Db)(e,a,s)||{};if(!o&&s.replyToMessageId){const o=(0,i.hj)(e,a,s.replyToMessageId);o?e=(0,r.lG)(e,o,a,s.id,n):t.loadMessage({chatId:a,messageId:s.replyToMessageId,threadUpdate:{isDeleting:n,lastMessageId:s.id}})}return e}function K(e,t,s){const{id:n,chatId:a}=s,{threadInfo:o,firstMessageId:c}=(0,i.Db)(e,a,s)||{},l=(0,i.Z1)(e,a),m=(null==l?void 0:l.unreadCount)&&!(0,i.gb)(e,a,u._f);if(e=V(e,t,s),o&&(!c&&(0,d.CI)(s)||(e=(0,r.xj)(e,a,o.threadId,[n]),(0,i.b9)(e,a,o.threadId)&&(e=(0,r.$S)(e,a,o.threadId,n),c||(e=(0,r.pf)(e,a,o.threadId,"firstMessageId",s.id)))),e=(0,r.pf)(e,a,o.threadId,"threadInfo",{...o,lastMessageId:s.id,messagesCount:o.messagesCount+1})),m)return e;if(e=(0,r.xj)(e,a,u._f,[n]),(0,i.b9)(e,a,u._f)){const t=(0,i.It)(e,a,u._f),s=(0,r.$S)(e,a,u._f,n),o=(0,i.Cb)(s,a,u._f);t&&!o.includes(t)||(e=s)}return e}function Y(e,t,s,n=!1){var a;const{chats:o}=e,i=null===(a=o.byId[t])||void 0===a?void 0:a.lastMessage;return!i||n||i.id===s.id||i.id===s.previousLocalId||s.id>i.id?(0,r.a4)(e,t,{lastMessage:s}):e}function W(e,t){const s=(0,i.Zw)(e,t),n=(0,i.gb)(e,t,u._f);if(!s||!n)return;let a=n.length;for(;a--;){const e=s[n[a]];if(!e.isDeleting)return e}}function X(e,t,s,a){if(e){t.forEach((t=>{const s=W(a=(0,r.cY)(a,e,t,{isDeleting:!0}),e);s&&(a=Y(a,e,s,!0))})),(0,n.R3)(a),s.requestChatUpdate({chatId:e});const o=[];return t.forEach((t=>{const n=(0,i.hj)(a,e,t);if(!n)return;a=V(a,s,n,!0);const{threadInfo:r}=(0,i.Db)(a,e,n)||{};r&&o.push(r.threadId)})),(0,n.R3)(a),void setTimeout((()=>{(0,n.R3)((0,r.K4)((0,n.Rd)(),e,t)),(0,g.Tw)(o).forEach((t=>{s.requestThreadInfoUpdate({chatId:e,threadId:t})}))}),_)}const o=[];t.forEach((e=>{const t=(0,i.X5)(a,e);if(t){o.push(t);const s=W(a=(0,r.cY)(a,t,e,{isDeleting:!0}),t);s&&(a=Y(a,t,s,!0)),setTimeout((()=>{(0,n.R3)((0,r.K4)((0,n.Rd)(),t,[e]))}),_)}})),(0,n.R3)(a),(0,g.Tw)(o).forEach((e=>{s.requestChatUpdate({chatId:e})}))}(0,n.Q6)("apiUpdate",((e,t,s)=>{switch(s["@type"]){case"newMessage":{const{chatId:o,id:c,message:l,shouldForceReply:m}=s;e=K(e=z(e,o,c,l),t,l),l.threadInfo&&(e=(0,r.Xg)(e,l.threadInfo.chatId,l.threadInfo.threadId,l.threadInfo)),(0,n.R3)(e);const h=(0,i.hj)(e,o,c);if((0,i.hg)(e,o,l)){var a;if(l.isOutgoing&&(null===(a=l.content)||void 0===a||!a.action)){const s=(0,i.Bt)(e);s&&t.focusMessage({chatId:o,threadId:s.threadId,messageId:l.id,noHighlight:!0,isResizingContainer:!0})}const{threadInfo:s}=(0,i.Db)(e,o,l)||{};s&&t.requestThreadInfoUpdate({chatId:o,threadId:s.threadId}),(0,d.CI)(l)||setTimeout((()=>{let e=(0,n.Rd)();m&&(e=(0,r.pf)(e,o,u._f,"replyingToId",c)),(0,n.R3)(Y(e,o,h))}),_)}else(0,n.R3)(Y((0,n.Rd)(),o,h));(0,i.N)(e,o)||t.loadTopChats();break}case"newScheduledMessage":{const{chatId:t,id:a,message:o}=s;e=z(e,t,a,o,!0);const c=(0,i.qy)(e,t)||[];e=(0,r.pf)(e,t,u._f,"scheduledIds",(0,g.Tw)([...c,a])),(0,n.R3)(e);break}case"updateMessage":{var o,c;const{chatId:a,id:d,message:l}=s;if(!(0,i.hj)(e,a,d))return;e=z(e,a,d,l);const m=(0,i.hj)(e,a,d);l.threadInfo&&(e=(0,r.Xg)(e,l.threadInfo.chatId,l.threadInfo.threadId,l.threadInfo)),e=Y(e,a,m),(0,n.R3)(e);const h=(0,i.Z1)(e,a);h&&!l.isOutgoing&&(null===(o=h.lastMessage)||void 0===o?void 0:o.id)===l.id&&(0,i.xo)(e,h)&&(0,i.hg)(e,a,l)&&(0,i.b9)(e,a,(null===(c=l.threadInfo)||void 0===c?void 0:c.threadId)||u._f)&&t.focusLastMessage();break}case"updateScheduledMessage":{const{chatId:t,id:a,message:o}=s;if(!(0,i.Tm)(e,t,a))return;e=z(e,t,a,o,!0);const c=Object.keys((0,i.Fn)(e,t)||{}).map(Number).sort(((e,t)=>t-e));e=(0,r.pf)(e,t,u._f,"scheduledIds",c),(0,n.R3)(e);break}case"updateMessageSendSucceeded":{const{chatId:a,localId:o,message:c}=s;e=K(e,t,c);const d=(0,i.hj)(e,a,o);e=(0,r.K4)(e,a,[o]),c.isScheduled&&(e=(0,r.bV)(e,a,[o])),e=(0,r.cY)(e,a,c.id,{...d,...c,previousLocalId:o});const l=(0,i.hj)(e,a,c.id);e=Y(e,a,l);const u=(0,i.Db)(e,a,c);null!=u&&u.threadInfo&&(t.markMessageListRead({maxId:c.id}),e=(0,r.pf)(e,a,u.threadInfo.threadId,"threadInfo",{...u.threadInfo,lastMessageId:c.id,lastReadInboxMessageId:c.id})),(0,n.R3)(e);break}case"updateScheduledMessageSendSucceeded":{const{chatId:t,localId:a,message:o}=s,c=(0,i.qy)(e,t)||[];e=(0,r.pf)(e,t,u._f,"scheduledIds",[...c,o.id]);const d=(0,i.Tm)(e,t,a);e=(0,r.bV)(e,t,[a]),e=(0,r.P4)(e,t,o.id,{...d,...o,previousLocalId:a}),(0,n.R3)(e);break}case"updatePinnedIds":{const{chatId:t,isPinned:a,messageIds:o}=s,c=(0,i.KB)(e,t)||[],d=a?[...c,...o].sort(((e,t)=>t-e)):c.filter((e=>!o.includes(e)));(0,n.R3)((0,r.pf)(e,t,u._f,"pinnedIds",d));break}case"updateThreadInfo":{const{chatId:t,threadId:a,threadInfo:o,firstMessageId:c}=s,d={...(0,i.tZ)(e,t,a),...o};if(!d.threadId)return;e=(0,r.Xg)(e,t,a,d),c&&(e=(0,r.pf)(e,t,a,"firstMessageId",c)),(0,n.R3)(e);break}case"resetMessages":{const{id:a}=s,o=(0,i.Zw)(e,a);o&&!(0,d.YC)(a)&&(e=(0,r.K4)(e,a,Object.keys(o).map(Number)),(0,n.R3)(e),t.loadFullChat({chatId:a,force:!0}));break}case"deleteMessages":{const{ids:n,chatId:a}=s;X(a,n,t,e);break}case"deleteScheduledMessages":{const{ids:t,chatId:a}=s;!function(e,t,s,a){e&&(t.forEach((t=>{a=(0,r.P4)(a,e,t,{isDeleting:!0})})),(0,n.R3)(a),setTimeout((()=>{a=(0,r.bV)((0,n.Rd)(),e,t);const s=(0,i.Fn)(a,e);a=(0,r.pf)(a,e,u._f,"scheduledIds",Object.keys(s||{}).map(Number)),(0,n.R3)(a)}),_))}(a,t,0,e);break}case"deleteHistory":{const{chatId:n}=s,a=e.messages.byChatId[n];a?X(n,Object.keys(a.byId).map(Number),t,e):t.requestChatUpdate({chatId:n});break}case"updateCommonBoxMessages":{const{ids:t,messageUpdate:a}=s;t.forEach((t=>{const s=(0,i.X5)(e,t);s&&(e=(0,r.cY)(e,s,t,a))})),(0,n.R3)(e);break}case"updateChannelMessages":{const{channelId:t,ids:a,messageUpdate:o}=s;a.forEach((s=>{e=(0,r.cY)(e,t,s,o)})),(0,n.R3)(e);break}case"updateMessagePoll":{const{pollId:t,pollUpdate:a}=s,o=(0,i.ZB)(e,t);if(null!=o&&o.content.poll){const t={...o.content.poll,...a},{results:s}=t.results||{};if(s&&!s.some((e=>e.isChosen))){const{results:e}=o.content.poll.results,n=e&&e.filter((e=>e.isChosen));n&&n.forEach((e=>{const n=s.findIndex((t=>t.option===e.option));n>=0&&(t.results.results[n].isChosen=!0)}))}(0,n.R3)((0,r.cY)(e,o.chatId,o.id,{content:{...o.content,poll:t}}))}break}case"updateMessagePollVote":{const{pollId:t,userId:a,options:o}=s,c=(0,i.ZB)(e,t);if(!c||!c.content.poll||!c.content.poll.results)break;const{poll:d}=c.content,{recentVoterIds:l,totalVoters:u,results:m}=d.results,h=l?[...l]:[],g=u?u+1:1,p=m?[...m]:[];h.push(a),o.forEach((t=>{const s=p.find((e=>e.option===t)),n=p.findIndex((e=>e.option===t)),o=s?{...s}:{option:t,votersCount:0};o.votersCount+=1,a===e.currentUserId&&(o.isChosen=!0),n?p[n]=o:p.push(o)})),(0,n.R3)((0,r.cY)(e,c.chatId,c.id,{content:{...c.content,poll:{...d,results:{...d.results,recentVoterIds:h,totalVoters:g,results:p}}}}));break}case"updateServiceNotification":{const{message:n}=s;(0,i.UW)(e)&&t.createServiceNotification({message:n});break}}}));const J=(0,C.P2)((function(){const e=(0,n.Rd)();(0,n.R3)((0,r.ps)(e,{...e.users.statusesById,...ee})),ee={}}),3e3,!0);let ee={};(0,n.Q6)("apiUpdate",((e,t,s)=>{switch(s["@type"]){case"deleteContact":return(0,r.GK)(e,s.id);case"updateUser":return(0,r.Nq)(e,s.id,s.user);case"updateUserStatus":return n=s.userId,a=s.status,ee[n]=a,void J();case"updateUserFullInfo":{const{id:t,fullInfo:n}=s,a=e.users.byId[t];if(!a)return;return(0,r.Nq)(e,t,{fullInfo:{...a.fullInfo,...n}})}}var n,a})),(0,n.Q6)("apiUpdate",((e,t,s)=>{switch(s["@type"]){case"updateStickerSet":return(0,r.Rg)(e,s.id,s.stickerSet)}})),(0,n.Q6)("apiUpdate",((e,t,s)=>{switch(s["@type"]){case"updatePeerBlocked":return s.isBlocked?(0,r.O4)((0,n.Rd)(),s.id):(0,r.rB)((0,n.Rd)(),s.id);case"updateResetContactList":(0,n.R3)({...(0,n.Rd)(),contactList:{userIds:[]}});break;case"updateFavoriteStickers":t.loadFavoriteStickers();break;case"updatePrivacy":e.settings.privacy[s.key]=s.rules}})),(0,n.Q6)("apiUpdate",((e,t,s)=>{switch(s["@type"]){case"updateNotifySettings":return(0,r.HN)(e,s.peerType,s.isSilent,s.shouldShowPreviews);case"updateNotifyExceptions":{const{chatId:t,isMuted:a,isSilent:o,shouldShowPreviews:i}=s;e.chats.byId[t]&&(e=(0,r.a4)(e,t,{isMuted:a})),(0,n.R3)((0,r.aK)(e,t,{isMuted:a,isSilent:o,shouldShowPreviews:i}));break}}})),(0,n.Q6)("apiUpdate",((e,t,s)=>{switch(s["@type"]){case"updateTwoFaStateWaitCode":return{...e,twoFaSettings:{...e.twoFaSettings,isLoading:!1,waitingEmailCodeLength:s.length}};case"updateTwoFaError":return{...e,twoFaSettings:{...e.twoFaSettings,error:s.message}}}}));var te=s(4446);(0,n.Q6)("apiUpdate",((e,t,s)=>{switch(s["@type"]){case"updateGroupCall":return"discarded"===s.call.connectionState?e.groupCalls.activeGroupCallId?void t.leaveGroupCall({shouldRemove:!0}):(0,te.dc)(e,s.call.id):(0,te.AH)(e,s.call.id,(0,g.CE)(s.call,["connectionState"]),void 0,s.call.participantsCount);case"updateGroupCallChatId":{const t=(0,i.Z1)(e,s.chatId);return t&&(e=(0,r.a4)(e,s.chatId,{fullInfo:{...t.fullInfo,groupCallId:s.call.id}})),e}case"updateGroupCallParticipants":{const{groupCallId:t,participants:a,nextOffset:o}=s,{currentUserId:r}=e;return e=(0,n.Rd)(),a.forEach((s=>{s.id&&(e=(0,te.B6)(e,t,s.id,s,!!o||r===s.id))})),o&&(e=(0,te.AH)(e,t,{nextOffset:o})),e}}}));var se=s(8674),ne=s(6752),ae=s(1279),oe=s(3551),re=s(3227),ie=s(3858),ce=s(1212),de=s(5332);function le(e){(0,o.d4)((()=>(0,C.Gq)(e)),[e])}var ue=s(9290);const me=document.querySelector('meta[name="viewport"]'),he=(null==me?void 0:me.getAttribute("content"))||"";function ge(e){e.preventDefault()}var pe=s(6590),fe=s(3989),Ie=s(7529),ve=s(3455),ye=s(706),Ze=s(2255);function Pe(){const[e,t]=(0,o.eJ)(window.navigator.onLine);return(0,o.d4)((()=>{function e(){t(window.navigator.onLine)}return window.addEventListener("online",e),window.addEventListener("offline",e),()=>{window.removeEventListener("offline",e),window.removeEventListener("online",e)}}),[]),e}var Ce=s(9107),we=s(6917),be=s(3106),Se=s(8964),Ee=s(231),Me=s(9589),ke=s(9187),Re=s(3321);const Te=[0,1,2],Ne=(0,o.X$)((0,n.c$)((e=>{const{query:t,fetchingStatus:s,chatId:n,date:a}=e.globalSearch,{currentUserId:o}=e,{byId:r}=e.chats,{animationLevel:c}=e.settings.byKey;return{searchQuery:t,isLoading:!!s&&Boolean(s.chats||s.messages),currentUserId:o,chatsById:r,globalSearchChatId:n,searchDate:a,theme:(0,i.Pu)(e),animationLevel:c}}))((({content:e,contactsFilter:t,onSearchQuery:s,onSelectSettings:r,onSelectContacts:i,onSelectArchived:c,onReset:l,searchQuery:u,isLoading:g,shouldSkipTransition:p,currentUserId:f,globalSearchChatId:I,searchDate:v,theme:y,animationLevel:Z,chatsById:P})=>{const{openChat:C,openTipsChat:w,setGlobalSearchDate:b,setSettingOption:S,setGlobalSearchChatId:E}=(0,n.uC)(),M=(0,Ce.Z)(),k=e===m.du.ChatList,R=(0,o.Ye)((()=>v?(0,N.xH)(new Date(1e3*v)):void 0),[v]),T=(0,o.Ye)((()=>k&&P?Object.values(P).reduce(((e,t)=>(0,d.pE)(t)&&t.unreadCount?e+1:e),0):0),[k,P]),B="web.telegram.org"===window.location.hostname,A=(0,o.Ye)((()=>({onTrigger:e,isOpen:t})=>o.ZP.createElement(Ee.Z,{round:!0,ripple:k&&!h.wB,size:"smaller",color:"translucent",className:t?"active":"",onClick:k?e:()=>l(),ariaLabel:k?M("AccDescrOpenMenu2"):"Return to chat list"},o.ZP.createElement("div",{className:(0,ne.Z)("animated-menu-icon",!k&&"state-back",p&&"no-animation")}))),[k,M,l,p]),x=(0,o.I4)((()=>{u||s("")}),[u,s]),L=(0,o.I4)((()=>{C({id:f,shouldReplaceHistory:!0})}),[f,C]),O=(0,o.I4)((e=>{e.stopPropagation();const t="light"===y?"dark":"light";S({theme:t}),S({shouldUseSystemTheme:!1}),(0,we.Z)(t,Z===a.zy)}),[Z,S,y]),F=(0,o.I4)((e=>{e.stopPropagation();const t=0===Z?2:0;Te.forEach(((e,s)=>{document.body.classList.toggle(`animation-level-${s}`,t===s)})),S({animationLevel:t})}),[Z,S]),U=Boolean(I)||e===m.du.GlobalSearch||e===m.du.Contacts,$=e===m.du.Contacts?M("SearchFriends"):M("Search");return o.ZP.createElement("div",{className:"LeftMainHeader"},o.ZP.createElement("div",{id:"LeftMainHeader",className:"left-header"},o.ZP.createElement(be.Z,{trigger:A,footer:`${a.iC} ${a.Ji}`},o.ZP.createElement(Se.Z,{icon:"saved-messages",onClick:L},M("SavedMessages")),o.ZP.createElement(Se.Z,{icon:"archive",onClick:c},o.ZP.createElement("span",{className:"menu-item-name"},M("ArchivedChats")),T>0&&o.ZP.createElement("div",{className:"archived-badge"},T)),o.ZP.createElement(Se.Z,{icon:"user",onClick:i},M("Contacts")),o.ZP.createElement(Se.Z,{icon:"settings",onClick:r},M("Settings")),o.ZP.createElement(Se.Z,{icon:"darkmode",onClick:O},o.ZP.createElement("span",{className:"menu-item-name"},M("lng_menu_night_mode")),o.ZP.createElement(Re.Z,{id:"darkmode",label:M("dark"===y?"lng_settings_disable_night_theme":"lng_settings_enable_night_theme"),checked:"dark"===y,noAnimation:!0})),o.ZP.createElement(Se.Z,{icon:"animations",onClick:F},o.ZP.createElement("span",{className:"menu-item-name capitalize"},M("Appearance.Animations").toLowerCase()),o.ZP.createElement(Re.Z,{id:"animations",label:"Toggle Animations",checked:Z>0})),o.ZP.createElement(Se.Z,{icon:"help",onClick:()=>{w({langCode:M.code})}},M("TelegramFeatures")),o.ZP.createElement(Se.Z,{icon:"bug",href:a.mU},"Report Bug"),B&&o.ZP.createElement(o.ZP.Fragment,null,o.ZP.createElement(Se.Z,{icon:"char-K",href:"https://web.telegram.org/k/",onClick:()=>{localStorage.setItem("kz_version",JSON.stringify("K")),(0,pe.Wv)()}},"Switch to K Version"),o.ZP.createElement(Se.Z,{icon:"char-W",href:"https://web.telegram.org/?legacy=1",onClick:pe.Wv},"Switch to Old Version"))),o.ZP.createElement(Me.Z,{inputId:"telegram-search-input",parentContainerClassName:"LeftSearch",className:I||v?"with-picker-item":"",value:t||u,focused:U,isLoading:g,placeholder:$,autoComplete:"off",canClose:Boolean(I||v),onChange:s,onReset:l,onFocus:x},R&&o.ZP.createElement(ke.Z,{icon:"calendar",title:R,canClose:!0,isMinimized:Boolean(I),className:"search-date",onClick:b,clickArg:{date:void 0}}),I&&o.ZP.createElement(ke.Z,{chatOrUserId:I,onClick:E,canClose:!0,clickArg:{id:void 0}}))))})));var Be=s(9204);const Ae=(0,o.X$)((()=>{const e=(0,Ce.Z)();return o.ZP.createElement("div",{id:"ConnectionState",dir:e.isRtl?"rtl":void 0},o.ZP.createElement(Be.Z,{color:"black"}),o.ZP.createElement("div",{className:"state-text"},e("WaitingForNetwork")))}));var xe=s(1174),Le=s(6071),Oe=s(3133),Fe=s(1080);const Ue=(0,o.X$)((0,n.c$)((e=>{const{chats:{listIds:t,byId:s},users:{byId:n},chatFolders:{byId:a,orderedIds:o,activeChatFolder:r},currentUserId:c,lastSyncTime:d,shouldSkipHistoryAnimations:l}=e;return{allListIds:t,chatsById:s,usersById:n,chatFoldersById:a,orderedFolderIds:o,lastSyncTime:d,notifySettings:(0,i.dZ)(e),notifyExceptions:(0,i.NJ)(e),activeChatFolder:r,currentUserId:c,shouldSkipHistoryAnimations:l}}))((({allListIds:e,chatsById:t,usersById:s,chatFoldersById:r,notifySettings:i,notifyExceptions:c,orderedFolderIds:l,activeChatFolder:u,currentUserId:m,lastSyncTime:p,shouldSkipHistoryAnimations:f,foldersDispatch:I,onScreenSelect:v})=>{const{loadChatFolders:y,setActiveChatFolder:Z,openChat:P}=(0,n.uC)(),C=(0,o.sO)(null),w=(0,Ce.Z)();(0,o.d4)((()=>{p&&y()}),[p,y]);const b=(0,o.Ye)((()=>l?l.map((e=>r[e]||{})).filter(Boolean):void 0),[r,l]),S=((n,a,r)=>{const l=(0,Le.Z)(3e3,!0),[u,m]=(0,o.eJ)(),[h,p,f]=(0,ye.Z)();return(0,se.ZP)(p,f),(0,ue.Z)((()=>{h||l((()=>{m((()=>{if(!b||!b.length)return;const n=b.map((n=>{const{unreadDialogsCount:a,hasActiveDialogs:o}=(0,d.Fu)(e,t,s,n,i,c)||{};return{id:n.id,badgeCount:a,isBadgeActive:o}}));return(0,g.ee)(n,"id")})())}))}),r.concat([h])),u})(0,0,[b,e,t,s,i,c]),E=(0,o.Ye)((()=>{if(b&&b.length)return[{title:"en"===w.code?"All":w("FilterAllChats"),id:a.Nf},...b.map((e=>({title:e.title,...null==S?void 0:S[e.id]})))]}),[b,S,w]),M=(0,o.I4)((e=>{Z(e,{forceOnHeavyAnimation:!0})}),[Z]);(0,o.d4)((()=>{E&&E.length&&u>=E.length&&Z(0)}),[u,E,Z]),(0,o.d4)((()=>{if(C.current&&h.$b&&E&&E.length)return(0,xe.s)(C.current,{selectorToPreventScroll:".chat-list",onSwipe:(e,t)=>t===xe.e.Left?(Z(Math.min(u+1,E.length-1),{forceOnHeavyAnimation:!0}),!0):t===xe.e.Right&&(Z(Math.max(0,u-1),{forceOnHeavyAnimation:!0}),!0)})}),[u,E,Z]);const k=(0,o.sO)();k.current=0!==u,(0,o.d4)((()=>k.current?(0,fe.Z)((()=>{k.current&&Z(0)})):void 0),[u,Z]),(0,pe.ZP)(0!==u,(()=>Z(0,{forceOnHeavyAnimation:!0}))),(0,o.d4)((()=>{const e=e=>{if(e.ctrlKey&&e.shiftKey&&e.code.startsWith("Digit")&&E){const[,t]=e.code.match(/Digit(\d)/)||[];if(!t)return;if("0"===t)return void P({id:m,shouldReplaceHistory:!0});const s=Number(t)-1;if(s>E.length-1)return;Z(s,{forceOnHeavyAnimation:!0}),e.preventDefault()}};return document.addEventListener("keydown",e,!0),()=>{document.removeEventListener("keydown",e,!0)}}));const{shouldRender:R,transitionClassNames:T}=(0,ce.Z)(!l,void 0,!0);function N(e){const t=Object.values(r).find((({id:e})=>e===E[u].id));return t&&0!==u?o.ZP.createElement(Fe.Z,{folderType:"folder",folderId:t.id,isActive:e,onScreenSelect:v,foldersDispatch:I}):o.ZP.createElement(Fe.Z,{folderType:"all",isActive:e,foldersDispatch:I,onScreenSelect:v})}return o.ZP.createElement("div",{className:"ChatFolders"},null!=E&&E.length?o.ZP.createElement(Oe.Z,{tabs:E,activeTab:u,onSwitchTab:M}):R?o.ZP.createElement("div",{className:(0,ne.Z)("tabs-placeholder",T)}):void 0,o.ZP.createElement(Ze.Z,{ref:C,name:f?"none":w.isRtl?"slide-optimized-rtl":"slide-optimized",activeKey:u,renderCount:E?E.length:void 0},N))})));var $e=s(9203),De=s(8778),qe=s(4288);const Qe=(0,o.X$)((e=>{const t=(0,De.Z)($e.gl.Extra,"LeftSearch");return t?o.ZP.createElement(t,e):o.ZP.createElement(qe.Z,null)})),Ge=(0,o.X$)((e=>{const t=(0,De.Z)($e.gl.Extra,"ContactList");return t?o.ZP.createElement(t,e):o.ZP.createElement(qe.Z,null)}));var je=s(2328);let He;const _e=(0,o.X$)((({isShown:e,onNewPrivateChat:t,onNewChannel:s,onNewGroup:n})=>{const[a,r]=(0,o.eJ)(!1);(0,o.d4)((()=>{e||r(!1)}),[e]);const i=(0,Ce.Z)(),c=(0,ne.Z)("NewChatButton",e&&"revealed",a&&"menu-is-open"),d=(0,o.I4)((()=>{He&&(clearTimeout(He),He=void 0)}),[]),l=(0,o.I4)((()=>{He&&(clearTimeout(He),He=void 0),He=window.setTimeout((()=>{r(!1)}),750)}),[]);return o.ZP.createElement("div",{className:c,onMouseEnter:d,onMouseLeave:l},o.ZP.createElement(Ee.Z,{round:!0,color:"primary",className:a?"active":"",onClick:()=>{r(!a)},ariaLabel:i(a?"Close":"NewMessageTitle"),tabIndex:-1},o.ZP.createElement("i",{className:"icon-new-chat-filled"}),o.ZP.createElement("i",{className:"icon-close"})),o.ZP.createElement(je.Z,{isOpen:a,positionX:"right",positionY:"bottom",autoClose:!0,onClose:()=>{r(!1)}},o.ZP.createElement(Se.Z,{icon:"channel",onClick:s},i("NewChannel")),o.ZP.createElement(Se.Z,{icon:"group",onClick:n},i("NewGroup")),o.ZP.createElement(Se.Z,{icon:"user",onClick:t},i("NewMessageTitle"))))}));var ze=s(126);const Ve=Object.keys(m.du).length/2;let Ke;const Ye=(0,n.c$)((e=>(0,g.ei)(e,["connectionState"])))((({content:e,searchQuery:t,searchDate:s,contactsFilter:n,shouldSkipTransition:a,foldersDispatch:r,onSearchQuery:i,onContentChange:c,onScreenSelect:d,onReset:l,connectionState:u})=>{const[g,p]=(0,o.eJ)(h.$b),f=!Pe()||"connectionStateConnecting"===u,I=(0,o.sO)(!1),v=(0,o.I4)((()=>{c(m.du.Settings)}),[c]),y=(0,o.I4)((()=>{c(m.du.Contacts)}),[c]),Z=(0,o.I4)((()=>{c(m.du.NewChannelStep1)}),[c]),P=(0,o.I4)((()=>{c(m.du.NewGroupStep1)}),[c]),C=(0,o.I4)((()=>{c(m.du.Archived)}),[c]),w=(0,o.I4)((()=>{e===m.du.ChatList&&(I.current=!0,p(!0))}),[e]),b=(0,o.I4)((()=>{I.current=!1,Ke&&(clearTimeout(Ke),Ke=void 0),Ke=window.setTimeout((()=>{I.current||p(!1)}),250)}),[]);(0,o.d4)((()=>{let t;return e!==m.du.ChatList?t=window.setTimeout((()=>{p(!1)}),250):(I.current||h.$b)&&p(!0),()=>{t&&(clearTimeout(t),t=void 0)}}),[e]);const[S,E,M]=function(){const[e,t]=(0,ye.Z)(!1);(0,o.d4)((()=>{const e=window.setTimeout(t,2592e5);return()=>{clearTimeout(e)}}),[t]);const{shouldRender:s,transitionClassNames:n}=(0,ce.Z)(e);return[s,n,()=>{window.location.reload()}]}(),k=(0,Ce.Z)();return o.ZP.createElement("div",{id:"LeftColumn-main",onMouseEnter:h.$b?void 0:w,onMouseLeave:h.$b?void 0:b},o.ZP.createElement(Ne,{content:e,contactsFilter:n,onSearchQuery:i,onSelectSettings:v,onSelectContacts:y,onSelectArchived:C,onReset:l,shouldSkipTransition:a}),o.ZP.createElement(ze.Z,{isOpen:f,isCustom:!0,className:"connection-state-wrapper opacity-transition slow"},(()=>o.ZP.createElement(Ae,null))),o.ZP.createElement(Ze.Z,{name:a?"none":"zoom-fade",renderCount:Ve,activeKey:e,shouldCleanup:!0,cleanupExceptionKey:m.du.ChatList,className:f?"pull-down":void 0},(a=>{switch(e){case m.du.ChatList:return o.ZP.createElement(Ue,{onScreenSelect:d,foldersDispatch:r});case m.du.GlobalSearch:return o.ZP.createElement(Qe,{searchQuery:t,searchDate:s,isActive:a,onReset:l});case m.du.Contacts:return o.ZP.createElement(Ge,{filter:n,isActive:a,onReset:l});default:return}})),S&&o.ZP.createElement(Ee.Z,{fluid:!0,pill:!0,className:(0,ne.Z)("btn-update",E),onClick:M},k("lng_update_telegram")),o.ZP.createElement(_e,{isShown:g,onNewPrivateChat:y,onNewChannel:Z,onNewGroup:P}))})),We=(0,o.X$)((e=>{const t=(0,De.Z)($e.gl.Extra,"Settings");return t?o.ZP.createElement(t,e):o.ZP.createElement(qe.Z,null)})),Xe=(0,o.X$)((e=>{const t=(0,De.Z)($e.gl.Extra,"NewChat");return t?o.ZP.createElement(t,e):o.ZP.createElement(qe.Z,null)})),Je=(0,o.X$)((e=>{const t=(0,De.Z)($e.gl.Extra,"ArchivedChats");return t?o.ZP.createElement(t,e):o.ZP.createElement(qe.Z,null)}));var et;!function(e){e[e.Main=0]="Main",e[e.Settings=1]="Settings",e[e.Archived=2]="Archived",e[e.NewGroup=3]="NewGroup",e[e.NewChannel=4]="NewChannel"}(et||(et={}));const tt=Object.keys(et).length/2,st=(0,o.X$)((0,n.c$)((e=>{const{globalSearch:{query:t,date:s},chatFolders:{activeChatFolder:n},shouldSkipHistoryAnimations:a,leftColumnWidth:o}=e;return{searchQuery:t,searchDate:s,activeChatFolder:n,shouldSkipHistoryAnimations:a,leftColumnWidth:o}}))((({searchQuery:e,searchDate:t,activeChatFolder:s,shouldSkipHistoryAnimations:a,leftColumnWidth:r})=>{const{setGlobalSearchQuery:i,setGlobalSearchChatId:c,resetChatCreation:d,setGlobalSearchDate:l,loadPasswordInfo:u,clearTwoFaError:g,setLeftColumnWidth:p,resetLeftColumnWidth:f}=(0,n.uC)(),I=(0,o.sO)(null),[v,y]=(0,o.eJ)(m.du.ChatList),[Z,P]=(0,o.eJ)(m.MT.Main),[C,w]=(0,o.eJ)(""),[b,S]=(0,ve.ZP)(),[E,M]=(0,o.eJ)(0);let k=et.Main;switch(v){case m.du.Archived:k=et.Archived;break;case m.du.Settings:k=et.Settings;break;case m.du.NewChannelStep1:case m.du.NewChannelStep2:k=et.NewChannel;break;case m.du.NewGroupStep1:case m.du.NewGroupStep2:k=et.NewGroup}const R=(0,o.I4)((e=>{if(v!==m.du.NewGroupStep2||e)if(v!==m.du.NewChannelStep2||e){if(v===m.du.NewGroupStep1){const e=document.getElementById("new-group-picker-search");e&&e.blur()}if(v===m.du.Settings)switch(Z){case m.MT.EditProfile:case m.MT.Folders:case m.MT.General:case m.MT.Notifications:case m.MT.DataStorage:case m.MT.Privacy:case m.MT.Language:return void P(m.MT.Main);case m.MT.GeneralChatBackground:return void P(m.MT.General);case m.MT.GeneralChatBackgroundColor:return void P(m.MT.GeneralChatBackground);case m.MT.PrivacyPhoneNumber:case m.MT.PrivacyLastSeen:case m.MT.PrivacyProfilePhoto:case m.MT.PrivacyForwarding:case m.MT.PrivacyGroupChats:case m.MT.PrivacyActiveSessions:case m.MT.PrivacyBlockedUsers:case m.MT.TwoFaDisabled:case m.MT.TwoFaEnabled:case m.MT.TwoFaCongratulations:return void P(m.MT.Privacy);case m.MT.PrivacyPhoneNumberAllowedContacts:case m.MT.PrivacyPhoneNumberDeniedContacts:return void P(m.MT.PrivacyPhoneNumber);case m.MT.PrivacyLastSeenAllowedContacts:case m.MT.PrivacyLastSeenDeniedContacts:return void P(m.MT.PrivacyLastSeen);case m.MT.PrivacyProfilePhotoAllowedContacts:case m.MT.PrivacyProfilePhotoDeniedContacts:return void P(m.MT.PrivacyProfilePhoto);case m.MT.PrivacyForwardingAllowedContacts:case m.MT.PrivacyForwardingDeniedContacts:return void P(m.MT.PrivacyForwarding);case m.MT.PrivacyGroupChatsAllowedContacts:case m.MT.PrivacyGroupChatsDeniedContacts:return void P(m.MT.PrivacyGroupChats);case m.MT.TwoFaNewPassword:return void P(m.MT.TwoFaDisabled);case m.MT.TwoFaNewPasswordConfirm:return void P(m.MT.TwoFaNewPassword);case m.MT.TwoFaNewPasswordHint:return void P(m.MT.TwoFaNewPasswordConfirm);case m.MT.TwoFaNewPasswordEmail:return void P(m.MT.TwoFaNewPasswordHint);case m.MT.TwoFaNewPasswordEmailCode:return void P(m.MT.TwoFaNewPasswordEmail);case m.MT.TwoFaChangePasswordCurrent:case m.MT.TwoFaTurnOff:case m.MT.TwoFaRecoveryEmailCurrentPassword:return void P(m.MT.TwoFaEnabled);case m.MT.TwoFaChangePasswordNew:return void P(m.MT.TwoFaChangePasswordCurrent);case m.MT.TwoFaChangePasswordConfirm:return void P(m.MT.TwoFaChangePasswordNew);case m.MT.TwoFaChangePasswordHint:return void P(m.MT.TwoFaChangePasswordConfirm);case m.MT.TwoFaRecoveryEmail:return void P(m.MT.TwoFaRecoveryEmailCurrentPassword);case m.MT.TwoFaRecoveryEmailCode:return void P(m.MT.TwoFaRecoveryEmail);case m.MT.FoldersCreateFolder:case m.MT.FoldersEditFolder:return void P(m.MT.Folders);case m.MT.FoldersIncludedChatsFromChatList:case m.MT.FoldersExcludedChatsFromChatList:return void P(m.MT.FoldersEditFolderFromChatList);case m.MT.FoldersEditFolderFromChatList:return y(m.du.ChatList),void P(m.MT.Main)}v!==m.du.ChatList||0!==s?(y(m.du.ChatList),w(""),i({query:""}),l({date:void 0}),c({id:void 0}),d(),setTimeout((()=>{M(Date.now())}),250)):y(m.du.GlobalSearch)}else y(m.du.NewChannelStep1);else y(m.du.NewGroupStep1)}),[v,s,Z,i,l,c,d]),T=(0,o.I4)((t=>{v!==m.du.Contacts?(y(m.du.GlobalSearch),t!==e&&i({query:t})):w(t)}),[v,e,i]);(0,o.d4)((()=>v!==m.du.ChatList||0===s?(0,fe.Z)((()=>R())):void 0),[s,v,R]),(0,o.d4)((()=>{if(v!==m.du.GlobalSearch)return document.addEventListener("keydown",e,!1),()=>{document.removeEventListener("keydown",e,!1)};function e(e){(h.jm&&e.metaKey||!h.jm&&e.ctrlKey)&&e.shiftKey&&"f"===(0,Ie.Z)(e)&&(e.preventDefault(),y(m.du.GlobalSearch))}}),[v]),(0,o.d4)((()=>{g(),Z===m.MT.Privacy&&u()}),[g,u,Z]);const{initResize:N,resetResize:B,handleMouseUp:A}=((e,t,s,n)=>{const[a,r,i]=(0,ye.Z)(),[c,d]=(0,o.eJ)(),[l,u]=(0,o.eJ)();(0,o.d4)((()=>{e.current&&n&&(e.current.style.width=`${n}px`)}),[e,n]);const m=()=>{document.body.classList.remove("no-selection","cursor-ew-resize")};return(0,o.d4)((()=>{if(!a)return;const s=t=>{const s=Math.ceil(l+t.clientX-c);e.current.style.width=`${s}px`},n=()=>{m(),document.removeEventListener("mousemove",s,!1),document.removeEventListener("mouseup",n,!1),document.removeEventListener("blur",n,!1),t(e.current.offsetWidth),i()};document.addEventListener("mousemove",s,!1),document.addEventListener("mouseup",n,!1),document.addEventListener("blur",n,!1)}),[l,c,e,t,a,i]),{initResize:t=>{document.body.classList.add("no-selection","cursor-ew-resize"),d(t.clientX),u(e.current.offsetWidth),r()},resetResize:t=>{t.preventDefault(),e.current.style.width="",s()},handleMouseUp:m}})(I,p,f,r),x=e=>{y(m.du.Settings),P(e)};return o.ZP.createElement("div",{id:"LeftColumn",ref:I},o.ZP.createElement(Ze.Z,{name:a?"none":h.s0,renderCount:tt,activeKey:k,shouldCleanup:!0,cleanupExceptionKey:et.Main},(s=>{switch(k){case et.Archived:return o.ZP.createElement(Je,{isActive:s,onReset:R,onContentChange:y});case et.Settings:return o.ZP.createElement(We,{isActive:s,currentScreen:Z,foldersState:b,foldersDispatch:S,onScreenSelect:x,onReset:R,shouldSkipTransition:a});case et.NewChannel:return o.ZP.createElement(Xe,{key:E,isActive:s,isChannel:!0,content:v,onContentChange:y,onReset:R});case et.NewGroup:return o.ZP.createElement(Xe,{key:E,isActive:s,content:v,onContentChange:y,onReset:R});default:return o.ZP.createElement(Ye,{content:v,searchQuery:e,searchDate:t,contactsFilter:C,foldersDispatch:S,onContentChange:y,onSearchQuery:T,onScreenSelect:x,onReset:R,shouldSkipTransition:a})}})),o.ZP.createElement("div",{className:"resize-handle",onMouseDown:N,onMouseUp:A,onDoubleClick:B}))})));var nt=s(2420),at=s(5780),ot=s(9524),rt=s(1394);const it=()=>{const[e,t]=(0,o.eJ)(ie.Z.get());return(0,o.d4)((()=>{const e=(0,C.P2)((()=>{t(ie.Z.get())}),250,!1);return window.addEventListener("resize",e),()=>{window.removeEventListener("resize",e)}}),[]),e};var ct=s(2678),dt=s(7204),lt=s(5326);const ut=728;var mt=s(3570),ht=s(5790),gt=s(8360),pt=s(2155),ft=s(6058),It=s(8799);const vt=(0,o.X$)((e=>{const{isOpen:t}=e,s=(0,De.Z)($e.gl.Extra,"HeaderMenuContainer",!t);return s?o.ZP.createElement(s,e):void 0})),yt=(0,o.X$)((0,n.c$)(((e,{chatId:t,threadId:s,messageListType:n})=>{var a;const o=(0,i.Z1)(e,t),r=Boolean(o&&(0,d.eA)(o));if(!o||o.isRestricted||(0,i.CA)(e))return{noMenu:!0};const c=(0,i.IK)(e,t),l=(0,i.FM)(e,t),m="thread"===n&&s===u._f,g="thread"===n&&s!==u._f,p=(0,i.Jf)(e),f=Boolean(c&&(0,i.s4)(e,c.id)),I=!f&&Boolean((0,i.pk)(e,t)),v=Boolean(m&&(r||(0,d.ZV)(o))&&o.isNotJoined);return{noMenu:!1,isChannel:r,isRightColumnShown:p,canStartBot:I,canRestartBot:f,canSubscribe:v,canSearch:m||g,canCall:h.Bi&&(0,d.YC)(o.id)&&!l&&!c,canMute:m&&!l&&!v,canLeave:m&&!v,canEnterVoiceChat:h.Bi&&o.isCallActive,canCreateVoiceChat:h.Bi&&!o.isCallActive&&((null===(a=o.adminRights)||void 0===a?void 0:a.manageCall)||o.isCreator&&(0,d.G9)(o))}}))((({chatId:e,threadId:t,noMenu:s,isChannel:a,canStartBot:r,canRestartBot:i,canSubscribe:c,canSearch:d,canCall:l,canMute:u,canLeave:m,canEnterVoiceChat:g,canCreateVoiceChat:p,isRightColumnShown:f,canExpandActions:I})=>{const{joinChannel:v,sendBotCommand:y,openLocalTextSearch:Z,restartBot:P,openCallFallbackConfirm:C}=(0,n.uC)(),w=(0,o.sO)(null),[b,S]=(0,o.eJ)(!1),[E,M]=(0,o.eJ)(void 0),k=(0,o.I4)((()=>{S(!0);const e=w.current.getBoundingClientRect();M({x:e.right,y:e.bottom})}),[]),R=(0,o.I4)((()=>{S(!1)}),[]),T=(0,o.I4)((()=>{M(void 0)}),[]),N=(0,o.I4)((()=>{v({chatId:e})}),[v,e]),B=(0,o.I4)((()=>{y({command:"/start"})}),[y]),A=(0,o.I4)((()=>{P({chatId:e})}),[e,P]),x=(0,o.I4)((()=>{Z(),h.wB?document.querySelector("#MobileSearch input").focus():setTimeout((()=>{const e=document.querySelector(".RightHeader .SearchInput input");e&&e.focus()}),400)}),[Z]);(0,o.d4)((()=>{if(d)return document.addEventListener("keydown",e,!1),()=>{document.removeEventListener("keydown",e,!1)};function e(e){h.fl&&(h.jm&&e.metaKey||!h.jm&&e.ctrlKey)&&!e.shiftKey&&"f"===(0,Ie.Z)(e)&&(e.preventDefault(),x())}}),[d,x]);const L=(0,Ce.Z)();return o.ZP.createElement("div",{className:"HeaderActions"},!h.wB&&o.ZP.createElement(o.ZP.Fragment,null,I&&c&&o.ZP.createElement(Ee.Z,{size:"tiny",ripple:!0,fluid:!0,onClick:N},L(a?"ProfileJoinChannel":"ProfileJoinGroup")),I&&r&&o.ZP.createElement(Ee.Z,{size:"tiny",ripple:!0,fluid:!0,onClick:B},L("BotStart")),I&&i&&o.ZP.createElement(Ee.Z,{size:"tiny",ripple:!0,fluid:!0,onClick:A},L("BotRestart")),d&&o.ZP.createElement(Ee.Z,{round:!0,ripple:f,color:"translucent",size:"smaller",onClick:x,ariaLabel:"Search in this chat"},o.ZP.createElement("i",{className:"icon-search"})),l&&o.ZP.createElement(Ee.Z,{round:!0,color:"translucent",size:"smaller",onClick:C,ariaLabel:"Call"},o.ZP.createElement("i",{className:"icon-phone"}))),o.ZP.createElement(Ee.Z,{ref:w,className:b?"active":"",round:!0,ripple:!h.wB,size:"smaller",color:"translucent",disabled:s,ariaLabel:"More actions",onClick:k},o.ZP.createElement("i",{className:"icon-more"})),E&&o.ZP.createElement(vt,{chatId:e,threadId:t,isOpen:b,anchor:E,withExtraActions:h.wB||!I,isChannel:a,canStartBot:r,canRestartBot:i,canSubscribe:c,canSearch:d,canCall:l,canMute:u,canLeave:m,canEnterVoiceChat:g,canCreateVoiceChat:p,onSubscribeChannel:N,onSearchClick:x,onClose:R,onCloseAnimationEnd:T}))})));var Zt=s(4399),Pt=s(2340),Ct=s(6202),wt=s(862);function bt(e){var t;const s=e&&(0,d.DH)(e),n=null==e||null===(t=e.content)||void 0===t?void 0:t.sticker,r=s&&n&&!(0,h.on)()&&s.includes("image/webp"),[i,c]=(0,o.eJ)(wt.Hu),l=null==e?void 0:e.id;return(0,o.bt)((()=>{r&&(0,wt.p6)(`b64-${l}`,s).then(c).catch((e=>{a.eM&&console.error(e)}))}),[l,r,s]),r?i:s}var St=s(7551),Et=s(8512);function Mt(e,t,s,n,a){return`M${e},${t+a}a${a},${a},0,0,1,\n ${s},0v${n-2*a}a${a},${a},0,0,1,${-s},0Z`}const kt=(0,o.X$)((({count:e,index:t})=>{const s=(0,o.sO)(null),n=(0,o.Ye)((()=>function(e,t){const s=e-t-1,n=function(e){let t=8;return 1===e?t=36:2===e?t=17:3===e?t=11:(4===e||e>3)&&(t=7.5),t}(e),a=function(e,t){let s=36;return 1===e?s=36:2===e?s=17:3===e?s=1===t?12:11:(4===e||e>3)&&(s=7.5),s}(e,s),o=function(e,t){return e<=3?36:t*e+2*(e-1)}(e,n),r=`clipPath${e}`;return{markHeight:a,clipPath:function(e,t,s){let n="";if(3===s)n=Mt(0,0,2,t,1)+Mt(0,12,2,t+1,1)+Mt(0,25,2,t,1);else for(let e=0;e\n \n `}(r,n,e),markTranslateY:function(e,t,s){return 1===s?0:2===s?0===e?0:t+2:3===s?0===e?0:1===e?12:25:(t+2)*e}(s,n,e),trackTranslateY:function(e,t,s,n){return t<=4||e<=1?0:e>=t-2?n-36:(s+4)/2+(e-2)*(s+2)}(s,e,n,o),trackHeight:o,clipPathId:r}}(e,t)),[e,t]);if((0,o.d4)((()=>{if(!s.current)return;const{trackHeight:e,trackTranslateY:t,markHeight:a,markTranslateY:o,clipPathId:r,clipPath:i}=n,c=s.current.firstElementChild;if(null!=s&&s.current){const n=s.current,{style:d}=n;d.height=`${e}px`,d.transform=`translateY(-${t}px)`,d.clipPath=`url("#${r}")`;const l=n.querySelector("svg"),u=n.querySelector("div"),m=n.querySelector("defs");l||c&&(c.innerHTML=` ${i} `),m&&(m.innerHTML=i),u&&(u.style.height=`${a}px`,u.style.transform=`translateY(${o}px)`)}}),[n]),1===e)return o.ZP.createElement("div",{className:"pinned-message-border"},o.ZP.createElement("div",{className:"pinned-message-border-wrapper-1",ref:s}));const{trackHeight:a,trackTranslateY:r,markHeight:i,markTranslateY:c,clipPathId:d}=n;return o.ZP.createElement("div",{className:(0,ne.Z)("pinned-message-border",e>4&&"pinned-message-border-mask")},o.ZP.createElement("div",{className:"pinned-message-border-wrapper",ref:s,style:`clip-path: url("#${d}"); width: 2px;\n height: ${a}px; transform: translateY(-${r}px);`},o.ZP.createElement("span",null),o.ZP.createElement("div",{className:"pinned-message-border-mark",style:`height: ${i}px; transform: translateY(${c}px);`})))})),Rt=(0,o.X$)((({message:e,count:t,index:s,customTitle:n,className:a,onUnpinMessage:r,onClick:i,onAllPinnedClick:c})=>{const l=(0,Ce.Z)(),u=bt(e),m=(0,Ct.Z)((0,d.Ti)(e,"pictogram")),h=(0,d.MK)(l,e,Boolean(u)),[g,p,f]=(0,ye.Z)(),I=(0,o.I4)((()=>{f(),r&&r(e.id)}),[f,r,e.id]);return o.ZP.createElement("div",{className:(0,ne.Z)("HeaderPinnedMessage-wrapper",a)},t>1&&o.ZP.createElement(Ee.Z,{round:!0,size:"smaller",color:"translucent",className:"pin-list-button",ariaLabel:l("EventLogFilterPinnedMessages"),onClick:c},o.ZP.createElement("i",{className:"icon-pin-list"})),r&&o.ZP.createElement(Ee.Z,{round:!0,size:"smaller",color:"translucent",ariaLabel:l("UnpinMessageAlertTitle"),className:"unpin-button",onClick:p},o.ZP.createElement("i",{className:"icon-close"})),o.ZP.createElement(St.Z,{isOpen:g,onClose:f,text:"Would you like to unpin this message?",confirmLabel:"Unpin",confirmHandler:I}),o.ZP.createElement("div",{className:"HeaderPinnedMessage",onClick:i,dir:l.isRtl?"rtl":void 0},o.ZP.createElement(kt,{count:t,index:s}),u&&function(e,t){const{width:s,height:n}=(0,Zt.W7)();return o.ZP.createElement("img",{src:t||e,width:s,height:n,alt:""})}(u,m),o.ZP.createElement("div",{className:"message-text"},o.ZP.createElement("div",{className:"title",dir:"auto"},n||`${l("PinnedMessage")} ${s>0?"#"+(t-s):""}`),o.ZP.createElement("p",{dir:"auto"},(0,Pt.Z)(h))),o.ZP.createElement(Et.Z,null)))}));var Tt=s(647),Nt=s(396),Bt=s(4532),At=s(3186),xt=s(663);function Lt(e,t,s="image/png"){const n=e instanceof Blob?URL.createObjectURL(e):e,a=new Image;return new Promise((o=>{a.onload=()=>{Ot(a,a.width*t,a.height*t,s).then((e=>URL.createObjectURL(e))).then(o).finally((()=>{e instanceof Blob&&URL.revokeObjectURL(n)}))},a.src=n}))}async function Ot(e,t,s,n="image/png"){if(!("createImageBitmap"in window))return Ft(e,t,s,void 0,n);try{const a=await window.createImageBitmap(e,{resizeWidth:t,resizeHeight:s,resizeQuality:"high"});if(a.height!==s||a.width!==t)throw new Error("Image bitmap resize not supported!");return await new Promise((e=>{const t=document.createElement("canvas");t.width=a.width,t.height=a.height;const s=t.getContext("bitmaprenderer");s?s.transferFromImageBitmap(a):t.getContext("2d").drawImage(a,0,0),t.toBlob(e,n)}))}catch(a){return Ft(e,t,s,void 0,n)}}function Ft(e,t,s,n=.5,a="image/png"){const o=document.createElement("canvas"),r=o.getContext("2d"),i=document.createElement("canvas"),c=i.getContext("2d");if(o.width=t,o.height=s,e.width*n>t){const s=1/n;let a={width:Math.floor(e.width*n),height:Math.floor(e.height*n)};for(i.width=a.width,i.height=a.height,c.drawImage(e,0,0,a.width,a.height);a.width*n>t;)a={width:Math.floor(a.width*n),height:Math.floor(a.height*n)},c.drawImage(i,0,0,a.width*s,a.height*s,0,0,a.width,a.height);r.drawImage(i,0,0,a.width,a.height,0,0,o.width,o.height)}else r.drawImage(e,0,0,o.width,o.height);return new Promise((e=>{o.toBlob(e,a)}))}var Ut=s(4524);const $t={width:200,height:200},Dt=115,qt=(e,t,s)=>{const{audio:n,voice:a}=(0,d.qp)(e),r=n?n.title||n.fileName:a?"Voice message":"",i=n&&n.performer||t&&(0,d.OU)(xt.i0,t),c=s&&(0,d.U)(xt.i0,s)||"Telegram",l=n&&(0,d.MR)(n)&&(0,d.Ti)(e,"pictogram"),u=t&&(0,d.RT)(t,"big"),m=n&&l||a&&u,h=(0,Ct.Z)(m),g=(0,o.Ye)((()=>function(e,t,s){if(!s)return $t;if(e){if(!e.thumbnailSizes||0===e.thumbnailSizes.length)return;return e.thumbnailSizes.find((e=>"m"===e.type))||e.thumbnailSizes[0]}return t?Zt.vY:void 0}(n,a,h)),[n,h,a]),{result:p}=((e,t,s)=>{const[n,a]=(0,o.eJ)(!1),[r,i]=(0,o.eJ)(),[c,d]=(0,o.eJ)(s);return(0,o.d4)((()=>{a(!0);let e=!1;return function(e,t){if(!e)return Promise.resolve(Ut);if(!t)return function(e,t,s,n="image/png"){const a=e instanceof Blob?URL.createObjectURL(e):e,o=new Image;return new Promise((r=>{o.onload=()=>{Ot(o,t,s,n).then((e=>URL.createObjectURL(e))).then(r).finally((()=>{e instanceof Blob&&URL.revokeObjectURL(a)}))},o.src=a}))}(e,Dt,Dt);const s=Math.min(t.width,t.height);return s{e||(a(!1),d(t))}),(t=>{e||(a(!1),i(t))})),()=>{e=!0}}),t),{isLoading:n,error:r,result:c}})(0,[h,g],Ut);return(0,o.Ye)((()=>(0,Bt.Of)({title:r,artist:i,album:c,artwork:[{src:p}]})),[c,i,r,p])};var Qt=s(8051);const Gt=(0,n.c$)(((e,{message:t})=>{const s=(0,i.Ur)(e,t),n=(0,i.Z1)(e,t.chatId),{volume:a,playbackRate:o,isMuted:r}=e.audioPlayer;return{sender:s,chat:n,volume:a,playbackRate:o,isMuted:r}}))((({message:e,className:t,noUi:s,sender:a,chat:r,volume:i,playbackRate:c,isMuted:l})=>{const{setAudioPlayerVolume:u,setAudioPlayerPlaybackRate:m,setAudioPlayerMuted:g,focusMessage:p,closeAudioPlayer:f}=(0,n.uC)(),I=(0,Ce.Z)(),{audio:v,voice:y,video:Z}=(0,d.qp)(e),P=Boolean(y||Z),C=a?(0,d.OU)(I,a):void 0,w=Tt.UV((0,d.Ti)(e,"inline")),b=qt(e,a,r),{playPause:S,stop:E,isPlaying:M,requestNextTrack:k,requestPreviousTrack:R,isFirst:T,isLast:N,setVolume:B,toggleMuted:A,setPlaybackRate:x}=(0,At.Z)((0,Nt.An)(e),(0,d.XV)(e),P?"voice":"audio",w,void 0,b,void 0,!0,void 0,void 0,(0,d.CI)(e),!0),L=P&&M;(0,o.d4)((()=>{if(L)return ie.Z.disableRefresh(),()=>{ie.Z.enableRefresh()}}),[L]);const O=(0,o.I4)((()=>{p({chatId:e.chatId,messageId:e.id})}),[p,e.chatId,e.id]),F=(0,o.I4)((()=>{M&&S(),f(),(0,Bt.Ay)(),E()}),[f,M,S,E]),U=(0,o.I4)((e=>{u({volume:e/100}),g({isMuted:!1}),B(e/100)}),[g,u,B]),$=(0,o.I4)((()=>{h.$b&&!h.cj||(A(),g({isMuted:!l}))}),[l,g,A]),D=(0,o.I4)((()=>{1===c?(x(1.8),m({playbackRate:1.8})):(x(1),m({playbackRate:1}))}),[c,m,x]),q=(0,o.Ye)((()=>0===i||l?"icon-muted":i<.3?"icon-volume-1":i<.6?"icon-volume-2":"icon-volume-3"),[i,l]);if(!s)return o.ZP.createElement("div",{className:(0,ne.Z)("AudioPlayer",t),dir:I.isRtl?"rtl":void 0},o.ZP.createElement(Ee.Z,{round:!0,ripple:!h.wB,color:"translucent",size:"smaller",className:"player-button",disabled:T(),onClick:R,ariaLabel:"Previous track"},o.ZP.createElement("i",{className:"icon-skip-previous"})),o.ZP.createElement(Ee.Z,{round:!0,ripple:!h.wB,color:"translucent",size:"smaller",className:(0,ne.Z)("toggle-play","player-button",M?"pause":"play"),onClick:S,ariaLabel:M?"Pause audio":"Play audio"},o.ZP.createElement("i",{className:"icon-play"}),o.ZP.createElement("i",{className:"icon-pause"})),o.ZP.createElement(Ee.Z,{round:!0,ripple:!h.wB,color:"translucent",size:"smaller",className:"player-button",disabled:N(),onClick:k,ariaLabel:"Next track"},o.ZP.createElement("i",{className:"icon-skip-next"})),o.ZP.createElement("div",{className:"AudioPlayer-content",onClick:O},v?function(e){const{title:t,performer:s,fileName:n}=e;return o.ZP.createElement(o.ZP.Fragment,null,o.ZP.createElement("div",{className:"title",dir:"auto"},(0,Pt.Z)(t||n)),s&&o.ZP.createElement("div",{className:"subtitle",dir:"auto"},(0,Pt.Z)(s)))}(v):function(e,t){return o.ZP.createElement(o.ZP.Fragment,null,o.ZP.createElement("div",{className:"title",dir:"auto"},t&&(0,Pt.Z)(t)),o.ZP.createElement("div",{className:"subtitle",dir:"auto"},e))}(I("AttachAudio"),C),o.ZP.createElement(Et.Z,null)),o.ZP.createElement(Ee.Z,{round:!0,className:"player-button volume-button",color:"translucent",size:"smaller",ariaLabel:"Volume",withClickPropagation:!0},o.ZP.createElement("i",{className:q,onClick:$}),!h.cj&&o.ZP.createElement(o.ZP.Fragment,null,o.ZP.createElement("div",{className:"volume-slider-spacer"}),o.ZP.createElement("div",{className:"volume-slider"},o.ZP.createElement(Qt.Z,{value:l?0:100*i,onChange:U})))),P&&o.ZP.createElement(Ee.Z,{round:!0,className:(0,ne.Z)("playback-button",1!==c&&"applied"),color:"translucent",size:"smaller",ariaLabel:"Playback Rate",ripple:!h.wB,onClick:D},o.ZP.createElement("span",{className:"playback-button-inner"},"2Х")),o.ZP.createElement(Ee.Z,{round:!0,className:"player-close",color:"translucent",size:"smaller",onClick:F,ariaLabel:"Close player"},o.ZP.createElement("i",{className:"icon-close"})))}));var jt=s(2607),Ht=s(172);const _t=(0,o.X$)((0,n.c$)(((e,{chatId:t})=>{const s=(0,i.Z1)(e,t),n=(0,jt.Bj)(e,t);return{groupCall:n,usersById:e.users.byId,chatsById:e.chats.byId,activeGroupCallId:e.groupCalls.activeGroupCallId,isActive:(n?n.participantsCount>0&&n.isLoaded:s&&s.isCallNotEmpty&&s.isCallActive)&&e.groupCalls.activeGroupCallId!==(null==n?void 0:n.id)}}))((({chatId:e,isActive:t,groupCall:s,hasPinnedOffset:a,usersById:r,chatsById:i})=>{const{joinGroupCall:c,subscribeToGroupCallUpdates:d}=(0,n.uC)(),l=(0,Ce.Z)(),u=(0,o.I4)((()=>{c({chatId:e})}),[c,e]),m=null==s?void 0:s.participants,h=(0,o.Ye)((()=>m?Object.values(m).filter(((e,t)=>t<3)).map((({id:e,isUser:t})=>{if(t){if(!r[e])return;return{user:r[e]}}if(i[e])return{chat:i[e]}})).filter(Boolean):[]),[i,m,r]);if((0,o.d4)((()=>{if(null!=s&&s.id&&(t||!s.isLoaded))return d({id:s.id,subscribed:!0}),()=>{d({id:s.id,subscribed:!1})}}),[null==s?void 0:s.id,null==s?void 0:s.isLoaded,t,d]),s)return o.ZP.createElement("div",{className:(0,ne.Z)("GroupCallTopPane",a&&"has-pinned-offset",!t&&"is-hidden"),onClick:u},o.ZP.createElement("div",{className:"info"},o.ZP.createElement("span",{className:"title"},l("VoipGroupVoiceChat")),o.ZP.createElement("span",{className:"participants"},l("Participants",s.participantsCount||0,"i"))),o.ZP.createElement("div",{className:"avatars"},h.map((e=>{if(e)return e.user?o.ZP.createElement(Ht.Z,{key:e.user.id,user:e.user}):o.ZP.createElement(Ht.Z,{key:e.chat.id,chat:e.chat})}))),o.ZP.createElement(Ee.Z,{round:!0,className:"join"},l("VoipChatJoin")))}))),zt=(0,o.X$)((0,n.c$)(((e,{chatId:t,threadId:s,messageListType:n})=>{const{isLeftColumnShown:a,lastSyncTime:o,shouldSkipHistoryAnimations:r}=e,{byId:c}=e.chats,d=(0,i.Z1)(e,t),{typingStatus:l}=d||{},{chatId:m,messageId:h}=e.audioPlayer,g=m&&h?(0,i.hj)(e,m,h):void 0;let p;if("pinned"===n){const s=(0,i.KB)(e,t);p=null==s?void 0:s.length}else if("scheduled"===n){const s=(0,i.qy)(e,t);p=null==s?void 0:s.length}else if("thread"===n&&s!==u._f){const n=(0,i.tZ)(e,t,s);p=(null==n?void 0:n.messagesCount)||0}const f={typingStatus:l,isLeftColumnShown:a,isRightColumnShown:(0,i.Jf)(e),isSelectModeActive:(0,i.CA)(e),audioMessage:g,chat:d,chatsById:c,messagesCount:p,isChatWithSelf:(0,i.FM)(e,t),isChatWithBot:d&&(0,i.xo)(e,d),lastSyncTime:o,shouldSkipHistoryAnimations:r,currentTransitionKey:Math.max(0,e.messages.messageLists.length-1),connectionState:e.connectionState},I=(0,i.Zw)(e,t);if("thread"!==n||!I)return f;if(Object.assign(f,{messagesById:I}),s!==u._f){const n=(0,i.qS)(e,t,s),a=n?(0,i.hj)(e,t,n):void 0,o=a?(0,i.cv)(e,a):void 0;return{...f,pinnedMessageIds:n,canUnpin:!1,topMessageSender:o}}const v=(0,i.KB)(e,t);if(null!=v&&v.length){const t=I[v[0]],{canUnpin:n}=t&&(0,i._k)(e,t,s)||{};return{...f,pinnedMessageIds:v,canUnpin:n}}return f}))((({chatId:e,threadId:t,messageListType:s,isReady:r,pinnedMessageIds:c,messagesById:l,canUnpin:m,topMessageSender:g,typingStatus:p,isSelectModeActive:f,isLeftColumnShown:I,isRightColumnShown:v,audioMessage:y,chat:Z,chatsById:P,messagesCount:C,isChatWithSelf:w,isChatWithBot:b,lastSyncTime:S,shouldSkipHistoryAnimations:E,currentTransitionKey:M,connectionState:k})=>{const{openChatWithInfo:R,pinMessage:T,focusMessage:N,openChat:B,openPreviousChat:A,loadPinnedMessages:x,toggleLeftColumn:L,exitMessageSelectMode:O}=(0,n.uC)(),F=(0,Ce.Z)(),U=(0,o.sO)(!0),[$,D]=(0,o.eJ)(0),q=Array.isArray(c)?c[$]:c,Q=l&&q?l[q]:void 0,G=Array.isArray(c)?c.length:c?1:void 0,j=Z&&(0,d.U)(F,Z).length,H=g?(0,d.OU)(F,g):void 0;(0,o.d4)((()=>{t===u._f&&S&&r&&x({chatId:e})}),[e,x,S,t,r]),(0,o.d4)((()=>{D(0)}),[c]),(0,ht.Z)(e,q,Q);const{width:_}=it(),z=_<=a.ks,V=h.p7&&I,K=(0,o.sO)(null),Y=(0,o.sO)(!0),W=(0,o.I4)((()=>{R({id:e})}),[R,e]),X=(0,o.I4)((t=>{T({chatId:e,messageId:t,isUnpin:!0})}),[T,e]),J=(0,o.I4)((()=>{if(Q){N({chatId:Q.chatId,threadId:t,messageId:Q.id});const e=(0,mt.Z)(G||1,$+1);D(e)}}),[Q,N,t,G,$]),ee=(0,o.I4)((()=>{B({id:e,threadId:u._f,type:"pinned"})}),[B,e]),te=(0,o.I4)((()=>{setTimeout((()=>{U.current=!0}),450)}),[]),se=(0,o.I4)((e=>{if(U.current){if(U.current=!1,h.wB){const e=document.getElementById(a.R2);e&&e.blur()}if(f)return O(),void te();if(t===u._f&&"thread"===s&&0===M)return h.wB||V?(e.stopPropagation(),B({id:void 0})):L(),void te();A(),te()}}),[t,s,M,f,A,V,B,L,O,te]),ae=(0,o.Ye)((()=>{if(z&&P)return(0,i.A1)((0,n.Rd)())||void 0}),[z,P]),oe=_>=a.ks&&_a.l3&&_30),re=oe||_>a._m&&_{const e=K.current;if(e)return re&&Ie?void(v||oe?(Y.current&&(e.classList.add("tools-stacked","animated"),Y.current=!1),setTimeout((()=>{e.classList.remove("animated")}),350)):(e.classList.remove("tools-stacked"),Y.current=!0)):(e.classList.remove("tools-stacked","animated"),void(Y.current=!0))}),[re,Ie,oe,v]);const ve=(!Pe()||"connectionStateConnecting"===k)&&(h.wB||h.p7&&!V);function ye(){return ve?o.ZP.createElement(o.ZP.Fragment,null,we(),o.ZP.createElement("h3",null,F("WaitingForNetwork"))):"thread"===s&&t===u._f?o.ZP.createElement(o.ZP.Fragment,null,(z||M>0)&&we(V,!0),o.ZP.createElement("div",{className:"chat-info-wrapper",onClick:W},(0,d.YC)(e)?o.ZP.createElement(ft.Z,{userId:e,typingStatus:p,withFullInfo:b,withMediaViewer:!0,withUpdatingStatus:!0,noRtl:!0}):o.ZP.createElement(It.Z,{chatId:e,typingStatus:p,noRtl:!0,withMediaViewer:!0,withFullInfo:!0,withUpdatingStatus:!0}))):"thread"===s?o.ZP.createElement(o.ZP.Fragment,null,we(),o.ZP.createElement("h3",null,F("CommentsCount",C,"i"))):"pinned"===s?o.ZP.createElement(o.ZP.Fragment,null,we(),o.ZP.createElement("h3",null,F("PinnedMessagesCount",C,"i"))):"scheduled"===s?o.ZP.createElement(o.ZP.Fragment,null,we(),o.ZP.createElement("h3",null,w?F("Reminders"):F("messages",C,"i"))):void 0}function we(e=!1,t=!1){return o.ZP.createElement("div",{className:"back-button"},o.ZP.createElement(Ee.Z,{round:!0,size:"smaller",color:"translucent",onClick:se,ariaLabel:F(e?"Close":"Back")},o.ZP.createElement("div",{className:(0,ne.Z)("animated-close-icon",!e&&"state-back")})),t&&ae&&o.ZP.createElement("div",{className:"unread-count active"},(0,pt.bi)(ae)))}const be=Boolean(ie&&le);return o.ZP.createElement("div",{className:"MiddleHeader",ref:K},o.ZP.createElement(Ze.Z,{name:E?"none":"slide-fade",activeKey:ve?1/0:M},ye),o.ZP.createElement(_t,{hasPinnedOffset:ue&&!!he||ie&&!!le,chatId:e}),ue&&he&&o.ZP.createElement(Rt,{key:e,message:he,count:ge||0,index:$,customTitle:fe,className:(0,ne.Z)(me,be&&"full-width"),onUnpinMessage:pe?X:void 0,onClick:J,onAllPinnedClick:ee}),o.ZP.createElement("div",{className:"header-tools"},be&&o.ZP.createElement(Gt,{key:(0,d.Tp)(le),message:le,className:de}),o.ZP.createElement(yt,{chatId:e,threadId:t,messageListType:s,canExpandActions:!be})))})));var Vt=s(2645),Kt=s(274);function Yt(e){return"albumId"in e}function Wt(e,t){let s,n=[],a={originalDate:e[0].date,datetime:Number((0,N.$Y)(1e3*e[0].date)),senderGroups:[n]};const o=[a];return e.forEach(((r,i)=>{r.isInAlbum?s?(s.messages.push(r),r.content.text&&(s.mainMessage=r)):s={albumId:r.groupedId,messages:[r],mainMessage:r}:n.push(r);const c=e[i+1];if(!s||c&&c.groupedId&&c.groupedId===s.albumId||(n.push(s),s=void 0),c){const e=Number((0,N.$Y)(1e3*c.date));a.datetime!==e?(a={originalDate:c.date,datetime:e,senderGroups:[]},o.push(a),n=[],a.senderGroups.push(n)):(c.id===t||r.senderId!==c.senderId||r.isOutgoing!==c.isOutgoing||(0,d.Lo)(r)||(0,d.Lo)(c)||r.forwardInfo&&c.forwardInfo&&(r.forwardInfo.senderUserId!==c.forwardInfo.senderUserId||r.forwardInfo.fromChatId!==c.forwardInfo.fromChatId||r.forwardInfo.hiddenUserName!==c.forwardInfo.hiddenUserName)||r.inlineButtons||c.inlineButtons||c.date-r.date>600)&&(n=[],a.senderGroups.push(n))}})),o}var Xt=s(386),Jt=s(2202);var es=s(7675),ts=s(539),ss=s(3657);const ns=h.wZ?1e3:350,as=h.wB?300:500;var os=s(7240),rs=s(935);function is(e){return"number"==typeof e}function cs(e,t){return e?t?238:175:t?238:100}function ds(e,t){const s=(0,d.B4)(e),n=(0,d.MF)(e),a=(0,d.O$)(e)||(0,d.F$)(e),o=(0,d.b7)(e),r=Boolean((0,d.F$)(e)),{width:i,height:c}=a?(0,Zt.Eh)(a,s,n,r,t):(0,Zt.GC)(o,s,n,t),l=cs(Boolean((0,d.UD)(e)));let u=1;ie+t),t)}function us(e,t,s){return es?s:e}function ms(e){const t={width:0,height:0};return e.forEach((({dimensions:e,sides:s})=>{2&s&&(t.width=e.width+e.x),4&s&&(t.height=e.height+e.y)})),t}function hs(e,t,s,n){const a=n.messages.map((e=>{const t=ds(e);return t.width/t.height})),o=function(e){return e.map((e=>e>1.2?"w":e<.8?"n":"q")).join("")}(a),r=function(e){return e.reduce(((e,t)=>t+e),1)/e.length}(a),i=a.length,c=a.some((e=>e>2)),d=(0,Zt.kc)(e,t,!1,s)-(t?2.5:0)*Zt.Gw;let l;const u={ratios:a,proportions:o,averageRatio:r,maxWidth:d,minWidth:100,maxHeight:d,spacing:2};return l=i>=5||c?function({ratios:e,averageRatio:t,maxWidth:s,minWidth:n,spacing:a,maxHeight:o=4*s/3}){const r=function(e,t){return e.map((e=>t>1.1?us(e,1,2.75):us(e,.6667,1)))}(e,t),i=e.length,c=new Array(i),d=[],l=e=>{const t=[];let n=0;e.forEach((e=>{t.push(((e,t)=>{const n=ls(r.slice(e,e+t),0);return(s-(t-1)*a)/n})(n,e)),n+=e})),d.push({lineCounts:e,heights:t})};for(let e=1;e!==i;++e){const t=i-e;e<=3&&t<=3&&l([e,t])}for(let e=1;e!==i-1;++e)for(let s=1;s!==i-e;++s){const n=i-e-s;e<=3&&s<=(t<.85?4:3)&&n<=3&&l([e,s,n])}for(let e=1;e!==i-1;++e)for(let t=1;t!==i-e;++t)for(let s=1;s!==i-e-t;++s){const n=i-e-t-s;e<=3&&t<=3&&s<=3&&n<=4&&l([e,t,s,n])}let u,m=0;for(let e=0;e{for(let e=1;e!==r;++e)if(s[e-1]>s[e])return 1.5;return 1})(),h=Math.abs(i-o)*c*l;(!u||h1.4&&t[1]-t[0]<.2?function(e){const{ratios:t,maxWidth:s,spacing:n,maxHeight:a}=e,o=Math.round(Math.min(s/t[0],Math.min(s/t[1],(a-n)/2)));return[{dimensions:{x:0,y:0,width:s,height:o},sides:11},{dimensions:{x:0,y:o+n,width:s,height:o},sides:14}]}(e):"ww"===s||"qq"===s?function(e){const{ratios:t,maxWidth:s,spacing:n,maxHeight:a}=e,o=(s-n)/2,r=Math.round(Math.min(o/t[0],Math.min(o/t[1],a)));return[{dimensions:{x:0,y:0,width:o,height:r},sides:13},{dimensions:{x:o+n,y:0,width:o,height:r},sides:7}]}(e):function(e){const{ratios:t,minWidth:s,maxWidth:n,spacing:a,maxHeight:o}=e,r=Math.round(1.5*s),i=Math.min(Math.round(Math.max(.4*(n-a),(n-a)/t[0]/(1/t[0]+1/t[1]))),n-a-r),c=n-i-a,d=Math.min(o,Math.round(Math.min(c/t[0],i/t[1])));return[{dimensions:{x:0,y:0,width:c,height:d},sides:13},{dimensions:{x:c+a,y:0,width:i,height:d},sides:7}]}(e)}(u):3===i?function(e){const{proportions:t}=e;return"n"===t[0]?function(e){const{maxHeight:t,spacing:s,ratios:n,maxWidth:a,minWidth:o}=e,r=t,i=Math.round(Math.min((t-s)/2,n[1]*(a-s)/(n[2]+n[1]))),c=r-i-s,d=Math.max(o,Math.round(Math.min((a-s)/2,Math.min(i*n[2],c*n[1])))),l=Math.min(Math.round(r*n[0]),a-s-d);return[{dimensions:{x:0,y:0,width:l,height:r},sides:13},{dimensions:{x:l+s,y:0,width:d,height:c},sides:3},{dimensions:{x:l+s,y:c+s,width:d,height:i},sides:6}]}(e):function(e){const{maxWidth:t,ratios:s,maxHeight:n,spacing:a}=e,o=t,r=Math.round(Math.min(o/s[0],.66*(n-a))),i=(t-a)/2,c=Math.min(n-r-a,Math.round(Math.min(i/s[1],i/s[2])));return[{dimensions:{x:0,y:0,width:o,height:r},sides:11},{dimensions:{x:0,y:r+a,width:i,height:c},sides:12},{dimensions:{x:i+a,y:r+a,width:o-i-a,height:c},sides:6}]}(e)}(u):function(e){const{proportions:t}=e;return"w"===t[0]?function({maxWidth:e,ratios:t,spacing:s,maxHeight:n,minWidth:a}){const o=e,r=Math.round(Math.min(o/t[0],.66*(n-s))),i=Math.round((e-2*s)/(t[1]+t[2]+t[3])),c=Math.max(a,Math.round(Math.min(.4*(e-2*s),i*t[1]))),d=Math.round(Math.max(Math.max(a,.33*(e-2*s)),i*t[3])),l=o-c-d-2*s,u=Math.min(n-r-s,i);return[{dimensions:{x:0,y:0,width:o,height:r},sides:11},{dimensions:{x:0,y:r+s,width:c,height:u},sides:12},{dimensions:{x:c+s,y:r+s,width:l,height:u},sides:4},{dimensions:{x:c+s+l+s,y:r+s,width:d,height:u},sides:6}]}(e):function({maxHeight:e,ratios:t,maxWidth:s,spacing:n,minWidth:a}){const o=e,r=Math.round(Math.min(o*t[0],.6*(s-n))),i=Math.round((e-2*n)/(1/t[1]+1/t[2]+1/t[3])),c=Math.round(i/t[1]),d=Math.round(i/t[2]),l=o-c-d-2*n,u=Math.max(a,Math.min(s-r-n,i));return[{dimensions:{x:0,y:0,width:r,height:o},sides:13},{dimensions:{x:r+n,y:0,width:u,height:c},sides:3},{dimensions:{x:r+n,y:c+n,width:u,height:d},sides:2},{dimensions:{x:r+n,y:c+d+2*n,width:u,height:l},sides:6}]}(e)}(u),{layout:l,containerStyle:ms(l)}}let gs;function ps(e){return gs||(gs=document.createElement("span"),gs.style.font=h.cj?'400 12px system-ui, -apple-system, BlinkMacSystemFont, "Roboto", "Apple Color Emoji", "Helvetica Neue", sans-serif':'400 12px "Roboto", -apple-system, "Apple Color Emoji", BlinkMacSystemFont, "Helvetica Neue", sans-serif',gs.style.whiteSpace="nowrap",gs.style.position="absolute",gs.style.left="-999px",gs.style.opacity=".01",document.body.appendChild(gs)),gs.innerHTML=e,gs.offsetWidth}function fs(e,t,s,n,a,r){(0,o.bt)((()=>{if(s&&e.current){const t=e.current.closest(".MessageList");(0,ts.Z)(t,e.current,a?"end":"centerOrTop",20,void 0!==n?1e3:void 0,n,void 0,r)}}),[e,t,s,n,a,r])}var Is=s(8005);const vs=(0,o.X$)((e=>{const{isOpen:t}=e,s=(0,De.Z)($e.gl.Extra,"ContextMenuContainer",!t);return s?o.ZP.createElement(s,e):void 0})),ys=(0,o.X$)((0,n.c$)(((e,{message:t})=>{const{byId:s}=e.users,n=t.senderId,{targetUserIds:a,targetChatId:o}=t.content.action||{},r=t.replyToMessageId,c=r?(0,i.hj)(e,t.chatId,r):void 0,l=(0,i._X)(e,t),{direction:u,noHighlight:m}=l&&e.focusedMessage||{},h=(0,i.Z1)(e,t.chatId);return{usersById:s,sender:h&&((0,d.eA)(h)||n===t.chatId)?h:n?(0,i.dy)(e,n):void 0,targetChatId:o,targetUserIds:a,targetMessage:c,isFocused:l,...l&&{focusDirection:u,noFocusHighlight:m}}}))((({message:e,observeIntersection:t,isEmbedded:s,appearanceOrder:n=0,isLastInList:a,usersById:r,sender:i,targetUserIds:c,targetMessage:d,targetChatId:l,isFocused:u,focusDirection:m,noFocusHighlight:h})=>{const g=(0,o.sO)(null);(0,ss._N)(g,t),(0,ht.Z)(e.chatId,e.replyToMessageId,d),fs(g,e.chatId,u,m,h);const p=(0,Ce.Z)(),f=n<=0,[I,v]=(0,ye.Z)(f);(0,o.d4)((()=>{f||setTimeout(v,10*n)}),[n,v,f]);const{transitionClassNames:y}=(0,ce.Z)(I,void 0,f,!1),Z=(0,o.Ye)((()=>c?c.map((e=>null==r?void 0:r[e])).filter(Boolean):void 0),[c,r]),P=(0,Is.D)(p,e,i,Z,d,l,s?{isEmbedded:!0,asPlain:!0}:void 0),{isContextMenuOpen:C,contextMenuPosition:w,handleBeforeContextMenu:b,handleContextMenu:S,handleContextMenuClose:E,handleContextMenuHide:M}=(0,os.Z)(g),k=void 0!==w;if(s)return o.ZP.createElement("span",{className:"embedded-action-message"},(0,Pt.Z)(P));const R=(0,ne.Z)("ActionMessage message-list-item",u&&!h&&"focused",k&&"has-menu-open",a&&"last-in-list",y);return o.ZP.createElement("div",{ref:g,id:`message${e.id}`,className:R,"data-message-id":e.id,onMouseDown:e=>{(0,Xt.q)(e),b(e)},onContextMenu:S},o.ZP.createElement("span",null,P),w&&o.ZP.createElement(vs,{isOpen:C,anchor:w,message:e,messageListType:"thread",onClose:E,onCloseAnimationEnd:M}))}))),Zs=({className:e,message:t,sender:s,title:n,customText:a,isProtected:r,observeIntersection:i,onClick:c})=>{const l=(0,o.sO)(null),u=(0,ss.Op)(l,i),m=(0,Ct.Z)(t&&(0,d.Ti)(t,"pictogram"),!u),h=t&&`sticker-reply-thumb${t.id}`,g=bt(t),p=Boolean(t&&(0,d.Y5)(t)),f=(0,Ce.Z)(),I=s&&(0,d.OU)(f,s);return o.ZP.createElement("div",{ref:l,className:(0,ne.Z)("EmbeddedMessage",e),onClick:t?c:void 0},g&&function(e,t,s,n,a){const{width:r,height:i}=(0,Zt.W7)();return o.ZP.createElement(o.ZP.Fragment,null,o.ZP.createElement("img",{id:e,src:s||t,width:r,height:i,alt:"",className:n?"round":"",draggable:!a}),a&&o.ZP.createElement("span",{className:"protector"}))}(h,g,m,p,r),o.ZP.createElement("div",{className:"message-text"},o.ZP.createElement("p",{dir:"auto"},t?(0,d.Lo)(t)?o.ZP.createElement(ys,{message:t,isEmbedded:!0}):(0,Pt.Z)((0,d.MK)(f,t,Boolean(g))):a||" "),o.ZP.createElement("div",{className:"message-title",dir:"auto"},(0,Pt.Z)(I||n||" "))))};var Ps=s(2535),Cs=s(4752),ws=s(8018);const bs=(0,o.X$)((({message:e,outgoingStatus:t,signature:s,onClick:n})=>{const a=(0,Ce.Z)(),[r,i]=(0,ye.Z)(),c=(0,o.Ye)((()=>{if(!r)return;const t=(0,N.SA)(1e3*e.date,a.code),s=e.isEdited&&(0,N.SA)(1e3*e.editDate,a.code),n=e.forwardInfo&&(0,N.SA)(1e3*e.forwardInfo.date,a.code);let o=t;return s&&(o+="\n",o+=a("lng_edited_date").replace("{date}",s)),n&&(o+="\n",o+=a("lng_forwarded_date").replace("{date}",n)),o}),[r,a,e]);return o.ZP.createElement("span",{className:"MessageMeta",dir:a.isRtl?"rtl":"ltr",onClick:n},Boolean(e.views)&&o.ZP.createElement(o.ZP.Fragment,null,o.ZP.createElement("span",{className:"message-views"},(0,pt.bi)(e.views)),o.ZP.createElement("i",{className:"icon-channelviews"})),s&&o.ZP.createElement("span",{className:"message-signature"},(0,Pt.Z)(s)),o.ZP.createElement("span",{className:"message-time",title:c,onMouseEnter:i},e.isEdited&&`${a("EditedMessage")} `,(0,N.mr)(1e3*e.date,a)),t&&o.ZP.createElement(ws.Z,{status:t}))}));var Ss=s(692),Es=s(7799),Ms=s(4851);const ks=({message:e,observeIntersection:t,observeIntersectionForPlaying:s,shouldLoop:n,lastSyncTime:r})=>{const i=(0,o.sO)(null),[c,l,u]=(0,ye.Z)(),m=e.content.sticker,{isAnimated:h,stickerSetId:g}=m,p=g===a.n,f=(0,ss.Op)(i,t),I=(0,ss.Op)(i,s),v=m.isPreloadedGlobally?`sticker${m.id}`:(0,d.Ti)(e,"inline"),y=bt(e),Z=(0,Ct.Z)(v,!f,(0,d.kG)(e,"inline",!0),r),P=Boolean(Z),[C,w]=(0,ye.Z)(P),b=h?C:P,S=(0,Ss.Z)(b),{width:E,height:M}=(0,Zt.Wr)(m),k=(0,ne.Z)("thumbnail",!y&&"empty"),R=(0,ne.Z)("Sticker media-inner",p&&"inactive");return o.ZP.createElement("div",{ref:i,className:R,onClick:p?void 0:l},!b&&o.ZP.createElement("img",{id:`sticker-thumb-${e.id}`,src:y,width:E,height:M,alt:"",className:k}),!h&&o.ZP.createElement("img",{id:`sticker-${e.id}`,src:Z,width:E,height:M,alt:"",className:(0,ne.Z)("full-media",S)}),h&&P&&o.ZP.createElement(Es.Z,{key:v,className:(0,ne.Z)("full-media",S),id:v,animationData:Z,size:E,play:I,noLoop:!n,onLoad:w}),o.ZP.createElement(Ms.Z,{isOpen:c,fromSticker:m,onClose:u}))};var Rs=s(7854),Ts=s(2566),Ns=s(5866);function Bs(e,t){return(0,Ns.Z)((0,d.DH)(e),Boolean(t),h.wB&&!h.vX)}const As={dark:{outgoing:"rgb(135,116,225)",incoming:"rgb(33,33,33)"},light:{outgoing:"rgb(238,255,222)",incoming:"rgb(255,255,255)"}};var xs=s(9196);const Ls=({id:e,message:t,observeIntersection:s,noAvatars:n,canAutoLoad:a,isInSelectMode:r,isSelected:i,uploadProgress:c,size:l="inline",dimensions:u,nonInteractive:m,shouldAffectAppendix:h,isDownloading:g,isProtected:p,theme:f,onClick:I,onCancelUpload:v})=>{const y=(0,o.sO)(null),Z=((0,d.O$)(t)||(0,d.F$)(t)).blobUrl,P=(0,ss.Op)(y,s),[C,w]=(0,o.eJ)(a),b=C&&P,{mediaData:S,loadProgress:E}=(0,Ts.Z)((0,d.Ti)(t,l),!b),M=Z||S,k=Bs(t,M),{loadProgress:R}=(0,Ts.Z)((0,d.Ti)(t,"download"),!g),{isUploading:T,isTransferring:N,transferProgress:B}=(0,d.Sc)(t,c||(g?R:E),b&&!M),A=!1===(0,dt.Z)(C),x=(0,Ss.Z)(M),{shouldRender:L,transitionClassNames:O}=(0,ce.Z)(N,void 0,A,"slow"),{shouldRender:F,transitionClassNames:U}=(0,ce.Z)(!M&&!C),$=(0,o.I4)((()=>{T?v&&v(t):M?I&&I(t.id):w((e=>!e))}),[M,T,t,v,I]),D=(0,d.B4)(t);(0,o.bt)((()=>{if(!h)return;const e=y.current.closest(".message-content");M?function(e,t,s,n,a){return n?Promise.resolve(As[a||"light"][t?"outgoing":"incoming"]):async function(e,t){const s=new Image;s.src=e,s.width||await new Promise((e=>{s.onload=e}));const n=document.createElement("canvas"),a=n.getContext("2d");n.width=s.width,n.height=s.height,a.drawImage(s,0,0,s.width,s.height);const o=t?s.width-1:0,r=s.height-1;return`rgba(${Array.from(a.getImageData(o,r,1,1).data).join(",")})`}(e,t)}(M,D,0,i,f).then((t=>{e.style.setProperty("--appendix-bg",t),e.setAttribute("data-has-custom-appendix","")})):e.classList.add("has-appendix-thumb")}),[M,D,h,r,i,f]);const{width:q,height:Q,isSmall:G}=u||ds(t,n),j=(0,ne.Z)("media-inner",!T&&!m&&"interactive",G&&"small-image",q===Q&&"square-image"),H=u?`width: ${q}px; height: ${Q}px; left: ${u.x}px; top: ${u.y}px;`:"";return o.ZP.createElement("div",{id:e,ref:y,className:j,style:H,onClick:T?void 0:$},o.ZP.createElement("canvas",{ref:k,className:"thumbnail",style:`width: ${q}px; height: ${Q}px`}),o.ZP.createElement("img",{src:M,className:`full-media ${x}`,width:q,height:Q,alt:"",draggable:!p}),p&&o.ZP.createElement("span",{className:"protector"}),L&&!F&&o.ZP.createElement("div",{className:`media-loading ${O}`},o.ZP.createElement(xs.Z,{progress:B,onClick:T?$:void 0})),F&&o.ZP.createElement("i",{className:(0,ne.Z)("icon-download",U)}),N&&o.ZP.createElement("span",{className:"message-transfer-progress"},Math.round(100*B),"%"))};var Os=s(2019),Fs=s(6898),Us=s(4753);function $s(e,t){var s;const n=(0,o.sO)(null===(s=e.current)||void 0===s?void 0:s.paused),a=(0,o.sO)();a.current=t;const r=(0,o.I4)((()=>{e.current&&(n.current=!e.current.paused,n.current&&e.current.pause())}),[e]),i=(0,o.I4)((()=>{e.current&&n.current&&a.current&&document.body.contains(e.current)&&(0,Us.Z)(e.current)}),[e]),c=(0,o.I4)((()=>{(0,C.T2)(i)}),[i]);(0,de.Z)(r,c),(0,se.ZP)(r,i)}function Ds(){return(Ds=Object.assign||function(e){for(var t=1;t{var I;const v=(0,o.sO)(null),y=(0,o.sO)(null),Z=(0,d.b7)(t)||(0,d.Cg)(t),P=Z.blobUrl,C=(0,ss.Op)(v,s),[w,b]=(0,o.eJ)(r),S=Boolean(w&&C&&l),[E,M]=(0,o.eJ)(i),k=(0,Ct.Z)((0,d.Ti)(t,"pictogram"),!(C&&l),(0,d.kG)(t,"pictogram"),l),R=(0,Ss.Z)(k),{mediaData:T,loadProgress:B}=(0,Ts.Z)((0,d.Ti)(t,"inline"),!S,(0,d.kG)(t,"inline"),l),A=P||T,x=Boolean(C&&A),L=Bs(t,k),{loadProgress:O}=(0,Ts.Z)((0,d.Ti)(t,"download"),!p,u.IU.BlobUrl,l),{isBuffered:F,bufferingHandlers:U}=(0,Os.Z)(!r),{isUploading:$,isTransferring:D,transferProgress:q}=(0,d.Sc)(t,c||(p?O:B),S&&!F||p),Q=!1===(0,dt.Z)(w),{shouldRender:G,transitionClassNames:j}=(0,ce.Z)(D,void 0,Q),{shouldRender:H,transitionClassNames:_}=(0,ce.Z)(w&&!E&&!G),[z,V]=(0,o.eJ)(0),K=(0,o.I4)((e=>{V(Math.max(0,e.currentTarget.currentTime-1))}),[]),Y=(null===(I=y.current)||void 0===I?void 0:I.duration)||Z.duration||0,W=(0,d.B4)(t),X=(0,d.MF)(t),{width:J,height:ee}=m||(0,Zt.GC)(Z,W,X,a);$s(y,x),(0,Fs.Z)(y,[x]);const te=(0,o.I4)((()=>{$?g&&g(t):p?(0,n.uC)().cancelMessageMediaDownload({message:t}):A?A&&!E?(M(!0),y.current.play()):h&&h(t.id):b((e=>!e))}),[$,p,A,E,h,g,t]),se=(0,ne.Z)("media-inner dark",!$&&"interactive"),ae=m?`width: ${J}px; height: ${ee}px; left: ${m.x}px; top: ${m.y}px;`:"";return o.ZP.createElement("div",{ref:v,id:e,className:se,style:ae,onClick:$?void 0:te},o.ZP.createElement("canvas",{ref:L,className:"thumbnail",style:`width: ${J}px; height: ${ee}px;`}),o.ZP.createElement("img",{src:k,className:(0,ne.Z)("thumbnail",R),style:`width: ${J}px; height: ${ee}px;`,alt:"",draggable:!f}),x&&o.ZP.createElement("video",Ds({ref:y,className:"full-media",width:J,height:ee,autoPlay:E,muted:!0,loop:!0,playsInline:!0},U,{draggable:!f,onTimeUpdate:K}),o.ZP.createElement("source",{src:A})),f&&o.ZP.createElement("span",{className:"protector"}),H&&o.ZP.createElement("i",{className:(0,ne.Z)("icon-large-play",_)}),G&&o.ZP.createElement("div",{className:(0,ne.Z)("media-loading",j)},o.ZP.createElement(xs.Z,{progress:q,onClick:te})),!w&&o.ZP.createElement("i",{className:"icon-download"}),D?o.ZP.createElement("span",{className:"message-transfer-progress"},$||p?`${Math.round(100*q)}%`:"..."):o.ZP.createElement("div",{className:"message-media-duration"},Z.isGif?"GIF":(0,N.k9)(Math.max(Y-z,0))))};var Qs=s(6272);const Gs=(0,n.c$)(((e,{contact:t})=>{const{countryList:{phoneCodes:s}}=e;return{user:(0,i.dy)(e,t.userId),phoneCodeList:s}}))((({contact:e,user:t,phoneCodeList:s})=>{const{openUserInfo:a}=(0,n.uC)(),{firstName:r,lastName:i,phoneNumber:c,userId:d}=e,l=(0,o.I4)((()=>{a({id:d})}),[a,d]);return o.ZP.createElement("div",{className:(0,ne.Z)("Contact",Boolean(d)&&"interactive"),onClick:d?l:void 0},o.ZP.createElement(Ht.Z,{size:"large",user:t,text:r||i}),o.ZP.createElement("div",{className:"contact-info"},o.ZP.createElement("div",{className:"contact-name"},r," ",i),o.ZP.createElement("div",{className:"contact-phone"},(0,Qs.WZ)(s,c))))}));var js=s(1218),Hs=s(4434),_s=s(6937);function zs(e,t){return t>0?(e/t*100).toFixed():0}const Vs=({answer:e,voteResults:t,totalVoters:s,maxVotersCount:n,correctResults:a,shouldAnimate:r})=>{const i=t&&t.find((t=>t.option===e.option)),c=0===a.length||-1!==a.indexOf(e.option),d=a.length>0&&c||(null==i?void 0:i.isChosen),l=i?zs(i.votersCount,s||0):0,[u,m]=(0,o.eJ)(r?0:l),h=(0,o.sO)(null),g=i?zs(i.votersCount,n||0):0,p=u{r&&m(l)}),[r,l]),(0,o.d4)((()=>{const e=h.current;if(e&&r){const t=e.firstElementChild,s=p?"":"stroke-dasharray: 100% 200%; stroke-dashoffset: -44";t?t.setAttribute("style",s):e.innerHTML=`\n \n \n `}}),[p,r]),!t||!i)return;const f=`width: ${g}%; transform:scaleX(${p?0:1})`;return o.ZP.createElement("div",{className:"PollOption",dir:"ltr"},o.ZP.createElement("div",{className:"poll-option-share "+("100"===l?"limit-width":"")},l,"%",d&&o.ZP.createElement("span",{className:(0,ne.Z)("poll-option-chosen",!c&&"wrong",r&&"animate")},o.ZP.createElement("i",{className:c?"icon-check":"icon-close"}))),o.ZP.createElement("div",{className:"poll-option-right"},o.ZP.createElement("div",{className:"poll-option-text",dir:"auto"},(0,Pt.Z)(e.text)),o.ZP.createElement("div",{className:(0,ne.Z)("poll-option-answer",d&&!c&&"wrong")},o.ZP.createElement("div",{className:"poll-option-corner",ref:h}),o.ZP.createElement("div",{className:"poll-option-line",style:f}))))},Ks=(0,o.X$)((0,n.c$)(((e,{poll:t})=>{const{recentVoterIds:s}=t.results,{serverTimeOffset:n,users:{byId:a}}=e;return s&&0!==s.length?{recentVoterIds:s,usersById:a,serverTimeOffset:n}:{}}))((({message:e,poll:t,recentVoterIds:s,usersById:a,onSendVote:r,serverTimeOffset:i})=>{const{loadMessage:c,openPollResults:d}=(0,n.uC)(),{id:l,chatId:u}=e,{summary:m,results:h}=t,[g,p]=(0,o.eJ)(!1),[f,I]=(0,o.eJ)([]),[v,y]=(0,o.eJ)(!1),[Z,P]=(0,o.eJ)(!1),[C,w]=(0,o.eJ)(!m.closed&&m.closeDate&&m.closeDate>0?Math.min(m.closeDate-Math.floor(Date.now()/1e3)+i,m.closePeriod):0),b=(0,o.sO)(null),{results:S,totalVoters:E}=h,M=S&&S.some((e=>e.isChosen)),k=!m.closed&&!M,R=!k&&m.isPublic&&Number(h.totalVoters)>0,T=k&&m.multipleChoice,B=S?Math.max(...S.map((e=>e.votersCount))):E,A=S?S.reduce(((e,t)=>(t.isCorrect&&e.push(t.option),e)),[]):[],x=m.answers.map((e=>({label:e.text,value:e.option,hidden:Boolean(m.quiz&&m.closePeriod&&C<=0)})));(0,o.d4)((()=>{g&&t.results.results&&t.results.results.some((e=>e.isChosen))&&p(!1)}),[g,t.results.results]),(0,o.d4)((()=>{C>0&&setTimeout((()=>w(C-1)),1e3);const e=b.current;if(e){const t=12*Math.PI,s=e.lastElementChild,n=e.firstElementChild;if(C<=5&&e.classList.add("hurry-up"),s&&n){const e=(m.closePeriod-C)/m.closePeriod*t;n.textContent=(0,N.k9)(C),s.firstElementChild.setAttribute("stroke-dashoffset",`-${e}`)}else e.innerHTML=`\n ${(0,N.k9)(C)}\n \n \n `}}),[C,m.closePeriod]),(0,o.d4)((()=>{m.quiz&&(C<=0||M&&!m.closed)&&c({chatId:u,messageId:l})}),[u,C,M,c,l,m.closed,m.quiz]),(0,o.d4)((()=>{let e;return m.quiz&&!m.closed&&m.closePeriod&&m.closePeriod>0&&(e=window.setTimeout((()=>{c({chatId:u,messageId:l})}),1e3*m.closePeriod)),()=>{e&&window.clearTimeout(e)}}),[k,u,c,l,m.closePeriod,m.closed,m.quiz]);const L=(0,o.Ye)((()=>s?s.reduce(((e,t)=>{const s=a[t];return s&&e.push(s),e}),[]):[]),[a,s]),O=(0,o.I4)((e=>{I([e]),p(!0),P(!0),r([e])}),[r]),F=(0,o.I4)((e=>{I(e)}),[]),U=(0,o.I4)((()=>{p(!0),P(!0),r(f)}),[r,f]),$=(0,o.I4)((()=>{d({chatId:u,messageId:l})}),[u,l,d]),D=(0,o.I4)((()=>{y(!0)}),[]),q=(0,o.I4)((()=>{y(!1),P(!1)}),[]);(0,o.d4)((()=>{Z&&M&&m.quiz&&h.results&&t.results.solution&&(h.results.find((e=>e.isChosen&&e.isCorrect))||y(!0))}),[M,Z,h.results,m.quiz,t.results.solution]);const Q=(0,Ce.Z)();return o.ZP.createElement("div",{className:"Poll",dir:Q.isRtl?"auto":"ltr"},v&&t.results.solution&&o.ZP.createElement(_s.Z,{message:(0,rs.H)(t.results.solution,t.results.solutionEntities),duration:5e3,onDismiss:q,containerId:"#middle-column-portals"}),o.ZP.createElement("div",{className:"poll-question"},(0,Pt.Z)(m.question,["emoji","br"])),o.ZP.createElement("div",{className:"poll-type"},Q(function(e){return void 0===e.isPublic?" ":e.quiz?e.isPublic?"QuizPoll":"AnonymousQuizPoll":e.closed?"FinalResults":e.isPublic?"PublicPoll":"AnonymousPoll"}(m)),L.length>0&&o.ZP.createElement("div",{className:"poll-recent-voters"},L.map((e=>o.ZP.createElement(Ht.Z,{size:"micro",user:e})))),C>0&&k&&o.ZP.createElement("div",{ref:b,className:"poll-countdown"}),m.quiz&&t.results.solution&&!k&&o.ZP.createElement(Ee.Z,{round:!0,size:"tiny",color:"translucent",className:"poll-quiz-help",disabled:v,onClick:D,ariaLabel:"Show Solution"},o.ZP.createElement("i",{className:"icon-lamp"}))),k&&o.ZP.createElement("div",{className:"poll-answers"},T?o.ZP.createElement(js.Z,{options:x,onChange:F,disabled:e.isScheduled||g,loadingOptions:g?f:void 0,round:!0}):o.ZP.createElement(Hs.Z,{name:`poll-${l}`,options:x,onChange:O,disabled:e.isScheduled||g,loadingOption:g?f[0]:void 0})),!k&&o.ZP.createElement("div",{className:"poll-results"},m.answers.map((function(e){return o.ZP.createElement(Vs,{key:e.option,shouldAnimate:Z,answer:e,voteResults:S,totalVoters:E,maxVotersCount:B,correctResults:A})}))),!R&&!T&&o.ZP.createElement("div",{className:"poll-voters-count"},function(e,t,s){return s?e(t?"Answer":"Vote",s,"i"):e(t?"Chat.Quiz.TotalVotesEmpty":"Chat.Poll.TotalVotesResultEmpty")}(Q,m.quiz,h.totalVoters)),T&&o.ZP.createElement(Ee.Z,{isText:!0,disabled:0===f.length,size:"tiny",onClick:U},Q("PollSubmitVotes")),R&&o.ZP.createElement(Ee.Z,{isText:!0,size:"tiny",onClick:$},Q("PollViewResults")))})));var Ys=s(8035),Ws=s(88);const Xs=(0,o.X$)((({message:e,observeIntersection:t,noAvatars:s,canAutoLoad:n,canAutoPlay:a,inPreview:r,lastSyncTime:i,isDownloading:c=!1,isProtected:l,theme:u,onMediaClick:m,onCancelMediaTransfer:h})=>{const g=(0,d.s1)(e);let p=!1;if(null!=g&&g.photo&&!g.video){const{width:t,height:s}=ds(e);p=t===s}const f=(0,o.I4)((()=>{m()}),[m]);if(!g)return;const{siteName:I,url:v,displayUrl:y,title:Z,description:P,photo:C,video:w}=g,b=(C||w)&&m&&!p,S=(0,Ys.Z)(P,170),E=(0,ne.Z)("WebPage",p&&"with-square-photo",!C&&!w&&!r&&"without-media",w&&"with-video");return o.ZP.createElement("div",{className:E,"data-initial":(I||y)[0],dir:"auto"},C&&!w&&o.ZP.createElement(Ls,{message:e,observeIntersection:t,noAvatars:s,canAutoLoad:n,size:p?"pictogram":"inline",nonInteractive:!b,onClick:b?f:void 0,onCancelUpload:h,isDownloading:c,isProtected:l,theme:u}),o.ZP.createElement("div",{className:"WebPage-text"},o.ZP.createElement(Ws.Z,{className:"site-name",url:v,text:I||y}),!r&&Z&&o.ZP.createElement("p",{className:"site-title"},(0,Pt.Z)(Z)),S&&o.ZP.createElement("p",{className:"site-description"},(0,Pt.Z)(S,["emoji","br"]))),!r&&w&&o.ZP.createElement(qs,{message:e,observeIntersection:t,noAvatars:s,canAutoLoad:n,canAutoPlay:a,lastSyncTime:i,onClick:b?f:void 0,onCancelUpload:h,isDownloading:c,isProtected:l}))}));var Js=s(9937);const en=(0,o.X$)((({message:e})=>{const t=(0,Ce.Z)(),s=(0,d.eO)(e),{title:n,text:a,amount:r,currency:i,isTest:c,photoUrl:l}=s;return o.ZP.createElement("div",{className:"Invoice"},n&&o.ZP.createElement("p",{className:"title"},(0,Pt.Z)(n)),a&&o.ZP.createElement("p",null,(0,Pt.Z)(a,["emoji","br"])),o.ZP.createElement("div",{className:"description "+(l?"has-image":"")},l&&o.ZP.createElement("img",{className:"invoice-image",src:l,alt:""}),o.ZP.createElement("p",{className:"description-text"},(0,Js.x)(r,i,t.code),c&&o.ZP.createElement("span",null,t("PaymentTestInvoice")))))}));function tn(e){return(0,o.X$)((0,n.c$)(((e,t)=>{const{message:s}=t;return{isInSelectMode:(0,i.CA)(e),isSelected:(0,i.vk)(e,s.id)}}))((t=>{const{isInSelectMode:s,isSelected:a,message:r,dimensions:i}=t,{toggleMessageSelection:c}=(0,n.uC)(),d=(0,o.I4)((e=>{e.stopPropagation(),c({messageId:r.id,withShift:null==e?void 0:e.shiftKey})}),[c,r]),l=(0,o.Ye)((()=>({...t,isInSelectMode:s,isSelected:a,dimensions:{...t.dimensions,x:0,y:0},onClick:s?void 0:t.onClick})),[t,s,a]);return o.ZP.createElement("div",{className:(0,ne.Z)("album-item-select-wrapper",a&&"is-selected"),style:i?`left: ${i.x}px; top: ${i.y}px;`:"",onClick:s?d:void 0},s&&o.ZP.createElement("div",{className:"message-select-control"},a&&o.ZP.createElement("i",{className:"icon-select"})),o.ZP.createElement(e,l))})))}const sn=tn(Ls),nn=tn(qs),an=(0,n.c$)(((e,{album:t})=>{const{chatId:s}=t.mainMessage,n=(0,i.Pu)(e),a=(0,i.xs)(e,s);return{theme:n,uploadsById:e.fileUploads.byMessageLocalId,activeDownloadIds:a}}))((({album:e,observeIntersection:t,hasCustomAppendix:s,lastSyncTime:a,isOwn:r,isProtected:c,albumLayout:l,onMediaClick:u,uploadsById:m,activeDownloadIds:h,theme:g})=>{const{cancelSendingMessage:p}=(0,n.uC)(),f=e.messages.length,I=(0,o.I4)((e=>{p({chatId:e.chatId,messageId:e.id})}),[p]),{width:v,height:y}=l.containerStyle;return o.ZP.createElement("div",{className:"Album",style:`width: ${v}px; height: ${y}px;`},e.messages.map((function(e,p){const{photo:v,video:y}=(0,d.qp)(e),Z=m[e.previousLocalId||e.id],P=null==Z?void 0:Z.progress,{dimensions:C,sides:w}=l.layout[p],b=(0,i.bH)((0,n.Rd)(),e),S=(0,i.__)((0,n.Rd)(),e);if(v){const n=s&&(r?p===f-1:Boolean(8&w&&4&w));return o.ZP.createElement(sn,{id:`album-media-${e.id}`,message:e,observeIntersection:t,canAutoLoad:b,shouldAffectAppendix:n,uploadProgress:P,dimensions:C,isProtected:c,onClick:u,onCancelUpload:I,isDownloading:h.includes(e.id),theme:g})}if(y)return o.ZP.createElement(nn,{id:`album-media-${e.id}`,message:e,observeIntersection:t,canAutoLoad:b,canAutoPlay:S,uploadProgress:P,lastSyncTime:a,dimensions:C,isProtected:c,onClick:u,onCancelUpload:I,isDownloading:h.includes(e.id),theme:g})})))}));function on(){return(on=Object.assign||function(e){for(var t=1;t{const i=(0,o.sO)(null),c=(0,o.sO)(null),l=(0,o.sO)(null),m=e.content.video,h=(0,ss.Op)(i,t),[g,p]=(0,o.eJ)(s),f=Boolean(g&&h&&a),{mediaData:I,loadProgress:v}=(0,Ts.Z)((0,d.Ti)(e,"inline"),!f,(0,d.kG)(e,"inline"),a),{loadProgress:y}=(0,Ts.Z)((0,d.Ti)(e,"download"),!r,u.IU.BlobUrl,a),Z=Bs(e,I),{isBuffered:P,bufferingHandlers:w}=(0,Os.Z)(),b=g&&!P||r,S=!1===(0,dt.Z)(g),E=(0,Ss.Z)(I),{shouldRender:M,transitionClassNames:k}=(0,ce.Z)(b||!P,void 0,S),[R,T]=(0,o.eJ)(!1),[B,A]=(0,o.eJ)(0);(0,o.d4)((()=>{if(!R)return;const e=Zt.Rj/2,t=2*(e-6)*Math.PI,s=t-B*t,n=l.current,a=c.current,o=a.firstElementChild;o?o.firstElementChild.setAttribute("stroke-dashoffset",s.toString()):a.innerHTML=`\n \n \n `,A(n.currentTime/n.duration)}),[R,B]);const x=Boolean(I&&h),L=()=>{T(!1),A(0),(0,Us.Z)(l.current),(0,C.T2)((()=>{c.current.innerHTML=""}))},O=(F=L,()=>{rn&&rn(),rn=F});var F;(0,o.d4)((()=>{l.current&&(x?(0,Us.Z)(l.current):l.current.pause())}),[x]),$s(l,x),(0,Fs.Z)(l,[I]);const U=(0,o.I4)((()=>{if(!I)return void p((e=>!e));if(r)return void(0,n.uC)().cancelMessageMediaDownload({message:e});const t=l.current;R?t.paused?((0,Us.Z)(t),(0,Nt.Es)()):t.pause():(O(),t.pause(),t.currentTime=0,(0,Us.Z)(t),(0,Nt.Es)(),T(!0))}),[O,R,r,I,e]),$=(0,o.I4)((e=>{const t=e.currentTarget;A(t.currentTime/t.duration)}),[]),D=(0,ne.Z)("full-media",E);return o.ZP.createElement("div",{ref:i,className:"RoundVideo media-inner",onClick:U},o.ZP.createElement("div",{className:"thumbnail-wrapper"},o.ZP.createElement("canvas",{ref:Z,className:"thumbnail",style:`width: ${Zt.Rj}px; height: ${Zt.Rj}px`})),I&&o.ZP.createElement("div",{className:"video-wrapper"},o.ZP.createElement("video",on({ref:l,className:D,width:Zt.Rj,height:Zt.Rj,autoPlay:!0,muted:!R,loop:!R,playsInline:!0,onEnded:R?L:void 0},w,{onTimeUpdate:R?$:void 0}),o.ZP.createElement("source",{src:I}))),o.ZP.createElement("div",{className:"progress",ref:c}),M&&o.ZP.createElement("div",{className:`media-loading ${k}`},o.ZP.createElement(xs.Z,{progress:r?y:v})),!I&&!g&&o.ZP.createElement("i",{className:"icon-download"}),o.ZP.createElement("div",{className:"message-media-duration"},R?(0,N.k9)(l.current.currentTime):(0,N.k9)(m.duration),(!R||l.current.paused)&&o.ZP.createElement("i",{className:"icon-muted"})))},dn=({message:e,onClick:t})=>{const s=(0,Ce.Z)();return o.ZP.createElement("div",{className:"InlineButtons"},e.inlineButtons.map((e=>o.ZP.createElement("div",{className:"row"},e.map((e=>o.ZP.createElement(Ee.Z,{size:"tiny",ripple:!0,disabled:"NOT_SUPPORTED"===e.type,onClick:()=>t({button:e})},(0,Pt.Z)(s(e.text)),"buy"===e.type&&o.ZP.createElement("i",{className:"icon-card"}),"url"===e.type&&!e.value.match(a.FS)&&o.ZP.createElement("i",{className:"icon-arrow-right"}))))))))},ln=(0,o.X$)((({threadInfo:e,disabled:t})=>{const{openChat:s}=(0,n.uC)(),a=(0,Ce.Z)(),{threadId:r,chatId:i,messagesCount:c,lastMessageId:l,lastReadInboxMessageId:u,recentReplierIds:m}=e,h=(0,o.I4)((()=>{s({id:i,threadId:r})}),[s,i,r]),g=(0,o.Ye)((()=>{if(null==m||!m.length)return;const{users:{byId:e},chats:{byId:t}}=(0,n.Rd)();return m.map((s=>(0,d.YC)(s)?e[s]:t[s])).filter(Boolean)}),[m]);if(void 0===c)return;const p=Boolean(u&&l&&u0&&o.ZP.createElement("div",{className:"recent-repliers",dir:a.isRtl?"rtl":"ltr"},g.map((e=>o.ZP.createElement(Ht.Z,{key:e.id,size:"small",user:(0,d.YC)(e.id)?e:void 0,chat:(0,d.YC)(e.id)?void 0:e})))),o.ZP.createElement("div",{className:"label",dir:"auto"},c?a("Comments",c,"i"):a("LeaveAComment")),o.ZP.createElement("i",{className:"icon-next"}))})),un="data-is-document-group-hover",mn={__html:''},hn={__html:''};function gn(e){const t=fn(e.currentTarget);t&&t.setAttribute(un,"")}function pn(e){const t=fn(e.currentTarget);t&&t.removeAttribute(un)}function fn(e){let t=e;do{t=t.nextElementSibling}while(t&&!t.classList.contains("last-in-document-group"));return t}const In=(0,o.X$)((0,n.c$)(((e,t)=>{const{focusedMessage:s,forwardMessages:n,lastSyncTime:a}=e,{message:o,album:r,withSenderName:c,withAvatar:l,threadId:u,messageListType:m}=t,{id:h,chatId:g,viaBotId:p,replyToChatId:f,replyToMessageId:I,isOutgoing:v,threadInfo:y}=o,Z=(0,i.Z1)(e,g),P=(0,i.FM)(e,g),C=(0,d.pK)(g),w=Z&&(0,d.eA)(Z),b=null==Z?void 0:Z.username,S=!P&&(0,d.Ul)(o),E=c||l||S,M=(0,i.Ur)(e,o),k=(0,i.cv)(e,o),R=p?(0,i.dy)(e,p):void 0,T=u?(0,i.qS)(e,g,u):void 0,N=o.id===T,B=I===T,A=I&&!B?(0,i.hj)(e,C&&f?f:g,I):void 0,x=A&&(0,i.Ur)(e,A),L=(0,i.uZ)(e,o),O="thread"===m&&(r?r.messages.some((t=>(0,i._X)(e,t))):(0,i._X)(e,o)),{direction:F,noHighlight:U,isResizingContainer:$}=O&&s||{},D=n.messageIds&&n.messageIds.includes(h),{query:q}=(0,i.n5)(e)||{},Q=(0,d._O)(o);let G;G=null!=r&&r.messages?r.messages.every((({id:t})=>(0,i.vk)(e,t))):(0,i.vk)(e,h);const{canReply:j}="thread"===m&&(0,i._k)(e,o,u)||{},H=(0,i.te)(e,o),_=y?(0,i.tZ)(e,y.chatId,y.threadId)||y:void 0;return{theme:(0,i.Pu)(e),chatUsername:b,forceSenderName:S,sender:E?M:void 0,originSender:k,botSender:R,shouldHideReply:B,isThreadTop:N,replyMessage:A,replyMessageSender:x,isProtected:(0,i.EV)(e,o),isFocused:O,isForwarding:D,isChatWithSelf:P,isRepliesChat:C,isChannel:w,canReply:j,lastSyncTime:a,highlight:q,isSingleEmoji:Boolean(Q),animatedEmoji:Q?(0,i.zB)(e,Q):void 0,isInSelectMode:(0,i.CA)(e),isSelected:G,isGroupSelected:!!o.groupedId&&!o.isInAlbum&&(0,i.a6)(e,g,o.groupedId),threadId:u,isDownloading:H,isPinnedList:"pinned"===m,canAutoLoadMedia:(0,i.bH)(e,o),canAutoPlayMedia:(0,i.__)(e,o),autoLoadFileMaxSizeMb:e.settings.byKey.autoLoadFileMaxSizeMb,shouldLoopStickers:(0,i.yB)(e),threadInfo:_,...v&&{outgoingStatus:(0,i.dT)(e,o,"scheduled"===m)},..."number"==typeof L&&{uploadProgress:L},...O&&{focusDirection:F,noFocusHighlight:U,isResizingContainer:$}}}))((({message:e,chatUsername:t,observeIntersectionForBottom:s,observeIntersectionForMedia:a,observeIntersectionForAnimatedStickers:r,album:i,noAvatars:c,withAvatar:l,withSenderName:g,noComments:p,appearanceOrder:f,isFirstInGroup:I,isLastInGroup:v,isFirstInDocumentGroup:y,isLastInDocumentGroup:Z,isLastInList:P,theme:C,forceSenderName:w,sender:b,originSender:S,botSender:E,isThreadTop:M,shouldHideReply:k,replyMessage:R,replyMessageSender:T,outgoingStatus:N,uploadProgress:B,isProtected:A,isFocused:x,focusDirection:L,noFocusHighlight:O,isResizingContainer:F,isForwarding:U,isChatWithSelf:$,isRepliesChat:D,isChannel:q,canReply:Q,lastSyncTime:G,highlight:j,animatedEmoji:H,isInSelectMode:_,isSelected:z,isGroupSelected:V,threadId:K,messageListType:Y,isPinnedList:W,isDownloading:X,canAutoLoadMedia:J,canAutoPlayMedia:ee,shouldLoopStickers:te,autoLoadFileMaxSizeMb:se,threadInfo:ae})=>{const{toggleMessageSelection:oe,clickInlineButton:de,disableContextMenuHint:le}=(0,n.uC)(),ue=(0,o.sO)(null),me=(0,o.sO)(null),he=(0,Ce.Z)();(0,ss._N)(me,s);const{isContextMenuOpen:ge,contextMenuPosition:pe,handleBeforeContextMenu:fe,handleContextMenu:Ie,handleContextMenuClose:ve,handleContextMenuHide:Ze}=(0,os.Z)(ue,h.$b&&_,!0,h.wZ);(0,o.d4)((()=>{ge&&le()}),[ge,le]);const Pe=f<=0,[we,be]=(0,ye.Z)(Pe);(0,o.d4)((()=>{Pe||setTimeout(be,10*f)}),[f,be,Pe]);const{transitionClassNames:Se}=(0,ce.Z)(we,void 0,Pe,!1),{id:Me,chatId:ke}=e,Re=(0,d.CI)(e),Te=(0,d.B4)(e),Ne="scheduled"===Y||e.isScheduled,Be=(0,d.ss)(e)&&!k,Ae=Boolean(ae)&&"thread"===Y,Le=(0,d.$D)(e),{forwardInfo:Oe,viaBotId:Fe}=e,Ue=Oe&&(!$||Ne)&&!D&&!Oe.isLinkedChannelPost&&!Le,$e=Boolean(e.groupedId)&&!e.isInAlbum,De=Boolean(i)&&i.messages.length>1,{text:qe,photo:Qe,video:Ge,audio:je,voice:He,document:_e,sticker:ze,contact:Ve,poll:Ke,webPage:Ye,invoice:We}=(0,d.qp)(e),Xe=(0,rs.X)(e,j,is(Le)),Je=void 0!==pe,et=q&&e.adminTitle||!Ue&&(null==Oe?void 0:Oe.adminTitle)||void 0,tt=(0,o.Ye)((()=>et?ps(et):void 0),[et]),st=!(Je||_||U)&&(!$e||Z),nt=q&&!Ne,at=Boolean(W||Oe&&(Oe.isChannelPost||$&&!Te||D)&&Oe.fromMessageId),ot=Oe&&($||D||!b)?S:b,rt=Oe?S:b,it=(0,o.I4)(((e,t)=>{oe({messageId:Me,groupedId:t,...(null==e?void 0:e.shiftKey)&&{withShift:!0},...De&&{childMessageIds:i.messages.map((({id:e})=>e))}})}),[oe,Me,De,i]),{handleMouseDown:ct,handleClick:dt,handleContextMenu:lt,handleDoubleClick:ut,handleContentDoubleClick:mt,isSwiped:gt}=function(e,t,s,a,r,i,c,d,l){const{setReplyingToId:u}=(0,n.uC)(),[m,g,p]=(0,ye.Z)();return(0,o.d4)((()=>{if(!h.$b||r||!i)return;let e;return(0,xe.s)(t.current,{selectorToPreventScroll:".MessageList",onSwipe:(t,s)=>s===xe.e.Left&&(e||(e=Date.now()),g(),!0),onRelease:()=>{e&&(u({messageId:s}),setTimeout(p,Math.max(0,150-(Date.now()-e))),e=void 0)}})}),[t,r,s,u,g,p,i]),{handleMouseDown:r?void 0:function(e){(0,Xt.q)(e),l(e)},handleClick:function(t){if(r)e(t);else if(h.wZ){const e=t.target;if(!e.classList.contains("text-content")&&!e.classList.contains("Message"))return;ie.Z.getIsKeyboardVisible()?setTimeout((()=>{d(t)}),350):d(t)}},handleContextMenu:r?c?re.Z:void 0:function(t){if(h.wZ){if(t.target.matches("a[href]"))return;t.preventDefault(),e()}else d(t)},handleDoubleClick:r?void 0:function(){u({messageId:s})},handleContentDoubleClick:h.$b?void 0:function(e){e.stopPropagation()},isSwiped:m}}(it,ue,Me,0,Boolean(_),Boolean(Q),Boolean(A),Ie,fe),{handleAvatarClick:pt,handleSenderClick:ft,handleViaBotClick:It,handleReplyClick:vt,handleMediaClick:yt,handleAudioPlay:Ct,handleAlbumMediaClick:wt,handleMetaClick:bt,handleReadMedia:St,handleCancelUpload:Et,handleVoteSend:Mt,handleGroupForward:kt,handleForward:Rt,handleFocus:Tt,handleFocusForwarded:Nt,handleDocumentGroupSelectAll:Bt}=function(e,t,s,a,r,i,c,l,h,g,p,f,I){const{openUserInfo:v,openChat:y,showNotification:Z,focusMessage:P,openMediaViewer:C,openAudioPlayer:w,markMessagesRead:b,cancelSendingMessage:S,sendPollVote:E,openForwardMenu:M,focusMessageInComments:k}=(0,n.uC)(),{id:R,forwardInfo:T,replyToMessageId:N,replyToChatId:B,replyToTopMessageId:A,groupedId:x}=s,L=(0,o.I4)((()=>{p&&((0,d.YC)(p.id)?v({id:p.id}):y({id:p.id}))}),[p,v,y]),O=(0,o.I4)((()=>{f?c&&null!=T&&T.channelPostId?P({chatId:f.id,messageId:T.channelPostId}):(0,d.YC)(f.id)?v({id:f.id}):y({id:f.id}):Z({message:e("HidAccount")})}),[c,P,T,e,y,v,f,Z]),F=(0,o.I4)((()=>{I&&v({id:I.id})}),[I,v]),U=(0,o.I4)((()=>{P({chatId:h&&B?B:a,threadId:r,messageId:N,replyMessageId:h&&B?void 0:R})}),[P,h,B,a,r,N,R]),$=(0,o.I4)((()=>{C({chatId:a,threadId:r,messageId:R,origin:l?m.bZ.ScheduledInline:m.bZ.Inline})}),[a,r,R,C,l]),D=(0,o.I4)((()=>{w({chatId:a,messageId:R})}),[a,R,w]),q=(0,o.I4)((e=>{C({chatId:a,threadId:r,messageId:e,origin:l?m.bZ.ScheduledAlbum:m.bZ.Album})}),[a,r,C,l]),Q=(0,o.I4)((()=>{b({messageIds:[R]})}),[R,b]),G=(0,o.I4)((()=>{S({chatId:a,messageId:R})}),[S,a,R]),j=(0,o.I4)((e=>{E({chatId:a,messageId:R,options:e})}),[a,R,E]),H=(0,o.I4)((()=>{M({fromChatId:a,groupedId:x})}),[M,a,x]),_=(0,o.I4)((()=>{if(g&&g.messages){const e=g.messages.map((({id:e})=>e));M({fromChatId:a,messageIds:e})}else M({fromChatId:a,messageIds:[R]})}),[g,M,a,R]),z=(0,o.I4)((()=>{P({chatId:a,threadId:u._f,messageId:R})}),[P,a,R]),V=(0,o.I4)((()=>{i?P({chatId:T.fromChatId,groupedId:x,groupedChatId:a}):h&&B?k({chatId:B,threadId:A,messageId:T.fromMessageId}):P({chatId:T.fromChatId,messageId:T.fromMessageId})}),[i,h,B,P,T,x,a,k,A]),K=(0,o.I4)((e=>{e.stopPropagation(),t(e,x)}),[t,x]);return{handleAvatarClick:L,handleSenderClick:O,handleViaBotClick:F,handleReplyClick:U,handleMediaClick:$,handleAudioPlay:D,handleAlbumMediaClick:q,handleMetaClick:K,handleReadMedia:Q,handleCancelUpload:G,handleVoteSend:j,handleGroupForward:H,handleForward:_,handleFocus:z,handleFocusForwarded:V,handleDocumentGroupSelectAll:K}}(he,it,e,ke,K,$e,Ue,Ne,D,i,ot,rt,E),At=(0,ne.Z)("Message message-list-item",I&&"first-in-group",A&&"is-protected",v&&"last-in-group",y&&"first-in-document-group",Z&&"last-in-document-group",P&&"last-in-list",Te&&"own",Boolean(e.views)&&"has-views",e.isEdited&&"was-edited",Be&&"has-reply",Je&&"has-menu-open",x&&!O&&"focused",U&&"is-forwarding",e.isDeleting&&"is-deleting",$e&&"is-in-document-group",De&&"is-album",e.hasUnreadMention&&"has-unread-mention",z&&"is-selected",_&&"is-in-selection-mode",M&&"is-thread-top",Boolean(e.inlineButtons)&&"has-inline-buttons",gt&&"is-swiped",Se),xt=function(e,{hasReply:t,customShape:s,isLastInGroup:n,asForwarded:a,hasThread:o,forceSenderName:r,hasComments:i,hasActionButton:c}={}){const{text:l,photo:u,video:m,audio:h,voice:g,document:p,poll:f,webPage:I,contact:v}=(0,d.qp)(e),y=["message-content"],Z=u||m,P=Z&&!l,C=Boolean(e.viaBotId);return is(s)?y.push(`emoji-only emoji-only-${s}`):l&&y.push("text"),c&&y.push("has-action-button"),s&&(y.push("custom-shape"),null!=m&&m.isRound&&y.push("round"),i&&y.push("has-comments")),u||m?y.push("media"):h?y.push("audio"):g?y.push("voice"):p?y.push("document"):v?y.push("contact"):f?y.push("poll"):I&&(y.push("web-page"),(I.photo||I.video)&&y.push("media")),a&&y.push("is-forwarded"),t&&y.push("is-reply"),o&&y.push("has-replies"),C&&y.push("is-via-bot"),r&&y.push("force-sender-name"),s||(y.push("has-shadow"),Z&&i&&y.push("has-background"),(t||a||!P||C||r)&&y.push("has-solid-background"),!n||!u&&P||y.push("has-appendix")),y.join(" ")}(e,{hasReply:Be,customShape:Le,isLastInGroup:v,asForwarded:Ue,hasThread:Ae,forceSenderName:w,hasComments:ae&&(null==ae?void 0:ae.messagesCount)>0,hasActionButton:nt||at}),Lt=ae&&(!$e||Z)&&"thread"===Y&&!p,Ot=xt.includes("has-appendix");(0,ht.Z)(D&&e.replyToChatId?e.replyToChatId:ke,Be?e.replyToMessageId:void 0,R,e.id),fs(ue,ke,x,L,O,F);let Ft,Ut="",$t=!1;const Dt=(0,o.Ye)((()=>De?hs(Te,Boolean(Ue),Boolean(c),i):void 0),[De,Te,Ue,c,i]),qt=Ue?28:0;if(De||!Qe&&!Ge)Dt&&(Ft=Math.max(cs(Boolean(qe),Lt),Dt.containerStyle.width),Ft-Dt.containerStyle.width>18&&($t=!0));else{let t;Qe?t=ds(e,c).width:Ge&&(t=Ge.isRound?Zt.Rj:ds(e,c).width),t&&(Ft=Math.max(cs(Boolean(qe),Lt),t),Ft-t>18&&($t=!0))}return Ft&&(Ut=`width: ${Ft+qt}px`),o.ZP.createElement("div",{ref:ue,id:`message${Me}`,className:At,style:tt?`--meta-safe-author-width: ${tt}px`:void 0,"data-message-id":Me,onMouseDown:ct,onClick:dt,onContextMenu:lt,onDoubleClick:ut,onMouseEnter:$e&&!Z?gn:void 0,onMouseLeave:$e&&!Z?pn:void 0},o.ZP.createElement("div",{ref:me,className:"bottom-marker","data-message-id":Me,"data-last-message-id":i?i.messages[i.messages.length-1].id:void 0,"data-has-unread-mention":e.hasUnreadMention}),!$e&&o.ZP.createElement("div",{className:"message-select-control"},z&&o.ZP.createElement("i",{className:"icon-select"})),Z&&o.ZP.createElement("div",{className:(0,ne.Z)("message-select-control group-select",V&&"is-selected"),onClick:Bt},V&&o.ZP.createElement("i",{className:"icon-select"})),l&&function(){const e=ot&&(0,d.YC)(ot.id),t=ot&&e?ot:void 0,s=ot&&!e?ot:void 0,n=!ot&&Oe?Oe.hiddenUserName:void 0;return o.ZP.createElement(Ht.Z,{size:"small",user:t,chat:s,text:n,lastSyncTime:G,onClick:t||s?pt:void 0})}(),o.ZP.createElement("div",{className:(0,ne.Z)("message-content-wrapper",xt.includes("text")&&"can-select-text")},o.ZP.createElement("div",{className:xt,style:Ut,dir:"auto"},Ue&&(!$e||y)&&o.ZP.createElement("div",{className:"message-title"},he("ForwardedMessage")),function(){const t=(0,ne.Z)("content-inner",Ue&&"forwarded-message",Be&&"reply-message",$t&&"no-media-corners"),s=v&&!Xe&&!Ue&&!Ae,n=!Ye&&!H&&Xe,l=(0,ne.Z)("text-content",n&&"with-meta",N&&"with-outgoing-icon");return o.ZP.createElement("div",{className:t,onDoubleClick:mt,dir:"auto"},function(){if(Le&&!Fe||!(g&&!Qe&&!Ge||Ue||Fe||w)||$e&&!y||Be&&Le)return;let t,s;return!rt||Le&&Fe?null!=Oe&&Oe.hiddenUserName&&(t=Oe.hiddenUserName):(t=(0,d.OU)(he,rt),Ue||(s=`color-${(0,d.Rs)(rt)}`)),o.ZP.createElement("div",{className:"message-title",dir:"ltr"},t?o.ZP.createElement("span",{className:(0,ne.Z)("interactive",s),onClick:ft,dir:"auto"},(0,Pt.Z)(t)):E?void 0:" ",E&&o.ZP.createElement(o.ZP.Fragment,null,o.ZP.createElement("span",{className:"via"},he("ViaBot")),o.ZP.createElement("span",{className:"interactive",onClick:It},(0,Pt.Z)(`@${E.username}`))),null!=Oe&&Oe.isLinkedChannelPost?o.ZP.createElement("span",{className:"admin-title",dir:"auto"},he("DiscussChannel")):e.adminTitle&&!q?o.ZP.createElement("span",{className:"admin-title",dir:"auto"},e.adminTitle):void 0)}(),Be&&o.ZP.createElement(Zs,{message:R,isProtected:A,sender:T,observeIntersection:a,onClick:vt}),ze&&o.ZP.createElement(ks,{message:e,observeIntersection:a,observeIntersectionForPlaying:r,shouldLoop:te,lastSyncTime:G}),H&&o.ZP.createElement(Rs.Z,{size:"small",sticker:H,observeIntersection:a,lastSyncTime:G,forceLoadPreview:Re}),De&&o.ZP.createElement(an,{album:i,albumLayout:Dt,observeIntersection:a,isOwn:Te,isProtected:A,hasCustomAppendix:s,lastSyncTime:G,onMediaClick:wt}),!De&&Qe&&o.ZP.createElement(Ls,{message:e,observeIntersection:a,noAvatars:c,canAutoLoad:J,uploadProgress:B,shouldAffectAppendix:s,onClick:yt,onCancelUpload:Et,isDownloading:X,isProtected:A,theme:C}),!De&&Ge&&Ge.isRound&&o.ZP.createElement(cn,{message:e,observeIntersection:a,canAutoLoad:J,lastSyncTime:G,isDownloading:X}),!De&&Ge&&!Ge.isRound&&o.ZP.createElement(qs,{message:e,observeIntersection:a,noAvatars:c,canAutoLoad:J,canAutoPlay:ee,uploadProgress:B,lastSyncTime:G,onClick:yt,onCancelUpload:Et,isDownloading:X,isProtected:A}),(je||He)&&o.ZP.createElement(Cs.Z,{theme:C,message:e,origin:m.Cr.Inline,uploadProgress:B,lastSyncTime:G,isSelectable:$e,isSelected:z,onPlay:Ct,onReadMedia:!He||Te&&!$?void 0:St,onCancelUpload:Et,isDownloading:X}),_e&&o.ZP.createElement(Ps.Z,{message:e,observeIntersection:a,canAutoLoad:J,autoLoadFileMaxSizeMb:se,uploadProgress:B,isSelectable:$e,isSelected:z,onMediaClick:yt,onCancelUpload:Et,isDownloading:X}),Ve&&o.ZP.createElement(Gs,{contact:Ve}),Ke&&o.ZP.createElement(Ks,{message:e,poll:Ke,onSendVote:Mt}),!H&&Xe&&o.ZP.createElement("p",{className:l,dir:"auto"},Xe,n&&o.ZP.createElement(bs,{message:e,outgoingStatus:N,signature:et,onClick:bt})),Ye&&o.ZP.createElement(Xs,{message:e,observeIntersection:a,noAvatars:c,canAutoLoad:J,canAutoPlay:ee,lastSyncTime:G,onMediaClick:yt,onCancelMediaTransfer:Et,isDownloading:X,isProtected:A,theme:C}),We&&o.ZP.createElement(en,{message:e}))}(),(!$e||Z)&&!(!Ye&&!H&&Xe)&&o.ZP.createElement(bs,{message:e,outgoingStatus:N,signature:et,onClick:bt}),st&&nt?o.ZP.createElement(Ee.Z,{className:"message-action-button",color:"translucent-white",round:!0,size:"tiny",ariaLabel:he("lng_context_forward_msg"),onClick:Z?kt:Rt},o.ZP.createElement("i",{className:"icon-share-filled"})):st&&at?o.ZP.createElement(Ee.Z,{className:"message-action-button",color:"translucent-white",round:!0,size:"tiny",ariaLabel:"Focus message",onClick:W?Tt:Nt},o.ZP.createElement("i",{className:"icon-arrow-right"})):void 0,Lt&&o.ZP.createElement(ln,{threadInfo:ae,disabled:p}),Ot&&o.ZP.createElement("div",{className:"svg-appendix",dangerouslySetInnerHTML:Te?mn:hn})),e.inlineButtons&&o.ZP.createElement(dn,{message:e,onClick:de})),pe&&o.ZP.createElement(vs,{isOpen:ge,anchor:pe,message:e,album:i,chatUsername:t,messageListType:Y,onClose:ve,onCloseAnimationEnd:Ze}))}))),vn=(0,o.X$)((0,n.c$)(((e,{chatId:t})=>{const s=(0,i.fS)(e,t),{chatId:n,isBot:a}=s||{};return{message:s,bot:n&&a?(0,i.dy)(e,n):void 0,channel:!a&&n?(0,i.Z1)(e,n):void 0}}))((({chatId:e,message:t,containerRef:s,bot:a,channel:r})=>{const{viewSponsoredMessage:i,openChat:c,openChatByInvite:l,startBot:u,focusMessage:m}=(0,n.uC)(),h=(0,Ce.Z)(),g=(0,o.sO)(null),p=Boolean(t),{observe:f}=(0,ss.S1)({rootRef:s,debounceMs:200,threshold:1});if((0,o.d4)((()=>p?f(g.current,(t=>{t.isIntersecting&&i({chatId:e})})):void 0),[e,p,f,i]),t)return o.ZP.createElement("div",{className:"SponsoredMessage Message open",key:"sponsored-message"},o.ZP.createElement("div",{className:"message-content has-shadow has-solid-background",dir:"auto"},o.ZP.createElement("div",{className:"content-inner",dir:"auto"},o.ZP.createElement("div",{className:"message-title",dir:"ltr"},a&&(0,Pt.Z)((0,d.Js)(a)||""),r&&(0,Pt.Z)(t.chatInviteTitle||(0,d.U)(h,r,a)||"")),o.ZP.createElement("p",{className:"text-content with-meta",dir:"auto",ref:g},o.ZP.createElement("span",{className:"text-content-inner",dir:"auto"},(0,rs.H)(t.text.text,t.text.entities)),o.ZP.createElement("span",{className:"MessageMeta",dir:"ltr"},o.ZP.createElement("span",{className:"message-signature"},h("SponsoredMessage")))),o.ZP.createElement(Ee.Z,{color:"secondary",size:"tiny",ripple:!0,onClick:()=>{t.chatInviteHash?l({hash:t.chatInviteHash}):t.channelPostId?m({chatId:t.chatId,messageId:t.channelPostId}):(c({id:t.chatId}),t.startParam&&u({botId:t.chatId,param:t.startParam}))},className:"SponsoredMessage__button"},h(t.isBot?"Conversation.ViewBot":t.channelPostId?"Conversation.ViewPost":"Conversation.ViewChannel")))))}))),yn=(0,o.X$)((({chatId:e,messageIds:t,messageGroups:s,isViewportNewest:r,isUnread:i,withUsers:c,noAvatars:l,containerRef:u,anchorIdRef:p,memoUnreadDividerBeforeIdRef:f,memoFirstUnreadIdRef:I,threadId:v,type:y,isReady:Z,isScrollingRef:P,isScrollPatchNeededRef:w,threadTopMessageId:b,hasLinkedChat:S,isSchedule:E,noAppearanceAnimation:M,onFabToggle:k,onNotchToggle:R})=>{const{openHistoryCalendar:T}=(0,n.uC)(),{observeIntersectionForMedia:B,observeIntersectionForReading:A,observeIntersectionForAnimatedStickers:x}=function(e,t,s){const{markMessageListRead:a,markMessagesRead:o}=(0,n.uC)(),{observe:r}=(0,ss.S1)({rootRef:t,throttleMs:ns,margin:as}),{observe:i,freeze:c,unfreeze:d}=(0,ss.S1)({rootRef:t,throttleMs:150},(t=>{if("thread"!==e)return;let n=0;const r=[];t.forEach((e=>{const{isIntersecting:t,target:s}=e;if(!t)return;const{dataset:a}=s,o=Number(a.lastMessageId||a.messageId);o>n&&(n=o),a.hasUnreadMention&&r.push(o)})),s.current&&n>=s.current&&a({maxId:n}),r.length&&o({messageIds:r})}));(0,de.Z)(c,d);const{observe:l}=(0,ss.S1)({rootRef:t,throttleMs:ns});return{observeIntersectionForMedia:r,observeIntersectionForReading:i,observeIntersectionForAnimatedStickers:l}}(y,u,I),{backwardsTriggerRef:L,forwardsTriggerRef:O,fabTriggerRef:F}=function(e,t,s,r,i,c,d,l,u,g){const{loadViewportMessages:p}=(0,n.uC)(),[f,I]=(0,o.Ye)((()=>"thread"===e?[(0,C.Ds)((()=>p({direction:m.Uq.Backwards})),1e3,!0,!1),(0,C.Ds)((()=>p({direction:m.Uq.Forwards})),1e3,!0,!1)]:[]),[p,s]),v=(0,o.sO)(null),y=(0,o.sO)(null),Z=(0,o.sO)(null);function P(){if(!l)return;if(!s||!s.length)return c(!1),void d(!1);if(!r)return c(!0),void d(!0);const{offsetHeight:e,scrollHeight:n,scrollTop:a}=t.current,o=Math.round(n-a-e),u=o<=1;c(i?!u:!(o<=50)),d(!u)}const{observe:w}=(0,ss.S1)({rootRef:t,margin:h.gZ},(e=>{if(!I||!f)return;if(s[0]>=a.AE)return;const t=e.find((({isIntersecting:e})=>e));if(!t)return;const{target:n}=t;"backwards-trigger"===n.className?(h.i4&&u.current&&s.length<=a.hT&&(g.current=!0),f()):"forwards-trigger"===n.className&&I()}));(0,ss._N)(v,w),(0,ss._N)(y,w);const{observe:b,freeze:S,unfreeze:E}=(0,ss.S1)({rootRef:t,margin:100},P);(0,ss._N)(Z,b);const{observe:M,freeze:k,unfreeze:R}=(0,ss.S1)({rootRef:t,margin:1},P);return(0,ss._N)(Z,M),(0,ue.Z)((()=>{l&&P()}),[l]),(0,ue.Z)((()=>{S(),k(),setTimeout((()=>{R(),E()}),250)}),[s]),{backwardsTriggerRef:v,forwardsTriggerRef:y,fabTriggerRef:Z}}(y,u,t,r,i,k,R,Z,P,w),U=(0,Ce.Z)(),$=o.ZP.createElement("div",{className:(0,ne.Z)("unread-divider","local-action-message"),key:"unread-messages"},o.ZP.createElement("span",null,U("UnreadMessages"))),D=M?0:s.reduce(((e,t)=>e+(0,g.xH)(t.senderGroups).length),0);let q=0;const Q=s.map(((e,t,s)=>{const n=e.senderGroups.map(((e,n,a)=>{if(1===e.length&&!Yt(e[0])&&(0,d.Lo)(e[0])){const r=e[0],i=n===a.length-1&&t===s.length-1;return(0,g.oA)([r.id===f.current&&$,o.ZP.createElement(ys,{key:r.id,message:r,observeIntersection:A,appearanceOrder:D-++q,isLastInList:i})])}let r;return(0,g.xH)(e.map(((i,u)=>{const m=Yt(i)?i.mainMessage:i,h=Yt(i)?i:void 0,I=(0,d.B4)(m),Z=Yt(i),P=e[u+1];m.previousLocalId&&p.current===`message${m.previousLocalId}`&&(p.current=`message${m.id}`);const C=!Z&&m.groupedId?m.groupedId:void 0,w=P&&!Yt(P)?P.groupedId:void 0,E={isFirstInGroup:0===u,isLastInGroup:u===e.length-1,isFirstInDocumentGroup:Boolean(C&&C!==r),isLastInDocumentGroup:Boolean(C&&C!==w),isLastInList:u===e.length-1&&n===a.length-1&&t===s.length-1};r=C;const M=(0,d.KK)(m),k="scheduled"!==y?M:`${m.date}_${M}`;return(0,g.oA)([m.id===f.current&&$,o.ZP.createElement(In,{key:k,message:m,observeIntersectionForBottom:A,observeIntersectionForMedia:B,observeIntersectionForAnimatedStickers:x,album:h,noAvatars:l,withAvatar:E.isLastInGroup&&c&&!I&&!(m.id===b),withSenderName:E.isFirstInGroup&&c&&!I,threadId:v,messageListType:y,noComments:!1===S,appearanceOrder:D-++q,isFirstInGroup:E.isFirstInGroup,isLastInGroup:E.isLastInGroup,isFirstInDocumentGroup:E.isFirstInDocumentGroup,isLastInDocumentGroup:E.isLastInDocumentGroup,isLastInList:E.isLastInList}),m.id===b&&o.ZP.createElement("div",{className:"local-action-message",key:"discussion-started"},o.ZP.createElement("span",null,U("DiscussionStarted")))])})))}));return o.ZP.createElement("div",{className:"message-date-group",key:e.datetime,onMouseDown:Xt.q,teactFastList:!0},o.ZP.createElement("div",{className:(0,ne.Z)("sticky-date",!E&&"interactive"),key:"date-header",onMouseDown:Xt.q,onClick:E?void 0:()=>T({selectedAt:e.datetime})},o.ZP.createElement("span",{dir:"auto"},E&&e.originalDate===a.t4&&U("MessageScheduledUntilOnline"),E&&e.originalDate!==a.t4&&U("MessageScheduledOn",(0,N.j1)(U,e.datetime,void 0,!0)),!E&&(0,N.j1)(U,e.datetime))),(0,g.xH)(n))}));return o.ZP.createElement("div",{className:"messages-container",teactFastList:!0},o.ZP.createElement("div",{ref:L,key:"backwards-trigger",className:"backwards-trigger"}),(0,g.xH)(Q),r&&o.ZP.createElement(vn,{key:e,chatId:e,containerRef:u}),o.ZP.createElement("div",{ref:O,key:"forwards-trigger",className:"forwards-trigger"}),o.ZP.createElement("div",{ref:F,key:"fab-trigger",className:"fab-trigger"}))}));var Zn=s(3547);const Pn=(0,o.X$)((0,n.c$)(((e,{userId:t})=>{const{stickers:s}=e.stickers.greeting,n=(0,d.db)(t)+(0,d.db)(e.currentUserId),a=null!=s&&s.length?s[n%s.length]:void 0,o=(0,i.Z1)(e,t);return o?{sticker:a,lastUnreadMessageId:o.lastMessage&&o.lastMessage.id!==o.lastReadInboxMessageId?o.lastMessage.id:void 0,connectionState:e.connectionState}:{}}))((({sticker:e,connectionState:t,lastUnreadMessageId:s})=>{const{loadGreetingStickers:a,sendMessage:r,markMessageListRead:i}=(0,n.uC)(),c=(0,Ce.Z)(),d=(0,o.sO)(null),{observe:l}=(0,ss.S1)({rootRef:d,debounceMs:200});(0,o.d4)((()=>{e||"connectionStateReady"!==t||a()}),[t,a,e]),(0,o.d4)((()=>{"connectionStateReady"===t&&s&&i({maxId:s})}),[t,i,s]);const u=(0,o.I4)((e=>{e={...e,isPreloadedGlobally:!0},r({sticker:e})}),[r]);return o.ZP.createElement("div",{className:"ContactGreeting",ref:d},o.ZP.createElement("div",{className:"wrapper"},o.ZP.createElement("p",{className:"title",dir:"auto"},c("Conversation.EmptyPlaceholder")),o.ZP.createElement("p",{className:"description",dir:"auto"},c("Conversation.GreetingText")),o.ZP.createElement("div",{className:"sticker"},e&&o.ZP.createElement(Zn.Z,{sticker:e,onClick:u,clickArg:e,observeIntersection:l,size:160,className:"large"}))))}))),Cn=(0,o.X$)((({isChatWithSelf:e,type:t,isGroupChatJustCreated:s})=>{const n=(0,Ce.Z)();return"scheduled"===t?function(e){return o.ZP.createElement("div",{className:"empty"},o.ZP.createElement("span",null,e("ScheduledMessages.EmptyPlaceholder")))}(n):e?function(e){return o.ZP.createElement("div",{className:"NoMessages"},o.ZP.createElement("div",{className:"wrapper"},o.ZP.createElement("i",{className:"icon icon-cloud-download"}),o.ZP.createElement("h3",{className:"title"},e("Conversation.CloudStorageInfo.Title")),o.ZP.createElement("ul",{className:"description"},o.ZP.createElement("li",null,e("Conversation.ClousStorageInfo.Description1")),o.ZP.createElement("li",null,e("Conversation.ClousStorageInfo.Description2")),o.ZP.createElement("li",null,e("Conversation.ClousStorageInfo.Description3")),o.ZP.createElement("li",null,e("Conversation.ClousStorageInfo.Description4")))))}(n):s?function(e){return o.ZP.createElement("div",{className:"NoMessages"},o.ZP.createElement("div",{className:"wrapper",dir:e.isRtl?"rtl":void 0},o.ZP.createElement("h3",{className:"title"},e("EmptyGroupInfo.Title")),o.ZP.createElement("p",{className:"description"},e("EmptyGroupInfo.Subtitle")),o.ZP.createElement("ul",{className:"list-checkmarks"},o.ZP.createElement("li",null,e("EmptyGroupInfo.Line1")),o.ZP.createElement("li",null,e("EmptyGroupInfo.Line2")),o.ZP.createElement("li",null,e("EmptyGroupInfo.Line3")),o.ZP.createElement("li",null,e("EmptyGroupInfo.Line4")))))}(n):o.ZP.createElement("div",{className:"empty"},o.ZP.createElement("span",null,n("NoMessages")))})),wn=(0,C.Ds)((e=>e()),200,!1),bn=(0,o.X$)((0,n.c$)(((e,{chatId:t,threadId:s,type:n})=>{const a=(0,i.Z1)(e,t);if(!a)return{};const o=(0,i.$W)(e,t,s,n),r="scheduled"===n?(0,i.Fn)(e,t):(0,i.Zw)(e,t),c=(0,i.qS)(e,t,s);if(s!==u._f&&!(r&&c&&r[c]))return{};const{isRestricted:l,restrictionReason:m,lastMessage:h}=a,g=(0,i.G$)(e,t),p=s===u._f&&!o&&!a.unreadCount&&!g&&h&&!h.groupedId,f=(0,i.IK)(e,t);let I;return(0,i.pk)(e,t)&&(I=f.fullInfo?f.fullInfo.botDescription||"NoMessages":"Updating bot info..."),{isChatLoaded:!0,isRestricted:l,restrictionReason:m,isChannelChat:(0,d.eA)(a),isGroupChat:(0,d.Bf)(a),isCreator:a.isCreator,isChatWithSelf:(0,i.FM)(e,t),isRepliesChat:(0,d.pK)(t),isBot:Boolean(f),messageIds:o,messagesById:r,firstUnreadId:(0,i.It)(e,t,s),isViewportNewest:"thread"!==n||(0,i.b9)(e,t,s),threadFirstMessageId:(0,i.yZ)(e,t,s),focusingId:g,isSelectModeActive:(0,i.CA)(e),botDescription:I,threadTopMessageId:c,hasLinkedChat:a.fullInfo&&"linkedChatId"in a.fullInfo?Boolean(a.fullInfo.linkedChatId):void 0,lastSyncTime:e.lastSyncTime,...p&&{lastMessage:h}}}))((({chatId:e,threadId:t,type:s,hasTools:r,onFabToggle:c,onNotchToggle:l,isChatLoaded:u,isChannelChat:h,isGroupChat:p,canPost:f,isReady:I,isChatWithSelf:v,isRepliesChat:y,isCreator:Z,isBot:P,messageIds:w,messagesById:b,firstUnreadId:S,isViewportNewest:E,threadFirstMessageId:M,isRestricted:k,restrictionReason:R,focusingId:T,isSelectModeActive:N,lastMessage:B,botDescription:A,threadTopMessageId:x,hasLinkedChat:L,lastSyncTime:O,withBottomShift:F})=>{var U,$,D,q,Q,G;const{loadViewportMessages:j,setScrollOffset:H,loadSponsoredMessages:_}=(0,n.uC)(),z=(0,o.sO)(null),V=(0,o.sO)("thread"===s&&(0,i.Vt)((0,n.Rd)(),e,t)||0),K=(0,o.sO)(),Y=(0,o.sO)(),W=(0,o.sO)(),X=(0,o.sO)(),J=(0,o.sO)(),ee=(0,o.sO)(),te=(0,o.sO)(!1),ae=(0,o.sO)(Boolean(B)),[oe,re]=(0,o.eJ)(),ie=Boolean(w);(0,ue.Z)((()=>{ie&&(0,C.R3)((()=>{ae.current=!1}))}),[ie]),(0,ue.Z)((()=>{X.current=S}),[S]),(0,ue.Z)((()=>{h&&I&&O&&_({chatId:e})}),[e,I,h,O]),(0,ue.Z)((()=>{ie&&(J.current=X.current)}),[ie]),(0,ue.Z)((()=>{ee.current=T}),[T]);const ce=(0,o.Ye)((()=>{if(!w||!b)return;const e=!x||w[0]&&M!==w[0]?w:[x,...w];if(!e.length)return;const t=e.map((e=>b[e])).filter(Boolean);return Wt((0,g.Xo)(t,["date","id"]),J.current)}),[w,b,M,x]),de=(0,o.Ye)((()=>{if("thread"===s)return(0,C.Ds)((()=>j({direction:m.Uq.Around})),1e3,!0,!1)}),[j,w]),{isScrolled:le,updateStickyDates:me}=function(){const[e,t]=(0,ye.Z)(!1),s=(0,Jt.Z)(1e3,!1);return{isScrolled:e,updateStickyDates:(0,o.I4)(((e,n)=>{t(),document.body.classList.contains("is-scrolling-messages")||(0,C.T2)((()=>{document.body.classList.add("is-scrolling-messages")})),s((()=>{(0,C.T2)((()=>{const t=document.querySelector(".stuck");t&&t.classList.remove("stuck");const s=function(e,t){const s=e.querySelectorAll(".sticky-date"),n=e.scrollTop;return Array.from(s).find((e=>{const{offsetTop:s,offsetHeight:a}=e,o=s-n;return-a<=o&&o<=(t?60:10)}))}(e,n);s&&s.classList.add("stuck"),document.body.classList.remove("is-scrolling-messages")}))}))}),[t,s])}}(),he=(0,o.sO)(),ge=(0,o.sO)(),pe=(0,o.I4)((()=>{if(te.current)return void(te.current=!1);he.current=!0;const n=z.current;ee.current||me(n,r),wn((()=>{he.current=!1,(0,C.T2)((()=>{n.parentElement&&(V.current=n.scrollHeight-n.scrollTop,"thread"===s&&H({chatId:e,threadId:t,scrollOffset:V.current}))}))}))}),[me,r,s,H,e,t]);(0,o.d4)((()=>{if(!("ResizeObserver"in window))return;const e=new ResizeObserver((([e])=>{e.target.offsetParent&&re(e.contentRect.height)}));return e.observe(z.current),()=>{e.disconnect()}}),[]);const{height:fe}=it();(0,o.d4)((()=>{I&&(z.current.dataset.normalHeight=String(z.current.offsetHeight))}),[fe,I,f]),(0,o.d4)((()=>{if(!de||!u||k||T)return;if(w&&w[w.length-1]>=a.AE)return;const e=z.current;(!w||w.length{if(!w||!W.current)return;const e=W.current.filter((e=>w.includes(Number(e.dataset.messageId)))),t=e[1]||e[0];t&&(K.current=t.id,Y.current=t.getBoundingClientRect().top)}),[w,E,oe,r]),(0,Vt.Z)((([e,t,s])=>{const n=z.current;W.current=Array.from(n.querySelectorAll(".message-list-item"));const o=w&&e&&w[w.length-1]!==e[e.length-1],i=(null==w?void 0:w[0])!==(null==e?void 0:e[0])&&(null==w?void 0:w.length)===a.hT/2+1,c=o&&!i,d=w&&ee.current===w[w.length-1],l=E&&c&&w&&w.length{n.parentElement&&n.parentElement.classList.remove("force-messages-scroll")}),500));const{scrollTop:u,scrollHeight:m,offsetHeight:h}=n,g=V.current,p=W.current[W.current.length-1];let f=g-(s||h);c&&(f-=p?p.offsetHeight:0);const I=E&&t&&f<=20;let v;if(c&&I&&!d&&(p&&(0,C.T2)((()=>{(0,ts.Z)(n,p,"end",20)})),v=m-h,V.current=Math.max(Math.ceil(m-v),h),!l))return;const y=void 0!==s&&s!==oe,Z=K.current&&n.querySelector(`#${K.current}`),P=!Z&&J.current&&n.querySelector(".unread-divider");if(I&&y){if((0,ts.N)())return;v=m-h}else Z?(ge.current&&(ge.current=!1,(0,es.z)(n)),v=u+(Z.getBoundingClientRect().top-(Y.current||0))):v=P?Math.min(P.offsetTop-(r?60:10),m-g):m-g;(0,es.Z)(n,Math.ceil(v)),ee.current||(te.current=!0,(0,C.T2)((()=>{te.current=!1}))),V.current=Math.max(Math.ceil(m-v),h)}),[w,E,oe,r]),(0,Kt.Z)((([e])=>{void 0!==e&&(0,se.YW)(200+a.fK)}),[N]);const Ie=(0,Ce.Z)(),ve=Boolean(e&&(0,d.YC)(e)),Ze=Boolean(!ve&&!h||v||y),Pe=Boolean(!Ze||h),we=(0,d.YC)(e)&&!v&&!P&&(!ce&&!B&&w&&(!W.current||0===W.current.length)||1===(null==w?void 0:w.length)&&"contactSignUp"===(null==b||null===(U=b[w[0]])||void 0===U||null===($=U.content.action)||void 0===$?void 0:$.type)||"contactSignUp"===(null==B||null===(D=B.content)||void 0===D||null===(q=D.action)||void 0===q?void 0:q.type)),be=p&&Z&&1===(null==w?void 0:w.length)&&"chatCreate"===(null==b||null===(Q=b[w[0]])||void 0===Q||null===(G=Q.content.action)||void 0===G?void 0:G.type),Se=(0,ne.Z)("MessageList custom-scroll",Pe&&"no-avatars",!f&&"no-composer","pinned"===s&&"type-pinned",F&&"with-bottom-shift",N&&"select-mode-active",le&&"scrolled",!I&&"is-animating");return o.ZP.createElement("div",{ref:z,className:Se,onScroll:pe,onMouseDown:Xt.q},k?o.ZP.createElement("div",{className:"empty"},o.ZP.createElement("span",null,R?R.text:"This is a private "+(h?"channel":"chat"))):A?o.ZP.createElement("div",{className:"empty"},o.ZP.createElement("span",null,(0,Pt.Z)(Ie(A),["br","emoji","links"]))):we?o.ZP.createElement(Pn,{userId:e}):!w||ce&&!be?w&&ce||B?o.ZP.createElement(yn,{chatId:e,messageIds:w||[B.id],messageGroups:ce||Wt([B]),isViewportNewest:Boolean(E),isUnread:Boolean(S),withUsers:Ze,noAvatars:Pe,containerRef:z,anchorIdRef:K,memoUnreadDividerBeforeIdRef:J,memoFirstUnreadIdRef:X,threadId:t,type:s,isReady:I,isScrollingRef:he,isScrollPatchNeededRef:ge,threadTopMessageId:x,hasLinkedChat:L,isSchedule:!!ce&&"scheduled"===s,noAppearanceAnimation:!ce||!ae.current,onFabToggle:c,onNotchToggle:l}):o.ZP.createElement(qe.Z,{color:"white"}):o.ZP.createElement(Cn,{chatId:e,type:s,isChatWithSelf:v,isGroupChatJustCreated:be}))}))),Sn=(0,o.X$)((0,n.c$)((e=>{const t=(0,i.Bt)(e);if(!t)return{};const{chatId:s,threadId:n,type:a}=t,o=(0,i.Z1)(e,s);return{messageListType:a,unreadCount:o&&n===u._f&&"thread"===a?o.unreadCount:void 0}}))((({isShown:e,canPost:t,messageListType:s,unreadCount:a,withExtraShift:r})=>{const{focusNextReply:i}=(0,n.uC)(),c=(0,Ce.Z)(),d=(0,o.sO)(null),l=(0,o.I4)((()=>{if(e)if("thread"===s)i();else{const e=d.current.parentElement.querySelector(".MessageList"),t=e.querySelectorAll(".message-list-item"),s=t[t.length-1];if(!s)return;(0,ts.Z)(e,s,"end",20)}}),[e,s,i]),u=(0,ne.Z)("ScrollDownButton",e&&"revealed",!t&&"no-composer",r&&"with-extra-shift");return o.ZP.createElement("div",{ref:d,className:u},o.ZP.createElement("div",{className:"ScrollDownButton-inner"},o.ZP.createElement(Ee.Z,{color:"secondary",round:!0,onClick:l,ariaLabel:c("AccDescrPageDown")},o.ZP.createElement("i",{className:"icon-arrow-down"})),Boolean(a)&&o.ZP.createElement("div",{className:"unread-count"},(0,pt.bi)(a))))})));var En=s(5723);const Mn=1280,kn=/\.[^/.]+$/;async function Rn(e,t,s,n){const o=URL.createObjectURL(t),{type:r,size:i}=t;let c,d;if(a.oG.has(r))if(s){const t=await(0,rt.pt)(o),{width:s,height:a}=t;if(s>Mn||a>Mn||"image/jpeg"!==r){const t=await Lt(o,Mn/Math.max(s,a),"image/jpeg");return URL.revokeObjectURL(o),Rn(e,await(0,rt.gm)(t),!0,n)}"image/jpeg"===r&&(e=e.replace(kn,".jpg")),c={width:s,height:a}}else d=o;else if(a.wG.has(r)){const{videoWidth:e,videoHeight:t,duration:s}=await(0,rt.jj)(o);c={width:e,height:t,duration:s},d=await(0,rt.ud)(o)}return{blobUrl:o,filename:e,mimeType:r,size:i,quick:c,previewBlobUrl:d,...n}}var Tn=s(6391);let Nn;function Bn(e){Nn.focus(),e.focus()}h.cj&&(Nn=document.createElement("input"),Nn.classList.add("for-ios-autocapitalization-fix"),document.body.appendChild(Nn));var An=s(4784),xn=s(2400),Ln=s(6389);const On={encoderPath:s.p+"c0155344d336103c2b6a0b28cc510750.js",reuseWorker:!0},Fn={type:"audio/ogg"};let Un,$n,Dn;async function qn(){return Un||(Un=s.e(161).then(s.t.bind(s,1161,23)),$n=(await Un).default,Dn=new $n(On)),Un}async function Qn(e){await async function(){await qn(),await Dn.start()}();const t=Date.now();let s;const n=[],a=[];Dn.ondataavailable=e=>{n.push(e)};const o=function(t,s){const n=t.sourceNode,o=n.context.createAnalyser();o.fftSize=64,n.connect(o);const r=o.frequencyBinCount,i=new Uint8Array(r);let c=!1;return function t(){if(c)return;o.getByteFrequencyData(i);const s=i.reduce(((e,t)=>e+t),0)/r/255;(t=>{a.push(255*t),e(t)})(s<.1?0:s),requestAnimationFrame(t)}(),()=>{c=!0}}(Dn);return{stop:()=>new Promise(((e,r)=>{Dn.onstop=()=>{e({blob:new Blob(n,Fn),duration:Math.round(((s||Date.now())-t)/1e3),waveform:a})},Dn.onerror=r;const i=Math.max(0,t+1e3-Date.now());setTimeout((()=>{Dn.stop(),o()}),i)})),pause:()=>{const e=Math.max(0,t+1e3-Date.now());setTimeout((()=>{Dn.pause(),s=Date.now(),o()}),e)}}}const Gn=["image/png","image/jpeg","image/gif"];function jn(e){const{text:t,entities:s}=e||{};if(!t)return"";const n=(0,rs.H)(t,s,void 0,void 0,!0);return Array.isArray(n)?n.join(""):n}let Hn,_n;var zn=s(3575),Vn=s(9295);const Kn=document.createElement("div"),Yn=/^@([a-z0-9_]{1,32})[\u00A0\u0020]+(.*)/i,Wn=/^@([a-z0-9_]{1,32})[\u00A0\u0020]+\n{2,}/i;const Xn=(0,C.P2)((e=>e()),500,!0),Jn=/^[\w@]{1,32}\s?/i,ea=(0,o.X$)((e=>{const{isOpen:t}=e,s=(0,De.Z)($e.gl.Extra,"DeleteMessageModal",!t);return s?o.ZP.createElement(s,e):void 0}));function ta(){return(ta=Object.assign||function(e){for(var t=1;t{const s=(0,o.sO)(!1),n=(0,o.I4)((()=>{if(s.current=!0,na)return na=!1,void e();sa&&(clearTimeout(sa),sa=void 0),sa=window.setTimeout((()=>{s.current&&e()}),200)}),[e]),a=(0,o.I4)((()=>{s.current=!1}),[]);return o.ZP.createElement(Ee.Z,ta({},t,{onMouseEnter:h.$b?void 0:n,onMouseLeave:h.$b?void 0:a,onClick:h.$b?e:void 0}))})),oa=(0,o.X$)((e=>{const{isOpen:t}=e,s=(0,De.Z)($e.gl.Extra,"AttachMenu",!t);return s?o.ZP.createElement(s,e):void 0})),ra=(0,o.X$)((e=>{const{isOpen:t}=e,s=(0,De.Z)($e.gl.Extra,"SymbolMenu",!t);return s?o.ZP.createElement(s,e):void 0})),ia=(0,o.X$)((e=>{const{isOpen:t}=e,s=(0,De.Z)($e.gl.Extra,"InlineBotTooltip",!t);return s?o.ZP.createElement(s,e):void 0})),ca=(0,o.X$)((e=>{const{isOpen:t}=e,s=(0,De.Z)($e.gl.Extra,"MentionTooltip",!t);return s?o.ZP.createElement(s,e):void 0})),da=(0,o.X$)((e=>{const{isOpen:t}=e,s=(0,De.Z)($e.gl.Extra,"CustomSendMenu",!t);return s?o.ZP.createElement(s,e):void 0})),la=e=>{const{isOpen:t}=e,s=(0,De.Z)($e.gl.Extra,"StickerTooltip",!t);return s?o.ZP.createElement(s,e):void 0};var ua=s(9830);const ma=(0,o.X$)((e=>{const{isOpen:t}=e,s=(0,De.Z)($e.gl.Extra,"BotCommandTooltip",!t);return s?o.ZP.createElement(s,e):void 0}));var ha=s(6503);const ga=(0,o.X$)((0,n.c$)(((e,{messageId:t})=>{const{chatId:s}=(0,i.Bt)(e)||{};return s?{message:(0,i.hj)(e,s,t)}:{}}))((({isOpen:e,message:t,onClose:s})=>{const{clickInlineButton:a}=(0,n.uC)(),[r,i]=(0,ha.Z)(e,s),{isKeyboardSingleUse:c}=t||{},[d,l,u]=(0,ye.Z)(!0),m=()=>{u(),s()};if((0,o.d4)((()=>{l()}),[l,t]),t&&t.keyboardButtons)return o.ZP.createElement(je.Z,{isOpen:e||d,autoClose:c,positionX:"right",positionY:"bottom",onClose:m,className:"BotKeyboardMenu",onCloseAnimationEnd:m,onMouseEnter:h.$b?void 0:r,onMouseLeave:h.$b?void 0:i},o.ZP.createElement("div",{className:"content"},t.keyboardButtons.map((e=>o.ZP.createElement("div",{className:"row"},e.map((e=>o.ZP.createElement(Ee.Z,{ripple:!0,disabled:"NOT_SUPPORTED"===e.type,onClick:()=>a({button:e})},e.text))))))))})));var pa=s(3616),fa=s(7891);const Ia=(0,o.X$)((0,n.c$)((e=>{const{chatId:t,threadId:s,type:n}=(0,i.Bt)(e)||{};if(!t||!s||!n)return{};const{currentUserId:a,forwardMessages:{fromChatId:o,toChatId:r,messageIds:c}}=e,l=(0,i.Yy)(e,t,s),u="scheduled"===n?(0,i.wU)(e,t):(0,i._$)(e,t,s),m=e.settings.byKey.animationLevel>=1,h=r===t;let g,p;if(l?g=(0,i.hj)(e,t,l):u?g=(0,i.kK)(e,t,s,n):h&&1===c.length&&(g=(0,i.hj)(e,o,c[0])),l&&g){const{forwardInfo:s}=g,n=t===a;s&&(s.isChannelPost||n)&&(p=(0,i.cv)(e,g)),p||(p=(0,i.Ur)(e,g))}else h&&(p=(0,d.YC)(o)?(0,i.dy)(e,o):(0,i.Z1)(e,o));return{replyingToId:l,editingId:u,message:g,sender:p,shouldAnimate:m,forwardedMessagesCount:h?c.length:void 0}}))((({replyingToId:e,editingId:t,message:s,sender:a,shouldAnimate:r,forwardedMessagesCount:i})=>{const{setReplyingToId:c,setEditingId:d,focusMessage:l,exitForwardMode:u}=(0,n.uC)(),m=Boolean((e||t)&&s||a&&i),h=(0,fa.Z)([i],i?300:void 0),{shouldRender:g,transitionClassNames:p}=(0,ce.Z)(h&&m,void 0,!r,void 0,!r),f=(0,o.I4)((()=>{e?c({messageId:void 0}):t?d({messageId:void 0}):i&&u()}),[e,t,i,c,d,u]);(0,o.d4)((()=>m?(0,fe.Z)(f):void 0),[m,f]);const I=(0,o.I4)((()=>{l({chatId:s.chatId,messageId:s.id})}),[l,s]),v=(0,ne.Z)("ComposerEmbeddedMessage",p),y=i&&i>1?`${i} forwarded messages`:void 0;if(g)return o.ZP.createElement("div",{className:v},o.ZP.createElement("div",null,o.ZP.createElement(Ee.Z,{round:!0,faded:!0,color:"translucent",ariaLabel:"Cancel replying",onClick:f},o.ZP.createElement("i",{className:"icon-close"})),o.ZP.createElement(Zs,{className:"inside-input",message:s,sender:a,customText:y,title:t?"Edit Message":void 0,onClick:I})))}))),va=(0,o.X$)((e=>{const{attachments:t}=e,s=(0,De.Z)($e.gl.Extra,"AttachmentModal",!t.length);return s?o.ZP.createElement(s,e):void 0})),ya=(0,o.X$)((e=>{const{isOpen:t}=e,s=(0,De.Z)($e.gl.Extra,"BotCommandMenu",!t);return s?o.ZP.createElement(s,e):void 0})),Za=(0,o.X$)((e=>{const{isOpen:t}=e,s=(0,De.Z)($e.gl.Extra,"PollModal",!t);return s?o.ZP.createElement(s,e):void 0})),Pa=(0,o.X$)((e=>{const{isOpen:t}=e,s=(0,De.Z)($e.gl.Extra,"DropArea",!t);return s?o.ZP.createElement(s,e):void 0})),Ca=new RegExp(a.FM,"i"),wa=(0,o.X$)((0,n.c$)(((e,{chatId:t,threadId:s})=>{const n=(0,i.tV)(e,t,s);return{theme:(0,i.Pu)(e),webPagePreview:e.webPagePreview,noWebPage:n}}))((({chatId:e,threadId:t,messageText:s,disabled:a,webPagePreview:r,noWebPage:i,theme:c})=>{const{loadWebPagePreview:d,clearWebPagePreview:l,toggleMessageWebPage:m}=(0,n.uC)(),h=(0,o.Ye)((()=>{const{text:e,entities:t}=(0,f.Z)(s),n=t&&t.find((({type:e})=>e===u.Vv.TextUrl));if(n)return n.url;const a=e.match(Ca);return a?a[0]:void 0}),[s]);(0,o.d4)((()=>{h?d({text:h}):(l(),m({chatId:e,threadId:t}))}),[e,m,l,h,d,t]),(0,ue.Z)((()=>{l(),m({chatId:e,threadId:t})}),[e]);const g=Boolean(r&&s.length&&!i&&!a),{shouldRender:p,transitionClassNames:I}=(0,ce.Z)(g),v=(0,gt.Z)(r,!0);if(!p||!v)return;const{photo:y,...Z}=v,P={content:{webPage:Z}};return o.ZP.createElement("div",{className:(0,ne.Z)("WebPagePreview",I)},o.ZP.createElement("div",null,o.ZP.createElement(Ee.Z,{round:!0,faded:!0,color:"translucent",ariaLabel:"Clear Webpage Preview",onClick:()=>{m({chatId:e,threadId:t,noWebPage:!0})}},o.ZP.createElement("i",{className:"icon-close"})),o.ZP.createElement(Xs,{message:P,inPreview:!0,theme:c})))})));var ba=s(2898);const Sa=(0,o.X$)((e=>{const{isOpen:t}=e,s=(0,De.Z)($e.gl.Extra,"CalendarModal",!t);return s?o.ZP.createElement(s,e):void 0})),Ea=(0,o.X$)((e=>{const{isOpen:t}=e,s=(0,De.Z)($e.gl.Extra,"SendAsMenu",!t);return s?o.ZP.createElement(s,e):void 0}));var Ma;!function(e){e.Send="send",e.Record="record",e.Edit="edit"}(Ma||(Ma={}));const ka=(0,o.X$)((0,n.c$)(((e,{chatId:t,threadId:s,messageListType:n})=>{var o,r,c,l;const m=(0,i.Z1)(e,t),h=m&&(0,i.Dg)(e,m),g=t!==a.FV?(0,i.IK)(e,t):void 0,p=Boolean(g),f=(0,i.FM)(e,t),I=p&&(0,i.FT)(e,t),v=(0,i.qy)(e,t),{language:y,shouldSuggestStickers:Z}=e.settings.byKey,P=e.emojiKeywords[a.pR],C=y!==a.pR?e.emojiKeywords[y]:void 0,w=I?I.id:void 0,b=w?(0,i.hj)(e,t,w):void 0,S=e.users.byId,E=e.chats.byId,{currentUserId:M}=e,k=null!=m&&m.fullInfo?(null==m||null===(o=m.fullInfo)||void 0===o?void 0:o.sendAsId)||M:void 0,R=k?null==S?void 0:S[k]:void 0,T=!R&&k?null==E?void 0:E[k]:void 0;return{editingMessage:(0,i.kK)(e,t,s,n),connectionState:e.connectionState,draft:(0,i.Ms)(e,t,s),chat:m,isChatWithBot:p,isChatWithSelf:f,canScheduleUntilOnline:Boolean(!f&&!p&&m&&h&&(0,d.YC)(t)&&(null===(r=(0,i.ss)(e,t))||void 0===r?void 0:r.wasOnline)),isRightColumnShown:(0,i.Jf)(e),isSelectModeActive:(0,i.CA)(e),withScheduledButton:s===u._f&&"thread"===n&&Boolean(null==v?void 0:v.length),shouldSchedule:"scheduled"===n,botKeyboardMessageId:w,botKeyboardPlaceholder:null==b?void 0:b.keyboardPlaceholder,isForwarding:t===e.forwardMessages.toChatId,isPollModalOpen:e.isPollModalOpen,stickersForEmoji:e.stickers.forEmoji.stickers,groupChatMembers:null==m||null===(c=m.fullInfo)||void 0===c?void 0:c.members,topInlineBotIds:null===(l=e.topInlineBots)||void 0===l?void 0:l.userIds,currentUserId:M,usersById:S,lastSyncTime:e.lastSyncTime,contentToBeScheduled:e.messages.contentToBeScheduled,shouldSuggestStickers:Z,recentEmojis:e.recentEmojis,baseEmojiKeywords:null==P?void 0:P.keywords,emojiKeywords:null==C?void 0:C.keywords,serverTimeOffset:e.serverTimeOffset,inlineBots:e.inlineBots.byUsername,isInlineBotLoading:e.inlineBots.isLoading,chatBotCommands:m&&m.fullInfo&&m.fullInfo.botCommands,botCommands:g&&g.fullInfo?g.fullInfo.botCommands||!1:void 0,sendAsUser:R,sendAsChat:T,sendAsId:k}}))((({dropAreaState:e,shouldSchedule:t,canScheduleUntilOnline:s,isReady:r,onDropHide:i,editingMessage:c,chatId:l,threadId:m,messageListType:g,draft:I,chat:v,connectionState:y,isChatWithBot:Z,isChatWithSelf:P,isRightColumnShown:w,isSelectModeActive:b,isForwarding:S,isPollModalOpen:E,botKeyboardMessageId:M,botKeyboardPlaceholder:k,withScheduledButton:R,stickersForEmoji:T,groupChatMembers:B,topInlineBotIds:A,currentUserId:x,usersById:L,lastSyncTime:O,contentToBeScheduled:F,shouldSuggestStickers:U,baseEmojiKeywords:$,emojiKeywords:D,serverTimeOffset:q,recentEmojis:Q,inlineBots:G,isInlineBotLoading:j,botCommands:H,chatBotCommands:_,sendAsUser:z,sendAsChat:V,sendAsId:K})=>{const{sendMessage:Y,clearDraft:W,showDialog:X,setStickerSearchQuery:J,setGifSearchQuery:ee,forwardMessages:te,openPollModal:se,closePollModal:ae,loadScheduledHistory:oe,openChat:re,addRecentEmoji:ce,sendInlineBotResult:me,loadSendAs:he}=(0,n.uC)(),ge=(0,Ce.Z)(),pe=(0,o.sO)(null),[Ie,ve]=(0,o.eJ)(""),Ze=(0,o.sO)(),Pe=(0,dt.Z)(e),[we,be,Se]=(0,ye.Z)(),[Me,ke]=(0,o.eJ)(),{width:Re}=ie.Z.get(),Te=null==v?void 0:v.sendAsIds,Ne=(0,Ln.Z)(l,m),Ae=(0,o.sO)(Ie);(0,o.d4)((()=>{Ae.current=Ie}),[Ie]),(0,o.d4)((()=>{Ze.current=void 0}),[l]),(0,o.d4)((()=>{l&&O&&m===u._f&&r&&oe({chatId:l})}),[r,l,oe,O,m]),(0,o.d4)((()=>{l&&v&&O&&!Te&&r&&(0,d.ZV)(v)&&he({chatId:l})}),[v,l,r,O,he,Te]);const xe=(0,o.sO)(!1);(0,ue.Z)((([e,t])=>{xe.current=Boolean(l===e&&Te&&!t)}),[l,Te]),(0,o.bt)((()=>{pe.current&&(pe.current.innerHTML='')}),[]),(0,o.d4)((()=>{F&&(ke(F),be())}),[F,be]);const[Le,Oe]=(0,o.eJ)([]),[Fe,Ue,$e]=(0,ye.Z)(),[De,qe,Qe]=(0,ye.Z)(),[Ge,je,He]=(0,ye.Z)(),[_e,ze,Ve]=(0,ye.Z)(),[Ke,Ye,We]=(0,ye.Z)(),[Xe,Je,et]=(0,ye.Z)(),[tt,st]=(0,ye.Z)(),[at,ot,rt]=(0,ye.Z)(),{startRecordingVoice:it,stopRecordingVoice:ct,pauseRecordingVoice:lt,activeVoiceRecording:ut,currentRecordTime:mt,recordButtonRef:ht,startRecordTimeRef:gt}=(()=>{const e=(0,o.sO)(null),[t,s]=(0,o.eJ)(),n=(0,o.sO)(),[a,r]=(0,o.eJ)();(0,o.d4)((()=>{h.s$&&h.mh&&qn()}),[]);const i=(0,o.I4)((async()=>{try{const{stop:t,pause:a}=await Qn((t=>{e.current&&(n.current&&Date.now()%4==0&&(e.current.style.boxShadow=`0 0 0 ${50*(t||0)}px rgba(0,0,0,.15)`),r(Date.now()))}));n.current=Date.now(),r(Date.now()),s({stop:t,pause:a})}catch(e){console.error(e)}}),[]),c=(0,o.I4)((()=>{if(t){e.current&&(e.current.style.boxShadow="none");try{return t.pause()}catch(e){return void console.error(e)}}}),[t]),d=(0,o.I4)((()=>{if(t){s(void 0),n.current=void 0,r(void 0),e.current&&(e.current.style.boxShadow="none");try{return t.stop()}catch(e){return void console.error(e)}}}),[t]);return(0,o.d4)((()=>t?(0,fe.Z)(d):void 0),[t,d]),{startRecordingVoice:i,pauseRecordingVoice:c,stopRecordingVoice:d,activeVoiceRecording:t,currentRecordTime:a,recordButtonRef:e,startRecordTimeRef:n}})();(function(e,t,s=!1){const n=(0,o.sO)(e);(0,o.bt)((()=>{n.current=e}),[e]),(0,o.d4)((()=>{if(void 0===t)return;const e=setInterval((()=>n.current()),t);return s||n.current(),()=>clearInterval(e)}),[t,s])})((()=>{Ne({type:"recordAudio"})}),ut&&a.o_),(0,o.d4)((()=>{ut||Ne({type:"cancel"})}),[ut,Ne]);const pt=c?Ma.Edit:!h.mh||ut||Ie&&!Le.length||S?Ma.Send:Ma.Record,ft=!t,{isMentionTooltipOpen:It,closeMentionTooltip:vt,insertMention:yt,mentionFilteredUsers:Zt}=(0,Vn.Z)(!Le.length,Ie,ve,void 0,B,A,x),{isOpen:Ct,id:wt,isGallery:bt,switchPm:St,results:Et,closeTooltip:Mt,help:kt,loadMore:Rt}=function(e,t,s,a){const[r,i,c]=(0,ye.Z)(),d=function(e){return Kn.innerHTML=e.replace(/
/g,"\n"),Kn.innerText}(s),{queryInlineBot:l,resetInlineBot:u}=(0,n.uC)(),{username:m,query:h,canShowHelp:g}=function(e){const t=e.match(Yn);return t?{username:t[1],query:t[2],canShowHelp:""===t[2]&&!e.match(Wn)}:{username:"",query:"",canShowHelp:!1}}(d),p=m.toLowerCase(),f=(0,dt.Z)(h),I=(0,dt.Z)(m),v=null==a?void 0:a[p],{id:y,switchPm:Z,offset:P,results:C,isGallery:w,help:b}=v||{};(0,o.d4)((()=>{f!==h&&c()}),[f,h,c]),(0,o.d4)((()=>{e&&p&&t&&l({chatId:t,username:p,query:h})}),[h,e,l,t,p]);const S=(0,o.I4)((()=>{l({chatId:t,username:p,query:h,offset:P})}),[P,t,h,l,p]);return(0,o.d4)((()=>{e&&y&&(Z||null!=C&&C.length)?i():c()}),[y,e,i,C,Z,c]),I!==m&&u({username:I}),{isOpen:r,closeTooltip:c,loadMore:S,username:m,id:y,isGallery:w,switchPm:Z,results:C,help:g&&b?`@${m} ${b}`:void 0}}(Boolean(!Le.length&&O),l,Ie,G),{isOpen:Tt,close:Nt,filteredBotCommands:Bt}=function(e,t,s,n){const[a,r,i]=(0,ye.Z)(),[c,d]=(0,o.eJ)(),l=(0,o.I4)((e=>{s||n?Xn((()=>{const t=(s||n||[]).filter((({command:t})=>!e||t.includes(e)));d(t&&t.length?t:void 0)})):d(void 0)}),[s,n]);return(0,o.d4)((()=>{if(e&&t.length)if(t.startsWith("/")){const e=(0,xn._)(t.substr(1)).match(Jn);l(e?e[0]:"")}else i();else i()}),[l,t,e,i]),(0,o.d4)((()=>{c&&c.length?r():i()}),[c,r,i]),{isOpen:a,close:i,filteredBotCommands:c}}(Boolean(H&&H.length||_&&_.length),Ie,H,_),{isContextMenuOpen:At,handleContextMenu:xt,handleContextMenuClose:Lt,handleContextMenuHide:Ot}=(0,os.Z)(ht,!(pt===Ma.Send&&ft)),Ft=(0,o.Ye)((()=>(0,d.H5)(v,Z)),[v,Z]),Ut=v&&(0,d.Nl)(v),$t=(0,d.Hd)(v),{isStickerTooltipOpen:Dt,closeStickerTooltip:qt}=function(e,t,s,a=!1){const r=(0,o.Ye)((()=>(0,xn._)(t).trim()),[t]),{loadStickersForEmoji:i,clearStickersForEmoji:c}=(0,n.uC)(),d=h.op&&1===(0,An.Z)(r)||!h.op&&Boolean(t.match(/^]*?>$/g)),l=Boolean(s)&&d;return(0,o.d4)((()=>{var t;a||(e&&d?i({emoji:h.op?r:null===(t=r.match(/alt="(.+)"/))||void 0===t?void 0:t[1]}):!l&&d||c())}),[t,d,c,i,e,a]),{isStickerTooltipOpen:l,closeStickerTooltip:c}}(Boolean(U&&Ft.canSendStickers&&!Le.length),Ie,T,!r),{isEmojiTooltipOpen:Qt,closeEmojiTooltip:Gt,filteredEmojis:jt,insertEmoji:_t}=(0,zn.Z)(Boolean(U&&Ft.canSendStickers&&!Le.length),Ie,Q,void 0,ve,$,D,!r),zt=(0,o.I4)(((e,t=a.R2)=>{const s=window.getSelection(),n=document.getElementById(t),o=(0,Pt.Z)(e,["escape_html","emoji_html","br_html"]).join("").replace(/\u200b+/g,"​");if(s.rangeCount){const e=s.getRangeAt(0);if((0,Tn.R)(e,t))return function(e){const t=window.getSelection();if(null!=t&&t.getRangeAt&&t.rangeCount){const s=t.getRangeAt(0);s.deleteContents();const n=s.createContextualFragment(e),a=n.lastChild;s.insertNode(n),a?(s.setStartAfter(a),s.setEndAfter(a)):s.collapse(!1),t.removeAllRanges(),t.addRange(s)}}(o),void n.dispatchEvent(new Event("input",{bubbles:!0}))}ve(`${Ae.current}${o}`),requestAnimationFrame((()=>{(0,En.Z)(n)}))}),[]),Vt=(0,o.I4)((()=>{const e=window.getSelection();if(e.rangeCount){const t=e.getRangeAt(0);if((0,Tn.R)(t,a.R2))return void document.execCommand("delete",!1)}ve(function(e){const t=document.createElement("div");t.contentEditable="true",t.style.position="absolute",t.style.left="-10000px",t.style.top="-10000px",t.innerHTML=e,document.body.appendChild(t);let s=t.lastChild;if(s.lastChild)for(;s.lastChild;)s=s.lastChild;const n=s.textContent.length,a=document.createRange(),o=window.getSelection();a.setStart(s,n),a.setEnd(s,n),o.removeAllRanges(),o.addRange(a),document.execCommand("delete",!1);const r=t.innerHTML;return document.body.removeChild(t),r}(Ae.current))}),[]),Kt=(0,o.I4)(((e=!1)=>{e||ve(""),Oe([]),qt(),Se(),ke(void 0),vt(),Gt(),h.wB?setTimeout((()=>Ve()),350):Ve()}),[qt,Se,vt,Gt,Ve]),Yt=(0,o.sO)();Yt.current=ct,(0,o.d4)((()=>()=>{Yt.current(),Kt()}),[l,Kt,Yt]);const Wt=((e,t,s,r,i)=>{const{editMessage:c}=(0,n.uC)();return(0,o.d4)((()=>{s?(t(jn(s.content.text)),requestAnimationFrame((()=>{const e=document.getElementById(a.R2);(0,En.Z)(e,!0)}))):t("")}),[s,t]),(0,o.I4)((()=>{const{text:t,entities:n}=(0,f.Z)(e.current);s&&(t||(0,d.u8)(s)?(c({messageId:s.id,text:t,entities:n}),r()):i())}),[c,s,e,i,r])})(Ae,ve,c,Kt,Je);((e,t,s,r,i,c,d)=>{const{saveDraft:l,clearDraft:u}=(0,n.uC)(),m=(0,o.I4)(((e,t)=>{i.current.length&&!d?l({chatId:e,threadId:t,draft:(0,f.Z)(i.current)}):u({chatId:e,threadId:t})}),[u,d,i,l]),g=(0,o.Ye)((()=>(0,C.Ds)((e=>e()),a.r_,!1)),[t]),p=(0,dt.Z)(t),I=(0,dt.Z)(s);(0,o.d4)((()=>(Hn=t,_n=s,()=>{Hn=void 0,_n=void 0,m(t,s)})),[t,s,m]),(0,o.d4)((()=>{t===p&&s===I||e&&(c(jn(e)),h.$b||requestAnimationFrame((()=>{const e=document.getElementById(a.R2);(0,En.Z)(e,!0)})))}),[t,s,e,c,m,p,I]);const v=(0,dt.Z)(r);(0,o.d4)((()=>{t&&s&&p===t&&I===s&&v!==r&&(r.length?g((()=>{Hn===t&&_n===s&&m(t,s)})):m(t,s))}),[t,r,p,v,I,g,s,m]);const y=(0,o.I4)((()=>{t&&s&&m(t,s)}),[t,s,m]);(0,de.Z)(y),le(y)})(I,l,m,Ie,Ae,ve,c),((e,t,s)=>{(0,o.d4)((()=>{async function n(n){if(!n.clipboardData)return;const o=document.activeElement;if(o&&![a.R2,a.nY].includes(o.id))return;const{items:r}=n.clipboardData,i=Array.from(r).find((e=>Gn.includes(e.type)&&"file"===e.kind)),c=i&&i.getAsFile(),d=n.clipboardData.getData("text").substring(0,4096);if(n.preventDefault(),c||d){if(c&&!s){const e=await Rn(c.name,c,!0);t((t=>[...t,e]))}d&&e(d,null==o?void 0:o.id)}}return document.addEventListener("paste",n,!1),()=>{document.removeEventListener("paste",n,!1)}}),[e,s,t])})(zt,Oe,c);const Xt=(0,o.I4)((async(e,t)=>{Oe(await Promise.all(e.map((e=>Rn(e.name,e,t)))))}),[]),Jt=(0,o.I4)((async(e,t)=>{Oe([...Le,...await Promise.all(e.map((e=>Rn(e.name,e,t))))])}),[Le]),es=(0,o.I4)((()=>{Oe([])}),[]),ts=(0,o.I4)((async(e=!1,t)=>{if("connectionStateReady"!==y)return;let s=Le;if(ut){const e=await ct();if(e){const{blob:t,duration:n,waveform:a}=e;s=[await Rn("wonderful-voice-message.ogg",t,!1,{voice:{duration:n,waveform:a}})]}}const{text:n,entities:o}=(0,f.Z)(Ae.current);if(!s.length&&!n&&!S)return;const r=s.length?1024:4096;if((null==n?void 0:n.length)>r){const e=n.length-r;return void X({data:{message:"MESSAGE_TOO_LONG_PLEASE_REMOVE_CHARACTERS",textParams:{"{EXTRA_CHARS_COUNT}":e,"{PLURAL_S}":e>1?"s":""},hasErrorKey:!0}})}const i=document.getElementById(a.R2);if(s.length||n){if($t&&!Ut){const e=(0,p.b)(q),t=Ze.current&&Math.floor(e-Ze.current),s=$t.nextSendDate&&$t.nextSendDate>e;if(t&&t<$t.seconds||s){const n=s?$t.nextSendDate-e:$t.seconds-t;return X({data:{message:ge("SlowModeHint",(0,N.k9)(n)),isSlowMode:!0,hasErrorKey:!1}}),void i.blur()}}Y({text:n,entities:o,attachments:s,scheduledAt:t,isSilent:e})}S&&te({scheduledAt:t,isSilent:e}),Ze.current=(0,p.b)(q),W({chatId:l,localOnly:!0}),h.cj&&i===document.activeElement&&Bn(i),requestAnimationFrame((()=>{Kt()}))}),[y,Le,ut,S,W,l,q,Kt,ct,X,$t,Ut,Y,te,ge]),ss=(0,o.I4)((()=>{Ve(),qe()}),[Ve,qe]),ns=(0,o.I4)((()=>{Qe(),We(),ze()}),[Qe,We,ze]),as=(0,o.I4)(((e,s=!1)=>{e={...e,isPreloadedGlobally:!0},t?(ke({sticker:e}),be()):(Y({sticker:e}),requestAnimationFrame((()=>{Kt(s)})))}),[t,be,Y,Kt]),rs=(0,o.I4)((e=>{t?(ke({gif:e}),be()):(Y({gif:e}),requestAnimationFrame((()=>{Kt(!0)})))}),[t,be,Y,Kt]),is=(0,o.I4)((e=>{if("connectionStateReady"!==y)return;me({id:e.id,queryId:e.queryId});const t=document.getElementById(a.R2);h.cj&&t===document.activeElement&&Bn(t),W({chatId:l,localOnly:!0}),requestAnimationFrame((()=>{Kt()}))}),[l,W,y,Kt,me]),cs=(0,o.I4)((()=>{W({chatId:l,localOnly:!0}),requestAnimationFrame((()=>{Kt()}))}),[l,W,Kt]),ds=(0,o.I4)((e=>{t?(ke({poll:e}),ae(),be()):(Y({poll:e}),ae())}),[ae,be,Y,t]),ls=(0,o.I4)((()=>{t?(ke({isSilent:!0}),be()):ts(!0)}),[ts,be,t]),us=(0,o.I4)(((e,t=!1)=>{const{isSilent:s,...n}=Me||{},a=Math.round(Math.max(e.getTime(),Date.now()+6e4)/1e3)+(t?0:q);Me&&0!==Object.keys(n).length?(Y({...Me,scheduledAt:a}),requestAnimationFrame((()=>{Kt()}))):ts(!!s,a),Se()}),[Se,ts,Kt,Me,Y,q]),ms=(0,o.I4)((()=>{us(new Date(1e3*a.t4),!0)}),[us]),hs=(0,o.I4)((()=>{Se(),ke(void 0)}),[Se]),gs=(0,o.I4)((e=>{"stickers"===e?(J({query:""}),ee({query:void 0})):(ee({query:""}),J({query:void 0}))}),[J,ee]),ps=(0,o.I4)((()=>{const e=document.getElementById(a.R2);h.wB&&e===document.activeElement?(e.blur(),setTimeout((()=>{Qe(),ze()}),100)):ze()}),[ze,Qe]),fs=(0,o.I4)((()=>{const e=document.getElementById(a.R2);if(!h.wB||e!==document.activeElement)return Qe(),Ve(),void Ye();e.blur(),setTimeout((()=>{Qe(),Ve(),Ye()}),100)}),[Qe,Ve,Ye]),Is=(0,o.I4)((()=>{re({id:l,threadId:m,type:"scheduled"})}),[re,l,m]);(0,o.d4)((()=>{w&&h.wB&&Ve()}),[w,Ve]),(0,o.d4)((()=>{r&&(b?ot():setTimeout((()=>{rt()}),200))}),[b,rt,ot,r]);const vs=(0,o.I4)((()=>{switch(pt){case Ma.Send:t?(ut&<(),be()):ts();break;case Ma.Record:it();break;case Ma.Edit:Wt()}}),[pt,t,it,Wt,ut,be,lt,ts]),ys=pt===Ma.Record&&!Ft.canAttachMedia,Zs=(0,dt.Z)(c,!0),Ps=c||Zs,Cs=new Date;Cs.setSeconds(0),Cs.setMilliseconds(0);const ws=new Date;ws.setFullYear(ws.getFullYear()+1);let bs="SendMessage";switch(pt){case Ma.Edit:bs="Save edited message";break;case Ma.Record:bs=ys?"Conversation.DefaultRestrictedMedia":"AccDescrVoiceMessage"}const Ss=(0,ne.Z)("Composer",!b&&"shown",at&&"hover-disabled"),Es=(0,ne.Z)("mobile-symbol-menu-button",!r&&"not-ready",tt?_e&&"menu-opened":_e&&"is-loading"),Ms=pt===Ma.Edit?Wt:t?be:ts;return o.ZP.createElement("div",{className:Ss},Ft.canAttachMedia&&r&&o.ZP.createElement(ba.Z,{containerId:"#middle-column-portals"},o.ZP.createElement(Pa,{isOpen:e!==nt.t.None,withQuick:[e,Pe].includes(nt.t.QuickFile),onHide:i,onFileSelect:Xt})),o.ZP.createElement(va,{chatId:l,threadId:m,attachments:Le,caption:Le.length?Ie:"",groupChatMembers:B,currentUserId:x,usersById:L,recentEmojis:Q,isReady:r,onCaptionUpdate:ve,baseEmojiKeywords:$,emojiKeywords:D,addRecentEmoji:ce,onSend:t?be:ts,onFileAppend:Jt,onClear:es}),o.ZP.createElement(Za,{isOpen:Boolean(E),onClear:ae,onSend:ds}),Ps&&o.ZP.createElement(ea,{isOpen:Xe,isSchedule:"scheduled"===g,onClose:et,message:Ps}),o.ZP.createElement(Ea,{isOpen:Ke,onClose:We,chatId:l,selectedSendAsId:K,sendAsIds:Te}),o.ZP.createElement(ca,{isOpen:It,onClose:vt,onInsertUserName:yt,filteredUsers:Zt,usersById:L}),o.ZP.createElement(ia,{isOpen:Ct,botId:wt,allowedAttachmentOptions:Ft,isGallery:bt,inlineBotResults:Et,switchPm:St,onSelectResult:is,loadMore:Rt,onClose:Mt}),o.ZP.createElement(ma,{isOpen:Tt,withUsername:Boolean(_),botCommands:Bt,onClick:cs,onClose:Nt}),o.ZP.createElement("div",{id:"message-compose"},o.ZP.createElement("div",{className:"svg-appendix",ref:pe}),o.ZP.createElement(Ia,null),o.ZP.createElement(wa,{chatId:l,threadId:m,messageText:Le.length?"":Ie,disabled:!Ft.canAttachEmbedLinks}),o.ZP.createElement("div",{className:"message-input-wrapper"},Z&&!1!==H&&!ut&&!c&&o.ZP.createElement(aa,{className:(0,ne.Z)("bot-commands",De&&"activated"),round:!0,disabled:void 0===H,color:"translucent",onActivate:ss,ariaLabel:"Open bot command keyboard"},o.ZP.createElement("i",{className:"icon-bot-commands-filled"})),!(null==Te||!Te.length)&&(z||V)&&o.ZP.createElement(Ee.Z,{round:!0,color:"translucent",onClick:Ke?We:fs,ariaLabel:ge("SendMessageAsTitle"),className:(0,ne.Z)("send-as-button",xe.current&&"appear-animation")},o.ZP.createElement(Ht.Z,{user:z,chat:V,size:"tiny"})),h.wB?o.ZP.createElement(Ee.Z,{className:Es,round:!0,color:"translucent",onClick:_e?Ve:ps,ariaLabel:"Choose emoji, sticker or GIF"},o.ZP.createElement("i",{className:"icon-smile"}),o.ZP.createElement("i",{className:"icon-keyboard"}),_e&&!tt&&o.ZP.createElement(Be.Z,{color:"gray"})):o.ZP.createElement(aa,{className:_e?"activated":"",round:!0,color:"translucent",onActivate:ns,ariaLabel:"Choose emoji, sticker or GIF"},o.ZP.createElement("i",{className:"icon-smile"})),o.ZP.createElement(pa.Z,{id:"message-input-text",chatId:l,threadId:m,html:Le.length?"":Ie,placeholder:ut&&Re<=600?"":k||ge("Message"),forcedPlaceholder:kt,canAutoFocus:r&&!Le.length,shouldSuppressFocus:h.wB&&_e,shouldSuppressTextFormatter:Qt||It||Ct,onUpdate:ve,onSend:Ms,onSuppressedFocus:Ve}),j&&Boolean(wt)&&o.ZP.createElement(Be.Z,{color:"gray"}),R&&o.ZP.createElement(Ee.Z,{round:!0,faded:!0,className:"scheduled-button",color:"translucent",onClick:Is,ariaLabel:"Open scheduled messages"},o.ZP.createElement("i",{className:"icon-schedule"})),M&&!ut&&!c&&o.ZP.createElement(aa,{className:Fe?"activated":"",round:!0,color:"translucent",onActivate:Ue,ariaLabel:"Open bot command keyboard"},o.ZP.createElement("i",{className:"icon-bot-command"})),!ut&&!c&&o.ZP.createElement(aa,{className:Ge?"activated":"",round:!0,color:"translucent",onActivate:je,ariaLabel:"Add an attachment"},o.ZP.createElement("i",{className:"icon-attach"})),ut&&mt&&o.ZP.createElement("span",{className:"recording-state"},(0,N.rM)(mt-gt.current)),o.ZP.createElement(la,{chatId:l,threadId:m,isOpen:Dt,onStickerSelect:as}),o.ZP.createElement(ua.Z,{isOpen:Qt,emojis:jt,onClose:Gt,onEmojiSelect:_t,addRecentEmoji:ce}),o.ZP.createElement(oa,{isOpen:Ge,allowedAttachmentOptions:Ft,onFileSelect:Xt,onPollCreate:se,onClose:He}),M&&o.ZP.createElement(ga,{messageId:M,isOpen:Fe,onClose:$e}),H&&o.ZP.createElement(ya,{isOpen:De,botCommands:H,onClose:Qe}),o.ZP.createElement(ra,{chatId:l,threadId:m,isOpen:_e,allowedAttachmentOptions:Ft,onLoad:st,onClose:Ve,onEmojiSelect:zt,onStickerSelect:as,onGifSelect:rs,onRemoveSymbol:Vt,onSearchOpen:gs,addRecentEmoji:ce}))),ut&&o.ZP.createElement(Ee.Z,{round:!0,color:"danger",className:"cancel",onClick:ct,ariaLabel:"Cancel voice recording"},o.ZP.createElement("i",{className:"icon-delete"})),o.ZP.createElement(Ee.Z,{ref:ht,round:!0,color:"secondary",className:(0,ne.Z)(pt,!r&&"not-ready",ut&&"recording"),disabled:ys,ariaLabel:ge(bs),onClick:vs,onContextMenu:pt===Ma.Send&&ft?xt:void 0},o.ZP.createElement("i",{className:"icon-send"}),o.ZP.createElement("i",{className:"icon-microphone-alt"}),o.ZP.createElement("i",{className:"icon-check"})),ft&&o.ZP.createElement(da,{isOpen:At,onSilentSend:P?void 0:ls,onScheduleSend:t?void 0:be,onClose:Lt,onCloseAnimationEnd:Ot}),o.ZP.createElement(Sa,{isOpen:we,withTimePicker:!0,selectedAt:Cs.getTime(),maxAt:(0,N._F)(ws),isFutureMode:!0,secondButtonLabel:s?ge("Schedule.SendWhenOnline"):void 0,onClose:hs,onSubmit:us,onSecondButtonClick:s?ms:void 0}))}))),Ra=(0,o.X$)((e=>{const{isActive:t}=e,s=(0,De.Z)($e.gl.Extra,"MobileSearch",!t,!0);return s?o.ZP.createElement(s,e):void 0})),Ta=(0,o.X$)((e=>{const{isActive:t}=e,s=(0,De.Z)($e.gl.Extra,"MessageSelectToolbar",!t);return s?o.ZP.createElement(s,e):void 0})),Na=(0,o.X$)((e=>{const{isOpen:t}=e,s=(0,De.Z)($e.gl.Extra,"UnpinAllMessagesModal",!t);return s?o.ZP.createElement(s,e):void 0})),Ba=(0,o.X$)((e=>{const{isOpen:t}=e,s=(0,De.Z)($e.gl.Extra,"PaymentModal",!t);return s?o.ZP.createElement(s,e):void 0})),Aa=(0,o.X$)((e=>{const{isOpen:t}=e,s=(0,De.Z)($e.gl.Extra,"ReceiptModal",!t);return s?o.ZP.createElement(s,e):void 0})),xa=(0,o.X$)((e=>{const{isOpen:t}=e,s=(0,De.Z)($e.gl.Extra,"SeenByModal",!t);return s?o.ZP.createElement(s,e):void 0})),La=h.wB?450+a.fK:void 0;function Oa(e){return"file"===e.kind&&e.type&&a.oG.has(e.type)}const Fa=(0,o.X$)((0,n.c$)((e=>{const t=(0,i.Pu)(e),{isBlurred:s,background:n,backgroundColor:a,patternColor:o}=e.settings.themes[t]||{},{messageLists:r}=e.messages,c=(0,i.Bt)(e),{isLeftColumnShown:l,chats:{listIds:m}}=e,g={theme:t,customBackground:n,backgroundColor:a,patternColor:o,isLeftColumnShown:l,isRightColumnShown:(0,i.Jf)(e),isBackgroundBlurred:s,isMobileSearchActive:Boolean(h.wB&&(0,i.n5)(e)),isSelectModeActive:(0,i.CA)(e),isPaymentModalOpen:e.payment.isPaymentModalOpen,isReceiptModalOpen:Boolean(e.payment.receipt),isSeenByModalOpen:Boolean(e.seenByModal),animationLevel:e.settings.byKey.animationLevel,currentTransitionKey:Math.max(0,e.messages.messageLists.length-1)};if(!c||!m.active)return g;const{chatId:p,threadId:f,type:I}=c,v=(0,i.Z1)(e,p),y=(0,i.IK)(e,p),Z=(0,i.KB)(e,p),{chatId:P,messageId:C}=e.audioPlayer,w=v&&(0,d.Qm)(v,f),b=(0,i.pk)(e,p),S="pinned"===I,E="scheduled"===I,M="thread"===I&&f===u._f,k=Boolean(v&&(0,d.eA)(v)),R=Boolean(v&&M&&(k||(0,d.ZV)(v))&&v.isNotJoined),T=Boolean(y&&(0,i.s4)(e,y.id)),N=!T&&b;return{...g,chatId:p,threadId:f,messageListType:I,isPrivate:(0,d.YC)(p),canPost:!S&&(!v||w)&&!b,isPinnedMessageList:S,isScheduledMessageList:E,currentUserBannedRights:null==v?void 0:v.currentUserBannedRights,defaultBannedRights:null==v?void 0:v.defaultBannedRights,hasPinnedOrAudioPlayer:f!==u._f||Boolean(!S&&(null==Z?void 0:Z.length))||Boolean(P&&C),pinnedMessagesCount:Z?Z.length:0,shouldSkipHistoryAnimations:e.shouldSkipHistoryAnimations,messageLists:r,isChannel:k,canSubscribe:R,canStartBot:N,canRestartBot:T}}))((({chatId:e,threadId:t,messageListType:s,isPrivate:r,isPinnedMessageList:i,messageLists:c,canPost:l,currentUserBannedRights:u,defaultBannedRights:m,hasPinnedOrAudioPlayer:g,pinnedMessagesCount:p,customBackground:f,theme:I,backgroundColor:v,patternColor:y,isLeftColumnShown:Z,isRightColumnShown:P,isBackgroundBlurred:C,isMobileSearchActive:w,isSelectModeActive:b,isPaymentModalOpen:S,isReceiptModalOpen:E,isSeenByModalOpen:M,animationLevel:k,shouldSkipHistoryAnimations:R,currentTransitionKey:T,isChannel:N,canSubscribe:B,canStartBot:A,canRestartBot:x})=>{const{openChat:L,unpinAllMessages:O,loadUser:F,closeLocalTextSearch:U,exitMessageSelectMode:$,closePaymentModal:D,clearReceipt:q,joinChannel:Q,sendBotCommand:G,restartBot:j}=(0,n.uC)(),{width:H}=it(),_=(0,Ce.Z)(),[z,V]=(0,o.eJ)(nt.t.None),[K,Y]=(0,o.eJ)(),[W,X]=(0,o.eJ)(),[J,ee]=(0,o.eJ)(!1),te=g&&(Ha._m&&H=a.ks&&H{e===a.oB&&i(!0)}),[e]),{isReady:r&&!d,handleOpenEnd:e!==a.oB?function(e){"transform"===e.propertyName&&e.target===e.currentTarget&&i(Boolean(n))}:void 0,handleSlideStop:e!==a.oB?function(){i(!0)}:void 0}}(k,T,ge,e);(0,o.d4)((()=>e?(0,fe.Z)((()=>{L({id:void 0})})):void 0),[e,L]),(0,ue.Z)((()=>{V(nt.t.None),Y(void 0),X(void 0)}),[e]),(0,o.d4)((()=>{const{visualViewport:e}=window;if(!e)return;const t=()=>{window.visualViewport.height!==document.documentElement.clientHeight?document.body.classList.add("keyboard-visible"):document.body.classList.remove("keyboard-visible")};return e.addEventListener("resize",t),()=>{e.removeEventListener("resize",t)}}),[]),(0,o.d4)((()=>{r&&F({userId:e})}),[e,r,F]);const we=(0,o.I4)((e=>{if(h.$b)return;const{items:t}=e.dataTransfer||{},s=t&&Array.from(t).filter((e=>"text/uri-list"!==e.type)).every(Oa);V(s?nt.t.QuickFile:nt.t.Document)}),[]),be=(0,o.I4)((()=>{V(nt.t.None)}),[]),Se=(0,o.I4)((()=>{ee(!0)}),[]),Me=(0,o.I4)((()=>{ee(!1)}),[]),ke=(0,o.I4)((()=>{O({chatId:e}),Me(),L({id:e})}),[O,L,Me,e]),Re=(0,o.I4)((()=>{L({id:e})}),[L,e]),Te=(0,o.I4)((()=>{Q({chatId:e})}),[Q,e]),Ne=(0,o.I4)((()=>{G({command:"/start"})}),[G]),Be=(0,o.I4)((()=>{j({chatId:e})}),[e,j]),Ae=((e,t)=>{const[s,n]=(0,o.eJ)(t);return(0,o.d4)((()=>{t&&(t.startsWith("#")?n(t):ot.fetch(a.fo,e,ot.Type.Blob).then((e=>{const t=URL.createObjectURL(e);(0,rt.pt)(t).then((()=>{n(`url(${t})`)}))})))}),[t,e]),t?s:void 0})(I,f),xe=(0,ne.Z)(le&&"has-header-tools",f&&"custom-bg-image",v&&"custom-bg-color",f&&C&&"blurred",h.aZ?"mask-image-disabled":"mask-image-enabled"),Le=(0,ne.Z)("messaging-disabled",!b&&"shown"),Oe=(0,d.q8)(_,u,m),{composerHiddenScale:Fe,toolbarHiddenScale:Ue,composerTranslateX:$e,toolbarTranslateX:De,unpinHiddenScale:qe,toolbarForUnpinHiddenScale:Qe}=(0,o.Ye)((()=>function(e,t){const s=e<=a.l3?16:32,n=function(e){if(e>a._m){const t=Math.min(Math.max(.25*e,288),424),s=Math.min(.25*e,424);return Math.min(e-t-s,ut)}if(e>a.ks){const t=Math.min(Math.max(.4*e,288),424);return Math.min(e-t,ut)}return e>ut?ut:e}(e),o=e<=a.l3?54:64,r=t?n-s-o:n-s,i=e>a.l3?Math.min(n-s,512):n-s,c=i/r,d=r/i;return{composerHiddenScale:c,toolbarHiddenScale:d,composerTranslateX:t?o/2*d:0,toolbarTranslateX:t?o/2*-1*c:0,unpinHiddenScale:i/258,toolbarForUnpinHiddenScale:258/i}}(H,de)),[de,H]),Ge=(0,ne.Z)("middle-column-footer",!de&&"no-composer",de&&W&&!b&&"with-notch");(0,pe.ZP)(se&&ae,(()=>{L({id:void 0},{forceSyncOnIOs:!0})}),void 0,void 0,void 0,(null==c?void 0:c.map(at.q))||[]),(0,pe.ZP)(w,U),(0,pe.ZP)(b,$);const je=Boolean(!i&&!de&&Oe),He=Boolean(ce||re||ie||i),_e=Boolean(je||b||i);return o.ZP.createElement("div",{id:"MiddleColumn",className:xe,onTransitionEnd:ye,style:`\n --composer-hidden-scale: ${Fe};\n --toolbar-hidden-scale: ${Ue};\n --unpin-hidden-scale: ${qe};\n --toolbar-unpin-hidden-scale: ${Qe};\n --composer-translate-x: ${$e}px;\n --toolbar-translate-x: ${De}px;\n --pattern-color: ${y};\n --theme-background-color:\n ${v||("dark"===I?a.It:a.p3)};\n `,onClick:h.p7&&Z?Re:void 0},o.ZP.createElement("div",{id:"middle-column-bg",style:Ae?`--custom-background: ${Ae}`:void 0}),o.ZP.createElement("div",{id:"middle-column-portals"}),se&&ae&&o.ZP.createElement(o.ZP.Fragment,null,o.ZP.createElement("div",{className:"messages-layout",onDragEnter:de?we:void 0},o.ZP.createElement(zt,{chatId:se,threadId:ae,messageListType:oe,isReady:ve}),o.ZP.createElement(Ze.Z,{name:R?"none":k===a.zy?"slide":"fade",activeKey:T,shouldCleanup:!0,cleanupExceptionKey:Ie,onStop:Pe},(()=>o.ZP.createElement(o.ZP.Fragment,null,o.ZP.createElement(bn,{key:`${se}-${ae}-${oe}`,chatId:se,threadId:ae,type:oe,canPost:de,hasTools:le,onFabToggle:Y,onNotchToggle:X,isReady:ve,withBottomShift:He}),o.ZP.createElement("div",{className:Ge},de&&o.ZP.createElement(ka,{chatId:se,threadId:ae,messageListType:oe,dropAreaState:z,onDropHide:be,isReady:ve}),i&&o.ZP.createElement("div",{className:"middle-column-footer-button-container",dir:_.isRtl?"rtl":void 0},o.ZP.createElement(Ee.Z,{size:"tiny",fluid:!0,color:"secondary",className:"unpin-all-button",onClick:Se},o.ZP.createElement("i",{className:"icon-unpin"}),o.ZP.createElement("span",null,_("Chat.Pinned.UnpinAll",p,"i")))),je&&o.ZP.createElement("div",{className:Le},o.ZP.createElement("div",{className:"messaging-disabled-inner"},o.ZP.createElement("span",null,Oe))),h.wB&&re&&o.ZP.createElement("div",{className:"middle-column-footer-button-container",dir:_.isRtl?"rtl":void 0},o.ZP.createElement(Ee.Z,{size:"tiny",fluid:!0,ripple:!0,className:"join-subscribe-button",onClick:Te},_(he?"ProfileJoinChannel":"ProfileJoinGroup"))),h.wB&&ie&&o.ZP.createElement("div",{className:"middle-column-footer-button-container",dir:_.isRtl?"rtl":void 0},o.ZP.createElement(Ee.Z,{size:"tiny",fluid:!0,ripple:!0,className:"join-subscribe-button",onClick:Ne},_("BotStart"))),h.wB&&ce&&o.ZP.createElement("div",{className:"middle-column-footer-button-container",dir:_.isRtl?"rtl":void 0},o.ZP.createElement(Ee.Z,{size:"tiny",fluid:!0,ripple:!0,className:"join-subscribe-button",onClick:Be},_("BotRestart"))),o.ZP.createElement(Ta,{messageListType:oe,isActive:b,canPost:de}),o.ZP.createElement(Ba,{isOpen:Boolean(S),onClose:D}),o.ZP.createElement(Aa,{isOpen:Boolean(E),onClose:q}),o.ZP.createElement(xa,{isOpen:M}))))),o.ZP.createElement(Sn,{isShown:me,canPost:de,withExtraShift:_e})),h.wB&&o.ZP.createElement(Ra,{isActive:Boolean(w)})),e&&o.ZP.createElement(Na,{isOpen:J,chatId:e,pinnedMessagesCount:p,onClose:Me,onUnpin:ke}))}))),Ua=(0,C.Ds)((e=>e()),200,!1);var $a;!function(e){e[e.Profile=0]="Profile",e[e.MemberList=1]="MemberList",e[e.SharedMedia=2]="SharedMedia",e[e.Search=3]="Search",e[e.Management=4]="Management",e[e.ManageInitial=5]="ManageInitial",e[e.ManageChannelSubscribers=6]="ManageChannelSubscribers",e[e.ManageChatAdministrators=7]="ManageChatAdministrators",e[e.ManageChatPrivacyType=8]="ManageChatPrivacyType",e[e.ManageDiscussion=9]="ManageDiscussion",e[e.ManageGroupPermissions=10]="ManageGroupPermissions",e[e.ManageGroupRemovedUsers=11]="ManageGroupRemovedUsers",e[e.ManageGroupUserPermissionsCreate=12]="ManageGroupUserPermissionsCreate",e[e.ManageGroupUserPermissions=13]="ManageGroupUserPermissions",e[e.ManageGroupRecentActions=14]="ManageGroupRecentActions",e[e.ManageGroupAdminRights=15]="ManageGroupAdminRights",e[e.ManageGroupNewAdminRights=16]="ManageGroupNewAdminRights",e[e.ManageGroupMembers=17]="ManageGroupMembers",e[e.ManageGroupAddAdmins=18]="ManageGroupAddAdmins",e[e.StickerSearch=19]="StickerSearch",e[e.GifSearch=20]="GifSearch",e[e.PollResults=21]="PollResults",e[e.AddingMembers=22]="AddingMembers"}($a||($a={}));const Da=(0,o.X$)((0,n.c$)(((e,{chatId:t,isProfile:s,isManagement:n})=>{const{query:a}=(0,i.n5)(e)||{},{query:o}=(0,i.y5)(e)||{},{query:r}=(0,i.yN)(e)||{},c=t?(0,i.Z1)(e,t):void 0,l=c&&(0,d.eA)(c),u=s&&t&&(0,d.YC)(t)?(0,i.dy)(e,t):void 0,m=u&&(0,d.kw)(u);return{canManage:Boolean(!n&&s&&!m&&c&&!(0,i.FM)(e,c.id)&&((0,d.YC)(c.id)||((0,d.Nl)(c)||c.isCreator)&&!c.isNotJoined)),canAddContact:m,isChannel:l,userId:null==u?void 0:u.id,messageSearchQuery:a,stickerSearchQuery:o,gifSearchQuery:r}}))((({isColumnOpen:e,isProfile:t,isSearch:s,isManagement:a,isStickerSearch:r,isGifSearch:i,isPollResults:c,isAddingChatMembers:d,profileState:l,managementScreen:u,canAddContact:g,userId:p,canManage:f,isChannel:I,onClose:v,messageSearchQuery:y,stickerSearchQuery:Z,gifSearchQuery:P,shouldSkipAnimation:C})=>{var w;const{setLocalTextSearchQuery:b,setStickerSearchQuery:S,setGifSearchQuery:E,searchTextMessagesLocal:M,toggleManagement:k,openHistoryCalendar:R,addContact:T}=(0,n.uC)(),B=(0,o.sO)(null),A=(0,o.I4)((e=>{b({query:e}),e.length&&Ua(M)}),[M,b]),x=(0,o.I4)((e=>{S({query:e})}),[S]),L=(0,o.I4)((e=>{E({query:e})}),[E]),O=(0,o.I4)((()=>{T({userId:p})}),[T,p]),[F,U]=(0,o.eJ)(!e);(0,o.d4)((()=>{setTimeout((()=>{U(!e)}),300)}),[e]);const $=(0,Ce.Z)(),D=t?l===m.vi.Profile?$a.Profile:l===m.vi.SharedMedia?$a.SharedMedia:l===m.vi.MemberList?$a.MemberList:-1:s?$a.Search:c?$a.PollResults:r?$a.StickerSearch:i?$a.GifSearch:d?$a.AddingMembers:a?u===m.u1.Initial?$a.ManageInitial:u===m.u1.ChatPrivacyType?$a.ManageChatPrivacyType:u===m.u1.Discussion?$a.ManageDiscussion:u===m.u1.ChannelSubscribers?$a.ManageChannelSubscribers:u===m.u1.GroupPermissions?$a.ManageGroupPermissions:u===m.u1.ChatAdministrators?$a.ManageChatAdministrators:u===m.u1.GroupRemovedUsers?$a.ManageGroupRemovedUsers:u===m.u1.GroupUserPermissionsCreate?$a.ManageGroupUserPermissionsCreate:u===m.u1.GroupUserPermissions?$a.ManageGroupUserPermissions:u===m.u1.GroupRecentActions?$a.ManageGroupRecentActions:u===m.u1.ChatAdminRights?$a.ManageGroupAdminRights:u===m.u1.ChatNewAdminRights?$a.ManageGroupNewAdminRights:u===m.u1.GroupMembers?$a.ManageGroupMembers:u===m.u1.GroupAddAdmins?$a.ManageGroupAddAdmins:void 0:void 0,q=null!==(w=(0,gt.Z)(D,!0))&&void 0!==w?w:-1;function Q(){if(-1!==q)switch(q){case $a.PollResults:return o.ZP.createElement("h3",null,$("PollResults"));case $a.Search:return o.ZP.createElement(o.ZP.Fragment,null,o.ZP.createElement(Me.Z,{parentContainerClassName:"RightSearch",value:y,onChange:A}),o.ZP.createElement(Ee.Z,{round:!0,size:"smaller",color:"translucent",onClick:()=>R({selectedAt:(0,N._F)(Date.now())}),ariaLabel:"Search messages by date"},o.ZP.createElement("i",{className:"icon-calendar"})));case $a.AddingMembers:return o.ZP.createElement("h3",null,$(I?"ChannelAddSubscribers":"GroupAddMembers"));case $a.ManageInitial:return o.ZP.createElement("h3",null,$("Edit"));case $a.ManageChatPrivacyType:return o.ZP.createElement("h3",null,$(I?"ChannelTypeHeader":"GroupTypeHeader"));case $a.ManageDiscussion:return o.ZP.createElement("h3",null,$("Discussion"));case $a.ManageChatAdministrators:return o.ZP.createElement("h3",null,$("ChannelAdministrators"));case $a.ManageGroupRecentActions:return o.ZP.createElement("h3",null,$("Group.Info.AdminLog"));case $a.ManageGroupAdminRights:return o.ZP.createElement("h3",null,$("EditAdminRights"));case $a.ManageGroupNewAdminRights:return o.ZP.createElement("h3",null,$("SetAsAdmin"));case $a.ManageGroupPermissions:return o.ZP.createElement("h3",null,$("ChannelPermissions"));case $a.ManageGroupRemovedUsers:return o.ZP.createElement("h3",null,$("ChannelBlockedUsers"));case $a.ManageGroupUserPermissionsCreate:return o.ZP.createElement("h3",null,$("ChannelAddException"));case $a.ManageGroupUserPermissions:return o.ZP.createElement("h3",null,$("UserRestrictions"));case $a.ManageGroupAddAdmins:return o.ZP.createElement("h3",null,$("Channel.Management.AddModerator"));case $a.StickerSearch:return o.ZP.createElement(Me.Z,{value:Z,placeholder:$("SearchStickersHint"),autoFocusSearch:!0,onChange:x});case $a.GifSearch:return o.ZP.createElement(Me.Z,{value:P,placeholder:$("SearchGifsTitle"),autoFocusSearch:!0,onChange:L});case $a.SharedMedia:return o.ZP.createElement("h3",null,$("SharedMedia"));case $a.ManageChannelSubscribers:return o.ZP.createElement("h3",null,$("ChannelSubscribers"));case $a.MemberList:case $a.ManageGroupMembers:return o.ZP.createElement("h3",null,$("GroupMembers"));default:return o.ZP.createElement(o.ZP.Fragment,null,o.ZP.createElement("h3",null,"Profile"),o.ZP.createElement("section",{className:"tools"},g&&o.ZP.createElement(Ee.Z,{round:!0,color:"translucent",size:"smaller",ariaLabel:$("AddContact"),onClick:O},o.ZP.createElement("i",{className:"icon-add-user"})),f&&o.ZP.createElement(Ee.Z,{round:!0,color:"translucent",size:"smaller",ariaLabel:$("Edit"),onClick:k},o.ZP.createElement("i",{className:"icon-edit"}))))}}const G=h.wB||D===$a.SharedMedia||D===$a.MemberList||D===$a.AddingMembers||a,j=(0,ne.Z)("animated-close-icon",G&&"state-back",(F||C)&&"no-transition");return o.ZP.createElement("div",{className:"RightHeader"},o.ZP.createElement(Ee.Z,{className:"close-button",round:!0,color:"translucent",size:"smaller",onClick:v,ariaLabel:$(G?"Common.Back":"Common.Close")},o.ZP.createElement("div",{ref:B,className:j})),o.ZP.createElement(Ze.Z,{name:F||C?"none":"slide-fade",activeKey:q},Q))})));var qa=s(91),Qa=s(7407);function Ga(e,t,s,n){const[o,r]=(0,Qa.Z)(s?t:void 0,n,void 0,a.Vk);return[o,r,!(!o||!n||o[0]===n[0])]}function ja(e,t,s,n,r,i){const c=(0,o.sO)();(0,ue.Z)((()=>{t===e&&r&&i&&(c.current=(0,d.R5)(r,i,e).reverse())}),[r,i,t,e]);const[l,u]=(0,Qa.Z)(n?s:void 0,c.current,void 0,"media"===e?a.EN:a.pn);return[l,u,!(!l||!c.current||l[0]===c.current[0])]}const Ha=(0,C.P2)((e=>e()),250,!1);let _a=!1;var za=s(1273),Va=s(1876),Ka=s(787),Ya=s(180),Wa=s(3709),Xa=s(5418),Ja=s(7262),eo=s(1151),to=s(2275);const so=[{type:"media",title:"SharedMediaTab2"},{type:"documents",title:"SharedFilesTab2"},{type:"links",title:"SharedLinksTab2"},{type:"audio",title:"SharedMusicTab2"},{type:"voice",title:"SharedVoiceTab2"}];function no(e){return[`.shared-media-transition > div:only-child > .${e}-list > .scroll-item`,`.shared-media-transition > .Transition__slide--active > .${e}-list > .scroll-item`].join(", ")}const ao=(0,o.X$)((0,n.c$)(((e,{chatId:t,userId:s})=>{var n,a;const o=(0,i.Z1)(e,t),r=(0,i.Zw)(e,s||t),{currentType:c,resultsByType:l}=(0,i.we)(e)||{},{foundIds:u}=l&&c&&l[c]||{},{byId:m,statusesById:h}=e.users,{byId:g}=e.chats,p=o&&(0,d.Bf)(o),f=o&&(0,d.eA)(o),I=p||f&&(0,d.Nl)(o),v=null==o||null===(n=o.fullInfo)||void 0===n?void 0:n.members,y=I&&o&&o.fullInfo&&!o.fullInfo.canViewMembers,Z=I&&o&&((0,d.VE)(o,"inviteUsers")||o.isCreator),P=I&&o&&((0,d.VE)(o,"banUsers")||o.isCreator),C=(0,i.xs)(e,t);let w,b,S;return s?b=s:(0,d.YC)(t)&&(b=t),b&&(S=(0,i.dy)(e,b),w=S&&!S.isSelf&&!(0,d.cS)(S)),{theme:(0,i.Pu)(e),isChannel:f,resolvedUserId:b,chatMessages:r,foundIds:u,mediaSearchType:c,hasCommonChatsTab:w,hasMembersTab:I,areMembersHidden:y,canAddMembers:Z,canDeleteMembers:P,currentUserId:e.currentUserId,isRightColumnShown:(0,i.Jf)(e),isRestricted:null==o?void 0:o.isRestricted,lastSyncTime:e.lastSyncTime,serverTimeOffset:e.serverTimeOffset,activeDownloadIds:C,usersById:m,userStatusesById:h,chatsById:g,isChatProtected:null==o?void 0:o.isProtected,...I&&v&&{members:v},...w&&S&&{commonChatIds:null===(a=S.commonChats)||void 0===a?void 0:a.ids}}}))((({chatId:e,profileState:t,onProfileStateChange:s,theme:r,isChannel:i,resolvedUserId:c,currentUserId:l,chatMessages:g,foundIds:p,mediaSearchType:f,hasCommonChatsTab:I,hasMembersTab:v,areMembersHidden:y,canAddMembers:Z,canDeleteMembers:P,commonChatIds:C,members:w,usersById:b,userStatusesById:S,chatsById:E,isRightColumnShown:M,isRestricted:k,lastSyncTime:R,activeDownloadIds:T,serverTimeOffset:N,isChatProtected:B})=>{const{setLocalMediaSearchType:A,loadMoreMembers:x,loadCommonChats:L,openChat:O,searchMediaMessagesLocal:F,openMediaViewer:U,openAudioPlayer:$,openUserInfo:D,focusMessage:q,loadProfilePhotos:Q,setNewChatMembersDialogState:G}=(0,n.uC)(),j=(0,o.sO)(null),H=(0,o.sO)(null),_=(0,Ce.Z)(),[z,V]=(0,o.eJ)(0),[K,Y]=(0,o.eJ)(),W=(0,o.Ye)((()=>[...v?[{type:"members",title:i?"ChannelSubscribers":"GroupMembers"}]:[],...so,...I?[{type:"commonChats",title:"SharedGroupsTab2"}]:[]]),[I,v,i]),X=W[z].type,[J,ee,te,se]=function(e,t,s,n,a,r,i,c,l,u,m,h,g,p,f,I=0){const v="members"!==a&&r?r:a,y=(0,o.Ye)((()=>{if(i&&l&&u)return(0,d.Z0)(i.map((({userId:e})=>e)),l,u,void 0,I)}),[i,I,l,u]),Z=(0,o.Ye)((()=>{if(c&&m)return(0,d.ih)(c,m,!0)}),[m,c]),[P,C,w]=Ga(0,t,f,y),[b,S,E]=ja("media",v,n,f,h,g),[M,k,R]=ja("documents",v,n,f,h,g),[T,N,B]=ja("links",v,n,f,h,g),[A,x,L]=ja("audio",v,n,f,h,g),[O,F,U]=ja("voice",v,n,f,h,g),[$,D,q]=Ga(0,s,f,Z);let Q,G,j=!1;switch(v){case"members":Q=P,G=C,j=w;break;case"commonChats":Q=$,G=D,j=q;break;case"media":Q=b,G=S,j=E;break;case"documents":Q=M,G=k,j=R;break;case"links":Q=T,G=N,j=B;break;case"audio":Q=A,G=x,j=L;break;case"voice":Q=O,G=F,j=U}return[v,Q,G,j]}(0,x,L,F,X,f,w,C,b,S,E,g,p,0,R,N),ne=W.findIndex((({type:e})=>e===J)),{handleScroll:ae}=function(e,t,s,n){(0,Kt.Z)((([s])=>{if(s&&s!==t){const s=e.current,a=s.querySelector(".TabList");s.scrollTop{_a=!1}),350))}}),[t,n]),(0,Kt.Z)((([t])=>{if(s!==m.vi.Profile||s===t)return;const a=e.current;if(!a)return;const o=a.querySelector(".TabList");!o||o.offsetTop>a.scrollTop||(_a=!0,(0,ts.Z)(a,a.firstElementChild,"start",void 0,2*a.offsetHeight),setTimeout((()=>{_a=!1}),350),n(s))}),[s]);const a=(0,o.I4)((()=>{const s=e.current;if(!s)return;const a=s.querySelector(".TabList");if(!a)return;let o=m.vi.Profile;s.scrollTop>=a.offsetTop&&(o="members"===t?m.vi.MemberList:m.vi.SharedMedia),n(o)}),[e,n,t]);return(0,o.d4)((()=>{_a||a()}),[a,t]),{handleScroll:(0,o.I4)((()=>{_a||Ha(a)}),[a])}}(j,X,t,s),{applyTransitionFix:oe,releaseTransitionFix:re}=function(e,t=".Transition.shared-media-transition"){return(0,o.d4)((()=>{function s(){const s=e.current,n=s.querySelector(t),a=s.querySelector(".TabList");n&&a&&(n.style.minHeight=s.offsetHeight-a.offsetHeight+"px")}return s(),window.addEventListener("resize",s,!1),()=>{window.removeEventListener("resize",s,!1)}}),[e,t]),{applyTransitionFix:(0,o.I4)((()=>{const t=e.current;if("hidden"!==t.style.overflowY){const e=t.offsetWidth-t.clientWidth;t.style.overflowY="hidden",t.style.marginRight=`${e}px`}}),[e]),releaseTransitionFix:(0,o.I4)((()=>{const t=e.current;t.style.overflowY="scroll",t.style.marginRight="0"}),[e])}}(j),[ie,ce]=(()=>{const[e,t]=(0,o.eJ)(!1);return[e,(0,o.I4)((()=>{t((e=>!e))}),[])]})(),de=(0,o.I4)((()=>{re(),ce()}),[re,ce]),le=(0,o.I4)((()=>{G(m.WB.InProgress)}),[G]);(0,o.d4)((()=>{A({mediaType:X})}),[A,X]);const ue=c||e;(0,o.d4)((()=>{R&&Q({profileId:ue})}),[Q,ue,R]);const me=(0,o.I4)((e=>{U({chatId:ue,threadId:u._f,messageId:e,origin:m.bZ.SharedMedia})}),[ue,U]),he=(0,o.I4)((e=>{$({chatId:ue,messageId:e})}),[ue,$]),ge=(0,o.I4)((e=>{D({id:e})}),[D]),pe=(0,o.I4)((e=>{q({chatId:ue,messageId:e})}),[ue,q]),fe=(0,o.I4)((()=>{Y(void 0)}),[]);let Ie;(0,o.d4)((()=>{if(H.current&&h.$b)return(0,xe.s)(H.current,{selectorToPreventScroll:".Profile",onSwipe:(e,t)=>t===xe.e.Left?(V(Math.min(z+1,W.length-1)),!0):t===xe.e.Right&&(V(Math.max(0,z-1)),!0)})}),[z,W.length]);const ve="members"===J||!v&&"media"===J;ve?Ie=M?0:1e3:ee||(Ie=a.Y);const ye=(0,fa.Z)([e,J],Ie);function Pe(){if(!ee||!ye||!g){const e=ve&&ee&&!ye;return o.ZP.createElement("div",{className:"content empty-list"},!e&&o.ZP.createElement(Be.Z,null))}if(!ee.length){let e;switch(J){case"members":e=y?"You have no access to group members list.":"No members found";break;case"commonChats":e=_("NoGroupsInCommon");break;case"documents":e=_("lng_media_file_empty");break;case"links":e=_("lng_media_link_empty");break;case"audio":e=_("lng_media_song_empty");break;case"voice":e=_("lng_media_audio_empty");break;default:e=_("SharedMedia.EmptyTitle")}return o.ZP.createElement("div",{className:"content empty-list"},o.ZP.createElement(Ja.Z,{text:e}))}return o.ZP.createElement("div",{className:`content ${J}-list`,dir:_.isRtl&&"media"===J?"rtl":void 0,teactFastList:!0},"media"===J?ee.map((e=>g[e]&&o.ZP.createElement(Wa.Z,{key:e,message:g[e],isProtected:B||g[e].isProtected,onClick:me}))):"documents"===J?ee.map((e=>g[e]&&o.ZP.createElement(Ps.Z,{key:e,message:g[e],withDate:!0,smaller:!0,className:"scroll-item",onDateClick:pe,isDownloading:T.includes(e)}))):"links"===J?ee.map((e=>g[e]&&o.ZP.createElement(Xa.Z,{key:e,message:g[e],isProtected:B||g[e].isProtected,onMessageClick:pe}))):"audio"===J?ee.map((e=>g[e]&&o.ZP.createElement(Cs.Z,{key:e,theme:r,message:g[e],origin:m.Cr.SharedMedia,date:g[e].date,lastSyncTime:R,className:"scroll-item",onPlay:he,onDateClick:pe,isDownloading:T.includes(e)}))):"voice"===J?ee.map((e=>g[e]&&o.ZP.createElement(Cs.Z,{key:e,theme:r,message:g[e],senderTitle:(0,qa.F)(_,g[e],E,b),origin:m.Cr.SharedMedia,date:g[e].date,lastSyncTime:R,className:"scroll-item",onPlay:he,onDateClick:pe,isDownloading:T.includes(e)}))):"members"===J?ee.map(((e,t)=>{return o.ZP.createElement(Va.Z,{key:e,teactOrderKey:t,className:"chat-item-clickable scroll-item small-icon",onClick:()=>ge(e),contextActions:(s=e,s!==l&&P?[{title:_("lng_context_remove_from_group"),icon:"stop",handler:()=>{Y(s)}}]:void 0)},o.ZP.createElement(ft.Z,{userId:e,forceShowSelf:!0}));var s})):"commonChats"===J?ee.map(((e,t)=>o.ZP.createElement(Va.Z,{key:e,teactOrderKey:t,className:"chat-item-clickable scroll-item small-icon",onClick:()=>O({id:e})},o.ZP.createElement(It.Z,{chatId:e})))):void 0)}return o.ZP.createElement(za.Z,{ref:j,className:"Profile custom-scroll",itemSelector:no(J),items:ye?ee:void 0,cacheBuster:ie,sensitiveArea:a.qU,preloadBackwards:ye?"members"===J?a.Vk:a.EN:0,noScrollRestoreOnTop:!0,noFastList:!0,onLoadMore:te,onScroll:ae},!se&&function(e,t){return o.ZP.createElement("div",{className:"profile-info"},o.ZP.createElement(Ka.Z,{userId:t||e}),o.ZP.createElement(Ya.Z,{chatOrUserId:t||e}))}(e,c),!k&&o.ZP.createElement("div",{className:"shared-media"},o.ZP.createElement(Ze.Z,{ref:H,name:_.isRtl?"slide-optimized-rtl":"slide-optimized",activeKey:ne,renderCount:W.length,shouldRestoreHeight:!0,className:"shared-media-transition",onStart:oe,onStop:de},Pe),o.ZP.createElement(Oe.Z,{big:!0,activeTab:z,tabs:W,onSwitchTab:V})),Z&&o.ZP.createElement(eo.Z,{isShown:"members"===J,onClick:le,ariaLabel:_("lng_channel_add_users")},o.ZP.createElement("i",{className:"icon-add-user-filled"})),P&&o.ZP.createElement(to.Z,{isOpen:Boolean(K),userId:K,onClose:fe}))}))),oo=(0,o.X$)((e=>{const t=(0,De.Z)($e.gl.Extra,"RightSearch");return t?o.ZP.createElement(t,e):o.ZP.createElement(qe.Z,null)})),ro=(0,o.X$)((e=>{const t=(0,De.Z)($e.gl.Extra,"Management");return t?o.ZP.createElement(t,e):o.ZP.createElement(qe.Z,null)})),io=(0,o.X$)((()=>{const e=(0,De.Z)($e.gl.Extra,"StickerSearch");return e?o.ZP.createElement(e,null):o.ZP.createElement(qe.Z,null)})),co=(0,o.X$)((()=>{const e=(0,De.Z)($e.gl.Extra,"GifSearch");return e?o.ZP.createElement(e,null):o.ZP.createElement(qe.Z,null)})),lo=(0,o.X$)((()=>{const e=(0,De.Z)($e.gl.Extra,"PollResults");return e?o.ZP.createElement(e,null):o.ZP.createElement(qe.Z,null)}));var uo=s(1820);const mo=(0,o.X$)((0,n.c$)(((e,{chatId:t})=>{var s;const n=(0,i.Z1)(e,t),{userIds:a}=e.contactList||{},{byId:o}=e.chats,{currentUserId:r,newChatMembersProgress:c,connectionState:l}=e,u=n&&(0,d.eA)(n),{query:h,fetchingStatus:g,globalUserIds:p,localUserIds:f}=e.userSearch;return{isChannel:u,members:null==n||null===(s=n.fullInfo)||void 0===s?void 0:s.members,currentUserId:r,chatsById:o,localContactIds:a,searchQuery:h,isSearching:g,isLoading:c===m.WB.Loading,globalUserIds:p,localUserIds:f,connectionState:l}}))((({isChannel:e,connectionState:t,members:s,onNextStep:a,currentUserId:r,chatsById:i,localContactIds:c,isLoading:l,searchQuery:u,isSearching:m,localUserIds:h,globalUserIds:p,onClose:f,isActive:I})=>{const{setUserSearchQuery:v,loadContactList:y}=(0,n.uC)(),Z=(0,Ce.Z)(),[P,C]=(0,o.eJ)([]),w=(0,dt.Z)(P)===P;(0,o.d4)((()=>{I&&"connectionStateReady"===t&&y()}),[t,I,y]),(0,pe.ZP)(I,f);const b=(0,o.Ye)((()=>s?s.map((e=>e.userId)):[]),[s]),S=(0,o.I4)((e=>{v({query:e})}),[v]),E=(0,o.Ye)((()=>{const t=(0,n.Rd)().users.byId,s=c?(0,d.kK)(c,t,u):[];return(0,d.ih)((0,g.Tw)([...s,...h||[],...p||[]]).filter((s=>{const n=t[s];return!b.includes(s)&&s!==r&&(!n||!(0,d.cS)(n)||!e&&n.canBeInvitedToGroup)})),i)}),[c,i,u,h,p,r,b,e]),M=(0,o.I4)((()=>{P.length&&(v({query:""}),a(P))}),[P,v,a]);return o.ZP.createElement("div",{className:"AddChatMembers"},o.ZP.createElement("div",{className:"AddChatMembers-inner"},o.ZP.createElement(uo.Z,{itemIds:E,selectedIds:P,filterValue:u,filterPlaceholder:Z("lng_channel_add_users"),searchInputId:"new-members-picker-search",isLoading:m,onSelectedIdsChange:C,onFilterChange:S,noScrollRestore:w}),o.ZP.createElement(eo.Z,{isShown:Boolean(P.length),disabled:l,ariaLabel:Z("lng_channel_add_users"),onClick:M},l?o.ZP.createElement(Be.Z,{color:"white"}):o.ZP.createElement("i",{className:"icon-arrow-right"}))))}))),ho=Object.keys(m.qt).length/2,go=Object.keys(m.u1).length/2;function po(){const e=document.querySelector(".RightHeader .SearchInput input");e&&e.blur()}const fo=(0,o.X$)((0,n.c$)((e=>{const{chatId:t,threadId:s}=(0,i.Bt)(e)||{},n=(0,i.g4)(e);return{contentKey:(0,i.Wq)(e),chatId:t,threadId:s,currentProfileUserId:e.users.selectedId,isChatSelected:Boolean(t&&n),shouldSkipHistoryAnimations:e.shouldSkipHistoryAnimations}}))((({contentKey:e,chatId:t,threadId:s,currentProfileUserId:r,isChatSelected:i,shouldSkipHistoryAnimations:c})=>{var d;const{toggleChatInfo:l,toggleManagement:u,openUserInfo:h,closeLocalTextSearch:g,setStickerSearchQuery:p,setGifSearchQuery:f,closePollResults:I,addChatMembers:v,setNewChatMembersDialogState:y}=(0,n.uC)(),{width:Z}=it(),[P,C]=(0,o.eJ)(m.vi.Profile),[w,b]=(0,o.eJ)(m.u1.Initial),[S,E]=(0,o.eJ)(),[M,k]=(0,o.eJ)(),R=P!==m.vi.Profile,T=void 0!==e,N=e===m.qt.ChatInfo||e===m.qt.UserInfo,B=e===m.qt.Search,A=e===m.qt.Management,x=e===m.qt.StickerSearch,L=e===m.qt.GifSearch,O=e===m.qt.PollResults,F=e===m.qt.AddingMembers,U=Z<=a._m,[$,D]=(0,o.eJ)(!T),q=null!==(d=(0,gt.Z)(e,!0,!i))&&void 0!==d?d:-1,Q=(0,o.I4)(((t=!0)=>{switch(e){case m.qt.AddingMembers:y(m.WB.Closed);break;case m.qt.ChatInfo:if(R&&t){C(m.vi.Profile);break}l(void 0,{forceSyncOnIOs:!0});break;case m.qt.UserInfo:if(R&&t){C(m.vi.Profile);break}h({id:void 0},{forceSyncOnIOs:!0});break;case m.qt.Management:switch(w){case m.u1.Initial:u();break;case m.u1.ChatPrivacyType:case m.u1.Discussion:case m.u1.GroupPermissions:case m.u1.GroupType:case m.u1.ChatAdministrators:case m.u1.ChannelSubscribers:case m.u1.GroupMembers:b(m.u1.Initial);break;case m.u1.GroupUserPermissionsCreate:case m.u1.GroupRemovedUsers:case m.u1.GroupUserPermissions:b(m.u1.GroupPermissions),E(void 0),k(void 0);break;case m.u1.ChatAdminRights:case m.u1.ChatNewAdminRights:case m.u1.GroupAddAdmins:case m.u1.GroupRecentActions:b(m.u1.ChatAdministrators)}break;case m.qt.Search:po(),g();break;case m.qt.StickerSearch:po(),p({query:void 0});break;case m.qt.GifSearch:po(),f({query:void 0});break;case m.qt.PollResults:I()}}),[e,R,l,h,I,y,w,u,g,p,f]),G=(0,o.I4)(((e,t)=>{E(e),k(t)}),[]),j=(0,o.I4)((e=>{v({chatId:t,memberIds:e})}),[v,t]);function H(e){if(-1!==q)switch(q){case m.qt.AddingMembers:return o.ZP.createElement(mo,{chatId:t,onNextStep:j,isActive:T&&e,onClose:Q});case m.qt.ChatInfo:case m.qt.UserInfo:return o.ZP.createElement(ao,{key:r||t,chatId:t,userId:r,profileState:P,onProfileStateChange:C});case m.qt.Search:return o.ZP.createElement(oo,{chatId:t,threadId:s,onClose:Q,isActive:T&&e});case m.qt.Management:return o.ZP.createElement(ro,{chatId:t,currentScreen:w,isPromotedByCurrentUser:M,selectedChatMemberId:S,onScreenSelect:b,onChatMemberSelect:G,isActive:T&&e,onClose:Q});case m.qt.StickerSearch:return o.ZP.createElement(io,{onClose:Q,isActive:T&&e});case m.qt.GifSearch:return o.ZP.createElement(co,{onClose:Q,isActive:T&&e});case m.qt.PollResults:return o.ZP.createElement(lo,{onClose:Q,isActive:T&&e})}}return(0,o.d4)((()=>T?(0,fe.Z)(Q):void 0),[T,Q]),(0,o.d4)((()=>{setTimeout((()=>{D(!T)}),300)}),[T]),(0,o.d4)((()=>{T&&U&&Q()}),[U]),(0,Vt.Z)((([s,n])=>{(s===m.qt.ChatInfo&&e===m.qt.UserInfo||s===m.qt.UserInfo&&e===m.qt.ChatInfo||n!==t)&&(C(m.vi.Profile),b(m.u1.Initial))}),[e,t]),(0,pe.ZP)(i&&(e===m.qt.ChatInfo||e===m.qt.UserInfo||e===m.qt.Management||e===m.qt.AddingMembers),(()=>Q(!1)),l),o.ZP.createElement("div",{id:"RightColumn-wrapper",className:i?void 0:"is-hidden"},U&&o.ZP.createElement("div",{className:"overlay-backdrop",onClick:Q}),o.ZP.createElement("div",{id:"RightColumn"},o.ZP.createElement(Da,{chatId:t,isColumnOpen:T,isProfile:N,isSearch:B,isManagement:A,isStickerSearch:x,isGifSearch:L,isPollResults:O,isAddingChatMembers:F,profileState:P,managementScreen:w,onClose:Q,shouldSkipAnimation:$||c}),o.ZP.createElement(Ze.Z,{name:$||c?"none":"zoom-fade",renderCount:ho+go,activeKey:A?ho+w:q,shouldCleanup:!0,cleanupExceptionKey:m.qt.ChatInfo},H)))}))),Io=(0,o.X$)((({isOpen:e})=>{const t=(0,De.Z)($e.gl.Extra,"MediaViewer",!e);return t?o.ZP.createElement(t,null):void 0}));function vo(e,t){const s=document.createElement("a");s.href=e,s.download=t;try{s.click()}catch(e){console.error(e)}}const yo=new Set,Zo=(0,o.X$)((0,n.c$)((e=>({activeDownloads:e.activeDownloads.byChatId,messages:e.messages.byChatId})))((({activeDownloads:e,messages:t})=>{const{cancelMessageMediaDownload:s}=(0,n.uC)();(0,o.d4)((()=>{Object.entries(e).forEach((([e,n])=>{n.map((s=>t[Number(e)].byId[s])).forEach((e=>{const t=(0,d.Ti)(e,"download");if(t){if(!yo.has(t)){const n=Tt.UV(t);if(n)return yo.delete(t),vo(n,(0,d.w6)(e)),void s({message:e});Tt.he(t,u.IU.BlobUrl,!0).then((n=>{yo.delete(t),n&&vo(n,(0,d.w6)(e)),s({message:e})})),yo.add(t)}}else s({message:e})}))}))}),[s,t,e])}))),Po=(0,o.X$)((({isOpen:e})=>{const t=(0,De.Z)($e.gl.Extra,"Notifications",!e);return t?o.ZP.createElement(t,null):void 0})),Co=(0,o.X$)((({isOpen:e})=>{const t=(0,De.Z)($e.gl.Extra,"Dialogs",!e);return t?o.ZP.createElement(t,null):void 0})),wo=(0,o.X$)((e=>{const{isOpen:t}=e,s=(0,De.Z)($e.gl.Extra,"ForwardPicker",!t);return s?o.ZP.createElement(s,e):void 0})),bo=(0,o.X$)((e=>{const{url:t}=e,s=(0,De.Z)($e.gl.Extra,"SafeLinkModal",!t);return s?o.ZP.createElement(s,e):void 0})),So=(0,o.X$)((e=>{const{isOpen:t}=e,s=(0,De.Z)($e.gl.Extra,"HistoryCalendar",!t);return s?o.ZP.createElement(s,e):void 0})),Eo=(0,o.X$)((e=>{const{groupCallId:t}=e,s=(0,De.Z)($e.gl.Calls,"GroupCall",!t);return s?o.ZP.createElement(s,e):void 0})),Mo=(0,o.X$)((e=>{const{groupCallId:t}=e,s=(0,De.Z)($e.gl.Calls,"ActiveCallHeader",!t);return s?o.ZP.createElement(s,null):void 0})),ko=(0,o.X$)((({isOpen:e})=>{const t=(0,De.Z)($e.gl.Calls,"CallFallbackConfirm",!e);return t?o.ZP.createElement(t,{isOpen:e}):void 0}));let Ro,To=!1;function No(e){document.querySelectorAll('link[rel="icon"], link[rel="alternate icon"]').forEach((t=>{e?t.href.includes("favicon-unread")||(t.href=t.href.replace("favicon","favicon-unread")):t.href=t.href.replace("favicon-unread","favicon")}))}function Bo(e){document.title!==e&&(document.title=e)}const Ao=(0,o.X$)((0,n.c$)((e=>{const{settings:{byKey:{animationLevel:t,language:s,wasTimeFormatSetManually:n}}}=e,{chatId:a,messageId:o}=e.audioPlayer,r=a&&o?(0,i.hj)(e,a,o):void 0;return{lastSyncTime:e.lastSyncTime,isLeftColumnShown:e.isLeftColumnShown,isRightColumnShown:(0,i.Jf)(e),isMediaViewerOpen:(0,i.zQ)(e),isForwardModalOpen:(0,i.Ev)(e),hasNotifications:Boolean(e.notifications.length),hasDialogs:Boolean(e.dialogs.length),audioMessage:r,safeLinkModalUrl:e.safeLinkModalUrl,isHistoryCalendarOpen:Boolean(e.historyCalendarSelectedAt),shouldSkipHistoryAnimations:e.shouldSkipHistoryAnimations,openedStickerSetShortName:e.openedStickerSetShortName,isServiceChatReady:(0,i.UW)(e),activeGroupCallId:e.groupCalls.activeGroupCallId,animationLevel:t,language:s,wasTimeFormatSetManually:n,isCallFallbackConfirmOpen:Boolean(e.groupCalls.isFallbackConfirmOpen),addedSetIds:e.stickers.added.setIds}}))((({lastSyncTime:e,isLeftColumnShown:t,isRightColumnShown:s,isMediaViewerOpen:r,isForwardModalOpen:c,hasNotifications:d,hasDialogs:l,audioMessage:u,activeGroupCallId:m,safeLinkModalUrl:g,isHistoryCalendarOpen:p,shouldSkipHistoryAnimations:f,openedStickerSetShortName:I,isServiceChatReady:v,animationLevel:y,language:Z,wasTimeFormatSetManually:P,isCallFallbackConfirmOpen:w,addedSetIds:b})=>{const{loadAnimatedEmojis:S,loadNotificationSettings:E,loadNotificationExceptions:M,updateIsOnline:k,loadTopInlineBots:R,loadEmojiKeywords:T,loadCountryList:N,loadStickerSets:B,loadAddedStickers:A,loadFavoriteStickers:x,ensureTimeFormat:L,openStickerSetShortName:O,checkVersionNotification:F}=(0,n.uC)(),U=Boolean(e);a.eM&&!To&&(To=!0,console.log(">>> RENDER MAIN")),(0,o.d4)((()=>{e&&(k(!0),S(),E(),M(),R(),T({language:a.pR}))}),[e,S,T,M,E,R,k]),(0,o.d4)((()=>{e&&(Z!==a.pR&&T({language:Z}),N({langCode:Z}))}),[Z,e,N,T]),(0,o.d4)((()=>{U&&(b?A():(B(),x()))}),[U,b,B,x,A]),(0,o.d4)((()=>{e&&v&&F()}),[e,v,F]),(0,o.d4)((()=>{e&&!P&&L()}),[e,P,L]),(0,o.d4)((()=>{e&&pe.Oy.startsWith("#?tgaddr=")&&(0,oe.o)(decodeURIComponent(pe.Oy.substr("#?tgaddr=".length)))}),[e]),(0,o.d4)((()=>{if(m)return ie.Z.disableRefresh(),()=>{ie.Z.enableRefresh()}}),[m]);const{transitionClassNames:$}=(0,ce.Z)(!t,void 0,!0,void 0,f),{transitionClassNames:D}=(0,ce.Z)(s,void 0,!0,void 0,f),q=(0,ne.Z)($.replace(/([\w-]+)/g,"middle-column-$1"),D.replace(/([\w-]+)/g,"right-column-$1"),f&&"history-animation-disabled");(0,ue.Z)((([e])=>{if(void 0===e||0===y)return;const t=(0,se.YW)();(0,ae.L)(document.getElementById("MiddleColumn"),t)}),[t]),(0,ue.Z)((([e])=>{if(void 0===e||0===y)return;(0,C.T2)((()=>{document.body.classList.add("animating-right-column")}));const t=(0,se.YW)();(0,ae.L)(document.getElementById("RightColumn"),(()=>{t(),(0,C.T2)((()=>{document.body.classList.remove("animating-right-column")}))}))}),[s]);const Q=(0,o.I4)((()=>{k(!1);const e=(0,i.A1)((0,n.Rd)());let t=0;clearInterval(Ro),Ro=window.setInterval((()=>{if(document.title.includes(a.ou))No(!1);else{if(t%2==0){const t=(0,i.A1)((0,n.Rd)())-e;t>0&&(Bo(`${t} notification${t>1?"s":""}`),No(!0))}else Bo(a.Ti),No(!1);t++}}),1e3)}),[k]),G=(0,o.I4)((()=>{k(!0),clearInterval(Ro),Ro=void 0,document.title.includes(a.ou)||Bo(a.Ti),No(!1)}),[k]),j=(0,o.I4)((()=>{O({stickerSetShortName:void 0})}),[O]);return(0,de.Z)(Q,G),le(Q),function(e=!1){(0,o.d4)((()=>{if(h.$b){if(!e)return null==me||me.setAttribute("content",he),h.cj&&!h.fl&&document.addEventListener("gesturestart",ge),()=>{null==me||me.setAttribute("content","width=device-width, initial-scale=1, shrink-to-fit=no"),h.cj&&!h.fl&&document.removeEventListener("gesturestart",ge)};null==me||me.setAttribute("content","width=device-width, initial-scale=1, shrink-to-fit=no, viewport-fit=cover")}}),[e])}(r),o.ZP.createElement("div",{id:"Main",className:q,onDrop:re.Z,onDragOver:re.Z},o.ZP.createElement(st,null),o.ZP.createElement(Fa,null),o.ZP.createElement(fo,null),o.ZP.createElement(Io,{isOpen:r}),o.ZP.createElement(wo,{isOpen:c}),o.ZP.createElement(Po,{isOpen:d}),o.ZP.createElement(Co,{isOpen:l}),u&&o.ZP.createElement(Gt,{key:u.id,message:u,noUi:!0}),o.ZP.createElement(bo,{url:g}),o.ZP.createElement(So,{isOpen:p}),o.ZP.createElement(Ms.Z,{isOpen:Boolean(I),onClose:j,stickerSetShortName:I}),m&&o.ZP.createElement(o.ZP.Fragment,null,o.ZP.createElement(Eo,{groupCallId:m}),o.ZP.createElement(Mo,{groupCallId:m})),o.ZP.createElement(Zo,null),o.ZP.createElement(ko,{isOpen:w}))})));a.eM&&console.log(">>> FINISH LOAD MAIN BUNDLE"),(0,n.Rd)().connectionState||(0,n.uC)().initApi()},4524:(e,t,s)=>{e.exports=s.p+"telegram-logo-filled.67469f6dc5e301e8e0bd..svg"}}]); -//# sourceMappingURL=87.77459230580aafa8639a.js.map \ No newline at end of file diff --git a/dist/87.77459230580aafa8639a.js.map b/dist/87.77459230580aafa8639a.js.map deleted file mode 100644 index da4d30da..00000000 --- a/dist/87.77459230580aafa8639a.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"87.77459230580aafa8639a.js","mappings":"oNAoDO,SAASA,EAAqBC,GACnC,MAAM,OAAEC,EAAF,SAAUC,IAAaC,EAAAA,EAAAA,IAAyBH,IAAW,GACjE,OAAKC,GAAW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ASkH,oBAAoB,eAAgBV,KAhB/CJ,MAAAA,IAAAA,GAAcg3B,aAAa,UAXE,gFA8B9B,CAACgwB,IoIiQJyjB,CAA2BnC,GAGzB,0BAAKr8F,GAAG,OAAOy3B,UAAWA,EAAWgnE,OAAQ5iC,GAAAA,EAAW6iC,WAAY7iC,GAAAA,GAClE,mBAAC,GAAD,MACA,mBAAC,GAAD,MACA,mBAAC,GAAD,MACA,mBAAC,GAAD,CAAazkC,OAAQilE,IACrB,mBAAC,GAAD,CAAejlE,OAAQmlE,IACvB,mBAAC,GAAD,CAAenlE,OAAQqlE,IACvB,mBAAC,GAAD,CAASrlE,OAAQslE,IAChB/mD,GAAgB,mBAAC,GAAD,CAAarjB,IAAKqjB,EAAa31C,GAAImG,QAASwvC,EAAcjD,MAAI,IAC/E,mBAAC,GAAD,CAAepmC,IAAKC,IACpB,mBAAC,GAAD,CAAiB6qB,OAAQulE,IACzB,mBAAC,KAAD,CACEvlE,OAAQl1B,QAAQsY,GAChBumB,QAASw9D,EACT7lF,oBAAqB8B,IAEtBwY,GACC,sCACE,mBAAC,GAAD,CAAWO,YAAaP,IACxB,mBAAC,GAAD,CAAkBO,YAAaP,KAGnC,mBAAC,GAAD,MACA,mBAAC,GAAD,CAAqBoE,OAAQylE,SCxT/Bp+E,EAAAA,IAEFC,QAAQC,IAAI,gCAGTra,EAAAA,EAAAA,MAAYwuB,kBACf7V,EAAAA,EAAAA,MAAc0hF,W","sources":["webpack://telegram-t/./src/modules/actions/ui/localSearch.ts","webpack://telegram-t/./src/modules/actions/ui/chats.ts","webpack://telegram-t/./src/modules/actions/ui/messages.ts","webpack://telegram-t/./src/versionNotification.txt","webpack://telegram-t/./src/modules/actions/ui/globalSearch.ts","webpack://telegram-t/./src/modules/actions/ui/stickerSearch.ts","webpack://telegram-t/./src/modules/actions/ui/users.ts","webpack://telegram-t/./src/modules/actions/ui/misc.ts","webpack://telegram-t/./src/modules/actions/ui/payments.ts","webpack://telegram-t/./src/modules/actions/api/messages.ts","webpack://telegram-t/./src/modules/actions/api/symbols.ts","webpack://telegram-t/./src/modules/actions/api/globalSearch.ts","webpack://telegram-t/./src/modules/actions/api/localSearch.ts","webpack://telegram-t/./src/modules/actions/api/management.ts","webpack://telegram-t/./src/modules/actions/api/sync.ts","webpack://telegram-t/./src/modules/actions/api/users.ts","webpack://telegram-t/./src/modules/reducers/bots.ts","webpack://telegram-t/./src/modules/actions/api/bots.ts","webpack://telegram-t/./src/modules/actions/api/twoFaSettings.ts","webpack://telegram-t/./src/modules/actions/api/payments.ts","webpack://telegram-t/./src/util/requestQuery.ts","webpack://telegram-t/./src/modules/actions/apiUpdaters/chats.ts","webpack://telegram-t/./src/modules/actions/apiUpdaters/messages.ts","webpack://telegram-t/./src/modules/actions/apiUpdaters/users.ts","webpack://telegram-t/./src/modules/actions/apiUpdaters/symbols.ts","webpack://telegram-t/./src/modules/actions/apiUpdaters/misc.ts","webpack://telegram-t/./src/modules/actions/apiUpdaters/settings.ts","webpack://telegram-t/./src/modules/actions/apiUpdaters/twoFaSettings.ts","webpack://telegram-t/./src/modules/actions/apiUpdaters/calls.ts","webpack://telegram-t/./src/hooks/useBeforeUnload.ts","webpack://telegram-t/./src/hooks/usePreventPinchZoomGesture.ts","webpack://telegram-t/./src/hooks/useBrowserOnline.ts","webpack://telegram-t/./src/components/left/main/LeftMainHeader.tsx","webpack://telegram-t/./src/components/left/ConnectionState.tsx","webpack://telegram-t/./src/components/left/main/ChatFolders.tsx","webpack://telegram-t/./src/hooks/useThrottledMemo.ts","webpack://telegram-t/./src/components/left/search/LeftSearch.async.tsx","webpack://telegram-t/./src/components/left/main/ContactList.async.tsx","webpack://telegram-t/./src/components/left/NewChatButton.tsx","webpack://telegram-t/./src/components/left/main/LeftMain.tsx","webpack://telegram-t/./src/components/left/settings/Settings.async.tsx","webpack://telegram-t/./src/components/left/newChat/NewChat.async.tsx","webpack://telegram-t/./src/components/left/ArchivedChats.async.tsx","webpack://telegram-t/./src/components/left/LeftColumn.tsx","webpack://telegram-t/./src/hooks/useResize.ts","webpack://telegram-t/./src/hooks/useCustomBackground.ts","webpack://telegram-t/./src/hooks/useWindowSize.ts","webpack://telegram-t/./src/components/middle/helpers/calculateMiddleFooterTransforms.ts","webpack://telegram-t/./src/components/middle/HeaderMenuContainer.async.tsx","webpack://telegram-t/./src/components/middle/HeaderActions.tsx","webpack://telegram-t/./src/hooks/useWebpThumbnail.ts","webpack://telegram-t/./src/components/middle/PinnedMessageNavigation.tsx","webpack://telegram-t/./src/components/middle/HeaderPinnedMessage.tsx","webpack://telegram-t/./src/util/imageResize.ts","webpack://telegram-t/./src/hooks/useMessageMediaMetadata.ts","webpack://telegram-t/./src/hooks/useAsync.ts","webpack://telegram-t/./src/components/middle/AudioPlayer.tsx","webpack://telegram-t/./src/components/calls/group/GroupCallTopPane.tsx","webpack://telegram-t/./src/components/middle/MiddleHeader.tsx","webpack://telegram-t/./src/components/middle/helpers/groupMessages.ts","webpack://telegram-t/./src/components/middle/hooks/useMessageObservers.ts","webpack://telegram-t/./src/components/middle/message/helpers/buildContentClassName.ts","webpack://telegram-t/./src/components/middle/message/helpers/mediaDimensions.ts","webpack://telegram-t/./src/components/middle/message/helpers/calculateAlbumLayout.ts","webpack://telegram-t/./src/components/middle/message/helpers/calculateAuthorWidth.ts","webpack://telegram-t/./src/components/middle/message/hooks/useFocusMessage.ts","webpack://telegram-t/./src/components/middle/message/ContextMenuContainer.async.tsx","webpack://telegram-t/./src/components/middle/ActionMessage.tsx","webpack://telegram-t/./src/components/common/EmbeddedMessage.tsx","webpack://telegram-t/./src/components/middle/message/MessageMeta.tsx","webpack://telegram-t/./src/components/middle/message/Sticker.tsx","webpack://telegram-t/./src/components/middle/message/hooks/useBlurredMediaThumbRef.ts","webpack://telegram-t/./src/components/middle/message/helpers/getCustomAppendixBg.ts","webpack://telegram-t/./src/components/middle/message/Photo.tsx","webpack://telegram-t/./src/components/middle/message/hooks/useVideoAutoPause.ts","webpack://telegram-t/./src/components/middle/message/Video.tsx","webpack://telegram-t/./src/components/middle/message/Contact.tsx","webpack://telegram-t/./src/components/middle/message/PollOption.tsx","webpack://telegram-t/./src/components/middle/message/Poll.tsx","webpack://telegram-t/./src/components/middle/message/WebPage.tsx","webpack://telegram-t/./src/components/middle/message/Invoice.tsx","webpack://telegram-t/./src/components/middle/message/hocs/withSelectControl.tsx","webpack://telegram-t/./src/components/middle/message/Album.tsx","webpack://telegram-t/./src/components/middle/message/RoundVideo.tsx","webpack://telegram-t/./src/components/middle/message/InlineButtons.tsx","webpack://telegram-t/./src/components/middle/message/CommentButton.tsx","webpack://telegram-t/./src/components/middle/message/Message.tsx","webpack://telegram-t/./src/components/middle/message/hooks/useOuterHandlers.ts","webpack://telegram-t/./src/components/middle/message/hooks/useInnerHandlers.ts","webpack://telegram-t/./src/components/middle/message/SponsoredMessage.tsx","webpack://telegram-t/./src/components/middle/MessageListContent.tsx","webpack://telegram-t/./src/components/middle/hooks/useScrollHooks.ts","webpack://telegram-t/./src/components/middle/ContactGreeting.tsx","webpack://telegram-t/./src/components/middle/NoMessages.tsx","webpack://telegram-t/./src/components/middle/MessageList.tsx","webpack://telegram-t/./src/components/middle/hooks/useStickyDates.ts","webpack://telegram-t/./src/components/middle/ScrollDownButton.tsx","webpack://telegram-t/./src/components/middle/composer/helpers/buildAttachment.ts","webpack://telegram-t/./src/components/middle/composer/helpers/applyIosAutoCapitalizationFix.ts","webpack://telegram-t/./src/hooks/useInterval.ts","webpack://telegram-t/./src/util/voiceRecording.ts","webpack://telegram-t/./node_modules/opus-recorder/dist/encoderWorker.min.js","webpack://telegram-t/./src/components/middle/composer/hooks/useVoiceRecording.ts","webpack://telegram-t/./src/components/middle/composer/hooks/useClipboardPaste.ts","webpack://telegram-t/./src/components/middle/composer/helpers/getMessageTextAsHtml.ts","webpack://telegram-t/./src/components/middle/composer/hooks/useDraft.ts","webpack://telegram-t/./src/components/middle/composer/hooks/useInlineBotTooltip.ts","webpack://telegram-t/./src/components/middle/composer/hooks/useBotCommandTooltip.ts","webpack://telegram-t/./src/components/common/DeleteMessageModal.async.tsx","webpack://telegram-t/./src/components/ui/ResponsiveHoverButton.tsx","webpack://telegram-t/./src/components/middle/composer/AttachMenu.async.tsx","webpack://telegram-t/./src/components/middle/composer/SymbolMenu.async.tsx","webpack://telegram-t/./src/components/middle/composer/InlineBotTooltip.async.tsx","webpack://telegram-t/./src/components/middle/composer/MentionTooltip.async.tsx","webpack://telegram-t/./src/components/middle/composer/CustomSendMenu.async.tsx","webpack://telegram-t/./src/components/middle/composer/StickerTooltip.async.tsx","webpack://telegram-t/./src/components/middle/composer/BotCommandTooltip.async.tsx","webpack://telegram-t/./src/components/middle/composer/BotKeyboardMenu.tsx","webpack://telegram-t/./src/components/middle/composer/ComposerEmbeddedMessage.tsx","webpack://telegram-t/./src/components/middle/composer/AttachmentModal.async.tsx","webpack://telegram-t/./src/components/middle/composer/BotCommandMenu.async.tsx","webpack://telegram-t/./src/components/middle/composer/PollModal.async.tsx","webpack://telegram-t/./src/components/middle/composer/DropArea.async.tsx","webpack://telegram-t/./src/components/middle/composer/WebPagePreview.tsx","webpack://telegram-t/./src/components/common/CalendarModal.async.tsx","webpack://telegram-t/./src/components/middle/composer/SendAsMenu.async.tsx","webpack://telegram-t/./src/components/middle/composer/Composer.tsx","webpack://telegram-t/./src/components/middle/composer/hooks/useStickerTooltip.ts","webpack://telegram-t/./src/util/insertHtmlInSelection.ts","webpack://telegram-t/./src/util/deleteLastCharacterOutsideSelection.ts","webpack://telegram-t/./src/components/middle/composer/hooks/useEditing.ts","webpack://telegram-t/./src/components/middle/MobileSearch.async.tsx","webpack://telegram-t/./src/components/middle/MessageSelectToolbar.async.tsx","webpack://telegram-t/./src/components/common/UnpinAllMessagesModal.async.tsx","webpack://telegram-t/./src/components/payment/PaymentModal.async.tsx","webpack://telegram-t/./src/components/payment/ReceiptModal.async.tsx","webpack://telegram-t/./src/components/common/SeenByModal.async.tsx","webpack://telegram-t/./src/components/middle/MiddleColumn.tsx","webpack://telegram-t/./src/components/right/RightHeader.tsx","webpack://telegram-t/./src/components/right/hooks/useProfileViewportIds.ts","webpack://telegram-t/./src/components/right/hooks/useProfileState.ts","webpack://telegram-t/./src/components/right/Profile.tsx","webpack://telegram-t/./src/components/right/hooks/useTransitionFixes.ts","webpack://telegram-t/./src/hooks/useCacheBuster.ts","webpack://telegram-t/./src/components/right/RightSearch.async.tsx","webpack://telegram-t/./src/components/right/management/Management.async.tsx","webpack://telegram-t/./src/components/right/StickerSearch.async.tsx","webpack://telegram-t/./src/components/right/GifSearch.async.tsx","webpack://telegram-t/./src/components/right/PollResults.async.tsx","webpack://telegram-t/./src/components/right/AddChatMembers.tsx","webpack://telegram-t/./src/components/right/RightColumn.tsx","webpack://telegram-t/./src/components/mediaViewer/MediaViewer.async.tsx","webpack://telegram-t/./src/util/download.ts","webpack://telegram-t/./src/components/main/DownloadManager.tsx","webpack://telegram-t/./src/components/main/Notifications.async.tsx","webpack://telegram-t/./src/components/main/Dialogs.async.tsx","webpack://telegram-t/./src/components/main/ForwardPicker.async.tsx","webpack://telegram-t/./src/components/main/SafeLinkModal.async.tsx","webpack://telegram-t/./src/components/main/HistoryCalendar.async.tsx","webpack://telegram-t/./src/components/calls/group/GroupCall.async.tsx","webpack://telegram-t/./src/components/calls/ActiveCallHeader.async.tsx","webpack://telegram-t/./src/components/calls/CallFallbackConfirm.async.tsx","webpack://telegram-t/./src/components/main/Main.tsx","webpack://telegram-t/./src/bundles/main.ts"],"sourcesContent":["import { addReducer } from '../../../lib/teact/teactn';\n\nimport {\n updateLocalTextSearch,\n replaceLocalTextSearchResults,\n updateLocalMediaSearchType,\n} from '../../reducers';\nimport { MEMO_EMPTY_ARRAY } from '../../../util/memo';\nimport { selectCurrentMessageList } from '../../selectors';\nimport { buildChatThreadKey } from '../../helpers';\nimport { GlobalState } from '../../../global/types';\n\naddReducer('openLocalTextSearch', (global) => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n return updateLocalTextSearch(global, chatId, threadId, true);\n});\n\naddReducer('closeLocalTextSearch', closeLocalTextSearch);\n\naddReducer('setLocalTextSearchQuery', (global, actions, payload) => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n const { query } = payload!;\n const chatThreadKey = buildChatThreadKey(chatId, threadId);\n const { query: currentQuery } = global.localTextSearch.byChatThreadKey[chatThreadKey] || {};\n\n if (query !== currentQuery) {\n global = replaceLocalTextSearchResults(global, chatId, threadId, MEMO_EMPTY_ARRAY);\n }\n\n global = updateLocalTextSearch(global, chatId, threadId, true, query);\n\n return global;\n});\n\naddReducer('setLocalMediaSearchType', (global, actions, payload) => {\n const { chatId } = selectCurrentMessageList(global) || {};\n if (!chatId) {\n return undefined;\n }\n\n const { mediaType } = payload!;\n return updateLocalMediaSearchType(global, chatId, mediaType);\n});\n\nexport function closeLocalTextSearch(global: GlobalState): GlobalState {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return global;\n }\n\n global = updateLocalTextSearch(global, chatId, threadId, false);\n global = replaceLocalTextSearchResults(global, chatId, threadId, undefined);\n return global;\n}\n","import { addReducer, setGlobal } from '../../../lib/teact/teactn';\n\nimport {\n exitMessageSelectMode, replaceThreadParam, updateCurrentMessageList,\n} from '../../reducers';\nimport { selectCurrentMessageList } from '../../selectors';\nimport { closeLocalTextSearch } from './localSearch';\n\naddReducer('openChat', (global, actions, payload) => {\n const {\n id, threadId = -1, type = 'thread', shouldReplaceHistory = false,\n } = payload!;\n\n const currentMessageList = selectCurrentMessageList(global);\n\n if (!currentMessageList\n || (\n currentMessageList.chatId !== id\n || currentMessageList.threadId !== threadId\n || currentMessageList.type !== type\n )) {\n global = replaceThreadParam(global, id, threadId, 'replyStack', []);\n global = exitMessageSelectMode(global);\n global = closeLocalTextSearch(global);\n\n global = {\n ...global,\n messages: {\n ...global.messages,\n contentToBeScheduled: undefined,\n },\n ...(id !== global.forwardMessages.toChatId && {\n forwardMessages: {},\n }),\n };\n\n setGlobal(global);\n }\n\n return updateCurrentMessageList(global, id, threadId, type, shouldReplaceHistory);\n});\n\naddReducer('openPreviousChat', (global) => {\n return updateCurrentMessageList(global, undefined);\n});\n\naddReducer('openChatWithInfo', (global, actions, payload) => {\n setGlobal({\n ...global,\n isChatInfoShown: true,\n });\n\n actions.openChat(payload);\n});\n\naddReducer('resetChatCreation', (global) => {\n return {\n ...global,\n chatCreation: undefined,\n };\n});\n\naddReducer('setNewChatMembersDialogState', (global, actions, payload) => {\n return {\n ...global,\n newChatMembersProgress: payload,\n };\n});\n\naddReducer('openNextChat', (global, actions, payload) => {\n const { targetIndexDelta, orderedIds } = payload;\n\n const { chatId } = selectCurrentMessageList(global) || {};\n\n if (!chatId) {\n actions.openChat({ id: orderedIds[0] });\n return;\n }\n\n const position = orderedIds.indexOf(chatId);\n\n if (position === -1) {\n return;\n }\n const nextId = orderedIds[position + targetIndexDelta];\n\n actions.openChat({ id: nextId, shouldReplaceHistory: true });\n});\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiMessage, MAIN_THREAD_ID } from '../../../api/types';\nimport { FocusDirection } from '../../../types';\n\nimport {\n ANIMATION_END_DELAY,\n APP_VERSION,\n FAST_SMOOTH_MAX_DURATION,\n SERVICE_NOTIFICATIONS_USER_ID,\n} from '../../../config';\nimport { IS_TOUCH_ENV } from '../../../util/environment';\nimport {\n enterMessageSelectMode,\n toggleMessageSelection,\n exitMessageSelectMode,\n replaceThreadParam,\n updateFocusDirection,\n updateFocusedMessage,\n} from '../../reducers';\nimport {\n selectCurrentChat,\n selectViewportIds,\n selectIsRightColumnShown,\n selectCurrentMessageList,\n selectChat,\n selectThreadInfo,\n selectChatMessages,\n selectAllowedMessageActions,\n selectMessageIdsByGroupId,\n selectForwardedMessageIdsByGroupId,\n selectIsViewportNewest,\n selectReplyingToId,\n selectReplyStack,\n} from '../../selectors';\nimport { findLast } from '../../../util/iteratees';\nimport { getServerTime } from '../../../util/serverTime';\n\n// @ts-ignore\nimport versionNotification from '../../../versionNotification.txt';\nimport parseMessageInput from '../../../util/parseMessageInput';\n\nconst FOCUS_DURATION = 1500;\nconst FOCUS_NO_HIGHLIGHT_DURATION = FAST_SMOOTH_MAX_DURATION + ANIMATION_END_DELAY;\nconst POLL_RESULT_OPEN_DELAY_MS = 450;\nconst SERVICE_NOTIFICATIONS_MAX_AMOUNT = 1e3;\n\nlet blurTimeout: number | undefined;\n\naddReducer('setScrollOffset', (global, actions, payload) => {\n const { chatId, threadId, scrollOffset } = payload!;\n\n return replaceThreadParam(global, chatId, threadId, 'scrollOffset', scrollOffset);\n});\n\naddReducer('setReplyingToId', (global, actions, payload) => {\n const { messageId } = payload!;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return undefined;\n }\n const { chatId, threadId } = currentMessageList;\n\n return replaceThreadParam(global, chatId, threadId, 'replyingToId', messageId);\n});\n\naddReducer('setEditingId', (global, actions, payload) => {\n const { messageId } = payload!;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return undefined;\n }\n\n const { chatId, threadId, type } = currentMessageList;\n const paramName = type === 'scheduled' ? 'editingScheduledId' : 'editingId';\n\n return replaceThreadParam(global, chatId, threadId, paramName, messageId);\n});\n\naddReducer('editLastMessage', (global) => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return undefined;\n }\n\n const chatMessages = selectChatMessages(global, chatId);\n const viewportIds = selectViewportIds(global, chatId, threadId);\n if (!chatMessages || !viewportIds) {\n return undefined;\n }\n\n const lastOwnEditableMessageId = findLast(viewportIds, (id) => {\n return Boolean(chatMessages[id] && selectAllowedMessageActions(global, chatMessages[id], threadId).canEdit);\n });\n\n if (!lastOwnEditableMessageId) {\n return undefined;\n }\n\n return replaceThreadParam(global, chatId, threadId, 'editingId', lastOwnEditableMessageId);\n});\n\naddReducer('replyToNextMessage', (global, actions, payload) => {\n const { targetIndexDelta } = payload;\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId) {\n return;\n }\n\n const chatMessages = selectChatMessages(global, chatId);\n const viewportIds = selectViewportIds(global, chatId, threadId);\n if (!chatMessages || !viewportIds) {\n return;\n }\n\n const replyingToId = selectReplyingToId(global, chatId, threadId);\n const isLatest = selectIsViewportNewest(global, chatId, threadId);\n\n let messageId: number | undefined;\n\n if (!isLatest || !replyingToId) {\n if (threadId === MAIN_THREAD_ID) {\n const chat = selectChat(global, chatId);\n\n messageId = chat?.lastMessage?.id;\n } else {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n\n messageId = threadInfo?.lastMessageId;\n }\n } else {\n const chatMessageKeys = Object.keys(chatMessages);\n const indexOfCurrent = chatMessageKeys.indexOf(replyingToId.toString());\n const newIndex = indexOfCurrent + targetIndexDelta;\n messageId = newIndex <= chatMessageKeys.length + 1 && newIndex >= 0\n ? Number(chatMessageKeys[newIndex])\n : undefined;\n }\n actions.setReplyingToId({ messageId });\n actions.focusMessage({\n chatId, threadId, messageId,\n });\n});\n\naddReducer('openMediaViewer', (global, actions, payload) => {\n const {\n chatId, threadId, messageId, avatarOwnerId, profilePhotoIndex, origin,\n } = payload!;\n\n return {\n ...global,\n mediaViewer: {\n chatId,\n threadId,\n messageId,\n avatarOwnerId,\n profilePhotoIndex,\n origin,\n },\n forwardMessages: {},\n };\n});\n\naddReducer('closeMediaViewer', (global) => {\n return {\n ...global,\n mediaViewer: {},\n };\n});\n\naddReducer('openAudioPlayer', (global, actions, payload) => {\n const {\n chatId, threadId, messageId, origin, volume, playbackRate, isMuted,\n } = payload!;\n\n return {\n ...global,\n audioPlayer: {\n chatId,\n threadId,\n messageId,\n origin: origin ?? global.audioPlayer.origin,\n volume: volume ?? global.audioPlayer.volume,\n playbackRate: playbackRate || global.audioPlayer.playbackRate,\n isMuted: isMuted || global.audioPlayer.isMuted,\n },\n };\n});\n\naddReducer('setAudioPlayerVolume', (global, actions, payload) => {\n const {\n volume,\n } = payload!;\n\n return {\n ...global,\n audioPlayer: {\n ...global.audioPlayer,\n volume,\n },\n };\n});\n\naddReducer('setAudioPlayerPlaybackRate', (global, actions, payload) => {\n const {\n playbackRate,\n } = payload!;\n\n return {\n ...global,\n audioPlayer: {\n ...global.audioPlayer,\n playbackRate,\n },\n };\n});\n\naddReducer('setAudioPlayerMuted', (global, actions, payload) => {\n const {\n isMuted,\n } = payload!;\n\n return {\n ...global,\n audioPlayer: {\n ...global.audioPlayer,\n isMuted,\n },\n };\n});\n\naddReducer('setAudioPlayerOrigin', (global, actions, payload) => {\n const {\n origin,\n } = payload!;\n\n return {\n ...global,\n audioPlayer: {\n ...global.audioPlayer,\n origin,\n },\n };\n});\n\naddReducer('closeAudioPlayer', (global) => {\n return {\n ...global,\n audioPlayer: {\n volume: global.audioPlayer.volume,\n playbackRate: global.audioPlayer.playbackRate,\n isMuted: global.audioPlayer.isMuted,\n },\n };\n});\n\naddReducer('openPollResults', (global, actions, payload) => {\n const { chatId, messageId } = payload!;\n\n const shouldOpenInstantly = selectIsRightColumnShown(global);\n\n if (!shouldOpenInstantly) {\n window.setTimeout(() => {\n const newGlobal = getGlobal();\n\n setGlobal({\n ...newGlobal,\n pollResults: {\n chatId,\n messageId,\n voters: {},\n },\n });\n }, POLL_RESULT_OPEN_DELAY_MS);\n } else if (chatId !== global.pollResults.chatId || messageId !== global.pollResults.messageId) {\n setGlobal({\n ...global,\n pollResults: {\n chatId,\n messageId,\n voters: {},\n },\n });\n }\n});\n\naddReducer('closePollResults', (global) => {\n setGlobal({\n ...global,\n pollResults: {},\n });\n});\n\naddReducer('focusLastMessage', (global, actions) => {\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n\n const { chatId, threadId } = currentMessageList;\n\n let lastMessageId: number | undefined;\n if (threadId === MAIN_THREAD_ID) {\n const chat = selectChat(global, chatId);\n\n lastMessageId = chat?.lastMessage?.id;\n } else {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n\n lastMessageId = threadInfo?.lastMessageId;\n }\n\n if (!lastMessageId) {\n return;\n }\n\n actions.focusMessage({\n chatId, threadId, messageId: lastMessageId, noHighlight: true,\n });\n});\n\naddReducer('focusNextReply', (global, actions) => {\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return undefined;\n }\n\n const { chatId, threadId } = currentMessageList;\n\n const replyStack = selectReplyStack(global, chatId, threadId);\n\n if (!replyStack || replyStack.length === 0) {\n actions.focusLastMessage();\n } else {\n const messageId = replyStack.pop();\n\n global = replaceThreadParam(global, chatId, threadId, 'replyStack', [...replyStack]);\n\n setGlobal(global);\n\n actions.focusMessage({\n chatId,\n threadId,\n messageId,\n });\n }\n\n return undefined;\n});\n\naddReducer('focusMessage', (global, actions, payload) => {\n const {\n chatId, threadId = MAIN_THREAD_ID, messageListType = 'thread', noHighlight, groupedId, groupedChatId,\n replyMessageId, isResizingContainer,\n } = payload!;\n\n let { messageId } = payload!;\n\n if (groupedId !== undefined) {\n const ids = selectForwardedMessageIdsByGroupId(global, groupedChatId, groupedId);\n if (ids?.length) {\n ([messageId] = ids);\n }\n }\n\n const currentMessageList = selectCurrentMessageList(global);\n const shouldSwitchChat = !currentMessageList || (\n chatId !== currentMessageList.chatId\n || threadId !== currentMessageList.threadId\n || messageListType !== currentMessageList.type\n );\n\n if (blurTimeout) {\n clearTimeout(blurTimeout);\n blurTimeout = undefined;\n }\n blurTimeout = window.setTimeout(() => {\n let newGlobal = getGlobal();\n newGlobal = updateFocusedMessage(newGlobal);\n newGlobal = updateFocusDirection(newGlobal);\n setGlobal(newGlobal);\n }, noHighlight ? FOCUS_NO_HIGHLIGHT_DURATION : FOCUS_DURATION);\n\n global = updateFocusedMessage(global, chatId, messageId, noHighlight, isResizingContainer);\n global = updateFocusDirection(global, undefined);\n\n if (replyMessageId) {\n const replyStack = selectReplyStack(global, chatId, threadId) || [];\n global = replaceThreadParam(global, chatId, threadId, 'replyStack', [...replyStack, replyMessageId]);\n }\n\n if (shouldSwitchChat) {\n global = updateFocusDirection(global, FocusDirection.Static);\n }\n\n const viewportIds = selectViewportIds(global, chatId, threadId);\n if (viewportIds && viewportIds.includes(messageId)) {\n setGlobal(global);\n actions.openChat({ id: chatId, threadId });\n return undefined;\n }\n\n if (shouldSwitchChat) {\n global = replaceThreadParam(global, chatId, threadId, 'viewportIds', undefined);\n }\n\n global = replaceThreadParam(global, chatId, threadId, 'outlyingIds', undefined);\n\n if (viewportIds && !shouldSwitchChat) {\n const direction = messageId > viewportIds[0] ? FocusDirection.Down : FocusDirection.Up;\n global = updateFocusDirection(global, direction);\n }\n\n setGlobal(global);\n\n actions.openChat({ id: chatId, threadId });\n actions.loadViewportMessages();\n return undefined;\n});\n\naddReducer('openForwardMenu', (global, actions, payload) => {\n const { fromChatId, messageIds, groupedId } = payload!;\n let groupedMessageIds;\n if (groupedId) {\n groupedMessageIds = selectMessageIdsByGroupId(global, fromChatId, groupedId);\n }\n return {\n ...global,\n forwardMessages: {\n fromChatId,\n messageIds: groupedMessageIds || messageIds,\n isModalShown: true,\n },\n };\n});\n\naddReducer('exitForwardMode', (global) => {\n setGlobal({\n ...global,\n forwardMessages: {},\n });\n});\n\naddReducer('setForwardChatId', (global, actions, payload) => {\n const { id } = payload!;\n\n setGlobal({\n ...global,\n forwardMessages: {\n ...global.forwardMessages,\n toChatId: id,\n isModalShown: false,\n },\n });\n\n actions.openChat({ id });\n actions.closeMediaViewer();\n actions.exitMessageSelectMode();\n});\n\naddReducer('openForwardMenuForSelectedMessages', (global, actions) => {\n if (!global.selectedMessages) {\n return;\n }\n\n const { chatId: fromChatId, messageIds } = global.selectedMessages;\n\n actions.openForwardMenu({ fromChatId, messageIds });\n});\n\naddReducer('cancelMessageMediaDownload', (global, actions, payload) => {\n const { message } = payload!;\n\n const byChatId = global.activeDownloads.byChatId[message.chatId];\n if (!byChatId || !byChatId.length) return;\n\n setGlobal({\n ...global,\n activeDownloads: {\n byChatId: {\n ...global.activeDownloads.byChatId,\n [message.chatId]: byChatId.filter((id) => id !== message.id),\n },\n },\n });\n});\n\naddReducer('downloadMessageMedia', (global, actions, payload) => {\n const { message } = payload!;\n if (!message) return;\n\n setGlobal({\n ...global,\n activeDownloads: {\n byChatId: {\n ...global.activeDownloads.byChatId,\n [message.chatId]: [...(global.activeDownloads.byChatId[message.chatId] || []), message.id],\n },\n },\n });\n});\n\naddReducer('downloadSelectedMessages', (global, actions) => {\n if (!global.selectedMessages) {\n return;\n }\n\n const { chatId, messageIds } = global.selectedMessages;\n const { threadId } = selectCurrentMessageList(global) || {};\n\n const chatMessages = selectChatMessages(global, chatId);\n if (!chatMessages || !threadId) return;\n const messages = messageIds.map((id) => chatMessages[id])\n .filter((message) => selectAllowedMessageActions(global, message, threadId).canDownload);\n messages.forEach((message) => actions.downloadMessageMedia({ message }));\n});\n\naddReducer('enterMessageSelectMode', (global, actions, payload) => {\n const { messageId } = payload || {};\n const openChat = selectCurrentChat(global);\n if (!openChat) {\n return global;\n }\n\n return enterMessageSelectMode(global, openChat.id, messageId);\n});\n\naddReducer('toggleMessageSelection', (global, actions, payload) => {\n const {\n messageId,\n groupedId,\n childMessageIds,\n withShift,\n } = payload!;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n\n const { chatId, threadId, type: messageListType } = currentMessageList;\n\n global = toggleMessageSelection(\n global, chatId, threadId, messageListType, messageId, groupedId, childMessageIds, withShift,\n );\n\n setGlobal(global);\n\n if (global.shouldShowContextMenuHint) {\n actions.disableContextMenuHint();\n actions.showNotification({\n // eslint-disable-next-line max-len\n message: `To **edit** or **reply**, close this menu. Then ${IS_TOUCH_ENV ? 'long tap' : 'right click'} on a message.`,\n });\n }\n});\n\naddReducer('disableContextMenuHint', (global) => {\n if (!global.shouldShowContextMenuHint) {\n return undefined;\n }\n\n return {\n ...global,\n shouldShowContextMenuHint: false,\n };\n});\n\naddReducer('exitMessageSelectMode', exitMessageSelectMode);\n\naddReducer('openPollModal', (global) => {\n return {\n ...global,\n isPollModalOpen: true,\n };\n});\n\naddReducer('closePollModal', (global) => {\n return {\n ...global,\n isPollModalOpen: false,\n };\n});\n\naddReducer('checkVersionNotification', (global, actions) => {\n const currentVersion = APP_VERSION.split('.').slice(0, 2).join('.');\n const { serviceNotifications } = global;\n\n if (serviceNotifications.find(({ version }) => version === currentVersion)) {\n return;\n }\n\n const message: Omit = {\n chatId: SERVICE_NOTIFICATIONS_USER_ID,\n date: getServerTime(global.serverTimeOffset),\n content: {\n text: parseMessageInput(versionNotification),\n },\n isOutgoing: false,\n };\n\n actions.createServiceNotification({\n message,\n version: currentVersion,\n });\n});\n\naddReducer('createServiceNotification', (global, actions, payload) => {\n const { message, version } = payload;\n const { serviceNotifications } = global;\n const serviceChat = selectChat(global, SERVICE_NOTIFICATIONS_USER_ID)!;\n\n const maxId = Math.max(\n serviceChat.lastMessage?.id || 0,\n ...serviceNotifications.map(({ id }) => id),\n );\n const fractionalPart = (serviceNotifications.length + 1) / SERVICE_NOTIFICATIONS_MAX_AMOUNT;\n // The fractional ID is made of the largest integer ID and an incremented fractional part\n const id = Math.floor(maxId) + fractionalPart;\n\n message.id = id;\n\n const serviceNotification = {\n id,\n message,\n version,\n isUnread: true,\n };\n\n setGlobal({\n ...global,\n serviceNotifications: [\n ...serviceNotifications.slice(-SERVICE_NOTIFICATIONS_MAX_AMOUNT),\n serviceNotification,\n ],\n });\n\n actions.apiUpdate({\n '@type': 'newMessage',\n id: message.id,\n chatId: message.chatId,\n message,\n });\n});\n\naddReducer('openSeenByModal', (global, actions, payload) => {\n const { chatId, messageId } = payload!;\n\n return {\n ...global,\n seenByModal: { chatId, messageId },\n };\n});\n\naddReducer('closeSeenByModal', (global) => {\n return {\n ...global,\n seenByModal: undefined,\n };\n});\n","export default \"**Telegram Web Z was updated to version 1.28**\\n\\n👏 **Harder**\\n• Support for join requests in groups and channels.\\n• Support for more service messages.\\n\\n🤩 **Better**\\n• Easier to select and adjust left column width.\\n• Redundant single quotes removed in Spanish and French translations.\\n• Support for hotkeys on non-qwerty keyboards.\\n• Use Ctrl+Shift+F or Ctrl+F (in PWA mode) to open global or local search.\\n• Chat: \\\"Add to folder...\\\" only appears for users with folders.\\n• Support for `start` parameter in `tg://resolve` links.\\n\\n💪 **Stronger**\\n• Fixed focusing on messages in a chat that was previously open.\\n• Fixed missing stickers in sticker suggestions.\\n• Fixed opening chats from user mentions.\\n• Fixed various glitches when appearing as a channel in public groups.\\n• Removed redundant download and forward options in chats with protected content.\\n\";","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { updateGlobalSearch, updateGlobalSearchContent } from '../../reducers';\n\nconst MAX_RECENTLY_FOUND_IDS = 10;\n\naddReducer('setGlobalSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n const { chatId } = global.globalSearch;\n\n return updateGlobalSearch(global, {\n globalResults: {},\n localResults: {},\n resultsByType: undefined,\n ...(query ? { fetchingStatus: { chats: !chatId, messages: true } } : { fetchingStatus: undefined }),\n query,\n });\n});\n\naddReducer('addRecentlyFoundChatId', (global, actions, payload) => {\n const { id } = payload!;\n const { recentlyFoundChatIds } = global.globalSearch;\n\n if (!recentlyFoundChatIds) {\n return updateGlobalSearch(global, { recentlyFoundChatIds: [id] });\n }\n\n const newRecentIds = recentlyFoundChatIds.filter((chatId) => chatId !== id);\n newRecentIds.unshift(id);\n if (newRecentIds.length > MAX_RECENTLY_FOUND_IDS) {\n newRecentIds.pop();\n }\n\n return updateGlobalSearch(global, { recentlyFoundChatIds: newRecentIds });\n});\n\naddReducer('clearRecentlyFoundChats', (global) => {\n return updateGlobalSearch(global, { recentlyFoundChatIds: undefined });\n});\n\naddReducer('setGlobalSearchContent', (global, actions, payload) => {\n const { content } = payload!;\n\n return updateGlobalSearchContent(global, content);\n});\n\naddReducer('setGlobalSearchChatId', (global, actions, payload) => {\n const { id } = payload!;\n\n return updateGlobalSearch(global, { chatId: id, query: undefined, resultsByType: undefined });\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\naddReducer('setStickerSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n search: {\n query,\n resultIds: undefined,\n },\n },\n };\n});\n\naddReducer('setGifSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n\n return {\n ...global,\n gifs: {\n ...global.gifs,\n search: {\n query,\n offsetId: undefined,\n results: undefined,\n },\n },\n };\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\n\nimport { updateSelectedUserId, updateUserSearch } from '../../reducers';\n\naddReducer('openUserInfo', (global, actions, payload) => {\n const { id } = payload!;\n\n actions.openChat({ id });\n});\n\nconst clearSelectedUserId = (global: GlobalState) => updateSelectedUserId(global, undefined);\n\naddReducer('openChat', clearSelectedUserId);\n\naddReducer('setUserSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n\n return updateUserSearch(global, {\n globalUserIds: undefined,\n localUserIds: undefined,\n fetchingStatus: Boolean(query),\n query,\n });\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\nimport { ApiError } from '../../../api/types';\n\nimport { IS_SINGLE_COLUMN_LAYOUT, IS_TABLET_COLUMN_LAYOUT } from '../../../util/environment';\nimport getReadableErrorText from '../../../util/getReadableErrorText';\nimport { selectCurrentMessageList } from '../../selectors';\nimport generateIdFor from '../../../util/generateIdFor';\n\nconst MAX_STORED_EMOJIS = 18; // Represents two rows of recent emojis\n\naddReducer('toggleChatInfo', (global) => {\n return {\n ...global,\n isChatInfoShown: !global.isChatInfoShown,\n };\n});\n\naddReducer('setLeftColumnWidth', (global, actions, payload) => {\n const leftColumnWidth = payload;\n\n return {\n ...global,\n leftColumnWidth,\n };\n});\n\naddReducer('resetLeftColumnWidth', (global) => {\n return {\n ...global,\n leftColumnWidth: undefined,\n };\n});\n\naddReducer('toggleManagement', (global): GlobalState | undefined => {\n const { chatId } = selectCurrentMessageList(global) || {};\n\n if (!chatId) {\n return undefined;\n }\n\n return {\n ...global,\n management: {\n byChatId: {\n ...global.management.byChatId,\n [chatId]: {\n ...global.management.byChatId[chatId],\n isActive: !(global.management.byChatId[chatId] || {}).isActive,\n },\n },\n },\n };\n});\n\naddReducer('closeManagement', (global): GlobalState | undefined => {\n const { chatId } = selectCurrentMessageList(global) || {};\n\n if (!chatId) {\n return undefined;\n }\n\n return {\n ...global,\n management: {\n byChatId: {\n ...global.management.byChatId,\n [chatId]: {\n ...global.management.byChatId[chatId],\n isActive: false,\n },\n },\n },\n };\n});\n\naddReducer('openChat', (global) => {\n if (!IS_SINGLE_COLUMN_LAYOUT && !IS_TABLET_COLUMN_LAYOUT) {\n return undefined;\n }\n\n return {\n ...global,\n isLeftColumnShown: global.messages.messageLists.length === 0,\n };\n});\n\naddReducer('toggleLeftColumn', (global) => {\n return {\n ...global,\n isLeftColumnShown: !global.isLeftColumnShown,\n };\n});\n\naddReducer('addRecentEmoji', (global, action, payload) => {\n const { emoji } = payload!;\n const { recentEmojis } = global;\n if (!recentEmojis) {\n return {\n ...global,\n recentEmojis: [emoji],\n };\n }\n\n const newEmojis = recentEmojis.filter((e) => e !== emoji);\n newEmojis.unshift(emoji);\n if (newEmojis.length > MAX_STORED_EMOJIS) {\n newEmojis.pop();\n }\n\n return {\n ...global,\n recentEmojis: newEmojis,\n };\n});\n\naddReducer('addRecentSticker', (global, action, payload) => {\n const { sticker } = payload!;\n const { recent } = global.stickers;\n if (!recent) {\n return {\n ...global,\n stickers: {\n ...global.stickers,\n recent: {\n hash: '0',\n stickers: [sticker],\n },\n },\n };\n }\n\n const newStickers = recent.stickers.filter((s) => s.id !== sticker.id);\n newStickers.unshift(sticker);\n\n return {\n ...global,\n stickers: {\n ...global.stickers,\n recent: {\n ...recent,\n stickers: newStickers,\n },\n },\n };\n});\n\naddReducer('showNotification', (global, actions, payload) => {\n const notification = payload!;\n notification.localId = generateIdFor({});\n\n const newNotifications = [...global.notifications];\n const existingNotificationIndex = newNotifications.findIndex((n) => n.message === notification.message);\n if (existingNotificationIndex !== -1) {\n newNotifications.splice(existingNotificationIndex, 1);\n }\n\n newNotifications.push(notification);\n\n return {\n ...global,\n notifications: newNotifications,\n };\n});\n\naddReducer('dismissNotification', (global, actions, payload) => {\n const newNotifications = global.notifications.filter(({ localId }) => localId !== payload.localId);\n\n return {\n ...global,\n notifications: newNotifications,\n };\n});\n\naddReducer('showDialog', (global, actions, payload) => {\n const { data } = payload!;\n\n // Filter out errors that we don't want to show to the user\n if ('message' in data && data.hasErrorKey && !getReadableErrorText(data)) {\n return global;\n }\n\n const newDialogs = [...global.dialogs];\n if ('message' in data) {\n const existingErrorIndex = newDialogs.findIndex((err) => (err as ApiError).message === data.message);\n if (existingErrorIndex !== -1) {\n newDialogs.splice(existingErrorIndex, 1);\n }\n }\n\n newDialogs.push(data);\n\n return {\n ...global,\n dialogs: newDialogs,\n };\n});\n\naddReducer('dismissDialog', (global) => {\n const newDialogs = [...global.dialogs];\n\n newDialogs.pop();\n\n return {\n ...global,\n dialogs: newDialogs,\n };\n});\n\naddReducer('toggleSafeLinkModal', (global, actions, payload) => {\n const { url: safeLinkModalUrl } = payload;\n\n return {\n ...global,\n safeLinkModalUrl,\n };\n});\n\naddReducer('openHistoryCalendar', (global, actions, payload) => {\n const { selectedAt } = payload;\n\n return {\n ...global,\n historyCalendarSelectedAt: selectedAt,\n };\n});\n\naddReducer('closeHistoryCalendar', (global) => {\n return {\n ...global,\n historyCalendarSelectedAt: undefined,\n };\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { clearPayment, closeInvoice } from '../../reducers';\n\naddReducer('openPaymentModal', (global, actions, payload) => {\n const { chatId, messageId } = payload;\n return {\n ...global,\n payment: {\n ...global.payment,\n chatId,\n messageId,\n isPaymentModalOpen: true,\n },\n };\n});\n\naddReducer('closePaymentModal', (global) => {\n const newGlobal = clearPayment(global);\n return closeInvoice(newGlobal);\n});\n\naddReducer('addPaymentError', (global, actions, payload) => {\n const { error } = payload!;\n\n return {\n ...global,\n payment: {\n ...global.payment,\n error,\n },\n };\n});\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalActions } from '../../../global/types';\nimport {\n ApiAttachment,\n ApiChat,\n ApiMessage,\n ApiMessageEntity,\n ApiNewPoll,\n ApiOnProgress,\n ApiSticker,\n ApiUser,\n ApiVideo,\n MAIN_THREAD_ID,\n MESSAGE_DELETED,\n} from '../../../api/types';\nimport { LoadMoreDirection } from '../../../types';\n\nimport { MAX_MEDIA_FILES_FOR_ALBUM, MESSAGE_LIST_SLICE, SERVICE_NOTIFICATIONS_USER_ID } from '../../../config';\nimport { IS_IOS } from '../../../util/environment';\nimport { callApi, cancelApiProgress } from '../../../api/gramjs';\nimport {\n areSortedArraysIntersecting, buildCollectionByKey, split, unique,\n} from '../../../util/iteratees';\nimport {\n addUsers,\n addChatMessagesById,\n replaceThreadParam,\n safeReplaceViewportIds,\n updateChatMessage,\n addChats,\n updateListedIds,\n updateOutlyingIds,\n replaceScheduledMessages,\n updateThreadInfos,\n updateChat,\n updateThreadUnreadFromForwardedMessage,\n updateSponsoredMessage,\n} from '../../reducers';\nimport {\n selectChat,\n selectChatMessage,\n selectCurrentMessageList,\n selectFocusedMessageId,\n selectCurrentChat,\n selectListedIds,\n selectOutlyingIds,\n selectViewportIds,\n selectRealLastReadId,\n selectReplyingToId,\n selectEditingId,\n selectDraft,\n selectThreadOriginChat,\n selectThreadTopMessageId,\n selectEditingScheduledId,\n selectEditingMessage,\n selectScheduledMessage,\n selectNoWebPage,\n selectFirstUnreadId,\n selectUser,\n selectSendAs,\n selectSponsoredMessage,\n} from '../../selectors';\nimport { debounce, rafPromise } from '../../../util/schedulers';\nimport { isServiceNotificationMessage } from '../../helpers';\n\nconst uploadProgressCallbacks = new Map();\n\nconst runDebouncedForMarkRead = debounce((cb) => cb(), 500, false);\n\naddReducer('loadViewportMessages', (global, actions, payload) => {\n const {\n direction = LoadMoreDirection.Around,\n isBudgetPreload = false,\n } = payload || {};\n\n let { chatId, threadId } = payload || {};\n\n if (!chatId) {\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return undefined;\n }\n\n chatId = currentMessageList.chatId;\n threadId = currentMessageList.threadId;\n }\n\n const chat = selectChat(global, chatId);\n // TODO Revise if `chat.isRestricted` check is needed\n if (!chat || chat.isRestricted) {\n return undefined;\n }\n\n const viewportIds = selectViewportIds(global, chatId, threadId);\n const listedIds = selectListedIds(global, chatId, threadId);\n const outlyingIds = selectOutlyingIds(global, chatId, threadId);\n\n if (!viewportIds || !viewportIds.length || direction === LoadMoreDirection.Around) {\n const offsetId = selectFocusedMessageId(global, chatId) || selectRealLastReadId(global, chatId, threadId);\n const isOutlying = Boolean(offsetId && listedIds && !listedIds.includes(offsetId));\n const historyIds = (isOutlying ? outlyingIds : listedIds) || [];\n const {\n newViewportIds, areSomeLocal, areAllLocal,\n } = getViewportSlice(historyIds, offsetId, LoadMoreDirection.Around);\n\n if (areSomeLocal && newViewportIds.length >= MESSAGE_LIST_SLICE) {\n global = safeReplaceViewportIds(global, chatId, threadId, newViewportIds);\n }\n\n if (!areAllLocal) {\n void loadViewportMessages(chat, threadId, offsetId, LoadMoreDirection.Around, isOutlying, isBudgetPreload);\n }\n } else {\n const offsetId = direction === LoadMoreDirection.Backwards ? viewportIds[0] : viewportIds[viewportIds.length - 1];\n const isOutlying = Boolean(outlyingIds);\n const historyIds = (isOutlying ? outlyingIds : listedIds)!;\n const {\n newViewportIds, areSomeLocal, areAllLocal,\n } = getViewportSlice(historyIds, offsetId, direction);\n\n if (areSomeLocal) {\n global = safeReplaceViewportIds(global, chatId, threadId, newViewportIds);\n }\n\n void loadWithBudget(actions, areAllLocal, isOutlying, isBudgetPreload, chat, threadId, direction, offsetId);\n\n if (isBudgetPreload) {\n return undefined;\n }\n }\n\n return global;\n});\n\nasync function loadWithBudget(\n actions: GlobalActions,\n areAllLocal: boolean, isOutlying: boolean, isBudgetPreload: boolean,\n chat: ApiChat, threadId: number, direction: LoadMoreDirection, offsetId?: number,\n) {\n if (!areAllLocal) {\n await loadViewportMessages(\n chat, threadId, offsetId, direction, isOutlying, isBudgetPreload,\n );\n }\n\n if (!isBudgetPreload) {\n // Let reducer return and update global\n await Promise.resolve();\n actions.loadViewportMessages({\n chatId: chat.id, threadId, direction, isBudgetPreload: true,\n });\n }\n}\n\naddReducer('loadMessage', (global, actions, payload) => {\n const {\n chatId, messageId, replyOriginForId, threadUpdate,\n } = payload!;\n const chat = selectChat(global, chatId);\n\n if (!chat) {\n return;\n }\n\n (async () => {\n const message = await loadMessage(chat, messageId, replyOriginForId);\n if (message && threadUpdate) {\n const { lastMessageId, isDeleting } = threadUpdate;\n\n setGlobal(updateThreadUnreadFromForwardedMessage(\n getGlobal(),\n message,\n chatId,\n lastMessageId,\n isDeleting,\n ));\n }\n })();\n});\n\naddReducer('sendMessage', (global, actions, payload) => {\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return undefined;\n }\n\n const { chatId, threadId, type } = currentMessageList;\n\n if (type === 'scheduled' && !payload.scheduledAt) {\n return {\n ...global,\n messages: {\n ...global.messages,\n contentToBeScheduled: payload,\n },\n };\n }\n\n const chat = selectChat(global, chatId)!;\n\n const params = {\n ...payload,\n chat,\n replyingTo: selectReplyingToId(global, chatId, threadId),\n noWebPage: selectNoWebPage(global, chatId, threadId),\n sendAs: selectSendAs(global, chatId),\n };\n\n actions.setReplyingToId({ messageId: undefined });\n actions.clearWebPagePreview({ chatId, threadId, value: false });\n\n const isSingle = !payload.attachments || payload.attachments.length <= 1;\n const isGrouped = !isSingle && payload.attachments && payload.attachments.length > 1;\n\n if (isSingle) {\n const { attachments, ...restParams } = params;\n sendMessage({\n ...restParams,\n attachment: attachments ? attachments[0] : undefined,\n });\n } else if (isGrouped) {\n const {\n text, entities, attachments, ...commonParams\n } = params;\n const groupedAttachments = split(attachments, MAX_MEDIA_FILES_FOR_ALBUM);\n for (let i = 0; i < groupedAttachments.length; i++) {\n const [firstAttachment, ...restAttachments] = groupedAttachments[i];\n const groupedId = `${Date.now()}${i}`;\n\n sendMessage({\n ...commonParams,\n text: i === 0 ? text : undefined,\n entities: i === 0 ? entities : undefined,\n attachment: firstAttachment,\n groupedId: restAttachments.length > 0 ? groupedId : undefined,\n });\n\n restAttachments.forEach((attachment: ApiAttachment) => {\n sendMessage({\n ...commonParams,\n attachment,\n groupedId,\n });\n });\n }\n } else {\n const {\n text, entities, attachments, replyingTo, ...commonParams\n } = params;\n\n if (text) {\n sendMessage({\n ...commonParams,\n text,\n entities,\n replyingTo,\n });\n }\n\n attachments.forEach((attachment: ApiAttachment) => {\n sendMessage({\n ...commonParams,\n attachment,\n });\n });\n }\n\n return undefined;\n});\n\naddReducer('editMessage', (global, actions, payload) => {\n const { serverTimeOffset } = global;\n const { text, entities } = payload!;\n\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n\n const { chatId, threadId, type: messageListType } = currentMessageList;\n const chat = selectChat(global, chatId);\n const message = selectEditingMessage(global, chatId, threadId, messageListType);\n if (!chat || !message) {\n return;\n }\n\n void callApi('editMessage', {\n chat, message, text, entities, noWebPage: selectNoWebPage(global, chatId, threadId), serverTimeOffset,\n });\n\n actions.setEditingId({ messageId: undefined });\n});\n\naddReducer('cancelSendingMessage', (global, actions, payload) => {\n const { chatId, messageId } = payload!;\n const message = selectChatMessage(global, chatId, messageId);\n const progressCallback = message && uploadProgressCallbacks.get(message.previousLocalId || message.id);\n if (progressCallback) {\n cancelApiProgress(progressCallback);\n }\n\n actions.apiUpdate({\n '@type': 'deleteMessages',\n ids: [messageId],\n chatId,\n });\n});\n\naddReducer('saveDraft', (global, actions, payload) => {\n const { chatId, threadId, draft } = payload!;\n if (!draft) {\n return undefined;\n }\n\n const { text, entities } = draft;\n const chat = selectChat(global, chatId)!;\n\n if (threadId === MAIN_THREAD_ID) {\n void callApi('saveDraft', {\n chat,\n text,\n entities,\n replyToMsgId: selectReplyingToId(global, chatId, threadId),\n });\n }\n\n global = replaceThreadParam(global, chatId, threadId, 'draft', draft);\n global = updateChat(global, chatId, { draftDate: Math.round(Date.now() / 1000) });\n\n return global;\n});\n\naddReducer('clearDraft', (global, actions, payload) => {\n const { chatId, threadId, localOnly } = payload!;\n if (!selectDraft(global, chatId, threadId)) {\n return undefined;\n }\n\n const chat = selectChat(global, chatId)!;\n\n if (!localOnly && threadId === MAIN_THREAD_ID) {\n void callApi('clearDraft', chat);\n }\n\n global = replaceThreadParam(global, chatId, threadId, 'draft', undefined);\n global = updateChat(global, chatId, { draftDate: undefined });\n\n return global;\n});\n\naddReducer('toggleMessageWebPage', (global, actions, payload) => {\n const { chatId, threadId, noWebPage } = payload!;\n\n return replaceThreadParam(global, chatId, threadId, 'noWebPage', noWebPage);\n});\n\naddReducer('pinMessage', (global, actions, payload) => {\n const chat = selectCurrentChat(global);\n if (!chat) {\n return;\n }\n\n const {\n messageId, isUnpin, isOneSide, isSilent,\n } = payload!;\n\n void callApi('pinMessage', {\n chat, messageId, isUnpin, isOneSide, isSilent,\n });\n});\n\naddReducer('unpinAllMessages', (global, actions, payload) => {\n const chat = selectChat(global, payload.chatId);\n if (!chat) {\n return;\n }\n\n void unpinAllMessages(chat);\n});\n\nasync function unpinAllMessages(chat: ApiChat) {\n await callApi('unpinAllMessages', { chat });\n let global = getGlobal();\n global = replaceThreadParam(global, chat.id, MAIN_THREAD_ID, 'pinnedIds', []);\n setGlobal(global);\n}\n\naddReducer('deleteMessages', (global, actions, payload) => {\n const { messageIds, shouldDeleteForAll } = payload!;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n const { chatId, threadId } = currentMessageList;\n const chat = selectChat(global, chatId)!;\n\n void callApi('deleteMessages', { chat, messageIds, shouldDeleteForAll });\n\n const editingId = selectEditingId(global, chatId, threadId);\n if (messageIds.includes(editingId)) {\n actions.setEditingId({ messageId: undefined });\n }\n});\n\naddReducer('deleteScheduledMessages', (global, actions, payload) => {\n const { messageIds } = payload!;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n\n const { chatId } = currentMessageList;\n const chat = selectChat(global, chatId)!;\n\n void callApi('deleteScheduledMessages', { chat, messageIds });\n\n const editingId = selectEditingScheduledId(global, chatId);\n if (messageIds.includes(editingId)) {\n actions.setEditingId({ messageId: undefined });\n }\n});\n\naddReducer('deleteHistory', (global, actions, payload) => {\n (async () => {\n const { chatId, shouldDeleteForAll } = payload!;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n const maxId = chat.lastMessage?.id;\n\n await callApi('deleteHistory', { chat, shouldDeleteForAll, maxId });\n\n const activeChat = selectCurrentMessageList(global);\n if (activeChat && activeChat.chatId === chatId) {\n actions.openChat({ id: undefined });\n }\n })();\n});\n\naddReducer('reportMessages', (global, actions, payload) => {\n (async () => {\n const {\n messageIds, reason, description,\n } = payload!;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n\n const { chatId } = currentMessageList;\n const chat = selectChat(global, chatId)!;\n\n const result = await callApi('reportMessages', {\n peer: chat, messageIds, reason, description,\n });\n\n actions.showNotification({\n message: result\n ? 'Thank you! Your report will be reviewed by our team.'\n : 'Error occured while submiting report. Please, try again later.',\n });\n })();\n});\n\naddReducer('sendMessageAction', (global, actions, payload) => {\n (async () => {\n const { action, chatId, threadId } = payload!;\n if (chatId === global.currentUserId) return; // Message actions are disabled in Saved Messages\n\n const chat = selectChat(global, chatId)!;\n if (!chat) return;\n\n await callApi('sendMessageAction', {\n peer: chat, threadId, action,\n });\n })();\n});\n\naddReducer('markMessageListRead', (global, actions, payload) => {\n const { serverTimeOffset } = global;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return undefined;\n }\n\n const { chatId, threadId } = currentMessageList;\n const chat = selectThreadOriginChat(global, chatId, threadId);\n if (!chat) {\n return undefined;\n }\n\n const { maxId } = payload!;\n\n runDebouncedForMarkRead(() => {\n void callApi('markMessageListRead', {\n serverTimeOffset, chat, threadId, maxId,\n });\n });\n\n // TODO Support local marking read for threads\n if (threadId !== MAIN_THREAD_ID) {\n return undefined;\n }\n\n if (chatId === SERVICE_NOTIFICATIONS_USER_ID) {\n global = {\n ...global,\n serviceNotifications: global.serviceNotifications.map((notification) => {\n return notification.isUnread && notification.id <= maxId ? { ...notification, isUnread: false } : notification;\n }),\n };\n }\n\n const viewportIds = selectViewportIds(global, chatId, threadId);\n const minId = selectFirstUnreadId(global, chatId, threadId);\n if (!viewportIds || !minId || !chat.unreadCount) {\n return global;\n }\n\n const readCount = countSortedIds(viewportIds!, minId, maxId);\n if (!readCount) {\n return global;\n }\n\n return updateChat(global, chatId, {\n lastReadInboxMessageId: maxId,\n unreadCount: Math.max(0, chat.unreadCount - readCount),\n });\n});\n\naddReducer('markMessagesRead', (global, actions, payload) => {\n const chat = selectCurrentChat(global);\n if (!chat) {\n return;\n }\n\n const { messageIds } = payload!;\n\n void callApi('markMessagesRead', { chat, messageIds });\n});\n\naddReducer('loadWebPagePreview', (global, actions, payload) => {\n const { text } = payload!;\n void loadWebPagePreview(text);\n});\n\naddReducer('clearWebPagePreview', (global) => {\n if (!global.webPagePreview) {\n return undefined;\n }\n\n return {\n ...global,\n webPagePreview: undefined,\n };\n});\n\naddReducer('sendPollVote', (global, actions, payload) => {\n const { chatId, messageId, options } = payload!;\n const chat = selectChat(global, chatId);\n\n if (chat) {\n void callApi('sendPollVote', { chat, messageId, options });\n }\n});\n\naddReducer('loadPollOptionResults', (global, actions, payload) => {\n const {\n chat, messageId, option, offset, limit, shouldResetVoters,\n } = payload!;\n\n void loadPollOptionResults(chat, messageId, option, offset, limit, shouldResetVoters);\n});\n\naddReducer('forwardMessages', (global, action, payload) => {\n const { fromChatId, messageIds, toChatId } = global.forwardMessages;\n const fromChat = fromChatId ? selectChat(global, fromChatId) : undefined;\n const toChat = toChatId ? selectChat(global, toChatId) : undefined;\n const messages = fromChatId && messageIds\n ? messageIds\n .sort((a, b) => a - b)\n .map((id) => selectChatMessage(global, fromChatId, id)).filter(Boolean as any)\n : undefined;\n\n if (!fromChat || !toChat || !messages) {\n return;\n }\n\n const { isSilent, scheduledAt } = payload;\n const sendAs = selectSendAs(global, toChatId!);\n\n const realMessages = messages.filter((m) => !isServiceNotificationMessage(m));\n if (realMessages.length) {\n void callApi('forwardMessages', {\n fromChat,\n toChat,\n messages: realMessages,\n serverTimeOffset: getGlobal().serverTimeOffset,\n isSilent,\n scheduledAt,\n sendAs,\n });\n }\n\n messages\n .filter((m) => isServiceNotificationMessage(m))\n .forEach((message) => {\n const { text, entities } = message.content.text || {};\n const { sticker, poll } = message.content;\n\n void sendMessage({\n chat: toChat,\n text,\n entities,\n sticker,\n poll,\n isSilent,\n scheduledAt,\n sendAs,\n });\n });\n\n setGlobal({\n ...getGlobal(),\n forwardMessages: {},\n });\n});\n\naddReducer('loadScheduledHistory', (global, actions, payload) => {\n const { chatId } = payload;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n void loadScheduledHistory(chat);\n});\n\naddReducer('sendScheduledMessages', (global, actions, payload) => {\n const {\n chatId, id,\n } = payload!;\n\n const chat = selectChat(global, chatId);\n\n if (!chat) {\n return;\n }\n\n void callApi('sendScheduledMessages', {\n chat,\n ids: [id],\n });\n});\n\naddReducer('rescheduleMessage', (global, actions, payload) => {\n const {\n chatId, messageId, scheduledAt,\n } = payload!;\n\n const chat = selectChat(global, chatId);\n const message = chat && selectScheduledMessage(global, chat.id, messageId);\n if (!chat || !message) {\n return;\n }\n\n void callApi('rescheduleMessage', {\n chat,\n message,\n scheduledAt,\n });\n});\n\naddReducer('requestThreadInfoUpdate', (global, actions, payload) => {\n const { chatId, threadId } = payload;\n const chat = selectThreadOriginChat(global, chatId, threadId);\n if (!chat) {\n return;\n }\n\n void callApi('requestThreadInfoUpdate', { chat, threadId });\n});\n\nasync function loadWebPagePreview(message: string) {\n const webPagePreview = await callApi('fetchWebPagePreview', { message });\n\n setGlobal({\n ...getGlobal(),\n webPagePreview,\n });\n}\n\nasync function loadViewportMessages(\n chat: ApiChat,\n threadId: number,\n offsetId: number | undefined,\n direction: LoadMoreDirection,\n isOutlying = false,\n isBudgetPreload = false,\n) {\n const chatId = chat.id;\n\n let addOffset: number | undefined;\n switch (direction) {\n case LoadMoreDirection.Backwards:\n addOffset = undefined;\n break;\n case LoadMoreDirection.Around:\n addOffset = -(Math.round(MESSAGE_LIST_SLICE / 2) + 1);\n break;\n case LoadMoreDirection.Forwards:\n addOffset = -(MESSAGE_LIST_SLICE + 1);\n break;\n }\n\n const result = await callApi('fetchMessages', {\n chat: selectThreadOriginChat(getGlobal(), chatId, threadId)!,\n offsetId,\n addOffset,\n limit: MESSAGE_LIST_SLICE,\n threadId,\n });\n\n if (!result) {\n return;\n }\n\n const {\n messages, users, chats, threadInfos,\n } = result;\n\n let global = getGlobal();\n\n const localMessages = chatId === SERVICE_NOTIFICATIONS_USER_ID\n ? global.serviceNotifications.map(({ message }) => message)\n : [];\n const allMessages = ([] as ApiMessage[]).concat(messages, localMessages);\n const byId = buildCollectionByKey(allMessages, 'id');\n const ids = Object.keys(byId).map(Number);\n\n global = addChatMessagesById(global, chatId, byId);\n global = isOutlying\n ? updateOutlyingIds(global, chatId, threadId, ids)\n : updateListedIds(global, chatId, threadId, ids);\n\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = addChats(global, buildCollectionByKey(chats, 'id'));\n global = updateThreadInfos(global, chatId, threadInfos);\n\n let listedIds = selectListedIds(global, chatId, threadId);\n const outlyingIds = selectOutlyingIds(global, chatId, threadId);\n\n if (isOutlying && listedIds && outlyingIds) {\n if (!outlyingIds.length || areSortedArraysIntersecting(listedIds, outlyingIds)) {\n global = updateListedIds(global, chatId, threadId, outlyingIds);\n listedIds = selectListedIds(global, chatId, threadId);\n global = replaceThreadParam(global, chatId, threadId, 'outlyingIds', undefined);\n isOutlying = false;\n }\n }\n\n if (!isBudgetPreload) {\n const historyIds = isOutlying ? outlyingIds! : listedIds!;\n const { newViewportIds } = getViewportSlice(historyIds, offsetId, direction);\n global = safeReplaceViewportIds(global, chatId, threadId, newViewportIds!);\n }\n\n setGlobal(global);\n}\n\nasync function loadMessage(chat: ApiChat, messageId: number, replyOriginForId: number) {\n const result = await callApi('fetchMessage', { chat, messageId });\n if (!result) {\n return undefined;\n }\n\n if (result === MESSAGE_DELETED) {\n if (replyOriginForId) {\n let global = getGlobal();\n const replyMessage = selectChatMessage(global, chat.id, replyOriginForId);\n global = updateChatMessage(global, chat.id, replyOriginForId, {\n ...replyMessage,\n replyToMessageId: undefined,\n });\n setGlobal(global);\n }\n\n return undefined;\n }\n\n let global = getGlobal();\n global = updateChatMessage(global, chat.id, messageId, result.message);\n global = addUsers(global, buildCollectionByKey(result.users, 'id'));\n setGlobal(global);\n\n return result.message;\n}\n\nfunction findClosestIndex(sourceIds: number[], offsetId: number) {\n if (offsetId < sourceIds[0]) {\n return 0;\n }\n\n if (offsetId > sourceIds[sourceIds.length - 1]) {\n return sourceIds.length - 1;\n }\n\n return sourceIds.findIndex((id, i) => (\n id === offsetId\n || (id < offsetId && sourceIds[i + 1] > offsetId)\n ));\n}\n\nfunction getViewportSlice(\n sourceIds: number[],\n offsetId: number | undefined,\n direction: LoadMoreDirection,\n) {\n const { length } = sourceIds;\n const index = offsetId ? findClosestIndex(sourceIds, offsetId) : -1;\n const isBackwards = direction === LoadMoreDirection.Backwards;\n const indexForDirection = isBackwards ? index : (index + 1) || length;\n const from = indexForDirection - MESSAGE_LIST_SLICE;\n const to = indexForDirection + MESSAGE_LIST_SLICE - 1;\n const newViewportIds = sourceIds.slice(Math.max(0, from), to + 1);\n\n let areSomeLocal;\n let areAllLocal;\n switch (direction) {\n case LoadMoreDirection.Backwards:\n areSomeLocal = indexForDirection > 0;\n areAllLocal = from >= 0;\n break;\n case LoadMoreDirection.Forwards:\n areSomeLocal = indexForDirection < length;\n areAllLocal = to <= length - 1;\n break;\n case LoadMoreDirection.Around:\n default:\n areSomeLocal = newViewportIds.length > 0;\n areAllLocal = newViewportIds.length === MESSAGE_LIST_SLICE;\n break;\n }\n\n return { newViewportIds, areSomeLocal, areAllLocal };\n}\n\nasync function sendMessage(params: {\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 serverTimeOffset?: number;\n isSilent?: boolean;\n scheduledAt?: number;\n sendAs?: ApiChat | ApiUser;\n}) {\n let localId: number | undefined;\n const progressCallback = params.attachment ? (progress: number, messageLocalId: number) => {\n if (!uploadProgressCallbacks.has(messageLocalId)) {\n localId = messageLocalId;\n uploadProgressCallbacks.set(messageLocalId, progressCallback!);\n }\n\n const global = getGlobal();\n\n setGlobal({\n ...global,\n fileUploads: {\n byMessageLocalId: {\n ...global.fileUploads.byMessageLocalId,\n [messageLocalId]: { progress },\n },\n },\n });\n } : undefined;\n\n // @optimization\n if (params.replyingTo || IS_IOS) {\n await rafPromise();\n }\n\n const global = getGlobal();\n params.serverTimeOffset = global.serverTimeOffset;\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return;\n }\n const { threadId } = currentMessageList;\n\n if (!params.replyingTo && threadId !== MAIN_THREAD_ID) {\n params.replyingTo = selectThreadTopMessageId(global, params.chat.id, threadId)!;\n }\n\n await callApi('sendMessage', params, progressCallback);\n\n if (progressCallback && localId) {\n uploadProgressCallbacks.delete(localId);\n }\n}\n\nasync function loadPollOptionResults(\n chat: ApiChat,\n messageId: number,\n option: string,\n offset?: string,\n limit?: number,\n shouldResetVoters?: boolean,\n) {\n const result = await callApi('loadPollOptionResults', {\n chat, messageId, option, offset, limit,\n });\n\n if (!result) {\n return;\n }\n\n let global = getGlobal();\n\n global = addUsers(global, buildCollectionByKey(result.users, 'id'));\n const { voters } = global.pollResults;\n\n setGlobal({\n ...global,\n pollResults: {\n ...global.pollResults,\n voters: {\n ...voters,\n [option]: unique([\n ...(!shouldResetVoters && voters && voters[option] ? voters[option] : []),\n ...(result && result.users.map((user) => user.id)),\n ]),\n },\n offsets: {\n ...(global.pollResults.offsets ? global.pollResults.offsets : {}),\n [option]: result.nextOffset || '',\n },\n },\n });\n}\n\naddReducer('loadPinnedMessages', (global, actions, payload) => {\n const { chatId } = payload;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n void loadPinnedMessages(chat);\n});\n\naddReducer('loadSeenBy', (global, actions, payload) => {\n const { chatId, messageId } = payload;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n (async () => {\n const result = await callApi('fetchSeenBy', { chat, messageId });\n if (!result) {\n return;\n }\n\n setGlobal(updateChatMessage(getGlobal(), chatId, messageId, {\n seenByUserIds: result,\n }));\n })();\n});\n\naddReducer('saveDefaultSendAs', (global, actions, payload) => {\n const { chatId, sendAsId } = payload;\n const chat = selectChat(global, chatId);\n const sendAsChat = selectChat(global, sendAsId) || selectUser(global, sendAsId);\n if (!chat || !sendAsChat) {\n return undefined;\n }\n\n void callApi('saveDefaultSendAs', { sendAs: sendAsChat, chat });\n\n return updateChat(global, chatId, {\n fullInfo: {\n ...chat.fullInfo,\n sendAsId,\n },\n });\n});\n\naddReducer('loadSendAs', (global, actions, payload) => {\n const { chatId } = payload;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n (async () => {\n const result = await callApi('fetchSendAs', { chat });\n if (!result) {\n global = updateChat(global, chatId, {\n sendAsIds: [],\n });\n setGlobal(global);\n return;\n }\n\n global = getGlobal();\n global = addUsers(global, buildCollectionByKey(result.users, 'id'));\n global = addChats(global, buildCollectionByKey(result.chats, 'id'));\n global = updateChat(global, chatId, {\n sendAsIds: result.ids,\n });\n setGlobal(global);\n })();\n});\n\nasync function loadPinnedMessages(chat: ApiChat) {\n const result = await callApi('fetchPinnedMessages', { chat });\n if (!result) {\n return;\n }\n\n const { messages, chats, users } = result;\n\n const byId = buildCollectionByKey(messages, 'id');\n const ids = Object.keys(byId).map(Number).sort((a, b) => b - a);\n\n let global = getGlobal();\n global = addChatMessagesById(global, chat.id, byId);\n global = replaceThreadParam(global, chat.id, MAIN_THREAD_ID, 'pinnedIds', ids);\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = addChats(global, buildCollectionByKey(chats, 'id'));\n setGlobal(global);\n}\n\nasync function loadScheduledHistory(chat: ApiChat) {\n const result = await callApi('fetchScheduledHistory', { chat });\n if (!result) {\n return;\n }\n\n const { messages } = result;\n\n const byId = buildCollectionByKey(messages, 'id');\n const ids = Object.keys(byId).map(Number).sort((a, b) => b - a);\n\n let global = getGlobal();\n global = replaceScheduledMessages(global, chat.id, byId);\n global = replaceThreadParam(global, chat.id, MAIN_THREAD_ID, 'scheduledIds', ids);\n setGlobal(global);\n}\n\naddReducer('loadSponsoredMessages', (global, actions, payload) => {\n const { chatId } = payload;\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n (async () => {\n const result = await callApi('fetchSponsoredMessages', { chat });\n if (!result) {\n return;\n }\n\n let newGlobal = updateSponsoredMessage(getGlobal(), chatId, result.messages[0]);\n newGlobal = addUsers(newGlobal, buildCollectionByKey(result.users, 'id'));\n newGlobal = addChats(newGlobal, buildCollectionByKey(result.chats, 'id'));\n\n setGlobal(newGlobal);\n })();\n});\n\naddReducer('viewSponsoredMessage', (global, actions, payload) => {\n const { chatId } = payload;\n const chat = selectChat(global, chatId);\n const message = selectSponsoredMessage(global, chatId);\n if (!chat || !message) {\n return;\n }\n\n void callApi('viewSponsoredMessage', { chat, random: message.randomId });\n});\n\nfunction countSortedIds(ids: number[], from: number, to: number) {\n let count = 0;\n\n for (let i = 0, l = ids.length; i < l; i++) {\n if (ids[i] >= from && ids[i] <= to) {\n count++;\n }\n\n if (ids[i] >= to) {\n break;\n }\n }\n\n return count;\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiSticker } from '../../../api/types';\nimport { LangCode } from '../../../types';\nimport { callApi } from '../../../api/gramjs';\nimport { pause, throttle } from '../../../util/schedulers';\nimport {\n updateStickerSets,\n updateStickerSet,\n replaceAnimatedEmojis,\n updateGifSearch,\n updateStickersForEmoji,\n rebuildStickersForEmoji,\n} from '../../reducers';\nimport searchWords from '../../../util/searchWords';\nimport { selectStickerSet } from '../../selectors';\n\nconst ADDED_SETS_THROTTLE = 200;\nconst ADDED_SETS_THROTTLE_CHUNK = 10;\n\nconst searchThrottled = throttle((cb) => cb(), 500, false);\n\naddReducer('loadStickerSets', (global) => {\n const { hash } = global.stickers.added || {};\n void loadStickerSets(hash);\n});\n\naddReducer('loadAddedStickers', (global, actions) => {\n const { setIds: addedSetIds } = global.stickers.added;\n if (!addedSetIds || !addedSetIds.length) {\n return;\n }\n\n (async () => {\n for (let i = 0; i < addedSetIds.length; i++) {\n actions.loadStickers({ stickerSetId: addedSetIds[i] });\n\n if (i % ADDED_SETS_THROTTLE_CHUNK === 0 && i > 0) {\n await pause(ADDED_SETS_THROTTLE);\n }\n }\n })();\n});\n\naddReducer('loadRecentStickers', (global) => {\n const { hash } = global.stickers.recent || {};\n void loadRecentStickers(hash);\n});\n\naddReducer('loadFavoriteStickers', (global) => {\n const { hash } = global.stickers.favorite || {};\n void loadFavoriteStickers(hash);\n});\n\naddReducer('loadGreetingStickers', (global) => {\n const { hash } = global.stickers.greeting || {};\n\n (async () => {\n const greeting = await callApi('fetchStickersForEmoji', { emoji: '👋⭐️', hash });\n\n if (!greeting) {\n return;\n }\n\n const newGlobal = getGlobal();\n\n setGlobal({\n ...newGlobal,\n stickers: {\n ...newGlobal.stickers,\n greeting: {\n hash: greeting.hash,\n stickers: greeting.stickers.filter((sticker) => sticker.emoji === '👋'),\n },\n },\n });\n })();\n});\n\naddReducer('loadFeaturedStickers', (global) => {\n const { hash } = global.stickers.featured || {};\n void loadFeaturedStickers(hash);\n});\n\naddReducer('loadStickers', (global, actions, payload) => {\n const { stickerSetId, stickerSetShortName } = payload!;\n let { stickerSetAccessHash } = payload!;\n\n if (!stickerSetAccessHash && !stickerSetShortName) {\n const stickerSet = selectStickerSet(global, stickerSetId);\n if (!stickerSet) {\n return;\n }\n\n stickerSetAccessHash = stickerSet.accessHash;\n }\n\n void loadStickers(stickerSetId, stickerSetAccessHash, stickerSetShortName);\n});\n\naddReducer('loadAnimatedEmojis', () => {\n void loadAnimatedEmojis();\n});\n\naddReducer('loadSavedGifs', (global) => {\n const { hash } = global.gifs.saved;\n void loadSavedGifs(hash);\n});\n\naddReducer('faveSticker', (global, actions, payload) => {\n const { sticker } = payload!;\n\n if (sticker) {\n void callApi('faveSticker', { sticker });\n }\n});\n\naddReducer('unfaveSticker', (global, actions, payload) => {\n const { sticker } = payload!;\n\n if (sticker) {\n void unfaveSticker(sticker);\n }\n});\n\naddReducer('toggleStickerSet', (global, actions, payload) => {\n const { stickerSetId } = payload!;\n const stickerSet = selectStickerSet(global, stickerSetId);\n if (!stickerSet) {\n return;\n }\n\n const { accessHash, installedDate } = stickerSet;\n\n void callApi(!installedDate ? 'installStickerSet' : 'uninstallStickerSet', { stickerSetId, accessHash });\n});\n\naddReducer('loadEmojiKeywords', (global, actions, payload: { language: LangCode }) => {\n const { language } = payload;\n\n let currentEmojiKeywords = global.emojiKeywords[language];\n if (currentEmojiKeywords?.isLoading) {\n return;\n }\n\n setGlobal({\n ...global,\n emojiKeywords: {\n ...global.emojiKeywords,\n [language]: {\n ...currentEmojiKeywords,\n isLoading: true,\n },\n },\n });\n\n (async () => {\n const emojiKeywords = await callApi('fetchEmojiKeywords', {\n language,\n fromVersion: currentEmojiKeywords ? currentEmojiKeywords.version : 0,\n });\n\n global = getGlobal();\n currentEmojiKeywords = global.emojiKeywords[language];\n\n if (!emojiKeywords) {\n setGlobal({\n ...global,\n emojiKeywords: {\n ...global.emojiKeywords,\n [language]: {\n ...currentEmojiKeywords,\n isLoading: false,\n },\n },\n });\n\n return;\n }\n\n setGlobal({\n ...global,\n emojiKeywords: {\n ...global.emojiKeywords,\n [language]: {\n isLoading: false,\n version: emojiKeywords.version,\n keywords: {\n ...(currentEmojiKeywords?.keywords),\n ...emojiKeywords.keywords,\n },\n },\n },\n });\n })();\n});\n\nasync function loadStickerSets(hash?: string) {\n const addedStickers = await callApi('fetchStickerSets', { hash });\n if (!addedStickers) {\n return;\n }\n\n setGlobal(updateStickerSets(\n getGlobal(),\n 'added',\n addedStickers.hash,\n addedStickers.sets,\n ));\n}\n\nasync function loadRecentStickers(hash?: string) {\n const recentStickers = await callApi('fetchRecentStickers', { hash });\n if (!recentStickers) {\n return;\n }\n\n const global = getGlobal();\n\n setGlobal({\n ...global,\n stickers: {\n ...global.stickers,\n recent: recentStickers,\n },\n });\n}\n\nasync function loadFavoriteStickers(hash?: string) {\n const favoriteStickers = await callApi('fetchFavoriteStickers', { hash });\n if (!favoriteStickers) {\n return;\n }\n\n const global = getGlobal();\n\n setGlobal({\n ...global,\n stickers: {\n ...global.stickers,\n favorite: favoriteStickers,\n },\n });\n}\n\nasync function loadFeaturedStickers(hash?: string) {\n const featuredStickers = await callApi('fetchFeaturedStickers', { hash });\n if (!featuredStickers) {\n return;\n }\n\n setGlobal(updateStickerSets(\n getGlobal(),\n 'featured',\n featuredStickers.hash,\n featuredStickers.sets,\n ));\n}\n\nasync function loadStickers(stickerSetId: string, accessHash: string, stickerSetShortName?: string) {\n const stickerSet = await callApi(\n 'fetchStickers',\n { stickerSetShortName, stickerSetId, accessHash },\n );\n if (!stickerSet) {\n return;\n }\n\n const { set, stickers, packs } = stickerSet;\n\n let global = getGlobal();\n\n global = updateStickerSet(global, set.id, { ...set, stickers, packs });\n\n const currentEmoji = global.stickers.forEmoji.emoji;\n if (currentEmoji && packs[currentEmoji]) {\n global = rebuildStickersForEmoji(global);\n }\n\n setGlobal(global);\n}\n\nasync function loadAnimatedEmojis() {\n const stickerSet = await callApi('fetchAnimatedEmojis');\n if (!stickerSet) {\n return;\n }\n\n const { set, stickers } = stickerSet;\n\n setGlobal(replaceAnimatedEmojis(getGlobal(), { ...set, stickers }));\n}\n\nfunction unfaveSticker(sticker: ApiSticker) {\n const global = getGlobal();\n\n // Remove sticker preemptively to get instant feedback when user removes sticker\n // from favorites while in Sticker Picker\n setGlobal({\n ...global,\n stickers: {\n ...global.stickers,\n favorite: {\n ...global.stickers.favorite,\n stickers: global.stickers.favorite.stickers.filter(({ id }) => id !== sticker.id),\n },\n },\n });\n\n void callApi('faveSticker', { sticker, unfave: true });\n}\n\naddReducer('setStickerSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n\n if (query) {\n void searchThrottled(() => {\n searchStickers(query);\n });\n }\n});\n\naddReducer('setGifSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n\n if (typeof query === 'string') {\n void searchThrottled(() => {\n searchGifs(query);\n });\n }\n});\n\naddReducer('searchMoreGifs', (global) => {\n const { query, offset } = global.gifs.search;\n\n if (typeof query === 'string') {\n void searchThrottled(() => {\n searchGifs(query, offset);\n });\n }\n});\n\naddReducer('loadStickersForEmoji', (global, actions, payload) => {\n const { emoji } = payload!;\n const { hash } = global.stickers.forEmoji;\n\n void searchThrottled(() => {\n loadStickersForEmoji(emoji, hash);\n });\n});\n\naddReducer('clearStickersForEmoji', (global) => {\n return {\n ...global,\n stickers: {\n ...global.stickers,\n forEmoji: {},\n },\n };\n});\n\naddReducer('openStickerSetShortName', (global, actions, payload) => {\n const { stickerSetShortName } = payload!;\n return {\n ...global,\n openedStickerSetShortName: stickerSetShortName,\n };\n});\n\nasync function searchStickers(query: string, hash?: string) {\n const result = await callApi('searchStickers', { query, hash });\n\n if (!result) {\n return;\n }\n\n const global = getGlobal();\n const { setsById, added } = global.stickers;\n\n const resultIds = result.sets.map(({ id }) => id);\n\n if (added.setIds) {\n added.setIds.forEach((id) => {\n if (!resultIds.includes(id)) {\n const { title } = setsById[id] || {};\n if (title && searchWords(title, query)) {\n resultIds.unshift(id);\n }\n }\n });\n }\n\n setGlobal(updateStickerSets(\n global,\n 'search',\n result.hash,\n result.sets,\n resultIds,\n ));\n}\n\nasync function searchGifs(query: string, offset?: string) {\n const result = await callApi('searchGifs', { query, offset });\n if (!result) {\n return;\n }\n\n setGlobal(updateGifSearch(getGlobal(), !offset, result.gifs, result.nextOffset));\n}\n\nasync function loadSavedGifs(hash?: string) {\n const savedGifs = await callApi('fetchSavedGifs', { hash });\n if (!savedGifs) {\n return;\n }\n\n const global = getGlobal();\n\n setGlobal({\n ...global,\n gifs: {\n ...global.gifs,\n saved: savedGifs,\n },\n });\n}\n\nasync function loadStickersForEmoji(emoji: string, hash?: string) {\n let global = getGlobal();\n setGlobal({\n ...global,\n stickers: {\n ...global.stickers,\n forEmoji: {\n ...global.stickers.forEmoji,\n emoji,\n },\n },\n });\n\n const result = await callApi('fetchStickersForEmoji', { emoji, hash });\n\n global = getGlobal();\n\n if (!result || global.stickers.forEmoji.emoji !== emoji) {\n return;\n }\n\n global = updateStickersForEmoji(global, emoji, result.stickers, result.hash);\n\n setGlobal(global);\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { callApi } from '../../../api/gramjs';\nimport { ApiChat, ApiGlobalMessageSearchType } from '../../../api/types';\n\nimport {\n addChats,\n addMessages,\n addUsers,\n updateGlobalSearch,\n updateGlobalSearchFetchingStatus,\n updateGlobalSearchResults,\n} from '../../reducers';\nimport { throttle } from '../../../util/schedulers';\nimport { selectChat, selectCurrentGlobalSearchQuery } from '../../selectors';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport { GLOBAL_SEARCH_SLICE } from '../../../config';\nimport { timestampPlusDay } from '../../../util/dateFormat';\n\nconst searchThrottled = throttle((cb) => cb(), 500, false);\n\naddReducer('setGlobalSearchQuery', (global, actions, payload) => {\n const { chatId } = global.globalSearch;\n const { query } = payload!;\n\n if (query && !chatId) {\n void searchThrottled(() => {\n searchChats(query);\n });\n }\n});\n\naddReducer('setGlobalSearchDate', (global, actions, payload) => {\n const { date } = payload!;\n const maxDate = date ? timestampPlusDay(date) : date;\n const newGlobal = updateGlobalSearch(global, {\n date,\n query: '',\n resultsByType: {\n ...global.globalSearch.resultsByType,\n text: {\n totalCount: undefined,\n foundIds: [],\n nextOffsetId: 0,\n },\n },\n });\n setGlobal(newGlobal);\n const { chatId } = global.globalSearch;\n const chat = chatId ? selectChat(global, chatId) : undefined;\n searchMessagesGlobal('', 'text', undefined, chat, maxDate, date);\n});\n\naddReducer('searchMessagesGlobal', (global, actions, payload) => {\n const {\n query, resultsByType, chatId, date,\n } = global.globalSearch;\n const maxDate = date ? timestampPlusDay(date) : date;\n const { type } = payload;\n const nextOffsetId = (resultsByType?.[type as ApiGlobalMessageSearchType])?.nextOffsetId;\n\n const chat = chatId ? selectChat(global, chatId) : undefined;\n\n searchMessagesGlobal(query, type, nextOffsetId, chat, maxDate, date);\n});\n\nasync function searchChats(query: string) {\n const result = await callApi('searchChats', { query });\n\n let global = getGlobal();\n const currentSearchQuery = selectCurrentGlobalSearchQuery(global);\n if (!result || !currentSearchQuery || (query !== currentSearchQuery)) {\n setGlobal(updateGlobalSearchFetchingStatus(global, { chats: false }));\n return;\n }\n\n const {\n localChats, localUsers, globalChats, globalUsers,\n } = result;\n\n if (localChats.length || globalChats.length) {\n global = addChats(global, buildCollectionByKey([...localChats, ...globalChats], 'id'));\n }\n\n if (localUsers.length || globalUsers.length) {\n global = addUsers(global, buildCollectionByKey([...localUsers, ...globalUsers], 'id'));\n }\n\n global = updateGlobalSearchFetchingStatus(global, { chats: false });\n global = updateGlobalSearch(global, {\n localResults: {\n chatIds: localChats.map(({ id }) => id),\n userIds: localUsers.map(({ id }) => id),\n },\n globalResults: {\n ...global.globalSearch.globalResults,\n chatIds: globalChats.map(({ id }) => id),\n userIds: globalUsers.map(({ id }) => id),\n },\n });\n\n setGlobal(global);\n}\n\nasync function searchMessagesGlobal(\n query = '', type: ApiGlobalMessageSearchType, offsetRate?: number, chat?: ApiChat, maxDate?: number, minDate?: number,\n) {\n let result;\n\n if (chat) {\n const localResult = await callApi('searchMessagesLocal', {\n chatOrUser: chat,\n query,\n type,\n limit: GLOBAL_SEARCH_SLICE,\n offsetId: offsetRate,\n minDate,\n maxDate,\n });\n\n if (localResult) {\n const {\n messages, users, totalCount, nextOffsetId,\n } = localResult;\n\n result = {\n messages,\n users,\n chats: [],\n totalCount,\n nextRate: nextOffsetId,\n };\n }\n } else {\n result = await callApi('searchMessagesGlobal', {\n query,\n offsetRate,\n limit: GLOBAL_SEARCH_SLICE,\n type,\n maxDate,\n minDate,\n });\n }\n\n let global = getGlobal();\n const currentSearchQuery = selectCurrentGlobalSearchQuery(global);\n if (!result || (query !== '' && query !== currentSearchQuery)) {\n setGlobal(updateGlobalSearchFetchingStatus(global, { messages: false }));\n return;\n }\n\n const {\n messages, users, chats, totalCount, nextRate,\n } = result;\n\n if (chats.length) {\n global = addChats(global, buildCollectionByKey(chats, 'id'));\n }\n\n if (users.length) {\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n }\n\n if (messages.length) {\n global = addMessages(global, messages);\n }\n\n global = updateGlobalSearchResults(\n global,\n messages,\n totalCount,\n type,\n nextRate,\n );\n\n setGlobal(global);\n}\n","import {\n addReducer, getDispatch, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { ApiChat, ApiUser, MAIN_THREAD_ID } from '../../../api/types';\n\nimport { MESSAGE_SEARCH_SLICE, SHARED_MEDIA_SLICE } from '../../../config';\nimport { callApi } from '../../../api/gramjs';\nimport {\n selectCurrentTextSearch,\n selectCurrentMediaSearchPeerId,\n selectCurrentMediaSearch, selectCurrentMessageList, selectChat, selectThreadInfo,\n} from '../../selectors';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport {\n addChatMessagesById,\n addUsers,\n updateLocalMediaSearchResults,\n updateLocalTextSearchResults,\n} from '../../reducers';\nimport { SharedMediaType } from '../../../types';\n\naddReducer('searchTextMessagesLocal', (global) => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n const chat = chatId ? selectChat(global, chatId) : undefined;\n const currentSearch = selectCurrentTextSearch(global);\n if (!chat || !currentSearch || !threadId) {\n return;\n }\n\n const { query, results } = currentSearch;\n const offsetId = results?.nextOffsetId;\n\n let topMessageId: number | undefined;\n if (threadId !== MAIN_THREAD_ID) {\n const threadInfo = selectThreadInfo(global, chatId!, threadId);\n topMessageId = threadInfo?.topMessageId;\n }\n\n void searchTextMessages(chat, threadId, topMessageId, query, offsetId);\n});\n\naddReducer('searchMediaMessagesLocal', (global) => {\n const peerId = selectCurrentMediaSearchPeerId(global);\n const chatOrUser = peerId\n ? global.users.byId[peerId] || global.chats.byId[peerId]\n : undefined;\n const currentSearch = selectCurrentMediaSearch(global);\n\n if (!chatOrUser || !currentSearch) {\n return;\n }\n\n const { currentType: type, resultsByType } = currentSearch;\n const currentResults = type && resultsByType && resultsByType[type];\n const offsetId = currentResults?.nextOffsetId;\n\n if (!type) {\n return;\n }\n\n void searchSharedMedia(chatOrUser, type, offsetId);\n});\n\naddReducer('searchMessagesByDate', (global, actions, payload) => {\n const { timestamp } = payload!;\n\n const { chatId } = selectCurrentMessageList(global) || {};\n if (!chatId) {\n return;\n }\n\n const chat = selectChat(global, chatId);\n if (!chat) {\n return;\n }\n\n void searchMessagesByDate(chat, timestamp);\n});\n\nasync function searchTextMessages(\n chatOrUser: ApiChat,\n threadId: number,\n topMessageId?: number,\n query?: string,\n offsetId?: number,\n) {\n const result = await callApi('searchMessagesLocal', {\n chatOrUser,\n type: 'text',\n query,\n topMessageId,\n limit: MESSAGE_SEARCH_SLICE,\n offsetId,\n });\n\n if (!result) {\n return;\n }\n\n const {\n messages, users, totalCount, nextOffsetId,\n } = result;\n\n const byId = buildCollectionByKey(messages, 'id');\n const newFoundIds = Object.keys(byId).map(Number);\n\n let global = getGlobal();\n\n const currentSearch = selectCurrentTextSearch(global);\n if (!currentSearch || (query && query !== currentSearch.query)) {\n return;\n }\n\n global = addChatMessagesById(global, chatOrUser.id, byId);\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = updateLocalTextSearchResults(global, chatOrUser.id, threadId, newFoundIds, totalCount, nextOffsetId);\n setGlobal(global);\n}\n\nasync function searchSharedMedia(\n chatOrUser: ApiChat | ApiUser,\n type: SharedMediaType,\n offsetId?: number,\n) {\n const result = await callApi('searchMessagesLocal', {\n chatOrUser,\n type,\n limit: SHARED_MEDIA_SLICE,\n offsetId,\n });\n\n if (!result) {\n return;\n }\n\n const {\n messages, users, totalCount, nextOffsetId,\n } = result;\n\n const byId = buildCollectionByKey(messages, 'id');\n const newFoundIds = Object.keys(byId).map(Number);\n\n let global = getGlobal();\n\n const currentSearch = selectCurrentMediaSearch(global);\n if (!currentSearch) {\n return;\n }\n\n global = addChatMessagesById(global, chatOrUser.id, byId);\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = updateLocalMediaSearchResults(global, chatOrUser.id, type, newFoundIds, totalCount, nextOffsetId);\n setGlobal(global);\n}\n\n/**\n * @param timestamp start of target date in seconds\n */\nasync function searchMessagesByDate(chat: ApiChat, timestamp: number) {\n const messageId = await callApi('findFirstMessageIdAfterDate', {\n chat,\n timestamp,\n });\n\n if (!messageId) {\n return;\n }\n\n getDispatch().focusMessage({\n chatId: chat.id,\n messageId,\n });\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { ManagementProgress } from '../../../types';\nimport { callApi } from '../../../api/gramjs';\nimport { updateManagement, updateManagementProgress } from '../../reducers';\nimport { selectChat, selectCurrentMessageList } from '../../selectors';\nimport { isChatBasicGroup } from '../../helpers';\n\naddReducer('checkPublicLink', (global, actions, payload) => {\n const { chatId } = selectCurrentMessageList(global) || {};\n if (!chatId) {\n return;\n }\n\n // No need to check the username if already in progress\n if (global.management.progress === ManagementProgress.InProgress) {\n return;\n }\n\n const { username } = payload!;\n\n (async () => {\n global = updateManagementProgress(global, ManagementProgress.InProgress);\n global = updateManagement(global, chatId, { isUsernameAvailable: undefined });\n setGlobal(global);\n\n const isUsernameAvailable = await callApi('checkChatUsername', { username })!;\n\n global = getGlobal();\n global = updateManagementProgress(\n global, isUsernameAvailable ? ManagementProgress.Complete : ManagementProgress.Error,\n );\n global = updateManagement(global, chatId, { isUsernameAvailable });\n setGlobal(global);\n })();\n});\n\naddReducer('updatePublicLink', (global, actions, payload) => {\n const { chatId } = selectCurrentMessageList(global) || {};\n let chat = chatId && selectChat(global, chatId);\n if (!chatId || !chat) {\n return;\n }\n\n const { username } = payload!;\n\n (async () => {\n global = updateManagementProgress(global, ManagementProgress.InProgress);\n setGlobal(global);\n\n if (isChatBasicGroup(chat)) {\n chat = await callApi('migrateChat', chat);\n\n if (!chat) {\n return;\n }\n\n actions.openChat({ id: chat.id });\n }\n\n const result = await callApi('setChatUsername', { chat, username });\n\n global = getGlobal();\n global = updateManagementProgress(global, result ? ManagementProgress.Complete : ManagementProgress.Error);\n global = updateManagement(global, chatId, { isUsernameAvailable: undefined });\n setGlobal(global);\n })();\n});\n\naddReducer('updatePrivateLink', (global) => {\n const { chatId } = selectCurrentMessageList(global) || {};\n const chat = chatId && selectChat(global, chatId);\n if (!chatId || !chat) {\n return;\n }\n\n callApi('updatePrivateLink', { chat });\n});\n","import {\n addReducer, getGlobal, setGlobal, getDispatch,\n} from '../../../lib/teact/teactn';\n\nimport {\n ApiChat, ApiFormattedText, ApiMessage, ApiUser, MAIN_THREAD_ID,\n} from '../../../api/types';\n\nimport {\n CHAT_LIST_LOAD_SLICE, DEBUG, MESSAGE_LIST_SLICE, SERVICE_NOTIFICATIONS_USER_ID,\n} from '../../../config';\nimport { callApi } from '../../../api/gramjs';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport { updateAppBadge } from '../../../util/appBadge';\nimport {\n replaceChatListIds,\n replaceChats,\n replaceUsers,\n replaceUserStatuses,\n updateUsers,\n addUserStatuses,\n updateChats,\n updateChatListSecondaryInfo,\n updateThreadInfos,\n replaceThreadParam,\n updateListedIds,\n safeReplaceViewportIds,\n addChatMessagesById,\n} from '../../reducers';\nimport {\n selectUser,\n selectChat,\n selectCurrentMessageList,\n selectDraft,\n selectChatMessage,\n selectThreadInfo,\n selectCountNotMutedUnread,\n selectLastServiceNotification,\n} from '../../selectors';\nimport { isUserId } from '../../helpers';\n\naddReducer('sync', (global, actions) => {\n void sync(actions.afterSync);\n});\n\naddReducer('afterSync', () => {\n void afterSync();\n});\n\nasync function sync(afterSyncCallback: () => void) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START SYNC');\n }\n\n await callApi('fetchCurrentUser');\n\n // This fetches only active chats and clears archived chats, which will be fetched in `afterSync`\n const savedUsers = await loadAndReplaceChats();\n await loadAndReplaceMessages(savedUsers);\n\n setGlobal({\n ...getGlobal(),\n lastSyncTime: Date.now(),\n });\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH SYNC');\n }\n\n afterSyncCallback();\n}\n\nasync function afterSync() {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START AFTER-SYNC');\n }\n\n await Promise.all([\n loadAndUpdateUsers(),\n loadAndReplaceArchivedChats(),\n ]);\n\n await callApi('fetchCurrentUser');\n\n updateAppBadge(selectCountNotMutedUnread(getGlobal()));\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH AFTER-SYNC');\n }\n}\n\nasync function loadAndReplaceChats() {\n let global = getGlobal();\n\n const result = await callApi('fetchChats', {\n limit: CHAT_LIST_LOAD_SLICE,\n withPinned: true,\n serverTimeOffset: global.serverTimeOffset,\n lastLocalServiceMessage: selectLastServiceNotification(global)?.message,\n });\n\n if (!result) {\n return undefined;\n }\n\n global = getGlobal();\n\n const { recentlyFoundChatIds } = global.globalSearch;\n const { userIds: contactIds } = global.contactList || {};\n const { currentUserId } = global;\n\n const savedPrivateChatIds = [\n ...(recentlyFoundChatIds || []),\n ...(contactIds || []),\n ...(currentUserId ? [currentUserId] : []),\n ];\n\n const savedUsers = savedPrivateChatIds\n .map((id) => selectUser(global, id))\n .filter(Boolean as any);\n\n const savedChats = savedPrivateChatIds\n .map((id) => selectChat(global, id))\n .filter(Boolean as any);\n\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n if (currentChatId) {\n const selectedChat = selectChat(global, currentChatId);\n if (selectedChat && !savedPrivateChatIds.includes(currentChatId)) {\n savedChats.push(selectedChat);\n }\n\n if (isUserId(currentChatId)) {\n const selectedChatUser = selectUser(global, currentChatId);\n if (selectedChatUser && !savedPrivateChatIds.includes(currentChatId)) {\n savedUsers.push(selectedChatUser);\n }\n }\n }\n\n savedUsers.push(...result.users);\n savedChats.push(...result.chats);\n\n global = replaceUserStatuses(global, result.userStatusesById);\n\n global = replaceChats(global, buildCollectionByKey(savedChats, 'id'));\n global = replaceChatListIds(global, 'active', result.chatIds);\n global = updateChatListSecondaryInfo(global, 'active', result);\n\n Object.keys(result.draftsById).forEach((chatId) => {\n global = replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'draft', result.draftsById[chatId]);\n });\n\n Object.keys(result.replyingToById).forEach((chatId) => {\n global = replaceThreadParam(\n global, chatId, MAIN_THREAD_ID, 'replyingToId', result.replyingToById[chatId],\n );\n });\n\n setGlobal(global);\n\n if (currentChatId && !global.chats.byId[currentChatId]) {\n getDispatch().openChat({ id: undefined });\n }\n\n return savedUsers;\n}\n\nasync function loadAndReplaceArchivedChats() {\n const result = await callApi('fetchChats', {\n limit: CHAT_LIST_LOAD_SLICE,\n archived: true,\n withPinned: true,\n serverTimeOffset: getGlobal().serverTimeOffset,\n });\n\n if (!result) {\n return;\n }\n\n let global = getGlobal();\n\n global = updateUsers(global, buildCollectionByKey(result.users, 'id'));\n global = addUserStatuses(global, result.userStatusesById);\n\n global = updateChats(global, buildCollectionByKey(result.chats, 'id'));\n global = replaceChatListIds(global, 'archived', result.chatIds);\n global = updateChatListSecondaryInfo(global, 'archived', result);\n\n setGlobal(global);\n}\n\nasync function loadAndReplaceMessages(savedUsers?: ApiUser[]) {\n let areMessagesLoaded = false;\n let users = savedUsers || [];\n\n let global = getGlobal();\n const { chatId: currentChatId, threadId: currentThreadId } = selectCurrentMessageList(global) || {};\n\n // Memoize drafts\n const draftChatIds = Object.keys(global.messages.byChatId);\n const draftsByChatId = draftChatIds.reduce>((acc, chatId) => {\n const draft = selectDraft(global, chatId, MAIN_THREAD_ID);\n if (draft) {\n acc[chatId] = draft;\n }\n\n return acc;\n }, {});\n\n if (currentChatId) {\n const result = await loadTopMessages(global.chats.byId[currentChatId]);\n global = getGlobal();\n const { chatId: newCurrentChatId } = selectCurrentMessageList(global) || {};\n const threadInfo = currentThreadId && selectThreadInfo(global, currentChatId, currentThreadId);\n\n if (result && newCurrentChatId === currentChatId) {\n const currentMessageListInfo = global.messages.byChatId[currentChatId];\n const localMessages = currentChatId === SERVICE_NOTIFICATIONS_USER_ID\n ? global.serviceNotifications.map(({ message }) => message)\n : [];\n const allMessages = ([] as ApiMessage[]).concat(result.messages, localMessages);\n const byId = buildCollectionByKey(allMessages, 'id');\n const listedIds = Object.keys(byId).map(Number);\n\n global = {\n ...global,\n messages: {\n ...global.messages,\n byChatId: {},\n },\n };\n\n global = addChatMessagesById(global, currentChatId, byId);\n global = updateListedIds(global, currentChatId, MAIN_THREAD_ID, listedIds);\n global = safeReplaceViewportIds(global, currentChatId, MAIN_THREAD_ID, listedIds);\n\n if (currentThreadId && threadInfo && threadInfo.originChannelId) {\n const { originChannelId } = threadInfo;\n const currentMessageListInfoOrigin = global.messages.byChatId[originChannelId];\n const resultOrigin = await loadTopMessages(global.chats.byId[originChannelId]);\n if (resultOrigin) {\n const byIdOrigin = buildCollectionByKey(resultOrigin.messages, 'id');\n const listedIdsOrigin = Object.keys(byIdOrigin).map(Number);\n\n global = {\n ...global,\n messages: {\n ...global.messages,\n byChatId: {\n ...global.messages.byChatId,\n [threadInfo.originChannelId]: {\n byId: byIdOrigin,\n threadsById: {\n [MAIN_THREAD_ID]: {\n ...(currentMessageListInfoOrigin?.threadsById[MAIN_THREAD_ID]),\n listedIds: listedIdsOrigin,\n viewportIds: listedIdsOrigin,\n outlyingIds: undefined,\n },\n },\n },\n [currentChatId]: {\n ...global.messages.byChatId[currentChatId],\n threadsById: {\n ...global.messages.byChatId[currentChatId].threadsById,\n [currentThreadId]: {\n ...(currentMessageListInfo?.threadsById[currentThreadId]),\n outlyingIds: undefined,\n },\n },\n },\n },\n },\n };\n }\n }\n\n global = updateChats(global, buildCollectionByKey(result.chats, 'id'));\n global = updateThreadInfos(global, currentChatId, result.threadInfos);\n\n areMessagesLoaded = true;\n users = Array.prototype.concat(users, result.users);\n }\n }\n\n if (!areMessagesLoaded) {\n global = {\n ...global,\n messages: {\n ...global.messages,\n byChatId: {},\n },\n };\n }\n\n // Restore drafts\n Object.keys(draftsByChatId).forEach((chatId) => {\n global = replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'draft', draftsByChatId[chatId]);\n });\n\n if (savedUsers) {\n global = replaceUsers(global, buildCollectionByKey(users, 'id'));\n } else if (users) {\n // If `fetchChats` has failed for some reason, we don't have saved chats, thus we can not replace\n global = updateUsers(global, buildCollectionByKey(users, 'id'));\n }\n\n setGlobal(global);\n\n const { chatId: audioChatId, messageId: audioMessageId } = global.audioPlayer;\n if (audioChatId && audioMessageId && !selectChatMessage(global, audioChatId, audioMessageId)) {\n getDispatch().closeAudioPlayer();\n }\n}\n\nasync function loadAndUpdateUsers() {\n let global = getGlobal();\n const { recentlyFoundChatIds } = global.globalSearch;\n const { userIds: contactIds } = global.contactList || {};\n if (\n (!contactIds || !contactIds.length)\n && (!recentlyFoundChatIds || !recentlyFoundChatIds.length)\n ) {\n return;\n }\n\n const users = [\n ...(recentlyFoundChatIds || []),\n ...(contactIds || []),\n ].map((id) => selectUser(global, id)).filter(Boolean as any);\n\n const result = await callApi('fetchUsers', { users });\n if (!result) {\n return;\n }\n\n const { users: updatedUsers, userStatusesById } = result;\n\n global = getGlobal();\n global = updateUsers(global, buildCollectionByKey(updatedUsers, 'id'));\n global = addUserStatuses(global, userStatusesById);\n setGlobal(global);\n}\n\nfunction loadTopMessages(chat: ApiChat) {\n return callApi('fetchMessages', {\n chat,\n threadId: MAIN_THREAD_ID,\n offsetId: chat.lastReadInboxMessageId,\n addOffset: -(Math.round(MESSAGE_LIST_SLICE / 2) + 1),\n limit: MESSAGE_LIST_SLICE,\n });\n}\n","import {\n addReducer, getDispatch, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { ApiUser } from '../../../api/types';\nimport { ManagementProgress } from '../../../types';\n\nimport { debounce, throttle } from '../../../util/schedulers';\nimport { buildCollectionByKey, pick, unique } from '../../../util/iteratees';\nimport { isUserBot, isUserId } from '../../helpers';\nimport { callApi } from '../../../api/gramjs';\nimport { selectChat, selectCurrentMessageList, selectUser } from '../../selectors';\nimport {\n addChats, addUsers, replaceUserStatuses, updateChat, updateManagementProgress, updateUser, updateUsers,\n updateUserSearch, updateUserSearchFetchingStatus,\n} from '../../reducers';\nimport { getServerTime } from '../../../util/serverTime';\n\nconst runDebouncedForFetchFullUser = debounce((cb) => cb(), 500, false, true);\nconst TOP_PEERS_REQUEST_COOLDOWN = 60; // 1 min\nconst runThrottledForSearch = throttle((cb) => cb(), 500, false);\n\naddReducer('loadFullUser', (global, actions, payload) => {\n const { userId } = payload!;\n const user = selectUser(global, userId);\n if (!user) {\n return;\n }\n\n const { id, accessHash } = user;\n\n runDebouncedForFetchFullUser(() => callApi('fetchFullUser', { id, accessHash }));\n});\n\naddReducer('loadUser', (global, actions, payload) => {\n const { userId } = payload!;\n const user = selectUser(global, userId);\n if (!user) {\n return;\n }\n\n (async () => {\n const result = await callApi('fetchUsers', { users: [user] });\n if (!result) {\n return;\n }\n\n const { users, userStatusesById } = result;\n\n global = getGlobal();\n\n global = updateUsers(global, buildCollectionByKey(users, 'id'));\n setGlobal(replaceUserStatuses(global, {\n ...global.users.statusesById,\n ...userStatusesById,\n }));\n\n setGlobal(global);\n })();\n});\n\naddReducer('loadTopUsers', (global) => {\n const { topPeers: { lastRequestedAt } } = global;\n\n if (!lastRequestedAt || getServerTime(global.serverTimeOffset) - lastRequestedAt > TOP_PEERS_REQUEST_COOLDOWN) {\n void loadTopUsers();\n }\n});\n\naddReducer('loadContactList', () => {\n void loadContactList();\n});\n\naddReducer('loadCurrentUser', () => {\n void callApi('fetchCurrentUser');\n});\n\naddReducer('loadCommonChats', (global) => {\n const { chatId } = selectCurrentMessageList(global) || {};\n const user = chatId ? selectUser(global, chatId) : undefined;\n if (!user || isUserBot(user) || user.commonChats?.isFullyLoaded) {\n return;\n }\n\n (async () => {\n const maxId = user.commonChats?.maxId;\n const result = await callApi('fetchCommonChats', user.id, user.accessHash!, maxId);\n if (!result) {\n return;\n }\n\n const { chats, chatIds, isFullyLoaded } = result;\n\n global = getGlobal();\n if (chats.length) {\n global = addChats(global, buildCollectionByKey(chats, 'id'));\n }\n global = updateUser(global, user.id, {\n commonChats: {\n maxId: chatIds.length ? chatIds[chatIds.length - 1] : '0',\n ids: unique((user.commonChats?.ids || []).concat(chatIds)),\n isFullyLoaded,\n },\n });\n setGlobal(global);\n })();\n});\n\naddReducer('updateContact', (global, actions, payload) => {\n const {\n userId, isMuted, firstName, lastName,\n } = payload!;\n\n void updateContact(userId, isMuted, firstName, lastName);\n});\n\naddReducer('deleteContact', (global, actions, payload) => {\n const { userId } = payload!;\n\n void deleteContact(userId);\n});\n\nasync function loadTopUsers() {\n const result = await callApi('fetchTopUsers');\n if (!result) {\n return;\n }\n\n const { ids, users } = result;\n\n let global = getGlobal();\n global = addUsers(global, buildCollectionByKey(users, 'id'));\n global = {\n ...global,\n topPeers: {\n ...global.topPeers,\n userIds: ids,\n lastRequestedAt: getServerTime(global.serverTimeOffset),\n },\n };\n setGlobal(global);\n}\n\nasync function loadContactList() {\n const contactList = await callApi('fetchContactList');\n if (!contactList) {\n return;\n }\n\n let global = addUsers(getGlobal(), buildCollectionByKey(contactList.users, 'id'));\n global = addChats(global, buildCollectionByKey(contactList.chats, 'id'));\n\n // Sort contact list by Last Name (or First Name), with latin names being placed first\n const getCompareString = (user: ApiUser) => (user.lastName || user.firstName || '');\n const collator = new Intl.Collator('en-US');\n\n const sortedUsers = contactList.users.sort((a, b) => (\n collator.compare(getCompareString(a), getCompareString(b))\n )).filter((user) => !user.isSelf);\n\n setGlobal({\n ...global,\n contactList: {\n userIds: sortedUsers.map((user) => user.id),\n },\n });\n}\n\nasync function updateContact(\n userId: string,\n isMuted: boolean,\n firstName: string,\n lastName?: string,\n) {\n const global = getGlobal();\n const user = selectUser(global, userId);\n if (!user) {\n return;\n }\n\n getDispatch().updateChatMutedState({ chatId: userId, isMuted });\n\n setGlobal(updateManagementProgress(getGlobal(), ManagementProgress.InProgress));\n\n let result;\n if (user.phoneNumber) {\n result = await callApi('updateContact', { phone: user.phoneNumber, firstName, lastName });\n } else {\n const { id, accessHash } = user;\n result = await callApi('addContact', {\n id,\n accessHash,\n phoneNumber: '',\n firstName,\n lastName,\n });\n }\n\n if (result) {\n setGlobal(updateUser(\n getGlobal(),\n user.id,\n {\n firstName,\n lastName,\n },\n ));\n }\n\n setGlobal(updateManagementProgress(getGlobal(), ManagementProgress.Complete));\n}\n\nasync function deleteContact(userId: string) {\n const global = getGlobal();\n const user = selectUser(global, userId);\n\n if (!user) {\n return;\n }\n\n const { id, accessHash } = user;\n\n await callApi('deleteContact', { id, accessHash });\n}\n\naddReducer('loadProfilePhotos', (global, actions, payload) => {\n const { profileId } = payload!;\n const isPrivate = isUserId(profileId);\n const user = isPrivate ? selectUser(global, profileId) : undefined;\n const chat = !isPrivate ? selectChat(global, profileId) : undefined;\n\n if (!user && !chat) {\n return;\n }\n\n (async () => {\n const result = await callApi('fetchProfilePhotos', user, chat);\n if (!result || !result.photos) {\n return;\n }\n\n let newGlobal = getGlobal();\n if (isPrivate) {\n newGlobal = updateUser(newGlobal, profileId, { photos: result.photos });\n } else {\n newGlobal = addUsers(newGlobal, buildCollectionByKey(result.users!, 'id'));\n newGlobal = updateChat(newGlobal, profileId, { photos: result.photos });\n }\n\n setGlobal(newGlobal);\n })();\n});\n\naddReducer('setUserSearchQuery', (global, actions, payload) => {\n const { query } = payload!;\n\n if (!query) return;\n\n void runThrottledForSearch(() => {\n searchUsers(query);\n });\n});\n\naddReducer('addContact', (global, actions, payload) => {\n const { userId } = payload!;\n const user = selectUser(global, userId);\n if (!user) {\n return;\n }\n\n void callApi('addContact', pick(user, ['id', 'accessHash', 'firstName', 'lastName', 'phoneNumber']));\n});\n\nasync function searchUsers(query: string) {\n const result = await callApi('searchChats', { query });\n\n let global = getGlobal();\n const currentSearchQuery = global.userSearch.query;\n\n if (!result || !currentSearchQuery || (query !== currentSearchQuery)) {\n setGlobal(updateUserSearchFetchingStatus(global, false));\n return;\n }\n\n const { localUsers, globalUsers } = result;\n\n let localUserIds;\n let globalUserIds;\n if (localUsers.length) {\n global = addUsers(global, buildCollectionByKey(localUsers, 'id'));\n localUserIds = localUsers.map(({ id }) => id);\n }\n if (globalUsers.length) {\n global = addUsers(global, buildCollectionByKey(globalUsers, 'id'));\n globalUserIds = globalUsers.map(({ id }) => id);\n }\n\n global = updateUserSearchFetchingStatus(global, false);\n global = updateUserSearch(global, { localUserIds, globalUserIds });\n\n setGlobal(global);\n}\n","import { GlobalState } from '../../global/types';\nimport { InlineBotSettings } from '../../types';\n\nexport function replaceInlineBotSettings(\n global: GlobalState, username: string, inlineBotSettings: InlineBotSettings | false,\n): GlobalState {\n return {\n ...global,\n inlineBots: {\n ...global.inlineBots,\n byUsername: {\n ...global.inlineBots.byUsername,\n [username]: inlineBotSettings,\n },\n },\n };\n}\n\nexport function replaceInlineBotsIsLoading(global: GlobalState, isLoading: boolean): GlobalState {\n return {\n ...global,\n inlineBots: {\n ...global.inlineBots,\n isLoading,\n },\n };\n}\n","import {\n addReducer, getDispatch, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { ApiChat, ApiContact, ApiUser } from '../../../api/types';\nimport { InlineBotSettings } from '../../../types';\n\nimport {\n RE_TG_LINK, RE_TME_LINK,\n} from '../../../config';\nimport { callApi } from '../../../api/gramjs';\nimport {\n selectChat, selectChatBot, selectChatMessage, selectCurrentChat, selectCurrentMessageList,\n selectReplyingToId, selectSendAs, selectUser,\n} from '../../selectors';\nimport { addChats, addUsers, removeBlockedContact } from '../../reducers';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport { debounce } from '../../../util/schedulers';\nimport { replaceInlineBotSettings, replaceInlineBotsIsLoading } from '../../reducers/bots';\nimport { getServerTime } from '../../../util/serverTime';\n\nconst TOP_PEERS_REQUEST_COOLDOWN = 60; // 1 min\nconst runDebouncedForSearch = debounce((cb) => cb(), 500, false);\n\naddReducer('clickInlineButton', (global, actions, payload) => {\n const { button } = payload;\n\n switch (button.type) {\n case 'command':\n actions.sendBotCommand({ command: button.value });\n break;\n case 'url':\n if (button.value.match(RE_TME_LINK) || button.value.match(RE_TG_LINK)) {\n actions.openTelegramLink({ url: button.value });\n } else {\n actions.toggleSafeLinkModal({ url: button.value });\n }\n break;\n case 'callback': {\n const chat = selectCurrentChat(global);\n if (!chat) {\n return;\n }\n\n void answerCallbackButton(chat, button.messageId, button.value);\n break;\n }\n case 'requestPoll':\n actions.openPollModal();\n break;\n case 'requestSelfContact': {\n const user = global.currentUserId ? selectUser(global, global.currentUserId) : undefined;\n if (!user) {\n return;\n }\n actions.showDialog({\n data: {\n phoneNumber: user.phoneNumber,\n firstName: user.firstName,\n lastName: user.lastName,\n userId: user.id,\n } as ApiContact,\n });\n break;\n }\n case 'buy': {\n const chat = selectCurrentChat(global);\n const { messageId, value } = button;\n if (!chat) {\n return;\n }\n\n if (value) {\n actions.getReceipt({ receiptMessageId: value, chatId: chat.id, messageId });\n } else {\n actions.getPaymentForm({ chat, messageId });\n actions.setInvoiceMessageInfo(selectChatMessage(global, chat.id, messageId));\n actions.openPaymentModal({ chatId: chat.id, messageId });\n }\n break;\n }\n }\n});\n\naddReducer('sendBotCommand', (global, actions, payload) => {\n const { command, chatId } = payload;\n const { currentUserId } = global;\n const chat = chatId ? selectChat(global, chatId) : selectCurrentChat(global);\n const currentMessageList = selectCurrentMessageList(global);\n\n if (!currentUserId || !chat || !currentMessageList) {\n return;\n }\n\n const { threadId } = currentMessageList;\n actions.setReplyingToId({ messageId: undefined });\n actions.clearWebPagePreview({ chatId: chat.id, threadId, value: false });\n\n void sendBotCommand(\n chat, currentUserId, command, selectReplyingToId(global, chat.id, threadId), selectSendAs(global, chatId),\n );\n});\n\naddReducer('restartBot', (global, actions, payload) => {\n const { chatId } = payload;\n const { currentUserId } = global;\n const chat = selectCurrentChat(global);\n const bot = currentUserId && selectChatBot(global, chatId);\n if (!currentUserId || !chat || !bot) {\n return;\n }\n\n (async () => {\n const result = await callApi('unblockContact', bot.id, bot.accessHash);\n if (!result) {\n return;\n }\n\n setGlobal(removeBlockedContact(getGlobal(), bot.id));\n void sendBotCommand(chat, currentUserId, '/start', undefined, selectSendAs(global, chatId));\n })();\n});\n\naddReducer('loadTopInlineBots', (global) => {\n const { lastRequestedAt } = global.topInlineBots;\n\n if (lastRequestedAt && getServerTime(global.serverTimeOffset) - lastRequestedAt < TOP_PEERS_REQUEST_COOLDOWN) {\n return;\n }\n\n (async () => {\n const result = await callApi('fetchTopInlineBots');\n if (!result) {\n return;\n }\n\n const { ids, users } = result;\n\n let newGlobal = getGlobal();\n newGlobal = addUsers(newGlobal, buildCollectionByKey(users, 'id'));\n newGlobal = {\n ...newGlobal,\n topInlineBots: {\n ...newGlobal.topInlineBots,\n userIds: ids,\n lastRequestedAt: getServerTime(global.serverTimeOffset),\n },\n };\n setGlobal(newGlobal);\n })();\n});\n\naddReducer('queryInlineBot', ((global, actions, payload) => {\n const {\n chatId, username, query, offset,\n } = payload;\n\n (async () => {\n let inlineBotData = global.inlineBots.byUsername[username];\n\n if (inlineBotData === false) {\n return;\n }\n\n if (inlineBotData === undefined) {\n const { user: inlineBot, chat } = await callApi('fetchInlineBot', { username }) || {};\n global = getGlobal();\n if (!inlineBot || !chat) {\n setGlobal(replaceInlineBotSettings(global, username, false));\n return;\n }\n\n global = addUsers(global, { [inlineBot.id]: inlineBot });\n global = addChats(global, { [chat.id]: chat });\n inlineBotData = {\n id: inlineBot.id,\n query: '',\n offset: '',\n switchPm: undefined,\n canLoadMore: true,\n results: [],\n };\n\n global = replaceInlineBotSettings(global, username, inlineBotData);\n setGlobal(global);\n }\n\n if (query === inlineBotData.query && !inlineBotData.canLoadMore) {\n return;\n }\n\n void runDebouncedForSearch(() => {\n searchInlineBot({\n username,\n inlineBotData: inlineBotData as InlineBotSettings,\n chatId,\n query,\n offset,\n });\n });\n })();\n}));\n\naddReducer('sendInlineBotResult', (global, actions, payload) => {\n const { id, queryId } = payload;\n const currentMessageList = selectCurrentMessageList(global);\n\n if (!currentMessageList || !id) {\n return;\n }\n\n const { chatId, threadId } = currentMessageList;\n\n const chat = selectChat(global, chatId)!;\n\n actions.setReplyingToId({ messageId: undefined });\n actions.clearWebPagePreview({ chatId, threadId, value: false });\n\n void callApi('sendInlineBotResult', {\n chat,\n resultId: id,\n queryId,\n replyingTo: selectReplyingToId(global, chatId, threadId),\n sendAs: selectSendAs(global, chatId),\n });\n});\n\naddReducer('resetInlineBot', (global, actions, payload) => {\n const { username } = payload;\n\n let inlineBotData = global.inlineBots.byUsername[username];\n\n if (!inlineBotData) {\n return;\n }\n\n inlineBotData = {\n id: inlineBotData.id,\n query: '',\n offset: '',\n switchPm: undefined,\n canLoadMore: true,\n results: [],\n };\n\n setGlobal(replaceInlineBotSettings(global, username, inlineBotData));\n});\n\naddReducer('startBot', (global, actions, payload) => {\n const { botId, param } = payload;\n\n const bot = selectUser(global, botId);\n if (!bot) {\n return;\n }\n\n (async () => {\n await callApi('startBot', {\n bot,\n startParam: param,\n });\n })();\n});\n\nasync function searchInlineBot({\n username,\n inlineBotData,\n chatId,\n query,\n offset,\n}: {\n username: string;\n inlineBotData: InlineBotSettings;\n chatId: string;\n query: string;\n offset?: string;\n}) {\n let global = getGlobal();\n const bot = selectUser(global, inlineBotData.id);\n const chat = selectChat(global, chatId);\n if (!bot || !chat) {\n return;\n }\n\n const shouldReplaceSettings = inlineBotData.query !== query;\n global = replaceInlineBotsIsLoading(global, true);\n global = replaceInlineBotSettings(global, username, {\n ...inlineBotData,\n query,\n ...(shouldReplaceSettings && { offset: undefined, results: [] }),\n });\n setGlobal(global);\n\n const result = await callApi('fetchInlineBotResults', {\n bot,\n chat,\n query,\n offset: shouldReplaceSettings ? undefined : offset,\n });\n\n const newInlineBotData = global.inlineBots.byUsername[username];\n global = replaceInlineBotsIsLoading(getGlobal(), false);\n if (!result || !newInlineBotData || query !== newInlineBotData.query) {\n setGlobal(global);\n return;\n }\n\n const currentIds = new Set((newInlineBotData.results || []).map((data) => data.id));\n const newResults = result.results.filter((data) => !currentIds.has(data.id));\n\n global = replaceInlineBotSettings(global, username, {\n ...newInlineBotData,\n help: result.help,\n ...(newResults.length && { isGallery: result.isGallery }),\n ...(result.switchPm && { switchPm: result.switchPm }),\n canLoadMore: result.results.length > 0 && Boolean(result.nextOffset),\n results: newInlineBotData.offset === '' || newInlineBotData.offset === result.nextOffset\n ? result.results\n : (newInlineBotData.results || []).concat(newResults),\n offset: newResults.length ? result.nextOffset : '',\n });\n\n setGlobal(global);\n}\n\nasync function sendBotCommand(\n chat: ApiChat, currentUserId: string, command: string, replyingTo?: number, sendAs?: ApiChat | ApiUser,\n) {\n await callApi('sendMessage', {\n chat,\n text: command,\n replyingTo,\n sendAs,\n });\n}\n\nasync function answerCallbackButton(chat: ApiChat, messageId: number, data: string) {\n const result = await callApi('answerCallbackButton', {\n chatId: chat.id,\n accessHash: chat.accessHash,\n messageId,\n data,\n });\n\n if (!result) {\n return;\n }\n\n const { showDialog, showNotification, toggleSafeLinkModal } = getDispatch();\n const { message, alert: isError, url } = result;\n\n if (isError) {\n showDialog({ data: { message: message || 'Error' } });\n } else if (message) {\n showNotification({ message });\n } else if (url) {\n toggleSafeLinkModal({ url });\n }\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { callApi } from '../../../api/gramjs';\nimport { replaceSettings, updateTwoFaSettings } from '../../reducers';\n\naddReducer('loadPasswordInfo', () => {\n (async () => {\n const result = await callApi('getPasswordInfo');\n if (!result) {\n return;\n }\n\n let global = getGlobal();\n global = replaceSettings(global, { hasPassword: result.hasPassword });\n global = updateTwoFaSettings(global, { hint: result.hint });\n setGlobal(global);\n })();\n});\n\naddReducer('checkPassword', (global, actions, payload) => {\n const { currentPassword, onSuccess } = payload;\n\n setGlobal(updateTwoFaSettings(global, { isLoading: true, error: undefined }));\n\n (async () => {\n const isSuccess = await callApi('checkPassword', currentPassword);\n\n setGlobal(updateTwoFaSettings(getGlobal(), { isLoading: false }));\n\n if (isSuccess) {\n onSuccess();\n }\n })();\n});\n\naddReducer('clearPassword', (global, actions, payload) => {\n const { currentPassword, onSuccess } = payload;\n\n setGlobal(updateTwoFaSettings(global, { isLoading: true, error: undefined }));\n\n (async () => {\n const isSuccess = await callApi('clearPassword', currentPassword);\n\n setGlobal(updateTwoFaSettings(getGlobal(), { isLoading: false }));\n\n if (isSuccess) {\n onSuccess();\n }\n })();\n});\n\naddReducer('updatePassword', (global, actions, payload) => {\n const {\n currentPassword, password, hint, email, onSuccess,\n } = payload;\n\n setGlobal(updateTwoFaSettings(global, { isLoading: true, error: undefined }));\n\n (async () => {\n const isSuccess = await callApi('updatePassword', currentPassword, password, hint, email);\n\n setGlobal(updateTwoFaSettings(getGlobal(), { isLoading: false }));\n\n if (isSuccess) {\n onSuccess();\n }\n })();\n});\n\naddReducer('updateRecoveryEmail', (global, actions, payload) => {\n const {\n currentPassword, email, onSuccess,\n } = payload;\n\n setGlobal(updateTwoFaSettings(global, { isLoading: true, error: undefined }));\n\n (async () => {\n const isSuccess = await callApi('updateRecoveryEmail', currentPassword, email);\n\n setGlobal(updateTwoFaSettings(getGlobal(), { isLoading: false, waitingEmailCodeLength: undefined }));\n\n if (isSuccess) {\n onSuccess();\n }\n })();\n});\n\naddReducer('provideTwoFaEmailCode', (global, actions, payload) => {\n const { code } = payload;\n\n void callApi('provideRecoveryEmailCode', code);\n});\n\naddReducer('clearTwoFaError', (global) => {\n return updateTwoFaSettings(global, { error: undefined });\n});\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { PaymentStep } from '../../../types';\nimport { ApiChat } from '../../../api/types';\n\nimport {\n selectPaymentMessageId,\n selectPaymentRequestId,\n selectProviderPublishableKey,\n selectStripeCredentials,\n selectChatMessage,\n selectPaymentChatId,\n selectChat,\n selectPaymentFormId,\n} from '../../selectors';\nimport { callApi } from '../../../api/gramjs';\nimport { getStripeError } from '../../helpers';\nimport { buildQueryString } from '../../../util/requestQuery';\n\nimport {\n updateShippingOptions,\n setPaymentStep,\n setRequestInfoId,\n setPaymentForm,\n setStripeCardInfo,\n setInvoiceMessageInfo,\n setReceipt,\n clearPayment,\n closeInvoice,\n} from '../../reducers';\n\naddReducer('validateRequestedInfo', (global, actions, payload) => {\n const { requestInfo, saveInfo } = payload;\n const chatId = selectPaymentChatId(global);\n const chat = chatId && selectChat(global, chatId);\n const messageId = selectPaymentMessageId(global);\n if (!chat || !messageId) {\n return;\n }\n void validateRequestedInfo(chat, messageId, requestInfo, saveInfo);\n});\n\nasync function validateRequestedInfo(chat: ApiChat, messageId: number, requestInfo: any, shouldSave?: true) {\n const result = await callApi('validateRequestedInfo', {\n chat, messageId, requestInfo, shouldSave,\n });\n if (!result) {\n return;\n }\n\n const { id, shippingOptions } = result;\n if (!id) {\n return;\n }\n\n let global = setRequestInfoId(getGlobal(), id);\n if (shippingOptions) {\n global = updateShippingOptions(global, shippingOptions);\n global = setPaymentStep(global, PaymentStep.Shipping);\n } else {\n global = setPaymentStep(global, PaymentStep.PaymentInfo);\n }\n setGlobal(global);\n}\n\naddReducer('getPaymentForm', (global, actions, payload) => {\n const { chat, messageId } = payload;\n if (!chat || !messageId) {\n return;\n }\n void getPaymentForm(chat, messageId);\n});\n\nasync function getPaymentForm(chat: ApiChat, messageId: number) {\n const result = await callApi('getPaymentForm', { chat, messageId });\n if (!result) {\n return;\n }\n let global = setPaymentForm(getGlobal(), result);\n let step = PaymentStep.PaymentInfo;\n if (global.payment.invoice\n && (global.payment.invoice.shippingAddressRequested\n || global.payment.invoice.nameRequested\n || global.payment.invoice.phoneRequested\n || global.payment.invoice.emailRequested)) {\n step = PaymentStep.ShippingInfo;\n }\n global = setPaymentStep(global, step);\n setGlobal(global);\n}\n\naddReducer('getReceipt', (global, actions, payload) => {\n const { receiptMessageId, chatId, messageId } = payload;\n const chat = chatId && selectChat(global, chatId);\n if (!messageId || !receiptMessageId || !chat) {\n return;\n }\n\n void getReceipt(chat, messageId, receiptMessageId);\n});\n\nasync function getReceipt(chat: ApiChat, messageId: number, receiptMessageId: number) {\n const result = await callApi('getReceipt', chat, receiptMessageId);\n if (!result) {\n return;\n }\n\n let global = getGlobal();\n const message = selectChatMessage(global, chat.id, messageId);\n global = setReceipt(global, result, message);\n setGlobal(global);\n}\n\naddReducer('clearPaymentError', (global) => {\n setGlobal({\n ...global,\n payment: {\n ...global.payment,\n error: undefined,\n },\n });\n});\n\naddReducer('clearReceipt', (global) => {\n setGlobal({\n ...global,\n payment: {\n ...global.payment,\n receipt: undefined,\n },\n });\n});\n\naddReducer('sendCredentialsInfo', (global, actions, payload) => {\n const publishableKey = selectProviderPublishableKey(global);\n if (!publishableKey) {\n return;\n }\n const { credentials } = payload;\n const { data } = credentials;\n void sendStripeCredentials(data, publishableKey);\n});\n\naddReducer('sendPaymentForm', (global, actions, payload) => {\n const { shippingOptionId, saveCredentials } = payload;\n const chatId = selectPaymentChatId(global);\n const chat = chatId && selectChat(global, chatId);\n const messageId = selectPaymentMessageId(global);\n const formId = selectPaymentFormId(global);\n const requestInfoId = selectPaymentRequestId(global);\n const publishableKey = selectProviderPublishableKey(global);\n const stripeCredentials = selectStripeCredentials(global);\n if (!chat || !messageId || !publishableKey || !formId) {\n return;\n }\n\n void sendPaymentForm(chat, messageId, formId, {\n save: saveCredentials,\n data: stripeCredentials,\n }, requestInfoId, shippingOptionId);\n});\n\nasync function sendStripeCredentials(\n data: {\n cardNumber: string;\n cardholder?: string;\n expiryMonth: string;\n expiryYear: string;\n cvv: string;\n country: string;\n zip: string;\n },\n publishableKey: string,\n) {\n const query = buildQueryString({\n 'card[number]': data.cardNumber,\n 'card[exp_month]': data.expiryMonth,\n 'card[exp_year]': data.expiryYear,\n 'card[cvc]': data.cvv,\n 'card[address_zip]': data.zip,\n 'card[address_country]': data.country,\n });\n\n const response = await fetch(`https://api.stripe.com/v1/tokens${query}`, {\n method: 'POST',\n credentials: 'same-origin',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n Authorization: `Bearer ${publishableKey}`,\n },\n });\n const result = await response.json();\n if (result.error) {\n const error = getStripeError(result.error);\n const global = getGlobal();\n setGlobal({\n ...global,\n payment: {\n ...global.payment,\n error: {\n ...error,\n },\n },\n });\n return;\n }\n let global = setStripeCardInfo(getGlobal(), {\n type: result.type,\n id: result.id,\n });\n global = setPaymentStep(global, PaymentStep.Checkout);\n setGlobal(global);\n}\n\nasync function sendPaymentForm(\n chat: ApiChat,\n messageId: number,\n formId: string,\n credentials: any,\n requestedInfoId?: string,\n shippingOptionId?: string,\n) {\n const result = await callApi('sendPaymentForm', {\n chat, messageId, formId, credentials, requestedInfoId, shippingOptionId,\n });\n if (result) {\n const global = clearPayment(getGlobal());\n setGlobal(closeInvoice(global));\n }\n}\n\naddReducer('setPaymentStep', (global, actions, payload = {}) => {\n return setPaymentStep(global, payload.step || PaymentStep.ShippingInfo);\n});\n\naddReducer('setInvoiceMessageInfo', (global, actions, payload) => {\n return setInvoiceMessageInfo(global, payload);\n});\n","export function buildQueryString(data: Record) {\n const query = Object.keys(data).map((k) => `${k}=${data[k]}`).join('&');\n return query.length > 0 ? `?${query}` : '';\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiUpdate, MAIN_THREAD_ID } from '../../../api/types';\n\nimport { ARCHIVED_FOLDER_ID, MAX_ACTIVE_PINNED_CHATS } from '../../../config';\nimport { pick } from '../../../util/iteratees';\nimport { closeMessageNotifications, notifyAboutNewMessage } from '../../../util/notifications';\nimport { updateAppBadge } from '../../../util/appBadge';\nimport {\n updateChat,\n updateChatListIds,\n updateChatListType,\n replaceThreadParam,\n leaveChat,\n} from '../../reducers';\nimport {\n selectChat,\n selectCommonBoxChatId,\n selectIsChatListed,\n selectChatListType,\n selectCurrentMessageList,\n selectCountNotMutedUnread,\n} from '../../selectors';\nimport { throttle } from '../../../util/schedulers';\n\nconst TYPING_STATUS_CLEAR_DELAY = 6000; // 6 seconds\n// Enough to animate and mark as read in Message List\nconst CURRENT_CHAT_UNREAD_DELAY = 1500;\n\nconst runThrottledForUpdateAppBadge = throttle((cb) => cb(), 500, true);\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n switch (update['@type']) {\n case 'updateChat': {\n if (!update.noTopChatsRequest && !selectIsChatListed(global, update.id)) {\n // Chat can appear in dialogs list.\n actions.loadTopChats();\n }\n\n const newGlobal = updateChat(global, update.id, update.chat, update.newProfilePhoto);\n setGlobal(newGlobal);\n\n runThrottledForUpdateAppBadge(() => updateAppBadge(selectCountNotMutedUnread(getGlobal())));\n\n if (update.chat.id) {\n closeMessageNotifications({\n chatId: update.chat.id,\n lastReadInboxMessageId: update.chat.lastReadInboxMessageId,\n });\n }\n break;\n }\n\n case 'updateChatJoin': {\n const listType = selectChatListType(global, update.id);\n if (!listType) {\n break;\n }\n\n global = updateChatListIds(global, listType, [update.id]);\n global = updateChat(global, update.id, { isNotJoined: false });\n setGlobal(global);\n\n const chat = selectChat(global, update.id);\n if (chat) {\n actions.requestChatUpdate({ chatId: chat.id });\n }\n break;\n }\n\n case 'updateChatLeave': {\n setGlobal(leaveChat(global, update.id));\n\n break;\n }\n\n case 'updateChatInbox': {\n setGlobal(updateChat(global, update.id, update.chat));\n\n runThrottledForUpdateAppBadge(() => updateAppBadge(selectCountNotMutedUnread(getGlobal())));\n\n break;\n }\n\n case 'updateChatTypingStatus': {\n const { id, typingStatus } = update;\n setGlobal(updateChat(global, id, { typingStatus }));\n\n setTimeout(() => {\n const newGlobal = getGlobal();\n const chat = selectChat(newGlobal, id);\n if (chat && typingStatus && chat.typingStatus && chat.typingStatus.timestamp === typingStatus.timestamp) {\n setGlobal(updateChat(newGlobal, id, { typingStatus: undefined }));\n }\n }, TYPING_STATUS_CLEAR_DELAY);\n\n break;\n }\n\n case 'newMessage': {\n const { message } = update;\n const { chatId: currentChatId, threadId, type: messageListType } = selectCurrentMessageList(global) || {};\n\n if (message.senderId === global.currentUserId && !message.isFromScheduled) {\n return;\n }\n\n const chat = selectChat(global, update.chatId);\n if (!chat) {\n return;\n }\n\n const isActiveChat = (\n messageListType === 'thread'\n && threadId === MAIN_THREAD_ID\n && update.chatId === currentChatId\n );\n\n if (isActiveChat) {\n setTimeout(() => {\n actions.requestChatUpdate({ chatId: update.chatId });\n }, CURRENT_CHAT_UNREAD_DELAY);\n } else {\n setGlobal(updateChat(global, update.chatId, {\n unreadCount: chat.unreadCount ? chat.unreadCount + 1 : 1,\n ...(update.message.hasUnreadMention && {\n unreadMentionsCount: chat.unreadMentionsCount ? chat.unreadMentionsCount + 1 : 1,\n }),\n }));\n }\n\n updateAppBadge(selectCountNotMutedUnread(getGlobal()));\n notifyAboutNewMessage({\n chat,\n message,\n });\n\n break;\n }\n\n case 'updateCommonBoxMessages':\n case 'updateChannelMessages': {\n const { ids, messageUpdate } = update;\n if (messageUpdate.hasUnreadMention !== false) {\n return;\n }\n\n ids.forEach((id) => {\n const chatId = ('channelId' in update ? update.channelId : selectCommonBoxChatId(global, id))!;\n const chat = selectChat(global, chatId);\n if (chat?.unreadMentionsCount) {\n global = updateChat(global, chatId, {\n unreadMentionsCount: chat.unreadMentionsCount - 1,\n });\n }\n });\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateChatFullInfo': {\n const { fullInfo } = update;\n const targetChat = global.chats.byId[update.id];\n if (!targetChat) {\n return;\n }\n\n setGlobal(updateChat(global, update.id, {\n fullInfo: {\n ...targetChat.fullInfo,\n ...fullInfo,\n },\n }));\n\n break;\n }\n\n case 'updatePinnedChatIds': {\n const { ids, folderId } = update;\n\n const listType = folderId === ARCHIVED_FOLDER_ID ? 'archived' : 'active';\n\n global = {\n ...global,\n chats: {\n ...global.chats,\n orderedPinnedIds: {\n ...global.chats.orderedPinnedIds,\n [listType]: ids.length ? ids : undefined,\n },\n },\n };\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateChatPinned': {\n const { id, isPinned } = update;\n const listType = selectChatListType(global, id);\n if (listType) {\n const { [listType]: orderedPinnedIds } = global.chats.orderedPinnedIds;\n\n let newOrderedPinnedIds = orderedPinnedIds || [];\n if (!isPinned) {\n newOrderedPinnedIds = newOrderedPinnedIds.filter((pinnedId) => pinnedId !== id);\n } else if (!newOrderedPinnedIds.includes(id)) {\n // When moving pinned chats to archive, active ordered pinned ids don't get updated\n // (to preserve chat pinned state when it returns from archive)\n // If user already has max pinned chats, we should check for orderedIds\n // that don't point to listed chats\n if (listType === 'active' && newOrderedPinnedIds.length >= MAX_ACTIVE_PINNED_CHATS) {\n const listIds = global.chats.listIds.active;\n newOrderedPinnedIds = newOrderedPinnedIds.filter((pinnedId) => listIds && listIds.includes(pinnedId));\n }\n\n newOrderedPinnedIds = [id, ...newOrderedPinnedIds];\n }\n\n global = {\n ...global,\n chats: {\n ...global.chats,\n orderedPinnedIds: {\n ...global.chats.orderedPinnedIds,\n [listType]: newOrderedPinnedIds.length ? newOrderedPinnedIds : undefined,\n },\n },\n };\n }\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateChatListType': {\n const { id, folderId } = update;\n\n setGlobal(updateChatListType(global, id, folderId));\n\n break;\n }\n\n case 'updateChatFolder': {\n const { id, folder } = update;\n const { byId: chatFoldersById, orderedIds } = global.chatFolders;\n\n const newChatFoldersById = folder\n ? { ...chatFoldersById, [id]: folder }\n : pick(\n chatFoldersById,\n Object.keys(chatFoldersById).map(Number).filter((folderId) => folderId !== id),\n );\n\n const newOrderedIds = folder\n ? orderedIds && orderedIds.includes(id) ? orderedIds : [...(orderedIds || []), id]\n : orderedIds ? orderedIds.filter((orderedId) => orderedId !== id) : undefined;\n\n setGlobal({\n ...global,\n chatFolders: {\n ...global.chatFolders,\n byId: newChatFoldersById,\n orderedIds: newOrderedIds,\n },\n });\n\n break;\n }\n\n case 'updateChatFoldersOrder': {\n const { orderedIds } = update;\n\n setGlobal({\n ...global,\n chatFolders: {\n ...global.chatFolders,\n orderedIds,\n },\n });\n\n break;\n }\n\n case 'updateRecommendedChatFolders': {\n const { folders } = update;\n\n setGlobal({\n ...global,\n chatFolders: {\n ...global.chatFolders,\n recommended: folders,\n },\n });\n\n break;\n }\n\n case 'updateChatMembers': {\n const targetChat = global.chats.byId[update.id];\n const { replacedMembers, addedMember, deletedMemberId } = update;\n if (!targetChat) {\n return;\n }\n\n let shouldUpdate = false;\n let members = targetChat.fullInfo?.members\n ? [...targetChat.fullInfo.members]\n : [];\n\n if (replacedMembers) {\n members = replacedMembers;\n shouldUpdate = true;\n } else if (addedMember) {\n if (\n !members.length\n || !members.some((m) => m.userId === addedMember.userId)\n ) {\n members.push(addedMember);\n shouldUpdate = true;\n }\n } else if (members.length && deletedMemberId) {\n const deleteIndex = members.findIndex((m) => m.userId === deletedMemberId);\n if (deleteIndex > -1) {\n members.slice(deleteIndex, 1);\n shouldUpdate = true;\n }\n }\n\n if (shouldUpdate) {\n const adminMembers = members.filter(({ isOwner, isAdmin }) => isOwner || isAdmin);\n // TODO Kicked members?\n\n setGlobal(updateChat(global, update.id, {\n membersCount: members.length,\n fullInfo: {\n ...targetChat.fullInfo,\n members,\n adminMembers,\n },\n }));\n }\n\n break;\n }\n\n case 'deleteProfilePhotos': {\n const { chatId, ids } = update;\n const chat = global.chats.byId[chatId];\n\n if (chat?.photos) {\n setGlobal(updateChat(global, chatId, {\n photos: chat.photos.filter((photo) => !ids.includes(photo.id)),\n }));\n }\n break;\n }\n\n case 'draftMessage': {\n const {\n chatId, formattedText, date, replyingToId,\n } = update;\n const chat = global.chats.byId[chatId];\n\n if (chat) {\n global = replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'draft', formattedText);\n global = replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'replyingToId', replyingToId);\n global = updateChat(global, chatId, { draftDate: date });\n\n setGlobal(global);\n }\n break;\n }\n\n case 'showInvite': {\n const { data } = update;\n\n actions.showDialog({ data });\n break;\n }\n }\n});\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport {\n ApiUpdate, ApiMessage, ApiPollResult, ApiThreadInfo, MAIN_THREAD_ID,\n} from '../../../api/types';\n\nimport { unique } from '../../../util/iteratees';\nimport {\n updateChat,\n deleteChatMessages,\n updateChatMessage,\n updateListedIds,\n addViewportId,\n updateThreadInfo,\n replaceThreadParam,\n updateScheduledMessage,\n deleteChatScheduledMessages,\n updateThreadUnreadFromForwardedMessage,\n} from '../../reducers';\nimport { GlobalActions, GlobalState } from '../../../global/types';\nimport {\n selectChatMessage,\n selectChatMessages,\n selectIsViewportNewest,\n selectListedIds,\n selectChatMessageByPollId,\n selectCommonBoxChatId,\n selectIsChatListed,\n selectThreadInfo,\n selectThreadByMessage,\n selectPinnedIds,\n selectScheduledMessage,\n selectScheduledMessages,\n isMessageInCurrentMessageList,\n selectScheduledIds,\n selectCurrentMessageList,\n selectViewportIds,\n selectFirstUnreadId,\n selectChat,\n selectIsChatWithBot,\n selectIsServiceChatReady,\n} from '../../selectors';\nimport { getMessageContent, isUserId, isMessageLocal } from '../../helpers';\n\nconst ANIMATION_DELAY = 350;\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n switch (update['@type']) {\n case 'newMessage': {\n const {\n chatId, id, message, shouldForceReply,\n } = update;\n global = updateWithLocalMedia(global, chatId, id, message);\n global = updateListedAndViewportIds(global, actions, message as ApiMessage);\n\n if (message.threadInfo) {\n global = updateThreadInfo(\n global,\n message.threadInfo.chatId,\n message.threadInfo.threadId,\n message.threadInfo,\n );\n }\n\n setGlobal(global);\n\n const newMessage = selectChatMessage(global, chatId, id)!;\n\n if (isMessageInCurrentMessageList(global, chatId, message as ApiMessage)) {\n if (message.isOutgoing && !(message.content?.action)) {\n const currentMessageList = selectCurrentMessageList(global);\n if (currentMessageList) {\n // We do not use `actions.focusLastMessage` as it may be set with a delay (see below)\n actions.focusMessage({\n chatId,\n threadId: currentMessageList.threadId,\n messageId: message.id,\n noHighlight: true,\n isResizingContainer: true,\n });\n }\n }\n\n const { threadInfo } = selectThreadByMessage(global, chatId, message as ApiMessage) || {};\n if (threadInfo) {\n actions.requestThreadInfoUpdate({ chatId, threadId: threadInfo.threadId });\n }\n\n // @perf Wait until scroll animation finishes or simply rely on delivery status update (which is itself delayed)\n if (!isMessageLocal(message as ApiMessage)) {\n setTimeout(() => {\n let delayedGlobal = getGlobal();\n if (shouldForceReply) {\n delayedGlobal = replaceThreadParam(delayedGlobal, chatId, MAIN_THREAD_ID, 'replyingToId', id);\n }\n setGlobal(updateChatLastMessage(delayedGlobal, chatId, newMessage));\n }, ANIMATION_DELAY);\n }\n } else {\n setGlobal(updateChatLastMessage(getGlobal(), chatId, newMessage));\n }\n\n // Edge case: New message in an old (not loaded) chat.\n if (!selectIsChatListed(global, chatId)) {\n actions.loadTopChats();\n }\n\n break;\n }\n\n case 'newScheduledMessage': {\n const { chatId, id, message } = update;\n\n global = updateWithLocalMedia(global, chatId, id, message, true);\n\n const scheduledIds = selectScheduledIds(global, chatId) || [];\n global = replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'scheduledIds', unique([...scheduledIds, id]));\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateMessage': {\n const { chatId, id, message } = update;\n\n const currentMessage = selectChatMessage(global, chatId, id);\n if (!currentMessage) {\n return;\n }\n\n global = updateWithLocalMedia(global, chatId, id, message);\n\n const newMessage = selectChatMessage(global, chatId, id)!;\n if (message.threadInfo) {\n global = updateThreadInfo(\n global,\n message.threadInfo.chatId,\n message.threadInfo.threadId,\n message.threadInfo,\n );\n }\n global = updateChatLastMessage(global, chatId, newMessage);\n\n setGlobal(global);\n\n // Scroll down if bot message height is changed with an updated inline keyboard.\n // A drawback: this will scroll down even if the previous scroll was not at bottom.\n const chat = selectChat(global, chatId);\n if (\n chat\n && !message.isOutgoing\n && chat.lastMessage?.id === message.id\n && selectIsChatWithBot(global, chat)\n && isMessageInCurrentMessageList(global, chatId, message as ApiMessage)\n && selectIsViewportNewest(global, chatId, message.threadInfo?.threadId || MAIN_THREAD_ID)\n ) {\n actions.focusLastMessage();\n }\n\n break;\n }\n\n case 'updateScheduledMessage': {\n const { chatId, id, message } = update;\n\n const currentMessage = selectScheduledMessage(global, chatId, id);\n if (!currentMessage) {\n return;\n }\n\n global = updateWithLocalMedia(global, chatId, id, message, true);\n const ids = Object.keys(selectScheduledMessages(global, chatId) || {}).map(Number).sort((a, b) => b - a);\n global = replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'scheduledIds', ids);\n setGlobal(global);\n\n break;\n }\n\n case 'updateMessageSendSucceeded': {\n const { chatId, localId, message } = update;\n\n global = updateListedAndViewportIds(global, actions, message as ApiMessage);\n\n const currentMessage = selectChatMessage(global, chatId, localId);\n\n global = deleteChatMessages(global, chatId, [localId]);\n\n // Edge case for \"Send When Online\"\n if (message.isScheduled) {\n global = deleteChatScheduledMessages(global, chatId, [localId]);\n }\n\n global = updateChatMessage(global, chatId, message.id, {\n ...currentMessage,\n ...message,\n previousLocalId: localId,\n });\n\n const newMessage = selectChatMessage(global, chatId, message.id)!;\n global = updateChatLastMessage(global, chatId, newMessage);\n\n const thread = selectThreadByMessage(global, chatId, message);\n // For some reason Telegram requires to manually mark outgoing thread messages read\n if (thread?.threadInfo) {\n actions.markMessageListRead({ maxId: message.id });\n\n global = replaceThreadParam(global, chatId, thread.threadInfo.threadId, 'threadInfo', {\n ...thread.threadInfo,\n lastMessageId: message.id,\n lastReadInboxMessageId: message.id,\n });\n }\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateScheduledMessageSendSucceeded': {\n const { chatId, localId, message } = update;\n const scheduledIds = selectScheduledIds(global, chatId) || [];\n global = replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'scheduledIds', [...scheduledIds, message.id]);\n\n const currentMessage = selectScheduledMessage(global, chatId, localId);\n\n global = deleteChatScheduledMessages(global, chatId, [localId]);\n global = updateScheduledMessage(global, chatId, message.id, {\n ...currentMessage,\n ...message,\n previousLocalId: localId,\n });\n\n setGlobal(global);\n break;\n }\n\n case 'updatePinnedIds': {\n const { chatId, isPinned, messageIds } = update;\n\n const currentPinnedIds = selectPinnedIds(global, chatId) || [];\n const newPinnedIds = isPinned\n ? [...currentPinnedIds, ...messageIds].sort((a, b) => b - a)\n : currentPinnedIds.filter((id) => !messageIds.includes(id));\n\n setGlobal(replaceThreadParam(global, chatId, MAIN_THREAD_ID, 'pinnedIds', newPinnedIds));\n\n break;\n }\n\n case 'updateThreadInfo': {\n const {\n chatId, threadId, threadInfo, firstMessageId,\n } = update;\n\n const currentThreadInfo = selectThreadInfo(global, chatId, threadId);\n const newTheadInfo = {\n ...currentThreadInfo,\n ...threadInfo,\n };\n\n if (!newTheadInfo.threadId) {\n return;\n }\n\n global = updateThreadInfo(global, chatId, threadId, newTheadInfo as ApiThreadInfo);\n\n if (firstMessageId) {\n global = replaceThreadParam(global, chatId, threadId, 'firstMessageId', firstMessageId);\n }\n\n setGlobal(global);\n\n break;\n }\n\n case 'resetMessages': {\n const { id: chatId } = update;\n const messagesById = selectChatMessages(global, chatId);\n\n if (messagesById && !isUserId(chatId)) {\n global = deleteChatMessages(global, chatId, Object.keys(messagesById).map(Number));\n setGlobal(global);\n actions.loadFullChat({ chatId, force: true });\n }\n\n break;\n }\n\n case 'deleteMessages': {\n const { ids, chatId } = update;\n\n deleteMessages(chatId, ids, actions, global);\n break;\n }\n\n case 'deleteScheduledMessages': {\n const { ids, chatId } = update;\n\n deleteScheduledMessages(chatId, ids, actions, global);\n break;\n }\n\n case 'deleteHistory': {\n const { chatId } = update;\n const chatMessages = global.messages.byChatId[chatId];\n if (chatMessages) {\n const ids = Object.keys(chatMessages.byId).map(Number);\n deleteMessages(chatId, ids, actions, global);\n } else {\n actions.requestChatUpdate({ chatId });\n }\n\n break;\n }\n\n case 'updateCommonBoxMessages': {\n const { ids, messageUpdate } = update;\n\n ids.forEach((id) => {\n const chatId = selectCommonBoxChatId(global, id);\n if (chatId) {\n global = updateChatMessage(global, chatId, id, messageUpdate);\n }\n });\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateChannelMessages': {\n const { channelId, ids, messageUpdate } = update;\n\n ids.forEach((id) => {\n global = updateChatMessage(global, channelId, id, messageUpdate);\n });\n\n setGlobal(global);\n\n break;\n }\n\n case 'updateMessagePoll': {\n const { pollId, pollUpdate } = update;\n\n const message = selectChatMessageByPollId(global, pollId);\n\n if (message?.content.poll) {\n const updatedPoll = { ...message.content.poll, ...pollUpdate };\n\n // Workaround for poll update bug: `chosen` option gets reset when someone votes after current user\n const { results: updatedResults } = updatedPoll.results || {};\n if (updatedResults && !updatedResults.some(((result) => result.isChosen))) {\n const { results } = message.content.poll.results;\n const chosenAnswers = results && results.filter((result) => result.isChosen);\n if (chosenAnswers) {\n chosenAnswers.forEach((chosenAnswer) => {\n const chosenAnswerIndex = updatedResults.findIndex((result) => result.option === chosenAnswer.option);\n if (chosenAnswerIndex >= 0) {\n updatedPoll.results.results![chosenAnswerIndex].isChosen = true;\n }\n });\n }\n }\n\n setGlobal(updateChatMessage(\n global,\n message.chatId,\n message.id,\n {\n content: {\n ...message.content,\n poll: updatedPoll,\n },\n },\n ));\n }\n break;\n }\n\n case 'updateMessagePollVote': {\n const { pollId, userId, options } = update;\n const message = selectChatMessageByPollId(global, pollId);\n if (!message || !message.content.poll || !message.content.poll.results) {\n break;\n }\n\n const { poll } = message.content;\n\n const { recentVoterIds, totalVoters, results } = poll.results;\n const newRecentVoterIds = recentVoterIds ? [...recentVoterIds] : [];\n const newTotalVoters = totalVoters ? totalVoters + 1 : 1;\n const newResults = results ? [...results] : [];\n\n newRecentVoterIds.push(userId);\n\n options.forEach((option) => {\n const targetOption = newResults.find((result) => result.option === option);\n const targetOptionIndex = newResults.findIndex((result) => result.option === option);\n const updatedOption: ApiPollResult = targetOption ? { ...targetOption } : { option, votersCount: 0 };\n\n updatedOption.votersCount += 1;\n if (userId === global.currentUserId) {\n updatedOption.isChosen = true;\n }\n\n if (targetOptionIndex) {\n newResults[targetOptionIndex] = updatedOption;\n } else {\n newResults.push(updatedOption);\n }\n });\n\n setGlobal(updateChatMessage(\n global,\n message.chatId,\n message.id,\n {\n content: {\n ...message.content,\n poll: {\n ...poll,\n results: {\n ...poll.results,\n recentVoterIds: newRecentVoterIds,\n totalVoters: newTotalVoters,\n results: newResults,\n },\n },\n },\n },\n ));\n\n break;\n }\n\n case 'updateServiceNotification': {\n const { message } = update;\n\n if (selectIsServiceChatReady(global)) {\n actions.createServiceNotification({ message });\n }\n\n break;\n }\n }\n});\n\nfunction updateWithLocalMedia(\n global: GlobalState, chatId: string, id: number, message: Partial, isScheduled = false,\n) {\n // Preserve locally uploaded media.\n const currentMessage = isScheduled\n ? selectScheduledMessage(global, chatId, id)\n : selectChatMessage(global, chatId, id);\n if (currentMessage && message.content) {\n const {\n photo, video, sticker, document,\n } = getMessageContent(currentMessage);\n if (photo && message.content.photo) {\n message.content.photo.blobUrl = photo.blobUrl;\n message.content.photo.thumbnail = photo.thumbnail;\n } else if (video && message.content.video) {\n message.content.video.blobUrl = video.blobUrl;\n } else if (sticker && message.content.sticker) {\n message.content.sticker.isPreloadedGlobally = sticker.isPreloadedGlobally;\n } else if (document && message.content.document) {\n message.content.document.previewBlobUrl = document.previewBlobUrl;\n }\n }\n\n return isScheduled\n ? updateScheduledMessage(global, chatId, id, message)\n : updateChatMessage(global, chatId, id, message);\n}\n\nfunction updateThreadUnread(global: GlobalState, actions: GlobalActions, message: ApiMessage, isDeleting?: boolean) {\n const { chatId } = message;\n\n const { threadInfo } = selectThreadByMessage(global, chatId, message) || {};\n\n if (!threadInfo && message.replyToMessageId) {\n const originMessage = selectChatMessage(global, chatId, message.replyToMessageId);\n if (originMessage) {\n global = updateThreadUnreadFromForwardedMessage(global, originMessage, chatId, message.id, isDeleting);\n } else {\n actions.loadMessage({\n chatId,\n messageId: message.replyToMessageId,\n threadUpdate: {\n isDeleting,\n lastMessageId: message.id,\n },\n });\n }\n }\n\n return global;\n}\n\nfunction updateListedAndViewportIds(global: GlobalState, actions: GlobalActions, message: ApiMessage) {\n const { id, chatId } = message;\n\n const { threadInfo, firstMessageId } = selectThreadByMessage(global, chatId, message) || {};\n\n const chat = selectChat(global, chatId);\n const isUnreadChatNotLoaded = chat?.unreadCount && !selectListedIds(global, chatId, MAIN_THREAD_ID);\n\n global = updateThreadUnread(global, actions, message);\n\n if (threadInfo) {\n if (firstMessageId || !isMessageLocal(message)) {\n global = updateListedIds(global, chatId, threadInfo.threadId, [id]);\n\n if (selectIsViewportNewest(global, chatId, threadInfo.threadId)) {\n global = addViewportId(global, chatId, threadInfo.threadId, id);\n\n if (!firstMessageId) {\n global = replaceThreadParam(global, chatId, threadInfo.threadId, 'firstMessageId', message.id);\n }\n }\n }\n\n global = replaceThreadParam(global, chatId, threadInfo.threadId, 'threadInfo', {\n ...threadInfo,\n lastMessageId: message.id,\n messagesCount: threadInfo.messagesCount + 1,\n });\n }\n\n if (isUnreadChatNotLoaded) {\n return global;\n }\n\n global = updateListedIds(global, chatId, MAIN_THREAD_ID, [id]);\n\n if (selectIsViewportNewest(global, chatId, MAIN_THREAD_ID)) {\n // Always keep the first unread message in the viewport list\n const firstUnreadId = selectFirstUnreadId(global, chatId, MAIN_THREAD_ID);\n const newGlobal = addViewportId(global, chatId, MAIN_THREAD_ID, id);\n const newViewportIds = selectViewportIds(newGlobal, chatId, MAIN_THREAD_ID);\n\n if (!firstUnreadId || newViewportIds!.includes(firstUnreadId)) {\n global = newGlobal;\n }\n }\n\n return global;\n}\n\nfunction updateChatLastMessage(\n global: GlobalState,\n chatId: string,\n message: ApiMessage,\n force = false,\n) {\n const { chats } = global;\n const currentLastMessage = chats.byId[chatId]?.lastMessage;\n\n if (currentLastMessage && !force) {\n const isSameOrNewer = (\n currentLastMessage.id === message.id || currentLastMessage.id === message.previousLocalId\n ) || message.id > currentLastMessage.id;\n\n if (!isSameOrNewer) {\n return global;\n }\n }\n\n return updateChat(global, chatId, { lastMessage: message });\n}\n\nfunction findLastMessage(global: GlobalState, chatId: string) {\n const byId = selectChatMessages(global, chatId);\n const listedIds = selectListedIds(global, chatId, MAIN_THREAD_ID);\n\n if (!byId || !listedIds) {\n return undefined;\n }\n\n let i = listedIds.length;\n while (i--) {\n const message = byId[listedIds[i]];\n if (!message.isDeleting) {\n return message;\n }\n }\n\n return undefined;\n}\n\nfunction deleteMessages(chatId: string | undefined, ids: number[], actions: GlobalActions, global: GlobalState) {\n // Channel update\n\n if (chatId) {\n ids.forEach((id) => {\n global = updateChatMessage(global, chatId, id, {\n isDeleting: true,\n });\n\n const newLastMessage = findLastMessage(global, chatId);\n if (newLastMessage) {\n global = updateChatLastMessage(global, chatId, newLastMessage, true);\n }\n });\n\n setGlobal(global);\n\n actions.requestChatUpdate({ chatId });\n\n const threadIdsToUpdate: number[] = [];\n\n ids.forEach((id) => {\n const message = selectChatMessage(global, chatId, id);\n if (!message) {\n return;\n }\n\n global = updateThreadUnread(global, actions, message, true);\n\n const { threadInfo } = selectThreadByMessage(global, chatId, message) || {};\n if (threadInfo) {\n threadIdsToUpdate.push(threadInfo.threadId);\n }\n });\n\n setGlobal(global);\n\n setTimeout(() => {\n setGlobal(deleteChatMessages(getGlobal(), chatId, ids));\n\n unique(threadIdsToUpdate).forEach((threadId) => {\n actions.requestThreadInfoUpdate({ chatId, threadId });\n });\n }, ANIMATION_DELAY);\n\n return;\n }\n\n // Common box update\n\n const chatsIdsToUpdate: string[] = [];\n\n ids.forEach((id) => {\n const commonBoxChatId = selectCommonBoxChatId(global, id);\n if (commonBoxChatId) {\n chatsIdsToUpdate.push(commonBoxChatId);\n\n global = updateChatMessage(global, commonBoxChatId, id, {\n isDeleting: true,\n });\n\n const newLastMessage = findLastMessage(global, commonBoxChatId);\n if (newLastMessage) {\n global = updateChatLastMessage(global, commonBoxChatId, newLastMessage, true);\n }\n\n setTimeout(() => {\n setGlobal(deleteChatMessages(getGlobal(), commonBoxChatId, [id]));\n }, ANIMATION_DELAY);\n }\n });\n\n setGlobal(global);\n\n unique(chatsIdsToUpdate).forEach((id) => {\n actions.requestChatUpdate({ chatId: id });\n });\n}\n\nfunction deleteScheduledMessages(\n chatId: string | undefined, ids: number[], actions: GlobalActions, global: GlobalState,\n) {\n if (!chatId) {\n return;\n }\n\n ids.forEach((id) => {\n global = updateScheduledMessage(global, chatId, id, {\n isDeleting: true,\n });\n });\n\n setGlobal(global);\n\n setTimeout(() => {\n global = deleteChatScheduledMessages(getGlobal(), chatId, ids);\n const scheduledMessages = selectScheduledMessages(global, chatId);\n global = replaceThreadParam(\n global, chatId, MAIN_THREAD_ID, 'scheduledIds', Object.keys(scheduledMessages || {}).map(Number),\n );\n setGlobal(global);\n }, ANIMATION_DELAY);\n}\n","import { addReducer, getGlobal, setGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiUpdate, ApiUserStatus } from '../../../api/types';\n\nimport { deleteContact, replaceUserStatuses, updateUser } from '../../reducers';\nimport { throttle } from '../../../util/schedulers';\n\nconst STATUS_UPDATE_THROTTLE = 3000;\n\nconst flushStatusUpdatesThrottled = throttle(flushStatusUpdates, STATUS_UPDATE_THROTTLE, true);\n\nlet pendingStatusUpdates: Record = {};\n\nfunction scheduleStatusUpdate(userId: string, statusUpdate: ApiUserStatus) {\n pendingStatusUpdates[userId] = statusUpdate;\n flushStatusUpdatesThrottled();\n}\n\nfunction flushStatusUpdates() {\n const global = getGlobal();\n\n setGlobal(replaceUserStatuses(global, {\n ...global.users.statusesById,\n ...pendingStatusUpdates,\n }));\n\n pendingStatusUpdates = {};\n}\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n switch (update['@type']) {\n case 'deleteContact': {\n return deleteContact(global, update.id);\n }\n\n case 'updateUser': {\n return updateUser(global, update.id, update.user);\n }\n\n case 'updateUserStatus': {\n // Status updates come very often so we throttle them\n scheduleStatusUpdate(update.userId, update.status);\n return undefined;\n }\n\n case 'updateUserFullInfo': {\n const { id, fullInfo } = update;\n const targetUser = global.users.byId[id];\n if (!targetUser) {\n return undefined;\n }\n\n return updateUser(global, id, {\n fullInfo: {\n ...targetUser.fullInfo,\n ...fullInfo,\n },\n });\n }\n }\n\n return undefined;\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { ApiUpdate } from '../../../api/types';\n\nimport { updateStickerSet } from '../../reducers';\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n switch (update['@type']) {\n case 'updateStickerSet': {\n return updateStickerSet(global, update.id, update.stickerSet);\n }\n }\n\n return undefined;\n});\n","import {\n addReducer, getGlobal, setGlobal,\n} from '../../../lib/teact/teactn';\n\nimport { ApiUpdate } from '../../../api/types';\nimport { ApiPrivacyKey } from '../../../types';\n\nimport { addBlockedContact, removeBlockedContact } from '../../reducers';\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n switch (update['@type']) {\n case 'updatePeerBlocked':\n if (update.isBlocked) {\n return addBlockedContact(getGlobal(), update.id);\n } else {\n return removeBlockedContact(getGlobal(), update.id);\n }\n\n case 'updateResetContactList':\n setGlobal({\n ...getGlobal(),\n contactList: {\n userIds: [],\n },\n });\n break;\n\n case 'updateFavoriteStickers':\n actions.loadFavoriteStickers();\n break;\n\n case 'updatePrivacy':\n global.settings.privacy[update.key as ApiPrivacyKey] = update.rules;\n break;\n }\n\n return undefined;\n});\n","import { addReducer, setGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiUpdate } from '../../../api/types';\nimport { GlobalState } from '../../../global/types';\nimport { addNotifyException, updateChat, updateNotifySettings } from '../../reducers';\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate): GlobalState | undefined => {\n switch (update['@type']) {\n case 'updateNotifySettings': {\n return updateNotifySettings(global, update.peerType, update.isSilent, update.shouldShowPreviews);\n }\n\n case 'updateNotifyExceptions': {\n const {\n chatId, isMuted, isSilent, shouldShowPreviews,\n } = update;\n const chat = global.chats.byId[chatId];\n\n if (chat) {\n global = updateChat(global, chatId, { isMuted });\n }\n\n setGlobal(addNotifyException(global, chatId, { isMuted, isSilent, shouldShowPreviews }));\n break;\n }\n }\n\n return undefined;\n});\n","import { addReducer } from '../../../lib/teact/teactn';\n\nimport { ApiUpdate } from '../../../api/types';\nimport { GlobalState } from '../../../global/types';\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate): GlobalState | undefined => {\n switch (update['@type']) {\n case 'updateTwoFaStateWaitCode': {\n return {\n ...global,\n twoFaSettings: {\n ...global.twoFaSettings,\n isLoading: false,\n waitingEmailCodeLength: update.length,\n },\n };\n }\n\n case 'updateTwoFaError': {\n return {\n ...global,\n twoFaSettings: {\n ...global.twoFaSettings,\n error: update.message,\n },\n };\n }\n }\n\n return undefined;\n});\n","import { addReducer, getGlobal } from '../../../lib/teact/teactn';\nimport { ApiUpdate } from '../../../api/types';\nimport { removeGroupCall, updateGroupCall, updateGroupCallParticipant } from '../../reducers/calls';\nimport { omit } from '../../../util/iteratees';\nimport { selectChat } from '../../selectors';\nimport { updateChat } from '../../reducers';\n\naddReducer('apiUpdate', (global, actions, update: ApiUpdate) => {\n switch (update['@type']) {\n case 'updateGroupCall': {\n if (update.call.connectionState === 'discarded') {\n if (global.groupCalls.activeGroupCallId) {\n actions.leaveGroupCall({ shouldRemove: true });\n return undefined;\n } else {\n return removeGroupCall(global, update.call.id);\n }\n }\n\n return updateGroupCall(global,\n update.call.id,\n omit(update.call, ['connectionState']),\n undefined,\n update.call.participantsCount);\n }\n case 'updateGroupCallChatId': {\n const chat = selectChat(global, update.chatId);\n if (chat) {\n global = updateChat(global, update.chatId, {\n fullInfo: {\n ...chat.fullInfo,\n groupCallId: update.call.id,\n },\n });\n }\n return global;\n }\n case 'updateGroupCallParticipants': {\n const { groupCallId, participants, nextOffset } = update;\n const { currentUserId } = global;\n\n // `secret-sauce` should disconnect if the participant is us but from another device\n global = getGlobal();\n participants.forEach((participant) => {\n if (participant.id) {\n global = updateGroupCallParticipant(global, groupCallId, participant.id, participant,\n !!nextOffset || currentUserId === participant.id);\n }\n });\n if (nextOffset) {\n global = updateGroupCall(global, groupCallId, {\n nextOffset,\n });\n }\n return global;\n }\n }\n\n return undefined;\n});\n","import { useEffect } from '../lib/teact/teact';\n\nimport { onBeforeUnload } from '../util/schedulers';\n\nexport default function useBeforeUnload(callback: AnyToVoidFunction) {\n useEffect(() => {\n return onBeforeUnload(callback);\n }, [callback]);\n}\n","import { useEffect } from '../lib/teact/teact';\nimport { IS_IOS, IS_PWA, IS_TOUCH_ENV } from '../util/environment';\n\nconst metaViewport = document.querySelector('meta[name=\"viewport\"]');\nconst defaultViewportContent = metaViewport?.getAttribute('content') || '';\nconst allowedZoomViewportContent = 'width=device-width, initial-scale=1, shrink-to-fit=no, viewport-fit=cover';\n\nexport default function usePreventPinchZoomGesture(isDisabled = false) {\n useEffect(() => {\n if (!IS_TOUCH_ENV) {\n return undefined;\n }\n\n if (isDisabled) {\n // Clean viewport content from values values that disable the ability to zoom a webpage\n // https://web.dev/meta-viewport/\n metaViewport?.setAttribute('content', allowedZoomViewportContent);\n return undefined;\n }\n\n metaViewport?.setAttribute('content', defaultViewportContent);\n\n // Since iOS 10 `user-scaleable=no` is disabled in Safari for iOS,\n // this is only applicable for the browser and does not apply to the PWA mode.\n // https://newbedev.com/how-do-you-disable-viewport-zooming-on-mobile-safari\n if (IS_IOS && !IS_PWA) {\n document.addEventListener('gesturestart', preventEvent);\n }\n\n return () => {\n metaViewport?.setAttribute('content', 'width=device-width, initial-scale=1, shrink-to-fit=no');\n if (IS_IOS && !IS_PWA) {\n document.removeEventListener('gesturestart', preventEvent);\n }\n };\n }, [isDisabled]);\n}\n\nfunction preventEvent(e: Event) {\n e.preventDefault();\n}\n","import { useEffect, useState } from '../lib/teact/teact';\n\nexport default function useBrowserOnline() {\n const [isOnline, setIsOnline] = useState(window.navigator.onLine);\n\n useEffect(() => {\n function handleChange() {\n setIsOnline(window.navigator.onLine);\n }\n\n window.addEventListener('online', handleChange);\n window.addEventListener('offline', handleChange);\n\n return () => {\n window.removeEventListener('offline', handleChange);\n window.removeEventListener('online', handleChange);\n };\n }, []);\n\n return isOnline;\n}\n","import React, {\n FC, useCallback, useMemo, memo,\n} from '../../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../../lib/teact/teactn';\n\nimport { LeftColumnContent, ISettings } from '../../../types';\nimport { ApiChat } from '../../../api/types';\n\nimport {\n ANIMATION_LEVEL_MAX, APP_NAME, APP_VERSION, FEEDBACK_URL,\n} from '../../../config';\nimport { IS_SINGLE_COLUMN_LAYOUT } from '../../../util/environment';\nimport buildClassName from '../../../util/buildClassName';\nimport { isChatArchived } from '../../../modules/helpers';\nimport { formatDateToString } from '../../../util/dateFormat';\nimport { selectTheme } from '../../../modules/selectors';\nimport switchTheme from '../../../util/switchTheme';\nimport useLang from '../../../hooks/useLang';\nimport { disableHistoryBack } from '../../../hooks/useHistoryBack';\n\nimport DropdownMenu from '../../ui/DropdownMenu';\nimport MenuItem from '../../ui/MenuItem';\nimport Button from '../../ui/Button';\nimport SearchInput from '../../ui/SearchInput';\nimport PickerSelectedItem from '../../common/PickerSelectedItem';\nimport Switcher from '../../ui/Switcher';\n\nimport './LeftMainHeader.scss';\n\ntype OwnProps = {\n content: LeftColumnContent;\n contactsFilter: string;\n shouldSkipTransition?: boolean;\n onSearchQuery: (query: string) => void;\n onSelectSettings: () => void;\n onSelectContacts: () => void;\n onSelectArchived: () => void;\n onReset: () => void;\n};\n\ntype StateProps = {\n searchQuery?: string;\n isLoading: boolean;\n currentUserId?: string;\n globalSearchChatId?: string;\n searchDate?: number;\n theme: ISettings['theme'];\n animationLevel: 0 | 1 | 2;\n chatsById?: Record;\n};\n\nconst ANIMATION_LEVEL_OPTIONS = [0, 1, 2];\n\nconst PRODUCTION_HOSTNAME = 'web.telegram.org';\nconst LEGACY_VERSION_URL = 'https://web.telegram.org/?legacy=1';\nconst WEBK_VERSION_URL = 'https://web.telegram.org/k/';\nconst PERMANENT_VERSION_KEY = 'kz_version';\n\nconst LeftMainHeader: FC = ({\n content,\n contactsFilter,\n onSearchQuery,\n onSelectSettings,\n onSelectContacts,\n onSelectArchived,\n onReset,\n searchQuery,\n isLoading,\n shouldSkipTransition,\n currentUserId,\n globalSearchChatId,\n searchDate,\n theme,\n animationLevel,\n chatsById,\n}) => {\n const {\n openChat,\n openTipsChat,\n setGlobalSearchDate,\n setSettingOption, setGlobalSearchChatId,\n } = getDispatch();\n\n const lang = useLang();\n const hasMenu = content === LeftColumnContent.ChatList;\n const clearedDateSearchParam = { date: undefined };\n const clearedChatSearchParam = { id: undefined };\n const selectedSearchDate = useMemo(() => {\n return searchDate\n ? formatDateToString(new Date(searchDate * 1000))\n : undefined;\n }, [searchDate]);\n const archivedUnreadChatsCount = useMemo(() => {\n if (!hasMenu || !chatsById) {\n return 0;\n }\n\n return Object.values(chatsById).reduce((total, chat) => {\n if (!isChatArchived(chat)) {\n return total;\n }\n\n return chat.unreadCount ? total + 1 : total;\n }, 0);\n }, [hasMenu, chatsById]);\n\n const withOtherVersions = window.location.hostname === PRODUCTION_HOSTNAME;\n\n const MainButton: FC<{ onTrigger: () => void; isOpen?: boolean }> = useMemo(() => {\n return ({ onTrigger, isOpen }) => (\n onReset()}\n ariaLabel={hasMenu ? lang('AccDescrOpenMenu2') : 'Return to chat list'}\n >\n
\n \n );\n }, [hasMenu, lang, onReset, shouldSkipTransition]);\n\n const handleSearchFocus = useCallback(() => {\n if (!searchQuery) {\n onSearchQuery('');\n }\n }, [searchQuery, onSearchQuery]);\n\n const handleSelectSaved = useCallback(() => {\n openChat({ id: currentUserId, shouldReplaceHistory: true });\n }, [currentUserId, openChat]);\n\n const handleDarkModeToggle = useCallback((e: React.SyntheticEvent) => {\n e.stopPropagation();\n const newTheme = theme === 'light' ? 'dark' : 'light';\n\n setSettingOption({ theme: newTheme });\n setSettingOption({ shouldUseSystemTheme: false });\n switchTheme(newTheme, animationLevel === ANIMATION_LEVEL_MAX);\n }, [animationLevel, setSettingOption, theme]);\n\n const handleAnimationLevelChange = useCallback((e: React.SyntheticEvent) => {\n e.stopPropagation();\n\n const newLevel = animationLevel === 0 ? 2 : 0;\n ANIMATION_LEVEL_OPTIONS.forEach((_, i) => {\n document.body.classList.toggle(`animation-level-${i}`, newLevel === i);\n });\n\n setSettingOption({ animationLevel: newLevel });\n }, [animationLevel, setSettingOption]);\n\n const handleSwitchToWebK = () => {\n localStorage.setItem(PERMANENT_VERSION_KEY, JSON.stringify('K'));\n disableHistoryBack();\n };\n\n const handleOpenTipsChat = () => {\n openTipsChat({ langCode: lang.code });\n };\n\n const isSearchFocused = (\n Boolean(globalSearchChatId)\n || content === LeftColumnContent.GlobalSearch\n || content === LeftColumnContent.Contacts\n );\n\n const searchInputPlaceholder = content === LeftColumnContent.Contacts\n ? lang('SearchFriends')\n : lang('Search');\n\n return (\n
\n
\n \n \n {lang('SavedMessages')}\n \n \n {lang('ArchivedChats')}\n {archivedUnreadChatsCount > 0 && (\n
{archivedUnreadChatsCount}
\n )}\n \n \n {lang('Contacts')}\n \n \n {lang('Settings')}\n \n \n {lang('lng_menu_night_mode')}\n \n \n \n {lang('Appearance.Animations').toLowerCase()}\n 0}\n />\n \n \n {lang('TelegramFeatures')}\n \n \n Report Bug\n \n {withOtherVersions && (\n <>\n \n Switch to K Version\n \n \n Switch to Old Version\n \n \n )}\n \n \n {selectedSearchDate && (\n \n )}\n {globalSearchChatId && (\n \n )}\n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n query: searchQuery, fetchingStatus, chatId, date,\n } = global.globalSearch;\n const { currentUserId } = global;\n const { byId: chatsById } = global.chats;\n const { animationLevel } = global.settings.byKey;\n\n return {\n searchQuery,\n isLoading: fetchingStatus ? Boolean(fetchingStatus.chats || fetchingStatus.messages) : false,\n currentUserId,\n chatsById,\n globalSearchChatId: chatId,\n searchDate: date,\n theme: selectTheme(global),\n animationLevel,\n };\n },\n)(LeftMainHeader));\n","import React, { memo, FC } from '../../lib/teact/teact';\n\nimport { GlobalState } from '../../global/types';\n\nimport useLang from '../../hooks/useLang';\n\nimport Spinner from '../ui/Spinner';\n\nimport './ConnectionState.scss';\n\ntype StateProps = Pick;\n\nconst ConnectionState: FC = () => {\n const lang = useLang();\n\n return (\n
\n \n
{lang('WaitingForNetwork')}
\n
\n );\n};\n\nexport default memo(ConnectionState);\n","import React, {\n FC, memo, useCallback, useEffect, useMemo, useRef,\n} from '../../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiChat, ApiChatFolder, ApiUser } from '../../../api/types';\nimport { GlobalState } from '../../../global/types';\nimport { NotifyException, NotifySettings, SettingsScreens } from '../../../types';\nimport { FolderEditDispatch } from '../../../hooks/reducers/useFoldersReducer';\n\nimport { IS_TOUCH_ENV } from '../../../util/environment';\nimport { ALL_FOLDER_ID } from '../../../config';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport { captureEvents, SwipeDirection } from '../../../util/captureEvents';\nimport { getFolderUnreadDialogs } from '../../../modules/helpers';\nimport { selectNotifyExceptions, selectNotifySettings } from '../../../modules/selectors';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport buildClassName from '../../../util/buildClassName';\nimport useThrottledMemo from '../../../hooks/useThrottledMemo';\nimport useLang from '../../../hooks/useLang';\nimport useHistoryBack from '../../../hooks/useHistoryBack';\nimport captureEscKeyListener from '../../../util/captureEscKeyListener';\n\nimport Transition from '../../ui/Transition';\nimport TabList from '../../ui/TabList';\nimport ChatList from './ChatList';\n\ntype OwnProps = {\n onScreenSelect: (screen: SettingsScreens) => void;\n foldersDispatch: FolderEditDispatch;\n};\n\ntype StateProps = {\n allListIds: GlobalState['chats']['listIds'];\n chatsById: Record;\n usersById: Record;\n chatFoldersById: Record;\n notifySettings: NotifySettings;\n notifyExceptions?: Record;\n orderedFolderIds?: number[];\n activeChatFolder: number;\n currentUserId?: string;\n lastSyncTime?: number;\n shouldSkipHistoryAnimations?: boolean;\n};\n\nconst INFO_THROTTLE = 3000;\nconst SAVED_MESSAGES_HOTKEY = '0';\n\nconst ChatFolders: FC = ({\n allListIds,\n chatsById,\n usersById,\n chatFoldersById,\n notifySettings,\n notifyExceptions,\n orderedFolderIds,\n activeChatFolder,\n currentUserId,\n lastSyncTime,\n shouldSkipHistoryAnimations,\n foldersDispatch,\n onScreenSelect,\n}) => {\n const {\n loadChatFolders,\n setActiveChatFolder,\n openChat,\n } = getDispatch();\n\n // eslint-disable-next-line no-null/no-null\n const transitionRef = useRef(null);\n\n const lang = useLang();\n\n useEffect(() => {\n if (lastSyncTime) {\n loadChatFolders();\n }\n }, [lastSyncTime, loadChatFolders]);\n\n const displayedFolders = useMemo(() => {\n return orderedFolderIds\n ? orderedFolderIds.map((id) => chatFoldersById[id] || {}).filter(Boolean)\n : undefined;\n }, [chatFoldersById, orderedFolderIds]);\n\n const folderCountersById = useThrottledMemo(() => {\n if (!displayedFolders || !displayedFolders.length) {\n return undefined;\n }\n\n const counters = displayedFolders.map((folder) => {\n const {\n unreadDialogsCount, hasActiveDialogs,\n } = getFolderUnreadDialogs(allListIds, chatsById, usersById, folder, notifySettings, notifyExceptions) || {};\n\n return {\n id: folder.id,\n badgeCount: unreadDialogsCount,\n isBadgeActive: hasActiveDialogs,\n };\n });\n\n return buildCollectionByKey(counters, 'id');\n }, INFO_THROTTLE, [displayedFolders, allListIds, chatsById, usersById, notifySettings, notifyExceptions]);\n\n const folderTabs = useMemo(() => {\n if (!displayedFolders || !displayedFolders.length) {\n return undefined;\n }\n\n return [\n { title: lang.code === 'en' ? 'All' : lang('FilterAllChats'), id: ALL_FOLDER_ID },\n ...displayedFolders.map((folder) => ({\n title: folder.title,\n ...(folderCountersById?.[folder.id]),\n })),\n ];\n }, [displayedFolders, folderCountersById, lang]);\n\n const handleSwitchTab = useCallback((index: number) => {\n setActiveChatFolder(index, { forceOnHeavyAnimation: true });\n }, [setActiveChatFolder]);\n\n // Prevent `activeTab` pointing at non-existing folder after update\n useEffect(() => {\n if (!folderTabs || !folderTabs.length) {\n return;\n }\n\n if (activeChatFolder >= folderTabs.length) {\n setActiveChatFolder(0);\n }\n }, [activeChatFolder, folderTabs, setActiveChatFolder]);\n\n useEffect(() => {\n if (!transitionRef.current || !IS_TOUCH_ENV || !folderTabs || !folderTabs.length) {\n return undefined;\n }\n\n return captureEvents(transitionRef.current, {\n selectorToPreventScroll: '.chat-list',\n onSwipe: ((e, direction) => {\n if (direction === SwipeDirection.Left) {\n setActiveChatFolder(Math.min(activeChatFolder + 1, folderTabs.length - 1), { forceOnHeavyAnimation: true });\n return true;\n } else if (direction === SwipeDirection.Right) {\n setActiveChatFolder(Math.max(0, activeChatFolder - 1), { forceOnHeavyAnimation: true });\n return true;\n }\n\n return false;\n }),\n });\n }, [activeChatFolder, folderTabs, setActiveChatFolder]);\n\n const isNotInAllTabRef = useRef();\n isNotInAllTabRef.current = activeChatFolder !== 0;\n useEffect(() => (isNotInAllTabRef.current ? captureEscKeyListener(() => {\n if (isNotInAllTabRef.current) {\n setActiveChatFolder(0);\n }\n }) : undefined), [activeChatFolder, setActiveChatFolder]);\n\n useHistoryBack(activeChatFolder !== 0, () => setActiveChatFolder(0, { forceOnHeavyAnimation: true }));\n\n useEffect(() => {\n const handleKeyDown = (e: KeyboardEvent) => {\n if (e.ctrlKey && e.shiftKey && e.code.startsWith('Digit') && folderTabs) {\n const [, digit] = e.code.match(/Digit(\\d)/) || [];\n if (!digit) return;\n\n if (digit === SAVED_MESSAGES_HOTKEY) {\n openChat({ id: currentUserId, shouldReplaceHistory: true });\n return;\n }\n\n const folder = Number(digit) - 1;\n if (folder > folderTabs.length - 1) return;\n\n setActiveChatFolder(folder, { forceOnHeavyAnimation: true });\n e.preventDefault();\n }\n };\n\n document.addEventListener('keydown', handleKeyDown, true);\n\n return () => {\n document.removeEventListener('keydown', handleKeyDown, true);\n };\n });\n\n const {\n shouldRender: shouldRenderPlaceholder, transitionClassNames,\n } = useShowTransition(!orderedFolderIds, undefined, true);\n\n function renderCurrentTab(isActive: boolean) {\n const activeFolder = Object.values(chatFoldersById)\n .find(({ id }) => id === folderTabs![activeChatFolder].id);\n\n if (!activeFolder || activeChatFolder === 0) {\n return (\n \n );\n }\n\n return (\n \n );\n }\n\n return (\n
\n {folderTabs?.length ? (\n \n ) : shouldRenderPlaceholder ? (\n
\n ) : undefined}\n \n {renderCurrentTab}\n \n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n chats: { listIds: allListIds, byId: chatsById },\n users: { byId: usersById },\n chatFolders: {\n byId: chatFoldersById,\n orderedIds: orderedFolderIds,\n activeChatFolder,\n },\n currentUserId,\n lastSyncTime,\n shouldSkipHistoryAnimations,\n } = global;\n\n return {\n allListIds,\n chatsById,\n usersById,\n chatFoldersById,\n orderedFolderIds,\n lastSyncTime,\n notifySettings: selectNotifySettings(global),\n notifyExceptions: selectNotifyExceptions(global),\n activeChatFolder,\n currentUserId,\n shouldSkipHistoryAnimations,\n };\n },\n)(ChatFolders));\n","import { useState } from '../lib/teact/teact';\n\nimport useThrottle from './useThrottle';\nimport useOnChange from './useOnChange';\nimport useHeavyAnimationCheck from './useHeavyAnimationCheck';\nimport useFlag from './useFlag';\n\nexport default (resolverFn: () => R, ms: number, dependencies: D) => {\n const runThrottled = useThrottle(ms, true);\n const [value, setValue] = useState();\n const [isFrozen, freeze, unfreeze] = useFlag();\n\n useHeavyAnimationCheck(freeze, unfreeze);\n\n useOnChange(() => {\n if (isFrozen) {\n return;\n }\n\n runThrottled(() => {\n setValue(resolverFn());\n });\n }, dependencies.concat([isFrozen]));\n\n return value;\n};\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { Bundles } from '../../../util/moduleLoader';\nimport { OwnProps } from './LeftSearch';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\nimport Loading from '../../ui/Loading';\n\nconst LeftSearchAsync: FC = (props) => {\n const LeftSearch = useModuleLoader(Bundles.Extra, 'LeftSearch');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return LeftSearch ? : ;\n};\n\nexport default memo(LeftSearchAsync);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { Bundles } from '../../../util/moduleLoader';\nimport { OwnProps } from './ContactList';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\nimport Loading from '../../ui/Loading';\n\nconst ContactListAsync: FC = (props) => {\n const ContactList = useModuleLoader(Bundles.Extra, 'ContactList');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return ContactList ? : ;\n};\n\nexport default memo(ContactListAsync);\n","import React, {\n FC, useCallback, useState, useEffect, memo,\n} from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\n\nimport Button from '../ui/Button';\nimport Menu from '../ui/Menu';\nimport MenuItem from '../ui/MenuItem';\n\nimport './NewChatButton.scss';\n\nconst MENU_CLOSE_DELAY_MS = 750;\nlet closeTimeout: number | undefined;\n\ntype OwnProps = {\n isShown: boolean;\n onNewPrivateChat: () => void;\n onNewChannel: () => void;\n onNewGroup: () => void;\n};\n\nconst NewChatButton: FC = ({\n isShown,\n onNewPrivateChat,\n onNewChannel,\n onNewGroup,\n}) => {\n const [isMenuOpen, setIsMenuOpen] = useState(false);\n\n useEffect(() => {\n if (!isShown) {\n setIsMenuOpen(false);\n }\n }, [isShown]);\n\n const lang = useLang();\n\n const fabClassName = buildClassName(\n 'NewChatButton',\n isShown && 'revealed',\n isMenuOpen && 'menu-is-open',\n );\n\n const toggleIsMenuOpen = () => {\n setIsMenuOpen(!isMenuOpen);\n };\n\n const handleClose = () => {\n setIsMenuOpen(false);\n };\n\n const handleMouseEnter = useCallback(() => {\n if (closeTimeout) {\n clearTimeout(closeTimeout);\n closeTimeout = undefined;\n }\n }, []);\n\n const handleMouseLeave = useCallback(() => {\n if (closeTimeout) {\n clearTimeout(closeTimeout);\n closeTimeout = undefined;\n }\n\n closeTimeout = window.setTimeout(() => {\n setIsMenuOpen(false);\n }, MENU_CLOSE_DELAY_MS);\n }, []);\n\n return (\n \n \n \n \n \n \n {lang('NewChannel')}\n {lang('NewGroup')}\n {lang('NewMessageTitle')}\n \n
\n );\n};\n\nexport default memo(NewChatButton);\n","import React, {\n FC, useState, useRef, useCallback, useEffect,\n} from '../../../lib/teact/teact';\nimport { withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalState } from '../../../global/types';\nimport { LeftColumnContent, SettingsScreens } from '../../../types';\nimport { FolderEditDispatch } from '../../../hooks/reducers/useFoldersReducer';\n\nimport { IS_TOUCH_ENV } from '../../../util/environment';\nimport { pick } from '../../../util/iteratees';\nimport buildClassName from '../../../util/buildClassName';\nimport useBrowserOnline from '../../../hooks/useBrowserOnline';\nimport useFlag from '../../../hooks/useFlag';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useLang from '../../../hooks/useLang';\n\nimport Transition from '../../ui/Transition';\nimport LeftMainHeader from './LeftMainHeader';\nimport ConnectionState from '../ConnectionState';\nimport ChatFolders from './ChatFolders';\nimport LeftSearch from '../search/LeftSearch.async';\nimport ContactList from './ContactList.async';\nimport NewChatButton from '../NewChatButton';\nimport ShowTransition from '../../ui/ShowTransition';\nimport Button from '../../ui/Button';\n\nimport './LeftMain.scss';\n\ntype OwnProps = {\n content: LeftColumnContent;\n searchQuery?: string;\n searchDate?: number;\n contactsFilter: string;\n shouldSkipTransition?: boolean;\n foldersDispatch: FolderEditDispatch;\n onSearchQuery: (query: string) => void;\n onContentChange: (content: LeftColumnContent) => void;\n onScreenSelect: (screen: SettingsScreens) => void;\n onReset: () => void;\n};\n\ntype StateProps = Pick;\n\nconst TRANSITION_RENDER_COUNT = Object.keys(LeftColumnContent).length / 2;\nconst BUTTON_CLOSE_DELAY_MS = 250;\nconst APP_OUTDATED_TIMEOUT = 3 * 24 * 60 * 60 * 1000; // 3 days\n\nlet closeTimeout: number | undefined;\n\nconst LeftMain: FC = ({\n content,\n searchQuery,\n searchDate,\n contactsFilter,\n shouldSkipTransition,\n foldersDispatch,\n onSearchQuery,\n onContentChange,\n onScreenSelect,\n onReset,\n connectionState,\n}) => {\n const [isNewChatButtonShown, setIsNewChatButtonShown] = useState(IS_TOUCH_ENV);\n\n const isBrowserOnline = useBrowserOnline();\n const isConnecting = !isBrowserOnline || connectionState === 'connectionStateConnecting';\n\n const isMouseInside = useRef(false);\n\n const handleSelectSettings = useCallback(() => {\n onContentChange(LeftColumnContent.Settings);\n }, [onContentChange]);\n\n const handleSelectContacts = useCallback(() => {\n onContentChange(LeftColumnContent.Contacts);\n }, [onContentChange]);\n\n const handleSelectNewChannel = useCallback(() => {\n onContentChange(LeftColumnContent.NewChannelStep1);\n }, [onContentChange]);\n\n const handleSelectNewGroup = useCallback(() => {\n onContentChange(LeftColumnContent.NewGroupStep1);\n }, [onContentChange]);\n\n const handleSelectArchived = useCallback(() => {\n onContentChange(LeftColumnContent.Archived);\n }, [onContentChange]);\n\n const handleMouseEnter = useCallback(() => {\n if (content !== LeftColumnContent.ChatList) {\n return;\n }\n isMouseInside.current = true;\n setIsNewChatButtonShown(true);\n }, [content]);\n\n const handleMouseLeave = useCallback(() => {\n isMouseInside.current = false;\n\n if (closeTimeout) {\n clearTimeout(closeTimeout);\n closeTimeout = undefined;\n }\n\n closeTimeout = window.setTimeout(() => {\n if (!isMouseInside.current) {\n setIsNewChatButtonShown(false);\n }\n }, BUTTON_CLOSE_DELAY_MS);\n }, []);\n\n useEffect(() => {\n let autoCloseTimeout: number | undefined;\n if (content !== LeftColumnContent.ChatList) {\n autoCloseTimeout = window.setTimeout(() => {\n setIsNewChatButtonShown(false);\n }, BUTTON_CLOSE_DELAY_MS);\n } else if (isMouseInside.current || IS_TOUCH_ENV) {\n setIsNewChatButtonShown(true);\n }\n\n return () => {\n if (autoCloseTimeout) {\n clearTimeout(autoCloseTimeout);\n autoCloseTimeout = undefined;\n }\n };\n }, [content]);\n\n const [shouldRenderUpdateButton, updateButtonClassNames, handleUpdateClick] = useAppOutdatedCheck();\n\n const lang = useLang();\n\n return (\n \n \n \n {() => }\n \n \n {(isActive) => {\n switch (content) {\n case LeftColumnContent.ChatList:\n return ;\n case LeftColumnContent.GlobalSearch:\n return (\n \n );\n case LeftColumnContent.Contacts:\n return ;\n default:\n return undefined;\n }\n }}\n \n {shouldRenderUpdateButton && (\n \n {lang('lng_update_telegram')}\n \n )}\n \n
\n );\n};\n\nfunction useAppOutdatedCheck() {\n const [isAppOutdated, markIsAppOutdated] = useFlag(false);\n\n useEffect(() => {\n const timeout = window.setTimeout(markIsAppOutdated, APP_OUTDATED_TIMEOUT);\n\n return () => {\n clearTimeout(timeout);\n };\n }, [markIsAppOutdated]);\n\n const { shouldRender, transitionClassNames } = useShowTransition(isAppOutdated);\n\n const handleUpdateClick = () => {\n window.location.reload();\n };\n\n return [shouldRender, transitionClassNames, handleUpdateClick] as const;\n}\n\nexport default withGlobal(\n (global): StateProps => pick(global, ['connectionState']),\n)(LeftMain);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport { OwnProps } from './Settings';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\nimport Loading from '../../ui/Loading';\n\nconst SettingsAsync: FC = (props) => {\n const Settings = useModuleLoader(Bundles.Extra, 'Settings');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return Settings ? : ;\n};\n\nexport default memo(SettingsAsync);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport { OwnProps } from './NewChat';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\nimport Loading from '../../ui/Loading';\n\nconst NewChatAsync: FC = (props) => {\n const NewChat = useModuleLoader(Bundles.Extra, 'NewChat');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return NewChat ? : ;\n};\n\nexport default memo(NewChatAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './ArchivedChats';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst ArchivedChatsAsync: FC = (props) => {\n const ArchivedChats = useModuleLoader(Bundles.Extra, 'ArchivedChats');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return ArchivedChats ? : ;\n};\n\nexport default memo(ArchivedChatsAsync);\n","import React, {\n FC, memo, useCallback, useEffect, useRef, useState,\n} from '../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../lib/teact/teactn';\n\nimport { LeftColumnContent, SettingsScreens } from '../../types';\n\nimport { IS_MAC_OS, LAYERS_ANIMATION_NAME } from '../../util/environment';\nimport captureEscKeyListener from '../../util/captureEscKeyListener';\nimport getKeyFromEvent from '../../util/getKeyFromEvent';\nimport useFoldersReducer from '../../hooks/reducers/useFoldersReducer';\nimport { useResize } from '../../hooks/useResize';\n\nimport Transition from '../ui/Transition';\nimport LeftMain from './main/LeftMain';\nimport Settings from './settings/Settings.async';\nimport NewChat from './newChat/NewChat.async';\nimport ArchivedChats from './ArchivedChats.async';\n\nimport './LeftColumn.scss';\n\ntype StateProps = {\n searchQuery?: string;\n searchDate?: number;\n activeChatFolder: number;\n shouldSkipHistoryAnimations?: boolean;\n leftColumnWidth?: number;\n};\n\nenum ContentType {\n Main,\n // eslint-disable-next-line @typescript-eslint/no-shadow\n Settings,\n Archived,\n // eslint-disable-next-line no-shadow\n NewGroup,\n // eslint-disable-next-line no-shadow\n NewChannel,\n}\n\nconst RENDER_COUNT = Object.keys(ContentType).length / 2;\nconst RESET_TRANSITION_DELAY_MS = 250;\n\nconst LeftColumn: FC = ({\n searchQuery,\n searchDate,\n activeChatFolder,\n shouldSkipHistoryAnimations,\n leftColumnWidth,\n}) => {\n const {\n setGlobalSearchQuery,\n setGlobalSearchChatId,\n resetChatCreation,\n setGlobalSearchDate,\n loadPasswordInfo,\n clearTwoFaError,\n setLeftColumnWidth,\n resetLeftColumnWidth,\n } = getDispatch();\n\n // eslint-disable-next-line no-null/no-null\n const resizeRef = useRef(null);\n const [content, setContent] = useState(LeftColumnContent.ChatList);\n const [settingsScreen, setSettingsScreen] = useState(SettingsScreens.Main);\n const [contactsFilter, setContactsFilter] = useState('');\n const [foldersState, foldersDispatch] = useFoldersReducer();\n\n // Used to reset child components in background.\n const [lastResetTime, setLastResetTime] = useState(0);\n\n let contentType: ContentType = ContentType.Main;\n switch (content) {\n case LeftColumnContent.Archived:\n contentType = ContentType.Archived;\n break;\n case LeftColumnContent.Settings:\n contentType = ContentType.Settings;\n break;\n case LeftColumnContent.NewChannelStep1:\n case LeftColumnContent.NewChannelStep2:\n contentType = ContentType.NewChannel;\n break;\n case LeftColumnContent.NewGroupStep1:\n case LeftColumnContent.NewGroupStep2:\n contentType = ContentType.NewGroup;\n break;\n }\n\n const handleReset = useCallback((forceReturnToChatList?: boolean) => {\n if (content === LeftColumnContent.NewGroupStep2\n && !forceReturnToChatList\n ) {\n setContent(LeftColumnContent.NewGroupStep1);\n return;\n }\n\n if (content === LeftColumnContent.NewChannelStep2\n && !forceReturnToChatList\n ) {\n setContent(LeftColumnContent.NewChannelStep1);\n return;\n }\n\n if (content === LeftColumnContent.NewGroupStep1) {\n const pickerSearchInput = document.getElementById('new-group-picker-search');\n if (pickerSearchInput) {\n pickerSearchInput.blur();\n }\n }\n\n if (content === LeftColumnContent.Settings) {\n switch (settingsScreen) {\n case SettingsScreens.EditProfile:\n case SettingsScreens.Folders:\n case SettingsScreens.General:\n case SettingsScreens.Notifications:\n case SettingsScreens.DataStorage:\n case SettingsScreens.Privacy:\n case SettingsScreens.Language:\n setSettingsScreen(SettingsScreens.Main);\n return;\n\n case SettingsScreens.GeneralChatBackground:\n setSettingsScreen(SettingsScreens.General);\n return;\n case SettingsScreens.GeneralChatBackgroundColor:\n setSettingsScreen(SettingsScreens.GeneralChatBackground);\n return;\n\n case SettingsScreens.PrivacyPhoneNumber:\n case SettingsScreens.PrivacyLastSeen:\n case SettingsScreens.PrivacyProfilePhoto:\n case SettingsScreens.PrivacyForwarding:\n case SettingsScreens.PrivacyGroupChats:\n case SettingsScreens.PrivacyActiveSessions:\n case SettingsScreens.PrivacyBlockedUsers:\n case SettingsScreens.TwoFaDisabled:\n case SettingsScreens.TwoFaEnabled:\n case SettingsScreens.TwoFaCongratulations:\n setSettingsScreen(SettingsScreens.Privacy);\n return;\n case SettingsScreens.PrivacyPhoneNumberAllowedContacts:\n case SettingsScreens.PrivacyPhoneNumberDeniedContacts:\n setSettingsScreen(SettingsScreens.PrivacyPhoneNumber);\n return;\n case SettingsScreens.PrivacyLastSeenAllowedContacts:\n case SettingsScreens.PrivacyLastSeenDeniedContacts:\n setSettingsScreen(SettingsScreens.PrivacyLastSeen);\n return;\n case SettingsScreens.PrivacyProfilePhotoAllowedContacts:\n case SettingsScreens.PrivacyProfilePhotoDeniedContacts:\n setSettingsScreen(SettingsScreens.PrivacyProfilePhoto);\n return;\n case SettingsScreens.PrivacyForwardingAllowedContacts:\n case SettingsScreens.PrivacyForwardingDeniedContacts:\n setSettingsScreen(SettingsScreens.PrivacyForwarding);\n return;\n case SettingsScreens.PrivacyGroupChatsAllowedContacts:\n case SettingsScreens.PrivacyGroupChatsDeniedContacts:\n setSettingsScreen(SettingsScreens.PrivacyGroupChats);\n return;\n case SettingsScreens.TwoFaNewPassword:\n setSettingsScreen(SettingsScreens.TwoFaDisabled);\n return;\n case SettingsScreens.TwoFaNewPasswordConfirm:\n setSettingsScreen(SettingsScreens.TwoFaNewPassword);\n return;\n case SettingsScreens.TwoFaNewPasswordHint:\n setSettingsScreen(SettingsScreens.TwoFaNewPasswordConfirm);\n return;\n case SettingsScreens.TwoFaNewPasswordEmail:\n setSettingsScreen(SettingsScreens.TwoFaNewPasswordHint);\n return;\n case SettingsScreens.TwoFaNewPasswordEmailCode:\n setSettingsScreen(SettingsScreens.TwoFaNewPasswordEmail);\n return;\n case SettingsScreens.TwoFaChangePasswordCurrent:\n case SettingsScreens.TwoFaTurnOff:\n case SettingsScreens.TwoFaRecoveryEmailCurrentPassword:\n setSettingsScreen(SettingsScreens.TwoFaEnabled);\n return;\n case SettingsScreens.TwoFaChangePasswordNew:\n setSettingsScreen(SettingsScreens.TwoFaChangePasswordCurrent);\n return;\n case SettingsScreens.TwoFaChangePasswordConfirm:\n setSettingsScreen(SettingsScreens.TwoFaChangePasswordNew);\n return;\n case SettingsScreens.TwoFaChangePasswordHint:\n setSettingsScreen(SettingsScreens.TwoFaChangePasswordConfirm);\n return;\n case SettingsScreens.TwoFaRecoveryEmail:\n setSettingsScreen(SettingsScreens.TwoFaRecoveryEmailCurrentPassword);\n return;\n case SettingsScreens.TwoFaRecoveryEmailCode:\n setSettingsScreen(SettingsScreens.TwoFaRecoveryEmail);\n return;\n\n case SettingsScreens.FoldersCreateFolder:\n case SettingsScreens.FoldersEditFolder:\n setSettingsScreen(SettingsScreens.Folders);\n return;\n\n case SettingsScreens.FoldersIncludedChatsFromChatList:\n case SettingsScreens.FoldersExcludedChatsFromChatList:\n setSettingsScreen(SettingsScreens.FoldersEditFolderFromChatList);\n return;\n\n case SettingsScreens.FoldersEditFolderFromChatList:\n setContent(LeftColumnContent.ChatList);\n setSettingsScreen(SettingsScreens.Main);\n return;\n default:\n break;\n }\n }\n\n if (content === LeftColumnContent.ChatList && activeChatFolder === 0) {\n setContent(LeftColumnContent.GlobalSearch);\n return;\n }\n\n setContent(LeftColumnContent.ChatList);\n setContactsFilter('');\n setGlobalSearchQuery({ query: '' });\n setGlobalSearchDate({ date: undefined });\n setGlobalSearchChatId({ id: undefined });\n resetChatCreation();\n setTimeout(() => {\n setLastResetTime(Date.now());\n }, RESET_TRANSITION_DELAY_MS);\n }, [\n content, activeChatFolder, settingsScreen, setGlobalSearchQuery, setGlobalSearchDate, setGlobalSearchChatId,\n resetChatCreation,\n ]);\n\n const handleSearchQuery = useCallback((query: string) => {\n if (content === LeftColumnContent.Contacts) {\n setContactsFilter(query);\n return;\n }\n\n setContent(LeftColumnContent.GlobalSearch);\n\n if (query !== searchQuery) {\n setGlobalSearchQuery({ query });\n }\n }, [content, searchQuery, setGlobalSearchQuery]);\n\n useEffect(\n () => (content !== LeftColumnContent.ChatList || activeChatFolder === 0\n ? captureEscKeyListener(() => handleReset())\n : undefined),\n [activeChatFolder, content, handleReset],\n );\n\n useEffect(() => {\n if (content === LeftColumnContent.GlobalSearch) {\n return undefined;\n }\n\n function handleKeyDown(e: KeyboardEvent) {\n if (((IS_MAC_OS && e.metaKey) || (!IS_MAC_OS && e.ctrlKey)) && e.shiftKey && getKeyFromEvent(e) === 'f') {\n e.preventDefault();\n setContent(LeftColumnContent.GlobalSearch);\n }\n }\n\n document.addEventListener('keydown', handleKeyDown, false);\n\n return () => {\n document.removeEventListener('keydown', handleKeyDown, false);\n };\n }, [content]);\n\n useEffect(() => {\n clearTwoFaError();\n\n if (settingsScreen === SettingsScreens.Privacy) {\n loadPasswordInfo();\n }\n }, [clearTwoFaError, loadPasswordInfo, settingsScreen]);\n\n const {\n initResize, resetResize, handleMouseUp,\n } = useResize(resizeRef, setLeftColumnWidth, resetLeftColumnWidth, leftColumnWidth);\n\n const handleSettingsScreenSelect = (screen: SettingsScreens) => {\n setContent(LeftColumnContent.Settings);\n setSettingsScreen(screen);\n };\n\n return (\n \n \n {(isActive) => {\n switch (contentType) {\n case ContentType.Archived:\n return (\n \n );\n case ContentType.Settings:\n return (\n \n );\n case ContentType.NewChannel:\n return (\n \n );\n case ContentType.NewGroup:\n return (\n \n );\n default:\n return (\n \n );\n }\n }}\n \n \n \n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const {\n globalSearch: {\n query,\n date,\n },\n chatFolders: {\n activeChatFolder,\n },\n shouldSkipHistoryAnimations,\n leftColumnWidth,\n } = global;\n return {\n searchQuery: query, searchDate: date, activeChatFolder, shouldSkipHistoryAnimations, leftColumnWidth,\n };\n },\n)(LeftColumn));\n","import { RefObject } from 'react';\nimport { useState, useEffect } from '../lib/teact/teact';\nimport useFlag from './useFlag';\n\nexport const useResize = (\n elementRef: RefObject,\n onResize: (width: number) => void,\n onReset: NoneToVoidFunction,\n initialWidth?: number,\n) => {\n const [isActive, markIsActive, unmarkIsActive] = useFlag();\n const [initialMouseX, setInitialMouseX] = useState();\n const [initialElementWidth, setInitialElementWidth] = useState();\n\n useEffect(() => {\n if (!elementRef.current || !initialWidth) {\n return;\n }\n\n elementRef.current.style.width = `${initialWidth}px`;\n }, [elementRef, initialWidth]);\n\n const handleMouseUp = () => {\n document.body.classList.remove('no-selection', 'cursor-ew-resize');\n };\n\n const initResize = (event: React.MouseEvent) => {\n document.body.classList.add('no-selection', 'cursor-ew-resize');\n\n setInitialMouseX(event.clientX);\n setInitialElementWidth(elementRef.current!.offsetWidth);\n markIsActive();\n };\n\n const resetResize = (event: React.MouseEvent) => {\n event.preventDefault();\n elementRef.current!.style.width = '';\n onReset();\n };\n\n useEffect(() => {\n if (!isActive) return;\n\n const handleMouseMove = (event: MouseEvent) => {\n const newWidth = Math.ceil(initialElementWidth + event.clientX - initialMouseX);\n elementRef.current!.style.width = `${newWidth}px`;\n };\n\n const stopDrag = () => {\n handleMouseUp();\n document.removeEventListener('mousemove', handleMouseMove, false);\n document.removeEventListener('mouseup', stopDrag, false);\n document.removeEventListener('blur', stopDrag, false);\n onResize(elementRef.current!.offsetWidth);\n unmarkIsActive();\n };\n\n document.addEventListener('mousemove', handleMouseMove, false);\n document.addEventListener('mouseup', stopDrag, false);\n document.addEventListener('blur', stopDrag, false);\n }, [initialElementWidth, initialMouseX, elementRef, onResize, isActive, unmarkIsActive]);\n\n return { initResize, resetResize, handleMouseUp };\n};\n","import { useEffect, useState } from '../lib/teact/teact';\n\nimport { ThemeKey } from '../types';\n\nimport { CUSTOM_BG_CACHE_NAME } from '../config';\nimport * as cacheApi from '../util/cacheApi';\nimport { preloadImage } from '../util/files';\n\nexport default (theme: ThemeKey, settingValue?: string) => {\n const [value, setValue] = useState(settingValue);\n\n useEffect(() => {\n if (!settingValue) {\n return;\n }\n\n if (settingValue.startsWith('#')) {\n setValue(settingValue);\n } else {\n cacheApi.fetch(CUSTOM_BG_CACHE_NAME, theme, cacheApi.Type.Blob)\n .then((blob) => {\n const url = URL.createObjectURL(blob);\n preloadImage(url)\n .then(() => {\n setValue(`url(${url})`);\n });\n });\n }\n }, [settingValue, theme]);\n\n return settingValue ? value : undefined;\n};\n","import { useEffect, useState } from '../lib/teact/teact';\n\nimport { throttle } from '../util/schedulers';\nimport windowSize from '../util/windowSize';\nimport { ApiDimensions } from '../api/types';\n\nconst THROTTLE = 250;\n\nexport default () => {\n const [size, setSize] = useState(windowSize.get());\n\n useEffect(() => {\n const handleResize = throttle(() => {\n setSize(windowSize.get());\n }, THROTTLE, false);\n\n window.addEventListener('resize', handleResize);\n\n return () => {\n window.removeEventListener('resize', handleResize);\n };\n }, []);\n\n return size;\n};\n","import {\n MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN,\n MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN,\n MOBILE_SCREEN_MAX_WIDTH,\n} from '../../../config';\n\nconst REM = 16; // px\nconst MAX_TOOLBAR_WIDTH = 32 * REM;\nconst MAX_MESSAGES_LIST_WIDTH = 45.5 * REM;\nconst SIDE_COLUMN_MAX_WIDTH = 26.5 * REM;\nconst MIN_LEFT_COLUMN_WIDTH = 18 * REM;\nconst UNPIN_BUTTON_WIDTH = 16.125 * REM;\n\nexport default function calculateMiddleFooterTransforms(windowWidth: number, canPost?: boolean) {\n const sidePadding = windowWidth <= MOBILE_SCREEN_MAX_WIDTH\n ? REM\n : 2 * REM;\n const messageListWidth = getMessageListWidth(windowWidth);\n const sendButtonWidth = windowWidth <= MOBILE_SCREEN_MAX_WIDTH\n ? 3.375 * REM\n : 4 * REM;\n\n const composerWidth = canPost\n ? messageListWidth - sidePadding - sendButtonWidth\n : messageListWidth - sidePadding;\n const toolbarWidth = windowWidth > MOBILE_SCREEN_MAX_WIDTH\n ? Math.min(messageListWidth - sidePadding, MAX_TOOLBAR_WIDTH)\n : messageListWidth - sidePadding;\n\n const composerHiddenScale = toolbarWidth / composerWidth;\n const toolbarHiddenScale = composerWidth / toolbarWidth;\n const unpinHiddenScale = toolbarWidth / UNPIN_BUTTON_WIDTH;\n const toolbarForUnpinHiddenScale = UNPIN_BUTTON_WIDTH / toolbarWidth;\n\n const composerTranslateX = canPost\n ? (sendButtonWidth / 2) * toolbarHiddenScale\n : 0;\n\n const toolbarTranslateX = canPost\n ? (sendButtonWidth / 2) * -1 * composerHiddenScale\n : 0;\n\n return {\n composerHiddenScale,\n toolbarHiddenScale,\n composerTranslateX,\n toolbarTranslateX,\n unpinHiddenScale,\n toolbarForUnpinHiddenScale,\n };\n}\n\nfunction getMessageListWidth(windowWidth: number) {\n if (windowWidth > MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN) {\n const leftColumnWidth = Math.min(\n Math.max(windowWidth * 0.25, MIN_LEFT_COLUMN_WIDTH),\n SIDE_COLUMN_MAX_WIDTH,\n );\n\n const rightColumnWidth = Math.min(\n windowWidth * 0.25,\n SIDE_COLUMN_MAX_WIDTH,\n );\n\n return Math.min(\n windowWidth - leftColumnWidth - rightColumnWidth,\n MAX_MESSAGES_LIST_WIDTH,\n );\n }\n\n if (windowWidth > MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN) {\n const leftColumnWidth = Math.min(\n Math.max(windowWidth * 0.4, MIN_LEFT_COLUMN_WIDTH),\n SIDE_COLUMN_MAX_WIDTH,\n );\n\n return Math.min(\n windowWidth - leftColumnWidth,\n MAX_MESSAGES_LIST_WIDTH,\n );\n }\n\n if (windowWidth > MAX_MESSAGES_LIST_WIDTH) {\n return MAX_MESSAGES_LIST_WIDTH;\n }\n\n return windowWidth;\n}\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './HeaderMenuContainer';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst HeaderMenuContainerAsync: FC = (props) => {\n const { isOpen } = props;\n const HeaderMenuContainer = useModuleLoader(Bundles.Extra, 'HeaderMenuContainer', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return HeaderMenuContainer ? : undefined;\n};\n\nexport default memo(HeaderMenuContainerAsync);\n","import React, {\n FC,\n memo,\n useRef,\n useCallback,\n useState,\n useEffect,\n} from '../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../lib/teact/teactn';\n\nimport { MessageListType } from '../../global/types';\nimport { MAIN_THREAD_ID } from '../../api/types';\nimport { IAnchorPosition } from '../../types';\n\nimport {\n ARE_CALLS_SUPPORTED, IS_MAC_OS, IS_PWA, IS_SINGLE_COLUMN_LAYOUT,\n} from '../../util/environment';\nimport getKeyFromEvent from '../../util/getKeyFromEvent';\nimport {\n isChatBasicGroup, isChatChannel, isChatSuperGroup, isUserId,\n} from '../../modules/helpers';\nimport {\n selectChat,\n selectChatBot,\n selectIsUserBlocked,\n selectIsChatBotNotStarted,\n selectIsChatWithSelf,\n selectIsInSelectMode,\n selectIsRightColumnShown,\n} from '../../modules/selectors';\nimport useLang from '../../hooks/useLang';\n\nimport Button from '../ui/Button';\nimport HeaderMenuContainer from './HeaderMenuContainer.async';\n\ninterface OwnProps {\n chatId: string;\n threadId: number;\n messageListType: MessageListType;\n canExpandActions: boolean;\n}\n\ninterface StateProps {\n noMenu?: boolean;\n isChannel?: boolean;\n isRightColumnShown?: boolean;\n canStartBot?: boolean;\n canRestartBot?: boolean;\n canSubscribe?: boolean;\n canSearch?: boolean;\n canCall?: boolean;\n canMute?: boolean;\n canLeave?: boolean;\n canEnterVoiceChat?: boolean;\n canCreateVoiceChat?: boolean;\n}\n\n// Chrome breaks layout when focusing input during transition\nconst SEARCH_FOCUS_DELAY_MS = 400;\n\nconst HeaderActions: FC = ({\n chatId,\n threadId,\n noMenu,\n isChannel,\n canStartBot,\n canRestartBot,\n canSubscribe,\n canSearch,\n canCall,\n canMute,\n canLeave,\n canEnterVoiceChat,\n canCreateVoiceChat,\n isRightColumnShown,\n canExpandActions,\n}) => {\n const {\n joinChannel,\n sendBotCommand,\n openLocalTextSearch,\n restartBot,\n openCallFallbackConfirm,\n } = getDispatch();\n\n // eslint-disable-next-line no-null/no-null\n const menuButtonRef = useRef(null);\n const [isMenuOpen, setIsMenuOpen] = useState(false);\n const [menuPosition, setMenuPosition] = useState(undefined);\n\n const handleHeaderMenuOpen = useCallback(() => {\n setIsMenuOpen(true);\n const rect = menuButtonRef.current!.getBoundingClientRect();\n setMenuPosition({ x: rect.right, y: rect.bottom });\n }, []);\n\n const handleHeaderMenuClose = useCallback(() => {\n setIsMenuOpen(false);\n }, []);\n\n const handleHeaderMenuHide = useCallback(() => {\n setMenuPosition(undefined);\n }, []);\n\n const handleSubscribeClick = useCallback(() => {\n joinChannel({ chatId });\n }, [joinChannel, chatId]);\n\n const handleStartBot = useCallback(() => {\n sendBotCommand({ command: '/start' });\n }, [sendBotCommand]);\n\n const handleRestartBot = useCallback(() => {\n restartBot({ chatId });\n }, [chatId, restartBot]);\n\n const handleSearchClick = useCallback(() => {\n openLocalTextSearch();\n\n if (IS_SINGLE_COLUMN_LAYOUT) {\n // iOS requires synchronous focus on user event.\n const searchInput = document.querySelector('#MobileSearch input')!;\n searchInput.focus();\n } else {\n setTimeout(() => {\n const searchInput = document.querySelector('.RightHeader .SearchInput input');\n if (searchInput) {\n searchInput.focus();\n }\n }, SEARCH_FOCUS_DELAY_MS);\n }\n }, [openLocalTextSearch]);\n\n useEffect(() => {\n if (!canSearch) {\n return undefined;\n }\n\n function handleKeyDown(e: KeyboardEvent) {\n if (\n IS_PWA && ((IS_MAC_OS && e.metaKey) || (!IS_MAC_OS && e.ctrlKey)) && !e.shiftKey && getKeyFromEvent(e) === 'f'\n ) {\n e.preventDefault();\n handleSearchClick();\n }\n }\n\n document.addEventListener('keydown', handleKeyDown, false);\n\n return () => {\n document.removeEventListener('keydown', handleKeyDown, false);\n };\n }, [canSearch, handleSearchClick]);\n\n const lang = useLang();\n\n return (\n
\n {!IS_SINGLE_COLUMN_LAYOUT && (\n <>\n {canExpandActions && canSubscribe && (\n \n {lang(isChannel ? 'ProfileJoinChannel' : 'ProfileJoinGroup')}\n \n )}\n {canExpandActions && canStartBot && (\n \n {lang('BotStart')}\n \n )}\n {canExpandActions && canRestartBot && (\n \n {lang('BotRestart')}\n \n )}\n {canSearch && (\n \n \n \n )}\n {canCall && (\n \n \n \n )}\n \n )}\n \n \n \n {menuPosition && (\n \n )}\n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { chatId, threadId, messageListType }): StateProps => {\n const chat = selectChat(global, chatId);\n const isChannel = Boolean(chat && isChatChannel(chat));\n\n if (!chat || chat.isRestricted || selectIsInSelectMode(global)) {\n return {\n noMenu: true,\n };\n }\n\n const bot = selectChatBot(global, chatId);\n const isChatWithSelf = selectIsChatWithSelf(global, chatId);\n const isMainThread = messageListType === 'thread' && threadId === MAIN_THREAD_ID;\n const isDiscussionThread = messageListType === 'thread' && threadId !== MAIN_THREAD_ID;\n const isRightColumnShown = selectIsRightColumnShown(global);\n\n const canRestartBot = Boolean(bot && selectIsUserBlocked(global, bot.id));\n const canStartBot = !canRestartBot && Boolean(selectIsChatBotNotStarted(global, chatId));\n const canSubscribe = Boolean(\n isMainThread && (isChannel || isChatSuperGroup(chat)) && chat.isNotJoined,\n );\n const canSearch = isMainThread || isDiscussionThread;\n const canCall = ARE_CALLS_SUPPORTED && isUserId(chat.id) && !isChatWithSelf && !bot;\n const canMute = isMainThread && !isChatWithSelf && !canSubscribe;\n const canLeave = isMainThread && !canSubscribe;\n const canEnterVoiceChat = ARE_CALLS_SUPPORTED && chat.isCallActive;\n const canCreateVoiceChat = ARE_CALLS_SUPPORTED && !chat.isCallActive\n && (chat.adminRights?.manageCall || (chat.isCreator && isChatBasicGroup(chat)));\n\n return {\n noMenu: false,\n isChannel,\n isRightColumnShown,\n canStartBot,\n canRestartBot,\n canSubscribe,\n canSearch,\n canCall,\n canMute,\n canLeave,\n canEnterVoiceChat,\n canCreateVoiceChat,\n };\n },\n)(HeaderActions));\n","import { useLayoutEffect, useState } from '../lib/teact/teact';\n\nimport { ApiMessage } from '../api/types';\n\nimport { DEBUG } from '../config';\nimport { isWebpSupported } from '../util/environment';\nimport { EMPTY_IMAGE_DATA_URI, webpToPngBase64 } from '../util/webpToPng';\nimport { getMessageMediaThumbDataUri } from '../modules/helpers';\n\nexport default function useWebpThumbnail(message?: ApiMessage) {\n const thumbDataUri = message && getMessageMediaThumbDataUri(message);\n const sticker = message?.content?.sticker;\n const shouldDecodeThumbnail = thumbDataUri && sticker && !isWebpSupported() && thumbDataUri.includes('image/webp');\n const [thumbnailDecoded, setThumbnailDecoded] = useState(EMPTY_IMAGE_DATA_URI);\n const messageId = message?.id;\n\n useLayoutEffect(() => {\n if (!shouldDecodeThumbnail) {\n return;\n }\n\n webpToPngBase64(`b64-${messageId}`, thumbDataUri!)\n .then(setThumbnailDecoded)\n .catch((err) => {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n });\n }, [messageId, shouldDecodeThumbnail, thumbDataUri]);\n\n return shouldDecodeThumbnail ? thumbnailDecoded : thumbDataUri;\n}\n","import React, {\n FC,\n useRef,\n useEffect,\n useMemo,\n memo,\n} from '../../lib/teact/teact';\n\nimport buildClassName from '../../util/buildClassName';\n\ntype OwnProps = {\n count: number;\n index: number;\n};\n\nconst BORDER_MASK_LEVEL = 4;\n\nconst PinnedMessageNavigation: FC = ({\n count, index,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef(null);\n\n const markupParams = useMemo(() => {\n return calculateMarkup(count, index);\n }, [count, index]);\n\n useEffect(() => {\n if (!containerRef.current) {\n return;\n }\n\n const {\n trackHeight,\n trackTranslateY,\n markHeight,\n markTranslateY,\n clipPathId,\n clipPath,\n } = markupParams;\n\n const firstChild = containerRef.current.firstElementChild;\n if (containerRef?.current) {\n const currentElement = containerRef.current;\n const { style } = currentElement;\n style.height = `${trackHeight}px`;\n style.transform = `translateY(-${trackTranslateY}px)`;\n style.clipPath = `url(\"#${clipPathId}\")`;\n const svg = currentElement.querySelector('svg');\n const div = currentElement.querySelector('div');\n const defs = currentElement.querySelector('defs');\n if (!svg) {\n if (firstChild) {\n firstChild.innerHTML = ` ${clipPath} `;\n }\n }\n if (defs) {\n defs.innerHTML = clipPath;\n }\n if (div) {\n div.style.height = `${markHeight}px`;\n div.style.transform = `translateY(${markTranslateY}px)`;\n }\n }\n }, [markupParams]);\n\n if (count === 1) {\n return (\n
\n \n
\n );\n }\n\n const {\n trackHeight, trackTranslateY, markHeight, markTranslateY, clipPathId,\n } = markupParams;\n\n return (\n
BORDER_MASK_LEVEL && 'pinned-message-border-mask')}>\n \n \n \n
\n \n );\n};\n\nfunction calculateMarkup(count: number, index: number) {\n const reverseIndex = count - index - 1;\n const barHeight = getBarHeight(count);\n const markHeight = getMarkHeight(count, reverseIndex);\n const trackHeight = getTrackHeight(count, barHeight);\n\n const clipPathId = `clipPath${count}`;\n const clipPath = getClipPath(clipPathId, barHeight, count);\n\n const markTranslateY = getMarkTranslateY(reverseIndex, barHeight, count);\n const trackTranslateY = getTrackTranslateY(reverseIndex, count, barHeight, trackHeight);\n return {\n markHeight,\n clipPath,\n markTranslateY,\n trackTranslateY,\n trackHeight,\n clipPathId,\n };\n}\n\nfunction getBarHeight(count: number): number {\n let barHeight = 8;\n if (count === 1) {\n barHeight = 36;\n } else if (count === 2) {\n barHeight = 17;\n } else if (count === 3) {\n barHeight = 11;\n } else if (count === 4) {\n barHeight = 7.5;\n } else if (count > 3) {\n barHeight = 7.5;\n }\n\n return barHeight;\n}\n\nfunction getMarkHeight(count: number, index: number) {\n let barHeight = 36;\n if (count === 1) {\n barHeight = 36;\n } else if (count === 2) {\n barHeight = 17;\n } else if (count === 3) {\n barHeight = index === 1 ? 12 : 11;\n } else if (count === 4) {\n barHeight = 7.5;\n } else if (count > 3) {\n barHeight = 7.5;\n }\n\n return barHeight;\n}\n\nfunction getTrackHeight(count: number, barHeight: number) {\n return count <= 3 ? 36 : barHeight * count + 2 * (count - 1);\n}\n\nfunction getClipPath(id: string, barHeight: number, count: number) {\n const radius = 1;\n\n let d = '';\n if (count === 3) {\n d = drawRect(0, 0, 2, barHeight, radius)\n + drawRect(0, 12, 2, barHeight + 1, radius)\n + drawRect(0, 25, 2, barHeight, radius);\n } else {\n for (let i = 0; i < count; i++) {\n d += drawRect(0, (barHeight + 2) * i, 2, barHeight, radius);\n }\n }\n\n return (\n `\n \n `\n );\n}\n\nfunction drawRect(x: number, y: number, width: number, height: number, radius: number) {\n return `M${x},${y + radius}a${radius},${radius},0,0,1,\n ${width},0v${height - 2 * radius}a${radius},${radius},0,0,1,${-width},0Z`;\n}\n\nfunction getMarkTranslateY(index: number, barHeight: number, count: number) {\n if (count === 1) {\n return 0;\n } else if (count === 2) {\n return index === 0 ? 0 : barHeight + 2;\n }\n\n if (count === 3) {\n if (index === 0) {\n return 0;\n } else if (index === 1) {\n return 12;\n }\n\n return 25;\n } else {\n return (barHeight + 2) * index;\n }\n}\n\nfunction getTrackTranslateY(index: number, count: number, barHeight: number, trackHeight: number) {\n if (count <= 4) {\n return 0;\n }\n\n if (index <= 1) {\n return 0;\n } else if (index >= count - 2) {\n return trackHeight - 36;\n }\n\n return (barHeight + 4) / 2 + (index - 2) * (barHeight + 2);\n}\n\nexport default memo(PinnedMessageNavigation);\n","import React, { FC, memo, useCallback } from '../../lib/teact/teact';\n\nimport { ApiMessage } from '../../api/types';\n\nimport { getPictogramDimensions } from '../common/helpers/mediaDimensions';\nimport { getMessageMediaHash, getMessageSummaryText } from '../../modules/helpers';\nimport renderText from '../common/helpers/renderText';\nimport useMedia from '../../hooks/useMedia';\nimport useWebpThumbnail from '../../hooks/useWebpThumbnail';\n\nimport ConfirmDialog from '../ui/ConfirmDialog';\nimport Button from '../ui/Button';\nimport RippleEffect from '../ui/RippleEffect';\nimport buildClassName from '../../util/buildClassName';\nimport useFlag from '../../hooks/useFlag';\nimport useLang from '../../hooks/useLang';\n\nimport PinnedMessageNavigation from './PinnedMessageNavigation';\n\ntype OwnProps = {\n message: ApiMessage;\n index: number;\n count: number;\n customTitle?: string;\n className?: string;\n onUnpinMessage?: (id: number) => void;\n onClick?: () => void;\n onAllPinnedClick?: () => void;\n};\n\nconst HeaderPinnedMessage: FC = ({\n message, count, index, customTitle, className, onUnpinMessage, onClick, onAllPinnedClick,\n}) => {\n const lang = useLang();\n const mediaThumbnail = useWebpThumbnail(message);\n const mediaBlobUrl = useMedia(getMessageMediaHash(message, 'pictogram'));\n\n const text = getMessageSummaryText(lang, message, Boolean(mediaThumbnail));\n const [isUnpinDialogOpen, openUnpinDialog, closeUnpinDialog] = useFlag();\n\n const handleUnpinMessage = useCallback(() => {\n closeUnpinDialog();\n\n if (onUnpinMessage) {\n onUnpinMessage(message.id);\n }\n }, [closeUnpinDialog, onUnpinMessage, message.id]);\n\n return (\n
\n {count > 1 && (\n \n \n \n )}\n {onUnpinMessage && (\n \n \n \n )}\n \n
\n \n {mediaThumbnail && renderPictogram(mediaThumbnail, mediaBlobUrl)}\n
\n
\n {customTitle || `${lang('PinnedMessage')} ${index > 0 ? `#${count - index}` : ''}`}\n
\n

{renderText(text)}

\n
\n\n \n
\n
\n );\n};\n\nfunction renderPictogram(thumbDataUri: string, blobUrl?: string) {\n const { width, height } = getPictogramDimensions();\n\n return (\n \"\"\n );\n}\n\nexport default memo(HeaderPinnedMessage);\n","export function scaleImage(image: string | Blob, ratio: number, outputType: string = 'image/png'): Promise {\n const url = image instanceof Blob ? URL.createObjectURL(image) : image;\n const img = new Image();\n return new Promise((resolve) => {\n img.onload = () => {\n scale(img, img.width * ratio, img.height * ratio, outputType)\n .then((blob) => URL.createObjectURL(blob))\n .then(resolve)\n .finally(() => {\n if (image instanceof Blob) {\n URL.revokeObjectURL(url); // Revoke blob url that we created\n }\n });\n };\n img.src = url;\n });\n}\n\nexport function resizeImage(\n image: string | Blob, width: number, height: number, outputType: string = 'image/png',\n): Promise {\n const url = image instanceof Blob ? URL.createObjectURL(image) : image;\n const img = new Image();\n return new Promise((resolve) => {\n img.onload = () => {\n scale(img, width, height, outputType)\n .then((blob) => URL.createObjectURL(blob))\n .then(resolve)\n .finally(() => {\n if (image instanceof Blob) {\n URL.revokeObjectURL(url); // Revoke blob url that we created\n }\n });\n };\n img.src = url;\n });\n}\n\nasync function scale(\n img: HTMLImageElement, width: number, height: number, outputType: string = 'image/png',\n) {\n // Safari does not have built-in resize method with quality control\n if ('createImageBitmap' in window) {\n try {\n const bitmap = await window.createImageBitmap(img,\n { resizeWidth: width, resizeHeight: height, resizeQuality: 'high' });\n if (bitmap.height !== height || bitmap.width !== width) {\n throw new Error('Image bitmap resize not supported!'); // FF93 added support for options, but not resize\n }\n return await new Promise((res) => {\n const canvas = document.createElement('canvas');\n canvas.width = bitmap.width;\n canvas.height = bitmap.height;\n const ctx = canvas.getContext('bitmaprenderer');\n if (ctx) {\n ctx.transferFromImageBitmap(bitmap);\n } else {\n canvas.getContext('2d')!.drawImage(bitmap, 0, 0);\n }\n canvas.toBlob(res, outputType);\n });\n } catch (e) {\n // Fallback. Firefox below 93 does not recognize `createImageBitmap` with 2 parameters\n return steppedScale(img, width, height, undefined, outputType);\n }\n } else {\n return steppedScale(img, width, height, undefined, outputType);\n }\n}\n\nfunction steppedScale(\n img: HTMLImageElement, width: number, height: number, step: number = 0.5, outputType: string = 'image/png',\n): Promise {\n const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d')!;\n const oc = document.createElement('canvas');\n const octx = oc.getContext('2d')!;\n\n canvas.width = width;\n canvas.height = height;\n\n if (img.width * step > width) { // For performance avoid unnecessary drawing\n const mul = 1 / step;\n let cur = {\n width: Math.floor(img.width * step),\n height: Math.floor(img.height * step),\n };\n\n oc.width = cur.width;\n oc.height = cur.height;\n\n octx.drawImage(img, 0, 0, cur.width, cur.height);\n\n while (cur.width * step > width) {\n cur = {\n width: Math.floor(cur.width * step),\n height: Math.floor(cur.height * step),\n };\n octx.drawImage(oc, 0, 0, cur.width * mul, cur.height * mul, 0, 0, cur.width, cur.height);\n }\n\n ctx.drawImage(oc, 0, 0, cur.width, cur.height, 0, 0, canvas.width, canvas.height);\n } else {\n ctx.drawImage(img, 0, 0, canvas.width, canvas.height);\n }\n\n return new Promise((resolve) => {\n canvas.toBlob(resolve, outputType);\n });\n}\n","import { useMemo } from '../lib/teact/teact';\n\nimport {\n ApiAudio, ApiChat, ApiMessage, ApiUser, ApiVoice,\n} from '../api/types';\n\nimport useMedia from './useMedia';\nimport { useAsync } from './useAsync';\nimport {\n getAudioHasCover, getChatAvatarHash, getChatTitle, getMessageContent, getMessageMediaHash, getSenderTitle,\n} from '../modules/helpers';\nimport { getTranslation } from '../util/langProvider';\nimport { buildMediaMetadata } from '../util/mediaSession';\nimport { scaleImage, resizeImage } from '../util/imageResize';\nimport { AVATAR_FULL_DIMENSIONS } from '../components/common/helpers/mediaDimensions';\n\n// @ts-ignore\nimport telegramLogoPath from '../assets/telegram-logo-filled.svg';\n\nconst LOGO_DIMENSIONS = { width: 200, height: 200 };\nconst MINIMAL_SIZE = 115; // spec says 100, but on Chrome 93 it's not showing\n\n// TODO Add support for video in future\nexport default (message: ApiMessage, sender?: ApiUser | ApiChat, chat?: ApiChat): MediaMetadata | undefined => {\n const { audio, voice } = getMessageContent(message);\n const title = audio ? (audio.title || audio.fileName) : voice ? 'Voice message' : '';\n const artist = (audio && audio.performer) || (sender && getSenderTitle(getTranslation, sender));\n const album = (chat && getChatTitle(getTranslation, chat)) || 'Telegram';\n\n const audioCoverHash = (audio && getAudioHasCover(audio) && getMessageMediaHash(message, 'pictogram'));\n const avatarHash = sender && getChatAvatarHash(sender, 'big');\n const hash = (audio && audioCoverHash) || (voice && avatarHash);\n const media = useMedia(hash);\n\n const size = useMemo(() => {\n return getCoverSize(audio, voice, media);\n }, [audio, media, voice]);\n const { result: url } = useAsync(() => makeGoodArtwork(media, size), [media, size], telegramLogoPath);\n return useMemo(() => {\n return buildMediaMetadata({\n title,\n artist,\n album,\n artwork: [{ src: url }],\n });\n }, [album, artist, title, url]);\n};\n\nfunction makeGoodArtwork(url?: string, size?: { width: number; height: number }): Promise {\n if (!url) return Promise.resolve(telegramLogoPath);\n if (!size) return resizeImage(url, MINIMAL_SIZE, MINIMAL_SIZE);\n const min = Math.min(size.width, size.height);\n if (min < MINIMAL_SIZE) {\n const ratio = MINIMAL_SIZE / min;\n return scaleImage(url, ratio);\n }\n return Promise.resolve(url);\n}\n\nfunction getCoverSize(audio?: ApiAudio, voice?: ApiVoice, url?: string) {\n if (!url) return LOGO_DIMENSIONS;\n if (audio) {\n if (!audio.thumbnailSizes || audio.thumbnailSizes.length === 0) return undefined;\n const preferred = audio.thumbnailSizes.find((size) => size.type === 'm');\n return preferred || audio.thumbnailSizes[0]; // Sometimes `m` is not present\n }\n\n if (voice) {\n return AVATAR_FULL_DIMENSIONS;\n }\n\n return undefined;\n}\n","import { useEffect, useState } from '../lib/teact/teact';\n\nexport const useAsync = (fn: () => Promise, deps: any[], defaultValue?: T) => {\n const [isLoading, setIsLoading] = useState(false);\n const [error, setError] = useState();\n const [result, setResult] = useState(defaultValue);\n useEffect(() => {\n setIsLoading(true);\n let wasCancelled = false;\n fn().then((res) => {\n if (wasCancelled) return;\n setIsLoading(false);\n setResult(res);\n }, (err) => {\n if (wasCancelled) return;\n setIsLoading(false);\n setError(err);\n });\n return () => {\n wasCancelled = true;\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, deps);\n return { isLoading, error, result };\n};\n","import React, {\n FC, useCallback, useEffect, useMemo,\n} from '../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../lib/teact/teactn';\n\nimport { AudioOrigin } from '../../types';\nimport {\n ApiAudio, ApiChat, ApiMessage, ApiUser,\n} from '../../api/types';\n\nimport { IS_IOS, IS_SINGLE_COLUMN_LAYOUT, IS_TOUCH_ENV } from '../../util/environment';\n\nimport * as mediaLoader from '../../util/mediaLoader';\nimport {\n getMediaDuration, getMessageContent, getMessageMediaHash, getSenderTitle, isMessageLocal,\n} from '../../modules/helpers';\nimport { selectChat, selectSender } from '../../modules/selectors';\nimport buildClassName from '../../util/buildClassName';\nimport { makeTrackId } from '../../util/audioPlayer';\nimport { clearMediaSession } from '../../util/mediaSession';\nimport windowSize from '../../util/windowSize';\nimport useAudioPlayer from '../../hooks/useAudioPlayer';\nimport useLang from '../../hooks/useLang';\nimport useMessageMediaMetadata from '../../hooks/useMessageMediaMetadata';\nimport renderText from '../common/helpers/renderText';\n\nimport RippleEffect from '../ui/RippleEffect';\nimport Button from '../ui/Button';\nimport RangeSlider from '../ui/RangeSlider';\n\nimport './AudioPlayer.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n origin?: AudioOrigin;\n className?: string;\n noUi?: boolean;\n};\n\ntype StateProps = {\n sender?: ApiChat | ApiUser;\n chat?: ApiChat;\n volume: number;\n playbackRate: number;\n isMuted: boolean;\n};\n\nconst FAST_PLAYBACK_RATE = 1.8;\n\nconst AudioPlayer: FC = ({\n message,\n className,\n noUi,\n sender,\n chat,\n volume,\n playbackRate,\n isMuted,\n}) => {\n const {\n setAudioPlayerVolume,\n setAudioPlayerPlaybackRate,\n setAudioPlayerMuted,\n focusMessage,\n closeAudioPlayer,\n } = getDispatch();\n\n const lang = useLang();\n const { audio, voice, video } = getMessageContent(message);\n const isVoice = Boolean(voice || video);\n const senderName = sender ? getSenderTitle(lang, sender) : undefined;\n const mediaData = mediaLoader.getFromMemory(getMessageMediaHash(message, 'inline')!) as (string | undefined);\n const mediaMetadata = useMessageMediaMetadata(message, sender, chat);\n\n const {\n playPause,\n stop,\n isPlaying,\n requestNextTrack,\n requestPreviousTrack,\n isFirst,\n isLast,\n setVolume,\n toggleMuted,\n setPlaybackRate,\n } = useAudioPlayer(\n makeTrackId(message),\n getMediaDuration(message)!,\n isVoice ? 'voice' : 'audio',\n mediaData,\n undefined,\n mediaMetadata,\n undefined,\n true,\n undefined,\n undefined,\n isMessageLocal(message),\n true,\n );\n\n // Prevent refresh by accidentally rotating device when listening to a voice message\n const isVoicePlaying = isVoice && isPlaying;\n useEffect(() => {\n if (!isVoicePlaying) {\n return undefined;\n }\n\n windowSize.disableRefresh();\n\n return () => {\n windowSize.enableRefresh();\n };\n }, [isVoicePlaying]);\n\n const handleClick = useCallback(() => {\n focusMessage({ chatId: message.chatId, messageId: message.id });\n }, [focusMessage, message.chatId, message.id]);\n\n const handleClose = useCallback(() => {\n if (isPlaying) {\n playPause();\n }\n closeAudioPlayer();\n clearMediaSession();\n stop();\n }, [closeAudioPlayer, isPlaying, playPause, stop]);\n\n const handleVolumeChange = useCallback((value: number) => {\n setAudioPlayerVolume({ volume: value / 100 });\n setAudioPlayerMuted({ isMuted: false });\n\n setVolume(value / 100);\n }, [setAudioPlayerMuted, setAudioPlayerVolume, setVolume]);\n\n const handleVolumeClick = useCallback(() => {\n if (IS_TOUCH_ENV && !IS_IOS) return;\n toggleMuted();\n setAudioPlayerMuted({ isMuted: !isMuted });\n }, [isMuted, setAudioPlayerMuted, toggleMuted]);\n\n const handlePlaybackClick = useCallback(() => {\n if (playbackRate === 1) {\n setPlaybackRate(FAST_PLAYBACK_RATE);\n setAudioPlayerPlaybackRate({ playbackRate: FAST_PLAYBACK_RATE });\n } else {\n setPlaybackRate(1);\n setAudioPlayerPlaybackRate({ playbackRate: 1 });\n }\n }, [playbackRate, setAudioPlayerPlaybackRate, setPlaybackRate]);\n\n const volumeIcon = useMemo(() => {\n if (volume === 0 || isMuted) return 'icon-muted';\n if (volume < 0.3) return 'icon-volume-1';\n if (volume < 0.6) return 'icon-volume-2';\n return 'icon-volume-3';\n }, [volume, isMuted]);\n\n if (noUi) {\n return undefined;\n }\n\n return (\n
\n \n \n \n \n \n \n \n \n \n \n\n
\n {audio ? renderAudio(audio) : renderVoice(lang('AttachAudio'), senderName)}\n \n
\n\n \n \n {!IS_IOS && (\n <>\n
\n
\n \n
\n \n )}\n \n\n {isVoice && (\n \n \n \n )}\n\n \n \n \n
\n );\n};\n\nfunction renderAudio(audio: ApiAudio) {\n const { title, performer, fileName } = audio;\n\n return (\n <>\n
{renderText(title || fileName)}
\n {performer && (\n
{renderText(performer)}
\n )}\n \n );\n}\n\nfunction renderVoice(subtitle: string, senderName?: string) {\n return (\n <>\n
{senderName && renderText(senderName)}
\n
{subtitle}
\n \n );\n}\n\nexport default withGlobal(\n (global, { message }): StateProps => {\n const sender = selectSender(global, message);\n const chat = selectChat(global, message.chatId);\n const { volume, playbackRate, isMuted } = global.audioPlayer;\n\n return {\n sender,\n chat,\n volume,\n playbackRate,\n isMuted,\n };\n },\n)(AudioPlayer);\n","import React, {\n FC, memo, useCallback, useEffect, useMemo,\n} from '../../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiChat, ApiGroupCall, ApiUser } from '../../../api/types';\n\nimport { selectChatGroupCall } from '../../../modules/selectors/calls';\nimport buildClassName from '../../../util/buildClassName';\nimport { selectChat } from '../../../modules/selectors';\nimport useLang from '../../../hooks/useLang';\n\nimport Button from '../../ui/Button';\nimport Avatar from '../../common/Avatar';\n\nimport './GroupCallTopPane.scss';\n\ntype OwnProps = {\n chatId: string;\n hasPinnedOffset: boolean;\n};\n\ntype StateProps = {\n groupCall?: ApiGroupCall;\n isActive: boolean;\n usersById: Record;\n chatsById: Record;\n};\n\nconst GroupCallTopPane: FC = ({\n chatId,\n isActive,\n groupCall,\n hasPinnedOffset,\n usersById,\n chatsById,\n}) => {\n const {\n joinGroupCall,\n subscribeToGroupCallUpdates,\n } = getDispatch();\n\n const lang = useLang();\n\n const handleJoinGroupCall = useCallback(() => {\n joinGroupCall({\n chatId,\n });\n }, [joinGroupCall, chatId]);\n\n const participants = groupCall?.participants;\n\n const fetchedParticipants = useMemo(() => {\n if (participants) {\n return Object.values(participants).filter((_, i) => i < 3).map(({ id, isUser }) => {\n if (isUser) {\n if (!usersById[id]) {\n return undefined;\n }\n return { user: usersById[id] };\n } else {\n if (!chatsById[id]) {\n return undefined;\n }\n return { chat: chatsById[id] };\n }\n }).filter(Boolean);\n } else return [];\n }, [chatsById, participants, usersById]);\n\n useEffect(() => {\n if (!groupCall?.id) return undefined;\n if (!isActive && groupCall.isLoaded) return undefined;\n\n subscribeToGroupCallUpdates({\n id: groupCall.id,\n subscribed: true,\n });\n\n return () => {\n subscribeToGroupCallUpdates({\n id: groupCall.id,\n subscribed: false,\n });\n };\n }, [groupCall?.id, groupCall?.isLoaded, isActive, subscribeToGroupCallUpdates]);\n\n if (!groupCall) return undefined;\n\n return (\n \n
\n {lang('VoipGroupVoiceChat')}\n {lang('Participants', groupCall.participantsCount || 0, 'i')}\n
\n
\n {fetchedParticipants.map((p) => {\n if (!p) return undefined;\n if (p.user) {\n return ;\n } else {\n return ;\n }\n })}\n
\n \n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { chatId }) => {\n const chat = selectChat(global, chatId)!;\n const groupCall = selectChatGroupCall(global, chatId);\n return {\n groupCall,\n usersById: global.users.byId,\n chatsById: global.chats.byId,\n activeGroupCallId: global.groupCalls.activeGroupCallId,\n isActive: ((!groupCall ? (chat && chat.isCallNotEmpty && chat.isCallActive)\n : (groupCall.participantsCount > 0 && groupCall.isLoaded)))\n && (global.groupCalls.activeGroupCallId !== groupCall?.id),\n };\n },\n)(GroupCallTopPane));\n","import React, {\n FC, useCallback, useMemo, memo, useEffect, useRef, useState,\n} from '../../lib/teact/teact';\nimport { getDispatch, getGlobal, withGlobal } from '../../lib/teact/teactn';\nimport cycleRestrict from '../../util/cycleRestrict';\n\nimport { MessageListType } from '../../global/types';\nimport {\n ApiMessage,\n ApiChat,\n ApiUser,\n ApiTypingStatus,\n MAIN_THREAD_ID, ApiUpdateConnectionStateType,\n} from '../../api/types';\n\nimport {\n MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN,\n MOBILE_SCREEN_MAX_WIDTH,\n EDITABLE_INPUT_ID,\n MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN,\n SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN,\n SAFE_SCREEN_WIDTH_FOR_CHAT_INFO,\n} from '../../config';\nimport { IS_SINGLE_COLUMN_LAYOUT, IS_TABLET_COLUMN_LAYOUT } from '../../util/environment';\nimport {\n isUserId,\n getMessageKey,\n getChatTitle,\n getSenderTitle,\n} from '../../modules/helpers';\nimport {\n selectChat,\n selectChatMessage,\n selectAllowedMessageActions,\n selectIsRightColumnShown,\n selectThreadTopMessageId,\n selectThreadInfo,\n selectChatMessages,\n selectPinnedIds,\n selectIsChatWithSelf,\n selectForwardedSender,\n selectScheduledIds,\n selectIsInSelectMode,\n selectIsChatWithBot,\n selectCountNotMutedUnread,\n} from '../../modules/selectors';\nimport useEnsureMessage from '../../hooks/useEnsureMessage';\nimport useWindowSize from '../../hooks/useWindowSize';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useCurrentOrPrev from '../../hooks/useCurrentOrPrev';\nimport { formatIntegerCompact } from '../../util/textFormat';\nimport buildClassName from '../../util/buildClassName';\nimport useLang from '../../hooks/useLang';\nimport useBrowserOnline from '../../hooks/useBrowserOnline';\n\nimport PrivateChatInfo from '../common/PrivateChatInfo';\nimport GroupChatInfo from '../common/GroupChatInfo';\nimport Transition from '../ui/Transition';\nimport Button from '../ui/Button';\nimport HeaderActions from './HeaderActions';\nimport HeaderPinnedMessage from './HeaderPinnedMessage';\nimport AudioPlayer from './AudioPlayer';\nimport GroupCallTopPane from '../calls/group/GroupCallTopPane';\n\nimport './MiddleHeader.scss';\n\nconst ANIMATION_DURATION = 350;\nconst BACK_BUTTON_INACTIVE_TIME = 450;\n\ntype OwnProps = {\n chatId: string;\n threadId: number;\n messageListType: MessageListType;\n isReady?: boolean;\n};\n\ntype StateProps = {\n chat?: ApiChat;\n pinnedMessageIds?: number[] | number;\n messagesById?: Record;\n canUnpin?: boolean;\n topMessageSender?: ApiChat | ApiUser;\n typingStatus?: ApiTypingStatus;\n isSelectModeActive?: boolean;\n isLeftColumnShown?: boolean;\n isRightColumnShown?: boolean;\n audioMessage?: ApiMessage;\n chatsById?: Record;\n messagesCount?: number;\n isChatWithSelf?: boolean;\n isChatWithBot?: boolean;\n lastSyncTime?: number;\n shouldSkipHistoryAnimations?: boolean;\n currentTransitionKey: number;\n connectionState?: ApiUpdateConnectionStateType;\n};\n\nconst MiddleHeader: FC = ({\n chatId,\n threadId,\n messageListType,\n isReady,\n pinnedMessageIds,\n messagesById,\n canUnpin,\n topMessageSender,\n typingStatus,\n isSelectModeActive,\n isLeftColumnShown,\n isRightColumnShown,\n audioMessage,\n chat,\n chatsById,\n messagesCount,\n isChatWithSelf,\n isChatWithBot,\n lastSyncTime,\n shouldSkipHistoryAnimations,\n currentTransitionKey,\n connectionState,\n}) => {\n const {\n openChatWithInfo,\n pinMessage,\n focusMessage,\n openChat,\n openPreviousChat,\n loadPinnedMessages,\n toggleLeftColumn,\n exitMessageSelectMode,\n } = getDispatch();\n\n const lang = useLang();\n const isBackButtonActive = useRef(true);\n\n const [pinnedMessageIndex, setPinnedMessageIndex] = useState(0);\n const pinnedMessageId = Array.isArray(pinnedMessageIds) ? pinnedMessageIds[pinnedMessageIndex] : pinnedMessageIds;\n const pinnedMessage = messagesById && pinnedMessageId ? messagesById[pinnedMessageId] : undefined;\n const pinnedMessagesCount = Array.isArray(pinnedMessageIds)\n ? pinnedMessageIds.length : (pinnedMessageIds ? 1 : undefined);\n const chatTitleLength = chat && getChatTitle(lang, chat).length;\n const topMessageTitle = topMessageSender ? getSenderTitle(lang, topMessageSender) : undefined;\n\n useEffect(() => {\n if (threadId === MAIN_THREAD_ID && lastSyncTime && isReady) {\n loadPinnedMessages({ chatId });\n }\n }, [chatId, loadPinnedMessages, lastSyncTime, threadId, isReady]);\n\n // Reset pinned index when switching chats and pinning/unpinning\n useEffect(() => {\n setPinnedMessageIndex(0);\n }, [pinnedMessageIds]);\n\n useEnsureMessage(chatId, pinnedMessageId, pinnedMessage);\n\n const { width: windowWidth } = useWindowSize();\n\n const isLeftColumnHideable = windowWidth <= MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN;\n const shouldShowCloseButton = IS_TABLET_COLUMN_LAYOUT && isLeftColumnShown;\n\n // eslint-disable-next-line no-null/no-null\n const componentRef = useRef(null);\n const shouldAnimateTools = useRef(true);\n\n const handleHeaderClick = useCallback(() => {\n openChatWithInfo({ id: chatId });\n }, [openChatWithInfo, chatId]);\n\n const handleUnpinMessage = useCallback((messageId: number) => {\n pinMessage({ chatId, messageId, isUnpin: true });\n }, [pinMessage, chatId]);\n\n const handlePinnedMessageClick = useCallback((): void => {\n if (pinnedMessage) {\n focusMessage({ chatId: pinnedMessage.chatId, threadId, messageId: pinnedMessage.id });\n\n const newIndex = cycleRestrict(pinnedMessagesCount || 1, pinnedMessageIndex + 1);\n setPinnedMessageIndex(newIndex);\n }\n }, [pinnedMessage, focusMessage, threadId, pinnedMessagesCount, pinnedMessageIndex]);\n\n const handleAllPinnedClick = useCallback(() => {\n openChat({ id: chatId, threadId: MAIN_THREAD_ID, type: 'pinned' });\n }, [openChat, chatId]);\n\n const setBackButtonActive = useCallback(() => {\n setTimeout(() => {\n isBackButtonActive.current = true;\n }, BACK_BUTTON_INACTIVE_TIME);\n }, []);\n\n const handleBackClick = useCallback((e: React.MouseEvent) => {\n if (!isBackButtonActive.current) return;\n\n // Workaround for missing UI when quickly clicking the Back button\n isBackButtonActive.current = false;\n if (IS_SINGLE_COLUMN_LAYOUT) {\n const messageInput = document.getElementById(EDITABLE_INPUT_ID);\n if (messageInput) {\n messageInput.blur();\n }\n }\n\n if (isSelectModeActive) {\n exitMessageSelectMode();\n setBackButtonActive();\n return;\n }\n\n if (threadId === MAIN_THREAD_ID && messageListType === 'thread' && currentTransitionKey === 0) {\n if (IS_SINGLE_COLUMN_LAYOUT || shouldShowCloseButton) {\n e.stopPropagation(); // Stop propagation to prevent chat re-opening on tablets\n openChat({ id: undefined });\n } else {\n toggleLeftColumn();\n }\n\n setBackButtonActive();\n\n return;\n }\n\n openPreviousChat();\n setBackButtonActive();\n }, [\n threadId, messageListType, currentTransitionKey, isSelectModeActive, openPreviousChat, shouldShowCloseButton,\n openChat, toggleLeftColumn, exitMessageSelectMode, setBackButtonActive,\n ]);\n\n const unreadCount = useMemo(() => {\n if (!isLeftColumnHideable || !chatsById) {\n return undefined;\n }\n\n return selectCountNotMutedUnread(getGlobal()) || undefined;\n }, [isLeftColumnHideable, chatsById]);\n\n const canToolsCollideWithChatInfo = (\n windowWidth >= MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN\n && windowWidth < SAFE_SCREEN_WIDTH_FOR_CHAT_INFO\n ) || (\n windowWidth > MOBILE_SCREEN_MAX_WIDTH\n && windowWidth < MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN\n && (!chatTitleLength || chatTitleLength > 30)\n );\n const shouldUseStackedToolsClass = canToolsCollideWithChatInfo || (\n windowWidth > MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN\n && windowWidth < SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN\n );\n\n const {\n shouldRender: shouldRenderAudioPlayer,\n transitionClassNames: audioPlayerClassNames,\n } = useShowTransition(Boolean(audioMessage));\n\n const renderingAudioMessage = useCurrentOrPrev(audioMessage);\n\n const {\n shouldRender: shouldRenderPinnedMessage,\n transitionClassNames: pinnedMessageClassNames,\n } = useShowTransition(Boolean(pinnedMessage));\n\n const renderingPinnedMessage = useCurrentOrPrev(pinnedMessage, true);\n const renderingPinnedMessagesCount = useCurrentOrPrev(pinnedMessagesCount, true);\n const renderingCanUnpin = useCurrentOrPrev(canUnpin, true);\n const renderingPinnedMessageTitle = useCurrentOrPrev(topMessageTitle);\n\n const canRevealTools = (shouldRenderPinnedMessage && renderingPinnedMessage)\n || (shouldRenderAudioPlayer && renderingAudioMessage);\n\n // Logic for transition to and from custom display of AudioPlayer/PinnedMessage on smaller screens\n useEffect(() => {\n const componentEl = componentRef.current;\n if (!componentEl) {\n return;\n }\n\n if (!shouldUseStackedToolsClass || !canRevealTools) {\n componentEl.classList.remove('tools-stacked', 'animated');\n shouldAnimateTools.current = true;\n return;\n }\n\n if (isRightColumnShown || canToolsCollideWithChatInfo) {\n if (shouldAnimateTools.current) {\n componentEl.classList.add('tools-stacked', 'animated');\n shouldAnimateTools.current = false;\n }\n\n // Remove animation class to prevent it messing up the show transitions\n setTimeout(() => {\n componentEl.classList.remove('animated');\n }, ANIMATION_DURATION);\n } else {\n componentEl.classList.remove('tools-stacked');\n shouldAnimateTools.current = true;\n }\n }, [shouldUseStackedToolsClass, canRevealTools, canToolsCollideWithChatInfo, isRightColumnShown]);\n\n const isBrowserOnline = useBrowserOnline();\n const isConnecting = (!isBrowserOnline || connectionState === 'connectionStateConnecting')\n && (IS_SINGLE_COLUMN_LAYOUT || (IS_TABLET_COLUMN_LAYOUT && !shouldShowCloseButton));\n\n function renderInfo() {\n if (isConnecting) {\n return (\n <>\n {renderBackButton()}\n

\n {lang('WaitingForNetwork')}\n

\n \n );\n }\n return (\n messageListType === 'thread' && threadId === MAIN_THREAD_ID ? (\n renderMainThreadInfo()\n ) : messageListType === 'thread' ? (\n <>\n {renderBackButton()}\n

\n {lang('CommentsCount', messagesCount, 'i')}\n

\n \n ) : messageListType === 'pinned' ? (\n <>\n {renderBackButton()}\n

\n {lang('PinnedMessagesCount', messagesCount, 'i')}\n

\n \n ) : messageListType === 'scheduled' ? (\n <>\n {renderBackButton()}\n

\n {isChatWithSelf ? lang('Reminders') : lang('messages', messagesCount, 'i')}\n

\n \n ) : undefined\n );\n }\n\n function renderMainThreadInfo() {\n return (\n <>\n {(isLeftColumnHideable || currentTransitionKey > 0) && renderBackButton(shouldShowCloseButton, true)}\n
\n {isUserId(chatId) ? (\n \n ) : (\n \n )}\n
\n \n );\n }\n\n function renderBackButton(asClose = false, withUnreadCount = false) {\n return (\n
\n \n
\n \n {withUnreadCount && unreadCount && (\n
\n {formatIntegerCompact(unreadCount)}\n
\n )}\n
\n );\n }\n\n const isAudioPlayerRendered = Boolean(shouldRenderAudioPlayer && renderingAudioMessage);\n\n return (\n
\n \n {renderInfo}\n \n\n \n\n {shouldRenderPinnedMessage && renderingPinnedMessage && (\n \n )}\n
\n {isAudioPlayerRendered && (\n \n )}\n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { chatId, threadId, messageListType }): StateProps => {\n const { isLeftColumnShown, lastSyncTime, shouldSkipHistoryAnimations } = global;\n const { byId: chatsById } = global.chats;\n const chat = selectChat(global, chatId);\n\n const { typingStatus } = chat || {};\n\n const { chatId: audioChatId, messageId: audioMessageId } = global.audioPlayer;\n const audioMessage = audioChatId && audioMessageId\n ? selectChatMessage(global, audioChatId, audioMessageId)\n : undefined;\n\n let messagesCount: number | undefined;\n if (messageListType === 'pinned') {\n const pinnedIds = selectPinnedIds(global, chatId);\n messagesCount = pinnedIds?.length;\n } else if (messageListType === 'scheduled') {\n const scheduledIds = selectScheduledIds(global, chatId);\n messagesCount = scheduledIds?.length;\n } else if (messageListType === 'thread' && threadId !== MAIN_THREAD_ID) {\n const threadInfo = selectThreadInfo(global, chatId, threadId);\n messagesCount = threadInfo?.messagesCount || 0;\n }\n\n const state: StateProps = {\n typingStatus,\n isLeftColumnShown,\n isRightColumnShown: selectIsRightColumnShown(global),\n isSelectModeActive: selectIsInSelectMode(global),\n audioMessage,\n chat,\n chatsById,\n messagesCount,\n isChatWithSelf: selectIsChatWithSelf(global, chatId),\n isChatWithBot: chat && selectIsChatWithBot(global, chat),\n lastSyncTime,\n shouldSkipHistoryAnimations,\n currentTransitionKey: Math.max(0, global.messages.messageLists.length - 1),\n connectionState: global.connectionState,\n };\n\n const messagesById = selectChatMessages(global, chatId);\n if (messageListType !== 'thread' || !messagesById) {\n return state;\n }\n\n Object.assign(state, { messagesById });\n\n if (threadId !== MAIN_THREAD_ID) {\n const pinnedMessageId = selectThreadTopMessageId(global, chatId, threadId);\n const message = pinnedMessageId ? selectChatMessage(global, chatId, pinnedMessageId) : undefined;\n const topMessageSender = message ? selectForwardedSender(global, message) : undefined;\n\n return {\n ...state,\n pinnedMessageIds: pinnedMessageId,\n canUnpin: false,\n topMessageSender,\n };\n }\n\n const pinnedMessageIds = selectPinnedIds(global, chatId);\n if (pinnedMessageIds?.length) {\n const firstPinnedMessage = messagesById[pinnedMessageIds[0]];\n const {\n canUnpin,\n } = (firstPinnedMessage && selectAllowedMessageActions(global, firstPinnedMessage, threadId)) || {};\n\n return {\n ...state,\n pinnedMessageIds,\n canUnpin,\n };\n }\n\n return state;\n },\n)(MiddleHeader));\n","import { ApiMessage } from '../../../api/types';\nimport { IAlbum } from '../../../types';\n\nimport { getDayStart } from '../../../util/dateFormat';\nimport { isActionMessage } from '../../../modules/helpers';\n\ntype SenderGroup = (ApiMessage | IAlbum)[];\n\nconst GROUP_INTERVAL_SECONDS = 600; // 10 minutes\n\nexport type MessageDateGroup = {\n originalDate: number;\n datetime: number;\n senderGroups: SenderGroup[];\n};\n\nexport function isAlbum(messageOrAlbum: ApiMessage | IAlbum): messageOrAlbum is IAlbum {\n return 'albumId' in messageOrAlbum;\n}\n\nexport function groupMessages(messages: ApiMessage[], firstUnreadId?: number) {\n let currentSenderGroup: SenderGroup = [];\n let currentDateGroup = {\n originalDate: messages[0].date,\n datetime: Number(getDayStart(messages[0].date * 1000)),\n senderGroups: [currentSenderGroup],\n };\n let currentAlbum: IAlbum | undefined;\n\n const dateGroups: MessageDateGroup[] = [currentDateGroup];\n\n messages.forEach((message, index) => {\n if (message.isInAlbum) {\n if (!currentAlbum) {\n currentAlbum = {\n albumId: message.groupedId!,\n messages: [message],\n mainMessage: message,\n };\n } else {\n currentAlbum.messages.push(message);\n if (message.content.text) {\n currentAlbum.mainMessage = message;\n }\n }\n } else {\n currentSenderGroup.push(message);\n }\n\n const nextMessage = messages[index + 1];\n\n if (\n currentAlbum\n && (!nextMessage || !nextMessage.groupedId || nextMessage.groupedId !== currentAlbum.albumId)\n ) {\n currentSenderGroup.push(currentAlbum);\n currentAlbum = undefined;\n }\n if (nextMessage) {\n const nextMessageDayStartsAt = Number(getDayStart(nextMessage.date * 1000));\n if (currentDateGroup.datetime !== nextMessageDayStartsAt) {\n currentDateGroup = {\n originalDate: nextMessage.date,\n datetime: nextMessageDayStartsAt,\n senderGroups: [],\n };\n dateGroups.push(currentDateGroup);\n\n currentSenderGroup = [];\n currentDateGroup.senderGroups.push(currentSenderGroup);\n } else if (\n nextMessage.id === firstUnreadId\n || message.senderId !== nextMessage.senderId\n || message.isOutgoing !== nextMessage.isOutgoing\n || isActionMessage(message)\n || isActionMessage(nextMessage)\n || (\n message.forwardInfo && nextMessage.forwardInfo\n && (\n message.forwardInfo.senderUserId !== nextMessage.forwardInfo.senderUserId\n || message.forwardInfo.fromChatId !== nextMessage.forwardInfo.fromChatId\n || message.forwardInfo.hiddenUserName !== nextMessage.forwardInfo.hiddenUserName\n )\n )\n || message.inlineButtons\n || nextMessage.inlineButtons\n || (nextMessage.date - message.date) > GROUP_INTERVAL_SECONDS\n ) {\n currentSenderGroup = [];\n currentDateGroup.senderGroups.push(currentSenderGroup);\n }\n }\n });\n\n return dateGroups;\n}\n","import { RefObject } from 'react';\nimport { getDispatch } from '../../../lib/teact/teactn';\n\nimport { MessageListType } from '../../../global/types';\n\nimport { IS_ANDROID, IS_SINGLE_COLUMN_LAYOUT } from '../../../util/environment';\nimport { useIntersectionObserver } from '../../../hooks/useIntersectionObserver';\nimport useBackgroundMode from '../../../hooks/useBackgroundMode';\n\nconst INTERSECTION_THROTTLE_FOR_MEDIA = IS_ANDROID ? 1000 : 350;\nconst INTERSECTION_MARGIN_FOR_MEDIA = IS_SINGLE_COLUMN_LAYOUT ? 300 : 500;\nconst INTERSECTION_THROTTLE_FOR_READING = 150;\n\nexport default function useMessageObservers(\n type: MessageListType,\n containerRef: RefObject,\n memoFirstUnreadIdRef: { current: number | undefined },\n) {\n const { markMessageListRead, markMessagesRead } = getDispatch();\n\n const {\n observe: observeIntersectionForMedia,\n } = useIntersectionObserver({\n rootRef: containerRef,\n throttleMs: INTERSECTION_THROTTLE_FOR_MEDIA,\n margin: INTERSECTION_MARGIN_FOR_MEDIA,\n });\n\n const {\n observe: observeIntersectionForReading, freeze: freezeForReading, unfreeze: unfreezeForReading,\n } = useIntersectionObserver({\n rootRef: containerRef,\n throttleMs: INTERSECTION_THROTTLE_FOR_READING,\n }, (entries) => {\n if (type !== 'thread') {\n return;\n }\n\n let maxId = 0;\n const mentionIds: number[] = [];\n\n entries.forEach((entry) => {\n const { isIntersecting, target } = entry;\n\n if (!isIntersecting) {\n return;\n }\n\n const { dataset } = target as HTMLDivElement;\n\n const messageId = Number(dataset.lastMessageId || dataset.messageId);\n if (messageId > maxId) {\n maxId = messageId;\n }\n\n if (dataset.hasUnreadMention) {\n mentionIds.push(messageId);\n }\n });\n\n if (memoFirstUnreadIdRef.current && maxId >= memoFirstUnreadIdRef.current) {\n markMessageListRead({ maxId });\n }\n\n if (mentionIds.length) {\n markMessagesRead({ messageIds: mentionIds });\n }\n });\n\n useBackgroundMode(freezeForReading, unfreezeForReading);\n\n const { observe: observeIntersectionForAnimatedStickers } = useIntersectionObserver({\n rootRef: containerRef,\n throttleMs: INTERSECTION_THROTTLE_FOR_MEDIA,\n });\n\n return {\n observeIntersectionForMedia,\n observeIntersectionForReading,\n observeIntersectionForAnimatedStickers,\n };\n}\n","import { ApiMessage } from '../../../../api/types';\n\nimport { getMessageContent } from '../../../../modules/helpers';\n\nexport function isEmojiOnlyMessage(customShape?: boolean | number) {\n return typeof customShape === 'number';\n}\n\nexport function buildContentClassName(\n message: ApiMessage,\n {\n hasReply,\n customShape,\n isLastInGroup,\n asForwarded,\n hasThread,\n forceSenderName,\n hasComments,\n hasActionButton,\n }: {\n hasReply?: boolean;\n customShape?: boolean | number;\n isLastInGroup?: boolean;\n asForwarded?: boolean;\n hasThread?: boolean;\n forceSenderName?: boolean;\n hasComments?: boolean;\n hasActionButton?: boolean;\n } = {},\n) {\n const {\n text, photo, video, audio, voice, document, poll, webPage, contact,\n } = getMessageContent(message);\n\n const classNames = ['message-content'];\n const isMedia = photo || video;\n const isMediaWithNoText = isMedia && !text;\n const isViaBot = Boolean(message.viaBotId);\n\n if (isEmojiOnlyMessage(customShape)) {\n classNames.push(`emoji-only emoji-only-${customShape}`);\n } else if (text) {\n classNames.push('text');\n }\n\n if (hasActionButton) {\n classNames.push('has-action-button');\n }\n\n if (customShape) {\n classNames.push('custom-shape');\n if (video?.isRound) {\n classNames.push('round');\n }\n\n if (hasComments) {\n classNames.push('has-comments');\n }\n }\n if (photo || video) {\n classNames.push('media');\n } else if (audio) {\n classNames.push('audio');\n } else if (voice) {\n classNames.push('voice');\n } else if (document) {\n classNames.push('document');\n } else if (contact) {\n classNames.push('contact');\n } else if (poll) {\n classNames.push('poll');\n } else if (webPage) {\n classNames.push('web-page');\n\n if (webPage.photo || webPage.video) {\n classNames.push('media');\n }\n }\n\n if (asForwarded) {\n classNames.push('is-forwarded');\n }\n\n if (hasReply) {\n classNames.push('is-reply');\n }\n\n if (hasThread) {\n classNames.push('has-replies');\n }\n\n if (isViaBot) {\n classNames.push('is-via-bot');\n }\n\n if (forceSenderName) {\n classNames.push('force-sender-name');\n }\n\n if (!customShape) {\n classNames.push('has-shadow');\n\n if (isMedia && hasComments) {\n classNames.push('has-background');\n }\n\n if (hasReply || asForwarded || !isMediaWithNoText || isViaBot || forceSenderName) {\n classNames.push('has-solid-background');\n }\n\n if (isLastInGroup && (photo || !isMediaWithNoText)) {\n classNames.push('has-appendix');\n }\n }\n\n return classNames.join(' ');\n}\n","import { ApiMessage } from '../../../../api/types';\nimport { calculateInlineImageDimensions, calculateVideoDimensions } from '../../../common/helpers/mediaDimensions';\nimport {\n getMessageText,\n getMessagePhoto,\n getMessageWebPagePhoto,\n isForwardedMessage,\n isOwnMessage,\n getMessageVideo,\n} from '../../../../modules/helpers';\n\nconst MIN_MEDIA_WIDTH = 100;\nconst MIN_MEDIA_WIDTH_WITH_COMMENTS = 238;\nconst MIN_MEDIA_WIDTH_WITH_TEXT = 175;\nconst MIN_MEDIA_WIDTH_WITH_TEXT_AND_COMMENTS = 238;\nconst MIN_MEDIA_HEIGHT = 90;\nconst SMALL_IMAGE_THRESHOLD = 12;\n\nexport function getMinMediaWidth(hasText?: boolean, hasCommentButton?: boolean) {\n return hasText\n ? (hasCommentButton ? MIN_MEDIA_WIDTH_WITH_TEXT_AND_COMMENTS : MIN_MEDIA_WIDTH_WITH_TEXT)\n : (hasCommentButton ? MIN_MEDIA_WIDTH_WITH_COMMENTS : MIN_MEDIA_WIDTH);\n}\n\nexport function calculateMediaDimensions(message: ApiMessage, noAvatars?: boolean) {\n const isOwn = isOwnMessage(message);\n const isForwarded = isForwardedMessage(message);\n const photo = getMessagePhoto(message) || getMessageWebPagePhoto(message);\n const video = getMessageVideo(message);\n\n const isWebPagePhoto = Boolean(getMessageWebPagePhoto(message));\n const { width, height } = photo\n ? calculateInlineImageDimensions(photo, isOwn, isForwarded, isWebPagePhoto, noAvatars)\n : calculateVideoDimensions(video!, isOwn, isForwarded, noAvatars);\n\n const hasText = Boolean(getMessageText(message));\n const minMediaWidth = getMinMediaWidth(hasText);\n\n let stretchFactor = 1;\n if (width < minMediaWidth && minMediaWidth - width < SMALL_IMAGE_THRESHOLD) {\n stretchFactor = minMediaWidth / width;\n }\n if (height * stretchFactor < MIN_MEDIA_HEIGHT && MIN_MEDIA_HEIGHT - height * stretchFactor < SMALL_IMAGE_THRESHOLD) {\n stretchFactor = MIN_MEDIA_HEIGHT / height;\n }\n\n const finalWidth = Math.round(width * stretchFactor);\n const finalHeight = Math.round(height * stretchFactor);\n\n return {\n width: finalWidth,\n height: finalHeight,\n isSmall: finalWidth < minMediaWidth || finalHeight < MIN_MEDIA_HEIGHT,\n };\n}\n","/* eslint-disable no-bitwise */\n// Based on\n// https://github.com/telegramdesktop/tdesktop/blob/dev/Telegram/SourceFiles/ui/grouped_layout.cpp\n// https://github.com/overtake/TelegramSwift/blob/master/Telegram-Mac/GroupedLayout.swift#L83\n\nimport { IAlbum } from '../../../../types';\nimport { ApiMessage, ApiDimensions } from '../../../../api/types';\n\nimport { getAvailableWidth, REM } from '../../../common/helpers/mediaDimensions';\nimport { calculateMediaDimensions } from './mediaDimensions';\n\nexport const AlbumRectPart = {\n None: 0,\n Top: 1,\n Right: 2,\n Bottom: 4,\n Left: 8,\n};\n\ntype IAttempt = {\n lineCounts: number[];\n heights: number[];\n};\nexport type IMediaDimensions = {\n width: number;\n height: number;\n x: number;\n y: number;\n};\ntype IMediaLayout = {\n dimensions: IMediaDimensions;\n sides: number;\n};\ntype ILayoutParams = {\n ratios: number[];\n proportions: string;\n averageRatio: number;\n maxWidth: number;\n minWidth: number;\n maxHeight: number;\n spacing: number;\n};\nexport type IAlbumLayout = {\n layout: IMediaLayout[];\n containerStyle: ApiDimensions;\n};\n\nfunction getRatios(messages: ApiMessage[]) {\n return messages.map(\n (message) => {\n const dimensions = calculateMediaDimensions(message) as ApiDimensions;\n\n return dimensions.width / dimensions.height;\n },\n );\n}\n\nfunction getProportions(ratios: number[]) {\n return ratios.map((ratio) => (ratio > 1.2 ? 'w' : (ratio < 0.8 ? 'n' : 'q'))).join('');\n}\n\nfunction getAverageRatio(ratios: number[]) {\n return ratios.reduce((result, ratio) => ratio + result, 1) / ratios.length;\n}\n\nfunction accumulate(list: number[], initValue: number) {\n return list.reduce((accumulator, item) => accumulator + item, initValue);\n}\n\nfunction clamp(num: number, low: number, high: number) {\n return num < low ? low : (num > high ? high : num);\n}\n\nfunction cropRatios(ratios: number[], averageRatio: number) {\n return ratios.map((ratio) => (averageRatio > 1.1 ? clamp(ratio, 1, 2.75) : clamp(ratio, 0.6667, 1)));\n}\n\nfunction calculateContainerSize(layout: IMediaLayout[]) {\n const styles: ApiDimensions = { width: 0, height: 0 };\n layout.forEach(({\n dimensions,\n sides,\n }) => {\n if (sides & AlbumRectPart.Right) {\n styles.width = dimensions.width + dimensions.x;\n }\n if (sides & AlbumRectPart.Bottom) {\n styles.height = dimensions.height + dimensions.y;\n }\n });\n\n return styles;\n}\n\nexport function calculateAlbumLayout(\n isOwn: boolean,\n isForwarded: boolean,\n noAvatars: boolean,\n album: IAlbum,\n): IAlbumLayout {\n const spacing = 2;\n const ratios = getRatios(album.messages);\n const proportions = getProportions(ratios);\n const averageRatio = getAverageRatio(ratios);\n const albumCount = ratios.length;\n const forceCalc = ratios.some((ratio) => ratio > 2);\n const maxWidth = getAvailableWidth(isOwn, isForwarded, false, noAvatars) - (isForwarded ? 2.5 : 0) * REM;\n const maxHeight = maxWidth;\n\n let layout;\n\n const params = {\n ratios,\n proportions,\n averageRatio,\n maxWidth,\n minWidth: 100,\n maxHeight,\n spacing,\n };\n\n if (albumCount >= 5 || forceCalc) {\n layout = layoutWithComplexLayouter(params);\n } else if (albumCount === 2) {\n layout = layoutTwo(params);\n } else if (albumCount === 3) {\n layout = layoutThree(params);\n } else {\n layout = layoutFour(params);\n }\n\n return {\n layout,\n containerStyle: calculateContainerSize(layout),\n };\n}\n\nfunction layoutWithComplexLayouter({\n ratios: originalRatios,\n averageRatio,\n maxWidth,\n minWidth,\n spacing,\n maxHeight = (4 * maxWidth) / 3,\n}: ILayoutParams) {\n const ratios = cropRatios(originalRatios, averageRatio);\n const count = originalRatios.length;\n const result = new Array(count);\n const attempts: IAttempt[] = [];\n\n const multiHeight = (offset: number, attemptCount: number) => {\n const attemptRatios = ratios.slice(offset, offset + attemptCount);\n const sum = accumulate(attemptRatios, 0);\n\n return (maxWidth - (attemptCount - 1) * spacing) / sum;\n };\n\n const pushAttempt = (lineCounts: number[]) => {\n const heights: number[] = [];\n let offset = 0;\n lineCounts.forEach((currentCount) => {\n heights.push(multiHeight(offset, currentCount));\n offset += currentCount;\n });\n\n attempts.push({\n lineCounts,\n heights,\n });\n };\n\n for (let first = 1; first !== count; ++first) {\n const second = count - first;\n if (first <= 3 && second <= 3) {\n pushAttempt([first, second]);\n }\n }\n\n for (let first = 1; first !== count - 1; ++first) {\n for (let second = 1; second !== count - first; ++second) {\n const third = count - first - second;\n if (first <= 3 && second <= (averageRatio < 0.85 ? 4 : 3) && third <= 3) {\n pushAttempt([first, second, third]);\n }\n }\n }\n\n for (let first = 1; first !== count - 1; ++first) {\n for (let second = 1; second !== count - first; ++second) {\n for (let third = 1; third !== count - first - second; ++third) {\n const fourth = count - first - second - third;\n if (first <= 3 && second <= 3 && third <= 3 && fourth <= 4) {\n pushAttempt([first, second, third, fourth]);\n }\n }\n }\n }\n\n let optimalAttempt: IAttempt | undefined;\n let optimalDiff = 0;\n for (let i = 0; i < attempts.length; i++) {\n const {\n heights,\n lineCounts,\n } = attempts[i];\n const lineCount = lineCounts.length;\n const totalHeight = accumulate(heights, 0) + spacing * (lineCount - 1);\n const minLineHeight = Math.min(...heights);\n const bad1 = minLineHeight < minWidth ? 1.5 : 1;\n const bad2 = (() => {\n for (let line = 1; line !== lineCount; ++line) {\n if (lineCounts[line - 1] > lineCounts[line]) {\n return 1.5;\n }\n }\n\n return 1;\n })();\n const diff = Math.abs(totalHeight - maxHeight) * bad1 * bad2;\n\n if (!optimalAttempt || diff < optimalDiff) {\n optimalAttempt = attempts[i];\n optimalDiff = diff;\n }\n }\n\n const optimalCounts = optimalAttempt!.lineCounts;\n const optimalHeights = optimalAttempt!.heights;\n const rowCount = optimalCounts.length;\n let index = 0;\n let y = 0;\n for (let row = 0; row !== rowCount; ++row) {\n const colCount = optimalCounts[row];\n const lineHeight = optimalHeights[row];\n const height = Math.round(lineHeight);\n let x = 0;\n\n for (let col = 0; col !== colCount; ++col) {\n const sides = AlbumRectPart.None\n | (row === 0 ? AlbumRectPart.Top : AlbumRectPart.None)\n | (row === rowCount - 1 ? AlbumRectPart.Bottom : AlbumRectPart.None)\n | (col === 0 ? AlbumRectPart.Left : AlbumRectPart.None)\n | (col === colCount - 1 ? AlbumRectPart.Right : AlbumRectPart.None);\n const ratio = ratios[index];\n const width = col === colCount - 1 ? maxWidth - x : Math.round(ratio * lineHeight);\n result[index] = {\n dimensions: {\n x,\n y,\n width,\n height,\n },\n sides,\n };\n x += width + spacing;\n ++index;\n }\n y += height + spacing;\n }\n\n return result;\n}\n\nfunction layoutTwo(params: ILayoutParams) {\n const {\n ratios,\n proportions,\n averageRatio,\n } = params;\n return proportions === 'ww' && averageRatio > 1.4 && ratios[1] - ratios[0] < 0.2\n ? layoutTwoTopBottom(params)\n : proportions === 'ww' || proportions === 'qq'\n ? layoutTwoLeftRightEqual(params)\n : layoutTwoLeftRight(params);\n}\n\nfunction layoutTwoTopBottom(params: ILayoutParams) {\n const {\n ratios,\n maxWidth,\n spacing,\n maxHeight,\n } = params;\n const height = Math.round(Math.min(maxWidth / ratios[0], Math.min(maxWidth / ratios[1], (maxHeight - spacing) / 2)));\n\n return [{\n dimensions: {\n x: 0,\n y: 0,\n width: maxWidth,\n height,\n },\n sides: AlbumRectPart.Left | AlbumRectPart.Top | AlbumRectPart.Right,\n }, {\n dimensions: {\n x: 0,\n y: height + spacing,\n width: maxWidth,\n height,\n },\n sides: AlbumRectPart.Left | AlbumRectPart.Bottom | AlbumRectPart.Right,\n }];\n}\n\nfunction layoutTwoLeftRightEqual(params: ILayoutParams) {\n const {\n ratios,\n maxWidth,\n spacing,\n maxHeight,\n } = params;\n const width = (maxWidth - spacing) / 2;\n const height = Math.round(Math.min(width / ratios[0], Math.min(width / ratios[1], maxHeight)));\n return [{\n dimensions: {\n x: 0,\n y: 0,\n width,\n height,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Left | AlbumRectPart.Bottom,\n }, {\n dimensions: {\n x: width + spacing,\n y: 0,\n width,\n height,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Right | AlbumRectPart.Bottom,\n }];\n}\n\nfunction layoutTwoLeftRight(params: ILayoutParams) {\n const {\n ratios,\n minWidth,\n maxWidth,\n spacing,\n maxHeight,\n } = params;\n const minimalWidth = Math.round(1.5 * minWidth);\n const secondWidth = Math.min(\n Math.round(\n Math.max(\n 0.4 * (maxWidth - spacing),\n (maxWidth - spacing) / ratios[0] / (1 / ratios[0] + 1 / ratios[1]),\n ),\n ),\n maxWidth - spacing - minimalWidth,\n );\n const firstWidth = maxWidth - secondWidth - spacing;\n const height = Math.min(maxHeight, Math.round(Math.min(firstWidth / ratios[0], secondWidth / ratios[1])));\n\n return [{\n dimensions: {\n x: 0,\n y: 0,\n width: firstWidth,\n height,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Left | AlbumRectPart.Bottom,\n }, {\n dimensions: {\n x: firstWidth + spacing,\n y: 0,\n width: secondWidth,\n height,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Right | AlbumRectPart.Bottom,\n }];\n}\n\nfunction layoutThree(params: ILayoutParams) {\n const { proportions } = params;\n\n return proportions[0] === 'n'\n ? layoutThreeLeftAndOther(params)\n : layoutThreeTopAndOther(params);\n}\n\nfunction layoutThreeLeftAndOther(params: ILayoutParams) {\n const {\n maxHeight,\n spacing,\n ratios,\n maxWidth,\n minWidth,\n } = params;\n const firstHeight = maxHeight;\n const thirdHeight = Math.round(\n Math.min(\n (maxHeight - spacing) / 2,\n (ratios[1] * (maxWidth - spacing)) / (ratios[2] + ratios[1]),\n ),\n );\n const secondHeight = firstHeight - thirdHeight - spacing;\n const rightWidth = Math.max(\n minWidth,\n Math.round(\n Math.min(\n (maxWidth - spacing) / 2,\n Math.min(\n thirdHeight * ratios[2],\n secondHeight * ratios[1],\n ),\n ),\n ),\n );\n const leftWidth = Math.min(Math.round(firstHeight * ratios[0]), maxWidth - spacing - rightWidth);\n\n return [{\n dimensions: {\n x: 0,\n y: 0,\n width: leftWidth,\n height: firstHeight,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Left | AlbumRectPart.Bottom,\n }, {\n dimensions: {\n x: leftWidth + spacing,\n y: 0,\n width: rightWidth,\n height: secondHeight,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Right,\n }, {\n dimensions: {\n x: leftWidth + spacing,\n y: secondHeight + spacing,\n width: rightWidth,\n height: thirdHeight,\n },\n sides: AlbumRectPart.Bottom | AlbumRectPart.Right,\n }];\n}\n\nfunction layoutThreeTopAndOther(params: ILayoutParams) {\n const {\n maxWidth,\n ratios,\n maxHeight,\n spacing,\n } = params;\n const firstWidth = maxWidth;\n const firstHeight = Math.round(Math.min(firstWidth / ratios[0], 0.66 * (maxHeight - spacing)));\n const secondWidth = (maxWidth - spacing) / 2;\n const secondHeight = Math.min(\n maxHeight - firstHeight - spacing,\n Math.round(Math.min(\n secondWidth / ratios[1],\n secondWidth / ratios[2],\n )),\n );\n const thirdWidth = firstWidth - secondWidth - spacing;\n\n return [{\n dimensions: {\n x: 0,\n y: 0,\n width: firstWidth,\n height: firstHeight,\n },\n sides: AlbumRectPart.Left | AlbumRectPart.Top | AlbumRectPart.Right,\n }, {\n dimensions: {\n x: 0,\n y: firstHeight + spacing,\n width: secondWidth,\n height: secondHeight,\n },\n sides: AlbumRectPart.Bottom | AlbumRectPart.Left,\n }, {\n dimensions: {\n x: secondWidth + spacing,\n y: firstHeight + spacing,\n width: thirdWidth,\n height: secondHeight,\n },\n sides: AlbumRectPart.Bottom | AlbumRectPart.Right,\n }];\n}\n\nfunction layoutFour(params: ILayoutParams) {\n const { proportions } = params;\n\n return proportions[0] === 'w'\n ? layoutFourTopAndOther(params)\n : layoutFourLeftAndOther(params);\n}\n\nfunction layoutFourTopAndOther({\n maxWidth,\n ratios,\n spacing,\n maxHeight,\n minWidth,\n}: ILayoutParams) {\n const w = maxWidth;\n const h0 = Math.round(Math.min(w / ratios[0], 0.66 * (maxHeight - spacing)));\n const h = Math.round((maxWidth - 2 * spacing) / (ratios[1] + ratios[2] + ratios[3]));\n const w0 = Math.max(minWidth, Math.round(Math.min(0.4 * (maxWidth - 2 * spacing), h * ratios[1])));\n const w2 = Math.round(Math.max(Math.max(minWidth, 0.33 * (maxWidth - 2 * spacing)), h * ratios[3]));\n const w1 = w - w0 - w2 - 2 * spacing;\n const h1 = Math.min(maxHeight - h0 - spacing, h);\n\n return [{\n dimensions: {\n x: 0,\n y: 0,\n width: w,\n height: h0,\n },\n sides: AlbumRectPart.Left | AlbumRectPart.Top | AlbumRectPart.Right,\n }, {\n dimensions: {\n x: 0,\n y: h0 + spacing,\n width: w0,\n height: h1,\n },\n sides: AlbumRectPart.Bottom | AlbumRectPart.Left,\n }, {\n dimensions: {\n x: w0 + spacing,\n y: h0 + spacing,\n width: w1,\n height: h1,\n },\n sides: AlbumRectPart.Bottom,\n }, {\n dimensions: {\n x: w0 + spacing + w1 + spacing,\n y: h0 + spacing,\n width: w2,\n height: h1,\n },\n sides: AlbumRectPart.Right | AlbumRectPart.Bottom,\n }];\n}\n\nfunction layoutFourLeftAndOther({\n maxHeight,\n ratios,\n maxWidth,\n spacing,\n minWidth,\n}: ILayoutParams) {\n const h = maxHeight;\n const w0 = Math.round(Math.min(h * ratios[0], 0.6 * (maxWidth - spacing)));\n const w = Math.round((maxHeight - 2 * spacing) / (1 / ratios[1] + 1 / ratios[2] + 1 / ratios[3]));\n const h0 = Math.round(w / ratios[1]);\n const h1 = Math.round(w / ratios[2]);\n const h2 = h - h0 - h1 - 2 * spacing;\n const w1 = Math.max(minWidth, Math.min(maxWidth - w0 - spacing, w));\n\n return [{\n dimensions: {\n x: 0,\n y: 0,\n width: w0,\n height: h,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Left | AlbumRectPart.Bottom,\n }, {\n dimensions: {\n x: w0 + spacing,\n y: 0,\n width: w1,\n height: h0,\n },\n sides: AlbumRectPart.Top | AlbumRectPart.Right,\n }, {\n dimensions: {\n x: w0 + spacing,\n y: h0 + spacing,\n width: w1,\n height: h1,\n },\n sides: AlbumRectPart.Right,\n }, {\n dimensions: {\n x: w0 + spacing,\n y: h0 + h1 + 2 * spacing,\n width: w1,\n height: h2,\n },\n sides: AlbumRectPart.Bottom | AlbumRectPart.Right,\n }];\n}\n","import { IS_IOS } from '../../../../util/environment';\n\nlet element: HTMLSpanElement | undefined;\n\nexport default function calculateAuthorWidth(text: string) {\n if (!element) {\n element = document.createElement('span');\n // eslint-disable-next-line max-len\n element.style.font = IS_IOS\n // eslint-disable-next-line max-len\n ? '400 12px system-ui, -apple-system, BlinkMacSystemFont, \"Roboto\", \"Apple Color Emoji\", \"Helvetica Neue\", sans-serif'\n : '400 12px \"Roboto\", -apple-system, \"Apple Color Emoji\", BlinkMacSystemFont, \"Helvetica Neue\", sans-serif';\n element.style.whiteSpace = 'nowrap';\n element.style.position = 'absolute';\n element.style.left = '-999px';\n element.style.opacity = '.01';\n document.body.appendChild(element);\n }\n\n element.innerHTML = text;\n\n return element.offsetWidth;\n}\n","import { FocusDirection } from '../../../../types';\n\nimport { useLayoutEffect } from '../../../../lib/teact/teact';\nimport fastSmoothScroll from '../../../../util/fastSmoothScroll';\n\n// This is used when the viewport was replaced.\nconst RELOCATED_FOCUS_OFFSET = 1000;\nconst FOCUS_MARGIN = 20;\n\nexport default function useFocusMessage(\n elementRef: { current: HTMLDivElement | null },\n chatId: string,\n isFocused?: boolean,\n focusDirection?: FocusDirection,\n noFocusHighlight?: boolean,\n isResizingContainer?: boolean,\n) {\n useLayoutEffect(() => {\n if (isFocused && elementRef.current) {\n const messagesContainer = elementRef.current.closest('.MessageList')!;\n\n fastSmoothScroll(\n messagesContainer,\n elementRef.current,\n // `noFocusHighlight` always called from “scroll-to-bottom” buttons\n noFocusHighlight ? 'end' : 'centerOrTop',\n FOCUS_MARGIN,\n focusDirection !== undefined ? RELOCATED_FOCUS_OFFSET : undefined,\n focusDirection,\n undefined,\n isResizingContainer,\n );\n }\n }, [elementRef, chatId, isFocused, focusDirection, noFocusHighlight, isResizingContainer]);\n}\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './ContextMenuContainer';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst ContextMenuContainerAsync: FC = (props) => {\n const { isOpen } = props;\n const ContextMenuContainer = useModuleLoader(Bundles.Extra, 'ContextMenuContainer', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return ContextMenuContainer ? : undefined;\n};\n\nexport default memo(ContextMenuContainerAsync);\n","import React, {\n FC, memo, useEffect, useMemo, useRef,\n} from '../../lib/teact/teact';\nimport { withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiUser, ApiMessage, ApiChat } from '../../api/types';\nimport { FocusDirection } from '../../types';\n\nimport {\n selectUser,\n selectChatMessage,\n selectIsMessageFocused,\n selectChat,\n} from '../../modules/selectors';\nimport { isChatChannel } from '../../modules/helpers';\nimport buildClassName from '../../util/buildClassName';\nimport renderText from '../common/helpers/renderText';\nimport { renderActionMessageText } from '../common/helpers/renderActionMessageText';\nimport useEnsureMessage from '../../hooks/useEnsureMessage';\nimport useContextMenuHandlers from '../../hooks/useContextMenuHandlers';\nimport { ObserveFn, useOnIntersect } from '../../hooks/useIntersectionObserver';\nimport useFocusMessage from './message/hooks/useFocusMessage';\nimport useLang from '../../hooks/useLang';\n\nimport ContextMenuContainer from './message/ContextMenuContainer.async';\nimport useFlag from '../../hooks/useFlag';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport { preventMessageInputBlur } from './helpers/preventMessageInputBlur';\n\ntype OwnProps = {\n message: ApiMessage;\n observeIntersection?: ObserveFn;\n isEmbedded?: boolean;\n appearanceOrder?: number;\n isLastInList?: boolean;\n};\n\ntype StateProps = {\n usersById: Record;\n sender?: ApiUser | ApiChat;\n targetUserIds?: string[];\n targetMessage?: ApiMessage;\n targetChatId?: string;\n isFocused: boolean;\n focusDirection?: FocusDirection;\n noFocusHighlight?: boolean;\n};\n\nconst APPEARANCE_DELAY = 10;\n\nconst ActionMessage: FC = ({\n message,\n observeIntersection,\n isEmbedded,\n appearanceOrder = 0,\n isLastInList,\n usersById,\n sender,\n targetUserIds,\n targetMessage,\n targetChatId,\n isFocused,\n focusDirection,\n noFocusHighlight,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n\n useOnIntersect(ref, observeIntersection);\n useEnsureMessage(message.chatId, message.replyToMessageId, targetMessage);\n useFocusMessage(ref, message.chatId, isFocused, focusDirection, noFocusHighlight);\n\n const lang = useLang();\n\n const noAppearanceAnimation = appearanceOrder <= 0;\n const [isShown, markShown] = useFlag(noAppearanceAnimation);\n useEffect(() => {\n if (noAppearanceAnimation) {\n return;\n }\n\n setTimeout(markShown, appearanceOrder * APPEARANCE_DELAY);\n }, [appearanceOrder, markShown, noAppearanceAnimation]);\n const { transitionClassNames } = useShowTransition(isShown, undefined, noAppearanceAnimation, false);\n\n const targetUsers = useMemo(() => {\n return targetUserIds\n ? targetUserIds.map((userId) => usersById?.[userId]).filter(Boolean as any)\n : undefined;\n }, [targetUserIds, usersById]);\n\n const content = renderActionMessageText(\n lang,\n message,\n sender,\n targetUsers,\n targetMessage,\n targetChatId,\n isEmbedded ? { isEmbedded: true, asPlain: true } : undefined,\n );\n const {\n isContextMenuOpen, contextMenuPosition,\n handleBeforeContextMenu, handleContextMenu,\n handleContextMenuClose, handleContextMenuHide,\n } = useContextMenuHandlers(ref);\n const isContextMenuShown = contextMenuPosition !== undefined;\n\n const handleMouseDown = (e: React.MouseEvent) => {\n preventMessageInputBlur(e);\n handleBeforeContextMenu(e);\n };\n\n if (isEmbedded) {\n return {renderText(content as string)};\n }\n\n const className = buildClassName(\n 'ActionMessage message-list-item',\n isFocused && !noFocusHighlight && 'focused',\n isContextMenuShown && 'has-menu-open',\n isLastInList && 'last-in-list',\n transitionClassNames,\n );\n\n return (\n \n {content}\n {contextMenuPosition && (\n \n )}\n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { message }): StateProps => {\n const { byId: usersById } = global.users;\n const userId = message.senderId;\n const { targetUserIds, targetChatId } = message.content.action || {};\n const targetMessageId = message.replyToMessageId;\n const targetMessage = targetMessageId\n ? selectChatMessage(global, message.chatId, targetMessageId)\n : undefined;\n\n const isFocused = selectIsMessageFocused(global, message);\n const { direction: focusDirection, noHighlight: noFocusHighlight } = (isFocused && global.focusedMessage) || {};\n\n const chat = selectChat(global, message.chatId);\n const sender = chat && (isChatChannel(chat) || userId === message.chatId)\n ? chat\n : userId ? selectUser(global, userId) : undefined;\n\n return {\n usersById,\n sender,\n targetChatId,\n targetUserIds,\n targetMessage,\n isFocused,\n ...(isFocused && { focusDirection, noFocusHighlight }),\n };\n },\n)(ActionMessage));\n","import React, { FC, useRef } from '../../lib/teact/teact';\n\nimport { ApiUser, ApiMessage, ApiChat } from '../../api/types';\n\nimport {\n getMessageMediaHash,\n isActionMessage,\n getMessageSummaryText,\n getSenderTitle,\n getMessageRoundVideo,\n} from '../../modules/helpers';\nimport renderText from './helpers/renderText';\nimport { getPictogramDimensions } from './helpers/mediaDimensions';\nimport buildClassName from '../../util/buildClassName';\nimport { ObserveFn, useIsIntersecting } from '../../hooks/useIntersectionObserver';\nimport useMedia from '../../hooks/useMedia';\nimport useWebpThumbnail from '../../hooks/useWebpThumbnail';\nimport useLang from '../../hooks/useLang';\n\nimport ActionMessage from '../middle/ActionMessage';\n\nimport './EmbeddedMessage.scss';\n\ntype OwnProps = {\n observeIntersection?: ObserveFn;\n className?: string;\n message?: ApiMessage;\n sender?: ApiUser | ApiChat;\n title?: string;\n customText?: string;\n isProtected?: boolean;\n onClick: NoneToVoidFunction;\n};\n\nconst NBSP = '\\u00A0';\n\nconst EmbeddedMessage: FC = ({\n className,\n message,\n sender,\n title,\n customText,\n isProtected,\n observeIntersection,\n onClick,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n\n const mediaBlobUrl = useMedia(message && getMessageMediaHash(message, 'pictogram'), !isIntersecting);\n const pictogramId = message && `sticker-reply-thumb${message.id}`;\n const mediaThumbnail = useWebpThumbnail(message);\n const isRoundVideo = Boolean(message && getMessageRoundVideo(message));\n\n const lang = useLang();\n\n const senderTitle = sender && getSenderTitle(lang, sender);\n\n return (\n \n {mediaThumbnail && renderPictogram(pictogramId, mediaThumbnail, mediaBlobUrl, isRoundVideo, isProtected)}\n
\n

\n {!message ? (\n customText || NBSP\n ) : isActionMessage(message) ? (\n \n ) : (\n renderText(getMessageSummaryText(lang, message, Boolean(mediaThumbnail)))\n )}\n

\n
{renderText(senderTitle || title || NBSP)}
\n
\n \n );\n};\n\nfunction renderPictogram(\n id: string | undefined,\n thumbDataUri: string,\n blobUrl?: string,\n isRoundVideo?: boolean,\n isProtected?: boolean,\n) {\n const { width, height } = getPictogramDimensions();\n\n return (\n <>\n \n {isProtected && }\n \n );\n}\n\nexport default EmbeddedMessage;\n","import React, {\n FC, memo, useMemo,\n} from '../../../lib/teact/teact';\n\nimport { ApiMessage, ApiMessageOutgoingStatus } from '../../../api/types';\n\nimport { formatDateTimeToString, formatTime } from '../../../util/dateFormat';\nimport { formatIntegerCompact } from '../../../util/textFormat';\n\nimport MessageOutgoingStatus from '../../common/MessageOutgoingStatus';\nimport renderText from '../../common/helpers/renderText';\nimport useLang from '../../../hooks/useLang';\nimport useFlag from '../../../hooks/useFlag';\n\nimport './MessageMeta.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n outgoingStatus?: ApiMessageOutgoingStatus;\n signature?: string;\n onClick: (e: React.MouseEvent) => void;\n};\n\nconst MessageMeta: FC = ({\n message, outgoingStatus, signature, onClick,\n}) => {\n const lang = useLang();\n const [isActivated, markActivated] = useFlag();\n\n const title = useMemo(() => {\n if (!isActivated) return undefined;\n const createDateTime = formatDateTimeToString(message.date * 1000, lang.code);\n const editDateTime = message.isEdited && formatDateTimeToString(message.editDate! * 1000, lang.code);\n const forwardedDateTime = message.forwardInfo && formatDateTimeToString(message.forwardInfo.date * 1000, lang.code);\n\n let text = createDateTime;\n if (editDateTime) {\n text += '\\n';\n text += lang('lng_edited_date').replace('{date}', editDateTime);\n }\n if (forwardedDateTime) {\n text += '\\n';\n text += lang('lng_forwarded_date').replace('{date}', forwardedDateTime);\n }\n\n return text;\n }, [isActivated, lang, message]);\n\n return (\n \n {Boolean(message.views) && (\n <>\n \n {formatIntegerCompact(message.views!)}\n \n \n \n )}\n {signature && (\n {renderText(signature)}\n )}\n \n {message.isEdited && `${lang('EditedMessage')} `}\n {formatTime(message.date * 1000, lang)}\n \n {outgoingStatus && (\n \n )}\n \n );\n};\n\nexport default memo(MessageMeta);\n","import React, { FC, useRef } from '../../../lib/teact/teact';\n\nimport { ApiMessage } from '../../../api/types';\n\nimport { MEMOJI_STICKER_ID } from '../../../config';\nimport { getStickerDimensions } from '../../common/helpers/mediaDimensions';\nimport { getMessageMediaFormat, getMessageMediaHash } from '../../../modules/helpers';\nimport buildClassName from '../../../util/buildClassName';\nimport { ObserveFn, useIsIntersecting } from '../../../hooks/useIntersectionObserver';\nimport useMedia from '../../../hooks/useMedia';\nimport useMediaTransition from '../../../hooks/useMediaTransition';\nimport useFlag from '../../../hooks/useFlag';\nimport useWebpThumbnail from '../../../hooks/useWebpThumbnail';\n\nimport AnimatedSticker from '../../common/AnimatedSticker';\nimport StickerSetModal from '../../common/StickerSetModal.async';\n\nimport './Sticker.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n observeIntersection: ObserveFn;\n observeIntersectionForPlaying: ObserveFn;\n shouldLoop?: boolean;\n lastSyncTime?: number;\n};\n\nconst Sticker: FC = ({\n message, observeIntersection, observeIntersectionForPlaying, shouldLoop, lastSyncTime,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n\n const [isModalOpen, openModal, closeModal] = useFlag();\n\n const sticker = message.content.sticker!;\n const { isAnimated, stickerSetId } = sticker;\n const isMemojiSticker = stickerSetId === MEMOJI_STICKER_ID;\n\n const shouldLoad = useIsIntersecting(ref, observeIntersection);\n const shouldPlay = useIsIntersecting(ref, observeIntersectionForPlaying);\n\n const mediaHash = sticker.isPreloadedGlobally ? `sticker${sticker.id}` : getMessageMediaHash(message, 'inline')!;\n const thumbDataUri = useWebpThumbnail(message);\n const mediaData = useMedia(\n mediaHash,\n !shouldLoad,\n getMessageMediaFormat(message, 'inline', true),\n lastSyncTime,\n );\n\n const isMediaLoaded = Boolean(mediaData);\n const [isAnimationLoaded, markAnimationLoaded] = useFlag(isMediaLoaded);\n const isMediaReady = isAnimated ? isAnimationLoaded : isMediaLoaded;\n const transitionClassNames = useMediaTransition(isMediaReady);\n\n const { width, height } = getStickerDimensions(sticker);\n const thumbClassName = buildClassName('thumbnail', !thumbDataUri && 'empty');\n\n const stickerClassName = buildClassName(\n 'Sticker media-inner',\n isMemojiSticker && 'inactive',\n );\n\n return (\n
\n {!isMediaReady && (\n \n )}\n {!isAnimated && (\n \n )}\n {isAnimated && isMediaLoaded && (\n \n )}\n \n
\n );\n};\n\nexport default Sticker;\n","import { ApiMessage } from '../../../../api/types';\n\nimport { IS_CANVAS_FILTER_SUPPORTED, IS_SINGLE_COLUMN_LAYOUT } from '../../../../util/environment';\nimport { getMessageMediaThumbDataUri } from '../../../../modules/helpers';\nimport useCanvasBlur from '../../../../hooks/useCanvasBlur';\n\nexport default function useBlurredMediaThumbRef(message: ApiMessage, fullMediaData?: string) {\n return useCanvasBlur(\n getMessageMediaThumbDataUri(message),\n Boolean(fullMediaData),\n IS_SINGLE_COLUMN_LAYOUT && !IS_CANVAS_FILTER_SUPPORTED,\n );\n}\n","import { ISettings } from '../../../../types';\n\nconst SELECTED_APPENDIX_COLORS = {\n dark: {\n outgoing: 'rgb(135,116,225)',\n incoming: 'rgb(33,33,33)',\n },\n light: {\n outgoing: 'rgb(238,255,222)',\n incoming: 'rgb(255,255,255)',\n },\n};\n\nexport default function getCustomAppendixBg(\n src: string, isOwn: boolean, inSelectMode?: boolean, isSelected?: boolean, theme?: ISettings['theme'],\n) {\n if (isSelected) {\n return Promise.resolve(SELECTED_APPENDIX_COLORS[theme || 'light'][isOwn ? 'outgoing' : 'incoming']);\n }\n return getAppendixColorFromImage(src, isOwn);\n}\n\nasync function getAppendixColorFromImage(src: string, isOwn: boolean) {\n const img = new Image();\n img.src = src;\n\n if (!img.width) {\n await new Promise((resolve) => {\n img.onload = resolve;\n });\n }\n\n const canvas = document.createElement('canvas');\n const ctx = canvas.getContext('2d')!;\n\n canvas.width = img.width;\n canvas.height = img.height;\n\n ctx.drawImage(img, 0, 0, img.width, img.height);\n\n const x = isOwn ? img.width - 1 : 0;\n const y = img.height - 1;\n\n const pixel = Array.from(ctx.getImageData(x, y, 1, 1).data);\n return `rgba(${pixel.join(',')})`;\n}\n","import React, {\n FC, useCallback, useLayoutEffect, useRef, useState,\n} from '../../../lib/teact/teact';\n\nimport { ApiMessage } from '../../../api/types';\nimport { ISettings } from '../../../types';\nimport { IMediaDimensions } from './helpers/calculateAlbumLayout';\n\nimport {\n getMessagePhoto,\n getMessageWebPagePhoto,\n getMessageMediaHash,\n getMediaTransferState,\n isOwnMessage,\n} from '../../../modules/helpers';\nimport { ObserveFn, useIsIntersecting } from '../../../hooks/useIntersectionObserver';\nimport useMediaWithLoadProgress from '../../../hooks/useMediaWithLoadProgress';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useBlurredMediaThumbRef from './hooks/useBlurredMediaThumbRef';\nimport usePrevious from '../../../hooks/usePrevious';\nimport useMediaTransition from '../../../hooks/useMediaTransition';\nimport buildClassName from '../../../util/buildClassName';\nimport getCustomAppendixBg from './helpers/getCustomAppendixBg';\nimport { calculateMediaDimensions } from './helpers/mediaDimensions';\n\nimport ProgressSpinner from '../../ui/ProgressSpinner';\n\nexport type OwnProps = {\n id?: string;\n message: ApiMessage;\n observeIntersection?: ObserveFn;\n noAvatars?: boolean;\n canAutoLoad?: boolean;\n isInSelectMode?: boolean;\n isSelected?: boolean;\n uploadProgress?: number;\n size?: 'inline' | 'pictogram';\n shouldAffectAppendix?: boolean;\n dimensions?: IMediaDimensions & { isSmall?: boolean };\n nonInteractive?: boolean;\n isDownloading: boolean;\n isProtected?: boolean;\n theme: ISettings['theme'];\n onClick?: (id: number) => void;\n onCancelUpload?: (message: ApiMessage) => void;\n};\n\nconst CUSTOM_APPENDIX_ATTRIBUTE = 'data-has-custom-appendix';\n\nconst Photo: FC = ({\n id,\n message,\n observeIntersection,\n noAvatars,\n canAutoLoad,\n isInSelectMode,\n isSelected,\n uploadProgress,\n size = 'inline',\n dimensions,\n nonInteractive,\n shouldAffectAppendix,\n isDownloading,\n isProtected,\n theme,\n onClick,\n onCancelUpload,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n\n const photo = (getMessagePhoto(message) || getMessageWebPagePhoto(message))!;\n const localBlobUrl = photo.blobUrl;\n\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n\n const [isLoadAllowed, setIsLoadAllowed] = useState(canAutoLoad);\n const shouldLoad = isLoadAllowed && isIntersecting;\n const {\n mediaData, loadProgress,\n } = useMediaWithLoadProgress(getMessageMediaHash(message, size), !shouldLoad);\n const fullMediaData = localBlobUrl || mediaData;\n const thumbRef = useBlurredMediaThumbRef(message, fullMediaData);\n\n const {\n loadProgress: downloadProgress,\n } = useMediaWithLoadProgress(getMessageMediaHash(message, 'download'), !isDownloading);\n\n const {\n isUploading, isTransferring, transferProgress,\n } = getMediaTransferState(\n message,\n uploadProgress || (isDownloading ? downloadProgress : loadProgress),\n shouldLoad && !fullMediaData,\n );\n const wasLoadDisabled = usePrevious(isLoadAllowed) === false;\n\n const transitionClassNames = useMediaTransition(fullMediaData);\n const {\n shouldRender: shouldRenderSpinner,\n transitionClassNames: spinnerClassNames,\n } = useShowTransition(isTransferring, undefined, wasLoadDisabled, 'slow');\n const {\n shouldRender: shouldRenderDownloadButton,\n transitionClassNames: downloadButtonClassNames,\n } = useShowTransition(!fullMediaData && !isLoadAllowed);\n\n const handleClick = useCallback(() => {\n if (isUploading) {\n if (onCancelUpload) {\n onCancelUpload(message);\n }\n } else if (!fullMediaData) {\n setIsLoadAllowed((isAllowed) => !isAllowed);\n } else if (onClick) {\n onClick(message.id);\n }\n }, [fullMediaData, isUploading, message, onCancelUpload, onClick]);\n\n const isOwn = isOwnMessage(message);\n useLayoutEffect(() => {\n if (!shouldAffectAppendix) {\n return;\n }\n\n const contentEl = ref.current!.closest('.message-content')!;\n\n if (fullMediaData) {\n getCustomAppendixBg(fullMediaData, isOwn, isInSelectMode, isSelected, theme).then((appendixBg) => {\n contentEl.style.setProperty('--appendix-bg', appendixBg);\n contentEl.setAttribute(CUSTOM_APPENDIX_ATTRIBUTE, '');\n });\n } else {\n contentEl.classList.add('has-appendix-thumb');\n }\n }, [fullMediaData, isOwn, shouldAffectAppendix, isInSelectMode, isSelected, theme]);\n\n const { width, height, isSmall } = dimensions || calculateMediaDimensions(message, noAvatars);\n\n const className = buildClassName(\n 'media-inner',\n !isUploading && !nonInteractive && 'interactive',\n isSmall && 'small-image',\n width === height && 'square-image',\n );\n\n const style = dimensions\n ? `width: ${width}px; height: ${height}px; left: ${dimensions.x}px; top: ${dimensions.y}px;`\n : '';\n\n return (\n \n \n \n {isProtected && }\n {shouldRenderSpinner && !shouldRenderDownloadButton && (\n
\n \n
\n )}\n {shouldRenderDownloadButton && }\n {isTransferring && (\n {Math.round(transferProgress * 100)}%\n )}\n \n );\n};\n\nexport default Photo;\n","import { useCallback, useRef } from '../../../../lib/teact/teact';\n\nimport { fastRaf } from '../../../../util/schedulers';\nimport safePlay from '../../../../util/safePlay';\nimport useBackgroundMode from '../../../../hooks/useBackgroundMode';\nimport useHeavyAnimationCheck from '../../../../hooks/useHeavyAnimationCheck';\n\nexport default function useVideoAutoPause(playerRef: { current: HTMLVideoElement | null }, canPlay: boolean) {\n const wasPlaying = useRef(playerRef.current?.paused);\n const canPlayRef = useRef();\n canPlayRef.current = canPlay;\n\n const freezePlaying = useCallback(() => {\n if (!playerRef.current) {\n return;\n }\n\n wasPlaying.current = !playerRef.current.paused;\n\n if (wasPlaying.current) {\n playerRef.current.pause();\n }\n }, [playerRef]);\n\n const unfreezePlaying = useCallback(() => {\n if (\n playerRef.current && wasPlaying.current && canPlayRef.current\n // At this point HTMLVideoElement can be unmounted from the DOM\n && document.body.contains(playerRef.current)\n ) {\n safePlay(playerRef.current);\n }\n }, [playerRef]);\n\n const unfreezePlayingOnRaf = useCallback(() => {\n fastRaf(unfreezePlaying);\n }, [unfreezePlaying]);\n\n useBackgroundMode(freezePlaying, unfreezePlayingOnRaf);\n useHeavyAnimationCheck(freezePlaying, unfreezePlaying);\n}\n","import React, {\n FC, useCallback, useRef, useState,\n} from '../../../lib/teact/teact';\nimport { getDispatch } from '../../../lib/teact/teactn';\n\nimport { ApiMediaFormat, ApiMessage } from '../../../api/types';\nimport { IMediaDimensions } from './helpers/calculateAlbumLayout';\n\nimport { formatMediaDuration } from '../../../util/dateFormat';\nimport buildClassName from '../../../util/buildClassName';\nimport { calculateVideoDimensions } from '../../common/helpers/mediaDimensions';\nimport {\n getMediaTransferState,\n getMessageMediaFormat,\n getMessageMediaHash,\n getMessageVideo,\n getMessageWebPageVideo,\n isForwardedMessage,\n isOwnMessage,\n} from '../../../modules/helpers';\nimport { ObserveFn, useIsIntersecting } from '../../../hooks/useIntersectionObserver';\nimport useMediaWithLoadProgress from '../../../hooks/useMediaWithLoadProgress';\nimport useMedia from '../../../hooks/useMedia';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport usePrevious from '../../../hooks/usePrevious';\nimport useBuffering from '../../../hooks/useBuffering';\nimport useVideoCleanup from '../../../hooks/useVideoCleanup';\nimport useMediaTransition from '../../../hooks/useMediaTransition';\nimport useVideoAutoPause from './hooks/useVideoAutoPause';\nimport useBlurredMediaThumbRef from './hooks/useBlurredMediaThumbRef';\n\nimport ProgressSpinner from '../../ui/ProgressSpinner';\n\nexport type OwnProps = {\n id?: string;\n message: ApiMessage;\n observeIntersection: ObserveFn;\n noAvatars?: boolean;\n canAutoLoad?: boolean;\n canAutoPlay?: boolean;\n uploadProgress?: number;\n dimensions?: IMediaDimensions;\n lastSyncTime?: number;\n isDownloading: boolean;\n isProtected?: boolean;\n onClick?: (id: number) => void;\n onCancelUpload?: (message: ApiMessage) => void;\n};\n\nconst Video: FC = ({\n id,\n message,\n observeIntersection,\n noAvatars,\n canAutoLoad,\n canAutoPlay,\n uploadProgress,\n lastSyncTime,\n dimensions,\n onClick,\n onCancelUpload,\n isDownloading,\n isProtected,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const videoRef = useRef(null);\n\n const video = (getMessageVideo(message) || getMessageWebPageVideo(message))!;\n const localBlobUrl = video.blobUrl;\n\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n\n const [isLoadAllowed, setIsLoadAllowed] = useState(canAutoLoad);\n const shouldLoad = Boolean(isLoadAllowed && isIntersecting && lastSyncTime);\n const [isPlayAllowed, setIsPlayAllowed] = useState(canAutoPlay);\n\n const previewBlobUrl = useMedia(\n getMessageMediaHash(message, 'pictogram'),\n !(isIntersecting && lastSyncTime),\n getMessageMediaFormat(message, 'pictogram'),\n lastSyncTime,\n );\n const previewClassNames = useMediaTransition(previewBlobUrl);\n\n const { mediaData, loadProgress } = useMediaWithLoadProgress(\n getMessageMediaHash(message, 'inline'),\n !shouldLoad,\n getMessageMediaFormat(message, 'inline'),\n lastSyncTime,\n );\n const fullMediaData = localBlobUrl || mediaData;\n const isInline = Boolean(isIntersecting && fullMediaData);\n // Thumbnail is always rendered so we can only disable blur if we have preview\n const thumbRef = useBlurredMediaThumbRef(message, previewBlobUrl);\n\n const { loadProgress: downloadProgress } = useMediaWithLoadProgress(\n getMessageMediaHash(message, 'download'),\n !isDownloading,\n ApiMediaFormat.BlobUrl,\n lastSyncTime,\n );\n\n const { isBuffered, bufferingHandlers } = useBuffering(!canAutoLoad);\n const { isUploading, isTransferring, transferProgress } = getMediaTransferState(\n message,\n uploadProgress || (isDownloading ? downloadProgress : loadProgress),\n (shouldLoad && !isBuffered) || isDownloading,\n );\n const wasLoadDisabled = usePrevious(isLoadAllowed) === false;\n const {\n shouldRender: shouldRenderSpinner,\n transitionClassNames: spinnerClassNames,\n } = useShowTransition(isTransferring, undefined, wasLoadDisabled);\n const {\n shouldRender: shouldRenderPlayButton,\n transitionClassNames: playButtonClassNames,\n } = useShowTransition(isLoadAllowed && !isPlayAllowed && !shouldRenderSpinner);\n\n const [playProgress, setPlayProgress] = useState(0);\n const handleTimeUpdate = useCallback((e: React.SyntheticEvent) => {\n setPlayProgress(Math.max(0, e.currentTarget.currentTime - 1));\n }, []);\n\n const duration = (videoRef.current?.duration) || video.duration || 0;\n\n const isOwn = isOwnMessage(message);\n const isForwarded = isForwardedMessage(message);\n const { width, height } = dimensions || calculateVideoDimensions(video, isOwn, isForwarded, noAvatars);\n\n useVideoAutoPause(videoRef, isInline);\n useVideoCleanup(videoRef, [isInline]);\n\n const handleClick = useCallback(() => {\n if (isUploading) {\n if (onCancelUpload) {\n onCancelUpload(message);\n }\n } else if (isDownloading) {\n getDispatch().cancelMessageMediaDownload({ message });\n } else if (!fullMediaData) {\n setIsLoadAllowed((isAllowed) => !isAllowed);\n } else if (fullMediaData && !isPlayAllowed) {\n setIsPlayAllowed(true);\n videoRef.current!.play();\n } else if (onClick) {\n onClick(message.id);\n }\n }, [isUploading, isDownloading, fullMediaData, isPlayAllowed, onClick, onCancelUpload, message]);\n\n const className = buildClassName('media-inner dark', !isUploading && 'interactive');\n const style = dimensions\n ? `width: ${width}px; height: ${height}px; left: ${dimensions.x}px; top: ${dimensions.y}px;`\n : '';\n\n return (\n \n \n \n {isInline && (\n \n \n \n )}\n {isProtected && }\n {shouldRenderPlayButton && }\n {shouldRenderSpinner && (\n
\n \n
\n )}\n {!isLoadAllowed && (\n \n )}\n {isTransferring ? (\n \n {(isUploading || isDownloading) ? `${Math.round(transferProgress * 100)}%` : '...'}\n \n ) : (\n
\n {video.isGif ? 'GIF' : formatMediaDuration(Math.max(duration - playProgress, 0))}\n
\n )}\n \n );\n};\n\nexport default Video;\n","import React, { FC, useCallback } from '../../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiUser, ApiContact, ApiCountryCode } from '../../../api/types';\n\nimport { selectUser } from '../../../modules/selectors';\nimport { formatPhoneNumberWithCode } from '../../../util/phoneNumber';\nimport buildClassName from '../../../util/buildClassName';\n\nimport Avatar from '../../common/Avatar';\n\nimport './Contact.scss';\n\ntype OwnProps = {\n contact: ApiContact;\n};\n\ntype StateProps = {\n user?: ApiUser;\n phoneCodeList: ApiCountryCode[];\n};\n\nconst Contact: FC = ({\n contact, user, phoneCodeList,\n}) => {\n const { openUserInfo } = getDispatch();\n\n const {\n firstName,\n lastName,\n phoneNumber,\n userId,\n } = contact;\n\n const handleClick = useCallback(() => {\n openUserInfo({ id: userId });\n }, [openUserInfo, userId]);\n\n return (\n \n \n
\n
{firstName} {lastName}
\n
{formatPhoneNumberWithCode(phoneCodeList, phoneNumber)}
\n
\n \n );\n};\n\nexport default withGlobal(\n (global, { contact }): StateProps => {\n const { countryList: { phoneCodes: phoneCodeList } } = global;\n return {\n user: selectUser(global, contact.userId),\n phoneCodeList,\n };\n },\n)(Contact);\n","import React, {\n FC, useState, useEffect, useRef,\n} from '../../../lib/teact/teact';\n\nimport { ApiPollAnswer, ApiPollResult } from '../../../api/types';\n\nimport buildClassName from '../../../util/buildClassName';\nimport renderText from '../../common/helpers/renderText';\n\nimport './PollOption.scss';\n\ntype OwnProps = {\n answer: ApiPollAnswer;\n voteResults?: ApiPollResult[];\n totalVoters?: number;\n maxVotersCount?: number;\n correctResults: string[];\n shouldAnimate: boolean;\n};\n\nconst PollOption: FC = ({\n answer,\n voteResults,\n totalVoters,\n maxVotersCount,\n correctResults,\n shouldAnimate,\n}) => {\n const result = voteResults && voteResults.find((r) => r.option === answer.option);\n const correctAnswer = correctResults.length === 0 || correctResults.indexOf(answer.option) !== -1;\n const showIcon = (correctResults.length > 0 && correctAnswer) || (result?.isChosen);\n const answerPercent = result ? getPercentage(result.votersCount, totalVoters || 0) : 0;\n const [finalPercent, setFinalPercent] = useState(shouldAnimate ? 0 : answerPercent);\n // eslint-disable-next-line no-null/no-null\n const lineRef = useRef(null);\n const lineWidth = result ? getPercentage(result.votersCount, maxVotersCount || 0) : 0;\n const isAnimationDoesNotStart = finalPercent < answerPercent;\n\n useEffect(() => {\n if (shouldAnimate) {\n setFinalPercent(answerPercent);\n }\n }, [shouldAnimate, answerPercent]);\n\n useEffect(() => {\n const lineEl = lineRef.current;\n\n if (lineEl && shouldAnimate) {\n const svgEl = lineEl.firstElementChild;\n\n const style = isAnimationDoesNotStart ? '' : 'stroke-dasharray: 100% 200%; stroke-dashoffset: -44';\n if (!svgEl) {\n lineEl.innerHTML = `\n \n \n `;\n } else {\n svgEl.setAttribute('style', style);\n }\n }\n }, [isAnimationDoesNotStart, shouldAnimate]);\n\n if (!voteResults || !result) {\n return undefined;\n }\n\n const lineStyle = `width: ${lineWidth}%; transform:scaleX(${isAnimationDoesNotStart ? 0 : 1})`;\n\n return (\n
\n
\n {answerPercent}%\n {showIcon && (\n \n \n \n )}\n
\n
\n
\n {renderText(answer.text)}\n
\n
\n
\n \n
\n
\n
\n );\n};\n\nfunction getPercentage(value: number, total: number) {\n return total > 0 ? ((value / total) * 100).toFixed() : 0;\n}\n\nexport default PollOption;\n","import React, {\n FC,\n useCallback,\n useEffect,\n useState,\n memo,\n useMemo,\n useRef,\n} from '../../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../../lib/teact/teactn';\n\nimport {\n ApiMessage, ApiPoll, ApiUser, ApiPollAnswer,\n} from '../../../api/types';\n\nimport renderText from '../../common/helpers/renderText';\nimport { renderTextWithEntities } from '../../common/helpers/renderMessageText';\nimport { formatMediaDuration } from '../../../util/dateFormat';\nimport useLang, { LangFn } from '../../../hooks/useLang';\n\nimport CheckboxGroup from '../../ui/CheckboxGroup';\nimport RadioGroup from '../../ui/RadioGroup';\nimport Avatar from '../../common/Avatar';\nimport Button from '../../ui/Button';\nimport Notification from '../../ui/Notification';\nimport PollOption from './PollOption';\n\nimport './Poll.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n poll: ApiPoll;\n onSendVote: (options: string[]) => void;\n};\n\ntype StateProps = {\n recentVoterIds?: number[];\n usersById: Record;\n serverTimeOffset: number;\n};\n\nconst SOLUTION_CONTAINER_ID = '#middle-column-portals';\nconst SOLUTION_DURATION = 5000;\nconst NBSP = '\\u00A0';\n\nconst Poll: FC = ({\n message,\n poll,\n recentVoterIds,\n usersById,\n onSendVote,\n serverTimeOffset,\n}) => {\n const { loadMessage, openPollResults } = getDispatch();\n\n const { id: messageId, chatId } = message;\n const { summary, results } = poll;\n const [isSubmitting, setIsSubmitting] = useState(false);\n const [chosenOptions, setChosenOptions] = useState([]);\n const [isSolutionShown, setIsSolutionShown] = useState(false);\n const [wasSubmitted, setWasSubmitted] = useState(false);\n const [closePeriod, setClosePeriod] = useState(\n !summary.closed && summary.closeDate && summary.closeDate > 0\n ? Math.min(summary.closeDate - Math.floor(Date.now() / 1000) + serverTimeOffset, summary.closePeriod!)\n : 0,\n );\n // eslint-disable-next-line no-null/no-null\n const countdownRef = useRef(null);\n const { results: voteResults, totalVoters } = results;\n const hasVoted = voteResults && voteResults.some((r) => r.isChosen);\n const canVote = !summary.closed && !hasVoted;\n const canViewResult = !canVote && summary.isPublic && Number(results.totalVoters) > 0;\n const isMultiple = canVote && summary.multipleChoice;\n const maxVotersCount = voteResults ? Math.max(...voteResults.map((r) => r.votersCount)) : totalVoters;\n const correctResults = voteResults ? voteResults.reduce((answers: string[], r) => {\n if (r.isCorrect) {\n answers.push(r.option);\n }\n\n return answers;\n }, []) : [];\n const answers = summary.answers.map((a) => ({\n label: a.text,\n value: a.option,\n hidden: Boolean(summary.quiz && summary.closePeriod && closePeriod <= 0),\n }));\n\n useEffect(() => {\n if (\n isSubmitting\n && poll.results.results\n && poll.results.results.some((result) => result.isChosen)\n ) {\n setIsSubmitting(false);\n }\n }, [isSubmitting, poll.results.results]);\n\n useEffect(() => {\n if (closePeriod > 0) {\n setTimeout(() => setClosePeriod(closePeriod - 1), 1000);\n }\n\n const countdownEl = countdownRef.current;\n\n if (countdownEl) {\n const circumference = 6 * 2 * Math.PI;\n const svgEl = countdownEl.lastElementChild;\n const timerEl = countdownEl.firstElementChild;\n if (closePeriod <= 5) {\n countdownEl.classList.add('hurry-up');\n }\n\n if (!svgEl || !timerEl) {\n countdownEl.innerHTML = `\n ${formatMediaDuration(closePeriod)}\n \n \n `;\n } else {\n const strokeDashOffset = ((summary.closePeriod! - closePeriod) / summary.closePeriod!) * circumference;\n timerEl.textContent = formatMediaDuration(closePeriod);\n (svgEl.firstElementChild as SVGElement).setAttribute('stroke-dashoffset', `-${strokeDashOffset}`);\n }\n }\n }, [closePeriod, summary.closePeriod]);\n\n useEffect(() => {\n if (summary.quiz && (closePeriod <= 0 || (hasVoted && !summary.closed))) {\n loadMessage({ chatId, messageId });\n }\n }, [chatId, closePeriod, hasVoted, loadMessage, messageId, summary.closed, summary.quiz]);\n\n // If the client time is not synchronized, the poll must be updated after the closePeriod time has expired.\n useEffect(() => {\n let timer: number | undefined;\n\n if (summary.quiz && !summary.closed && summary.closePeriod && summary.closePeriod > 0) {\n timer = window.setTimeout(() => {\n loadMessage({ chatId, messageId });\n }, summary.closePeriod * 1000);\n }\n\n return () => {\n if (timer) {\n window.clearTimeout(timer);\n }\n };\n }, [canVote, chatId, loadMessage, messageId, summary.closePeriod, summary.closed, summary.quiz]);\n\n const recentVoters = useMemo(() => {\n return recentVoterIds ? recentVoterIds.reduce((result: ApiUser[], id) => {\n const user = usersById[id];\n if (user) {\n result.push(user);\n }\n\n return result;\n }, []) : [];\n }, [usersById, recentVoterIds]);\n\n const handleRadioChange = useCallback(\n (option: string) => {\n setChosenOptions([option]);\n setIsSubmitting(true);\n setWasSubmitted(true);\n onSendVote([option]);\n }, [onSendVote],\n );\n\n const handleCheckboxChange = useCallback(\n (options: string[]) => {\n setChosenOptions(options);\n }, [],\n );\n\n const handleVoteClick = useCallback(\n () => {\n setIsSubmitting(true);\n setWasSubmitted(true);\n onSendVote(chosenOptions);\n }, [onSendVote, chosenOptions],\n );\n\n const handleViewResultsClick = useCallback(\n () => {\n openPollResults({ chatId, messageId });\n }, [chatId, messageId, openPollResults],\n );\n\n const handleSolutionShow = useCallback(() => {\n setIsSolutionShown(true);\n }, []);\n\n const handleSolutionHide = useCallback(() => {\n setIsSolutionShown(false);\n setWasSubmitted(false);\n }, []);\n\n // Show the solution to quiz if the answer was incorrect\n useEffect(() => {\n if (wasSubmitted && hasVoted && summary.quiz && results.results && poll.results.solution) {\n const correctResult = results.results.find((r) => r.isChosen && r.isCorrect);\n if (!correctResult) {\n setIsSolutionShown(true);\n }\n }\n }, [hasVoted, wasSubmitted, results.results, summary.quiz, poll.results.solution]);\n\n const lang = useLang();\n\n function renderResultOption(answer: ApiPollAnswer) {\n return (\n \n );\n }\n\n function renderRecentVoters() {\n return (\n recentVoters.length > 0 && (\n
\n {recentVoters.map((user) => (\n \n ))}\n
\n )\n );\n }\n\n function renderSolution() {\n return (\n isSolutionShown && poll.results.solution && (\n \n )\n );\n }\n\n return (\n
\n {renderSolution()}\n
{renderText(summary.question, ['emoji', 'br'])}
\n
\n {lang(getPollTypeString(summary))}\n {renderRecentVoters()}\n {closePeriod > 0 && canVote &&
}\n {summary.quiz && poll.results.solution && !canVote && (\n \n \n \n )}\n
\n {canVote && (\n
\n {isMultiple\n ? (\n \n )\n : (\n \n )}\n
\n )}\n {!canVote && (\n
\n {summary.answers.map(renderResultOption)}\n
\n )}\n {!canViewResult && !isMultiple && (\n
{getReadableVotersCount(lang, summary.quiz, results.totalVoters)}
\n )}\n {isMultiple && (\n \n {lang('PollSubmitVotes')}\n \n )}\n {canViewResult && (\n \n {lang('PollViewResults')}\n \n )}\n
\n );\n};\n\nfunction getPollTypeString(summary: ApiPoll['summary']) {\n // When we just created the poll, some properties don't exist.\n if (typeof summary.isPublic === 'undefined') {\n return NBSP;\n }\n\n if (summary.quiz) {\n return summary.isPublic ? 'QuizPoll' : 'AnonymousQuizPoll';\n }\n\n if (summary.closed) {\n return 'FinalResults';\n }\n\n return summary.isPublic ? 'PublicPoll' : 'AnonymousPoll';\n}\n\nfunction getReadableVotersCount(lang: LangFn, isQuiz: true | undefined, count?: number) {\n if (!count) {\n return lang(isQuiz ? 'Chat.Quiz.TotalVotesEmpty' : 'Chat.Poll.TotalVotesResultEmpty');\n }\n\n return lang(isQuiz ? 'Answer' : 'Vote', count, 'i');\n}\n\nexport default memo(withGlobal(\n (global, { poll }) => {\n const { recentVoterIds } = poll.results;\n const { serverTimeOffset, users: { byId: usersById } } = global;\n if (!recentVoterIds || recentVoterIds.length === 0) {\n return {};\n }\n\n return {\n recentVoterIds,\n usersById,\n serverTimeOffset,\n };\n },\n)(Poll));\n","import React, { FC, memo, useCallback } from '../../../lib/teact/teact';\n\nimport { ApiMessage } from '../../../api/types';\nimport { ObserveFn } from '../../../hooks/useIntersectionObserver';\nimport { ISettings } from '../../../types';\n\nimport { getMessageWebPage } from '../../../modules/helpers';\nimport { calculateMediaDimensions } from './helpers/mediaDimensions';\nimport renderText from '../../common/helpers/renderText';\nimport trimText from '../../../util/trimText';\nimport buildClassName from '../../../util/buildClassName';\n\nimport SafeLink from '../../common/SafeLink';\nimport Photo from './Photo';\nimport Video from './Video';\n\nimport './WebPage.scss';\n\nconst MAX_TEXT_LENGTH = 170; // symbols\n\ntype OwnProps = {\n message: ApiMessage;\n observeIntersection?: ObserveFn;\n noAvatars?: boolean;\n canAutoLoad?: boolean;\n canAutoPlay?: boolean;\n inPreview?: boolean;\n lastSyncTime?: number;\n isDownloading?: boolean;\n isProtected?: boolean;\n theme: ISettings['theme'];\n onMediaClick?: () => void;\n onCancelMediaTransfer?: () => void;\n};\n\nconst WebPage: FC = ({\n message,\n observeIntersection,\n noAvatars,\n canAutoLoad,\n canAutoPlay,\n inPreview,\n lastSyncTime,\n isDownloading = false,\n isProtected,\n theme,\n onMediaClick,\n onCancelMediaTransfer,\n}) => {\n const webPage = getMessageWebPage(message);\n\n let isSquarePhoto = false;\n if (webPage?.photo && !webPage.video) {\n const { width, height } = calculateMediaDimensions(message);\n isSquarePhoto = width === height;\n }\n\n const handleMediaClick = useCallback(() => {\n onMediaClick!();\n }, [onMediaClick]);\n\n if (!webPage) {\n return undefined;\n }\n\n const {\n siteName,\n url,\n displayUrl,\n title,\n description,\n photo,\n video,\n } = webPage;\n const isMediaInteractive = (photo || video) && onMediaClick && !isSquarePhoto;\n const truncatedDescription = trimText(description, MAX_TEXT_LENGTH);\n\n const className = buildClassName(\n 'WebPage',\n isSquarePhoto && 'with-square-photo',\n !photo && !video && !inPreview && 'without-media',\n video && 'with-video',\n );\n\n return (\n \n {photo && !video && (\n \n )}\n
\n \n {!inPreview && title && (\n

{renderText(title)}

\n )}\n {truncatedDescription && (\n

{renderText(truncatedDescription, ['emoji', 'br'])}

\n )}\n
\n {!inPreview && video && (\n \n )}\n
\n );\n};\n\nexport default memo(WebPage);\n","import React, { FC, memo } from '../../../lib/teact/teact';\n\nimport { ApiMessage } from '../../../api/types';\n\nimport { getMessageInvoice } from '../../../modules/helpers';\nimport { formatCurrency } from '../../../util/formatCurrency';\nimport renderText from '../../common/helpers/renderText';\nimport useLang from '../../../hooks/useLang';\n\nimport './Invoice.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n};\n\nconst Invoice: FC = ({\n message,\n}) => {\n const lang = useLang();\n const invoice = getMessageInvoice(message);\n\n const {\n title,\n text,\n amount,\n currency,\n isTest,\n photoUrl,\n } = invoice!;\n\n return (\n \n {title && (\n

{renderText(title)}

\n )}\n {text && (\n

{renderText(text, ['emoji', 'br'])}

\n )}\n
\n {photoUrl && (\n \n )}\n

\n {formatCurrency(amount, currency, lang.code)}\n {isTest && {lang('PaymentTestInvoice')}}\n

\n
\n
\n );\n};\n\nexport default memo(Invoice);\n","import { MouseEvent as ReactMouseEvent } from 'react';\nimport React, {\n FC,\n useCallback,\n useMemo,\n memo,\n} from '../../../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../../../lib/teact/teactn';\n\nimport { OwnProps as PhotoProps } from '../Photo';\nimport { OwnProps as VideoProps } from '../Video';\n\nimport buildClassName from '../../../../util/buildClassName';\nimport {\n selectIsInSelectMode,\n selectIsMessageSelected,\n} from '../../../../modules/selectors';\n\ntype OwnProps =\n PhotoProps\n & VideoProps;\n\ntype StateProps = {\n isInSelectMode?: boolean;\n isSelected?: boolean;\n};\n\nexport default function withSelectControl(WrappedComponent: FC) {\n const ComponentWithSelectControl: FC = (props) => {\n const {\n isInSelectMode,\n isSelected,\n message,\n dimensions,\n } = props;\n const { toggleMessageSelection } = getDispatch();\n\n const handleMessageSelect = useCallback((e: ReactMouseEvent) => {\n e.stopPropagation();\n toggleMessageSelection({ messageId: message.id, withShift: e?.shiftKey });\n }, [toggleMessageSelection, message]);\n\n const newProps = useMemo(() => {\n return {\n ...props,\n isInSelectMode,\n isSelected,\n dimensions: {\n ...props.dimensions,\n x: 0,\n y: 0,\n },\n onClick: isInSelectMode ? undefined : props.onClick,\n };\n }, [props, isInSelectMode, isSelected]);\n\n return (\n \n {isInSelectMode && (\n
\n {isSelected && (\n \n )}\n
\n )}\n {/* eslint-disable-next-line react/jsx-props-no-spreading */}\n \n \n );\n };\n\n return memo(withGlobal(\n (global, ownProps) => {\n const { message } = ownProps;\n return {\n isInSelectMode: selectIsInSelectMode(global),\n isSelected: selectIsMessageSelected(global, message.id),\n };\n },\n )(ComponentWithSelectControl));\n}\n","import React, { FC, useCallback } from '../../../lib/teact/teact';\n\nimport { GlobalState } from '../../../global/types';\nimport { ApiMessage } from '../../../api/types';\nimport { IAlbum, ISettings } from '../../../types';\nimport { AlbumRectPart, IAlbumLayout } from './helpers/calculateAlbumLayout';\n\nimport { getMessageContent } from '../../../modules/helpers';\nimport { getDispatch, getGlobal, withGlobal } from '../../../lib/teact/teactn';\nimport withSelectControl from './hocs/withSelectControl';\nimport { ObserveFn } from '../../../hooks/useIntersectionObserver';\nimport {\n selectActiveDownloadIds,\n selectCanAutoLoadMedia,\n selectCanAutoPlayMedia,\n selectTheme,\n} from '../../../modules/selectors';\n\nimport Photo from './Photo';\nimport Video from './Video';\n\nimport './Album.scss';\n\nconst PhotoWithSelect = withSelectControl(Photo);\nconst VideoWithSelect = withSelectControl(Video);\n\ntype OwnProps = {\n album: IAlbum;\n observeIntersection: ObserveFn;\n hasCustomAppendix?: boolean;\n lastSyncTime?: number;\n isOwn: boolean;\n isProtected?: boolean;\n albumLayout: IAlbumLayout;\n onMediaClick: (messageId: number) => void;\n};\n\ntype StateProps = {\n theme: ISettings['theme'];\n uploadsById: GlobalState['fileUploads']['byMessageLocalId'];\n activeDownloadIds: number[];\n};\n\nconst Album: FC = ({\n album,\n observeIntersection,\n hasCustomAppendix,\n lastSyncTime,\n isOwn,\n isProtected,\n albumLayout,\n onMediaClick,\n uploadsById,\n activeDownloadIds,\n theme,\n}) => {\n const { cancelSendingMessage } = getDispatch();\n\n const mediaCount = album.messages.length;\n\n const handleCancelUpload = useCallback((message: ApiMessage) => {\n cancelSendingMessage({ chatId: message.chatId, messageId: message.id });\n }, [cancelSendingMessage]);\n\n function renderAlbumMessage(message: ApiMessage, index: number) {\n const { photo, video } = getMessageContent(message);\n const fileUpload = uploadsById[message.previousLocalId || message.id];\n const uploadProgress = fileUpload?.progress;\n const { dimensions, sides } = albumLayout.layout[index];\n\n // Ignoring global updates is a known drawback here\n const canAutoLoad = selectCanAutoLoadMedia(getGlobal(), message);\n const canAutoPlay = selectCanAutoPlayMedia(getGlobal(), message);\n\n if (photo) {\n const shouldAffectAppendix = hasCustomAppendix && (\n // eslint-disable-next-line no-bitwise\n (isOwn ? index === mediaCount - 1 : Boolean(sides & AlbumRectPart.Left && sides & AlbumRectPart.Bottom))\n );\n\n return (\n \n );\n } else if (video) {\n return (\n \n );\n }\n\n return undefined;\n }\n\n const { width: containerWidth, height: containerHeight } = albumLayout.containerStyle;\n\n return (\n \n {album.messages.map(renderAlbumMessage)}\n \n );\n};\n\nexport default withGlobal(\n (global, { album }): StateProps => {\n const { chatId } = album.mainMessage;\n const theme = selectTheme(global);\n const activeDownloadIds = selectActiveDownloadIds(global, chatId);\n return {\n theme,\n uploadsById: global.fileUploads.byMessageLocalId,\n activeDownloadIds,\n };\n },\n)(Album);\n","import React, {\n FC,\n useCallback,\n useEffect,\n useRef,\n useState,\n} from '../../../lib/teact/teact';\nimport { getDispatch } from '../../../lib/teact/teactn';\n\nimport { ApiMediaFormat, ApiMessage } from '../../../api/types';\n\nimport { ROUND_VIDEO_DIMENSIONS_PX } from '../../common/helpers/mediaDimensions';\nimport { getMessageMediaFormat, getMessageMediaHash } from '../../../modules/helpers';\nimport { formatMediaDuration } from '../../../util/dateFormat';\nimport buildClassName from '../../../util/buildClassName';\nimport { stopCurrentAudio } from '../../../util/audioPlayer';\nimport safePlay from '../../../util/safePlay';\nimport { fastRaf } from '../../../util/schedulers';\nimport { ObserveFn, useIsIntersecting } from '../../../hooks/useIntersectionObserver';\nimport useMediaWithLoadProgress from '../../../hooks/useMediaWithLoadProgress';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useMediaTransition from '../../../hooks/useMediaTransition';\nimport usePrevious from '../../../hooks/usePrevious';\nimport useBuffering from '../../../hooks/useBuffering';\nimport useVideoCleanup from '../../../hooks/useVideoCleanup';\nimport useVideoAutoPause from './hooks/useVideoAutoPause';\nimport useBlurredMediaThumbRef from './hooks/useBlurredMediaThumbRef';\n\nimport ProgressSpinner from '../../ui/ProgressSpinner';\n\nimport './RoundVideo.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n observeIntersection: ObserveFn;\n canAutoLoad?: boolean;\n lastSyncTime?: number;\n isDownloading?: boolean;\n};\n\nlet currentOnRelease: NoneToVoidFunction;\n\nfunction createCapture(onRelease: NoneToVoidFunction) {\n return () => {\n if (currentOnRelease) {\n currentOnRelease();\n }\n\n currentOnRelease = onRelease;\n };\n}\n\nconst RoundVideo: FC = ({\n message,\n observeIntersection,\n canAutoLoad,\n lastSyncTime,\n isDownloading,\n}) => {\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const playingProgressRef = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const playerRef = useRef(null);\n\n const video = message.content.video!;\n\n const isIntersecting = useIsIntersecting(ref, observeIntersection);\n\n const [isLoadAllowed, setIsLoadAllowed] = useState(canAutoLoad);\n const shouldLoad = Boolean(isLoadAllowed && isIntersecting && lastSyncTime);\n const { mediaData, loadProgress } = useMediaWithLoadProgress(\n getMessageMediaHash(message, 'inline'),\n !shouldLoad,\n getMessageMediaFormat(message, 'inline'),\n lastSyncTime,\n );\n\n const { loadProgress: downloadProgress } = useMediaWithLoadProgress(\n getMessageMediaHash(message, 'download'),\n !isDownloading,\n ApiMediaFormat.BlobUrl,\n lastSyncTime,\n );\n const thumbRef = useBlurredMediaThumbRef(message, mediaData);\n\n const { isBuffered, bufferingHandlers } = useBuffering();\n const isTransferring = (isLoadAllowed && !isBuffered) || isDownloading;\n const wasLoadDisabled = usePrevious(isLoadAllowed) === false;\n\n const transitionClassNames = useMediaTransition(mediaData);\n const {\n shouldRender: shouldSpinnerRender,\n transitionClassNames: spinnerClassNames,\n } = useShowTransition(isTransferring || !isBuffered, undefined, wasLoadDisabled);\n\n const [isActivated, setIsActivated] = useState(false);\n const [progress, setProgress] = useState(0);\n\n useEffect(() => {\n if (!isActivated) {\n return;\n }\n\n const svgCenter = ROUND_VIDEO_DIMENSIONS_PX / 2;\n const svgMargin = 6;\n const circumference = (svgCenter - svgMargin) * 2 * Math.PI;\n const strokeDashOffset = circumference - progress * circumference;\n\n const playerEl = playerRef.current!;\n const playingProgressEl = playingProgressRef.current!;\n const svgEl = playingProgressEl.firstElementChild;\n\n if (!svgEl) {\n playingProgressEl.innerHTML = `\n \n \n `;\n } else {\n (svgEl.firstElementChild as SVGElement).setAttribute('stroke-dashoffset', strokeDashOffset.toString());\n }\n\n setProgress(playerEl.currentTime / playerEl.duration);\n }, [isActivated, progress]);\n\n const shouldPlay = Boolean(mediaData && isIntersecting);\n\n const stopPlaying = () => {\n setIsActivated(false);\n setProgress(0);\n safePlay(playerRef.current!);\n\n fastRaf(() => {\n playingProgressRef.current!.innerHTML = '';\n });\n };\n\n const capturePlaying = createCapture(stopPlaying);\n\n useEffect(() => {\n if (!playerRef.current) {\n return;\n }\n\n if (shouldPlay) {\n safePlay(playerRef.current);\n } else {\n playerRef.current.pause();\n }\n }, [shouldPlay]);\n\n useVideoAutoPause(playerRef, shouldPlay);\n useVideoCleanup(playerRef, [mediaData]);\n\n const handleClick = useCallback(() => {\n if (!mediaData) {\n setIsLoadAllowed((isAllowed) => !isAllowed);\n\n return;\n }\n\n if (isDownloading) {\n getDispatch().cancelMessageMediaDownload({ message });\n return;\n }\n\n const playerEl = playerRef.current!;\n if (isActivated) {\n if (playerEl.paused) {\n safePlay(playerEl);\n stopCurrentAudio();\n } else {\n playerEl.pause();\n }\n } else {\n capturePlaying();\n // Pause is a workaround for iOS Safari – otherwise it stops video after several frames\n playerEl.pause();\n playerEl.currentTime = 0;\n safePlay(playerEl);\n stopCurrentAudio();\n\n setIsActivated(true);\n }\n }, [capturePlaying, isActivated, isDownloading, mediaData, message]);\n\n const handleTimeUpdate = useCallback((e: React.UIEvent) => {\n const playerEl = e.currentTarget;\n\n setProgress(playerEl.currentTime / playerEl.duration);\n }, []);\n\n const videoClassName = buildClassName('full-media', transitionClassNames);\n\n return (\n \n
\n \n
\n {mediaData && (\n
\n {/* eslint-disable-next-line jsx-a11y/media-has-caption */}\n \n \n \n
\n )}\n
\n {shouldSpinnerRender && (\n
\n \n
\n )}\n {!mediaData && !isLoadAllowed && (\n \n )}\n
\n {isActivated ? formatMediaDuration(playerRef.current!.currentTime) : formatMediaDuration(video.duration)}\n {(!isActivated || playerRef.current!.paused) && }\n
\n
\n );\n};\n\nexport default RoundVideo;\n","import React, { FC } from '../../../lib/teact/teact';\n\nimport { ApiKeyboardButton, ApiMessage } from '../../../api/types';\n\nimport { RE_TME_LINK } from '../../../config';\nimport renderText from '../../common/helpers/renderText';\nimport useLang from '../../../hooks/useLang';\n\nimport Button from '../../ui/Button';\n\nimport './InlineButtons.scss';\n\ntype OwnProps = {\n message: ApiMessage;\n onClick: ({ button }: { button: ApiKeyboardButton }) => void;\n};\n\nconst InlineButtons: FC = ({ message, onClick }) => {\n const lang = useLang();\n\n return (\n
\n {message.inlineButtons!.map((row) => (\n
\n {row.map((button) => (\n onClick({ button })}\n >\n {renderText(lang(button.text))}\n {button.type === 'buy' && }\n {button.type === 'url' && !button.value!.match(RE_TME_LINK) && }\n \n ))}\n
\n ))}\n
\n );\n};\n\nexport default InlineButtons;\n","import React, {\n FC, memo, useCallback, useMemo,\n} from '../../../lib/teact/teact';\nimport { getDispatch, getGlobal } from '../../../lib/teact/teactn';\n\nimport {\n ApiChat, ApiThreadInfo, ApiUser,\n} from '../../../api/types';\n\nimport { isUserId } from '../../../modules/helpers';\nimport { formatIntegerCompact } from '../../../util/textFormat';\nimport buildClassName from '../../../util/buildClassName';\nimport useLang from '../../../hooks/useLang';\n\nimport Avatar from '../../common/Avatar';\n\nimport './CommentButton.scss';\n\ntype OwnProps = {\n threadInfo: ApiThreadInfo;\n disabled?: boolean;\n};\n\nconst CommentButton: FC = ({\n threadInfo,\n disabled,\n}) => {\n const { openChat } = getDispatch();\n\n const lang = useLang();\n const {\n threadId, chatId, messagesCount, lastMessageId, lastReadInboxMessageId, recentReplierIds,\n } = threadInfo;\n\n const handleClick = useCallback(() => {\n openChat({ id: chatId, threadId });\n }, [openChat, chatId, threadId]);\n\n const recentRepliers = useMemo(() => {\n if (!recentReplierIds?.length) {\n return undefined;\n }\n\n // No need for expensive global updates on chats and users, so we avoid them\n const { users: { byId: usersById }, chats: { byId: chatsById } } = getGlobal();\n\n return recentReplierIds.map((peerId) => {\n return isUserId(peerId) ? usersById[peerId] : chatsById[peerId];\n }).filter(Boolean);\n }, [recentReplierIds]);\n\n if (messagesCount === undefined) {\n return undefined;\n }\n\n function renderRecentRepliers() {\n return (\n recentRepliers && recentRepliers.length > 0 && (\n
\n {recentRepliers.map((user) => (\n \n ))}\n
\n )\n );\n }\n\n const hasUnread = Boolean(lastReadInboxMessageId && lastMessageId && lastReadInboxMessageId < lastMessageId);\n\n return (\n \n \n {(!recentRepliers || recentRepliers.length === 0) && }\n {renderRecentRepliers()}\n
\n {messagesCount ? lang('Comments', messagesCount, 'i') : lang('LeaveAComment')}\n
\n \n \n );\n};\n\nexport default memo(CommentButton);\n","import React, {\n FC,\n memo,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n} from '../../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../../lib/teact/teactn';\n\nimport { MessageListType } from '../../../global/types';\nimport {\n ApiMessage,\n ApiMessageOutgoingStatus,\n ApiUser,\n ApiChat,\n ApiSticker,\n ApiThreadInfo,\n} from '../../../api/types';\nimport {\n AudioOrigin, FocusDirection, IAlbum, ISettings,\n} from '../../../types';\n\nimport { IS_ANDROID, IS_TOUCH_ENV } from '../../../util/environment';\nimport {\n selectChat,\n selectChatMessage,\n selectUploadProgress,\n selectIsChatWithSelf,\n selectOutgoingStatus,\n selectUser,\n selectIsMessageFocused,\n selectCurrentTextSearch,\n selectAnimatedEmoji,\n selectIsInSelectMode,\n selectIsMessageSelected,\n selectIsDocumentGroupSelected,\n selectSender,\n selectForwardedSender,\n selectThreadTopMessageId,\n selectCanAutoLoadMedia,\n selectCanAutoPlayMedia,\n selectShouldLoopStickers,\n selectTheme,\n selectAllowedMessageActions,\n selectIsDownloading,\n selectThreadInfo,\n selectIsMessageProtected,\n} from '../../../modules/selectors';\nimport {\n getMessageContent,\n isOwnMessage,\n isReplyMessage,\n isAnonymousOwnMessage,\n isMessageLocal,\n isUserId,\n isChatWithRepliesBot,\n getMessageCustomShape,\n isChatChannel,\n getMessageSingleEmoji,\n getSenderTitle,\n getUserColorKey,\n} from '../../../modules/helpers';\nimport buildClassName from '../../../util/buildClassName';\nimport useEnsureMessage from '../../../hooks/useEnsureMessage';\nimport useContextMenuHandlers from '../../../hooks/useContextMenuHandlers';\nimport { renderMessageText } from '../../common/helpers/renderMessageText';\nimport { ROUND_VIDEO_DIMENSIONS_PX } from '../../common/helpers/mediaDimensions';\nimport { buildContentClassName, isEmojiOnlyMessage } from './helpers/buildContentClassName';\nimport { getMinMediaWidth, calculateMediaDimensions } from './helpers/mediaDimensions';\nimport { calculateAlbumLayout } from './helpers/calculateAlbumLayout';\nimport renderText from '../../common/helpers/renderText';\nimport calculateAuthorWidth from './helpers/calculateAuthorWidth';\nimport { ObserveFn, useOnIntersect } from '../../../hooks/useIntersectionObserver';\nimport useLang from '../../../hooks/useLang';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useFlag from '../../../hooks/useFlag';\nimport useFocusMessage from './hooks/useFocusMessage';\nimport useOuterHandlers from './hooks/useOuterHandlers';\nimport useInnerHandlers from './hooks/useInnerHandlers';\n\nimport Button from '../../ui/Button';\nimport Avatar from '../../common/Avatar';\nimport EmbeddedMessage from '../../common/EmbeddedMessage';\nimport Document from '../../common/Document';\nimport Audio from '../../common/Audio';\nimport MessageMeta from './MessageMeta';\nimport ContextMenuContainer from './ContextMenuContainer.async';\nimport Sticker from './Sticker';\nimport AnimatedEmoji from '../../common/AnimatedEmoji';\nimport Photo from './Photo';\nimport Video from './Video';\nimport Contact from './Contact';\nimport Poll from './Poll';\nimport WebPage from './WebPage';\nimport Invoice from './Invoice';\nimport Album from './Album';\nimport RoundVideo from './RoundVideo';\nimport InlineButtons from './InlineButtons';\nimport CommentButton from './CommentButton';\n\nimport './Message.scss';\n\ntype MessagePositionProperties = {\n isFirstInGroup: boolean;\n isLastInGroup: boolean;\n isFirstInDocumentGroup: boolean;\n isLastInDocumentGroup: boolean;\n isLastInList: boolean;\n};\n\ntype OwnProps =\n {\n message: ApiMessage;\n observeIntersectionForBottom: ObserveFn;\n observeIntersectionForMedia: ObserveFn;\n observeIntersectionForAnimatedStickers: ObserveFn;\n album?: IAlbum;\n noAvatars?: boolean;\n withAvatar?: boolean;\n withSenderName?: boolean;\n threadId: number;\n messageListType: MessageListType;\n noComments: boolean;\n appearanceOrder: number;\n }\n & MessagePositionProperties;\n\ntype StateProps = {\n theme: ISettings['theme'];\n forceSenderName?: boolean;\n chatUsername?: string;\n sender?: ApiUser | ApiChat;\n originSender?: ApiUser | ApiChat;\n botSender?: ApiUser;\n isThreadTop?: boolean;\n shouldHideReply?: boolean;\n replyMessage?: ApiMessage;\n replyMessageSender?: ApiUser | ApiChat;\n outgoingStatus?: ApiMessageOutgoingStatus;\n uploadProgress?: number;\n isProtected?: boolean;\n isFocused?: boolean;\n focusDirection?: FocusDirection;\n noFocusHighlight?: boolean;\n isResizingContainer?: boolean;\n isForwarding?: boolean;\n isChatWithSelf?: boolean;\n isRepliesChat?: boolean;\n isChannel?: boolean;\n canReply?: boolean;\n lastSyncTime?: number;\n highlight?: string;\n isSingleEmoji?: boolean;\n animatedEmoji?: ApiSticker;\n isInSelectMode?: boolean;\n isSelected?: boolean;\n isGroupSelected?: boolean;\n isDownloading: boolean;\n threadId?: number;\n isPinnedList?: boolean;\n canAutoLoadMedia?: boolean;\n canAutoPlayMedia?: boolean;\n shouldLoopStickers?: boolean;\n autoLoadFileMaxSizeMb: number;\n threadInfo?: ApiThreadInfo;\n};\n\nconst NBSP = '\\u00A0';\nconst GROUP_MESSAGE_HOVER_ATTRIBUTE = 'data-is-document-group-hover';\n// eslint-disable-next-line max-len\nconst APPENDIX_OWN = { __html: '' };\n// eslint-disable-next-line max-len\nconst APPENDIX_NOT_OWN = { __html: '' };\nconst APPEARANCE_DELAY = 10;\nconst NO_MEDIA_CORNERS_THRESHOLD = 18;\n\nconst Message: FC = ({\n message,\n chatUsername,\n observeIntersectionForBottom,\n observeIntersectionForMedia,\n observeIntersectionForAnimatedStickers,\n album,\n noAvatars,\n withAvatar,\n withSenderName,\n noComments,\n appearanceOrder,\n isFirstInGroup,\n isLastInGroup,\n isFirstInDocumentGroup,\n isLastInDocumentGroup,\n isLastInList,\n theme,\n forceSenderName,\n sender,\n originSender,\n botSender,\n isThreadTop,\n shouldHideReply,\n replyMessage,\n replyMessageSender,\n outgoingStatus,\n uploadProgress,\n isProtected,\n isFocused,\n focusDirection,\n noFocusHighlight,\n isResizingContainer,\n isForwarding,\n isChatWithSelf,\n isRepliesChat,\n isChannel,\n canReply,\n lastSyncTime,\n highlight,\n animatedEmoji,\n isInSelectMode,\n isSelected,\n isGroupSelected,\n threadId,\n messageListType,\n isPinnedList,\n isDownloading,\n canAutoLoadMedia,\n canAutoPlayMedia,\n shouldLoopStickers,\n autoLoadFileMaxSizeMb,\n threadInfo,\n}) => {\n const {\n toggleMessageSelection,\n clickInlineButton,\n disableContextMenuHint,\n } = getDispatch();\n\n // eslint-disable-next-line no-null/no-null\n const ref = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const bottomMarkerRef = useRef(null);\n\n const lang = useLang();\n\n useOnIntersect(bottomMarkerRef, observeIntersectionForBottom);\n\n const {\n isContextMenuOpen, contextMenuPosition,\n handleBeforeContextMenu, handleContextMenu: onContextMenu,\n handleContextMenuClose, handleContextMenuHide,\n } = useContextMenuHandlers(ref, IS_TOUCH_ENV && isInSelectMode, true, IS_ANDROID);\n\n useEffect(() => {\n if (isContextMenuOpen) {\n disableContextMenuHint();\n }\n }, [isContextMenuOpen, disableContextMenuHint]);\n\n const noAppearanceAnimation = appearanceOrder <= 0;\n const [isShown, markShown] = useFlag(noAppearanceAnimation);\n useEffect(() => {\n if (noAppearanceAnimation) {\n return;\n }\n\n setTimeout(markShown, appearanceOrder * APPEARANCE_DELAY);\n }, [appearanceOrder, markShown, noAppearanceAnimation]);\n const { transitionClassNames } = useShowTransition(isShown, undefined, noAppearanceAnimation, false);\n\n const { id: messageId, chatId } = message;\n\n const isLocal = isMessageLocal(message);\n const isOwn = isOwnMessage(message);\n const isScheduled = messageListType === 'scheduled' || message.isScheduled;\n const hasReply = isReplyMessage(message) && !shouldHideReply;\n const hasThread = Boolean(threadInfo) && messageListType === 'thread';\n const customShape = getMessageCustomShape(message);\n const { forwardInfo, viaBotId } = message;\n const asForwarded = (\n forwardInfo\n && (!isChatWithSelf || isScheduled)\n && !isRepliesChat\n && !forwardInfo.isLinkedChannelPost\n && !customShape\n );\n const isInDocumentGroup = Boolean(message.groupedId) && !message.isInAlbum;\n const isAlbum = Boolean(album) && album!.messages.length > 1;\n const {\n text, photo, video, audio, voice, document, sticker, contact, poll, webPage, invoice,\n } = getMessageContent(message);\n const textParts = renderMessageText(message, highlight, isEmojiOnlyMessage(customShape));\n const isContextMenuShown = contextMenuPosition !== undefined;\n const signature = (\n (isChannel && message.adminTitle) || (!asForwarded && forwardInfo?.adminTitle) || undefined\n );\n const metaSafeAuthorWidth = useMemo(() => {\n return signature ? calculateAuthorWidth(signature) : undefined;\n }, [signature]);\n const canShowActionButton = (\n !(isContextMenuShown || isInSelectMode || isForwarding)\n && (!isInDocumentGroup || isLastInDocumentGroup)\n );\n const canForward = isChannel && !isScheduled;\n const canFocus = Boolean(isPinnedList\n || (forwardInfo\n && (forwardInfo.isChannelPost || (isChatWithSelf && !isOwn) || isRepliesChat)\n && forwardInfo.fromMessageId\n ));\n const avatarPeer = forwardInfo && (isChatWithSelf || isRepliesChat || !sender) ? originSender : sender;\n const senderPeer = forwardInfo ? originSender : sender;\n\n const selectMessage = useCallback((e?: React.MouseEvent, groupedId?: string) => {\n toggleMessageSelection({\n messageId,\n groupedId,\n ...(e?.shiftKey && { withShift: true }),\n ...(isAlbum && { childMessageIds: album!.messages.map(({ id }) => id) }),\n });\n }, [toggleMessageSelection, messageId, isAlbum, album]);\n\n const {\n handleMouseDown,\n handleClick,\n handleContextMenu,\n handleDoubleClick,\n handleContentDoubleClick,\n isSwiped,\n } = useOuterHandlers(\n selectMessage,\n ref,\n messageId,\n isAlbum,\n Boolean(isInSelectMode),\n Boolean(canReply),\n Boolean(isProtected),\n onContextMenu,\n handleBeforeContextMenu,\n );\n\n const {\n handleAvatarClick,\n handleSenderClick,\n handleViaBotClick,\n handleReplyClick,\n handleMediaClick,\n handleAudioPlay,\n handleAlbumMediaClick,\n handleMetaClick,\n handleReadMedia,\n handleCancelUpload,\n handleVoteSend,\n handleGroupForward,\n handleForward,\n handleFocus,\n handleFocusForwarded,\n handleDocumentGroupSelectAll,\n } = useInnerHandlers(\n lang,\n selectMessage,\n message,\n chatId,\n threadId,\n isInDocumentGroup,\n asForwarded,\n isScheduled,\n isRepliesChat,\n album,\n avatarPeer,\n senderPeer,\n botSender,\n );\n\n const containerClassName = buildClassName(\n 'Message message-list-item',\n isFirstInGroup && 'first-in-group',\n isProtected && 'is-protected',\n isLastInGroup && 'last-in-group',\n isFirstInDocumentGroup && 'first-in-document-group',\n isLastInDocumentGroup && 'last-in-document-group',\n isLastInList && 'last-in-list',\n isOwn && 'own',\n Boolean(message.views) && 'has-views',\n message.isEdited && 'was-edited',\n hasReply && 'has-reply',\n isContextMenuShown && 'has-menu-open',\n isFocused && !noFocusHighlight && 'focused',\n isForwarding && 'is-forwarding',\n message.isDeleting && 'is-deleting',\n isInDocumentGroup && 'is-in-document-group',\n isAlbum && 'is-album',\n message.hasUnreadMention && 'has-unread-mention',\n isSelected && 'is-selected',\n isInSelectMode && 'is-in-selection-mode',\n isThreadTop && 'is-thread-top',\n Boolean(message.inlineButtons) && 'has-inline-buttons',\n isSwiped && 'is-swiped',\n transitionClassNames,\n );\n const contentClassName = buildContentClassName(message, {\n hasReply,\n customShape,\n isLastInGroup,\n asForwarded,\n hasThread,\n forceSenderName,\n hasComments: threadInfo && threadInfo?.messagesCount > 0,\n hasActionButton: canForward || canFocus,\n });\n const withCommentButton = (\n threadInfo && (!isInDocumentGroup || isLastInDocumentGroup) && messageListType === 'thread' && !noComments\n );\n const withAppendix = contentClassName.includes('has-appendix');\n\n useEnsureMessage(\n isRepliesChat && message.replyToChatId ? message.replyToChatId : chatId,\n hasReply ? message.replyToMessageId : undefined,\n replyMessage,\n message.id,\n );\n useFocusMessage(ref, chatId, isFocused, focusDirection, noFocusHighlight, isResizingContainer);\n\n let style = '';\n let calculatedWidth;\n let noMediaCorners = false;\n const albumLayout = useMemo(() => {\n return isAlbum ? calculateAlbumLayout(isOwn, Boolean(asForwarded), Boolean(noAvatars), album!) : undefined;\n }, [isAlbum, isOwn, asForwarded, noAvatars, album]);\n\n const extraPadding = asForwarded ? 28 : 0;\n if (!isAlbum && (photo || video)) {\n let width: number | undefined;\n if (photo) {\n width = calculateMediaDimensions(message, noAvatars).width;\n } else if (video) {\n if (video.isRound) {\n width = ROUND_VIDEO_DIMENSIONS_PX;\n } else {\n width = calculateMediaDimensions(message, noAvatars).width;\n }\n }\n\n if (width) {\n calculatedWidth = Math.max(getMinMediaWidth(Boolean(text), withCommentButton), width);\n if (calculatedWidth - width > NO_MEDIA_CORNERS_THRESHOLD) {\n noMediaCorners = true;\n }\n }\n } else if (albumLayout) {\n calculatedWidth = Math.max(getMinMediaWidth(Boolean(text), withCommentButton), albumLayout.containerStyle.width);\n if (calculatedWidth - albumLayout.containerStyle.width > NO_MEDIA_CORNERS_THRESHOLD) {\n noMediaCorners = true;\n }\n }\n\n if (calculatedWidth) {\n style = `width: ${calculatedWidth + extraPadding}px`;\n }\n\n function renderAvatar() {\n const isAvatarPeerUser = avatarPeer && isUserId(avatarPeer.id);\n const avatarUser = (avatarPeer && isAvatarPeerUser) ? avatarPeer as ApiUser : undefined;\n const avatarChat = (avatarPeer && !isAvatarPeerUser) ? avatarPeer as ApiChat : undefined;\n const hiddenName = (!avatarPeer && forwardInfo) ? forwardInfo.hiddenUserName : undefined;\n\n return (\n \n );\n }\n\n function renderContent() {\n const className = buildClassName(\n 'content-inner',\n asForwarded && 'forwarded-message',\n hasReply && 'reply-message',\n noMediaCorners && 'no-media-corners',\n );\n const hasCustomAppendix = isLastInGroup && !textParts && !asForwarded && !hasThread;\n const shouldInlineMeta = !webPage && !animatedEmoji && textParts;\n const textContentClass = buildClassName(\n 'text-content',\n shouldInlineMeta && 'with-meta',\n outgoingStatus && 'with-outgoing-icon',\n );\n\n return (\n
\n {renderSenderName()}\n {hasReply && (\n \n )}\n {sticker && (\n \n )}\n {animatedEmoji && (\n \n )}\n {isAlbum && (\n \n )}\n {!isAlbum && photo && (\n \n )}\n {!isAlbum && video && video.isRound && (\n \n )}\n {!isAlbum && video && !video.isRound && (\n \n )}\n {(audio || voice) && (\n \n )}\n {document && (\n \n )}\n {contact && (\n \n )}\n {poll && (\n \n )}\n {!animatedEmoji && textParts && (\n

\n {textParts}\n {shouldInlineMeta && (\n \n )}\n

\n )}\n {webPage && (\n \n )}\n {invoice && }\n
\n );\n }\n\n function renderSenderName() {\n const shouldRender = !(customShape && !viaBotId) && (\n (withSenderName && !photo && !video) || asForwarded || viaBotId || forceSenderName\n ) && (!isInDocumentGroup || isFirstInDocumentGroup) && !(hasReply && customShape);\n\n if (!shouldRender) {\n return undefined;\n }\n\n let senderTitle;\n let senderColor;\n if (senderPeer && !(customShape && viaBotId)) {\n senderTitle = getSenderTitle(lang, senderPeer);\n\n if (!asForwarded) {\n senderColor = `color-${getUserColorKey(senderPeer)}`;\n }\n } else if (forwardInfo?.hiddenUserName) {\n senderTitle = forwardInfo.hiddenUserName;\n }\n\n return (\n
\n {senderTitle ? (\n \n {renderText(senderTitle)}\n \n ) : !botSender ? (\n NBSP\n ) : undefined}\n {botSender && (\n <>\n {lang('ViaBot')}\n \n {renderText(`@${botSender.username}`)}\n \n \n )}\n {forwardInfo?.isLinkedChannelPost ? (\n {lang('DiscussChannel')}\n ) : message.adminTitle && !isChannel ? (\n {message.adminTitle}\n ) : undefined}\n
\n );\n }\n\n return (\n \n \n {!isInDocumentGroup && (\n
\n {isSelected && }\n
\n )}\n {isLastInDocumentGroup && (\n \n {isGroupSelected && (\n \n )}\n \n )}\n {withAvatar && renderAvatar()}\n \n \n {asForwarded && (!isInDocumentGroup || isFirstInDocumentGroup) && (\n
{lang('ForwardedMessage')}
\n )}\n {renderContent()}\n {(!isInDocumentGroup || isLastInDocumentGroup) && !(!webPage && !animatedEmoji && textParts) && (\n \n )}\n {canShowActionButton && canForward ? (\n \n \n \n ) : canShowActionButton && canFocus ? (\n \n \n \n ) : undefined}\n {withCommentButton && }\n {withAppendix && (\n
\n )}\n
\n {message.inlineButtons && (\n \n )}\n \n {contextMenuPosition && (\n \n )}\n \n );\n};\n\nfunction handleDocumentGroupMouseEnter(e: React.MouseEvent) {\n const lastGroupElement = getLastElementInDocumentGroup(e.currentTarget);\n if (lastGroupElement) {\n lastGroupElement.setAttribute(GROUP_MESSAGE_HOVER_ATTRIBUTE, '');\n }\n}\n\nfunction handleDocumentGroupMouseLeave(e: React.MouseEvent) {\n const lastGroupElement = getLastElementInDocumentGroup(e.currentTarget);\n if (lastGroupElement) {\n lastGroupElement.removeAttribute(GROUP_MESSAGE_HOVER_ATTRIBUTE);\n }\n}\n\nfunction getLastElementInDocumentGroup(element: Element) {\n let current: Element | null = element;\n\n do {\n current = current.nextElementSibling;\n } while (current && !current.classList.contains('last-in-document-group'));\n\n return current;\n}\n\nexport default memo(withGlobal(\n (global, ownProps): StateProps => {\n const { focusedMessage, forwardMessages, lastSyncTime } = global;\n const {\n message, album, withSenderName, withAvatar, threadId, messageListType,\n } = ownProps;\n const {\n id, chatId, viaBotId, replyToChatId, replyToMessageId, isOutgoing, threadInfo,\n } = message;\n\n const chat = selectChat(global, chatId);\n const isChatWithSelf = selectIsChatWithSelf(global, chatId);\n const isRepliesChat = isChatWithRepliesBot(chatId);\n const isChannel = chat && isChatChannel(chat);\n const chatUsername = chat?.username;\n\n const forceSenderName = !isChatWithSelf && isAnonymousOwnMessage(message);\n const canShowSender = withSenderName || withAvatar || forceSenderName;\n const sender = selectSender(global, message);\n const originSender = selectForwardedSender(global, message);\n const botSender = viaBotId ? selectUser(global, viaBotId) : undefined;\n\n const threadTopMessageId = threadId ? selectThreadTopMessageId(global, chatId, threadId) : undefined;\n const isThreadTop = message.id === threadTopMessageId;\n\n const shouldHideReply = replyToMessageId === threadTopMessageId;\n const replyMessage = replyToMessageId && !shouldHideReply\n ? selectChatMessage(global, isRepliesChat && replyToChatId ? replyToChatId : chatId, replyToMessageId)\n : undefined;\n const replyMessageSender = replyMessage && selectSender(global, replyMessage);\n\n const uploadProgress = selectUploadProgress(global, message);\n const isFocused = messageListType === 'thread' && (\n album\n ? album.messages.some((m) => selectIsMessageFocused(global, m))\n : selectIsMessageFocused(global, message)\n );\n\n const {\n direction: focusDirection, noHighlight: noFocusHighlight, isResizingContainer,\n } = (isFocused && focusedMessage) || {};\n\n const isForwarding = forwardMessages.messageIds && forwardMessages.messageIds.includes(id);\n\n const { query: highlight } = selectCurrentTextSearch(global) || {};\n\n const singleEmoji = getMessageSingleEmoji(message);\n let isSelected: boolean;\n\n if (album?.messages) {\n isSelected = album.messages.every(({ id: messageId }) => selectIsMessageSelected(global, messageId));\n } else {\n isSelected = selectIsMessageSelected(global, id);\n }\n\n const { canReply } = (messageListType === 'thread' && selectAllowedMessageActions(global, message, threadId)) || {};\n const isDownloading = selectIsDownloading(global, message);\n const actualThreadInfo = threadInfo\n ? selectThreadInfo(global, threadInfo.chatId, threadInfo.threadId) || threadInfo\n : undefined;\n\n return {\n theme: selectTheme(global),\n chatUsername,\n forceSenderName,\n sender: canShowSender ? sender : undefined,\n originSender,\n botSender,\n shouldHideReply,\n isThreadTop,\n replyMessage,\n replyMessageSender,\n isProtected: selectIsMessageProtected(global, message),\n isFocused,\n isForwarding,\n isChatWithSelf,\n isRepliesChat,\n isChannel,\n canReply,\n lastSyncTime,\n highlight,\n isSingleEmoji: Boolean(singleEmoji),\n animatedEmoji: singleEmoji ? selectAnimatedEmoji(global, singleEmoji) : undefined,\n isInSelectMode: selectIsInSelectMode(global),\n isSelected,\n isGroupSelected: (\n !!message.groupedId && !message.isInAlbum && selectIsDocumentGroupSelected(global, chatId, message.groupedId)\n ),\n threadId,\n isDownloading,\n isPinnedList: messageListType === 'pinned',\n canAutoLoadMedia: selectCanAutoLoadMedia(global, message),\n canAutoPlayMedia: selectCanAutoPlayMedia(global, message),\n autoLoadFileMaxSizeMb: global.settings.byKey.autoLoadFileMaxSizeMb,\n shouldLoopStickers: selectShouldLoopStickers(global),\n threadInfo: actualThreadInfo,\n ...(isOutgoing && { outgoingStatus: selectOutgoingStatus(global, message, messageListType === 'scheduled') }),\n ...(typeof uploadProgress === 'number' && { uploadProgress }),\n ...(isFocused && { focusDirection, noFocusHighlight, isResizingContainer }),\n };\n },\n)(Message));\n","import { RefObject } from 'react';\nimport React, { useEffect } from '../../../../lib/teact/teact';\nimport { getDispatch } from '../../../../lib/teact/teactn';\n\nimport { IS_ANDROID, IS_TOUCH_ENV } from '../../../../util/environment';\nimport windowSize from '../../../../util/windowSize';\nimport { captureEvents, SwipeDirection } from '../../../../util/captureEvents';\nimport useFlag from '../../../../hooks/useFlag';\nimport { preventMessageInputBlur } from '../../helpers/preventMessageInputBlur';\nimport stopEvent from '../../../../util/stopEvent';\n\nconst ANDROID_KEYBOARD_HIDE_DELAY_MS = 350;\nconst SWIPE_ANIMATION_DURATION = 150;\n\nexport default function useOuterHandlers(\n selectMessage: (e?: React.MouseEvent, groupedId?: string) => void,\n containerRef: RefObject,\n messageId: number,\n isAlbum: boolean,\n isInSelectMode: boolean,\n canReply: boolean,\n isProtected: boolean,\n onContextMenu: (e: React.MouseEvent) => void,\n handleBeforeContextMenu: (e: React.MouseEvent) => void,\n) {\n const { setReplyingToId } = getDispatch();\n\n const [isSwiped, markSwiped, unmarkSwiped] = useFlag();\n\n function handleMouseDown(e: React.MouseEvent) {\n preventMessageInputBlur(e);\n handleBeforeContextMenu(e);\n }\n\n function handleClick(e: React.MouseEvent) {\n if (isInSelectMode) {\n selectMessage(e);\n } else if (IS_ANDROID) {\n const target = e.target as HTMLDivElement;\n if (!target.classList.contains('text-content') && !target.classList.contains('Message')) {\n return;\n }\n\n if (windowSize.getIsKeyboardVisible()) {\n setTimeout(() => {\n onContextMenu(e);\n }, ANDROID_KEYBOARD_HIDE_DELAY_MS);\n } else {\n onContextMenu(e);\n }\n }\n }\n\n function handleContextMenu(e: React.MouseEvent) {\n if (IS_ANDROID) {\n if ((e.target as HTMLElement).matches('a[href]')) {\n return;\n }\n\n e.preventDefault();\n selectMessage();\n } else {\n onContextMenu(e);\n }\n }\n\n function handleContainerDoubleClick() {\n setReplyingToId({ messageId });\n }\n\n function stopPropagation(e: React.MouseEvent) {\n e.stopPropagation();\n }\n\n useEffect(() => {\n if (!IS_TOUCH_ENV || isInSelectMode || !canReply) {\n return undefined;\n }\n\n let startedAt: number | undefined;\n return captureEvents(containerRef.current!, {\n selectorToPreventScroll: '.MessageList',\n onSwipe: ((e, direction) => {\n if (direction === SwipeDirection.Left) {\n if (!startedAt) {\n startedAt = Date.now();\n }\n\n markSwiped();\n\n return true;\n }\n\n return false;\n }),\n onRelease: () => {\n if (!startedAt) {\n return;\n }\n\n setReplyingToId({ messageId });\n\n setTimeout(unmarkSwiped, Math.max(0, SWIPE_ANIMATION_DURATION - (Date.now() - startedAt)));\n startedAt = undefined;\n },\n });\n }, [containerRef, isInSelectMode, messageId, setReplyingToId, markSwiped, unmarkSwiped, canReply]);\n\n return {\n handleMouseDown: !isInSelectMode ? handleMouseDown : undefined,\n handleClick,\n handleContextMenu: !isInSelectMode ? handleContextMenu : (isProtected ? stopEvent : undefined),\n handleDoubleClick: !isInSelectMode ? handleContainerDoubleClick : undefined,\n handleContentDoubleClick: !IS_TOUCH_ENV ? stopPropagation : undefined,\n isSwiped,\n };\n}\n","import React, { useCallback } from '../../../../lib/teact/teact';\nimport { getDispatch } from '../../../../lib/teact/teactn';\n\nimport { isUserId } from '../../../../modules/helpers';\nimport { IAlbum, MediaViewerOrigin } from '../../../../types';\nimport {\n ApiChat, ApiMessage, ApiUser, MAIN_THREAD_ID,\n} from '../../../../api/types';\nimport { LangFn } from '../../../../hooks/useLang';\n\nexport default function useInnerHandlers(\n lang: LangFn,\n selectMessage: (e: React.MouseEvent, groupedId?: string) => void,\n message: ApiMessage,\n chatId: string,\n threadId: number,\n isInDocumentGroup: boolean,\n asForwarded?: boolean,\n isScheduled?: boolean,\n isChatWithRepliesBot?: boolean,\n album?: IAlbum,\n avatarPeer?: ApiUser | ApiChat,\n senderPeer?: ApiUser | ApiChat,\n botSender?: ApiUser,\n) {\n const {\n openUserInfo, openChat, showNotification, focusMessage, openMediaViewer, openAudioPlayer,\n markMessagesRead, cancelSendingMessage, sendPollVote, openForwardMenu, focusMessageInComments,\n } = getDispatch();\n\n const {\n id: messageId, forwardInfo, replyToMessageId, replyToChatId, replyToTopMessageId, groupedId,\n } = message;\n\n const handleAvatarClick = useCallback(() => {\n if (!avatarPeer) {\n return;\n }\n\n if (isUserId(avatarPeer.id)) {\n openUserInfo({ id: avatarPeer.id });\n } else {\n openChat({ id: avatarPeer.id });\n }\n }, [avatarPeer, openUserInfo, openChat]);\n\n const handleSenderClick = useCallback(() => {\n if (!senderPeer) {\n showNotification({ message: lang('HidAccount') });\n\n return;\n }\n\n if (asForwarded && forwardInfo?.channelPostId) {\n focusMessage({ chatId: senderPeer.id, messageId: forwardInfo.channelPostId });\n } else if (isUserId(senderPeer.id)) {\n openUserInfo({ id: senderPeer.id });\n } else {\n openChat({ id: senderPeer.id });\n }\n }, [\n asForwarded, focusMessage, forwardInfo, lang, openChat, openUserInfo, senderPeer, showNotification,\n ]);\n\n const handleViaBotClick = useCallback(() => {\n if (!botSender) {\n return;\n }\n\n openUserInfo({ id: botSender.id });\n }, [botSender, openUserInfo]);\n\n const handleReplyClick = useCallback((): void => {\n focusMessage({\n chatId: isChatWithRepliesBot && replyToChatId ? replyToChatId : chatId,\n threadId,\n messageId: replyToMessageId,\n replyMessageId: isChatWithRepliesBot && replyToChatId ? undefined : messageId,\n });\n }, [focusMessage, isChatWithRepliesBot, replyToChatId, chatId, threadId, replyToMessageId, messageId]);\n\n const handleMediaClick = useCallback((): void => {\n openMediaViewer({\n chatId, threadId, messageId, origin: isScheduled ? MediaViewerOrigin.ScheduledInline : MediaViewerOrigin.Inline,\n });\n }, [chatId, threadId, messageId, openMediaViewer, isScheduled]);\n\n const handleAudioPlay = useCallback((): void => {\n openAudioPlayer({ chatId, messageId });\n }, [chatId, messageId, openAudioPlayer]);\n\n const handleAlbumMediaClick = useCallback((albumMessageId: number): void => {\n openMediaViewer({\n chatId,\n threadId,\n messageId: albumMessageId,\n origin: isScheduled ? MediaViewerOrigin.ScheduledAlbum : MediaViewerOrigin.Album,\n });\n }, [chatId, threadId, openMediaViewer, isScheduled]);\n\n const handleReadMedia = useCallback((): void => {\n markMessagesRead({ messageIds: [messageId] });\n }, [messageId, markMessagesRead]);\n\n const handleCancelUpload = useCallback(() => {\n cancelSendingMessage({ chatId, messageId });\n }, [cancelSendingMessage, chatId, messageId]);\n\n const handleVoteSend = useCallback((options: string[]) => {\n sendPollVote({ chatId, messageId, options });\n }, [chatId, messageId, sendPollVote]);\n\n const handleGroupForward = useCallback(() => {\n openForwardMenu({ fromChatId: chatId, groupedId });\n }, [openForwardMenu, chatId, groupedId]);\n\n const handleForward = useCallback(() => {\n if (album && album.messages) {\n const messageIds = album.messages.map(({ id }) => id);\n openForwardMenu({ fromChatId: chatId, messageIds });\n } else {\n openForwardMenu({ fromChatId: chatId, messageIds: [messageId] });\n }\n }, [album, openForwardMenu, chatId, messageId]);\n\n const handleFocus = useCallback(() => {\n focusMessage({\n chatId, threadId: MAIN_THREAD_ID, messageId,\n });\n }, [focusMessage, chatId, messageId]);\n\n const handleFocusForwarded = useCallback(() => {\n if (isInDocumentGroup) {\n focusMessage({\n chatId: forwardInfo!.fromChatId, groupedId, groupedChatId: chatId,\n });\n return;\n }\n\n if (isChatWithRepliesBot && replyToChatId) {\n focusMessageInComments({\n chatId: replyToChatId,\n threadId: replyToTopMessageId,\n messageId: forwardInfo!.fromMessageId,\n });\n } else {\n focusMessage({\n chatId: forwardInfo!.fromChatId, messageId: forwardInfo!.fromMessageId,\n });\n }\n }, [\n isInDocumentGroup, isChatWithRepliesBot, replyToChatId, focusMessage, forwardInfo, groupedId, chatId,\n focusMessageInComments, replyToTopMessageId,\n ]);\n\n const selectWithGroupedId = useCallback((e: React.MouseEvent) => {\n e.stopPropagation();\n\n selectMessage(e, groupedId);\n }, [selectMessage, groupedId]);\n\n return {\n handleAvatarClick,\n handleSenderClick,\n handleViaBotClick,\n handleReplyClick,\n handleMediaClick,\n handleAudioPlay,\n handleAlbumMediaClick,\n handleMetaClick: selectWithGroupedId,\n handleReadMedia,\n handleCancelUpload,\n handleVoteSend,\n handleGroupForward,\n handleForward,\n handleFocus,\n handleFocusForwarded,\n handleDocumentGroupSelectAll: selectWithGroupedId,\n };\n}\n","import { RefObject } from 'react';\nimport React, {\n FC, memo, useEffect, useRef,\n} from '../../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiChat, ApiSponsoredMessage, ApiUser } from '../../../api/types';\n\nimport { renderTextWithEntities } from '../../common/helpers/renderMessageText';\nimport { selectChat, selectSponsoredMessage, selectUser } from '../../../modules/selectors';\nimport { getChatTitle, getUserFullName } from '../../../modules/helpers';\nimport renderText from '../../common/helpers/renderText';\nimport useLang from '../../../hooks/useLang';\nimport { useIntersectionObserver } from '../../../hooks/useIntersectionObserver';\n\nimport Button from '../../ui/Button';\n\nimport './SponsoredMessage.scss';\n\ntype OwnProps = {\n chatId: string;\n containerRef: RefObject;\n};\n\ntype StateProps = {\n message?: ApiSponsoredMessage;\n bot?: ApiUser;\n channel?: ApiChat;\n};\n\nconst INTERSECTION_DEBOUNCE_MS = 200;\n\nconst SponsoredMessage: FC = ({\n chatId,\n message,\n containerRef,\n bot,\n channel,\n}) => {\n const {\n viewSponsoredMessage,\n openChat,\n openChatByInvite,\n startBot,\n focusMessage,\n } = getDispatch();\n const lang = useLang();\n // eslint-disable-next-line no-null/no-null\n const contentRef = useRef(null);\n const shouldObserve = Boolean(message);\n const {\n observe: observeIntersection,\n } = useIntersectionObserver({\n rootRef: containerRef,\n debounceMs: INTERSECTION_DEBOUNCE_MS,\n threshold: 1,\n });\n\n useEffect(() => {\n return shouldObserve ? observeIntersection(contentRef.current!, (target) => {\n if (target.isIntersecting) {\n viewSponsoredMessage({ chatId });\n }\n }) : undefined;\n }, [chatId, shouldObserve, observeIntersection, viewSponsoredMessage]);\n\n if (!message) {\n return undefined;\n }\n\n const handleClick = () => {\n if (message.chatInviteHash) {\n openChatByInvite({ hash: message.chatInviteHash });\n } else if (message.channelPostId) {\n focusMessage({ chatId: message.chatId, messageId: message.channelPostId });\n } else {\n openChat({ id: message.chatId });\n\n if (message.startParam) {\n startBot({\n botId: message.chatId,\n param: message.startParam,\n });\n }\n }\n };\n\n return (\n
\n
\n
\n
\n {bot && renderText(getUserFullName(bot) || '')}\n {channel && renderText(message.chatInviteTitle || getChatTitle(lang, channel, bot) || '')}\n
\n\n

\n \n {renderTextWithEntities(message.text.text, message.text.entities)}\n \n\n \n {lang('SponsoredMessage')}\n \n

\n\n \n
\n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { chatId }): StateProps => {\n const message = selectSponsoredMessage(global, chatId);\n const { chatId: fromChatId, isBot } = message || {};\n\n return {\n message,\n bot: fromChatId && isBot ? selectUser(global, fromChatId) : undefined,\n channel: !isBot && fromChatId ? selectChat(global, fromChatId) : undefined,\n };\n },\n)(SponsoredMessage));\n","import { RefObject } from 'react';\nimport React, { FC, memo } from '../../lib/teact/teact';\n\nimport { MessageListType } from '../../global/types';\n\nimport { SCHEDULED_WHEN_ONLINE } from '../../config';\nimport buildClassName from '../../util/buildClassName';\nimport { compact, flatten } from '../../util/iteratees';\nimport { formatHumanDate } from '../../util/dateFormat';\nimport { getMessageOriginalId, isActionMessage, isOwnMessage } from '../../modules/helpers';\nimport useLang from '../../hooks/useLang';\nimport { isAlbum, MessageDateGroup } from './helpers/groupMessages';\nimport { preventMessageInputBlur } from './helpers/preventMessageInputBlur';\nimport useScrollHooks from './hooks/useScrollHooks';\nimport useMessageObservers from './hooks/useMessageObservers';\n\nimport Message from './message/Message';\nimport SponsoredMessage from './message/SponsoredMessage';\nimport ActionMessage from './ActionMessage';\nimport { getDispatch } from '../../lib/teact/teactn';\n\ninterface OwnProps {\n chatId: string;\n messageIds: number[];\n messageGroups: MessageDateGroup[];\n isViewportNewest: boolean;\n isUnread: boolean;\n withUsers: boolean;\n noAvatars: boolean;\n containerRef: RefObject;\n anchorIdRef: { current: string | undefined };\n memoUnreadDividerBeforeIdRef: { current: number | undefined };\n memoFirstUnreadIdRef: { current: number | undefined };\n threadId: number;\n type: MessageListType;\n isReady: boolean;\n isScrollingRef: { current: boolean | undefined };\n isScrollPatchNeededRef: { current: boolean | undefined };\n threadTopMessageId: number | undefined;\n hasLinkedChat: boolean | undefined;\n isSchedule: boolean;\n noAppearanceAnimation: boolean;\n onFabToggle: AnyToVoidFunction;\n onNotchToggle: AnyToVoidFunction;\n}\n\nconst UNREAD_DIVIDER_CLASS = 'unread-divider';\n\nconst MessageListContent: FC = ({\n chatId,\n messageIds,\n messageGroups,\n isViewportNewest,\n isUnread,\n withUsers,\n noAvatars,\n containerRef,\n anchorIdRef,\n memoUnreadDividerBeforeIdRef,\n memoFirstUnreadIdRef,\n threadId,\n type,\n isReady,\n isScrollingRef,\n isScrollPatchNeededRef,\n threadTopMessageId,\n hasLinkedChat,\n isSchedule,\n noAppearanceAnimation,\n onFabToggle,\n onNotchToggle,\n}) => {\n const { openHistoryCalendar } = getDispatch();\n\n const {\n observeIntersectionForMedia,\n observeIntersectionForReading,\n observeIntersectionForAnimatedStickers,\n } = useMessageObservers(type, containerRef, memoFirstUnreadIdRef);\n\n const {\n backwardsTriggerRef,\n forwardsTriggerRef,\n fabTriggerRef,\n } = useScrollHooks(\n type,\n containerRef,\n messageIds,\n isViewportNewest,\n isUnread,\n onFabToggle,\n onNotchToggle,\n isReady,\n isScrollingRef,\n isScrollPatchNeededRef,\n );\n\n const lang = useLang();\n\n const unreadDivider = (\n
\n {lang('UnreadMessages')}\n
\n );\n\n const messageCountToAnimate = noAppearanceAnimation ? 0 : messageGroups.reduce((acc, messageGroup) => {\n return acc + flatten(messageGroup.senderGroups).length;\n }, 0);\n let appearanceIndex = 0;\n\n const dateGroups = messageGroups.map((\n dateGroup: MessageDateGroup,\n dateGroupIndex: number,\n dateGroupsArray: MessageDateGroup[],\n ) => {\n const senderGroups = dateGroup.senderGroups.map((\n senderGroup,\n senderGroupIndex,\n senderGroupsArray,\n ) => {\n if (senderGroup.length === 1 && !isAlbum(senderGroup[0]) && isActionMessage(senderGroup[0])) {\n const message = senderGroup[0];\n const isLastInList = (\n senderGroupIndex === senderGroupsArray.length - 1\n && dateGroupIndex === dateGroupsArray.length - 1\n );\n\n return compact([\n message.id === memoUnreadDividerBeforeIdRef.current && unreadDivider,\n ,\n ]);\n }\n\n let currentDocumentGroupId: string | undefined;\n\n return flatten(senderGroup.map((\n messageOrAlbum,\n messageIndex,\n ) => {\n const message = isAlbum(messageOrAlbum) ? messageOrAlbum.mainMessage : messageOrAlbum;\n const album = isAlbum(messageOrAlbum) ? messageOrAlbum : undefined;\n const isOwn = isOwnMessage(message);\n const isMessageAlbum = isAlbum(messageOrAlbum);\n const nextMessage = senderGroup[messageIndex + 1];\n\n if (message.previousLocalId && anchorIdRef.current === `message${message.previousLocalId}`) {\n anchorIdRef.current = `message${message.id}`;\n }\n\n const documentGroupId = !isMessageAlbum && message.groupedId ? message.groupedId : undefined;\n const nextDocumentGroupId = nextMessage && !isAlbum(nextMessage) ? nextMessage.groupedId : undefined;\n\n const position = {\n isFirstInGroup: messageIndex === 0,\n isLastInGroup: messageIndex === senderGroup.length - 1,\n isFirstInDocumentGroup: Boolean(documentGroupId && documentGroupId !== currentDocumentGroupId),\n isLastInDocumentGroup: Boolean(documentGroupId && documentGroupId !== nextDocumentGroupId),\n isLastInList: (\n messageIndex === senderGroup.length - 1\n && senderGroupIndex === senderGroupsArray.length - 1\n && dateGroupIndex === dateGroupsArray.length - 1\n ),\n };\n\n currentDocumentGroupId = documentGroupId;\n\n const originalId = getMessageOriginalId(message);\n // Scheduled messages can have local IDs in the middle of the list,\n // and keys should be ordered, so we prefix it with a date.\n // However, this may lead to issues if server date is not synchronized with the local one.\n const key = type !== 'scheduled' ? originalId : `${message.date}_${originalId}`;\n\n return compact([\n message.id === memoUnreadDividerBeforeIdRef.current && unreadDivider,\n ,\n message.id === threadTopMessageId && (\n
\n {lang('DiscussionStarted')}\n
\n ),\n ]);\n }));\n });\n\n return (\n \n openHistoryCalendar({ selectedAt: dateGroup.datetime }) : undefined}\n >\n \n {isSchedule && dateGroup.originalDate === SCHEDULED_WHEN_ONLINE && (\n lang('MessageScheduledUntilOnline')\n )}\n {isSchedule && dateGroup.originalDate !== SCHEDULED_WHEN_ONLINE && (\n lang('MessageScheduledOn', formatHumanDate(lang, dateGroup.datetime, undefined, true))\n )}\n {!isSchedule && formatHumanDate(lang, dateGroup.datetime)}\n \n \n {flatten(senderGroups)}\n \n );\n });\n\n return (\n
\n
\n {flatten(dateGroups)}\n {isViewportNewest && }\n \n \n
\n );\n};\n\nexport default memo(MessageListContent);\n","import { RefObject } from 'react';\nimport { getDispatch } from '../../../lib/teact/teactn';\nimport { useMemo, useRef } from '../../../lib/teact/teact';\n\nimport { LoadMoreDirection } from '../../../types';\nimport { MessageListType } from '../../../global/types';\n\nimport { LOCAL_MESSAGE_ID_BASE, MESSAGE_LIST_SLICE } from '../../../config';\nimport { IS_SCROLL_PATCH_NEEDED, MESSAGE_LIST_SENSITIVE_AREA } from '../../../util/environment';\nimport { debounce } from '../../../util/schedulers';\nimport { useIntersectionObserver, useOnIntersect } from '../../../hooks/useIntersectionObserver';\nimport useOnChange from '../../../hooks/useOnChange';\n\nconst FAB_THRESHOLD = 50;\nconst NOTCH_THRESHOLD = 1; // Notch has zero height so we at least need a 1px margin to intersect\nconst TOOLS_FREEZE_TIMEOUT = 250; // Approximate message sending animation duration\n\nexport default function useScrollHooks(\n type: MessageListType,\n containerRef: RefObject,\n messageIds: number[],\n isViewportNewest: boolean,\n isUnread: boolean,\n onFabToggle: AnyToVoidFunction,\n onNotchToggle: AnyToVoidFunction,\n isReady: boolean,\n isScrollingRef: { current: boolean | undefined },\n isScrollPatchNeededRef: { current: boolean | undefined },\n) {\n const { loadViewportMessages } = getDispatch();\n\n const [loadMoreBackwards, loadMoreForwards] = useMemo(\n () => (type === 'thread' ? [\n debounce(() => loadViewportMessages({ direction: LoadMoreDirection.Backwards }), 1000, true, false),\n debounce(() => loadViewportMessages({ direction: LoadMoreDirection.Forwards }), 1000, true, false),\n ] : []),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [loadViewportMessages, messageIds],\n );\n\n // eslint-disable-next-line no-null/no-null\n const backwardsTriggerRef = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const forwardsTriggerRef = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const fabTriggerRef = useRef(null);\n\n function toggleScrollTools() {\n if (!isReady) return;\n\n if (!messageIds || !messageIds.length) {\n onFabToggle(false);\n onNotchToggle(false);\n return;\n }\n\n if (!isViewportNewest) {\n onFabToggle(true);\n onNotchToggle(true);\n return;\n }\n\n const { offsetHeight, scrollHeight, scrollTop } = containerRef.current!;\n const scrollBottom = Math.round(scrollHeight - scrollTop - offsetHeight);\n const isNearBottom = scrollBottom <= FAB_THRESHOLD;\n const isAtBottom = scrollBottom <= NOTCH_THRESHOLD;\n\n onFabToggle(isUnread ? !isAtBottom : !isNearBottom);\n onNotchToggle(!isAtBottom);\n }\n\n const {\n observe: observeIntersection,\n } = useIntersectionObserver({\n rootRef: containerRef,\n margin: MESSAGE_LIST_SENSITIVE_AREA,\n }, (entries) => {\n if (!loadMoreForwards || !loadMoreBackwards) {\n return;\n }\n\n // Loading history while sending a message can return the same message and cause ambiguity\n const isFirstMessageLocal = messageIds[0] >= LOCAL_MESSAGE_ID_BASE;\n if (isFirstMessageLocal) {\n return;\n }\n\n const triggerEntry = entries.find(({ isIntersecting }) => isIntersecting);\n if (!triggerEntry) {\n return;\n }\n\n const { target } = triggerEntry;\n\n if (target.className === 'backwards-trigger') {\n if (\n IS_SCROLL_PATCH_NEEDED && isScrollingRef.current && messageIds.length <= MESSAGE_LIST_SLICE\n ) {\n isScrollPatchNeededRef.current = true;\n }\n\n loadMoreBackwards();\n } else if (target.className === 'forwards-trigger') {\n loadMoreForwards();\n }\n });\n\n useOnIntersect(backwardsTriggerRef, observeIntersection);\n useOnIntersect(forwardsTriggerRef, observeIntersection);\n\n const {\n observe: observeIntersectionForFab,\n freeze: freezeForFab,\n unfreeze: unfreezeForFab,\n } = useIntersectionObserver({\n rootRef: containerRef,\n margin: FAB_THRESHOLD * 2,\n }, toggleScrollTools);\n\n useOnIntersect(fabTriggerRef, observeIntersectionForFab);\n\n const {\n observe: observeIntersectionForNotch,\n freeze: freezeForNotch,\n unfreeze: unfreezeForNotch,\n } = useIntersectionObserver({\n rootRef: containerRef,\n margin: NOTCH_THRESHOLD,\n }, toggleScrollTools);\n\n useOnIntersect(fabTriggerRef, observeIntersectionForNotch);\n\n useOnChange(() => {\n if (isReady) {\n toggleScrollTools();\n }\n }, [isReady]);\n\n // Workaround for FAB and notch flickering with tall incoming message\n useOnChange(() => {\n freezeForFab();\n freezeForNotch();\n\n setTimeout(() => {\n unfreezeForNotch();\n unfreezeForFab();\n }, TOOLS_FREEZE_TIMEOUT);\n }, [messageIds]);\n\n return { backwardsTriggerRef, forwardsTriggerRef, fabTriggerRef };\n}\n","import React, {\n FC, memo, useCallback, useEffect, useRef,\n} from '../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiSticker, ApiUpdateConnectionStateType } from '../../api/types';\n\nimport { selectChat } from '../../modules/selectors';\nimport { useIntersectionObserver } from '../../hooks/useIntersectionObserver';\nimport useLang from '../../hooks/useLang';\nimport { getUserIdDividend } from '../../modules/helpers';\n\nimport StickerButton from '../common/StickerButton';\n\nimport './ContactGreeting.scss';\n\ntype OwnProps = {\n userId: string;\n};\n\ntype StateProps = {\n sticker?: ApiSticker;\n lastUnreadMessageId?: number;\n connectionState?: ApiUpdateConnectionStateType;\n};\n\nconst INTERSECTION_DEBOUNCE_MS = 200;\n\nconst ContactGreeting: FC = ({\n sticker,\n connectionState,\n lastUnreadMessageId,\n}) => {\n const {\n loadGreetingStickers,\n sendMessage,\n markMessageListRead,\n } = getDispatch();\n\n const lang = useLang();\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef(null);\n const {\n observe: observeIntersection,\n } = useIntersectionObserver({\n rootRef: containerRef,\n debounceMs: INTERSECTION_DEBOUNCE_MS,\n });\n useEffect(() => {\n if (sticker || connectionState !== 'connectionStateReady') {\n return;\n }\n\n loadGreetingStickers();\n }, [connectionState, loadGreetingStickers, sticker]);\n\n useEffect(() => {\n if (connectionState === 'connectionStateReady' && lastUnreadMessageId) {\n markMessageListRead({ maxId: lastUnreadMessageId });\n }\n }, [connectionState, markMessageListRead, lastUnreadMessageId]);\n\n const handleStickerSelect = useCallback((selectedSticker: ApiSticker) => {\n selectedSticker = {\n ...selectedSticker,\n isPreloadedGlobally: true,\n };\n sendMessage({ sticker: selectedSticker });\n }, [sendMessage]);\n\n return (\n
\n
\n

{lang('Conversation.EmptyPlaceholder')}

\n

{lang('Conversation.GreetingText')}

\n\n
\n {sticker && (\n \n )}\n
\n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { userId }): StateProps => {\n const { stickers } = global.stickers.greeting;\n const dividend = getUserIdDividend(userId) + getUserIdDividend(global.currentUserId!);\n const sticker = stickers?.length ? stickers[dividend % stickers.length] : undefined;\n const chat = selectChat(global, userId);\n if (!chat) {\n return {};\n }\n\n return {\n sticker,\n lastUnreadMessageId: chat.lastMessage && chat.lastMessage.id !== chat.lastReadInboxMessageId\n ? chat.lastMessage.id\n : undefined,\n connectionState: global.connectionState,\n };\n },\n)(ContactGreeting));\n","import React, { FC, memo } from '../../lib/teact/teact';\n\nimport { MessageListType } from '../../global/types';\n\nimport useLang, { LangFn } from '../../hooks/useLang';\n\nimport './NoMessages.scss';\n\ntype OwnProps = {\n chatId: string;\n isChatWithSelf?: boolean;\n type: MessageListType;\n isGroupChatJustCreated?: boolean;\n};\n\nconst NoMessages: FC = ({\n isChatWithSelf, type, isGroupChatJustCreated,\n}) => {\n const lang = useLang();\n\n if (type === 'scheduled') {\n return renderScheduled(lang);\n }\n\n if (isChatWithSelf) {\n return renderSavedMessages(lang);\n }\n\n if (isGroupChatJustCreated) {\n return renderGroup(lang);\n }\n\n return (\n
{lang('NoMessages')}
\n );\n};\n\nfunction renderScheduled(lang: LangFn) {\n return (\n
{lang('ScheduledMessages.EmptyPlaceholder')}
\n );\n}\n\nfunction renderSavedMessages(lang: LangFn) {\n return (\n
\n
\n \n

{lang('Conversation.CloudStorageInfo.Title')}

\n
    \n
  • {lang('Conversation.ClousStorageInfo.Description1')}
  • \n
  • {lang('Conversation.ClousStorageInfo.Description2')}
  • \n
  • {lang('Conversation.ClousStorageInfo.Description3')}
  • \n
  • {lang('Conversation.ClousStorageInfo.Description4')}
  • \n
\n
\n
\n );\n}\n\nfunction renderGroup(lang: LangFn) {\n return (\n
\n
\n

{lang('EmptyGroupInfo.Title')}

\n

{lang('EmptyGroupInfo.Subtitle')}

\n
    \n
  • {lang('EmptyGroupInfo.Line1')}
  • \n
  • {lang('EmptyGroupInfo.Line2')}
  • \n
  • {lang('EmptyGroupInfo.Line3')}
  • \n
  • {lang('EmptyGroupInfo.Line4')}
  • \n
\n
\n
\n );\n}\n\nexport default memo(NoMessages);\n","import React, {\n FC, memo, useCallback, useEffect, useMemo, useRef, useState,\n} from '../../lib/teact/teact';\nimport { getDispatch, getGlobal, withGlobal } from '../../lib/teact/teactn';\n\nimport {\n ApiMessage, ApiRestrictionReason, MAIN_THREAD_ID,\n} from '../../api/types';\nimport { MessageListType } from '../../global/types';\nimport { LoadMoreDirection } from '../../types';\n\nimport { ANIMATION_END_DELAY, LOCAL_MESSAGE_ID_BASE, MESSAGE_LIST_SLICE } from '../../config';\nimport {\n selectChatMessages,\n selectIsViewportNewest,\n selectFirstUnreadId,\n selectFocusedMessageId,\n selectChat,\n selectIsInSelectMode,\n selectIsChatWithSelf,\n selectChatBot,\n selectIsChatBotNotStarted,\n selectScrollOffset,\n selectThreadTopMessageId,\n selectFirstMessageId,\n selectScheduledMessages,\n selectCurrentMessageIds,\n} from '../../modules/selectors';\nimport {\n isChatChannel,\n isUserId,\n isChatWithRepliesBot,\n isChatGroup,\n} from '../../modules/helpers';\nimport { orderBy } from '../../util/iteratees';\nimport { fastRaf, debounce, onTickEnd } from '../../util/schedulers';\nimport useLayoutEffectWithPrevDeps from '../../hooks/useLayoutEffectWithPrevDeps';\nimport useEffectWithPrevDeps from '../../hooks/useEffectWithPrevDeps';\nimport buildClassName from '../../util/buildClassName';\nimport { groupMessages } from './helpers/groupMessages';\nimport { preventMessageInputBlur } from './helpers/preventMessageInputBlur';\nimport useOnChange from '../../hooks/useOnChange';\nimport useStickyDates from './hooks/useStickyDates';\nimport { dispatchHeavyAnimationEvent } from '../../hooks/useHeavyAnimationCheck';\nimport resetScroll, { patchChromiumScroll } from '../../util/resetScroll';\nimport fastSmoothScroll, { isAnimatingScroll } from '../../util/fastSmoothScroll';\nimport renderText from '../common/helpers/renderText';\nimport useLang from '../../hooks/useLang';\nimport useWindowSize from '../../hooks/useWindowSize';\n\nimport Loading from '../ui/Loading';\nimport MessageListContent from './MessageListContent';\nimport ContactGreeting from './ContactGreeting';\nimport NoMessages from './NoMessages';\n\nimport './MessageList.scss';\n\ntype OwnProps = {\n chatId: string;\n threadId: number;\n type: MessageListType;\n canPost: boolean;\n isReady: boolean;\n onFabToggle: (shouldShow: boolean) => void;\n onNotchToggle: (shouldShow: boolean) => void;\n hasTools?: boolean;\n withBottomShift?: boolean;\n};\n\ntype StateProps = {\n isChatLoaded?: boolean;\n isChannelChat?: boolean;\n isGroupChat?: boolean;\n isChatWithSelf?: boolean;\n isRepliesChat?: boolean;\n isCreator?: boolean;\n isBot?: boolean;\n messageIds?: number[];\n messagesById?: Record;\n firstUnreadId?: number;\n isViewportNewest?: boolean;\n isRestricted?: boolean;\n restrictionReason?: ApiRestrictionReason;\n focusingId?: number;\n isSelectModeActive?: boolean;\n animationLevel?: number;\n lastMessage?: ApiMessage;\n botDescription?: string;\n threadTopMessageId?: number;\n threadFirstMessageId?: number;\n hasLinkedChat?: boolean;\n lastSyncTime?: number;\n};\n\nconst BOTTOM_THRESHOLD = 20;\nconst UNREAD_DIVIDER_TOP = 10;\nconst UNREAD_DIVIDER_TOP_WITH_TOOLS = 60;\nconst SCROLL_DEBOUNCE = 200;\nconst MESSAGE_ANIMATION_DURATION = 500;\nconst BOTTOM_FOCUS_MARGIN = 20;\nconst SELECT_MODE_ANIMATION_DURATION = 200;\nconst UNREAD_DIVIDER_CLASS = 'unread-divider';\n\nconst runDebouncedForScroll = debounce((cb) => cb(), SCROLL_DEBOUNCE, false);\n\nconst MessageList: FC = ({\n chatId,\n threadId,\n type,\n hasTools,\n onFabToggle,\n onNotchToggle,\n isChatLoaded,\n isChannelChat,\n isGroupChat,\n canPost,\n isReady,\n isChatWithSelf,\n isRepliesChat,\n isCreator,\n isBot,\n messageIds,\n messagesById,\n firstUnreadId,\n isViewportNewest,\n threadFirstMessageId,\n isRestricted,\n restrictionReason,\n focusingId,\n isSelectModeActive,\n lastMessage,\n botDescription,\n threadTopMessageId,\n hasLinkedChat,\n lastSyncTime,\n withBottomShift,\n}) => {\n const { loadViewportMessages, setScrollOffset, loadSponsoredMessages } = getDispatch();\n\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef(null);\n\n // We update local cached `scrollOffsetRef` when opening chat.\n // Then we update global version every second on scrolling.\n const scrollOffsetRef = useRef((type === 'thread' && selectScrollOffset(getGlobal(), chatId, threadId)) || 0);\n const anchorIdRef = useRef();\n const anchorTopRef = useRef();\n const listItemElementsRef = useRef();\n const memoFirstUnreadIdRef = useRef();\n const memoUnreadDividerBeforeIdRef = useRef();\n const memoFocusingIdRef = useRef();\n const isScrollTopJustUpdatedRef = useRef(false);\n const shouldAnimateAppearanceRef = useRef(Boolean(lastMessage));\n\n const [containerHeight, setContainerHeight] = useState();\n\n const areMessagesLoaded = Boolean(messageIds);\n\n useOnChange(() => {\n // We only need it first time when message list appears\n if (areMessagesLoaded) {\n onTickEnd(() => {\n shouldAnimateAppearanceRef.current = false;\n });\n }\n }, [areMessagesLoaded]);\n\n // Updated every time (to be used from intersection callback closure)\n useOnChange(() => {\n memoFirstUnreadIdRef.current = firstUnreadId;\n }, [firstUnreadId]);\n\n useOnChange(() => {\n if (isChannelChat && isReady && lastSyncTime) {\n loadSponsoredMessages({ chatId });\n }\n }, [chatId, isReady, isChannelChat, lastSyncTime]);\n\n // Updated only once when messages are loaded (as we want the unread divider to keep its position)\n useOnChange(() => {\n if (areMessagesLoaded) {\n memoUnreadDividerBeforeIdRef.current = memoFirstUnreadIdRef.current;\n }\n }, [areMessagesLoaded]);\n\n useOnChange(() => {\n memoFocusingIdRef.current = focusingId;\n }, [focusingId]);\n\n const messageGroups = useMemo(() => {\n if (!messageIds || !messagesById) {\n return undefined;\n }\n\n const viewportIds = threadTopMessageId && (!messageIds[0] || threadFirstMessageId === messageIds[0])\n ? [threadTopMessageId, ...messageIds]\n : messageIds;\n\n if (!viewportIds.length) {\n return undefined;\n }\n\n const listedMessages = viewportIds.map((id) => messagesById[id]).filter(Boolean);\n return groupMessages(orderBy(listedMessages, ['date', 'id']), memoUnreadDividerBeforeIdRef.current);\n }, [messageIds, messagesById, threadFirstMessageId, threadTopMessageId]);\n\n const loadMoreAround = useMemo(() => {\n if (type !== 'thread') {\n return undefined;\n }\n\n return debounce(() => loadViewportMessages({ direction: LoadMoreDirection.Around }), 1000, true, false);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [loadViewportMessages, messageIds]);\n\n const { isScrolled, updateStickyDates } = useStickyDates();\n\n const isScrollingRef = useRef();\n const isScrollPatchNeededRef = useRef();\n\n const handleScroll = useCallback(() => {\n if (isScrollTopJustUpdatedRef.current) {\n isScrollTopJustUpdatedRef.current = false;\n return;\n }\n\n isScrollingRef.current = true;\n\n const container = containerRef.current!;\n\n if (!memoFocusingIdRef.current) {\n updateStickyDates(container, hasTools);\n }\n\n runDebouncedForScroll(() => {\n isScrollingRef.current = false;\n\n fastRaf(() => {\n if (!container.parentElement) {\n return;\n }\n\n scrollOffsetRef.current = container.scrollHeight - container.scrollTop;\n\n if (type === 'thread') {\n setScrollOffset({ chatId, threadId, scrollOffset: scrollOffsetRef.current });\n }\n });\n });\n }, [updateStickyDates, hasTools, type, setScrollOffset, chatId, threadId]);\n\n // Container resize observer (caused by Composer reply/webpage panels)\n useEffect(() => {\n if (!('ResizeObserver' in window) || process.env.APP_ENV === 'perf') {\n return undefined;\n }\n\n const observer = new ResizeObserver(([entry]) => {\n // During animation\n if (!(entry.target as HTMLDivElement).offsetParent) {\n return;\n }\n\n setContainerHeight(entry.contentRect.height);\n });\n\n observer.observe(containerRef.current!);\n\n return () => {\n observer.disconnect();\n };\n }, []);\n\n // Memorize height for scroll animation\n const { height: windowHeight } = useWindowSize();\n\n useEffect(() => {\n if (isReady) {\n containerRef.current!.dataset.normalHeight = String(containerRef.current!.offsetHeight);\n }\n }, [windowHeight, isReady, canPost]);\n\n // Initial message loading\n useEffect(() => {\n if (!loadMoreAround || !isChatLoaded || isRestricted || focusingId) {\n return;\n }\n\n // Loading history while sending a message can return the same message and cause ambiguity\n const isLastMessageLocal = messageIds && messageIds[messageIds.length - 1] >= LOCAL_MESSAGE_ID_BASE;\n if (isLastMessageLocal) {\n return;\n }\n\n const container = containerRef.current!;\n\n if (!messageIds || (\n messageIds.length < MESSAGE_LIST_SLICE / 2\n && (container.firstElementChild as HTMLDivElement).clientHeight <= container.offsetHeight\n )) {\n loadMoreAround();\n }\n }, [isChatLoaded, messageIds, loadMoreAround, focusingId, isRestricted]);\n\n // Remember scroll position before repositioning it\n useOnChange(() => {\n if (!messageIds || !listItemElementsRef.current) {\n return;\n }\n\n const preservedItemElements = listItemElementsRef.current\n .filter((element) => messageIds.includes(Number(element.dataset.messageId)));\n\n // We avoid the very first item as it may be a partly-loaded album\n // and also because it may be removed when messages limit is reached\n const anchor = preservedItemElements[1] || preservedItemElements[0];\n if (!anchor) {\n return;\n }\n\n anchorIdRef.current = anchor.id;\n anchorTopRef.current = anchor.getBoundingClientRect().top;\n // This should match deps for `useLayoutEffectWithPrevDeps` below\n }, [messageIds, isViewportNewest, containerHeight, hasTools]);\n\n // Handles updated message list, takes care of scroll repositioning\n useLayoutEffectWithPrevDeps(([\n prevMessageIds, prevIsViewportNewest, prevContainerHeight,\n ]: [\n typeof messageIds, typeof isViewportNewest, typeof containerHeight,\n ]) => {\n const container = containerRef.current!;\n listItemElementsRef.current = Array.from(container.querySelectorAll('.message-list-item'));\n\n const hasLastMessageChanged = (\n messageIds && prevMessageIds && messageIds[messageIds.length - 1] !== prevMessageIds[prevMessageIds.length - 1]\n );\n const hasViewportShifted = (\n messageIds?.[0] !== prevMessageIds?.[0] && messageIds?.length === (MESSAGE_LIST_SLICE / 2 + 1)\n );\n const wasMessageAdded = hasLastMessageChanged && !hasViewportShifted;\n const isAlreadyFocusing = messageIds && memoFocusingIdRef.current === messageIds[messageIds.length - 1];\n\n // Add extra height when few messages to allow smooth scroll animation. Uses assumption that `parentElement`\n // is a Transition slide and its CSS class can not be reset in a declarative way.\n const shouldForceScroll = (\n isViewportNewest\n && wasMessageAdded\n && (messageIds && messageIds.length < MESSAGE_LIST_SLICE / 2)\n && !container.parentElement!.classList.contains('force-messages-scroll')\n && (container.firstElementChild as HTMLDivElement)!.clientHeight <= container.offsetHeight * 2\n );\n\n if (shouldForceScroll) {\n container.parentElement!.classList.add('force-messages-scroll');\n\n setTimeout(() => {\n if (container.parentElement) {\n container.parentElement.classList.remove('force-messages-scroll');\n }\n }, MESSAGE_ANIMATION_DURATION);\n }\n\n const { scrollTop, scrollHeight, offsetHeight } = container;\n const scrollOffset = scrollOffsetRef.current;\n const lastItemElement = listItemElementsRef.current[listItemElementsRef.current.length - 1];\n\n let bottomOffset = scrollOffset - (prevContainerHeight || offsetHeight);\n if (wasMessageAdded) {\n // If two new messages come at once (e.g. when bot responds) then the first message will update `scrollOffset`\n // right away (before animation) which creates inconsistency until the animation completes. To workaround that,\n // we calculate `isAtBottom` with a \"buffer\" of the latest message height (this is approximate).\n const lastItemHeight = lastItemElement ? lastItemElement.offsetHeight : 0;\n bottomOffset -= lastItemHeight;\n }\n const isAtBottom = isViewportNewest && prevIsViewportNewest && bottomOffset <= BOTTOM_THRESHOLD;\n\n let newScrollTop!: number;\n\n if (wasMessageAdded && isAtBottom && !isAlreadyFocusing) {\n if (lastItemElement) {\n fastRaf(() => {\n fastSmoothScroll(\n container,\n lastItemElement,\n 'end',\n BOTTOM_FOCUS_MARGIN,\n );\n });\n }\n\n newScrollTop = scrollHeight - offsetHeight;\n scrollOffsetRef.current = Math.max(Math.ceil(scrollHeight - newScrollTop), offsetHeight);\n\n // Scroll still needs to be restored after container resize\n if (!shouldForceScroll) {\n return;\n }\n }\n\n if (process.env.APP_ENV === 'perf') {\n // eslint-disable-next-line no-console\n console.time('scrollTop');\n }\n\n const isResized = prevContainerHeight !== undefined && prevContainerHeight !== containerHeight;\n const anchor = anchorIdRef.current && container.querySelector(`#${anchorIdRef.current}`);\n const unreadDivider = (\n !anchor\n && memoUnreadDividerBeforeIdRef.current\n && container.querySelector(`.${UNREAD_DIVIDER_CLASS}`)\n );\n\n if (isAtBottom && isResized) {\n if (isAnimatingScroll()) {\n return;\n }\n\n newScrollTop = scrollHeight - offsetHeight;\n } else if (anchor) {\n if (isScrollPatchNeededRef.current) {\n isScrollPatchNeededRef.current = false;\n patchChromiumScroll(container);\n }\n\n const newAnchorTop = anchor.getBoundingClientRect().top;\n newScrollTop = scrollTop + (newAnchorTop - (anchorTopRef.current || 0));\n } else if (unreadDivider) {\n newScrollTop = Math.min(\n unreadDivider.offsetTop - (hasTools ? UNREAD_DIVIDER_TOP_WITH_TOOLS : UNREAD_DIVIDER_TOP),\n scrollHeight - scrollOffset,\n );\n } else {\n newScrollTop = scrollHeight - scrollOffset;\n }\n\n resetScroll(container, Math.ceil(newScrollTop));\n\n if (!memoFocusingIdRef.current) {\n isScrollTopJustUpdatedRef.current = true;\n fastRaf(() => {\n isScrollTopJustUpdatedRef.current = false;\n });\n }\n\n scrollOffsetRef.current = Math.max(Math.ceil(scrollHeight - newScrollTop), offsetHeight);\n\n if (process.env.APP_ENV === 'perf') {\n // eslint-disable-next-line no-console\n console.timeEnd('scrollTop');\n }\n // This should match deps for `useOnChange` above\n }, [messageIds, isViewportNewest, containerHeight, hasTools]);\n\n useEffectWithPrevDeps(([prevIsSelectModeActive]) => {\n if (prevIsSelectModeActive !== undefined) {\n dispatchHeavyAnimationEvent(SELECT_MODE_ANIMATION_DURATION + ANIMATION_END_DELAY);\n }\n }, [isSelectModeActive]);\n\n const lang = useLang();\n\n const isPrivate = Boolean(chatId && isUserId(chatId));\n const withUsers = Boolean((!isPrivate && !isChannelChat) || isChatWithSelf || isRepliesChat);\n const noAvatars = Boolean(!withUsers || isChannelChat);\n const shouldRenderGreeting = isUserId(chatId) && !isChatWithSelf && !isBot\n && (\n (\n !messageGroups && !lastMessage && messageIds\n // Used to avoid flickering when deleting a greeting that has just been sent\n && (!listItemElementsRef.current || listItemElementsRef.current.length === 0)\n )\n || (messageIds?.length === 1 && messagesById?.[messageIds[0]]?.content.action?.type === 'contactSignUp')\n || (lastMessage?.content?.action?.type === 'contactSignUp')\n );\n\n const isGroupChatJustCreated = isGroupChat && isCreator\n && messageIds?.length === 1 && messagesById?.[messageIds[0]]?.content.action?.type === 'chatCreate';\n\n const className = buildClassName(\n 'MessageList custom-scroll',\n noAvatars && 'no-avatars',\n !canPost && 'no-composer',\n type === 'pinned' && 'type-pinned',\n withBottomShift && 'with-bottom-shift',\n isSelectModeActive && 'select-mode-active',\n isScrolled && 'scrolled',\n !isReady && 'is-animating',\n );\n\n return (\n \n {isRestricted ? (\n
\n \n {restrictionReason ? restrictionReason.text : `This is a private ${isChannelChat ? 'channel' : 'chat'}`}\n \n
\n ) : botDescription ? (\n
{renderText(lang(botDescription), ['br', 'emoji', 'links'])}
\n ) : shouldRenderGreeting ? (\n \n ) : messageIds && (!messageGroups || isGroupChatJustCreated) ? (\n \n ) : ((messageIds && messageGroups) || lastMessage) ? (\n \n ) : (\n \n )}\n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { chatId, threadId, type }): StateProps => {\n const chat = selectChat(global, chatId);\n if (!chat) {\n return {};\n }\n\n const messageIds = selectCurrentMessageIds(global, chatId, threadId, type);\n const messagesById = type === 'scheduled'\n ? selectScheduledMessages(global, chatId)\n : selectChatMessages(global, chatId);\n const threadTopMessageId = selectThreadTopMessageId(global, chatId, threadId);\n\n if (\n threadId !== MAIN_THREAD_ID\n && !(messagesById && threadTopMessageId && messagesById[threadTopMessageId])\n ) {\n return {};\n }\n\n const { isRestricted, restrictionReason, lastMessage } = chat;\n const focusingId = selectFocusedMessageId(global, chatId);\n\n const withLastMessageWhenPreloading = (\n threadId === MAIN_THREAD_ID\n && !messageIds && !chat.unreadCount && !focusingId && lastMessage && !lastMessage.groupedId\n );\n\n const chatBot = selectChatBot(global, chatId)!;\n let botDescription: string | undefined;\n if (selectIsChatBotNotStarted(global, chatId)) {\n if (chatBot.fullInfo) {\n botDescription = chatBot.fullInfo.botDescription || 'NoMessages';\n } else {\n botDescription = 'Updating bot info...';\n }\n }\n\n return {\n isChatLoaded: true,\n isRestricted,\n restrictionReason,\n isChannelChat: isChatChannel(chat),\n isGroupChat: isChatGroup(chat),\n isCreator: chat.isCreator,\n isChatWithSelf: selectIsChatWithSelf(global, chatId),\n isRepliesChat: isChatWithRepliesBot(chatId),\n isBot: Boolean(chatBot),\n messageIds,\n messagesById,\n firstUnreadId: selectFirstUnreadId(global, chatId, threadId),\n isViewportNewest: type !== 'thread' || selectIsViewportNewest(global, chatId, threadId),\n threadFirstMessageId: selectFirstMessageId(global, chatId, threadId),\n focusingId,\n isSelectModeActive: selectIsInSelectMode(global),\n botDescription,\n threadTopMessageId,\n hasLinkedChat: chat.fullInfo && ('linkedChatId' in chat.fullInfo)\n ? Boolean(chat.fullInfo.linkedChatId)\n : undefined,\n lastSyncTime: global.lastSyncTime,\n ...(withLastMessageWhenPreloading && { lastMessage }),\n };\n },\n)(MessageList));\n","import { useCallback } from '../../../lib/teact/teact';\n\nimport { fastRaf } from '../../../util/schedulers';\nimport useDebounce from '../../../hooks/useDebounce';\nimport useFlag from '../../../hooks/useFlag';\n\nconst DEBOUNCE = 1000;\nconst STICKY_TOP = 10;\nconst STICKY_TOP_WITH_TOOLS = 60;\n\nexport default function useStickyDates() {\n // For some reason we can not synchronously hide a sticky element (from `useLayoutEffect`) when chat opens\n // so we will add `position: sticky` only after first scroll. There would be no animation on the first show though.\n const [isScrolled, markIsScrolled] = useFlag(false);\n\n const runDebounced = useDebounce(DEBOUNCE, false);\n\n const updateStickyDates = useCallback((container: HTMLDivElement, hasTools?: boolean) => {\n markIsScrolled();\n\n if (!document.body.classList.contains('is-scrolling-messages')) {\n fastRaf(() => {\n document.body.classList.add('is-scrolling-messages');\n });\n }\n\n runDebounced(() => {\n fastRaf(() => {\n const currentStuck = document.querySelector('.stuck');\n if (currentStuck) {\n currentStuck.classList.remove('stuck');\n }\n\n const stuckDateEl = findStuckDate(container, hasTools);\n if (stuckDateEl) {\n stuckDateEl.classList.add('stuck');\n }\n\n document.body.classList.remove('is-scrolling-messages');\n });\n });\n }, [markIsScrolled, runDebounced]);\n\n return {\n isScrolled,\n updateStickyDates,\n };\n}\n\nfunction findStuckDate(container: HTMLElement, hasTools?: boolean) {\n const allElements = container.querySelectorAll('.sticky-date');\n const containerTop = container.scrollTop;\n\n return Array.from(allElements).find((el) => {\n const { offsetTop, offsetHeight } = el;\n const top = offsetTop - containerTop;\n return -offsetHeight <= top && top <= (hasTools ? STICKY_TOP_WITH_TOOLS : STICKY_TOP);\n });\n}\n","import React, {\n FC, useCallback, memo, useRef,\n} from '../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../lib/teact/teactn';\n\nimport { MessageListType } from '../../global/types';\nimport { MAIN_THREAD_ID } from '../../api/types';\n\nimport { selectChat, selectCurrentMessageList } from '../../modules/selectors';\nimport { formatIntegerCompact } from '../../util/textFormat';\nimport buildClassName from '../../util/buildClassName';\nimport fastSmoothScroll from '../../util/fastSmoothScroll';\nimport useLang from '../../hooks/useLang';\n\nimport Button from '../ui/Button';\n\nimport './ScrollDownButton.scss';\n\ntype OwnProps = {\n isShown: boolean;\n canPost?: boolean;\n withExtraShift?: boolean;\n};\n\ntype StateProps = {\n messageListType?: MessageListType;\n unreadCount?: number;\n};\n\nconst FOCUS_MARGIN = 20;\n\nconst ScrollDownButton: FC = ({\n isShown,\n canPost,\n messageListType,\n unreadCount,\n withExtraShift,\n}) => {\n const { focusNextReply } = getDispatch();\n\n const lang = useLang();\n // eslint-disable-next-line no-null/no-null\n const elementRef = useRef(null);\n\n const handleClick = useCallback(() => {\n if (!isShown) {\n return;\n }\n\n if (messageListType === 'thread') {\n focusNextReply();\n } else {\n const messagesContainer = elementRef.current!.parentElement!.querySelector('.MessageList')!;\n const messageElements = messagesContainer.querySelectorAll('.message-list-item');\n const lastMessageElement = messageElements[messageElements.length - 1];\n if (!lastMessageElement) {\n return;\n }\n\n fastSmoothScroll(messagesContainer, lastMessageElement, 'end', FOCUS_MARGIN);\n }\n }, [isShown, messageListType, focusNextReply]);\n\n const fabClassName = buildClassName(\n 'ScrollDownButton',\n isShown && 'revealed',\n !canPost && 'no-composer',\n withExtraShift && 'with-extra-shift',\n );\n\n return (\n
\n
\n \n \n \n {Boolean(unreadCount) && (\n
{formatIntegerCompact(unreadCount!)}
\n )}\n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const currentMessageList = selectCurrentMessageList(global);\n if (!currentMessageList) {\n return {};\n }\n\n const { chatId, threadId, type: messageListType } = currentMessageList;\n const chat = selectChat(global, chatId);\n\n return {\n messageListType,\n unreadCount: chat && threadId === MAIN_THREAD_ID && messageListType === 'thread' ? chat.unreadCount : undefined,\n };\n },\n)(ScrollDownButton));\n","import { ApiAttachment } from '../../../../api/types';\nimport { SUPPORTED_IMAGE_CONTENT_TYPES, SUPPORTED_VIDEO_CONTENT_TYPES } from '../../../../config';\nimport {\n preloadImage,\n preloadVideo,\n createPosterForVideo,\n fetchBlob,\n} from '../../../../util/files';\nimport { scaleImage } from '../../../../util/imageResize';\n\nconst MAX_QUICK_IMG_SIZE = 1280; // px\nconst FILE_EXT_REGEX = /\\.[^/.]+$/;\n\nexport default async function buildAttachment(\n filename: string, blob: Blob, isQuick: boolean, options?: Partial,\n): Promise {\n const blobUrl = URL.createObjectURL(blob);\n const { type: mimeType, size } = blob;\n let quick;\n let previewBlobUrl;\n\n if (SUPPORTED_IMAGE_CONTENT_TYPES.has(mimeType)) {\n if (isQuick) {\n const img = await preloadImage(blobUrl);\n const { width, height } = img;\n\n if (width > MAX_QUICK_IMG_SIZE || height > MAX_QUICK_IMG_SIZE || mimeType !== 'image/jpeg') {\n const resizedUrl = await scaleImage(blobUrl, MAX_QUICK_IMG_SIZE / Math.max(width, height), 'image/jpeg');\n URL.revokeObjectURL(blobUrl);\n const newBlob = await fetchBlob(resizedUrl);\n return buildAttachment(filename, newBlob, true, options);\n }\n\n if (mimeType === 'image/jpeg') {\n filename = filename.replace(FILE_EXT_REGEX, '.jpg');\n }\n\n quick = { width, height };\n } else {\n previewBlobUrl = blobUrl;\n }\n } else if (SUPPORTED_VIDEO_CONTENT_TYPES.has(mimeType)) {\n const { videoWidth: width, videoHeight: height, duration } = await preloadVideo(blobUrl);\n quick = { width, height, duration };\n\n previewBlobUrl = await createPosterForVideo(blobUrl);\n }\n\n return {\n blobUrl,\n filename,\n mimeType,\n size,\n quick,\n previewBlobUrl,\n ...options,\n };\n}\n","import { IS_IOS } from '../../../../util/environment';\n\nlet resetInput: HTMLInputElement;\n\nif (IS_IOS) {\n resetInput = document.createElement('input');\n resetInput.classList.add('for-ios-autocapitalization-fix');\n document.body.appendChild(resetInput);\n}\n\n// https://stackoverflow.com/a/55652503\nexport default function applyIosAutoCapitalizationFix(inputEl: HTMLElement) {\n resetInput.focus();\n inputEl.focus();\n}\n","import { useEffect, useLayoutEffect, useRef } from '../lib/teact/teact';\n\nfunction useInterval(callback: NoneToVoidFunction, delay?: number, noFirst = false) {\n const savedCallback = useRef(callback);\n\n useLayoutEffect(() => {\n savedCallback.current = callback;\n }, [callback]);\n\n useEffect(() => {\n if (delay === undefined) {\n return undefined;\n }\n\n const id = setInterval(() => savedCallback.current(), delay);\n if (!noFirst) savedCallback.current();\n\n return () => clearInterval(id);\n }, [delay, noFirst]);\n}\n\nexport default useInterval;\n","// @ts-ignore\nimport encoderPath from 'file-loader!opus-recorder/dist/encoderWorker.min';\n\nexport type Result = { blob: Blob; duration: number; waveform: number[] };\n\ninterface IOpusRecorder extends Omit {\n new(options: AnyLiteral): IOpusRecorder;\n\n start(stream?: MediaStreamAudioSourceNode): void;\n\n sourceNode: MediaStreamAudioSourceNode;\n\n ondataavailable: (typedArray: Uint8Array) => void;\n}\n\nconst MIN_RECORDING_TIME = 1000;\nconst POLYFILL_OPTIONS = { encoderPath, reuseWorker: true };\nconst BLOB_PARAMS = { type: 'audio/ogg' };\nconst FFT_SIZE = 64;\nconst MIN_VOLUME = 0.1;\n\nlet opusRecorderPromise: Promise<{ default: IOpusRecorder }>;\nlet OpusRecorder: IOpusRecorder;\nlet mediaRecorder: IOpusRecorder;\n\nexport async function init() {\n if (!opusRecorderPromise) {\n // @ts-ignore\n opusRecorderPromise = import('opus-recorder');\n OpusRecorder = (await opusRecorderPromise).default;\n mediaRecorder = new OpusRecorder(POLYFILL_OPTIONS);\n }\n\n return opusRecorderPromise;\n}\n\nexport async function start(analyzerCallback: Function) {\n await startMediaRecorder();\n\n const startedAt = Date.now();\n let pausedAt: number;\n const chunks: Uint8Array[] = [];\n const waveform: number[] = [];\n\n mediaRecorder.ondataavailable = (typedArray) => {\n chunks.push(typedArray);\n };\n\n const releaseAnalyzer = subscribeToAnalyzer(mediaRecorder, (volume: number) => {\n waveform.push(volume * 255);\n analyzerCallback(volume);\n });\n\n return {\n stop: () => new Promise((resolve, reject) => {\n mediaRecorder.onstop = () => {\n resolve({\n blob: new Blob(chunks, BLOB_PARAMS),\n duration: Math.round(((pausedAt || Date.now()) - startedAt) / 1000),\n waveform,\n });\n };\n mediaRecorder.onerror = reject;\n\n const delayStop = Math.max(0, startedAt + MIN_RECORDING_TIME - Date.now());\n setTimeout(() => {\n mediaRecorder.stop();\n releaseAnalyzer();\n }, delayStop);\n }),\n pause: () => {\n const delayStop = Math.max(0, startedAt + MIN_RECORDING_TIME - Date.now());\n setTimeout(() => {\n mediaRecorder.pause();\n pausedAt = Date.now();\n releaseAnalyzer();\n }, delayStop);\n },\n };\n}\n\nasync function startMediaRecorder() {\n await init();\n await mediaRecorder.start();\n}\n\nfunction subscribeToAnalyzer(recorder: IOpusRecorder, cb: Function) {\n const source = recorder.sourceNode;\n const analyser = source.context.createAnalyser();\n analyser.fftSize = FFT_SIZE;\n source.connect(analyser);\n\n const dataLength = analyser.frequencyBinCount;\n const dataArray = new Uint8Array(dataLength);\n let isDestroyed = false;\n\n function tick() {\n if (isDestroyed) {\n return;\n }\n\n analyser.getByteFrequencyData(dataArray);\n\n const sum = dataArray.reduce((acc, current) => acc + current, 0);\n const mean = (sum / dataLength);\n const volume = mean / 255;\n\n cb(volume < MIN_VOLUME ? 0 : volume);\n\n requestAnimationFrame(tick);\n }\n\n tick();\n\n return () => {\n isDestroyed = true;\n };\n}\n","export default __webpack_public_path__ + \"c0155344d336103c2b6a0b28cc510750.js\";","import {\n useCallback, useEffect, useRef, useState,\n} from '../../../../lib/teact/teact';\n\nimport { IS_SAFARI, IS_VOICE_RECORDING_SUPPORTED } from '../../../../util/environment';\nimport * as voiceRecording from '../../../../util/voiceRecording';\nimport captureEscKeyListener from '../../../../util/captureEscKeyListener';\n\ntype ActiveVoiceRecording = { stop: () => Promise; pause: NoneToVoidFunction } | undefined;\n\nexport default () => {\n // eslint-disable-next-line no-null/no-null\n const recordButtonRef = useRef(null);\n const [activeVoiceRecording, setActiveVoiceRecording] = useState();\n const startRecordTimeRef = useRef();\n const [currentRecordTime, setCurrentRecordTime] = useState();\n\n useEffect(() => {\n // Preloading worker fixes silent first record on iOS\n if (IS_SAFARI && IS_VOICE_RECORDING_SUPPORTED) {\n void voiceRecording.init();\n }\n }, []);\n\n const startRecordingVoice = useCallback(async () => {\n try {\n const { stop, pause } = await voiceRecording.start((tickVolume: number) => {\n if (recordButtonRef.current) {\n if (startRecordTimeRef.current && Date.now() % 4 === 0) {\n recordButtonRef.current.style.boxShadow = `0 0 0 ${(tickVolume || 0) * 50}px rgba(0,0,0,.15)`;\n }\n setCurrentRecordTime(Date.now());\n }\n });\n startRecordTimeRef.current = Date.now();\n setCurrentRecordTime(Date.now());\n\n setActiveVoiceRecording({ stop, pause });\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n }, []);\n\n const pauseRecordingVoice = useCallback(() => {\n if (!activeVoiceRecording) {\n return undefined;\n }\n\n if (recordButtonRef.current) {\n recordButtonRef.current.style.boxShadow = 'none';\n }\n try {\n return activeVoiceRecording!.pause();\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(err);\n return undefined;\n }\n }, [activeVoiceRecording]);\n\n const stopRecordingVoice = useCallback(() => {\n if (!activeVoiceRecording) {\n return undefined;\n }\n\n setActiveVoiceRecording(undefined);\n startRecordTimeRef.current = undefined;\n setCurrentRecordTime(undefined);\n if (recordButtonRef.current) {\n recordButtonRef.current.style.boxShadow = 'none';\n }\n try {\n return activeVoiceRecording!.stop();\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(err);\n return undefined;\n }\n }, [activeVoiceRecording]);\n\n useEffect(() => {\n return activeVoiceRecording ? captureEscKeyListener(stopRecordingVoice) : undefined;\n }, [activeVoiceRecording, stopRecordingVoice]);\n\n return {\n startRecordingVoice,\n pauseRecordingVoice,\n stopRecordingVoice,\n activeVoiceRecording,\n currentRecordTime,\n recordButtonRef,\n startRecordTimeRef,\n };\n};\n","import { StateHookSetter, useEffect } from '../../../../lib/teact/teact';\nimport { ApiAttachment, ApiMessage } from '../../../../api/types';\n\nimport buildAttachment from '../helpers/buildAttachment';\nimport { EDITABLE_INPUT_ID, EDITABLE_INPUT_MODAL_ID } from '../../../../config';\n\nconst CLIPBOARD_ACCEPTED_TYPES = ['image/png', 'image/jpeg', 'image/gif'];\nconst MAX_MESSAGE_LENGTH = 4096;\n\nexport default (\n insertTextAndUpdateCursor: (text: string, inputId?: string) => void,\n setAttachments: StateHookSetter,\n editedMessage: ApiMessage | undefined,\n) => {\n useEffect(() => {\n async function handlePaste(e: ClipboardEvent) {\n if (!e.clipboardData) {\n return;\n }\n\n const input = document.activeElement;\n if (input && ![EDITABLE_INPUT_ID, EDITABLE_INPUT_MODAL_ID].includes(input.id)) {\n return;\n }\n\n const { items } = e.clipboardData;\n const media = Array.from(items)\n .find((item) => CLIPBOARD_ACCEPTED_TYPES.includes(item.type) && item.kind === 'file');\n const file = media && media.getAsFile();\n const pastedText = e.clipboardData.getData('text').substring(0, MAX_MESSAGE_LENGTH);\n\n e.preventDefault();\n\n if (!file && !pastedText) {\n return;\n }\n\n if (file && !editedMessage) {\n const attachment = await buildAttachment(file.name, file, true);\n setAttachments((attachments) => [\n ...attachments,\n attachment,\n ]);\n }\n\n if (pastedText) {\n insertTextAndUpdateCursor(pastedText, input?.id);\n }\n }\n\n document.addEventListener('paste', handlePaste, false);\n\n return () => {\n document.removeEventListener('paste', handlePaste, false);\n };\n }, [insertTextAndUpdateCursor, editedMessage, setAttachments]);\n};\n","import { ApiFormattedText } from '../../../../api/types';\nimport { renderTextWithEntities } from '../../../common/helpers/renderMessageText';\n\nexport default function getMessageTextAsHtml(formattedText?: ApiFormattedText) {\n const { text, entities } = formattedText || {};\n if (!text) {\n return '';\n }\n\n const result = renderTextWithEntities(\n text,\n entities,\n undefined,\n undefined,\n true,\n );\n\n if (Array.isArray(result)) {\n return result.join('');\n }\n\n return result;\n}\n","import { useCallback, useEffect, useMemo } from '../../../../lib/teact/teact';\nimport { getDispatch } from '../../../../lib/teact/teactn';\n\nimport { ApiFormattedText, ApiMessage } from '../../../../api/types';\n\nimport { DRAFT_DEBOUNCE, EDITABLE_INPUT_ID } from '../../../../config';\nimport usePrevious from '../../../../hooks/usePrevious';\nimport { debounce } from '../../../../util/schedulers';\nimport focusEditableElement from '../../../../util/focusEditableElement';\nimport parseMessageInput from '../../../../util/parseMessageInput';\nimport getMessageTextAsHtml from '../helpers/getMessageTextAsHtml';\nimport useBackgroundMode from '../../../../hooks/useBackgroundMode';\nimport useBeforeUnload from '../../../../hooks/useBeforeUnload';\nimport { IS_TOUCH_ENV } from '../../../../util/environment';\n\n// Used to avoid running debounced callbacks when chat changes.\nlet currentChatId: string | undefined;\nlet currentThreadId: number | undefined;\n\nexport default (\n draft: ApiFormattedText | undefined,\n chatId: string,\n threadId: number,\n html: string,\n htmlRef: { current: string },\n setHtml: (html: string) => void,\n editedMessage: ApiMessage | undefined,\n) => {\n const { saveDraft, clearDraft } = getDispatch();\n\n const updateDraft = useCallback((draftChatId: string, draftThreadId: number) => {\n if (htmlRef.current.length && !editedMessage) {\n saveDraft({ chatId: draftChatId, threadId: draftThreadId, draft: parseMessageInput(htmlRef.current!) });\n } else {\n clearDraft({ chatId: draftChatId, threadId: draftThreadId });\n }\n }, [clearDraft, editedMessage, htmlRef, saveDraft]);\n\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const runDebouncedForSaveDraft = useMemo(() => debounce((cb) => cb(), DRAFT_DEBOUNCE, false), [chatId]);\n\n const prevChatId = usePrevious(chatId);\n const prevThreadId = usePrevious(threadId);\n\n // Save draft on chat change\n useEffect(() => {\n currentChatId = chatId;\n currentThreadId = threadId;\n\n return () => {\n currentChatId = undefined;\n currentThreadId = undefined;\n\n updateDraft(chatId, threadId);\n };\n }, [chatId, threadId, updateDraft]);\n\n // Restore draft on chat change\n useEffect(() => {\n if (chatId === prevChatId && threadId === prevThreadId) {\n return;\n }\n\n if (!draft) {\n return;\n }\n\n setHtml(getMessageTextAsHtml(draft));\n\n if (!IS_TOUCH_ENV) {\n requestAnimationFrame(() => {\n const messageInput = document.getElementById(EDITABLE_INPUT_ID)!;\n focusEditableElement(messageInput, true);\n });\n }\n }, [chatId, threadId, draft, setHtml, updateDraft, prevChatId, prevThreadId]);\n\n // Update draft when input changes\n const prevHtml = usePrevious(html);\n useEffect(() => {\n if (!chatId || !threadId || prevChatId !== chatId || prevThreadId !== threadId || prevHtml === html) {\n return;\n }\n\n if (html.length) {\n runDebouncedForSaveDraft(() => {\n if (currentChatId !== chatId || currentThreadId !== threadId) {\n return;\n }\n\n updateDraft(chatId, threadId);\n });\n } else {\n updateDraft(chatId, threadId);\n }\n }, [chatId, html, prevChatId, prevHtml, prevThreadId, runDebouncedForSaveDraft, threadId, updateDraft]);\n\n const handleBlur = useCallback(() => {\n if (chatId && threadId) {\n updateDraft(chatId, threadId);\n }\n }, [chatId, threadId, updateDraft]);\n\n useBackgroundMode(handleBlur);\n useBeforeUnload(handleBlur);\n};\n","import { useCallback, useEffect } from '../../../../lib/teact/teact';\nimport { getDispatch } from '../../../../lib/teact/teactn';\nimport { InlineBotSettings } from '../../../../types';\nimport useFlag from '../../../../hooks/useFlag';\nimport usePrevious from '../../../../hooks/usePrevious';\n\nconst tempEl = document.createElement('div');\nconst INLINE_BOT_QUERY_REGEXP = /^@([a-z0-9_]{1,32})[\\u00A0\\u0020]+(.*)/i;\nconst HAS_NEW_LINE = /^@([a-z0-9_]{1,32})[\\u00A0\\u0020]+\\n{2,}/i;\n\nexport default function useInlineBotTooltip(\n isAllowed: boolean,\n chatId: string,\n html: string,\n inlineBots?: Record,\n) {\n const [isOpen, markIsOpen, unmarkIsOpen] = useFlag();\n const text = getPlainText(html);\n const { queryInlineBot, resetInlineBot } = getDispatch();\n const { username, query, canShowHelp } = parseStartWithUsernameString(text);\n const usernameLowered = username.toLowerCase();\n const prevQuery = usePrevious(query);\n const prevUsername = usePrevious(username);\n const inlineBotData = inlineBots?.[usernameLowered];\n const {\n id: botId,\n switchPm,\n offset,\n results,\n isGallery,\n help,\n } = inlineBotData || {};\n\n useEffect(() => {\n if (prevQuery !== query) {\n unmarkIsOpen();\n }\n }, [prevQuery, query, unmarkIsOpen]);\n\n useEffect(() => {\n if (isAllowed && usernameLowered && chatId) {\n queryInlineBot({ chatId, username: usernameLowered, query });\n }\n }, [query, isAllowed, queryInlineBot, chatId, usernameLowered]);\n\n const loadMore = useCallback(() => {\n queryInlineBot({\n chatId, username: usernameLowered, query, offset,\n });\n }, [offset, chatId, query, queryInlineBot, usernameLowered]);\n\n useEffect(() => {\n if (isAllowed && botId && (switchPm || (results?.length))) {\n markIsOpen();\n } else {\n unmarkIsOpen();\n }\n }, [botId, isAllowed, markIsOpen, results, switchPm, unmarkIsOpen]);\n\n if (prevUsername !== username) {\n resetInlineBot({ username: prevUsername });\n }\n\n return {\n isOpen,\n closeTooltip: unmarkIsOpen,\n loadMore,\n username,\n id: botId,\n isGallery,\n switchPm,\n results,\n help: canShowHelp && help ? `@${username} ${help}` : undefined,\n };\n}\n\nfunction getPlainText(html: string) {\n tempEl.innerHTML = html.replace(/
/g, '\\n');\n\n return tempEl.innerText;\n}\n\nfunction parseStartWithUsernameString(text: string) {\n const result = text.match(INLINE_BOT_QUERY_REGEXP);\n if (!result) {\n return { username: '', query: '', canShowHelp: false };\n }\n\n return {\n username: result[1],\n query: result[2],\n canShowHelp: result[2] === '' && !text.match(HAS_NEW_LINE),\n };\n}\n","import {\n useCallback, useEffect, useState,\n} from '../../../../lib/teact/teact';\n\nimport { ApiBotCommand } from '../../../../api/types';\n\nimport { prepareForRegExp } from '../helpers/prepareForRegExp';\nimport { throttle } from '../../../../util/schedulers';\nimport useFlag from '../../../../hooks/useFlag';\n\nconst runThrottled = throttle((cb) => cb(), 500, true);\nconst RE_COMMAND = /^[\\w@]{1,32}\\s?/i;\n\nexport default function useBotCommandTooltip(\n isAllowed: boolean,\n html: string,\n botCommands?: ApiBotCommand[] | false,\n chatBotCommands?: ApiBotCommand[],\n) {\n const [isOpen, markIsOpen, unmarkIsOpen] = useFlag();\n const [filteredBotCommands, setFilteredBotCommands] = useState();\n\n const getFilteredCommands = useCallback((filter) => {\n if (!botCommands && !chatBotCommands) {\n setFilteredBotCommands(undefined);\n\n return;\n }\n\n runThrottled(() => {\n const nextFilteredBotCommands = (botCommands || chatBotCommands || [])\n .filter(({ command }) => !filter || command.includes(filter));\n setFilteredBotCommands(\n nextFilteredBotCommands && nextFilteredBotCommands.length ? nextFilteredBotCommands : undefined,\n );\n });\n }, [botCommands, chatBotCommands]);\n\n useEffect(() => {\n if (!isAllowed || !html.length) {\n unmarkIsOpen();\n return;\n }\n\n const shouldShowCommands = html.startsWith('/');\n\n if (shouldShowCommands) {\n const filter = prepareForRegExp(html.substr(1)).match(RE_COMMAND);\n getFilteredCommands(filter ? filter[0] : '');\n } else {\n unmarkIsOpen();\n }\n }, [getFilteredCommands, html, isAllowed, unmarkIsOpen]);\n\n useEffect(() => {\n if (filteredBotCommands && filteredBotCommands.length) {\n markIsOpen();\n } else {\n unmarkIsOpen();\n }\n }, [filteredBotCommands, markIsOpen, unmarkIsOpen]);\n\n return {\n isOpen,\n close: unmarkIsOpen,\n filteredBotCommands,\n };\n}\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './DeleteMessageModal';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst DeleteMessageModalAsync: FC = (props) => {\n const { isOpen } = props;\n const DeleteMessageModal = useModuleLoader(Bundles.Extra, 'DeleteMessageModal', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return DeleteMessageModal ? : undefined;\n};\n\nexport default memo(DeleteMessageModalAsync);\n","import React, {\n FC, useRef, useCallback, memo,\n} from '../../lib/teact/teact';\n\nimport { IS_TOUCH_ENV } from '../../util/environment';\n\nimport Button, { OwnProps as ButtonProps } from './Button';\n\ntype OwnProps = {\n onActivate: NoneToVoidFunction;\n} & Omit;\n\nconst BUTTON_ACTIVATE_DELAY = 200;\nlet openTimeout: number | undefined;\nlet isFirstTimeActivation = true;\n\nconst ResponsiveHoverButton: FC = ({ onActivate, ...buttonProps }) => {\n const isMouseInside = useRef(false);\n\n const handleMouseEnter = useCallback(() => {\n isMouseInside.current = true;\n\n // This is used to counter additional delay caused by asynchronous module loading\n if (isFirstTimeActivation) {\n isFirstTimeActivation = false;\n onActivate();\n return;\n }\n\n if (openTimeout) {\n clearTimeout(openTimeout);\n openTimeout = undefined;\n }\n openTimeout = window.setTimeout(() => {\n if (isMouseInside.current) {\n onActivate();\n }\n }, BUTTON_ACTIVATE_DELAY);\n }, [onActivate]);\n\n const handleMouseLeave = useCallback(() => {\n isMouseInside.current = false;\n }, []);\n\n return (\n \n );\n};\n\nexport default memo(ResponsiveHoverButton);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './AttachMenu';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst AttachMenuAsync: FC = (props) => {\n const { isOpen } = props;\n const AttachMenu = useModuleLoader(Bundles.Extra, 'AttachMenu', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return AttachMenu ? : undefined;\n};\n\nexport default memo(AttachMenuAsync);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './SymbolMenu';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst SymbolMenuAsync: FC = (props) => {\n const { isOpen } = props;\n const SymbolMenu = useModuleLoader(Bundles.Extra, 'SymbolMenu', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return SymbolMenu ? : undefined;\n};\n\nexport default memo(SymbolMenuAsync);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './InlineBotTooltip';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst InlineBotTooltipAsync: FC = (props) => {\n const { isOpen } = props;\n const InlineBotTooltip = useModuleLoader(Bundles.Extra, 'InlineBotTooltip', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return InlineBotTooltip ? : undefined;\n};\n\nexport default memo(InlineBotTooltipAsync);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './MentionTooltip';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst MentionTooltipAsync: FC = (props) => {\n const { isOpen } = props;\n const MentionTooltip = useModuleLoader(Bundles.Extra, 'MentionTooltip', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return MentionTooltip ? : undefined;\n};\n\nexport default memo(MentionTooltipAsync);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './CustomSendMenu';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst CustomSendMenuAsync: FC = (props) => {\n const { isOpen } = props;\n const CustomSend = useModuleLoader(Bundles.Extra, 'CustomSendMenu', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return CustomSend ? : undefined;\n};\n\nexport default memo(CustomSendMenuAsync);\n","import React, { FC } from '../../../lib/teact/teact';\nimport { OwnProps } from './StickerTooltip';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst StickerTooltipAsync: FC = (props) => {\n const { isOpen } = props;\n const StickerTooltip = useModuleLoader(Bundles.Extra, 'StickerTooltip', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return StickerTooltip ? : undefined;\n};\n\nexport default StickerTooltipAsync;\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './BotCommandTooltip';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst BotCommandTooltipAsync: FC = (props) => {\n const { isOpen } = props;\n const BotCommandTooltip = useModuleLoader(Bundles.Extra, 'BotCommandTooltip', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return BotCommandTooltip ? : undefined;\n};\n\nexport default memo(BotCommandTooltipAsync);\n","import React, { FC, memo, useEffect } from '../../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiMessage } from '../../../api/types';\n\nimport { IS_TOUCH_ENV } from '../../../util/environment';\nimport { selectChatMessage, selectCurrentMessageList } from '../../../modules/selectors';\nimport useMouseInside from '../../../hooks/useMouseInside';\nimport useFlag from '../../../hooks/useFlag';\n\nimport Menu from '../../ui/Menu';\nimport Button from '../../ui/Button';\n\nimport './BotKeyboardMenu.scss';\n\nexport type OwnProps = {\n isOpen: boolean;\n messageId: number;\n onClose: NoneToVoidFunction;\n};\n\ntype StateProps = {\n message?: ApiMessage;\n};\n\nconst BotKeyboardMenu: FC = ({\n isOpen, message, onClose,\n}) => {\n const { clickInlineButton } = getDispatch();\n\n const [handleMouseEnter, handleMouseLeave] = useMouseInside(isOpen, onClose);\n const { isKeyboardSingleUse } = message || {};\n const [forceOpen, markForceOpen, unmarkForceOpen] = useFlag(true);\n\n const handleClose = () => {\n unmarkForceOpen();\n onClose();\n };\n\n useEffect(() => {\n markForceOpen();\n }, [markForceOpen, message]);\n\n if (!message || !message.keyboardButtons) {\n return undefined;\n }\n\n return (\n \n
\n {message.keyboardButtons.map((row) => (\n
\n {row.map((button) => (\n clickInlineButton({ button })}\n >\n {button.text}\n \n ))}\n
\n ))}\n
\n \n );\n};\n\nexport default memo(withGlobal(\n (global, { messageId }): StateProps => {\n const { chatId } = selectCurrentMessageList(global) || {};\n if (!chatId) {\n return {};\n }\n\n return { message: selectChatMessage(global, chatId, messageId) };\n },\n)(BotKeyboardMenu));\n","import React, {\n FC, memo, useCallback, useEffect,\n} from '../../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiChat, ApiMessage, ApiUser } from '../../../api/types';\n\nimport {\n selectChat,\n selectChatMessage,\n selectSender,\n selectForwardedSender,\n selectUser,\n selectCurrentMessageList,\n selectReplyingToId,\n selectEditingId,\n selectEditingScheduledId,\n selectEditingMessage,\n} from '../../../modules/selectors';\nimport captureEscKeyListener from '../../../util/captureEscKeyListener';\nimport useAsyncRendering from '../../right/hooks/useAsyncRendering';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport buildClassName from '../../../util/buildClassName';\nimport { isUserId } from '../../../modules/helpers';\n\nimport Button from '../../ui/Button';\nimport EmbeddedMessage from '../../common/EmbeddedMessage';\n\nimport './ComposerEmbeddedMessage.scss';\n\ntype StateProps = {\n replyingToId?: number;\n editingId?: number;\n message?: ApiMessage;\n sender?: ApiUser | ApiChat;\n shouldAnimate?: boolean;\n forwardedMessagesCount?: number;\n};\n\nconst FORWARD_RENDERING_DELAY = 300;\n\nconst ComposerEmbeddedMessage: FC = ({\n replyingToId,\n editingId,\n message,\n sender,\n shouldAnimate,\n forwardedMessagesCount,\n}) => {\n const {\n setReplyingToId,\n setEditingId,\n focusMessage,\n exitForwardMode,\n } = getDispatch();\n\n const isShown = Boolean(\n ((replyingToId || editingId) && message)\n || (sender && forwardedMessagesCount),\n );\n const canAnimate = useAsyncRendering(\n [forwardedMessagesCount],\n forwardedMessagesCount ? FORWARD_RENDERING_DELAY : undefined,\n );\n\n const {\n shouldRender, transitionClassNames,\n } = useShowTransition(canAnimate && isShown, undefined, !shouldAnimate, undefined, !shouldAnimate);\n\n const clearEmbedded = useCallback(() => {\n if (replyingToId) {\n setReplyingToId({ messageId: undefined });\n } else if (editingId) {\n setEditingId({ messageId: undefined });\n } else if (forwardedMessagesCount) {\n exitForwardMode();\n }\n }, [replyingToId, editingId, forwardedMessagesCount, setReplyingToId, setEditingId, exitForwardMode]);\n\n useEffect(() => (isShown ? captureEscKeyListener(clearEmbedded) : undefined), [isShown, clearEmbedded]);\n\n const handleMessageClick = useCallback((): void => {\n focusMessage({ chatId: message!.chatId, messageId: message!.id });\n }, [focusMessage, message]);\n\n const className = buildClassName('ComposerEmbeddedMessage', transitionClassNames);\n\n const customText = forwardedMessagesCount && forwardedMessagesCount > 1\n ? `${forwardedMessagesCount} forwarded messages`\n : undefined;\n\n if (!shouldRender) {\n return undefined;\n }\n\n return (\n
\n
\n \n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { chatId, threadId, type: messageListType } = selectCurrentMessageList(global) || {};\n if (!chatId || !threadId || !messageListType) {\n return {};\n }\n\n const {\n currentUserId,\n forwardMessages: { fromChatId, toChatId, messageIds: forwardMessageIds },\n } = global;\n\n const replyingToId = selectReplyingToId(global, chatId, threadId);\n const editingId = messageListType === 'scheduled'\n ? selectEditingScheduledId(global, chatId)\n : selectEditingId(global, chatId, threadId);\n const shouldAnimate = global.settings.byKey.animationLevel >= 1;\n const isForwarding = toChatId === chatId;\n\n let message;\n if (replyingToId) {\n message = selectChatMessage(global, chatId, replyingToId);\n } else if (editingId) {\n message = selectEditingMessage(global, chatId, threadId, messageListType);\n } else if (isForwarding && forwardMessageIds!.length === 1) {\n message = selectChatMessage(global, fromChatId!, forwardMessageIds![0]);\n }\n\n let sender: ApiChat | ApiUser | undefined;\n if (replyingToId && message) {\n const { forwardInfo } = message;\n const isChatWithSelf = chatId === currentUserId;\n\n if (forwardInfo && (forwardInfo.isChannelPost || isChatWithSelf)) {\n sender = selectForwardedSender(global, message);\n }\n\n if (!sender) {\n sender = selectSender(global, message);\n }\n } else if (isForwarding) {\n sender = isUserId(fromChatId!) ? selectUser(global, fromChatId!) : selectChat(global, fromChatId!);\n }\n\n return {\n replyingToId,\n editingId,\n message,\n sender,\n shouldAnimate,\n forwardedMessagesCount: isForwarding ? forwardMessageIds!.length : undefined,\n };\n },\n)(ComposerEmbeddedMessage));\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './AttachmentModal';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst AttachmentModalAsync: FC = (props) => {\n const { attachments } = props;\n const AttachmentModal = useModuleLoader(Bundles.Extra, 'AttachmentModal', !attachments.length);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return AttachmentModal ? : undefined;\n};\n\nexport default memo(AttachmentModalAsync);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './BotCommandMenu';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst BotCommandMenuAsync: FC = (props) => {\n const { isOpen } = props;\n const BotCommandMenu = useModuleLoader(Bundles.Extra, 'BotCommandMenu', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return BotCommandMenu ? : undefined;\n};\n\nexport default memo(BotCommandMenuAsync);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './PollModal';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst PollModalAsync: FC = (props) => {\n const { isOpen } = props;\n const PollModal = useModuleLoader(Bundles.Extra, 'PollModal', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return PollModal ? : undefined;\n};\n\nexport default memo(PollModalAsync);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './DropArea';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst DropAreaAsync: FC = (props) => {\n const { isOpen } = props;\n const DropArea = useModuleLoader(Bundles.Extra, 'DropArea', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return DropArea ? : undefined;\n};\n\nexport default memo(DropAreaAsync);\nexport { DropAreaState } from './DropArea';\n","import React, {\n FC, memo, useEffect, useMemo,\n} from '../../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiMessage, ApiMessageEntityTypes, ApiWebPage } from '../../../api/types';\nimport { ISettings } from '../../../types';\n\nimport { RE_LINK_TEMPLATE } from '../../../config';\nimport { selectNoWebPage, selectTheme } from '../../../modules/selectors';\nimport parseMessageInput from '../../../util/parseMessageInput';\nimport useOnChange from '../../../hooks/useOnChange';\nimport useShowTransition from '../../../hooks/useShowTransition';\nimport useCurrentOrPrev from '../../../hooks/useCurrentOrPrev';\nimport buildClassName from '../../../util/buildClassName';\n\nimport WebPage from '../message/WebPage';\nimport Button from '../../ui/Button';\n\nimport './WebPagePreview.scss';\n\ntype OwnProps = {\n chatId: string;\n threadId: number;\n messageText: string;\n disabled?: boolean;\n};\n\ntype StateProps = {\n webPagePreview?: ApiWebPage;\n noWebPage?: boolean;\n theme: ISettings['theme'];\n};\n\nconst RE_LINK = new RegExp(RE_LINK_TEMPLATE, 'i');\n\nconst WebPagePreview: FC = ({\n chatId,\n threadId,\n messageText,\n disabled,\n webPagePreview,\n noWebPage,\n theme,\n}) => {\n const {\n loadWebPagePreview,\n clearWebPagePreview,\n toggleMessageWebPage,\n } = getDispatch();\n\n const link = useMemo(() => {\n const { text, entities } = parseMessageInput(messageText);\n\n const linkEntity = entities && entities.find(({ type }) => type === ApiMessageEntityTypes.TextUrl);\n if (linkEntity) {\n return linkEntity.url;\n }\n\n const textMatch = text.match(RE_LINK);\n if (textMatch) {\n return textMatch[0];\n }\n\n return undefined;\n }, [messageText]);\n\n useEffect(() => {\n if (link) {\n loadWebPagePreview({ text: link });\n } else {\n clearWebPagePreview();\n toggleMessageWebPage({ chatId, threadId });\n }\n }, [chatId, toggleMessageWebPage, clearWebPagePreview, link, loadWebPagePreview, threadId]);\n\n useOnChange(() => {\n clearWebPagePreview();\n toggleMessageWebPage({ chatId, threadId });\n }, [chatId]);\n\n const isShown = Boolean(webPagePreview && messageText.length && !noWebPage && !disabled);\n const { shouldRender, transitionClassNames } = useShowTransition(isShown);\n\n const renderingWebPage = useCurrentOrPrev(webPagePreview, true);\n\n if (!shouldRender || !renderingWebPage) {\n return undefined;\n }\n\n const handleClearWebpagePreview = () => {\n toggleMessageWebPage({ chatId, threadId, noWebPage: true });\n };\n\n // TODO Refactor so `WebPage` can be used without message\n const { photo, ...webPageWithoutPhoto } = renderingWebPage;\n const messageStub = {\n content: {\n webPage: webPageWithoutPhoto,\n },\n } as ApiMessage;\n\n return (\n
\n
\n \n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { chatId, threadId }): StateProps => {\n const noWebPage = selectNoWebPage(global, chatId, threadId);\n return {\n theme: selectTheme(global),\n webPagePreview: global.webPagePreview,\n noWebPage,\n };\n },\n)(WebPagePreview));\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './CalendarModal';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst CalendarModalAsync: FC = (props) => {\n const { isOpen } = props;\n const CalendarModal = useModuleLoader(Bundles.Extra, 'CalendarModal', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return CalendarModal ? : undefined;\n};\n\nexport default memo(CalendarModalAsync);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { OwnProps } from './SendAsMenu';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nconst SendAsMenuAsync: FC = (props) => {\n const { isOpen } = props;\n const SendAsMenu = useModuleLoader(Bundles.Extra, 'SendAsMenu', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return SendAsMenu ? : undefined;\n};\n\nexport default memo(SendAsMenuAsync);\n","import React, {\n FC, memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState,\n} from '../../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../../lib/teact/teactn';\n\nimport { GlobalState, MessageListType } from '../../../global/types';\nimport {\n ApiAttachment,\n ApiBotInlineResult,\n ApiBotInlineMediaResult,\n ApiSticker,\n ApiVideo,\n ApiNewPoll,\n ApiMessage,\n ApiFormattedText,\n ApiChat,\n ApiChatMember,\n ApiUser,\n MAIN_THREAD_ID,\n ApiBotCommand,\n} from '../../../api/types';\nimport { InlineBotSettings } from '../../../types';\n\nimport {\n BASE_EMOJI_KEYWORD_LANG, EDITABLE_INPUT_ID, REPLIES_USER_ID, SCHEDULED_WHEN_ONLINE, SEND_MESSAGE_ACTION_INTERVAL,\n} from '../../../config';\nimport { IS_VOICE_RECORDING_SUPPORTED, IS_SINGLE_COLUMN_LAYOUT, IS_IOS } from '../../../util/environment';\nimport {\n selectChat,\n selectIsRightColumnShown,\n selectIsInSelectMode,\n selectNewestMessageWithBotKeyboardButtons,\n selectDraft,\n selectScheduledIds,\n selectEditingMessage,\n selectIsChatWithSelf,\n selectChatBot,\n selectChatUser,\n selectChatMessage,\n selectUserStatus,\n} from '../../../modules/selectors';\nimport {\n getAllowedAttachmentOptions,\n getChatSlowModeOptions,\n isUserId,\n isChatAdmin,\n isChatSuperGroup,\n} from '../../../modules/helpers';\nimport { formatMediaDuration, formatVoiceRecordDuration, getDayStartAt } from '../../../util/dateFormat';\nimport focusEditableElement from '../../../util/focusEditableElement';\nimport parseMessageInput from '../../../util/parseMessageInput';\nimport buildAttachment from './helpers/buildAttachment';\nimport renderText from '../../common/helpers/renderText';\nimport insertHtmlInSelection from '../../../util/insertHtmlInSelection';\nimport deleteLastCharacterOutsideSelection from '../../../util/deleteLastCharacterOutsideSelection';\nimport buildClassName from '../../../util/buildClassName';\nimport windowSize from '../../../util/windowSize';\nimport { isSelectionInsideInput } from './helpers/selection';\nimport applyIosAutoCapitalizationFix from './helpers/applyIosAutoCapitalizationFix';\nimport { getServerTime } from '../../../util/serverTime';\n\nimport useFlag from '../../../hooks/useFlag';\nimport usePrevious from '../../../hooks/usePrevious';\nimport useStickerTooltip from './hooks/useStickerTooltip';\nimport useContextMenuHandlers from '../../../hooks/useContextMenuHandlers';\nimport useLang from '../../../hooks/useLang';\nimport useSendMessageAction from '../../../hooks/useSendMessageAction';\nimport useInterval from '../../../hooks/useInterval';\nimport useOnChange from '../../../hooks/useOnChange';\nimport useVoiceRecording from './hooks/useVoiceRecording';\nimport useClipboardPaste from './hooks/useClipboardPaste';\nimport useDraft from './hooks/useDraft';\nimport useEditing from './hooks/useEditing';\nimport useEmojiTooltip from './hooks/useEmojiTooltip';\nimport useMentionTooltip from './hooks/useMentionTooltip';\nimport useInlineBotTooltip from './hooks/useInlineBotTooltip';\nimport useBotCommandTooltip from './hooks/useBotCommandTooltip';\n\nimport DeleteMessageModal from '../../common/DeleteMessageModal.async';\nimport Button from '../../ui/Button';\nimport ResponsiveHoverButton from '../../ui/ResponsiveHoverButton';\nimport Spinner from '../../ui/Spinner';\nimport AttachMenu from './AttachMenu.async';\nimport SymbolMenu from './SymbolMenu.async';\nimport InlineBotTooltip from './InlineBotTooltip.async';\nimport MentionTooltip from './MentionTooltip.async';\nimport CustomSendMenu from './CustomSendMenu.async';\nimport StickerTooltip from './StickerTooltip.async';\nimport EmojiTooltip from './EmojiTooltip.async';\nimport BotCommandTooltip from './BotCommandTooltip.async';\nimport BotKeyboardMenu from './BotKeyboardMenu';\nimport MessageInput from './MessageInput';\nimport ComposerEmbeddedMessage from './ComposerEmbeddedMessage';\nimport AttachmentModal from './AttachmentModal.async';\nimport BotCommandMenu from './BotCommandMenu.async';\nimport PollModal from './PollModal.async';\nimport DropArea, { DropAreaState } from './DropArea.async';\nimport WebPagePreview from './WebPagePreview';\nimport Portal from '../../ui/Portal';\nimport CalendarModal from '../../common/CalendarModal.async';\nimport SendAsMenu from './SendAsMenu.async';\nimport Avatar from '../../common/Avatar';\n\nimport './Composer.scss';\n\ntype OwnProps = {\n chatId: string;\n threadId: number;\n messageListType: MessageListType;\n dropAreaState: string;\n isReady: boolean;\n onDropHide: NoneToVoidFunction;\n};\n\ntype StateProps =\n {\n editingMessage?: ApiMessage;\n chat?: ApiChat;\n draft?: ApiFormattedText;\n isChatWithBot?: boolean;\n isChatWithSelf?: boolean;\n isRightColumnShown?: boolean;\n isSelectModeActive?: boolean;\n isForwarding?: boolean;\n isPollModalOpen?: boolean;\n botKeyboardMessageId?: number;\n botKeyboardPlaceholder?: string;\n withScheduledButton?: boolean;\n shouldSchedule?: boolean;\n canScheduleUntilOnline?: boolean;\n stickersForEmoji?: ApiSticker[];\n groupChatMembers?: ApiChatMember[];\n currentUserId?: string;\n usersById?: Record;\n recentEmojis: string[];\n lastSyncTime?: number;\n contentToBeScheduled?: GlobalState['messages']['contentToBeScheduled'];\n shouldSuggestStickers?: boolean;\n baseEmojiKeywords?: Record;\n emojiKeywords?: Record;\n serverTimeOffset: number;\n topInlineBotIds?: string[];\n isInlineBotLoading: boolean;\n inlineBots?: Record;\n botCommands?: ApiBotCommand[] | false;\n chatBotCommands?: ApiBotCommand[];\n sendAsUser?: ApiUser;\n sendAsChat?: ApiChat;\n sendAsId?: string;\n }\n & Pick;\n\nenum MainButtonState {\n Send = 'send',\n Record = 'record',\n Edit = 'edit',\n}\n\nconst VOICE_RECORDING_FILENAME = 'wonderful-voice-message.ogg';\n// When voice recording is active, composer placeholder will hide to prevent overlapping\nconst SCREEN_WIDTH_TO_HIDE_PLACEHOLDER = 600; // px\n\nconst MOBILE_KEYBOARD_HIDE_DELAY_MS = 100;\nconst SELECT_MODE_TRANSITION_MS = 200;\nconst MESSAGE_MAX_LENGTH = 4096;\nconst CAPTION_MAX_LENGTH = 1024;\nconst SENDING_ANIMATION_DURATION = 350;\n// eslint-disable-next-line max-len\nconst APPENDIX = '';\n\nconst Composer: FC = ({\n dropAreaState,\n shouldSchedule,\n canScheduleUntilOnline,\n isReady,\n onDropHide,\n editingMessage,\n chatId,\n threadId,\n messageListType,\n draft,\n chat,\n connectionState,\n isChatWithBot,\n isChatWithSelf,\n isRightColumnShown,\n isSelectModeActive,\n isForwarding,\n isPollModalOpen,\n botKeyboardMessageId,\n botKeyboardPlaceholder,\n withScheduledButton,\n stickersForEmoji,\n groupChatMembers,\n topInlineBotIds,\n currentUserId,\n usersById,\n lastSyncTime,\n contentToBeScheduled,\n shouldSuggestStickers,\n baseEmojiKeywords,\n emojiKeywords,\n serverTimeOffset,\n recentEmojis,\n inlineBots,\n isInlineBotLoading,\n botCommands,\n chatBotCommands,\n sendAsUser,\n sendAsChat,\n sendAsId,\n}) => {\n const {\n sendMessage,\n clearDraft,\n showDialog,\n setStickerSearchQuery,\n setGifSearchQuery,\n forwardMessages,\n openPollModal,\n closePollModal,\n loadScheduledHistory,\n openChat,\n addRecentEmoji,\n sendInlineBotResult,\n loadSendAs,\n } = getDispatch();\n const lang = useLang();\n\n // eslint-disable-next-line no-null/no-null\n const appendixRef = useRef(null);\n const [html, setHtml] = useState('');\n const lastMessageSendTimeSeconds = useRef();\n const prevDropAreaState = usePrevious(dropAreaState);\n const [isCalendarOpen, openCalendar, closeCalendar] = useFlag();\n const [\n scheduledMessageArgs, setScheduledMessageArgs,\n ] = useState();\n const { width: windowWidth } = windowSize.get();\n const sendAsIds = chat?.sendAsIds;\n const sendMessageAction = useSendMessageAction(chatId, threadId);\n\n // Cache for frequently updated state\n const htmlRef = useRef(html);\n useEffect(() => {\n htmlRef.current = html;\n }, [html]);\n\n useEffect(() => {\n lastMessageSendTimeSeconds.current = undefined;\n }, [chatId]);\n\n useEffect(() => {\n if (chatId && lastSyncTime && threadId === MAIN_THREAD_ID && isReady) {\n loadScheduledHistory({ chatId });\n }\n }, [isReady, chatId, loadScheduledHistory, lastSyncTime, threadId]);\n\n useEffect(() => {\n if (chatId && chat && lastSyncTime && !sendAsIds && isReady && isChatSuperGroup(chat)) {\n loadSendAs({ chatId });\n }\n }, [chat, chatId, isReady, lastSyncTime, loadSendAs, sendAsIds]);\n\n const shouldAnimateSendAsButtonRef = useRef(false);\n useOnChange(([prevChatId, prevSendAsIds]) => {\n // We only animate send-as button if `sendAsIds` was missing when opening the chat\n shouldAnimateSendAsButtonRef.current = Boolean(chatId === prevChatId && sendAsIds && !prevSendAsIds);\n }, [chatId, sendAsIds]);\n\n useLayoutEffect(() => {\n if (!appendixRef.current) return;\n\n appendixRef.current.innerHTML = APPENDIX;\n }, []);\n\n useEffect(() => {\n if (contentToBeScheduled) {\n setScheduledMessageArgs(contentToBeScheduled);\n openCalendar();\n }\n }, [contentToBeScheduled, openCalendar]);\n\n const [attachments, setAttachments] = useState([]);\n\n const [isBotKeyboardOpen, openBotKeyboard, closeBotKeyboard] = useFlag();\n const [isBotCommandMenuOpen, openBotCommandMenu, closeBotCommandMenu] = useFlag();\n const [isAttachMenuOpen, openAttachMenu, closeAttachMenu] = useFlag();\n const [isSymbolMenuOpen, openSymbolMenu, closeSymbolMenu] = useFlag();\n const [isSendAsMenuOpen, openSendAsMenu, closeSendAsMenu] = useFlag();\n const [isDeleteModalOpen, openDeleteModal, closeDeleteModal] = useFlag();\n const [isSymbolMenuLoaded, onSymbolMenuLoadingComplete] = useFlag();\n const [isHoverDisabled, disableHover, enableHover] = useFlag();\n\n const {\n startRecordingVoice,\n stopRecordingVoice,\n pauseRecordingVoice,\n activeVoiceRecording,\n currentRecordTime,\n recordButtonRef: mainButtonRef,\n startRecordTimeRef,\n } = useVoiceRecording();\n\n useInterval(() => {\n sendMessageAction({ type: 'recordAudio' });\n }, activeVoiceRecording && SEND_MESSAGE_ACTION_INTERVAL);\n\n useEffect(() => {\n if (!activeVoiceRecording) {\n sendMessageAction({ type: 'cancel' });\n }\n }, [activeVoiceRecording, sendMessageAction]);\n\n const mainButtonState = editingMessage\n ? MainButtonState.Edit\n : !IS_VOICE_RECORDING_SUPPORTED || activeVoiceRecording || (html && !attachments.length) || isForwarding\n ? MainButtonState.Send\n : MainButtonState.Record;\n const canShowCustomSendMenu = !shouldSchedule;\n\n const {\n isMentionTooltipOpen, closeMentionTooltip, insertMention, mentionFilteredUsers,\n } = useMentionTooltip(\n !attachments.length,\n html,\n setHtml,\n undefined,\n groupChatMembers,\n topInlineBotIds,\n currentUserId,\n );\n\n const {\n isOpen: isInlineBotTooltipOpen,\n id: inlineBotId,\n isGallery: isInlineBotTooltipGallery,\n switchPm: inlineBotSwitchPm,\n results: inlineBotResults,\n closeTooltip: closeInlineBotTooltip,\n help: inlineBotHelp,\n loadMore: loadMoreForInlineBot,\n } = useInlineBotTooltip(\n Boolean(!attachments.length && lastSyncTime),\n chatId,\n html,\n inlineBots,\n );\n\n const {\n isOpen: isBotCommandTooltipOpen,\n close: closeBotCommandTooltip,\n filteredBotCommands: botTooltipCommands,\n } = useBotCommandTooltip(\n Boolean((botCommands && botCommands.length) || (chatBotCommands && chatBotCommands.length)),\n html,\n botCommands,\n chatBotCommands,\n );\n\n const {\n isContextMenuOpen: isCustomSendMenuOpen,\n handleContextMenu,\n handleContextMenuClose,\n handleContextMenuHide,\n } = useContextMenuHandlers(mainButtonRef, !(mainButtonState === MainButtonState.Send && canShowCustomSendMenu));\n\n const allowedAttachmentOptions = useMemo(() => {\n return getAllowedAttachmentOptions(chat, isChatWithBot);\n }, [chat, isChatWithBot]);\n\n const isAdmin = chat && isChatAdmin(chat);\n const slowMode = getChatSlowModeOptions(chat);\n\n const { isStickerTooltipOpen, closeStickerTooltip } = useStickerTooltip(\n Boolean(shouldSuggestStickers && allowedAttachmentOptions.canSendStickers && !attachments.length),\n html,\n stickersForEmoji,\n !isReady,\n );\n const {\n isEmojiTooltipOpen, closeEmojiTooltip, filteredEmojis, insertEmoji,\n } = useEmojiTooltip(\n Boolean(shouldSuggestStickers && allowedAttachmentOptions.canSendStickers && !attachments.length),\n html,\n recentEmojis,\n undefined,\n setHtml,\n baseEmojiKeywords,\n emojiKeywords,\n !isReady,\n );\n\n const insertTextAndUpdateCursor = useCallback((text: string, inputId: string = EDITABLE_INPUT_ID) => {\n const selection = window.getSelection()!;\n const messageInput = document.getElementById(inputId)!;\n const newHtml = renderText(text, ['escape_html', 'emoji_html', 'br_html'])\n .join('')\n .replace(/\\u200b+/g, '\\u200b');\n\n if (selection.rangeCount) {\n const selectionRange = selection.getRangeAt(0);\n if (isSelectionInsideInput(selectionRange, inputId)) {\n insertHtmlInSelection(newHtml);\n messageInput.dispatchEvent(new Event('input', { bubbles: true }));\n return;\n }\n }\n\n setHtml(`${htmlRef.current!}${newHtml}`);\n\n // If selection is outside of input, set cursor at the end of input\n requestAnimationFrame(() => {\n focusEditableElement(messageInput);\n });\n }, []);\n\n const removeSymbol = useCallback(() => {\n const selection = window.getSelection()!;\n\n if (selection.rangeCount) {\n const selectionRange = selection.getRangeAt(0);\n if (isSelectionInsideInput(selectionRange, EDITABLE_INPUT_ID)) {\n document.execCommand('delete', false);\n return;\n }\n }\n\n setHtml(deleteLastCharacterOutsideSelection(htmlRef.current!));\n }, []);\n\n const resetComposer = useCallback((shouldPreserveInput = false) => {\n if (!shouldPreserveInput) {\n setHtml('');\n }\n setAttachments([]);\n closeStickerTooltip();\n closeCalendar();\n setScheduledMessageArgs(undefined);\n closeMentionTooltip();\n closeEmojiTooltip();\n\n if (IS_SINGLE_COLUMN_LAYOUT) {\n // @optimization\n setTimeout(() => closeSymbolMenu(), SENDING_ANIMATION_DURATION);\n } else {\n closeSymbolMenu();\n }\n }, [closeStickerTooltip, closeCalendar, closeMentionTooltip, closeEmojiTooltip, closeSymbolMenu]);\n\n // Handle chat change (ref is used to avoid redundant effect calls)\n const stopRecordingVoiceRef = useRef();\n stopRecordingVoiceRef.current = stopRecordingVoice;\n useEffect(() => {\n return () => {\n stopRecordingVoiceRef.current!();\n resetComposer();\n };\n }, [chatId, resetComposer, stopRecordingVoiceRef]);\n\n const handleEditComplete = useEditing(htmlRef, setHtml, editingMessage, resetComposer, openDeleteModal);\n useDraft(draft, chatId, threadId, html, htmlRef, setHtml, editingMessage);\n useClipboardPaste(insertTextAndUpdateCursor, setAttachments, editingMessage);\n\n const handleFileSelect = useCallback(async (files: File[], isQuick: boolean) => {\n setAttachments(await Promise.all(files.map((file) => buildAttachment(file.name, file, isQuick))));\n }, []);\n\n const handleAppendFiles = useCallback(async (files: File[], isQuick: boolean) => {\n setAttachments([\n ...attachments,\n ...await Promise.all(files.map((file) => buildAttachment(file.name, file, isQuick))),\n ]);\n }, [attachments]);\n\n const handleClearAttachment = useCallback(() => {\n setAttachments([]);\n }, []);\n\n const handleSend = useCallback(async (isSilent = false, scheduledAt?: number) => {\n if (connectionState !== 'connectionStateReady') {\n return;\n }\n\n let currentAttachments = attachments;\n\n if (activeVoiceRecording) {\n const record = await stopRecordingVoice();\n if (record) {\n const { blob, duration, waveform } = record;\n currentAttachments = [await buildAttachment(\n VOICE_RECORDING_FILENAME,\n blob,\n false,\n { voice: { duration, waveform } },\n )];\n }\n }\n\n const { text, entities } = parseMessageInput(htmlRef.current!);\n\n if (!currentAttachments.length && !text && !isForwarding) {\n return;\n }\n\n const maxLength = currentAttachments.length ? CAPTION_MAX_LENGTH : MESSAGE_MAX_LENGTH;\n if (text?.length > maxLength) {\n const extraLength = text.length - maxLength;\n showDialog({\n data: {\n message: 'MESSAGE_TOO_LONG_PLEASE_REMOVE_CHARACTERS',\n textParams: {\n '{EXTRA_CHARS_COUNT}': extraLength,\n '{PLURAL_S}': extraLength > 1 ? 's' : '',\n },\n hasErrorKey: true,\n },\n });\n\n return;\n }\n\n const messageInput = document.getElementById(EDITABLE_INPUT_ID)!;\n\n if (currentAttachments.length || text) {\n if (slowMode && !isAdmin) {\n const nowSeconds = getServerTime(serverTimeOffset);\n const secondsSinceLastMessage = lastMessageSendTimeSeconds.current\n && Math.floor(nowSeconds - lastMessageSendTimeSeconds.current);\n const nextSendDateNotReached = slowMode.nextSendDate && slowMode.nextSendDate > nowSeconds;\n\n if (\n (secondsSinceLastMessage && secondsSinceLastMessage < slowMode.seconds)\n || nextSendDateNotReached\n ) {\n const secondsRemaining = nextSendDateNotReached\n ? slowMode.nextSendDate! - nowSeconds\n : slowMode.seconds - secondsSinceLastMessage!;\n showDialog({\n data: {\n message: lang('SlowModeHint', formatMediaDuration(secondsRemaining)),\n isSlowMode: true,\n hasErrorKey: false,\n },\n });\n\n messageInput.blur();\n\n return;\n }\n }\n\n sendMessage({\n text,\n entities,\n attachments: currentAttachments,\n scheduledAt,\n isSilent,\n });\n }\n\n if (isForwarding) {\n forwardMessages({\n scheduledAt,\n isSilent,\n });\n }\n\n lastMessageSendTimeSeconds.current = getServerTime(serverTimeOffset);\n\n clearDraft({ chatId, localOnly: true });\n\n if (IS_IOS && messageInput === document.activeElement) {\n applyIosAutoCapitalizationFix(messageInput);\n }\n\n // Wait until message animation starts\n requestAnimationFrame(() => {\n resetComposer();\n });\n }, [\n connectionState, attachments, activeVoiceRecording, isForwarding, clearDraft, chatId, serverTimeOffset,\n resetComposer, stopRecordingVoice, showDialog, slowMode, isAdmin, sendMessage, forwardMessages, lang,\n ]);\n\n const handleActivateBotCommandMenu = useCallback(() => {\n closeSymbolMenu();\n openBotCommandMenu();\n }, [closeSymbolMenu, openBotCommandMenu]);\n\n const handleActivateSymbolMenu = useCallback(() => {\n closeBotCommandMenu();\n closeSendAsMenu();\n openSymbolMenu();\n }, [closeBotCommandMenu, closeSendAsMenu, openSymbolMenu]);\n\n const handleStickerSelect = useCallback((sticker: ApiSticker, shouldPreserveInput = false) => {\n sticker = {\n ...sticker,\n isPreloadedGlobally: true,\n };\n\n if (shouldSchedule) {\n setScheduledMessageArgs({ sticker });\n openCalendar();\n } else {\n sendMessage({ sticker });\n requestAnimationFrame(() => {\n resetComposer(shouldPreserveInput);\n });\n }\n }, [shouldSchedule, openCalendar, sendMessage, resetComposer]);\n\n const handleGifSelect = useCallback((gif: ApiVideo) => {\n if (shouldSchedule) {\n setScheduledMessageArgs({ gif });\n openCalendar();\n } else {\n sendMessage({ gif });\n requestAnimationFrame(() => {\n resetComposer(true);\n });\n }\n }, [shouldSchedule, openCalendar, sendMessage, resetComposer]);\n\n const handleInlineBotSelect = useCallback((inlineResult: ApiBotInlineResult | ApiBotInlineMediaResult) => {\n if (connectionState !== 'connectionStateReady') {\n return;\n }\n\n sendInlineBotResult({\n id: inlineResult.id,\n queryId: inlineResult.queryId,\n });\n\n const messageInput = document.getElementById(EDITABLE_INPUT_ID)!;\n if (IS_IOS && messageInput === document.activeElement) {\n applyIosAutoCapitalizationFix(messageInput);\n }\n\n clearDraft({ chatId, localOnly: true });\n requestAnimationFrame(() => {\n resetComposer();\n });\n }, [chatId, clearDraft, connectionState, resetComposer, sendInlineBotResult]);\n\n const handleBotCommandSelect = useCallback(() => {\n clearDraft({ chatId, localOnly: true });\n requestAnimationFrame(() => {\n resetComposer();\n });\n }, [chatId, clearDraft, resetComposer]);\n\n const handlePollSend = useCallback((poll: ApiNewPoll) => {\n if (shouldSchedule) {\n setScheduledMessageArgs({ poll });\n closePollModal();\n openCalendar();\n } else {\n sendMessage({ poll });\n closePollModal();\n }\n }, [closePollModal, openCalendar, sendMessage, shouldSchedule]);\n\n const handleSilentSend = useCallback(() => {\n if (shouldSchedule) {\n setScheduledMessageArgs({ isSilent: true });\n openCalendar();\n } else {\n void handleSend(true);\n }\n }, [handleSend, openCalendar, shouldSchedule]);\n\n const handleMessageSchedule = useCallback((date: Date, isWhenOnline = false) => {\n const { isSilent, ...restArgs } = scheduledMessageArgs || {};\n\n // Scheduled time can not be less than 10 seconds in future\n const scheduledAt = Math.round(Math.max(date.getTime(), Date.now() + 60 * 1000) / 1000)\n + (isWhenOnline ? 0 : serverTimeOffset);\n\n if (!scheduledMessageArgs || Object.keys(restArgs).length === 0) {\n void handleSend(!!isSilent, scheduledAt);\n } else {\n sendMessage({\n ...scheduledMessageArgs,\n scheduledAt,\n });\n requestAnimationFrame(() => {\n resetComposer();\n });\n }\n closeCalendar();\n }, [closeCalendar, handleSend, resetComposer, scheduledMessageArgs, sendMessage, serverTimeOffset]);\n\n const handleMessageScheduleUntilOnline = useCallback(() => {\n handleMessageSchedule(new Date(SCHEDULED_WHEN_ONLINE * 1000), true);\n }, [handleMessageSchedule]);\n\n const handleCloseCalendar = useCallback(() => {\n closeCalendar();\n setScheduledMessageArgs(undefined);\n }, [closeCalendar]);\n\n const handleSearchOpen = useCallback((type: 'stickers' | 'gifs') => {\n if (type === 'stickers') {\n setStickerSearchQuery({ query: '' });\n setGifSearchQuery({ query: undefined });\n } else {\n setGifSearchQuery({ query: '' });\n setStickerSearchQuery({ query: undefined });\n }\n }, [setStickerSearchQuery, setGifSearchQuery]);\n\n const handleSymbolMenuOpen = useCallback(() => {\n const messageInput = document.getElementById(EDITABLE_INPUT_ID)!;\n\n if (!IS_SINGLE_COLUMN_LAYOUT || messageInput !== document.activeElement) {\n openSymbolMenu();\n return;\n }\n\n messageInput.blur();\n setTimeout(() => {\n closeBotCommandMenu();\n openSymbolMenu();\n }, MOBILE_KEYBOARD_HIDE_DELAY_MS);\n }, [openSymbolMenu, closeBotCommandMenu]);\n\n const handleSendAsMenuOpen = useCallback(() => {\n const messageInput = document.getElementById(EDITABLE_INPUT_ID)!;\n\n if (!IS_SINGLE_COLUMN_LAYOUT || messageInput !== document.activeElement) {\n closeBotCommandMenu();\n closeSymbolMenu();\n openSendAsMenu();\n return;\n }\n\n messageInput.blur();\n setTimeout(() => {\n closeBotCommandMenu();\n closeSymbolMenu();\n openSendAsMenu();\n }, MOBILE_KEYBOARD_HIDE_DELAY_MS);\n }, [closeBotCommandMenu, closeSymbolMenu, openSendAsMenu]);\n\n const handleAllScheduledClick = useCallback(() => {\n openChat({ id: chatId, threadId, type: 'scheduled' });\n }, [openChat, chatId, threadId]);\n\n useEffect(() => {\n if (isRightColumnShown && IS_SINGLE_COLUMN_LAYOUT) {\n closeSymbolMenu();\n }\n }, [isRightColumnShown, closeSymbolMenu]);\n\n useEffect(() => {\n if (!isReady) return;\n\n if (isSelectModeActive) {\n disableHover();\n } else {\n setTimeout(() => {\n enableHover();\n }, SELECT_MODE_TRANSITION_MS);\n }\n }, [isSelectModeActive, enableHover, disableHover, isReady]);\n\n const mainButtonHandler = useCallback(() => {\n switch (mainButtonState) {\n case MainButtonState.Send:\n if (shouldSchedule) {\n if (activeVoiceRecording) {\n pauseRecordingVoice();\n }\n openCalendar();\n } else {\n void handleSend();\n }\n break;\n case MainButtonState.Record:\n void startRecordingVoice();\n break;\n case MainButtonState.Edit:\n handleEditComplete();\n break;\n default:\n break;\n }\n }, [\n mainButtonState, shouldSchedule, startRecordingVoice, handleEditComplete,\n activeVoiceRecording, openCalendar, pauseRecordingVoice, handleSend,\n ]);\n\n const areVoiceMessagesNotAllowed = mainButtonState === MainButtonState.Record\n && !allowedAttachmentOptions.canAttachMedia;\n\n const prevEditedMessage = usePrevious(editingMessage, true);\n const renderedEditedMessage = editingMessage || prevEditedMessage;\n\n const scheduledDefaultDate = new Date();\n scheduledDefaultDate.setSeconds(0);\n scheduledDefaultDate.setMilliseconds(0);\n\n const scheduledMaxDate = new Date();\n scheduledMaxDate.setFullYear(scheduledMaxDate.getFullYear() + 1);\n\n let sendButtonAriaLabel = 'SendMessage';\n switch (mainButtonState) {\n case MainButtonState.Edit:\n sendButtonAriaLabel = 'Save edited message';\n break;\n case MainButtonState.Record:\n sendButtonAriaLabel = areVoiceMessagesNotAllowed\n ? 'Conversation.DefaultRestrictedMedia'\n : 'AccDescrVoiceMessage';\n }\n\n const className = buildClassName(\n 'Composer',\n !isSelectModeActive && 'shown',\n isHoverDisabled && 'hover-disabled',\n );\n\n const symbolMenuButtonClassName = buildClassName(\n 'mobile-symbol-menu-button',\n !isReady && 'not-ready',\n isSymbolMenuLoaded\n ? (isSymbolMenuOpen && 'menu-opened')\n : (isSymbolMenuOpen && 'is-loading'),\n );\n\n const onSend = mainButtonState === MainButtonState.Edit\n ? handleEditComplete\n : (shouldSchedule ? openCalendar : handleSend);\n\n return (\n
\n {allowedAttachmentOptions.canAttachMedia && isReady && (\n \n \n \n )}\n \n \n {renderedEditedMessage && (\n \n )}\n \n \n \n \n
\n
\n \n \n
\n {isChatWithBot && botCommands !== false && !activeVoiceRecording && !editingMessage && (\n \n \n \n )}\n {!!sendAsIds?.length && (sendAsUser || sendAsChat) && (\n \n \n \n )}\n {IS_SINGLE_COLUMN_LAYOUT ? (\n \n \n \n {isSymbolMenuOpen && !isSymbolMenuLoaded && }\n \n ) : (\n \n \n \n )}\n \n {isInlineBotLoading && Boolean(inlineBotId) && (\n \n )}\n {withScheduledButton && (\n \n \n \n )}\n {botKeyboardMessageId && !activeVoiceRecording && !editingMessage && (\n \n \n \n )}\n {!activeVoiceRecording && !editingMessage && (\n \n \n \n )}\n {activeVoiceRecording && currentRecordTime && (\n \n {formatVoiceRecordDuration(currentRecordTime - startRecordTimeRef.current!)}\n \n )}\n \n \n \n {botKeyboardMessageId && (\n \n )}\n {botCommands && (\n \n )}\n \n
\n
\n {activeVoiceRecording && (\n \n \n \n )}\n \n \n \n \n \n {canShowCustomSendMenu && (\n \n )}\n \n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { chatId, threadId, messageListType }): StateProps => {\n const chat = selectChat(global, chatId);\n const chatUser = chat && selectChatUser(global, chat);\n const chatBot = chatId !== REPLIES_USER_ID ? selectChatBot(global, chatId) : undefined;\n const isChatWithBot = Boolean(chatBot);\n const isChatWithSelf = selectIsChatWithSelf(global, chatId);\n const messageWithActualBotKeyboard = isChatWithBot && selectNewestMessageWithBotKeyboardButtons(global, chatId);\n const scheduledIds = selectScheduledIds(global, chatId);\n const { language, shouldSuggestStickers } = global.settings.byKey;\n const baseEmojiKeywords = global.emojiKeywords[BASE_EMOJI_KEYWORD_LANG];\n const emojiKeywords = language !== BASE_EMOJI_KEYWORD_LANG ? global.emojiKeywords[language] : undefined;\n const botKeyboardMessageId = messageWithActualBotKeyboard ? messageWithActualBotKeyboard.id : undefined;\n const keyboardMessage = botKeyboardMessageId ? selectChatMessage(global, chatId, botKeyboardMessageId) : undefined;\n const usersById = global.users.byId;\n const chatsById = global.chats.byId;\n const { currentUserId } = global;\n const sendAsId = chat?.fullInfo ? chat?.fullInfo?.sendAsId || currentUserId : undefined;\n const sendAsUser = sendAsId ? usersById?.[sendAsId] : undefined;\n const sendAsChat = !sendAsUser && sendAsId ? chatsById?.[sendAsId] : undefined;\n\n return {\n editingMessage: selectEditingMessage(global, chatId, threadId, messageListType),\n connectionState: global.connectionState,\n draft: selectDraft(global, chatId, threadId),\n chat,\n isChatWithBot,\n isChatWithSelf,\n canScheduleUntilOnline: Boolean(\n !isChatWithSelf && !isChatWithBot && chat && chatUser\n && isUserId(chatId) && selectUserStatus(global, chatId)?.wasOnline,\n ),\n isRightColumnShown: selectIsRightColumnShown(global),\n isSelectModeActive: selectIsInSelectMode(global),\n withScheduledButton: (\n threadId === MAIN_THREAD_ID\n && messageListType === 'thread'\n && Boolean(scheduledIds?.length)\n ),\n shouldSchedule: messageListType === 'scheduled',\n botKeyboardMessageId,\n botKeyboardPlaceholder: keyboardMessage?.keyboardPlaceholder,\n isForwarding: chatId === global.forwardMessages.toChatId,\n isPollModalOpen: global.isPollModalOpen,\n stickersForEmoji: global.stickers.forEmoji.stickers,\n groupChatMembers: chat?.fullInfo?.members,\n topInlineBotIds: global.topInlineBots?.userIds,\n currentUserId,\n usersById,\n lastSyncTime: global.lastSyncTime,\n contentToBeScheduled: global.messages.contentToBeScheduled,\n shouldSuggestStickers,\n recentEmojis: global.recentEmojis,\n baseEmojiKeywords: baseEmojiKeywords?.keywords,\n emojiKeywords: emojiKeywords?.keywords,\n serverTimeOffset: global.serverTimeOffset,\n inlineBots: global.inlineBots.byUsername,\n isInlineBotLoading: global.inlineBots.isLoading,\n chatBotCommands: chat && chat.fullInfo && chat.fullInfo.botCommands,\n botCommands: chatBot && chatBot.fullInfo ? (chatBot.fullInfo.botCommands || false) : undefined,\n sendAsUser,\n sendAsChat,\n sendAsId,\n };\n },\n)(Composer));\n","import { useEffect, useMemo } from '../../../../lib/teact/teact';\nimport { getDispatch } from '../../../../lib/teact/teactn';\n\nimport { ApiSticker } from '../../../../api/types';\n\nimport { IS_EMOJI_SUPPORTED } from '../../../../util/environment';\n\nimport parseEmojiOnlyString from '../../../common/helpers/parseEmojiOnlyString';\nimport { prepareForRegExp } from '../helpers/prepareForRegExp';\n\nexport default function useStickerTooltip(\n isAllowed: boolean,\n html: string,\n stickers?: ApiSticker[],\n isDisabled = false,\n) {\n const cleanHtml = useMemo(() => prepareForRegExp(html).trim(), [html]);\n const { loadStickersForEmoji, clearStickersForEmoji } = getDispatch();\n const isSingleEmoji = (\n (IS_EMOJI_SUPPORTED && parseEmojiOnlyString(cleanHtml) === 1)\n || (!IS_EMOJI_SUPPORTED && Boolean(html.match(/^]*?>$/g)))\n );\n const hasStickers = Boolean(stickers) && isSingleEmoji;\n\n useEffect(() => {\n if (isDisabled) return;\n\n if (isAllowed && isSingleEmoji) {\n loadStickersForEmoji({\n emoji: IS_EMOJI_SUPPORTED ? cleanHtml : cleanHtml.match(/alt=\"(.+)\"/)?.[1],\n });\n } else if (hasStickers || !isSingleEmoji) {\n clearStickersForEmoji();\n }\n // We omit `hasStickers` here to prevent re-fetching after manually closing tooltip (via ).\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [html, isSingleEmoji, clearStickersForEmoji, loadStickersForEmoji, isAllowed, isDisabled]);\n\n return {\n isStickerTooltipOpen: hasStickers,\n closeStickerTooltip: clearStickersForEmoji,\n };\n}\n","export default function insertHtmlInSelection(html: string) {\n const selection = window.getSelection();\n\n if (selection?.getRangeAt && selection.rangeCount) {\n const range = selection.getRangeAt(0);\n range.deleteContents();\n\n const fragment = range.createContextualFragment(html);\n const lastInsertedNode = fragment.lastChild;\n range.insertNode(fragment);\n if (lastInsertedNode) {\n range.setStartAfter(lastInsertedNode);\n range.setEndAfter(lastInsertedNode);\n } else {\n range.collapse(false);\n }\n selection.removeAllRanges();\n selection.addRange(range);\n }\n}\n","export default function deleteLastCharacterOutsideSelection(html: string) {\n const tempInput = document.createElement('div');\n tempInput.contentEditable = 'true';\n tempInput.style.position = 'absolute';\n tempInput.style.left = '-10000px';\n tempInput.style.top = '-10000px';\n tempInput.innerHTML = html;\n document.body.appendChild(tempInput);\n let element = tempInput.lastChild!;\n\n if (element.lastChild) {\n // Selects the last and the deepest child of the element.\n while (element.lastChild) {\n element = element.lastChild;\n }\n }\n\n // Gets length of the element's content.\n const textLength = element.textContent!.length;\n const range = document.createRange();\n const selection = window.getSelection()!;\n\n // Sets selection position to the end of the element.\n range.setStart(element, textLength);\n range.setEnd(element, textLength);\n selection.removeAllRanges();\n selection.addRange(range);\n document.execCommand('delete', false);\n\n const result = tempInput.innerHTML;\n document.body.removeChild(tempInput);\n\n return result;\n}\n","import { useCallback, useEffect } from '../../../../lib/teact/teact';\nimport { getDispatch } from '../../../../lib/teact/teactn';\n\nimport { ApiMessage } from '../../../../api/types';\n\nimport { EDITABLE_INPUT_ID } from '../../../../config';\nimport parseMessageInput from '../../../../util/parseMessageInput';\nimport getMessageTextAsHtml from '../helpers/getMessageTextAsHtml';\nimport focusEditableElement from '../../../../util/focusEditableElement';\nimport { hasMessageMedia } from '../../../../modules/helpers';\n\nexport default (\n htmlRef: { current: string },\n setHtml: (html: string) => void,\n editedMessage: ApiMessage | undefined,\n resetComposer: () => void,\n openDeleteModal: () => void,\n) => {\n const { editMessage } = getDispatch();\n\n // TODO useOnChange\n // Handle editing message\n useEffect(() => {\n if (!editedMessage) {\n setHtml('');\n return;\n }\n\n setHtml(getMessageTextAsHtml(editedMessage.content.text));\n\n requestAnimationFrame(() => {\n const messageInput = document.getElementById(EDITABLE_INPUT_ID)!;\n focusEditableElement(messageInput, true);\n });\n }, [editedMessage, setHtml]);\n\n const handleEditComplete = useCallback(() => {\n const { text, entities } = parseMessageInput(htmlRef.current!);\n\n if (!editedMessage) {\n return;\n }\n\n if (!text && !hasMessageMedia(editedMessage)) {\n openDeleteModal();\n return;\n }\n\n editMessage({\n messageId: editedMessage.id,\n text,\n entities,\n });\n\n resetComposer();\n }, [editMessage, editedMessage, htmlRef, openDeleteModal, resetComposer]);\n\n return handleEditComplete;\n};\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './MobileSearch';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst MobileSearchAsync: FC = (props) => {\n const { isActive } = props;\n const MobileSearch = useModuleLoader(Bundles.Extra, 'MobileSearch', !isActive, true);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return MobileSearch ? : undefined;\n};\n\nexport default memo(MobileSearchAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\nimport { OwnProps } from './MessageSelectToolbar';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst MessageSelectToolbarAsync: FC = (props) => {\n const { isActive } = props;\n const MessageSelectToolbar = useModuleLoader(Bundles.Extra, 'MessageSelectToolbar', !isActive);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return MessageSelectToolbar ? : undefined;\n};\n\nexport default memo(MessageSelectToolbarAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './UnpinAllMessagesModal';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst UnpinAllMessagesModalAsync: FC = (props) => {\n const { isOpen } = props;\n const UnpinAllMessagesModal = useModuleLoader(Bundles.Extra, 'UnpinAllMessagesModal', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return UnpinAllMessagesModal ? : undefined;\n};\n\nexport default memo(UnpinAllMessagesModalAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './PaymentModal';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst PaymentModalAsync: FC = (props) => {\n const { isOpen } = props;\n const PaymentModal = useModuleLoader(Bundles.Extra, 'PaymentModal', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return PaymentModal ? : undefined;\n};\n\nexport default memo(PaymentModalAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './ReceiptModal';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst ReceiptModalAsync: FC = (props) => {\n const { isOpen } = props;\n const ReceiptModal = useModuleLoader(Bundles.Extra, 'ReceiptModal', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return ReceiptModal ? : undefined;\n};\n\nexport default memo(ReceiptModalAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './SeenByModal';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst SeenByModalAsync: FC = (props) => {\n const { isOpen } = props;\n const SeenByModal = useModuleLoader(Bundles.Extra, 'SeenByModal', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return SeenByModal ? : undefined;\n};\n\nexport default memo(SeenByModalAsync);\n","import React, {\n FC, useEffect, useState, memo, useMemo, useCallback,\n} from '../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiChatBannedRights, MAIN_THREAD_ID } from '../../api/types';\nimport { MessageListType, MessageList as GlobalMessageList } from '../../global/types';\nimport { ThemeKey } from '../../types';\n\nimport {\n MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN,\n MOBILE_SCREEN_MAX_WIDTH,\n MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN,\n SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN,\n SAFE_SCREEN_WIDTH_FOR_CHAT_INFO,\n ANIMATION_LEVEL_MAX,\n ANIMATION_END_DELAY,\n DARK_THEME_BG_COLOR,\n LIGHT_THEME_BG_COLOR,\n ANIMATION_LEVEL_MIN,\n SUPPORTED_IMAGE_CONTENT_TYPES,\n} from '../../config';\nimport {\n IS_SINGLE_COLUMN_LAYOUT,\n IS_TABLET_COLUMN_LAYOUT,\n IS_TOUCH_ENV,\n MASK_IMAGE_DISABLED,\n} from '../../util/environment';\nimport { DropAreaState } from './composer/DropArea';\nimport {\n selectChat,\n selectChatBot,\n selectCurrentMessageList,\n selectCurrentTextSearch,\n selectIsChatBotNotStarted,\n selectIsInSelectMode,\n selectIsRightColumnShown,\n selectIsUserBlocked,\n selectPinnedIds,\n selectTheme,\n} from '../../modules/selectors';\nimport {\n getCanPostInChat, getMessageSendingRestrictionReason, isChatChannel, isChatSuperGroup, isUserId,\n} from '../../modules/helpers';\nimport captureEscKeyListener from '../../util/captureEscKeyListener';\nimport buildClassName from '../../util/buildClassName';\nimport { createMessageHash } from '../../util/routing';\nimport useCustomBackground from '../../hooks/useCustomBackground';\nimport useWindowSize from '../../hooks/useWindowSize';\nimport usePrevDuringAnimation from '../../hooks/usePrevDuringAnimation';\nimport useLang from '../../hooks/useLang';\nimport useHistoryBack from '../../hooks/useHistoryBack';\nimport usePrevious from '../../hooks/usePrevious';\nimport useForceUpdate from '../../hooks/useForceUpdate';\nimport useOnChange from '../../hooks/useOnChange';\nimport calculateMiddleFooterTransforms from './helpers/calculateMiddleFooterTransforms';\n\nimport Transition from '../ui/Transition';\nimport MiddleHeader from './MiddleHeader';\nimport MessageList from './MessageList';\nimport ScrollDownButton from './ScrollDownButton';\nimport Composer from './composer/Composer';\nimport Button from '../ui/Button';\nimport MobileSearch from './MobileSearch.async';\nimport MessageSelectToolbar from './MessageSelectToolbar.async';\nimport UnpinAllMessagesModal from '../common/UnpinAllMessagesModal.async';\nimport PaymentModal from '../payment/PaymentModal.async';\nimport ReceiptModal from '../payment/ReceiptModal.async';\nimport SeenByModal from '../common/SeenByModal.async';\n\nimport './MiddleColumn.scss';\n\ntype StateProps = {\n chatId?: string;\n threadId?: number;\n messageListType?: MessageListType;\n isPrivate?: boolean;\n isPinnedMessageList?: boolean;\n isScheduledMessageList?: boolean;\n canPost?: boolean;\n currentUserBannedRights?: ApiChatBannedRights;\n defaultBannedRights?: ApiChatBannedRights;\n hasPinnedOrAudioPlayer?: boolean;\n pinnedMessagesCount?: number;\n theme: ThemeKey;\n customBackground?: string;\n backgroundColor?: string;\n patternColor?: string;\n isLeftColumnShown?: boolean;\n isRightColumnShown?: boolean;\n isBackgroundBlurred?: boolean;\n isMobileSearchActive?: boolean;\n isSelectModeActive?: boolean;\n isPaymentModalOpen?: boolean;\n isReceiptModalOpen?: boolean;\n isSeenByModalOpen: boolean;\n animationLevel?: number;\n shouldSkipHistoryAnimations?: boolean;\n currentTransitionKey: number;\n messageLists?: GlobalMessageList[];\n isChannel?: boolean;\n canSubscribe?: boolean;\n canStartBot?: boolean;\n canRestartBot?: boolean;\n};\n\nconst CLOSE_ANIMATION_DURATION = IS_SINGLE_COLUMN_LAYOUT ? 450 + ANIMATION_END_DELAY : undefined;\n\nfunction isImage(item: DataTransferItem) {\n return item.kind === 'file' && item.type && SUPPORTED_IMAGE_CONTENT_TYPES.has(item.type);\n}\n\nconst MiddleColumn: FC = ({\n chatId,\n threadId,\n messageListType,\n isPrivate,\n isPinnedMessageList,\n messageLists,\n canPost,\n currentUserBannedRights,\n defaultBannedRights,\n hasPinnedOrAudioPlayer,\n pinnedMessagesCount,\n customBackground,\n theme,\n backgroundColor,\n patternColor,\n isLeftColumnShown,\n isRightColumnShown,\n isBackgroundBlurred,\n isMobileSearchActive,\n isSelectModeActive,\n isPaymentModalOpen,\n isReceiptModalOpen,\n isSeenByModalOpen,\n animationLevel,\n shouldSkipHistoryAnimations,\n currentTransitionKey,\n isChannel,\n canSubscribe,\n canStartBot,\n canRestartBot,\n}) => {\n const {\n openChat,\n unpinAllMessages,\n loadUser,\n closeLocalTextSearch,\n exitMessageSelectMode,\n closePaymentModal,\n clearReceipt,\n joinChannel,\n sendBotCommand,\n restartBot,\n } = getDispatch();\n\n const { width: windowWidth } = useWindowSize();\n\n const lang = useLang();\n const [dropAreaState, setDropAreaState] = useState(DropAreaState.None);\n const [isFabShown, setIsFabShown] = useState();\n const [isNotchShown, setIsNotchShown] = useState();\n const [isUnpinModalOpen, setIsUnpinModalOpen] = useState(false);\n\n const hasTools = hasPinnedOrAudioPlayer && (\n windowWidth < MOBILE_SCREEN_MAX_WIDTH\n || (\n isRightColumnShown && windowWidth > MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN\n && windowWidth < SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN\n ) || (\n windowWidth >= MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN\n && windowWidth < SAFE_SCREEN_WIDTH_FOR_CHAT_INFO\n )\n );\n\n const renderingChatId = usePrevDuringAnimation(chatId, CLOSE_ANIMATION_DURATION);\n const renderingThreadId = usePrevDuringAnimation(threadId, CLOSE_ANIMATION_DURATION);\n const renderingMessageListType = usePrevDuringAnimation(messageListType, CLOSE_ANIMATION_DURATION);\n const renderingCanSubscribe = usePrevDuringAnimation(canSubscribe, CLOSE_ANIMATION_DURATION);\n const renderingCanStartBot = usePrevDuringAnimation(canStartBot, CLOSE_ANIMATION_DURATION);\n const renderingCanRestartBot = usePrevDuringAnimation(canRestartBot, CLOSE_ANIMATION_DURATION);\n const renderingCanPost = usePrevDuringAnimation(canPost, CLOSE_ANIMATION_DURATION)\n && !renderingCanRestartBot && !renderingCanStartBot && !renderingCanSubscribe;\n const renderingHasTools = usePrevDuringAnimation(hasTools, CLOSE_ANIMATION_DURATION);\n const renderingIsFabShown = usePrevDuringAnimation(isFabShown, CLOSE_ANIMATION_DURATION);\n const renderingIsChannel = usePrevDuringAnimation(isChannel, CLOSE_ANIMATION_DURATION);\n\n const prevTransitionKey = usePrevious(currentTransitionKey);\n\n const cleanupExceptionKey = (\n prevTransitionKey !== undefined && prevTransitionKey < currentTransitionKey ? prevTransitionKey : undefined\n );\n\n const { isReady, handleOpenEnd, handleSlideStop } = useIsReady(\n animationLevel, currentTransitionKey, prevTransitionKey, chatId,\n );\n\n useEffect(() => {\n return chatId\n ? captureEscKeyListener(() => {\n openChat({ id: undefined });\n })\n : undefined;\n }, [chatId, openChat]);\n\n useOnChange(() => {\n setDropAreaState(DropAreaState.None);\n setIsFabShown(undefined);\n setIsNotchShown(undefined);\n }, [chatId]);\n\n // Fix for mobile virtual keyboard\n useEffect(() => {\n const { visualViewport } = window as any;\n if (!visualViewport) {\n return undefined;\n }\n\n const handleResize = () => {\n if (window.visualViewport.height !== document.documentElement.clientHeight) {\n document.body.classList.add('keyboard-visible');\n } else {\n document.body.classList.remove('keyboard-visible');\n }\n };\n\n visualViewport.addEventListener('resize', handleResize);\n\n return () => {\n visualViewport.removeEventListener('resize', handleResize);\n };\n }, []);\n\n useEffect(() => {\n if (isPrivate) {\n loadUser({ userId: chatId });\n }\n }, [chatId, isPrivate, loadUser]);\n\n const handleDragEnter = useCallback((e: React.DragEvent) => {\n if (IS_TOUCH_ENV) {\n return;\n }\n\n const { items } = e.dataTransfer || {};\n const shouldDrawQuick = items && Array.from(items)\n // Filter unnecessary element for drag and drop images in Firefox (https://github.com/Ajaxy/telegram-tt/issues/49)\n // https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API/Recommended_drag_types#image\n .filter((item) => item.type !== 'text/uri-list')\n // As of September 2021, native clients suggest \"send quick, but compressed\" only for images\n .every(isImage);\n\n setDropAreaState(shouldDrawQuick ? DropAreaState.QuickFile : DropAreaState.Document);\n }, []);\n\n const handleHideDropArea = useCallback(() => {\n setDropAreaState(DropAreaState.None);\n }, []);\n\n const handleOpenUnpinModal = useCallback(() => {\n setIsUnpinModalOpen(true);\n }, []);\n\n const closeUnpinModal = useCallback(() => {\n setIsUnpinModalOpen(false);\n }, []);\n\n const handleUnpinAllMessages = useCallback(() => {\n unpinAllMessages({ chatId });\n closeUnpinModal();\n openChat({ id: chatId });\n }, [unpinAllMessages, openChat, closeUnpinModal, chatId]);\n\n const handleTabletFocus = useCallback(() => {\n openChat({ id: chatId });\n }, [openChat, chatId]);\n\n const handleSubscribeClick = useCallback(() => {\n joinChannel({ chatId });\n }, [joinChannel, chatId]);\n\n const handleStartBot = useCallback(() => {\n sendBotCommand({ command: '/start' });\n }, [sendBotCommand]);\n\n const handleRestartBot = useCallback(() => {\n restartBot({ chatId });\n }, [chatId, restartBot]);\n\n const customBackgroundValue = useCustomBackground(theme, customBackground);\n\n const className = buildClassName(\n renderingHasTools && 'has-header-tools',\n customBackground && 'custom-bg-image',\n backgroundColor && 'custom-bg-color',\n customBackground && isBackgroundBlurred && 'blurred',\n MASK_IMAGE_DISABLED ? 'mask-image-disabled' : 'mask-image-enabled',\n );\n\n const messagingDisabledClassName = buildClassName(\n 'messaging-disabled',\n !isSelectModeActive && 'shown',\n );\n\n const messageSendingRestrictionReason = getMessageSendingRestrictionReason(\n lang, currentUserBannedRights, defaultBannedRights,\n );\n\n // CSS Variables calculation doesn't work properly with transforms, so we calculate transform values in JS\n const {\n composerHiddenScale, toolbarHiddenScale,\n composerTranslateX, toolbarTranslateX,\n unpinHiddenScale, toolbarForUnpinHiddenScale,\n } = useMemo(\n () => calculateMiddleFooterTransforms(windowWidth, renderingCanPost),\n [renderingCanPost, windowWidth],\n );\n\n const footerClassName = buildClassName(\n 'middle-column-footer',\n !renderingCanPost && 'no-composer',\n renderingCanPost && isNotchShown && !isSelectModeActive && 'with-notch',\n );\n\n const closeChat = () => {\n openChat({ id: undefined }, { forceSyncOnIOs: true });\n };\n\n useHistoryBack(\n renderingChatId && renderingThreadId,\n closeChat, undefined, undefined, undefined,\n messageLists?.map(createMessageHash) || [],\n );\n\n useHistoryBack(isMobileSearchActive, closeLocalTextSearch);\n useHistoryBack(isSelectModeActive, exitMessageSelectMode);\n\n const isMessagingDisabled = Boolean(!isPinnedMessageList && !renderingCanPost && messageSendingRestrictionReason);\n const withMessageListBottomShift = Boolean(\n renderingCanRestartBot || renderingCanSubscribe || renderingCanStartBot || isPinnedMessageList,\n );\n const withExtraShift = Boolean(isMessagingDisabled || isSelectModeActive || isPinnedMessageList);\n\n return (\n \n \n
\n {renderingChatId && renderingThreadId && (\n <>\n
\n \n \n {() => (\n <>\n \n
\n {renderingCanPost && (\n \n )}\n {isPinnedMessageList && (\n
\n \n \n {lang('Chat.Pinned.UnpinAll', pinnedMessagesCount, 'i')}\n \n
\n )}\n {isMessagingDisabled && (\n
\n
\n \n {messageSendingRestrictionReason}\n \n
\n
\n )}\n {IS_SINGLE_COLUMN_LAYOUT && renderingCanSubscribe && (\n
\n \n {lang(renderingIsChannel ? 'ProfileJoinChannel' : 'ProfileJoinGroup')}\n \n
\n )}\n {IS_SINGLE_COLUMN_LAYOUT && renderingCanStartBot && (\n
\n \n {lang('BotStart')}\n \n
\n )}\n {IS_SINGLE_COLUMN_LAYOUT && renderingCanRestartBot && (\n
\n \n {lang('BotRestart')}\n \n
\n )}\n \n \n \n \n
\n \n )}\n \n\n \n
\n {IS_SINGLE_COLUMN_LAYOUT && }\n \n )}\n {chatId && (\n \n )}\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const theme = selectTheme(global);\n const {\n isBlurred: isBackgroundBlurred, background: customBackground, backgroundColor, patternColor,\n } = global.settings.themes[theme] || {};\n\n const { messageLists } = global.messages;\n const currentMessageList = selectCurrentMessageList(global);\n const { isLeftColumnShown, chats: { listIds } } = global;\n\n const state: StateProps = {\n theme,\n customBackground,\n backgroundColor,\n patternColor,\n isLeftColumnShown,\n isRightColumnShown: selectIsRightColumnShown(global),\n isBackgroundBlurred,\n isMobileSearchActive: Boolean(IS_SINGLE_COLUMN_LAYOUT && selectCurrentTextSearch(global)),\n isSelectModeActive: selectIsInSelectMode(global),\n isPaymentModalOpen: global.payment.isPaymentModalOpen,\n isReceiptModalOpen: Boolean(global.payment.receipt),\n isSeenByModalOpen: Boolean(global.seenByModal),\n animationLevel: global.settings.byKey.animationLevel,\n currentTransitionKey: Math.max(0, global.messages.messageLists.length - 1),\n };\n\n if (!currentMessageList || !listIds.active) {\n return state;\n }\n\n const { chatId, threadId, type: messageListType } = currentMessageList;\n const chat = selectChat(global, chatId);\n const bot = selectChatBot(global, chatId);\n const pinnedIds = selectPinnedIds(global, chatId);\n const { chatId: audioChatId, messageId: audioMessageId } = global.audioPlayer;\n\n const canPost = chat && getCanPostInChat(chat, threadId);\n const isBotNotStarted = selectIsChatBotNotStarted(global, chatId);\n const isPinnedMessageList = messageListType === 'pinned';\n const isScheduledMessageList = messageListType === 'scheduled';\n const isMainThread = messageListType === 'thread' && threadId === MAIN_THREAD_ID;\n const isChannel = Boolean(chat && isChatChannel(chat));\n const canSubscribe = Boolean(\n chat && isMainThread && (isChannel || isChatSuperGroup(chat)) && chat.isNotJoined,\n );\n const canRestartBot = Boolean(bot && selectIsUserBlocked(global, bot.id));\n const canStartBot = !canRestartBot && isBotNotStarted;\n\n return {\n ...state,\n chatId,\n threadId,\n messageListType,\n isPrivate: isUserId(chatId),\n canPost: !isPinnedMessageList && (!chat || canPost) && !isBotNotStarted,\n isPinnedMessageList,\n isScheduledMessageList,\n currentUserBannedRights: chat?.currentUserBannedRights,\n defaultBannedRights: chat?.defaultBannedRights,\n hasPinnedOrAudioPlayer: (\n threadId !== MAIN_THREAD_ID\n || Boolean(!isPinnedMessageList && pinnedIds?.length)\n || Boolean(audioChatId && audioMessageId)\n ),\n pinnedMessagesCount: pinnedIds ? pinnedIds.length : 0,\n shouldSkipHistoryAnimations: global.shouldSkipHistoryAnimations,\n messageLists,\n isChannel,\n canSubscribe,\n canStartBot,\n canRestartBot,\n };\n },\n)(MiddleColumn));\n\nfunction useIsReady(\n animationLevel?: number,\n currentTransitionKey?: number,\n prevTransitionKey?: number,\n chatId?: string,\n) {\n const [isReady, setIsReady] = useState(!IS_SINGLE_COLUMN_LAYOUT);\n const forceUpdate = useForceUpdate();\n\n const willSwitchMessageList = prevTransitionKey !== undefined && prevTransitionKey !== currentTransitionKey;\n if (willSwitchMessageList) {\n if (animationLevel !== ANIMATION_LEVEL_MIN) {\n setIsReady(false);\n } else {\n forceUpdate();\n }\n }\n\n useOnChange(() => {\n if (animationLevel === ANIMATION_LEVEL_MIN) {\n setIsReady(true);\n }\n }, [animationLevel]);\n\n function handleOpenEnd(e: React.TransitionEvent) {\n if (e.propertyName === 'transform' && e.target === e.currentTarget) {\n setIsReady(Boolean(chatId));\n }\n }\n\n function handleSlideStop() {\n setIsReady(true);\n }\n\n return {\n isReady: isReady && !willSwitchMessageList,\n handleOpenEnd: animationLevel !== ANIMATION_LEVEL_MIN ? handleOpenEnd : undefined,\n handleSlideStop: animationLevel !== ANIMATION_LEVEL_MIN ? handleSlideStop : undefined,\n };\n}\n","import React, {\n FC, memo, useCallback, useEffect, useRef, useState,\n} from '../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../lib/teact/teactn';\n\nimport { ManagementScreens, ProfileState } from '../../types';\n\nimport { IS_SINGLE_COLUMN_LAYOUT } from '../../util/environment';\nimport { debounce } from '../../util/schedulers';\nimport buildClassName from '../../util/buildClassName';\nimport {\n selectChat,\n selectCurrentGifSearch,\n selectCurrentStickerSearch,\n selectCurrentTextSearch,\n selectIsChatWithSelf,\n selectUser,\n} from '../../modules/selectors';\nimport {\n getCanAddContact,\n isChatAdmin,\n isChatChannel,\n isUserId,\n} from '../../modules/helpers';\nimport useCurrentOrPrev from '../../hooks/useCurrentOrPrev';\nimport useLang from '../../hooks/useLang';\n\nimport SearchInput from '../ui/SearchInput';\nimport Button from '../ui/Button';\nimport Transition from '../ui/Transition';\nimport './RightHeader.scss';\nimport { getDayStartAt } from '../../util/dateFormat';\n\ntype OwnProps = {\n chatId?: string;\n isColumnOpen?: boolean;\n isProfile?: boolean;\n isSearch?: boolean;\n isManagement?: boolean;\n isStickerSearch?: boolean;\n isGifSearch?: boolean;\n isPollResults?: boolean;\n isAddingChatMembers?: boolean;\n shouldSkipAnimation?: boolean;\n profileState?: ProfileState;\n managementScreen?: ManagementScreens;\n onClose: () => void;\n};\n\ntype StateProps = {\n canAddContact?: boolean;\n canManage?: boolean;\n isChannel?: boolean;\n userId?: string;\n messageSearchQuery?: string;\n stickerSearchQuery?: string;\n gifSearchQuery?: string;\n};\n\nconst COLUMN_CLOSE_DELAY_MS = 300;\nconst runDebouncedForSearch = debounce((cb) => cb(), 200, false);\n\nenum HeaderContent {\n Profile,\n MemberList,\n SharedMedia,\n Search,\n Management,\n ManageInitial,\n ManageChannelSubscribers,\n ManageChatAdministrators,\n ManageChatPrivacyType,\n ManageDiscussion,\n ManageGroupPermissions,\n ManageGroupRemovedUsers,\n ManageGroupUserPermissionsCreate,\n ManageGroupUserPermissions,\n ManageGroupRecentActions,\n ManageGroupAdminRights,\n ManageGroupNewAdminRights,\n ManageGroupMembers,\n ManageGroupAddAdmins,\n StickerSearch,\n GifSearch,\n PollResults,\n AddingMembers,\n}\n\nconst RightHeader: FC = ({\n isColumnOpen,\n isProfile,\n isSearch,\n isManagement,\n isStickerSearch,\n isGifSearch,\n isPollResults,\n isAddingChatMembers,\n profileState,\n managementScreen,\n canAddContact,\n userId,\n canManage,\n isChannel,\n onClose,\n messageSearchQuery,\n stickerSearchQuery,\n gifSearchQuery,\n shouldSkipAnimation,\n}) => {\n const {\n setLocalTextSearchQuery,\n setStickerSearchQuery,\n setGifSearchQuery,\n searchTextMessagesLocal,\n toggleManagement,\n openHistoryCalendar, addContact,\n } = getDispatch();\n\n // eslint-disable-next-line no-null/no-null\n const backButtonRef = useRef(null);\n\n const handleMessageSearchQueryChange = useCallback((query: string) => {\n setLocalTextSearchQuery({ query });\n\n if (query.length) {\n runDebouncedForSearch(searchTextMessagesLocal);\n }\n }, [searchTextMessagesLocal, setLocalTextSearchQuery]);\n\n const handleStickerSearchQueryChange = useCallback((query: string) => {\n setStickerSearchQuery({ query });\n }, [setStickerSearchQuery]);\n\n const handleGifSearchQueryChange = useCallback((query: string) => {\n setGifSearchQuery({ query });\n }, [setGifSearchQuery]);\n\n const handleAddContact = useCallback(() => {\n addContact({ userId });\n }, [addContact, userId]);\n\n const [shouldSkipTransition, setShouldSkipTransition] = useState(!isColumnOpen);\n\n useEffect(() => {\n setTimeout(() => {\n setShouldSkipTransition(!isColumnOpen);\n }, COLUMN_CLOSE_DELAY_MS);\n }, [isColumnOpen]);\n\n const lang = useLang();\n const contentKey = isProfile ? (\n profileState === ProfileState.Profile ? (\n HeaderContent.Profile\n ) : profileState === ProfileState.SharedMedia ? (\n HeaderContent.SharedMedia\n ) : profileState === ProfileState.MemberList ? (\n HeaderContent.MemberList\n ) : -1 // Never reached\n ) : isSearch ? (\n HeaderContent.Search\n ) : isPollResults ? (\n HeaderContent.PollResults\n ) : isStickerSearch ? (\n HeaderContent.StickerSearch\n ) : isGifSearch ? (\n HeaderContent.GifSearch\n ) : isAddingChatMembers ? (\n HeaderContent.AddingMembers\n ) : isManagement ? (\n managementScreen === ManagementScreens.Initial ? (\n HeaderContent.ManageInitial\n ) : managementScreen === ManagementScreens.ChatPrivacyType ? (\n HeaderContent.ManageChatPrivacyType\n ) : managementScreen === ManagementScreens.Discussion ? (\n HeaderContent.ManageDiscussion\n ) : managementScreen === ManagementScreens.ChannelSubscribers ? (\n HeaderContent.ManageChannelSubscribers\n ) : managementScreen === ManagementScreens.GroupPermissions ? (\n HeaderContent.ManageGroupPermissions\n ) : managementScreen === ManagementScreens.ChatAdministrators ? (\n HeaderContent.ManageChatAdministrators\n ) : managementScreen === ManagementScreens.GroupRemovedUsers ? (\n HeaderContent.ManageGroupRemovedUsers\n ) : managementScreen === ManagementScreens.GroupUserPermissionsCreate ? (\n HeaderContent.ManageGroupUserPermissionsCreate\n ) : managementScreen === ManagementScreens.GroupUserPermissions ? (\n HeaderContent.ManageGroupUserPermissions\n ) : managementScreen === ManagementScreens.GroupRecentActions ? (\n HeaderContent.ManageGroupRecentActions\n ) : managementScreen === ManagementScreens.ChatAdminRights ? (\n HeaderContent.ManageGroupAdminRights\n ) : managementScreen === ManagementScreens.ChatNewAdminRights ? (\n HeaderContent.ManageGroupNewAdminRights\n ) : managementScreen === ManagementScreens.GroupMembers ? (\n HeaderContent.ManageGroupMembers\n ) : managementScreen === ManagementScreens.GroupAddAdmins ? (\n HeaderContent.ManageGroupAddAdmins\n ) : undefined // Never reached\n ) : undefined; // When column is closed\n\n const renderingContentKey = useCurrentOrPrev(contentKey, true) ?? -1;\n\n function renderHeaderContent() {\n if (renderingContentKey === -1) {\n return undefined;\n }\n\n switch (renderingContentKey) {\n case HeaderContent.PollResults:\n return

{lang('PollResults')}

;\n case HeaderContent.Search:\n return (\n <>\n \n openHistoryCalendar({ selectedAt: getDayStartAt(Date.now()) })}\n ariaLabel=\"Search messages by date\"\n >\n \n \n \n );\n case HeaderContent.AddingMembers:\n return

{lang(isChannel ? 'ChannelAddSubscribers' : 'GroupAddMembers')}

;\n case HeaderContent.ManageInitial:\n return

{lang('Edit')}

;\n case HeaderContent.ManageChatPrivacyType:\n return

{lang(isChannel ? 'ChannelTypeHeader' : 'GroupTypeHeader')}

;\n case HeaderContent.ManageDiscussion:\n return

{lang('Discussion')}

;\n case HeaderContent.ManageChatAdministrators:\n return

{lang('ChannelAdministrators')}

;\n case HeaderContent.ManageGroupRecentActions:\n return

{lang('Group.Info.AdminLog')}

;\n case HeaderContent.ManageGroupAdminRights:\n return

{lang('EditAdminRights')}

;\n case HeaderContent.ManageGroupNewAdminRights:\n return

{lang('SetAsAdmin')}

;\n case HeaderContent.ManageGroupPermissions:\n return

{lang('ChannelPermissions')}

;\n case HeaderContent.ManageGroupRemovedUsers:\n return

{lang('ChannelBlockedUsers')}

;\n case HeaderContent.ManageGroupUserPermissionsCreate:\n return

{lang('ChannelAddException')}

;\n case HeaderContent.ManageGroupUserPermissions:\n return

{lang('UserRestrictions')}

;\n case HeaderContent.ManageGroupAddAdmins:\n return

{lang('Channel.Management.AddModerator')}

;\n case HeaderContent.StickerSearch:\n return (\n \n );\n case HeaderContent.GifSearch:\n return (\n \n );\n case HeaderContent.SharedMedia:\n return

{lang('SharedMedia')}

;\n case HeaderContent.ManageChannelSubscribers:\n return

{lang('ChannelSubscribers')}

;\n case HeaderContent.MemberList:\n case HeaderContent.ManageGroupMembers:\n return

{lang('GroupMembers')}

;\n default:\n return (\n <>\n

Profile

\n
\n {canAddContact && (\n \n \n \n )}\n {canManage && (\n \n \n \n )}\n
\n \n );\n }\n }\n\n const isBackButton = (\n IS_SINGLE_COLUMN_LAYOUT\n || contentKey === HeaderContent.SharedMedia\n || contentKey === HeaderContent.MemberList\n || contentKey === HeaderContent.AddingMembers\n || isManagement\n );\n\n const buttonClassName = buildClassName(\n 'animated-close-icon',\n isBackButton && 'state-back',\n (shouldSkipTransition || shouldSkipAnimation) && 'no-transition',\n );\n\n return (\n
\n \n
\n \n \n {renderHeaderContent}\n \n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { chatId, isProfile, isManagement }): StateProps => {\n const { query: messageSearchQuery } = selectCurrentTextSearch(global) || {};\n const { query: stickerSearchQuery } = selectCurrentStickerSearch(global) || {};\n const { query: gifSearchQuery } = selectCurrentGifSearch(global) || {};\n const chat = chatId ? selectChat(global, chatId) : undefined;\n const isChannel = chat && isChatChannel(chat);\n const user = isProfile && chatId && isUserId(chatId) ? selectUser(global, chatId) : undefined;\n\n const canAddContact = user && getCanAddContact(user);\n const canManage = Boolean(\n !isManagement\n && isProfile\n && !canAddContact\n && chat\n && !selectIsChatWithSelf(global, chat.id)\n // chat.isCreator is for Basic Groups\n && (isUserId(chat.id) || ((isChatAdmin(chat) || chat.isCreator) && !chat.isNotJoined)),\n );\n\n return {\n canManage,\n canAddContact,\n isChannel,\n userId: user?.id,\n messageSearchQuery,\n stickerSearchQuery,\n gifSearchQuery,\n };\n },\n)(RightHeader));\n","import { useMemo, useRef } from '../../../lib/teact/teact';\n\nimport {\n ApiChat, ApiChatMember, ApiMessage, ApiUser, ApiUserStatus,\n} from '../../../api/types';\nimport { ProfileTabType, SharedMediaType } from '../../../types';\n\nimport { MEMBERS_SLICE, MESSAGE_SEARCH_SLICE, SHARED_MEDIA_SLICE } from '../../../config';\nimport { getMessageContentIds, sortChatIds, sortUserIds } from '../../../modules/helpers';\nimport useOnChange from '../../../hooks/useOnChange';\nimport useInfiniteScroll from '../../../hooks/useInfiniteScroll';\n\nexport default function useProfileViewportIds(\n isRightColumnShown: boolean,\n loadMoreMembers: AnyToVoidFunction,\n loadCommonChats: AnyToVoidFunction,\n searchMessages: AnyToVoidFunction,\n tabType: ProfileTabType,\n mediaSearchType?: SharedMediaType,\n groupChatMembers?: ApiChatMember[],\n commonChatIds?: string[],\n usersById?: Record,\n userStatusesById?: Record,\n chatsById?: Record,\n chatMessages?: Record,\n foundIds?: number[],\n chatId?: string,\n lastSyncTime?: number,\n serverTimeOffset = 0,\n) {\n const resultType = tabType === 'members' || !mediaSearchType ? tabType : mediaSearchType;\n\n const memberIds = useMemo(() => {\n if (!groupChatMembers || !usersById || !userStatusesById) {\n return undefined;\n }\n\n return sortUserIds(\n groupChatMembers.map(({ userId }) => userId),\n usersById,\n userStatusesById,\n undefined,\n serverTimeOffset,\n );\n }, [groupChatMembers, serverTimeOffset, usersById, userStatusesById]);\n\n const chatIds = useMemo(() => {\n if (!commonChatIds || !chatsById) {\n return undefined;\n }\n\n return sortChatIds(commonChatIds, chatsById, true);\n }, [chatsById, commonChatIds]);\n\n const [memberViewportIds, getMoreMembers, noProfileInfoForMembers] = useInfiniteScrollForLoadableItems(\n resultType, loadMoreMembers, lastSyncTime, memberIds,\n );\n\n const [mediaViewportIds, getMoreMedia, noProfileInfoForMedia] = useInfiniteScrollForSharedMedia(\n 'media', resultType, searchMessages, lastSyncTime, chatMessages, foundIds,\n );\n\n const [documentViewportIds, getMoreDocuments, noProfileInfoForDocuments] = useInfiniteScrollForSharedMedia(\n 'documents', resultType, searchMessages, lastSyncTime, chatMessages, foundIds,\n );\n\n const [linkViewportIds, getMoreLinks, noProfileInfoForLinks] = useInfiniteScrollForSharedMedia(\n 'links', resultType, searchMessages, lastSyncTime, chatMessages, foundIds,\n );\n\n const [audioViewportIds, getMoreAudio, noProfileInfoForAudio] = useInfiniteScrollForSharedMedia(\n 'audio', resultType, searchMessages, lastSyncTime, chatMessages, foundIds,\n );\n\n const [voiceViewportIds, getMoreVoices, noProfileInfoForVoices] = useInfiniteScrollForSharedMedia(\n 'voice', resultType, searchMessages, lastSyncTime, chatMessages, foundIds,\n );\n\n const [commonChatViewportIds, getMoreCommonChats, noProfileInfoForCommonChats] = useInfiniteScrollForLoadableItems(\n resultType, loadCommonChats, lastSyncTime, chatIds,\n );\n\n let viewportIds: number[] | string[] | undefined;\n let getMore: AnyToVoidFunction | undefined;\n let noProfileInfo = false;\n\n switch (resultType) {\n case 'members':\n viewportIds = memberViewportIds;\n getMore = getMoreMembers;\n noProfileInfo = noProfileInfoForMembers;\n break;\n case 'commonChats':\n viewportIds = commonChatViewportIds;\n getMore = getMoreCommonChats;\n noProfileInfo = noProfileInfoForCommonChats;\n break;\n case 'media':\n viewportIds = mediaViewportIds;\n getMore = getMoreMedia;\n noProfileInfo = noProfileInfoForMedia;\n break;\n case 'documents':\n viewportIds = documentViewportIds;\n getMore = getMoreDocuments;\n noProfileInfo = noProfileInfoForDocuments;\n break;\n case 'links':\n viewportIds = linkViewportIds;\n getMore = getMoreLinks;\n noProfileInfo = noProfileInfoForLinks;\n break;\n case 'audio':\n viewportIds = audioViewportIds;\n getMore = getMoreAudio;\n noProfileInfo = noProfileInfoForAudio;\n break;\n case 'voice':\n viewportIds = voiceViewportIds;\n getMore = getMoreVoices;\n noProfileInfo = noProfileInfoForVoices;\n break;\n }\n\n return [resultType, viewportIds, getMore, noProfileInfo] as const;\n}\n\nfunction useInfiniteScrollForLoadableItems(\n currentResultType?: ProfileTabType,\n handleLoadMore?: AnyToVoidFunction,\n lastSyncTime?: number,\n itemIds?: string[],\n) {\n const [viewportIds, getMore] = useInfiniteScroll(\n lastSyncTime ? handleLoadMore : undefined,\n itemIds,\n undefined,\n MEMBERS_SLICE,\n );\n\n const isOnTop = !viewportIds || !itemIds || viewportIds[0] === itemIds[0];\n\n return [viewportIds, getMore, !isOnTop] as const;\n}\n\nfunction useInfiniteScrollForSharedMedia(\n forSharedMediaType: SharedMediaType,\n currentResultType?: ProfileTabType,\n handleLoadMore?: AnyToVoidFunction,\n lastSyncTime?: number,\n chatMessages?: Record,\n foundIds?: number[],\n) {\n const messageIdsRef = useRef();\n\n useOnChange(() => {\n if (currentResultType === forSharedMediaType && chatMessages && foundIds) {\n messageIdsRef.current = getMessageContentIds(\n chatMessages,\n foundIds,\n forSharedMediaType,\n ).reverse();\n }\n }, [chatMessages, foundIds, currentResultType, forSharedMediaType]);\n\n const [viewportIds, getMore] = useInfiniteScroll(\n lastSyncTime ? handleLoadMore : undefined,\n messageIdsRef.current,\n undefined,\n forSharedMediaType === 'media' ? SHARED_MEDIA_SLICE : MESSAGE_SEARCH_SLICE,\n );\n\n const isOnTop = !viewportIds || !messageIdsRef.current || viewportIds[0] === messageIdsRef.current[0];\n\n return [viewportIds, getMore, !isOnTop] as const;\n}\n","import { useCallback, useEffect } from '../../../lib/teact/teact';\n\nimport { ProfileState } from '../../../types';\n\nimport fastSmoothScroll from '../../../util/fastSmoothScroll';\nimport { throttle } from '../../../util/schedulers';\nimport useEffectWithPrevDeps from '../../../hooks/useEffectWithPrevDeps';\n\nconst TRANSITION_DURATION = 300;\nconst PROGRAMMATIC_SCROLL_TIMEOUT_MS = 350;\n\nconst runThrottledForScroll = throttle((cb) => cb(), 250, false);\n\nlet isScrollingProgrammatically = false;\n\nexport default function useProfileState(\n containerRef: { current: HTMLDivElement | null },\n tabType: string,\n profileState: ProfileState,\n onProfileStateChange: (state: ProfileState) => void,\n) {\n // Scroll to tabs if needed\n useEffectWithPrevDeps(([prevTabType]) => {\n if (prevTabType && prevTabType !== tabType) {\n const container = containerRef.current!;\n const tabsEl = container.querySelector('.TabList')!;\n if (container.scrollTop < tabsEl.offsetTop) {\n onProfileStateChange(tabType === 'members' ? ProfileState.MemberList : ProfileState.SharedMedia);\n isScrollingProgrammatically = true;\n fastSmoothScroll(container, tabsEl, 'start', undefined, undefined, undefined, TRANSITION_DURATION);\n setTimeout(() => {\n isScrollingProgrammatically = false;\n }, PROGRAMMATIC_SCROLL_TIMEOUT_MS);\n }\n }\n }, [tabType, onProfileStateChange]);\n\n // Scroll to top\n useEffectWithPrevDeps(([prevProfileState]) => {\n if (profileState !== ProfileState.Profile || profileState === prevProfileState) {\n return;\n }\n\n const container = containerRef.current;\n if (!container) {\n return;\n }\n\n const tabListEl = container.querySelector('.TabList');\n if (!tabListEl || tabListEl.offsetTop > container.scrollTop) {\n return;\n }\n\n isScrollingProgrammatically = true;\n fastSmoothScroll(\n container,\n container.firstElementChild as HTMLElement,\n 'start',\n undefined,\n container.offsetHeight * 2,\n );\n\n setTimeout(() => {\n isScrollingProgrammatically = false;\n }, PROGRAMMATIC_SCROLL_TIMEOUT_MS);\n\n onProfileStateChange(profileState);\n }, [profileState]);\n\n const determineProfileState = useCallback(() => {\n const container = containerRef.current;\n if (!container) {\n return;\n }\n\n const tabListEl = container.querySelector('.TabList');\n if (!tabListEl) {\n return;\n }\n\n let state: ProfileState = ProfileState.Profile;\n if (container.scrollTop >= tabListEl.offsetTop) {\n state = tabType === 'members'\n ? ProfileState.MemberList\n : ProfileState.SharedMedia;\n }\n\n onProfileStateChange(state);\n }, [containerRef, onProfileStateChange, tabType]);\n\n // Determine profile state when switching tabs\n useEffect(() => {\n if (isScrollingProgrammatically) {\n return;\n }\n\n determineProfileState();\n }, [determineProfileState, tabType]);\n\n // Determine profile state when scrolling\n const handleScroll = useCallback(() => {\n if (isScrollingProgrammatically) {\n return;\n }\n\n runThrottledForScroll(determineProfileState);\n }, [determineProfileState]);\n\n return { handleScroll };\n}\n","import React, {\n FC, useCallback, useEffect, useMemo, useRef, useState, memo,\n} from '../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../lib/teact/teactn';\n\nimport {\n MAIN_THREAD_ID,\n ApiMessage,\n ApiChat,\n ApiChatMember,\n ApiUser,\n ApiUserStatus,\n} from '../../api/types';\nimport {\n NewChatMembersProgress, ISettings, MediaViewerOrigin, ProfileState, ProfileTabType, SharedMediaType, AudioOrigin,\n} from '../../types';\n\nimport {\n MEMBERS_SLICE,\n PROFILE_SENSITIVE_AREA,\n SHARED_MEDIA_SLICE,\n SLIDE_TRANSITION_DURATION,\n} from '../../config';\nimport { IS_TOUCH_ENV } from '../../util/environment';\nimport {\n getHasAdminRight, isChatAdmin, isChatChannel, isChatGroup, isUserBot, isUserId,\n} from '../../modules/helpers';\nimport {\n selectChatMessages,\n selectChat,\n selectCurrentMediaSearch,\n selectIsRightColumnShown,\n selectTheme,\n selectActiveDownloadIds,\n selectUser,\n} from '../../modules/selectors';\nimport { captureEvents, SwipeDirection } from '../../util/captureEvents';\nimport { getSenderName } from '../left/search/helpers/getSenderName';\nimport useCacheBuster from '../../hooks/useCacheBuster';\nimport useProfileViewportIds from './hooks/useProfileViewportIds';\nimport useProfileState from './hooks/useProfileState';\nimport useTransitionFixes from './hooks/useTransitionFixes';\nimport useAsyncRendering from './hooks/useAsyncRendering';\nimport useLang from '../../hooks/useLang';\n\nimport Transition from '../ui/Transition';\nimport InfiniteScroll from '../ui/InfiniteScroll';\nimport TabList from '../ui/TabList';\nimport Spinner from '../ui/Spinner';\nimport ListItem from '../ui/ListItem';\nimport PrivateChatInfo from '../common/PrivateChatInfo';\nimport ProfileInfo from '../common/ProfileInfo';\nimport Document from '../common/Document';\nimport Audio from '../common/Audio';\nimport ChatExtra from '../common/ChatExtra';\nimport Media from '../common/Media';\nimport WebLink from '../common/WebLink';\nimport NothingFound from '../common/NothingFound';\nimport FloatingActionButton from '../ui/FloatingActionButton';\nimport DeleteMemberModal from './DeleteMemberModal';\nimport GroupChatInfo from '../common/GroupChatInfo';\n\nimport './Profile.scss';\n\ntype OwnProps = {\n chatId: string;\n userId?: string;\n profileState: ProfileState;\n onProfileStateChange: (state: ProfileState) => void;\n};\n\ntype StateProps = {\n theme: ISettings['theme'];\n isChannel?: boolean;\n currentUserId?: string;\n resolvedUserId?: string;\n chatMessages?: Record;\n foundIds?: number[];\n mediaSearchType?: SharedMediaType;\n hasCommonChatsTab?: boolean;\n hasMembersTab?: boolean;\n areMembersHidden?: boolean;\n canAddMembers?: boolean;\n canDeleteMembers?: boolean;\n members?: ApiChatMember[];\n commonChatIds?: string[];\n chatsById: Record;\n usersById: Record;\n userStatusesById: Record;\n isRightColumnShown: boolean;\n isRestricted?: boolean;\n lastSyncTime?: number;\n serverTimeOffset: number;\n activeDownloadIds: number[];\n isChatProtected?: boolean;\n};\n\nconst TABS = [\n { type: 'media', title: 'SharedMediaTab2' },\n { type: 'documents', title: 'SharedFilesTab2' },\n { type: 'links', title: 'SharedLinksTab2' },\n { type: 'audio', title: 'SharedMusicTab2' },\n { type: 'voice', title: 'SharedVoiceTab2' },\n];\n\nconst HIDDEN_RENDER_DELAY = 1000;\n\nconst Profile: FC = ({\n chatId,\n profileState,\n onProfileStateChange,\n theme,\n isChannel,\n resolvedUserId,\n currentUserId,\n chatMessages,\n foundIds,\n mediaSearchType,\n hasCommonChatsTab,\n hasMembersTab,\n areMembersHidden,\n canAddMembers,\n canDeleteMembers,\n commonChatIds,\n members,\n usersById,\n userStatusesById,\n chatsById,\n isRightColumnShown,\n isRestricted,\n lastSyncTime,\n activeDownloadIds,\n serverTimeOffset,\n isChatProtected,\n}) => {\n const {\n setLocalMediaSearchType,\n loadMoreMembers,\n loadCommonChats,\n openChat,\n searchMediaMessagesLocal,\n openMediaViewer,\n openAudioPlayer,\n openUserInfo,\n focusMessage,\n loadProfilePhotos,\n setNewChatMembersDialogState,\n } = getDispatch();\n\n // eslint-disable-next-line no-null/no-null\n const containerRef = useRef(null);\n // eslint-disable-next-line no-null/no-null\n const transitionRef = useRef(null);\n const lang = useLang();\n const [activeTab, setActiveTab] = useState(0);\n const [deletingUserId, setDeletingUserId] = useState();\n\n const tabs = useMemo(() => ([\n ...(hasMembersTab ? [{\n type: 'members', title: isChannel ? 'ChannelSubscribers' : 'GroupMembers',\n }] : []),\n ...TABS,\n ...(hasCommonChatsTab ? [{\n type: 'commonChats', title: 'SharedGroupsTab2',\n }] : []),\n ]), [hasCommonChatsTab, hasMembersTab, isChannel]);\n const tabType = tabs[activeTab].type as ProfileTabType;\n\n const [resultType, viewportIds, getMore, noProfileInfo] = useProfileViewportIds(\n isRightColumnShown, loadMoreMembers, loadCommonChats, searchMediaMessagesLocal, tabType, mediaSearchType, members,\n commonChatIds, usersById, userStatusesById, chatsById, chatMessages, foundIds, chatId, lastSyncTime,\n serverTimeOffset,\n );\n const activeKey = tabs.findIndex(({ type }) => type === resultType);\n\n const { handleScroll } = useProfileState(containerRef, tabType, profileState, onProfileStateChange);\n\n const { applyTransitionFix, releaseTransitionFix } = useTransitionFixes(containerRef);\n\n const [cacheBuster, resetCacheBuster] = useCacheBuster();\n\n const handleTransitionStop = useCallback(() => {\n releaseTransitionFix();\n resetCacheBuster();\n }, [releaseTransitionFix, resetCacheBuster]);\n\n const handleNewMemberDialogOpen = useCallback(() => {\n setNewChatMembersDialogState(NewChatMembersProgress.InProgress);\n }, [setNewChatMembersDialogState]);\n\n // Update search type when switching tabs\n useEffect(() => {\n setLocalMediaSearchType({ mediaType: tabType });\n }, [setLocalMediaSearchType, tabType]);\n\n const profileId = resolvedUserId || chatId;\n\n useEffect(() => {\n if (lastSyncTime) {\n loadProfilePhotos({ profileId });\n }\n }, [loadProfilePhotos, profileId, lastSyncTime]);\n\n const handleSelectMedia = useCallback((messageId: number) => {\n openMediaViewer({\n chatId: profileId,\n threadId: MAIN_THREAD_ID,\n messageId,\n origin: MediaViewerOrigin.SharedMedia,\n });\n }, [profileId, openMediaViewer]);\n\n const handlePlayAudio = useCallback((messageId: number) => {\n openAudioPlayer({ chatId: profileId, messageId });\n }, [profileId, openAudioPlayer]);\n\n const handleMemberClick = useCallback((id: string) => {\n openUserInfo({ id });\n }, [openUserInfo]);\n\n const handleMessageFocus = useCallback((messageId: number) => {\n focusMessage({ chatId: profileId, messageId });\n }, [profileId, focusMessage]);\n\n const handleDeleteMembersModalClose = useCallback(() => {\n setDeletingUserId(undefined);\n }, []);\n\n useEffect(() => {\n if (!transitionRef.current || !IS_TOUCH_ENV) {\n return undefined;\n }\n\n return captureEvents(transitionRef.current, {\n selectorToPreventScroll: '.Profile',\n onSwipe: ((e, direction) => {\n if (direction === SwipeDirection.Left) {\n setActiveTab(Math.min(activeTab + 1, tabs.length - 1));\n return true;\n } else if (direction === SwipeDirection.Right) {\n setActiveTab(Math.max(0, activeTab - 1));\n return true;\n }\n\n return false;\n }),\n });\n }, [activeTab, tabs.length]);\n\n let renderingDelay;\n const isFirstTab = resultType === 'members' || (!hasMembersTab && resultType === 'media');\n // @optimization Used to unparallelize rendering of message list and profile media\n if (isFirstTab) {\n renderingDelay = !isRightColumnShown ? HIDDEN_RENDER_DELAY : 0;\n // @optimization Used to delay first render of secondary tabs while animating\n } else if (!viewportIds) {\n renderingDelay = SLIDE_TRANSITION_DURATION;\n }\n const canRenderContents = useAsyncRendering([chatId, resultType], renderingDelay);\n\n function getMemberContextAction(memberId: string) {\n return memberId === currentUserId || !canDeleteMembers ? undefined : [{\n title: lang('lng_context_remove_from_group'),\n icon: 'stop',\n handler: () => {\n setDeletingUserId(memberId);\n },\n }];\n }\n\n function renderSharedMedia() {\n if (!viewportIds || !canRenderContents || !chatMessages) {\n // This is just a single-frame delay, so we do not show spinner\n const noSpinner = isFirstTab && viewportIds && !canRenderContents;\n\n return (\n
\n {!noSpinner && }\n
\n );\n }\n\n if (!viewportIds.length) {\n let text: string;\n\n switch (resultType) {\n case 'members':\n text = areMembersHidden ? 'You have no access to group members list.' : 'No members found';\n break;\n case 'commonChats':\n text = lang('NoGroupsInCommon');\n break;\n case 'documents':\n text = lang('lng_media_file_empty');\n break;\n case 'links':\n text = lang('lng_media_link_empty');\n break;\n case 'audio':\n text = lang('lng_media_song_empty');\n break;\n case 'voice':\n text = lang('lng_media_audio_empty');\n break;\n default:\n text = lang('SharedMedia.EmptyTitle');\n }\n\n return (\n
\n \n
\n );\n }\n\n return (\n \n {resultType === 'media' ? (\n (viewportIds as number[])!.map((id) => chatMessages[id] && (\n \n ))\n ) : resultType === 'documents' ? (\n (viewportIds as number[])!.map((id) => chatMessages[id] && (\n \n ))\n ) : resultType === 'links' ? (\n (viewportIds as number[])!.map((id) => chatMessages[id] && (\n \n ))\n ) : resultType === 'audio' ? (\n (viewportIds as number[])!.map((id) => chatMessages[id] && (\n \n ))\n ) : resultType === 'voice' ? (\n (viewportIds as number[])!.map((id) => chatMessages[id] && (\n \n ))\n ) : resultType === 'members' ? (\n (viewportIds as string[])!.map((id, i) => (\n handleMemberClick(id)}\n contextActions={getMemberContextAction(id)}\n >\n \n \n ))\n ) : resultType === 'commonChats' ? (\n (viewportIds as string[])!.map((id, i) => (\n openChat({ id })}\n >\n \n \n ))\n ) : undefined}\n
\n );\n }\n\n return (\n \n {!noProfileInfo && renderProfileInfo(chatId, resolvedUserId)}\n {!isRestricted && (\n \n \n {renderSharedMedia}\n \n \n
\n )}\n\n {canAddMembers && (\n \n \n \n )}\n {canDeleteMembers && (\n \n )}\n \n );\n};\n\nfunction renderProfileInfo(chatId: string, resolvedUserId?: string) {\n return (\n
\n \n \n
\n );\n}\n\nfunction buildInfiniteScrollItemSelector(resultType: string) {\n return [\n // Used on first render\n `.shared-media-transition > div:only-child > .${resultType}-list > .scroll-item`,\n // Used after transition\n `.shared-media-transition > .Transition__slide--active > .${resultType}-list > .scroll-item`,\n ].join(', ');\n}\n\nexport default memo(withGlobal(\n (global, { chatId, userId }): StateProps => {\n const chat = selectChat(global, chatId);\n\n const chatMessages = selectChatMessages(global, userId || chatId);\n const { currentType: mediaSearchType, resultsByType } = selectCurrentMediaSearch(global) || {};\n const { foundIds } = (resultsByType && mediaSearchType && resultsByType[mediaSearchType]) || {};\n\n const { byId: usersById, statusesById: userStatusesById } = global.users;\n const { byId: chatsById } = global.chats;\n\n const isGroup = chat && isChatGroup(chat);\n const isChannel = chat && isChatChannel(chat);\n const hasMembersTab = isGroup || (isChannel && isChatAdmin(chat!));\n const members = chat?.fullInfo?.members;\n const areMembersHidden = hasMembersTab && chat && chat.fullInfo && !chat.fullInfo.canViewMembers;\n const canAddMembers = hasMembersTab && chat && (getHasAdminRight(chat, 'inviteUsers') || chat.isCreator);\n const canDeleteMembers = hasMembersTab && chat && (getHasAdminRight(chat, 'banUsers') || chat.isCreator);\n\n const activeDownloadIds = selectActiveDownloadIds(global, chatId);\n\n let hasCommonChatsTab;\n let resolvedUserId;\n let user;\n if (userId) {\n resolvedUserId = userId;\n } else if (isUserId(chatId)) {\n resolvedUserId = chatId;\n }\n if (resolvedUserId) {\n user = selectUser(global, resolvedUserId);\n hasCommonChatsTab = user && !user.isSelf && !isUserBot(user);\n }\n\n return {\n theme: selectTheme(global),\n isChannel,\n resolvedUserId,\n chatMessages,\n foundIds,\n mediaSearchType,\n hasCommonChatsTab,\n hasMembersTab,\n areMembersHidden,\n canAddMembers,\n canDeleteMembers,\n currentUserId: global.currentUserId,\n isRightColumnShown: selectIsRightColumnShown(global),\n isRestricted: chat?.isRestricted,\n lastSyncTime: global.lastSyncTime,\n serverTimeOffset: global.serverTimeOffset,\n activeDownloadIds,\n usersById,\n userStatusesById,\n chatsById,\n isChatProtected: chat?.isProtected,\n ...(hasMembersTab && members && { members }),\n ...(hasCommonChatsTab && user && { commonChatIds: user.commonChats?.ids }),\n };\n },\n)(Profile));\n","import { useCallback, useEffect } from '../../../lib/teact/teact';\n\nexport default function useTransitionFixes(\n containerRef: { current: HTMLDivElement | null },\n transitionElSelector = '.Transition.shared-media-transition',\n) {\n // Set `min-height` for shared media container to prevent jumping when switching tabs\n useEffect(() => {\n function setMinHeight() {\n const container = containerRef.current!;\n const transitionEl = container.querySelector(transitionElSelector);\n const tabsEl = container.querySelector('.TabList');\n if (transitionEl && tabsEl) {\n transitionEl.style.minHeight = `${container.offsetHeight - tabsEl.offsetHeight}px`;\n }\n }\n\n setMinHeight();\n\n window.addEventListener('resize', setMinHeight, false);\n\n return () => {\n window.removeEventListener('resize', setMinHeight, false);\n };\n }, [containerRef, transitionElSelector]);\n\n // Workaround for scrollable content flickering during animation.\n const applyTransitionFix = useCallback(() => {\n const container = containerRef.current!;\n if (container.style.overflowY !== 'hidden') {\n const scrollBarWidth = container.offsetWidth - container.clientWidth;\n container.style.overflowY = 'hidden';\n container.style.marginRight = `${scrollBarWidth}px`;\n }\n }, [containerRef]);\n\n const releaseTransitionFix = useCallback(() => {\n const container = containerRef.current!;\n container.style.overflowY = 'scroll';\n container.style.marginRight = '0';\n }, [containerRef]);\n\n return { applyTransitionFix, releaseTransitionFix };\n}\n","import { useCallback, useState } from '../lib/teact/teact';\n\nexport default () => {\n const [cacheBuster, setCacheBuster] = useState(false);\n\n const updateCacheBuster = useCallback(() => {\n setCacheBuster((current) => !current);\n }, []);\n\n return [cacheBuster, updateCacheBuster] as const;\n};\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { OwnProps } from './RightSearch';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport Loading from '../ui/Loading';\n\nconst RightSearchAsync: FC = (props) => {\n const RightSearch = useModuleLoader(Bundles.Extra, 'RightSearch');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return RightSearch ? : ;\n};\n\nexport default memo(RightSearchAsync);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport { Bundles } from '../../../util/moduleLoader';\n\nimport { OwnProps } from './Management';\n\nimport useModuleLoader from '../../../hooks/useModuleLoader';\n\nimport Loading from '../../ui/Loading';\n\nconst ManagementAsync: FC = (props) => {\n const Management = useModuleLoader(Bundles.Extra, 'Management');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return Management ? : ;\n};\n\nexport default memo(ManagementAsync);\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 StickerSearchAsync: FC = () => {\n const StickerSearch = useModuleLoader(Bundles.Extra, 'StickerSearch');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return StickerSearch ? : ;\n};\n\nexport default memo(StickerSearchAsync);\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 GifSearchAsync: FC = () => {\n const GifSearch = useModuleLoader(Bundles.Extra, 'GifSearch');\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return GifSearch ? : ;\n};\n\nexport default memo(GifSearchAsync);\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 PollResultsAsync: FC = () => {\n const PollResults = useModuleLoader(Bundles.Extra, 'PollResults');\n\n return PollResults ? : ;\n};\n\nexport default memo(PollResultsAsync);\n","import React, {\n FC, useCallback, useMemo, memo, useState, useEffect,\n} from '../../lib/teact/teact';\nimport { getDispatch, getGlobal, withGlobal } from '../../lib/teact/teactn';\n\nimport {\n ApiChat, ApiChatMember, ApiUpdateConnectionStateType,\n} from '../../api/types';\nimport { NewChatMembersProgress } from '../../types';\n\nimport { unique } from '../../util/iteratees';\nimport { selectChat } from '../../modules/selectors';\nimport {\n filterUsersByName, isChatChannel, isUserBot, sortChatIds,\n} from '../../modules/helpers';\nimport useLang from '../../hooks/useLang';\nimport usePrevious from '../../hooks/usePrevious';\nimport useHistoryBack from '../../hooks/useHistoryBack';\n\nimport Picker from '../common/Picker';\nimport FloatingActionButton from '../ui/FloatingActionButton';\nimport Spinner from '../ui/Spinner';\n\nimport './AddChatMembers.scss';\n\nexport type OwnProps = {\n chatId: string;\n isActive: boolean;\n onNextStep: (memberIds: string[]) => void;\n onClose: NoneToVoidFunction;\n};\n\ntype StateProps = {\n connectionState?: ApiUpdateConnectionStateType;\n isChannel?: boolean;\n members?: ApiChatMember[];\n currentUserId?: string;\n chatsById: Record;\n localContactIds?: string[];\n searchQuery?: string;\n isLoading: boolean;\n isSearching?: boolean;\n localUserIds?: string[];\n globalUserIds?: string[];\n};\n\nconst AddChatMembers: FC = ({\n isChannel,\n connectionState,\n members,\n onNextStep,\n currentUserId,\n chatsById,\n localContactIds,\n isLoading,\n searchQuery,\n isSearching,\n localUserIds,\n globalUserIds,\n onClose,\n isActive,\n}) => {\n const { setUserSearchQuery, loadContactList } = getDispatch();\n\n const lang = useLang();\n const [selectedMemberIds, setSelectedMemberIds] = useState([]);\n const prevSelectedMemberIds = usePrevious(selectedMemberIds);\n const noPickerScrollRestore = prevSelectedMemberIds === selectedMemberIds;\n\n useEffect(() => {\n if (isActive && connectionState === 'connectionStateReady') {\n loadContactList();\n }\n }, [connectionState, isActive, loadContactList]);\n\n useHistoryBack(isActive, onClose);\n\n const memberIds = useMemo(() => {\n return members ? members.map((member) => member.userId) : [];\n }, [members]);\n\n const handleFilterChange = useCallback((query: string) => {\n setUserSearchQuery({ query });\n }, [setUserSearchQuery]);\n\n const displayedIds = useMemo(() => {\n // No need for expensive global updates on users, so we avoid them\n const usersById = getGlobal().users.byId;\n const filteredContactIds = localContactIds ? filterUsersByName(localContactIds, usersById, searchQuery) : [];\n\n return sortChatIds(\n unique([\n ...filteredContactIds,\n ...(localUserIds || []),\n ...(globalUserIds || []),\n ]).filter((userId) => {\n const user = usersById[userId];\n\n // The user can be added to the chat if the following conditions are met:\n // the user has not yet been added to the current chat\n // AND it is not the current user,\n // AND (it is not found (user from global search) OR it is not a bot OR it is a bot,\n // but the current chat is not a channel AND the appropriate permission is set).\n return (\n !memberIds.includes(userId)\n && userId !== currentUserId\n && (!user || !isUserBot(user) || (!isChannel && user.canBeInvitedToGroup))\n );\n }),\n chatsById,\n );\n }, [\n localContactIds, chatsById, searchQuery, localUserIds, globalUserIds, currentUserId, memberIds, isChannel,\n ]);\n\n const handleNextStep = useCallback(() => {\n if (selectedMemberIds.length) {\n setUserSearchQuery({ query: '' });\n onNextStep(selectedMemberIds);\n }\n }, [selectedMemberIds, setUserSearchQuery, onNextStep]);\n\n return (\n
\n
\n \n\n \n {isLoading ? (\n \n ) : (\n \n )}\n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global, { chatId }): StateProps => {\n const chat = selectChat(global, chatId);\n const { userIds: localContactIds } = global.contactList || {};\n const { byId: chatsById } = global.chats;\n const { currentUserId, newChatMembersProgress, connectionState } = global;\n const isChannel = chat && isChatChannel(chat);\n\n const {\n query: searchQuery,\n fetchingStatus,\n globalUserIds,\n localUserIds,\n } = global.userSearch;\n\n return {\n isChannel,\n members: chat?.fullInfo?.members,\n currentUserId,\n chatsById,\n localContactIds,\n searchQuery,\n isSearching: fetchingStatus,\n isLoading: newChatMembersProgress === NewChatMembersProgress.Loading,\n globalUserIds,\n localUserIds,\n connectionState,\n };\n },\n)(AddChatMembers));\n","import React, {\n FC, memo, useCallback, useEffect, useState,\n} from '../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../lib/teact/teactn';\n\nimport {\n ManagementScreens, NewChatMembersProgress, ProfileState, RightColumnContent,\n} from '../../types';\n\nimport { MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN } from '../../config';\nimport captureEscKeyListener from '../../util/captureEscKeyListener';\nimport {\n selectAreActiveChatsLoaded,\n selectCurrentMessageList,\n selectRightColumnContentKey,\n} from '../../modules/selectors';\nimport useLayoutEffectWithPrevDeps from '../../hooks/useLayoutEffectWithPrevDeps';\nimport useWindowSize from '../../hooks/useWindowSize';\nimport useCurrentOrPrev from '../../hooks/useCurrentOrPrev';\nimport useHistoryBack from '../../hooks/useHistoryBack';\n\nimport RightHeader from './RightHeader';\nimport Profile from './Profile';\nimport Transition from '../ui/Transition';\nimport RightSearch from './RightSearch.async';\nimport Management from './management/Management.async';\nimport StickerSearch from './StickerSearch.async';\nimport GifSearch from './GifSearch.async';\nimport PollResults from './PollResults.async';\nimport AddChatMembers from './AddChatMembers';\n\nimport './RightColumn.scss';\n\ntype StateProps = {\n contentKey?: RightColumnContent;\n chatId?: string;\n threadId?: number;\n currentProfileUserId?: string;\n isChatSelected: boolean;\n shouldSkipHistoryAnimations?: boolean;\n};\n\nconst COLUMN_CLOSE_DELAY_MS = 300;\nconst MAIN_SCREENS_COUNT = Object.keys(RightColumnContent).length / 2;\nconst MANAGEMENT_SCREENS_COUNT = Object.keys(ManagementScreens).length / 2;\n\nfunction blurSearchInput() {\n const searchInput = document.querySelector('.RightHeader .SearchInput input') as HTMLInputElement;\n if (searchInput) {\n searchInput.blur();\n }\n}\n\nconst RightColumn: FC = ({\n contentKey,\n chatId,\n threadId,\n currentProfileUserId,\n isChatSelected,\n shouldSkipHistoryAnimations,\n}) => {\n const {\n toggleChatInfo,\n toggleManagement,\n openUserInfo,\n closeLocalTextSearch,\n setStickerSearchQuery,\n setGifSearchQuery,\n closePollResults,\n addChatMembers,\n setNewChatMembersDialogState,\n } = getDispatch();\n\n const { width: windowWidth } = useWindowSize();\n const [profileState, setProfileState] = useState(ProfileState.Profile);\n const [managementScreen, setManagementScreen] = useState(ManagementScreens.Initial);\n const [selectedChatMemberId, setSelectedChatMemberId] = useState();\n const [isPromotedByCurrentUser, setIsPromotedByCurrentUser] = useState();\n const isScrolledDown = profileState !== ProfileState.Profile;\n\n const isOpen = contentKey !== undefined;\n const isProfile = contentKey === RightColumnContent.ChatInfo || contentKey === RightColumnContent.UserInfo;\n const isSearch = contentKey === RightColumnContent.Search;\n const isManagement = contentKey === RightColumnContent.Management;\n const isStickerSearch = contentKey === RightColumnContent.StickerSearch;\n const isGifSearch = contentKey === RightColumnContent.GifSearch;\n const isPollResults = contentKey === RightColumnContent.PollResults;\n const isAddingChatMembers = contentKey === RightColumnContent.AddingMembers;\n const isOverlaying = windowWidth <= MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN;\n\n const [shouldSkipTransition, setShouldSkipTransition] = useState(!isOpen);\n\n const renderingContentKey = useCurrentOrPrev(contentKey, true, !isChatSelected) ?? -1;\n\n const close = useCallback((shouldScrollUp = true) => {\n switch (contentKey) {\n case RightColumnContent.AddingMembers:\n setNewChatMembersDialogState(NewChatMembersProgress.Closed);\n break;\n case RightColumnContent.ChatInfo:\n if (isScrolledDown && shouldScrollUp) {\n setProfileState(ProfileState.Profile);\n break;\n }\n toggleChatInfo(undefined, { forceSyncOnIOs: true });\n break;\n case RightColumnContent.UserInfo:\n if (isScrolledDown && shouldScrollUp) {\n setProfileState(ProfileState.Profile);\n break;\n }\n openUserInfo({ id: undefined }, { forceSyncOnIOs: true });\n break;\n case RightColumnContent.Management: {\n switch (managementScreen) {\n case ManagementScreens.Initial:\n toggleManagement();\n break;\n case ManagementScreens.ChatPrivacyType:\n case ManagementScreens.Discussion:\n case ManagementScreens.GroupPermissions:\n case ManagementScreens.GroupType:\n case ManagementScreens.ChatAdministrators:\n case ManagementScreens.ChannelSubscribers:\n case ManagementScreens.GroupMembers:\n setManagementScreen(ManagementScreens.Initial);\n break;\n case ManagementScreens.GroupUserPermissionsCreate:\n case ManagementScreens.GroupRemovedUsers:\n case ManagementScreens.GroupUserPermissions:\n setManagementScreen(ManagementScreens.GroupPermissions);\n setSelectedChatMemberId(undefined);\n setIsPromotedByCurrentUser(undefined);\n break;\n case ManagementScreens.ChatAdminRights:\n case ManagementScreens.ChatNewAdminRights:\n case ManagementScreens.GroupAddAdmins:\n case ManagementScreens.GroupRecentActions:\n setManagementScreen(ManagementScreens.ChatAdministrators);\n break;\n }\n\n break;\n }\n case RightColumnContent.Search: {\n blurSearchInput();\n closeLocalTextSearch();\n break;\n }\n case RightColumnContent.StickerSearch:\n blurSearchInput();\n setStickerSearchQuery({ query: undefined });\n break;\n case RightColumnContent.GifSearch: {\n blurSearchInput();\n setGifSearchQuery({ query: undefined });\n break;\n }\n case RightColumnContent.PollResults:\n closePollResults();\n break;\n }\n }, [\n contentKey, isScrolledDown, toggleChatInfo, openUserInfo, closePollResults, setNewChatMembersDialogState,\n managementScreen, toggleManagement, closeLocalTextSearch, setStickerSearchQuery, setGifSearchQuery,\n ]);\n\n const handleSelectChatMember = useCallback((memberId, isPromoted) => {\n setSelectedChatMemberId(memberId);\n setIsPromotedByCurrentUser(isPromoted);\n }, []);\n\n const handleAppendingChatMembers = useCallback((memberIds: string[]) => {\n addChatMembers({ chatId, memberIds });\n }, [addChatMembers, chatId]);\n\n useEffect(() => (isOpen ? captureEscKeyListener(close) : undefined), [isOpen, close]);\n\n useEffect(() => {\n setTimeout(() => {\n setShouldSkipTransition(!isOpen);\n }, COLUMN_CLOSE_DELAY_MS);\n }, [isOpen]);\n\n // Close Right Column when it transforms into overlayed state on screen resize\n useEffect(() => {\n if (isOpen && isOverlaying) {\n close();\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [isOverlaying]);\n\n // We need to clear profile state and management screen state, when changing chats\n useLayoutEffectWithPrevDeps(([prevContentKey, prevChatId]) => {\n if (\n (prevContentKey === RightColumnContent.ChatInfo && contentKey === RightColumnContent.UserInfo)\n || (prevContentKey === RightColumnContent.UserInfo && contentKey === RightColumnContent.ChatInfo)\n || (prevChatId !== chatId)\n ) {\n setProfileState(ProfileState.Profile);\n setManagementScreen(ManagementScreens.Initial);\n }\n }, [contentKey, chatId]);\n\n useHistoryBack(isChatSelected && (contentKey === RightColumnContent.ChatInfo\n || contentKey === RightColumnContent.UserInfo || contentKey === RightColumnContent.Management\n || contentKey === RightColumnContent.AddingMembers),\n () => close(false), toggleChatInfo);\n\n // eslint-disable-next-line consistent-return\n function renderContent(isActive: boolean) {\n if (renderingContentKey === -1) {\n return undefined;\n }\n\n switch (renderingContentKey) {\n case RightColumnContent.AddingMembers:\n return (\n \n );\n case RightColumnContent.ChatInfo:\n case RightColumnContent.UserInfo:\n return (\n \n );\n case RightColumnContent.Search:\n return ;\n case RightColumnContent.Management:\n return (\n \n );\n\n case RightColumnContent.StickerSearch:\n return ;\n case RightColumnContent.GifSearch:\n return ;\n case RightColumnContent.PollResults:\n return ;\n }\n }\n\n return (\n \n {isOverlaying && (\n
\n )}\n
\n \n \n {renderContent}\n \n
\n
\n );\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { chatId, threadId } = selectCurrentMessageList(global) || {};\n const areActiveChatsLoaded = selectAreActiveChatsLoaded(global);\n\n return {\n contentKey: selectRightColumnContentKey(global),\n chatId,\n threadId,\n currentProfileUserId: global.users.selectedId,\n isChatSelected: Boolean(chatId && areActiveChatsLoaded),\n shouldSkipHistoryAnimations: global.shouldSkipHistoryAnimations,\n };\n },\n)(RightColumn));\n","import React, { FC, memo } from '../../lib/teact/teact';\n\nimport { Bundles } from '../../util/moduleLoader';\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\ninterface OwnProps {\n isOpen: boolean;\n}\n\nconst MediaViewerAsync: FC = ({ isOpen }) => {\n const MediaViewer = useModuleLoader(Bundles.Extra, 'MediaViewer', !isOpen);\n\n return MediaViewer ? : undefined;\n};\n\nexport default memo(MediaViewerAsync);\n","export default function download(url: string, filename: string) {\n const link = document.createElement('a');\n link.href = url;\n link.download = filename;\n try {\n link.click();\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(err); // Suppress redundant \"Blob loading failed\" error popup on IOS\n }\n}\n","import { FC, memo, useEffect } from '../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../lib/teact/teactn';\n\nimport { Thread } from '../../global/types';\nimport { ApiMediaFormat, ApiMessage } from '../../api/types';\n\nimport * as mediaLoader from '../../util/mediaLoader';\nimport download from '../../util/download';\nimport {\n getMessageContentFilename, getMessageMediaHash,\n} from '../../modules/helpers';\n\ntype StateProps = {\n activeDownloads: Record;\n messages: Record;\n threadsById: Record;\n }>;\n};\n\nconst startedDownloads = new Set();\n\nconst DownloadManager: FC = ({\n activeDownloads,\n messages,\n}) => {\n const { cancelMessageMediaDownload } = getDispatch();\n\n useEffect(() => {\n Object.entries(activeDownloads).forEach(([chatId, messageIds]) => {\n const activeMessages = messageIds.map((id) => messages[Number(chatId)].byId[id]);\n activeMessages.forEach((message) => {\n const downloadHash = getMessageMediaHash(message, 'download');\n if (!downloadHash) {\n cancelMessageMediaDownload({ message });\n return;\n }\n\n if (!startedDownloads.has(downloadHash)) {\n const mediaData = mediaLoader.getFromMemory(downloadHash);\n if (mediaData) {\n startedDownloads.delete(downloadHash);\n download(mediaData, getMessageContentFilename(message));\n cancelMessageMediaDownload({ message });\n return;\n }\n\n mediaLoader.fetch(downloadHash, ApiMediaFormat.BlobUrl, true).then((result) => {\n startedDownloads.delete(downloadHash);\n if (result) {\n download(result, getMessageContentFilename(message));\n }\n cancelMessageMediaDownload({ message });\n });\n\n startedDownloads.add(downloadHash);\n }\n });\n });\n }, [\n cancelMessageMediaDownload,\n messages,\n activeDownloads,\n ]);\n\n return undefined;\n};\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const activeDownloads = global.activeDownloads.byChatId;\n const messages = global.messages.byChatId;\n return {\n activeDownloads,\n messages,\n };\n },\n)(DownloadManager));\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst NotificationsAsync: FC = ({ isOpen }) => {\n const Notifications = useModuleLoader(Bundles.Extra, 'Notifications', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return Notifications ? : undefined;\n};\n\nexport default memo(NotificationsAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst DialogsAsync: FC = ({ isOpen }) => {\n const Dialogs = useModuleLoader(Bundles.Extra, 'Dialogs', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return Dialogs ? : undefined;\n};\n\nexport default memo(DialogsAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\nimport { OwnProps } from './ForwardPicker';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst ForwardPickerAsync: FC = (props) => {\n const { isOpen } = props;\n const ForwardPicker = useModuleLoader(Bundles.Extra, 'ForwardPicker', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return ForwardPicker ? : undefined;\n};\n\nexport default memo(ForwardPickerAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport { OwnProps } from './SafeLinkModal';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst SafeLinkModalAsync: FC = (props) => {\n const { url } = props;\n const SafeLinkModal = useModuleLoader(Bundles.Extra, 'SafeLinkModal', !url);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return SafeLinkModal ? : undefined;\n};\n\nexport default memo(SafeLinkModalAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport { Bundles } from '../../util/moduleLoader';\n\nimport { OwnProps } from './HistoryCalendar';\n\nimport useModuleLoader from '../../hooks/useModuleLoader';\n\nconst HistoryCalendarAsync: FC = (props) => {\n const { isOpen } = props;\n const HistoryCalendar = useModuleLoader(Bundles.Extra, 'HistoryCalendar', !isOpen);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return HistoryCalendar ? : undefined;\n};\n\nexport default memo(HistoryCalendarAsync);\n","import React, { FC, memo } from '../../../lib/teact/teact';\nimport useModuleLoader from '../../../hooks/useModuleLoader';\nimport { Bundles } from '../../../util/moduleLoader';\nimport { OwnProps } from './GroupCall';\n\nconst GroupCallAsync: FC = (props) => {\n const { groupCallId } = props;\n const GroupCall = useModuleLoader(Bundles.Calls, 'GroupCall', !groupCallId);\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n return GroupCall ? : undefined;\n};\n\nexport default memo(GroupCallAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport { Bundles } from '../../util/moduleLoader';\n\ntype OwnProps = {\n groupCallId?: string;\n};\n\nconst ActiveCallHeaderAsync: FC = (props) => {\n const { groupCallId } = props;\n const ActiveCallHeader = useModuleLoader(Bundles.Calls, 'ActiveCallHeader', !groupCallId);\n\n return ActiveCallHeader ? : undefined;\n};\n\nexport default memo(ActiveCallHeaderAsync);\n","import React, { FC, memo } from '../../lib/teact/teact';\nimport useModuleLoader from '../../hooks/useModuleLoader';\nimport { Bundles } from '../../util/moduleLoader';\n\ntype OwnProps = {\n isOpen: boolean;\n};\n\nconst CallFallbackConfirmAsync: FC = ({ isOpen }) => {\n const CallFallbackConfirm = useModuleLoader(Bundles.Calls, 'CallFallbackConfirm', !isOpen);\n\n return CallFallbackConfirm ? : undefined;\n};\n\nexport default memo(CallFallbackConfirmAsync);\n","import React, {\n FC, useEffect, memo, useCallback,\n} from '../../lib/teact/teact';\nimport { getDispatch, getGlobal, withGlobal } from '../../lib/teact/teactn';\n\nimport { LangCode } from '../../types';\nimport { ApiMessage } from '../../api/types';\n\nimport '../../modules/actions/all';\nimport {\n BASE_EMOJI_KEYWORD_LANG, DEBUG, INACTIVE_MARKER, PAGE_TITLE,\n} from '../../config';\nimport {\n selectChatMessage,\n selectCountNotMutedUnread,\n selectIsForwardModalOpen,\n selectIsMediaViewerOpen,\n selectIsRightColumnShown,\n selectIsServiceChatReady,\n} from '../../modules/selectors';\nimport { dispatchHeavyAnimationEvent } from '../../hooks/useHeavyAnimationCheck';\nimport buildClassName from '../../util/buildClassName';\nimport { fastRaf } from '../../util/schedulers';\nimport { waitForTransitionEnd } from '../../util/cssAnimationEndListeners';\nimport { processDeepLink } from '../../util/deeplink';\nimport stopEvent from '../../util/stopEvent';\nimport windowSize from '../../util/windowSize';\nimport useShowTransition from '../../hooks/useShowTransition';\nimport useBackgroundMode from '../../hooks/useBackgroundMode';\nimport useBeforeUnload from '../../hooks/useBeforeUnload';\nimport useOnChange from '../../hooks/useOnChange';\nimport usePreventPinchZoomGesture from '../../hooks/usePreventPinchZoomGesture';\nimport { LOCATION_HASH } from '../../hooks/useHistoryBack';\n\nimport LeftColumn from '../left/LeftColumn';\nimport MiddleColumn from '../middle/MiddleColumn';\nimport RightColumn from '../right/RightColumn';\nimport MediaViewer from '../mediaViewer/MediaViewer.async';\nimport AudioPlayer from '../middle/AudioPlayer';\nimport DownloadManager from './DownloadManager';\nimport Notifications from './Notifications.async';\nimport Dialogs from './Dialogs.async';\nimport ForwardPicker from './ForwardPicker.async';\nimport SafeLinkModal from './SafeLinkModal.async';\nimport HistoryCalendar from './HistoryCalendar.async';\nimport StickerSetModal from '../common/StickerSetModal.async';\nimport GroupCall from '../calls/group/GroupCall.async';\nimport ActiveCallHeader from '../calls/ActiveCallHeader.async';\nimport CallFallbackConfirm from '../calls/CallFallbackConfirm.async';\n\nimport './Main.scss';\n\ntype StateProps = {\n lastSyncTime?: number;\n isLeftColumnShown: boolean;\n isRightColumnShown: boolean;\n isMediaViewerOpen: boolean;\n isForwardModalOpen: boolean;\n hasNotifications: boolean;\n hasDialogs: boolean;\n audioMessage?: ApiMessage;\n safeLinkModalUrl?: string;\n isHistoryCalendarOpen: boolean;\n shouldSkipHistoryAnimations?: boolean;\n openedStickerSetShortName?: string;\n activeGroupCallId?: string;\n isServiceChatReady?: boolean;\n animationLevel: number;\n language?: LangCode;\n wasTimeFormatSetManually?: boolean;\n isCallFallbackConfirmOpen: boolean;\n addedSetIds?: string[];\n};\n\nconst NOTIFICATION_INTERVAL = 1000;\n\nlet notificationInterval: number | undefined;\n\n// eslint-disable-next-line @typescript-eslint/naming-convention\nlet DEBUG_isLogged = false;\n\nconst Main: FC = ({\n lastSyncTime,\n isLeftColumnShown,\n isRightColumnShown,\n isMediaViewerOpen,\n isForwardModalOpen,\n hasNotifications,\n hasDialogs,\n audioMessage,\n activeGroupCallId,\n safeLinkModalUrl,\n isHistoryCalendarOpen,\n shouldSkipHistoryAnimations,\n openedStickerSetShortName,\n isServiceChatReady,\n animationLevel,\n language,\n wasTimeFormatSetManually,\n isCallFallbackConfirmOpen,\n addedSetIds,\n}) => {\n const {\n loadAnimatedEmojis,\n loadNotificationSettings,\n loadNotificationExceptions,\n updateIsOnline,\n loadTopInlineBots,\n loadEmojiKeywords,\n loadCountryList,\n loadStickerSets,\n loadAddedStickers,\n loadFavoriteStickers,\n ensureTimeFormat,\n openStickerSetShortName,\n checkVersionNotification,\n } = getDispatch();\n const isSynced = Boolean(lastSyncTime);\n\n if (DEBUG && !DEBUG_isLogged) {\n DEBUG_isLogged = true;\n // eslint-disable-next-line no-console\n console.log('>>> RENDER MAIN');\n }\n\n // Initial API calls\n useEffect(() => {\n if (lastSyncTime) {\n updateIsOnline(true);\n loadAnimatedEmojis();\n loadNotificationSettings();\n loadNotificationExceptions();\n loadTopInlineBots();\n loadEmojiKeywords({ language: BASE_EMOJI_KEYWORD_LANG });\n }\n }, [\n lastSyncTime, loadAnimatedEmojis, loadEmojiKeywords, loadNotificationExceptions, loadNotificationSettings,\n loadTopInlineBots, updateIsOnline,\n ]);\n\n // Language-based API calls\n useEffect(() => {\n if (lastSyncTime) {\n if (language !== BASE_EMOJI_KEYWORD_LANG) {\n loadEmojiKeywords({ language });\n }\n\n loadCountryList({ langCode: language });\n }\n }, [language, lastSyncTime, loadCountryList, loadEmojiKeywords]);\n\n // Sticker sets\n useEffect(() => {\n if (isSynced) {\n if (!addedSetIds) {\n loadStickerSets();\n loadFavoriteStickers();\n } else {\n loadAddedStickers();\n }\n }\n }, [isSynced, addedSetIds, loadStickerSets, loadFavoriteStickers, loadAddedStickers]);\n\n // Check version when service chat is ready\n useEffect(() => {\n if (lastSyncTime && isServiceChatReady) {\n checkVersionNotification();\n }\n }, [lastSyncTime, isServiceChatReady, checkVersionNotification]);\n\n // Ensure time format\n useEffect(() => {\n if (lastSyncTime && !wasTimeFormatSetManually) {\n ensureTimeFormat();\n }\n }, [lastSyncTime, wasTimeFormatSetManually, ensureTimeFormat]);\n\n // Parse deep link\n useEffect(() => {\n if (lastSyncTime && LOCATION_HASH.startsWith('#?tgaddr=')) {\n processDeepLink(decodeURIComponent(LOCATION_HASH.substr('#?tgaddr='.length)));\n }\n }, [lastSyncTime]);\n\n // Prevent refresh by accidentally rotating device when listening to a voice chat\n useEffect(() => {\n if (!activeGroupCallId) {\n return undefined;\n }\n\n windowSize.disableRefresh();\n\n return () => {\n windowSize.enableRefresh();\n };\n }, [activeGroupCallId]);\n\n const {\n transitionClassNames: middleColumnTransitionClassNames,\n } = useShowTransition(!isLeftColumnShown, undefined, true, undefined, shouldSkipHistoryAnimations);\n\n const {\n transitionClassNames: rightColumnTransitionClassNames,\n } = useShowTransition(isRightColumnShown, undefined, true, undefined, shouldSkipHistoryAnimations);\n\n const className = buildClassName(\n middleColumnTransitionClassNames.replace(/([\\w-]+)/g, 'middle-column-$1'),\n rightColumnTransitionClassNames.replace(/([\\w-]+)/g, 'right-column-$1'),\n shouldSkipHistoryAnimations && 'history-animation-disabled',\n );\n\n // Dispatch heavy transition event when opening middle column\n useOnChange(([prevIsLeftColumnShown]) => {\n if (prevIsLeftColumnShown === undefined || animationLevel === 0) {\n return;\n }\n\n const dispatchHeavyAnimationEnd = dispatchHeavyAnimationEvent();\n\n waitForTransitionEnd(document.getElementById('MiddleColumn')!, dispatchHeavyAnimationEnd);\n }, [isLeftColumnShown]);\n\n // Dispatch heavy transition event and add body class when opening right column\n useOnChange(([prevIsRightColumnShown]) => {\n if (prevIsRightColumnShown === undefined || animationLevel === 0) {\n return;\n }\n\n fastRaf(() => {\n document.body.classList.add('animating-right-column');\n });\n\n const dispatchHeavyAnimationEnd = dispatchHeavyAnimationEvent();\n\n waitForTransitionEnd(document.getElementById('RightColumn')!, () => {\n dispatchHeavyAnimationEnd();\n\n fastRaf(() => {\n document.body.classList.remove('animating-right-column');\n });\n });\n }, [isRightColumnShown]);\n\n const handleBlur = useCallback(() => {\n updateIsOnline(false);\n\n const initialUnread = selectCountNotMutedUnread(getGlobal());\n let index = 0;\n\n clearInterval(notificationInterval);\n notificationInterval = window.setInterval(() => {\n if (document.title.includes(INACTIVE_MARKER)) {\n updateIcon(false);\n return;\n }\n\n if (index % 2 === 0) {\n const newUnread = selectCountNotMutedUnread(getGlobal()) - initialUnread;\n if (newUnread > 0) {\n updatePageTitle(`${newUnread} notification${newUnread > 1 ? 's' : ''}`);\n updateIcon(true);\n }\n } else {\n updatePageTitle(PAGE_TITLE);\n updateIcon(false);\n }\n\n index++;\n }, NOTIFICATION_INTERVAL);\n }, [updateIsOnline]);\n\n const handleFocus = useCallback(() => {\n updateIsOnline(true);\n\n clearInterval(notificationInterval);\n notificationInterval = undefined;\n\n if (!document.title.includes(INACTIVE_MARKER)) {\n updatePageTitle(PAGE_TITLE);\n }\n\n updateIcon(false);\n }, [updateIsOnline]);\n\n const handleStickerSetModalClose = useCallback(() => {\n openStickerSetShortName({ stickerSetShortName: undefined });\n }, [openStickerSetShortName]);\n\n // Online status and browser tab indicators\n useBackgroundMode(handleBlur, handleFocus);\n useBeforeUnload(handleBlur);\n\n usePreventPinchZoomGesture(isMediaViewerOpen);\n\n return (\n
\n \n \n \n \n \n \n \n {audioMessage && }\n \n \n \n {activeGroupCallId && (\n <>\n \n \n \n )}\n \n \n
\n );\n};\n\nfunction updateIcon(asUnread: boolean) {\n document.querySelectorAll('link[rel=\"icon\"], link[rel=\"alternate icon\"]')\n .forEach((link) => {\n if (asUnread) {\n if (!link.href.includes('favicon-unread')) {\n link.href = link.href.replace('favicon', 'favicon-unread');\n }\n } else {\n link.href = link.href.replace('favicon-unread', 'favicon');\n }\n });\n}\n\n// For some reason setting `document.title` to the same value\n// causes increment of Chrome Dev Tools > Performance Monitor > DOM Nodes counter\nfunction updatePageTitle(nextTitle: string) {\n if (document.title !== nextTitle) {\n document.title = nextTitle;\n }\n}\n\nexport default memo(withGlobal(\n (global): StateProps => {\n const { settings: { byKey: { animationLevel, language, wasTimeFormatSetManually } } } = global;\n const { chatId: audioChatId, messageId: audioMessageId } = global.audioPlayer;\n const audioMessage = audioChatId && audioMessageId\n ? selectChatMessage(global, audioChatId, audioMessageId)\n : undefined;\n\n return {\n lastSyncTime: global.lastSyncTime,\n isLeftColumnShown: global.isLeftColumnShown,\n isRightColumnShown: selectIsRightColumnShown(global),\n isMediaViewerOpen: selectIsMediaViewerOpen(global),\n isForwardModalOpen: selectIsForwardModalOpen(global),\n hasNotifications: Boolean(global.notifications.length),\n hasDialogs: Boolean(global.dialogs.length),\n audioMessage,\n safeLinkModalUrl: global.safeLinkModalUrl,\n isHistoryCalendarOpen: Boolean(global.historyCalendarSelectedAt),\n shouldSkipHistoryAnimations: global.shouldSkipHistoryAnimations,\n openedStickerSetShortName: global.openedStickerSetShortName,\n isServiceChatReady: selectIsServiceChatReady(global),\n activeGroupCallId: global.groupCalls.activeGroupCallId,\n animationLevel,\n language,\n wasTimeFormatSetManually,\n isCallFallbackConfirmOpen: Boolean(global.groupCalls.isFallbackConfirmOpen),\n addedSetIds: global.stickers.added.setIds,\n };\n },\n)(Main));\n","import { getDispatch, getGlobal } from '../lib/teact/teactn';\n\nimport { DEBUG } from '../config';\n\nexport { default as Main } from '../components/main/Main';\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH LOAD MAIN BUNDLE');\n}\n\nif (!getGlobal().connectionState) {\n getDispatch().initApi();\n}\n"],"names":["closeLocalTextSearch","global","chatId","threadId","selectCurrentMessageList","updateLocalTextSearch","replaceLocalTextSearchResults","undefined","addReducer","actions","payload","query","chatThreadKey","buildChatThreadKey","currentQuery","localTextSearch","byChatThreadKey","MEMO_EMPTY_ARRAY","mediaType","updateLocalMediaSearchType","id","type","shouldReplaceHistory","currentMessageList","replaceThreadParam","exitMessageSelectMode","messages","contentToBeScheduled","forwardMessages","toChatId","setGlobal","updateCurrentMessageList","isChatInfoShown","openChat","chatCreation","newChatMembersProgress","targetIndexDelta","orderedIds","position","indexOf","nextId","FOCUS_NO_HIGHLIGHT_DURATION","FAST_SMOOTH_MAX_DURATION","ANIMATION_END_DELAY","blurTimeout","scrollOffset","messageId","paramName","chatMessages","selectChatMessages","viewportIds","selectViewportIds","lastOwnEditableMessageId","findLast","Boolean","selectAllowedMessageActions","canEdit","replyingToId","selectReplyingToId","selectIsViewportNewest","chatMessageKeys","Object","keys","newIndex","toString","length","Number","MAIN_THREAD_ID","chat","selectChat","lastMessage","threadInfo","selectThreadInfo","lastMessageId","setReplyingToId","focusMessage","avatarOwnerId","profilePhotoIndex","origin","mediaViewer","volume","playbackRate","isMuted","audioPlayer","selectIsRightColumnShown","pollResults","voters","window","setTimeout","newGlobal","getGlobal","noHighlight","replyStack","selectReplyStack","pop","focusLastMessage","messageListType","groupedId","groupedChatId","replyMessageId","isResizingContainer","ids","selectForwardedMessageIdsByGroupId","shouldSwitchChat","clearTimeout","updateFocusedMessage","updateFocusDirection","FocusDirection","includes","direction","loadViewportMessages","fromChatId","messageIds","groupedMessageIds","selectMessageIdsByGroupId","isModalShown","closeMediaViewer","selectedMessages","openForwardMenu","message","byChatId","activeDownloads","filter","map","canDownload","forEach","downloadMessageMedia","selectCurrentChat","enterMessageSelectMode","childMessageIds","withShift","toggleMessageSelection","shouldShowContextMenuHint","disableContextMenuHint","showNotification","IS_TOUCH_ENV","isPollModalOpen","currentVersion","APP_VERSION","slice","join","serviceNotifications","find","version","SERVICE_NOTIFICATIONS_USER_ID","date","getServerTime","serverTimeOffset","content","text","parseMessageInput","isOutgoing","createServiceNotification","serviceChat","maxId","Math","max","fractionalPart","floor","serviceNotification","isUnread","apiUpdate","seenByModal","globalSearch","updateGlobalSearch","globalResults","localResults","resultsByType","fetchingStatus","chats","recentlyFoundChatIds","newRecentIds","unshift","updateGlobalSearchContent","stickers","search","resultIds","gifs","offsetId","results","updateSelectedUserId","updateUserSearch","globalUserIds","localUserIds","leftColumnWidth","management","isActive","IS_SINGLE_COLUMN_LAYOUT","IS_TABLET_COLUMN_LAYOUT","isLeftColumnShown","messageLists","action","emoji","recentEmojis","newEmojis","e","sticker","recent","hash","newStickers","s","notification","localId","generateIdFor","newNotifications","notifications","existingNotificationIndex","findIndex","n","splice","push","data","hasErrorKey","getReadableErrorText","newDialogs","dialogs","existingErrorIndex","err","url","safeLinkModalUrl","selectedAt","historyCalendarSelectedAt","payment","isPaymentModalOpen","clearPayment","closeInvoice","error","uploadProgressCallbacks","Map","runDebouncedForMarkRead","debounce","cb","async","isOutlying","isBudgetPreload","addOffset","LoadMoreDirection","round","MESSAGE_LIST_SLICE","result","callApi","selectThreadOriginChat","limit","users","threadInfos","localMessages","allMessages","concat","byId","buildCollectionByKey","addChatMessagesById","updateOutlyingIds","updateListedIds","addUsers","addChats","updateThreadInfos","listedIds","selectListedIds","outlyingIds","selectOutlyingIds","areSortedArraysIntersecting","historyIds","newViewportIds","getViewportSlice","safeReplaceViewportIds","sourceIds","index","i","findClosestIndex","indexForDirection","from","to","areSomeLocal","areAllLocal","sendMessage","params","progressCallback","attachment","progress","messageLocalId","has","set","fileUploads","byMessageLocalId","replyingTo","IS_IOS","rafPromise","selectThreadTopMessageId","delete","isRestricted","Promise","resolve","loadWithBudget","selectFocusedMessageId","selectRealLastReadId","replyOriginForId","threadUpdate","MESSAGE_DELETED","replyMessage","selectChatMessage","updateChatMessage","replyToMessageId","loadMessage","isDeleting","updateThreadUnreadFromForwardedMessage","scheduledAt","noWebPage","selectNoWebPage","sendAs","selectSendAs","clearWebPagePreview","value","isSingle","attachments","isGrouped","restParams","entities","commonParams","groupedAttachments","split","MAX_MEDIA_FILES_FOR_ALBUM","firstAttachment","restAttachments","Date","now","selectEditingMessage","setEditingId","get","previousLocalId","cancelApiProgress","draft","replyToMsgId","updateChat","draftDate","localOnly","selectDraft","isUnpin","isOneSide","isSilent","unpinAllMessages","shouldDeleteForAll","editingId","selectEditingId","selectEditingScheduledId","activeChat","reason","description","peer","currentUserId","minId","selectFirstUnreadId","unreadCount","readCount","count","l","countSortedIds","lastReadInboxMessageId","webPagePreview","loadWebPagePreview","options","option","offset","shouldResetVoters","unique","user","offsets","nextOffset","loadPollOptionResults","fromChat","toChat","sort","a","b","realMessages","m","isServiceNotificationMessage","poll","replaceScheduledMessages","loadScheduledHistory","selectScheduledMessage","loadPinnedMessages","seenByUserIds","sendAsId","sendAsChat","selectUser","fullInfo","sendAsIds","updateSponsoredMessage","selectSponsoredMessage","random","randomId","searchThrottled","throttle","searchGifs","updateGifSearch","added","addedStickers","updateStickerSets","sets","loadStickerSets","setIds","addedSetIds","loadStickers","stickerSetId","pause","recentStickers","loadRecentStickers","favorite","favoriteStickers","loadFavoriteStickers","greeting","featured","featuredStickers","loadFeaturedStickers","stickerSetShortName","stickerSetAccessHash","stickerSet","selectStickerSet","accessHash","packs","updateStickerSet","currentEmoji","forEmoji","rebuildStickersForEmoji","replaceAnimatedEmojis","loadAnimatedEmojis","saved","savedGifs","loadSavedGifs","unfave","unfaveSticker","installedDate","language","currentEmojiKeywords","emojiKeywords","isLoading","fromVersion","keywords","searchStickers","setsById","title","searchWords","updateStickersForEmoji","loadStickersForEmoji","openedStickerSetShortName","searchMessagesGlobal","offsetRate","maxDate","minDate","localResult","chatOrUser","GLOBAL_SEARCH_SLICE","totalCount","nextOffsetId","nextRate","currentSearchQuery","selectCurrentGlobalSearchQuery","updateGlobalSearchFetchingStatus","addMessages","updateGlobalSearchResults","localChats","localUsers","globalChats","globalUsers","chatIds","userIds","searchChats","timestampPlusDay","foundIds","currentSearch","selectCurrentTextSearch","topMessageId","MESSAGE_SEARCH_SLICE","newFoundIds","updateLocalTextSearchResults","searchTextMessages","peerId","selectCurrentMediaSearchPeerId","selectCurrentMediaSearch","currentType","currentResults","SHARED_MEDIA_SLICE","updateLocalMediaSearchResults","searchSharedMedia","timestamp","getDispatch","searchMessagesByDate","ManagementProgress","username","updateManagementProgress","updateManagement","isUsernameAvailable","isChatBasicGroup","loadAndReplaceArchivedChats","CHAT_LIST_LOAD_SLICE","archived","withPinned","updateUsers","addUserStatuses","userStatusesById","updateChats","replaceChatListIds","updateChatListSecondaryInfo","loadAndUpdateUsers","contactIds","contactList","updatedUsers","loadTopMessages","afterSyncCallback","DEBUG","console","log","savedUsers","lastLocalServiceMessage","selectLastServiceNotification","savedPrivateChatIds","savedChats","currentChatId","selectedChat","isUserId","selectedChatUser","replaceUserStatuses","replaceChats","draftsById","replyingToById","loadAndReplaceChats","areMessagesLoaded","currentThreadId","draftsByChatId","reduce","acc","newCurrentChatId","currentMessageListInfo","originChannelId","currentMessageListInfoOrigin","resultOrigin","byIdOrigin","listedIdsOrigin","threadsById","Array","prototype","replaceUsers","audioChatId","audioMessageId","closeAudioPlayer","loadAndReplaceMessages","lastSyncTime","sync","afterSync","all","updateAppBadge","selectCountNotMutedUnread","runDebouncedForFetchFullUser","runThrottledForSearch","replaceInlineBotSettings","inlineBotSettings","inlineBots","byUsername","replaceInlineBotsIsLoading","userId","statusesById","topPeers","lastRequestedAt","loadTopUsers","getCompareString","lastName","firstName","collator","Intl","Collator","sortedUsers","compare","isSelf","loadContactList","isUserBot","commonChats","isFullyLoaded","updateUser","updateChatMutedState","phoneNumber","phone","updateContact","deleteContact","profileId","isPrivate","photos","userSearch","updateUserSearchFetchingStatus","searchUsers","pick","runDebouncedForSearch","sendBotCommand","command","button","match","RE_TME_LINK","RE_TG_LINK","openTelegramLink","toggleSafeLinkModal","showDialog","alert","isError","answerCallbackButton","openPollModal","getReceipt","receiptMessageId","getPaymentForm","setInvoiceMessageInfo","openPaymentModal","bot","selectChatBot","removeBlockedContact","topInlineBots","inlineBotData","inlineBot","switchPm","canLoadMore","shouldReplaceSettings","newInlineBotData","currentIds","Set","newResults","help","isGallery","searchInlineBot","queryId","resultId","botId","param","startParam","replaceSettings","hasPassword","updateTwoFaSettings","hint","currentPassword","onSuccess","isSuccess","password","email","waitingEmailCodeLength","code","requestInfo","saveInfo","selectPaymentChatId","selectPaymentMessageId","shouldSave","shippingOptions","setRequestInfoId","updateShippingOptions","setPaymentStep","PaymentStep","validateRequestedInfo","setPaymentForm","step","invoice","shippingAddressRequested","nameRequested","phoneRequested","emailRequested","setReceipt","receipt","publishableKey","selectProviderPublishableKey","credentials","k","buildQueryString","cardNumber","expiryMonth","expiryYear","cvv","zip","country","response","fetch","method","headers","Authorization","json","getStripeError","setStripeCardInfo","sendStripeCredentials","shippingOptionId","saveCredentials","formId","selectPaymentFormId","requestInfoId","selectPaymentRequestId","stripeCredentials","selectStripeCredentials","requestedInfoId","sendPaymentForm","save","runThrottledForUpdateAppBadge","update","noTopChatsRequest","selectIsChatListed","loadTopChats","newProfilePhoto","closeMessageNotifications","listType","selectChatListType","updateChatListIds","isNotJoined","requestChatUpdate","leaveChat","typingStatus","senderId","isFromScheduled","hasUnreadMention","unreadMentionsCount","notifyAboutNewMessage","messageUpdate","channelId","selectCommonBoxChatId","targetChat","folderId","ARCHIVED_FOLDER_ID","orderedPinnedIds","isPinned","newOrderedPinnedIds","MAX_ACTIVE_PINNED_CHATS","listIds","active","pinnedId","updateChatListType","folder","chatFoldersById","chatFolders","newChatFoldersById","newOrderedIds","orderedId","folders","recommended","replacedMembers","addedMember","deletedMemberId","shouldUpdate","members","some","deleteIndex","adminMembers","isOwner","isAdmin","membersCount","photo","formattedText","ANIMATION_DELAY","updateWithLocalMedia","isScheduled","currentMessage","video","document","getMessageContent","blobUrl","thumbnail","isPreloadedGlobally","previewBlobUrl","updateScheduledMessage","updateThreadUnread","selectThreadByMessage","originMessage","updateListedAndViewportIds","firstMessageId","isUnreadChatNotLoaded","isMessageLocal","addViewportId","messagesCount","firstUnreadId","updateChatLastMessage","force","currentLastMessage","findLastMessage","deleteMessages","newLastMessage","threadIdsToUpdate","deleteChatMessages","requestThreadInfoUpdate","chatsIdsToUpdate","commonBoxChatId","shouldForceReply","updateThreadInfo","newMessage","isMessageInCurrentMessageList","delayedGlobal","scheduledIds","selectScheduledIds","selectIsChatWithBot","selectScheduledMessages","deleteChatScheduledMessages","thread","markMessageListRead","currentPinnedIds","selectPinnedIds","newPinnedIds","newTheadInfo","messagesById","loadFullChat","scheduledMessages","deleteScheduledMessages","pollId","pollUpdate","selectChatMessageByPollId","updatedPoll","updatedResults","isChosen","chosenAnswers","chosenAnswer","chosenAnswerIndex","recentVoterIds","totalVoters","newRecentVoterIds","newTotalVoters","targetOption","targetOptionIndex","updatedOption","votersCount","selectIsServiceChatReady","flushStatusUpdatesThrottled","pendingStatusUpdates","statusUpdate","status","targetUser","isBlocked","addBlockedContact","settings","privacy","key","rules","updateNotifySettings","peerType","shouldShowPreviews","addNotifyException","twoFaSettings","call","connectionState","groupCalls","activeGroupCallId","leaveGroupCall","shouldRemove","removeGroupCall","updateGroupCall","omit","participantsCount","groupCallId","participants","participant","updateGroupCallParticipant","useBeforeUnload","callback","useEffect","onBeforeUnload","metaViewport","querySelector","defaultViewportContent","getAttribute","preventEvent","preventDefault","useBrowserOnline","isOnline","setIsOnline","useState","navigator","onLine","handleChange","addEventListener","removeEventListener","ANIMATION_LEVEL_OPTIONS","memo","withGlobal","searchQuery","chatsById","animationLevel","byKey","globalSearchChatId","searchDate","theme","selectTheme","contactsFilter","onSearchQuery","onSelectSettings","onSelectContacts","onSelectArchived","onReset","shouldSkipTransition","openTipsChat","setGlobalSearchDate","setSettingOption","setGlobalSearchChatId","lang","useLang","hasMenu","LeftColumnContent","selectedSearchDate","useMemo","formatDateToString","archivedUnreadChatsCount","values","total","isChatArchived","withOtherVersions","location","hostname","MainButton","onTrigger","isOpen","Button","ripple","size","color","className","onClick","ariaLabel","buildClassName","handleSearchFocus","useCallback","handleSelectSaved","handleDarkModeToggle","stopPropagation","newTheme","shouldUseSystemTheme","switchTheme","ANIMATION_LEVEL_MAX","handleAnimationLevelChange","newLevel","_","body","classList","toggle","isSearchFocused","searchInputPlaceholder","DropdownMenu","trigger","footer","APP_NAME","MenuItem","icon","Switcher","label","checked","noAnimation","toLowerCase","langCode","href","FEEDBACK_URL","localStorage","setItem","JSON","stringify","disableHistoryBack","SearchInput","inputId","parentContainerClassName","focused","placeholder","autoComplete","canClose","onChange","onFocus","PickerSelectedItem","isMinimized","clickArg","chatOrUserId","dir","isRtl","Spinner","allListIds","usersById","orderedFolderIds","activeChatFolder","shouldSkipHistoryAnimations","notifySettings","selectNotifySettings","notifyExceptions","selectNotifyExceptions","foldersDispatch","onScreenSelect","loadChatFolders","setActiveChatFolder","transitionRef","useRef","displayedFolders","folderCountersById","resolverFn","ms","dependencies","runThrottled","useThrottle","setValue","isFrozen","freeze","unfreeze","useFlag","useHeavyAnimationCheck","useOnChange","counters","unreadDialogsCount","hasActiveDialogs","getFolderUnreadDialogs","badgeCount","isBadgeActive","useThrottledMemo","folderTabs","ALL_FOLDER_ID","handleSwitchTab","forceOnHeavyAnimation","current","captureEvents","selectorToPreventScroll","onSwipe","SwipeDirection","min","isNotInAllTabRef","captureEscKeyListener","useHistoryBack","handleKeyDown","ctrlKey","shiftKey","startsWith","digit","shouldRender","shouldRenderPlaceholder","transitionClassNames","useShowTransition","renderCurrentTab","activeFolder","ChatList","folderType","TabList","tabs","activeTab","onSwitchTab","Transition","ref","name","activeKey","renderCount","props","LeftSearch","useModuleLoader","Bundles","Loading","ContactList","closeTimeout","isShown","onNewPrivateChat","onNewChannel","onNewGroup","isMenuOpen","setIsMenuOpen","fabClassName","handleMouseEnter","handleMouseLeave","onMouseEnter","onMouseLeave","tabIndex","Menu","positionX","positionY","autoClose","onClose","TRANSITION_RENDER_COUNT","onContentChange","isNewChatButtonShown","setIsNewChatButtonShown","isConnecting","isMouseInside","handleSelectSettings","handleSelectContacts","handleSelectNewChannel","handleSelectNewGroup","handleSelectArchived","autoCloseTimeout","shouldRenderUpdateButton","updateButtonClassNames","handleUpdateClick","isAppOutdated","markIsAppOutdated","timeout","reload","useAppOutdatedCheck","ShowTransition","isCustom","shouldCleanup","cleanupExceptionKey","fluid","pill","Settings","NewChat","ArchivedChats","ContentType","RENDER_COUNT","setGlobalSearchQuery","resetChatCreation","loadPasswordInfo","clearTwoFaError","setLeftColumnWidth","resetLeftColumnWidth","resizeRef","setContent","settingsScreen","setSettingsScreen","SettingsScreens","setContactsFilter","foldersState","useFoldersReducer","lastResetTime","setLastResetTime","contentType","Main","Archived","NewChannel","NewGroup","handleReset","forceReturnToChatList","pickerSearchInput","getElementById","blur","handleSearchQuery","IS_MAC_OS","metaKey","getKeyFromEvent","initResize","resetResize","handleMouseUp","elementRef","onResize","initialWidth","markIsActive","unmarkIsActive","initialMouseX","setInitialMouseX","initialElementWidth","setInitialElementWidth","style","width","remove","handleMouseMove","event","newWidth","ceil","clientX","stopDrag","offsetWidth","add","useResize","handleSettingsScreenSelect","screen","LAYERS_ANIMATION_NAME","currentScreen","isChannel","onMouseDown","onMouseUp","onDoubleClick","setSize","windowSize","handleResize","MAX_MESSAGES_LIST_WIDTH","HeaderMenuContainer","isChatChannel","selectIsInSelectMode","noMenu","isChatWithSelf","selectIsChatWithSelf","isMainThread","isDiscussionThread","isRightColumnShown","canRestartBot","selectIsUserBlocked","canStartBot","selectIsChatBotNotStarted","canSubscribe","isChatSuperGroup","canSearch","canCall","ARE_CALLS_SUPPORTED","canMute","canLeave","canEnterVoiceChat","isCallActive","canCreateVoiceChat","adminRights","manageCall","isCreator","canExpandActions","joinChannel","openLocalTextSearch","restartBot","openCallFallbackConfirm","menuButtonRef","menuPosition","setMenuPosition","handleHeaderMenuOpen","rect","getBoundingClientRect","x","right","y","bottom","handleHeaderMenuClose","handleHeaderMenuHide","handleSubscribeClick","handleStartBot","handleRestartBot","handleSearchClick","focus","searchInput","IS_PWA","disabled","anchor","withExtraActions","onSubscribeChannel","onSearchClick","onCloseAnimationEnd","useWebpThumbnail","thumbDataUri","getMessageMediaThumbDataUri","shouldDecodeThumbnail","isWebpSupported","thumbnailDecoded","setThumbnailDecoded","EMPTY_IMAGE_DATA_URI","useLayoutEffect","webpToPngBase64","then","catch","drawRect","height","radius","containerRef","markupParams","reverseIndex","barHeight","getBarHeight","markHeight","getMarkHeight","trackHeight","getTrackHeight","clipPathId","clipPath","d","getClipPath","markTranslateY","getMarkTranslateY","trackTranslateY","getTrackTranslateY","calculateMarkup","firstChild","firstElementChild","currentElement","transform","svg","div","defs","innerHTML","customTitle","onUnpinMessage","onAllPinnedClick","mediaThumbnail","mediaBlobUrl","useMedia","getMessageMediaHash","getMessageSummaryText","isUnpinDialogOpen","openUnpinDialog","closeUnpinDialog","handleUnpinMessage","ConfirmDialog","confirmLabel","confirmHandler","getPictogramDimensions","src","alt","renderPictogram","renderText","RippleEffect","scaleImage","image","ratio","outputType","Blob","URL","createObjectURL","img","Image","onload","scale","blob","finally","revokeObjectURL","steppedScale","bitmap","createImageBitmap","resizeWidth","resizeHeight","resizeQuality","Error","res","canvas","createElement","ctx","getContext","transferFromImageBitmap","drawImage","toBlob","oc","octx","mul","cur","LOGO_DIMENSIONS","MINIMAL_SIZE","sender","audio","voice","fileName","artist","performer","getSenderTitle","getTranslation","album","getChatTitle","audioCoverHash","getAudioHasCover","avatarHash","getChatAvatarHash","media","thumbnailSizes","AVATAR_FULL_DIMENSIONS","getCoverSize","fn","deps","defaultValue","setIsLoading","setError","setResult","wasCancelled","telegramLogoPath","resizeImage","makeGoodArtwork","useAsync","buildMediaMetadata","artwork","selectSender","noUi","setAudioPlayerVolume","setAudioPlayerPlaybackRate","setAudioPlayerMuted","isVoice","senderName","mediaData","mediaLoader","mediaMetadata","useMessageMediaMetadata","playPause","stop","isPlaying","requestNextTrack","requestPreviousTrack","isFirst","isLast","setVolume","toggleMuted","setPlaybackRate","useAudioPlayer","makeTrackId","getMediaDuration","isVoicePlaying","handleClick","handleClose","clearMediaSession","handleVolumeChange","handleVolumeClick","handlePlaybackClick","volumeIcon","renderAudio","subtitle","renderVoice","withClickPropagation","RangeSlider","groupCall","selectChatGroupCall","isLoaded","isCallNotEmpty","hasPinnedOffset","joinGroupCall","subscribeToGroupCallUpdates","handleJoinGroupCall","fetchedParticipants","isUser","subscribed","p","Avatar","audioMessage","pinnedIds","state","isSelectModeActive","isChatWithBot","currentTransitionKey","assign","pinnedMessageId","topMessageSender","selectForwardedSender","pinnedMessageIds","canUnpin","firstPinnedMessage","isReady","openChatWithInfo","pinMessage","openPreviousChat","toggleLeftColumn","isBackButtonActive","pinnedMessageIndex","setPinnedMessageIndex","isArray","pinnedMessage","pinnedMessagesCount","chatTitleLength","topMessageTitle","useEnsureMessage","windowWidth","useWindowSize","isLeftColumnHideable","MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN","shouldShowCloseButton","componentRef","shouldAnimateTools","handleHeaderClick","handlePinnedMessageClick","cycleRestrict","handleAllPinnedClick","setBackButtonActive","handleBackClick","messageInput","EDITABLE_INPUT_ID","canToolsCollideWithChatInfo","SAFE_SCREEN_WIDTH_FOR_CHAT_INFO","MOBILE_SCREEN_MAX_WIDTH","shouldUseStackedToolsClass","MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN","SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN","shouldRenderAudioPlayer","audioPlayerClassNames","renderingAudioMessage","useCurrentOrPrev","shouldRenderPinnedMessage","pinnedMessageClassNames","renderingPinnedMessage","renderingPinnedMessagesCount","renderingCanUnpin","renderingPinnedMessageTitle","canRevealTools","componentEl","renderInfo","renderBackButton","PrivateChatInfo","withFullInfo","withMediaViewer","withUpdatingStatus","noRtl","GroupChatInfo","asClose","withUnreadCount","formatIntegerCompact","isAudioPlayerRendered","Infinity","getMessageKey","isAlbum","messageOrAlbum","groupMessages","currentAlbum","currentSenderGroup","currentDateGroup","originalDate","datetime","getDayStart","senderGroups","dateGroups","isInAlbum","mainMessage","albumId","nextMessage","nextMessageDayStartsAt","isActionMessage","forwardInfo","senderUserId","hiddenUserName","inlineButtons","INTERSECTION_THROTTLE_FOR_MEDIA","IS_ANDROID","INTERSECTION_MARGIN_FOR_MEDIA","isEmojiOnlyMessage","customShape","getMinMediaWidth","hasText","hasCommentButton","calculateMediaDimensions","noAvatars","isOwn","isOwnMessage","isForwarded","isForwardedMessage","getMessagePhoto","getMessageWebPagePhoto","getMessageVideo","isWebPagePhoto","calculateInlineImageDimensions","calculateVideoDimensions","minMediaWidth","getMessageText","stretchFactor","finalWidth","finalHeight","isSmall","accumulate","list","initValue","accumulator","item","clamp","num","low","high","calculateContainerSize","layout","styles","dimensions","sides","calculateAlbumLayout","ratios","proportions","getProportions","averageRatio","getAverageRatio","albumCount","forceCalc","maxWidth","getAvailableWidth","REM","minWidth","maxHeight","spacing","originalRatios","cropRatios","attempts","pushAttempt","lineCounts","heights","currentCount","attemptCount","sum","multiHeight","first","second","third","fourth","optimalAttempt","optimalDiff","lineCount","totalHeight","bad1","bad2","line","diff","abs","optimalCounts","optimalHeights","rowCount","row","colCount","lineHeight","col","layoutWithComplexLayouter","AlbumRectPart","layoutTwoTopBottom","layoutTwoLeftRightEqual","minimalWidth","secondWidth","firstWidth","layoutTwoLeftRight","layoutTwo","firstHeight","thirdHeight","secondHeight","rightWidth","leftWidth","layoutThreeLeftAndOther","layoutThreeTopAndOther","layoutThree","w","h0","h","w0","w2","w1","h1","layoutFourTopAndOther","h2","layoutFourLeftAndOther","layoutFour","containerStyle","element","calculateAuthorWidth","font","whiteSpace","left","opacity","appendChild","useFocusMessage","isFocused","focusDirection","noFocusHighlight","messagesContainer","closest","fastSmoothScroll","ContextMenuContainer","targetUserIds","targetChatId","targetMessageId","targetMessage","selectIsMessageFocused","focusedMessage","observeIntersection","isEmbedded","appearanceOrder","isLastInList","useOnIntersect","noAppearanceAnimation","markShown","targetUsers","renderActionMessageText","asPlain","isContextMenuOpen","contextMenuPosition","handleBeforeContextMenu","handleContextMenu","handleContextMenuClose","handleContextMenuHide","useContextMenuHandlers","isContextMenuShown","preventMessageInputBlur","onContextMenu","customText","isProtected","isIntersecting","useIsIntersecting","pictogramId","isRoundVideo","getMessageRoundVideo","senderTitle","draggable","outgoingStatus","signature","isActivated","markActivated","createDateTime","formatDateTimeToString","editDateTime","isEdited","editDate","forwardedDateTime","replace","views","formatTime","MessageOutgoingStatus","observeIntersectionForPlaying","shouldLoop","isModalOpen","openModal","closeModal","isAnimated","isMemojiSticker","MEMOJI_STICKER_ID","shouldLoad","shouldPlay","mediaHash","getMessageMediaFormat","isMediaLoaded","isAnimationLoaded","markAnimationLoaded","isMediaReady","useMediaTransition","getStickerDimensions","thumbClassName","stickerClassName","AnimatedSticker","animationData","play","noLoop","onLoad","fromSticker","useBlurredMediaThumbRef","fullMediaData","useCanvasBlur","IS_CANVAS_FILTER_SUPPORTED","SELECTED_APPENDIX_COLORS","dark","outgoing","incoming","light","canAutoLoad","isInSelectMode","isSelected","uploadProgress","nonInteractive","shouldAffectAppendix","isDownloading","onCancelUpload","localBlobUrl","isLoadAllowed","setIsLoadAllowed","loadProgress","useMediaWithLoadProgress","thumbRef","downloadProgress","isUploading","isTransferring","transferProgress","getMediaTransferState","wasLoadDisabled","usePrevious","shouldRenderSpinner","spinnerClassNames","shouldRenderDownloadButton","downloadButtonClassNames","isAllowed","contentEl","inSelectMode","getImageData","getAppendixColorFromImage","getCustomAppendixBg","appendixBg","setProperty","setAttribute","ProgressSpinner","useVideoAutoPause","playerRef","canPlay","wasPlaying","paused","canPlayRef","freezePlaying","unfreezePlaying","contains","safePlay","unfreezePlayingOnRaf","fastRaf","useBackgroundMode","canAutoPlay","videoRef","getMessageWebPageVideo","isPlayAllowed","setIsPlayAllowed","previewClassNames","isInline","ApiMediaFormat","isBuffered","bufferingHandlers","useBuffering","shouldRenderPlayButton","playButtonClassNames","playProgress","setPlayProgress","handleTimeUpdate","currentTarget","currentTime","duration","useVideoCleanup","cancelMessageMediaDownload","autoPlay","muted","loop","playsInline","onTimeUpdate","isGif","formatMediaDuration","contact","countryList","phoneCodes","phoneCodeList","openUserInfo","formatPhoneNumberWithCode","getPercentage","toFixed","answer","voteResults","maxVotersCount","correctResults","shouldAnimate","r","correctAnswer","showIcon","answerPercent","finalPercent","setFinalPercent","lineRef","lineWidth","isAnimationDoesNotStart","lineEl","svgEl","lineStyle","onSendVote","openPollResults","summary","isSubmitting","setIsSubmitting","chosenOptions","setChosenOptions","isSolutionShown","setIsSolutionShown","wasSubmitted","setWasSubmitted","closePeriod","setClosePeriod","closed","closeDate","countdownRef","hasVoted","canVote","canViewResult","isPublic","isMultiple","multipleChoice","answers","isCorrect","hidden","quiz","countdownEl","circumference","PI","lastElementChild","timerEl","strokeDashOffset","textContent","timer","recentVoters","handleRadioChange","handleCheckboxChange","handleVoteClick","handleViewResultsClick","handleSolutionShow","handleSolutionHide","solution","Notification","renderTextWithEntities","solutionEntities","onDismiss","containerId","question","getPollTypeString","CheckboxGroup","loadingOptions","RadioGroup","loadingOption","isQuiz","getReadableVotersCount","isText","inPreview","onMediaClick","onCancelMediaTransfer","webPage","getMessageWebPage","isSquarePhoto","handleMediaClick","siteName","displayUrl","isMediaInteractive","truncatedDescription","trimText","SafeLink","getMessageInvoice","amount","currency","isTest","photoUrl","formatCurrency","withSelectControl","WrappedComponent","ownProps","selectIsMessageSelected","handleMessageSelect","newProps","PhotoWithSelect","Photo","VideoWithSelect","Video","activeDownloadIds","selectActiveDownloadIds","uploadsById","hasCustomAppendix","albumLayout","cancelSendingMessage","mediaCount","handleCancelUpload","containerWidth","containerHeight","fileUpload","selectCanAutoLoadMedia","selectCanAutoPlayMedia","currentOnRelease","playingProgressRef","shouldSpinnerRender","setIsActivated","setProgress","svgCenter","ROUND_VIDEO_DIMENSIONS_PX","playerEl","playingProgressEl","stopPlaying","capturePlaying","onRelease","stopCurrentAudio","videoClassName","onEnded","recentReplierIds","recentRepliers","hasUnread","GROUP_MESSAGE_HOVER_ATTRIBUTE","APPENDIX_OWN","__html","APPENDIX_NOT_OWN","handleDocumentGroupMouseEnter","lastGroupElement","getLastElementInDocumentGroup","handleDocumentGroupMouseLeave","removeAttribute","nextElementSibling","withSenderName","withAvatar","viaBotId","replyToChatId","isRepliesChat","isChatWithRepliesBot","chatUsername","forceSenderName","isAnonymousOwnMessage","canShowSender","originSender","botSender","threadTopMessageId","isThreadTop","shouldHideReply","replyMessageSender","selectUploadProgress","isForwarding","highlight","singleEmoji","getMessageSingleEmoji","every","canReply","selectIsDownloading","actualThreadInfo","selectIsMessageProtected","isSingleEmoji","animatedEmoji","selectAnimatedEmoji","isGroupSelected","selectIsDocumentGroupSelected","isPinnedList","canAutoLoadMedia","canAutoPlayMedia","autoLoadFileMaxSizeMb","shouldLoopStickers","selectShouldLoopStickers","selectOutgoingStatus","observeIntersectionForBottom","observeIntersectionForMedia","observeIntersectionForAnimatedStickers","noComments","isFirstInGroup","isLastInGroup","isFirstInDocumentGroup","isLastInDocumentGroup","clickInlineButton","bottomMarkerRef","isLocal","hasReply","isReplyMessage","hasThread","getMessageCustomShape","asForwarded","isLinkedChannelPost","isInDocumentGroup","textParts","renderMessageText","adminTitle","metaSafeAuthorWidth","canShowActionButton","canForward","canFocus","isChannelPost","fromMessageId","avatarPeer","senderPeer","selectMessage","handleMouseDown","handleDoubleClick","handleContentDoubleClick","isSwiped","markSwiped","unmarkSwiped","startedAt","target","stopEvent","matches","useOuterHandlers","handleAvatarClick","handleSenderClick","handleViaBotClick","handleReplyClick","handleAudioPlay","handleAlbumMediaClick","handleMetaClick","handleReadMedia","handleVoteSend","handleGroupForward","handleForward","handleFocus","handleFocusForwarded","handleDocumentGroupSelectAll","openMediaViewer","openAudioPlayer","markMessagesRead","sendPollVote","focusMessageInComments","replyToTopMessageId","channelPostId","MediaViewerOrigin","albumMessageId","selectWithGroupedId","useInnerHandlers","containerClassName","contentClassName","hasComments","hasActionButton","classNames","isMedia","isMediaWithNoText","isViaBot","isRound","buildContentClassName","withCommentButton","withAppendix","calculatedWidth","noMediaCorners","extraPadding","isAvatarPeerUser","avatarUser","avatarChat","hiddenName","renderAvatar","shouldInlineMeta","textContentClass","senderColor","getUserColorKey","renderSenderName","AnimatedEmoji","forceLoadPreview","Audio","AudioOrigin","isSelectable","onPlay","onReadMedia","Document","renderContent","dangerouslySetInnerHTML","isBot","channel","viewSponsoredMessage","openChatByInvite","startBot","contentRef","shouldObserve","observe","useIntersectionObserver","rootRef","debounceMs","threshold","getUserFullName","chatInviteTitle","chatInviteHash","messageGroups","isViewportNewest","withUsers","anchorIdRef","memoUnreadDividerBeforeIdRef","memoFirstUnreadIdRef","isScrollingRef","isScrollPatchNeededRef","hasLinkedChat","isSchedule","onFabToggle","onNotchToggle","openHistoryCalendar","observeIntersectionForReading","throttleMs","margin","freezeForReading","unfreezeForReading","entries","mentionIds","entry","dataset","useMessageObservers","backwardsTriggerRef","forwardsTriggerRef","fabTriggerRef","loadMoreBackwards","loadMoreForwards","toggleScrollTools","offsetHeight","scrollHeight","scrollTop","scrollBottom","isAtBottom","MESSAGE_LIST_SENSITIVE_AREA","LOCAL_MESSAGE_ID_BASE","triggerEntry","IS_SCROLL_PATCH_NEEDED","observeIntersectionForFab","freezeForFab","unfreezeForFab","FAB_THRESHOLD","observeIntersectionForNotch","freezeForNotch","unfreezeForNotch","useScrollHooks","unreadDivider","messageCountToAnimate","messageGroup","flatten","appearanceIndex","dateGroup","dateGroupIndex","dateGroupsArray","senderGroup","senderGroupIndex","senderGroupsArray","compact","currentDocumentGroupId","messageIndex","isMessageAlbum","documentGroupId","nextDocumentGroupId","originalId","getMessageOriginalId","teactFastList","SCHEDULED_WHEN_ONLINE","formatHumanDate","dividend","getUserIdDividend","lastUnreadMessageId","loadGreetingStickers","handleStickerSelect","selectedSticker","StickerButton","isGroupChatJustCreated","renderScheduled","renderSavedMessages","renderGroup","runDebouncedForScroll","selectCurrentMessageIds","restrictionReason","focusingId","withLastMessageWhenPreloading","chatBot","botDescription","isChatLoaded","isChannelChat","isGroupChat","isChatGroup","threadFirstMessageId","selectFirstMessageId","linkedChatId","hasTools","canPost","withBottomShift","setScrollOffset","loadSponsoredMessages","scrollOffsetRef","selectScrollOffset","anchorTopRef","listItemElementsRef","memoFocusingIdRef","isScrollTopJustUpdatedRef","shouldAnimateAppearanceRef","setContainerHeight","onTickEnd","listedMessages","orderBy","loadMoreAround","isScrolled","updateStickyDates","markIsScrolled","runDebounced","useDebounce","container","currentStuck","stuckDateEl","allElements","querySelectorAll","containerTop","el","offsetTop","top","findStuckDate","useStickyDates","handleScroll","parentElement","observer","ResizeObserver","offsetParent","contentRect","disconnect","windowHeight","normalHeight","String","clientHeight","preservedItemElements","useLayoutEffectWithPrevDeps","prevMessageIds","prevIsViewportNewest","prevContainerHeight","hasLastMessageChanged","hasViewportShifted","wasMessageAdded","isAlreadyFocusing","shouldForceScroll","lastItemElement","bottomOffset","newScrollTop","isResized","isAnimatingScroll","patchChromiumScroll","resetScroll","useEffectWithPrevDeps","prevIsSelectModeActive","dispatchHeavyAnimationEvent","shouldRenderGreeting","onScroll","withExtraShift","focusNextReply","messageElements","lastMessageElement","MAX_QUICK_IMG_SIZE","FILE_EXT_REGEX","buildAttachment","filename","isQuick","mimeType","quick","SUPPORTED_IMAGE_CONTENT_TYPES","preloadImage","resizedUrl","fetchBlob","SUPPORTED_VIDEO_CONTENT_TYPES","videoWidth","videoHeight","preloadVideo","createPosterForVideo","resetInput","applyIosAutoCapitalizationFix","inputEl","POLYFILL_OPTIONS","encoderPath","reuseWorker","BLOB_PARAMS","opusRecorderPromise","OpusRecorder","mediaRecorder","init","default","start","analyzerCallback","startMediaRecorder","pausedAt","chunks","waveform","ondataavailable","typedArray","releaseAnalyzer","recorder","source","sourceNode","analyser","context","createAnalyser","fftSize","connect","dataLength","frequencyBinCount","dataArray","Uint8Array","isDestroyed","tick","getByteFrequencyData","requestAnimationFrame","subscribeToAnalyzer","reject","onstop","onerror","delayStop","CLIPBOARD_ACCEPTED_TYPES","getMessageTextAsHtml","tempEl","INLINE_BOT_QUERY_REGEXP","HAS_NEW_LINE","RE_COMMAND","DeleteMessageModal","openTimeout","isFirstTimeActivation","onActivate","buttonProps","AttachMenu","SymbolMenu","InlineBotTooltip","MentionTooltip","CustomSend","StickerTooltip","BotCommandTooltip","useMouseInside","isKeyboardSingleUse","forceOpen","markForceOpen","unmarkForceOpen","keyboardButtons","forwardMessageIds","forwardedMessagesCount","exitForwardMode","canAnimate","useAsyncRendering","clearEmbedded","handleMessageClick","faded","AttachmentModal","BotCommandMenu","PollModal","DropArea","RE_LINK","RegExp","RE_LINK_TEMPLATE","messageText","toggleMessageWebPage","link","linkEntity","ApiMessageEntityTypes","textMatch","renderingWebPage","webPageWithoutPhoto","messageStub","CalendarModal","SendAsMenu","MainButtonState","chatUser","selectChatUser","REPLIES_USER_ID","messageWithActualBotKeyboard","selectNewestMessageWithBotKeyboardButtons","shouldSuggestStickers","baseEmojiKeywords","BASE_EMOJI_KEYWORD_LANG","botKeyboardMessageId","keyboardMessage","sendAsUser","editingMessage","canScheduleUntilOnline","selectUserStatus","wasOnline","withScheduledButton","shouldSchedule","botKeyboardPlaceholder","keyboardPlaceholder","stickersForEmoji","groupChatMembers","topInlineBotIds","isInlineBotLoading","chatBotCommands","botCommands","dropAreaState","onDropHide","clearDraft","setStickerSearchQuery","setGifSearchQuery","closePollModal","addRecentEmoji","sendInlineBotResult","loadSendAs","appendixRef","html","setHtml","lastMessageSendTimeSeconds","prevDropAreaState","isCalendarOpen","openCalendar","closeCalendar","scheduledMessageArgs","setScheduledMessageArgs","sendMessageAction","useSendMessageAction","htmlRef","shouldAnimateSendAsButtonRef","prevChatId","prevSendAsIds","setAttachments","isBotKeyboardOpen","openBotKeyboard","closeBotKeyboard","isBotCommandMenuOpen","openBotCommandMenu","closeBotCommandMenu","isAttachMenuOpen","openAttachMenu","closeAttachMenu","isSymbolMenuOpen","openSymbolMenu","closeSymbolMenu","isSendAsMenuOpen","openSendAsMenu","closeSendAsMenu","isDeleteModalOpen","openDeleteModal","closeDeleteModal","isSymbolMenuLoaded","onSymbolMenuLoadingComplete","isHoverDisabled","disableHover","enableHover","startRecordingVoice","stopRecordingVoice","pauseRecordingVoice","activeVoiceRecording","currentRecordTime","recordButtonRef","mainButtonRef","startRecordTimeRef","setActiveVoiceRecording","setCurrentRecordTime","IS_SAFARI","IS_VOICE_RECORDING_SUPPORTED","voiceRecording","tickVolume","boxShadow","useVoiceRecording","delay","noFirst","savedCallback","setInterval","clearInterval","useInterval","SEND_MESSAGE_ACTION_INTERVAL","mainButtonState","Edit","Send","Record","canShowCustomSendMenu","isMentionTooltipOpen","closeMentionTooltip","insertMention","mentionFilteredUsers","useMentionTooltip","isInlineBotTooltipOpen","inlineBotId","isInlineBotTooltipGallery","inlineBotSwitchPm","inlineBotResults","closeTooltip","closeInlineBotTooltip","inlineBotHelp","loadMore","loadMoreForInlineBot","markIsOpen","unmarkIsOpen","innerText","getPlainText","queryInlineBot","resetInlineBot","canShowHelp","parseStartWithUsernameString","usernameLowered","prevQuery","prevUsername","useInlineBotTooltip","isBotCommandTooltipOpen","close","closeBotCommandTooltip","filteredBotCommands","botTooltipCommands","setFilteredBotCommands","getFilteredCommands","nextFilteredBotCommands","prepareForRegExp","substr","useBotCommandTooltip","isCustomSendMenuOpen","allowedAttachmentOptions","getAllowedAttachmentOptions","isChatAdmin","slowMode","getChatSlowModeOptions","isStickerTooltipOpen","closeStickerTooltip","isDisabled","cleanHtml","trim","clearStickersForEmoji","IS_EMOJI_SUPPORTED","parseEmojiOnlyString","hasStickers","useStickerTooltip","canSendStickers","isEmojiTooltipOpen","closeEmojiTooltip","filteredEmojis","insertEmoji","useEmojiTooltip","insertTextAndUpdateCursor","selection","getSelection","newHtml","rangeCount","selectionRange","getRangeAt","isSelectionInsideInput","range","deleteContents","fragment","createContextualFragment","lastInsertedNode","lastChild","insertNode","setStartAfter","setEndAfter","collapse","removeAllRanges","addRange","insertHtmlInSelection","dispatchEvent","Event","bubbles","focusEditableElement","removeSymbol","execCommand","tempInput","contentEditable","textLength","createRange","setStart","setEnd","removeChild","deleteLastCharacterOutsideSelection","resetComposer","shouldPreserveInput","stopRecordingVoiceRef","handleEditComplete","editedMessage","editMessage","hasMessageMedia","useEditing","saveDraft","updateDraft","draftChatId","draftThreadId","runDebouncedForSaveDraft","DRAFT_DEBOUNCE","prevThreadId","prevHtml","handleBlur","useDraft","handlePaste","clipboardData","input","activeElement","EDITABLE_INPUT_MODAL_ID","items","kind","file","getAsFile","pastedText","getData","substring","useClipboardPaste","handleFileSelect","files","handleAppendFiles","handleClearAttachment","handleSend","currentAttachments","record","maxLength","extraLength","textParams","nowSeconds","secondsSinceLastMessage","nextSendDateNotReached","nextSendDate","seconds","secondsRemaining","isSlowMode","handleActivateBotCommandMenu","handleActivateSymbolMenu","handleGifSelect","gif","handleInlineBotSelect","inlineResult","handleBotCommandSelect","handlePollSend","handleSilentSend","handleMessageSchedule","isWhenOnline","restArgs","getTime","handleMessageScheduleUntilOnline","handleCloseCalendar","handleSearchOpen","handleSymbolMenuOpen","handleSendAsMenuOpen","handleAllScheduledClick","mainButtonHandler","areVoiceMessagesNotAllowed","canAttachMedia","prevEditedMessage","renderedEditedMessage","scheduledDefaultDate","setSeconds","setMilliseconds","scheduledMaxDate","setFullYear","getFullYear","sendButtonAriaLabel","symbolMenuButtonClassName","onSend","Portal","DropAreaState","withQuick","onHide","onFileSelect","caption","onCaptionUpdate","onFileAppend","onClear","selectedSendAsId","onInsertUserName","filteredUsers","onSelectResult","withUsername","canAttachEmbedLinks","MessageInput","forcedPlaceholder","canAutoFocus","shouldSuppressFocus","shouldSuppressTextFormatter","onUpdate","onSuppressedFocus","formatVoiceRecordDuration","onStickerSelect","emojis","onEmojiSelect","onPollCreate","onGifSelect","onRemoveSymbol","onSearchOpen","onSilentSend","onScheduleSend","withTimePicker","maxAt","getDayStartAt","isFutureMode","secondButtonLabel","onSubmit","onSecondButtonClick","MobileSearch","MessageSelectToolbar","UnpinAllMessagesModal","PaymentModal","ReceiptModal","SeenByModal","CLOSE_ANIMATION_DURATION","isImage","isBlurred","isBackgroundBlurred","background","customBackground","backgroundColor","patternColor","themes","isMobileSearchActive","isReceiptModalOpen","isSeenByModalOpen","getCanPostInChat","isBotNotStarted","isPinnedMessageList","isScheduledMessageList","currentUserBannedRights","defaultBannedRights","hasPinnedOrAudioPlayer","loadUser","closePaymentModal","clearReceipt","setDropAreaState","isFabShown","setIsFabShown","isNotchShown","setIsNotchShown","isUnpinModalOpen","setIsUnpinModalOpen","renderingChatId","usePrevDuringAnimation","renderingThreadId","renderingMessageListType","renderingCanSubscribe","renderingCanStartBot","renderingCanRestartBot","renderingCanPost","renderingHasTools","renderingIsFabShown","renderingIsChannel","prevTransitionKey","handleOpenEnd","handleSlideStop","setIsReady","forceUpdate","useForceUpdate","willSwitchMessageList","ANIMATION_LEVEL_MIN","propertyName","useIsReady","visualViewport","documentElement","handleDragEnter","dataTransfer","shouldDrawQuick","handleHideDropArea","handleOpenUnpinModal","closeUnpinModal","handleUnpinAllMessages","handleTabletFocus","customBackgroundValue","settingValue","cacheApi","CUSTOM_BG_CACHE_NAME","Type","useCustomBackground","MASK_IMAGE_DISABLED","messagingDisabledClassName","messageSendingRestrictionReason","getMessageSendingRestrictionReason","composerHiddenScale","toolbarHiddenScale","composerTranslateX","toolbarTranslateX","unpinHiddenScale","toolbarForUnpinHiddenScale","sidePadding","messageListWidth","rightColumnWidth","getMessageListWidth","sendButtonWidth","composerWidth","toolbarWidth","calculateMiddleFooterTransforms","footerClassName","forceSyncOnIOs","createMessageHash","isMessagingDisabled","withMessageListBottomShift","onTransitionEnd","DARK_THEME_BG_COLOR","LIGHT_THEME_BG_COLOR","onDragEnter","onStop","onUnpin","HeaderContent","isProfile","isManagement","messageSearchQuery","stickerSearchQuery","selectCurrentStickerSearch","gifSearchQuery","selectCurrentGifSearch","canAddContact","getCanAddContact","canManage","isColumnOpen","isSearch","isStickerSearch","isGifSearch","isPollResults","isAddingChatMembers","profileState","managementScreen","shouldSkipAnimation","setLocalTextSearchQuery","searchTextMessagesLocal","toggleManagement","addContact","backButtonRef","handleMessageSearchQueryChange","handleStickerSearchQueryChange","handleGifSearchQueryChange","handleAddContact","setShouldSkipTransition","contentKey","ProfileState","Profile","SharedMedia","MemberList","Search","PollResults","StickerSearch","GifSearch","AddingMembers","ManagementScreens","ManageInitial","ManageChatPrivacyType","ManageDiscussion","ManageChannelSubscribers","ManageGroupPermissions","ManageChatAdministrators","ManageGroupRemovedUsers","ManageGroupUserPermissionsCreate","ManageGroupUserPermissions","ManageGroupRecentActions","ManageGroupAdminRights","ManageGroupNewAdminRights","ManageGroupMembers","ManageGroupAddAdmins","renderingContentKey","renderHeaderContent","autoFocusSearch","isBackButton","buttonClassName","useInfiniteScrollForLoadableItems","currentResultType","handleLoadMore","itemIds","getMore","useInfiniteScroll","MEMBERS_SLICE","useInfiniteScrollForSharedMedia","forSharedMediaType","messageIdsRef","getMessageContentIds","reverse","runThrottledForScroll","isScrollingProgrammatically","TABS","buildInfiniteScrollItemSelector","resultType","mediaSearchType","isGroup","hasMembersTab","areMembersHidden","canViewMembers","canAddMembers","getHasAdminRight","canDeleteMembers","hasCommonChatsTab","resolvedUserId","isChatProtected","commonChatIds","onProfileStateChange","setLocalMediaSearchType","loadMoreMembers","loadCommonChats","searchMediaMessagesLocal","loadProfilePhotos","setNewChatMembersDialogState","setActiveTab","deletingUserId","setDeletingUserId","tabType","noProfileInfo","searchMessages","memberIds","sortUserIds","sortChatIds","memberViewportIds","getMoreMembers","noProfileInfoForMembers","mediaViewportIds","getMoreMedia","noProfileInfoForMedia","documentViewportIds","getMoreDocuments","noProfileInfoForDocuments","linkViewportIds","getMoreLinks","noProfileInfoForLinks","audioViewportIds","getMoreAudio","noProfileInfoForAudio","voiceViewportIds","getMoreVoices","noProfileInfoForVoices","commonChatViewportIds","getMoreCommonChats","noProfileInfoForCommonChats","useProfileViewportIds","prevTabType","tabsEl","prevProfileState","tabListEl","determineProfileState","useProfileState","applyTransitionFix","releaseTransitionFix","transitionElSelector","setMinHeight","transitionEl","minHeight","overflowY","scrollBarWidth","clientWidth","marginRight","useTransitionFixes","cacheBuster","resetCacheBuster","setCacheBuster","useCacheBuster","handleTransitionStop","handleNewMemberDialogOpen","NewChatMembersProgress","handleSelectMedia","handlePlayAudio","handleMemberClick","handleMessageFocus","handleDeleteMembersModalClose","renderingDelay","isFirstTab","SLIDE_TRANSITION_DURATION","canRenderContents","renderSharedMedia","noSpinner","NothingFound","Media","withDate","smaller","onDateClick","WebLink","onMessageClick","getSenderName","ListItem","teactOrderKey","contextActions","memberId","handler","forceShowSelf","InfiniteScroll","itemSelector","sensitiveArea","PROFILE_SENSITIVE_AREA","preloadBackwards","noScrollRestoreOnTop","noFastList","onLoadMore","ProfileInfo","ChatExtra","renderProfileInfo","shouldRestoreHeight","onStart","big","FloatingActionButton","DeleteMemberModal","RightSearch","Management","localContactIds","isSearching","onNextStep","setUserSearchQuery","selectedMemberIds","setSelectedMemberIds","noPickerScrollRestore","member","handleFilterChange","displayedIds","filteredContactIds","filterUsersByName","canBeInvitedToGroup","handleNextStep","Picker","selectedIds","filterValue","filterPlaceholder","searchInputId","onSelectedIdsChange","onFilterChange","noScrollRestore","MAIN_SCREENS_COUNT","RightColumnContent","MANAGEMENT_SCREENS_COUNT","blurSearchInput","areActiveChatsLoaded","selectAreActiveChatsLoaded","selectRightColumnContentKey","currentProfileUserId","selectedId","isChatSelected","toggleChatInfo","closePollResults","addChatMembers","setProfileState","setManagementScreen","selectedChatMemberId","setSelectedChatMemberId","isPromotedByCurrentUser","setIsPromotedByCurrentUser","isScrolledDown","isOverlaying","shouldScrollUp","handleSelectChatMember","isPromoted","handleAppendingChatMembers","onChatMemberSelect","prevContentKey","MediaViewer","download","click","startedDownloads","downloadHash","getMessageContentFilename","Notifications","Dialogs","ForwardPicker","SafeLinkModal","HistoryCalendar","GroupCall","ActiveCallHeader","CallFallbackConfirm","notificationInterval","DEBUG_isLogged","updateIcon","asUnread","updatePageTitle","nextTitle","wasTimeFormatSetManually","isMediaViewerOpen","selectIsMediaViewerOpen","isForwardModalOpen","selectIsForwardModalOpen","hasNotifications","hasDialogs","isHistoryCalendarOpen","isServiceChatReady","isCallFallbackConfirmOpen","isFallbackConfirmOpen","loadNotificationSettings","loadNotificationExceptions","updateIsOnline","loadTopInlineBots","loadEmojiKeywords","loadCountryList","loadAddedStickers","ensureTimeFormat","openStickerSetShortName","checkVersionNotification","isSynced","LOCATION_HASH","processDeepLink","decodeURIComponent","middleColumnTransitionClassNames","rightColumnTransitionClassNames","prevIsLeftColumnShown","dispatchHeavyAnimationEnd","waitForTransitionEnd","prevIsRightColumnShown","initialUnread","INACTIVE_MARKER","newUnread","PAGE_TITLE","handleStickerSetModalClose","usePreventPinchZoomGesture","onDrop","onDragOver","initApi"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/927.04b93a71a7d051ccd448.js b/dist/927.151d396500bf8aa6cf1e.js similarity index 99% rename from dist/927.04b93a71a7d051ccd448.js rename to dist/927.151d396500bf8aa6cf1e.js index 2b5ba40a..3d0d1438 100644 --- a/dist/927.04b93a71a7d051ccd448.js +++ b/dist/927.151d396500bf8aa6cf1e.js @@ -1,2 +1,2 @@ -(()=>{var e,t,n={6927:(e,t,n)=>{"use strict";var s={};n.r(s),n.d(s,{Type:()=>Tt,clear:()=>Vt,fetch:()=>Bt,save:()=>xt});var a={};n.r(a),n.d(a,{addChatMembers:()=>Nn,addContact:()=>Ns,answerCallbackButton:()=>ri,blockContact:()=>La,checkChatUsername:()=>sa,checkPassword:()=>ga,checkUsername:()=>Da,clearDraft:()=>rn,clearPassword:()=>pa,createChannel:()=>dn,createGroupCall:()=>Sa,createGroupChat:()=>hn,deleteChannel:()=>fn,deleteChat:()=>gn,deleteChatFolder:()=>In,deleteChatMember:()=>Fn,deleteChatUser:()=>un,deleteContact:()=>Fs,deleteHistory:()=>as,deleteMessages:()=>ns,deleteScheduledMessages:()=>ss,destroy:()=>Gt,discardGroupCall:()=>ba,disconnect:()=>Kt,downloadMedia:()=>$t,editChatFolder:()=>Cn,editChatPhoto:()=>mn,editGroupCallParticipant:()=>wa,editGroupCallTitle:()=>Ca,editMessage:()=>Xn,exportGroupCallInvite:()=>Ia,faveSticker:()=>zs,fetchAnimatedEmojis:()=>js,fetchAuthorizations:()=>qa,fetchBlockedContacts:()=>Fa,fetchChat:()=>sn,fetchChatFolders:()=>bn,fetchChats:()=>en,fetchCommonChats:()=>Es,fetchContactList:()=>Bs,fetchContentSettings:()=>ni,fetchCountryList:()=>ii,fetchCurrentUser:()=>Xt,fetchEmojiKeywords:()=>ea,fetchFavoriteStickers:()=>Gs,fetchFeaturedStickers:()=>Ks,fetchFullChat:()=>tn,fetchFullUser:()=>Us,fetchGroupCallParticipants:()=>va,fetchGroupsForDiscussion:()=>Tn,fetchInlineBot:()=>di,fetchInlineBotResults:()=>li,fetchLangPack:()=>Ja,fetchLangStrings:()=>Qa,fetchLanguages:()=>$a,fetchMembers:()=>Dn,fetchMessage:()=>jn,fetchMessages:()=>Wn,fetchNearestCountry:()=>Ds,fetchNotificationExceptions:()=>Ka,fetchNotificationSettings:()=>za,fetchPinnedMessages:()=>ws,fetchPrivacySettings:()=>Xa,fetchProfilePhotos:()=>Ls,fetchRecentStickers:()=>Hs,fetchRecommendedChatFolders:()=>wn,fetchSavedGifs:()=>Js,fetchScheduledHistory:()=>_s,fetchSeenBy:()=>Cs,fetchSendAs:()=>Is,fetchSponsoredMessages:()=>Ps,fetchStickerSets:()=>qs,fetchStickers:()=>Ws,fetchStickersForEmoji:()=>Ys,fetchTopInlineBots:()=>ci,fetchTopUsers:()=>Ts,fetchUsers:()=>xs,fetchWallpapers:()=>Va,fetchWebPagePreview:()=>gs,findFirstMessageIdAfterDate:()=>ms,forwardMessages:()=>hs,getChatByUsername:()=>Pn,getGroupCall:()=>ya,getPasswordInfo:()=>la,getPaymentForm:()=>mi,getReceipt:()=>_i,importChatInvite:()=>qn,installStickerSet:()=>Qs,joinChannel:()=>ln,joinGroupCall:()=>Aa,joinGroupCallPresentation:()=>Ma,leaveChannel:()=>pn,leaveGroupCall:()=>Pa,leaveGroupCallPresentation:()=>Ra,loadPollOptionResults:()=>fs,markMessageListRead:()=>rs,markMessagesRead:()=>cs,migrateChat:()=>xn,openChatByInvite:()=>Vn,pinMessage:()=>es,provideAuthCode:()=>At,provideAuthPassword:()=>St,provideAuthPhoneNumber:()=>Pt,provideAuthRegistration:()=>Mt,provideRecoveryEmailCode:()=>ma,registerDevice:()=>Za,reportMessages:()=>is,requestChatUpdate:()=>an,requestThreadInfoUpdate:()=>ds,rescheduleMessage:()=>Zn,restartAuth:()=>kt,restartAuthWithQr:()=>Rt,saveDefaultSendAs:()=>vs,saveDraft:()=>on,searchChats:()=>nn,searchGifs:()=>Zs,searchMessagesGlobal:()=>us,searchMessagesLocal:()=>ls,searchStickers:()=>$s,sendInlineBotResult:()=>ui,sendMessage:()=>Jn,sendMessageAction:()=>os,sendPaymentForm:()=>hi,sendPollVote:()=>ps,sendScheduledMessages:()=>ys,setChatUsername:()=>aa,setDiscussionGroup:()=>Bn,setPrivacySettings:()=>ei,startBot:()=>gi,terminateAllAuthorizations:()=>Ga,terminateAuthorization:()=>Ha,toggleChatArchived:()=>yn,toggleChatPinned:()=>_n,toggleDialogUnread:()=>vn,toggleGroupCallStartSubscription:()=>ka,toggleIsProtected:()=>Hn,togglePreHistoryHidden:()=>An,toggleSignatures:()=>En,unblockContact:()=>Oa,uninstallStickerSet:()=>Xs,unpinAllMessages:()=>ts,unregisterDevice:()=>Ya,updateChatAbout:()=>Un,updateChatAdmin:()=>kn,updateChatDefaultBannedRights:()=>Sn,updateChatMemberBannedRights:()=>Mn,updateChatMutedState:()=>cn,updateChatTitle:()=>Rn,updateContact:()=>Vs,updateContactSignUpNotification:()=>Wa,updateContentSettings:()=>si,updateIsOnline:()=>ti,updateNotificationSettings:()=>ja,updatePassword:()=>fa,updatePrivateLink:()=>ia,updateProfile:()=>Ea,updateProfilePhoto:()=>Ba,updateRecoveryEmail:()=>ha,updateUsername:()=>Ta,uploadProfilePhoto:()=>xa,uploadWallpaper:()=>Na,validateRequestedInfo:()=>fi,viewSponsoredMessage:()=>As});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 A(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 S(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=S(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=A(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;l{e instanceof g.Api.User&&e.photo?H(e):(e instanceof g.Api.Chat||e instanceof g.Api.Channel)&&e.photo&&function(e,t=!1){const n=V(e.id,e instanceof g.Api.Chat?"chat":"channel");t&&v.chats[n]||(v.chats[n]=e)}(e)}))}function K(e){return String.fromCharCode(...e)}function z(e){return F.from(e,"binary")}function W(e){return"number"==typeof e?function(e){return e>0?"user":e<=-1e9?"channel":"chat"}(e):e.startsWith("-")?e.length>=11?"channel":"chat":"user"}function j(e){const t=W(e);return"user"===t?new g.Api.PeerUser({userId:le(e,"user")}):"channel"===t?new g.Api.PeerChannel({channelId:le(e,"channel")}):new g.Api.PeerChat({chatId:le(e,"chat")})}function $(e,t){const n=W(e);return"user"===n?new g.Api.InputPeerUser({userId:le(e,"user"),accessHash:U()(t)}):"channel"===n?new g.Api.InputPeerChannel({channelId:le(e,"channel"),accessHash:U()(t)}):new g.Api.InputPeerChat({chatId:le(e,"chat")})}function J(e){const t=W(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 $(e,String(n))}function Q(e,t){const n=W(e);return"user"===n?new g.Api.InputUser({userId:le(e,"user"),accessHash:U()(t)}):"channel"===n?new g.Api.InputChannel({channelId:le(e,"channel"),accessHash:U()(t)}):le(e,"chat")}function X(e,t){return new g.Api.InputStickerSetID({id:U()(e),accessHash:U()(t)})}function Z(e){const t=v.documents[e.id];if(t)return new g.Api.InputDocument(f(t,["id","accessHash","fileReference"]))}function Y(e){const t=Z(e);if(t)return new g.Api.InputMediaDocument({id:t})}function ee(){return(0,E.readBigIntFromBuffer)((0,E.generateRandomBytes)(8),!0,!0)}function te(e,t,n){return new g.Api.Message({id:e,peerId:j(t),fromId:j(t),media:n.media})}function ne(e){const{type:t,offset:n,length:s,url:a,userId:i}=e,o=i?v.users[i]:void 0;switch(t){case D.Bold:return new g.Api.MessageEntityBold({offset:n,length:s});case D.Italic:return new g.Api.MessageEntityItalic({offset:n,length:s});case D.Underline:return new g.Api.MessageEntityUnderline({offset:n,length:s});case D.Strike:return new g.Api.MessageEntityStrike({offset:n,length:s});case D.Code:return new g.Api.MessageEntityCode({offset:n,length:s});case D.Pre:return new g.Api.MessageEntityPre({offset:n,length:s,language:""});case D.Blockquote:return new g.Api.MessageEntityBlockquote({offset:n,length:s});case D.TextUrl:return new g.Api.MessageEntityTextUrl({offset:n,length:s,url:a});case D.Url:return new g.Api.MessageEntityUrl({offset:n,length:s});case D.Hashtag:return new g.Api.MessageEntityHashtag({offset:n,length:s});case D.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 se(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 ae({phone:e,firstName:t,lastName:n}){return new g.Api.InputPhoneContact({clientId:U()(1),phone:e,firstName:t,lastName:n})}function ie(e,t=0){return new g.Api.ChatBannedRights({...e,untilDate:t})}function oe(e){return new g.Api.ChatAdminRights(e)}function re(e){const{shippingAddress:t}=e;return new g.Api.PaymentRequestedInfo({...e,shippingAddress:t?new g.Api.PostAddress(t):void 0})}function ce(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 de(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 le(e,t){return"number"==typeof e?U()(Math.abs(e)):"user"===t?U()(e):U()(e.slice(1))}function ue(e){return new g.Api.InputGroupCall({id:U()(e.id),accessHash:U()(e.accessHash)})}const ge="temp";let pe,fe=1e9;function he(e){const{fromId:t,message:n,entities:s,startParam:a,channelPost:i,chatInvite:o,chatInviteHash:r,randomId:c}=e,d=t?N(t):void 0,l=o?o instanceof g.Api.ChatInvite?o.title:o.chat instanceof g.Api.ChatEmpty?void 0:o.chat.title:void 0;return{randomId:K(c),isBot:!!t&&B(t),text:ye(n,s),expiresAt:Math.round(Date.now()/1e3)+3e5,...d&&{chatId:d},...r&&{chatInviteHash:r},...o&&{chatInviteTitle:l},...a&&{startParam:a},...i&&{channelPostId:i}}}function me(e){const t=L(e);if(t&&(e instanceof g.Api.Message||e instanceof g.Api.MessageService))return _e(t,e)}function _e(e,t){const n=t.fromId?N(t.fromId):void 0,s=t.peerId?N(t.peerId):void 0,a=!n&&e===pe,i=t.out&&!t.post||a&&!t.fwdFrom;let o={};t.media&&(o={...we(t.media)}),!t.message||o.sticker||o.poll||o.contact||(o={...o,text:ye(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,c;const d=[];let l,u="other";const p="users"in e?e.users&&e.users.map((e=>V(e,"user"))):"userId"in e&&[V(e.userId,"user")]||[];let f;if(e instanceof g.Api.MessageActionChatCreate)c="Notification.CreatedChatWithTitle",d.push("%action_origin%",e.title),u="chatCreate";else if(e instanceof g.Api.MessageActionChatEditTitle)s?(c="Channel.MessageTitleUpdated",d.push(e.title)):(c="Notification.ChangedGroupName",d.push("%action_origin%",e.title));else if(e instanceof g.Api.MessageActionChatEditPhoto)s?c="Channel.MessagePhotoUpdated":(c="Notification.ChangedGroupPhoto",d.push("%action_origin%"));else if(e instanceof g.Api.MessageActionChatDeletePhoto)c=s?"Channel.MessagePhotoRemoved":"Group.MessagePhotoRemoved";else if(e instanceof g.Api.MessageActionChatAddUser)!t||p.includes(t)?(c="Notification.JoinedChat",d.push("%target_user%")):(c="Notification.Invited",d.push("%action_origin%","%target_user%"));else if(e instanceof g.Api.MessageActionChatDeleteUser)!t||p.includes(t)?(c="Notification.LeftChat",d.push("%target_user%")):(c="Notification.Kicked",d.push("%action_origin%","%target_user%"));else if(e instanceof g.Api.MessageActionChatJoinedByLink)c="Notification.JoinedGroupByLink",d.push("%action_origin%");else if(e instanceof g.Api.MessageActionChannelCreate)c="Notification.CreatedChannel";else if(e instanceof g.Api.MessageActionChatMigrateTo)f=N(e),c="Migrated to %target_chat%",d.push("%target_chat%");else if(e instanceof g.Api.MessageActionChannelMigrateFrom)f=N(e),c="Migrated from %target_chat%",d.push("%target_chat%");else if(e instanceof g.Api.MessageActionPinMessage)c="Chat.Service.Group.UpdatedPinnedMessage1",d.push("%action_origin%","%message%");else if(e instanceof g.Api.MessageActionHistoryClear)c="HistoryCleared",u="historyClear";else if(e instanceof g.Api.MessageActionPhoneCall){const t=Boolean(e.duration);if(c=[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);d.push(`${t} min${t>1?"s":""}`)}}else if(e instanceof g.Api.MessageActionInviteToGroupCall)c="Notification.VoiceChatInvitation",i={id:e.call.id.toString(),accessHash:e.call.accessHash.toString()},d.push("%action_origin%","%target_user%");else if(e instanceof g.Api.MessageActionContactSignUp)c="Notification.Joined",d.push("%action_origin%"),u="contactSignUp";else if(e instanceof g.Api.MessageActionPaymentSent)o=Number(e.totalAmount),r=e.currency,c="PaymentSuccessfullyPaid",n&&p.push(n),d.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);c="Notification.VoiceChatEnded",d.push(`${t} min${t>1?"s":""}`)}else c="Notification.VoiceChatStartedChannel",i={id:e.call.id.toString(),accessHash:e.call.accessHash.toString()};else e instanceof g.Api.MessageActionBotAllowed?(c="Chat.Service.BotPermissionAllowed",d.push(e.domain)):e instanceof g.Api.MessageActionCustomAction?c=e.message:e instanceof g.Api.MessageActionChatJoinedByRequest?(c="ChatService.UserJoinedGroupByRequest",d.push("%action_origin%")):c="ChatList.UnsupportedMessage";return"photo"in e&&e.photo instanceof g.Api.Photo&&(q(e.photo),l=C(e.photo)),{text:c,type:u,targetUserIds:p,targetChatId:f,photo:l,amount:o,currency:r,translationValues:d,call:i}}(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=K(e.data)):e instanceof g.Api.KeyboardButtonRequestPoll?n="requestPoll":e instanceof g.Api.KeyboardButtonRequestPhone?n="requestSelfContact":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&&N(e.savedFromPeer),s=e.fromId&&N(e.fromId);return{date:e.date,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&&pe||e,views:t.views,isFromScheduled:t.fromScheduled,...c&&{replyToMessageId:c},...l&&{replyToChatId:N(l)},...d&&{replyToTopMessageId:d},..._&&{forwardInfo:_},...u&&{isEdited:u,editDate:t.editDate},...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:V(t.viaBotId,"user")},...(null==y?void 0:y.comments)&&{threadInfo:Re(y,t.id,e)},...w&&{adminTitle:w},...t.noforwards&&{isProtected:!0}}}function ye(e,t){return null!=t&&t.some((e=>e instanceof g.Api.MessageEntitySpoiler))?{text:"The message is not supported on this version of Telegram."}:{text:e,...t&&{entities:t.map(ke)}}}function be(e){if(e instanceof g.Api.DraftMessageEmpty)return;const{message:t,entities:n,replyToMsgId:s,date:a}=e;return{formattedText:t?ye(t,n):void 0,replyingToId:s,date:a}}function we(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 A(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 Ce(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{id:String(e.document.id),fileName:Se(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{id:String(e.document.id),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 Ie(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:V(a,"user")}}(e);if(r)return{contact:r};const c=function(e){if(e instanceof g.Api.MessageMediaPoll)return ve(e.poll,e.results)}(e);if(c)return{poll:c};const d=Ae(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 Ce(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:Se(e,"video"),width:d,height:l,supportsStreaming:u,isRound:p,isGif:Boolean(r),thumbnail:w(s),size:a}}function Ie(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:Se(e),thumbnail:d,mediaType:l,mediaSize:u}}function ve(e,t){const{id:n,answers:s}=e,a=s.map((e=>({text:e.text,option:K(e.option)})));return{id:String(n),summary:{isPublic:e.publicVoters,...f(e,["closed","multipleChoice","quiz","question","closePeriod","closeDate"]),answers:a},results:Pe(t)}}function Pe(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:K(e),votersCount:s})));return{totalVoters:n,recentVoterIds:null==s?void 0:s.map((e=>V(e,"user"))),results:o,solution:a,...i&&{solutionEntities:i.map(ke)}}}function Ae(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=Ce(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?Ie(s):void 0,video:a}}function Se(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 Me(e,t){return{poll:{id:String(t),summary:f(e.summary,["question","answers"]),results:{}}}}function ke(e){const{className:t,offset:n,length:s}=e;return{type:t,offset:n,length:s,...e instanceof g.Api.MessageEntityMentionName&&{userId:V(e.userId,"user")},..."url"in e&&{url:e.url}}}function Re(e,t,n){const{channelId:s,replies:a,maxId:i,readMaxId:o,recentRepliers:r}=e;if(!s)return;const c=V(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(N)}}:void 0}const Ue=e=>Math.floor(Date.now()/1e3)+e;function Ee(e,t=!1){const n=Boolean("min"in e&&e.min),s="accessHash"in e&&String(e.accessHash),a="photo"in e&&e.photo&&qe(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},...(e instanceof g.Api.Chat||e instanceof g.Api.Channel)&&{isProtected:Boolean("noforwards"in e&&e.noforwards)},...t&&{isSupport:!0},...Te(e),..."creator"in e&&{isCreator:e.creator},...Be(e),...xe(e)}}function De(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&&Ue(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 xe(e){return e instanceof g.Api.Chat&&e.migratedTo&&!(e.migratedTo instanceof g.Api.InputChannelEmpty)?{migratedTo:{chatId:N(e.migratedTo),...e.migratedTo instanceof g.Api.InputChannel&&{accessHash:String(e.migratedTo.accessHash)}}}:{}}function Ve(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:V(e.id,e instanceof g.Api.User?"user":"chat"),type:Ne(e),title:e instanceof g.Api.User?Oe(e):e.title,...Ee(e,t)}}function Ne(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 Fe(e){return B(e)?`user${e.userId}`:x(e)?`chat${e.chatId}`:`chat${e.channelId}`}function Le(e,t){return B(e)?Oe(t):t.title}function Oe(e){return e.firstName?`${e.firstName}${e.lastName?` ${e.lastName}`:""}`:e.lastName||void 0}function qe(e){if("photoId"in e)return String(e.photoId)}function He(e){return{userId:e instanceof g.Api.ChannelParticipantBanned||e instanceof g.Api.ChannelParticipantLeft?N(e.peer):V(e.userId,"user"),inviterId:"inviterId"in e?V(e.inviterId,"user"):void 0,joinedDate:"date"in e?e.date:void 0,kickedByUserId:"kickedBy"in e?V(e.kickedBy,"user"):void 0,promotedByUserId:"promotedBy"in e?V(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 Ge(e){return e instanceof g.Api.ChatParticipants||e instanceof g.Api.channels.ChannelParticipants?e.participants.map(He).filter(Boolean):void 0}function Ke(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:N(e.fromId)},timestamp:Date.now()+1e3*t}}}function ze(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(N).filter(Boolean),includedChatIds:e.includePeers.map(N).filter(Boolean),excludedChatIds:e.excludePeers.map(N).filter(Boolean)};var t,n}function We({filter:e,description:t}){return{...ze(e),description:t}}function je(e){return e.reduce(((e,t)=>{const n=V(t.userId,"user");return e.concat(t.commands.map((e=>({botId:n,..._(e)}))))}),[])}function $e(e){const{fullUser:{about:t,commonChatsCount:n,pinnedMsgId:s,botInfo:a,blocked:i},users:o}=e,r=Je(o[0]);return{...r,fullInfo:{bio:t,commonChatsCount:n,pinnedMessageId:s,isBlocked:Boolean(i),...a&&{botDescription:a.description},...a&&a.commands.length&&{botCommands:Xe(r.id,a)}}}}function Je(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:V(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||"",noStatus:!e.status,...e.accessHash&&{accessHash:String(e.accessHash)},...a&&{avatarHash:a},...e.bot&&e.botInlinePlaceholder&&{botPlaceholder:e.botInlinePlaceholder}}}function Qe(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 Xe(e,t){return t.commands.map((({command:t,description:n})=>({botId:e,command:t,description:n})))}function Ze(e){const t={},n=[];return e.forEach((e=>{const s=Je(e);s&&(n.push(s),"status"in e&&(t[s.id]=Qe(e.status)))})),{users:n,userStatusesById:t}}function Ye(e){if(e instanceof g.Api.WallPaperNoFile)return;const{slug:t}=e,n=Ie(e.document);return n?{slug:t,document:n}:void 0}function et(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 tt(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=>V(e,"user"))):e instanceof g.Api.PrivacyValueDisallowUsers?a=e.users.map((e=>V(e,"user"))):e instanceof g.Api.PrivacyValueAllowChatParticipants?s=e.chats.map((e=>V(e,"chat"))):e instanceof g.Api.PrivacyValueDisallowChatParticipants&&(i=e.chats.map((e=>V(e,"chat"))))})),t||(t="nobody"),{visibility:t,allowUserIds:n||[],allowChatIds:s||[],blockUserIds:a||[],blockChatIds:i||[]}}function nt(e,t,n){const{silent:s,muteUntil:a,showPreviews:i,sound:o}=e;return{chatId:N(t),isMuted:s||"number"==typeof a&&Ue(n)e instanceof g.Api.User)).map(Je).forEach((e=>{e&&ct({"@type":"updateUser",id:e.id,user:e})})),e.filter((e=>e instanceof g.Api.Chat||e instanceof g.Api.Channel)).map((e=>Ve(e))).forEach((e=>{e&&ct({"@type":"updateChat",id:e.id,chat:e})}))}function pt(e,t){if(e instanceof g.connection.UpdateServerTimeOffset)lt=e.timeOffset;else if(e instanceof g.connection.UpdateConnectionState){let t;switch(e.state){case g.connection.UpdateConnectionState.disconnected:t="connectionStateConnecting";break;case g.connection.UpdateConnectionState.broken:t="connectionStateBroken";break;case g.connection.UpdateConnectionState.connected:default:t="connectionStateReady"}ct({"@type":"updateConnectionState",connectionState:t})}else if(e instanceof g.Api.UpdateNewMessage||e instanceof g.Api.UpdateNewScheduledMessage||e instanceof g.Api.UpdateNewChannelMessage||e instanceof g.Api.UpdateShortChatMessage||e instanceof g.Api.UpdateShortMessage){let t,s;if(e instanceof g.Api.UpdateShortChatMessage)t=_e(V((a=e).chatId,"chat"),{...a,fromId:j(V(a.fromId,"user"))});else if(e instanceof g.Api.UpdateShortMessage)t=function(e){return _e(V(e.userId,"user"),{...e,fromId:j(e.out?pe:V(e.userId,"user"))})}(e);else{var n;if(e.message instanceof g.Api.MessageEmpty)return;e.message instanceof g.Api.Message&&se(e.message)&&O(e.message),t=me(e.message),s="replyMarkup"in e.message&&(null===(n=e.message)||void 0===n?void 0:n.replyMarkup)instanceof g.Api.ReplyKeyboardForceReply&&(!e.message.replyMarkup.selective||t.isMentioned)}const i=e._entities;if(i&&(G(i),gt(i)),e instanceof g.Api.UpdateNewScheduledMessage?ct({"@type":dt.has(t.id)?"updateScheduledMessage":"newScheduledMessage",id:t.id,chatId:t.chatId,message:t}):ct({"@type":dt.has(t.id)?"updateMessage":"newMessage",id:t.id,chatId:t.chatId,message:t,shouldForceReply:s}),e.message instanceof g.Api.MessageService){const{action:n}=e.message;if(n instanceof g.Api.MessageActionChatEditTitle)ct({"@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=qe(s),i=L(e.message);v.chats[i]&&(v.chats[i].photo=s),q(n.photo),a&&ct({"@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=L(e.message);v.chats[n]&&(v.chats[n].photo=new g.Api.ChatPhotoEmpty),ct({"@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))&&(ct({"@type":"updateChat",id:t.chatId,chat:{isRestricted:!0}}),ct({"@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)))&&ct({"@type":"updateChatJoin",id:t.chatId}):n instanceof g.Api.MessageActionGroupCall&&!n.duration&&n.call&&ct({"@type":"updateGroupCallChatId",chatId:t.chatId,call:{id:n.call.id.toString(),accessHash:n.call.accessHash.toString()}})}}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&&se(e.message)&&O(e.message);const t=me(e.message);ct({"@type":"updateMessage",id:t.id,chatId:t.chatId,message:t})}else if(e instanceof g.Api.UpdateDeleteMessages)ct({"@type":"deleteMessages",ids:e.messages});else if(e instanceof g.Api.UpdateDeleteScheduledMessages)ct({"@type":"deleteScheduledMessages",ids:e.messages,chatId:N(e.peer)});else if(e instanceof g.Api.UpdateDeleteChannelMessages){const t=V(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&&ct({"@type":"deleteMessages",ids:s,chatId:t}),i.length&&ct({"@type":"deleteProfilePhotos",ids:i,chatId:t}),a.length&&setTimeout((()=>{ct({"@type":"deleteMessages",ids:a,chatId:t})}),1e3)}else if(e instanceof g.Api.UpdateServiceNotification)if(e.popup)ct({"@type":"error",error:{message:e.message}});else{const t=function(e,t){const n=fe++;let s={};return e.media&&(s={...we(e.media)}),!e.message||s.sticker||s.poll||s.contact||(s={...s,text:ye(e.message,e.entities)}),{id:n,chatId:d,date:e.inboxDate||t,content:s,isOutgoing:!1}}(e,Date.now()/1e3+lt);se(e)&&O(te(t.id,t.chatId,e)),ct({"@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:ye(s.content.text.text,e.entities)}),e.media&&(a={...a,...we(e.media)});const t=te(e.id,s.chatId,e);se(t)&&O(t)}dt.add(e.id);const i="date"in e&&1e3*e.datee instanceof g.Api.DialogPeer)).map((e=>N(e.peer))):[];ct({"@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;ct({"@type":"updateChatListType",id:N(n),folderId:t})}));else if(e instanceof g.Api.UpdateDialogFilter){const{id:t,filter:n}=e,s=n?ze(n):void 0;ct({"@type":"updateChatFolder",id:t,folder:s})}else if(e instanceof g.Api.UpdateDialogFilterOrder)ct({"@type":"updateChatFoldersOrder",orderedIds:e.order});else if(e instanceof g.Api.UpdateChatParticipants){const t=Ge(e.participants);ct({"@type":"updateChatMembers",id:V(e.participants.chatId,"chat"),replacedMembers:t})}else if(e instanceof g.Api.UpdateChatParticipantAdd){const t=He(f(e,["userId","inviterId","date"]));ct({"@type":"updateChatMembers",id:V(e.chatId,"chat"),addedMember:t})}else if(e instanceof g.Api.UpdateChatParticipantDelete)ct({"@type":"updateChatMembers",id:V(e.chatId,"chat"),deletedMemberId:V(e.userId,"user")});else if(e instanceof g.Api.UpdatePinnedMessages||e instanceof g.Api.UpdatePinnedChannelMessages){const t=e instanceof g.Api.UpdatePinnedMessages?N(e.peer):V(e.channelId,"channel");ct({"@type":"updatePinnedIds",chatId:t,messageIds:e.messages,isPinned:e.pinned})}else if(e instanceof g.Api.UpdateNotifySettings&&e.peer instanceof g.Api.NotifyPeer)ct({"@type":"updateNotifyExceptions",...nt(e.notifySettings,e.peer.peer,lt)});else if(e instanceof g.Api.UpdateUserTyping||e instanceof g.Api.UpdateChatUserTyping){const t=e instanceof g.Api.UpdateUserTyping?V(e.userId,"user"):V(e.chatId,"chat");ct({"@type":"updateChatTypingStatus",id:t,typingStatus:Ke(e,lt)})}else if(e instanceof g.Api.UpdateChannelUserTyping){const t=V(e.channelId,"channel");ct({"@type":"updateChatTypingStatus",id:t,typingStatus:Ke(e,lt)})}else if(e instanceof g.Api.UpdateChannel){const{_entities:n}=e;if(!n)return;const s=n.find((e=>e instanceof g.Api.Channel||e instanceof g.Api.ChannelForbidden));if(s instanceof g.Api.Channel){if(ut)return void(ut=!1);t instanceof g.Api.messages.ToggleNoForwards&&(ut=!0,setTimeout((()=>{ut=!1}),2e3));const n=Ve(s);n&&(ct({"@type":"updateChat",id:n.id,chat:n}),ct({"@type":n.isNotJoined?"updateChatLeave":"updateChatJoin",id:V(e.channelId,"channel")}))}else if(s instanceof g.Api.ChannelForbidden){const t=V(e.channelId,"channel");ct({"@type":"updateChat",id:t,chat:{isRestricted:!0}}),ct({"@type":"updateChatLeave",id:t})}else 0===n.length&&ct({"@type":"resetMessages",id:V(e.channelId,"channel")})}else if(e instanceof g.Api.UpdateDialogUnreadMark&&e.peer instanceof g.Api.DialogPeer)ct({"@type":"updateChat",id:N(e.peer.peer),chat:{hasUnreadMark:e.unread}});else if(e instanceof g.Api.UpdateChatDefaultBannedRights)ct({"@type":"updateChat",id:N(e.peer),chat:{defaultBannedRights:_(e.defaultBannedRights)}});else if(e instanceof g.Api.UpdateUserStatus)ct({"@type":"updateUserStatus",userId:V(e.userId,"user"),status:Qe(e.status)});else if(e instanceof g.Api.UpdateUserName){const t=V(e.userId,"user"),n=v.users[t],s=null!=n&&n.mutualContact&&!n.self?f(e,["username"]):f(e,["firstName","lastName","username"]);ct({"@type":"updateUser",id:t,user:s})}else if(e instanceof g.Api.UpdateUserPhoto){const{userId:t,photo:n}=e,s=V(t,"user"),a=qe(n);v.users[s]&&(v.users[s].photo=n),ct({"@type":"updateUser",id:s,user:{avatarHash:a}})}else if(e instanceof g.Api.UpdateUserPhone){const{userId:t,phone:n}=e;ct({"@type":"updateUser",id:V(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=>{ct({"@type":"deleteContact",id:V(e.id,"user")})})),t.filter((e=>e instanceof g.Api.User&&e.contact)).map(Je).forEach((e=>{e&&ct({"@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;ct({"@type":"updateNotifySettings",peerType:i,isSilent:Boolean(n||"number"==typeof s&&Date.now()+1e3*lt<1e3*s),shouldShowPreviews:Boolean(t)})}else if(e instanceof g.Api.UpdatePeerBlocked)ct({"@type":"updatePeerBlocked",id:N(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&&ct({"@type":"updatePrivacy",key:t,rules:tt(e.rules)})}else if(e instanceof g.Api.UpdateDraftMessage)ct({"@type":"draftMessage",chatId:N(e.peer),...be(e.draft)});else if(e instanceof g.Api.UpdateContactsReset)ct({"@type":"updateResetContactList"});else if(e instanceof g.Api.UpdateFavedStickers)ct({"@type":"updateFavoriteStickers"});else if(e instanceof g.Api.UpdateGroupCall)ct({"@type":"updateGroupCall",call:rt(e.call)});else if(e instanceof g.Api.UpdateGroupCallConnection)ct({"@type":"updateGroupCallConnection",data:JSON.parse(e.params.data),presentation:Boolean(e.presentation)});else if(e instanceof g.Api.UpdateGroupCallParticipants){const t=e._entities;t&&(G(t),gt(t)),ct({"@type":"updateGroupCallParticipants",groupCallId:(s=e.call,s.id.toString()),participants:e.participants.map(at)})}var s,a}const ft={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."},ht={};let mt;function _t(){return mt(vt("authorizationStateWaitPhoneNumber")),new Promise(((e,t)=>{ht.resolve=e,ht.reject=t}))}function yt(e=!1){return mt({...vt("authorizationStateWaitCode"),isCodeViaApp:e}),new Promise(((e,t)=>{ht.resolve=e,ht.reject=t}))}function bt(e){return mt({...vt("authorizationStateWaitPassword"),hint:e}),new Promise((e=>{ht.resolve=e}))}function wt(){return mt(vt("authorizationStateWaitRegistration")),new Promise((e=>{ht.resolve=e}))}function Ct(e){return mt({...vt("authorizationStateWaitQrCode"),qrCode:{token:btoa(String.fromCharCode(...e.token)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),expires:e.expires}}),new Promise(((e,t)=>{ht.reject=t}))}function It(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=ft[e.message];t||(t="Unexpected Error"),mt({"@type":"updateAuthorizationError",message:t})}function vt(e){return{"@type":"updateAuthorizationState",authorizationState:e}}function Pt(e){ht.resolve&&ht.resolve(e)}function At(e){ht.resolve&&ht.resolve(e)}function St(e){ht.resolve&&ht.resolve(e)}function Mt(e){const{firstName:t,lastName:n}=e;ht.resolve&&ht.resolve([t,n])}function kt(){ht.reject&&ht.reject(new Error("RESTART_AUTH"))}function Rt(){ht.reject&&ht.reject(new Error("RESTART_AUTH_WITH_QR"))}var Ut=n(9832),Et=n(5802);const Dt=self.caches;let Tt;async function Bt(e,t,n,s=!1){if(Dt)try{const a=new Request(t.replace(/:/g,"_")),i=await Dt.open(e),o=await i.match(a);if(!o)return;const r=o.headers.get("Content-Type");switch(n){case Tt.Text:return await o.text();case Tt.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 Tt.Json:return await o.json();default:return}}catch(e){return void console.warn(e)}}async function xt(e,t,n){if(Dt)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 Dt.open(e);return await o.put(a,i)}catch(e){return void console.warn(e)}}async function Vt(e){try{if(!Dt)return;return await Dt.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"}(Tt||(Tt={}));const Nt=new Set(["msg","sticker","gif","wallpaper","photo","webDocument"]);function Ft(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}Ut.Logger.setLevel("warn");const Lt={build:e=>e};let Ot,qt,Ht=!1;async function Gt(){await jt(new g.Api.auth.LogOut),await qt.destroy()}async function Kt(){await qt.disconnect()}function zt(e){Ot({"@type":"updateSession",sessionData:e})}function Wt(e){e instanceof g.connection.UpdateConnectionState?Ht=e.state===g.connection.UpdateConnectionState.connected:e instanceof g.Api.UpdatesTooLong?async function(){try{await jt(new g.Api.users.GetFullUser({id:new g.Api.InputUserSelf}),void 0,!0)}catch(e){"AUTH_KEY_UNREGISTERED"===e.message&&Ot({"@type":"updateConnectionState",connectionState:"connectionStateBroken"})}}():e instanceof g.connection.UpdateServerTimeOffset&&Ot({"@type":"updateServerTimeOffset",serverTimeOffset:e.timeOffset})}async function jt(e,t=!1,n=!1){if(Ht)try{const n=await qt.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=>{pt(t,e)}))):n instanceof g.Api.UpdatesTooLong||pt(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;Ot({"@type":"error",error:{message:s,isSlowMode:n,hasErrorKey:!0}})}(t,e)}}function $t(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./]+)(?::\d+)?(\?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]?W(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(Nt.has(d)){o===T.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===T.Lottie?"application/json":Ft(e),data:e}}{const e=await t.downloadProfilePhoto(p,"profile"===c[1]);return{mimeType:Ft(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 T.BlobUrl:return new Blob([e],{type:n});case T.Lottie:{const t=(0,Et.inflate)(e,{to:"string"});return JSON.parse(t)}case T.Progressive:return e.buffer}}(d,t,l);if(!p)return;const f=t!==T.Progressive&&(t!==T.BlobUrl||p.size<=524288);return s&&f&&xt(e.startsWith("avatar")?"tt-media-avatars":"tt-media",e,p),{prepared:t===T.Progressive?"":(h=p,h instanceof Blob?URL.createObjectURL(h):h),arrayBuffer:t===T.Progressive?p:void 0,mimeType:l,fullSize:u};var h}(e,qt,Ht,t)}function Jt(e,t){return qt.uploadFile({file:e,onProgress:t,workers:16})}function Qt(e){return qt.updateTwoFaSettings(e)}async function Xt(){const e=await jt(new g.Api.users.GetFullUser({id:new g.Api.InputUserSelf}));if(!(e&&e.users[0]instanceof g.Api.User))return;const t=e.users[0];v.users[V(t.id,"user")]=t;const n=$e(e);var s;s=n.id,pe=s,function(e){mt({"@type":"updateCurrentUser",currentUser:e})}(n)}const Zt=2**31-1;let Yt;async function en({limit:e,offsetDate:t,archived:n,withPinned:s,serverTimeOffset:a,lastLocalServiceMessage:i}){const o=await jt(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 jt(new g.Api.messages.GetPinnedDialogs({folderId:n?1:void 0})):void 0;if(!o||o instanceof g.Api.messages.DialogsNotModified)return;r&&On(r),On(o);const c=p((r?r.messages:[]).concat(o.messages).map(me).filter(Boolean),"chatId"),l={...r&&Ln(r),...Ln(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=De(e,l[Fe(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}=be(e.draft)||{};n&&(f[t.id]=n),s&&(h[t.id]=s)}}));const y=u.map((e=>e.id)),{users:b,userStatusesById:w}=Ze(((null==r?void 0:r.users)||[]).concat(o.users));let C;return C=o instanceof g.Api.messages.DialogsSlice?o.count:y.length,{chatIds:y,chats:u,users:b,userStatusesById:w,draftsById:f,replyingToById:h,orderedPinnedIds:s?_:void 0,totalChatCount:C}}function tn(e){const{id:t,accessHash:n,adminRights:s}=e;return Q(t,n)instanceof g.Api.InputChannel?async function(e,t,n){var s;const a=await jt(new g.Api.channels.GetFullChannel({channel:Q(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:_,defaultSendAs:y}=a.fullChat,b=r instanceof g.Api.ChatInviteExported?r.link:void 0,{members:w,users:C}=p&&await Dn(e,t)||{},{members:I,users:v}=p&&n&&await Dn(e,t,"kicked")||{},{members:P,users:A}=p&&n&&await Dn(e,t,"admin")||{},S=_?je(_):void 0;if((null==a||null===(s=a.chats)||void 0===s?void 0:s.length)>1){On(a);const[,e]=a.chats,t=Ve(e,void 0,!0);t&&Yt({"@type":"updateChat",id:t.id,chat:t})}return{fullInfo:{about:i,onlineCount:o,inviteLink:b,slowMode:c?{seconds:c,nextSendDate:d}:void 0,migratedFrom:l?{chatId:V(l,"chat"),maxMessageId:u}:void 0,canViewMembers:p,isPreHistoryHidden:h,members:w,kickedMembers:I,adminMembers:P,groupCallId:m?String(m.id):void 0,linkedChatId:f?V(f,"chat"):void 0,botCommands:S,sendAsId:y?N(y):void 0},users:[...C||[],...v||[],...A||[]],groupCall:m?{chatId:e,isLoaded:!1,id:m.id.toString(),accessHash:null==m?void 0:m.accessHash.toString(),participants:{},version:0,participantsCount:0,connectionState:"disconnected"}:void 0}}(t,n,s):async function(e){const t=await jt(new g.Api.messages.GetFullChat({chatId:Q(e)}));if(!(t&&t.fullChat instanceof g.Api.ChatFull))return;On(t);const{about:n,participants:s,exportedInvite:a,botInfo:i,call:o}=t.fullChat,r=Ge(s),c=r?r.filter((({isAdmin:e,isOwner:t})=>e||t)):void 0;return{fullInfo:{about:n,members:r,adminMembers:c,canViewMembers:!0,botCommands:i?je(i):void 0,...a&&{inviteLink:a.link},groupCallId:null==o?void 0:o.id.toString()},users:t.users.map(Je).filter(Boolean),groupCall:o?{chatId:e,isLoaded:!1,id:o.id.toString(),accessHash:o.accessHash.toString(),connectionState:"disconnected",participantsCount:0,version:0,participants:{}}:void 0}}(t)}async function nn({query:e}){const t=await jt(new g.Api.contacts.Search({q:e}));if(!t)return;On(t);const n=t.myResults.map(N),s=t.chats.concat(t.users).map((e=>Ve(e))).filter(Boolean),a=t.users.map(Je).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 sn({type:e,user:t}){let n;if("self"===e||"user"===e){const s=await jt(new g.Api.users.GetUsers({id:["user"===e&&t?Q(t.id,t.accessHash):new g.Api.InputUserSelf]}));if(!s||!s.length)return;[n]=s}else if("support"===e){const e=await jt(new g.Api.help.GetSupport);if(!e||!e.user)return;n=e.user}const s=Ve(n,"support"===e);if(s)return Yt({"@type":"updateChat",id:s.id,chat:s}),{chatId:s.id}}async function an({chat:e,serverTimeOffset:t,lastLocalMessage:n,noLastMessage:s}){const{id:a,accessHash:i}=e,o=await jt(new g.Api.messages.GetPeerDialogs({peers:[new g.Api.InputDialogPeer({peer:$(a,i)})]}));if(!o)return;const r=o.dialogs[0];if(!(r&&r instanceof g.Api.Dialog))return;const c=Ln(o)[Fe(r.peer)];if(!c)return;On(o);const d=me(o.messages[0]),l=n&&(!d||n.date>d.date)?n:d;Yt({"@type":"updateChat",id:a,chat:{...De(r,c,t),...!s&&{lastMessage:l}}})}function on({chat:e,text:t,entities:n,replyToMsgId:s}){return jt(new g.Api.messages.SaveDraft({peer:$(e.id,e.accessHash),message:t,...n&&{entities:n.map(ne)},replyToMsgId:s}))}function rn(e){return jt(new g.Api.messages.SaveDraft({peer:$(e.id,e.accessHash),message:""}))}async function cn({chat:e,isMuted:t,serverTimeOffset:n}){await jt(new g.Api.account.UpdateNotifySettings({peer:new g.Api.InputNotifyPeer({peer:$(e.id,e.accessHash)}),settings:new g.Api.InputPeerNotifySettings({muteUntil:t?Zt:0})})),Yt({"@type":"updateNotifyExceptions",chatId:e.id,isMuted:t}),an({chat:e,serverTimeOffset:n,noLastMessage:!0})}async function dn({title:e,about:t="",users:n},s=!1){const a=await jt(new g.Api.channels.CreateChannel({broadcast:!0,title:e,about:t}),!0);if(!(a instanceof g.Api.Updates))return;const i=a.chats[0];if(!(i&&i instanceof g.Api.Channel))return;const o=Ve(i);if(null!=n&&n.length)try{await jt(new g.Api.channels.InviteToChannel({channel:Q(o.id,o.accessHash),users:n.map((({id:e,accessHash:t})=>Q(e,t)))}),!0,s)}catch(e){}return o}function ln({channelId:e,accessHash:t}){return jt(new g.Api.channels.JoinChannel({channel:Q(e,t)}),!0)}function un({chat:e,user:t}){if("chatTypeBasicGroup"===e.type)return jt(new g.Api.messages.DeleteChatUser({chatId:Q(e.id,e.accessHash),userId:Q(t.id,t.accessHash)}),!0)}function gn({chatId:e}){return jt(new g.Api.messages.DeleteChat({chatId:Q(e)}),!0)}function pn({channelId:e,accessHash:t}){return jt(new g.Api.channels.LeaveChannel({channel:Q(e,t)}),!0)}function fn({channelId:e,accessHash:t}){return jt(new g.Api.channels.DeleteChannel({channel:Q(e,t)}),!0)}async function hn({title:e,users:t}){const n=await jt(new g.Api.messages.CreateChat({title:e,users:t.map((({id:e,accessHash:t})=>Q(e,t)))}),!0,!0);if(!(n instanceof g.Api.Updates))return;const s=n.chats[0];return s&&s instanceof g.Api.Chat?Ve(s):void 0}async function mn({chatId:e,accessHash:t,photo:n}){const s=await Jt(n),a=Q(e,t);return jt(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 _n({chat:e,shouldBePinned:t}){const{id:n,accessHash:s}=e;await jt(new g.Api.messages.ToggleDialogPin({peer:new g.Api.InputDialogPeer({peer:$(n,s)}),pinned:t||void 0}))&&Yt({"@type":"updateChatPinned",id:e.id,isPinned:t})}function yn({chat:e,folderId:t}){const{id:n,accessHash:s}=e;return jt(new g.Api.folders.EditPeerFolders({folderPeers:[new g.Api.InputFolderPeer({peer:$(n,s),folderId:t})]}),!0)}async function bn(){const e=await jt(new g.Api.messages.GetDialogFilters);if(e)return{byId:p(e.map(ze),"id"),orderedIds:e.map((({id:e})=>e))}}async function wn(){const e=await jt(new g.Api.messages.GetSuggestedDialogFilters);if(e)return e.map(We)}async function Cn({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(J).filter(Boolean):[],h=u?u.map(J).filter(Boolean):[],m=p?p.map(J).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 jt(new g.Api.messages.UpdateDialogFilter({id:e,filter:n}))&&Yt({"@type":"updateChatFolder",id:e,folder:t})}async function In(e){const t=await jt(new g.Api.messages.UpdateDialogFilter({id:e,filter:void 0})),n=await wn();t&&Yt({"@type":"updateChatFolder",id:e,folder:void 0}),n&&Yt({"@type":"updateRecommendedChatFolders",folders:n})}async function vn({chat:e,hasUnreadMark:t}){const{id:n,accessHash:s}=e;await jt(new g.Api.messages.MarkDialogUnread({peer:new g.Api.InputDialogPeer({peer:$(n,s)}),unread:t||void 0}))&&Yt({"@type":"updateChat",id:e.id,chat:{hasUnreadMark:t}})}async function Pn(e){const t=await jt(new g.Api.contacts.ResolveUsername({username:e}));if(!t)return;const{users:n,chats:s}=t,a=s.length?Ve(s[0]):Ve(n[0]);return a?(On(t),a):void 0}function An({chat:e,isEnabled:t}){const{id:n,accessHash:s}=e,a=Q(n,s);return jt(new g.Api.channels.TogglePreHistoryHidden({channel:a,enabled:t}),!0)}function Sn({chat:e,bannedRights:t}){const{id:n,accessHash:s}=e,a=$(n,s);return jt(new g.Api.messages.EditChatDefaultBannedRights({peer:a,bannedRights:ie(t)}),!0)}function Mn({chat:e,user:t,bannedRights:n,untilDate:s}){const a=Q(e.id,e.accessHash),i=$(t.id,t.accessHash);return jt(new g.Api.channels.EditBanned({channel:a,participant:i,bannedRights:ie(n,s)}),!0)}function kn({chat:e,user:t,adminRights:n,customTitle:s=""}){const a=Q(e.id,e.accessHash),i=Q(t.id,t.accessHash);return jt(new g.Api.channels.EditAdmin({channel:a,userId:i,adminRights:oe(n),rank:s}),!0)}async function Rn(e,t){const n=Q(e.id,e.accessHash);await jt(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 Un(e,t){await jt(new g.Api.messages.EditChatAbout({peer:$(e.id,e.accessHash),about:t}))&&Yt({"@type":"updateChatFullInfo",id:e.id,fullInfo:{about:t}})}function En({chat:e,isEnabled:t}){const{id:n,accessHash:s}=e,a=Q(n,s);return jt(new g.Api.channels.ToggleSignatures({channel:a,enabled:t}),!0)}async function Dn(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 jt(new g.Api.channels.GetParticipants({channel:Q(e,t),filter:a,offset:s,limit:200}));if(i&&!(i instanceof g.Api.channels.ChannelParticipantsNotModified))return On(i),{members:Ge(i),users:i.users.map(Je).filter(Boolean)}}async function Tn(){const e=await jt(new g.Api.channels.GetGroupsForDiscussion);if(e)return On(e),e.chats.map((e=>Ve(e)))}function Bn({channel:e,chat:t}){return jt(new g.Api.channels.SetDiscussionGroup({broadcast:$(e.id,e.accessHash),group:t?$(t.id,t.accessHash):new g.Api.InputChannelEmpty}))}async function xn(e){const t=await jt(new g.Api.messages.MigrateChat({chatId:Q(e.id)}),!0);if(t&&t instanceof g.Api.Updates)return On(t),Ve(t.chats[1])}async function Vn(e){const t=await jt(new g.Api.messages.CheckChatInvite({hash:e}));if(!t)return;let n;if(t instanceof g.Api.ChatInvite){const{photo:n,participantsCount:s,title:a,channel:i,requestNeeded:o,about:r}=t;n instanceof g.Api.Photo&&q(t.photo),Yt({"@type":"showInvite",data:{title:a,about:r,hash:e,participantsCount:s,isChannel:i,isRequestNeeded:o,...n instanceof g.Api.Photo&&{photo:C(n)}}})}else n=Ve(t.chat),n&&Yt({"@type":"updateChat",id:n.id,chat:n});return n?{chatId:n.id}:void 0}function Nn(e,t,n=!1){try{return"chatTypeChannel"===e.type||"chatTypeSuperGroup"===e.type?jt(new g.Api.channels.InviteToChannel({channel:Q(e.id,e.accessHash),users:t.map((e=>Q(e.id,e.accessHash)))}),!0,n):Promise.all(t.map((t=>jt(new g.Api.messages.AddChatUser({chatId:Q(e.id),userId:Q(t.id,t.accessHash)}),!0,n))))}catch(e){return}}function Fn(e,t){return"chatTypeChannel"===e.type||"chatTypeSuperGroup"===e.type?Mn({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:Zt}):jt(new g.Api.messages.DeleteChatUser({chatId:Q(e.id),userId:Q(t.id,t.accessHash)}),!0)}function Ln(e){const t={};return e.chats.forEach((e=>{t[`chat${e.id}`]=e})),e.users.forEach((e=>{t[`user${e.id}`]=e})),t}function On(e){"users"in e&&G(e.users),"chats"in e&&G(e.chats),"messages"in e&&e.messages.forEach((e=>{e instanceof g.Api.Message&&se(e)&&O(e)}))}async function qn({hash:e}){const t=await jt(new g.Api.messages.ImportChatInvite({hash:e}),!0);if(t instanceof g.Api.Updates&&t.chats.length)return Ve(t.chats[0])}function Hn({chat:e,isProtected:t}){const{id:n,accessHash:s}=e;return jt(new g.Api.messages.ToggleNoForwards({peer:$(n,s),enabled:t}),!0)}function Gn(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}),Gn(this,"name",void 0),Object.assign(this,s)}else super(e),Gn(this,"name",void 0);this.name=t}});var Kn=n(8764).Buffer;let zn;async function Wn({chat:e,threadId:t,...n}){const s=-1===t?g.Api.messages.GetHistory:g.Api.messages.GetReplies;let a;try{a=await jt(new s({peer:$(e.id,e.accessHash),...-1!==t&&{msgId:t},...n}),void 0,!0)}catch(t){"CHANNEL_PRIVATE"===t.message&&zn({"@type":"updateChat",id:e.id,chat:{isRestricted:!0}})}if(!a||a instanceof g.Api.messages.MessagesNotModified||!a.messages)return;bs(a);const i=a.messages.map(me).filter(Boolean),o=a.users.map(Je).filter(Boolean),r=a.chats.map((e=>Ve(e))).filter(Boolean),c=i.map((({threadInfo:e})=>e)).filter(Boolean);return{messages:i,users:o,chats:r,threadInfos:c}}async function jn({chat:e,messageId:t}){const n="channel"===W(e.id);let s;try{s=await jt(n?new g.Api.channels.GetMessages({channel:Q(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&&zn({"@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&&me(a);return i?(a instanceof g.Api.Message&&O(a),{message:i,users:s.users.map(Je).filter(Boolean)}):void 0}let $n=Promise.resolve();function Jn({chat:e,text:t,entities:n,replyingTo:s,attachment:a,sticker:i,gif:o,poll:r,contact:c,isSilent:d,scheduledAt:l,groupedId:u,noWebPage:p,sendAs:f,serverTimeOffset:h},m){const _=function(e,t,n,s,a,i,o,r,c,d,l,u,g=0){const p=fe++,f=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:ge,sizes:[],thumbnail:{width:o,height:r,dataUri:""},blobUrl:n}}:{video:{id:ge,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:{id:ge,duration:t,waveform:s}}}return a.startsWith("audio/")?{audio:{id:ge,mimeType:a,fileName:t,size:i,duration:200}}:{document:{mimeType:a,fileName:t,size:i,...s&&{previewBlobUrl:s}}}}(a),h="chatTypeChannel"===e.type;return{id:p,chatId:e.id,content:{...t&&{text:{text:t,entities:n}},...f,...i&&{sticker:i},...o&&{video:o},...r&&Me(r,p),...c&&{contact:c}},date:l||Math.round(Date.now()/1e3)+g,isOutgoing:!h,senderId:(null==u?void 0:u.id)||pe,...s&&{replyToMessageId:s},...d&&{groupedId:d,...f&&(f.photo||f.video)&&{isInAlbum:!0}},...l&&{isScheduled:!0}}}(e,t,n,s,a,i,o,r,c,u,l,f,h);zn({"@type":_.isScheduled?"newScheduledMessage":"newMessage",id:_.id,chatId:e.id,message:_}),setTimeout((()=>{zn({"@type":_.isScheduled?"updateScheduledMessage":"updateMessage",id:_.id,chatId:e.id,message:{sendingState:"messageSendingStatePending"}})}),1e3);const y=ee();if(v.localMessages[String(y)]=_,u)return function({chat:e,text:t,entities:n,replyingTo:s,attachment:a,groupedId:i,isSilent:o,scheduledAt:r,sendAs:c},d,l,u){let p=-1;Qn[i]||(Qn[i]={counter:0,singleMediaByIndex:{}}),p=Qn[i].counter++;const f=$n;return $n=(async()=>{let h;try{h=await Yn(l,a,u)}catch(e){return Qn[i].counter--,void await f}const m=await async function(e,t){const n=await jt(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})})}}($(e.id,e.accessHash),h);if(await f,!m)return void Qn[i].counter--;if(Qn[i].singleMediaByIndex[p]=new g.Api.InputSingleMedia({media:m,randomId:d,message:t||"",entities:n?n.map(ne):void 0}),Object.keys(Qn[i].singleMediaByIndex).length{let u;if(a)try{u=await Yn(_,a,m)}catch(e){return void await b}else i?u=Y(i):o?u=Y(o):r?u=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:z(t)}))),quiz:n.quiz,multipleChoice:n.multipleChoice});if(!s)return new g.Api.InputMediaPoll({poll:a});const i=s.correctAnswers.map(z),{solution:o}=s,r=s.solutionEntities?s.solutionEntities.map(ne):[];return new g.Api.InputMediaPoll({poll:a,correctAnswers:i,...o&&{solution:o,solutionEntities:r}})}(r,y):c&&(u=new g.Api.InputMediaContact({phoneNumber:c.phoneNumber,firstName:c.firstName,lastName:c.lastName,vcard:""}));await b;const h=u?g.Api.messages.SendMedia:g.Api.messages.SendMessage;await jt(new h({clearDraft:!0,message:t||"",entities:n?n.map(ne):void 0,peer:$(e.id,e.accessHash),randomId:y,...d&&{silent:d},...l&&{scheduleDate:l},...s&&{replyToMsgId:s},...u&&{media:u},...p&&{noWebpage:p},...f&&{sendAs:$(f.id,f.accessHash)}}),!0)})(),$n}const Qn={};async function Xn({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}}}};zn({"@type":o?"updateScheduledMessage":"updateMessage",id:t.id,chatId:e.id,message:r}),v.localMessages[t.id]={...t,...r};const c=s&&s.map(ne);await jt(new g.Api.messages.EditMessage({message:n||"",entities:c,peer:$(e.id,e.accessHash),id:t.id,...o&&{scheduleDate:t.date},...a&&{noWebpage:a}}),!0)}async function Zn({chat:e,message:t,scheduledAt:n}){await jt(new g.Api.messages.EditMessage({peer:$(e.id,e.accessHash),id:t.id,scheduleDate:n}),!0)}async function Yn(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 Jt(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:Kn.from(n)}))}return new g.Api.InputMediaUploadedDocument({file:p,mimeType:i,attributes:f})}async function es({chat:e,messageId:t,isUnpin:n,isOneSide:s,isSilent:a}){await jt(new g.Api.messages.UpdatePinnedMessage({peer:$(e.id,e.accessHash),id:t,...n&&{unpin:!0},...s&&{pmOneside:!0},...a&&{silent:!0}}),!0)}async function ts({chat:e}){await jt(new g.Api.messages.UnpinAllMessages({peer:$(e.id,e.accessHash)}),!0)}async function ns({chat:e,messageIds:t,shouldDeleteForAll:n}){const s="channel"===W(e.id);await jt(s?new g.Api.channels.DeleteMessages({channel:Q(e.id,e.accessHash),id:t}):new g.Api.messages.DeleteMessages({id:t,...n&&{revoke:!0}}))&&zn({"@type":"deleteMessages",ids:t,...s&&{chatId:e.id}})}async function ss({chat:e,messageIds:t}){await jt(new g.Api.messages.DeleteScheduledMessages({peer:$(e.id,e.accessHash),id:t}))&&zn({"@type":"deleteScheduledMessages",ids:t,chatId:e.id})}async function as({chat:e,shouldDeleteForAll:t,maxId:n}){const s="channel"===W(e.id);await jt(s?new g.Api.channels.DeleteHistory({channel:Q(e.id,e.accessHash),maxId:n}):new g.Api.messages.DeleteHistory({peer:$(e.id,e.accessHash),...t&&{revoke:!0},...!t&&{just_clear:!0},maxId:n}))&&zn({"@type":"deleteHistory",chatId:e.id})}async function is({peer:e,messageIds:t,reason:n,description:s}){return await jt(new g.Api.messages.Report({peer:$(e.id,e.accessHash),id:t,reason:de(n),message:s}))}async function os({peer:e,threadId:t,action:n}){const s=function(e){switch(e.type){case"cancel":return new g.Api.SendMessageCancelAction;case"typing":return new g.Api.SendMessageTypingAction;case"recordAudio":return new g.Api.SendMessageRecordAudioAction;case"chooseSticker":return new g.Api.SendMessageChooseStickerAction}}(n);if(s)return await jt(new g.Api.messages.SetTyping({peer:$(e.id,e.accessHash),topMsgId:t,action:s}))}async function rs({chat:e,threadId:t,maxId:n,serverTimeOffset:s}){const a="channel"===W(e.id);a&&-1===t?await jt(new g.Api.channels.ReadHistory({channel:Q(e.id,e.accessHash),maxId:n})):a?await jt(new g.Api.messages.ReadDiscussion({peer:$(e.id,e.accessHash),msgId:t,readMaxId:n})):await jt(new g.Api.messages.ReadHistory({peer:$(e.id,e.accessHash),maxId:n})),-1===t?an({chat:e,serverTimeOffset:s,noLastMessage:!0}):ds({chat:e,threadId:t})}async function cs({chat:e,messageIds:t}){const n="channel"===W(e.id);await jt(n?new g.Api.channels.ReadMessageContents({channel:Q(e.id,e.accessHash),id:t}):new g.Api.messages.ReadMessageContents({id:t})),zn({...n?{"@type":"updateChannelMessages",channelId:e.id}:{"@type":"updateCommonBoxMessages"},ids:t,messageUpdate:{hasUnreadMention:!1,isMediaUnread:!1}})}async function ds({chat:e,threadId:t}){const[n,s]=await Promise.all([jt(new g.Api.messages.GetDiscussionMessage({peer:$(e.id,e.accessHash),msgId:t})),jt(new g.Api.messages.GetReplies({peer:$(e.id,e.accessHash),msgId:t,offsetId:1,addOffset:-1,limit:1}))]);if(!n||!n.messages.length)return;const a=L(n.messages[0]);return a?(zn({"@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=>Ve(e))).filter(Boolean).forEach((e=>{zn({"@type":"updateChat",id:e.id,chat:e,noTopChatsRequest:!0})})),{discussionChatId:a}):void 0}async function ls({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 jt(new g.Api.messages.Search({peer:$(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;bs(c);const d=c.messages.map(me).filter(Boolean),l=c.users.map(Je).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 us({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 jt(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;bs({chats:r.chats,users:r.users,messages:r.messages});const c=r.chats.map((e=>Ve(e))).filter(Boolean),d=r.users.map(Je).filter(Boolean),l=r.messages.map(me).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 gs({message:e}){const t=await jt(new g.Api.messages.GetWebPagePreview({message:e}));return t&&Ae(t)}async function ps({chat:e,messageId:t,options:n}){const{id:s,accessHash:a}=e;await jt(new g.Api.messages.SendVote({peer:$(s,a),msgId:t,options:n.map(z)}),!0)}async function fs({chat:e,messageId:t,option:n,offset:s,limit:a,shouldResetVoters:i}){const{id:o,accessHash:r}=e,c=await jt(new g.Api.messages.GetPollVotes({peer:$(o,r),id:t,...n&&{option:z(n)},...s&&{offset:s},...a&&{limit:a}}));if(!c)return;bs({chats:[],users:c.users,messages:[]});const d=c.users.map(Je).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 hs({fromChat:e,toChat:t,messages:n,serverTimeOffset:s,isSilent:a,scheduledAt:i,sendAs:o}){const r=n.map((({id:e})=>e)),c=n.map(ee);n.forEach(((e,n)=>{const a=function(e,t,n,s){const a=fe++,{content:i,chatId:o,id:r,senderId:c,groupedId:d,isInAlbum:l}=t,u=i.audio,g=e.id===pe&&(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:pe,sendingState:"messageSendingStatePending",groupedId:d,isInAlbum:l,...c!==pe&&!u&&{forwardInfo:{date:t.date,isChannelPost:!1,fromChatId:o,fromMessageId:r,senderUserId:c}},...s&&{isScheduled:!0}}}(t,e,s,i);v.localMessages[String(c[n])]=a,zn({"@type":a.isScheduled?"newScheduledMessage":"newMessage",id:a.id,chatId:t.id,message:a})})),await jt(new g.Api.messages.ForwardMessages({fromPeer:$(e.id,e.accessHash),toPeer:$(t.id,t.accessHash),randomId:c,id:r,...a&&{sil2ent:a},...i&&{scheduleDate:i},...o&&{sendAs:$(o.id,o.accessHash)}}),!0)}async function ms({chat:e,timestamp:t}){const n=await jt(new g.Api.messages.GetHistory({peer:$(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 _s({chat:e}){const{id:t,accessHash:n}=e,s=await jt(new g.Api.messages.GetScheduledHistory({peer:$(t,n)}));if(s&&!(s instanceof g.Api.messages.MessagesNotModified)&&s.messages)return bs(s),{messages:s.messages.map(me).filter(Boolean)}}async function ys({chat:e,ids:t}){const{id:n,accessHash:s}=e;await jt(new g.Api.messages.SendScheduledMessages({peer:$(n,s),id:t}),!0)}function bs(e){e.users.forEach((e=>{e instanceof g.Api.User&&(v.users[V(e.id,"user")]=e)})),e.chats.forEach((e=>{(e instanceof g.Api.Chat||e instanceof g.Api.Channel)&&(v.chats[V(e.id,e instanceof g.Api.Chat?"chat":"channel")]=e)})),e.messages.forEach((e=>{(e instanceof g.Api.Message&&se(e)||e instanceof g.Api.MessageService&&function(e){return"photo"in e.action&&e.action.photo instanceof g.Api.Photo}(e))&&O(e)}))}async function ws({chat:e}){const t=await jt(new g.Api.messages.Search({peer:$(e.id,e.accessHash),filter:new g.Api.InputMessagesFilterPinned,q:"",limit:50}));if(t&&!(t instanceof g.Api.messages.MessagesNotModified)&&t.messages)return bs(t),{messages:t.messages.map(me).filter(Boolean),users:t.users.map(Je).filter(Boolean),chats:t.chats.map((e=>Ve(e))).filter(Boolean)}}async function Cs({chat:e,messageId:t}){const n=await jt(new g.Api.messages.GetMessageReadParticipants({peer:$(e.id,e.accessHash),msgId:t}));return n?n.map(String):void 0}async function Is({chat:e}){const t=await jt(new g.Api.channels.GetSendAs({peer:$(e.id,e.accessHash)}));if(t)return G(t.users),G(t.chats),{users:t.users.map(Je).filter(Boolean),chats:t.chats.map((e=>Ve(e))).filter(Boolean),ids:t.peers.map(N)}}function vs({sendAs:e,chat:t}){return jt(new g.Api.messages.SaveDefaultSendAs({peer:$(t.id,t.accessHash),sendAs:$(e.id,e.accessHash)}))}async function Ps({chat:e}){const t=await jt(new g.Api.channels.GetSponsoredMessages({channel:$(e.id,e.accessHash)}));if(t&&t.messages.length)return bs(t),{messages:t.messages.map(he).filter(Boolean),users:t.users.map(Je).filter(Boolean),chats:t.chats.map((e=>Ve(e))).filter(Boolean)}}async function As({chat:e,random:t}){await jt(new g.Api.channels.ViewSponsoredMessage({channel:$(e.id,e.accessHash),randomId:z(t)}))}let Ss,Ms,ks,Rs;async function Us({id:e,accessHash:t}){const n=Q(e,t);if(!(n instanceof g.Api.InputUser))return;const s=await jt(new g.Api.users.GetFullUser({id:n}));if(!s)return;const a=$e(s);Ss({"@type":"updateUser",id:e,user:{fullInfo:a.fullInfo}})}async function Es(e,t,n){const s=await jt(new g.Api.messages.GetCommonChats({userId:Q(e,t),maxId:n?le(n,W(n)):void 0,limit:100}));if(!s)return;Os(s);const a=[],i=[];return s.chats.forEach((e=>{const t=Ve(e);t&&(i.push(t),a.push(t.id))})),{chats:i,chatIds:a,isFullyLoaded:a.length<100}}async function Ds(){const e=await jt(new g.Api.help.GetNearestDc);return null==e?void 0:e.country}async function Ts(){const e=await jt(new g.Api.contacts.GetTopPeers({correspondents:!0}));if(!(e instanceof g.Api.contacts.TopPeers))return;const t=e.users.map(Je).filter((e=>!!e&&!e.isSelf));return{ids:t.map((({id:e})=>e)),users:t}}async function Bs(){const e=await jt(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[V(e.id,"user")]=e)})),{users:e.users.map(Je).filter(Boolean),chats:e.users.map((e=>Ve(e))).filter(Boolean)}}async function xs({users:e}){const t=await jt(new g.Api.users.GetUsers({id:e.map((({id:e,accessHash:t})=>$(e,t)))}));if(t&&t.length)return t.forEach((e=>{e instanceof g.Api.User&&(v.users[V(e.id,"user")]=e)})),Ze(t)}function Vs({phone:e,firstName:t,lastName:n}){return jt(new g.Api.contacts.ImportContacts({contacts:[ae({phone:e||"",firstName:t||"",lastName:n||""})]}))}function Ns({id:e,accessHash:t,phoneNumber:n="",firstName:s="",lastName:a=""}){return jt(new g.Api.contacts.AddContact({id:Q(e,t),firstName:s,lastName:a,phone:n}),!0)}async function Fs({id:e,accessHash:t}){const n=Q(e,t);n instanceof g.Api.InputUser&&await jt(new g.Api.contacts.DeleteContacts({id:[n]}))&&Ss({"@type":"deleteContact",id:e})}async function Ls(e,t){if(e){const{id:t,accessHash:n}=e,s=await jt(new g.Api.photos.GetUserPhotos({userId:Q(t,n),limit:40,offset:0,maxId:U()("0")}));if(!s)return;return Os(s),{photos:s.photos.filter((e=>e instanceof g.Api.Photo)).map(C)}}const n=await ls({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 Os(e){"chats"in e&&G(e.chats),"photos"in e&&e.photos.forEach(q)}async function qs({hash:e="0"}){const t=await jt(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(S)}}async function Hs({hash:e="0"}){const t=await jt(new g.Api.messages.GetRecentStickers({hash:U()(e)}));if(t&&!(t instanceof g.Api.messages.RecentStickersNotModified))return{hash:String(t.hash),stickers:ta(t.stickers.slice(0,20))}}async function Gs({hash:e="0"}){const t=await jt(new g.Api.messages.GetFavedStickers({hash:U()(e)}));if(t&&!(t instanceof g.Api.messages.FavedStickersNotModified))return{hash:String(t.hash),stickers:ta(t.stickers)}}async function Ks({hash:e="0"}){const t=await jt(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 zs({sticker:e,unfave:t}){const n=new g.Api.messages.FaveSticker({id:Z(e),unfave:t});await jt(n)&&Ms({"@type":"updateFavoriteStickers"})}async function Ws({stickerSetShortName:e,stickerSetId:t,accessHash:n}){const s=await jt(new g.Api.messages.GetStickerSet({stickerset:t?X(t,n):(a=e,new g.Api.InputStickerSetShortName({shortName:a}))}));var a,i;if(s instanceof g.Api.messages.StickerSet)return{set:S(s.set),stickers:ta(s.documents),packs:(i=s.packs,i.reduce(((e,{emoticon:t,documents:n})=>(e[t]=n.map((e=>A(v.documents[String(e)]))).filter(Boolean),e)),{}))}}async function js(){const e=await jt(new g.Api.messages.GetStickerSet({stickerset:new g.Api.InputStickerSetAnimatedEmoji}));if(e instanceof g.Api.messages.StickerSet)return{set:S(e.set),stickers:ta(e.documents)}}async function $s({query:e,hash:t="0"}){const n=await jt(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 Js({hash:e="0"}){const t=await jt(new g.Api.messages.GetSavedGifs({hash:U()(e)}));if(t&&!(t instanceof g.Api.messages.SavedGifsNotModified))return{hash:String(t.hash),gifs:na(t.gifs)}}async function Qs({stickerSetId:e,accessHash:t}){await jt(new g.Api.messages.InstallStickerSet({stickerset:X(e,t)}))&&Ms({"@type":"updateStickerSet",id:e,stickerSet:{installedDate:Date.now()}})}async function Xs({stickerSetId:e,accessHash:t}){await jt(new g.Api.messages.UninstallStickerSet({stickerset:X(e,t)}))&&Ms({"@type":"updateStickerSet",id:e,stickerSet:{installedDate:void 0}})}async function Zs({query:e,offset:t=""}){if(!ks){const e=await jt(new g.Api.help.GetConfig);if(!e)return;const t=await jt(new g.Api.contacts.ResolveUsername({username:e.gifSearchUsername}));if(!(t&&t.users[0]instanceof g.Api.User))return;ks=new g.Api.InputUser({userId:t.peer.userId,accessHash:t.users[0].accessHash})}const n=await jt(new g.Api.messages.GetInlineBotResults({bot:ks,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:na(s)}}async function Ys({emoji:e,hash:t="0"}){const n=await jt(new g.Api.messages.GetStickers({emoticon:e,hash:U()(t)}));if(n&&!(n instanceof g.Api.messages.StickersNotModified))return{stickers:ta(n.stickers),hash:String(n.hash)}}async function ea({language:e,fromVersion:t}){const n=await jt(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 ta(e){return e.map((e=>{if(e instanceof g.Api.Document){const t=A(e);if(t)return v.documents[String(e.id)]=e,t}})).filter(Boolean)}function na(e){return e.map((e=>{if(e instanceof g.Api.Document){const t=Ce(e);if(t)return v.documents[String(e.id)]=e,t}})).filter(Boolean)}async function sa({username:e}){try{return await jt(new g.Api.channels.CheckUsername({channel:new g.Api.InputChannelEmpty,username:e}),void 0,!0)}catch(e){return!1}}async function aa({chat:e,username:t}){await jt(new g.Api.channels.UpdateUsername({channel:Q(e.id,e.accessHash),username:t}))&&Rs({"@type":"updateChat",id:e.id,chat:{username:t}})}async function ia({chat:e,usageLimit:t,expireDate:n}){const s=await jt(new g.Api.messages.ExportChatInvite({peer:$(e.id,e.accessHash),usageLimit:t,expireDate:n}));if(s)return Rs({"@type":"updateChatFullInfo",id:e.id,fullInfo:{inviteLink:s.link}}),s.link}const oa={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"},ra={};let ca,da;async function la(){const e=await jt(new g.Api.account.GetPassword);if(!e)return;const{hint:t,hasPassword:n}=e;return{hint:t,hasPassword:n}}function ua(e){return ca({"@type":"updateTwoFaStateWaitCode",length:e}),new Promise(((e,t)=>{ra.resolve=e,ra.reject=t}))}async function ga(e){try{return await Qt({isCheckPassword:!0,currentPassword:e}),!0}catch(e){return _a(e),!1}}async function pa(e){try{return await Qt({currentPassword:e}),!0}catch(e){return _a(e),!1}}async function fa(e,t,n,s){try{return await Qt({currentPassword:e,newPassword:t,hint:n,email:s,emailCodeCallback:ua,onEmailCodeError:_a}),!0}catch(e){return _a(e),!1}}async function ha(e,t){try{return await Qt({currentPassword:e,newPassword:e,email:t,emailCodeCallback:ua,onEmailCodeError:_a}),!0}catch(e){return _a(e),!1}}function ma(e){ra.resolve(e)}function _a(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=oa[e.message];t||(t="Unexpected Error"),ca({"@type":"updateTwoFaError",message:t})}async function ya({call:e}){const t=await jt(new g.Api.phone.GetGroupCall({call:ue(e)}));if(!t)return;G(t.users),G(t.chats);const n=t.users.map(Je).filter(Boolean),s=t.chats.map((e=>Ve(e))).filter(Boolean);return{groupCall:rt(t.call),users:n,chats:s}}function ba({call:e}){return jt(new g.Api.phone.DiscardGroupCall({call:ue(e)}),!0)}function wa({call:e,participant:t,muted:n,presentationPaused:s,videoStopped:a,videoPaused:i,volume:o,raiseHand:r}){return jt(new g.Api.phone.EditGroupCallParticipant({call:ue(e),participant:$(t.id,t.accessHash),...void 0!==a&&{videoStopped:a},...void 0!==i&&{videoPaused:i},...void 0!==n&&{muted:n},...void 0!==s&&{presentationPaused:s},...void 0!==r&&{raiseHand:r},...void 0!==o&&{volume:o}}),!0)}function Ca({groupCall:e,title:t}){return jt(new g.Api.phone.EditGroupCallTitle({title:t,call:ue(e)}),!0)}async function Ia({call:e,canSelfUnmute:t}){const n=await jt(new g.Api.phone.ExportGroupCallInvite({canSelfUnmute:t||void 0,call:ue(e)}));if(n)return n.link}async function va({call:e,offset:t}){const n=await jt(new g.Api.phone.GetGroupParticipants({call:ue(e),ids:[],sources:[],offset:t||"",limit:100}));if(!n)return;G(n.users),G(n.chats);const s=n.users.map(Je).filter(Boolean),a=n.chats.map((e=>Ve(e))).filter(Boolean);return da({"@type":"updateGroupCallParticipants",groupCallId:e.id,participants:n.participants.map(at),nextOffset:n.nextOffset}),{users:s,chats:a}}function Pa({call:e}){return jt(new g.Api.phone.LeaveGroupCall({call:ue(e)}),!0)}async function Aa({call:e,inviteHash:t,params:n}){const s=await jt(new g.Api.phone.JoinGroupCall({call:ue(e),joinAs:new g.Api.InputPeerSelf,muted:!0,videoStopped:!0,params:new g.Api.DataJSON({data:JSON.stringify(n)}),inviteHash:t}),!0);if(s&&s instanceof g.Api.Updates){const e=s.updates.find((e=>e instanceof g.Api.UpdateGroupCall));if(!(e instanceof g.Api.UpdateGroupCall))return;return rt(e.call)}}async function Sa({peer:e}){const t=(0,E.readBigIntFromBuffer)((0,E.generateRandomBytes)(4),!0,!0).toJSNumber(),n=await jt(new g.Api.phone.CreateGroupCall({peer:$(e.id,e.accessHash),randomId:t}),!0);if(n&&n instanceof g.Api.Updates){const e=n.updates[0];if(e instanceof g.Api.UpdateGroupCall)return rt(e.call)}}function Ma({call:e,params:t}){return jt(new g.Api.phone.JoinGroupCallPresentation({call:ue(e),params:new g.Api.DataJSON({data:JSON.stringify(t)})}),!0)}function ka({call:e,subscribed:t}){return jt(new g.Api.phone.ToggleGroupCallStartSubscription({call:ue(e),subscribed:t}),!0)}function Ra({call:e}){return jt(new g.Api.phone.LeaveGroupCallPresentation({call:ue(e)}),!0)}const Ua=["ar","fa","id","ko","uz"];function Ea({firstName:e,lastName:t,about:n}){return jt(new g.Api.account.UpdateProfile({firstName:e||"",lastName:t||"",about:n||""}))}function Da(e){return jt(new g.Api.account.CheckUsername({username:e}))}function Ta(e){return jt(new g.Api.account.UpdateUsername({username:e}))}async function Ba(e){const t=await Jt(e);return jt(new g.Api.photos.UploadProfilePhoto({file:t}))}async function xa(e){const t=await Jt(e);await jt(new g.Api.photos.UploadProfilePhoto({file:t}))}async function Va(){const e=await jt(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(Ye).filter(Boolean)}}async function Na(e){const t=await Jt(e),n=await jt(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=Ye(n);return s?(v.documents[String(n.document.id)]=n.document,{wallpaper:s}):void 0}async function Fa(){const e=await jt(new g.Api.contacts.GetBlocked({limit:100}));if(e)return ai(e),{users:e.users.map(Je).filter(Boolean),chats:e.chats.map((e=>Ve(e,void 0,!0))).filter(Boolean),blockedIds:e.blocked.map((e=>N(e.peerId))),totalCount:e instanceof g.Api.contacts.BlockedSlice?e.count:e.blocked.length}}function La(e,t){return jt(new g.Api.contacts.Block({id:$(e,t)}))}function Oa(e,t){return jt(new g.Api.contacts.Unblock({id:$(e,t)}))}async function qa(){const e=await jt(new g.Api.account.GetAuthorizations);if(e)return e.authorizations.map(et)}function Ha(e){return jt(new g.Api.account.ResetAuthorization({hash:U()(e)}))}function Ga(){return jt(new g.Api.auth.ResetAuthorizations)}async function Ka({serverTimeOffset:e}){const t=await jt(new g.Api.account.GetNotifyExceptions({compareSound:!0}));if(t instanceof g.Api.Updates||t instanceof g.Api.UpdatesCombined)return ai(t),t.updates.reduce(((t,n)=>n instanceof g.Api.UpdateNotifySettings&&n.peer instanceof g.Api.NotifyPeer?(t.push(nt(n.notifySettings,n.peer.peer,e)),t):t),[])}async function za({serverTimeOffset:e}){const[t,n,s,a]=await Promise.all([jt(new g.Api.account.GetContactSignUpNotification),jt(new g.Api.account.GetNotifySettings({peer:new g.Api.InputNotifyUsers})),jt(new g.Api.account.GetNotifySettings({peer:new g.Api.InputNotifyChats})),jt(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&&Ue(e)jt(new g.Api.langpack.GetLangPack({langPack:e,langCode:Ua.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 Qa({langPack:e,langCode:t,keys:n}){const s=await jt(new g.Api.langpack.GetStrings({langPack:e,langCode:Ua.includes(t)?`${t}-raw`:t,keys:n}));if(s)return s.map(_)}async function Xa(e){const t=ce(e),n=await jt(new g.Api.account.GetPrivacy({key:t}));if(n)return ai(n),tt(n.rules)}function Za(e){const t=qt.session.getAuthKey().getKey();return jt(new g.Api.account.RegisterDevice({tokenType:10,secret:t,appSandbox:!1,otherUids:[],token:e}))}function Ya(e){return jt(new g.Api.account.UnregisterDevice({tokenType:10,otherUids:[],token:e}))}async function ei(e,t){const n=ce(e),s=[];switch(t.allowedUsers&&s.push(new g.Api.InputPrivacyValueAllowUsers({users:t.allowedUsers.map((({id:e,accessHash:t})=>Q(e,t)))})),t.allowedChats&&s.push(new g.Api.InputPrivacyValueAllowChatParticipants({chats:t.allowedChats.map((({id:e})=>Q(e)))})),t.blockedUsers&&s.push(new g.Api.InputPrivacyValueDisallowUsers({users:t.blockedUsers.map((({id:e,accessHash:t})=>Q(e,t)))})),t.blockedChats&&s.push(new g.Api.InputPrivacyValueDisallowChatParticipants({chats:t.blockedChats.map((({id:e})=>Q(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 jt(new g.Api.account.SetPrivacy({key:n,rules:s}));if(a)return ai(a),tt(a.rules)}async function ti(e){await jt(new g.Api.account.UpdateStatus({offline:!e}))}async function ni(){const e=await jt(new g.Api.account.GetContentSettings);if(e)return{isSensitiveEnabled:Boolean(e.sensitiveEnabled),canChangeSensitive:Boolean(e.sensitiveCanChange)}}function si(e){return jt(new g.Api.account.SetContentSettings({sensitiveEnabled:e||void 0}))}function ai(e){e.users.forEach((e=>{e instanceof g.Api.User&&(v.users[V(e.id,"user")]=e)})),e.chats.forEach((e=>{(e instanceof g.Api.Chat||e instanceof g.Api.Channel)&&(v.chats[V(e.id,e instanceof g.Api.Chat?"chat":"channel")]=e)}))}async function ii({langCode:e="en"}){const t=await jt(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=>st(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=>st(e))).sort(((e,t)=>e.name?e.name.localeCompare(t.name):e.defaultName.localeCompare(t.defaultName)))};var n,s}function oi(e){return e?f(e,["url","mimeType"]):void 0}function ri({chatId:e,accessHash:t,messageId:n,data:s}){return jt(new g.Api.messages.GetBotCallbackAnswer({peer:$(e,t),msgId:n,data:z(s)}))}async function ci(){const e=await jt(new g.Api.contacts.GetTopPeers({botsInline:!0}));if(!(e instanceof g.Api.contacts.TopPeers))return;const t=e.users.map(Je).filter(Boolean);return{ids:t.map((({id:e})=>e)),users:t}}async function di({username:e}){const t=await jt(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 H(t.users[0]),{user:Je(t.users[0]),chat:Ve(t.users[0])}}async function li({bot:e,chat:t,query:n,offset:s=""}){const a=await jt(new g.Api.messages.GetInlineBotResults({bot:$(e.id,e.accessHash),peer:$(t.id,t.accessHash),query:n,offset:s}));var i,o,r,c,d;if(a)return G(a.users),{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(Je).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:A(r)},...o instanceof g.Api.Photo&&{photo:C(o)},..."gif"===s&&r instanceof g.Api.Document&&{gif:Ce(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:oi(r)}}(e,i));var t,n,s})))}}async function ui({chat:e,resultId:t,queryId:n,replyingTo:s,sendAs:a}){const i=ee();await jt(new g.Api.messages.SendInlineBotResult({clearDraft:!0,randomId:i,queryId:U()(n),peer:$(e.id,e.accessHash),id:t,...s&&{replyToMsgId:s},...a&&{sendAs:$(a.id,a.accessHash)}}),!0)}async function gi({bot:e,startParam:t}){const n=ee();await jt(new g.Api.messages.StartBot({bot:$(e.id,e.accessHash),peer:$(e.id,e.accessHash),randomId:n,startParam:t}),!0)}function pi(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 fi({chat:e,messageId:t,requestInfo:n,shouldSave:s}){const a=await jt(new g.Api.payments.ValidateRequestedInfo({peer:$(e.id,e.accessHash),msgId:t,save:s||void 0,info:re(n)}));if(!a)return;const{id:i,shippingOptions:o}=a;return i?{id:i,shippingOptions:pi(o)}:void 0}function hi({chat:e,messageId:t,formId:n,requestedInfoId:s,shippingOptionId:a,credentials:i}){return jt(new g.Api.payments.SendPaymentForm({formId:U()(n),peer:$(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 mi({chat:e,messageId:t}){const n=await jt(new g.Api.payments.GetPaymentForm({peer:$(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 _i(e,t){const n=await jt(new g.Api.payments.GetPaymentReceipt({peer:$(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 yi;async function bi(e,t){yi=e,function(e){ct=e}(Pi),function(e){mt=e}(Pi),function(e){Yt=e}(Pi),function(e){zn=e}(Pi),function(e){Ss=e}(Pi),function(e){Ms=e}(Pi),function(e){Rs=e}(Pi),function(e){ca=e}(Pi),function(e){da=e}(Pi),await async function(e,t){Ot=e;const{userAgent:n,platform:s,sessionData:a,isTest:i,isMovSupported:o}=t,r=new g.sessions.CallbackSession(a,zt);self.isMovSupported=o,qt=new g.TelegramClient(r,"2496","8da85b0d5bfe62527e5b244c209159c3",{deviceModel:navigator.userAgent||n||"Unknown UserAgent",systemVersion:s||"Unknown platform",appVersion:"1.28.4 Z",useWSS:!0,additionalDcsDisabled:!1,testServers:i}),qt.addEventHandler(Wt,Lt),qt.addEventHandler(pt,Lt);try{try{await qt.start({phoneNumber:_t,phoneCode:yt,password:bt,firstAndLastNames:wt,qrCode:Ct,onError:It,initialMethod:"iOS"===s||"Android"===s?"phoneNumber":"qrCode"})}catch(e){if("Disconnect"!==e.message)return void Ot({"@type":"updateConnectionState",connectionState:"connectionStateBroken"})}mt(vt("authorizationStateReady")),zt(r.getSessionData()),Ot({"@type":"updateApiReady"}),Xt()}catch(e){throw e}}(Pi,t)}const wi=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(!vi||e!==Ii)return;const t=vi;vi=void 0,t.forEach(yi)}));let Ci,Ii,vi;function Pi(e){vi?vi.push(e):vi=[e],Ci&&!o.has(e["@type"])||(Ci=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))}}(wi,i,!0),Ii=Math.random()),Ci(Ii)}self.onerror=e=>{console.error(e),Mi({type:"unhandledError",error:{message:e.error.message||"Uncaught exception in worker"}})},self.addEventListener("unhandledrejection",(e=>{console.error(e),Mi({type:"unhandledError",error:{message:e.reason.message||"Uncaught rejection in worker"}})}));const Ai=new Map;function Si(e){Mi({type:"update",update:e})}function Mi(e,t){t?postMessage(e,[t]):postMessage(e)}onmessage=async e=>{const{data:t}=e;switch(t.type){case"initApi":await bi(Si,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];Mi({type:"methodCallback",messageId:e,callbackArgs:t},n instanceof ArrayBuffer?n:void 0)};Ai.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&&Mi({type:"methodResponse",messageId:e,response:t},i)}catch(t){e&&Mi({type:"methodResponse",messageId:e,error:{message:t.message}})}e&&Ai.delete(e);break}case"cancelProgress":{const e=Ai.get(t.messageId);e&&(e.isCanceled=!0);break}case"ping":Mi({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 D=U.multiply(C),T=k.add(D),B=l(E,T,g),[x,V,N,F,L]=await Promise.all([c(h(B)),c(I),c(v),c(n.salt1),c(n.salt2)]),O=await c(s.concat([_(V,N),F,L,R,P,x]));return new i.InputCheckPasswordSRP({srpId:e.srpId,A:s.from(R),M1:O})},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),A=r?r+1-m:void 0;return d.concat(P,A)}},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),A=l.concat([C,P]),S=l.from(A).reverse();let M;for(let e=0;e<20;e++){const e=h.generateRandomBytes(32),n=await h.sha256(l.concat([e,A])),s=l.concat([S,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),D=E.decryptIge(k.encryptedAnswer),T=new m(D);T.read(20);const B=T.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),L=h.modExp(u(B.g),F,x),O=h.modExp(V,F,x),q=new(a().ClientDHInnerData)({nonce:o.nonce,serverNonce:o.serverNonce,retryId:u.zero,gB:h.getByteArray(L,!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(O));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{RPCError:s}=n(7873),a=n(5585),i=n(9109),o=n(9618),r=n(3302),{doAuthentication:c}=n(9870),d=n(2301),l=n(3254),u=n(8963),g=n(4287),{MsgsAck:p,upload:f,MsgsStateInfo:h,Pong:m}=n(7404).constructors,_=n(6411),y=n(5544),{UpdateConnectionState:b,UpdateServerTimeOffset:w}=n(8415),{BadMessageError:C}=n(8187),{BadServerSalt:I,BadMsgNotification:v,MsgDetailedInfo:P,MsgNewDetailedInfo:A,NewSessionCreated:S,FutureSalts:M,MsgsStateReq:k,MsgResendReq:R,MsgsAllInfo:U}=n(7404).constructors,{SecurityError:E}=n(8187),{InvalidBufferError:D}=n(8187),{LogOut:T}=n(7404).requests.auth,{RPCMessageToError:B}=n(7873),{TypeNotFoundError:x}=n(8187);class V{constructor(e,t){const n={...V.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 r,this._state=new i(this.authKey,this._log),this._send_queue=new _(this._state,this._log),this._pending_state={},this._pending_ack=new Set,this._last_acks=[],this._handlers={[d.CONSTRUCTOR_ID]:this._handleRPCResult.bind(this),[l.CONSTRUCTOR_ID]:this._handleContainer.bind(this),[u.CONSTRUCTOR_ID]:this._handleGzipPacked.bind(this),[m.CONSTRUCTOR_ID]:this._handlePong.bind(this),[I.CONSTRUCTOR_ID]:this._handleBadServerSalt.bind(this),[v.CONSTRUCTOR_ID]:this._handleBadNotification.bind(this),[P.CONSTRUCTOR_ID]:this._handleDetailedInfo.bind(this),[A.CONSTRUCTOR_ID]:this._handleNewDetailedInfo.bind(this),[S.CONSTRUCTOR_ID]:this._handleNewSessionCreated.bind(this),[p.CONSTRUCTOR_ID]:this._handleAck.bind(this),[M.CONSTRUCTOR_ID]:this._handleFutureSalts.bind(this),[k.CONSTRUCTOR_ID]:this._handleStateForgotten.bind(this),[R.CONSTRUCTOR_ID]:this._handleStateForgotten.bind(this),[U.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 x){this._log.info(`Type ${e.invalidConstructorId} not found, remaining data ${e.remaining}`);continue}if(e instanceof E){this._log.warn(`Security error while unpacking a received message: ${e}`);continue}return e instanceof D?void(404===e.code?this._handleBadAuthKey():(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){e instanceof s?"AUTH_KEY_UNREGISTERED"===e.message&&this._handleBadAuthKey(!0):(this._log.error("Unhandled error while receiving data"),this._log.error(e))}}}_handleBadAuthKey(e){e&&this._isMainSender||(this._log.warn(`Broken authorization key for dc ${this._dcId}, resetting...`),this._isMainSender&&this._updateCallback?this._updateCallback(new b(b.broken)):!this._isMainSender&&this._onConnectionBreak&&this._onConnectionBreak(this._dcId))}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 y(t.body).tgReadObject()instanceof f.File))throw new x("Not an upload.File")}catch(e){if(this._log.error(e),e instanceof x)return void this._log.info(`Received response without parent request: ${t.body}`);throw e}if(t.error){const e=B(t.error,n.request);throw this._send_queue.append(new g(new p({msgIds:[n.msgId]}))),n.reject(e),e}try{const e=new y(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 y(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 w(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 w(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 C(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 g(new h(e.msgId,String.fromCharCode(1).repeat(e.obj.msgIds))))}_handleMsgAll(e){}reconnect(){this._user_connected&&!this._reconnecting&&(this._reconnecting=!0,o.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 N,F,L;L={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},(F="DEFAULT_OPTIONS")in(N=V)?Object.defineProperty(N,F,{value:L,enumerable:!0,configurable:!0,writable:!0}):N[F]=L,e.exports=V},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.msgIds=[],this.reset()}reset(){this.id=i.generateRandomLong(!0),this._sequence=0,this._lastMsgId=a(0),this.msgIds=[]}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();if(this.msgIds.includes(p.toString()))throw new l("Duplicate msgIds");this.msgIds.length>500&&this.msgIds.shift(),this.msgIds.push(p.toString());const 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:136,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 noforwards:flags.25?true id:long title:string photo:ChatPhoto participants_count:int date:int version:int migrated_to:flags.6?InputChannel admin_rights:flags.14?ChatAdminRights default_banned_rights:flags.18?ChatBannedRights = Chat;\nchatForbidden#6592a1a7 id:long title:string = Chat;\nchannel#8261ac61 flags:# creator:flags.0?true left:flags.2?true broadcast:flags.5?true verified:flags.7?true megagroup:flags.8?true restricted:flags.9?true signatures:flags.11?true min:flags.12?true scam:flags.19?true has_link:flags.20?true has_geo:flags.21?true slowmode_enabled:flags.22?true call_active:flags.23?true call_not_empty:flags.24?true fake:flags.25?true gigagroup:flags.26?true noforwards:flags.27?true id:long access_hash:flags.13?long title:string username:flags.6?string photo:ChatPhoto date:int restriction_reason:flags.9?Vector admin_rights:flags.14?ChatAdminRights banned_rights:flags.15?ChatBannedRights default_banned_rights:flags.18?ChatBannedRights participants_count:flags.17?int = Chat;\nchannelForbidden#17d493d5 flags:# broadcast:flags.5?true megagroup:flags.8?true id:long access_hash:long title:string until_date:flags.16?int = Chat;\nchatFull#d18ee226 flags:# can_set_username:flags.7?true has_scheduled:flags.8?true id:long about:string participants:ChatParticipants chat_photo:flags.2?Photo notify_settings:PeerNotifySettings exported_invite:flags.13?ExportedChatInvite bot_info:flags.3?Vector pinned_msg_id:flags.6?int folder_id:flags.11?int call:flags.12?InputGroupCall ttl_period:flags.14?int groupcall_default_join_as:flags.15?Peer theme_emoticon:flags.16?string requests_pending:flags.17?int recent_requesters:flags.17?Vector available_reactions:flags.18?Vector = ChatFull;\nchannelFull#e13c3d20 flags:# can_view_participants:flags.3?true can_set_username:flags.6?true can_set_stickers:flags.7?true hidden_prehistory:flags.10?true can_set_location:flags.16?true has_scheduled:flags.19?true can_view_stats:flags.20?true blocked:flags.22?true id:long about:string participants_count:flags.0?int admins_count:flags.1?int kicked_count:flags.2?int banned_count:flags.2?int online_count:flags.13?int read_inbox_max_id:int read_outbox_max_id:int unread_count:int chat_photo:Photo notify_settings:PeerNotifySettings exported_invite:flags.23?ExportedChatInvite bot_info:Vector migrated_from_chat_id:flags.4?long migrated_from_max_id:flags.4?int pinned_msg_id:flags.5?int stickerset:flags.8?StickerSet available_min_id:flags.9?int folder_id:flags.11?int linked_chat_id:flags.14?long location:flags.15?ChannelLocation slowmode_seconds:flags.17?int slowmode_next_send_date:flags.18?int stats_dc:flags.12?int pts:int call:flags.21?InputGroupCall ttl_period:flags.24?int pending_suggestions:flags.25?Vector groupcall_default_join_as:flags.26?Peer theme_emoticon:flags.27?string requests_pending:flags.28?int recent_requesters:flags.28?Vector default_send_as:flags.29?Peer available_reactions:flags.30?Vector = ChatFull;\nchatParticipant#c02d4007 user_id:long inviter_id:long date:int = ChatParticipant;\nchatParticipantCreator#e46bcee4 user_id:long = ChatParticipant;\nchatParticipantAdmin#a0933f5b user_id:long inviter_id:long date:int = ChatParticipant;\nchatParticipantsForbidden#8763d3e1 flags:# chat_id:long self_participant:flags.0?ChatParticipant = ChatParticipants;\nchatParticipants#3cbc93f8 chat_id:long participants:Vector version:int = ChatParticipants;\nchatPhotoEmpty#37c1011c = ChatPhoto;\nchatPhoto#1c6e1c11 flags:# has_video:flags.0?true photo_id:long stripped_thumb:flags.1?bytes dc_id:int = ChatPhoto;\nmessageEmpty#90a6ca84 flags:# id:int peer_id:flags.0?Peer = Message;\nmessage#38116ee0 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true post:flags.14?true from_scheduled:flags.18?true legacy:flags.19?true edit_hide:flags.21?true pinned:flags.24?true noforwards:flags.26?true id:int from_id:flags.8?Peer peer_id:Peer fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?long reply_to:flags.3?MessageReplyHeader date:int message:string media:flags.9?MessageMedia reply_markup:flags.6?ReplyMarkup entities:flags.7?Vector views:flags.10?int forwards:flags.10?int replies:flags.23?MessageReplies edit_date:flags.15?int post_author:flags.16?string grouped_id:flags.17?long reactions:flags.20?MessageReactions restriction_reason:flags.22?Vector ttl_period:flags.25?int = Message;\nmessageService#2b085862 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true post:flags.14?true legacy:flags.19?true id:int from_id:flags.8?Peer peer_id:Peer reply_to:flags.3?MessageReplyHeader date:int action:MessageAction ttl_period:flags.25?int = Message;\nmessageMediaEmpty#3ded6320 = MessageMedia;\nmessageMediaPhoto#695150d7 flags:# photo:flags.0?Photo ttl_seconds:flags.2?int = MessageMedia;\nmessageMediaGeo#56e0d474 geo:GeoPoint = MessageMedia;\nmessageMediaContact#70322949 phone_number:string first_name:string last_name:string vcard:string user_id:long = MessageMedia;\nmessageMediaUnsupported#9f84f49e = MessageMedia;\nmessageMediaDocument#9cb070d7 flags:# document:flags.0?Document ttl_seconds:flags.2?int = MessageMedia;\nmessageMediaWebPage#a32dd600 webpage:WebPage = MessageMedia;\nmessageMediaVenue#2ec0533f geo:GeoPoint title:string address:string provider:string venue_id:string venue_type:string = MessageMedia;\nmessageMediaGame#fdb19008 game:Game = MessageMedia;\nmessageMediaInvoice#84551347 flags:# shipping_address_requested:flags.1?true test:flags.3?true title:string description:string photo:flags.0?WebDocument receipt_msg_id:flags.2?int currency:string total_amount:long start_param:string = MessageMedia;\nmessageMediaGeoLive#b940c666 flags:# geo:GeoPoint heading:flags.0?int period:int proximity_notification_radius:flags.1?int = MessageMedia;\nmessageMediaPoll#4bd6e798 poll:Poll results:PollResults = MessageMedia;\nmessageMediaDice#3f7ee58b value:int emoticon:string = MessageMedia;\nmessageActionEmpty#b6aef7b0 = MessageAction;\nmessageActionChatCreate#bd47cbad title:string users:Vector = MessageAction;\nmessageActionChatEditTitle#b5a1ce5a title:string = MessageAction;\nmessageActionChatEditPhoto#7fcb13a8 photo:Photo = MessageAction;\nmessageActionChatDeletePhoto#95e3fbef = MessageAction;\nmessageActionChatAddUser#15cefd00 users:Vector = MessageAction;\nmessageActionChatDeleteUser#a43f30cc user_id:long = MessageAction;\nmessageActionChatJoinedByLink#31224c3 inviter_id:long = MessageAction;\nmessageActionChannelCreate#95d2ac92 title:string = MessageAction;\nmessageActionChatMigrateTo#e1037f92 channel_id:long = MessageAction;\nmessageActionChannelMigrateFrom#ea3948e9 title:string chat_id:long = MessageAction;\nmessageActionPinMessage#94bd38ed = MessageAction;\nmessageActionHistoryClear#9fbab604 = MessageAction;\nmessageActionGameScore#92a72876 game_id:long score:int = MessageAction;\nmessageActionPaymentSentMe#8f31b327 flags:# currency:string total_amount:long payload:bytes info:flags.0?PaymentRequestedInfo shipping_option_id:flags.1?string charge:PaymentCharge = MessageAction;\nmessageActionPaymentSent#40699cd0 currency:string total_amount:long = MessageAction;\nmessageActionPhoneCall#80e11a7f flags:# video:flags.2?true call_id:long reason:flags.0?PhoneCallDiscardReason duration:flags.1?int = MessageAction;\nmessageActionScreenshotTaken#4792929b = MessageAction;\nmessageActionCustomAction#fae69f56 message:string = MessageAction;\nmessageActionBotAllowed#abe9affe domain:string = MessageAction;\nmessageActionSecureValuesSentMe#1b287353 values:Vector credentials:SecureCredentialsEncrypted = MessageAction;\nmessageActionSecureValuesSent#d95c6154 types:Vector = MessageAction;\nmessageActionContactSignUp#f3f25f76 = MessageAction;\nmessageActionGeoProximityReached#98e0d697 from_id:Peer to_id:Peer distance:int = MessageAction;\nmessageActionGroupCall#7a0d7f42 flags:# call:InputGroupCall duration:flags.0?int = MessageAction;\nmessageActionInviteToGroupCall#502f92f7 call:InputGroupCall users:Vector = MessageAction;\nmessageActionSetMessagesTTL#aa1afbfd period:int = MessageAction;\nmessageActionGroupCallScheduled#b3a07661 call:InputGroupCall schedule_date:int = MessageAction;\nmessageActionSetChatTheme#aa786345 emoticon:string = MessageAction;\nmessageActionChatJoinedByRequest#ebbca3cb = MessageAction;\ndialog#2c171f72 flags:# pinned:flags.2?true unread_mark:flags.3?true peer:Peer top_message:int read_inbox_max_id:int read_outbox_max_id:int unread_count:int unread_mentions_count:int notify_settings:PeerNotifySettings pts:flags.0?int draft:flags.1?DraftMessage folder_id:flags.4?int = Dialog;\ndialogFolder#71bd134c flags:# pinned:flags.2?true folder:Folder peer:Peer top_message:int unread_muted_peers_count:int unread_unmuted_peers_count:int unread_muted_messages_count:int unread_unmuted_messages_count:int = Dialog;\nphotoEmpty#2331b22d id:long = Photo;\nphoto#fb197a65 flags:# has_stickers:flags.0?true id:long access_hash:long file_reference:bytes date:int sizes:Vector video_sizes:flags.1?Vector dc_id:int = Photo;\nphotoSizeEmpty#e17e23c type:string = PhotoSize;\nphotoSize#75c78e60 type:string w:int h:int size:int = PhotoSize;\nphotoCachedSize#21e1ad6 type:string w:int h:int bytes:bytes = PhotoSize;\nphotoStrippedSize#e0b0bc2e type:string bytes:bytes = PhotoSize;\nphotoSizeProgressive#fa3efb95 type:string w:int h:int sizes:Vector = PhotoSize;\nphotoPathSize#d8214d41 type:string bytes:bytes = PhotoSize;\ngeoPointEmpty#1117dd5f = GeoPoint;\ngeoPoint#b2a2f663 flags:# long:double lat:double access_hash:long accuracy_radius:flags.0?int = GeoPoint;\nauth.sentCode#5e002502 flags:# type:auth.SentCodeType phone_code_hash:string next_type:flags.1?auth.CodeType timeout:flags.2?int = auth.SentCode;\nauth.authorization#33fb7bb8 flags:# setup_password_required:flags.1?true otherwise_relogin_days:flags.1?int tmp_sessions:flags.0?int user:User = auth.Authorization;\nauth.authorizationSignUpRequired#44747e9a flags:# terms_of_service:flags.0?help.TermsOfService = auth.Authorization;\nauth.exportedAuthorization#b434e2b8 id:long bytes:bytes = auth.ExportedAuthorization;\ninputNotifyPeer#b8bc5b0c peer:InputPeer = InputNotifyPeer;\ninputNotifyUsers#193b4417 = InputNotifyPeer;\ninputNotifyChats#4a95e84e = InputNotifyPeer;\ninputNotifyBroadcasts#b1db7c7e = InputNotifyPeer;\ninputPeerNotifySettings#9c3d198e flags:# show_previews:flags.0?Bool silent:flags.1?Bool mute_until:flags.2?int sound:flags.3?string = InputPeerNotifySettings;\npeerNotifySettings#af509d20 flags:# show_previews:flags.0?Bool silent:flags.1?Bool mute_until:flags.2?int sound:flags.3?string = PeerNotifySettings;\npeerSettings#a518110d flags:# report_spam:flags.0?true add_contact:flags.1?true block_contact:flags.2?true share_contact:flags.3?true need_contacts_exception:flags.4?true report_geo:flags.5?true autoarchived:flags.7?true invite_members:flags.8?true request_chat_broadcast:flags.10?true geo_distance:flags.6?int request_chat_title:flags.9?string request_chat_date:flags.9?int = PeerSettings;\nwallPaper#a437c3ed id:long flags:# creator:flags.0?true default:flags.1?true pattern:flags.3?true dark:flags.4?true access_hash:long slug:string document:Document settings:flags.2?WallPaperSettings = WallPaper;\nwallPaperNoFile#e0804116 id:long flags:# default:flags.1?true dark:flags.4?true settings:flags.2?WallPaperSettings = WallPaper;\ninputReportReasonSpam#58dbcab8 = ReportReason;\ninputReportReasonViolence#1e22c78d = ReportReason;\ninputReportReasonPornography#2e59d922 = ReportReason;\ninputReportReasonChildAbuse#adf44ee3 = ReportReason;\ninputReportReasonOther#c1e4a2b1 = ReportReason;\ninputReportReasonCopyright#9b89f93a = ReportReason;\ninputReportReasonGeoIrrelevant#dbd4feed = ReportReason;\ninputReportReasonFake#f5ddd6e7 = ReportReason;\nuserFull#cf366521 flags:# blocked:flags.0?true phone_calls_available:flags.4?true phone_calls_private:flags.5?true can_pin_message:flags.7?true has_scheduled:flags.12?true video_calls_available:flags.13?true id:long about:flags.1?string settings:PeerSettings profile_photo:flags.2?Photo notify_settings:PeerNotifySettings bot_info:flags.3?BotInfo pinned_msg_id:flags.6?int common_chats_count:int folder_id:flags.11?int ttl_period:flags.14?int theme_emoticon:flags.15?string private_forward_name:flags.16?string = UserFull;\ncontact#145ade0b user_id:long mutual:Bool = Contact;\nimportedContact#c13e3c50 user_id:long client_id:long = ImportedContact;\ncontactStatus#16d9703b user_id:long status:UserStatus = ContactStatus;\ncontacts.contactsNotModified#b74ba9d2 = contacts.Contacts;\ncontacts.contacts#eae87e42 contacts:Vector saved_count:int users:Vector = contacts.Contacts;\ncontacts.importedContacts#77d01c3b imported:Vector popular_invites:Vector retry_contacts:Vector users:Vector = contacts.ImportedContacts;\ncontacts.blocked#ade1591 blocked:Vector chats:Vector users:Vector = contacts.Blocked;\ncontacts.blockedSlice#e1664194 count:int blocked:Vector chats:Vector users:Vector = contacts.Blocked;\nmessages.dialogs#15ba6c40 dialogs:Vector messages:Vector chats:Vector users:Vector = messages.Dialogs;\nmessages.dialogsSlice#71e094f3 count:int dialogs:Vector messages:Vector chats:Vector users:Vector = messages.Dialogs;\nmessages.dialogsNotModified#f0e3e596 count:int = messages.Dialogs;\nmessages.messages#8c718e87 messages:Vector chats:Vector users:Vector = messages.Messages;\nmessages.messagesSlice#3a54685e flags:# inexact:flags.1?true count:int next_rate:flags.0?int offset_id_offset:flags.2?int messages:Vector chats:Vector users:Vector = messages.Messages;\nmessages.channelMessages#64479808 flags:# inexact:flags.1?true pts:int count:int offset_id_offset:flags.2?int messages:Vector chats:Vector users:Vector = messages.Messages;\nmessages.messagesNotModified#74535f21 count:int = messages.Messages;\nmessages.chats#64ff9fd5 chats:Vector = messages.Chats;\nmessages.chatsSlice#9cd81144 count:int chats:Vector = messages.Chats;\nmessages.chatFull#e5d7d19c full_chat:ChatFull chats:Vector users:Vector = messages.ChatFull;\nmessages.affectedHistory#b45c69d1 pts:int pts_count:int offset:int = messages.AffectedHistory;\ninputMessagesFilterEmpty#57e2f66c = MessagesFilter;\ninputMessagesFilterPhotos#9609a51c = MessagesFilter;\ninputMessagesFilterVideo#9fc00e65 = MessagesFilter;\ninputMessagesFilterPhotoVideo#56e9f0e4 = MessagesFilter;\ninputMessagesFilterDocument#9eddf188 = MessagesFilter;\ninputMessagesFilterUrl#7ef0dd87 = MessagesFilter;\ninputMessagesFilterGif#ffc86587 = MessagesFilter;\ninputMessagesFilterVoice#50f5c392 = MessagesFilter;\ninputMessagesFilterMusic#3751b49e = MessagesFilter;\ninputMessagesFilterChatPhotos#3a20ecb8 = MessagesFilter;\ninputMessagesFilterPhoneCalls#80c99768 flags:# missed:flags.0?true = MessagesFilter;\ninputMessagesFilterRoundVoice#7a7c17a4 = MessagesFilter;\ninputMessagesFilterRoundVideo#b549da53 = MessagesFilter;\ninputMessagesFilterMyMentions#c1f8e69a = MessagesFilter;\ninputMessagesFilterGeo#e7026d0d = MessagesFilter;\ninputMessagesFilterContacts#e062db83 = MessagesFilter;\ninputMessagesFilterPinned#1bb00451 = MessagesFilter;\nupdateNewMessage#1f2b0afd message:Message pts:int pts_count:int = Update;\nupdateMessageID#4e90bfd6 id:int random_id:long = Update;\nupdateDeleteMessages#a20db0e5 messages:Vector pts:int pts_count:int = Update;\nupdateUserTyping#c01e857f user_id:long action:SendMessageAction = Update;\nupdateChatUserTyping#83487af0 chat_id:long from_id:Peer action:SendMessageAction = Update;\nupdateChatParticipants#7761198 participants:ChatParticipants = Update;\nupdateUserStatus#e5bdf8de user_id:long status:UserStatus = Update;\nupdateUserName#c3f202e0 user_id:long first_name:string last_name:string username:string = Update;\nupdateUserPhoto#f227868c user_id:long date:int photo:UserProfilePhoto previous:Bool = Update;\nupdateNewEncryptedMessage#12bcbd9a message:EncryptedMessage qts:int = Update;\nupdateEncryptedChatTyping#1710f156 chat_id:int = Update;\nupdateEncryption#b4a2e88d chat:EncryptedChat date:int = Update;\nupdateEncryptedMessagesRead#38fe25b7 chat_id:int max_date:int date:int = Update;\nupdateChatParticipantAdd#3dda5451 chat_id:long user_id:long inviter_id:long date:int version:int = Update;\nupdateChatParticipantDelete#e32f3d77 chat_id:long user_id:long version:int = Update;\nupdateDcOptions#8e5e9873 dc_options:Vector = Update;\nupdateNotifySettings#bec268ef peer:NotifyPeer notify_settings:PeerNotifySettings = Update;\nupdateServiceNotification#ebe46819 flags:# popup:flags.0?true inbox_date:flags.1?int type:string message:string media:MessageMedia entities:Vector = Update;\nupdatePrivacy#ee3b272a key:PrivacyKey rules:Vector = Update;\nupdateUserPhone#5492a13 user_id:long phone:string = Update;\nupdateReadHistoryInbox#9c974fdf flags:# folder_id:flags.0?int peer:Peer max_id:int still_unread_count:int pts:int pts_count:int = Update;\nupdateReadHistoryOutbox#2f2f21bf peer:Peer max_id:int pts:int pts_count:int = Update;\nupdateWebPage#7f891213 webpage:WebPage pts:int pts_count:int = Update;\nupdateReadMessagesContents#68c13933 messages:Vector pts:int pts_count:int = Update;\nupdateChannelTooLong#108d941f flags:# channel_id:long pts:flags.0?int = Update;\nupdateChannel#635b4c09 channel_id:long = Update;\nupdateNewChannelMessage#62ba04d9 message:Message pts:int pts_count:int = Update;\nupdateReadChannelInbox#922e6e10 flags:# folder_id:flags.0?int channel_id:long max_id:int still_unread_count:int pts:int = Update;\nupdateDeleteChannelMessages#c32d5b12 channel_id:long messages:Vector pts:int pts_count:int = Update;\nupdateChannelMessageViews#f226ac08 channel_id:long id:int views:int = Update;\nupdateChatParticipantAdmin#d7ca61a2 chat_id:long user_id:long is_admin:Bool version:int = Update;\nupdateNewStickerSet#688a30aa stickerset:messages.StickerSet = Update;\nupdateStickerSetsOrder#bb2d201 flags:# masks:flags.0?true order:Vector = Update;\nupdateStickerSets#43ae3dec = Update;\nupdateSavedGifs#9375341e = Update;\nupdateBotInlineQuery#496f379c flags:# query_id:long user_id:long query:string geo:flags.0?GeoPoint peer_type:flags.1?InlineQueryPeerType offset:string = Update;\nupdateBotInlineSend#12f12a07 flags:# user_id:long query:string geo:flags.0?GeoPoint id:string msg_id:flags.1?InputBotInlineMessageID = Update;\nupdateEditChannelMessage#1b3f4df7 message:Message pts:int pts_count:int = Update;\nupdateBotCallbackQuery#b9cfc48d flags:# query_id:long user_id:long peer:Peer msg_id:int chat_instance:long data:flags.0?bytes game_short_name:flags.1?string = Update;\nupdateEditMessage#e40370a3 message:Message pts:int pts_count:int = Update;\nupdateInlineBotCallbackQuery#691e9052 flags:# query_id:long user_id:long msg_id:InputBotInlineMessageID chat_instance:long data:flags.0?bytes game_short_name:flags.1?string = Update;\nupdateReadChannelOutbox#b75f99a9 channel_id:long max_id:int = Update;\nupdateDraftMessage#ee2bb969 peer:Peer draft:DraftMessage = Update;\nupdateReadFeaturedStickers#571d2742 = Update;\nupdateRecentStickers#9a422c20 = Update;\nupdateConfig#a229dd06 = Update;\nupdatePtsChanged#3354678f = Update;\nupdateChannelWebPage#2f2ba99f channel_id:long webpage:WebPage pts:int pts_count:int = Update;\nupdateDialogPinned#6e6fe51c flags:# pinned:flags.0?true folder_id:flags.1?int peer:DialogPeer = Update;\nupdatePinnedDialogs#fa0f3ca2 flags:# folder_id:flags.1?int order:flags.0?Vector = Update;\nupdateBotWebhookJSON#8317c0c3 data:DataJSON = Update;\nupdateBotWebhookJSONQuery#9b9240a6 query_id:long data:DataJSON timeout:int = Update;\nupdateBotShippingQuery#b5aefd7d query_id:long user_id:long payload:bytes shipping_address:PostAddress = Update;\nupdateBotPrecheckoutQuery#8caa9a96 flags:# query_id:long user_id:long payload:bytes info:flags.0?PaymentRequestedInfo shipping_option_id:flags.1?string currency:string total_amount:long = Update;\nupdatePhoneCall#ab0f6b1e phone_call:PhoneCall = Update;\nupdateLangPackTooLong#46560264 lang_code:string = Update;\nupdateLangPack#56022f4d difference:LangPackDifference = Update;\nupdateFavedStickers#e511996d = Update;\nupdateChannelReadMessagesContents#44bdd535 channel_id:long messages:Vector = Update;\nupdateContactsReset#7084a7be = Update;\nupdateChannelAvailableMessages#b23fc698 channel_id:long available_min_id:int = Update;\nupdateDialogUnreadMark#e16459c3 flags:# unread:flags.0?true peer:DialogPeer = Update;\nupdateMessagePoll#aca1657b flags:# poll_id:long poll:flags.0?Poll results:PollResults = Update;\nupdateChatDefaultBannedRights#54c01850 peer:Peer default_banned_rights:ChatBannedRights version:int = Update;\nupdateFolderPeers#19360dc0 folder_peers:Vector pts:int pts_count:int = Update;\nupdatePeerSettings#6a7e7366 peer:Peer settings:PeerSettings = Update;\nupdatePeerLocated#b4afcfb0 peers:Vector = Update;\nupdateNewScheduledMessage#39a51dfb message:Message = Update;\nupdateDeleteScheduledMessages#90866cee peer:Peer messages:Vector = Update;\nupdateTheme#8216fba3 theme:Theme = Update;\nupdateGeoLiveViewed#871fb939 peer:Peer msg_id:int = Update;\nupdateLoginToken#564fe691 = Update;\nupdateMessagePollVote#106395c9 poll_id:long user_id:long options:Vector qts:int = Update;\nupdateDialogFilter#26ffde7d flags:# id:int filter:flags.0?DialogFilter = Update;\nupdateDialogFilterOrder#a5d72105 order:Vector = Update;\nupdateDialogFilters#3504914f = Update;\nupdatePhoneCallSignalingData#2661bf09 phone_call_id:long data:bytes = Update;\nupdateChannelMessageForwards#d29a27f4 channel_id:long id:int forwards:int = Update;\nupdateReadChannelDiscussionInbox#d6b19546 flags:# channel_id:long top_msg_id:int read_max_id:int broadcast_id:flags.0?long broadcast_post:flags.0?int = Update;\nupdateReadChannelDiscussionOutbox#695c9e7c channel_id:long top_msg_id:int read_max_id:int = Update;\nupdatePeerBlocked#246a4b22 peer_id:Peer blocked:Bool = Update;\nupdateChannelUserTyping#8c88c923 flags:# channel_id:long top_msg_id:flags.0?int from_id:Peer action:SendMessageAction = Update;\nupdatePinnedMessages#ed85eab5 flags:# pinned:flags.0?true peer:Peer messages:Vector pts:int pts_count:int = Update;\nupdatePinnedChannelMessages#5bb98608 flags:# pinned:flags.0?true channel_id:long messages:Vector pts:int pts_count:int = Update;\nupdateChat#f89a6a4e chat_id:long = Update;\nupdateGroupCallParticipants#f2ebdb4e call:InputGroupCall participants:Vector version:int = Update;\nupdateGroupCall#14b24500 chat_id:long call:GroupCall = Update;\nupdatePeerHistoryTTL#bb9bb9a5 flags:# peer:Peer ttl_period:flags.0?int = Update;\nupdateChatParticipant#d087663a flags:# chat_id:long date:int actor_id:long user_id:long prev_participant:flags.0?ChatParticipant new_participant:flags.1?ChatParticipant invite:flags.2?ExportedChatInvite qts:int = Update;\nupdateChannelParticipant#985d3abb flags:# channel_id:long date:int actor_id:long user_id:long prev_participant:flags.0?ChannelParticipant new_participant:flags.1?ChannelParticipant invite:flags.2?ExportedChatInvite qts:int = Update;\nupdateBotStopped#c4870a49 user_id:long date:int stopped:Bool qts:int = Update;\nupdateGroupCallConnection#b783982 flags:# presentation:flags.0?true params:DataJSON = Update;\nupdateBotCommands#4d712f2e peer:Peer bot_id:long commands:Vector = Update;\nupdatePendingJoinRequests#7063c3db peer:Peer requests_pending:int recent_requesters:Vector = Update;\nupdateBotChatInviteRequester#11dfa986 peer:Peer date:int user_id:long about:string invite:ExportedChatInvite qts:int = Update;\nupdateMessageReactions#154798c3 peer:Peer msg_id:int reactions:MessageReactions = Update;\nupdates.state#a56c2a3e pts:int qts:int date:int seq:int unread_count:int = updates.State;\nupdates.differenceEmpty#5d75a138 date:int seq:int = updates.Difference;\nupdates.difference#f49ca0 new_messages:Vector new_encrypted_messages:Vector other_updates:Vector chats:Vector users:Vector state:updates.State = updates.Difference;\nupdates.differenceSlice#a8fb1981 new_messages:Vector new_encrypted_messages:Vector other_updates:Vector chats:Vector users:Vector intermediate_state:updates.State = updates.Difference;\nupdates.differenceTooLong#4afe8f6d pts:int = updates.Difference;\nupdatesTooLong#e317af7e = Updates;\nupdateShortMessage#313bc7f8 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true id:int user_id:long message:string pts:int pts_count:int date:int fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?long reply_to:flags.3?MessageReplyHeader entities:flags.7?Vector ttl_period:flags.25?int = Updates;\nupdateShortChatMessage#4d6deea5 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true id:int from_id:long chat_id:long message:string pts:int pts_count:int date:int fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?long reply_to:flags.3?MessageReplyHeader entities:flags.7?Vector ttl_period:flags.25?int = Updates;\nupdateShort#78d4dec1 update:Update date:int = Updates;\nupdatesCombined#725b04c3 updates:Vector users:Vector chats:Vector date:int seq_start:int seq:int = Updates;\nupdates#74ae4240 updates:Vector users:Vector chats:Vector date:int seq:int = Updates;\nupdateShortSentMessage#9015e101 flags:# out:flags.1?true id:int pts:int pts_count:int date:int media:flags.9?MessageMedia entities:flags.7?Vector ttl_period:flags.25?int = Updates;\nphotos.photos#8dca6aa5 photos:Vector users:Vector = photos.Photos;\nphotos.photosSlice#15051f54 count:int photos:Vector users:Vector = photos.Photos;\nphotos.photo#20212ca8 photo:Photo users:Vector = photos.Photo;\nupload.file#96a18d5 type:storage.FileType mtime:int bytes:bytes = upload.File;\nupload.fileCdnRedirect#f18cda44 dc_id:int file_token:bytes encryption_key:bytes encryption_iv:bytes file_hashes:Vector = upload.File;\ndcOption#18b7a10d flags:# ipv6:flags.0?true media_only:flags.1?true tcpo_only:flags.2?true cdn:flags.3?true static:flags.4?true id:int ip_address:string port:int secret:flags.10?bytes = DcOption;\nconfig#330b4067 flags:# phonecalls_enabled:flags.1?true default_p2p_contacts:flags.3?true preload_featured_stickers:flags.4?true ignore_phone_entities:flags.5?true revoke_pm_inbox:flags.6?true blocked_mode:flags.8?true pfs_enabled:flags.13?true date:int expires:int test_mode:Bool this_dc:int dc_options:Vector dc_txt_domain_name:string chat_size_max:int megagroup_size_max:int forwarded_count_max:int online_update_period_ms:int offline_blur_timeout_ms:int offline_idle_timeout_ms:int online_cloud_timeout_ms:int notify_cloud_delay_ms:int notify_default_delay_ms:int push_chat_period_ms:int push_chat_limit:int saved_gifs_limit:int edit_time_limit:int revoke_time_limit:int revoke_pm_time_limit:int rating_e_decay:int stickers_recent_limit:int stickers_faved_limit:int channels_read_media_period:int tmp_sessions:flags.0?int pinned_dialogs_count_max:int pinned_infolder_count_max:int call_receive_timeout_ms:int call_ring_timeout_ms:int call_connect_timeout_ms:int call_packet_timeout_ms:int me_url_prefix:string autoupdate_url_prefix:flags.7?string gif_search_username:flags.9?string venue_search_username:flags.10?string img_search_username:flags.11?string static_maps_provider:flags.12?string caption_length_max:int message_length_max:int webfile_dc_id:int suggested_lang_code:flags.2?string lang_pack_version:flags.2?int base_lang_pack_version:flags.2?int = Config;\nnearestDc#8e1a1775 country:string this_dc:int nearest_dc:int = NearestDc;\nhelp.appUpdate#ccbbce30 flags:# can_not_skip:flags.0?true id:int version:string text:string entities:Vector document:flags.1?Document url:flags.2?string sticker:flags.3?Document = help.AppUpdate;\nhelp.noAppUpdate#c45a6536 = help.AppUpdate;\nhelp.inviteText#18cb9f78 message:string = help.InviteText;\nencryptedChatEmpty#ab7ec0a0 id:int = EncryptedChat;\nencryptedChatWaiting#66b25953 id:int access_hash:long date:int admin_id:long participant_id:long = EncryptedChat;\nencryptedChatRequested#48f1d94c flags:# folder_id:flags.0?int id:int access_hash:long date:int admin_id:long participant_id:long g_a:bytes = EncryptedChat;\nencryptedChat#61f0d4c7 id:int access_hash:long date:int admin_id:long participant_id:long g_a_or_b:bytes key_fingerprint:long = EncryptedChat;\nencryptedChatDiscarded#1e1c7c45 flags:# history_deleted:flags.0?true id:int = EncryptedChat;\ninputEncryptedChat#f141b5e1 chat_id:int access_hash:long = InputEncryptedChat;\nencryptedFileEmpty#c21f497e = EncryptedFile;\nencryptedFile#4a70994c id:long access_hash:long size:int dc_id:int key_fingerprint:int = EncryptedFile;\ninputEncryptedFileEmpty#1837c364 = InputEncryptedFile;\ninputEncryptedFileUploaded#64bd0306 id:long parts:int md5_checksum:string key_fingerprint:int = InputEncryptedFile;\ninputEncryptedFile#5a17b5e5 id:long access_hash:long = InputEncryptedFile;\ninputEncryptedFileBigUploaded#2dc173c8 id:long parts:int key_fingerprint:int = InputEncryptedFile;\nencryptedMessage#ed18c118 random_id:long chat_id:int date:int bytes:bytes file:EncryptedFile = EncryptedMessage;\nencryptedMessageService#23734b06 random_id:long chat_id:int date:int bytes:bytes = EncryptedMessage;\nmessages.dhConfigNotModified#c0e24635 random:bytes = messages.DhConfig;\nmessages.dhConfig#2c221edd g:int p:bytes version:int random:bytes = messages.DhConfig;\nmessages.sentEncryptedMessage#560f8935 date:int = messages.SentEncryptedMessage;\nmessages.sentEncryptedFile#9493ff32 date:int file:EncryptedFile = messages.SentEncryptedMessage;\ninputDocumentEmpty#72f0eaae = InputDocument;\ninputDocument#1abfb575 id:long access_hash:long file_reference:bytes = InputDocument;\ndocumentEmpty#36f8c871 id:long = Document;\ndocument#1e87342b flags:# id:long access_hash:long file_reference:bytes date:int mime_type:string size:int thumbs:flags.0?Vector video_thumbs:flags.1?Vector dc_id:int attributes:Vector = Document;\nhelp.support#17c6b5f6 phone_number:string user:User = help.Support;\nnotifyPeer#9fd40bd8 peer:Peer = NotifyPeer;\nnotifyUsers#b4c83b4c = NotifyPeer;\nnotifyChats#c007cec3 = NotifyPeer;\nnotifyBroadcasts#d612e8ef = NotifyPeer;\nsendMessageTypingAction#16bf744e = SendMessageAction;\nsendMessageCancelAction#fd5ec8f5 = SendMessageAction;\nsendMessageRecordVideoAction#a187d66f = SendMessageAction;\nsendMessageUploadVideoAction#e9763aec progress:int = SendMessageAction;\nsendMessageRecordAudioAction#d52f73f7 = SendMessageAction;\nsendMessageUploadAudioAction#f351d7ab progress:int = SendMessageAction;\nsendMessageUploadPhotoAction#d1d34a26 progress:int = SendMessageAction;\nsendMessageUploadDocumentAction#aa0cd9e4 progress:int = SendMessageAction;\nsendMessageGeoLocationAction#176f8ba1 = SendMessageAction;\nsendMessageChooseContactAction#628cbc6f = SendMessageAction;\nsendMessageGamePlayAction#dd6a8f48 = SendMessageAction;\nsendMessageRecordRoundAction#88f27fbc = SendMessageAction;\nsendMessageUploadRoundAction#243e1c66 progress:int = SendMessageAction;\nspeakingInGroupCallAction#d92c2285 = SendMessageAction;\nsendMessageHistoryImportAction#dbda9246 progress:int = SendMessageAction;\nsendMessageChooseStickerAction#b05ac6b1 = SendMessageAction;\nsendMessageEmojiInteraction#25972bcb emoticon:string msg_id:int interaction:DataJSON = SendMessageAction;\nsendMessageEmojiInteractionSeen#b665902e emoticon:string = SendMessageAction;\ncontacts.found#b3134d9d my_results:Vector results:Vector chats:Vector users:Vector = contacts.Found;\ninputPrivacyKeyStatusTimestamp#4f96cb18 = InputPrivacyKey;\ninputPrivacyKeyChatInvite#bdfb0426 = InputPrivacyKey;\ninputPrivacyKeyPhoneCall#fabadc5f = InputPrivacyKey;\ninputPrivacyKeyPhoneP2P#db9e70d2 = InputPrivacyKey;\ninputPrivacyKeyForwards#a4dd4c08 = InputPrivacyKey;\ninputPrivacyKeyProfilePhoto#5719bacc = InputPrivacyKey;\ninputPrivacyKeyPhoneNumber#352dafa = InputPrivacyKey;\ninputPrivacyKeyAddedByPhone#d1219bdd = InputPrivacyKey;\nprivacyKeyStatusTimestamp#bc2eab30 = PrivacyKey;\nprivacyKeyChatInvite#500e6dfa = PrivacyKey;\nprivacyKeyPhoneCall#3d662b7b = PrivacyKey;\nprivacyKeyPhoneP2P#39491cc8 = PrivacyKey;\nprivacyKeyForwards#69ec56a3 = PrivacyKey;\nprivacyKeyProfilePhoto#96151fed = PrivacyKey;\nprivacyKeyPhoneNumber#d19ae46d = PrivacyKey;\nprivacyKeyAddedByPhone#42ffd42b = PrivacyKey;\ninputPrivacyValueAllowContacts#d09e07b = InputPrivacyRule;\ninputPrivacyValueAllowAll#184b35ce = InputPrivacyRule;\ninputPrivacyValueAllowUsers#131cc67f users:Vector = InputPrivacyRule;\ninputPrivacyValueDisallowContacts#ba52007 = InputPrivacyRule;\ninputPrivacyValueDisallowAll#d66b66c9 = InputPrivacyRule;\ninputPrivacyValueDisallowUsers#90110467 users:Vector = InputPrivacyRule;\ninputPrivacyValueAllowChatParticipants#840649cf chats:Vector = InputPrivacyRule;\ninputPrivacyValueDisallowChatParticipants#e94f0f86 chats:Vector = InputPrivacyRule;\nprivacyValueAllowContacts#fffe1bac = PrivacyRule;\nprivacyValueAllowAll#65427b82 = PrivacyRule;\nprivacyValueAllowUsers#b8905fb2 users:Vector = PrivacyRule;\nprivacyValueDisallowContacts#f888fa1a = PrivacyRule;\nprivacyValueDisallowAll#8b73e763 = PrivacyRule;\nprivacyValueDisallowUsers#e4621141 users:Vector = PrivacyRule;\nprivacyValueAllowChatParticipants#6b134e8e chats:Vector = PrivacyRule;\nprivacyValueDisallowChatParticipants#41c87565 chats:Vector = PrivacyRule;\naccount.privacyRules#50a04e45 rules:Vector chats:Vector users:Vector = account.PrivacyRules;\naccountDaysTTL#b8d0afdf days:int = AccountDaysTTL;\ndocumentAttributeImageSize#6c37c15c w:int h:int = DocumentAttribute;\ndocumentAttributeAnimated#11b58939 = DocumentAttribute;\ndocumentAttributeSticker#6319d612 flags:# mask:flags.1?true alt:string stickerset:InputStickerSet mask_coords:flags.0?MaskCoords = DocumentAttribute;\ndocumentAttributeVideo#ef02ce6 flags:# round_message:flags.0?true supports_streaming:flags.1?true duration:int w:int h:int = DocumentAttribute;\ndocumentAttributeAudio#9852f9c6 flags:# voice:flags.10?true duration:int title:flags.0?string performer:flags.1?string waveform:flags.2?bytes = DocumentAttribute;\ndocumentAttributeFilename#15590068 file_name:string = DocumentAttribute;\ndocumentAttributeHasStickers#9801d2f7 = DocumentAttribute;\nmessages.stickersNotModified#f1749a22 = messages.Stickers;\nmessages.stickers#30a6ec7e hash:long stickers:Vector = messages.Stickers;\nstickerPack#12b299d4 emoticon:string documents:Vector = StickerPack;\nmessages.allStickersNotModified#e86602c3 = messages.AllStickers;\nmessages.allStickers#cdbbcebb hash:long sets:Vector = messages.AllStickers;\nmessages.affectedMessages#84d19185 pts:int pts_count:int = messages.AffectedMessages;\nwebPageEmpty#eb1477e8 id:long = WebPage;\nwebPagePending#c586da1c id:long date:int = WebPage;\nwebPage#e89c45b2 flags:# id:long url:string display_url:string hash:int type:flags.0?string site_name:flags.1?string title:flags.2?string description:flags.3?string photo:flags.4?Photo embed_url:flags.5?string embed_type:flags.5?string embed_width:flags.6?int embed_height:flags.6?int duration:flags.7?int author:flags.8?string document:flags.9?Document cached_page:flags.10?Page attributes:flags.12?Vector = WebPage;\nwebPageNotModified#7311ca11 flags:# cached_page_views:flags.0?int = WebPage;\nauthorization#ad01d61d flags:# current:flags.0?true official_app:flags.1?true password_pending:flags.2?true encrypted_requests_disabled:flags.3?true call_requests_disabled:flags.4?true hash:long device_model:string platform:string system_version:string api_id:int app_name:string app_version:string date_created:int date_active:int ip:string country:string region:string = Authorization;\naccount.authorizations#4bff8ea0 authorization_ttl_days:int authorizations:Vector = account.Authorizations;\naccount.password#185b184f flags:# has_recovery:flags.0?true has_secure_values:flags.1?true has_password:flags.2?true current_algo:flags.2?PasswordKdfAlgo srp_B:flags.2?bytes srp_id:flags.2?long hint:flags.3?string email_unconfirmed_pattern:flags.4?string new_algo:PasswordKdfAlgo new_secure_algo:SecurePasswordKdfAlgo secure_random:bytes pending_reset_date:flags.5?int = account.Password;\naccount.passwordSettings#9a5c33e5 flags:# email:flags.0?string secure_settings:flags.1?SecureSecretSettings = account.PasswordSettings;\naccount.passwordInputSettings#c23727c9 flags:# new_algo:flags.0?PasswordKdfAlgo new_password_hash:flags.0?bytes hint:flags.0?string email:flags.1?string new_secure_settings:flags.2?SecureSecretSettings = account.PasswordInputSettings;\nauth.passwordRecovery#137948a5 email_pattern:string = auth.PasswordRecovery;\nreceivedNotifyMessage#a384b779 id:int flags:int = ReceivedNotifyMessage;\nchatInviteExported#ab4a819 flags:# revoked:flags.0?true permanent:flags.5?true request_needed:flags.6?true link:string admin_id:long date:int start_date:flags.4?int expire_date:flags.1?int usage_limit:flags.2?int usage:flags.3?int requested:flags.7?int title:flags.8?string = ExportedChatInvite;\nchatInviteAlready#5a686d7c chat:Chat = ChatInvite;\nchatInvite#300c44c1 flags:# channel:flags.0?true broadcast:flags.1?true public:flags.2?true megagroup:flags.3?true request_needed:flags.6?true title:string about:flags.5?string photo:Photo participants_count:int participants:flags.4?Vector = ChatInvite;\nchatInvitePeek#61695cb0 chat:Chat expires:int = ChatInvite;\ninputStickerSetEmpty#ffb62b95 = InputStickerSet;\ninputStickerSetID#9de7a269 id:long access_hash:long = InputStickerSet;\ninputStickerSetShortName#861cc8a0 short_name:string = InputStickerSet;\ninputStickerSetAnimatedEmoji#28703c8 = InputStickerSet;\ninputStickerSetDice#e67f520e emoticon:string = InputStickerSet;\ninputStickerSetAnimatedEmojiAnimations#cde3739 = InputStickerSet;\nstickerSet#d7df217a flags:# archived:flags.1?true official:flags.2?true masks:flags.3?true animated:flags.5?true installed_date:flags.0?int id:long access_hash:long title:string short_name:string thumbs:flags.4?Vector thumb_dc_id:flags.4?int thumb_version:flags.4?int count:int hash:int = StickerSet;\nmessages.stickerSet#b60a24a6 set:StickerSet packs:Vector documents:Vector = messages.StickerSet;\nmessages.stickerSetNotModified#d3f924eb = messages.StickerSet;\nbotCommand#c27ac8c7 command:string description:string = BotCommand;\nbotInfo#1b74b335 user_id:long description:string commands:Vector = BotInfo;\nkeyboardButton#a2fa4880 text:string = KeyboardButton;\nkeyboardButtonUrl#258aff05 text:string url:string = KeyboardButton;\nkeyboardButtonCallback#35bbdb6b flags:# requires_password:flags.0?true text:string data:bytes = KeyboardButton;\nkeyboardButtonRequestPhone#b16a6c29 text:string = KeyboardButton;\nkeyboardButtonRequestGeoLocation#fc796b3f text:string = KeyboardButton;\nkeyboardButtonSwitchInline#568a748 flags:# same_peer:flags.0?true text:string query:string = KeyboardButton;\nkeyboardButtonGame#50f41ccf text:string = KeyboardButton;\nkeyboardButtonBuy#afd93fbb text:string = KeyboardButton;\nkeyboardButtonUrlAuth#10b78d29 flags:# text:string fwd_text:flags.0?string url:string button_id:int = KeyboardButton;\ninputKeyboardButtonUrlAuth#d02e7fd4 flags:# request_write_access:flags.0?true text:string fwd_text:flags.1?string url:string bot:InputUser = KeyboardButton;\nkeyboardButtonRequestPoll#bbc7515d flags:# quiz:flags.0?Bool text:string = KeyboardButton;\ninputKeyboardButtonUserProfile#e988037b text:string user_id:InputUser = KeyboardButton;\nkeyboardButtonUserProfile#308660c1 text:string user_id:long = KeyboardButton;\nkeyboardButtonRow#77608b83 buttons:Vector = KeyboardButtonRow;\nreplyKeyboardHide#a03e5b85 flags:# selective:flags.2?true = ReplyMarkup;\nreplyKeyboardForceReply#86b40b08 flags:# single_use:flags.1?true selective:flags.2?true placeholder:flags.3?string = ReplyMarkup;\nreplyKeyboardMarkup#85dd99d1 flags:# resize:flags.0?true single_use:flags.1?true selective:flags.2?true rows:Vector placeholder:flags.3?string = ReplyMarkup;\nreplyInlineMarkup#48a30254 rows:Vector = ReplyMarkup;\nmessageEntityUnknown#bb92ba95 offset:int length:int = MessageEntity;\nmessageEntityMention#fa04579d offset:int length:int = MessageEntity;\nmessageEntityHashtag#6f635b0d offset:int length:int = MessageEntity;\nmessageEntityBotCommand#6cef8ac7 offset:int length:int = MessageEntity;\nmessageEntityUrl#6ed02538 offset:int length:int = MessageEntity;\nmessageEntityEmail#64e475c2 offset:int length:int = MessageEntity;\nmessageEntityBold#bd610bc9 offset:int length:int = MessageEntity;\nmessageEntityItalic#826f8b60 offset:int length:int = MessageEntity;\nmessageEntityCode#28a20571 offset:int length:int = MessageEntity;\nmessageEntityPre#73924be0 offset:int length:int language:string = MessageEntity;\nmessageEntityTextUrl#76a6d327 offset:int length:int url:string = MessageEntity;\nmessageEntityMentionName#dc7b1140 offset:int length:int user_id:long = MessageEntity;\ninputMessageEntityMentionName#208e68c9 offset:int length:int user_id:InputUser = MessageEntity;\nmessageEntityPhone#9b69e34b offset:int length:int = MessageEntity;\nmessageEntityCashtag#4c4e743f offset:int length:int = MessageEntity;\nmessageEntityUnderline#9c4e7e8b offset:int length:int = MessageEntity;\nmessageEntityStrike#bf0693d4 offset:int length:int = MessageEntity;\nmessageEntityBlockquote#20df5d0 offset:int length:int = MessageEntity;\nmessageEntityBankCard#761e6af4 offset:int length:int = MessageEntity;\nmessageEntitySpoiler#32ca960f offset:int length:int = MessageEntity;\ninputChannelEmpty#ee8c1e86 = InputChannel;\ninputChannel#f35aec28 channel_id:long access_hash:long = InputChannel;\ninputChannelFromMessage#5b934f9d peer:InputPeer msg_id:int channel_id:long = InputChannel;\ncontacts.resolvedPeer#7f077ad9 peer:Peer chats:Vector users:Vector = contacts.ResolvedPeer;\nmessageRange#ae30253 min_id:int max_id:int = MessageRange;\nupdates.channelDifferenceEmpty#3e11affb flags:# final:flags.0?true pts:int timeout:flags.1?int = updates.ChannelDifference;\nupdates.channelDifferenceTooLong#a4bcc6fe flags:# final:flags.0?true timeout:flags.1?int dialog:Dialog messages:Vector chats:Vector users:Vector = updates.ChannelDifference;\nupdates.channelDifference#2064674e flags:# final:flags.0?true pts:int timeout:flags.1?int new_messages:Vector other_updates:Vector chats:Vector users:Vector = updates.ChannelDifference;\nchannelMessagesFilterEmpty#94d42ee7 = ChannelMessagesFilter;\nchannelMessagesFilter#cd77d957 flags:# exclude_new_messages:flags.1?true ranges:Vector = ChannelMessagesFilter;\nchannelParticipant#c00c07c0 user_id:long date:int = ChannelParticipant;\nchannelParticipantSelf#35a8bfa7 flags:# via_request:flags.0?true user_id:long inviter_id:long date:int = ChannelParticipant;\nchannelParticipantCreator#2fe601d3 flags:# user_id:long admin_rights:ChatAdminRights rank:flags.0?string = ChannelParticipant;\nchannelParticipantAdmin#34c3bb53 flags:# can_edit:flags.0?true self:flags.1?true user_id:long inviter_id:flags.1?long promoted_by:long date:int admin_rights:ChatAdminRights rank:flags.2?string = ChannelParticipant;\nchannelParticipantBanned#6df8014e flags:# left:flags.0?true peer:Peer kicked_by:long date:int banned_rights:ChatBannedRights = ChannelParticipant;\nchannelParticipantLeft#1b03f006 peer:Peer = ChannelParticipant;\nchannelParticipantsRecent#de3f3c79 = ChannelParticipantsFilter;\nchannelParticipantsAdmins#b4608969 = ChannelParticipantsFilter;\nchannelParticipantsKicked#a3b54985 q:string = ChannelParticipantsFilter;\nchannelParticipantsBots#b0d1865b = ChannelParticipantsFilter;\nchannelParticipantsBanned#1427a5e1 q:string = ChannelParticipantsFilter;\nchannelParticipantsSearch#656ac4b q:string = ChannelParticipantsFilter;\nchannelParticipantsContacts#bb6ae88d q:string = ChannelParticipantsFilter;\nchannelParticipantsMentions#e04b5ceb flags:# q:flags.0?string top_msg_id:flags.1?int = ChannelParticipantsFilter;\nchannels.channelParticipants#9ab0feaf count:int participants:Vector chats:Vector users:Vector = channels.ChannelParticipants;\nchannels.channelParticipantsNotModified#f0173fe9 = channels.ChannelParticipants;\nchannels.channelParticipant#dfb80317 participant:ChannelParticipant chats:Vector users:Vector = channels.ChannelParticipant;\nhelp.termsOfService#780a0310 flags:# popup:flags.0?true id:DataJSON text:string entities:Vector min_age_confirm:flags.1?int = help.TermsOfService;\nmessages.savedGifsNotModified#e8025ca2 = messages.SavedGifs;\nmessages.savedGifs#84a02a0d hash:long gifs:Vector = messages.SavedGifs;\ninputBotInlineMessageMediaAuto#3380c786 flags:# message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageText#3dcd7a87 flags:# no_webpage:flags.0?true message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaGeo#96929a85 flags:# geo_point:InputGeoPoint heading:flags.0?int period:flags.1?int proximity_notification_radius:flags.3?int reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaVenue#417bbf11 flags:# geo_point:InputGeoPoint title:string address:string provider:string venue_id:string venue_type:string reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaContact#a6edbffd flags:# phone_number:string first_name:string last_name:string vcard:string reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageGame#4b425864 flags:# reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaInvoice#d7e78225 flags:# title:string description:string photo:flags.0?InputWebDocument invoice:Invoice payload:bytes provider:string provider_data:DataJSON reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineResult#88bf9319 flags:# id:string type:string title:flags.1?string description:flags.2?string url:flags.3?string thumb:flags.4?InputWebDocument content:flags.5?InputWebDocument send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultPhoto#a8d864a7 id:string type:string photo:InputPhoto send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultDocument#fff8fdc4 flags:# id:string type:string title:flags.1?string description:flags.2?string document:InputDocument send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultGame#4fa417f2 id:string short_name:string send_message:InputBotInlineMessage = InputBotInlineResult;\nbotInlineMessageMediaAuto#764cf810 flags:# message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageText#8c7f65e2 flags:# no_webpage:flags.0?true message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaGeo#51846fd flags:# geo:GeoPoint heading:flags.0?int period:flags.1?int proximity_notification_radius:flags.3?int reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaVenue#8a86659c flags:# geo:GeoPoint title:string address:string provider:string venue_id:string venue_type:string reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaContact#18d1cdc2 flags:# phone_number:string first_name:string last_name:string vcard:string reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaInvoice#354a9b09 flags:# shipping_address_requested:flags.1?true test:flags.3?true title:string description:string photo:flags.0?WebDocument currency:string total_amount:long reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineResult#11965f3a flags:# id:string type:string title:flags.1?string description:flags.2?string url:flags.3?string thumb:flags.4?WebDocument content:flags.5?WebDocument send_message:BotInlineMessage = BotInlineResult;\nbotInlineMediaResult#17db940b flags:# id:string type:string photo:flags.0?Photo document:flags.1?Document title:flags.2?string description:flags.3?string send_message:BotInlineMessage = BotInlineResult;\nmessages.botResults#947ca848 flags:# gallery:flags.0?true query_id:long next_offset:flags.1?string switch_pm:flags.2?InlineBotSwitchPM results:Vector cache_time:int users:Vector = messages.BotResults;\nexportedMessageLink#5dab1af4 link:string html:string = ExportedMessageLink;\nmessageFwdHeader#5f777dce flags:# imported:flags.7?true from_id:flags.0?Peer from_name:flags.5?string date:int channel_post:flags.2?int post_author:flags.3?string saved_from_peer:flags.4?Peer saved_from_msg_id:flags.4?int psa_type:flags.6?string = MessageFwdHeader;\nauth.codeTypeSms#72a3158c = auth.CodeType;\nauth.codeTypeCall#741cd3e3 = auth.CodeType;\nauth.codeTypeFlashCall#226ccefb = auth.CodeType;\nauth.codeTypeMissedCall#d61ad6ee = auth.CodeType;\nauth.sentCodeTypeApp#3dbb5986 length:int = auth.SentCodeType;\nauth.sentCodeTypeSms#c000bba2 length:int = auth.SentCodeType;\nauth.sentCodeTypeCall#5353e5a7 length:int = auth.SentCodeType;\nauth.sentCodeTypeFlashCall#ab03c6d9 pattern:string = auth.SentCodeType;\nauth.sentCodeTypeMissedCall#82006484 prefix:string length:int = auth.SentCodeType;\nmessages.botCallbackAnswer#36585ea4 flags:# alert:flags.1?true has_url:flags.3?true native_ui:flags.4?true message:flags.0?string url:flags.2?string cache_time:int = messages.BotCallbackAnswer;\nmessages.messageEditData#26b5dde6 flags:# caption:flags.0?true = messages.MessageEditData;\ninputBotInlineMessageID#890c3d89 dc_id:int id:long access_hash:long = InputBotInlineMessageID;\ninputBotInlineMessageID64#b6d915d7 dc_id:int owner_id:long id:int access_hash:long = InputBotInlineMessageID;\ninlineBotSwitchPM#3c20629f text:string start_param:string = InlineBotSwitchPM;\nmessages.peerDialogs#3371c354 dialogs:Vector messages:Vector chats:Vector users:Vector state:updates.State = messages.PeerDialogs;\ntopPeer#edcdc05b peer:Peer rating:double = TopPeer;\ntopPeerCategoryBotsPM#ab661b5b = TopPeerCategory;\ntopPeerCategoryBotsInline#148677e2 = TopPeerCategory;\ntopPeerCategoryCorrespondents#637b7ed = TopPeerCategory;\ntopPeerCategoryGroups#bd17a14a = TopPeerCategory;\ntopPeerCategoryChannels#161d9628 = TopPeerCategory;\ntopPeerCategoryPhoneCalls#1e76a78c = TopPeerCategory;\ntopPeerCategoryForwardUsers#a8406ca9 = TopPeerCategory;\ntopPeerCategoryForwardChats#fbeec0f0 = TopPeerCategory;\ntopPeerCategoryPeers#fb834291 category:TopPeerCategory count:int peers:Vector = TopPeerCategoryPeers;\ncontacts.topPeersNotModified#de266ef5 = contacts.TopPeers;\ncontacts.topPeers#70b772a8 categories:Vector chats:Vector users:Vector = contacts.TopPeers;\ncontacts.topPeersDisabled#b52c939d = contacts.TopPeers;\ndraftMessageEmpty#1b0c841a flags:# date:flags.0?int = DraftMessage;\ndraftMessage#fd8e711f flags:# no_webpage:flags.1?true reply_to_msg_id:flags.0?int message:string entities:flags.3?Vector date:int = DraftMessage;\nmessages.featuredStickersNotModified#c6dc0c66 count:int = messages.FeaturedStickers;\nmessages.featuredStickers#84c02310 hash:long count:int sets:Vector unread:Vector = messages.FeaturedStickers;\nmessages.recentStickersNotModified#b17f890 = messages.RecentStickers;\nmessages.recentStickers#88d37c56 hash:long packs:Vector stickers:Vector dates:Vector = messages.RecentStickers;\nmessages.archivedStickers#4fcba9c8 count:int sets:Vector = messages.ArchivedStickers;\nmessages.stickerSetInstallResultSuccess#38641628 = messages.StickerSetInstallResult;\nmessages.stickerSetInstallResultArchive#35e410a8 sets:Vector = messages.StickerSetInstallResult;\nstickerSetCovered#6410a5d2 set:StickerSet cover:Document = StickerSetCovered;\nstickerSetMultiCovered#3407e51b set:StickerSet covers:Vector = StickerSetCovered;\nmaskCoords#aed6dbb2 n:int x:double y:double zoom:double = MaskCoords;\ninputStickeredMediaPhoto#4a992157 id:InputPhoto = InputStickeredMedia;\ninputStickeredMediaDocument#438865b id:InputDocument = InputStickeredMedia;\ngame#bdf9653b flags:# id:long access_hash:long short_name:string title:string description:string photo:Photo document:flags.0?Document = Game;\ninputGameID#32c3e77 id:long access_hash:long = InputGame;\ninputGameShortName#c331e80a bot_id:InputUser short_name:string = InputGame;\nhighScore#73a379eb pos:int user_id:long score:int = HighScore;\nmessages.highScores#9a3bfd99 scores:Vector users:Vector = messages.HighScores;\ntextEmpty#dc3d824f = RichText;\ntextPlain#744694e0 text:string = RichText;\ntextBold#6724abc4 text:RichText = RichText;\ntextItalic#d912a59c text:RichText = RichText;\ntextUnderline#c12622c4 text:RichText = RichText;\ntextStrike#9bf8bb95 text:RichText = RichText;\ntextFixed#6c3f19b9 text:RichText = RichText;\ntextUrl#3c2884c1 text:RichText url:string webpage_id:long = RichText;\ntextEmail#de5a0dd6 text:RichText email:string = RichText;\ntextConcat#7e6260d7 texts:Vector = RichText;\ntextSubscript#ed6a8504 text:RichText = RichText;\ntextSuperscript#c7fb5e01 text:RichText = RichText;\ntextMarked#34b8621 text:RichText = RichText;\ntextPhone#1ccb966a text:RichText phone:string = RichText;\ntextImage#81ccf4f document_id:long w:int h:int = RichText;\ntextAnchor#35553762 text:RichText name:string = RichText;\npageBlockUnsupported#13567e8a = PageBlock;\npageBlockTitle#70abc3fd text:RichText = PageBlock;\npageBlockSubtitle#8ffa9a1f text:RichText = PageBlock;\npageBlockAuthorDate#baafe5e0 author:RichText published_date:int = PageBlock;\npageBlockHeader#bfd064ec text:RichText = PageBlock;\npageBlockSubheader#f12bb6e1 text:RichText = PageBlock;\npageBlockParagraph#467a0766 text:RichText = PageBlock;\npageBlockPreformatted#c070d93e text:RichText language:string = PageBlock;\npageBlockFooter#48870999 text:RichText = PageBlock;\npageBlockDivider#db20b188 = PageBlock;\npageBlockAnchor#ce0d37b0 name:string = PageBlock;\npageBlockList#e4e88011 items:Vector = PageBlock;\npageBlockBlockquote#263d7c26 text:RichText caption:RichText = PageBlock;\npageBlockPullquote#4f4456d3 text:RichText caption:RichText = PageBlock;\npageBlockPhoto#1759c560 flags:# photo_id:long caption:PageCaption url:flags.0?string webpage_id:flags.0?long = PageBlock;\npageBlockVideo#7c8fe7b6 flags:# autoplay:flags.0?true loop:flags.1?true video_id:long caption:PageCaption = PageBlock;\npageBlockCover#39f23300 cover:PageBlock = PageBlock;\npageBlockEmbed#a8718dc5 flags:# full_width:flags.0?true allow_scrolling:flags.3?true url:flags.1?string html:flags.2?string poster_photo_id:flags.4?long w:flags.5?int h:flags.5?int caption:PageCaption = PageBlock;\npageBlockEmbedPost#f259a80b url:string webpage_id:long author_photo_id:long author:string date:int blocks:Vector caption:PageCaption = PageBlock;\npageBlockCollage#65a0fa4d items:Vector caption:PageCaption = PageBlock;\npageBlockSlideshow#31f9590 items:Vector caption:PageCaption = PageBlock;\npageBlockChannel#ef1751b5 channel:Chat = PageBlock;\npageBlockAudio#804361ea audio_id:long caption:PageCaption = PageBlock;\npageBlockKicker#1e148390 text:RichText = PageBlock;\npageBlockTable#bf4dea82 flags:# bordered:flags.0?true striped:flags.1?true title:RichText rows:Vector = PageBlock;\npageBlockOrderedList#9a8ae1e1 items:Vector = PageBlock;\npageBlockDetails#76768bed flags:# open:flags.0?true blocks:Vector title:RichText = PageBlock;\npageBlockRelatedArticles#16115a96 title:RichText articles:Vector = PageBlock;\npageBlockMap#a44f3ef6 geo:GeoPoint zoom:int w:int h:int caption:PageCaption = PageBlock;\nphoneCallDiscardReasonMissed#85e42301 = PhoneCallDiscardReason;\nphoneCallDiscardReasonDisconnect#e095c1a0 = PhoneCallDiscardReason;\nphoneCallDiscardReasonHangup#57adc690 = PhoneCallDiscardReason;\nphoneCallDiscardReasonBusy#faf7e8c9 = PhoneCallDiscardReason;\ndataJSON#7d748d04 data:string = DataJSON;\nlabeledPrice#cb296bf8 label:string amount:long = LabeledPrice;\ninvoice#cd886e0 flags:# test:flags.0?true name_requested:flags.1?true phone_requested:flags.2?true email_requested:flags.3?true shipping_address_requested:flags.4?true flexible:flags.5?true phone_to_provider:flags.6?true email_to_provider:flags.7?true currency:string prices:Vector max_tip_amount:flags.8?long suggested_tip_amounts:flags.8?Vector = Invoice;\npaymentCharge#ea02c27e id:string provider_charge_id:string = PaymentCharge;\npostAddress#1e8caaeb street_line1:string street_line2:string city:string state:string country_iso2:string post_code:string = PostAddress;\npaymentRequestedInfo#909c3f94 flags:# name:flags.0?string phone:flags.1?string email:flags.2?string shipping_address:flags.3?PostAddress = PaymentRequestedInfo;\npaymentSavedCredentialsCard#cdc27a1f id:string title:string = PaymentSavedCredentials;\nwebDocument#1c570ed1 url:string access_hash:long size:int mime_type:string attributes:Vector = WebDocument;\nwebDocumentNoProxy#f9c8bcc6 url:string size:int mime_type:string attributes:Vector = WebDocument;\ninputWebDocument#9bed434d url:string size:int mime_type:string attributes:Vector = InputWebDocument;\ninputWebFileLocation#c239d686 url:string access_hash:long = InputWebFileLocation;\ninputWebFileGeoPointLocation#9f2221c9 geo_point:InputGeoPoint access_hash:long w:int h:int zoom:int scale:int = InputWebFileLocation;\nupload.webFile#21e753bc size:int mime_type:string file_type:storage.FileType mtime:int bytes:bytes = upload.WebFile;\npayments.paymentForm#1694761b flags:# can_save_credentials:flags.2?true password_missing:flags.3?true form_id:long bot_id:long invoice:Invoice provider_id:long url:string native_provider:flags.4?string native_params:flags.4?DataJSON saved_info:flags.0?PaymentRequestedInfo saved_credentials:flags.1?PaymentSavedCredentials users:Vector = payments.PaymentForm;\npayments.validatedRequestedInfo#d1451883 flags:# id:flags.0?string shipping_options:flags.1?Vector = payments.ValidatedRequestedInfo;\npayments.paymentResult#4e5f810d updates:Updates = payments.PaymentResult;\npayments.paymentVerificationNeeded#d8411139 url:string = payments.PaymentResult;\npayments.paymentReceipt#70c4fe03 flags:# date:int bot_id:long provider_id:long title:string description:string photo:flags.2?WebDocument invoice:Invoice info:flags.0?PaymentRequestedInfo shipping:flags.1?ShippingOption tip_amount:flags.3?long currency:string total_amount:long credentials_title:string users:Vector = payments.PaymentReceipt;\npayments.savedInfo#fb8fe43c flags:# has_saved_credentials:flags.1?true saved_info:flags.0?PaymentRequestedInfo = payments.SavedInfo;\ninputPaymentCredentialsSaved#c10eb2cf id:string tmp_password:bytes = InputPaymentCredentials;\ninputPaymentCredentials#3417d728 flags:# save:flags.0?true data:DataJSON = InputPaymentCredentials;\ninputPaymentCredentialsApplePay#aa1c39f payment_data:DataJSON = InputPaymentCredentials;\ninputPaymentCredentialsGooglePay#8ac32801 payment_token:DataJSON = InputPaymentCredentials;\naccount.tmpPassword#db64fd34 tmp_password:bytes valid_until:int = account.TmpPassword;\nshippingOption#b6213cdf id:string title:string prices:Vector = ShippingOption;\ninputStickerSetItem#ffa0a496 flags:# document:InputDocument emoji:string mask_coords:flags.0?MaskCoords = InputStickerSetItem;\ninputPhoneCall#1e36fded id:long access_hash:long = InputPhoneCall;\nphoneCallEmpty#5366c915 id:long = PhoneCall;\nphoneCallWaiting#c5226f17 flags:# video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long protocol:PhoneCallProtocol receive_date:flags.0?int = PhoneCall;\nphoneCallRequested#14b0ed0c flags:# video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long g_a_hash:bytes protocol:PhoneCallProtocol = PhoneCall;\nphoneCallAccepted#3660c311 flags:# video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long g_b:bytes protocol:PhoneCallProtocol = PhoneCall;\nphoneCall#967f7c67 flags:# p2p_allowed:flags.5?true video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long g_a_or_b:bytes key_fingerprint:long protocol:PhoneCallProtocol connections:Vector start_date:int = PhoneCall;\nphoneCallDiscarded#50ca4de1 flags:# need_rating:flags.2?true need_debug:flags.3?true video:flags.6?true id:long reason:flags.0?PhoneCallDiscardReason duration:flags.1?int = PhoneCall;\nphoneConnection#9d4c17c0 id:long ip:string ipv6:string port:int peer_tag:bytes = PhoneConnection;\nphoneConnectionWebrtc#635fe375 flags:# turn:flags.0?true stun:flags.1?true id:long ip:string ipv6:string port:int username:string password:string = PhoneConnection;\nphoneCallProtocol#fc878fc8 flags:# udp_p2p:flags.0?true udp_reflector:flags.1?true min_layer:int max_layer:int library_versions:Vector = PhoneCallProtocol;\nphone.phoneCall#ec82e140 phone_call:PhoneCall users:Vector = phone.PhoneCall;\nupload.cdnFileReuploadNeeded#eea8e46e request_token:bytes = upload.CdnFile;\nupload.cdnFile#a99fca4f bytes:bytes = upload.CdnFile;\ncdnPublicKey#c982eaba dc_id:int public_key:string = CdnPublicKey;\ncdnConfig#5725e40a public_keys:Vector = CdnConfig;\nlangPackString#cad181f6 key:string value:string = LangPackString;\nlangPackStringPluralized#6c47ac9f flags:# key:string zero_value:flags.0?string one_value:flags.1?string two_value:flags.2?string few_value:flags.3?string many_value:flags.4?string other_value:string = LangPackString;\nlangPackStringDeleted#2979eeb2 key:string = LangPackString;\nlangPackDifference#f385c1f6 lang_code:string from_version:int version:int strings:Vector = LangPackDifference;\nlangPackLanguage#eeca5ce3 flags:# official:flags.0?true rtl:flags.2?true beta:flags.3?true name:string native_name:string lang_code:string base_lang_code:flags.1?string plural_code:string strings_count:int translated_count:int translations_url:string = LangPackLanguage;\nchannelAdminLogEventActionChangeTitle#e6dfb825 prev_value:string new_value:string = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeAbout#55188a2e prev_value:string new_value:string = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeUsername#6a4afc38 prev_value:string new_value:string = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangePhoto#434bd2af prev_photo:Photo new_photo:Photo = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleInvites#1b7907ae new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleSignatures#26ae0971 new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionUpdatePinned#e9e82c18 message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionEditMessage#709b2405 prev_message:Message new_message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionDeleteMessage#42e047bb message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantJoin#183040d3 = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantLeave#f89777f2 = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantInvite#e31c34d8 participant:ChannelParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantToggleBan#e6d83d7e prev_participant:ChannelParticipant new_participant:ChannelParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantToggleAdmin#d5676710 prev_participant:ChannelParticipant new_participant:ChannelParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeStickerSet#b1c3caa7 prev_stickerset:InputStickerSet new_stickerset:InputStickerSet = ChannelAdminLogEventAction;\nchannelAdminLogEventActionTogglePreHistoryHidden#5f5c95f1 new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionDefaultBannedRights#2df5fc0a prev_banned_rights:ChatBannedRights new_banned_rights:ChatBannedRights = ChannelAdminLogEventAction;\nchannelAdminLogEventActionStopPoll#8f079643 message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeLinkedChat#50c7ac8 prev_value:long new_value:long = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeLocation#e6b76ae prev_value:ChannelLocation new_value:ChannelLocation = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleSlowMode#53909779 prev_value:int new_value:int = ChannelAdminLogEventAction;\nchannelAdminLogEventActionStartGroupCall#23209745 call:InputGroupCall = ChannelAdminLogEventAction;\nchannelAdminLogEventActionDiscardGroupCall#db9f9140 call:InputGroupCall = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantMute#f92424d2 participant:GroupCallParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantUnmute#e64429c0 participant:GroupCallParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleGroupCallSetting#56d6a247 join_muted:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantJoinByInvite#5cdada77 invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionExportedInviteDelete#5a50fca4 invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionExportedInviteRevoke#410a134e invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionExportedInviteEdit#e90ebb59 prev_invite:ExportedChatInvite new_invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantVolume#3e7f6847 participant:GroupCallParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeHistoryTTL#6e941a38 prev_value:int new_value:int = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantJoinByRequest#afb6144a invite:ExportedChatInvite approved_by:long = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleNoForwards#cb2ac766 new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionSendMessage#278f2868 message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeAvailableReactions#9cf7f76a prev_value:Vector new_value:Vector = ChannelAdminLogEventAction;\nchannelAdminLogEvent#1fad68cd id:long date:int user_id:long action:ChannelAdminLogEventAction = ChannelAdminLogEvent;\nchannels.adminLogResults#ed8af74d events:Vector chats:Vector users:Vector = channels.AdminLogResults;\nchannelAdminLogEventsFilter#ea107ae4 flags:# join:flags.0?true leave:flags.1?true invite:flags.2?true ban:flags.3?true unban:flags.4?true kick:flags.5?true unkick:flags.6?true promote:flags.7?true demote:flags.8?true info:flags.9?true settings:flags.10?true pinned:flags.11?true edit:flags.12?true delete:flags.13?true group_call:flags.14?true invites:flags.15?true send:flags.16?true = ChannelAdminLogEventsFilter;\npopularContact#5ce14175 client_id:long importers:int = PopularContact;\nmessages.favedStickersNotModified#9e8fa6d3 = messages.FavedStickers;\nmessages.favedStickers#2cb51097 hash:long packs:Vector stickers:Vector = messages.FavedStickers;\nrecentMeUrlUnknown#46e1d13d url:string = RecentMeUrl;\nrecentMeUrlUser#b92c09e2 url:string user_id:long = RecentMeUrl;\nrecentMeUrlChat#b2da71d2 url:string chat_id:long = RecentMeUrl;\nrecentMeUrlChatInvite#eb49081d url:string chat_invite:ChatInvite = RecentMeUrl;\nrecentMeUrlStickerSet#bc0a57dc url:string set:StickerSetCovered = RecentMeUrl;\nhelp.recentMeUrls#e0310d7 urls:Vector chats:Vector users:Vector = help.RecentMeUrls;\ninputSingleMedia#1cc6e91f flags:# media:InputMedia random_id:long message:string entities:flags.0?Vector = InputSingleMedia;\nwebAuthorization#a6f8f452 hash:long bot_id:long domain:string browser:string platform:string date_created:int date_active:int ip:string region:string = WebAuthorization;\naccount.webAuthorizations#ed56c9fc authorizations:Vector users:Vector = account.WebAuthorizations;\ninputMessageID#a676a322 id:int = InputMessage;\ninputMessageReplyTo#bad88395 id:int = InputMessage;\ninputMessagePinned#86872538 = InputMessage;\ninputMessageCallbackQuery#acfa1a7e id:int query_id:long = InputMessage;\ninputDialogPeer#fcaafeb7 peer:InputPeer = InputDialogPeer;\ninputDialogPeerFolder#64600527 folder_id:int = InputDialogPeer;\ndialogPeer#e56dbf05 peer:Peer = DialogPeer;\ndialogPeerFolder#514519e2 folder_id:int = DialogPeer;\nmessages.foundStickerSetsNotModified#d54b65d = messages.FoundStickerSets;\nmessages.foundStickerSets#8af09dd2 hash:long sets:Vector = messages.FoundStickerSets;\nfileHash#6242c773 offset:int limit:int hash:bytes = FileHash;\ninputClientProxy#75588b3f address:string port:int = InputClientProxy;\nhelp.termsOfServiceUpdateEmpty#e3309f7f expires:int = help.TermsOfServiceUpdate;\nhelp.termsOfServiceUpdate#28ecf961 expires:int terms_of_service:help.TermsOfService = help.TermsOfServiceUpdate;\ninputSecureFileUploaded#3334b0f0 id:long parts:int md5_checksum:string file_hash:bytes secret:bytes = InputSecureFile;\ninputSecureFile#5367e5be id:long access_hash:long = InputSecureFile;\nsecureFileEmpty#64199744 = SecureFile;\nsecureFile#e0277a62 id:long access_hash:long size:int dc_id:int date:int file_hash:bytes secret:bytes = SecureFile;\nsecureData#8aeabec3 data:bytes data_hash:bytes secret:bytes = SecureData;\nsecurePlainPhone#7d6099dd phone:string = SecurePlainData;\nsecurePlainEmail#21ec5a5f email:string = SecurePlainData;\nsecureValueTypePersonalDetails#9d2a81e3 = SecureValueType;\nsecureValueTypePassport#3dac6a00 = SecureValueType;\nsecureValueTypeDriverLicense#6e425c4 = SecureValueType;\nsecureValueTypeIdentityCard#a0d0744b = SecureValueType;\nsecureValueTypeInternalPassport#99a48f23 = SecureValueType;\nsecureValueTypeAddress#cbe31e26 = SecureValueType;\nsecureValueTypeUtilityBill#fc36954e = SecureValueType;\nsecureValueTypeBankStatement#89137c0d = SecureValueType;\nsecureValueTypeRentalAgreement#8b883488 = SecureValueType;\nsecureValueTypePassportRegistration#99e3806a = SecureValueType;\nsecureValueTypeTemporaryRegistration#ea02ec33 = SecureValueType;\nsecureValueTypePhone#b320aadb = SecureValueType;\nsecureValueTypeEmail#8e3ca7ee = SecureValueType;\nsecureValue#187fa0ca flags:# type:SecureValueType data:flags.0?SecureData front_side:flags.1?SecureFile reverse_side:flags.2?SecureFile selfie:flags.3?SecureFile translation:flags.6?Vector files:flags.4?Vector plain_data:flags.5?SecurePlainData hash:bytes = SecureValue;\ninputSecureValue#db21d0a7 flags:# type:SecureValueType data:flags.0?SecureData front_side:flags.1?InputSecureFile reverse_side:flags.2?InputSecureFile selfie:flags.3?InputSecureFile translation:flags.6?Vector files:flags.4?Vector plain_data:flags.5?SecurePlainData = InputSecureValue;\nsecureValueHash#ed1ecdb0 type:SecureValueType hash:bytes = SecureValueHash;\nsecureValueErrorData#e8a40bd9 type:SecureValueType data_hash:bytes field:string text:string = SecureValueError;\nsecureValueErrorFrontSide#be3dfa type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorReverseSide#868a2aa5 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorSelfie#e537ced6 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorFile#7a700873 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorFiles#666220e9 type:SecureValueType file_hash:Vector text:string = SecureValueError;\nsecureValueError#869d758f type:SecureValueType hash:bytes text:string = SecureValueError;\nsecureValueErrorTranslationFile#a1144770 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorTranslationFiles#34636dd8 type:SecureValueType file_hash:Vector text:string = SecureValueError;\nsecureCredentialsEncrypted#33f0ea47 data:bytes hash:bytes secret:bytes = SecureCredentialsEncrypted;\naccount.authorizationForm#ad2e1cd8 flags:# required_types:Vector values:Vector errors:Vector users:Vector privacy_policy_url:flags.0?string = account.AuthorizationForm;\naccount.sentEmailCode#811f854f email_pattern:string length:int = account.SentEmailCode;\nhelp.deepLinkInfoEmpty#66afa166 = help.DeepLinkInfo;\nhelp.deepLinkInfo#6a4ee832 flags:# update_app:flags.0?true message:string entities:flags.1?Vector = help.DeepLinkInfo;\nsavedPhoneContact#1142bd56 phone:string first_name:string last_name:string date:int = SavedContact;\naccount.takeout#4dba4501 id:long = account.Takeout;\npasswordKdfAlgoUnknown#d45ab096 = PasswordKdfAlgo;\npasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow#3a912d4a salt1:bytes salt2:bytes g:int p:bytes = PasswordKdfAlgo;\nsecurePasswordKdfAlgoUnknown#4a8537 = SecurePasswordKdfAlgo;\nsecurePasswordKdfAlgoPBKDF2HMACSHA512iter100000#bbf2dda0 salt:bytes = SecurePasswordKdfAlgo;\nsecurePasswordKdfAlgoSHA512#86471d92 salt:bytes = SecurePasswordKdfAlgo;\nsecureSecretSettings#1527bcac secure_algo:SecurePasswordKdfAlgo secure_secret:bytes secure_secret_id:long = SecureSecretSettings;\ninputCheckPasswordEmpty#9880f658 = InputCheckPasswordSRP;\ninputCheckPasswordSRP#d27ff082 srp_id:long A:bytes M1:bytes = InputCheckPasswordSRP;\nsecureRequiredType#829d99da flags:# native_names:flags.0?true selfie_required:flags.1?true translation_required:flags.2?true type:SecureValueType = SecureRequiredType;\nsecureRequiredTypeOneOf#27477b4 types:Vector = SecureRequiredType;\nhelp.passportConfigNotModified#bfb9f457 = help.PassportConfig;\nhelp.passportConfig#a098d6af hash:int countries_langs:DataJSON = help.PassportConfig;\ninputAppEvent#1d1b1245 time:double type:string peer:long data:JSONValue = InputAppEvent;\njsonObjectValue#c0de1bd9 key:string value:JSONValue = JSONObjectValue;\njsonNull#3f6d7b68 = JSONValue;\njsonBool#c7345e6a value:Bool = JSONValue;\njsonNumber#2be0dfa4 value:double = JSONValue;\njsonString#b71e767a value:string = JSONValue;\njsonArray#f7444763 value:Vector = JSONValue;\njsonObject#99c1d49d value:Vector = JSONValue;\npageTableCell#34566b6a flags:# header:flags.0?true align_center:flags.3?true align_right:flags.4?true valign_middle:flags.5?true valign_bottom:flags.6?true text:flags.7?RichText colspan:flags.1?int rowspan:flags.2?int = PageTableCell;\npageTableRow#e0c0c5e5 cells:Vector = PageTableRow;\npageCaption#6f747657 text:RichText credit:RichText = PageCaption;\npageListItemText#b92fb6cd text:RichText = PageListItem;\npageListItemBlocks#25e073fc blocks:Vector = PageListItem;\npageListOrderedItemText#5e068047 num:string text:RichText = PageListOrderedItem;\npageListOrderedItemBlocks#98dd8936 num:string blocks:Vector = PageListOrderedItem;\npageRelatedArticle#b390dc08 flags:# url:string webpage_id:long title:flags.0?string description:flags.1?string photo_id:flags.2?long author:flags.3?string published_date:flags.4?int = PageRelatedArticle;\npage#98657f0d flags:# part:flags.0?true rtl:flags.1?true v2:flags.2?true url:string blocks:Vector photos:Vector documents:Vector views:flags.3?int = Page;\nhelp.supportName#8c05f1c9 name:string = help.SupportName;\nhelp.userInfoEmpty#f3ae2eed = help.UserInfo;\nhelp.userInfo#1eb3758 message:string entities:Vector author:string date:int = help.UserInfo;\npollAnswer#6ca9c2e9 text:string option:bytes = PollAnswer;\npoll#86e18161 id:long flags:# closed:flags.0?true public_voters:flags.1?true multiple_choice:flags.2?true quiz:flags.3?true question:string answers:Vector close_period:flags.4?int close_date:flags.5?int = Poll;\npollAnswerVoters#3b6ddad2 flags:# chosen:flags.0?true correct:flags.1?true option:bytes voters:int = PollAnswerVoters;\npollResults#dcb82ea3 flags:# min:flags.0?true results:flags.1?Vector total_voters:flags.2?int recent_voters:flags.3?Vector solution:flags.4?string solution_entities:flags.4?Vector = PollResults;\nchatOnlines#f041e250 onlines:int = ChatOnlines;\nstatsURL#47a971e0 url:string = StatsURL;\nchatAdminRights#5fb224d5 flags:# change_info:flags.0?true post_messages:flags.1?true edit_messages:flags.2?true delete_messages:flags.3?true ban_users:flags.4?true invite_users:flags.5?true pin_messages:flags.7?true add_admins:flags.9?true anonymous:flags.10?true manage_call:flags.11?true other:flags.12?true = ChatAdminRights;\nchatBannedRights#9f120418 flags:# view_messages:flags.0?true send_messages:flags.1?true send_media:flags.2?true send_stickers:flags.3?true send_gifs:flags.4?true send_games:flags.5?true send_inline:flags.6?true embed_links:flags.7?true send_polls:flags.8?true change_info:flags.10?true invite_users:flags.15?true pin_messages:flags.17?true until_date:int = ChatBannedRights;\ninputWallPaper#e630b979 id:long access_hash:long = InputWallPaper;\ninputWallPaperSlug#72091c80 slug:string = InputWallPaper;\ninputWallPaperNoFile#967a462e id:long = InputWallPaper;\naccount.wallPapersNotModified#1c199183 = account.WallPapers;\naccount.wallPapers#cdc3858c hash:long wallpapers:Vector = account.WallPapers;\ncodeSettings#8a6469c2 flags:# allow_flashcall:flags.0?true current_number:flags.1?true allow_app_hash:flags.4?true allow_missed_call:flags.5?true logout_tokens:flags.6?Vector = CodeSettings;\nwallPaperSettings#1dc1bca4 flags:# blur:flags.1?true motion:flags.2?true background_color:flags.0?int second_background_color:flags.4?int third_background_color:flags.5?int fourth_background_color:flags.6?int intensity:flags.3?int rotation:flags.4?int = WallPaperSettings;\nautoDownloadSettings#e04232f3 flags:# disabled:flags.0?true video_preload_large:flags.1?true audio_preload_next:flags.2?true phonecalls_less_data:flags.3?true photo_size_max:int video_size_max:int file_size_max:int video_upload_maxbitrate:int = AutoDownloadSettings;\naccount.autoDownloadSettings#63cacf26 low:AutoDownloadSettings medium:AutoDownloadSettings high:AutoDownloadSettings = account.AutoDownloadSettings;\nemojiKeyword#d5b3b9f9 keyword:string emoticons:Vector = EmojiKeyword;\nemojiKeywordDeleted#236df622 keyword:string emoticons:Vector = EmojiKeyword;\nemojiKeywordsDifference#5cc761bd lang_code:string from_version:int version:int keywords:Vector = EmojiKeywordsDifference;\nemojiURL#a575739d url:string = EmojiURL;\nemojiLanguage#b3fb5361 lang_code:string = EmojiLanguage;\nfolder#ff544e65 flags:# autofill_new_broadcasts:flags.0?true autofill_public_groups:flags.1?true autofill_new_correspondents:flags.2?true id:int title:string photo:flags.3?ChatPhoto = Folder;\ninputFolderPeer#fbd2c296 peer:InputPeer folder_id:int = InputFolderPeer;\nfolderPeer#e9baa668 peer:Peer folder_id:int = FolderPeer;\nmessages.searchCounter#e844ebff flags:# inexact:flags.1?true filter:MessagesFilter count:int = messages.SearchCounter;\nurlAuthResultRequest#92d33a0e flags:# request_write_access:flags.0?true bot:User domain:string = UrlAuthResult;\nurlAuthResultAccepted#8f8c0e4e url:string = UrlAuthResult;\nurlAuthResultDefault#a9d6db1f = UrlAuthResult;\nchannelLocationEmpty#bfb5ad8b = ChannelLocation;\nchannelLocation#209b82db geo_point:GeoPoint address:string = ChannelLocation;\npeerLocated#ca461b5d peer:Peer expires:int distance:int = PeerLocated;\npeerSelfLocated#f8ec284b expires:int = PeerLocated;\nrestrictionReason#d072acb4 platform:string reason:string text:string = RestrictionReason;\ninputTheme#3c5693e9 id:long access_hash:long = InputTheme;\ninputThemeSlug#f5890df1 slug:string = InputTheme;\ntheme#a00e67d6 flags:# creator:flags.0?true default:flags.1?true for_chat:flags.5?true id:long access_hash:long slug:string title:string document:flags.2?Document settings:flags.3?Vector emoticon:flags.6?string installs_count:flags.4?int = Theme;\naccount.themesNotModified#f41eb622 = account.Themes;\naccount.themes#9a3d8c6d hash:long themes:Vector = account.Themes;\nauth.loginToken#629f1980 expires:int token:bytes = auth.LoginToken;\nauth.loginTokenMigrateTo#68e9916 dc_id:int token:bytes = auth.LoginToken;\nauth.loginTokenSuccess#390d5c5e authorization:auth.Authorization = auth.LoginToken;\naccount.contentSettings#57e28221 flags:# sensitive_enabled:flags.0?true sensitive_can_change:flags.1?true = account.ContentSettings;\nmessages.inactiveChats#a927fec5 dates:Vector chats:Vector users:Vector = messages.InactiveChats;\nbaseThemeClassic#c3a12462 = BaseTheme;\nbaseThemeDay#fbd81688 = BaseTheme;\nbaseThemeNight#b7b31ea8 = BaseTheme;\nbaseThemeTinted#6d5f77ee = BaseTheme;\nbaseThemeArctic#5b11125a = BaseTheme;\ninputThemeSettings#8fde504f flags:# message_colors_animated:flags.2?true base_theme:BaseTheme accent_color:int outbox_accent_color:flags.3?int message_colors:flags.0?Vector wallpaper:flags.1?InputWallPaper wallpaper_settings:flags.1?WallPaperSettings = InputThemeSettings;\nthemeSettings#fa58b6d4 flags:# message_colors_animated:flags.2?true base_theme:BaseTheme accent_color:int outbox_accent_color:flags.3?int message_colors:flags.0?Vector wallpaper:flags.1?WallPaper = ThemeSettings;\nwebPageAttributeTheme#54b56617 flags:# documents:flags.0?Vector settings:flags.1?ThemeSettings = WebPageAttribute;\nmessageUserVote#34d247b4 user_id:long option:bytes date:int = MessageUserVote;\nmessageUserVoteInputOption#3ca5b0ec user_id:long date:int = MessageUserVote;\nmessageUserVoteMultiple#8a65e557 user_id:long options:Vector date:int = MessageUserVote;\nmessages.votesList#823f649 flags:# count:int votes:Vector users:Vector next_offset:flags.0?string = messages.VotesList;\nbankCardOpenUrl#f568028a url:string name:string = BankCardOpenUrl;\npayments.bankCardData#3e24e573 title:string open_urls:Vector = payments.BankCardData;\ndialogFilter#7438f7e8 flags:# contacts:flags.0?true non_contacts:flags.1?true groups:flags.2?true broadcasts:flags.3?true bots:flags.4?true exclude_muted:flags.11?true exclude_read:flags.12?true exclude_archived:flags.13?true id:int title:string emoticon:flags.25?string pinned_peers:Vector include_peers:Vector exclude_peers:Vector = DialogFilter;\ndialogFilterSuggested#77744d4a filter:DialogFilter description:string = DialogFilterSuggested;\nstatsDateRangeDays#b637edaf min_date:int max_date:int = StatsDateRangeDays;\nstatsAbsValueAndPrev#cb43acde current:double previous:double = StatsAbsValueAndPrev;\nstatsPercentValue#cbce2fe0 part:double total:double = StatsPercentValue;\nstatsGraphAsync#4a27eb2d token:string = StatsGraph;\nstatsGraphError#bedc9822 error:string = StatsGraph;\nstatsGraph#8ea464b6 flags:# json:DataJSON zoom_token:flags.0?string = StatsGraph;\nmessageInteractionCounters#ad4fc9bd msg_id:int views:int forwards:int = MessageInteractionCounters;\nstats.broadcastStats#bdf78394 period:StatsDateRangeDays followers:StatsAbsValueAndPrev views_per_post:StatsAbsValueAndPrev shares_per_post:StatsAbsValueAndPrev enabled_notifications:StatsPercentValue growth_graph:StatsGraph followers_graph:StatsGraph mute_graph:StatsGraph top_hours_graph:StatsGraph interactions_graph:StatsGraph iv_interactions_graph:StatsGraph views_by_source_graph:StatsGraph new_followers_by_source_graph:StatsGraph languages_graph:StatsGraph recent_message_interactions:Vector = stats.BroadcastStats;\nhelp.promoDataEmpty#98f6ac75 expires:int = help.PromoData;\nhelp.promoData#8c39793f flags:# proxy:flags.0?true expires:int peer:Peer chats:Vector users:Vector psa_type:flags.1?string psa_message:flags.2?string = help.PromoData;\nvideoSize#de33b094 flags:# type:string w:int h:int size:int video_start_ts:flags.0?double = VideoSize;\nstatsGroupTopPoster#9d04af9b user_id:long messages:int avg_chars:int = StatsGroupTopPoster;\nstatsGroupTopAdmin#d7584c87 user_id:long deleted:int kicked:int banned:int = StatsGroupTopAdmin;\nstatsGroupTopInviter#535f779d user_id:long invitations:int = StatsGroupTopInviter;\nstats.megagroupStats#ef7ff916 period:StatsDateRangeDays members:StatsAbsValueAndPrev messages:StatsAbsValueAndPrev viewers:StatsAbsValueAndPrev posters:StatsAbsValueAndPrev growth_graph:StatsGraph members_graph:StatsGraph new_members_by_source_graph:StatsGraph languages_graph:StatsGraph messages_graph:StatsGraph actions_graph:StatsGraph top_hours_graph:StatsGraph weekdays_graph:StatsGraph top_posters:Vector top_admins:Vector top_inviters:Vector users:Vector = stats.MegagroupStats;\nglobalPrivacySettings#bea2f424 flags:# archive_and_mute_new_noncontact_peers:flags.0?Bool = GlobalPrivacySettings;\nhelp.countryCode#4203c5ef flags:# country_code:string prefixes:flags.0?Vector patterns:flags.1?Vector = help.CountryCode;\nhelp.country#c3878e23 flags:# hidden:flags.0?true iso2:string default_name:string name:flags.1?string country_codes:Vector = help.Country;\nhelp.countriesListNotModified#93cc1f32 = help.CountriesList;\nhelp.countriesList#87d0759e countries:Vector hash:int = help.CountriesList;\nmessageViews#455b853d flags:# views:flags.0?int forwards:flags.1?int replies:flags.2?MessageReplies = MessageViews;\nmessages.messageViews#b6c4f543 views:Vector chats:Vector users:Vector = messages.MessageViews;\nmessages.discussionMessage#a6341782 flags:# messages:Vector max_id:flags.0?int read_inbox_max_id:flags.1?int read_outbox_max_id:flags.2?int unread_count:int chats:Vector users:Vector = messages.DiscussionMessage;\nmessageReplyHeader#a6d57763 flags:# reply_to_msg_id:int reply_to_peer_id:flags.0?Peer reply_to_top_id:flags.1?int = MessageReplyHeader;\nmessageReplies#83d60fc2 flags:# comments:flags.0?true replies:int replies_pts:int recent_repliers:flags.1?Vector channel_id:flags.0?long max_id:flags.2?int read_max_id:flags.3?int = MessageReplies;\npeerBlocked#e8fd8014 peer_id:Peer date:int = PeerBlocked;\nstats.messageStats#8999f295 views_graph:StatsGraph = stats.MessageStats;\ngroupCallDiscarded#7780bcb4 id:long access_hash:long duration:int = GroupCall;\ngroupCall#d597650c flags:# join_muted:flags.1?true can_change_join_muted:flags.2?true join_date_asc:flags.6?true schedule_start_subscribed:flags.8?true can_start_video:flags.9?true record_video_active:flags.11?true id:long access_hash:long participants_count:int title:flags.3?string stream_dc_id:flags.4?int record_start_date:flags.5?int schedule_date:flags.7?int unmuted_video_count:flags.10?int unmuted_video_limit:int version:int = GroupCall;\ninputGroupCall#d8aa840f id:long access_hash:long = InputGroupCall;\ngroupCallParticipant#eba636fe flags:# muted:flags.0?true left:flags.1?true can_self_unmute:flags.2?true just_joined:flags.4?true versioned:flags.5?true min:flags.8?true muted_by_you:flags.9?true volume_by_admin:flags.10?true self:flags.12?true video_joined:flags.15?true peer:Peer date:int active_date:flags.3?int source:int volume:flags.7?int about:flags.11?string raise_hand_rating:flags.13?long video:flags.6?GroupCallParticipantVideo presentation:flags.14?GroupCallParticipantVideo = GroupCallParticipant;\nphone.groupCall#9e727aad call:GroupCall participants:Vector participants_next_offset:string chats:Vector users:Vector = phone.GroupCall;\nphone.groupParticipants#f47751b6 count:int participants:Vector next_offset:string chats:Vector users:Vector version:int = phone.GroupParticipants;\ninlineQueryPeerTypeSameBotPM#3081ed9d = InlineQueryPeerType;\ninlineQueryPeerTypePM#833c0fac = InlineQueryPeerType;\ninlineQueryPeerTypeChat#d766c50a = InlineQueryPeerType;\ninlineQueryPeerTypeMegagroup#5ec4be43 = InlineQueryPeerType;\ninlineQueryPeerTypeBroadcast#6334ee9a = InlineQueryPeerType;\nmessages.historyImport#1662af0b id:long = messages.HistoryImport;\nmessages.historyImportParsed#5e0fb7b9 flags:# pm:flags.0?true group:flags.1?true title:flags.2?string = messages.HistoryImportParsed;\nmessages.affectedFoundMessages#ef8d3e6c pts:int pts_count:int offset:int messages:Vector = messages.AffectedFoundMessages;\nchatInviteImporter#8c5adfd9 flags:# requested:flags.0?true user_id:long date:int about:flags.2?string approved_by:flags.1?long = ChatInviteImporter;\nmessages.exportedChatInvites#bdc62dcc count:int invites:Vector users:Vector = messages.ExportedChatInvites;\nmessages.exportedChatInvite#1871be50 invite:ExportedChatInvite users:Vector = messages.ExportedChatInvite;\nmessages.exportedChatInviteReplaced#222600ef invite:ExportedChatInvite new_invite:ExportedChatInvite users:Vector = messages.ExportedChatInvite;\nmessages.chatInviteImporters#81b6b00a count:int importers:Vector users:Vector = messages.ChatInviteImporters;\nchatAdminWithInvites#f2ecef23 admin_id:long invites_count:int revoked_invites_count:int = ChatAdminWithInvites;\nmessages.chatAdminsWithInvites#b69b72d7 admins:Vector users:Vector = messages.ChatAdminsWithInvites;\nmessages.checkedHistoryImportPeer#a24de717 confirm_text:string = messages.CheckedHistoryImportPeer;\nphone.joinAsPeers#afe5623f peers:Vector chats:Vector users:Vector = phone.JoinAsPeers;\nphone.exportedGroupCallInvite#204bd158 link:string = phone.ExportedGroupCallInvite;\ngroupCallParticipantVideoSourceGroup#dcb118b7 semantics:string sources:Vector = GroupCallParticipantVideoSourceGroup;\ngroupCallParticipantVideo#67753ac8 flags:# paused:flags.0?true endpoint:string source_groups:Vector audio_source:flags.1?int = GroupCallParticipantVideo;\nstickers.suggestedShortName#85fea03f short_name:string = stickers.SuggestedShortName;\nbotCommandScopeDefault#2f6cb2ab = BotCommandScope;\nbotCommandScopeUsers#3c4f04d8 = BotCommandScope;\nbotCommandScopeChats#6fe1a881 = BotCommandScope;\nbotCommandScopeChatAdmins#b9aa606a = BotCommandScope;\nbotCommandScopePeer#db9d897d peer:InputPeer = BotCommandScope;\nbotCommandScopePeerAdmins#3fd863d1 peer:InputPeer = BotCommandScope;\nbotCommandScopePeerUser#a1321f3 peer:InputPeer user_id:InputUser = BotCommandScope;\naccount.resetPasswordFailedWait#e3779861 retry_date:int = account.ResetPasswordResult;\naccount.resetPasswordRequestedWait#e9effc7d until_date:int = account.ResetPasswordResult;\naccount.resetPasswordOk#e926d63e = account.ResetPasswordResult;\nsponsoredMessage#3a836df8 flags:# random_id:bytes from_id:flags.3?Peer chat_invite:flags.4?ChatInvite chat_invite_hash:flags.4?string channel_post:flags.2?int start_param:flags.0?string message:string entities:flags.1?Vector = SponsoredMessage;\nmessages.sponsoredMessages#65a4c7d5 messages:Vector chats:Vector users:Vector = messages.SponsoredMessages;\nsearchResultsCalendarPeriod#c9b0539f date:int min_msg_id:int max_msg_id:int count:int = SearchResultsCalendarPeriod;\nmessages.searchResultsCalendar#147ee23c flags:# inexact:flags.0?true count:int min_date:int min_msg_id:int offset_id_offset:flags.1?int periods:Vector messages:Vector chats:Vector users:Vector = messages.SearchResultsCalendar;\nsearchResultPosition#7f648b67 msg_id:int date:int offset:int = SearchResultsPosition;\nmessages.searchResultsPositions#53b22baf count:int positions:Vector = messages.SearchResultsPositions;\nchannels.sendAsPeers#8356cda9 peers:Vector chats:Vector users:Vector = channels.SendAsPeers;\nusers.userFull#3b6d152e full_user:UserFull chats:Vector users:Vector = users.UserFull;\nmessages.peerSettings#6880b94d settings:PeerSettings chats:Vector users:Vector = messages.PeerSettings;\nauth.loggedOut#c3a2835f flags:# future_auth_token:flags.0?bytes = auth.LoggedOut;\nreactionCount#6fb250d1 flags:# chosen:flags.0?true reaction:string count:int = ReactionCount;\nmessageReactions#87b6e36 flags:# min:flags.0?true can_see_list:flags.2?true results:Vector recent_reactons:flags.1?Vector = MessageReactions;\nmessageUserReaction#932844fa user_id:long reaction:string = MessageUserReaction;\nmessages.messageReactionsList#a366923c flags:# count:int reactions:Vector users:Vector next_offset:flags.0?string = messages.MessageReactionsList;\navailableReaction#21d7c4b flags:# inactive:flags.0?true reaction:string title:string static_icon:Document appear_animation:Document select_animation:Document activate_animation:Document effect_animation:Document = AvailableReaction;\nmessages.availableReactionsNotModified#9f071957 = messages.AvailableReactions;\nmessages.availableReactions#768e3aad hash:int reactions:Vector = messages.AvailableReactions;\n---functions---\ninitConnection#c1cd5ea9 {X:Type} flags:# api_id:int device_model:string system_version:string app_version:string system_lang_code:string lang_pack:string lang_code:string proxy:flags.0?InputClientProxy params:flags.1?JSONValue query:!X = X;\ninvokeWithLayer#da9b0d0d {X:Type} layer:int query:!X = X;\nauth.sendCode#a677244f phone_number:string api_id:int api_hash:string settings:CodeSettings = auth.SentCode;\nauth.signUp#80eee427 phone_number:string phone_code_hash:string first_name:string last_name:string = auth.Authorization;\nauth.signIn#bcd51581 phone_number:string phone_code_hash:string phone_code:string = auth.Authorization;\nauth.logOut#3e72ba19 = auth.LoggedOut;\nauth.resetAuthorizations#9fab0d1a = Bool;\nauth.exportAuthorization#e5bfffcd dc_id:int = auth.ExportedAuthorization;\nauth.importAuthorization#a57a7dad id:long bytes:bytes = auth.Authorization;\nauth.bindTempAuthKey#cdd42a05 perm_auth_key_id:long nonce:long expires_at:int encrypted_message:bytes = Bool;\nauth.checkPassword#d18b4d16 password:InputCheckPasswordSRP = auth.Authorization;\nauth.requestPasswordRecovery#d897bc66 = auth.PasswordRecovery;\nauth.resendCode#3ef1a9bf phone_number:string phone_code_hash:string = auth.SentCode;\nauth.cancelCode#1f040578 phone_number:string phone_code_hash:string = Bool;\nauth.dropTempAuthKeys#8e48a188 except_auth_keys:Vector = Bool;\nauth.exportLoginToken#b7e085fe api_id:int api_hash:string except_ids:Vector = auth.LoginToken;\nauth.importLoginToken#95ac5ce4 token:bytes = auth.LoginToken;\naccount.registerDevice#ec86017a flags:# no_muted:flags.0?true token_type:int token:string app_sandbox:Bool secret:bytes other_uids:Vector = Bool;\naccount.unregisterDevice#6a0d3206 token_type:int token:string other_uids:Vector = Bool;\naccount.updateNotifySettings#84be5b93 peer:InputNotifyPeer settings:InputPeerNotifySettings = Bool;\naccount.getNotifySettings#12b3ad31 peer:InputNotifyPeer = PeerNotifySettings;\naccount.updateProfile#78515775 flags:# first_name:flags.0?string last_name:flags.1?string about:flags.2?string = User;\naccount.updateStatus#6628562c offline:Bool = Bool;\naccount.getWallPapers#7967d36 hash:long = account.WallPapers;\naccount.checkUsername#2714d86c username:string = Bool;\naccount.updateUsername#3e0bdd7c username:string = User;\naccount.getPrivacy#dadbc950 key:InputPrivacyKey = account.PrivacyRules;\naccount.setPrivacy#c9f81ce8 key:InputPrivacyKey rules:Vector = account.PrivacyRules;\naccount.getAuthorizations#e320c158 = account.Authorizations;\naccount.resetAuthorization#df77f3bc hash:long = Bool;\naccount.getPassword#548a30f5 = account.Password;\naccount.getPasswordSettings#9cd4eaf9 password:InputCheckPasswordSRP = account.PasswordSettings;\naccount.updatePasswordSettings#a59b102f password:InputCheckPasswordSRP new_settings:account.PasswordInputSettings = Bool;\naccount.sendConfirmPhoneCode#1b3faa88 hash:string settings:CodeSettings = auth.SentCode;\naccount.confirmPhone#5f2178c3 phone_code_hash:string phone_code:string = Bool;\naccount.getTmpPassword#449e0b51 password:InputCheckPasswordSRP period:int = account.TmpPassword;\naccount.sendVerifyPhoneCode#a5a356f9 phone_number:string settings:CodeSettings = auth.SentCode;\naccount.confirmPasswordEmail#8fdf1920 code:string = Bool;\naccount.getContactSignUpNotification#9f07c728 = Bool;\naccount.setContactSignUpNotification#cff43f61 silent:Bool = Bool;\naccount.getNotifyExceptions#53577479 flags:# compare_sound:flags.1?true peer:flags.0?InputNotifyPeer = Updates;\naccount.uploadWallPaper#dd853661 file:InputFile mime_type:string settings:WallPaperSettings = WallPaper;\naccount.setContentSettings#b574b16b flags:# sensitive_enabled:flags.0?true = Bool;\naccount.getContentSettings#8b9b4dae = account.ContentSettings;\nusers.getUsers#d91a548 id:Vector = Vector;\nusers.getFullUser#b60f5918 id:InputUser = users.UserFull;\ncontacts.getContacts#5dd69e12 hash:long = contacts.Contacts;\ncontacts.importContacts#2c800be5 contacts:Vector = contacts.ImportedContacts;\ncontacts.deleteContacts#96a0e00 id:Vector = Updates;\ncontacts.block#68cc1411 id:InputPeer = Bool;\ncontacts.unblock#bea65d50 id:InputPeer = Bool;\ncontacts.getBlocked#f57c350f offset:int limit:int = contacts.Blocked;\ncontacts.search#11f812d8 q:string limit:int = contacts.Found;\ncontacts.resolveUsername#f93ccba3 username:string = contacts.ResolvedPeer;\ncontacts.getTopPeers#973478b6 flags:# correspondents:flags.0?true bots_pm:flags.1?true bots_inline:flags.2?true phone_calls:flags.3?true forward_users:flags.4?true forward_chats:flags.5?true groups:flags.10?true channels:flags.15?true offset:int limit:int hash:long = contacts.TopPeers;\ncontacts.addContact#e8f463d0 flags:# add_phone_privacy_exception:flags.0?true id:InputUser first_name:string last_name:string phone:string = Updates;\nmessages.getMessages#63c66506 id:Vector = messages.Messages;\nmessages.getDialogs#a0f4cb4f flags:# exclude_pinned:flags.0?true folder_id:flags.1?int offset_date:int offset_id:int offset_peer:InputPeer limit:int hash:long = messages.Dialogs;\nmessages.getHistory#4423e6c5 peer:InputPeer offset_id:int offset_date:int add_offset:int limit:int max_id:int min_id:int hash:long = messages.Messages;\nmessages.search#a0fda762 flags:# peer:InputPeer q:string from_id:flags.0?InputPeer top_msg_id:flags.1?int filter:MessagesFilter min_date:int max_date:int offset_id:int add_offset:int limit:int max_id:int min_id:int hash:long = messages.Messages;\nmessages.readHistory#e306d3a peer:InputPeer max_id:int = messages.AffectedMessages;\nmessages.deleteHistory#b08f922a flags:# just_clear:flags.0?true revoke:flags.1?true peer:InputPeer max_id:int min_date:flags.2?int max_date:flags.3?int = messages.AffectedHistory;\nmessages.deleteMessages#e58e95d2 flags:# revoke:flags.0?true id:Vector = messages.AffectedMessages;\nmessages.receivedMessages#5a954c0 max_id:int = Vector;\nmessages.setTyping#58943ee2 flags:# peer:InputPeer top_msg_id:flags.0?int action:SendMessageAction = Bool;\nmessages.sendMessage#d9d75a4 flags:# no_webpage:flags.1?true silent:flags.5?true background:flags.6?true clear_draft:flags.7?true noforwards:flags.14?true peer:InputPeer reply_to_msg_id:flags.0?int message:string random_id:long reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector schedule_date:flags.10?int send_as:flags.13?InputPeer = Updates;\nmessages.sendMedia#e25ff8e0 flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true noforwards:flags.14?true peer:InputPeer reply_to_msg_id:flags.0?int media:InputMedia message:string random_id:long reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector schedule_date:flags.10?int send_as:flags.13?InputPeer = Updates;\nmessages.forwardMessages#cc30290b flags:# silent:flags.5?true background:flags.6?true with_my_score:flags.8?true drop_author:flags.11?true drop_media_captions:flags.12?true noforwards:flags.14?true from_peer:InputPeer id:Vector random_id:Vector to_peer:InputPeer schedule_date:flags.10?int send_as:flags.13?InputPeer = Updates;\nmessages.report#8953ab4e peer:InputPeer id:Vector reason:ReportReason message:string = Bool;\nmessages.getChats#49e9528f id:Vector = messages.Chats;\nmessages.getFullChat#aeb00b34 chat_id:long = messages.ChatFull;\nmessages.editChatTitle#73783ffd chat_id:long title:string = Updates;\nmessages.editChatPhoto#35ddd674 chat_id:long photo:InputChatPhoto = Updates;\nmessages.addChatUser#f24753e3 chat_id:long user_id:InputUser fwd_limit:int = Updates;\nmessages.deleteChatUser#a2185cab flags:# revoke_history:flags.0?true chat_id:long user_id:InputUser = Updates;\nmessages.createChat#9cb126e users:Vector title:string = Updates;\nmessages.getDhConfig#26cf8950 version:int random_length:int = messages.DhConfig;\nmessages.readMessageContents#36a73f77 id:Vector = messages.AffectedMessages;\nmessages.getStickers#d5a5d3a1 emoticon:string hash:long = messages.Stickers;\nmessages.getAllStickers#b8a0a1a8 hash:long = messages.AllStickers;\nmessages.getWebPagePreview#8b68b0cc flags:# message:string entities:flags.3?Vector = MessageMedia;\nmessages.exportChatInvite#a02ce5d5 flags:# legacy_revoke_permanent:flags.2?true request_needed:flags.3?true peer:InputPeer expire_date:flags.0?int usage_limit:flags.1?int title:flags.4?string = ExportedChatInvite;\nmessages.checkChatInvite#3eadb1bb hash:string = ChatInvite;\nmessages.importChatInvite#6c50051c hash:string = Updates;\nmessages.getStickerSet#c8a0ec74 stickerset:InputStickerSet hash:int = messages.StickerSet;\nmessages.installStickerSet#c78fe460 stickerset:InputStickerSet archived:Bool = messages.StickerSetInstallResult;\nmessages.uninstallStickerSet#f96e55de stickerset:InputStickerSet = Bool;\nmessages.startBot#e6df7378 bot:InputUser peer:InputPeer random_id:long start_param:string = Updates;\nmessages.migrateChat#a2875319 chat_id:long = Updates;\nmessages.searchGlobal#4bc6589a flags:# folder_id:flags.0?int q:string filter:MessagesFilter min_date:int max_date:int offset_rate:int offset_peer:InputPeer offset_id:int limit:int = messages.Messages;\nmessages.getDocumentByHash#338e2464 sha256:bytes size:int mime_type:string = Document;\nmessages.getSavedGifs#5cf09635 hash:long = messages.SavedGifs;\nmessages.getInlineBotResults#514e999d flags:# bot:InputUser peer:InputPeer geo_point:flags.0?InputGeoPoint query:string offset:string = messages.BotResults;\nmessages.sendInlineBotResult#7aa11297 flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true hide_via:flags.11?true peer:InputPeer reply_to_msg_id:flags.0?int random_id:long query_id:long id:string schedule_date:flags.10?int send_as:flags.13?InputPeer = Updates;\nmessages.editMessage#48f71778 flags:# no_webpage:flags.1?true peer:InputPeer id:int message:flags.11?string media:flags.14?InputMedia reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector schedule_date:flags.15?int = Updates;\nmessages.getBotCallbackAnswer#9342ca07 flags:# game:flags.1?true peer:InputPeer msg_id:int data:flags.0?bytes password:flags.2?InputCheckPasswordSRP = messages.BotCallbackAnswer;\nmessages.getPeerDialogs#e470bcfd peers:Vector = messages.PeerDialogs;\nmessages.saveDraft#bc39e14b flags:# no_webpage:flags.1?true reply_to_msg_id:flags.0?int peer:InputPeer message:string entities:flags.3?Vector = Bool;\nmessages.getFeaturedStickers#64780b14 hash:long = messages.FeaturedStickers;\nmessages.readFeaturedStickers#5b118126 id:Vector = Bool;\nmessages.getRecentStickers#9da9403b flags:# attached:flags.0?true hash:long = messages.RecentStickers;\nmessages.getCommonChats#e40ca104 user_id:InputUser max_id:long limit:int = messages.Chats;\nmessages.getWebPage#32ca8f91 url:string hash:int = WebPage;\nmessages.toggleDialogPin#a731e257 flags:# pinned:flags.0?true peer:InputDialogPeer = Bool;\nmessages.getPinnedDialogs#d6b94df2 folder_id:int = messages.PeerDialogs;\nmessages.uploadMedia#519bc2b1 peer:InputPeer media:InputMedia = MessageMedia;\nmessages.getFavedStickers#4f1aaa9 hash:long = messages.FavedStickers;\nmessages.faveSticker#b9ffc55b id:InputDocument unfave:Bool = Bool;\nmessages.sendMultiMedia#f803138f flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true noforwards:flags.14?true peer:InputPeer reply_to_msg_id:flags.0?int multi_media:Vector schedule_date:flags.10?int send_as:flags.13?InputPeer = Updates;\nmessages.searchStickerSets#35705b8a flags:# exclude_featured:flags.0?true q:string hash:long = messages.FoundStickerSets;\nmessages.markDialogUnread#c286d98f flags:# unread:flags.0?true peer:InputDialogPeer = Bool;\nmessages.updatePinnedMessage#d2aaf7ec flags:# silent:flags.0?true unpin:flags.1?true pm_oneside:flags.2?true peer:InputPeer id:int = Updates;\nmessages.sendVote#10ea6184 peer:InputPeer msg_id:int options:Vector = Updates;\nmessages.getOnlines#6e2be050 peer:InputPeer = ChatOnlines;\nmessages.editChatAbout#def60797 peer:InputPeer about:string = Bool;\nmessages.editChatDefaultBannedRights#a5866b41 peer:InputPeer banned_rights:ChatBannedRights = Updates;\nmessages.getEmojiKeywordsDifference#1508b6af lang_code:string from_version:int = EmojiKeywordsDifference;\nmessages.getScheduledHistory#f516760b peer:InputPeer hash:long = messages.Messages;\nmessages.sendScheduledMessages#bd38850a peer:InputPeer id:Vector = Updates;\nmessages.deleteScheduledMessages#59ae2b16 peer:InputPeer id:Vector = Updates;\nmessages.getPollVotes#b86e380e flags:# peer:InputPeer id:int option:flags.0?bytes offset:flags.1?string limit:int = messages.VotesList;\nmessages.getDialogFilters#f19ed96d = Vector;\nmessages.getSuggestedDialogFilters#a29cd42c = Vector;\nmessages.updateDialogFilter#1ad4a04a flags:# id:int filter:flags.0?DialogFilter = Bool;\nmessages.getReplies#22ddd30c peer:InputPeer msg_id:int offset_id:int offset_date:int add_offset:int limit:int max_id:int min_id:int hash:long = messages.Messages;\nmessages.getDiscussionMessage#446972fd peer:InputPeer msg_id:int = messages.DiscussionMessage;\nmessages.readDiscussion#f731a9f4 peer:InputPeer msg_id:int read_max_id:int = Bool;\nmessages.unpinAllMessages#f025bc8b peer:InputPeer = messages.AffectedHistory;\nmessages.deleteChat#5bd0ee50 chat_id:long = Bool;\nmessages.getMessageReadParticipants#2c6f97b7 peer:InputPeer msg_id:int = Vector;\nmessages.toggleNoForwards#b11eafa2 peer:InputPeer enabled:Bool = Updates;\nmessages.saveDefaultSendAs#ccfddf96 peer:InputPeer send_as:InputPeer = Bool;\nupdates.getState#edd4882a = updates.State;\nupdates.getDifference#25939651 flags:# pts:int pts_total_limit:flags.0?int date:int qts:int = updates.Difference;\nupdates.getChannelDifference#3173d78 flags:# force:flags.0?true channel:InputChannel filter:ChannelMessagesFilter pts:int limit:int = updates.ChannelDifference;\nphotos.uploadProfilePhoto#89f30f69 flags:# file:flags.0?InputFile video:flags.1?InputFile video_start_ts:flags.2?double = photos.Photo;\nphotos.getUserPhotos#91cd32a8 user_id:InputUser offset:int max_id:long limit:int = photos.Photos;\nupload.saveFilePart#b304a621 file_id:long file_part:int bytes:bytes = Bool;\nupload.getFile#b15a9afc flags:# precise:flags.0?true cdn_supported:flags.1?true location:InputFileLocation offset:int limit:int = upload.File;\nupload.saveBigFilePart#de7b673d file_id:long file_part:int file_total_parts:int bytes:bytes = Bool;\nupload.getWebFile#24e6818d location:InputWebFileLocation offset:int limit:int = upload.WebFile;\nhelp.getConfig#c4f9186b = Config;\nhelp.getNearestDc#1fb33026 = NearestDc;\nhelp.getSupport#9cdf08cd = help.Support;\nhelp.acceptTermsOfService#ee72f79a id:DataJSON = Bool;\nhelp.getCountriesList#735787a8 lang_code:string hash:int = help.CountriesList;\nchannels.readHistory#cc104937 channel:InputChannel max_id:int = Bool;\nchannels.deleteMessages#84c1fd4e channel:InputChannel id:Vector = messages.AffectedMessages;\nchannels.getMessages#ad8c9a23 channel:InputChannel id:Vector = messages.Messages;\nchannels.getParticipants#77ced9d0 channel:InputChannel filter:ChannelParticipantsFilter offset:int limit:int hash:long = channels.ChannelParticipants;\nchannels.getParticipant#a0ab6cc6 channel:InputChannel participant:InputPeer = channels.ChannelParticipant;\nchannels.getChannels#a7f6bbb id:Vector = messages.Chats;\nchannels.getFullChannel#8736a09 channel:InputChannel = messages.ChatFull;\nchannels.createChannel#3d5fb10f flags:# broadcast:flags.0?true megagroup:flags.1?true for_import:flags.3?true title:string about:string geo_point:flags.2?InputGeoPoint address:flags.2?string = Updates;\nchannels.editAdmin#d33c8902 channel:InputChannel user_id:InputUser admin_rights:ChatAdminRights rank:string = Updates;\nchannels.editTitle#566decd0 channel:InputChannel title:string = Updates;\nchannels.editPhoto#f12e57c9 channel:InputChannel photo:InputChatPhoto = Updates;\nchannels.checkUsername#10e6bd2c channel:InputChannel username:string = Bool;\nchannels.updateUsername#3514b3de channel:InputChannel username:string = Bool;\nchannels.joinChannel#24b524c5 channel:InputChannel = Updates;\nchannels.leaveChannel#f836aa95 channel:InputChannel = Updates;\nchannels.inviteToChannel#199f3a6c channel:InputChannel users:Vector = Updates;\nchannels.deleteChannel#c0111fe3 channel:InputChannel = Updates;\nchannels.toggleSignatures#1f69b606 channel:InputChannel enabled:Bool = Updates;\nchannels.editBanned#96e6cd81 channel:InputChannel participant:InputPeer banned_rights:ChatBannedRights = Updates;\nchannels.readMessageContents#eab5dc38 channel:InputChannel id:Vector = Bool;\nchannels.togglePreHistoryHidden#eabbb94c channel:InputChannel enabled:Bool = Updates;\nchannels.getGroupsForDiscussion#f5dad378 = messages.Chats;\nchannels.setDiscussionGroup#40582bb2 broadcast:InputChannel group:InputChannel = Bool;\nchannels.viewSponsoredMessage#beaedb94 channel:InputChannel random_id:bytes = Bool;\nchannels.getSponsoredMessages#ec210fbf channel:InputChannel = messages.SponsoredMessages;\nchannels.getSendAs#dc770ee peer:InputPeer = channels.SendAsPeers;\npayments.getPaymentForm#8a333c8d flags:# peer:InputPeer msg_id:int theme_params:flags.0?DataJSON = payments.PaymentForm;\npayments.getPaymentReceipt#2478d1cc peer:InputPeer msg_id:int = payments.PaymentReceipt;\npayments.validateRequestedInfo#db103170 flags:# save:flags.0?true peer:InputPeer msg_id:int info:PaymentRequestedInfo = payments.ValidatedRequestedInfo;\npayments.sendPaymentForm#30c3bc9d flags:# form_id:long peer:InputPeer msg_id:int requested_info_id:flags.0?string shipping_option_id:flags.1?string credentials:InputPaymentCredentials tip_amount:flags.2?long = payments.PaymentResult;\npayments.getSavedInfo#227d824b = payments.SavedInfo;\nphone.createGroupCall#48cdc6d8 flags:# peer:InputPeer random_id:int title:flags.0?string schedule_date:flags.1?int = Updates;\nphone.joinGroupCall#b132ff7b flags:# muted:flags.0?true video_stopped:flags.2?true call:InputGroupCall join_as:InputPeer invite_hash:flags.1?string params:DataJSON = Updates;\nphone.leaveGroupCall#500377f9 call:InputGroupCall source:int = Updates;\nphone.discardGroupCall#7a777135 call:InputGroupCall = Updates;\nphone.getGroupCall#41845db call:InputGroupCall limit:int = phone.GroupCall;\nphone.getGroupParticipants#c558d8ab call:InputGroupCall ids:Vector sources:Vector offset:string limit:int = phone.GroupParticipants;\nphone.editGroupCallParticipant#a5273abf flags:# call:InputGroupCall participant:InputPeer muted:flags.0?Bool volume:flags.1?int raise_hand:flags.2?Bool video_stopped:flags.3?Bool video_paused:flags.4?Bool presentation_paused:flags.5?Bool = Updates;\nphone.exportGroupCallInvite#e6aa647f flags:# can_self_unmute:flags.0?true call:InputGroupCall = phone.ExportedGroupCallInvite;\nphone.toggleGroupCallStartSubscription#219c34e6 call:InputGroupCall subscribed:Bool = Updates;\nphone.joinGroupCallPresentation#cbea6bc4 call:InputGroupCall params:DataJSON = Updates;\nphone.leaveGroupCallPresentation#1c50d144 call:InputGroupCall = Updates;\nlangpack.getLangPack#f2f2330a lang_pack:string lang_code:string = LangPackDifference;\nlangpack.getStrings#efea3803 lang_pack:string lang_code:string keys:Vector = Vector;\nlangpack.getLanguages#42c6978f lang_pack:string = Vector;\nfolders.editPeerFolders#6847d0ab folder_peers:Vector = Updates;"},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;\np_q_inner_data_dc#a9f55f95 pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 dc:int = P_Q_inner_data;\np_q_inner_data_temp#3c6a84d4 pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 expires_in:int = P_Q_inner_data;\np_q_inner_data_temp_dc#56fddf88 pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 dc:int expires_in:int = P_Q_inner_data;\nserver_DH_params_fail#79cb045d nonce:int128 server_nonce:int128 new_nonce_hash:int128 = Server_DH_Params;\nserver_DH_params_ok#d0e8075c nonce:int128 server_nonce:int128 encrypted_answer:string = Server_DH_Params;\nserver_DH_inner_data#b5890dba nonce:int128 server_nonce:int128 g:int dh_prime:string g_a:string server_time:int = Server_DH_inner_data;\nclient_DH_inner_data#6643b654 nonce:int128 server_nonce:int128 retry_id:long g_b:string = Client_DH_Inner_Data;\ndh_gen_ok#3bcbf734 nonce:int128 server_nonce:int128 new_nonce_hash1:int128 = Set_client_DH_params_answer;\ndh_gen_retry#46dc1fb9 nonce:int128 server_nonce:int128 new_nonce_hash2:int128 = Set_client_DH_params_answer;\ndh_gen_fail#a69dae02 nonce:int128 server_nonce:int128 new_nonce_hash3:int128 = Set_client_DH_params_answer;\ndestroy_auth_key_ok#f660e1d4 = DestroyAuthKeyRes;\ndestroy_auth_key_none#0a9f2259 = DestroyAuthKeyRes;\ndestroy_auth_key_fail#ea109b13 = DestroyAuthKeyRes;\n---functions---\nreq_pq#60469778 nonce:int128 = ResPQ;\nreq_pq_multi#be7e8ef1 nonce:int128 = ResPQ;\nreq_pq_multi_new#51b410fd nonce:int128 = ResPQ;\nreq_DH_params#d712e4be nonce:int128 server_nonce:int128 p:string q:string public_key_fingerprint:long encrypted_data:string = Server_DH_Params;\nset_client_DH_params#f5045f1f nonce:int128 server_nonce:int128 encrypted_data:string = Set_client_DH_params_answer;\ndestroy_auth_key#d1435160 = DestroyAuthKeyRes;\n---types---\nmsgs_ack#62d6b459 msg_ids:Vector = MsgsAck;\nbad_msg_notification#a7eff811 bad_msg_id:long bad_msg_seqno:int error_code:int = BadMsgNotification;\nbad_server_salt#edab447b bad_msg_id:long bad_msg_seqno:int error_code:int new_server_salt:long = BadMsgNotification;\nmsgs_state_req#da69fb52 msg_ids:Vector = MsgsStateReq;\nmsgs_state_info#04deb57d req_msg_id:long info:string = MsgsStateInfo;\nmsgs_all_info#8cc0d131 msg_ids:Vector info:string = MsgsAllInfo;\nmsg_detailed_info#276d3ec6 msg_id:long answer_msg_id:long bytes:int status:int = MsgDetailedInfo;\nmsg_new_detailed_info#809db6df answer_msg_id:long bytes:int status:int = MsgDetailedInfo;\nmsg_resend_req#7d861a08 msg_ids:Vector = MsgResendReq;\nrpc_error#2144ca19 error_code:int error_message:string = RpcError;\nrpc_answer_unknown#5e2ad36e = RpcDropAnswer;\nrpc_answer_dropped_running#cd78e586 = RpcDropAnswer;\nrpc_answer_dropped#a43ad8b7 msg_id:long seq_no:int bytes:int = RpcDropAnswer;\nfuture_salt#0949d9dc valid_since:int valid_until:int salt:long = FutureSalt;\nfuture_salts#ae500895 req_msg_id:long now:int salts:vector = FutureSalts;\npong#347773c5 msg_id:long ping_id:long = Pong;\ndestroy_session_ok#e22045fc session_id:long = DestroySessionRes;\ndestroy_session_none#62d350c9 session_id:long = DestroySessionRes;\nnew_session_created#9ec20908 first_msg_id:long unique_id:long server_salt:long = NewSession;\nhttp_wait#9299359f max_delay:int wait_after:int max_wait:int = HttpWait;\nipPort#d433ad73 ipv4:int port:int = IpPort;\nipPortSecret#37982646 ipv4:int port:int secret:bytes = IpPort;\naccessPointRule#4679b65f phone_prefix_rules:string dc_id:int ips:vector = AccessPointRule;\nhelp.configSimple#5a592a6c date:int expires:int rules:vector = help.ConfigSimple;\ntlsClientHello blocks:vector = TlsClientHello;\ntlsBlockString data:string = TlsBlock;\ntlsBlockRandom length:int = TlsBlock;\ntlsBlockZero length:int = TlsBlock;\ntlsBlockDomain = TlsBlock;\ntlsBlockGrease seed:int = TlsBlock;\ntlsBlockScope entries:Vector = TlsBlock;\n---functions---\nping#7abe77ec ping_id:long = Pong;\nping_delay_disconnect#f3427b8c ping_id:long disconnect_delay:int = Pong;"}},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(6927)));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={927: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=927.04b93a71a7d051ccd448.js.map \ No newline at end of file +(()=>{var e,t,n={6927:(e,t,n)=>{"use strict";var s={};n.r(s),n.d(s,{Type:()=>Tt,clear:()=>Vt,fetch:()=>Bt,save:()=>xt});var a={};n.r(a),n.d(a,{addChatMembers:()=>Nn,addContact:()=>Ns,answerCallbackButton:()=>ri,blockContact:()=>La,checkChatUsername:()=>sa,checkPassword:()=>ga,checkUsername:()=>Da,clearDraft:()=>rn,clearPassword:()=>pa,createChannel:()=>dn,createGroupCall:()=>Sa,createGroupChat:()=>hn,deleteChannel:()=>fn,deleteChat:()=>gn,deleteChatFolder:()=>In,deleteChatMember:()=>Fn,deleteChatUser:()=>un,deleteContact:()=>Fs,deleteHistory:()=>as,deleteMessages:()=>ns,deleteScheduledMessages:()=>ss,destroy:()=>Gt,discardGroupCall:()=>ba,disconnect:()=>Kt,downloadMedia:()=>$t,editChatFolder:()=>Cn,editChatPhoto:()=>mn,editGroupCallParticipant:()=>wa,editGroupCallTitle:()=>Ca,editMessage:()=>Xn,exportGroupCallInvite:()=>Ia,faveSticker:()=>zs,fetchAnimatedEmojis:()=>js,fetchAuthorizations:()=>qa,fetchBlockedContacts:()=>Fa,fetchChat:()=>sn,fetchChatFolders:()=>bn,fetchChats:()=>en,fetchCommonChats:()=>Es,fetchContactList:()=>Bs,fetchContentSettings:()=>ni,fetchCountryList:()=>ii,fetchCurrentUser:()=>Xt,fetchEmojiKeywords:()=>ea,fetchFavoriteStickers:()=>Gs,fetchFeaturedStickers:()=>Ks,fetchFullChat:()=>tn,fetchFullUser:()=>Us,fetchGroupCallParticipants:()=>va,fetchGroupsForDiscussion:()=>Tn,fetchInlineBot:()=>di,fetchInlineBotResults:()=>li,fetchLangPack:()=>Ja,fetchLangStrings:()=>Qa,fetchLanguages:()=>$a,fetchMembers:()=>Dn,fetchMessage:()=>jn,fetchMessages:()=>Wn,fetchNearestCountry:()=>Ds,fetchNotificationExceptions:()=>Ka,fetchNotificationSettings:()=>za,fetchPinnedMessages:()=>ws,fetchPrivacySettings:()=>Xa,fetchProfilePhotos:()=>Ls,fetchRecentStickers:()=>Hs,fetchRecommendedChatFolders:()=>wn,fetchSavedGifs:()=>Js,fetchScheduledHistory:()=>_s,fetchSeenBy:()=>Cs,fetchSendAs:()=>Is,fetchSponsoredMessages:()=>Ps,fetchStickerSets:()=>qs,fetchStickers:()=>Ws,fetchStickersForEmoji:()=>Ys,fetchTopInlineBots:()=>ci,fetchTopUsers:()=>Ts,fetchUsers:()=>xs,fetchWallpapers:()=>Va,fetchWebPagePreview:()=>gs,findFirstMessageIdAfterDate:()=>ms,forwardMessages:()=>hs,getChatByUsername:()=>Pn,getGroupCall:()=>ya,getPasswordInfo:()=>la,getPaymentForm:()=>mi,getReceipt:()=>_i,importChatInvite:()=>qn,installStickerSet:()=>Qs,joinChannel:()=>ln,joinGroupCall:()=>Aa,joinGroupCallPresentation:()=>Ma,leaveChannel:()=>pn,leaveGroupCall:()=>Pa,leaveGroupCallPresentation:()=>Ra,loadPollOptionResults:()=>fs,markMessageListRead:()=>rs,markMessagesRead:()=>cs,migrateChat:()=>xn,openChatByInvite:()=>Vn,pinMessage:()=>es,provideAuthCode:()=>At,provideAuthPassword:()=>St,provideAuthPhoneNumber:()=>Pt,provideAuthRegistration:()=>Mt,provideRecoveryEmailCode:()=>ma,registerDevice:()=>Za,reportMessages:()=>is,requestChatUpdate:()=>an,requestThreadInfoUpdate:()=>ds,rescheduleMessage:()=>Zn,restartAuth:()=>kt,restartAuthWithQr:()=>Rt,saveDefaultSendAs:()=>vs,saveDraft:()=>on,searchChats:()=>nn,searchGifs:()=>Zs,searchMessagesGlobal:()=>us,searchMessagesLocal:()=>ls,searchStickers:()=>$s,sendInlineBotResult:()=>ui,sendMessage:()=>Jn,sendMessageAction:()=>os,sendPaymentForm:()=>hi,sendPollVote:()=>ps,sendScheduledMessages:()=>ys,setChatUsername:()=>aa,setDiscussionGroup:()=>Bn,setPrivacySettings:()=>ei,startBot:()=>gi,terminateAllAuthorizations:()=>Ga,terminateAuthorization:()=>Ha,toggleChatArchived:()=>yn,toggleChatPinned:()=>_n,toggleDialogUnread:()=>vn,toggleGroupCallStartSubscription:()=>ka,toggleIsProtected:()=>Hn,togglePreHistoryHidden:()=>An,toggleSignatures:()=>En,unblockContact:()=>Oa,uninstallStickerSet:()=>Xs,unpinAllMessages:()=>ts,unregisterDevice:()=>Ya,updateChatAbout:()=>Un,updateChatAdmin:()=>kn,updateChatDefaultBannedRights:()=>Sn,updateChatMemberBannedRights:()=>Mn,updateChatMutedState:()=>cn,updateChatTitle:()=>Rn,updateContact:()=>Vs,updateContactSignUpNotification:()=>Wa,updateContentSettings:()=>si,updateIsOnline:()=>ti,updateNotificationSettings:()=>ja,updatePassword:()=>fa,updatePrivateLink:()=>ia,updateProfile:()=>Ea,updateProfilePhoto:()=>Ba,updateRecoveryEmail:()=>ha,updateUsername:()=>Ta,uploadProfilePhoto:()=>xa,uploadWallpaper:()=>Na,validateRequestedInfo:()=>fi,viewSponsoredMessage:()=>As});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 A(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 S(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=S(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=A(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;l{e instanceof g.Api.User&&e.photo?H(e):(e instanceof g.Api.Chat||e instanceof g.Api.Channel)&&e.photo&&function(e,t=!1){const n=V(e.id,e instanceof g.Api.Chat?"chat":"channel");t&&v.chats[n]||(v.chats[n]=e)}(e)}))}function K(e){return String.fromCharCode(...e)}function z(e){return F.from(e,"binary")}function W(e){return"number"==typeof e?function(e){return e>0?"user":e<=-1e9?"channel":"chat"}(e):e.startsWith("-")?e.length>=11?"channel":"chat":"user"}function j(e){const t=W(e);return"user"===t?new g.Api.PeerUser({userId:le(e,"user")}):"channel"===t?new g.Api.PeerChannel({channelId:le(e,"channel")}):new g.Api.PeerChat({chatId:le(e,"chat")})}function $(e,t){const n=W(e);return"user"===n?new g.Api.InputPeerUser({userId:le(e,"user"),accessHash:U()(t)}):"channel"===n?new g.Api.InputPeerChannel({channelId:le(e,"channel"),accessHash:U()(t)}):new g.Api.InputPeerChat({chatId:le(e,"chat")})}function J(e){const t=W(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 $(e,String(n))}function Q(e,t){const n=W(e);return"user"===n?new g.Api.InputUser({userId:le(e,"user"),accessHash:U()(t)}):"channel"===n?new g.Api.InputChannel({channelId:le(e,"channel"),accessHash:U()(t)}):le(e,"chat")}function X(e,t){return new g.Api.InputStickerSetID({id:U()(e),accessHash:U()(t)})}function Z(e){const t=v.documents[e.id];if(t)return new g.Api.InputDocument(f(t,["id","accessHash","fileReference"]))}function Y(e){const t=Z(e);if(t)return new g.Api.InputMediaDocument({id:t})}function ee(){return(0,E.readBigIntFromBuffer)((0,E.generateRandomBytes)(8),!0,!0)}function te(e,t,n){return new g.Api.Message({id:e,peerId:j(t),fromId:j(t),media:n.media})}function ne(e){const{type:t,offset:n,length:s,url:a,userId:i}=e,o=i?v.users[i]:void 0;switch(t){case D.Bold:return new g.Api.MessageEntityBold({offset:n,length:s});case D.Italic:return new g.Api.MessageEntityItalic({offset:n,length:s});case D.Underline:return new g.Api.MessageEntityUnderline({offset:n,length:s});case D.Strike:return new g.Api.MessageEntityStrike({offset:n,length:s});case D.Code:return new g.Api.MessageEntityCode({offset:n,length:s});case D.Pre:return new g.Api.MessageEntityPre({offset:n,length:s,language:""});case D.Blockquote:return new g.Api.MessageEntityBlockquote({offset:n,length:s});case D.TextUrl:return new g.Api.MessageEntityTextUrl({offset:n,length:s,url:a});case D.Url:return new g.Api.MessageEntityUrl({offset:n,length:s});case D.Hashtag:return new g.Api.MessageEntityHashtag({offset:n,length:s});case D.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 se(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 ae({phone:e,firstName:t,lastName:n}){return new g.Api.InputPhoneContact({clientId:U()(1),phone:e,firstName:t,lastName:n})}function ie(e,t=0){return new g.Api.ChatBannedRights({...e,untilDate:t})}function oe(e){return new g.Api.ChatAdminRights(e)}function re(e){const{shippingAddress:t}=e;return new g.Api.PaymentRequestedInfo({...e,shippingAddress:t?new g.Api.PostAddress(t):void 0})}function ce(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 de(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 le(e,t){return"number"==typeof e?U()(Math.abs(e)):"user"===t?U()(e):U()(e.slice(1))}function ue(e){return new g.Api.InputGroupCall({id:U()(e.id),accessHash:U()(e.accessHash)})}const ge="temp";let pe,fe=1e9;function he(e){const{fromId:t,message:n,entities:s,startParam:a,channelPost:i,chatInvite:o,chatInviteHash:r,randomId:c}=e,d=t?N(t):void 0,l=o?o instanceof g.Api.ChatInvite?o.title:o.chat instanceof g.Api.ChatEmpty?void 0:o.chat.title:void 0;return{randomId:K(c),isBot:!!t&&B(t),text:ye(n,s),expiresAt:Math.round(Date.now()/1e3)+3e5,...d&&{chatId:d},...r&&{chatInviteHash:r},...o&&{chatInviteTitle:l},...a&&{startParam:a},...i&&{channelPostId:i}}}function me(e){const t=L(e);if(t&&(e instanceof g.Api.Message||e instanceof g.Api.MessageService))return _e(t,e)}function _e(e,t){const n=t.fromId?N(t.fromId):void 0,s=t.peerId?N(t.peerId):void 0,a=!n&&e===pe,i=t.out&&!t.post||a&&!t.fwdFrom;let o={};t.media&&(o={...we(t.media)}),!t.message||o.sticker||o.poll||o.contact||(o={...o,text:ye(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,c;const d=[];let l,u="other";const p="users"in e?e.users&&e.users.map((e=>V(e,"user"))):"userId"in e&&[V(e.userId,"user")]||[];let f;if(e instanceof g.Api.MessageActionChatCreate)c="Notification.CreatedChatWithTitle",d.push("%action_origin%",e.title),u="chatCreate";else if(e instanceof g.Api.MessageActionChatEditTitle)s?(c="Channel.MessageTitleUpdated",d.push(e.title)):(c="Notification.ChangedGroupName",d.push("%action_origin%",e.title));else if(e instanceof g.Api.MessageActionChatEditPhoto)s?c="Channel.MessagePhotoUpdated":(c="Notification.ChangedGroupPhoto",d.push("%action_origin%"));else if(e instanceof g.Api.MessageActionChatDeletePhoto)c=s?"Channel.MessagePhotoRemoved":"Group.MessagePhotoRemoved";else if(e instanceof g.Api.MessageActionChatAddUser)!t||p.includes(t)?(c="Notification.JoinedChat",d.push("%target_user%")):(c="Notification.Invited",d.push("%action_origin%","%target_user%"));else if(e instanceof g.Api.MessageActionChatDeleteUser)!t||p.includes(t)?(c="Notification.LeftChat",d.push("%target_user%")):(c="Notification.Kicked",d.push("%action_origin%","%target_user%"));else if(e instanceof g.Api.MessageActionChatJoinedByLink)c="Notification.JoinedGroupByLink",d.push("%action_origin%");else if(e instanceof g.Api.MessageActionChannelCreate)c="Notification.CreatedChannel";else if(e instanceof g.Api.MessageActionChatMigrateTo)f=N(e),c="Migrated to %target_chat%",d.push("%target_chat%");else if(e instanceof g.Api.MessageActionChannelMigrateFrom)f=N(e),c="Migrated from %target_chat%",d.push("%target_chat%");else if(e instanceof g.Api.MessageActionPinMessage)c="Chat.Service.Group.UpdatedPinnedMessage1",d.push("%action_origin%","%message%");else if(e instanceof g.Api.MessageActionHistoryClear)c="HistoryCleared",u="historyClear";else if(e instanceof g.Api.MessageActionPhoneCall){const t=Boolean(e.duration);if(c=[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);d.push(`${t} min${t>1?"s":""}`)}}else if(e instanceof g.Api.MessageActionInviteToGroupCall)c="Notification.VoiceChatInvitation",i={id:e.call.id.toString(),accessHash:e.call.accessHash.toString()},d.push("%action_origin%","%target_user%");else if(e instanceof g.Api.MessageActionContactSignUp)c="Notification.Joined",d.push("%action_origin%"),u="contactSignUp";else if(e instanceof g.Api.MessageActionPaymentSent)o=Number(e.totalAmount),r=e.currency,c="PaymentSuccessfullyPaid",n&&p.push(n),d.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);c="Notification.VoiceChatEnded",d.push(`${t} min${t>1?"s":""}`)}else c="Notification.VoiceChatStartedChannel",i={id:e.call.id.toString(),accessHash:e.call.accessHash.toString()};else e instanceof g.Api.MessageActionBotAllowed?(c="Chat.Service.BotPermissionAllowed",d.push(e.domain)):e instanceof g.Api.MessageActionCustomAction?c=e.message:e instanceof g.Api.MessageActionChatJoinedByRequest?(c="ChatService.UserJoinedGroupByRequest",d.push("%action_origin%")):c="ChatList.UnsupportedMessage";return"photo"in e&&e.photo instanceof g.Api.Photo&&(q(e.photo),l=C(e.photo)),{text:c,type:u,targetUserIds:p,targetChatId:f,photo:l,amount:o,currency:r,translationValues:d,call:i}}(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=K(e.data)):e instanceof g.Api.KeyboardButtonRequestPoll?n="requestPoll":e instanceof g.Api.KeyboardButtonRequestPhone?n="requestSelfContact":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&&N(e.savedFromPeer),s=e.fromId&&N(e.fromId);return{date:e.date,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&&pe||e,views:t.views,isFromScheduled:t.fromScheduled,...c&&{replyToMessageId:c},...l&&{replyToChatId:N(l)},...d&&{replyToTopMessageId:d},..._&&{forwardInfo:_},...u&&{isEdited:u,editDate:t.editDate},...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:V(t.viaBotId,"user")},...(null==y?void 0:y.comments)&&{threadInfo:Re(y,t.id,e)},...w&&{adminTitle:w},...t.noforwards&&{isProtected:!0}}}function ye(e,t){return null!=t&&t.some((e=>e instanceof g.Api.MessageEntitySpoiler))?{text:"The message is not supported on this version of Telegram."}:{text:e,...t&&{entities:t.map(ke)}}}function be(e){if(e instanceof g.Api.DraftMessageEmpty)return;const{message:t,entities:n,replyToMsgId:s,date:a}=e;return{formattedText:t?ye(t,n):void 0,replyingToId:s,date:a}}function we(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 A(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 Ce(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{id:String(e.document.id),fileName:Se(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{id:String(e.document.id),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 Ie(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:V(a,"user")}}(e);if(r)return{contact:r};const c=function(e){if(e instanceof g.Api.MessageMediaPoll)return ve(e.poll,e.results)}(e);if(c)return{poll:c};const d=Ae(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 Ce(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:Se(e,"video"),width:d,height:l,supportsStreaming:u,isRound:p,isGif:Boolean(r),thumbnail:w(s),size:a}}function Ie(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:Se(e),thumbnail:d,mediaType:l,mediaSize:u}}function ve(e,t){const{id:n,answers:s}=e,a=s.map((e=>({text:e.text,option:K(e.option)})));return{id:String(n),summary:{isPublic:e.publicVoters,...f(e,["closed","multipleChoice","quiz","question","closePeriod","closeDate"]),answers:a},results:Pe(t)}}function Pe(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:K(e),votersCount:s})));return{totalVoters:n,recentVoterIds:null==s?void 0:s.map((e=>V(e,"user"))),results:o,solution:a,...i&&{solutionEntities:i.map(ke)}}}function Ae(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=Ce(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?Ie(s):void 0,video:a}}function Se(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 Me(e,t){return{poll:{id:String(t),summary:f(e.summary,["question","answers"]),results:{}}}}function ke(e){const{className:t,offset:n,length:s}=e;return{type:t,offset:n,length:s,...e instanceof g.Api.MessageEntityMentionName&&{userId:V(e.userId,"user")},..."url"in e&&{url:e.url}}}function Re(e,t,n){const{channelId:s,replies:a,maxId:i,readMaxId:o,recentRepliers:r}=e;if(!s)return;const c=V(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(N)}}:void 0}const Ue=e=>Math.floor(Date.now()/1e3)+e;function Ee(e,t=!1){const n=Boolean("min"in e&&e.min),s="accessHash"in e&&String(e.accessHash),a="photo"in e&&e.photo&&qe(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},...(e instanceof g.Api.Chat||e instanceof g.Api.Channel)&&{isProtected:Boolean("noforwards"in e&&e.noforwards)},...t&&{isSupport:!0},...Te(e),..."creator"in e&&{isCreator:e.creator},...Be(e),...xe(e)}}function De(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&&Ue(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 xe(e){return e instanceof g.Api.Chat&&e.migratedTo&&!(e.migratedTo instanceof g.Api.InputChannelEmpty)?{migratedTo:{chatId:N(e.migratedTo),...e.migratedTo instanceof g.Api.InputChannel&&{accessHash:String(e.migratedTo.accessHash)}}}:{}}function Ve(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:V(e.id,e instanceof g.Api.User?"user":"chat"),type:Ne(e),title:e instanceof g.Api.User?Oe(e):e.title,...Ee(e,t)}}function Ne(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 Fe(e){return B(e)?`user${e.userId}`:x(e)?`chat${e.chatId}`:`chat${e.channelId}`}function Le(e,t){return B(e)?Oe(t):t.title}function Oe(e){return e.firstName?`${e.firstName}${e.lastName?` ${e.lastName}`:""}`:e.lastName||void 0}function qe(e){if("photoId"in e)return String(e.photoId)}function He(e){return{userId:e instanceof g.Api.ChannelParticipantBanned||e instanceof g.Api.ChannelParticipantLeft?N(e.peer):V(e.userId,"user"),inviterId:"inviterId"in e?V(e.inviterId,"user"):void 0,joinedDate:"date"in e?e.date:void 0,kickedByUserId:"kickedBy"in e?V(e.kickedBy,"user"):void 0,promotedByUserId:"promotedBy"in e?V(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 Ge(e){return e instanceof g.Api.ChatParticipants||e instanceof g.Api.channels.ChannelParticipants?e.participants.map(He).filter(Boolean):void 0}function Ke(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:N(e.fromId)},timestamp:Date.now()+1e3*t}}}function ze(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(N).filter(Boolean),includedChatIds:e.includePeers.map(N).filter(Boolean),excludedChatIds:e.excludePeers.map(N).filter(Boolean)};var t,n}function We({filter:e,description:t}){return{...ze(e),description:t}}function je(e){return e.reduce(((e,t)=>{const n=V(t.userId,"user");return e.concat(t.commands.map((e=>({botId:n,..._(e)}))))}),[])}function $e(e){const{fullUser:{about:t,commonChatsCount:n,pinnedMsgId:s,botInfo:a,blocked:i},users:o}=e,r=Je(o[0]);return{...r,fullInfo:{bio:t,commonChatsCount:n,pinnedMessageId:s,isBlocked:Boolean(i),...a&&{botDescription:a.description},...a&&a.commands.length&&{botCommands:Xe(r.id,a)}}}}function Je(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:V(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||"",noStatus:!e.status,...e.accessHash&&{accessHash:String(e.accessHash)},...a&&{avatarHash:a},...e.bot&&e.botInlinePlaceholder&&{botPlaceholder:e.botInlinePlaceholder}}}function Qe(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 Xe(e,t){return t.commands.map((({command:t,description:n})=>({botId:e,command:t,description:n})))}function Ze(e){const t={},n=[];return e.forEach((e=>{const s=Je(e);s&&(n.push(s),"status"in e&&(t[s.id]=Qe(e.status)))})),{users:n,userStatusesById:t}}function Ye(e){if(e instanceof g.Api.WallPaperNoFile)return;const{slug:t}=e,n=Ie(e.document);return n?{slug:t,document:n}:void 0}function et(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 tt(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=>V(e,"user"))):e instanceof g.Api.PrivacyValueDisallowUsers?a=e.users.map((e=>V(e,"user"))):e instanceof g.Api.PrivacyValueAllowChatParticipants?s=e.chats.map((e=>V(e,"chat"))):e instanceof g.Api.PrivacyValueDisallowChatParticipants&&(i=e.chats.map((e=>V(e,"chat"))))})),t||(t="nobody"),{visibility:t,allowUserIds:n||[],allowChatIds:s||[],blockUserIds:a||[],blockChatIds:i||[]}}function nt(e,t,n){const{silent:s,muteUntil:a,showPreviews:i,sound:o}=e;return{chatId:N(t),isMuted:s||"number"==typeof a&&Ue(n)e instanceof g.Api.User)).map(Je).forEach((e=>{e&&ct({"@type":"updateUser",id:e.id,user:e})})),e.filter((e=>e instanceof g.Api.Chat||e instanceof g.Api.Channel)).map((e=>Ve(e))).forEach((e=>{e&&ct({"@type":"updateChat",id:e.id,chat:e})}))}function pt(e,t){if(e instanceof g.connection.UpdateServerTimeOffset)lt=e.timeOffset;else if(e instanceof g.connection.UpdateConnectionState){let t;switch(e.state){case g.connection.UpdateConnectionState.disconnected:t="connectionStateConnecting";break;case g.connection.UpdateConnectionState.broken:t="connectionStateBroken";break;case g.connection.UpdateConnectionState.connected:default:t="connectionStateReady"}ct({"@type":"updateConnectionState",connectionState:t})}else if(e instanceof g.Api.UpdateNewMessage||e instanceof g.Api.UpdateNewScheduledMessage||e instanceof g.Api.UpdateNewChannelMessage||e instanceof g.Api.UpdateShortChatMessage||e instanceof g.Api.UpdateShortMessage){let t,s;if(e instanceof g.Api.UpdateShortChatMessage)t=_e(V((a=e).chatId,"chat"),{...a,fromId:j(V(a.fromId,"user"))});else if(e instanceof g.Api.UpdateShortMessage)t=function(e){return _e(V(e.userId,"user"),{...e,fromId:j(e.out?pe:V(e.userId,"user"))})}(e);else{var n;if(e.message instanceof g.Api.MessageEmpty)return;e.message instanceof g.Api.Message&&se(e.message)&&O(e.message),t=me(e.message),s="replyMarkup"in e.message&&(null===(n=e.message)||void 0===n?void 0:n.replyMarkup)instanceof g.Api.ReplyKeyboardForceReply&&(!e.message.replyMarkup.selective||t.isMentioned)}const i=e._entities;if(i&&(G(i),gt(i)),e instanceof g.Api.UpdateNewScheduledMessage?ct({"@type":dt.has(t.id)?"updateScheduledMessage":"newScheduledMessage",id:t.id,chatId:t.chatId,message:t}):ct({"@type":dt.has(t.id)?"updateMessage":"newMessage",id:t.id,chatId:t.chatId,message:t,shouldForceReply:s}),e.message instanceof g.Api.MessageService){const{action:n}=e.message;if(n instanceof g.Api.MessageActionChatEditTitle)ct({"@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=qe(s),i=L(e.message);v.chats[i]&&(v.chats[i].photo=s),q(n.photo),a&&ct({"@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=L(e.message);v.chats[n]&&(v.chats[n].photo=new g.Api.ChatPhotoEmpty),ct({"@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))&&(ct({"@type":"updateChat",id:t.chatId,chat:{isRestricted:!0}}),ct({"@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)))&&ct({"@type":"updateChatJoin",id:t.chatId}):n instanceof g.Api.MessageActionGroupCall&&!n.duration&&n.call&&ct({"@type":"updateGroupCallChatId",chatId:t.chatId,call:{id:n.call.id.toString(),accessHash:n.call.accessHash.toString()}})}}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&&se(e.message)&&O(e.message);const t=me(e.message);ct({"@type":"updateMessage",id:t.id,chatId:t.chatId,message:t})}else if(e instanceof g.Api.UpdateDeleteMessages)ct({"@type":"deleteMessages",ids:e.messages});else if(e instanceof g.Api.UpdateDeleteScheduledMessages)ct({"@type":"deleteScheduledMessages",ids:e.messages,chatId:N(e.peer)});else if(e instanceof g.Api.UpdateDeleteChannelMessages){const t=V(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&&ct({"@type":"deleteMessages",ids:s,chatId:t}),i.length&&ct({"@type":"deleteProfilePhotos",ids:i,chatId:t}),a.length&&setTimeout((()=>{ct({"@type":"deleteMessages",ids:a,chatId:t})}),1e3)}else if(e instanceof g.Api.UpdateServiceNotification)if(e.popup)ct({"@type":"error",error:{message:e.message}});else{const t=function(e,t){const n=fe++;let s={};return e.media&&(s={...we(e.media)}),!e.message||s.sticker||s.poll||s.contact||(s={...s,text:ye(e.message,e.entities)}),{id:n,chatId:d,date:e.inboxDate||t,content:s,isOutgoing:!1}}(e,Date.now()/1e3+lt);se(e)&&O(te(t.id,t.chatId,e)),ct({"@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:ye(s.content.text.text,e.entities)}),e.media&&(a={...a,...we(e.media)});const t=te(e.id,s.chatId,e);se(t)&&O(t)}dt.add(e.id);const i="date"in e&&1e3*e.datee instanceof g.Api.DialogPeer)).map((e=>N(e.peer))):[];ct({"@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;ct({"@type":"updateChatListType",id:N(n),folderId:t})}));else if(e instanceof g.Api.UpdateDialogFilter){const{id:t,filter:n}=e,s=n?ze(n):void 0;ct({"@type":"updateChatFolder",id:t,folder:s})}else if(e instanceof g.Api.UpdateDialogFilterOrder)ct({"@type":"updateChatFoldersOrder",orderedIds:e.order});else if(e instanceof g.Api.UpdateChatParticipants){const t=Ge(e.participants);ct({"@type":"updateChatMembers",id:V(e.participants.chatId,"chat"),replacedMembers:t})}else if(e instanceof g.Api.UpdateChatParticipantAdd){const t=He(f(e,["userId","inviterId","date"]));ct({"@type":"updateChatMembers",id:V(e.chatId,"chat"),addedMember:t})}else if(e instanceof g.Api.UpdateChatParticipantDelete)ct({"@type":"updateChatMembers",id:V(e.chatId,"chat"),deletedMemberId:V(e.userId,"user")});else if(e instanceof g.Api.UpdatePinnedMessages||e instanceof g.Api.UpdatePinnedChannelMessages){const t=e instanceof g.Api.UpdatePinnedMessages?N(e.peer):V(e.channelId,"channel");ct({"@type":"updatePinnedIds",chatId:t,messageIds:e.messages,isPinned:e.pinned})}else if(e instanceof g.Api.UpdateNotifySettings&&e.peer instanceof g.Api.NotifyPeer)ct({"@type":"updateNotifyExceptions",...nt(e.notifySettings,e.peer.peer,lt)});else if(e instanceof g.Api.UpdateUserTyping||e instanceof g.Api.UpdateChatUserTyping){const t=e instanceof g.Api.UpdateUserTyping?V(e.userId,"user"):V(e.chatId,"chat");ct({"@type":"updateChatTypingStatus",id:t,typingStatus:Ke(e,lt)})}else if(e instanceof g.Api.UpdateChannelUserTyping){const t=V(e.channelId,"channel");ct({"@type":"updateChatTypingStatus",id:t,typingStatus:Ke(e,lt)})}else if(e instanceof g.Api.UpdateChannel){const{_entities:n}=e;if(!n)return;const s=n.find((e=>e instanceof g.Api.Channel||e instanceof g.Api.ChannelForbidden));if(s instanceof g.Api.Channel){if(ut)return void(ut=!1);t instanceof g.Api.messages.ToggleNoForwards&&(ut=!0,setTimeout((()=>{ut=!1}),2e3));const n=Ve(s);n&&(ct({"@type":"updateChat",id:n.id,chat:n}),ct({"@type":n.isNotJoined?"updateChatLeave":"updateChatJoin",id:V(e.channelId,"channel")}))}else if(s instanceof g.Api.ChannelForbidden){const t=V(e.channelId,"channel");ct({"@type":"updateChat",id:t,chat:{isRestricted:!0}}),ct({"@type":"updateChatLeave",id:t})}else 0===n.length&&ct({"@type":"resetMessages",id:V(e.channelId,"channel")})}else if(e instanceof g.Api.UpdateDialogUnreadMark&&e.peer instanceof g.Api.DialogPeer)ct({"@type":"updateChat",id:N(e.peer.peer),chat:{hasUnreadMark:e.unread}});else if(e instanceof g.Api.UpdateChatDefaultBannedRights)ct({"@type":"updateChat",id:N(e.peer),chat:{defaultBannedRights:_(e.defaultBannedRights)}});else if(e instanceof g.Api.UpdateUserStatus)ct({"@type":"updateUserStatus",userId:V(e.userId,"user"),status:Qe(e.status)});else if(e instanceof g.Api.UpdateUserName){const t=V(e.userId,"user"),n=v.users[t],s=null!=n&&n.mutualContact&&!n.self?f(e,["username"]):f(e,["firstName","lastName","username"]);ct({"@type":"updateUser",id:t,user:s})}else if(e instanceof g.Api.UpdateUserPhoto){const{userId:t,photo:n}=e,s=V(t,"user"),a=qe(n);v.users[s]&&(v.users[s].photo=n),ct({"@type":"updateUser",id:s,user:{avatarHash:a}})}else if(e instanceof g.Api.UpdateUserPhone){const{userId:t,phone:n}=e;ct({"@type":"updateUser",id:V(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=>{ct({"@type":"deleteContact",id:V(e.id,"user")})})),t.filter((e=>e instanceof g.Api.User&&e.contact)).map(Je).forEach((e=>{e&&ct({"@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;ct({"@type":"updateNotifySettings",peerType:i,isSilent:Boolean(n||"number"==typeof s&&Date.now()+1e3*lt<1e3*s),shouldShowPreviews:Boolean(t)})}else if(e instanceof g.Api.UpdatePeerBlocked)ct({"@type":"updatePeerBlocked",id:N(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&&ct({"@type":"updatePrivacy",key:t,rules:tt(e.rules)})}else if(e instanceof g.Api.UpdateDraftMessage)ct({"@type":"draftMessage",chatId:N(e.peer),...be(e.draft)});else if(e instanceof g.Api.UpdateContactsReset)ct({"@type":"updateResetContactList"});else if(e instanceof g.Api.UpdateFavedStickers)ct({"@type":"updateFavoriteStickers"});else if(e instanceof g.Api.UpdateGroupCall)ct({"@type":"updateGroupCall",call:rt(e.call)});else if(e instanceof g.Api.UpdateGroupCallConnection)ct({"@type":"updateGroupCallConnection",data:JSON.parse(e.params.data),presentation:Boolean(e.presentation)});else if(e instanceof g.Api.UpdateGroupCallParticipants){const t=e._entities;t&&(G(t),gt(t)),ct({"@type":"updateGroupCallParticipants",groupCallId:(s=e.call,s.id.toString()),participants:e.participants.map(at)})}var s,a}const ft={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."},ht={};let mt;function _t(){return mt(vt("authorizationStateWaitPhoneNumber")),new Promise(((e,t)=>{ht.resolve=e,ht.reject=t}))}function yt(e=!1){return mt({...vt("authorizationStateWaitCode"),isCodeViaApp:e}),new Promise(((e,t)=>{ht.resolve=e,ht.reject=t}))}function bt(e){return mt({...vt("authorizationStateWaitPassword"),hint:e}),new Promise((e=>{ht.resolve=e}))}function wt(){return mt(vt("authorizationStateWaitRegistration")),new Promise((e=>{ht.resolve=e}))}function Ct(e){return mt({...vt("authorizationStateWaitQrCode"),qrCode:{token:btoa(String.fromCharCode(...e.token)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),expires:e.expires}}),new Promise(((e,t)=>{ht.reject=t}))}function It(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=ft[e.message];t||(t="Unexpected Error"),mt({"@type":"updateAuthorizationError",message:t})}function vt(e){return{"@type":"updateAuthorizationState",authorizationState:e}}function Pt(e){ht.resolve&&ht.resolve(e)}function At(e){ht.resolve&&ht.resolve(e)}function St(e){ht.resolve&&ht.resolve(e)}function Mt(e){const{firstName:t,lastName:n}=e;ht.resolve&&ht.resolve([t,n])}function kt(){ht.reject&&ht.reject(new Error("RESTART_AUTH"))}function Rt(){ht.reject&&ht.reject(new Error("RESTART_AUTH_WITH_QR"))}var Ut=n(9832),Et=n(5802);const Dt=self.caches;let Tt;async function Bt(e,t,n,s=!1){if(Dt)try{const a=new Request(t.replace(/:/g,"_")),i=await Dt.open(e),o=await i.match(a);if(!o)return;const r=o.headers.get("Content-Type");switch(n){case Tt.Text:return await o.text();case Tt.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 Tt.Json:return await o.json();default:return}}catch(e){return void console.warn(e)}}async function xt(e,t,n){if(Dt)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 Dt.open(e);return await o.put(a,i)}catch(e){return void console.warn(e)}}async function Vt(e){try{if(!Dt)return;return await Dt.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"}(Tt||(Tt={}));const Nt=new Set(["msg","sticker","gif","wallpaper","photo","webDocument"]);function Ft(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}Ut.Logger.setLevel("warn");const Lt={build:e=>e};let Ot,qt,Ht=!1;async function Gt(){await jt(new g.Api.auth.LogOut),await qt.destroy()}async function Kt(){await qt.disconnect()}function zt(e){Ot({"@type":"updateSession",sessionData:e})}function Wt(e){e instanceof g.connection.UpdateConnectionState?Ht=e.state===g.connection.UpdateConnectionState.connected:e instanceof g.Api.UpdatesTooLong?async function(){try{await jt(new g.Api.users.GetFullUser({id:new g.Api.InputUserSelf}),void 0,!0)}catch(e){"AUTH_KEY_UNREGISTERED"===e.message&&Ot({"@type":"updateConnectionState",connectionState:"connectionStateBroken"})}}():e instanceof g.connection.UpdateServerTimeOffset&&Ot({"@type":"updateServerTimeOffset",serverTimeOffset:e.timeOffset})}async function jt(e,t=!1,n=!1){if(Ht)try{const n=await qt.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=>{pt(t,e)}))):n instanceof g.Api.UpdatesTooLong||pt(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;Ot({"@type":"error",error:{message:s,isSlowMode:n,hasErrorKey:!0}})}(t,e)}}function $t(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./]+)(?::\d+)?(\?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]?W(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(Nt.has(d)){o===T.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===T.Lottie?"application/json":Ft(e),data:e}}{const e=await t.downloadProfilePhoto(p,"profile"===c[1]);return{mimeType:Ft(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 T.BlobUrl:return new Blob([e],{type:n});case T.Lottie:{const t=(0,Et.inflate)(e,{to:"string"});return JSON.parse(t)}case T.Progressive:return e.buffer}}(d,t,l);if(!p)return;const f=t!==T.Progressive&&(t!==T.BlobUrl||p.size<=524288);return s&&f&&xt(e.startsWith("avatar")?"tt-media-avatars":"tt-media",e,p),{prepared:t===T.Progressive?"":(h=p,h instanceof Blob?URL.createObjectURL(h):h),arrayBuffer:t===T.Progressive?p:void 0,mimeType:l,fullSize:u};var h}(e,qt,Ht,t)}function Jt(e,t){return qt.uploadFile({file:e,onProgress:t,workers:16})}function Qt(e){return qt.updateTwoFaSettings(e)}async function Xt(){const e=await jt(new g.Api.users.GetFullUser({id:new g.Api.InputUserSelf}));if(!(e&&e.users[0]instanceof g.Api.User))return;const t=e.users[0];v.users[V(t.id,"user")]=t;const n=$e(e);var s;s=n.id,pe=s,function(e){mt({"@type":"updateCurrentUser",currentUser:e})}(n)}const Zt=2**31-1;let Yt;async function en({limit:e,offsetDate:t,archived:n,withPinned:s,serverTimeOffset:a,lastLocalServiceMessage:i}){const o=await jt(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 jt(new g.Api.messages.GetPinnedDialogs({folderId:n?1:void 0})):void 0;if(!o||o instanceof g.Api.messages.DialogsNotModified)return;r&&On(r),On(o);const c=p((r?r.messages:[]).concat(o.messages).map(me).filter(Boolean),"chatId"),l={...r&&Ln(r),...Ln(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=De(e,l[Fe(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}=be(e.draft)||{};n&&(f[t.id]=n),s&&(h[t.id]=s)}}));const y=u.map((e=>e.id)),{users:b,userStatusesById:w}=Ze(((null==r?void 0:r.users)||[]).concat(o.users));let C;return C=o instanceof g.Api.messages.DialogsSlice?o.count:y.length,{chatIds:y,chats:u,users:b,userStatusesById:w,draftsById:f,replyingToById:h,orderedPinnedIds:s?_:void 0,totalChatCount:C}}function tn(e){const{id:t,accessHash:n,adminRights:s}=e;return Q(t,n)instanceof g.Api.InputChannel?async function(e,t,n){var s;const a=await jt(new g.Api.channels.GetFullChannel({channel:Q(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:_,defaultSendAs:y}=a.fullChat,b=r instanceof g.Api.ChatInviteExported?r.link:void 0,{members:w,users:C}=p&&await Dn(e,t)||{},{members:I,users:v}=p&&n&&await Dn(e,t,"kicked")||{},{members:P,users:A}=p&&n&&await Dn(e,t,"admin")||{},S=_?je(_):void 0;if((null==a||null===(s=a.chats)||void 0===s?void 0:s.length)>1){On(a);const[,e]=a.chats,t=Ve(e,void 0,!0);t&&Yt({"@type":"updateChat",id:t.id,chat:t})}return{fullInfo:{about:i,onlineCount:o,inviteLink:b,slowMode:c?{seconds:c,nextSendDate:d}:void 0,migratedFrom:l?{chatId:V(l,"chat"),maxMessageId:u}:void 0,canViewMembers:p,isPreHistoryHidden:h,members:w,kickedMembers:I,adminMembers:P,groupCallId:m?String(m.id):void 0,linkedChatId:f?V(f,"chat"):void 0,botCommands:S,sendAsId:y?N(y):void 0},users:[...C||[],...v||[],...A||[]],groupCall:m?{chatId:e,isLoaded:!1,id:m.id.toString(),accessHash:null==m?void 0:m.accessHash.toString(),participants:{},version:0,participantsCount:0,connectionState:"disconnected"}:void 0}}(t,n,s):async function(e){const t=await jt(new g.Api.messages.GetFullChat({chatId:Q(e)}));if(!(t&&t.fullChat instanceof g.Api.ChatFull))return;On(t);const{about:n,participants:s,exportedInvite:a,botInfo:i,call:o}=t.fullChat,r=Ge(s),c=r?r.filter((({isAdmin:e,isOwner:t})=>e||t)):void 0;return{fullInfo:{about:n,members:r,adminMembers:c,canViewMembers:!0,botCommands:i?je(i):void 0,...a&&{inviteLink:a.link},groupCallId:null==o?void 0:o.id.toString()},users:t.users.map(Je).filter(Boolean),groupCall:o?{chatId:e,isLoaded:!1,id:o.id.toString(),accessHash:o.accessHash.toString(),connectionState:"disconnected",participantsCount:0,version:0,participants:{}}:void 0}}(t)}async function nn({query:e}){const t=await jt(new g.Api.contacts.Search({q:e}));if(!t)return;On(t);const n=t.myResults.map(N),s=t.chats.concat(t.users).map((e=>Ve(e))).filter(Boolean),a=t.users.map(Je).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 sn({type:e,user:t}){let n;if("self"===e||"user"===e){const s=await jt(new g.Api.users.GetUsers({id:["user"===e&&t?Q(t.id,t.accessHash):new g.Api.InputUserSelf]}));if(!s||!s.length)return;[n]=s}else if("support"===e){const e=await jt(new g.Api.help.GetSupport);if(!e||!e.user)return;n=e.user}const s=Ve(n,"support"===e);if(s)return Yt({"@type":"updateChat",id:s.id,chat:s}),{chatId:s.id}}async function an({chat:e,serverTimeOffset:t,lastLocalMessage:n,noLastMessage:s}){const{id:a,accessHash:i}=e,o=await jt(new g.Api.messages.GetPeerDialogs({peers:[new g.Api.InputDialogPeer({peer:$(a,i)})]}));if(!o)return;const r=o.dialogs[0];if(!(r&&r instanceof g.Api.Dialog))return;const c=Ln(o)[Fe(r.peer)];if(!c)return;On(o);const d=me(o.messages[0]),l=n&&(!d||n.date>d.date)?n:d;Yt({"@type":"updateChat",id:a,chat:{...De(r,c,t),...!s&&{lastMessage:l}}})}function on({chat:e,text:t,entities:n,replyToMsgId:s}){return jt(new g.Api.messages.SaveDraft({peer:$(e.id,e.accessHash),message:t,...n&&{entities:n.map(ne)},replyToMsgId:s}))}function rn(e){return jt(new g.Api.messages.SaveDraft({peer:$(e.id,e.accessHash),message:""}))}async function cn({chat:e,isMuted:t,serverTimeOffset:n}){await jt(new g.Api.account.UpdateNotifySettings({peer:new g.Api.InputNotifyPeer({peer:$(e.id,e.accessHash)}),settings:new g.Api.InputPeerNotifySettings({muteUntil:t?Zt:0})})),Yt({"@type":"updateNotifyExceptions",chatId:e.id,isMuted:t}),an({chat:e,serverTimeOffset:n,noLastMessage:!0})}async function dn({title:e,about:t="",users:n},s=!1){const a=await jt(new g.Api.channels.CreateChannel({broadcast:!0,title:e,about:t}),!0);if(!(a instanceof g.Api.Updates))return;const i=a.chats[0];if(!(i&&i instanceof g.Api.Channel))return;const o=Ve(i);if(null!=n&&n.length)try{await jt(new g.Api.channels.InviteToChannel({channel:Q(o.id,o.accessHash),users:n.map((({id:e,accessHash:t})=>Q(e,t)))}),!0,s)}catch(e){}return o}function ln({channelId:e,accessHash:t}){return jt(new g.Api.channels.JoinChannel({channel:Q(e,t)}),!0)}function un({chat:e,user:t}){if("chatTypeBasicGroup"===e.type)return jt(new g.Api.messages.DeleteChatUser({chatId:Q(e.id,e.accessHash),userId:Q(t.id,t.accessHash)}),!0)}function gn({chatId:e}){return jt(new g.Api.messages.DeleteChat({chatId:Q(e)}),!0)}function pn({channelId:e,accessHash:t}){return jt(new g.Api.channels.LeaveChannel({channel:Q(e,t)}),!0)}function fn({channelId:e,accessHash:t}){return jt(new g.Api.channels.DeleteChannel({channel:Q(e,t)}),!0)}async function hn({title:e,users:t}){const n=await jt(new g.Api.messages.CreateChat({title:e,users:t.map((({id:e,accessHash:t})=>Q(e,t)))}),!0,!0);if(!(n instanceof g.Api.Updates))return;const s=n.chats[0];return s&&s instanceof g.Api.Chat?Ve(s):void 0}async function mn({chatId:e,accessHash:t,photo:n}){const s=await Jt(n),a=Q(e,t);return jt(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 _n({chat:e,shouldBePinned:t}){const{id:n,accessHash:s}=e;await jt(new g.Api.messages.ToggleDialogPin({peer:new g.Api.InputDialogPeer({peer:$(n,s)}),pinned:t||void 0}))&&Yt({"@type":"updateChatPinned",id:e.id,isPinned:t})}function yn({chat:e,folderId:t}){const{id:n,accessHash:s}=e;return jt(new g.Api.folders.EditPeerFolders({folderPeers:[new g.Api.InputFolderPeer({peer:$(n,s),folderId:t})]}),!0)}async function bn(){const e=await jt(new g.Api.messages.GetDialogFilters);if(e)return{byId:p(e.map(ze),"id"),orderedIds:e.map((({id:e})=>e))}}async function wn(){const e=await jt(new g.Api.messages.GetSuggestedDialogFilters);if(e)return e.map(We)}async function Cn({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(J).filter(Boolean):[],h=u?u.map(J).filter(Boolean):[],m=p?p.map(J).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 jt(new g.Api.messages.UpdateDialogFilter({id:e,filter:n}))&&Yt({"@type":"updateChatFolder",id:e,folder:t})}async function In(e){const t=await jt(new g.Api.messages.UpdateDialogFilter({id:e,filter:void 0})),n=await wn();t&&Yt({"@type":"updateChatFolder",id:e,folder:void 0}),n&&Yt({"@type":"updateRecommendedChatFolders",folders:n})}async function vn({chat:e,hasUnreadMark:t}){const{id:n,accessHash:s}=e;await jt(new g.Api.messages.MarkDialogUnread({peer:new g.Api.InputDialogPeer({peer:$(n,s)}),unread:t||void 0}))&&Yt({"@type":"updateChat",id:e.id,chat:{hasUnreadMark:t}})}async function Pn(e){const t=await jt(new g.Api.contacts.ResolveUsername({username:e}));if(!t)return;const{users:n,chats:s}=t,a=s.length?Ve(s[0]):Ve(n[0]);return a?(On(t),a):void 0}function An({chat:e,isEnabled:t}){const{id:n,accessHash:s}=e,a=Q(n,s);return jt(new g.Api.channels.TogglePreHistoryHidden({channel:a,enabled:t}),!0)}function Sn({chat:e,bannedRights:t}){const{id:n,accessHash:s}=e,a=$(n,s);return jt(new g.Api.messages.EditChatDefaultBannedRights({peer:a,bannedRights:ie(t)}),!0)}function Mn({chat:e,user:t,bannedRights:n,untilDate:s}){const a=Q(e.id,e.accessHash),i=$(t.id,t.accessHash);return jt(new g.Api.channels.EditBanned({channel:a,participant:i,bannedRights:ie(n,s)}),!0)}function kn({chat:e,user:t,adminRights:n,customTitle:s=""}){const a=Q(e.id,e.accessHash),i=Q(t.id,t.accessHash);return jt(new g.Api.channels.EditAdmin({channel:a,userId:i,adminRights:oe(n),rank:s}),!0)}async function Rn(e,t){const n=Q(e.id,e.accessHash);await jt(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 Un(e,t){await jt(new g.Api.messages.EditChatAbout({peer:$(e.id,e.accessHash),about:t}))&&Yt({"@type":"updateChatFullInfo",id:e.id,fullInfo:{about:t}})}function En({chat:e,isEnabled:t}){const{id:n,accessHash:s}=e,a=Q(n,s);return jt(new g.Api.channels.ToggleSignatures({channel:a,enabled:t}),!0)}async function Dn(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 jt(new g.Api.channels.GetParticipants({channel:Q(e,t),filter:a,offset:s,limit:200}));if(i&&!(i instanceof g.Api.channels.ChannelParticipantsNotModified))return On(i),{members:Ge(i),users:i.users.map(Je).filter(Boolean)}}async function Tn(){const e=await jt(new g.Api.channels.GetGroupsForDiscussion);if(e)return On(e),e.chats.map((e=>Ve(e)))}function Bn({channel:e,chat:t}){return jt(new g.Api.channels.SetDiscussionGroup({broadcast:$(e.id,e.accessHash),group:t?$(t.id,t.accessHash):new g.Api.InputChannelEmpty}))}async function xn(e){const t=await jt(new g.Api.messages.MigrateChat({chatId:Q(e.id)}),!0);if(t&&t instanceof g.Api.Updates)return On(t),Ve(t.chats[1])}async function Vn(e){const t=await jt(new g.Api.messages.CheckChatInvite({hash:e}));if(!t)return;let n;if(t instanceof g.Api.ChatInvite){const{photo:n,participantsCount:s,title:a,channel:i,requestNeeded:o,about:r}=t;n instanceof g.Api.Photo&&q(t.photo),Yt({"@type":"showInvite",data:{title:a,about:r,hash:e,participantsCount:s,isChannel:i,isRequestNeeded:o,...n instanceof g.Api.Photo&&{photo:C(n)}}})}else n=Ve(t.chat),n&&Yt({"@type":"updateChat",id:n.id,chat:n});return n?{chatId:n.id}:void 0}function Nn(e,t,n=!1){try{return"chatTypeChannel"===e.type||"chatTypeSuperGroup"===e.type?jt(new g.Api.channels.InviteToChannel({channel:Q(e.id,e.accessHash),users:t.map((e=>Q(e.id,e.accessHash)))}),!0,n):Promise.all(t.map((t=>jt(new g.Api.messages.AddChatUser({chatId:Q(e.id),userId:Q(t.id,t.accessHash)}),!0,n))))}catch(e){return}}function Fn(e,t){return"chatTypeChannel"===e.type||"chatTypeSuperGroup"===e.type?Mn({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:Zt}):jt(new g.Api.messages.DeleteChatUser({chatId:Q(e.id),userId:Q(t.id,t.accessHash)}),!0)}function Ln(e){const t={};return e.chats.forEach((e=>{t[`chat${e.id}`]=e})),e.users.forEach((e=>{t[`user${e.id}`]=e})),t}function On(e){"users"in e&&G(e.users),"chats"in e&&G(e.chats),"messages"in e&&e.messages.forEach((e=>{e instanceof g.Api.Message&&se(e)&&O(e)}))}async function qn({hash:e}){const t=await jt(new g.Api.messages.ImportChatInvite({hash:e}),!0);if(t instanceof g.Api.Updates&&t.chats.length)return Ve(t.chats[0])}function Hn({chat:e,isProtected:t}){const{id:n,accessHash:s}=e;return jt(new g.Api.messages.ToggleNoForwards({peer:$(n,s),enabled:t}),!0)}function Gn(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}),Gn(this,"name",void 0),Object.assign(this,s)}else super(e),Gn(this,"name",void 0);this.name=t}});var Kn=n(8764).Buffer;let zn;async function Wn({chat:e,threadId:t,...n}){const s=-1===t?g.Api.messages.GetHistory:g.Api.messages.GetReplies;let a;try{a=await jt(new s({peer:$(e.id,e.accessHash),...-1!==t&&{msgId:t},...n}),void 0,!0)}catch(t){"CHANNEL_PRIVATE"===t.message&&zn({"@type":"updateChat",id:e.id,chat:{isRestricted:!0}})}if(!a||a instanceof g.Api.messages.MessagesNotModified||!a.messages)return;bs(a);const i=a.messages.map(me).filter(Boolean),o=a.users.map(Je).filter(Boolean),r=a.chats.map((e=>Ve(e))).filter(Boolean),c=i.map((({threadInfo:e})=>e)).filter(Boolean);return{messages:i,users:o,chats:r,threadInfos:c}}async function jn({chat:e,messageId:t}){const n="channel"===W(e.id);let s;try{s=await jt(n?new g.Api.channels.GetMessages({channel:Q(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&&zn({"@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&&me(a);return i?(a instanceof g.Api.Message&&O(a),{message:i,users:s.users.map(Je).filter(Boolean)}):void 0}let $n=Promise.resolve();function Jn({chat:e,text:t,entities:n,replyingTo:s,attachment:a,sticker:i,gif:o,poll:r,contact:c,isSilent:d,scheduledAt:l,groupedId:u,noWebPage:p,sendAs:f,serverTimeOffset:h},m){const _=function(e,t,n,s,a,i,o,r,c,d,l,u,g=0){const p=fe++,f=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:ge,sizes:[],thumbnail:{width:o,height:r,dataUri:""},blobUrl:n}}:{video:{id:ge,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:{id:ge,duration:t,waveform:s}}}return a.startsWith("audio/")?{audio:{id:ge,mimeType:a,fileName:t,size:i,duration:200}}:{document:{mimeType:a,fileName:t,size:i,...s&&{previewBlobUrl:s}}}}(a),h="chatTypeChannel"===e.type;return{id:p,chatId:e.id,content:{...t&&{text:{text:t,entities:n}},...f,...i&&{sticker:i},...o&&{video:o},...r&&Me(r,p),...c&&{contact:c}},date:l||Math.round(Date.now()/1e3)+g,isOutgoing:!h,senderId:(null==u?void 0:u.id)||pe,...s&&{replyToMessageId:s},...d&&{groupedId:d,...f&&(f.photo||f.video)&&{isInAlbum:!0}},...l&&{isScheduled:!0}}}(e,t,n,s,a,i,o,r,c,u,l,f,h);zn({"@type":_.isScheduled?"newScheduledMessage":"newMessage",id:_.id,chatId:e.id,message:_}),setTimeout((()=>{zn({"@type":_.isScheduled?"updateScheduledMessage":"updateMessage",id:_.id,chatId:e.id,message:{sendingState:"messageSendingStatePending"}})}),1e3);const y=ee();if(v.localMessages[String(y)]=_,u)return function({chat:e,text:t,entities:n,replyingTo:s,attachment:a,groupedId:i,isSilent:o,scheduledAt:r,sendAs:c},d,l,u){let p=-1;Qn[i]||(Qn[i]={counter:0,singleMediaByIndex:{}}),p=Qn[i].counter++;const f=$n;return $n=(async()=>{let h;try{h=await Yn(l,a,u)}catch(e){return Qn[i].counter--,void await f}const m=await async function(e,t){const n=await jt(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})})}}($(e.id,e.accessHash),h);if(await f,!m)return void Qn[i].counter--;if(Qn[i].singleMediaByIndex[p]=new g.Api.InputSingleMedia({media:m,randomId:d,message:t||"",entities:n?n.map(ne):void 0}),Object.keys(Qn[i].singleMediaByIndex).length{let u;if(a)try{u=await Yn(_,a,m)}catch(e){return void await b}else i?u=Y(i):o?u=Y(o):r?u=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:z(t)}))),quiz:n.quiz,multipleChoice:n.multipleChoice});if(!s)return new g.Api.InputMediaPoll({poll:a});const i=s.correctAnswers.map(z),{solution:o}=s,r=s.solutionEntities?s.solutionEntities.map(ne):[];return new g.Api.InputMediaPoll({poll:a,correctAnswers:i,...o&&{solution:o,solutionEntities:r}})}(r,y):c&&(u=new g.Api.InputMediaContact({phoneNumber:c.phoneNumber,firstName:c.firstName,lastName:c.lastName,vcard:""}));await b;const h=u?g.Api.messages.SendMedia:g.Api.messages.SendMessage;await jt(new h({clearDraft:!0,message:t||"",entities:n?n.map(ne):void 0,peer:$(e.id,e.accessHash),randomId:y,...d&&{silent:d},...l&&{scheduleDate:l},...s&&{replyToMsgId:s},...u&&{media:u},...p&&{noWebpage:p},...f&&{sendAs:$(f.id,f.accessHash)}}),!0)})(),$n}const Qn={};async function Xn({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}}}};zn({"@type":o?"updateScheduledMessage":"updateMessage",id:t.id,chatId:e.id,message:r}),v.localMessages[t.id]={...t,...r};const c=s&&s.map(ne);await jt(new g.Api.messages.EditMessage({message:n||"",entities:c,peer:$(e.id,e.accessHash),id:t.id,...o&&{scheduleDate:t.date},...a&&{noWebpage:a}}),!0)}async function Zn({chat:e,message:t,scheduledAt:n}){await jt(new g.Api.messages.EditMessage({peer:$(e.id,e.accessHash),id:t.id,scheduleDate:n}),!0)}async function Yn(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 Jt(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:Kn.from(n)}))}return new g.Api.InputMediaUploadedDocument({file:p,mimeType:i,attributes:f})}async function es({chat:e,messageId:t,isUnpin:n,isOneSide:s,isSilent:a}){await jt(new g.Api.messages.UpdatePinnedMessage({peer:$(e.id,e.accessHash),id:t,...n&&{unpin:!0},...s&&{pmOneside:!0},...a&&{silent:!0}}),!0)}async function ts({chat:e}){await jt(new g.Api.messages.UnpinAllMessages({peer:$(e.id,e.accessHash)}),!0)}async function ns({chat:e,messageIds:t,shouldDeleteForAll:n}){const s="channel"===W(e.id);await jt(s?new g.Api.channels.DeleteMessages({channel:Q(e.id,e.accessHash),id:t}):new g.Api.messages.DeleteMessages({id:t,...n&&{revoke:!0}}))&&zn({"@type":"deleteMessages",ids:t,...s&&{chatId:e.id}})}async function ss({chat:e,messageIds:t}){await jt(new g.Api.messages.DeleteScheduledMessages({peer:$(e.id,e.accessHash),id:t}))&&zn({"@type":"deleteScheduledMessages",ids:t,chatId:e.id})}async function as({chat:e,shouldDeleteForAll:t,maxId:n}){const s="channel"===W(e.id);await jt(s?new g.Api.channels.DeleteHistory({channel:Q(e.id,e.accessHash),maxId:n}):new g.Api.messages.DeleteHistory({peer:$(e.id,e.accessHash),...t&&{revoke:!0},...!t&&{just_clear:!0},maxId:n}))&&zn({"@type":"deleteHistory",chatId:e.id})}async function is({peer:e,messageIds:t,reason:n,description:s}){return await jt(new g.Api.messages.Report({peer:$(e.id,e.accessHash),id:t,reason:de(n),message:s}))}async function os({peer:e,threadId:t,action:n}){const s=function(e){switch(e.type){case"cancel":return new g.Api.SendMessageCancelAction;case"typing":return new g.Api.SendMessageTypingAction;case"recordAudio":return new g.Api.SendMessageRecordAudioAction;case"chooseSticker":return new g.Api.SendMessageChooseStickerAction}}(n);if(s)return await jt(new g.Api.messages.SetTyping({peer:$(e.id,e.accessHash),topMsgId:t,action:s}))}async function rs({chat:e,threadId:t,maxId:n,serverTimeOffset:s}){const a="channel"===W(e.id);a&&-1===t?await jt(new g.Api.channels.ReadHistory({channel:Q(e.id,e.accessHash),maxId:n})):a?await jt(new g.Api.messages.ReadDiscussion({peer:$(e.id,e.accessHash),msgId:t,readMaxId:n})):await jt(new g.Api.messages.ReadHistory({peer:$(e.id,e.accessHash),maxId:n})),-1===t?an({chat:e,serverTimeOffset:s,noLastMessage:!0}):ds({chat:e,threadId:t})}async function cs({chat:e,messageIds:t}){const n="channel"===W(e.id);await jt(n?new g.Api.channels.ReadMessageContents({channel:Q(e.id,e.accessHash),id:t}):new g.Api.messages.ReadMessageContents({id:t})),zn({...n?{"@type":"updateChannelMessages",channelId:e.id}:{"@type":"updateCommonBoxMessages"},ids:t,messageUpdate:{hasUnreadMention:!1,isMediaUnread:!1}})}async function ds({chat:e,threadId:t}){const[n,s]=await Promise.all([jt(new g.Api.messages.GetDiscussionMessage({peer:$(e.id,e.accessHash),msgId:t})),jt(new g.Api.messages.GetReplies({peer:$(e.id,e.accessHash),msgId:t,offsetId:1,addOffset:-1,limit:1}))]);if(!n||!n.messages.length)return;const a=L(n.messages[0]);return a?(zn({"@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=>Ve(e))).filter(Boolean).forEach((e=>{zn({"@type":"updateChat",id:e.id,chat:e,noTopChatsRequest:!0})})),{discussionChatId:a}):void 0}async function ls({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 jt(new g.Api.messages.Search({peer:$(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;bs(c);const d=c.messages.map(me).filter(Boolean),l=c.users.map(Je).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 us({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 jt(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;bs({chats:r.chats,users:r.users,messages:r.messages});const c=r.chats.map((e=>Ve(e))).filter(Boolean),d=r.users.map(Je).filter(Boolean),l=r.messages.map(me).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 gs({message:e}){const t=await jt(new g.Api.messages.GetWebPagePreview({message:e}));return t&&Ae(t)}async function ps({chat:e,messageId:t,options:n}){const{id:s,accessHash:a}=e;await jt(new g.Api.messages.SendVote({peer:$(s,a),msgId:t,options:n.map(z)}),!0)}async function fs({chat:e,messageId:t,option:n,offset:s,limit:a,shouldResetVoters:i}){const{id:o,accessHash:r}=e,c=await jt(new g.Api.messages.GetPollVotes({peer:$(o,r),id:t,...n&&{option:z(n)},...s&&{offset:s},...a&&{limit:a}}));if(!c)return;bs({chats:[],users:c.users,messages:[]});const d=c.users.map(Je).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 hs({fromChat:e,toChat:t,messages:n,serverTimeOffset:s,isSilent:a,scheduledAt:i,sendAs:o}){const r=n.map((({id:e})=>e)),c=n.map(ee);n.forEach(((e,n)=>{const a=function(e,t,n,s){const a=fe++,{content:i,chatId:o,id:r,senderId:c,groupedId:d,isInAlbum:l}=t,u=i.audio,g=e.id===pe&&(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:pe,sendingState:"messageSendingStatePending",groupedId:d,isInAlbum:l,...c!==pe&&!u&&{forwardInfo:{date:t.date,isChannelPost:!1,fromChatId:o,fromMessageId:r,senderUserId:c}},...s&&{isScheduled:!0}}}(t,e,s,i);v.localMessages[String(c[n])]=a,zn({"@type":a.isScheduled?"newScheduledMessage":"newMessage",id:a.id,chatId:t.id,message:a})})),await jt(new g.Api.messages.ForwardMessages({fromPeer:$(e.id,e.accessHash),toPeer:$(t.id,t.accessHash),randomId:c,id:r,...a&&{sil2ent:a},...i&&{scheduleDate:i},...o&&{sendAs:$(o.id,o.accessHash)}}),!0)}async function ms({chat:e,timestamp:t}){const n=await jt(new g.Api.messages.GetHistory({peer:$(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 _s({chat:e}){const{id:t,accessHash:n}=e,s=await jt(new g.Api.messages.GetScheduledHistory({peer:$(t,n)}));if(s&&!(s instanceof g.Api.messages.MessagesNotModified)&&s.messages)return bs(s),{messages:s.messages.map(me).filter(Boolean)}}async function ys({chat:e,ids:t}){const{id:n,accessHash:s}=e;await jt(new g.Api.messages.SendScheduledMessages({peer:$(n,s),id:t}),!0)}function bs(e){e.users.forEach((e=>{e instanceof g.Api.User&&(v.users[V(e.id,"user")]=e)})),e.chats.forEach((e=>{(e instanceof g.Api.Chat||e instanceof g.Api.Channel)&&(v.chats[V(e.id,e instanceof g.Api.Chat?"chat":"channel")]=e)})),e.messages.forEach((e=>{(e instanceof g.Api.Message&&se(e)||e instanceof g.Api.MessageService&&function(e){return"photo"in e.action&&e.action.photo instanceof g.Api.Photo}(e))&&O(e)}))}async function ws({chat:e}){const t=await jt(new g.Api.messages.Search({peer:$(e.id,e.accessHash),filter:new g.Api.InputMessagesFilterPinned,q:"",limit:50}));if(t&&!(t instanceof g.Api.messages.MessagesNotModified)&&t.messages)return bs(t),{messages:t.messages.map(me).filter(Boolean),users:t.users.map(Je).filter(Boolean),chats:t.chats.map((e=>Ve(e))).filter(Boolean)}}async function Cs({chat:e,messageId:t}){const n=await jt(new g.Api.messages.GetMessageReadParticipants({peer:$(e.id,e.accessHash),msgId:t}));return n?n.map(String):void 0}async function Is({chat:e}){const t=await jt(new g.Api.channels.GetSendAs({peer:$(e.id,e.accessHash)}));if(t)return G(t.users),G(t.chats),{users:t.users.map(Je).filter(Boolean),chats:t.chats.map((e=>Ve(e))).filter(Boolean),ids:t.peers.map(N)}}function vs({sendAs:e,chat:t}){return jt(new g.Api.messages.SaveDefaultSendAs({peer:$(t.id,t.accessHash),sendAs:$(e.id,e.accessHash)}))}async function Ps({chat:e}){const t=await jt(new g.Api.channels.GetSponsoredMessages({channel:$(e.id,e.accessHash)}));if(t&&t.messages.length)return bs(t),{messages:t.messages.map(he).filter(Boolean),users:t.users.map(Je).filter(Boolean),chats:t.chats.map((e=>Ve(e))).filter(Boolean)}}async function As({chat:e,random:t}){await jt(new g.Api.channels.ViewSponsoredMessage({channel:$(e.id,e.accessHash),randomId:z(t)}))}let Ss,Ms,ks,Rs;async function Us({id:e,accessHash:t}){const n=Q(e,t);if(!(n instanceof g.Api.InputUser))return;const s=await jt(new g.Api.users.GetFullUser({id:n}));if(!s)return;const a=$e(s);Ss({"@type":"updateUser",id:e,user:{fullInfo:a.fullInfo}})}async function Es(e,t,n){const s=await jt(new g.Api.messages.GetCommonChats({userId:Q(e,t),maxId:n?le(n,W(n)):void 0,limit:100}));if(!s)return;Os(s);const a=[],i=[];return s.chats.forEach((e=>{const t=Ve(e);t&&(i.push(t),a.push(t.id))})),{chats:i,chatIds:a,isFullyLoaded:a.length<100}}async function Ds(){const e=await jt(new g.Api.help.GetNearestDc);return null==e?void 0:e.country}async function Ts(){const e=await jt(new g.Api.contacts.GetTopPeers({correspondents:!0}));if(!(e instanceof g.Api.contacts.TopPeers))return;const t=e.users.map(Je).filter((e=>!!e&&!e.isSelf));return{ids:t.map((({id:e})=>e)),users:t}}async function Bs(){const e=await jt(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[V(e.id,"user")]=e)})),{users:e.users.map(Je).filter(Boolean),chats:e.users.map((e=>Ve(e))).filter(Boolean)}}async function xs({users:e}){const t=await jt(new g.Api.users.GetUsers({id:e.map((({id:e,accessHash:t})=>$(e,t)))}));if(t&&t.length)return t.forEach((e=>{e instanceof g.Api.User&&(v.users[V(e.id,"user")]=e)})),Ze(t)}function Vs({phone:e,firstName:t,lastName:n}){return jt(new g.Api.contacts.ImportContacts({contacts:[ae({phone:e||"",firstName:t||"",lastName:n||""})]}))}function Ns({id:e,accessHash:t,phoneNumber:n="",firstName:s="",lastName:a=""}){return jt(new g.Api.contacts.AddContact({id:Q(e,t),firstName:s,lastName:a,phone:n}),!0)}async function Fs({id:e,accessHash:t}){const n=Q(e,t);n instanceof g.Api.InputUser&&await jt(new g.Api.contacts.DeleteContacts({id:[n]}))&&Ss({"@type":"deleteContact",id:e})}async function Ls(e,t){if(e){const{id:t,accessHash:n}=e,s=await jt(new g.Api.photos.GetUserPhotos({userId:Q(t,n),limit:40,offset:0,maxId:U()("0")}));if(!s)return;return Os(s),{photos:s.photos.filter((e=>e instanceof g.Api.Photo)).map(C)}}const n=await ls({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 Os(e){"chats"in e&&G(e.chats),"photos"in e&&e.photos.forEach(q)}async function qs({hash:e="0"}){const t=await jt(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(S)}}async function Hs({hash:e="0"}){const t=await jt(new g.Api.messages.GetRecentStickers({hash:U()(e)}));if(t&&!(t instanceof g.Api.messages.RecentStickersNotModified))return{hash:String(t.hash),stickers:ta(t.stickers.slice(0,20))}}async function Gs({hash:e="0"}){const t=await jt(new g.Api.messages.GetFavedStickers({hash:U()(e)}));if(t&&!(t instanceof g.Api.messages.FavedStickersNotModified))return{hash:String(t.hash),stickers:ta(t.stickers)}}async function Ks({hash:e="0"}){const t=await jt(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 zs({sticker:e,unfave:t}){const n=new g.Api.messages.FaveSticker({id:Z(e),unfave:t});await jt(n)&&Ms({"@type":"updateFavoriteStickers"})}async function Ws({stickerSetShortName:e,stickerSetId:t,accessHash:n}){const s=await jt(new g.Api.messages.GetStickerSet({stickerset:t?X(t,n):(a=e,new g.Api.InputStickerSetShortName({shortName:a}))}));var a,i;if(s instanceof g.Api.messages.StickerSet)return{set:S(s.set),stickers:ta(s.documents),packs:(i=s.packs,i.reduce(((e,{emoticon:t,documents:n})=>(e[t]=n.map((e=>A(v.documents[String(e)]))).filter(Boolean),e)),{}))}}async function js(){const e=await jt(new g.Api.messages.GetStickerSet({stickerset:new g.Api.InputStickerSetAnimatedEmoji}));if(e instanceof g.Api.messages.StickerSet)return{set:S(e.set),stickers:ta(e.documents)}}async function $s({query:e,hash:t="0"}){const n=await jt(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 Js({hash:e="0"}){const t=await jt(new g.Api.messages.GetSavedGifs({hash:U()(e)}));if(t&&!(t instanceof g.Api.messages.SavedGifsNotModified))return{hash:String(t.hash),gifs:na(t.gifs)}}async function Qs({stickerSetId:e,accessHash:t}){await jt(new g.Api.messages.InstallStickerSet({stickerset:X(e,t)}))&&Ms({"@type":"updateStickerSet",id:e,stickerSet:{installedDate:Date.now()}})}async function Xs({stickerSetId:e,accessHash:t}){await jt(new g.Api.messages.UninstallStickerSet({stickerset:X(e,t)}))&&Ms({"@type":"updateStickerSet",id:e,stickerSet:{installedDate:void 0}})}async function Zs({query:e,offset:t=""}){if(!ks){const e=await jt(new g.Api.help.GetConfig);if(!e)return;const t=await jt(new g.Api.contacts.ResolveUsername({username:e.gifSearchUsername}));if(!(t&&t.users[0]instanceof g.Api.User))return;ks=new g.Api.InputUser({userId:t.peer.userId,accessHash:t.users[0].accessHash})}const n=await jt(new g.Api.messages.GetInlineBotResults({bot:ks,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:na(s)}}async function Ys({emoji:e,hash:t="0"}){const n=await jt(new g.Api.messages.GetStickers({emoticon:e,hash:U()(t)}));if(n&&!(n instanceof g.Api.messages.StickersNotModified))return{stickers:ta(n.stickers),hash:String(n.hash)}}async function ea({language:e,fromVersion:t}){const n=await jt(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 ta(e){return e.map((e=>{if(e instanceof g.Api.Document){const t=A(e);if(t)return v.documents[String(e.id)]=e,t}})).filter(Boolean)}function na(e){return e.map((e=>{if(e instanceof g.Api.Document){const t=Ce(e);if(t)return v.documents[String(e.id)]=e,t}})).filter(Boolean)}async function sa({username:e}){try{return await jt(new g.Api.channels.CheckUsername({channel:new g.Api.InputChannelEmpty,username:e}),void 0,!0)}catch(e){return!1}}async function aa({chat:e,username:t}){await jt(new g.Api.channels.UpdateUsername({channel:Q(e.id,e.accessHash),username:t}))&&Rs({"@type":"updateChat",id:e.id,chat:{username:t}})}async function ia({chat:e,usageLimit:t,expireDate:n}){const s=await jt(new g.Api.messages.ExportChatInvite({peer:$(e.id,e.accessHash),usageLimit:t,expireDate:n}));if(s)return Rs({"@type":"updateChatFullInfo",id:e.id,fullInfo:{inviteLink:s.link}}),s.link}const oa={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"},ra={};let ca,da;async function la(){const e=await jt(new g.Api.account.GetPassword);if(!e)return;const{hint:t,hasPassword:n}=e;return{hint:t,hasPassword:n}}function ua(e){return ca({"@type":"updateTwoFaStateWaitCode",length:e}),new Promise(((e,t)=>{ra.resolve=e,ra.reject=t}))}async function ga(e){try{return await Qt({isCheckPassword:!0,currentPassword:e}),!0}catch(e){return _a(e),!1}}async function pa(e){try{return await Qt({currentPassword:e}),!0}catch(e){return _a(e),!1}}async function fa(e,t,n,s){try{return await Qt({currentPassword:e,newPassword:t,hint:n,email:s,emailCodeCallback:ua,onEmailCodeError:_a}),!0}catch(e){return _a(e),!1}}async function ha(e,t){try{return await Qt({currentPassword:e,newPassword:e,email:t,emailCodeCallback:ua,onEmailCodeError:_a}),!0}catch(e){return _a(e),!1}}function ma(e){ra.resolve(e)}function _a(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=oa[e.message];t||(t="Unexpected Error"),ca({"@type":"updateTwoFaError",message:t})}async function ya({call:e}){const t=await jt(new g.Api.phone.GetGroupCall({call:ue(e)}));if(!t)return;G(t.users),G(t.chats);const n=t.users.map(Je).filter(Boolean),s=t.chats.map((e=>Ve(e))).filter(Boolean);return{groupCall:rt(t.call),users:n,chats:s}}function ba({call:e}){return jt(new g.Api.phone.DiscardGroupCall({call:ue(e)}),!0)}function wa({call:e,participant:t,muted:n,presentationPaused:s,videoStopped:a,videoPaused:i,volume:o,raiseHand:r}){return jt(new g.Api.phone.EditGroupCallParticipant({call:ue(e),participant:$(t.id,t.accessHash),...void 0!==a&&{videoStopped:a},...void 0!==i&&{videoPaused:i},...void 0!==n&&{muted:n},...void 0!==s&&{presentationPaused:s},...void 0!==r&&{raiseHand:r},...void 0!==o&&{volume:o}}),!0)}function Ca({groupCall:e,title:t}){return jt(new g.Api.phone.EditGroupCallTitle({title:t,call:ue(e)}),!0)}async function Ia({call:e,canSelfUnmute:t}){const n=await jt(new g.Api.phone.ExportGroupCallInvite({canSelfUnmute:t||void 0,call:ue(e)}));if(n)return n.link}async function va({call:e,offset:t}){const n=await jt(new g.Api.phone.GetGroupParticipants({call:ue(e),ids:[],sources:[],offset:t||"",limit:100}));if(!n)return;G(n.users),G(n.chats);const s=n.users.map(Je).filter(Boolean),a=n.chats.map((e=>Ve(e))).filter(Boolean);return da({"@type":"updateGroupCallParticipants",groupCallId:e.id,participants:n.participants.map(at),nextOffset:n.nextOffset}),{users:s,chats:a}}function Pa({call:e}){return jt(new g.Api.phone.LeaveGroupCall({call:ue(e)}),!0)}async function Aa({call:e,inviteHash:t,params:n}){const s=await jt(new g.Api.phone.JoinGroupCall({call:ue(e),joinAs:new g.Api.InputPeerSelf,muted:!0,videoStopped:!0,params:new g.Api.DataJSON({data:JSON.stringify(n)}),inviteHash:t}),!0);if(s&&s instanceof g.Api.Updates){const e=s.updates.find((e=>e instanceof g.Api.UpdateGroupCall));if(!(e instanceof g.Api.UpdateGroupCall))return;return rt(e.call)}}async function Sa({peer:e}){const t=(0,E.readBigIntFromBuffer)((0,E.generateRandomBytes)(4),!0,!0).toJSNumber(),n=await jt(new g.Api.phone.CreateGroupCall({peer:$(e.id,e.accessHash),randomId:t}),!0);if(n&&n instanceof g.Api.Updates){const e=n.updates[0];if(e instanceof g.Api.UpdateGroupCall)return rt(e.call)}}function Ma({call:e,params:t}){return jt(new g.Api.phone.JoinGroupCallPresentation({call:ue(e),params:new g.Api.DataJSON({data:JSON.stringify(t)})}),!0)}function ka({call:e,subscribed:t}){return jt(new g.Api.phone.ToggleGroupCallStartSubscription({call:ue(e),subscribed:t}),!0)}function Ra({call:e}){return jt(new g.Api.phone.LeaveGroupCallPresentation({call:ue(e)}),!0)}const Ua=["ar","fa","id","ko","uz"];function Ea({firstName:e,lastName:t,about:n}){return jt(new g.Api.account.UpdateProfile({firstName:e||"",lastName:t||"",about:n||""}))}function Da(e){return jt(new g.Api.account.CheckUsername({username:e}))}function Ta(e){return jt(new g.Api.account.UpdateUsername({username:e}))}async function Ba(e){const t=await Jt(e);return jt(new g.Api.photos.UploadProfilePhoto({file:t}))}async function xa(e){const t=await Jt(e);await jt(new g.Api.photos.UploadProfilePhoto({file:t}))}async function Va(){const e=await jt(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(Ye).filter(Boolean)}}async function Na(e){const t=await Jt(e),n=await jt(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=Ye(n);return s?(v.documents[String(n.document.id)]=n.document,{wallpaper:s}):void 0}async function Fa(){const e=await jt(new g.Api.contacts.GetBlocked({limit:100}));if(e)return ai(e),{users:e.users.map(Je).filter(Boolean),chats:e.chats.map((e=>Ve(e,void 0,!0))).filter(Boolean),blockedIds:e.blocked.map((e=>N(e.peerId))),totalCount:e instanceof g.Api.contacts.BlockedSlice?e.count:e.blocked.length}}function La(e,t){return jt(new g.Api.contacts.Block({id:$(e,t)}))}function Oa(e,t){return jt(new g.Api.contacts.Unblock({id:$(e,t)}))}async function qa(){const e=await jt(new g.Api.account.GetAuthorizations);if(e)return e.authorizations.map(et)}function Ha(e){return jt(new g.Api.account.ResetAuthorization({hash:U()(e)}))}function Ga(){return jt(new g.Api.auth.ResetAuthorizations)}async function Ka({serverTimeOffset:e}){const t=await jt(new g.Api.account.GetNotifyExceptions({compareSound:!0}));if(t instanceof g.Api.Updates||t instanceof g.Api.UpdatesCombined)return ai(t),t.updates.reduce(((t,n)=>n instanceof g.Api.UpdateNotifySettings&&n.peer instanceof g.Api.NotifyPeer?(t.push(nt(n.notifySettings,n.peer.peer,e)),t):t),[])}async function za({serverTimeOffset:e}){const[t,n,s,a]=await Promise.all([jt(new g.Api.account.GetContactSignUpNotification),jt(new g.Api.account.GetNotifySettings({peer:new g.Api.InputNotifyUsers})),jt(new g.Api.account.GetNotifySettings({peer:new g.Api.InputNotifyChats})),jt(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&&Ue(e)jt(new g.Api.langpack.GetLangPack({langPack:e,langCode:Ua.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 Qa({langPack:e,langCode:t,keys:n}){const s=await jt(new g.Api.langpack.GetStrings({langPack:e,langCode:Ua.includes(t)?`${t}-raw`:t,keys:n}));if(s)return s.map(_)}async function Xa(e){const t=ce(e),n=await jt(new g.Api.account.GetPrivacy({key:t}));if(n)return ai(n),tt(n.rules)}function Za(e){const t=qt.session.getAuthKey().getKey();return jt(new g.Api.account.RegisterDevice({tokenType:10,secret:t,appSandbox:!1,otherUids:[],token:e}))}function Ya(e){return jt(new g.Api.account.UnregisterDevice({tokenType:10,otherUids:[],token:e}))}async function ei(e,t){const n=ce(e),s=[];switch(t.allowedUsers&&s.push(new g.Api.InputPrivacyValueAllowUsers({users:t.allowedUsers.map((({id:e,accessHash:t})=>Q(e,t)))})),t.allowedChats&&s.push(new g.Api.InputPrivacyValueAllowChatParticipants({chats:t.allowedChats.map((({id:e})=>Q(e)))})),t.blockedUsers&&s.push(new g.Api.InputPrivacyValueDisallowUsers({users:t.blockedUsers.map((({id:e,accessHash:t})=>Q(e,t)))})),t.blockedChats&&s.push(new g.Api.InputPrivacyValueDisallowChatParticipants({chats:t.blockedChats.map((({id:e})=>Q(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 jt(new g.Api.account.SetPrivacy({key:n,rules:s}));if(a)return ai(a),tt(a.rules)}async function ti(e){await jt(new g.Api.account.UpdateStatus({offline:!e}))}async function ni(){const e=await jt(new g.Api.account.GetContentSettings);if(e)return{isSensitiveEnabled:Boolean(e.sensitiveEnabled),canChangeSensitive:Boolean(e.sensitiveCanChange)}}function si(e){return jt(new g.Api.account.SetContentSettings({sensitiveEnabled:e||void 0}))}function ai(e){e.users.forEach((e=>{e instanceof g.Api.User&&(v.users[V(e.id,"user")]=e)})),e.chats.forEach((e=>{(e instanceof g.Api.Chat||e instanceof g.Api.Channel)&&(v.chats[V(e.id,e instanceof g.Api.Chat?"chat":"channel")]=e)}))}async function ii({langCode:e="en"}){const t=await jt(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=>st(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=>st(e))).sort(((e,t)=>e.name?e.name.localeCompare(t.name):e.defaultName.localeCompare(t.defaultName)))};var n,s}function oi(e){return e?f(e,["url","mimeType"]):void 0}function ri({chatId:e,accessHash:t,messageId:n,data:s}){return jt(new g.Api.messages.GetBotCallbackAnswer({peer:$(e,t),msgId:n,data:z(s)}))}async function ci(){const e=await jt(new g.Api.contacts.GetTopPeers({botsInline:!0}));if(!(e instanceof g.Api.contacts.TopPeers))return;const t=e.users.map(Je).filter(Boolean);return{ids:t.map((({id:e})=>e)),users:t}}async function di({username:e}){const t=await jt(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 H(t.users[0]),{user:Je(t.users[0]),chat:Ve(t.users[0])}}async function li({bot:e,chat:t,query:n,offset:s=""}){const a=await jt(new g.Api.messages.GetInlineBotResults({bot:$(e.id,e.accessHash),peer:$(t.id,t.accessHash),query:n,offset:s}));var i,o,r,c,d;if(a)return G(a.users),{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(Je).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:A(r)},...o instanceof g.Api.Photo&&{photo:C(o)},..."gif"===s&&r instanceof g.Api.Document&&{gif:Ce(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:oi(r)}}(e,i));var t,n,s})))}}async function ui({chat:e,resultId:t,queryId:n,replyingTo:s,sendAs:a}){const i=ee();await jt(new g.Api.messages.SendInlineBotResult({clearDraft:!0,randomId:i,queryId:U()(n),peer:$(e.id,e.accessHash),id:t,...s&&{replyToMsgId:s},...a&&{sendAs:$(a.id,a.accessHash)}}),!0)}async function gi({bot:e,startParam:t}){const n=ee();await jt(new g.Api.messages.StartBot({bot:$(e.id,e.accessHash),peer:$(e.id,e.accessHash),randomId:n,startParam:t}),!0)}function pi(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 fi({chat:e,messageId:t,requestInfo:n,shouldSave:s}){const a=await jt(new g.Api.payments.ValidateRequestedInfo({peer:$(e.id,e.accessHash),msgId:t,save:s||void 0,info:re(n)}));if(!a)return;const{id:i,shippingOptions:o}=a;return i?{id:i,shippingOptions:pi(o)}:void 0}function hi({chat:e,messageId:t,formId:n,requestedInfoId:s,shippingOptionId:a,credentials:i}){return jt(new g.Api.payments.SendPaymentForm({formId:U()(n),peer:$(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 mi({chat:e,messageId:t}){const n=await jt(new g.Api.payments.GetPaymentForm({peer:$(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 _i(e,t){const n=await jt(new g.Api.payments.GetPaymentReceipt({peer:$(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 yi;async function bi(e,t){yi=e,function(e){ct=e}(Pi),function(e){mt=e}(Pi),function(e){Yt=e}(Pi),function(e){zn=e}(Pi),function(e){Ss=e}(Pi),function(e){Ms=e}(Pi),function(e){Rs=e}(Pi),function(e){ca=e}(Pi),function(e){da=e}(Pi),await async function(e,t){Ot=e;const{userAgent:n,platform:s,sessionData:a,isTest:i,isMovSupported:o}=t,r=new g.sessions.CallbackSession(a,zt);self.isMovSupported=o,qt=new g.TelegramClient(r,"2496","8da85b0d5bfe62527e5b244c209159c3",{deviceModel:navigator.userAgent||n||"Unknown UserAgent",systemVersion:s||"Unknown platform",appVersion:"1.28.5 Z",useWSS:!0,additionalDcsDisabled:!1,testServers:i}),qt.addEventHandler(Wt,Lt),qt.addEventHandler(pt,Lt);try{try{await qt.start({phoneNumber:_t,phoneCode:yt,password:bt,firstAndLastNames:wt,qrCode:Ct,onError:It,initialMethod:"iOS"===s||"Android"===s?"phoneNumber":"qrCode"})}catch(e){if("Disconnect"!==e.message)return void Ot({"@type":"updateConnectionState",connectionState:"connectionStateBroken"})}mt(vt("authorizationStateReady")),zt(r.getSessionData()),Ot({"@type":"updateApiReady"}),Xt()}catch(e){throw e}}(Pi,t)}const wi=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(!vi||e!==Ii)return;const t=vi;vi=void 0,t.forEach(yi)}));let Ci,Ii,vi;function Pi(e){vi?vi.push(e):vi=[e],Ci&&!o.has(e["@type"])||(Ci=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))}}(wi,i,!0),Ii=Math.random()),Ci(Ii)}self.onerror=e=>{console.error(e),Mi({type:"unhandledError",error:{message:e.error.message||"Uncaught exception in worker"}})},self.addEventListener("unhandledrejection",(e=>{console.error(e),Mi({type:"unhandledError",error:{message:e.reason.message||"Uncaught rejection in worker"}})}));const Ai=new Map;function Si(e){Mi({type:"update",update:e})}function Mi(e,t){t?postMessage(e,[t]):postMessage(e)}onmessage=async e=>{const{data:t}=e;switch(t.type){case"initApi":await bi(Si,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];Mi({type:"methodCallback",messageId:e,callbackArgs:t},n instanceof ArrayBuffer?n:void 0)};Ai.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&&Mi({type:"methodResponse",messageId:e,response:t},i)}catch(t){e&&Mi({type:"methodResponse",messageId:e,error:{message:t.message}})}e&&Ai.delete(e);break}case"cancelProgress":{const e=Ai.get(t.messageId);e&&(e.isCanceled=!0);break}case"ping":Mi({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 D=U.multiply(C),T=k.add(D),B=l(E,T,g),[x,V,N,F,L]=await Promise.all([c(h(B)),c(I),c(v),c(n.salt1),c(n.salt2)]),O=await c(s.concat([_(V,N),F,L,R,P,x]));return new i.InputCheckPasswordSRP({srpId:e.srpId,A:s.from(R),M1:O})},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),A=r?r+1-m:void 0;return d.concat(P,A)}},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),A=l.concat([C,P]),S=l.from(A).reverse();let M;for(let e=0;e<20;e++){const e=h.generateRandomBytes(32),n=await h.sha256(l.concat([e,A])),s=l.concat([S,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),D=E.decryptIge(k.encryptedAnswer),T=new m(D);T.read(20);const B=T.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),L=h.modExp(u(B.g),F,x),O=h.modExp(V,F,x),q=new(a().ClientDHInnerData)({nonce:o.nonce,serverNonce:o.serverNonce,retryId:u.zero,gB:h.getByteArray(L,!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(O));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{RPCError:s}=n(7873),a=n(5585),i=n(9109),o=n(9618),r=n(3302),{doAuthentication:c}=n(9870),d=n(2301),l=n(3254),u=n(8963),g=n(4287),{MsgsAck:p,upload:f,MsgsStateInfo:h,Pong:m}=n(7404).constructors,_=n(6411),y=n(5544),{UpdateConnectionState:b,UpdateServerTimeOffset:w}=n(8415),{BadMessageError:C}=n(8187),{BadServerSalt:I,BadMsgNotification:v,MsgDetailedInfo:P,MsgNewDetailedInfo:A,NewSessionCreated:S,FutureSalts:M,MsgsStateReq:k,MsgResendReq:R,MsgsAllInfo:U}=n(7404).constructors,{SecurityError:E}=n(8187),{InvalidBufferError:D}=n(8187),{LogOut:T}=n(7404).requests.auth,{RPCMessageToError:B}=n(7873),{TypeNotFoundError:x}=n(8187);class V{constructor(e,t){const n={...V.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 r,this._state=new i(this.authKey,this._log),this._send_queue=new _(this._state,this._log),this._pending_state={},this._pending_ack=new Set,this._last_acks=[],this._handlers={[d.CONSTRUCTOR_ID]:this._handleRPCResult.bind(this),[l.CONSTRUCTOR_ID]:this._handleContainer.bind(this),[u.CONSTRUCTOR_ID]:this._handleGzipPacked.bind(this),[m.CONSTRUCTOR_ID]:this._handlePong.bind(this),[I.CONSTRUCTOR_ID]:this._handleBadServerSalt.bind(this),[v.CONSTRUCTOR_ID]:this._handleBadNotification.bind(this),[P.CONSTRUCTOR_ID]:this._handleDetailedInfo.bind(this),[A.CONSTRUCTOR_ID]:this._handleNewDetailedInfo.bind(this),[S.CONSTRUCTOR_ID]:this._handleNewSessionCreated.bind(this),[p.CONSTRUCTOR_ID]:this._handleAck.bind(this),[M.CONSTRUCTOR_ID]:this._handleFutureSalts.bind(this),[k.CONSTRUCTOR_ID]:this._handleStateForgotten.bind(this),[R.CONSTRUCTOR_ID]:this._handleStateForgotten.bind(this),[U.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 x){this._log.info(`Type ${e.invalidConstructorId} not found, remaining data ${e.remaining}`);continue}if(e instanceof E){this._log.warn(`Security error while unpacking a received message: ${e}`);continue}return e instanceof D?void(404===e.code?this._handleBadAuthKey():(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){e instanceof s?"AUTH_KEY_UNREGISTERED"===e.message&&this._handleBadAuthKey(!0):(this._log.error("Unhandled error while receiving data"),this._log.error(e))}}}_handleBadAuthKey(e){e&&this._isMainSender||(this._log.warn(`Broken authorization key for dc ${this._dcId}, resetting...`),this._isMainSender&&this._updateCallback?this._updateCallback(new b(b.broken)):!this._isMainSender&&this._onConnectionBreak&&this._onConnectionBreak(this._dcId))}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 y(t.body).tgReadObject()instanceof f.File))throw new x("Not an upload.File")}catch(e){if(this._log.error(e),e instanceof x)return void this._log.info(`Received response without parent request: ${t.body}`);throw e}if(t.error){const e=B(t.error,n.request);throw this._send_queue.append(new g(new p({msgIds:[n.msgId]}))),n.reject(e),e}try{const e=new y(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 y(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 w(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 w(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 C(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 g(new h(e.msgId,String.fromCharCode(1).repeat(e.obj.msgIds))))}_handleMsgAll(e){}reconnect(){this._user_connected&&!this._reconnecting&&(this._reconnecting=!0,o.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 N,F,L;L={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},(F="DEFAULT_OPTIONS")in(N=V)?Object.defineProperty(N,F,{value:L,enumerable:!0,configurable:!0,writable:!0}):N[F]=L,e.exports=V},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.msgIds=[],this.reset()}reset(){this.id=i.generateRandomLong(!0),this._sequence=0,this._lastMsgId=a(0),this.msgIds=[]}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();if(this.msgIds.includes(p.toString()))throw new l("Duplicate msgIds");this.msgIds.length>500&&this.msgIds.shift(),this.msgIds.push(p.toString());const 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:136,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 noforwards:flags.25?true id:long title:string photo:ChatPhoto participants_count:int date:int version:int migrated_to:flags.6?InputChannel admin_rights:flags.14?ChatAdminRights default_banned_rights:flags.18?ChatBannedRights = Chat;\nchatForbidden#6592a1a7 id:long title:string = Chat;\nchannel#8261ac61 flags:# creator:flags.0?true left:flags.2?true broadcast:flags.5?true verified:flags.7?true megagroup:flags.8?true restricted:flags.9?true signatures:flags.11?true min:flags.12?true scam:flags.19?true has_link:flags.20?true has_geo:flags.21?true slowmode_enabled:flags.22?true call_active:flags.23?true call_not_empty:flags.24?true fake:flags.25?true gigagroup:flags.26?true noforwards:flags.27?true id:long access_hash:flags.13?long title:string username:flags.6?string photo:ChatPhoto date:int restriction_reason:flags.9?Vector admin_rights:flags.14?ChatAdminRights banned_rights:flags.15?ChatBannedRights default_banned_rights:flags.18?ChatBannedRights participants_count:flags.17?int = Chat;\nchannelForbidden#17d493d5 flags:# broadcast:flags.5?true megagroup:flags.8?true id:long access_hash:long title:string until_date:flags.16?int = Chat;\nchatFull#d18ee226 flags:# can_set_username:flags.7?true has_scheduled:flags.8?true id:long about:string participants:ChatParticipants chat_photo:flags.2?Photo notify_settings:PeerNotifySettings exported_invite:flags.13?ExportedChatInvite bot_info:flags.3?Vector pinned_msg_id:flags.6?int folder_id:flags.11?int call:flags.12?InputGroupCall ttl_period:flags.14?int groupcall_default_join_as:flags.15?Peer theme_emoticon:flags.16?string requests_pending:flags.17?int recent_requesters:flags.17?Vector available_reactions:flags.18?Vector = ChatFull;\nchannelFull#e13c3d20 flags:# can_view_participants:flags.3?true can_set_username:flags.6?true can_set_stickers:flags.7?true hidden_prehistory:flags.10?true can_set_location:flags.16?true has_scheduled:flags.19?true can_view_stats:flags.20?true blocked:flags.22?true id:long about:string participants_count:flags.0?int admins_count:flags.1?int kicked_count:flags.2?int banned_count:flags.2?int online_count:flags.13?int read_inbox_max_id:int read_outbox_max_id:int unread_count:int chat_photo:Photo notify_settings:PeerNotifySettings exported_invite:flags.23?ExportedChatInvite bot_info:Vector migrated_from_chat_id:flags.4?long migrated_from_max_id:flags.4?int pinned_msg_id:flags.5?int stickerset:flags.8?StickerSet available_min_id:flags.9?int folder_id:flags.11?int linked_chat_id:flags.14?long location:flags.15?ChannelLocation slowmode_seconds:flags.17?int slowmode_next_send_date:flags.18?int stats_dc:flags.12?int pts:int call:flags.21?InputGroupCall ttl_period:flags.24?int pending_suggestions:flags.25?Vector groupcall_default_join_as:flags.26?Peer theme_emoticon:flags.27?string requests_pending:flags.28?int recent_requesters:flags.28?Vector default_send_as:flags.29?Peer available_reactions:flags.30?Vector = ChatFull;\nchatParticipant#c02d4007 user_id:long inviter_id:long date:int = ChatParticipant;\nchatParticipantCreator#e46bcee4 user_id:long = ChatParticipant;\nchatParticipantAdmin#a0933f5b user_id:long inviter_id:long date:int = ChatParticipant;\nchatParticipantsForbidden#8763d3e1 flags:# chat_id:long self_participant:flags.0?ChatParticipant = ChatParticipants;\nchatParticipants#3cbc93f8 chat_id:long participants:Vector version:int = ChatParticipants;\nchatPhotoEmpty#37c1011c = ChatPhoto;\nchatPhoto#1c6e1c11 flags:# has_video:flags.0?true photo_id:long stripped_thumb:flags.1?bytes dc_id:int = ChatPhoto;\nmessageEmpty#90a6ca84 flags:# id:int peer_id:flags.0?Peer = Message;\nmessage#38116ee0 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true post:flags.14?true from_scheduled:flags.18?true legacy:flags.19?true edit_hide:flags.21?true pinned:flags.24?true noforwards:flags.26?true id:int from_id:flags.8?Peer peer_id:Peer fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?long reply_to:flags.3?MessageReplyHeader date:int message:string media:flags.9?MessageMedia reply_markup:flags.6?ReplyMarkup entities:flags.7?Vector views:flags.10?int forwards:flags.10?int replies:flags.23?MessageReplies edit_date:flags.15?int post_author:flags.16?string grouped_id:flags.17?long reactions:flags.20?MessageReactions restriction_reason:flags.22?Vector ttl_period:flags.25?int = Message;\nmessageService#2b085862 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true post:flags.14?true legacy:flags.19?true id:int from_id:flags.8?Peer peer_id:Peer reply_to:flags.3?MessageReplyHeader date:int action:MessageAction ttl_period:flags.25?int = Message;\nmessageMediaEmpty#3ded6320 = MessageMedia;\nmessageMediaPhoto#695150d7 flags:# photo:flags.0?Photo ttl_seconds:flags.2?int = MessageMedia;\nmessageMediaGeo#56e0d474 geo:GeoPoint = MessageMedia;\nmessageMediaContact#70322949 phone_number:string first_name:string last_name:string vcard:string user_id:long = MessageMedia;\nmessageMediaUnsupported#9f84f49e = MessageMedia;\nmessageMediaDocument#9cb070d7 flags:# document:flags.0?Document ttl_seconds:flags.2?int = MessageMedia;\nmessageMediaWebPage#a32dd600 webpage:WebPage = MessageMedia;\nmessageMediaVenue#2ec0533f geo:GeoPoint title:string address:string provider:string venue_id:string venue_type:string = MessageMedia;\nmessageMediaGame#fdb19008 game:Game = MessageMedia;\nmessageMediaInvoice#84551347 flags:# shipping_address_requested:flags.1?true test:flags.3?true title:string description:string photo:flags.0?WebDocument receipt_msg_id:flags.2?int currency:string total_amount:long start_param:string = MessageMedia;\nmessageMediaGeoLive#b940c666 flags:# geo:GeoPoint heading:flags.0?int period:int proximity_notification_radius:flags.1?int = MessageMedia;\nmessageMediaPoll#4bd6e798 poll:Poll results:PollResults = MessageMedia;\nmessageMediaDice#3f7ee58b value:int emoticon:string = MessageMedia;\nmessageActionEmpty#b6aef7b0 = MessageAction;\nmessageActionChatCreate#bd47cbad title:string users:Vector = MessageAction;\nmessageActionChatEditTitle#b5a1ce5a title:string = MessageAction;\nmessageActionChatEditPhoto#7fcb13a8 photo:Photo = MessageAction;\nmessageActionChatDeletePhoto#95e3fbef = MessageAction;\nmessageActionChatAddUser#15cefd00 users:Vector = MessageAction;\nmessageActionChatDeleteUser#a43f30cc user_id:long = MessageAction;\nmessageActionChatJoinedByLink#31224c3 inviter_id:long = MessageAction;\nmessageActionChannelCreate#95d2ac92 title:string = MessageAction;\nmessageActionChatMigrateTo#e1037f92 channel_id:long = MessageAction;\nmessageActionChannelMigrateFrom#ea3948e9 title:string chat_id:long = MessageAction;\nmessageActionPinMessage#94bd38ed = MessageAction;\nmessageActionHistoryClear#9fbab604 = MessageAction;\nmessageActionGameScore#92a72876 game_id:long score:int = MessageAction;\nmessageActionPaymentSentMe#8f31b327 flags:# currency:string total_amount:long payload:bytes info:flags.0?PaymentRequestedInfo shipping_option_id:flags.1?string charge:PaymentCharge = MessageAction;\nmessageActionPaymentSent#40699cd0 currency:string total_amount:long = MessageAction;\nmessageActionPhoneCall#80e11a7f flags:# video:flags.2?true call_id:long reason:flags.0?PhoneCallDiscardReason duration:flags.1?int = MessageAction;\nmessageActionScreenshotTaken#4792929b = MessageAction;\nmessageActionCustomAction#fae69f56 message:string = MessageAction;\nmessageActionBotAllowed#abe9affe domain:string = MessageAction;\nmessageActionSecureValuesSentMe#1b287353 values:Vector credentials:SecureCredentialsEncrypted = MessageAction;\nmessageActionSecureValuesSent#d95c6154 types:Vector = MessageAction;\nmessageActionContactSignUp#f3f25f76 = MessageAction;\nmessageActionGeoProximityReached#98e0d697 from_id:Peer to_id:Peer distance:int = MessageAction;\nmessageActionGroupCall#7a0d7f42 flags:# call:InputGroupCall duration:flags.0?int = MessageAction;\nmessageActionInviteToGroupCall#502f92f7 call:InputGroupCall users:Vector = MessageAction;\nmessageActionSetMessagesTTL#aa1afbfd period:int = MessageAction;\nmessageActionGroupCallScheduled#b3a07661 call:InputGroupCall schedule_date:int = MessageAction;\nmessageActionSetChatTheme#aa786345 emoticon:string = MessageAction;\nmessageActionChatJoinedByRequest#ebbca3cb = MessageAction;\ndialog#2c171f72 flags:# pinned:flags.2?true unread_mark:flags.3?true peer:Peer top_message:int read_inbox_max_id:int read_outbox_max_id:int unread_count:int unread_mentions_count:int notify_settings:PeerNotifySettings pts:flags.0?int draft:flags.1?DraftMessage folder_id:flags.4?int = Dialog;\ndialogFolder#71bd134c flags:# pinned:flags.2?true folder:Folder peer:Peer top_message:int unread_muted_peers_count:int unread_unmuted_peers_count:int unread_muted_messages_count:int unread_unmuted_messages_count:int = Dialog;\nphotoEmpty#2331b22d id:long = Photo;\nphoto#fb197a65 flags:# has_stickers:flags.0?true id:long access_hash:long file_reference:bytes date:int sizes:Vector video_sizes:flags.1?Vector dc_id:int = Photo;\nphotoSizeEmpty#e17e23c type:string = PhotoSize;\nphotoSize#75c78e60 type:string w:int h:int size:int = PhotoSize;\nphotoCachedSize#21e1ad6 type:string w:int h:int bytes:bytes = PhotoSize;\nphotoStrippedSize#e0b0bc2e type:string bytes:bytes = PhotoSize;\nphotoSizeProgressive#fa3efb95 type:string w:int h:int sizes:Vector = PhotoSize;\nphotoPathSize#d8214d41 type:string bytes:bytes = PhotoSize;\ngeoPointEmpty#1117dd5f = GeoPoint;\ngeoPoint#b2a2f663 flags:# long:double lat:double access_hash:long accuracy_radius:flags.0?int = GeoPoint;\nauth.sentCode#5e002502 flags:# type:auth.SentCodeType phone_code_hash:string next_type:flags.1?auth.CodeType timeout:flags.2?int = auth.SentCode;\nauth.authorization#33fb7bb8 flags:# setup_password_required:flags.1?true otherwise_relogin_days:flags.1?int tmp_sessions:flags.0?int user:User = auth.Authorization;\nauth.authorizationSignUpRequired#44747e9a flags:# terms_of_service:flags.0?help.TermsOfService = auth.Authorization;\nauth.exportedAuthorization#b434e2b8 id:long bytes:bytes = auth.ExportedAuthorization;\ninputNotifyPeer#b8bc5b0c peer:InputPeer = InputNotifyPeer;\ninputNotifyUsers#193b4417 = InputNotifyPeer;\ninputNotifyChats#4a95e84e = InputNotifyPeer;\ninputNotifyBroadcasts#b1db7c7e = InputNotifyPeer;\ninputPeerNotifySettings#9c3d198e flags:# show_previews:flags.0?Bool silent:flags.1?Bool mute_until:flags.2?int sound:flags.3?string = InputPeerNotifySettings;\npeerNotifySettings#af509d20 flags:# show_previews:flags.0?Bool silent:flags.1?Bool mute_until:flags.2?int sound:flags.3?string = PeerNotifySettings;\npeerSettings#a518110d flags:# report_spam:flags.0?true add_contact:flags.1?true block_contact:flags.2?true share_contact:flags.3?true need_contacts_exception:flags.4?true report_geo:flags.5?true autoarchived:flags.7?true invite_members:flags.8?true request_chat_broadcast:flags.10?true geo_distance:flags.6?int request_chat_title:flags.9?string request_chat_date:flags.9?int = PeerSettings;\nwallPaper#a437c3ed id:long flags:# creator:flags.0?true default:flags.1?true pattern:flags.3?true dark:flags.4?true access_hash:long slug:string document:Document settings:flags.2?WallPaperSettings = WallPaper;\nwallPaperNoFile#e0804116 id:long flags:# default:flags.1?true dark:flags.4?true settings:flags.2?WallPaperSettings = WallPaper;\ninputReportReasonSpam#58dbcab8 = ReportReason;\ninputReportReasonViolence#1e22c78d = ReportReason;\ninputReportReasonPornography#2e59d922 = ReportReason;\ninputReportReasonChildAbuse#adf44ee3 = ReportReason;\ninputReportReasonOther#c1e4a2b1 = ReportReason;\ninputReportReasonCopyright#9b89f93a = ReportReason;\ninputReportReasonGeoIrrelevant#dbd4feed = ReportReason;\ninputReportReasonFake#f5ddd6e7 = ReportReason;\nuserFull#cf366521 flags:# blocked:flags.0?true phone_calls_available:flags.4?true phone_calls_private:flags.5?true can_pin_message:flags.7?true has_scheduled:flags.12?true video_calls_available:flags.13?true id:long about:flags.1?string settings:PeerSettings profile_photo:flags.2?Photo notify_settings:PeerNotifySettings bot_info:flags.3?BotInfo pinned_msg_id:flags.6?int common_chats_count:int folder_id:flags.11?int ttl_period:flags.14?int theme_emoticon:flags.15?string private_forward_name:flags.16?string = UserFull;\ncontact#145ade0b user_id:long mutual:Bool = Contact;\nimportedContact#c13e3c50 user_id:long client_id:long = ImportedContact;\ncontactStatus#16d9703b user_id:long status:UserStatus = ContactStatus;\ncontacts.contactsNotModified#b74ba9d2 = contacts.Contacts;\ncontacts.contacts#eae87e42 contacts:Vector saved_count:int users:Vector = contacts.Contacts;\ncontacts.importedContacts#77d01c3b imported:Vector popular_invites:Vector retry_contacts:Vector users:Vector = contacts.ImportedContacts;\ncontacts.blocked#ade1591 blocked:Vector chats:Vector users:Vector = contacts.Blocked;\ncontacts.blockedSlice#e1664194 count:int blocked:Vector chats:Vector users:Vector = contacts.Blocked;\nmessages.dialogs#15ba6c40 dialogs:Vector messages:Vector chats:Vector users:Vector = messages.Dialogs;\nmessages.dialogsSlice#71e094f3 count:int dialogs:Vector messages:Vector chats:Vector users:Vector = messages.Dialogs;\nmessages.dialogsNotModified#f0e3e596 count:int = messages.Dialogs;\nmessages.messages#8c718e87 messages:Vector chats:Vector users:Vector = messages.Messages;\nmessages.messagesSlice#3a54685e flags:# inexact:flags.1?true count:int next_rate:flags.0?int offset_id_offset:flags.2?int messages:Vector chats:Vector users:Vector = messages.Messages;\nmessages.channelMessages#64479808 flags:# inexact:flags.1?true pts:int count:int offset_id_offset:flags.2?int messages:Vector chats:Vector users:Vector = messages.Messages;\nmessages.messagesNotModified#74535f21 count:int = messages.Messages;\nmessages.chats#64ff9fd5 chats:Vector = messages.Chats;\nmessages.chatsSlice#9cd81144 count:int chats:Vector = messages.Chats;\nmessages.chatFull#e5d7d19c full_chat:ChatFull chats:Vector users:Vector = messages.ChatFull;\nmessages.affectedHistory#b45c69d1 pts:int pts_count:int offset:int = messages.AffectedHistory;\ninputMessagesFilterEmpty#57e2f66c = MessagesFilter;\ninputMessagesFilterPhotos#9609a51c = MessagesFilter;\ninputMessagesFilterVideo#9fc00e65 = MessagesFilter;\ninputMessagesFilterPhotoVideo#56e9f0e4 = MessagesFilter;\ninputMessagesFilterDocument#9eddf188 = MessagesFilter;\ninputMessagesFilterUrl#7ef0dd87 = MessagesFilter;\ninputMessagesFilterGif#ffc86587 = MessagesFilter;\ninputMessagesFilterVoice#50f5c392 = MessagesFilter;\ninputMessagesFilterMusic#3751b49e = MessagesFilter;\ninputMessagesFilterChatPhotos#3a20ecb8 = MessagesFilter;\ninputMessagesFilterPhoneCalls#80c99768 flags:# missed:flags.0?true = MessagesFilter;\ninputMessagesFilterRoundVoice#7a7c17a4 = MessagesFilter;\ninputMessagesFilterRoundVideo#b549da53 = MessagesFilter;\ninputMessagesFilterMyMentions#c1f8e69a = MessagesFilter;\ninputMessagesFilterGeo#e7026d0d = MessagesFilter;\ninputMessagesFilterContacts#e062db83 = MessagesFilter;\ninputMessagesFilterPinned#1bb00451 = MessagesFilter;\nupdateNewMessage#1f2b0afd message:Message pts:int pts_count:int = Update;\nupdateMessageID#4e90bfd6 id:int random_id:long = Update;\nupdateDeleteMessages#a20db0e5 messages:Vector pts:int pts_count:int = Update;\nupdateUserTyping#c01e857f user_id:long action:SendMessageAction = Update;\nupdateChatUserTyping#83487af0 chat_id:long from_id:Peer action:SendMessageAction = Update;\nupdateChatParticipants#7761198 participants:ChatParticipants = Update;\nupdateUserStatus#e5bdf8de user_id:long status:UserStatus = Update;\nupdateUserName#c3f202e0 user_id:long first_name:string last_name:string username:string = Update;\nupdateUserPhoto#f227868c user_id:long date:int photo:UserProfilePhoto previous:Bool = Update;\nupdateNewEncryptedMessage#12bcbd9a message:EncryptedMessage qts:int = Update;\nupdateEncryptedChatTyping#1710f156 chat_id:int = Update;\nupdateEncryption#b4a2e88d chat:EncryptedChat date:int = Update;\nupdateEncryptedMessagesRead#38fe25b7 chat_id:int max_date:int date:int = Update;\nupdateChatParticipantAdd#3dda5451 chat_id:long user_id:long inviter_id:long date:int version:int = Update;\nupdateChatParticipantDelete#e32f3d77 chat_id:long user_id:long version:int = Update;\nupdateDcOptions#8e5e9873 dc_options:Vector = Update;\nupdateNotifySettings#bec268ef peer:NotifyPeer notify_settings:PeerNotifySettings = Update;\nupdateServiceNotification#ebe46819 flags:# popup:flags.0?true inbox_date:flags.1?int type:string message:string media:MessageMedia entities:Vector = Update;\nupdatePrivacy#ee3b272a key:PrivacyKey rules:Vector = Update;\nupdateUserPhone#5492a13 user_id:long phone:string = Update;\nupdateReadHistoryInbox#9c974fdf flags:# folder_id:flags.0?int peer:Peer max_id:int still_unread_count:int pts:int pts_count:int = Update;\nupdateReadHistoryOutbox#2f2f21bf peer:Peer max_id:int pts:int pts_count:int = Update;\nupdateWebPage#7f891213 webpage:WebPage pts:int pts_count:int = Update;\nupdateReadMessagesContents#68c13933 messages:Vector pts:int pts_count:int = Update;\nupdateChannelTooLong#108d941f flags:# channel_id:long pts:flags.0?int = Update;\nupdateChannel#635b4c09 channel_id:long = Update;\nupdateNewChannelMessage#62ba04d9 message:Message pts:int pts_count:int = Update;\nupdateReadChannelInbox#922e6e10 flags:# folder_id:flags.0?int channel_id:long max_id:int still_unread_count:int pts:int = Update;\nupdateDeleteChannelMessages#c32d5b12 channel_id:long messages:Vector pts:int pts_count:int = Update;\nupdateChannelMessageViews#f226ac08 channel_id:long id:int views:int = Update;\nupdateChatParticipantAdmin#d7ca61a2 chat_id:long user_id:long is_admin:Bool version:int = Update;\nupdateNewStickerSet#688a30aa stickerset:messages.StickerSet = Update;\nupdateStickerSetsOrder#bb2d201 flags:# masks:flags.0?true order:Vector = Update;\nupdateStickerSets#43ae3dec = Update;\nupdateSavedGifs#9375341e = Update;\nupdateBotInlineQuery#496f379c flags:# query_id:long user_id:long query:string geo:flags.0?GeoPoint peer_type:flags.1?InlineQueryPeerType offset:string = Update;\nupdateBotInlineSend#12f12a07 flags:# user_id:long query:string geo:flags.0?GeoPoint id:string msg_id:flags.1?InputBotInlineMessageID = Update;\nupdateEditChannelMessage#1b3f4df7 message:Message pts:int pts_count:int = Update;\nupdateBotCallbackQuery#b9cfc48d flags:# query_id:long user_id:long peer:Peer msg_id:int chat_instance:long data:flags.0?bytes game_short_name:flags.1?string = Update;\nupdateEditMessage#e40370a3 message:Message pts:int pts_count:int = Update;\nupdateInlineBotCallbackQuery#691e9052 flags:# query_id:long user_id:long msg_id:InputBotInlineMessageID chat_instance:long data:flags.0?bytes game_short_name:flags.1?string = Update;\nupdateReadChannelOutbox#b75f99a9 channel_id:long max_id:int = Update;\nupdateDraftMessage#ee2bb969 peer:Peer draft:DraftMessage = Update;\nupdateReadFeaturedStickers#571d2742 = Update;\nupdateRecentStickers#9a422c20 = Update;\nupdateConfig#a229dd06 = Update;\nupdatePtsChanged#3354678f = Update;\nupdateChannelWebPage#2f2ba99f channel_id:long webpage:WebPage pts:int pts_count:int = Update;\nupdateDialogPinned#6e6fe51c flags:# pinned:flags.0?true folder_id:flags.1?int peer:DialogPeer = Update;\nupdatePinnedDialogs#fa0f3ca2 flags:# folder_id:flags.1?int order:flags.0?Vector = Update;\nupdateBotWebhookJSON#8317c0c3 data:DataJSON = Update;\nupdateBotWebhookJSONQuery#9b9240a6 query_id:long data:DataJSON timeout:int = Update;\nupdateBotShippingQuery#b5aefd7d query_id:long user_id:long payload:bytes shipping_address:PostAddress = Update;\nupdateBotPrecheckoutQuery#8caa9a96 flags:# query_id:long user_id:long payload:bytes info:flags.0?PaymentRequestedInfo shipping_option_id:flags.1?string currency:string total_amount:long = Update;\nupdatePhoneCall#ab0f6b1e phone_call:PhoneCall = Update;\nupdateLangPackTooLong#46560264 lang_code:string = Update;\nupdateLangPack#56022f4d difference:LangPackDifference = Update;\nupdateFavedStickers#e511996d = Update;\nupdateChannelReadMessagesContents#44bdd535 channel_id:long messages:Vector = Update;\nupdateContactsReset#7084a7be = Update;\nupdateChannelAvailableMessages#b23fc698 channel_id:long available_min_id:int = Update;\nupdateDialogUnreadMark#e16459c3 flags:# unread:flags.0?true peer:DialogPeer = Update;\nupdateMessagePoll#aca1657b flags:# poll_id:long poll:flags.0?Poll results:PollResults = Update;\nupdateChatDefaultBannedRights#54c01850 peer:Peer default_banned_rights:ChatBannedRights version:int = Update;\nupdateFolderPeers#19360dc0 folder_peers:Vector pts:int pts_count:int = Update;\nupdatePeerSettings#6a7e7366 peer:Peer settings:PeerSettings = Update;\nupdatePeerLocated#b4afcfb0 peers:Vector = Update;\nupdateNewScheduledMessage#39a51dfb message:Message = Update;\nupdateDeleteScheduledMessages#90866cee peer:Peer messages:Vector = Update;\nupdateTheme#8216fba3 theme:Theme = Update;\nupdateGeoLiveViewed#871fb939 peer:Peer msg_id:int = Update;\nupdateLoginToken#564fe691 = Update;\nupdateMessagePollVote#106395c9 poll_id:long user_id:long options:Vector qts:int = Update;\nupdateDialogFilter#26ffde7d flags:# id:int filter:flags.0?DialogFilter = Update;\nupdateDialogFilterOrder#a5d72105 order:Vector = Update;\nupdateDialogFilters#3504914f = Update;\nupdatePhoneCallSignalingData#2661bf09 phone_call_id:long data:bytes = Update;\nupdateChannelMessageForwards#d29a27f4 channel_id:long id:int forwards:int = Update;\nupdateReadChannelDiscussionInbox#d6b19546 flags:# channel_id:long top_msg_id:int read_max_id:int broadcast_id:flags.0?long broadcast_post:flags.0?int = Update;\nupdateReadChannelDiscussionOutbox#695c9e7c channel_id:long top_msg_id:int read_max_id:int = Update;\nupdatePeerBlocked#246a4b22 peer_id:Peer blocked:Bool = Update;\nupdateChannelUserTyping#8c88c923 flags:# channel_id:long top_msg_id:flags.0?int from_id:Peer action:SendMessageAction = Update;\nupdatePinnedMessages#ed85eab5 flags:# pinned:flags.0?true peer:Peer messages:Vector pts:int pts_count:int = Update;\nupdatePinnedChannelMessages#5bb98608 flags:# pinned:flags.0?true channel_id:long messages:Vector pts:int pts_count:int = Update;\nupdateChat#f89a6a4e chat_id:long = Update;\nupdateGroupCallParticipants#f2ebdb4e call:InputGroupCall participants:Vector version:int = Update;\nupdateGroupCall#14b24500 chat_id:long call:GroupCall = Update;\nupdatePeerHistoryTTL#bb9bb9a5 flags:# peer:Peer ttl_period:flags.0?int = Update;\nupdateChatParticipant#d087663a flags:# chat_id:long date:int actor_id:long user_id:long prev_participant:flags.0?ChatParticipant new_participant:flags.1?ChatParticipant invite:flags.2?ExportedChatInvite qts:int = Update;\nupdateChannelParticipant#985d3abb flags:# channel_id:long date:int actor_id:long user_id:long prev_participant:flags.0?ChannelParticipant new_participant:flags.1?ChannelParticipant invite:flags.2?ExportedChatInvite qts:int = Update;\nupdateBotStopped#c4870a49 user_id:long date:int stopped:Bool qts:int = Update;\nupdateGroupCallConnection#b783982 flags:# presentation:flags.0?true params:DataJSON = Update;\nupdateBotCommands#4d712f2e peer:Peer bot_id:long commands:Vector = Update;\nupdatePendingJoinRequests#7063c3db peer:Peer requests_pending:int recent_requesters:Vector = Update;\nupdateBotChatInviteRequester#11dfa986 peer:Peer date:int user_id:long about:string invite:ExportedChatInvite qts:int = Update;\nupdateMessageReactions#154798c3 peer:Peer msg_id:int reactions:MessageReactions = Update;\nupdates.state#a56c2a3e pts:int qts:int date:int seq:int unread_count:int = updates.State;\nupdates.differenceEmpty#5d75a138 date:int seq:int = updates.Difference;\nupdates.difference#f49ca0 new_messages:Vector new_encrypted_messages:Vector other_updates:Vector chats:Vector users:Vector state:updates.State = updates.Difference;\nupdates.differenceSlice#a8fb1981 new_messages:Vector new_encrypted_messages:Vector other_updates:Vector chats:Vector users:Vector intermediate_state:updates.State = updates.Difference;\nupdates.differenceTooLong#4afe8f6d pts:int = updates.Difference;\nupdatesTooLong#e317af7e = Updates;\nupdateShortMessage#313bc7f8 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true id:int user_id:long message:string pts:int pts_count:int date:int fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?long reply_to:flags.3?MessageReplyHeader entities:flags.7?Vector ttl_period:flags.25?int = Updates;\nupdateShortChatMessage#4d6deea5 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true id:int from_id:long chat_id:long message:string pts:int pts_count:int date:int fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?long reply_to:flags.3?MessageReplyHeader entities:flags.7?Vector ttl_period:flags.25?int = Updates;\nupdateShort#78d4dec1 update:Update date:int = Updates;\nupdatesCombined#725b04c3 updates:Vector users:Vector chats:Vector date:int seq_start:int seq:int = Updates;\nupdates#74ae4240 updates:Vector users:Vector chats:Vector date:int seq:int = Updates;\nupdateShortSentMessage#9015e101 flags:# out:flags.1?true id:int pts:int pts_count:int date:int media:flags.9?MessageMedia entities:flags.7?Vector ttl_period:flags.25?int = Updates;\nphotos.photos#8dca6aa5 photos:Vector users:Vector = photos.Photos;\nphotos.photosSlice#15051f54 count:int photos:Vector users:Vector = photos.Photos;\nphotos.photo#20212ca8 photo:Photo users:Vector = photos.Photo;\nupload.file#96a18d5 type:storage.FileType mtime:int bytes:bytes = upload.File;\nupload.fileCdnRedirect#f18cda44 dc_id:int file_token:bytes encryption_key:bytes encryption_iv:bytes file_hashes:Vector = upload.File;\ndcOption#18b7a10d flags:# ipv6:flags.0?true media_only:flags.1?true tcpo_only:flags.2?true cdn:flags.3?true static:flags.4?true id:int ip_address:string port:int secret:flags.10?bytes = DcOption;\nconfig#330b4067 flags:# phonecalls_enabled:flags.1?true default_p2p_contacts:flags.3?true preload_featured_stickers:flags.4?true ignore_phone_entities:flags.5?true revoke_pm_inbox:flags.6?true blocked_mode:flags.8?true pfs_enabled:flags.13?true date:int expires:int test_mode:Bool this_dc:int dc_options:Vector dc_txt_domain_name:string chat_size_max:int megagroup_size_max:int forwarded_count_max:int online_update_period_ms:int offline_blur_timeout_ms:int offline_idle_timeout_ms:int online_cloud_timeout_ms:int notify_cloud_delay_ms:int notify_default_delay_ms:int push_chat_period_ms:int push_chat_limit:int saved_gifs_limit:int edit_time_limit:int revoke_time_limit:int revoke_pm_time_limit:int rating_e_decay:int stickers_recent_limit:int stickers_faved_limit:int channels_read_media_period:int tmp_sessions:flags.0?int pinned_dialogs_count_max:int pinned_infolder_count_max:int call_receive_timeout_ms:int call_ring_timeout_ms:int call_connect_timeout_ms:int call_packet_timeout_ms:int me_url_prefix:string autoupdate_url_prefix:flags.7?string gif_search_username:flags.9?string venue_search_username:flags.10?string img_search_username:flags.11?string static_maps_provider:flags.12?string caption_length_max:int message_length_max:int webfile_dc_id:int suggested_lang_code:flags.2?string lang_pack_version:flags.2?int base_lang_pack_version:flags.2?int = Config;\nnearestDc#8e1a1775 country:string this_dc:int nearest_dc:int = NearestDc;\nhelp.appUpdate#ccbbce30 flags:# can_not_skip:flags.0?true id:int version:string text:string entities:Vector document:flags.1?Document url:flags.2?string sticker:flags.3?Document = help.AppUpdate;\nhelp.noAppUpdate#c45a6536 = help.AppUpdate;\nhelp.inviteText#18cb9f78 message:string = help.InviteText;\nencryptedChatEmpty#ab7ec0a0 id:int = EncryptedChat;\nencryptedChatWaiting#66b25953 id:int access_hash:long date:int admin_id:long participant_id:long = EncryptedChat;\nencryptedChatRequested#48f1d94c flags:# folder_id:flags.0?int id:int access_hash:long date:int admin_id:long participant_id:long g_a:bytes = EncryptedChat;\nencryptedChat#61f0d4c7 id:int access_hash:long date:int admin_id:long participant_id:long g_a_or_b:bytes key_fingerprint:long = EncryptedChat;\nencryptedChatDiscarded#1e1c7c45 flags:# history_deleted:flags.0?true id:int = EncryptedChat;\ninputEncryptedChat#f141b5e1 chat_id:int access_hash:long = InputEncryptedChat;\nencryptedFileEmpty#c21f497e = EncryptedFile;\nencryptedFile#4a70994c id:long access_hash:long size:int dc_id:int key_fingerprint:int = EncryptedFile;\ninputEncryptedFileEmpty#1837c364 = InputEncryptedFile;\ninputEncryptedFileUploaded#64bd0306 id:long parts:int md5_checksum:string key_fingerprint:int = InputEncryptedFile;\ninputEncryptedFile#5a17b5e5 id:long access_hash:long = InputEncryptedFile;\ninputEncryptedFileBigUploaded#2dc173c8 id:long parts:int key_fingerprint:int = InputEncryptedFile;\nencryptedMessage#ed18c118 random_id:long chat_id:int date:int bytes:bytes file:EncryptedFile = EncryptedMessage;\nencryptedMessageService#23734b06 random_id:long chat_id:int date:int bytes:bytes = EncryptedMessage;\nmessages.dhConfigNotModified#c0e24635 random:bytes = messages.DhConfig;\nmessages.dhConfig#2c221edd g:int p:bytes version:int random:bytes = messages.DhConfig;\nmessages.sentEncryptedMessage#560f8935 date:int = messages.SentEncryptedMessage;\nmessages.sentEncryptedFile#9493ff32 date:int file:EncryptedFile = messages.SentEncryptedMessage;\ninputDocumentEmpty#72f0eaae = InputDocument;\ninputDocument#1abfb575 id:long access_hash:long file_reference:bytes = InputDocument;\ndocumentEmpty#36f8c871 id:long = Document;\ndocument#1e87342b flags:# id:long access_hash:long file_reference:bytes date:int mime_type:string size:int thumbs:flags.0?Vector video_thumbs:flags.1?Vector dc_id:int attributes:Vector = Document;\nhelp.support#17c6b5f6 phone_number:string user:User = help.Support;\nnotifyPeer#9fd40bd8 peer:Peer = NotifyPeer;\nnotifyUsers#b4c83b4c = NotifyPeer;\nnotifyChats#c007cec3 = NotifyPeer;\nnotifyBroadcasts#d612e8ef = NotifyPeer;\nsendMessageTypingAction#16bf744e = SendMessageAction;\nsendMessageCancelAction#fd5ec8f5 = SendMessageAction;\nsendMessageRecordVideoAction#a187d66f = SendMessageAction;\nsendMessageUploadVideoAction#e9763aec progress:int = SendMessageAction;\nsendMessageRecordAudioAction#d52f73f7 = SendMessageAction;\nsendMessageUploadAudioAction#f351d7ab progress:int = SendMessageAction;\nsendMessageUploadPhotoAction#d1d34a26 progress:int = SendMessageAction;\nsendMessageUploadDocumentAction#aa0cd9e4 progress:int = SendMessageAction;\nsendMessageGeoLocationAction#176f8ba1 = SendMessageAction;\nsendMessageChooseContactAction#628cbc6f = SendMessageAction;\nsendMessageGamePlayAction#dd6a8f48 = SendMessageAction;\nsendMessageRecordRoundAction#88f27fbc = SendMessageAction;\nsendMessageUploadRoundAction#243e1c66 progress:int = SendMessageAction;\nspeakingInGroupCallAction#d92c2285 = SendMessageAction;\nsendMessageHistoryImportAction#dbda9246 progress:int = SendMessageAction;\nsendMessageChooseStickerAction#b05ac6b1 = SendMessageAction;\nsendMessageEmojiInteraction#25972bcb emoticon:string msg_id:int interaction:DataJSON = SendMessageAction;\nsendMessageEmojiInteractionSeen#b665902e emoticon:string = SendMessageAction;\ncontacts.found#b3134d9d my_results:Vector results:Vector chats:Vector users:Vector = contacts.Found;\ninputPrivacyKeyStatusTimestamp#4f96cb18 = InputPrivacyKey;\ninputPrivacyKeyChatInvite#bdfb0426 = InputPrivacyKey;\ninputPrivacyKeyPhoneCall#fabadc5f = InputPrivacyKey;\ninputPrivacyKeyPhoneP2P#db9e70d2 = InputPrivacyKey;\ninputPrivacyKeyForwards#a4dd4c08 = InputPrivacyKey;\ninputPrivacyKeyProfilePhoto#5719bacc = InputPrivacyKey;\ninputPrivacyKeyPhoneNumber#352dafa = InputPrivacyKey;\ninputPrivacyKeyAddedByPhone#d1219bdd = InputPrivacyKey;\nprivacyKeyStatusTimestamp#bc2eab30 = PrivacyKey;\nprivacyKeyChatInvite#500e6dfa = PrivacyKey;\nprivacyKeyPhoneCall#3d662b7b = PrivacyKey;\nprivacyKeyPhoneP2P#39491cc8 = PrivacyKey;\nprivacyKeyForwards#69ec56a3 = PrivacyKey;\nprivacyKeyProfilePhoto#96151fed = PrivacyKey;\nprivacyKeyPhoneNumber#d19ae46d = PrivacyKey;\nprivacyKeyAddedByPhone#42ffd42b = PrivacyKey;\ninputPrivacyValueAllowContacts#d09e07b = InputPrivacyRule;\ninputPrivacyValueAllowAll#184b35ce = InputPrivacyRule;\ninputPrivacyValueAllowUsers#131cc67f users:Vector = InputPrivacyRule;\ninputPrivacyValueDisallowContacts#ba52007 = InputPrivacyRule;\ninputPrivacyValueDisallowAll#d66b66c9 = InputPrivacyRule;\ninputPrivacyValueDisallowUsers#90110467 users:Vector = InputPrivacyRule;\ninputPrivacyValueAllowChatParticipants#840649cf chats:Vector = InputPrivacyRule;\ninputPrivacyValueDisallowChatParticipants#e94f0f86 chats:Vector = InputPrivacyRule;\nprivacyValueAllowContacts#fffe1bac = PrivacyRule;\nprivacyValueAllowAll#65427b82 = PrivacyRule;\nprivacyValueAllowUsers#b8905fb2 users:Vector = PrivacyRule;\nprivacyValueDisallowContacts#f888fa1a = PrivacyRule;\nprivacyValueDisallowAll#8b73e763 = PrivacyRule;\nprivacyValueDisallowUsers#e4621141 users:Vector = PrivacyRule;\nprivacyValueAllowChatParticipants#6b134e8e chats:Vector = PrivacyRule;\nprivacyValueDisallowChatParticipants#41c87565 chats:Vector = PrivacyRule;\naccount.privacyRules#50a04e45 rules:Vector chats:Vector users:Vector = account.PrivacyRules;\naccountDaysTTL#b8d0afdf days:int = AccountDaysTTL;\ndocumentAttributeImageSize#6c37c15c w:int h:int = DocumentAttribute;\ndocumentAttributeAnimated#11b58939 = DocumentAttribute;\ndocumentAttributeSticker#6319d612 flags:# mask:flags.1?true alt:string stickerset:InputStickerSet mask_coords:flags.0?MaskCoords = DocumentAttribute;\ndocumentAttributeVideo#ef02ce6 flags:# round_message:flags.0?true supports_streaming:flags.1?true duration:int w:int h:int = DocumentAttribute;\ndocumentAttributeAudio#9852f9c6 flags:# voice:flags.10?true duration:int title:flags.0?string performer:flags.1?string waveform:flags.2?bytes = DocumentAttribute;\ndocumentAttributeFilename#15590068 file_name:string = DocumentAttribute;\ndocumentAttributeHasStickers#9801d2f7 = DocumentAttribute;\nmessages.stickersNotModified#f1749a22 = messages.Stickers;\nmessages.stickers#30a6ec7e hash:long stickers:Vector = messages.Stickers;\nstickerPack#12b299d4 emoticon:string documents:Vector = StickerPack;\nmessages.allStickersNotModified#e86602c3 = messages.AllStickers;\nmessages.allStickers#cdbbcebb hash:long sets:Vector = messages.AllStickers;\nmessages.affectedMessages#84d19185 pts:int pts_count:int = messages.AffectedMessages;\nwebPageEmpty#eb1477e8 id:long = WebPage;\nwebPagePending#c586da1c id:long date:int = WebPage;\nwebPage#e89c45b2 flags:# id:long url:string display_url:string hash:int type:flags.0?string site_name:flags.1?string title:flags.2?string description:flags.3?string photo:flags.4?Photo embed_url:flags.5?string embed_type:flags.5?string embed_width:flags.6?int embed_height:flags.6?int duration:flags.7?int author:flags.8?string document:flags.9?Document cached_page:flags.10?Page attributes:flags.12?Vector = WebPage;\nwebPageNotModified#7311ca11 flags:# cached_page_views:flags.0?int = WebPage;\nauthorization#ad01d61d flags:# current:flags.0?true official_app:flags.1?true password_pending:flags.2?true encrypted_requests_disabled:flags.3?true call_requests_disabled:flags.4?true hash:long device_model:string platform:string system_version:string api_id:int app_name:string app_version:string date_created:int date_active:int ip:string country:string region:string = Authorization;\naccount.authorizations#4bff8ea0 authorization_ttl_days:int authorizations:Vector = account.Authorizations;\naccount.password#185b184f flags:# has_recovery:flags.0?true has_secure_values:flags.1?true has_password:flags.2?true current_algo:flags.2?PasswordKdfAlgo srp_B:flags.2?bytes srp_id:flags.2?long hint:flags.3?string email_unconfirmed_pattern:flags.4?string new_algo:PasswordKdfAlgo new_secure_algo:SecurePasswordKdfAlgo secure_random:bytes pending_reset_date:flags.5?int = account.Password;\naccount.passwordSettings#9a5c33e5 flags:# email:flags.0?string secure_settings:flags.1?SecureSecretSettings = account.PasswordSettings;\naccount.passwordInputSettings#c23727c9 flags:# new_algo:flags.0?PasswordKdfAlgo new_password_hash:flags.0?bytes hint:flags.0?string email:flags.1?string new_secure_settings:flags.2?SecureSecretSettings = account.PasswordInputSettings;\nauth.passwordRecovery#137948a5 email_pattern:string = auth.PasswordRecovery;\nreceivedNotifyMessage#a384b779 id:int flags:int = ReceivedNotifyMessage;\nchatInviteExported#ab4a819 flags:# revoked:flags.0?true permanent:flags.5?true request_needed:flags.6?true link:string admin_id:long date:int start_date:flags.4?int expire_date:flags.1?int usage_limit:flags.2?int usage:flags.3?int requested:flags.7?int title:flags.8?string = ExportedChatInvite;\nchatInviteAlready#5a686d7c chat:Chat = ChatInvite;\nchatInvite#300c44c1 flags:# channel:flags.0?true broadcast:flags.1?true public:flags.2?true megagroup:flags.3?true request_needed:flags.6?true title:string about:flags.5?string photo:Photo participants_count:int participants:flags.4?Vector = ChatInvite;\nchatInvitePeek#61695cb0 chat:Chat expires:int = ChatInvite;\ninputStickerSetEmpty#ffb62b95 = InputStickerSet;\ninputStickerSetID#9de7a269 id:long access_hash:long = InputStickerSet;\ninputStickerSetShortName#861cc8a0 short_name:string = InputStickerSet;\ninputStickerSetAnimatedEmoji#28703c8 = InputStickerSet;\ninputStickerSetDice#e67f520e emoticon:string = InputStickerSet;\ninputStickerSetAnimatedEmojiAnimations#cde3739 = InputStickerSet;\nstickerSet#d7df217a flags:# archived:flags.1?true official:flags.2?true masks:flags.3?true animated:flags.5?true installed_date:flags.0?int id:long access_hash:long title:string short_name:string thumbs:flags.4?Vector thumb_dc_id:flags.4?int thumb_version:flags.4?int count:int hash:int = StickerSet;\nmessages.stickerSet#b60a24a6 set:StickerSet packs:Vector documents:Vector = messages.StickerSet;\nmessages.stickerSetNotModified#d3f924eb = messages.StickerSet;\nbotCommand#c27ac8c7 command:string description:string = BotCommand;\nbotInfo#1b74b335 user_id:long description:string commands:Vector = BotInfo;\nkeyboardButton#a2fa4880 text:string = KeyboardButton;\nkeyboardButtonUrl#258aff05 text:string url:string = KeyboardButton;\nkeyboardButtonCallback#35bbdb6b flags:# requires_password:flags.0?true text:string data:bytes = KeyboardButton;\nkeyboardButtonRequestPhone#b16a6c29 text:string = KeyboardButton;\nkeyboardButtonRequestGeoLocation#fc796b3f text:string = KeyboardButton;\nkeyboardButtonSwitchInline#568a748 flags:# same_peer:flags.0?true text:string query:string = KeyboardButton;\nkeyboardButtonGame#50f41ccf text:string = KeyboardButton;\nkeyboardButtonBuy#afd93fbb text:string = KeyboardButton;\nkeyboardButtonUrlAuth#10b78d29 flags:# text:string fwd_text:flags.0?string url:string button_id:int = KeyboardButton;\ninputKeyboardButtonUrlAuth#d02e7fd4 flags:# request_write_access:flags.0?true text:string fwd_text:flags.1?string url:string bot:InputUser = KeyboardButton;\nkeyboardButtonRequestPoll#bbc7515d flags:# quiz:flags.0?Bool text:string = KeyboardButton;\ninputKeyboardButtonUserProfile#e988037b text:string user_id:InputUser = KeyboardButton;\nkeyboardButtonUserProfile#308660c1 text:string user_id:long = KeyboardButton;\nkeyboardButtonRow#77608b83 buttons:Vector = KeyboardButtonRow;\nreplyKeyboardHide#a03e5b85 flags:# selective:flags.2?true = ReplyMarkup;\nreplyKeyboardForceReply#86b40b08 flags:# single_use:flags.1?true selective:flags.2?true placeholder:flags.3?string = ReplyMarkup;\nreplyKeyboardMarkup#85dd99d1 flags:# resize:flags.0?true single_use:flags.1?true selective:flags.2?true rows:Vector placeholder:flags.3?string = ReplyMarkup;\nreplyInlineMarkup#48a30254 rows:Vector = ReplyMarkup;\nmessageEntityUnknown#bb92ba95 offset:int length:int = MessageEntity;\nmessageEntityMention#fa04579d offset:int length:int = MessageEntity;\nmessageEntityHashtag#6f635b0d offset:int length:int = MessageEntity;\nmessageEntityBotCommand#6cef8ac7 offset:int length:int = MessageEntity;\nmessageEntityUrl#6ed02538 offset:int length:int = MessageEntity;\nmessageEntityEmail#64e475c2 offset:int length:int = MessageEntity;\nmessageEntityBold#bd610bc9 offset:int length:int = MessageEntity;\nmessageEntityItalic#826f8b60 offset:int length:int = MessageEntity;\nmessageEntityCode#28a20571 offset:int length:int = MessageEntity;\nmessageEntityPre#73924be0 offset:int length:int language:string = MessageEntity;\nmessageEntityTextUrl#76a6d327 offset:int length:int url:string = MessageEntity;\nmessageEntityMentionName#dc7b1140 offset:int length:int user_id:long = MessageEntity;\ninputMessageEntityMentionName#208e68c9 offset:int length:int user_id:InputUser = MessageEntity;\nmessageEntityPhone#9b69e34b offset:int length:int = MessageEntity;\nmessageEntityCashtag#4c4e743f offset:int length:int = MessageEntity;\nmessageEntityUnderline#9c4e7e8b offset:int length:int = MessageEntity;\nmessageEntityStrike#bf0693d4 offset:int length:int = MessageEntity;\nmessageEntityBlockquote#20df5d0 offset:int length:int = MessageEntity;\nmessageEntityBankCard#761e6af4 offset:int length:int = MessageEntity;\nmessageEntitySpoiler#32ca960f offset:int length:int = MessageEntity;\ninputChannelEmpty#ee8c1e86 = InputChannel;\ninputChannel#f35aec28 channel_id:long access_hash:long = InputChannel;\ninputChannelFromMessage#5b934f9d peer:InputPeer msg_id:int channel_id:long = InputChannel;\ncontacts.resolvedPeer#7f077ad9 peer:Peer chats:Vector users:Vector = contacts.ResolvedPeer;\nmessageRange#ae30253 min_id:int max_id:int = MessageRange;\nupdates.channelDifferenceEmpty#3e11affb flags:# final:flags.0?true pts:int timeout:flags.1?int = updates.ChannelDifference;\nupdates.channelDifferenceTooLong#a4bcc6fe flags:# final:flags.0?true timeout:flags.1?int dialog:Dialog messages:Vector chats:Vector users:Vector = updates.ChannelDifference;\nupdates.channelDifference#2064674e flags:# final:flags.0?true pts:int timeout:flags.1?int new_messages:Vector other_updates:Vector chats:Vector users:Vector = updates.ChannelDifference;\nchannelMessagesFilterEmpty#94d42ee7 = ChannelMessagesFilter;\nchannelMessagesFilter#cd77d957 flags:# exclude_new_messages:flags.1?true ranges:Vector = ChannelMessagesFilter;\nchannelParticipant#c00c07c0 user_id:long date:int = ChannelParticipant;\nchannelParticipantSelf#35a8bfa7 flags:# via_request:flags.0?true user_id:long inviter_id:long date:int = ChannelParticipant;\nchannelParticipantCreator#2fe601d3 flags:# user_id:long admin_rights:ChatAdminRights rank:flags.0?string = ChannelParticipant;\nchannelParticipantAdmin#34c3bb53 flags:# can_edit:flags.0?true self:flags.1?true user_id:long inviter_id:flags.1?long promoted_by:long date:int admin_rights:ChatAdminRights rank:flags.2?string = ChannelParticipant;\nchannelParticipantBanned#6df8014e flags:# left:flags.0?true peer:Peer kicked_by:long date:int banned_rights:ChatBannedRights = ChannelParticipant;\nchannelParticipantLeft#1b03f006 peer:Peer = ChannelParticipant;\nchannelParticipantsRecent#de3f3c79 = ChannelParticipantsFilter;\nchannelParticipantsAdmins#b4608969 = ChannelParticipantsFilter;\nchannelParticipantsKicked#a3b54985 q:string = ChannelParticipantsFilter;\nchannelParticipantsBots#b0d1865b = ChannelParticipantsFilter;\nchannelParticipantsBanned#1427a5e1 q:string = ChannelParticipantsFilter;\nchannelParticipantsSearch#656ac4b q:string = ChannelParticipantsFilter;\nchannelParticipantsContacts#bb6ae88d q:string = ChannelParticipantsFilter;\nchannelParticipantsMentions#e04b5ceb flags:# q:flags.0?string top_msg_id:flags.1?int = ChannelParticipantsFilter;\nchannels.channelParticipants#9ab0feaf count:int participants:Vector chats:Vector users:Vector = channels.ChannelParticipants;\nchannels.channelParticipantsNotModified#f0173fe9 = channels.ChannelParticipants;\nchannels.channelParticipant#dfb80317 participant:ChannelParticipant chats:Vector users:Vector = channels.ChannelParticipant;\nhelp.termsOfService#780a0310 flags:# popup:flags.0?true id:DataJSON text:string entities:Vector min_age_confirm:flags.1?int = help.TermsOfService;\nmessages.savedGifsNotModified#e8025ca2 = messages.SavedGifs;\nmessages.savedGifs#84a02a0d hash:long gifs:Vector = messages.SavedGifs;\ninputBotInlineMessageMediaAuto#3380c786 flags:# message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageText#3dcd7a87 flags:# no_webpage:flags.0?true message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaGeo#96929a85 flags:# geo_point:InputGeoPoint heading:flags.0?int period:flags.1?int proximity_notification_radius:flags.3?int reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaVenue#417bbf11 flags:# geo_point:InputGeoPoint title:string address:string provider:string venue_id:string venue_type:string reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaContact#a6edbffd flags:# phone_number:string first_name:string last_name:string vcard:string reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageGame#4b425864 flags:# reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaInvoice#d7e78225 flags:# title:string description:string photo:flags.0?InputWebDocument invoice:Invoice payload:bytes provider:string provider_data:DataJSON reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineResult#88bf9319 flags:# id:string type:string title:flags.1?string description:flags.2?string url:flags.3?string thumb:flags.4?InputWebDocument content:flags.5?InputWebDocument send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultPhoto#a8d864a7 id:string type:string photo:InputPhoto send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultDocument#fff8fdc4 flags:# id:string type:string title:flags.1?string description:flags.2?string document:InputDocument send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultGame#4fa417f2 id:string short_name:string send_message:InputBotInlineMessage = InputBotInlineResult;\nbotInlineMessageMediaAuto#764cf810 flags:# message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageText#8c7f65e2 flags:# no_webpage:flags.0?true message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaGeo#51846fd flags:# geo:GeoPoint heading:flags.0?int period:flags.1?int proximity_notification_radius:flags.3?int reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaVenue#8a86659c flags:# geo:GeoPoint title:string address:string provider:string venue_id:string venue_type:string reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaContact#18d1cdc2 flags:# phone_number:string first_name:string last_name:string vcard:string reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaInvoice#354a9b09 flags:# shipping_address_requested:flags.1?true test:flags.3?true title:string description:string photo:flags.0?WebDocument currency:string total_amount:long reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineResult#11965f3a flags:# id:string type:string title:flags.1?string description:flags.2?string url:flags.3?string thumb:flags.4?WebDocument content:flags.5?WebDocument send_message:BotInlineMessage = BotInlineResult;\nbotInlineMediaResult#17db940b flags:# id:string type:string photo:flags.0?Photo document:flags.1?Document title:flags.2?string description:flags.3?string send_message:BotInlineMessage = BotInlineResult;\nmessages.botResults#947ca848 flags:# gallery:flags.0?true query_id:long next_offset:flags.1?string switch_pm:flags.2?InlineBotSwitchPM results:Vector cache_time:int users:Vector = messages.BotResults;\nexportedMessageLink#5dab1af4 link:string html:string = ExportedMessageLink;\nmessageFwdHeader#5f777dce flags:# imported:flags.7?true from_id:flags.0?Peer from_name:flags.5?string date:int channel_post:flags.2?int post_author:flags.3?string saved_from_peer:flags.4?Peer saved_from_msg_id:flags.4?int psa_type:flags.6?string = MessageFwdHeader;\nauth.codeTypeSms#72a3158c = auth.CodeType;\nauth.codeTypeCall#741cd3e3 = auth.CodeType;\nauth.codeTypeFlashCall#226ccefb = auth.CodeType;\nauth.codeTypeMissedCall#d61ad6ee = auth.CodeType;\nauth.sentCodeTypeApp#3dbb5986 length:int = auth.SentCodeType;\nauth.sentCodeTypeSms#c000bba2 length:int = auth.SentCodeType;\nauth.sentCodeTypeCall#5353e5a7 length:int = auth.SentCodeType;\nauth.sentCodeTypeFlashCall#ab03c6d9 pattern:string = auth.SentCodeType;\nauth.sentCodeTypeMissedCall#82006484 prefix:string length:int = auth.SentCodeType;\nmessages.botCallbackAnswer#36585ea4 flags:# alert:flags.1?true has_url:flags.3?true native_ui:flags.4?true message:flags.0?string url:flags.2?string cache_time:int = messages.BotCallbackAnswer;\nmessages.messageEditData#26b5dde6 flags:# caption:flags.0?true = messages.MessageEditData;\ninputBotInlineMessageID#890c3d89 dc_id:int id:long access_hash:long = InputBotInlineMessageID;\ninputBotInlineMessageID64#b6d915d7 dc_id:int owner_id:long id:int access_hash:long = InputBotInlineMessageID;\ninlineBotSwitchPM#3c20629f text:string start_param:string = InlineBotSwitchPM;\nmessages.peerDialogs#3371c354 dialogs:Vector messages:Vector chats:Vector users:Vector state:updates.State = messages.PeerDialogs;\ntopPeer#edcdc05b peer:Peer rating:double = TopPeer;\ntopPeerCategoryBotsPM#ab661b5b = TopPeerCategory;\ntopPeerCategoryBotsInline#148677e2 = TopPeerCategory;\ntopPeerCategoryCorrespondents#637b7ed = TopPeerCategory;\ntopPeerCategoryGroups#bd17a14a = TopPeerCategory;\ntopPeerCategoryChannels#161d9628 = TopPeerCategory;\ntopPeerCategoryPhoneCalls#1e76a78c = TopPeerCategory;\ntopPeerCategoryForwardUsers#a8406ca9 = TopPeerCategory;\ntopPeerCategoryForwardChats#fbeec0f0 = TopPeerCategory;\ntopPeerCategoryPeers#fb834291 category:TopPeerCategory count:int peers:Vector = TopPeerCategoryPeers;\ncontacts.topPeersNotModified#de266ef5 = contacts.TopPeers;\ncontacts.topPeers#70b772a8 categories:Vector chats:Vector users:Vector = contacts.TopPeers;\ncontacts.topPeersDisabled#b52c939d = contacts.TopPeers;\ndraftMessageEmpty#1b0c841a flags:# date:flags.0?int = DraftMessage;\ndraftMessage#fd8e711f flags:# no_webpage:flags.1?true reply_to_msg_id:flags.0?int message:string entities:flags.3?Vector date:int = DraftMessage;\nmessages.featuredStickersNotModified#c6dc0c66 count:int = messages.FeaturedStickers;\nmessages.featuredStickers#84c02310 hash:long count:int sets:Vector unread:Vector = messages.FeaturedStickers;\nmessages.recentStickersNotModified#b17f890 = messages.RecentStickers;\nmessages.recentStickers#88d37c56 hash:long packs:Vector stickers:Vector dates:Vector = messages.RecentStickers;\nmessages.archivedStickers#4fcba9c8 count:int sets:Vector = messages.ArchivedStickers;\nmessages.stickerSetInstallResultSuccess#38641628 = messages.StickerSetInstallResult;\nmessages.stickerSetInstallResultArchive#35e410a8 sets:Vector = messages.StickerSetInstallResult;\nstickerSetCovered#6410a5d2 set:StickerSet cover:Document = StickerSetCovered;\nstickerSetMultiCovered#3407e51b set:StickerSet covers:Vector = StickerSetCovered;\nmaskCoords#aed6dbb2 n:int x:double y:double zoom:double = MaskCoords;\ninputStickeredMediaPhoto#4a992157 id:InputPhoto = InputStickeredMedia;\ninputStickeredMediaDocument#438865b id:InputDocument = InputStickeredMedia;\ngame#bdf9653b flags:# id:long access_hash:long short_name:string title:string description:string photo:Photo document:flags.0?Document = Game;\ninputGameID#32c3e77 id:long access_hash:long = InputGame;\ninputGameShortName#c331e80a bot_id:InputUser short_name:string = InputGame;\nhighScore#73a379eb pos:int user_id:long score:int = HighScore;\nmessages.highScores#9a3bfd99 scores:Vector users:Vector = messages.HighScores;\ntextEmpty#dc3d824f = RichText;\ntextPlain#744694e0 text:string = RichText;\ntextBold#6724abc4 text:RichText = RichText;\ntextItalic#d912a59c text:RichText = RichText;\ntextUnderline#c12622c4 text:RichText = RichText;\ntextStrike#9bf8bb95 text:RichText = RichText;\ntextFixed#6c3f19b9 text:RichText = RichText;\ntextUrl#3c2884c1 text:RichText url:string webpage_id:long = RichText;\ntextEmail#de5a0dd6 text:RichText email:string = RichText;\ntextConcat#7e6260d7 texts:Vector = RichText;\ntextSubscript#ed6a8504 text:RichText = RichText;\ntextSuperscript#c7fb5e01 text:RichText = RichText;\ntextMarked#34b8621 text:RichText = RichText;\ntextPhone#1ccb966a text:RichText phone:string = RichText;\ntextImage#81ccf4f document_id:long w:int h:int = RichText;\ntextAnchor#35553762 text:RichText name:string = RichText;\npageBlockUnsupported#13567e8a = PageBlock;\npageBlockTitle#70abc3fd text:RichText = PageBlock;\npageBlockSubtitle#8ffa9a1f text:RichText = PageBlock;\npageBlockAuthorDate#baafe5e0 author:RichText published_date:int = PageBlock;\npageBlockHeader#bfd064ec text:RichText = PageBlock;\npageBlockSubheader#f12bb6e1 text:RichText = PageBlock;\npageBlockParagraph#467a0766 text:RichText = PageBlock;\npageBlockPreformatted#c070d93e text:RichText language:string = PageBlock;\npageBlockFooter#48870999 text:RichText = PageBlock;\npageBlockDivider#db20b188 = PageBlock;\npageBlockAnchor#ce0d37b0 name:string = PageBlock;\npageBlockList#e4e88011 items:Vector = PageBlock;\npageBlockBlockquote#263d7c26 text:RichText caption:RichText = PageBlock;\npageBlockPullquote#4f4456d3 text:RichText caption:RichText = PageBlock;\npageBlockPhoto#1759c560 flags:# photo_id:long caption:PageCaption url:flags.0?string webpage_id:flags.0?long = PageBlock;\npageBlockVideo#7c8fe7b6 flags:# autoplay:flags.0?true loop:flags.1?true video_id:long caption:PageCaption = PageBlock;\npageBlockCover#39f23300 cover:PageBlock = PageBlock;\npageBlockEmbed#a8718dc5 flags:# full_width:flags.0?true allow_scrolling:flags.3?true url:flags.1?string html:flags.2?string poster_photo_id:flags.4?long w:flags.5?int h:flags.5?int caption:PageCaption = PageBlock;\npageBlockEmbedPost#f259a80b url:string webpage_id:long author_photo_id:long author:string date:int blocks:Vector caption:PageCaption = PageBlock;\npageBlockCollage#65a0fa4d items:Vector caption:PageCaption = PageBlock;\npageBlockSlideshow#31f9590 items:Vector caption:PageCaption = PageBlock;\npageBlockChannel#ef1751b5 channel:Chat = PageBlock;\npageBlockAudio#804361ea audio_id:long caption:PageCaption = PageBlock;\npageBlockKicker#1e148390 text:RichText = PageBlock;\npageBlockTable#bf4dea82 flags:# bordered:flags.0?true striped:flags.1?true title:RichText rows:Vector = PageBlock;\npageBlockOrderedList#9a8ae1e1 items:Vector = PageBlock;\npageBlockDetails#76768bed flags:# open:flags.0?true blocks:Vector title:RichText = PageBlock;\npageBlockRelatedArticles#16115a96 title:RichText articles:Vector = PageBlock;\npageBlockMap#a44f3ef6 geo:GeoPoint zoom:int w:int h:int caption:PageCaption = PageBlock;\nphoneCallDiscardReasonMissed#85e42301 = PhoneCallDiscardReason;\nphoneCallDiscardReasonDisconnect#e095c1a0 = PhoneCallDiscardReason;\nphoneCallDiscardReasonHangup#57adc690 = PhoneCallDiscardReason;\nphoneCallDiscardReasonBusy#faf7e8c9 = PhoneCallDiscardReason;\ndataJSON#7d748d04 data:string = DataJSON;\nlabeledPrice#cb296bf8 label:string amount:long = LabeledPrice;\ninvoice#cd886e0 flags:# test:flags.0?true name_requested:flags.1?true phone_requested:flags.2?true email_requested:flags.3?true shipping_address_requested:flags.4?true flexible:flags.5?true phone_to_provider:flags.6?true email_to_provider:flags.7?true currency:string prices:Vector max_tip_amount:flags.8?long suggested_tip_amounts:flags.8?Vector = Invoice;\npaymentCharge#ea02c27e id:string provider_charge_id:string = PaymentCharge;\npostAddress#1e8caaeb street_line1:string street_line2:string city:string state:string country_iso2:string post_code:string = PostAddress;\npaymentRequestedInfo#909c3f94 flags:# name:flags.0?string phone:flags.1?string email:flags.2?string shipping_address:flags.3?PostAddress = PaymentRequestedInfo;\npaymentSavedCredentialsCard#cdc27a1f id:string title:string = PaymentSavedCredentials;\nwebDocument#1c570ed1 url:string access_hash:long size:int mime_type:string attributes:Vector = WebDocument;\nwebDocumentNoProxy#f9c8bcc6 url:string size:int mime_type:string attributes:Vector = WebDocument;\ninputWebDocument#9bed434d url:string size:int mime_type:string attributes:Vector = InputWebDocument;\ninputWebFileLocation#c239d686 url:string access_hash:long = InputWebFileLocation;\ninputWebFileGeoPointLocation#9f2221c9 geo_point:InputGeoPoint access_hash:long w:int h:int zoom:int scale:int = InputWebFileLocation;\nupload.webFile#21e753bc size:int mime_type:string file_type:storage.FileType mtime:int bytes:bytes = upload.WebFile;\npayments.paymentForm#1694761b flags:# can_save_credentials:flags.2?true password_missing:flags.3?true form_id:long bot_id:long invoice:Invoice provider_id:long url:string native_provider:flags.4?string native_params:flags.4?DataJSON saved_info:flags.0?PaymentRequestedInfo saved_credentials:flags.1?PaymentSavedCredentials users:Vector = payments.PaymentForm;\npayments.validatedRequestedInfo#d1451883 flags:# id:flags.0?string shipping_options:flags.1?Vector = payments.ValidatedRequestedInfo;\npayments.paymentResult#4e5f810d updates:Updates = payments.PaymentResult;\npayments.paymentVerificationNeeded#d8411139 url:string = payments.PaymentResult;\npayments.paymentReceipt#70c4fe03 flags:# date:int bot_id:long provider_id:long title:string description:string photo:flags.2?WebDocument invoice:Invoice info:flags.0?PaymentRequestedInfo shipping:flags.1?ShippingOption tip_amount:flags.3?long currency:string total_amount:long credentials_title:string users:Vector = payments.PaymentReceipt;\npayments.savedInfo#fb8fe43c flags:# has_saved_credentials:flags.1?true saved_info:flags.0?PaymentRequestedInfo = payments.SavedInfo;\ninputPaymentCredentialsSaved#c10eb2cf id:string tmp_password:bytes = InputPaymentCredentials;\ninputPaymentCredentials#3417d728 flags:# save:flags.0?true data:DataJSON = InputPaymentCredentials;\ninputPaymentCredentialsApplePay#aa1c39f payment_data:DataJSON = InputPaymentCredentials;\ninputPaymentCredentialsGooglePay#8ac32801 payment_token:DataJSON = InputPaymentCredentials;\naccount.tmpPassword#db64fd34 tmp_password:bytes valid_until:int = account.TmpPassword;\nshippingOption#b6213cdf id:string title:string prices:Vector = ShippingOption;\ninputStickerSetItem#ffa0a496 flags:# document:InputDocument emoji:string mask_coords:flags.0?MaskCoords = InputStickerSetItem;\ninputPhoneCall#1e36fded id:long access_hash:long = InputPhoneCall;\nphoneCallEmpty#5366c915 id:long = PhoneCall;\nphoneCallWaiting#c5226f17 flags:# video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long protocol:PhoneCallProtocol receive_date:flags.0?int = PhoneCall;\nphoneCallRequested#14b0ed0c flags:# video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long g_a_hash:bytes protocol:PhoneCallProtocol = PhoneCall;\nphoneCallAccepted#3660c311 flags:# video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long g_b:bytes protocol:PhoneCallProtocol = PhoneCall;\nphoneCall#967f7c67 flags:# p2p_allowed:flags.5?true video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long g_a_or_b:bytes key_fingerprint:long protocol:PhoneCallProtocol connections:Vector start_date:int = PhoneCall;\nphoneCallDiscarded#50ca4de1 flags:# need_rating:flags.2?true need_debug:flags.3?true video:flags.6?true id:long reason:flags.0?PhoneCallDiscardReason duration:flags.1?int = PhoneCall;\nphoneConnection#9d4c17c0 id:long ip:string ipv6:string port:int peer_tag:bytes = PhoneConnection;\nphoneConnectionWebrtc#635fe375 flags:# turn:flags.0?true stun:flags.1?true id:long ip:string ipv6:string port:int username:string password:string = PhoneConnection;\nphoneCallProtocol#fc878fc8 flags:# udp_p2p:flags.0?true udp_reflector:flags.1?true min_layer:int max_layer:int library_versions:Vector = PhoneCallProtocol;\nphone.phoneCall#ec82e140 phone_call:PhoneCall users:Vector = phone.PhoneCall;\nupload.cdnFileReuploadNeeded#eea8e46e request_token:bytes = upload.CdnFile;\nupload.cdnFile#a99fca4f bytes:bytes = upload.CdnFile;\ncdnPublicKey#c982eaba dc_id:int public_key:string = CdnPublicKey;\ncdnConfig#5725e40a public_keys:Vector = CdnConfig;\nlangPackString#cad181f6 key:string value:string = LangPackString;\nlangPackStringPluralized#6c47ac9f flags:# key:string zero_value:flags.0?string one_value:flags.1?string two_value:flags.2?string few_value:flags.3?string many_value:flags.4?string other_value:string = LangPackString;\nlangPackStringDeleted#2979eeb2 key:string = LangPackString;\nlangPackDifference#f385c1f6 lang_code:string from_version:int version:int strings:Vector = LangPackDifference;\nlangPackLanguage#eeca5ce3 flags:# official:flags.0?true rtl:flags.2?true beta:flags.3?true name:string native_name:string lang_code:string base_lang_code:flags.1?string plural_code:string strings_count:int translated_count:int translations_url:string = LangPackLanguage;\nchannelAdminLogEventActionChangeTitle#e6dfb825 prev_value:string new_value:string = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeAbout#55188a2e prev_value:string new_value:string = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeUsername#6a4afc38 prev_value:string new_value:string = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangePhoto#434bd2af prev_photo:Photo new_photo:Photo = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleInvites#1b7907ae new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleSignatures#26ae0971 new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionUpdatePinned#e9e82c18 message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionEditMessage#709b2405 prev_message:Message new_message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionDeleteMessage#42e047bb message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantJoin#183040d3 = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantLeave#f89777f2 = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantInvite#e31c34d8 participant:ChannelParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantToggleBan#e6d83d7e prev_participant:ChannelParticipant new_participant:ChannelParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantToggleAdmin#d5676710 prev_participant:ChannelParticipant new_participant:ChannelParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeStickerSet#b1c3caa7 prev_stickerset:InputStickerSet new_stickerset:InputStickerSet = ChannelAdminLogEventAction;\nchannelAdminLogEventActionTogglePreHistoryHidden#5f5c95f1 new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionDefaultBannedRights#2df5fc0a prev_banned_rights:ChatBannedRights new_banned_rights:ChatBannedRights = ChannelAdminLogEventAction;\nchannelAdminLogEventActionStopPoll#8f079643 message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeLinkedChat#50c7ac8 prev_value:long new_value:long = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeLocation#e6b76ae prev_value:ChannelLocation new_value:ChannelLocation = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleSlowMode#53909779 prev_value:int new_value:int = ChannelAdminLogEventAction;\nchannelAdminLogEventActionStartGroupCall#23209745 call:InputGroupCall = ChannelAdminLogEventAction;\nchannelAdminLogEventActionDiscardGroupCall#db9f9140 call:InputGroupCall = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantMute#f92424d2 participant:GroupCallParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantUnmute#e64429c0 participant:GroupCallParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleGroupCallSetting#56d6a247 join_muted:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantJoinByInvite#5cdada77 invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionExportedInviteDelete#5a50fca4 invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionExportedInviteRevoke#410a134e invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionExportedInviteEdit#e90ebb59 prev_invite:ExportedChatInvite new_invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantVolume#3e7f6847 participant:GroupCallParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeHistoryTTL#6e941a38 prev_value:int new_value:int = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantJoinByRequest#afb6144a invite:ExportedChatInvite approved_by:long = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleNoForwards#cb2ac766 new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionSendMessage#278f2868 message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeAvailableReactions#9cf7f76a prev_value:Vector new_value:Vector = ChannelAdminLogEventAction;\nchannelAdminLogEvent#1fad68cd id:long date:int user_id:long action:ChannelAdminLogEventAction = ChannelAdminLogEvent;\nchannels.adminLogResults#ed8af74d events:Vector chats:Vector users:Vector = channels.AdminLogResults;\nchannelAdminLogEventsFilter#ea107ae4 flags:# join:flags.0?true leave:flags.1?true invite:flags.2?true ban:flags.3?true unban:flags.4?true kick:flags.5?true unkick:flags.6?true promote:flags.7?true demote:flags.8?true info:flags.9?true settings:flags.10?true pinned:flags.11?true edit:flags.12?true delete:flags.13?true group_call:flags.14?true invites:flags.15?true send:flags.16?true = ChannelAdminLogEventsFilter;\npopularContact#5ce14175 client_id:long importers:int = PopularContact;\nmessages.favedStickersNotModified#9e8fa6d3 = messages.FavedStickers;\nmessages.favedStickers#2cb51097 hash:long packs:Vector stickers:Vector = messages.FavedStickers;\nrecentMeUrlUnknown#46e1d13d url:string = RecentMeUrl;\nrecentMeUrlUser#b92c09e2 url:string user_id:long = RecentMeUrl;\nrecentMeUrlChat#b2da71d2 url:string chat_id:long = RecentMeUrl;\nrecentMeUrlChatInvite#eb49081d url:string chat_invite:ChatInvite = RecentMeUrl;\nrecentMeUrlStickerSet#bc0a57dc url:string set:StickerSetCovered = RecentMeUrl;\nhelp.recentMeUrls#e0310d7 urls:Vector chats:Vector users:Vector = help.RecentMeUrls;\ninputSingleMedia#1cc6e91f flags:# media:InputMedia random_id:long message:string entities:flags.0?Vector = InputSingleMedia;\nwebAuthorization#a6f8f452 hash:long bot_id:long domain:string browser:string platform:string date_created:int date_active:int ip:string region:string = WebAuthorization;\naccount.webAuthorizations#ed56c9fc authorizations:Vector users:Vector = account.WebAuthorizations;\ninputMessageID#a676a322 id:int = InputMessage;\ninputMessageReplyTo#bad88395 id:int = InputMessage;\ninputMessagePinned#86872538 = InputMessage;\ninputMessageCallbackQuery#acfa1a7e id:int query_id:long = InputMessage;\ninputDialogPeer#fcaafeb7 peer:InputPeer = InputDialogPeer;\ninputDialogPeerFolder#64600527 folder_id:int = InputDialogPeer;\ndialogPeer#e56dbf05 peer:Peer = DialogPeer;\ndialogPeerFolder#514519e2 folder_id:int = DialogPeer;\nmessages.foundStickerSetsNotModified#d54b65d = messages.FoundStickerSets;\nmessages.foundStickerSets#8af09dd2 hash:long sets:Vector = messages.FoundStickerSets;\nfileHash#6242c773 offset:int limit:int hash:bytes = FileHash;\ninputClientProxy#75588b3f address:string port:int = InputClientProxy;\nhelp.termsOfServiceUpdateEmpty#e3309f7f expires:int = help.TermsOfServiceUpdate;\nhelp.termsOfServiceUpdate#28ecf961 expires:int terms_of_service:help.TermsOfService = help.TermsOfServiceUpdate;\ninputSecureFileUploaded#3334b0f0 id:long parts:int md5_checksum:string file_hash:bytes secret:bytes = InputSecureFile;\ninputSecureFile#5367e5be id:long access_hash:long = InputSecureFile;\nsecureFileEmpty#64199744 = SecureFile;\nsecureFile#e0277a62 id:long access_hash:long size:int dc_id:int date:int file_hash:bytes secret:bytes = SecureFile;\nsecureData#8aeabec3 data:bytes data_hash:bytes secret:bytes = SecureData;\nsecurePlainPhone#7d6099dd phone:string = SecurePlainData;\nsecurePlainEmail#21ec5a5f email:string = SecurePlainData;\nsecureValueTypePersonalDetails#9d2a81e3 = SecureValueType;\nsecureValueTypePassport#3dac6a00 = SecureValueType;\nsecureValueTypeDriverLicense#6e425c4 = SecureValueType;\nsecureValueTypeIdentityCard#a0d0744b = SecureValueType;\nsecureValueTypeInternalPassport#99a48f23 = SecureValueType;\nsecureValueTypeAddress#cbe31e26 = SecureValueType;\nsecureValueTypeUtilityBill#fc36954e = SecureValueType;\nsecureValueTypeBankStatement#89137c0d = SecureValueType;\nsecureValueTypeRentalAgreement#8b883488 = SecureValueType;\nsecureValueTypePassportRegistration#99e3806a = SecureValueType;\nsecureValueTypeTemporaryRegistration#ea02ec33 = SecureValueType;\nsecureValueTypePhone#b320aadb = SecureValueType;\nsecureValueTypeEmail#8e3ca7ee = SecureValueType;\nsecureValue#187fa0ca flags:# type:SecureValueType data:flags.0?SecureData front_side:flags.1?SecureFile reverse_side:flags.2?SecureFile selfie:flags.3?SecureFile translation:flags.6?Vector files:flags.4?Vector plain_data:flags.5?SecurePlainData hash:bytes = SecureValue;\ninputSecureValue#db21d0a7 flags:# type:SecureValueType data:flags.0?SecureData front_side:flags.1?InputSecureFile reverse_side:flags.2?InputSecureFile selfie:flags.3?InputSecureFile translation:flags.6?Vector files:flags.4?Vector plain_data:flags.5?SecurePlainData = InputSecureValue;\nsecureValueHash#ed1ecdb0 type:SecureValueType hash:bytes = SecureValueHash;\nsecureValueErrorData#e8a40bd9 type:SecureValueType data_hash:bytes field:string text:string = SecureValueError;\nsecureValueErrorFrontSide#be3dfa type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorReverseSide#868a2aa5 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorSelfie#e537ced6 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorFile#7a700873 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorFiles#666220e9 type:SecureValueType file_hash:Vector text:string = SecureValueError;\nsecureValueError#869d758f type:SecureValueType hash:bytes text:string = SecureValueError;\nsecureValueErrorTranslationFile#a1144770 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorTranslationFiles#34636dd8 type:SecureValueType file_hash:Vector text:string = SecureValueError;\nsecureCredentialsEncrypted#33f0ea47 data:bytes hash:bytes secret:bytes = SecureCredentialsEncrypted;\naccount.authorizationForm#ad2e1cd8 flags:# required_types:Vector values:Vector errors:Vector users:Vector privacy_policy_url:flags.0?string = account.AuthorizationForm;\naccount.sentEmailCode#811f854f email_pattern:string length:int = account.SentEmailCode;\nhelp.deepLinkInfoEmpty#66afa166 = help.DeepLinkInfo;\nhelp.deepLinkInfo#6a4ee832 flags:# update_app:flags.0?true message:string entities:flags.1?Vector = help.DeepLinkInfo;\nsavedPhoneContact#1142bd56 phone:string first_name:string last_name:string date:int = SavedContact;\naccount.takeout#4dba4501 id:long = account.Takeout;\npasswordKdfAlgoUnknown#d45ab096 = PasswordKdfAlgo;\npasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow#3a912d4a salt1:bytes salt2:bytes g:int p:bytes = PasswordKdfAlgo;\nsecurePasswordKdfAlgoUnknown#4a8537 = SecurePasswordKdfAlgo;\nsecurePasswordKdfAlgoPBKDF2HMACSHA512iter100000#bbf2dda0 salt:bytes = SecurePasswordKdfAlgo;\nsecurePasswordKdfAlgoSHA512#86471d92 salt:bytes = SecurePasswordKdfAlgo;\nsecureSecretSettings#1527bcac secure_algo:SecurePasswordKdfAlgo secure_secret:bytes secure_secret_id:long = SecureSecretSettings;\ninputCheckPasswordEmpty#9880f658 = InputCheckPasswordSRP;\ninputCheckPasswordSRP#d27ff082 srp_id:long A:bytes M1:bytes = InputCheckPasswordSRP;\nsecureRequiredType#829d99da flags:# native_names:flags.0?true selfie_required:flags.1?true translation_required:flags.2?true type:SecureValueType = SecureRequiredType;\nsecureRequiredTypeOneOf#27477b4 types:Vector = SecureRequiredType;\nhelp.passportConfigNotModified#bfb9f457 = help.PassportConfig;\nhelp.passportConfig#a098d6af hash:int countries_langs:DataJSON = help.PassportConfig;\ninputAppEvent#1d1b1245 time:double type:string peer:long data:JSONValue = InputAppEvent;\njsonObjectValue#c0de1bd9 key:string value:JSONValue = JSONObjectValue;\njsonNull#3f6d7b68 = JSONValue;\njsonBool#c7345e6a value:Bool = JSONValue;\njsonNumber#2be0dfa4 value:double = JSONValue;\njsonString#b71e767a value:string = JSONValue;\njsonArray#f7444763 value:Vector = JSONValue;\njsonObject#99c1d49d value:Vector = JSONValue;\npageTableCell#34566b6a flags:# header:flags.0?true align_center:flags.3?true align_right:flags.4?true valign_middle:flags.5?true valign_bottom:flags.6?true text:flags.7?RichText colspan:flags.1?int rowspan:flags.2?int = PageTableCell;\npageTableRow#e0c0c5e5 cells:Vector = PageTableRow;\npageCaption#6f747657 text:RichText credit:RichText = PageCaption;\npageListItemText#b92fb6cd text:RichText = PageListItem;\npageListItemBlocks#25e073fc blocks:Vector = PageListItem;\npageListOrderedItemText#5e068047 num:string text:RichText = PageListOrderedItem;\npageListOrderedItemBlocks#98dd8936 num:string blocks:Vector = PageListOrderedItem;\npageRelatedArticle#b390dc08 flags:# url:string webpage_id:long title:flags.0?string description:flags.1?string photo_id:flags.2?long author:flags.3?string published_date:flags.4?int = PageRelatedArticle;\npage#98657f0d flags:# part:flags.0?true rtl:flags.1?true v2:flags.2?true url:string blocks:Vector photos:Vector documents:Vector views:flags.3?int = Page;\nhelp.supportName#8c05f1c9 name:string = help.SupportName;\nhelp.userInfoEmpty#f3ae2eed = help.UserInfo;\nhelp.userInfo#1eb3758 message:string entities:Vector author:string date:int = help.UserInfo;\npollAnswer#6ca9c2e9 text:string option:bytes = PollAnswer;\npoll#86e18161 id:long flags:# closed:flags.0?true public_voters:flags.1?true multiple_choice:flags.2?true quiz:flags.3?true question:string answers:Vector close_period:flags.4?int close_date:flags.5?int = Poll;\npollAnswerVoters#3b6ddad2 flags:# chosen:flags.0?true correct:flags.1?true option:bytes voters:int = PollAnswerVoters;\npollResults#dcb82ea3 flags:# min:flags.0?true results:flags.1?Vector total_voters:flags.2?int recent_voters:flags.3?Vector solution:flags.4?string solution_entities:flags.4?Vector = PollResults;\nchatOnlines#f041e250 onlines:int = ChatOnlines;\nstatsURL#47a971e0 url:string = StatsURL;\nchatAdminRights#5fb224d5 flags:# change_info:flags.0?true post_messages:flags.1?true edit_messages:flags.2?true delete_messages:flags.3?true ban_users:flags.4?true invite_users:flags.5?true pin_messages:flags.7?true add_admins:flags.9?true anonymous:flags.10?true manage_call:flags.11?true other:flags.12?true = ChatAdminRights;\nchatBannedRights#9f120418 flags:# view_messages:flags.0?true send_messages:flags.1?true send_media:flags.2?true send_stickers:flags.3?true send_gifs:flags.4?true send_games:flags.5?true send_inline:flags.6?true embed_links:flags.7?true send_polls:flags.8?true change_info:flags.10?true invite_users:flags.15?true pin_messages:flags.17?true until_date:int = ChatBannedRights;\ninputWallPaper#e630b979 id:long access_hash:long = InputWallPaper;\ninputWallPaperSlug#72091c80 slug:string = InputWallPaper;\ninputWallPaperNoFile#967a462e id:long = InputWallPaper;\naccount.wallPapersNotModified#1c199183 = account.WallPapers;\naccount.wallPapers#cdc3858c hash:long wallpapers:Vector = account.WallPapers;\ncodeSettings#8a6469c2 flags:# allow_flashcall:flags.0?true current_number:flags.1?true allow_app_hash:flags.4?true allow_missed_call:flags.5?true logout_tokens:flags.6?Vector = CodeSettings;\nwallPaperSettings#1dc1bca4 flags:# blur:flags.1?true motion:flags.2?true background_color:flags.0?int second_background_color:flags.4?int third_background_color:flags.5?int fourth_background_color:flags.6?int intensity:flags.3?int rotation:flags.4?int = WallPaperSettings;\nautoDownloadSettings#e04232f3 flags:# disabled:flags.0?true video_preload_large:flags.1?true audio_preload_next:flags.2?true phonecalls_less_data:flags.3?true photo_size_max:int video_size_max:int file_size_max:int video_upload_maxbitrate:int = AutoDownloadSettings;\naccount.autoDownloadSettings#63cacf26 low:AutoDownloadSettings medium:AutoDownloadSettings high:AutoDownloadSettings = account.AutoDownloadSettings;\nemojiKeyword#d5b3b9f9 keyword:string emoticons:Vector = EmojiKeyword;\nemojiKeywordDeleted#236df622 keyword:string emoticons:Vector = EmojiKeyword;\nemojiKeywordsDifference#5cc761bd lang_code:string from_version:int version:int keywords:Vector = EmojiKeywordsDifference;\nemojiURL#a575739d url:string = EmojiURL;\nemojiLanguage#b3fb5361 lang_code:string = EmojiLanguage;\nfolder#ff544e65 flags:# autofill_new_broadcasts:flags.0?true autofill_public_groups:flags.1?true autofill_new_correspondents:flags.2?true id:int title:string photo:flags.3?ChatPhoto = Folder;\ninputFolderPeer#fbd2c296 peer:InputPeer folder_id:int = InputFolderPeer;\nfolderPeer#e9baa668 peer:Peer folder_id:int = FolderPeer;\nmessages.searchCounter#e844ebff flags:# inexact:flags.1?true filter:MessagesFilter count:int = messages.SearchCounter;\nurlAuthResultRequest#92d33a0e flags:# request_write_access:flags.0?true bot:User domain:string = UrlAuthResult;\nurlAuthResultAccepted#8f8c0e4e url:string = UrlAuthResult;\nurlAuthResultDefault#a9d6db1f = UrlAuthResult;\nchannelLocationEmpty#bfb5ad8b = ChannelLocation;\nchannelLocation#209b82db geo_point:GeoPoint address:string = ChannelLocation;\npeerLocated#ca461b5d peer:Peer expires:int distance:int = PeerLocated;\npeerSelfLocated#f8ec284b expires:int = PeerLocated;\nrestrictionReason#d072acb4 platform:string reason:string text:string = RestrictionReason;\ninputTheme#3c5693e9 id:long access_hash:long = InputTheme;\ninputThemeSlug#f5890df1 slug:string = InputTheme;\ntheme#a00e67d6 flags:# creator:flags.0?true default:flags.1?true for_chat:flags.5?true id:long access_hash:long slug:string title:string document:flags.2?Document settings:flags.3?Vector emoticon:flags.6?string installs_count:flags.4?int = Theme;\naccount.themesNotModified#f41eb622 = account.Themes;\naccount.themes#9a3d8c6d hash:long themes:Vector = account.Themes;\nauth.loginToken#629f1980 expires:int token:bytes = auth.LoginToken;\nauth.loginTokenMigrateTo#68e9916 dc_id:int token:bytes = auth.LoginToken;\nauth.loginTokenSuccess#390d5c5e authorization:auth.Authorization = auth.LoginToken;\naccount.contentSettings#57e28221 flags:# sensitive_enabled:flags.0?true sensitive_can_change:flags.1?true = account.ContentSettings;\nmessages.inactiveChats#a927fec5 dates:Vector chats:Vector users:Vector = messages.InactiveChats;\nbaseThemeClassic#c3a12462 = BaseTheme;\nbaseThemeDay#fbd81688 = BaseTheme;\nbaseThemeNight#b7b31ea8 = BaseTheme;\nbaseThemeTinted#6d5f77ee = BaseTheme;\nbaseThemeArctic#5b11125a = BaseTheme;\ninputThemeSettings#8fde504f flags:# message_colors_animated:flags.2?true base_theme:BaseTheme accent_color:int outbox_accent_color:flags.3?int message_colors:flags.0?Vector wallpaper:flags.1?InputWallPaper wallpaper_settings:flags.1?WallPaperSettings = InputThemeSettings;\nthemeSettings#fa58b6d4 flags:# message_colors_animated:flags.2?true base_theme:BaseTheme accent_color:int outbox_accent_color:flags.3?int message_colors:flags.0?Vector wallpaper:flags.1?WallPaper = ThemeSettings;\nwebPageAttributeTheme#54b56617 flags:# documents:flags.0?Vector settings:flags.1?ThemeSettings = WebPageAttribute;\nmessageUserVote#34d247b4 user_id:long option:bytes date:int = MessageUserVote;\nmessageUserVoteInputOption#3ca5b0ec user_id:long date:int = MessageUserVote;\nmessageUserVoteMultiple#8a65e557 user_id:long options:Vector date:int = MessageUserVote;\nmessages.votesList#823f649 flags:# count:int votes:Vector users:Vector next_offset:flags.0?string = messages.VotesList;\nbankCardOpenUrl#f568028a url:string name:string = BankCardOpenUrl;\npayments.bankCardData#3e24e573 title:string open_urls:Vector = payments.BankCardData;\ndialogFilter#7438f7e8 flags:# contacts:flags.0?true non_contacts:flags.1?true groups:flags.2?true broadcasts:flags.3?true bots:flags.4?true exclude_muted:flags.11?true exclude_read:flags.12?true exclude_archived:flags.13?true id:int title:string emoticon:flags.25?string pinned_peers:Vector include_peers:Vector exclude_peers:Vector = DialogFilter;\ndialogFilterSuggested#77744d4a filter:DialogFilter description:string = DialogFilterSuggested;\nstatsDateRangeDays#b637edaf min_date:int max_date:int = StatsDateRangeDays;\nstatsAbsValueAndPrev#cb43acde current:double previous:double = StatsAbsValueAndPrev;\nstatsPercentValue#cbce2fe0 part:double total:double = StatsPercentValue;\nstatsGraphAsync#4a27eb2d token:string = StatsGraph;\nstatsGraphError#bedc9822 error:string = StatsGraph;\nstatsGraph#8ea464b6 flags:# json:DataJSON zoom_token:flags.0?string = StatsGraph;\nmessageInteractionCounters#ad4fc9bd msg_id:int views:int forwards:int = MessageInteractionCounters;\nstats.broadcastStats#bdf78394 period:StatsDateRangeDays followers:StatsAbsValueAndPrev views_per_post:StatsAbsValueAndPrev shares_per_post:StatsAbsValueAndPrev enabled_notifications:StatsPercentValue growth_graph:StatsGraph followers_graph:StatsGraph mute_graph:StatsGraph top_hours_graph:StatsGraph interactions_graph:StatsGraph iv_interactions_graph:StatsGraph views_by_source_graph:StatsGraph new_followers_by_source_graph:StatsGraph languages_graph:StatsGraph recent_message_interactions:Vector = stats.BroadcastStats;\nhelp.promoDataEmpty#98f6ac75 expires:int = help.PromoData;\nhelp.promoData#8c39793f flags:# proxy:flags.0?true expires:int peer:Peer chats:Vector users:Vector psa_type:flags.1?string psa_message:flags.2?string = help.PromoData;\nvideoSize#de33b094 flags:# type:string w:int h:int size:int video_start_ts:flags.0?double = VideoSize;\nstatsGroupTopPoster#9d04af9b user_id:long messages:int avg_chars:int = StatsGroupTopPoster;\nstatsGroupTopAdmin#d7584c87 user_id:long deleted:int kicked:int banned:int = StatsGroupTopAdmin;\nstatsGroupTopInviter#535f779d user_id:long invitations:int = StatsGroupTopInviter;\nstats.megagroupStats#ef7ff916 period:StatsDateRangeDays members:StatsAbsValueAndPrev messages:StatsAbsValueAndPrev viewers:StatsAbsValueAndPrev posters:StatsAbsValueAndPrev growth_graph:StatsGraph members_graph:StatsGraph new_members_by_source_graph:StatsGraph languages_graph:StatsGraph messages_graph:StatsGraph actions_graph:StatsGraph top_hours_graph:StatsGraph weekdays_graph:StatsGraph top_posters:Vector top_admins:Vector top_inviters:Vector users:Vector = stats.MegagroupStats;\nglobalPrivacySettings#bea2f424 flags:# archive_and_mute_new_noncontact_peers:flags.0?Bool = GlobalPrivacySettings;\nhelp.countryCode#4203c5ef flags:# country_code:string prefixes:flags.0?Vector patterns:flags.1?Vector = help.CountryCode;\nhelp.country#c3878e23 flags:# hidden:flags.0?true iso2:string default_name:string name:flags.1?string country_codes:Vector = help.Country;\nhelp.countriesListNotModified#93cc1f32 = help.CountriesList;\nhelp.countriesList#87d0759e countries:Vector hash:int = help.CountriesList;\nmessageViews#455b853d flags:# views:flags.0?int forwards:flags.1?int replies:flags.2?MessageReplies = MessageViews;\nmessages.messageViews#b6c4f543 views:Vector chats:Vector users:Vector = messages.MessageViews;\nmessages.discussionMessage#a6341782 flags:# messages:Vector max_id:flags.0?int read_inbox_max_id:flags.1?int read_outbox_max_id:flags.2?int unread_count:int chats:Vector users:Vector = messages.DiscussionMessage;\nmessageReplyHeader#a6d57763 flags:# reply_to_msg_id:int reply_to_peer_id:flags.0?Peer reply_to_top_id:flags.1?int = MessageReplyHeader;\nmessageReplies#83d60fc2 flags:# comments:flags.0?true replies:int replies_pts:int recent_repliers:flags.1?Vector channel_id:flags.0?long max_id:flags.2?int read_max_id:flags.3?int = MessageReplies;\npeerBlocked#e8fd8014 peer_id:Peer date:int = PeerBlocked;\nstats.messageStats#8999f295 views_graph:StatsGraph = stats.MessageStats;\ngroupCallDiscarded#7780bcb4 id:long access_hash:long duration:int = GroupCall;\ngroupCall#d597650c flags:# join_muted:flags.1?true can_change_join_muted:flags.2?true join_date_asc:flags.6?true schedule_start_subscribed:flags.8?true can_start_video:flags.9?true record_video_active:flags.11?true id:long access_hash:long participants_count:int title:flags.3?string stream_dc_id:flags.4?int record_start_date:flags.5?int schedule_date:flags.7?int unmuted_video_count:flags.10?int unmuted_video_limit:int version:int = GroupCall;\ninputGroupCall#d8aa840f id:long access_hash:long = InputGroupCall;\ngroupCallParticipant#eba636fe flags:# muted:flags.0?true left:flags.1?true can_self_unmute:flags.2?true just_joined:flags.4?true versioned:flags.5?true min:flags.8?true muted_by_you:flags.9?true volume_by_admin:flags.10?true self:flags.12?true video_joined:flags.15?true peer:Peer date:int active_date:flags.3?int source:int volume:flags.7?int about:flags.11?string raise_hand_rating:flags.13?long video:flags.6?GroupCallParticipantVideo presentation:flags.14?GroupCallParticipantVideo = GroupCallParticipant;\nphone.groupCall#9e727aad call:GroupCall participants:Vector participants_next_offset:string chats:Vector users:Vector = phone.GroupCall;\nphone.groupParticipants#f47751b6 count:int participants:Vector next_offset:string chats:Vector users:Vector version:int = phone.GroupParticipants;\ninlineQueryPeerTypeSameBotPM#3081ed9d = InlineQueryPeerType;\ninlineQueryPeerTypePM#833c0fac = InlineQueryPeerType;\ninlineQueryPeerTypeChat#d766c50a = InlineQueryPeerType;\ninlineQueryPeerTypeMegagroup#5ec4be43 = InlineQueryPeerType;\ninlineQueryPeerTypeBroadcast#6334ee9a = InlineQueryPeerType;\nmessages.historyImport#1662af0b id:long = messages.HistoryImport;\nmessages.historyImportParsed#5e0fb7b9 flags:# pm:flags.0?true group:flags.1?true title:flags.2?string = messages.HistoryImportParsed;\nmessages.affectedFoundMessages#ef8d3e6c pts:int pts_count:int offset:int messages:Vector = messages.AffectedFoundMessages;\nchatInviteImporter#8c5adfd9 flags:# requested:flags.0?true user_id:long date:int about:flags.2?string approved_by:flags.1?long = ChatInviteImporter;\nmessages.exportedChatInvites#bdc62dcc count:int invites:Vector users:Vector = messages.ExportedChatInvites;\nmessages.exportedChatInvite#1871be50 invite:ExportedChatInvite users:Vector = messages.ExportedChatInvite;\nmessages.exportedChatInviteReplaced#222600ef invite:ExportedChatInvite new_invite:ExportedChatInvite users:Vector = messages.ExportedChatInvite;\nmessages.chatInviteImporters#81b6b00a count:int importers:Vector users:Vector = messages.ChatInviteImporters;\nchatAdminWithInvites#f2ecef23 admin_id:long invites_count:int revoked_invites_count:int = ChatAdminWithInvites;\nmessages.chatAdminsWithInvites#b69b72d7 admins:Vector users:Vector = messages.ChatAdminsWithInvites;\nmessages.checkedHistoryImportPeer#a24de717 confirm_text:string = messages.CheckedHistoryImportPeer;\nphone.joinAsPeers#afe5623f peers:Vector chats:Vector users:Vector = phone.JoinAsPeers;\nphone.exportedGroupCallInvite#204bd158 link:string = phone.ExportedGroupCallInvite;\ngroupCallParticipantVideoSourceGroup#dcb118b7 semantics:string sources:Vector = GroupCallParticipantVideoSourceGroup;\ngroupCallParticipantVideo#67753ac8 flags:# paused:flags.0?true endpoint:string source_groups:Vector audio_source:flags.1?int = GroupCallParticipantVideo;\nstickers.suggestedShortName#85fea03f short_name:string = stickers.SuggestedShortName;\nbotCommandScopeDefault#2f6cb2ab = BotCommandScope;\nbotCommandScopeUsers#3c4f04d8 = BotCommandScope;\nbotCommandScopeChats#6fe1a881 = BotCommandScope;\nbotCommandScopeChatAdmins#b9aa606a = BotCommandScope;\nbotCommandScopePeer#db9d897d peer:InputPeer = BotCommandScope;\nbotCommandScopePeerAdmins#3fd863d1 peer:InputPeer = BotCommandScope;\nbotCommandScopePeerUser#a1321f3 peer:InputPeer user_id:InputUser = BotCommandScope;\naccount.resetPasswordFailedWait#e3779861 retry_date:int = account.ResetPasswordResult;\naccount.resetPasswordRequestedWait#e9effc7d until_date:int = account.ResetPasswordResult;\naccount.resetPasswordOk#e926d63e = account.ResetPasswordResult;\nsponsoredMessage#3a836df8 flags:# random_id:bytes from_id:flags.3?Peer chat_invite:flags.4?ChatInvite chat_invite_hash:flags.4?string channel_post:flags.2?int start_param:flags.0?string message:string entities:flags.1?Vector = SponsoredMessage;\nmessages.sponsoredMessages#65a4c7d5 messages:Vector chats:Vector users:Vector = messages.SponsoredMessages;\nsearchResultsCalendarPeriod#c9b0539f date:int min_msg_id:int max_msg_id:int count:int = SearchResultsCalendarPeriod;\nmessages.searchResultsCalendar#147ee23c flags:# inexact:flags.0?true count:int min_date:int min_msg_id:int offset_id_offset:flags.1?int periods:Vector messages:Vector chats:Vector users:Vector = messages.SearchResultsCalendar;\nsearchResultPosition#7f648b67 msg_id:int date:int offset:int = SearchResultsPosition;\nmessages.searchResultsPositions#53b22baf count:int positions:Vector = messages.SearchResultsPositions;\nchannels.sendAsPeers#8356cda9 peers:Vector chats:Vector users:Vector = channels.SendAsPeers;\nusers.userFull#3b6d152e full_user:UserFull chats:Vector users:Vector = users.UserFull;\nmessages.peerSettings#6880b94d settings:PeerSettings chats:Vector users:Vector = messages.PeerSettings;\nauth.loggedOut#c3a2835f flags:# future_auth_token:flags.0?bytes = auth.LoggedOut;\nreactionCount#6fb250d1 flags:# chosen:flags.0?true reaction:string count:int = ReactionCount;\nmessageReactions#87b6e36 flags:# min:flags.0?true can_see_list:flags.2?true results:Vector recent_reactons:flags.1?Vector = MessageReactions;\nmessageUserReaction#932844fa user_id:long reaction:string = MessageUserReaction;\nmessages.messageReactionsList#a366923c flags:# count:int reactions:Vector users:Vector next_offset:flags.0?string = messages.MessageReactionsList;\navailableReaction#21d7c4b flags:# inactive:flags.0?true reaction:string title:string static_icon:Document appear_animation:Document select_animation:Document activate_animation:Document effect_animation:Document = AvailableReaction;\nmessages.availableReactionsNotModified#9f071957 = messages.AvailableReactions;\nmessages.availableReactions#768e3aad hash:int reactions:Vector = messages.AvailableReactions;\n---functions---\ninitConnection#c1cd5ea9 {X:Type} flags:# api_id:int device_model:string system_version:string app_version:string system_lang_code:string lang_pack:string lang_code:string proxy:flags.0?InputClientProxy params:flags.1?JSONValue query:!X = X;\ninvokeWithLayer#da9b0d0d {X:Type} layer:int query:!X = X;\nauth.sendCode#a677244f phone_number:string api_id:int api_hash:string settings:CodeSettings = auth.SentCode;\nauth.signUp#80eee427 phone_number:string phone_code_hash:string first_name:string last_name:string = auth.Authorization;\nauth.signIn#bcd51581 phone_number:string phone_code_hash:string phone_code:string = auth.Authorization;\nauth.logOut#3e72ba19 = auth.LoggedOut;\nauth.resetAuthorizations#9fab0d1a = Bool;\nauth.exportAuthorization#e5bfffcd dc_id:int = auth.ExportedAuthorization;\nauth.importAuthorization#a57a7dad id:long bytes:bytes = auth.Authorization;\nauth.bindTempAuthKey#cdd42a05 perm_auth_key_id:long nonce:long expires_at:int encrypted_message:bytes = Bool;\nauth.checkPassword#d18b4d16 password:InputCheckPasswordSRP = auth.Authorization;\nauth.requestPasswordRecovery#d897bc66 = auth.PasswordRecovery;\nauth.resendCode#3ef1a9bf phone_number:string phone_code_hash:string = auth.SentCode;\nauth.cancelCode#1f040578 phone_number:string phone_code_hash:string = Bool;\nauth.dropTempAuthKeys#8e48a188 except_auth_keys:Vector = Bool;\nauth.exportLoginToken#b7e085fe api_id:int api_hash:string except_ids:Vector = auth.LoginToken;\nauth.importLoginToken#95ac5ce4 token:bytes = auth.LoginToken;\naccount.registerDevice#ec86017a flags:# no_muted:flags.0?true token_type:int token:string app_sandbox:Bool secret:bytes other_uids:Vector = Bool;\naccount.unregisterDevice#6a0d3206 token_type:int token:string other_uids:Vector = Bool;\naccount.updateNotifySettings#84be5b93 peer:InputNotifyPeer settings:InputPeerNotifySettings = Bool;\naccount.getNotifySettings#12b3ad31 peer:InputNotifyPeer = PeerNotifySettings;\naccount.updateProfile#78515775 flags:# first_name:flags.0?string last_name:flags.1?string about:flags.2?string = User;\naccount.updateStatus#6628562c offline:Bool = Bool;\naccount.getWallPapers#7967d36 hash:long = account.WallPapers;\naccount.checkUsername#2714d86c username:string = Bool;\naccount.updateUsername#3e0bdd7c username:string = User;\naccount.getPrivacy#dadbc950 key:InputPrivacyKey = account.PrivacyRules;\naccount.setPrivacy#c9f81ce8 key:InputPrivacyKey rules:Vector = account.PrivacyRules;\naccount.getAuthorizations#e320c158 = account.Authorizations;\naccount.resetAuthorization#df77f3bc hash:long = Bool;\naccount.getPassword#548a30f5 = account.Password;\naccount.getPasswordSettings#9cd4eaf9 password:InputCheckPasswordSRP = account.PasswordSettings;\naccount.updatePasswordSettings#a59b102f password:InputCheckPasswordSRP new_settings:account.PasswordInputSettings = Bool;\naccount.sendConfirmPhoneCode#1b3faa88 hash:string settings:CodeSettings = auth.SentCode;\naccount.confirmPhone#5f2178c3 phone_code_hash:string phone_code:string = Bool;\naccount.getTmpPassword#449e0b51 password:InputCheckPasswordSRP period:int = account.TmpPassword;\naccount.sendVerifyPhoneCode#a5a356f9 phone_number:string settings:CodeSettings = auth.SentCode;\naccount.confirmPasswordEmail#8fdf1920 code:string = Bool;\naccount.getContactSignUpNotification#9f07c728 = Bool;\naccount.setContactSignUpNotification#cff43f61 silent:Bool = Bool;\naccount.getNotifyExceptions#53577479 flags:# compare_sound:flags.1?true peer:flags.0?InputNotifyPeer = Updates;\naccount.uploadWallPaper#dd853661 file:InputFile mime_type:string settings:WallPaperSettings = WallPaper;\naccount.setContentSettings#b574b16b flags:# sensitive_enabled:flags.0?true = Bool;\naccount.getContentSettings#8b9b4dae = account.ContentSettings;\nusers.getUsers#d91a548 id:Vector = Vector;\nusers.getFullUser#b60f5918 id:InputUser = users.UserFull;\ncontacts.getContacts#5dd69e12 hash:long = contacts.Contacts;\ncontacts.importContacts#2c800be5 contacts:Vector = contacts.ImportedContacts;\ncontacts.deleteContacts#96a0e00 id:Vector = Updates;\ncontacts.block#68cc1411 id:InputPeer = Bool;\ncontacts.unblock#bea65d50 id:InputPeer = Bool;\ncontacts.getBlocked#f57c350f offset:int limit:int = contacts.Blocked;\ncontacts.search#11f812d8 q:string limit:int = contacts.Found;\ncontacts.resolveUsername#f93ccba3 username:string = contacts.ResolvedPeer;\ncontacts.getTopPeers#973478b6 flags:# correspondents:flags.0?true bots_pm:flags.1?true bots_inline:flags.2?true phone_calls:flags.3?true forward_users:flags.4?true forward_chats:flags.5?true groups:flags.10?true channels:flags.15?true offset:int limit:int hash:long = contacts.TopPeers;\ncontacts.addContact#e8f463d0 flags:# add_phone_privacy_exception:flags.0?true id:InputUser first_name:string last_name:string phone:string = Updates;\nmessages.getMessages#63c66506 id:Vector = messages.Messages;\nmessages.getDialogs#a0f4cb4f flags:# exclude_pinned:flags.0?true folder_id:flags.1?int offset_date:int offset_id:int offset_peer:InputPeer limit:int hash:long = messages.Dialogs;\nmessages.getHistory#4423e6c5 peer:InputPeer offset_id:int offset_date:int add_offset:int limit:int max_id:int min_id:int hash:long = messages.Messages;\nmessages.search#a0fda762 flags:# peer:InputPeer q:string from_id:flags.0?InputPeer top_msg_id:flags.1?int filter:MessagesFilter min_date:int max_date:int offset_id:int add_offset:int limit:int max_id:int min_id:int hash:long = messages.Messages;\nmessages.readHistory#e306d3a peer:InputPeer max_id:int = messages.AffectedMessages;\nmessages.deleteHistory#b08f922a flags:# just_clear:flags.0?true revoke:flags.1?true peer:InputPeer max_id:int min_date:flags.2?int max_date:flags.3?int = messages.AffectedHistory;\nmessages.deleteMessages#e58e95d2 flags:# revoke:flags.0?true id:Vector = messages.AffectedMessages;\nmessages.receivedMessages#5a954c0 max_id:int = Vector;\nmessages.setTyping#58943ee2 flags:# peer:InputPeer top_msg_id:flags.0?int action:SendMessageAction = Bool;\nmessages.sendMessage#d9d75a4 flags:# no_webpage:flags.1?true silent:flags.5?true background:flags.6?true clear_draft:flags.7?true noforwards:flags.14?true peer:InputPeer reply_to_msg_id:flags.0?int message:string random_id:long reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector schedule_date:flags.10?int send_as:flags.13?InputPeer = Updates;\nmessages.sendMedia#e25ff8e0 flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true noforwards:flags.14?true peer:InputPeer reply_to_msg_id:flags.0?int media:InputMedia message:string random_id:long reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector schedule_date:flags.10?int send_as:flags.13?InputPeer = Updates;\nmessages.forwardMessages#cc30290b flags:# silent:flags.5?true background:flags.6?true with_my_score:flags.8?true drop_author:flags.11?true drop_media_captions:flags.12?true noforwards:flags.14?true from_peer:InputPeer id:Vector random_id:Vector to_peer:InputPeer schedule_date:flags.10?int send_as:flags.13?InputPeer = Updates;\nmessages.report#8953ab4e peer:InputPeer id:Vector reason:ReportReason message:string = Bool;\nmessages.getChats#49e9528f id:Vector = messages.Chats;\nmessages.getFullChat#aeb00b34 chat_id:long = messages.ChatFull;\nmessages.editChatTitle#73783ffd chat_id:long title:string = Updates;\nmessages.editChatPhoto#35ddd674 chat_id:long photo:InputChatPhoto = Updates;\nmessages.addChatUser#f24753e3 chat_id:long user_id:InputUser fwd_limit:int = Updates;\nmessages.deleteChatUser#a2185cab flags:# revoke_history:flags.0?true chat_id:long user_id:InputUser = Updates;\nmessages.createChat#9cb126e users:Vector title:string = Updates;\nmessages.getDhConfig#26cf8950 version:int random_length:int = messages.DhConfig;\nmessages.readMessageContents#36a73f77 id:Vector = messages.AffectedMessages;\nmessages.getStickers#d5a5d3a1 emoticon:string hash:long = messages.Stickers;\nmessages.getAllStickers#b8a0a1a8 hash:long = messages.AllStickers;\nmessages.getWebPagePreview#8b68b0cc flags:# message:string entities:flags.3?Vector = MessageMedia;\nmessages.exportChatInvite#a02ce5d5 flags:# legacy_revoke_permanent:flags.2?true request_needed:flags.3?true peer:InputPeer expire_date:flags.0?int usage_limit:flags.1?int title:flags.4?string = ExportedChatInvite;\nmessages.checkChatInvite#3eadb1bb hash:string = ChatInvite;\nmessages.importChatInvite#6c50051c hash:string = Updates;\nmessages.getStickerSet#c8a0ec74 stickerset:InputStickerSet hash:int = messages.StickerSet;\nmessages.installStickerSet#c78fe460 stickerset:InputStickerSet archived:Bool = messages.StickerSetInstallResult;\nmessages.uninstallStickerSet#f96e55de stickerset:InputStickerSet = Bool;\nmessages.startBot#e6df7378 bot:InputUser peer:InputPeer random_id:long start_param:string = Updates;\nmessages.migrateChat#a2875319 chat_id:long = Updates;\nmessages.searchGlobal#4bc6589a flags:# folder_id:flags.0?int q:string filter:MessagesFilter min_date:int max_date:int offset_rate:int offset_peer:InputPeer offset_id:int limit:int = messages.Messages;\nmessages.getDocumentByHash#338e2464 sha256:bytes size:int mime_type:string = Document;\nmessages.getSavedGifs#5cf09635 hash:long = messages.SavedGifs;\nmessages.getInlineBotResults#514e999d flags:# bot:InputUser peer:InputPeer geo_point:flags.0?InputGeoPoint query:string offset:string = messages.BotResults;\nmessages.sendInlineBotResult#7aa11297 flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true hide_via:flags.11?true peer:InputPeer reply_to_msg_id:flags.0?int random_id:long query_id:long id:string schedule_date:flags.10?int send_as:flags.13?InputPeer = Updates;\nmessages.editMessage#48f71778 flags:# no_webpage:flags.1?true peer:InputPeer id:int message:flags.11?string media:flags.14?InputMedia reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector schedule_date:flags.15?int = Updates;\nmessages.getBotCallbackAnswer#9342ca07 flags:# game:flags.1?true peer:InputPeer msg_id:int data:flags.0?bytes password:flags.2?InputCheckPasswordSRP = messages.BotCallbackAnswer;\nmessages.getPeerDialogs#e470bcfd peers:Vector = messages.PeerDialogs;\nmessages.saveDraft#bc39e14b flags:# no_webpage:flags.1?true reply_to_msg_id:flags.0?int peer:InputPeer message:string entities:flags.3?Vector = Bool;\nmessages.getFeaturedStickers#64780b14 hash:long = messages.FeaturedStickers;\nmessages.readFeaturedStickers#5b118126 id:Vector = Bool;\nmessages.getRecentStickers#9da9403b flags:# attached:flags.0?true hash:long = messages.RecentStickers;\nmessages.getCommonChats#e40ca104 user_id:InputUser max_id:long limit:int = messages.Chats;\nmessages.getWebPage#32ca8f91 url:string hash:int = WebPage;\nmessages.toggleDialogPin#a731e257 flags:# pinned:flags.0?true peer:InputDialogPeer = Bool;\nmessages.getPinnedDialogs#d6b94df2 folder_id:int = messages.PeerDialogs;\nmessages.uploadMedia#519bc2b1 peer:InputPeer media:InputMedia = MessageMedia;\nmessages.getFavedStickers#4f1aaa9 hash:long = messages.FavedStickers;\nmessages.faveSticker#b9ffc55b id:InputDocument unfave:Bool = Bool;\nmessages.sendMultiMedia#f803138f flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true noforwards:flags.14?true peer:InputPeer reply_to_msg_id:flags.0?int multi_media:Vector schedule_date:flags.10?int send_as:flags.13?InputPeer = Updates;\nmessages.searchStickerSets#35705b8a flags:# exclude_featured:flags.0?true q:string hash:long = messages.FoundStickerSets;\nmessages.markDialogUnread#c286d98f flags:# unread:flags.0?true peer:InputDialogPeer = Bool;\nmessages.updatePinnedMessage#d2aaf7ec flags:# silent:flags.0?true unpin:flags.1?true pm_oneside:flags.2?true peer:InputPeer id:int = Updates;\nmessages.sendVote#10ea6184 peer:InputPeer msg_id:int options:Vector = Updates;\nmessages.getOnlines#6e2be050 peer:InputPeer = ChatOnlines;\nmessages.editChatAbout#def60797 peer:InputPeer about:string = Bool;\nmessages.editChatDefaultBannedRights#a5866b41 peer:InputPeer banned_rights:ChatBannedRights = Updates;\nmessages.getEmojiKeywordsDifference#1508b6af lang_code:string from_version:int = EmojiKeywordsDifference;\nmessages.getScheduledHistory#f516760b peer:InputPeer hash:long = messages.Messages;\nmessages.sendScheduledMessages#bd38850a peer:InputPeer id:Vector = Updates;\nmessages.deleteScheduledMessages#59ae2b16 peer:InputPeer id:Vector = Updates;\nmessages.getPollVotes#b86e380e flags:# peer:InputPeer id:int option:flags.0?bytes offset:flags.1?string limit:int = messages.VotesList;\nmessages.getDialogFilters#f19ed96d = Vector;\nmessages.getSuggestedDialogFilters#a29cd42c = Vector;\nmessages.updateDialogFilter#1ad4a04a flags:# id:int filter:flags.0?DialogFilter = Bool;\nmessages.getReplies#22ddd30c peer:InputPeer msg_id:int offset_id:int offset_date:int add_offset:int limit:int max_id:int min_id:int hash:long = messages.Messages;\nmessages.getDiscussionMessage#446972fd peer:InputPeer msg_id:int = messages.DiscussionMessage;\nmessages.readDiscussion#f731a9f4 peer:InputPeer msg_id:int read_max_id:int = Bool;\nmessages.unpinAllMessages#f025bc8b peer:InputPeer = messages.AffectedHistory;\nmessages.deleteChat#5bd0ee50 chat_id:long = Bool;\nmessages.getMessageReadParticipants#2c6f97b7 peer:InputPeer msg_id:int = Vector;\nmessages.toggleNoForwards#b11eafa2 peer:InputPeer enabled:Bool = Updates;\nmessages.saveDefaultSendAs#ccfddf96 peer:InputPeer send_as:InputPeer = Bool;\nupdates.getState#edd4882a = updates.State;\nupdates.getDifference#25939651 flags:# pts:int pts_total_limit:flags.0?int date:int qts:int = updates.Difference;\nupdates.getChannelDifference#3173d78 flags:# force:flags.0?true channel:InputChannel filter:ChannelMessagesFilter pts:int limit:int = updates.ChannelDifference;\nphotos.uploadProfilePhoto#89f30f69 flags:# file:flags.0?InputFile video:flags.1?InputFile video_start_ts:flags.2?double = photos.Photo;\nphotos.getUserPhotos#91cd32a8 user_id:InputUser offset:int max_id:long limit:int = photos.Photos;\nupload.saveFilePart#b304a621 file_id:long file_part:int bytes:bytes = Bool;\nupload.getFile#b15a9afc flags:# precise:flags.0?true cdn_supported:flags.1?true location:InputFileLocation offset:int limit:int = upload.File;\nupload.saveBigFilePart#de7b673d file_id:long file_part:int file_total_parts:int bytes:bytes = Bool;\nupload.getWebFile#24e6818d location:InputWebFileLocation offset:int limit:int = upload.WebFile;\nhelp.getConfig#c4f9186b = Config;\nhelp.getNearestDc#1fb33026 = NearestDc;\nhelp.getSupport#9cdf08cd = help.Support;\nhelp.acceptTermsOfService#ee72f79a id:DataJSON = Bool;\nhelp.getCountriesList#735787a8 lang_code:string hash:int = help.CountriesList;\nchannels.readHistory#cc104937 channel:InputChannel max_id:int = Bool;\nchannels.deleteMessages#84c1fd4e channel:InputChannel id:Vector = messages.AffectedMessages;\nchannels.getMessages#ad8c9a23 channel:InputChannel id:Vector = messages.Messages;\nchannels.getParticipants#77ced9d0 channel:InputChannel filter:ChannelParticipantsFilter offset:int limit:int hash:long = channels.ChannelParticipants;\nchannels.getParticipant#a0ab6cc6 channel:InputChannel participant:InputPeer = channels.ChannelParticipant;\nchannels.getChannels#a7f6bbb id:Vector = messages.Chats;\nchannels.getFullChannel#8736a09 channel:InputChannel = messages.ChatFull;\nchannels.createChannel#3d5fb10f flags:# broadcast:flags.0?true megagroup:flags.1?true for_import:flags.3?true title:string about:string geo_point:flags.2?InputGeoPoint address:flags.2?string = Updates;\nchannels.editAdmin#d33c8902 channel:InputChannel user_id:InputUser admin_rights:ChatAdminRights rank:string = Updates;\nchannels.editTitle#566decd0 channel:InputChannel title:string = Updates;\nchannels.editPhoto#f12e57c9 channel:InputChannel photo:InputChatPhoto = Updates;\nchannels.checkUsername#10e6bd2c channel:InputChannel username:string = Bool;\nchannels.updateUsername#3514b3de channel:InputChannel username:string = Bool;\nchannels.joinChannel#24b524c5 channel:InputChannel = Updates;\nchannels.leaveChannel#f836aa95 channel:InputChannel = Updates;\nchannels.inviteToChannel#199f3a6c channel:InputChannel users:Vector = Updates;\nchannels.deleteChannel#c0111fe3 channel:InputChannel = Updates;\nchannels.toggleSignatures#1f69b606 channel:InputChannel enabled:Bool = Updates;\nchannels.editBanned#96e6cd81 channel:InputChannel participant:InputPeer banned_rights:ChatBannedRights = Updates;\nchannels.readMessageContents#eab5dc38 channel:InputChannel id:Vector = Bool;\nchannels.togglePreHistoryHidden#eabbb94c channel:InputChannel enabled:Bool = Updates;\nchannels.getGroupsForDiscussion#f5dad378 = messages.Chats;\nchannels.setDiscussionGroup#40582bb2 broadcast:InputChannel group:InputChannel = Bool;\nchannels.viewSponsoredMessage#beaedb94 channel:InputChannel random_id:bytes = Bool;\nchannels.getSponsoredMessages#ec210fbf channel:InputChannel = messages.SponsoredMessages;\nchannels.getSendAs#dc770ee peer:InputPeer = channels.SendAsPeers;\npayments.getPaymentForm#8a333c8d flags:# peer:InputPeer msg_id:int theme_params:flags.0?DataJSON = payments.PaymentForm;\npayments.getPaymentReceipt#2478d1cc peer:InputPeer msg_id:int = payments.PaymentReceipt;\npayments.validateRequestedInfo#db103170 flags:# save:flags.0?true peer:InputPeer msg_id:int info:PaymentRequestedInfo = payments.ValidatedRequestedInfo;\npayments.sendPaymentForm#30c3bc9d flags:# form_id:long peer:InputPeer msg_id:int requested_info_id:flags.0?string shipping_option_id:flags.1?string credentials:InputPaymentCredentials tip_amount:flags.2?long = payments.PaymentResult;\npayments.getSavedInfo#227d824b = payments.SavedInfo;\nphone.createGroupCall#48cdc6d8 flags:# peer:InputPeer random_id:int title:flags.0?string schedule_date:flags.1?int = Updates;\nphone.joinGroupCall#b132ff7b flags:# muted:flags.0?true video_stopped:flags.2?true call:InputGroupCall join_as:InputPeer invite_hash:flags.1?string params:DataJSON = Updates;\nphone.leaveGroupCall#500377f9 call:InputGroupCall source:int = Updates;\nphone.discardGroupCall#7a777135 call:InputGroupCall = Updates;\nphone.getGroupCall#41845db call:InputGroupCall limit:int = phone.GroupCall;\nphone.getGroupParticipants#c558d8ab call:InputGroupCall ids:Vector sources:Vector offset:string limit:int = phone.GroupParticipants;\nphone.editGroupCallParticipant#a5273abf flags:# call:InputGroupCall participant:InputPeer muted:flags.0?Bool volume:flags.1?int raise_hand:flags.2?Bool video_stopped:flags.3?Bool video_paused:flags.4?Bool presentation_paused:flags.5?Bool = Updates;\nphone.exportGroupCallInvite#e6aa647f flags:# can_self_unmute:flags.0?true call:InputGroupCall = phone.ExportedGroupCallInvite;\nphone.toggleGroupCallStartSubscription#219c34e6 call:InputGroupCall subscribed:Bool = Updates;\nphone.joinGroupCallPresentation#cbea6bc4 call:InputGroupCall params:DataJSON = Updates;\nphone.leaveGroupCallPresentation#1c50d144 call:InputGroupCall = Updates;\nlangpack.getLangPack#f2f2330a lang_pack:string lang_code:string = LangPackDifference;\nlangpack.getStrings#efea3803 lang_pack:string lang_code:string keys:Vector = Vector;\nlangpack.getLanguages#42c6978f lang_pack:string = Vector;\nfolders.editPeerFolders#6847d0ab folder_peers:Vector = Updates;"},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;\np_q_inner_data_dc#a9f55f95 pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 dc:int = P_Q_inner_data;\np_q_inner_data_temp#3c6a84d4 pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 expires_in:int = P_Q_inner_data;\np_q_inner_data_temp_dc#56fddf88 pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 dc:int expires_in:int = P_Q_inner_data;\nserver_DH_params_fail#79cb045d nonce:int128 server_nonce:int128 new_nonce_hash:int128 = Server_DH_Params;\nserver_DH_params_ok#d0e8075c nonce:int128 server_nonce:int128 encrypted_answer:string = Server_DH_Params;\nserver_DH_inner_data#b5890dba nonce:int128 server_nonce:int128 g:int dh_prime:string g_a:string server_time:int = Server_DH_inner_data;\nclient_DH_inner_data#6643b654 nonce:int128 server_nonce:int128 retry_id:long g_b:string = Client_DH_Inner_Data;\ndh_gen_ok#3bcbf734 nonce:int128 server_nonce:int128 new_nonce_hash1:int128 = Set_client_DH_params_answer;\ndh_gen_retry#46dc1fb9 nonce:int128 server_nonce:int128 new_nonce_hash2:int128 = Set_client_DH_params_answer;\ndh_gen_fail#a69dae02 nonce:int128 server_nonce:int128 new_nonce_hash3:int128 = Set_client_DH_params_answer;\ndestroy_auth_key_ok#f660e1d4 = DestroyAuthKeyRes;\ndestroy_auth_key_none#0a9f2259 = DestroyAuthKeyRes;\ndestroy_auth_key_fail#ea109b13 = DestroyAuthKeyRes;\n---functions---\nreq_pq#60469778 nonce:int128 = ResPQ;\nreq_pq_multi#be7e8ef1 nonce:int128 = ResPQ;\nreq_pq_multi_new#51b410fd nonce:int128 = ResPQ;\nreq_DH_params#d712e4be nonce:int128 server_nonce:int128 p:string q:string public_key_fingerprint:long encrypted_data:string = Server_DH_Params;\nset_client_DH_params#f5045f1f nonce:int128 server_nonce:int128 encrypted_data:string = Set_client_DH_params_answer;\ndestroy_auth_key#d1435160 = DestroyAuthKeyRes;\n---types---\nmsgs_ack#62d6b459 msg_ids:Vector = MsgsAck;\nbad_msg_notification#a7eff811 bad_msg_id:long bad_msg_seqno:int error_code:int = BadMsgNotification;\nbad_server_salt#edab447b bad_msg_id:long bad_msg_seqno:int error_code:int new_server_salt:long = BadMsgNotification;\nmsgs_state_req#da69fb52 msg_ids:Vector = MsgsStateReq;\nmsgs_state_info#04deb57d req_msg_id:long info:string = MsgsStateInfo;\nmsgs_all_info#8cc0d131 msg_ids:Vector info:string = MsgsAllInfo;\nmsg_detailed_info#276d3ec6 msg_id:long answer_msg_id:long bytes:int status:int = MsgDetailedInfo;\nmsg_new_detailed_info#809db6df answer_msg_id:long bytes:int status:int = MsgDetailedInfo;\nmsg_resend_req#7d861a08 msg_ids:Vector = MsgResendReq;\nrpc_error#2144ca19 error_code:int error_message:string = RpcError;\nrpc_answer_unknown#5e2ad36e = RpcDropAnswer;\nrpc_answer_dropped_running#cd78e586 = RpcDropAnswer;\nrpc_answer_dropped#a43ad8b7 msg_id:long seq_no:int bytes:int = RpcDropAnswer;\nfuture_salt#0949d9dc valid_since:int valid_until:int salt:long = FutureSalt;\nfuture_salts#ae500895 req_msg_id:long now:int salts:vector = FutureSalts;\npong#347773c5 msg_id:long ping_id:long = Pong;\ndestroy_session_ok#e22045fc session_id:long = DestroySessionRes;\ndestroy_session_none#62d350c9 session_id:long = DestroySessionRes;\nnew_session_created#9ec20908 first_msg_id:long unique_id:long server_salt:long = NewSession;\nhttp_wait#9299359f max_delay:int wait_after:int max_wait:int = HttpWait;\nipPort#d433ad73 ipv4:int port:int = IpPort;\nipPortSecret#37982646 ipv4:int port:int secret:bytes = IpPort;\naccessPointRule#4679b65f phone_prefix_rules:string dc_id:int ips:vector = AccessPointRule;\nhelp.configSimple#5a592a6c date:int expires:int rules:vector = help.ConfigSimple;\ntlsClientHello blocks:vector = TlsClientHello;\ntlsBlockString data:string = TlsBlock;\ntlsBlockRandom length:int = TlsBlock;\ntlsBlockZero length:int = TlsBlock;\ntlsBlockDomain = TlsBlock;\ntlsBlockGrease seed:int = TlsBlock;\ntlsBlockScope entries:Vector = TlsBlock;\n---functions---\nping#7abe77ec ping_id:long = Pong;\nping_delay_disconnect#f3427b8c ping_id:long disconnect_delay:int = Pong;"}},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(6927)));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={927: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=927.151d396500bf8aa6cf1e.js.map \ No newline at end of file diff --git a/dist/927.04b93a71a7d051ccd448.js.map b/dist/927.151d396500bf8aa6cf1e.js.map similarity index 99% rename from dist/927.04b93a71a7d051ccd448.js.map rename to dist/927.151d396500bf8aa6cf1e.js.map index 5fcc3bea..9cfd53c5 100644 --- a/dist/927.04b93a71a7d051ccd448.js.map +++ b/dist/927.151d396500bf8aa6cf1e.js.map @@ -1 +1 @@ -{"version":3,"file":"927.04b93a71a7d051ccd448.js","mappings":"UAAIA,ECAAC,E,ujICAG,MA0GMC,GAnEyB,oBAAXC,QAA0BA,OAAOC,YAmEzBC,KAAKC,MAAM,MACjCC,EAA6B,IAAIC,IAAI,CAChD,aAAc,sBAAuB,iBAAkB,0BAA2B,kBA0BvEC,EAAgC,IAAID,IAAI,CACnD,YAAa,YAAa,eAGfE,EAAgC,IAAIF,IAAI,CACnD,cAoBWG,GAjB6B,IAAIH,IAAI,IAC7CC,KACAC,IAYyC,IAAIF,IAAI,CAAC,KAAM,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,IAChBw5B,EAAoBjhE,EAAE,KAAKsiC,KAAKl3C,GmHDd61E,EAAoBx5B,K","sources":["webpack://telegram-t/webpack/runtime/chunk loaded","webpack://telegram-t/webpack/runtime/startup chunk dependencies","webpack://telegram-t/./src/config.ts","webpack://telegram-t/./src/util/schedulers.ts","webpack://telegram-t/./src/util/iteratees.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/helpers.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/pathBytesToSvg.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/common.ts","webpack://telegram-t/./src/api/gramjs/localDb.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/symbols.ts","webpack://telegram-t/./src/util/waveform.ts","webpack://telegram-t/./src/api/types/messages.ts","webpack://telegram-t/./src/api/types/media.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/peers.ts","webpack://telegram-t/./src/api/gramjs/helpers.ts","webpack://telegram-t/./src/api/gramjs/gramjsBuilders/index.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/messages.ts","webpack://telegram-t/./src/util/serverTime.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/chats.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/users.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/misc.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/calls.ts","webpack://telegram-t/./src/api/gramjs/updater.ts","webpack://telegram-t/./src/api/gramjs/methods/auth.ts","webpack://telegram-t/./src/util/cacheApi.ts","webpack://telegram-t/./src/api/gramjs/methods/media.ts","webpack://telegram-t/./src/api/gramjs/methods/client.ts","webpack://telegram-t/./src/api/gramjs/methods/chats.ts","webpack://telegram-t/./src/util/files.ts","webpack://telegram-t/./src/api/gramjs/methods/messages.ts","webpack://telegram-t/./src/api/gramjs/methods/users.ts","webpack://telegram-t/./src/api/gramjs/methods/symbols.ts","webpack://telegram-t/./src/api/gramjs/methods/management.ts","webpack://telegram-t/./src/api/gramjs/methods/twoFaSettings.ts","webpack://telegram-t/./src/api/gramjs/methods/calls.ts","webpack://telegram-t/./src/api/gramjs/methods/settings.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/bots.ts","webpack://telegram-t/./src/api/gramjs/methods/bots.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/payments.ts","webpack://telegram-t/./src/api/gramjs/methods/payments.ts","webpack://telegram-t/./src/api/gramjs/provider.ts","webpack://telegram-t/./src/api/gramjs/worker/worker.ts","webpack://telegram-t/./src/lib/gramjs/Helpers.js","webpack://telegram-t/./src/lib/gramjs/Password.js","webpack://telegram-t/./src/lib/gramjs/Utils.js","webpack://telegram-t/./src/lib/gramjs/Version.js","webpack://telegram-t/./src/lib/gramjs/client/2fa.ts","webpack://telegram-t/./src/lib/gramjs/client/TelegramClient.js","webpack://telegram-t/./src/lib/gramjs/client/auth.ts","webpack://telegram-t/./src/lib/gramjs/client/downloadFile.ts","webpack://telegram-t/./src/lib/gramjs/client/uploadFile.ts","webpack://telegram-t/./src/lib/gramjs/crypto/AuthKey.js","webpack://telegram-t/./src/lib/gramjs/crypto/CTR.js","webpack://telegram-t/./src/lib/gramjs/crypto/Factorizator.js","webpack://telegram-t/./src/lib/gramjs/crypto/IGE.js","webpack://telegram-t/./src/lib/gramjs/crypto/converters.ts","webpack://telegram-t/./src/lib/gramjs/crypto/crypto.js","webpack://telegram-t/./src/lib/gramjs/crypto/words.ts","webpack://telegram-t/./src/lib/gramjs/errors/Common.js","webpack://telegram-t/./src/lib/gramjs/errors/RPCBaseErrors.js","webpack://telegram-t/./src/lib/gramjs/errors/RPCErrorList.js","webpack://telegram-t/./src/lib/gramjs/errors/index.js","webpack://telegram-t/./src/lib/gramjs/events/Raw.js","webpack://telegram-t/./src/lib/gramjs/events/common.js","webpack://telegram-t/./src/lib/gramjs/events/index.js","webpack://telegram-t/./src/lib/gramjs/extensions/AsyncQueue.js","webpack://telegram-t/./src/lib/gramjs/extensions/BinaryReader.js","webpack://telegram-t/./src/lib/gramjs/extensions/BinaryWriter.js","webpack://telegram-t/./src/lib/gramjs/extensions/Logger.js","webpack://telegram-t/./src/lib/gramjs/extensions/MessagePacker.js","webpack://telegram-t/./src/lib/gramjs/extensions/PromisedWebSockets.js","webpack://telegram-t/./src/lib/gramjs/extensions/index.js","webpack://telegram-t/./src/lib/gramjs/index.js","webpack://telegram-t/./src/lib/gramjs/crypto/RSA.ts","webpack://telegram-t/./src/lib/gramjs/network/Authenticator.ts","webpack://telegram-t/./src/lib/gramjs/network/MTProtoPlainSender.js","webpack://telegram-t/./src/lib/gramjs/network/MTProtoSender.js","webpack://telegram-t/./src/lib/gramjs/network/MTProtoState.js","webpack://telegram-t/./src/lib/gramjs/network/RequestState.js","webpack://telegram-t/./src/lib/gramjs/network/connection/Connection.js","webpack://telegram-t/./src/lib/gramjs/network/connection/TCPAbridged.js","webpack://telegram-t/./src/lib/gramjs/network/connection/TCPObfuscated.js","webpack://telegram-t/./src/lib/gramjs/network/connection/index.js","webpack://telegram-t/./src/lib/gramjs/network/index.js","webpack://telegram-t/./src/lib/gramjs/sessions/Abstract.js","webpack://telegram-t/./src/lib/gramjs/sessions/CacheApiSession.js","webpack://telegram-t/./src/lib/gramjs/sessions/CallbackSession.js","webpack://telegram-t/./src/lib/gramjs/sessions/IdbSession.js","webpack://telegram-t/./src/lib/gramjs/sessions/LocalStorageSession.js","webpack://telegram-t/./src/lib/gramjs/sessions/Memory.js","webpack://telegram-t/./src/lib/gramjs/sessions/StorageSession.js","webpack://telegram-t/./src/lib/gramjs/sessions/StringSession.js","webpack://telegram-t/./src/lib/gramjs/sessions/index.js","webpack://telegram-t/./src/lib/gramjs/tl/AllTLObjects.js","webpack://telegram-t/./src/lib/gramjs/tl/api.js","webpack://telegram-t/./src/lib/gramjs/tl/apiTl.js","webpack://telegram-t/./src/lib/gramjs/tl/core/GZIPPacked.js","webpack://telegram-t/./src/lib/gramjs/tl/core/MessageContainer.js","webpack://telegram-t/./src/lib/gramjs/tl/core/RPCResult.js","webpack://telegram-t/./src/lib/gramjs/tl/core/TLMessage.js","webpack://telegram-t/./src/lib/gramjs/tl/core/index.js","webpack://telegram-t/./src/lib/gramjs/tl/generationHelpers.js","webpack://telegram-t/./src/lib/gramjs/tl/index.js","webpack://telegram-t/./src/lib/gramjs/tl/schemaTl.js","webpack://telegram-t/webpack/bootstrap","webpack://telegram-t/webpack/runtime/compat get default export","webpack://telegram-t/webpack/runtime/define property getters","webpack://telegram-t/webpack/runtime/ensure chunk","webpack://telegram-t/webpack/runtime/get javascript chunk filename","webpack://telegram-t/webpack/runtime/get mini-css chunk filename","webpack://telegram-t/webpack/runtime/global","webpack://telegram-t/webpack/runtime/hasOwnProperty shorthand","webpack://telegram-t/webpack/runtime/make namespace object","webpack://telegram-t/webpack/runtime/node module decorator","webpack://telegram-t/webpack/runtime/publicPath","webpack://telegram-t/webpack/runtime/importScripts chunk loading","webpack://telegram-t/webpack/startup"],"sourcesContent":["var deferred = [];\n__webpack_require__.O = (result, chunkIds, fn, priority) => {\n\tif(chunkIds) {\n\t\tpriority = priority || 0;\n\t\tfor(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1];\n\t\tdeferred[i] = [chunkIds, fn, priority];\n\t\treturn;\n\t}\n\tvar notFulfilled = Infinity;\n\tfor (var i = 0; i < deferred.length; i++) {\n\t\tvar [chunkIds, fn, priority] = deferred[i];\n\t\tvar fulfilled = true;\n\t\tfor (var j = 0; j < chunkIds.length; j++) {\n\t\t\tif ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(__webpack_require__.O).every((key) => (__webpack_require__.O[key](chunkIds[j])))) {\n\t\t\t\tchunkIds.splice(j--, 1);\n\t\t\t} else {\n\t\t\t\tfulfilled = false;\n\t\t\t\tif(priority < notFulfilled) notFulfilled = priority;\n\t\t\t}\n\t\t}\n\t\tif(fulfilled) {\n\t\t\tdeferred.splice(i--, 1)\n\t\t\tvar r = fn();\n\t\t\tif (r !== undefined) result = r;\n\t\t}\n\t}\n\treturn result;\n};","var next = __webpack_require__.x;\n__webpack_require__.x = () => {\n\treturn __webpack_require__.e(592).then(next);\n};","export const PAGE_TITLE = 'Telegram';\nexport const INACTIVE_MARKER = ' [Inactive]';\n\nexport const APP_NAME = process.env.APP_NAME || 'Telegram WebZ';\nexport const APP_VERSION = process.env.APP_VERSION || 'dev';\n\nexport const DEBUG = (\n process.env.APP_ENV !== 'production' && process.env.APP_ENV !== 'perf' && process.env.APP_ENV !== 'test'\n);\nexport const DEBUG_MORE = false;\n\nexport const IS_TEST = process.env.APP_ENV === 'test';\nexport const IS_PERF = process.env.APP_ENV === 'perf';\n\nexport const DEBUG_ALERT_MSG = 'Shoot!\\nSomething went wrong, please see the error details in Dev Tools Console.';\nexport const DEBUG_GRAMJS = false;\n\nexport const SESSION_USER_KEY = 'user_auth';\nexport const LEGACY_SESSION_KEY = 'GramJs:sessionId';\n\nexport const GLOBAL_STATE_CACHE_DISABLED = false;\nexport const GLOBAL_STATE_CACHE_KEY = 'tt-global-state';\nexport const GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT = 30;\nexport const GLOBAL_STATE_CACHE_USER_LIST_LIMIT = 5000;\n\nexport const MEDIA_CACHE_DISABLED = false;\nexport const MEDIA_CACHE_NAME = 'tt-media';\nexport const MEDIA_CACHE_NAME_AVATARS = 'tt-media-avatars';\nexport const MEDIA_PROGRESSIVE_CACHE_DISABLED = false;\nexport const MEDIA_PROGRESSIVE_CACHE_NAME = 'tt-media-progressive';\nexport const MEDIA_CACHE_MAX_BYTES = 512 * 1024; // 512 KB\nexport const CUSTOM_BG_CACHE_NAME = 'tt-custom-bg';\nexport const LANG_CACHE_NAME = 'tt-lang-packs-v7';\nexport const ASSET_CACHE_NAME = 'tt-assets';\nexport const AUTODOWNLOAD_FILESIZE_MB_LIMITS = [1, 5, 10, 50, 100, 500];\n\nexport const DOWNLOAD_WORKERS = 16;\nexport const UPLOAD_WORKERS = 16;\n\nconst isBigScreen = typeof window !== 'undefined' && window.innerHeight >= 900;\n\nexport const MIN_PASSWORD_LENGTH = 1;\n\nexport const MESSAGE_LIST_SLICE = isBigScreen ? 60 : 40;\nexport const MESSAGE_LIST_VIEWPORT_LIMIT = MESSAGE_LIST_SLICE * 2;\n\nexport const CHAT_HEIGHT_PX = 72;\nexport const CHAT_LIST_SLICE = isBigScreen ? 30 : 25;\nexport const CHAT_LIST_LOAD_SLICE = 100;\nexport const SHARED_MEDIA_SLICE = 42;\nexport const MESSAGE_SEARCH_SLICE = 42;\nexport const GLOBAL_SEARCH_SLICE = 20;\nexport const MEMBERS_SLICE = 30;\nexport const MEMBERS_LOAD_SLICE = 200;\nexport const PINNED_MESSAGES_LIMIT = 50;\nexport const BLOCKED_LIST_LIMIT = 100;\nexport const PROFILE_PHOTOS_LIMIT = 40;\nexport const PROFILE_SENSITIVE_AREA = 500;\nexport const COMMON_CHATS_LIMIT = 100;\nexport const GROUP_CALL_PARTICIPANTS_LIMIT = 100;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 20;\nexport const ALL_CHATS_PRELOAD_DISABLED = false;\n\nexport const SPONSORED_MESSAGE_CACHE_MS = 300000; // 5 min\n\nexport const DEFAULT_VOLUME = 1;\nexport const DEFAULT_PLAYBACK_RATE = 1;\n\nexport const ANIMATION_LEVEL_MIN = 0;\nexport const ANIMATION_LEVEL_MED = 1;\nexport const ANIMATION_LEVEL_MAX = 2;\nexport const ANIMATION_LEVEL_DEFAULT = ANIMATION_LEVEL_MAX;\n\nexport const DEFAULT_MESSAGE_TEXT_SIZE_PX = 16;\nexport const IOS_DEFAULT_MESSAGE_TEXT_SIZE_PX = 17;\nexport const MACOS_DEFAULT_MESSAGE_TEXT_SIZE_PX = 15;\n\nexport const DRAFT_DEBOUNCE = 10000; // 10s\nexport const SEND_MESSAGE_ACTION_INTERVAL = 3000; // 3s\n\nexport const EDITABLE_INPUT_ID = 'editable-message-text';\nexport const EDITABLE_INPUT_MODAL_ID = 'editable-message-text-modal';\n\n// Screen width where Pinned Message / Audio Player in the Middle Header can be safely displayed\nexport const SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1440; // px\n// Screen width where Pinned Message / Audio Player in the Middle Header shouldn't collapse with ChatInfo\nexport const SAFE_SCREEN_WIDTH_FOR_CHAT_INFO = 1150; // px\n\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1275; // px\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN = 925; // px\nexport const MOBILE_SCREEN_MAX_WIDTH = 600; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH = 950; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT = 450; // px\n\nexport const LOCAL_MESSAGE_ID_BASE = 1e9;\nexport const TMP_CHAT_ID = '0';\n\nexport const ANIMATION_END_DELAY = 100;\n\nexport const FAST_SMOOTH_MAX_DISTANCE = 1500;\nexport const FAST_SMOOTH_MIN_DURATION = 250;\nexport const FAST_SMOOTH_MAX_DURATION = 600;\nexport const FAST_SMOOTH_SHORT_TRANSITION_MAX_DISTANCE = 500; // px\n\n// Average duration of message sending animation\nexport const API_UPDATE_THROTTLE = Math.round((FAST_SMOOTH_MIN_DURATION + FAST_SMOOTH_MAX_DURATION) / 2);\nexport const API_THROTTLE_RESET_UPDATES = new Set([\n 'newMessage', 'newScheduledMessage', 'deleteMessages', 'deleteScheduledMessages', 'deleteHistory',\n]);\n\nexport const STICKER_SIZE_INLINE_DESKTOP_FACTOR = 13;\nexport const STICKER_SIZE_INLINE_MOBILE_FACTOR = 11;\nexport const STICKER_SIZE_AUTH = 160;\nexport const STICKER_SIZE_AUTH_MOBILE = 120;\nexport const STICKER_SIZE_PICKER = 64;\nexport const STICKER_SIZE_GENERAL_SETTINGS = 48;\nexport const STICKER_SIZE_PICKER_HEADER = 32;\nexport const STICKER_SIZE_SEARCH = 64;\nexport const STICKER_SIZE_MODAL = 64;\nexport const STICKER_SIZE_TWO_FA = 160;\nexport const STICKER_SIZE_DISCUSSION_GROUPS = 140;\nexport const STICKER_SIZE_FOLDER_SETTINGS = 80;\nexport const STICKER_SIZE_INLINE_BOT_RESULT = 100;\nexport const RECENT_STICKERS_LIMIT = 20;\nexport const MEMOJI_STICKER_ID = 'MEMOJI_STICKER';\n\nexport const BASE_EMOJI_KEYWORD_LANG = 'en';\n\nexport const MENU_TRANSITION_DURATION = 200;\nexport const SLIDE_TRANSITION_DURATION = 450;\n\nexport const VIDEO_MOV_TYPE = 'video/quicktime';\n\nexport const SUPPORTED_IMAGE_CONTENT_TYPES = new Set([\n 'image/png', 'image/gif', 'image/jpeg',\n]);\n\nexport const SUPPORTED_VIDEO_CONTENT_TYPES = new Set([\n 'video/mp4', // video/quicktime added dynamically in environment.ts\n]);\n\nexport const CONTENT_TYPES_WITH_PREVIEW = new Set([\n ...SUPPORTED_IMAGE_CONTENT_TYPES,\n ...SUPPORTED_VIDEO_CONTENT_TYPES,\n]);\n\nexport const CONTENT_NOT_SUPPORTED = 'The message is not supported on this version of Telegram.';\n\n// eslint-disable-next-line max-len\nexport const RE_LINK_TEMPLATE = '((ftp|https?):\\\\/\\\\/)?((www\\\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\\\.[a-zA-Z0-9()]{1,63})\\\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)';\nexport const RE_MENTION_TEMPLATE = '(@[\\\\w\\\\d_-]+)';\nexport const RE_TG_LINK = /^tg:(\\/\\/)?([?=&\\d\\w_-]+)?/gm;\nexport const RE_TME_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/)/gm;\n\n// eslint-disable-next-line max-len\nexport const COUNTRIES_WITH_12H_TIME_FORMAT = new Set(['AU', 'BD', 'CA', 'CO', 'EG', 'HN', 'IE', 'IN', 'JO', 'MX', 'MY', 'NI', 'NZ', 'PH', 'PK', 'SA', 'SV', 'US']);\n\n// MTProto constants\nexport const SERVICE_NOTIFICATIONS_USER_ID = '777000';\nexport const REPLIES_USER_ID = '1271266957'; // TODO For Test connection ID must be equal to 708513\nexport const ALL_FOLDER_ID = 0;\nexport const ARCHIVED_FOLDER_ID = 1;\nexport const DELETED_COMMENTS_CHANNEL_ID = '-777';\nexport const MAX_MEDIA_FILES_FOR_ALBUM = 10;\nexport const MAX_ACTIVE_PINNED_CHATS = 5;\nexport const SCHEDULED_WHEN_ONLINE = 0x7FFFFFFE;\nexport const DEFAULT_LANG_CODE = 'en';\nexport const DEFAULT_LANG_PACK = 'android';\nexport const LANG_PACKS = ['android', 'ios', 'tdesktop', 'macos'] as const;\nexport const TIPS_USERNAME = 'TelegramTips';\nexport const LOCALIZED_TIPS = ['ar', 'pt-br', 'id', 'it', 'ko', 'ms', 'pl', 'es', 'tr'];\nexport const FEEDBACK_URL = 'https://bugs.telegram.org/?tag_ids=41&sort=time';\nexport const LIGHT_THEME_BG_COLOR = '#A2AF8E';\nexport const DARK_THEME_BG_COLOR = '#0F0F0F';\nexport const DARK_THEME_PATTERN_COLOR = '#0a0a0a8c';\nexport const DEFAULT_PATTERN_COLOR = 'rgba(90, 110, 70, 0.6)';\n// TODO Get values from `getConfig` method once it's available\nexport const SEEN_BY_MEMBERS_CHAT_MAX = 50;\nexport const SEEN_BY_MEMBERS_EXPIRE = 604680; // One week - 2 min\n\n// Group calls\nexport const GROUP_CALL_VOLUME_MULTIPLIER = 100;\nexport const GROUP_CALL_DEFAULT_VOLUME = 100 * GROUP_CALL_VOLUME_MULTIPLIER;\nexport const ENABLE_THUMBNAIL_VIDEO = false;\n","type Scheduler =\n typeof requestAnimationFrame\n | typeof onTickEnd\n | typeof runNow;\n\nexport function debounce(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n shouldRunLast = true,\n) {\n let waitingTimeout: number | undefined;\n\n return (...args: Parameters) => {\n if (waitingTimeout) {\n clearTimeout(waitingTimeout);\n waitingTimeout = undefined;\n } else if (shouldRunFirst) {\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n waitingTimeout = self.setTimeout(() => {\n if (shouldRunLast) {\n fn(...args);\n }\n\n waitingTimeout = undefined;\n }, ms);\n };\n}\n\nexport function throttle(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n) {\n let interval: number | undefined;\n let isPending: boolean;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n isPending = true;\n args = _args;\n\n if (!interval) {\n if (shouldRunFirst) {\n isPending = false;\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n interval = self.setInterval(() => {\n if (!isPending) {\n // eslint-disable-next-line no-restricted-globals\n self.clearInterval(interval!);\n interval = undefined;\n return;\n }\n\n isPending = false;\n fn(...args);\n }, ms);\n }\n };\n}\n\nexport function throttleWithRaf(fn: F) {\n return throttleWith(fastRaf, fn);\n}\n\nexport function throttleWithPrimaryRaf(fn: F) {\n return throttleWith(fastRafPrimary, fn);\n}\n\nexport function throttleWithTickEnd(fn: F) {\n return throttleWith(onTickEnd, fn);\n}\n\nexport function throttleWithNow(fn: F) {\n return throttleWith(runNow, fn);\n}\n\nexport function throttleWith(schedulerFn: Scheduler, fn: F) {\n let waiting = false;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n args = _args;\n\n if (!waiting) {\n waiting = true;\n\n schedulerFn(() => {\n waiting = false;\n fn(...args);\n });\n }\n };\n}\n\nexport function onIdle(cb: NoneToVoidFunction, timeout?: number) {\n // eslint-disable-next-line no-restricted-globals\n if (self.requestIdleCallback) {\n // eslint-disable-next-line no-restricted-globals\n self.requestIdleCallback(cb, { timeout });\n } else {\n onTickEnd(cb);\n }\n}\n\nfunction runNow(fn: NoneToVoidFunction) {\n fn();\n}\n\nexport const pause = (ms: number) => new Promise((resolve) => {\n setTimeout(() => resolve(), ms);\n});\n\nexport function rafPromise() {\n return new Promise((resolve) => {\n fastRaf(resolve);\n });\n}\n\nlet fastRafCallbacks: NoneToVoidFunction[] | undefined;\nlet fastRafPrimaryCallbacks: NoneToVoidFunction[] | undefined;\n\n// May result in an immediate execution if called from another `requestAnimationFrame` callback\nexport function fastRaf(callback: NoneToVoidFunction, isPrimary = false) {\n if (!fastRafCallbacks) {\n fastRafCallbacks = isPrimary ? [] : [callback];\n fastRafPrimaryCallbacks = isPrimary ? [callback] : [];\n\n requestAnimationFrame(() => {\n const currentCallbacks = fastRafCallbacks!;\n const currentPrimaryCallbacks = fastRafPrimaryCallbacks!;\n fastRafCallbacks = undefined;\n fastRafPrimaryCallbacks = undefined;\n currentPrimaryCallbacks.forEach((cb) => cb());\n currentCallbacks.forEach((cb) => cb());\n });\n } else if (isPrimary) {\n fastRafPrimaryCallbacks!.push(callback);\n } else {\n fastRafCallbacks.push(callback);\n }\n}\n\nexport function fastRafPrimary(callback: NoneToVoidFunction) {\n fastRaf(callback, true);\n}\n\nlet onTickEndCallbacks: NoneToVoidFunction[] | undefined;\nlet onTickEndPrimaryCallbacks: NoneToVoidFunction[] | undefined;\n\nexport function onTickEnd(callback: NoneToVoidFunction, isPrimary = false) {\n if (!onTickEndCallbacks) {\n onTickEndCallbacks = isPrimary ? [] : [callback];\n onTickEndPrimaryCallbacks = isPrimary ? [callback] : [];\n\n Promise.resolve().then(() => {\n const currentCallbacks = onTickEndCallbacks!;\n const currentPrimaryCallbacks = onTickEndPrimaryCallbacks!;\n onTickEndCallbacks = undefined;\n onTickEndPrimaryCallbacks = undefined;\n currentPrimaryCallbacks.forEach((cb) => cb());\n currentCallbacks.forEach((cb) => cb());\n });\n } else if (isPrimary) {\n onTickEndPrimaryCallbacks!.push(callback);\n } else {\n onTickEndCallbacks.push(callback);\n }\n}\n\nexport function onTickEndPrimary(callback: NoneToVoidFunction) {\n onTickEnd(callback, true);\n}\n\nlet beforeUnloadCallbacks: NoneToVoidFunction[] | undefined;\n\nexport function onBeforeUnload(callback: NoneToVoidFunction, isLast = false) {\n if (!beforeUnloadCallbacks) {\n beforeUnloadCallbacks = [];\n // eslint-disable-next-line no-restricted-globals\n self.addEventListener('beforeunload', () => {\n beforeUnloadCallbacks!.forEach((cb) => cb());\n });\n }\n\n if (isLast) {\n beforeUnloadCallbacks.push(callback);\n } else {\n beforeUnloadCallbacks.unshift(callback);\n }\n\n return () => {\n beforeUnloadCallbacks = beforeUnloadCallbacks!.filter((cb) => cb !== callback);\n };\n}\n","type CollectionByKey = Record;\n\ntype OrderDirection =\n 'asc'\n | 'desc';\n\ninterface OrderCallback {\n (member: T): any;\n}\n\nexport function buildCollectionByKey(collection: T[], key: keyof T) {\n return collection.reduce((byKey: CollectionByKey, member: T) => {\n byKey[member[key]] = member;\n\n return byKey;\n }, {});\n}\n\nexport function mapValues(\n byKey: CollectionByKey,\n callback: (member: M, key: string, index: number, originalByKey: CollectionByKey) => R,\n): CollectionByKey {\n return Object.keys(byKey).reduce((newByKey: CollectionByKey, key, index) => {\n newByKey[key] = callback(byKey[key], key, index, byKey);\n return newByKey;\n }, {});\n}\n\nexport function pick(object: T, keys: K[]) {\n return keys.reduce((result, key) => {\n result[key] = object[key];\n return result;\n }, {} as Pick);\n}\n\nexport function pickTruthy(object: T, keys: K[]) {\n return keys.reduce((result, key) => {\n if (object[key]) {\n result[key] = object[key];\n }\n\n return result;\n }, {} as Pick);\n}\n\nexport function omit(object: T, keys: K[]) {\n const stringKeys = new Set(keys.map(String));\n const savedKeys = Object.keys(object)\n .filter((key) => !stringKeys.has(key)) as Array>;\n\n return pick(object, savedKeys);\n}\n\nexport function orderBy(\n collection: T[],\n orderRule: (keyof T) | OrderCallback | ((keyof T) | OrderCallback)[],\n mode: OrderDirection | [OrderDirection, OrderDirection] = 'asc',\n): T[] {\n function compareValues(a: T, b: T, currentOrderRule: (keyof T) | OrderCallback, isAsc: boolean) {\n const aValue = (typeof currentOrderRule === 'function' ? currentOrderRule(a) : a[currentOrderRule]) || 0;\n const bValue = (typeof currentOrderRule === 'function' ? currentOrderRule(b) : b[currentOrderRule]) || 0;\n\n return isAsc ? aValue - bValue : bValue - aValue;\n }\n\n if (Array.isArray(orderRule)) {\n const [mode1, mode2] = Array.isArray(mode) ? mode : [mode, mode];\n const [orderRule1, orderRule2] = orderRule;\n const isAsc1 = mode1 === 'asc';\n const isAsc2 = mode2 === 'asc';\n\n return collection.sort((a, b) => {\n return compareValues(a, b, orderRule1, isAsc1) || compareValues(a, b, orderRule2, isAsc2);\n });\n }\n\n const isAsc = mode === 'asc';\n return collection.sort((a, b) => {\n return compareValues(a, b, orderRule, isAsc);\n });\n}\n\nexport function flatten(array: any[]) {\n return array.reduce((result, member) => {\n if (Array.isArray(member)) {\n return result.concat(member);\n } else {\n result.push(member);\n return result;\n }\n }, []);\n}\n\nexport function unique(array: T[]): T[] {\n return Array.from(new Set(array));\n}\n\nexport function compact(array: any[]) {\n return array.filter(Boolean);\n}\n\nexport function areSortedArraysEqual(array1: any[], array2: any[]) {\n if (array1.length !== array2.length) {\n return false;\n }\n\n return array1.every((item, i) => item === array2[i]);\n}\n\nexport function areSortedArraysIntersecting(array1: any[], array2: any[]) {\n return array1[0] <= array2[array2.length - 1] && array1[array1.length - 1] >= array2[0];\n}\n\nexport function findIntersectionWithSet(array: T[], set: Set): T[] {\n return array.filter((a) => set.has(a));\n}\n\nexport function split(array: any[], chunkSize: number) {\n const result = [];\n for (let i = 0; i < array.length; i += chunkSize) {\n result.push(array.slice(i, i + chunkSize));\n }\n\n return result;\n}\n\nexport function cloneDeep(value: T): T {\n if (typeof value !== 'object') {\n return value;\n }\n\n if (Array.isArray(value)) {\n return value.map(cloneDeep) as typeof value;\n }\n\n return Object.keys(value).reduce((acc, key) => {\n acc[key as keyof T] = cloneDeep(value[key as keyof T]);\n return acc;\n }, {} as T);\n}\n\nexport function findLast(array: Array, predicate: (value: T, index: number, obj: T[]) => boolean): T | undefined {\n let cursor = array.length;\n\n while (cursor--) {\n if (predicate(array[cursor], cursor, array)) {\n return array[cursor];\n }\n }\n\n return undefined;\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\n\ntype VirtualFields =\n 'flags'\n | 'CONSTRUCTOR_ID'\n | 'SUBCLASS_OF_ID'\n | 'className'\n | 'classType'\n | 'getBytes';\n\nexport function bytesToDataUri(bytes: Buffer, shouldOmitPrefix = false, mimeType: string = 'image/jpeg') {\n const prefix = shouldOmitPrefix ? '' : `data:${mimeType};base64,`;\n\n return `${prefix}${btoa(String.fromCharCode(...bytes))}`;\n}\n\nexport function omitVirtualClassFields & { flags?: any }>(\n instance: T,\n): Omit {\n const {\n flags,\n CONSTRUCTOR_ID,\n SUBCLASS_OF_ID,\n className,\n classType,\n getBytes,\n ...rest\n } = instance;\n\n return rest;\n}\n","/* eslint-disable no-bitwise */\n\n// eslint-disable-next-line max-len\nconst TEMPLATE = '';\nconst LOOKUP = 'AACAAAAHAAALMAAAQASTAVAAAZaacaaaahaaalmaaaqastava.az0123456789-,';\n\nexport function pathBytesToSvg(bytes: Buffer, width: number, height: number) {\n return TEMPLATE\n .replace('{{path}}', buildPath(bytes))\n .replace('{{width}}', String(width))\n .replace('{{height}}', String(height));\n}\n\nfunction buildPath(bytes: Buffer) {\n let path = 'M';\n\n const len = bytes.length;\n for (let i = 0; i < len; i++) {\n const num = bytes[i];\n if (num >= 128 + 64) {\n path += LOOKUP[num - 128 - 64];\n } else {\n if (num >= 128) {\n path += ',';\n } else if (num >= 64) {\n path += '-';\n }\n path += String(num & 63);\n }\n }\n\n path += 'z';\n\n return path;\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport { strippedPhotoToJpg } from '../../../lib/gramjs/Utils';\n\nimport {\n ApiPhoto, ApiPhotoSize, ApiThumbnail,\n} from '../../types';\nimport { bytesToDataUri } from './helpers';\nimport { pathBytesToSvg } from './pathBytesToSvg';\n\nconst DEFAULT_THUMB_SIZE = { w: 100, h: 100 };\n\nexport function buildApiThumbnailFromStripped(\n sizes?: GramJs.TypePhotoSize[], mimeType?: string,\n): ApiThumbnail | undefined {\n if (!sizes || !sizes.length) {\n return undefined;\n }\n\n const thumb = sizes.find((s: any): s is GramJs.PhotoStrippedSize => s instanceof GramJs.PhotoStrippedSize);\n if (!thumb) {\n return undefined;\n }\n\n const realSizes = sizes.filter((s): s is GramJs.PhotoSize => s instanceof GramJs.PhotoSize);\n const { w, h } = realSizes.length ? realSizes[realSizes.length - 1] : DEFAULT_THUMB_SIZE;\n const { bytes } = thumb;\n const dataUri = bytesToDataUri(\n !mimeType || mimeType === 'image/jpeg' ? strippedPhotoToJpg(bytes) : bytes,\n undefined,\n mimeType,\n );\n\n return {\n dataUri,\n width: w,\n height: h,\n };\n}\n\nexport function buildApiThumbnailFromCached(photoSize: GramJs.PhotoCachedSize): ApiThumbnail | undefined {\n const { w, h, bytes } = photoSize;\n const dataUri = bytesToDataUri(bytes, undefined, 'image/webp');\n\n return {\n dataUri,\n width: w,\n height: h,\n };\n}\n\nexport function buildApiThumbnailFromPath(\n photoSize: GramJs.PhotoPathSize,\n sizeAttribute: GramJs.DocumentAttributeImageSize,\n): ApiThumbnail | undefined {\n const { w, h } = sizeAttribute;\n const dataUri = `data:image/svg+xml;utf8,${pathBytesToSvg(photoSize.bytes, w, h)}`;\n\n return {\n dataUri,\n width: w,\n height: h,\n };\n}\n\nexport function buildApiPhoto(photo: GramJs.Photo): ApiPhoto {\n const sizes = photo.sizes\n .filter((s: any): s is GramJs.PhotoSize => {\n return s instanceof GramJs.PhotoSize || s instanceof GramJs.PhotoSizeProgressive;\n })\n .map(buildApiPhotoSize);\n\n return {\n id: String(photo.id),\n thumbnail: buildApiThumbnailFromStripped(photo.sizes),\n sizes,\n };\n}\n\nexport function buildApiPhotoSize(photoSize: GramJs.PhotoSize): ApiPhotoSize {\n const { w, h, type } = photoSize;\n\n return {\n width: w,\n height: h,\n type: type as ('m' | 'x' | 'y'),\n };\n}\n","import { Api as GramJs } from '../../lib/gramjs';\nimport { ApiMessage } from '../types';\n\ninterface LocalDb {\n localMessages: Record;\n // Used for loading avatars and media through in-memory Gram JS instances.\n chats: Record;\n users: Record;\n messages: Record;\n documents: Record;\n stickerSets: Record;\n photos: Record;\n webDocuments: Record;\n}\n\nexport default {\n localMessages: {},\n chats: {},\n users: {},\n messages: {},\n documents: {},\n stickerSets: {},\n photos: {},\n webDocuments: {},\n} as LocalDb;\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport { ApiSticker, ApiStickerSet } from '../../types';\nimport { MEMOJI_STICKER_ID } from '../../../config';\n\nimport { buildApiThumbnailFromCached, buildApiThumbnailFromPath } from './common';\nimport localDb from '../localDb';\n\nconst ANIMATED_STICKER_MIME_TYPE = 'application/x-tgsticker';\n\nexport function buildStickerFromDocument(document: GramJs.TypeDocument): ApiSticker | undefined {\n if (document instanceof GramJs.DocumentEmpty) {\n return undefined;\n }\n\n const stickerAttribute = document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeSticker => (\n attr instanceof GramJs.DocumentAttributeSticker\n ));\n\n const fileAttribute = document.mimeType === ANIMATED_STICKER_MIME_TYPE && document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeFilename => (\n attr instanceof GramJs.DocumentAttributeFilename\n ));\n\n if (!stickerAttribute && !fileAttribute) {\n return undefined;\n }\n\n const sizeAttribute = document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeImageSize => (\n attr instanceof GramJs.DocumentAttributeImageSize\n ));\n\n const stickerSetInfo = stickerAttribute && stickerAttribute.stickerset instanceof GramJs.InputStickerSetID\n ? stickerAttribute.stickerset\n : undefined;\n const emoji = stickerAttribute?.alt;\n const isAnimated = document.mimeType === ANIMATED_STICKER_MIME_TYPE;\n const cachedThumb = document.thumbs && document.thumbs.find(\n (s): s is GramJs.PhotoCachedSize => s instanceof GramJs.PhotoCachedSize,\n );\n const pathThumb = document.thumbs && document.thumbs.find(\n (s): s is GramJs.PhotoPathSize => s instanceof GramJs.PhotoPathSize,\n );\n const thumbnail = cachedThumb ? (\n buildApiThumbnailFromCached(cachedThumb)\n ) : pathThumb && sizeAttribute ? (\n buildApiThumbnailFromPath(pathThumb, sizeAttribute)\n ) : undefined;\n\n const { w: width, h: height } = cachedThumb as GramJs.PhotoCachedSize || sizeAttribute || {};\n\n return {\n id: String(document.id),\n stickerSetId: stickerSetInfo ? String(stickerSetInfo.id) : MEMOJI_STICKER_ID,\n stickerSetAccessHash: stickerSetInfo && String(stickerSetInfo.accessHash),\n emoji,\n isAnimated,\n width,\n height,\n thumbnail,\n };\n}\n\nexport function buildStickerSet(set: GramJs.StickerSet): ApiStickerSet {\n const {\n archived,\n animated,\n installedDate,\n id,\n accessHash,\n title,\n thumbs,\n count,\n shortName,\n } = set;\n\n return {\n archived,\n isAnimated: animated,\n installedDate,\n id: String(id),\n accessHash: String(accessHash),\n title,\n hasThumbnail: Boolean(thumbs?.length),\n count,\n shortName,\n };\n}\n\nexport function buildStickerSetCovered(coveredStickerSet: GramJs.TypeStickerSetCovered): ApiStickerSet {\n const stickerSet = buildStickerSet(coveredStickerSet.set);\n\n const stickerSetCovers = (coveredStickerSet instanceof GramJs.StickerSetMultiCovered)\n ? coveredStickerSet.covers\n : [coveredStickerSet.cover];\n\n stickerSet.covers = [];\n stickerSetCovers.forEach((cover) => {\n if (cover instanceof GramJs.Document) {\n const coverSticker = buildStickerFromDocument(cover);\n if (coverSticker) {\n stickerSet.covers!.push(coverSticker);\n localDb.documents[String(cover.id)] = cover;\n }\n }\n });\n\n return stickerSet;\n}\n","/* eslint-disable no-bitwise */\n\n// eslint-disable-next-line max-len\n// Ref: https://github.com/telegramdesktop/tdesktop/blob/0743e71ab6b928d2ee5bae1aed991849b1e2b291/Telegram/SourceFiles/data/data_document.cpp#L1018\nexport function decodeWaveform(encoded5bit: Uint8Array) {\n const bitsCount = encoded5bit.length * 8;\n const valuesCount = Math.floor(bitsCount / 5);\n if (!valuesCount) {\n return [];\n }\n\n // Read each 5 bit of encoded5bit as 0-31 unsigned char.\n // We count the index of the byte in which the desired 5-bit sequence starts.\n // And then we read a uint16 starting from that byte to guarantee to get all of those 5 bits.\n //\n // BUT! if it is the last byte we have, we're not allowed to read a uint16 starting with it.\n // Because it will be an overflow (we'll access one byte after the available memory).\n // We see, that only the last 5 bits could start in the last available byte and be problematic.\n // So we read in a general way all the entries in a general way except the last one.\n const result = Array(valuesCount);\n const bitsData = encoded5bit;\n for (let i = 0, l = valuesCount - 1; i !== l; ++i) {\n const byteIndex = Math.floor((i * 5) / 8);\n const bitShift = Math.floor((i * 5) % 8);\n const value = bitsData[byteIndex] + (bitsData[byteIndex + 1] << 8);\n result[i] = ((value >> bitShift) & 0x1F);\n }\n const lastByteIndex = Math.floor(((valuesCount - 1) * 5) / 8);\n const lastBitShift = Math.floor(((valuesCount - 1) * 5) % 8);\n const lastValue = bitsData[lastByteIndex] + (bitsData[lastByteIndex + 1] << 8);\n result[valuesCount - 1] = (lastValue >> lastBitShift) & 0x1F;\n\n return result;\n}\n\nexport function interpolateArray(data: number[], fitCount: number) {\n let peak = 0;\n const newData = new Array(fitCount);\n const springFactor = data.length / fitCount;\n const leftFiller = data[0];\n const rightFiller = data[data.length - 1];\n for (let i = 0; i < fitCount; i++) {\n const idx = Math.floor(i * springFactor);\n const val = ((data[idx - 1] ?? leftFiller) + (data[idx] ?? leftFiller) + (data[idx + 1] ?? rightFiller)) / 3;\n newData[i] = val;\n if (peak < val) {\n peak = val;\n }\n }\n return { data: newData, peak };\n}\n","import { ApiGroupCall } from './calls';\n\nexport interface ApiDimensions {\n width: number;\n height: number;\n}\n\nexport interface ApiPhotoSize extends ApiDimensions {\n type: 's' | 'm' | 'x' | 'y' | 'z';\n}\n\nexport interface ApiThumbnail extends ApiDimensions {\n dataUri: string;\n}\n\nexport interface ApiPhoto {\n id: string;\n thumbnail?: ApiThumbnail;\n sizes: ApiPhotoSize[];\n blobUrl?: string;\n}\n\nexport interface ApiSticker {\n id: string;\n stickerSetId: string;\n stickerSetAccessHash?: string;\n emoji?: string;\n isAnimated: boolean;\n width?: number;\n height?: number;\n thumbnail?: ApiThumbnail;\n isPreloadedGlobally?: boolean;\n}\n\nexport interface ApiStickerSet {\n archived?: true;\n isAnimated?: true;\n installedDate?: number;\n id: string;\n accessHash: string;\n title: string;\n hasThumbnail?: boolean;\n count: number;\n stickers?: ApiSticker[];\n packs?: Record;\n covers?: ApiSticker[];\n shortName: string;\n}\n\nexport interface ApiVideo {\n id: string;\n mimeType: string;\n duration: number;\n fileName: string;\n width?: number;\n height?: number;\n supportsStreaming?: boolean;\n isRound?: boolean;\n isGif?: boolean;\n thumbnail?: ApiThumbnail;\n blobUrl?: string;\n size: number;\n}\n\nexport interface ApiAudio {\n id: string;\n size: number;\n mimeType: string;\n fileName: string;\n duration: number;\n performer?: string;\n title?: string;\n thumbnailSizes?: ApiPhotoSize[];\n}\n\nexport interface ApiVoice {\n id: string;\n duration: number;\n waveform?: number[];\n}\n\nexport interface ApiDocument {\n id?: string;\n fileName: string;\n size: number;\n timestamp?: number;\n mimeType: string;\n thumbnail?: ApiThumbnail;\n previewBlobUrl?: string;\n mediaType?: 'photo' | 'video';\n mediaSize?: ApiDimensions;\n}\n\nexport interface ApiContact {\n firstName: string;\n lastName: string;\n phoneNumber: string;\n userId: string;\n}\n\nexport interface ApiPollAnswer {\n text: string;\n option: string;\n}\n\nexport interface ApiPollResult {\n isChosen?: true;\n isCorrect?: true;\n option: string;\n votersCount: number;\n}\n\nexport interface ApiPoll {\n id: string;\n summary: {\n closed?: true;\n isPublic?: true;\n multipleChoice?: true;\n quiz?: true;\n question: string;\n answers: ApiPollAnswer[];\n closePeriod?: number;\n closeDate?: number;\n };\n results: {\n results?: ApiPollResult[];\n totalVoters?: number;\n recentVoterIds?: string[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n}\n\nexport interface ApiInvoice {\n text: string;\n title: string;\n photoUrl?: string;\n amount: number;\n currency: string;\n receiptMsgId?: number;\n isTest?: boolean;\n}\n\nexport type ApiNewPoll = {\n summary: ApiPoll['summary'];\n quiz?: {\n correctAnswers: string[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n};\n\nexport interface ApiAction {\n text: string;\n targetUserIds?: string[];\n targetChatId?: string;\n type: 'historyClear' | 'contactSignUp' | 'chatCreate' | 'other';\n photo?: ApiPhoto;\n amount?: number;\n currency?: string;\n translationValues: string[];\n call?: Partial;\n}\n\nexport interface ApiWebPage {\n id: number;\n url: string;\n displayUrl: string;\n type?: string;\n siteName?: string;\n title?: string;\n description?: string;\n photo?: ApiPhoto;\n duration?: number;\n document?: ApiDocument;\n video?: ApiVideo;\n}\n\nexport interface ApiMessageForwardInfo {\n date: number;\n isChannelPost: boolean;\n channelPostId?: number;\n isLinkedChannelPost?: boolean;\n fromChatId?: string;\n senderUserId?: string;\n fromMessageId?: number;\n hiddenUserName?: string;\n adminTitle?: string;\n}\n\nexport interface ApiMessageEntity {\n type: string;\n offset: number;\n length: number;\n userId?: string;\n url?: string;\n}\n\nexport enum ApiMessageEntityTypes {\n Bold = 'MessageEntityBold',\n Blockquote = 'MessageEntityBlockquote',\n BotCommand = 'MessageEntityBotCommand',\n Cashtag = 'MessageEntityCashtag',\n Code = 'MessageEntityCode',\n Email = 'MessageEntityEmail',\n Hashtag = 'MessageEntityHashtag',\n Italic = 'MessageEntityItalic',\n MentionName = 'MessageEntityMentionName',\n Mention = 'MessageEntityMention',\n Phone = 'MessageEntityPhone',\n Pre = 'MessageEntityPre',\n Strike = 'MessageEntityStrike',\n TextUrl = 'MessageEntityTextUrl',\n Url = 'MessageEntityUrl',\n Underline = 'MessageEntityUnderline',\n Unknown = 'MessageEntityUnknown',\n}\n\nexport interface ApiFormattedText {\n text: string;\n entities?: ApiMessageEntity[];\n}\n\nexport interface ApiMessage {\n id: number;\n chatId: string;\n content: {\n text?: ApiFormattedText;\n photo?: ApiPhoto;\n video?: ApiVideo;\n document?: ApiDocument;\n sticker?: ApiSticker;\n contact?: ApiContact;\n poll?: ApiPoll;\n action?: ApiAction;\n webPage?: ApiWebPage;\n audio?: ApiAudio;\n voice?: ApiVoice;\n invoice?: ApiInvoice;\n };\n date: number;\n isOutgoing: boolean;\n senderId?: string;\n replyToChatId?: string;\n replyToMessageId?: number;\n replyToTopMessageId?: number;\n sendingState?: 'messageSendingStatePending' | 'messageSendingStateFailed';\n forwardInfo?: ApiMessageForwardInfo;\n isDeleting?: boolean;\n previousLocalId?: number;\n views?: number;\n isEdited?: boolean;\n editDate?: number;\n isMentioned?: boolean;\n isMediaUnread?: boolean;\n groupedId?: string;\n isInAlbum?: boolean;\n hasUnreadMention?: boolean;\n inlineButtons?: ApiKeyboardButtons;\n keyboardButtons?: ApiKeyboardButtons;\n keyboardPlaceholder?: string;\n isKeyboardSingleUse?: boolean;\n viaBotId?: string;\n threadInfo?: ApiThreadInfo;\n adminTitle?: string;\n isScheduled?: boolean;\n shouldHideKeyboardButtons?: boolean;\n isFromScheduled?: boolean;\n seenByUserIds?: string[];\n isProtected?: boolean;\n}\n\nexport interface ApiThreadInfo {\n threadId: number;\n chatId: string;\n topMessageId?: number;\n originChannelId?: string;\n messagesCount: number;\n lastMessageId?: number;\n lastReadInboxMessageId?: number;\n recentReplierIds?: string[];\n}\n\nexport type ApiMessageOutgoingStatus = 'read' | 'succeeded' | 'pending' | 'failed';\n\nexport type ApiSponsoredMessage = {\n chatId?: string;\n randomId: string;\n isBot?: boolean;\n channelPostId?: number;\n startParam?: string;\n chatInviteHash?: string;\n chatInviteTitle?: string;\n text: ApiFormattedText;\n expiresAt: number;\n};\n\nexport interface ApiKeyboardButton {\n type: 'command' | 'url' | 'callback' | 'requestPoll' | 'requestSelfContact' | 'buy' | 'NOT_SUPPORTED';\n text: string;\n messageId: number;\n value?: string;\n}\n\nexport type ApiKeyboardButtons = ApiKeyboardButton[][];\nexport type ApiReplyKeyboard = {\n keyboardPlaceholder?: string;\n isKeyboardSingleUse?: boolean;\n} & {\n [K in 'inlineButtons' | 'keyboardButtons']?: ApiKeyboardButtons;\n};\n\nexport type ApiMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'voice' | 'profilePhoto';\nexport type ApiGlobalMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'voice';\n\nexport type ApiReportReason = 'spam' | 'violence' | 'pornography' | 'childAbuse'\n| 'copyright' | 'geoIrrelevant' | 'fake' | 'other';\n\nexport type ApiSendMessageAction = {\n type: 'cancel' | 'typing' | 'recordAudio' | 'chooseSticker';\n};\n\nexport const MAIN_THREAD_ID = -1;\n\n// `Symbol` can not be transferred from worker\nexport const MESSAGE_DELETED = 'MESSAGE_DELETED';\n","// We cache avatars as Data URI for faster initial load\n// and messages media as Blob for smaller size.\n\nexport enum ApiMediaFormat {\n BlobUrl,\n Lottie,\n Progressive,\n Stream,\n}\n\nexport type ApiParsedMedia = string | Blob | AnyLiteral | ArrayBuffer;\nexport type ApiPreparedMedia = string | AnyLiteral;\nexport type ApiMediaFormatToPrepared = T extends ApiMediaFormat.Lottie ? AnyLiteral : string;\n","import BigInt from 'big-integer';\n\nimport { Api as GramJs } from '../../../lib/gramjs';\n\nexport function isPeerUser(peer: GramJs.TypePeer | GramJs.TypeInputPeer): peer is GramJs.PeerUser {\n return peer.hasOwnProperty('userId');\n}\n\nexport function isPeerChat(peer: GramJs.TypePeer | GramJs.TypeInputPeer): peer is GramJs.PeerChat {\n return peer.hasOwnProperty('chatId');\n}\n\nexport function isPeerChannel(peer: GramJs.TypePeer | GramJs.TypeInputPeer): peer is GramJs.PeerChannel {\n return peer.hasOwnProperty('channelId');\n}\n\nexport function buildApiPeerId(id: BigInt.BigInteger, type: 'user' | 'chat' | 'channel') {\n return type === 'user' ? String(id) : `-${id}`;\n}\n\nexport function getApiChatIdFromMtpPeer(peer: GramJs.TypePeer | GramJs.TypeInputPeer) {\n if (isPeerUser(peer)) {\n return buildApiPeerId(peer.userId, 'user');\n } else if (isPeerChat(peer)) {\n return buildApiPeerId(peer.chatId, 'chat');\n } else {\n return buildApiPeerId((peer as GramJs.InputPeerChannel).channelId, 'channel');\n }\n}\n","import { Api as GramJs } from '../../lib/gramjs';\nimport localDb from './localDb';\nimport { buildApiPeerId, getApiChatIdFromMtpPeer } from './apiBuilders/peers';\n\nexport function resolveMessageApiChatId(mtpMessage: GramJs.TypeMessage) {\n if (!(mtpMessage instanceof GramJs.Message || mtpMessage instanceof GramJs.MessageService)) {\n return undefined;\n }\n\n return getApiChatIdFromMtpPeer(mtpMessage.peerId);\n}\n\nexport function addMessageToLocalDb(message: GramJs.Message | GramJs.MessageService) {\n const messageFullId = `${resolveMessageApiChatId(message)}-${message.id}`;\n localDb.messages[messageFullId] = message;\n\n if (\n message instanceof GramJs.Message\n && message.media instanceof GramJs.MessageMediaDocument\n && message.media.document instanceof GramJs.Document\n ) {\n localDb.documents[String(message.media.document.id)] = message.media.document;\n }\n\n if (\n message instanceof GramJs.Message\n && message.media instanceof GramJs.MessageMediaWebPage\n && message.media.webpage instanceof GramJs.WebPage\n && message.media.webpage.document instanceof GramJs.Document\n ) {\n localDb.documents[String(message.media.webpage.document.id)] = message.media.webpage.document;\n }\n\n if (message instanceof GramJs.MessageService && 'photo' in message.action) {\n addPhotoToLocalDb(message.action.photo);\n }\n}\n\nexport function addPhotoToLocalDb(photo: GramJs.TypePhoto) {\n if (photo instanceof GramJs.Photo) {\n localDb.photos[String(photo.id)] = photo;\n }\n}\n\nfunction addChatToLocalDb(chat: GramJs.Chat | GramJs.Channel, noOverwrite = false) {\n const id = buildApiPeerId(chat.id, chat instanceof GramJs.Chat ? 'chat' : 'channel');\n if (!noOverwrite || !localDb.chats[id]) {\n localDb.chats[id] = chat;\n }\n}\n\nexport function addUserToLocalDb(user: GramJs.User, shouldOverwrite = false) {\n const id = buildApiPeerId(user.id, 'user');\n if (shouldOverwrite || !localDb.users[id]) {\n localDb.users[id] = user;\n }\n}\n\nexport function addEntitiesWithPhotosToLocalDb(entities: (GramJs.TypeUser | GramJs.TypeChat)[]) {\n entities.forEach((entity) => {\n if (entity instanceof GramJs.User && entity.photo) {\n addUserToLocalDb(entity);\n } else if ((entity instanceof GramJs.Chat || entity instanceof GramJs.Channel) && entity.photo) {\n addChatToLocalDb(entity);\n }\n });\n}\n\nexport function serializeBytes(value: Buffer) {\n return String.fromCharCode(...value);\n}\n\nexport function deserializeBytes(value: string) {\n return Buffer.from(value, 'binary');\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\n\nimport { ApiPrivacyKey } from '../../../types';\n\nimport { generateRandomBytes, readBigIntFromBuffer } from '../../../lib/gramjs/Helpers';\nimport {\n ApiChatAdminRights,\n ApiChatBannedRights,\n ApiChatFolder,\n ApiGroupCall,\n ApiMessageEntity,\n ApiMessageEntityTypes,\n ApiNewPoll,\n ApiReportReason,\n ApiSendMessageAction,\n ApiSticker,\n ApiVideo,\n} from '../../types';\nimport localDb from '../localDb';\nimport { pick } from '../../../util/iteratees';\nimport { deserializeBytes } from '../helpers';\n\nconst CHANNEL_ID_MIN_LENGTH = 11; // Example: -1000000000\n\nexport function getEntityTypeById(chatOrUserId: string) {\n if (typeof chatOrUserId === 'number') {\n return getEntityTypeByDeprecatedId(chatOrUserId);\n }\n\n if (!chatOrUserId.startsWith('-')) {\n return 'user';\n } else if (chatOrUserId.length >= CHANNEL_ID_MIN_LENGTH) {\n return 'channel';\n } else {\n return 'chat';\n }\n}\n\n// Workaround for old-fashioned IDs stored locally\nexport function getEntityTypeByDeprecatedId(chatOrUserId: number) {\n if (chatOrUserId > 0) {\n return 'user';\n } else if (chatOrUserId <= -1000000000) {\n return 'channel';\n } else {\n return 'chat';\n }\n}\n\nexport function buildPeer(chatOrUserId: string): GramJs.TypePeer {\n const type = getEntityTypeById(chatOrUserId);\n\n if (type === 'user') {\n return new GramJs.PeerUser({\n userId: buildMtpPeerId(chatOrUserId, 'user'),\n });\n } else if (type === 'channel') {\n return new GramJs.PeerChannel({\n channelId: buildMtpPeerId(chatOrUserId, 'channel'),\n });\n } else {\n return new GramJs.PeerChat({\n chatId: buildMtpPeerId(chatOrUserId, 'chat'),\n });\n }\n}\n\nexport function buildInputPeer(chatOrUserId: string, accessHash?: string): GramJs.TypeInputPeer {\n const type = getEntityTypeById(chatOrUserId);\n\n if (type === 'user') {\n return new GramJs.InputPeerUser({\n userId: buildMtpPeerId(chatOrUserId, 'user'),\n accessHash: BigInt(accessHash!),\n });\n } else if (type === 'channel') {\n return new GramJs.InputPeerChannel({\n channelId: buildMtpPeerId(chatOrUserId, 'channel'),\n accessHash: BigInt(accessHash!),\n });\n } else {\n return new GramJs.InputPeerChat({\n chatId: buildMtpPeerId(chatOrUserId, 'chat'),\n });\n }\n}\n\nexport function buildInputPeerFromLocalDb(chatOrUserId: string): GramJs.TypeInputPeer | undefined {\n const type = getEntityTypeById(chatOrUserId);\n let accessHash: BigInt.BigInteger | undefined;\n\n if (type === 'user') {\n accessHash = localDb.users[chatOrUserId]?.accessHash;\n if (!accessHash) {\n return undefined;\n }\n } else if (type === 'channel') {\n accessHash = (localDb.chats[chatOrUserId] as GramJs.Channel)?.accessHash;\n if (!accessHash) {\n return undefined;\n }\n }\n\n return buildInputPeer(chatOrUserId, String(accessHash));\n}\n\nexport function buildInputEntity(chatOrUserId: string, accessHash?: string) {\n const type = getEntityTypeById(chatOrUserId);\n\n if (type === 'user') {\n return new GramJs.InputUser({\n userId: buildMtpPeerId(chatOrUserId, 'user'),\n accessHash: BigInt(accessHash!),\n });\n } else if (type === 'channel') {\n return new GramJs.InputChannel({\n channelId: buildMtpPeerId(chatOrUserId, 'channel'),\n accessHash: BigInt(accessHash!),\n });\n } else {\n return buildMtpPeerId(chatOrUserId, 'chat');\n }\n}\n\nexport function buildInputStickerSet(id: string, accessHash: string) {\n return new GramJs.InputStickerSetID({\n id: BigInt(id),\n accessHash: BigInt(accessHash),\n });\n}\n\nexport function buildInputStickerSetShortName(shortName: string) {\n return new GramJs.InputStickerSetShortName({\n shortName,\n });\n}\n\nexport function buildInputDocument(media: ApiSticker | ApiVideo) {\n const document = localDb.documents[media.id];\n\n if (!document) {\n return undefined;\n }\n\n return new GramJs.InputDocument(pick(document, [\n 'id',\n 'accessHash',\n 'fileReference',\n ]));\n}\n\nexport function buildInputMediaDocument(media: ApiSticker | ApiVideo) {\n const inputDocument = buildInputDocument(media);\n\n if (!inputDocument) {\n return undefined;\n }\n\n return new GramJs.InputMediaDocument({ id: inputDocument });\n}\n\nexport function buildInputPoll(pollParams: ApiNewPoll, randomId: BigInt.BigInteger) {\n const { summary, quiz } = pollParams;\n\n const poll = new GramJs.Poll({\n id: randomId,\n publicVoters: summary.isPublic,\n question: summary.question,\n answers: summary.answers.map(({ text, option }) => {\n return new GramJs.PollAnswer({ text, option: deserializeBytes(option) });\n }),\n quiz: summary.quiz,\n multipleChoice: summary.multipleChoice,\n });\n\n if (!quiz) {\n return new GramJs.InputMediaPoll({ poll });\n }\n\n const correctAnswers = quiz.correctAnswers.map(deserializeBytes);\n const { solution } = quiz;\n const solutionEntities = quiz.solutionEntities ? quiz.solutionEntities.map(buildMtpMessageEntity) : [];\n\n return new GramJs.InputMediaPoll({\n poll,\n correctAnswers,\n ...(solution && {\n solution,\n solutionEntities,\n }),\n });\n}\n\nexport function buildFilterFromApiFolder(folder: ApiChatFolder): GramJs.DialogFilter {\n const {\n emoticon,\n contacts,\n nonContacts,\n groups,\n channels,\n bots,\n excludeArchived,\n excludeMuted,\n excludeRead,\n pinnedChatIds,\n includedChatIds,\n excludedChatIds,\n } = folder;\n\n const pinnedPeers = pinnedChatIds\n ? pinnedChatIds.map(buildInputPeerFromLocalDb).filter(Boolean as any)\n : [];\n\n const includePeers = includedChatIds\n ? includedChatIds.map(buildInputPeerFromLocalDb).filter(Boolean as any)\n : [];\n\n const excludePeers = excludedChatIds\n ? excludedChatIds.map(buildInputPeerFromLocalDb).filter(Boolean as any)\n : [];\n\n return new GramJs.DialogFilter({\n id: folder.id,\n title: folder.title,\n emoticon: emoticon || undefined,\n contacts: contacts || undefined,\n nonContacts: nonContacts || undefined,\n groups: groups || undefined,\n bots: bots || undefined,\n excludeArchived: excludeArchived || undefined,\n excludeMuted: excludeMuted || undefined,\n excludeRead: excludeRead || undefined,\n broadcasts: channels || undefined,\n pinnedPeers,\n includePeers,\n excludePeers,\n });\n}\n\nexport function generateRandomBigInt() {\n return readBigIntFromBuffer(generateRandomBytes(8), true, true);\n}\n\nexport function generateRandomInt() {\n return readBigIntFromBuffer(generateRandomBytes(4), true, true).toJSNumber();\n}\n\nexport function buildMessageFromUpdate(\n id: number,\n chatId: string,\n update: GramJs.UpdateShortSentMessage | GramJs.UpdateServiceNotification,\n) {\n // This is not a proper message, but we only need these fields for downloading media through `localDb`.\n return new GramJs.Message({\n id,\n peerId: buildPeer(chatId),\n fromId: buildPeer(chatId),\n media: update.media,\n } as GramJs.Message);\n}\n\nexport function buildMtpMessageEntity(entity: ApiMessageEntity): GramJs.TypeMessageEntity {\n const {\n type, offset, length, url, userId,\n } = entity;\n\n const user = userId ? localDb.users[userId] : undefined;\n\n switch (type) {\n case ApiMessageEntityTypes.Bold:\n return new GramJs.MessageEntityBold({ offset, length });\n case ApiMessageEntityTypes.Italic:\n return new GramJs.MessageEntityItalic({ offset, length });\n case ApiMessageEntityTypes.Underline:\n return new GramJs.MessageEntityUnderline({ offset, length });\n case ApiMessageEntityTypes.Strike:\n return new GramJs.MessageEntityStrike({ offset, length });\n case ApiMessageEntityTypes.Code:\n return new GramJs.MessageEntityCode({ offset, length });\n case ApiMessageEntityTypes.Pre:\n return new GramJs.MessageEntityPre({ offset, length, language: '' });\n case ApiMessageEntityTypes.Blockquote:\n return new GramJs.MessageEntityBlockquote({ offset, length });\n case ApiMessageEntityTypes.TextUrl:\n return new GramJs.MessageEntityTextUrl({ offset, length, url: url! });\n case ApiMessageEntityTypes.Url:\n return new GramJs.MessageEntityUrl({ offset, length });\n case ApiMessageEntityTypes.Hashtag:\n return new GramJs.MessageEntityHashtag({ offset, length });\n case ApiMessageEntityTypes.MentionName:\n return new GramJs.InputMessageEntityMentionName({\n offset,\n length,\n userId: new GramJs.InputUser({ userId: BigInt(userId!), accessHash: user!.accessHash! }),\n });\n default:\n return new GramJs.MessageEntityUnknown({ offset, length });\n }\n}\n\nexport function isMessageWithMedia(message: GramJs.Message | GramJs.UpdateServiceNotification) {\n const { media } = message;\n if (!media) {\n return false;\n }\n\n return (\n media instanceof GramJs.MessageMediaPhoto\n || media instanceof GramJs.MessageMediaDocument\n || (\n media instanceof GramJs.MessageMediaWebPage\n && media.webpage instanceof GramJs.WebPage\n && (\n media.webpage.photo instanceof GramJs.Photo || (\n media.webpage.document instanceof GramJs.Document\n && media.webpage.document.mimeType.startsWith('video')\n )\n )\n )\n );\n}\n\nexport function isServiceMessageWithMedia(message: GramJs.MessageService) {\n return 'photo' in message.action && message.action.photo instanceof GramJs.Photo;\n}\n\nexport function buildChatPhotoForLocalDb(photo: GramJs.TypePhoto) {\n if (photo instanceof GramJs.PhotoEmpty) {\n return new GramJs.ChatPhotoEmpty();\n }\n\n const { dcId, id: photoId } = photo;\n\n return new GramJs.ChatPhoto({\n dcId,\n photoId,\n });\n}\n\nexport function buildInputContact({\n phone,\n firstName,\n lastName,\n}: {\n phone: string;\n firstName: string;\n lastName: string;\n}) {\n return new GramJs.InputPhoneContact({\n clientId: BigInt(1),\n phone,\n firstName,\n lastName,\n });\n}\n\nexport function buildChatBannedRights(\n bannedRights: ApiChatBannedRights,\n untilDate = 0,\n) {\n return new GramJs.ChatBannedRights({\n ...bannedRights,\n untilDate,\n });\n}\n\nexport function buildChatAdminRights(\n adminRights: ApiChatAdminRights,\n) {\n return new GramJs.ChatAdminRights(adminRights);\n}\n\nexport function buildShippingInfo(info: GramJs.PaymentRequestedInfo) {\n const { shippingAddress } = info;\n return new GramJs.PaymentRequestedInfo({\n ...info,\n shippingAddress: shippingAddress\n ? new GramJs.PostAddress(shippingAddress)\n : undefined,\n });\n}\n\nexport function buildInputPrivacyKey(privacyKey: ApiPrivacyKey) {\n switch (privacyKey) {\n case 'phoneNumber':\n return new GramJs.InputPrivacyKeyPhoneNumber();\n\n case 'lastSeen':\n return new GramJs.InputPrivacyKeyStatusTimestamp();\n\n case 'profilePhoto':\n return new GramJs.InputPrivacyKeyProfilePhoto();\n\n case 'forwards':\n return new GramJs.InputPrivacyKeyForwards();\n\n case 'chatInvite':\n return new GramJs.InputPrivacyKeyChatInvite();\n }\n\n return undefined;\n}\n\nexport function buildInputReportReason(reason: ApiReportReason) {\n switch (reason) {\n case 'spam':\n return new GramJs.InputReportReasonSpam();\n case 'violence':\n return new GramJs.InputReportReasonViolence();\n case 'childAbuse':\n return new GramJs.InputReportReasonChildAbuse();\n case 'pornography':\n return new GramJs.InputReportReasonPornography();\n case 'copyright':\n return new GramJs.InputReportReasonCopyright();\n case 'fake':\n return new GramJs.InputReportReasonFake();\n case 'geoIrrelevant':\n return new GramJs.InputReportReasonGeoIrrelevant();\n case 'other':\n return new GramJs.InputReportReasonOther();\n }\n\n return undefined;\n}\n\nexport function buildSendMessageAction(action: ApiSendMessageAction) {\n switch (action.type) {\n case 'cancel':\n return new GramJs.SendMessageCancelAction();\n case 'typing':\n return new GramJs.SendMessageTypingAction();\n case 'recordAudio':\n return new GramJs.SendMessageRecordAudioAction();\n case 'chooseSticker':\n return new GramJs.SendMessageChooseStickerAction();\n }\n return undefined;\n}\n\nexport function buildMtpPeerId(id: string, type: 'user' | 'chat' | 'channel') {\n // Workaround for old-fashioned IDs stored locally\n if (typeof id === 'number') {\n return BigInt(Math.abs(id));\n }\n\n return type === 'user' ? BigInt(id) : BigInt(id.slice(1));\n}\n\nexport function buildInputGroupCall(groupCall: Partial) {\n return new GramJs.InputGroupCall({\n id: BigInt(groupCall.id!),\n accessHash: BigInt(groupCall.accessHash!),\n });\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n ApiMessage,\n ApiMessageForwardInfo,\n ApiPhoto,\n ApiSticker,\n ApiVideo,\n ApiVoice,\n ApiAudio,\n ApiDocument,\n ApiAction,\n ApiContact,\n ApiAttachment,\n ApiPoll,\n ApiNewPoll,\n ApiWebPage,\n ApiMessageEntity,\n ApiFormattedText,\n ApiReplyKeyboard,\n ApiKeyboardButton,\n ApiChat,\n ApiThreadInfo,\n ApiInvoice,\n ApiGroupCall,\n ApiUser,\n ApiSponsoredMessage,\n} from '../../types';\n\nimport {\n CONTENT_NOT_SUPPORTED,\n DELETED_COMMENTS_CHANNEL_ID,\n LOCAL_MESSAGE_ID_BASE,\n SERVICE_NOTIFICATIONS_USER_ID,\n SPONSORED_MESSAGE_CACHE_MS,\n SUPPORTED_IMAGE_CONTENT_TYPES,\n SUPPORTED_VIDEO_CONTENT_TYPES,\n VIDEO_MOV_TYPE,\n} from '../../../config';\nimport { pick } from '../../../util/iteratees';\nimport { buildStickerFromDocument } from './symbols';\nimport { buildApiPhoto, buildApiPhotoSize, buildApiThumbnailFromStripped } from './common';\nimport { interpolateArray } from '../../../util/waveform';\nimport { buildPeer } from '../gramjsBuilders';\nimport { addPhotoToLocalDb, resolveMessageApiChatId, serializeBytes } from '../helpers';\nimport { buildApiPeerId, getApiChatIdFromMtpPeer, isPeerUser } from './peers';\n\nconst LOCAL_MEDIA_UPLOADING_TEMP_ID = 'temp';\nconst INPUT_WAVEFORM_LENGTH = 63;\n\nlet localMessageCounter = LOCAL_MESSAGE_ID_BASE;\nlet currentUserId!: string;\n\nexport function setMessageBuilderCurrentUserId(_currentUserId: string) {\n currentUserId = _currentUserId;\n}\n\nexport function buildApiSponsoredMessage(mtpMessage: GramJs.SponsoredMessage): ApiSponsoredMessage | undefined {\n const {\n fromId, message, entities, startParam, channelPost, chatInvite, chatInviteHash, randomId,\n } = mtpMessage;\n const chatId = fromId ? getApiChatIdFromMtpPeer(fromId) : undefined;\n const chatInviteTitle = chatInvite\n ? (chatInvite instanceof GramJs.ChatInvite\n ? chatInvite.title\n : !(chatInvite.chat instanceof GramJs.ChatEmpty) ? chatInvite.chat.title : undefined)\n : undefined;\n\n return {\n randomId: serializeBytes(randomId),\n isBot: fromId ? isPeerUser(fromId) : false,\n text: buildMessageTextContent(message, entities),\n expiresAt: Math.round(Date.now() / 1000) + SPONSORED_MESSAGE_CACHE_MS,\n ...(chatId && { chatId }),\n ...(chatInviteHash && { chatInviteHash }),\n ...(chatInvite && { chatInviteTitle }),\n ...(startParam && { startParam }),\n ...(channelPost && { channelPostId: channelPost }),\n };\n}\n\nexport function buildApiMessage(mtpMessage: GramJs.TypeMessage): ApiMessage | undefined {\n const chatId = resolveMessageApiChatId(mtpMessage);\n if (\n !chatId\n || !(mtpMessage instanceof GramJs.Message || mtpMessage instanceof GramJs.MessageService)) {\n return undefined;\n }\n\n return buildApiMessageWithChatId(chatId, mtpMessage);\n}\n\nexport function buildApiMessageFromShort(mtpMessage: GramJs.UpdateShortMessage): ApiMessage {\n const chatId = buildApiPeerId(mtpMessage.userId, 'user');\n\n return buildApiMessageWithChatId(chatId, {\n ...mtpMessage,\n fromId: buildPeer(mtpMessage.out ? currentUserId : buildApiPeerId(mtpMessage.userId, 'user')),\n });\n}\n\nexport function buildApiMessageFromShortChat(mtpMessage: GramJs.UpdateShortChatMessage): ApiMessage {\n const chatId = buildApiPeerId(mtpMessage.chatId, 'chat');\n\n return buildApiMessageWithChatId(chatId, {\n ...mtpMessage,\n fromId: buildPeer(buildApiPeerId(mtpMessage.fromId, 'user')),\n });\n}\n\nexport function buildApiMessageFromNotification(\n notification: GramJs.UpdateServiceNotification,\n currentDate: number,\n): ApiMessage {\n const localId = localMessageCounter++;\n let content: ApiMessage['content'] = {};\n\n if (notification.media) {\n content = {\n ...buildMessageMediaContent(notification.media),\n };\n }\n\n if (notification.message && !content.sticker && !content.poll && !content.contact) {\n content = {\n ...content,\n text: buildMessageTextContent(notification.message, notification.entities),\n };\n }\n\n return {\n id: localId,\n chatId: SERVICE_NOTIFICATIONS_USER_ID,\n date: notification.inboxDate || currentDate,\n content,\n isOutgoing: false,\n };\n}\n\ntype UniversalMessage = (\n Pick\n & Pick, (\n 'out' | 'message' | 'entities' | 'fromId' | 'peerId' | 'fwdFrom' | 'replyTo' | 'replyMarkup' | 'post' |\n 'media' | 'action' | 'views' | 'editDate' | 'editHide' | 'mediaUnread' | 'groupedId' | 'mentioned' | 'viaBotId' |\n 'replies' | 'fromScheduled' | 'postAuthor' | 'noforwards'\n )>\n);\n\nexport function buildApiMessageWithChatId(chatId: string, mtpMessage: UniversalMessage): ApiMessage {\n const fromId = mtpMessage.fromId ? getApiChatIdFromMtpPeer(mtpMessage.fromId) : undefined;\n const peerId = mtpMessage.peerId ? getApiChatIdFromMtpPeer(mtpMessage.peerId) : undefined;\n const isChatWithSelf = !fromId && chatId === currentUserId;\n const isOutgoing = (mtpMessage.out && !mtpMessage.post) || (isChatWithSelf && !mtpMessage.fwdFrom);\n\n let content: ApiMessage['content'] = {};\n\n if (mtpMessage.media) {\n content = {\n ...buildMessageMediaContent(mtpMessage.media),\n };\n }\n\n if (mtpMessage.message && !content.sticker && !content.poll && !content.contact) {\n content = {\n ...content,\n text: buildMessageTextContent(mtpMessage.message, mtpMessage.entities),\n };\n }\n\n const action = mtpMessage.action\n && buildAction(mtpMessage.action, fromId, peerId, Boolean(mtpMessage.post), isOutgoing);\n if (action) {\n content.action = action;\n }\n\n const { replyToMsgId, replyToTopId, replyToPeerId } = mtpMessage.replyTo || {};\n const isEdited = mtpMessage.editDate && !mtpMessage.editHide;\n const {\n inlineButtons, keyboardButtons, keyboardPlaceholder, isKeyboardSingleUse,\n } = buildReplyButtons(mtpMessage) || {};\n const forwardInfo = mtpMessage.fwdFrom && buildApiMessageForwardInfo(mtpMessage.fwdFrom, isChatWithSelf);\n const { replies, mediaUnread: isMediaUnread, postAuthor } = mtpMessage;\n const groupedId = mtpMessage.groupedId && String(mtpMessage.groupedId);\n const isInAlbum = Boolean(groupedId) && !(content.document || content.audio);\n const shouldHideKeyboardButtons = mtpMessage.replyMarkup instanceof GramJs.ReplyKeyboardHide;\n\n return {\n id: mtpMessage.id,\n chatId,\n isOutgoing,\n content,\n date: mtpMessage.date,\n senderId: fromId || (mtpMessage.out && mtpMessage.post && currentUserId) || chatId,\n views: mtpMessage.views,\n isFromScheduled: mtpMessage.fromScheduled,\n ...(replyToMsgId && { replyToMessageId: replyToMsgId }),\n ...(replyToPeerId && { replyToChatId: getApiChatIdFromMtpPeer(replyToPeerId) }),\n ...(replyToTopId && { replyToTopMessageId: replyToTopId }),\n ...(forwardInfo && { forwardInfo }),\n ...(isEdited && { isEdited, editDate: mtpMessage.editDate }),\n ...(isMediaUnread && { isMediaUnread }),\n ...(mtpMessage.mentioned && isMediaUnread && { hasUnreadMention: true }),\n ...(mtpMessage.mentioned && { isMentioned: true }),\n ...(groupedId && {\n groupedId,\n isInAlbum,\n }),\n inlineButtons,\n ...(keyboardButtons && { keyboardButtons, keyboardPlaceholder, isKeyboardSingleUse }),\n ...(shouldHideKeyboardButtons && { shouldHideKeyboardButtons }),\n ...(mtpMessage.viaBotId && { viaBotId: buildApiPeerId(mtpMessage.viaBotId, 'user') }),\n ...(replies?.comments && { threadInfo: buildThreadInfo(replies, mtpMessage.id, chatId) }),\n ...(postAuthor && { adminTitle: postAuthor }),\n ...(mtpMessage.noforwards && { isProtected: true }),\n };\n}\n\nexport function buildMessageTextContent(\n message: string,\n entities?: GramJs.TypeMessageEntity[],\n): ApiFormattedText {\n if (entities?.some((e) => e instanceof GramJs.MessageEntitySpoiler)) {\n return {\n text: CONTENT_NOT_SUPPORTED,\n };\n }\n\n return {\n text: message,\n ...(entities && { entities: entities.map(buildApiMessageEntity) }),\n };\n}\n\nexport function buildMessageDraft(draft: GramJs.TypeDraftMessage) {\n if (draft instanceof GramJs.DraftMessageEmpty) {\n return undefined;\n }\n\n const {\n message, entities, replyToMsgId, date,\n } = draft;\n\n return {\n formattedText: message ? buildMessageTextContent(message, entities) : undefined,\n replyingToId: replyToMsgId,\n date,\n };\n}\n\nexport function buildMessageMediaContent(media: GramJs.TypeMessageMedia): ApiMessage['content'] | undefined {\n if ('ttlSeconds' in media && media.ttlSeconds) {\n return undefined;\n }\n\n const sticker = buildSticker(media);\n if (sticker) return { sticker };\n\n const photo = buildPhoto(media);\n if (photo) return { photo };\n\n const video = buildVideo(media);\n if (video) return { video };\n\n const audio = buildAudio(media);\n if (audio) return { audio };\n\n const voice = buildVoice(media);\n if (voice) return { voice };\n\n const document = buildDocumentFromMedia(media);\n if (document) return { document };\n\n const contact = buildContact(media);\n if (contact) return { contact };\n\n const poll = buildPollFromMedia(media);\n if (poll) return { poll };\n\n const webPage = buildWebPage(media);\n if (webPage) return { webPage };\n\n const invoice = buildInvoiceFromMedia(media);\n if (invoice) return { invoice };\n\n return undefined;\n}\n\nfunction buildApiMessageForwardInfo(fwdFrom: GramJs.MessageFwdHeader, isChatWithSelf = false): ApiMessageForwardInfo {\n const savedFromPeerId = fwdFrom.savedFromPeer && getApiChatIdFromMtpPeer(fwdFrom.savedFromPeer);\n const fromId = fwdFrom.fromId && getApiChatIdFromMtpPeer(fwdFrom.fromId);\n\n return {\n date: fwdFrom.date,\n isChannelPost: Boolean(fwdFrom.channelPost),\n channelPostId: fwdFrom.channelPost,\n isLinkedChannelPost: Boolean(fwdFrom.channelPost && savedFromPeerId && !isChatWithSelf),\n fromChatId: savedFromPeerId || fromId,\n fromMessageId: fwdFrom.channelPost || fwdFrom.savedFromMsgId,\n senderUserId: fromId,\n hiddenUserName: fwdFrom.fromName,\n adminTitle: fwdFrom.postAuthor,\n };\n}\n\nfunction buildSticker(media: GramJs.TypeMessageMedia): ApiSticker | undefined {\n if (\n !(media instanceof GramJs.MessageMediaDocument)\n || !media.document\n || !(media.document instanceof GramJs.Document)\n ) {\n return undefined;\n }\n\n return buildStickerFromDocument(media.document);\n}\n\nfunction buildPhoto(media: GramJs.TypeMessageMedia): ApiPhoto | undefined {\n if (!(media instanceof GramJs.MessageMediaPhoto) || !media.photo || !(media.photo instanceof GramJs.Photo)) {\n return undefined;\n }\n\n return buildApiPhoto(media.photo);\n}\n\nexport function buildVideoFromDocument(document: GramJs.Document): ApiVideo | undefined {\n if (document instanceof GramJs.DocumentEmpty) {\n return undefined;\n }\n\n const {\n id, mimeType, thumbs, size, attributes,\n } = document;\n\n // eslint-disable-next-line no-restricted-globals\n if (mimeType === VIDEO_MOV_TYPE && !(self as any).isMovSupported) {\n return undefined;\n }\n\n const videoAttr = attributes\n .find((a: any): a is GramJs.DocumentAttributeVideo => a instanceof GramJs.DocumentAttributeVideo);\n\n if (!videoAttr) {\n return undefined;\n }\n\n const gifAttr = attributes\n .find((a: any): a is GramJs.DocumentAttributeAnimated => a instanceof GramJs.DocumentAttributeAnimated);\n\n const {\n duration,\n w: width,\n h: height,\n supportsStreaming = false,\n roundMessage: isRound = false,\n } = videoAttr;\n\n return {\n id: String(id),\n mimeType,\n duration,\n fileName: getFilenameFromDocument(document, 'video'),\n width,\n height,\n supportsStreaming,\n isRound,\n isGif: Boolean(gifAttr),\n thumbnail: buildApiThumbnailFromStripped(thumbs),\n size,\n };\n}\n\nfunction buildVideo(media: GramJs.TypeMessageMedia): ApiVideo | undefined {\n if (\n !(media instanceof GramJs.MessageMediaDocument)\n || !(media.document instanceof GramJs.Document)\n || !media.document.mimeType.startsWith('video')\n ) {\n return undefined;\n }\n\n return buildVideoFromDocument(media.document);\n}\n\nfunction buildAudio(media: GramJs.TypeMessageMedia): ApiAudio | undefined {\n if (\n !(media instanceof GramJs.MessageMediaDocument)\n || !media.document\n || !(media.document instanceof GramJs.Document)\n ) {\n return undefined;\n }\n\n const audioAttribute = media.document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeAudio => (\n attr instanceof GramJs.DocumentAttributeAudio\n ));\n\n if (!audioAttribute || audioAttribute.voice) {\n return undefined;\n }\n\n const thumbnailSizes = media.document.thumbs && media.document.thumbs\n .filter((thumb): thumb is GramJs.PhotoSize => thumb instanceof GramJs.PhotoSize)\n .map((thumb) => buildApiPhotoSize(thumb));\n\n return {\n id: String(media.document.id),\n fileName: getFilenameFromDocument(media.document, 'audio'),\n thumbnailSizes,\n ...pick(media.document, ['size', 'mimeType']),\n ...pick(audioAttribute, ['duration', 'performer', 'title']),\n };\n}\n\nfunction buildVoice(media: GramJs.TypeMessageMedia): ApiVoice | undefined {\n if (\n !(media instanceof GramJs.MessageMediaDocument)\n || !media.document\n || !(media.document instanceof GramJs.Document)\n ) {\n return undefined;\n }\n\n const audioAttribute = media.document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeAudio => (\n attr instanceof GramJs.DocumentAttributeAudio\n ));\n\n if (!audioAttribute || !audioAttribute.voice) {\n return undefined;\n }\n\n const { duration, waveform } = audioAttribute;\n\n return {\n id: String(media.document.id),\n duration,\n waveform: waveform ? Array.from(waveform) : undefined,\n };\n}\n\nfunction buildDocumentFromMedia(media: GramJs.TypeMessageMedia) {\n if (!(media instanceof GramJs.MessageMediaDocument) || !media.document) {\n return undefined;\n }\n\n return buildApiDocument(media.document);\n}\n\nexport function buildApiDocument(document: GramJs.TypeDocument): ApiDocument | undefined {\n if (!(document instanceof GramJs.Document)) {\n return undefined;\n }\n\n const {\n id, size, mimeType, date, thumbs, attributes,\n } = document;\n\n const thumbnail = thumbs && buildApiThumbnailFromStripped(thumbs);\n\n let mediaType: ApiDocument['mediaType'] | undefined;\n let mediaSize: ApiDocument['mediaSize'] | undefined;\n const photoSize = thumbs && thumbs.find((s: any): s is GramJs.PhotoSize => s instanceof GramJs.PhotoSize);\n if (photoSize) {\n mediaSize = {\n width: photoSize.w,\n height: photoSize.h,\n };\n\n if (SUPPORTED_IMAGE_CONTENT_TYPES.has(mimeType)) {\n mediaType = 'photo';\n\n const imageAttribute = attributes\n .find((a: any): a is GramJs.DocumentAttributeImageSize => a instanceof GramJs.DocumentAttributeImageSize);\n\n if (imageAttribute) {\n const { w: width, h: height } = imageAttribute;\n mediaSize = {\n width,\n height,\n };\n }\n } else if (SUPPORTED_VIDEO_CONTENT_TYPES.has(mimeType)) {\n mediaType = 'video';\n }\n }\n\n return {\n id: String(id),\n size,\n mimeType,\n timestamp: date,\n fileName: getFilenameFromDocument(document),\n thumbnail,\n mediaType,\n mediaSize,\n };\n}\n\nfunction buildContact(media: GramJs.TypeMessageMedia): ApiContact | undefined {\n if (!(media instanceof GramJs.MessageMediaContact)) {\n return undefined;\n }\n\n const {\n firstName, lastName, phoneNumber, userId,\n } = media;\n\n return {\n firstName, lastName, phoneNumber, userId: buildApiPeerId(userId, 'user'),\n };\n}\n\nfunction buildPollFromMedia(media: GramJs.TypeMessageMedia): ApiPoll | undefined {\n if (!(media instanceof GramJs.MessageMediaPoll)) {\n return undefined;\n }\n\n return buildPoll(media.poll, media.results);\n}\n\nfunction buildInvoiceFromMedia(media: GramJs.TypeMessageMedia): ApiInvoice | undefined {\n if (!(media instanceof GramJs.MessageMediaInvoice)) {\n return undefined;\n }\n\n return buildInvoice(media);\n}\n\nexport function buildPoll(poll: GramJs.Poll, pollResults: GramJs.PollResults): ApiPoll {\n const { id, answers: rawAnswers } = poll;\n const answers = rawAnswers.map((answer) => ({\n text: answer.text,\n option: serializeBytes(answer.option),\n }));\n\n return {\n id: String(id),\n summary: {\n isPublic: poll.publicVoters,\n ...pick(poll, [\n 'closed',\n 'multipleChoice',\n 'quiz',\n 'question',\n 'closePeriod',\n 'closeDate',\n ]),\n answers,\n },\n results: buildPollResults(pollResults),\n };\n}\n\nexport function buildInvoice(media: GramJs.MessageMediaInvoice): ApiInvoice {\n const {\n description: text, title, photo, test, totalAmount, currency, receiptMsgId,\n } = media;\n\n return {\n text,\n title,\n photoUrl: photo?.url,\n receiptMsgId,\n amount: Number(totalAmount),\n currency,\n isTest: test,\n };\n}\n\nexport function buildPollResults(pollResults: GramJs.PollResults): ApiPoll['results'] {\n const {\n results: rawResults, totalVoters, recentVoters, solution, solutionEntities: entities,\n } = pollResults;\n const results = rawResults && rawResults.map(({\n option, chosen, correct, voters,\n }) => ({\n isChosen: chosen,\n isCorrect: correct,\n option: serializeBytes(option),\n votersCount: voters,\n }));\n\n return {\n totalVoters,\n recentVoterIds: recentVoters?.map((id) => buildApiPeerId(id, 'user')),\n results,\n solution,\n ...(entities && { solutionEntities: entities.map(buildApiMessageEntity) }),\n };\n}\n\nexport function buildWebPage(media: GramJs.TypeMessageMedia): ApiWebPage | undefined {\n if (\n !(media instanceof GramJs.MessageMediaWebPage)\n || !(media.webpage instanceof GramJs.WebPage)\n ) {\n return undefined;\n }\n\n const { id, photo, document } = media.webpage;\n\n let video;\n if (document instanceof GramJs.Document && document.mimeType.startsWith('video/')) {\n video = buildVideoFromDocument(document);\n }\n\n return {\n id: Number(id),\n ...pick(media.webpage, [\n 'url',\n 'displayUrl',\n 'type',\n 'siteName',\n 'title',\n 'description',\n 'duration',\n ]),\n photo: photo instanceof GramJs.Photo ? buildApiPhoto(photo) : undefined,\n document: !video && document ? buildApiDocument(document) : undefined,\n video,\n };\n}\n\nfunction buildAction(\n action: GramJs.TypeMessageAction,\n senderId: string | undefined,\n targetPeerId: string | undefined,\n isChannelPost: boolean,\n isOutgoing: boolean,\n): ApiAction | undefined {\n if (action instanceof GramJs.MessageActionEmpty) {\n return undefined;\n }\n\n let call: Partial | undefined;\n let amount: number | undefined;\n let currency: string | undefined;\n let text: string;\n const translationValues = [];\n let type: ApiAction['type'] = 'other';\n let photo: ApiPhoto | undefined;\n\n const targetUserIds = 'users' in action\n ? action.users && action.users.map((id) => buildApiPeerId(id, 'user'))\n : ('userId' in action && [buildApiPeerId(action.userId, 'user')]) || [];\n let targetChatId: string | undefined;\n\n if (action instanceof GramJs.MessageActionChatCreate) {\n text = 'Notification.CreatedChatWithTitle';\n translationValues.push('%action_origin%', action.title);\n type = 'chatCreate';\n } else if (action instanceof GramJs.MessageActionChatEditTitle) {\n if (isChannelPost) {\n text = 'Channel.MessageTitleUpdated';\n translationValues.push(action.title);\n } else {\n text = 'Notification.ChangedGroupName';\n translationValues.push('%action_origin%', action.title);\n }\n } else if (action instanceof GramJs.MessageActionChatEditPhoto) {\n if (isChannelPost) {\n text = 'Channel.MessagePhotoUpdated';\n } else {\n text = 'Notification.ChangedGroupPhoto';\n translationValues.push('%action_origin%');\n }\n } else if (action instanceof GramJs.MessageActionChatDeletePhoto) {\n if (isChannelPost) {\n text = 'Channel.MessagePhotoRemoved';\n } else {\n text = 'Group.MessagePhotoRemoved';\n }\n } else if (action instanceof GramJs.MessageActionChatAddUser) {\n if (!senderId || targetUserIds.includes(senderId)) {\n text = 'Notification.JoinedChat';\n translationValues.push('%target_user%');\n } else {\n text = 'Notification.Invited';\n translationValues.push('%action_origin%', '%target_user%');\n }\n } else if (action instanceof GramJs.MessageActionChatDeleteUser) {\n if (!senderId || targetUserIds.includes(senderId)) {\n text = 'Notification.LeftChat';\n translationValues.push('%target_user%');\n } else {\n text = 'Notification.Kicked';\n translationValues.push('%action_origin%', '%target_user%');\n }\n } else if (action instanceof GramJs.MessageActionChatJoinedByLink) {\n text = 'Notification.JoinedGroupByLink';\n translationValues.push('%action_origin%');\n } else if (action instanceof GramJs.MessageActionChannelCreate) {\n text = 'Notification.CreatedChannel';\n } else if (action instanceof GramJs.MessageActionChatMigrateTo) {\n targetChatId = getApiChatIdFromMtpPeer(action);\n text = 'Migrated to %target_chat%';\n translationValues.push('%target_chat%');\n } else if (action instanceof GramJs.MessageActionChannelMigrateFrom) {\n targetChatId = getApiChatIdFromMtpPeer(action);\n text = 'Migrated from %target_chat%';\n translationValues.push('%target_chat%');\n } else if (action instanceof GramJs.MessageActionPinMessage) {\n text = 'Chat.Service.Group.UpdatedPinnedMessage1';\n translationValues.push('%action_origin%', '%message%');\n } else if (action instanceof GramJs.MessageActionHistoryClear) {\n text = 'HistoryCleared';\n type = 'historyClear';\n } else if (action instanceof GramJs.MessageActionPhoneCall) {\n const withDuration = Boolean(action.duration);\n text = [\n withDuration ? 'ChatList.Service' : 'Chat',\n action.video ? 'VideoCall' : 'Call',\n isOutgoing ? (withDuration ? 'outgoing' : 'Outgoing') : (withDuration ? 'incoming' : 'Incoming'),\n ].join('.');\n\n if (withDuration) {\n const mins = Math.max(Math.round(action.duration! / 60), 1);\n translationValues.push(`${mins} min${mins > 1 ? 's' : ''}`);\n }\n } else if (action instanceof GramJs.MessageActionInviteToGroupCall) {\n text = 'Notification.VoiceChatInvitation';\n call = {\n id: action.call.id.toString(),\n accessHash: action.call.accessHash.toString(),\n };\n translationValues.push('%action_origin%', '%target_user%');\n } else if (action instanceof GramJs.MessageActionContactSignUp) {\n text = 'Notification.Joined';\n translationValues.push('%action_origin%');\n type = 'contactSignUp';\n } else if (action instanceof GramJs.MessageActionPaymentSent) {\n amount = Number(action.totalAmount);\n currency = action.currency;\n text = 'PaymentSuccessfullyPaid';\n if (targetPeerId) {\n targetUserIds.push(targetPeerId);\n }\n translationValues.push('%payment_amount%', '%target_user%', '%product%');\n } else if (action instanceof GramJs.MessageActionGroupCall) {\n if (action.duration) {\n const mins = Math.max(Math.round(action.duration / 60), 1);\n text = 'Notification.VoiceChatEnded';\n translationValues.push(`${mins} min${mins > 1 ? 's' : ''}`);\n } else {\n text = 'Notification.VoiceChatStartedChannel';\n call = {\n id: action.call.id.toString(),\n accessHash: action.call.accessHash.toString(),\n };\n }\n } else if (action instanceof GramJs.MessageActionBotAllowed) {\n text = 'Chat.Service.BotPermissionAllowed';\n translationValues.push(action.domain);\n } else if (action instanceof GramJs.MessageActionCustomAction) {\n text = action.message;\n } else if (action instanceof GramJs.MessageActionChatJoinedByRequest) {\n text = 'ChatService.UserJoinedGroupByRequest';\n translationValues.push('%action_origin%');\n } else {\n text = 'ChatList.UnsupportedMessage';\n }\n\n if ('photo' in action && action.photo instanceof GramJs.Photo) {\n addPhotoToLocalDb(action.photo);\n photo = buildApiPhoto(action.photo);\n }\n\n return {\n text,\n type,\n targetUserIds,\n targetChatId,\n photo, // TODO Only used internally now, will be used for the UI in future\n amount,\n currency,\n translationValues,\n call,\n };\n}\n\nfunction buildReplyButtons(message: UniversalMessage): ApiReplyKeyboard | undefined {\n const { id: messageId, replyMarkup, media } = message;\n\n if (!replyMarkup) {\n if (media instanceof GramJs.MessageMediaWebPage && media.webpage instanceof GramJs.WebPage) {\n if (media.webpage.type === 'telegram_message') {\n return {\n inlineButtons: [[{\n type: 'url' as const,\n text: 'Show Message',\n messageId,\n value: media.webpage.url,\n }]],\n };\n }\n }\n\n return undefined;\n }\n\n // TODO\n if (!(replyMarkup instanceof GramJs.ReplyKeyboardMarkup || replyMarkup instanceof GramJs.ReplyInlineMarkup)) {\n return undefined;\n }\n\n const markup = replyMarkup.rows.map(({ buttons }) => {\n return buttons.map((button) => {\n let { text } = button;\n\n let type;\n let value;\n if (button instanceof GramJs.KeyboardButton) {\n type = 'command';\n value = text;\n } else if (button instanceof GramJs.KeyboardButtonUrl) {\n type = 'url';\n value = button.url;\n } else if (button instanceof GramJs.KeyboardButtonCallback) {\n type = 'callback';\n value = serializeBytes(button.data);\n } else if (button instanceof GramJs.KeyboardButtonRequestPoll) {\n type = 'requestPoll';\n } else if (button instanceof GramJs.KeyboardButtonRequestPhone) {\n type = 'requestSelfContact';\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 contact?: ApiContact,\n groupedId?: string,\n scheduledAt?: number,\n sendAs?: ApiChat | ApiUser,\n serverTimeOffset = 0,\n): ApiMessage {\n const localId = localMessageCounter++;\n const media = attachment && buildUploadingMedia(attachment);\n const isChannel = chat.type === 'chatTypeChannel';\n\n return {\n id: localId,\n chatId: chat.id,\n content: {\n ...(text && {\n text: {\n text,\n entities,\n },\n }),\n ...media,\n ...(sticker && { sticker }),\n ...(gif && { video: gif }),\n ...(poll && buildNewPoll(poll, localId)),\n ...(contact && { contact }),\n },\n date: scheduledAt || Math.round(Date.now() / 1000) + serverTimeOffset,\n isOutgoing: !isChannel,\n senderId: sendAs?.id || currentUserId,\n ...(replyingTo && { replyToMessageId: replyingTo }),\n ...(groupedId && {\n groupedId,\n ...(media && (media.photo || media.video) && { isInAlbum: true }),\n }),\n ...(scheduledAt && { isScheduled: true }),\n };\n}\n\nexport function buildLocalForwardedMessage(\n toChat: ApiChat,\n message: ApiMessage,\n serverTimeOffset: number,\n scheduledAt?: number,\n): ApiMessage {\n const localId = localMessageCounter++;\n const {\n content,\n chatId: fromChatId,\n id: fromMessageId,\n senderId,\n groupedId,\n isInAlbum,\n } = message;\n\n const isAudio = content.audio;\n const asIncomingInChatWithSelf = (\n toChat.id === currentUserId && (fromChatId !== toChat.id || message.forwardInfo) && !isAudio\n );\n\n return {\n id: localId,\n chatId: toChat.id,\n content,\n date: scheduledAt || Math.round(Date.now() / 1000) + serverTimeOffset,\n isOutgoing: !asIncomingInChatWithSelf && toChat.type !== 'chatTypeChannel',\n senderId: currentUserId,\n sendingState: 'messageSendingStatePending',\n groupedId,\n isInAlbum,\n // Forward info doesn't get added when users forwards his own messages, also when forwarding audio\n ...(senderId !== currentUserId && !isAudio && {\n forwardInfo: {\n date: message.date,\n isChannelPost: false,\n fromChatId,\n fromMessageId,\n senderUserId: senderId,\n },\n }),\n ...(scheduledAt && { isScheduled: true }),\n };\n}\n\nfunction buildUploadingMedia(\n attachment: ApiAttachment,\n): ApiMessage['content'] {\n const {\n filename: fileName,\n blobUrl,\n previewBlobUrl,\n mimeType,\n size,\n } = attachment;\n\n if (attachment.quick) {\n const { width, height, duration } = attachment.quick;\n\n if (mimeType.startsWith('image/')) {\n return {\n photo: {\n id: LOCAL_MEDIA_UPLOADING_TEMP_ID,\n sizes: [],\n thumbnail: { width, height, dataUri: '' }, // Used only for dimensions\n blobUrl,\n },\n };\n } else {\n return {\n video: {\n id: LOCAL_MEDIA_UPLOADING_TEMP_ID,\n mimeType,\n duration: duration || 0,\n fileName,\n width,\n height,\n blobUrl,\n ...(previewBlobUrl && { thumbnail: { width, height, dataUri: previewBlobUrl } }),\n size,\n },\n };\n }\n } else if (attachment.voice) {\n const { duration, waveform } = attachment.voice;\n const { data: inputWaveform } = interpolateArray(waveform, INPUT_WAVEFORM_LENGTH);\n return {\n voice: {\n id: LOCAL_MEDIA_UPLOADING_TEMP_ID,\n duration,\n waveform: inputWaveform,\n },\n };\n } else if (mimeType.startsWith('audio/')) {\n return {\n audio: {\n id: LOCAL_MEDIA_UPLOADING_TEMP_ID,\n mimeType,\n fileName,\n size,\n duration: 200, // Arbitrary\n },\n };\n } else {\n return {\n document: {\n mimeType,\n fileName,\n size,\n ...(previewBlobUrl && { previewBlobUrl }),\n },\n };\n }\n}\n\nfunction buildNewPoll(poll: ApiNewPoll, localId: number) {\n return {\n poll: {\n id: String(localId),\n summary: pick(poll.summary, ['question', 'answers']),\n results: {},\n },\n };\n}\n\nfunction buildApiMessageEntity(entity: GramJs.TypeMessageEntity): ApiMessageEntity {\n const { className: type, offset, length } = entity;\n return {\n type,\n offset,\n length,\n ...(entity instanceof GramJs.MessageEntityMentionName && { userId: buildApiPeerId(entity.userId, 'user') }),\n ...('url' in entity && { url: entity.url }),\n };\n}\n\nfunction buildThreadInfo(\n messageReplies: GramJs.TypeMessageReplies, messageId: number, chatId: string,\n): ApiThreadInfo | undefined {\n const {\n channelId, replies, maxId, readMaxId, recentRepliers,\n } = messageReplies;\n if (!channelId) {\n return undefined;\n }\n\n const apiChannelId = buildApiPeerId(channelId, 'channel');\n if (apiChannelId === DELETED_COMMENTS_CHANNEL_ID) {\n return undefined;\n }\n\n const isPostThread = chatId !== apiChannelId;\n\n return {\n threadId: messageId,\n ...(isPostThread ? {\n chatId: apiChannelId,\n originChannelId: chatId,\n } : {\n chatId,\n }),\n messagesCount: replies,\n lastMessageId: maxId,\n lastReadInboxMessageId: readMaxId,\n ...(recentRepliers && { recentReplierIds: recentRepliers.map(getApiChatIdFromMtpPeer) }),\n };\n}\n","export const getServerTime = (serverTimeOffset: number) => {\n return Math.floor(Date.now() / 1000) + serverTimeOffset;\n};\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport {\n ApiChat,\n ApiChatAdminRights,\n ApiChatBannedRights,\n ApiBotCommand,\n ApiChatFolder,\n ApiChatMember,\n ApiRestrictionReason,\n} from '../../types';\nimport { pick, pickTruthy } from '../../../util/iteratees';\nimport {\n buildApiPeerId, getApiChatIdFromMtpPeer, isPeerChat, isPeerUser,\n} from './peers';\nimport { omitVirtualClassFields } from './helpers';\nimport { getServerTime } from '../../../util/serverTime';\n\ntype PeerEntityApiChatFields = Omit;\n\nfunction buildApiChatFieldsFromPeerEntity(\n peerEntity: GramJs.TypeUser | GramJs.TypeChat,\n isSupport = false,\n): PeerEntityApiChatFields {\n const isMin = Boolean('min' in peerEntity && peerEntity.min);\n const accessHash = ('accessHash' in peerEntity) && String(peerEntity.accessHash);\n const avatarHash = ('photo' in peerEntity) && peerEntity.photo && buildAvatarHash(peerEntity.photo);\n const isSignaturesShown = Boolean('signatures' in peerEntity && peerEntity.signatures);\n const hasPrivateLink = Boolean('hasLink' in peerEntity && peerEntity.hasLink);\n\n return {\n isMin,\n hasPrivateLink,\n isSignaturesShown,\n ...(accessHash && { accessHash }),\n ...(avatarHash && { avatarHash }),\n ...(\n (peerEntity instanceof GramJs.Channel || peerEntity instanceof GramJs.User)\n && { username: peerEntity.username }\n ),\n ...(('verified' in peerEntity) && { isVerified: peerEntity.verified }),\n ...(('callActive' in peerEntity) && { isCallActive: peerEntity.callActive }),\n ...(('callNotEmpty' in peerEntity) && { isCallNotEmpty: peerEntity.callNotEmpty }),\n ...((peerEntity instanceof GramJs.Chat || peerEntity instanceof GramJs.Channel) && {\n ...(peerEntity.participantsCount && { membersCount: peerEntity.participantsCount }),\n joinDate: peerEntity.date,\n }),\n ...((peerEntity instanceof GramJs.Chat || peerEntity instanceof GramJs.Channel) && {\n isProtected: Boolean('noforwards' in peerEntity && peerEntity.noforwards),\n }),\n ...(isSupport && { isSupport: true }),\n ...buildApiChatPermissions(peerEntity),\n ...(('creator' in peerEntity) && { isCreator: peerEntity.creator }),\n ...buildApiChatRestrictions(peerEntity),\n ...buildApiChatMigrationInfo(peerEntity),\n };\n}\n\nexport function buildApiChatFromDialog(\n dialog: GramJs.Dialog,\n peerEntity: GramJs.TypeUser | GramJs.TypeChat,\n serverTimeOffset: number,\n): ApiChat {\n const {\n peer, folderId, unreadMark, unreadCount, unreadMentionsCount, notifySettings: { silent, muteUntil },\n readOutboxMaxId, readInboxMaxId, draft,\n } = dialog;\n const isMuted = silent || (typeof muteUntil === 'number' && getServerTime(serverTimeOffset) < muteUntil);\n\n return {\n id: getApiChatIdFromMtpPeer(peer),\n ...(folderId && { folderId }),\n type: getApiChatTypeFromPeerEntity(peerEntity),\n title: getApiChatTitleFromMtpPeer(peer, peerEntity),\n lastReadOutboxMessageId: readOutboxMaxId,\n lastReadInboxMessageId: readInboxMaxId,\n unreadCount,\n unreadMentionsCount,\n isMuted,\n ...(unreadMark && { hasUnreadMark: true }),\n ...(draft instanceof GramJs.DraftMessage && { draftDate: draft.date }),\n ...buildApiChatFieldsFromPeerEntity(peerEntity),\n };\n}\n\nfunction buildApiChatPermissions(peerEntity: GramJs.TypeUser | GramJs.TypeChat): {\n adminRights?: ApiChatAdminRights;\n currentUserBannedRights?: ApiChatBannedRights;\n defaultBannedRights?: ApiChatBannedRights;\n} {\n if (!(peerEntity instanceof GramJs.Chat || peerEntity instanceof GramJs.Channel)) {\n return {};\n }\n\n return {\n adminRights: peerEntity.adminRights ? omitVirtualClassFields(peerEntity.adminRights) : undefined,\n currentUserBannedRights: peerEntity instanceof GramJs.Channel && peerEntity.bannedRights\n ? omitVirtualClassFields(peerEntity.bannedRights)\n : undefined,\n defaultBannedRights: peerEntity.defaultBannedRights\n ? omitVirtualClassFields(peerEntity.defaultBannedRights)\n : undefined,\n };\n}\n\nfunction buildApiChatRestrictions(peerEntity: GramJs.TypeUser | GramJs.TypeChat): {\n isNotJoined?: boolean;\n isRestricted?: boolean;\n restrictionReason?: ApiRestrictionReason;\n} {\n if (peerEntity instanceof GramJs.ChatForbidden || peerEntity instanceof GramJs.ChannelForbidden) {\n return {\n isRestricted: true,\n };\n }\n\n const restrictions = {};\n\n if ('restricted' in peerEntity) {\n const restrictionReason = peerEntity.restricted\n ? buildApiChatRestrictionReason(peerEntity.restrictionReason)\n : undefined;\n\n if (restrictionReason) {\n Object.assign(restrictions, {\n isRestricted: true,\n restrictionReason,\n });\n }\n }\n\n if (peerEntity instanceof GramJs.Chat) {\n Object.assign(restrictions, {\n isNotJoined: peerEntity.left,\n isRestricted: peerEntity.kicked,\n });\n }\n\n if (peerEntity instanceof GramJs.Channel) {\n Object.assign(restrictions, {\n // `left` is weirdly set to `true` on all channels never joined before\n isNotJoined: peerEntity.left,\n });\n }\n\n return restrictions;\n}\n\nfunction buildApiChatMigrationInfo(peerEntity: GramJs.TypeChat): {\n migratedTo?: {\n chatId: string;\n accessHash?: string;\n };\n} {\n if (\n peerEntity instanceof GramJs.Chat\n && peerEntity.migratedTo\n && !(peerEntity.migratedTo instanceof GramJs.InputChannelEmpty)\n ) {\n return {\n migratedTo: {\n chatId: getApiChatIdFromMtpPeer(peerEntity.migratedTo),\n ...(peerEntity.migratedTo instanceof GramJs.InputChannel && {\n accessHash: String(peerEntity.migratedTo.accessHash),\n }),\n },\n };\n }\n\n return {};\n}\n\nfunction buildApiChatRestrictionReason(\n restrictionReasons?: GramJs.RestrictionReason[],\n): ApiRestrictionReason | undefined {\n if (!restrictionReasons) {\n return undefined;\n }\n\n const targetReason = restrictionReasons.find(({ platform }) => platform === 'all');\n return targetReason ? pick(targetReason, ['reason', 'text']) : undefined;\n}\n\nexport function buildApiChatFromPreview(\n preview: GramJs.TypeChat | GramJs.TypeUser,\n isSupport = false,\n withForbidden = false,\n): ApiChat | undefined {\n if (!(\n preview instanceof GramJs.Chat\n || preview instanceof GramJs.Channel\n || preview instanceof GramJs.User\n || (\n withForbidden\n && (\n preview instanceof GramJs.ChatForbidden\n || preview instanceof GramJs.ChannelForbidden\n )\n )\n )) {\n return undefined;\n }\n\n return {\n id: buildApiPeerId(preview.id, preview instanceof GramJs.User ? 'user' : 'chat'),\n type: getApiChatTypeFromPeerEntity(preview),\n title: preview instanceof GramJs.User ? getUserName(preview) : preview.title,\n ...buildApiChatFieldsFromPeerEntity(preview, isSupport),\n };\n}\n\nexport function getApiChatTypeFromPeerEntity(peerEntity: GramJs.TypeChat | GramJs.TypeUser) {\n if (peerEntity instanceof GramJs.User || peerEntity instanceof GramJs.UserEmpty) {\n return 'chatTypePrivate';\n } else if (\n peerEntity instanceof GramJs.Chat\n || peerEntity instanceof GramJs.ChatForbidden\n || peerEntity instanceof GramJs.ChatEmpty\n ) {\n return 'chatTypeBasicGroup';\n } else {\n return peerEntity.megagroup ? 'chatTypeSuperGroup' : 'chatTypeChannel';\n }\n}\n\nexport function getPeerKey(peer: GramJs.TypePeer) {\n if (isPeerUser(peer)) {\n return `user${peer.userId}`;\n } else if (isPeerChat(peer)) {\n return `chat${peer.chatId}`;\n } else {\n return `chat${peer.channelId}`;\n }\n}\n\nexport function getApiChatTitleFromMtpPeer(peer: GramJs.TypePeer, peerEntity: GramJs.User | GramJs.Chat) {\n if (isPeerUser(peer)) {\n return getUserName(peerEntity as GramJs.User);\n } else {\n return (peerEntity as GramJs.Chat).title;\n }\n}\n\nfunction getUserName(user: GramJs.User) {\n return user.firstName\n ? `${user.firstName}${user.lastName ? ` ${user.lastName}` : ''}`\n : (user.lastName || undefined);\n}\n\nexport function buildAvatarHash(photo: GramJs.TypeUserProfilePhoto | GramJs.TypeChatPhoto) {\n if ('photoId' in photo) {\n return String(photo.photoId);\n }\n\n return undefined;\n}\n\nexport function buildChatMember(\n member: GramJs.TypeChatParticipant | GramJs.TypeChannelParticipant,\n): ApiChatMember | undefined {\n const userId = (member instanceof GramJs.ChannelParticipantBanned || member instanceof GramJs.ChannelParticipantLeft)\n ? getApiChatIdFromMtpPeer(member.peer)\n : buildApiPeerId(member.userId, 'user');\n\n return {\n userId,\n inviterId: 'inviterId' in member ? buildApiPeerId(member.inviterId as BigInt.BigInteger, 'user') : undefined,\n joinedDate: 'date' in member ? member.date : undefined,\n kickedByUserId: 'kickedBy' in member ? buildApiPeerId(member.kickedBy, 'user') : undefined,\n promotedByUserId: 'promotedBy' in member ? buildApiPeerId(member.promotedBy, 'user') : undefined,\n bannedRights: 'bannedRights' in member ? omitVirtualClassFields(member.bannedRights) : undefined,\n adminRights: 'adminRights' in member ? omitVirtualClassFields(member.adminRights) : undefined,\n customTitle: 'rank' in member ? member.rank : undefined,\n ...((member instanceof GramJs.ChannelParticipantAdmin || member instanceof GramJs.ChatParticipantAdmin) && {\n isAdmin: true,\n }),\n ...((member instanceof GramJs.ChannelParticipantCreator || member instanceof GramJs.ChatParticipantCreator) && {\n isOwner: true,\n }),\n };\n}\n\nexport function buildChatMembers(\n participants: GramJs.TypeChatParticipants | GramJs.channels.ChannelParticipants,\n) {\n // Duplicate code because of TS union-type shenanigans\n if (participants instanceof GramJs.ChatParticipants) {\n return participants.participants.map(buildChatMember).filter(Boolean as any);\n }\n if (participants instanceof GramJs.channels.ChannelParticipants) {\n return participants.participants.map(buildChatMember).filter(Boolean as any);\n }\n\n return undefined;\n}\n\nexport function buildChatTypingStatus(\n update: GramJs.UpdateUserTyping | GramJs.UpdateChatUserTyping | GramJs.UpdateChannelUserTyping,\n serverTimeOffset: number,\n) {\n let action: string = '';\n if (update.action instanceof GramJs.SendMessageCancelAction) {\n return undefined;\n } else if (update.action instanceof GramJs.SendMessageTypingAction) {\n action = 'lng_user_typing';\n } else if (update.action instanceof GramJs.SendMessageRecordVideoAction) {\n action = 'lng_send_action_record_video';\n } else if (update.action instanceof GramJs.SendMessageUploadVideoAction) {\n action = 'lng_send_action_upload_video';\n } else if (update.action instanceof GramJs.SendMessageRecordAudioAction) {\n action = 'lng_send_action_record_audio';\n } else if (update.action instanceof GramJs.SendMessageUploadAudioAction) {\n action = 'lng_send_action_upload_audio';\n } else if (update.action instanceof GramJs.SendMessageUploadPhotoAction) {\n action = 'lng_send_action_upload_photo';\n } else if (update.action instanceof GramJs.SendMessageUploadDocumentAction) {\n action = 'lng_send_action_upload_file';\n } else if (update.action instanceof GramJs.SendMessageGeoLocationAction) {\n action = 'selecting a location to share';\n } else if (update.action instanceof GramJs.SendMessageChooseContactAction) {\n action = 'selecting a contact to share';\n } else if (update.action instanceof GramJs.SendMessageGamePlayAction) {\n action = 'lng_playing_game';\n } else if (update.action instanceof GramJs.SendMessageRecordRoundAction) {\n action = 'lng_send_action_record_round';\n } else if (update.action instanceof GramJs.SendMessageUploadRoundAction) {\n action = 'lng_send_action_upload_round';\n } else if (update.action instanceof GramJs.SendMessageChooseStickerAction) {\n action = 'lng_send_action_choose_sticker';\n } else if (update.action instanceof GramJs.SpeakingInGroupCallAction) {\n return undefined;\n }\n\n return {\n action,\n ...(!(update instanceof GramJs.UpdateUserTyping) && { userId: getApiChatIdFromMtpPeer(update.fromId) }),\n timestamp: Date.now() + serverTimeOffset * 1000,\n };\n}\n\nexport function buildApiChatFolder(filter: GramJs.DialogFilter): ApiChatFolder {\n return {\n ...pickTruthy(filter, [\n 'id', 'title', 'emoticon', 'contacts', 'nonContacts', 'groups', 'bots',\n 'excludeMuted', 'excludeRead', 'excludeArchived',\n ]),\n channels: filter.broadcasts,\n pinnedChatIds: filter.pinnedPeers.map(getApiChatIdFromMtpPeer).filter(Boolean as any),\n includedChatIds: filter.includePeers.map(getApiChatIdFromMtpPeer).filter(Boolean as any),\n excludedChatIds: filter.excludePeers.map(getApiChatIdFromMtpPeer).filter(Boolean as any),\n };\n}\n\nexport function buildApiChatFolderFromSuggested({\n filter, description,\n}: {\n filter: GramJs.DialogFilter;\n description: string;\n}): ApiChatFolder {\n return {\n ...buildApiChatFolder(filter),\n description,\n };\n}\n\nexport function buildApiChatBotCommands(botInfos: GramJs.BotInfo[]) {\n return botInfos.reduce((botCommands, botInfo) => {\n const botId = buildApiPeerId(botInfo.userId, 'user');\n\n botCommands = botCommands.concat(botInfo.commands.map((mtpCommand) => ({\n botId,\n ...omitVirtualClassFields(mtpCommand),\n })));\n\n return botCommands;\n }, [] as ApiBotCommand[]);\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n ApiBotCommand, ApiUser, ApiUserStatus, ApiUserType,\n} from '../../types';\nimport { buildApiPeerId } from './peers';\n\nexport function buildApiUserFromFull(mtpUserFull: GramJs.users.UserFull): ApiUser {\n const {\n fullUser: {\n about, commonChatsCount, pinnedMsgId, botInfo, blocked,\n },\n users,\n } = mtpUserFull;\n\n const user = buildApiUser(users[0])!;\n\n return {\n ...user,\n fullInfo: {\n bio: about,\n commonChatsCount,\n pinnedMessageId: pinnedMsgId,\n isBlocked: Boolean(blocked),\n ...(botInfo && { botDescription: botInfo.description }),\n ...(botInfo && botInfo.commands.length && { botCommands: buildApiBotCommands(user.id, botInfo) }),\n },\n };\n}\n\nexport function buildApiUser(mtpUser: GramJs.TypeUser): ApiUser | undefined {\n if (!(mtpUser instanceof GramJs.User)) {\n return undefined;\n }\n\n const { id, firstName, lastName } = mtpUser;\n const avatarHash = mtpUser.photo instanceof GramJs.UserProfilePhoto\n ? String(mtpUser.photo.photoId)\n : undefined;\n const userType = buildApiUserType(mtpUser);\n\n return {\n id: buildApiPeerId(id, 'user'),\n isMin: Boolean(mtpUser.min),\n ...(mtpUser.self && { isSelf: true }),\n ...(mtpUser.verified && { isVerified: true }),\n ...((mtpUser.contact || mtpUser.mutualContact) && { isContact: true }),\n type: userType,\n ...(firstName && { firstName }),\n ...(userType === 'userTypeBot' && { canBeInvitedToGroup: !mtpUser.botNochats }),\n ...(lastName && { lastName }),\n username: mtpUser.username || '',\n phoneNumber: mtpUser.phone || '',\n noStatus: !mtpUser.status,\n ...(mtpUser.accessHash && { accessHash: String(mtpUser.accessHash) }),\n ...(avatarHash && { avatarHash }),\n ...(mtpUser.bot && mtpUser.botInlinePlaceholder && { botPlaceholder: mtpUser.botInlinePlaceholder }),\n };\n}\n\nfunction buildApiUserType(user: GramJs.User): ApiUserType {\n if (user.bot) {\n return 'userTypeBot';\n }\n if (user.deleted) {\n return 'userTypeDeleted';\n }\n\n return 'userTypeRegular';\n}\n\nexport function buildApiUserStatus(mtpStatus?: GramJs.TypeUserStatus): ApiUserStatus {\n if (!mtpStatus || mtpStatus instanceof GramJs.UserStatusEmpty) {\n return { type: 'userStatusEmpty' };\n } else if (mtpStatus instanceof GramJs.UserStatusOnline) {\n return { type: 'userStatusOnline', expires: mtpStatus.expires };\n } else if (mtpStatus instanceof GramJs.UserStatusOffline) {\n return { type: 'userStatusOffline', wasOnline: mtpStatus.wasOnline };\n } else if (mtpStatus instanceof GramJs.UserStatusRecently) {\n return { type: 'userStatusRecently' };\n } else if (mtpStatus instanceof GramJs.UserStatusLastWeek) {\n return { type: 'userStatusLastWeek' };\n } else {\n return { type: 'userStatusLastMonth' };\n }\n}\n\nfunction buildApiBotCommands(botId: string, botInfo: GramJs.BotInfo) {\n return botInfo.commands.map(({ command, description }) => ({\n botId,\n command,\n description,\n })) as ApiBotCommand[];\n}\n\nexport function buildApiUsersAndStatuses(mtpUsers: GramJs.TypeUser[]) {\n const userStatusesById: Record = {};\n const users: ApiUser[] = [];\n\n mtpUsers.forEach((mtpUser) => {\n const user = buildApiUser(mtpUser);\n if (!user) {\n return;\n }\n\n users.push(user);\n\n if ('status' in mtpUser) {\n userStatusesById[user.id] = buildApiUserStatus(mtpUser.status);\n }\n });\n\n return { users, userStatusesById };\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\n\nimport { ApiCountry, ApiSession, ApiWallpaper } from '../../types';\nimport { ApiPrivacySettings, ApiPrivacyKey, PrivacyVisibility } from '../../../types';\n\nimport { buildApiDocument } from './messages';\nimport { buildApiPeerId, getApiChatIdFromMtpPeer } from './peers';\nimport { flatten, pick } from '../../../util/iteratees';\nimport { getServerTime } from '../../../util/serverTime';\n\nexport function buildApiWallpaper(wallpaper: GramJs.TypeWallPaper): ApiWallpaper | undefined {\n if (wallpaper instanceof GramJs.WallPaperNoFile) {\n // TODO: Plain color wallpapers\n return undefined;\n }\n\n const { slug } = wallpaper;\n\n const document = buildApiDocument(wallpaper.document);\n\n if (!document) {\n return undefined;\n }\n\n return {\n slug,\n document,\n };\n}\n\nexport function buildApiSession(session: GramJs.Authorization): ApiSession {\n return {\n isCurrent: Boolean(session.current),\n isOfficialApp: Boolean(session.officialApp),\n isPasswordPending: Boolean(session.passwordPending),\n hash: String(session.hash),\n ...pick(session, [\n 'deviceModel', 'platform', 'systemVersion', 'appName', 'appVersion', 'dateCreated', 'dateActive',\n 'ip', 'country', 'region',\n ]),\n };\n}\n\nexport function buildPrivacyKey(key: GramJs.TypePrivacyKey): ApiPrivacyKey | undefined {\n switch (key.className) {\n case 'PrivacyKeyPhoneNumber':\n return 'phoneNumber';\n case 'PrivacyKeyStatusTimestamp':\n return 'lastSeen';\n case 'PrivacyKeyProfilePhoto':\n return 'profilePhoto';\n case 'PrivacyKeyForwards':\n return 'forwards';\n case 'PrivacyKeyChatInvite':\n return 'chatInvite';\n }\n\n return undefined;\n}\n\nexport function buildPrivacyRules(rules: GramJs.TypePrivacyRule[]): ApiPrivacySettings {\n let visibility: PrivacyVisibility | undefined;\n let allowUserIds: string[] | undefined;\n let allowChatIds: string[] | undefined;\n let blockUserIds: string[] | undefined;\n let blockChatIds: string[] | undefined;\n\n rules.forEach((rule) => {\n if (rule instanceof GramJs.PrivacyValueAllowAll) {\n visibility = visibility || 'everybody';\n } else if (rule instanceof GramJs.PrivacyValueAllowContacts) {\n visibility = visibility || 'contacts';\n } else if (rule instanceof GramJs.PrivacyValueDisallowContacts) {\n visibility = visibility || 'nonContacts';\n } else if (rule instanceof GramJs.PrivacyValueDisallowAll) {\n visibility = visibility || 'nobody';\n } else if (rule instanceof GramJs.PrivacyValueAllowUsers) {\n allowUserIds = rule.users.map((chatId) => buildApiPeerId(chatId, 'user'));\n } else if (rule instanceof GramJs.PrivacyValueDisallowUsers) {\n blockUserIds = rule.users.map((chatId) => buildApiPeerId(chatId, 'user'));\n } else if (rule instanceof GramJs.PrivacyValueAllowChatParticipants) {\n allowChatIds = rule.chats.map((chatId) => buildApiPeerId(chatId, 'chat'));\n } else if (rule instanceof GramJs.PrivacyValueDisallowChatParticipants) {\n blockChatIds = rule.chats.map((chatId) => buildApiPeerId(chatId, 'chat'));\n }\n });\n\n if (!visibility) {\n // disallow by default.\n visibility = 'nobody';\n }\n\n return {\n visibility,\n allowUserIds: allowUserIds || [],\n allowChatIds: allowChatIds || [],\n blockUserIds: blockUserIds || [],\n blockChatIds: blockChatIds || [],\n };\n}\n\nexport function buildApiNotifyException(\n notifySettings: GramJs.TypePeerNotifySettings, peer: GramJs.TypePeer, serverTimeOffset: number,\n) {\n const {\n silent, muteUntil, showPreviews, sound,\n } = notifySettings;\n\n return {\n chatId: getApiChatIdFromMtpPeer(peer),\n isMuted: silent || (typeof muteUntil === 'number' && getServerTime(serverTimeOffset) < muteUntil),\n ...(sound === '' && { isSilent: true }),\n ...(showPreviews !== undefined && { shouldShowPreviews: Boolean(showPreviews) }),\n };\n}\n\nfunction buildApiCountry(country: GramJs.help.Country, code?: GramJs.help.CountryCode) {\n const {\n hidden, iso2, defaultName, name,\n } = country;\n const { countryCode, prefixes, patterns } = code || {};\n\n return {\n isHidden: hidden,\n iso2,\n defaultName,\n name,\n countryCode,\n prefixes,\n patterns,\n };\n}\n\nexport function buildApiCountryList(countries: GramJs.help.Country[]) {\n const listByCode = flatten(\n countries\n .filter((country) => !country.hidden)\n .map((country) => (\n country.countryCodes.map((code) => buildApiCountry(country, code))\n )),\n )\n .sort((a: ApiCountry, b: ApiCountry) => (\n a.name ? a.name.localeCompare(b.name!) : a.defaultName.localeCompare(b.defaultName)\n ));\n\n const generalList = countries\n .filter((country) => !country.hidden)\n .map((country) => buildApiCountry(country))\n .sort((a, b) => (\n a.name ? a.name.localeCompare(b.name!) : a.defaultName.localeCompare(b.defaultName)\n ));\n\n return {\n phoneCodes: listByCode,\n general: generalList,\n };\n}\n","import { GroupCallParticipant, GroupCallParticipantVideo, SsrcGroup } from '../../../lib/secret-sauce';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport { ApiGroupCall } from '../../types';\nimport { getApiChatIdFromMtpPeer, isPeerUser } from './peers';\n\nexport function buildApiGroupCallParticipant(participant: GramJs.GroupCallParticipant): GroupCallParticipant {\n const {\n self, min, about, date, versioned, canSelfUnmute, justJoined, left, muted, mutedByYou, source, volume,\n volumeByAdmin, videoJoined, peer, video, presentation, raiseHandRating,\n } = participant;\n\n return {\n isSelf: self,\n isMin: min,\n canSelfUnmute,\n isLeft: left,\n isMuted: muted,\n isMutedByMe: mutedByYou,\n hasJustJoined: justJoined,\n isVolumeByAdmin: volumeByAdmin,\n isVersioned: versioned,\n isVideoJoined: videoJoined,\n about,\n source,\n raiseHandRating: raiseHandRating?.toString(),\n volume,\n date: new Date(date),\n isUser: isPeerUser(peer),\n id: getApiChatIdFromMtpPeer(peer),\n video: video ? buildApiGroupCallParticipantVideo(video) : undefined,\n presentation: presentation ? buildApiGroupCallParticipantVideo(presentation) : undefined,\n };\n}\n\nfunction buildApiGroupCallParticipantVideo(\n participantVideo: GramJs.GroupCallParticipantVideo,\n): GroupCallParticipantVideo {\n const {\n audioSource, endpoint, paused, sourceGroups,\n } = participantVideo;\n return {\n audioSource,\n endpoint,\n isPaused: paused,\n sourceGroups: sourceGroups.map(buildApiGroupCallParticipantVideoSourceGroup),\n };\n}\n\nfunction buildApiGroupCallParticipantVideoSourceGroup(\n participantVideoSourceGroup: GramJs.GroupCallParticipantVideoSourceGroup,\n): SsrcGroup {\n return {\n semantics: participantVideoSourceGroup.semantics,\n sources: participantVideoSourceGroup.sources,\n };\n}\n\nexport function buildApiGroupCall(groupCall: GramJs.TypeGroupCall): ApiGroupCall {\n const {\n id, accessHash,\n } = groupCall;\n\n if (groupCall instanceof GramJs.GroupCallDiscarded) {\n return {\n connectionState: 'discarded',\n id: id.toString(),\n accessHash: accessHash.toString(),\n participantsCount: 0,\n version: 0,\n participants: {},\n };\n }\n\n const {\n version, participantsCount, streamDcId, scheduleDate, canChangeJoinMuted, joinMuted, canStartVideo,\n scheduleStartSubscribed,\n } = groupCall;\n\n return {\n connectionState: 'disconnected',\n isLoaded: true,\n id: id.toString(),\n accessHash: accessHash.toString(),\n version,\n participantsCount,\n streamDcId,\n scheduleDate,\n canChangeJoinMuted,\n joinMuted,\n canStartVideo,\n scheduleStartSubscribed,\n participants: {},\n };\n}\n\nexport function getGroupCallId(groupCall: GramJs.TypeInputGroupCall) {\n return groupCall.id.toString();\n}\n","import { GroupCallConnectionData } from '../../lib/secret-sauce';\nimport { Api as GramJs, connection } from '../../lib/gramjs';\nimport { ApiMessage, ApiUpdateConnectionStateType, OnApiUpdate } from '../types';\n\nimport { pick } from '../../util/iteratees';\nimport {\n buildApiMessage,\n buildApiMessageFromShort,\n buildApiMessageFromShortChat,\n buildMessageMediaContent,\n buildMessageTextContent,\n buildPoll,\n buildPollResults,\n buildApiMessageFromNotification,\n buildMessageDraft,\n} from './apiBuilders/messages';\nimport {\n buildChatMember,\n buildChatMembers,\n buildChatTypingStatus,\n buildAvatarHash,\n buildApiChatFromPreview,\n buildApiChatFolder,\n} from './apiBuilders/chats';\nimport { buildApiUser, buildApiUserStatus } from './apiBuilders/users';\nimport {\n buildMessageFromUpdate,\n isMessageWithMedia,\n buildChatPhotoForLocalDb,\n} from './gramjsBuilders';\nimport localDb from './localDb';\nimport { omitVirtualClassFields } from './apiBuilders/helpers';\nimport { DEBUG } from '../../config';\nimport {\n addMessageToLocalDb,\n addEntitiesWithPhotosToLocalDb,\n addPhotoToLocalDb,\n resolveMessageApiChatId,\n serializeBytes,\n} from './helpers';\nimport { buildApiNotifyException, buildPrivacyKey, buildPrivacyRules } from './apiBuilders/misc';\nimport { buildApiPhoto } from './apiBuilders/common';\nimport {\n buildApiGroupCall,\n buildApiGroupCallParticipant,\n getGroupCallId,\n} from './apiBuilders/calls';\nimport { buildApiPeerId, getApiChatIdFromMtpPeer } from './apiBuilders/peers';\n\ntype Update = (\n (GramJs.TypeUpdate | GramJs.TypeUpdates) & { _entities?: (GramJs.TypeUser | GramJs.TypeChat)[] }\n) | typeof connection.UpdateConnectionState;\n\nconst DELETE_MISSING_CHANNEL_MESSAGE_DELAY = 1000;\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nconst sentMessageIds = new Set();\nlet serverTimeOffset = 0;\n// Workaround for a situation when an incorrect update comes with an undefined property `adminRights`\nlet shouldIgnoreNextChannelUpdate = false;\nconst IGNORE_NEXT_CHANNEL_UPDATE_TIMEOUT = 2000;\n\nfunction dispatchUserAndChatUpdates(entities: (GramJs.TypeUser | GramJs.TypeChat)[]) {\n entities\n .filter((e) => e instanceof GramJs.User)\n .map(buildApiUser)\n .forEach((user) => {\n if (!user) {\n return;\n }\n\n onUpdate({\n '@type': 'updateUser',\n id: user.id,\n user,\n });\n });\n\n entities\n .filter((e) => e instanceof GramJs.Chat || e instanceof GramJs.Channel)\n .map((e) => buildApiChatFromPreview(e))\n .forEach((chat) => {\n if (!chat) {\n return;\n }\n\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n });\n}\n\nexport function updater(update: Update, originRequest?: GramJs.AnyRequest) {\n if (update instanceof connection.UpdateServerTimeOffset) {\n serverTimeOffset = update.timeOffset;\n } else if (update instanceof connection.UpdateConnectionState) {\n let connectionState: ApiUpdateConnectionStateType;\n\n switch (update.state) {\n case connection.UpdateConnectionState.disconnected:\n connectionState = 'connectionStateConnecting';\n break;\n case connection.UpdateConnectionState.broken:\n connectionState = 'connectionStateBroken';\n break;\n case connection.UpdateConnectionState.connected:\n default:\n connectionState = 'connectionStateReady';\n break;\n }\n\n onUpdate({\n '@type': 'updateConnectionState',\n connectionState,\n });\n\n // Messages\n } else if (\n update instanceof GramJs.UpdateNewMessage\n || update instanceof GramJs.UpdateNewScheduledMessage\n || update instanceof GramJs.UpdateNewChannelMessage\n || update instanceof GramJs.UpdateShortChatMessage\n || update instanceof GramJs.UpdateShortMessage\n ) {\n let message: ApiMessage | undefined;\n let shouldForceReply: boolean | undefined;\n\n if (update instanceof GramJs.UpdateShortChatMessage) {\n message = buildApiMessageFromShortChat(update);\n } else if (update instanceof GramJs.UpdateShortMessage) {\n message = buildApiMessageFromShort(update);\n } else {\n // TODO Remove if proven not reproducing\n if (update.message instanceof GramJs.MessageEmpty) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected update:', update.className, update);\n }\n\n return;\n }\n\n if (update.message instanceof GramJs.Message && isMessageWithMedia(update.message)) {\n addMessageToLocalDb(update.message);\n }\n\n message = buildApiMessage(update.message)!;\n shouldForceReply = 'replyMarkup' in update.message\n && update.message?.replyMarkup instanceof GramJs.ReplyKeyboardForceReply\n && (!update.message.replyMarkup.selective || message.isMentioned);\n }\n\n // eslint-disable-next-line no-underscore-dangle\n const entities = update._entities;\n if (entities) {\n addEntitiesWithPhotosToLocalDb(entities);\n dispatchUserAndChatUpdates(entities);\n }\n\n if (update instanceof GramJs.UpdateNewScheduledMessage) {\n onUpdate({\n '@type': sentMessageIds.has(message.id) ? 'updateScheduledMessage' : 'newScheduledMessage',\n id: message.id,\n chatId: message.chatId,\n message,\n });\n } else {\n onUpdate({\n '@type': sentMessageIds.has(message.id) ? 'updateMessage' : 'newMessage',\n id: message.id,\n chatId: message.chatId,\n message,\n shouldForceReply,\n });\n }\n\n // Some updates to a Chat/Channel don't have a dedicated update class.\n // We can get info on some updates from Service Messages.\n if (update.message instanceof GramJs.MessageService) {\n const { action } = update.message;\n\n if (action instanceof GramJs.MessageActionChatEditTitle) {\n onUpdate({\n '@type': 'updateChat',\n id: message.chatId,\n chat: {\n title: action.title,\n },\n });\n } else if (action instanceof GramJs.MessageActionChatEditPhoto) {\n const photo = buildChatPhotoForLocalDb(action.photo);\n const avatarHash = buildAvatarHash(photo);\n\n const localDbChatId = resolveMessageApiChatId(update.message)!;\n if (localDb.chats[localDbChatId]) {\n localDb.chats[localDbChatId].photo = photo;\n }\n addPhotoToLocalDb(action.photo);\n\n if (avatarHash) {\n onUpdate({\n '@type': 'updateChat',\n id: message.chatId,\n chat: {\n avatarHash,\n },\n ...(action.photo instanceof GramJs.Photo && { newProfilePhoto: buildApiPhoto(action.photo) }),\n });\n }\n } else if (action instanceof GramJs.MessageActionChatDeletePhoto) {\n const localDbChatId = resolveMessageApiChatId(update.message)!;\n if (localDb.chats[localDbChatId]) {\n localDb.chats[localDbChatId].photo = new GramJs.ChatPhotoEmpty();\n }\n\n onUpdate({\n '@type': 'updateChat',\n id: message.chatId,\n chat: { avatarHash: undefined },\n });\n } else if (action instanceof GramJs.MessageActionChatDeleteUser) {\n // eslint-disable-next-line no-underscore-dangle\n if (update._entities && update._entities.some((e): e is GramJs.User => (\n e instanceof GramJs.User && !!e.self && e.id === action.userId\n ))) {\n onUpdate({\n '@type': 'updateChat',\n id: message.chatId,\n chat: {\n isRestricted: true,\n },\n });\n\n onUpdate({\n '@type': 'updateChatLeave',\n id: message.chatId,\n });\n }\n } else if (action instanceof GramJs.MessageActionChatAddUser) {\n // eslint-disable-next-line no-underscore-dangle\n if (update._entities && update._entities.some((e): e is GramJs.User => (\n e instanceof GramJs.User && !!e.self && action.users.includes(e.id)\n ))) {\n onUpdate({\n '@type': 'updateChatJoin',\n id: message.chatId,\n });\n }\n } else if (action instanceof GramJs.MessageActionGroupCall) {\n if (!action.duration && action.call) {\n onUpdate({\n '@type': 'updateGroupCallChatId',\n chatId: message.chatId,\n call: {\n id: action.call.id.toString(),\n accessHash: action.call.accessHash.toString(),\n },\n });\n }\n }\n }\n } else if (\n update instanceof GramJs.UpdateEditMessage\n || update instanceof GramJs.UpdateEditChannelMessage\n ) {\n // TODO Remove if proven not reproducing\n if (update.message instanceof GramJs.MessageEmpty) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected update:', update.className, update);\n }\n\n return;\n }\n\n if (update.message instanceof GramJs.Message && isMessageWithMedia(update.message)) {\n addMessageToLocalDb(update.message);\n }\n\n const message = buildApiMessage(update.message)!;\n\n onUpdate({\n '@type': 'updateMessage',\n id: message.id,\n chatId: message.chatId,\n message,\n });\n } else if (update instanceof GramJs.UpdateDeleteMessages) {\n onUpdate({\n '@type': 'deleteMessages',\n ids: update.messages,\n });\n } else if (update instanceof GramJs.UpdateDeleteScheduledMessages) {\n onUpdate({\n '@type': 'deleteScheduledMessages',\n ids: update.messages,\n chatId: getApiChatIdFromMtpPeer(update.peer),\n });\n } else if (update instanceof GramJs.UpdateDeleteChannelMessages) {\n const chatId = buildApiPeerId(update.channelId, 'channel');\n const ids = update.messages;\n const existingIds = ids.filter((id) => localDb.messages[`${chatId}-${id}`]);\n const missingIds = ids.filter((id) => !localDb.messages[`${chatId}-${id}`]);\n const profilePhotoIds = ids.map((id) => {\n const message = localDb.messages[`${chatId}-${id}`];\n\n return message && message instanceof GramJs.MessageService && 'photo' in message.action\n ? String(message.action.photo.id)\n : undefined;\n }).filter(Boolean as any);\n\n if (existingIds.length) {\n onUpdate({\n '@type': 'deleteMessages',\n ids: existingIds,\n chatId,\n });\n }\n\n if (profilePhotoIds.length) {\n onUpdate({\n '@type': 'deleteProfilePhotos',\n ids: profilePhotoIds,\n chatId,\n });\n }\n\n // For some reason delete message update sometimes comes before new message update\n if (missingIds.length) {\n setTimeout(() => {\n onUpdate({\n '@type': 'deleteMessages',\n ids: missingIds,\n chatId,\n });\n }, DELETE_MISSING_CHANNEL_MESSAGE_DELAY);\n }\n } else if (update instanceof GramJs.UpdateServiceNotification) {\n if (update.popup) {\n onUpdate({\n '@type': 'error',\n error: {\n message: update.message,\n },\n });\n } else {\n const currentDate = Date.now() / 1000 + serverTimeOffset;\n const message = buildApiMessageFromNotification(update, currentDate);\n\n if (isMessageWithMedia(update)) {\n addMessageToLocalDb(buildMessageFromUpdate(message.id, message.chatId, update));\n }\n\n onUpdate({\n '@type': 'updateServiceNotification',\n message,\n });\n }\n } else if ((\n originRequest instanceof GramJs.messages.SendMessage\n || originRequest instanceof GramJs.messages.SendMedia\n || originRequest instanceof GramJs.messages.SendMultiMedia\n || originRequest instanceof GramJs.messages.ForwardMessages\n ) && (\n update instanceof GramJs.UpdateMessageID\n || update instanceof GramJs.UpdateShortSentMessage\n )) {\n let randomId;\n if ('randomId' in update) {\n randomId = update.randomId;\n } else if ('randomId' in originRequest) {\n randomId = originRequest.randomId;\n }\n\n const localMessage = randomId && localDb.localMessages[String(randomId)];\n if (!localMessage) {\n throw new Error('Local message not found');\n }\n\n let newContent: ApiMessage['content'] | undefined;\n if (update instanceof GramJs.UpdateShortSentMessage) {\n if (localMessage.content.text && update.entities) {\n newContent = {\n text: buildMessageTextContent(localMessage.content.text.text, update.entities),\n };\n }\n if (update.media) {\n newContent = {\n ...newContent,\n ...buildMessageMediaContent(update.media),\n };\n }\n\n const mtpMessage = buildMessageFromUpdate(update.id, localMessage.chatId, update);\n if (isMessageWithMedia(mtpMessage)) {\n addMessageToLocalDb(mtpMessage);\n }\n }\n\n sentMessageIds.add(update.id);\n\n // Edge case for \"Send When Online\"\n const isAlreadySent = 'date' in update && update.date * 1000 < Date.now() + serverTimeOffset * 1000;\n\n onUpdate({\n '@type': localMessage.isScheduled && !isAlreadySent\n ? 'updateScheduledMessageSendSucceeded'\n : 'updateMessageSendSucceeded',\n chatId: localMessage.chatId,\n localId: localMessage.id,\n message: {\n ...localMessage,\n ...(newContent && {\n content: {\n ...localMessage.content,\n ...newContent,\n },\n }),\n id: update.id,\n sendingState: undefined,\n ...('date' in update && { date: update.date }),\n },\n });\n } else if (update instanceof GramJs.UpdateReadMessagesContents) {\n onUpdate({\n '@type': 'updateCommonBoxMessages',\n ids: update.messages,\n messageUpdate: {\n hasUnreadMention: false,\n isMediaUnread: false,\n },\n });\n } else if (update instanceof GramJs.UpdateChannelReadMessagesContents) {\n onUpdate({\n '@type': 'updateChannelMessages',\n channelId: buildApiPeerId(update.channelId, 'channel'),\n ids: update.messages,\n messageUpdate: {\n hasUnreadMention: false,\n isMediaUnread: false,\n },\n });\n } else if (update instanceof GramJs.UpdateMessagePoll) {\n const { pollId, poll, results } = update;\n if (poll) {\n const apiPoll = buildPoll(poll, results);\n\n onUpdate({\n '@type': 'updateMessagePoll',\n pollId: String(pollId),\n pollUpdate: apiPoll,\n });\n } else {\n const pollResults = buildPollResults(results);\n onUpdate({\n '@type': 'updateMessagePoll',\n pollId: String(pollId),\n pollUpdate: { results: pollResults },\n });\n }\n } else if (update instanceof GramJs.UpdateMessagePollVote) {\n onUpdate({\n '@type': 'updateMessagePollVote',\n pollId: String(update.pollId),\n userId: buildApiPeerId(update.userId, 'user'),\n options: update.options.map(serializeBytes),\n });\n } else if (update instanceof GramJs.UpdateChannelMessageViews) {\n onUpdate({\n '@type': 'updateMessage',\n chatId: buildApiPeerId(update.channelId, 'channel'),\n id: update.id,\n message: { views: update.views },\n });\n\n // Chats\n } else if (update instanceof GramJs.UpdateReadHistoryInbox) {\n onUpdate({\n '@type': 'updateChatInbox',\n id: getApiChatIdFromMtpPeer(update.peer),\n chat: {\n lastReadInboxMessageId: update.maxId,\n unreadCount: update.stillUnreadCount,\n },\n });\n } else if (update instanceof GramJs.UpdateReadHistoryOutbox) {\n onUpdate({\n '@type': 'updateChat',\n id: getApiChatIdFromMtpPeer(update.peer),\n chat: {\n lastReadOutboxMessageId: update.maxId,\n },\n });\n } else if (update instanceof GramJs.UpdateReadChannelInbox) {\n onUpdate({\n '@type': 'updateChat',\n id: buildApiPeerId(update.channelId, 'channel'),\n chat: {\n lastReadInboxMessageId: update.maxId,\n unreadCount: update.stillUnreadCount,\n },\n });\n } else if (update instanceof GramJs.UpdateReadChannelOutbox) {\n onUpdate({\n '@type': 'updateChat',\n id: buildApiPeerId(update.channelId, 'channel'),\n chat: {\n lastReadOutboxMessageId: update.maxId,\n },\n });\n } else if (\n update instanceof GramJs.UpdateDialogPinned\n && update.peer instanceof GramJs.DialogPeer\n ) {\n onUpdate({\n '@type': 'updateChatPinned',\n id: getApiChatIdFromMtpPeer(update.peer.peer),\n isPinned: update.pinned || false,\n });\n } else if (update instanceof GramJs.UpdatePinnedDialogs) {\n const ids = update.order\n ? update.order\n .filter((dp): dp is GramJs.DialogPeer => dp instanceof GramJs.DialogPeer)\n .map((dp) => getApiChatIdFromMtpPeer(dp.peer))\n : [];\n\n onUpdate({\n '@type': 'updatePinnedChatIds',\n ids,\n folderId: update.folderId || undefined,\n });\n } else if (update instanceof GramJs.UpdateFolderPeers) {\n update.folderPeers.forEach((folderPeer) => {\n const { folderId, peer } = folderPeer;\n\n onUpdate({\n '@type': 'updateChatListType',\n id: getApiChatIdFromMtpPeer(peer),\n folderId,\n });\n });\n } else if (update instanceof GramJs.UpdateDialogFilter) {\n const { id, filter } = update;\n const folder = filter ? buildApiChatFolder(filter) : undefined;\n\n onUpdate({\n '@type': 'updateChatFolder',\n id,\n folder,\n });\n } else if (update instanceof GramJs.UpdateDialogFilterOrder) {\n onUpdate({\n '@type': 'updateChatFoldersOrder',\n orderedIds: update.order,\n });\n } else if (update instanceof GramJs.UpdateChatParticipants) {\n const replacedMembers = buildChatMembers(update.participants);\n\n onUpdate({\n '@type': 'updateChatMembers',\n id: buildApiPeerId(update.participants.chatId, 'chat'),\n replacedMembers,\n });\n } else if (update instanceof GramJs.UpdateChatParticipantAdd) {\n const addedMember = buildChatMember(\n pick(update, ['userId', 'inviterId', 'date']) as GramJs.ChatParticipant,\n );\n\n onUpdate({\n '@type': 'updateChatMembers',\n id: buildApiPeerId(update.chatId, 'chat'),\n addedMember,\n });\n } else if (update instanceof GramJs.UpdateChatParticipantDelete) {\n onUpdate({\n '@type': 'updateChatMembers',\n id: buildApiPeerId(update.chatId, 'chat'),\n deletedMemberId: buildApiPeerId(update.userId, 'user'),\n });\n } else if (\n update instanceof GramJs.UpdatePinnedMessages\n || update instanceof GramJs.UpdatePinnedChannelMessages\n ) {\n const chatId = update instanceof GramJs.UpdatePinnedMessages\n ? getApiChatIdFromMtpPeer(update.peer)\n : buildApiPeerId(update.channelId, 'channel');\n\n onUpdate({\n '@type': 'updatePinnedIds',\n chatId,\n messageIds: update.messages,\n isPinned: update.pinned,\n });\n } else if (\n update instanceof GramJs.UpdateNotifySettings\n && update.peer instanceof GramJs.NotifyPeer\n ) {\n onUpdate({\n '@type': 'updateNotifyExceptions',\n ...buildApiNotifyException(update.notifySettings, update.peer.peer, serverTimeOffset),\n });\n } else if (\n update instanceof GramJs.UpdateUserTyping\n || update instanceof GramJs.UpdateChatUserTyping\n ) {\n const id = update instanceof GramJs.UpdateUserTyping\n ? buildApiPeerId(update.userId, 'user')\n : buildApiPeerId(update.chatId, 'chat');\n\n onUpdate({\n '@type': 'updateChatTypingStatus',\n id,\n typingStatus: buildChatTypingStatus(update, serverTimeOffset),\n });\n } else if (update instanceof GramJs.UpdateChannelUserTyping) {\n const id = buildApiPeerId(update.channelId, 'channel');\n\n onUpdate({\n '@type': 'updateChatTypingStatus',\n id,\n typingStatus: buildChatTypingStatus(update, serverTimeOffset),\n });\n } else if (update instanceof GramJs.UpdateChannel) {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n const { _entities } = update;\n if (!_entities) {\n return;\n }\n\n const channel = _entities.find((e): e is GramJs.Channel | GramJs.ChannelForbidden => (\n e instanceof GramJs.Channel || e instanceof GramJs.ChannelForbidden\n ));\n\n if (channel instanceof GramJs.Channel) {\n if (shouldIgnoreNextChannelUpdate) {\n shouldIgnoreNextChannelUpdate = false;\n return;\n }\n\n if (originRequest instanceof GramJs.messages.ToggleNoForwards) {\n shouldIgnoreNextChannelUpdate = true;\n setTimeout(() => { shouldIgnoreNextChannelUpdate = false; }, IGNORE_NEXT_CHANNEL_UPDATE_TIMEOUT);\n }\n\n const chat = buildApiChatFromPreview(channel);\n if (chat) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n\n onUpdate({\n '@type': chat.isNotJoined ? 'updateChatLeave' : 'updateChatJoin',\n id: buildApiPeerId(update.channelId, 'channel'),\n });\n }\n } else if (channel instanceof GramJs.ChannelForbidden) {\n const chatId = buildApiPeerId(update.channelId, 'channel');\n\n onUpdate({\n '@type': 'updateChat',\n id: chatId,\n chat: {\n isRestricted: true,\n },\n });\n\n onUpdate({\n '@type': 'updateChatLeave',\n id: chatId,\n });\n } else if (_entities.length === 0) {\n // The link to the discussion group may have been changed.\n // No corresponding update available at this moment https://core.telegram.org/type/Updates\n onUpdate({\n '@type': 'resetMessages',\n id: buildApiPeerId(update.channelId, 'channel'),\n });\n }\n } else if (\n update instanceof GramJs.UpdateDialogUnreadMark\n && update.peer instanceof GramJs.DialogPeer\n ) {\n onUpdate({\n '@type': 'updateChat',\n id: getApiChatIdFromMtpPeer(update.peer.peer),\n chat: {\n hasUnreadMark: update.unread,\n },\n });\n } else if (update instanceof GramJs.UpdateChatDefaultBannedRights) {\n onUpdate({\n '@type': 'updateChat',\n id: getApiChatIdFromMtpPeer(update.peer),\n chat: {\n defaultBannedRights: omitVirtualClassFields(update.defaultBannedRights),\n },\n });\n\n // Users\n } else if (update instanceof GramJs.UpdateUserStatus) {\n onUpdate({\n '@type': 'updateUserStatus',\n userId: buildApiPeerId(update.userId, 'user'),\n status: buildApiUserStatus(update.status),\n });\n } else if (update instanceof GramJs.UpdateUserName) {\n const apiUserId = buildApiPeerId(update.userId, 'user');\n const updatedUser = localDb.users[apiUserId];\n const user = updatedUser?.mutualContact && !updatedUser.self\n ? pick(update, ['username'])\n : pick(update, ['firstName', 'lastName', 'username']);\n\n onUpdate({\n '@type': 'updateUser',\n id: apiUserId,\n user,\n });\n } else if (update instanceof GramJs.UpdateUserPhoto) {\n const { userId, photo } = update;\n const apiUserId = buildApiPeerId(userId, 'user');\n const avatarHash = buildAvatarHash(photo);\n\n if (localDb.users[apiUserId]) {\n localDb.users[apiUserId].photo = photo;\n }\n\n onUpdate({\n '@type': 'updateUser',\n id: apiUserId,\n user: { avatarHash },\n });\n } else if (update instanceof GramJs.UpdateUserPhone) {\n const { userId, phone } = update;\n\n onUpdate({\n '@type': 'updateUser',\n id: buildApiPeerId(userId, 'user'),\n user: { phoneNumber: phone },\n });\n } else if (update instanceof GramJs.UpdatePeerSettings) {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n const { _entities } = update;\n if (!_entities) {\n return;\n }\n\n if (_entities?.length) {\n _entities\n .filter((e) => e instanceof GramJs.User && !e.contact)\n .forEach((user) => {\n onUpdate({\n '@type': 'deleteContact',\n id: buildApiPeerId(user.id, 'user'),\n });\n });\n\n _entities\n .filter((e) => e instanceof GramJs.User && e.contact)\n .map(buildApiUser)\n .forEach((user) => {\n if (!user) {\n return;\n }\n\n onUpdate({\n '@type': 'updateUser',\n id: user.id,\n user,\n });\n });\n }\n\n // Settings\n } else if (update instanceof GramJs.UpdateNotifySettings) {\n const {\n notifySettings: {\n showPreviews, silent, muteUntil,\n },\n peer: { className },\n } = update;\n\n const peerType = className === 'NotifyUsers'\n ? 'contact'\n : (className === 'NotifyChats'\n ? 'group'\n : (className === 'NotifyBroadcasts'\n ? 'broadcast'\n : undefined\n )\n );\n\n if (!peerType) {\n return;\n }\n\n onUpdate({\n '@type': 'updateNotifySettings',\n peerType,\n isSilent: Boolean(silent\n || (typeof muteUntil === 'number' && Date.now() + serverTimeOffset * 1000 < muteUntil * 1000)),\n shouldShowPreviews: Boolean(showPreviews),\n });\n } else if (update instanceof GramJs.UpdatePeerBlocked) {\n onUpdate({\n '@type': 'updatePeerBlocked',\n id: getApiChatIdFromMtpPeer(update.peerId),\n isBlocked: update.blocked,\n });\n } else if (update instanceof GramJs.UpdatePrivacy) {\n const key = buildPrivacyKey(update.key);\n if (key) {\n onUpdate({\n '@type': 'updatePrivacy',\n key,\n rules: buildPrivacyRules(update.rules),\n });\n }\n\n // Misc\n } else if (update instanceof GramJs.UpdateDraftMessage) {\n onUpdate({\n '@type': 'draftMessage',\n chatId: getApiChatIdFromMtpPeer(update.peer),\n ...buildMessageDraft(update.draft),\n });\n } else if (update instanceof GramJs.UpdateContactsReset) {\n onUpdate({ '@type': 'updateResetContactList' });\n } else if (update instanceof GramJs.UpdateFavedStickers) {\n onUpdate({ '@type': 'updateFavoriteStickers' });\n } else if (update instanceof GramJs.UpdateGroupCall) {\n onUpdate({\n '@type': 'updateGroupCall',\n call: buildApiGroupCall(update.call),\n });\n } else if (update instanceof GramJs.UpdateGroupCallConnection) {\n onUpdate({\n '@type': 'updateGroupCallConnection',\n data: JSON.parse(update.params.data) as GroupCallConnectionData,\n presentation: Boolean(update.presentation),\n });\n } else if (update instanceof GramJs.UpdateGroupCallParticipants) {\n // eslint-disable-next-line no-underscore-dangle\n const entities = update._entities;\n if (entities) {\n addEntitiesWithPhotosToLocalDb(entities);\n dispatchUserAndChatUpdates(entities);\n }\n\n onUpdate({\n '@type': 'updateGroupCallParticipants',\n groupCallId: getGroupCallId(update.call),\n participants: update.participants.map(buildApiGroupCallParticipant),\n });\n } else if (DEBUG) {\n const params = typeof update === 'object' && 'className' in update ? update.className : update;\n // eslint-disable-next-line no-console\n console.warn('[GramJs/updater] Unexpected update:', params);\n }\n}\n","import { errors } from '../../../lib/gramjs';\nimport {\n ApiUpdateAuthorizationState,\n ApiUpdateAuthorizationStateType,\n OnApiUpdate,\n ApiUser,\n} from '../../types';\n\nimport { DEBUG } from '../../../config';\n\nconst ApiErrors: { [k: string]: string } = {\n PHONE_NUMBER_INVALID: 'Invalid phone number.',\n PHONE_CODE_INVALID: 'Invalid code.',\n PASSWORD_HASH_INVALID: 'Incorrect password.',\n PHONE_PASSWORD_FLOOD: 'Limit exceeded. Please try again later.',\n PHONE_NUMBER_BANNED: 'This phone number is banned.',\n};\n\nconst authController: {\n resolve?: Function;\n reject?: Function;\n} = {};\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport function onRequestPhoneNumber() {\n onUpdate(buildAuthStateUpdate('authorizationStateWaitPhoneNumber'));\n\n return new Promise((resolve, reject) => {\n authController.resolve = resolve;\n authController.reject = reject;\n });\n}\n\nexport function onRequestCode(isCodeViaApp = false) {\n onUpdate({\n ...buildAuthStateUpdate('authorizationStateWaitCode'),\n isCodeViaApp,\n });\n\n return new Promise((resolve, reject) => {\n authController.resolve = resolve;\n authController.reject = reject;\n });\n}\n\nexport function onRequestPassword(hint?: string) {\n onUpdate({\n ...buildAuthStateUpdate('authorizationStateWaitPassword'),\n hint,\n });\n\n return new Promise((resolve) => {\n authController.resolve = resolve;\n });\n}\n\nexport function onRequestRegistration() {\n onUpdate(buildAuthStateUpdate('authorizationStateWaitRegistration'));\n\n return new Promise<[string, string?]>((resolve) => {\n authController.resolve = resolve;\n });\n}\n\nexport function onRequestQrCode(qrCode: { token: Buffer; expires: number }) {\n onUpdate({\n ...buildAuthStateUpdate('authorizationStateWaitQrCode'),\n qrCode: {\n token: btoa(String.fromCharCode(...qrCode.token)).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, ''),\n expires: qrCode.expires,\n },\n });\n\n return new Promise((resolve, reject) => {\n authController.reject = reject;\n });\n}\n\nexport function onAuthError(err: Error) {\n let message: string;\n\n if (err instanceof errors.FloodWaitError) {\n const hours = Math.ceil(Number(err.seconds) / 60 / 60);\n message = `Too many attempts. Try again in ${hours > 1 ? `${hours} hours` : 'an hour'}`;\n } else {\n message = ApiErrors[err.message];\n }\n\n if (!message) {\n message = 'Unexpected Error';\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n }\n\n onUpdate({\n '@type': 'updateAuthorizationError',\n message,\n });\n}\n\nexport function onAuthReady() {\n onUpdate(buildAuthStateUpdate('authorizationStateReady'));\n}\n\nexport function onCurrentUserUpdate(currentUser: ApiUser) {\n onUpdate({\n '@type': 'updateCurrentUser',\n currentUser,\n });\n}\n\nexport function buildAuthStateUpdate(authorizationState: ApiUpdateAuthorizationStateType): ApiUpdateAuthorizationState {\n return {\n '@type': 'updateAuthorizationState',\n authorizationState,\n };\n}\n\nexport function provideAuthPhoneNumber(phoneNumber: string) {\n if (!authController.resolve) {\n return;\n }\n\n authController.resolve(phoneNumber);\n}\n\nexport function provideAuthCode(code: string) {\n if (!authController.resolve) {\n return;\n }\n\n authController.resolve(code);\n}\n\nexport function provideAuthPassword(password: string) {\n if (!authController.resolve) {\n return;\n }\n\n authController.resolve(password);\n}\n\nexport function provideAuthRegistration(registration: { firstName: string; lastName: string }) {\n const { firstName, lastName } = registration;\n\n if (!authController.resolve) {\n return;\n }\n\n authController.resolve([firstName, lastName]);\n}\n\nexport function restartAuth() {\n if (!authController.reject) {\n return;\n }\n\n authController.reject(new Error('RESTART_AUTH'));\n}\n\nexport function restartAuthWithQr() {\n if (!authController.reject) {\n return;\n }\n\n authController.reject(new Error('RESTART_AUTH_WITH_QR'));\n}\n","// eslint-disable-next-line no-restricted-globals\nconst cacheApi = self.caches;\n\nexport enum Type {\n Text,\n Blob,\n Json,\n}\n\nexport async function fetch(\n cacheName: string, key: string, type: Type, isHtmlAllowed = false,\n) {\n if (!cacheApi) {\n return undefined;\n }\n\n try {\n // To avoid the error \"Request scheme 'webdocument' is unsupported\"\n const request = new Request(key.replace(/:/g, '_'));\n const cache = await cacheApi.open(cacheName);\n const response = await cache.match(request);\n if (!response) {\n return undefined;\n }\n\n const contentType = response.headers.get('Content-Type');\n\n switch (type) {\n case Type.Text:\n return await response.text();\n case Type.Blob: {\n // Ignore deprecated data-uri avatars\n if (key.startsWith('avatar') && contentType && contentType.startsWith('text')) {\n return undefined;\n }\n\n const blob = await response.blob();\n\n // Safari does not return correct Content-Type header for webp images.\n if (key.startsWith('sticker')) {\n return new Blob([blob], { type: 'image/webp' });\n }\n\n const shouldRecreate = !blob.type || (!isHtmlAllowed && blob.type.includes('html'));\n // iOS Safari fails to preserve `type` in cache\n let resolvedType = blob.type || contentType;\n\n if (!(shouldRecreate && resolvedType)) {\n return blob;\n }\n\n // Prevent HTML-in-video attacks (for files that were cached before fix)\n if (!isHtmlAllowed) {\n resolvedType = resolvedType.replace(/html/gi, '');\n }\n\n return new Blob([blob], { type: resolvedType });\n }\n case Type.Json:\n return await response.json();\n default:\n return undefined;\n }\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n\nexport async function save(cacheName: string, key: string, data: AnyLiteral | Blob | string) {\n if (!cacheApi) {\n return undefined;\n }\n\n try {\n const cacheData = typeof data === 'string' || data instanceof Blob ? data : JSON.stringify(data);\n // To avoid the error \"Request scheme 'webdocument' is unsupported\"\n const request = new Request(key.replace(/:/g, '_'));\n const response = new Response(cacheData);\n const cache = await cacheApi.open(cacheName);\n return await cache.put(request, response);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n\nexport async function clear(cacheName: string) {\n try {\n if (!cacheApi) {\n return undefined;\n }\n\n return await cacheApi.delete(cacheName);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n","import { inflate } from 'pako/dist/pako_inflate';\n\nimport { Api as GramJs, TelegramClient } from '../../../lib/gramjs';\nimport {\n ApiMediaFormat, ApiOnProgress, ApiParsedMedia, ApiPreparedMedia,\n} from '../../types';\n\nimport {\n DOWNLOAD_WORKERS,\n MEDIA_CACHE_DISABLED,\n MEDIA_CACHE_MAX_BYTES,\n MEDIA_CACHE_NAME,\n MEDIA_CACHE_NAME_AVATARS,\n} from '../../../config';\nimport localDb from '../localDb';\nimport { getEntityTypeById } from '../gramjsBuilders';\nimport * as cacheApi from '../../../util/cacheApi';\n\ntype EntityType = (\n 'msg' | 'sticker' | 'wallpaper' | 'gif' | 'channel' | 'chat' | 'user' | 'photo' | 'stickerSet' | 'webDocument'\n);\nconst MEDIA_ENTITY_TYPES = new Set(['msg', 'sticker', 'gif', 'wallpaper', 'photo', 'webDocument']);\n\nexport default async function downloadMedia(\n {\n url, mediaFormat, start, end, isHtmlAllowed,\n }: {\n url: string; mediaFormat: ApiMediaFormat; start?: number; end?: number; isHtmlAllowed?: boolean;\n },\n client: TelegramClient,\n isConnected: boolean,\n onProgress?: ApiOnProgress,\n) {\n const {\n data, mimeType, fullSize,\n } = await download(url, client, isConnected, onProgress, start, end, mediaFormat, isHtmlAllowed) || {};\n if (!data) {\n return undefined;\n }\n\n const parsed = await parseMedia(data, mediaFormat, mimeType);\n if (!parsed) {\n return undefined;\n }\n\n const canCache = mediaFormat !== ApiMediaFormat.Progressive && (\n mediaFormat !== ApiMediaFormat.BlobUrl || (parsed as Blob).size <= MEDIA_CACHE_MAX_BYTES\n );\n\n if (!MEDIA_CACHE_DISABLED && cacheApi && canCache) {\n const cacheName = url.startsWith('avatar') ? MEDIA_CACHE_NAME_AVATARS : MEDIA_CACHE_NAME;\n void cacheApi.save(cacheName, url, parsed);\n }\n\n const prepared = mediaFormat === ApiMediaFormat.Progressive ? '' : prepareMedia(parsed);\n const arrayBuffer = mediaFormat === ApiMediaFormat.Progressive ? parsed as ArrayBuffer : undefined;\n\n return {\n prepared,\n arrayBuffer,\n mimeType,\n fullSize,\n };\n}\n\nasync function download(\n url: string,\n client: TelegramClient,\n isConnected: boolean,\n onProgress?: ApiOnProgress,\n start?: number,\n end?: number,\n mediaFormat?: ApiMediaFormat,\n isHtmlAllowed?: boolean,\n) {\n const mediaMatch = url.startsWith('webDocument')\n ? url.match(/(webDocument):(.+)/)\n : url.match(/(avatar|profile|photo|msg|stickerSet|sticker|wallpaper|gif|file)([-\\d\\w./]+)(?::\\d+)?(\\?size=\\w+)?/);\n if (!mediaMatch) {\n return undefined;\n }\n\n if (mediaMatch[1] === 'file') {\n const response = await fetch(mediaMatch[2]);\n const data = await response.arrayBuffer();\n return { data };\n }\n\n if (!isConnected) {\n return Promise.reject(new Error('ERROR: Client is not connected'));\n }\n\n let entityType: EntityType;\n const entityId: string | number = mediaMatch[2];\n const sizeType = mediaMatch[3] ? mediaMatch[3].replace('?size=', '') : undefined;\n let entity: (\n GramJs.User | GramJs.Chat | GramJs.Channel | GramJs.Photo |\n GramJs.Message | GramJs.MessageService |\n GramJs.Document | GramJs.StickerSet | GramJs.TypeWebDocument | undefined\n );\n\n if (mediaMatch[1] === 'avatar' || mediaMatch[1] === 'profile') {\n entityType = getEntityTypeById(entityId);\n } else {\n entityType = mediaMatch[1] as 'msg' | 'sticker' | 'wallpaper' | 'gif' | 'stickerSet' | 'photo' | 'webDocument';\n }\n\n switch (entityType) {\n case 'channel':\n case 'chat':\n entity = localDb.chats[entityId];\n break;\n case 'user':\n entity = localDb.users[entityId];\n break;\n case 'msg':\n entity = localDb.messages[entityId];\n break;\n case 'sticker':\n case 'gif':\n case 'wallpaper':\n entity = localDb.documents[entityId];\n break;\n case 'photo':\n entity = localDb.photos[entityId];\n break;\n case 'stickerSet':\n entity = localDb.stickerSets[entityId];\n break;\n case 'webDocument':\n entity = localDb.webDocuments[entityId];\n break;\n }\n\n if (!entity) {\n return undefined;\n }\n\n if (MEDIA_ENTITY_TYPES.has(entityType)) {\n if (mediaFormat === ApiMediaFormat.Stream) {\n onProgress!.acceptsBuffer = true;\n }\n\n const data = await client.downloadMedia(entity, {\n sizeType, start, end, progressCallback: onProgress, workers: DOWNLOAD_WORKERS,\n });\n let mimeType;\n let fullSize;\n\n if (entity instanceof GramJs.Message) {\n mimeType = getMessageMediaMimeType(entity, sizeType);\n if (entity.media instanceof GramJs.MessageMediaDocument && entity.media.document instanceof GramJs.Document) {\n fullSize = entity.media.document.size;\n }\n if (entity.media instanceof GramJs.MessageMediaWebPage\n && entity.media.webpage instanceof GramJs.WebPage\n && entity.media.webpage.document instanceof GramJs.Document) {\n fullSize = entity.media.webpage.document.size;\n }\n } else if (entity instanceof GramJs.Photo) {\n mimeType = 'image/jpeg';\n } else if (entityType === 'sticker' && sizeType) {\n mimeType = 'image/webp';\n } else if (entityType === 'webDocument') {\n mimeType = (entity as GramJs.TypeWebDocument).mimeType;\n } else {\n mimeType = (entity as GramJs.Document).mimeType;\n fullSize = (entity as GramJs.Document).size;\n }\n\n // Prevent HTML-in-video attacks\n if (!isHtmlAllowed && mimeType) {\n mimeType = mimeType.replace(/html/gi, '');\n }\n\n return { mimeType, data, fullSize };\n } else if (entityType === 'stickerSet') {\n const data = await client.downloadStickerSetThumb(entity);\n const mimeType = mediaFormat === ApiMediaFormat.Lottie ? 'application/json' : getMimeType(data);\n\n return { mimeType, data };\n } else {\n const data = await client.downloadProfilePhoto(entity, mediaMatch[1] === 'profile');\n const mimeType = getMimeType(data);\n\n return { mimeType, data };\n }\n}\n\nfunction getMessageMediaMimeType(message: GramJs.Message, sizeType?: string) {\n if (!message || !message.media) {\n return undefined;\n }\n\n if (message.media instanceof GramJs.MessageMediaPhoto) {\n return 'image/jpeg';\n }\n\n if (message.media instanceof GramJs.MessageMediaDocument && message.media.document instanceof GramJs.Document) {\n if (sizeType) {\n return message.media.document!.attributes.some((a) => a instanceof GramJs.DocumentAttributeSticker)\n ? 'image/webp'\n : 'image/jpeg';\n }\n\n return message.media.document!.mimeType;\n }\n\n if (message.media instanceof GramJs.MessageMediaWebPage\n && message.media.webpage instanceof GramJs.WebPage\n && message.media.webpage.document instanceof GramJs.Document) {\n return message.media.webpage.document.mimeType;\n }\n\n return undefined;\n}\n\n// eslint-disable-next-line no-async-without-await/no-async-without-await\nasync function parseMedia(\n data: Buffer, mediaFormat: ApiMediaFormat, mimeType?: string,\n): Promise {\n switch (mediaFormat) {\n case ApiMediaFormat.BlobUrl:\n return new Blob([data], { type: mimeType });\n case ApiMediaFormat.Lottie: {\n const json = inflate(data, { to: 'string' });\n return JSON.parse(json);\n }\n case ApiMediaFormat.Progressive: {\n return data.buffer;\n }\n }\n\n return undefined;\n}\n\nfunction prepareMedia(mediaData: ApiParsedMedia): ApiPreparedMedia {\n if (mediaData instanceof Blob) {\n return URL.createObjectURL(mediaData);\n }\n\n return mediaData;\n}\n\nfunction getMimeType(data: Uint8Array, fallbackMimeType = 'image/jpeg') {\n if (data.length < 4) {\n return fallbackMimeType;\n }\n\n let type = fallbackMimeType;\n const signature = data.subarray(0, 4).reduce((result, byte) => result + byte.toString(16), '');\n\n // https://en.wikipedia.org/wiki/List_of_file_signatures\n switch (signature) {\n case '89504e47':\n type = 'image/png';\n break;\n case '47494638':\n type = 'image/gif';\n break;\n case 'ffd8ffe0':\n case 'ffd8ffe1':\n case 'ffd8ffe2':\n case 'ffd8ffe3':\n case 'ffd8ffe8':\n type = 'image/jpeg';\n break;\n case '52494646':\n // In our case only webp is expected\n type = 'image/webp';\n break;\n }\n\n return type;\n}\n","import {\n TelegramClient, sessions, Api as GramJs, connection,\n} from '../../../lib/gramjs';\nimport { Logger as GramJsLogger } from '../../../lib/gramjs/extensions/index';\nimport { TwoFaParams } from '../../../lib/gramjs/client/2fa';\n\nimport {\n ApiInitialArgs,\n ApiMediaFormat,\n ApiOnProgress,\n ApiSessionData,\n OnApiUpdate,\n} from '../../types';\n\nimport {\n DEBUG, DEBUG_GRAMJS, UPLOAD_WORKERS, IS_TEST, APP_VERSION,\n} from '../../../config';\nimport {\n onRequestPhoneNumber, onRequestCode, onRequestPassword, onRequestRegistration,\n onAuthError, onAuthReady, onCurrentUserUpdate, onRequestQrCode,\n} from './auth';\nimport { updater } from '../updater';\nimport { setMessageBuilderCurrentUserId } from '../apiBuilders/messages';\nimport downloadMediaWithClient from './media';\nimport { buildApiUserFromFull } from '../apiBuilders/users';\nimport localDb from '../localDb';\nimport { buildApiPeerId } from '../apiBuilders/peers';\n\nconst DEFAULT_USER_AGENT = 'Unknown UserAgent';\nconst DEFAULT_PLATFORM = 'Unknown platform';\nconst APP_CODE_NAME = 'Z';\n\nGramJsLogger.setLevel(DEBUG_GRAMJS ? 'debug' : 'warn');\n\nconst gramJsUpdateEventBuilder = { build: (update: object) => update };\n\nlet onUpdate: OnApiUpdate;\nlet client: TelegramClient;\nlet isConnected = false;\n\nexport async function init(_onUpdate: OnApiUpdate, initialArgs: ApiInitialArgs) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START INIT API');\n }\n\n onUpdate = _onUpdate;\n\n const {\n userAgent, platform, sessionData, isTest, isMovSupported,\n } = initialArgs;\n const session = new sessions.CallbackSession(sessionData, onSessionUpdate);\n\n // eslint-disable-next-line no-restricted-globals\n (self as any).isMovSupported = isMovSupported;\n\n client = new TelegramClient(\n session,\n process.env.TELEGRAM_T_API_ID,\n process.env.TELEGRAM_T_API_HASH,\n {\n deviceModel: navigator.userAgent || userAgent || DEFAULT_USER_AGENT,\n systemVersion: platform || DEFAULT_PLATFORM,\n appVersion: `${APP_VERSION} ${APP_CODE_NAME}`,\n useWSS: true,\n additionalDcsDisabled: IS_TEST,\n testServers: isTest,\n } as any,\n );\n\n client.addEventHandler(handleGramJsUpdate, gramJsUpdateEventBuilder);\n client.addEventHandler(updater, gramJsUpdateEventBuilder);\n\n try {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[GramJs/client] CONNECTING');\n\n // eslint-disable-next-line no-restricted-globals\n (self as any).invoke = invokeRequest;\n // eslint-disable-next-line no-restricted-globals\n (self as any).GramJs = GramJs;\n }\n\n try {\n await client.start({\n phoneNumber: onRequestPhoneNumber,\n phoneCode: onRequestCode,\n password: onRequestPassword,\n firstAndLastNames: onRequestRegistration,\n qrCode: onRequestQrCode,\n onError: onAuthError,\n initialMethod: platform === 'iOS' || platform === 'Android' ? 'phoneNumber' : 'qrCode',\n });\n } catch (err) {\n // TODO Investigate which request causes this exception\n if (err.message !== 'Disconnect') {\n onUpdate({\n '@type': 'updateConnectionState',\n connectionState: 'connectionStateBroken',\n });\n\n return;\n }\n }\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH INIT API');\n // eslint-disable-next-line no-console\n console.log('[GramJs/client] CONNECTED');\n }\n\n onAuthReady();\n onSessionUpdate(session.getSessionData());\n onUpdate({ '@type': 'updateApiReady' });\n\n void fetchCurrentUser();\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[GramJs/client] CONNECTING ERROR', err);\n }\n\n throw err;\n }\n}\n\nexport async function destroy() {\n await invokeRequest(new GramJs.auth.LogOut());\n await client.destroy();\n}\n\nexport async function disconnect() {\n await client.disconnect();\n}\n\nexport function getClient() {\n return client;\n}\n\nfunction onSessionUpdate(sessionData: ApiSessionData) {\n onUpdate({\n '@type': 'updateSession',\n sessionData,\n });\n}\n\nfunction handleGramJsUpdate(update: any) {\n if (update instanceof connection.UpdateConnectionState) {\n isConnected = update.state === connection.UpdateConnectionState.connected;\n } else if (update instanceof GramJs.UpdatesTooLong) {\n void handleTerminatedSession();\n } else if (update instanceof connection.UpdateServerTimeOffset) {\n onUpdate({\n '@type': 'updateServerTimeOffset',\n serverTimeOffset: update.timeOffset,\n });\n }\n}\n\nexport async function invokeRequest(\n request: T,\n shouldHandleUpdates = false,\n shouldThrow = false,\n): Promise {\n if (!isConnected) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(`[GramJs/client] INVOKE ERROR ${request.className}: Client is not connected`);\n }\n\n return undefined;\n }\n\n try {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log(`[GramJs/client] INVOKE ${request.className}`);\n }\n\n const result = await client.invoke(request);\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log(`[GramJs/client] INVOKE RESPONSE ${request.className}`, result);\n }\n\n if (shouldHandleUpdates) {\n type ResultWithUpdates =\n typeof result\n & { updates?: GramJs.Updates | GramJs.UpdatesCombined };\n\n let updatesContainer;\n if (result instanceof GramJs.Updates || result instanceof GramJs.UpdatesCombined) {\n updatesContainer = result;\n } else if ('updates' in (result as ResultWithUpdates) && (\n (result as ResultWithUpdates).updates instanceof GramJs.Updates\n || (result as ResultWithUpdates).updates instanceof GramJs.UpdatesCombined\n )) {\n updatesContainer = (result as ResultWithUpdates).updates;\n }\n\n if (updatesContainer) {\n injectUpdateEntities(updatesContainer);\n\n updatesContainer.updates.forEach((update) => {\n updater(update, request);\n });\n } else if (result instanceof GramJs.UpdatesTooLong) {\n // TODO Implement\n } else {\n updater(result as GramJs.TypeUpdates, request);\n }\n }\n\n return result;\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log(`[GramJs/client] INVOKE ERROR ${request.className}`);\n // eslint-disable-next-line no-console\n console.error(err);\n }\n\n if (shouldThrow) {\n throw err;\n }\n\n dispatchErrorUpdate(err, request);\n\n return undefined;\n }\n}\n\nexport function downloadMedia(\n args: { url: string; mediaFormat: ApiMediaFormat; start?: number; end?: number; isHtmlAllowed?: boolean },\n onProgress?: ApiOnProgress,\n) {\n return downloadMediaWithClient(args, client, isConnected, onProgress);\n}\n\nexport function uploadFile(file: File, onProgress?: ApiOnProgress) {\n return client.uploadFile({ file, onProgress, workers: UPLOAD_WORKERS });\n}\n\nexport function updateTwoFaSettings(params: TwoFaParams) {\n return client.updateTwoFaSettings(params);\n}\n\nexport async function fetchCurrentUser() {\n const userFull = await invokeRequest(new GramJs.users.GetFullUser({\n id: new GramJs.InputUserSelf(),\n }));\n\n if (!userFull || !(userFull.users[0] instanceof GramJs.User)) {\n return;\n }\n\n const user = userFull.users[0];\n\n localDb.users[buildApiPeerId(user.id, 'user')] = user;\n const currentUser = buildApiUserFromFull(userFull);\n\n setMessageBuilderCurrentUserId(currentUser.id);\n onCurrentUserUpdate(currentUser);\n}\n\nexport function dispatchErrorUpdate(err: Error, request: T) {\n const isSlowMode = err.message.startsWith('A wait of') && (\n request instanceof GramJs.messages.SendMessage\n || request instanceof GramJs.messages.SendMedia\n || request instanceof GramJs.messages.SendMultiMedia\n );\n\n const { message } = err;\n\n onUpdate({\n '@type': 'error',\n error: {\n message,\n isSlowMode,\n hasErrorKey: true,\n },\n });\n}\n\nfunction injectUpdateEntities(result: GramJs.Updates | GramJs.UpdatesCombined) {\n const entities = [...result.users, ...result.chats];\n\n result.updates.forEach((update) => {\n if (entities) {\n // eslint-disable-next-line no-underscore-dangle\n (update as any)._entities = entities;\n }\n });\n}\n\nasync function handleTerminatedSession() {\n try {\n await invokeRequest(new GramJs.users.GetFullUser({\n id: new GramJs.InputUserSelf(),\n }), undefined, true);\n } catch (err) {\n if (err.message === 'AUTH_KEY_UNREGISTERED') {\n onUpdate({\n '@type': 'updateConnectionState',\n connectionState: 'connectionStateBroken',\n });\n }\n }\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport {\n OnApiUpdate,\n ApiChat,\n ApiMessage,\n ApiUser,\n ApiMessageEntity,\n ApiFormattedText,\n ApiChatFullInfo,\n ApiChatFolder,\n ApiChatBannedRights,\n ApiChatAdminRights,\n ApiGroupCall,\n} from '../../types';\n\nimport {\n DEBUG, ARCHIVED_FOLDER_ID, MEMBERS_LOAD_SLICE, SERVICE_NOTIFICATIONS_USER_ID,\n} from '../../../config';\nimport { invokeRequest, uploadFile } from './client';\nimport {\n buildApiChatFromDialog,\n getPeerKey,\n buildChatMembers,\n buildApiChatFromPreview,\n buildApiChatFolder,\n buildApiChatFolderFromSuggested,\n buildApiChatBotCommands,\n} from '../apiBuilders/chats';\nimport { buildApiMessage, buildMessageDraft } from '../apiBuilders/messages';\nimport { buildApiUser, buildApiUsersAndStatuses } from '../apiBuilders/users';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport {\n buildInputEntity,\n buildInputPeer,\n buildMtpMessageEntity,\n buildFilterFromApiFolder,\n isMessageWithMedia,\n buildChatBannedRights,\n buildChatAdminRights,\n} from '../gramjsBuilders';\nimport { addEntitiesWithPhotosToLocalDb, addMessageToLocalDb, addPhotoToLocalDb } from '../helpers';\nimport { buildApiPeerId, getApiChatIdFromMtpPeer } from '../apiBuilders/peers';\nimport { buildApiPhoto } from '../apiBuilders/common';\n\nconst MAX_INT_32 = 2 ** 31 - 1;\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function fetchChats({\n limit,\n offsetDate,\n archived,\n withPinned,\n serverTimeOffset,\n lastLocalServiceMessage,\n}: {\n limit: number;\n offsetDate?: number;\n archived?: boolean;\n withPinned?: boolean;\n serverTimeOffset: number;\n lastLocalServiceMessage?: ApiMessage;\n}) {\n const result = await invokeRequest(new GramJs.messages.GetDialogs({\n offsetPeer: new GramJs.InputPeerEmpty(),\n limit,\n offsetDate,\n folderId: archived ? ARCHIVED_FOLDER_ID : undefined,\n ...(withPinned && { excludePinned: true }),\n }));\n const resultPinned = withPinned\n ? await invokeRequest(new GramJs.messages.GetPinnedDialogs({\n folderId: archived ? ARCHIVED_FOLDER_ID : undefined,\n }))\n : undefined;\n\n if (!result || result instanceof GramJs.messages.DialogsNotModified) {\n return undefined;\n }\n\n if (resultPinned) {\n updateLocalDb(resultPinned);\n }\n updateLocalDb(result);\n\n const lastMessagesByChatId = buildCollectionByKey(\n (resultPinned ? resultPinned.messages : []).concat(result.messages)\n .map(buildApiMessage)\n .filter(Boolean as any),\n 'chatId',\n );\n const peersByKey: Record = {\n ...(resultPinned && preparePeers(resultPinned)),\n ...preparePeers(result),\n };\n const chats: ApiChat[] = [];\n const draftsById: Record = {};\n const replyingToById: Record = {};\n\n const dialogs = (resultPinned ? resultPinned.dialogs : []).concat(result.dialogs);\n\n const orderedPinnedIds: string[] = [];\n\n dialogs.forEach((dialog) => {\n if (\n !(dialog instanceof GramJs.Dialog)\n // This request can return dialogs not belonging to specified folder\n || (!archived && dialog.folderId === ARCHIVED_FOLDER_ID)\n || (archived && dialog.folderId !== ARCHIVED_FOLDER_ID)\n ) {\n return;\n }\n\n const peerEntity = peersByKey[getPeerKey(dialog.peer)];\n const chat = buildApiChatFromDialog(dialog, peerEntity, serverTimeOffset);\n\n if (\n chat.id === SERVICE_NOTIFICATIONS_USER_ID\n && lastLocalServiceMessage\n && (!lastMessagesByChatId[chat.id] || lastLocalServiceMessage.date > lastMessagesByChatId[chat.id].date)\n ) {\n chat.lastMessage = lastLocalServiceMessage;\n } else {\n chat.lastMessage = lastMessagesByChatId[chat.id];\n }\n\n chat.isListed = true;\n chats.push(chat);\n\n if (withPinned && dialog.pinned) {\n orderedPinnedIds.push(chat.id);\n }\n\n if (dialog.draft) {\n const { formattedText, replyingToId } = buildMessageDraft(dialog.draft) || {};\n if (formattedText) {\n draftsById[chat.id] = formattedText;\n }\n if (replyingToId) {\n replyingToById[chat.id] = replyingToId;\n }\n }\n });\n\n const chatIds = chats.map((chat) => chat.id);\n\n const { users, userStatusesById } = buildApiUsersAndStatuses((resultPinned?.users || []).concat(result.users));\n\n let totalChatCount: number;\n if (result instanceof GramJs.messages.DialogsSlice) {\n totalChatCount = result.count;\n } else {\n totalChatCount = chatIds.length;\n }\n\n return {\n chatIds,\n chats,\n users,\n userStatusesById,\n draftsById,\n replyingToById,\n orderedPinnedIds: withPinned ? orderedPinnedIds : undefined,\n totalChatCount,\n };\n}\n\nexport function fetchFullChat(chat: ApiChat) {\n const { id, accessHash, adminRights } = chat;\n\n const input = buildInputEntity(id, accessHash);\n\n return input instanceof GramJs.InputChannel\n ? getFullChannelInfo(id, accessHash!, adminRights)\n : getFullChatInfo(id);\n}\n\nexport async function searchChats({ query }: { query: string }) {\n const result = await invokeRequest(new GramJs.contacts.Search({ q: query }));\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const localPeerIds = result.myResults.map(getApiChatIdFromMtpPeer);\n const allChats = result.chats.concat(result.users)\n .map((user) => buildApiChatFromPreview(user))\n .filter(Boolean as any);\n const allUsers = result.users.map(buildApiUser).filter((user) => !!user && !user.isSelf) as ApiUser[];\n\n return {\n localChats: allChats.filter((r) => localPeerIds.includes(r.id)),\n localUsers: allUsers.filter((u) => localPeerIds.includes(u.id)),\n globalChats: allChats.filter((r) => !localPeerIds.includes(r.id)),\n globalUsers: allUsers.filter((u) => !localPeerIds.includes(u.id)),\n };\n}\n\nexport async function fetchChat({\n type, user,\n}: {\n type: 'user' | 'self' | 'support'; user?: ApiUser;\n}) {\n let mtpUser: GramJs.User | undefined;\n\n if (type === 'self' || type === 'user') {\n const result = await invokeRequest(new GramJs.users.GetUsers({\n id: [\n type === 'user' && user\n ? buildInputEntity(user.id, user.accessHash) as GramJs.InputUser\n : new GramJs.InputUserSelf(),\n ],\n }));\n if (!result || !result.length) {\n return undefined;\n }\n\n [mtpUser] = result;\n } else if (type === 'support') {\n const result = await invokeRequest(new GramJs.help.GetSupport());\n if (!result || !result.user) {\n return undefined;\n }\n\n mtpUser = result.user;\n }\n\n const chat = buildApiChatFromPreview(mtpUser!, type === 'support');\n if (!chat) {\n return undefined;\n }\n\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n\n return { chatId: chat.id };\n}\n\nexport async function requestChatUpdate({\n chat,\n serverTimeOffset,\n lastLocalMessage,\n noLastMessage,\n}: {\n chat: ApiChat; serverTimeOffset: number; lastLocalMessage?: ApiMessage; noLastMessage?: boolean;\n}) {\n const { id, accessHash } = chat;\n\n const result = await invokeRequest(new GramJs.messages.GetPeerDialogs({\n peers: [new GramJs.InputDialogPeer({\n peer: buildInputPeer(id, accessHash),\n })],\n }));\n\n if (!result) {\n return;\n }\n\n const dialog = result.dialogs[0];\n if (!dialog || !(dialog instanceof GramJs.Dialog)) {\n return;\n }\n\n const peersByKey = preparePeers(result);\n const peerEntity = peersByKey[getPeerKey(dialog.peer)];\n if (!peerEntity) {\n return;\n }\n\n updateLocalDb(result);\n\n const lastRemoteMessage = buildApiMessage(result.messages[0]);\n const lastMessage = lastLocalMessage && (!lastRemoteMessage || (lastLocalMessage.date > lastRemoteMessage.date))\n ? lastLocalMessage\n : lastRemoteMessage;\n\n onUpdate({\n '@type': 'updateChat',\n id,\n chat: {\n ...buildApiChatFromDialog(dialog, peerEntity, serverTimeOffset),\n ...(!noLastMessage && { lastMessage }),\n },\n });\n}\n\nexport function saveDraft({\n chat,\n text,\n entities,\n replyToMsgId,\n}: {\n chat: ApiChat;\n text: string;\n entities?: ApiMessageEntity[];\n replyToMsgId?: number;\n}) {\n return invokeRequest(new GramJs.messages.SaveDraft({\n peer: buildInputPeer(chat.id, chat.accessHash),\n message: text,\n ...(entities && {\n entities: entities.map(buildMtpMessageEntity),\n }),\n replyToMsgId,\n }));\n}\n\nexport function clearDraft(chat: ApiChat) {\n return invokeRequest(new GramJs.messages.SaveDraft({\n peer: buildInputPeer(chat.id, chat.accessHash),\n message: '',\n }));\n}\n\nasync function getFullChatInfo(chatId: string): Promise<{\n fullInfo: ApiChatFullInfo;\n users?: ApiUser[];\n groupCall?: Partial;\n} | undefined> {\n const result = await invokeRequest(new GramJs.messages.GetFullChat({\n chatId: buildInputEntity(chatId) as BigInt.BigInteger,\n }));\n\n if (!result || !(result.fullChat instanceof GramJs.ChatFull)) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const {\n about,\n participants,\n exportedInvite,\n botInfo,\n call,\n } = result.fullChat;\n\n const members = buildChatMembers(participants);\n const adminMembers = members ? members.filter(({ isAdmin, isOwner }) => isAdmin || isOwner) : undefined;\n const botCommands = botInfo ? buildApiChatBotCommands(botInfo) : undefined;\n\n return {\n fullInfo: {\n about,\n members,\n adminMembers,\n canViewMembers: true,\n botCommands,\n ...(exportedInvite && {\n inviteLink: exportedInvite.link,\n }),\n groupCallId: call?.id.toString(),\n },\n users: result.users.map(buildApiUser).filter(Boolean as any),\n groupCall: call ? {\n chatId,\n isLoaded: false,\n id: call.id.toString(),\n accessHash: call.accessHash.toString(),\n connectionState: 'disconnected',\n participantsCount: 0,\n version: 0,\n participants: {},\n } : undefined,\n };\n}\n\nasync function getFullChannelInfo(\n id: string,\n accessHash: string,\n adminRights?: ApiChatAdminRights,\n): Promise<{\n fullInfo: ApiChatFullInfo;\n users?: ApiUser[];\n groupCall?: Partial;\n } | undefined> {\n const result = await invokeRequest(new GramJs.channels.GetFullChannel({\n channel: buildInputEntity(id, accessHash) as GramJs.InputChannel,\n }));\n\n if (!result || !(result.fullChat instanceof GramJs.ChannelFull)) {\n return undefined;\n }\n\n const {\n about,\n onlineCount,\n exportedInvite,\n slowmodeSeconds,\n slowmodeNextSendDate,\n migratedFromChatId,\n migratedFromMaxId,\n canViewParticipants,\n linkedChatId,\n hiddenPrehistory,\n call,\n botInfo,\n defaultSendAs,\n } = result.fullChat;\n\n const inviteLink = exportedInvite instanceof GramJs.ChatInviteExported\n ? exportedInvite.link\n : undefined;\n\n const { members, users } = (canViewParticipants && await fetchMembers(id, accessHash)) || {};\n const { members: kickedMembers, users: bannedUsers } = (\n canViewParticipants && adminRights && await fetchMembers(id, accessHash, 'kicked')\n ) || {};\n const { members: adminMembers, users: adminUsers } = (\n canViewParticipants && adminRights && await fetchMembers(id, accessHash, 'admin')\n ) || {};\n const botCommands = botInfo ? buildApiChatBotCommands(botInfo) : undefined;\n\n if (result?.chats?.length > 1) {\n updateLocalDb(result);\n\n const [, mtpLinkedChat] = result.chats;\n const chat = buildApiChatFromPreview(mtpLinkedChat, undefined, true);\n if (chat) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n }\n }\n\n return {\n fullInfo: {\n about,\n onlineCount,\n inviteLink,\n slowMode: slowmodeSeconds ? {\n seconds: slowmodeSeconds,\n nextSendDate: slowmodeNextSendDate,\n } : undefined,\n migratedFrom: migratedFromChatId ? {\n chatId: buildApiPeerId(migratedFromChatId, 'chat'),\n maxMessageId: migratedFromMaxId,\n } : undefined,\n canViewMembers: canViewParticipants,\n isPreHistoryHidden: hiddenPrehistory,\n members,\n kickedMembers,\n adminMembers,\n groupCallId: call ? String(call.id) : undefined,\n linkedChatId: linkedChatId ? buildApiPeerId(linkedChatId, 'chat') : undefined,\n botCommands,\n sendAsId: defaultSendAs ? getApiChatIdFromMtpPeer(defaultSendAs) : undefined,\n },\n users: [...(users || []), ...(bannedUsers || []), ...(adminUsers || [])],\n groupCall: call ? {\n chatId: id,\n isLoaded: false,\n id: call.id.toString(),\n accessHash: call?.accessHash.toString(),\n participants: {},\n version: 0,\n participantsCount: 0,\n connectionState: 'disconnected',\n } : undefined,\n };\n}\n\nexport async function updateChatMutedState({\n chat, isMuted, serverTimeOffset,\n}: {\n chat: ApiChat; isMuted: boolean; serverTimeOffset: number;\n}) {\n await invokeRequest(new GramJs.account.UpdateNotifySettings({\n peer: new GramJs.InputNotifyPeer({\n peer: buildInputPeer(chat.id, chat.accessHash),\n }),\n settings: new GramJs.InputPeerNotifySettings({ muteUntil: isMuted ? MAX_INT_32 : 0 }),\n }));\n\n onUpdate({\n '@type': 'updateNotifyExceptions',\n chatId: chat.id,\n isMuted,\n });\n\n void requestChatUpdate({\n chat,\n serverTimeOffset,\n noLastMessage: true,\n });\n}\n\nexport async function createChannel({\n title, about = '', users,\n}: {\n title: string; about?: string; users?: ApiUser[];\n}, noErrorUpdate = false): Promise {\n const result = await invokeRequest(new GramJs.channels.CreateChannel({\n broadcast: true,\n title,\n about,\n }), true);\n\n // `createChannel` can return a lot of different update types according to docs,\n // but currently channel creation returns only `Updates` type.\n // Errors are added to catch unexpected cases in future testing\n if (!(result instanceof GramJs.Updates)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected channel creation update', result);\n }\n return undefined;\n }\n\n const newChannel = result.chats[0];\n if (!newChannel || !(newChannel instanceof GramJs.Channel)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Created channel not found', result);\n }\n return undefined;\n }\n\n const channel = buildApiChatFromPreview(newChannel)!;\n\n if (users?.length) {\n try {\n await invokeRequest(new GramJs.channels.InviteToChannel({\n channel: buildInputEntity(channel.id, channel.accessHash) as GramJs.InputChannel,\n users: users.map(({ id, accessHash }) => buildInputEntity(id, accessHash)) as GramJs.InputUser[],\n }), true, noErrorUpdate);\n } catch (err) {\n // `noErrorUpdate` will cause an exception which we don't want either\n }\n }\n\n return channel;\n}\n\nexport function joinChannel({\n channelId, accessHash,\n}: {\n channelId: string; accessHash: string;\n}) {\n return invokeRequest(new GramJs.channels.JoinChannel({\n channel: buildInputEntity(channelId, accessHash) as GramJs.InputChannel,\n }), true);\n}\n\nexport function deleteChatUser({\n chat, user,\n}: {\n chat: ApiChat; user: ApiUser;\n}) {\n if (chat.type !== 'chatTypeBasicGroup') return undefined;\n return invokeRequest(new GramJs.messages.DeleteChatUser({\n chatId: buildInputEntity(chat.id, chat.accessHash) as BigInt.BigInteger,\n userId: buildInputEntity(user.id, user.accessHash) as GramJs.InputUser,\n }), true);\n}\n\nexport function deleteChat({\n chatId,\n}: {\n chatId: string;\n}) {\n return invokeRequest(new GramJs.messages.DeleteChat({\n chatId: buildInputEntity(chatId) as BigInt.BigInteger,\n }), true);\n}\n\nexport function leaveChannel({\n channelId, accessHash,\n}: {\n channelId: string; accessHash: string;\n}) {\n return invokeRequest(new GramJs.channels.LeaveChannel({\n channel: buildInputEntity(channelId, accessHash) as GramJs.InputChannel,\n }), true);\n}\n\nexport function deleteChannel({\n channelId, accessHash,\n}: {\n channelId: string; accessHash: string;\n}) {\n return invokeRequest(new GramJs.channels.DeleteChannel({\n channel: buildInputEntity(channelId, accessHash) as GramJs.InputChannel,\n }), true);\n}\n\nexport async function createGroupChat({\n title, users,\n}: {\n title: string; users: ApiUser[];\n}): Promise {\n const result = await invokeRequest(new GramJs.messages.CreateChat({\n title,\n users: users.map(({ id, accessHash }) => buildInputEntity(id, accessHash)) as GramJs.InputUser[],\n }), true, true);\n\n // `createChat` can return a lot of different update types according to docs,\n // but currently chat creation returns only `Updates` type.\n // Errors are added to catch unexpected cases in future testing\n if (!(result instanceof GramJs.Updates)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected chat creation update', result);\n }\n return undefined;\n }\n\n const newChat = result.chats[0];\n if (!newChat || !(newChat instanceof GramJs.Chat)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Created chat not found', result);\n }\n return undefined;\n }\n\n return buildApiChatFromPreview(newChat);\n}\n\nexport async function editChatPhoto({\n chatId, accessHash, photo,\n}: {\n chatId: string; accessHash?: string; photo: File;\n}) {\n const uploadedPhoto = await uploadFile(photo);\n const inputEntity = buildInputEntity(chatId, accessHash);\n\n return invokeRequest(\n inputEntity instanceof GramJs.InputChannel\n ? new GramJs.channels.EditPhoto({\n channel: inputEntity as GramJs.InputChannel,\n photo: new GramJs.InputChatUploadedPhoto({\n file: uploadedPhoto,\n }),\n })\n : new GramJs.messages.EditChatPhoto({\n chatId: inputEntity as BigInt.BigInteger,\n photo: new GramJs.InputChatUploadedPhoto({\n file: uploadedPhoto,\n }),\n }),\n true,\n );\n}\n\nexport async function toggleChatPinned({\n chat,\n shouldBePinned,\n}: {\n chat: ApiChat;\n shouldBePinned: boolean;\n}) {\n const { id, accessHash } = chat;\n\n const isActionSuccessful = await invokeRequest(new GramJs.messages.ToggleDialogPin({\n peer: new GramJs.InputDialogPeer({\n peer: buildInputPeer(id, accessHash),\n }),\n pinned: shouldBePinned || undefined,\n }));\n\n if (isActionSuccessful) {\n onUpdate({\n '@type': 'updateChatPinned',\n id: chat.id,\n isPinned: shouldBePinned,\n });\n }\n}\n\nexport function toggleChatArchived({\n chat, folderId,\n}: {\n chat: ApiChat; folderId: number;\n}) {\n const { id, accessHash } = chat;\n\n return invokeRequest(new GramJs.folders.EditPeerFolders({\n folderPeers: [new GramJs.InputFolderPeer({\n peer: buildInputPeer(id, accessHash),\n folderId,\n })],\n }), true);\n}\n\nexport async function fetchChatFolders() {\n const result = await invokeRequest(new GramJs.messages.GetDialogFilters());\n\n if (!result) {\n return undefined;\n }\n\n return {\n byId: buildCollectionByKey(result.map(buildApiChatFolder), 'id') as Record,\n orderedIds: result.map(({ id }) => id),\n };\n}\n\nexport async function fetchRecommendedChatFolders() {\n const results = await invokeRequest(new GramJs.messages.GetSuggestedDialogFilters());\n\n if (!results) {\n return undefined;\n }\n\n return results.map(buildApiChatFolderFromSuggested);\n}\n\nexport async function editChatFolder({\n id,\n folderUpdate,\n}: {\n id: number;\n folderUpdate: ApiChatFolder;\n}) {\n const filter = buildFilterFromApiFolder(folderUpdate);\n\n const isActionSuccessful = await invokeRequest(new GramJs.messages.UpdateDialogFilter({\n id,\n filter,\n }));\n\n if (isActionSuccessful) {\n onUpdate({\n '@type': 'updateChatFolder',\n id,\n folder: folderUpdate,\n });\n }\n}\n\nexport async function deleteChatFolder(id: number) {\n const isActionSuccessful = await invokeRequest(new GramJs.messages.UpdateDialogFilter({\n id,\n filter: undefined,\n }));\n const recommendedChatFolders = await fetchRecommendedChatFolders();\n\n if (isActionSuccessful) {\n onUpdate({\n '@type': 'updateChatFolder',\n id,\n folder: undefined,\n });\n }\n if (recommendedChatFolders) {\n onUpdate({\n '@type': 'updateRecommendedChatFolders',\n folders: recommendedChatFolders,\n });\n }\n}\n\nexport async function toggleDialogUnread({\n chat, hasUnreadMark,\n}: {\n chat: ApiChat; hasUnreadMark: boolean | undefined;\n}) {\n const { id, accessHash } = chat;\n\n const isActionSuccessful = await invokeRequest(new GramJs.messages.MarkDialogUnread({\n peer: new GramJs.InputDialogPeer({\n peer: buildInputPeer(id, accessHash),\n }),\n unread: hasUnreadMark || undefined,\n }));\n\n if (isActionSuccessful) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat: { hasUnreadMark },\n });\n }\n}\n\nexport async function getChatByUsername(username: string) {\n const result = await invokeRequest(new GramJs.contacts.ResolveUsername({\n username,\n }));\n\n if (!result) {\n return undefined;\n }\n\n const { users, chats } = result;\n\n const chat = chats.length\n ? buildApiChatFromPreview(chats[0])\n : buildApiChatFromPreview(users[0]);\n\n if (!chat) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return chat;\n}\n\nexport function togglePreHistoryHidden({\n chat, isEnabled,\n}: { chat: ApiChat; isEnabled: boolean }) {\n const { id, accessHash } = chat;\n const channel = buildInputEntity(id, accessHash);\n\n return invokeRequest(new GramJs.channels.TogglePreHistoryHidden({\n channel: channel as GramJs.InputChannel,\n enabled: isEnabled,\n }), true);\n}\n\nexport function updateChatDefaultBannedRights({\n chat, bannedRights,\n}: { chat: ApiChat; bannedRights: ApiChatBannedRights }) {\n const { id, accessHash } = chat;\n const peer = buildInputPeer(id, accessHash);\n\n return invokeRequest(new GramJs.messages.EditChatDefaultBannedRights({\n peer,\n bannedRights: buildChatBannedRights(bannedRights),\n }), true);\n}\n\nexport function updateChatMemberBannedRights({\n chat, user, bannedRights, untilDate,\n}: { chat: ApiChat; user: ApiUser; bannedRights: ApiChatBannedRights; untilDate?: number }) {\n const channel = buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel;\n const participant = buildInputPeer(user.id, user.accessHash) as GramJs.InputUser;\n\n return invokeRequest(new GramJs.channels.EditBanned({\n channel,\n participant,\n bannedRights: buildChatBannedRights(bannedRights, untilDate),\n }), true);\n}\n\nexport function updateChatAdmin({\n chat, user, adminRights, customTitle = '',\n}: { chat: ApiChat; user: ApiUser; adminRights: ApiChatAdminRights; customTitle: string }) {\n const channel = buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel;\n const userId = buildInputEntity(user.id, user.accessHash) as GramJs.InputUser;\n\n return invokeRequest(new GramJs.channels.EditAdmin({\n channel,\n userId,\n adminRights: buildChatAdminRights(adminRights),\n rank: customTitle,\n }), true);\n}\n\nexport async function updateChatTitle(chat: ApiChat, title: string) {\n const inputEntity = buildInputEntity(chat.id, chat.accessHash);\n await invokeRequest(\n inputEntity instanceof GramJs.InputChannel\n ? new GramJs.channels.EditTitle({\n channel: inputEntity as GramJs.InputChannel,\n title,\n }) : new GramJs.messages.EditChatTitle({\n chatId: inputEntity as BigInt.BigInteger,\n title,\n }),\n true,\n );\n}\n\nexport async function updateChatAbout(chat: ApiChat, about: string) {\n const result = await invokeRequest(new GramJs.messages.EditChatAbout({\n peer: buildInputPeer(chat.id, chat.accessHash),\n about,\n }));\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'updateChatFullInfo',\n id: chat.id,\n fullInfo: {\n about,\n },\n });\n}\n\nexport function toggleSignatures({\n chat, isEnabled,\n}: { chat: ApiChat; isEnabled: boolean }) {\n const { id, accessHash } = chat;\n const channel = buildInputEntity(id, accessHash);\n\n return invokeRequest(new GramJs.channels.ToggleSignatures({\n channel: channel as GramJs.InputChannel,\n enabled: isEnabled,\n }), true);\n}\n\ntype ChannelMembersFilter =\n 'kicked'\n | 'admin'\n | 'recent';\n\nexport async function fetchMembers(\n chatId: string,\n accessHash: string,\n memberFilter: ChannelMembersFilter = 'recent',\n offset?: number,\n) {\n let filter: GramJs.TypeChannelParticipantsFilter;\n\n switch (memberFilter) {\n case 'kicked':\n filter = new GramJs.ChannelParticipantsKicked({ q: '' });\n break;\n case 'admin':\n filter = new GramJs.ChannelParticipantsAdmins();\n break;\n default:\n filter = new GramJs.ChannelParticipantsRecent();\n break;\n }\n\n const result = await invokeRequest(new GramJs.channels.GetParticipants({\n channel: buildInputEntity(chatId, accessHash) as GramJs.InputChannel,\n filter,\n offset,\n limit: MEMBERS_LOAD_SLICE,\n }));\n\n if (!result || result instanceof GramJs.channels.ChannelParticipantsNotModified) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return {\n members: buildChatMembers(result),\n users: result.users.map(buildApiUser).filter(Boolean as any),\n };\n}\n\nexport async function fetchGroupsForDiscussion() {\n const result = await invokeRequest(new GramJs.channels.GetGroupsForDiscussion());\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return result.chats.map((chat) => buildApiChatFromPreview(chat));\n}\n\nexport function setDiscussionGroup({\n channel,\n chat,\n}: {\n channel: ApiChat;\n chat?: ApiChat;\n}) {\n return invokeRequest(new GramJs.channels.SetDiscussionGroup({\n broadcast: buildInputPeer(channel.id, channel.accessHash),\n group: chat ? buildInputPeer(chat.id, chat.accessHash) : new GramJs.InputChannelEmpty(),\n }));\n}\n\nexport async function migrateChat(chat: ApiChat) {\n const result = await invokeRequest(\n new GramJs.messages.MigrateChat({ chatId: buildInputEntity(chat.id) as BigInt.BigInteger }), true,\n );\n\n // `migrateChat` can return a lot of different update types according to docs,\n // but currently chat migrations returns only `Updates` type.\n // Errors are added to catch unexpected cases in future testing\n if (!result || !(result instanceof GramJs.Updates)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected channel creation update', result);\n }\n\n return undefined;\n }\n\n updateLocalDb(result);\n\n return buildApiChatFromPreview(result.chats[1]);\n}\n\nexport async function openChatByInvite(hash: string) {\n const result = await invokeRequest(new GramJs.messages.CheckChatInvite({ hash }));\n\n if (!result) {\n return undefined;\n }\n\n let chat: ApiChat | undefined;\n\n if (result instanceof GramJs.ChatInvite) {\n const {\n photo, participantsCount, title, channel, requestNeeded, about,\n } = result;\n\n if (photo instanceof GramJs.Photo) {\n addPhotoToLocalDb(result.photo);\n }\n\n onUpdate({\n '@type': 'showInvite',\n data: {\n title,\n about,\n hash,\n participantsCount,\n isChannel: channel,\n isRequestNeeded: requestNeeded,\n ...(photo instanceof GramJs.Photo && { photo: buildApiPhoto(photo) }),\n },\n });\n } else {\n chat = buildApiChatFromPreview(result.chat);\n\n if (chat) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n }\n }\n\n if (!chat) {\n return undefined;\n }\n\n return { chatId: chat.id };\n}\n\nexport function addChatMembers(chat: ApiChat, users: ApiUser[], noErrorUpdate = false) {\n try {\n if (chat.type === 'chatTypeChannel' || chat.type === 'chatTypeSuperGroup') {\n return invokeRequest(new GramJs.channels.InviteToChannel({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n users: users.map((user) => buildInputEntity(user.id, user.accessHash)) as GramJs.InputUser[],\n }), true, noErrorUpdate);\n }\n\n return Promise.all(users.map((user) => {\n return invokeRequest(new GramJs.messages.AddChatUser({\n chatId: buildInputEntity(chat.id) as BigInt.BigInteger,\n userId: buildInputEntity(user.id, user.accessHash) as GramJs.InputUser,\n }), true, noErrorUpdate);\n }));\n } catch (err) {\n // `noErrorUpdate` will cause an exception which we don't want either\n return undefined;\n }\n}\n\nexport function deleteChatMember(chat: ApiChat, user: ApiUser) {\n if (chat.type === 'chatTypeChannel' || chat.type === 'chatTypeSuperGroup') {\n return updateChatMemberBannedRights({\n chat,\n user,\n bannedRights: {\n viewMessages: true,\n sendMessages: true,\n sendMedia: true,\n sendStickers: true,\n sendGifs: true,\n sendGames: true,\n sendInline: true,\n embedLinks: true,\n sendPolls: true,\n changeInfo: true,\n inviteUsers: true,\n pinMessages: true,\n },\n untilDate: MAX_INT_32,\n });\n } else {\n return invokeRequest(new GramJs.messages.DeleteChatUser({\n chatId: buildInputEntity(chat.id) as BigInt.BigInteger,\n userId: buildInputEntity(user.id, user.accessHash) as GramJs.InputUser,\n }), true);\n }\n}\n\nfunction preparePeers(\n result: GramJs.messages.Dialogs | GramJs.messages.DialogsSlice | GramJs.messages.PeerDialogs,\n) {\n const store: Record = {};\n\n result.chats.forEach((chat) => {\n store[`chat${chat.id}`] = chat;\n });\n\n result.users.forEach((user) => {\n store[`user${user.id}`] = user;\n });\n\n return store;\n}\n\nfunction updateLocalDb(result: (\n GramJs.messages.Dialogs | GramJs.messages.DialogsSlice | GramJs.messages.PeerDialogs |\n GramJs.messages.ChatFull | GramJs.contacts.Found |\n GramJs.contacts.ResolvedPeer | GramJs.channels.ChannelParticipants |\n GramJs.messages.Chats | GramJs.messages.ChatsSlice | GramJs.TypeUpdates\n)) {\n if ('users' in result) {\n addEntitiesWithPhotosToLocalDb(result.users);\n }\n\n if ('chats' in result) {\n addEntitiesWithPhotosToLocalDb(result.chats);\n }\n\n if ('messages' in result) {\n result.messages.forEach((message) => {\n if (message instanceof GramJs.Message && isMessageWithMedia(message)) {\n addMessageToLocalDb(message);\n }\n });\n }\n}\n\nexport async function importChatInvite({ hash }: { hash: string }) {\n const updates = await invokeRequest(new GramJs.messages.ImportChatInvite({ hash }), true);\n if (!(updates instanceof GramJs.Updates) || !updates.chats.length) {\n return undefined;\n }\n\n return buildApiChatFromPreview(updates.chats[0]);\n}\n\nexport function toggleIsProtected({\n chat, isProtected,\n}: { chat: ApiChat; isProtected: boolean }) {\n const { id, accessHash } = chat;\n\n return invokeRequest(new GramJs.messages.ToggleNoForwards({\n peer: buildInputPeer(id, accessHash),\n enabled: isProtected,\n }), true);\n}\n","import { pause } from './schedulers';\n\n// Polyfill for Safari: `File` is not available in web worker\nif (typeof File === 'undefined') {\n // eslint-disable-next-line no-global-assign, no-restricted-globals, func-names\n self.File = class extends Blob {\n name: string;\n\n constructor(fileBits: BlobPart[], fileName: string, options?: FilePropertyBag) {\n if (options) {\n const { type, ...rest } = options;\n super(fileBits, { type });\n Object.assign(this, rest);\n } else {\n super(fileBits);\n }\n\n this.name = fileName;\n }\n } as typeof File;\n}\n\nexport function dataUriToBlob(dataUri: string) {\n const arr = dataUri.split(',');\n const mime = arr[0].match(/:(.*?);/)![1];\n const bstr = atob(arr[1]);\n let n = bstr.length;\n const u8arr = new Uint8Array(n);\n\n while (n--) {\n u8arr[n] = bstr.charCodeAt(n);\n }\n\n return new Blob([u8arr], { type: mime });\n}\n\nexport function blobToDataUri(blob: Blob): Promise {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n\n reader.onload = (e: ProgressEvent) => {\n const { result } = e.target || {};\n if (typeof result === 'string') {\n resolve(result);\n }\n\n reject(new Error('Failed to read blob'));\n };\n\n reader.onerror = reject;\n reader.readAsDataURL(blob);\n });\n}\n\nexport function blobToFile(blob: Blob, fileName: string) {\n return new File([blob], fileName, {\n lastModified: Date.now(),\n type: blob.type,\n });\n}\n\nexport function preloadImage(url: string): Promise {\n return new Promise((resolve, reject) => {\n const img = new Image();\n img.onload = () => resolve(img);\n img.onerror = reject;\n img.src = url;\n });\n}\n\nexport function preloadVideo(url: string): Promise {\n return new Promise((resolve, reject) => {\n const video = document.createElement('video');\n video.volume = 0;\n video.onloadedmetadata = () => resolve(video);\n video.onerror = reject;\n video.src = url;\n });\n}\n\nexport async function createPosterForVideo(url: string): Promise {\n const video = await preloadVideo(url);\n\n return Promise.race([\n pause(2000) as Promise,\n new Promise((resolve, reject) => {\n video.onseeked = () => {\n if (!video.videoWidth || !video.videoHeight) {\n resolve(undefined);\n }\n\n const canvas = document.createElement('canvas');\n canvas.width = video.videoWidth;\n canvas.height = video.videoHeight;\n const ctx = canvas.getContext('2d')!;\n ctx.drawImage(video, 0, 0);\n resolve(canvas.toDataURL('image/jpeg'));\n };\n video.onerror = reject;\n video.currentTime = Math.min(video.duration, 1);\n }),\n ]);\n}\n\nexport async function fetchBlob(blobUrl: string) {\n const response = await fetch(blobUrl);\n return response.blob();\n}\n\nexport async function fetchFile(blobUrl: string, fileName: string) {\n const blob = await fetchBlob(blobUrl);\n return blobToFile(blob, fileName);\n}\n\nexport function imgToCanvas(img: HTMLImageElement) {\n const canvas = document.createElement('canvas');\n canvas.width = img.width;\n canvas.height = img.height;\n\n const ctx = canvas.getContext('2d')!;\n ctx.drawImage(img, 0, 0);\n\n return canvas;\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n ApiChat,\n ApiAttachment,\n ApiMessage,\n OnApiUpdate,\n ApiMessageSearchType,\n ApiUser,\n ApiSticker,\n ApiVideo,\n ApiNewPoll,\n ApiMessageEntity,\n ApiOnProgress,\n ApiThreadInfo,\n MAIN_THREAD_ID,\n MESSAGE_DELETED,\n ApiGlobalMessageSearchType,\n ApiReportReason,\n ApiSponsoredMessage,\n ApiSendMessageAction,\n ApiContact,\n} from '../../types';\n\nimport {\n ALL_FOLDER_ID,\n DEBUG,\n PINNED_MESSAGES_LIMIT,\n SUPPORTED_IMAGE_CONTENT_TYPES,\n SUPPORTED_VIDEO_CONTENT_TYPES,\n} from '../../../config';\nimport { invokeRequest, uploadFile } from './client';\nimport {\n buildApiMessage,\n buildLocalMessage,\n buildWebPage,\n buildLocalForwardedMessage,\n buildApiSponsoredMessage,\n} from '../apiBuilders/messages';\nimport { buildApiUser } from '../apiBuilders/users';\nimport {\n buildInputEntity,\n buildInputPeer,\n generateRandomBigInt,\n getEntityTypeById,\n buildInputMediaDocument,\n buildInputPoll,\n buildMtpMessageEntity,\n isMessageWithMedia,\n isServiceMessageWithMedia,\n buildInputReportReason,\n buildSendMessageAction,\n} from '../gramjsBuilders';\nimport localDb from '../localDb';\nimport { buildApiChatFromPreview } from '../apiBuilders/chats';\nimport { fetchFile } from '../../../util/files';\nimport {\n addEntitiesWithPhotosToLocalDb,\n addMessageToLocalDb,\n deserializeBytes,\n resolveMessageApiChatId,\n} from '../helpers';\nimport { interpolateArray } from '../../../util/waveform';\nimport { requestChatUpdate } from './chats';\nimport { buildApiPeerId, getApiChatIdFromMtpPeer } from '../apiBuilders/peers';\n\nconst FAST_SEND_TIMEOUT = 1000;\nconst INPUT_WAVEFORM_LENGTH = 63;\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function fetchMessages({\n chat,\n threadId,\n ...pagination\n}: {\n chat: ApiChat;\n threadId?: number;\n offsetId?: number;\n addOffset?: number;\n limit: number;\n}) {\n const RequestClass = threadId === MAIN_THREAD_ID ? GramJs.messages.GetHistory : GramJs.messages.GetReplies;\n let result;\n\n try {\n result = await invokeRequest(new RequestClass({\n peer: buildInputPeer(chat.id, chat.accessHash),\n ...(threadId !== MAIN_THREAD_ID && {\n msgId: threadId,\n }),\n ...pagination,\n }), undefined, true);\n } catch (err) {\n if (err.message === 'CHANNEL_PRIVATE') {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat: {\n isRestricted: true,\n },\n });\n }\n }\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter(Boolean as any);\n const threadInfos = messages.map(({ threadInfo }) => threadInfo).filter(Boolean as any);\n\n return {\n messages,\n users,\n chats,\n threadInfos,\n };\n}\n\nexport async function fetchMessage({ chat, messageId }: { chat: ApiChat; messageId: number }) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n\n let result;\n try {\n result = await invokeRequest(\n isChannel\n ? new GramJs.channels.GetMessages({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n id: [new GramJs.InputMessageID({ id: messageId })],\n })\n : new GramJs.messages.GetMessages({\n id: [new GramJs.InputMessageID({ id: messageId })],\n }),\n undefined,\n true,\n );\n } catch (err) {\n const { message } = err;\n\n // When fetching messages for the bot @replies, there may be situations when the user was banned\n // in the comment group or this group was deleted\n if (message !== 'CHANNEL_PRIVATE') {\n onUpdate({\n '@type': 'error',\n error: {\n message,\n isSlowMode: false,\n hasErrorKey: true,\n },\n });\n }\n }\n\n if (!result || result instanceof GramJs.messages.MessagesNotModified) {\n return undefined;\n }\n\n const mtpMessage = result.messages[0];\n if (!mtpMessage) {\n return undefined;\n }\n\n if (mtpMessage instanceof GramJs.MessageEmpty) {\n return MESSAGE_DELETED;\n }\n\n const message = mtpMessage && buildApiMessage(mtpMessage);\n if (!message) {\n return undefined;\n }\n\n if (mtpMessage instanceof GramJs.Message) {\n addMessageToLocalDb(mtpMessage);\n }\n\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n\n return { message, users };\n}\n\nlet queue = Promise.resolve();\n\nexport function sendMessage(\n {\n chat,\n text,\n entities,\n replyingTo,\n attachment,\n sticker,\n gif,\n poll,\n contact,\n isSilent,\n scheduledAt,\n groupedId,\n noWebPage,\n sendAs,\n serverTimeOffset,\n }: {\n chat: ApiChat;\n text?: string;\n entities?: ApiMessageEntity[];\n replyingTo?: number;\n attachment?: ApiAttachment;\n sticker?: ApiSticker;\n gif?: ApiVideo;\n poll?: ApiNewPoll;\n contact?: ApiContact;\n isSilent?: boolean;\n scheduledAt?: number;\n groupedId?: string;\n noWebPage?: boolean;\n sendAs?: ApiUser | ApiChat;\n serverTimeOffset?: number;\n },\n onProgress?: ApiOnProgress,\n) {\n const localMessage = buildLocalMessage(\n chat, text, entities, replyingTo, attachment, sticker, gif, poll, contact, groupedId, scheduledAt,\n sendAs, serverTimeOffset,\n );\n onUpdate({\n '@type': localMessage.isScheduled ? 'newScheduledMessage' : 'newMessage',\n id: localMessage.id,\n chatId: chat.id,\n message: localMessage,\n });\n\n // This is expected to arrive after `updateMessageSendSucceeded` which replaces the local ID,\n // so in most cases this will be simply ignored\n setTimeout(() => {\n onUpdate({\n '@type': localMessage.isScheduled ? 'updateScheduledMessage' : 'updateMessage',\n id: localMessage.id,\n chatId: chat.id,\n message: {\n sendingState: 'messageSendingStatePending',\n },\n });\n }, FAST_SEND_TIMEOUT);\n\n const randomId = generateRandomBigInt();\n localDb.localMessages[String(randomId)] = localMessage;\n\n if (groupedId) {\n return sendGroupedMedia({\n chat, text, entities, replyingTo, attachment: attachment!, groupedId, isSilent, scheduledAt,\n }, randomId, localMessage, onProgress);\n }\n\n const prevQueue = queue;\n queue = (async () => {\n let media: GramJs.TypeInputMedia | undefined;\n if (attachment) {\n try {\n media = await uploadMedia(localMessage, attachment, onProgress!);\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n\n await prevQueue;\n\n return;\n }\n } else if (sticker) {\n media = buildInputMediaDocument(sticker);\n } else if (gif) {\n media = buildInputMediaDocument(gif);\n } else if (poll) {\n media = buildInputPoll(poll, randomId);\n } else if (contact) {\n media = new GramJs.InputMediaContact({\n phoneNumber: contact.phoneNumber,\n firstName: contact.firstName,\n lastName: contact.lastName,\n vcard: '',\n });\n }\n\n await prevQueue;\n\n const RequestClass = media ? GramJs.messages.SendMedia : GramJs.messages.SendMessage;\n\n await invokeRequest(new RequestClass({\n clearDraft: true,\n message: text || '',\n entities: entities ? entities.map(buildMtpMessageEntity) : undefined,\n peer: buildInputPeer(chat.id, chat.accessHash),\n randomId,\n ...(isSilent && { silent: isSilent }),\n ...(scheduledAt && { scheduleDate: scheduledAt }),\n ...(replyingTo && { replyToMsgId: replyingTo }),\n ...(media && { media }),\n ...(noWebPage && { noWebpage: noWebPage }),\n ...(sendAs && { sendAs: buildInputPeer(sendAs.id, sendAs.accessHash) }),\n }), true);\n })();\n\n return queue;\n}\n\nconst groupedUploads: Record;\n}> = {};\n\nfunction sendGroupedMedia(\n {\n chat,\n text,\n entities,\n replyingTo,\n attachment,\n groupedId,\n isSilent,\n scheduledAt,\n sendAs,\n }: {\n chat: ApiChat;\n text?: string;\n entities?: ApiMessageEntity[];\n replyingTo?: number;\n attachment: ApiAttachment;\n groupedId: string;\n isSilent?: boolean;\n scheduledAt?: number;\n sendAs?: ApiUser | ApiChat;\n },\n randomId: GramJs.long,\n localMessage: ApiMessage,\n onProgress?: ApiOnProgress,\n) {\n let groupIndex = -1;\n if (!groupedUploads[groupedId]) {\n groupedUploads[groupedId] = {\n counter: 0,\n singleMediaByIndex: {},\n };\n }\n\n groupIndex = groupedUploads[groupedId].counter++;\n\n const prevQueue = queue;\n queue = (async () => {\n let media;\n try {\n media = await uploadMedia(localMessage, attachment, onProgress!);\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n\n groupedUploads[groupedId].counter--;\n\n await prevQueue;\n\n return;\n }\n\n const inputMedia = await fetchInputMedia(\n buildInputPeer(chat.id, chat.accessHash),\n media as GramJs.InputMediaUploadedPhoto | GramJs.InputMediaUploadedDocument,\n );\n\n await prevQueue;\n\n if (!inputMedia) {\n groupedUploads[groupedId].counter--;\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('Failed to upload grouped media');\n }\n\n return;\n }\n\n groupedUploads[groupedId].singleMediaByIndex[groupIndex] = new GramJs.InputSingleMedia({\n media: inputMedia,\n randomId,\n message: text || '',\n entities: entities ? entities.map(buildMtpMessageEntity) : undefined,\n });\n\n if (Object.keys(groupedUploads[groupedId].singleMediaByIndex).length < groupedUploads[groupedId].counter) {\n return;\n }\n\n const { singleMediaByIndex } = groupedUploads[groupedId];\n delete groupedUploads[groupedId];\n\n await invokeRequest(new GramJs.messages.SendMultiMedia({\n clearDraft: true,\n peer: buildInputPeer(chat.id, chat.accessHash),\n multiMedia: Object.values(singleMediaByIndex), // Object keys are usually ordered\n replyToMsgId: replyingTo,\n ...(isSilent && { silent: isSilent }),\n ...(scheduledAt && { scheduleDate: scheduledAt }),\n ...(sendAs && { sendAs: buildInputPeer(sendAs.id, sendAs.accessHash) }),\n }), true);\n })();\n\n return queue;\n}\n\nasync function fetchInputMedia(\n peer: GramJs.TypeInputPeer,\n uploadedMedia: GramJs.InputMediaUploadedPhoto | GramJs.InputMediaUploadedDocument,\n) {\n const messageMedia = await invokeRequest(new GramJs.messages.UploadMedia({\n peer,\n media: uploadedMedia,\n }));\n\n if ((\n messageMedia instanceof GramJs.MessageMediaPhoto\n && messageMedia.photo\n && messageMedia.photo instanceof GramJs.Photo)\n ) {\n const { photo: { id, accessHash, fileReference } } = messageMedia;\n\n return new GramJs.InputMediaPhoto({\n id: new GramJs.InputPhoto({ id, accessHash, fileReference }),\n });\n }\n\n if ((\n messageMedia instanceof GramJs.MessageMediaDocument\n && messageMedia.document\n && messageMedia.document instanceof GramJs.Document)\n ) {\n const { document: { id, accessHash, fileReference } } = messageMedia;\n\n return new GramJs.InputMediaDocument({\n id: new GramJs.InputDocument({ id, accessHash, fileReference }),\n });\n }\n\n return undefined;\n}\n\nexport async function editMessage({\n chat,\n message,\n text,\n entities,\n noWebPage,\n serverTimeOffset,\n}: {\n chat: ApiChat;\n message: ApiMessage;\n text: string;\n entities?: ApiMessageEntity[];\n noWebPage?: boolean;\n serverTimeOffset: number;\n}) {\n const isScheduled = message.date * 1000 > Date.now() + serverTimeOffset * 1000;\n const messageUpdate: Partial = {\n content: {\n ...message.content,\n ...(text && {\n text: {\n text,\n entities,\n },\n }),\n },\n };\n\n onUpdate({\n '@type': isScheduled ? 'updateScheduledMessage' : 'updateMessage',\n id: message.id,\n chatId: chat.id,\n message: messageUpdate,\n });\n\n // TODO Revise intersecting with scheduled\n localDb.localMessages[message.id] = { ...message, ...messageUpdate };\n\n const mtpEntities = entities && entities.map(buildMtpMessageEntity);\n\n await invokeRequest(new GramJs.messages.EditMessage({\n message: text || '',\n entities: mtpEntities,\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: message.id,\n ...(isScheduled && { scheduleDate: message.date }),\n ...(noWebPage && { noWebpage: noWebPage }),\n }), true);\n}\n\nexport async function rescheduleMessage({\n chat,\n message,\n scheduledAt,\n}: {\n chat: ApiChat;\n message: ApiMessage;\n scheduledAt: number;\n}) {\n await invokeRequest(new GramJs.messages.EditMessage({\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: message.id,\n scheduleDate: scheduledAt,\n }), true);\n}\n\nasync function uploadMedia(localMessage: ApiMessage, attachment: ApiAttachment, onProgress: ApiOnProgress) {\n const {\n filename, blobUrl, mimeType, quick, voice,\n } = attachment;\n\n const file = await fetchFile(blobUrl, filename);\n const patchedOnProgress: ApiOnProgress = (progress) => {\n if (onProgress.isCanceled) {\n patchedOnProgress.isCanceled = true;\n } else {\n onProgress(progress, localMessage.id);\n }\n };\n const inputFile = await uploadFile(file, patchedOnProgress);\n\n const attributes: GramJs.TypeDocumentAttribute[] = [new GramJs.DocumentAttributeFilename({ fileName: filename })];\n if (quick) {\n if (SUPPORTED_IMAGE_CONTENT_TYPES.has(mimeType)) {\n return new GramJs.InputMediaUploadedPhoto({ file: inputFile });\n }\n\n if (SUPPORTED_VIDEO_CONTENT_TYPES.has(mimeType)) {\n const { width, height, duration } = quick;\n if (duration !== undefined) {\n attributes.push(new GramJs.DocumentAttributeVideo({\n duration,\n w: width,\n h: height,\n supportsStreaming: true,\n }));\n }\n }\n }\n\n if (voice) {\n const { duration, waveform } = voice;\n const { data: inputWaveform } = interpolateArray(waveform, INPUT_WAVEFORM_LENGTH);\n attributes.push(new GramJs.DocumentAttributeAudio({\n voice: true,\n duration,\n waveform: Buffer.from(inputWaveform),\n }));\n }\n\n return new GramJs.InputMediaUploadedDocument({\n file: inputFile,\n mimeType,\n attributes,\n });\n}\n\nexport async function pinMessage({\n chat, messageId, isUnpin, isOneSide, isSilent,\n}: { chat: ApiChat; messageId: number; isUnpin: boolean; isOneSide: boolean; isSilent: boolean }) {\n await invokeRequest(new GramJs.messages.UpdatePinnedMessage({\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: messageId,\n ...(isUnpin && { unpin: true }),\n ...(isOneSide && { pmOneside: true }),\n ...(isSilent && { silent: true }),\n }), true);\n}\n\nexport async function unpinAllMessages({ chat }: { chat: ApiChat }) {\n await invokeRequest(new GramJs.messages.UnpinAllMessages({\n peer: buildInputPeer(chat.id, chat.accessHash),\n }), true);\n}\n\nexport async function deleteMessages({\n chat, messageIds, shouldDeleteForAll,\n}: {\n chat: ApiChat; messageIds: number[]; shouldDeleteForAll?: boolean;\n}) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n\n const result = await invokeRequest(\n isChannel\n ? new GramJs.channels.DeleteMessages({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n id: messageIds,\n })\n : new GramJs.messages.DeleteMessages({\n id: messageIds,\n ...(shouldDeleteForAll && { revoke: true }),\n }),\n );\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'deleteMessages',\n ids: messageIds,\n ...(isChannel && { chatId: chat.id }),\n });\n}\n\nexport async function deleteScheduledMessages({\n chat, messageIds,\n}: {\n chat: ApiChat; messageIds: number[];\n}) {\n const result = await invokeRequest(\n new GramJs.messages.DeleteScheduledMessages({\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: messageIds,\n }),\n );\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'deleteScheduledMessages',\n ids: messageIds,\n chatId: chat.id,\n });\n}\n\nexport async function deleteHistory({\n chat, shouldDeleteForAll, maxId,\n}: {\n chat: ApiChat; shouldDeleteForAll?: boolean; maxId?: number;\n}) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n const result = await invokeRequest(\n isChannel\n ? new GramJs.channels.DeleteHistory({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n maxId,\n })\n : new GramJs.messages.DeleteHistory({\n peer: buildInputPeer(chat.id, chat.accessHash),\n ...(shouldDeleteForAll && { revoke: true }),\n ...(!shouldDeleteForAll && { just_clear: true }),\n maxId,\n }),\n );\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'deleteHistory',\n chatId: chat.id,\n });\n}\n\nexport async function reportMessages({\n peer, messageIds, reason, description,\n}: {\n peer: ApiChat | ApiUser; messageIds: number[]; reason: ApiReportReason; description?: string;\n}) {\n const result = await invokeRequest(new GramJs.messages.Report({\n peer: buildInputPeer(peer.id, peer.accessHash),\n id: messageIds,\n reason: buildInputReportReason(reason),\n message: description,\n }));\n\n return result;\n}\n\nexport async function sendMessageAction({\n peer, threadId, action,\n}: {\n peer: ApiChat | ApiUser; threadId?: number; action: ApiSendMessageAction;\n}) {\n const gramAction = buildSendMessageAction(action);\n if (!gramAction) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('Unsupported message action', action);\n }\n return undefined;\n }\n\n const result = await invokeRequest(new GramJs.messages.SetTyping({\n peer: buildInputPeer(peer.id, peer.accessHash),\n topMsgId: threadId,\n action: gramAction,\n }));\n return result;\n}\n\nexport async function markMessageListRead({\n chat, threadId, maxId, serverTimeOffset,\n}: {\n chat: ApiChat; threadId: number; maxId?: number; serverTimeOffset: number;\n}) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n\n if (isChannel && threadId === MAIN_THREAD_ID) {\n await invokeRequest(new GramJs.channels.ReadHistory({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n maxId,\n }));\n } else if (isChannel) {\n await invokeRequest(new GramJs.messages.ReadDiscussion({\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: threadId,\n readMaxId: maxId,\n }));\n } else {\n await invokeRequest(new GramJs.messages.ReadHistory({\n peer: buildInputPeer(chat.id, chat.accessHash),\n maxId,\n }));\n }\n\n if (threadId === MAIN_THREAD_ID) {\n void requestChatUpdate({ chat, serverTimeOffset, noLastMessage: true });\n } else {\n void requestThreadInfoUpdate({ chat, threadId });\n }\n}\n\nexport async function markMessagesRead({\n chat, messageIds,\n}: {\n chat: ApiChat; messageIds: number[];\n}) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n\n await invokeRequest(\n isChannel\n ? new GramJs.channels.ReadMessageContents({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n id: messageIds,\n })\n : new GramJs.messages.ReadMessageContents({\n id: messageIds,\n }),\n );\n\n onUpdate({\n ...(isChannel ? {\n '@type': 'updateChannelMessages',\n channelId: chat.id,\n } : {\n '@type': 'updateCommonBoxMessages',\n }),\n ids: messageIds,\n messageUpdate: {\n hasUnreadMention: false,\n isMediaUnread: false,\n },\n });\n}\n\nexport async function requestThreadInfoUpdate({\n chat, threadId,\n}: {\n chat: ApiChat; threadId: number;\n}) {\n const [topMessageResult, repliesResult] = await Promise.all([\n invokeRequest(new GramJs.messages.GetDiscussionMessage({\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: threadId,\n })),\n invokeRequest(new GramJs.messages.GetReplies({\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: threadId,\n offsetId: 1,\n addOffset: -1,\n limit: 1,\n })),\n ]);\n\n if (!topMessageResult || !topMessageResult.messages.length) {\n return undefined;\n }\n\n const discussionChatId = resolveMessageApiChatId(topMessageResult.messages[0]);\n if (!discussionChatId) {\n return undefined;\n }\n\n onUpdate({\n '@type': 'updateThreadInfo',\n chatId: discussionChatId,\n threadId,\n threadInfo: {\n threadId,\n topMessageId: topMessageResult.messages[topMessageResult.messages.length - 1].id,\n lastReadInboxMessageId: topMessageResult.readInboxMaxId,\n messagesCount: (repliesResult instanceof GramJs.messages.ChannelMessages) ? repliesResult.count : undefined,\n },\n firstMessageId: repliesResult && 'messages' in repliesResult && repliesResult.messages.length\n ? repliesResult.messages[0].id\n : undefined,\n });\n\n const chats = topMessageResult.chats.map((c) => buildApiChatFromPreview(c)).filter(Boolean as any);\n chats.forEach((newChat) => {\n onUpdate({\n '@type': 'updateChat',\n id: newChat.id,\n chat: newChat,\n noTopChatsRequest: true,\n });\n });\n\n return {\n discussionChatId,\n };\n}\n\nexport async function searchMessagesLocal({\n chatOrUser, type, query, topMessageId, minDate, maxDate, ...pagination\n}: {\n chatOrUser: ApiChat | ApiUser;\n type?: ApiMessageSearchType | ApiGlobalMessageSearchType;\n query?: string;\n topMessageId?: number;\n offsetId?: number;\n addOffset?: number;\n limit: number;\n minDate?: number;\n maxDate?: number;\n}) {\n let filter;\n switch (type) {\n case 'media':\n filter = new GramJs.InputMessagesFilterPhotoVideo();\n break;\n case 'documents':\n filter = new GramJs.InputMessagesFilterDocument();\n break;\n case 'links':\n filter = new GramJs.InputMessagesFilterUrl();\n break;\n case 'audio':\n filter = new GramJs.InputMessagesFilterMusic();\n break;\n case 'voice':\n filter = new GramJs.InputMessagesFilterRoundVoice();\n break;\n case 'profilePhoto':\n filter = new GramJs.InputMessagesFilterChatPhotos();\n break;\n case 'text':\n default: {\n filter = new GramJs.InputMessagesFilterEmpty();\n }\n }\n\n const result = await invokeRequest(new GramJs.messages.Search({\n peer: buildInputPeer(chatOrUser.id, chatOrUser.accessHash),\n filter,\n q: query || '',\n topMsgId: topMessageId,\n minDate,\n maxDate,\n ...pagination,\n }));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n\n let totalCount = messages.length;\n let nextOffsetId: number | undefined;\n if (result instanceof GramJs.messages.MessagesSlice || result instanceof GramJs.messages.ChannelMessages) {\n totalCount = result.count;\n\n if (messages.length) {\n nextOffsetId = messages[messages.length - 1].id;\n }\n }\n\n return {\n messages,\n users,\n totalCount,\n nextOffsetId,\n };\n}\n\nexport async function searchMessagesGlobal({\n query, offsetRate = 0, limit, type = 'text', minDate, maxDate,\n}: {\n query: string;\n offsetRate?: number;\n limit: number;\n type?: ApiGlobalMessageSearchType;\n minDate?: number;\n maxDate?: number;\n}) {\n let filter;\n switch (type) {\n case 'media':\n filter = new GramJs.InputMessagesFilterPhotoVideo();\n break;\n case 'documents':\n filter = new GramJs.InputMessagesFilterDocument();\n break;\n case 'links':\n filter = new GramJs.InputMessagesFilterUrl();\n break;\n case 'audio':\n filter = new GramJs.InputMessagesFilterMusic();\n break;\n case 'voice':\n filter = new GramJs.InputMessagesFilterRoundVoice();\n break;\n case 'text':\n default: {\n if (!query && !(maxDate && minDate)) {\n return undefined;\n }\n\n filter = new GramJs.InputMessagesFilterEmpty();\n }\n }\n\n const result = await invokeRequest(new GramJs.messages.SearchGlobal({\n q: query,\n offsetRate,\n offsetPeer: new GramJs.InputPeerEmpty(),\n limit,\n filter,\n folderId: ALL_FOLDER_ID,\n minDate,\n maxDate,\n }));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb({\n chats: result.chats,\n users: result.users,\n messages: result.messages,\n } as GramJs.messages.Messages);\n\n const chats = result.chats.map((user) => buildApiChatFromPreview(user)).filter(Boolean as any);\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n\n let totalCount = messages.length;\n let nextRate: number | undefined;\n if (result instanceof GramJs.messages.MessagesSlice || result instanceof GramJs.messages.ChannelMessages) {\n totalCount = result.count;\n\n if (messages.length) {\n nextRate = messages[messages.length - 1].id;\n }\n }\n\n return {\n messages,\n users,\n chats,\n totalCount,\n nextRate: 'nextRate' in result && result.nextRate ? result.nextRate : nextRate,\n };\n}\n\nexport async function fetchWebPagePreview({ message }: { message: string }) {\n const preview = await invokeRequest(new GramJs.messages.GetWebPagePreview({\n message,\n }));\n\n return preview && buildWebPage(preview);\n}\n\nexport async function sendPollVote({\n chat, messageId, options,\n}: {\n chat: ApiChat;\n messageId: number;\n options: string[];\n}) {\n const { id, accessHash } = chat;\n\n await invokeRequest(new GramJs.messages.SendVote({\n peer: buildInputPeer(id, accessHash),\n msgId: messageId,\n options: options.map(deserializeBytes),\n }), true);\n}\n\nexport async function loadPollOptionResults({\n chat, messageId, option, offset, limit, shouldResetVoters,\n}: {\n chat: ApiChat;\n messageId: number;\n option?: string;\n offset?: string;\n limit?: number;\n shouldResetVoters?: boolean;\n}) {\n const { id, accessHash } = chat;\n\n const result = await invokeRequest(new GramJs.messages.GetPollVotes({\n peer: buildInputPeer(id, accessHash),\n id: messageId,\n ...(option && { option: deserializeBytes(option) }),\n ...(offset && { offset }),\n ...(limit && { limit }),\n }));\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb({\n chats: [] as GramJs.TypeChat[],\n users: result.users,\n messages: [] as GramJs.Message[],\n } as GramJs.messages.Messages);\n\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const votes = result.votes.map((vote) => ({\n userId: vote.userId,\n date: vote.date,\n }));\n\n return {\n count: result.count,\n votes,\n users,\n nextOffset: result.nextOffset,\n shouldResetVoters,\n };\n}\n\nexport async function forwardMessages({\n fromChat,\n toChat,\n messages,\n serverTimeOffset,\n isSilent,\n scheduledAt,\n sendAs,\n}: {\n fromChat: ApiChat;\n toChat: ApiChat;\n messages: ApiMessage[];\n serverTimeOffset: number;\n isSilent?: boolean;\n scheduledAt?: number;\n sendAs?: ApiUser | ApiChat;\n}) {\n const messageIds = messages.map(({ id }) => id);\n const randomIds = messages.map(generateRandomBigInt);\n\n messages.forEach((message, index) => {\n const localMessage = buildLocalForwardedMessage(toChat, message, serverTimeOffset, scheduledAt);\n localDb.localMessages[String(randomIds[index])] = localMessage;\n\n onUpdate({\n '@type': localMessage.isScheduled ? 'newScheduledMessage' : 'newMessage',\n id: localMessage.id,\n chatId: toChat.id,\n message: localMessage,\n });\n });\n\n await invokeRequest(new GramJs.messages.ForwardMessages({\n fromPeer: buildInputPeer(fromChat.id, fromChat.accessHash),\n toPeer: buildInputPeer(toChat.id, toChat.accessHash),\n randomId: randomIds,\n id: messageIds,\n ...(isSilent && { sil2ent: isSilent }),\n ...(scheduledAt && { scheduleDate: scheduledAt }),\n ...(sendAs && { sendAs: buildInputPeer(sendAs.id, sendAs.accessHash) }),\n }), true);\n}\n\nexport async function findFirstMessageIdAfterDate({\n chat,\n timestamp,\n}: {\n chat: ApiChat;\n timestamp: number;\n}) {\n const result = await invokeRequest(new GramJs.messages.GetHistory({\n peer: buildInputPeer(chat.id, chat.accessHash),\n offsetDate: timestamp,\n addOffset: -1,\n limit: 1,\n }));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages || !result.messages.length\n ) {\n return undefined;\n }\n\n return result.messages[0].id;\n}\n\nexport async function fetchScheduledHistory({ chat }: { chat: ApiChat }) {\n const { id, accessHash } = chat;\n\n const result = await invokeRequest(new GramJs.messages.GetScheduledHistory({\n peer: buildInputPeer(id, accessHash),\n }));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n\n return {\n messages,\n };\n}\n\nexport async function sendScheduledMessages({ chat, ids }: { chat: ApiChat; ids: number[] }) {\n const { id, accessHash } = chat;\n\n await invokeRequest(new GramJs.messages.SendScheduledMessages({\n peer: buildInputPeer(id, accessHash),\n id: ids,\n }), true);\n}\n\nfunction updateLocalDb(result: (\n GramJs.messages.MessagesSlice | GramJs.messages.Messages | GramJs.messages.ChannelMessages |\n GramJs.messages.DiscussionMessage | GramJs.messages.SponsoredMessages\n)) {\n result.users.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[buildApiPeerId(user.id, 'user')] = user;\n }\n });\n\n result.chats.forEach((chat) => {\n if (chat instanceof GramJs.Chat || chat instanceof GramJs.Channel) {\n localDb.chats[buildApiPeerId(chat.id, chat instanceof GramJs.Chat ? 'chat' : 'channel')] = chat;\n }\n });\n\n result.messages.forEach((message) => {\n if ((message instanceof GramJs.Message && isMessageWithMedia(message))\n || (message instanceof GramJs.MessageService && isServiceMessageWithMedia(message))\n ) {\n addMessageToLocalDb(message);\n }\n });\n}\n\nexport async function fetchPinnedMessages({ chat }: { chat: ApiChat }) {\n const result = await invokeRequest(new GramJs.messages.Search(\n {\n peer: buildInputPeer(chat.id, chat.accessHash),\n filter: new GramJs.InputMessagesFilterPinned(),\n q: '',\n limit: PINNED_MESSAGES_LIMIT,\n },\n ));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter(Boolean as any);\n\n return {\n messages,\n users,\n chats,\n };\n}\n\nexport async function fetchSeenBy({ chat, messageId }: { chat: ApiChat; messageId: number }) {\n const result = await invokeRequest(new GramJs.messages.GetMessageReadParticipants({\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: messageId,\n }));\n\n return result ? result.map(String) : undefined;\n}\n\nexport async function fetchSendAs({\n chat,\n}: {\n chat: ApiChat;\n}) {\n const result = await invokeRequest(new GramJs.channels.GetSendAs({\n peer: buildInputPeer(chat.id, chat.accessHash),\n }));\n\n if (!result) {\n return undefined;\n }\n\n addEntitiesWithPhotosToLocalDb(result.users);\n addEntitiesWithPhotosToLocalDb(result.chats);\n\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter(Boolean as any);\n\n return {\n users,\n chats,\n ids: result.peers.map(getApiChatIdFromMtpPeer),\n };\n}\n\nexport function saveDefaultSendAs({\n sendAs, chat,\n}: {\n sendAs: ApiChat | ApiUser; chat: ApiChat;\n}) {\n return invokeRequest(new GramJs.messages.SaveDefaultSendAs({\n peer: buildInputPeer(chat.id, chat.accessHash),\n sendAs: buildInputPeer(sendAs.id, sendAs.accessHash),\n }));\n}\n\nexport async function fetchSponsoredMessages({ chat }: { chat: ApiChat }) {\n const result = await invokeRequest(new GramJs.channels.GetSponsoredMessages({\n channel: buildInputPeer(chat.id, chat.accessHash),\n }));\n\n if (!result || !result.messages.length) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiSponsoredMessage).filter(Boolean as any);\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter(Boolean as any);\n\n return {\n messages,\n users,\n chats,\n };\n}\n\nexport async function viewSponsoredMessage({ chat, random }: { chat: ApiChat; random: string }) {\n await invokeRequest(new GramJs.channels.ViewSponsoredMessage({\n channel: buildInputPeer(chat.id, chat.accessHash),\n randomId: deserializeBytes(random),\n }));\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport {\n OnApiUpdate, ApiUser, ApiChat, ApiPhoto,\n} from '../../types';\n\nimport { COMMON_CHATS_LIMIT, PROFILE_PHOTOS_LIMIT } from '../../../config';\nimport { invokeRequest } from './client';\nimport { searchMessagesLocal } from './messages';\nimport {\n buildInputEntity,\n buildInputPeer,\n buildInputContact,\n buildMtpPeerId,\n getEntityTypeById,\n} from '../gramjsBuilders';\nimport { buildApiUser, buildApiUserFromFull, buildApiUsersAndStatuses } from '../apiBuilders/users';\nimport { buildApiChatFromPreview } from '../apiBuilders/chats';\nimport { buildApiPhoto } from '../apiBuilders/common';\nimport localDb from '../localDb';\nimport { addEntitiesWithPhotosToLocalDb, addPhotoToLocalDb } from '../helpers';\nimport { buildApiPeerId } from '../apiBuilders/peers';\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function fetchFullUser({\n id,\n accessHash,\n}: {\n id: string;\n accessHash?: string;\n}) {\n const input = buildInputEntity(id, accessHash);\n if (!(input instanceof GramJs.InputUser)) {\n return;\n }\n\n const fullInfo = await invokeRequest(new GramJs.users.GetFullUser({ id: input }));\n\n if (!fullInfo) {\n return;\n }\n\n const userWithFullInfo = buildApiUserFromFull(fullInfo);\n\n onUpdate({\n '@type': 'updateUser',\n id,\n user: {\n fullInfo: userWithFullInfo.fullInfo,\n },\n });\n}\n\nexport async function fetchCommonChats(id: string, accessHash?: string, maxId?: string) {\n const commonChats = await invokeRequest(new GramJs.messages.GetCommonChats({\n userId: buildInputEntity(id, accessHash) as GramJs.InputUser,\n maxId: maxId ? buildMtpPeerId(maxId, getEntityTypeById(maxId)) : undefined,\n limit: COMMON_CHATS_LIMIT,\n }));\n\n if (!commonChats) {\n return undefined;\n }\n\n updateLocalDb(commonChats);\n\n const chatIds: string[] = [];\n const chats: ApiChat[] = [];\n\n commonChats.chats.forEach((mtpChat) => {\n const chat = buildApiChatFromPreview(mtpChat);\n\n if (chat) {\n chats.push(chat);\n chatIds.push(chat.id);\n }\n });\n\n return { chats, chatIds, isFullyLoaded: chatIds.length < COMMON_CHATS_LIMIT };\n}\n\nexport async function fetchNearestCountry() {\n const dcInfo = await invokeRequest(new GramJs.help.GetNearestDc());\n\n return dcInfo?.country;\n}\n\nexport async function fetchTopUsers() {\n const topPeers = await invokeRequest(new GramJs.contacts.GetTopPeers({\n correspondents: true,\n }));\n if (!(topPeers instanceof GramJs.contacts.TopPeers)) {\n return undefined;\n }\n\n const users = topPeers.users.map(buildApiUser).filter((user) => !!user && !user.isSelf) as ApiUser[];\n const ids = users.map(({ id }) => id);\n\n return {\n ids,\n users,\n };\n}\n\nexport async function fetchContactList() {\n const result = await invokeRequest(new GramJs.contacts.GetContacts({ hash: BigInt('0') }));\n if (!result || result instanceof GramJs.contacts.ContactsNotModified) {\n return undefined;\n }\n\n result.users.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[buildApiPeerId(user.id, 'user')] = user;\n }\n });\n\n return {\n users: result.users.map(buildApiUser).filter(Boolean as any),\n chats: result.users.map((user) => buildApiChatFromPreview(user)).filter(Boolean as any),\n };\n}\n\nexport async function fetchUsers({ users }: { users: ApiUser[] }) {\n const result = await invokeRequest(new GramJs.users.GetUsers({\n id: users.map(({ id, accessHash }) => buildInputPeer(id, accessHash)),\n }));\n if (!result || !result.length) {\n return undefined;\n }\n\n result.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[buildApiPeerId(user.id, 'user')] = user;\n }\n });\n\n return buildApiUsersAndStatuses(result);\n}\n\nexport function updateContact({\n phone,\n firstName,\n lastName,\n}: {\n phone?: string;\n firstName?: string;\n lastName?: string;\n}) {\n return invokeRequest(new GramJs.contacts.ImportContacts({\n contacts: [buildInputContact({\n phone: phone || '',\n firstName: firstName || '',\n lastName: lastName || '',\n })],\n }));\n}\n\nexport function addContact({\n id,\n accessHash,\n phoneNumber = '',\n firstName = '',\n lastName = '',\n}: {\n id: string;\n accessHash?: string;\n phoneNumber?: string;\n firstName?: string;\n lastName?: string;\n}) {\n return invokeRequest(new GramJs.contacts.AddContact({\n id: buildInputEntity(id, accessHash) as GramJs.InputUser,\n firstName,\n lastName,\n phone: phoneNumber,\n }), true);\n}\n\nexport async function deleteContact({\n id,\n accessHash,\n}: {\n id: string;\n accessHash?: string;\n}) {\n const input = buildInputEntity(id, accessHash);\n if (!(input instanceof GramJs.InputUser)) {\n return;\n }\n\n const result = await invokeRequest(new GramJs.contacts.DeleteContacts({ id: [input] }));\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'deleteContact',\n id,\n });\n}\n\nexport async function fetchProfilePhotos(user?: ApiUser, chat?: ApiChat) {\n if (user) {\n const { id, accessHash } = user;\n\n const result = await invokeRequest(new GramJs.photos.GetUserPhotos({\n userId: buildInputEntity(id, accessHash) as GramJs.InputUser,\n limit: PROFILE_PHOTOS_LIMIT,\n offset: 0,\n maxId: BigInt('0'),\n }));\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return {\n photos: result.photos\n .filter((photo): photo is GramJs.Photo => photo instanceof GramJs.Photo)\n .map(buildApiPhoto),\n };\n }\n\n const result = await searchMessagesLocal({\n chatOrUser: chat!,\n type: 'profilePhoto',\n limit: PROFILE_PHOTOS_LIMIT,\n });\n\n if (!result) {\n return undefined;\n }\n\n const { messages, users } = result;\n\n return {\n photos: messages.map((message) => message.content.action!.photo).filter(Boolean as any),\n users,\n };\n}\n\nfunction updateLocalDb(result: (GramJs.photos.Photos | GramJs.photos.PhotosSlice | GramJs.messages.Chats)) {\n if ('chats' in result) {\n addEntitiesWithPhotosToLocalDb(result.chats);\n }\n\n if ('photos' in result) {\n result.photos.forEach(addPhotoToLocalDb);\n }\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport { ApiSticker, ApiVideo, OnApiUpdate } from '../../types';\n\nimport { invokeRequest } from './client';\nimport { buildStickerFromDocument, buildStickerSet, buildStickerSetCovered } from '../apiBuilders/symbols';\nimport { buildInputStickerSet, buildInputDocument, buildInputStickerSetShortName } from '../gramjsBuilders';\nimport { buildVideoFromDocument } from '../apiBuilders/messages';\nimport { RECENT_STICKERS_LIMIT } from '../../../config';\n\nimport localDb from '../localDb';\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function fetchStickerSets({ hash = '0' }: { hash?: string }) {\n const allStickers = await invokeRequest(new GramJs.messages.GetAllStickers({ hash: BigInt(hash) }));\n\n if (!allStickers || allStickers instanceof GramJs.messages.AllStickersNotModified) {\n return undefined;\n }\n\n allStickers.sets.forEach((stickerSet) => {\n if (stickerSet.thumbs?.length) {\n localDb.stickerSets[String(stickerSet.id)] = stickerSet;\n }\n });\n\n return {\n hash: String(allStickers.hash),\n sets: allStickers.sets.map(buildStickerSet),\n };\n}\n\nexport async function fetchRecentStickers({ hash = '0' }: { hash?: string }) {\n const result = await invokeRequest(new GramJs.messages.GetRecentStickers({ hash: BigInt(hash) }));\n\n if (!result || result instanceof GramJs.messages.RecentStickersNotModified) {\n return undefined;\n }\n\n return {\n hash: String(result.hash),\n stickers: processStickerResult(result.stickers.slice(0, RECENT_STICKERS_LIMIT)),\n };\n}\n\nexport async function fetchFavoriteStickers({ hash = '0' }: { hash?: string }) {\n const result = await invokeRequest(new GramJs.messages.GetFavedStickers({ hash: BigInt(hash) }));\n\n if (!result || result instanceof GramJs.messages.FavedStickersNotModified) {\n return undefined;\n }\n\n return {\n hash: String(result.hash),\n stickers: processStickerResult(result.stickers),\n };\n}\n\nexport async function fetchFeaturedStickers({ hash = '0' }: { hash?: string }) {\n const result = await invokeRequest(new GramJs.messages.GetFeaturedStickers({ hash: BigInt(hash) }));\n\n if (!result || result instanceof GramJs.messages.FeaturedStickersNotModified) {\n return undefined;\n }\n\n return {\n hash: String(result.hash),\n sets: result.sets.map(buildStickerSetCovered),\n };\n}\n\nexport async function faveSticker({\n sticker,\n unfave,\n}: {\n sticker: ApiSticker;\n unfave?: boolean;\n}) {\n const request = new GramJs.messages.FaveSticker({\n id: buildInputDocument(sticker),\n unfave,\n });\n\n const result = await invokeRequest(request);\n if (result) {\n onUpdate({\n '@type': 'updateFavoriteStickers',\n });\n }\n}\n\nexport async function fetchStickers(\n { stickerSetShortName, stickerSetId, accessHash }:\n { stickerSetShortName?: string; stickerSetId?: string; accessHash: string },\n) {\n const result = await invokeRequest(new GramJs.messages.GetStickerSet({\n stickerset: stickerSetId\n ? buildInputStickerSet(stickerSetId, accessHash)\n : buildInputStickerSetShortName(stickerSetShortName!),\n }));\n\n if (!(result instanceof GramJs.messages.StickerSet)) {\n return undefined;\n }\n\n return {\n set: buildStickerSet(result.set),\n stickers: processStickerResult(result.documents),\n packs: processStickerPackResult(result.packs),\n };\n}\n\nexport async function fetchAnimatedEmojis() {\n const result = await invokeRequest(new GramJs.messages.GetStickerSet({\n stickerset: new GramJs.InputStickerSetAnimatedEmoji(),\n }));\n\n if (!(result instanceof GramJs.messages.StickerSet)) {\n return undefined;\n }\n\n return {\n set: buildStickerSet(result.set),\n stickers: processStickerResult(result.documents),\n };\n}\n\nexport async function searchStickers({ query, hash = '0' }: { query: string; hash?: string }) {\n const result = await invokeRequest(new GramJs.messages.SearchStickerSets({\n q: query,\n hash: BigInt(hash),\n }));\n\n if (!result || result instanceof GramJs.messages.FoundStickerSetsNotModified) {\n return undefined;\n }\n\n return {\n hash: String(result.hash),\n sets: result.sets.map(buildStickerSetCovered),\n };\n}\n\nexport async function fetchSavedGifs({ hash = '0' }: { hash?: string }) {\n const result = await invokeRequest(new GramJs.messages.GetSavedGifs({ hash: BigInt(hash) }));\n\n if (!result || result instanceof GramJs.messages.SavedGifsNotModified) {\n return undefined;\n }\n\n return {\n hash: String(result.hash),\n gifs: processGifResult(result.gifs),\n };\n}\n\nexport async function installStickerSet({ stickerSetId, accessHash }: { stickerSetId: string; accessHash: string }) {\n const result = await invokeRequest(new GramJs.messages.InstallStickerSet({\n stickerset: buildInputStickerSet(stickerSetId, accessHash),\n }));\n\n if (result) {\n onUpdate({\n '@type': 'updateStickerSet',\n id: stickerSetId,\n stickerSet: { installedDate: Date.now() },\n });\n }\n}\n\nexport async function uninstallStickerSet({ stickerSetId, accessHash }: { stickerSetId: string; accessHash: string }) {\n const result = await invokeRequest(new GramJs.messages.UninstallStickerSet({\n stickerset: buildInputStickerSet(stickerSetId, accessHash),\n }));\n\n if (result) {\n onUpdate({\n '@type': 'updateStickerSet',\n id: stickerSetId,\n stickerSet: { installedDate: undefined },\n });\n }\n}\n\nlet inputGifBot: GramJs.InputUser | undefined;\n\nexport async function searchGifs({ query, offset = '' }: { query: string; offset?: string }) {\n if (!inputGifBot) {\n const config = await invokeRequest(new GramJs.help.GetConfig());\n if (!config) {\n return undefined;\n }\n\n const resolvedPeer = await invokeRequest(new GramJs.contacts.ResolveUsername({\n username: config.gifSearchUsername,\n }));\n if (!resolvedPeer || !(resolvedPeer.users[0] instanceof GramJs.User)) {\n return undefined;\n }\n\n inputGifBot = new GramJs.InputUser({\n userId: (resolvedPeer.peer as GramJs.PeerUser).userId,\n accessHash: resolvedPeer.users[0].accessHash!,\n });\n }\n\n const result = await invokeRequest(new GramJs.messages.GetInlineBotResults({\n bot: inputGifBot,\n peer: new GramJs.InputPeerEmpty(),\n query,\n offset,\n }));\n if (!result) {\n return undefined;\n }\n\n const documents = result.results\n .map((foundGif) => {\n if (foundGif instanceof GramJs.BotInlineMediaResult) {\n return foundGif.document;\n }\n\n return undefined;\n })\n .filter(Boolean as any);\n\n return {\n nextOffset: result.nextOffset,\n gifs: processGifResult(documents),\n };\n}\n\nexport async function fetchStickersForEmoji({\n emoji, hash = '0',\n}: { emoji: string; hash?: string }) {\n const result = await invokeRequest(new GramJs.messages.GetStickers({\n emoticon: emoji,\n hash: BigInt(hash),\n }));\n\n if (!result || result instanceof GramJs.messages.StickersNotModified) {\n return undefined;\n }\n\n return {\n stickers: processStickerResult(result.stickers),\n hash: String(result.hash),\n };\n}\n\nexport async function fetchEmojiKeywords({ language, fromVersion }: {\n language: string;\n fromVersion?: number;\n}) {\n const result = await invokeRequest(new GramJs.messages.GetEmojiKeywordsDifference({\n langCode: language,\n fromVersion,\n }));\n\n if (!result) {\n return undefined;\n }\n\n return {\n language: result.langCode,\n version: result.version,\n keywords: result.keywords.reduce((acc, emojiKeyword) => {\n acc[emojiKeyword.keyword] = emojiKeyword.emoticons;\n\n return acc;\n }, {} as Record),\n };\n}\n\nfunction processStickerResult(stickers: GramJs.TypeDocument[]) {\n return stickers\n .map((document) => {\n if (document instanceof GramJs.Document) {\n const sticker = buildStickerFromDocument(document);\n if (sticker) {\n localDb.documents[String(document.id)] = document;\n\n return sticker;\n }\n }\n\n return undefined;\n })\n .filter(Boolean as any);\n}\n\nfunction processStickerPackResult(packs: GramJs.StickerPack[]) {\n return packs.reduce((acc, { emoticon, documents }) => {\n acc[emoticon] = documents.map((documentId) => buildStickerFromDocument(\n localDb.documents[String(documentId)],\n )).filter(Boolean as any);\n return acc;\n }, {} as Record);\n}\n\nfunction processGifResult(gifs: GramJs.TypeDocument[]) {\n return gifs\n .map((document) => {\n if (document instanceof GramJs.Document) {\n const gif = buildVideoFromDocument(document);\n if (gif) {\n localDb.documents[String(document.id)] = document;\n\n return gif;\n }\n }\n\n return undefined;\n })\n .filter(Boolean as any);\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\n\nimport { invokeRequest } from './client';\nimport { buildInputEntity, buildInputPeer } from '../gramjsBuilders';\nimport { ApiChat, OnApiUpdate } from '../../types';\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function checkChatUsername(\n { username }: { username: string },\n) {\n try {\n const result = await invokeRequest(new GramJs.channels.CheckUsername({\n channel: new GramJs.InputChannelEmpty(),\n username,\n }), undefined, true);\n\n return result!;\n } catch (err) {\n return false;\n }\n}\n\nexport async function setChatUsername(\n { chat, username }: { chat: ApiChat; username: string },\n) {\n const result = await invokeRequest(new GramJs.channels.UpdateUsername({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n username,\n }));\n\n if (result) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat: { username },\n });\n }\n}\n\nexport async function updatePrivateLink({\n chat, usageLimit, expireDate,\n}: {\n chat: ApiChat; usageLimit?: number; expireDate?: number;\n}) {\n const result = await invokeRequest(new GramJs.messages.ExportChatInvite({\n peer: buildInputPeer(chat.id, chat.accessHash),\n usageLimit,\n expireDate,\n }));\n\n if (!result) {\n return undefined;\n }\n\n onUpdate({\n '@type': 'updateChatFullInfo',\n id: chat.id,\n fullInfo: {\n inviteLink: result.link,\n },\n });\n\n return result.link;\n}\n","import { Api as GramJs, errors } from '../../../lib/gramjs';\n\nimport { OnApiUpdate } from '../../types';\n\nimport { DEBUG } from '../../../config';\nimport { invokeRequest, updateTwoFaSettings } from './client';\n\nconst ApiErrors: { [k: string]: string } = {\n EMAIL_UNCONFIRMED: 'Email unconfirmed',\n EMAIL_HASH_EXPIRED: 'Email hash expired',\n NEW_SALT_INVALID: 'The new salt is invalid',\n NEW_SETTINGS_INVALID: 'The new password settings are invalid',\n CODE_INVALID: 'Invalid Code',\n PASSWORD_HASH_INVALID: 'Invalid Password',\n};\n\nconst emailCodeController: {\n resolve?: Function;\n reject?: Function;\n} = {};\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function getPasswordInfo() {\n const result = await invokeRequest(new GramJs.account.GetPassword());\n if (!result) {\n return undefined;\n }\n\n const { hint, hasPassword } = result;\n\n return { hint, hasPassword };\n}\n\nfunction onRequestEmailCode(length: number) {\n onUpdate({\n '@type': 'updateTwoFaStateWaitCode',\n length,\n });\n\n return new Promise((resolve, reject) => {\n emailCodeController.resolve = resolve;\n emailCodeController.reject = reject;\n });\n}\n\nexport async function checkPassword(currentPassword: string) {\n try {\n await updateTwoFaSettings({ isCheckPassword: true, currentPassword });\n\n return true;\n } catch (err) {\n onError(err);\n\n return false;\n }\n}\n\nexport async function clearPassword(currentPassword: string) {\n try {\n await updateTwoFaSettings({ currentPassword });\n\n return true;\n } catch (err) {\n onError(err);\n\n return false;\n }\n}\n\nexport async function updatePassword(currentPassword: string, password: string, hint?: string, email?: string) {\n try {\n await updateTwoFaSettings({\n currentPassword,\n newPassword: password,\n hint,\n email,\n emailCodeCallback: onRequestEmailCode,\n onEmailCodeError: onError,\n });\n\n return true;\n } catch (err) {\n onError(err);\n\n return false;\n }\n}\n\nexport async function updateRecoveryEmail(currentPassword: string, email: string) {\n try {\n await updateTwoFaSettings({\n currentPassword,\n newPassword: currentPassword,\n email,\n emailCodeCallback: onRequestEmailCode,\n onEmailCodeError: onError,\n });\n\n return true;\n } catch (err) {\n onError(err);\n\n return false;\n }\n}\n\nexport function provideRecoveryEmailCode(code: string) {\n emailCodeController.resolve!(code);\n}\n\nfunction onError(err: Error) {\n let message: string;\n\n if (err instanceof errors.FloodWaitError) {\n const hours = Math.ceil(Number(err.seconds) / 60 / 60);\n message = `Too many attempts. Try again in ${hours > 1 ? `${hours} hours` : 'an hour'}`;\n } else {\n message = ApiErrors[err.message];\n }\n\n if (!message) {\n message = 'Unexpected Error';\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n }\n\n onUpdate({\n '@type': 'updateTwoFaError',\n message,\n });\n}\n","import { JoinGroupCallPayload } from '../../../lib/secret-sauce';\nimport {\n ApiChat, ApiUser, OnApiUpdate, ApiGroupCall,\n} from '../../types';\nimport { Api as GramJs } from '../../../lib/gramjs';\n\nimport { invokeRequest } from './client';\nimport { buildInputGroupCall, buildInputPeer, generateRandomInt } from '../gramjsBuilders';\nimport {\n buildApiGroupCall,\n buildApiGroupCallParticipant,\n\n} from '../apiBuilders/calls';\nimport { buildApiUser } from '../apiBuilders/users';\nimport { buildApiChatFromPreview } from '../apiBuilders/chats';\nimport { addEntitiesWithPhotosToLocalDb } from '../helpers';\nimport { GROUP_CALL_PARTICIPANTS_LIMIT } from '../../../config';\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function getGroupCall({\n call,\n}: {\n call: Partial;\n}) {\n const result = await invokeRequest(new GramJs.phone.GetGroupCall({\n call: buildInputGroupCall(call),\n }));\n\n if (!result) {\n return undefined;\n }\n\n addEntitiesWithPhotosToLocalDb(result.users);\n addEntitiesWithPhotosToLocalDb(result.chats);\n\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter(Boolean as any);\n\n return {\n groupCall: buildApiGroupCall(result.call),\n users,\n chats,\n };\n}\n\nexport function discardGroupCall({\n call,\n}: {\n call: ApiGroupCall;\n}) {\n return invokeRequest(new GramJs.phone.DiscardGroupCall({\n call: buildInputGroupCall(call),\n }), true);\n}\n\nexport function editGroupCallParticipant({\n call, participant, muted, presentationPaused, videoStopped, videoPaused, volume,\n raiseHand,\n}: {\n call: ApiGroupCall; participant: ApiUser; muted?: boolean; presentationPaused?: boolean;\n videoStopped?: boolean; videoPaused?: boolean; raiseHand?: boolean; volume?: number;\n}) {\n return invokeRequest(new GramJs.phone.EditGroupCallParticipant({\n call: buildInputGroupCall(call),\n participant: buildInputPeer(participant.id, participant.accessHash),\n ...(videoStopped !== undefined && { videoStopped }),\n ...(videoPaused !== undefined && { videoPaused }),\n ...(muted !== undefined && { muted }),\n ...(presentationPaused !== undefined && { presentationPaused }),\n ...(raiseHand !== undefined && { raiseHand }),\n ...(volume !== undefined && { volume }),\n }), true);\n}\n\nexport function editGroupCallTitle({\n groupCall, title,\n}: {\n groupCall: ApiGroupCall; title: string;\n}) {\n return invokeRequest(new GramJs.phone.EditGroupCallTitle({\n title,\n call: buildInputGroupCall(groupCall),\n }), true);\n}\n\nexport async function exportGroupCallInvite({\n call, canSelfUnmute,\n}: {\n call: ApiGroupCall; canSelfUnmute: boolean;\n}) {\n const result = await invokeRequest(new GramJs.phone.ExportGroupCallInvite({\n canSelfUnmute: canSelfUnmute || undefined,\n call: buildInputGroupCall(call),\n }));\n\n if (!result) {\n return undefined;\n }\n\n return result.link;\n}\n\nexport async function fetchGroupCallParticipants({\n call, offset,\n}: {\n call: ApiGroupCall; offset?: string;\n}) {\n const result = await invokeRequest(new GramJs.phone.GetGroupParticipants({\n call: buildInputGroupCall(call),\n ids: [],\n sources: [],\n offset: offset || '',\n limit: GROUP_CALL_PARTICIPANTS_LIMIT,\n }));\n\n if (!result) {\n return undefined;\n }\n\n addEntitiesWithPhotosToLocalDb(result.users);\n addEntitiesWithPhotosToLocalDb(result.chats);\n\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter(Boolean as any);\n\n onUpdate({\n '@type': 'updateGroupCallParticipants',\n groupCallId: call.id,\n participants: result.participants.map(buildApiGroupCallParticipant),\n nextOffset: result.nextOffset,\n });\n\n return {\n users, chats,\n };\n}\n\nexport function leaveGroupCall({\n call,\n}: {\n call: ApiGroupCall;\n}) {\n return invokeRequest(new GramJs.phone.LeaveGroupCall({\n call: buildInputGroupCall(call),\n }), true);\n}\n\nexport async function joinGroupCall({\n call, inviteHash, params,\n}: {\n call: ApiGroupCall; inviteHash?: string; params: JoinGroupCallPayload;\n}) {\n const result = await invokeRequest(new GramJs.phone.JoinGroupCall({\n call: buildInputGroupCall(call),\n joinAs: new GramJs.InputPeerSelf(),\n muted: true,\n videoStopped: true,\n params: new GramJs.DataJSON({\n data: JSON.stringify(params),\n }),\n inviteHash,\n }), true);\n\n if (!result) return undefined;\n\n if (result instanceof GramJs.Updates) {\n const update = result.updates.find((u) => u instanceof GramJs.UpdateGroupCall);\n if (!(update instanceof GramJs.UpdateGroupCall)) return undefined;\n\n return buildApiGroupCall(update.call);\n }\n\n return undefined;\n}\n\nexport async function createGroupCall({\n peer,\n}: {\n peer: ApiChat;\n}) {\n const randomId = generateRandomInt();\n const result = await invokeRequest(new GramJs.phone.CreateGroupCall({\n peer: buildInputPeer(peer.id, peer.accessHash),\n randomId,\n }), true);\n\n if (!result) return undefined;\n\n if (result instanceof GramJs.Updates) {\n const update = result.updates[0];\n if (update instanceof GramJs.UpdateGroupCall) {\n return buildApiGroupCall(update.call);\n }\n }\n\n return undefined;\n}\n\nexport function joinGroupCallPresentation({\n call, params,\n}: {\n call: ApiGroupCall; params: JoinGroupCallPayload;\n}) {\n return invokeRequest(new GramJs.phone.JoinGroupCallPresentation({\n call: buildInputGroupCall(call),\n params: new GramJs.DataJSON({\n data: JSON.stringify(params),\n }),\n }), true);\n}\n\nexport function toggleGroupCallStartSubscription({\n call, subscribed,\n}: {\n call: ApiGroupCall; subscribed: boolean;\n}) {\n return invokeRequest(new GramJs.phone.ToggleGroupCallStartSubscription({\n call: buildInputGroupCall(call),\n subscribed,\n }), true);\n}\n\nexport function leaveGroupCallPresentation({\n call,\n}: {\n call: ApiGroupCall;\n}) {\n return invokeRequest(new GramJs.phone.LeaveGroupCallPresentation({\n call: buildInputGroupCall(call),\n }), true);\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\n\nimport {\n ApiChat, ApiLangString, ApiLanguage, ApiNotifyException, ApiUser, ApiWallpaper,\n} from '../../types';\nimport { ApiPrivacyKey, InputPrivacyRules, LangCode } from '../../../types';\n\nimport { BLOCKED_LIST_LIMIT, DEFAULT_LANG_PACK, LANG_PACKS } from '../../../config';\nimport {\n buildApiWallpaper, buildApiSession, buildPrivacyRules, buildApiNotifyException, buildApiCountryList,\n} from '../apiBuilders/misc';\n\nimport { buildApiUser } from '../apiBuilders/users';\nimport { buildApiChatFromPreview } from '../apiBuilders/chats';\nimport { buildInputPrivacyKey, buildInputPeer, buildInputEntity } from '../gramjsBuilders';\nimport { invokeRequest, uploadFile, getClient } from './client';\nimport { omitVirtualClassFields } from '../apiBuilders/helpers';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport { getServerTime } from '../../../util/serverTime';\nimport { buildApiPeerId, getApiChatIdFromMtpPeer } from '../apiBuilders/peers';\nimport localDb from '../localDb';\n\nconst MAX_INT_32 = 2 ** 31 - 1;\nconst BETA_LANG_CODES = ['ar', 'fa', 'id', 'ko', 'uz'];\n\nexport function updateProfile({\n firstName,\n lastName,\n about,\n}: {\n firstName?: string;\n lastName?: string;\n about?: string;\n}) {\n return invokeRequest(new GramJs.account.UpdateProfile({\n firstName: firstName || '',\n lastName: lastName || '',\n about: about || '',\n }));\n}\n\nexport function checkUsername(username: string) {\n return invokeRequest(new GramJs.account.CheckUsername({ username }));\n}\n\nexport function updateUsername(username: string) {\n return invokeRequest(new GramJs.account.UpdateUsername({ username }));\n}\n\nexport async function updateProfilePhoto(file: File) {\n const inputFile = await uploadFile(file);\n return invokeRequest(new GramJs.photos.UploadProfilePhoto({\n file: inputFile,\n }));\n}\n\nexport async function uploadProfilePhoto(file: File) {\n const inputFile = await uploadFile(file);\n await invokeRequest(new GramJs.photos.UploadProfilePhoto({\n file: inputFile,\n }));\n}\n\nexport async function fetchWallpapers() {\n const result = await invokeRequest(new GramJs.account.GetWallPapers({ hash: BigInt('0') }));\n\n if (!result || result instanceof GramJs.account.WallPapersNotModified) {\n return undefined;\n }\n\n const filteredWallpapers = result.wallpapers.filter((wallpaper) => {\n if (\n !(wallpaper instanceof GramJs.WallPaper)\n || !(wallpaper.document instanceof GramJs.Document)\n ) {\n return false;\n }\n\n return !wallpaper.pattern && wallpaper.document.mimeType !== 'application/x-tgwallpattern';\n }) as GramJs.WallPaper[];\n\n filteredWallpapers.forEach((wallpaper) => {\n localDb.documents[String(wallpaper.document.id)] = wallpaper.document as GramJs.Document;\n });\n\n return {\n wallpapers: filteredWallpapers.map(buildApiWallpaper).filter(Boolean as any),\n };\n}\n\nexport async function uploadWallpaper(file: File) {\n const inputFile = await uploadFile(file);\n\n const result = await invokeRequest(new GramJs.account.UploadWallPaper({\n file: inputFile,\n mimeType: file.type,\n settings: new GramJs.WallPaperSettings(),\n }));\n\n if (!result || !(result instanceof GramJs.WallPaper)) {\n return undefined;\n }\n\n const wallpaper = buildApiWallpaper(result);\n if (!wallpaper) {\n return undefined;\n }\n\n localDb.documents[String(result.document.id)] = result.document as GramJs.Document;\n\n return { wallpaper };\n}\n\nexport async function fetchBlockedContacts() {\n const result = await invokeRequest(new GramJs.contacts.GetBlocked({\n limit: BLOCKED_LIST_LIMIT,\n }));\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return {\n users: result.users.map(buildApiUser).filter(Boolean as any),\n chats: result.chats.map((chat) => buildApiChatFromPreview(chat, undefined, true)).filter(Boolean as any),\n blockedIds: result.blocked.map((blocked) => getApiChatIdFromMtpPeer(blocked.peerId)),\n totalCount: result instanceof GramJs.contacts.BlockedSlice ? result.count : result.blocked.length,\n };\n}\n\nexport function blockContact(chatOrUserId: string, accessHash?: string) {\n return invokeRequest(new GramJs.contacts.Block({\n id: buildInputPeer(chatOrUserId, accessHash),\n }));\n}\n\nexport function unblockContact(chatOrUserId: string, accessHash?: string) {\n return invokeRequest(new GramJs.contacts.Unblock({\n id: buildInputPeer(chatOrUserId, accessHash),\n }));\n}\n\nexport async function fetchAuthorizations() {\n const result = await invokeRequest(new GramJs.account.GetAuthorizations());\n if (!result) {\n return undefined;\n }\n\n return result.authorizations.map(buildApiSession);\n}\n\nexport function terminateAuthorization(hash: string) {\n return invokeRequest(new GramJs.account.ResetAuthorization({ hash: BigInt(hash) }));\n}\n\nexport function terminateAllAuthorizations() {\n return invokeRequest(new GramJs.auth.ResetAuthorizations());\n}\n\nexport async function fetchNotificationExceptions({\n serverTimeOffset,\n}: { serverTimeOffset: number }) {\n const result = await invokeRequest(new GramJs.account.GetNotifyExceptions({ compareSound: true }));\n\n if (!(result instanceof GramJs.Updates || result instanceof GramJs.UpdatesCombined)) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return result.updates.reduce((acc, update) => {\n if (!(update instanceof GramJs.UpdateNotifySettings && update.peer instanceof GramJs.NotifyPeer)) {\n return acc;\n }\n\n acc.push(buildApiNotifyException(update.notifySettings, update.peer.peer, serverTimeOffset));\n\n return acc;\n }, [] as ApiNotifyException[]);\n}\n\nexport async function fetchNotificationSettings({\n serverTimeOffset,\n}: { serverTimeOffset: number }) {\n const [\n isMutedContactSignUpNotification,\n privateContactNotificationsSettings,\n groupNotificationsSettings,\n broadcastNotificationsSettings,\n ] = await Promise.all([\n invokeRequest(new GramJs.account.GetContactSignUpNotification()),\n invokeRequest(new GramJs.account.GetNotifySettings({\n peer: new GramJs.InputNotifyUsers(),\n })),\n invokeRequest(new GramJs.account.GetNotifySettings({\n peer: new GramJs.InputNotifyChats(),\n })),\n invokeRequest(new GramJs.account.GetNotifySettings({\n peer: new GramJs.InputNotifyBroadcasts(),\n })),\n ]);\n\n if (!privateContactNotificationsSettings || !groupNotificationsSettings || !broadcastNotificationsSettings) {\n return false;\n }\n\n const {\n silent: privateSilent, muteUntil: privateMuteUntil, showPreviews: privateShowPreviews,\n } = privateContactNotificationsSettings;\n const {\n silent: groupSilent, muteUntil: groupMuteUntil, showPreviews: groupShowPreviews,\n } = groupNotificationsSettings;\n const {\n silent: broadcastSilent, muteUntil: broadcastMuteUntil, showPreviews: broadcastShowPreviews,\n } = broadcastNotificationsSettings;\n\n return {\n hasContactJoinedNotifications: !isMutedContactSignUpNotification,\n hasPrivateChatsNotifications: !(\n privateSilent\n || (typeof privateMuteUntil === 'number' && getServerTime(serverTimeOffset) < privateMuteUntil)\n ),\n hasPrivateChatsMessagePreview: privateShowPreviews,\n hasGroupNotifications: !(\n groupSilent || (typeof groupMuteUntil === 'number'\n && getServerTime(serverTimeOffset) < groupMuteUntil)\n ),\n hasGroupMessagePreview: groupShowPreviews,\n hasBroadcastNotifications: !(\n broadcastSilent || (typeof broadcastMuteUntil === 'number'\n && getServerTime(serverTimeOffset) < broadcastMuteUntil)\n ),\n hasBroadcastMessagePreview: broadcastShowPreviews,\n };\n}\n\nexport function updateContactSignUpNotification(isSilent: boolean) {\n return invokeRequest(new GramJs.account.SetContactSignUpNotification({ silent: isSilent }));\n}\n\nexport function updateNotificationSettings(peerType: 'contact' | 'group' | 'broadcast', {\n isSilent,\n shouldShowPreviews,\n}: {\n isSilent: boolean;\n shouldShowPreviews: boolean;\n}) {\n let peer: GramJs.TypeInputNotifyPeer;\n if (peerType === 'contact') {\n peer = new GramJs.InputNotifyUsers();\n } else if (peerType === 'group') {\n peer = new GramJs.InputNotifyChats();\n } else {\n peer = new GramJs.InputNotifyBroadcasts();\n }\n\n const settings = {\n showPreviews: shouldShowPreviews,\n silent: isSilent,\n muteUntil: isSilent ? MAX_INT_32 : 0,\n };\n\n return invokeRequest(new GramJs.account.UpdateNotifySettings({\n peer,\n settings: new GramJs.InputPeerNotifySettings(settings),\n }));\n}\n\nexport async function fetchLanguages(): Promise {\n const result = await invokeRequest(new GramJs.langpack.GetLanguages({\n langPack: DEFAULT_LANG_PACK,\n }));\n if (!result) {\n return undefined;\n }\n\n return result.map(omitVirtualClassFields);\n}\n\nexport async function fetchLangPack({ sourceLangPacks, langCode }: {\n sourceLangPacks: typeof LANG_PACKS;\n langCode: string;\n}) {\n const results = await Promise.all(sourceLangPacks.map((langPack) => {\n return invokeRequest(new GramJs.langpack.GetLangPack({\n langPack,\n langCode: BETA_LANG_CODES.includes(langCode) ? `${langCode}-raw` : langCode,\n }));\n }));\n\n const collections = results\n .filter(Boolean as any)\n .map((result) => {\n return buildCollectionByKey(result.strings.map(omitVirtualClassFields), 'key');\n });\n\n if (!collections.length) {\n return undefined;\n }\n\n return { langPack: Object.assign({}, ...collections.reverse()) };\n}\n\nexport async function fetchLangStrings({ langPack, langCode, keys }: {\n langPack: string; langCode: string; keys: string[];\n}) {\n const result = await invokeRequest(new GramJs.langpack.GetStrings({\n langPack,\n langCode: BETA_LANG_CODES.includes(langCode) ? `${langCode}-raw` : langCode,\n keys,\n }));\n\n if (!result) {\n return undefined;\n }\n\n return result.map(omitVirtualClassFields);\n}\n\nexport async function fetchPrivacySettings(privacyKey: ApiPrivacyKey) {\n const key = buildInputPrivacyKey(privacyKey);\n const result = await invokeRequest(new GramJs.account.GetPrivacy({ key }));\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return buildPrivacyRules(result.rules);\n}\n\nexport function registerDevice(token: string) {\n const client = getClient();\n const secret = client.session.getAuthKey().getKey();\n return invokeRequest(new GramJs.account.RegisterDevice({\n tokenType: 10,\n secret,\n appSandbox: false,\n otherUids: [],\n token,\n }));\n}\n\nexport function unregisterDevice(token: string) {\n return invokeRequest(new GramJs.account.UnregisterDevice({\n tokenType: 10,\n otherUids: [],\n token,\n }));\n}\n\nexport async function setPrivacySettings(\n privacyKey: ApiPrivacyKey, rules: InputPrivacyRules,\n) {\n const key = buildInputPrivacyKey(privacyKey);\n const privacyRules: GramJs.TypeInputPrivacyRule[] = [];\n\n if (rules.allowedUsers) {\n privacyRules.push(new GramJs.InputPrivacyValueAllowUsers({\n users: rules.allowedUsers.map(({ id, accessHash }) => buildInputEntity(id, accessHash) as GramJs.InputUser),\n }));\n }\n if (rules.allowedChats) {\n privacyRules.push(new GramJs.InputPrivacyValueAllowChatParticipants({\n chats: rules.allowedChats.map(({ id }) => buildInputEntity(id) as BigInt.BigInteger),\n }));\n }\n if (rules.blockedUsers) {\n privacyRules.push(new GramJs.InputPrivacyValueDisallowUsers({\n users: rules.blockedUsers.map(({ id, accessHash }) => buildInputEntity(id, accessHash) as GramJs.InputUser),\n }));\n }\n if (rules.blockedChats) {\n privacyRules.push(new GramJs.InputPrivacyValueDisallowChatParticipants({\n chats: rules.blockedChats.map(({ id }) => buildInputEntity(id) as BigInt.BigInteger),\n }));\n }\n switch (rules.visibility) {\n case 'everybody':\n privacyRules.push(new GramJs.InputPrivacyValueAllowAll());\n break;\n\n case 'contacts':\n privacyRules.push(new GramJs.InputPrivacyValueAllowContacts());\n break;\n\n case 'nonContacts':\n privacyRules.push(new GramJs.InputPrivacyValueDisallowContacts());\n break;\n\n case 'nobody':\n privacyRules.push(new GramJs.InputPrivacyValueDisallowAll());\n break;\n }\n\n const result = await invokeRequest(new GramJs.account.SetPrivacy({ key, rules: privacyRules }));\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return buildPrivacyRules(result.rules);\n}\n\nexport async function updateIsOnline(isOnline: boolean) {\n await invokeRequest(new GramJs.account.UpdateStatus({ offline: !isOnline }));\n}\n\nexport async function fetchContentSettings() {\n const result = await invokeRequest(new GramJs.account.GetContentSettings());\n if (!result) {\n return undefined;\n }\n\n return {\n isSensitiveEnabled: Boolean(result.sensitiveEnabled),\n canChangeSensitive: Boolean(result.sensitiveCanChange),\n };\n}\n\nexport function updateContentSettings(isEnabled: boolean) {\n return invokeRequest(new GramJs.account.SetContentSettings({\n sensitiveEnabled: isEnabled || undefined,\n }));\n}\n\nfunction updateLocalDb(\n result: (\n GramJs.account.PrivacyRules | GramJs.contacts.Blocked | GramJs.contacts.BlockedSlice |\n GramJs.Updates | GramJs.UpdatesCombined\n ),\n) {\n result.users.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[buildApiPeerId(user.id, 'user')] = user;\n }\n });\n\n result.chats.forEach((chat) => {\n if (chat instanceof GramJs.Chat || chat instanceof GramJs.Channel) {\n localDb.chats[buildApiPeerId(chat.id, chat instanceof GramJs.Chat ? 'chat' : 'channel')] = chat;\n }\n });\n}\n\nexport async function fetchCountryList({ langCode = 'en' }: { langCode?: LangCode }) {\n const countryList = await invokeRequest(new GramJs.help.GetCountriesList({\n langCode,\n }));\n\n if (!(countryList instanceof GramJs.help.CountriesList)) {\n return undefined;\n }\n return buildApiCountryList(countryList.countries);\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n ApiBotInlineMediaResult, ApiBotInlineResult, ApiBotInlineSwitchPm, ApiInlineResultType, ApiWebDocument,\n} from '../../types';\n\nimport { pick } from '../../../util/iteratees';\nimport { buildApiPhoto, buildApiThumbnailFromStripped } from './common';\nimport { buildVideoFromDocument } from './messages';\nimport { buildStickerFromDocument } from './symbols';\n\nexport function buildApiBotInlineResult(result: GramJs.BotInlineResult, queryId: string): ApiBotInlineResult {\n const {\n id, type, title, description, url, thumb,\n } = result;\n\n return {\n id,\n queryId,\n type: type as ApiInlineResultType,\n title,\n description,\n url,\n webThumbnail: buildApiWebDocument(thumb),\n };\n}\n\nexport function buildApiBotInlineMediaResult(\n result: GramJs.BotInlineMediaResult, queryId: string,\n): ApiBotInlineMediaResult {\n const {\n id, type, title, description, photo, document,\n } = result;\n\n return {\n id,\n queryId,\n type: type as ApiInlineResultType,\n title,\n description,\n ...(type === 'sticker' && document instanceof GramJs.Document && { sticker: buildStickerFromDocument(document) }),\n ...(photo instanceof GramJs.Photo && { photo: buildApiPhoto(photo) }),\n ...(type === 'gif' && document instanceof GramJs.Document && { gif: buildVideoFromDocument(document) }),\n ...(type === 'video' && document instanceof GramJs.Document && {\n thumbnail: buildApiThumbnailFromStripped(document.thumbs),\n }),\n };\n}\n\nexport function buildBotSwitchPm(switchPm?: GramJs.InlineBotSwitchPM) {\n return switchPm ? pick(switchPm, ['text', 'startParam']) as ApiBotInlineSwitchPm : undefined;\n}\n\nfunction buildApiWebDocument(document?: GramJs.TypeWebDocument): ApiWebDocument | undefined {\n return document ? pick(document, ['url', 'mimeType']) : undefined;\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\n\nimport { ApiChat, ApiUser } from '../../types';\n\nimport localDb from '../localDb';\nimport { invokeRequest } from './client';\nimport { buildInputPeer, generateRandomBigInt } from '../gramjsBuilders';\nimport { buildApiUser } from '../apiBuilders/users';\nimport { buildApiBotInlineMediaResult, buildApiBotInlineResult, buildBotSwitchPm } from '../apiBuilders/bots';\nimport { buildApiChatFromPreview } from '../apiBuilders/chats';\nimport { addEntitiesWithPhotosToLocalDb, addUserToLocalDb, deserializeBytes } from '../helpers';\n\nexport function init() {\n}\n\nexport function answerCallbackButton(\n {\n chatId, accessHash, messageId, data,\n }: {\n chatId: string; accessHash?: string; messageId: number; data: string;\n },\n) {\n return invokeRequest(new GramJs.messages.GetBotCallbackAnswer({\n peer: buildInputPeer(chatId, accessHash),\n msgId: messageId,\n data: deserializeBytes(data),\n }));\n}\n\nexport async function fetchTopInlineBots() {\n const topPeers = await invokeRequest(new GramJs.contacts.GetTopPeers({\n botsInline: true,\n }));\n\n if (!(topPeers instanceof GramJs.contacts.TopPeers)) {\n return undefined;\n }\n\n const users = topPeers.users.map(buildApiUser).filter(Boolean as any);\n const ids = users.map(({ id }) => id);\n\n return {\n ids,\n users,\n };\n}\n\nexport async function fetchInlineBot({ username }: { username: string }) {\n const resolvedPeer = await invokeRequest(new GramJs.contacts.ResolveUsername({ username }));\n\n if (\n !resolvedPeer\n || !(\n resolvedPeer.users[0] instanceof GramJs.User\n && resolvedPeer.users[0].bot\n && resolvedPeer.users[0].botInlinePlaceholder\n )\n ) {\n return undefined;\n }\n\n addUserToLocalDb(resolvedPeer.users[0]);\n\n return {\n user: buildApiUser(resolvedPeer.users[0]),\n chat: buildApiChatFromPreview(resolvedPeer.users[0]),\n };\n}\n\nexport async function fetchInlineBotResults({\n bot, chat, query, offset = '',\n}: {\n bot: ApiUser; chat: ApiChat; query: string; offset?: string;\n}) {\n const result = await invokeRequest(new GramJs.messages.GetInlineBotResults({\n bot: buildInputPeer(bot.id, bot.accessHash),\n peer: buildInputPeer(chat.id, chat.accessHash),\n query,\n offset,\n }));\n\n if (!result) {\n return undefined;\n }\n\n addEntitiesWithPhotosToLocalDb(result.users);\n\n return {\n isGallery: Boolean(result.gallery),\n help: bot.botPlaceholder,\n nextOffset: getInlineBotResultsNextOffset(bot.username, result.nextOffset),\n switchPm: buildBotSwitchPm(result.switchPm),\n users: result.users.map(buildApiUser).filter(Boolean as any),\n results: processInlineBotResult(String(result.queryId), result.results),\n };\n}\n\nexport async function sendInlineBotResult({\n chat, resultId, queryId, replyingTo, sendAs,\n}: {\n chat: ApiChat;\n resultId: string;\n queryId: string;\n replyingTo?: number;\n sendAs?: ApiUser | ApiChat;\n}) {\n const randomId = generateRandomBigInt();\n\n await invokeRequest(new GramJs.messages.SendInlineBotResult({\n clearDraft: true,\n randomId,\n queryId: BigInt(queryId),\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: resultId,\n ...(replyingTo && { replyToMsgId: replyingTo }),\n ...(sendAs && { sendAs: buildInputPeer(sendAs.id, sendAs.accessHash) }),\n }), true);\n}\n\nexport async function startBot({\n bot, startParam,\n}: {\n bot: ApiUser;\n startParam?: string;\n}) {\n const randomId = generateRandomBigInt();\n\n await invokeRequest(new GramJs.messages.StartBot({\n bot: buildInputPeer(bot.id, bot.accessHash),\n peer: buildInputPeer(bot.id, bot.accessHash),\n randomId,\n startParam,\n }), true);\n}\n\nfunction processInlineBotResult(queryId: string, results: GramJs.TypeBotInlineResult[]) {\n return results.map((result) => {\n if (result instanceof GramJs.BotInlineMediaResult) {\n if (result.document instanceof GramJs.Document) {\n addDocumentToLocalDb(result.document);\n }\n\n if (result.photo instanceof GramJs.Photo) {\n addPhotoToLocalDb(result.photo);\n }\n\n return buildApiBotInlineMediaResult(result, queryId);\n }\n\n if (result.thumb) {\n addWebDocumentToLocalDb(result.thumb);\n }\n\n return buildApiBotInlineResult(result, queryId);\n });\n}\n\nfunction getInlineBotResultsNextOffset(username: string, nextOffset?: string) {\n return username === 'gif' && nextOffset === '0' ? '' : nextOffset;\n}\n\nfunction addDocumentToLocalDb(document: GramJs.Document) {\n localDb.documents[String(document.id)] = document;\n}\n\nfunction addPhotoToLocalDb(photo: GramJs.Photo) {\n localDb.photos[String(photo.id)] = photo;\n}\n\nfunction addWebDocumentToLocalDb(webDocument: GramJs.TypeWebDocument) {\n localDb.webDocuments[webDocument.url] = webDocument;\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\n\nexport function buildShippingOptions(shippingOptions: GramJs.ShippingOption[] | undefined) {\n if (!shippingOptions) {\n return undefined;\n }\n return Object.values(shippingOptions).map((option) => {\n return {\n id: option.id,\n title: option.title,\n amount: option.prices.reduce((ac, cur) => ac + Number((cur.amount as any).value), 0),\n prices: option.prices.map(({ label, amount }) => {\n return {\n label,\n amount: Number((amount as any).value),\n };\n }),\n };\n });\n}\n\nexport function buildReceipt(receipt: GramJs.payments.PaymentReceipt) {\n const {\n invoice,\n info,\n shipping,\n currency,\n totalAmount,\n credentialsTitle,\n } = receipt;\n\n const { shippingAddress, phone, name } = (info || {});\n\n const { prices } = invoice;\n const mapedPrices = prices.map(({ label, amount }) => ({\n label,\n amount: Number((amount as any).value),\n }));\n\n let shippingPrices;\n let shippingMethod;\n\n if (shipping) {\n shippingPrices = shipping.prices.map(({ label, amount }) => {\n return {\n label,\n amount: Number((amount as any).value),\n };\n });\n shippingMethod = shipping.title;\n }\n\n return {\n currency,\n prices: mapedPrices,\n info: { shippingAddress, phone, name },\n totalAmount: Number((totalAmount as any).value),\n credentialsTitle,\n shippingPrices,\n shippingMethod,\n };\n}\n\nexport function buildPaymentForm(form: GramJs.payments.PaymentForm) {\n const {\n formId,\n canSaveCredentials,\n passwordMissing,\n providerId,\n nativeProvider,\n nativeParams,\n savedInfo,\n invoice,\n } = form;\n\n const {\n test,\n nameRequested,\n phoneRequested,\n emailRequested,\n shippingAddressRequested,\n flexible,\n phoneToProvider,\n emailToProvider,\n currency,\n prices,\n } = invoice;\n\n const mapedPrices = prices.map(({ label, amount }) => ({\n label,\n amount: Number((amount as any).value),\n }));\n\n const nativeData = nativeParams ? JSON.parse(nativeParams.data) : {};\n return {\n canSaveCredentials,\n passwordMissing,\n formId: String(formId),\n providerId: String(providerId),\n nativeProvider,\n savedInfo,\n invoice: {\n test,\n nameRequested,\n phoneRequested,\n emailRequested,\n shippingAddressRequested,\n flexible,\n phoneToProvider,\n emailToProvider,\n currency,\n prices: mapedPrices,\n },\n nativeParams: {\n needCardholderName: nativeData.need_cardholder_name,\n needCountry: nativeData.need_country,\n needZip: nativeData.need_zip,\n publishableKey: nativeData.publishable_key,\n },\n };\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport { invokeRequest } from './client';\nimport { buildInputPeer, buildShippingInfo } from '../gramjsBuilders';\nimport { buildShippingOptions, buildPaymentForm, buildReceipt } from '../apiBuilders/payments';\nimport { ApiChat } from '../../types';\n\nexport async function validateRequestedInfo({\n chat,\n messageId,\n requestInfo,\n shouldSave,\n}: {\n chat: ApiChat;\n messageId: number;\n requestInfo: GramJs.TypePaymentRequestedInfo;\n shouldSave?: boolean;\n}): Promise<{\n id: string;\n shippingOptions: any;\n } | undefined> {\n const result = await invokeRequest(new GramJs.payments.ValidateRequestedInfo({\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: messageId,\n save: shouldSave || undefined,\n info: buildShippingInfo(requestInfo),\n }));\n if (!result) {\n return undefined;\n }\n\n const { id, shippingOptions } = result;\n if (!id) {\n return undefined;\n }\n\n return {\n id,\n shippingOptions: buildShippingOptions(shippingOptions),\n };\n}\n\nexport function sendPaymentForm({\n chat,\n messageId,\n formId,\n requestedInfoId,\n shippingOptionId,\n credentials,\n}: {\n chat: ApiChat;\n messageId: number;\n formId: string;\n credentials: any;\n requestedInfoId?: string;\n shippingOptionId?: string;\n}) {\n return invokeRequest(new GramJs.payments.SendPaymentForm({\n formId: BigInt(formId),\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: messageId,\n requestedInfoId,\n shippingOptionId,\n credentials: new GramJs.InputPaymentCredentials({\n save: credentials.save,\n data: new GramJs.DataJSON({ data: JSON.stringify(credentials.data) }),\n }),\n }), true);\n}\n\nexport async function getPaymentForm({\n chat, messageId,\n}: {\n chat: ApiChat;\n messageId: number;\n}) {\n const result = await invokeRequest(new GramJs.payments.GetPaymentForm({\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: messageId,\n }));\n\n if (!result) {\n return undefined;\n }\n\n return buildPaymentForm(result);\n}\n\nexport async function getReceipt(chat: ApiChat, msgId: number) {\n const result = await invokeRequest(new GramJs.payments.GetPaymentReceipt({\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId,\n }));\n if (!result) {\n return undefined;\n }\n\n return buildReceipt(result);\n}\n","import {\n OnApiUpdate,\n ApiInitialArgs,\n ApiUpdate,\n ApiOnProgress,\n} from '../types';\nimport { Methods, MethodArgs, MethodResponse } from './methods/types';\n\nimport { API_THROTTLE_RESET_UPDATES, API_UPDATE_THROTTLE } from '../../config';\nimport { throttle, throttleWithTickEnd } from '../../util/schedulers';\nimport { init as initUpdater } from './updater';\nimport { init as initAuth } from './methods/auth';\nimport { init as initChats } from './methods/chats';\nimport { init as initMessages } from './methods/messages';\nimport { init as initUsers } from './methods/users';\nimport { init as initClient } from './methods/client';\nimport { init as initStickers } from './methods/symbols';\nimport { init as initManagement } from './methods/management';\nimport { init as initTwoFaSettings } from './methods/twoFaSettings';\nimport { init as initCalls } from './methods/calls';\nimport * as methods from './methods';\n\nlet onUpdate: OnApiUpdate;\n\nexport async function initApi(_onUpdate: OnApiUpdate, initialArgs: ApiInitialArgs) {\n onUpdate = _onUpdate;\n\n initUpdater(handleUpdate);\n initAuth(handleUpdate);\n initChats(handleUpdate);\n initMessages(handleUpdate);\n initUsers(handleUpdate);\n initStickers(handleUpdate);\n initManagement(handleUpdate);\n initTwoFaSettings(handleUpdate);\n initCalls(handleUpdate);\n\n await initClient(handleUpdate, initialArgs);\n}\n\nexport function callApi(fnName: T, ...args: MethodArgs): MethodResponse {\n // @ts-ignore\n return methods[fnName](...args) as MethodResponse;\n}\n\nexport function cancelApiProgress(progressCallback: ApiOnProgress) {\n progressCallback.isCanceled = true;\n}\n\nconst flushUpdatesOnTickEnd = throttleWithTickEnd(flushUpdates);\n\nlet flushUpdatesThrottled: typeof flushUpdatesOnTickEnd | undefined;\nlet currentThrottleId: number | undefined;\n\nlet pendingUpdates: ApiUpdate[] | undefined;\n\nfunction handleUpdate(update: ApiUpdate) {\n if (!pendingUpdates) {\n pendingUpdates = [update];\n } else {\n pendingUpdates.push(update);\n }\n\n if (!flushUpdatesThrottled || API_THROTTLE_RESET_UPDATES.has(update['@type'])) {\n flushUpdatesThrottled = throttle(flushUpdatesOnTickEnd, API_UPDATE_THROTTLE, true);\n currentThrottleId = Math.random();\n }\n\n flushUpdatesThrottled(currentThrottleId!);\n}\n\nfunction flushUpdates(throttleId: number) {\n if (!pendingUpdates || throttleId !== currentThrottleId) {\n return;\n }\n\n const currentUpdates = pendingUpdates!;\n pendingUpdates = undefined;\n currentUpdates.forEach(onUpdate);\n}\n","import { ApiOnProgress, ApiUpdate } from '../../types';\nimport { OriginMessageEvent, WorkerMessageData } from './types';\n\nimport { DEBUG } from '../../../config';\nimport { initApi, callApi, cancelApiProgress } from '../provider';\n\ndeclare const self: WorkerGlobalScope;\n\nhandleErrors();\n\n// TODO Re-use `util/createWorkerInterface.ts`\n\nconst callbackState = new Map();\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH LOAD WORKER');\n}\n\nonmessage = async (message: OriginMessageEvent) => {\n const { data } = message;\n\n switch (data.type) {\n case 'initApi': {\n await initApi(onUpdate, data.args[0]);\n break;\n }\n case 'callMethod': {\n const { messageId, name, args } = data;\n try {\n if (messageId) {\n const callback = (...callbackArgs: any[]) => {\n const lastArg = callbackArgs[callbackArgs.length - 1];\n\n sendToOrigin({\n type: 'methodCallback',\n messageId,\n callbackArgs,\n }, lastArg instanceof ArrayBuffer ? lastArg : undefined);\n };\n\n callbackState.set(messageId, callback);\n\n args.push(callback as never);\n }\n\n const response = await callApi(name, ...args);\n const { arrayBuffer } = (typeof response === 'object' && 'arrayBuffer' in response && response) || {};\n\n if (messageId) {\n sendToOrigin({\n type: 'methodResponse',\n messageId,\n response,\n }, arrayBuffer);\n }\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(error);\n }\n\n if (messageId) {\n sendToOrigin({\n type: 'methodResponse',\n messageId,\n error: { message: error.message },\n });\n }\n }\n\n if (messageId) {\n callbackState.delete(messageId);\n }\n\n break;\n }\n case 'cancelProgress': {\n const callback = callbackState.get(data.messageId);\n if (callback) {\n cancelApiProgress(callback);\n }\n\n break;\n }\n case 'ping': {\n sendToOrigin({\n type: 'methodResponse',\n messageId: data.messageId!,\n });\n\n break;\n }\n }\n};\n\nfunction handleErrors() {\n self.onerror = (e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n sendToOrigin({ type: 'unhandledError', error: { message: e.error.message || 'Uncaught exception in worker' } });\n };\n\n self.addEventListener('unhandledrejection', (e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n sendToOrigin({ type: 'unhandledError', error: { message: e.reason.message || 'Uncaught rejection in worker' } });\n });\n}\n\nfunction onUpdate(update: ApiUpdate) {\n sendToOrigin({\n type: 'update',\n update,\n });\n}\n\nfunction sendToOrigin(data: WorkerMessageData, arrayBuffer?: ArrayBuffer) {\n if (arrayBuffer) {\n postMessage(data, [arrayBuffer]);\n } else {\n postMessage(data);\n }\n}\n","const BigInt = require('big-integer');\nconst crypto = require('./crypto/crypto');\n\n/**\n * converts a buffer to big int\n * @param buffer\n * @param little\n * @param signed\n * @returns {bigInt.BigInteger}\n */\nfunction readBigIntFromBuffer(buffer, little = true, signed = false) {\n let randBuffer = Buffer.from(buffer);\n const bytesNumber = randBuffer.length;\n if (little) {\n randBuffer = randBuffer.reverse();\n }\n let bigInt = BigInt(randBuffer.toString('hex'), 16);\n if (signed && Math.floor(bigInt.toString('2').length / 8) >= bytesNumber) {\n bigInt = bigInt.subtract(BigInt(2)\n .pow(BigInt(bytesNumber * 8)));\n }\n return bigInt;\n}\n\n/**\n * Special case signed little ints\n * @param big\n * @param number\n * @returns {Buffer}\n */\nfunction toSignedLittleBuffer(big, number = 8) {\n const bigNumber = BigInt(big);\n const byteArray = [];\n for (let i = 0; i < number; i++) {\n byteArray[i] = bigNumber.shiftRight(8 * i)\n .and(255);\n }\n return Buffer.from(byteArray);\n}\n\n\n/**\n * converts a big int to a buffer\n * @param bigInt {bigInt.BigInteger}\n * @param bytesNumber\n * @param little\n * @param signed\n * @returns {Buffer}\n */\nfunction readBufferFromBigInt(bigInt, bytesNumber, little = true, signed = false) {\n bigInt = BigInt(bigInt);\n const bitLength = bigInt.bitLength();\n\n const bytes = Math.ceil(bitLength / 8);\n if (bytesNumber < bytes) {\n throw new Error('OverflowError: int too big to convert');\n }\n if (!signed && bigInt.lesser(BigInt(0))) {\n throw new Error('Cannot convert to unsigned');\n }\n let below = false;\n if (bigInt.lesser(BigInt(0))) {\n below = true;\n bigInt = bigInt.abs();\n }\n\n const hex = bigInt.toString('16')\n .padStart(bytesNumber * 2, '0');\n let l = Buffer.from(hex, 'hex');\n if (little) {\n l = l.reverse();\n }\n\n if (signed && below) {\n if (little) {\n let reminder = false;\n if (l[0] !== 0) {\n l[0] -= 1;\n }\n for (let i = 0; i < l.length; i++) {\n if (l[i] === 0) {\n reminder = true;\n continue;\n }\n if (reminder) {\n l[i] -= 1;\n reminder = false;\n }\n l[i] = 255 - l[i];\n }\n } else {\n l[l.length - 1] = 256 - l[l.length - 1];\n for (let i = 0; i < l.length - 1; i++) {\n l[i] = 255 - l[i];\n }\n }\n }\n return l;\n}\n\n/**\n * Generates a random long integer (8 bytes), which is optionally signed\n * @returns {BigInteger}\n */\nfunction generateRandomLong(signed = true) {\n return readBigIntFromBuffer(generateRandomBytes(8), true, signed);\n}\n\n/**\n * .... really javascript\n * @param n {number}\n * @param m {number}\n * @returns {number}\n */\nfunction mod(n, m) {\n return ((n % m) + m) % m;\n}\n\n/**\n * returns a positive bigInt\n * @param n {BigInt}\n * @param m {BigInt}\n * @returns {BigInt}\n */\nfunction bigIntMod(n, m) {\n return ((n.remainder(m)).add(m)).remainder(m);\n}\n\n/**\n * Generates a random bytes array\n * @param count\n * @returns {Buffer}\n */\nfunction generateRandomBytes(count) {\n return Buffer.from(crypto.randomBytes(count));\n}\n\n/**\n * Calculate the key based on Telegram guidelines, specifying whether it's the client or not\n * @param sharedKey\n * @param msgKey\n * @param client\n * @returns {{iv: Buffer, key: Buffer}}\n */\n\n/* CONTEST\nthis is mtproto 1 (mostly used for secret chats)\nasync function calcKey(sharedKey, msgKey, client) {\n const x = client === true ? 0 : 8\n const [sha1a, sha1b, sha1c, sha1d] = await Promise.all([\n sha1(Buffer.concat([msgKey, sharedKey.slice(x, x + 32)])),\n sha1(Buffer.concat([sharedKey.slice(x + 32, x + 48), msgKey, sharedKey.slice(x + 48, x + 64)])),\n sha1(Buffer.concat([sharedKey.slice(x + 64, x + 96), msgKey])),\n sha1(Buffer.concat([msgKey, sharedKey.slice(x + 96, x + 128)]))\n ])\n const key = Buffer.concat([sha1a.slice(0, 8), sha1b.slice(8, 20), sha1c.slice(4, 16)])\n const iv = Buffer.concat([sha1a.slice(8, 20), sha1b.slice(0, 8), sha1c.slice(16, 20), sha1d.slice(0, 8)])\n return {\n key,\n iv\n }\n}\n\n */\n\n/**\n * Generates the key data corresponding to the given nonces\n * @param serverNonce\n * @param newNonce\n * @returns {{key: Buffer, iv: Buffer}}\n */\nasync function generateKeyDataFromNonce(serverNonce, newNonce) {\n serverNonce = toSignedLittleBuffer(serverNonce, 16);\n newNonce = toSignedLittleBuffer(newNonce, 32);\n const [hash1, hash2, hash3] = await Promise.all([\n sha1(Buffer.concat([newNonce, serverNonce])),\n sha1(Buffer.concat([serverNonce, newNonce])),\n sha1(Buffer.concat([newNonce, newNonce])),\n ]);\n const keyBuffer = Buffer.concat([hash1, hash2.slice(0, 12)]);\n const ivBuffer = Buffer.concat([hash2.slice(12, 20), hash3, newNonce.slice(0, 4)]);\n return {\n key: keyBuffer,\n iv: ivBuffer,\n };\n}\n\nfunction convertToLittle(buf) {\n const correct = Buffer.alloc(buf.length * 4);\n\n for (let i = 0; i < buf.length; i++) {\n correct.writeUInt32BE(buf[i], i * 4);\n }\n return correct;\n}\n\n/**\n * Calculates the SHA1 digest for the given data\n * @param data\n * @returns {Promise}\n */\nfunction sha1(data) {\n const shaSum = crypto.createHash('sha1');\n shaSum.update(data);\n return shaSum.digest();\n}\n\n\n/**\n * Calculates the SHA256 digest for the given data\n * @param data\n * @returns {Promise}\n */\nfunction sha256(data) {\n const shaSum = crypto.createHash('sha256');\n shaSum.update(data);\n return shaSum.digest();\n}\n\n/**\n * Fast mod pow for RSA calculation. a^b % n\n * @param a\n * @param b\n * @param n\n * @returns {bigInt.BigInteger}\n */\nfunction modExp(a, b, n) {\n a = a.remainder(n);\n let result = BigInt.one;\n let x = a;\n while (b.greater(BigInt.zero)) {\n const leastSignificantBit = b.remainder(BigInt(2));\n b = b.divide(BigInt(2));\n if (leastSignificantBit.eq(BigInt.one)) {\n result = result.multiply(x);\n result = result.remainder(n);\n }\n x = x.multiply(x);\n x = x.remainder(n);\n }\n return result;\n}\n\n\n/**\n * Gets the arbitrary-length byte array corresponding to the given integer\n * @param integer {number,BigInteger}\n * @param signed {boolean}\n * @returns {Buffer}\n */\nfunction getByteArray(integer, signed = false) {\n const bits = integer.toString(2).length;\n const byteLength = Math.floor((bits + 8 - 1) / 8);\n return readBufferFromBigInt(BigInt(integer), byteLength, false, signed);\n}\n\n/**\n * returns a random int from min (inclusive) and max (inclusive)\n * @param min\n * @param max\n * @returns {number}\n */\nfunction getRandomInt(min, max) {\n min = Math.ceil(min);\n max = Math.floor(max);\n return Math.floor(Math.random() * (max - min + 1)) + min;\n}\n\n/**\n * Sleeps a specified amount of time\n * @param ms time in milliseconds\n * @returns {Promise}\n */\nconst sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));\n\n/**\n * Helper to export two buffers of same length\n * @returns {Buffer}\n */\n\nfunction bufferXor(a, b) {\n const res = [];\n for (let i = 0; i < a.length; i++) {\n res.push(a[i] ^ b[i]);\n }\n return Buffer.from(res);\n}\n\n/**\n * Checks if the obj is an array\n * @param obj\n * @returns {boolean}\n */\n/*\nCONTEST\nwe do'nt support array requests anyway\nfunction isArrayLike(obj) {\n if (!obj) return false\n const l = obj.length\n if (typeof l != 'number' || l < 0) return false\n if (Math.floor(l) !== l) return false\n // fast check\n if (l > 0 && !(l - 1 in obj)) return false\n // more complete check (optional)\n for (let i = 0; i < l; ++i) {\n if (!(i in obj)) return false\n }\n return true\n}\n*/\n\n// Taken from https://stackoverflow.com/questions/18638900/javascript-crc32/18639999#18639999\nfunction makeCRCTable() {\n let c;\n const crcTable = [];\n for (let n = 0; n < 256; n++) {\n c = n;\n for (let k = 0; k < 8; k++) {\n c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));\n }\n crcTable[n] = c;\n }\n return crcTable;\n}\n\nlet crcTable;\n\nfunction crc32(buf) {\n if (!crcTable) {\n crcTable = makeCRCTable();\n }\n if (!Buffer.isBuffer(buf)) {\n buf = Buffer.from(buf);\n }\n let crc = -1;\n\n for (let index = 0; index < buf.length; index++) {\n const byte = buf[index];\n crc = crcTable[(crc ^ byte) & 0xff] ^ (crc >>> 8);\n }\n return (crc ^ (-1)) >>> 0;\n}\n\n/**\n * Creates a deferred object\n * @return {Deferred}\n */\nfunction createDeferred() {\n let resolve;\n const promise = new Promise((_resolve) => {\n resolve = _resolve;\n });\n\n return {\n promise,\n resolve,\n };\n}\n\nmodule.exports = {\n readBigIntFromBuffer,\n readBufferFromBigInt,\n generateRandomLong,\n mod,\n crc32,\n generateRandomBytes,\n // calcKey,\n generateKeyDataFromNonce,\n sha1,\n sha256,\n bigIntMod,\n modExp,\n getRandomInt,\n sleep,\n getByteArray,\n // isArrayLike,\n toSignedLittleBuffer,\n convertToLittle,\n bufferXor,\n createDeferred,\n};\n","const BigInt = require('big-integer');\nconst { constructors } = require('./tl');\nconst {\n readBigIntFromBuffer,\n readBufferFromBigInt,\n sha256,\n bigIntMod,\n modExp,\n generateRandomBytes,\n} = require('./Helpers');\nconst crypto = require('./crypto/crypto');\n\nconst SIZE_FOR_HASH = 256;\n\n/**\n *\n *\n * @param prime{BigInteger}\n * @param g{BigInteger}\n */\n\n/*\nWe don't support changing passwords yet\nfunction checkPrimeAndGoodCheck(prime, g) {\n console.error('Unsupported function `checkPrimeAndGoodCheck` call. Arguments:', prime, g)\n\n const goodPrimeBitsCount = 2048\n if (prime < 0 || prime.bitLength() !== goodPrimeBitsCount) {\n throw new Error(`bad prime count ${prime.bitLength()},expected ${goodPrimeBitsCount}`)\n }\n // TODO this is kinda slow\n if (Factorizator.factorize(prime)[0] !== 1) {\n throw new Error('give \"prime\" is not prime')\n }\n if (g.eq(BigInt(2))) {\n if ((prime.remainder(BigInt(8))).neq(BigInt(7))) {\n throw new Error(`bad g ${g}, mod8 ${prime % 8}`)\n }\n } else if (g.eq(BigInt(3))) {\n if ((prime.remainder(BigInt(3))).neq(BigInt(2))) {\n throw new Error(`bad g ${g}, mod3 ${prime % 3}`)\n }\n // eslint-disable-next-line no-empty\n } else if (g.eq(BigInt(4))) {\n\n } else if (g.eq(BigInt(5))) {\n if (!([ BigInt(1), BigInt(4) ].includes(prime.remainder(BigInt(5))))) {\n throw new Error(`bad g ${g}, mod8 ${prime % 5}`)\n }\n } else if (g.eq(BigInt(6))) {\n if (!([ BigInt(19), BigInt(23) ].includes(prime.remainder(BigInt(24))))) {\n throw new Error(`bad g ${g}, mod8 ${prime % 24}`)\n }\n } else if (g.eq(BigInt(7))) {\n if (!([ BigInt(3), BigInt(5), BigInt(6) ].includes(prime.remainder(BigInt(7))))) {\n throw new Error(`bad g ${g}, mod8 ${prime % 7}`)\n }\n } else {\n throw new Error(`bad g ${g}`)\n }\n const primeSub1Div2 = (prime.subtract(BigInt(1))).divide(BigInt(2))\n if (Factorizator.factorize(primeSub1Div2)[0] !== 1) {\n throw new Error('(prime - 1) // 2 is not prime')\n }\n}\n*/\n/**\n *\n * @param primeBytes{Buffer}\n * @param g{number}\n */\nfunction checkPrimeAndGood(primeBytes, g) {\n const goodPrime = Buffer.from([\n 0xC7, 0x1C, 0xAE, 0xB9, 0xC6, 0xB1, 0xC9, 0x04, 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 { RPCError } = require('../errors');\n\nconst MtProtoPlainSender = require('./MTProtoPlainSender');\nconst MTProtoState = require('./MTProtoState');\nconst Helpers = require('../Helpers');\nconst AuthKey = require('../crypto/AuthKey');\nconst { doAuthentication } = require('./Authenticator');\nconst RPCResult = require('../tl/core/RPCResult');\nconst MessageContainer = require('../tl/core/MessageContainer');\nconst GZIPPacked = require('../tl/core/GZIPPacked');\nconst RequestState = require('./RequestState');\n\nconst {\n MsgsAck,\n upload,\n MsgsStateInfo,\n Pong,\n} = require('../tl').constructors;\nconst MessagePacker = require('../extensions/MessagePacker');\nconst BinaryReader = require('../extensions/BinaryReader');\nconst {\n UpdateConnectionState,\n UpdateServerTimeOffset,\n} = require('./index');\nconst { BadMessageError } = require('../errors/Common');\nconst {\n BadServerSalt,\n BadMsgNotification,\n MsgDetailedInfo,\n MsgNewDetailedInfo,\n NewSessionCreated,\n FutureSalts,\n MsgsStateReq,\n MsgResendReq,\n MsgsAllInfo,\n} = require('../tl').constructors;\nconst { SecurityError } = require('../errors/Common');\nconst { InvalidBufferError } = require('../errors/Common');\nconst { LogOut } = require('../tl').requests.auth;\nconst { RPCMessageToError } = require('../errors');\nconst { TypeNotFoundError } = require('../errors/Common');\n\n/**\n * MTProto Mobile Protocol sender\n * (https://core.telegram.org/mtproto/description)\n * This class is responsible for wrapping requests into `TLMessage`'s,\n * sending them over the network and receiving them in a safe manner.\n *\n * Automatic reconnection due to temporary network issues is a concern\n * for this class as well, including retry of messages that could not\n * be sent successfully.\n *\n * A new authorization key will be generated on connection if no other\n * key exists yet.\n */\nclass MTProtoSender {\n static DEFAULT_OPTIONS = {\n logger: undefined,\n retries: Infinity,\n delay: 2000,\n autoReconnect: true,\n connectTimeout: undefined,\n authKeyCallback: undefined,\n updateCallback: undefined,\n autoReconnectCallback: undefined,\n isMainSender: undefined,\n onConnectionBreak: undefined,\n };\n\n /**\n * @param authKey\n * @param opts\n */\n constructor(authKey, opts) {\n const args = { ...MTProtoSender.DEFAULT_OPTIONS, ...opts };\n this._connection = undefined;\n this._log = args.logger;\n this._dcId = args.dcId;\n this._retries = args.retries;\n this._delay = args.delay;\n this._autoReconnect = args.autoReconnect;\n this._connectTimeout = args.connectTimeout;\n this._authKeyCallback = args.authKeyCallback;\n this._updateCallback = args.updateCallback;\n this._autoReconnectCallback = args.autoReconnectCallback;\n this._isMainSender = args.isMainSender;\n this._onConnectionBreak = args.onConnectionBreak;\n\n /**\n * whether we disconnected ourself or telegram did it.\n */\n this.userDisconnected = false;\n\n /**\n * Whether the user has explicitly connected or disconnected.\n *\n * If a disconnection happens for any other reason and it\n * was *not* user action then the pending messages won't\n * be cleared but on explicit user disconnection all the\n * pending futures should be cancelled.\n */\n this._user_connected = false;\n this._reconnecting = false;\n this._disconnected = true;\n\n /**\n * We need to join the loops upon disconnection\n */\n this._send_loop_handle = undefined;\n this._recv_loop_handle = undefined;\n\n /**\n * Preserving the references of the AuthKey and state is important\n */\n this.authKey = authKey || new AuthKey();\n this._state = new MTProtoState(this.authKey, this._log);\n\n /**\n * Outgoing messages are put in a queue and sent in a batch.\n * Note that here we're also storing their ``_RequestState``.\n */\n this._send_queue = new MessagePacker(this._state, this._log);\n\n /**\n * Sent states are remembered until a response is received.\n */\n this._pending_state = {};\n\n /**\n * Responses must be acknowledged, and we can also batch these.\n */\n this._pending_ack = new Set();\n\n /**\n * Similar to pending_messages but only for the last acknowledges.\n * These can't go in pending_messages because no acknowledge for them\n * is received, but we may still need to resend their state on bad salts.\n */\n this._last_acks = [];\n\n /**\n * Jump table from response ID to method that handles it\n */\n\n this._handlers = {\n [RPCResult.CONSTRUCTOR_ID]: this._handleRPCResult.bind(this),\n [MessageContainer.CONSTRUCTOR_ID]: this._handleContainer.bind(this),\n [GZIPPacked.CONSTRUCTOR_ID]: this._handleGzipPacked.bind(this),\n [Pong.CONSTRUCTOR_ID]: this._handlePong.bind(this),\n [BadServerSalt.CONSTRUCTOR_ID]: this._handleBadServerSalt.bind(this),\n [BadMsgNotification.CONSTRUCTOR_ID]: this._handleBadNotification.bind(this),\n [MsgDetailedInfo.CONSTRUCTOR_ID]: this._handleDetailedInfo.bind(this),\n [MsgNewDetailedInfo.CONSTRUCTOR_ID]: this._handleNewDetailedInfo.bind(this),\n [NewSessionCreated.CONSTRUCTOR_ID]: this._handleNewSessionCreated.bind(this),\n [MsgsAck.CONSTRUCTOR_ID]: this._handleAck.bind(this),\n [FutureSalts.CONSTRUCTOR_ID]: this._handleFutureSalts.bind(this),\n [MsgsStateReq.CONSTRUCTOR_ID]: this._handleStateForgotten.bind(this),\n [MsgResendReq.CONSTRUCTOR_ID]: this._handleStateForgotten.bind(this),\n [MsgsAllInfo.CONSTRUCTOR_ID]: this._handleMsgAll.bind(this),\n };\n }\n\n // Public API\n\n /**\n * Connects to the specified given connection using the given auth key.\n * @param connection\n * @param [force]\n * @returns {Promise}\n */\n async connect(connection, force) {\n if (this._user_connected && !force) {\n this._log.info('User is already connected!');\n return false;\n }\n this.isConnecting = true;\n this._connection = connection;\n\n for (let attempt = 0; attempt < this._retries; attempt++) {\n try {\n await this._connect();\n if (this._updateCallback) {\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.connected));\n }\n break;\n } catch (err) {\n if (this._updateCallback && attempt === 0) {\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.disconnected));\n }\n this._log.error(`WebSocket connection failed attempt: ${attempt + 1}`);\n // eslint-disable-next-line no-console\n console.error(err);\n await Helpers.sleep(this._delay);\n }\n }\n this.isConnecting = false;\n return true;\n }\n\n isConnected() {\n return this._user_connected;\n }\n\n /**\n * Cleanly disconnects the instance from the network, cancels\n * all pending requests, and closes the send and receive loops.\n */\n async disconnect() {\n this.userDisconnected = true;\n await this._disconnect();\n }\n\n /**\n *\n This method enqueues the given request to be sent. Its send\n state will be saved until a response arrives, and a ``Future``\n that will be resolved when the response arrives will be returned:\n\n .. code-block:: javascript\n\n async def method():\n # Sending (enqueued for the send loop)\n future = sender.send(request)\n # Receiving (waits for the receive loop to read the result)\n result = await future\n\n Designed like this because Telegram may send the response at\n any point, and it can send other items while one waits for it.\n Once the response for this future arrives, it is set with the\n received result, quite similar to how a ``receive()`` call\n would otherwise work.\n\n Since the receiving part is \"built in\" the future, it's\n impossible to await receive a result that was never sent.\n * @param request\n * @returns {RequestState}\n */\n send(request) {\n if (!this._user_connected) {\n throw new Error('Cannot send requests while disconnected');\n }\n const state = new RequestState(request);\n this._send_queue.append(state);\n return state.promise;\n }\n\n /**\n * Same as send but returns the full state. usefull for invoke after logic\n * @param request\n * @return {RequestState}\n */\n sendWithInvokeSupport(request) {\n if (!this._user_connected) {\n throw new Error('Cannot send requests while disconnected');\n }\n const state = new RequestState(request, undefined, this._pending_state);\n this._send_queue.append(state);\n return state;\n }\n\n /**\n * Performs the actual connection, retrying, generating the\n * authorization key if necessary, and starting the send and\n * receive loops.\n * @returns {Promise}\n * @private\n */\n async _connect() {\n this._log.info('Connecting to {0}...'.replace('{0}', this._connection));\n await this._connection.connect();\n this._log.debug('Connection success!');\n // process.exit(0)\n if (!this.authKey.getKey()) {\n const plain = new MtProtoPlainSender(this._connection, this._log);\n this._log.debug('New auth_key attempt ...');\n const res = await doAuthentication(plain, this._log);\n this._log.debug('Generated new auth_key successfully');\n await this.authKey.setKey(res.authKey);\n\n this._state.timeOffset = res.timeOffset;\n\n if (this._updateCallback) {\n this._updateCallback(new UpdateServerTimeOffset(this._state.timeOffset));\n }\n\n /**\n * This is *EXTREMELY* important since we don't control\n * external references to the authorization key, we must\n * notify whenever we change it. This is crucial when we\n * switch to different data centers.\n */\n if (this._authKeyCallback) {\n await this._authKeyCallback(this.authKey, this._dcId);\n }\n } else {\n this._authenticated = true;\n this._log.debug('Already have an auth key ...');\n }\n this._user_connected = true;\n this._reconnecting = false;\n\n this._log.debug('Starting send loop');\n this._send_loop_handle = this._sendLoop();\n\n this._log.debug('Starting receive loop');\n this._recv_loop_handle = this._recvLoop();\n\n // _disconnected only completes after manual disconnection\n // or errors after which the sender cannot continue such\n // as failing to reconnect or any unexpected error.\n\n this._log.info('Connection to %s complete!'.replace('%s', this._connection.toString()));\n }\n\n async _disconnect() {\n this._send_queue.rejectAll();\n\n if (this._connection === undefined) {\n this._log.info('Not disconnecting (already have no connection)');\n return;\n }\n if (this._updateCallback) {\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.disconnected));\n }\n this._log.info('Disconnecting from %s...'.replace('%s', this._connection.toString()));\n this._user_connected = false;\n this._log.debug('Closing current connection...');\n await this._connection.disconnect();\n }\n\n /**\n * This loop is responsible for popping items off the send\n * queue, encrypting them, and sending them over the network.\n * Besides `connect`, only this method ever sends data.\n * @returns {Promise}\n * @private\n */\n async _sendLoop() {\n this._send_queue = new MessagePacker(this._state, this._log);\n\n while (this._user_connected && !this._reconnecting) {\n if (this._pending_ack.size) {\n const ack = new RequestState(new MsgsAck({ msgIds: Array(...this._pending_ack) }));\n this._send_queue.append(ack);\n this._last_acks.push(ack);\n if (this._last_acks.length >= 10) {\n this._last_acks.shift();\n }\n this._pending_ack.clear();\n }\n this._log.debug(`Waiting for messages to send...${this._reconnecting}`);\n // TODO Wait for the connection send queue to be empty?\n // This means that while it's not empty we can wait for\n // more messages to be added to the send queue.\n const res = await this._send_queue.get();\n\n if (this._reconnecting) {\n return;\n }\n\n if (!res) {\n continue;\n }\n let { data } = res;\n const { batch } = res;\n this._log.debug(`Encrypting ${batch.length} message(s) in ${data.length} bytes for sending`);\n\n data = await this._state.encryptMessageData(data);\n\n try {\n await this._connection.send(data);\n } catch (e) {\n this._log.error(e);\n this._log.info('Connection closed while sending data');\n return;\n }\n for (const state of batch) {\n if (!Array.isArray(state)) {\n if (state.request.classType === 'request') {\n this._pending_state[state.msgId] = state;\n }\n } else {\n for (const s of state) {\n if (s.request.classType === 'request') {\n this._pending_state[s.msgId] = s;\n }\n }\n }\n }\n this._log.debug('Encrypted messages put in a queue to be sent');\n }\n }\n\n async _recvLoop() {\n let body;\n let message;\n\n while (this._user_connected && !this._reconnecting) {\n // this._log.debug('Receiving items from the network...');\n this._log.debug('Receiving items from the network...');\n try {\n body = await this._connection.recv();\n } catch (e) {\n // this._log.info('Connection closed while receiving data');\n /** when the server disconnects us we want to reconnect */\n if (!this.userDisconnected) {\n this._log.error(e);\n this._log.warn('Connection closed while receiving data');\n this.reconnect();\n }\n return;\n }\n try {\n message = await this._state.decryptMessageData(body);\n } catch (e) {\n if (e instanceof TypeNotFoundError) {\n // Received object which we don't know how to deserialize\n this._log.info(`Type ${e.invalidConstructorId} not found, remaining data ${e.remaining}`);\n continue;\n } else if (e instanceof SecurityError) {\n // A step while decoding had the incorrect data. This message\n // should not be considered safe and it should be ignored.\n this._log.warn(`Security error while unpacking a received message: ${e}`);\n continue;\n } else if (e instanceof InvalidBufferError) {\n // 404 means that the server has \"forgotten\" our auth key and we need to create a new one.\n if (e.code === 404) {\n this._handleBadAuthKey();\n } else {\n // this happens sometimes when telegram is having some internal issues.\n // reconnecting should be enough usually\n // since the data we sent and received is probably wrong now.\n this._log.warn(`Invalid buffer ${e.code} for dc ${this._dcId}`);\n this.reconnect();\n }\n return;\n } else {\n this._log.error('Unhandled error while receiving data');\n this._log.error(e);\n this.reconnect();\n return;\n }\n }\n try {\n await this._processMessage(message);\n } catch (e) {\n // `RPCError` errors except for 'AUTH_KEY_UNREGISTERED' should be handled by the client\n if (e instanceof RPCError) {\n if (e.message === 'AUTH_KEY_UNREGISTERED') {\n // 'AUTH_KEY_UNREGISTERED' for the main sender is thrown when unauthorized and should be ignored\n this._handleBadAuthKey(true);\n }\n } else {\n this._log.error('Unhandled error while receiving data');\n this._log.error(e);\n }\n }\n }\n }\n\n _handleBadAuthKey(shouldSkipForMain) {\n if (shouldSkipForMain && this._isMainSender) {\n return;\n }\n\n this._log.warn(`Broken authorization key for dc ${this._dcId}, resetting...`);\n\n if (this._isMainSender && this._updateCallback) {\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.broken));\n } else if (!this._isMainSender && this._onConnectionBreak) {\n this._onConnectionBreak(this._dcId);\n }\n }\n\n // Response Handlers\n\n /**\n * Adds the given message to the list of messages that must be\n * acknowledged and dispatches control to different ``_handle_*``\n * method based on its type.\n * @param message\n * @returns {Promise}\n * @private\n */\n async _processMessage(message) {\n this._pending_ack.add(message.msgId);\n // eslint-disable-next-line require-atomic-updates\n message.obj = await message.obj;\n let handler = this._handlers[message.obj.CONSTRUCTOR_ID];\n if (!handler) {\n handler = this._handleUpdate.bind(this);\n }\n\n await handler(message);\n }\n\n /**\n * Pops the states known to match the given ID from pending messages.\n * This method should be used when the response isn't specific.\n * @param msgId\n * @returns {*[]}\n * @private\n */\n _popStates(msgId) {\n let state = this._pending_state[msgId];\n if (state) {\n this._pending_state[msgId].deferred.resolve();\n delete this._pending_state[msgId];\n return [state];\n }\n\n const toPop = [];\n\n for (state of Object.values(this._pending_state)) {\n if (state.containerId && state.containerId.equals(msgId)) {\n toPop.push(state.msgId);\n }\n }\n\n if (toPop.length) {\n const temp = [];\n for (const x of toPop) {\n temp.push(this._pending_state[x]);\n this._pending_state[x].deferred.resolve();\n delete this._pending_state[x];\n }\n return temp;\n }\n\n for (const ack of this._last_acks) {\n if (ack.msgId === msgId) {\n return [ack];\n }\n }\n\n return [];\n }\n\n /**\n * Handles the result for Remote Procedure Calls:\n * rpc_result#f35c6d01 req_msg_id:long result:bytes = RpcResult;\n * This is where the future results for sent requests are set.\n * @param message\n * @returns {Promise}\n * @private\n */\n _handleRPCResult(message) {\n const result = message.obj;\n const state = this._pending_state[result.reqMsgId];\n if (state) {\n state.deferred.resolve();\n delete this._pending_state[result.reqMsgId];\n }\n this._log.debug(`Handling RPC result for message ${result.reqMsgId}`);\n\n if (!state) {\n // TODO We should not get responses to things we never sent\n // However receiving a File() with empty bytes is \"common\".\n // See #658, #759 and #958. They seem to happen in a container\n // which contain the real response right after.\n try {\n const reader = new BinaryReader(result.body);\n if (!(reader.tgReadObject() instanceof upload.File)) {\n throw new TypeNotFoundError('Not an upload.File');\n }\n } catch (e) {\n this._log.error(e);\n if (e instanceof TypeNotFoundError) {\n this._log.info(`Received response without parent request: ${result.body}`);\n return;\n } else {\n throw e;\n }\n }\n }\n if (result.error) {\n // eslint-disable-next-line new-cap\n const error = RPCMessageToError(result.error, state.request);\n this._send_queue.append(new RequestState(new MsgsAck({ msgIds: [state.msgId] })));\n state.reject(error);\n throw error;\n } else {\n try {\n const reader = new BinaryReader(result.body);\n const read = state.request.readResult(reader);\n state.resolve(read);\n } catch (err) {\n state.reject(err);\n throw err;\n }\n }\n }\n\n /**\n * Processes the inner messages of a container with many of them:\n * msg_container#73f1f8dc messages:vector<%Message> = MessageContainer;\n * @param message\n * @returns {Promise}\n * @private\n */\n async _handleContainer(message) {\n this._log.debug('Handling container');\n for (const innerMessage of message.obj.messages) {\n await this._processMessage(innerMessage);\n }\n }\n\n /**\n * Unpacks the data from a gzipped object and processes it:\n * gzip_packed#3072cfa1 packed_data:bytes = Object;\n * @param message\n * @returns {Promise}\n * @private\n */\n async _handleGzipPacked(message) {\n this._log.debug('Handling gzipped data');\n const reader = new BinaryReader(message.obj.data);\n message.obj = reader.tgReadObject();\n await this._processMessage(message);\n }\n\n _handleUpdate(message) {\n if (message.obj.SUBCLASS_OF_ID !== 0x8af52aac) {\n // crc32(b'Updates')\n this._log.warn(`Note: ${message.obj.className} is not an update, not dispatching it`);\n return;\n }\n this._log.debug(`Handling update ${message.obj.className}`);\n if (this._updateCallback) {\n this._updateCallback(message.obj);\n }\n }\n\n /**\n * Handles pong results, which don't come inside a ``RPCResult``\n * but are still sent through a request:\n * pong#347773c5 msg_id:long ping_id:long = Pong;\n * @param message\n * @returns {Promise}\n * @private\n */\n _handlePong(message) {\n const pong = message.obj;\n\n const newTimeOffset = this._state.updateTimeOffset(message.msgId);\n if (this._updateCallback) {\n this._updateCallback(new UpdateServerTimeOffset(newTimeOffset));\n }\n\n this._log.debug(`Handling pong for message ${pong.msgId}`);\n const state = this._pending_state[pong.msgId];\n this._pending_state[pong.msgId].deferred.resolve();\n delete this._pending_state[pong.msgId];\n\n // Todo Check result\n if (state) {\n state.resolve(pong);\n }\n }\n\n /**\n * Corrects the currently used server salt to use the right value\n * before enqueuing the rejected message to be re-sent:\n * bad_server_salt#edab447b bad_msg_id:long bad_msg_seqno:int\n * error_code:int new_server_salt:long = BadMsgNotification;\n * @param message\n * @returns {Promise}\n * @private\n */\n _handleBadServerSalt(message) {\n const badSalt = message.obj;\n this._log.debug(`Handling bad salt for message ${badSalt.badMsgId}`);\n this._state.salt = badSalt.newServerSalt;\n const states = this._popStates(badSalt.badMsgId);\n this._send_queue.extend(states);\n this._log.debug(`${states.length} message(s) will be resent`);\n }\n\n /**\n * Adjusts the current state to be correct based on the\n * received bad message notification whenever possible:\n * bad_msg_notification#a7eff811 bad_msg_id:long bad_msg_seqno:int\n * error_code:int = BadMsgNotification;\n * @param message\n * @returns {Promise}\n * @private\n */\n _handleBadNotification(message) {\n const badMsg = message.obj;\n const states = this._popStates(badMsg.badMsgId);\n this._log.debug(`Handling bad msg ${JSON.stringify(badMsg)}`);\n if ([16, 17].includes(badMsg.errorCode)) {\n // Sent msg_id too low or too high (respectively).\n // Use the current msg_id to determine the right time offset.\n const newTimeOffset = this._state.updateTimeOffset(message.msgId);\n\n if (this._updateCallback) {\n this._updateCallback(new UpdateServerTimeOffset(newTimeOffset));\n }\n\n this._log.info(`System clock is wrong, set time offset to ${newTimeOffset}s`);\n } else if (badMsg.errorCode === 32) {\n // msg_seqno too low, so just pump it up by some \"large\" amount\n // TODO A better fix would be to start with a new fresh session ID\n this._state._sequence += 64;\n } else if (badMsg.errorCode === 33) {\n // msg_seqno too high never seems to happen but just in case\n this._state._sequence -= 16;\n } else {\n for (const state of states) {\n state.reject(new BadMessageError(state.request, badMsg.errorCode));\n }\n\n return;\n }\n // Messages are to be re-sent once we've corrected the issue\n this._send_queue.extend(states);\n this._log.debug(`${states.length} messages will be resent due to bad msg`);\n }\n\n /**\n * Updates the current status with the received detailed information:\n * msg_detailed_info#276d3ec6 msg_id:long answer_msg_id:long\n * bytes:int status:int = MsgDetailedInfo;\n * @param message\n * @returns {Promise}\n * @private\n */\n _handleDetailedInfo(message) {\n // TODO https://goo.gl/VvpCC6\n const msgId = message.obj.answerMsgId;\n this._log.debug(`Handling detailed info for message ${msgId}`);\n this._pending_ack.add(msgId);\n }\n\n /**\n * Updates the current status with the received detailed information:\n * msg_new_detailed_info#809db6df answer_msg_id:long\n * bytes:int status:int = MsgDetailedInfo;\n * @param message\n * @returns {Promise}\n * @private\n */\n _handleNewDetailedInfo(message) {\n // TODO https://goo.gl/VvpCC6\n const msgId = message.obj.answerMsgId;\n this._log.debug(`Handling new detailed info for message ${msgId}`);\n this._pending_ack.add(msgId);\n }\n\n /**\n * Updates the current status with the received session information:\n * new_session_created#9ec20908 first_msg_id:long unique_id:long\n * server_salt:long = NewSession;\n * @param message\n * @returns {Promise}\n * @private\n */\n _handleNewSessionCreated(message) {\n // TODO https://goo.gl/LMyN7A\n this._log.debug('Handling new session created');\n this._state.salt = message.obj.serverSalt;\n }\n\n /**\n * Handles a server acknowledge about our messages. Normally\n * these can be ignored except in the case of ``auth.logOut``:\n *\n * auth.logOut#5717da40 = Bool;\n *\n * Telegram doesn't seem to send its result so we need to confirm\n * it manually. No other request is known to have this behaviour.\n\n * Since the ID of sent messages consisting of a container is\n * never returned (unless on a bad notification), this method\n * also removes containers messages when any of their inner\n * messages are acknowledged.\n\n * @param message\n * @returns {Promise}\n * @private\n */\n _handleAck(message) {\n const ack = message.obj;\n this._log.debug(`Handling acknowledge for ${ack.msgIds}`);\n for (const msgId of ack.msgIds) {\n const state = this._pending_state[msgId];\n if (state && state.request instanceof LogOut) {\n this._pending_state[msgId].deferred.resolve();\n delete this._pending_state[msgId];\n state.resolve(true);\n }\n }\n }\n\n /**\n * Handles future salt results, which don't come inside a\n * ``rpc_result`` but are still sent through a request:\n * future_salts#ae500895 req_msg_id:long now:int\n * salts:vector = FutureSalts;\n * @param message\n * @returns {Promise}\n * @private\n */\n _handleFutureSalts(message) {\n // TODO save these salts and automatically adjust to the\n // correct one whenever the salt in use expires.\n this._log.debug(`Handling future salts for message ${message.msgId}`);\n const state = this._pending_state[message.msgId];\n\n if (state) {\n this._pending_state[message].deferred.resolve();\n delete this._pending_state[message];\n state.resolve(message.obj);\n }\n }\n\n /**\n * Handles both :tl:`MsgsStateReq` and :tl:`MsgResendReq` by\n * enqueuing a :tl:`MsgsStateInfo` to be sent at a later point.\n * @param message\n * @returns {Promise}\n * @private\n */\n _handleStateForgotten(message) {\n this._send_queue.append(\n new RequestState(new MsgsStateInfo(message.msgId, String.fromCharCode(1)\n .repeat(message.obj.msgIds))),\n );\n }\n\n /**\n * Handles :tl:`MsgsAllInfo` by doing nothing (yet).\n * used as part of the telegram protocol https://core.telegram.org/mtproto/service_messages_about_messages\n * This message does not require an acknowledgment.\n * @param message\n * @returns {Promise}\n * @private\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _handleMsgAll(message) {\n }\n\n reconnect() {\n if (this._user_connected && !this._reconnecting) {\n this._reconnecting = true;\n // TODO Should we set this?\n // this._user_connected = false\n // we want to wait a second between each reconnect try to not flood the server with reconnects\n // in case of internal server issues.\n Helpers.sleep(1000)\n .then(() => {\n this._log.info('Started reconnecting');\n this._reconnect();\n });\n }\n }\n\n async _reconnect() {\n this._log.debug('Closing current connection...');\n try {\n await this._disconnect();\n } catch (err) {\n this._log.warn(err);\n }\n\n this._send_queue.append(undefined);\n this._state.reset();\n\n // For some reason reusing existing connection caused stuck requests\n const newConnection = new this._connection.constructor(\n this._connection._ip,\n this._connection._port,\n this._connection._dcId,\n this._connection._log,\n this._connection._testServers,\n );\n await this.connect(newConnection, true);\n\n this._reconnecting = false;\n // uncomment this if you want to resend\n // this._send_queue.extend(Object.values(this._pending_state))\n for (const state of Object.values(this._pending_state)) {\n state.deferred.resolve();\n }\n this._pending_state = {};\n if (this._autoReconnectCallback) {\n await this._autoReconnectCallback();\n }\n }\n}\n\nmodule.exports = MTProtoSender;\n","const BigInt = require('big-integer');\n\nconst Helpers = require('../Helpers');\nconst IGE = require('../crypto/IGE');\nconst BinaryReader = require('../extensions/BinaryReader');\nconst GZIPPacked = require('../tl/core/GZIPPacked');\nconst { TLMessage } = require('../tl/core');\nconst {\n SecurityError,\n InvalidBufferError,\n} = require('../errors/Common');\nconst { InvokeAfterMsg } = require('../tl').requests;\nconst {\n toSignedLittleBuffer,\n} = require('../Helpers');\n\nclass MTProtoState {\n /**\n *\n `telethon.network.mtprotosender.MTProtoSender` needs to hold a state\n in order to be able to encrypt and decrypt incoming/outgoing messages,\n as well as generating the message IDs. Instances of this class hold\n together all the required information.\n\n It doesn't make sense to use `telethon.sessions.abstract.Session` for\n the sender because the sender should *not* be concerned about storing\n this information to disk, as one may create as many senders as they\n desire to any other data center, or some CDN. Using the same session\n for all these is not a good idea as each need their own authkey, and\n the concept of \"copying\" sessions with the unnecessary entities or\n updates state for these connections doesn't make sense.\n\n While it would be possible to have a `MTProtoPlainState` that does no\n encryption so that it was usable through the `MTProtoLayer` and thus\n avoid the need for a `MTProtoPlainSender`, the `MTProtoLayer` is more\n focused to efficiency and this state is also more advanced (since it\n supports gzipping and invoking after other message IDs). There are too\n many methods that would be needed to make it convenient to use for the\n authentication process, at which point the `MTProtoPlainSender` is better\n * @param authKey\n * @param loggers\n */\n constructor(authKey, loggers) {\n this.authKey = authKey;\n this._log = loggers;\n this.timeOffset = 0;\n this.salt = 0;\n\n this.id = undefined;\n this._sequence = undefined;\n this._lastMsgId = undefined;\n this.msgIds = [];\n this.reset();\n }\n\n /**\n * Resets the state\n */\n reset() {\n // Session IDs can be random on every connection\n this.id = Helpers.generateRandomLong(true);\n this._sequence = 0;\n this._lastMsgId = BigInt(0);\n this.msgIds = [];\n }\n\n /**\n * Updates the message ID to a new one,\n * used when the time offset changed.\n * @param message\n */\n updateMessageId(message) {\n message.msgId = this._getNewMsgId();\n }\n\n /**\n * Calculate the key based on Telegram guidelines, specifying whether it's the client or not\n * @param authKey\n * @param msgKey\n * @param client\n * @returns {{iv: Buffer, key: Buffer}}\n */\n async _calcKey(authKey, msgKey, client) {\n const x = client === true ? 0 : 8;\n const [sha256a, sha256b] = await Promise.all([\n Helpers.sha256(Buffer.concat([msgKey, authKey.slice(x, x + 36)])),\n Helpers.sha256(Buffer.concat([authKey.slice(x + 40, x + 76), msgKey])),\n ]);\n const key = Buffer.concat([sha256a.slice(0, 8), sha256b.slice(8, 24), sha256a.slice(24, 32)]);\n const iv = Buffer.concat([sha256b.slice(0, 8), sha256a.slice(8, 24), sha256b.slice(24, 32)]);\n return {\n key,\n iv,\n };\n }\n\n /**\n * Writes a message containing the given data into buffer.\n * Returns the message id.\n * @param buffer\n * @param data\n * @param contentRelated\n * @param afterId\n */\n async writeDataAsMessage(buffer, data, contentRelated, afterId) {\n const msgId = this._getNewMsgId();\n const seqNo = this._getSeqNo(contentRelated);\n let body;\n if (!afterId) {\n body = await GZIPPacked.gzipIfSmaller(contentRelated, data);\n } else {\n // Invoke query expects a query with a getBytes func\n body = await GZIPPacked.gzipIfSmaller(contentRelated, new InvokeAfterMsg(afterId, {\n getBytes() {\n return data;\n },\n }).getBytes());\n }\n const s = Buffer.alloc(4);\n s.writeInt32LE(seqNo, 0);\n const b = Buffer.alloc(4);\n b.writeInt32LE(body.length, 0);\n const m = toSignedLittleBuffer(msgId, 8);\n buffer.write(Buffer.concat([m, s, b]));\n buffer.write(body);\n return msgId;\n }\n\n /**\n * Encrypts the given message data using the current authorization key\n * following MTProto 2.0 guidelines core.telegram.org/mtproto/description.\n * @param data\n */\n async encryptMessageData(data) {\n await this.authKey.waitForKey();\n const s = toSignedLittleBuffer(this.salt, 8);\n const i = toSignedLittleBuffer(this.id, 8);\n data = Buffer.concat([Buffer.concat([s, i]), data]);\n const padding = Helpers.generateRandomBytes(Helpers.mod(-(data.length + 12), 16) + 12);\n // Being substr(what, offset, length); x = 0 for client\n // \"msg_key_large = SHA256(substr(auth_key, 88+x, 32) + pt + padding)\"\n const msgKeyLarge = await Helpers.sha256(Buffer.concat([this.authKey.getKey()\n .slice(88, 88 + 32), data, padding]));\n // \"msg_key = substr (msg_key_large, 8, 16)\"\n const msgKey = msgKeyLarge.slice(8, 24);\n\n const {\n iv,\n key,\n } = await this._calcKey(this.authKey.getKey(), msgKey, true);\n\n const keyId = Helpers.readBufferFromBigInt(this.authKey.keyId, 8);\n return Buffer.concat([keyId, msgKey, new IGE(key, iv).encryptIge(Buffer.concat([data, padding]))]);\n }\n\n /**\n * Inverse of `encrypt_message_data` for incoming server messages.\n * @param body\n */\n async decryptMessageData(body) {\n if (body.length < 8) {\n throw new InvalidBufferError(body);\n }\n if (body.length < 0) { // length needs to be positive\n throw new SecurityError('Server replied with negative length');\n }\n if (body.length % 4 !== 0) {\n throw new SecurityError('Server replied with length not divisible by 4');\n }\n // TODO Check salt,sessionId, and sequenceNumber\n const keyId = Helpers.readBigIntFromBuffer(body.slice(0, 8));\n if (keyId.neq(this.authKey.keyId)) {\n throw new SecurityError('Server replied with an invalid auth key');\n }\n\n const msgKey = body.slice(8, 24);\n const {\n iv,\n key,\n } = await this._calcKey(this.authKey.getKey(), msgKey, false);\n body = new IGE(key, iv).decryptIge(body.slice(24));\n\n // https://core.telegram.org/mtproto/security_guidelines\n // Sections \"checking sha256 hash\" and \"message length\"\n\n const ourKey = await Helpers.sha256(Buffer.concat([this.authKey.getKey()\n .slice(96, 96 + 32), body]));\n\n if (!msgKey.equals(ourKey.slice(8, 24))) {\n throw new SecurityError('Received msg_key doesn\\'t match with expected one');\n }\n\n const reader = new BinaryReader(body);\n reader.readLong(); // removeSalt\n const serverId = reader.readLong();\n if (!serverId.eq(this.id)) {\n throw new SecurityError('Server replied with a wrong session ID');\n }\n\n const remoteMsgId = reader.readLong();\n // if we get a duplicate message id we should ignore it.\n if (this.msgIds.includes(remoteMsgId.toString())) {\n throw new SecurityError('Duplicate msgIds');\n }\n // we only store the latest 500 message ids from the server\n if (this.msgIds.length > 500) {\n this.msgIds.shift();\n }\n this.msgIds.push(remoteMsgId.toString());\n\n const remoteSequence = reader.readInt();\n const containerLen = reader.readInt(); // msgLen for the inner object, padding ignored\n const diff = body.length - containerLen;\n // We want to check if it's between 12 and 1024\n // https://core.telegram.org/mtproto/security_guidelines#checking-message-length\n if (diff < 12 || diff > 1024) {\n throw new SecurityError('Server replied with the wrong message padding');\n }\n\n // We could read msg_len bytes and use those in a new reader to read\n // the next TLObject without including the padding, but since the\n // reader isn't used for anything else after this, it's unnecessary.\n const obj = reader.tgReadObject();\n\n return new TLMessage(remoteMsgId, remoteSequence, obj);\n }\n\n /**\n * Generates a new unique message ID based on the current\n * time (in ms) since epoch, applying a known time offset.\n * @private\n */\n _getNewMsgId() {\n const now = new Date().getTime() / 1000 + this.timeOffset;\n const nanoseconds = Math.floor((now - Math.floor(now)) * 1e9);\n let newMsgId = (BigInt(Math.floor(now))\n .shiftLeft(BigInt(32))).or(BigInt(nanoseconds)\n .shiftLeft(BigInt(2)));\n if (this._lastMsgId.greaterOrEquals(newMsgId)) {\n newMsgId = this._lastMsgId.add(BigInt(4));\n }\n this._lastMsgId = newMsgId;\n return newMsgId;\n }\n\n /**\n * Updates the time offset to the correct\n * one given a known valid message ID.\n * @param correctMsgId {BigInteger}\n */\n updateTimeOffset(correctMsgId) {\n const bad = this._getNewMsgId();\n const old = this.timeOffset;\n const now = Math.floor(new Date().getTime() / 1000);\n const correct = correctMsgId.shiftRight(BigInt(32));\n this.timeOffset = correct - now;\n\n if (this.timeOffset !== old) {\n this._lastMsgId = BigInt(0);\n this._log.debug(\n `Updated time offset (old offset ${old}, bad ${bad}, good ${correctMsgId}, new ${this.timeOffset})`,\n );\n }\n\n return this.timeOffset;\n }\n\n /**\n * Generates the next sequence number depending on whether\n * it should be for a content-related query or not.\n * @param contentRelated\n * @private\n */\n _getSeqNo(contentRelated) {\n if (contentRelated) {\n const result = this._sequence * 2 + 1;\n this._sequence += 1;\n return result;\n } else {\n return this._sequence * 2;\n }\n }\n}\n\nmodule.exports = MTProtoState;\n","const { createDeferred } = require('../Helpers');\n\nclass RequestState {\n constructor(request, after = undefined, pending = {}) {\n this.containerId = undefined;\n this.msgId = undefined;\n this.request = request;\n this.data = request.getBytes();\n this.after = after;\n this.result = undefined;\n this.pending = pending;\n this.deferred = createDeferred();\n this.promise = new Promise((resolve, reject) => {\n this.resolve = resolve;\n this.reject = reject;\n });\n }\n\n isReady() {\n const state = this.pending[this.after.id];\n if (!state) {\n return true;\n }\n return state.deferred.promise;\n }\n}\n\nmodule.exports = RequestState;\n","const PromisedWebSockets = require('../../extensions/PromisedWebSockets');\nconst AsyncQueue = require('../../extensions/AsyncQueue');\n\n/**\n * The `Connection` class is a wrapper around ``asyncio.open_connection``.\n *\n * Subclasses will implement different transport modes as atomic operations,\n * which this class eases doing since the exposed interface simply puts and\n * gets complete data payloads to and from queues.\n *\n * The only error that will raise from send and receive methods is\n * ``ConnectionError``, which will raise when attempting to send if\n * the client is disconnected (includes remote disconnections).\n */\nclass Connection {\n PacketCodecClass = undefined;\n\n constructor(ip, port, dcId, loggers, testServers) {\n this._ip = ip;\n this._port = port;\n this._dcId = dcId;\n this._log = loggers;\n this._testServers = testServers;\n this._connected = false;\n this._sendTask = undefined;\n this._recvTask = undefined;\n this._codec = undefined;\n this._obfuscation = undefined; // TcpObfuscated and MTProxy\n this._sendArray = new AsyncQueue();\n this._recvArray = new AsyncQueue();\n // this.socket = new PromiseSocket(new Socket())\n\n this.socket = new PromisedWebSockets(this.disconnectCallback.bind(this));\n }\n\n async disconnectCallback() {\n await this.disconnect(true);\n }\n\n async _connect() {\n this._log.debug('Connecting');\n this._codec = new this.PacketCodecClass(this);\n await this.socket.connect(this._port, this._ip, this._testServers);\n this._log.debug('Finished connecting');\n // await this.socket.connect({host: this._ip, port: this._port});\n await this._initConn();\n }\n\n async connect() {\n await this._connect();\n this._connected = true;\n\n if (!this._sendTask) {\n this._sendTask = this._sendLoop();\n }\n this._recvTask = this._recvLoop();\n }\n\n async disconnect(fromCallback = false) {\n if (!this._connected) {\n return;\n }\n\n this._connected = false;\n void this._recvArray.push(undefined);\n if (!fromCallback) {\n await this.socket.close();\n }\n }\n\n async send(data) {\n if (!this._connected) {\n throw new Error('Not connected');\n }\n await this._sendArray.push(data);\n }\n\n async recv() {\n while (this._connected) {\n const result = await this._recvArray.pop();\n // null = sentinel value = keep trying\n if (result) {\n return result;\n }\n }\n throw new Error('Not connected');\n }\n\n async _sendLoop() {\n // TODO handle errors\n try {\n while (this._connected) {\n const data = await this._sendArray.pop();\n if (!data) {\n this._sendTask = undefined;\n return;\n }\n await this._send(data);\n }\n } catch (e) {\n this._log.info('The server closed the connection while sending');\n }\n }\n\n async _recvLoop() {\n let data;\n while (this._connected) {\n try {\n data = await this._recv();\n if (!data) {\n throw new Error('no data received');\n }\n } catch (e) {\n this._log.info('connection closed');\n // await this._recvArray.push()\n\n this.disconnect();\n return;\n }\n await this._recvArray.push(data);\n }\n }\n\n async _initConn() {\n if (this._codec.tag) {\n await this.socket.write(this._codec.tag);\n }\n }\n\n _send(data) {\n const encodedPacket = this._codec.encodePacket(data);\n this.socket.write(encodedPacket);\n }\n\n _recv() {\n return this._codec.readPacket(this.socket);\n }\n\n toString() {\n return `${this._ip}:${this._port}/${this.constructor.name.replace('Connection', '')}`;\n }\n}\n\nclass ObfuscatedConnection extends Connection {\n ObfuscatedIO = undefined;\n\n _initConn() {\n this._obfuscation = new this.ObfuscatedIO(this);\n this.socket.write(this._obfuscation.header);\n }\n\n _send(data) {\n this._obfuscation.write(this._codec.encodePacket(data));\n }\n\n _recv() {\n return this._codec.readPacket(this._obfuscation);\n }\n}\n\nclass PacketCodec {\n constructor(connection) {\n this._conn = connection;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n encodePacket(data) {\n throw new Error('Not Implemented');\n\n // Override\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n readPacket(reader) {\n // override\n throw new Error('Not Implemented');\n }\n}\n\nmodule.exports = {\n Connection,\n PacketCodec,\n ObfuscatedConnection,\n};\n","const BigInt = require('big-integer');\nconst { readBufferFromBigInt } = require('../../Helpers');\nconst {\n Connection,\n PacketCodec,\n} = require('./Connection');\n\nclass AbridgedPacketCodec extends PacketCodec {\n static tag = Buffer.from('ef', 'hex');\n\n static obfuscateTag = Buffer.from('efefefef', 'hex');\n\n constructor(props) {\n super(props);\n this.tag = AbridgedPacketCodec.tag;\n this.obfuscateTag = AbridgedPacketCodec.obfuscateTag;\n }\n\n encodePacket(data) {\n let length = data.length >> 2;\n if (length < 127) {\n const b = Buffer.alloc(1);\n b.writeUInt8(length, 0);\n length = b;\n } else {\n length = Buffer.concat([Buffer.from('7f', 'hex'), readBufferFromBigInt(BigInt(length), 3)]);\n }\n return Buffer.concat([length, data]);\n }\n\n async readPacket(reader) {\n const readData = await reader.read(1);\n let length = readData[0];\n if (length >= 127) {\n length = Buffer.concat([await reader.read(3), Buffer.alloc(1)])\n .readInt32LE(0);\n }\n\n return reader.read(length << 2);\n }\n}\n\n/**\n * This is the mode with the lowest overhead, as it will\n * only require 1 byte if the packet length is less than\n * 508 bytes (127 << 2, which is very common).\n */\nclass ConnectionTCPAbridged extends Connection {\n PacketCodecClass = AbridgedPacketCodec;\n}\n\nmodule.exports = {\n ConnectionTCPAbridged,\n AbridgedPacketCodec,\n};\n","const { generateRandomBytes } = require('../../Helpers');\nconst { ObfuscatedConnection } = require('./Connection');\nconst { AbridgedPacketCodec } = require('./TCPAbridged');\nconst CTR = require('../../crypto/CTR');\n\nclass ObfuscatedIO {\n header = undefined;\n\n constructor(connection) {\n this.connection = connection.socket;\n const res = this.initHeader(connection.PacketCodecClass);\n this.header = res.random;\n\n this._encrypt = res.encryptor;\n this._decrypt = res.decryptor;\n }\n\n initHeader(packetCodec) {\n // Obfuscated messages secrets cannot start with any of these\n const keywords = [Buffer.from('50567247', 'hex'), Buffer.from('474554', 'hex'),\n Buffer.from('504f5354', 'hex'), Buffer.from('eeeeeeee', 'hex')];\n let random;\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n random = generateRandomBytes(64);\n if (random[0] !== 0xef && !(random.slice(4, 8)\n .equals(Buffer.alloc(4)))) {\n let ok = true;\n for (const key of keywords) {\n if (key.equals(random.slice(0, 4))) {\n ok = false;\n break;\n }\n }\n if (ok) {\n break;\n }\n }\n }\n random = random.toJSON().data;\n\n const randomReversed = Buffer.from(random.slice(8, 56))\n .reverse();\n // Encryption has \"continuous buffer\" enabled\n const encryptKey = Buffer.from(random.slice(8, 40));\n const encryptIv = Buffer.from(random.slice(40, 56));\n const decryptKey = Buffer.from(randomReversed.slice(0, 32));\n const decryptIv = Buffer.from(randomReversed.slice(32, 48));\n const encryptor = new CTR(encryptKey, encryptIv);\n const decryptor = new CTR(decryptKey, decryptIv);\n\n random = Buffer.concat([\n Buffer.from(random.slice(0, 56)), packetCodec.obfuscateTag, Buffer.from(random.slice(60)),\n ]);\n random = Buffer.concat([\n Buffer.from(random.slice(0, 56)), Buffer.from(encryptor.encrypt(random)\n .slice(56, 64)), Buffer.from(random.slice(64)),\n ]);\n return {\n random,\n encryptor,\n decryptor,\n };\n }\n\n async read(n) {\n const data = await this.connection.readExactly(n);\n return this._decrypt.encrypt(data);\n }\n\n write(data) {\n this.connection.write(this._encrypt.encrypt(data));\n }\n}\n\nclass ConnectionTCPObfuscated extends ObfuscatedConnection {\n ObfuscatedIO = ObfuscatedIO;\n\n PacketCodecClass = AbridgedPacketCodec;\n}\n\nmodule.exports = {\n ConnectionTCPObfuscated,\n};\n","const { Connection } = require('./Connection');\nconst { ConnectionTCPFull } = require('./TCPFull');\nconst { ConnectionTCPAbridged } = require('./TCPAbridged');\nconst { ConnectionTCPObfuscated } = require('./TCPObfuscated');\n\nmodule.exports = {\n Connection,\n ConnectionTCPFull,\n ConnectionTCPAbridged,\n ConnectionTCPObfuscated,\n};\n","const MTProtoPlainSender = require('./MTProtoPlainSender');\nconst MTProtoSender = require('./MTProtoSender');\n\nclass UpdateConnectionState {\n static disconnected = -1;\n\n static connected = 1;\n\n static broken = 0;\n\n constructor(state) {\n this.state = state;\n }\n}\n\nclass UpdateServerTimeOffset {\n constructor(timeOffset) {\n this.timeOffset = timeOffset;\n }\n}\n\nconst {\n Connection,\n ConnectionTCPFull,\n ConnectionTCPAbridged,\n ConnectionTCPObfuscated,\n} = require('./connection');\n\nmodule.exports = {\n Connection,\n ConnectionTCPFull,\n ConnectionTCPAbridged,\n ConnectionTCPObfuscated,\n MTProtoPlainSender,\n MTProtoSender,\n UpdateConnectionState,\n UpdateServerTimeOffset,\n};\n","class Session {\n /**\n * Creates a clone of this session file\n * @param toInstance {Session|null}\n * @returns {Session}\n */\n\n /* CONTEST\n clone(toInstance = null) {\n return toInstance || new this.constructor()\n } */\n\n /**\n * Returns the currently-used data center ID.\n */\n get dcId() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Returns the server address where the library should connect to.\n */\n get serverAddress() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Returns the port to which the library should connect to.\n */\n get port() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Returns an ``AuthKey`` instance associated with the saved\n * data center, or `None` if a new one should be generated.\n */\n get authKey() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Sets the ``AuthKey`` to be used for the saved data center.\n * @param value\n */\n set authKey(value) {\n throw new Error('Not Implemented');\n }\n\n /**\n * Sets the information of the data center address and port that\n * the library should connect to, as well as the data center ID,\n * which is currently unused.\n * @param dcId {number}\n * @param serverAddress {string}\n * @param port {number}\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n setDC(dcId, serverAddress, port) {\n throw new Error('Not implemented');\n }\n\n /**\n * Returns an ID of the takeout process initialized for this session,\n * or `None` if there's no were any unfinished takeout requests.\n */\n /* CONTEST\n get takeoutId() {\n throw new Error('Not Implemented')\n }\n */\n /**\n * Sets the ID of the unfinished takeout process for this session.\n * @param value\n */\n /* CONTEST\n set takeoutId(value) {\n throw new Error('Not Implemented')\n }\n */\n /**\n * Returns the ``UpdateState`` associated with the given `entity_id`.\n * If the `entity_id` is 0, it should return the ``UpdateState`` for\n * no specific channel (the \"general\" state). If no state is known\n * it should ``return None``.\n * @param entityId\n */\n /* CONTEST\n getUpdateState(entityId) {\n throw new Error('Not Implemented')\n }\n\n */\n\n /**\n * Sets the given ``UpdateState`` for the specified `entity_id`, which\n * should be 0 if the ``UpdateState`` is the \"general\" state (and not\n * for any specific channel).\n * @param entityId\n * @param state\n */\n /* CONTEST\n setUpdateState(entityId, state) {\n throw new Error('Not Implemented')\n }\n\n */\n\n /**\n * Called on client disconnection. Should be used to\n * free any used resources. Can be left empty if none.\n */\n\n /* CONTEST\n close() {\n\n }\n\n */\n\n /**\n * called whenever important properties change. It should\n * make persist the relevant session information to disk.\n */\n save() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Called upon client.log_out(). Should delete the stored\n * information from disk since it's not valid anymore.\n */\n\n delete() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Lists available sessions. Not used by the library itself.\n */\n /* CONTEST\n listSessions() {\n throw new Error('Not Implemented')\n }\n\n */\n\n /**\n * Processes the input ``TLObject`` or ``list`` and saves\n * whatever information is relevant (e.g., ID or access hash).\n * @param tlo\n */\n /* CONTEST\n processEntities(tlo) {\n throw new Error('Not Implemented')\n }\n\n */\n\n /**\n * Turns the given key into an ``InputPeer`` (e.g. ``InputPeerUser``).\n * The library uses this method whenever an ``InputPeer`` is needed\n * to suit several purposes (e.g. user only provided its ID or wishes\n * to use a cached username to avoid extra RPC).\n */\n /* CONTEST\n getInputEntity(key) {\n throw new Error('Not Implemented')\n }\n\n */\n}\n\nmodule.exports = Session;\n","/* eslint-disable no-restricted-globals */\nconst StorageSession = require('./StorageSession');\n\nconst CACHE_NAME = 'GramJs';\n\nclass CacheApiSession extends StorageSession {\n async _delete() {\n const request = new Request(this._storageKey);\n const cache = await self.caches.open(CACHE_NAME);\n return cache.delete(request);\n }\n\n async _fetchFromCache() {\n const request = new Request(this._storageKey);\n const cache = await self.caches.open(CACHE_NAME);\n const cached = await cache.match(request);\n return cached ? cached.text() : undefined;\n }\n\n async _saveToCache(data) {\n const request = new Request(this._storageKey);\n const response = new Response(data);\n const cache = await self.caches.open(CACHE_NAME);\n return cache.put(request, response);\n }\n}\n\nmodule.exports = CacheApiSession;\n","const MemorySession = require('./Memory');\nconst AuthKey = require('../crypto/AuthKey');\nconst utils = require('../Utils');\n\nclass CallbackSession extends MemorySession {\n constructor(sessionData, callback) {\n super();\n\n this._sessionData = sessionData;\n this._callback = callback;\n\n this._authKeys = {};\n }\n\n get authKey() {\n throw new Error('Not supported');\n }\n\n set authKey(value) {\n throw new Error('Not supported');\n }\n\n async load() {\n if (!this._sessionData) {\n return;\n }\n\n const {\n mainDcId,\n keys,\n hashes,\n } = this._sessionData;\n const {\n ipAddress,\n port,\n } = utils.getDC(mainDcId);\n\n this.setDC(mainDcId, ipAddress, port, true);\n\n await Promise.all(Object.keys(keys)\n .map(async (dcId) => {\n const key = typeof keys[dcId] === 'string'\n ? Buffer.from(keys[dcId], 'hex')\n : Buffer.from(keys[dcId]);\n\n if (hashes[dcId]) {\n const hash = typeof hashes[dcId] === 'string'\n ? Buffer.from(hashes[dcId], 'hex')\n : Buffer.from(hashes[dcId]);\n\n this._authKeys[dcId] = new AuthKey(key, hash);\n } else {\n this._authKeys[dcId] = new AuthKey();\n await this._authKeys[dcId].setKey(key, true);\n }\n }));\n }\n\n setDC(dcId, serverAddress, port, skipOnUpdate = false) {\n this._dcId = dcId;\n this._serverAddress = serverAddress;\n this._port = port;\n\n delete this._authKeys[dcId];\n\n if (!skipOnUpdate) {\n void this._onUpdate();\n }\n }\n\n getAuthKey(dcId = this._dcId) {\n return this._authKeys[dcId];\n }\n\n setAuthKey(authKey, dcId = this._dcId) {\n this._authKeys[dcId] = authKey;\n\n void this._onUpdate();\n }\n\n getSessionData() {\n const sessionData = {\n mainDcId: this._dcId,\n keys: {},\n hashes: {},\n };\n\n Object\n .keys(this._authKeys)\n .forEach((dcId) => {\n const authKey = this._authKeys[dcId];\n if (!authKey || !authKey._key) return;\n\n sessionData.keys[dcId] = authKey._key.toString('hex');\n sessionData.hashes[dcId] = authKey._hash.toString('hex');\n });\n\n return sessionData;\n }\n\n _onUpdate() {\n this._callback(this.getSessionData());\n }\n\n delete() {\n this._callback(undefined);\n }\n}\n\nmodule.exports = CallbackSession;\n","const idb = require('idb-keyval');\nconst StorageSession = require('./StorageSession');\n\nconst CACHE_NAME = 'GramJs';\n\nclass IdbSession extends StorageSession {\n _delete() {\n return idb.del(`${CACHE_NAME}:${this._storageKey}`);\n }\n\n _fetchFromCache() {\n return idb.get(`${CACHE_NAME}:${this._storageKey}`);\n }\n\n _saveToCache(data) {\n return idb.set(`${CACHE_NAME}:${this._storageKey}`, data);\n }\n}\n\nmodule.exports = IdbSession;\n","const StorageSession = require('./StorageSession');\n\nclass LocalStorageSession extends StorageSession {\n _delete() {\n return localStorage.removeItem(this._storageKey);\n }\n\n _fetchFromCache() {\n return localStorage.getItem(this._storageKey);\n }\n\n _saveToCache(data) {\n return localStorage.setItem(this._storageKey, data);\n }\n}\n\nmodule.exports = LocalStorageSession;\n","const Session = require('./Abstract');\n\nclass MemorySession extends Session {\n constructor() {\n super();\n\n this._serverAddress = undefined;\n this._dcId = 0;\n this._port = undefined;\n this._takeoutId = undefined;\n\n this._entities = new Set();\n this._updateStates = {};\n }\n\n get dcId() {\n return this._dcId;\n }\n\n get serverAddress() {\n return this._serverAddress;\n }\n\n get port() {\n return this._port;\n }\n\n get authKey() {\n return this._authKey;\n }\n\n set authKey(value) {\n this._authKey = value;\n }\n\n setDC(dcId, serverAddress, port) {\n this._dcId = dcId | 0;\n this._serverAddress = serverAddress;\n this._port = port;\n }\n\n /* CONTEST\n get takeoutId() {\n return this._takeoutId\n }\n\n set takeoutId(value) {\n this._takeoutId = value\n }\n\n\n getUpdateState(entityId) {\n return this._updateStates[entityId]\n }\n\n setUpdateState(entityId, state) {\n return this._updateStates[entityId] = state\n }\n\n close() {\n }\n\n save() {\n }\n\n async load() {\n\n }\n\n delete() {\n }\n\n _entityValuesToRow(id, hash, username, phone, name) {\n // While this is a simple implementation it might be overrode by,\n // other classes so they don't need to implement the plural form\n // of the method. Don't remove.\n return [id, hash, username, phone, name]\n }\n\n _entityToRow(e) {\n if (!(e.classType === \"constructor\")) {\n return\n }\n let p\n let markedId\n try {\n p = utils.getInputPeer(e, false)\n markedId = utils.getPeerId(p)\n } catch (e) {\n // Note: `get_input_peer` already checks for non-zero `accessHash`.\n // See issues #354 and #392. It also checks that the entity\n // is not `min`, because its `accessHash` cannot be used\n // anywhere (since layer 102, there are two access hashes).\n return\n }\n let pHash\n if (p instanceof types.InputPeerUser || p instanceof types.InputPeerChannel) {\n pHash = p.accessHash\n } else if (p instanceof types.InputPeerChat) {\n pHash = 0\n } else {\n return\n }\n\n let username = e.username\n if (username) {\n username = username.toLowerCase()\n }\n const phone = e.phone\n const name = utils.getDisplayName(e)\n return this._entityValuesToRow(markedId, pHash, username, phone, name)\n }\n\n _entitiesToRows(tlo) {\n let entities = []\n if (tlo.classType === \"constructor\" && utils.isListLike(tlo)) {\n // This may be a list of users already for instance\n entities = tlo\n } else {\n if (tlo instanceof Object) {\n if ('user' in tlo) {\n entities.push(tlo.user)\n }\n if ('chats' in tlo && utils.isListLike(tlo.chats)) {\n entities.concat(tlo.chats)\n }\n if ('users' in tlo && utils.isListLike(tlo.users)) {\n entities.concat(tlo.users)\n }\n }\n }\n const rows = [] // Rows to add (id, hash, username, phone, name)\n for (const e of entities) {\n const row = this._entityToRow(e)\n if (row) {\n rows.push(row)\n }\n }\n return rows\n }\n\n processEntities(tlo) {\n const entitiesSet = this._entitiesToRows(tlo)\n for (const e of entitiesSet) {\n this._entities.add(e)\n }\n }\n\n getEntityRowsByPhone(phone) {\n for (const e of this._entities) { // id, hash, username, phone, name\n if (e[3] === phone) {\n return [e[0], e[1]]\n }\n }\n }\n\n getEntityRowsByUsername(username) {\n for (const e of this._entities) { // id, hash, username, phone, name\n if (e[2] === username) {\n return [e[0], e[1]]\n }\n }\n }\n\n getEntityRowsByName(name) {\n for (const e of this._entities) { // id, hash, username, phone, name\n if (e[4] === name) {\n return [e[0], e[1]]\n }\n }\n }\n\n getEntityRowsById(id, exact = true) {\n if (exact) {\n for (const e of this._entities) { // id, hash, username, phone, name\n if (e[0] === id) {\n return [e[0], e[1]]\n }\n }\n } else {\n const ids = [utils.getPeerId(new types.PeerUser({ userId: id })),\n utils.getPeerId(new types.PeerChat({ chatId: id })),\n utils.getPeerId(new types.PeerChannel({ channelId: id })),\n ]\n for (const e of this._entities) { // id, hash, username, phone, name\n if (ids.includes(e[0])) {\n return [e[0], e[1]]\n }\n }\n }\n }\n\n getInputEntity(key) {\n let exact\n if (key.SUBCLASS_OF_ID !== undefined) {\n if ([0xc91c90b6, 0xe669bf46, 0x40f202fd].includes(key.SUBCLASS_OF_ID)) {\n // hex(crc32(b'InputPeer', b'InputUser' and b'InputChannel'))\n // We already have an Input version, so nothing else required\n return key\n }\n // Try to early return if this key can be casted as input peer\n return utils.getInputPeer(key)\n } else {\n // Not a TLObject or can't be cast into InputPeer\n if (key.classType === 'constructor') {\n key = utils.getPeerId(key)\n exact = true\n } else {\n exact = !(typeof key == 'number') || key < 0\n }\n }\n let result = null\n if (typeof key === 'string') {\n const phone = utils.parsePhone(key)\n if (phone) {\n result = this.getEntityRowsByPhone(phone)\n } else {\n const { username, isInvite } = utils.parseUsername(key)\n if (username && !isInvite) {\n result = this.getEntityRowsByUsername(username)\n } else {\n const tup = utils.resolveInviteLink(key)[1]\n if (tup) {\n result = this.getEntityRowsById(tup, false)\n }\n }\n }\n } else if (typeof key === 'number') {\n result = this.getEntityRowsById(key, exact)\n }\n if (!result && typeof key === 'string') {\n result = this.getEntityRowsByName(key)\n }\n\n if (result) {\n let entityId = result[0] // unpack resulting tuple\n const entityHash = result[1]\n const resolved = utils.resolveId(entityId)\n entityId = resolved[0]\n const kind = resolved[1]\n // removes the mark and returns type of entity\n if (kind === types.PeerUser) {\n return new types.InputPeerUser({ userId: entityId, accessHash: entityHash })\n } else if (kind === types.PeerChat) {\n return new types.InputPeerChat({ chatId: entityId })\n } else if (kind === types.PeerChannel) {\n return new types.InputPeerChannel({ channelId: entityId, accessHash: entityHash })\n }\n } else {\n throw new Error('Could not find input entity with key ' + key)\n }\n } */\n}\n\nmodule.exports = MemorySession;\n","const MemorySession = require('./Memory');\nconst AuthKey = require('../crypto/AuthKey');\nconst utils = require('../Utils');\n\nconst STORAGE_KEY_BASE = 'GramJs-session-';\nconst SESSION_DATA_PREFIX = 'session:';\n\nclass StorageSession extends MemorySession {\n constructor(sessionInfo) {\n super();\n\n this._authKeys = {};\n\n if (sessionInfo && sessionInfo.startsWith(SESSION_DATA_PREFIX)) {\n this._sessionString = sessionInfo;\n } else if (sessionInfo) {\n this._storageKey = sessionInfo;\n }\n }\n\n get authKey() {\n throw new Error('Not supported');\n }\n\n set authKey(value) {\n throw new Error('Not supported');\n }\n\n async load() {\n if (this._sessionString) {\n await this._loadFromSessionString();\n return;\n }\n\n if (!this._storageKey) {\n return;\n }\n\n try {\n const json = await this._fetchFromCache();\n const {\n mainDcId,\n keys,\n hashes,\n } = JSON.parse(json);\n const {\n ipAddress,\n port,\n } = utils.getDC(mainDcId);\n\n this.setDC(mainDcId, ipAddress, port, true);\n\n Object.keys(keys)\n .forEach((dcId) => {\n if (keys[dcId] && hashes[dcId]) {\n this._authKeys[dcId] = new AuthKey(\n Buffer.from(keys[dcId].data),\n Buffer.from(hashes[dcId].data),\n );\n }\n });\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn('Failed to retrieve or parse session from storage');\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n }\n\n setDC(dcId, serverAddress, port, skipUpdateStorage = false) {\n this._dcId = dcId;\n this._serverAddress = serverAddress;\n this._port = port;\n\n delete this._authKeys[dcId];\n\n if (!skipUpdateStorage) {\n void this._updateStorage();\n }\n }\n\n async save() {\n if (!this._storageKey) {\n this._storageKey = generateStorageKey();\n }\n\n await this._updateStorage();\n\n return this._storageKey;\n }\n\n getAuthKey(dcId = this._dcId) {\n return this._authKeys[dcId];\n }\n\n setAuthKey(authKey, dcId = this._dcId) {\n this._authKeys[dcId] = authKey;\n\n void this._updateStorage();\n }\n\n getSessionData(asHex) {\n const sessionData = {\n mainDcId: this._dcId,\n keys: {},\n hashes: {},\n };\n\n Object\n .keys(this._authKeys)\n .forEach((dcId) => {\n const authKey = this._authKeys[dcId];\n if (!authKey._key) return;\n\n sessionData.keys[dcId] = asHex ? authKey._key.toString('hex') : authKey._key;\n sessionData.hashes[dcId] = asHex ? authKey._hash.toString('hex') : authKey._hash;\n });\n\n return sessionData;\n }\n\n async _loadFromSessionString() {\n const [, mainDcIdStr, mainDcKey] = this._sessionString.split(':');\n const mainDcId = Number(mainDcIdStr);\n const {\n ipAddress,\n port,\n } = utils.getDC(mainDcId);\n this.setDC(mainDcId, ipAddress, port);\n const authKey = new AuthKey();\n await authKey.setKey(Buffer.from(mainDcKey, 'hex'), true);\n this.setAuthKey(authKey, mainDcId);\n }\n\n async _updateStorage() {\n if (!this._storageKey) {\n return;\n }\n\n try {\n await this._saveToCache(JSON.stringify(this.getSessionData()));\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn('Failed to update session in storage');\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n }\n\n async delete() {\n try {\n return await this._delete();\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn('Failed to delete session from storage');\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n return undefined;\n }\n\n // @abstract\n _delete() {\n throw new Error('Not Implemented');\n }\n\n // @abstract\n _fetchFromCache() {\n throw new Error('Not Implemented');\n }\n\n // @abstract\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _saveToCache(data) {\n throw new Error('Not Implemented');\n }\n}\n\nfunction generateStorageKey() {\n // Creating two sessions at the same moment is not expected nor supported.\n return `${STORAGE_KEY_BASE}${Date.now()}`;\n}\n\nmodule.exports = StorageSession;\n","const MemorySession = require('./Memory');\nconst AuthKey = require('../crypto/AuthKey');\nconst BinaryReader = require('../extensions/BinaryReader');\n\nconst CURRENT_VERSION = '1';\n\n\nclass StringSession extends MemorySession {\n /**\n * This session file can be easily saved and loaded as a string. According\n * to the initial design, it contains only the data that is necessary for\n * successful connection and authentication, so takeout ID is not stored.\n\n * It is thought to be used where you don't want to create any on-disk\n * files but would still like to be able to save and load existing sessions\n * by other means.\n\n * You can use custom `encode` and `decode` functions, if present:\n\n * `encode` definition must be ``function encode(value: Buffer) -> string:``.\n * `decode` definition must be ``function decode(value: string) -> Buffer:``.\n * @param session {string|null}\n */\n constructor(session = undefined) {\n super();\n if (session) {\n if (session[0] !== CURRENT_VERSION) {\n throw new Error('Not a valid string');\n }\n session = session.slice(1);\n const r = StringSession.decode(session);\n const reader = new BinaryReader(r);\n this._dcId = reader.read(1)\n .readUInt8(0);\n const serverAddressLen = reader.read(2)\n .readInt16BE(0);\n this._serverAddress = String(reader.read(serverAddressLen));\n this._port = reader.read(2)\n .readInt16BE(0);\n this._key = reader.read(-1);\n }\n }\n\n /**\n * @param x {Buffer}\n * @returns {string}\n */\n static encode(x) {\n return x.toString('base64');\n }\n\n /**\n * @param x {string}\n * @returns {Buffer}\n */\n static decode(x) {\n return Buffer.from(x, 'base64');\n }\n\n async load() {\n if (this._key) {\n this._authKey = new AuthKey();\n await this._authKey.setKey(this._key);\n }\n }\n\n save() {\n if (!this.authKey) {\n return '';\n }\n const dcBuffer = Buffer.from([this.dcId]);\n const addressBuffer = Buffer.from(this.serverAddress);\n const addressLengthBuffer = Buffer.alloc(2);\n addressLengthBuffer.writeInt16BE(addressBuffer.length, 0);\n const portBuffer = Buffer.alloc(2);\n portBuffer.writeInt16BE(this.port, 0);\n\n return CURRENT_VERSION + StringSession.encode(Buffer.concat([\n dcBuffer,\n addressLengthBuffer,\n addressBuffer,\n portBuffer,\n this.authKey.getKey(),\n ]));\n }\n\n getAuthKey(dcId) {\n if (dcId && dcId !== this.dcId) {\n // Not supported.\n return undefined;\n }\n\n return this.authKey;\n }\n\n setAuthKey(authKey, dcId) {\n if (dcId && dcId !== this.dcId) {\n // Not supported.\n return;\n }\n\n this.authKey = authKey;\n }\n}\n\nmodule.exports = StringSession;\n","const Memory = require('./Memory');\nconst StringSession = require('./StringSession');\nconst CacheApiSession = require('./CacheApiSession');\nconst LocalStorageSession = require('./LocalStorageSession');\nconst IdbSession = require('./IdbSession');\nconst CallbackSession = require('./CallbackSession');\n\nmodule.exports = {\n Memory,\n StringSession,\n CacheApiSession,\n LocalStorageSession,\n IdbSession,\n CallbackSession,\n};\n","const api = require('./api');\n\nconst LAYER = 136;\nconst tlobjects = {};\n\nfor (const tl of Object.values(api)) {\n if (tl.CONSTRUCTOR_ID) {\n tlobjects[tl.CONSTRUCTOR_ID] = tl;\n } else {\n for (const sub of Object.values(tl)) {\n tlobjects[sub.CONSTRUCTOR_ID] = sub;\n }\n }\n}\n\nmodule.exports = {\n LAYER,\n tlobjects,\n};\n","const {\n parseTl,\n serializeBytes,\n serializeDate,\n} = require('./generationHelpers');\nconst {\n toSignedLittleBuffer,\n} = require('../Helpers');\n\nconst tlContent = require('./apiTl.js');\nconst schemeContent = require('./schemaTl.js');\n\n/* CONTEST\nconst NAMED_AUTO_CASTS = new Set([\n 'chatId,int'\n])\nconst NAMED_BLACKLIST = new Set([\n 'discardEncryption'\n])\nconst AUTO_CASTS = new Set([\n 'InputPeer',\n 'InputChannel',\n 'InputUser',\n 'InputDialogPeer',\n 'InputNotifyPeer',\n 'InputMedia',\n 'InputPhoto',\n 'InputMessage',\n 'InputDocument',\n 'InputChatPhoto'\n])\n\n */\n// eslint-disable-next-line no-restricted-globals\nconst CACHING_SUPPORTED = typeof self !== 'undefined' && self.localStorage !== undefined;\n\nconst CACHE_KEY = 'GramJs:apiCache';\n\nfunction buildApiFromTlSchema() {\n let definitions;\n const fromCache = CACHING_SUPPORTED && loadFromCache();\n\n if (fromCache) {\n definitions = fromCache;\n } else {\n definitions = loadFromTlSchemas();\n\n if (CACHING_SUPPORTED) {\n localStorage.setItem(CACHE_KEY, JSON.stringify(definitions));\n }\n }\n\n return mergeWithNamespaces(\n createClasses('constructor', definitions.constructors),\n createClasses('request', definitions.requests),\n );\n}\n\nfunction loadFromCache() {\n const jsonCache = localStorage.getItem(CACHE_KEY);\n return jsonCache && JSON.parse(jsonCache);\n}\n\nfunction loadFromTlSchemas() {\n const [constructorParamsApi, functionParamsApi] = extractParams(tlContent);\n const [constructorParamsSchema, functionParamsSchema] = extractParams(schemeContent);\n const constructors = [].concat(constructorParamsApi, constructorParamsSchema);\n const requests = [].concat(functionParamsApi, functionParamsSchema);\n\n return {\n constructors,\n requests,\n };\n}\n\nfunction mergeWithNamespaces(obj1, obj2) {\n const result = { ...obj1 };\n\n Object.keys(obj2)\n .forEach((key) => {\n if (typeof obj2[key] === 'function' || !result[key]) {\n result[key] = obj2[key];\n } else {\n Object.assign(result[key], obj2[key]);\n }\n });\n\n return result;\n}\n\nfunction extractParams(fileContent) {\n const f = parseTl(fileContent, 109);\n const constructors = [];\n const functions = [];\n for (const d of f) {\n if (d.isFunction) {\n functions.push(d);\n } else {\n constructors.push(d);\n }\n }\n return [constructors, functions];\n}\n\nfunction argToBytes(x, type) {\n switch (type) {\n case 'int': {\n const i = Buffer.alloc(4);\n i.writeInt32LE(x, 0);\n return i;\n }\n case 'long':\n return toSignedLittleBuffer(x, 8);\n case 'int128':\n return toSignedLittleBuffer(x, 16);\n case 'int256':\n return toSignedLittleBuffer(x, 32);\n case 'double': {\n const d = Buffer.alloc(8);\n d.writeDoubleLE(x, 0);\n return d;\n }\n case 'string':\n return serializeBytes(x);\n case 'Bool':\n return x ? Buffer.from('b5757299', 'hex') : Buffer.from('379779bc', 'hex');\n case 'true':\n return Buffer.alloc(0);\n case 'bytes':\n return serializeBytes(x);\n case 'date':\n return serializeDate(x);\n default:\n return x.getBytes();\n }\n}\n\n/*\nCONTEST\nasync function getInputFromResolve(utils, client, peer, peerType) {\n switch (peerType) {\n case 'InputPeer':\n return utils.getInputPeer(await client.getInputEntity(peer))\n case 'InputChannel':\n return utils.getInputChannel(await client.getInputEntity(peer))\n case 'InputUser':\n return utils.getInputUser(await client.getInputEntity(peer))\n case 'InputDialogPeer':\n return await client._getInputDialog(peer)\n case 'InputNotifyPeer':\n return await client._getInputNotify(peer)\n case 'InputMedia':\n return utils.getInputMedia(peer)\n case 'InputPhoto':\n return utils.getInputPhoto(peer)\n case 'InputMessage':\n return utils.getInputMessage(peer)\n case 'InputDocument':\n return utils.getInputDocument(peer)\n case 'InputChatPhoto':\n return utils.getInputChatPhoto(peer)\n case 'chatId,int' :\n return await client.getPeerId(peer, false)\n default:\n throw new Error('unsupported peer type : ' + peerType)\n }\n}\n*/\nfunction getArgFromReader(reader, arg) {\n if (arg.isVector) {\n if (arg.useVectorId) {\n reader.readInt();\n }\n const temp = [];\n const len = reader.readInt();\n arg.isVector = false;\n for (let i = 0; i < len; i++) {\n temp.push(getArgFromReader(reader, arg));\n }\n arg.isVector = true;\n return temp;\n } else if (arg.flagIndicator) {\n return reader.readInt();\n } else {\n switch (arg.type) {\n case 'int':\n return reader.readInt();\n case 'long':\n return reader.readLong();\n case 'int128':\n return reader.readLargeInt(128);\n case 'int256':\n return reader.readLargeInt(256);\n case 'double':\n return reader.readDouble();\n case 'string':\n return reader.tgReadString();\n case 'Bool':\n return reader.tgReadBool();\n case 'true':\n return true;\n case 'bytes':\n return reader.tgReadBytes();\n case 'date':\n return reader.tgReadDate();\n default:\n if (!arg.skipConstructorId) {\n return reader.tgReadObject();\n } else {\n throw new Error(`Unknown type ${arg}`);\n }\n }\n }\n}\n\nfunction createClasses(classesType, params) {\n const classes = {};\n for (const classParams of params) {\n const {\n name,\n constructorId,\n subclassOfId,\n argsConfig,\n namespace,\n result,\n } = classParams;\n const fullName = [namespace, name].join('.')\n .replace(/^\\./, '');\n\n class VirtualClass {\n static CONSTRUCTOR_ID = constructorId;\n\n static SUBCLASS_OF_ID = subclassOfId;\n\n static className = fullName;\n\n static classType = classesType;\n\n CONSTRUCTOR_ID = constructorId;\n\n SUBCLASS_OF_ID = subclassOfId;\n\n className = fullName;\n\n classType = classesType;\n\n constructor(args) {\n args = args || {};\n Object.keys(args)\n .forEach((argName) => {\n this[argName] = args[argName];\n });\n }\n\n static fromReader(reader) {\n const args = {};\n\n for (const argName in argsConfig) {\n if (argsConfig.hasOwnProperty(argName)) {\n const arg = argsConfig[argName];\n if (arg.isFlag) {\n if (arg.type === 'true') {\n args[argName] = Boolean(args.flags & (1 << arg.flagIndex));\n continue;\n }\n if (args.flags & (1 << arg.flagIndex)) {\n args[argName] = getArgFromReader(reader, arg);\n } else {\n args[argName] = undefined;\n }\n } else {\n if (arg.flagIndicator) {\n arg.name = 'flags';\n }\n args[argName] = getArgFromReader(reader, arg);\n }\n }\n }\n return new VirtualClass(args);\n }\n\n getBytes() {\n // The next is pseudo-code:\n const idForBytes = this.CONSTRUCTOR_ID;\n const c = Buffer.alloc(4);\n c.writeUInt32LE(idForBytes, 0);\n const buffers = [c];\n for (const arg in argsConfig) {\n if (argsConfig.hasOwnProperty(arg)) {\n if (argsConfig[arg].isFlag) {\n if ((this[arg] === false && argsConfig[arg].type === 'true')\n || this[arg] === undefined) {\n continue;\n }\n }\n if (argsConfig[arg].isVector) {\n if (argsConfig[arg].useVectorId) {\n buffers.push(Buffer.from('15c4b51c', 'hex'));\n }\n const l = Buffer.alloc(4);\n l.writeInt32LE(this[arg].length, 0);\n buffers.push(l, Buffer.concat(this[arg].map((x) => argToBytes(x, argsConfig[arg].type))));\n } else if (argsConfig[arg].flagIndicator) {\n if (!Object.values(argsConfig)\n .some((f) => f.isFlag)) {\n buffers.push(Buffer.alloc(4));\n } else {\n let flagCalculate = 0;\n for (const f in argsConfig) {\n if (argsConfig[f].isFlag) {\n if ((this[f] === false && argsConfig[f].type === 'true')\n || this[f] === undefined) {\n flagCalculate |= 0;\n } else {\n flagCalculate |= 1 << argsConfig[f].flagIndex;\n }\n }\n }\n const f = Buffer.alloc(4);\n f.writeUInt32LE(flagCalculate, 0);\n buffers.push(f);\n }\n } else {\n buffers.push(argToBytes(this[arg], argsConfig[arg].type));\n\n if (this[arg] && typeof this[arg].getBytes === 'function') {\n let boxed = (argsConfig[arg].type.charAt(argsConfig[arg].type.indexOf('.') + 1));\n boxed = boxed === boxed.toUpperCase();\n if (!boxed) {\n buffers.shift();\n }\n }\n }\n }\n }\n return Buffer.concat(buffers);\n }\n\n readResult(reader) {\n if (classesType !== 'request') {\n throw new Error('`readResult()` called for non-request instance');\n }\n\n const m = result.match(/Vector<(int|long)>/);\n if (m) {\n reader.readInt();\n const temp = [];\n const len = reader.readInt();\n if (m[1] === 'int') {\n for (let i = 0; i < len; i++) {\n temp.push(reader.readInt());\n }\n } else {\n for (let i = 0; i < len; i++) {\n temp.push(reader.readLong());\n }\n }\n return temp;\n } else {\n return reader.tgReadObject();\n }\n }\n\n /* CONTEST\n async resolve(client, utils) {\n\n if (classesType !== 'request') {\n throw new Error('`resolve()` called for non-request instance')\n }\n\n for (const arg in argsConfig) {\n if (argsConfig.hasOwnProperty(arg)) {\n if (!AUTO_CASTS.has(argsConfig[arg].type)) {\n if (!NAMED_AUTO_CASTS.has(`${argsConfig[arg].name},${argsConfig[arg].type}`)) {\n continue\n }\n }\n if (argsConfig[arg].isFlag) {\n if (!this[arg]) {\n continue\n }\n }\n if (argsConfig[arg].isVector) {\n const temp = []\n for (const x of this[arg]) {\n temp.push(await getInputFromResolve(utils, client, x, argsConfig[arg].type))\n }\n this[arg] = temp\n } else {\n this[arg] = await getInputFromResolve(utils, client, this[arg], argsConfig[arg].type)\n }\n }\n }\n } */\n }\n\n if (namespace) {\n if (!classes[namespace]) {\n classes[namespace] = {};\n }\n classes[namespace][name] = VirtualClass;\n } else {\n classes[name] = VirtualClass;\n }\n }\n\n return classes;\n}\n\nmodule.exports = buildApiFromTlSchema();\n","module.exports = `boolFalse#bc799737 = Bool;\nboolTrue#997275b5 = Bool;\ntrue#3fedd339 = True;\nvector#1cb5c415 {t:Type} # [ t ] = Vector t;\nerror#c4b9f9bb code:int text:string = Error;\nnull#56730bcc = Null;\ninputPeerEmpty#7f3b18ea = InputPeer;\ninputPeerSelf#7da07ec9 = InputPeer;\ninputPeerChat#35a95cb9 chat_id:long = InputPeer;\ninputPeerUser#dde8a54c user_id:long access_hash:long = InputPeer;\ninputPeerChannel#27bcbbfc channel_id:long access_hash:long = InputPeer;\ninputPeerUserFromMessage#a87b0a1c peer:InputPeer msg_id:int user_id:long = InputPeer;\ninputPeerChannelFromMessage#bd2a0840 peer:InputPeer msg_id:int channel_id:long = InputPeer;\ninputUserEmpty#b98886cf = InputUser;\ninputUserSelf#f7c1b13f = InputUser;\ninputUser#f21158c6 user_id:long access_hash:long = InputUser;\ninputUserFromMessage#1da448e2 peer:InputPeer msg_id:int user_id:long = InputUser;\ninputPhoneContact#f392b7f4 client_id:long phone:string first_name:string last_name:string = InputContact;\ninputFile#f52ff27f id:long parts:int name:string md5_checksum:string = InputFile;\ninputFileBig#fa4f0bb5 id:long parts:int name:string = InputFile;\ninputMediaEmpty#9664f57f = InputMedia;\ninputMediaUploadedPhoto#1e287d04 flags:# file:InputFile stickers:flags.0?Vector ttl_seconds:flags.1?int = InputMedia;\ninputMediaPhoto#b3ba0635 flags:# id:InputPhoto ttl_seconds:flags.0?int = InputMedia;\ninputMediaGeoPoint#f9c44144 geo_point:InputGeoPoint = InputMedia;\ninputMediaContact#f8ab7dfb phone_number:string first_name:string last_name:string vcard:string = InputMedia;\ninputMediaUploadedDocument#5b38c6c1 flags:# nosound_video:flags.3?true force_file:flags.4?true file:InputFile thumb:flags.2?InputFile mime_type:string attributes:Vector stickers:flags.0?Vector ttl_seconds:flags.1?int = InputMedia;\ninputMediaDocument#33473058 flags:# id:InputDocument ttl_seconds:flags.0?int query:flags.1?string = InputMedia;\ninputMediaVenue#c13d1c11 geo_point:InputGeoPoint title:string address:string provider:string venue_id:string venue_type:string = InputMedia;\ninputMediaPhotoExternal#e5bbfe1a flags:# url:string ttl_seconds:flags.0?int = InputMedia;\ninputMediaDocumentExternal#fb52dc99 flags:# url:string ttl_seconds:flags.0?int = InputMedia;\ninputMediaGame#d33f43f3 id:InputGame = InputMedia;\ninputMediaInvoice#d9799874 flags:# title:string description:string photo:flags.0?InputWebDocument invoice:Invoice payload:bytes provider:string provider_data:DataJSON start_param:flags.1?string = InputMedia;\ninputMediaGeoLive#971fa843 flags:# stopped:flags.0?true geo_point:InputGeoPoint heading:flags.2?int period:flags.1?int proximity_notification_radius:flags.3?int = InputMedia;\ninputMediaPoll#f94e5f1 flags:# poll:Poll correct_answers:flags.0?Vector solution:flags.1?string solution_entities:flags.1?Vector = InputMedia;\ninputMediaDice#e66fbf7b emoticon:string = InputMedia;\ninputChatPhotoEmpty#1ca48f57 = InputChatPhoto;\ninputChatUploadedPhoto#c642724e flags:# file:flags.0?InputFile video:flags.1?InputFile video_start_ts:flags.2?double = InputChatPhoto;\ninputChatPhoto#8953ad37 id:InputPhoto = InputChatPhoto;\ninputGeoPointEmpty#e4c123d6 = InputGeoPoint;\ninputGeoPoint#48222faf flags:# lat:double long:double accuracy_radius:flags.0?int = InputGeoPoint;\ninputPhotoEmpty#1cd7bf0d = InputPhoto;\ninputPhoto#3bb3b94a id:long access_hash:long file_reference:bytes = InputPhoto;\ninputFileLocation#dfdaabe1 volume_id:long local_id:int secret:long file_reference:bytes = InputFileLocation;\ninputEncryptedFileLocation#f5235d55 id:long access_hash:long = InputFileLocation;\ninputDocumentFileLocation#bad07584 id:long access_hash:long file_reference:bytes thumb_size:string = InputFileLocation;\ninputSecureFileLocation#cbc7ee28 id:long access_hash:long = InputFileLocation;\ninputTakeoutFileLocation#29be5899 = InputFileLocation;\ninputPhotoFileLocation#40181ffe id:long access_hash:long file_reference:bytes thumb_size:string = InputFileLocation;\ninputPhotoLegacyFileLocation#d83466f3 id:long access_hash:long file_reference:bytes volume_id:long local_id:int secret:long = InputFileLocation;\ninputPeerPhotoFileLocation#37257e99 flags:# big:flags.0?true peer:InputPeer photo_id:long = InputFileLocation;\ninputStickerSetThumb#9d84f3db stickerset:InputStickerSet thumb_version:int = InputFileLocation;\ninputGroupCallStream#598a92a flags:# call:InputGroupCall time_ms:long scale:int video_channel:flags.0?int video_quality:flags.0?int = InputFileLocation;\npeerUser#59511722 user_id:long = Peer;\npeerChat#36c6019a chat_id:long = Peer;\npeerChannel#a2a5371e channel_id:long = Peer;\nstorage.fileUnknown#aa963b05 = storage.FileType;\nstorage.filePartial#40bc6f52 = storage.FileType;\nstorage.fileJpeg#7efe0e = storage.FileType;\nstorage.fileGif#cae1aadf = storage.FileType;\nstorage.filePng#a4f63c0 = storage.FileType;\nstorage.filePdf#ae1e508d = storage.FileType;\nstorage.fileMp3#528a0677 = storage.FileType;\nstorage.fileMov#4b09ebbc = storage.FileType;\nstorage.fileMp4#b3cea0e4 = storage.FileType;\nstorage.fileWebp#1081464c = storage.FileType;\nuserEmpty#d3bc4b7a id:long = User;\nuser#3ff6ecb0 flags:# self:flags.10?true contact:flags.11?true mutual_contact:flags.12?true deleted:flags.13?true bot:flags.14?true bot_chat_history:flags.15?true bot_nochats:flags.16?true verified:flags.17?true restricted:flags.18?true min:flags.20?true bot_inline_geo:flags.21?true support:flags.23?true scam:flags.24?true apply_min_photo:flags.25?true fake:flags.26?true id:long access_hash:flags.0?long first_name:flags.1?string last_name:flags.2?string username:flags.3?string phone:flags.4?string photo:flags.5?UserProfilePhoto status:flags.6?UserStatus bot_info_version:flags.14?int restriction_reason:flags.18?Vector bot_inline_placeholder:flags.19?string lang_code:flags.22?string = User;\nuserProfilePhotoEmpty#4f11bae1 = UserProfilePhoto;\nuserProfilePhoto#82d1f706 flags:# has_video:flags.0?true photo_id:long stripped_thumb:flags.1?bytes dc_id:int = UserProfilePhoto;\nuserStatusEmpty#9d05049 = UserStatus;\nuserStatusOnline#edb93949 expires:int = UserStatus;\nuserStatusOffline#8c703f was_online:int = UserStatus;\nuserStatusRecently#e26f42f1 = UserStatus;\nuserStatusLastWeek#7bf09fc = UserStatus;\nuserStatusLastMonth#77ebc742 = UserStatus;\nchatEmpty#29562865 id:long = Chat;\nchat#41cbf256 flags:# creator:flags.0?true kicked:flags.1?true left:flags.2?true deactivated:flags.5?true call_active:flags.23?true call_not_empty:flags.24?true noforwards:flags.25?true id:long title:string photo:ChatPhoto participants_count:int date:int version:int migrated_to:flags.6?InputChannel admin_rights:flags.14?ChatAdminRights default_banned_rights:flags.18?ChatBannedRights = Chat;\nchatForbidden#6592a1a7 id:long title:string = Chat;\nchannel#8261ac61 flags:# creator:flags.0?true left:flags.2?true broadcast:flags.5?true verified:flags.7?true megagroup:flags.8?true restricted:flags.9?true signatures:flags.11?true min:flags.12?true scam:flags.19?true has_link:flags.20?true has_geo:flags.21?true slowmode_enabled:flags.22?true call_active:flags.23?true call_not_empty:flags.24?true fake:flags.25?true gigagroup:flags.26?true noforwards:flags.27?true id:long access_hash:flags.13?long title:string username:flags.6?string photo:ChatPhoto date:int restriction_reason:flags.9?Vector admin_rights:flags.14?ChatAdminRights banned_rights:flags.15?ChatBannedRights default_banned_rights:flags.18?ChatBannedRights participants_count:flags.17?int = Chat;\nchannelForbidden#17d493d5 flags:# broadcast:flags.5?true megagroup:flags.8?true id:long access_hash:long title:string until_date:flags.16?int = Chat;\nchatFull#d18ee226 flags:# can_set_username:flags.7?true has_scheduled:flags.8?true id:long about:string participants:ChatParticipants chat_photo:flags.2?Photo notify_settings:PeerNotifySettings exported_invite:flags.13?ExportedChatInvite bot_info:flags.3?Vector pinned_msg_id:flags.6?int folder_id:flags.11?int call:flags.12?InputGroupCall ttl_period:flags.14?int groupcall_default_join_as:flags.15?Peer theme_emoticon:flags.16?string requests_pending:flags.17?int recent_requesters:flags.17?Vector available_reactions:flags.18?Vector = ChatFull;\nchannelFull#e13c3d20 flags:# can_view_participants:flags.3?true can_set_username:flags.6?true can_set_stickers:flags.7?true hidden_prehistory:flags.10?true can_set_location:flags.16?true has_scheduled:flags.19?true can_view_stats:flags.20?true blocked:flags.22?true id:long about:string participants_count:flags.0?int admins_count:flags.1?int kicked_count:flags.2?int banned_count:flags.2?int online_count:flags.13?int read_inbox_max_id:int read_outbox_max_id:int unread_count:int chat_photo:Photo notify_settings:PeerNotifySettings exported_invite:flags.23?ExportedChatInvite bot_info:Vector migrated_from_chat_id:flags.4?long migrated_from_max_id:flags.4?int pinned_msg_id:flags.5?int stickerset:flags.8?StickerSet available_min_id:flags.9?int folder_id:flags.11?int linked_chat_id:flags.14?long location:flags.15?ChannelLocation slowmode_seconds:flags.17?int slowmode_next_send_date:flags.18?int stats_dc:flags.12?int pts:int call:flags.21?InputGroupCall ttl_period:flags.24?int pending_suggestions:flags.25?Vector groupcall_default_join_as:flags.26?Peer theme_emoticon:flags.27?string requests_pending:flags.28?int recent_requesters:flags.28?Vector default_send_as:flags.29?Peer available_reactions:flags.30?Vector = ChatFull;\nchatParticipant#c02d4007 user_id:long inviter_id:long date:int = ChatParticipant;\nchatParticipantCreator#e46bcee4 user_id:long = ChatParticipant;\nchatParticipantAdmin#a0933f5b user_id:long inviter_id:long date:int = ChatParticipant;\nchatParticipantsForbidden#8763d3e1 flags:# chat_id:long self_participant:flags.0?ChatParticipant = ChatParticipants;\nchatParticipants#3cbc93f8 chat_id:long participants:Vector version:int = ChatParticipants;\nchatPhotoEmpty#37c1011c = ChatPhoto;\nchatPhoto#1c6e1c11 flags:# has_video:flags.0?true photo_id:long stripped_thumb:flags.1?bytes dc_id:int = ChatPhoto;\nmessageEmpty#90a6ca84 flags:# id:int peer_id:flags.0?Peer = Message;\nmessage#38116ee0 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true post:flags.14?true from_scheduled:flags.18?true legacy:flags.19?true edit_hide:flags.21?true pinned:flags.24?true noforwards:flags.26?true id:int from_id:flags.8?Peer peer_id:Peer fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?long reply_to:flags.3?MessageReplyHeader date:int message:string media:flags.9?MessageMedia reply_markup:flags.6?ReplyMarkup entities:flags.7?Vector views:flags.10?int forwards:flags.10?int replies:flags.23?MessageReplies edit_date:flags.15?int post_author:flags.16?string grouped_id:flags.17?long reactions:flags.20?MessageReactions restriction_reason:flags.22?Vector ttl_period:flags.25?int = Message;\nmessageService#2b085862 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true post:flags.14?true legacy:flags.19?true id:int from_id:flags.8?Peer peer_id:Peer reply_to:flags.3?MessageReplyHeader date:int action:MessageAction ttl_period:flags.25?int = Message;\nmessageMediaEmpty#3ded6320 = MessageMedia;\nmessageMediaPhoto#695150d7 flags:# photo:flags.0?Photo ttl_seconds:flags.2?int = MessageMedia;\nmessageMediaGeo#56e0d474 geo:GeoPoint = MessageMedia;\nmessageMediaContact#70322949 phone_number:string first_name:string last_name:string vcard:string user_id:long = MessageMedia;\nmessageMediaUnsupported#9f84f49e = MessageMedia;\nmessageMediaDocument#9cb070d7 flags:# document:flags.0?Document ttl_seconds:flags.2?int = MessageMedia;\nmessageMediaWebPage#a32dd600 webpage:WebPage = MessageMedia;\nmessageMediaVenue#2ec0533f geo:GeoPoint title:string address:string provider:string venue_id:string venue_type:string = MessageMedia;\nmessageMediaGame#fdb19008 game:Game = MessageMedia;\nmessageMediaInvoice#84551347 flags:# shipping_address_requested:flags.1?true test:flags.3?true title:string description:string photo:flags.0?WebDocument receipt_msg_id:flags.2?int currency:string total_amount:long start_param:string = MessageMedia;\nmessageMediaGeoLive#b940c666 flags:# geo:GeoPoint heading:flags.0?int period:int proximity_notification_radius:flags.1?int = MessageMedia;\nmessageMediaPoll#4bd6e798 poll:Poll results:PollResults = MessageMedia;\nmessageMediaDice#3f7ee58b value:int emoticon:string = MessageMedia;\nmessageActionEmpty#b6aef7b0 = MessageAction;\nmessageActionChatCreate#bd47cbad title:string users:Vector = MessageAction;\nmessageActionChatEditTitle#b5a1ce5a title:string = MessageAction;\nmessageActionChatEditPhoto#7fcb13a8 photo:Photo = MessageAction;\nmessageActionChatDeletePhoto#95e3fbef = MessageAction;\nmessageActionChatAddUser#15cefd00 users:Vector = MessageAction;\nmessageActionChatDeleteUser#a43f30cc user_id:long = MessageAction;\nmessageActionChatJoinedByLink#31224c3 inviter_id:long = MessageAction;\nmessageActionChannelCreate#95d2ac92 title:string = MessageAction;\nmessageActionChatMigrateTo#e1037f92 channel_id:long = MessageAction;\nmessageActionChannelMigrateFrom#ea3948e9 title:string chat_id:long = MessageAction;\nmessageActionPinMessage#94bd38ed = MessageAction;\nmessageActionHistoryClear#9fbab604 = MessageAction;\nmessageActionGameScore#92a72876 game_id:long score:int = MessageAction;\nmessageActionPaymentSentMe#8f31b327 flags:# currency:string total_amount:long payload:bytes info:flags.0?PaymentRequestedInfo shipping_option_id:flags.1?string charge:PaymentCharge = MessageAction;\nmessageActionPaymentSent#40699cd0 currency:string total_amount:long = MessageAction;\nmessageActionPhoneCall#80e11a7f flags:# video:flags.2?true call_id:long reason:flags.0?PhoneCallDiscardReason duration:flags.1?int = MessageAction;\nmessageActionScreenshotTaken#4792929b = MessageAction;\nmessageActionCustomAction#fae69f56 message:string = MessageAction;\nmessageActionBotAllowed#abe9affe domain:string = MessageAction;\nmessageActionSecureValuesSentMe#1b287353 values:Vector credentials:SecureCredentialsEncrypted = MessageAction;\nmessageActionSecureValuesSent#d95c6154 types:Vector = MessageAction;\nmessageActionContactSignUp#f3f25f76 = MessageAction;\nmessageActionGeoProximityReached#98e0d697 from_id:Peer to_id:Peer distance:int = MessageAction;\nmessageActionGroupCall#7a0d7f42 flags:# call:InputGroupCall duration:flags.0?int = MessageAction;\nmessageActionInviteToGroupCall#502f92f7 call:InputGroupCall users:Vector = MessageAction;\nmessageActionSetMessagesTTL#aa1afbfd period:int = MessageAction;\nmessageActionGroupCallScheduled#b3a07661 call:InputGroupCall schedule_date:int = MessageAction;\nmessageActionSetChatTheme#aa786345 emoticon:string = MessageAction;\nmessageActionChatJoinedByRequest#ebbca3cb = MessageAction;\ndialog#2c171f72 flags:# pinned:flags.2?true unread_mark:flags.3?true peer:Peer top_message:int read_inbox_max_id:int read_outbox_max_id:int unread_count:int unread_mentions_count:int notify_settings:PeerNotifySettings pts:flags.0?int draft:flags.1?DraftMessage folder_id:flags.4?int = Dialog;\ndialogFolder#71bd134c flags:# pinned:flags.2?true folder:Folder peer:Peer top_message:int unread_muted_peers_count:int unread_unmuted_peers_count:int unread_muted_messages_count:int unread_unmuted_messages_count:int = Dialog;\nphotoEmpty#2331b22d id:long = Photo;\nphoto#fb197a65 flags:# has_stickers:flags.0?true id:long access_hash:long file_reference:bytes date:int sizes:Vector video_sizes:flags.1?Vector dc_id:int = Photo;\nphotoSizeEmpty#e17e23c type:string = PhotoSize;\nphotoSize#75c78e60 type:string w:int h:int size:int = PhotoSize;\nphotoCachedSize#21e1ad6 type:string w:int h:int bytes:bytes = PhotoSize;\nphotoStrippedSize#e0b0bc2e type:string bytes:bytes = PhotoSize;\nphotoSizeProgressive#fa3efb95 type:string w:int h:int sizes:Vector = PhotoSize;\nphotoPathSize#d8214d41 type:string bytes:bytes = PhotoSize;\ngeoPointEmpty#1117dd5f = GeoPoint;\ngeoPoint#b2a2f663 flags:# long:double lat:double access_hash:long accuracy_radius:flags.0?int = GeoPoint;\nauth.sentCode#5e002502 flags:# type:auth.SentCodeType phone_code_hash:string next_type:flags.1?auth.CodeType timeout:flags.2?int = auth.SentCode;\nauth.authorization#33fb7bb8 flags:# setup_password_required:flags.1?true otherwise_relogin_days:flags.1?int tmp_sessions:flags.0?int user:User = auth.Authorization;\nauth.authorizationSignUpRequired#44747e9a flags:# terms_of_service:flags.0?help.TermsOfService = auth.Authorization;\nauth.exportedAuthorization#b434e2b8 id:long bytes:bytes = auth.ExportedAuthorization;\ninputNotifyPeer#b8bc5b0c peer:InputPeer = InputNotifyPeer;\ninputNotifyUsers#193b4417 = InputNotifyPeer;\ninputNotifyChats#4a95e84e = InputNotifyPeer;\ninputNotifyBroadcasts#b1db7c7e = InputNotifyPeer;\ninputPeerNotifySettings#9c3d198e flags:# show_previews:flags.0?Bool silent:flags.1?Bool mute_until:flags.2?int sound:flags.3?string = InputPeerNotifySettings;\npeerNotifySettings#af509d20 flags:# show_previews:flags.0?Bool silent:flags.1?Bool mute_until:flags.2?int sound:flags.3?string = PeerNotifySettings;\npeerSettings#a518110d flags:# report_spam:flags.0?true add_contact:flags.1?true block_contact:flags.2?true share_contact:flags.3?true need_contacts_exception:flags.4?true report_geo:flags.5?true autoarchived:flags.7?true invite_members:flags.8?true request_chat_broadcast:flags.10?true geo_distance:flags.6?int request_chat_title:flags.9?string request_chat_date:flags.9?int = PeerSettings;\nwallPaper#a437c3ed id:long flags:# creator:flags.0?true default:flags.1?true pattern:flags.3?true dark:flags.4?true access_hash:long slug:string document:Document settings:flags.2?WallPaperSettings = WallPaper;\nwallPaperNoFile#e0804116 id:long flags:# default:flags.1?true dark:flags.4?true settings:flags.2?WallPaperSettings = WallPaper;\ninputReportReasonSpam#58dbcab8 = ReportReason;\ninputReportReasonViolence#1e22c78d = ReportReason;\ninputReportReasonPornography#2e59d922 = ReportReason;\ninputReportReasonChildAbuse#adf44ee3 = ReportReason;\ninputReportReasonOther#c1e4a2b1 = ReportReason;\ninputReportReasonCopyright#9b89f93a = ReportReason;\ninputReportReasonGeoIrrelevant#dbd4feed = ReportReason;\ninputReportReasonFake#f5ddd6e7 = ReportReason;\nuserFull#cf366521 flags:# blocked:flags.0?true phone_calls_available:flags.4?true phone_calls_private:flags.5?true can_pin_message:flags.7?true has_scheduled:flags.12?true video_calls_available:flags.13?true id:long about:flags.1?string settings:PeerSettings profile_photo:flags.2?Photo notify_settings:PeerNotifySettings bot_info:flags.3?BotInfo pinned_msg_id:flags.6?int common_chats_count:int folder_id:flags.11?int ttl_period:flags.14?int theme_emoticon:flags.15?string private_forward_name:flags.16?string = UserFull;\ncontact#145ade0b user_id:long mutual:Bool = Contact;\nimportedContact#c13e3c50 user_id:long client_id:long = ImportedContact;\ncontactStatus#16d9703b user_id:long status:UserStatus = ContactStatus;\ncontacts.contactsNotModified#b74ba9d2 = contacts.Contacts;\ncontacts.contacts#eae87e42 contacts:Vector saved_count:int users:Vector = contacts.Contacts;\ncontacts.importedContacts#77d01c3b imported:Vector popular_invites:Vector retry_contacts:Vector users:Vector = contacts.ImportedContacts;\ncontacts.blocked#ade1591 blocked:Vector chats:Vector users:Vector = contacts.Blocked;\ncontacts.blockedSlice#e1664194 count:int blocked:Vector chats:Vector users:Vector = contacts.Blocked;\nmessages.dialogs#15ba6c40 dialogs:Vector messages:Vector chats:Vector users:Vector = messages.Dialogs;\nmessages.dialogsSlice#71e094f3 count:int dialogs:Vector messages:Vector chats:Vector users:Vector = messages.Dialogs;\nmessages.dialogsNotModified#f0e3e596 count:int = messages.Dialogs;\nmessages.messages#8c718e87 messages:Vector chats:Vector users:Vector = messages.Messages;\nmessages.messagesSlice#3a54685e flags:# inexact:flags.1?true count:int next_rate:flags.0?int offset_id_offset:flags.2?int messages:Vector chats:Vector users:Vector = messages.Messages;\nmessages.channelMessages#64479808 flags:# inexact:flags.1?true pts:int count:int offset_id_offset:flags.2?int messages:Vector chats:Vector users:Vector = messages.Messages;\nmessages.messagesNotModified#74535f21 count:int = messages.Messages;\nmessages.chats#64ff9fd5 chats:Vector = messages.Chats;\nmessages.chatsSlice#9cd81144 count:int chats:Vector = messages.Chats;\nmessages.chatFull#e5d7d19c full_chat:ChatFull chats:Vector users:Vector = messages.ChatFull;\nmessages.affectedHistory#b45c69d1 pts:int pts_count:int offset:int = messages.AffectedHistory;\ninputMessagesFilterEmpty#57e2f66c = MessagesFilter;\ninputMessagesFilterPhotos#9609a51c = MessagesFilter;\ninputMessagesFilterVideo#9fc00e65 = MessagesFilter;\ninputMessagesFilterPhotoVideo#56e9f0e4 = MessagesFilter;\ninputMessagesFilterDocument#9eddf188 = MessagesFilter;\ninputMessagesFilterUrl#7ef0dd87 = MessagesFilter;\ninputMessagesFilterGif#ffc86587 = MessagesFilter;\ninputMessagesFilterVoice#50f5c392 = MessagesFilter;\ninputMessagesFilterMusic#3751b49e = MessagesFilter;\ninputMessagesFilterChatPhotos#3a20ecb8 = MessagesFilter;\ninputMessagesFilterPhoneCalls#80c99768 flags:# missed:flags.0?true = MessagesFilter;\ninputMessagesFilterRoundVoice#7a7c17a4 = MessagesFilter;\ninputMessagesFilterRoundVideo#b549da53 = MessagesFilter;\ninputMessagesFilterMyMentions#c1f8e69a = MessagesFilter;\ninputMessagesFilterGeo#e7026d0d = MessagesFilter;\ninputMessagesFilterContacts#e062db83 = MessagesFilter;\ninputMessagesFilterPinned#1bb00451 = MessagesFilter;\nupdateNewMessage#1f2b0afd message:Message pts:int pts_count:int = Update;\nupdateMessageID#4e90bfd6 id:int random_id:long = Update;\nupdateDeleteMessages#a20db0e5 messages:Vector pts:int pts_count:int = Update;\nupdateUserTyping#c01e857f user_id:long action:SendMessageAction = Update;\nupdateChatUserTyping#83487af0 chat_id:long from_id:Peer action:SendMessageAction = Update;\nupdateChatParticipants#7761198 participants:ChatParticipants = Update;\nupdateUserStatus#e5bdf8de user_id:long status:UserStatus = Update;\nupdateUserName#c3f202e0 user_id:long first_name:string last_name:string username:string = Update;\nupdateUserPhoto#f227868c user_id:long date:int photo:UserProfilePhoto previous:Bool = Update;\nupdateNewEncryptedMessage#12bcbd9a message:EncryptedMessage qts:int = Update;\nupdateEncryptedChatTyping#1710f156 chat_id:int = Update;\nupdateEncryption#b4a2e88d chat:EncryptedChat date:int = Update;\nupdateEncryptedMessagesRead#38fe25b7 chat_id:int max_date:int date:int = Update;\nupdateChatParticipantAdd#3dda5451 chat_id:long user_id:long inviter_id:long date:int version:int = Update;\nupdateChatParticipantDelete#e32f3d77 chat_id:long user_id:long version:int = Update;\nupdateDcOptions#8e5e9873 dc_options:Vector = Update;\nupdateNotifySettings#bec268ef peer:NotifyPeer notify_settings:PeerNotifySettings = Update;\nupdateServiceNotification#ebe46819 flags:# popup:flags.0?true inbox_date:flags.1?int type:string message:string media:MessageMedia entities:Vector = Update;\nupdatePrivacy#ee3b272a key:PrivacyKey rules:Vector = Update;\nupdateUserPhone#5492a13 user_id:long phone:string = Update;\nupdateReadHistoryInbox#9c974fdf flags:# folder_id:flags.0?int peer:Peer max_id:int still_unread_count:int pts:int pts_count:int = Update;\nupdateReadHistoryOutbox#2f2f21bf peer:Peer max_id:int pts:int pts_count:int = Update;\nupdateWebPage#7f891213 webpage:WebPage pts:int pts_count:int = Update;\nupdateReadMessagesContents#68c13933 messages:Vector pts:int pts_count:int = Update;\nupdateChannelTooLong#108d941f flags:# channel_id:long pts:flags.0?int = Update;\nupdateChannel#635b4c09 channel_id:long = Update;\nupdateNewChannelMessage#62ba04d9 message:Message pts:int pts_count:int = Update;\nupdateReadChannelInbox#922e6e10 flags:# folder_id:flags.0?int channel_id:long max_id:int still_unread_count:int pts:int = Update;\nupdateDeleteChannelMessages#c32d5b12 channel_id:long messages:Vector pts:int pts_count:int = Update;\nupdateChannelMessageViews#f226ac08 channel_id:long id:int views:int = Update;\nupdateChatParticipantAdmin#d7ca61a2 chat_id:long user_id:long is_admin:Bool version:int = Update;\nupdateNewStickerSet#688a30aa stickerset:messages.StickerSet = Update;\nupdateStickerSetsOrder#bb2d201 flags:# masks:flags.0?true order:Vector = Update;\nupdateStickerSets#43ae3dec = Update;\nupdateSavedGifs#9375341e = Update;\nupdateBotInlineQuery#496f379c flags:# query_id:long user_id:long query:string geo:flags.0?GeoPoint peer_type:flags.1?InlineQueryPeerType offset:string = Update;\nupdateBotInlineSend#12f12a07 flags:# user_id:long query:string geo:flags.0?GeoPoint id:string msg_id:flags.1?InputBotInlineMessageID = Update;\nupdateEditChannelMessage#1b3f4df7 message:Message pts:int pts_count:int = Update;\nupdateBotCallbackQuery#b9cfc48d flags:# query_id:long user_id:long peer:Peer msg_id:int chat_instance:long data:flags.0?bytes game_short_name:flags.1?string = Update;\nupdateEditMessage#e40370a3 message:Message pts:int pts_count:int = Update;\nupdateInlineBotCallbackQuery#691e9052 flags:# query_id:long user_id:long msg_id:InputBotInlineMessageID chat_instance:long data:flags.0?bytes game_short_name:flags.1?string = Update;\nupdateReadChannelOutbox#b75f99a9 channel_id:long max_id:int = Update;\nupdateDraftMessage#ee2bb969 peer:Peer draft:DraftMessage = Update;\nupdateReadFeaturedStickers#571d2742 = Update;\nupdateRecentStickers#9a422c20 = Update;\nupdateConfig#a229dd06 = Update;\nupdatePtsChanged#3354678f = Update;\nupdateChannelWebPage#2f2ba99f channel_id:long webpage:WebPage pts:int pts_count:int = Update;\nupdateDialogPinned#6e6fe51c flags:# pinned:flags.0?true folder_id:flags.1?int peer:DialogPeer = Update;\nupdatePinnedDialogs#fa0f3ca2 flags:# folder_id:flags.1?int order:flags.0?Vector = Update;\nupdateBotWebhookJSON#8317c0c3 data:DataJSON = Update;\nupdateBotWebhookJSONQuery#9b9240a6 query_id:long data:DataJSON timeout:int = Update;\nupdateBotShippingQuery#b5aefd7d query_id:long user_id:long payload:bytes shipping_address:PostAddress = Update;\nupdateBotPrecheckoutQuery#8caa9a96 flags:# query_id:long user_id:long payload:bytes info:flags.0?PaymentRequestedInfo shipping_option_id:flags.1?string currency:string total_amount:long = Update;\nupdatePhoneCall#ab0f6b1e phone_call:PhoneCall = Update;\nupdateLangPackTooLong#46560264 lang_code:string = Update;\nupdateLangPack#56022f4d difference:LangPackDifference = Update;\nupdateFavedStickers#e511996d = Update;\nupdateChannelReadMessagesContents#44bdd535 channel_id:long messages:Vector = Update;\nupdateContactsReset#7084a7be = Update;\nupdateChannelAvailableMessages#b23fc698 channel_id:long available_min_id:int = Update;\nupdateDialogUnreadMark#e16459c3 flags:# unread:flags.0?true peer:DialogPeer = Update;\nupdateMessagePoll#aca1657b flags:# poll_id:long poll:flags.0?Poll results:PollResults = Update;\nupdateChatDefaultBannedRights#54c01850 peer:Peer default_banned_rights:ChatBannedRights version:int = Update;\nupdateFolderPeers#19360dc0 folder_peers:Vector pts:int pts_count:int = Update;\nupdatePeerSettings#6a7e7366 peer:Peer settings:PeerSettings = Update;\nupdatePeerLocated#b4afcfb0 peers:Vector = Update;\nupdateNewScheduledMessage#39a51dfb message:Message = Update;\nupdateDeleteScheduledMessages#90866cee peer:Peer messages:Vector = Update;\nupdateTheme#8216fba3 theme:Theme = Update;\nupdateGeoLiveViewed#871fb939 peer:Peer msg_id:int = Update;\nupdateLoginToken#564fe691 = Update;\nupdateMessagePollVote#106395c9 poll_id:long user_id:long options:Vector qts:int = Update;\nupdateDialogFilter#26ffde7d flags:# id:int filter:flags.0?DialogFilter = Update;\nupdateDialogFilterOrder#a5d72105 order:Vector = Update;\nupdateDialogFilters#3504914f = Update;\nupdatePhoneCallSignalingData#2661bf09 phone_call_id:long data:bytes = Update;\nupdateChannelMessageForwards#d29a27f4 channel_id:long id:int forwards:int = Update;\nupdateReadChannelDiscussionInbox#d6b19546 flags:# channel_id:long top_msg_id:int read_max_id:int broadcast_id:flags.0?long broadcast_post:flags.0?int = Update;\nupdateReadChannelDiscussionOutbox#695c9e7c channel_id:long top_msg_id:int read_max_id:int = Update;\nupdatePeerBlocked#246a4b22 peer_id:Peer blocked:Bool = Update;\nupdateChannelUserTyping#8c88c923 flags:# channel_id:long top_msg_id:flags.0?int from_id:Peer action:SendMessageAction = Update;\nupdatePinnedMessages#ed85eab5 flags:# pinned:flags.0?true peer:Peer messages:Vector pts:int pts_count:int = Update;\nupdatePinnedChannelMessages#5bb98608 flags:# pinned:flags.0?true channel_id:long messages:Vector pts:int pts_count:int = Update;\nupdateChat#f89a6a4e chat_id:long = Update;\nupdateGroupCallParticipants#f2ebdb4e call:InputGroupCall participants:Vector version:int = Update;\nupdateGroupCall#14b24500 chat_id:long call:GroupCall = Update;\nupdatePeerHistoryTTL#bb9bb9a5 flags:# peer:Peer ttl_period:flags.0?int = Update;\nupdateChatParticipant#d087663a flags:# chat_id:long date:int actor_id:long user_id:long prev_participant:flags.0?ChatParticipant new_participant:flags.1?ChatParticipant invite:flags.2?ExportedChatInvite qts:int = Update;\nupdateChannelParticipant#985d3abb flags:# channel_id:long date:int actor_id:long user_id:long prev_participant:flags.0?ChannelParticipant new_participant:flags.1?ChannelParticipant invite:flags.2?ExportedChatInvite qts:int = Update;\nupdateBotStopped#c4870a49 user_id:long date:int stopped:Bool qts:int = Update;\nupdateGroupCallConnection#b783982 flags:# presentation:flags.0?true params:DataJSON = Update;\nupdateBotCommands#4d712f2e peer:Peer bot_id:long commands:Vector = Update;\nupdatePendingJoinRequests#7063c3db peer:Peer requests_pending:int recent_requesters:Vector = Update;\nupdateBotChatInviteRequester#11dfa986 peer:Peer date:int user_id:long about:string invite:ExportedChatInvite qts:int = Update;\nupdateMessageReactions#154798c3 peer:Peer msg_id:int reactions:MessageReactions = Update;\nupdates.state#a56c2a3e pts:int qts:int date:int seq:int unread_count:int = updates.State;\nupdates.differenceEmpty#5d75a138 date:int seq:int = updates.Difference;\nupdates.difference#f49ca0 new_messages:Vector new_encrypted_messages:Vector other_updates:Vector chats:Vector users:Vector state:updates.State = updates.Difference;\nupdates.differenceSlice#a8fb1981 new_messages:Vector new_encrypted_messages:Vector other_updates:Vector chats:Vector users:Vector intermediate_state:updates.State = updates.Difference;\nupdates.differenceTooLong#4afe8f6d pts:int = updates.Difference;\nupdatesTooLong#e317af7e = Updates;\nupdateShortMessage#313bc7f8 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true id:int user_id:long message:string pts:int pts_count:int date:int fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?long reply_to:flags.3?MessageReplyHeader entities:flags.7?Vector ttl_period:flags.25?int = Updates;\nupdateShortChatMessage#4d6deea5 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true id:int from_id:long chat_id:long message:string pts:int pts_count:int date:int fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?long reply_to:flags.3?MessageReplyHeader entities:flags.7?Vector ttl_period:flags.25?int = Updates;\nupdateShort#78d4dec1 update:Update date:int = Updates;\nupdatesCombined#725b04c3 updates:Vector users:Vector chats:Vector date:int seq_start:int seq:int = Updates;\nupdates#74ae4240 updates:Vector users:Vector chats:Vector date:int seq:int = Updates;\nupdateShortSentMessage#9015e101 flags:# out:flags.1?true id:int pts:int pts_count:int date:int media:flags.9?MessageMedia entities:flags.7?Vector ttl_period:flags.25?int = Updates;\nphotos.photos#8dca6aa5 photos:Vector users:Vector = photos.Photos;\nphotos.photosSlice#15051f54 count:int photos:Vector users:Vector = photos.Photos;\nphotos.photo#20212ca8 photo:Photo users:Vector = photos.Photo;\nupload.file#96a18d5 type:storage.FileType mtime:int bytes:bytes = upload.File;\nupload.fileCdnRedirect#f18cda44 dc_id:int file_token:bytes encryption_key:bytes encryption_iv:bytes file_hashes:Vector = upload.File;\ndcOption#18b7a10d flags:# ipv6:flags.0?true media_only:flags.1?true tcpo_only:flags.2?true cdn:flags.3?true static:flags.4?true id:int ip_address:string port:int secret:flags.10?bytes = DcOption;\nconfig#330b4067 flags:# phonecalls_enabled:flags.1?true default_p2p_contacts:flags.3?true preload_featured_stickers:flags.4?true ignore_phone_entities:flags.5?true revoke_pm_inbox:flags.6?true blocked_mode:flags.8?true pfs_enabled:flags.13?true date:int expires:int test_mode:Bool this_dc:int dc_options:Vector dc_txt_domain_name:string chat_size_max:int megagroup_size_max:int forwarded_count_max:int online_update_period_ms:int offline_blur_timeout_ms:int offline_idle_timeout_ms:int online_cloud_timeout_ms:int notify_cloud_delay_ms:int notify_default_delay_ms:int push_chat_period_ms:int push_chat_limit:int saved_gifs_limit:int edit_time_limit:int revoke_time_limit:int revoke_pm_time_limit:int rating_e_decay:int stickers_recent_limit:int stickers_faved_limit:int channels_read_media_period:int tmp_sessions:flags.0?int pinned_dialogs_count_max:int pinned_infolder_count_max:int call_receive_timeout_ms:int call_ring_timeout_ms:int call_connect_timeout_ms:int call_packet_timeout_ms:int me_url_prefix:string autoupdate_url_prefix:flags.7?string gif_search_username:flags.9?string venue_search_username:flags.10?string img_search_username:flags.11?string static_maps_provider:flags.12?string caption_length_max:int message_length_max:int webfile_dc_id:int suggested_lang_code:flags.2?string lang_pack_version:flags.2?int base_lang_pack_version:flags.2?int = Config;\nnearestDc#8e1a1775 country:string this_dc:int nearest_dc:int = NearestDc;\nhelp.appUpdate#ccbbce30 flags:# can_not_skip:flags.0?true id:int version:string text:string entities:Vector document:flags.1?Document url:flags.2?string sticker:flags.3?Document = help.AppUpdate;\nhelp.noAppUpdate#c45a6536 = help.AppUpdate;\nhelp.inviteText#18cb9f78 message:string = help.InviteText;\nencryptedChatEmpty#ab7ec0a0 id:int = EncryptedChat;\nencryptedChatWaiting#66b25953 id:int access_hash:long date:int admin_id:long participant_id:long = EncryptedChat;\nencryptedChatRequested#48f1d94c flags:# folder_id:flags.0?int id:int access_hash:long date:int admin_id:long participant_id:long g_a:bytes = EncryptedChat;\nencryptedChat#61f0d4c7 id:int access_hash:long date:int admin_id:long participant_id:long g_a_or_b:bytes key_fingerprint:long = EncryptedChat;\nencryptedChatDiscarded#1e1c7c45 flags:# history_deleted:flags.0?true id:int = EncryptedChat;\ninputEncryptedChat#f141b5e1 chat_id:int access_hash:long = InputEncryptedChat;\nencryptedFileEmpty#c21f497e = EncryptedFile;\nencryptedFile#4a70994c id:long access_hash:long size:int dc_id:int key_fingerprint:int = EncryptedFile;\ninputEncryptedFileEmpty#1837c364 = InputEncryptedFile;\ninputEncryptedFileUploaded#64bd0306 id:long parts:int md5_checksum:string key_fingerprint:int = InputEncryptedFile;\ninputEncryptedFile#5a17b5e5 id:long access_hash:long = InputEncryptedFile;\ninputEncryptedFileBigUploaded#2dc173c8 id:long parts:int key_fingerprint:int = InputEncryptedFile;\nencryptedMessage#ed18c118 random_id:long chat_id:int date:int bytes:bytes file:EncryptedFile = EncryptedMessage;\nencryptedMessageService#23734b06 random_id:long chat_id:int date:int bytes:bytes = EncryptedMessage;\nmessages.dhConfigNotModified#c0e24635 random:bytes = messages.DhConfig;\nmessages.dhConfig#2c221edd g:int p:bytes version:int random:bytes = messages.DhConfig;\nmessages.sentEncryptedMessage#560f8935 date:int = messages.SentEncryptedMessage;\nmessages.sentEncryptedFile#9493ff32 date:int file:EncryptedFile = messages.SentEncryptedMessage;\ninputDocumentEmpty#72f0eaae = InputDocument;\ninputDocument#1abfb575 id:long access_hash:long file_reference:bytes = InputDocument;\ndocumentEmpty#36f8c871 id:long = Document;\ndocument#1e87342b flags:# id:long access_hash:long file_reference:bytes date:int mime_type:string size:int thumbs:flags.0?Vector video_thumbs:flags.1?Vector dc_id:int attributes:Vector = Document;\nhelp.support#17c6b5f6 phone_number:string user:User = help.Support;\nnotifyPeer#9fd40bd8 peer:Peer = NotifyPeer;\nnotifyUsers#b4c83b4c = NotifyPeer;\nnotifyChats#c007cec3 = NotifyPeer;\nnotifyBroadcasts#d612e8ef = NotifyPeer;\nsendMessageTypingAction#16bf744e = SendMessageAction;\nsendMessageCancelAction#fd5ec8f5 = SendMessageAction;\nsendMessageRecordVideoAction#a187d66f = SendMessageAction;\nsendMessageUploadVideoAction#e9763aec progress:int = SendMessageAction;\nsendMessageRecordAudioAction#d52f73f7 = SendMessageAction;\nsendMessageUploadAudioAction#f351d7ab progress:int = SendMessageAction;\nsendMessageUploadPhotoAction#d1d34a26 progress:int = SendMessageAction;\nsendMessageUploadDocumentAction#aa0cd9e4 progress:int = SendMessageAction;\nsendMessageGeoLocationAction#176f8ba1 = SendMessageAction;\nsendMessageChooseContactAction#628cbc6f = SendMessageAction;\nsendMessageGamePlayAction#dd6a8f48 = SendMessageAction;\nsendMessageRecordRoundAction#88f27fbc = SendMessageAction;\nsendMessageUploadRoundAction#243e1c66 progress:int = SendMessageAction;\nspeakingInGroupCallAction#d92c2285 = SendMessageAction;\nsendMessageHistoryImportAction#dbda9246 progress:int = SendMessageAction;\nsendMessageChooseStickerAction#b05ac6b1 = SendMessageAction;\nsendMessageEmojiInteraction#25972bcb emoticon:string msg_id:int interaction:DataJSON = SendMessageAction;\nsendMessageEmojiInteractionSeen#b665902e emoticon:string = SendMessageAction;\ncontacts.found#b3134d9d my_results:Vector results:Vector chats:Vector users:Vector = contacts.Found;\ninputPrivacyKeyStatusTimestamp#4f96cb18 = InputPrivacyKey;\ninputPrivacyKeyChatInvite#bdfb0426 = InputPrivacyKey;\ninputPrivacyKeyPhoneCall#fabadc5f = InputPrivacyKey;\ninputPrivacyKeyPhoneP2P#db9e70d2 = InputPrivacyKey;\ninputPrivacyKeyForwards#a4dd4c08 = InputPrivacyKey;\ninputPrivacyKeyProfilePhoto#5719bacc = InputPrivacyKey;\ninputPrivacyKeyPhoneNumber#352dafa = InputPrivacyKey;\ninputPrivacyKeyAddedByPhone#d1219bdd = InputPrivacyKey;\nprivacyKeyStatusTimestamp#bc2eab30 = PrivacyKey;\nprivacyKeyChatInvite#500e6dfa = PrivacyKey;\nprivacyKeyPhoneCall#3d662b7b = PrivacyKey;\nprivacyKeyPhoneP2P#39491cc8 = PrivacyKey;\nprivacyKeyForwards#69ec56a3 = PrivacyKey;\nprivacyKeyProfilePhoto#96151fed = PrivacyKey;\nprivacyKeyPhoneNumber#d19ae46d = PrivacyKey;\nprivacyKeyAddedByPhone#42ffd42b = PrivacyKey;\ninputPrivacyValueAllowContacts#d09e07b = InputPrivacyRule;\ninputPrivacyValueAllowAll#184b35ce = InputPrivacyRule;\ninputPrivacyValueAllowUsers#131cc67f users:Vector = InputPrivacyRule;\ninputPrivacyValueDisallowContacts#ba52007 = InputPrivacyRule;\ninputPrivacyValueDisallowAll#d66b66c9 = InputPrivacyRule;\ninputPrivacyValueDisallowUsers#90110467 users:Vector = InputPrivacyRule;\ninputPrivacyValueAllowChatParticipants#840649cf chats:Vector = InputPrivacyRule;\ninputPrivacyValueDisallowChatParticipants#e94f0f86 chats:Vector = InputPrivacyRule;\nprivacyValueAllowContacts#fffe1bac = PrivacyRule;\nprivacyValueAllowAll#65427b82 = PrivacyRule;\nprivacyValueAllowUsers#b8905fb2 users:Vector = PrivacyRule;\nprivacyValueDisallowContacts#f888fa1a = PrivacyRule;\nprivacyValueDisallowAll#8b73e763 = PrivacyRule;\nprivacyValueDisallowUsers#e4621141 users:Vector = PrivacyRule;\nprivacyValueAllowChatParticipants#6b134e8e chats:Vector = PrivacyRule;\nprivacyValueDisallowChatParticipants#41c87565 chats:Vector = PrivacyRule;\naccount.privacyRules#50a04e45 rules:Vector chats:Vector users:Vector = account.PrivacyRules;\naccountDaysTTL#b8d0afdf days:int = AccountDaysTTL;\ndocumentAttributeImageSize#6c37c15c w:int h:int = DocumentAttribute;\ndocumentAttributeAnimated#11b58939 = DocumentAttribute;\ndocumentAttributeSticker#6319d612 flags:# mask:flags.1?true alt:string stickerset:InputStickerSet mask_coords:flags.0?MaskCoords = DocumentAttribute;\ndocumentAttributeVideo#ef02ce6 flags:# round_message:flags.0?true supports_streaming:flags.1?true duration:int w:int h:int = DocumentAttribute;\ndocumentAttributeAudio#9852f9c6 flags:# voice:flags.10?true duration:int title:flags.0?string performer:flags.1?string waveform:flags.2?bytes = DocumentAttribute;\ndocumentAttributeFilename#15590068 file_name:string = DocumentAttribute;\ndocumentAttributeHasStickers#9801d2f7 = DocumentAttribute;\nmessages.stickersNotModified#f1749a22 = messages.Stickers;\nmessages.stickers#30a6ec7e hash:long stickers:Vector = messages.Stickers;\nstickerPack#12b299d4 emoticon:string documents:Vector = StickerPack;\nmessages.allStickersNotModified#e86602c3 = messages.AllStickers;\nmessages.allStickers#cdbbcebb hash:long sets:Vector = messages.AllStickers;\nmessages.affectedMessages#84d19185 pts:int pts_count:int = messages.AffectedMessages;\nwebPageEmpty#eb1477e8 id:long = WebPage;\nwebPagePending#c586da1c id:long date:int = WebPage;\nwebPage#e89c45b2 flags:# id:long url:string display_url:string hash:int type:flags.0?string site_name:flags.1?string title:flags.2?string description:flags.3?string photo:flags.4?Photo embed_url:flags.5?string embed_type:flags.5?string embed_width:flags.6?int embed_height:flags.6?int duration:flags.7?int author:flags.8?string document:flags.9?Document cached_page:flags.10?Page attributes:flags.12?Vector = WebPage;\nwebPageNotModified#7311ca11 flags:# cached_page_views:flags.0?int = WebPage;\nauthorization#ad01d61d flags:# current:flags.0?true official_app:flags.1?true password_pending:flags.2?true encrypted_requests_disabled:flags.3?true call_requests_disabled:flags.4?true hash:long device_model:string platform:string system_version:string api_id:int app_name:string app_version:string date_created:int date_active:int ip:string country:string region:string = Authorization;\naccount.authorizations#4bff8ea0 authorization_ttl_days:int authorizations:Vector = account.Authorizations;\naccount.password#185b184f flags:# has_recovery:flags.0?true has_secure_values:flags.1?true has_password:flags.2?true current_algo:flags.2?PasswordKdfAlgo srp_B:flags.2?bytes srp_id:flags.2?long hint:flags.3?string email_unconfirmed_pattern:flags.4?string new_algo:PasswordKdfAlgo new_secure_algo:SecurePasswordKdfAlgo secure_random:bytes pending_reset_date:flags.5?int = account.Password;\naccount.passwordSettings#9a5c33e5 flags:# email:flags.0?string secure_settings:flags.1?SecureSecretSettings = account.PasswordSettings;\naccount.passwordInputSettings#c23727c9 flags:# new_algo:flags.0?PasswordKdfAlgo new_password_hash:flags.0?bytes hint:flags.0?string email:flags.1?string new_secure_settings:flags.2?SecureSecretSettings = account.PasswordInputSettings;\nauth.passwordRecovery#137948a5 email_pattern:string = auth.PasswordRecovery;\nreceivedNotifyMessage#a384b779 id:int flags:int = ReceivedNotifyMessage;\nchatInviteExported#ab4a819 flags:# revoked:flags.0?true permanent:flags.5?true request_needed:flags.6?true link:string admin_id:long date:int start_date:flags.4?int expire_date:flags.1?int usage_limit:flags.2?int usage:flags.3?int requested:flags.7?int title:flags.8?string = ExportedChatInvite;\nchatInviteAlready#5a686d7c chat:Chat = ChatInvite;\nchatInvite#300c44c1 flags:# channel:flags.0?true broadcast:flags.1?true public:flags.2?true megagroup:flags.3?true request_needed:flags.6?true title:string about:flags.5?string photo:Photo participants_count:int participants:flags.4?Vector = ChatInvite;\nchatInvitePeek#61695cb0 chat:Chat expires:int = ChatInvite;\ninputStickerSetEmpty#ffb62b95 = InputStickerSet;\ninputStickerSetID#9de7a269 id:long access_hash:long = InputStickerSet;\ninputStickerSetShortName#861cc8a0 short_name:string = InputStickerSet;\ninputStickerSetAnimatedEmoji#28703c8 = InputStickerSet;\ninputStickerSetDice#e67f520e emoticon:string = InputStickerSet;\ninputStickerSetAnimatedEmojiAnimations#cde3739 = InputStickerSet;\nstickerSet#d7df217a flags:# archived:flags.1?true official:flags.2?true masks:flags.3?true animated:flags.5?true installed_date:flags.0?int id:long access_hash:long title:string short_name:string thumbs:flags.4?Vector thumb_dc_id:flags.4?int thumb_version:flags.4?int count:int hash:int = StickerSet;\nmessages.stickerSet#b60a24a6 set:StickerSet packs:Vector documents:Vector = messages.StickerSet;\nmessages.stickerSetNotModified#d3f924eb = messages.StickerSet;\nbotCommand#c27ac8c7 command:string description:string = BotCommand;\nbotInfo#1b74b335 user_id:long description:string commands:Vector = BotInfo;\nkeyboardButton#a2fa4880 text:string = KeyboardButton;\nkeyboardButtonUrl#258aff05 text:string url:string = KeyboardButton;\nkeyboardButtonCallback#35bbdb6b flags:# requires_password:flags.0?true text:string data:bytes = KeyboardButton;\nkeyboardButtonRequestPhone#b16a6c29 text:string = KeyboardButton;\nkeyboardButtonRequestGeoLocation#fc796b3f text:string = KeyboardButton;\nkeyboardButtonSwitchInline#568a748 flags:# same_peer:flags.0?true text:string query:string = KeyboardButton;\nkeyboardButtonGame#50f41ccf text:string = KeyboardButton;\nkeyboardButtonBuy#afd93fbb text:string = KeyboardButton;\nkeyboardButtonUrlAuth#10b78d29 flags:# text:string fwd_text:flags.0?string url:string button_id:int = KeyboardButton;\ninputKeyboardButtonUrlAuth#d02e7fd4 flags:# request_write_access:flags.0?true text:string fwd_text:flags.1?string url:string bot:InputUser = KeyboardButton;\nkeyboardButtonRequestPoll#bbc7515d flags:# quiz:flags.0?Bool text:string = KeyboardButton;\ninputKeyboardButtonUserProfile#e988037b text:string user_id:InputUser = KeyboardButton;\nkeyboardButtonUserProfile#308660c1 text:string user_id:long = KeyboardButton;\nkeyboardButtonRow#77608b83 buttons:Vector = KeyboardButtonRow;\nreplyKeyboardHide#a03e5b85 flags:# selective:flags.2?true = ReplyMarkup;\nreplyKeyboardForceReply#86b40b08 flags:# single_use:flags.1?true selective:flags.2?true placeholder:flags.3?string = ReplyMarkup;\nreplyKeyboardMarkup#85dd99d1 flags:# resize:flags.0?true single_use:flags.1?true selective:flags.2?true rows:Vector placeholder:flags.3?string = ReplyMarkup;\nreplyInlineMarkup#48a30254 rows:Vector = ReplyMarkup;\nmessageEntityUnknown#bb92ba95 offset:int length:int = MessageEntity;\nmessageEntityMention#fa04579d offset:int length:int = MessageEntity;\nmessageEntityHashtag#6f635b0d offset:int length:int = MessageEntity;\nmessageEntityBotCommand#6cef8ac7 offset:int length:int = MessageEntity;\nmessageEntityUrl#6ed02538 offset:int length:int = MessageEntity;\nmessageEntityEmail#64e475c2 offset:int length:int = MessageEntity;\nmessageEntityBold#bd610bc9 offset:int length:int = MessageEntity;\nmessageEntityItalic#826f8b60 offset:int length:int = MessageEntity;\nmessageEntityCode#28a20571 offset:int length:int = MessageEntity;\nmessageEntityPre#73924be0 offset:int length:int language:string = MessageEntity;\nmessageEntityTextUrl#76a6d327 offset:int length:int url:string = MessageEntity;\nmessageEntityMentionName#dc7b1140 offset:int length:int user_id:long = MessageEntity;\ninputMessageEntityMentionName#208e68c9 offset:int length:int user_id:InputUser = MessageEntity;\nmessageEntityPhone#9b69e34b offset:int length:int = MessageEntity;\nmessageEntityCashtag#4c4e743f offset:int length:int = MessageEntity;\nmessageEntityUnderline#9c4e7e8b offset:int length:int = MessageEntity;\nmessageEntityStrike#bf0693d4 offset:int length:int = MessageEntity;\nmessageEntityBlockquote#20df5d0 offset:int length:int = MessageEntity;\nmessageEntityBankCard#761e6af4 offset:int length:int = MessageEntity;\nmessageEntitySpoiler#32ca960f offset:int length:int = MessageEntity;\ninputChannelEmpty#ee8c1e86 = InputChannel;\ninputChannel#f35aec28 channel_id:long access_hash:long = InputChannel;\ninputChannelFromMessage#5b934f9d peer:InputPeer msg_id:int channel_id:long = InputChannel;\ncontacts.resolvedPeer#7f077ad9 peer:Peer chats:Vector users:Vector = contacts.ResolvedPeer;\nmessageRange#ae30253 min_id:int max_id:int = MessageRange;\nupdates.channelDifferenceEmpty#3e11affb flags:# final:flags.0?true pts:int timeout:flags.1?int = updates.ChannelDifference;\nupdates.channelDifferenceTooLong#a4bcc6fe flags:# final:flags.0?true timeout:flags.1?int dialog:Dialog messages:Vector chats:Vector users:Vector = updates.ChannelDifference;\nupdates.channelDifference#2064674e flags:# final:flags.0?true pts:int timeout:flags.1?int new_messages:Vector other_updates:Vector chats:Vector users:Vector = updates.ChannelDifference;\nchannelMessagesFilterEmpty#94d42ee7 = ChannelMessagesFilter;\nchannelMessagesFilter#cd77d957 flags:# exclude_new_messages:flags.1?true ranges:Vector = ChannelMessagesFilter;\nchannelParticipant#c00c07c0 user_id:long date:int = ChannelParticipant;\nchannelParticipantSelf#35a8bfa7 flags:# via_request:flags.0?true user_id:long inviter_id:long date:int = ChannelParticipant;\nchannelParticipantCreator#2fe601d3 flags:# user_id:long admin_rights:ChatAdminRights rank:flags.0?string = ChannelParticipant;\nchannelParticipantAdmin#34c3bb53 flags:# can_edit:flags.0?true self:flags.1?true user_id:long inviter_id:flags.1?long promoted_by:long date:int admin_rights:ChatAdminRights rank:flags.2?string = ChannelParticipant;\nchannelParticipantBanned#6df8014e flags:# left:flags.0?true peer:Peer kicked_by:long date:int banned_rights:ChatBannedRights = ChannelParticipant;\nchannelParticipantLeft#1b03f006 peer:Peer = ChannelParticipant;\nchannelParticipantsRecent#de3f3c79 = ChannelParticipantsFilter;\nchannelParticipantsAdmins#b4608969 = ChannelParticipantsFilter;\nchannelParticipantsKicked#a3b54985 q:string = ChannelParticipantsFilter;\nchannelParticipantsBots#b0d1865b = ChannelParticipantsFilter;\nchannelParticipantsBanned#1427a5e1 q:string = ChannelParticipantsFilter;\nchannelParticipantsSearch#656ac4b q:string = ChannelParticipantsFilter;\nchannelParticipantsContacts#bb6ae88d q:string = ChannelParticipantsFilter;\nchannelParticipantsMentions#e04b5ceb flags:# q:flags.0?string top_msg_id:flags.1?int = ChannelParticipantsFilter;\nchannels.channelParticipants#9ab0feaf count:int participants:Vector chats:Vector users:Vector = channels.ChannelParticipants;\nchannels.channelParticipantsNotModified#f0173fe9 = channels.ChannelParticipants;\nchannels.channelParticipant#dfb80317 participant:ChannelParticipant chats:Vector users:Vector = channels.ChannelParticipant;\nhelp.termsOfService#780a0310 flags:# popup:flags.0?true id:DataJSON text:string entities:Vector min_age_confirm:flags.1?int = help.TermsOfService;\nmessages.savedGifsNotModified#e8025ca2 = messages.SavedGifs;\nmessages.savedGifs#84a02a0d hash:long gifs:Vector = messages.SavedGifs;\ninputBotInlineMessageMediaAuto#3380c786 flags:# message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageText#3dcd7a87 flags:# no_webpage:flags.0?true message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaGeo#96929a85 flags:# geo_point:InputGeoPoint heading:flags.0?int period:flags.1?int proximity_notification_radius:flags.3?int reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaVenue#417bbf11 flags:# geo_point:InputGeoPoint title:string address:string provider:string venue_id:string venue_type:string reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaContact#a6edbffd flags:# phone_number:string first_name:string last_name:string vcard:string reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageGame#4b425864 flags:# reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaInvoice#d7e78225 flags:# title:string description:string photo:flags.0?InputWebDocument invoice:Invoice payload:bytes provider:string provider_data:DataJSON reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineResult#88bf9319 flags:# id:string type:string title:flags.1?string description:flags.2?string url:flags.3?string thumb:flags.4?InputWebDocument content:flags.5?InputWebDocument send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultPhoto#a8d864a7 id:string type:string photo:InputPhoto send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultDocument#fff8fdc4 flags:# id:string type:string title:flags.1?string description:flags.2?string document:InputDocument send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultGame#4fa417f2 id:string short_name:string send_message:InputBotInlineMessage = InputBotInlineResult;\nbotInlineMessageMediaAuto#764cf810 flags:# message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageText#8c7f65e2 flags:# no_webpage:flags.0?true message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaGeo#51846fd flags:# geo:GeoPoint heading:flags.0?int period:flags.1?int proximity_notification_radius:flags.3?int reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaVenue#8a86659c flags:# geo:GeoPoint title:string address:string provider:string venue_id:string venue_type:string reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaContact#18d1cdc2 flags:# phone_number:string first_name:string last_name:string vcard:string reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaInvoice#354a9b09 flags:# shipping_address_requested:flags.1?true test:flags.3?true title:string description:string photo:flags.0?WebDocument currency:string total_amount:long reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineResult#11965f3a flags:# id:string type:string title:flags.1?string description:flags.2?string url:flags.3?string thumb:flags.4?WebDocument content:flags.5?WebDocument send_message:BotInlineMessage = BotInlineResult;\nbotInlineMediaResult#17db940b flags:# id:string type:string photo:flags.0?Photo document:flags.1?Document title:flags.2?string description:flags.3?string send_message:BotInlineMessage = BotInlineResult;\nmessages.botResults#947ca848 flags:# gallery:flags.0?true query_id:long next_offset:flags.1?string switch_pm:flags.2?InlineBotSwitchPM results:Vector cache_time:int users:Vector = messages.BotResults;\nexportedMessageLink#5dab1af4 link:string html:string = ExportedMessageLink;\nmessageFwdHeader#5f777dce flags:# imported:flags.7?true from_id:flags.0?Peer from_name:flags.5?string date:int channel_post:flags.2?int post_author:flags.3?string saved_from_peer:flags.4?Peer saved_from_msg_id:flags.4?int psa_type:flags.6?string = MessageFwdHeader;\nauth.codeTypeSms#72a3158c = auth.CodeType;\nauth.codeTypeCall#741cd3e3 = auth.CodeType;\nauth.codeTypeFlashCall#226ccefb = auth.CodeType;\nauth.codeTypeMissedCall#d61ad6ee = auth.CodeType;\nauth.sentCodeTypeApp#3dbb5986 length:int = auth.SentCodeType;\nauth.sentCodeTypeSms#c000bba2 length:int = auth.SentCodeType;\nauth.sentCodeTypeCall#5353e5a7 length:int = auth.SentCodeType;\nauth.sentCodeTypeFlashCall#ab03c6d9 pattern:string = auth.SentCodeType;\nauth.sentCodeTypeMissedCall#82006484 prefix:string length:int = auth.SentCodeType;\nmessages.botCallbackAnswer#36585ea4 flags:# alert:flags.1?true has_url:flags.3?true native_ui:flags.4?true message:flags.0?string url:flags.2?string cache_time:int = messages.BotCallbackAnswer;\nmessages.messageEditData#26b5dde6 flags:# caption:flags.0?true = messages.MessageEditData;\ninputBotInlineMessageID#890c3d89 dc_id:int id:long access_hash:long = InputBotInlineMessageID;\ninputBotInlineMessageID64#b6d915d7 dc_id:int owner_id:long id:int access_hash:long = InputBotInlineMessageID;\ninlineBotSwitchPM#3c20629f text:string start_param:string = InlineBotSwitchPM;\nmessages.peerDialogs#3371c354 dialogs:Vector messages:Vector chats:Vector users:Vector state:updates.State = messages.PeerDialogs;\ntopPeer#edcdc05b peer:Peer rating:double = TopPeer;\ntopPeerCategoryBotsPM#ab661b5b = TopPeerCategory;\ntopPeerCategoryBotsInline#148677e2 = TopPeerCategory;\ntopPeerCategoryCorrespondents#637b7ed = TopPeerCategory;\ntopPeerCategoryGroups#bd17a14a = TopPeerCategory;\ntopPeerCategoryChannels#161d9628 = TopPeerCategory;\ntopPeerCategoryPhoneCalls#1e76a78c = TopPeerCategory;\ntopPeerCategoryForwardUsers#a8406ca9 = TopPeerCategory;\ntopPeerCategoryForwardChats#fbeec0f0 = TopPeerCategory;\ntopPeerCategoryPeers#fb834291 category:TopPeerCategory count:int peers:Vector = TopPeerCategoryPeers;\ncontacts.topPeersNotModified#de266ef5 = contacts.TopPeers;\ncontacts.topPeers#70b772a8 categories:Vector chats:Vector users:Vector = contacts.TopPeers;\ncontacts.topPeersDisabled#b52c939d = contacts.TopPeers;\ndraftMessageEmpty#1b0c841a flags:# date:flags.0?int = DraftMessage;\ndraftMessage#fd8e711f flags:# no_webpage:flags.1?true reply_to_msg_id:flags.0?int message:string entities:flags.3?Vector date:int = DraftMessage;\nmessages.featuredStickersNotModified#c6dc0c66 count:int = messages.FeaturedStickers;\nmessages.featuredStickers#84c02310 hash:long count:int sets:Vector unread:Vector = messages.FeaturedStickers;\nmessages.recentStickersNotModified#b17f890 = messages.RecentStickers;\nmessages.recentStickers#88d37c56 hash:long packs:Vector stickers:Vector dates:Vector = messages.RecentStickers;\nmessages.archivedStickers#4fcba9c8 count:int sets:Vector = messages.ArchivedStickers;\nmessages.stickerSetInstallResultSuccess#38641628 = messages.StickerSetInstallResult;\nmessages.stickerSetInstallResultArchive#35e410a8 sets:Vector = messages.StickerSetInstallResult;\nstickerSetCovered#6410a5d2 set:StickerSet cover:Document = StickerSetCovered;\nstickerSetMultiCovered#3407e51b set:StickerSet covers:Vector = StickerSetCovered;\nmaskCoords#aed6dbb2 n:int x:double y:double zoom:double = MaskCoords;\ninputStickeredMediaPhoto#4a992157 id:InputPhoto = InputStickeredMedia;\ninputStickeredMediaDocument#438865b id:InputDocument = InputStickeredMedia;\ngame#bdf9653b flags:# id:long access_hash:long short_name:string title:string description:string photo:Photo document:flags.0?Document = Game;\ninputGameID#32c3e77 id:long access_hash:long = InputGame;\ninputGameShortName#c331e80a bot_id:InputUser short_name:string = InputGame;\nhighScore#73a379eb pos:int user_id:long score:int = HighScore;\nmessages.highScores#9a3bfd99 scores:Vector users:Vector = messages.HighScores;\ntextEmpty#dc3d824f = RichText;\ntextPlain#744694e0 text:string = RichText;\ntextBold#6724abc4 text:RichText = RichText;\ntextItalic#d912a59c text:RichText = RichText;\ntextUnderline#c12622c4 text:RichText = RichText;\ntextStrike#9bf8bb95 text:RichText = RichText;\ntextFixed#6c3f19b9 text:RichText = RichText;\ntextUrl#3c2884c1 text:RichText url:string webpage_id:long = RichText;\ntextEmail#de5a0dd6 text:RichText email:string = RichText;\ntextConcat#7e6260d7 texts:Vector = RichText;\ntextSubscript#ed6a8504 text:RichText = RichText;\ntextSuperscript#c7fb5e01 text:RichText = RichText;\ntextMarked#34b8621 text:RichText = RichText;\ntextPhone#1ccb966a text:RichText phone:string = RichText;\ntextImage#81ccf4f document_id:long w:int h:int = RichText;\ntextAnchor#35553762 text:RichText name:string = RichText;\npageBlockUnsupported#13567e8a = PageBlock;\npageBlockTitle#70abc3fd text:RichText = PageBlock;\npageBlockSubtitle#8ffa9a1f text:RichText = PageBlock;\npageBlockAuthorDate#baafe5e0 author:RichText published_date:int = PageBlock;\npageBlockHeader#bfd064ec text:RichText = PageBlock;\npageBlockSubheader#f12bb6e1 text:RichText = PageBlock;\npageBlockParagraph#467a0766 text:RichText = PageBlock;\npageBlockPreformatted#c070d93e text:RichText language:string = PageBlock;\npageBlockFooter#48870999 text:RichText = PageBlock;\npageBlockDivider#db20b188 = PageBlock;\npageBlockAnchor#ce0d37b0 name:string = PageBlock;\npageBlockList#e4e88011 items:Vector = PageBlock;\npageBlockBlockquote#263d7c26 text:RichText caption:RichText = PageBlock;\npageBlockPullquote#4f4456d3 text:RichText caption:RichText = PageBlock;\npageBlockPhoto#1759c560 flags:# photo_id:long caption:PageCaption url:flags.0?string webpage_id:flags.0?long = PageBlock;\npageBlockVideo#7c8fe7b6 flags:# autoplay:flags.0?true loop:flags.1?true video_id:long caption:PageCaption = PageBlock;\npageBlockCover#39f23300 cover:PageBlock = PageBlock;\npageBlockEmbed#a8718dc5 flags:# full_width:flags.0?true allow_scrolling:flags.3?true url:flags.1?string html:flags.2?string poster_photo_id:flags.4?long w:flags.5?int h:flags.5?int caption:PageCaption = PageBlock;\npageBlockEmbedPost#f259a80b url:string webpage_id:long author_photo_id:long author:string date:int blocks:Vector caption:PageCaption = PageBlock;\npageBlockCollage#65a0fa4d items:Vector caption:PageCaption = PageBlock;\npageBlockSlideshow#31f9590 items:Vector caption:PageCaption = PageBlock;\npageBlockChannel#ef1751b5 channel:Chat = PageBlock;\npageBlockAudio#804361ea audio_id:long caption:PageCaption = PageBlock;\npageBlockKicker#1e148390 text:RichText = PageBlock;\npageBlockTable#bf4dea82 flags:# bordered:flags.0?true striped:flags.1?true title:RichText rows:Vector = PageBlock;\npageBlockOrderedList#9a8ae1e1 items:Vector = PageBlock;\npageBlockDetails#76768bed flags:# open:flags.0?true blocks:Vector title:RichText = PageBlock;\npageBlockRelatedArticles#16115a96 title:RichText articles:Vector = PageBlock;\npageBlockMap#a44f3ef6 geo:GeoPoint zoom:int w:int h:int caption:PageCaption = PageBlock;\nphoneCallDiscardReasonMissed#85e42301 = PhoneCallDiscardReason;\nphoneCallDiscardReasonDisconnect#e095c1a0 = PhoneCallDiscardReason;\nphoneCallDiscardReasonHangup#57adc690 = PhoneCallDiscardReason;\nphoneCallDiscardReasonBusy#faf7e8c9 = PhoneCallDiscardReason;\ndataJSON#7d748d04 data:string = DataJSON;\nlabeledPrice#cb296bf8 label:string amount:long = LabeledPrice;\ninvoice#cd886e0 flags:# test:flags.0?true name_requested:flags.1?true phone_requested:flags.2?true email_requested:flags.3?true shipping_address_requested:flags.4?true flexible:flags.5?true phone_to_provider:flags.6?true email_to_provider:flags.7?true currency:string prices:Vector max_tip_amount:flags.8?long suggested_tip_amounts:flags.8?Vector = Invoice;\npaymentCharge#ea02c27e id:string provider_charge_id:string = PaymentCharge;\npostAddress#1e8caaeb street_line1:string street_line2:string city:string state:string country_iso2:string post_code:string = PostAddress;\npaymentRequestedInfo#909c3f94 flags:# name:flags.0?string phone:flags.1?string email:flags.2?string shipping_address:flags.3?PostAddress = PaymentRequestedInfo;\npaymentSavedCredentialsCard#cdc27a1f id:string title:string = PaymentSavedCredentials;\nwebDocument#1c570ed1 url:string access_hash:long size:int mime_type:string attributes:Vector = WebDocument;\nwebDocumentNoProxy#f9c8bcc6 url:string size:int mime_type:string attributes:Vector = WebDocument;\ninputWebDocument#9bed434d url:string size:int mime_type:string attributes:Vector = InputWebDocument;\ninputWebFileLocation#c239d686 url:string access_hash:long = InputWebFileLocation;\ninputWebFileGeoPointLocation#9f2221c9 geo_point:InputGeoPoint access_hash:long w:int h:int zoom:int scale:int = InputWebFileLocation;\nupload.webFile#21e753bc size:int mime_type:string file_type:storage.FileType mtime:int bytes:bytes = upload.WebFile;\npayments.paymentForm#1694761b flags:# can_save_credentials:flags.2?true password_missing:flags.3?true form_id:long bot_id:long invoice:Invoice provider_id:long url:string native_provider:flags.4?string native_params:flags.4?DataJSON saved_info:flags.0?PaymentRequestedInfo saved_credentials:flags.1?PaymentSavedCredentials users:Vector = payments.PaymentForm;\npayments.validatedRequestedInfo#d1451883 flags:# id:flags.0?string shipping_options:flags.1?Vector = payments.ValidatedRequestedInfo;\npayments.paymentResult#4e5f810d updates:Updates = payments.PaymentResult;\npayments.paymentVerificationNeeded#d8411139 url:string = payments.PaymentResult;\npayments.paymentReceipt#70c4fe03 flags:# date:int bot_id:long provider_id:long title:string description:string photo:flags.2?WebDocument invoice:Invoice info:flags.0?PaymentRequestedInfo shipping:flags.1?ShippingOption tip_amount:flags.3?long currency:string total_amount:long credentials_title:string users:Vector = payments.PaymentReceipt;\npayments.savedInfo#fb8fe43c flags:# has_saved_credentials:flags.1?true saved_info:flags.0?PaymentRequestedInfo = payments.SavedInfo;\ninputPaymentCredentialsSaved#c10eb2cf id:string tmp_password:bytes = InputPaymentCredentials;\ninputPaymentCredentials#3417d728 flags:# save:flags.0?true data:DataJSON = InputPaymentCredentials;\ninputPaymentCredentialsApplePay#aa1c39f payment_data:DataJSON = InputPaymentCredentials;\ninputPaymentCredentialsGooglePay#8ac32801 payment_token:DataJSON = InputPaymentCredentials;\naccount.tmpPassword#db64fd34 tmp_password:bytes valid_until:int = account.TmpPassword;\nshippingOption#b6213cdf id:string title:string prices:Vector = ShippingOption;\ninputStickerSetItem#ffa0a496 flags:# document:InputDocument emoji:string mask_coords:flags.0?MaskCoords = InputStickerSetItem;\ninputPhoneCall#1e36fded id:long access_hash:long = InputPhoneCall;\nphoneCallEmpty#5366c915 id:long = PhoneCall;\nphoneCallWaiting#c5226f17 flags:# video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long protocol:PhoneCallProtocol receive_date:flags.0?int = PhoneCall;\nphoneCallRequested#14b0ed0c flags:# video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long g_a_hash:bytes protocol:PhoneCallProtocol = PhoneCall;\nphoneCallAccepted#3660c311 flags:# video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long g_b:bytes protocol:PhoneCallProtocol = PhoneCall;\nphoneCall#967f7c67 flags:# p2p_allowed:flags.5?true video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long g_a_or_b:bytes key_fingerprint:long protocol:PhoneCallProtocol connections:Vector start_date:int = PhoneCall;\nphoneCallDiscarded#50ca4de1 flags:# need_rating:flags.2?true need_debug:flags.3?true video:flags.6?true id:long reason:flags.0?PhoneCallDiscardReason duration:flags.1?int = PhoneCall;\nphoneConnection#9d4c17c0 id:long ip:string ipv6:string port:int peer_tag:bytes = PhoneConnection;\nphoneConnectionWebrtc#635fe375 flags:# turn:flags.0?true stun:flags.1?true id:long ip:string ipv6:string port:int username:string password:string = PhoneConnection;\nphoneCallProtocol#fc878fc8 flags:# udp_p2p:flags.0?true udp_reflector:flags.1?true min_layer:int max_layer:int library_versions:Vector = PhoneCallProtocol;\nphone.phoneCall#ec82e140 phone_call:PhoneCall users:Vector = phone.PhoneCall;\nupload.cdnFileReuploadNeeded#eea8e46e request_token:bytes = upload.CdnFile;\nupload.cdnFile#a99fca4f bytes:bytes = upload.CdnFile;\ncdnPublicKey#c982eaba dc_id:int public_key:string = CdnPublicKey;\ncdnConfig#5725e40a public_keys:Vector = CdnConfig;\nlangPackString#cad181f6 key:string value:string = LangPackString;\nlangPackStringPluralized#6c47ac9f flags:# key:string zero_value:flags.0?string one_value:flags.1?string two_value:flags.2?string few_value:flags.3?string many_value:flags.4?string other_value:string = LangPackString;\nlangPackStringDeleted#2979eeb2 key:string = LangPackString;\nlangPackDifference#f385c1f6 lang_code:string from_version:int version:int strings:Vector = LangPackDifference;\nlangPackLanguage#eeca5ce3 flags:# official:flags.0?true rtl:flags.2?true beta:flags.3?true name:string native_name:string lang_code:string base_lang_code:flags.1?string plural_code:string strings_count:int translated_count:int translations_url:string = LangPackLanguage;\nchannelAdminLogEventActionChangeTitle#e6dfb825 prev_value:string new_value:string = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeAbout#55188a2e prev_value:string new_value:string = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeUsername#6a4afc38 prev_value:string new_value:string = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangePhoto#434bd2af prev_photo:Photo new_photo:Photo = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleInvites#1b7907ae new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleSignatures#26ae0971 new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionUpdatePinned#e9e82c18 message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionEditMessage#709b2405 prev_message:Message new_message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionDeleteMessage#42e047bb message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantJoin#183040d3 = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantLeave#f89777f2 = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantInvite#e31c34d8 participant:ChannelParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantToggleBan#e6d83d7e prev_participant:ChannelParticipant new_participant:ChannelParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantToggleAdmin#d5676710 prev_participant:ChannelParticipant new_participant:ChannelParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeStickerSet#b1c3caa7 prev_stickerset:InputStickerSet new_stickerset:InputStickerSet = ChannelAdminLogEventAction;\nchannelAdminLogEventActionTogglePreHistoryHidden#5f5c95f1 new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionDefaultBannedRights#2df5fc0a prev_banned_rights:ChatBannedRights new_banned_rights:ChatBannedRights = ChannelAdminLogEventAction;\nchannelAdminLogEventActionStopPoll#8f079643 message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeLinkedChat#50c7ac8 prev_value:long new_value:long = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeLocation#e6b76ae prev_value:ChannelLocation new_value:ChannelLocation = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleSlowMode#53909779 prev_value:int new_value:int = ChannelAdminLogEventAction;\nchannelAdminLogEventActionStartGroupCall#23209745 call:InputGroupCall = ChannelAdminLogEventAction;\nchannelAdminLogEventActionDiscardGroupCall#db9f9140 call:InputGroupCall = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantMute#f92424d2 participant:GroupCallParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantUnmute#e64429c0 participant:GroupCallParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleGroupCallSetting#56d6a247 join_muted:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantJoinByInvite#5cdada77 invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionExportedInviteDelete#5a50fca4 invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionExportedInviteRevoke#410a134e invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionExportedInviteEdit#e90ebb59 prev_invite:ExportedChatInvite new_invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantVolume#3e7f6847 participant:GroupCallParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeHistoryTTL#6e941a38 prev_value:int new_value:int = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantJoinByRequest#afb6144a invite:ExportedChatInvite approved_by:long = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleNoForwards#cb2ac766 new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionSendMessage#278f2868 message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeAvailableReactions#9cf7f76a prev_value:Vector new_value:Vector = ChannelAdminLogEventAction;\nchannelAdminLogEvent#1fad68cd id:long date:int user_id:long action:ChannelAdminLogEventAction = ChannelAdminLogEvent;\nchannels.adminLogResults#ed8af74d events:Vector chats:Vector users:Vector = channels.AdminLogResults;\nchannelAdminLogEventsFilter#ea107ae4 flags:# join:flags.0?true leave:flags.1?true invite:flags.2?true ban:flags.3?true unban:flags.4?true kick:flags.5?true unkick:flags.6?true promote:flags.7?true demote:flags.8?true info:flags.9?true settings:flags.10?true pinned:flags.11?true edit:flags.12?true delete:flags.13?true group_call:flags.14?true invites:flags.15?true send:flags.16?true = ChannelAdminLogEventsFilter;\npopularContact#5ce14175 client_id:long importers:int = PopularContact;\nmessages.favedStickersNotModified#9e8fa6d3 = messages.FavedStickers;\nmessages.favedStickers#2cb51097 hash:long packs:Vector stickers:Vector = messages.FavedStickers;\nrecentMeUrlUnknown#46e1d13d url:string = RecentMeUrl;\nrecentMeUrlUser#b92c09e2 url:string user_id:long = RecentMeUrl;\nrecentMeUrlChat#b2da71d2 url:string chat_id:long = RecentMeUrl;\nrecentMeUrlChatInvite#eb49081d url:string chat_invite:ChatInvite = RecentMeUrl;\nrecentMeUrlStickerSet#bc0a57dc url:string set:StickerSetCovered = RecentMeUrl;\nhelp.recentMeUrls#e0310d7 urls:Vector chats:Vector users:Vector = help.RecentMeUrls;\ninputSingleMedia#1cc6e91f flags:# media:InputMedia random_id:long message:string entities:flags.0?Vector = InputSingleMedia;\nwebAuthorization#a6f8f452 hash:long bot_id:long domain:string browser:string platform:string date_created:int date_active:int ip:string region:string = WebAuthorization;\naccount.webAuthorizations#ed56c9fc authorizations:Vector users:Vector = account.WebAuthorizations;\ninputMessageID#a676a322 id:int = InputMessage;\ninputMessageReplyTo#bad88395 id:int = InputMessage;\ninputMessagePinned#86872538 = InputMessage;\ninputMessageCallbackQuery#acfa1a7e id:int query_id:long = InputMessage;\ninputDialogPeer#fcaafeb7 peer:InputPeer = InputDialogPeer;\ninputDialogPeerFolder#64600527 folder_id:int = InputDialogPeer;\ndialogPeer#e56dbf05 peer:Peer = DialogPeer;\ndialogPeerFolder#514519e2 folder_id:int = DialogPeer;\nmessages.foundStickerSetsNotModified#d54b65d = messages.FoundStickerSets;\nmessages.foundStickerSets#8af09dd2 hash:long sets:Vector = messages.FoundStickerSets;\nfileHash#6242c773 offset:int limit:int hash:bytes = FileHash;\ninputClientProxy#75588b3f address:string port:int = InputClientProxy;\nhelp.termsOfServiceUpdateEmpty#e3309f7f expires:int = help.TermsOfServiceUpdate;\nhelp.termsOfServiceUpdate#28ecf961 expires:int terms_of_service:help.TermsOfService = help.TermsOfServiceUpdate;\ninputSecureFileUploaded#3334b0f0 id:long parts:int md5_checksum:string file_hash:bytes secret:bytes = InputSecureFile;\ninputSecureFile#5367e5be id:long access_hash:long = InputSecureFile;\nsecureFileEmpty#64199744 = SecureFile;\nsecureFile#e0277a62 id:long access_hash:long size:int dc_id:int date:int file_hash:bytes secret:bytes = SecureFile;\nsecureData#8aeabec3 data:bytes data_hash:bytes secret:bytes = SecureData;\nsecurePlainPhone#7d6099dd phone:string = SecurePlainData;\nsecurePlainEmail#21ec5a5f email:string = SecurePlainData;\nsecureValueTypePersonalDetails#9d2a81e3 = SecureValueType;\nsecureValueTypePassport#3dac6a00 = SecureValueType;\nsecureValueTypeDriverLicense#6e425c4 = SecureValueType;\nsecureValueTypeIdentityCard#a0d0744b = SecureValueType;\nsecureValueTypeInternalPassport#99a48f23 = SecureValueType;\nsecureValueTypeAddress#cbe31e26 = SecureValueType;\nsecureValueTypeUtilityBill#fc36954e = SecureValueType;\nsecureValueTypeBankStatement#89137c0d = SecureValueType;\nsecureValueTypeRentalAgreement#8b883488 = SecureValueType;\nsecureValueTypePassportRegistration#99e3806a = SecureValueType;\nsecureValueTypeTemporaryRegistration#ea02ec33 = SecureValueType;\nsecureValueTypePhone#b320aadb = SecureValueType;\nsecureValueTypeEmail#8e3ca7ee = SecureValueType;\nsecureValue#187fa0ca flags:# type:SecureValueType data:flags.0?SecureData front_side:flags.1?SecureFile reverse_side:flags.2?SecureFile selfie:flags.3?SecureFile translation:flags.6?Vector files:flags.4?Vector plain_data:flags.5?SecurePlainData hash:bytes = SecureValue;\ninputSecureValue#db21d0a7 flags:# type:SecureValueType data:flags.0?SecureData front_side:flags.1?InputSecureFile reverse_side:flags.2?InputSecureFile selfie:flags.3?InputSecureFile translation:flags.6?Vector files:flags.4?Vector plain_data:flags.5?SecurePlainData = InputSecureValue;\nsecureValueHash#ed1ecdb0 type:SecureValueType hash:bytes = SecureValueHash;\nsecureValueErrorData#e8a40bd9 type:SecureValueType data_hash:bytes field:string text:string = SecureValueError;\nsecureValueErrorFrontSide#be3dfa type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorReverseSide#868a2aa5 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorSelfie#e537ced6 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorFile#7a700873 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorFiles#666220e9 type:SecureValueType file_hash:Vector text:string = SecureValueError;\nsecureValueError#869d758f type:SecureValueType hash:bytes text:string = SecureValueError;\nsecureValueErrorTranslationFile#a1144770 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorTranslationFiles#34636dd8 type:SecureValueType file_hash:Vector text:string = SecureValueError;\nsecureCredentialsEncrypted#33f0ea47 data:bytes hash:bytes secret:bytes = SecureCredentialsEncrypted;\naccount.authorizationForm#ad2e1cd8 flags:# required_types:Vector values:Vector errors:Vector users:Vector privacy_policy_url:flags.0?string = account.AuthorizationForm;\naccount.sentEmailCode#811f854f email_pattern:string length:int = account.SentEmailCode;\nhelp.deepLinkInfoEmpty#66afa166 = help.DeepLinkInfo;\nhelp.deepLinkInfo#6a4ee832 flags:# update_app:flags.0?true message:string entities:flags.1?Vector = help.DeepLinkInfo;\nsavedPhoneContact#1142bd56 phone:string first_name:string last_name:string date:int = SavedContact;\naccount.takeout#4dba4501 id:long = account.Takeout;\npasswordKdfAlgoUnknown#d45ab096 = PasswordKdfAlgo;\npasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow#3a912d4a salt1:bytes salt2:bytes g:int p:bytes = PasswordKdfAlgo;\nsecurePasswordKdfAlgoUnknown#4a8537 = SecurePasswordKdfAlgo;\nsecurePasswordKdfAlgoPBKDF2HMACSHA512iter100000#bbf2dda0 salt:bytes = SecurePasswordKdfAlgo;\nsecurePasswordKdfAlgoSHA512#86471d92 salt:bytes = SecurePasswordKdfAlgo;\nsecureSecretSettings#1527bcac secure_algo:SecurePasswordKdfAlgo secure_secret:bytes secure_secret_id:long = SecureSecretSettings;\ninputCheckPasswordEmpty#9880f658 = InputCheckPasswordSRP;\ninputCheckPasswordSRP#d27ff082 srp_id:long A:bytes M1:bytes = InputCheckPasswordSRP;\nsecureRequiredType#829d99da flags:# native_names:flags.0?true selfie_required:flags.1?true translation_required:flags.2?true type:SecureValueType = SecureRequiredType;\nsecureRequiredTypeOneOf#27477b4 types:Vector = SecureRequiredType;\nhelp.passportConfigNotModified#bfb9f457 = help.PassportConfig;\nhelp.passportConfig#a098d6af hash:int countries_langs:DataJSON = help.PassportConfig;\ninputAppEvent#1d1b1245 time:double type:string peer:long data:JSONValue = InputAppEvent;\njsonObjectValue#c0de1bd9 key:string value:JSONValue = JSONObjectValue;\njsonNull#3f6d7b68 = JSONValue;\njsonBool#c7345e6a value:Bool = JSONValue;\njsonNumber#2be0dfa4 value:double = JSONValue;\njsonString#b71e767a value:string = JSONValue;\njsonArray#f7444763 value:Vector = JSONValue;\njsonObject#99c1d49d value:Vector = JSONValue;\npageTableCell#34566b6a flags:# header:flags.0?true align_center:flags.3?true align_right:flags.4?true valign_middle:flags.5?true valign_bottom:flags.6?true text:flags.7?RichText colspan:flags.1?int rowspan:flags.2?int = PageTableCell;\npageTableRow#e0c0c5e5 cells:Vector = PageTableRow;\npageCaption#6f747657 text:RichText credit:RichText = PageCaption;\npageListItemText#b92fb6cd text:RichText = PageListItem;\npageListItemBlocks#25e073fc blocks:Vector = PageListItem;\npageListOrderedItemText#5e068047 num:string text:RichText = PageListOrderedItem;\npageListOrderedItemBlocks#98dd8936 num:string blocks:Vector = PageListOrderedItem;\npageRelatedArticle#b390dc08 flags:# url:string webpage_id:long title:flags.0?string description:flags.1?string photo_id:flags.2?long author:flags.3?string published_date:flags.4?int = PageRelatedArticle;\npage#98657f0d flags:# part:flags.0?true rtl:flags.1?true v2:flags.2?true url:string blocks:Vector photos:Vector documents:Vector views:flags.3?int = Page;\nhelp.supportName#8c05f1c9 name:string = help.SupportName;\nhelp.userInfoEmpty#f3ae2eed = help.UserInfo;\nhelp.userInfo#1eb3758 message:string entities:Vector author:string date:int = help.UserInfo;\npollAnswer#6ca9c2e9 text:string option:bytes = PollAnswer;\npoll#86e18161 id:long flags:# closed:flags.0?true public_voters:flags.1?true multiple_choice:flags.2?true quiz:flags.3?true question:string answers:Vector close_period:flags.4?int close_date:flags.5?int = Poll;\npollAnswerVoters#3b6ddad2 flags:# chosen:flags.0?true correct:flags.1?true option:bytes voters:int = PollAnswerVoters;\npollResults#dcb82ea3 flags:# min:flags.0?true results:flags.1?Vector total_voters:flags.2?int recent_voters:flags.3?Vector solution:flags.4?string solution_entities:flags.4?Vector = PollResults;\nchatOnlines#f041e250 onlines:int = ChatOnlines;\nstatsURL#47a971e0 url:string = StatsURL;\nchatAdminRights#5fb224d5 flags:# change_info:flags.0?true post_messages:flags.1?true edit_messages:flags.2?true delete_messages:flags.3?true ban_users:flags.4?true invite_users:flags.5?true pin_messages:flags.7?true add_admins:flags.9?true anonymous:flags.10?true manage_call:flags.11?true other:flags.12?true = ChatAdminRights;\nchatBannedRights#9f120418 flags:# view_messages:flags.0?true send_messages:flags.1?true send_media:flags.2?true send_stickers:flags.3?true send_gifs:flags.4?true send_games:flags.5?true send_inline:flags.6?true embed_links:flags.7?true send_polls:flags.8?true change_info:flags.10?true invite_users:flags.15?true pin_messages:flags.17?true until_date:int = ChatBannedRights;\ninputWallPaper#e630b979 id:long access_hash:long = InputWallPaper;\ninputWallPaperSlug#72091c80 slug:string = InputWallPaper;\ninputWallPaperNoFile#967a462e id:long = InputWallPaper;\naccount.wallPapersNotModified#1c199183 = account.WallPapers;\naccount.wallPapers#cdc3858c hash:long wallpapers:Vector = account.WallPapers;\ncodeSettings#8a6469c2 flags:# allow_flashcall:flags.0?true current_number:flags.1?true allow_app_hash:flags.4?true allow_missed_call:flags.5?true logout_tokens:flags.6?Vector = CodeSettings;\nwallPaperSettings#1dc1bca4 flags:# blur:flags.1?true motion:flags.2?true background_color:flags.0?int second_background_color:flags.4?int third_background_color:flags.5?int fourth_background_color:flags.6?int intensity:flags.3?int rotation:flags.4?int = WallPaperSettings;\nautoDownloadSettings#e04232f3 flags:# disabled:flags.0?true video_preload_large:flags.1?true audio_preload_next:flags.2?true phonecalls_less_data:flags.3?true photo_size_max:int video_size_max:int file_size_max:int video_upload_maxbitrate:int = AutoDownloadSettings;\naccount.autoDownloadSettings#63cacf26 low:AutoDownloadSettings medium:AutoDownloadSettings high:AutoDownloadSettings = account.AutoDownloadSettings;\nemojiKeyword#d5b3b9f9 keyword:string emoticons:Vector = EmojiKeyword;\nemojiKeywordDeleted#236df622 keyword:string emoticons:Vector = EmojiKeyword;\nemojiKeywordsDifference#5cc761bd lang_code:string from_version:int version:int keywords:Vector = EmojiKeywordsDifference;\nemojiURL#a575739d url:string = EmojiURL;\nemojiLanguage#b3fb5361 lang_code:string = EmojiLanguage;\nfolder#ff544e65 flags:# autofill_new_broadcasts:flags.0?true autofill_public_groups:flags.1?true autofill_new_correspondents:flags.2?true id:int title:string photo:flags.3?ChatPhoto = Folder;\ninputFolderPeer#fbd2c296 peer:InputPeer folder_id:int = InputFolderPeer;\nfolderPeer#e9baa668 peer:Peer folder_id:int = FolderPeer;\nmessages.searchCounter#e844ebff flags:# inexact:flags.1?true filter:MessagesFilter count:int = messages.SearchCounter;\nurlAuthResultRequest#92d33a0e flags:# request_write_access:flags.0?true bot:User domain:string = UrlAuthResult;\nurlAuthResultAccepted#8f8c0e4e url:string = UrlAuthResult;\nurlAuthResultDefault#a9d6db1f = UrlAuthResult;\nchannelLocationEmpty#bfb5ad8b = ChannelLocation;\nchannelLocation#209b82db geo_point:GeoPoint address:string = ChannelLocation;\npeerLocated#ca461b5d peer:Peer expires:int distance:int = PeerLocated;\npeerSelfLocated#f8ec284b expires:int = PeerLocated;\nrestrictionReason#d072acb4 platform:string reason:string text:string = RestrictionReason;\ninputTheme#3c5693e9 id:long access_hash:long = InputTheme;\ninputThemeSlug#f5890df1 slug:string = InputTheme;\ntheme#a00e67d6 flags:# creator:flags.0?true default:flags.1?true for_chat:flags.5?true id:long access_hash:long slug:string title:string document:flags.2?Document settings:flags.3?Vector emoticon:flags.6?string installs_count:flags.4?int = Theme;\naccount.themesNotModified#f41eb622 = account.Themes;\naccount.themes#9a3d8c6d hash:long themes:Vector = account.Themes;\nauth.loginToken#629f1980 expires:int token:bytes = auth.LoginToken;\nauth.loginTokenMigrateTo#68e9916 dc_id:int token:bytes = auth.LoginToken;\nauth.loginTokenSuccess#390d5c5e authorization:auth.Authorization = auth.LoginToken;\naccount.contentSettings#57e28221 flags:# sensitive_enabled:flags.0?true sensitive_can_change:flags.1?true = account.ContentSettings;\nmessages.inactiveChats#a927fec5 dates:Vector chats:Vector users:Vector = messages.InactiveChats;\nbaseThemeClassic#c3a12462 = BaseTheme;\nbaseThemeDay#fbd81688 = BaseTheme;\nbaseThemeNight#b7b31ea8 = BaseTheme;\nbaseThemeTinted#6d5f77ee = BaseTheme;\nbaseThemeArctic#5b11125a = BaseTheme;\ninputThemeSettings#8fde504f flags:# message_colors_animated:flags.2?true base_theme:BaseTheme accent_color:int outbox_accent_color:flags.3?int message_colors:flags.0?Vector wallpaper:flags.1?InputWallPaper wallpaper_settings:flags.1?WallPaperSettings = InputThemeSettings;\nthemeSettings#fa58b6d4 flags:# message_colors_animated:flags.2?true base_theme:BaseTheme accent_color:int outbox_accent_color:flags.3?int message_colors:flags.0?Vector wallpaper:flags.1?WallPaper = ThemeSettings;\nwebPageAttributeTheme#54b56617 flags:# documents:flags.0?Vector settings:flags.1?ThemeSettings = WebPageAttribute;\nmessageUserVote#34d247b4 user_id:long option:bytes date:int = MessageUserVote;\nmessageUserVoteInputOption#3ca5b0ec user_id:long date:int = MessageUserVote;\nmessageUserVoteMultiple#8a65e557 user_id:long options:Vector date:int = MessageUserVote;\nmessages.votesList#823f649 flags:# count:int votes:Vector users:Vector next_offset:flags.0?string = messages.VotesList;\nbankCardOpenUrl#f568028a url:string name:string = BankCardOpenUrl;\npayments.bankCardData#3e24e573 title:string open_urls:Vector = payments.BankCardData;\ndialogFilter#7438f7e8 flags:# contacts:flags.0?true non_contacts:flags.1?true groups:flags.2?true broadcasts:flags.3?true bots:flags.4?true exclude_muted:flags.11?true exclude_read:flags.12?true exclude_archived:flags.13?true id:int title:string emoticon:flags.25?string pinned_peers:Vector include_peers:Vector exclude_peers:Vector = DialogFilter;\ndialogFilterSuggested#77744d4a filter:DialogFilter description:string = DialogFilterSuggested;\nstatsDateRangeDays#b637edaf min_date:int max_date:int = StatsDateRangeDays;\nstatsAbsValueAndPrev#cb43acde current:double previous:double = StatsAbsValueAndPrev;\nstatsPercentValue#cbce2fe0 part:double total:double = StatsPercentValue;\nstatsGraphAsync#4a27eb2d token:string = StatsGraph;\nstatsGraphError#bedc9822 error:string = StatsGraph;\nstatsGraph#8ea464b6 flags:# json:DataJSON zoom_token:flags.0?string = StatsGraph;\nmessageInteractionCounters#ad4fc9bd msg_id:int views:int forwards:int = MessageInteractionCounters;\nstats.broadcastStats#bdf78394 period:StatsDateRangeDays followers:StatsAbsValueAndPrev views_per_post:StatsAbsValueAndPrev shares_per_post:StatsAbsValueAndPrev enabled_notifications:StatsPercentValue growth_graph:StatsGraph followers_graph:StatsGraph mute_graph:StatsGraph top_hours_graph:StatsGraph interactions_graph:StatsGraph iv_interactions_graph:StatsGraph views_by_source_graph:StatsGraph new_followers_by_source_graph:StatsGraph languages_graph:StatsGraph recent_message_interactions:Vector = stats.BroadcastStats;\nhelp.promoDataEmpty#98f6ac75 expires:int = help.PromoData;\nhelp.promoData#8c39793f flags:# proxy:flags.0?true expires:int peer:Peer chats:Vector users:Vector psa_type:flags.1?string psa_message:flags.2?string = help.PromoData;\nvideoSize#de33b094 flags:# type:string w:int h:int size:int video_start_ts:flags.0?double = VideoSize;\nstatsGroupTopPoster#9d04af9b user_id:long messages:int avg_chars:int = StatsGroupTopPoster;\nstatsGroupTopAdmin#d7584c87 user_id:long deleted:int kicked:int banned:int = StatsGroupTopAdmin;\nstatsGroupTopInviter#535f779d user_id:long invitations:int = StatsGroupTopInviter;\nstats.megagroupStats#ef7ff916 period:StatsDateRangeDays members:StatsAbsValueAndPrev messages:StatsAbsValueAndPrev viewers:StatsAbsValueAndPrev posters:StatsAbsValueAndPrev growth_graph:StatsGraph members_graph:StatsGraph new_members_by_source_graph:StatsGraph languages_graph:StatsGraph messages_graph:StatsGraph actions_graph:StatsGraph top_hours_graph:StatsGraph weekdays_graph:StatsGraph top_posters:Vector top_admins:Vector top_inviters:Vector users:Vector = stats.MegagroupStats;\nglobalPrivacySettings#bea2f424 flags:# archive_and_mute_new_noncontact_peers:flags.0?Bool = GlobalPrivacySettings;\nhelp.countryCode#4203c5ef flags:# country_code:string prefixes:flags.0?Vector patterns:flags.1?Vector = help.CountryCode;\nhelp.country#c3878e23 flags:# hidden:flags.0?true iso2:string default_name:string name:flags.1?string country_codes:Vector = help.Country;\nhelp.countriesListNotModified#93cc1f32 = help.CountriesList;\nhelp.countriesList#87d0759e countries:Vector hash:int = help.CountriesList;\nmessageViews#455b853d flags:# views:flags.0?int forwards:flags.1?int replies:flags.2?MessageReplies = MessageViews;\nmessages.messageViews#b6c4f543 views:Vector chats:Vector users:Vector = messages.MessageViews;\nmessages.discussionMessage#a6341782 flags:# messages:Vector max_id:flags.0?int read_inbox_max_id:flags.1?int read_outbox_max_id:flags.2?int unread_count:int chats:Vector users:Vector = messages.DiscussionMessage;\nmessageReplyHeader#a6d57763 flags:# reply_to_msg_id:int reply_to_peer_id:flags.0?Peer reply_to_top_id:flags.1?int = MessageReplyHeader;\nmessageReplies#83d60fc2 flags:# comments:flags.0?true replies:int replies_pts:int recent_repliers:flags.1?Vector channel_id:flags.0?long max_id:flags.2?int read_max_id:flags.3?int = MessageReplies;\npeerBlocked#e8fd8014 peer_id:Peer date:int = PeerBlocked;\nstats.messageStats#8999f295 views_graph:StatsGraph = stats.MessageStats;\ngroupCallDiscarded#7780bcb4 id:long access_hash:long duration:int = GroupCall;\ngroupCall#d597650c flags:# join_muted:flags.1?true can_change_join_muted:flags.2?true join_date_asc:flags.6?true schedule_start_subscribed:flags.8?true can_start_video:flags.9?true record_video_active:flags.11?true id:long access_hash:long participants_count:int title:flags.3?string stream_dc_id:flags.4?int record_start_date:flags.5?int schedule_date:flags.7?int unmuted_video_count:flags.10?int unmuted_video_limit:int version:int = GroupCall;\ninputGroupCall#d8aa840f id:long access_hash:long = InputGroupCall;\ngroupCallParticipant#eba636fe flags:# muted:flags.0?true left:flags.1?true can_self_unmute:flags.2?true just_joined:flags.4?true versioned:flags.5?true min:flags.8?true muted_by_you:flags.9?true volume_by_admin:flags.10?true self:flags.12?true video_joined:flags.15?true peer:Peer date:int active_date:flags.3?int source:int volume:flags.7?int about:flags.11?string raise_hand_rating:flags.13?long video:flags.6?GroupCallParticipantVideo presentation:flags.14?GroupCallParticipantVideo = GroupCallParticipant;\nphone.groupCall#9e727aad call:GroupCall participants:Vector participants_next_offset:string chats:Vector users:Vector = phone.GroupCall;\nphone.groupParticipants#f47751b6 count:int participants:Vector next_offset:string chats:Vector users:Vector version:int = phone.GroupParticipants;\ninlineQueryPeerTypeSameBotPM#3081ed9d = InlineQueryPeerType;\ninlineQueryPeerTypePM#833c0fac = InlineQueryPeerType;\ninlineQueryPeerTypeChat#d766c50a = InlineQueryPeerType;\ninlineQueryPeerTypeMegagroup#5ec4be43 = InlineQueryPeerType;\ninlineQueryPeerTypeBroadcast#6334ee9a = InlineQueryPeerType;\nmessages.historyImport#1662af0b id:long = messages.HistoryImport;\nmessages.historyImportParsed#5e0fb7b9 flags:# pm:flags.0?true group:flags.1?true title:flags.2?string = messages.HistoryImportParsed;\nmessages.affectedFoundMessages#ef8d3e6c pts:int pts_count:int offset:int messages:Vector = messages.AffectedFoundMessages;\nchatInviteImporter#8c5adfd9 flags:# requested:flags.0?true user_id:long date:int about:flags.2?string approved_by:flags.1?long = ChatInviteImporter;\nmessages.exportedChatInvites#bdc62dcc count:int invites:Vector users:Vector = messages.ExportedChatInvites;\nmessages.exportedChatInvite#1871be50 invite:ExportedChatInvite users:Vector = messages.ExportedChatInvite;\nmessages.exportedChatInviteReplaced#222600ef invite:ExportedChatInvite new_invite:ExportedChatInvite users:Vector = messages.ExportedChatInvite;\nmessages.chatInviteImporters#81b6b00a count:int importers:Vector users:Vector = messages.ChatInviteImporters;\nchatAdminWithInvites#f2ecef23 admin_id:long invites_count:int revoked_invites_count:int = ChatAdminWithInvites;\nmessages.chatAdminsWithInvites#b69b72d7 admins:Vector users:Vector = messages.ChatAdminsWithInvites;\nmessages.checkedHistoryImportPeer#a24de717 confirm_text:string = messages.CheckedHistoryImportPeer;\nphone.joinAsPeers#afe5623f peers:Vector chats:Vector users:Vector = phone.JoinAsPeers;\nphone.exportedGroupCallInvite#204bd158 link:string = phone.ExportedGroupCallInvite;\ngroupCallParticipantVideoSourceGroup#dcb118b7 semantics:string sources:Vector = GroupCallParticipantVideoSourceGroup;\ngroupCallParticipantVideo#67753ac8 flags:# paused:flags.0?true endpoint:string source_groups:Vector audio_source:flags.1?int = GroupCallParticipantVideo;\nstickers.suggestedShortName#85fea03f short_name:string = stickers.SuggestedShortName;\nbotCommandScopeDefault#2f6cb2ab = BotCommandScope;\nbotCommandScopeUsers#3c4f04d8 = BotCommandScope;\nbotCommandScopeChats#6fe1a881 = BotCommandScope;\nbotCommandScopeChatAdmins#b9aa606a = BotCommandScope;\nbotCommandScopePeer#db9d897d peer:InputPeer = BotCommandScope;\nbotCommandScopePeerAdmins#3fd863d1 peer:InputPeer = BotCommandScope;\nbotCommandScopePeerUser#a1321f3 peer:InputPeer user_id:InputUser = BotCommandScope;\naccount.resetPasswordFailedWait#e3779861 retry_date:int = account.ResetPasswordResult;\naccount.resetPasswordRequestedWait#e9effc7d until_date:int = account.ResetPasswordResult;\naccount.resetPasswordOk#e926d63e = account.ResetPasswordResult;\nsponsoredMessage#3a836df8 flags:# random_id:bytes from_id:flags.3?Peer chat_invite:flags.4?ChatInvite chat_invite_hash:flags.4?string channel_post:flags.2?int start_param:flags.0?string message:string entities:flags.1?Vector = SponsoredMessage;\nmessages.sponsoredMessages#65a4c7d5 messages:Vector chats:Vector users:Vector = messages.SponsoredMessages;\nsearchResultsCalendarPeriod#c9b0539f date:int min_msg_id:int max_msg_id:int count:int = SearchResultsCalendarPeriod;\nmessages.searchResultsCalendar#147ee23c flags:# inexact:flags.0?true count:int min_date:int min_msg_id:int offset_id_offset:flags.1?int periods:Vector messages:Vector chats:Vector users:Vector = messages.SearchResultsCalendar;\nsearchResultPosition#7f648b67 msg_id:int date:int offset:int = SearchResultsPosition;\nmessages.searchResultsPositions#53b22baf count:int positions:Vector = messages.SearchResultsPositions;\nchannels.sendAsPeers#8356cda9 peers:Vector chats:Vector users:Vector = channels.SendAsPeers;\nusers.userFull#3b6d152e full_user:UserFull chats:Vector users:Vector = users.UserFull;\nmessages.peerSettings#6880b94d settings:PeerSettings chats:Vector users:Vector = messages.PeerSettings;\nauth.loggedOut#c3a2835f flags:# future_auth_token:flags.0?bytes = auth.LoggedOut;\nreactionCount#6fb250d1 flags:# chosen:flags.0?true reaction:string count:int = ReactionCount;\nmessageReactions#87b6e36 flags:# min:flags.0?true can_see_list:flags.2?true results:Vector recent_reactons:flags.1?Vector = MessageReactions;\nmessageUserReaction#932844fa user_id:long reaction:string = MessageUserReaction;\nmessages.messageReactionsList#a366923c flags:# count:int reactions:Vector users:Vector next_offset:flags.0?string = messages.MessageReactionsList;\navailableReaction#21d7c4b flags:# inactive:flags.0?true reaction:string title:string static_icon:Document appear_animation:Document select_animation:Document activate_animation:Document effect_animation:Document = AvailableReaction;\nmessages.availableReactionsNotModified#9f071957 = messages.AvailableReactions;\nmessages.availableReactions#768e3aad hash:int reactions:Vector = messages.AvailableReactions;\n---functions---\ninitConnection#c1cd5ea9 {X:Type} flags:# api_id:int device_model:string system_version:string app_version:string system_lang_code:string lang_pack:string lang_code:string proxy:flags.0?InputClientProxy params:flags.1?JSONValue query:!X = X;\ninvokeWithLayer#da9b0d0d {X:Type} layer:int query:!X = X;\nauth.sendCode#a677244f phone_number:string api_id:int api_hash:string settings:CodeSettings = auth.SentCode;\nauth.signUp#80eee427 phone_number:string phone_code_hash:string first_name:string last_name:string = auth.Authorization;\nauth.signIn#bcd51581 phone_number:string phone_code_hash:string phone_code:string = auth.Authorization;\nauth.logOut#3e72ba19 = auth.LoggedOut;\nauth.resetAuthorizations#9fab0d1a = Bool;\nauth.exportAuthorization#e5bfffcd dc_id:int = auth.ExportedAuthorization;\nauth.importAuthorization#a57a7dad id:long bytes:bytes = auth.Authorization;\nauth.bindTempAuthKey#cdd42a05 perm_auth_key_id:long nonce:long expires_at:int encrypted_message:bytes = Bool;\nauth.checkPassword#d18b4d16 password:InputCheckPasswordSRP = auth.Authorization;\nauth.requestPasswordRecovery#d897bc66 = auth.PasswordRecovery;\nauth.resendCode#3ef1a9bf phone_number:string phone_code_hash:string = auth.SentCode;\nauth.cancelCode#1f040578 phone_number:string phone_code_hash:string = Bool;\nauth.dropTempAuthKeys#8e48a188 except_auth_keys:Vector = Bool;\nauth.exportLoginToken#b7e085fe api_id:int api_hash:string except_ids:Vector = auth.LoginToken;\nauth.importLoginToken#95ac5ce4 token:bytes = auth.LoginToken;\naccount.registerDevice#ec86017a flags:# no_muted:flags.0?true token_type:int token:string app_sandbox:Bool secret:bytes other_uids:Vector = Bool;\naccount.unregisterDevice#6a0d3206 token_type:int token:string other_uids:Vector = Bool;\naccount.updateNotifySettings#84be5b93 peer:InputNotifyPeer settings:InputPeerNotifySettings = Bool;\naccount.getNotifySettings#12b3ad31 peer:InputNotifyPeer = PeerNotifySettings;\naccount.updateProfile#78515775 flags:# first_name:flags.0?string last_name:flags.1?string about:flags.2?string = User;\naccount.updateStatus#6628562c offline:Bool = Bool;\naccount.getWallPapers#7967d36 hash:long = account.WallPapers;\naccount.checkUsername#2714d86c username:string = Bool;\naccount.updateUsername#3e0bdd7c username:string = User;\naccount.getPrivacy#dadbc950 key:InputPrivacyKey = account.PrivacyRules;\naccount.setPrivacy#c9f81ce8 key:InputPrivacyKey rules:Vector = account.PrivacyRules;\naccount.getAuthorizations#e320c158 = account.Authorizations;\naccount.resetAuthorization#df77f3bc hash:long = Bool;\naccount.getPassword#548a30f5 = account.Password;\naccount.getPasswordSettings#9cd4eaf9 password:InputCheckPasswordSRP = account.PasswordSettings;\naccount.updatePasswordSettings#a59b102f password:InputCheckPasswordSRP new_settings:account.PasswordInputSettings = Bool;\naccount.sendConfirmPhoneCode#1b3faa88 hash:string settings:CodeSettings = auth.SentCode;\naccount.confirmPhone#5f2178c3 phone_code_hash:string phone_code:string = Bool;\naccount.getTmpPassword#449e0b51 password:InputCheckPasswordSRP period:int = account.TmpPassword;\naccount.sendVerifyPhoneCode#a5a356f9 phone_number:string settings:CodeSettings = auth.SentCode;\naccount.confirmPasswordEmail#8fdf1920 code:string = Bool;\naccount.getContactSignUpNotification#9f07c728 = Bool;\naccount.setContactSignUpNotification#cff43f61 silent:Bool = Bool;\naccount.getNotifyExceptions#53577479 flags:# compare_sound:flags.1?true peer:flags.0?InputNotifyPeer = Updates;\naccount.uploadWallPaper#dd853661 file:InputFile mime_type:string settings:WallPaperSettings = WallPaper;\naccount.setContentSettings#b574b16b flags:# sensitive_enabled:flags.0?true = Bool;\naccount.getContentSettings#8b9b4dae = account.ContentSettings;\nusers.getUsers#d91a548 id:Vector = Vector;\nusers.getFullUser#b60f5918 id:InputUser = users.UserFull;\ncontacts.getContacts#5dd69e12 hash:long = contacts.Contacts;\ncontacts.importContacts#2c800be5 contacts:Vector = contacts.ImportedContacts;\ncontacts.deleteContacts#96a0e00 id:Vector = Updates;\ncontacts.block#68cc1411 id:InputPeer = Bool;\ncontacts.unblock#bea65d50 id:InputPeer = Bool;\ncontacts.getBlocked#f57c350f offset:int limit:int = contacts.Blocked;\ncontacts.search#11f812d8 q:string limit:int = contacts.Found;\ncontacts.resolveUsername#f93ccba3 username:string = contacts.ResolvedPeer;\ncontacts.getTopPeers#973478b6 flags:# correspondents:flags.0?true bots_pm:flags.1?true bots_inline:flags.2?true phone_calls:flags.3?true forward_users:flags.4?true forward_chats:flags.5?true groups:flags.10?true channels:flags.15?true offset:int limit:int hash:long = contacts.TopPeers;\ncontacts.addContact#e8f463d0 flags:# add_phone_privacy_exception:flags.0?true id:InputUser first_name:string last_name:string phone:string = Updates;\nmessages.getMessages#63c66506 id:Vector = messages.Messages;\nmessages.getDialogs#a0f4cb4f flags:# exclude_pinned:flags.0?true folder_id:flags.1?int offset_date:int offset_id:int offset_peer:InputPeer limit:int hash:long = messages.Dialogs;\nmessages.getHistory#4423e6c5 peer:InputPeer offset_id:int offset_date:int add_offset:int limit:int max_id:int min_id:int hash:long = messages.Messages;\nmessages.search#a0fda762 flags:# peer:InputPeer q:string from_id:flags.0?InputPeer top_msg_id:flags.1?int filter:MessagesFilter min_date:int max_date:int offset_id:int add_offset:int limit:int max_id:int min_id:int hash:long = messages.Messages;\nmessages.readHistory#e306d3a peer:InputPeer max_id:int = messages.AffectedMessages;\nmessages.deleteHistory#b08f922a flags:# just_clear:flags.0?true revoke:flags.1?true peer:InputPeer max_id:int min_date:flags.2?int max_date:flags.3?int = messages.AffectedHistory;\nmessages.deleteMessages#e58e95d2 flags:# revoke:flags.0?true id:Vector = messages.AffectedMessages;\nmessages.receivedMessages#5a954c0 max_id:int = Vector;\nmessages.setTyping#58943ee2 flags:# peer:InputPeer top_msg_id:flags.0?int action:SendMessageAction = Bool;\nmessages.sendMessage#d9d75a4 flags:# no_webpage:flags.1?true silent:flags.5?true background:flags.6?true clear_draft:flags.7?true noforwards:flags.14?true peer:InputPeer reply_to_msg_id:flags.0?int message:string random_id:long reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector schedule_date:flags.10?int send_as:flags.13?InputPeer = Updates;\nmessages.sendMedia#e25ff8e0 flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true noforwards:flags.14?true peer:InputPeer reply_to_msg_id:flags.0?int media:InputMedia message:string random_id:long reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector schedule_date:flags.10?int send_as:flags.13?InputPeer = Updates;\nmessages.forwardMessages#cc30290b flags:# silent:flags.5?true background:flags.6?true with_my_score:flags.8?true drop_author:flags.11?true drop_media_captions:flags.12?true noforwards:flags.14?true from_peer:InputPeer id:Vector random_id:Vector to_peer:InputPeer schedule_date:flags.10?int send_as:flags.13?InputPeer = Updates;\nmessages.report#8953ab4e peer:InputPeer id:Vector reason:ReportReason message:string = Bool;\nmessages.getChats#49e9528f id:Vector = messages.Chats;\nmessages.getFullChat#aeb00b34 chat_id:long = messages.ChatFull;\nmessages.editChatTitle#73783ffd chat_id:long title:string = Updates;\nmessages.editChatPhoto#35ddd674 chat_id:long photo:InputChatPhoto = Updates;\nmessages.addChatUser#f24753e3 chat_id:long user_id:InputUser fwd_limit:int = Updates;\nmessages.deleteChatUser#a2185cab flags:# revoke_history:flags.0?true chat_id:long user_id:InputUser = Updates;\nmessages.createChat#9cb126e users:Vector title:string = Updates;\nmessages.getDhConfig#26cf8950 version:int random_length:int = messages.DhConfig;\nmessages.readMessageContents#36a73f77 id:Vector = messages.AffectedMessages;\nmessages.getStickers#d5a5d3a1 emoticon:string hash:long = messages.Stickers;\nmessages.getAllStickers#b8a0a1a8 hash:long = messages.AllStickers;\nmessages.getWebPagePreview#8b68b0cc flags:# message:string entities:flags.3?Vector = MessageMedia;\nmessages.exportChatInvite#a02ce5d5 flags:# legacy_revoke_permanent:flags.2?true request_needed:flags.3?true peer:InputPeer expire_date:flags.0?int usage_limit:flags.1?int title:flags.4?string = ExportedChatInvite;\nmessages.checkChatInvite#3eadb1bb hash:string = ChatInvite;\nmessages.importChatInvite#6c50051c hash:string = Updates;\nmessages.getStickerSet#c8a0ec74 stickerset:InputStickerSet hash:int = messages.StickerSet;\nmessages.installStickerSet#c78fe460 stickerset:InputStickerSet archived:Bool = messages.StickerSetInstallResult;\nmessages.uninstallStickerSet#f96e55de stickerset:InputStickerSet = Bool;\nmessages.startBot#e6df7378 bot:InputUser peer:InputPeer random_id:long start_param:string = Updates;\nmessages.migrateChat#a2875319 chat_id:long = Updates;\nmessages.searchGlobal#4bc6589a flags:# folder_id:flags.0?int q:string filter:MessagesFilter min_date:int max_date:int offset_rate:int offset_peer:InputPeer offset_id:int limit:int = messages.Messages;\nmessages.getDocumentByHash#338e2464 sha256:bytes size:int mime_type:string = Document;\nmessages.getSavedGifs#5cf09635 hash:long = messages.SavedGifs;\nmessages.getInlineBotResults#514e999d flags:# bot:InputUser peer:InputPeer geo_point:flags.0?InputGeoPoint query:string offset:string = messages.BotResults;\nmessages.sendInlineBotResult#7aa11297 flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true hide_via:flags.11?true peer:InputPeer reply_to_msg_id:flags.0?int random_id:long query_id:long id:string schedule_date:flags.10?int send_as:flags.13?InputPeer = Updates;\nmessages.editMessage#48f71778 flags:# no_webpage:flags.1?true peer:InputPeer id:int message:flags.11?string media:flags.14?InputMedia reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector schedule_date:flags.15?int = Updates;\nmessages.getBotCallbackAnswer#9342ca07 flags:# game:flags.1?true peer:InputPeer msg_id:int data:flags.0?bytes password:flags.2?InputCheckPasswordSRP = messages.BotCallbackAnswer;\nmessages.getPeerDialogs#e470bcfd peers:Vector = messages.PeerDialogs;\nmessages.saveDraft#bc39e14b flags:# no_webpage:flags.1?true reply_to_msg_id:flags.0?int peer:InputPeer message:string entities:flags.3?Vector = Bool;\nmessages.getFeaturedStickers#64780b14 hash:long = messages.FeaturedStickers;\nmessages.readFeaturedStickers#5b118126 id:Vector = Bool;\nmessages.getRecentStickers#9da9403b flags:# attached:flags.0?true hash:long = messages.RecentStickers;\nmessages.getCommonChats#e40ca104 user_id:InputUser max_id:long limit:int = messages.Chats;\nmessages.getWebPage#32ca8f91 url:string hash:int = WebPage;\nmessages.toggleDialogPin#a731e257 flags:# pinned:flags.0?true peer:InputDialogPeer = Bool;\nmessages.getPinnedDialogs#d6b94df2 folder_id:int = messages.PeerDialogs;\nmessages.uploadMedia#519bc2b1 peer:InputPeer media:InputMedia = MessageMedia;\nmessages.getFavedStickers#4f1aaa9 hash:long = messages.FavedStickers;\nmessages.faveSticker#b9ffc55b id:InputDocument unfave:Bool = Bool;\nmessages.sendMultiMedia#f803138f flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true noforwards:flags.14?true peer:InputPeer reply_to_msg_id:flags.0?int multi_media:Vector schedule_date:flags.10?int send_as:flags.13?InputPeer = Updates;\nmessages.searchStickerSets#35705b8a flags:# exclude_featured:flags.0?true q:string hash:long = messages.FoundStickerSets;\nmessages.markDialogUnread#c286d98f flags:# unread:flags.0?true peer:InputDialogPeer = Bool;\nmessages.updatePinnedMessage#d2aaf7ec flags:# silent:flags.0?true unpin:flags.1?true pm_oneside:flags.2?true peer:InputPeer id:int = Updates;\nmessages.sendVote#10ea6184 peer:InputPeer msg_id:int options:Vector = Updates;\nmessages.getOnlines#6e2be050 peer:InputPeer = ChatOnlines;\nmessages.editChatAbout#def60797 peer:InputPeer about:string = Bool;\nmessages.editChatDefaultBannedRights#a5866b41 peer:InputPeer banned_rights:ChatBannedRights = Updates;\nmessages.getEmojiKeywordsDifference#1508b6af lang_code:string from_version:int = EmojiKeywordsDifference;\nmessages.getScheduledHistory#f516760b peer:InputPeer hash:long = messages.Messages;\nmessages.sendScheduledMessages#bd38850a peer:InputPeer id:Vector = Updates;\nmessages.deleteScheduledMessages#59ae2b16 peer:InputPeer id:Vector = Updates;\nmessages.getPollVotes#b86e380e flags:# peer:InputPeer id:int option:flags.0?bytes offset:flags.1?string limit:int = messages.VotesList;\nmessages.getDialogFilters#f19ed96d = Vector;\nmessages.getSuggestedDialogFilters#a29cd42c = Vector;\nmessages.updateDialogFilter#1ad4a04a flags:# id:int filter:flags.0?DialogFilter = Bool;\nmessages.getReplies#22ddd30c peer:InputPeer msg_id:int offset_id:int offset_date:int add_offset:int limit:int max_id:int min_id:int hash:long = messages.Messages;\nmessages.getDiscussionMessage#446972fd peer:InputPeer msg_id:int = messages.DiscussionMessage;\nmessages.readDiscussion#f731a9f4 peer:InputPeer msg_id:int read_max_id:int = Bool;\nmessages.unpinAllMessages#f025bc8b peer:InputPeer = messages.AffectedHistory;\nmessages.deleteChat#5bd0ee50 chat_id:long = Bool;\nmessages.getMessageReadParticipants#2c6f97b7 peer:InputPeer msg_id:int = Vector;\nmessages.toggleNoForwards#b11eafa2 peer:InputPeer enabled:Bool = Updates;\nmessages.saveDefaultSendAs#ccfddf96 peer:InputPeer send_as:InputPeer = Bool;\nupdates.getState#edd4882a = updates.State;\nupdates.getDifference#25939651 flags:# pts:int pts_total_limit:flags.0?int date:int qts:int = updates.Difference;\nupdates.getChannelDifference#3173d78 flags:# force:flags.0?true channel:InputChannel filter:ChannelMessagesFilter pts:int limit:int = updates.ChannelDifference;\nphotos.uploadProfilePhoto#89f30f69 flags:# file:flags.0?InputFile video:flags.1?InputFile video_start_ts:flags.2?double = photos.Photo;\nphotos.getUserPhotos#91cd32a8 user_id:InputUser offset:int max_id:long limit:int = photos.Photos;\nupload.saveFilePart#b304a621 file_id:long file_part:int bytes:bytes = Bool;\nupload.getFile#b15a9afc flags:# precise:flags.0?true cdn_supported:flags.1?true location:InputFileLocation offset:int limit:int = upload.File;\nupload.saveBigFilePart#de7b673d file_id:long file_part:int file_total_parts:int bytes:bytes = Bool;\nupload.getWebFile#24e6818d location:InputWebFileLocation offset:int limit:int = upload.WebFile;\nhelp.getConfig#c4f9186b = Config;\nhelp.getNearestDc#1fb33026 = NearestDc;\nhelp.getSupport#9cdf08cd = help.Support;\nhelp.acceptTermsOfService#ee72f79a id:DataJSON = Bool;\nhelp.getCountriesList#735787a8 lang_code:string hash:int = help.CountriesList;\nchannels.readHistory#cc104937 channel:InputChannel max_id:int = Bool;\nchannels.deleteMessages#84c1fd4e channel:InputChannel id:Vector = messages.AffectedMessages;\nchannels.getMessages#ad8c9a23 channel:InputChannel id:Vector = messages.Messages;\nchannels.getParticipants#77ced9d0 channel:InputChannel filter:ChannelParticipantsFilter offset:int limit:int hash:long = channels.ChannelParticipants;\nchannels.getParticipant#a0ab6cc6 channel:InputChannel participant:InputPeer = channels.ChannelParticipant;\nchannels.getChannels#a7f6bbb id:Vector = messages.Chats;\nchannels.getFullChannel#8736a09 channel:InputChannel = messages.ChatFull;\nchannels.createChannel#3d5fb10f flags:# broadcast:flags.0?true megagroup:flags.1?true for_import:flags.3?true title:string about:string geo_point:flags.2?InputGeoPoint address:flags.2?string = Updates;\nchannels.editAdmin#d33c8902 channel:InputChannel user_id:InputUser admin_rights:ChatAdminRights rank:string = Updates;\nchannels.editTitle#566decd0 channel:InputChannel title:string = Updates;\nchannels.editPhoto#f12e57c9 channel:InputChannel photo:InputChatPhoto = Updates;\nchannels.checkUsername#10e6bd2c channel:InputChannel username:string = Bool;\nchannels.updateUsername#3514b3de channel:InputChannel username:string = Bool;\nchannels.joinChannel#24b524c5 channel:InputChannel = Updates;\nchannels.leaveChannel#f836aa95 channel:InputChannel = Updates;\nchannels.inviteToChannel#199f3a6c channel:InputChannel users:Vector = Updates;\nchannels.deleteChannel#c0111fe3 channel:InputChannel = Updates;\nchannels.toggleSignatures#1f69b606 channel:InputChannel enabled:Bool = Updates;\nchannels.editBanned#96e6cd81 channel:InputChannel participant:InputPeer banned_rights:ChatBannedRights = Updates;\nchannels.readMessageContents#eab5dc38 channel:InputChannel id:Vector = Bool;\nchannels.togglePreHistoryHidden#eabbb94c channel:InputChannel enabled:Bool = Updates;\nchannels.getGroupsForDiscussion#f5dad378 = messages.Chats;\nchannels.setDiscussionGroup#40582bb2 broadcast:InputChannel group:InputChannel = Bool;\nchannels.viewSponsoredMessage#beaedb94 channel:InputChannel random_id:bytes = Bool;\nchannels.getSponsoredMessages#ec210fbf channel:InputChannel = messages.SponsoredMessages;\nchannels.getSendAs#dc770ee peer:InputPeer = channels.SendAsPeers;\npayments.getPaymentForm#8a333c8d flags:# peer:InputPeer msg_id:int theme_params:flags.0?DataJSON = payments.PaymentForm;\npayments.getPaymentReceipt#2478d1cc peer:InputPeer msg_id:int = payments.PaymentReceipt;\npayments.validateRequestedInfo#db103170 flags:# save:flags.0?true peer:InputPeer msg_id:int info:PaymentRequestedInfo = payments.ValidatedRequestedInfo;\npayments.sendPaymentForm#30c3bc9d flags:# form_id:long peer:InputPeer msg_id:int requested_info_id:flags.0?string shipping_option_id:flags.1?string credentials:InputPaymentCredentials tip_amount:flags.2?long = payments.PaymentResult;\npayments.getSavedInfo#227d824b = payments.SavedInfo;\nphone.createGroupCall#48cdc6d8 flags:# peer:InputPeer random_id:int title:flags.0?string schedule_date:flags.1?int = Updates;\nphone.joinGroupCall#b132ff7b flags:# muted:flags.0?true video_stopped:flags.2?true call:InputGroupCall join_as:InputPeer invite_hash:flags.1?string params:DataJSON = Updates;\nphone.leaveGroupCall#500377f9 call:InputGroupCall source:int = Updates;\nphone.discardGroupCall#7a777135 call:InputGroupCall = Updates;\nphone.getGroupCall#41845db call:InputGroupCall limit:int = phone.GroupCall;\nphone.getGroupParticipants#c558d8ab call:InputGroupCall ids:Vector sources:Vector offset:string limit:int = phone.GroupParticipants;\nphone.editGroupCallParticipant#a5273abf flags:# call:InputGroupCall participant:InputPeer muted:flags.0?Bool volume:flags.1?int raise_hand:flags.2?Bool video_stopped:flags.3?Bool video_paused:flags.4?Bool presentation_paused:flags.5?Bool = Updates;\nphone.exportGroupCallInvite#e6aa647f flags:# can_self_unmute:flags.0?true call:InputGroupCall = phone.ExportedGroupCallInvite;\nphone.toggleGroupCallStartSubscription#219c34e6 call:InputGroupCall subscribed:Bool = Updates;\nphone.joinGroupCallPresentation#cbea6bc4 call:InputGroupCall params:DataJSON = Updates;\nphone.leaveGroupCallPresentation#1c50d144 call:InputGroupCall = Updates;\nlangpack.getLangPack#f2f2330a lang_pack:string lang_code:string = LangPackDifference;\nlangpack.getStrings#efea3803 lang_pack:string lang_code:string keys:Vector = Vector;\nlangpack.getLanguages#42c6978f lang_pack:string = Vector;\nfolders.editPeerFolders#6847d0ab folder_peers:Vector = Updates;`;","const { inflate } = require('pako/dist/pako_inflate');\nconst { serializeBytes } = require('../index');\n\n// CONTEST const { deflate } = require('pako/dist/pako_deflate')\n\nclass GZIPPacked {\n static CONSTRUCTOR_ID = 0x3072cfa1;\n\n static classType = 'constructor';\n\n constructor(data) {\n this.data = data;\n this.CONSTRUCTOR_ID = 0x3072cfa1;\n this.classType = 'constructor';\n }\n\n static async gzipIfSmaller(contentRelated, data) {\n if (contentRelated && data.length > 512) {\n const gzipped = await (new GZIPPacked(data)).toBytes();\n if (gzipped.length < data.length) {\n return gzipped;\n }\n }\n return data;\n }\n\n static gzip(input) {\n return Buffer.from(input);\n // TODO this usually makes it faster for large requests\n // return Buffer.from(deflate(input, { level: 9, gzip: true }))\n }\n\n static ungzip(input) {\n return Buffer.from(inflate(input));\n }\n\n static read(reader) {\n const constructor = reader.readInt(false);\n if (constructor !== GZIPPacked.CONSTRUCTOR_ID) {\n throw new Error('not equal');\n }\n return GZIPPacked.gzip(reader.tgReadBytes());\n }\n\n static async fromReader(reader) {\n return new GZIPPacked(await GZIPPacked.ungzip(reader.tgReadBytes()));\n }\n\n async toBytes() {\n const g = Buffer.alloc(4);\n g.writeUInt32LE(GZIPPacked.CONSTRUCTOR_ID, 0);\n return Buffer.concat([\n g,\n serializeBytes(await GZIPPacked.gzip(this.data)),\n ]);\n }\n}\n\nmodule.exports = GZIPPacked;\n","const TLMessage = require('./TLMessage');\n\nclass MessageContainer {\n static CONSTRUCTOR_ID = 0x73f1f8dc;\n\n static classType = 'constructor';\n\n // Maximum size in bytes for the inner payload of the container.\n // Telegram will close the connection if the payload is bigger.\n // The overhead of the container itself is subtracted.\n static MAXIMUM_SIZE = 1044456 - 8;\n\n // Maximum amount of messages that can't be sent inside a single\n // container, inclusive. Beyond this limit Telegram will respond\n // with BAD_MESSAGE 64 (invalid container).\n //\n // This limit is not 100% accurate and may in some cases be higher.\n // However, sending up to 100 requests at once in a single container\n // is a reasonable conservative value, since it could also depend on\n // other factors like size per request, but we cannot know this.\n static MAXIMUM_LENGTH = 100;\n\n constructor(messages) {\n this.CONSTRUCTOR_ID = 0x73f1f8dc;\n this.messages = messages;\n this.classType = 'constructor';\n }\n\n static fromReader(reader) {\n const messages = [];\n const length = reader.readInt();\n for (let x = 0; x < length; x++) {\n const msgId = reader.readLong();\n const seqNo = reader.readInt();\n const containerLength = reader.readInt();\n const before = reader.tellPosition();\n const obj = reader.tgReadObject();\n reader.setPosition(before + containerLength);\n const tlMessage = new TLMessage(msgId, seqNo, obj);\n messages.push(tlMessage);\n }\n return new MessageContainer(messages);\n }\n}\n\nmodule.exports = MessageContainer;\n","const { RpcError } = require('../index').constructors;\nconst GZIPPacked = require('./GZIPPacked');\n\nclass RPCResult {\n static CONSTRUCTOR_ID = 0xf35c6d01;\n\n static classType = 'constructor';\n\n constructor(reqMsgId, body, error) {\n this.CONSTRUCTOR_ID = 0xf35c6d01;\n this.reqMsgId = reqMsgId;\n this.body = body;\n this.error = error;\n this.classType = 'constructor';\n }\n\n static async fromReader(reader) {\n const msgId = reader.readLong();\n const innerCode = reader.readInt(false);\n if (innerCode === RpcError.CONSTRUCTOR_ID) {\n return new RPCResult(msgId, undefined, RpcError.fromReader(reader));\n }\n if (innerCode === GZIPPacked.CONSTRUCTOR_ID) {\n return new RPCResult(msgId, (await GZIPPacked.fromReader(reader)).data);\n }\n reader.seek(-4);\n // This reader.read() will read more than necessary, but it's okay.\n // We could make use of MessageContainer's length here, but since\n // it's not necessary we don't need to care about it.\n return new RPCResult(msgId, reader.read(), undefined);\n }\n}\n\nmodule.exports = RPCResult;\n","class TLMessage {\n static SIZE_OVERHEAD = 12;\n\n static classType = 'constructor';\n\n constructor(msgId, seqNo, obj) {\n this.msgId = msgId;\n this.seqNo = seqNo;\n this.obj = obj;\n this.classType = 'constructor';\n }\n}\n\nmodule.exports = TLMessage;\n","const TLMessage = require('./TLMessage');\nconst RPCResult = require('./RPCResult');\nconst MessageContainer = require('./MessageContainer');\nconst GZIPPacked = require('./GZIPPacked');\n\nconst coreObjects = {\n [RPCResult.CONSTRUCTOR_ID]: RPCResult,\n [GZIPPacked.CONSTRUCTOR_ID]: GZIPPacked,\n [MessageContainer.CONSTRUCTOR_ID]: MessageContainer,\n};\n\nmodule.exports = {\n TLMessage,\n RPCResult,\n MessageContainer,\n GZIPPacked,\n coreObjects,\n};\n","const snakeToCamelCase = (name) => {\n const result = name.replace(/(?:^|_)([a-z])/g, (_, g) => g.toUpperCase());\n return result.replace(/_/g, '');\n};\nconst variableSnakeToCamelCase = (str) => str.replace(\n /([-_][a-z])/g,\n (group) => group.toUpperCase()\n .replace('-', '')\n .replace('_', ''),\n);\n\nconst CORE_TYPES = new Set([\n 0xbc799737, // boolFalse#bc799737 = Bool;\n 0x997275b5, // boolTrue#997275b5 = Bool;\n 0x3fedd339, // true#3fedd339 = True;\n 0xc4b9f9bb, // error#c4b9f9bb code:int text:string = Error;\n 0x56730bcc, // null#56730bcc = Null;\n]);\nconst AUTH_KEY_TYPES = new Set([\n 0x05162463, // resPQ,\n 0x83c95aec, // p_q_inner_data\n 0xa9f55f95, // p_q_inner_data_dc\n 0x3c6a84d4, // p_q_inner_data_temp\n 0x56fddf88, // p_q_inner_data_temp_dc\n 0xd0e8075c, // server_DH_params_ok\n 0xb5890dba, // server_DH_inner_data\n 0x6643b654, // client_DH_inner_data\n 0xd712e4be, // req_DH_params\n 0xf5045f1f, // set_client_DH_params\n 0x3072cfa1, // gzip_packed\n]);\n\n// This is copy-pasted from `gramjs/Helpers.js` to not depend on TypeScript modules\nfunction makeCRCTable() {\n let c;\n const crcTable = [];\n for (let n = 0; n < 256; n++) {\n c = n;\n for (let k = 0; k < 8; k++) {\n c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));\n }\n crcTable[n] = c;\n }\n return crcTable;\n}\n\nlet crcTable;\n\nfunction crc32(buf) {\n if (!crcTable) {\n crcTable = makeCRCTable();\n }\n if (!Buffer.isBuffer(buf)) {\n buf = Buffer.from(buf);\n }\n let crc = -1;\n\n for (let index = 0; index < buf.length; index++) {\n const byte = buf[index];\n crc = crcTable[(crc ^ byte) & 0xff] ^ (crc >>> 8);\n }\n return (crc ^ (-1)) >>> 0;\n}\n\nconst findAll = (regex, str, matches = []) => {\n if (!regex.flags.includes('g')) {\n regex = new RegExp(regex.source, 'g');\n }\n\n const res = regex.exec(str);\n\n if (res) {\n matches.push(res.slice(1));\n findAll(regex, str, matches);\n }\n\n return matches;\n};\n\nconst fromLine = (line, isFunction) => {\n const match = line.match(/([\\w.]+)(?:#([0-9a-fA-F]+))?(?:\\s{?\\w+:[\\w\\d<>#.?!]+}?)*\\s=\\s([\\w\\d<>#.?]+);$/);\n if (!match) {\n // Probably \"vector#1cb5c415 {t:Type} # [ t ] = Vector t;\"\n throw new Error(`Cannot parse TLObject ${line}`);\n }\n\n const argsMatch = findAll(/({)?(\\w+):([\\w\\d<>#.?!]+)}?/, line);\n const currentConfig = {\n name: match[1],\n constructorId: parseInt(match[2], 16),\n argsConfig: {},\n subclassOfId: crc32(match[3]),\n result: match[3],\n isFunction,\n namespace: undefined,\n };\n if (!currentConfig.constructorId) {\n const hexId = '';\n let args;\n\n if (Object.values(currentConfig.argsConfig).length) {\n args = ` ${Object.keys(currentConfig.argsConfig)\n .map((arg) => arg.toString())\n .join(' ')}`;\n } else {\n args = '';\n }\n\n const representation = `${currentConfig.name}${hexId}${args} = ${currentConfig.result}`\n .replace(/(:|\\?)bytes /g, '$1string ')\n .replace(/|{|}/g, '')\n .replace(/ \\w+:flags\\.\\d+\\?true/g, '');\n\n if (currentConfig.name === 'inputMediaInvoice') {\n // eslint-disable-next-line no-empty\n if (currentConfig.name === 'inputMediaInvoice') {\n }\n }\n\n currentConfig.constructorId = crc32(Buffer.from(representation, 'utf8'));\n }\n for (const [brace, name, argType] of argsMatch) {\n if (brace === undefined) {\n currentConfig.argsConfig[variableSnakeToCamelCase(name)] = buildArgConfig(name, argType);\n }\n }\n if (currentConfig.name.includes('.')) {\n [currentConfig.namespace, currentConfig.name] = currentConfig.name.split(/\\.(.+)/);\n }\n currentConfig.name = snakeToCamelCase(currentConfig.name);\n /*\n for (const arg in currentConfig.argsConfig){\n if (currentConfig.argsConfig.hasOwnProperty(arg)){\n if (currentConfig.argsConfig[arg].flagIndicator){\n delete currentConfig.argsConfig[arg]\n }\n }\n } */\n return currentConfig;\n};\n\nfunction buildArgConfig(name, argType) {\n name = name === 'self' ? 'is_self' : name;\n // Default values\n const currentConfig = {\n isVector: false,\n isFlag: false,\n skipConstructorId: false,\n flagIndex: -1,\n flagIndicator: true,\n type: undefined,\n useVectorId: undefined,\n };\n\n // The type can be an indicator that other arguments will be flags\n if (argType !== '#') {\n currentConfig.flagIndicator = false;\n // Strip the exclamation mark always to have only the name\n currentConfig.type = argType.replace(/^!+/, '');\n\n // The type may be a flag (flags.IDX?REAL_TYPE)\n // Note that 'flags' is NOT the flags name; this\n // is determined by a previous argument\n // However, we assume that the argument will always be called 'flags'\n // @ts-ignore\n const flagMatch = currentConfig.type.match(/flags.(\\d+)\\?([\\w<>.]+)/);\n\n if (flagMatch) {\n currentConfig.isFlag = true;\n currentConfig.flagIndex = Number(flagMatch[1]);\n // Update the type to match the exact type, not the \"flagged\" one\n [, , currentConfig.type] = flagMatch;\n }\n\n // Then check if the type is a Vector\n // @ts-ignore\n const vectorMatch = currentConfig.type.match(/[Vv]ector<([\\w\\d.]+)>/);\n\n if (vectorMatch) {\n currentConfig.isVector = true;\n\n // If the type's first letter is not uppercase, then\n // it is a constructor and we use (read/write) its ID.\n // @ts-ignore\n currentConfig.useVectorId = currentConfig.type.charAt(0) === 'V';\n\n // Update the type to match the one inside the vector\n [, currentConfig.type] = vectorMatch;\n }\n\n // See use_vector_id. An example of such case is ipPort in\n // help.configSpecial\n // @ts-ignore\n if (/^[a-z]$/.test(currentConfig.type.split('.')\n .pop()\n .charAt(0))\n ) {\n currentConfig.skipConstructorId = true;\n }\n\n // The name may contain \"date\" in it, if this is the case and\n // the type is \"int\", we can safely assume that this should be\n // treated as a \"date\" object. Note that this is not a valid\n // Telegram object, but it's easier to work with\n // if (\n // this.type === 'int' &&\n // (/(\\b|_)([dr]ate|until|since)(\\b|_)/.test(name) ||\n // ['expires', 'expires_at', 'was_online'].includes(name))\n // ) {\n // this.type = 'date';\n // }\n }\n return currentConfig;\n}\n\n\nfunction* parseTl(content, layer, methods = [], ignoreIds = CORE_TYPES) {\n (methods || []).reduce((o, m) => ({\n ...o,\n [m.name]: m,\n }), {});\n const objAll = [];\n const objByName = {};\n const objByType = {};\n\n const file = content;\n\n let isFunction = false;\n\n for (let line of file.split('\\n')) {\n const commentIndex = line.indexOf('//');\n\n if (commentIndex !== -1) {\n line = line.slice(0, commentIndex);\n }\n\n line = line.trim();\n\n if (!line) {\n continue;\n }\n\n const match = line.match(/---(\\w+)---/);\n\n if (match) {\n const [, followingTypes] = match;\n isFunction = followingTypes === 'functions';\n continue;\n }\n\n try {\n const result = fromLine(line, isFunction);\n\n if (ignoreIds.has(result.constructorId)) {\n continue;\n }\n\n objAll.push(result);\n\n if (!result.isFunction) {\n if (!objByType[result.result]) {\n objByType[result.result] = [];\n }\n\n objByName[result.name] = result;\n objByType[result.result].push(result);\n }\n } catch (e) {\n if (!e.toString()\n .includes('vector#1cb5c415')) {\n throw e;\n }\n }\n }\n\n // Once all objects have been parsed, replace the\n // string type from the arguments with references\n for (const obj of objAll) {\n // console.log(obj)\n if (AUTH_KEY_TYPES.has(obj.constructorId)) {\n for (const arg in obj.argsConfig) {\n if (obj.argsConfig[arg].type === 'string') {\n obj.argsConfig[arg].type = 'bytes';\n }\n }\n }\n }\n\n for (const obj of objAll) {\n yield obj;\n }\n}\n\nfunction serializeBytes(data) {\n if (!(data instanceof Buffer)) {\n if (typeof data === 'string') {\n data = Buffer.from(data);\n } else {\n throw Error(`Bytes or str expected, not ${data.constructor.name}`);\n }\n }\n const r = [];\n let padding;\n if (data.length < 254) {\n padding = (data.length + 1) % 4;\n if (padding !== 0) {\n padding = 4 - padding;\n }\n r.push(Buffer.from([data.length]));\n r.push(data);\n } else {\n padding = data.length % 4;\n if (padding !== 0) {\n padding = 4 - padding;\n }\n r.push(Buffer.from([254, data.length % 256, (data.length >> 8) % 256, (data.length >> 16) % 256]));\n r.push(data);\n }\n r.push(Buffer.alloc(padding)\n .fill(0));\n\n return Buffer.concat(r);\n}\n\nfunction serializeDate(dt) {\n if (!dt) {\n return Buffer.alloc(4)\n .fill(0);\n }\n if (dt instanceof Date) {\n dt = Math.floor((Date.now() - dt.getTime()) / 1000);\n }\n if (typeof dt === 'number') {\n const t = Buffer.alloc(4);\n t.writeInt32LE(dt, 0);\n return t;\n }\n throw Error(`Cannot interpret \"${dt}\" as a date`);\n}\n\nmodule.exports = {\n findAll,\n parseTl,\n buildArgConfig,\n fromLine,\n CORE_TYPES,\n serializeDate,\n serializeBytes,\n snakeToCamelCase,\n variableSnakeToCamelCase,\n};\n","const api = require('./api');\nconst {\n serializeBytes,\n serializeDate,\n} = require('./generationHelpers');\n\nmodule.exports = {\n // TODO Refactor internal usages to always use `api`.\n constructors: api,\n requests: api,\n serializeBytes,\n serializeDate,\n};\n","module.exports = `resPQ#05162463 nonce:int128 server_nonce:int128 pq:string server_public_key_fingerprints:Vector = ResPQ;\np_q_inner_data#83c95aec pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 = P_Q_inner_data;\np_q_inner_data_dc#a9f55f95 pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 dc:int = P_Q_inner_data;\np_q_inner_data_temp#3c6a84d4 pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 expires_in:int = P_Q_inner_data;\np_q_inner_data_temp_dc#56fddf88 pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 dc:int expires_in:int = P_Q_inner_data;\nserver_DH_params_fail#79cb045d nonce:int128 server_nonce:int128 new_nonce_hash:int128 = Server_DH_Params;\nserver_DH_params_ok#d0e8075c nonce:int128 server_nonce:int128 encrypted_answer:string = Server_DH_Params;\nserver_DH_inner_data#b5890dba nonce:int128 server_nonce:int128 g:int dh_prime:string g_a:string server_time:int = Server_DH_inner_data;\nclient_DH_inner_data#6643b654 nonce:int128 server_nonce:int128 retry_id:long g_b:string = Client_DH_Inner_Data;\ndh_gen_ok#3bcbf734 nonce:int128 server_nonce:int128 new_nonce_hash1:int128 = Set_client_DH_params_answer;\ndh_gen_retry#46dc1fb9 nonce:int128 server_nonce:int128 new_nonce_hash2:int128 = Set_client_DH_params_answer;\ndh_gen_fail#a69dae02 nonce:int128 server_nonce:int128 new_nonce_hash3:int128 = Set_client_DH_params_answer;\ndestroy_auth_key_ok#f660e1d4 = DestroyAuthKeyRes;\ndestroy_auth_key_none#0a9f2259 = DestroyAuthKeyRes;\ndestroy_auth_key_fail#ea109b13 = DestroyAuthKeyRes;\n---functions---\nreq_pq#60469778 nonce:int128 = ResPQ;\nreq_pq_multi#be7e8ef1 nonce:int128 = ResPQ;\nreq_pq_multi_new#51b410fd nonce:int128 = ResPQ;\nreq_DH_params#d712e4be nonce:int128 server_nonce:int128 p:string q:string public_key_fingerprint:long encrypted_data:string = Server_DH_Params;\nset_client_DH_params#f5045f1f nonce:int128 server_nonce:int128 encrypted_data:string = Set_client_DH_params_answer;\ndestroy_auth_key#d1435160 = DestroyAuthKeyRes;\n---types---\nmsgs_ack#62d6b459 msg_ids:Vector = MsgsAck;\nbad_msg_notification#a7eff811 bad_msg_id:long bad_msg_seqno:int error_code:int = BadMsgNotification;\nbad_server_salt#edab447b bad_msg_id:long bad_msg_seqno:int error_code:int new_server_salt:long = BadMsgNotification;\nmsgs_state_req#da69fb52 msg_ids:Vector = MsgsStateReq;\nmsgs_state_info#04deb57d req_msg_id:long info:string = MsgsStateInfo;\nmsgs_all_info#8cc0d131 msg_ids:Vector info:string = MsgsAllInfo;\nmsg_detailed_info#276d3ec6 msg_id:long answer_msg_id:long bytes:int status:int = MsgDetailedInfo;\nmsg_new_detailed_info#809db6df answer_msg_id:long bytes:int status:int = MsgDetailedInfo;\nmsg_resend_req#7d861a08 msg_ids:Vector = MsgResendReq;\nrpc_error#2144ca19 error_code:int error_message:string = RpcError;\nrpc_answer_unknown#5e2ad36e = RpcDropAnswer;\nrpc_answer_dropped_running#cd78e586 = RpcDropAnswer;\nrpc_answer_dropped#a43ad8b7 msg_id:long seq_no:int bytes:int = RpcDropAnswer;\nfuture_salt#0949d9dc valid_since:int valid_until:int salt:long = FutureSalt;\nfuture_salts#ae500895 req_msg_id:long now:int salts:vector = FutureSalts;\npong#347773c5 msg_id:long ping_id:long = Pong;\ndestroy_session_ok#e22045fc session_id:long = DestroySessionRes;\ndestroy_session_none#62d350c9 session_id:long = DestroySessionRes;\nnew_session_created#9ec20908 first_msg_id:long unique_id:long server_salt:long = NewSession;\nhttp_wait#9299359f max_delay:int wait_after:int max_wait:int = HttpWait;\nipPort#d433ad73 ipv4:int port:int = IpPort;\nipPortSecret#37982646 ipv4:int port:int secret:bytes = IpPort;\naccessPointRule#4679b65f phone_prefix_rules:string dc_id:int ips:vector = AccessPointRule;\nhelp.configSimple#5a592a6c date:int expires:int rules:vector = help.ConfigSimple;\ntlsClientHello blocks:vector = TlsClientHello;\ntlsBlockString data:string = TlsBlock;\ntlsBlockRandom length:int = TlsBlock;\ntlsBlockZero length:int = TlsBlock;\ntlsBlockDomain = TlsBlock;\ntlsBlockGrease seed:int = TlsBlock;\ntlsBlockScope entries:Vector = TlsBlock;\n---functions---\nping#7abe77ec ping_id:long = Pong;\nping_delay_disconnect#f3427b8c ping_id:long disconnect_delay:int = Pong;`;","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\tid: moduleId,\n\t\tloaded: false,\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Flag the module as loaded\n\tmodule.loaded = true;\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n// expose the modules object (__webpack_modules__)\n__webpack_require__.m = __webpack_modules__;\n\n// the startup function\n__webpack_require__.x = () => {\n\t// Load entry module and return exports\n\t// This entry module depends on other loaded chunks and execution need to be delayed\n\tvar __webpack_exports__ = __webpack_require__.O(undefined, [592], () => (__webpack_require__(6927)))\n\t__webpack_exports__ = __webpack_require__.O(__webpack_exports__);\n\treturn __webpack_exports__;\n};\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.f = {};\n// This file contains only the entry chunk.\n// The chunk loading function for additional chunks\n__webpack_require__.e = (chunkId) => {\n\treturn Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => {\n\t\t__webpack_require__.f[key](chunkId, promises);\n\t\treturn promises;\n\t}, []));\n};","// This function allow to reference async chunks and sibling chunks for the entrypoint\n__webpack_require__.u = (chunkId) => {\n\t// return url for filenames based on template\n\treturn \"\" + chunkId + \".\" + \"d7ca037ed9b7d1c6792a\" + \".js\";\n};","// This function allow to reference all chunks\n__webpack_require__.miniCssF = (chunkId) => {\n\t// return url for filenames based on template\n\treturn undefined;\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","__webpack_require__.nmd = (module) => {\n\tmodule.paths = [];\n\tif (!module.children) module.children = [];\n\treturn module;\n};","var scriptUrl;\nif (__webpack_require__.g.importScripts) scriptUrl = __webpack_require__.g.location + \"\";\nvar document = __webpack_require__.g.document;\nif (!scriptUrl && document) {\n\tif (document.currentScript)\n\t\tscriptUrl = document.currentScript.src\n\tif (!scriptUrl) {\n\t\tvar scripts = document.getElementsByTagName(\"script\");\n\t\tif(scripts.length) scriptUrl = scripts[scripts.length - 1].src\n\t}\n}\n// When supporting browsers where an automatic publicPath is not supported you must specify an output.publicPath manually via configuration\n// or pass an empty string (\"\") and set the __webpack_public_path__ variable from your code to use your own logic.\nif (!scriptUrl) throw new Error(\"Automatic publicPath is not supported in this browser\");\nscriptUrl = scriptUrl.replace(/#.*$/, \"\").replace(/\\?.*$/, \"\").replace(/\\/[^\\/]+$/, \"/\");\n__webpack_require__.p = scriptUrl;","// no baseURI\n\n// object to store loaded chunks\n// \"1\" means \"already loaded\"\nvar installedChunks = {\n\t927: 1\n};\n\n// importScripts chunk loading\nvar installChunk = (data) => {\n\tvar [chunkIds, moreModules, runtime] = data;\n\tfor(var moduleId in moreModules) {\n\t\tif(__webpack_require__.o(moreModules, moduleId)) {\n\t\t\t__webpack_require__.m[moduleId] = moreModules[moduleId];\n\t\t}\n\t}\n\tif(runtime) runtime(__webpack_require__);\n\twhile(chunkIds.length)\n\t\tinstalledChunks[chunkIds.pop()] = 1;\n\tparentChunkLoadingFunction(data);\n};\n__webpack_require__.f.i = (chunkId, promises) => {\n\t// \"1\" is the signal for \"already loaded\"\n\tif(!installedChunks[chunkId]) {\n\t\tif(true) { // all chunks have JS\n\t\t\timportScripts(__webpack_require__.p + __webpack_require__.u(chunkId));\n\t\t}\n\t}\n};\n\nvar chunkLoadingGlobal = self[\"webpackChunktelegram_t\"] = self[\"webpackChunktelegram_t\"] || [];\nvar parentChunkLoadingFunction = chunkLoadingGlobal.push.bind(chunkLoadingGlobal);\nchunkLoadingGlobal.push = installChunk;\n\n// no HMR\n\n// no HMR manifest","// run startup\nvar __webpack_exports__ = __webpack_require__.x();\n"],"names":["deferred","next","API_UPDATE_THROTTLE","window","innerHeight","Math","round","API_THROTTLE_RESET_UPDATES","Set","SUPPORTED_IMAGE_CONTENT_TYPES","SUPPORTED_VIDEO_CONTENT_TYPES","SERVICE_NOTIFICATIONS_USER_ID","onTickEndCallbacks","onTickEndPrimaryCallbacks","buildCollectionByKey","collection","key","reduce","byKey","member","pick","object","keys","result","bytesToDataUri","bytes","shouldOmitPrefix","mimeType","btoa","String","fromCharCode","omitVirtualClassFields","instance","flags","CONSTRUCTOR_ID","SUBCLASS_OF_ID","className","classType","getBytes","rest","pathBytesToSvg","width","height","replace","path","len","length","i","num","buildPath","DEFAULT_THUMB_SIZE","w","h","buildApiThumbnailFromStripped","sizes","thumb","find","s","GramJs","realSizes","filter","dataUri","strippedPhotoToJpg","undefined","buildApiPhoto","photo","map","buildApiPhotoSize","id","thumbnail","photoSize","type","localMessages","chats","users","messages","documents","stickerSets","photos","webDocuments","ANIMATED_STICKER_MIME_TYPE","buildStickerFromDocument","document","stickerAttribute","attributes","attr","fileAttribute","sizeAttribute","stickerSetInfo","stickerset","emoji","alt","isAnimated","cachedThumb","thumbs","pathThumb","buildApiThumbnailFromCached","buildApiThumbnailFromPath","stickerSetId","stickerSetAccessHash","accessHash","buildStickerSet","set","archived","animated","installedDate","title","count","shortName","hasThumbnail","Boolean","buildStickerSetCovered","coveredStickerSet","stickerSet","stickerSetCovers","covers","cover","forEach","coverSticker","push","localDb","interpolateArray","data","fitCount","peak","newData","Array","springFactor","leftFiller","rightFiller","idx","floor","val","ApiMessageEntityTypes","ApiMediaFormat","isPeerUser","peer","hasOwnProperty","isPeerChat","buildApiPeerId","getApiChatIdFromMtpPeer","userId","chatId","channelId","resolveMessageApiChatId","mtpMessage","peerId","addMessageToLocalDb","message","messageFullId","media","webpage","action","addPhotoToLocalDb","addUserToLocalDb","user","shouldOverwrite","addEntitiesWithPhotosToLocalDb","entities","entity","chat","noOverwrite","addChatToLocalDb","serializeBytes","value","deserializeBytes","Buffer","from","getEntityTypeById","chatOrUserId","getEntityTypeByDeprecatedId","startsWith","buildPeer","buildMtpPeerId","buildInputPeer","BigInt","buildInputPeerFromLocalDb","buildInputEntity","buildInputStickerSet","buildInputDocument","buildInputMediaDocument","inputDocument","generateRandomBigInt","readBigIntFromBuffer","generateRandomBytes","buildMessageFromUpdate","update","fromId","buildMtpMessageEntity","offset","url","Bold","Italic","Underline","Strike","Code","Pre","language","Blockquote","TextUrl","Url","Hashtag","MentionName","isMessageWithMedia","buildInputContact","phone","firstName","lastName","clientId","buildChatBannedRights","bannedRights","untilDate","buildChatAdminRights","adminRights","buildShippingInfo","info","shippingAddress","buildInputPrivacyKey","privacyKey","buildInputReportReason","reason","abs","slice","buildInputGroupCall","groupCall","LOCAL_MEDIA_UPLOADING_TEMP_ID","currentUserId","localMessageCounter","buildApiSponsoredMessage","startParam","channelPost","chatInvite","chatInviteHash","randomId","chatInviteTitle","isBot","text","buildMessageTextContent","expiresAt","Date","now","channelPostId","buildApiMessage","buildApiMessageWithChatId","isChatWithSelf","isOutgoing","out","post","fwdFrom","content","buildMessageMediaContent","sticker","poll","contact","senderId","targetPeerId","isChannelPost","call","amount","currency","translationValues","targetUserIds","targetChatId","includes","withDuration","duration","video","join","mins","max","toString","Number","totalAmount","domain","buildAction","replyToMsgId","replyToTopId","replyToPeerId","replyTo","isEdited","editDate","editHide","inlineButtons","keyboardButtons","keyboardPlaceholder","isKeyboardSingleUse","messageId","replyMarkup","markup","rows","buttons","button","receiptMsgId","placeholder","singleUse","buildReplyButtons","forwardInfo","savedFromPeerId","savedFromPeer","date","isLinkedChannelPost","fromChatId","fromMessageId","savedFromMsgId","senderUserId","hiddenUserName","fromName","adminTitle","postAuthor","buildApiMessageForwardInfo","replies","mediaUnread","isMediaUnread","groupedId","isInAlbum","audio","shouldHideKeyboardButtons","views","isFromScheduled","fromScheduled","replyToMessageId","replyToChatId","replyToTopMessageId","mentioned","hasUnreadMention","isMentioned","viaBotId","comments","threadInfo","buildThreadInfo","noforwards","isProtected","some","e","buildApiMessageEntity","buildMessageDraft","draft","formattedText","replyingToId","ttlSeconds","buildSticker","buildPhoto","buildVideoFromDocument","buildVideo","audioAttribute","voice","thumbnailSizes","fileName","getFilenameFromDocument","buildAudio","waveform","buildVoice","buildApiDocument","buildDocumentFromMedia","phoneNumber","buildContact","buildPoll","results","buildPollFromMedia","webPage","buildWebPage","invoice","description","test","photoUrl","isTest","buildInvoice","buildInvoiceFromMedia","size","self","isMovSupported","videoAttr","a","gifAttr","supportsStreaming","roundMessage","isRound","isGif","mediaType","mediaSize","has","imageAttribute","timestamp","pollResults","answers","rawAnswers","answer","option","summary","isPublic","publicVoters","buildPollResults","rawResults","totalVoters","recentVoters","solution","solutionEntities","chosen","correct","voters","isChosen","isCorrect","votersCount","recentVoterIds","defaultBase","filenameAttribute","extension","split","buildNewPoll","localId","messageReplies","maxId","readMaxId","recentRepliers","apiChannelId","threadId","originChannelId","messagesCount","lastMessageId","lastReadInboxMessageId","recentReplierIds","getServerTime","serverTimeOffset","buildApiChatFieldsFromPeerEntity","peerEntity","isSupport","isMin","min","avatarHash","buildAvatarHash","isSignaturesShown","signatures","hasPrivateLink","hasLink","username","isVerified","verified","isCallActive","callActive","isCallNotEmpty","callNotEmpty","participantsCount","membersCount","joinDate","buildApiChatPermissions","isCreator","creator","buildApiChatRestrictions","buildApiChatMigrationInfo","buildApiChatFromDialog","dialog","folderId","unreadMark","unreadCount","unreadMentionsCount","notifySettings","silent","muteUntil","readOutboxMaxId","readInboxMaxId","isMuted","getApiChatTypeFromPeerEntity","getApiChatTitleFromMtpPeer","lastReadOutboxMessageId","hasUnreadMark","draftDate","currentUserBannedRights","defaultBannedRights","isRestricted","restrictions","restrictionReason","restricted","restrictionReasons","targetReason","platform","buildApiChatRestrictionReason","Object","assign","isNotJoined","left","kicked","migratedTo","buildApiChatFromPreview","preview","withForbidden","getUserName","megagroup","getPeerKey","photoId","buildChatMember","inviterId","joinedDate","kickedByUserId","kickedBy","promotedByUserId","promotedBy","customTitle","rank","isAdmin","isOwner","buildChatMembers","participants","buildChatTypingStatus","buildApiChatFolder","channels","broadcasts","pinnedChatIds","pinnedPeers","includedChatIds","includePeers","excludedChatIds","excludePeers","buildApiChatFolderFromSuggested","buildApiChatBotCommands","botInfos","botCommands","botInfo","botId","concat","commands","mtpCommand","buildApiUserFromFull","mtpUserFull","fullUser","about","commonChatsCount","pinnedMsgId","blocked","buildApiUser","fullInfo","bio","pinnedMessageId","isBlocked","botDescription","buildApiBotCommands","mtpUser","userType","bot","deleted","isSelf","mutualContact","isContact","canBeInvitedToGroup","botNochats","noStatus","status","botInlinePlaceholder","botPlaceholder","buildApiUserStatus","mtpStatus","expires","wasOnline","command","buildApiUsersAndStatuses","mtpUsers","userStatusesById","buildApiWallpaper","wallpaper","slug","buildApiSession","session","isCurrent","current","isOfficialApp","officialApp","isPasswordPending","passwordPending","hash","buildPrivacyRules","rules","visibility","allowUserIds","allowChatIds","blockUserIds","blockChatIds","rule","buildApiNotifyException","showPreviews","sound","isSilent","shouldShowPreviews","buildApiCountry","country","code","hidden","iso2","defaultName","name","countryCode","prefixes","patterns","isHidden","buildApiGroupCallParticipant","participant","versioned","canSelfUnmute","justJoined","muted","mutedByYou","source","volume","volumeByAdmin","videoJoined","presentation","raiseHandRating","isLeft","isMutedByMe","hasJustJoined","isVolumeByAdmin","isVersioned","isVideoJoined","isUser","buildApiGroupCallParticipantVideo","participantVideo","audioSource","endpoint","paused","sourceGroups","isPaused","buildApiGroupCallParticipantVideoSourceGroup","participantVideoSourceGroup","semantics","sources","buildApiGroupCall","connectionState","version","streamDcId","scheduleDate","canChangeJoinMuted","joinMuted","canStartVideo","scheduleStartSubscribed","isLoaded","onUpdate","sentMessageIds","shouldIgnoreNextChannelUpdate","dispatchUserAndChatUpdates","updater","originRequest","connection","timeOffset","state","shouldForceReply","buildApiMessageFromShort","selective","_entities","dcId","buildChatPhotoForLocalDb","localDbChatId","newProfilePhoto","ids","existingIds","missingIds","profilePhotoIds","setTimeout","popup","error","notification","currentDate","inboxDate","buildApiMessageFromNotification","localMessage","Error","newContent","add","isAlreadySent","isScheduled","sendingState","messageUpdate","pollId","apiPoll","pollUpdate","options","stillUnreadCount","isPinned","pinned","order","dp","folderPeers","folderPeer","folder","orderedIds","replacedMembers","addedMember","deletedMemberId","messageIds","typingStatus","channel","unread","apiUserId","updatedUser","peerType","buildPrivacyKey","JSON","parse","params","groupCallId","ApiErrors","PHONE_NUMBER_INVALID","PHONE_CODE_INVALID","PASSWORD_HASH_INVALID","PHONE_PASSWORD_FLOOD","PHONE_NUMBER_BANNED","authController","onRequestPhoneNumber","buildAuthStateUpdate","Promise","resolve","reject","onRequestCode","isCodeViaApp","onRequestPassword","hint","onRequestRegistration","onRequestQrCode","qrCode","token","onAuthError","err","errors","hours","ceil","seconds","authorizationState","provideAuthPhoneNumber","provideAuthCode","provideAuthPassword","password","provideAuthRegistration","registration","restartAuth","restartAuthWithQr","cacheApi","caches","Type","async","fetch","cacheName","isHtmlAllowed","request","Request","cache","open","response","match","contentType","headers","get","Text","Blob","blob","shouldRecreate","resolvedType","Json","json","console","warn","save","cacheData","stringify","Response","put","clear","delete","MEDIA_ENTITY_TYPES","getMimeType","fallbackMimeType","subarray","byte","GramJsLogger","gramJsUpdateEventBuilder","build","client","isConnected","destroy","invokeRequest","disconnect","onSessionUpdate","sessionData","handleGramJsUpdate","handleTerminatedSession","shouldHandleUpdates","shouldThrow","invoke","updatesContainer","updates","injectUpdateEntities","isSlowMode","hasErrorKey","dispatchErrorUpdate","downloadMedia","args","onProgress","mediaFormat","start","end","fullSize","mediaMatch","arrayBuffer","entityType","entityId","sizeType","Stream","acceptsBuffer","progressCallback","workers","getMessageMediaMimeType","downloadStickerSetThumb","Lottie","downloadProfilePhoto","download","parsed","BlobUrl","inflate","to","Progressive","buffer","parseMedia","canCache","prepared","mediaData","URL","createObjectURL","downloadMediaWithClient","uploadFile","file","updateTwoFaSettings","fetchCurrentUser","userFull","currentUser","_currentUserId","onCurrentUserUpdate","MAX_INT_32","fetchChats","limit","offsetDate","withPinned","lastLocalServiceMessage","offsetPeer","excludePinned","resultPinned","updateLocalDb","lastMessagesByChatId","peersByKey","preparePeers","draftsById","replyingToById","dialogs","orderedPinnedIds","lastMessage","isListed","chatIds","totalChatCount","fetchFullChat","fullChat","onlineCount","exportedInvite","slowmodeSeconds","slowmodeNextSendDate","migratedFromChatId","migratedFromMaxId","canViewParticipants","linkedChatId","hiddenPrehistory","defaultSendAs","inviteLink","link","members","fetchMembers","kickedMembers","bannedUsers","adminMembers","adminUsers","mtpLinkedChat","slowMode","nextSendDate","migratedFrom","maxMessageId","canViewMembers","isPreHistoryHidden","sendAsId","getFullChannelInfo","getFullChatInfo","searchChats","query","q","localPeerIds","myResults","allChats","allUsers","localChats","r","localUsers","u","globalChats","globalUsers","fetchChat","requestChatUpdate","lastLocalMessage","noLastMessage","peers","lastRemoteMessage","saveDraft","clearDraft","updateChatMutedState","settings","createChannel","noErrorUpdate","broadcast","newChannel","joinChannel","deleteChatUser","deleteChat","leaveChannel","deleteChannel","createGroupChat","newChat","editChatPhoto","uploadedPhoto","inputEntity","toggleChatPinned","shouldBePinned","toggleChatArchived","fetchChatFolders","byId","fetchRecommendedChatFolders","editChatFolder","folderUpdate","emoticon","contacts","nonContacts","groups","bots","excludeArchived","excludeMuted","excludeRead","buildFilterFromApiFolder","deleteChatFolder","isActionSuccessful","recommendedChatFolders","folders","toggleDialogUnread","getChatByUsername","togglePreHistoryHidden","isEnabled","enabled","updateChatDefaultBannedRights","updateChatMemberBannedRights","updateChatAdmin","updateChatTitle","updateChatAbout","toggleSignatures","memberFilter","fetchGroupsForDiscussion","setDiscussionGroup","group","migrateChat","openChatByInvite","requestNeeded","isChannel","isRequestNeeded","addChatMembers","all","deleteChatMember","viewMessages","sendMessages","sendMedia","sendStickers","sendGifs","sendGames","sendInline","embedLinks","sendPolls","changeInfo","inviteUsers","pinMessages","store","importChatInvite","toggleIsProtected","File","constructor","fileBits","super","this","fetchMessages","pagination","RequestClass","msgId","c","threadInfos","fetchMessage","queue","sendMessage","replyingTo","attachment","gif","scheduledAt","noWebPage","sendAs","filename","blobUrl","previewBlobUrl","quick","inputWaveform","buildUploadingMedia","buildLocalMessage","groupIndex","groupedUploads","counter","singleMediaByIndex","prevQueue","uploadMedia","inputMedia","uploadedMedia","messageMedia","fileReference","fetchInputMedia","multiMedia","values","sendGroupedMedia","pollParams","quiz","question","multipleChoice","correctAnswers","buildInputPoll","vcard","noWebpage","editMessage","mtpEntities","rescheduleMessage","lastModified","blobToFile","fetchBlob","fetchFile","patchedOnProgress","progress","isCanceled","inputFile","pinMessage","isUnpin","isOneSide","unpin","pmOneside","unpinAllMessages","deleteMessages","shouldDeleteForAll","revoke","deleteScheduledMessages","deleteHistory","just_clear","reportMessages","sendMessageAction","gramAction","buildSendMessageAction","topMsgId","markMessageListRead","requestThreadInfoUpdate","markMessagesRead","topMessageResult","repliesResult","offsetId","addOffset","discussionChatId","topMessageId","firstMessageId","noTopChatsRequest","searchMessagesLocal","chatOrUser","minDate","maxDate","nextOffsetId","totalCount","searchMessagesGlobal","offsetRate","nextRate","fetchWebPagePreview","sendPollVote","loadPollOptionResults","shouldResetVoters","votes","vote","nextOffset","forwardMessages","fromChat","toChat","randomIds","index","isAudio","asIncomingInChatWithSelf","buildLocalForwardedMessage","fromPeer","toPeer","sil2ent","findFirstMessageIdAfterDate","fetchScheduledHistory","sendScheduledMessages","isServiceMessageWithMedia","fetchPinnedMessages","fetchSeenBy","fetchSendAs","saveDefaultSendAs","fetchSponsoredMessages","viewSponsoredMessage","random","inputGifBot","fetchFullUser","input","userWithFullInfo","fetchCommonChats","commonChats","mtpChat","isFullyLoaded","fetchNearestCountry","dcInfo","fetchTopUsers","topPeers","correspondents","fetchContactList","fetchUsers","updateContact","addContact","deleteContact","fetchProfilePhotos","fetchStickerSets","allStickers","sets","fetchRecentStickers","stickers","processStickerResult","fetchFavoriteStickers","fetchFeaturedStickers","faveSticker","unfave","fetchStickers","stickerSetShortName","packs","acc","documentId","fetchAnimatedEmojis","searchStickers","fetchSavedGifs","gifs","processGifResult","installStickerSet","uninstallStickerSet","searchGifs","config","resolvedPeer","gifSearchUsername","foundGif","fetchStickersForEmoji","fetchEmojiKeywords","fromVersion","langCode","keywords","emojiKeyword","keyword","emoticons","checkChatUsername","setChatUsername","updatePrivateLink","usageLimit","expireDate","EMAIL_UNCONFIRMED","EMAIL_HASH_EXPIRED","NEW_SALT_INVALID","NEW_SETTINGS_INVALID","CODE_INVALID","emailCodeController","getPasswordInfo","hasPassword","onRequestEmailCode","checkPassword","currentPassword","isCheckPassword","onError","clearPassword","updatePassword","email","newPassword","emailCodeCallback","onEmailCodeError","updateRecoveryEmail","provideRecoveryEmailCode","getGroupCall","discardGroupCall","editGroupCallParticipant","presentationPaused","videoStopped","videoPaused","raiseHand","editGroupCallTitle","exportGroupCallInvite","fetchGroupCallParticipants","leaveGroupCall","joinGroupCall","inviteHash","joinAs","createGroupCall","toJSNumber","joinGroupCallPresentation","toggleGroupCallStartSubscription","subscribed","leaveGroupCallPresentation","BETA_LANG_CODES","updateProfile","checkUsername","updateUsername","updateProfilePhoto","uploadProfilePhoto","fetchWallpapers","filteredWallpapers","wallpapers","pattern","uploadWallpaper","fetchBlockedContacts","blockedIds","blockContact","unblockContact","fetchAuthorizations","authorizations","terminateAuthorization","terminateAllAuthorizations","fetchNotificationExceptions","compareSound","fetchNotificationSettings","isMutedContactSignUpNotification","privateContactNotificationsSettings","groupNotificationsSettings","broadcastNotificationsSettings","privateSilent","privateMuteUntil","privateShowPreviews","groupSilent","groupMuteUntil","groupShowPreviews","broadcastSilent","broadcastMuteUntil","broadcastShowPreviews","hasContactJoinedNotifications","hasPrivateChatsNotifications","hasPrivateChatsMessagePreview","hasGroupNotifications","hasGroupMessagePreview","hasBroadcastNotifications","hasBroadcastMessagePreview","updateContactSignUpNotification","updateNotificationSettings","fetchLanguages","langPack","fetchLangPack","sourceLangPacks","collections","strings","reverse","fetchLangStrings","fetchPrivacySettings","registerDevice","secret","getAuthKey","getKey","tokenType","appSandbox","otherUids","unregisterDevice","setPrivacySettings","privacyRules","allowedUsers","allowedChats","blockedUsers","blockedChats","updateIsOnline","isOnline","offline","fetchContentSettings","isSensitiveEnabled","sensitiveEnabled","canChangeSensitive","sensitiveCanChange","updateContentSettings","fetchCountryList","countryList","countries","phoneCodes","array","countryCodes","isArray","sort","b","localeCompare","general","buildApiWebDocument","answerCallbackButton","fetchTopInlineBots","botsInline","fetchInlineBot","fetchInlineBotResults","queryId","switchPm","isGallery","gallery","help","buildApiBotInlineMediaResult","webDocument","webThumbnail","buildApiBotInlineResult","sendInlineBotResult","resultId","startBot","buildShippingOptions","shippingOptions","prices","ac","cur","label","validateRequestedInfo","requestInfo","shouldSave","sendPaymentForm","formId","requestedInfoId","shippingOptionId","credentials","getPaymentForm","form","canSaveCredentials","passwordMissing","providerId","nativeProvider","nativeParams","savedInfo","nameRequested","phoneRequested","emailRequested","shippingAddressRequested","flexible","phoneToProvider","emailToProvider","mapedPrices","nativeData","needCardholderName","need_cardholder_name","needCountry","need_country","needZip","need_zip","publishableKey","publishable_key","buildPaymentForm","getReceipt","receipt","shipping","credentialsTitle","shippingPrices","shippingMethod","buildReceipt","initApi","_onUpdate","initialArgs","initUpdater","handleUpdate","initAuth","initChats","initMessages","initUsers","initStickers","initManagement","initTwoFaSettings","initCalls","userAgent","sessions","TelegramClient","process","deviceModel","navigator","systemVersion","appVersion","useWSS","additionalDcsDisabled","testServers","addEventHandler","phoneCode","firstAndLastNames","initialMethod","getSessionData","initClient","flushUpdatesOnTickEnd","schedulerFn","fn","waiting","_args","throttleWith","callback","isPrimary","then","currentCallbacks","currentPrimaryCallbacks","cb","throttleId","pendingUpdates","currentThrottleId","currentUpdates","flushUpdatesThrottled","ms","shouldRunFirst","interval","isPending","setInterval","clearInterval","throttle","onerror","sendToOrigin","addEventListener","callbackState","Map","postMessage","onmessage","callbackArgs","lastArg","ArrayBuffer","fnName","methods","callApi","require","crypto","little","signed","randBuffer","bytesNumber","bigInt","subtract","pow","toSignedLittleBuffer","big","number","bigNumber","byteArray","shiftRight","and","readBufferFromBigInt","bitLength","lesser","below","hex","padStart","l","reminder","randomBytes","sha1","shaSum","createHash","digest","crcTable","module","exports","generateRandomLong","mod","n","m","crc32","buf","k","makeCRCTable","isBuffer","crc","generateKeyDataFromNonce","serverNonce","newNonce","hash1","hash2","hash3","iv","sha256","bigIntMod","remainder","modExp","one","x","greater","zero","leastSignificantBit","divide","eq","multiply","getRandomInt","sleep","getByteArray","integer","bits","byteLength","convertToLittle","alloc","writeUInt32BE","bufferXor","res","createDeferred","promise","_resolve","constructors","checkPrimeAndGood","primeBytes","g","equals","numBytesForHash","bigNumForHash","isGoodModExpFirst","modexp","prime","diff","xor","computeHash","algo","salt1","salt2","salt","iterations","pbkdf2","pbkdf2sha512","computeCheck","currentAlgo","PasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow","pwHash","p","B","srp_B","isGoodLarge","pForHash","gForHash","bForHash","gX","kgX","aForHash","A","generateAndCheckRandom","gB","ux","aUx","S","K","pSha","gSha","salt1Sha","salt2Sha","M1","InputCheckPasswordSRP","srpId","computeDigest","JPEG_HEADER","JPEG_FOOTER","_raiseCastFail","target","getMessageId","getInputPeer","allowSelf","checkHash","User","InputPeerSelf","InputPeerUser","Chat","ChatEmpty","ChatForbidden","InputPeerChat","Channel","TypeError","InputPeerChannel","ChannelForbidden","InputUser","InputChannel","UserEmpty","InputPeerEmpty","UserFull","ChatFull","PeerChat","getDisplayName","getAppropriatedPartSize","fileSize","stripped","header","getDC","downloadDC","ipAddress","port","pwd","Api","newAlgo","newSettings","newPasswordHash","newSecureSettings","codeLength","os","Logger","MemorySession","Helpers","utils","Session","LAYER","requests","MTProtoSender","ConnectionTCPObfuscated","authFlow","checkAuthorization","downloadFile","WEBDOCUMENT_REQUEST_PART_SIZE","sizeTypes","apiId","apiHash","opts","DEFAULT_OPTIONS","_useIPV6","useIPV6","baseLogger","_log","floodSleepLimit","_eventBuilders","_phoneCodeHash","parseInt","_requestRetries","requestRetries","_connectionRetries","connectionRetries","_retryDelay","retryDelay","proxy","_proxy","_timeout","timeout","_autoReconnect","autoReconnect","_connection","_floodWaitedRequests","_initWith","InvokeWithLayer","layer","InitConnection","release","systemLangCode","_config","phoneCodeHashes","_exportedSenderPromises","_exportedSenderReleaseTimeouts","_additionalDcsDisabled","_loopStarted","_reconnecting","_destroyed","_initSession","_sender","logger","retries","delay","connectTimeout","authKeyCallback","_authKeyCallback","bind","updateCallback","_handleUpdate","isMainSender","userDisconnected","_user_connected","_disconnected","serverAddress","connect","setAuthKey","authKey","send","GetConfig","_updateLoop","load","setDC","attempts","PingDelayDisconnect","pingId","MIN_SAFE_INTEGER","MAX_SAFE_INTEGER","disconnectDelay","race","getTime","_lastRequest","GetState","sender","newDc","DC","setKey","dc","_authenticated","auth","ExportAuthorization","req","ImportAuthorization","shouldReconnect","existingSender","_connectSender","_createExportedSender","isConnecting","_borrowExportedSender","clearTimeout","onConnectionBreak","_cleanupExportedSender","getSender","inputLocation","messageOrMedia","Message","MessageMediaWebPage","WebPage","MessageMediaPhoto","Photo","_downloadPhoto","MessageMediaDocument","Document","_downloadDocument","MessageMediaContact","_downloadContact","WebDocument","WebDocumentNoProxy","_downloadWebDocument","isBig","loc","chatPhoto","UserProfilePhoto","ChatPhoto","InputPeerPhotoFileLocation","thumbVersion","InputStickerSetThumb","InputStickerSetID","thumbDcId","_pickFileSize","indexOf","_downloadCachedPhotoSize","PhotoStrippedSize","PhotoSizeEmpty","PhotoCachedSize","InputPhotoFileLocation","thumbSize","doc","InputDocumentFileLocation","buff","downloaded","upload","GetWebFile","location","InputWebFileLocation","attempt","sendWithInvokeSupport","ServerError","FloodWaitError","FloodTestPhoneWaitError","PhoneMigrateError","NetworkMigrateError","UserMigrateError","_switchDC","MsgWaitError","isReady","GetUsers","InputUserSelf","authParams","apiCredentials","fileParams","event","Updates","UpdatesCombined","_processUpdate","UpdateShort","others","_dispatchUpdate","ptsDate","builder","times","pause","Infinity","sequentialUpdates","DEFAULT_INITIAL_METHOD","me","botAuthToken","signInBot","signInUser","signInUserWithQrCode","phoneCodeHash","sendCodeResult","sendCode","forceSMS","termsOfService","isRegistrationRequired","signInWithPassword","isScanningComplete","inputPromise","exceptIds","updatePromise","result2","authorization","migratedResult","sendResult","resendResult","passwordSrpResult","passwordSrpCheck","computePasswordSrpCheck","ONE_MB","Foreman","maxWorkers","requestWorker","activeWorkers","releaseWorker","partSizeKb","partSize","partsCount","foreman","promises","hasEnded","isPrecise","offsetMemo","precise","buffers","totalLength","fileId","isLarge","partCount","fileToBuffer","sendingParts","j","jMemo","bytesMemo","filePart","fileTotalParts","parts","md5Checksum","BinaryReader","AuthKey","_key","_hash","reader","auxHash","readLong","read","keyId","writeUInt8","shaData","other","cipher","createCipheriv","encrypt","Factorizator","neq","temp","pq","y","randBetween","minus","ys","condition","gcd","IGE","AESIGE","ige","decryptIge","cipherText","decrypt","encryptIge","plainText","padding","i2abLow","uint8","Uint8Array","int","i2abBig","ab2iLow","ab","Uint32Array","ab2iBig","isBigEndian","i2ab","ab2i","AES","getWords","Counter","initialValue","setBytes","_counter","increment","CTR","_remainingCounter","_remainingCounterIndex","_aes","encrypted","Hash","algorithm","subtle","createDecipheriv","getRandomValues","passwordKey","importKey","deriveBits","s2i","str","pos","charCodeAt","right","ReadCancelledError","TypeNotFoundError","invalidConstructorId","remaining","alert","InvalidChecksumError","checksum","validChecksum","InvalidBufferError","payload","readInt32LE","SecurityError","BadMessageError","errorMessage","ErrorMessages","CdnFileTamperedError","RPCError","_fmtRequest","InvalidDCError","BadRequestError","UnauthorizedError","ForbiddenError","NotFoundError","AuthKeyError","FloodError","TimedOutError","capture","SlowModeWaitError","FileMigrateError","EmailUnconfirmedError","rpcErrorRe","Common","RPCBaseErrors","RPCErrorList","RPCMessageToError","rpcError","msgRegex","Cls","EventBuilder","types","func","blacklistChats","resolved","NewMessage","Raw","StopPropagation","_queue","canGet","resolveGet","canPush","resolvePush","returned","pop","coreObjects","tlobjects","stream","_last","readByte","readInt","readUInt32LE","readLargeInt","readFloat","readFloatLE","readDouble","readDoubleLE","getBuffer","tgReadBytes","firstByte","tgReadString","tgReadBool","tgReadDate","tgReadObject","constructorId","clazz","seek","tellPosition","setPosition","fromReader","tgReadVector","close","position","_stream","write","getValue","_level","level","isBrowser","browser","__nwjs","colors","debug","messageFormat","canSend","levels","stack","format","toISOString","toUpperCase","color","log","MessageContainer","TLMessage","BinaryWriter","USE_INVOKE_AFTER_WITH","_state","_pendingStates","_ready","setReady","append","after","catch","finally","extend","states","batch","MAXIMUM_LENGTH","shift","SIZE_OVERHEAD","MAXIMUM_SIZE","afterId","writeDataAsMessage","unshift","writeUInt32LE","writeInt32LE","containerId","rejectAll","requestState","Mutex","mutex","WebSocketClient","closeError","disconnectedCallback","closed","readData","thisTime","canRead","toReturn","resolveRead","getWebSocketLink","ip","website","onopen","receive","onclose","wasClean","runExclusive","PromisedWebSockets","MessagePacker","AsyncQueue","tl","events","extensions","helpers","PUBLIC_KEYS","fingerprint","_serverKeys","keyInfo","doAuthentication","nonce","resPQ","factorize","pBuffer","qBuffer","pqInnerData","targetFingerprint","targetKey","serverPublicKeyFingerprints","dataWithPadding","dataPadReversed","encryptedData","tempKey","shaDigestKeyWithData","dataWithHash","aesEncrypted","tempKeyXor","keyAesEncrypted","keyAesEncryptedInt","greaterOrEquals","encryptedDataBuffer","serverDhParams","publicKeyFingerprint","sh","nnh","newNonceHash","encryptedAnswer","plainTextAnswer","serverDhInner","dhPrime","ga","gA","serverTime","gb","gab","clientDhInner","retryId","clientDdhInnerHashed","clientDhEncrypted","dhGen","nonceTypes","nonceNumber","calcNewNonceHash","MTProtoState","loggers","body","_getNewMsgId","recv","MtProtoPlainSender","RPCResult","GZIPPacked","RequestState","MsgsAck","MsgsStateInfo","Pong","UpdateConnectionState","UpdateServerTimeOffset","BadServerSalt","BadMsgNotification","MsgDetailedInfo","MsgNewDetailedInfo","NewSessionCreated","FutureSalts","MsgsStateReq","MsgResendReq","MsgsAllInfo","LogOut","_dcId","_retries","_delay","_connectTimeout","_updateCallback","_autoReconnectCallback","autoReconnectCallback","_isMainSender","_onConnectionBreak","_send_loop_handle","_recv_loop_handle","_send_queue","_pending_state","_pending_ack","_last_acks","_handlers","_handleRPCResult","_handleContainer","_handleGzipPacked","_handlePong","_handleBadServerSalt","_handleBadNotification","_handleDetailedInfo","_handleNewDetailedInfo","_handleNewSessionCreated","_handleAck","_handleFutureSalts","_handleStateForgotten","_handleMsgAll","force","_connect","connected","disconnected","_disconnect","plain","_sendLoop","_recvLoop","ack","msgIds","encryptMessageData","reconnect","decryptMessageData","_handleBadAuthKey","_processMessage","shouldSkipForMain","broken","obj","handler","_popStates","toPop","reqMsgId","readResult","innerMessage","pong","newTimeOffset","updateTimeOffset","badSalt","badMsgId","newServerSalt","badMsg","errorCode","_sequence","answerMsgId","serverSalt","repeat","_reconnect","reset","newConnection","_ip","_port","_testServers","InvokeAfterMsg","_lastMsgId","updateMessageId","msgKey","sha256a","sha256b","contentRelated","seqNo","_getSeqNo","gzipIfSmaller","waitForKey","_calcKey","ourKey","remoteMsgId","remoteSequence","containerLen","nanoseconds","newMsgId","shiftLeft","or","correctMsgId","bad","old","pending","Connection","_connected","_sendTask","_recvTask","_codec","_obfuscation","_sendArray","_recvArray","socket","disconnectCallback","PacketCodecClass","_initConn","fromCallback","_send","_recv","tag","encodedPacket","encodePacket","readPacket","PacketCodec","_conn","ObfuscatedConnection","ObfuscatedIO","AbridgedPacketCodec","props","obfuscateTag","ConnectionTCPAbridged","initHeader","_encrypt","encryptor","_decrypt","decryptor","packetCodec","ok","toJSON","randomReversed","encryptKey","encryptIv","decryptKey","decryptIv","readExactly","ConnectionTCPFull","MTProtoPlainSender","StorageSession","CACHE_NAME","_storageKey","cached","_sessionData","_callback","_authKeys","mainDcId","hashes","skipOnUpdate","_serverAddress","idb","_delete","del","_fetchFromCache","_saveToCache","localStorage","removeItem","getItem","setItem","_takeoutId","_updateStates","_authKey","sessionInfo","_sessionString","_loadFromSessionString","skipUpdateStorage","_updateStorage","asHex","mainDcIdStr","mainDcKey","StringSession","decode","readUInt8","serverAddressLen","readInt16BE","dcBuffer","addressBuffer","addressLengthBuffer","writeInt16BE","portBuffer","encode","Memory","CacheApiSession","LocalStorageSession","IdbSession","CallbackSession","api","sub","parseTl","serializeDate","tlContent","schemeContent","CACHING_SUPPORTED","CACHE_KEY","extractParams","fileContent","f","functions","d","isFunction","argToBytes","writeDoubleLE","getArgFromReader","arg","isVector","useVectorId","flagIndicator","skipConstructorId","createClasses","classesType","classes","classParams","subclassOfId","argsConfig","namespace","fullName","VirtualClass","argName","isFlag","flagIndex","idForBytes","flagCalculate","boxed","charAt","definitions","fromCache","jsonCache","loadFromCache","constructorParamsApi","functionParamsApi","constructorParamsSchema","functionParamsSchema","loadFromTlSchemas","obj1","obj2","mergeWithNamespaces","buildApiFromTlSchema","gzipped","toBytes","gzip","ungzip","containerLength","before","tlMessage","RpcError","innerCode","snakeToCamelCase","_","variableSnakeToCamelCase","CORE_TYPES","AUTH_KEY_TYPES","findAll","regex","matches","RegExp","exec","fromLine","line","argsMatch","currentConfig","hexId","representation","brace","argType","buildArgConfig","flagMatch","vectorMatch","ignoreIds","o","objAll","objByName","objByType","commentIndex","trim","followingTypes","dt","fill","t","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","loaded","__webpack_modules__","__webpack_exports__","O","chunkIds","priority","notFulfilled","fulfilled","every","splice","getter","__esModule","definition","defineProperty","enumerable","chunkId","miniCssF","globalThis","Function","prop","prototype","Symbol","toStringTag","nmd","paths","children","scriptUrl","importScripts","currentScript","src","scripts","getElementsByTagName","installedChunks","chunkLoadingGlobal","parentChunkLoadingFunction","moreModules","runtime"],"sourceRoot":""} \ No newline at end of file +{"version":3,"file":"927.151d396500bf8aa6cf1e.js","mappings":"UAAIA,ECAAC,E,ujICAG,MA0GMC,GAnEyB,oBAAXC,QAA0BA,OAAOC,YAmEzBC,KAAKC,MAAM,MACjCC,EAA6B,IAAIC,IAAI,CAChD,aAAc,sBAAuB,iBAAkB,0BAA2B,kBA0BvEC,EAAgC,IAAID,IAAI,CACnD,YAAa,YAAa,eAGfE,EA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gB5B,EAAS1c,OAAS,EACnCwe,EAA2BzwE,K,GlHnBxBzH,EAAO61E,EAAoBx5B,EAC/Bw5B,EAAoBx5B,EAAI,IAChBw5B,EAAoBjhE,EAAE,KAAKsiC,KAAKl3C,GmHDd61E,EAAoBx5B,K","sources":["webpack://telegram-t/webpack/runtime/chunk loaded","webpack://telegram-t/webpack/runtime/startup chunk dependencies","webpack://telegram-t/./src/config.ts","webpack://telegram-t/./src/util/schedulers.ts","webpack://telegram-t/./src/util/iteratees.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/helpers.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/pathBytesToSvg.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/common.ts","webpack://telegram-t/./src/api/gramjs/localDb.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/symbols.ts","webpack://telegram-t/./src/util/waveform.ts","webpack://telegram-t/./src/api/types/messages.ts","webpack://telegram-t/./src/api/types/media.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/peers.ts","webpack://telegram-t/./src/api/gramjs/helpers.ts","webpack://telegram-t/./src/api/gramjs/gramjsBuilders/index.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/messages.ts","webpack://telegram-t/./src/util/serverTime.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/chats.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/users.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/misc.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/calls.ts","webpack://telegram-t/./src/api/gramjs/updater.ts","webpack://telegram-t/./src/api/gramjs/methods/auth.ts","webpack://telegram-t/./src/util/cacheApi.ts","webpack://telegram-t/./src/api/gramjs/methods/media.ts","webpack://telegram-t/./src/api/gramjs/methods/client.ts","webpack://telegram-t/./src/api/gramjs/methods/chats.ts","webpack://telegram-t/./src/util/files.ts","webpack://telegram-t/./src/api/gramjs/methods/messages.ts","webpack://telegram-t/./src/api/gramjs/methods/users.ts","webpack://telegram-t/./src/api/gramjs/methods/symbols.ts","webpack://telegram-t/./src/api/gramjs/methods/management.ts","webpack://telegram-t/./src/api/gramjs/methods/twoFaSettings.ts","webpack://telegram-t/./src/api/gramjs/methods/calls.ts","webpack://telegram-t/./src/api/gramjs/methods/settings.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/bots.ts","webpack://telegram-t/./src/api/gramjs/methods/bots.ts","webpack://telegram-t/./src/api/gramjs/apiBuilders/payments.ts","webpack://telegram-t/./src/api/gramjs/methods/payments.ts","webpack://telegram-t/./src/api/gramjs/provider.ts","webpack://telegram-t/./src/api/gramjs/worker/worker.ts","webpack://telegram-t/./src/lib/gramjs/Helpers.js","webpack://telegram-t/./src/lib/gramjs/Password.js","webpack://telegram-t/./src/lib/gramjs/Utils.js","webpack://telegram-t/./src/lib/gramjs/Version.js","webpack://telegram-t/./src/lib/gramjs/client/2fa.ts","webpack://telegram-t/./src/lib/gramjs/client/TelegramClient.js","webpack://telegram-t/./src/lib/gramjs/client/auth.ts","webpack://telegram-t/./src/lib/gramjs/client/downloadFile.ts","webpack://telegram-t/./src/lib/gramjs/client/uploadFile.ts","webpack://telegram-t/./src/lib/gramjs/crypto/AuthKey.js","webpack://telegram-t/./src/lib/gramjs/crypto/CTR.js","webpack://telegram-t/./src/lib/gramjs/crypto/Factorizator.js","webpack://telegram-t/./src/lib/gramjs/crypto/IGE.js","webpack://telegram-t/./src/lib/gramjs/crypto/converters.ts","webpack://telegram-t/./src/lib/gramjs/crypto/crypto.js","webpack://telegram-t/./src/lib/gramjs/crypto/words.ts","webpack://telegram-t/./src/lib/gramjs/errors/Common.js","webpack://telegram-t/./src/lib/gramjs/errors/RPCBaseErrors.js","webpack://telegram-t/./src/lib/gramjs/errors/RPCErrorList.js","webpack://telegram-t/./src/lib/gramjs/errors/index.js","webpack://telegram-t/./src/lib/gramjs/events/Raw.js","webpack://telegram-t/./src/lib/gramjs/events/common.js","webpack://telegram-t/./src/lib/gramjs/events/index.js","webpack://telegram-t/./src/lib/gramjs/extensions/AsyncQueue.js","webpack://telegram-t/./src/lib/gramjs/extensions/BinaryReader.js","webpack://telegram-t/./src/lib/gramjs/extensions/BinaryWriter.js","webpack://telegram-t/./src/lib/gramjs/extensions/Logger.js","webpack://telegram-t/./src/lib/gramjs/extensions/MessagePacker.js","webpack://telegram-t/./src/lib/gramjs/extensions/PromisedWebSockets.js","webpack://telegram-t/./src/lib/gramjs/extensions/index.js","webpack://telegram-t/./src/lib/gramjs/index.js","webpack://telegram-t/./src/lib/gramjs/crypto/RSA.ts","webpack://telegram-t/./src/lib/gramjs/network/Authenticator.ts","webpack://telegram-t/./src/lib/gramjs/network/MTProtoPlainSender.js","webpack://telegram-t/./src/lib/gramjs/network/MTProtoSender.js","webpack://telegram-t/./src/lib/gramjs/network/MTProtoState.js","webpack://telegram-t/./src/lib/gramjs/network/RequestState.js","webpack://telegram-t/./src/lib/gramjs/network/connection/Connection.js","webpack://telegram-t/./src/lib/gramjs/network/connection/TCPAbridged.js","webpack://telegram-t/./src/lib/gramjs/network/connection/TCPObfuscated.js","webpack://telegram-t/./src/lib/gramjs/network/connection/index.js","webpack://telegram-t/./src/lib/gramjs/network/index.js","webpack://telegram-t/./src/lib/gramjs/sessions/Abstract.js","webpack://telegram-t/./src/lib/gramjs/sessions/CacheApiSession.js","webpack://telegram-t/./src/lib/gramjs/sessions/CallbackSession.js","webpack://telegram-t/./src/lib/gramjs/sessions/IdbSession.js","webpack://telegram-t/./src/lib/gramjs/sessions/LocalStorageSession.js","webpack://telegram-t/./src/lib/gramjs/sessions/Memory.js","webpack://telegram-t/./src/lib/gramjs/sessions/StorageSession.js","webpack://telegram-t/./src/lib/gramjs/sessions/StringSession.js","webpack://telegram-t/./src/lib/gramjs/sessions/index.js","webpack://telegram-t/./src/lib/gramjs/tl/AllTLObjects.js","webpack://telegram-t/./src/lib/gramjs/tl/api.js","webpack://telegram-t/./src/lib/gramjs/tl/apiTl.js","webpack://telegram-t/./src/lib/gramjs/tl/core/GZIPPacked.js","webpack://telegram-t/./src/lib/gramjs/tl/core/MessageContainer.js","webpack://telegram-t/./src/lib/gramjs/tl/core/RPCResult.js","webpack://telegram-t/./src/lib/gramjs/tl/core/TLMessage.js","webpack://telegram-t/./src/lib/gramjs/tl/core/index.js","webpack://telegram-t/./src/lib/gramjs/tl/generationHelpers.js","webpack://telegram-t/./src/lib/gramjs/tl/index.js","webpack://telegram-t/./src/lib/gramjs/tl/schemaTl.js","webpack://telegram-t/webpack/bootstrap","webpack://telegram-t/webpack/runtime/compat get default export","webpack://telegram-t/webpack/runtime/define property getters","webpack://telegram-t/webpack/runtime/ensure chunk","webpack://telegram-t/webpack/runtime/get javascript chunk filename","webpack://telegram-t/webpack/runtime/get mini-css chunk filename","webpack://telegram-t/webpack/runtime/global","webpack://telegram-t/webpack/runtime/hasOwnProperty shorthand","webpack://telegram-t/webpack/runtime/make namespace object","webpack://telegram-t/webpack/runtime/node module decorator","webpack://telegram-t/webpack/runtime/publicPath","webpack://telegram-t/webpack/runtime/importScripts chunk loading","webpack://telegram-t/webpack/startup"],"sourcesContent":["var deferred = [];\n__webpack_require__.O = (result, chunkIds, fn, priority) => {\n\tif(chunkIds) {\n\t\tpriority = priority || 0;\n\t\tfor(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1];\n\t\tdeferred[i] = [chunkIds, fn, priority];\n\t\treturn;\n\t}\n\tvar notFulfilled = Infinity;\n\tfor (var i = 0; i < deferred.length; i++) {\n\t\tvar [chunkIds, fn, priority] = deferred[i];\n\t\tvar fulfilled = true;\n\t\tfor (var j = 0; j < chunkIds.length; j++) {\n\t\t\tif ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(__webpack_require__.O).every((key) => (__webpack_require__.O[key](chunkIds[j])))) {\n\t\t\t\tchunkIds.splice(j--, 1);\n\t\t\t} else {\n\t\t\t\tfulfilled = false;\n\t\t\t\tif(priority < notFulfilled) notFulfilled = priority;\n\t\t\t}\n\t\t}\n\t\tif(fulfilled) {\n\t\t\tdeferred.splice(i--, 1)\n\t\t\tvar r = fn();\n\t\t\tif (r !== undefined) result = r;\n\t\t}\n\t}\n\treturn result;\n};","var next = __webpack_require__.x;\n__webpack_require__.x = () => {\n\treturn __webpack_require__.e(592).then(next);\n};","export const PAGE_TITLE = 'Telegram';\nexport const INACTIVE_MARKER = ' [Inactive]';\n\nexport const APP_NAME = process.env.APP_NAME || 'Telegram WebZ';\nexport const APP_VERSION = process.env.APP_VERSION || 'dev';\n\nexport const DEBUG = (\n process.env.APP_ENV !== 'production' && process.env.APP_ENV !== 'perf' && process.env.APP_ENV !== 'test'\n);\nexport const DEBUG_MORE = false;\n\nexport const IS_TEST = process.env.APP_ENV === 'test';\nexport const IS_PERF = process.env.APP_ENV === 'perf';\n\nexport const DEBUG_ALERT_MSG = 'Shoot!\\nSomething went wrong, please see the error details in Dev Tools Console.';\nexport const DEBUG_GRAMJS = false;\n\nexport const SESSION_USER_KEY = 'user_auth';\nexport const LEGACY_SESSION_KEY = 'GramJs:sessionId';\n\nexport const GLOBAL_STATE_CACHE_DISABLED = false;\nexport const GLOBAL_STATE_CACHE_KEY = 'tt-global-state';\nexport const GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT = 30;\nexport const GLOBAL_STATE_CACHE_USER_LIST_LIMIT = 5000;\n\nexport const MEDIA_CACHE_DISABLED = false;\nexport const MEDIA_CACHE_NAME = 'tt-media';\nexport const MEDIA_CACHE_NAME_AVATARS = 'tt-media-avatars';\nexport const MEDIA_PROGRESSIVE_CACHE_DISABLED = false;\nexport const MEDIA_PROGRESSIVE_CACHE_NAME = 'tt-media-progressive';\nexport const MEDIA_CACHE_MAX_BYTES = 512 * 1024; // 512 KB\nexport const CUSTOM_BG_CACHE_NAME = 'tt-custom-bg';\nexport const LANG_CACHE_NAME = 'tt-lang-packs-v7';\nexport const ASSET_CACHE_NAME = 'tt-assets';\nexport const AUTODOWNLOAD_FILESIZE_MB_LIMITS = [1, 5, 10, 50, 100, 500];\n\nexport const DOWNLOAD_WORKERS = 16;\nexport const UPLOAD_WORKERS = 16;\n\nconst isBigScreen = typeof window !== 'undefined' && window.innerHeight >= 900;\n\nexport const MIN_PASSWORD_LENGTH = 1;\n\nexport const MESSAGE_LIST_SLICE = isBigScreen ? 60 : 40;\nexport const MESSAGE_LIST_VIEWPORT_LIMIT = MESSAGE_LIST_SLICE * 2;\n\nexport const CHAT_HEIGHT_PX = 72;\nexport const CHAT_LIST_SLICE = isBigScreen ? 30 : 25;\nexport const CHAT_LIST_LOAD_SLICE = 100;\nexport const SHARED_MEDIA_SLICE = 42;\nexport const MESSAGE_SEARCH_SLICE = 42;\nexport const GLOBAL_SEARCH_SLICE = 20;\nexport const MEMBERS_SLICE = 30;\nexport const MEMBERS_LOAD_SLICE = 200;\nexport const PINNED_MESSAGES_LIMIT = 50;\nexport const BLOCKED_LIST_LIMIT = 100;\nexport const PROFILE_PHOTOS_LIMIT = 40;\nexport const PROFILE_SENSITIVE_AREA = 500;\nexport const COMMON_CHATS_LIMIT = 100;\nexport const GROUP_CALL_PARTICIPANTS_LIMIT = 100;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 20;\nexport const ALL_CHATS_PRELOAD_DISABLED = false;\n\nexport const SPONSORED_MESSAGE_CACHE_MS = 300000; // 5 min\n\nexport const DEFAULT_VOLUME = 1;\nexport const DEFAULT_PLAYBACK_RATE = 1;\n\nexport const ANIMATION_LEVEL_MIN = 0;\nexport const ANIMATION_LEVEL_MED = 1;\nexport const ANIMATION_LEVEL_MAX = 2;\nexport const ANIMATION_LEVEL_DEFAULT = ANIMATION_LEVEL_MAX;\n\nexport const DEFAULT_MESSAGE_TEXT_SIZE_PX = 16;\nexport const IOS_DEFAULT_MESSAGE_TEXT_SIZE_PX = 17;\nexport const MACOS_DEFAULT_MESSAGE_TEXT_SIZE_PX = 15;\n\nexport const DRAFT_DEBOUNCE = 10000; // 10s\nexport const SEND_MESSAGE_ACTION_INTERVAL = 3000; // 3s\n\nexport const EDITABLE_INPUT_ID = 'editable-message-text';\nexport const EDITABLE_INPUT_MODAL_ID = 'editable-message-text-modal';\n\n// Screen width where Pinned Message / Audio Player in the Middle Header can be safely displayed\nexport const SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1440; // px\n// Screen width where Pinned Message / Audio Player in the Middle Header shouldn't collapse with ChatInfo\nexport const SAFE_SCREEN_WIDTH_FOR_CHAT_INFO = 1150; // px\n\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1275; // px\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN = 925; // px\nexport const MOBILE_SCREEN_MAX_WIDTH = 600; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH = 950; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT = 450; // px\n\nexport const LOCAL_MESSAGE_ID_BASE = 1e9;\nexport const TMP_CHAT_ID = '0';\n\nexport const ANIMATION_END_DELAY = 100;\n\nexport const FAST_SMOOTH_MAX_DISTANCE = 1500;\nexport const FAST_SMOOTH_MIN_DURATION = 250;\nexport const FAST_SMOOTH_MAX_DURATION = 600;\nexport const FAST_SMOOTH_SHORT_TRANSITION_MAX_DISTANCE = 500; // px\n\n// Average duration of message sending animation\nexport const API_UPDATE_THROTTLE = Math.round((FAST_SMOOTH_MIN_DURATION + FAST_SMOOTH_MAX_DURATION) / 2);\nexport const API_THROTTLE_RESET_UPDATES = new Set([\n 'newMessage', 'newScheduledMessage', 'deleteMessages', 'deleteScheduledMessages', 'deleteHistory',\n]);\n\nexport const STICKER_SIZE_INLINE_DESKTOP_FACTOR = 13;\nexport const STICKER_SIZE_INLINE_MOBILE_FACTOR = 11;\nexport const STICKER_SIZE_AUTH = 160;\nexport const STICKER_SIZE_AUTH_MOBILE = 120;\nexport const STICKER_SIZE_PICKER = 64;\nexport const STICKER_SIZE_GENERAL_SETTINGS = 48;\nexport const STICKER_SIZE_PICKER_HEADER = 32;\nexport const STICKER_SIZE_SEARCH = 64;\nexport const STICKER_SIZE_MODAL = 64;\nexport const STICKER_SIZE_TWO_FA = 160;\nexport const STICKER_SIZE_DISCUSSION_GROUPS = 140;\nexport const STICKER_SIZE_FOLDER_SETTINGS = 80;\nexport const STICKER_SIZE_INLINE_BOT_RESULT = 100;\nexport const RECENT_STICKERS_LIMIT = 20;\nexport const MEMOJI_STICKER_ID = 'MEMOJI_STICKER';\n\nexport const BASE_EMOJI_KEYWORD_LANG = 'en';\n\nexport const MENU_TRANSITION_DURATION = 200;\nexport const SLIDE_TRANSITION_DURATION = 450;\n\nexport const VIDEO_MOV_TYPE = 'video/quicktime';\n\nexport const SUPPORTED_IMAGE_CONTENT_TYPES = new Set([\n 'image/png', 'image/gif', 'image/jpeg',\n]);\n\nexport const SUPPORTED_VIDEO_CONTENT_TYPES = new Set([\n 'video/mp4', // video/quicktime added dynamically in environment.ts\n]);\n\nexport const CONTENT_TYPES_WITH_PREVIEW = new Set([\n ...SUPPORTED_IMAGE_CONTENT_TYPES,\n ...SUPPORTED_VIDEO_CONTENT_TYPES,\n]);\n\nexport const CONTENT_NOT_SUPPORTED = 'The message is not supported on this version of Telegram.';\n\n// eslint-disable-next-line max-len\nexport const RE_LINK_TEMPLATE = '((ftp|https?):\\\\/\\\\/)?((www\\\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\\\.[a-zA-Z0-9()]{1,63})\\\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)';\nexport const RE_MENTION_TEMPLATE = '(@[\\\\w\\\\d_-]+)';\nexport const RE_TG_LINK = /^tg:(\\/\\/)?([?=&\\d\\w_-]+)?/gm;\nexport const RE_TME_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/)/gm;\n\n// eslint-disable-next-line max-len\nexport const COUNTRIES_WITH_12H_TIME_FORMAT = new Set(['AU', 'BD', 'CA', 'CO', 'EG', 'HN', 'IE', 'IN', 'JO', 'MX', 'MY', 'NI', 'NZ', 'PH', 'PK', 'SA', 'SV', 'US']);\n\n// MTProto constants\nexport const SERVICE_NOTIFICATIONS_USER_ID = '777000';\nexport const REPLIES_USER_ID = '1271266957'; // TODO For Test connection ID must be equal to 708513\nexport const ALL_FOLDER_ID = 0;\nexport const ARCHIVED_FOLDER_ID = 1;\nexport const DELETED_COMMENTS_CHANNEL_ID = '-777';\nexport const MAX_MEDIA_FILES_FOR_ALBUM = 10;\nexport const MAX_ACTIVE_PINNED_CHATS = 5;\nexport const SCHEDULED_WHEN_ONLINE = 0x7FFFFFFE;\nexport const DEFAULT_LANG_CODE = 'en';\nexport const DEFAULT_LANG_PACK = 'android';\nexport const LANG_PACKS = ['android', 'ios', 'tdesktop', 'macos'] as const;\nexport const TIPS_USERNAME = 'TelegramTips';\nexport const LOCALIZED_TIPS = ['ar', 'pt-br', 'id', 'it', 'ko', 'ms', 'pl', 'es', 'tr'];\nexport const FEEDBACK_URL = 'https://bugs.telegram.org/?tag_ids=41&sort=time';\nexport const LIGHT_THEME_BG_COLOR = '#A2AF8E';\nexport const DARK_THEME_BG_COLOR = '#0F0F0F';\nexport const DARK_THEME_PATTERN_COLOR = '#0a0a0a8c';\nexport const DEFAULT_PATTERN_COLOR = 'rgba(90, 110, 70, 0.6)';\n// TODO Get values from `getConfig` method once it's available\nexport const SEEN_BY_MEMBERS_CHAT_MAX = 50;\nexport const SEEN_BY_MEMBERS_EXPIRE = 604680; // One week - 2 min\n\n// Group calls\nexport const GROUP_CALL_VOLUME_MULTIPLIER = 100;\nexport const GROUP_CALL_DEFAULT_VOLUME = 100 * GROUP_CALL_VOLUME_MULTIPLIER;\nexport const ENABLE_THUMBNAIL_VIDEO = false;\n","type Scheduler =\n typeof requestAnimationFrame\n | typeof onTickEnd\n | typeof runNow;\n\nexport function debounce(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n shouldRunLast = true,\n) {\n let waitingTimeout: number | undefined;\n\n return (...args: Parameters) => {\n if (waitingTimeout) {\n clearTimeout(waitingTimeout);\n waitingTimeout = undefined;\n } else if (shouldRunFirst) {\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n waitingTimeout = self.setTimeout(() => {\n if (shouldRunLast) {\n fn(...args);\n }\n\n waitingTimeout = undefined;\n }, ms);\n };\n}\n\nexport function throttle(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n) {\n let interval: number | undefined;\n let isPending: boolean;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n isPending = true;\n args = _args;\n\n if (!interval) {\n if (shouldRunFirst) {\n isPending = false;\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n interval = self.setInterval(() => {\n if (!isPending) {\n // eslint-disable-next-line no-restricted-globals\n self.clearInterval(interval!);\n interval = undefined;\n return;\n }\n\n isPending = false;\n fn(...args);\n }, ms);\n }\n };\n}\n\nexport function throttleWithRaf(fn: F) {\n return throttleWith(fastRaf, fn);\n}\n\nexport function throttleWithPrimaryRaf(fn: F) {\n return throttleWith(fastRafPrimary, fn);\n}\n\nexport function throttleWithTickEnd(fn: F) {\n return throttleWith(onTickEnd, fn);\n}\n\nexport function throttleWithNow(fn: F) {\n return throttleWith(runNow, fn);\n}\n\nexport function throttleWith(schedulerFn: Scheduler, fn: F) {\n let waiting = false;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n args = _args;\n\n if (!waiting) {\n waiting = true;\n\n schedulerFn(() => {\n waiting = false;\n fn(...args);\n });\n }\n };\n}\n\nexport function onIdle(cb: NoneToVoidFunction, timeout?: number) {\n // eslint-disable-next-line no-restricted-globals\n if (self.requestIdleCallback) {\n // eslint-disable-next-line no-restricted-globals\n self.requestIdleCallback(cb, { timeout });\n } else {\n onTickEnd(cb);\n }\n}\n\nfunction runNow(fn: NoneToVoidFunction) {\n fn();\n}\n\nexport const pause = (ms: number) => new Promise((resolve) => {\n setTimeout(() => resolve(), ms);\n});\n\nexport function rafPromise() {\n return new Promise((resolve) => {\n fastRaf(resolve);\n });\n}\n\nlet fastRafCallbacks: NoneToVoidFunction[] | undefined;\nlet fastRafPrimaryCallbacks: NoneToVoidFunction[] | undefined;\n\n// May result in an immediate execution if called from another `requestAnimationFrame` callback\nexport function fastRaf(callback: NoneToVoidFunction, isPrimary = false) {\n if (!fastRafCallbacks) {\n fastRafCallbacks = isPrimary ? [] : [callback];\n fastRafPrimaryCallbacks = isPrimary ? [callback] : [];\n\n requestAnimationFrame(() => {\n const currentCallbacks = fastRafCallbacks!;\n const currentPrimaryCallbacks = fastRafPrimaryCallbacks!;\n fastRafCallbacks = undefined;\n fastRafPrimaryCallbacks = undefined;\n currentPrimaryCallbacks.forEach((cb) => cb());\n currentCallbacks.forEach((cb) => cb());\n });\n } else if (isPrimary) {\n fastRafPrimaryCallbacks!.push(callback);\n } else {\n fastRafCallbacks.push(callback);\n }\n}\n\nexport function fastRafPrimary(callback: NoneToVoidFunction) {\n fastRaf(callback, true);\n}\n\nlet onTickEndCallbacks: NoneToVoidFunction[] | undefined;\nlet onTickEndPrimaryCallbacks: NoneToVoidFunction[] | undefined;\n\nexport function onTickEnd(callback: NoneToVoidFunction, isPrimary = false) {\n if (!onTickEndCallbacks) {\n onTickEndCallbacks = isPrimary ? [] : [callback];\n onTickEndPrimaryCallbacks = isPrimary ? [callback] : [];\n\n Promise.resolve().then(() => {\n const currentCallbacks = onTickEndCallbacks!;\n const currentPrimaryCallbacks = onTickEndPrimaryCallbacks!;\n onTickEndCallbacks = undefined;\n onTickEndPrimaryCallbacks = undefined;\n currentPrimaryCallbacks.forEach((cb) => cb());\n currentCallbacks.forEach((cb) => cb());\n });\n } else if (isPrimary) {\n onTickEndPrimaryCallbacks!.push(callback);\n } else {\n onTickEndCallbacks.push(callback);\n }\n}\n\nexport function onTickEndPrimary(callback: NoneToVoidFunction) {\n onTickEnd(callback, true);\n}\n\nlet beforeUnloadCallbacks: NoneToVoidFunction[] | undefined;\n\nexport function onBeforeUnload(callback: NoneToVoidFunction, isLast = false) {\n if (!beforeUnloadCallbacks) {\n beforeUnloadCallbacks = [];\n // eslint-disable-next-line no-restricted-globals\n self.addEventListener('beforeunload', () => {\n beforeUnloadCallbacks!.forEach((cb) => cb());\n });\n }\n\n if (isLast) {\n beforeUnloadCallbacks.push(callback);\n } else {\n beforeUnloadCallbacks.unshift(callback);\n }\n\n return () => {\n beforeUnloadCallbacks = beforeUnloadCallbacks!.filter((cb) => cb !== callback);\n };\n}\n","type CollectionByKey = Record;\n\ntype OrderDirection =\n 'asc'\n | 'desc';\n\ninterface OrderCallback {\n (member: T): any;\n}\n\nexport function buildCollectionByKey(collection: T[], key: keyof T) {\n return collection.reduce((byKey: CollectionByKey, member: T) => {\n byKey[member[key]] = member;\n\n return byKey;\n }, {});\n}\n\nexport function mapValues(\n byKey: CollectionByKey,\n callback: (member: M, key: string, index: number, originalByKey: CollectionByKey) => R,\n): CollectionByKey {\n return Object.keys(byKey).reduce((newByKey: CollectionByKey, key, index) => {\n newByKey[key] = callback(byKey[key], key, index, byKey);\n return newByKey;\n }, {});\n}\n\nexport function pick(object: T, keys: K[]) {\n return keys.reduce((result, key) => {\n result[key] = object[key];\n return result;\n }, {} as Pick);\n}\n\nexport function pickTruthy(object: T, keys: K[]) {\n return keys.reduce((result, key) => {\n if (object[key]) {\n result[key] = object[key];\n }\n\n return result;\n }, {} as Pick);\n}\n\nexport function omit(object: T, keys: K[]) {\n const stringKeys = new Set(keys.map(String));\n const savedKeys = Object.keys(object)\n .filter((key) => !stringKeys.has(key)) as Array>;\n\n return pick(object, savedKeys);\n}\n\nexport function orderBy(\n collection: T[],\n orderRule: (keyof T) | OrderCallback | ((keyof T) | OrderCallback)[],\n mode: OrderDirection | [OrderDirection, OrderDirection] = 'asc',\n): T[] {\n function compareValues(a: T, b: T, currentOrderRule: (keyof T) | OrderCallback, isAsc: boolean) {\n const aValue = (typeof currentOrderRule === 'function' ? currentOrderRule(a) : a[currentOrderRule]) || 0;\n const bValue = (typeof currentOrderRule === 'function' ? currentOrderRule(b) : b[currentOrderRule]) || 0;\n\n return isAsc ? aValue - bValue : bValue - aValue;\n }\n\n if (Array.isArray(orderRule)) {\n const [mode1, mode2] = Array.isArray(mode) ? mode : [mode, mode];\n const [orderRule1, orderRule2] = orderRule;\n const isAsc1 = mode1 === 'asc';\n const isAsc2 = mode2 === 'asc';\n\n return collection.sort((a, b) => {\n return compareValues(a, b, orderRule1, isAsc1) || compareValues(a, b, orderRule2, isAsc2);\n });\n }\n\n const isAsc = mode === 'asc';\n return collection.sort((a, b) => {\n return compareValues(a, b, orderRule, isAsc);\n });\n}\n\nexport function flatten(array: any[]) {\n return array.reduce((result, member) => {\n if (Array.isArray(member)) {\n return result.concat(member);\n } else {\n result.push(member);\n return result;\n }\n }, []);\n}\n\nexport function unique(array: T[]): T[] {\n return Array.from(new Set(array));\n}\n\nexport function compact(array: any[]) {\n return array.filter(Boolean);\n}\n\nexport function areSortedArraysEqual(array1: any[], array2: any[]) {\n if (array1.length !== array2.length) {\n return false;\n }\n\n return array1.every((item, i) => item === array2[i]);\n}\n\nexport function areSortedArraysIntersecting(array1: any[], array2: any[]) {\n return array1[0] <= array2[array2.length - 1] && array1[array1.length - 1] >= array2[0];\n}\n\nexport function findIntersectionWithSet(array: T[], set: Set): T[] {\n return array.filter((a) => set.has(a));\n}\n\nexport function split(array: any[], chunkSize: number) {\n const result = [];\n for (let i = 0; i < array.length; i += chunkSize) {\n result.push(array.slice(i, i + chunkSize));\n }\n\n return result;\n}\n\nexport function cloneDeep(value: T): T {\n if (typeof value !== 'object') {\n return value;\n }\n\n if (Array.isArray(value)) {\n return value.map(cloneDeep) as typeof value;\n }\n\n return Object.keys(value).reduce((acc, key) => {\n acc[key as keyof T] = cloneDeep(value[key as keyof T]);\n return acc;\n }, {} as T);\n}\n\nexport function findLast(array: Array, predicate: (value: T, index: number, obj: T[]) => boolean): T | undefined {\n let cursor = array.length;\n\n while (cursor--) {\n if (predicate(array[cursor], cursor, array)) {\n return array[cursor];\n }\n }\n\n return undefined;\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\n\ntype VirtualFields =\n 'flags'\n | 'CONSTRUCTOR_ID'\n | 'SUBCLASS_OF_ID'\n | 'className'\n | 'classType'\n | 'getBytes';\n\nexport function bytesToDataUri(bytes: Buffer, shouldOmitPrefix = false, mimeType: string = 'image/jpeg') {\n const prefix = shouldOmitPrefix ? '' : `data:${mimeType};base64,`;\n\n return `${prefix}${btoa(String.fromCharCode(...bytes))}`;\n}\n\nexport function omitVirtualClassFields & { flags?: any }>(\n instance: T,\n): Omit {\n const {\n flags,\n CONSTRUCTOR_ID,\n SUBCLASS_OF_ID,\n className,\n classType,\n getBytes,\n ...rest\n } = instance;\n\n return rest;\n}\n","/* eslint-disable no-bitwise */\n\n// eslint-disable-next-line max-len\nconst TEMPLATE = '';\nconst LOOKUP = 'AACAAAAHAAALMAAAQASTAVAAAZaacaaaahaaalmaaaqastava.az0123456789-,';\n\nexport function pathBytesToSvg(bytes: Buffer, width: number, height: number) {\n return TEMPLATE\n .replace('{{path}}', buildPath(bytes))\n .replace('{{width}}', String(width))\n .replace('{{height}}', String(height));\n}\n\nfunction buildPath(bytes: Buffer) {\n let path = 'M';\n\n const len = bytes.length;\n for (let i = 0; i < len; i++) {\n const num = bytes[i];\n if (num >= 128 + 64) {\n path += LOOKUP[num - 128 - 64];\n } else {\n if (num >= 128) {\n path += ',';\n } else if (num >= 64) {\n path += '-';\n }\n path += String(num & 63);\n }\n }\n\n path += 'z';\n\n return path;\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport { strippedPhotoToJpg } from '../../../lib/gramjs/Utils';\n\nimport {\n ApiPhoto, ApiPhotoSize, ApiThumbnail,\n} from '../../types';\nimport { bytesToDataUri } from './helpers';\nimport { pathBytesToSvg } from './pathBytesToSvg';\n\nconst DEFAULT_THUMB_SIZE = { w: 100, h: 100 };\n\nexport function buildApiThumbnailFromStripped(\n sizes?: GramJs.TypePhotoSize[], mimeType?: string,\n): ApiThumbnail | undefined {\n if (!sizes || !sizes.length) {\n return undefined;\n }\n\n const thumb = sizes.find((s: any): s is GramJs.PhotoStrippedSize => s instanceof GramJs.PhotoStrippedSize);\n if (!thumb) {\n return undefined;\n }\n\n const realSizes = sizes.filter((s): s is GramJs.PhotoSize => s instanceof GramJs.PhotoSize);\n const { w, h } = realSizes.length ? realSizes[realSizes.length - 1] : DEFAULT_THUMB_SIZE;\n const { bytes } = thumb;\n const dataUri = bytesToDataUri(\n !mimeType || mimeType === 'image/jpeg' ? strippedPhotoToJpg(bytes) : bytes,\n undefined,\n mimeType,\n );\n\n return {\n dataUri,\n width: w,\n height: h,\n };\n}\n\nexport function buildApiThumbnailFromCached(photoSize: GramJs.PhotoCachedSize): ApiThumbnail | undefined {\n const { w, h, bytes } = photoSize;\n const dataUri = bytesToDataUri(bytes, undefined, 'image/webp');\n\n return {\n dataUri,\n width: w,\n height: h,\n };\n}\n\nexport function buildApiThumbnailFromPath(\n photoSize: GramJs.PhotoPathSize,\n sizeAttribute: GramJs.DocumentAttributeImageSize,\n): ApiThumbnail | undefined {\n const { w, h } = sizeAttribute;\n const dataUri = `data:image/svg+xml;utf8,${pathBytesToSvg(photoSize.bytes, w, h)}`;\n\n return {\n dataUri,\n width: w,\n height: h,\n };\n}\n\nexport function buildApiPhoto(photo: GramJs.Photo): ApiPhoto {\n const sizes = photo.sizes\n .filter((s: any): s is GramJs.PhotoSize => {\n return s instanceof GramJs.PhotoSize || s instanceof GramJs.PhotoSizeProgressive;\n })\n .map(buildApiPhotoSize);\n\n return {\n id: String(photo.id),\n thumbnail: buildApiThumbnailFromStripped(photo.sizes),\n sizes,\n };\n}\n\nexport function buildApiPhotoSize(photoSize: GramJs.PhotoSize): ApiPhotoSize {\n const { w, h, type } = photoSize;\n\n return {\n width: w,\n height: h,\n type: type as ('m' | 'x' | 'y'),\n };\n}\n","import { Api as GramJs } from '../../lib/gramjs';\nimport { ApiMessage } from '../types';\n\ninterface LocalDb {\n localMessages: Record;\n // Used for loading avatars and media through in-memory Gram JS instances.\n chats: Record;\n users: Record;\n messages: Record;\n documents: Record;\n stickerSets: Record;\n photos: Record;\n webDocuments: Record;\n}\n\nexport default {\n localMessages: {},\n chats: {},\n users: {},\n messages: {},\n documents: {},\n stickerSets: {},\n photos: {},\n webDocuments: {},\n} as LocalDb;\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport { ApiSticker, ApiStickerSet } from '../../types';\nimport { MEMOJI_STICKER_ID } from '../../../config';\n\nimport { buildApiThumbnailFromCached, buildApiThumbnailFromPath } from './common';\nimport localDb from '../localDb';\n\nconst ANIMATED_STICKER_MIME_TYPE = 'application/x-tgsticker';\n\nexport function buildStickerFromDocument(document: GramJs.TypeDocument): ApiSticker | undefined {\n if (document instanceof GramJs.DocumentEmpty) {\n return undefined;\n }\n\n const stickerAttribute = document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeSticker => (\n attr instanceof GramJs.DocumentAttributeSticker\n ));\n\n const fileAttribute = document.mimeType === ANIMATED_STICKER_MIME_TYPE && document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeFilename => (\n attr instanceof GramJs.DocumentAttributeFilename\n ));\n\n if (!stickerAttribute && !fileAttribute) {\n return undefined;\n }\n\n const sizeAttribute = document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeImageSize => (\n attr instanceof GramJs.DocumentAttributeImageSize\n ));\n\n const stickerSetInfo = stickerAttribute && stickerAttribute.stickerset instanceof GramJs.InputStickerSetID\n ? stickerAttribute.stickerset\n : undefined;\n const emoji = stickerAttribute?.alt;\n const isAnimated = document.mimeType === ANIMATED_STICKER_MIME_TYPE;\n const cachedThumb = document.thumbs && document.thumbs.find(\n (s): s is GramJs.PhotoCachedSize => s instanceof GramJs.PhotoCachedSize,\n );\n const pathThumb = document.thumbs && document.thumbs.find(\n (s): s is GramJs.PhotoPathSize => s instanceof GramJs.PhotoPathSize,\n );\n const thumbnail = cachedThumb ? (\n buildApiThumbnailFromCached(cachedThumb)\n ) : pathThumb && sizeAttribute ? (\n buildApiThumbnailFromPath(pathThumb, sizeAttribute)\n ) : undefined;\n\n const { w: width, h: height } = cachedThumb as GramJs.PhotoCachedSize || sizeAttribute || {};\n\n return {\n id: String(document.id),\n stickerSetId: stickerSetInfo ? String(stickerSetInfo.id) : MEMOJI_STICKER_ID,\n stickerSetAccessHash: stickerSetInfo && String(stickerSetInfo.accessHash),\n emoji,\n isAnimated,\n width,\n height,\n thumbnail,\n };\n}\n\nexport function buildStickerSet(set: GramJs.StickerSet): ApiStickerSet {\n const {\n archived,\n animated,\n installedDate,\n id,\n accessHash,\n title,\n thumbs,\n count,\n shortName,\n } = set;\n\n return {\n archived,\n isAnimated: animated,\n installedDate,\n id: String(id),\n accessHash: String(accessHash),\n title,\n hasThumbnail: Boolean(thumbs?.length),\n count,\n shortName,\n };\n}\n\nexport function buildStickerSetCovered(coveredStickerSet: GramJs.TypeStickerSetCovered): ApiStickerSet {\n const stickerSet = buildStickerSet(coveredStickerSet.set);\n\n const stickerSetCovers = (coveredStickerSet instanceof GramJs.StickerSetMultiCovered)\n ? coveredStickerSet.covers\n : [coveredStickerSet.cover];\n\n stickerSet.covers = [];\n stickerSetCovers.forEach((cover) => {\n if (cover instanceof GramJs.Document) {\n const coverSticker = buildStickerFromDocument(cover);\n if (coverSticker) {\n stickerSet.covers!.push(coverSticker);\n localDb.documents[String(cover.id)] = cover;\n }\n }\n });\n\n return stickerSet;\n}\n","/* eslint-disable no-bitwise */\n\n// eslint-disable-next-line max-len\n// Ref: https://github.com/telegramdesktop/tdesktop/blob/0743e71ab6b928d2ee5bae1aed991849b1e2b291/Telegram/SourceFiles/data/data_document.cpp#L1018\nexport function decodeWaveform(encoded5bit: Uint8Array) {\n const bitsCount = encoded5bit.length * 8;\n const valuesCount = Math.floor(bitsCount / 5);\n if (!valuesCount) {\n return [];\n }\n\n // Read each 5 bit of encoded5bit as 0-31 unsigned char.\n // We count the index of the byte in which the desired 5-bit sequence starts.\n // And then we read a uint16 starting from that byte to guarantee to get all of those 5 bits.\n //\n // BUT! if it is the last byte we have, we're not allowed to read a uint16 starting with it.\n // Because it will be an overflow (we'll access one byte after the available memory).\n // We see, that only the last 5 bits could start in the last available byte and be problematic.\n // So we read in a general way all the entries in a general way except the last one.\n const result = Array(valuesCount);\n const bitsData = encoded5bit;\n for (let i = 0, l = valuesCount - 1; i !== l; ++i) {\n const byteIndex = Math.floor((i * 5) / 8);\n const bitShift = Math.floor((i * 5) % 8);\n const value = bitsData[byteIndex] + (bitsData[byteIndex + 1] << 8);\n result[i] = ((value >> bitShift) & 0x1F);\n }\n const lastByteIndex = Math.floor(((valuesCount - 1) * 5) / 8);\n const lastBitShift = Math.floor(((valuesCount - 1) * 5) % 8);\n const lastValue = bitsData[lastByteIndex] + (bitsData[lastByteIndex + 1] << 8);\n result[valuesCount - 1] = (lastValue >> lastBitShift) & 0x1F;\n\n return result;\n}\n\nexport function interpolateArray(data: number[], fitCount: number) {\n let peak = 0;\n const newData = new Array(fitCount);\n const springFactor = data.length / fitCount;\n const leftFiller = data[0];\n const rightFiller = data[data.length - 1];\n for (let i = 0; i < fitCount; i++) {\n const idx = Math.floor(i * springFactor);\n const val = ((data[idx - 1] ?? leftFiller) + (data[idx] ?? leftFiller) + (data[idx + 1] ?? rightFiller)) / 3;\n newData[i] = val;\n if (peak < val) {\n peak = val;\n }\n }\n return { data: newData, peak };\n}\n","import { ApiGroupCall } from './calls';\n\nexport interface ApiDimensions {\n width: number;\n height: number;\n}\n\nexport interface ApiPhotoSize extends ApiDimensions {\n type: 's' | 'm' | 'x' | 'y' | 'z';\n}\n\nexport interface ApiThumbnail extends ApiDimensions {\n dataUri: string;\n}\n\nexport interface ApiPhoto {\n id: string;\n thumbnail?: ApiThumbnail;\n sizes: ApiPhotoSize[];\n blobUrl?: string;\n}\n\nexport interface ApiSticker {\n id: string;\n stickerSetId: string;\n stickerSetAccessHash?: string;\n emoji?: string;\n isAnimated: boolean;\n width?: number;\n height?: number;\n thumbnail?: ApiThumbnail;\n isPreloadedGlobally?: boolean;\n}\n\nexport interface ApiStickerSet {\n archived?: true;\n isAnimated?: true;\n installedDate?: number;\n id: string;\n accessHash: string;\n title: string;\n hasThumbnail?: boolean;\n count: number;\n stickers?: ApiSticker[];\n packs?: Record;\n covers?: ApiSticker[];\n shortName: string;\n}\n\nexport interface ApiVideo {\n id: string;\n mimeType: string;\n duration: number;\n fileName: string;\n width?: number;\n height?: number;\n supportsStreaming?: boolean;\n isRound?: boolean;\n isGif?: boolean;\n thumbnail?: ApiThumbnail;\n blobUrl?: string;\n size: number;\n}\n\nexport interface ApiAudio {\n id: string;\n size: number;\n mimeType: string;\n fileName: string;\n duration: number;\n performer?: string;\n title?: string;\n thumbnailSizes?: ApiPhotoSize[];\n}\n\nexport interface ApiVoice {\n id: string;\n duration: number;\n waveform?: number[];\n}\n\nexport interface ApiDocument {\n id?: string;\n fileName: string;\n size: number;\n timestamp?: number;\n mimeType: string;\n thumbnail?: ApiThumbnail;\n previewBlobUrl?: string;\n mediaType?: 'photo' | 'video';\n mediaSize?: ApiDimensions;\n}\n\nexport interface ApiContact {\n firstName: string;\n lastName: string;\n phoneNumber: string;\n userId: string;\n}\n\nexport interface ApiPollAnswer {\n text: string;\n option: string;\n}\n\nexport interface ApiPollResult {\n isChosen?: true;\n isCorrect?: true;\n option: string;\n votersCount: number;\n}\n\nexport interface ApiPoll {\n id: string;\n summary: {\n closed?: true;\n isPublic?: true;\n multipleChoice?: true;\n quiz?: true;\n question: string;\n answers: ApiPollAnswer[];\n closePeriod?: number;\n closeDate?: number;\n };\n results: {\n results?: ApiPollResult[];\n totalVoters?: number;\n recentVoterIds?: string[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n}\n\nexport interface ApiInvoice {\n text: string;\n title: string;\n photoUrl?: string;\n amount: number;\n currency: string;\n receiptMsgId?: number;\n isTest?: boolean;\n}\n\nexport type ApiNewPoll = {\n summary: ApiPoll['summary'];\n quiz?: {\n correctAnswers: string[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n};\n\nexport interface ApiAction {\n text: string;\n targetUserIds?: string[];\n targetChatId?: string;\n type: 'historyClear' | 'contactSignUp' | 'chatCreate' | 'other';\n photo?: ApiPhoto;\n amount?: number;\n currency?: string;\n translationValues: string[];\n call?: Partial;\n}\n\nexport interface ApiWebPage {\n id: number;\n url: string;\n displayUrl: string;\n type?: string;\n siteName?: string;\n title?: string;\n description?: string;\n photo?: ApiPhoto;\n duration?: number;\n document?: ApiDocument;\n video?: ApiVideo;\n}\n\nexport interface ApiMessageForwardInfo {\n date: number;\n isChannelPost: boolean;\n channelPostId?: number;\n isLinkedChannelPost?: boolean;\n fromChatId?: string;\n senderUserId?: string;\n fromMessageId?: number;\n hiddenUserName?: string;\n adminTitle?: string;\n}\n\nexport interface ApiMessageEntity {\n type: string;\n offset: number;\n length: number;\n userId?: string;\n url?: string;\n}\n\nexport enum ApiMessageEntityTypes {\n Bold = 'MessageEntityBold',\n Blockquote = 'MessageEntityBlockquote',\n BotCommand = 'MessageEntityBotCommand',\n Cashtag = 'MessageEntityCashtag',\n Code = 'MessageEntityCode',\n Email = 'MessageEntityEmail',\n Hashtag = 'MessageEntityHashtag',\n Italic = 'MessageEntityItalic',\n MentionName = 'MessageEntityMentionName',\n Mention = 'MessageEntityMention',\n Phone = 'MessageEntityPhone',\n Pre = 'MessageEntityPre',\n Strike = 'MessageEntityStrike',\n TextUrl = 'MessageEntityTextUrl',\n Url = 'MessageEntityUrl',\n Underline = 'MessageEntityUnderline',\n Unknown = 'MessageEntityUnknown',\n}\n\nexport interface ApiFormattedText {\n text: string;\n entities?: ApiMessageEntity[];\n}\n\nexport interface ApiMessage {\n id: number;\n chatId: string;\n content: {\n text?: ApiFormattedText;\n photo?: ApiPhoto;\n video?: ApiVideo;\n document?: ApiDocument;\n sticker?: ApiSticker;\n contact?: ApiContact;\n poll?: ApiPoll;\n action?: ApiAction;\n webPage?: ApiWebPage;\n audio?: ApiAudio;\n voice?: ApiVoice;\n invoice?: ApiInvoice;\n };\n date: number;\n isOutgoing: boolean;\n senderId?: string;\n replyToChatId?: string;\n replyToMessageId?: number;\n replyToTopMessageId?: number;\n sendingState?: 'messageSendingStatePending' | 'messageSendingStateFailed';\n forwardInfo?: ApiMessageForwardInfo;\n isDeleting?: boolean;\n previousLocalId?: number;\n views?: number;\n isEdited?: boolean;\n editDate?: number;\n isMentioned?: boolean;\n isMediaUnread?: boolean;\n groupedId?: string;\n isInAlbum?: boolean;\n hasUnreadMention?: boolean;\n inlineButtons?: ApiKeyboardButtons;\n keyboardButtons?: ApiKeyboardButtons;\n keyboardPlaceholder?: string;\n isKeyboardSingleUse?: boolean;\n viaBotId?: string;\n threadInfo?: ApiThreadInfo;\n adminTitle?: string;\n isScheduled?: boolean;\n shouldHideKeyboardButtons?: boolean;\n isFromScheduled?: boolean;\n seenByUserIds?: string[];\n isProtected?: boolean;\n}\n\nexport interface ApiThreadInfo {\n threadId: number;\n chatId: string;\n topMessageId?: number;\n originChannelId?: string;\n messagesCount: number;\n lastMessageId?: number;\n lastReadInboxMessageId?: number;\n recentReplierIds?: string[];\n}\n\nexport type ApiMessageOutgoingStatus = 'read' | 'succeeded' | 'pending' | 'failed';\n\nexport type ApiSponsoredMessage = {\n chatId?: string;\n randomId: string;\n isBot?: boolean;\n channelPostId?: number;\n startParam?: string;\n chatInviteHash?: string;\n chatInviteTitle?: string;\n text: ApiFormattedText;\n expiresAt: number;\n};\n\nexport interface ApiKeyboardButton {\n type: 'command' | 'url' | 'callback' | 'requestPoll' | 'requestSelfContact' | 'buy' | 'NOT_SUPPORTED';\n text: string;\n messageId: number;\n value?: string;\n}\n\nexport type ApiKeyboardButtons = ApiKeyboardButton[][];\nexport type ApiReplyKeyboard = {\n keyboardPlaceholder?: string;\n isKeyboardSingleUse?: boolean;\n} & {\n [K in 'inlineButtons' | 'keyboardButtons']?: ApiKeyboardButtons;\n};\n\nexport type ApiMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'voice' | 'profilePhoto';\nexport type ApiGlobalMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'voice';\n\nexport type ApiReportReason = 'spam' | 'violence' | 'pornography' | 'childAbuse'\n| 'copyright' | 'geoIrrelevant' | 'fake' | 'other';\n\nexport type ApiSendMessageAction = {\n type: 'cancel' | 'typing' | 'recordAudio' | 'chooseSticker';\n};\n\nexport const MAIN_THREAD_ID = -1;\n\n// `Symbol` can not be transferred from worker\nexport const MESSAGE_DELETED = 'MESSAGE_DELETED';\n","// We cache avatars as Data URI for faster initial load\n// and messages media as Blob for smaller size.\n\nexport enum ApiMediaFormat {\n BlobUrl,\n Lottie,\n Progressive,\n Stream,\n}\n\nexport type ApiParsedMedia = string | Blob | AnyLiteral | ArrayBuffer;\nexport type ApiPreparedMedia = string | AnyLiteral;\nexport type ApiMediaFormatToPrepared = T extends ApiMediaFormat.Lottie ? AnyLiteral : string;\n","import BigInt from 'big-integer';\n\nimport { Api as GramJs } from '../../../lib/gramjs';\n\nexport function isPeerUser(peer: GramJs.TypePeer | GramJs.TypeInputPeer): peer is GramJs.PeerUser {\n return peer.hasOwnProperty('userId');\n}\n\nexport function isPeerChat(peer: GramJs.TypePeer | GramJs.TypeInputPeer): peer is GramJs.PeerChat {\n return peer.hasOwnProperty('chatId');\n}\n\nexport function isPeerChannel(peer: GramJs.TypePeer | GramJs.TypeInputPeer): peer is GramJs.PeerChannel {\n return peer.hasOwnProperty('channelId');\n}\n\nexport function buildApiPeerId(id: BigInt.BigInteger, type: 'user' | 'chat' | 'channel') {\n return type === 'user' ? String(id) : `-${id}`;\n}\n\nexport function getApiChatIdFromMtpPeer(peer: GramJs.TypePeer | GramJs.TypeInputPeer) {\n if (isPeerUser(peer)) {\n return buildApiPeerId(peer.userId, 'user');\n } else if (isPeerChat(peer)) {\n return buildApiPeerId(peer.chatId, 'chat');\n } else {\n return buildApiPeerId((peer as GramJs.InputPeerChannel).channelId, 'channel');\n }\n}\n","import { Api as GramJs } from '../../lib/gramjs';\nimport localDb from './localDb';\nimport { buildApiPeerId, getApiChatIdFromMtpPeer } from './apiBuilders/peers';\n\nexport function resolveMessageApiChatId(mtpMessage: GramJs.TypeMessage) {\n if (!(mtpMessage instanceof GramJs.Message || mtpMessage instanceof GramJs.MessageService)) {\n return undefined;\n }\n\n return getApiChatIdFromMtpPeer(mtpMessage.peerId);\n}\n\nexport function addMessageToLocalDb(message: GramJs.Message | GramJs.MessageService) {\n const messageFullId = `${resolveMessageApiChatId(message)}-${message.id}`;\n localDb.messages[messageFullId] = message;\n\n if (\n message instanceof GramJs.Message\n && message.media instanceof GramJs.MessageMediaDocument\n && message.media.document instanceof GramJs.Document\n ) {\n localDb.documents[String(message.media.document.id)] = message.media.document;\n }\n\n if (\n message instanceof GramJs.Message\n && message.media instanceof GramJs.MessageMediaWebPage\n && message.media.webpage instanceof GramJs.WebPage\n && message.media.webpage.document instanceof GramJs.Document\n ) {\n localDb.documents[String(message.media.webpage.document.id)] = message.media.webpage.document;\n }\n\n if (message instanceof GramJs.MessageService && 'photo' in message.action) {\n addPhotoToLocalDb(message.action.photo);\n }\n}\n\nexport function addPhotoToLocalDb(photo: GramJs.TypePhoto) {\n if (photo instanceof GramJs.Photo) {\n localDb.photos[String(photo.id)] = photo;\n }\n}\n\nfunction addChatToLocalDb(chat: GramJs.Chat | GramJs.Channel, noOverwrite = false) {\n const id = buildApiPeerId(chat.id, chat instanceof GramJs.Chat ? 'chat' : 'channel');\n if (!noOverwrite || !localDb.chats[id]) {\n localDb.chats[id] = chat;\n }\n}\n\nexport function addUserToLocalDb(user: GramJs.User, shouldOverwrite = false) {\n const id = buildApiPeerId(user.id, 'user');\n if (shouldOverwrite || !localDb.users[id]) {\n localDb.users[id] = user;\n }\n}\n\nexport function addEntitiesWithPhotosToLocalDb(entities: (GramJs.TypeUser | GramJs.TypeChat)[]) {\n entities.forEach((entity) => {\n if (entity instanceof GramJs.User && entity.photo) {\n addUserToLocalDb(entity);\n } else if ((entity instanceof GramJs.Chat || entity instanceof GramJs.Channel) && entity.photo) {\n addChatToLocalDb(entity);\n }\n });\n}\n\nexport function serializeBytes(value: Buffer) {\n return String.fromCharCode(...value);\n}\n\nexport function deserializeBytes(value: string) {\n return Buffer.from(value, 'binary');\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\n\nimport { ApiPrivacyKey } from '../../../types';\n\nimport { generateRandomBytes, readBigIntFromBuffer } from '../../../lib/gramjs/Helpers';\nimport {\n ApiChatAdminRights,\n ApiChatBannedRights,\n ApiChatFolder,\n ApiGroupCall,\n ApiMessageEntity,\n ApiMessageEntityTypes,\n ApiNewPoll,\n ApiReportReason,\n ApiSendMessageAction,\n ApiSticker,\n ApiVideo,\n} from '../../types';\nimport localDb from '../localDb';\nimport { pick } from '../../../util/iteratees';\nimport { deserializeBytes } from '../helpers';\n\nconst CHANNEL_ID_MIN_LENGTH = 11; // Example: -1000000000\n\nexport function getEntityTypeById(chatOrUserId: string) {\n if (typeof chatOrUserId === 'number') {\n return getEntityTypeByDeprecatedId(chatOrUserId);\n }\n\n if (!chatOrUserId.startsWith('-')) {\n return 'user';\n } else if (chatOrUserId.length >= CHANNEL_ID_MIN_LENGTH) {\n return 'channel';\n } else {\n return 'chat';\n }\n}\n\n// Workaround for old-fashioned IDs stored locally\nexport function getEntityTypeByDeprecatedId(chatOrUserId: number) {\n if (chatOrUserId > 0) {\n return 'user';\n } else if (chatOrUserId <= -1000000000) {\n return 'channel';\n } else {\n return 'chat';\n }\n}\n\nexport function buildPeer(chatOrUserId: string): GramJs.TypePeer {\n const type = getEntityTypeById(chatOrUserId);\n\n if (type === 'user') {\n return new GramJs.PeerUser({\n userId: buildMtpPeerId(chatOrUserId, 'user'),\n });\n } else if (type === 'channel') {\n return new GramJs.PeerChannel({\n channelId: buildMtpPeerId(chatOrUserId, 'channel'),\n });\n } else {\n return new GramJs.PeerChat({\n chatId: buildMtpPeerId(chatOrUserId, 'chat'),\n });\n }\n}\n\nexport function buildInputPeer(chatOrUserId: string, accessHash?: string): GramJs.TypeInputPeer {\n const type = getEntityTypeById(chatOrUserId);\n\n if (type === 'user') {\n return new GramJs.InputPeerUser({\n userId: buildMtpPeerId(chatOrUserId, 'user'),\n accessHash: BigInt(accessHash!),\n });\n } else if (type === 'channel') {\n return new GramJs.InputPeerChannel({\n channelId: buildMtpPeerId(chatOrUserId, 'channel'),\n accessHash: BigInt(accessHash!),\n });\n } else {\n return new GramJs.InputPeerChat({\n chatId: buildMtpPeerId(chatOrUserId, 'chat'),\n });\n }\n}\n\nexport function buildInputPeerFromLocalDb(chatOrUserId: string): GramJs.TypeInputPeer | undefined {\n const type = getEntityTypeById(chatOrUserId);\n let accessHash: BigInt.BigInteger | undefined;\n\n if (type === 'user') {\n accessHash = localDb.users[chatOrUserId]?.accessHash;\n if (!accessHash) {\n return undefined;\n }\n } else if (type === 'channel') {\n accessHash = (localDb.chats[chatOrUserId] as GramJs.Channel)?.accessHash;\n if (!accessHash) {\n return undefined;\n }\n }\n\n return buildInputPeer(chatOrUserId, String(accessHash));\n}\n\nexport function buildInputEntity(chatOrUserId: string, accessHash?: string) {\n const type = getEntityTypeById(chatOrUserId);\n\n if (type === 'user') {\n return new GramJs.InputUser({\n userId: buildMtpPeerId(chatOrUserId, 'user'),\n accessHash: BigInt(accessHash!),\n });\n } else if (type === 'channel') {\n return new GramJs.InputChannel({\n channelId: buildMtpPeerId(chatOrUserId, 'channel'),\n accessHash: BigInt(accessHash!),\n });\n } else {\n return buildMtpPeerId(chatOrUserId, 'chat');\n }\n}\n\nexport function buildInputStickerSet(id: string, accessHash: string) {\n return new GramJs.InputStickerSetID({\n id: BigInt(id),\n accessHash: BigInt(accessHash),\n });\n}\n\nexport function buildInputStickerSetShortName(shortName: string) {\n return new GramJs.InputStickerSetShortName({\n shortName,\n });\n}\n\nexport function buildInputDocument(media: ApiSticker | ApiVideo) {\n const document = localDb.documents[media.id];\n\n if (!document) {\n return undefined;\n }\n\n return new GramJs.InputDocument(pick(document, [\n 'id',\n 'accessHash',\n 'fileReference',\n ]));\n}\n\nexport function buildInputMediaDocument(media: ApiSticker | ApiVideo) {\n const inputDocument = buildInputDocument(media);\n\n if (!inputDocument) {\n return undefined;\n }\n\n return new GramJs.InputMediaDocument({ id: inputDocument });\n}\n\nexport function buildInputPoll(pollParams: ApiNewPoll, randomId: BigInt.BigInteger) {\n const { summary, quiz } = pollParams;\n\n const poll = new GramJs.Poll({\n id: randomId,\n publicVoters: summary.isPublic,\n question: summary.question,\n answers: summary.answers.map(({ text, option }) => {\n return new GramJs.PollAnswer({ text, option: deserializeBytes(option) });\n }),\n quiz: summary.quiz,\n multipleChoice: summary.multipleChoice,\n });\n\n if (!quiz) {\n return new GramJs.InputMediaPoll({ poll });\n }\n\n const correctAnswers = quiz.correctAnswers.map(deserializeBytes);\n const { solution } = quiz;\n const solutionEntities = quiz.solutionEntities ? quiz.solutionEntities.map(buildMtpMessageEntity) : [];\n\n return new GramJs.InputMediaPoll({\n poll,\n correctAnswers,\n ...(solution && {\n solution,\n solutionEntities,\n }),\n });\n}\n\nexport function buildFilterFromApiFolder(folder: ApiChatFolder): GramJs.DialogFilter {\n const {\n emoticon,\n contacts,\n nonContacts,\n groups,\n channels,\n bots,\n excludeArchived,\n excludeMuted,\n excludeRead,\n pinnedChatIds,\n includedChatIds,\n excludedChatIds,\n } = folder;\n\n const pinnedPeers = pinnedChatIds\n ? pinnedChatIds.map(buildInputPeerFromLocalDb).filter(Boolean as any)\n : [];\n\n const includePeers = includedChatIds\n ? includedChatIds.map(buildInputPeerFromLocalDb).filter(Boolean as any)\n : [];\n\n const excludePeers = excludedChatIds\n ? excludedChatIds.map(buildInputPeerFromLocalDb).filter(Boolean as any)\n : [];\n\n return new GramJs.DialogFilter({\n id: folder.id,\n title: folder.title,\n emoticon: emoticon || undefined,\n contacts: contacts || undefined,\n nonContacts: nonContacts || undefined,\n groups: groups || undefined,\n bots: bots || undefined,\n excludeArchived: excludeArchived || undefined,\n excludeMuted: excludeMuted || undefined,\n excludeRead: excludeRead || undefined,\n broadcasts: channels || undefined,\n pinnedPeers,\n includePeers,\n excludePeers,\n });\n}\n\nexport function generateRandomBigInt() {\n return readBigIntFromBuffer(generateRandomBytes(8), true, true);\n}\n\nexport function generateRandomInt() {\n return readBigIntFromBuffer(generateRandomBytes(4), true, true).toJSNumber();\n}\n\nexport function buildMessageFromUpdate(\n id: number,\n chatId: string,\n update: GramJs.UpdateShortSentMessage | GramJs.UpdateServiceNotification,\n) {\n // This is not a proper message, but we only need these fields for downloading media through `localDb`.\n return new GramJs.Message({\n id,\n peerId: buildPeer(chatId),\n fromId: buildPeer(chatId),\n media: update.media,\n } as GramJs.Message);\n}\n\nexport function buildMtpMessageEntity(entity: ApiMessageEntity): GramJs.TypeMessageEntity {\n const {\n type, offset, length, url, userId,\n } = entity;\n\n const user = userId ? localDb.users[userId] : undefined;\n\n switch (type) {\n case ApiMessageEntityTypes.Bold:\n return new GramJs.MessageEntityBold({ offset, length });\n case ApiMessageEntityTypes.Italic:\n return new GramJs.MessageEntityItalic({ offset, length });\n case ApiMessageEntityTypes.Underline:\n return new GramJs.MessageEntityUnderline({ offset, length });\n case ApiMessageEntityTypes.Strike:\n return new GramJs.MessageEntityStrike({ offset, length });\n case ApiMessageEntityTypes.Code:\n return new GramJs.MessageEntityCode({ offset, length });\n case ApiMessageEntityTypes.Pre:\n return new GramJs.MessageEntityPre({ offset, length, language: '' });\n case ApiMessageEntityTypes.Blockquote:\n return new GramJs.MessageEntityBlockquote({ offset, length });\n case ApiMessageEntityTypes.TextUrl:\n return new GramJs.MessageEntityTextUrl({ offset, length, url: url! });\n case ApiMessageEntityTypes.Url:\n return new GramJs.MessageEntityUrl({ offset, length });\n case ApiMessageEntityTypes.Hashtag:\n return new GramJs.MessageEntityHashtag({ offset, length });\n case ApiMessageEntityTypes.MentionName:\n return new GramJs.InputMessageEntityMentionName({\n offset,\n length,\n userId: new GramJs.InputUser({ userId: BigInt(userId!), accessHash: user!.accessHash! }),\n });\n default:\n return new GramJs.MessageEntityUnknown({ offset, length });\n }\n}\n\nexport function isMessageWithMedia(message: GramJs.Message | GramJs.UpdateServiceNotification) {\n const { media } = message;\n if (!media) {\n return false;\n }\n\n return (\n media instanceof GramJs.MessageMediaPhoto\n || media instanceof GramJs.MessageMediaDocument\n || (\n media instanceof GramJs.MessageMediaWebPage\n && media.webpage instanceof GramJs.WebPage\n && (\n media.webpage.photo instanceof GramJs.Photo || (\n media.webpage.document instanceof GramJs.Document\n && media.webpage.document.mimeType.startsWith('video')\n )\n )\n )\n );\n}\n\nexport function isServiceMessageWithMedia(message: GramJs.MessageService) {\n return 'photo' in message.action && message.action.photo instanceof GramJs.Photo;\n}\n\nexport function buildChatPhotoForLocalDb(photo: GramJs.TypePhoto) {\n if (photo instanceof GramJs.PhotoEmpty) {\n return new GramJs.ChatPhotoEmpty();\n }\n\n const { dcId, id: photoId } = photo;\n\n return new GramJs.ChatPhoto({\n dcId,\n photoId,\n });\n}\n\nexport function buildInputContact({\n phone,\n firstName,\n lastName,\n}: {\n phone: string;\n firstName: string;\n lastName: string;\n}) {\n return new GramJs.InputPhoneContact({\n clientId: BigInt(1),\n phone,\n firstName,\n lastName,\n });\n}\n\nexport function buildChatBannedRights(\n bannedRights: ApiChatBannedRights,\n untilDate = 0,\n) {\n return new GramJs.ChatBannedRights({\n ...bannedRights,\n untilDate,\n });\n}\n\nexport function buildChatAdminRights(\n adminRights: ApiChatAdminRights,\n) {\n return new GramJs.ChatAdminRights(adminRights);\n}\n\nexport function buildShippingInfo(info: GramJs.PaymentRequestedInfo) {\n const { shippingAddress } = info;\n return new GramJs.PaymentRequestedInfo({\n ...info,\n shippingAddress: shippingAddress\n ? new GramJs.PostAddress(shippingAddress)\n : undefined,\n });\n}\n\nexport function buildInputPrivacyKey(privacyKey: ApiPrivacyKey) {\n switch (privacyKey) {\n case 'phoneNumber':\n return new GramJs.InputPrivacyKeyPhoneNumber();\n\n case 'lastSeen':\n return new GramJs.InputPrivacyKeyStatusTimestamp();\n\n case 'profilePhoto':\n return new GramJs.InputPrivacyKeyProfilePhoto();\n\n case 'forwards':\n return new GramJs.InputPrivacyKeyForwards();\n\n case 'chatInvite':\n return new GramJs.InputPrivacyKeyChatInvite();\n }\n\n return undefined;\n}\n\nexport function buildInputReportReason(reason: ApiReportReason) {\n switch (reason) {\n case 'spam':\n return new GramJs.InputReportReasonSpam();\n case 'violence':\n return new GramJs.InputReportReasonViolence();\n case 'childAbuse':\n return new GramJs.InputReportReasonChildAbuse();\n case 'pornography':\n return new GramJs.InputReportReasonPornography();\n case 'copyright':\n return new GramJs.InputReportReasonCopyright();\n case 'fake':\n return new GramJs.InputReportReasonFake();\n case 'geoIrrelevant':\n return new GramJs.InputReportReasonGeoIrrelevant();\n case 'other':\n return new GramJs.InputReportReasonOther();\n }\n\n return undefined;\n}\n\nexport function buildSendMessageAction(action: ApiSendMessageAction) {\n switch (action.type) {\n case 'cancel':\n return new GramJs.SendMessageCancelAction();\n case 'typing':\n return new GramJs.SendMessageTypingAction();\n case 'recordAudio':\n return new GramJs.SendMessageRecordAudioAction();\n case 'chooseSticker':\n return new GramJs.SendMessageChooseStickerAction();\n }\n return undefined;\n}\n\nexport function buildMtpPeerId(id: string, type: 'user' | 'chat' | 'channel') {\n // Workaround for old-fashioned IDs stored locally\n if (typeof id === 'number') {\n return BigInt(Math.abs(id));\n }\n\n return type === 'user' ? BigInt(id) : BigInt(id.slice(1));\n}\n\nexport function buildInputGroupCall(groupCall: Partial) {\n return new GramJs.InputGroupCall({\n id: BigInt(groupCall.id!),\n accessHash: BigInt(groupCall.accessHash!),\n });\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n ApiMessage,\n ApiMessageForwardInfo,\n ApiPhoto,\n ApiSticker,\n ApiVideo,\n ApiVoice,\n ApiAudio,\n ApiDocument,\n ApiAction,\n ApiContact,\n ApiAttachment,\n ApiPoll,\n ApiNewPoll,\n ApiWebPage,\n ApiMessageEntity,\n ApiFormattedText,\n ApiReplyKeyboard,\n ApiKeyboardButton,\n ApiChat,\n ApiThreadInfo,\n ApiInvoice,\n ApiGroupCall,\n ApiUser,\n ApiSponsoredMessage,\n} from '../../types';\n\nimport {\n CONTENT_NOT_SUPPORTED,\n DELETED_COMMENTS_CHANNEL_ID,\n LOCAL_MESSAGE_ID_BASE,\n SERVICE_NOTIFICATIONS_USER_ID,\n SPONSORED_MESSAGE_CACHE_MS,\n SUPPORTED_IMAGE_CONTENT_TYPES,\n SUPPORTED_VIDEO_CONTENT_TYPES,\n VIDEO_MOV_TYPE,\n} from '../../../config';\nimport { pick } from '../../../util/iteratees';\nimport { buildStickerFromDocument } from './symbols';\nimport { buildApiPhoto, buildApiPhotoSize, buildApiThumbnailFromStripped } from './common';\nimport { interpolateArray } from '../../../util/waveform';\nimport { buildPeer } from '../gramjsBuilders';\nimport { addPhotoToLocalDb, resolveMessageApiChatId, serializeBytes } from '../helpers';\nimport { buildApiPeerId, getApiChatIdFromMtpPeer, isPeerUser } from './peers';\n\nconst LOCAL_MEDIA_UPLOADING_TEMP_ID = 'temp';\nconst INPUT_WAVEFORM_LENGTH = 63;\n\nlet localMessageCounter = LOCAL_MESSAGE_ID_BASE;\nlet currentUserId!: string;\n\nexport function setMessageBuilderCurrentUserId(_currentUserId: string) {\n currentUserId = _currentUserId;\n}\n\nexport function buildApiSponsoredMessage(mtpMessage: GramJs.SponsoredMessage): ApiSponsoredMessage | undefined {\n const {\n fromId, message, entities, startParam, channelPost, chatInvite, chatInviteHash, randomId,\n } = mtpMessage;\n const chatId = fromId ? getApiChatIdFromMtpPeer(fromId) : undefined;\n const chatInviteTitle = chatInvite\n ? (chatInvite instanceof GramJs.ChatInvite\n ? chatInvite.title\n : !(chatInvite.chat instanceof GramJs.ChatEmpty) ? chatInvite.chat.title : undefined)\n : undefined;\n\n return {\n randomId: serializeBytes(randomId),\n isBot: fromId ? isPeerUser(fromId) : false,\n text: buildMessageTextContent(message, entities),\n expiresAt: Math.round(Date.now() / 1000) + SPONSORED_MESSAGE_CACHE_MS,\n ...(chatId && { chatId }),\n ...(chatInviteHash && { chatInviteHash }),\n ...(chatInvite && { chatInviteTitle }),\n ...(startParam && { startParam }),\n ...(channelPost && { channelPostId: channelPost }),\n };\n}\n\nexport function buildApiMessage(mtpMessage: GramJs.TypeMessage): ApiMessage | undefined {\n const chatId = resolveMessageApiChatId(mtpMessage);\n if (\n !chatId\n || !(mtpMessage instanceof GramJs.Message || mtpMessage instanceof GramJs.MessageService)) {\n return undefined;\n }\n\n return buildApiMessageWithChatId(chatId, mtpMessage);\n}\n\nexport function buildApiMessageFromShort(mtpMessage: GramJs.UpdateShortMessage): ApiMessage {\n const chatId = buildApiPeerId(mtpMessage.userId, 'user');\n\n return buildApiMessageWithChatId(chatId, {\n ...mtpMessage,\n fromId: buildPeer(mtpMessage.out ? currentUserId : buildApiPeerId(mtpMessage.userId, 'user')),\n });\n}\n\nexport function buildApiMessageFromShortChat(mtpMessage: GramJs.UpdateShortChatMessage): ApiMessage {\n const chatId = buildApiPeerId(mtpMessage.chatId, 'chat');\n\n return buildApiMessageWithChatId(chatId, {\n ...mtpMessage,\n fromId: buildPeer(buildApiPeerId(mtpMessage.fromId, 'user')),\n });\n}\n\nexport function buildApiMessageFromNotification(\n notification: GramJs.UpdateServiceNotification,\n currentDate: number,\n): ApiMessage {\n const localId = localMessageCounter++;\n let content: ApiMessage['content'] = {};\n\n if (notification.media) {\n content = {\n ...buildMessageMediaContent(notification.media),\n };\n }\n\n if (notification.message && !content.sticker && !content.poll && !content.contact) {\n content = {\n ...content,\n text: buildMessageTextContent(notification.message, notification.entities),\n };\n }\n\n return {\n id: localId,\n chatId: SERVICE_NOTIFICATIONS_USER_ID,\n date: notification.inboxDate || currentDate,\n content,\n isOutgoing: false,\n };\n}\n\ntype UniversalMessage = (\n Pick\n & Pick, (\n 'out' | 'message' | 'entities' | 'fromId' | 'peerId' | 'fwdFrom' | 'replyTo' | 'replyMarkup' | 'post' |\n 'media' | 'action' | 'views' | 'editDate' | 'editHide' | 'mediaUnread' | 'groupedId' | 'mentioned' | 'viaBotId' |\n 'replies' | 'fromScheduled' | 'postAuthor' | 'noforwards'\n )>\n);\n\nexport function buildApiMessageWithChatId(chatId: string, mtpMessage: UniversalMessage): ApiMessage {\n const fromId = mtpMessage.fromId ? getApiChatIdFromMtpPeer(mtpMessage.fromId) : undefined;\n const peerId = mtpMessage.peerId ? getApiChatIdFromMtpPeer(mtpMessage.peerId) : undefined;\n const isChatWithSelf = !fromId && chatId === currentUserId;\n const isOutgoing = (mtpMessage.out && !mtpMessage.post) || (isChatWithSelf && !mtpMessage.fwdFrom);\n\n let content: ApiMessage['content'] = {};\n\n if (mtpMessage.media) {\n content = {\n ...buildMessageMediaContent(mtpMessage.media),\n };\n }\n\n if (mtpMessage.message && !content.sticker && !content.poll && !content.contact) {\n content = {\n ...content,\n text: buildMessageTextContent(mtpMessage.message, mtpMessage.entities),\n };\n }\n\n const action = mtpMessage.action\n && buildAction(mtpMessage.action, fromId, peerId, Boolean(mtpMessage.post), isOutgoing);\n if (action) {\n content.action = action;\n }\n\n const { replyToMsgId, replyToTopId, replyToPeerId } = mtpMessage.replyTo || {};\n const isEdited = mtpMessage.editDate && !mtpMessage.editHide;\n const {\n inlineButtons, keyboardButtons, keyboardPlaceholder, isKeyboardSingleUse,\n } = buildReplyButtons(mtpMessage) || {};\n const forwardInfo = mtpMessage.fwdFrom && buildApiMessageForwardInfo(mtpMessage.fwdFrom, isChatWithSelf);\n const { replies, mediaUnread: isMediaUnread, postAuthor } = mtpMessage;\n const groupedId = mtpMessage.groupedId && String(mtpMessage.groupedId);\n const isInAlbum = Boolean(groupedId) && !(content.document || content.audio);\n const shouldHideKeyboardButtons = mtpMessage.replyMarkup instanceof GramJs.ReplyKeyboardHide;\n\n return {\n id: mtpMessage.id,\n chatId,\n isOutgoing,\n content,\n date: mtpMessage.date,\n senderId: fromId || (mtpMessage.out && mtpMessage.post && currentUserId) || chatId,\n views: mtpMessage.views,\n isFromScheduled: mtpMessage.fromScheduled,\n ...(replyToMsgId && { replyToMessageId: replyToMsgId }),\n ...(replyToPeerId && { replyToChatId: getApiChatIdFromMtpPeer(replyToPeerId) }),\n ...(replyToTopId && { replyToTopMessageId: replyToTopId }),\n ...(forwardInfo && { forwardInfo }),\n ...(isEdited && { isEdited, editDate: mtpMessage.editDate }),\n ...(isMediaUnread && { isMediaUnread }),\n ...(mtpMessage.mentioned && isMediaUnread && { hasUnreadMention: true }),\n ...(mtpMessage.mentioned && { isMentioned: true }),\n ...(groupedId && {\n groupedId,\n isInAlbum,\n }),\n inlineButtons,\n ...(keyboardButtons && { keyboardButtons, keyboardPlaceholder, isKeyboardSingleUse }),\n ...(shouldHideKeyboardButtons && { shouldHideKeyboardButtons }),\n ...(mtpMessage.viaBotId && { viaBotId: buildApiPeerId(mtpMessage.viaBotId, 'user') }),\n ...(replies?.comments && { threadInfo: buildThreadInfo(replies, mtpMessage.id, chatId) }),\n ...(postAuthor && { adminTitle: postAuthor }),\n ...(mtpMessage.noforwards && { isProtected: true }),\n };\n}\n\nexport function buildMessageTextContent(\n message: string,\n entities?: GramJs.TypeMessageEntity[],\n): ApiFormattedText {\n if (entities?.some((e) => e instanceof GramJs.MessageEntitySpoiler)) {\n return {\n text: CONTENT_NOT_SUPPORTED,\n };\n }\n\n return {\n text: message,\n ...(entities && { entities: entities.map(buildApiMessageEntity) }),\n };\n}\n\nexport function buildMessageDraft(draft: GramJs.TypeDraftMessage) {\n if (draft instanceof GramJs.DraftMessageEmpty) {\n return undefined;\n }\n\n const {\n message, entities, replyToMsgId, date,\n } = draft;\n\n return {\n formattedText: message ? buildMessageTextContent(message, entities) : undefined,\n replyingToId: replyToMsgId,\n date,\n };\n}\n\nexport function buildMessageMediaContent(media: GramJs.TypeMessageMedia): ApiMessage['content'] | undefined {\n if ('ttlSeconds' in media && media.ttlSeconds) {\n return undefined;\n }\n\n const sticker = buildSticker(media);\n if (sticker) return { sticker };\n\n const photo = buildPhoto(media);\n if (photo) return { photo };\n\n const video = buildVideo(media);\n if (video) return { video };\n\n const audio = buildAudio(media);\n if (audio) return { audio };\n\n const voice = buildVoice(media);\n if (voice) return { voice };\n\n const document = buildDocumentFromMedia(media);\n if (document) return { document };\n\n const contact = buildContact(media);\n if (contact) return { contact };\n\n const poll = buildPollFromMedia(media);\n if (poll) return { poll };\n\n const webPage = buildWebPage(media);\n if (webPage) return { webPage };\n\n const invoice = buildInvoiceFromMedia(media);\n if (invoice) return { invoice };\n\n return undefined;\n}\n\nfunction buildApiMessageForwardInfo(fwdFrom: GramJs.MessageFwdHeader, isChatWithSelf = false): ApiMessageForwardInfo {\n const savedFromPeerId = fwdFrom.savedFromPeer && getApiChatIdFromMtpPeer(fwdFrom.savedFromPeer);\n const fromId = fwdFrom.fromId && getApiChatIdFromMtpPeer(fwdFrom.fromId);\n\n return {\n date: fwdFrom.date,\n isChannelPost: Boolean(fwdFrom.channelPost),\n channelPostId: fwdFrom.channelPost,\n isLinkedChannelPost: Boolean(fwdFrom.channelPost && savedFromPeerId && !isChatWithSelf),\n fromChatId: savedFromPeerId || fromId,\n fromMessageId: fwdFrom.channelPost || fwdFrom.savedFromMsgId,\n senderUserId: fromId,\n hiddenUserName: fwdFrom.fromName,\n adminTitle: fwdFrom.postAuthor,\n };\n}\n\nfunction buildSticker(media: GramJs.TypeMessageMedia): ApiSticker | undefined {\n if (\n !(media instanceof GramJs.MessageMediaDocument)\n || !media.document\n || !(media.document instanceof GramJs.Document)\n ) {\n return undefined;\n }\n\n return buildStickerFromDocument(media.document);\n}\n\nfunction buildPhoto(media: GramJs.TypeMessageMedia): ApiPhoto | undefined {\n if (!(media instanceof GramJs.MessageMediaPhoto) || !media.photo || !(media.photo instanceof GramJs.Photo)) {\n return undefined;\n }\n\n return buildApiPhoto(media.photo);\n}\n\nexport function buildVideoFromDocument(document: GramJs.Document): ApiVideo | undefined {\n if (document instanceof GramJs.DocumentEmpty) {\n return undefined;\n }\n\n const {\n id, mimeType, thumbs, size, attributes,\n } = document;\n\n // eslint-disable-next-line no-restricted-globals\n if (mimeType === VIDEO_MOV_TYPE && !(self as any).isMovSupported) {\n return undefined;\n }\n\n const videoAttr = attributes\n .find((a: any): a is GramJs.DocumentAttributeVideo => a instanceof GramJs.DocumentAttributeVideo);\n\n if (!videoAttr) {\n return undefined;\n }\n\n const gifAttr = attributes\n .find((a: any): a is GramJs.DocumentAttributeAnimated => a instanceof GramJs.DocumentAttributeAnimated);\n\n const {\n duration,\n w: width,\n h: height,\n supportsStreaming = false,\n roundMessage: isRound = false,\n } = videoAttr;\n\n return {\n id: String(id),\n mimeType,\n duration,\n fileName: getFilenameFromDocument(document, 'video'),\n width,\n height,\n supportsStreaming,\n isRound,\n isGif: Boolean(gifAttr),\n thumbnail: buildApiThumbnailFromStripped(thumbs),\n size,\n };\n}\n\nfunction buildVideo(media: GramJs.TypeMessageMedia): ApiVideo | undefined {\n if (\n !(media instanceof GramJs.MessageMediaDocument)\n || !(media.document instanceof GramJs.Document)\n || !media.document.mimeType.startsWith('video')\n ) {\n return undefined;\n }\n\n return buildVideoFromDocument(media.document);\n}\n\nfunction buildAudio(media: GramJs.TypeMessageMedia): ApiAudio | undefined {\n if (\n !(media instanceof GramJs.MessageMediaDocument)\n || !media.document\n || !(media.document instanceof GramJs.Document)\n ) {\n return undefined;\n }\n\n const audioAttribute = media.document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeAudio => (\n attr instanceof GramJs.DocumentAttributeAudio\n ));\n\n if (!audioAttribute || audioAttribute.voice) {\n return undefined;\n }\n\n const thumbnailSizes = media.document.thumbs && media.document.thumbs\n .filter((thumb): thumb is GramJs.PhotoSize => thumb instanceof GramJs.PhotoSize)\n .map((thumb) => buildApiPhotoSize(thumb));\n\n return {\n id: String(media.document.id),\n fileName: getFilenameFromDocument(media.document, 'audio'),\n thumbnailSizes,\n ...pick(media.document, ['size', 'mimeType']),\n ...pick(audioAttribute, ['duration', 'performer', 'title']),\n };\n}\n\nfunction buildVoice(media: GramJs.TypeMessageMedia): ApiVoice | undefined {\n if (\n !(media instanceof GramJs.MessageMediaDocument)\n || !media.document\n || !(media.document instanceof GramJs.Document)\n ) {\n return undefined;\n }\n\n const audioAttribute = media.document.attributes\n .find((attr: any): attr is GramJs.DocumentAttributeAudio => (\n attr instanceof GramJs.DocumentAttributeAudio\n ));\n\n if (!audioAttribute || !audioAttribute.voice) {\n return undefined;\n }\n\n const { duration, waveform } = audioAttribute;\n\n return {\n id: String(media.document.id),\n duration,\n waveform: waveform ? Array.from(waveform) : undefined,\n };\n}\n\nfunction buildDocumentFromMedia(media: GramJs.TypeMessageMedia) {\n if (!(media instanceof GramJs.MessageMediaDocument) || !media.document) {\n return undefined;\n }\n\n return buildApiDocument(media.document);\n}\n\nexport function buildApiDocument(document: GramJs.TypeDocument): ApiDocument | undefined {\n if (!(document instanceof GramJs.Document)) {\n return undefined;\n }\n\n const {\n id, size, mimeType, date, thumbs, attributes,\n } = document;\n\n const thumbnail = thumbs && buildApiThumbnailFromStripped(thumbs);\n\n let mediaType: ApiDocument['mediaType'] | undefined;\n let mediaSize: ApiDocument['mediaSize'] | undefined;\n const photoSize = thumbs && thumbs.find((s: any): s is GramJs.PhotoSize => s instanceof GramJs.PhotoSize);\n if (photoSize) {\n mediaSize = {\n width: photoSize.w,\n height: photoSize.h,\n };\n\n if (SUPPORTED_IMAGE_CONTENT_TYPES.has(mimeType)) {\n mediaType = 'photo';\n\n const imageAttribute = attributes\n .find((a: any): a is GramJs.DocumentAttributeImageSize => a instanceof GramJs.DocumentAttributeImageSize);\n\n if (imageAttribute) {\n const { w: width, h: height } = imageAttribute;\n mediaSize = {\n width,\n height,\n };\n }\n } else if (SUPPORTED_VIDEO_CONTENT_TYPES.has(mimeType)) {\n mediaType = 'video';\n }\n }\n\n return {\n id: String(id),\n size,\n mimeType,\n timestamp: date,\n fileName: getFilenameFromDocument(document),\n thumbnail,\n mediaType,\n mediaSize,\n };\n}\n\nfunction buildContact(media: GramJs.TypeMessageMedia): ApiContact | undefined {\n if (!(media instanceof GramJs.MessageMediaContact)) {\n return undefined;\n }\n\n const {\n firstName, lastName, phoneNumber, userId,\n } = media;\n\n return {\n firstName, lastName, phoneNumber, userId: buildApiPeerId(userId, 'user'),\n };\n}\n\nfunction buildPollFromMedia(media: GramJs.TypeMessageMedia): ApiPoll | undefined {\n if (!(media instanceof GramJs.MessageMediaPoll)) {\n return undefined;\n }\n\n return buildPoll(media.poll, media.results);\n}\n\nfunction buildInvoiceFromMedia(media: GramJs.TypeMessageMedia): ApiInvoice | undefined {\n if (!(media instanceof GramJs.MessageMediaInvoice)) {\n return undefined;\n }\n\n return buildInvoice(media);\n}\n\nexport function buildPoll(poll: GramJs.Poll, pollResults: GramJs.PollResults): ApiPoll {\n const { id, answers: rawAnswers } = poll;\n const answers = rawAnswers.map((answer) => ({\n text: answer.text,\n option: serializeBytes(answer.option),\n }));\n\n return {\n id: String(id),\n summary: {\n isPublic: poll.publicVoters,\n ...pick(poll, [\n 'closed',\n 'multipleChoice',\n 'quiz',\n 'question',\n 'closePeriod',\n 'closeDate',\n ]),\n answers,\n },\n results: buildPollResults(pollResults),\n };\n}\n\nexport function buildInvoice(media: GramJs.MessageMediaInvoice): ApiInvoice {\n const {\n description: text, title, photo, test, totalAmount, currency, receiptMsgId,\n } = media;\n\n return {\n text,\n title,\n photoUrl: photo?.url,\n receiptMsgId,\n amount: Number(totalAmount),\n currency,\n isTest: test,\n };\n}\n\nexport function buildPollResults(pollResults: GramJs.PollResults): ApiPoll['results'] {\n const {\n results: rawResults, totalVoters, recentVoters, solution, solutionEntities: entities,\n } = pollResults;\n const results = rawResults && rawResults.map(({\n option, chosen, correct, voters,\n }) => ({\n isChosen: chosen,\n isCorrect: correct,\n option: serializeBytes(option),\n votersCount: voters,\n }));\n\n return {\n totalVoters,\n recentVoterIds: recentVoters?.map((id) => buildApiPeerId(id, 'user')),\n results,\n solution,\n ...(entities && { solutionEntities: entities.map(buildApiMessageEntity) }),\n };\n}\n\nexport function buildWebPage(media: GramJs.TypeMessageMedia): ApiWebPage | undefined {\n if (\n !(media instanceof GramJs.MessageMediaWebPage)\n || !(media.webpage instanceof GramJs.WebPage)\n ) {\n return undefined;\n }\n\n const { id, photo, document } = media.webpage;\n\n let video;\n if (document instanceof GramJs.Document && document.mimeType.startsWith('video/')) {\n video = buildVideoFromDocument(document);\n }\n\n return {\n id: Number(id),\n ...pick(media.webpage, [\n 'url',\n 'displayUrl',\n 'type',\n 'siteName',\n 'title',\n 'description',\n 'duration',\n ]),\n photo: photo instanceof GramJs.Photo ? buildApiPhoto(photo) : undefined,\n document: !video && document ? buildApiDocument(document) : undefined,\n video,\n };\n}\n\nfunction buildAction(\n action: GramJs.TypeMessageAction,\n senderId: string | undefined,\n targetPeerId: string | undefined,\n isChannelPost: boolean,\n isOutgoing: boolean,\n): ApiAction | undefined {\n if (action instanceof GramJs.MessageActionEmpty) {\n return undefined;\n }\n\n let call: Partial | undefined;\n let amount: number | undefined;\n let currency: string | undefined;\n let text: string;\n const translationValues = [];\n let type: ApiAction['type'] = 'other';\n let photo: ApiPhoto | undefined;\n\n const targetUserIds = 'users' in action\n ? action.users && action.users.map((id) => buildApiPeerId(id, 'user'))\n : ('userId' in action && [buildApiPeerId(action.userId, 'user')]) || [];\n let targetChatId: string | undefined;\n\n if (action instanceof GramJs.MessageActionChatCreate) {\n text = 'Notification.CreatedChatWithTitle';\n translationValues.push('%action_origin%', action.title);\n type = 'chatCreate';\n } else if (action instanceof GramJs.MessageActionChatEditTitle) {\n if (isChannelPost) {\n text = 'Channel.MessageTitleUpdated';\n translationValues.push(action.title);\n } else {\n text = 'Notification.ChangedGroupName';\n translationValues.push('%action_origin%', action.title);\n }\n } else if (action instanceof GramJs.MessageActionChatEditPhoto) {\n if (isChannelPost) {\n text = 'Channel.MessagePhotoUpdated';\n } else {\n text = 'Notification.ChangedGroupPhoto';\n translationValues.push('%action_origin%');\n }\n } else if (action instanceof GramJs.MessageActionChatDeletePhoto) {\n if (isChannelPost) {\n text = 'Channel.MessagePhotoRemoved';\n } else {\n text = 'Group.MessagePhotoRemoved';\n }\n } else if (action instanceof GramJs.MessageActionChatAddUser) {\n if (!senderId || targetUserIds.includes(senderId)) {\n text = 'Notification.JoinedChat';\n translationValues.push('%target_user%');\n } else {\n text = 'Notification.Invited';\n translationValues.push('%action_origin%', '%target_user%');\n }\n } else if (action instanceof GramJs.MessageActionChatDeleteUser) {\n if (!senderId || targetUserIds.includes(senderId)) {\n text = 'Notification.LeftChat';\n translationValues.push('%target_user%');\n } else {\n text = 'Notification.Kicked';\n translationValues.push('%action_origin%', '%target_user%');\n }\n } else if (action instanceof GramJs.MessageActionChatJoinedByLink) {\n text = 'Notification.JoinedGroupByLink';\n translationValues.push('%action_origin%');\n } else if (action instanceof GramJs.MessageActionChannelCreate) {\n text = 'Notification.CreatedChannel';\n } else if (action instanceof GramJs.MessageActionChatMigrateTo) {\n targetChatId = getApiChatIdFromMtpPeer(action);\n text = 'Migrated to %target_chat%';\n translationValues.push('%target_chat%');\n } else if (action instanceof GramJs.MessageActionChannelMigrateFrom) {\n targetChatId = getApiChatIdFromMtpPeer(action);\n text = 'Migrated from %target_chat%';\n translationValues.push('%target_chat%');\n } else if (action instanceof GramJs.MessageActionPinMessage) {\n text = 'Chat.Service.Group.UpdatedPinnedMessage1';\n translationValues.push('%action_origin%', '%message%');\n } else if (action instanceof GramJs.MessageActionHistoryClear) {\n text = 'HistoryCleared';\n type = 'historyClear';\n } else if (action instanceof GramJs.MessageActionPhoneCall) {\n const withDuration = Boolean(action.duration);\n text = [\n withDuration ? 'ChatList.Service' : 'Chat',\n action.video ? 'VideoCall' : 'Call',\n isOutgoing ? (withDuration ? 'outgoing' : 'Outgoing') : (withDuration ? 'incoming' : 'Incoming'),\n ].join('.');\n\n if (withDuration) {\n const mins = Math.max(Math.round(action.duration! / 60), 1);\n translationValues.push(`${mins} min${mins > 1 ? 's' : ''}`);\n }\n } else if (action instanceof GramJs.MessageActionInviteToGroupCall) {\n text = 'Notification.VoiceChatInvitation';\n call = {\n id: action.call.id.toString(),\n accessHash: action.call.accessHash.toString(),\n };\n translationValues.push('%action_origin%', '%target_user%');\n } else if (action instanceof GramJs.MessageActionContactSignUp) {\n text = 'Notification.Joined';\n translationValues.push('%action_origin%');\n type = 'contactSignUp';\n } else if (action instanceof GramJs.MessageActionPaymentSent) {\n amount = Number(action.totalAmount);\n currency = action.currency;\n text = 'PaymentSuccessfullyPaid';\n if (targetPeerId) {\n targetUserIds.push(targetPeerId);\n }\n translationValues.push('%payment_amount%', '%target_user%', '%product%');\n } else if (action instanceof GramJs.MessageActionGroupCall) {\n if (action.duration) {\n const mins = Math.max(Math.round(action.duration / 60), 1);\n text = 'Notification.VoiceChatEnded';\n translationValues.push(`${mins} min${mins > 1 ? 's' : ''}`);\n } else {\n text = 'Notification.VoiceChatStartedChannel';\n call = {\n id: action.call.id.toString(),\n accessHash: action.call.accessHash.toString(),\n };\n }\n } else if (action instanceof GramJs.MessageActionBotAllowed) {\n text = 'Chat.Service.BotPermissionAllowed';\n translationValues.push(action.domain);\n } else if (action instanceof GramJs.MessageActionCustomAction) {\n text = action.message;\n } else if (action instanceof GramJs.MessageActionChatJoinedByRequest) {\n text = 'ChatService.UserJoinedGroupByRequest';\n translationValues.push('%action_origin%');\n } else {\n text = 'ChatList.UnsupportedMessage';\n }\n\n if ('photo' in action && action.photo instanceof GramJs.Photo) {\n addPhotoToLocalDb(action.photo);\n photo = buildApiPhoto(action.photo);\n }\n\n return {\n text,\n type,\n targetUserIds,\n targetChatId,\n photo, // TODO Only used internally now, will be used for the UI in future\n amount,\n currency,\n translationValues,\n call,\n };\n}\n\nfunction buildReplyButtons(message: UniversalMessage): ApiReplyKeyboard | undefined {\n const { id: messageId, replyMarkup, media } = message;\n\n if (!replyMarkup) {\n if (media instanceof GramJs.MessageMediaWebPage && media.webpage instanceof GramJs.WebPage) {\n if (media.webpage.type === 'telegram_message') {\n return {\n inlineButtons: [[{\n type: 'url' as const,\n text: 'Show Message',\n messageId,\n value: media.webpage.url,\n }]],\n };\n }\n }\n\n return undefined;\n }\n\n // TODO\n if (!(replyMarkup instanceof GramJs.ReplyKeyboardMarkup || replyMarkup instanceof GramJs.ReplyInlineMarkup)) {\n return undefined;\n }\n\n const markup = replyMarkup.rows.map(({ buttons }) => {\n return buttons.map((button) => {\n let { text } = button;\n\n let type;\n let value;\n if (button instanceof GramJs.KeyboardButton) {\n type = 'command';\n value = text;\n } else if (button instanceof GramJs.KeyboardButtonUrl) {\n type = 'url';\n value = button.url;\n } else if (button instanceof GramJs.KeyboardButtonCallback) {\n type = 'callback';\n value = serializeBytes(button.data);\n } else if (button instanceof GramJs.KeyboardButtonRequestPoll) {\n type = 'requestPoll';\n } else if (button instanceof GramJs.KeyboardButtonRequestPhone) {\n type = 'requestSelfContact';\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 contact?: ApiContact,\n groupedId?: string,\n scheduledAt?: number,\n sendAs?: ApiChat | ApiUser,\n serverTimeOffset = 0,\n): ApiMessage {\n const localId = localMessageCounter++;\n const media = attachment && buildUploadingMedia(attachment);\n const isChannel = chat.type === 'chatTypeChannel';\n\n return {\n id: localId,\n chatId: chat.id,\n content: {\n ...(text && {\n text: {\n text,\n entities,\n },\n }),\n ...media,\n ...(sticker && { sticker }),\n ...(gif && { video: gif }),\n ...(poll && buildNewPoll(poll, localId)),\n ...(contact && { contact }),\n },\n date: scheduledAt || Math.round(Date.now() / 1000) + serverTimeOffset,\n isOutgoing: !isChannel,\n senderId: sendAs?.id || currentUserId,\n ...(replyingTo && { replyToMessageId: replyingTo }),\n ...(groupedId && {\n groupedId,\n ...(media && (media.photo || media.video) && { isInAlbum: true }),\n }),\n ...(scheduledAt && { isScheduled: true }),\n };\n}\n\nexport function buildLocalForwardedMessage(\n toChat: ApiChat,\n message: ApiMessage,\n serverTimeOffset: number,\n scheduledAt?: number,\n): ApiMessage {\n const localId = localMessageCounter++;\n const {\n content,\n chatId: fromChatId,\n id: fromMessageId,\n senderId,\n groupedId,\n isInAlbum,\n } = message;\n\n const isAudio = content.audio;\n const asIncomingInChatWithSelf = (\n toChat.id === currentUserId && (fromChatId !== toChat.id || message.forwardInfo) && !isAudio\n );\n\n return {\n id: localId,\n chatId: toChat.id,\n content,\n date: scheduledAt || Math.round(Date.now() / 1000) + serverTimeOffset,\n isOutgoing: !asIncomingInChatWithSelf && toChat.type !== 'chatTypeChannel',\n senderId: currentUserId,\n sendingState: 'messageSendingStatePending',\n groupedId,\n isInAlbum,\n // Forward info doesn't get added when users forwards his own messages, also when forwarding audio\n ...(senderId !== currentUserId && !isAudio && {\n forwardInfo: {\n date: message.date,\n isChannelPost: false,\n fromChatId,\n fromMessageId,\n senderUserId: senderId,\n },\n }),\n ...(scheduledAt && { isScheduled: true }),\n };\n}\n\nfunction buildUploadingMedia(\n attachment: ApiAttachment,\n): ApiMessage['content'] {\n const {\n filename: fileName,\n blobUrl,\n previewBlobUrl,\n mimeType,\n size,\n } = attachment;\n\n if (attachment.quick) {\n const { width, height, duration } = attachment.quick;\n\n if (mimeType.startsWith('image/')) {\n return {\n photo: {\n id: LOCAL_MEDIA_UPLOADING_TEMP_ID,\n sizes: [],\n thumbnail: { width, height, dataUri: '' }, // Used only for dimensions\n blobUrl,\n },\n };\n } else {\n return {\n video: {\n id: LOCAL_MEDIA_UPLOADING_TEMP_ID,\n mimeType,\n duration: duration || 0,\n fileName,\n width,\n height,\n blobUrl,\n ...(previewBlobUrl && { thumbnail: { width, height, dataUri: previewBlobUrl } }),\n size,\n },\n };\n }\n } else if (attachment.voice) {\n const { duration, waveform } = attachment.voice;\n const { data: inputWaveform } = interpolateArray(waveform, INPUT_WAVEFORM_LENGTH);\n return {\n voice: {\n id: LOCAL_MEDIA_UPLOADING_TEMP_ID,\n duration,\n waveform: inputWaveform,\n },\n };\n } else if (mimeType.startsWith('audio/')) {\n return {\n audio: {\n id: LOCAL_MEDIA_UPLOADING_TEMP_ID,\n mimeType,\n fileName,\n size,\n duration: 200, // Arbitrary\n },\n };\n } else {\n return {\n document: {\n mimeType,\n fileName,\n size,\n ...(previewBlobUrl && { previewBlobUrl }),\n },\n };\n }\n}\n\nfunction buildNewPoll(poll: ApiNewPoll, localId: number) {\n return {\n poll: {\n id: String(localId),\n summary: pick(poll.summary, ['question', 'answers']),\n results: {},\n },\n };\n}\n\nfunction buildApiMessageEntity(entity: GramJs.TypeMessageEntity): ApiMessageEntity {\n const { className: type, offset, length } = entity;\n return {\n type,\n offset,\n length,\n ...(entity instanceof GramJs.MessageEntityMentionName && { userId: buildApiPeerId(entity.userId, 'user') }),\n ...('url' in entity && { url: entity.url }),\n };\n}\n\nfunction buildThreadInfo(\n messageReplies: GramJs.TypeMessageReplies, messageId: number, chatId: string,\n): ApiThreadInfo | undefined {\n const {\n channelId, replies, maxId, readMaxId, recentRepliers,\n } = messageReplies;\n if (!channelId) {\n return undefined;\n }\n\n const apiChannelId = buildApiPeerId(channelId, 'channel');\n if (apiChannelId === DELETED_COMMENTS_CHANNEL_ID) {\n return undefined;\n }\n\n const isPostThread = chatId !== apiChannelId;\n\n return {\n threadId: messageId,\n ...(isPostThread ? {\n chatId: apiChannelId,\n originChannelId: chatId,\n } : {\n chatId,\n }),\n messagesCount: replies,\n lastMessageId: maxId,\n lastReadInboxMessageId: readMaxId,\n ...(recentRepliers && { recentReplierIds: recentRepliers.map(getApiChatIdFromMtpPeer) }),\n };\n}\n","export const getServerTime = (serverTimeOffset: number) => {\n return Math.floor(Date.now() / 1000) + serverTimeOffset;\n};\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport {\n ApiChat,\n ApiChatAdminRights,\n ApiChatBannedRights,\n ApiBotCommand,\n ApiChatFolder,\n ApiChatMember,\n ApiRestrictionReason,\n} from '../../types';\nimport { pick, pickTruthy } from '../../../util/iteratees';\nimport {\n buildApiPeerId, getApiChatIdFromMtpPeer, isPeerChat, isPeerUser,\n} from './peers';\nimport { omitVirtualClassFields } from './helpers';\nimport { getServerTime } from '../../../util/serverTime';\n\ntype PeerEntityApiChatFields = Omit;\n\nfunction buildApiChatFieldsFromPeerEntity(\n peerEntity: GramJs.TypeUser | GramJs.TypeChat,\n isSupport = false,\n): PeerEntityApiChatFields {\n const isMin = Boolean('min' in peerEntity && peerEntity.min);\n const accessHash = ('accessHash' in peerEntity) && String(peerEntity.accessHash);\n const avatarHash = ('photo' in peerEntity) && peerEntity.photo && buildAvatarHash(peerEntity.photo);\n const isSignaturesShown = Boolean('signatures' in peerEntity && peerEntity.signatures);\n const hasPrivateLink = Boolean('hasLink' in peerEntity && peerEntity.hasLink);\n\n return {\n isMin,\n hasPrivateLink,\n isSignaturesShown,\n ...(accessHash && { accessHash }),\n ...(avatarHash && { avatarHash }),\n ...(\n (peerEntity instanceof GramJs.Channel || peerEntity instanceof GramJs.User)\n && { username: peerEntity.username }\n ),\n ...(('verified' in peerEntity) && { isVerified: peerEntity.verified }),\n ...(('callActive' in peerEntity) && { isCallActive: peerEntity.callActive }),\n ...(('callNotEmpty' in peerEntity) && { isCallNotEmpty: peerEntity.callNotEmpty }),\n ...((peerEntity instanceof GramJs.Chat || peerEntity instanceof GramJs.Channel) && {\n ...(peerEntity.participantsCount && { membersCount: peerEntity.participantsCount }),\n joinDate: peerEntity.date,\n }),\n ...((peerEntity instanceof GramJs.Chat || peerEntity instanceof GramJs.Channel) && {\n isProtected: Boolean('noforwards' in peerEntity && peerEntity.noforwards),\n }),\n ...(isSupport && { isSupport: true }),\n ...buildApiChatPermissions(peerEntity),\n ...(('creator' in peerEntity) && { isCreator: peerEntity.creator }),\n ...buildApiChatRestrictions(peerEntity),\n ...buildApiChatMigrationInfo(peerEntity),\n };\n}\n\nexport function buildApiChatFromDialog(\n dialog: GramJs.Dialog,\n peerEntity: GramJs.TypeUser | GramJs.TypeChat,\n serverTimeOffset: number,\n): ApiChat {\n const {\n peer, folderId, unreadMark, unreadCount, unreadMentionsCount, notifySettings: { silent, muteUntil },\n readOutboxMaxId, readInboxMaxId, draft,\n } = dialog;\n const isMuted = silent || (typeof muteUntil === 'number' && getServerTime(serverTimeOffset) < muteUntil);\n\n return {\n id: getApiChatIdFromMtpPeer(peer),\n ...(folderId && { folderId }),\n type: getApiChatTypeFromPeerEntity(peerEntity),\n title: getApiChatTitleFromMtpPeer(peer, peerEntity),\n lastReadOutboxMessageId: readOutboxMaxId,\n lastReadInboxMessageId: readInboxMaxId,\n unreadCount,\n unreadMentionsCount,\n isMuted,\n ...(unreadMark && { hasUnreadMark: true }),\n ...(draft instanceof GramJs.DraftMessage && { draftDate: draft.date }),\n ...buildApiChatFieldsFromPeerEntity(peerEntity),\n };\n}\n\nfunction buildApiChatPermissions(peerEntity: GramJs.TypeUser | GramJs.TypeChat): {\n adminRights?: ApiChatAdminRights;\n currentUserBannedRights?: ApiChatBannedRights;\n defaultBannedRights?: ApiChatBannedRights;\n} {\n if (!(peerEntity instanceof GramJs.Chat || peerEntity instanceof GramJs.Channel)) {\n return {};\n }\n\n return {\n adminRights: peerEntity.adminRights ? omitVirtualClassFields(peerEntity.adminRights) : undefined,\n currentUserBannedRights: peerEntity instanceof GramJs.Channel && peerEntity.bannedRights\n ? omitVirtualClassFields(peerEntity.bannedRights)\n : undefined,\n defaultBannedRights: peerEntity.defaultBannedRights\n ? omitVirtualClassFields(peerEntity.defaultBannedRights)\n : undefined,\n };\n}\n\nfunction buildApiChatRestrictions(peerEntity: GramJs.TypeUser | GramJs.TypeChat): {\n isNotJoined?: boolean;\n isRestricted?: boolean;\n restrictionReason?: ApiRestrictionReason;\n} {\n if (peerEntity instanceof GramJs.ChatForbidden || peerEntity instanceof GramJs.ChannelForbidden) {\n return {\n isRestricted: true,\n };\n }\n\n const restrictions = {};\n\n if ('restricted' in peerEntity) {\n const restrictionReason = peerEntity.restricted\n ? buildApiChatRestrictionReason(peerEntity.restrictionReason)\n : undefined;\n\n if (restrictionReason) {\n Object.assign(restrictions, {\n isRestricted: true,\n restrictionReason,\n });\n }\n }\n\n if (peerEntity instanceof GramJs.Chat) {\n Object.assign(restrictions, {\n isNotJoined: peerEntity.left,\n isRestricted: peerEntity.kicked,\n });\n }\n\n if (peerEntity instanceof GramJs.Channel) {\n Object.assign(restrictions, {\n // `left` is weirdly set to `true` on all channels never joined before\n isNotJoined: peerEntity.left,\n });\n }\n\n return restrictions;\n}\n\nfunction buildApiChatMigrationInfo(peerEntity: GramJs.TypeChat): {\n migratedTo?: {\n chatId: string;\n accessHash?: string;\n };\n} {\n if (\n peerEntity instanceof GramJs.Chat\n && peerEntity.migratedTo\n && !(peerEntity.migratedTo instanceof GramJs.InputChannelEmpty)\n ) {\n return {\n migratedTo: {\n chatId: getApiChatIdFromMtpPeer(peerEntity.migratedTo),\n ...(peerEntity.migratedTo instanceof GramJs.InputChannel && {\n accessHash: String(peerEntity.migratedTo.accessHash),\n }),\n },\n };\n }\n\n return {};\n}\n\nfunction buildApiChatRestrictionReason(\n restrictionReasons?: GramJs.RestrictionReason[],\n): ApiRestrictionReason | undefined {\n if (!restrictionReasons) {\n return undefined;\n }\n\n const targetReason = restrictionReasons.find(({ platform }) => platform === 'all');\n return targetReason ? pick(targetReason, ['reason', 'text']) : undefined;\n}\n\nexport function buildApiChatFromPreview(\n preview: GramJs.TypeChat | GramJs.TypeUser,\n isSupport = false,\n withForbidden = false,\n): ApiChat | undefined {\n if (!(\n preview instanceof GramJs.Chat\n || preview instanceof GramJs.Channel\n || preview instanceof GramJs.User\n || (\n withForbidden\n && (\n preview instanceof GramJs.ChatForbidden\n || preview instanceof GramJs.ChannelForbidden\n )\n )\n )) {\n return undefined;\n }\n\n return {\n id: buildApiPeerId(preview.id, preview instanceof GramJs.User ? 'user' : 'chat'),\n type: getApiChatTypeFromPeerEntity(preview),\n title: preview instanceof GramJs.User ? getUserName(preview) : preview.title,\n ...buildApiChatFieldsFromPeerEntity(preview, isSupport),\n };\n}\n\nexport function getApiChatTypeFromPeerEntity(peerEntity: GramJs.TypeChat | GramJs.TypeUser) {\n if (peerEntity instanceof GramJs.User || peerEntity instanceof GramJs.UserEmpty) {\n return 'chatTypePrivate';\n } else if (\n peerEntity instanceof GramJs.Chat\n || peerEntity instanceof GramJs.ChatForbidden\n || peerEntity instanceof GramJs.ChatEmpty\n ) {\n return 'chatTypeBasicGroup';\n } else {\n return peerEntity.megagroup ? 'chatTypeSuperGroup' : 'chatTypeChannel';\n }\n}\n\nexport function getPeerKey(peer: GramJs.TypePeer) {\n if (isPeerUser(peer)) {\n return `user${peer.userId}`;\n } else if (isPeerChat(peer)) {\n return `chat${peer.chatId}`;\n } else {\n return `chat${peer.channelId}`;\n }\n}\n\nexport function getApiChatTitleFromMtpPeer(peer: GramJs.TypePeer, peerEntity: GramJs.User | GramJs.Chat) {\n if (isPeerUser(peer)) {\n return getUserName(peerEntity as GramJs.User);\n } else {\n return (peerEntity as GramJs.Chat).title;\n }\n}\n\nfunction getUserName(user: GramJs.User) {\n return user.firstName\n ? `${user.firstName}${user.lastName ? ` ${user.lastName}` : ''}`\n : (user.lastName || undefined);\n}\n\nexport function buildAvatarHash(photo: GramJs.TypeUserProfilePhoto | GramJs.TypeChatPhoto) {\n if ('photoId' in photo) {\n return String(photo.photoId);\n }\n\n return undefined;\n}\n\nexport function buildChatMember(\n member: GramJs.TypeChatParticipant | GramJs.TypeChannelParticipant,\n): ApiChatMember | undefined {\n const userId = (member instanceof GramJs.ChannelParticipantBanned || member instanceof GramJs.ChannelParticipantLeft)\n ? getApiChatIdFromMtpPeer(member.peer)\n : buildApiPeerId(member.userId, 'user');\n\n return {\n userId,\n inviterId: 'inviterId' in member ? buildApiPeerId(member.inviterId as BigInt.BigInteger, 'user') : undefined,\n joinedDate: 'date' in member ? member.date : undefined,\n kickedByUserId: 'kickedBy' in member ? buildApiPeerId(member.kickedBy, 'user') : undefined,\n promotedByUserId: 'promotedBy' in member ? buildApiPeerId(member.promotedBy, 'user') : undefined,\n bannedRights: 'bannedRights' in member ? omitVirtualClassFields(member.bannedRights) : undefined,\n adminRights: 'adminRights' in member ? omitVirtualClassFields(member.adminRights) : undefined,\n customTitle: 'rank' in member ? member.rank : undefined,\n ...((member instanceof GramJs.ChannelParticipantAdmin || member instanceof GramJs.ChatParticipantAdmin) && {\n isAdmin: true,\n }),\n ...((member instanceof GramJs.ChannelParticipantCreator || member instanceof GramJs.ChatParticipantCreator) && {\n isOwner: true,\n }),\n };\n}\n\nexport function buildChatMembers(\n participants: GramJs.TypeChatParticipants | GramJs.channels.ChannelParticipants,\n) {\n // Duplicate code because of TS union-type shenanigans\n if (participants instanceof GramJs.ChatParticipants) {\n return participants.participants.map(buildChatMember).filter(Boolean as any);\n }\n if (participants instanceof GramJs.channels.ChannelParticipants) {\n return participants.participants.map(buildChatMember).filter(Boolean as any);\n }\n\n return undefined;\n}\n\nexport function buildChatTypingStatus(\n update: GramJs.UpdateUserTyping | GramJs.UpdateChatUserTyping | GramJs.UpdateChannelUserTyping,\n serverTimeOffset: number,\n) {\n let action: string = '';\n if (update.action instanceof GramJs.SendMessageCancelAction) {\n return undefined;\n } else if (update.action instanceof GramJs.SendMessageTypingAction) {\n action = 'lng_user_typing';\n } else if (update.action instanceof GramJs.SendMessageRecordVideoAction) {\n action = 'lng_send_action_record_video';\n } else if (update.action instanceof GramJs.SendMessageUploadVideoAction) {\n action = 'lng_send_action_upload_video';\n } else if (update.action instanceof GramJs.SendMessageRecordAudioAction) {\n action = 'lng_send_action_record_audio';\n } else if (update.action instanceof GramJs.SendMessageUploadAudioAction) {\n action = 'lng_send_action_upload_audio';\n } else if (update.action instanceof GramJs.SendMessageUploadPhotoAction) {\n action = 'lng_send_action_upload_photo';\n } else if (update.action instanceof GramJs.SendMessageUploadDocumentAction) {\n action = 'lng_send_action_upload_file';\n } else if (update.action instanceof GramJs.SendMessageGeoLocationAction) {\n action = 'selecting a location to share';\n } else if (update.action instanceof GramJs.SendMessageChooseContactAction) {\n action = 'selecting a contact to share';\n } else if (update.action instanceof GramJs.SendMessageGamePlayAction) {\n action = 'lng_playing_game';\n } else if (update.action instanceof GramJs.SendMessageRecordRoundAction) {\n action = 'lng_send_action_record_round';\n } else if (update.action instanceof GramJs.SendMessageUploadRoundAction) {\n action = 'lng_send_action_upload_round';\n } else if (update.action instanceof GramJs.SendMessageChooseStickerAction) {\n action = 'lng_send_action_choose_sticker';\n } else if (update.action instanceof GramJs.SpeakingInGroupCallAction) {\n return undefined;\n }\n\n return {\n action,\n ...(!(update instanceof GramJs.UpdateUserTyping) && { userId: getApiChatIdFromMtpPeer(update.fromId) }),\n timestamp: Date.now() + serverTimeOffset * 1000,\n };\n}\n\nexport function buildApiChatFolder(filter: GramJs.DialogFilter): ApiChatFolder {\n return {\n ...pickTruthy(filter, [\n 'id', 'title', 'emoticon', 'contacts', 'nonContacts', 'groups', 'bots',\n 'excludeMuted', 'excludeRead', 'excludeArchived',\n ]),\n channels: filter.broadcasts,\n pinnedChatIds: filter.pinnedPeers.map(getApiChatIdFromMtpPeer).filter(Boolean as any),\n includedChatIds: filter.includePeers.map(getApiChatIdFromMtpPeer).filter(Boolean as any),\n excludedChatIds: filter.excludePeers.map(getApiChatIdFromMtpPeer).filter(Boolean as any),\n };\n}\n\nexport function buildApiChatFolderFromSuggested({\n filter, description,\n}: {\n filter: GramJs.DialogFilter;\n description: string;\n}): ApiChatFolder {\n return {\n ...buildApiChatFolder(filter),\n description,\n };\n}\n\nexport function buildApiChatBotCommands(botInfos: GramJs.BotInfo[]) {\n return botInfos.reduce((botCommands, botInfo) => {\n const botId = buildApiPeerId(botInfo.userId, 'user');\n\n botCommands = botCommands.concat(botInfo.commands.map((mtpCommand) => ({\n botId,\n ...omitVirtualClassFields(mtpCommand),\n })));\n\n return botCommands;\n }, [] as ApiBotCommand[]);\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n ApiBotCommand, ApiUser, ApiUserStatus, ApiUserType,\n} from '../../types';\nimport { buildApiPeerId } from './peers';\n\nexport function buildApiUserFromFull(mtpUserFull: GramJs.users.UserFull): ApiUser {\n const {\n fullUser: {\n about, commonChatsCount, pinnedMsgId, botInfo, blocked,\n },\n users,\n } = mtpUserFull;\n\n const user = buildApiUser(users[0])!;\n\n return {\n ...user,\n fullInfo: {\n bio: about,\n commonChatsCount,\n pinnedMessageId: pinnedMsgId,\n isBlocked: Boolean(blocked),\n ...(botInfo && { botDescription: botInfo.description }),\n ...(botInfo && botInfo.commands.length && { botCommands: buildApiBotCommands(user.id, botInfo) }),\n },\n };\n}\n\nexport function buildApiUser(mtpUser: GramJs.TypeUser): ApiUser | undefined {\n if (!(mtpUser instanceof GramJs.User)) {\n return undefined;\n }\n\n const { id, firstName, lastName } = mtpUser;\n const avatarHash = mtpUser.photo instanceof GramJs.UserProfilePhoto\n ? String(mtpUser.photo.photoId)\n : undefined;\n const userType = buildApiUserType(mtpUser);\n\n return {\n id: buildApiPeerId(id, 'user'),\n isMin: Boolean(mtpUser.min),\n ...(mtpUser.self && { isSelf: true }),\n ...(mtpUser.verified && { isVerified: true }),\n ...((mtpUser.contact || mtpUser.mutualContact) && { isContact: true }),\n type: userType,\n ...(firstName && { firstName }),\n ...(userType === 'userTypeBot' && { canBeInvitedToGroup: !mtpUser.botNochats }),\n ...(lastName && { lastName }),\n username: mtpUser.username || '',\n phoneNumber: mtpUser.phone || '',\n noStatus: !mtpUser.status,\n ...(mtpUser.accessHash && { accessHash: String(mtpUser.accessHash) }),\n ...(avatarHash && { avatarHash }),\n ...(mtpUser.bot && mtpUser.botInlinePlaceholder && { botPlaceholder: mtpUser.botInlinePlaceholder }),\n };\n}\n\nfunction buildApiUserType(user: GramJs.User): ApiUserType {\n if (user.bot) {\n return 'userTypeBot';\n }\n if (user.deleted) {\n return 'userTypeDeleted';\n }\n\n return 'userTypeRegular';\n}\n\nexport function buildApiUserStatus(mtpStatus?: GramJs.TypeUserStatus): ApiUserStatus {\n if (!mtpStatus || mtpStatus instanceof GramJs.UserStatusEmpty) {\n return { type: 'userStatusEmpty' };\n } else if (mtpStatus instanceof GramJs.UserStatusOnline) {\n return { type: 'userStatusOnline', expires: mtpStatus.expires };\n } else if (mtpStatus instanceof GramJs.UserStatusOffline) {\n return { type: 'userStatusOffline', wasOnline: mtpStatus.wasOnline };\n } else if (mtpStatus instanceof GramJs.UserStatusRecently) {\n return { type: 'userStatusRecently' };\n } else if (mtpStatus instanceof GramJs.UserStatusLastWeek) {\n return { type: 'userStatusLastWeek' };\n } else {\n return { type: 'userStatusLastMonth' };\n }\n}\n\nfunction buildApiBotCommands(botId: string, botInfo: GramJs.BotInfo) {\n return botInfo.commands.map(({ command, description }) => ({\n botId,\n command,\n description,\n })) as ApiBotCommand[];\n}\n\nexport function buildApiUsersAndStatuses(mtpUsers: GramJs.TypeUser[]) {\n const userStatusesById: Record = {};\n const users: ApiUser[] = [];\n\n mtpUsers.forEach((mtpUser) => {\n const user = buildApiUser(mtpUser);\n if (!user) {\n return;\n }\n\n users.push(user);\n\n if ('status' in mtpUser) {\n userStatusesById[user.id] = buildApiUserStatus(mtpUser.status);\n }\n });\n\n return { users, userStatusesById };\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\n\nimport { ApiCountry, ApiSession, ApiWallpaper } from '../../types';\nimport { ApiPrivacySettings, ApiPrivacyKey, PrivacyVisibility } from '../../../types';\n\nimport { buildApiDocument } from './messages';\nimport { buildApiPeerId, getApiChatIdFromMtpPeer } from './peers';\nimport { flatten, pick } from '../../../util/iteratees';\nimport { getServerTime } from '../../../util/serverTime';\n\nexport function buildApiWallpaper(wallpaper: GramJs.TypeWallPaper): ApiWallpaper | undefined {\n if (wallpaper instanceof GramJs.WallPaperNoFile) {\n // TODO: Plain color wallpapers\n return undefined;\n }\n\n const { slug } = wallpaper;\n\n const document = buildApiDocument(wallpaper.document);\n\n if (!document) {\n return undefined;\n }\n\n return {\n slug,\n document,\n };\n}\n\nexport function buildApiSession(session: GramJs.Authorization): ApiSession {\n return {\n isCurrent: Boolean(session.current),\n isOfficialApp: Boolean(session.officialApp),\n isPasswordPending: Boolean(session.passwordPending),\n hash: String(session.hash),\n ...pick(session, [\n 'deviceModel', 'platform', 'systemVersion', 'appName', 'appVersion', 'dateCreated', 'dateActive',\n 'ip', 'country', 'region',\n ]),\n };\n}\n\nexport function buildPrivacyKey(key: GramJs.TypePrivacyKey): ApiPrivacyKey | undefined {\n switch (key.className) {\n case 'PrivacyKeyPhoneNumber':\n return 'phoneNumber';\n case 'PrivacyKeyStatusTimestamp':\n return 'lastSeen';\n case 'PrivacyKeyProfilePhoto':\n return 'profilePhoto';\n case 'PrivacyKeyForwards':\n return 'forwards';\n case 'PrivacyKeyChatInvite':\n return 'chatInvite';\n }\n\n return undefined;\n}\n\nexport function buildPrivacyRules(rules: GramJs.TypePrivacyRule[]): ApiPrivacySettings {\n let visibility: PrivacyVisibility | undefined;\n let allowUserIds: string[] | undefined;\n let allowChatIds: string[] | undefined;\n let blockUserIds: string[] | undefined;\n let blockChatIds: string[] | undefined;\n\n rules.forEach((rule) => {\n if (rule instanceof GramJs.PrivacyValueAllowAll) {\n visibility = visibility || 'everybody';\n } else if (rule instanceof GramJs.PrivacyValueAllowContacts) {\n visibility = visibility || 'contacts';\n } else if (rule instanceof GramJs.PrivacyValueDisallowContacts) {\n visibility = visibility || 'nonContacts';\n } else if (rule instanceof GramJs.PrivacyValueDisallowAll) {\n visibility = visibility || 'nobody';\n } else if (rule instanceof GramJs.PrivacyValueAllowUsers) {\n allowUserIds = rule.users.map((chatId) => buildApiPeerId(chatId, 'user'));\n } else if (rule instanceof GramJs.PrivacyValueDisallowUsers) {\n blockUserIds = rule.users.map((chatId) => buildApiPeerId(chatId, 'user'));\n } else if (rule instanceof GramJs.PrivacyValueAllowChatParticipants) {\n allowChatIds = rule.chats.map((chatId) => buildApiPeerId(chatId, 'chat'));\n } else if (rule instanceof GramJs.PrivacyValueDisallowChatParticipants) {\n blockChatIds = rule.chats.map((chatId) => buildApiPeerId(chatId, 'chat'));\n }\n });\n\n if (!visibility) {\n // disallow by default.\n visibility = 'nobody';\n }\n\n return {\n visibility,\n allowUserIds: allowUserIds || [],\n allowChatIds: allowChatIds || [],\n blockUserIds: blockUserIds || [],\n blockChatIds: blockChatIds || [],\n };\n}\n\nexport function buildApiNotifyException(\n notifySettings: GramJs.TypePeerNotifySettings, peer: GramJs.TypePeer, serverTimeOffset: number,\n) {\n const {\n silent, muteUntil, showPreviews, sound,\n } = notifySettings;\n\n return {\n chatId: getApiChatIdFromMtpPeer(peer),\n isMuted: silent || (typeof muteUntil === 'number' && getServerTime(serverTimeOffset) < muteUntil),\n ...(sound === '' && { isSilent: true }),\n ...(showPreviews !== undefined && { shouldShowPreviews: Boolean(showPreviews) }),\n };\n}\n\nfunction buildApiCountry(country: GramJs.help.Country, code?: GramJs.help.CountryCode) {\n const {\n hidden, iso2, defaultName, name,\n } = country;\n const { countryCode, prefixes, patterns } = code || {};\n\n return {\n isHidden: hidden,\n iso2,\n defaultName,\n name,\n countryCode,\n prefixes,\n patterns,\n };\n}\n\nexport function buildApiCountryList(countries: GramJs.help.Country[]) {\n const listByCode = flatten(\n countries\n .filter((country) => !country.hidden)\n .map((country) => (\n country.countryCodes.map((code) => buildApiCountry(country, code))\n )),\n )\n .sort((a: ApiCountry, b: ApiCountry) => (\n a.name ? a.name.localeCompare(b.name!) : a.defaultName.localeCompare(b.defaultName)\n ));\n\n const generalList = countries\n .filter((country) => !country.hidden)\n .map((country) => buildApiCountry(country))\n .sort((a, b) => (\n a.name ? a.name.localeCompare(b.name!) : a.defaultName.localeCompare(b.defaultName)\n ));\n\n return {\n phoneCodes: listByCode,\n general: generalList,\n };\n}\n","import { GroupCallParticipant, GroupCallParticipantVideo, SsrcGroup } from '../../../lib/secret-sauce';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport { ApiGroupCall } from '../../types';\nimport { getApiChatIdFromMtpPeer, isPeerUser } from './peers';\n\nexport function buildApiGroupCallParticipant(participant: GramJs.GroupCallParticipant): GroupCallParticipant {\n const {\n self, min, about, date, versioned, canSelfUnmute, justJoined, left, muted, mutedByYou, source, volume,\n volumeByAdmin, videoJoined, peer, video, presentation, raiseHandRating,\n } = participant;\n\n return {\n isSelf: self,\n isMin: min,\n canSelfUnmute,\n isLeft: left,\n isMuted: muted,\n isMutedByMe: mutedByYou,\n hasJustJoined: justJoined,\n isVolumeByAdmin: volumeByAdmin,\n isVersioned: versioned,\n isVideoJoined: videoJoined,\n about,\n source,\n raiseHandRating: raiseHandRating?.toString(),\n volume,\n date: new Date(date),\n isUser: isPeerUser(peer),\n id: getApiChatIdFromMtpPeer(peer),\n video: video ? buildApiGroupCallParticipantVideo(video) : undefined,\n presentation: presentation ? buildApiGroupCallParticipantVideo(presentation) : undefined,\n };\n}\n\nfunction buildApiGroupCallParticipantVideo(\n participantVideo: GramJs.GroupCallParticipantVideo,\n): GroupCallParticipantVideo {\n const {\n audioSource, endpoint, paused, sourceGroups,\n } = participantVideo;\n return {\n audioSource,\n endpoint,\n isPaused: paused,\n sourceGroups: sourceGroups.map(buildApiGroupCallParticipantVideoSourceGroup),\n };\n}\n\nfunction buildApiGroupCallParticipantVideoSourceGroup(\n participantVideoSourceGroup: GramJs.GroupCallParticipantVideoSourceGroup,\n): SsrcGroup {\n return {\n semantics: participantVideoSourceGroup.semantics,\n sources: participantVideoSourceGroup.sources,\n };\n}\n\nexport function buildApiGroupCall(groupCall: GramJs.TypeGroupCall): ApiGroupCall {\n const {\n id, accessHash,\n } = groupCall;\n\n if (groupCall instanceof GramJs.GroupCallDiscarded) {\n return {\n connectionState: 'discarded',\n id: id.toString(),\n accessHash: accessHash.toString(),\n participantsCount: 0,\n version: 0,\n participants: {},\n };\n }\n\n const {\n version, participantsCount, streamDcId, scheduleDate, canChangeJoinMuted, joinMuted, canStartVideo,\n scheduleStartSubscribed,\n } = groupCall;\n\n return {\n connectionState: 'disconnected',\n isLoaded: true,\n id: id.toString(),\n accessHash: accessHash.toString(),\n version,\n participantsCount,\n streamDcId,\n scheduleDate,\n canChangeJoinMuted,\n joinMuted,\n canStartVideo,\n scheduleStartSubscribed,\n participants: {},\n };\n}\n\nexport function getGroupCallId(groupCall: GramJs.TypeInputGroupCall) {\n return groupCall.id.toString();\n}\n","import { GroupCallConnectionData } from '../../lib/secret-sauce';\nimport { Api as GramJs, connection } from '../../lib/gramjs';\nimport { ApiMessage, ApiUpdateConnectionStateType, OnApiUpdate } from '../types';\n\nimport { pick } from '../../util/iteratees';\nimport {\n buildApiMessage,\n buildApiMessageFromShort,\n buildApiMessageFromShortChat,\n buildMessageMediaContent,\n buildMessageTextContent,\n buildPoll,\n buildPollResults,\n buildApiMessageFromNotification,\n buildMessageDraft,\n} from './apiBuilders/messages';\nimport {\n buildChatMember,\n buildChatMembers,\n buildChatTypingStatus,\n buildAvatarHash,\n buildApiChatFromPreview,\n buildApiChatFolder,\n} from './apiBuilders/chats';\nimport { buildApiUser, buildApiUserStatus } from './apiBuilders/users';\nimport {\n buildMessageFromUpdate,\n isMessageWithMedia,\n buildChatPhotoForLocalDb,\n} from './gramjsBuilders';\nimport localDb from './localDb';\nimport { omitVirtualClassFields } from './apiBuilders/helpers';\nimport { DEBUG } from '../../config';\nimport {\n addMessageToLocalDb,\n addEntitiesWithPhotosToLocalDb,\n addPhotoToLocalDb,\n resolveMessageApiChatId,\n serializeBytes,\n} from './helpers';\nimport { buildApiNotifyException, buildPrivacyKey, buildPrivacyRules } from './apiBuilders/misc';\nimport { buildApiPhoto } from './apiBuilders/common';\nimport {\n buildApiGroupCall,\n buildApiGroupCallParticipant,\n getGroupCallId,\n} from './apiBuilders/calls';\nimport { buildApiPeerId, getApiChatIdFromMtpPeer } from './apiBuilders/peers';\n\ntype Update = (\n (GramJs.TypeUpdate | GramJs.TypeUpdates) & { _entities?: (GramJs.TypeUser | GramJs.TypeChat)[] }\n) | typeof connection.UpdateConnectionState;\n\nconst DELETE_MISSING_CHANNEL_MESSAGE_DELAY = 1000;\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nconst sentMessageIds = new Set();\nlet serverTimeOffset = 0;\n// Workaround for a situation when an incorrect update comes with an undefined property `adminRights`\nlet shouldIgnoreNextChannelUpdate = false;\nconst IGNORE_NEXT_CHANNEL_UPDATE_TIMEOUT = 2000;\n\nfunction dispatchUserAndChatUpdates(entities: (GramJs.TypeUser | GramJs.TypeChat)[]) {\n entities\n .filter((e) => e instanceof GramJs.User)\n .map(buildApiUser)\n .forEach((user) => {\n if (!user) {\n return;\n }\n\n onUpdate({\n '@type': 'updateUser',\n id: user.id,\n user,\n });\n });\n\n entities\n .filter((e) => e instanceof GramJs.Chat || e instanceof GramJs.Channel)\n .map((e) => buildApiChatFromPreview(e))\n .forEach((chat) => {\n if (!chat) {\n return;\n }\n\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n });\n}\n\nexport function updater(update: Update, originRequest?: GramJs.AnyRequest) {\n if (update instanceof connection.UpdateServerTimeOffset) {\n serverTimeOffset = update.timeOffset;\n } else if (update instanceof connection.UpdateConnectionState) {\n let connectionState: ApiUpdateConnectionStateType;\n\n switch (update.state) {\n case connection.UpdateConnectionState.disconnected:\n connectionState = 'connectionStateConnecting';\n break;\n case connection.UpdateConnectionState.broken:\n connectionState = 'connectionStateBroken';\n break;\n case connection.UpdateConnectionState.connected:\n default:\n connectionState = 'connectionStateReady';\n break;\n }\n\n onUpdate({\n '@type': 'updateConnectionState',\n connectionState,\n });\n\n // Messages\n } else if (\n update instanceof GramJs.UpdateNewMessage\n || update instanceof GramJs.UpdateNewScheduledMessage\n || update instanceof GramJs.UpdateNewChannelMessage\n || update instanceof GramJs.UpdateShortChatMessage\n || update instanceof GramJs.UpdateShortMessage\n ) {\n let message: ApiMessage | undefined;\n let shouldForceReply: boolean | undefined;\n\n if (update instanceof GramJs.UpdateShortChatMessage) {\n message = buildApiMessageFromShortChat(update);\n } else if (update instanceof GramJs.UpdateShortMessage) {\n message = buildApiMessageFromShort(update);\n } else {\n // TODO Remove if proven not reproducing\n if (update.message instanceof GramJs.MessageEmpty) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected update:', update.className, update);\n }\n\n return;\n }\n\n if (update.message instanceof GramJs.Message && isMessageWithMedia(update.message)) {\n addMessageToLocalDb(update.message);\n }\n\n message = buildApiMessage(update.message)!;\n shouldForceReply = 'replyMarkup' in update.message\n && update.message?.replyMarkup instanceof GramJs.ReplyKeyboardForceReply\n && (!update.message.replyMarkup.selective || message.isMentioned);\n }\n\n // eslint-disable-next-line no-underscore-dangle\n const entities = update._entities;\n if (entities) {\n addEntitiesWithPhotosToLocalDb(entities);\n dispatchUserAndChatUpdates(entities);\n }\n\n if (update instanceof GramJs.UpdateNewScheduledMessage) {\n onUpdate({\n '@type': sentMessageIds.has(message.id) ? 'updateScheduledMessage' : 'newScheduledMessage',\n id: message.id,\n chatId: message.chatId,\n message,\n });\n } else {\n onUpdate({\n '@type': sentMessageIds.has(message.id) ? 'updateMessage' : 'newMessage',\n id: message.id,\n chatId: message.chatId,\n message,\n shouldForceReply,\n });\n }\n\n // Some updates to a Chat/Channel don't have a dedicated update class.\n // We can get info on some updates from Service Messages.\n if (update.message instanceof GramJs.MessageService) {\n const { action } = update.message;\n\n if (action instanceof GramJs.MessageActionChatEditTitle) {\n onUpdate({\n '@type': 'updateChat',\n id: message.chatId,\n chat: {\n title: action.title,\n },\n });\n } else if (action instanceof GramJs.MessageActionChatEditPhoto) {\n const photo = buildChatPhotoForLocalDb(action.photo);\n const avatarHash = buildAvatarHash(photo);\n\n const localDbChatId = resolveMessageApiChatId(update.message)!;\n if (localDb.chats[localDbChatId]) {\n localDb.chats[localDbChatId].photo = photo;\n }\n addPhotoToLocalDb(action.photo);\n\n if (avatarHash) {\n onUpdate({\n '@type': 'updateChat',\n id: message.chatId,\n chat: {\n avatarHash,\n },\n ...(action.photo instanceof GramJs.Photo && { newProfilePhoto: buildApiPhoto(action.photo) }),\n });\n }\n } else if (action instanceof GramJs.MessageActionChatDeletePhoto) {\n const localDbChatId = resolveMessageApiChatId(update.message)!;\n if (localDb.chats[localDbChatId]) {\n localDb.chats[localDbChatId].photo = new GramJs.ChatPhotoEmpty();\n }\n\n onUpdate({\n '@type': 'updateChat',\n id: message.chatId,\n chat: { avatarHash: undefined },\n });\n } else if (action instanceof GramJs.MessageActionChatDeleteUser) {\n // eslint-disable-next-line no-underscore-dangle\n if (update._entities && update._entities.some((e): e is GramJs.User => (\n e instanceof GramJs.User && !!e.self && e.id === action.userId\n ))) {\n onUpdate({\n '@type': 'updateChat',\n id: message.chatId,\n chat: {\n isRestricted: true,\n },\n });\n\n onUpdate({\n '@type': 'updateChatLeave',\n id: message.chatId,\n });\n }\n } else if (action instanceof GramJs.MessageActionChatAddUser) {\n // eslint-disable-next-line no-underscore-dangle\n if (update._entities && update._entities.some((e): e is GramJs.User => (\n e instanceof GramJs.User && !!e.self && action.users.includes(e.id)\n ))) {\n onUpdate({\n '@type': 'updateChatJoin',\n id: message.chatId,\n });\n }\n } else if (action instanceof GramJs.MessageActionGroupCall) {\n if (!action.duration && action.call) {\n onUpdate({\n '@type': 'updateGroupCallChatId',\n chatId: message.chatId,\n call: {\n id: action.call.id.toString(),\n accessHash: action.call.accessHash.toString(),\n },\n });\n }\n }\n }\n } else if (\n update instanceof GramJs.UpdateEditMessage\n || update instanceof GramJs.UpdateEditChannelMessage\n ) {\n // TODO Remove if proven not reproducing\n if (update.message instanceof GramJs.MessageEmpty) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected update:', update.className, update);\n }\n\n return;\n }\n\n if (update.message instanceof GramJs.Message && isMessageWithMedia(update.message)) {\n addMessageToLocalDb(update.message);\n }\n\n const message = buildApiMessage(update.message)!;\n\n onUpdate({\n '@type': 'updateMessage',\n id: message.id,\n chatId: message.chatId,\n message,\n });\n } else if (update instanceof GramJs.UpdateDeleteMessages) {\n onUpdate({\n '@type': 'deleteMessages',\n ids: update.messages,\n });\n } else if (update instanceof GramJs.UpdateDeleteScheduledMessages) {\n onUpdate({\n '@type': 'deleteScheduledMessages',\n ids: update.messages,\n chatId: getApiChatIdFromMtpPeer(update.peer),\n });\n } else if (update instanceof GramJs.UpdateDeleteChannelMessages) {\n const chatId = buildApiPeerId(update.channelId, 'channel');\n const ids = update.messages;\n const existingIds = ids.filter((id) => localDb.messages[`${chatId}-${id}`]);\n const missingIds = ids.filter((id) => !localDb.messages[`${chatId}-${id}`]);\n const profilePhotoIds = ids.map((id) => {\n const message = localDb.messages[`${chatId}-${id}`];\n\n return message && message instanceof GramJs.MessageService && 'photo' in message.action\n ? String(message.action.photo.id)\n : undefined;\n }).filter(Boolean as any);\n\n if (existingIds.length) {\n onUpdate({\n '@type': 'deleteMessages',\n ids: existingIds,\n chatId,\n });\n }\n\n if (profilePhotoIds.length) {\n onUpdate({\n '@type': 'deleteProfilePhotos',\n ids: profilePhotoIds,\n chatId,\n });\n }\n\n // For some reason delete message update sometimes comes before new message update\n if (missingIds.length) {\n setTimeout(() => {\n onUpdate({\n '@type': 'deleteMessages',\n ids: missingIds,\n chatId,\n });\n }, DELETE_MISSING_CHANNEL_MESSAGE_DELAY);\n }\n } else if (update instanceof GramJs.UpdateServiceNotification) {\n if (update.popup) {\n onUpdate({\n '@type': 'error',\n error: {\n message: update.message,\n },\n });\n } else {\n const currentDate = Date.now() / 1000 + serverTimeOffset;\n const message = buildApiMessageFromNotification(update, currentDate);\n\n if (isMessageWithMedia(update)) {\n addMessageToLocalDb(buildMessageFromUpdate(message.id, message.chatId, update));\n }\n\n onUpdate({\n '@type': 'updateServiceNotification',\n message,\n });\n }\n } else if ((\n originRequest instanceof GramJs.messages.SendMessage\n || originRequest instanceof GramJs.messages.SendMedia\n || originRequest instanceof GramJs.messages.SendMultiMedia\n || originRequest instanceof GramJs.messages.ForwardMessages\n ) && (\n update instanceof GramJs.UpdateMessageID\n || update instanceof GramJs.UpdateShortSentMessage\n )) {\n let randomId;\n if ('randomId' in update) {\n randomId = update.randomId;\n } else if ('randomId' in originRequest) {\n randomId = originRequest.randomId;\n }\n\n const localMessage = randomId && localDb.localMessages[String(randomId)];\n if (!localMessage) {\n throw new Error('Local message not found');\n }\n\n let newContent: ApiMessage['content'] | undefined;\n if (update instanceof GramJs.UpdateShortSentMessage) {\n if (localMessage.content.text && update.entities) {\n newContent = {\n text: buildMessageTextContent(localMessage.content.text.text, update.entities),\n };\n }\n if (update.media) {\n newContent = {\n ...newContent,\n ...buildMessageMediaContent(update.media),\n };\n }\n\n const mtpMessage = buildMessageFromUpdate(update.id, localMessage.chatId, update);\n if (isMessageWithMedia(mtpMessage)) {\n addMessageToLocalDb(mtpMessage);\n }\n }\n\n sentMessageIds.add(update.id);\n\n // Edge case for \"Send When Online\"\n const isAlreadySent = 'date' in update && update.date * 1000 < Date.now() + serverTimeOffset * 1000;\n\n onUpdate({\n '@type': localMessage.isScheduled && !isAlreadySent\n ? 'updateScheduledMessageSendSucceeded'\n : 'updateMessageSendSucceeded',\n chatId: localMessage.chatId,\n localId: localMessage.id,\n message: {\n ...localMessage,\n ...(newContent && {\n content: {\n ...localMessage.content,\n ...newContent,\n },\n }),\n id: update.id,\n sendingState: undefined,\n ...('date' in update && { date: update.date }),\n },\n });\n } else if (update instanceof GramJs.UpdateReadMessagesContents) {\n onUpdate({\n '@type': 'updateCommonBoxMessages',\n ids: update.messages,\n messageUpdate: {\n hasUnreadMention: false,\n isMediaUnread: false,\n },\n });\n } else if (update instanceof GramJs.UpdateChannelReadMessagesContents) {\n onUpdate({\n '@type': 'updateChannelMessages',\n channelId: buildApiPeerId(update.channelId, 'channel'),\n ids: update.messages,\n messageUpdate: {\n hasUnreadMention: false,\n isMediaUnread: false,\n },\n });\n } else if (update instanceof GramJs.UpdateMessagePoll) {\n const { pollId, poll, results } = update;\n if (poll) {\n const apiPoll = buildPoll(poll, results);\n\n onUpdate({\n '@type': 'updateMessagePoll',\n pollId: String(pollId),\n pollUpdate: apiPoll,\n });\n } else {\n const pollResults = buildPollResults(results);\n onUpdate({\n '@type': 'updateMessagePoll',\n pollId: String(pollId),\n pollUpdate: { results: pollResults },\n });\n }\n } else if (update instanceof GramJs.UpdateMessagePollVote) {\n onUpdate({\n '@type': 'updateMessagePollVote',\n pollId: String(update.pollId),\n userId: buildApiPeerId(update.userId, 'user'),\n options: update.options.map(serializeBytes),\n });\n } else if (update instanceof GramJs.UpdateChannelMessageViews) {\n onUpdate({\n '@type': 'updateMessage',\n chatId: buildApiPeerId(update.channelId, 'channel'),\n id: update.id,\n message: { views: update.views },\n });\n\n // Chats\n } else if (update instanceof GramJs.UpdateReadHistoryInbox) {\n onUpdate({\n '@type': 'updateChatInbox',\n id: getApiChatIdFromMtpPeer(update.peer),\n chat: {\n lastReadInboxMessageId: update.maxId,\n unreadCount: update.stillUnreadCount,\n },\n });\n } else if (update instanceof GramJs.UpdateReadHistoryOutbox) {\n onUpdate({\n '@type': 'updateChat',\n id: getApiChatIdFromMtpPeer(update.peer),\n chat: {\n lastReadOutboxMessageId: update.maxId,\n },\n });\n } else if (update instanceof GramJs.UpdateReadChannelInbox) {\n onUpdate({\n '@type': 'updateChat',\n id: buildApiPeerId(update.channelId, 'channel'),\n chat: {\n lastReadInboxMessageId: update.maxId,\n unreadCount: update.stillUnreadCount,\n },\n });\n } else if (update instanceof GramJs.UpdateReadChannelOutbox) {\n onUpdate({\n '@type': 'updateChat',\n id: buildApiPeerId(update.channelId, 'channel'),\n chat: {\n lastReadOutboxMessageId: update.maxId,\n },\n });\n } else if (\n update instanceof GramJs.UpdateDialogPinned\n && update.peer instanceof GramJs.DialogPeer\n ) {\n onUpdate({\n '@type': 'updateChatPinned',\n id: getApiChatIdFromMtpPeer(update.peer.peer),\n isPinned: update.pinned || false,\n });\n } else if (update instanceof GramJs.UpdatePinnedDialogs) {\n const ids = update.order\n ? update.order\n .filter((dp): dp is GramJs.DialogPeer => dp instanceof GramJs.DialogPeer)\n .map((dp) => getApiChatIdFromMtpPeer(dp.peer))\n : [];\n\n onUpdate({\n '@type': 'updatePinnedChatIds',\n ids,\n folderId: update.folderId || undefined,\n });\n } else if (update instanceof GramJs.UpdateFolderPeers) {\n update.folderPeers.forEach((folderPeer) => {\n const { folderId, peer } = folderPeer;\n\n onUpdate({\n '@type': 'updateChatListType',\n id: getApiChatIdFromMtpPeer(peer),\n folderId,\n });\n });\n } else if (update instanceof GramJs.UpdateDialogFilter) {\n const { id, filter } = update;\n const folder = filter ? buildApiChatFolder(filter) : undefined;\n\n onUpdate({\n '@type': 'updateChatFolder',\n id,\n folder,\n });\n } else if (update instanceof GramJs.UpdateDialogFilterOrder) {\n onUpdate({\n '@type': 'updateChatFoldersOrder',\n orderedIds: update.order,\n });\n } else if (update instanceof GramJs.UpdateChatParticipants) {\n const replacedMembers = buildChatMembers(update.participants);\n\n onUpdate({\n '@type': 'updateChatMembers',\n id: buildApiPeerId(update.participants.chatId, 'chat'),\n replacedMembers,\n });\n } else if (update instanceof GramJs.UpdateChatParticipantAdd) {\n const addedMember = buildChatMember(\n pick(update, ['userId', 'inviterId', 'date']) as GramJs.ChatParticipant,\n );\n\n onUpdate({\n '@type': 'updateChatMembers',\n id: buildApiPeerId(update.chatId, 'chat'),\n addedMember,\n });\n } else if (update instanceof GramJs.UpdateChatParticipantDelete) {\n onUpdate({\n '@type': 'updateChatMembers',\n id: buildApiPeerId(update.chatId, 'chat'),\n deletedMemberId: buildApiPeerId(update.userId, 'user'),\n });\n } else if (\n update instanceof GramJs.UpdatePinnedMessages\n || update instanceof GramJs.UpdatePinnedChannelMessages\n ) {\n const chatId = update instanceof GramJs.UpdatePinnedMessages\n ? getApiChatIdFromMtpPeer(update.peer)\n : buildApiPeerId(update.channelId, 'channel');\n\n onUpdate({\n '@type': 'updatePinnedIds',\n chatId,\n messageIds: update.messages,\n isPinned: update.pinned,\n });\n } else if (\n update instanceof GramJs.UpdateNotifySettings\n && update.peer instanceof GramJs.NotifyPeer\n ) {\n onUpdate({\n '@type': 'updateNotifyExceptions',\n ...buildApiNotifyException(update.notifySettings, update.peer.peer, serverTimeOffset),\n });\n } else if (\n update instanceof GramJs.UpdateUserTyping\n || update instanceof GramJs.UpdateChatUserTyping\n ) {\n const id = update instanceof GramJs.UpdateUserTyping\n ? buildApiPeerId(update.userId, 'user')\n : buildApiPeerId(update.chatId, 'chat');\n\n onUpdate({\n '@type': 'updateChatTypingStatus',\n id,\n typingStatus: buildChatTypingStatus(update, serverTimeOffset),\n });\n } else if (update instanceof GramJs.UpdateChannelUserTyping) {\n const id = buildApiPeerId(update.channelId, 'channel');\n\n onUpdate({\n '@type': 'updateChatTypingStatus',\n id,\n typingStatus: buildChatTypingStatus(update, serverTimeOffset),\n });\n } else if (update instanceof GramJs.UpdateChannel) {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n const { _entities } = update;\n if (!_entities) {\n return;\n }\n\n const channel = _entities.find((e): e is GramJs.Channel | GramJs.ChannelForbidden => (\n e instanceof GramJs.Channel || e instanceof GramJs.ChannelForbidden\n ));\n\n if (channel instanceof GramJs.Channel) {\n if (shouldIgnoreNextChannelUpdate) {\n shouldIgnoreNextChannelUpdate = false;\n return;\n }\n\n if (originRequest instanceof GramJs.messages.ToggleNoForwards) {\n shouldIgnoreNextChannelUpdate = true;\n setTimeout(() => { shouldIgnoreNextChannelUpdate = false; }, IGNORE_NEXT_CHANNEL_UPDATE_TIMEOUT);\n }\n\n const chat = buildApiChatFromPreview(channel);\n if (chat) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n\n onUpdate({\n '@type': chat.isNotJoined ? 'updateChatLeave' : 'updateChatJoin',\n id: buildApiPeerId(update.channelId, 'channel'),\n });\n }\n } else if (channel instanceof GramJs.ChannelForbidden) {\n const chatId = buildApiPeerId(update.channelId, 'channel');\n\n onUpdate({\n '@type': 'updateChat',\n id: chatId,\n chat: {\n isRestricted: true,\n },\n });\n\n onUpdate({\n '@type': 'updateChatLeave',\n id: chatId,\n });\n } else if (_entities.length === 0) {\n // The link to the discussion group may have been changed.\n // No corresponding update available at this moment https://core.telegram.org/type/Updates\n onUpdate({\n '@type': 'resetMessages',\n id: buildApiPeerId(update.channelId, 'channel'),\n });\n }\n } else if (\n update instanceof GramJs.UpdateDialogUnreadMark\n && update.peer instanceof GramJs.DialogPeer\n ) {\n onUpdate({\n '@type': 'updateChat',\n id: getApiChatIdFromMtpPeer(update.peer.peer),\n chat: {\n hasUnreadMark: update.unread,\n },\n });\n } else if (update instanceof GramJs.UpdateChatDefaultBannedRights) {\n onUpdate({\n '@type': 'updateChat',\n id: getApiChatIdFromMtpPeer(update.peer),\n chat: {\n defaultBannedRights: omitVirtualClassFields(update.defaultBannedRights),\n },\n });\n\n // Users\n } else if (update instanceof GramJs.UpdateUserStatus) {\n onUpdate({\n '@type': 'updateUserStatus',\n userId: buildApiPeerId(update.userId, 'user'),\n status: buildApiUserStatus(update.status),\n });\n } else if (update instanceof GramJs.UpdateUserName) {\n const apiUserId = buildApiPeerId(update.userId, 'user');\n const updatedUser = localDb.users[apiUserId];\n const user = updatedUser?.mutualContact && !updatedUser.self\n ? pick(update, ['username'])\n : pick(update, ['firstName', 'lastName', 'username']);\n\n onUpdate({\n '@type': 'updateUser',\n id: apiUserId,\n user,\n });\n } else if (update instanceof GramJs.UpdateUserPhoto) {\n const { userId, photo } = update;\n const apiUserId = buildApiPeerId(userId, 'user');\n const avatarHash = buildAvatarHash(photo);\n\n if (localDb.users[apiUserId]) {\n localDb.users[apiUserId].photo = photo;\n }\n\n onUpdate({\n '@type': 'updateUser',\n id: apiUserId,\n user: { avatarHash },\n });\n } else if (update instanceof GramJs.UpdateUserPhone) {\n const { userId, phone } = update;\n\n onUpdate({\n '@type': 'updateUser',\n id: buildApiPeerId(userId, 'user'),\n user: { phoneNumber: phone },\n });\n } else if (update instanceof GramJs.UpdatePeerSettings) {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n const { _entities } = update;\n if (!_entities) {\n return;\n }\n\n if (_entities?.length) {\n _entities\n .filter((e) => e instanceof GramJs.User && !e.contact)\n .forEach((user) => {\n onUpdate({\n '@type': 'deleteContact',\n id: buildApiPeerId(user.id, 'user'),\n });\n });\n\n _entities\n .filter((e) => e instanceof GramJs.User && e.contact)\n .map(buildApiUser)\n .forEach((user) => {\n if (!user) {\n return;\n }\n\n onUpdate({\n '@type': 'updateUser',\n id: user.id,\n user,\n });\n });\n }\n\n // Settings\n } else if (update instanceof GramJs.UpdateNotifySettings) {\n const {\n notifySettings: {\n showPreviews, silent, muteUntil,\n },\n peer: { className },\n } = update;\n\n const peerType = className === 'NotifyUsers'\n ? 'contact'\n : (className === 'NotifyChats'\n ? 'group'\n : (className === 'NotifyBroadcasts'\n ? 'broadcast'\n : undefined\n )\n );\n\n if (!peerType) {\n return;\n }\n\n onUpdate({\n '@type': 'updateNotifySettings',\n peerType,\n isSilent: Boolean(silent\n || (typeof muteUntil === 'number' && Date.now() + serverTimeOffset * 1000 < muteUntil * 1000)),\n shouldShowPreviews: Boolean(showPreviews),\n });\n } else if (update instanceof GramJs.UpdatePeerBlocked) {\n onUpdate({\n '@type': 'updatePeerBlocked',\n id: getApiChatIdFromMtpPeer(update.peerId),\n isBlocked: update.blocked,\n });\n } else if (update instanceof GramJs.UpdatePrivacy) {\n const key = buildPrivacyKey(update.key);\n if (key) {\n onUpdate({\n '@type': 'updatePrivacy',\n key,\n rules: buildPrivacyRules(update.rules),\n });\n }\n\n // Misc\n } else if (update instanceof GramJs.UpdateDraftMessage) {\n onUpdate({\n '@type': 'draftMessage',\n chatId: getApiChatIdFromMtpPeer(update.peer),\n ...buildMessageDraft(update.draft),\n });\n } else if (update instanceof GramJs.UpdateContactsReset) {\n onUpdate({ '@type': 'updateResetContactList' });\n } else if (update instanceof GramJs.UpdateFavedStickers) {\n onUpdate({ '@type': 'updateFavoriteStickers' });\n } else if (update instanceof GramJs.UpdateGroupCall) {\n onUpdate({\n '@type': 'updateGroupCall',\n call: buildApiGroupCall(update.call),\n });\n } else if (update instanceof GramJs.UpdateGroupCallConnection) {\n onUpdate({\n '@type': 'updateGroupCallConnection',\n data: JSON.parse(update.params.data) as GroupCallConnectionData,\n presentation: Boolean(update.presentation),\n });\n } else if (update instanceof GramJs.UpdateGroupCallParticipants) {\n // eslint-disable-next-line no-underscore-dangle\n const entities = update._entities;\n if (entities) {\n addEntitiesWithPhotosToLocalDb(entities);\n dispatchUserAndChatUpdates(entities);\n }\n\n onUpdate({\n '@type': 'updateGroupCallParticipants',\n groupCallId: getGroupCallId(update.call),\n participants: update.participants.map(buildApiGroupCallParticipant),\n });\n } else if (DEBUG) {\n const params = typeof update === 'object' && 'className' in update ? update.className : update;\n // eslint-disable-next-line no-console\n console.warn('[GramJs/updater] Unexpected update:', params);\n }\n}\n","import { errors } from '../../../lib/gramjs';\nimport {\n ApiUpdateAuthorizationState,\n ApiUpdateAuthorizationStateType,\n OnApiUpdate,\n ApiUser,\n} from '../../types';\n\nimport { DEBUG } from '../../../config';\n\nconst ApiErrors: { [k: string]: string } = {\n PHONE_NUMBER_INVALID: 'Invalid phone number.',\n PHONE_CODE_INVALID: 'Invalid code.',\n PASSWORD_HASH_INVALID: 'Incorrect password.',\n PHONE_PASSWORD_FLOOD: 'Limit exceeded. Please try again later.',\n PHONE_NUMBER_BANNED: 'This phone number is banned.',\n};\n\nconst authController: {\n resolve?: Function;\n reject?: Function;\n} = {};\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport function onRequestPhoneNumber() {\n onUpdate(buildAuthStateUpdate('authorizationStateWaitPhoneNumber'));\n\n return new Promise((resolve, reject) => {\n authController.resolve = resolve;\n authController.reject = reject;\n });\n}\n\nexport function onRequestCode(isCodeViaApp = false) {\n onUpdate({\n ...buildAuthStateUpdate('authorizationStateWaitCode'),\n isCodeViaApp,\n });\n\n return new Promise((resolve, reject) => {\n authController.resolve = resolve;\n authController.reject = reject;\n });\n}\n\nexport function onRequestPassword(hint?: string) {\n onUpdate({\n ...buildAuthStateUpdate('authorizationStateWaitPassword'),\n hint,\n });\n\n return new Promise((resolve) => {\n authController.resolve = resolve;\n });\n}\n\nexport function onRequestRegistration() {\n onUpdate(buildAuthStateUpdate('authorizationStateWaitRegistration'));\n\n return new Promise<[string, string?]>((resolve) => {\n authController.resolve = resolve;\n });\n}\n\nexport function onRequestQrCode(qrCode: { token: Buffer; expires: number }) {\n onUpdate({\n ...buildAuthStateUpdate('authorizationStateWaitQrCode'),\n qrCode: {\n token: btoa(String.fromCharCode(...qrCode.token)).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, ''),\n expires: qrCode.expires,\n },\n });\n\n return new Promise((resolve, reject) => {\n authController.reject = reject;\n });\n}\n\nexport function onAuthError(err: Error) {\n let message: string;\n\n if (err instanceof errors.FloodWaitError) {\n const hours = Math.ceil(Number(err.seconds) / 60 / 60);\n message = `Too many attempts. Try again in ${hours > 1 ? `${hours} hours` : 'an hour'}`;\n } else {\n message = ApiErrors[err.message];\n }\n\n if (!message) {\n message = 'Unexpected Error';\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n }\n\n onUpdate({\n '@type': 'updateAuthorizationError',\n message,\n });\n}\n\nexport function onAuthReady() {\n onUpdate(buildAuthStateUpdate('authorizationStateReady'));\n}\n\nexport function onCurrentUserUpdate(currentUser: ApiUser) {\n onUpdate({\n '@type': 'updateCurrentUser',\n currentUser,\n });\n}\n\nexport function buildAuthStateUpdate(authorizationState: ApiUpdateAuthorizationStateType): ApiUpdateAuthorizationState {\n return {\n '@type': 'updateAuthorizationState',\n authorizationState,\n };\n}\n\nexport function provideAuthPhoneNumber(phoneNumber: string) {\n if (!authController.resolve) {\n return;\n }\n\n authController.resolve(phoneNumber);\n}\n\nexport function provideAuthCode(code: string) {\n if (!authController.resolve) {\n return;\n }\n\n authController.resolve(code);\n}\n\nexport function provideAuthPassword(password: string) {\n if (!authController.resolve) {\n return;\n }\n\n authController.resolve(password);\n}\n\nexport function provideAuthRegistration(registration: { firstName: string; lastName: string }) {\n const { firstName, lastName } = registration;\n\n if (!authController.resolve) {\n return;\n }\n\n authController.resolve([firstName, lastName]);\n}\n\nexport function restartAuth() {\n if (!authController.reject) {\n return;\n }\n\n authController.reject(new Error('RESTART_AUTH'));\n}\n\nexport function restartAuthWithQr() {\n if (!authController.reject) {\n return;\n }\n\n authController.reject(new Error('RESTART_AUTH_WITH_QR'));\n}\n","// eslint-disable-next-line no-restricted-globals\nconst cacheApi = self.caches;\n\nexport enum Type {\n Text,\n Blob,\n Json,\n}\n\nexport async function fetch(\n cacheName: string, key: string, type: Type, isHtmlAllowed = false,\n) {\n if (!cacheApi) {\n return undefined;\n }\n\n try {\n // To avoid the error \"Request scheme 'webdocument' is unsupported\"\n const request = new Request(key.replace(/:/g, '_'));\n const cache = await cacheApi.open(cacheName);\n const response = await cache.match(request);\n if (!response) {\n return undefined;\n }\n\n const contentType = response.headers.get('Content-Type');\n\n switch (type) {\n case Type.Text:\n return await response.text();\n case Type.Blob: {\n // Ignore deprecated data-uri avatars\n if (key.startsWith('avatar') && contentType && contentType.startsWith('text')) {\n return undefined;\n }\n\n const blob = await response.blob();\n\n // Safari does not return correct Content-Type header for webp images.\n if (key.startsWith('sticker')) {\n return new Blob([blob], { type: 'image/webp' });\n }\n\n const shouldRecreate = !blob.type || (!isHtmlAllowed && blob.type.includes('html'));\n // iOS Safari fails to preserve `type` in cache\n let resolvedType = blob.type || contentType;\n\n if (!(shouldRecreate && resolvedType)) {\n return blob;\n }\n\n // Prevent HTML-in-video attacks (for files that were cached before fix)\n if (!isHtmlAllowed) {\n resolvedType = resolvedType.replace(/html/gi, '');\n }\n\n return new Blob([blob], { type: resolvedType });\n }\n case Type.Json:\n return await response.json();\n default:\n return undefined;\n }\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n\nexport async function save(cacheName: string, key: string, data: AnyLiteral | Blob | string) {\n if (!cacheApi) {\n return undefined;\n }\n\n try {\n const cacheData = typeof data === 'string' || data instanceof Blob ? data : JSON.stringify(data);\n // To avoid the error \"Request scheme 'webdocument' is unsupported\"\n const request = new Request(key.replace(/:/g, '_'));\n const response = new Response(cacheData);\n const cache = await cacheApi.open(cacheName);\n return await cache.put(request, response);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n\nexport async function clear(cacheName: string) {\n try {\n if (!cacheApi) {\n return undefined;\n }\n\n return await cacheApi.delete(cacheName);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn(err);\n return undefined;\n }\n}\n","import { inflate } from 'pako/dist/pako_inflate';\n\nimport { Api as GramJs, TelegramClient } from '../../../lib/gramjs';\nimport {\n ApiMediaFormat, ApiOnProgress, ApiParsedMedia, ApiPreparedMedia,\n} from '../../types';\n\nimport {\n DOWNLOAD_WORKERS,\n MEDIA_CACHE_DISABLED,\n MEDIA_CACHE_MAX_BYTES,\n MEDIA_CACHE_NAME,\n MEDIA_CACHE_NAME_AVATARS,\n} from '../../../config';\nimport localDb from '../localDb';\nimport { getEntityTypeById } from '../gramjsBuilders';\nimport * as cacheApi from '../../../util/cacheApi';\n\ntype EntityType = (\n 'msg' | 'sticker' | 'wallpaper' | 'gif' | 'channel' | 'chat' | 'user' | 'photo' | 'stickerSet' | 'webDocument'\n);\nconst MEDIA_ENTITY_TYPES = new Set(['msg', 'sticker', 'gif', 'wallpaper', 'photo', 'webDocument']);\n\nexport default async function downloadMedia(\n {\n url, mediaFormat, start, end, isHtmlAllowed,\n }: {\n url: string; mediaFormat: ApiMediaFormat; start?: number; end?: number; isHtmlAllowed?: boolean;\n },\n client: TelegramClient,\n isConnected: boolean,\n onProgress?: ApiOnProgress,\n) {\n const {\n data, mimeType, fullSize,\n } = await download(url, client, isConnected, onProgress, start, end, mediaFormat, isHtmlAllowed) || {};\n if (!data) {\n return undefined;\n }\n\n const parsed = await parseMedia(data, mediaFormat, mimeType);\n if (!parsed) {\n return undefined;\n }\n\n const canCache = mediaFormat !== ApiMediaFormat.Progressive && (\n mediaFormat !== ApiMediaFormat.BlobUrl || (parsed as Blob).size <= MEDIA_CACHE_MAX_BYTES\n );\n\n if (!MEDIA_CACHE_DISABLED && cacheApi && canCache) {\n const cacheName = url.startsWith('avatar') ? MEDIA_CACHE_NAME_AVATARS : MEDIA_CACHE_NAME;\n void cacheApi.save(cacheName, url, parsed);\n }\n\n const prepared = mediaFormat === ApiMediaFormat.Progressive ? '' : prepareMedia(parsed);\n const arrayBuffer = mediaFormat === ApiMediaFormat.Progressive ? parsed as ArrayBuffer : undefined;\n\n return {\n prepared,\n arrayBuffer,\n mimeType,\n fullSize,\n };\n}\n\nasync function download(\n url: string,\n client: TelegramClient,\n isConnected: boolean,\n onProgress?: ApiOnProgress,\n start?: number,\n end?: number,\n mediaFormat?: ApiMediaFormat,\n isHtmlAllowed?: boolean,\n) {\n const mediaMatch = url.startsWith('webDocument')\n ? url.match(/(webDocument):(.+)/)\n : url.match(/(avatar|profile|photo|msg|stickerSet|sticker|wallpaper|gif|file)([-\\d\\w./]+)(?::\\d+)?(\\?size=\\w+)?/);\n if (!mediaMatch) {\n return undefined;\n }\n\n if (mediaMatch[1] === 'file') {\n const response = await fetch(mediaMatch[2]);\n const data = await response.arrayBuffer();\n return { data };\n }\n\n if (!isConnected) {\n return Promise.reject(new Error('ERROR: Client is not connected'));\n }\n\n let entityType: EntityType;\n const entityId: string | number = mediaMatch[2];\n const sizeType = mediaMatch[3] ? mediaMatch[3].replace('?size=', '') : undefined;\n let entity: (\n GramJs.User | GramJs.Chat | GramJs.Channel | GramJs.Photo |\n GramJs.Message | GramJs.MessageService |\n GramJs.Document | GramJs.StickerSet | GramJs.TypeWebDocument | undefined\n );\n\n if (mediaMatch[1] === 'avatar' || mediaMatch[1] === 'profile') {\n entityType = getEntityTypeById(entityId);\n } else {\n entityType = mediaMatch[1] as 'msg' | 'sticker' | 'wallpaper' | 'gif' | 'stickerSet' | 'photo' | 'webDocument';\n }\n\n switch (entityType) {\n case 'channel':\n case 'chat':\n entity = localDb.chats[entityId];\n break;\n case 'user':\n entity = localDb.users[entityId];\n break;\n case 'msg':\n entity = localDb.messages[entityId];\n break;\n case 'sticker':\n case 'gif':\n case 'wallpaper':\n entity = localDb.documents[entityId];\n break;\n case 'photo':\n entity = localDb.photos[entityId];\n break;\n case 'stickerSet':\n entity = localDb.stickerSets[entityId];\n break;\n case 'webDocument':\n entity = localDb.webDocuments[entityId];\n break;\n }\n\n if (!entity) {\n return undefined;\n }\n\n if (MEDIA_ENTITY_TYPES.has(entityType)) {\n if (mediaFormat === ApiMediaFormat.Stream) {\n onProgress!.acceptsBuffer = true;\n }\n\n const data = await client.downloadMedia(entity, {\n sizeType, start, end, progressCallback: onProgress, workers: DOWNLOAD_WORKERS,\n });\n let mimeType;\n let fullSize;\n\n if (entity instanceof GramJs.Message) {\n mimeType = getMessageMediaMimeType(entity, sizeType);\n if (entity.media instanceof GramJs.MessageMediaDocument && entity.media.document instanceof GramJs.Document) {\n fullSize = entity.media.document.size;\n }\n if (entity.media instanceof GramJs.MessageMediaWebPage\n && entity.media.webpage instanceof GramJs.WebPage\n && entity.media.webpage.document instanceof GramJs.Document) {\n fullSize = entity.media.webpage.document.size;\n }\n } else if (entity instanceof GramJs.Photo) {\n mimeType = 'image/jpeg';\n } else if (entityType === 'sticker' && sizeType) {\n mimeType = 'image/webp';\n } else if (entityType === 'webDocument') {\n mimeType = (entity as GramJs.TypeWebDocument).mimeType;\n } else {\n mimeType = (entity as GramJs.Document).mimeType;\n fullSize = (entity as GramJs.Document).size;\n }\n\n // Prevent HTML-in-video attacks\n if (!isHtmlAllowed && mimeType) {\n mimeType = mimeType.replace(/html/gi, '');\n }\n\n return { mimeType, data, fullSize };\n } else if (entityType === 'stickerSet') {\n const data = await client.downloadStickerSetThumb(entity);\n const mimeType = mediaFormat === ApiMediaFormat.Lottie ? 'application/json' : getMimeType(data);\n\n return { mimeType, data };\n } else {\n const data = await client.downloadProfilePhoto(entity, mediaMatch[1] === 'profile');\n const mimeType = getMimeType(data);\n\n return { mimeType, data };\n }\n}\n\nfunction getMessageMediaMimeType(message: GramJs.Message, sizeType?: string) {\n if (!message || !message.media) {\n return undefined;\n }\n\n if (message.media instanceof GramJs.MessageMediaPhoto) {\n return 'image/jpeg';\n }\n\n if (message.media instanceof GramJs.MessageMediaDocument && message.media.document instanceof GramJs.Document) {\n if (sizeType) {\n return message.media.document!.attributes.some((a) => a instanceof GramJs.DocumentAttributeSticker)\n ? 'image/webp'\n : 'image/jpeg';\n }\n\n return message.media.document!.mimeType;\n }\n\n if (message.media instanceof GramJs.MessageMediaWebPage\n && message.media.webpage instanceof GramJs.WebPage\n && message.media.webpage.document instanceof GramJs.Document) {\n return message.media.webpage.document.mimeType;\n }\n\n return undefined;\n}\n\n// eslint-disable-next-line no-async-without-await/no-async-without-await\nasync function parseMedia(\n data: Buffer, mediaFormat: ApiMediaFormat, mimeType?: string,\n): Promise {\n switch (mediaFormat) {\n case ApiMediaFormat.BlobUrl:\n return new Blob([data], { type: mimeType });\n case ApiMediaFormat.Lottie: {\n const json = inflate(data, { to: 'string' });\n return JSON.parse(json);\n }\n case ApiMediaFormat.Progressive: {\n return data.buffer;\n }\n }\n\n return undefined;\n}\n\nfunction prepareMedia(mediaData: ApiParsedMedia): ApiPreparedMedia {\n if (mediaData instanceof Blob) {\n return URL.createObjectURL(mediaData);\n }\n\n return mediaData;\n}\n\nfunction getMimeType(data: Uint8Array, fallbackMimeType = 'image/jpeg') {\n if (data.length < 4) {\n return fallbackMimeType;\n }\n\n let type = fallbackMimeType;\n const signature = data.subarray(0, 4).reduce((result, byte) => result + byte.toString(16), '');\n\n // https://en.wikipedia.org/wiki/List_of_file_signatures\n switch (signature) {\n case '89504e47':\n type = 'image/png';\n break;\n case '47494638':\n type = 'image/gif';\n break;\n case 'ffd8ffe0':\n case 'ffd8ffe1':\n case 'ffd8ffe2':\n case 'ffd8ffe3':\n case 'ffd8ffe8':\n type = 'image/jpeg';\n break;\n case '52494646':\n // In our case only webp is expected\n type = 'image/webp';\n break;\n }\n\n return type;\n}\n","import {\n TelegramClient, sessions, Api as GramJs, connection,\n} from '../../../lib/gramjs';\nimport { Logger as GramJsLogger } from '../../../lib/gramjs/extensions/index';\nimport { TwoFaParams } from '../../../lib/gramjs/client/2fa';\n\nimport {\n ApiInitialArgs,\n ApiMediaFormat,\n ApiOnProgress,\n ApiSessionData,\n OnApiUpdate,\n} from '../../types';\n\nimport {\n DEBUG, DEBUG_GRAMJS, UPLOAD_WORKERS, IS_TEST, APP_VERSION,\n} from '../../../config';\nimport {\n onRequestPhoneNumber, onRequestCode, onRequestPassword, onRequestRegistration,\n onAuthError, onAuthReady, onCurrentUserUpdate, onRequestQrCode,\n} from './auth';\nimport { updater } from '../updater';\nimport { setMessageBuilderCurrentUserId } from '../apiBuilders/messages';\nimport downloadMediaWithClient from './media';\nimport { buildApiUserFromFull } from '../apiBuilders/users';\nimport localDb from '../localDb';\nimport { buildApiPeerId } from '../apiBuilders/peers';\n\nconst DEFAULT_USER_AGENT = 'Unknown UserAgent';\nconst DEFAULT_PLATFORM = 'Unknown platform';\nconst APP_CODE_NAME = 'Z';\n\nGramJsLogger.setLevel(DEBUG_GRAMJS ? 'debug' : 'warn');\n\nconst gramJsUpdateEventBuilder = { build: (update: object) => update };\n\nlet onUpdate: OnApiUpdate;\nlet client: TelegramClient;\nlet isConnected = false;\n\nexport async function init(_onUpdate: OnApiUpdate, initialArgs: ApiInitialArgs) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> START INIT API');\n }\n\n onUpdate = _onUpdate;\n\n const {\n userAgent, platform, sessionData, isTest, isMovSupported,\n } = initialArgs;\n const session = new sessions.CallbackSession(sessionData, onSessionUpdate);\n\n // eslint-disable-next-line no-restricted-globals\n (self as any).isMovSupported = isMovSupported;\n\n client = new TelegramClient(\n session,\n process.env.TELEGRAM_T_API_ID,\n process.env.TELEGRAM_T_API_HASH,\n {\n deviceModel: navigator.userAgent || userAgent || DEFAULT_USER_AGENT,\n systemVersion: platform || DEFAULT_PLATFORM,\n appVersion: `${APP_VERSION} ${APP_CODE_NAME}`,\n useWSS: true,\n additionalDcsDisabled: IS_TEST,\n testServers: isTest,\n } as any,\n );\n\n client.addEventHandler(handleGramJsUpdate, gramJsUpdateEventBuilder);\n client.addEventHandler(updater, gramJsUpdateEventBuilder);\n\n try {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[GramJs/client] CONNECTING');\n\n // eslint-disable-next-line no-restricted-globals\n (self as any).invoke = invokeRequest;\n // eslint-disable-next-line no-restricted-globals\n (self as any).GramJs = GramJs;\n }\n\n try {\n await client.start({\n phoneNumber: onRequestPhoneNumber,\n phoneCode: onRequestCode,\n password: onRequestPassword,\n firstAndLastNames: onRequestRegistration,\n qrCode: onRequestQrCode,\n onError: onAuthError,\n initialMethod: platform === 'iOS' || platform === 'Android' ? 'phoneNumber' : 'qrCode',\n });\n } catch (err) {\n // TODO Investigate which request causes this exception\n if (err.message !== 'Disconnect') {\n onUpdate({\n '@type': 'updateConnectionState',\n connectionState: 'connectionStateBroken',\n });\n\n return;\n }\n }\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH INIT API');\n // eslint-disable-next-line no-console\n console.log('[GramJs/client] CONNECTED');\n }\n\n onAuthReady();\n onSessionUpdate(session.getSessionData());\n onUpdate({ '@type': 'updateApiReady' });\n\n void fetchCurrentUser();\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('[GramJs/client] CONNECTING ERROR', err);\n }\n\n throw err;\n }\n}\n\nexport async function destroy() {\n await invokeRequest(new GramJs.auth.LogOut());\n await client.destroy();\n}\n\nexport async function disconnect() {\n await client.disconnect();\n}\n\nexport function getClient() {\n return client;\n}\n\nfunction onSessionUpdate(sessionData: ApiSessionData) {\n onUpdate({\n '@type': 'updateSession',\n sessionData,\n });\n}\n\nfunction handleGramJsUpdate(update: any) {\n if (update instanceof connection.UpdateConnectionState) {\n isConnected = update.state === connection.UpdateConnectionState.connected;\n } else if (update instanceof GramJs.UpdatesTooLong) {\n void handleTerminatedSession();\n } else if (update instanceof connection.UpdateServerTimeOffset) {\n onUpdate({\n '@type': 'updateServerTimeOffset',\n serverTimeOffset: update.timeOffset,\n });\n }\n}\n\nexport async function invokeRequest(\n request: T,\n shouldHandleUpdates = false,\n shouldThrow = false,\n): Promise {\n if (!isConnected) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(`[GramJs/client] INVOKE ERROR ${request.className}: Client is not connected`);\n }\n\n return undefined;\n }\n\n try {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log(`[GramJs/client] INVOKE ${request.className}`);\n }\n\n const result = await client.invoke(request);\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log(`[GramJs/client] INVOKE RESPONSE ${request.className}`, result);\n }\n\n if (shouldHandleUpdates) {\n type ResultWithUpdates =\n typeof result\n & { updates?: GramJs.Updates | GramJs.UpdatesCombined };\n\n let updatesContainer;\n if (result instanceof GramJs.Updates || result instanceof GramJs.UpdatesCombined) {\n updatesContainer = result;\n } else if ('updates' in (result as ResultWithUpdates) && (\n (result as ResultWithUpdates).updates instanceof GramJs.Updates\n || (result as ResultWithUpdates).updates instanceof GramJs.UpdatesCombined\n )) {\n updatesContainer = (result as ResultWithUpdates).updates;\n }\n\n if (updatesContainer) {\n injectUpdateEntities(updatesContainer);\n\n updatesContainer.updates.forEach((update) => {\n updater(update, request);\n });\n } else if (result instanceof GramJs.UpdatesTooLong) {\n // TODO Implement\n } else {\n updater(result as GramJs.TypeUpdates, request);\n }\n }\n\n return result;\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.log(`[GramJs/client] INVOKE ERROR ${request.className}`);\n // eslint-disable-next-line no-console\n console.error(err);\n }\n\n if (shouldThrow) {\n throw err;\n }\n\n dispatchErrorUpdate(err, request);\n\n return undefined;\n }\n}\n\nexport function downloadMedia(\n args: { url: string; mediaFormat: ApiMediaFormat; start?: number; end?: number; isHtmlAllowed?: boolean },\n onProgress?: ApiOnProgress,\n) {\n return downloadMediaWithClient(args, client, isConnected, onProgress);\n}\n\nexport function uploadFile(file: File, onProgress?: ApiOnProgress) {\n return client.uploadFile({ file, onProgress, workers: UPLOAD_WORKERS });\n}\n\nexport function updateTwoFaSettings(params: TwoFaParams) {\n return client.updateTwoFaSettings(params);\n}\n\nexport async function fetchCurrentUser() {\n const userFull = await invokeRequest(new GramJs.users.GetFullUser({\n id: new GramJs.InputUserSelf(),\n }));\n\n if (!userFull || !(userFull.users[0] instanceof GramJs.User)) {\n return;\n }\n\n const user = userFull.users[0];\n\n localDb.users[buildApiPeerId(user.id, 'user')] = user;\n const currentUser = buildApiUserFromFull(userFull);\n\n setMessageBuilderCurrentUserId(currentUser.id);\n onCurrentUserUpdate(currentUser);\n}\n\nexport function dispatchErrorUpdate(err: Error, request: T) {\n const isSlowMode = err.message.startsWith('A wait of') && (\n request instanceof GramJs.messages.SendMessage\n || request instanceof GramJs.messages.SendMedia\n || request instanceof GramJs.messages.SendMultiMedia\n );\n\n const { message } = err;\n\n onUpdate({\n '@type': 'error',\n error: {\n message,\n isSlowMode,\n hasErrorKey: true,\n },\n });\n}\n\nfunction injectUpdateEntities(result: GramJs.Updates | GramJs.UpdatesCombined) {\n const entities = [...result.users, ...result.chats];\n\n result.updates.forEach((update) => {\n if (entities) {\n // eslint-disable-next-line no-underscore-dangle\n (update as any)._entities = entities;\n }\n });\n}\n\nasync function handleTerminatedSession() {\n try {\n await invokeRequest(new GramJs.users.GetFullUser({\n id: new GramJs.InputUserSelf(),\n }), undefined, true);\n } catch (err) {\n if (err.message === 'AUTH_KEY_UNREGISTERED') {\n onUpdate({\n '@type': 'updateConnectionState',\n connectionState: 'connectionStateBroken',\n });\n }\n }\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport {\n OnApiUpdate,\n ApiChat,\n ApiMessage,\n ApiUser,\n ApiMessageEntity,\n ApiFormattedText,\n ApiChatFullInfo,\n ApiChatFolder,\n ApiChatBannedRights,\n ApiChatAdminRights,\n ApiGroupCall,\n} from '../../types';\n\nimport {\n DEBUG, ARCHIVED_FOLDER_ID, MEMBERS_LOAD_SLICE, SERVICE_NOTIFICATIONS_USER_ID,\n} from '../../../config';\nimport { invokeRequest, uploadFile } from './client';\nimport {\n buildApiChatFromDialog,\n getPeerKey,\n buildChatMembers,\n buildApiChatFromPreview,\n buildApiChatFolder,\n buildApiChatFolderFromSuggested,\n buildApiChatBotCommands,\n} from '../apiBuilders/chats';\nimport { buildApiMessage, buildMessageDraft } from '../apiBuilders/messages';\nimport { buildApiUser, buildApiUsersAndStatuses } from '../apiBuilders/users';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport {\n buildInputEntity,\n buildInputPeer,\n buildMtpMessageEntity,\n buildFilterFromApiFolder,\n isMessageWithMedia,\n buildChatBannedRights,\n buildChatAdminRights,\n} from '../gramjsBuilders';\nimport { addEntitiesWithPhotosToLocalDb, addMessageToLocalDb, addPhotoToLocalDb } from '../helpers';\nimport { buildApiPeerId, getApiChatIdFromMtpPeer } from '../apiBuilders/peers';\nimport { buildApiPhoto } from '../apiBuilders/common';\n\nconst MAX_INT_32 = 2 ** 31 - 1;\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function fetchChats({\n limit,\n offsetDate,\n archived,\n withPinned,\n serverTimeOffset,\n lastLocalServiceMessage,\n}: {\n limit: number;\n offsetDate?: number;\n archived?: boolean;\n withPinned?: boolean;\n serverTimeOffset: number;\n lastLocalServiceMessage?: ApiMessage;\n}) {\n const result = await invokeRequest(new GramJs.messages.GetDialogs({\n offsetPeer: new GramJs.InputPeerEmpty(),\n limit,\n offsetDate,\n folderId: archived ? ARCHIVED_FOLDER_ID : undefined,\n ...(withPinned && { excludePinned: true }),\n }));\n const resultPinned = withPinned\n ? await invokeRequest(new GramJs.messages.GetPinnedDialogs({\n folderId: archived ? ARCHIVED_FOLDER_ID : undefined,\n }))\n : undefined;\n\n if (!result || result instanceof GramJs.messages.DialogsNotModified) {\n return undefined;\n }\n\n if (resultPinned) {\n updateLocalDb(resultPinned);\n }\n updateLocalDb(result);\n\n const lastMessagesByChatId = buildCollectionByKey(\n (resultPinned ? resultPinned.messages : []).concat(result.messages)\n .map(buildApiMessage)\n .filter(Boolean as any),\n 'chatId',\n );\n const peersByKey: Record = {\n ...(resultPinned && preparePeers(resultPinned)),\n ...preparePeers(result),\n };\n const chats: ApiChat[] = [];\n const draftsById: Record = {};\n const replyingToById: Record = {};\n\n const dialogs = (resultPinned ? resultPinned.dialogs : []).concat(result.dialogs);\n\n const orderedPinnedIds: string[] = [];\n\n dialogs.forEach((dialog) => {\n if (\n !(dialog instanceof GramJs.Dialog)\n // This request can return dialogs not belonging to specified folder\n || (!archived && dialog.folderId === ARCHIVED_FOLDER_ID)\n || (archived && dialog.folderId !== ARCHIVED_FOLDER_ID)\n ) {\n return;\n }\n\n const peerEntity = peersByKey[getPeerKey(dialog.peer)];\n const chat = buildApiChatFromDialog(dialog, peerEntity, serverTimeOffset);\n\n if (\n chat.id === SERVICE_NOTIFICATIONS_USER_ID\n && lastLocalServiceMessage\n && (!lastMessagesByChatId[chat.id] || lastLocalServiceMessage.date > lastMessagesByChatId[chat.id].date)\n ) {\n chat.lastMessage = lastLocalServiceMessage;\n } else {\n chat.lastMessage = lastMessagesByChatId[chat.id];\n }\n\n chat.isListed = true;\n chats.push(chat);\n\n if (withPinned && dialog.pinned) {\n orderedPinnedIds.push(chat.id);\n }\n\n if (dialog.draft) {\n const { formattedText, replyingToId } = buildMessageDraft(dialog.draft) || {};\n if (formattedText) {\n draftsById[chat.id] = formattedText;\n }\n if (replyingToId) {\n replyingToById[chat.id] = replyingToId;\n }\n }\n });\n\n const chatIds = chats.map((chat) => chat.id);\n\n const { users, userStatusesById } = buildApiUsersAndStatuses((resultPinned?.users || []).concat(result.users));\n\n let totalChatCount: number;\n if (result instanceof GramJs.messages.DialogsSlice) {\n totalChatCount = result.count;\n } else {\n totalChatCount = chatIds.length;\n }\n\n return {\n chatIds,\n chats,\n users,\n userStatusesById,\n draftsById,\n replyingToById,\n orderedPinnedIds: withPinned ? orderedPinnedIds : undefined,\n totalChatCount,\n };\n}\n\nexport function fetchFullChat(chat: ApiChat) {\n const { id, accessHash, adminRights } = chat;\n\n const input = buildInputEntity(id, accessHash);\n\n return input instanceof GramJs.InputChannel\n ? getFullChannelInfo(id, accessHash!, adminRights)\n : getFullChatInfo(id);\n}\n\nexport async function searchChats({ query }: { query: string }) {\n const result = await invokeRequest(new GramJs.contacts.Search({ q: query }));\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const localPeerIds = result.myResults.map(getApiChatIdFromMtpPeer);\n const allChats = result.chats.concat(result.users)\n .map((user) => buildApiChatFromPreview(user))\n .filter(Boolean as any);\n const allUsers = result.users.map(buildApiUser).filter((user) => !!user && !user.isSelf) as ApiUser[];\n\n return {\n localChats: allChats.filter((r) => localPeerIds.includes(r.id)),\n localUsers: allUsers.filter((u) => localPeerIds.includes(u.id)),\n globalChats: allChats.filter((r) => !localPeerIds.includes(r.id)),\n globalUsers: allUsers.filter((u) => !localPeerIds.includes(u.id)),\n };\n}\n\nexport async function fetchChat({\n type, user,\n}: {\n type: 'user' | 'self' | 'support'; user?: ApiUser;\n}) {\n let mtpUser: GramJs.User | undefined;\n\n if (type === 'self' || type === 'user') {\n const result = await invokeRequest(new GramJs.users.GetUsers({\n id: [\n type === 'user' && user\n ? buildInputEntity(user.id, user.accessHash) as GramJs.InputUser\n : new GramJs.InputUserSelf(),\n ],\n }));\n if (!result || !result.length) {\n return undefined;\n }\n\n [mtpUser] = result;\n } else if (type === 'support') {\n const result = await invokeRequest(new GramJs.help.GetSupport());\n if (!result || !result.user) {\n return undefined;\n }\n\n mtpUser = result.user;\n }\n\n const chat = buildApiChatFromPreview(mtpUser!, type === 'support');\n if (!chat) {\n return undefined;\n }\n\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n\n return { chatId: chat.id };\n}\n\nexport async function requestChatUpdate({\n chat,\n serverTimeOffset,\n lastLocalMessage,\n noLastMessage,\n}: {\n chat: ApiChat; serverTimeOffset: number; lastLocalMessage?: ApiMessage; noLastMessage?: boolean;\n}) {\n const { id, accessHash } = chat;\n\n const result = await invokeRequest(new GramJs.messages.GetPeerDialogs({\n peers: [new GramJs.InputDialogPeer({\n peer: buildInputPeer(id, accessHash),\n })],\n }));\n\n if (!result) {\n return;\n }\n\n const dialog = result.dialogs[0];\n if (!dialog || !(dialog instanceof GramJs.Dialog)) {\n return;\n }\n\n const peersByKey = preparePeers(result);\n const peerEntity = peersByKey[getPeerKey(dialog.peer)];\n if (!peerEntity) {\n return;\n }\n\n updateLocalDb(result);\n\n const lastRemoteMessage = buildApiMessage(result.messages[0]);\n const lastMessage = lastLocalMessage && (!lastRemoteMessage || (lastLocalMessage.date > lastRemoteMessage.date))\n ? lastLocalMessage\n : lastRemoteMessage;\n\n onUpdate({\n '@type': 'updateChat',\n id,\n chat: {\n ...buildApiChatFromDialog(dialog, peerEntity, serverTimeOffset),\n ...(!noLastMessage && { lastMessage }),\n },\n });\n}\n\nexport function saveDraft({\n chat,\n text,\n entities,\n replyToMsgId,\n}: {\n chat: ApiChat;\n text: string;\n entities?: ApiMessageEntity[];\n replyToMsgId?: number;\n}) {\n return invokeRequest(new GramJs.messages.SaveDraft({\n peer: buildInputPeer(chat.id, chat.accessHash),\n message: text,\n ...(entities && {\n entities: entities.map(buildMtpMessageEntity),\n }),\n replyToMsgId,\n }));\n}\n\nexport function clearDraft(chat: ApiChat) {\n return invokeRequest(new GramJs.messages.SaveDraft({\n peer: buildInputPeer(chat.id, chat.accessHash),\n message: '',\n }));\n}\n\nasync function getFullChatInfo(chatId: string): Promise<{\n fullInfo: ApiChatFullInfo;\n users?: ApiUser[];\n groupCall?: Partial;\n} | undefined> {\n const result = await invokeRequest(new GramJs.messages.GetFullChat({\n chatId: buildInputEntity(chatId) as BigInt.BigInteger,\n }));\n\n if (!result || !(result.fullChat instanceof GramJs.ChatFull)) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const {\n about,\n participants,\n exportedInvite,\n botInfo,\n call,\n } = result.fullChat;\n\n const members = buildChatMembers(participants);\n const adminMembers = members ? members.filter(({ isAdmin, isOwner }) => isAdmin || isOwner) : undefined;\n const botCommands = botInfo ? buildApiChatBotCommands(botInfo) : undefined;\n\n return {\n fullInfo: {\n about,\n members,\n adminMembers,\n canViewMembers: true,\n botCommands,\n ...(exportedInvite && {\n inviteLink: exportedInvite.link,\n }),\n groupCallId: call?.id.toString(),\n },\n users: result.users.map(buildApiUser).filter(Boolean as any),\n groupCall: call ? {\n chatId,\n isLoaded: false,\n id: call.id.toString(),\n accessHash: call.accessHash.toString(),\n connectionState: 'disconnected',\n participantsCount: 0,\n version: 0,\n participants: {},\n } : undefined,\n };\n}\n\nasync function getFullChannelInfo(\n id: string,\n accessHash: string,\n adminRights?: ApiChatAdminRights,\n): Promise<{\n fullInfo: ApiChatFullInfo;\n users?: ApiUser[];\n groupCall?: Partial;\n } | undefined> {\n const result = await invokeRequest(new GramJs.channels.GetFullChannel({\n channel: buildInputEntity(id, accessHash) as GramJs.InputChannel,\n }));\n\n if (!result || !(result.fullChat instanceof GramJs.ChannelFull)) {\n return undefined;\n }\n\n const {\n about,\n onlineCount,\n exportedInvite,\n slowmodeSeconds,\n slowmodeNextSendDate,\n migratedFromChatId,\n migratedFromMaxId,\n canViewParticipants,\n linkedChatId,\n hiddenPrehistory,\n call,\n botInfo,\n defaultSendAs,\n } = result.fullChat;\n\n const inviteLink = exportedInvite instanceof GramJs.ChatInviteExported\n ? exportedInvite.link\n : undefined;\n\n const { members, users } = (canViewParticipants && await fetchMembers(id, accessHash)) || {};\n const { members: kickedMembers, users: bannedUsers } = (\n canViewParticipants && adminRights && await fetchMembers(id, accessHash, 'kicked')\n ) || {};\n const { members: adminMembers, users: adminUsers } = (\n canViewParticipants && adminRights && await fetchMembers(id, accessHash, 'admin')\n ) || {};\n const botCommands = botInfo ? buildApiChatBotCommands(botInfo) : undefined;\n\n if (result?.chats?.length > 1) {\n updateLocalDb(result);\n\n const [, mtpLinkedChat] = result.chats;\n const chat = buildApiChatFromPreview(mtpLinkedChat, undefined, true);\n if (chat) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n }\n }\n\n return {\n fullInfo: {\n about,\n onlineCount,\n inviteLink,\n slowMode: slowmodeSeconds ? {\n seconds: slowmodeSeconds,\n nextSendDate: slowmodeNextSendDate,\n } : undefined,\n migratedFrom: migratedFromChatId ? {\n chatId: buildApiPeerId(migratedFromChatId, 'chat'),\n maxMessageId: migratedFromMaxId,\n } : undefined,\n canViewMembers: canViewParticipants,\n isPreHistoryHidden: hiddenPrehistory,\n members,\n kickedMembers,\n adminMembers,\n groupCallId: call ? String(call.id) : undefined,\n linkedChatId: linkedChatId ? buildApiPeerId(linkedChatId, 'chat') : undefined,\n botCommands,\n sendAsId: defaultSendAs ? getApiChatIdFromMtpPeer(defaultSendAs) : undefined,\n },\n users: [...(users || []), ...(bannedUsers || []), ...(adminUsers || [])],\n groupCall: call ? {\n chatId: id,\n isLoaded: false,\n id: call.id.toString(),\n accessHash: call?.accessHash.toString(),\n participants: {},\n version: 0,\n participantsCount: 0,\n connectionState: 'disconnected',\n } : undefined,\n };\n}\n\nexport async function updateChatMutedState({\n chat, isMuted, serverTimeOffset,\n}: {\n chat: ApiChat; isMuted: boolean; serverTimeOffset: number;\n}) {\n await invokeRequest(new GramJs.account.UpdateNotifySettings({\n peer: new GramJs.InputNotifyPeer({\n peer: buildInputPeer(chat.id, chat.accessHash),\n }),\n settings: new GramJs.InputPeerNotifySettings({ muteUntil: isMuted ? MAX_INT_32 : 0 }),\n }));\n\n onUpdate({\n '@type': 'updateNotifyExceptions',\n chatId: chat.id,\n isMuted,\n });\n\n void requestChatUpdate({\n chat,\n serverTimeOffset,\n noLastMessage: true,\n });\n}\n\nexport async function createChannel({\n title, about = '', users,\n}: {\n title: string; about?: string; users?: ApiUser[];\n}, noErrorUpdate = false): Promise {\n const result = await invokeRequest(new GramJs.channels.CreateChannel({\n broadcast: true,\n title,\n about,\n }), true);\n\n // `createChannel` can return a lot of different update types according to docs,\n // but currently channel creation returns only `Updates` type.\n // Errors are added to catch unexpected cases in future testing\n if (!(result instanceof GramJs.Updates)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected channel creation update', result);\n }\n return undefined;\n }\n\n const newChannel = result.chats[0];\n if (!newChannel || !(newChannel instanceof GramJs.Channel)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Created channel not found', result);\n }\n return undefined;\n }\n\n const channel = buildApiChatFromPreview(newChannel)!;\n\n if (users?.length) {\n try {\n await invokeRequest(new GramJs.channels.InviteToChannel({\n channel: buildInputEntity(channel.id, channel.accessHash) as GramJs.InputChannel,\n users: users.map(({ id, accessHash }) => buildInputEntity(id, accessHash)) as GramJs.InputUser[],\n }), true, noErrorUpdate);\n } catch (err) {\n // `noErrorUpdate` will cause an exception which we don't want either\n }\n }\n\n return channel;\n}\n\nexport function joinChannel({\n channelId, accessHash,\n}: {\n channelId: string; accessHash: string;\n}) {\n return invokeRequest(new GramJs.channels.JoinChannel({\n channel: buildInputEntity(channelId, accessHash) as GramJs.InputChannel,\n }), true);\n}\n\nexport function deleteChatUser({\n chat, user,\n}: {\n chat: ApiChat; user: ApiUser;\n}) {\n if (chat.type !== 'chatTypeBasicGroup') return undefined;\n return invokeRequest(new GramJs.messages.DeleteChatUser({\n chatId: buildInputEntity(chat.id, chat.accessHash) as BigInt.BigInteger,\n userId: buildInputEntity(user.id, user.accessHash) as GramJs.InputUser,\n }), true);\n}\n\nexport function deleteChat({\n chatId,\n}: {\n chatId: string;\n}) {\n return invokeRequest(new GramJs.messages.DeleteChat({\n chatId: buildInputEntity(chatId) as BigInt.BigInteger,\n }), true);\n}\n\nexport function leaveChannel({\n channelId, accessHash,\n}: {\n channelId: string; accessHash: string;\n}) {\n return invokeRequest(new GramJs.channels.LeaveChannel({\n channel: buildInputEntity(channelId, accessHash) as GramJs.InputChannel,\n }), true);\n}\n\nexport function deleteChannel({\n channelId, accessHash,\n}: {\n channelId: string; accessHash: string;\n}) {\n return invokeRequest(new GramJs.channels.DeleteChannel({\n channel: buildInputEntity(channelId, accessHash) as GramJs.InputChannel,\n }), true);\n}\n\nexport async function createGroupChat({\n title, users,\n}: {\n title: string; users: ApiUser[];\n}): Promise {\n const result = await invokeRequest(new GramJs.messages.CreateChat({\n title,\n users: users.map(({ id, accessHash }) => buildInputEntity(id, accessHash)) as GramJs.InputUser[],\n }), true, true);\n\n // `createChat` can return a lot of different update types according to docs,\n // but currently chat creation returns only `Updates` type.\n // Errors are added to catch unexpected cases in future testing\n if (!(result instanceof GramJs.Updates)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected chat creation update', result);\n }\n return undefined;\n }\n\n const newChat = result.chats[0];\n if (!newChat || !(newChat instanceof GramJs.Chat)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Created chat not found', result);\n }\n return undefined;\n }\n\n return buildApiChatFromPreview(newChat);\n}\n\nexport async function editChatPhoto({\n chatId, accessHash, photo,\n}: {\n chatId: string; accessHash?: string; photo: File;\n}) {\n const uploadedPhoto = await uploadFile(photo);\n const inputEntity = buildInputEntity(chatId, accessHash);\n\n return invokeRequest(\n inputEntity instanceof GramJs.InputChannel\n ? new GramJs.channels.EditPhoto({\n channel: inputEntity as GramJs.InputChannel,\n photo: new GramJs.InputChatUploadedPhoto({\n file: uploadedPhoto,\n }),\n })\n : new GramJs.messages.EditChatPhoto({\n chatId: inputEntity as BigInt.BigInteger,\n photo: new GramJs.InputChatUploadedPhoto({\n file: uploadedPhoto,\n }),\n }),\n true,\n );\n}\n\nexport async function toggleChatPinned({\n chat,\n shouldBePinned,\n}: {\n chat: ApiChat;\n shouldBePinned: boolean;\n}) {\n const { id, accessHash } = chat;\n\n const isActionSuccessful = await invokeRequest(new GramJs.messages.ToggleDialogPin({\n peer: new GramJs.InputDialogPeer({\n peer: buildInputPeer(id, accessHash),\n }),\n pinned: shouldBePinned || undefined,\n }));\n\n if (isActionSuccessful) {\n onUpdate({\n '@type': 'updateChatPinned',\n id: chat.id,\n isPinned: shouldBePinned,\n });\n }\n}\n\nexport function toggleChatArchived({\n chat, folderId,\n}: {\n chat: ApiChat; folderId: number;\n}) {\n const { id, accessHash } = chat;\n\n return invokeRequest(new GramJs.folders.EditPeerFolders({\n folderPeers: [new GramJs.InputFolderPeer({\n peer: buildInputPeer(id, accessHash),\n folderId,\n })],\n }), true);\n}\n\nexport async function fetchChatFolders() {\n const result = await invokeRequest(new GramJs.messages.GetDialogFilters());\n\n if (!result) {\n return undefined;\n }\n\n return {\n byId: buildCollectionByKey(result.map(buildApiChatFolder), 'id') as Record,\n orderedIds: result.map(({ id }) => id),\n };\n}\n\nexport async function fetchRecommendedChatFolders() {\n const results = await invokeRequest(new GramJs.messages.GetSuggestedDialogFilters());\n\n if (!results) {\n return undefined;\n }\n\n return results.map(buildApiChatFolderFromSuggested);\n}\n\nexport async function editChatFolder({\n id,\n folderUpdate,\n}: {\n id: number;\n folderUpdate: ApiChatFolder;\n}) {\n const filter = buildFilterFromApiFolder(folderUpdate);\n\n const isActionSuccessful = await invokeRequest(new GramJs.messages.UpdateDialogFilter({\n id,\n filter,\n }));\n\n if (isActionSuccessful) {\n onUpdate({\n '@type': 'updateChatFolder',\n id,\n folder: folderUpdate,\n });\n }\n}\n\nexport async function deleteChatFolder(id: number) {\n const isActionSuccessful = await invokeRequest(new GramJs.messages.UpdateDialogFilter({\n id,\n filter: undefined,\n }));\n const recommendedChatFolders = await fetchRecommendedChatFolders();\n\n if (isActionSuccessful) {\n onUpdate({\n '@type': 'updateChatFolder',\n id,\n folder: undefined,\n });\n }\n if (recommendedChatFolders) {\n onUpdate({\n '@type': 'updateRecommendedChatFolders',\n folders: recommendedChatFolders,\n });\n }\n}\n\nexport async function toggleDialogUnread({\n chat, hasUnreadMark,\n}: {\n chat: ApiChat; hasUnreadMark: boolean | undefined;\n}) {\n const { id, accessHash } = chat;\n\n const isActionSuccessful = await invokeRequest(new GramJs.messages.MarkDialogUnread({\n peer: new GramJs.InputDialogPeer({\n peer: buildInputPeer(id, accessHash),\n }),\n unread: hasUnreadMark || undefined,\n }));\n\n if (isActionSuccessful) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat: { hasUnreadMark },\n });\n }\n}\n\nexport async function getChatByUsername(username: string) {\n const result = await invokeRequest(new GramJs.contacts.ResolveUsername({\n username,\n }));\n\n if (!result) {\n return undefined;\n }\n\n const { users, chats } = result;\n\n const chat = chats.length\n ? buildApiChatFromPreview(chats[0])\n : buildApiChatFromPreview(users[0]);\n\n if (!chat) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return chat;\n}\n\nexport function togglePreHistoryHidden({\n chat, isEnabled,\n}: { chat: ApiChat; isEnabled: boolean }) {\n const { id, accessHash } = chat;\n const channel = buildInputEntity(id, accessHash);\n\n return invokeRequest(new GramJs.channels.TogglePreHistoryHidden({\n channel: channel as GramJs.InputChannel,\n enabled: isEnabled,\n }), true);\n}\n\nexport function updateChatDefaultBannedRights({\n chat, bannedRights,\n}: { chat: ApiChat; bannedRights: ApiChatBannedRights }) {\n const { id, accessHash } = chat;\n const peer = buildInputPeer(id, accessHash);\n\n return invokeRequest(new GramJs.messages.EditChatDefaultBannedRights({\n peer,\n bannedRights: buildChatBannedRights(bannedRights),\n }), true);\n}\n\nexport function updateChatMemberBannedRights({\n chat, user, bannedRights, untilDate,\n}: { chat: ApiChat; user: ApiUser; bannedRights: ApiChatBannedRights; untilDate?: number }) {\n const channel = buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel;\n const participant = buildInputPeer(user.id, user.accessHash) as GramJs.InputUser;\n\n return invokeRequest(new GramJs.channels.EditBanned({\n channel,\n participant,\n bannedRights: buildChatBannedRights(bannedRights, untilDate),\n }), true);\n}\n\nexport function updateChatAdmin({\n chat, user, adminRights, customTitle = '',\n}: { chat: ApiChat; user: ApiUser; adminRights: ApiChatAdminRights; customTitle: string }) {\n const channel = buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel;\n const userId = buildInputEntity(user.id, user.accessHash) as GramJs.InputUser;\n\n return invokeRequest(new GramJs.channels.EditAdmin({\n channel,\n userId,\n adminRights: buildChatAdminRights(adminRights),\n rank: customTitle,\n }), true);\n}\n\nexport async function updateChatTitle(chat: ApiChat, title: string) {\n const inputEntity = buildInputEntity(chat.id, chat.accessHash);\n await invokeRequest(\n inputEntity instanceof GramJs.InputChannel\n ? new GramJs.channels.EditTitle({\n channel: inputEntity as GramJs.InputChannel,\n title,\n }) : new GramJs.messages.EditChatTitle({\n chatId: inputEntity as BigInt.BigInteger,\n title,\n }),\n true,\n );\n}\n\nexport async function updateChatAbout(chat: ApiChat, about: string) {\n const result = await invokeRequest(new GramJs.messages.EditChatAbout({\n peer: buildInputPeer(chat.id, chat.accessHash),\n about,\n }));\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'updateChatFullInfo',\n id: chat.id,\n fullInfo: {\n about,\n },\n });\n}\n\nexport function toggleSignatures({\n chat, isEnabled,\n}: { chat: ApiChat; isEnabled: boolean }) {\n const { id, accessHash } = chat;\n const channel = buildInputEntity(id, accessHash);\n\n return invokeRequest(new GramJs.channels.ToggleSignatures({\n channel: channel as GramJs.InputChannel,\n enabled: isEnabled,\n }), true);\n}\n\ntype ChannelMembersFilter =\n 'kicked'\n | 'admin'\n | 'recent';\n\nexport async function fetchMembers(\n chatId: string,\n accessHash: string,\n memberFilter: ChannelMembersFilter = 'recent',\n offset?: number,\n) {\n let filter: GramJs.TypeChannelParticipantsFilter;\n\n switch (memberFilter) {\n case 'kicked':\n filter = new GramJs.ChannelParticipantsKicked({ q: '' });\n break;\n case 'admin':\n filter = new GramJs.ChannelParticipantsAdmins();\n break;\n default:\n filter = new GramJs.ChannelParticipantsRecent();\n break;\n }\n\n const result = await invokeRequest(new GramJs.channels.GetParticipants({\n channel: buildInputEntity(chatId, accessHash) as GramJs.InputChannel,\n filter,\n offset,\n limit: MEMBERS_LOAD_SLICE,\n }));\n\n if (!result || result instanceof GramJs.channels.ChannelParticipantsNotModified) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return {\n members: buildChatMembers(result),\n users: result.users.map(buildApiUser).filter(Boolean as any),\n };\n}\n\nexport async function fetchGroupsForDiscussion() {\n const result = await invokeRequest(new GramJs.channels.GetGroupsForDiscussion());\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return result.chats.map((chat) => buildApiChatFromPreview(chat));\n}\n\nexport function setDiscussionGroup({\n channel,\n chat,\n}: {\n channel: ApiChat;\n chat?: ApiChat;\n}) {\n return invokeRequest(new GramJs.channels.SetDiscussionGroup({\n broadcast: buildInputPeer(channel.id, channel.accessHash),\n group: chat ? buildInputPeer(chat.id, chat.accessHash) : new GramJs.InputChannelEmpty(),\n }));\n}\n\nexport async function migrateChat(chat: ApiChat) {\n const result = await invokeRequest(\n new GramJs.messages.MigrateChat({ chatId: buildInputEntity(chat.id) as BigInt.BigInteger }), true,\n );\n\n // `migrateChat` can return a lot of different update types according to docs,\n // but currently chat migrations returns only `Updates` type.\n // Errors are added to catch unexpected cases in future testing\n if (!result || !(result instanceof GramJs.Updates)) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error('Unexpected channel creation update', result);\n }\n\n return undefined;\n }\n\n updateLocalDb(result);\n\n return buildApiChatFromPreview(result.chats[1]);\n}\n\nexport async function openChatByInvite(hash: string) {\n const result = await invokeRequest(new GramJs.messages.CheckChatInvite({ hash }));\n\n if (!result) {\n return undefined;\n }\n\n let chat: ApiChat | undefined;\n\n if (result instanceof GramJs.ChatInvite) {\n const {\n photo, participantsCount, title, channel, requestNeeded, about,\n } = result;\n\n if (photo instanceof GramJs.Photo) {\n addPhotoToLocalDb(result.photo);\n }\n\n onUpdate({\n '@type': 'showInvite',\n data: {\n title,\n about,\n hash,\n participantsCount,\n isChannel: channel,\n isRequestNeeded: requestNeeded,\n ...(photo instanceof GramJs.Photo && { photo: buildApiPhoto(photo) }),\n },\n });\n } else {\n chat = buildApiChatFromPreview(result.chat);\n\n if (chat) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat,\n });\n }\n }\n\n if (!chat) {\n return undefined;\n }\n\n return { chatId: chat.id };\n}\n\nexport function addChatMembers(chat: ApiChat, users: ApiUser[], noErrorUpdate = false) {\n try {\n if (chat.type === 'chatTypeChannel' || chat.type === 'chatTypeSuperGroup') {\n return invokeRequest(new GramJs.channels.InviteToChannel({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n users: users.map((user) => buildInputEntity(user.id, user.accessHash)) as GramJs.InputUser[],\n }), true, noErrorUpdate);\n }\n\n return Promise.all(users.map((user) => {\n return invokeRequest(new GramJs.messages.AddChatUser({\n chatId: buildInputEntity(chat.id) as BigInt.BigInteger,\n userId: buildInputEntity(user.id, user.accessHash) as GramJs.InputUser,\n }), true, noErrorUpdate);\n }));\n } catch (err) {\n // `noErrorUpdate` will cause an exception which we don't want either\n return undefined;\n }\n}\n\nexport function deleteChatMember(chat: ApiChat, user: ApiUser) {\n if (chat.type === 'chatTypeChannel' || chat.type === 'chatTypeSuperGroup') {\n return updateChatMemberBannedRights({\n chat,\n user,\n bannedRights: {\n viewMessages: true,\n sendMessages: true,\n sendMedia: true,\n sendStickers: true,\n sendGifs: true,\n sendGames: true,\n sendInline: true,\n embedLinks: true,\n sendPolls: true,\n changeInfo: true,\n inviteUsers: true,\n pinMessages: true,\n },\n untilDate: MAX_INT_32,\n });\n } else {\n return invokeRequest(new GramJs.messages.DeleteChatUser({\n chatId: buildInputEntity(chat.id) as BigInt.BigInteger,\n userId: buildInputEntity(user.id, user.accessHash) as GramJs.InputUser,\n }), true);\n }\n}\n\nfunction preparePeers(\n result: GramJs.messages.Dialogs | GramJs.messages.DialogsSlice | GramJs.messages.PeerDialogs,\n) {\n const store: Record = {};\n\n result.chats.forEach((chat) => {\n store[`chat${chat.id}`] = chat;\n });\n\n result.users.forEach((user) => {\n store[`user${user.id}`] = user;\n });\n\n return store;\n}\n\nfunction updateLocalDb(result: (\n GramJs.messages.Dialogs | GramJs.messages.DialogsSlice | GramJs.messages.PeerDialogs |\n GramJs.messages.ChatFull | GramJs.contacts.Found |\n GramJs.contacts.ResolvedPeer | GramJs.channels.ChannelParticipants |\n GramJs.messages.Chats | GramJs.messages.ChatsSlice | GramJs.TypeUpdates\n)) {\n if ('users' in result) {\n addEntitiesWithPhotosToLocalDb(result.users);\n }\n\n if ('chats' in result) {\n addEntitiesWithPhotosToLocalDb(result.chats);\n }\n\n if ('messages' in result) {\n result.messages.forEach((message) => {\n if (message instanceof GramJs.Message && isMessageWithMedia(message)) {\n addMessageToLocalDb(message);\n }\n });\n }\n}\n\nexport async function importChatInvite({ hash }: { hash: string }) {\n const updates = await invokeRequest(new GramJs.messages.ImportChatInvite({ hash }), true);\n if (!(updates instanceof GramJs.Updates) || !updates.chats.length) {\n return undefined;\n }\n\n return buildApiChatFromPreview(updates.chats[0]);\n}\n\nexport function toggleIsProtected({\n chat, isProtected,\n}: { chat: ApiChat; isProtected: boolean }) {\n const { id, accessHash } = chat;\n\n return invokeRequest(new GramJs.messages.ToggleNoForwards({\n peer: buildInputPeer(id, accessHash),\n enabled: isProtected,\n }), true);\n}\n","import { pause } from './schedulers';\n\n// Polyfill for Safari: `File` is not available in web worker\nif (typeof File === 'undefined') {\n // eslint-disable-next-line no-global-assign, no-restricted-globals, func-names\n self.File = class extends Blob {\n name: string;\n\n constructor(fileBits: BlobPart[], fileName: string, options?: FilePropertyBag) {\n if (options) {\n const { type, ...rest } = options;\n super(fileBits, { type });\n Object.assign(this, rest);\n } else {\n super(fileBits);\n }\n\n this.name = fileName;\n }\n } as typeof File;\n}\n\nexport function dataUriToBlob(dataUri: string) {\n const arr = dataUri.split(',');\n const mime = arr[0].match(/:(.*?);/)![1];\n const bstr = atob(arr[1]);\n let n = bstr.length;\n const u8arr = new Uint8Array(n);\n\n while (n--) {\n u8arr[n] = bstr.charCodeAt(n);\n }\n\n return new Blob([u8arr], { type: mime });\n}\n\nexport function blobToDataUri(blob: Blob): Promise {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n\n reader.onload = (e: ProgressEvent) => {\n const { result } = e.target || {};\n if (typeof result === 'string') {\n resolve(result);\n }\n\n reject(new Error('Failed to read blob'));\n };\n\n reader.onerror = reject;\n reader.readAsDataURL(blob);\n });\n}\n\nexport function blobToFile(blob: Blob, fileName: string) {\n return new File([blob], fileName, {\n lastModified: Date.now(),\n type: blob.type,\n });\n}\n\nexport function preloadImage(url: string): Promise {\n return new Promise((resolve, reject) => {\n const img = new Image();\n img.onload = () => resolve(img);\n img.onerror = reject;\n img.src = url;\n });\n}\n\nexport function preloadVideo(url: string): Promise {\n return new Promise((resolve, reject) => {\n const video = document.createElement('video');\n video.volume = 0;\n video.onloadedmetadata = () => resolve(video);\n video.onerror = reject;\n video.src = url;\n });\n}\n\nexport async function createPosterForVideo(url: string): Promise {\n const video = await preloadVideo(url);\n\n return Promise.race([\n pause(2000) as Promise,\n new Promise((resolve, reject) => {\n video.onseeked = () => {\n if (!video.videoWidth || !video.videoHeight) {\n resolve(undefined);\n }\n\n const canvas = document.createElement('canvas');\n canvas.width = video.videoWidth;\n canvas.height = video.videoHeight;\n const ctx = canvas.getContext('2d')!;\n ctx.drawImage(video, 0, 0);\n resolve(canvas.toDataURL('image/jpeg'));\n };\n video.onerror = reject;\n video.currentTime = Math.min(video.duration, 1);\n }),\n ]);\n}\n\nexport async function fetchBlob(blobUrl: string) {\n const response = await fetch(blobUrl);\n return response.blob();\n}\n\nexport async function fetchFile(blobUrl: string, fileName: string) {\n const blob = await fetchBlob(blobUrl);\n return blobToFile(blob, fileName);\n}\n\nexport function imgToCanvas(img: HTMLImageElement) {\n const canvas = document.createElement('canvas');\n canvas.width = img.width;\n canvas.height = img.height;\n\n const ctx = canvas.getContext('2d')!;\n ctx.drawImage(img, 0, 0);\n\n return canvas;\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n ApiChat,\n ApiAttachment,\n ApiMessage,\n OnApiUpdate,\n ApiMessageSearchType,\n ApiUser,\n ApiSticker,\n ApiVideo,\n ApiNewPoll,\n ApiMessageEntity,\n ApiOnProgress,\n ApiThreadInfo,\n MAIN_THREAD_ID,\n MESSAGE_DELETED,\n ApiGlobalMessageSearchType,\n ApiReportReason,\n ApiSponsoredMessage,\n ApiSendMessageAction,\n ApiContact,\n} from '../../types';\n\nimport {\n ALL_FOLDER_ID,\n DEBUG,\n PINNED_MESSAGES_LIMIT,\n SUPPORTED_IMAGE_CONTENT_TYPES,\n SUPPORTED_VIDEO_CONTENT_TYPES,\n} from '../../../config';\nimport { invokeRequest, uploadFile } from './client';\nimport {\n buildApiMessage,\n buildLocalMessage,\n buildWebPage,\n buildLocalForwardedMessage,\n buildApiSponsoredMessage,\n} from '../apiBuilders/messages';\nimport { buildApiUser } from '../apiBuilders/users';\nimport {\n buildInputEntity,\n buildInputPeer,\n generateRandomBigInt,\n getEntityTypeById,\n buildInputMediaDocument,\n buildInputPoll,\n buildMtpMessageEntity,\n isMessageWithMedia,\n isServiceMessageWithMedia,\n buildInputReportReason,\n buildSendMessageAction,\n} from '../gramjsBuilders';\nimport localDb from '../localDb';\nimport { buildApiChatFromPreview } from '../apiBuilders/chats';\nimport { fetchFile } from '../../../util/files';\nimport {\n addEntitiesWithPhotosToLocalDb,\n addMessageToLocalDb,\n deserializeBytes,\n resolveMessageApiChatId,\n} from '../helpers';\nimport { interpolateArray } from '../../../util/waveform';\nimport { requestChatUpdate } from './chats';\nimport { buildApiPeerId, getApiChatIdFromMtpPeer } from '../apiBuilders/peers';\n\nconst FAST_SEND_TIMEOUT = 1000;\nconst INPUT_WAVEFORM_LENGTH = 63;\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function fetchMessages({\n chat,\n threadId,\n ...pagination\n}: {\n chat: ApiChat;\n threadId?: number;\n offsetId?: number;\n addOffset?: number;\n limit: number;\n}) {\n const RequestClass = threadId === MAIN_THREAD_ID ? GramJs.messages.GetHistory : GramJs.messages.GetReplies;\n let result;\n\n try {\n result = await invokeRequest(new RequestClass({\n peer: buildInputPeer(chat.id, chat.accessHash),\n ...(threadId !== MAIN_THREAD_ID && {\n msgId: threadId,\n }),\n ...pagination,\n }), undefined, true);\n } catch (err) {\n if (err.message === 'CHANNEL_PRIVATE') {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat: {\n isRestricted: true,\n },\n });\n }\n }\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter(Boolean as any);\n const threadInfos = messages.map(({ threadInfo }) => threadInfo).filter(Boolean as any);\n\n return {\n messages,\n users,\n chats,\n threadInfos,\n };\n}\n\nexport async function fetchMessage({ chat, messageId }: { chat: ApiChat; messageId: number }) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n\n let result;\n try {\n result = await invokeRequest(\n isChannel\n ? new GramJs.channels.GetMessages({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n id: [new GramJs.InputMessageID({ id: messageId })],\n })\n : new GramJs.messages.GetMessages({\n id: [new GramJs.InputMessageID({ id: messageId })],\n }),\n undefined,\n true,\n );\n } catch (err) {\n const { message } = err;\n\n // When fetching messages for the bot @replies, there may be situations when the user was banned\n // in the comment group or this group was deleted\n if (message !== 'CHANNEL_PRIVATE') {\n onUpdate({\n '@type': 'error',\n error: {\n message,\n isSlowMode: false,\n hasErrorKey: true,\n },\n });\n }\n }\n\n if (!result || result instanceof GramJs.messages.MessagesNotModified) {\n return undefined;\n }\n\n const mtpMessage = result.messages[0];\n if (!mtpMessage) {\n return undefined;\n }\n\n if (mtpMessage instanceof GramJs.MessageEmpty) {\n return MESSAGE_DELETED;\n }\n\n const message = mtpMessage && buildApiMessage(mtpMessage);\n if (!message) {\n return undefined;\n }\n\n if (mtpMessage instanceof GramJs.Message) {\n addMessageToLocalDb(mtpMessage);\n }\n\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n\n return { message, users };\n}\n\nlet queue = Promise.resolve();\n\nexport function sendMessage(\n {\n chat,\n text,\n entities,\n replyingTo,\n attachment,\n sticker,\n gif,\n poll,\n contact,\n isSilent,\n scheduledAt,\n groupedId,\n noWebPage,\n sendAs,\n serverTimeOffset,\n }: {\n chat: ApiChat;\n text?: string;\n entities?: ApiMessageEntity[];\n replyingTo?: number;\n attachment?: ApiAttachment;\n sticker?: ApiSticker;\n gif?: ApiVideo;\n poll?: ApiNewPoll;\n contact?: ApiContact;\n isSilent?: boolean;\n scheduledAt?: number;\n groupedId?: string;\n noWebPage?: boolean;\n sendAs?: ApiUser | ApiChat;\n serverTimeOffset?: number;\n },\n onProgress?: ApiOnProgress,\n) {\n const localMessage = buildLocalMessage(\n chat, text, entities, replyingTo, attachment, sticker, gif, poll, contact, groupedId, scheduledAt,\n sendAs, serverTimeOffset,\n );\n onUpdate({\n '@type': localMessage.isScheduled ? 'newScheduledMessage' : 'newMessage',\n id: localMessage.id,\n chatId: chat.id,\n message: localMessage,\n });\n\n // This is expected to arrive after `updateMessageSendSucceeded` which replaces the local ID,\n // so in most cases this will be simply ignored\n setTimeout(() => {\n onUpdate({\n '@type': localMessage.isScheduled ? 'updateScheduledMessage' : 'updateMessage',\n id: localMessage.id,\n chatId: chat.id,\n message: {\n sendingState: 'messageSendingStatePending',\n },\n });\n }, FAST_SEND_TIMEOUT);\n\n const randomId = generateRandomBigInt();\n localDb.localMessages[String(randomId)] = localMessage;\n\n if (groupedId) {\n return sendGroupedMedia({\n chat, text, entities, replyingTo, attachment: attachment!, groupedId, isSilent, scheduledAt,\n }, randomId, localMessage, onProgress);\n }\n\n const prevQueue = queue;\n queue = (async () => {\n let media: GramJs.TypeInputMedia | undefined;\n if (attachment) {\n try {\n media = await uploadMedia(localMessage, attachment, onProgress!);\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n\n await prevQueue;\n\n return;\n }\n } else if (sticker) {\n media = buildInputMediaDocument(sticker);\n } else if (gif) {\n media = buildInputMediaDocument(gif);\n } else if (poll) {\n media = buildInputPoll(poll, randomId);\n } else if (contact) {\n media = new GramJs.InputMediaContact({\n phoneNumber: contact.phoneNumber,\n firstName: contact.firstName,\n lastName: contact.lastName,\n vcard: '',\n });\n }\n\n await prevQueue;\n\n const RequestClass = media ? GramJs.messages.SendMedia : GramJs.messages.SendMessage;\n\n await invokeRequest(new RequestClass({\n clearDraft: true,\n message: text || '',\n entities: entities ? entities.map(buildMtpMessageEntity) : undefined,\n peer: buildInputPeer(chat.id, chat.accessHash),\n randomId,\n ...(isSilent && { silent: isSilent }),\n ...(scheduledAt && { scheduleDate: scheduledAt }),\n ...(replyingTo && { replyToMsgId: replyingTo }),\n ...(media && { media }),\n ...(noWebPage && { noWebpage: noWebPage }),\n ...(sendAs && { sendAs: buildInputPeer(sendAs.id, sendAs.accessHash) }),\n }), true);\n })();\n\n return queue;\n}\n\nconst groupedUploads: Record;\n}> = {};\n\nfunction sendGroupedMedia(\n {\n chat,\n text,\n entities,\n replyingTo,\n attachment,\n groupedId,\n isSilent,\n scheduledAt,\n sendAs,\n }: {\n chat: ApiChat;\n text?: string;\n entities?: ApiMessageEntity[];\n replyingTo?: number;\n attachment: ApiAttachment;\n groupedId: string;\n isSilent?: boolean;\n scheduledAt?: number;\n sendAs?: ApiUser | ApiChat;\n },\n randomId: GramJs.long,\n localMessage: ApiMessage,\n onProgress?: ApiOnProgress,\n) {\n let groupIndex = -1;\n if (!groupedUploads[groupedId]) {\n groupedUploads[groupedId] = {\n counter: 0,\n singleMediaByIndex: {},\n };\n }\n\n groupIndex = groupedUploads[groupedId].counter++;\n\n const prevQueue = queue;\n queue = (async () => {\n let media;\n try {\n media = await uploadMedia(localMessage, attachment, onProgress!);\n } catch (err) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n\n groupedUploads[groupedId].counter--;\n\n await prevQueue;\n\n return;\n }\n\n const inputMedia = await fetchInputMedia(\n buildInputPeer(chat.id, chat.accessHash),\n media as GramJs.InputMediaUploadedPhoto | GramJs.InputMediaUploadedDocument,\n );\n\n await prevQueue;\n\n if (!inputMedia) {\n groupedUploads[groupedId].counter--;\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('Failed to upload grouped media');\n }\n\n return;\n }\n\n groupedUploads[groupedId].singleMediaByIndex[groupIndex] = new GramJs.InputSingleMedia({\n media: inputMedia,\n randomId,\n message: text || '',\n entities: entities ? entities.map(buildMtpMessageEntity) : undefined,\n });\n\n if (Object.keys(groupedUploads[groupedId].singleMediaByIndex).length < groupedUploads[groupedId].counter) {\n return;\n }\n\n const { singleMediaByIndex } = groupedUploads[groupedId];\n delete groupedUploads[groupedId];\n\n await invokeRequest(new GramJs.messages.SendMultiMedia({\n clearDraft: true,\n peer: buildInputPeer(chat.id, chat.accessHash),\n multiMedia: Object.values(singleMediaByIndex), // Object keys are usually ordered\n replyToMsgId: replyingTo,\n ...(isSilent && { silent: isSilent }),\n ...(scheduledAt && { scheduleDate: scheduledAt }),\n ...(sendAs && { sendAs: buildInputPeer(sendAs.id, sendAs.accessHash) }),\n }), true);\n })();\n\n return queue;\n}\n\nasync function fetchInputMedia(\n peer: GramJs.TypeInputPeer,\n uploadedMedia: GramJs.InputMediaUploadedPhoto | GramJs.InputMediaUploadedDocument,\n) {\n const messageMedia = await invokeRequest(new GramJs.messages.UploadMedia({\n peer,\n media: uploadedMedia,\n }));\n\n if ((\n messageMedia instanceof GramJs.MessageMediaPhoto\n && messageMedia.photo\n && messageMedia.photo instanceof GramJs.Photo)\n ) {\n const { photo: { id, accessHash, fileReference } } = messageMedia;\n\n return new GramJs.InputMediaPhoto({\n id: new GramJs.InputPhoto({ id, accessHash, fileReference }),\n });\n }\n\n if ((\n messageMedia instanceof GramJs.MessageMediaDocument\n && messageMedia.document\n && messageMedia.document instanceof GramJs.Document)\n ) {\n const { document: { id, accessHash, fileReference } } = messageMedia;\n\n return new GramJs.InputMediaDocument({\n id: new GramJs.InputDocument({ id, accessHash, fileReference }),\n });\n }\n\n return undefined;\n}\n\nexport async function editMessage({\n chat,\n message,\n text,\n entities,\n noWebPage,\n serverTimeOffset,\n}: {\n chat: ApiChat;\n message: ApiMessage;\n text: string;\n entities?: ApiMessageEntity[];\n noWebPage?: boolean;\n serverTimeOffset: number;\n}) {\n const isScheduled = message.date * 1000 > Date.now() + serverTimeOffset * 1000;\n const messageUpdate: Partial = {\n content: {\n ...message.content,\n ...(text && {\n text: {\n text,\n entities,\n },\n }),\n },\n };\n\n onUpdate({\n '@type': isScheduled ? 'updateScheduledMessage' : 'updateMessage',\n id: message.id,\n chatId: chat.id,\n message: messageUpdate,\n });\n\n // TODO Revise intersecting with scheduled\n localDb.localMessages[message.id] = { ...message, ...messageUpdate };\n\n const mtpEntities = entities && entities.map(buildMtpMessageEntity);\n\n await invokeRequest(new GramJs.messages.EditMessage({\n message: text || '',\n entities: mtpEntities,\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: message.id,\n ...(isScheduled && { scheduleDate: message.date }),\n ...(noWebPage && { noWebpage: noWebPage }),\n }), true);\n}\n\nexport async function rescheduleMessage({\n chat,\n message,\n scheduledAt,\n}: {\n chat: ApiChat;\n message: ApiMessage;\n scheduledAt: number;\n}) {\n await invokeRequest(new GramJs.messages.EditMessage({\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: message.id,\n scheduleDate: scheduledAt,\n }), true);\n}\n\nasync function uploadMedia(localMessage: ApiMessage, attachment: ApiAttachment, onProgress: ApiOnProgress) {\n const {\n filename, blobUrl, mimeType, quick, voice,\n } = attachment;\n\n const file = await fetchFile(blobUrl, filename);\n const patchedOnProgress: ApiOnProgress = (progress) => {\n if (onProgress.isCanceled) {\n patchedOnProgress.isCanceled = true;\n } else {\n onProgress(progress, localMessage.id);\n }\n };\n const inputFile = await uploadFile(file, patchedOnProgress);\n\n const attributes: GramJs.TypeDocumentAttribute[] = [new GramJs.DocumentAttributeFilename({ fileName: filename })];\n if (quick) {\n if (SUPPORTED_IMAGE_CONTENT_TYPES.has(mimeType)) {\n return new GramJs.InputMediaUploadedPhoto({ file: inputFile });\n }\n\n if (SUPPORTED_VIDEO_CONTENT_TYPES.has(mimeType)) {\n const { width, height, duration } = quick;\n if (duration !== undefined) {\n attributes.push(new GramJs.DocumentAttributeVideo({\n duration,\n w: width,\n h: height,\n supportsStreaming: true,\n }));\n }\n }\n }\n\n if (voice) {\n const { duration, waveform } = voice;\n const { data: inputWaveform } = interpolateArray(waveform, INPUT_WAVEFORM_LENGTH);\n attributes.push(new GramJs.DocumentAttributeAudio({\n voice: true,\n duration,\n waveform: Buffer.from(inputWaveform),\n }));\n }\n\n return new GramJs.InputMediaUploadedDocument({\n file: inputFile,\n mimeType,\n attributes,\n });\n}\n\nexport async function pinMessage({\n chat, messageId, isUnpin, isOneSide, isSilent,\n}: { chat: ApiChat; messageId: number; isUnpin: boolean; isOneSide: boolean; isSilent: boolean }) {\n await invokeRequest(new GramJs.messages.UpdatePinnedMessage({\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: messageId,\n ...(isUnpin && { unpin: true }),\n ...(isOneSide && { pmOneside: true }),\n ...(isSilent && { silent: true }),\n }), true);\n}\n\nexport async function unpinAllMessages({ chat }: { chat: ApiChat }) {\n await invokeRequest(new GramJs.messages.UnpinAllMessages({\n peer: buildInputPeer(chat.id, chat.accessHash),\n }), true);\n}\n\nexport async function deleteMessages({\n chat, messageIds, shouldDeleteForAll,\n}: {\n chat: ApiChat; messageIds: number[]; shouldDeleteForAll?: boolean;\n}) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n\n const result = await invokeRequest(\n isChannel\n ? new GramJs.channels.DeleteMessages({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n id: messageIds,\n })\n : new GramJs.messages.DeleteMessages({\n id: messageIds,\n ...(shouldDeleteForAll && { revoke: true }),\n }),\n );\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'deleteMessages',\n ids: messageIds,\n ...(isChannel && { chatId: chat.id }),\n });\n}\n\nexport async function deleteScheduledMessages({\n chat, messageIds,\n}: {\n chat: ApiChat; messageIds: number[];\n}) {\n const result = await invokeRequest(\n new GramJs.messages.DeleteScheduledMessages({\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: messageIds,\n }),\n );\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'deleteScheduledMessages',\n ids: messageIds,\n chatId: chat.id,\n });\n}\n\nexport async function deleteHistory({\n chat, shouldDeleteForAll, maxId,\n}: {\n chat: ApiChat; shouldDeleteForAll?: boolean; maxId?: number;\n}) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n const result = await invokeRequest(\n isChannel\n ? new GramJs.channels.DeleteHistory({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n maxId,\n })\n : new GramJs.messages.DeleteHistory({\n peer: buildInputPeer(chat.id, chat.accessHash),\n ...(shouldDeleteForAll && { revoke: true }),\n ...(!shouldDeleteForAll && { just_clear: true }),\n maxId,\n }),\n );\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'deleteHistory',\n chatId: chat.id,\n });\n}\n\nexport async function reportMessages({\n peer, messageIds, reason, description,\n}: {\n peer: ApiChat | ApiUser; messageIds: number[]; reason: ApiReportReason; description?: string;\n}) {\n const result = await invokeRequest(new GramJs.messages.Report({\n peer: buildInputPeer(peer.id, peer.accessHash),\n id: messageIds,\n reason: buildInputReportReason(reason),\n message: description,\n }));\n\n return result;\n}\n\nexport async function sendMessageAction({\n peer, threadId, action,\n}: {\n peer: ApiChat | ApiUser; threadId?: number; action: ApiSendMessageAction;\n}) {\n const gramAction = buildSendMessageAction(action);\n if (!gramAction) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.warn('Unsupported message action', action);\n }\n return undefined;\n }\n\n const result = await invokeRequest(new GramJs.messages.SetTyping({\n peer: buildInputPeer(peer.id, peer.accessHash),\n topMsgId: threadId,\n action: gramAction,\n }));\n return result;\n}\n\nexport async function markMessageListRead({\n chat, threadId, maxId, serverTimeOffset,\n}: {\n chat: ApiChat; threadId: number; maxId?: number; serverTimeOffset: number;\n}) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n\n if (isChannel && threadId === MAIN_THREAD_ID) {\n await invokeRequest(new GramJs.channels.ReadHistory({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n maxId,\n }));\n } else if (isChannel) {\n await invokeRequest(new GramJs.messages.ReadDiscussion({\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: threadId,\n readMaxId: maxId,\n }));\n } else {\n await invokeRequest(new GramJs.messages.ReadHistory({\n peer: buildInputPeer(chat.id, chat.accessHash),\n maxId,\n }));\n }\n\n if (threadId === MAIN_THREAD_ID) {\n void requestChatUpdate({ chat, serverTimeOffset, noLastMessage: true });\n } else {\n void requestThreadInfoUpdate({ chat, threadId });\n }\n}\n\nexport async function markMessagesRead({\n chat, messageIds,\n}: {\n chat: ApiChat; messageIds: number[];\n}) {\n const isChannel = getEntityTypeById(chat.id) === 'channel';\n\n await invokeRequest(\n isChannel\n ? new GramJs.channels.ReadMessageContents({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n id: messageIds,\n })\n : new GramJs.messages.ReadMessageContents({\n id: messageIds,\n }),\n );\n\n onUpdate({\n ...(isChannel ? {\n '@type': 'updateChannelMessages',\n channelId: chat.id,\n } : {\n '@type': 'updateCommonBoxMessages',\n }),\n ids: messageIds,\n messageUpdate: {\n hasUnreadMention: false,\n isMediaUnread: false,\n },\n });\n}\n\nexport async function requestThreadInfoUpdate({\n chat, threadId,\n}: {\n chat: ApiChat; threadId: number;\n}) {\n const [topMessageResult, repliesResult] = await Promise.all([\n invokeRequest(new GramJs.messages.GetDiscussionMessage({\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: threadId,\n })),\n invokeRequest(new GramJs.messages.GetReplies({\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: threadId,\n offsetId: 1,\n addOffset: -1,\n limit: 1,\n })),\n ]);\n\n if (!topMessageResult || !topMessageResult.messages.length) {\n return undefined;\n }\n\n const discussionChatId = resolveMessageApiChatId(topMessageResult.messages[0]);\n if (!discussionChatId) {\n return undefined;\n }\n\n onUpdate({\n '@type': 'updateThreadInfo',\n chatId: discussionChatId,\n threadId,\n threadInfo: {\n threadId,\n topMessageId: topMessageResult.messages[topMessageResult.messages.length - 1].id,\n lastReadInboxMessageId: topMessageResult.readInboxMaxId,\n messagesCount: (repliesResult instanceof GramJs.messages.ChannelMessages) ? repliesResult.count : undefined,\n },\n firstMessageId: repliesResult && 'messages' in repliesResult && repliesResult.messages.length\n ? repliesResult.messages[0].id\n : undefined,\n });\n\n const chats = topMessageResult.chats.map((c) => buildApiChatFromPreview(c)).filter(Boolean as any);\n chats.forEach((newChat) => {\n onUpdate({\n '@type': 'updateChat',\n id: newChat.id,\n chat: newChat,\n noTopChatsRequest: true,\n });\n });\n\n return {\n discussionChatId,\n };\n}\n\nexport async function searchMessagesLocal({\n chatOrUser, type, query, topMessageId, minDate, maxDate, ...pagination\n}: {\n chatOrUser: ApiChat | ApiUser;\n type?: ApiMessageSearchType | ApiGlobalMessageSearchType;\n query?: string;\n topMessageId?: number;\n offsetId?: number;\n addOffset?: number;\n limit: number;\n minDate?: number;\n maxDate?: number;\n}) {\n let filter;\n switch (type) {\n case 'media':\n filter = new GramJs.InputMessagesFilterPhotoVideo();\n break;\n case 'documents':\n filter = new GramJs.InputMessagesFilterDocument();\n break;\n case 'links':\n filter = new GramJs.InputMessagesFilterUrl();\n break;\n case 'audio':\n filter = new GramJs.InputMessagesFilterMusic();\n break;\n case 'voice':\n filter = new GramJs.InputMessagesFilterRoundVoice();\n break;\n case 'profilePhoto':\n filter = new GramJs.InputMessagesFilterChatPhotos();\n break;\n case 'text':\n default: {\n filter = new GramJs.InputMessagesFilterEmpty();\n }\n }\n\n const result = await invokeRequest(new GramJs.messages.Search({\n peer: buildInputPeer(chatOrUser.id, chatOrUser.accessHash),\n filter,\n q: query || '',\n topMsgId: topMessageId,\n minDate,\n maxDate,\n ...pagination,\n }));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n\n let totalCount = messages.length;\n let nextOffsetId: number | undefined;\n if (result instanceof GramJs.messages.MessagesSlice || result instanceof GramJs.messages.ChannelMessages) {\n totalCount = result.count;\n\n if (messages.length) {\n nextOffsetId = messages[messages.length - 1].id;\n }\n }\n\n return {\n messages,\n users,\n totalCount,\n nextOffsetId,\n };\n}\n\nexport async function searchMessagesGlobal({\n query, offsetRate = 0, limit, type = 'text', minDate, maxDate,\n}: {\n query: string;\n offsetRate?: number;\n limit: number;\n type?: ApiGlobalMessageSearchType;\n minDate?: number;\n maxDate?: number;\n}) {\n let filter;\n switch (type) {\n case 'media':\n filter = new GramJs.InputMessagesFilterPhotoVideo();\n break;\n case 'documents':\n filter = new GramJs.InputMessagesFilterDocument();\n break;\n case 'links':\n filter = new GramJs.InputMessagesFilterUrl();\n break;\n case 'audio':\n filter = new GramJs.InputMessagesFilterMusic();\n break;\n case 'voice':\n filter = new GramJs.InputMessagesFilterRoundVoice();\n break;\n case 'text':\n default: {\n if (!query && !(maxDate && minDate)) {\n return undefined;\n }\n\n filter = new GramJs.InputMessagesFilterEmpty();\n }\n }\n\n const result = await invokeRequest(new GramJs.messages.SearchGlobal({\n q: query,\n offsetRate,\n offsetPeer: new GramJs.InputPeerEmpty(),\n limit,\n filter,\n folderId: ALL_FOLDER_ID,\n minDate,\n maxDate,\n }));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb({\n chats: result.chats,\n users: result.users,\n messages: result.messages,\n } as GramJs.messages.Messages);\n\n const chats = result.chats.map((user) => buildApiChatFromPreview(user)).filter(Boolean as any);\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n\n let totalCount = messages.length;\n let nextRate: number | undefined;\n if (result instanceof GramJs.messages.MessagesSlice || result instanceof GramJs.messages.ChannelMessages) {\n totalCount = result.count;\n\n if (messages.length) {\n nextRate = messages[messages.length - 1].id;\n }\n }\n\n return {\n messages,\n users,\n chats,\n totalCount,\n nextRate: 'nextRate' in result && result.nextRate ? result.nextRate : nextRate,\n };\n}\n\nexport async function fetchWebPagePreview({ message }: { message: string }) {\n const preview = await invokeRequest(new GramJs.messages.GetWebPagePreview({\n message,\n }));\n\n return preview && buildWebPage(preview);\n}\n\nexport async function sendPollVote({\n chat, messageId, options,\n}: {\n chat: ApiChat;\n messageId: number;\n options: string[];\n}) {\n const { id, accessHash } = chat;\n\n await invokeRequest(new GramJs.messages.SendVote({\n peer: buildInputPeer(id, accessHash),\n msgId: messageId,\n options: options.map(deserializeBytes),\n }), true);\n}\n\nexport async function loadPollOptionResults({\n chat, messageId, option, offset, limit, shouldResetVoters,\n}: {\n chat: ApiChat;\n messageId: number;\n option?: string;\n offset?: string;\n limit?: number;\n shouldResetVoters?: boolean;\n}) {\n const { id, accessHash } = chat;\n\n const result = await invokeRequest(new GramJs.messages.GetPollVotes({\n peer: buildInputPeer(id, accessHash),\n id: messageId,\n ...(option && { option: deserializeBytes(option) }),\n ...(offset && { offset }),\n ...(limit && { limit }),\n }));\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb({\n chats: [] as GramJs.TypeChat[],\n users: result.users,\n messages: [] as GramJs.Message[],\n } as GramJs.messages.Messages);\n\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const votes = result.votes.map((vote) => ({\n userId: vote.userId,\n date: vote.date,\n }));\n\n return {\n count: result.count,\n votes,\n users,\n nextOffset: result.nextOffset,\n shouldResetVoters,\n };\n}\n\nexport async function forwardMessages({\n fromChat,\n toChat,\n messages,\n serverTimeOffset,\n isSilent,\n scheduledAt,\n sendAs,\n}: {\n fromChat: ApiChat;\n toChat: ApiChat;\n messages: ApiMessage[];\n serverTimeOffset: number;\n isSilent?: boolean;\n scheduledAt?: number;\n sendAs?: ApiUser | ApiChat;\n}) {\n const messageIds = messages.map(({ id }) => id);\n const randomIds = messages.map(generateRandomBigInt);\n\n messages.forEach((message, index) => {\n const localMessage = buildLocalForwardedMessage(toChat, message, serverTimeOffset, scheduledAt);\n localDb.localMessages[String(randomIds[index])] = localMessage;\n\n onUpdate({\n '@type': localMessage.isScheduled ? 'newScheduledMessage' : 'newMessage',\n id: localMessage.id,\n chatId: toChat.id,\n message: localMessage,\n });\n });\n\n await invokeRequest(new GramJs.messages.ForwardMessages({\n fromPeer: buildInputPeer(fromChat.id, fromChat.accessHash),\n toPeer: buildInputPeer(toChat.id, toChat.accessHash),\n randomId: randomIds,\n id: messageIds,\n ...(isSilent && { sil2ent: isSilent }),\n ...(scheduledAt && { scheduleDate: scheduledAt }),\n ...(sendAs && { sendAs: buildInputPeer(sendAs.id, sendAs.accessHash) }),\n }), true);\n}\n\nexport async function findFirstMessageIdAfterDate({\n chat,\n timestamp,\n}: {\n chat: ApiChat;\n timestamp: number;\n}) {\n const result = await invokeRequest(new GramJs.messages.GetHistory({\n peer: buildInputPeer(chat.id, chat.accessHash),\n offsetDate: timestamp,\n addOffset: -1,\n limit: 1,\n }));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages || !result.messages.length\n ) {\n return undefined;\n }\n\n return result.messages[0].id;\n}\n\nexport async function fetchScheduledHistory({ chat }: { chat: ApiChat }) {\n const { id, accessHash } = chat;\n\n const result = await invokeRequest(new GramJs.messages.GetScheduledHistory({\n peer: buildInputPeer(id, accessHash),\n }));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n\n return {\n messages,\n };\n}\n\nexport async function sendScheduledMessages({ chat, ids }: { chat: ApiChat; ids: number[] }) {\n const { id, accessHash } = chat;\n\n await invokeRequest(new GramJs.messages.SendScheduledMessages({\n peer: buildInputPeer(id, accessHash),\n id: ids,\n }), true);\n}\n\nfunction updateLocalDb(result: (\n GramJs.messages.MessagesSlice | GramJs.messages.Messages | GramJs.messages.ChannelMessages |\n GramJs.messages.DiscussionMessage | GramJs.messages.SponsoredMessages\n)) {\n result.users.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[buildApiPeerId(user.id, 'user')] = user;\n }\n });\n\n result.chats.forEach((chat) => {\n if (chat instanceof GramJs.Chat || chat instanceof GramJs.Channel) {\n localDb.chats[buildApiPeerId(chat.id, chat instanceof GramJs.Chat ? 'chat' : 'channel')] = chat;\n }\n });\n\n result.messages.forEach((message) => {\n if ((message instanceof GramJs.Message && isMessageWithMedia(message))\n || (message instanceof GramJs.MessageService && isServiceMessageWithMedia(message))\n ) {\n addMessageToLocalDb(message);\n }\n });\n}\n\nexport async function fetchPinnedMessages({ chat }: { chat: ApiChat }) {\n const result = await invokeRequest(new GramJs.messages.Search(\n {\n peer: buildInputPeer(chat.id, chat.accessHash),\n filter: new GramJs.InputMessagesFilterPinned(),\n q: '',\n limit: PINNED_MESSAGES_LIMIT,\n },\n ));\n\n if (\n !result\n || result instanceof GramJs.messages.MessagesNotModified\n || !result.messages\n ) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiMessage).filter(Boolean as any);\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter(Boolean as any);\n\n return {\n messages,\n users,\n chats,\n };\n}\n\nexport async function fetchSeenBy({ chat, messageId }: { chat: ApiChat; messageId: number }) {\n const result = await invokeRequest(new GramJs.messages.GetMessageReadParticipants({\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: messageId,\n }));\n\n return result ? result.map(String) : undefined;\n}\n\nexport async function fetchSendAs({\n chat,\n}: {\n chat: ApiChat;\n}) {\n const result = await invokeRequest(new GramJs.channels.GetSendAs({\n peer: buildInputPeer(chat.id, chat.accessHash),\n }));\n\n if (!result) {\n return undefined;\n }\n\n addEntitiesWithPhotosToLocalDb(result.users);\n addEntitiesWithPhotosToLocalDb(result.chats);\n\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter(Boolean as any);\n\n return {\n users,\n chats,\n ids: result.peers.map(getApiChatIdFromMtpPeer),\n };\n}\n\nexport function saveDefaultSendAs({\n sendAs, chat,\n}: {\n sendAs: ApiChat | ApiUser; chat: ApiChat;\n}) {\n return invokeRequest(new GramJs.messages.SaveDefaultSendAs({\n peer: buildInputPeer(chat.id, chat.accessHash),\n sendAs: buildInputPeer(sendAs.id, sendAs.accessHash),\n }));\n}\n\nexport async function fetchSponsoredMessages({ chat }: { chat: ApiChat }) {\n const result = await invokeRequest(new GramJs.channels.GetSponsoredMessages({\n channel: buildInputPeer(chat.id, chat.accessHash),\n }));\n\n if (!result || !result.messages.length) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n const messages = result.messages.map(buildApiSponsoredMessage).filter(Boolean as any);\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter(Boolean as any);\n\n return {\n messages,\n users,\n chats,\n };\n}\n\nexport async function viewSponsoredMessage({ chat, random }: { chat: ApiChat; random: string }) {\n await invokeRequest(new GramJs.channels.ViewSponsoredMessage({\n channel: buildInputPeer(chat.id, chat.accessHash),\n randomId: deserializeBytes(random),\n }));\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport {\n OnApiUpdate, ApiUser, ApiChat, ApiPhoto,\n} from '../../types';\n\nimport { COMMON_CHATS_LIMIT, PROFILE_PHOTOS_LIMIT } from '../../../config';\nimport { invokeRequest } from './client';\nimport { searchMessagesLocal } from './messages';\nimport {\n buildInputEntity,\n buildInputPeer,\n buildInputContact,\n buildMtpPeerId,\n getEntityTypeById,\n} from '../gramjsBuilders';\nimport { buildApiUser, buildApiUserFromFull, buildApiUsersAndStatuses } from '../apiBuilders/users';\nimport { buildApiChatFromPreview } from '../apiBuilders/chats';\nimport { buildApiPhoto } from '../apiBuilders/common';\nimport localDb from '../localDb';\nimport { addEntitiesWithPhotosToLocalDb, addPhotoToLocalDb } from '../helpers';\nimport { buildApiPeerId } from '../apiBuilders/peers';\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function fetchFullUser({\n id,\n accessHash,\n}: {\n id: string;\n accessHash?: string;\n}) {\n const input = buildInputEntity(id, accessHash);\n if (!(input instanceof GramJs.InputUser)) {\n return;\n }\n\n const fullInfo = await invokeRequest(new GramJs.users.GetFullUser({ id: input }));\n\n if (!fullInfo) {\n return;\n }\n\n const userWithFullInfo = buildApiUserFromFull(fullInfo);\n\n onUpdate({\n '@type': 'updateUser',\n id,\n user: {\n fullInfo: userWithFullInfo.fullInfo,\n },\n });\n}\n\nexport async function fetchCommonChats(id: string, accessHash?: string, maxId?: string) {\n const commonChats = await invokeRequest(new GramJs.messages.GetCommonChats({\n userId: buildInputEntity(id, accessHash) as GramJs.InputUser,\n maxId: maxId ? buildMtpPeerId(maxId, getEntityTypeById(maxId)) : undefined,\n limit: COMMON_CHATS_LIMIT,\n }));\n\n if (!commonChats) {\n return undefined;\n }\n\n updateLocalDb(commonChats);\n\n const chatIds: string[] = [];\n const chats: ApiChat[] = [];\n\n commonChats.chats.forEach((mtpChat) => {\n const chat = buildApiChatFromPreview(mtpChat);\n\n if (chat) {\n chats.push(chat);\n chatIds.push(chat.id);\n }\n });\n\n return { chats, chatIds, isFullyLoaded: chatIds.length < COMMON_CHATS_LIMIT };\n}\n\nexport async function fetchNearestCountry() {\n const dcInfo = await invokeRequest(new GramJs.help.GetNearestDc());\n\n return dcInfo?.country;\n}\n\nexport async function fetchTopUsers() {\n const topPeers = await invokeRequest(new GramJs.contacts.GetTopPeers({\n correspondents: true,\n }));\n if (!(topPeers instanceof GramJs.contacts.TopPeers)) {\n return undefined;\n }\n\n const users = topPeers.users.map(buildApiUser).filter((user) => !!user && !user.isSelf) as ApiUser[];\n const ids = users.map(({ id }) => id);\n\n return {\n ids,\n users,\n };\n}\n\nexport async function fetchContactList() {\n const result = await invokeRequest(new GramJs.contacts.GetContacts({ hash: BigInt('0') }));\n if (!result || result instanceof GramJs.contacts.ContactsNotModified) {\n return undefined;\n }\n\n result.users.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[buildApiPeerId(user.id, 'user')] = user;\n }\n });\n\n return {\n users: result.users.map(buildApiUser).filter(Boolean as any),\n chats: result.users.map((user) => buildApiChatFromPreview(user)).filter(Boolean as any),\n };\n}\n\nexport async function fetchUsers({ users }: { users: ApiUser[] }) {\n const result = await invokeRequest(new GramJs.users.GetUsers({\n id: users.map(({ id, accessHash }) => buildInputPeer(id, accessHash)),\n }));\n if (!result || !result.length) {\n return undefined;\n }\n\n result.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[buildApiPeerId(user.id, 'user')] = user;\n }\n });\n\n return buildApiUsersAndStatuses(result);\n}\n\nexport function updateContact({\n phone,\n firstName,\n lastName,\n}: {\n phone?: string;\n firstName?: string;\n lastName?: string;\n}) {\n return invokeRequest(new GramJs.contacts.ImportContacts({\n contacts: [buildInputContact({\n phone: phone || '',\n firstName: firstName || '',\n lastName: lastName || '',\n })],\n }));\n}\n\nexport function addContact({\n id,\n accessHash,\n phoneNumber = '',\n firstName = '',\n lastName = '',\n}: {\n id: string;\n accessHash?: string;\n phoneNumber?: string;\n firstName?: string;\n lastName?: string;\n}) {\n return invokeRequest(new GramJs.contacts.AddContact({\n id: buildInputEntity(id, accessHash) as GramJs.InputUser,\n firstName,\n lastName,\n phone: phoneNumber,\n }), true);\n}\n\nexport async function deleteContact({\n id,\n accessHash,\n}: {\n id: string;\n accessHash?: string;\n}) {\n const input = buildInputEntity(id, accessHash);\n if (!(input instanceof GramJs.InputUser)) {\n return;\n }\n\n const result = await invokeRequest(new GramJs.contacts.DeleteContacts({ id: [input] }));\n\n if (!result) {\n return;\n }\n\n onUpdate({\n '@type': 'deleteContact',\n id,\n });\n}\n\nexport async function fetchProfilePhotos(user?: ApiUser, chat?: ApiChat) {\n if (user) {\n const { id, accessHash } = user;\n\n const result = await invokeRequest(new GramJs.photos.GetUserPhotos({\n userId: buildInputEntity(id, accessHash) as GramJs.InputUser,\n limit: PROFILE_PHOTOS_LIMIT,\n offset: 0,\n maxId: BigInt('0'),\n }));\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return {\n photos: result.photos\n .filter((photo): photo is GramJs.Photo => photo instanceof GramJs.Photo)\n .map(buildApiPhoto),\n };\n }\n\n const result = await searchMessagesLocal({\n chatOrUser: chat!,\n type: 'profilePhoto',\n limit: PROFILE_PHOTOS_LIMIT,\n });\n\n if (!result) {\n return undefined;\n }\n\n const { messages, users } = result;\n\n return {\n photos: messages.map((message) => message.content.action!.photo).filter(Boolean as any),\n users,\n };\n}\n\nfunction updateLocalDb(result: (GramJs.photos.Photos | GramJs.photos.PhotosSlice | GramJs.messages.Chats)) {\n if ('chats' in result) {\n addEntitiesWithPhotosToLocalDb(result.chats);\n }\n\n if ('photos' in result) {\n result.photos.forEach(addPhotoToLocalDb);\n }\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport { ApiSticker, ApiVideo, OnApiUpdate } from '../../types';\n\nimport { invokeRequest } from './client';\nimport { buildStickerFromDocument, buildStickerSet, buildStickerSetCovered } from '../apiBuilders/symbols';\nimport { buildInputStickerSet, buildInputDocument, buildInputStickerSetShortName } from '../gramjsBuilders';\nimport { buildVideoFromDocument } from '../apiBuilders/messages';\nimport { RECENT_STICKERS_LIMIT } from '../../../config';\n\nimport localDb from '../localDb';\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function fetchStickerSets({ hash = '0' }: { hash?: string }) {\n const allStickers = await invokeRequest(new GramJs.messages.GetAllStickers({ hash: BigInt(hash) }));\n\n if (!allStickers || allStickers instanceof GramJs.messages.AllStickersNotModified) {\n return undefined;\n }\n\n allStickers.sets.forEach((stickerSet) => {\n if (stickerSet.thumbs?.length) {\n localDb.stickerSets[String(stickerSet.id)] = stickerSet;\n }\n });\n\n return {\n hash: String(allStickers.hash),\n sets: allStickers.sets.map(buildStickerSet),\n };\n}\n\nexport async function fetchRecentStickers({ hash = '0' }: { hash?: string }) {\n const result = await invokeRequest(new GramJs.messages.GetRecentStickers({ hash: BigInt(hash) }));\n\n if (!result || result instanceof GramJs.messages.RecentStickersNotModified) {\n return undefined;\n }\n\n return {\n hash: String(result.hash),\n stickers: processStickerResult(result.stickers.slice(0, RECENT_STICKERS_LIMIT)),\n };\n}\n\nexport async function fetchFavoriteStickers({ hash = '0' }: { hash?: string }) {\n const result = await invokeRequest(new GramJs.messages.GetFavedStickers({ hash: BigInt(hash) }));\n\n if (!result || result instanceof GramJs.messages.FavedStickersNotModified) {\n return undefined;\n }\n\n return {\n hash: String(result.hash),\n stickers: processStickerResult(result.stickers),\n };\n}\n\nexport async function fetchFeaturedStickers({ hash = '0' }: { hash?: string }) {\n const result = await invokeRequest(new GramJs.messages.GetFeaturedStickers({ hash: BigInt(hash) }));\n\n if (!result || result instanceof GramJs.messages.FeaturedStickersNotModified) {\n return undefined;\n }\n\n return {\n hash: String(result.hash),\n sets: result.sets.map(buildStickerSetCovered),\n };\n}\n\nexport async function faveSticker({\n sticker,\n unfave,\n}: {\n sticker: ApiSticker;\n unfave?: boolean;\n}) {\n const request = new GramJs.messages.FaveSticker({\n id: buildInputDocument(sticker),\n unfave,\n });\n\n const result = await invokeRequest(request);\n if (result) {\n onUpdate({\n '@type': 'updateFavoriteStickers',\n });\n }\n}\n\nexport async function fetchStickers(\n { stickerSetShortName, stickerSetId, accessHash }:\n { stickerSetShortName?: string; stickerSetId?: string; accessHash: string },\n) {\n const result = await invokeRequest(new GramJs.messages.GetStickerSet({\n stickerset: stickerSetId\n ? buildInputStickerSet(stickerSetId, accessHash)\n : buildInputStickerSetShortName(stickerSetShortName!),\n }));\n\n if (!(result instanceof GramJs.messages.StickerSet)) {\n return undefined;\n }\n\n return {\n set: buildStickerSet(result.set),\n stickers: processStickerResult(result.documents),\n packs: processStickerPackResult(result.packs),\n };\n}\n\nexport async function fetchAnimatedEmojis() {\n const result = await invokeRequest(new GramJs.messages.GetStickerSet({\n stickerset: new GramJs.InputStickerSetAnimatedEmoji(),\n }));\n\n if (!(result instanceof GramJs.messages.StickerSet)) {\n return undefined;\n }\n\n return {\n set: buildStickerSet(result.set),\n stickers: processStickerResult(result.documents),\n };\n}\n\nexport async function searchStickers({ query, hash = '0' }: { query: string; hash?: string }) {\n const result = await invokeRequest(new GramJs.messages.SearchStickerSets({\n q: query,\n hash: BigInt(hash),\n }));\n\n if (!result || result instanceof GramJs.messages.FoundStickerSetsNotModified) {\n return undefined;\n }\n\n return {\n hash: String(result.hash),\n sets: result.sets.map(buildStickerSetCovered),\n };\n}\n\nexport async function fetchSavedGifs({ hash = '0' }: { hash?: string }) {\n const result = await invokeRequest(new GramJs.messages.GetSavedGifs({ hash: BigInt(hash) }));\n\n if (!result || result instanceof GramJs.messages.SavedGifsNotModified) {\n return undefined;\n }\n\n return {\n hash: String(result.hash),\n gifs: processGifResult(result.gifs),\n };\n}\n\nexport async function installStickerSet({ stickerSetId, accessHash }: { stickerSetId: string; accessHash: string }) {\n const result = await invokeRequest(new GramJs.messages.InstallStickerSet({\n stickerset: buildInputStickerSet(stickerSetId, accessHash),\n }));\n\n if (result) {\n onUpdate({\n '@type': 'updateStickerSet',\n id: stickerSetId,\n stickerSet: { installedDate: Date.now() },\n });\n }\n}\n\nexport async function uninstallStickerSet({ stickerSetId, accessHash }: { stickerSetId: string; accessHash: string }) {\n const result = await invokeRequest(new GramJs.messages.UninstallStickerSet({\n stickerset: buildInputStickerSet(stickerSetId, accessHash),\n }));\n\n if (result) {\n onUpdate({\n '@type': 'updateStickerSet',\n id: stickerSetId,\n stickerSet: { installedDate: undefined },\n });\n }\n}\n\nlet inputGifBot: GramJs.InputUser | undefined;\n\nexport async function searchGifs({ query, offset = '' }: { query: string; offset?: string }) {\n if (!inputGifBot) {\n const config = await invokeRequest(new GramJs.help.GetConfig());\n if (!config) {\n return undefined;\n }\n\n const resolvedPeer = await invokeRequest(new GramJs.contacts.ResolveUsername({\n username: config.gifSearchUsername,\n }));\n if (!resolvedPeer || !(resolvedPeer.users[0] instanceof GramJs.User)) {\n return undefined;\n }\n\n inputGifBot = new GramJs.InputUser({\n userId: (resolvedPeer.peer as GramJs.PeerUser).userId,\n accessHash: resolvedPeer.users[0].accessHash!,\n });\n }\n\n const result = await invokeRequest(new GramJs.messages.GetInlineBotResults({\n bot: inputGifBot,\n peer: new GramJs.InputPeerEmpty(),\n query,\n offset,\n }));\n if (!result) {\n return undefined;\n }\n\n const documents = result.results\n .map((foundGif) => {\n if (foundGif instanceof GramJs.BotInlineMediaResult) {\n return foundGif.document;\n }\n\n return undefined;\n })\n .filter(Boolean as any);\n\n return {\n nextOffset: result.nextOffset,\n gifs: processGifResult(documents),\n };\n}\n\nexport async function fetchStickersForEmoji({\n emoji, hash = '0',\n}: { emoji: string; hash?: string }) {\n const result = await invokeRequest(new GramJs.messages.GetStickers({\n emoticon: emoji,\n hash: BigInt(hash),\n }));\n\n if (!result || result instanceof GramJs.messages.StickersNotModified) {\n return undefined;\n }\n\n return {\n stickers: processStickerResult(result.stickers),\n hash: String(result.hash),\n };\n}\n\nexport async function fetchEmojiKeywords({ language, fromVersion }: {\n language: string;\n fromVersion?: number;\n}) {\n const result = await invokeRequest(new GramJs.messages.GetEmojiKeywordsDifference({\n langCode: language,\n fromVersion,\n }));\n\n if (!result) {\n return undefined;\n }\n\n return {\n language: result.langCode,\n version: result.version,\n keywords: result.keywords.reduce((acc, emojiKeyword) => {\n acc[emojiKeyword.keyword] = emojiKeyword.emoticons;\n\n return acc;\n }, {} as Record),\n };\n}\n\nfunction processStickerResult(stickers: GramJs.TypeDocument[]) {\n return stickers\n .map((document) => {\n if (document instanceof GramJs.Document) {\n const sticker = buildStickerFromDocument(document);\n if (sticker) {\n localDb.documents[String(document.id)] = document;\n\n return sticker;\n }\n }\n\n return undefined;\n })\n .filter(Boolean as any);\n}\n\nfunction processStickerPackResult(packs: GramJs.StickerPack[]) {\n return packs.reduce((acc, { emoticon, documents }) => {\n acc[emoticon] = documents.map((documentId) => buildStickerFromDocument(\n localDb.documents[String(documentId)],\n )).filter(Boolean as any);\n return acc;\n }, {} as Record);\n}\n\nfunction processGifResult(gifs: GramJs.TypeDocument[]) {\n return gifs\n .map((document) => {\n if (document instanceof GramJs.Document) {\n const gif = buildVideoFromDocument(document);\n if (gif) {\n localDb.documents[String(document.id)] = document;\n\n return gif;\n }\n }\n\n return undefined;\n })\n .filter(Boolean as any);\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\n\nimport { invokeRequest } from './client';\nimport { buildInputEntity, buildInputPeer } from '../gramjsBuilders';\nimport { ApiChat, OnApiUpdate } from '../../types';\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function checkChatUsername(\n { username }: { username: string },\n) {\n try {\n const result = await invokeRequest(new GramJs.channels.CheckUsername({\n channel: new GramJs.InputChannelEmpty(),\n username,\n }), undefined, true);\n\n return result!;\n } catch (err) {\n return false;\n }\n}\n\nexport async function setChatUsername(\n { chat, username }: { chat: ApiChat; username: string },\n) {\n const result = await invokeRequest(new GramJs.channels.UpdateUsername({\n channel: buildInputEntity(chat.id, chat.accessHash) as GramJs.InputChannel,\n username,\n }));\n\n if (result) {\n onUpdate({\n '@type': 'updateChat',\n id: chat.id,\n chat: { username },\n });\n }\n}\n\nexport async function updatePrivateLink({\n chat, usageLimit, expireDate,\n}: {\n chat: ApiChat; usageLimit?: number; expireDate?: number;\n}) {\n const result = await invokeRequest(new GramJs.messages.ExportChatInvite({\n peer: buildInputPeer(chat.id, chat.accessHash),\n usageLimit,\n expireDate,\n }));\n\n if (!result) {\n return undefined;\n }\n\n onUpdate({\n '@type': 'updateChatFullInfo',\n id: chat.id,\n fullInfo: {\n inviteLink: result.link,\n },\n });\n\n return result.link;\n}\n","import { Api as GramJs, errors } from '../../../lib/gramjs';\n\nimport { OnApiUpdate } from '../../types';\n\nimport { DEBUG } from '../../../config';\nimport { invokeRequest, updateTwoFaSettings } from './client';\n\nconst ApiErrors: { [k: string]: string } = {\n EMAIL_UNCONFIRMED: 'Email unconfirmed',\n EMAIL_HASH_EXPIRED: 'Email hash expired',\n NEW_SALT_INVALID: 'The new salt is invalid',\n NEW_SETTINGS_INVALID: 'The new password settings are invalid',\n CODE_INVALID: 'Invalid Code',\n PASSWORD_HASH_INVALID: 'Invalid Password',\n};\n\nconst emailCodeController: {\n resolve?: Function;\n reject?: Function;\n} = {};\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function getPasswordInfo() {\n const result = await invokeRequest(new GramJs.account.GetPassword());\n if (!result) {\n return undefined;\n }\n\n const { hint, hasPassword } = result;\n\n return { hint, hasPassword };\n}\n\nfunction onRequestEmailCode(length: number) {\n onUpdate({\n '@type': 'updateTwoFaStateWaitCode',\n length,\n });\n\n return new Promise((resolve, reject) => {\n emailCodeController.resolve = resolve;\n emailCodeController.reject = reject;\n });\n}\n\nexport async function checkPassword(currentPassword: string) {\n try {\n await updateTwoFaSettings({ isCheckPassword: true, currentPassword });\n\n return true;\n } catch (err) {\n onError(err);\n\n return false;\n }\n}\n\nexport async function clearPassword(currentPassword: string) {\n try {\n await updateTwoFaSettings({ currentPassword });\n\n return true;\n } catch (err) {\n onError(err);\n\n return false;\n }\n}\n\nexport async function updatePassword(currentPassword: string, password: string, hint?: string, email?: string) {\n try {\n await updateTwoFaSettings({\n currentPassword,\n newPassword: password,\n hint,\n email,\n emailCodeCallback: onRequestEmailCode,\n onEmailCodeError: onError,\n });\n\n return true;\n } catch (err) {\n onError(err);\n\n return false;\n }\n}\n\nexport async function updateRecoveryEmail(currentPassword: string, email: string) {\n try {\n await updateTwoFaSettings({\n currentPassword,\n newPassword: currentPassword,\n email,\n emailCodeCallback: onRequestEmailCode,\n onEmailCodeError: onError,\n });\n\n return true;\n } catch (err) {\n onError(err);\n\n return false;\n }\n}\n\nexport function provideRecoveryEmailCode(code: string) {\n emailCodeController.resolve!(code);\n}\n\nfunction onError(err: Error) {\n let message: string;\n\n if (err instanceof errors.FloodWaitError) {\n const hours = Math.ceil(Number(err.seconds) / 60 / 60);\n message = `Too many attempts. Try again in ${hours > 1 ? `${hours} hours` : 'an hour'}`;\n } else {\n message = ApiErrors[err.message];\n }\n\n if (!message) {\n message = 'Unexpected Error';\n\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n }\n\n onUpdate({\n '@type': 'updateTwoFaError',\n message,\n });\n}\n","import { JoinGroupCallPayload } from '../../../lib/secret-sauce';\nimport {\n ApiChat, ApiUser, OnApiUpdate, ApiGroupCall,\n} from '../../types';\nimport { Api as GramJs } from '../../../lib/gramjs';\n\nimport { invokeRequest } from './client';\nimport { buildInputGroupCall, buildInputPeer, generateRandomInt } from '../gramjsBuilders';\nimport {\n buildApiGroupCall,\n buildApiGroupCallParticipant,\n\n} from '../apiBuilders/calls';\nimport { buildApiUser } from '../apiBuilders/users';\nimport { buildApiChatFromPreview } from '../apiBuilders/chats';\nimport { addEntitiesWithPhotosToLocalDb } from '../helpers';\nimport { GROUP_CALL_PARTICIPANTS_LIMIT } from '../../../config';\n\nlet onUpdate: OnApiUpdate;\n\nexport function init(_onUpdate: OnApiUpdate) {\n onUpdate = _onUpdate;\n}\n\nexport async function getGroupCall({\n call,\n}: {\n call: Partial;\n}) {\n const result = await invokeRequest(new GramJs.phone.GetGroupCall({\n call: buildInputGroupCall(call),\n }));\n\n if (!result) {\n return undefined;\n }\n\n addEntitiesWithPhotosToLocalDb(result.users);\n addEntitiesWithPhotosToLocalDb(result.chats);\n\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter(Boolean as any);\n\n return {\n groupCall: buildApiGroupCall(result.call),\n users,\n chats,\n };\n}\n\nexport function discardGroupCall({\n call,\n}: {\n call: ApiGroupCall;\n}) {\n return invokeRequest(new GramJs.phone.DiscardGroupCall({\n call: buildInputGroupCall(call),\n }), true);\n}\n\nexport function editGroupCallParticipant({\n call, participant, muted, presentationPaused, videoStopped, videoPaused, volume,\n raiseHand,\n}: {\n call: ApiGroupCall; participant: ApiUser; muted?: boolean; presentationPaused?: boolean;\n videoStopped?: boolean; videoPaused?: boolean; raiseHand?: boolean; volume?: number;\n}) {\n return invokeRequest(new GramJs.phone.EditGroupCallParticipant({\n call: buildInputGroupCall(call),\n participant: buildInputPeer(participant.id, participant.accessHash),\n ...(videoStopped !== undefined && { videoStopped }),\n ...(videoPaused !== undefined && { videoPaused }),\n ...(muted !== undefined && { muted }),\n ...(presentationPaused !== undefined && { presentationPaused }),\n ...(raiseHand !== undefined && { raiseHand }),\n ...(volume !== undefined && { volume }),\n }), true);\n}\n\nexport function editGroupCallTitle({\n groupCall, title,\n}: {\n groupCall: ApiGroupCall; title: string;\n}) {\n return invokeRequest(new GramJs.phone.EditGroupCallTitle({\n title,\n call: buildInputGroupCall(groupCall),\n }), true);\n}\n\nexport async function exportGroupCallInvite({\n call, canSelfUnmute,\n}: {\n call: ApiGroupCall; canSelfUnmute: boolean;\n}) {\n const result = await invokeRequest(new GramJs.phone.ExportGroupCallInvite({\n canSelfUnmute: canSelfUnmute || undefined,\n call: buildInputGroupCall(call),\n }));\n\n if (!result) {\n return undefined;\n }\n\n return result.link;\n}\n\nexport async function fetchGroupCallParticipants({\n call, offset,\n}: {\n call: ApiGroupCall; offset?: string;\n}) {\n const result = await invokeRequest(new GramJs.phone.GetGroupParticipants({\n call: buildInputGroupCall(call),\n ids: [],\n sources: [],\n offset: offset || '',\n limit: GROUP_CALL_PARTICIPANTS_LIMIT,\n }));\n\n if (!result) {\n return undefined;\n }\n\n addEntitiesWithPhotosToLocalDb(result.users);\n addEntitiesWithPhotosToLocalDb(result.chats);\n\n const users = result.users.map(buildApiUser).filter(Boolean as any);\n const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter(Boolean as any);\n\n onUpdate({\n '@type': 'updateGroupCallParticipants',\n groupCallId: call.id,\n participants: result.participants.map(buildApiGroupCallParticipant),\n nextOffset: result.nextOffset,\n });\n\n return {\n users, chats,\n };\n}\n\nexport function leaveGroupCall({\n call,\n}: {\n call: ApiGroupCall;\n}) {\n return invokeRequest(new GramJs.phone.LeaveGroupCall({\n call: buildInputGroupCall(call),\n }), true);\n}\n\nexport async function joinGroupCall({\n call, inviteHash, params,\n}: {\n call: ApiGroupCall; inviteHash?: string; params: JoinGroupCallPayload;\n}) {\n const result = await invokeRequest(new GramJs.phone.JoinGroupCall({\n call: buildInputGroupCall(call),\n joinAs: new GramJs.InputPeerSelf(),\n muted: true,\n videoStopped: true,\n params: new GramJs.DataJSON({\n data: JSON.stringify(params),\n }),\n inviteHash,\n }), true);\n\n if (!result) return undefined;\n\n if (result instanceof GramJs.Updates) {\n const update = result.updates.find((u) => u instanceof GramJs.UpdateGroupCall);\n if (!(update instanceof GramJs.UpdateGroupCall)) return undefined;\n\n return buildApiGroupCall(update.call);\n }\n\n return undefined;\n}\n\nexport async function createGroupCall({\n peer,\n}: {\n peer: ApiChat;\n}) {\n const randomId = generateRandomInt();\n const result = await invokeRequest(new GramJs.phone.CreateGroupCall({\n peer: buildInputPeer(peer.id, peer.accessHash),\n randomId,\n }), true);\n\n if (!result) return undefined;\n\n if (result instanceof GramJs.Updates) {\n const update = result.updates[0];\n if (update instanceof GramJs.UpdateGroupCall) {\n return buildApiGroupCall(update.call);\n }\n }\n\n return undefined;\n}\n\nexport function joinGroupCallPresentation({\n call, params,\n}: {\n call: ApiGroupCall; params: JoinGroupCallPayload;\n}) {\n return invokeRequest(new GramJs.phone.JoinGroupCallPresentation({\n call: buildInputGroupCall(call),\n params: new GramJs.DataJSON({\n data: JSON.stringify(params),\n }),\n }), true);\n}\n\nexport function toggleGroupCallStartSubscription({\n call, subscribed,\n}: {\n call: ApiGroupCall; subscribed: boolean;\n}) {\n return invokeRequest(new GramJs.phone.ToggleGroupCallStartSubscription({\n call: buildInputGroupCall(call),\n subscribed,\n }), true);\n}\n\nexport function leaveGroupCallPresentation({\n call,\n}: {\n call: ApiGroupCall;\n}) {\n return invokeRequest(new GramJs.phone.LeaveGroupCallPresentation({\n call: buildInputGroupCall(call),\n }), true);\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\n\nimport {\n ApiChat, ApiLangString, ApiLanguage, ApiNotifyException, ApiUser, ApiWallpaper,\n} from '../../types';\nimport { ApiPrivacyKey, InputPrivacyRules, LangCode } from '../../../types';\n\nimport { BLOCKED_LIST_LIMIT, DEFAULT_LANG_PACK, LANG_PACKS } from '../../../config';\nimport {\n buildApiWallpaper, buildApiSession, buildPrivacyRules, buildApiNotifyException, buildApiCountryList,\n} from '../apiBuilders/misc';\n\nimport { buildApiUser } from '../apiBuilders/users';\nimport { buildApiChatFromPreview } from '../apiBuilders/chats';\nimport { buildInputPrivacyKey, buildInputPeer, buildInputEntity } from '../gramjsBuilders';\nimport { invokeRequest, uploadFile, getClient } from './client';\nimport { omitVirtualClassFields } from '../apiBuilders/helpers';\nimport { buildCollectionByKey } from '../../../util/iteratees';\nimport { getServerTime } from '../../../util/serverTime';\nimport { buildApiPeerId, getApiChatIdFromMtpPeer } from '../apiBuilders/peers';\nimport localDb from '../localDb';\n\nconst MAX_INT_32 = 2 ** 31 - 1;\nconst BETA_LANG_CODES = ['ar', 'fa', 'id', 'ko', 'uz'];\n\nexport function updateProfile({\n firstName,\n lastName,\n about,\n}: {\n firstName?: string;\n lastName?: string;\n about?: string;\n}) {\n return invokeRequest(new GramJs.account.UpdateProfile({\n firstName: firstName || '',\n lastName: lastName || '',\n about: about || '',\n }));\n}\n\nexport function checkUsername(username: string) {\n return invokeRequest(new GramJs.account.CheckUsername({ username }));\n}\n\nexport function updateUsername(username: string) {\n return invokeRequest(new GramJs.account.UpdateUsername({ username }));\n}\n\nexport async function updateProfilePhoto(file: File) {\n const inputFile = await uploadFile(file);\n return invokeRequest(new GramJs.photos.UploadProfilePhoto({\n file: inputFile,\n }));\n}\n\nexport async function uploadProfilePhoto(file: File) {\n const inputFile = await uploadFile(file);\n await invokeRequest(new GramJs.photos.UploadProfilePhoto({\n file: inputFile,\n }));\n}\n\nexport async function fetchWallpapers() {\n const result = await invokeRequest(new GramJs.account.GetWallPapers({ hash: BigInt('0') }));\n\n if (!result || result instanceof GramJs.account.WallPapersNotModified) {\n return undefined;\n }\n\n const filteredWallpapers = result.wallpapers.filter((wallpaper) => {\n if (\n !(wallpaper instanceof GramJs.WallPaper)\n || !(wallpaper.document instanceof GramJs.Document)\n ) {\n return false;\n }\n\n return !wallpaper.pattern && wallpaper.document.mimeType !== 'application/x-tgwallpattern';\n }) as GramJs.WallPaper[];\n\n filteredWallpapers.forEach((wallpaper) => {\n localDb.documents[String(wallpaper.document.id)] = wallpaper.document as GramJs.Document;\n });\n\n return {\n wallpapers: filteredWallpapers.map(buildApiWallpaper).filter(Boolean as any),\n };\n}\n\nexport async function uploadWallpaper(file: File) {\n const inputFile = await uploadFile(file);\n\n const result = await invokeRequest(new GramJs.account.UploadWallPaper({\n file: inputFile,\n mimeType: file.type,\n settings: new GramJs.WallPaperSettings(),\n }));\n\n if (!result || !(result instanceof GramJs.WallPaper)) {\n return undefined;\n }\n\n const wallpaper = buildApiWallpaper(result);\n if (!wallpaper) {\n return undefined;\n }\n\n localDb.documents[String(result.document.id)] = result.document as GramJs.Document;\n\n return { wallpaper };\n}\n\nexport async function fetchBlockedContacts() {\n const result = await invokeRequest(new GramJs.contacts.GetBlocked({\n limit: BLOCKED_LIST_LIMIT,\n }));\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return {\n users: result.users.map(buildApiUser).filter(Boolean as any),\n chats: result.chats.map((chat) => buildApiChatFromPreview(chat, undefined, true)).filter(Boolean as any),\n blockedIds: result.blocked.map((blocked) => getApiChatIdFromMtpPeer(blocked.peerId)),\n totalCount: result instanceof GramJs.contacts.BlockedSlice ? result.count : result.blocked.length,\n };\n}\n\nexport function blockContact(chatOrUserId: string, accessHash?: string) {\n return invokeRequest(new GramJs.contacts.Block({\n id: buildInputPeer(chatOrUserId, accessHash),\n }));\n}\n\nexport function unblockContact(chatOrUserId: string, accessHash?: string) {\n return invokeRequest(new GramJs.contacts.Unblock({\n id: buildInputPeer(chatOrUserId, accessHash),\n }));\n}\n\nexport async function fetchAuthorizations() {\n const result = await invokeRequest(new GramJs.account.GetAuthorizations());\n if (!result) {\n return undefined;\n }\n\n return result.authorizations.map(buildApiSession);\n}\n\nexport function terminateAuthorization(hash: string) {\n return invokeRequest(new GramJs.account.ResetAuthorization({ hash: BigInt(hash) }));\n}\n\nexport function terminateAllAuthorizations() {\n return invokeRequest(new GramJs.auth.ResetAuthorizations());\n}\n\nexport async function fetchNotificationExceptions({\n serverTimeOffset,\n}: { serverTimeOffset: number }) {\n const result = await invokeRequest(new GramJs.account.GetNotifyExceptions({ compareSound: true }));\n\n if (!(result instanceof GramJs.Updates || result instanceof GramJs.UpdatesCombined)) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return result.updates.reduce((acc, update) => {\n if (!(update instanceof GramJs.UpdateNotifySettings && update.peer instanceof GramJs.NotifyPeer)) {\n return acc;\n }\n\n acc.push(buildApiNotifyException(update.notifySettings, update.peer.peer, serverTimeOffset));\n\n return acc;\n }, [] as ApiNotifyException[]);\n}\n\nexport async function fetchNotificationSettings({\n serverTimeOffset,\n}: { serverTimeOffset: number }) {\n const [\n isMutedContactSignUpNotification,\n privateContactNotificationsSettings,\n groupNotificationsSettings,\n broadcastNotificationsSettings,\n ] = await Promise.all([\n invokeRequest(new GramJs.account.GetContactSignUpNotification()),\n invokeRequest(new GramJs.account.GetNotifySettings({\n peer: new GramJs.InputNotifyUsers(),\n })),\n invokeRequest(new GramJs.account.GetNotifySettings({\n peer: new GramJs.InputNotifyChats(),\n })),\n invokeRequest(new GramJs.account.GetNotifySettings({\n peer: new GramJs.InputNotifyBroadcasts(),\n })),\n ]);\n\n if (!privateContactNotificationsSettings || !groupNotificationsSettings || !broadcastNotificationsSettings) {\n return false;\n }\n\n const {\n silent: privateSilent, muteUntil: privateMuteUntil, showPreviews: privateShowPreviews,\n } = privateContactNotificationsSettings;\n const {\n silent: groupSilent, muteUntil: groupMuteUntil, showPreviews: groupShowPreviews,\n } = groupNotificationsSettings;\n const {\n silent: broadcastSilent, muteUntil: broadcastMuteUntil, showPreviews: broadcastShowPreviews,\n } = broadcastNotificationsSettings;\n\n return {\n hasContactJoinedNotifications: !isMutedContactSignUpNotification,\n hasPrivateChatsNotifications: !(\n privateSilent\n || (typeof privateMuteUntil === 'number' && getServerTime(serverTimeOffset) < privateMuteUntil)\n ),\n hasPrivateChatsMessagePreview: privateShowPreviews,\n hasGroupNotifications: !(\n groupSilent || (typeof groupMuteUntil === 'number'\n && getServerTime(serverTimeOffset) < groupMuteUntil)\n ),\n hasGroupMessagePreview: groupShowPreviews,\n hasBroadcastNotifications: !(\n broadcastSilent || (typeof broadcastMuteUntil === 'number'\n && getServerTime(serverTimeOffset) < broadcastMuteUntil)\n ),\n hasBroadcastMessagePreview: broadcastShowPreviews,\n };\n}\n\nexport function updateContactSignUpNotification(isSilent: boolean) {\n return invokeRequest(new GramJs.account.SetContactSignUpNotification({ silent: isSilent }));\n}\n\nexport function updateNotificationSettings(peerType: 'contact' | 'group' | 'broadcast', {\n isSilent,\n shouldShowPreviews,\n}: {\n isSilent: boolean;\n shouldShowPreviews: boolean;\n}) {\n let peer: GramJs.TypeInputNotifyPeer;\n if (peerType === 'contact') {\n peer = new GramJs.InputNotifyUsers();\n } else if (peerType === 'group') {\n peer = new GramJs.InputNotifyChats();\n } else {\n peer = new GramJs.InputNotifyBroadcasts();\n }\n\n const settings = {\n showPreviews: shouldShowPreviews,\n silent: isSilent,\n muteUntil: isSilent ? MAX_INT_32 : 0,\n };\n\n return invokeRequest(new GramJs.account.UpdateNotifySettings({\n peer,\n settings: new GramJs.InputPeerNotifySettings(settings),\n }));\n}\n\nexport async function fetchLanguages(): Promise {\n const result = await invokeRequest(new GramJs.langpack.GetLanguages({\n langPack: DEFAULT_LANG_PACK,\n }));\n if (!result) {\n return undefined;\n }\n\n return result.map(omitVirtualClassFields);\n}\n\nexport async function fetchLangPack({ sourceLangPacks, langCode }: {\n sourceLangPacks: typeof LANG_PACKS;\n langCode: string;\n}) {\n const results = await Promise.all(sourceLangPacks.map((langPack) => {\n return invokeRequest(new GramJs.langpack.GetLangPack({\n langPack,\n langCode: BETA_LANG_CODES.includes(langCode) ? `${langCode}-raw` : langCode,\n }));\n }));\n\n const collections = results\n .filter(Boolean as any)\n .map((result) => {\n return buildCollectionByKey(result.strings.map(omitVirtualClassFields), 'key');\n });\n\n if (!collections.length) {\n return undefined;\n }\n\n return { langPack: Object.assign({}, ...collections.reverse()) };\n}\n\nexport async function fetchLangStrings({ langPack, langCode, keys }: {\n langPack: string; langCode: string; keys: string[];\n}) {\n const result = await invokeRequest(new GramJs.langpack.GetStrings({\n langPack,\n langCode: BETA_LANG_CODES.includes(langCode) ? `${langCode}-raw` : langCode,\n keys,\n }));\n\n if (!result) {\n return undefined;\n }\n\n return result.map(omitVirtualClassFields);\n}\n\nexport async function fetchPrivacySettings(privacyKey: ApiPrivacyKey) {\n const key = buildInputPrivacyKey(privacyKey);\n const result = await invokeRequest(new GramJs.account.GetPrivacy({ key }));\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return buildPrivacyRules(result.rules);\n}\n\nexport function registerDevice(token: string) {\n const client = getClient();\n const secret = client.session.getAuthKey().getKey();\n return invokeRequest(new GramJs.account.RegisterDevice({\n tokenType: 10,\n secret,\n appSandbox: false,\n otherUids: [],\n token,\n }));\n}\n\nexport function unregisterDevice(token: string) {\n return invokeRequest(new GramJs.account.UnregisterDevice({\n tokenType: 10,\n otherUids: [],\n token,\n }));\n}\n\nexport async function setPrivacySettings(\n privacyKey: ApiPrivacyKey, rules: InputPrivacyRules,\n) {\n const key = buildInputPrivacyKey(privacyKey);\n const privacyRules: GramJs.TypeInputPrivacyRule[] = [];\n\n if (rules.allowedUsers) {\n privacyRules.push(new GramJs.InputPrivacyValueAllowUsers({\n users: rules.allowedUsers.map(({ id, accessHash }) => buildInputEntity(id, accessHash) as GramJs.InputUser),\n }));\n }\n if (rules.allowedChats) {\n privacyRules.push(new GramJs.InputPrivacyValueAllowChatParticipants({\n chats: rules.allowedChats.map(({ id }) => buildInputEntity(id) as BigInt.BigInteger),\n }));\n }\n if (rules.blockedUsers) {\n privacyRules.push(new GramJs.InputPrivacyValueDisallowUsers({\n users: rules.blockedUsers.map(({ id, accessHash }) => buildInputEntity(id, accessHash) as GramJs.InputUser),\n }));\n }\n if (rules.blockedChats) {\n privacyRules.push(new GramJs.InputPrivacyValueDisallowChatParticipants({\n chats: rules.blockedChats.map(({ id }) => buildInputEntity(id) as BigInt.BigInteger),\n }));\n }\n switch (rules.visibility) {\n case 'everybody':\n privacyRules.push(new GramJs.InputPrivacyValueAllowAll());\n break;\n\n case 'contacts':\n privacyRules.push(new GramJs.InputPrivacyValueAllowContacts());\n break;\n\n case 'nonContacts':\n privacyRules.push(new GramJs.InputPrivacyValueDisallowContacts());\n break;\n\n case 'nobody':\n privacyRules.push(new GramJs.InputPrivacyValueDisallowAll());\n break;\n }\n\n const result = await invokeRequest(new GramJs.account.SetPrivacy({ key, rules: privacyRules }));\n\n if (!result) {\n return undefined;\n }\n\n updateLocalDb(result);\n\n return buildPrivacyRules(result.rules);\n}\n\nexport async function updateIsOnline(isOnline: boolean) {\n await invokeRequest(new GramJs.account.UpdateStatus({ offline: !isOnline }));\n}\n\nexport async function fetchContentSettings() {\n const result = await invokeRequest(new GramJs.account.GetContentSettings());\n if (!result) {\n return undefined;\n }\n\n return {\n isSensitiveEnabled: Boolean(result.sensitiveEnabled),\n canChangeSensitive: Boolean(result.sensitiveCanChange),\n };\n}\n\nexport function updateContentSettings(isEnabled: boolean) {\n return invokeRequest(new GramJs.account.SetContentSettings({\n sensitiveEnabled: isEnabled || undefined,\n }));\n}\n\nfunction updateLocalDb(\n result: (\n GramJs.account.PrivacyRules | GramJs.contacts.Blocked | GramJs.contacts.BlockedSlice |\n GramJs.Updates | GramJs.UpdatesCombined\n ),\n) {\n result.users.forEach((user) => {\n if (user instanceof GramJs.User) {\n localDb.users[buildApiPeerId(user.id, 'user')] = user;\n }\n });\n\n result.chats.forEach((chat) => {\n if (chat instanceof GramJs.Chat || chat instanceof GramJs.Channel) {\n localDb.chats[buildApiPeerId(chat.id, chat instanceof GramJs.Chat ? 'chat' : 'channel')] = chat;\n }\n });\n}\n\nexport async function fetchCountryList({ langCode = 'en' }: { langCode?: LangCode }) {\n const countryList = await invokeRequest(new GramJs.help.GetCountriesList({\n langCode,\n }));\n\n if (!(countryList instanceof GramJs.help.CountriesList)) {\n return undefined;\n }\n return buildApiCountryList(countryList.countries);\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\nimport {\n ApiBotInlineMediaResult, ApiBotInlineResult, ApiBotInlineSwitchPm, ApiInlineResultType, ApiWebDocument,\n} from '../../types';\n\nimport { pick } from '../../../util/iteratees';\nimport { buildApiPhoto, buildApiThumbnailFromStripped } from './common';\nimport { buildVideoFromDocument } from './messages';\nimport { buildStickerFromDocument } from './symbols';\n\nexport function buildApiBotInlineResult(result: GramJs.BotInlineResult, queryId: string): ApiBotInlineResult {\n const {\n id, type, title, description, url, thumb,\n } = result;\n\n return {\n id,\n queryId,\n type: type as ApiInlineResultType,\n title,\n description,\n url,\n webThumbnail: buildApiWebDocument(thumb),\n };\n}\n\nexport function buildApiBotInlineMediaResult(\n result: GramJs.BotInlineMediaResult, queryId: string,\n): ApiBotInlineMediaResult {\n const {\n id, type, title, description, photo, document,\n } = result;\n\n return {\n id,\n queryId,\n type: type as ApiInlineResultType,\n title,\n description,\n ...(type === 'sticker' && document instanceof GramJs.Document && { sticker: buildStickerFromDocument(document) }),\n ...(photo instanceof GramJs.Photo && { photo: buildApiPhoto(photo) }),\n ...(type === 'gif' && document instanceof GramJs.Document && { gif: buildVideoFromDocument(document) }),\n ...(type === 'video' && document instanceof GramJs.Document && {\n thumbnail: buildApiThumbnailFromStripped(document.thumbs),\n }),\n };\n}\n\nexport function buildBotSwitchPm(switchPm?: GramJs.InlineBotSwitchPM) {\n return switchPm ? pick(switchPm, ['text', 'startParam']) as ApiBotInlineSwitchPm : undefined;\n}\n\nfunction buildApiWebDocument(document?: GramJs.TypeWebDocument): ApiWebDocument | undefined {\n return document ? pick(document, ['url', 'mimeType']) : undefined;\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\n\nimport { ApiChat, ApiUser } from '../../types';\n\nimport localDb from '../localDb';\nimport { invokeRequest } from './client';\nimport { buildInputPeer, generateRandomBigInt } from '../gramjsBuilders';\nimport { buildApiUser } from '../apiBuilders/users';\nimport { buildApiBotInlineMediaResult, buildApiBotInlineResult, buildBotSwitchPm } from '../apiBuilders/bots';\nimport { buildApiChatFromPreview } from '../apiBuilders/chats';\nimport { addEntitiesWithPhotosToLocalDb, addUserToLocalDb, deserializeBytes } from '../helpers';\n\nexport function init() {\n}\n\nexport function answerCallbackButton(\n {\n chatId, accessHash, messageId, data,\n }: {\n chatId: string; accessHash?: string; messageId: number; data: string;\n },\n) {\n return invokeRequest(new GramJs.messages.GetBotCallbackAnswer({\n peer: buildInputPeer(chatId, accessHash),\n msgId: messageId,\n data: deserializeBytes(data),\n }));\n}\n\nexport async function fetchTopInlineBots() {\n const topPeers = await invokeRequest(new GramJs.contacts.GetTopPeers({\n botsInline: true,\n }));\n\n if (!(topPeers instanceof GramJs.contacts.TopPeers)) {\n return undefined;\n }\n\n const users = topPeers.users.map(buildApiUser).filter(Boolean as any);\n const ids = users.map(({ id }) => id);\n\n return {\n ids,\n users,\n };\n}\n\nexport async function fetchInlineBot({ username }: { username: string }) {\n const resolvedPeer = await invokeRequest(new GramJs.contacts.ResolveUsername({ username }));\n\n if (\n !resolvedPeer\n || !(\n resolvedPeer.users[0] instanceof GramJs.User\n && resolvedPeer.users[0].bot\n && resolvedPeer.users[0].botInlinePlaceholder\n )\n ) {\n return undefined;\n }\n\n addUserToLocalDb(resolvedPeer.users[0]);\n\n return {\n user: buildApiUser(resolvedPeer.users[0]),\n chat: buildApiChatFromPreview(resolvedPeer.users[0]),\n };\n}\n\nexport async function fetchInlineBotResults({\n bot, chat, query, offset = '',\n}: {\n bot: ApiUser; chat: ApiChat; query: string; offset?: string;\n}) {\n const result = await invokeRequest(new GramJs.messages.GetInlineBotResults({\n bot: buildInputPeer(bot.id, bot.accessHash),\n peer: buildInputPeer(chat.id, chat.accessHash),\n query,\n offset,\n }));\n\n if (!result) {\n return undefined;\n }\n\n addEntitiesWithPhotosToLocalDb(result.users);\n\n return {\n isGallery: Boolean(result.gallery),\n help: bot.botPlaceholder,\n nextOffset: getInlineBotResultsNextOffset(bot.username, result.nextOffset),\n switchPm: buildBotSwitchPm(result.switchPm),\n users: result.users.map(buildApiUser).filter(Boolean as any),\n results: processInlineBotResult(String(result.queryId), result.results),\n };\n}\n\nexport async function sendInlineBotResult({\n chat, resultId, queryId, replyingTo, sendAs,\n}: {\n chat: ApiChat;\n resultId: string;\n queryId: string;\n replyingTo?: number;\n sendAs?: ApiUser | ApiChat;\n}) {\n const randomId = generateRandomBigInt();\n\n await invokeRequest(new GramJs.messages.SendInlineBotResult({\n clearDraft: true,\n randomId,\n queryId: BigInt(queryId),\n peer: buildInputPeer(chat.id, chat.accessHash),\n id: resultId,\n ...(replyingTo && { replyToMsgId: replyingTo }),\n ...(sendAs && { sendAs: buildInputPeer(sendAs.id, sendAs.accessHash) }),\n }), true);\n}\n\nexport async function startBot({\n bot, startParam,\n}: {\n bot: ApiUser;\n startParam?: string;\n}) {\n const randomId = generateRandomBigInt();\n\n await invokeRequest(new GramJs.messages.StartBot({\n bot: buildInputPeer(bot.id, bot.accessHash),\n peer: buildInputPeer(bot.id, bot.accessHash),\n randomId,\n startParam,\n }), true);\n}\n\nfunction processInlineBotResult(queryId: string, results: GramJs.TypeBotInlineResult[]) {\n return results.map((result) => {\n if (result instanceof GramJs.BotInlineMediaResult) {\n if (result.document instanceof GramJs.Document) {\n addDocumentToLocalDb(result.document);\n }\n\n if (result.photo instanceof GramJs.Photo) {\n addPhotoToLocalDb(result.photo);\n }\n\n return buildApiBotInlineMediaResult(result, queryId);\n }\n\n if (result.thumb) {\n addWebDocumentToLocalDb(result.thumb);\n }\n\n return buildApiBotInlineResult(result, queryId);\n });\n}\n\nfunction getInlineBotResultsNextOffset(username: string, nextOffset?: string) {\n return username === 'gif' && nextOffset === '0' ? '' : nextOffset;\n}\n\nfunction addDocumentToLocalDb(document: GramJs.Document) {\n localDb.documents[String(document.id)] = document;\n}\n\nfunction addPhotoToLocalDb(photo: GramJs.Photo) {\n localDb.photos[String(photo.id)] = photo;\n}\n\nfunction addWebDocumentToLocalDb(webDocument: GramJs.TypeWebDocument) {\n localDb.webDocuments[webDocument.url] = webDocument;\n}\n","import { Api as GramJs } from '../../../lib/gramjs';\n\nexport function buildShippingOptions(shippingOptions: GramJs.ShippingOption[] | undefined) {\n if (!shippingOptions) {\n return undefined;\n }\n return Object.values(shippingOptions).map((option) => {\n return {\n id: option.id,\n title: option.title,\n amount: option.prices.reduce((ac, cur) => ac + Number((cur.amount as any).value), 0),\n prices: option.prices.map(({ label, amount }) => {\n return {\n label,\n amount: Number((amount as any).value),\n };\n }),\n };\n });\n}\n\nexport function buildReceipt(receipt: GramJs.payments.PaymentReceipt) {\n const {\n invoice,\n info,\n shipping,\n currency,\n totalAmount,\n credentialsTitle,\n } = receipt;\n\n const { shippingAddress, phone, name } = (info || {});\n\n const { prices } = invoice;\n const mapedPrices = prices.map(({ label, amount }) => ({\n label,\n amount: Number((amount as any).value),\n }));\n\n let shippingPrices;\n let shippingMethod;\n\n if (shipping) {\n shippingPrices = shipping.prices.map(({ label, amount }) => {\n return {\n label,\n amount: Number((amount as any).value),\n };\n });\n shippingMethod = shipping.title;\n }\n\n return {\n currency,\n prices: mapedPrices,\n info: { shippingAddress, phone, name },\n totalAmount: Number((totalAmount as any).value),\n credentialsTitle,\n shippingPrices,\n shippingMethod,\n };\n}\n\nexport function buildPaymentForm(form: GramJs.payments.PaymentForm) {\n const {\n formId,\n canSaveCredentials,\n passwordMissing,\n providerId,\n nativeProvider,\n nativeParams,\n savedInfo,\n invoice,\n } = form;\n\n const {\n test,\n nameRequested,\n phoneRequested,\n emailRequested,\n shippingAddressRequested,\n flexible,\n phoneToProvider,\n emailToProvider,\n currency,\n prices,\n } = invoice;\n\n const mapedPrices = prices.map(({ label, amount }) => ({\n label,\n amount: Number((amount as any).value),\n }));\n\n const nativeData = nativeParams ? JSON.parse(nativeParams.data) : {};\n return {\n canSaveCredentials,\n passwordMissing,\n formId: String(formId),\n providerId: String(providerId),\n nativeProvider,\n savedInfo,\n invoice: {\n test,\n nameRequested,\n phoneRequested,\n emailRequested,\n shippingAddressRequested,\n flexible,\n phoneToProvider,\n emailToProvider,\n currency,\n prices: mapedPrices,\n },\n nativeParams: {\n needCardholderName: nativeData.need_cardholder_name,\n needCountry: nativeData.need_country,\n needZip: nativeData.need_zip,\n publishableKey: nativeData.publishable_key,\n },\n };\n}\n","import BigInt from 'big-integer';\nimport { Api as GramJs } from '../../../lib/gramjs';\nimport { invokeRequest } from './client';\nimport { buildInputPeer, buildShippingInfo } from '../gramjsBuilders';\nimport { buildShippingOptions, buildPaymentForm, buildReceipt } from '../apiBuilders/payments';\nimport { ApiChat } from '../../types';\n\nexport async function validateRequestedInfo({\n chat,\n messageId,\n requestInfo,\n shouldSave,\n}: {\n chat: ApiChat;\n messageId: number;\n requestInfo: GramJs.TypePaymentRequestedInfo;\n shouldSave?: boolean;\n}): Promise<{\n id: string;\n shippingOptions: any;\n } | undefined> {\n const result = await invokeRequest(new GramJs.payments.ValidateRequestedInfo({\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: messageId,\n save: shouldSave || undefined,\n info: buildShippingInfo(requestInfo),\n }));\n if (!result) {\n return undefined;\n }\n\n const { id, shippingOptions } = result;\n if (!id) {\n return undefined;\n }\n\n return {\n id,\n shippingOptions: buildShippingOptions(shippingOptions),\n };\n}\n\nexport function sendPaymentForm({\n chat,\n messageId,\n formId,\n requestedInfoId,\n shippingOptionId,\n credentials,\n}: {\n chat: ApiChat;\n messageId: number;\n formId: string;\n credentials: any;\n requestedInfoId?: string;\n shippingOptionId?: string;\n}) {\n return invokeRequest(new GramJs.payments.SendPaymentForm({\n formId: BigInt(formId),\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: messageId,\n requestedInfoId,\n shippingOptionId,\n credentials: new GramJs.InputPaymentCredentials({\n save: credentials.save,\n data: new GramJs.DataJSON({ data: JSON.stringify(credentials.data) }),\n }),\n }), true);\n}\n\nexport async function getPaymentForm({\n chat, messageId,\n}: {\n chat: ApiChat;\n messageId: number;\n}) {\n const result = await invokeRequest(new GramJs.payments.GetPaymentForm({\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId: messageId,\n }));\n\n if (!result) {\n return undefined;\n }\n\n return buildPaymentForm(result);\n}\n\nexport async function getReceipt(chat: ApiChat, msgId: number) {\n const result = await invokeRequest(new GramJs.payments.GetPaymentReceipt({\n peer: buildInputPeer(chat.id, chat.accessHash),\n msgId,\n }));\n if (!result) {\n return undefined;\n }\n\n return buildReceipt(result);\n}\n","import {\n OnApiUpdate,\n ApiInitialArgs,\n ApiUpdate,\n ApiOnProgress,\n} from '../types';\nimport { Methods, MethodArgs, MethodResponse } from './methods/types';\n\nimport { API_THROTTLE_RESET_UPDATES, API_UPDATE_THROTTLE } from '../../config';\nimport { throttle, throttleWithTickEnd } from '../../util/schedulers';\nimport { init as initUpdater } from './updater';\nimport { init as initAuth } from './methods/auth';\nimport { init as initChats } from './methods/chats';\nimport { init as initMessages } from './methods/messages';\nimport { init as initUsers } from './methods/users';\nimport { init as initClient } from './methods/client';\nimport { init as initStickers } from './methods/symbols';\nimport { init as initManagement } from './methods/management';\nimport { init as initTwoFaSettings } from './methods/twoFaSettings';\nimport { init as initCalls } from './methods/calls';\nimport * as methods from './methods';\n\nlet onUpdate: OnApiUpdate;\n\nexport async function initApi(_onUpdate: OnApiUpdate, initialArgs: ApiInitialArgs) {\n onUpdate = _onUpdate;\n\n initUpdater(handleUpdate);\n initAuth(handleUpdate);\n initChats(handleUpdate);\n initMessages(handleUpdate);\n initUsers(handleUpdate);\n initStickers(handleUpdate);\n initManagement(handleUpdate);\n initTwoFaSettings(handleUpdate);\n initCalls(handleUpdate);\n\n await initClient(handleUpdate, initialArgs);\n}\n\nexport function callApi(fnName: T, ...args: MethodArgs): MethodResponse {\n // @ts-ignore\n return methods[fnName](...args) as MethodResponse;\n}\n\nexport function cancelApiProgress(progressCallback: ApiOnProgress) {\n progressCallback.isCanceled = true;\n}\n\nconst flushUpdatesOnTickEnd = throttleWithTickEnd(flushUpdates);\n\nlet flushUpdatesThrottled: typeof flushUpdatesOnTickEnd | undefined;\nlet currentThrottleId: number | undefined;\n\nlet pendingUpdates: ApiUpdate[] | undefined;\n\nfunction handleUpdate(update: ApiUpdate) {\n if (!pendingUpdates) {\n pendingUpdates = [update];\n } else {\n pendingUpdates.push(update);\n }\n\n if (!flushUpdatesThrottled || API_THROTTLE_RESET_UPDATES.has(update['@type'])) {\n flushUpdatesThrottled = throttle(flushUpdatesOnTickEnd, API_UPDATE_THROTTLE, true);\n currentThrottleId = Math.random();\n }\n\n flushUpdatesThrottled(currentThrottleId!);\n}\n\nfunction flushUpdates(throttleId: number) {\n if (!pendingUpdates || throttleId !== currentThrottleId) {\n return;\n }\n\n const currentUpdates = pendingUpdates!;\n pendingUpdates = undefined;\n currentUpdates.forEach(onUpdate);\n}\n","import { ApiOnProgress, ApiUpdate } from '../../types';\nimport { OriginMessageEvent, WorkerMessageData } from './types';\n\nimport { DEBUG } from '../../../config';\nimport { initApi, callApi, cancelApiProgress } from '../provider';\n\ndeclare const self: WorkerGlobalScope;\n\nhandleErrors();\n\n// TODO Re-use `util/createWorkerInterface.ts`\n\nconst callbackState = new Map();\n\nif (DEBUG) {\n // eslint-disable-next-line no-console\n console.log('>>> FINISH LOAD WORKER');\n}\n\nonmessage = async (message: OriginMessageEvent) => {\n const { data } = message;\n\n switch (data.type) {\n case 'initApi': {\n await initApi(onUpdate, data.args[0]);\n break;\n }\n case 'callMethod': {\n const { messageId, name, args } = data;\n try {\n if (messageId) {\n const callback = (...callbackArgs: any[]) => {\n const lastArg = callbackArgs[callbackArgs.length - 1];\n\n sendToOrigin({\n type: 'methodCallback',\n messageId,\n callbackArgs,\n }, lastArg instanceof ArrayBuffer ? lastArg : undefined);\n };\n\n callbackState.set(messageId, callback);\n\n args.push(callback as never);\n }\n\n const response = await callApi(name, ...args);\n const { arrayBuffer } = (typeof response === 'object' && 'arrayBuffer' in response && response) || {};\n\n if (messageId) {\n sendToOrigin({\n type: 'methodResponse',\n messageId,\n response,\n }, arrayBuffer);\n }\n } catch (error) {\n if (DEBUG) {\n // eslint-disable-next-line no-console\n console.error(error);\n }\n\n if (messageId) {\n sendToOrigin({\n type: 'methodResponse',\n messageId,\n error: { message: error.message },\n });\n }\n }\n\n if (messageId) {\n callbackState.delete(messageId);\n }\n\n break;\n }\n case 'cancelProgress': {\n const callback = callbackState.get(data.messageId);\n if (callback) {\n cancelApiProgress(callback);\n }\n\n break;\n }\n case 'ping': {\n sendToOrigin({\n type: 'methodResponse',\n messageId: data.messageId!,\n });\n\n break;\n }\n }\n};\n\nfunction handleErrors() {\n self.onerror = (e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n sendToOrigin({ type: 'unhandledError', error: { message: e.error.message || 'Uncaught exception in worker' } });\n };\n\n self.addEventListener('unhandledrejection', (e) => {\n // eslint-disable-next-line no-console\n console.error(e);\n sendToOrigin({ type: 'unhandledError', error: { message: e.reason.message || 'Uncaught rejection in worker' } });\n });\n}\n\nfunction onUpdate(update: ApiUpdate) {\n sendToOrigin({\n type: 'update',\n update,\n });\n}\n\nfunction sendToOrigin(data: WorkerMessageData, arrayBuffer?: ArrayBuffer) {\n if (arrayBuffer) {\n postMessage(data, [arrayBuffer]);\n } else {\n postMessage(data);\n }\n}\n","const BigInt = require('big-integer');\nconst crypto = require('./crypto/crypto');\n\n/**\n * converts a buffer to big int\n * @param buffer\n * @param little\n * @param signed\n * @returns {bigInt.BigInteger}\n */\nfunction readBigIntFromBuffer(buffer, little = true, signed = false) {\n let randBuffer = Buffer.from(buffer);\n const bytesNumber = randBuffer.length;\n if (little) {\n randBuffer = randBuffer.reverse();\n }\n let bigInt = BigInt(randBuffer.toString('hex'), 16);\n if (signed && Math.floor(bigInt.toString('2').length / 8) >= bytesNumber) {\n bigInt = bigInt.subtract(BigInt(2)\n .pow(BigInt(bytesNumber * 8)));\n }\n return bigInt;\n}\n\n/**\n * Special case signed little ints\n * @param big\n * @param number\n * @returns {Buffer}\n */\nfunction toSignedLittleBuffer(big, number = 8) {\n const bigNumber = BigInt(big);\n const byteArray = [];\n for (let i = 0; i < number; i++) {\n byteArray[i] = bigNumber.shiftRight(8 * i)\n .and(255);\n }\n return Buffer.from(byteArray);\n}\n\n\n/**\n * converts a big int to a buffer\n * @param bigInt {bigInt.BigInteger}\n * @param bytesNumber\n * @param little\n * @param signed\n * @returns {Buffer}\n */\nfunction readBufferFromBigInt(bigInt, bytesNumber, little = true, signed = false) {\n bigInt = BigInt(bigInt);\n const bitLength = bigInt.bitLength();\n\n const bytes = Math.ceil(bitLength / 8);\n if (bytesNumber < bytes) {\n throw new Error('OverflowError: int too big to convert');\n }\n if (!signed && bigInt.lesser(BigInt(0))) {\n throw new Error('Cannot convert to unsigned');\n }\n let below = false;\n if (bigInt.lesser(BigInt(0))) {\n below = true;\n bigInt = bigInt.abs();\n }\n\n const hex = bigInt.toString('16')\n .padStart(bytesNumber * 2, '0');\n let l = Buffer.from(hex, 'hex');\n if (little) {\n l = l.reverse();\n }\n\n if (signed && below) {\n if (little) {\n let reminder = false;\n if (l[0] !== 0) {\n l[0] -= 1;\n }\n for (let i = 0; i < l.length; i++) {\n if (l[i] === 0) {\n reminder = true;\n continue;\n }\n if (reminder) {\n l[i] -= 1;\n reminder = false;\n }\n l[i] = 255 - l[i];\n }\n } else {\n l[l.length - 1] = 256 - l[l.length - 1];\n for (let i = 0; i < l.length - 1; i++) {\n l[i] = 255 - l[i];\n }\n }\n }\n return l;\n}\n\n/**\n * Generates a random long integer (8 bytes), which is optionally signed\n * @returns {BigInteger}\n */\nfunction generateRandomLong(signed = true) {\n return readBigIntFromBuffer(generateRandomBytes(8), true, signed);\n}\n\n/**\n * .... really javascript\n * @param n {number}\n * @param m {number}\n * @returns {number}\n */\nfunction mod(n, m) {\n return ((n % m) + m) % m;\n}\n\n/**\n * returns a positive bigInt\n * @param n {BigInt}\n * @param m {BigInt}\n * @returns {BigInt}\n */\nfunction bigIntMod(n, m) {\n return ((n.remainder(m)).add(m)).remainder(m);\n}\n\n/**\n * Generates a random bytes array\n * @param count\n * @returns {Buffer}\n */\nfunction generateRandomBytes(count) {\n return Buffer.from(crypto.randomBytes(count));\n}\n\n/**\n * Calculate the key based on Telegram guidelines, specifying whether it's the client or not\n * @param sharedKey\n * @param msgKey\n * @param client\n * @returns {{iv: Buffer, key: Buffer}}\n */\n\n/* CONTEST\nthis is mtproto 1 (mostly used for secret chats)\nasync function calcKey(sharedKey, msgKey, client) {\n const x = client === true ? 0 : 8\n const [sha1a, sha1b, sha1c, sha1d] = await Promise.all([\n sha1(Buffer.concat([msgKey, sharedKey.slice(x, x + 32)])),\n sha1(Buffer.concat([sharedKey.slice(x + 32, x + 48), msgKey, sharedKey.slice(x + 48, x + 64)])),\n sha1(Buffer.concat([sharedKey.slice(x + 64, x + 96), msgKey])),\n sha1(Buffer.concat([msgKey, sharedKey.slice(x + 96, x + 128)]))\n ])\n const key = Buffer.concat([sha1a.slice(0, 8), sha1b.slice(8, 20), sha1c.slice(4, 16)])\n const iv = Buffer.concat([sha1a.slice(8, 20), sha1b.slice(0, 8), sha1c.slice(16, 20), sha1d.slice(0, 8)])\n return {\n key,\n iv\n }\n}\n\n */\n\n/**\n * Generates the key data corresponding to the given nonces\n * @param serverNonce\n * @param newNonce\n * @returns {{key: Buffer, iv: Buffer}}\n */\nasync function generateKeyDataFromNonce(serverNonce, newNonce) {\n serverNonce = toSignedLittleBuffer(serverNonce, 16);\n newNonce = toSignedLittleBuffer(newNonce, 32);\n const [hash1, hash2, hash3] = await Promise.all([\n sha1(Buffer.concat([newNonce, serverNonce])),\n sha1(Buffer.concat([serverNonce, newNonce])),\n sha1(Buffer.concat([newNonce, newNonce])),\n ]);\n const keyBuffer = Buffer.concat([hash1, hash2.slice(0, 12)]);\n const ivBuffer = Buffer.concat([hash2.slice(12, 20), hash3, newNonce.slice(0, 4)]);\n return {\n key: keyBuffer,\n iv: ivBuffer,\n };\n}\n\nfunction convertToLittle(buf) {\n const correct = Buffer.alloc(buf.length * 4);\n\n for (let i = 0; i < buf.length; i++) {\n correct.writeUInt32BE(buf[i], i * 4);\n }\n return correct;\n}\n\n/**\n * Calculates the SHA1 digest for the given data\n * @param data\n * @returns {Promise}\n */\nfunction sha1(data) {\n const shaSum = crypto.createHash('sha1');\n shaSum.update(data);\n return shaSum.digest();\n}\n\n\n/**\n * Calculates the SHA256 digest for the given data\n * @param data\n * @returns {Promise}\n */\nfunction sha256(data) {\n const shaSum = crypto.createHash('sha256');\n shaSum.update(data);\n return shaSum.digest();\n}\n\n/**\n * Fast mod pow for RSA calculation. a^b % n\n * @param a\n * @param b\n * @param n\n * @returns {bigInt.BigInteger}\n */\nfunction modExp(a, b, n) {\n a = a.remainder(n);\n let result = BigInt.one;\n let x = a;\n while (b.greater(BigInt.zero)) {\n const leastSignificantBit = b.remainder(BigInt(2));\n b = b.divide(BigInt(2));\n if (leastSignificantBit.eq(BigInt.one)) {\n result = result.multiply(x);\n result = result.remainder(n);\n }\n x = x.multiply(x);\n x = x.remainder(n);\n }\n return result;\n}\n\n\n/**\n * Gets the arbitrary-length byte array corresponding to the given integer\n * @param integer {number,BigInteger}\n * @param signed {boolean}\n * @returns {Buffer}\n */\nfunction getByteArray(integer, signed = false) {\n const bits = integer.toString(2).length;\n const byteLength = Math.floor((bits + 8 - 1) / 8);\n return readBufferFromBigInt(BigInt(integer), byteLength, false, signed);\n}\n\n/**\n * returns a random int from min (inclusive) and max (inclusive)\n * @param min\n * @param max\n * @returns {number}\n */\nfunction getRandomInt(min, max) {\n min = Math.ceil(min);\n max = Math.floor(max);\n return Math.floor(Math.random() * (max - min + 1)) + min;\n}\n\n/**\n * Sleeps a specified amount of time\n * @param ms time in milliseconds\n * @returns {Promise}\n */\nconst sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));\n\n/**\n * Helper to export two buffers of same length\n * @returns {Buffer}\n */\n\nfunction bufferXor(a, b) {\n const res = [];\n for (let i = 0; i < a.length; i++) {\n res.push(a[i] ^ b[i]);\n }\n return Buffer.from(res);\n}\n\n/**\n * Checks if the obj is an array\n * @param obj\n * @returns {boolean}\n */\n/*\nCONTEST\nwe do'nt support array requests anyway\nfunction isArrayLike(obj) {\n if (!obj) return false\n const l = obj.length\n if (typeof l != 'number' || l < 0) return false\n if (Math.floor(l) !== l) return false\n // fast check\n if (l > 0 && !(l - 1 in obj)) return false\n // more complete check (optional)\n for (let i = 0; i < l; ++i) {\n if (!(i in obj)) return false\n }\n return true\n}\n*/\n\n// Taken from https://stackoverflow.com/questions/18638900/javascript-crc32/18639999#18639999\nfunction makeCRCTable() {\n let c;\n const crcTable = [];\n for (let n = 0; n < 256; n++) {\n c = n;\n for (let k = 0; k < 8; k++) {\n c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));\n }\n crcTable[n] = c;\n }\n return crcTable;\n}\n\nlet crcTable;\n\nfunction crc32(buf) {\n if (!crcTable) {\n crcTable = makeCRCTable();\n }\n if (!Buffer.isBuffer(buf)) {\n buf = Buffer.from(buf);\n }\n let crc = -1;\n\n for (let index = 0; index < buf.length; index++) {\n const byte = buf[index];\n crc = crcTable[(crc ^ byte) & 0xff] ^ (crc >>> 8);\n }\n return (crc ^ (-1)) >>> 0;\n}\n\n/**\n * Creates a deferred object\n * @return {Deferred}\n */\nfunction createDeferred() {\n let resolve;\n const promise = new Promise((_resolve) => {\n resolve = _resolve;\n });\n\n return {\n promise,\n resolve,\n };\n}\n\nmodule.exports = {\n readBigIntFromBuffer,\n readBufferFromBigInt,\n generateRandomLong,\n mod,\n crc32,\n generateRandomBytes,\n // calcKey,\n generateKeyDataFromNonce,\n sha1,\n sha256,\n bigIntMod,\n modExp,\n getRandomInt,\n sleep,\n getByteArray,\n // isArrayLike,\n toSignedLittleBuffer,\n convertToLittle,\n bufferXor,\n createDeferred,\n};\n","const BigInt = require('big-integer');\nconst { constructors } = require('./tl');\nconst {\n readBigIntFromBuffer,\n readBufferFromBigInt,\n sha256,\n bigIntMod,\n modExp,\n generateRandomBytes,\n} = require('./Helpers');\nconst crypto = require('./crypto/crypto');\n\nconst SIZE_FOR_HASH = 256;\n\n/**\n *\n *\n * @param prime{BigInteger}\n * @param g{BigInteger}\n */\n\n/*\nWe don't support changing passwords yet\nfunction checkPrimeAndGoodCheck(prime, g) {\n console.error('Unsupported function `checkPrimeAndGoodCheck` call. Arguments:', prime, g)\n\n const goodPrimeBitsCount = 2048\n if (prime < 0 || prime.bitLength() !== goodPrimeBitsCount) {\n throw new Error(`bad prime count ${prime.bitLength()},expected ${goodPrimeBitsCount}`)\n }\n // TODO this is kinda slow\n if (Factorizator.factorize(prime)[0] !== 1) {\n throw new Error('give \"prime\" is not prime')\n }\n if (g.eq(BigInt(2))) {\n if ((prime.remainder(BigInt(8))).neq(BigInt(7))) {\n throw new Error(`bad g ${g}, mod8 ${prime % 8}`)\n }\n } else if (g.eq(BigInt(3))) {\n if ((prime.remainder(BigInt(3))).neq(BigInt(2))) {\n throw new Error(`bad g ${g}, mod3 ${prime % 3}`)\n }\n // eslint-disable-next-line no-empty\n } else if (g.eq(BigInt(4))) {\n\n } else if (g.eq(BigInt(5))) {\n if (!([ BigInt(1), BigInt(4) ].includes(prime.remainder(BigInt(5))))) {\n throw new Error(`bad g ${g}, mod8 ${prime % 5}`)\n }\n } else if (g.eq(BigInt(6))) {\n if (!([ BigInt(19), BigInt(23) ].includes(prime.remainder(BigInt(24))))) {\n throw new Error(`bad g ${g}, mod8 ${prime % 24}`)\n }\n } else if (g.eq(BigInt(7))) {\n if (!([ BigInt(3), BigInt(5), BigInt(6) ].includes(prime.remainder(BigInt(7))))) {\n throw new Error(`bad g ${g}, mod8 ${prime % 7}`)\n }\n } else {\n throw new Error(`bad g ${g}`)\n }\n const primeSub1Div2 = (prime.subtract(BigInt(1))).divide(BigInt(2))\n if (Factorizator.factorize(primeSub1Div2)[0] !== 1) {\n throw new Error('(prime - 1) // 2 is not prime')\n }\n}\n*/\n/**\n *\n * @param primeBytes{Buffer}\n * @param g{number}\n */\nfunction checkPrimeAndGood(primeBytes, g) {\n const goodPrime = Buffer.from([\n 0xC7, 0x1C, 0xAE, 0xB9, 0xC6, 0xB1, 0xC9, 0x04, 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 { RPCError } = require('../errors');\n\nconst MtProtoPlainSender = require('./MTProtoPlainSender');\nconst MTProtoState = require('./MTProtoState');\nconst Helpers = require('../Helpers');\nconst AuthKey = require('../crypto/AuthKey');\nconst { doAuthentication } = require('./Authenticator');\nconst RPCResult = require('../tl/core/RPCResult');\nconst MessageContainer = require('../tl/core/MessageContainer');\nconst GZIPPacked = require('../tl/core/GZIPPacked');\nconst RequestState = require('./RequestState');\n\nconst {\n MsgsAck,\n upload,\n MsgsStateInfo,\n Pong,\n} = require('../tl').constructors;\nconst MessagePacker = require('../extensions/MessagePacker');\nconst BinaryReader = require('../extensions/BinaryReader');\nconst {\n UpdateConnectionState,\n UpdateServerTimeOffset,\n} = require('./index');\nconst { BadMessageError } = require('../errors/Common');\nconst {\n BadServerSalt,\n BadMsgNotification,\n MsgDetailedInfo,\n MsgNewDetailedInfo,\n NewSessionCreated,\n FutureSalts,\n MsgsStateReq,\n MsgResendReq,\n MsgsAllInfo,\n} = require('../tl').constructors;\nconst { SecurityError } = require('../errors/Common');\nconst { InvalidBufferError } = require('../errors/Common');\nconst { LogOut } = require('../tl').requests.auth;\nconst { RPCMessageToError } = require('../errors');\nconst { TypeNotFoundError } = require('../errors/Common');\n\n/**\n * MTProto Mobile Protocol sender\n * (https://core.telegram.org/mtproto/description)\n * This class is responsible for wrapping requests into `TLMessage`'s,\n * sending them over the network and receiving them in a safe manner.\n *\n * Automatic reconnection due to temporary network issues is a concern\n * for this class as well, including retry of messages that could not\n * be sent successfully.\n *\n * A new authorization key will be generated on connection if no other\n * key exists yet.\n */\nclass MTProtoSender {\n static DEFAULT_OPTIONS = {\n logger: undefined,\n retries: Infinity,\n delay: 2000,\n autoReconnect: true,\n connectTimeout: undefined,\n authKeyCallback: undefined,\n updateCallback: undefined,\n autoReconnectCallback: undefined,\n isMainSender: undefined,\n onConnectionBreak: undefined,\n };\n\n /**\n * @param authKey\n * @param opts\n */\n constructor(authKey, opts) {\n const args = { ...MTProtoSender.DEFAULT_OPTIONS, ...opts };\n this._connection = undefined;\n this._log = args.logger;\n this._dcId = args.dcId;\n this._retries = args.retries;\n this._delay = args.delay;\n this._autoReconnect = args.autoReconnect;\n this._connectTimeout = args.connectTimeout;\n this._authKeyCallback = args.authKeyCallback;\n this._updateCallback = args.updateCallback;\n this._autoReconnectCallback = args.autoReconnectCallback;\n this._isMainSender = args.isMainSender;\n this._onConnectionBreak = args.onConnectionBreak;\n\n /**\n * whether we disconnected ourself or telegram did it.\n */\n this.userDisconnected = false;\n\n /**\n * Whether the user has explicitly connected or disconnected.\n *\n * If a disconnection happens for any other reason and it\n * was *not* user action then the pending messages won't\n * be cleared but on explicit user disconnection all the\n * pending futures should be cancelled.\n */\n this._user_connected = false;\n this._reconnecting = false;\n this._disconnected = true;\n\n /**\n * We need to join the loops upon disconnection\n */\n this._send_loop_handle = undefined;\n this._recv_loop_handle = undefined;\n\n /**\n * Preserving the references of the AuthKey and state is important\n */\n this.authKey = authKey || new AuthKey();\n this._state = new MTProtoState(this.authKey, this._log);\n\n /**\n * Outgoing messages are put in a queue and sent in a batch.\n * Note that here we're also storing their ``_RequestState``.\n */\n this._send_queue = new MessagePacker(this._state, this._log);\n\n /**\n * Sent states are remembered until a response is received.\n */\n this._pending_state = {};\n\n /**\n * Responses must be acknowledged, and we can also batch these.\n */\n this._pending_ack = new Set();\n\n /**\n * Similar to pending_messages but only for the last acknowledges.\n * These can't go in pending_messages because no acknowledge for them\n * is received, but we may still need to resend their state on bad salts.\n */\n this._last_acks = [];\n\n /**\n * Jump table from response ID to method that handles it\n */\n\n this._handlers = {\n [RPCResult.CONSTRUCTOR_ID]: this._handleRPCResult.bind(this),\n [MessageContainer.CONSTRUCTOR_ID]: this._handleContainer.bind(this),\n [GZIPPacked.CONSTRUCTOR_ID]: this._handleGzipPacked.bind(this),\n [Pong.CONSTRUCTOR_ID]: this._handlePong.bind(this),\n [BadServerSalt.CONSTRUCTOR_ID]: this._handleBadServerSalt.bind(this),\n [BadMsgNotification.CONSTRUCTOR_ID]: this._handleBadNotification.bind(this),\n [MsgDetailedInfo.CONSTRUCTOR_ID]: this._handleDetailedInfo.bind(this),\n [MsgNewDetailedInfo.CONSTRUCTOR_ID]: this._handleNewDetailedInfo.bind(this),\n [NewSessionCreated.CONSTRUCTOR_ID]: this._handleNewSessionCreated.bind(this),\n [MsgsAck.CONSTRUCTOR_ID]: this._handleAck.bind(this),\n [FutureSalts.CONSTRUCTOR_ID]: this._handleFutureSalts.bind(this),\n [MsgsStateReq.CONSTRUCTOR_ID]: this._handleStateForgotten.bind(this),\n [MsgResendReq.CONSTRUCTOR_ID]: this._handleStateForgotten.bind(this),\n [MsgsAllInfo.CONSTRUCTOR_ID]: this._handleMsgAll.bind(this),\n };\n }\n\n // Public API\n\n /**\n * Connects to the specified given connection using the given auth key.\n * @param connection\n * @param [force]\n * @returns {Promise}\n */\n async connect(connection, force) {\n if (this._user_connected && !force) {\n this._log.info('User is already connected!');\n return false;\n }\n this.isConnecting = true;\n this._connection = connection;\n\n for (let attempt = 0; attempt < this._retries; attempt++) {\n try {\n await this._connect();\n if (this._updateCallback) {\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.connected));\n }\n break;\n } catch (err) {\n if (this._updateCallback && attempt === 0) {\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.disconnected));\n }\n this._log.error(`WebSocket connection failed attempt: ${attempt + 1}`);\n // eslint-disable-next-line no-console\n console.error(err);\n await Helpers.sleep(this._delay);\n }\n }\n this.isConnecting = false;\n return true;\n }\n\n isConnected() {\n return this._user_connected;\n }\n\n /**\n * Cleanly disconnects the instance from the network, cancels\n * all pending requests, and closes the send and receive loops.\n */\n async disconnect() {\n this.userDisconnected = true;\n await this._disconnect();\n }\n\n /**\n *\n This method enqueues the given request to be sent. Its send\n state will be saved until a response arrives, and a ``Future``\n that will be resolved when the response arrives will be returned:\n\n .. code-block:: javascript\n\n async def method():\n # Sending (enqueued for the send loop)\n future = sender.send(request)\n # Receiving (waits for the receive loop to read the result)\n result = await future\n\n Designed like this because Telegram may send the response at\n any point, and it can send other items while one waits for it.\n Once the response for this future arrives, it is set with the\n received result, quite similar to how a ``receive()`` call\n would otherwise work.\n\n Since the receiving part is \"built in\" the future, it's\n impossible to await receive a result that was never sent.\n * @param request\n * @returns {RequestState}\n */\n send(request) {\n if (!this._user_connected) {\n throw new Error('Cannot send requests while disconnected');\n }\n const state = new RequestState(request);\n this._send_queue.append(state);\n return state.promise;\n }\n\n /**\n * Same as send but returns the full state. usefull for invoke after logic\n * @param request\n * @return {RequestState}\n */\n sendWithInvokeSupport(request) {\n if (!this._user_connected) {\n throw new Error('Cannot send requests while disconnected');\n }\n const state = new RequestState(request, undefined, this._pending_state);\n this._send_queue.append(state);\n return state;\n }\n\n /**\n * Performs the actual connection, retrying, generating the\n * authorization key if necessary, and starting the send and\n * receive loops.\n * @returns {Promise}\n * @private\n */\n async _connect() {\n this._log.info('Connecting to {0}...'.replace('{0}', this._connection));\n await this._connection.connect();\n this._log.debug('Connection success!');\n // process.exit(0)\n if (!this.authKey.getKey()) {\n const plain = new MtProtoPlainSender(this._connection, this._log);\n this._log.debug('New auth_key attempt ...');\n const res = await doAuthentication(plain, this._log);\n this._log.debug('Generated new auth_key successfully');\n await this.authKey.setKey(res.authKey);\n\n this._state.timeOffset = res.timeOffset;\n\n if (this._updateCallback) {\n this._updateCallback(new UpdateServerTimeOffset(this._state.timeOffset));\n }\n\n /**\n * This is *EXTREMELY* important since we don't control\n * external references to the authorization key, we must\n * notify whenever we change it. This is crucial when we\n * switch to different data centers.\n */\n if (this._authKeyCallback) {\n await this._authKeyCallback(this.authKey, this._dcId);\n }\n } else {\n this._authenticated = true;\n this._log.debug('Already have an auth key ...');\n }\n this._user_connected = true;\n this._reconnecting = false;\n\n this._log.debug('Starting send loop');\n this._send_loop_handle = this._sendLoop();\n\n this._log.debug('Starting receive loop');\n this._recv_loop_handle = this._recvLoop();\n\n // _disconnected only completes after manual disconnection\n // or errors after which the sender cannot continue such\n // as failing to reconnect or any unexpected error.\n\n this._log.info('Connection to %s complete!'.replace('%s', this._connection.toString()));\n }\n\n async _disconnect() {\n this._send_queue.rejectAll();\n\n if (this._connection === undefined) {\n this._log.info('Not disconnecting (already have no connection)');\n return;\n }\n if (this._updateCallback) {\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.disconnected));\n }\n this._log.info('Disconnecting from %s...'.replace('%s', this._connection.toString()));\n this._user_connected = false;\n this._log.debug('Closing current connection...');\n await this._connection.disconnect();\n }\n\n /**\n * This loop is responsible for popping items off the send\n * queue, encrypting them, and sending them over the network.\n * Besides `connect`, only this method ever sends data.\n * @returns {Promise}\n * @private\n */\n async _sendLoop() {\n this._send_queue = new MessagePacker(this._state, this._log);\n\n while (this._user_connected && !this._reconnecting) {\n if (this._pending_ack.size) {\n const ack = new RequestState(new MsgsAck({ msgIds: Array(...this._pending_ack) }));\n this._send_queue.append(ack);\n this._last_acks.push(ack);\n if (this._last_acks.length >= 10) {\n this._last_acks.shift();\n }\n this._pending_ack.clear();\n }\n this._log.debug(`Waiting for messages to send...${this._reconnecting}`);\n // TODO Wait for the connection send queue to be empty?\n // This means that while it's not empty we can wait for\n // more messages to be added to the send queue.\n const res = await this._send_queue.get();\n\n if (this._reconnecting) {\n return;\n }\n\n if (!res) {\n continue;\n }\n let { data } = res;\n const { batch } = res;\n this._log.debug(`Encrypting ${batch.length} message(s) in ${data.length} bytes for sending`);\n\n data = await this._state.encryptMessageData(data);\n\n try {\n await this._connection.send(data);\n } catch (e) {\n this._log.error(e);\n this._log.info('Connection closed while sending data');\n return;\n }\n for (const state of batch) {\n if (!Array.isArray(state)) {\n if (state.request.classType === 'request') {\n this._pending_state[state.msgId] = state;\n }\n } else {\n for (const s of state) {\n if (s.request.classType === 'request') {\n this._pending_state[s.msgId] = s;\n }\n }\n }\n }\n this._log.debug('Encrypted messages put in a queue to be sent');\n }\n }\n\n async _recvLoop() {\n let body;\n let message;\n\n while (this._user_connected && !this._reconnecting) {\n // this._log.debug('Receiving items from the network...');\n this._log.debug('Receiving items from the network...');\n try {\n body = await this._connection.recv();\n } catch (e) {\n // this._log.info('Connection closed while receiving data');\n /** when the server disconnects us we want to reconnect */\n if (!this.userDisconnected) {\n this._log.error(e);\n this._log.warn('Connection closed while receiving data');\n this.reconnect();\n }\n return;\n }\n try {\n message = await this._state.decryptMessageData(body);\n } catch (e) {\n if (e instanceof TypeNotFoundError) {\n // Received object which we don't know how to deserialize\n this._log.info(`Type ${e.invalidConstructorId} not found, remaining data ${e.remaining}`);\n continue;\n } else if (e instanceof SecurityError) {\n // A step while decoding had the incorrect data. This message\n // should not be considered safe and it should be ignored.\n this._log.warn(`Security error while unpacking a received message: ${e}`);\n continue;\n } else if (e instanceof InvalidBufferError) {\n // 404 means that the server has \"forgotten\" our auth key and we need to create a new one.\n if (e.code === 404) {\n this._handleBadAuthKey();\n } else {\n // this happens sometimes when telegram is having some internal issues.\n // reconnecting should be enough usually\n // since the data we sent and received is probably wrong now.\n this._log.warn(`Invalid buffer ${e.code} for dc ${this._dcId}`);\n this.reconnect();\n }\n return;\n } else {\n this._log.error('Unhandled error while receiving data');\n this._log.error(e);\n this.reconnect();\n return;\n }\n }\n try {\n await this._processMessage(message);\n } catch (e) {\n // `RPCError` errors except for 'AUTH_KEY_UNREGISTERED' should be handled by the client\n if (e instanceof RPCError) {\n if (e.message === 'AUTH_KEY_UNREGISTERED') {\n // 'AUTH_KEY_UNREGISTERED' for the main sender is thrown when unauthorized and should be ignored\n this._handleBadAuthKey(true);\n }\n } else {\n this._log.error('Unhandled error while receiving data');\n this._log.error(e);\n }\n }\n }\n }\n\n _handleBadAuthKey(shouldSkipForMain) {\n if (shouldSkipForMain && this._isMainSender) {\n return;\n }\n\n this._log.warn(`Broken authorization key for dc ${this._dcId}, resetting...`);\n\n if (this._isMainSender && this._updateCallback) {\n this._updateCallback(new UpdateConnectionState(UpdateConnectionState.broken));\n } else if (!this._isMainSender && this._onConnectionBreak) {\n this._onConnectionBreak(this._dcId);\n }\n }\n\n // Response Handlers\n\n /**\n * Adds the given message to the list of messages that must be\n * acknowledged and dispatches control to different ``_handle_*``\n * method based on its type.\n * @param message\n * @returns {Promise}\n * @private\n */\n async _processMessage(message) {\n this._pending_ack.add(message.msgId);\n // eslint-disable-next-line require-atomic-updates\n message.obj = await message.obj;\n let handler = this._handlers[message.obj.CONSTRUCTOR_ID];\n if (!handler) {\n handler = this._handleUpdate.bind(this);\n }\n\n await handler(message);\n }\n\n /**\n * Pops the states known to match the given ID from pending messages.\n * This method should be used when the response isn't specific.\n * @param msgId\n * @returns {*[]}\n * @private\n */\n _popStates(msgId) {\n let state = this._pending_state[msgId];\n if (state) {\n this._pending_state[msgId].deferred.resolve();\n delete this._pending_state[msgId];\n return [state];\n }\n\n const toPop = [];\n\n for (state of Object.values(this._pending_state)) {\n if (state.containerId && state.containerId.equals(msgId)) {\n toPop.push(state.msgId);\n }\n }\n\n if (toPop.length) {\n const temp = [];\n for (const x of toPop) {\n temp.push(this._pending_state[x]);\n this._pending_state[x].deferred.resolve();\n delete this._pending_state[x];\n }\n return temp;\n }\n\n for (const ack of this._last_acks) {\n if (ack.msgId === msgId) {\n return [ack];\n }\n }\n\n return [];\n }\n\n /**\n * Handles the result for Remote Procedure Calls:\n * rpc_result#f35c6d01 req_msg_id:long result:bytes = RpcResult;\n * This is where the future results for sent requests are set.\n * @param message\n * @returns {Promise}\n * @private\n */\n _handleRPCResult(message) {\n const result = message.obj;\n const state = this._pending_state[result.reqMsgId];\n if (state) {\n state.deferred.resolve();\n delete this._pending_state[result.reqMsgId];\n }\n this._log.debug(`Handling RPC result for message ${result.reqMsgId}`);\n\n if (!state) {\n // TODO We should not get responses to things we never sent\n // However receiving a File() with empty bytes is \"common\".\n // See #658, #759 and #958. They seem to happen in a container\n // which contain the real response right after.\n try {\n const reader = new BinaryReader(result.body);\n if (!(reader.tgReadObject() instanceof upload.File)) {\n throw new TypeNotFoundError('Not an upload.File');\n }\n } catch (e) {\n this._log.error(e);\n if (e instanceof TypeNotFoundError) {\n this._log.info(`Received response without parent request: ${result.body}`);\n return;\n } else {\n throw e;\n }\n }\n }\n if (result.error) {\n // eslint-disable-next-line new-cap\n const error = RPCMessageToError(result.error, state.request);\n this._send_queue.append(new RequestState(new MsgsAck({ msgIds: [state.msgId] })));\n state.reject(error);\n throw error;\n } else {\n try {\n const reader = new BinaryReader(result.body);\n const read = state.request.readResult(reader);\n state.resolve(read);\n } catch (err) {\n state.reject(err);\n throw err;\n }\n }\n }\n\n /**\n * Processes the inner messages of a container with many of them:\n * msg_container#73f1f8dc messages:vector<%Message> = MessageContainer;\n * @param message\n * @returns {Promise}\n * @private\n */\n async _handleContainer(message) {\n this._log.debug('Handling container');\n for (const innerMessage of message.obj.messages) {\n await this._processMessage(innerMessage);\n }\n }\n\n /**\n * Unpacks the data from a gzipped object and processes it:\n * gzip_packed#3072cfa1 packed_data:bytes = Object;\n * @param message\n * @returns {Promise}\n * @private\n */\n async _handleGzipPacked(message) {\n this._log.debug('Handling gzipped data');\n const reader = new BinaryReader(message.obj.data);\n message.obj = reader.tgReadObject();\n await this._processMessage(message);\n }\n\n _handleUpdate(message) {\n if (message.obj.SUBCLASS_OF_ID !== 0x8af52aac) {\n // crc32(b'Updates')\n this._log.warn(`Note: ${message.obj.className} is not an update, not dispatching it`);\n return;\n }\n this._log.debug(`Handling update ${message.obj.className}`);\n if (this._updateCallback) {\n this._updateCallback(message.obj);\n }\n }\n\n /**\n * Handles pong results, which don't come inside a ``RPCResult``\n * but are still sent through a request:\n * pong#347773c5 msg_id:long ping_id:long = Pong;\n * @param message\n * @returns {Promise}\n * @private\n */\n _handlePong(message) {\n const pong = message.obj;\n\n const newTimeOffset = this._state.updateTimeOffset(message.msgId);\n if (this._updateCallback) {\n this._updateCallback(new UpdateServerTimeOffset(newTimeOffset));\n }\n\n this._log.debug(`Handling pong for message ${pong.msgId}`);\n const state = this._pending_state[pong.msgId];\n this._pending_state[pong.msgId].deferred.resolve();\n delete this._pending_state[pong.msgId];\n\n // Todo Check result\n if (state) {\n state.resolve(pong);\n }\n }\n\n /**\n * Corrects the currently used server salt to use the right value\n * before enqueuing the rejected message to be re-sent:\n * bad_server_salt#edab447b bad_msg_id:long bad_msg_seqno:int\n * error_code:int new_server_salt:long = BadMsgNotification;\n * @param message\n * @returns {Promise}\n * @private\n */\n _handleBadServerSalt(message) {\n const badSalt = message.obj;\n this._log.debug(`Handling bad salt for message ${badSalt.badMsgId}`);\n this._state.salt = badSalt.newServerSalt;\n const states = this._popStates(badSalt.badMsgId);\n this._send_queue.extend(states);\n this._log.debug(`${states.length} message(s) will be resent`);\n }\n\n /**\n * Adjusts the current state to be correct based on the\n * received bad message notification whenever possible:\n * bad_msg_notification#a7eff811 bad_msg_id:long bad_msg_seqno:int\n * error_code:int = BadMsgNotification;\n * @param message\n * @returns {Promise}\n * @private\n */\n _handleBadNotification(message) {\n const badMsg = message.obj;\n const states = this._popStates(badMsg.badMsgId);\n this._log.debug(`Handling bad msg ${JSON.stringify(badMsg)}`);\n if ([16, 17].includes(badMsg.errorCode)) {\n // Sent msg_id too low or too high (respectively).\n // Use the current msg_id to determine the right time offset.\n const newTimeOffset = this._state.updateTimeOffset(message.msgId);\n\n if (this._updateCallback) {\n this._updateCallback(new UpdateServerTimeOffset(newTimeOffset));\n }\n\n this._log.info(`System clock is wrong, set time offset to ${newTimeOffset}s`);\n } else if (badMsg.errorCode === 32) {\n // msg_seqno too low, so just pump it up by some \"large\" amount\n // TODO A better fix would be to start with a new fresh session ID\n this._state._sequence += 64;\n } else if (badMsg.errorCode === 33) {\n // msg_seqno too high never seems to happen but just in case\n this._state._sequence -= 16;\n } else {\n for (const state of states) {\n state.reject(new BadMessageError(state.request, badMsg.errorCode));\n }\n\n return;\n }\n // Messages are to be re-sent once we've corrected the issue\n this._send_queue.extend(states);\n this._log.debug(`${states.length} messages will be resent due to bad msg`);\n }\n\n /**\n * Updates the current status with the received detailed information:\n * msg_detailed_info#276d3ec6 msg_id:long answer_msg_id:long\n * bytes:int status:int = MsgDetailedInfo;\n * @param message\n * @returns {Promise}\n * @private\n */\n _handleDetailedInfo(message) {\n // TODO https://goo.gl/VvpCC6\n const msgId = message.obj.answerMsgId;\n this._log.debug(`Handling detailed info for message ${msgId}`);\n this._pending_ack.add(msgId);\n }\n\n /**\n * Updates the current status with the received detailed information:\n * msg_new_detailed_info#809db6df answer_msg_id:long\n * bytes:int status:int = MsgDetailedInfo;\n * @param message\n * @returns {Promise}\n * @private\n */\n _handleNewDetailedInfo(message) {\n // TODO https://goo.gl/VvpCC6\n const msgId = message.obj.answerMsgId;\n this._log.debug(`Handling new detailed info for message ${msgId}`);\n this._pending_ack.add(msgId);\n }\n\n /**\n * Updates the current status with the received session information:\n * new_session_created#9ec20908 first_msg_id:long unique_id:long\n * server_salt:long = NewSession;\n * @param message\n * @returns {Promise}\n * @private\n */\n _handleNewSessionCreated(message) {\n // TODO https://goo.gl/LMyN7A\n this._log.debug('Handling new session created');\n this._state.salt = message.obj.serverSalt;\n }\n\n /**\n * Handles a server acknowledge about our messages. Normally\n * these can be ignored except in the case of ``auth.logOut``:\n *\n * auth.logOut#5717da40 = Bool;\n *\n * Telegram doesn't seem to send its result so we need to confirm\n * it manually. No other request is known to have this behaviour.\n\n * Since the ID of sent messages consisting of a container is\n * never returned (unless on a bad notification), this method\n * also removes containers messages when any of their inner\n * messages are acknowledged.\n\n * @param message\n * @returns {Promise}\n * @private\n */\n _handleAck(message) {\n const ack = message.obj;\n this._log.debug(`Handling acknowledge for ${ack.msgIds}`);\n for (const msgId of ack.msgIds) {\n const state = this._pending_state[msgId];\n if (state && state.request instanceof LogOut) {\n this._pending_state[msgId].deferred.resolve();\n delete this._pending_state[msgId];\n state.resolve(true);\n }\n }\n }\n\n /**\n * Handles future salt results, which don't come inside a\n * ``rpc_result`` but are still sent through a request:\n * future_salts#ae500895 req_msg_id:long now:int\n * salts:vector = FutureSalts;\n * @param message\n * @returns {Promise}\n * @private\n */\n _handleFutureSalts(message) {\n // TODO save these salts and automatically adjust to the\n // correct one whenever the salt in use expires.\n this._log.debug(`Handling future salts for message ${message.msgId}`);\n const state = this._pending_state[message.msgId];\n\n if (state) {\n this._pending_state[message].deferred.resolve();\n delete this._pending_state[message];\n state.resolve(message.obj);\n }\n }\n\n /**\n * Handles both :tl:`MsgsStateReq` and :tl:`MsgResendReq` by\n * enqueuing a :tl:`MsgsStateInfo` to be sent at a later point.\n * @param message\n * @returns {Promise}\n * @private\n */\n _handleStateForgotten(message) {\n this._send_queue.append(\n new RequestState(new MsgsStateInfo(message.msgId, String.fromCharCode(1)\n .repeat(message.obj.msgIds))),\n );\n }\n\n /**\n * Handles :tl:`MsgsAllInfo` by doing nothing (yet).\n * used as part of the telegram protocol https://core.telegram.org/mtproto/service_messages_about_messages\n * This message does not require an acknowledgment.\n * @param message\n * @returns {Promise}\n * @private\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _handleMsgAll(message) {\n }\n\n reconnect() {\n if (this._user_connected && !this._reconnecting) {\n this._reconnecting = true;\n // TODO Should we set this?\n // this._user_connected = false\n // we want to wait a second between each reconnect try to not flood the server with reconnects\n // in case of internal server issues.\n Helpers.sleep(1000)\n .then(() => {\n this._log.info('Started reconnecting');\n this._reconnect();\n });\n }\n }\n\n async _reconnect() {\n this._log.debug('Closing current connection...');\n try {\n await this._disconnect();\n } catch (err) {\n this._log.warn(err);\n }\n\n this._send_queue.append(undefined);\n this._state.reset();\n\n // For some reason reusing existing connection caused stuck requests\n const newConnection = new this._connection.constructor(\n this._connection._ip,\n this._connection._port,\n this._connection._dcId,\n this._connection._log,\n this._connection._testServers,\n );\n await this.connect(newConnection, true);\n\n this._reconnecting = false;\n // uncomment this if you want to resend\n // this._send_queue.extend(Object.values(this._pending_state))\n for (const state of Object.values(this._pending_state)) {\n state.deferred.resolve();\n }\n this._pending_state = {};\n if (this._autoReconnectCallback) {\n await this._autoReconnectCallback();\n }\n }\n}\n\nmodule.exports = MTProtoSender;\n","const BigInt = require('big-integer');\n\nconst Helpers = require('../Helpers');\nconst IGE = require('../crypto/IGE');\nconst BinaryReader = require('../extensions/BinaryReader');\nconst GZIPPacked = require('../tl/core/GZIPPacked');\nconst { TLMessage } = require('../tl/core');\nconst {\n SecurityError,\n InvalidBufferError,\n} = require('../errors/Common');\nconst { InvokeAfterMsg } = require('../tl').requests;\nconst {\n toSignedLittleBuffer,\n} = require('../Helpers');\n\nclass MTProtoState {\n /**\n *\n `telethon.network.mtprotosender.MTProtoSender` needs to hold a state\n in order to be able to encrypt and decrypt incoming/outgoing messages,\n as well as generating the message IDs. Instances of this class hold\n together all the required information.\n\n It doesn't make sense to use `telethon.sessions.abstract.Session` for\n the sender because the sender should *not* be concerned about storing\n this information to disk, as one may create as many senders as they\n desire to any other data center, or some CDN. Using the same session\n for all these is not a good idea as each need their own authkey, and\n the concept of \"copying\" sessions with the unnecessary entities or\n updates state for these connections doesn't make sense.\n\n While it would be possible to have a `MTProtoPlainState` that does no\n encryption so that it was usable through the `MTProtoLayer` and thus\n avoid the need for a `MTProtoPlainSender`, the `MTProtoLayer` is more\n focused to efficiency and this state is also more advanced (since it\n supports gzipping and invoking after other message IDs). There are too\n many methods that would be needed to make it convenient to use for the\n authentication process, at which point the `MTProtoPlainSender` is better\n * @param authKey\n * @param loggers\n */\n constructor(authKey, loggers) {\n this.authKey = authKey;\n this._log = loggers;\n this.timeOffset = 0;\n this.salt = 0;\n\n this.id = undefined;\n this._sequence = undefined;\n this._lastMsgId = undefined;\n this.msgIds = [];\n this.reset();\n }\n\n /**\n * Resets the state\n */\n reset() {\n // Session IDs can be random on every connection\n this.id = Helpers.generateRandomLong(true);\n this._sequence = 0;\n this._lastMsgId = BigInt(0);\n this.msgIds = [];\n }\n\n /**\n * Updates the message ID to a new one,\n * used when the time offset changed.\n * @param message\n */\n updateMessageId(message) {\n message.msgId = this._getNewMsgId();\n }\n\n /**\n * Calculate the key based on Telegram guidelines, specifying whether it's the client or not\n * @param authKey\n * @param msgKey\n * @param client\n * @returns {{iv: Buffer, key: Buffer}}\n */\n async _calcKey(authKey, msgKey, client) {\n const x = client === true ? 0 : 8;\n const [sha256a, sha256b] = await Promise.all([\n Helpers.sha256(Buffer.concat([msgKey, authKey.slice(x, x + 36)])),\n Helpers.sha256(Buffer.concat([authKey.slice(x + 40, x + 76), msgKey])),\n ]);\n const key = Buffer.concat([sha256a.slice(0, 8), sha256b.slice(8, 24), sha256a.slice(24, 32)]);\n const iv = Buffer.concat([sha256b.slice(0, 8), sha256a.slice(8, 24), sha256b.slice(24, 32)]);\n return {\n key,\n iv,\n };\n }\n\n /**\n * Writes a message containing the given data into buffer.\n * Returns the message id.\n * @param buffer\n * @param data\n * @param contentRelated\n * @param afterId\n */\n async writeDataAsMessage(buffer, data, contentRelated, afterId) {\n const msgId = this._getNewMsgId();\n const seqNo = this._getSeqNo(contentRelated);\n let body;\n if (!afterId) {\n body = await GZIPPacked.gzipIfSmaller(contentRelated, data);\n } else {\n // Invoke query expects a query with a getBytes func\n body = await GZIPPacked.gzipIfSmaller(contentRelated, new InvokeAfterMsg(afterId, {\n getBytes() {\n return data;\n },\n }).getBytes());\n }\n const s = Buffer.alloc(4);\n s.writeInt32LE(seqNo, 0);\n const b = Buffer.alloc(4);\n b.writeInt32LE(body.length, 0);\n const m = toSignedLittleBuffer(msgId, 8);\n buffer.write(Buffer.concat([m, s, b]));\n buffer.write(body);\n return msgId;\n }\n\n /**\n * Encrypts the given message data using the current authorization key\n * following MTProto 2.0 guidelines core.telegram.org/mtproto/description.\n * @param data\n */\n async encryptMessageData(data) {\n await this.authKey.waitForKey();\n const s = toSignedLittleBuffer(this.salt, 8);\n const i = toSignedLittleBuffer(this.id, 8);\n data = Buffer.concat([Buffer.concat([s, i]), data]);\n const padding = Helpers.generateRandomBytes(Helpers.mod(-(data.length + 12), 16) + 12);\n // Being substr(what, offset, length); x = 0 for client\n // \"msg_key_large = SHA256(substr(auth_key, 88+x, 32) + pt + padding)\"\n const msgKeyLarge = await Helpers.sha256(Buffer.concat([this.authKey.getKey()\n .slice(88, 88 + 32), data, padding]));\n // \"msg_key = substr (msg_key_large, 8, 16)\"\n const msgKey = msgKeyLarge.slice(8, 24);\n\n const {\n iv,\n key,\n } = await this._calcKey(this.authKey.getKey(), msgKey, true);\n\n const keyId = Helpers.readBufferFromBigInt(this.authKey.keyId, 8);\n return Buffer.concat([keyId, msgKey, new IGE(key, iv).encryptIge(Buffer.concat([data, padding]))]);\n }\n\n /**\n * Inverse of `encrypt_message_data` for incoming server messages.\n * @param body\n */\n async decryptMessageData(body) {\n if (body.length < 8) {\n throw new InvalidBufferError(body);\n }\n if (body.length < 0) { // length needs to be positive\n throw new SecurityError('Server replied with negative length');\n }\n if (body.length % 4 !== 0) {\n throw new SecurityError('Server replied with length not divisible by 4');\n }\n // TODO Check salt,sessionId, and sequenceNumber\n const keyId = Helpers.readBigIntFromBuffer(body.slice(0, 8));\n if (keyId.neq(this.authKey.keyId)) {\n throw new SecurityError('Server replied with an invalid auth key');\n }\n\n const msgKey = body.slice(8, 24);\n const {\n iv,\n key,\n } = await this._calcKey(this.authKey.getKey(), msgKey, false);\n body = new IGE(key, iv).decryptIge(body.slice(24));\n\n // https://core.telegram.org/mtproto/security_guidelines\n // Sections \"checking sha256 hash\" and \"message length\"\n\n const ourKey = await Helpers.sha256(Buffer.concat([this.authKey.getKey()\n .slice(96, 96 + 32), body]));\n\n if (!msgKey.equals(ourKey.slice(8, 24))) {\n throw new SecurityError('Received msg_key doesn\\'t match with expected one');\n }\n\n const reader = new BinaryReader(body);\n reader.readLong(); // removeSalt\n const serverId = reader.readLong();\n if (!serverId.eq(this.id)) {\n throw new SecurityError('Server replied with a wrong session ID');\n }\n\n const remoteMsgId = reader.readLong();\n // if we get a duplicate message id we should ignore it.\n if (this.msgIds.includes(remoteMsgId.toString())) {\n throw new SecurityError('Duplicate msgIds');\n }\n // we only store the latest 500 message ids from the server\n if (this.msgIds.length > 500) {\n this.msgIds.shift();\n }\n this.msgIds.push(remoteMsgId.toString());\n\n const remoteSequence = reader.readInt();\n const containerLen = reader.readInt(); // msgLen for the inner object, padding ignored\n const diff = body.length - containerLen;\n // We want to check if it's between 12 and 1024\n // https://core.telegram.org/mtproto/security_guidelines#checking-message-length\n if (diff < 12 || diff > 1024) {\n throw new SecurityError('Server replied with the wrong message padding');\n }\n\n // We could read msg_len bytes and use those in a new reader to read\n // the next TLObject without including the padding, but since the\n // reader isn't used for anything else after this, it's unnecessary.\n const obj = reader.tgReadObject();\n\n return new TLMessage(remoteMsgId, remoteSequence, obj);\n }\n\n /**\n * Generates a new unique message ID based on the current\n * time (in ms) since epoch, applying a known time offset.\n * @private\n */\n _getNewMsgId() {\n const now = new Date().getTime() / 1000 + this.timeOffset;\n const nanoseconds = Math.floor((now - Math.floor(now)) * 1e9);\n let newMsgId = (BigInt(Math.floor(now))\n .shiftLeft(BigInt(32))).or(BigInt(nanoseconds)\n .shiftLeft(BigInt(2)));\n if (this._lastMsgId.greaterOrEquals(newMsgId)) {\n newMsgId = this._lastMsgId.add(BigInt(4));\n }\n this._lastMsgId = newMsgId;\n return newMsgId;\n }\n\n /**\n * Updates the time offset to the correct\n * one given a known valid message ID.\n * @param correctMsgId {BigInteger}\n */\n updateTimeOffset(correctMsgId) {\n const bad = this._getNewMsgId();\n const old = this.timeOffset;\n const now = Math.floor(new Date().getTime() / 1000);\n const correct = correctMsgId.shiftRight(BigInt(32));\n this.timeOffset = correct - now;\n\n if (this.timeOffset !== old) {\n this._lastMsgId = BigInt(0);\n this._log.debug(\n `Updated time offset (old offset ${old}, bad ${bad}, good ${correctMsgId}, new ${this.timeOffset})`,\n );\n }\n\n return this.timeOffset;\n }\n\n /**\n * Generates the next sequence number depending on whether\n * it should be for a content-related query or not.\n * @param contentRelated\n * @private\n */\n _getSeqNo(contentRelated) {\n if (contentRelated) {\n const result = this._sequence * 2 + 1;\n this._sequence += 1;\n return result;\n } else {\n return this._sequence * 2;\n }\n }\n}\n\nmodule.exports = MTProtoState;\n","const { createDeferred } = require('../Helpers');\n\nclass RequestState {\n constructor(request, after = undefined, pending = {}) {\n this.containerId = undefined;\n this.msgId = undefined;\n this.request = request;\n this.data = request.getBytes();\n this.after = after;\n this.result = undefined;\n this.pending = pending;\n this.deferred = createDeferred();\n this.promise = new Promise((resolve, reject) => {\n this.resolve = resolve;\n this.reject = reject;\n });\n }\n\n isReady() {\n const state = this.pending[this.after.id];\n if (!state) {\n return true;\n }\n return state.deferred.promise;\n }\n}\n\nmodule.exports = RequestState;\n","const PromisedWebSockets = require('../../extensions/PromisedWebSockets');\nconst AsyncQueue = require('../../extensions/AsyncQueue');\n\n/**\n * The `Connection` class is a wrapper around ``asyncio.open_connection``.\n *\n * Subclasses will implement different transport modes as atomic operations,\n * which this class eases doing since the exposed interface simply puts and\n * gets complete data payloads to and from queues.\n *\n * The only error that will raise from send and receive methods is\n * ``ConnectionError``, which will raise when attempting to send if\n * the client is disconnected (includes remote disconnections).\n */\nclass Connection {\n PacketCodecClass = undefined;\n\n constructor(ip, port, dcId, loggers, testServers) {\n this._ip = ip;\n this._port = port;\n this._dcId = dcId;\n this._log = loggers;\n this._testServers = testServers;\n this._connected = false;\n this._sendTask = undefined;\n this._recvTask = undefined;\n this._codec = undefined;\n this._obfuscation = undefined; // TcpObfuscated and MTProxy\n this._sendArray = new AsyncQueue();\n this._recvArray = new AsyncQueue();\n // this.socket = new PromiseSocket(new Socket())\n\n this.socket = new PromisedWebSockets(this.disconnectCallback.bind(this));\n }\n\n async disconnectCallback() {\n await this.disconnect(true);\n }\n\n async _connect() {\n this._log.debug('Connecting');\n this._codec = new this.PacketCodecClass(this);\n await this.socket.connect(this._port, this._ip, this._testServers);\n this._log.debug('Finished connecting');\n // await this.socket.connect({host: this._ip, port: this._port});\n await this._initConn();\n }\n\n async connect() {\n await this._connect();\n this._connected = true;\n\n if (!this._sendTask) {\n this._sendTask = this._sendLoop();\n }\n this._recvTask = this._recvLoop();\n }\n\n async disconnect(fromCallback = false) {\n if (!this._connected) {\n return;\n }\n\n this._connected = false;\n void this._recvArray.push(undefined);\n if (!fromCallback) {\n await this.socket.close();\n }\n }\n\n async send(data) {\n if (!this._connected) {\n throw new Error('Not connected');\n }\n await this._sendArray.push(data);\n }\n\n async recv() {\n while (this._connected) {\n const result = await this._recvArray.pop();\n // null = sentinel value = keep trying\n if (result) {\n return result;\n }\n }\n throw new Error('Not connected');\n }\n\n async _sendLoop() {\n // TODO handle errors\n try {\n while (this._connected) {\n const data = await this._sendArray.pop();\n if (!data) {\n this._sendTask = undefined;\n return;\n }\n await this._send(data);\n }\n } catch (e) {\n this._log.info('The server closed the connection while sending');\n }\n }\n\n async _recvLoop() {\n let data;\n while (this._connected) {\n try {\n data = await this._recv();\n if (!data) {\n throw new Error('no data received');\n }\n } catch (e) {\n this._log.info('connection closed');\n // await this._recvArray.push()\n\n this.disconnect();\n return;\n }\n await this._recvArray.push(data);\n }\n }\n\n async _initConn() {\n if (this._codec.tag) {\n await this.socket.write(this._codec.tag);\n }\n }\n\n _send(data) {\n const encodedPacket = this._codec.encodePacket(data);\n this.socket.write(encodedPacket);\n }\n\n _recv() {\n return this._codec.readPacket(this.socket);\n }\n\n toString() {\n return `${this._ip}:${this._port}/${this.constructor.name.replace('Connection', '')}`;\n }\n}\n\nclass ObfuscatedConnection extends Connection {\n ObfuscatedIO = undefined;\n\n _initConn() {\n this._obfuscation = new this.ObfuscatedIO(this);\n this.socket.write(this._obfuscation.header);\n }\n\n _send(data) {\n this._obfuscation.write(this._codec.encodePacket(data));\n }\n\n _recv() {\n return this._codec.readPacket(this._obfuscation);\n }\n}\n\nclass PacketCodec {\n constructor(connection) {\n this._conn = connection;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n encodePacket(data) {\n throw new Error('Not Implemented');\n\n // Override\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n readPacket(reader) {\n // override\n throw new Error('Not Implemented');\n }\n}\n\nmodule.exports = {\n Connection,\n PacketCodec,\n ObfuscatedConnection,\n};\n","const BigInt = require('big-integer');\nconst { readBufferFromBigInt } = require('../../Helpers');\nconst {\n Connection,\n PacketCodec,\n} = require('./Connection');\n\nclass AbridgedPacketCodec extends PacketCodec {\n static tag = Buffer.from('ef', 'hex');\n\n static obfuscateTag = Buffer.from('efefefef', 'hex');\n\n constructor(props) {\n super(props);\n this.tag = AbridgedPacketCodec.tag;\n this.obfuscateTag = AbridgedPacketCodec.obfuscateTag;\n }\n\n encodePacket(data) {\n let length = data.length >> 2;\n if (length < 127) {\n const b = Buffer.alloc(1);\n b.writeUInt8(length, 0);\n length = b;\n } else {\n length = Buffer.concat([Buffer.from('7f', 'hex'), readBufferFromBigInt(BigInt(length), 3)]);\n }\n return Buffer.concat([length, data]);\n }\n\n async readPacket(reader) {\n const readData = await reader.read(1);\n let length = readData[0];\n if (length >= 127) {\n length = Buffer.concat([await reader.read(3), Buffer.alloc(1)])\n .readInt32LE(0);\n }\n\n return reader.read(length << 2);\n }\n}\n\n/**\n * This is the mode with the lowest overhead, as it will\n * only require 1 byte if the packet length is less than\n * 508 bytes (127 << 2, which is very common).\n */\nclass ConnectionTCPAbridged extends Connection {\n PacketCodecClass = AbridgedPacketCodec;\n}\n\nmodule.exports = {\n ConnectionTCPAbridged,\n AbridgedPacketCodec,\n};\n","const { generateRandomBytes } = require('../../Helpers');\nconst { ObfuscatedConnection } = require('./Connection');\nconst { AbridgedPacketCodec } = require('./TCPAbridged');\nconst CTR = require('../../crypto/CTR');\n\nclass ObfuscatedIO {\n header = undefined;\n\n constructor(connection) {\n this.connection = connection.socket;\n const res = this.initHeader(connection.PacketCodecClass);\n this.header = res.random;\n\n this._encrypt = res.encryptor;\n this._decrypt = res.decryptor;\n }\n\n initHeader(packetCodec) {\n // Obfuscated messages secrets cannot start with any of these\n const keywords = [Buffer.from('50567247', 'hex'), Buffer.from('474554', 'hex'),\n Buffer.from('504f5354', 'hex'), Buffer.from('eeeeeeee', 'hex')];\n let random;\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n random = generateRandomBytes(64);\n if (random[0] !== 0xef && !(random.slice(4, 8)\n .equals(Buffer.alloc(4)))) {\n let ok = true;\n for (const key of keywords) {\n if (key.equals(random.slice(0, 4))) {\n ok = false;\n break;\n }\n }\n if (ok) {\n break;\n }\n }\n }\n random = random.toJSON().data;\n\n const randomReversed = Buffer.from(random.slice(8, 56))\n .reverse();\n // Encryption has \"continuous buffer\" enabled\n const encryptKey = Buffer.from(random.slice(8, 40));\n const encryptIv = Buffer.from(random.slice(40, 56));\n const decryptKey = Buffer.from(randomReversed.slice(0, 32));\n const decryptIv = Buffer.from(randomReversed.slice(32, 48));\n const encryptor = new CTR(encryptKey, encryptIv);\n const decryptor = new CTR(decryptKey, decryptIv);\n\n random = Buffer.concat([\n Buffer.from(random.slice(0, 56)), packetCodec.obfuscateTag, Buffer.from(random.slice(60)),\n ]);\n random = Buffer.concat([\n Buffer.from(random.slice(0, 56)), Buffer.from(encryptor.encrypt(random)\n .slice(56, 64)), Buffer.from(random.slice(64)),\n ]);\n return {\n random,\n encryptor,\n decryptor,\n };\n }\n\n async read(n) {\n const data = await this.connection.readExactly(n);\n return this._decrypt.encrypt(data);\n }\n\n write(data) {\n this.connection.write(this._encrypt.encrypt(data));\n }\n}\n\nclass ConnectionTCPObfuscated extends ObfuscatedConnection {\n ObfuscatedIO = ObfuscatedIO;\n\n PacketCodecClass = AbridgedPacketCodec;\n}\n\nmodule.exports = {\n ConnectionTCPObfuscated,\n};\n","const { Connection } = require('./Connection');\nconst { ConnectionTCPFull } = require('./TCPFull');\nconst { ConnectionTCPAbridged } = require('./TCPAbridged');\nconst { ConnectionTCPObfuscated } = require('./TCPObfuscated');\n\nmodule.exports = {\n Connection,\n ConnectionTCPFull,\n ConnectionTCPAbridged,\n ConnectionTCPObfuscated,\n};\n","const MTProtoPlainSender = require('./MTProtoPlainSender');\nconst MTProtoSender = require('./MTProtoSender');\n\nclass UpdateConnectionState {\n static disconnected = -1;\n\n static connected = 1;\n\n static broken = 0;\n\n constructor(state) {\n this.state = state;\n }\n}\n\nclass UpdateServerTimeOffset {\n constructor(timeOffset) {\n this.timeOffset = timeOffset;\n }\n}\n\nconst {\n Connection,\n ConnectionTCPFull,\n ConnectionTCPAbridged,\n ConnectionTCPObfuscated,\n} = require('./connection');\n\nmodule.exports = {\n Connection,\n ConnectionTCPFull,\n ConnectionTCPAbridged,\n ConnectionTCPObfuscated,\n MTProtoPlainSender,\n MTProtoSender,\n UpdateConnectionState,\n UpdateServerTimeOffset,\n};\n","class Session {\n /**\n * Creates a clone of this session file\n * @param toInstance {Session|null}\n * @returns {Session}\n */\n\n /* CONTEST\n clone(toInstance = null) {\n return toInstance || new this.constructor()\n } */\n\n /**\n * Returns the currently-used data center ID.\n */\n get dcId() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Returns the server address where the library should connect to.\n */\n get serverAddress() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Returns the port to which the library should connect to.\n */\n get port() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Returns an ``AuthKey`` instance associated with the saved\n * data center, or `None` if a new one should be generated.\n */\n get authKey() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Sets the ``AuthKey`` to be used for the saved data center.\n * @param value\n */\n set authKey(value) {\n throw new Error('Not Implemented');\n }\n\n /**\n * Sets the information of the data center address and port that\n * the library should connect to, as well as the data center ID,\n * which is currently unused.\n * @param dcId {number}\n * @param serverAddress {string}\n * @param port {number}\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n setDC(dcId, serverAddress, port) {\n throw new Error('Not implemented');\n }\n\n /**\n * Returns an ID of the takeout process initialized for this session,\n * or `None` if there's no were any unfinished takeout requests.\n */\n /* CONTEST\n get takeoutId() {\n throw new Error('Not Implemented')\n }\n */\n /**\n * Sets the ID of the unfinished takeout process for this session.\n * @param value\n */\n /* CONTEST\n set takeoutId(value) {\n throw new Error('Not Implemented')\n }\n */\n /**\n * Returns the ``UpdateState`` associated with the given `entity_id`.\n * If the `entity_id` is 0, it should return the ``UpdateState`` for\n * no specific channel (the \"general\" state). If no state is known\n * it should ``return None``.\n * @param entityId\n */\n /* CONTEST\n getUpdateState(entityId) {\n throw new Error('Not Implemented')\n }\n\n */\n\n /**\n * Sets the given ``UpdateState`` for the specified `entity_id`, which\n * should be 0 if the ``UpdateState`` is the \"general\" state (and not\n * for any specific channel).\n * @param entityId\n * @param state\n */\n /* CONTEST\n setUpdateState(entityId, state) {\n throw new Error('Not Implemented')\n }\n\n */\n\n /**\n * Called on client disconnection. Should be used to\n * free any used resources. Can be left empty if none.\n */\n\n /* CONTEST\n close() {\n\n }\n\n */\n\n /**\n * called whenever important properties change. It should\n * make persist the relevant session information to disk.\n */\n save() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Called upon client.log_out(). Should delete the stored\n * information from disk since it's not valid anymore.\n */\n\n delete() {\n throw new Error('Not Implemented');\n }\n\n /**\n * Lists available sessions. Not used by the library itself.\n */\n /* CONTEST\n listSessions() {\n throw new Error('Not Implemented')\n }\n\n */\n\n /**\n * Processes the input ``TLObject`` or ``list`` and saves\n * whatever information is relevant (e.g., ID or access hash).\n * @param tlo\n */\n /* CONTEST\n processEntities(tlo) {\n throw new Error('Not Implemented')\n }\n\n */\n\n /**\n * Turns the given key into an ``InputPeer`` (e.g. ``InputPeerUser``).\n * The library uses this method whenever an ``InputPeer`` is needed\n * to suit several purposes (e.g. user only provided its ID or wishes\n * to use a cached username to avoid extra RPC).\n */\n /* CONTEST\n getInputEntity(key) {\n throw new Error('Not Implemented')\n }\n\n */\n}\n\nmodule.exports = Session;\n","/* eslint-disable no-restricted-globals */\nconst StorageSession = require('./StorageSession');\n\nconst CACHE_NAME = 'GramJs';\n\nclass CacheApiSession extends StorageSession {\n async _delete() {\n const request = new Request(this._storageKey);\n const cache = await self.caches.open(CACHE_NAME);\n return cache.delete(request);\n }\n\n async _fetchFromCache() {\n const request = new Request(this._storageKey);\n const cache = await self.caches.open(CACHE_NAME);\n const cached = await cache.match(request);\n return cached ? cached.text() : undefined;\n }\n\n async _saveToCache(data) {\n const request = new Request(this._storageKey);\n const response = new Response(data);\n const cache = await self.caches.open(CACHE_NAME);\n return cache.put(request, response);\n }\n}\n\nmodule.exports = CacheApiSession;\n","const MemorySession = require('./Memory');\nconst AuthKey = require('../crypto/AuthKey');\nconst utils = require('../Utils');\n\nclass CallbackSession extends MemorySession {\n constructor(sessionData, callback) {\n super();\n\n this._sessionData = sessionData;\n this._callback = callback;\n\n this._authKeys = {};\n }\n\n get authKey() {\n throw new Error('Not supported');\n }\n\n set authKey(value) {\n throw new Error('Not supported');\n }\n\n async load() {\n if (!this._sessionData) {\n return;\n }\n\n const {\n mainDcId,\n keys,\n hashes,\n } = this._sessionData;\n const {\n ipAddress,\n port,\n } = utils.getDC(mainDcId);\n\n this.setDC(mainDcId, ipAddress, port, true);\n\n await Promise.all(Object.keys(keys)\n .map(async (dcId) => {\n const key = typeof keys[dcId] === 'string'\n ? Buffer.from(keys[dcId], 'hex')\n : Buffer.from(keys[dcId]);\n\n if (hashes[dcId]) {\n const hash = typeof hashes[dcId] === 'string'\n ? Buffer.from(hashes[dcId], 'hex')\n : Buffer.from(hashes[dcId]);\n\n this._authKeys[dcId] = new AuthKey(key, hash);\n } else {\n this._authKeys[dcId] = new AuthKey();\n await this._authKeys[dcId].setKey(key, true);\n }\n }));\n }\n\n setDC(dcId, serverAddress, port, skipOnUpdate = false) {\n this._dcId = dcId;\n this._serverAddress = serverAddress;\n this._port = port;\n\n delete this._authKeys[dcId];\n\n if (!skipOnUpdate) {\n void this._onUpdate();\n }\n }\n\n getAuthKey(dcId = this._dcId) {\n return this._authKeys[dcId];\n }\n\n setAuthKey(authKey, dcId = this._dcId) {\n this._authKeys[dcId] = authKey;\n\n void this._onUpdate();\n }\n\n getSessionData() {\n const sessionData = {\n mainDcId: this._dcId,\n keys: {},\n hashes: {},\n };\n\n Object\n .keys(this._authKeys)\n .forEach((dcId) => {\n const authKey = this._authKeys[dcId];\n if (!authKey || !authKey._key) return;\n\n sessionData.keys[dcId] = authKey._key.toString('hex');\n sessionData.hashes[dcId] = authKey._hash.toString('hex');\n });\n\n return sessionData;\n }\n\n _onUpdate() {\n this._callback(this.getSessionData());\n }\n\n delete() {\n this._callback(undefined);\n }\n}\n\nmodule.exports = CallbackSession;\n","const idb = require('idb-keyval');\nconst StorageSession = require('./StorageSession');\n\nconst CACHE_NAME = 'GramJs';\n\nclass IdbSession extends StorageSession {\n _delete() {\n return idb.del(`${CACHE_NAME}:${this._storageKey}`);\n }\n\n _fetchFromCache() {\n return idb.get(`${CACHE_NAME}:${this._storageKey}`);\n }\n\n _saveToCache(data) {\n return idb.set(`${CACHE_NAME}:${this._storageKey}`, data);\n }\n}\n\nmodule.exports = IdbSession;\n","const StorageSession = require('./StorageSession');\n\nclass LocalStorageSession extends StorageSession {\n _delete() {\n return localStorage.removeItem(this._storageKey);\n }\n\n _fetchFromCache() {\n return localStorage.getItem(this._storageKey);\n }\n\n _saveToCache(data) {\n return localStorage.setItem(this._storageKey, data);\n }\n}\n\nmodule.exports = LocalStorageSession;\n","const Session = require('./Abstract');\n\nclass MemorySession extends Session {\n constructor() {\n super();\n\n this._serverAddress = undefined;\n this._dcId = 0;\n this._port = undefined;\n this._takeoutId = undefined;\n\n this._entities = new Set();\n this._updateStates = {};\n }\n\n get dcId() {\n return this._dcId;\n }\n\n get serverAddress() {\n return this._serverAddress;\n }\n\n get port() {\n return this._port;\n }\n\n get authKey() {\n return this._authKey;\n }\n\n set authKey(value) {\n this._authKey = value;\n }\n\n setDC(dcId, serverAddress, port) {\n this._dcId = dcId | 0;\n this._serverAddress = serverAddress;\n this._port = port;\n }\n\n /* CONTEST\n get takeoutId() {\n return this._takeoutId\n }\n\n set takeoutId(value) {\n this._takeoutId = value\n }\n\n\n getUpdateState(entityId) {\n return this._updateStates[entityId]\n }\n\n setUpdateState(entityId, state) {\n return this._updateStates[entityId] = state\n }\n\n close() {\n }\n\n save() {\n }\n\n async load() {\n\n }\n\n delete() {\n }\n\n _entityValuesToRow(id, hash, username, phone, name) {\n // While this is a simple implementation it might be overrode by,\n // other classes so they don't need to implement the plural form\n // of the method. Don't remove.\n return [id, hash, username, phone, name]\n }\n\n _entityToRow(e) {\n if (!(e.classType === \"constructor\")) {\n return\n }\n let p\n let markedId\n try {\n p = utils.getInputPeer(e, false)\n markedId = utils.getPeerId(p)\n } catch (e) {\n // Note: `get_input_peer` already checks for non-zero `accessHash`.\n // See issues #354 and #392. It also checks that the entity\n // is not `min`, because its `accessHash` cannot be used\n // anywhere (since layer 102, there are two access hashes).\n return\n }\n let pHash\n if (p instanceof types.InputPeerUser || p instanceof types.InputPeerChannel) {\n pHash = p.accessHash\n } else if (p instanceof types.InputPeerChat) {\n pHash = 0\n } else {\n return\n }\n\n let username = e.username\n if (username) {\n username = username.toLowerCase()\n }\n const phone = e.phone\n const name = utils.getDisplayName(e)\n return this._entityValuesToRow(markedId, pHash, username, phone, name)\n }\n\n _entitiesToRows(tlo) {\n let entities = []\n if (tlo.classType === \"constructor\" && utils.isListLike(tlo)) {\n // This may be a list of users already for instance\n entities = tlo\n } else {\n if (tlo instanceof Object) {\n if ('user' in tlo) {\n entities.push(tlo.user)\n }\n if ('chats' in tlo && utils.isListLike(tlo.chats)) {\n entities.concat(tlo.chats)\n }\n if ('users' in tlo && utils.isListLike(tlo.users)) {\n entities.concat(tlo.users)\n }\n }\n }\n const rows = [] // Rows to add (id, hash, username, phone, name)\n for (const e of entities) {\n const row = this._entityToRow(e)\n if (row) {\n rows.push(row)\n }\n }\n return rows\n }\n\n processEntities(tlo) {\n const entitiesSet = this._entitiesToRows(tlo)\n for (const e of entitiesSet) {\n this._entities.add(e)\n }\n }\n\n getEntityRowsByPhone(phone) {\n for (const e of this._entities) { // id, hash, username, phone, name\n if (e[3] === phone) {\n return [e[0], e[1]]\n }\n }\n }\n\n getEntityRowsByUsername(username) {\n for (const e of this._entities) { // id, hash, username, phone, name\n if (e[2] === username) {\n return [e[0], e[1]]\n }\n }\n }\n\n getEntityRowsByName(name) {\n for (const e of this._entities) { // id, hash, username, phone, name\n if (e[4] === name) {\n return [e[0], e[1]]\n }\n }\n }\n\n getEntityRowsById(id, exact = true) {\n if (exact) {\n for (const e of this._entities) { // id, hash, username, phone, name\n if (e[0] === id) {\n return [e[0], e[1]]\n }\n }\n } else {\n const ids = [utils.getPeerId(new types.PeerUser({ userId: id })),\n utils.getPeerId(new types.PeerChat({ chatId: id })),\n utils.getPeerId(new types.PeerChannel({ channelId: id })),\n ]\n for (const e of this._entities) { // id, hash, username, phone, name\n if (ids.includes(e[0])) {\n return [e[0], e[1]]\n }\n }\n }\n }\n\n getInputEntity(key) {\n let exact\n if (key.SUBCLASS_OF_ID !== undefined) {\n if ([0xc91c90b6, 0xe669bf46, 0x40f202fd].includes(key.SUBCLASS_OF_ID)) {\n // hex(crc32(b'InputPeer', b'InputUser' and b'InputChannel'))\n // We already have an Input version, so nothing else required\n return key\n }\n // Try to early return if this key can be casted as input peer\n return utils.getInputPeer(key)\n } else {\n // Not a TLObject or can't be cast into InputPeer\n if (key.classType === 'constructor') {\n key = utils.getPeerId(key)\n exact = true\n } else {\n exact = !(typeof key == 'number') || key < 0\n }\n }\n let result = null\n if (typeof key === 'string') {\n const phone = utils.parsePhone(key)\n if (phone) {\n result = this.getEntityRowsByPhone(phone)\n } else {\n const { username, isInvite } = utils.parseUsername(key)\n if (username && !isInvite) {\n result = this.getEntityRowsByUsername(username)\n } else {\n const tup = utils.resolveInviteLink(key)[1]\n if (tup) {\n result = this.getEntityRowsById(tup, false)\n }\n }\n }\n } else if (typeof key === 'number') {\n result = this.getEntityRowsById(key, exact)\n }\n if (!result && typeof key === 'string') {\n result = this.getEntityRowsByName(key)\n }\n\n if (result) {\n let entityId = result[0] // unpack resulting tuple\n const entityHash = result[1]\n const resolved = utils.resolveId(entityId)\n entityId = resolved[0]\n const kind = resolved[1]\n // removes the mark and returns type of entity\n if (kind === types.PeerUser) {\n return new types.InputPeerUser({ userId: entityId, accessHash: entityHash })\n } else if (kind === types.PeerChat) {\n return new types.InputPeerChat({ chatId: entityId })\n } else if (kind === types.PeerChannel) {\n return new types.InputPeerChannel({ channelId: entityId, accessHash: entityHash })\n }\n } else {\n throw new Error('Could not find input entity with key ' + key)\n }\n } */\n}\n\nmodule.exports = MemorySession;\n","const MemorySession = require('./Memory');\nconst AuthKey = require('../crypto/AuthKey');\nconst utils = require('../Utils');\n\nconst STORAGE_KEY_BASE = 'GramJs-session-';\nconst SESSION_DATA_PREFIX = 'session:';\n\nclass StorageSession extends MemorySession {\n constructor(sessionInfo) {\n super();\n\n this._authKeys = {};\n\n if (sessionInfo && sessionInfo.startsWith(SESSION_DATA_PREFIX)) {\n this._sessionString = sessionInfo;\n } else if (sessionInfo) {\n this._storageKey = sessionInfo;\n }\n }\n\n get authKey() {\n throw new Error('Not supported');\n }\n\n set authKey(value) {\n throw new Error('Not supported');\n }\n\n async load() {\n if (this._sessionString) {\n await this._loadFromSessionString();\n return;\n }\n\n if (!this._storageKey) {\n return;\n }\n\n try {\n const json = await this._fetchFromCache();\n const {\n mainDcId,\n keys,\n hashes,\n } = JSON.parse(json);\n const {\n ipAddress,\n port,\n } = utils.getDC(mainDcId);\n\n this.setDC(mainDcId, ipAddress, port, true);\n\n Object.keys(keys)\n .forEach((dcId) => {\n if (keys[dcId] && hashes[dcId]) {\n this._authKeys[dcId] = new AuthKey(\n Buffer.from(keys[dcId].data),\n Buffer.from(hashes[dcId].data),\n );\n }\n });\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn('Failed to retrieve or parse session from storage');\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n }\n\n setDC(dcId, serverAddress, port, skipUpdateStorage = false) {\n this._dcId = dcId;\n this._serverAddress = serverAddress;\n this._port = port;\n\n delete this._authKeys[dcId];\n\n if (!skipUpdateStorage) {\n void this._updateStorage();\n }\n }\n\n async save() {\n if (!this._storageKey) {\n this._storageKey = generateStorageKey();\n }\n\n await this._updateStorage();\n\n return this._storageKey;\n }\n\n getAuthKey(dcId = this._dcId) {\n return this._authKeys[dcId];\n }\n\n setAuthKey(authKey, dcId = this._dcId) {\n this._authKeys[dcId] = authKey;\n\n void this._updateStorage();\n }\n\n getSessionData(asHex) {\n const sessionData = {\n mainDcId: this._dcId,\n keys: {},\n hashes: {},\n };\n\n Object\n .keys(this._authKeys)\n .forEach((dcId) => {\n const authKey = this._authKeys[dcId];\n if (!authKey._key) return;\n\n sessionData.keys[dcId] = asHex ? authKey._key.toString('hex') : authKey._key;\n sessionData.hashes[dcId] = asHex ? authKey._hash.toString('hex') : authKey._hash;\n });\n\n return sessionData;\n }\n\n async _loadFromSessionString() {\n const [, mainDcIdStr, mainDcKey] = this._sessionString.split(':');\n const mainDcId = Number(mainDcIdStr);\n const {\n ipAddress,\n port,\n } = utils.getDC(mainDcId);\n this.setDC(mainDcId, ipAddress, port);\n const authKey = new AuthKey();\n await authKey.setKey(Buffer.from(mainDcKey, 'hex'), true);\n this.setAuthKey(authKey, mainDcId);\n }\n\n async _updateStorage() {\n if (!this._storageKey) {\n return;\n }\n\n try {\n await this._saveToCache(JSON.stringify(this.getSessionData()));\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn('Failed to update session in storage');\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n }\n\n async delete() {\n try {\n return await this._delete();\n } catch (err) {\n // eslint-disable-next-line no-console\n console.warn('Failed to delete session from storage');\n // eslint-disable-next-line no-console\n console.warn(err);\n }\n return undefined;\n }\n\n // @abstract\n _delete() {\n throw new Error('Not Implemented');\n }\n\n // @abstract\n _fetchFromCache() {\n throw new Error('Not Implemented');\n }\n\n // @abstract\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _saveToCache(data) {\n throw new Error('Not Implemented');\n }\n}\n\nfunction generateStorageKey() {\n // Creating two sessions at the same moment is not expected nor supported.\n return `${STORAGE_KEY_BASE}${Date.now()}`;\n}\n\nmodule.exports = StorageSession;\n","const MemorySession = require('./Memory');\nconst AuthKey = require('../crypto/AuthKey');\nconst BinaryReader = require('../extensions/BinaryReader');\n\nconst CURRENT_VERSION = '1';\n\n\nclass StringSession extends MemorySession {\n /**\n * This session file can be easily saved and loaded as a string. According\n * to the initial design, it contains only the data that is necessary for\n * successful connection and authentication, so takeout ID is not stored.\n\n * It is thought to be used where you don't want to create any on-disk\n * files but would still like to be able to save and load existing sessions\n * by other means.\n\n * You can use custom `encode` and `decode` functions, if present:\n\n * `encode` definition must be ``function encode(value: Buffer) -> string:``.\n * `decode` definition must be ``function decode(value: string) -> Buffer:``.\n * @param session {string|null}\n */\n constructor(session = undefined) {\n super();\n if (session) {\n if (session[0] !== CURRENT_VERSION) {\n throw new Error('Not a valid string');\n }\n session = session.slice(1);\n const r = StringSession.decode(session);\n const reader = new BinaryReader(r);\n this._dcId = reader.read(1)\n .readUInt8(0);\n const serverAddressLen = reader.read(2)\n .readInt16BE(0);\n this._serverAddress = String(reader.read(serverAddressLen));\n this._port = reader.read(2)\n .readInt16BE(0);\n this._key = reader.read(-1);\n }\n }\n\n /**\n * @param x {Buffer}\n * @returns {string}\n */\n static encode(x) {\n return x.toString('base64');\n }\n\n /**\n * @param x {string}\n * @returns {Buffer}\n */\n static decode(x) {\n return Buffer.from(x, 'base64');\n }\n\n async load() {\n if (this._key) {\n this._authKey = new AuthKey();\n await this._authKey.setKey(this._key);\n }\n }\n\n save() {\n if (!this.authKey) {\n return '';\n }\n const dcBuffer = Buffer.from([this.dcId]);\n const addressBuffer = Buffer.from(this.serverAddress);\n const addressLengthBuffer = Buffer.alloc(2);\n addressLengthBuffer.writeInt16BE(addressBuffer.length, 0);\n const portBuffer = Buffer.alloc(2);\n portBuffer.writeInt16BE(this.port, 0);\n\n return CURRENT_VERSION + StringSession.encode(Buffer.concat([\n dcBuffer,\n addressLengthBuffer,\n addressBuffer,\n portBuffer,\n this.authKey.getKey(),\n ]));\n }\n\n getAuthKey(dcId) {\n if (dcId && dcId !== this.dcId) {\n // Not supported.\n return undefined;\n }\n\n return this.authKey;\n }\n\n setAuthKey(authKey, dcId) {\n if (dcId && dcId !== this.dcId) {\n // Not supported.\n return;\n }\n\n this.authKey = authKey;\n }\n}\n\nmodule.exports = StringSession;\n","const Memory = require('./Memory');\nconst StringSession = require('./StringSession');\nconst CacheApiSession = require('./CacheApiSession');\nconst LocalStorageSession = require('./LocalStorageSession');\nconst IdbSession = require('./IdbSession');\nconst CallbackSession = require('./CallbackSession');\n\nmodule.exports = {\n Memory,\n StringSession,\n CacheApiSession,\n LocalStorageSession,\n IdbSession,\n CallbackSession,\n};\n","const api = require('./api');\n\nconst LAYER = 136;\nconst tlobjects = {};\n\nfor (const tl of Object.values(api)) {\n if (tl.CONSTRUCTOR_ID) {\n tlobjects[tl.CONSTRUCTOR_ID] = tl;\n } else {\n for (const sub of Object.values(tl)) {\n tlobjects[sub.CONSTRUCTOR_ID] = sub;\n }\n }\n}\n\nmodule.exports = {\n LAYER,\n tlobjects,\n};\n","const {\n parseTl,\n serializeBytes,\n serializeDate,\n} = require('./generationHelpers');\nconst {\n toSignedLittleBuffer,\n} = require('../Helpers');\n\nconst tlContent = require('./apiTl.js');\nconst schemeContent = require('./schemaTl.js');\n\n/* CONTEST\nconst NAMED_AUTO_CASTS = new Set([\n 'chatId,int'\n])\nconst NAMED_BLACKLIST = new Set([\n 'discardEncryption'\n])\nconst AUTO_CASTS = new Set([\n 'InputPeer',\n 'InputChannel',\n 'InputUser',\n 'InputDialogPeer',\n 'InputNotifyPeer',\n 'InputMedia',\n 'InputPhoto',\n 'InputMessage',\n 'InputDocument',\n 'InputChatPhoto'\n])\n\n */\n// eslint-disable-next-line no-restricted-globals\nconst CACHING_SUPPORTED = typeof self !== 'undefined' && self.localStorage !== undefined;\n\nconst CACHE_KEY = 'GramJs:apiCache';\n\nfunction buildApiFromTlSchema() {\n let definitions;\n const fromCache = CACHING_SUPPORTED && loadFromCache();\n\n if (fromCache) {\n definitions = fromCache;\n } else {\n definitions = loadFromTlSchemas();\n\n if (CACHING_SUPPORTED) {\n localStorage.setItem(CACHE_KEY, JSON.stringify(definitions));\n }\n }\n\n return mergeWithNamespaces(\n createClasses('constructor', definitions.constructors),\n createClasses('request', definitions.requests),\n );\n}\n\nfunction loadFromCache() {\n const jsonCache = localStorage.getItem(CACHE_KEY);\n return jsonCache && JSON.parse(jsonCache);\n}\n\nfunction loadFromTlSchemas() {\n const [constructorParamsApi, functionParamsApi] = extractParams(tlContent);\n const [constructorParamsSchema, functionParamsSchema] = extractParams(schemeContent);\n const constructors = [].concat(constructorParamsApi, constructorParamsSchema);\n const requests = [].concat(functionParamsApi, functionParamsSchema);\n\n return {\n constructors,\n requests,\n };\n}\n\nfunction mergeWithNamespaces(obj1, obj2) {\n const result = { ...obj1 };\n\n Object.keys(obj2)\n .forEach((key) => {\n if (typeof obj2[key] === 'function' || !result[key]) {\n result[key] = obj2[key];\n } else {\n Object.assign(result[key], obj2[key]);\n }\n });\n\n return result;\n}\n\nfunction extractParams(fileContent) {\n const f = parseTl(fileContent, 109);\n const constructors = [];\n const functions = [];\n for (const d of f) {\n if (d.isFunction) {\n functions.push(d);\n } else {\n constructors.push(d);\n }\n }\n return [constructors, functions];\n}\n\nfunction argToBytes(x, type) {\n switch (type) {\n case 'int': {\n const i = Buffer.alloc(4);\n i.writeInt32LE(x, 0);\n return i;\n }\n case 'long':\n return toSignedLittleBuffer(x, 8);\n case 'int128':\n return toSignedLittleBuffer(x, 16);\n case 'int256':\n return toSignedLittleBuffer(x, 32);\n case 'double': {\n const d = Buffer.alloc(8);\n d.writeDoubleLE(x, 0);\n return d;\n }\n case 'string':\n return serializeBytes(x);\n case 'Bool':\n return x ? Buffer.from('b5757299', 'hex') : Buffer.from('379779bc', 'hex');\n case 'true':\n return Buffer.alloc(0);\n case 'bytes':\n return serializeBytes(x);\n case 'date':\n return serializeDate(x);\n default:\n return x.getBytes();\n }\n}\n\n/*\nCONTEST\nasync function getInputFromResolve(utils, client, peer, peerType) {\n switch (peerType) {\n case 'InputPeer':\n return utils.getInputPeer(await client.getInputEntity(peer))\n case 'InputChannel':\n return utils.getInputChannel(await client.getInputEntity(peer))\n case 'InputUser':\n return utils.getInputUser(await client.getInputEntity(peer))\n case 'InputDialogPeer':\n return await client._getInputDialog(peer)\n case 'InputNotifyPeer':\n return await client._getInputNotify(peer)\n case 'InputMedia':\n return utils.getInputMedia(peer)\n case 'InputPhoto':\n return utils.getInputPhoto(peer)\n case 'InputMessage':\n return utils.getInputMessage(peer)\n case 'InputDocument':\n return utils.getInputDocument(peer)\n case 'InputChatPhoto':\n return utils.getInputChatPhoto(peer)\n case 'chatId,int' :\n return await client.getPeerId(peer, false)\n default:\n throw new Error('unsupported peer type : ' + peerType)\n }\n}\n*/\nfunction getArgFromReader(reader, arg) {\n if (arg.isVector) {\n if (arg.useVectorId) {\n reader.readInt();\n }\n const temp = [];\n const len = reader.readInt();\n arg.isVector = false;\n for (let i = 0; i < len; i++) {\n temp.push(getArgFromReader(reader, arg));\n }\n arg.isVector = true;\n return temp;\n } else if (arg.flagIndicator) {\n return reader.readInt();\n } else {\n switch (arg.type) {\n case 'int':\n return reader.readInt();\n case 'long':\n return reader.readLong();\n case 'int128':\n return reader.readLargeInt(128);\n case 'int256':\n return reader.readLargeInt(256);\n case 'double':\n return reader.readDouble();\n case 'string':\n return reader.tgReadString();\n case 'Bool':\n return reader.tgReadBool();\n case 'true':\n return true;\n case 'bytes':\n return reader.tgReadBytes();\n case 'date':\n return reader.tgReadDate();\n default:\n if (!arg.skipConstructorId) {\n return reader.tgReadObject();\n } else {\n throw new Error(`Unknown type ${arg}`);\n }\n }\n }\n}\n\nfunction createClasses(classesType, params) {\n const classes = {};\n for (const classParams of params) {\n const {\n name,\n constructorId,\n subclassOfId,\n argsConfig,\n namespace,\n result,\n } = classParams;\n const fullName = [namespace, name].join('.')\n .replace(/^\\./, '');\n\n class VirtualClass {\n static CONSTRUCTOR_ID = constructorId;\n\n static SUBCLASS_OF_ID = subclassOfId;\n\n static className = fullName;\n\n static classType = classesType;\n\n CONSTRUCTOR_ID = constructorId;\n\n SUBCLASS_OF_ID = subclassOfId;\n\n className = fullName;\n\n classType = classesType;\n\n constructor(args) {\n args = args || {};\n Object.keys(args)\n .forEach((argName) => {\n this[argName] = args[argName];\n });\n }\n\n static fromReader(reader) {\n const args = {};\n\n for (const argName in argsConfig) {\n if (argsConfig.hasOwnProperty(argName)) {\n const arg = argsConfig[argName];\n if (arg.isFlag) {\n if (arg.type === 'true') {\n args[argName] = Boolean(args.flags & (1 << arg.flagIndex));\n continue;\n }\n if (args.flags & (1 << arg.flagIndex)) {\n args[argName] = getArgFromReader(reader, arg);\n } else {\n args[argName] = undefined;\n }\n } else {\n if (arg.flagIndicator) {\n arg.name = 'flags';\n }\n args[argName] = getArgFromReader(reader, arg);\n }\n }\n }\n return new VirtualClass(args);\n }\n\n getBytes() {\n // The next is pseudo-code:\n const idForBytes = this.CONSTRUCTOR_ID;\n const c = Buffer.alloc(4);\n c.writeUInt32LE(idForBytes, 0);\n const buffers = [c];\n for (const arg in argsConfig) {\n if (argsConfig.hasOwnProperty(arg)) {\n if (argsConfig[arg].isFlag) {\n if ((this[arg] === false && argsConfig[arg].type === 'true')\n || this[arg] === undefined) {\n continue;\n }\n }\n if (argsConfig[arg].isVector) {\n if (argsConfig[arg].useVectorId) {\n buffers.push(Buffer.from('15c4b51c', 'hex'));\n }\n const l = Buffer.alloc(4);\n l.writeInt32LE(this[arg].length, 0);\n buffers.push(l, Buffer.concat(this[arg].map((x) => argToBytes(x, argsConfig[arg].type))));\n } else if (argsConfig[arg].flagIndicator) {\n if (!Object.values(argsConfig)\n .some((f) => f.isFlag)) {\n buffers.push(Buffer.alloc(4));\n } else {\n let flagCalculate = 0;\n for (const f in argsConfig) {\n if (argsConfig[f].isFlag) {\n if ((this[f] === false && argsConfig[f].type === 'true')\n || this[f] === undefined) {\n flagCalculate |= 0;\n } else {\n flagCalculate |= 1 << argsConfig[f].flagIndex;\n }\n }\n }\n const f = Buffer.alloc(4);\n f.writeUInt32LE(flagCalculate, 0);\n buffers.push(f);\n }\n } else {\n buffers.push(argToBytes(this[arg], argsConfig[arg].type));\n\n if (this[arg] && typeof this[arg].getBytes === 'function') {\n let boxed = (argsConfig[arg].type.charAt(argsConfig[arg].type.indexOf('.') + 1));\n boxed = boxed === boxed.toUpperCase();\n if (!boxed) {\n buffers.shift();\n }\n }\n }\n }\n }\n return Buffer.concat(buffers);\n }\n\n readResult(reader) {\n if (classesType !== 'request') {\n throw new Error('`readResult()` called for non-request instance');\n }\n\n const m = result.match(/Vector<(int|long)>/);\n if (m) {\n reader.readInt();\n const temp = [];\n const len = reader.readInt();\n if (m[1] === 'int') {\n for (let i = 0; i < len; i++) {\n temp.push(reader.readInt());\n }\n } else {\n for (let i = 0; i < len; i++) {\n temp.push(reader.readLong());\n }\n }\n return temp;\n } else {\n return reader.tgReadObject();\n }\n }\n\n /* CONTEST\n async resolve(client, utils) {\n\n if (classesType !== 'request') {\n throw new Error('`resolve()` called for non-request instance')\n }\n\n for (const arg in argsConfig) {\n if (argsConfig.hasOwnProperty(arg)) {\n if (!AUTO_CASTS.has(argsConfig[arg].type)) {\n if (!NAMED_AUTO_CASTS.has(`${argsConfig[arg].name},${argsConfig[arg].type}`)) {\n continue\n }\n }\n if (argsConfig[arg].isFlag) {\n if (!this[arg]) {\n continue\n }\n }\n if (argsConfig[arg].isVector) {\n const temp = []\n for (const x of this[arg]) {\n temp.push(await getInputFromResolve(utils, client, x, argsConfig[arg].type))\n }\n this[arg] = temp\n } else {\n this[arg] = await getInputFromResolve(utils, client, this[arg], argsConfig[arg].type)\n }\n }\n }\n } */\n }\n\n if (namespace) {\n if (!classes[namespace]) {\n classes[namespace] = {};\n }\n classes[namespace][name] = VirtualClass;\n } else {\n classes[name] = VirtualClass;\n }\n }\n\n return classes;\n}\n\nmodule.exports = buildApiFromTlSchema();\n","module.exports = `boolFalse#bc799737 = Bool;\nboolTrue#997275b5 = Bool;\ntrue#3fedd339 = True;\nvector#1cb5c415 {t:Type} # [ t ] = Vector t;\nerror#c4b9f9bb code:int text:string = Error;\nnull#56730bcc = Null;\ninputPeerEmpty#7f3b18ea = InputPeer;\ninputPeerSelf#7da07ec9 = InputPeer;\ninputPeerChat#35a95cb9 chat_id:long = InputPeer;\ninputPeerUser#dde8a54c user_id:long access_hash:long = InputPeer;\ninputPeerChannel#27bcbbfc channel_id:long access_hash:long = InputPeer;\ninputPeerUserFromMessage#a87b0a1c peer:InputPeer msg_id:int user_id:long = InputPeer;\ninputPeerChannelFromMessage#bd2a0840 peer:InputPeer msg_id:int channel_id:long = InputPeer;\ninputUserEmpty#b98886cf = InputUser;\ninputUserSelf#f7c1b13f = InputUser;\ninputUser#f21158c6 user_id:long access_hash:long = InputUser;\ninputUserFromMessage#1da448e2 peer:InputPeer msg_id:int user_id:long = InputUser;\ninputPhoneContact#f392b7f4 client_id:long phone:string first_name:string last_name:string = InputContact;\ninputFile#f52ff27f id:long parts:int name:string md5_checksum:string = InputFile;\ninputFileBig#fa4f0bb5 id:long parts:int name:string = InputFile;\ninputMediaEmpty#9664f57f = InputMedia;\ninputMediaUploadedPhoto#1e287d04 flags:# file:InputFile stickers:flags.0?Vector ttl_seconds:flags.1?int = InputMedia;\ninputMediaPhoto#b3ba0635 flags:# id:InputPhoto ttl_seconds:flags.0?int = InputMedia;\ninputMediaGeoPoint#f9c44144 geo_point:InputGeoPoint = InputMedia;\ninputMediaContact#f8ab7dfb phone_number:string first_name:string last_name:string vcard:string = InputMedia;\ninputMediaUploadedDocument#5b38c6c1 flags:# nosound_video:flags.3?true force_file:flags.4?true file:InputFile thumb:flags.2?InputFile mime_type:string attributes:Vector stickers:flags.0?Vector ttl_seconds:flags.1?int = InputMedia;\ninputMediaDocument#33473058 flags:# id:InputDocument ttl_seconds:flags.0?int query:flags.1?string = InputMedia;\ninputMediaVenue#c13d1c11 geo_point:InputGeoPoint title:string address:string provider:string venue_id:string venue_type:string = InputMedia;\ninputMediaPhotoExternal#e5bbfe1a flags:# url:string ttl_seconds:flags.0?int = InputMedia;\ninputMediaDocumentExternal#fb52dc99 flags:# url:string ttl_seconds:flags.0?int = InputMedia;\ninputMediaGame#d33f43f3 id:InputGame = InputMedia;\ninputMediaInvoice#d9799874 flags:# title:string description:string photo:flags.0?InputWebDocument invoice:Invoice payload:bytes provider:string provider_data:DataJSON start_param:flags.1?string = InputMedia;\ninputMediaGeoLive#971fa843 flags:# stopped:flags.0?true geo_point:InputGeoPoint heading:flags.2?int period:flags.1?int proximity_notification_radius:flags.3?int = InputMedia;\ninputMediaPoll#f94e5f1 flags:# poll:Poll correct_answers:flags.0?Vector solution:flags.1?string solution_entities:flags.1?Vector = InputMedia;\ninputMediaDice#e66fbf7b emoticon:string = InputMedia;\ninputChatPhotoEmpty#1ca48f57 = InputChatPhoto;\ninputChatUploadedPhoto#c642724e flags:# file:flags.0?InputFile video:flags.1?InputFile video_start_ts:flags.2?double = InputChatPhoto;\ninputChatPhoto#8953ad37 id:InputPhoto = InputChatPhoto;\ninputGeoPointEmpty#e4c123d6 = InputGeoPoint;\ninputGeoPoint#48222faf flags:# lat:double long:double accuracy_radius:flags.0?int = InputGeoPoint;\ninputPhotoEmpty#1cd7bf0d = InputPhoto;\ninputPhoto#3bb3b94a id:long access_hash:long file_reference:bytes = InputPhoto;\ninputFileLocation#dfdaabe1 volume_id:long local_id:int secret:long file_reference:bytes = InputFileLocation;\ninputEncryptedFileLocation#f5235d55 id:long access_hash:long = InputFileLocation;\ninputDocumentFileLocation#bad07584 id:long access_hash:long file_reference:bytes thumb_size:string = InputFileLocation;\ninputSecureFileLocation#cbc7ee28 id:long access_hash:long = InputFileLocation;\ninputTakeoutFileLocation#29be5899 = InputFileLocation;\ninputPhotoFileLocation#40181ffe id:long access_hash:long file_reference:bytes thumb_size:string = InputFileLocation;\ninputPhotoLegacyFileLocation#d83466f3 id:long access_hash:long file_reference:bytes volume_id:long local_id:int secret:long = InputFileLocation;\ninputPeerPhotoFileLocation#37257e99 flags:# big:flags.0?true peer:InputPeer photo_id:long = InputFileLocation;\ninputStickerSetThumb#9d84f3db stickerset:InputStickerSet thumb_version:int = InputFileLocation;\ninputGroupCallStream#598a92a flags:# call:InputGroupCall time_ms:long scale:int video_channel:flags.0?int video_quality:flags.0?int = InputFileLocation;\npeerUser#59511722 user_id:long = Peer;\npeerChat#36c6019a chat_id:long = Peer;\npeerChannel#a2a5371e channel_id:long = Peer;\nstorage.fileUnknown#aa963b05 = storage.FileType;\nstorage.filePartial#40bc6f52 = storage.FileType;\nstorage.fileJpeg#7efe0e = storage.FileType;\nstorage.fileGif#cae1aadf = storage.FileType;\nstorage.filePng#a4f63c0 = storage.FileType;\nstorage.filePdf#ae1e508d = storage.FileType;\nstorage.fileMp3#528a0677 = storage.FileType;\nstorage.fileMov#4b09ebbc = storage.FileType;\nstorage.fileMp4#b3cea0e4 = storage.FileType;\nstorage.fileWebp#1081464c = storage.FileType;\nuserEmpty#d3bc4b7a id:long = User;\nuser#3ff6ecb0 flags:# self:flags.10?true contact:flags.11?true mutual_contact:flags.12?true deleted:flags.13?true bot:flags.14?true bot_chat_history:flags.15?true bot_nochats:flags.16?true verified:flags.17?true restricted:flags.18?true min:flags.20?true bot_inline_geo:flags.21?true support:flags.23?true scam:flags.24?true apply_min_photo:flags.25?true fake:flags.26?true id:long access_hash:flags.0?long first_name:flags.1?string last_name:flags.2?string username:flags.3?string phone:flags.4?string photo:flags.5?UserProfilePhoto status:flags.6?UserStatus bot_info_version:flags.14?int restriction_reason:flags.18?Vector bot_inline_placeholder:flags.19?string lang_code:flags.22?string = User;\nuserProfilePhotoEmpty#4f11bae1 = UserProfilePhoto;\nuserProfilePhoto#82d1f706 flags:# has_video:flags.0?true photo_id:long stripped_thumb:flags.1?bytes dc_id:int = UserProfilePhoto;\nuserStatusEmpty#9d05049 = UserStatus;\nuserStatusOnline#edb93949 expires:int = UserStatus;\nuserStatusOffline#8c703f was_online:int = UserStatus;\nuserStatusRecently#e26f42f1 = UserStatus;\nuserStatusLastWeek#7bf09fc = UserStatus;\nuserStatusLastMonth#77ebc742 = UserStatus;\nchatEmpty#29562865 id:long = Chat;\nchat#41cbf256 flags:# creator:flags.0?true kicked:flags.1?true left:flags.2?true deactivated:flags.5?true call_active:flags.23?true call_not_empty:flags.24?true noforwards:flags.25?true id:long title:string photo:ChatPhoto participants_count:int date:int version:int migrated_to:flags.6?InputChannel admin_rights:flags.14?ChatAdminRights default_banned_rights:flags.18?ChatBannedRights = Chat;\nchatForbidden#6592a1a7 id:long title:string = Chat;\nchannel#8261ac61 flags:# creator:flags.0?true left:flags.2?true broadcast:flags.5?true verified:flags.7?true megagroup:flags.8?true restricted:flags.9?true signatures:flags.11?true min:flags.12?true scam:flags.19?true has_link:flags.20?true has_geo:flags.21?true slowmode_enabled:flags.22?true call_active:flags.23?true call_not_empty:flags.24?true fake:flags.25?true gigagroup:flags.26?true noforwards:flags.27?true id:long access_hash:flags.13?long title:string username:flags.6?string photo:ChatPhoto date:int restriction_reason:flags.9?Vector admin_rights:flags.14?ChatAdminRights banned_rights:flags.15?ChatBannedRights default_banned_rights:flags.18?ChatBannedRights participants_count:flags.17?int = Chat;\nchannelForbidden#17d493d5 flags:# broadcast:flags.5?true megagroup:flags.8?true id:long access_hash:long title:string until_date:flags.16?int = Chat;\nchatFull#d18ee226 flags:# can_set_username:flags.7?true has_scheduled:flags.8?true id:long about:string participants:ChatParticipants chat_photo:flags.2?Photo notify_settings:PeerNotifySettings exported_invite:flags.13?ExportedChatInvite bot_info:flags.3?Vector pinned_msg_id:flags.6?int folder_id:flags.11?int call:flags.12?InputGroupCall ttl_period:flags.14?int groupcall_default_join_as:flags.15?Peer theme_emoticon:flags.16?string requests_pending:flags.17?int recent_requesters:flags.17?Vector available_reactions:flags.18?Vector = ChatFull;\nchannelFull#e13c3d20 flags:# can_view_participants:flags.3?true can_set_username:flags.6?true can_set_stickers:flags.7?true hidden_prehistory:flags.10?true can_set_location:flags.16?true has_scheduled:flags.19?true can_view_stats:flags.20?true blocked:flags.22?true id:long about:string participants_count:flags.0?int admins_count:flags.1?int kicked_count:flags.2?int banned_count:flags.2?int online_count:flags.13?int read_inbox_max_id:int read_outbox_max_id:int unread_count:int chat_photo:Photo notify_settings:PeerNotifySettings exported_invite:flags.23?ExportedChatInvite bot_info:Vector migrated_from_chat_id:flags.4?long migrated_from_max_id:flags.4?int pinned_msg_id:flags.5?int stickerset:flags.8?StickerSet available_min_id:flags.9?int folder_id:flags.11?int linked_chat_id:flags.14?long location:flags.15?ChannelLocation slowmode_seconds:flags.17?int slowmode_next_send_date:flags.18?int stats_dc:flags.12?int pts:int call:flags.21?InputGroupCall ttl_period:flags.24?int pending_suggestions:flags.25?Vector groupcall_default_join_as:flags.26?Peer theme_emoticon:flags.27?string requests_pending:flags.28?int recent_requesters:flags.28?Vector default_send_as:flags.29?Peer available_reactions:flags.30?Vector = ChatFull;\nchatParticipant#c02d4007 user_id:long inviter_id:long date:int = ChatParticipant;\nchatParticipantCreator#e46bcee4 user_id:long = ChatParticipant;\nchatParticipantAdmin#a0933f5b user_id:long inviter_id:long date:int = ChatParticipant;\nchatParticipantsForbidden#8763d3e1 flags:# chat_id:long self_participant:flags.0?ChatParticipant = ChatParticipants;\nchatParticipants#3cbc93f8 chat_id:long participants:Vector version:int = ChatParticipants;\nchatPhotoEmpty#37c1011c = ChatPhoto;\nchatPhoto#1c6e1c11 flags:# has_video:flags.0?true photo_id:long stripped_thumb:flags.1?bytes dc_id:int = ChatPhoto;\nmessageEmpty#90a6ca84 flags:# id:int peer_id:flags.0?Peer = Message;\nmessage#38116ee0 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true post:flags.14?true from_scheduled:flags.18?true legacy:flags.19?true edit_hide:flags.21?true pinned:flags.24?true noforwards:flags.26?true id:int from_id:flags.8?Peer peer_id:Peer fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?long reply_to:flags.3?MessageReplyHeader date:int message:string media:flags.9?MessageMedia reply_markup:flags.6?ReplyMarkup entities:flags.7?Vector views:flags.10?int forwards:flags.10?int replies:flags.23?MessageReplies edit_date:flags.15?int post_author:flags.16?string grouped_id:flags.17?long reactions:flags.20?MessageReactions restriction_reason:flags.22?Vector ttl_period:flags.25?int = Message;\nmessageService#2b085862 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true post:flags.14?true legacy:flags.19?true id:int from_id:flags.8?Peer peer_id:Peer reply_to:flags.3?MessageReplyHeader date:int action:MessageAction ttl_period:flags.25?int = Message;\nmessageMediaEmpty#3ded6320 = MessageMedia;\nmessageMediaPhoto#695150d7 flags:# photo:flags.0?Photo ttl_seconds:flags.2?int = MessageMedia;\nmessageMediaGeo#56e0d474 geo:GeoPoint = MessageMedia;\nmessageMediaContact#70322949 phone_number:string first_name:string last_name:string vcard:string user_id:long = MessageMedia;\nmessageMediaUnsupported#9f84f49e = MessageMedia;\nmessageMediaDocument#9cb070d7 flags:# document:flags.0?Document ttl_seconds:flags.2?int = MessageMedia;\nmessageMediaWebPage#a32dd600 webpage:WebPage = MessageMedia;\nmessageMediaVenue#2ec0533f geo:GeoPoint title:string address:string provider:string venue_id:string venue_type:string = MessageMedia;\nmessageMediaGame#fdb19008 game:Game = MessageMedia;\nmessageMediaInvoice#84551347 flags:# shipping_address_requested:flags.1?true test:flags.3?true title:string description:string photo:flags.0?WebDocument receipt_msg_id:flags.2?int currency:string total_amount:long start_param:string = MessageMedia;\nmessageMediaGeoLive#b940c666 flags:# geo:GeoPoint heading:flags.0?int period:int proximity_notification_radius:flags.1?int = MessageMedia;\nmessageMediaPoll#4bd6e798 poll:Poll results:PollResults = MessageMedia;\nmessageMediaDice#3f7ee58b value:int emoticon:string = MessageMedia;\nmessageActionEmpty#b6aef7b0 = MessageAction;\nmessageActionChatCreate#bd47cbad title:string users:Vector = MessageAction;\nmessageActionChatEditTitle#b5a1ce5a title:string = MessageAction;\nmessageActionChatEditPhoto#7fcb13a8 photo:Photo = MessageAction;\nmessageActionChatDeletePhoto#95e3fbef = MessageAction;\nmessageActionChatAddUser#15cefd00 users:Vector = MessageAction;\nmessageActionChatDeleteUser#a43f30cc user_id:long = MessageAction;\nmessageActionChatJoinedByLink#31224c3 inviter_id:long = MessageAction;\nmessageActionChannelCreate#95d2ac92 title:string = MessageAction;\nmessageActionChatMigrateTo#e1037f92 channel_id:long = MessageAction;\nmessageActionChannelMigrateFrom#ea3948e9 title:string chat_id:long = MessageAction;\nmessageActionPinMessage#94bd38ed = MessageAction;\nmessageActionHistoryClear#9fbab604 = MessageAction;\nmessageActionGameScore#92a72876 game_id:long score:int = MessageAction;\nmessageActionPaymentSentMe#8f31b327 flags:# currency:string total_amount:long payload:bytes info:flags.0?PaymentRequestedInfo shipping_option_id:flags.1?string charge:PaymentCharge = MessageAction;\nmessageActionPaymentSent#40699cd0 currency:string total_amount:long = MessageAction;\nmessageActionPhoneCall#80e11a7f flags:# video:flags.2?true call_id:long reason:flags.0?PhoneCallDiscardReason duration:flags.1?int = MessageAction;\nmessageActionScreenshotTaken#4792929b = MessageAction;\nmessageActionCustomAction#fae69f56 message:string = MessageAction;\nmessageActionBotAllowed#abe9affe domain:string = MessageAction;\nmessageActionSecureValuesSentMe#1b287353 values:Vector credentials:SecureCredentialsEncrypted = MessageAction;\nmessageActionSecureValuesSent#d95c6154 types:Vector = MessageAction;\nmessageActionContactSignUp#f3f25f76 = MessageAction;\nmessageActionGeoProximityReached#98e0d697 from_id:Peer to_id:Peer distance:int = MessageAction;\nmessageActionGroupCall#7a0d7f42 flags:# call:InputGroupCall duration:flags.0?int = MessageAction;\nmessageActionInviteToGroupCall#502f92f7 call:InputGroupCall users:Vector = MessageAction;\nmessageActionSetMessagesTTL#aa1afbfd period:int = MessageAction;\nmessageActionGroupCallScheduled#b3a07661 call:InputGroupCall schedule_date:int = MessageAction;\nmessageActionSetChatTheme#aa786345 emoticon:string = MessageAction;\nmessageActionChatJoinedByRequest#ebbca3cb = MessageAction;\ndialog#2c171f72 flags:# pinned:flags.2?true unread_mark:flags.3?true peer:Peer top_message:int read_inbox_max_id:int read_outbox_max_id:int unread_count:int unread_mentions_count:int notify_settings:PeerNotifySettings pts:flags.0?int draft:flags.1?DraftMessage folder_id:flags.4?int = Dialog;\ndialogFolder#71bd134c flags:# pinned:flags.2?true folder:Folder peer:Peer top_message:int unread_muted_peers_count:int unread_unmuted_peers_count:int unread_muted_messages_count:int unread_unmuted_messages_count:int = Dialog;\nphotoEmpty#2331b22d id:long = Photo;\nphoto#fb197a65 flags:# has_stickers:flags.0?true id:long access_hash:long file_reference:bytes date:int sizes:Vector video_sizes:flags.1?Vector dc_id:int = Photo;\nphotoSizeEmpty#e17e23c type:string = PhotoSize;\nphotoSize#75c78e60 type:string w:int h:int size:int = PhotoSize;\nphotoCachedSize#21e1ad6 type:string w:int h:int bytes:bytes = PhotoSize;\nphotoStrippedSize#e0b0bc2e type:string bytes:bytes = PhotoSize;\nphotoSizeProgressive#fa3efb95 type:string w:int h:int sizes:Vector = PhotoSize;\nphotoPathSize#d8214d41 type:string bytes:bytes = PhotoSize;\ngeoPointEmpty#1117dd5f = GeoPoint;\ngeoPoint#b2a2f663 flags:# long:double lat:double access_hash:long accuracy_radius:flags.0?int = GeoPoint;\nauth.sentCode#5e002502 flags:# type:auth.SentCodeType phone_code_hash:string next_type:flags.1?auth.CodeType timeout:flags.2?int = auth.SentCode;\nauth.authorization#33fb7bb8 flags:# setup_password_required:flags.1?true otherwise_relogin_days:flags.1?int tmp_sessions:flags.0?int user:User = auth.Authorization;\nauth.authorizationSignUpRequired#44747e9a flags:# terms_of_service:flags.0?help.TermsOfService = auth.Authorization;\nauth.exportedAuthorization#b434e2b8 id:long bytes:bytes = auth.ExportedAuthorization;\ninputNotifyPeer#b8bc5b0c peer:InputPeer = InputNotifyPeer;\ninputNotifyUsers#193b4417 = InputNotifyPeer;\ninputNotifyChats#4a95e84e = InputNotifyPeer;\ninputNotifyBroadcasts#b1db7c7e = InputNotifyPeer;\ninputPeerNotifySettings#9c3d198e flags:# show_previews:flags.0?Bool silent:flags.1?Bool mute_until:flags.2?int sound:flags.3?string = InputPeerNotifySettings;\npeerNotifySettings#af509d20 flags:# show_previews:flags.0?Bool silent:flags.1?Bool mute_until:flags.2?int sound:flags.3?string = PeerNotifySettings;\npeerSettings#a518110d flags:# report_spam:flags.0?true add_contact:flags.1?true block_contact:flags.2?true share_contact:flags.3?true need_contacts_exception:flags.4?true report_geo:flags.5?true autoarchived:flags.7?true invite_members:flags.8?true request_chat_broadcast:flags.10?true geo_distance:flags.6?int request_chat_title:flags.9?string request_chat_date:flags.9?int = PeerSettings;\nwallPaper#a437c3ed id:long flags:# creator:flags.0?true default:flags.1?true pattern:flags.3?true dark:flags.4?true access_hash:long slug:string document:Document settings:flags.2?WallPaperSettings = WallPaper;\nwallPaperNoFile#e0804116 id:long flags:# default:flags.1?true dark:flags.4?true settings:flags.2?WallPaperSettings = WallPaper;\ninputReportReasonSpam#58dbcab8 = ReportReason;\ninputReportReasonViolence#1e22c78d = ReportReason;\ninputReportReasonPornography#2e59d922 = ReportReason;\ninputReportReasonChildAbuse#adf44ee3 = ReportReason;\ninputReportReasonOther#c1e4a2b1 = ReportReason;\ninputReportReasonCopyright#9b89f93a = ReportReason;\ninputReportReasonGeoIrrelevant#dbd4feed = ReportReason;\ninputReportReasonFake#f5ddd6e7 = ReportReason;\nuserFull#cf366521 flags:# blocked:flags.0?true phone_calls_available:flags.4?true phone_calls_private:flags.5?true can_pin_message:flags.7?true has_scheduled:flags.12?true video_calls_available:flags.13?true id:long about:flags.1?string settings:PeerSettings profile_photo:flags.2?Photo notify_settings:PeerNotifySettings bot_info:flags.3?BotInfo pinned_msg_id:flags.6?int common_chats_count:int folder_id:flags.11?int ttl_period:flags.14?int theme_emoticon:flags.15?string private_forward_name:flags.16?string = UserFull;\ncontact#145ade0b user_id:long mutual:Bool = Contact;\nimportedContact#c13e3c50 user_id:long client_id:long = ImportedContact;\ncontactStatus#16d9703b user_id:long status:UserStatus = ContactStatus;\ncontacts.contactsNotModified#b74ba9d2 = contacts.Contacts;\ncontacts.contacts#eae87e42 contacts:Vector saved_count:int users:Vector = contacts.Contacts;\ncontacts.importedContacts#77d01c3b imported:Vector popular_invites:Vector retry_contacts:Vector users:Vector = contacts.ImportedContacts;\ncontacts.blocked#ade1591 blocked:Vector chats:Vector users:Vector = contacts.Blocked;\ncontacts.blockedSlice#e1664194 count:int blocked:Vector chats:Vector users:Vector = contacts.Blocked;\nmessages.dialogs#15ba6c40 dialogs:Vector messages:Vector chats:Vector users:Vector = messages.Dialogs;\nmessages.dialogsSlice#71e094f3 count:int dialogs:Vector messages:Vector chats:Vector users:Vector = messages.Dialogs;\nmessages.dialogsNotModified#f0e3e596 count:int = messages.Dialogs;\nmessages.messages#8c718e87 messages:Vector chats:Vector users:Vector = messages.Messages;\nmessages.messagesSlice#3a54685e flags:# inexact:flags.1?true count:int next_rate:flags.0?int offset_id_offset:flags.2?int messages:Vector chats:Vector users:Vector = messages.Messages;\nmessages.channelMessages#64479808 flags:# inexact:flags.1?true pts:int count:int offset_id_offset:flags.2?int messages:Vector chats:Vector users:Vector = messages.Messages;\nmessages.messagesNotModified#74535f21 count:int = messages.Messages;\nmessages.chats#64ff9fd5 chats:Vector = messages.Chats;\nmessages.chatsSlice#9cd81144 count:int chats:Vector = messages.Chats;\nmessages.chatFull#e5d7d19c full_chat:ChatFull chats:Vector users:Vector = messages.ChatFull;\nmessages.affectedHistory#b45c69d1 pts:int pts_count:int offset:int = messages.AffectedHistory;\ninputMessagesFilterEmpty#57e2f66c = MessagesFilter;\ninputMessagesFilterPhotos#9609a51c = MessagesFilter;\ninputMessagesFilterVideo#9fc00e65 = MessagesFilter;\ninputMessagesFilterPhotoVideo#56e9f0e4 = MessagesFilter;\ninputMessagesFilterDocument#9eddf188 = MessagesFilter;\ninputMessagesFilterUrl#7ef0dd87 = MessagesFilter;\ninputMessagesFilterGif#ffc86587 = MessagesFilter;\ninputMessagesFilterVoice#50f5c392 = MessagesFilter;\ninputMessagesFilterMusic#3751b49e = MessagesFilter;\ninputMessagesFilterChatPhotos#3a20ecb8 = MessagesFilter;\ninputMessagesFilterPhoneCalls#80c99768 flags:# missed:flags.0?true = MessagesFilter;\ninputMessagesFilterRoundVoice#7a7c17a4 = MessagesFilter;\ninputMessagesFilterRoundVideo#b549da53 = MessagesFilter;\ninputMessagesFilterMyMentions#c1f8e69a = MessagesFilter;\ninputMessagesFilterGeo#e7026d0d = MessagesFilter;\ninputMessagesFilterContacts#e062db83 = MessagesFilter;\ninputMessagesFilterPinned#1bb00451 = MessagesFilter;\nupdateNewMessage#1f2b0afd message:Message pts:int pts_count:int = Update;\nupdateMessageID#4e90bfd6 id:int random_id:long = Update;\nupdateDeleteMessages#a20db0e5 messages:Vector pts:int pts_count:int = Update;\nupdateUserTyping#c01e857f user_id:long action:SendMessageAction = Update;\nupdateChatUserTyping#83487af0 chat_id:long from_id:Peer action:SendMessageAction = Update;\nupdateChatParticipants#7761198 participants:ChatParticipants = Update;\nupdateUserStatus#e5bdf8de user_id:long status:UserStatus = Update;\nupdateUserName#c3f202e0 user_id:long first_name:string last_name:string username:string = Update;\nupdateUserPhoto#f227868c user_id:long date:int photo:UserProfilePhoto previous:Bool = Update;\nupdateNewEncryptedMessage#12bcbd9a message:EncryptedMessage qts:int = Update;\nupdateEncryptedChatTyping#1710f156 chat_id:int = Update;\nupdateEncryption#b4a2e88d chat:EncryptedChat date:int = Update;\nupdateEncryptedMessagesRead#38fe25b7 chat_id:int max_date:int date:int = Update;\nupdateChatParticipantAdd#3dda5451 chat_id:long user_id:long inviter_id:long date:int version:int = Update;\nupdateChatParticipantDelete#e32f3d77 chat_id:long user_id:long version:int = Update;\nupdateDcOptions#8e5e9873 dc_options:Vector = Update;\nupdateNotifySettings#bec268ef peer:NotifyPeer notify_settings:PeerNotifySettings = Update;\nupdateServiceNotification#ebe46819 flags:# popup:flags.0?true inbox_date:flags.1?int type:string message:string media:MessageMedia entities:Vector = Update;\nupdatePrivacy#ee3b272a key:PrivacyKey rules:Vector = Update;\nupdateUserPhone#5492a13 user_id:long phone:string = Update;\nupdateReadHistoryInbox#9c974fdf flags:# folder_id:flags.0?int peer:Peer max_id:int still_unread_count:int pts:int pts_count:int = Update;\nupdateReadHistoryOutbox#2f2f21bf peer:Peer max_id:int pts:int pts_count:int = Update;\nupdateWebPage#7f891213 webpage:WebPage pts:int pts_count:int = Update;\nupdateReadMessagesContents#68c13933 messages:Vector pts:int pts_count:int = Update;\nupdateChannelTooLong#108d941f flags:# channel_id:long pts:flags.0?int = Update;\nupdateChannel#635b4c09 channel_id:long = Update;\nupdateNewChannelMessage#62ba04d9 message:Message pts:int pts_count:int = Update;\nupdateReadChannelInbox#922e6e10 flags:# folder_id:flags.0?int channel_id:long max_id:int still_unread_count:int pts:int = Update;\nupdateDeleteChannelMessages#c32d5b12 channel_id:long messages:Vector pts:int pts_count:int = Update;\nupdateChannelMessageViews#f226ac08 channel_id:long id:int views:int = Update;\nupdateChatParticipantAdmin#d7ca61a2 chat_id:long user_id:long is_admin:Bool version:int = Update;\nupdateNewStickerSet#688a30aa stickerset:messages.StickerSet = Update;\nupdateStickerSetsOrder#bb2d201 flags:# masks:flags.0?true order:Vector = Update;\nupdateStickerSets#43ae3dec = Update;\nupdateSavedGifs#9375341e = Update;\nupdateBotInlineQuery#496f379c flags:# query_id:long user_id:long query:string geo:flags.0?GeoPoint peer_type:flags.1?InlineQueryPeerType offset:string = Update;\nupdateBotInlineSend#12f12a07 flags:# user_id:long query:string geo:flags.0?GeoPoint id:string msg_id:flags.1?InputBotInlineMessageID = Update;\nupdateEditChannelMessage#1b3f4df7 message:Message pts:int pts_count:int = Update;\nupdateBotCallbackQuery#b9cfc48d flags:# query_id:long user_id:long peer:Peer msg_id:int chat_instance:long data:flags.0?bytes game_short_name:flags.1?string = Update;\nupdateEditMessage#e40370a3 message:Message pts:int pts_count:int = Update;\nupdateInlineBotCallbackQuery#691e9052 flags:# query_id:long user_id:long msg_id:InputBotInlineMessageID chat_instance:long data:flags.0?bytes game_short_name:flags.1?string = Update;\nupdateReadChannelOutbox#b75f99a9 channel_id:long max_id:int = Update;\nupdateDraftMessage#ee2bb969 peer:Peer draft:DraftMessage = Update;\nupdateReadFeaturedStickers#571d2742 = Update;\nupdateRecentStickers#9a422c20 = Update;\nupdateConfig#a229dd06 = Update;\nupdatePtsChanged#3354678f = Update;\nupdateChannelWebPage#2f2ba99f channel_id:long webpage:WebPage pts:int pts_count:int = Update;\nupdateDialogPinned#6e6fe51c flags:# pinned:flags.0?true folder_id:flags.1?int peer:DialogPeer = Update;\nupdatePinnedDialogs#fa0f3ca2 flags:# folder_id:flags.1?int order:flags.0?Vector = Update;\nupdateBotWebhookJSON#8317c0c3 data:DataJSON = Update;\nupdateBotWebhookJSONQuery#9b9240a6 query_id:long data:DataJSON timeout:int = Update;\nupdateBotShippingQuery#b5aefd7d query_id:long user_id:long payload:bytes shipping_address:PostAddress = Update;\nupdateBotPrecheckoutQuery#8caa9a96 flags:# query_id:long user_id:long payload:bytes info:flags.0?PaymentRequestedInfo shipping_option_id:flags.1?string currency:string total_amount:long = Update;\nupdatePhoneCall#ab0f6b1e phone_call:PhoneCall = Update;\nupdateLangPackTooLong#46560264 lang_code:string = Update;\nupdateLangPack#56022f4d difference:LangPackDifference = Update;\nupdateFavedStickers#e511996d = Update;\nupdateChannelReadMessagesContents#44bdd535 channel_id:long messages:Vector = Update;\nupdateContactsReset#7084a7be = Update;\nupdateChannelAvailableMessages#b23fc698 channel_id:long available_min_id:int = Update;\nupdateDialogUnreadMark#e16459c3 flags:# unread:flags.0?true peer:DialogPeer = Update;\nupdateMessagePoll#aca1657b flags:# poll_id:long poll:flags.0?Poll results:PollResults = Update;\nupdateChatDefaultBannedRights#54c01850 peer:Peer default_banned_rights:ChatBannedRights version:int = Update;\nupdateFolderPeers#19360dc0 folder_peers:Vector pts:int pts_count:int = Update;\nupdatePeerSettings#6a7e7366 peer:Peer settings:PeerSettings = Update;\nupdatePeerLocated#b4afcfb0 peers:Vector = Update;\nupdateNewScheduledMessage#39a51dfb message:Message = Update;\nupdateDeleteScheduledMessages#90866cee peer:Peer messages:Vector = Update;\nupdateTheme#8216fba3 theme:Theme = Update;\nupdateGeoLiveViewed#871fb939 peer:Peer msg_id:int = Update;\nupdateLoginToken#564fe691 = Update;\nupdateMessagePollVote#106395c9 poll_id:long user_id:long options:Vector qts:int = Update;\nupdateDialogFilter#26ffde7d flags:# id:int filter:flags.0?DialogFilter = Update;\nupdateDialogFilterOrder#a5d72105 order:Vector = Update;\nupdateDialogFilters#3504914f = Update;\nupdatePhoneCallSignalingData#2661bf09 phone_call_id:long data:bytes = Update;\nupdateChannelMessageForwards#d29a27f4 channel_id:long id:int forwards:int = Update;\nupdateReadChannelDiscussionInbox#d6b19546 flags:# channel_id:long top_msg_id:int read_max_id:int broadcast_id:flags.0?long broadcast_post:flags.0?int = Update;\nupdateReadChannelDiscussionOutbox#695c9e7c channel_id:long top_msg_id:int read_max_id:int = Update;\nupdatePeerBlocked#246a4b22 peer_id:Peer blocked:Bool = Update;\nupdateChannelUserTyping#8c88c923 flags:# channel_id:long top_msg_id:flags.0?int from_id:Peer action:SendMessageAction = Update;\nupdatePinnedMessages#ed85eab5 flags:# pinned:flags.0?true peer:Peer messages:Vector pts:int pts_count:int = Update;\nupdatePinnedChannelMessages#5bb98608 flags:# pinned:flags.0?true channel_id:long messages:Vector pts:int pts_count:int = Update;\nupdateChat#f89a6a4e chat_id:long = Update;\nupdateGroupCallParticipants#f2ebdb4e call:InputGroupCall participants:Vector version:int = Update;\nupdateGroupCall#14b24500 chat_id:long call:GroupCall = Update;\nupdatePeerHistoryTTL#bb9bb9a5 flags:# peer:Peer ttl_period:flags.0?int = Update;\nupdateChatParticipant#d087663a flags:# chat_id:long date:int actor_id:long user_id:long prev_participant:flags.0?ChatParticipant new_participant:flags.1?ChatParticipant invite:flags.2?ExportedChatInvite qts:int = Update;\nupdateChannelParticipant#985d3abb flags:# channel_id:long date:int actor_id:long user_id:long prev_participant:flags.0?ChannelParticipant new_participant:flags.1?ChannelParticipant invite:flags.2?ExportedChatInvite qts:int = Update;\nupdateBotStopped#c4870a49 user_id:long date:int stopped:Bool qts:int = Update;\nupdateGroupCallConnection#b783982 flags:# presentation:flags.0?true params:DataJSON = Update;\nupdateBotCommands#4d712f2e peer:Peer bot_id:long commands:Vector = Update;\nupdatePendingJoinRequests#7063c3db peer:Peer requests_pending:int recent_requesters:Vector = Update;\nupdateBotChatInviteRequester#11dfa986 peer:Peer date:int user_id:long about:string invite:ExportedChatInvite qts:int = Update;\nupdateMessageReactions#154798c3 peer:Peer msg_id:int reactions:MessageReactions = Update;\nupdates.state#a56c2a3e pts:int qts:int date:int seq:int unread_count:int = updates.State;\nupdates.differenceEmpty#5d75a138 date:int seq:int = updates.Difference;\nupdates.difference#f49ca0 new_messages:Vector new_encrypted_messages:Vector other_updates:Vector chats:Vector users:Vector state:updates.State = updates.Difference;\nupdates.differenceSlice#a8fb1981 new_messages:Vector new_encrypted_messages:Vector other_updates:Vector chats:Vector users:Vector intermediate_state:updates.State = updates.Difference;\nupdates.differenceTooLong#4afe8f6d pts:int = updates.Difference;\nupdatesTooLong#e317af7e = Updates;\nupdateShortMessage#313bc7f8 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true id:int user_id:long message:string pts:int pts_count:int date:int fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?long reply_to:flags.3?MessageReplyHeader entities:flags.7?Vector ttl_period:flags.25?int = Updates;\nupdateShortChatMessage#4d6deea5 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true id:int from_id:long chat_id:long message:string pts:int pts_count:int date:int fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?long reply_to:flags.3?MessageReplyHeader entities:flags.7?Vector ttl_period:flags.25?int = Updates;\nupdateShort#78d4dec1 update:Update date:int = Updates;\nupdatesCombined#725b04c3 updates:Vector users:Vector chats:Vector date:int seq_start:int seq:int = Updates;\nupdates#74ae4240 updates:Vector users:Vector chats:Vector date:int seq:int = Updates;\nupdateShortSentMessage#9015e101 flags:# out:flags.1?true id:int pts:int pts_count:int date:int media:flags.9?MessageMedia entities:flags.7?Vector ttl_period:flags.25?int = Updates;\nphotos.photos#8dca6aa5 photos:Vector users:Vector = photos.Photos;\nphotos.photosSlice#15051f54 count:int photos:Vector users:Vector = photos.Photos;\nphotos.photo#20212ca8 photo:Photo users:Vector = photos.Photo;\nupload.file#96a18d5 type:storage.FileType mtime:int bytes:bytes = upload.File;\nupload.fileCdnRedirect#f18cda44 dc_id:int file_token:bytes encryption_key:bytes encryption_iv:bytes file_hashes:Vector = upload.File;\ndcOption#18b7a10d flags:# ipv6:flags.0?true media_only:flags.1?true tcpo_only:flags.2?true cdn:flags.3?true static:flags.4?true id:int ip_address:string port:int secret:flags.10?bytes = DcOption;\nconfig#330b4067 flags:# phonecalls_enabled:flags.1?true default_p2p_contacts:flags.3?true preload_featured_stickers:flags.4?true ignore_phone_entities:flags.5?true revoke_pm_inbox:flags.6?true blocked_mode:flags.8?true pfs_enabled:flags.13?true date:int expires:int test_mode:Bool this_dc:int dc_options:Vector dc_txt_domain_name:string chat_size_max:int megagroup_size_max:int forwarded_count_max:int online_update_period_ms:int offline_blur_timeout_ms:int offline_idle_timeout_ms:int online_cloud_timeout_ms:int notify_cloud_delay_ms:int notify_default_delay_ms:int push_chat_period_ms:int push_chat_limit:int saved_gifs_limit:int edit_time_limit:int revoke_time_limit:int revoke_pm_time_limit:int rating_e_decay:int stickers_recent_limit:int stickers_faved_limit:int channels_read_media_period:int tmp_sessions:flags.0?int pinned_dialogs_count_max:int pinned_infolder_count_max:int call_receive_timeout_ms:int call_ring_timeout_ms:int call_connect_timeout_ms:int call_packet_timeout_ms:int me_url_prefix:string autoupdate_url_prefix:flags.7?string gif_search_username:flags.9?string venue_search_username:flags.10?string img_search_username:flags.11?string static_maps_provider:flags.12?string caption_length_max:int message_length_max:int webfile_dc_id:int suggested_lang_code:flags.2?string lang_pack_version:flags.2?int base_lang_pack_version:flags.2?int = Config;\nnearestDc#8e1a1775 country:string this_dc:int nearest_dc:int = NearestDc;\nhelp.appUpdate#ccbbce30 flags:# can_not_skip:flags.0?true id:int version:string text:string entities:Vector document:flags.1?Document url:flags.2?string sticker:flags.3?Document = help.AppUpdate;\nhelp.noAppUpdate#c45a6536 = help.AppUpdate;\nhelp.inviteText#18cb9f78 message:string = help.InviteText;\nencryptedChatEmpty#ab7ec0a0 id:int = EncryptedChat;\nencryptedChatWaiting#66b25953 id:int access_hash:long date:int admin_id:long participant_id:long = EncryptedChat;\nencryptedChatRequested#48f1d94c flags:# folder_id:flags.0?int id:int access_hash:long date:int admin_id:long participant_id:long g_a:bytes = EncryptedChat;\nencryptedChat#61f0d4c7 id:int access_hash:long date:int admin_id:long participant_id:long g_a_or_b:bytes key_fingerprint:long = EncryptedChat;\nencryptedChatDiscarded#1e1c7c45 flags:# history_deleted:flags.0?true id:int = EncryptedChat;\ninputEncryptedChat#f141b5e1 chat_id:int access_hash:long = InputEncryptedChat;\nencryptedFileEmpty#c21f497e = EncryptedFile;\nencryptedFile#4a70994c id:long access_hash:long size:int dc_id:int key_fingerprint:int = EncryptedFile;\ninputEncryptedFileEmpty#1837c364 = InputEncryptedFile;\ninputEncryptedFileUploaded#64bd0306 id:long parts:int md5_checksum:string key_fingerprint:int = InputEncryptedFile;\ninputEncryptedFile#5a17b5e5 id:long access_hash:long = InputEncryptedFile;\ninputEncryptedFileBigUploaded#2dc173c8 id:long parts:int key_fingerprint:int = InputEncryptedFile;\nencryptedMessage#ed18c118 random_id:long chat_id:int date:int bytes:bytes file:EncryptedFile = EncryptedMessage;\nencryptedMessageService#23734b06 random_id:long chat_id:int date:int bytes:bytes = EncryptedMessage;\nmessages.dhConfigNotModified#c0e24635 random:bytes = messages.DhConfig;\nmessages.dhConfig#2c221edd g:int p:bytes version:int random:bytes = messages.DhConfig;\nmessages.sentEncryptedMessage#560f8935 date:int = messages.SentEncryptedMessage;\nmessages.sentEncryptedFile#9493ff32 date:int file:EncryptedFile = messages.SentEncryptedMessage;\ninputDocumentEmpty#72f0eaae = InputDocument;\ninputDocument#1abfb575 id:long access_hash:long file_reference:bytes = InputDocument;\ndocumentEmpty#36f8c871 id:long = Document;\ndocument#1e87342b flags:# id:long access_hash:long file_reference:bytes date:int mime_type:string size:int thumbs:flags.0?Vector video_thumbs:flags.1?Vector dc_id:int attributes:Vector = Document;\nhelp.support#17c6b5f6 phone_number:string user:User = help.Support;\nnotifyPeer#9fd40bd8 peer:Peer = NotifyPeer;\nnotifyUsers#b4c83b4c = NotifyPeer;\nnotifyChats#c007cec3 = NotifyPeer;\nnotifyBroadcasts#d612e8ef = NotifyPeer;\nsendMessageTypingAction#16bf744e = SendMessageAction;\nsendMessageCancelAction#fd5ec8f5 = SendMessageAction;\nsendMessageRecordVideoAction#a187d66f = SendMessageAction;\nsendMessageUploadVideoAction#e9763aec progress:int = SendMessageAction;\nsendMessageRecordAudioAction#d52f73f7 = SendMessageAction;\nsendMessageUploadAudioAction#f351d7ab progress:int = SendMessageAction;\nsendMessageUploadPhotoAction#d1d34a26 progress:int = SendMessageAction;\nsendMessageUploadDocumentAction#aa0cd9e4 progress:int = SendMessageAction;\nsendMessageGeoLocationAction#176f8ba1 = SendMessageAction;\nsendMessageChooseContactAction#628cbc6f = SendMessageAction;\nsendMessageGamePlayAction#dd6a8f48 = SendMessageAction;\nsendMessageRecordRoundAction#88f27fbc = SendMessageAction;\nsendMessageUploadRoundAction#243e1c66 progress:int = SendMessageAction;\nspeakingInGroupCallAction#d92c2285 = SendMessageAction;\nsendMessageHistoryImportAction#dbda9246 progress:int = SendMessageAction;\nsendMessageChooseStickerAction#b05ac6b1 = SendMessageAction;\nsendMessageEmojiInteraction#25972bcb emoticon:string msg_id:int interaction:DataJSON = SendMessageAction;\nsendMessageEmojiInteractionSeen#b665902e emoticon:string = SendMessageAction;\ncontacts.found#b3134d9d my_results:Vector results:Vector chats:Vector users:Vector = contacts.Found;\ninputPrivacyKeyStatusTimestamp#4f96cb18 = InputPrivacyKey;\ninputPrivacyKeyChatInvite#bdfb0426 = InputPrivacyKey;\ninputPrivacyKeyPhoneCall#fabadc5f = InputPrivacyKey;\ninputPrivacyKeyPhoneP2P#db9e70d2 = InputPrivacyKey;\ninputPrivacyKeyForwards#a4dd4c08 = InputPrivacyKey;\ninputPrivacyKeyProfilePhoto#5719bacc = InputPrivacyKey;\ninputPrivacyKeyPhoneNumber#352dafa = InputPrivacyKey;\ninputPrivacyKeyAddedByPhone#d1219bdd = InputPrivacyKey;\nprivacyKeyStatusTimestamp#bc2eab30 = PrivacyKey;\nprivacyKeyChatInvite#500e6dfa = PrivacyKey;\nprivacyKeyPhoneCall#3d662b7b = PrivacyKey;\nprivacyKeyPhoneP2P#39491cc8 = PrivacyKey;\nprivacyKeyForwards#69ec56a3 = PrivacyKey;\nprivacyKeyProfilePhoto#96151fed = PrivacyKey;\nprivacyKeyPhoneNumber#d19ae46d = PrivacyKey;\nprivacyKeyAddedByPhone#42ffd42b = PrivacyKey;\ninputPrivacyValueAllowContacts#d09e07b = InputPrivacyRule;\ninputPrivacyValueAllowAll#184b35ce = InputPrivacyRule;\ninputPrivacyValueAllowUsers#131cc67f users:Vector = InputPrivacyRule;\ninputPrivacyValueDisallowContacts#ba52007 = InputPrivacyRule;\ninputPrivacyValueDisallowAll#d66b66c9 = InputPrivacyRule;\ninputPrivacyValueDisallowUsers#90110467 users:Vector = InputPrivacyRule;\ninputPrivacyValueAllowChatParticipants#840649cf chats:Vector = InputPrivacyRule;\ninputPrivacyValueDisallowChatParticipants#e94f0f86 chats:Vector = InputPrivacyRule;\nprivacyValueAllowContacts#fffe1bac = PrivacyRule;\nprivacyValueAllowAll#65427b82 = PrivacyRule;\nprivacyValueAllowUsers#b8905fb2 users:Vector = PrivacyRule;\nprivacyValueDisallowContacts#f888fa1a = PrivacyRule;\nprivacyValueDisallowAll#8b73e763 = PrivacyRule;\nprivacyValueDisallowUsers#e4621141 users:Vector = PrivacyRule;\nprivacyValueAllowChatParticipants#6b134e8e chats:Vector = PrivacyRule;\nprivacyValueDisallowChatParticipants#41c87565 chats:Vector = PrivacyRule;\naccount.privacyRules#50a04e45 rules:Vector chats:Vector users:Vector = account.PrivacyRules;\naccountDaysTTL#b8d0afdf days:int = AccountDaysTTL;\ndocumentAttributeImageSize#6c37c15c w:int h:int = DocumentAttribute;\ndocumentAttributeAnimated#11b58939 = DocumentAttribute;\ndocumentAttributeSticker#6319d612 flags:# mask:flags.1?true alt:string stickerset:InputStickerSet mask_coords:flags.0?MaskCoords = DocumentAttribute;\ndocumentAttributeVideo#ef02ce6 flags:# round_message:flags.0?true supports_streaming:flags.1?true duration:int w:int h:int = DocumentAttribute;\ndocumentAttributeAudio#9852f9c6 flags:# voice:flags.10?true duration:int title:flags.0?string performer:flags.1?string waveform:flags.2?bytes = DocumentAttribute;\ndocumentAttributeFilename#15590068 file_name:string = DocumentAttribute;\ndocumentAttributeHasStickers#9801d2f7 = DocumentAttribute;\nmessages.stickersNotModified#f1749a22 = messages.Stickers;\nmessages.stickers#30a6ec7e hash:long stickers:Vector = messages.Stickers;\nstickerPack#12b299d4 emoticon:string documents:Vector = StickerPack;\nmessages.allStickersNotModified#e86602c3 = messages.AllStickers;\nmessages.allStickers#cdbbcebb hash:long sets:Vector = messages.AllStickers;\nmessages.affectedMessages#84d19185 pts:int pts_count:int = messages.AffectedMessages;\nwebPageEmpty#eb1477e8 id:long = WebPage;\nwebPagePending#c586da1c id:long date:int = WebPage;\nwebPage#e89c45b2 flags:# id:long url:string display_url:string hash:int type:flags.0?string site_name:flags.1?string title:flags.2?string description:flags.3?string photo:flags.4?Photo embed_url:flags.5?string embed_type:flags.5?string embed_width:flags.6?int embed_height:flags.6?int duration:flags.7?int author:flags.8?string document:flags.9?Document cached_page:flags.10?Page attributes:flags.12?Vector = WebPage;\nwebPageNotModified#7311ca11 flags:# cached_page_views:flags.0?int = WebPage;\nauthorization#ad01d61d flags:# current:flags.0?true official_app:flags.1?true password_pending:flags.2?true encrypted_requests_disabled:flags.3?true call_requests_disabled:flags.4?true hash:long device_model:string platform:string system_version:string api_id:int app_name:string app_version:string date_created:int date_active:int ip:string country:string region:string = Authorization;\naccount.authorizations#4bff8ea0 authorization_ttl_days:int authorizations:Vector = account.Authorizations;\naccount.password#185b184f flags:# has_recovery:flags.0?true has_secure_values:flags.1?true has_password:flags.2?true current_algo:flags.2?PasswordKdfAlgo srp_B:flags.2?bytes srp_id:flags.2?long hint:flags.3?string email_unconfirmed_pattern:flags.4?string new_algo:PasswordKdfAlgo new_secure_algo:SecurePasswordKdfAlgo secure_random:bytes pending_reset_date:flags.5?int = account.Password;\naccount.passwordSettings#9a5c33e5 flags:# email:flags.0?string secure_settings:flags.1?SecureSecretSettings = account.PasswordSettings;\naccount.passwordInputSettings#c23727c9 flags:# new_algo:flags.0?PasswordKdfAlgo new_password_hash:flags.0?bytes hint:flags.0?string email:flags.1?string new_secure_settings:flags.2?SecureSecretSettings = account.PasswordInputSettings;\nauth.passwordRecovery#137948a5 email_pattern:string = auth.PasswordRecovery;\nreceivedNotifyMessage#a384b779 id:int flags:int = ReceivedNotifyMessage;\nchatInviteExported#ab4a819 flags:# revoked:flags.0?true permanent:flags.5?true request_needed:flags.6?true link:string admin_id:long date:int start_date:flags.4?int expire_date:flags.1?int usage_limit:flags.2?int usage:flags.3?int requested:flags.7?int title:flags.8?string = ExportedChatInvite;\nchatInviteAlready#5a686d7c chat:Chat = ChatInvite;\nchatInvite#300c44c1 flags:# channel:flags.0?true broadcast:flags.1?true public:flags.2?true megagroup:flags.3?true request_needed:flags.6?true title:string about:flags.5?string photo:Photo participants_count:int participants:flags.4?Vector = ChatInvite;\nchatInvitePeek#61695cb0 chat:Chat expires:int = ChatInvite;\ninputStickerSetEmpty#ffb62b95 = InputStickerSet;\ninputStickerSetID#9de7a269 id:long access_hash:long = InputStickerSet;\ninputStickerSetShortName#861cc8a0 short_name:string = InputStickerSet;\ninputStickerSetAnimatedEmoji#28703c8 = InputStickerSet;\ninputStickerSetDice#e67f520e emoticon:string = InputStickerSet;\ninputStickerSetAnimatedEmojiAnimations#cde3739 = InputStickerSet;\nstickerSet#d7df217a flags:# archived:flags.1?true official:flags.2?true masks:flags.3?true animated:flags.5?true installed_date:flags.0?int id:long access_hash:long title:string short_name:string thumbs:flags.4?Vector thumb_dc_id:flags.4?int thumb_version:flags.4?int count:int hash:int = StickerSet;\nmessages.stickerSet#b60a24a6 set:StickerSet packs:Vector documents:Vector = messages.StickerSet;\nmessages.stickerSetNotModified#d3f924eb = messages.StickerSet;\nbotCommand#c27ac8c7 command:string description:string = BotCommand;\nbotInfo#1b74b335 user_id:long description:string commands:Vector = BotInfo;\nkeyboardButton#a2fa4880 text:string = KeyboardButton;\nkeyboardButtonUrl#258aff05 text:string url:string = KeyboardButton;\nkeyboardButtonCallback#35bbdb6b flags:# requires_password:flags.0?true text:string data:bytes = KeyboardButton;\nkeyboardButtonRequestPhone#b16a6c29 text:string = KeyboardButton;\nkeyboardButtonRequestGeoLocation#fc796b3f text:string = KeyboardButton;\nkeyboardButtonSwitchInline#568a748 flags:# same_peer:flags.0?true text:string query:string = KeyboardButton;\nkeyboardButtonGame#50f41ccf text:string = KeyboardButton;\nkeyboardButtonBuy#afd93fbb text:string = KeyboardButton;\nkeyboardButtonUrlAuth#10b78d29 flags:# text:string fwd_text:flags.0?string url:string button_id:int = KeyboardButton;\ninputKeyboardButtonUrlAuth#d02e7fd4 flags:# request_write_access:flags.0?true text:string fwd_text:flags.1?string url:string bot:InputUser = KeyboardButton;\nkeyboardButtonRequestPoll#bbc7515d flags:# quiz:flags.0?Bool text:string = KeyboardButton;\ninputKeyboardButtonUserProfile#e988037b text:string user_id:InputUser = KeyboardButton;\nkeyboardButtonUserProfile#308660c1 text:string user_id:long = KeyboardButton;\nkeyboardButtonRow#77608b83 buttons:Vector = KeyboardButtonRow;\nreplyKeyboardHide#a03e5b85 flags:# selective:flags.2?true = ReplyMarkup;\nreplyKeyboardForceReply#86b40b08 flags:# single_use:flags.1?true selective:flags.2?true placeholder:flags.3?string = ReplyMarkup;\nreplyKeyboardMarkup#85dd99d1 flags:# resize:flags.0?true single_use:flags.1?true selective:flags.2?true rows:Vector placeholder:flags.3?string = ReplyMarkup;\nreplyInlineMarkup#48a30254 rows:Vector = ReplyMarkup;\nmessageEntityUnknown#bb92ba95 offset:int length:int = MessageEntity;\nmessageEntityMention#fa04579d offset:int length:int = MessageEntity;\nmessageEntityHashtag#6f635b0d offset:int length:int = MessageEntity;\nmessageEntityBotCommand#6cef8ac7 offset:int length:int = MessageEntity;\nmessageEntityUrl#6ed02538 offset:int length:int = MessageEntity;\nmessageEntityEmail#64e475c2 offset:int length:int = MessageEntity;\nmessageEntityBold#bd610bc9 offset:int length:int = MessageEntity;\nmessageEntityItalic#826f8b60 offset:int length:int = MessageEntity;\nmessageEntityCode#28a20571 offset:int length:int = MessageEntity;\nmessageEntityPre#73924be0 offset:int length:int language:string = MessageEntity;\nmessageEntityTextUrl#76a6d327 offset:int length:int url:string = MessageEntity;\nmessageEntityMentionName#dc7b1140 offset:int length:int user_id:long = MessageEntity;\ninputMessageEntityMentionName#208e68c9 offset:int length:int user_id:InputUser = MessageEntity;\nmessageEntityPhone#9b69e34b offset:int length:int = MessageEntity;\nmessageEntityCashtag#4c4e743f offset:int length:int = MessageEntity;\nmessageEntityUnderline#9c4e7e8b offset:int length:int = MessageEntity;\nmessageEntityStrike#bf0693d4 offset:int length:int = MessageEntity;\nmessageEntityBlockquote#20df5d0 offset:int length:int = MessageEntity;\nmessageEntityBankCard#761e6af4 offset:int length:int = MessageEntity;\nmessageEntitySpoiler#32ca960f offset:int length:int = MessageEntity;\ninputChannelEmpty#ee8c1e86 = InputChannel;\ninputChannel#f35aec28 channel_id:long access_hash:long = InputChannel;\ninputChannelFromMessage#5b934f9d peer:InputPeer msg_id:int channel_id:long = InputChannel;\ncontacts.resolvedPeer#7f077ad9 peer:Peer chats:Vector users:Vector = contacts.ResolvedPeer;\nmessageRange#ae30253 min_id:int max_id:int = MessageRange;\nupdates.channelDifferenceEmpty#3e11affb flags:# final:flags.0?true pts:int timeout:flags.1?int = updates.ChannelDifference;\nupdates.channelDifferenceTooLong#a4bcc6fe flags:# final:flags.0?true timeout:flags.1?int dialog:Dialog messages:Vector chats:Vector users:Vector = updates.ChannelDifference;\nupdates.channelDifference#2064674e flags:# final:flags.0?true pts:int timeout:flags.1?int new_messages:Vector other_updates:Vector chats:Vector users:Vector = updates.ChannelDifference;\nchannelMessagesFilterEmpty#94d42ee7 = ChannelMessagesFilter;\nchannelMessagesFilter#cd77d957 flags:# exclude_new_messages:flags.1?true ranges:Vector = ChannelMessagesFilter;\nchannelParticipant#c00c07c0 user_id:long date:int = ChannelParticipant;\nchannelParticipantSelf#35a8bfa7 flags:# via_request:flags.0?true user_id:long inviter_id:long date:int = ChannelParticipant;\nchannelParticipantCreator#2fe601d3 flags:# user_id:long admin_rights:ChatAdminRights rank:flags.0?string = ChannelParticipant;\nchannelParticipantAdmin#34c3bb53 flags:# can_edit:flags.0?true self:flags.1?true user_id:long inviter_id:flags.1?long promoted_by:long date:int admin_rights:ChatAdminRights rank:flags.2?string = ChannelParticipant;\nchannelParticipantBanned#6df8014e flags:# left:flags.0?true peer:Peer kicked_by:long date:int banned_rights:ChatBannedRights = ChannelParticipant;\nchannelParticipantLeft#1b03f006 peer:Peer = ChannelParticipant;\nchannelParticipantsRecent#de3f3c79 = ChannelParticipantsFilter;\nchannelParticipantsAdmins#b4608969 = ChannelParticipantsFilter;\nchannelParticipantsKicked#a3b54985 q:string = ChannelParticipantsFilter;\nchannelParticipantsBots#b0d1865b = ChannelParticipantsFilter;\nchannelParticipantsBanned#1427a5e1 q:string = ChannelParticipantsFilter;\nchannelParticipantsSearch#656ac4b q:string = ChannelParticipantsFilter;\nchannelParticipantsContacts#bb6ae88d q:string = ChannelParticipantsFilter;\nchannelParticipantsMentions#e04b5ceb flags:# q:flags.0?string top_msg_id:flags.1?int = ChannelParticipantsFilter;\nchannels.channelParticipants#9ab0feaf count:int participants:Vector chats:Vector users:Vector = channels.ChannelParticipants;\nchannels.channelParticipantsNotModified#f0173fe9 = channels.ChannelParticipants;\nchannels.channelParticipant#dfb80317 participant:ChannelParticipant chats:Vector users:Vector = channels.ChannelParticipant;\nhelp.termsOfService#780a0310 flags:# popup:flags.0?true id:DataJSON text:string entities:Vector min_age_confirm:flags.1?int = help.TermsOfService;\nmessages.savedGifsNotModified#e8025ca2 = messages.SavedGifs;\nmessages.savedGifs#84a02a0d hash:long gifs:Vector = messages.SavedGifs;\ninputBotInlineMessageMediaAuto#3380c786 flags:# message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageText#3dcd7a87 flags:# no_webpage:flags.0?true message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaGeo#96929a85 flags:# geo_point:InputGeoPoint heading:flags.0?int period:flags.1?int proximity_notification_radius:flags.3?int reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaVenue#417bbf11 flags:# geo_point:InputGeoPoint title:string address:string provider:string venue_id:string venue_type:string reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaContact#a6edbffd flags:# phone_number:string first_name:string last_name:string vcard:string reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageGame#4b425864 flags:# reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaInvoice#d7e78225 flags:# title:string description:string photo:flags.0?InputWebDocument invoice:Invoice payload:bytes provider:string provider_data:DataJSON reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineResult#88bf9319 flags:# id:string type:string title:flags.1?string description:flags.2?string url:flags.3?string thumb:flags.4?InputWebDocument content:flags.5?InputWebDocument send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultPhoto#a8d864a7 id:string type:string photo:InputPhoto send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultDocument#fff8fdc4 flags:# id:string type:string title:flags.1?string description:flags.2?string document:InputDocument send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultGame#4fa417f2 id:string short_name:string send_message:InputBotInlineMessage = InputBotInlineResult;\nbotInlineMessageMediaAuto#764cf810 flags:# message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageText#8c7f65e2 flags:# no_webpage:flags.0?true message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaGeo#51846fd flags:# geo:GeoPoint heading:flags.0?int period:flags.1?int proximity_notification_radius:flags.3?int reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaVenue#8a86659c flags:# geo:GeoPoint title:string address:string provider:string venue_id:string venue_type:string reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaContact#18d1cdc2 flags:# phone_number:string first_name:string last_name:string vcard:string reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaInvoice#354a9b09 flags:# shipping_address_requested:flags.1?true test:flags.3?true title:string description:string photo:flags.0?WebDocument currency:string total_amount:long reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineResult#11965f3a flags:# id:string type:string title:flags.1?string description:flags.2?string url:flags.3?string thumb:flags.4?WebDocument content:flags.5?WebDocument send_message:BotInlineMessage = BotInlineResult;\nbotInlineMediaResult#17db940b flags:# id:string type:string photo:flags.0?Photo document:flags.1?Document title:flags.2?string description:flags.3?string send_message:BotInlineMessage = BotInlineResult;\nmessages.botResults#947ca848 flags:# gallery:flags.0?true query_id:long next_offset:flags.1?string switch_pm:flags.2?InlineBotSwitchPM results:Vector cache_time:int users:Vector = messages.BotResults;\nexportedMessageLink#5dab1af4 link:string html:string = ExportedMessageLink;\nmessageFwdHeader#5f777dce flags:# imported:flags.7?true from_id:flags.0?Peer from_name:flags.5?string date:int channel_post:flags.2?int post_author:flags.3?string saved_from_peer:flags.4?Peer saved_from_msg_id:flags.4?int psa_type:flags.6?string = MessageFwdHeader;\nauth.codeTypeSms#72a3158c = auth.CodeType;\nauth.codeTypeCall#741cd3e3 = auth.CodeType;\nauth.codeTypeFlashCall#226ccefb = auth.CodeType;\nauth.codeTypeMissedCall#d61ad6ee = auth.CodeType;\nauth.sentCodeTypeApp#3dbb5986 length:int = auth.SentCodeType;\nauth.sentCodeTypeSms#c000bba2 length:int = auth.SentCodeType;\nauth.sentCodeTypeCall#5353e5a7 length:int = auth.SentCodeType;\nauth.sentCodeTypeFlashCall#ab03c6d9 pattern:string = auth.SentCodeType;\nauth.sentCodeTypeMissedCall#82006484 prefix:string length:int = auth.SentCodeType;\nmessages.botCallbackAnswer#36585ea4 flags:# alert:flags.1?true has_url:flags.3?true native_ui:flags.4?true message:flags.0?string url:flags.2?string cache_time:int = messages.BotCallbackAnswer;\nmessages.messageEditData#26b5dde6 flags:# caption:flags.0?true = messages.MessageEditData;\ninputBotInlineMessageID#890c3d89 dc_id:int id:long access_hash:long = InputBotInlineMessageID;\ninputBotInlineMessageID64#b6d915d7 dc_id:int owner_id:long id:int access_hash:long = InputBotInlineMessageID;\ninlineBotSwitchPM#3c20629f text:string start_param:string = InlineBotSwitchPM;\nmessages.peerDialogs#3371c354 dialogs:Vector messages:Vector chats:Vector users:Vector state:updates.State = messages.PeerDialogs;\ntopPeer#edcdc05b peer:Peer rating:double = TopPeer;\ntopPeerCategoryBotsPM#ab661b5b = TopPeerCategory;\ntopPeerCategoryBotsInline#148677e2 = TopPeerCategory;\ntopPeerCategoryCorrespondents#637b7ed = TopPeerCategory;\ntopPeerCategoryGroups#bd17a14a = TopPeerCategory;\ntopPeerCategoryChannels#161d9628 = TopPeerCategory;\ntopPeerCategoryPhoneCalls#1e76a78c = TopPeerCategory;\ntopPeerCategoryForwardUsers#a8406ca9 = TopPeerCategory;\ntopPeerCategoryForwardChats#fbeec0f0 = TopPeerCategory;\ntopPeerCategoryPeers#fb834291 category:TopPeerCategory count:int peers:Vector = TopPeerCategoryPeers;\ncontacts.topPeersNotModified#de266ef5 = contacts.TopPeers;\ncontacts.topPeers#70b772a8 categories:Vector chats:Vector users:Vector = contacts.TopPeers;\ncontacts.topPeersDisabled#b52c939d = contacts.TopPeers;\ndraftMessageEmpty#1b0c841a flags:# date:flags.0?int = DraftMessage;\ndraftMessage#fd8e711f flags:# no_webpage:flags.1?true reply_to_msg_id:flags.0?int message:string entities:flags.3?Vector date:int = DraftMessage;\nmessages.featuredStickersNotModified#c6dc0c66 count:int = messages.FeaturedStickers;\nmessages.featuredStickers#84c02310 hash:long count:int sets:Vector unread:Vector = messages.FeaturedStickers;\nmessages.recentStickersNotModified#b17f890 = messages.RecentStickers;\nmessages.recentStickers#88d37c56 hash:long packs:Vector stickers:Vector dates:Vector = messages.RecentStickers;\nmessages.archivedStickers#4fcba9c8 count:int sets:Vector = messages.ArchivedStickers;\nmessages.stickerSetInstallResultSuccess#38641628 = messages.StickerSetInstallResult;\nmessages.stickerSetInstallResultArchive#35e410a8 sets:Vector = messages.StickerSetInstallResult;\nstickerSetCovered#6410a5d2 set:StickerSet cover:Document = StickerSetCovered;\nstickerSetMultiCovered#3407e51b set:StickerSet covers:Vector = StickerSetCovered;\nmaskCoords#aed6dbb2 n:int x:double y:double zoom:double = MaskCoords;\ninputStickeredMediaPhoto#4a992157 id:InputPhoto = InputStickeredMedia;\ninputStickeredMediaDocument#438865b id:InputDocument = InputStickeredMedia;\ngame#bdf9653b flags:# id:long access_hash:long short_name:string title:string description:string photo:Photo document:flags.0?Document = Game;\ninputGameID#32c3e77 id:long access_hash:long = InputGame;\ninputGameShortName#c331e80a bot_id:InputUser short_name:string = InputGame;\nhighScore#73a379eb pos:int user_id:long score:int = HighScore;\nmessages.highScores#9a3bfd99 scores:Vector users:Vector = messages.HighScores;\ntextEmpty#dc3d824f = RichText;\ntextPlain#744694e0 text:string = RichText;\ntextBold#6724abc4 text:RichText = RichText;\ntextItalic#d912a59c text:RichText = RichText;\ntextUnderline#c12622c4 text:RichText = RichText;\ntextStrike#9bf8bb95 text:RichText = RichText;\ntextFixed#6c3f19b9 text:RichText = RichText;\ntextUrl#3c2884c1 text:RichText url:string webpage_id:long = RichText;\ntextEmail#de5a0dd6 text:RichText email:string = RichText;\ntextConcat#7e6260d7 texts:Vector = RichText;\ntextSubscript#ed6a8504 text:RichText = RichText;\ntextSuperscript#c7fb5e01 text:RichText = RichText;\ntextMarked#34b8621 text:RichText = RichText;\ntextPhone#1ccb966a text:RichText phone:string = RichText;\ntextImage#81ccf4f document_id:long w:int h:int = RichText;\ntextAnchor#35553762 text:RichText name:string = RichText;\npageBlockUnsupported#13567e8a = PageBlock;\npageBlockTitle#70abc3fd text:RichText = PageBlock;\npageBlockSubtitle#8ffa9a1f text:RichText = PageBlock;\npageBlockAuthorDate#baafe5e0 author:RichText published_date:int = PageBlock;\npageBlockHeader#bfd064ec text:RichText = PageBlock;\npageBlockSubheader#f12bb6e1 text:RichText = PageBlock;\npageBlockParagraph#467a0766 text:RichText = PageBlock;\npageBlockPreformatted#c070d93e text:RichText language:string = PageBlock;\npageBlockFooter#48870999 text:RichText = PageBlock;\npageBlockDivider#db20b188 = PageBlock;\npageBlockAnchor#ce0d37b0 name:string = PageBlock;\npageBlockList#e4e88011 items:Vector = PageBlock;\npageBlockBlockquote#263d7c26 text:RichText caption:RichText = PageBlock;\npageBlockPullquote#4f4456d3 text:RichText caption:RichText = PageBlock;\npageBlockPhoto#1759c560 flags:# photo_id:long caption:PageCaption url:flags.0?string webpage_id:flags.0?long = PageBlock;\npageBlockVideo#7c8fe7b6 flags:# autoplay:flags.0?true loop:flags.1?true video_id:long caption:PageCaption = PageBlock;\npageBlockCover#39f23300 cover:PageBlock = PageBlock;\npageBlockEmbed#a8718dc5 flags:# full_width:flags.0?true allow_scrolling:flags.3?true url:flags.1?string html:flags.2?string poster_photo_id:flags.4?long w:flags.5?int h:flags.5?int caption:PageCaption = PageBlock;\npageBlockEmbedPost#f259a80b url:string webpage_id:long author_photo_id:long author:string date:int blocks:Vector caption:PageCaption = PageBlock;\npageBlockCollage#65a0fa4d items:Vector caption:PageCaption = PageBlock;\npageBlockSlideshow#31f9590 items:Vector caption:PageCaption = PageBlock;\npageBlockChannel#ef1751b5 channel:Chat = PageBlock;\npageBlockAudio#804361ea audio_id:long caption:PageCaption = PageBlock;\npageBlockKicker#1e148390 text:RichText = PageBlock;\npageBlockTable#bf4dea82 flags:# bordered:flags.0?true striped:flags.1?true title:RichText rows:Vector = PageBlock;\npageBlockOrderedList#9a8ae1e1 items:Vector = PageBlock;\npageBlockDetails#76768bed flags:# open:flags.0?true blocks:Vector title:RichText = PageBlock;\npageBlockRelatedArticles#16115a96 title:RichText articles:Vector = PageBlock;\npageBlockMap#a44f3ef6 geo:GeoPoint zoom:int w:int h:int caption:PageCaption = PageBlock;\nphoneCallDiscardReasonMissed#85e42301 = PhoneCallDiscardReason;\nphoneCallDiscardReasonDisconnect#e095c1a0 = PhoneCallDiscardReason;\nphoneCallDiscardReasonHangup#57adc690 = PhoneCallDiscardReason;\nphoneCallDiscardReasonBusy#faf7e8c9 = PhoneCallDiscardReason;\ndataJSON#7d748d04 data:string = DataJSON;\nlabeledPrice#cb296bf8 label:string amount:long = LabeledPrice;\ninvoice#cd886e0 flags:# test:flags.0?true name_requested:flags.1?true phone_requested:flags.2?true email_requested:flags.3?true shipping_address_requested:flags.4?true flexible:flags.5?true phone_to_provider:flags.6?true email_to_provider:flags.7?true currency:string prices:Vector max_tip_amount:flags.8?long suggested_tip_amounts:flags.8?Vector = Invoice;\npaymentCharge#ea02c27e id:string provider_charge_id:string = PaymentCharge;\npostAddress#1e8caaeb street_line1:string street_line2:string city:string state:string country_iso2:string post_code:string = PostAddress;\npaymentRequestedInfo#909c3f94 flags:# name:flags.0?string phone:flags.1?string email:flags.2?string shipping_address:flags.3?PostAddress = PaymentRequestedInfo;\npaymentSavedCredentialsCard#cdc27a1f id:string title:string = PaymentSavedCredentials;\nwebDocument#1c570ed1 url:string access_hash:long size:int mime_type:string attributes:Vector = WebDocument;\nwebDocumentNoProxy#f9c8bcc6 url:string size:int mime_type:string attributes:Vector = WebDocument;\ninputWebDocument#9bed434d url:string size:int mime_type:string attributes:Vector = InputWebDocument;\ninputWebFileLocation#c239d686 url:string access_hash:long = InputWebFileLocation;\ninputWebFileGeoPointLocation#9f2221c9 geo_point:InputGeoPoint access_hash:long w:int h:int zoom:int scale:int = InputWebFileLocation;\nupload.webFile#21e753bc size:int mime_type:string file_type:storage.FileType mtime:int bytes:bytes = upload.WebFile;\npayments.paymentForm#1694761b flags:# can_save_credentials:flags.2?true password_missing:flags.3?true form_id:long bot_id:long invoice:Invoice provider_id:long url:string native_provider:flags.4?string native_params:flags.4?DataJSON saved_info:flags.0?PaymentRequestedInfo saved_credentials:flags.1?PaymentSavedCredentials users:Vector = payments.PaymentForm;\npayments.validatedRequestedInfo#d1451883 flags:# id:flags.0?string shipping_options:flags.1?Vector = payments.ValidatedRequestedInfo;\npayments.paymentResult#4e5f810d updates:Updates = payments.PaymentResult;\npayments.paymentVerificationNeeded#d8411139 url:string = payments.PaymentResult;\npayments.paymentReceipt#70c4fe03 flags:# date:int bot_id:long provider_id:long title:string description:string photo:flags.2?WebDocument invoice:Invoice info:flags.0?PaymentRequestedInfo shipping:flags.1?ShippingOption tip_amount:flags.3?long currency:string total_amount:long credentials_title:string users:Vector = payments.PaymentReceipt;\npayments.savedInfo#fb8fe43c flags:# has_saved_credentials:flags.1?true saved_info:flags.0?PaymentRequestedInfo = payments.SavedInfo;\ninputPaymentCredentialsSaved#c10eb2cf id:string tmp_password:bytes = InputPaymentCredentials;\ninputPaymentCredentials#3417d728 flags:# save:flags.0?true data:DataJSON = InputPaymentCredentials;\ninputPaymentCredentialsApplePay#aa1c39f payment_data:DataJSON = InputPaymentCredentials;\ninputPaymentCredentialsGooglePay#8ac32801 payment_token:DataJSON = InputPaymentCredentials;\naccount.tmpPassword#db64fd34 tmp_password:bytes valid_until:int = account.TmpPassword;\nshippingOption#b6213cdf id:string title:string prices:Vector = ShippingOption;\ninputStickerSetItem#ffa0a496 flags:# document:InputDocument emoji:string mask_coords:flags.0?MaskCoords = InputStickerSetItem;\ninputPhoneCall#1e36fded id:long access_hash:long = InputPhoneCall;\nphoneCallEmpty#5366c915 id:long = PhoneCall;\nphoneCallWaiting#c5226f17 flags:# video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long protocol:PhoneCallProtocol receive_date:flags.0?int = PhoneCall;\nphoneCallRequested#14b0ed0c flags:# video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long g_a_hash:bytes protocol:PhoneCallProtocol = PhoneCall;\nphoneCallAccepted#3660c311 flags:# video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long g_b:bytes protocol:PhoneCallProtocol = PhoneCall;\nphoneCall#967f7c67 flags:# p2p_allowed:flags.5?true video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long g_a_or_b:bytes key_fingerprint:long protocol:PhoneCallProtocol connections:Vector start_date:int = PhoneCall;\nphoneCallDiscarded#50ca4de1 flags:# need_rating:flags.2?true need_debug:flags.3?true video:flags.6?true id:long reason:flags.0?PhoneCallDiscardReason duration:flags.1?int = PhoneCall;\nphoneConnection#9d4c17c0 id:long ip:string ipv6:string port:int peer_tag:bytes = PhoneConnection;\nphoneConnectionWebrtc#635fe375 flags:# turn:flags.0?true stun:flags.1?true id:long ip:string ipv6:string port:int username:string password:string = PhoneConnection;\nphoneCallProtocol#fc878fc8 flags:# udp_p2p:flags.0?true udp_reflector:flags.1?true min_layer:int max_layer:int library_versions:Vector = PhoneCallProtocol;\nphone.phoneCall#ec82e140 phone_call:PhoneCall users:Vector = phone.PhoneCall;\nupload.cdnFileReuploadNeeded#eea8e46e request_token:bytes = upload.CdnFile;\nupload.cdnFile#a99fca4f bytes:bytes = upload.CdnFile;\ncdnPublicKey#c982eaba dc_id:int public_key:string = CdnPublicKey;\ncdnConfig#5725e40a public_keys:Vector = CdnConfig;\nlangPackString#cad181f6 key:string value:string = LangPackString;\nlangPackStringPluralized#6c47ac9f flags:# key:string zero_value:flags.0?string one_value:flags.1?string two_value:flags.2?string few_value:flags.3?string many_value:flags.4?string other_value:string = LangPackString;\nlangPackStringDeleted#2979eeb2 key:string = LangPackString;\nlangPackDifference#f385c1f6 lang_code:string from_version:int version:int strings:Vector = LangPackDifference;\nlangPackLanguage#eeca5ce3 flags:# official:flags.0?true rtl:flags.2?true beta:flags.3?true name:string native_name:string lang_code:string base_lang_code:flags.1?string plural_code:string strings_count:int translated_count:int translations_url:string = LangPackLanguage;\nchannelAdminLogEventActionChangeTitle#e6dfb825 prev_value:string new_value:string = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeAbout#55188a2e prev_value:string new_value:string = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeUsername#6a4afc38 prev_value:string new_value:string = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangePhoto#434bd2af prev_photo:Photo new_photo:Photo = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleInvites#1b7907ae new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleSignatures#26ae0971 new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionUpdatePinned#e9e82c18 message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionEditMessage#709b2405 prev_message:Message new_message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionDeleteMessage#42e047bb message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantJoin#183040d3 = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantLeave#f89777f2 = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantInvite#e31c34d8 participant:ChannelParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantToggleBan#e6d83d7e prev_participant:ChannelParticipant new_participant:ChannelParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantToggleAdmin#d5676710 prev_participant:ChannelParticipant new_participant:ChannelParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeStickerSet#b1c3caa7 prev_stickerset:InputStickerSet new_stickerset:InputStickerSet = ChannelAdminLogEventAction;\nchannelAdminLogEventActionTogglePreHistoryHidden#5f5c95f1 new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionDefaultBannedRights#2df5fc0a prev_banned_rights:ChatBannedRights new_banned_rights:ChatBannedRights = ChannelAdminLogEventAction;\nchannelAdminLogEventActionStopPoll#8f079643 message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeLinkedChat#50c7ac8 prev_value:long new_value:long = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeLocation#e6b76ae prev_value:ChannelLocation new_value:ChannelLocation = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleSlowMode#53909779 prev_value:int new_value:int = ChannelAdminLogEventAction;\nchannelAdminLogEventActionStartGroupCall#23209745 call:InputGroupCall = ChannelAdminLogEventAction;\nchannelAdminLogEventActionDiscardGroupCall#db9f9140 call:InputGroupCall = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantMute#f92424d2 participant:GroupCallParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantUnmute#e64429c0 participant:GroupCallParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleGroupCallSetting#56d6a247 join_muted:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantJoinByInvite#5cdada77 invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionExportedInviteDelete#5a50fca4 invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionExportedInviteRevoke#410a134e invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionExportedInviteEdit#e90ebb59 prev_invite:ExportedChatInvite new_invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantVolume#3e7f6847 participant:GroupCallParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeHistoryTTL#6e941a38 prev_value:int new_value:int = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantJoinByRequest#afb6144a invite:ExportedChatInvite approved_by:long = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleNoForwards#cb2ac766 new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionSendMessage#278f2868 message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeAvailableReactions#9cf7f76a prev_value:Vector new_value:Vector = ChannelAdminLogEventAction;\nchannelAdminLogEvent#1fad68cd id:long date:int user_id:long action:ChannelAdminLogEventAction = ChannelAdminLogEvent;\nchannels.adminLogResults#ed8af74d events:Vector chats:Vector users:Vector = channels.AdminLogResults;\nchannelAdminLogEventsFilter#ea107ae4 flags:# join:flags.0?true leave:flags.1?true invite:flags.2?true ban:flags.3?true unban:flags.4?true kick:flags.5?true unkick:flags.6?true promote:flags.7?true demote:flags.8?true info:flags.9?true settings:flags.10?true pinned:flags.11?true edit:flags.12?true delete:flags.13?true group_call:flags.14?true invites:flags.15?true send:flags.16?true = ChannelAdminLogEventsFilter;\npopularContact#5ce14175 client_id:long importers:int = PopularContact;\nmessages.favedStickersNotModified#9e8fa6d3 = messages.FavedStickers;\nmessages.favedStickers#2cb51097 hash:long packs:Vector stickers:Vector = messages.FavedStickers;\nrecentMeUrlUnknown#46e1d13d url:string = RecentMeUrl;\nrecentMeUrlUser#b92c09e2 url:string user_id:long = RecentMeUrl;\nrecentMeUrlChat#b2da71d2 url:string chat_id:long = RecentMeUrl;\nrecentMeUrlChatInvite#eb49081d url:string chat_invite:ChatInvite = RecentMeUrl;\nrecentMeUrlStickerSet#bc0a57dc url:string set:StickerSetCovered = RecentMeUrl;\nhelp.recentMeUrls#e0310d7 urls:Vector chats:Vector users:Vector = help.RecentMeUrls;\ninputSingleMedia#1cc6e91f flags:# media:InputMedia random_id:long message:string entities:flags.0?Vector = InputSingleMedia;\nwebAuthorization#a6f8f452 hash:long bot_id:long domain:string browser:string platform:string date_created:int date_active:int ip:string region:string = WebAuthorization;\naccount.webAuthorizations#ed56c9fc authorizations:Vector users:Vector = account.WebAuthorizations;\ninputMessageID#a676a322 id:int = InputMessage;\ninputMessageReplyTo#bad88395 id:int = InputMessage;\ninputMessagePinned#86872538 = InputMessage;\ninputMessageCallbackQuery#acfa1a7e id:int query_id:long = InputMessage;\ninputDialogPeer#fcaafeb7 peer:InputPeer = InputDialogPeer;\ninputDialogPeerFolder#64600527 folder_id:int = InputDialogPeer;\ndialogPeer#e56dbf05 peer:Peer = DialogPeer;\ndialogPeerFolder#514519e2 folder_id:int = DialogPeer;\nmessages.foundStickerSetsNotModified#d54b65d = messages.FoundStickerSets;\nmessages.foundStickerSets#8af09dd2 hash:long sets:Vector = messages.FoundStickerSets;\nfileHash#6242c773 offset:int limit:int hash:bytes = FileHash;\ninputClientProxy#75588b3f address:string port:int = InputClientProxy;\nhelp.termsOfServiceUpdateEmpty#e3309f7f expires:int = help.TermsOfServiceUpdate;\nhelp.termsOfServiceUpdate#28ecf961 expires:int terms_of_service:help.TermsOfService = help.TermsOfServiceUpdate;\ninputSecureFileUploaded#3334b0f0 id:long parts:int md5_checksum:string file_hash:bytes secret:bytes = InputSecureFile;\ninputSecureFile#5367e5be id:long access_hash:long = InputSecureFile;\nsecureFileEmpty#64199744 = SecureFile;\nsecureFile#e0277a62 id:long access_hash:long size:int dc_id:int date:int file_hash:bytes secret:bytes = SecureFile;\nsecureData#8aeabec3 data:bytes data_hash:bytes secret:bytes = SecureData;\nsecurePlainPhone#7d6099dd phone:string = SecurePlainData;\nsecurePlainEmail#21ec5a5f email:string = SecurePlainData;\nsecureValueTypePersonalDetails#9d2a81e3 = SecureValueType;\nsecureValueTypePassport#3dac6a00 = SecureValueType;\nsecureValueTypeDriverLicense#6e425c4 = SecureValueType;\nsecureValueTypeIdentityCard#a0d0744b = SecureValueType;\nsecureValueTypeInternalPassport#99a48f23 = SecureValueType;\nsecureValueTypeAddress#cbe31e26 = SecureValueType;\nsecureValueTypeUtilityBill#fc36954e = SecureValueType;\nsecureValueTypeBankStatement#89137c0d = SecureValueType;\nsecureValueTypeRentalAgreement#8b883488 = SecureValueType;\nsecureValueTypePassportRegistration#99e3806a = SecureValueType;\nsecureValueTypeTemporaryRegistration#ea02ec33 = SecureValueType;\nsecureValueTypePhone#b320aadb = SecureValueType;\nsecureValueTypeEmail#8e3ca7ee = SecureValueType;\nsecureValue#187fa0ca flags:# type:SecureValueType data:flags.0?SecureData front_side:flags.1?SecureFile reverse_side:flags.2?SecureFile selfie:flags.3?SecureFile translation:flags.6?Vector files:flags.4?Vector plain_data:flags.5?SecurePlainData hash:bytes = SecureValue;\ninputSecureValue#db21d0a7 flags:# type:SecureValueType data:flags.0?SecureData front_side:flags.1?InputSecureFile reverse_side:flags.2?InputSecureFile selfie:flags.3?InputSecureFile translation:flags.6?Vector files:flags.4?Vector plain_data:flags.5?SecurePlainData = InputSecureValue;\nsecureValueHash#ed1ecdb0 type:SecureValueType hash:bytes = SecureValueHash;\nsecureValueErrorData#e8a40bd9 type:SecureValueType data_hash:bytes field:string text:string = SecureValueError;\nsecureValueErrorFrontSide#be3dfa type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorReverseSide#868a2aa5 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorSelfie#e537ced6 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorFile#7a700873 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorFiles#666220e9 type:SecureValueType file_hash:Vector text:string = SecureValueError;\nsecureValueError#869d758f type:SecureValueType hash:bytes text:string = SecureValueError;\nsecureValueErrorTranslationFile#a1144770 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorTranslationFiles#34636dd8 type:SecureValueType file_hash:Vector text:string = SecureValueError;\nsecureCredentialsEncrypted#33f0ea47 data:bytes hash:bytes secret:bytes = SecureCredentialsEncrypted;\naccount.authorizationForm#ad2e1cd8 flags:# required_types:Vector values:Vector errors:Vector users:Vector privacy_policy_url:flags.0?string = account.AuthorizationForm;\naccount.sentEmailCode#811f854f email_pattern:string length:int = account.SentEmailCode;\nhelp.deepLinkInfoEmpty#66afa166 = help.DeepLinkInfo;\nhelp.deepLinkInfo#6a4ee832 flags:# update_app:flags.0?true message:string entities:flags.1?Vector = help.DeepLinkInfo;\nsavedPhoneContact#1142bd56 phone:string first_name:string last_name:string date:int = SavedContact;\naccount.takeout#4dba4501 id:long = account.Takeout;\npasswordKdfAlgoUnknown#d45ab096 = PasswordKdfAlgo;\npasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow#3a912d4a salt1:bytes salt2:bytes g:int p:bytes = PasswordKdfAlgo;\nsecurePasswordKdfAlgoUnknown#4a8537 = SecurePasswordKdfAlgo;\nsecurePasswordKdfAlgoPBKDF2HMACSHA512iter100000#bbf2dda0 salt:bytes = SecurePasswordKdfAlgo;\nsecurePasswordKdfAlgoSHA512#86471d92 salt:bytes = SecurePasswordKdfAlgo;\nsecureSecretSettings#1527bcac secure_algo:SecurePasswordKdfAlgo secure_secret:bytes secure_secret_id:long = SecureSecretSettings;\ninputCheckPasswordEmpty#9880f658 = InputCheckPasswordSRP;\ninputCheckPasswordSRP#d27ff082 srp_id:long A:bytes M1:bytes = InputCheckPasswordSRP;\nsecureRequiredType#829d99da flags:# native_names:flags.0?true selfie_required:flags.1?true translation_required:flags.2?true type:SecureValueType = SecureRequiredType;\nsecureRequiredTypeOneOf#27477b4 types:Vector = SecureRequiredType;\nhelp.passportConfigNotModified#bfb9f457 = help.PassportConfig;\nhelp.passportConfig#a098d6af hash:int countries_langs:DataJSON = help.PassportConfig;\ninputAppEvent#1d1b1245 time:double type:string peer:long data:JSONValue = InputAppEvent;\njsonObjectValue#c0de1bd9 key:string value:JSONValue = JSONObjectValue;\njsonNull#3f6d7b68 = JSONValue;\njsonBool#c7345e6a value:Bool = JSONValue;\njsonNumber#2be0dfa4 value:double = JSONValue;\njsonString#b71e767a value:string = JSONValue;\njsonArray#f7444763 value:Vector = JSONValue;\njsonObject#99c1d49d value:Vector = JSONValue;\npageTableCell#34566b6a flags:# header:flags.0?true align_center:flags.3?true align_right:flags.4?true valign_middle:flags.5?true valign_bottom:flags.6?true text:flags.7?RichText colspan:flags.1?int rowspan:flags.2?int = PageTableCell;\npageTableRow#e0c0c5e5 cells:Vector = PageTableRow;\npageCaption#6f747657 text:RichText credit:RichText = PageCaption;\npageListItemText#b92fb6cd text:RichText = PageListItem;\npageListItemBlocks#25e073fc blocks:Vector = PageListItem;\npageListOrderedItemText#5e068047 num:string text:RichText = PageListOrderedItem;\npageListOrderedItemBlocks#98dd8936 num:string blocks:Vector = PageListOrderedItem;\npageRelatedArticle#b390dc08 flags:# url:string webpage_id:long title:flags.0?string description:flags.1?string photo_id:flags.2?long author:flags.3?string published_date:flags.4?int = PageRelatedArticle;\npage#98657f0d flags:# part:flags.0?true rtl:flags.1?true v2:flags.2?true url:string blocks:Vector photos:Vector documents:Vector views:flags.3?int = Page;\nhelp.supportName#8c05f1c9 name:string = help.SupportName;\nhelp.userInfoEmpty#f3ae2eed = help.UserInfo;\nhelp.userInfo#1eb3758 message:string entities:Vector author:string date:int = help.UserInfo;\npollAnswer#6ca9c2e9 text:string option:bytes = PollAnswer;\npoll#86e18161 id:long flags:# closed:flags.0?true public_voters:flags.1?true multiple_choice:flags.2?true quiz:flags.3?true question:string answers:Vector close_period:flags.4?int close_date:flags.5?int = Poll;\npollAnswerVoters#3b6ddad2 flags:# chosen:flags.0?true correct:flags.1?true option:bytes voters:int = PollAnswerVoters;\npollResults#dcb82ea3 flags:# min:flags.0?true results:flags.1?Vector total_voters:flags.2?int recent_voters:flags.3?Vector solution:flags.4?string solution_entities:flags.4?Vector = PollResults;\nchatOnlines#f041e250 onlines:int = ChatOnlines;\nstatsURL#47a971e0 url:string = StatsURL;\nchatAdminRights#5fb224d5 flags:# change_info:flags.0?true post_messages:flags.1?true edit_messages:flags.2?true delete_messages:flags.3?true ban_users:flags.4?true invite_users:flags.5?true pin_messages:flags.7?true add_admins:flags.9?true anonymous:flags.10?true manage_call:flags.11?true other:flags.12?true = ChatAdminRights;\nchatBannedRights#9f120418 flags:# view_messages:flags.0?true send_messages:flags.1?true send_media:flags.2?true send_stickers:flags.3?true send_gifs:flags.4?true send_games:flags.5?true send_inline:flags.6?true embed_links:flags.7?true send_polls:flags.8?true change_info:flags.10?true invite_users:flags.15?true pin_messages:flags.17?true until_date:int = ChatBannedRights;\ninputWallPaper#e630b979 id:long access_hash:long = InputWallPaper;\ninputWallPaperSlug#72091c80 slug:string = InputWallPaper;\ninputWallPaperNoFile#967a462e id:long = InputWallPaper;\naccount.wallPapersNotModified#1c199183 = account.WallPapers;\naccount.wallPapers#cdc3858c hash:long wallpapers:Vector = account.WallPapers;\ncodeSettings#8a6469c2 flags:# allow_flashcall:flags.0?true current_number:flags.1?true allow_app_hash:flags.4?true allow_missed_call:flags.5?true logout_tokens:flags.6?Vector = CodeSettings;\nwallPaperSettings#1dc1bca4 flags:# blur:flags.1?true motion:flags.2?true background_color:flags.0?int second_background_color:flags.4?int third_background_color:flags.5?int fourth_background_color:flags.6?int intensity:flags.3?int rotation:flags.4?int = WallPaperSettings;\nautoDownloadSettings#e04232f3 flags:# disabled:flags.0?true video_preload_large:flags.1?true audio_preload_next:flags.2?true phonecalls_less_data:flags.3?true photo_size_max:int video_size_max:int file_size_max:int video_upload_maxbitrate:int = AutoDownloadSettings;\naccount.autoDownloadSettings#63cacf26 low:AutoDownloadSettings medium:AutoDownloadSettings high:AutoDownloadSettings = account.AutoDownloadSettings;\nemojiKeyword#d5b3b9f9 keyword:string emoticons:Vector = EmojiKeyword;\nemojiKeywordDeleted#236df622 keyword:string emoticons:Vector = EmojiKeyword;\nemojiKeywordsDifference#5cc761bd lang_code:string from_version:int version:int keywords:Vector = EmojiKeywordsDifference;\nemojiURL#a575739d url:string = EmojiURL;\nemojiLanguage#b3fb5361 lang_code:string = EmojiLanguage;\nfolder#ff544e65 flags:# autofill_new_broadcasts:flags.0?true autofill_public_groups:flags.1?true autofill_new_correspondents:flags.2?true id:int title:string photo:flags.3?ChatPhoto = Folder;\ninputFolderPeer#fbd2c296 peer:InputPeer folder_id:int = InputFolderPeer;\nfolderPeer#e9baa668 peer:Peer folder_id:int = FolderPeer;\nmessages.searchCounter#e844ebff flags:# inexact:flags.1?true filter:MessagesFilter count:int = messages.SearchCounter;\nurlAuthResultRequest#92d33a0e flags:# request_write_access:flags.0?true bot:User domain:string = UrlAuthResult;\nurlAuthResultAccepted#8f8c0e4e url:string = UrlAuthResult;\nurlAuthResultDefault#a9d6db1f = UrlAuthResult;\nchannelLocationEmpty#bfb5ad8b = ChannelLocation;\nchannelLocation#209b82db geo_point:GeoPoint address:string = ChannelLocation;\npeerLocated#ca461b5d peer:Peer expires:int distance:int = PeerLocated;\npeerSelfLocated#f8ec284b expires:int = PeerLocated;\nrestrictionReason#d072acb4 platform:string reason:string text:string = RestrictionReason;\ninputTheme#3c5693e9 id:long access_hash:long = InputTheme;\ninputThemeSlug#f5890df1 slug:string = InputTheme;\ntheme#a00e67d6 flags:# creator:flags.0?true default:flags.1?true for_chat:flags.5?true id:long access_hash:long slug:string title:string document:flags.2?Document settings:flags.3?Vector emoticon:flags.6?string installs_count:flags.4?int = Theme;\naccount.themesNotModified#f41eb622 = account.Themes;\naccount.themes#9a3d8c6d hash:long themes:Vector = account.Themes;\nauth.loginToken#629f1980 expires:int token:bytes = auth.LoginToken;\nauth.loginTokenMigrateTo#68e9916 dc_id:int token:bytes = auth.LoginToken;\nauth.loginTokenSuccess#390d5c5e authorization:auth.Authorization = auth.LoginToken;\naccount.contentSettings#57e28221 flags:# sensitive_enabled:flags.0?true sensitive_can_change:flags.1?true = account.ContentSettings;\nmessages.inactiveChats#a927fec5 dates:Vector chats:Vector users:Vector = messages.InactiveChats;\nbaseThemeClassic#c3a12462 = BaseTheme;\nbaseThemeDay#fbd81688 = BaseTheme;\nbaseThemeNight#b7b31ea8 = BaseTheme;\nbaseThemeTinted#6d5f77ee = BaseTheme;\nbaseThemeArctic#5b11125a = BaseTheme;\ninputThemeSettings#8fde504f flags:# message_colors_animated:flags.2?true base_theme:BaseTheme accent_color:int outbox_accent_color:flags.3?int message_colors:flags.0?Vector wallpaper:flags.1?InputWallPaper wallpaper_settings:flags.1?WallPaperSettings = InputThemeSettings;\nthemeSettings#fa58b6d4 flags:# message_colors_animated:flags.2?true base_theme:BaseTheme accent_color:int outbox_accent_color:flags.3?int message_colors:flags.0?Vector wallpaper:flags.1?WallPaper = ThemeSettings;\nwebPageAttributeTheme#54b56617 flags:# documents:flags.0?Vector settings:flags.1?ThemeSettings = WebPageAttribute;\nmessageUserVote#34d247b4 user_id:long option:bytes date:int = MessageUserVote;\nmessageUserVoteInputOption#3ca5b0ec user_id:long date:int = MessageUserVote;\nmessageUserVoteMultiple#8a65e557 user_id:long options:Vector date:int = MessageUserVote;\nmessages.votesList#823f649 flags:# count:int votes:Vector users:Vector next_offset:flags.0?string = messages.VotesList;\nbankCardOpenUrl#f568028a url:string name:string = BankCardOpenUrl;\npayments.bankCardData#3e24e573 title:string open_urls:Vector = payments.BankCardData;\ndialogFilter#7438f7e8 flags:# contacts:flags.0?true non_contacts:flags.1?true groups:flags.2?true broadcasts:flags.3?true bots:flags.4?true exclude_muted:flags.11?true exclude_read:flags.12?true exclude_archived:flags.13?true id:int title:string emoticon:flags.25?string pinned_peers:Vector include_peers:Vector exclude_peers:Vector = DialogFilter;\ndialogFilterSuggested#77744d4a filter:DialogFilter description:string = DialogFilterSuggested;\nstatsDateRangeDays#b637edaf min_date:int max_date:int = StatsDateRangeDays;\nstatsAbsValueAndPrev#cb43acde current:double previous:double = StatsAbsValueAndPrev;\nstatsPercentValue#cbce2fe0 part:double total:double = StatsPercentValue;\nstatsGraphAsync#4a27eb2d token:string = StatsGraph;\nstatsGraphError#bedc9822 error:string = StatsGraph;\nstatsGraph#8ea464b6 flags:# json:DataJSON zoom_token:flags.0?string = StatsGraph;\nmessageInteractionCounters#ad4fc9bd msg_id:int views:int forwards:int = MessageInteractionCounters;\nstats.broadcastStats#bdf78394 period:StatsDateRangeDays followers:StatsAbsValueAndPrev views_per_post:StatsAbsValueAndPrev shares_per_post:StatsAbsValueAndPrev enabled_notifications:StatsPercentValue growth_graph:StatsGraph followers_graph:StatsGraph mute_graph:StatsGraph top_hours_graph:StatsGraph interactions_graph:StatsGraph iv_interactions_graph:StatsGraph views_by_source_graph:StatsGraph new_followers_by_source_graph:StatsGraph languages_graph:StatsGraph recent_message_interactions:Vector = stats.BroadcastStats;\nhelp.promoDataEmpty#98f6ac75 expires:int = help.PromoData;\nhelp.promoData#8c39793f flags:# proxy:flags.0?true expires:int peer:Peer chats:Vector users:Vector psa_type:flags.1?string psa_message:flags.2?string = help.PromoData;\nvideoSize#de33b094 flags:# type:string w:int h:int size:int video_start_ts:flags.0?double = VideoSize;\nstatsGroupTopPoster#9d04af9b user_id:long messages:int avg_chars:int = StatsGroupTopPoster;\nstatsGroupTopAdmin#d7584c87 user_id:long deleted:int kicked:int banned:int = StatsGroupTopAdmin;\nstatsGroupTopInviter#535f779d user_id:long invitations:int = StatsGroupTopInviter;\nstats.megagroupStats#ef7ff916 period:StatsDateRangeDays members:StatsAbsValueAndPrev messages:StatsAbsValueAndPrev viewers:StatsAbsValueAndPrev posters:StatsAbsValueAndPrev growth_graph:StatsGraph members_graph:StatsGraph new_members_by_source_graph:StatsGraph languages_graph:StatsGraph messages_graph:StatsGraph actions_graph:StatsGraph top_hours_graph:StatsGraph weekdays_graph:StatsGraph top_posters:Vector top_admins:Vector top_inviters:Vector users:Vector = stats.MegagroupStats;\nglobalPrivacySettings#bea2f424 flags:# archive_and_mute_new_noncontact_peers:flags.0?Bool = GlobalPrivacySettings;\nhelp.countryCode#4203c5ef flags:# country_code:string prefixes:flags.0?Vector patterns:flags.1?Vector = help.CountryCode;\nhelp.country#c3878e23 flags:# hidden:flags.0?true iso2:string default_name:string name:flags.1?string country_codes:Vector = help.Country;\nhelp.countriesListNotModified#93cc1f32 = help.CountriesList;\nhelp.countriesList#87d0759e countries:Vector hash:int = help.CountriesList;\nmessageViews#455b853d flags:# views:flags.0?int forwards:flags.1?int replies:flags.2?MessageReplies = MessageViews;\nmessages.messageViews#b6c4f543 views:Vector chats:Vector users:Vector = messages.MessageViews;\nmessages.discussionMessage#a6341782 flags:# messages:Vector max_id:flags.0?int read_inbox_max_id:flags.1?int read_outbox_max_id:flags.2?int unread_count:int chats:Vector users:Vector = messages.DiscussionMessage;\nmessageReplyHeader#a6d57763 flags:# reply_to_msg_id:int reply_to_peer_id:flags.0?Peer reply_to_top_id:flags.1?int = MessageReplyHeader;\nmessageReplies#83d60fc2 flags:# comments:flags.0?true replies:int replies_pts:int recent_repliers:flags.1?Vector channel_id:flags.0?long max_id:flags.2?int read_max_id:flags.3?int = MessageReplies;\npeerBlocked#e8fd8014 peer_id:Peer date:int = PeerBlocked;\nstats.messageStats#8999f295 views_graph:StatsGraph = stats.MessageStats;\ngroupCallDiscarded#7780bcb4 id:long access_hash:long duration:int = GroupCall;\ngroupCall#d597650c flags:# join_muted:flags.1?true can_change_join_muted:flags.2?true join_date_asc:flags.6?true schedule_start_subscribed:flags.8?true can_start_video:flags.9?true record_video_active:flags.11?true id:long access_hash:long participants_count:int title:flags.3?string stream_dc_id:flags.4?int record_start_date:flags.5?int schedule_date:flags.7?int unmuted_video_count:flags.10?int unmuted_video_limit:int version:int = GroupCall;\ninputGroupCall#d8aa840f id:long access_hash:long = InputGroupCall;\ngroupCallParticipant#eba636fe flags:# muted:flags.0?true left:flags.1?true can_self_unmute:flags.2?true just_joined:flags.4?true versioned:flags.5?true min:flags.8?true muted_by_you:flags.9?true volume_by_admin:flags.10?true self:flags.12?true video_joined:flags.15?true peer:Peer date:int active_date:flags.3?int source:int volume:flags.7?int about:flags.11?string raise_hand_rating:flags.13?long video:flags.6?GroupCallParticipantVideo presentation:flags.14?GroupCallParticipantVideo = GroupCallParticipant;\nphone.groupCall#9e727aad call:GroupCall participants:Vector participants_next_offset:string chats:Vector users:Vector = phone.GroupCall;\nphone.groupParticipants#f47751b6 count:int participants:Vector next_offset:string chats:Vector users:Vector version:int = phone.GroupParticipants;\ninlineQueryPeerTypeSameBotPM#3081ed9d = InlineQueryPeerType;\ninlineQueryPeerTypePM#833c0fac = InlineQueryPeerType;\ninlineQueryPeerTypeChat#d766c50a = InlineQueryPeerType;\ninlineQueryPeerTypeMegagroup#5ec4be43 = InlineQueryPeerType;\ninlineQueryPeerTypeBroadcast#6334ee9a = InlineQueryPeerType;\nmessages.historyImport#1662af0b id:long = messages.HistoryImport;\nmessages.historyImportParsed#5e0fb7b9 flags:# pm:flags.0?true group:flags.1?true title:flags.2?string = messages.HistoryImportParsed;\nmessages.affectedFoundMessages#ef8d3e6c pts:int pts_count:int offset:int messages:Vector = messages.AffectedFoundMessages;\nchatInviteImporter#8c5adfd9 flags:# requested:flags.0?true user_id:long date:int about:flags.2?string approved_by:flags.1?long = ChatInviteImporter;\nmessages.exportedChatInvites#bdc62dcc count:int invites:Vector users:Vector = messages.ExportedChatInvites;\nmessages.exportedChatInvite#1871be50 invite:ExportedChatInvite users:Vector = messages.ExportedChatInvite;\nmessages.exportedChatInviteReplaced#222600ef invite:ExportedChatInvite new_invite:ExportedChatInvite users:Vector = messages.ExportedChatInvite;\nmessages.chatInviteImporters#81b6b00a count:int importers:Vector users:Vector = messages.ChatInviteImporters;\nchatAdminWithInvites#f2ecef23 admin_id:long invites_count:int revoked_invites_count:int = ChatAdminWithInvites;\nmessages.chatAdminsWithInvites#b69b72d7 admins:Vector users:Vector = messages.ChatAdminsWithInvites;\nmessages.checkedHistoryImportPeer#a24de717 confirm_text:string = messages.CheckedHistoryImportPeer;\nphone.joinAsPeers#afe5623f peers:Vector chats:Vector users:Vector = phone.JoinAsPeers;\nphone.exportedGroupCallInvite#204bd158 link:string = phone.ExportedGroupCallInvite;\ngroupCallParticipantVideoSourceGroup#dcb118b7 semantics:string sources:Vector = GroupCallParticipantVideoSourceGroup;\ngroupCallParticipantVideo#67753ac8 flags:# paused:flags.0?true endpoint:string source_groups:Vector audio_source:flags.1?int = GroupCallParticipantVideo;\nstickers.suggestedShortName#85fea03f short_name:string = stickers.SuggestedShortName;\nbotCommandScopeDefault#2f6cb2ab = BotCommandScope;\nbotCommandScopeUsers#3c4f04d8 = BotCommandScope;\nbotCommandScopeChats#6fe1a881 = BotCommandScope;\nbotCommandScopeChatAdmins#b9aa606a = BotCommandScope;\nbotCommandScopePeer#db9d897d peer:InputPeer = BotCommandScope;\nbotCommandScopePeerAdmins#3fd863d1 peer:InputPeer = BotCommandScope;\nbotCommandScopePeerUser#a1321f3 peer:InputPeer user_id:InputUser = BotCommandScope;\naccount.resetPasswordFailedWait#e3779861 retry_date:int = account.ResetPasswordResult;\naccount.resetPasswordRequestedWait#e9effc7d until_date:int = account.ResetPasswordResult;\naccount.resetPasswordOk#e926d63e = account.ResetPasswordResult;\nsponsoredMessage#3a836df8 flags:# random_id:bytes from_id:flags.3?Peer chat_invite:flags.4?ChatInvite chat_invite_hash:flags.4?string channel_post:flags.2?int start_param:flags.0?string message:string entities:flags.1?Vector = SponsoredMessage;\nmessages.sponsoredMessages#65a4c7d5 messages:Vector chats:Vector users:Vector = messages.SponsoredMessages;\nsearchResultsCalendarPeriod#c9b0539f date:int min_msg_id:int max_msg_id:int count:int = SearchResultsCalendarPeriod;\nmessages.searchResultsCalendar#147ee23c flags:# inexact:flags.0?true count:int min_date:int min_msg_id:int offset_id_offset:flags.1?int periods:Vector messages:Vector chats:Vector users:Vector = messages.SearchResultsCalendar;\nsearchResultPosition#7f648b67 msg_id:int date:int offset:int = SearchResultsPosition;\nmessages.searchResultsPositions#53b22baf count:int positions:Vector = messages.SearchResultsPositions;\nchannels.sendAsPeers#8356cda9 peers:Vector chats:Vector users:Vector = channels.SendAsPeers;\nusers.userFull#3b6d152e full_user:UserFull chats:Vector users:Vector = users.UserFull;\nmessages.peerSettings#6880b94d settings:PeerSettings chats:Vector users:Vector = messages.PeerSettings;\nauth.loggedOut#c3a2835f flags:# future_auth_token:flags.0?bytes = auth.LoggedOut;\nreactionCount#6fb250d1 flags:# chosen:flags.0?true reaction:string count:int = ReactionCount;\nmessageReactions#87b6e36 flags:# min:flags.0?true can_see_list:flags.2?true results:Vector recent_reactons:flags.1?Vector = MessageReactions;\nmessageUserReaction#932844fa user_id:long reaction:string = MessageUserReaction;\nmessages.messageReactionsList#a366923c flags:# count:int reactions:Vector users:Vector next_offset:flags.0?string = messages.MessageReactionsList;\navailableReaction#21d7c4b flags:# inactive:flags.0?true reaction:string title:string static_icon:Document appear_animation:Document select_animation:Document activate_animation:Document effect_animation:Document = AvailableReaction;\nmessages.availableReactionsNotModified#9f071957 = messages.AvailableReactions;\nmessages.availableReactions#768e3aad hash:int reactions:Vector = messages.AvailableReactions;\n---functions---\ninitConnection#c1cd5ea9 {X:Type} flags:# api_id:int device_model:string system_version:string app_version:string system_lang_code:string lang_pack:string lang_code:string proxy:flags.0?InputClientProxy params:flags.1?JSONValue query:!X = X;\ninvokeWithLayer#da9b0d0d {X:Type} layer:int query:!X = X;\nauth.sendCode#a677244f phone_number:string api_id:int api_hash:string settings:CodeSettings = auth.SentCode;\nauth.signUp#80eee427 phone_number:string phone_code_hash:string first_name:string last_name:string = auth.Authorization;\nauth.signIn#bcd51581 phone_number:string phone_code_hash:string phone_code:string = auth.Authorization;\nauth.logOut#3e72ba19 = auth.LoggedOut;\nauth.resetAuthorizations#9fab0d1a = Bool;\nauth.exportAuthorization#e5bfffcd dc_id:int = auth.ExportedAuthorization;\nauth.importAuthorization#a57a7dad id:long bytes:bytes = auth.Authorization;\nauth.bindTempAuthKey#cdd42a05 perm_auth_key_id:long nonce:long expires_at:int encrypted_message:bytes = Bool;\nauth.checkPassword#d18b4d16 password:InputCheckPasswordSRP = auth.Authorization;\nauth.requestPasswordRecovery#d897bc66 = auth.PasswordRecovery;\nauth.resendCode#3ef1a9bf phone_number:string phone_code_hash:string = auth.SentCode;\nauth.cancelCode#1f040578 phone_number:string phone_code_hash:string = Bool;\nauth.dropTempAuthKeys#8e48a188 except_auth_keys:Vector = Bool;\nauth.exportLoginToken#b7e085fe api_id:int api_hash:string except_ids:Vector = auth.LoginToken;\nauth.importLoginToken#95ac5ce4 token:bytes = auth.LoginToken;\naccount.registerDevice#ec86017a flags:# no_muted:flags.0?true token_type:int token:string app_sandbox:Bool secret:bytes other_uids:Vector = Bool;\naccount.unregisterDevice#6a0d3206 token_type:int token:string other_uids:Vector = Bool;\naccount.updateNotifySettings#84be5b93 peer:InputNotifyPeer settings:InputPeerNotifySettings = Bool;\naccount.getNotifySettings#12b3ad31 peer:InputNotifyPeer = PeerNotifySettings;\naccount.updateProfile#78515775 flags:# first_name:flags.0?string last_name:flags.1?string about:flags.2?string = User;\naccount.updateStatus#6628562c offline:Bool = Bool;\naccount.getWallPapers#7967d36 hash:long = account.WallPapers;\naccount.checkUsername#2714d86c username:string = Bool;\naccount.updateUsername#3e0bdd7c username:string = User;\naccount.getPrivacy#dadbc950 key:InputPrivacyKey = account.PrivacyRules;\naccount.setPrivacy#c9f81ce8 key:InputPrivacyKey rules:Vector = account.PrivacyRules;\naccount.getAuthorizations#e320c158 = account.Authorizations;\naccount.resetAuthorization#df77f3bc hash:long = Bool;\naccount.getPassword#548a30f5 = account.Password;\naccount.getPasswordSettings#9cd4eaf9 password:InputCheckPasswordSRP = account.PasswordSettings;\naccount.updatePasswordSettings#a59b102f password:InputCheckPasswordSRP new_settings:account.PasswordInputSettings = Bool;\naccount.sendConfirmPhoneCode#1b3faa88 hash:string settings:CodeSettings = auth.SentCode;\naccount.confirmPhone#5f2178c3 phone_code_hash:string phone_code:string = Bool;\naccount.getTmpPassword#449e0b51 password:InputCheckPasswordSRP period:int = account.TmpPassword;\naccount.sendVerifyPhoneCode#a5a356f9 phone_number:string settings:CodeSettings = auth.SentCode;\naccount.confirmPasswordEmail#8fdf1920 code:string = Bool;\naccount.getContactSignUpNotification#9f07c728 = Bool;\naccount.setContactSignUpNotification#cff43f61 silent:Bool = Bool;\naccount.getNotifyExceptions#53577479 flags:# compare_sound:flags.1?true peer:flags.0?InputNotifyPeer = Updates;\naccount.uploadWallPaper#dd853661 file:InputFile mime_type:string settings:WallPaperSettings = WallPaper;\naccount.setContentSettings#b574b16b flags:# sensitive_enabled:flags.0?true = Bool;\naccount.getContentSettings#8b9b4dae = account.ContentSettings;\nusers.getUsers#d91a548 id:Vector = Vector;\nusers.getFullUser#b60f5918 id:InputUser = users.UserFull;\ncontacts.getContacts#5dd69e12 hash:long = contacts.Contacts;\ncontacts.importContacts#2c800be5 contacts:Vector = contacts.ImportedContacts;\ncontacts.deleteContacts#96a0e00 id:Vector = Updates;\ncontacts.block#68cc1411 id:InputPeer = Bool;\ncontacts.unblock#bea65d50 id:InputPeer = Bool;\ncontacts.getBlocked#f57c350f offset:int limit:int = contacts.Blocked;\ncontacts.search#11f812d8 q:string limit:int = contacts.Found;\ncontacts.resolveUsername#f93ccba3 username:string = contacts.ResolvedPeer;\ncontacts.getTopPeers#973478b6 flags:# correspondents:flags.0?true bots_pm:flags.1?true bots_inline:flags.2?true phone_calls:flags.3?true forward_users:flags.4?true forward_chats:flags.5?true groups:flags.10?true channels:flags.15?true offset:int limit:int hash:long = contacts.TopPeers;\ncontacts.addContact#e8f463d0 flags:# add_phone_privacy_exception:flags.0?true id:InputUser first_name:string last_name:string phone:string = Updates;\nmessages.getMessages#63c66506 id:Vector = messages.Messages;\nmessages.getDialogs#a0f4cb4f flags:# exclude_pinned:flags.0?true folder_id:flags.1?int offset_date:int offset_id:int offset_peer:InputPeer limit:int hash:long = messages.Dialogs;\nmessages.getHistory#4423e6c5 peer:InputPeer offset_id:int offset_date:int add_offset:int limit:int max_id:int min_id:int hash:long = messages.Messages;\nmessages.search#a0fda762 flags:# peer:InputPeer q:string from_id:flags.0?InputPeer top_msg_id:flags.1?int filter:MessagesFilter min_date:int max_date:int offset_id:int add_offset:int limit:int max_id:int min_id:int hash:long = messages.Messages;\nmessages.readHistory#e306d3a peer:InputPeer max_id:int = messages.AffectedMessages;\nmessages.deleteHistory#b08f922a flags:# just_clear:flags.0?true revoke:flags.1?true peer:InputPeer max_id:int min_date:flags.2?int max_date:flags.3?int = messages.AffectedHistory;\nmessages.deleteMessages#e58e95d2 flags:# revoke:flags.0?true id:Vector = messages.AffectedMessages;\nmessages.receivedMessages#5a954c0 max_id:int = Vector;\nmessages.setTyping#58943ee2 flags:# peer:InputPeer top_msg_id:flags.0?int action:SendMessageAction = Bool;\nmessages.sendMessage#d9d75a4 flags:# no_webpage:flags.1?true silent:flags.5?true background:flags.6?true clear_draft:flags.7?true noforwards:flags.14?true peer:InputPeer reply_to_msg_id:flags.0?int message:string random_id:long reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector schedule_date:flags.10?int send_as:flags.13?InputPeer = Updates;\nmessages.sendMedia#e25ff8e0 flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true noforwards:flags.14?true peer:InputPeer reply_to_msg_id:flags.0?int media:InputMedia message:string random_id:long reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector schedule_date:flags.10?int send_as:flags.13?InputPeer = Updates;\nmessages.forwardMessages#cc30290b flags:# silent:flags.5?true background:flags.6?true with_my_score:flags.8?true drop_author:flags.11?true drop_media_captions:flags.12?true noforwards:flags.14?true from_peer:InputPeer id:Vector random_id:Vector to_peer:InputPeer schedule_date:flags.10?int send_as:flags.13?InputPeer = Updates;\nmessages.report#8953ab4e peer:InputPeer id:Vector reason:ReportReason message:string = Bool;\nmessages.getChats#49e9528f id:Vector = messages.Chats;\nmessages.getFullChat#aeb00b34 chat_id:long = messages.ChatFull;\nmessages.editChatTitle#73783ffd chat_id:long title:string = Updates;\nmessages.editChatPhoto#35ddd674 chat_id:long photo:InputChatPhoto = Updates;\nmessages.addChatUser#f24753e3 chat_id:long user_id:InputUser fwd_limit:int = Updates;\nmessages.deleteChatUser#a2185cab flags:# revoke_history:flags.0?true chat_id:long user_id:InputUser = Updates;\nmessages.createChat#9cb126e users:Vector title:string = Updates;\nmessages.getDhConfig#26cf8950 version:int random_length:int = messages.DhConfig;\nmessages.readMessageContents#36a73f77 id:Vector = messages.AffectedMessages;\nmessages.getStickers#d5a5d3a1 emoticon:string hash:long = messages.Stickers;\nmessages.getAllStickers#b8a0a1a8 hash:long = messages.AllStickers;\nmessages.getWebPagePreview#8b68b0cc flags:# message:string entities:flags.3?Vector = MessageMedia;\nmessages.exportChatInvite#a02ce5d5 flags:# legacy_revoke_permanent:flags.2?true request_needed:flags.3?true peer:InputPeer expire_date:flags.0?int usage_limit:flags.1?int title:flags.4?string = ExportedChatInvite;\nmessages.checkChatInvite#3eadb1bb hash:string = ChatInvite;\nmessages.importChatInvite#6c50051c hash:string = Updates;\nmessages.getStickerSet#c8a0ec74 stickerset:InputStickerSet hash:int = messages.StickerSet;\nmessages.installStickerSet#c78fe460 stickerset:InputStickerSet archived:Bool = messages.StickerSetInstallResult;\nmessages.uninstallStickerSet#f96e55de stickerset:InputStickerSet = Bool;\nmessages.startBot#e6df7378 bot:InputUser peer:InputPeer random_id:long start_param:string = Updates;\nmessages.migrateChat#a2875319 chat_id:long = Updates;\nmessages.searchGlobal#4bc6589a flags:# folder_id:flags.0?int q:string filter:MessagesFilter min_date:int max_date:int offset_rate:int offset_peer:InputPeer offset_id:int limit:int = messages.Messages;\nmessages.getDocumentByHash#338e2464 sha256:bytes size:int mime_type:string = Document;\nmessages.getSavedGifs#5cf09635 hash:long = messages.SavedGifs;\nmessages.getInlineBotResults#514e999d flags:# bot:InputUser peer:InputPeer geo_point:flags.0?InputGeoPoint query:string offset:string = messages.BotResults;\nmessages.sendInlineBotResult#7aa11297 flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true hide_via:flags.11?true peer:InputPeer reply_to_msg_id:flags.0?int random_id:long query_id:long id:string schedule_date:flags.10?int send_as:flags.13?InputPeer = Updates;\nmessages.editMessage#48f71778 flags:# no_webpage:flags.1?true peer:InputPeer id:int message:flags.11?string media:flags.14?InputMedia reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector schedule_date:flags.15?int = Updates;\nmessages.getBotCallbackAnswer#9342ca07 flags:# game:flags.1?true peer:InputPeer msg_id:int data:flags.0?bytes password:flags.2?InputCheckPasswordSRP = messages.BotCallbackAnswer;\nmessages.getPeerDialogs#e470bcfd peers:Vector = messages.PeerDialogs;\nmessages.saveDraft#bc39e14b flags:# no_webpage:flags.1?true reply_to_msg_id:flags.0?int peer:InputPeer message:string entities:flags.3?Vector = Bool;\nmessages.getFeaturedStickers#64780b14 hash:long = messages.FeaturedStickers;\nmessages.readFeaturedStickers#5b118126 id:Vector = Bool;\nmessages.getRecentStickers#9da9403b flags:# attached:flags.0?true hash:long = messages.RecentStickers;\nmessages.getCommonChats#e40ca104 user_id:InputUser max_id:long limit:int = messages.Chats;\nmessages.getWebPage#32ca8f91 url:string hash:int = WebPage;\nmessages.toggleDialogPin#a731e257 flags:# pinned:flags.0?true peer:InputDialogPeer = Bool;\nmessages.getPinnedDialogs#d6b94df2 folder_id:int = messages.PeerDialogs;\nmessages.uploadMedia#519bc2b1 peer:InputPeer media:InputMedia = MessageMedia;\nmessages.getFavedStickers#4f1aaa9 hash:long = messages.FavedStickers;\nmessages.faveSticker#b9ffc55b id:InputDocument unfave:Bool = Bool;\nmessages.sendMultiMedia#f803138f flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true noforwards:flags.14?true peer:InputPeer reply_to_msg_id:flags.0?int multi_media:Vector schedule_date:flags.10?int send_as:flags.13?InputPeer = Updates;\nmessages.searchStickerSets#35705b8a flags:# exclude_featured:flags.0?true q:string hash:long = messages.FoundStickerSets;\nmessages.markDialogUnread#c286d98f flags:# unread:flags.0?true peer:InputDialogPeer = Bool;\nmessages.updatePinnedMessage#d2aaf7ec flags:# silent:flags.0?true unpin:flags.1?true pm_oneside:flags.2?true peer:InputPeer id:int = Updates;\nmessages.sendVote#10ea6184 peer:InputPeer msg_id:int options:Vector = Updates;\nmessages.getOnlines#6e2be050 peer:InputPeer = ChatOnlines;\nmessages.editChatAbout#def60797 peer:InputPeer about:string = Bool;\nmessages.editChatDefaultBannedRights#a5866b41 peer:InputPeer banned_rights:ChatBannedRights = Updates;\nmessages.getEmojiKeywordsDifference#1508b6af lang_code:string from_version:int = EmojiKeywordsDifference;\nmessages.getScheduledHistory#f516760b peer:InputPeer hash:long = messages.Messages;\nmessages.sendScheduledMessages#bd38850a peer:InputPeer id:Vector = Updates;\nmessages.deleteScheduledMessages#59ae2b16 peer:InputPeer id:Vector = Updates;\nmessages.getPollVotes#b86e380e flags:# peer:InputPeer id:int option:flags.0?bytes offset:flags.1?string limit:int = messages.VotesList;\nmessages.getDialogFilters#f19ed96d = Vector;\nmessages.getSuggestedDialogFilters#a29cd42c = Vector;\nmessages.updateDialogFilter#1ad4a04a flags:# id:int filter:flags.0?DialogFilter = Bool;\nmessages.getReplies#22ddd30c peer:InputPeer msg_id:int offset_id:int offset_date:int add_offset:int limit:int max_id:int min_id:int hash:long = messages.Messages;\nmessages.getDiscussionMessage#446972fd peer:InputPeer msg_id:int = messages.DiscussionMessage;\nmessages.readDiscussion#f731a9f4 peer:InputPeer msg_id:int read_max_id:int = Bool;\nmessages.unpinAllMessages#f025bc8b peer:InputPeer = messages.AffectedHistory;\nmessages.deleteChat#5bd0ee50 chat_id:long = Bool;\nmessages.getMessageReadParticipants#2c6f97b7 peer:InputPeer msg_id:int = Vector;\nmessages.toggleNoForwards#b11eafa2 peer:InputPeer enabled:Bool = Updates;\nmessages.saveDefaultSendAs#ccfddf96 peer:InputPeer send_as:InputPeer = Bool;\nupdates.getState#edd4882a = updates.State;\nupdates.getDifference#25939651 flags:# pts:int pts_total_limit:flags.0?int date:int qts:int = updates.Difference;\nupdates.getChannelDifference#3173d78 flags:# force:flags.0?true channel:InputChannel filter:ChannelMessagesFilter pts:int limit:int = updates.ChannelDifference;\nphotos.uploadProfilePhoto#89f30f69 flags:# file:flags.0?InputFile video:flags.1?InputFile video_start_ts:flags.2?double = photos.Photo;\nphotos.getUserPhotos#91cd32a8 user_id:InputUser offset:int max_id:long limit:int = photos.Photos;\nupload.saveFilePart#b304a621 file_id:long file_part:int bytes:bytes = Bool;\nupload.getFile#b15a9afc flags:# precise:flags.0?true cdn_supported:flags.1?true location:InputFileLocation offset:int limit:int = upload.File;\nupload.saveBigFilePart#de7b673d file_id:long file_part:int file_total_parts:int bytes:bytes = Bool;\nupload.getWebFile#24e6818d location:InputWebFileLocation offset:int limit:int = upload.WebFile;\nhelp.getConfig#c4f9186b = Config;\nhelp.getNearestDc#1fb33026 = NearestDc;\nhelp.getSupport#9cdf08cd = help.Support;\nhelp.acceptTermsOfService#ee72f79a id:DataJSON = Bool;\nhelp.getCountriesList#735787a8 lang_code:string hash:int = help.CountriesList;\nchannels.readHistory#cc104937 channel:InputChannel max_id:int = Bool;\nchannels.deleteMessages#84c1fd4e channel:InputChannel id:Vector = messages.AffectedMessages;\nchannels.getMessages#ad8c9a23 channel:InputChannel id:Vector = messages.Messages;\nchannels.getParticipants#77ced9d0 channel:InputChannel filter:ChannelParticipantsFilter offset:int limit:int hash:long = channels.ChannelParticipants;\nchannels.getParticipant#a0ab6cc6 channel:InputChannel participant:InputPeer = channels.ChannelParticipant;\nchannels.getChannels#a7f6bbb id:Vector = messages.Chats;\nchannels.getFullChannel#8736a09 channel:InputChannel = messages.ChatFull;\nchannels.createChannel#3d5fb10f flags:# broadcast:flags.0?true megagroup:flags.1?true for_import:flags.3?true title:string about:string geo_point:flags.2?InputGeoPoint address:flags.2?string = Updates;\nchannels.editAdmin#d33c8902 channel:InputChannel user_id:InputUser admin_rights:ChatAdminRights rank:string = Updates;\nchannels.editTitle#566decd0 channel:InputChannel title:string = Updates;\nchannels.editPhoto#f12e57c9 channel:InputChannel photo:InputChatPhoto = Updates;\nchannels.checkUsername#10e6bd2c channel:InputChannel username:string = Bool;\nchannels.updateUsername#3514b3de channel:InputChannel username:string = Bool;\nchannels.joinChannel#24b524c5 channel:InputChannel = Updates;\nchannels.leaveChannel#f836aa95 channel:InputChannel = Updates;\nchannels.inviteToChannel#199f3a6c channel:InputChannel users:Vector = Updates;\nchannels.deleteChannel#c0111fe3 channel:InputChannel = Updates;\nchannels.toggleSignatures#1f69b606 channel:InputChannel enabled:Bool = Updates;\nchannels.editBanned#96e6cd81 channel:InputChannel participant:InputPeer banned_rights:ChatBannedRights = Updates;\nchannels.readMessageContents#eab5dc38 channel:InputChannel id:Vector = Bool;\nchannels.togglePreHistoryHidden#eabbb94c channel:InputChannel enabled:Bool = Updates;\nchannels.getGroupsForDiscussion#f5dad378 = messages.Chats;\nchannels.setDiscussionGroup#40582bb2 broadcast:InputChannel group:InputChannel = Bool;\nchannels.viewSponsoredMessage#beaedb94 channel:InputChannel random_id:bytes = Bool;\nchannels.getSponsoredMessages#ec210fbf channel:InputChannel = messages.SponsoredMessages;\nchannels.getSendAs#dc770ee peer:InputPeer = channels.SendAsPeers;\npayments.getPaymentForm#8a333c8d flags:# peer:InputPeer msg_id:int theme_params:flags.0?DataJSON = payments.PaymentForm;\npayments.getPaymentReceipt#2478d1cc peer:InputPeer msg_id:int = payments.PaymentReceipt;\npayments.validateRequestedInfo#db103170 flags:# save:flags.0?true peer:InputPeer msg_id:int info:PaymentRequestedInfo = payments.ValidatedRequestedInfo;\npayments.sendPaymentForm#30c3bc9d flags:# form_id:long peer:InputPeer msg_id:int requested_info_id:flags.0?string shipping_option_id:flags.1?string credentials:InputPaymentCredentials tip_amount:flags.2?long = payments.PaymentResult;\npayments.getSavedInfo#227d824b = payments.SavedInfo;\nphone.createGroupCall#48cdc6d8 flags:# peer:InputPeer random_id:int title:flags.0?string schedule_date:flags.1?int = Updates;\nphone.joinGroupCall#b132ff7b flags:# muted:flags.0?true video_stopped:flags.2?true call:InputGroupCall join_as:InputPeer invite_hash:flags.1?string params:DataJSON = Updates;\nphone.leaveGroupCall#500377f9 call:InputGroupCall source:int = Updates;\nphone.discardGroupCall#7a777135 call:InputGroupCall = Updates;\nphone.getGroupCall#41845db call:InputGroupCall limit:int = phone.GroupCall;\nphone.getGroupParticipants#c558d8ab call:InputGroupCall ids:Vector sources:Vector offset:string limit:int = phone.GroupParticipants;\nphone.editGroupCallParticipant#a5273abf flags:# call:InputGroupCall participant:InputPeer muted:flags.0?Bool volume:flags.1?int raise_hand:flags.2?Bool video_stopped:flags.3?Bool video_paused:flags.4?Bool presentation_paused:flags.5?Bool = Updates;\nphone.exportGroupCallInvite#e6aa647f flags:# can_self_unmute:flags.0?true call:InputGroupCall = phone.ExportedGroupCallInvite;\nphone.toggleGroupCallStartSubscription#219c34e6 call:InputGroupCall subscribed:Bool = Updates;\nphone.joinGroupCallPresentation#cbea6bc4 call:InputGroupCall params:DataJSON = Updates;\nphone.leaveGroupCallPresentation#1c50d144 call:InputGroupCall = Updates;\nlangpack.getLangPack#f2f2330a lang_pack:string lang_code:string = LangPackDifference;\nlangpack.getStrings#efea3803 lang_pack:string lang_code:string keys:Vector = Vector;\nlangpack.getLanguages#42c6978f lang_pack:string = Vector;\nfolders.editPeerFolders#6847d0ab folder_peers:Vector = Updates;`;","const { inflate } = require('pako/dist/pako_inflate');\nconst { serializeBytes } = require('../index');\n\n// CONTEST const { deflate } = require('pako/dist/pako_deflate')\n\nclass GZIPPacked {\n static CONSTRUCTOR_ID = 0x3072cfa1;\n\n static classType = 'constructor';\n\n constructor(data) {\n this.data = data;\n this.CONSTRUCTOR_ID = 0x3072cfa1;\n this.classType = 'constructor';\n }\n\n static async gzipIfSmaller(contentRelated, data) {\n if (contentRelated && data.length > 512) {\n const gzipped = await (new GZIPPacked(data)).toBytes();\n if (gzipped.length < data.length) {\n return gzipped;\n }\n }\n return data;\n }\n\n static gzip(input) {\n return Buffer.from(input);\n // TODO this usually makes it faster for large requests\n // return Buffer.from(deflate(input, { level: 9, gzip: true }))\n }\n\n static ungzip(input) {\n return Buffer.from(inflate(input));\n }\n\n static read(reader) {\n const constructor = reader.readInt(false);\n if (constructor !== GZIPPacked.CONSTRUCTOR_ID) {\n throw new Error('not equal');\n }\n return GZIPPacked.gzip(reader.tgReadBytes());\n }\n\n static async fromReader(reader) {\n return new GZIPPacked(await GZIPPacked.ungzip(reader.tgReadBytes()));\n }\n\n async toBytes() {\n const g = Buffer.alloc(4);\n g.writeUInt32LE(GZIPPacked.CONSTRUCTOR_ID, 0);\n return Buffer.concat([\n g,\n serializeBytes(await GZIPPacked.gzip(this.data)),\n ]);\n }\n}\n\nmodule.exports = GZIPPacked;\n","const TLMessage = require('./TLMessage');\n\nclass MessageContainer {\n static CONSTRUCTOR_ID = 0x73f1f8dc;\n\n static classType = 'constructor';\n\n // Maximum size in bytes for the inner payload of the container.\n // Telegram will close the connection if the payload is bigger.\n // The overhead of the container itself is subtracted.\n static MAXIMUM_SIZE = 1044456 - 8;\n\n // Maximum amount of messages that can't be sent inside a single\n // container, inclusive. Beyond this limit Telegram will respond\n // with BAD_MESSAGE 64 (invalid container).\n //\n // This limit is not 100% accurate and may in some cases be higher.\n // However, sending up to 100 requests at once in a single container\n // is a reasonable conservative value, since it could also depend on\n // other factors like size per request, but we cannot know this.\n static MAXIMUM_LENGTH = 100;\n\n constructor(messages) {\n this.CONSTRUCTOR_ID = 0x73f1f8dc;\n this.messages = messages;\n this.classType = 'constructor';\n }\n\n static fromReader(reader) {\n const messages = [];\n const length = reader.readInt();\n for (let x = 0; x < length; x++) {\n const msgId = reader.readLong();\n const seqNo = reader.readInt();\n const containerLength = reader.readInt();\n const before = reader.tellPosition();\n const obj = reader.tgReadObject();\n reader.setPosition(before + containerLength);\n const tlMessage = new TLMessage(msgId, seqNo, obj);\n messages.push(tlMessage);\n }\n return new MessageContainer(messages);\n }\n}\n\nmodule.exports = MessageContainer;\n","const { RpcError } = require('../index').constructors;\nconst GZIPPacked = require('./GZIPPacked');\n\nclass RPCResult {\n static CONSTRUCTOR_ID = 0xf35c6d01;\n\n static classType = 'constructor';\n\n constructor(reqMsgId, body, error) {\n this.CONSTRUCTOR_ID = 0xf35c6d01;\n this.reqMsgId = reqMsgId;\n this.body = body;\n this.error = error;\n this.classType = 'constructor';\n }\n\n static async fromReader(reader) {\n const msgId = reader.readLong();\n const innerCode = reader.readInt(false);\n if (innerCode === RpcError.CONSTRUCTOR_ID) {\n return new RPCResult(msgId, undefined, RpcError.fromReader(reader));\n }\n if (innerCode === GZIPPacked.CONSTRUCTOR_ID) {\n return new RPCResult(msgId, (await GZIPPacked.fromReader(reader)).data);\n }\n reader.seek(-4);\n // This reader.read() will read more than necessary, but it's okay.\n // We could make use of MessageContainer's length here, but since\n // it's not necessary we don't need to care about it.\n return new RPCResult(msgId, reader.read(), undefined);\n }\n}\n\nmodule.exports = RPCResult;\n","class TLMessage {\n static SIZE_OVERHEAD = 12;\n\n static classType = 'constructor';\n\n constructor(msgId, seqNo, obj) {\n this.msgId = msgId;\n this.seqNo = seqNo;\n this.obj = obj;\n this.classType = 'constructor';\n }\n}\n\nmodule.exports = TLMessage;\n","const TLMessage = require('./TLMessage');\nconst RPCResult = require('./RPCResult');\nconst MessageContainer = require('./MessageContainer');\nconst GZIPPacked = require('./GZIPPacked');\n\nconst coreObjects = {\n [RPCResult.CONSTRUCTOR_ID]: RPCResult,\n [GZIPPacked.CONSTRUCTOR_ID]: GZIPPacked,\n [MessageContainer.CONSTRUCTOR_ID]: MessageContainer,\n};\n\nmodule.exports = {\n TLMessage,\n RPCResult,\n MessageContainer,\n GZIPPacked,\n coreObjects,\n};\n","const snakeToCamelCase = (name) => {\n const result = name.replace(/(?:^|_)([a-z])/g, (_, g) => g.toUpperCase());\n return result.replace(/_/g, '');\n};\nconst variableSnakeToCamelCase = (str) => str.replace(\n /([-_][a-z])/g,\n (group) => group.toUpperCase()\n .replace('-', '')\n .replace('_', ''),\n);\n\nconst CORE_TYPES = new Set([\n 0xbc799737, // boolFalse#bc799737 = Bool;\n 0x997275b5, // boolTrue#997275b5 = Bool;\n 0x3fedd339, // true#3fedd339 = True;\n 0xc4b9f9bb, // error#c4b9f9bb code:int text:string = Error;\n 0x56730bcc, // null#56730bcc = Null;\n]);\nconst AUTH_KEY_TYPES = new Set([\n 0x05162463, // resPQ,\n 0x83c95aec, // p_q_inner_data\n 0xa9f55f95, // p_q_inner_data_dc\n 0x3c6a84d4, // p_q_inner_data_temp\n 0x56fddf88, // p_q_inner_data_temp_dc\n 0xd0e8075c, // server_DH_params_ok\n 0xb5890dba, // server_DH_inner_data\n 0x6643b654, // client_DH_inner_data\n 0xd712e4be, // req_DH_params\n 0xf5045f1f, // set_client_DH_params\n 0x3072cfa1, // gzip_packed\n]);\n\n// This is copy-pasted from `gramjs/Helpers.js` to not depend on TypeScript modules\nfunction makeCRCTable() {\n let c;\n const crcTable = [];\n for (let n = 0; n < 256; n++) {\n c = n;\n for (let k = 0; k < 8; k++) {\n c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));\n }\n crcTable[n] = c;\n }\n return crcTable;\n}\n\nlet crcTable;\n\nfunction crc32(buf) {\n if (!crcTable) {\n crcTable = makeCRCTable();\n }\n if (!Buffer.isBuffer(buf)) {\n buf = Buffer.from(buf);\n }\n let crc = -1;\n\n for (let index = 0; index < buf.length; index++) {\n const byte = buf[index];\n crc = crcTable[(crc ^ byte) & 0xff] ^ (crc >>> 8);\n }\n return (crc ^ (-1)) >>> 0;\n}\n\nconst findAll = (regex, str, matches = []) => {\n if (!regex.flags.includes('g')) {\n regex = new RegExp(regex.source, 'g');\n }\n\n const res = regex.exec(str);\n\n if (res) {\n matches.push(res.slice(1));\n findAll(regex, str, matches);\n }\n\n return matches;\n};\n\nconst fromLine = (line, isFunction) => {\n const match = line.match(/([\\w.]+)(?:#([0-9a-fA-F]+))?(?:\\s{?\\w+:[\\w\\d<>#.?!]+}?)*\\s=\\s([\\w\\d<>#.?]+);$/);\n if (!match) {\n // Probably \"vector#1cb5c415 {t:Type} # [ t ] = Vector t;\"\n throw new Error(`Cannot parse TLObject ${line}`);\n }\n\n const argsMatch = findAll(/({)?(\\w+):([\\w\\d<>#.?!]+)}?/, line);\n const currentConfig = {\n name: match[1],\n constructorId: parseInt(match[2], 16),\n argsConfig: {},\n subclassOfId: crc32(match[3]),\n result: match[3],\n isFunction,\n namespace: undefined,\n };\n if (!currentConfig.constructorId) {\n const hexId = '';\n let args;\n\n if (Object.values(currentConfig.argsConfig).length) {\n args = ` ${Object.keys(currentConfig.argsConfig)\n .map((arg) => arg.toString())\n .join(' ')}`;\n } else {\n args = '';\n }\n\n const representation = `${currentConfig.name}${hexId}${args} = ${currentConfig.result}`\n .replace(/(:|\\?)bytes /g, '$1string ')\n .replace(/|{|}/g, '')\n .replace(/ \\w+:flags\\.\\d+\\?true/g, '');\n\n if (currentConfig.name === 'inputMediaInvoice') {\n // eslint-disable-next-line no-empty\n if (currentConfig.name === 'inputMediaInvoice') {\n }\n }\n\n currentConfig.constructorId = crc32(Buffer.from(representation, 'utf8'));\n }\n for (const [brace, name, argType] of argsMatch) {\n if (brace === undefined) {\n currentConfig.argsConfig[variableSnakeToCamelCase(name)] = buildArgConfig(name, argType);\n }\n }\n if (currentConfig.name.includes('.')) {\n [currentConfig.namespace, currentConfig.name] = currentConfig.name.split(/\\.(.+)/);\n }\n currentConfig.name = snakeToCamelCase(currentConfig.name);\n /*\n for (const arg in currentConfig.argsConfig){\n if (currentConfig.argsConfig.hasOwnProperty(arg)){\n if (currentConfig.argsConfig[arg].flagIndicator){\n delete currentConfig.argsConfig[arg]\n }\n }\n } */\n return currentConfig;\n};\n\nfunction buildArgConfig(name, argType) {\n name = name === 'self' ? 'is_self' : name;\n // Default values\n const currentConfig = {\n isVector: false,\n isFlag: false,\n skipConstructorId: false,\n flagIndex: -1,\n flagIndicator: true,\n type: undefined,\n useVectorId: undefined,\n };\n\n // The type can be an indicator that other arguments will be flags\n if (argType !== '#') {\n currentConfig.flagIndicator = false;\n // Strip the exclamation mark always to have only the name\n currentConfig.type = argType.replace(/^!+/, '');\n\n // The type may be a flag (flags.IDX?REAL_TYPE)\n // Note that 'flags' is NOT the flags name; this\n // is determined by a previous argument\n // However, we assume that the argument will always be called 'flags'\n // @ts-ignore\n const flagMatch = currentConfig.type.match(/flags.(\\d+)\\?([\\w<>.]+)/);\n\n if (flagMatch) {\n currentConfig.isFlag = true;\n currentConfig.flagIndex = Number(flagMatch[1]);\n // Update the type to match the exact type, not the \"flagged\" one\n [, , currentConfig.type] = flagMatch;\n }\n\n // Then check if the type is a Vector\n // @ts-ignore\n const vectorMatch = currentConfig.type.match(/[Vv]ector<([\\w\\d.]+)>/);\n\n if (vectorMatch) {\n currentConfig.isVector = true;\n\n // If the type's first letter is not uppercase, then\n // it is a constructor and we use (read/write) its ID.\n // @ts-ignore\n currentConfig.useVectorId = currentConfig.type.charAt(0) === 'V';\n\n // Update the type to match the one inside the vector\n [, currentConfig.type] = vectorMatch;\n }\n\n // See use_vector_id. An example of such case is ipPort in\n // help.configSpecial\n // @ts-ignore\n if (/^[a-z]$/.test(currentConfig.type.split('.')\n .pop()\n .charAt(0))\n ) {\n currentConfig.skipConstructorId = true;\n }\n\n // The name may contain \"date\" in it, if this is the case and\n // the type is \"int\", we can safely assume that this should be\n // treated as a \"date\" object. Note that this is not a valid\n // Telegram object, but it's easier to work with\n // if (\n // this.type === 'int' &&\n // (/(\\b|_)([dr]ate|until|since)(\\b|_)/.test(name) ||\n // ['expires', 'expires_at', 'was_online'].includes(name))\n // ) {\n // this.type = 'date';\n // }\n }\n return currentConfig;\n}\n\n\nfunction* parseTl(content, layer, methods = [], ignoreIds = CORE_TYPES) {\n (methods || []).reduce((o, m) => ({\n ...o,\n [m.name]: m,\n }), {});\n const objAll = [];\n const objByName = {};\n const objByType = {};\n\n const file = content;\n\n let isFunction = false;\n\n for (let line of file.split('\\n')) {\n const commentIndex = line.indexOf('//');\n\n if (commentIndex !== -1) {\n line = line.slice(0, commentIndex);\n }\n\n line = line.trim();\n\n if (!line) {\n continue;\n }\n\n const match = line.match(/---(\\w+)---/);\n\n if (match) {\n const [, followingTypes] = match;\n isFunction = followingTypes === 'functions';\n continue;\n }\n\n try {\n const result = fromLine(line, isFunction);\n\n if (ignoreIds.has(result.constructorId)) {\n continue;\n }\n\n objAll.push(result);\n\n if (!result.isFunction) {\n if (!objByType[result.result]) {\n objByType[result.result] = [];\n }\n\n objByName[result.name] = result;\n objByType[result.result].push(result);\n }\n } catch (e) {\n if (!e.toString()\n .includes('vector#1cb5c415')) {\n throw e;\n }\n }\n }\n\n // Once all objects have been parsed, replace the\n // string type from the arguments with references\n for (const obj of objAll) {\n // console.log(obj)\n if (AUTH_KEY_TYPES.has(obj.constructorId)) {\n for (const arg in obj.argsConfig) {\n if (obj.argsConfig[arg].type === 'string') {\n obj.argsConfig[arg].type = 'bytes';\n }\n }\n }\n }\n\n for (const obj of objAll) {\n yield obj;\n }\n}\n\nfunction serializeBytes(data) {\n if (!(data instanceof Buffer)) {\n if (typeof data === 'string') {\n data = Buffer.from(data);\n } else {\n throw Error(`Bytes or str expected, not ${data.constructor.name}`);\n }\n }\n const r = [];\n let padding;\n if (data.length < 254) {\n padding = (data.length + 1) % 4;\n if (padding !== 0) {\n padding = 4 - padding;\n }\n r.push(Buffer.from([data.length]));\n r.push(data);\n } else {\n padding = data.length % 4;\n if (padding !== 0) {\n padding = 4 - padding;\n }\n r.push(Buffer.from([254, data.length % 256, (data.length >> 8) % 256, (data.length >> 16) % 256]));\n r.push(data);\n }\n r.push(Buffer.alloc(padding)\n .fill(0));\n\n return Buffer.concat(r);\n}\n\nfunction serializeDate(dt) {\n if (!dt) {\n return Buffer.alloc(4)\n .fill(0);\n }\n if (dt instanceof Date) {\n dt = Math.floor((Date.now() - dt.getTime()) / 1000);\n }\n if (typeof dt === 'number') {\n const t = Buffer.alloc(4);\n t.writeInt32LE(dt, 0);\n return t;\n }\n throw Error(`Cannot interpret \"${dt}\" as a date`);\n}\n\nmodule.exports = {\n findAll,\n parseTl,\n buildArgConfig,\n fromLine,\n CORE_TYPES,\n serializeDate,\n serializeBytes,\n snakeToCamelCase,\n variableSnakeToCamelCase,\n};\n","const api = require('./api');\nconst {\n serializeBytes,\n serializeDate,\n} = require('./generationHelpers');\n\nmodule.exports = {\n // TODO Refactor internal usages to always use `api`.\n constructors: api,\n requests: api,\n serializeBytes,\n serializeDate,\n};\n","module.exports = `resPQ#05162463 nonce:int128 server_nonce:int128 pq:string server_public_key_fingerprints:Vector = ResPQ;\np_q_inner_data#83c95aec pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 = P_Q_inner_data;\np_q_inner_data_dc#a9f55f95 pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 dc:int = P_Q_inner_data;\np_q_inner_data_temp#3c6a84d4 pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 expires_in:int = P_Q_inner_data;\np_q_inner_data_temp_dc#56fddf88 pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 dc:int expires_in:int = P_Q_inner_data;\nserver_DH_params_fail#79cb045d nonce:int128 server_nonce:int128 new_nonce_hash:int128 = Server_DH_Params;\nserver_DH_params_ok#d0e8075c nonce:int128 server_nonce:int128 encrypted_answer:string = Server_DH_Params;\nserver_DH_inner_data#b5890dba nonce:int128 server_nonce:int128 g:int dh_prime:string g_a:string server_time:int = Server_DH_inner_data;\nclient_DH_inner_data#6643b654 nonce:int128 server_nonce:int128 retry_id:long g_b:string = Client_DH_Inner_Data;\ndh_gen_ok#3bcbf734 nonce:int128 server_nonce:int128 new_nonce_hash1:int128 = Set_client_DH_params_answer;\ndh_gen_retry#46dc1fb9 nonce:int128 server_nonce:int128 new_nonce_hash2:int128 = Set_client_DH_params_answer;\ndh_gen_fail#a69dae02 nonce:int128 server_nonce:int128 new_nonce_hash3:int128 = Set_client_DH_params_answer;\ndestroy_auth_key_ok#f660e1d4 = DestroyAuthKeyRes;\ndestroy_auth_key_none#0a9f2259 = DestroyAuthKeyRes;\ndestroy_auth_key_fail#ea109b13 = DestroyAuthKeyRes;\n---functions---\nreq_pq#60469778 nonce:int128 = ResPQ;\nreq_pq_multi#be7e8ef1 nonce:int128 = ResPQ;\nreq_pq_multi_new#51b410fd nonce:int128 = ResPQ;\nreq_DH_params#d712e4be nonce:int128 server_nonce:int128 p:string q:string public_key_fingerprint:long encrypted_data:string = Server_DH_Params;\nset_client_DH_params#f5045f1f nonce:int128 server_nonce:int128 encrypted_data:string = Set_client_DH_params_answer;\ndestroy_auth_key#d1435160 = DestroyAuthKeyRes;\n---types---\nmsgs_ack#62d6b459 msg_ids:Vector = MsgsAck;\nbad_msg_notification#a7eff811 bad_msg_id:long bad_msg_seqno:int error_code:int = BadMsgNotification;\nbad_server_salt#edab447b bad_msg_id:long bad_msg_seqno:int error_code:int new_server_salt:long = BadMsgNotification;\nmsgs_state_req#da69fb52 msg_ids:Vector = MsgsStateReq;\nmsgs_state_info#04deb57d req_msg_id:long info:string = MsgsStateInfo;\nmsgs_all_info#8cc0d131 msg_ids:Vector info:string = MsgsAllInfo;\nmsg_detailed_info#276d3ec6 msg_id:long answer_msg_id:long bytes:int status:int = MsgDetailedInfo;\nmsg_new_detailed_info#809db6df answer_msg_id:long bytes:int status:int = MsgDetailedInfo;\nmsg_resend_req#7d861a08 msg_ids:Vector = MsgResendReq;\nrpc_error#2144ca19 error_code:int error_message:string = RpcError;\nrpc_answer_unknown#5e2ad36e = RpcDropAnswer;\nrpc_answer_dropped_running#cd78e586 = RpcDropAnswer;\nrpc_answer_dropped#a43ad8b7 msg_id:long seq_no:int bytes:int = RpcDropAnswer;\nfuture_salt#0949d9dc valid_since:int valid_until:int salt:long = FutureSalt;\nfuture_salts#ae500895 req_msg_id:long now:int salts:vector = FutureSalts;\npong#347773c5 msg_id:long ping_id:long = Pong;\ndestroy_session_ok#e22045fc session_id:long = DestroySessionRes;\ndestroy_session_none#62d350c9 session_id:long = DestroySessionRes;\nnew_session_created#9ec20908 first_msg_id:long unique_id:long server_salt:long = NewSession;\nhttp_wait#9299359f max_delay:int wait_after:int max_wait:int = HttpWait;\nipPort#d433ad73 ipv4:int port:int = IpPort;\nipPortSecret#37982646 ipv4:int port:int secret:bytes = IpPort;\naccessPointRule#4679b65f phone_prefix_rules:string dc_id:int ips:vector = AccessPointRule;\nhelp.configSimple#5a592a6c date:int expires:int rules:vector = help.ConfigSimple;\ntlsClientHello blocks:vector = TlsClientHello;\ntlsBlockString data:string = TlsBlock;\ntlsBlockRandom length:int = TlsBlock;\ntlsBlockZero length:int = TlsBlock;\ntlsBlockDomain = TlsBlock;\ntlsBlockGrease seed:int = TlsBlock;\ntlsBlockScope entries:Vector = TlsBlock;\n---functions---\nping#7abe77ec ping_id:long = Pong;\nping_delay_disconnect#f3427b8c ping_id:long disconnect_delay:int = Pong;`;","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\tid: moduleId,\n\t\tloaded: false,\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Flag the module as loaded\n\tmodule.loaded = true;\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n// expose the modules object (__webpack_modules__)\n__webpack_require__.m = __webpack_modules__;\n\n// the startup function\n__webpack_require__.x = () => {\n\t// Load entry module and return exports\n\t// This entry module depends on other loaded chunks and execution need to be delayed\n\tvar __webpack_exports__ = __webpack_require__.O(undefined, [592], () => (__webpack_require__(6927)))\n\t__webpack_exports__ = __webpack_require__.O(__webpack_exports__);\n\treturn __webpack_exports__;\n};\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.f = {};\n// This file contains only the entry chunk.\n// The chunk loading function for additional chunks\n__webpack_require__.e = (chunkId) => {\n\treturn Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => {\n\t\t__webpack_require__.f[key](chunkId, promises);\n\t\treturn promises;\n\t}, []));\n};","// This function allow to reference async chunks and sibling chunks for the entrypoint\n__webpack_require__.u = (chunkId) => {\n\t// return url for filenames based on template\n\treturn \"\" + chunkId + \".\" + \"d7ca037ed9b7d1c6792a\" + \".js\";\n};","// This function allow to reference all chunks\n__webpack_require__.miniCssF = (chunkId) => {\n\t// return url for filenames based on template\n\treturn undefined;\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","__webpack_require__.nmd = (module) => {\n\tmodule.paths = [];\n\tif (!module.children) module.children = [];\n\treturn module;\n};","var scriptUrl;\nif (__webpack_require__.g.importScripts) scriptUrl = __webpack_require__.g.location + \"\";\nvar document = __webpack_require__.g.document;\nif (!scriptUrl && document) {\n\tif (document.currentScript)\n\t\tscriptUrl = document.currentScript.src\n\tif (!scriptUrl) {\n\t\tvar scripts = document.getElementsByTagName(\"script\");\n\t\tif(scripts.length) scriptUrl = scripts[scripts.length - 1].src\n\t}\n}\n// When supporting browsers where an automatic publicPath is not supported you must specify an output.publicPath manually via configuration\n// or pass an empty string (\"\") and set the __webpack_public_path__ variable from your code to use your own logic.\nif (!scriptUrl) throw new Error(\"Automatic publicPath is not supported in this browser\");\nscriptUrl = scriptUrl.replace(/#.*$/, \"\").replace(/\\?.*$/, \"\").replace(/\\/[^\\/]+$/, \"/\");\n__webpack_require__.p = scriptUrl;","// no baseURI\n\n// object to store loaded chunks\n// \"1\" means \"already loaded\"\nvar installedChunks = {\n\t927: 1\n};\n\n// importScripts chunk loading\nvar installChunk = (data) => {\n\tvar [chunkIds, moreModules, runtime] = data;\n\tfor(var moduleId in moreModules) {\n\t\tif(__webpack_require__.o(moreModules, moduleId)) {\n\t\t\t__webpack_require__.m[moduleId] = moreModules[moduleId];\n\t\t}\n\t}\n\tif(runtime) runtime(__webpack_require__);\n\twhile(chunkIds.length)\n\t\tinstalledChunks[chunkIds.pop()] = 1;\n\tparentChunkLoadingFunction(data);\n};\n__webpack_require__.f.i = (chunkId, promises) => {\n\t// \"1\" is the signal for \"already loaded\"\n\tif(!installedChunks[chunkId]) {\n\t\tif(true) { // all chunks have JS\n\t\t\timportScripts(__webpack_require__.p + __webpack_require__.u(chunkId));\n\t\t}\n\t}\n};\n\nvar chunkLoadingGlobal = self[\"webpackChunktelegram_t\"] = self[\"webpackChunktelegram_t\"] || [];\nvar parentChunkLoadingFunction = chunkLoadingGlobal.push.bind(chunkLoadingGlobal);\nchunkLoadingGlobal.push = installChunk;\n\n// no HMR\n\n// no HMR manifest","// run startup\nvar __webpack_exports__ = __webpack_require__.x();\n"],"names":["deferred","next","API_UPDATE_THROTTLE","window","innerHeight","Math","round","API_THROTTLE_RESET_UPDATES","Set","SUPPORTED_IMAGE_CONTENT_TYPES","SUPPORTED_VIDEO_CONTENT_TYPES","SERVICE_NOTIFICATIONS_USER_ID","onTickEndCallbacks","onTickEndPrimaryCallbacks","buildCollectionByKey","collection","key","reduce","byKey","member","pick","object","keys","result","bytesToDataUri","bytes","shouldOmitPrefix","mimeType","btoa","String","fromCharCode","omitVirtualClassFields","instance","flags","CONSTRUCTOR_ID","SUBCLASS_OF_ID","className","classType","getBytes","rest","pathBytesToSvg","width","height","replace","path","len","length","i","num","buildPath","DEFAULT_THUMB_SIZE","w","h","buildApiThumbnailFromStripped","sizes","thumb","find","s","GramJs","realSizes","filter","dataUri","strippedPhotoToJpg","undefined","buildApiPhoto","photo","map","buildApiPhotoSize","id","thumbnail","photoSize","type","localMessages","chats","users","messages","documents","stickerSets","photos","webDocuments","ANIMATED_STICKER_MIME_TYPE","buildStickerFromDocument","document","stickerAttribute","attributes","attr","fileAttribute","sizeAttribute","stickerSetInfo","stickerset","emoji","alt","isAnimated","cachedThumb","thumbs","pathThumb","buildApiThumbnailFromCached","buildApiThumbnailFromPath","stickerSetId","stickerSetAccessHash","accessHash","buildStickerSet","set","archived","animated","installedDate","title","count","shortName","hasThumbnail","Boolean","buildStickerSetCovered","coveredStickerSet","stickerSet","stickerSetCovers","covers","cover","forEach","coverSticker","push","localDb","interpolateArray","data","fitCount","peak","newData","Array","springFactor","leftFiller","rightFiller","idx","floor","val","ApiMessageEntityTypes","ApiMediaFormat","isPeerUser","peer","hasOwnProperty","isPeerChat","buildApiPeerId","getApiChatIdFromMtpPeer","userId","chatId","channelId","resolveMessageApiChatId","mtpMessage","peerId","addMessageToLocalDb","message","messageFullId","media","webpage","action","addPhotoToLocalDb","addUserToLocalDb","user","shouldOverwrite","addEntitiesWithPhotosToLocalDb","entities","entity","chat","noOverwrite","addChatToLocalDb","serializeBytes","value","deserializeBytes","Buffer","from","getEntityTypeById","chatOrUserId","getEntityTypeByDeprecatedId","startsWith","buildPeer","buildMtpPeerId","buildInputPeer","BigInt","buildInputPeerFromLocalDb","buildInputEntity","buildInputStickerSet","buildInputDocument","buildInputMediaDocument","inputDocument","generateRandomBigInt","readBigIntFromBuffer","generateRandomBytes","buildMessageFromUpdate","update","fromId","buildMtpMessageEntity","offset","url","Bold","Italic","Underline","Strike","Code","Pre","language","Blockquote","TextUrl","Url","Hashtag","MentionName","isMessageWithMedia","buildInputContact","phone","firstName","lastName","clientId","buildChatBannedRights","bannedRights","untilDate","buildChatAdminRights","adminRights","buildShippingInfo","info","shippingAddress","buildInputPrivacyKey","privacyKey","buildInputReportReason","reason","abs","slice","buildInputGroupCall","groupCall","LOCAL_MEDIA_UPLOADING_TEMP_ID","currentUserId","localMessageCounter","buildApiSponsoredMessage","startParam","channelPost","chatInvite","chatInviteHash","randomId","chatInviteTitle","isBot","text","buildMessageTextContent","expiresAt","Date","now","channelPostId","buildApiMessage","buildApiMessageWithChatId","isChatWithSelf","isOutgoing","out","post","fwdFrom","content","buildMessageMediaContent","sticker","poll","contact","senderId","targetPeerId","isChannelPost","call","amount","currency","translationValues","targetUserIds","targetChatId","includes","withDuration","duration","video","join","mins","max","toString","Number","totalAmount","domain","buildAction","replyToMsgId","replyToTopId","replyToPeerId","replyTo","isEdited","editDate","editHide","inlineButtons","keyboardButtons","keyboardPlaceholder","isKeyboardSingleUse","messageId","replyMarkup","markup","rows","buttons","button","receiptMsgId","placeholder","singleUse","buildReplyButtons","forwardInfo","savedFromPeerId","savedFromPeer","date","isLinkedChannelPost","fromChatId","fromMessageId","savedFromMsgId","senderUserId","hiddenUserName","fromName","adminTitle","postAuthor","buildApiMessageForwardInfo","replies","mediaUnread","isMediaUnread","groupedId","isInAlbum","audio","shouldHideKeyboardButtons","views","isFromScheduled","fromScheduled","replyToMessageId","replyToChatId","replyToTopMessageId","mentioned","hasUnreadMention","isMentioned","viaBotId","comments","threadInfo","buildThreadInfo","noforwards","isProtected","some","e","buildApiMessageEntity","buildMessageDraft","draft","formattedText","replyingToId","ttlSeconds","buildSticker","buildPhoto","buildVideoFromDocument","buildVideo","audioAttribute","voice","thumbnailSizes","fileName","getFilenameFromDocument","buildAudio","waveform","buildVoice","buildApiDocument","buildDocumentFromMedia","phoneNumber","buildContact","buildPoll","results","buildPollFromMedia","webPage","buildWebPage","invoice","description","test","photoUrl","isTest","buildInvoice","buildInvoiceFromMedia","size","self","isMovSupported","videoAttr","a","gifAttr","supportsStreaming","roundMessage","isRound","isGif","mediaType","mediaSize","has","imageAttribute","timestamp","pollResults","answers","rawAnswers","answer","option","summary","isPublic","publicVoters","buildPollResults","rawResults","totalVoters","recentVoters","solution","solutionEntities","chosen","correct","voters","isChosen","isCorrect","votersCount","recentVoterIds","defaultBase","filenameAttribute","extension","split","buildNewPoll","localId","messageReplies","maxId","readMaxId","recentRepliers","apiChannelId","threadId","originChannelId","messagesCount","lastMessageId","lastReadInboxMessageId","recentReplierIds","getServerTime","serverTimeOffset","buildApiChatFieldsFromPeerEntity","peerEntity","isSupport","isMin","min","avatarHash","buildAvatarHash","isSignaturesShown","signatures","hasPrivateLink","hasLink","username","isVerified","verified","isCallActive","callActive","isCallNotEmpty","callNotEmpty","participantsCount","membersCount","joinDate","buildApiChatPermissions","isCreator","creator","buildApiChatRestrictions","buildApiChatMigrationInfo","buildApiChatFromDialog","dialog","folderId","unreadMark","unreadCount","unreadMentionsCount","notifySettings","silent","muteUntil","readOutboxMaxId","readInboxMaxId","isMuted","getApiChatTypeFromPeerEntity","getApiChatTitleFromMtpPeer","lastReadOutboxMessageId","hasUnreadMark","draftDate","currentUserBannedRights","defaultBannedRights","isRestricted","restrictions","restrictionReason","restricted","restrictionReasons","targetReason","platform","buildApiChatRestrictionReason","Object","assign","isNotJoined","left","kicked","migratedTo","buildApiChatFromPreview","preview","withForbidden","getUserName","megagroup","getPeerKey","photoId","buildChatMember","inviterId","joinedDate","kickedByUserId","kickedBy","promotedByUserId","promotedBy","customTitle","rank","isAdmin","isOwner","buildChatMembers","participants","buildChatTypingStatus","buildApiChatFolder","channels","broadcasts","pinnedChatIds","pinnedPeers","includedChatIds","includePeers","excludedChatIds","excludePeers","buildApiChatFolderFromSuggested","buildApiChatBotCommands","botInfos","botCommands","botInfo","botId","concat","commands","mtpCommand","buildApiUserFromFull","mtpUserFull","fullUser","about","commonChatsCount","pinnedMsgId","blocked","buildApiUser","fullInfo","bio","pinnedMessageId","isBlocked","botDescription","buildApiBotCommands","mtpUser","userType","bot","deleted","isSelf","mutualContact","isContact","canBeInvitedToGroup","botNochats","noStatus","status","botInlinePlaceholder","botPlaceholder","buildApiUserStatus","mtpStatus","expires","wasOnline","command","buildApiUsersAndStatuses","mtpUsers","userStatusesById","buildApiWallpaper","wallpaper","slug","buildApiSession","session","isCurrent","current","isOfficialApp","officialApp","isPasswordPending","passwordPending","hash","buildPrivacyRules","rules","visibility","allowUserIds","allowChatIds","blockUserIds","blockChatIds","rule","buildApiNotifyException","showPreviews","sound","isSilent","shouldShowPreviews","buildApiCountry","country","code","hidden","iso2","defaultName","name","countryCode","prefixes","patterns","isHidden","buildApiGroupCallParticipant","participant","versioned","canSelfUnmute","justJoined","muted","mutedByYou","source","volume","volumeByAdmin","videoJoined","presentation","raiseHandRating","isLeft","isMutedByMe","hasJustJoined","isVolumeByAdmin","isVersioned","isVideoJoined","isUser","buildApiGroupCallParticipantVideo","participantVideo","audioSource","endpoint","paused","sourceGroups","isPaused","buildApiGroupCallParticipantVideoSourceGroup","participantVideoSourceGroup","semantics","sources","buildApiGroupCall","connectionState","version","streamDcId","scheduleDate","canChangeJoinMuted","joinMuted","canStartVideo","scheduleStartSubscribed","isLoaded","onUpdate","sentMessageIds","shouldIgnoreNextChannelUpdate","dispatchUserAndChatUpdates","updater","originRequest","connection","timeOffset","state","shouldForceReply","buildApiMessageFromShort","selective","_entities","dcId","buildChatPhotoForLocalDb","localDbChatId","newProfilePhoto","ids","existingIds","missingIds","profilePhotoIds","setTimeout","popup","error","notification","currentDate","inboxDate","buildApiMessageFromNotification","localMessage","Error","newContent","add","isAlreadySent","isScheduled","sendingState","messageUpdate","pollId","apiPoll","pollUpdate","options","stillUnreadCount","isPinned","pinned","order","dp","folderPeers","folderPeer","folder","orderedIds","replacedMembers","addedMember","deletedMemberId","messageIds","typingStatus","channel","unread","apiUserId","updatedUser","peerType","buildPrivacyKey","JSON","parse","params","groupCallId","ApiErrors","PHONE_NUMBER_INVALID","PHONE_CODE_INVALID","PASSWORD_HASH_INVALID","PHONE_PASSWORD_FLOOD","PHONE_NUMBER_BANNED","authController","onRequestPhoneNumber","buildAuthStateUpdate","Promise","resolve","reject","onRequestCode","isCodeViaApp","onRequestPassword","hint","onRequestRegistration","onRequestQrCode","qrCode","token","onAuthError","err","errors","hours","ceil","seconds","authorizationState","provideAuthPhoneNumber","provideAuthCode","provideAuthPassword","password","provideAuthRegistration","registration","restartAuth","restartAuthWithQr","cacheApi","caches","Type","async","fetch","cacheName","isHtmlAllowed","request","Request","cache","open","response","match","contentType","headers","get","Text","Blob","blob","shouldRecreate","resolvedType","Json","json","console","warn","save","cacheData","stringify","Response","put","clear","delete","MEDIA_ENTITY_TYPES","getMimeType","fallbackMimeType","subarray","byte","GramJsLogger","gramJsUpdateEventBuilder","build","client","isConnected","destroy","invokeRequest","disconnect","onSessionUpdate","sessionData","handleGramJsUpdate","handleTerminatedSession","shouldHandleUpdates","shouldThrow","invoke","updatesContainer","updates","injectUpdateEntities","isSlowMode","hasErrorKey","dispatchErrorUpdate","downloadMedia","args","onProgress","mediaFormat","start","end","fullSize","mediaMatch","arrayBuffer","entityType","entityId","sizeType","Stream","acceptsBuffer","progressCallback","workers","getMessageMediaMimeType","downloadStickerSetThumb","Lottie","downloadProfilePhoto","download","parsed","BlobUrl","inflate","to","Progressive","buffer","parseMedia","canCache","prepared","mediaData","URL","createObjectURL","downloadMediaWithClient","uploadFile","file","updateTwoFaSettings","fetchCurrentUser","userFull","currentUser","_currentUserId","onCurrentUserUpdate","MAX_INT_32","fetchChats","limit","offsetDate","withPinned","lastLocalServiceMessage","offsetPeer","excludePinned","resultPinned","updateLocalDb","lastMessagesByChatId","peersByKey","preparePeers","draftsById","replyingToById","dialogs","orderedPinnedIds","lastMessage","isListed","chatIds","totalChatCount","fetchFullChat","fullChat","onlineCount","exportedInvite","slowmodeSeconds","slowmodeNextSendDate","migratedFromChatId","migratedFromMaxId","canViewParticipants","linkedChatId","hiddenPrehistory","defaultSendAs","inviteLink","link","members","fetchMembers","kickedMembers","bannedUsers","adminMembers","adminUsers","mtpLinkedChat","slowMode","nextSendDate","migratedFrom","maxMessageId","canViewMembers","isPreHistoryHidden","sendAsId","getFullChannelInfo","getFullChatInfo","searchChats","query","q","localPeerIds","myResults","allChats","allUsers","localChats","r","localUsers","u","globalChats","globalUsers","fetchChat","requestChatUpdate","lastLocalMessage","noLastMessage","peers","lastRemoteMessage","saveDraft","clearDraft","updateChatMutedState","settings","createChannel","noErrorUpdate","broadcast","newChannel","joinChannel","deleteChatUser","deleteChat","leaveChannel","deleteChannel","createGroupChat","newChat","editChatPhoto","uploadedPhoto","inputEntity","toggleChatPinned","shouldBePinned","toggleChatArchived","fetchChatFolders","byId","fetchRecommendedChatFolders","editChatFolder","folderUpdate","emoticon","contacts","nonContacts","groups","bots","excludeArchived","excludeMuted","excludeRead","buildFilterFromApiFolder","deleteChatFolder","isActionSuccessful","recommendedChatFolders","folders","toggleDialogUnread","getChatByUsername","togglePreHistoryHidden","isEnabled","enabled","updateChatDefaultBannedRights","updateChatMemberBannedRights","updateChatAdmin","updateChatTitle","updateChatAbout","toggleSignatures","memberFilter","fetchGroupsForDiscussion","setDiscussionGroup","group","migrateChat","openChatByInvite","requestNeeded","isChannel","isRequestNeeded","addChatMembers","all","deleteChatMember","viewMessages","sendMessages","sendMedia","sendStickers","sendGifs","sendGames","sendInline","embedLinks","sendPolls","changeInfo","inviteUsers","pinMessages","store","importChatInvite","toggleIsProtected","File","constructor","fileBits","super","this","fetchMessages","pagination","RequestClass","msgId","c","threadInfos","fetchMessage","queue","sendMessage","replyingTo","attachment","gif","scheduledAt","noWebPage","sendAs","filename","blobUrl","previewBlobUrl","quick","inputWaveform","buildUploadingMedia","buildLocalMessage","groupIndex","groupedUploads","counter","singleMediaByIndex","prevQueue","uploadMedia","inputMedia","uploadedMedia","messageMedia","fileReference","fetchInputMedia","multiMedia","values","sendGroupedMedia","pollParams","quiz","question","multipleChoice","correctAnswers","buildInputPoll","vcard","noWebpage","editMessage","mtpEntities","rescheduleMessage","lastModified","blobToFile","fetchBlob","fetchFile","patchedOnProgress","progress","isCanceled","inputFile","pinMessage","isUnpin","isOneSide","unpin","pmOneside","unpinAllMessages","deleteMessages","shouldDeleteForAll","revoke","deleteScheduledMessages","deleteHistory","just_clear","reportMessages","sendMessageAction","gramAction","buildSendMessageAction","topMsgId","markMessageListRead","requestThreadInfoUpdate","markMessagesRead","topMessageResult","repliesResult","offsetId","addOffset","discussionChatId","topMessageId","firstMessageId","noTopChatsRequest","searchMessagesLocal","chatOrUser","minDate","maxDate","nextOffsetId","totalCount","searchMessagesGlobal","offsetRate","nextRate","fetchWebPagePreview","sendPollVote","loadPollOptionResults","shouldResetVoters","votes","vote","nextOffset","forwardMessages","fromChat","toChat","randomIds","index","isAudio","asIncomingInChatWithSelf","buildLocalForwardedMessage","fromPeer","toPeer","sil2ent","findFirstMessageIdAfterDate","fetchScheduledHistory","sendScheduledMessages","isServiceMessageWithMedia","fetchPinnedMessages","fetchSeenBy","fetchSendAs","saveDefaultSendAs","fetchSponsoredMessages","viewSponsoredMessage","random","inputGifBot","fetchFullUser","input","userWithFullInfo","fetchCommonChats","commonChats","mtpChat","isFullyLoaded","fetchNearestCountry","dcInfo","fetchTopUsers","topPeers","correspondents","fetchContactList","fetchUsers","updateContact","addContact","deleteContact","fetchProfilePhotos","fetchStickerSets","allStickers","sets","fetchRecentStickers","stickers","processStickerResult","fetchFavoriteStickers","fetchFeaturedStickers","faveSticker","unfave","fetchStickers","stickerSetShortName","packs","acc","documentId","fetchAnimatedEmojis","searchStickers","fetchSavedGifs","gifs","processGifResult","installStickerSet","uninstallStickerSet","searchGifs","config","resolvedPeer","gifSearchUsername","foundGif","fetchStickersForEmoji","fetchEmojiKeywords","fromVersion","langCode","keywords","emojiKeyword","keyword","emoticons","checkChatUsername","setChatUsername","updatePrivateLink","usageLimit","expireDate","EMAIL_UNCONFIRMED","EMAIL_HASH_EXPIRED","NEW_SALT_INVALID","NEW_SETTINGS_INVALID","CODE_INVALID","emailCodeController","getPasswordInfo","hasPassword","onRequestEmailCode","checkPassword","currentPassword","isCheckPassword","onError","clearPassword","updatePassword","email","newPassword","emailCodeCallback","onEmailCodeError","updateRecoveryEmail","provideRecoveryEmailCode","getGroupCall","discardGroupCall","editGroupCallParticipant","presentationPaused","videoStopped","videoPaused","raiseHand","editGroupCallTitle","exportGroupCallInvite","fetchGroupCallParticipants","leaveGroupCall","joinGroupCall","inviteHash","joinAs","createGroupCall","toJSNumber","joinGroupCallPresentation","toggleGroupCallStartSubscription","subscribed","leaveGroupCallPresentation","BETA_LANG_CODES","updateProfile","checkUsername","updateUsername","updateProfilePhoto","uploadProfilePhoto","fetchWallpapers","filteredWallpapers","wallpapers","pattern","uploadWallpaper","fetchBlockedContacts","blockedIds","blockContact","unblockContact","fetchAuthorizations","authorizations","terminateAuthorization","terminateAllAuthorizations","fetchNotificationExceptions","compareSound","fetchNotificationSettings","isMutedContactSignUpNotification","privateContactNotificationsSettings","groupNotificationsSettings","broadcastNotificationsSettings","privateSilent","privateMuteUntil","privateShowPreviews","groupSilent","groupMuteUntil","groupShowPreviews","broadcastSilent","broadcastMuteUntil","broadcastShowPreviews","hasContactJoinedNotifications","hasPrivateChatsNotifications","hasPrivateChatsMessagePreview","hasGroupNotifications","hasGroupMessagePreview","hasBroadcastNotifications","hasBroadcastMessagePreview","updateContactSignUpNotification","updateNotificationSettings","fetchLanguages","langPack","fetchLangPack","sourceLangPacks","collections","strings","reverse","fetchLangStrings","fetchPrivacySettings","registerDevice","secret","getAuthKey","getKey","tokenType","appSandbox","otherUids","unregisterDevice","setPrivacySettings","privacyRules","allowedUsers","allowedChats","blockedUsers","blockedChats","updateIsOnline","isOnline","offline","fetchContentSettings","isSensitiveEnabled","sensitiveEnabled","canChangeSensitive","sensitiveCanChange","updateContentSettings","fetchCountryList","countryList","countries","phoneCodes","array","countryCodes","isArray","sort","b","localeCompare","general","buildApiWebDocument","answerCallbackButton","fetchTopInlineBots","botsInline","fetchInlineBot","fetchInlineBotResults","queryId","switchPm","isGallery","gallery","help","buildApiBotInlineMediaResult","webDocument","webThumbnail","buildApiBotInlineResult","sendInlineBotResult","resultId","startBot","buildShippingOptions","shippingOptions","prices","ac","cur","label","validateRequestedInfo","requestInfo","shouldSave","sendPaymentForm","formId","requestedInfoId","shippingOptionId","credentials","getPaymentForm","form","canSaveCredentials","passwordMissing","providerId","nativeProvider","nativeParams","savedInfo","nameRequested","phoneRequested","emailRequested","shippingAddressRequested","flexible","phoneToProvider","emailToProvider","mapedPrices","nativeData","needCardholderName","need_cardholder_name","needCountry","need_country","needZip","need_zip","publishableKey","publishable_key","buildPaymentForm","getReceipt","receipt","shipping","credentialsTitle","shippingPrices","shippingMethod","buildReceipt","initApi","_onUpdate","initialArgs","initUpdater","handleUpdate","initAuth","initChats","initMessages","initUsers","initStickers","initManagement","initTwoFaSettings","initCalls","userAgent","sessions","TelegramClient","process","deviceModel","navigator","systemVersion","appVersion","useWSS","additionalDcsDisabled","testServers","addEventHandler","phoneCode","firstAndLastNames","initialMethod","getSessionData","initClient","flushUpdatesOnTickEnd","schedulerFn","fn","waiting","_args","throttleWith","callback","isPrimary","then","currentCallbacks","currentPrimaryCallbacks","cb","throttleId","pendingUpdates","currentThrottleId","currentUpdates","flushUpdatesThrottled","ms","shouldRunFirst","interval","isPending","setInterval","clearInterval","throttle","onerror","sendToOrigin","addEventListener","callbackState","Map","postMessage","onmessage","callbackArgs","lastArg","ArrayBuffer","fnName","methods","callApi","require","crypto","little","signed","randBuffer","bytesNumber","bigInt","subtract","pow","toSignedLittleBuffer","big","number","bigNumber","byteArray","shiftRight","and","readBufferFromBigInt","bitLength","lesser","below","hex","padStart","l","reminder","randomBytes","sha1","shaSum","createHash","digest","crcTable","module","exports","generateRandomLong","mod","n","m","crc32","buf","k","makeCRCTable","isBuffer","crc","generateKeyDataFromNonce","serverNonce","newNonce","hash1","hash2","hash3","iv","sha256","bigIntMod","remainder","modExp","one","x","greater","zero","leastSignificantBit","divide","eq","multiply","getRandomInt","sleep","getByteArray","integer","bits","byteLength","convertToLittle","alloc","writeUInt32BE","bufferXor","res","createDeferred","promise","_resolve","constructors","checkPrimeAndGood","primeBytes","g","equals","numBytesForHash","bigNumForHash","isGoodModExpFirst","modexp","prime","diff","xor","computeHash","algo","salt1","salt2","salt","iterations","pbkdf2","pbkdf2sha512","computeCheck","currentAlgo","PasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow","pwHash","p","B","srp_B","isGoodLarge","pForHash","gForHash","bForHash","gX","kgX","aForHash","A","generateAndCheckRandom","gB","ux","aUx","S","K","pSha","gSha","salt1Sha","salt2Sha","M1","InputCheckPasswordSRP","srpId","computeDigest","JPEG_HEADER","JPEG_FOOTER","_raiseCastFail","target","getMessageId","getInputPeer","allowSelf","checkHash","User","InputPeerSelf","InputPeerUser","Chat","ChatEmpty","ChatForbidden","InputPeerChat","Channel","TypeError","InputPeerChannel","ChannelForbidden","InputUser","InputChannel","UserEmpty","InputPeerEmpty","UserFull","ChatFull","PeerChat","getDisplayName","getAppropriatedPartSize","fileSize","stripped","header","getDC","downloadDC","ipAddress","port","pwd","Api","newAlgo","newSettings","newPasswordHash","newSecureSettings","codeLength","os","Logger","MemorySession","Helpers","utils","Session","LAYER","requests","MTProtoSender","ConnectionTCPObfuscated","authFlow","checkAuthorization","downloadFile","WEBDOCUMENT_REQUEST_PART_SIZE","sizeTypes","apiId","apiHash","opts","DEFAULT_OPTIONS","_useIPV6","useIPV6","baseLogger","_log","floodSleepLimit","_eventBuilders","_phoneCodeHash","parseInt","_requestRetries","requestRetries","_connectionRetries","connectionRetries","_retryDelay","retryDelay","proxy","_proxy","_timeout","timeout","_autoReconnect","autoReconnect","_connection","_floodWaitedRequests","_initWith","InvokeWithLayer","layer","InitConnection","release","systemLangCode","_config","phoneCodeHashes","_exportedSenderPromises","_exportedSenderReleaseTimeouts","_additionalDcsDisabled","_loopStarted","_reconnecting","_destroyed","_initSession","_sender","logger","retries","delay","connectTimeout","authKeyCallback","_authKeyCallback","bind","updateCallback","_handleUpdate","isMainSender","userDisconnected","_user_connected","_disconnected","serverAddress","connect","setAuthKey","authKey","send","GetConfig","_updateLoop","load","setDC","attempts","PingDelayDisconnect","pingId","MIN_SAFE_INTEGER","MAX_SAFE_INTEGER","disconnectDelay","race","getTime","_lastRequest","GetState","sender","newDc","DC","setKey","dc","_authenticated","auth","ExportAuthorization","req","ImportAuthorization","shouldReconnect","existingSender","_connectSender","_createExportedSender","isConnecting","_borrowExportedSender","clearTimeout","onConnectionBreak","_cleanupExportedSender","getSender","inputLocation","messageOrMedia","Message","MessageMediaWebPage","WebPage","MessageMediaPhoto","Photo","_downloadPhoto","MessageMediaDocument","Document","_downloadDocument","MessageMediaContact","_downloadContact","WebDocument","WebDocumentNoProxy","_downloadWebDocument","isBig","loc","chatPhoto","UserProfilePhoto","ChatPhoto","InputPeerPhotoFileLocation","thumbVersion","InputStickerSetThumb","InputStickerSetID","thumbDcId","_pickFileSize","indexOf","_downloadCachedPhotoSize","PhotoStrippedSize","PhotoSizeEmpty","PhotoCachedSize","InputPhotoFileLocation","thumbSize","doc","InputDocumentFileLocation","buff","downloaded","upload","GetWebFile","location","InputWebFileLocation","attempt","sendWithInvokeSupport","ServerError","FloodWaitError","FloodTestPhoneWaitError","PhoneMigrateError","NetworkMigrateError","UserMigrateError","_switchDC","MsgWaitError","isReady","GetUsers","InputUserSelf","authParams","apiCredentials","fileParams","event","Updates","UpdatesCombined","_processUpdate","UpdateShort","others","_dispatchUpdate","ptsDate","builder","times","pause","Infinity","sequentialUpdates","DEFAULT_INITIAL_METHOD","me","botAuthToken","signInBot","signInUser","signInUserWithQrCode","phoneCodeHash","sendCodeResult","sendCode","forceSMS","termsOfService","isRegistrationRequired","signInWithPassword","isScanningComplete","inputPromise","exceptIds","updatePromise","result2","authorization","migratedResult","sendResult","resendResult","passwordSrpResult","passwordSrpCheck","computePasswordSrpCheck","ONE_MB","Foreman","maxWorkers","requestWorker","activeWorkers","releaseWorker","partSizeKb","partSize","partsCount","foreman","promises","hasEnded","isPrecise","offsetMemo","precise","buffers","totalLength","fileId","isLarge","partCount","fileToBuffer","sendingParts","j","jMemo","bytesMemo","filePart","fileTotalParts","parts","md5Checksum","BinaryReader","AuthKey","_key","_hash","reader","auxHash","readLong","read","keyId","writeUInt8","shaData","other","cipher","createCipheriv","encrypt","Factorizator","neq","temp","pq","y","randBetween","minus","ys","condition","gcd","IGE","AESIGE","ige","decryptIge","cipherText","decrypt","encryptIge","plainText","padding","i2abLow","uint8","Uint8Array","int","i2abBig","ab2iLow","ab","Uint32Array","ab2iBig","isBigEndian","i2ab","ab2i","AES","getWords","Counter","initialValue","setBytes","_counter","increment","CTR","_remainingCounter","_remainingCounterIndex","_aes","encrypted","Hash","algorithm","subtle","createDecipheriv","getRandomValues","passwordKey","importKey","deriveBits","s2i","str","pos","charCodeAt","right","ReadCancelledError","TypeNotFoundError","invalidConstructorId","remaining","alert","InvalidChecksumError","checksum","validChecksum","InvalidBufferError","payload","readInt32LE","SecurityError","BadMessageError","errorMessage","ErrorMessages","CdnFileTamperedError","RPCError","_fmtRequest","InvalidDCError","BadRequestError","UnauthorizedError","ForbiddenError","NotFoundError","AuthKeyError","FloodError","TimedOutError","capture","SlowModeWaitError","FileMigrateError","EmailUnconfirmedError","rpcErrorRe","Common","RPCBaseErrors","RPCErrorList","RPCMessageToError","rpcError","msgRegex","Cls","EventBuilder","types","func","blacklistChats","resolved","NewMessage","Raw","StopPropagation","_queue","canGet","resolveGet","canPush","resolvePush","returned","pop","coreObjects","tlobjects","stream","_last","readByte","readInt","readUInt32LE","readLargeInt","readFloat","readFloatLE","readDouble","readDoubleLE","getBuffer","tgReadBytes","firstByte","tgReadString","tgReadBool","tgReadDate","tgReadObject","constructorId","clazz","seek","tellPosition","setPosition","fromReader","tgReadVector","close","position","_stream","write","getValue","_level","level","isBrowser","browser","__nwjs","colors","debug","messageFormat","canSend","levels","stack","format","toISOString","toUpperCase","color","log","MessageContainer","TLMessage","BinaryWriter","USE_INVOKE_AFTER_WITH","_state","_pendingStates","_ready","setReady","append","after","catch","finally","extend","states","batch","MAXIMUM_LENGTH","shift","SIZE_OVERHEAD","MAXIMUM_SIZE","afterId","writeDataAsMessage","unshift","writeUInt32LE","writeInt32LE","containerId","rejectAll","requestState","Mutex","mutex","WebSocketClient","closeError","disconnectedCallback","closed","readData","thisTime","canRead","toReturn","resolveRead","getWebSocketLink","ip","website","onopen","receive","onclose","wasClean","runExclusive","PromisedWebSockets","MessagePacker","AsyncQueue","tl","events","extensions","helpers","PUBLIC_KEYS","fingerprint","_serverKeys","keyInfo","doAuthentication","nonce","resPQ","factorize","pBuffer","qBuffer","pqInnerData","targetFingerprint","targetKey","serverPublicKeyFingerprints","dataWithPadding","dataPadReversed","encryptedData","tempKey","shaDigestKeyWithData","dataWithHash","aesEncrypted","tempKeyXor","keyAesEncrypted","keyAesEncryptedInt","greaterOrEquals","encryptedDataBuffer","serverDhParams","publicKeyFingerprint","sh","nnh","newNonceHash","encryptedAnswer","plainTextAnswer","serverDhInner","dhPrime","ga","gA","serverTime","gb","gab","clientDhInner","retryId","clientDdhInnerHashed","clientDhEncrypted","dhGen","nonceTypes","nonceNumber","calcNewNonceHash","MTProtoState","loggers","body","_getNewMsgId","recv","MtProtoPlainSender","RPCResult","GZIPPacked","RequestState","MsgsAck","MsgsStateInfo","Pong","UpdateConnectionState","UpdateServerTimeOffset","BadServerSalt","BadMsgNotification","MsgDetailedInfo","MsgNewDetailedInfo","NewSessionCreated","FutureSalts","MsgsStateReq","MsgResendReq","MsgsAllInfo","LogOut","_dcId","_retries","_delay","_connectTimeout","_updateCallback","_autoReconnectCallback","autoReconnectCallback","_isMainSender","_onConnectionBreak","_send_loop_handle","_recv_loop_handle","_send_queue","_pending_state","_pending_ack","_last_acks","_handlers","_handleRPCResult","_handleContainer","_handleGzipPacked","_handlePong","_handleBadServerSalt","_handleBadNotification","_handleDetailedInfo","_handleNewDetailedInfo","_handleNewSessionCreated","_handleAck","_handleFutureSalts","_handleStateForgotten","_handleMsgAll","force","_connect","connected","disconnected","_disconnect","plain","_sendLoop","_recvLoop","ack","msgIds","encryptMessageData","reconnect","decryptMessageData","_handleBadAuthKey","_processMessage","shouldSkipForMain","broken","obj","handler","_popStates","toPop","reqMsgId","readResult","innerMessage","pong","newTimeOffset","updateTimeOffset","badSalt","badMsgId","newServerSalt","badMsg","errorCode","_sequence","answerMsgId","serverSalt","repeat","_reconnect","reset","newConnection","_ip","_port","_testServers","InvokeAfterMsg","_lastMsgId","updateMessageId","msgKey","sha256a","sha256b","contentRelated","seqNo","_getSeqNo","gzipIfSmaller","waitForKey","_calcKey","ourKey","remoteMsgId","remoteSequence","containerLen","nanoseconds","newMsgId","shiftLeft","or","correctMsgId","bad","old","pending","Connection","_connected","_sendTask","_recvTask","_codec","_obfuscation","_sendArray","_recvArray","socket","disconnectCallback","PacketCodecClass","_initConn","fromCallback","_send","_recv","tag","encodedPacket","encodePacket","readPacket","PacketCodec","_conn","ObfuscatedConnection","ObfuscatedIO","AbridgedPacketCodec","props","obfuscateTag","ConnectionTCPAbridged","initHeader","_encrypt","encryptor","_decrypt","decryptor","packetCodec","ok","toJSON","randomReversed","encryptKey","encryptIv","decryptKey","decryptIv","readExactly","ConnectionTCPFull","MTProtoPlainSender","StorageSession","CACHE_NAME","_storageKey","cached","_sessionData","_callback","_authKeys","mainDcId","hashes","skipOnUpdate","_serverAddress","idb","_delete","del","_fetchFromCache","_saveToCache","localStorage","removeItem","getItem","setItem","_takeoutId","_updateStates","_authKey","sessionInfo","_sessionString","_loadFromSessionString","skipUpdateStorage","_updateStorage","asHex","mainDcIdStr","mainDcKey","StringSession","decode","readUInt8","serverAddressLen","readInt16BE","dcBuffer","addressBuffer","addressLengthBuffer","writeInt16BE","portBuffer","encode","Memory","CacheApiSession","LocalStorageSession","IdbSession","CallbackSession","api","sub","parseTl","serializeDate","tlContent","schemeContent","CACHING_SUPPORTED","CACHE_KEY","extractParams","fileContent","f","functions","d","isFunction","argToBytes","writeDoubleLE","getArgFromReader","arg","isVector","useVectorId","flagIndicator","skipConstructorId","createClasses","classesType","classes","classParams","subclassOfId","argsConfig","namespace","fullName","VirtualClass","argName","isFlag","flagIndex","idForBytes","flagCalculate","boxed","charAt","definitions","fromCache","jsonCache","loadFromCache","constructorParamsApi","functionParamsApi","constructorParamsSchema","functionParamsSchema","loadFromTlSchemas","obj1","obj2","mergeWithNamespaces","buildApiFromTlSchema","gzipped","toBytes","gzip","ungzip","containerLength","before","tlMessage","RpcError","innerCode","snakeToCamelCase","_","variableSnakeToCamelCase","CORE_TYPES","AUTH_KEY_TYPES","findAll","regex","matches","RegExp","exec","fromLine","line","argsMatch","currentConfig","hexId","representation","brace","argType","buildArgConfig","flagMatch","vectorMatch","ignoreIds","o","objAll","objByName","objByType","commentIndex","trim","followingTypes","dt","fill","t","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","loaded","__webpack_modules__","__webpack_exports__","O","chunkIds","priority","notFulfilled","fulfilled","every","splice","getter","__esModule","definition","defineProperty","enumerable","chunkId","miniCssF","globalThis","Function","prop","prototype","Symbol","toStringTag","nmd","paths","children","scriptUrl","importScripts","currentScript","src","scripts","getElementsByTagName","installedChunks","chunkLoadingGlobal","parentChunkLoadingFunction","moreModules","runtime"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/index.html b/dist/index.html index 416092c3..d3619d42 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.694bb1485bda2f2e118a.js b/dist/main.694bb1485bda2f2e118a.js new file mode 100644 index 00000000..0a701cfa --- /dev/null +++ b/dist/main.694bb1485bda2f2e118a.js @@ -0,0 +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(927),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){var o;throw new Error(null===(o=t.error)||void 0===o?void 0:o.message)}}))}(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),l=n(1396);function f(e){if(!e)return;const t=(0,l.X)(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:(0,l.X)(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}},8005:(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(6752),i=n(8033),c=n(5116);const l=({className:e,sender:t,children:n})=>{const{openUserInfo:o}=(0,c.uC)(),d=(0,r.I4)((()=>{t&&o({id:t.id})}),[t,o]);return t?r.ZP.createElement(i.Z,{className:(0,s.Z)("UserLink",e),onClick:d},n):n},f=({className:e,message:t,children:n})=>{const{focusMessage:o}=(0,c.uC)(),d=(0,r.I4)((()=>{t&&o({chatId:t.chatId,messageId:t.id})}),[o,t]);return t?r.ZP.createElement(i.Z,{className:(0,s.Z)("MessageLink",e),onClick:d},n):n},h=({className:e,chatId:t,children:n})=>{const{openChat:o}=(0,c.uC)(),d=(0,r.I4)((()=>{t&&o({id:t})}),[t,o]);return t?r.ZP.createElement(i.Z,{className:(0,s.Z)("ChatLink",e),onClick:d},n):n},m=({className:e,groupCall:t,children:n})=>{const{joinGroupCall:o}=(0,c.uC)(),d=(0,r.I4)((()=>{t&&o({id:t.id,accessHash:t.accessHash})}),[t,o]);return t?r.ZP.createElement(i.Z,{className:(0,s.Z)("GroupCallLink",e),onClick:d},n):n};function p(e,t,n,s,i,c,l={}){if(!t.content.action)return[];const{text:p,translationValues:v,amount:b,currency:w,call:I}=t.content.action,C=[],S={...l,maxTextLength:32};let E,P=e("Chat.Service.Group.UpdatedPinnedMessage1"!==p||i?p:"Message.PinnedGenericMessage",v&&v.length?v:void 0);return P.includes("%payment_amount%")&&(E=y(P,"%payment_amount%",(0,u.x)(b,w,e.code)),P=E.pop(),C.push(...E)),E=y(P,"%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(h,{className:"action-link",chatId:t.id},t&&(0,a.Z)(u))}(e,t,n)}(e,n,l.asPlain)||" ":"User"),P=E.pop(),C.push(...E),E=y(P,"%target_user%",s?s.map((e=>g(e,l.asPlain))).filter(Boolean):"User"),P=E.pop(),C.push(...E),E=y(P,"%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:h,isEmbedded:m,asPlain:p}=n,g=m&&u&&!s&&!i&&!c&&!l;let y=(0,d.Z)(u,h);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(f,{className:"action-link",message:t},(0,a.Z)(y)),"»"):r.ZP.createElement(f,{className:"action-link",message:t},(0,a.Z)(y))}(e,i,S):"a message"),P=E.pop(),C.push(...E),E=y(P,"%product%",i?function(e){return e.content&&e.content.invoice?e.content.invoice.title:"a product"}(i):"a product"),P=E.pop(),C.push(...E),E=y(P,"%target_chat%",c?function(e,t){const n="another chat";return t?n:r.ZP.createElement(h,{className:"action-link",chatId:e},n)}(c,l.asPlain):"another chat"),C.push(...E),l.asPlain?C.join("").trim():I?function(e,t){return r.ZP.createElement(m,{groupCall:e},t)}(I,C):C}function g(e,t){const n=(0,d.Z)((0,o.Js)(e));return t?n:r.ZP.createElement(l,{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.push(n),e):(t.innerText=n,e.push(t.innerHTML),e)),[])}(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.push(t),e;const n=t.toLowerCase(),o=n.indexOf(u.toLowerCase()),d=n[o+u.length];if(o<0||d&&d.match(l))return e.push(t),e;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.push(t),e;const n=t.match(g);if(!n||!n.length)return e.push(t),e;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.push(d),e;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)=>{if("string"!=typeof n)return e.push(n),e;const o=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}),[]);return[...e,...o]}),[])}const g=new RegExp(`${d.FM}|${d.uW}`,"ig");function y(e,t){return e.reduce(((e,n)=>{if("string"!=typeof n)return e.push(n),e;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:()=>u});var r=n(4050),o=n(5116),d=n(1638);const u=(0,o.c$)(((e,{userId:t})=>({userOrChat:t?(0,d.dy)(e,t):void 0})))((({username:e,userOrChat:t,children:n})=>{const{openChat:d,openChatByUsername:u}=(0,o.uC)();return r.ZP.createElement("a",{onClick:()=>{t?d({id:t.id}):e&&u({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"),Z=(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:Z,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,hT:()=>M,YQ:()=>A,rS:()=>k,t_:()=>T,Ov:()=>N,EN:()=>L,pn:()=>R,Hk:()=>D,Vk:()=>O,mo:()=>Z,qU:()=>_,ul:()=>x,NM:()=>F,Qx:()=>B,mw:()=>$,oB:()=>U,zy:()=>j,CX:()=>W,xS:()=>G,b6:()=>H,AR:()=>V,r_:()=>z,o_:()=>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,VC:()=>Re,FM:()=>De,uW:()=>Oe,g$:()=>Ze,FS:()=>_e,FD:()=>xe,aw:()=>Fe,FV:()=>Be,Nf:()=>$e,WS:()=>Ue,DU:()=>je,EG:()=>We,t4:()=>Ge,sR:()=>He,$O:()=>Ve,Bg:()=>ze,vi:()=>Qe,Db:()=>Ke,mU:()=>Je,p3:()=>qe,It:()=>Ye,Vv:()=>Xe,g:()=>et,Hc:()=>tt,EH:()=>nt,Ro:()=>rt,aC:()=>ot,LH:()=>dt});const r="Telegram",o=" [Inactive]",d="Telegram WebZ",u="1.28.5",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-v7",S=[1,5,10,50,100,500],E="undefined"!=typeof window&&window.innerHeight>=900,P=1,M=E?60:40,A=2*M,k=72,T=E?30:25,N=100,L=42,R=42,D=20,O=30,Z=200,_=500,x=20,F=!1,B=1,$=1,U=0,j=2,W=j,G=16,H=17,V=15,z=1e4,Q=3e3,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="The message is not supported on this version of Telegram.",De="((ftp|https?):\\/\\/)?((www\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\.[a-zA-Z0-9()]{1,63})\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)",Oe="(@[\\w\\d_-]+)",Ze=/^tg:(\/\/)?([?=&\d\w_-]+)?/gm,_e=/^(?:https?:\/\/)?(?:t\.me\/)/gm,xe=new Set(["AU","BD","CA","CO","EG","HN","IE","IN","JO","MX","MY","NI","NZ","PH","PK","SA","SV","US"]),Fe="777000",Be="1271266957",$e=0,Ue=1,je=10,We=5,Ge=2147483646,He="en",Ve="android",ze=["android","ios","tdesktop","macos"],Qe="TelegramTips",Ke=["ar","pt-br","id","it","ko","ms","pl","es","tr"],Je="https://bugs.telegram.org/?tag_ids=41&sort=time",qe="#A2AF8E",Ye="#0F0F0F",Xe="#0a0a0a8c",et="rgba(90, 110, 70, 0.6)",tt=50,nt=604680,rt=100,ot=100*rt,dt=!1},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,{ZP:()=>s,zG:()=>i,YW:()=>c});var r=n(4050);const o="tt-event-heavy-animation-start",d="tt-event-heavy-animation-end";let u,a=!1;const s=(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])};function i(){return a}function c(e=1e3){function t(){u&&(clearTimeout(u),u=void 0),a=!1,document.dispatchEvent(new Event(d))}return a||(a=!0,document.dispatchEvent(new Event(o))),u&&(clearTimeout(u),u=void 0),u=window.setTimeout(t,e),t}},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={},a=new Map;function s(e,t,n,r=!1){const o=c(t,e);l(o,e,r)?function(e,t,n){d[e]||(d[e]=0,document.addEventListener(e,m)),function(e){return u[e]||(u[e]=new Map),u[e]}(e).set(t,n),function(e){const t=a.get(e);if(t)return t;const n=new Set;return a.set(e,n),n}(t).add(e),d[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){d[e]--,d[e]||document.removeEventListener(e,m),u[e].delete(t),a.get(t).delete(e)}function h(e){const t=a.get(e);t&&(t.forEach((t=>f(t,e))),a.delete(e))}function m(e){const t=u[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",(()=>{const e=Object.keys(d).length,t=Object.values(d).reduce(((e,t)=>e+t),0),n=Object.keys(u).length,r=Object.values(u).reduce(((e,t)=>e+t.size),0),o=a.size,s=Array.from(a.values()).reduce(((e,t)=>e+t.size),0);console.warn("DELEGATED EVENTS STATS",{delegatedHandlersCount1:t,delegatedHandlersCount2:r,delegatedEventTypesCount:s,delegationRegistriesCount:n,delegationElementsCount:o,documentListenersCount:e})}))},2916:(e,t,n)=>{n.d(t,{Z:()=>y});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","role"]),i={autoPlay:"autoplay",autoComplete:"autocomplete"},c={};function l(e,t,n,o,c,{skipComponentUpdate:y=!1,forceIndex:v=!1,fragment:b,moveDirection:w}={}){if(!y&&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)),!y&&n&&(0,r.op)(n)&&n.componentInstance.isMounted&&h(n,o,c,e),t===n)return n;if(!t&&n){(0,r.op)(n)&&(n=f(n,o,c,e));const t=m(n);(0,r.CD)(n,t),v&&e.childNodes[c]?e.insertBefore(t,e.childNodes[c]):(b||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,c,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(w){const n=(0,r.U9)(t),o=e.childNodes["up"===w?c:c+1];o?e.insertBefore(n,o):(b||e).appendChild(n)}o||function(e,t,n){const r=Object.keys(e.props),o=Object.keys(t.props);r.forEach((r=>{const o=e.props[r],d=t.props[r];void 0!==o&&(void 0===d||o!==d&&r.startsWith("on"))&&function(e,t,n){"className"===t?e.className="":"value"===t?e.value="":"style"===t?e.style.cssText="":"dangerouslySetInnerHTML"===t?e.innerHTML="":t.startsWith("on")?(0,u.xg)(e,t,n,t.endsWith("Capture")):t.startsWith("data-")||t.startsWith("aria-")||s.has(t)?e.removeAttribute(t):a.has(t)||delete e[i[t]||t]}(n,r,o)})),o.forEach((r=>{const o=e.props[r],d=t.props[r];void 0!==d&&d!==o&&g(n,r,d)}))}(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)&&null==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;const s=null!=a;if(s&&!o.has(a))return l(n,r,void 0,t,-1),e;if(!s){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=>{void 0!==n[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){"className"===t?e.className=n:"value"===t?e.value=n:"style"===t?e.style.cssText=n:"dangerouslySetInnerHTML"===t?e.innerHTML=n.__html:t.startsWith("on")?(0,u.Oo)(e,t,n,t.endsWith("Capture")):t.startsWith("data-")||t.startsWith("aria-")||s.has(t)?e.setAttribute(t,n):a.has(t)||(e[i[t]||t]=n)}const y={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:()=>Z,I4:()=>_,sO:()=>x,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,o,d){const{cursor:u,byCursor:s}=l.hooks.effects,i=l;function c(){if(!i.isMounted)return;const{cleanup:e}=s[u];if("function"==typeof e)try{let t;if(r.eM&&(t=performance.now()),e(),r.eM){const e=performance.now()-t,n=i.name;e>7&&console.warn(`[Teact] Slow cleanup at effect cursor #${u}: ${n}, ${Math.round(e)} ms`)}}catch(e){(0,a.S)(e)}}function f(){if(!i.isMounted)return;let e;if(r.eM&&(e=performance.now()),s[u].cleanup=n(),r.eM){const t=performance.now()-e,n=i.name;t>7&&console.warn(`[Teact] Slow effect at cursor #${u}: ${n}, ${Math.round(t)} ms`)}}if(void 0!==s[u]&&o&&s[u].dependencies){if(o.some(((e,t)=>e!==s[u].dependencies[t]))){if(d){const e=o.reduce(((e,t,n)=>{const r=s[u].dependencies[n];return t!==r&&e.push(`${n}: ${r} => ${t}`),e}),[]);console.log(`[Teact] Effect "${d}" caused by dependencies.`,e.join(", "))}t(c),e(f)}}else d&&console.log(`[Teact] Effect "${d}" caused by missing dependencies.`),t(c),e(f);s[u]={effect:n,dependencies:o,cleanup:s[u]?s[u].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 Z(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,n){return Z((()=>e),t,n)}function x(e){return Z((()=>({current:e})),[])}function F(e,t=u.Z,n){return function(o){const d=x(o),a=x();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.warn("COMPONENTS",(0,d.Xo)(Object.values(C),"renderCount","desc"))}));const B={createElement:y,Fragment:c}},5116:(e,t,n)=>{n.d(t,{ZP:()=>h,R3:()=>I,Rd:()=>C,uC:()=>S,Q6:()=>E,ll:()=>P,Iq:()=>M,c$:()=>A});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),l=n(8674);function f(){return(f=Object.assign||function(e){for(var t=1;t7&&console.warn(`[TeactN] Slow containers update: ${Math.round(t)} ms`)}}],y={},v=new Map,b=(0,a.$6)(w);function w(e=!1){e||!(0,l.zG)()?g.forEach((e=>e(m))):(0,a.T2)(b)}function I(e,t){"object"==typeof e&&e!==m&&(m=e,null!=t&&t.forceSyncOnIOs?w(!0):b(null==t?void 0:t.forceOnHeavyAnimation))}function C(){return m}function S(){return y}function E(e,t){p[e]||(p[e]=[],y[e]=(t,n)=>{!function(e,t,n){p[e]&&p[e].forEach((e=>{const r=e(m,y,t);r&&I(r,n)}))}(e,t,n)}),p[e].push(t)}function P(e){g.push(e)}function M(e){const t=g.indexOf(e);-1!==t&&g.splice(t,1)}function A(e=(()=>({}))){return t=>function n(o){n.DEBUG_contentComponentName=t.name;const[a]=(0,r.eJ)((0,u.Z)(v)),i=(0,d.Z)();(0,r.d4)((()=>()=>{v.delete(a)}),[a]);let l=v.get(a);if(l||(l={mapStateToProps:e,ownProps:o,areMappedPropsChanged:!1,forceUpdate:i,DEBUG_updates:0,DEBUG_componentName:t.name},v.set(a,l)),l.areMappedPropsChanged&&(l.areMappedPropsChanged=!1),!l.mappedProps||!(0,s.Z)(l.ownProps,o)){l.ownProps=o;try{l.mappedProps=e(m,o)}catch(e){(0,c.S)(e)}}return r.ZP.createElement(t,f({},l.mappedProps,o))}}o.eM&&(window.getGlobal=C,document.addEventListener("dblclick",(()=>{console.warn("GLOBAL CONTAINERS",(0,i.Xo)(Array.from(v.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(1638),l=n(307),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(307),a=n(663),s=n(1638),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});break}}}))},7895:(e,t,n)=>{var r=n(5116),o=n(3716),d=n(7361),u=n(663),a=n(6917),s=n(1638),i=n(1622),c=n(7926);!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,l=(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)(l,t===o.zy),(0,c.$)(),(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"),d.s$&&document.body.classList.add("is-safari")})),(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},{forceSyncOnIOs:!0})}))},3781:(e,t,n)=>{var r=n(5116),o=n(307);(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:()=>c,Bf:()=>l,G9:()=>f,ZV:()=>h,eA:()=>m,Ru:()=>p,pK:()=>g,l6:()=>y,zX:()=>v,U:()=>b,GM:()=>w,hu:()=>I,RT:()=>C,Hp:()=>S,Nl:()=>E,VE:()=>P,Mg:()=>M,Qm:()=>A,H5:()=>k,q8:()=>T,Hd:()=>N,OE:()=>L,pE:()=>R,i4:()=>D,Sm:()=>O,cc:()=>Z,P4:()=>_,O:()=>x,wG:()=>B,Fu:()=>$,SB:()=>U,zF:()=>j,ih:()=>W,$l:()=>G});var r=n(6137),o=n(3716),d=n(782),u=n(5527),a=n(790),s=n(5765);const i=Date.now()/1e3+31622400;function c(e){return"number"==typeof e?e>0:!e.startsWith("-")}function l(e){return f(e)||h(e)}function f(e){return"chatTypeBasicGroup"===e.type}function h(e){return"chatTypeSuperGroup"===e.type}function m(e){return"chatTypeChannel"===e.type}function p(e){return"chatTypePrivate"===e.type||"chatTypeBasicGroup"===e.type}function g(e){return e===o.FV}function y(e){switch(e.type){case"chatTypePrivate":return"PrivateChat";case"chatTypeBasicGroup":case"chatTypeSuperGroup":return"AccDescrGroup";case"chatTypeChannel":return"AccDescrChannel";default:return"Chat"}}function v(e){if("chatTypePrivate"===e.type||"chatTypeSecret"===e.type)return e.id}function b(e,t,n,r=!1){return r||n&&t.id===n.id&&n.isSelf?e("SavedMessages"):t.title||e("HiddenName")}function w(e){if(e.fullInfo)return e.fullInfo.about}function I(e){const{username:t}=e;if(t)return`https://t.me/${t}`;const{inviteLink:n}=e.fullInfo||{};return n}function C(e,t="normal"){if(e.avatarHash)switch(t){case"big":return`profile${e.id}?${e.avatarHash}`;default:return`avatar${e.id}?${e.avatarHash}`}}function S(e){return!e.lastMessage}function E(e){return Boolean(e.adminRights)}function P(e,t){return!!e.adminRights&&e.adminRights[t]}function M(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 A(e,t){return t!==r._f||!(e.isRestricted||e.migratedTo||e.isNotJoined||g(e.id))&&(!!e.isCreator||!!c(e.id)||(m(e)?P(e,"postMessages"):E(e)||!M(e,"sendMessages")))}function k(e,t=!1){if(!e)return{canAttachMedia:!1,canAttachPolls:!1,canSendStickers:!1,canSendGifs:!1,canAttachEmbedLinks:!1};const n=E(e);return{canAttachMedia:n||!M(e,"sendMedia"),canAttachPolls:(n||!M(e,"sendPolls"))&&(!c(e.id)||t),canSendStickers:n||!M(e,"sendStickers"),canSendGifs:n||!M(e,"sendGifs"),canAttachEmbedLinks:n||!M(e,"embedLinks")}}function T(e,t,n){if(null!=t&&t.sendMessages){const{untilDate:n}=t;return n&&n{const c=t[e];return c&&function(e,t,n,r,d,u,a,s){if(!e.isListed)return!1;const{id:i,type:c,unreadMentionsCount:l}=e;if(null!=u&&u.has(i))return!1;if(null!=a&&a.has(i))return!0;if(null!=s&&s.has(i))return!0;if(t.excludeArchived&&e.folderId===o.WS)return!1;if(t.excludeRead&&!e.unreadCount&&!l&&!e.hasUnreadMark)return!1;if(t.excludeMuted&&!l&&D(e,r,d))return!1;if("chatTypePrivate"===c){const e=n[i];if(e){const{type:n,isContact:r}=e;if("userTypeBot"===n){if(t.bots)return!0}else{if(t.contacts&&r)return!0;if(t.nonContacts&&!r)return!0}}}else{if("chatTypeChannel"===c)return!!t.channels;if("chatTypeBasicGroup"===c||"chatTypeSuperGroup"===c)return!!t.groups}return!1}(c,r,n,d,u,a,s,i)})),r.pinnedChatIds]}function x(e,t,n,r="all",o=!1){const u=new Set(t),a=n?new Set(n):void 0,s=(null==n?void 0:n.reduce(((t,n)=>{const o=e[n];return o&&u.has(o.id)&&F(o,r)&&t.push(o),t}),[]))||[],i=t.reduce(((t,n)=>{const o=e[n];return!o||a&&a.has(o.id)||!F(o,r)||t.push(o),t}),[]);return{pinnedChats:s,otherChats:o?i:(0,d.Xo)(i,L,"desc")}}function F(e,t){return e.lastMessage&&!e.migratedTo&&!e.isRestricted&&!e.isNotJoined&&!("all"===t&&e.folderId===o.WS)&&!("archived"===t&&e.folderId!==o.WS)}function B(e,t){const n=new Set(t);return{pinnedChats:e.pinnedChats.filter((({id:e})=>n.has(e))),otherChats:e.otherChats.filter((({id:e})=>n.has(e)))}}function $(e,t,n,r,o,d){const[u]=_(e,t,n,r,o,d);let a=!1;return{unreadDialogsCount:u.reduce(((e,n)=>{const r=t[n];if(null==r||!r.lastMessage||null!=r&&r.isRestricted||null!=r&&r.isNotJoined)return e;const u=r.unreadCount||r.hasUnreadMark;return u&&e++,!a&&(r.unreadMentionsCount||u&&!D(r,o,d))&&(a=!0),e}),0),hasActiveDialogs:a}}function U(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}=o;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]=_(e,t,n,r,o,d),{pinnedChats:s,otherChats:i}=x(t,u,a,"folder",!0);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 j(e,t,n){if(n&&!c(t))return n.isSelf?e("FromYou"):(0,u.Vl)(n)}function W(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")}function G(e,t,n,r,o){if(!r)return t;const d=(0,s.W)(r);return t.filter((t=>{const r=n[t];return!!r&&d(b(e,r,void 0,t===o))}))}},2858:(e,t,n)=>{n.d(t,{uw:()=>se,$l:()=>o.$l,kK:()=>r.kK,H5:()=>o.H5,MR:()=>J,kw:()=>r.kw,cc:()=>o.cc,Qm:()=>o.Qm,RT:()=>o.RT,GM:()=>o.GM,hu:()=>o.hu,N0:()=>te,OE:()=>o.OE,Hd:()=>o.Hd,U:()=>o.U,l6:()=>o.l6,T7:()=>y,SB:()=>o.SB,Fu:()=>o.Fu,VE:()=>o.VE,XV:()=>ae,Sc:()=>de,N5:()=>Z,oP:()=>_,qp:()=>N,w6:()=>k,R5:()=>ue,$D:()=>p,aE:()=>B,ep:()=>Y,c0:()=>X,eO:()=>W,Tp:()=>c,kG:()=>q,Ti:()=>Q,DH:()=>z,KK:()=>f,O$:()=>R,t9:()=>j,Y5:()=>O,zF:()=>o.zF,q8:()=>o.q8,_O:()=>g,bf:()=>F,MK:()=>h,UD:()=>m,b7:()=>D,kd:()=>x,s1:()=>G,F$:()=>H,Cg:()=>V,bV:()=>ne,HV:()=>re,zX:()=>o.zX,OU:()=>E,RI:()=>P,Ow:()=>ce,Rs:()=>r.Rs,Vl:()=>r.Vl,Js:()=>r.Js,db:()=>r.db,Tq:()=>r.Tq,jC:()=>oe,BM:()=>ee,u8:()=>L,Lo:()=>I,Ul:()=>S,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:()=>w,CD:()=>A,rl:()=>$,hC:()=>U,CI:()=>M,B4:()=>v,ss:()=>b,jM:()=>C,cS:()=>r.cS,YC:()=>o.YC,kM:()=>r.kM,Mg:()=>o.Mg,Ak:()=>l,O:()=>o.O,P4:()=>o.P4,wG:()=>o.wG,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=new RegExp(u.FM,"i");function c(e){const{chatId:t,id:n}=e;return function(e,t){return`msg${e}-${t}`}(t,n)}function l(e){const t=e.match(/^msg(-?\d+)-(\d+)/);return{chatId:t[1],messageId:Number(t[2])}}function f(e){return e.previousLocalId||e.id}function h(e,t,n=!1){const{text:r,photo:o,video:d,audio:a,voice:s,document:i,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():a?`${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")}`:s?`${n?"":"🎤 "}${m||e("AttachAudio")}`:i?`${n?"":"📎 "}${m||i.fileName}`:l?e("AttachContact"):f?`${n?"":"📊 "}${f.summary.question}`:h?"Invoice":r?m:u.VC}function m(e){const{text:t,sticker:n,photo:r,video:o,audio:d,voice:a,document:s,poll:i,webPage:c,contact:l,invoice:f}=e.content;return t?t.text:n||r||o||d||a||s||l||i||c||f?void 0:u.VC}function p(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 g(e){const{text:t}=e.content;if(t&&t.text.length<=6&&1===p(e))return t.text}function y(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(i)),!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(i)}}if(!n&&t&&(n=t.text.match(i)),n)return{url:n[0],domain:n[3]}}function v(e){return e.isOutgoing}function b(e){return Boolean(e.replyToMessageId)}function w(e){return Boolean(e.forwardInfo)}function I(e){return!!e.content.action}function C(e){return e.chatId===u.aw&&Math.round(e.id)!==e.id}function S(e){return Boolean(e.senderId)&&!(0,o.YC)(e.senderId)&&v(e)}function E(e,t){return(0,o.YC)(t.id)?(0,r.Js)(t):(0,o.U)(e,t)}function P(e){return e.sendingState?"messageSendingStateFailed"===e.sendingState?"failed":"pending":"succeeded"}function M(e){return e.id>=u.AE}function A(e){return e.content.action&&"historyClear"===e.content.action.type}function k(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=c(e);return r?`${d}.jpg`:t.voice?a.m5?`${d}.ogg`:`${d}.wav`:d}var T=n(5376);function N(e){return e.content}function L(e){return Boolean(R(e)||D(e)||B(e)||F(e)||function(e){return e.content.contact}(e)||j(e)||Z(e)||_(e)||x(e))}function R(e){return e.content.photo}function D(e){return e.content.video}function O(e){const{video:t}=e.content;return null!=t&&t.isRound?t:void 0}function Z(e){return e.content.action}function _(e){return e.content.audio}function x(e){return e.content.voice}function F(e){return e.content.sticker}function B(e){return e.content.document}function $(e){const t=B(e);return t?"photo"===t.mediaType:void 0}function U(e){const t=B(e);return t?"video"===t.mediaType:void 0}function j(e){return e.content.poll}function W(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 V(e){var t;return null===(t=G(e))||void 0===t?void 0:t.video}function z(e){var t;return null===(t=function(e){const t=R(e)||D(e)||B(e)||F(e)||H(e)||V(e);if(t)return t.thumbnail}(e))||void 0===t?void 0:t.dataUri}function Q(e,t){const{photo:n,video:r,sticker:o,audio:d,voice:u,document:a}=e.content,s=H(e),i=V(e),l=r||i,f=n||s;if(!(f||l||o||d||u||a))return;const h=(f||l||o||d||u||a).id,m=`${c(e)}${h?`:${h}`:""}`;if(l)switch(t){case"micro":case"pictogram":return`${m}?size=m`;case"inline":return ee(e)?void 0:K(l,m);case"viewerPreview":return`${m}?size=m`;case"viewerFull":return K(l,m);case"download":return`${m}?download`}if(f)switch(t){case"micro":case"pictogram":return`${m}?size=m`;case"inline":return ee(e)?void 0:`${m}?size=x`;case"viewerPreview":return`${m}?size=x`;case"viewerFull":case"download":return`${m}?size=z`}if(a)switch(t){case"micro":case"pictogram":case"inline":case"viewerPreview":if(!(0,T.v6)(a)||ee(e))return;return`${m}?size=m`;case"viewerFull":case"download":return m}if(o)switch(t){case"micro":return;case"pictogram":return`${m}?size=m`;case"inline":return m;case"download":return`${m}?download`}if(d)switch(t){case"micro":case"pictogram":return J(d)?`${m}?size=m`:void 0;case"inline":return K(d,m);case"download":return`${m}?download`}if(u)switch(t){case"micro":case"pictogram":return;case"inline":return m;case"download":return`${m}?download`}}function K(e,t){return a.I_&&a.s$?`${t}?fileSize=${e.size}&mimeType=${e.mimeType}`:t}function J(e){return e.thumbnailSizes&&e.thumbnailSizes.length>0}function q(e,t){const{sticker:n,video:r,audio:o,voice:u}=e.content,s=r||V(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 Y(e){const{photo:t,video:n,document:r}=e.content,o=H(e),d=V(e);if(t||o)return`photo${e.date}.jpeg`;const{fileName:u}=n||d||r||{};return u}function X(e){const{video:t,document:n}=e.content,r=V(e),{size:o}=t||r||n||{};return o}function ee(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 te(e,t,n=!1){const r=ue(e,t,n?"media":"inlineMedia");return n?r.reverse():r}function ne(e){return e.sizes.find((e=>"z"===e.type))||e.sizes.find((e=>"y"===e.type))||re(e)}function re(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 oe(e){if(e.width&&e.height)return e}function de(e,t,n=!1){const r=M(e);return{isUploading:r,isTransferring:r||n,transferProgress:Number(t)}}function ue(e,t,n){let r;switch(n){case"media":r=e=>{const t=D(e);return R(e)||t&&!t.isRound&&!t.isGif};break;case"documents":r=B;break;case"links":r=e=>G(e)||function(e){const{text:t}=e.content,n=t&&t.text.match(i);if(n)return{url:n[0],domain:n[3]}}(e);break;case"audio":r=_;break;case"voice":r=e=>{const t=D(e);return x(e)||t&&t.isRound};break;case"inlineMedia":r=e=>{const t=D(e);return R(e)||t&&!t.isRound&&!t.isGif||$(e)||U(e)};break;default:return[]}return t.reduce(((t,n)=>(e[n]&&r(e[n])&&t.push(n),t)),[])}function ae(e){const{audio:t,voice:n,video:r}=N(e),o=t||n||r||V(e);if(o)return o.duration}function se(e,t){return`${e}_${t}`}const ie={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 ce(e){const{message:t,code:n,param:r}=e,{field:o,message:d}=r?ie[r]:ie[n];return{field:o,message:d,description:t}}},5527:(e,t,n)=>{n.d(t,{Vl:()=>i,Js:()=>c,Tq:()=>l,kM:()=>f,NB:()=>h,cS:()=>m,kw:()=>p,Z0:()=>g,kK:()=>y,db:()=>v,Rs:()=>b});var r=n(3716),o=n(790),d=n(782),u=n(2267),a=n(5765);const s=[1,8,5,2,7,4,6];function i(e){if(e)switch(e.type){case"userTypeBot":case"userTypeRegular":return e.firstName||e.lastName;case"userTypeDeleted":case"userTypeUnknown":return"Deleted";default:return}}function c(e){if(e){if(h(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 l(e,t,n,d){if(t.id===r.aw)return e("ServiceNotifications").toLowerCase();if(t.type&&"userTypeBot"===t.type)return e("Bot");if(!n)return"";switch(n.type){case"userStatusEmpty":return e("ALongTimeAgo");case"userStatusLastMonth":return e("WithinAMonth");case"userStatusLastWeek":return e("WithinAWeek");case"userStatusOffline":{const{wasOnline:t}=n;if(!t)return e("LastSeen.Offline");const r=new Date((new Date).getTime()+1e3*d),u=new Date(1e3*t);if(u>=r)return e("LastSeen.JustNow");const a=new Date(r.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*d))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(r.getDate()-1),i.setHours(0,0,0,0),u>new Date(i.getTime()+1e3*d)?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 f(e,t){const{id:n,type:o}=e;return!!t&&n!==r.aw&&"userStatusOnline"===t.type&&"userTypeBot"!==o}function h(e){return!e.noStatus&&"userTypeBot"!==e.type&&e.id!==r.aw&&("userTypeDeleted"===e.type||"userTypeUnknown"===e.type)}function m(e){return"userTypeBot"===e.type}function p(e){return!e.isContact&&!m(e)}function g(e,t,n,r,o=0){return(0,d.Xo)(e,(e=>{const d=(0,u.b)(o);if(r&&r.includes(e))return d+172800-(r.length-r.indexOf(e));const a=t[e],s=n[e];if(!a||!s)return 0;if("userStatusOnline"===s.type)return s.expires;if("userStatusOffline"===s.type&&s.wasOnline)return s.wasOnline;switch(s.type){case"userStatusRecently":return d-86400;case"userStatusLastWeek":return d-604800;case"userStatusLastMonth":return d-18144e3;default:return 0}}),"desc")}function y(e,t,n){if(!n)return e;const r=(0,a.W)(n);return e.filter((e=>{const n=t[e];if(!n)return!1;const o=c(n);return o&&r(o)||r(n.username)}))}function v(e){return"number"==typeof e?Math.abs(e):Math.abs(Number(e))}function b(e){const t=e?v(e.id)%7:0;return s[t]}},6788:(e,t,n)=>{n.d(t,{Mg:()=>u,B1:()=>a,SL:()=>s,a4:()=>i,GL:()=>c,fZ:()=>l,Pi:()=>h,vv:()=>m,Dd:()=>p});var r=n(3716),o=n(782),d=n(1638);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:o}=e.chats,d=f(e,t,n,r);return d?s(e,{...o,[t]:d}):e}function c(e,t){const n=Object.keys(t).reduce(((n,r)=>{const o=f(e,r,t[r]);return o&&(n[r]=o),n}),{});return e=s(e,{...e.chats.byId,...n})}function l(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=f(e,d,t[d]);n&&(o[d]=n,r||(r=!0))}return o}),{});return r?e=s(e,{...n,...o}):e}function f(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||[]]}};if(s.id&&s.type)return s}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]}})),i(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)))),i(e,t,{isNotJoined:!0})}},307:(e,t,n)=>{n.d(t,{O4:()=>we,c_:()=>h,fZ:()=>r.fZ,m6:()=>f,aK:()=>ve,aJ:()=>ye,zn:()=>Y,Sh:()=>G,$S:()=>I,bp:()=>Ne,WY:()=>Le,K4:()=>g,bV:()=>y,GK:()=>z,M6:()=>T,i9:()=>L,Dd:()=>r.Dd,vy:()=>F,rB:()=>Ie,g_:()=>_,Mg:()=>r.Mg,SL:()=>r.SL,Pb:()=>ae,w3:()=>P,BI:()=>pe,lr:()=>ge,pf:()=>l,ps:()=>q,s5:()=>$,y9:()=>C,nA:()=>Me,_7:()=>ke,Q$:()=>Pe,Dq:()=>Te,vT:()=>Ee,QH:()=>Ae,Ob:()=>N,a4:()=>r.a4,B1:()=>r.B1,vv:()=>r.vv,Pi:()=>r.Pi,cY:()=>m,GL:()=>r.GL,Wy:()=>s,wV:()=>k,cq:()=>M,rq:()=>Z,No:()=>ee,Og:()=>te,xv:()=>re,px:()=>ne,xj:()=>v,c1:()=>le,z5:()=>ce,qr:()=>ue,dx:()=>se,fw:()=>me,H9:()=>he,HN:()=>be,ff:()=>b,P4:()=>p,x1:()=>V,TM:()=>Se,Fn:()=>A,Rg:()=>O,z3:()=>D,IM:()=>x,Xg:()=>S,j6:()=>E,lG:()=>R,IE:()=>Ce,Nq:()=>j,Lm:()=>Q,Q3:()=>K,eD:()=>W});var r=n(6788),o=n(6137),d=n(3716),u=n(1638),a=n(782);function s(e,t,n=o._f,r="thread",u){const{messageLists:a}=e.messages;let s=a;if(u||d.Cg)s=t?[{chatId:t,threadId:n,type:r}]:[];else if(t){const e=a[a.length-1];e&&e.chatId===t&&e.threadId===n&&e.type===r||(s=e&&e.chatId===d.AJ?[...a.slice(0,-1),{chatId:t,threadId:n,type:r}]:[...a,{chatId:t,threadId:n,type:r}])}else s=a.slice(0,-1);return{...e,messages:{...e.messages,messageLists:s}}}function i(e,t,n){return c(e,t,{byId:n})}function c(e,t,n){const r=e.messages.byChatId[t]||{byId:{},threadsById:{}};return{...e,messages:{...e.messages,byChatId:{...e.messages.byChatId,[t]:{...r,...n}}}}}function l(e,t,n,r,o){return function(e,t,n,r){const o=e.messages.byChatId[t];return c(e,t,{threadsById:{...null==o?void 0:o.threadsById,[n]:{...null==o?void 0:o.threadsById[n],...r}}})}(e,t,n,{[r]:o})}function f(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=h(e,t,n[t])})),e}function h(e,t,n){const r=(0,u.Zw)(e,t);return r&&Object.keys(n).every((e=>Boolean(r[Number(e)])))?e:i(e,t,{...n,...r})}function m(e,t,n,r){const o=(0,u.Zw)(e,t)||{},d={...o[n],...r};return d.id?i(e,t,{...o,[n]:d}):e}function p(e,t,n,r){const o=(0,u.Fn)(e,t)||{},d={...o[n],...r};return d.id?P(e,t,{...o,[n]:d}):e}function g(e,t,n){const r=(0,u.Zw)(e,t);if(!r)return e;const o=(0,a.CE)(r,n),d=Object.values((0,a.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,u.tZ)(e,t,r);let d=(0,u.gb)(e,t,r),a=(0,u.qC)(e,t,r),s=(0,u.Cb)(e,t,r),i=(0,u.KB)(e,t),c=null==o?void 0:o.messagesCount;n.forEach((e=>{d&&d.includes(e)&&(d=d.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=l(e,t,r,"listedIds",d),e=l(e,t,r,"outlyingIds",a),e=l(e,t,r,"viewportIds",s),e=l(e,t,r,"pinnedIds",i),o&&void 0!==c&&(e=l(e,t,r,"threadInfo",{...o,messagesCount:c}))})),d.length){const n=(0,u.Bt)(e),r=n&&n.chatId===t&&"thread"===n.type,o=null==n?void 0:n.threadId;d.forEach((n=>{const{fromChatId:d,fromMessageId:a}=n.forwardInfo,i=(0,u.hj)(e,d,a);r&&o===a&&(e=s(e,t)),i&&(e=m(e,d,a,{threadInfo:void 0}))}))}return e=i(e,t,o)}function y(e,t,n){const r=(0,u.Fn)(e,t);if(!r)return e;const d=(0,a.CE)(r,n);let s=(0,u.qy)(e,t);return s&&(n.forEach((e=>{s.includes(e)&&(s=s.filter((t=>t!==e)))})),e=l(e,t,o._f,"scheduledIds",s)),P(e,t,d)}function v(e,t,n,r){const o=(0,u.gb)(e,t,n),d=null!=o&&o.length?r.filter((e=>!o.includes(e))):r;return o&&!d.length?e:l(e,t,n,"listedIds",w([...o||[],...d]))}function b(e,t,n,r){const o=(0,u.qC)(e,t,n),d=null!=o&&o.length?r.filter((e=>!o.includes(e))):r;return o&&!d.length?e:l(e,t,n,"outlyingIds",w([...o||[],...d]))}function w(e){return e.sort(((e,t)=>e-t))}function I(e,t,n,r){const o=(0,u.Cb)(e,t,n)||[];return o.includes(r)?e:l(e,t,n,"viewportIds",w([...o.length{e=S(e,t.chatId,t.threadId,t)})),e}function P(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 M(e,t,n,r=!1,o=!1){return{...e,focusedMessage:{...e.focusedMessage,chatId:t,messageId:n,noHighlight:r,isResizingContainer:o}}}function A(e,t,n){return{...e,messages:{...e.messages,sponsoredByChatId:{...e.messages.sponsoredByChatId,[t]:n}}}}function k(e,t){return{...e,focusedMessage:{...e.focusedMessage,direction:t}}}function T(e,t,n){return{...e,selectedMessages:{chatId:t,messageIds:n?Array.prototype.concat([],n):[]}}}function N(e,t,n,r,o,d,s,i=!1){const{selectedMessages:c}=e;d&&(s=(0,u.xH)(e,t,d));const l=s||[o];if(!c)return T(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 d=(0,u.$W)(e,t,n,r),s=d.indexOf(f[f.length-1]),i=d.indexOf(o),c=Math.min(s,i),l=Math.max(s,i),m=d.slice(c,l+1);h=(0,a.Tw)([...f,...m])}else h=[...f,...m];return h.length?{...e,selectedMessages:{...c,messageIds:h}}:L(e)}function L(e){return{...e,selectedMessages:void 0}}function R(e,t,n,r,o){const{channelPostId:d,fromChatId:a}=t.forwardInfo||{};if(d&&a){const t=(0,u.tZ)(e,n,d);t&&(e=l(e,n,d,"threadInfo",{...t,lastMessageId:r,messagesCount:t.messagesCount+(o?-1:1)}))}return e}function D(e,t,n,r,o){const d=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,a.ee)(d,"id")},[t]:{...e.stickers[t],hash:n,..."search"===t?{resultIds:o}:{setIds:r.map((({id:e})=>e))}}}}}function O(e,t,n){const r=e.stickers.setsById[t]||{};return{...e,stickers:{...e.stickers,setsById:{...e.stickers.setsById,[t]:{...r,...n}}}}}function Z(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 _(e,t){return{...e,animatedEmojis:t}}function x(e,t,n,r){const o=[...(0,u.Pk)(e,t),...n||[]],d=(0,a.Tw)(o.map((({id:e})=>e))),s=(0,a.ee)(o,"id"),i=d.map((e=>s[e]));return{...e,stickers:{...e.stickers,forEmoji:{emoji:t,stickers:i,hash:r}}}}function F(e){const{emoji:t,stickers:n,hash:r}=e.stickers.forEmoji||{};return t?x(e,t,n,r):e}var B=n(735);function $(e,t){return{...e,users:{...e.users,byId:t}}}function U(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 j(e,t,n){const{byId:r}=e.users,o=H(e,t,n);return o?$(e=U(e,[o]),{...r,[t]:o}):e}function W(e,t){const n=Object.keys(t).reduce(((n,r)=>{const o=H(e,r,t[r]);return o&&(n[r]=o),n}),{});return e=U(e=$(e,{...e.users.byId,...n}),Object.values(n))}function G(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=H(e,d,t[d]);n&&(o[d]=n,r||(r=!0))}return o}),{});return r?e=U(e=$(e,{...n,...o}),Object.values(o)):e}function H(e,t,n){const{byId:r}=e.users,o=r[t],d=n.isMin&&o&&!o.isMin,u={...o,...d?(0,a.CE)(n,["isMin","accessHash"]):n};if(u.id&&u.type)return u}function V(e,t){return e.users.selectedId===t?e:{...e,users:{...e.users,selectedId:t}}}function z(e,t){const{byId:n}=e.users,{userIds:r}=e.contactList||{};return $(e={...e,contactList:{userIds:r?r.filter((e=>e!==t)):B.D}},{...n,[t]:{...n[t],isContact:void 0}})}function Q(e,t){return{...e,userSearch:{...e.userSearch,...t}}}function K(e,t){return Q(e,{fetchingStatus:t})}function J(e,t,n){const{byId:r}=e.users,o=r[t];return o&&o.fullInfo?j(e,t,{...o,fullInfo:{...o.fullInfo,isBlocked:n}}):e}function q(e,t){return{...e,users:{...e.users,statusesById:t}}}function Y(e,t){const{statusesById:n}=e.users,r=Object.keys(t).filter((e=>!n[e]));return r.length?e=q(e,{...n,...(0,a.ei)(t,r)}):e}const X=e=>`${e.chatId}_${e.id}`;function ee(e,t){return{...e,globalSearch:{...e.globalSearch,...t}}}function te(e,t){return ee(e,{currentContent:t})}function ne(e,t,n,r,o){var d;const{resultsByType:u}=e.globalSearch||{},s=t.reduce(((e,t)=>(e[X(t)]=t,e)),{}),i=null==u||null===(d=u[r])||void 0===d?void 0:d.foundIds;if(void 0!==i&&Object.keys(s).every((e=>i.includes(X(s[e])))))return re(e,{messages:!1});const c=i||[],l=t.map((e=>X(e))),f=Array.prototype.concat(c,l),h=(0,a.et)(c,f)?c:f;return ee(e=re(e,{messages:!1}),{resultsByType:{...(e.globalSearch||{}).resultsByType,[r]:{totalCount:n,nextOffsetId:o,foundIds:h}}})}function re(e,t){return ee(e,{fetchingStatus:{...e.globalSearch.fetchingStatus,...t}})}var oe=n(2858);function de(e,t,n){return{...e,localTextSearch:{byChatThreadKey:{...e.localTextSearch.byChatThreadKey,[t]:n}}}}function ue(e,t,n,r,o){const d=(0,oe.uw)(t,n);return de(e,d,{...e.localTextSearch.byChatThreadKey[d],isActive:r,query:o})}function ae(e,t,n,r,o,d){const u=(0,oe.uw)(t,n);return de(e,u,{...e.localTextSearch.byChatThreadKey[u],results:{foundIds:r,totalCount:o,nextOffsetId:d}})}function se(e,t,n,r,o,d){const u=(0,oe.uw)(t,n),{results:s}=e.localTextSearch.byChatThreadKey[u]||{},i=(null==s?void 0:s.foundIds)||[],c=fe((0,a.Tw)(Array.prototype.concat(i,r)));return ae(e,t,n,(0,a.et)(i,c)?i:c,o,d)}function ie(e,t,n){return{...e,localMediaSearch:{byChatId:{...e.localMediaSearch.byChatId,[t]:n}}}}function ce(e,t,n){return ie(e,t,{...e.localMediaSearch.byChatId[t],currentType:n})}function le(e,t,n,r,o,d){const{resultsByType:u}=e.localMediaSearch.byChatId[t]||{},s=null!=u&&u[n]?u[n].foundIds:[],i=fe((0,a.Tw)(Array.prototype.concat(s,r)));return function(e,t,n,r,o,d){return ie(e,t,{...e.localMediaSearch.byChatId[t],resultsByType:{...(e.localMediaSearch.byChatId[t]||{}).resultsByType,[n]:{foundIds:r,totalCount:o,nextOffsetId:d}}})}(e,t,n,(0,a.et)(s,i)?s:i,o,d)}function fe(e){return e.sort(((e,t)=>e-t))}function he(e,t){return{...e,management:{...e.management,progress:t}}}function me(e,t,n){return{...e,management:{...e.management,byChatId:{...e.management.byChatId,[t]:{...e.management.byChatId[t]||{},...n}}}}}function pe(e,t){return{...e,settings:{...e.settings,byKey:{...e.settings.byKey,...t}}}}function ge(e,t,n){return{...e,settings:{...e.settings,themes:{...e.settings.themes,[t]:{...e.settings.themes[t]||{},...n}}}}}function ye(e,t){return t.forEach((t=>{const{chatId:n,...r}=t;e=ve(e,n,r)})),e}function ve(e,t,n){return{...e,settings:{...e.settings,notifyExceptions:{...e.settings.notifyExceptions,[t]:n}}}}function be(e,t,n,r){switch(t){case"contact":return pe(e,{...void 0!==n&&{hasPrivateChatsNotifications:!n},...void 0!==r&&{hasPrivateChatsMessagePreview:r}});case"group":return pe(e,{...void 0!==n&&{hasGroupNotifications:!n},...void 0!==r&&{hasGroupMessagePreview:r}});case"broadcast":return pe(e,{...void 0!==n&&{hasBroadcastNotifications:!n},...void 0!==r&&{hasBroadcastMessagePreview:r}});default:return}}function we(e,t){return e=J(e,t,!0),{...e,blocked:{...e.blocked,ids:[t,...e.blocked.ids],totalCount:e.blocked.totalCount+1}}}function Ie(e,t){return e=J(e,t,!1),{...e,blocked:{...e.blocked,ids:e.blocked.ids.filter((e=>e!==t)),totalCount:e.blocked.totalCount-1}}}function Ce(e,t){return{...e,twoFaSettings:{...e.twoFaSettings,...t}}}function Se(e,t){return{...e,payment:{...e.payment,shippingOptions:t}}}function Ee(e,t){return{...e,payment:{...e.payment,requestId:t}}}function Pe(e,t){return{...e,payment:{...e.payment,step:t}}}function Me(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 Ae(e,t){return{...e,payment:{...e.payment,stripeCredentials:{...t}}}}function ke(e,t){return{...e,payment:{...e.payment,...t}}}function Te(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 Ne(e){return{...e,payment:{}}}function Le(e){return{...e,payment:{...e.payment,isPaymentModalOpen:!1}}}},8857:(e,t,n)=>{n.d(t,{Z1:()=>s,Dg:()=>i,FM:()=>c,xo:()=>l,P_:()=>f,YK:()=>h,IK:()=>m,pk:()=>p,g4:()=>g,N:()=>y,Ek:()=>v,Mw:()=>b,ep:()=>w,DI:()=>I,A1:()=>C,UW:()=>S,_5:()=>E});var r=n(6137),o=n(2858),d=n(6376),u=n(3716),a=n(2913);function s(e,t){return e.chats.byId[t]}function i(e,t){const n=(0,o.zX)(t);return!!n&&(0,d.dy)(e,n)}function c(e,t){return t===e.currentUserId}function l(e,t){const n=i(e,t);return n&&(0,o.cS)(n)}function f(e){return Object.values(e.chats.byId).find((({isSupport:e})=>e))}function h(e,t){if(!(0,o.YC)(t.id)&&!(0,o.eA)(t)&&t.fullInfo)return t.fullInfo.members&&t.fullInfo.members.length!==u.mo?t.fullInfo.members.reduce(((t,{userId:n})=>n!==e.currentUserId&&e.users.byId[n]&&(0,o.kM)(e.users.byId[n],e.users.statusesById[n])?t+1:t),0):t.fullInfo.onlineCount}function m(e,t){const n=s(e,t),r=n&&(0,o.zX)(n),u=r&&(0,d.dy)(e,r);if(u&&(0,o.cS)(u))return u}function p(e,t){const n=s(e,t),d=m(e,t);if(!n||!d)return!1;if(n.lastMessage&&(0,o.CD)(n.lastMessage))return!0;const u=e.messages.byChatId[t];if(!u)return!1;const{listedIds:a}=u.threadsById[r._f]||{};return a&&!a.length}function g(e){return Boolean(e.chats.listIds.active)}function y(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 v(e,t){const n=s(e,t);if(n&&y(e,t))return n.folderId===u.WS?"archived":"active"}function b(e,t){return e.chatFolders.byId[t]}function w(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 I(e,t){const n=t.toLowerCase();return Object.values(e.chats.byId).find((e=>e.username&&e.username.toLowerCase()===n))}function C(e){const t=e.chats.listIds.active;if(!t)return 0;const n=e.chats.byId,r=(0,a.d)(e),d=(0,a.N)(e);return t.reduce(((e,t)=>{const u=n[t];return!(u&&u.unreadCount&&u.isListed)||u.isNotJoined||u.isRestricted||!u.unreadMentionsCount&&(0,o.i4)(u,r,d)?e:e+u.unreadCount}),0)}function S(e){return Boolean(s(e,u.aw))}function E(e,t){var n;const r=s(e,t);if(!r)return;const o=null==r||null===(n=r.fullInfo)||void 0===n?void 0:n.sendAsId;return o?(0,d.dy)(e,o)||s(e,o):void 0}},1638:(e,t,n)=>{n.d(t,{hg:()=>j,xs:()=>oe,_k:()=>X,zB:()=>g,g4:()=>a.g4,bH:()=>ye,__:()=>be,xl:()=>ee,Nu:()=>ne,nB:()=>te,Z1:()=>a.Z1,IK:()=>a.IK,DI:()=>a.DI,Mw:()=>a.Mw,Ek:()=>a.Ek,hj:()=>G,ZB:()=>z,Zw:()=>I,YK:()=>a.YK,Dg:()=>a.Dg,X5:()=>ie,A1:()=>a.A1,jr:()=>w,yN:()=>f,JX:()=>Oe,pP:()=>Te,we:()=>Ae,og:()=>Me,$W:()=>M,Bt:()=>b,y5:()=>l,n5:()=>Pe,Ms:()=>O,_$:()=>R,kK:()=>V,wU:()=>D,yZ:()=>x,It:()=>ae,G$:()=>Q,y8:()=>fe,cv:()=>Y,ku:()=>Se,pk:()=>a.pk,N:()=>a.N,ep:()=>a.ep,xo:()=>a.xo,FM:()=>a.FM,a6:()=>me,te:()=>re,Ev:()=>se,CA:()=>ce,zQ:()=>Ne,_X:()=>K,EV:()=>Ce,vk:()=>le,Jf:()=>Re,UW:()=>a.UW,s4:()=>s.s4,b9:()=>W,VF:()=>Ie,gb:()=>E,aW:()=>ke,xH:()=>he,FT:()=>ge,tV:()=>Z,NJ:()=>Ue.N,dZ:()=>Ue.d,dT:()=>J,qC:()=>P,gx:()=>Ze,eh:()=>xe,Mz:()=>_e,sp:()=>Fe,KB:()=>k,$$:()=>Be,rd:()=>ue,p9:()=>F,Yy:()=>L,Wq:()=>Le,qy:()=>T,Tm:()=>H,Fn:()=>C,Vt:()=>N,D7:()=>pe,_5:()=>a._5,Ur:()=>q,yB:()=>we,fS:()=>Ee,Ny:()=>h,E_:()=>m,Pk:()=>p,i3:()=>$e,P_:()=>a.P_,Pu:()=>De,Db:()=>U,tZ:()=>_,Cm:()=>B,qS:()=>$,uZ:()=>de,dy:()=>s.dy,ss:()=>s.ss,Cb:()=>A});var r=n(1713),o=n(7361),d=n(6137),u=n(3716),a=n(8857),s=n(6376),i=n(2858),c=n(782);function l(e){return e.stickers.search}function f(e){return e.gifs.search}function h(e,t){return e.stickers.setsById[t]}function m(e,t){return Object.values(e.stickers.setsById).find((e=>e.shortName.toLowerCase()===t.toLowerCase()))}function p(e,t){const n=Object.values(e.stickers.setsById);let r=[];return e.stickers.favorite.stickers.forEach((e=>{e.emoji===t&&r.push(e)})),n.forEach((({packs:e})=>{if(!e)return;const n=e[t];n&&(r=r.concat(n))})),r}function g(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 y=n(2267),v=n(735);function b(e){const{messageLists:t}=e.messages;if(t.length)return t[t.length-1]}function w(e){const{chatId:t}=b(e)||{};return t?(0,a.Z1)(e,t):void 0}function I(e,t){var n;return null===(n=e.messages.byChatId[t])||void 0===n?void 0:n.byId}function C(e,t){var n;return null===(n=e.scheduledMessages.byChatId[t])||void 0===n?void 0:n.byId}function S(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 E(e,t,n){return S(e,t,n,"listedIds")}function P(e,t,n){return S(e,t,n,"outlyingIds")}function M(e,t,n,r){switch(r){case"thread":return A(e,t,n);case"pinned":return k(e,t);case"scheduled":return T(e,t)}}function A(e,t,n){return S(e,t,n,"viewportIds")}function k(e,t){return S(e,t,d._f,"pinnedIds")}function T(e,t){return S(e,t,d._f,"scheduledIds")}function N(e,t,n){return S(e,t,n,"scrollOffset")}function L(e,t,n){return S(e,t,n,"replyingToId")}function R(e,t,n){return S(e,t,n,"editingId")}function D(e,t){return S(e,t,d._f,"editingScheduledId")}function O(e,t,n){return S(e,t,n,"draft")}function Z(e,t,n){return S(e,t,n,"noWebPage")}function _(e,t,n){return S(e,t,n,"threadInfo")}function x(e,t,n){return S(e,t,n,"firstMessageId")}function F(e,t,n){return S(e,t,n,"replyStack")}function B(e,t,n){if(n===d._f)return(0,a.Z1)(e,t);const r=_(e,t,n);return r?(0,a.Z1)(e,r.originChannelId||t):void 0}function $(e,t,n){if(n===d._f)return;const r=_(e,t,n);return r?r.topMessageId:void 0}function U(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 j(e,t,n){const r=b(e);if(!r)return!1;const{threadInfo:o}=U(e,t,n)||{};return t===r.chatId&&(r.threadId===d._f||o&&r.threadId===o.threadId)}function W(e,t,n){const r=A(e,t,n);if(!r||!r.length)return!0;let o;if(n===d._f){const n=(0,a.Z1)(e,t);if(!n||!n.lastMessage)return!0;o=n.lastMessage.id}else{const r=_(e,t,n);if(!r||!r.lastMessageId)return;o=r.lastMessageId}return o>=u.AE&&!G(e,t,o)||r[r.length-1]>=o}function G(e,t,n){const r=I(e,t);return r?r[n]:void 0}function H(e,t,n){const r=C(e,t);return r?r[n]:void 0}function V(e,t,n,r){if("scheduled"===r){const n=D(e,t);return n?H(e,t,n):void 0}{const r=R(e,t,n);return r?G(e,t,r):void 0}}function z(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 Q(e,t){const{chatId:n,messageId:r}=e.focusedMessage||{};return n===t?r:void 0}function K(e,t){const n=Q(e,t.chatId);return!!n&&(n===t.id||n===t.previousLocalId)}function J(e,t,n=!1){return function(e,t){const{lastReadOutboxMessageId:n}=(0,a.Z1)(e,t.chatId)||{};return(0,i.CI)(t)||!n||ne===t.id))}(e,t.content.sticker),Z=!b&&D&&!O,_=!b&&O,x=!b,F=!b&&(m||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,L,E,P,T,A,N,R,Z,_,x,F,B,$].every((e=>!e)),canReply:C,canEdit:L,canPin:E,canUnpin:P,canReport:T,canDelete:A,canDeleteForAll:N,canForward:R,canFaveSticker:Z,canUnfaveSticker:_,canCopy:x,canCopyLink:F,canSelect:B,canDownload:$}}function ee(e){const{messageIds:t}=e.selectedMessages||{},{chatId:n,threadId:r}=b(e)||{},o=n&&I(e,n);if(!o||!t||!r)return{};const d=t.map((t=>o[t]&&X(e,o[t],r))).filter(Boolean);return{canDelete:d.every((e=>e.canDelete)),canDeleteForAll:d.every((e=>e.canDeleteForAll))}}function te(e){const{messageIds:t}=e.selectedMessages||{},{chatId:n,threadId:r}=b(e)||{},o=n&&I(e,n);return!!(o&&t&&r)&&t.map((t=>o[t]&&X(e,o[t],r))).filter(Boolean).every((e=>e.canReport))}function ne(e){const{messageIds:t}=e.selectedMessages||{},{chatId:n,threadId:r}=b(e)||{},o=n&&I(e,n);return!!(o&&t&&r)&&t.map((t=>o[t]&&X(e,o[t],r))).filter(Boolean).some((e=>e.canDownload))}function re(e,t){const n=e.activeDownloads.byChatId[t.chatId];return!!n&&n.includes(t.id)}function oe(e,t){return e.activeDownloads.byChatId[t]||v.D}function de(e,t){var n;return null===(n=e.fileUploads.byMessageLocalId[t.previousLocalId||t.id])||void 0===n?void 0:n.progress}function ue(e,t,n){if(n===d._f){const n=(0,a.Z1)(e,t);if(!n)return;if(!n.lastReadInboxMessageId)return;return n.lastMessage?(0,i.CI)(n.lastMessage)?n.lastMessage.id:Math.min(n.lastMessage.id,n.lastReadInboxMessageId):n.lastReadInboxMessageId}{const r=_(e,t,n);if(!r)return;return r.lastReadInboxMessageId?Math.min(r.lastReadInboxMessageId,r.lastMessageId||1/0):r.topMessageId}}function ae(e,t,n){const r=(0,a.Z1)(e,t);if(n===d._f){if(!r)return}else{const r=_(e,t,n);if(!r||void 0!==r.lastMessageId&&r.lastMessageId===r.lastReadInboxMessageId)return}const o=P(e,t,n),s=E(e,t,n),i=I(e,t);if(!i||!o&&!s)return;const c=ue(e,t,n);if(!c&&r&&r.isNotJoined)return;const l=t===u.aw?e.serviceNotifications.reduce(((e,t)=>!t.isUnread&&t.id>e?t.id:e),-1):-1;function f(e){return e.find((e=>(!c||e>c)&&i[e]&&(!i[e].isOutgoing||i[e].isFromScheduled)&&e>l))}if(o){const e=f(o);if(e)return e}if(s){const e=f(s);if(e)return e}}function se(e){const{forwardMessages:t}=e;return Boolean(t.isModalShown)}function ie(e,t){const n=Object.values(e.chats.byId).find((e=>(0,i.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=(0,a.Z1)(e,n);return o&&(0,i.Ru)(o)&&r[o.id].byId[t]}))}function ce(e){const{selectedMessages:t}=e;return Boolean(t)}function le(e,t){const{messageIds:n}=e.selectedMessages||{};return!!n&&n.includes(t)}function fe(e,t,n){const r=I(e,t);if(r)return Object.values(r).filter((e=>e.groupedId===n&&e.forwardInfo)).map((({forwardInfo:e})=>e.fromMessageId))}function he(e,t,n){const r=I(e,t);if(r)return Object.keys(r).map(Number).filter((e=>r[e].groupedId===n))}function me(e,t,n){const{messageIds:r}=e.selectedMessages||{};if(!r)return!1;const o=he(e,t,n);return o&&o.every((e=>r.includes(e)))}function pe(e){const{messageIds:t}=e.selectedMessages||{};return t?t.length:0}function ge(e,t){const n=(0,a.Z1)(e,t);if(!n)return;if(!(0,a.xo)(e,n))return;const r=I(e,t),o=A(e,t,d._f);if(!r||!o)return;const u=(0,c.dF)(o,(e=>!r[e].isOutgoing&&Boolean(r[e].keyboardButtons))),s=(0,c.dF)(o,(e=>Boolean(r[e].shouldHideKeyboardButtons)));return u&&s&&s>u?void 0:u?r[u]:void 0}function ye(e,t){const n=(0,a.Z1)(e,t.chatId);if(!n)return;const r=q(e,t),o=Boolean((0,i.O$)(t)||(0,i.F$)(t)),d=Boolean((0,i.b7)(t)||(0,i.Cg)(t)),u=Boolean((0,i.oP)(t)||(0,i.kd)(t)||(0,i.aE)(t)),{canAutoLoadPhotoFromContacts:s,canAutoLoadPhotoInPrivateChats:c,canAutoLoadPhotoInGroups:l,canAutoLoadPhotoInChannels:f,canAutoLoadVideoFromContacts:h,canAutoLoadVideoInPrivateChats:m,canAutoLoadVideoInGroups:p,canAutoLoadVideoInChannels:g,canAutoLoadFileFromContacts:y,canAutoLoadFileInPrivateChats:v,canAutoLoadFileInGroups:b,canAutoLoadFileInChannels:w}=e.settings.byKey;return o?ve({global:e,chat:n,sender:r,canAutoLoadMediaFromContacts:s,canAutoLoadMediaInPrivateChats:c,canAutoLoadMediaInGroups:l,canAutoLoadMediaInChannels:f}):d?ve({global:e,chat:n,sender:r,canAutoLoadMediaFromContacts:h,canAutoLoadMediaInPrivateChats:m,canAutoLoadMediaInGroups:p,canAutoLoadMediaInChannels:g}):!u||ve({global:e,chat:n,sender:r,canAutoLoadMediaFromContacts:y,canAutoLoadMediaInPrivateChats:v,canAutoLoadMediaInGroups:b,canAutoLoadMediaInChannels:w})}function ve({global:e,chat:t,sender:n,canAutoLoadMediaFromContacts:r,canAutoLoadMediaInPrivateChats:o,canAutoLoadMediaInGroups:d,canAutoLoadMediaInChannels:u}){const a=Boolean(n&&(n.id===e.currentUserId||(0,s.nM)(e,n)));return Boolean(a&&r||!a&&o&&(0,i.YC)(t.id)||d&&(0,i.Bf)(t)||u&&(0,i.eA)(t))}function be(e,t){const n=(0,i.b7)(t)||(0,i.Cg)(t);if(!n)return;const{canAutoPlayVideos:r,canAutoPlayGifs:o}=e.settings.byKey,d=n.isGif||n.isRound;return r&&!d||o&&d}function we(e){return e.settings.byKey.shouldLoopStickers}function Ie(e){const{serviceNotifications:t}=e,n=Math.max(...t.map((({id:e})=>e)));return t.find((({id:e})=>e===n))}function Ce(e,t){var n;return!!t&&(t.isProtected||(null===(n=(0,a.Z1)(e,t.chatId))||void 0===n?void 0:n.isProtected))}function Se(e,t,n){var r;if(null!==(r=(0,a.Z1)(e,t))&&void 0!==r&&r.isProtected)return!0;if(!n)return!1;const o=I(e,t);return n.some((e=>{var t;return null===(t=o[e])||void 0===t?void 0:t.isProtected}))}function Ee(e,t){const n=(0,a.Z1)(e,t),r=n&&(0,i.eA)(n)?e.messages.sponsoredByChatId[t]:void 0;return r&&r.expiresAt>=Math.round(Date.now()/1e3)?r:void 0}function Pe(e){const{chatId:t,threadId:n}=b(e)||{};if(!t||!n)return;const r=(0,i.uw)(t,n),o=e.localTextSearch.byChatThreadKey[r];return o&&o.isActive?o:void 0}function Me(e){const{byChatId:t}=e.localMediaSearch,{chatId:n}=b(e)||{},r=e.users.selectedId;return r&&t[r]?r:n}function Ae(e){const t=Me(e);if(t)return e.localMediaSearch.byChatId[t]}function ke(e,t){return e.management.byChatId[t]}function Te(e){const{chatId:t,threadId:n}=b(e)||{};if(!t||!n)return;if((0,i.YC)(t))return"user";const r=(0,a.Z1)(e,t);return r?(0,i.Bf)(r)?"group":"channel":void 0}function Ne(e){const{mediaViewer:t}=e;return Boolean(t.messageId||t.avatarOwnerId)}function Le(e){const{users:t,isChatInfoShown:n,newChatMembersProgress:d}=e,u=d!==r.WB.Closed,s=function(e){const{pollResults:t}=e;return Boolean(t.messageId)}(e),i=Boolean(!o.wB&&Pe(e)),c=function(e){const{chatId:t,threadId:n}=b(e)||{};if(!t||!n)return;const r=e.management.byChatId[t];return r&&r.isActive?r:void 0}(e),h=void 0!==l(e).query,m=void 0!==f(e).query,{chatId:p}=b(e)||{},g=t.selectedId,y=(0,a.g4)(e),v=Boolean(g&&y),w=Boolean(p&&y)&&n;return s?r.qt.PollResults:i?r.qt.Search:c?r.qt.Management:h?r.qt.StickerSearch:m?r.qt.GifSearch:u?r.qt.AddingMembers:v?r.qt.UserInfo:w?r.qt.ChatInfo:void 0}function Re(e){return void 0!==Le(e)}function De(e){const{theme:t,shouldUseSystemTheme:n}=e.settings.byKey;return n?(0,o.vn)():t}function Oe(e){return e.globalSearch.query}function Ze(e){return e.payment.chatId}function _e(e){return e.payment.messageId}function xe(e){return e.payment.formId}function Fe(e){return e.payment.requestId}function Be(e){return e.payment.nativeParams?e.payment.nativeParams.publishableKey:void 0}function $e(e){return e.payment.stripeCredentials}var Ue=n(2913)},2913:(e,t,n)=>{function r(e){return e.settings.byKey}function o(e){return e.settings.notifyExceptions}n.d(t,{d:()=>r,N:()=>o})},6376:(e,t,n)=>{function r(e,t){return e.users.byId[t]}function o(e,t){return e.users.statusesById[t]}function d(e,t){var n;const o=r(e,t);return null==o||null===(n=o.fullInfo)||void 0===n?void 0:n.isBlocked}function u(e,t){return e.contactList&&e.contactList.userIds.includes(t.id)}n.d(t,{dy:()=>r,ss:()=>o,s4:()=>d,nM:()=>u})},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.ChatNewAdminRights=12]="ChatNewAdminRights",e[e.GroupMembers=13]="GroupMembers",e[e.GroupAddAdmins=14]="GroupAddAdmins"}(v||(v={}))},9933:(e,t,n)=>{n.d(t,{cK:()=>d,jt:()=>u,M8:()=>a,vr:()=>s});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)}))}const a={linear:e=>e,easeIn:e=>e**1.675,easeOut:e=>1-(1-e**1.675),easeInOut:e=>.5*(Math.sin((e-.5)*Math.PI)+1),easeInQuad:e=>e*e,easeOutQuad:e=>e*(2-e),easeInOutQuad:e=>e<.5?2*e*e:(4-2*e)*e-1,easeInCubic:e=>e*e*e,easeOutCubic:e=>--e*e*e+1,easeInOutCubic:e=>e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1,easeInQuart:e=>e*e*e*e,easeOutQuart:e=>1- --e*e*e*e,easeInOutQuart:e=>e<.5?8*e*e*e*e:1-8*--e*e*e*e,easeInQuint:e=>e*e*e*e*e,easeOutQuint:e=>1+--e*e*e*e*e,easeInOutQuint:e=>e<.5?16*e*e*e*e*e:1+16*--e*e*e*e*e};function s({timing:e=a.linear,onUpdate:t,duration:n,onEnd:r,from:o,to:d}){const s=Date.now();let i=!1;return u((()=>{if(i)return!1;let u=(Date.now()-s)/n;u>1&&(u=1);const a=e(u);if("number"==typeof o&&"number"==typeof d)t(o+(d-o)*a);else if(Array.isArray(o)&&Array.isArray(d)){const e=o.map(((e,t)=>e+(d[t]-e)*a));t(e)}return 1===u&&r&&r(),u<1})),()=>{i=!0,r&&r()}}},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,SA:()=>w,xk:()=>C,IS:()=>S});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?P:E)(e("Weekday.Today"));const t=new Date(s);if(t.setDate(s.getDate()-1),i(a)===i(t))return(d||!n?P:E)(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?P:E)(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?P:E)(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())).replace(/'de'/g,"de")}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("number"==typeof e?new Date(e):e).toLocaleString(t,{year:"numeric",month:"short",day:"numeric"})}function w(e,t="en-US"){return("number"==typeof e?new Date(e):e).toLocaleString(t,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"})}function I(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 C(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||!I(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&&I(Number(u),s)?`${String(s+1).padStart(2,"0")}-${String(u).padStart(2,"0")}`:void 0}function S(e){return e+86400}function E(e){return`${e[0].toLowerCase()}${e.slice(1)}`}function P(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[^\ufe0f]/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)}},1396:(e,t,n)=>{function r(e){if(e)return e.includes("://")?e:`http://${e}`}n.d(t,{X:()=>r})},7361:(e,t,n)=>{n.d(t,{Bi:()=>k,cL:()=>R,wZ:()=>p,vX:()=>M,op:()=>C,cj:()=>m,jm:()=>h,pA:()=>L,m5:()=>P,I_:()=>E,fl:()=>y,t0:()=>A,s$:()=>g,i4:()=>O,Mc:()=>S,wB:()=>b,p7:()=>w,$b:()=>v,mh:()=>I,s0:()=>T,aZ:()=>D,gZ:()=>Z,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="requestFullscreen"in document.createElement("div"),k=!navigator.userAgent.includes("Firefox"),T=p?"slide-fade":m?"slide-layers":"push-slide",N=document.createElement("video"),L=Boolean(N.canPlayType(r.Ng).replace("no","")||m);L&&r.wG.add(r.Ng);const R=window.devicePixelRatio||1,D=!0,O=!h&&!m&&!p,Z=O?300:750},1394:(e,t,n)=>{n.d(t,{A9:()=>d,YJ:()=>u,hl:()=>a,pt:()=>s,jj:()=>i,ud:()=>c,gm:()=>l,dc:()=>f,ao:()=>h});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()}async function f(e,t){return a(await l(e),t)}function h(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",ADMINS_TOO_MUCH:"There are too many admins",ADMIN_RANK_EMOJI_NOT_ALLOWED:"An admin rank cannot contain emojis",ADMIN_RANK_INVALID:"The specified admin rank is invalid",FRESH_CHANGE_ADMINS_FORBIDDEN:"You were just elected admin, you can't add or modify other admins yet",INPUT_USER_DEACTIVATED:"The specified user was deleted"},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"){function r(e,t,n,r){const o=("function"==typeof n?n(e):e[n])||0,d=("function"==typeof n?n(t):t[n])||0;return r?o-d:d-o}if(Array.isArray(t)){const[o,d]=Array.isArray(n)?n:[n,n],[u,a]=t,s="asc"===o,i="asc"===d;return e.sort(((e,t)=>r(e,t,u,s)||r(e,t,a,i)))}const o="asc"===n;return e.sort(((e,n)=>r(e,n,t,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",e[e.Calls=3]="Calls"}(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(739),n.e(886),n.e(884),n.e(87)]).then(n.bind(n,4087));break;case o.Extra:d[o.Extra]=Promise.all([n.e(739),n.e(886),n.e(301)]).then(n.bind(n,4301));break;case o.Calls:d[o.Calls]=Promise.all([n.e(739),n.e(884),n.e(532)]).then(n.bind(n,7936))}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(8005),u=n(3716),a=n(5116),s=n(2858),i=n(663),c=n(307),l=n(1638),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"})}},7926:(e,t,n)=>{n.d(t,{L:()=>d,$:()=>u});const r="kz_version",o=["Z","K"];function d(e){localStorage.setItem(r,JSON.stringify(e))}function u(){(function(){const e=localStorage.getItem(r);if(!e)return!1;try{const t=JSON.parse(e);return o.includes(t)}catch(e){return!1}})()||d("Z")}},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 s(y,e)}function u(e){return s(v,e)}function a(e){return s(b,e)}function s(e,t){let n,r=!1;return(...o)=>{n=o,r||(r=!0,e((()=>{r=!1,t(...n)})))}}function i(e,t){self.requestIdleCallback?self.requestIdleCallback(e,{timeout:t}):b(e)}n.d(t,{Ds:()=>r,P2:()=>o,mS:()=>d,wT:()=>u,$6:()=>a,Q8:()=>i,wO:()=>c,Pn:()=>l,T2:()=>y,D0:()=>v,R3:()=>b,zD:()=>w,Gq:()=>I});const c=e=>new Promise((t=>{setTimeout((()=>t()),e)}));function l(){return new Promise((e=>{y(e)}))}let f,h,m,p,g;function y(e,t=!1){f?t?h.push(e):f.push(e):(f=t?[]:[e],h=t?[e]:[],requestAnimationFrame((()=>{const e=f,t=h;f=void 0,h=void 0,t.forEach((e=>e())),e.forEach((e=>e()))})))}function v(e){y(e,!0)}function b(e,t=!1){m?t?p.push(e):m.push(e):(m=t?[]:[e],p=t?[e]:[],Promise.resolve().then((()=>{const e=m,t=p;m=void 0,p=void 0,t.forEach((e=>e())),e.forEach((e=>e()))})))}function w(e){b(e,!0)}function I(e,t=!1){return g||(g=[],self.addEventListener("beforeunload",(()=>{g.forEach((e=>e()))}))),t?g.push(e):g.unshift(e),()=>{g=g.filter((t=>t!==e))}}},5765:(e,t,n)=>{let r;n.d(t,{Z:()=>o,W:()=>d});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="string"==typeof t?t.toLowerCase().split(r):t,o=e.toLowerCase();if(1===n.length&&!o.includes(n[0]))return!1;let d;return n.every((e=>!!o.includes(e)&&(d||(d=o.split(r)),d.some((t=>t.startsWith(e))))))}function d(e){const t=e.toLowerCase().split(r);return e=>o(e,t)}},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.cK)((()=>{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+"."+{87:"74a4d72480e8214a0dde",99:"f03a947e6e336feffec8",133:"64de2daa3ae6549d8f45",161:"286d0207d962142ad548",301:"751950a7a21e70acdb7c",354:"47391222364a22307e69",472:"21e5264f606f2b525030",501:"72ce4b6e27f459e194cd",524:"95e29e37c83dea5150d6",532:"5ff953a5af12d8af60a9",536:"55dc7dd4ab42a2c9f037",739:"462b85f7a954e903b4cd",745:"9316c5c2b711c39a20a5",884:"bf91279ce235c0463204",886:"2870895152d4462e05bf",915:"0588cdc78683d0e9bbbc",927:"151d396500bf8aa6cf1e",941:"5b93118a31cc89905ee3",993:"f0aad9f6787f211b4e51"}[e]+".js",s.miniCssF=e=>e+"."+{87:"74a4d72480e8214a0dde",133:"64de2daa3ae6549d8f45",301:"751950a7a21e70acdb7c",472:"21e5264f606f2b525030",532:"5ff953a5af12d8af60a9",886:"2870895152d4462e05bf"}[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]&&{87:1,133:1,301:1,472:1,532:1,886: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.ZT&&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:{},statusesById:{}},chats:{listIds:{},isFullyLoaded:{},orderedPinnedIds:{},totalCount:{},byId:{}},messages:{byChatId:{},messageLists:[],sponsoredByChatId:{}},groupCalls:{byId:{}},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(1638),m=s(4688),p=s(5780),g=s(6590),y=s(2858);const v=(0,c.P2)((()=>(0,c.Q8)(S)),5e3,!1);let b,w=!1;function I(){w=!0,b=(0,c.Gq)(S,!0),window.addEventListener("blur",S),(0,t.ll)(v)}function C(){w=!1,(0,t.Iq)(v),window.removeEventListener("blur",S),b&&b()}function S(){if(!w||(0,l.zG)())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:E(n),users:P(n),chats:M(n),messages:A(n),globalSearch:{recentlyFoundChatIds:n.globalSearch.recentlyFoundChatIds},settings:k(n),chatFolders:T(n),groupCalls:N(n)},o=JSON.stringify(r);localStorage.setItem(e.Uh,o)}function E(t){return window.innerWidth>e._m&&t.isChatInfoShown}function P(t){const{users:{byId:n,statusesById:r,selectedId:o}}=t,d=(t.chats.listIds.active||[]).slice(0,e.gJ).filter(y.YC),u=Object.keys(n),a=d.concat(u).slice(0,e.lO);return{byId:(0,f.ei)(n,a),statusesById:(0,f.ei)(r,a),selectedId:window.innerWidth>e._m?o:void 0}}function M(t){const n=(t.chats.listIds.active||[]).slice(0,e.gJ),{chatId:r}=(0,h.Bt)(t)||{},o=n.concat(r?[r]:[]);return{...t.chats,byId:(0,f.ei)(t.chats.byId,o),listIds:{active:n},isFullyLoaded:{},orderedPinnedIds:{active:t.chats.orderedPinnedIds.active}}}function A(t){const n={},{chatId:r}=(0,h.Bt)(t)||{};return(t.chats.listIds.active||[]).slice(0,e.gJ).concat(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:[],sponsoredByChatId:{}}}function k(e){const{byKey:t,themes:n}=e.settings;return{byKey:t,themes:n,privacy:{},notifyExceptions:{}}}function T(e){return{...e.chatFolders,activeChatFolder:0}}function N(e){return{...e.groupCalls,byId:{},activeGroupCallId:void 0,isGroupCallPanelHidden:void 0,isFallbackConfirmOpen:void 0}}e.sd||((0,t.Q6)("saveSession",(()=>{w||I()})),(0,t.Q6)("reset",(()=>{localStorage.removeItem(e.Uh),w&&C()}))),(0,t.Q6)("init",(()=>{const t=(0,f.Xh)(a);return function(t){if(!e.sd)return(0,m.ti)(!0)?(I(),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),t.groupCalls||(t.groupCalls=n.groupCalls),t.users.statusesById||(t.users.statusesById={}),t.messages.sponsoredByChatId||(t.messages.sponsoredByChatId={})}(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 C()}(t)||t}));var L=s(4050),R=s(3858);const D="tt-active-tab",O=String(Date.now()+Math.random());let Z;localStorage.setItem(D,O);const _=window.setInterval((()=>{Z&&localStorage.getItem(D)!==O&&(Z(),clearInterval(_))}),2e3);var x=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),G=s(9203),H=s(6752),V=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,G.$y)(G.gl.Main,"Main").then(j),Q()]),authPhoneNumber:()=>Promise.all([j(),(0,$.pt)(V)]),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}}))((({page:e,children:n,hasCustomBackground:r,hasCustomBackgroundColor:o,isRightColumnShown:d,shouldSkipHistoryAnimations:u,leftColumnWidth:a})=>{const{setIsUiReady:s}=(0,t.uC)(),[i,l]=(0,x.Z)(),{shouldRender:f,transitionClassNames:h}=(0,B.Z)(!i,void 0,!0);return(0,L.d4)((()=>{let t;return Promise.race([(0,c.wO)(700),(async()=>{try{await K[e]()}catch(e){}})()]).then((()=>{l(),s({uiReadyState:1}),t=window.setTimeout((()=>{s({uiReadyState:2})}),1e3)})),()=>{t&&(clearTimeout(t),t=void 0),s({uiReadyState:0})}}),[]),L.ZP.createElement("div",{id:"UiLoader"},n,f&&!u&&L.ZP.createElement("div",{className:(0,H.Z)("mask",h)},"main"===e?L.ZP.createElement(L.ZP.Fragment,null,L.ZP.createElement("div",{className:"left",style:a?`width: ${a}px`:void 0}),L.ZP.createElement("div",{className:(0,H.Z)("middle",r&&"custom-bg-image",o&&"custom-bg-color",d&&"with-right-column")}),d&&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=""){if(!t.length)return e;const n=(0,ue.W)(t);return e.filter((e=>n(e.defaultName)||e.name&&n(e.name)))}(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,H.Z)("input-group",t&&"touched")},L.ZP.createElement("input",{ref:u,className:(0,H.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,H.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}}))((({connectionState:e,authState:r,authPhoneNumber:o,authIsLoading:d,authIsLoadingQrCode:u,authError:a,authRememberMe:s,authNearestCountry:i,phoneCodeList:c,language:l})=>{const{setAuthPhoneNumber:f,setAuthRememberMe:h,loadNearestCountry:m,loadCountryList:p,clearAuthError:g,goToAuthQrCode:y,setSettingOption:v}=(0,t.uC)(),b=(0,X.Z)(),w=(0,L.sO)(null),I=te(),C=ee(I,"ContinueOnThisLanguage"),[S,E]=(0,L.eJ)(),[P,M]=(0,L.eJ)(),[A,k]=(0,L.eJ)(!1),[T,N]=(0,L.eJ)(),[R,D,O]=(0,x.Z)(),Z=S?`+${S.countryCode} ${P||""}`:P,_=Z&&Z.replace(/[^\d]+/g,"").length>=7;(0,L.d4)((()=>{n.$b||w.current.focus()}),[S]),(0,L.d4)((()=>{"connectionStateReady"!==e||i||m()}),[e,i,m]),(0,L.d4)((()=>{"connectionStateReady"===e&&p({langCode:l})}),[e,l,p]),(0,L.d4)((()=>{i&&c&&!S&&!A&&E((0,q.U9)(c,i)[0])}),[S,i,A,c]);const F=(0,L.I4)((e=>{e.length||M("");const t=c&&(0,q.g3)(c,e),n=!S||t&&t.iso2!==S.iso2||!t&&e.length?t:S;(!S||!n||n&&n.iso2!==S.iso2)&&E(n),M((0,q.un)(e,n))}),[c,S]),B=(0,L.I4)((()=>{D(),(0,Y.m0)(I,(()=>{O(),v({language:I})}))}),[D,v,I,O]);(0,L.d4)((()=>{void 0===P&&o&&F(o)}),[o,P,F]),(0,L.bt)((()=>{w.current&&T&&w.current.setSelectionRange(...T)}),[T]);const U=(0,L.sO)(!1),W=(0,L.I4)((()=>{U.current=!0,requestAnimationFrame((()=>{U.current=!1}))}),[]),G=(0,L.I4)((e=>{E(e),M("")}),[]),H=(0,L.I4)((e=>{a&&g(),pe||(pe=!0,j(),(0,$.pt)(z));const{value:t,selectionStart:r,selectionEnd:o}=e.target;N(r&&o&&o1&&!U.current;F(d?`${S.countryCode} ${t}`:t)}),[a,g,S,Z,F]),V=(0,L.I4)((e=>{h(e.target.checked)}),[h]),Q="authorizationStateWaitPhoneNumber"===r;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"},b("StartText")),L.ZP.createElement("form",{action:"",onSubmit:function(e){e.preventDefault(),d||_&&f({phoneNumber:Z})}},L.ZP.createElement(me,{id:"sign-in-phone-code",value:S,isLoading:!i&&!S,onChange:G}),L.ZP.createElement(oe.Z,{ref:w,id:"sign-in-phone-number",label:b("Login.PhonePlaceholder"),value:Z,error:a&&b(a),inputMode:"tel",onChange:H,onPaste:n.s$?W:void 0}),L.ZP.createElement(re.Z,{id:"sign-in-keep-session",label:"Keep me signed in",checked:Boolean(s),onChange:V}),_&&(Q?L.ZP.createElement(ne.Z,{type:"submit",ripple:!0,isLoading:d},b("Login.Next")):L.ZP.createElement(de.Z,null)),Q&&L.ZP.createElement(ne.Z,{isText:!0,ripple:!0,isLoading:u,onClick:y},b("Login.QR.Login")),I&&I!==l&&C&&L.ZP.createElement(ne.Z,{isText:!0,isLoading:R,onClick:B},C))))})));var ye=s(8778);const ve=(0,L.X$)((()=>{const e=(0,ye.Z)(G.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)(G.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)(G.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}}))((({connectionState:n,authState:r,authQrCode:o,language:d})=>{const{returnToAuthPhoneNumber:u,setSettingOption:a}=(0,t.uC)(),s=te(),i=(0,X.Z)(),c=(0,L.sO)(null),l=ee(s,"ContinueOnThisLanguage"),[f,h,m]=(0,x.Z)();(0,L.d4)((()=>{if(!o||"connectionStateReady"!==n)return;const e=c.current;e.innerHTML="",e.classList.remove("pre-animate"),Se.render({text:`tg://login?token=${o.token}`,radius:.5,ecLevel:"M",fill:"#4E96D4",size:280},e)}),[n,o]),(0,L.d4)((()=>{"connectionStateReady"===n&&(0,Y.m0)(e.sR)}),[n]);const p=(0,L.I4)((()=>{h(),(0,Y.m0)(s,(()=>{m(),a({language:s})}))}),[h,a,s,m]),g="authorizationStateWaitQrCode"===r;return L.ZP.createElement("div",{id:"auth-qr-form",className:"custom-scroll"},L.ZP.createElement("div",{className:"auth-form qr"},o?L.ZP.createElement("div",{key:"qr-container",className:"qr-container pre-animate",ref:c}):L.ZP.createElement("div",{key:"qr-loading",className:"qr-loading"},L.ZP.createElement(de.Z,null)),L.ZP.createElement("h3",null,i("Login.QR.Title")),L.ZP.createElement("ol",null,L.ZP.createElement("li",null,L.ZP.createElement("span",null,i("Login.QR.Help1"))),L.ZP.createElement("li",null,L.ZP.createElement("span",null,(0,ae.Z)(i("Login.QR.Help2"),["simple_markdown"]))),L.ZP.createElement("li",null,L.ZP.createElement("span",null,i("Login.QR.Help3")))),g&&L.ZP.createElement(ne.Z,{isText:!0,onClick:u},i("Login.QR.Cancel")),s&&s!==d&&l&&L.ZP.createElement(ne.Z,{isText:!0,isLoading:f,onClick:p},l)))}))),Pe=(0,L.X$)((0,t.c$)((e=>(0,f.ei)(e,["authState"])))((({authState:e})=>{const{reset:r,initApi:o,returnToAuthPhoneNumber:d,goToAuthQrCode:u}=(0,t.uC)();(0,L.d4)((()=>{r(),o()}),[r,o]);const a="iOS"===n.Lt||"Android"===n.Lt;switch((0,g.ZP)(!a&&"authorizationStateWaitPhoneNumber"===e||a&&"authorizationStateWaitQrCode"===e,(()=>{a?d():u()})),(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 a?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)(G.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"])))((({authState:n})=>{const{disconnect:r}=(0,t.uC)(),[o,d]=(0,x.Z)(!1);if((0,L.d4)((()=>{(0,R.z)(),Z=()=>{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.694bb1485bda2f2e118a.js.map \ No newline at end of file diff --git a/dist/main.694bb1485bda2f2e118a.js.map b/dist/main.694bb1485bda2f2e118a.js.map new file mode 100644 index 00000000..5de2f5c6 --- /dev/null +++ b/dist/main.694bb1485bda2f2e118a.js.map @@ -0,0 +1 @@ +{"version":3,"file":"main.694bb1485bda2f2e118a.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,E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AAU,MACR4iE,EAAAA,EAAAA,KfTFr5E,EeU6B,KACzBkrF,IACAjjF,SAASX,MAAS,GAAEkR,EAAAA,KAAaC,EAAAA,KAEjC2yE,OAED,CAACF,EAAYE,IAIZD,EACF,OAAO,mBAAC,GAAD,MAGT,GAAItvD,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,OAAOovD,KAIb,OAAOxW,EAAAA,EAAAA,KAAiB,GAAQwW,KAAe,mBAAC,GAAD,SC3C7CjsF,EAAAA,IAEFC,QAAQC,IAAI,aAGdqH,EAAAA,EAAAA,MAAcsvB,OAEV72B,EAAAA,IAEFC,QAAQC,IAAI,4BAGdmsF,EAAAA,EAAAA,OACE,mBAAC,GAAD,MACApjF,SAASw8E,eAAe,SAGtBzlF,EAAAA,IAEFC,QAAQC,IAAI,6BAGd+I,SAAS5I,iBAAiB,YAAY,KAEpCJ,QAAQsC,KAAK,gBAAgB+xB,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/GroupCallLink.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/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/modules/selectors/settings.ts","webpack://telegram-t/./src/modules/selectors/users.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/ensureProtocol.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/permanentWebVersion.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 = {\"87\":1,\"133\":1,\"301\":1,\"472\":1,\"532\":1,\"886\":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 new Error(data.error?.message);\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","import { ApiGroupCall } from './calls';\n\nexport interface ApiDimensions {\n width: number;\n height: number;\n}\n\nexport interface ApiPhotoSize extends ApiDimensions {\n type: 's' | 'm' | 'x' | 'y' | 'z';\n}\n\nexport interface ApiThumbnail extends ApiDimensions {\n dataUri: string;\n}\n\nexport interface ApiPhoto {\n id: string;\n thumbnail?: ApiThumbnail;\n sizes: ApiPhotoSize[];\n blobUrl?: string;\n}\n\nexport interface ApiSticker {\n id: string;\n stickerSetId: string;\n stickerSetAccessHash?: string;\n emoji?: string;\n isAnimated: boolean;\n width?: number;\n height?: number;\n thumbnail?: ApiThumbnail;\n isPreloadedGlobally?: boolean;\n}\n\nexport interface ApiStickerSet {\n archived?: true;\n isAnimated?: true;\n installedDate?: number;\n id: string;\n accessHash: string;\n title: string;\n hasThumbnail?: boolean;\n count: number;\n stickers?: ApiSticker[];\n packs?: Record;\n covers?: ApiSticker[];\n shortName: string;\n}\n\nexport interface ApiVideo {\n id: string;\n mimeType: string;\n duration: number;\n fileName: string;\n width?: number;\n height?: number;\n supportsStreaming?: boolean;\n isRound?: boolean;\n isGif?: boolean;\n thumbnail?: ApiThumbnail;\n blobUrl?: string;\n size: number;\n}\n\nexport interface ApiAudio {\n id: string;\n size: number;\n mimeType: string;\n fileName: string;\n duration: number;\n performer?: string;\n title?: string;\n thumbnailSizes?: ApiPhotoSize[];\n}\n\nexport interface ApiVoice {\n id: string;\n duration: number;\n waveform?: number[];\n}\n\nexport interface ApiDocument {\n id?: string;\n fileName: string;\n size: number;\n timestamp?: number;\n mimeType: string;\n thumbnail?: ApiThumbnail;\n previewBlobUrl?: string;\n mediaType?: 'photo' | 'video';\n mediaSize?: ApiDimensions;\n}\n\nexport interface ApiContact {\n firstName: string;\n lastName: string;\n phoneNumber: string;\n userId: string;\n}\n\nexport interface ApiPollAnswer {\n text: string;\n option: string;\n}\n\nexport interface ApiPollResult {\n isChosen?: true;\n isCorrect?: true;\n option: string;\n votersCount: number;\n}\n\nexport interface ApiPoll {\n id: string;\n summary: {\n closed?: true;\n isPublic?: true;\n multipleChoice?: true;\n quiz?: true;\n question: string;\n answers: ApiPollAnswer[];\n closePeriod?: number;\n closeDate?: number;\n };\n results: {\n results?: ApiPollResult[];\n totalVoters?: number;\n recentVoterIds?: string[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n}\n\nexport interface ApiInvoice {\n text: string;\n title: string;\n photoUrl?: string;\n amount: number;\n currency: string;\n receiptMsgId?: number;\n isTest?: boolean;\n}\n\nexport type ApiNewPoll = {\n summary: ApiPoll['summary'];\n quiz?: {\n correctAnswers: string[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n};\n\nexport interface ApiAction {\n text: string;\n targetUserIds?: string[];\n targetChatId?: string;\n type: 'historyClear' | 'contactSignUp' | 'chatCreate' | 'other';\n photo?: ApiPhoto;\n amount?: number;\n currency?: string;\n translationValues: string[];\n call?: Partial;\n}\n\nexport interface ApiWebPage {\n id: number;\n url: string;\n displayUrl: string;\n type?: string;\n siteName?: string;\n title?: string;\n description?: string;\n photo?: ApiPhoto;\n duration?: number;\n document?: ApiDocument;\n video?: ApiVideo;\n}\n\nexport interface ApiMessageForwardInfo {\n date: number;\n isChannelPost: boolean;\n channelPostId?: number;\n isLinkedChannelPost?: boolean;\n fromChatId?: string;\n senderUserId?: string;\n fromMessageId?: number;\n hiddenUserName?: string;\n adminTitle?: string;\n}\n\nexport interface ApiMessageEntity {\n type: string;\n offset: number;\n length: number;\n userId?: string;\n url?: string;\n}\n\nexport enum ApiMessageEntityTypes {\n Bold = 'MessageEntityBold',\n Blockquote = 'MessageEntityBlockquote',\n BotCommand = 'MessageEntityBotCommand',\n Cashtag = 'MessageEntityCashtag',\n Code = 'MessageEntityCode',\n Email = 'MessageEntityEmail',\n Hashtag = 'MessageEntityHashtag',\n Italic = 'MessageEntityItalic',\n MentionName = 'MessageEntityMentionName',\n Mention = 'MessageEntityMention',\n Phone = 'MessageEntityPhone',\n Pre = 'MessageEntityPre',\n Strike = 'MessageEntityStrike',\n TextUrl = 'MessageEntityTextUrl',\n Url = 'MessageEntityUrl',\n Underline = 'MessageEntityUnderline',\n Unknown = 'MessageEntityUnknown',\n}\n\nexport interface ApiFormattedText {\n text: string;\n entities?: ApiMessageEntity[];\n}\n\nexport interface ApiMessage {\n id: number;\n chatId: string;\n content: {\n text?: ApiFormattedText;\n photo?: ApiPhoto;\n video?: ApiVideo;\n document?: ApiDocument;\n sticker?: ApiSticker;\n contact?: ApiContact;\n poll?: ApiPoll;\n action?: ApiAction;\n webPage?: ApiWebPage;\n audio?: ApiAudio;\n voice?: ApiVoice;\n invoice?: ApiInvoice;\n };\n date: number;\n isOutgoing: boolean;\n senderId?: string;\n replyToChatId?: string;\n replyToMessageId?: number;\n replyToTopMessageId?: number;\n sendingState?: 'messageSendingStatePending' | 'messageSendingStateFailed';\n forwardInfo?: ApiMessageForwardInfo;\n isDeleting?: boolean;\n previousLocalId?: number;\n views?: number;\n isEdited?: boolean;\n editDate?: number;\n isMentioned?: boolean;\n isMediaUnread?: boolean;\n groupedId?: string;\n isInAlbum?: boolean;\n hasUnreadMention?: boolean;\n inlineButtons?: ApiKeyboardButtons;\n keyboardButtons?: ApiKeyboardButtons;\n keyboardPlaceholder?: string;\n isKeyboardSingleUse?: boolean;\n viaBotId?: string;\n threadInfo?: ApiThreadInfo;\n adminTitle?: string;\n isScheduled?: boolean;\n shouldHideKeyboardButtons?: boolean;\n isFromScheduled?: boolean;\n seenByUserIds?: string[];\n isProtected?: boolean;\n}\n\nexport interface ApiThreadInfo {\n threadId: number;\n chatId: string;\n topMessageId?: number;\n originChannelId?: string;\n messagesCount: number;\n lastMessageId?: number;\n lastReadInboxMessageId?: number;\n recentReplierIds?: string[];\n}\n\nexport type ApiMessageOutgoingStatus = 'read' | 'succeeded' | 'pending' | 'failed';\n\nexport type ApiSponsoredMessage = {\n chatId?: string;\n randomId: string;\n isBot?: boolean;\n channelPostId?: number;\n startParam?: string;\n chatInviteHash?: string;\n chatInviteTitle?: string;\n text: ApiFormattedText;\n expiresAt: number;\n};\n\nexport interface ApiKeyboardButton {\n type: 'command' | 'url' | 'callback' | 'requestPoll' | 'requestSelfContact' | 'buy' | 'NOT_SUPPORTED';\n text: string;\n messageId: number;\n value?: string;\n}\n\nexport type ApiKeyboardButtons = ApiKeyboardButton[][];\nexport type ApiReplyKeyboard = {\n keyboardPlaceholder?: string;\n isKeyboardSingleUse?: boolean;\n} & {\n [K in 'inlineButtons' | 'keyboardButtons']?: ApiKeyboardButtons;\n};\n\nexport type ApiMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'voice' | 'profilePhoto';\nexport type ApiGlobalMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'voice';\n\nexport type ApiReportReason = 'spam' | 'violence' | 'pornography' | 'childAbuse'\n| 'copyright' | 'geoIrrelevant' | 'fake' | 'other';\n\nexport type ApiSendMessageAction = {\n type: 'cancel' | 'typing' | 'recordAudio' | 'chooseSticker';\n};\n\nexport const MAIN_THREAD_ID = -1;\n\n// `Symbol` can not be transferred from worker\nexport const MESSAGE_DELETED = 'MESSAGE_DELETED';\n","/* 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';\nimport { ensureProtocol } from '../../util/ensureProtocol';\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 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';\n\nimport { ApiChat, ApiUser } from '../../api/types';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport Link from '../ui/Link';\nimport { getDispatch } from '../../lib/teact/teactn';\n\ntype OwnProps = {\n className?: string;\n sender?: ApiUser | ApiChat;\n children: any;\n};\n\nconst UserLink: FC = ({\n className, sender, children,\n}) => {\n const { openUserInfo } = getDispatch();\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 UserLink;\n","import React, { FC, useCallback } from '../../lib/teact/teact';\nimport { getDispatch } from '../../lib/teact/teactn';\n\nimport { ApiMessage } from '../../api/types';\n\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\nconst MessageLink: FC = ({\n className, message, children,\n}) => {\n const { focusMessage } = getDispatch();\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 MessageLink;\n","import React, { FC, useCallback } from '../../lib/teact/teact';\nimport { getDispatch } from '../../lib/teact/teactn';\n\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\nconst ChatLink: FC = ({\n className, chatId, children,\n}) => {\n const { openChat } = getDispatch();\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 ChatLink;\n","import React, { FC, useCallback } from '../../lib/teact/teact';\n\nimport { ApiGroupCall } from '../../api/types';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport Link from '../ui/Link';\nimport { getDispatch } from '../../lib/teact/teactn';\n\ntype OwnProps = {\n className?: string;\n groupCall?: Partial;\n children: any;\n};\n\nconst GroupCallLink: FC = ({\n className, groupCall, children,\n}) => {\n const { joinGroupCall } = getDispatch();\n\n const handleClick = useCallback(() => {\n if (groupCall) {\n joinGroupCall({ id: groupCall.id, accessHash: groupCall.accessHash });\n }\n }, [groupCall, joinGroupCall]);\n\n if (!groupCall) {\n return children;\n }\n\n return (\n {children}\n );\n};\n\nexport default GroupCallLink;\n","import React from '../../../lib/teact/teact';\n\nimport {\n ApiChat, ApiMessage, ApiUser, ApiGroupCall,\n} 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';\nimport GroupCallLink from '../GroupCallLink';\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, call,\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 if (call) {\n return renderGroupCallContent(call, content);\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 renderGroupCallContent(groupCall: Partial, text: TextPart[]): string | TextPart | undefined {\n return (\n \n {text}\n \n );\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 result.push(part);\n return result;\n }\n\n divEl.innerText = part;\n result.push(divEl.innerHTML);\n\n return result;\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 result.push(part);\n return result;\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: TextPart[], part) => {\n if (typeof part !== 'string') {\n result.push(part);\n return result;\n }\n\n const splittenParts = 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\n return [...result, ...splittenParts];\n }, []);\n}\n\nfunction addHighlight(textParts: TextPart[], highlight: string | undefined): TextPart[] {\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string' || !highlight) {\n result.push(part);\n return result;\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 result.push(part);\n return result;\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 result.push(part);\n return result;\n }\n\n const links = part.match(RE_LINK);\n if (!links || !links.length) {\n result.push(part);\n return result;\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 result.push(part);\n return result;\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 { getDispatch, withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiChat, ApiUser } from '../../../api/types';\n\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\nconst MentionLink: FC = ({\n username,\n userOrChat,\n children,\n}) => {\n const {\n openChat,\n openChatByUsername,\n } = getDispatch();\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)(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-v7';\nexport const ASSET_CACHE_NAME = 'tt-assets';\nexport const AUTODOWNLOAD_FILESIZE_MB_LIMITS = [1, 5, 10, 50, 100, 500];\n\nexport const DOWNLOAD_WORKERS = 16;\nexport const UPLOAD_WORKERS = 16;\n\nconst isBigScreen = typeof window !== 'undefined' && window.innerHeight >= 900;\n\nexport const MIN_PASSWORD_LENGTH = 1;\n\nexport const MESSAGE_LIST_SLICE = isBigScreen ? 60 : 40;\nexport const MESSAGE_LIST_VIEWPORT_LIMIT = MESSAGE_LIST_SLICE * 2;\n\nexport const CHAT_HEIGHT_PX = 72;\nexport const CHAT_LIST_SLICE = isBigScreen ? 30 : 25;\nexport const CHAT_LIST_LOAD_SLICE = 100;\nexport const SHARED_MEDIA_SLICE = 42;\nexport const MESSAGE_SEARCH_SLICE = 42;\nexport const GLOBAL_SEARCH_SLICE = 20;\nexport const MEMBERS_SLICE = 30;\nexport const MEMBERS_LOAD_SLICE = 200;\nexport const PINNED_MESSAGES_LIMIT = 50;\nexport const BLOCKED_LIST_LIMIT = 100;\nexport const PROFILE_PHOTOS_LIMIT = 40;\nexport const PROFILE_SENSITIVE_AREA = 500;\nexport const COMMON_CHATS_LIMIT = 100;\nexport const GROUP_CALL_PARTICIPANTS_LIMIT = 100;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 20;\nexport const ALL_CHATS_PRELOAD_DISABLED = false;\n\nexport const SPONSORED_MESSAGE_CACHE_MS = 300000; // 5 min\n\nexport const DEFAULT_VOLUME = 1;\nexport const DEFAULT_PLAYBACK_RATE = 1;\n\nexport const ANIMATION_LEVEL_MIN = 0;\nexport const ANIMATION_LEVEL_MED = 1;\nexport const ANIMATION_LEVEL_MAX = 2;\nexport const ANIMATION_LEVEL_DEFAULT = ANIMATION_LEVEL_MAX;\n\nexport const DEFAULT_MESSAGE_TEXT_SIZE_PX = 16;\nexport const IOS_DEFAULT_MESSAGE_TEXT_SIZE_PX = 17;\nexport const MACOS_DEFAULT_MESSAGE_TEXT_SIZE_PX = 15;\n\nexport const DRAFT_DEBOUNCE = 10000; // 10s\nexport const SEND_MESSAGE_ACTION_INTERVAL = 3000; // 3s\n\nexport const EDITABLE_INPUT_ID = 'editable-message-text';\nexport const EDITABLE_INPUT_MODAL_ID = 'editable-message-text-modal';\n\n// Screen width where Pinned Message / Audio Player in the Middle Header can be safely displayed\nexport const SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1440; // px\n// Screen width where Pinned Message / Audio Player in the Middle Header shouldn't collapse with ChatInfo\nexport const SAFE_SCREEN_WIDTH_FOR_CHAT_INFO = 1150; // px\n\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1275; // px\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN = 925; // px\nexport const MOBILE_SCREEN_MAX_WIDTH = 600; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH = 950; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT = 450; // px\n\nexport const LOCAL_MESSAGE_ID_BASE = 1e9;\nexport const TMP_CHAT_ID = '0';\n\nexport const ANIMATION_END_DELAY = 100;\n\nexport const FAST_SMOOTH_MAX_DISTANCE = 1500;\nexport const FAST_SMOOTH_MIN_DURATION = 250;\nexport const FAST_SMOOTH_MAX_DURATION = 600;\nexport const FAST_SMOOTH_SHORT_TRANSITION_MAX_DISTANCE = 500; // px\n\n// Average duration of message sending animation\nexport const API_UPDATE_THROTTLE = Math.round((FAST_SMOOTH_MIN_DURATION + FAST_SMOOTH_MAX_DURATION) / 2);\nexport const API_THROTTLE_RESET_UPDATES = new Set([\n 'newMessage', 'newScheduledMessage', 'deleteMessages', 'deleteScheduledMessages', 'deleteHistory',\n]);\n\nexport const STICKER_SIZE_INLINE_DESKTOP_FACTOR = 13;\nexport const STICKER_SIZE_INLINE_MOBILE_FACTOR = 11;\nexport const STICKER_SIZE_AUTH = 160;\nexport const STICKER_SIZE_AUTH_MOBILE = 120;\nexport const STICKER_SIZE_PICKER = 64;\nexport const STICKER_SIZE_GENERAL_SETTINGS = 48;\nexport const STICKER_SIZE_PICKER_HEADER = 32;\nexport const STICKER_SIZE_SEARCH = 64;\nexport const STICKER_SIZE_MODAL = 64;\nexport const STICKER_SIZE_TWO_FA = 160;\nexport const STICKER_SIZE_DISCUSSION_GROUPS = 140;\nexport const STICKER_SIZE_FOLDER_SETTINGS = 80;\nexport const STICKER_SIZE_INLINE_BOT_RESULT = 100;\nexport const RECENT_STICKERS_LIMIT = 20;\nexport const MEMOJI_STICKER_ID = 'MEMOJI_STICKER';\n\nexport const BASE_EMOJI_KEYWORD_LANG = 'en';\n\nexport const MENU_TRANSITION_DURATION = 200;\nexport const SLIDE_TRANSITION_DURATION = 450;\n\nexport const VIDEO_MOV_TYPE = 'video/quicktime';\n\nexport const SUPPORTED_IMAGE_CONTENT_TYPES = new Set([\n 'image/png', 'image/gif', 'image/jpeg',\n]);\n\nexport const SUPPORTED_VIDEO_CONTENT_TYPES = new Set([\n 'video/mp4', // video/quicktime added dynamically in environment.ts\n]);\n\nexport const CONTENT_TYPES_WITH_PREVIEW = new Set([\n ...SUPPORTED_IMAGE_CONTENT_TYPES,\n ...SUPPORTED_VIDEO_CONTENT_TYPES,\n]);\n\nexport const CONTENT_NOT_SUPPORTED = 'The message is not supported on this version of Telegram.';\n\n// eslint-disable-next-line max-len\nexport const RE_LINK_TEMPLATE = '((ftp|https?):\\\\/\\\\/)?((www\\\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\\\.[a-zA-Z0-9()]{1,63})\\\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)';\nexport const RE_MENTION_TEMPLATE = '(@[\\\\w\\\\d_-]+)';\nexport const RE_TG_LINK = /^tg:(\\/\\/)?([?=&\\d\\w_-]+)?/gm;\nexport const RE_TME_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/)/gm;\n\n// eslint-disable-next-line max-len\nexport const COUNTRIES_WITH_12H_TIME_FORMAT = new Set(['AU', 'BD', 'CA', 'CO', 'EG', 'HN', 'IE', 'IN', 'JO', 'MX', 'MY', 'NI', 'NZ', 'PH', 'PK', 'SA', 'SV', 'US']);\n\n// MTProto constants\nexport const SERVICE_NOTIFICATIONS_USER_ID = '777000';\nexport const REPLIES_USER_ID = '1271266957'; // TODO For Test connection ID must be equal to 708513\nexport const ALL_FOLDER_ID = 0;\nexport const ARCHIVED_FOLDER_ID = 1;\nexport const DELETED_COMMENTS_CHANNEL_ID = '-777';\nexport const MAX_MEDIA_FILES_FOR_ALBUM = 10;\nexport const MAX_ACTIVE_PINNED_CHATS = 5;\nexport const SCHEDULED_WHEN_ONLINE = 0x7FFFFFFE;\nexport const DEFAULT_LANG_CODE = 'en';\nexport const DEFAULT_LANG_PACK = 'android';\nexport const LANG_PACKS = ['android', 'ios', 'tdesktop', 'macos'] as const;\nexport const TIPS_USERNAME = 'TelegramTips';\nexport const LOCALIZED_TIPS = ['ar', 'pt-br', 'id', 'it', 'ko', 'ms', 'pl', 'es', 'tr'];\nexport const FEEDBACK_URL = 'https://bugs.telegram.org/?tag_ids=41&sort=time';\nexport const LIGHT_THEME_BG_COLOR = '#A2AF8E';\nexport const DARK_THEME_BG_COLOR = '#0F0F0F';\nexport const DARK_THEME_PATTERN_COLOR = '#0a0a0a8c';\nexport const DEFAULT_PATTERN_COLOR = 'rgba(90, 110, 70, 0.6)';\n// TODO Get values from `getConfig` method once it's available\nexport const SEEN_BY_MEMBERS_CHAT_MAX = 50;\nexport const SEEN_BY_MEMBERS_EXPIRE = 604680; // One week - 2 min\n\n// Group calls\nexport const GROUP_CALL_VOLUME_MULTIPLIER = 100;\nexport const GROUP_CALL_DEFAULT_VOLUME = 100 * GROUP_CALL_VOLUME_MULTIPLIER;\nexport const ENABLE_THUMBNAIL_VIDEO = false;\n","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\nconst ANIMATION_START_EVENT = 'tt-event-heavy-animation-start';\nconst ANIMATION_END_EVENT = 'tt-event-heavy-animation-end';\n\nlet timeout: number | undefined;\nlet isAnimating = false;\n\n// Make sure to end even if end callback was not called (which was some hardly-reproducible bug)\nconst AUTO_END_TIMEOUT = 1000;\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\nexport function isHeavyAnimating() {\n return isAnimating;\n}\n\nexport function dispatchHeavyAnimationEvent(duration = AUTO_END_TIMEOUT) {\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 // Race condition may happen if another `dispatchHeavyAnimationEvent` is called before `onEnd`\n function onEnd() {\n if (timeout) {\n clearTimeout(timeout);\n timeout = undefined;\n }\n\n isAnimating = false;\n document.dispatchEvent(new Event(ANIMATION_END_EVENT));\n }\n\n timeout = window.setTimeout(onEnd, duration);\n\n return onEnd;\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;\ntype DelegationRegistry = Map;\n\nconst NON_BUBBLEABLE_EVENTS = new Set(['scroll', 'mouseenter', 'mouseleave']);\n\nconst documentEventCounters: Record = {};\nconst delegationRegistryByEventType: Record = {};\nconst delegatedEventTypesByElement = new Map>();\n\nexport function addEventListener(element: HTMLElement, propName: string, handler: Handler, asCapture = false) {\n const eventType = resolveEventType(propName, element);\n if (canUseEventDelegation(eventType, element, asCapture)) {\n addDelegatedListener(eventType, element, handler);\n } else {\n element.addEventListener(eventType, handler, asCapture);\n }\n}\n\nexport function removeEventListener(element: HTMLElement, propName: string, handler: Handler, asCapture = false) {\n const eventType = resolveEventType(propName, element);\n if (canUseEventDelegation(eventType, element, asCapture)) {\n removeDelegatedListener(eventType, element);\n } else {\n element.removeEventListener(eventType, handler, asCapture);\n }\n}\n\nfunction resolveEventType(propName: string, element: HTMLElement) {\n const eventType = propName\n .replace(/^on/, '')\n .replace(/Capture$/, '').toLowerCase();\n\n if (eventType === '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 (eventType === 'doubleclick') {\n return 'dblclick';\n }\n\n // Replace focus/blur by their \"bubbleable\" versions\n if (eventType === 'focus') {\n return 'focusin';\n }\n\n if (eventType === 'blur') {\n return 'focusout';\n }\n\n return eventType;\n}\n\nfunction canUseEventDelegation(realEventType: string, element: HTMLElement, asCapture: boolean) {\n return (\n !asCapture\n && !NON_BUBBLEABLE_EVENTS.has(realEventType)\n && element.tagName !== 'VIDEO'\n && element.tagName !== 'IFRAME'\n );\n}\n\nfunction addDelegatedListener(eventType: string, element: HTMLElement, handler: Handler) {\n if (!documentEventCounters[eventType]) {\n documentEventCounters[eventType] = 0;\n document.addEventListener(eventType, handleEvent);\n }\n\n resolveDelegationRegistry(eventType).set(element, handler);\n resolveDelegatedEventTypes(element).add(eventType);\n documentEventCounters[eventType]++;\n}\n\nfunction removeDelegatedListener(eventType: string, element: HTMLElement) {\n documentEventCounters[eventType]--;\n if (!documentEventCounters[eventType]) {\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(eventType, handleEvent);\n }\n\n delegationRegistryByEventType[eventType].delete(element);\n delegatedEventTypesByElement.get(element)!.delete(eventType);\n}\n\nexport function removeAllDelegatedListeners(element: HTMLElement) {\n const eventTypes = delegatedEventTypesByElement.get(element);\n if (!eventTypes) {\n return;\n }\n\n eventTypes.forEach((eventType) => removeDelegatedListener(eventType, element));\n delegatedEventTypesByElement.delete(element);\n}\n\nfunction handleEvent(realEvent: Event) {\n const events = delegationRegistryByEventType[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 resolveDelegationRegistry(eventType: string) {\n if (!delegationRegistryByEventType[eventType]) {\n delegationRegistryByEventType[eventType] = new Map();\n }\n\n return delegationRegistryByEventType[eventType];\n}\n\nfunction resolveDelegatedEventTypes(element: HTMLElement) {\n const existing = delegatedEventTypesByElement.get(element);\n if (existing) {\n return existing;\n }\n\n const newSet = new Set();\n delegatedEventTypesByElement.set(element, newSet);\n\n return newSet;\n}\n\nif (DEBUG) {\n document.addEventListener('dblclick', () => {\n const documentListenersCount = Object.keys(documentEventCounters).length;\n const delegatedHandlersCount1 = Object.values(documentEventCounters)\n .reduce((acc, counter) => acc + counter, 0);\n const delegationRegistriesCount = Object.keys(delegationRegistryByEventType).length;\n const delegatedHandlersCount2 = Object.values(delegationRegistryByEventType)\n .reduce((acc, delegationRegistry) => acc + delegationRegistry.size, 0);\n const delegationElementsCount = delegatedEventTypesByElement.size;\n const delegatedEventTypesCount = Array.from(delegatedEventTypesByElement.values())\n .reduce((acc, eventTypes) => acc + eventTypes.size, 0);\n\n // eslint-disable-next-line no-console\n console.warn('DELEGATED EVENTS STATS', {\n delegatedHandlersCount1,\n delegatedHandlersCount2,\n delegatedEventTypesCount,\n delegationRegistriesCount,\n delegationElementsCount,\n documentListenersCount,\n });\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', 'role']);\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 if (props[key] !== undefined) {\n setAttribute(element, key, props[key]);\n }\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 // eslint-disable-next-line no-null/no-null\n if (DEBUG && isRealElement($newChild) && (key === undefined || key === null)) {\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 // eslint-disable-next-line no-null/no-null\n const isKeyPresent = key !== undefined && key !== null;\n\n // First we handle removed children\n if (isKeyPresent && !newKeys.has(key)) {\n renderWithVirtual(currentEl, $currentChild, undefined, $new, -1);\n\n return acc;\n } else if (!isKeyPresent) {\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 const currentValue = $current.props[key];\n const newValue = $new.props[key];\n\n if (\n currentValue !== undefined\n && (\n newValue === undefined\n || (currentValue !== newValue && key.startsWith('on'))\n )\n ) {\n removeAttribute(element, key, currentValue);\n }\n });\n\n newKeys.forEach((key) => {\n const currentValue = $current.props[key];\n const newValue = $new.props[key];\n\n if (newValue !== undefined && newValue !== currentValue) {\n setAttribute(element, key, newValue);\n }\n });\n}\n\nfunction setAttribute(element: HTMLElement, key: string, value: any) {\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 === 'dangerouslySetInnerHTML') {\n // eslint-disable-next-line no-underscore-dangle\n element.innerHTML = value.__html;\n } else if (key.startsWith('on')) {\n addEventListener(element, key, value, key.endsWith('Capture'));\n } else if (key.startsWith('data-') || key.startsWith('aria-') || 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 === 'dangerouslySetInnerHTML') {\n element.innerHTML = '';\n } else if (key.startsWith('on')) {\n removeEventListener(element, key, value, key.endsWith('Capture'));\n } else if (key.startsWith('data-') || key.startsWith('aria-') || 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\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\nconst DEBUG_RENDER_THRESHOLD = 7;\nconst DEBUG_EFFECT_THRESHOLD = 7;\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.warn('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 duration = performance.now() - DEBUG_startAt!;\n const componentName = componentInstance.name;\n if (duration > DEBUG_RENDER_THRESHOLD) {\n // eslint-disable-next-line no-console\n console.warn(`[Teact] Slow component render: ${componentName}, ${Math.round(duration)} ms`);\n }\n DEBUG_components[componentName].renderTimes.push(duration);\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 // 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 cleanup();\n\n if (DEBUG) {\n const duration = performance.now() - DEBUG_startAt!;\n const componentName = componentInstance.name;\n if (duration > DEBUG_EFFECT_THRESHOLD) {\n // eslint-disable-next-line no-console\n console.warn(\n `[Teact] Slow cleanup at effect cursor #${cursor}: ${componentName}, ${Math.round(duration)} ms`,\n );\n }\n }\n } catch (err) {\n handleError(err);\n }\n }\n }\n\n function exec() {\n if (!componentInstance.isMounted) {\n return;\n }\n\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 byCursor[cursor].cleanup = effect() as Function;\n\n if (DEBUG) {\n const duration = performance.now() - DEBUG_startAt!;\n const componentName = componentInstance.name;\n if (duration > DEBUG_EFFECT_THRESHOLD) {\n // eslint-disable-next-line no-console\n console.warn(`[Teact] Slow effect at cursor #${cursor}: ${componentName}, ${Math.round(duration)} ms`);\n }\n }\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(`[Teact] Effect \"${debugKey}\" caused by dependencies.`, causedBy.join(', '));\n }\n\n primarySchedulerFn(execCleanup);\n schedulerFn(exec);\n }\n } else {\n if (debugKey) {\n // eslint-disable-next-line no-console\n console.log(`[Teact] Effect \"${debugKey}\" caused by missing dependencies.`);\n }\n\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[], debugKey?: string): F {\n // eslint-disable-next-line react-hooks/exhaustive-deps\n return useMemo(() => newCallback, dependencies, debugKey);\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 { fastRaf, throttleWithTickEnd } from '../../util/schedulers';\nimport arePropsShallowEqual, { getUnequalProps } from '../../util/arePropsShallowEqual';\nimport { orderBy } from '../../util/iteratees';\nimport {\n GlobalState, GlobalActions, ActionTypes, DispatchOptions,\n} from '../../global/types';\nimport { handleError } from '../../util/handleError';\nimport { isHeavyAnimating } from '../../hooks/useHeavyAnimationCheck';\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);\n\nlet currentGlobal = {} as GlobalState;\n\nconst reducers: Record = {};\nconst callbacks: Function[] = [updateContainers];\nconst actions = {} as GlobalActions;\nconst containers = new Map;\n ownProps: Props;\n mappedProps?: Props;\n forceUpdate: Function;\n areMappedPropsChanged: boolean;\n DEBUG_updates: number;\n DEBUG_componentName: string;\n}>();\n\nconst runCallbacksThrottled = throttleWithTickEnd(runCallbacks);\n\nfunction runCallbacks(forceOnHeavyAnimation = false) {\n if (!forceOnHeavyAnimation && isHeavyAnimating()) {\n fastRaf(runCallbacksThrottled);\n return;\n }\n\n callbacks.forEach((cb) => cb(currentGlobal));\n}\n\nexport function setGlobal(newGlobal?: GlobalState, options?: DispatchOptions) {\n if (typeof newGlobal === 'object' && newGlobal !== currentGlobal) {\n currentGlobal = newGlobal;\n if (options?.forceSyncOnIOs) {\n runCallbacks(true);\n } else {\n runCallbacksThrottled(options?.forceOnHeavyAnimation);\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, options?: DispatchOptions) {\n if (reducers[name]) {\n reducers[name].forEach((reducer) => {\n const newGlobal = reducer(currentGlobal, actions, payload);\n if (newGlobal) {\n setGlobal(newGlobal, options);\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, ownProps, mappedProps, forceUpdate,\n } = container;\n\n let newMappedProps;\n\n try {\n newMappedProps = mapStateToProps(currentGlobal, ownProps);\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, options?: DispatchOptions) => {\n onDispatch(name, payload, options);\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) {\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 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 = mapStateToProps(currentGlobal, props);\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.warn(\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 });\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_SAFARI, 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';\nimport { ensurePermanentWebVersion } from '../../../util/permanentWebVersion';\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\n switchTheme(theme, animationLevel === ANIMATION_LEVEL_MAX);\n\n ensurePermanentWebVersion();\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 if (IS_SAFARI) {\n document.body.classList.add('is-safari');\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 }, { forceSyncOnIOs: 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 { GlobalState } from '../../global/types';\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';\nimport { prepareSearchWordsForNeedle } from '../../util/searchWords';\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(chat.joinDate || 0, chat.draftDate || 0, chat.lastMessage?.date || 0);\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 allListIds: GlobalState['chats']['listIds'],\n chatsById: Record,\n usersById: Record,\n folder: ApiChatFolder,\n notifySettings: NotifySettings,\n notifyExceptions?: Record,\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 = ([] as string[]).concat(allListIds.active || [], allListIds.archived || [])\n .filter((id) => {\n const chat = chatsById[id];\n return chat && filterChatFolder(\n chat,\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\n// This function is the most expensive in the project, so any possible optimizations are welcome\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 const { id: chatId, type, unreadMentionsCount } = chat;\n\n if (excludedChatIds?.has(chatId)) {\n return false;\n }\n\n if (includedChatIds?.has(chatId)) {\n return true;\n }\n\n if (pinnedChatIds?.has(chatId)) {\n return true;\n }\n\n if (folder.excludeArchived && chat.folderId === ARCHIVED_FOLDER_ID) {\n return false;\n }\n\n if (folder.excludeRead && !chat.unreadCount && !unreadMentionsCount && !chat.hasUnreadMark) {\n return false;\n }\n\n if (folder.excludeMuted && !unreadMentionsCount && selectIsChatMuted(chat, notifySettings, notifyExceptions)) {\n return false;\n }\n\n if (type === 'chatTypePrivate') {\n const user = usersById[chatId];\n if (user) {\n const { type: userType, isContact } = user;\n\n if (userType === 'userTypeBot') {\n if (folder.bots) {\n return true;\n }\n } else {\n if (folder.contacts && isContact) {\n return true;\n }\n\n if (folder.nonContacts && !isContact) {\n return true;\n }\n }\n }\n } else if (type === 'chatTypeChannel') {\n return !!folder.channels;\n } else if (type === 'chatTypeBasicGroup' || type === 'chatTypeSuperGroup') {\n return !!folder.groups;\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 noOrder = false,\n) {\n const listIdsSet = new Set(listIds);\n const orderedPinnedIdsSet = orderedPinnedIds ? new Set(orderedPinnedIds) : undefined;\n\n const pinnedChats = orderedPinnedIds?.reduce((acc, id) => {\n const chat = chatsById[id];\n\n if (chat && listIdsSet.has(chat.id) && checkChat(chat, folderType)) {\n acc.push(chat);\n }\n\n return acc;\n }, [] as ApiChat[]) || [];\n\n const otherChats = listIds.reduce((acc, id) => {\n const chat = chatsById[id];\n\n if (chat && (!orderedPinnedIdsSet || !orderedPinnedIdsSet.has(chat.id)) && checkChat(chat, folderType)) {\n acc.push(chat);\n }\n\n return acc;\n }, [] as ApiChat[]);\n\n return {\n pinnedChats,\n otherChats: noOrder ? otherChats : orderBy(otherChats, getChatOrder, 'desc'),\n };\n}\n\nfunction checkChat(chat: ApiChat, folderType: 'all' | 'archived' | 'folder') {\n return (\n chat.lastMessage && !chat.migratedTo && !chat.isRestricted && !chat.isNotJoined\n && !(folderType === 'all' && chat.folderId === ARCHIVED_FOLDER_ID)\n && !(folderType === 'archived' && chat.folderId !== ARCHIVED_FOLDER_ID)\n );\n}\n\nexport function reduceChatList(\n chatArrays: { pinnedChats: ApiChat[]; otherChats: ApiChat[] },\n filteredIds: string[],\n) {\n const filteredIdsSet = new Set(filteredIds);\n\n return {\n pinnedChats: chatArrays.pinnedChats.filter(({ id }) => filteredIdsSet.has(id)),\n otherChats: chatArrays.otherChats.filter(({ id }) => filteredIdsSet.has(id)),\n };\n}\n\nexport function getFolderUnreadDialogs(\n allListIds: GlobalState['chats']['listIds'],\n chatsById: Record,\n usersById: Record,\n folder: ApiChatFolder,\n notifySettings: NotifySettings,\n notifyExceptions?: Record,\n) {\n const [listIds] = prepareFolderListIds(allListIds, chatsById, usersById, folder, notifySettings, notifyExceptions);\n\n let hasActiveDialogs = false;\n const unreadDialogsCount = listIds.reduce((acc, id) => {\n const chat = chatsById[id];\n if (!chat?.lastMessage || chat?.isRestricted || chat?.isNotJoined) {\n return acc;\n }\n\n const isUnread = chat.unreadCount || chat.hasUnreadMark;\n\n if (isUnread) {\n acc++;\n }\n\n if (!hasActiveDialogs && (\n chat.unreadMentionsCount || (isUnread && !selectIsChatMuted(chat, notifySettings, notifyExceptions))\n )) {\n hasActiveDialogs = true;\n }\n\n return acc;\n }, 0);\n\n return {\n unreadDialogsCount,\n hasActiveDialogs,\n };\n}\n\nexport function getFolderDescriptionText(\n lang: LangFn,\n allListIds: GlobalState['chats']['listIds'],\n chatsById: Record,\n usersById: Record,\n folder: ApiChatFolder,\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(allListIds, chatsById, usersById, folder, 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 allListIds: GlobalState['chats']['listIds'],\n chatsById: Record,\n usersById: Record,\n folder: ApiChatFolder,\n notifySettings: NotifySettings,\n notifyExceptions?: Record,\n) {\n const [listIds, pinnedIds] = prepareFolderListIds(\n allListIds, chatsById, usersById, folder, notifySettings, notifyExceptions,\n );\n const { pinnedChats, otherChats } = prepareChatList(chatsById, listIds, pinnedIds, 'folder', true);\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\nexport function filterChatsByName(\n lang: LangFn,\n chatIds: string[],\n chatsById: Record,\n query?: string,\n currentUserId?: string,\n) {\n if (!query) {\n return chatIds;\n }\n\n const searchWords = prepareSearchWordsForNeedle(query);\n\n return chatIds.filter((id) => {\n const chat = chatsById[id];\n if (!chat) {\n return false;\n }\n\n return searchWords(getChatTitle(lang, chat, undefined, id === currentUserId));\n });\n}\n","import {\n ApiChat, ApiMessage, ApiMessageEntityTypes, ApiUser,\n} from '../../api/types';\nimport { LangFn } from '../../hooks/useLang';\n\nimport {\n LOCAL_MESSAGE_ID_BASE,\n SERVICE_NOTIFICATIONS_USER_ID,\n RE_LINK_TEMPLATE,\n CONTENT_NOT_SUPPORTED,\n} 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 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 mediaId = (messagePhoto || messageVideo || sticker || audio || voice || document)!.id;\n const base = `${getMessageKey(message)}${mediaId ? `:${mediaId}` : ''}`;\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, ApiUserStatus } 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';\nimport { prepareSearchWordsForNeedle } from '../../util/searchWords';\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(\n lang: LangFn, user: ApiUser, userStatus: ApiUserStatus | undefined, serverTimeOffset: number,\n) {\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 (!userStatus) {\n return '';\n }\n\n switch (userStatus.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 } = userStatus;\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, userStatus?: ApiUserStatus) {\n const { id, type } = user;\n\n if (!userStatus) {\n return false;\n }\n\n if (id === SERVICE_NOTIFICATIONS_USER_ID) {\n return false;\n }\n\n return userStatus.type === 'userStatusOnline' && type !== 'userTypeBot';\n}\n\nexport function isDeletedUser(user: ApiUser) {\n if (user.noStatus || 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 userStatusesById: 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 const userStatus = userStatusesById[id];\n if (!user || !userStatus) {\n return 0;\n }\n\n if (userStatus.type === 'userStatusOnline') {\n return userStatus.expires;\n } else if (userStatus.type === 'userStatusOffline' && userStatus.wasOnline) {\n return userStatus.wasOnline;\n }\n\n switch (userStatus.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 filterUsersByName(userIds: string[], usersById: Record, query?: string) {\n if (!query) {\n return userIds;\n }\n\n const searchWords = prepareSearchWordsForNeedle(query);\n\n return userIds.filter((id) => {\n const user = usersById[id];\n if (!user) {\n return false;\n }\n\n const name = getUserFullName(user);\n return (name && searchWords(name)) || searchWords(user.username);\n });\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\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 if (!updatedChat) {\n return global;\n }\n\n return replaceChats(global, {\n ...byId,\n [chatId]: updatedChat,\n });\n}\n\nexport function updateChats(global: GlobalState, newById: Record): GlobalState {\n const updatedById = Object.keys(newById).reduce((acc: Record, id) => {\n const updatedChat = getUpdatedChat(global, id, newById[id]);\n if (updatedChat) {\n acc[id] = updatedChat;\n }\n\n return acc;\n }, {});\n\n global = replaceChats(global, {\n ...global.chats.byId,\n ...updatedById,\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, newById: Record): GlobalState {\n const { byId } = global.chats;\n let isUpdated = false;\n\n const addedById = Object.keys(newById).reduce>((acc, id) => {\n if (!byId[id] || (byId[id].isMin && !newById[id].isMin)) {\n const updatedChat = getUpdatedChat(global, id, newById[id]);\n if (updatedChat) {\n acc[id] = updatedChat;\n if (!isUpdated) {\n isUpdated = true;\n }\n }\n }\n return acc;\n }, {});\n\n if (!isUpdated) {\n return global;\n }\n\n global = replaceChats(global, {\n ...byId,\n ...addedById,\n });\n\n return global;\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) {\n const { byId } = global.chats;\n const chat = byId[chatId];\n const shouldOmitMinInfo = chatUpdate.isMin && chat && !chat.isMin;\n const updatedChat: ApiChat = {\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 undefined;\n }\n\n return updatedChat;\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 {\n ApiMessage, ApiSponsoredMessage, ApiThreadInfo, MAIN_THREAD_ID,\n} 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 updateSponsoredMessage(\n global: GlobalState, chatId: string, message: ApiSponsoredMessage,\n): GlobalState {\n return {\n ...global,\n messages: {\n ...global.messages,\n sponsoredByChatId: {\n ...global.messages.sponsoredByChatId,\n [chatId]: message,\n },\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, ApiUserStatus } from '../../api/types';\n\nimport { omit, pick } 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\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 if (!updatedUser) {\n return global;\n }\n\n global = updateContactList(global, [updatedUser]);\n\n return replaceUsers(global, {\n ...byId,\n [userId]: updatedUser,\n });\n}\n\nexport function updateUsers(global: GlobalState, newById: Record): GlobalState {\n const updatedById = Object.keys(newById).reduce((acc: Record, id) => {\n const updatedUser = getUpdatedUser(global, id, newById[id]);\n if (updatedUser) {\n acc[id] = updatedUser;\n }\n\n return acc;\n }, {});\n\n global = replaceUsers(global, {\n ...global.users.byId,\n ...updatedById,\n });\n\n global = updateContactList(global, Object.values(updatedById));\n\n return global;\n}\n\n// @optimization Allows to avoid redundant updates which cause a lot of renders\nexport function addUsers(global: GlobalState, newById: Record): GlobalState {\n const { byId } = global.users;\n let isUpdated = false;\n\n const addedById = Object.keys(newById).reduce>((acc, id) => {\n if (!byId[id] || (byId[id].isMin && !newById[id].isMin)) {\n const updatedUser = getUpdatedUser(global, id, newById[id]);\n if (updatedUser) {\n acc[id] = updatedUser;\n if (!isUpdated) {\n isUpdated = true;\n }\n }\n }\n return acc;\n }, {});\n\n if (!isUpdated) {\n return global;\n }\n\n global = replaceUsers(global, {\n ...byId,\n ...addedById,\n });\n\n global = updateContactList(global, Object.values(addedById));\n\n return global;\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) {\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 undefined;\n }\n\n return updatedUser;\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 deleteContact(global: GlobalState, userId: string): GlobalState {\n const { byId } = global.users;\n const { userIds } = global.contactList || {};\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, {\n ...byId,\n [userId]: {\n ...byId[userId],\n isContact: undefined,\n },\n });\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\nexport function replaceUserStatuses(global: GlobalState, newById: Record): GlobalState {\n return {\n ...global,\n users: {\n ...global.users,\n statusesById: newById,\n },\n };\n}\n\n// @optimization Allows to avoid redundant updates which cause a lot of renders\nexport function addUserStatuses(global: GlobalState, newById: Record): GlobalState {\n const { statusesById } = global.users;\n\n const newKeys = Object.keys(newById).filter((id) => !statusesById[id]);\n if (!newKeys.length) {\n return global;\n }\n\n global = replaceUserStatuses(global, {\n ...statusesById,\n ...pick(newById, newKeys),\n });\n\n return global;\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 { 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 (\n userId !== global.currentUserId\n && global.users.byId[userId]\n && isUserOnline(global.users.byId[userId], global.users.statusesById[userId])\n ) {\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\nexport function selectSendAs(global: GlobalState, chatId: string) {\n const chat = selectChat(global, chatId);\n if (!chat) return undefined;\n\n const id = chat?.fullInfo?.sendAsId;\n if (!id) return undefined;\n\n return selectUser(global, id) || selectChat(global, 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 // Favorites\n global.stickers.favorite.stickers.forEach((sticker) => {\n if (sticker.emoji === emoji) stickersForEmoji.push(sticker);\n });\n\n // Added sets\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 return listIds.find((id) => {\n return (\n (!lastReadId || 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(global: GlobalState, message: ApiMessage) {\n const chat = selectChat(global, message.chatId);\n if (!chat) {\n return undefined;\n }\n\n const sender = selectSender(global, message);\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\nexport function selectIsMessageProtected(global: GlobalState, message?: ApiMessage) {\n return message ? message.isProtected || selectChat(global, message.chatId)?.isProtected : false;\n}\n\nexport function selectHasProtectedMessage(global: GlobalState, chatId: string, messageIds?: number[]) {\n if (selectChat(global, chatId)?.isProtected) {\n return true;\n }\n\n if (!messageIds) {\n return false;\n }\n\n const messages = selectChatMessages(global, chatId);\n\n return messageIds.some((messageId) => messages[messageId]?.isProtected);\n}\n\nexport function selectSponsoredMessage(global: GlobalState, chatId: string) {\n const chat = selectChat(global, chatId);\n const message = chat && isChatChannel(chat) ? global.messages.sponsoredByChatId[chatId] : undefined;\n\n return message && message.expiresAt >= Math.round(Date.now() / 1000) ? message : undefined;\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 { 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 { GlobalState } from '../../global/types';\nimport { ApiChat, ApiUser, ApiUserStatus } from '../../api/types';\n\nexport function selectUser(global: GlobalState, userId: string): ApiUser | undefined {\n return global.users.byId[userId];\n}\n\nexport function selectUserStatus(global: GlobalState, userId: string): ApiUserStatus | undefined {\n return global.users.statusesById[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 {\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 ChatNewAdminRights,\n GroupMembers,\n GroupAddAdmins,\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\nexport type TimingFn = (t: number) => number;\n\nexport type AnimateNumberProps = {\n to: number | number[];\n from: number | number[];\n duration: number;\n onUpdate: (value: any) => void;\n timing?: TimingFn;\n onEnd?: () => void;\n};\n\nexport const timingFunctions = {\n linear: (t: number) => t,\n easeIn: (t: number) => t ** 1.675,\n easeOut: (t: number) => 1 - (1 - t ** 1.675),\n easeInOut: (t: number) => 0.5 * (Math.sin((t - 0.5) * Math.PI) + 1),\n easeInQuad: (t: number) => t * t,\n easeOutQuad: (t: number) => t * (2 - t),\n easeInOutQuad: (t: number) => (t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t),\n easeInCubic: (t: number) => t * t * t,\n easeOutCubic: (t: number) => (--t) * t * t + 1,\n easeInOutCubic: (t: number) => (t < 0.5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1),\n easeInQuart: (t: number) => t * t * t * t,\n easeOutQuart: (t: number) => 1 - (--t) * t * t * t,\n easeInOutQuart: (t: number) => (t < 0.5 ? 8 * t * t * t * t : 1 - 8 * (--t) * t * t * t),\n easeInQuint: (t: number) => t * t * t * t * t,\n easeOutQuint: (t: number) => 1 + (--t) * t * t * t * t,\n easeInOutQuint: (t: number) => (t < 0.5 ? 16 * t * t * t * t * t : 1 + 16 * (--t) * t * t * t * t),\n};\n\nexport function animateNumber({\n timing = timingFunctions.linear,\n onUpdate,\n duration,\n onEnd,\n from,\n to,\n}: AnimateNumberProps) {\n const t0 = Date.now();\n let canceled = false;\n\n animate(() => {\n if (canceled) return false;\n const t1 = Date.now();\n let t = (t1 - t0) / duration;\n if (t > 1) t = 1;\n const progress = timing(t);\n if (typeof from === 'number' && typeof to === 'number') {\n onUpdate(from + ((to - from) * progress));\n } else if (Array.isArray(from) && Array.isArray(to)) {\n const result = from.map((f, i) => f + ((to[i] - f) * progress));\n onUpdate(result);\n }\n if (t === 1 && onEnd) onEnd();\n return t < 1;\n });\n\n return () => {\n canceled = true;\n if (onEnd) onEnd();\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 // Workaround for https://bugs.telegram.org/c/5777\n .replace(/'de'/g, 'de');\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(datetime: Date | number, locale = 'en-US') {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n return date.toLocaleString(\n locale,\n {\n year: 'numeric',\n month: 'short',\n day: 'numeric',\n },\n );\n}\n\nexport function formatDateTimeToString(datetime: Date | number, locale = 'en-US') {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n return date.toLocaleString(\n locale,\n {\n year: 'numeric',\n month: 'short',\n day: 'numeric',\n hour: 'numeric',\n minute: 'numeric',\n second: '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[^\\ufe0f]/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","export function ensureProtocol(url?: string) {\n if (!url) {\n return undefined;\n }\n\n // HTTP was chosen by default as a fix for https://bugs.telegram.org/c/10712.\n // It is also the default protocol in the official TDesktop client.\n return url.includes('://') ? url : `http://${url}`;\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 = (\n window.matchMedia('(display-mode: standalone)').matches\n || (window.navigator as any).standalone\n || document.referrer.includes('android-app://')\n);\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 IS_REQUEST_FULLSCREEN_SUPPORTED = 'requestFullscreen' in document.createElement('div');\nexport const ARE_CALLS_SUPPORTED = !navigator.userAgent.includes('Firefox');\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\nexport const IS_SCROLL_PATCH_NEEDED = !IS_MAC_OS && !IS_IOS && !IS_ANDROID;\n\n// Smaller area reduces scroll jumps caused by `patchChromiumScroll`\nexport const MESSAGE_LIST_SENSITIVE_AREA = IS_SCROLL_PATCH_NEEDED ? 300 : 750;\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 ADMINS_TOO_MUCH: 'There are too many admins',\n ADMIN_RANK_EMOJI_NOT_ALLOWED: 'An admin rank cannot contain emojis',\n ADMIN_RANK_INVALID: 'The specified admin rank is invalid',\n FRESH_CHANGE_ADMINS_FORBIDDEN: 'You were just elected admin, you can\\'t add or modify other admins yet',\n INPUT_USER_DEACTIVATED: 'The specified user was deleted',\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 =\n 'asc'\n | 'desc';\n\ninterface OrderCallback {\n (member: T): any;\n}\n\nexport function buildCollectionByKey(collection: T[], key: keyof T) {\n return collection.reduce((byKey: CollectionByKey, member: T) => {\n byKey[member[key]] = member;\n\n return byKey;\n }, {});\n}\n\nexport function mapValues(\n byKey: CollectionByKey,\n callback: (member: M, key: string, index: number, originalByKey: CollectionByKey) => R,\n): CollectionByKey {\n return Object.keys(byKey).reduce((newByKey: CollectionByKey, key, index) => {\n newByKey[key] = callback(byKey[key], key, index, byKey);\n return newByKey;\n }, {});\n}\n\nexport function pick(object: T, keys: K[]) {\n return keys.reduce((result, key) => {\n result[key] = object[key];\n return result;\n }, {} as Pick);\n}\n\nexport function pickTruthy(object: T, keys: K[]) {\n return keys.reduce((result, key) => {\n if (object[key]) {\n result[key] = object[key];\n }\n\n return result;\n }, {} as Pick);\n}\n\nexport function omit(object: T, keys: K[]) {\n const stringKeys = new Set(keys.map(String));\n const savedKeys = Object.keys(object)\n .filter((key) => !stringKeys.has(key)) as Array>;\n\n return pick(object, savedKeys);\n}\n\nexport function orderBy(\n collection: T[],\n orderRule: (keyof T) | OrderCallback | ((keyof T) | OrderCallback)[],\n mode: OrderDirection | [OrderDirection, OrderDirection] = 'asc',\n): T[] {\n function compareValues(a: T, b: T, currentOrderRule: (keyof T) | OrderCallback, isAsc: boolean) {\n const aValue = (typeof currentOrderRule === 'function' ? currentOrderRule(a) : a[currentOrderRule]) || 0;\n const bValue = (typeof currentOrderRule === 'function' ? currentOrderRule(b) : b[currentOrderRule]) || 0;\n\n return isAsc ? aValue - bValue : bValue - aValue;\n }\n\n if (Array.isArray(orderRule)) {\n const [mode1, mode2] = Array.isArray(mode) ? mode : [mode, mode];\n const [orderRule1, orderRule2] = orderRule;\n const isAsc1 = mode1 === 'asc';\n const isAsc2 = mode2 === 'asc';\n\n return collection.sort((a, b) => {\n return compareValues(a, b, orderRule1, isAsc1) || compareValues(a, b, orderRule2, isAsc2);\n });\n }\n\n const isAsc = mode === 'asc';\n return collection.sort((a, b) => {\n return compareValues(a, b, orderRule, isAsc);\n });\n}\n\nexport function flatten(array: any[]) {\n return array.reduce((result, member) => {\n if (Array.isArray(member)) {\n return result.concat(member);\n } else {\n result.push(member);\n return result;\n }\n }, []);\n}\n\nexport function unique(array: T[]): T[] {\n return Array.from(new Set(array));\n}\n\nexport function compact(array: any[]) {\n return array.filter(Boolean);\n}\n\nexport function areSortedArraysEqual(array1: any[], array2: any[]) {\n if (array1.length !== array2.length) {\n return false;\n }\n\n return array1.every((item, i) => item === array2[i]);\n}\n\nexport function areSortedArraysIntersecting(array1: any[], array2: any[]) {\n return array1[0] <= array2[array2.length - 1] && array1[array1.length - 1] >= array2[0];\n}\n\nexport function findIntersectionWithSet(array: T[], set: Set): T[] {\n return array.filter((a) => set.has(a));\n}\n\nexport function split(array: any[], chunkSize: number) {\n const result = [];\n for (let i = 0; i < array.length; i += chunkSize) {\n result.push(array.slice(i, i + chunkSize));\n }\n\n return result;\n}\n\nexport function cloneDeep(value: T): T {\n if (typeof value !== 'object') {\n return value;\n }\n\n if (Array.isArray(value)) {\n return value.map(cloneDeep) as typeof value;\n }\n\n return Object.keys(value).reduce((acc, key) => {\n acc[key as keyof T] = cloneDeep(value[key as keyof T]);\n return acc;\n }, {} as T);\n}\n\nexport function findLast(array: Array, predicate: (value: T, index: number, obj: T[]) => boolean): T | undefined {\n let cursor = array.length;\n\n while (cursor--) {\n if (predicate(array[cursor], cursor, array)) {\n return array[cursor];\n }\n }\n\n return undefined;\n}\n","import { 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 Calls,\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 [Bundles.Calls]: typeof import('../bundles/calls');\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 case Bundles.Calls:\n LOAD_PROMISES[Bundles.Calls] = import('../bundles/calls');\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","const PERMANENT_VERSION_KEY = 'kz_version';\nconst AVAILABLE_VERSIONS = ['Z', 'K'] as const;\nconst DEFAULT_VERSION = 'Z';\n\nexport function setPermanentWebVersion(version: typeof AVAILABLE_VERSIONS[number]) {\n localStorage.setItem(PERMANENT_VERSION_KEY, JSON.stringify(version));\n}\n\nexport function ensurePermanentWebVersion() {\n if (!hasPermanentWebVersion()) {\n setPermanentWebVersion(DEFAULT_VERSION);\n }\n}\n\nfunction hasPermanentWebVersion() {\n const json = localStorage.getItem(PERMANENT_VERSION_KEY);\n if (!json) {\n return false;\n }\n\n try {\n const version = JSON.parse(json);\n return AVAILABLE_VERSIONS.includes(version);\n } catch (err) {\n return false;\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 fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n waitingTimeout = self.setTimeout(() => {\n if (shouldRunLast) {\n fn(...args);\n }\n\n waitingTimeout = undefined;\n }, ms);\n };\n}\n\nexport function throttle(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n) {\n let interval: number | undefined;\n let isPending: boolean;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n isPending = true;\n args = _args;\n\n if (!interval) {\n if (shouldRunFirst) {\n isPending = false;\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n interval = self.setInterval(() => {\n if (!isPending) {\n // eslint-disable-next-line no-restricted-globals\n self.clearInterval(interval!);\n interval = undefined;\n return;\n }\n\n isPending = false;\n fn(...args);\n }, ms);\n }\n };\n}\n\nexport function throttleWithRaf(fn: F) {\n return throttleWith(fastRaf, fn);\n}\n\nexport function throttleWithPrimaryRaf(fn: F) {\n return throttleWith(fastRafPrimary, fn);\n}\n\nexport function throttleWithTickEnd(fn: F) {\n return throttleWith(onTickEnd, fn);\n}\n\nexport function throttleWithNow(fn: F) {\n return throttleWith(runNow, fn);\n}\n\nexport function throttleWith(schedulerFn: Scheduler, fn: F) {\n let waiting = false;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n args = _args;\n\n if (!waiting) {\n waiting = true;\n\n schedulerFn(() => {\n waiting = false;\n fn(...args);\n });\n }\n };\n}\n\nexport function onIdle(cb: NoneToVoidFunction, timeout?: number) {\n // eslint-disable-next-line no-restricted-globals\n if (self.requestIdleCallback) {\n // eslint-disable-next-line no-restricted-globals\n self.requestIdleCallback(cb, { timeout });\n } else {\n onTickEnd(cb);\n }\n}\n\nfunction runNow(fn: NoneToVoidFunction) {\n fn();\n}\n\nexport const pause = (ms: number) => new Promise((resolve) => {\n setTimeout(() => resolve(), ms);\n});\n\nexport function rafPromise() {\n return new Promise((resolve) => {\n fastRaf(resolve);\n });\n}\n\nlet fastRafCallbacks: NoneToVoidFunction[] | undefined;\nlet fastRafPrimaryCallbacks: NoneToVoidFunction[] | undefined;\n\n// May result in an immediate execution if called from another `requestAnimationFrame` callback\nexport function fastRaf(callback: NoneToVoidFunction, isPrimary = false) {\n if (!fastRafCallbacks) {\n fastRafCallbacks = isPrimary ? [] : [callback];\n fastRafPrimaryCallbacks = isPrimary ? [callback] : [];\n\n requestAnimationFrame(() => {\n const currentCallbacks = fastRafCallbacks!;\n const currentPrimaryCallbacks = fastRafPrimaryCallbacks!;\n fastRafCallbacks = undefined;\n fastRafPrimaryCallbacks = undefined;\n currentPrimaryCallbacks.forEach((cb) => cb());\n currentCallbacks.forEach((cb) => cb());\n });\n } else if (isPrimary) {\n fastRafPrimaryCallbacks!.push(callback);\n } else {\n fastRafCallbacks.push(callback);\n }\n}\n\nexport function fastRafPrimary(callback: NoneToVoidFunction) {\n fastRaf(callback, true);\n}\n\nlet onTickEndCallbacks: NoneToVoidFunction[] | undefined;\nlet onTickEndPrimaryCallbacks: NoneToVoidFunction[] | undefined;\n\nexport function onTickEnd(callback: NoneToVoidFunction, isPrimary = false) {\n if (!onTickEndCallbacks) {\n onTickEndCallbacks = isPrimary ? [] : [callback];\n onTickEndPrimaryCallbacks = isPrimary ? [callback] : [];\n\n Promise.resolve().then(() => {\n const currentCallbacks = onTickEndCallbacks!;\n const currentPrimaryCallbacks = onTickEndPrimaryCallbacks!;\n onTickEndCallbacks = undefined;\n onTickEndPrimaryCallbacks = undefined;\n currentPrimaryCallbacks.forEach((cb) => cb());\n currentCallbacks.forEach((cb) => cb());\n });\n } else if (isPrimary) {\n onTickEndPrimaryCallbacks!.push(callback);\n } else {\n onTickEndCallbacks.push(callback);\n }\n}\n\nexport function onTickEndPrimary(callback: NoneToVoidFunction) {\n onTickEnd(callback, true);\n}\n\nlet beforeUnloadCallbacks: NoneToVoidFunction[] | undefined;\n\nexport function onBeforeUnload(callback: NoneToVoidFunction, isLast = false) {\n if (!beforeUnloadCallbacks) {\n beforeUnloadCallbacks = [];\n // eslint-disable-next-line no-restricted-globals\n self.addEventListener('beforeunload', () => {\n beforeUnloadCallbacks!.forEach((cb) => cb());\n });\n }\n\n if (isLast) {\n beforeUnloadCallbacks.push(callback);\n } else {\n beforeUnloadCallbacks.unshift(callback);\n }\n\n return () => {\n beforeUnloadCallbacks = beforeUnloadCallbacks!.filter((cb) => cb !== callback);\n };\n}\n","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 | string[]) {\n if (!haystack || !needle) {\n return false;\n }\n\n const needleWords = typeof needle === 'string' ? needle.toLowerCase().split(RE_NOT_LETTER) : needle;\n const haystackLower = haystack.toLowerCase();\n\n // @optimization\n if (needleWords.length === 1 && !haystackLower.includes(needleWords[0])) {\n return false;\n }\n\n let haystackWords: string[];\n\n return needleWords.every((needleWord) => {\n if (!haystackLower.includes(needleWord)) {\n return false;\n }\n\n if (!haystackWords) {\n haystackWords = haystackLower.split(RE_NOT_LETTER);\n }\n\n return haystackWords.some((haystackWord) => haystackWord.startsWith(needleWord));\n });\n}\n\nexport function prepareSearchWordsForNeedle(needle: string) {\n const needleWords = needle.toLowerCase().split(RE_NOT_LETTER);\n\n return (haystack: string) => searchWords(haystack, needleWords);\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 + \".\" + {\"87\":\"74a4d72480e8214a0dde\",\"99\":\"f03a947e6e336feffec8\",\"133\":\"64de2daa3ae6549d8f45\",\"161\":\"286d0207d962142ad548\",\"301\":\"751950a7a21e70acdb7c\",\"354\":\"47391222364a22307e69\",\"472\":\"21e5264f606f2b525030\",\"501\":\"72ce4b6e27f459e194cd\",\"524\":\"95e29e37c83dea5150d6\",\"532\":\"5ff953a5af12d8af60a9\",\"536\":\"55dc7dd4ab42a2c9f037\",\"739\":\"462b85f7a954e903b4cd\",\"745\":\"9316c5c2b711c39a20a5\",\"884\":\"bf91279ce235c0463204\",\"886\":\"2870895152d4462e05bf\",\"915\":\"0588cdc78683d0e9bbbc\",\"927\":\"151d396500bf8aa6cf1e\",\"941\":\"5b93118a31cc89905ee3\",\"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 + \".\" + {\"87\":\"74a4d72480e8214a0dde\",\"133\":\"64de2daa3ae6549d8f45\",\"301\":\"751950a7a21e70acdb7c\",\"472\":\"21e5264f606f2b525030\",\"532\":\"5ff953a5af12d8af60a9\",\"886\":\"2870895152d4462e05bf\"}[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, DEBUG_MORE } 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_MORE) {\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 statusesById: {},\n },\n\n chats: {\n listIds: {},\n isFullyLoaded: {},\n orderedPinnedIds: {},\n totalCount: {},\n byId: {},\n },\n\n messages: {\n byChatId: {},\n messageLists: [],\n sponsoredByChatId: {},\n },\n\n groupCalls: {\n byId: {},\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 { isHeavyAnimating } 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 unsubscribeFromBeforeUnload: NoneToVoidFunction | undefined;\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 if (!cached.groupCalls) {\n cached.groupCalls = initialState.groupCalls;\n }\n\n if (!cached.users.statusesById) {\n cached.users.statusesById = {};\n }\n\n if (!cached.messages.sponsoredByChatId) {\n cached.messages.sponsoredByChatId = {};\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 groupCalls: reduceGroupCalls(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, statusesById, selectedId } } = global;\n const chatIds = (global.chats.listIds.active || []).slice(0, GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT).filter(isUserId);\n const userIds = Object.keys(byId);\n const idsToSave = chatIds.concat(userIds).slice(0, GLOBAL_STATE_CACHE_USER_LIST_LIMIT);\n\n return {\n byId: pick(byId, idsToSave),\n statusesById: pick(statusesById, 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 newListIds = (global.chats.listIds.active || []).slice(0, GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT);\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n const idsToSave = newListIds.concat(currentChatId ? [currentChatId] : []);\n\n return {\n ...global.chats,\n byId: pick(global.chats.byId, idsToSave),\n listIds: {\n active: newListIds,\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 chatIds = (global.chats.listIds.active || []).slice(0, GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT);\n const chatIdsToSave = chatIds.concat(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 sponsoredByChatId: {},\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 reduceGroupCalls(global: GlobalState): GlobalState['groupCalls'] {\n return {\n ...global.groupCalls,\n byId: {},\n activeGroupCallId: undefined,\n isGroupCallPanelHidden: undefined,\n isFallbackConfirmOpen: undefined,\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 { getDispatch, getGlobal, withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiMediaFormat } from '../../api/types';\nimport { 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 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 =\n Pick\n & {\n hasCustomBackground?: boolean;\n hasCustomBackgroundColor: boolean;\n isRightColumnShown?: boolean;\n leftColumnWidth?: number;\n };\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}) => {\n const { setIsUiReady } = getDispatch();\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)(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 { prepareSearchWordsForNeedle } 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 if (!filter.length) {\n return countryList;\n }\n\n const searchWords = prepareSearchWordsForNeedle(filter);\n\n return countryList.filter((country) => (\n searchWords(country.defaultName) || (country.name && searchWords(country.name))\n ));\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 { getDispatch, withGlobal } from '../../lib/teact/teactn';\n\nimport { 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};\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}) => {\n const {\n setAuthPhoneNumber,\n setAuthRememberMe,\n loadNearestCountry,\n loadCountryList,\n clearAuthError,\n goToAuthQrCode,\n setSettingOption,\n } = getDispatch();\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)(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 & {\n language?: LangCode;\n };\n\nconst DATA_PREFIX = 'tg://login?token=';\n\nconst AuthCode: FC = ({\n connectionState,\n authState,\n authQrCode,\n language,\n}) => {\n const {\n returnToAuthPhoneNumber,\n setSettingOption,\n } = getDispatch();\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 useEffect(() => {\n if (connectionState === 'connectionStateReady') {\n void setLanguage(DEFAULT_LANG_CODE);\n }\n }, [connectionState]);\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)(AuthCode));\n","import React, { FC, useEffect, memo } from '../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../lib/teact/teactn';\n\nimport { 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;\n\nconst Auth: FC = ({\n authState,\n}) => {\n const {\n reset, initApi, returnToAuthPhoneNumber, goToAuthQrCode,\n } = getDispatch();\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)(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, { getDispatch, withGlobal } from './lib/teact/teactn';\n\nimport { 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;\n\nconst App: FC = ({ authState }) => {\n const { disconnect } = getDispatch();\n\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)(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","Error","message","subscribeToWorker","platform","window","async","Promise","race","makeRequest","pause","then","err","Date","now","startedAt","location","reload","args","callApi","fnName","name","warn","cancelApiProgress","progressCallback","isCanceled","postMessage","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","getDomain","url","href","ensureProtocol","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","sender","openUserInfo","id","Link","focusMessage","handleMessageClick","chatId","openChat","groupCall","joinGroupCall","accessHash","renderActionMessageText","lang","actionOrigin","targetUsers","targetMessage","targetChatId","options","action","translationValues","amount","currency","call","textOptions","maxTextLength","processed","unprocessed","undefined","includes","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","renderGroupCallContent","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","splittenParts","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","withGlobal","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_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","SEND_MESSAGE_ACTION_INTERVAL","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","CONTENT_NOT_SUPPORTED","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","SEEN_BY_MEMBERS_CHAT_MAX","SEEN_BY_MEMBERS_EXPIRE","GROUP_CALL_VOLUME_MULTIPLIER","GROUP_CALL_DEFAULT_VOLUME","ENABLE_THUMBNAIL_VIDEO","cb","dependencies","debugKey","prevDeps","usePrevious","initial","setValue","setTrigger","ANIMATION_START_EVENT","ANIMATION_END_EVENT","timeout","isAnimating","handleAnimationStart","handleAnimationEnd","removeEventListener","isHeavyAnimating","duration","onEnd","clearTimeout","dispatchEvent","Event","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","documentEventCounters","delegationRegistryByEventType","delegatedEventTypesByElement","propName","handler","asCapture","eventType","resolveEventType","canUseEventDelegation","resolveDelegationRegistry","existing","newSet","resolveDelegatedEventTypes","add","addDelegatedListener","removeDelegatedListener","tagName","realEventType","has","removeAllDelegatedListeners","eventTypes","realEvent","events","furtherCallsPrevented","Proxy","p","Reflect","body","parentNode","documentListenersCount","keys","delegatedHandlersCount1","values","acc","counter","delegationRegistriesCount","delegatedHandlersCount2","delegationRegistry","delegationElementsCount","delegatedEventTypesCount","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","newKeys","key","currentValue","newValue","cssText","removeAttribute","setAttribute","updateAttributes","currentEl","teactFastList","$newChild","currentRemainingIndex","remainingByKey","$currentChild","isKeyPresent","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","__html","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","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","React","currentGlobal","reducers","callbacks","containers","mapStateToProps","ownProps","mappedProps","newMappedProps","Number","isNaN","DEBUG_componentName","areMappedPropsChanged","DEBUG_updates","updateTime","actions","runCallbacksThrottled","throttleWithTickEnd","runCallbacks","forceOnHeavyAnimation","setGlobal","newGlobal","forceSyncOnIOs","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","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","handleSystemThemeChange","currentThemeMatch","documentElement","currentTheme","nextTheme","selectTheme","animationLevel","switchTheme","mql","matchMedia","addListener","subscribeToSystemThemeChange","messageTextSize","theme","setProperty","toString","IS_TOUCH_ENV","ensurePermanentWebVersion","startWebsync","IS_ANDROID","IS_MAC_OS","IS_SAFARI","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","allListIds","folder","excludedChatIds","includedChatIds","pinnedChatIds","active","archived","isListed","unreadMentionsCount","excludeArchived","excludeRead","unreadCount","hasUnreadMark","excludeMuted","userType","isContact","bots","contacts","nonContacts","channels","groups","filterChatFolder","prepareChatList","listIds","orderedPinnedIds","folderType","noOrder","listIdsSet","orderedPinnedIdsSet","pinnedChats","checkChat","otherChats","reduceChatList","chatArrays","filteredIds","filteredIdsSet","getFolderUnreadDialogs","hasActiveDialogs","unreadDialogsCount","isUnread","getFolderDescriptionText","emoticon","description","pinnedIds","getFolderChatsCount","getMessageSenderName","getUserFirstOrLastName","sortChatIds","chatIds","shouldPrioritizeVerified","priorityIds","priority","isVerified","filterChatsByName","query","searchWords","prepareSearchWordsForNeedle","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","mediaId","hasMessageLocalBlobUrl","getVideoOrAudioBaseHash","getAudioHasCover","IS_PROGRESSIVE_SUPPORTED","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","userStatus","wasOnline","getTime","wasOnlineDate","diff","today","setHours","yesterday","setDate","getDate","formatFullDate","isUserOnline","noStatus","isUserBot","getCanAddContact","sortUserIds","userIds","userStatusesById","getServerTime","expires","filterUsersByName","getUserIdDividend","abs","getUserColorKey","peer","replaceChatListIds","newIds","updateChatListIds","idsUpdate","replaceChats","newById","updateChat","chatUpdate","updatedChat","getUpdatedChat","updatedById","addChats","isUpdated","addedById","isMin","shouldOmitMinInfo","omit","photos","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","updateSponsoredMessage","sponsoredByChatId","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","updateContactList","updatedUsers","contactUserIds","contactList","newContactUserIds","userUpdate","updatedUser","getUpdatedUser","updateUsers","updateSelectedUserId","selectedId","deleteContact","MEMO_EMPTY_ARRAY","updateUserSearch","searchStatePartial","userSearch","updateUserSearchFetchingStatus","newState","fetchingStatus","updateUserBlockedState","isBlocked","replaceUserStatuses","statusesById","addUserStatuses","pick","getComplexKey","updateGlobalSearch","globalSearch","updateGlobalSearchContent","currentContent","updateGlobalSearchResults","newFoundMessages","nextRate","resultsByType","newFoundMessagesById","foundIdsForType","foundIds","updateGlobalSearchFetchingStatus","prevFoundIds","newFoundIds","foundOrPrevFoundIds","nextOffsetId","replaceLocalTextSearch","chatThreadKey","searchParams","localTextSearch","byChatThreadKey","updateLocalTextSearch","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","selectChat","selectChatUser","selectIsChatWithSelf","selectIsChatWithBot","selectSupportChat","isSupport","selectChatOnlineCount","members","onlineCount","selectChatBot","selectIsChatBotNotStarted","bot","messageInfo","selectAreActiveChatsLoaded","selectIsChatListed","targetList","list","selectChatFolder","chatFolders","selectIsChatPinned","chatFoldersById","selectChatByUsername","usernameLowered","selectCountNotMutedUnread","activeChatIds","selectNotifyExceptions","selectIsServiceChatReady","selectSendAs","sendAsId","selectCurrentStickerSearch","selectCurrentGifSearch","selectStickerSet","selectStickerSetByShortName","shortName","stickerSets","stickersForEmoji","favorite","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","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","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","selectIsMessageProtected","isProtected","selectHasProtectedMessage","selectSponsoredMessage","expiresAt","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","selectUserStatus","selectIsUserBlocked","LoadMoreDirection","FocusDirection","SettingsScreens","LeftColumnContent","GlobalSearchContent","MediaViewerOrigin","AudioOrigin","ChatCreationProgress","ManagementProgress","ProfileState","PaymentStep","ManagementScreens","currentInstance","animateSingle","tick","instance","isCancelled","animate","timingFunctions","linear","easeIn","easeOut","easeInOut","sin","PI","easeInQuad","easeOutQuad","easeInOutQuad","easeInCubic","easeOutCubic","easeInOutCubic","easeInQuart","easeOutQuart","easeInOutQuart","easeInQuint","easeOutQuint","easeInOutQuint","animateNumber","timing","t0","canceled","f","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","formatDateTimeToString","hour","minute","second","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","IS_REQUEST_FULLSCREEN_SUPPORTED","ARE_CALLS_SUPPORTED","LAYERS_ANIMATION_NAME","TEST_VIDEO","DPR","devicePixelRatio","MASK_IMAGE_DISABLED","IS_SCROLL_PATCH_NEEDED","MESSAGE_LIST_SENSITIVE_AREA","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","fetchFile","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","ADMINS_TOO_MUCH","ADMIN_RANK_EMOJI_NOT_ALLOWED","ADMIN_RANK_INVALID","FRESH_CHANGE_ADMINS_FORBIDDEN","INPUT_USER_DEACTIVATED","SHIPPING_ERRORS","getReadableErrorText","isSlowMode","textParams","extraPartIndex","errorMessage","handleErrorEvent","ErrorEvent","reason","throttle","alert","collection","member","mapValues","newByKey","object","stringKeys","orderRule","mode","compareValues","currentOrderRule","isAsc","aValue","bValue","mode1","mode2","orderRule1","orderRule2","isAsc1","isAsc2","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","Calls","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","privateChatUser","senderName","getNotificationContent","imageHash","mediaLoader","getAvatar","badge","vibrate","onclick","close","onshow","closeMessageNotifications","notifyClientReady","PERMANENT_VERSION_KEY","AVAILABLE_VERSIONS","setPermanentWebVersion","version","hasPermanentWebVersion","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","haystack","needle","needleWords","haystackLower","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","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__","m","getter","__esModule","getPrototypeOf","obj","ns","create","def","getOwnPropertyNames","definition","o","defineProperty","enumerable","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","hasErrorKey","INITIAL_STATE","isLeftColumnShown","phoneCodes","general","groupCalls","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","setupCaching","clearCaching","reducedGlobal","reduceShowChatInfo","reduceUsers","reduceChats","reduceMessages","recentlyFoundChatIds","reduceSettings","reduceChatFolders","reduceGroupCalls","idsToSave","newListIds","mainThread","activeGroupCallId","isGroupCallPanelHidden","isFallbackConfirmOpen","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.e8d33405b37130f28896.js b/dist/main.e8d33405b37130f28896.js deleted file mode 100644 index fcfa13db..00000000 --- a/dist/main.e8d33405b37130f28896.js +++ /dev/null @@ -1,2 +0,0 @@ -(()=>{"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(927),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){var o;throw new Error(null===(o=t.error)||void 0===o?void 0:o.message)}}))}(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),l=n(1396);function f(e){if(!e)return;const t=(0,l.X)(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:(0,l.X)(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}},8005:(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(6752),i=n(8033),c=n(5116);const l=({className:e,sender:t,children:n})=>{const{openUserInfo:o}=(0,c.uC)(),d=(0,r.I4)((()=>{t&&o({id:t.id})}),[t,o]);return t?r.ZP.createElement(i.Z,{className:(0,s.Z)("UserLink",e),onClick:d},n):n},f=({className:e,message:t,children:n})=>{const{focusMessage:o}=(0,c.uC)(),d=(0,r.I4)((()=>{t&&o({chatId:t.chatId,messageId:t.id})}),[o,t]);return t?r.ZP.createElement(i.Z,{className:(0,s.Z)("MessageLink",e),onClick:d},n):n},h=({className:e,chatId:t,children:n})=>{const{openChat:o}=(0,c.uC)(),d=(0,r.I4)((()=>{t&&o({id:t})}),[t,o]);return t?r.ZP.createElement(i.Z,{className:(0,s.Z)("ChatLink",e),onClick:d},n):n},m=({className:e,groupCall:t,children:n})=>{const{joinGroupCall:o}=(0,c.uC)(),d=(0,r.I4)((()=>{t&&o({id:t.id,accessHash:t.accessHash})}),[t,o]);return t?r.ZP.createElement(i.Z,{className:(0,s.Z)("GroupCallLink",e),onClick:d},n):n};function p(e,t,n,s,i,c,l={}){if(!t.content.action)return[];const{text:p,translationValues:v,amount:b,currency:w,call:I}=t.content.action,C=[],S={...l,maxTextLength:32};let E,P=e("Chat.Service.Group.UpdatedPinnedMessage1"!==p||i?p:"Message.PinnedGenericMessage",v&&v.length?v:void 0);return P.includes("%payment_amount%")&&(E=y(P,"%payment_amount%",(0,u.x)(b,w,e.code)),P=E.pop(),C.push(...E)),E=y(P,"%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(h,{className:"action-link",chatId:t.id},t&&(0,a.Z)(u))}(e,t,n)}(e,n,l.asPlain)||" ":"User"),P=E.pop(),C.push(...E),E=y(P,"%target_user%",s?s.map((e=>g(e,l.asPlain))).filter(Boolean):"User"),P=E.pop(),C.push(...E),E=y(P,"%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:h,isEmbedded:m,asPlain:p}=n,g=m&&u&&!s&&!i&&!c&&!l;let y=(0,d.Z)(u,h);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(f,{className:"action-link",message:t},(0,a.Z)(y)),"»"):r.ZP.createElement(f,{className:"action-link",message:t},(0,a.Z)(y))}(e,i,S):"a message"),P=E.pop(),C.push(...E),E=y(P,"%product%",i?function(e){return e.content&&e.content.invoice?e.content.invoice.title:"a product"}(i):"a product"),P=E.pop(),C.push(...E),E=y(P,"%target_chat%",c?function(e,t){const n="another chat";return t?n:r.ZP.createElement(h,{className:"action-link",chatId:e},n)}(c,l.asPlain):"another chat"),C.push(...E),l.asPlain?C.join("").trim():I?function(e,t){return r.ZP.createElement(m,{groupCall:e},t)}(I,C):C}function g(e,t){const n=(0,d.Z)((0,o.Js)(e));return t?n:r.ZP.createElement(l,{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.push(n),e):(t.innerText=n,e.push(t.innerHTML),e)),[])}(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.push(t),e;const n=t.toLowerCase(),o=n.indexOf(u.toLowerCase()),d=n[o+u.length];if(o<0||d&&d.match(l))return e.push(t),e;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.push(t),e;const n=t.match(g);if(!n||!n.length)return e.push(t),e;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.push(d),e;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)=>{if("string"!=typeof n)return e.push(n),e;const o=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}),[]);return[...e,...o]}),[])}const g=new RegExp(`${d.FM}|${d.uW}`,"ig");function y(e,t){return e.reduce(((e,n)=>{if("string"!=typeof n)return e.push(n),e;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:()=>u});var r=n(4050),o=n(5116),d=n(1638);const u=(0,o.c$)(((e,{userId:t})=>({userOrChat:t?(0,d.dy)(e,t):void 0})))((({username:e,userOrChat:t,children:n})=>{const{openChat:d,openChatByUsername:u}=(0,o.uC)();return r.ZP.createElement("a",{onClick:()=>{t?d({id:t.id}):e&&u({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"),Z=(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:Z,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,hT:()=>M,YQ:()=>A,rS:()=>k,t_:()=>T,Ov:()=>N,EN:()=>L,pn:()=>R,Hk:()=>D,Vk:()=>O,mo:()=>Z,qU:()=>_,ul:()=>x,NM:()=>F,Qx:()=>B,mw:()=>$,oB:()=>U,zy:()=>j,CX:()=>W,xS:()=>G,b6:()=>H,AR:()=>V,r_:()=>z,o_:()=>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,VC:()=>Re,FM:()=>De,uW:()=>Oe,g$:()=>Ze,FS:()=>_e,FD:()=>xe,aw:()=>Fe,FV:()=>Be,Nf:()=>$e,WS:()=>Ue,DU:()=>je,EG:()=>We,t4:()=>Ge,sR:()=>He,$O:()=>Ve,Bg:()=>ze,vi:()=>Qe,Db:()=>Ke,mU:()=>Je,p3:()=>qe,It:()=>Ye,Vv:()=>Xe,g:()=>et,Hc:()=>tt,EH:()=>nt,Ro:()=>rt,aC:()=>ot,LH:()=>dt});const r="Telegram",o=" [Inactive]",d="Telegram WebZ",u="1.28.4",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-v7",S=[1,5,10,50,100,500],E="undefined"!=typeof window&&window.innerHeight>=900,P=1,M=E?60:40,A=2*M,k=72,T=E?30:25,N=100,L=42,R=42,D=20,O=30,Z=200,_=500,x=20,F=!1,B=1,$=1,U=0,j=2,W=j,G=16,H=17,V=15,z=1e4,Q=3e3,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="The message is not supported on this version of Telegram.",De="((ftp|https?):\\/\\/)?((www\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\.[a-zA-Z0-9()]{1,63})\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)",Oe="(@[\\w\\d_-]+)",Ze=/^tg:(\/\/)?([?=&\d\w_-]+)?/gm,_e=/^(?:https?:\/\/)?(?:t\.me\/)/gm,xe=new Set(["AU","BD","CA","CO","EG","HN","IE","IN","JO","MX","MY","NI","NZ","PH","PK","SA","SV","US"]),Fe="777000",Be="1271266957",$e=0,Ue=1,je=10,We=5,Ge=2147483646,He="en",Ve="android",ze=["android","ios","tdesktop","macos"],Qe="TelegramTips",Ke=["ar","pt-br","id","it","ko","ms","pl","es","tr"],Je="https://bugs.telegram.org/?tag_ids=41&sort=time",qe="#A2AF8E",Ye="#0F0F0F",Xe="#0a0a0a8c",et="rgba(90, 110, 70, 0.6)",tt=50,nt=604680,rt=100,ot=100*rt,dt=!1},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,{ZP:()=>s,zG:()=>i,YW:()=>c});var r=n(4050);const o="tt-event-heavy-animation-start",d="tt-event-heavy-animation-end";let u,a=!1;const s=(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])};function i(){return a}function c(e=1e3){function t(){u&&(clearTimeout(u),u=void 0),a=!1,document.dispatchEvent(new Event(d))}return a||(a=!0,document.dispatchEvent(new Event(o))),u&&(clearTimeout(u),u=void 0),u=window.setTimeout(t,e),t}},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={},a=new Map;function s(e,t,n,r=!1){const o=c(t,e);l(o,e,r)?function(e,t,n){d[e]||(d[e]=0,document.addEventListener(e,m)),function(e){return u[e]||(u[e]=new Map),u[e]}(e).set(t,n),function(e){const t=a.get(e);if(t)return t;const n=new Set;return a.set(e,n),n}(t).add(e),d[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){d[e]--,d[e]||document.removeEventListener(e,m),u[e].delete(t),a.get(t).delete(e)}function h(e){const t=a.get(e);t&&(t.forEach((t=>f(t,e))),a.delete(e))}function m(e){const t=u[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",(()=>{const e=Object.keys(d).length,t=Object.values(d).reduce(((e,t)=>e+t),0),n=Object.keys(u).length,r=Object.values(u).reduce(((e,t)=>e+t.size),0),o=a.size,s=Array.from(a.values()).reduce(((e,t)=>e+t.size),0);console.warn("DELEGATED EVENTS STATS",{delegatedHandlersCount1:t,delegatedHandlersCount2:r,delegatedEventTypesCount:s,delegationRegistriesCount:n,delegationElementsCount:o,documentListenersCount:e})}))},2916:(e,t,n)=>{n.d(t,{Z:()=>y});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","role"]),i={autoPlay:"autoplay",autoComplete:"autocomplete"},c={};function l(e,t,n,o,c,{skipComponentUpdate:y=!1,forceIndex:v=!1,fragment:b,moveDirection:w}={}){if(!y&&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)),!y&&n&&(0,r.op)(n)&&n.componentInstance.isMounted&&h(n,o,c,e),t===n)return n;if(!t&&n){(0,r.op)(n)&&(n=f(n,o,c,e));const t=m(n);(0,r.CD)(n,t),v&&e.childNodes[c]?e.insertBefore(t,e.childNodes[c]):(b||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,c,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(w){const n=(0,r.U9)(t),o=e.childNodes["up"===w?c:c+1];o?e.insertBefore(n,o):(b||e).appendChild(n)}o||function(e,t,n){const r=Object.keys(e.props),o=Object.keys(t.props);r.forEach((r=>{const o=e.props[r],d=t.props[r];void 0!==o&&(void 0===d||o!==d&&r.startsWith("on"))&&function(e,t,n){"className"===t?e.className="":"value"===t?e.value="":"style"===t?e.style.cssText="":"dangerouslySetInnerHTML"===t?e.innerHTML="":t.startsWith("on")?(0,u.xg)(e,t,n,t.endsWith("Capture")):t.startsWith("data-")||t.startsWith("aria-")||s.has(t)?e.removeAttribute(t):a.has(t)||delete e[i[t]||t]}(n,r,o)})),o.forEach((r=>{const o=e.props[r],d=t.props[r];void 0!==d&&d!==o&&g(n,r,d)}))}(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)&&null==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;const s=null!=a;if(s&&!o.has(a))return l(n,r,void 0,t,-1),e;if(!s){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=>{void 0!==n[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){"className"===t?e.className=n:"value"===t?e.value=n:"style"===t?e.style.cssText=n:"dangerouslySetInnerHTML"===t?e.innerHTML=n.__html:t.startsWith("on")?(0,u.Oo)(e,t,n,t.endsWith("Capture")):t.startsWith("data-")||t.startsWith("aria-")||s.has(t)?e.setAttribute(t,n):a.has(t)||(e[i[t]||t]=n)}const y={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:()=>Z,I4:()=>_,sO:()=>x,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,o,d){const{cursor:u,byCursor:s}=l.hooks.effects,i=l;function c(){if(!i.isMounted)return;const{cleanup:e}=s[u];if("function"==typeof e)try{let t;if(r.eM&&(t=performance.now()),e(),r.eM){const e=performance.now()-t,n=i.name;e>7&&console.warn(`[Teact] Slow cleanup at effect cursor #${u}: ${n}, ${Math.round(e)} ms`)}}catch(e){(0,a.S)(e)}}function f(){if(!i.isMounted)return;let e;if(r.eM&&(e=performance.now()),s[u].cleanup=n(),r.eM){const t=performance.now()-e,n=i.name;t>7&&console.warn(`[Teact] Slow effect at cursor #${u}: ${n}, ${Math.round(t)} ms`)}}if(void 0!==s[u]&&o&&s[u].dependencies){if(o.some(((e,t)=>e!==s[u].dependencies[t]))){if(d){const e=o.reduce(((e,t,n)=>{const r=s[u].dependencies[n];return t!==r&&e.push(`${n}: ${r} => ${t}`),e}),[]);console.log(`[Teact] Effect "${d}" caused by dependencies.`,e.join(", "))}t(c),e(f)}}else d&&console.log(`[Teact] Effect "${d}" caused by missing dependencies.`),t(c),e(f);s[u]={effect:n,dependencies:o,cleanup:s[u]?s[u].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 Z(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,n){return Z((()=>e),t,n)}function x(e){return Z((()=>({current:e})),[])}function F(e,t=u.Z,n){return function(o){const d=x(o),a=x();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.warn("COMPONENTS",(0,d.Xo)(Object.values(C),"renderCount","desc"))}));const B={createElement:y,Fragment:c}},5116:(e,t,n)=>{n.d(t,{ZP:()=>h,R3:()=>I,Rd:()=>C,uC:()=>S,Q6:()=>E,ll:()=>P,Iq:()=>M,c$:()=>A});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),l=n(8674);function f(){return(f=Object.assign||function(e){for(var t=1;t7&&console.warn(`[TeactN] Slow containers update: ${Math.round(t)} ms`)}}],y={},v=new Map,b=(0,a.$6)(w);function w(e=!1){e||!(0,l.zG)()?g.forEach((e=>e(m))):(0,a.T2)(b)}function I(e,t){"object"==typeof e&&e!==m&&(m=e,null!=t&&t.forceSyncOnIOs?w(!0):b(null==t?void 0:t.forceOnHeavyAnimation))}function C(){return m}function S(){return y}function E(e,t){p[e]||(p[e]=[],y[e]=(t,n)=>{!function(e,t,n){p[e]&&p[e].forEach((e=>{const r=e(m,y,t);r&&I(r,n)}))}(e,t,n)}),p[e].push(t)}function P(e){g.push(e)}function M(e){const t=g.indexOf(e);-1!==t&&g.splice(t,1)}function A(e=(()=>({}))){return t=>function n(o){n.DEBUG_contentComponentName=t.name;const[a]=(0,r.eJ)((0,u.Z)(v)),i=(0,d.Z)();(0,r.d4)((()=>()=>{v.delete(a)}),[a]);let l=v.get(a);if(l||(l={mapStateToProps:e,ownProps:o,areMappedPropsChanged:!1,forceUpdate:i,DEBUG_updates:0,DEBUG_componentName:t.name},v.set(a,l)),l.areMappedPropsChanged&&(l.areMappedPropsChanged=!1),!l.mappedProps||!(0,s.Z)(l.ownProps,o)){l.ownProps=o;try{l.mappedProps=e(m,o)}catch(e){(0,c.S)(e)}}return r.ZP.createElement(t,f({},l.mappedProps,o))}}o.eM&&(window.getGlobal=C,document.addEventListener("dblclick",(()=>{console.warn("GLOBAL CONTAINERS",(0,i.Xo)(Array.from(v.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(1638),l=n(307),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(307),a=n(663),s=n(1638),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});break}}}))},7895:(e,t,n)=>{var r=n(5116),o=n(3716),d=n(7361),u=n(663),a=n(6917),s=n(1638),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"),d.s$&&document.body.classList.add("is-safari")})),(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},{forceSyncOnIOs:!0})}))},3781:(e,t,n)=>{var r=n(5116),o=n(307);(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:()=>c,Bf:()=>l,G9:()=>f,ZV:()=>h,eA:()=>m,Ru:()=>p,pK:()=>g,l6:()=>y,zX:()=>v,U:()=>b,GM:()=>w,hu:()=>I,RT:()=>C,Hp:()=>S,Nl:()=>E,VE:()=>P,Mg:()=>M,Qm:()=>A,H5:()=>k,q8:()=>T,Hd:()=>N,OE:()=>L,pE:()=>R,i4:()=>D,Sm:()=>O,cc:()=>Z,P4:()=>_,O:()=>x,wG:()=>B,Fu:()=>$,SB:()=>U,zF:()=>j,ih:()=>W,$l:()=>G});var r=n(6137),o=n(3716),d=n(782),u=n(5527),a=n(790),s=n(5765);const i=Date.now()/1e3+31622400;function c(e){return"number"==typeof e?e>0:!e.startsWith("-")}function l(e){return f(e)||h(e)}function f(e){return"chatTypeBasicGroup"===e.type}function h(e){return"chatTypeSuperGroup"===e.type}function m(e){return"chatTypeChannel"===e.type}function p(e){return"chatTypePrivate"===e.type||"chatTypeBasicGroup"===e.type}function g(e){return e===o.FV}function y(e){switch(e.type){case"chatTypePrivate":return"PrivateChat";case"chatTypeBasicGroup":case"chatTypeSuperGroup":return"AccDescrGroup";case"chatTypeChannel":return"AccDescrChannel";default:return"Chat"}}function v(e){if("chatTypePrivate"===e.type||"chatTypeSecret"===e.type)return e.id}function b(e,t,n,r=!1){return r||n&&t.id===n.id&&n.isSelf?e("SavedMessages"):t.title||e("HiddenName")}function w(e){if(e.fullInfo)return e.fullInfo.about}function I(e){const{username:t}=e;if(t)return`https://t.me/${t}`;const{inviteLink:n}=e.fullInfo||{};return n}function C(e,t="normal"){if(e.avatarHash)switch(t){case"big":return`profile${e.id}?${e.avatarHash}`;default:return`avatar${e.id}?${e.avatarHash}`}}function S(e){return!e.lastMessage}function E(e){return Boolean(e.adminRights)}function P(e,t){return!!e.adminRights&&e.adminRights[t]}function M(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 A(e,t){return t!==r._f||!(e.isRestricted||e.migratedTo||e.isNotJoined||g(e.id))&&(!!e.isCreator||!!c(e.id)||(m(e)?P(e,"postMessages"):E(e)||!M(e,"sendMessages")))}function k(e,t=!1){if(!e)return{canAttachMedia:!1,canAttachPolls:!1,canSendStickers:!1,canSendGifs:!1,canAttachEmbedLinks:!1};const n=E(e);return{canAttachMedia:n||!M(e,"sendMedia"),canAttachPolls:(n||!M(e,"sendPolls"))&&(!c(e.id)||t),canSendStickers:n||!M(e,"sendStickers"),canSendGifs:n||!M(e,"sendGifs"),canAttachEmbedLinks:n||!M(e,"embedLinks")}}function T(e,t,n){if(null!=t&&t.sendMessages){const{untilDate:n}=t;return n&&n{const c=t[e];return c&&function(e,t,n,r,d,u,a,s){if(!e.isListed)return!1;const{id:i,type:c,unreadMentionsCount:l}=e;if(null!=u&&u.has(i))return!1;if(null!=a&&a.has(i))return!0;if(null!=s&&s.has(i))return!0;if(t.excludeArchived&&e.folderId===o.WS)return!1;if(t.excludeRead&&!e.unreadCount&&!l&&!e.hasUnreadMark)return!1;if(t.excludeMuted&&!l&&D(e,r,d))return!1;if("chatTypePrivate"===c){const e=n[i];if(e){const{type:n,isContact:r}=e;if("userTypeBot"===n){if(t.bots)return!0}else{if(t.contacts&&r)return!0;if(t.nonContacts&&!r)return!0}}}else{if("chatTypeChannel"===c)return!!t.channels;if("chatTypeBasicGroup"===c||"chatTypeSuperGroup"===c)return!!t.groups}return!1}(c,r,n,d,u,a,s,i)})),r.pinnedChatIds]}function x(e,t,n,r="all",o=!1){const u=new Set(t),a=n?new Set(n):void 0,s=(null==n?void 0:n.reduce(((t,n)=>{const o=e[n];return o&&u.has(o.id)&&F(o,r)&&t.push(o),t}),[]))||[],i=t.reduce(((t,n)=>{const o=e[n];return!o||a&&a.has(o.id)||!F(o,r)||t.push(o),t}),[]);return{pinnedChats:s,otherChats:o?i:(0,d.Xo)(i,L,"desc")}}function F(e,t){return e.lastMessage&&!e.migratedTo&&!e.isRestricted&&!e.isNotJoined&&!("all"===t&&e.folderId===o.WS)&&!("archived"===t&&e.folderId!==o.WS)}function B(e,t){const n=new Set(t);return{pinnedChats:e.pinnedChats.filter((({id:e})=>n.has(e))),otherChats:e.otherChats.filter((({id:e})=>n.has(e)))}}function $(e,t,n,r,o,d){const[u]=_(e,t,n,r,o,d);let a=!1;return{unreadDialogsCount:u.reduce(((e,n)=>{const r=t[n];if(null==r||!r.lastMessage||null!=r&&r.isRestricted||null!=r&&r.isNotJoined)return e;const u=r.unreadCount||r.hasUnreadMark;return u&&e++,!a&&(r.unreadMentionsCount||u&&!D(r,o,d))&&(a=!0),e}),0),hasActiveDialogs:a}}function U(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}=o;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]=_(e,t,n,r,o,d),{pinnedChats:s,otherChats:i}=x(t,u,a,"folder",!0);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 j(e,t,n){if(n&&!c(t))return n.isSelf?e("FromYou"):(0,u.Vl)(n)}function W(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")}function G(e,t,n,r,o){if(!r)return t;const d=(0,s.W)(r);return t.filter((t=>{const r=n[t];return!!r&&d(b(e,r,void 0,t===o))}))}},2858:(e,t,n)=>{n.d(t,{uw:()=>se,$l:()=>o.$l,kK:()=>r.kK,H5:()=>o.H5,MR:()=>J,kw:()=>r.kw,cc:()=>o.cc,Qm:()=>o.Qm,RT:()=>o.RT,GM:()=>o.GM,hu:()=>o.hu,N0:()=>te,OE:()=>o.OE,Hd:()=>o.Hd,U:()=>o.U,l6:()=>o.l6,T7:()=>y,SB:()=>o.SB,Fu:()=>o.Fu,VE:()=>o.VE,XV:()=>ae,Sc:()=>de,N5:()=>Z,oP:()=>_,qp:()=>N,w6:()=>k,R5:()=>ue,$D:()=>p,aE:()=>B,ep:()=>Y,c0:()=>X,eO:()=>W,Tp:()=>c,kG:()=>q,Ti:()=>Q,DH:()=>z,KK:()=>f,O$:()=>R,t9:()=>j,Y5:()=>O,zF:()=>o.zF,q8:()=>o.q8,_O:()=>g,bf:()=>F,MK:()=>h,UD:()=>m,b7:()=>D,kd:()=>x,s1:()=>G,F$:()=>H,Cg:()=>V,bV:()=>ne,HV:()=>re,zX:()=>o.zX,OU:()=>E,RI:()=>P,Ow:()=>ce,Rs:()=>r.Rs,Vl:()=>r.Vl,Js:()=>r.Js,db:()=>r.db,Tq:()=>r.Tq,jC:()=>oe,BM:()=>ee,u8:()=>L,Lo:()=>I,Ul:()=>S,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:()=>w,CD:()=>A,rl:()=>$,hC:()=>U,CI:()=>M,B4:()=>v,ss:()=>b,jM:()=>C,cS:()=>r.cS,YC:()=>o.YC,kM:()=>r.kM,Mg:()=>o.Mg,Ak:()=>l,O:()=>o.O,P4:()=>o.P4,wG:()=>o.wG,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=new RegExp(u.FM,"i");function c(e){const{chatId:t,id:n}=e;return function(e,t){return`msg${e}-${t}`}(t,n)}function l(e){const t=e.match(/^msg(-?\d+)-(\d+)/);return{chatId:t[1],messageId:Number(t[2])}}function f(e){return e.previousLocalId||e.id}function h(e,t,n=!1){const{text:r,photo:o,video:d,audio:a,voice:s,document:i,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():a?`${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")}`:s?`${n?"":"🎤 "}${m||e("AttachAudio")}`:i?`${n?"":"📎 "}${m||i.fileName}`:l?e("AttachContact"):f?`${n?"":"📊 "}${f.summary.question}`:h?"Invoice":r?m:u.VC}function m(e){const{text:t,sticker:n,photo:r,video:o,audio:d,voice:a,document:s,poll:i,webPage:c,contact:l,invoice:f}=e.content;return t?t.text:n||r||o||d||a||s||l||i||c||f?void 0:u.VC}function p(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 g(e){const{text:t}=e.content;if(t&&t.text.length<=6&&1===p(e))return t.text}function y(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(i)),!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(i)}}if(!n&&t&&(n=t.text.match(i)),n)return{url:n[0],domain:n[3]}}function v(e){return e.isOutgoing}function b(e){return Boolean(e.replyToMessageId)}function w(e){return Boolean(e.forwardInfo)}function I(e){return!!e.content.action}function C(e){return e.chatId===u.aw&&Math.round(e.id)!==e.id}function S(e){return Boolean(e.senderId)&&!(0,o.YC)(e.senderId)&&v(e)}function E(e,t){return(0,o.YC)(t.id)?(0,r.Js)(t):(0,o.U)(e,t)}function P(e){return e.sendingState?"messageSendingStateFailed"===e.sendingState?"failed":"pending":"succeeded"}function M(e){return e.id>=u.AE}function A(e){return e.content.action&&"historyClear"===e.content.action.type}function k(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=c(e);return r?`${d}.jpg`:t.voice?a.m5?`${d}.ogg`:`${d}.wav`:d}var T=n(5376);function N(e){return e.content}function L(e){return Boolean(R(e)||D(e)||B(e)||F(e)||function(e){return e.content.contact}(e)||j(e)||Z(e)||_(e)||x(e))}function R(e){return e.content.photo}function D(e){return e.content.video}function O(e){const{video:t}=e.content;return null!=t&&t.isRound?t:void 0}function Z(e){return e.content.action}function _(e){return e.content.audio}function x(e){return e.content.voice}function F(e){return e.content.sticker}function B(e){return e.content.document}function $(e){const t=B(e);return t?"photo"===t.mediaType:void 0}function U(e){const t=B(e);return t?"video"===t.mediaType:void 0}function j(e){return e.content.poll}function W(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 V(e){var t;return null===(t=G(e))||void 0===t?void 0:t.video}function z(e){var t;return null===(t=function(e){const t=R(e)||D(e)||B(e)||F(e)||H(e)||V(e);if(t)return t.thumbnail}(e))||void 0===t?void 0:t.dataUri}function Q(e,t){const{photo:n,video:r,sticker:o,audio:d,voice:u,document:a}=e.content,s=H(e),i=V(e),l=r||i,f=n||s;if(!(f||l||o||d||u||a))return;const h=(f||l||o||d||u||a).id,m=`${c(e)}${h?`:${h}`:""}`;if(l)switch(t){case"micro":case"pictogram":return`${m}?size=m`;case"inline":return ee(e)?void 0:K(l,m);case"viewerPreview":return`${m}?size=m`;case"viewerFull":return K(l,m);case"download":return`${m}?download`}if(f)switch(t){case"micro":case"pictogram":return`${m}?size=m`;case"inline":return ee(e)?void 0:`${m}?size=x`;case"viewerPreview":return`${m}?size=x`;case"viewerFull":case"download":return`${m}?size=z`}if(a)switch(t){case"micro":case"pictogram":case"inline":case"viewerPreview":if(!(0,T.v6)(a)||ee(e))return;return`${m}?size=m`;case"viewerFull":case"download":return m}if(o)switch(t){case"micro":return;case"pictogram":return`${m}?size=m`;case"inline":return m;case"download":return`${m}?download`}if(d)switch(t){case"micro":case"pictogram":return J(d)?`${m}?size=m`:void 0;case"inline":return K(d,m);case"download":return`${m}?download`}if(u)switch(t){case"micro":case"pictogram":return;case"inline":return m;case"download":return`${m}?download`}}function K(e,t){return a.I_&&a.s$?`${t}?fileSize=${e.size}&mimeType=${e.mimeType}`:t}function J(e){return e.thumbnailSizes&&e.thumbnailSizes.length>0}function q(e,t){const{sticker:n,video:r,audio:o,voice:u}=e.content,s=r||V(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 Y(e){const{photo:t,video:n,document:r}=e.content,o=H(e),d=V(e);if(t||o)return`photo${e.date}.jpeg`;const{fileName:u}=n||d||r||{};return u}function X(e){const{video:t,document:n}=e.content,r=V(e),{size:o}=t||r||n||{};return o}function ee(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 te(e,t,n=!1){const r=ue(e,t,n?"media":"inlineMedia");return n?r.reverse():r}function ne(e){return e.sizes.find((e=>"z"===e.type))||e.sizes.find((e=>"y"===e.type))||re(e)}function re(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 oe(e){if(e.width&&e.height)return e}function de(e,t,n=!1){const r=M(e);return{isUploading:r,isTransferring:r||n,transferProgress:Number(t)}}function ue(e,t,n){let r;switch(n){case"media":r=e=>{const t=D(e);return R(e)||t&&!t.isRound&&!t.isGif};break;case"documents":r=B;break;case"links":r=e=>G(e)||function(e){const{text:t}=e.content,n=t&&t.text.match(i);if(n)return{url:n[0],domain:n[3]}}(e);break;case"audio":r=_;break;case"voice":r=e=>{const t=D(e);return x(e)||t&&t.isRound};break;case"inlineMedia":r=e=>{const t=D(e);return R(e)||t&&!t.isRound&&!t.isGif||$(e)||U(e)};break;default:return[]}return t.reduce(((t,n)=>(e[n]&&r(e[n])&&t.push(n),t)),[])}function ae(e){const{audio:t,voice:n,video:r}=N(e),o=t||n||r||V(e);if(o)return o.duration}function se(e,t){return`${e}_${t}`}const ie={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 ce(e){const{message:t,code:n,param:r}=e,{field:o,message:d}=r?ie[r]:ie[n];return{field:o,message:d,description:t}}},5527:(e,t,n)=>{n.d(t,{Vl:()=>i,Js:()=>c,Tq:()=>l,kM:()=>f,NB:()=>h,cS:()=>m,kw:()=>p,Z0:()=>g,kK:()=>y,db:()=>v,Rs:()=>b});var r=n(3716),o=n(790),d=n(782),u=n(2267),a=n(5765);const s=[1,8,5,2,7,4,6];function i(e){if(e)switch(e.type){case"userTypeBot":case"userTypeRegular":return e.firstName||e.lastName;case"userTypeDeleted":case"userTypeUnknown":return"Deleted";default:return}}function c(e){if(e){if(h(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 l(e,t,n,d){if(t.id===r.aw)return e("ServiceNotifications").toLowerCase();if(t.type&&"userTypeBot"===t.type)return e("Bot");if(!n)return"";switch(n.type){case"userStatusEmpty":return e("ALongTimeAgo");case"userStatusLastMonth":return e("WithinAMonth");case"userStatusLastWeek":return e("WithinAWeek");case"userStatusOffline":{const{wasOnline:t}=n;if(!t)return e("LastSeen.Offline");const r=new Date((new Date).getTime()+1e3*d),u=new Date(1e3*t);if(u>=r)return e("LastSeen.JustNow");const a=new Date(r.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*d))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(r.getDate()-1),i.setHours(0,0,0,0),u>new Date(i.getTime()+1e3*d)?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 f(e,t){const{id:n,type:o}=e;return!!t&&n!==r.aw&&"userStatusOnline"===t.type&&"userTypeBot"!==o}function h(e){return!e.noStatus&&"userTypeBot"!==e.type&&e.id!==r.aw&&("userTypeDeleted"===e.type||"userTypeUnknown"===e.type)}function m(e){return"userTypeBot"===e.type}function p(e){return!e.isContact&&!m(e)}function g(e,t,n,r,o=0){return(0,d.Xo)(e,(e=>{const d=(0,u.b)(o);if(r&&r.includes(e))return d+172800-(r.length-r.indexOf(e));const a=t[e],s=n[e];if(!a||!s)return 0;if("userStatusOnline"===s.type)return s.expires;if("userStatusOffline"===s.type&&s.wasOnline)return s.wasOnline;switch(s.type){case"userStatusRecently":return d-86400;case"userStatusLastWeek":return d-604800;case"userStatusLastMonth":return d-18144e3;default:return 0}}),"desc")}function y(e,t,n){if(!n)return e;const r=(0,a.W)(n);return e.filter((e=>{const n=t[e];if(!n)return!1;const o=c(n);return o&&r(o)||r(n.username)}))}function v(e){return"number"==typeof e?Math.abs(e):Math.abs(Number(e))}function b(e){const t=e?v(e.id)%7:0;return s[t]}},6788:(e,t,n)=>{n.d(t,{Mg:()=>u,B1:()=>a,SL:()=>s,a4:()=>i,GL:()=>c,fZ:()=>l,Pi:()=>h,vv:()=>m,Dd:()=>p});var r=n(3716),o=n(782),d=n(1638);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:o}=e.chats,d=f(e,t,n,r);return d?s(e,{...o,[t]:d}):e}function c(e,t){const n=Object.keys(t).reduce(((n,r)=>{const o=f(e,r,t[r]);return o&&(n[r]=o),n}),{});return e=s(e,{...e.chats.byId,...n})}function l(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=f(e,d,t[d]);n&&(o[d]=n,r||(r=!0))}return o}),{});return r?e=s(e,{...n,...o}):e}function f(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||[]]}};if(s.id&&s.type)return s}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]}})),i(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)))),i(e,t,{isNotJoined:!0})}},307:(e,t,n)=>{n.d(t,{O4:()=>we,c_:()=>h,fZ:()=>r.fZ,m6:()=>f,aK:()=>ve,aJ:()=>ye,zn:()=>Y,Sh:()=>G,$S:()=>I,bp:()=>Ne,WY:()=>Le,K4:()=>g,bV:()=>y,GK:()=>z,M6:()=>T,i9:()=>L,Dd:()=>r.Dd,vy:()=>F,rB:()=>Ie,g_:()=>_,Mg:()=>r.Mg,SL:()=>r.SL,Pb:()=>ae,w3:()=>P,BI:()=>pe,lr:()=>ge,pf:()=>l,ps:()=>q,s5:()=>$,y9:()=>C,nA:()=>Me,_7:()=>ke,Q$:()=>Pe,Dq:()=>Te,vT:()=>Ee,QH:()=>Ae,Ob:()=>N,a4:()=>r.a4,B1:()=>r.B1,vv:()=>r.vv,Pi:()=>r.Pi,cY:()=>m,GL:()=>r.GL,Wy:()=>s,wV:()=>k,cq:()=>M,rq:()=>Z,No:()=>ee,Og:()=>te,xv:()=>re,px:()=>ne,xj:()=>v,c1:()=>le,z5:()=>ce,qr:()=>ue,dx:()=>se,fw:()=>me,H9:()=>he,HN:()=>be,ff:()=>b,P4:()=>p,x1:()=>V,TM:()=>Se,Fn:()=>A,Rg:()=>O,z3:()=>D,IM:()=>x,Xg:()=>S,j6:()=>E,lG:()=>R,IE:()=>Ce,Nq:()=>j,Lm:()=>Q,Q3:()=>K,eD:()=>W});var r=n(6788),o=n(6137),d=n(3716),u=n(1638),a=n(782);function s(e,t,n=o._f,r="thread",u){const{messageLists:a}=e.messages;let s=a;if(u||d.Cg)s=t?[{chatId:t,threadId:n,type:r}]:[];else if(t){const e=a[a.length-1];e&&e.chatId===t&&e.threadId===n&&e.type===r||(s=e&&e.chatId===d.AJ?[...a.slice(0,-1),{chatId:t,threadId:n,type:r}]:[...a,{chatId:t,threadId:n,type:r}])}else s=a.slice(0,-1);return{...e,messages:{...e.messages,messageLists:s}}}function i(e,t,n){return c(e,t,{byId:n})}function c(e,t,n){const r=e.messages.byChatId[t]||{byId:{},threadsById:{}};return{...e,messages:{...e.messages,byChatId:{...e.messages.byChatId,[t]:{...r,...n}}}}}function l(e,t,n,r,o){return function(e,t,n,r){const o=e.messages.byChatId[t];return c(e,t,{threadsById:{...null==o?void 0:o.threadsById,[n]:{...null==o?void 0:o.threadsById[n],...r}}})}(e,t,n,{[r]:o})}function f(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=h(e,t,n[t])})),e}function h(e,t,n){const r=(0,u.Zw)(e,t);return r&&Object.keys(n).every((e=>Boolean(r[Number(e)])))?e:i(e,t,{...n,...r})}function m(e,t,n,r){const o=(0,u.Zw)(e,t)||{},d={...o[n],...r};return d.id?i(e,t,{...o,[n]:d}):e}function p(e,t,n,r){const o=(0,u.Fn)(e,t)||{},d={...o[n],...r};return d.id?P(e,t,{...o,[n]:d}):e}function g(e,t,n){const r=(0,u.Zw)(e,t);if(!r)return e;const o=(0,a.CE)(r,n),d=Object.values((0,a.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,u.tZ)(e,t,r);let d=(0,u.gb)(e,t,r),a=(0,u.qC)(e,t,r),s=(0,u.Cb)(e,t,r),i=(0,u.KB)(e,t),c=null==o?void 0:o.messagesCount;n.forEach((e=>{d&&d.includes(e)&&(d=d.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=l(e,t,r,"listedIds",d),e=l(e,t,r,"outlyingIds",a),e=l(e,t,r,"viewportIds",s),e=l(e,t,r,"pinnedIds",i),o&&void 0!==c&&(e=l(e,t,r,"threadInfo",{...o,messagesCount:c}))})),d.length){const n=(0,u.Bt)(e),r=n&&n.chatId===t&&"thread"===n.type,o=null==n?void 0:n.threadId;d.forEach((n=>{const{fromChatId:d,fromMessageId:a}=n.forwardInfo,i=(0,u.hj)(e,d,a);r&&o===a&&(e=s(e,t)),i&&(e=m(e,d,a,{threadInfo:void 0}))}))}return e=i(e,t,o)}function y(e,t,n){const r=(0,u.Fn)(e,t);if(!r)return e;const d=(0,a.CE)(r,n);let s=(0,u.qy)(e,t);return s&&(n.forEach((e=>{s.includes(e)&&(s=s.filter((t=>t!==e)))})),e=l(e,t,o._f,"scheduledIds",s)),P(e,t,d)}function v(e,t,n,r){const o=(0,u.gb)(e,t,n),d=null!=o&&o.length?r.filter((e=>!o.includes(e))):r;return o&&!d.length?e:l(e,t,n,"listedIds",w([...o||[],...d]))}function b(e,t,n,r){const o=(0,u.qC)(e,t,n),d=null!=o&&o.length?r.filter((e=>!o.includes(e))):r;return o&&!d.length?e:l(e,t,n,"outlyingIds",w([...o||[],...d]))}function w(e){return e.sort(((e,t)=>e-t))}function I(e,t,n,r){const o=(0,u.Cb)(e,t,n)||[];return o.includes(r)?e:l(e,t,n,"viewportIds",w([...o.length{e=S(e,t.chatId,t.threadId,t)})),e}function P(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 M(e,t,n,r=!1,o=!1){return{...e,focusedMessage:{...e.focusedMessage,chatId:t,messageId:n,noHighlight:r,isResizingContainer:o}}}function A(e,t,n){return{...e,messages:{...e.messages,sponsoredByChatId:{...e.messages.sponsoredByChatId,[t]:n}}}}function k(e,t){return{...e,focusedMessage:{...e.focusedMessage,direction:t}}}function T(e,t,n){return{...e,selectedMessages:{chatId:t,messageIds:n?Array.prototype.concat([],n):[]}}}function N(e,t,n,r,o,d,s,i=!1){const{selectedMessages:c}=e;d&&(s=(0,u.xH)(e,t,d));const l=s||[o];if(!c)return T(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 d=(0,u.$W)(e,t,n,r),s=d.indexOf(f[f.length-1]),i=d.indexOf(o),c=Math.min(s,i),l=Math.max(s,i),m=d.slice(c,l+1);h=(0,a.Tw)([...f,...m])}else h=[...f,...m];return h.length?{...e,selectedMessages:{...c,messageIds:h}}:L(e)}function L(e){return{...e,selectedMessages:void 0}}function R(e,t,n,r,o){const{channelPostId:d,fromChatId:a}=t.forwardInfo||{};if(d&&a){const t=(0,u.tZ)(e,n,d);t&&(e=l(e,n,d,"threadInfo",{...t,lastMessageId:r,messagesCount:t.messagesCount+(o?-1:1)}))}return e}function D(e,t,n,r,o){const d=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,a.ee)(d,"id")},[t]:{...e.stickers[t],hash:n,..."search"===t?{resultIds:o}:{setIds:r.map((({id:e})=>e))}}}}}function O(e,t,n){const r=e.stickers.setsById[t]||{};return{...e,stickers:{...e.stickers,setsById:{...e.stickers.setsById,[t]:{...r,...n}}}}}function Z(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 _(e,t){return{...e,animatedEmojis:t}}function x(e,t,n,r){const o=[...(0,u.Pk)(e,t),...n||[]],d=(0,a.Tw)(o.map((({id:e})=>e))),s=(0,a.ee)(o,"id"),i=d.map((e=>s[e]));return{...e,stickers:{...e.stickers,forEmoji:{emoji:t,stickers:i,hash:r}}}}function F(e){const{emoji:t,stickers:n,hash:r}=e.stickers.forEmoji||{};return t?x(e,t,n,r):e}var B=n(735);function $(e,t){return{...e,users:{...e.users,byId:t}}}function U(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 j(e,t,n){const{byId:r}=e.users,o=H(e,t,n);return o?$(e=U(e,[o]),{...r,[t]:o}):e}function W(e,t){const n=Object.keys(t).reduce(((n,r)=>{const o=H(e,r,t[r]);return o&&(n[r]=o),n}),{});return e=U(e=$(e,{...e.users.byId,...n}),Object.values(n))}function G(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=H(e,d,t[d]);n&&(o[d]=n,r||(r=!0))}return o}),{});return r?e=U(e=$(e,{...n,...o}),Object.values(o)):e}function H(e,t,n){const{byId:r}=e.users,o=r[t],d=n.isMin&&o&&!o.isMin,u={...o,...d?(0,a.CE)(n,["isMin","accessHash"]):n};if(u.id&&u.type)return u}function V(e,t){return e.users.selectedId===t?e:{...e,users:{...e.users,selectedId:t}}}function z(e,t){const{byId:n}=e.users,{userIds:r}=e.contactList||{};return $(e={...e,contactList:{userIds:r?r.filter((e=>e!==t)):B.D}},{...n,[t]:{...n[t],isContact:void 0}})}function Q(e,t){return{...e,userSearch:{...e.userSearch,...t}}}function K(e,t){return Q(e,{fetchingStatus:t})}function J(e,t,n){const{byId:r}=e.users,o=r[t];return o&&o.fullInfo?j(e,t,{...o,fullInfo:{...o.fullInfo,isBlocked:n}}):e}function q(e,t){return{...e,users:{...e.users,statusesById:t}}}function Y(e,t){const{statusesById:n}=e.users,r=Object.keys(t).filter((e=>!n[e]));return r.length?e=q(e,{...n,...(0,a.ei)(t,r)}):e}const X=e=>`${e.chatId}_${e.id}`;function ee(e,t){return{...e,globalSearch:{...e.globalSearch,...t}}}function te(e,t){return ee(e,{currentContent:t})}function ne(e,t,n,r,o){var d;const{resultsByType:u}=e.globalSearch||{},s=t.reduce(((e,t)=>(e[X(t)]=t,e)),{}),i=null==u||null===(d=u[r])||void 0===d?void 0:d.foundIds;if(void 0!==i&&Object.keys(s).every((e=>i.includes(X(s[e])))))return re(e,{messages:!1});const c=i||[],l=t.map((e=>X(e))),f=Array.prototype.concat(c,l),h=(0,a.et)(c,f)?c:f;return ee(e=re(e,{messages:!1}),{resultsByType:{...(e.globalSearch||{}).resultsByType,[r]:{totalCount:n,nextOffsetId:o,foundIds:h}}})}function re(e,t){return ee(e,{fetchingStatus:{...e.globalSearch.fetchingStatus,...t}})}var oe=n(2858);function de(e,t,n){return{...e,localTextSearch:{byChatThreadKey:{...e.localTextSearch.byChatThreadKey,[t]:n}}}}function ue(e,t,n,r,o){const d=(0,oe.uw)(t,n);return de(e,d,{...e.localTextSearch.byChatThreadKey[d],isActive:r,query:o})}function ae(e,t,n,r,o,d){const u=(0,oe.uw)(t,n);return de(e,u,{...e.localTextSearch.byChatThreadKey[u],results:{foundIds:r,totalCount:o,nextOffsetId:d}})}function se(e,t,n,r,o,d){const u=(0,oe.uw)(t,n),{results:s}=e.localTextSearch.byChatThreadKey[u]||{},i=(null==s?void 0:s.foundIds)||[],c=fe((0,a.Tw)(Array.prototype.concat(i,r)));return ae(e,t,n,(0,a.et)(i,c)?i:c,o,d)}function ie(e,t,n){return{...e,localMediaSearch:{byChatId:{...e.localMediaSearch.byChatId,[t]:n}}}}function ce(e,t,n){return ie(e,t,{...e.localMediaSearch.byChatId[t],currentType:n})}function le(e,t,n,r,o,d){const{resultsByType:u}=e.localMediaSearch.byChatId[t]||{},s=null!=u&&u[n]?u[n].foundIds:[],i=fe((0,a.Tw)(Array.prototype.concat(s,r)));return function(e,t,n,r,o,d){return ie(e,t,{...e.localMediaSearch.byChatId[t],resultsByType:{...(e.localMediaSearch.byChatId[t]||{}).resultsByType,[n]:{foundIds:r,totalCount:o,nextOffsetId:d}}})}(e,t,n,(0,a.et)(s,i)?s:i,o,d)}function fe(e){return e.sort(((e,t)=>e-t))}function he(e,t){return{...e,management:{...e.management,progress:t}}}function me(e,t,n){return{...e,management:{...e.management,byChatId:{...e.management.byChatId,[t]:{...e.management.byChatId[t]||{},...n}}}}}function pe(e,t){return{...e,settings:{...e.settings,byKey:{...e.settings.byKey,...t}}}}function ge(e,t,n){return{...e,settings:{...e.settings,themes:{...e.settings.themes,[t]:{...e.settings.themes[t]||{},...n}}}}}function ye(e,t){return t.forEach((t=>{const{chatId:n,...r}=t;e=ve(e,n,r)})),e}function ve(e,t,n){return{...e,settings:{...e.settings,notifyExceptions:{...e.settings.notifyExceptions,[t]:n}}}}function be(e,t,n,r){switch(t){case"contact":return pe(e,{...void 0!==n&&{hasPrivateChatsNotifications:!n},...void 0!==r&&{hasPrivateChatsMessagePreview:r}});case"group":return pe(e,{...void 0!==n&&{hasGroupNotifications:!n},...void 0!==r&&{hasGroupMessagePreview:r}});case"broadcast":return pe(e,{...void 0!==n&&{hasBroadcastNotifications:!n},...void 0!==r&&{hasBroadcastMessagePreview:r}});default:return}}function we(e,t){return e=J(e,t,!0),{...e,blocked:{...e.blocked,ids:[t,...e.blocked.ids],totalCount:e.blocked.totalCount+1}}}function Ie(e,t){return e=J(e,t,!1),{...e,blocked:{...e.blocked,ids:e.blocked.ids.filter((e=>e!==t)),totalCount:e.blocked.totalCount-1}}}function Ce(e,t){return{...e,twoFaSettings:{...e.twoFaSettings,...t}}}function Se(e,t){return{...e,payment:{...e.payment,shippingOptions:t}}}function Ee(e,t){return{...e,payment:{...e.payment,requestId:t}}}function Pe(e,t){return{...e,payment:{...e.payment,step:t}}}function Me(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 Ae(e,t){return{...e,payment:{...e.payment,stripeCredentials:{...t}}}}function ke(e,t){return{...e,payment:{...e.payment,...t}}}function Te(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 Ne(e){return{...e,payment:{}}}function Le(e){return{...e,payment:{...e.payment,isPaymentModalOpen:!1}}}},8857:(e,t,n)=>{n.d(t,{Z1:()=>s,Dg:()=>i,FM:()=>c,xo:()=>l,P_:()=>f,YK:()=>h,IK:()=>m,pk:()=>p,g4:()=>g,N:()=>y,Ek:()=>v,Mw:()=>b,ep:()=>w,DI:()=>I,A1:()=>C,UW:()=>S,_5:()=>E});var r=n(6137),o=n(2858),d=n(6376),u=n(3716),a=n(2913);function s(e,t){return e.chats.byId[t]}function i(e,t){const n=(0,o.zX)(t);return!!n&&(0,d.dy)(e,n)}function c(e,t){return t===e.currentUserId}function l(e,t){const n=i(e,t);return n&&(0,o.cS)(n)}function f(e){return Object.values(e.chats.byId).find((({isSupport:e})=>e))}function h(e,t){if(!(0,o.YC)(t.id)&&!(0,o.eA)(t)&&t.fullInfo)return t.fullInfo.members&&t.fullInfo.members.length!==u.mo?t.fullInfo.members.reduce(((t,{userId:n})=>n!==e.currentUserId&&e.users.byId[n]&&(0,o.kM)(e.users.byId[n],e.users.statusesById[n])?t+1:t),0):t.fullInfo.onlineCount}function m(e,t){const n=s(e,t),r=n&&(0,o.zX)(n),u=r&&(0,d.dy)(e,r);if(u&&(0,o.cS)(u))return u}function p(e,t){const n=s(e,t),d=m(e,t);if(!n||!d)return!1;if(n.lastMessage&&(0,o.CD)(n.lastMessage))return!0;const u=e.messages.byChatId[t];if(!u)return!1;const{listedIds:a}=u.threadsById[r._f]||{};return a&&!a.length}function g(e){return Boolean(e.chats.listIds.active)}function y(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 v(e,t){const n=s(e,t);if(n&&y(e,t))return n.folderId===u.WS?"archived":"active"}function b(e,t){return e.chatFolders.byId[t]}function w(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 I(e,t){const n=t.toLowerCase();return Object.values(e.chats.byId).find((e=>e.username&&e.username.toLowerCase()===n))}function C(e){const t=e.chats.listIds.active;if(!t)return 0;const n=e.chats.byId,r=(0,a.d)(e),d=(0,a.N)(e);return t.reduce(((e,t)=>{const u=n[t];return!(u&&u.unreadCount&&u.isListed)||u.isNotJoined||u.isRestricted||!u.unreadMentionsCount&&(0,o.i4)(u,r,d)?e:e+u.unreadCount}),0)}function S(e){return Boolean(s(e,u.aw))}function E(e,t){var n;const r=s(e,t);if(!r)return;const o=null==r||null===(n=r.fullInfo)||void 0===n?void 0:n.sendAsId;return o?(0,d.dy)(e,o)||s(e,o):void 0}},1638:(e,t,n)=>{n.d(t,{hg:()=>j,xs:()=>oe,_k:()=>X,zB:()=>g,g4:()=>a.g4,bH:()=>ye,__:()=>be,xl:()=>ee,Nu:()=>ne,nB:()=>te,Z1:()=>a.Z1,IK:()=>a.IK,DI:()=>a.DI,Mw:()=>a.Mw,Ek:()=>a.Ek,hj:()=>G,ZB:()=>z,Zw:()=>I,YK:()=>a.YK,Dg:()=>a.Dg,X5:()=>ie,A1:()=>a.A1,jr:()=>w,yN:()=>f,JX:()=>Oe,pP:()=>Te,we:()=>Ae,og:()=>Me,$W:()=>M,Bt:()=>b,y5:()=>l,n5:()=>Pe,Ms:()=>O,_$:()=>R,kK:()=>V,wU:()=>D,yZ:()=>x,It:()=>ae,G$:()=>Q,y8:()=>fe,cv:()=>Y,ku:()=>Se,pk:()=>a.pk,N:()=>a.N,ep:()=>a.ep,xo:()=>a.xo,FM:()=>a.FM,a6:()=>me,te:()=>re,Ev:()=>se,CA:()=>ce,zQ:()=>Ne,_X:()=>K,EV:()=>Ce,vk:()=>le,Jf:()=>Re,UW:()=>a.UW,s4:()=>s.s4,b9:()=>W,VF:()=>Ie,gb:()=>E,aW:()=>ke,xH:()=>he,FT:()=>ge,tV:()=>Z,NJ:()=>Ue.N,dZ:()=>Ue.d,dT:()=>J,qC:()=>P,gx:()=>Ze,eh:()=>xe,Mz:()=>_e,sp:()=>Fe,KB:()=>k,$$:()=>Be,rd:()=>ue,p9:()=>F,Yy:()=>L,Wq:()=>Le,qy:()=>T,Tm:()=>H,Fn:()=>C,Vt:()=>N,D7:()=>pe,_5:()=>a._5,Ur:()=>q,yB:()=>we,fS:()=>Ee,Ny:()=>h,E_:()=>m,Pk:()=>p,i3:()=>$e,P_:()=>a.P_,Pu:()=>De,Db:()=>U,tZ:()=>_,Cm:()=>B,qS:()=>$,uZ:()=>de,dy:()=>s.dy,ss:()=>s.ss,Cb:()=>A});var r=n(1713),o=n(7361),d=n(6137),u=n(3716),a=n(8857),s=n(6376),i=n(2858),c=n(782);function l(e){return e.stickers.search}function f(e){return e.gifs.search}function h(e,t){return e.stickers.setsById[t]}function m(e,t){return Object.values(e.stickers.setsById).find((e=>e.shortName.toLowerCase()===t.toLowerCase()))}function p(e,t){const n=Object.values(e.stickers.setsById);let r=[];return e.stickers.favorite.stickers.forEach((e=>{e.emoji===t&&r.push(e)})),n.forEach((({packs:e})=>{if(!e)return;const n=e[t];n&&(r=r.concat(n))})),r}function g(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 y=n(2267),v=n(735);function b(e){const{messageLists:t}=e.messages;if(t.length)return t[t.length-1]}function w(e){const{chatId:t}=b(e)||{};return t?(0,a.Z1)(e,t):void 0}function I(e,t){var n;return null===(n=e.messages.byChatId[t])||void 0===n?void 0:n.byId}function C(e,t){var n;return null===(n=e.scheduledMessages.byChatId[t])||void 0===n?void 0:n.byId}function S(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 E(e,t,n){return S(e,t,n,"listedIds")}function P(e,t,n){return S(e,t,n,"outlyingIds")}function M(e,t,n,r){switch(r){case"thread":return A(e,t,n);case"pinned":return k(e,t);case"scheduled":return T(e,t)}}function A(e,t,n){return S(e,t,n,"viewportIds")}function k(e,t){return S(e,t,d._f,"pinnedIds")}function T(e,t){return S(e,t,d._f,"scheduledIds")}function N(e,t,n){return S(e,t,n,"scrollOffset")}function L(e,t,n){return S(e,t,n,"replyingToId")}function R(e,t,n){return S(e,t,n,"editingId")}function D(e,t){return S(e,t,d._f,"editingScheduledId")}function O(e,t,n){return S(e,t,n,"draft")}function Z(e,t,n){return S(e,t,n,"noWebPage")}function _(e,t,n){return S(e,t,n,"threadInfo")}function x(e,t,n){return S(e,t,n,"firstMessageId")}function F(e,t,n){return S(e,t,n,"replyStack")}function B(e,t,n){if(n===d._f)return(0,a.Z1)(e,t);const r=_(e,t,n);return r?(0,a.Z1)(e,r.originChannelId||t):void 0}function $(e,t,n){if(n===d._f)return;const r=_(e,t,n);return r?r.topMessageId:void 0}function U(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 j(e,t,n){const r=b(e);if(!r)return!1;const{threadInfo:o}=U(e,t,n)||{};return t===r.chatId&&(r.threadId===d._f||o&&r.threadId===o.threadId)}function W(e,t,n){const r=A(e,t,n);if(!r||!r.length)return!0;let o;if(n===d._f){const n=(0,a.Z1)(e,t);if(!n||!n.lastMessage)return!0;o=n.lastMessage.id}else{const r=_(e,t,n);if(!r||!r.lastMessageId)return;o=r.lastMessageId}return o>=u.AE&&!G(e,t,o)||r[r.length-1]>=o}function G(e,t,n){const r=I(e,t);return r?r[n]:void 0}function H(e,t,n){const r=C(e,t);return r?r[n]:void 0}function V(e,t,n,r){if("scheduled"===r){const n=D(e,t);return n?H(e,t,n):void 0}{const r=R(e,t,n);return r?G(e,t,r):void 0}}function z(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 Q(e,t){const{chatId:n,messageId:r}=e.focusedMessage||{};return n===t?r:void 0}function K(e,t){const n=Q(e,t.chatId);return!!n&&(n===t.id||n===t.previousLocalId)}function J(e,t,n=!1){return function(e,t){const{lastReadOutboxMessageId:n}=(0,a.Z1)(e,t.chatId)||{};return(0,i.CI)(t)||!n||ne===t.id))}(e,t.content.sticker),Z=!b&&D&&!O,_=!b&&O,x=!b,F=!b&&(m||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,L,E,P,T,A,N,R,Z,_,x,F,B,$].every((e=>!e)),canReply:C,canEdit:L,canPin:E,canUnpin:P,canReport:T,canDelete:A,canDeleteForAll:N,canForward:R,canFaveSticker:Z,canUnfaveSticker:_,canCopy:x,canCopyLink:F,canSelect:B,canDownload:$}}function ee(e){const{messageIds:t}=e.selectedMessages||{},{chatId:n,threadId:r}=b(e)||{},o=n&&I(e,n);if(!o||!t||!r)return{};const d=t.map((t=>o[t]&&X(e,o[t],r))).filter(Boolean);return{canDelete:d.every((e=>e.canDelete)),canDeleteForAll:d.every((e=>e.canDeleteForAll))}}function te(e){const{messageIds:t}=e.selectedMessages||{},{chatId:n,threadId:r}=b(e)||{},o=n&&I(e,n);return!!(o&&t&&r)&&t.map((t=>o[t]&&X(e,o[t],r))).filter(Boolean).every((e=>e.canReport))}function ne(e){const{messageIds:t}=e.selectedMessages||{},{chatId:n,threadId:r}=b(e)||{},o=n&&I(e,n);return!!(o&&t&&r)&&t.map((t=>o[t]&&X(e,o[t],r))).filter(Boolean).some((e=>e.canDownload))}function re(e,t){const n=e.activeDownloads.byChatId[t.chatId];return!!n&&n.includes(t.id)}function oe(e,t){return e.activeDownloads.byChatId[t]||v.D}function de(e,t){var n;return null===(n=e.fileUploads.byMessageLocalId[t.previousLocalId||t.id])||void 0===n?void 0:n.progress}function ue(e,t,n){if(n===d._f){const n=(0,a.Z1)(e,t);if(!n)return;if(!n.lastReadInboxMessageId)return;return n.lastMessage?(0,i.CI)(n.lastMessage)?n.lastMessage.id:Math.min(n.lastMessage.id,n.lastReadInboxMessageId):n.lastReadInboxMessageId}{const r=_(e,t,n);if(!r)return;return r.lastReadInboxMessageId?Math.min(r.lastReadInboxMessageId,r.lastMessageId||1/0):r.topMessageId}}function ae(e,t,n){const r=(0,a.Z1)(e,t);if(n===d._f){if(!r)return}else{const r=_(e,t,n);if(!r||void 0!==r.lastMessageId&&r.lastMessageId===r.lastReadInboxMessageId)return}const o=P(e,t,n),s=E(e,t,n),i=I(e,t);if(!i||!o&&!s)return;const c=ue(e,t,n);if(!c&&r&&r.isNotJoined)return;const l=t===u.aw?e.serviceNotifications.reduce(((e,t)=>!t.isUnread&&t.id>e?t.id:e),-1):-1;function f(e){return e.find((e=>(!c||e>c)&&i[e]&&(!i[e].isOutgoing||i[e].isFromScheduled)&&e>l))}if(o){const e=f(o);if(e)return e}if(s){const e=f(s);if(e)return e}}function se(e){const{forwardMessages:t}=e;return Boolean(t.isModalShown)}function ie(e,t){const n=Object.values(e.chats.byId).find((e=>(0,i.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=(0,a.Z1)(e,n);return o&&(0,i.Ru)(o)&&r[o.id].byId[t]}))}function ce(e){const{selectedMessages:t}=e;return Boolean(t)}function le(e,t){const{messageIds:n}=e.selectedMessages||{};return!!n&&n.includes(t)}function fe(e,t,n){const r=I(e,t);if(r)return Object.values(r).filter((e=>e.groupedId===n&&e.forwardInfo)).map((({forwardInfo:e})=>e.fromMessageId))}function he(e,t,n){const r=I(e,t);if(r)return Object.keys(r).map(Number).filter((e=>r[e].groupedId===n))}function me(e,t,n){const{messageIds:r}=e.selectedMessages||{};if(!r)return!1;const o=he(e,t,n);return o&&o.every((e=>r.includes(e)))}function pe(e){const{messageIds:t}=e.selectedMessages||{};return t?t.length:0}function ge(e,t){const n=(0,a.Z1)(e,t);if(!n)return;if(!(0,a.xo)(e,n))return;const r=I(e,t),o=A(e,t,d._f);if(!r||!o)return;const u=(0,c.dF)(o,(e=>!r[e].isOutgoing&&Boolean(r[e].keyboardButtons))),s=(0,c.dF)(o,(e=>Boolean(r[e].shouldHideKeyboardButtons)));return u&&s&&s>u?void 0:u?r[u]:void 0}function ye(e,t){const n=(0,a.Z1)(e,t.chatId);if(!n)return;const r=q(e,t),o=Boolean((0,i.O$)(t)||(0,i.F$)(t)),d=Boolean((0,i.b7)(t)||(0,i.Cg)(t)),u=Boolean((0,i.oP)(t)||(0,i.kd)(t)||(0,i.aE)(t)),{canAutoLoadPhotoFromContacts:s,canAutoLoadPhotoInPrivateChats:c,canAutoLoadPhotoInGroups:l,canAutoLoadPhotoInChannels:f,canAutoLoadVideoFromContacts:h,canAutoLoadVideoInPrivateChats:m,canAutoLoadVideoInGroups:p,canAutoLoadVideoInChannels:g,canAutoLoadFileFromContacts:y,canAutoLoadFileInPrivateChats:v,canAutoLoadFileInGroups:b,canAutoLoadFileInChannels:w}=e.settings.byKey;return o?ve({global:e,chat:n,sender:r,canAutoLoadMediaFromContacts:s,canAutoLoadMediaInPrivateChats:c,canAutoLoadMediaInGroups:l,canAutoLoadMediaInChannels:f}):d?ve({global:e,chat:n,sender:r,canAutoLoadMediaFromContacts:h,canAutoLoadMediaInPrivateChats:m,canAutoLoadMediaInGroups:p,canAutoLoadMediaInChannels:g}):!u||ve({global:e,chat:n,sender:r,canAutoLoadMediaFromContacts:y,canAutoLoadMediaInPrivateChats:v,canAutoLoadMediaInGroups:b,canAutoLoadMediaInChannels:w})}function ve({global:e,chat:t,sender:n,canAutoLoadMediaFromContacts:r,canAutoLoadMediaInPrivateChats:o,canAutoLoadMediaInGroups:d,canAutoLoadMediaInChannels:u}){const a=Boolean(n&&(n.id===e.currentUserId||(0,s.nM)(e,n)));return Boolean(a&&r||!a&&o&&(0,i.YC)(t.id)||d&&(0,i.Bf)(t)||u&&(0,i.eA)(t))}function be(e,t){const n=(0,i.b7)(t)||(0,i.Cg)(t);if(!n)return;const{canAutoPlayVideos:r,canAutoPlayGifs:o}=e.settings.byKey,d=n.isGif||n.isRound;return r&&!d||o&&d}function we(e){return e.settings.byKey.shouldLoopStickers}function Ie(e){const{serviceNotifications:t}=e,n=Math.max(...t.map((({id:e})=>e)));return t.find((({id:e})=>e===n))}function Ce(e,t){var n;return!!t&&(t.isProtected||(null===(n=(0,a.Z1)(e,t.chatId))||void 0===n?void 0:n.isProtected))}function Se(e,t,n){var r;if(null!==(r=(0,a.Z1)(e,t))&&void 0!==r&&r.isProtected)return!0;if(!n)return!1;const o=I(e,t);return n.some((e=>{var t;return null===(t=o[e])||void 0===t?void 0:t.isProtected}))}function Ee(e,t){const n=(0,a.Z1)(e,t),r=n&&(0,i.eA)(n)?e.messages.sponsoredByChatId[t]:void 0;return r&&r.expiresAt>=Math.round(Date.now()/1e3)?r:void 0}function Pe(e){const{chatId:t,threadId:n}=b(e)||{};if(!t||!n)return;const r=(0,i.uw)(t,n),o=e.localTextSearch.byChatThreadKey[r];return o&&o.isActive?o:void 0}function Me(e){const{byChatId:t}=e.localMediaSearch,{chatId:n}=b(e)||{},r=e.users.selectedId;return r&&t[r]?r:n}function Ae(e){const t=Me(e);if(t)return e.localMediaSearch.byChatId[t]}function ke(e,t){return e.management.byChatId[t]}function Te(e){const{chatId:t,threadId:n}=b(e)||{};if(!t||!n)return;if((0,i.YC)(t))return"user";const r=(0,a.Z1)(e,t);return r?(0,i.Bf)(r)?"group":"channel":void 0}function Ne(e){const{mediaViewer:t}=e;return Boolean(t.messageId||t.avatarOwnerId)}function Le(e){const{users:t,isChatInfoShown:n,newChatMembersProgress:d}=e,u=d!==r.WB.Closed,s=function(e){const{pollResults:t}=e;return Boolean(t.messageId)}(e),i=Boolean(!o.wB&&Pe(e)),c=function(e){const{chatId:t,threadId:n}=b(e)||{};if(!t||!n)return;const r=e.management.byChatId[t];return r&&r.isActive?r:void 0}(e),h=void 0!==l(e).query,m=void 0!==f(e).query,{chatId:p}=b(e)||{},g=t.selectedId,y=(0,a.g4)(e),v=Boolean(g&&y),w=Boolean(p&&y)&&n;return s?r.qt.PollResults:i?r.qt.Search:c?r.qt.Management:h?r.qt.StickerSearch:m?r.qt.GifSearch:u?r.qt.AddingMembers:v?r.qt.UserInfo:w?r.qt.ChatInfo:void 0}function Re(e){return void 0!==Le(e)}function De(e){const{theme:t,shouldUseSystemTheme:n}=e.settings.byKey;return n?(0,o.vn)():t}function Oe(e){return e.globalSearch.query}function Ze(e){return e.payment.chatId}function _e(e){return e.payment.messageId}function xe(e){return e.payment.formId}function Fe(e){return e.payment.requestId}function Be(e){return e.payment.nativeParams?e.payment.nativeParams.publishableKey:void 0}function $e(e){return e.payment.stripeCredentials}var Ue=n(2913)},2913:(e,t,n)=>{function r(e){return e.settings.byKey}function o(e){return e.settings.notifyExceptions}n.d(t,{d:()=>r,N:()=>o})},6376:(e,t,n)=>{function r(e,t){return e.users.byId[t]}function o(e,t){return e.users.statusesById[t]}function d(e,t){var n;const o=r(e,t);return null==o||null===(n=o.fullInfo)||void 0===n?void 0:n.isBlocked}function u(e,t){return e.contactList&&e.contactList.userIds.includes(t.id)}n.d(t,{dy:()=>r,ss:()=>o,s4:()=>d,nM:()=>u})},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.ChatNewAdminRights=12]="ChatNewAdminRights",e[e.GroupMembers=13]="GroupMembers",e[e.GroupAddAdmins=14]="GroupAddAdmins"}(v||(v={}))},9933:(e,t,n)=>{n.d(t,{cK:()=>d,jt:()=>u,M8:()=>a,vr:()=>s});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)}))}const a={linear:e=>e,easeIn:e=>e**1.675,easeOut:e=>1-(1-e**1.675),easeInOut:e=>.5*(Math.sin((e-.5)*Math.PI)+1),easeInQuad:e=>e*e,easeOutQuad:e=>e*(2-e),easeInOutQuad:e=>e<.5?2*e*e:(4-2*e)*e-1,easeInCubic:e=>e*e*e,easeOutCubic:e=>--e*e*e+1,easeInOutCubic:e=>e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1,easeInQuart:e=>e*e*e*e,easeOutQuart:e=>1- --e*e*e*e,easeInOutQuart:e=>e<.5?8*e*e*e*e:1-8*--e*e*e*e,easeInQuint:e=>e*e*e*e*e,easeOutQuint:e=>1+--e*e*e*e*e,easeInOutQuint:e=>e<.5?16*e*e*e*e*e:1+16*--e*e*e*e*e};function s({timing:e=a.linear,onUpdate:t,duration:n,onEnd:r,from:o,to:d}){const s=Date.now();let i=!1;return u((()=>{if(i)return!1;let u=(Date.now()-s)/n;u>1&&(u=1);const a=e(u);if("number"==typeof o&&"number"==typeof d)t(o+(d-o)*a);else if(Array.isArray(o)&&Array.isArray(d)){const e=o.map(((e,t)=>e+(d[t]-e)*a));t(e)}return 1===u&&r&&r(),u<1})),()=>{i=!0,r&&r()}}},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,SA:()=>w,xk:()=>C,IS:()=>S});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?P:E)(e("Weekday.Today"));const t=new Date(s);if(t.setDate(s.getDate()-1),i(a)===i(t))return(d||!n?P:E)(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?P:E)(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?P:E)(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())).replace(/'de'/g,"de")}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("number"==typeof e?new Date(e):e).toLocaleString(t,{year:"numeric",month:"short",day:"numeric"})}function w(e,t="en-US"){return("number"==typeof e?new Date(e):e).toLocaleString(t,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"})}function I(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 C(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||!I(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&&I(Number(u),s)?`${String(s+1).padStart(2,"0")}-${String(u).padStart(2,"0")}`:void 0}function S(e){return e+86400}function E(e){return`${e[0].toLowerCase()}${e.slice(1)}`}function P(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[^\ufe0f]/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)}},1396:(e,t,n)=>{function r(e){if(e)return e.includes("://")?e:`http://${e}`}n.d(t,{X:()=>r})},7361:(e,t,n)=>{n.d(t,{Bi:()=>k,cL:()=>R,wZ:()=>p,vX:()=>M,op:()=>C,cj:()=>m,jm:()=>h,pA:()=>L,m5:()=>P,I_:()=>E,fl:()=>y,t0:()=>A,s$:()=>g,i4:()=>O,Mc:()=>S,wB:()=>b,p7:()=>w,$b:()=>v,mh:()=>I,s0:()=>T,aZ:()=>D,gZ:()=>Z,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="requestFullscreen"in document.createElement("div"),k=!navigator.userAgent.includes("Firefox"),T=p?"slide-fade":m?"slide-layers":"push-slide",N=document.createElement("video"),L=Boolean(N.canPlayType(r.Ng).replace("no","")||m);L&&r.wG.add(r.Ng);const R=window.devicePixelRatio||1,D=!0,O=!h&&!m&&!p,Z=O?300:750},1394:(e,t,n)=>{n.d(t,{A9:()=>d,YJ:()=>u,hl:()=>a,pt:()=>s,jj:()=>i,ud:()=>c,gm:()=>l,dc:()=>f,ao:()=>h});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()}async function f(e,t){return a(await l(e),t)}function h(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",ADMINS_TOO_MUCH:"There are too many admins",ADMIN_RANK_EMOJI_NOT_ALLOWED:"An admin rank cannot contain emojis",ADMIN_RANK_INVALID:"The specified admin rank is invalid",FRESH_CHANGE_ADMINS_FORBIDDEN:"You were just elected admin, you can't add or modify other admins yet",INPUT_USER_DEACTIVATED:"The specified user was deleted"},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"){function r(e,t,n,r){const o=("function"==typeof n?n(e):e[n])||0,d=("function"==typeof n?n(t):t[n])||0;return r?o-d:d-o}if(Array.isArray(t)){const[o,d]=Array.isArray(n)?n:[n,n],[u,a]=t,s="asc"===o,i="asc"===d;return e.sort(((e,t)=>r(e,t,u,s)||r(e,t,a,i)))}const o="asc"===n;return e.sort(((e,n)=>r(e,n,t,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",e[e.Calls=3]="Calls"}(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(739),n.e(886),n.e(884),n.e(87)]).then(n.bind(n,4087));break;case o.Extra:d[o.Extra]=Promise.all([n.e(739),n.e(886),n.e(301)]).then(n.bind(n,4301));break;case o.Calls:d[o.Calls]=Promise.all([n.e(739),n.e(884),n.e(532)]).then(n.bind(n,7936))}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(8005),u=n(3716),a=n(5116),s=n(2858),i=n(663),c=n(307),l=n(1638),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 s(y,e)}function u(e){return s(v,e)}function a(e){return s(b,e)}function s(e,t){let n,r=!1;return(...o)=>{n=o,r||(r=!0,e((()=>{r=!1,t(...n)})))}}function i(e,t){self.requestIdleCallback?self.requestIdleCallback(e,{timeout:t}):b(e)}n.d(t,{Ds:()=>r,P2:()=>o,mS:()=>d,wT:()=>u,$6:()=>a,Q8:()=>i,wO:()=>c,Pn:()=>l,T2:()=>y,D0:()=>v,R3:()=>b,zD:()=>w,Gq:()=>I});const c=e=>new Promise((t=>{setTimeout((()=>t()),e)}));function l(){return new Promise((e=>{y(e)}))}let f,h,m,p,g;function y(e,t=!1){f?t?h.push(e):f.push(e):(f=t?[]:[e],h=t?[e]:[],requestAnimationFrame((()=>{const e=f,t=h;f=void 0,h=void 0,t.forEach((e=>e())),e.forEach((e=>e()))})))}function v(e){y(e,!0)}function b(e,t=!1){m?t?p.push(e):m.push(e):(m=t?[]:[e],p=t?[e]:[],Promise.resolve().then((()=>{const e=m,t=p;m=void 0,p=void 0,t.forEach((e=>e())),e.forEach((e=>e()))})))}function w(e){b(e,!0)}function I(e,t=!1){return g||(g=[],self.addEventListener("beforeunload",(()=>{g.forEach((e=>e()))}))),t?g.push(e):g.unshift(e),()=>{g=g.filter((t=>t!==e))}}},5765:(e,t,n)=>{let r;n.d(t,{Z:()=>o,W:()=>d});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="string"==typeof t?t.toLowerCase().split(r):t,o=e.toLowerCase();if(1===n.length&&!o.includes(n[0]))return!1;let d;return n.every((e=>!!o.includes(e)&&(d||(d=o.split(r)),d.some((t=>t.startsWith(e))))))}function d(e){const t=e.toLowerCase().split(r);return e=>o(e,t)}},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.cK)((()=>{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+"."+{87:"77459230580aafa8639a",99:"f03a947e6e336feffec8",133:"64de2daa3ae6549d8f45",161:"286d0207d962142ad548",301:"751950a7a21e70acdb7c",354:"44bc53595e49ca5bc9f9",472:"21e5264f606f2b525030",501:"72ce4b6e27f459e194cd",524:"80c446dcb25355f04b36",532:"5ff953a5af12d8af60a9",536:"55dc7dd4ab42a2c9f037",739:"462b85f7a954e903b4cd",745:"9316c5c2b711c39a20a5",884:"bf91279ce235c0463204",886:"2870895152d4462e05bf",915:"0588cdc78683d0e9bbbc",927:"04b93a71a7d051ccd448",941:"5b93118a31cc89905ee3",993:"f0aad9f6787f211b4e51"}[e]+".js",s.miniCssF=e=>e+"."+{87:"77459230580aafa8639a",133:"64de2daa3ae6549d8f45",301:"751950a7a21e70acdb7c",472:"21e5264f606f2b525030",532:"5ff953a5af12d8af60a9",886:"2870895152d4462e05bf"}[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]&&{87:1,133:1,301:1,472:1,532:1,886: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.ZT&&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:{},statusesById:{}},chats:{listIds:{},isFullyLoaded:{},orderedPinnedIds:{},totalCount:{},byId:{}},messages:{byChatId:{},messageLists:[],sponsoredByChatId:{}},groupCalls:{byId:{}},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(1638),m=s(4688),p=s(5780),g=s(6590),y=s(2858);const v=(0,c.P2)((()=>(0,c.Q8)(S)),5e3,!1);let b,w=!1;function I(){w=!0,b=(0,c.Gq)(S,!0),window.addEventListener("blur",S),(0,t.ll)(v)}function C(){w=!1,(0,t.Iq)(v),window.removeEventListener("blur",S),b&&b()}function S(){if(!w||(0,l.zG)())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:E(n),users:P(n),chats:M(n),messages:A(n),globalSearch:{recentlyFoundChatIds:n.globalSearch.recentlyFoundChatIds},settings:k(n),chatFolders:T(n),groupCalls:N(n)},o=JSON.stringify(r);localStorage.setItem(e.Uh,o)}function E(t){return window.innerWidth>e._m&&t.isChatInfoShown}function P(t){const{users:{byId:n,statusesById:r,selectedId:o}}=t,d=(t.chats.listIds.active||[]).slice(0,e.gJ).filter(y.YC),u=Object.keys(n),a=d.concat(u).slice(0,e.lO);return{byId:(0,f.ei)(n,a),statusesById:(0,f.ei)(r,a),selectedId:window.innerWidth>e._m?o:void 0}}function M(t){const n=(t.chats.listIds.active||[]).slice(0,e.gJ),{chatId:r}=(0,h.Bt)(t)||{},o=n.concat(r?[r]:[]);return{...t.chats,byId:(0,f.ei)(t.chats.byId,o),listIds:{active:n},isFullyLoaded:{},orderedPinnedIds:{active:t.chats.orderedPinnedIds.active}}}function A(t){const n={},{chatId:r}=(0,h.Bt)(t)||{};return(t.chats.listIds.active||[]).slice(0,e.gJ).concat(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:[],sponsoredByChatId:{}}}function k(e){const{byKey:t,themes:n}=e.settings;return{byKey:t,themes:n,privacy:{},notifyExceptions:{}}}function T(e){return{...e.chatFolders,activeChatFolder:0}}function N(e){return{...e.groupCalls,byId:{},activeGroupCallId:void 0,isGroupCallPanelHidden:void 0,isFallbackConfirmOpen:void 0}}e.sd||((0,t.Q6)("saveSession",(()=>{w||I()})),(0,t.Q6)("reset",(()=>{localStorage.removeItem(e.Uh),w&&C()}))),(0,t.Q6)("init",(()=>{const t=(0,f.Xh)(a);return function(t){if(!e.sd)return(0,m.ti)(!0)?(I(),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),t.groupCalls||(t.groupCalls=n.groupCalls),t.users.statusesById||(t.users.statusesById={}),t.messages.sponsoredByChatId||(t.messages.sponsoredByChatId={})}(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 C()}(t)||t}));var L=s(4050),R=s(3858);const D="tt-active-tab",O=String(Date.now()+Math.random());let Z;localStorage.setItem(D,O);const _=window.setInterval((()=>{Z&&localStorage.getItem(D)!==O&&(Z(),clearInterval(_))}),2e3);var x=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),G=s(9203),H=s(6752),V=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,G.$y)(G.gl.Main,"Main").then(j),Q()]),authPhoneNumber:()=>Promise.all([j(),(0,$.pt)(V)]),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}}))((({page:e,children:n,hasCustomBackground:r,hasCustomBackgroundColor:o,isRightColumnShown:d,shouldSkipHistoryAnimations:u,leftColumnWidth:a})=>{const{setIsUiReady:s}=(0,t.uC)(),[i,l]=(0,x.Z)(),{shouldRender:f,transitionClassNames:h}=(0,B.Z)(!i,void 0,!0);return(0,L.d4)((()=>{let t;return Promise.race([(0,c.wO)(700),(async()=>{try{await K[e]()}catch(e){}})()]).then((()=>{l(),s({uiReadyState:1}),t=window.setTimeout((()=>{s({uiReadyState:2})}),1e3)})),()=>{t&&(clearTimeout(t),t=void 0),s({uiReadyState:0})}}),[]),L.ZP.createElement("div",{id:"UiLoader"},n,f&&!u&&L.ZP.createElement("div",{className:(0,H.Z)("mask",h)},"main"===e?L.ZP.createElement(L.ZP.Fragment,null,L.ZP.createElement("div",{className:"left",style:a?`width: ${a}px`:void 0}),L.ZP.createElement("div",{className:(0,H.Z)("middle",r&&"custom-bg-image",o&&"custom-bg-color",d&&"with-right-column")}),d&&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=""){if(!t.length)return e;const n=(0,ue.W)(t);return e.filter((e=>n(e.defaultName)||e.name&&n(e.name)))}(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,H.Z)("input-group",t&&"touched")},L.ZP.createElement("input",{ref:u,className:(0,H.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,H.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}}))((({connectionState:e,authState:r,authPhoneNumber:o,authIsLoading:d,authIsLoadingQrCode:u,authError:a,authRememberMe:s,authNearestCountry:i,phoneCodeList:c,language:l})=>{const{setAuthPhoneNumber:f,setAuthRememberMe:h,loadNearestCountry:m,loadCountryList:p,clearAuthError:g,goToAuthQrCode:y,setSettingOption:v}=(0,t.uC)(),b=(0,X.Z)(),w=(0,L.sO)(null),I=te(),C=ee(I,"ContinueOnThisLanguage"),[S,E]=(0,L.eJ)(),[P,M]=(0,L.eJ)(),[A,k]=(0,L.eJ)(!1),[T,N]=(0,L.eJ)(),[R,D,O]=(0,x.Z)(),Z=S?`+${S.countryCode} ${P||""}`:P,_=Z&&Z.replace(/[^\d]+/g,"").length>=7;(0,L.d4)((()=>{n.$b||w.current.focus()}),[S]),(0,L.d4)((()=>{"connectionStateReady"!==e||i||m()}),[e,i,m]),(0,L.d4)((()=>{"connectionStateReady"===e&&p({langCode:l})}),[e,l,p]),(0,L.d4)((()=>{i&&c&&!S&&!A&&E((0,q.U9)(c,i)[0])}),[S,i,A,c]);const F=(0,L.I4)((e=>{e.length||M("");const t=c&&(0,q.g3)(c,e),n=!S||t&&t.iso2!==S.iso2||!t&&e.length?t:S;(!S||!n||n&&n.iso2!==S.iso2)&&E(n),M((0,q.un)(e,n))}),[c,S]),B=(0,L.I4)((()=>{D(),(0,Y.m0)(I,(()=>{O(),v({language:I})}))}),[D,v,I,O]);(0,L.d4)((()=>{void 0===P&&o&&F(o)}),[o,P,F]),(0,L.bt)((()=>{w.current&&T&&w.current.setSelectionRange(...T)}),[T]);const U=(0,L.sO)(!1),W=(0,L.I4)((()=>{U.current=!0,requestAnimationFrame((()=>{U.current=!1}))}),[]),G=(0,L.I4)((e=>{E(e),M("")}),[]),H=(0,L.I4)((e=>{a&&g(),pe||(pe=!0,j(),(0,$.pt)(z));const{value:t,selectionStart:r,selectionEnd:o}=e.target;N(r&&o&&o1&&!U.current;F(d?`${S.countryCode} ${t}`:t)}),[a,g,S,Z,F]),V=(0,L.I4)((e=>{h(e.target.checked)}),[h]),Q="authorizationStateWaitPhoneNumber"===r;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"},b("StartText")),L.ZP.createElement("form",{action:"",onSubmit:function(e){e.preventDefault(),d||_&&f({phoneNumber:Z})}},L.ZP.createElement(me,{id:"sign-in-phone-code",value:S,isLoading:!i&&!S,onChange:G}),L.ZP.createElement(oe.Z,{ref:w,id:"sign-in-phone-number",label:b("Login.PhonePlaceholder"),value:Z,error:a&&b(a),inputMode:"tel",onChange:H,onPaste:n.s$?W:void 0}),L.ZP.createElement(re.Z,{id:"sign-in-keep-session",label:"Keep me signed in",checked:Boolean(s),onChange:V}),_&&(Q?L.ZP.createElement(ne.Z,{type:"submit",ripple:!0,isLoading:d},b("Login.Next")):L.ZP.createElement(de.Z,null)),Q&&L.ZP.createElement(ne.Z,{isText:!0,ripple:!0,isLoading:u,onClick:y},b("Login.QR.Login")),I&&I!==l&&C&&L.ZP.createElement(ne.Z,{isText:!0,isLoading:R,onClick:B},C))))})));var ye=s(8778);const ve=(0,L.X$)((()=>{const e=(0,ye.Z)(G.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)(G.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)(G.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}}))((({connectionState:n,authState:r,authQrCode:o,language:d})=>{const{returnToAuthPhoneNumber:u,setSettingOption:a}=(0,t.uC)(),s=te(),i=(0,X.Z)(),c=(0,L.sO)(null),l=ee(s,"ContinueOnThisLanguage"),[f,h,m]=(0,x.Z)();(0,L.d4)((()=>{if(!o||"connectionStateReady"!==n)return;const e=c.current;e.innerHTML="",e.classList.remove("pre-animate"),Se.render({text:`tg://login?token=${o.token}`,radius:.5,ecLevel:"M",fill:"#4E96D4",size:280},e)}),[n,o]),(0,L.d4)((()=>{"connectionStateReady"===n&&(0,Y.m0)(e.sR)}),[n]);const p=(0,L.I4)((()=>{h(),(0,Y.m0)(s,(()=>{m(),a({language:s})}))}),[h,a,s,m]),g="authorizationStateWaitQrCode"===r;return L.ZP.createElement("div",{id:"auth-qr-form",className:"custom-scroll"},L.ZP.createElement("div",{className:"auth-form qr"},o?L.ZP.createElement("div",{key:"qr-container",className:"qr-container pre-animate",ref:c}):L.ZP.createElement("div",{key:"qr-loading",className:"qr-loading"},L.ZP.createElement(de.Z,null)),L.ZP.createElement("h3",null,i("Login.QR.Title")),L.ZP.createElement("ol",null,L.ZP.createElement("li",null,L.ZP.createElement("span",null,i("Login.QR.Help1"))),L.ZP.createElement("li",null,L.ZP.createElement("span",null,(0,ae.Z)(i("Login.QR.Help2"),["simple_markdown"]))),L.ZP.createElement("li",null,L.ZP.createElement("span",null,i("Login.QR.Help3")))),g&&L.ZP.createElement(ne.Z,{isText:!0,onClick:u},i("Login.QR.Cancel")),s&&s!==d&&l&&L.ZP.createElement(ne.Z,{isText:!0,isLoading:f,onClick:p},l)))}))),Pe=(0,L.X$)((0,t.c$)((e=>(0,f.ei)(e,["authState"])))((({authState:e})=>{const{reset:r,initApi:o,returnToAuthPhoneNumber:d,goToAuthQrCode:u}=(0,t.uC)();(0,L.d4)((()=>{r(),o()}),[r,o]);const a="iOS"===n.Lt||"Android"===n.Lt;switch((0,g.ZP)(!a&&"authorizationStateWaitPhoneNumber"===e||a&&"authorizationStateWaitQrCode"===e,(()=>{a?d():u()})),(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 a?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)(G.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"])))((({authState:n})=>{const{disconnect:r}=(0,t.uC)(),[o,d]=(0,x.Z)(!1);if((0,L.d4)((()=>{(0,R.z)(),Z=()=>{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.e8d33405b37130f28896.js.map \ No newline at end of file diff --git a/dist/main.e8d33405b37130f28896.js.map b/dist/main.e8d33405b37130f28896.js.map deleted file mode 100644 index 1df4d1e9..00000000 --- a/dist/main.e8d33405b37130f28896.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"main.e8d33405b37130f28896.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,E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,KAEjCsyE,OAED,CAACF,EAAYE,IAIZD,EACF,OAAO,mBAAC,GAAD,MAGT,GAAIjvD,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,OAAO+uD,KAIb,OAAOzW,EAAAA,EAAAA,KAAiB,GAAQyW,KAAe,mBAAC,GAAD,SC3C7C5rF,EAAAA,IAEFC,QAAQC,IAAI,aAGdqH,EAAAA,EAAAA,MAAcsvB,OAEV72B,EAAAA,IAEFC,QAAQC,IAAI,4BAGd8rF,EAAAA,EAAAA,OACE,mBAAC,GAAD,MACA/iF,SAASm8E,eAAe,SAGtBplF,EAAAA,IAEFC,QAAQC,IAAI,6BAGd+I,SAAS5I,iBAAiB,YAAY,KAEpCJ,QAAQsC,KAAK,gBAAgB+xB,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/GroupCallLink.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/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/modules/selectors/settings.ts","webpack://telegram-t/./src/modules/selectors/users.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/ensureProtocol.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 = {\"87\":1,\"133\":1,\"301\":1,\"472\":1,\"532\":1,\"886\":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 new Error(data.error?.message);\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","import { ApiGroupCall } from './calls';\n\nexport interface ApiDimensions {\n width: number;\n height: number;\n}\n\nexport interface ApiPhotoSize extends ApiDimensions {\n type: 's' | 'm' | 'x' | 'y' | 'z';\n}\n\nexport interface ApiThumbnail extends ApiDimensions {\n dataUri: string;\n}\n\nexport interface ApiPhoto {\n id: string;\n thumbnail?: ApiThumbnail;\n sizes: ApiPhotoSize[];\n blobUrl?: string;\n}\n\nexport interface ApiSticker {\n id: string;\n stickerSetId: string;\n stickerSetAccessHash?: string;\n emoji?: string;\n isAnimated: boolean;\n width?: number;\n height?: number;\n thumbnail?: ApiThumbnail;\n isPreloadedGlobally?: boolean;\n}\n\nexport interface ApiStickerSet {\n archived?: true;\n isAnimated?: true;\n installedDate?: number;\n id: string;\n accessHash: string;\n title: string;\n hasThumbnail?: boolean;\n count: number;\n stickers?: ApiSticker[];\n packs?: Record;\n covers?: ApiSticker[];\n shortName: string;\n}\n\nexport interface ApiVideo {\n id: string;\n mimeType: string;\n duration: number;\n fileName: string;\n width?: number;\n height?: number;\n supportsStreaming?: boolean;\n isRound?: boolean;\n isGif?: boolean;\n thumbnail?: ApiThumbnail;\n blobUrl?: string;\n size: number;\n}\n\nexport interface ApiAudio {\n id: string;\n size: number;\n mimeType: string;\n fileName: string;\n duration: number;\n performer?: string;\n title?: string;\n thumbnailSizes?: ApiPhotoSize[];\n}\n\nexport interface ApiVoice {\n id: string;\n duration: number;\n waveform?: number[];\n}\n\nexport interface ApiDocument {\n id?: string;\n fileName: string;\n size: number;\n timestamp?: number;\n mimeType: string;\n thumbnail?: ApiThumbnail;\n previewBlobUrl?: string;\n mediaType?: 'photo' | 'video';\n mediaSize?: ApiDimensions;\n}\n\nexport interface ApiContact {\n firstName: string;\n lastName: string;\n phoneNumber: string;\n userId: string;\n}\n\nexport interface ApiPollAnswer {\n text: string;\n option: string;\n}\n\nexport interface ApiPollResult {\n isChosen?: true;\n isCorrect?: true;\n option: string;\n votersCount: number;\n}\n\nexport interface ApiPoll {\n id: string;\n summary: {\n closed?: true;\n isPublic?: true;\n multipleChoice?: true;\n quiz?: true;\n question: string;\n answers: ApiPollAnswer[];\n closePeriod?: number;\n closeDate?: number;\n };\n results: {\n results?: ApiPollResult[];\n totalVoters?: number;\n recentVoterIds?: string[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n}\n\nexport interface ApiInvoice {\n text: string;\n title: string;\n photoUrl?: string;\n amount: number;\n currency: string;\n receiptMsgId?: number;\n isTest?: boolean;\n}\n\nexport type ApiNewPoll = {\n summary: ApiPoll['summary'];\n quiz?: {\n correctAnswers: string[];\n solution?: string;\n solutionEntities?: ApiMessageEntity[];\n };\n};\n\nexport interface ApiAction {\n text: string;\n targetUserIds?: string[];\n targetChatId?: string;\n type: 'historyClear' | 'contactSignUp' | 'chatCreate' | 'other';\n photo?: ApiPhoto;\n amount?: number;\n currency?: string;\n translationValues: string[];\n call?: Partial;\n}\n\nexport interface ApiWebPage {\n id: number;\n url: string;\n displayUrl: string;\n type?: string;\n siteName?: string;\n title?: string;\n description?: string;\n photo?: ApiPhoto;\n duration?: number;\n document?: ApiDocument;\n video?: ApiVideo;\n}\n\nexport interface ApiMessageForwardInfo {\n date: number;\n isChannelPost: boolean;\n channelPostId?: number;\n isLinkedChannelPost?: boolean;\n fromChatId?: string;\n senderUserId?: string;\n fromMessageId?: number;\n hiddenUserName?: string;\n adminTitle?: string;\n}\n\nexport interface ApiMessageEntity {\n type: string;\n offset: number;\n length: number;\n userId?: string;\n url?: string;\n}\n\nexport enum ApiMessageEntityTypes {\n Bold = 'MessageEntityBold',\n Blockquote = 'MessageEntityBlockquote',\n BotCommand = 'MessageEntityBotCommand',\n Cashtag = 'MessageEntityCashtag',\n Code = 'MessageEntityCode',\n Email = 'MessageEntityEmail',\n Hashtag = 'MessageEntityHashtag',\n Italic = 'MessageEntityItalic',\n MentionName = 'MessageEntityMentionName',\n Mention = 'MessageEntityMention',\n Phone = 'MessageEntityPhone',\n Pre = 'MessageEntityPre',\n Strike = 'MessageEntityStrike',\n TextUrl = 'MessageEntityTextUrl',\n Url = 'MessageEntityUrl',\n Underline = 'MessageEntityUnderline',\n Unknown = 'MessageEntityUnknown',\n}\n\nexport interface ApiFormattedText {\n text: string;\n entities?: ApiMessageEntity[];\n}\n\nexport interface ApiMessage {\n id: number;\n chatId: string;\n content: {\n text?: ApiFormattedText;\n photo?: ApiPhoto;\n video?: ApiVideo;\n document?: ApiDocument;\n sticker?: ApiSticker;\n contact?: ApiContact;\n poll?: ApiPoll;\n action?: ApiAction;\n webPage?: ApiWebPage;\n audio?: ApiAudio;\n voice?: ApiVoice;\n invoice?: ApiInvoice;\n };\n date: number;\n isOutgoing: boolean;\n senderId?: string;\n replyToChatId?: string;\n replyToMessageId?: number;\n replyToTopMessageId?: number;\n sendingState?: 'messageSendingStatePending' | 'messageSendingStateFailed';\n forwardInfo?: ApiMessageForwardInfo;\n isDeleting?: boolean;\n previousLocalId?: number;\n views?: number;\n isEdited?: boolean;\n editDate?: number;\n isMentioned?: boolean;\n isMediaUnread?: boolean;\n groupedId?: string;\n isInAlbum?: boolean;\n hasUnreadMention?: boolean;\n inlineButtons?: ApiKeyboardButtons;\n keyboardButtons?: ApiKeyboardButtons;\n keyboardPlaceholder?: string;\n isKeyboardSingleUse?: boolean;\n viaBotId?: string;\n threadInfo?: ApiThreadInfo;\n adminTitle?: string;\n isScheduled?: boolean;\n shouldHideKeyboardButtons?: boolean;\n isFromScheduled?: boolean;\n seenByUserIds?: string[];\n isProtected?: boolean;\n}\n\nexport interface ApiThreadInfo {\n threadId: number;\n chatId: string;\n topMessageId?: number;\n originChannelId?: string;\n messagesCount: number;\n lastMessageId?: number;\n lastReadInboxMessageId?: number;\n recentReplierIds?: string[];\n}\n\nexport type ApiMessageOutgoingStatus = 'read' | 'succeeded' | 'pending' | 'failed';\n\nexport type ApiSponsoredMessage = {\n chatId?: string;\n randomId: string;\n isBot?: boolean;\n channelPostId?: number;\n startParam?: string;\n chatInviteHash?: string;\n chatInviteTitle?: string;\n text: ApiFormattedText;\n expiresAt: number;\n};\n\nexport interface ApiKeyboardButton {\n type: 'command' | 'url' | 'callback' | 'requestPoll' | 'requestSelfContact' | 'buy' | 'NOT_SUPPORTED';\n text: string;\n messageId: number;\n value?: string;\n}\n\nexport type ApiKeyboardButtons = ApiKeyboardButton[][];\nexport type ApiReplyKeyboard = {\n keyboardPlaceholder?: string;\n isKeyboardSingleUse?: boolean;\n} & {\n [K in 'inlineButtons' | 'keyboardButtons']?: ApiKeyboardButtons;\n};\n\nexport type ApiMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'voice' | 'profilePhoto';\nexport type ApiGlobalMessageSearchType = 'text' | 'media' | 'documents' | 'links' | 'audio' | 'voice';\n\nexport type ApiReportReason = 'spam' | 'violence' | 'pornography' | 'childAbuse'\n| 'copyright' | 'geoIrrelevant' | 'fake' | 'other';\n\nexport type ApiSendMessageAction = {\n type: 'cancel' | 'typing' | 'recordAudio' | 'chooseSticker';\n};\n\nexport const MAIN_THREAD_ID = -1;\n\n// `Symbol` can not be transferred from worker\nexport const MESSAGE_DELETED = 'MESSAGE_DELETED';\n","/* 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';\nimport { ensureProtocol } from '../../util/ensureProtocol';\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 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';\n\nimport { ApiChat, ApiUser } from '../../api/types';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport Link from '../ui/Link';\nimport { getDispatch } from '../../lib/teact/teactn';\n\ntype OwnProps = {\n className?: string;\n sender?: ApiUser | ApiChat;\n children: any;\n};\n\nconst UserLink: FC = ({\n className, sender, children,\n}) => {\n const { openUserInfo } = getDispatch();\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 UserLink;\n","import React, { FC, useCallback } from '../../lib/teact/teact';\nimport { getDispatch } from '../../lib/teact/teactn';\n\nimport { ApiMessage } from '../../api/types';\n\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\nconst MessageLink: FC = ({\n className, message, children,\n}) => {\n const { focusMessage } = getDispatch();\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 MessageLink;\n","import React, { FC, useCallback } from '../../lib/teact/teact';\nimport { getDispatch } from '../../lib/teact/teactn';\n\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\nconst ChatLink: FC = ({\n className, chatId, children,\n}) => {\n const { openChat } = getDispatch();\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 ChatLink;\n","import React, { FC, useCallback } from '../../lib/teact/teact';\n\nimport { ApiGroupCall } from '../../api/types';\n\nimport buildClassName from '../../util/buildClassName';\n\nimport Link from '../ui/Link';\nimport { getDispatch } from '../../lib/teact/teactn';\n\ntype OwnProps = {\n className?: string;\n groupCall?: Partial;\n children: any;\n};\n\nconst GroupCallLink: FC = ({\n className, groupCall, children,\n}) => {\n const { joinGroupCall } = getDispatch();\n\n const handleClick = useCallback(() => {\n if (groupCall) {\n joinGroupCall({ id: groupCall.id, accessHash: groupCall.accessHash });\n }\n }, [groupCall, joinGroupCall]);\n\n if (!groupCall) {\n return children;\n }\n\n return (\n {children}\n );\n};\n\nexport default GroupCallLink;\n","import React from '../../../lib/teact/teact';\n\nimport {\n ApiChat, ApiMessage, ApiUser, ApiGroupCall,\n} 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';\nimport GroupCallLink from '../GroupCallLink';\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, call,\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 if (call) {\n return renderGroupCallContent(call, content);\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 renderGroupCallContent(groupCall: Partial, text: TextPart[]): string | TextPart | undefined {\n return (\n \n {text}\n \n );\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 result.push(part);\n return result;\n }\n\n divEl.innerText = part;\n result.push(divEl.innerHTML);\n\n return result;\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 result.push(part);\n return result;\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: TextPart[], part) => {\n if (typeof part !== 'string') {\n result.push(part);\n return result;\n }\n\n const splittenParts = 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\n return [...result, ...splittenParts];\n }, []);\n}\n\nfunction addHighlight(textParts: TextPart[], highlight: string | undefined): TextPart[] {\n return textParts.reduce((result, part) => {\n if (typeof part !== 'string' || !highlight) {\n result.push(part);\n return result;\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 result.push(part);\n return result;\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 result.push(part);\n return result;\n }\n\n const links = part.match(RE_LINK);\n if (!links || !links.length) {\n result.push(part);\n return result;\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 result.push(part);\n return result;\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 { getDispatch, withGlobal } from '../../../lib/teact/teactn';\n\nimport { ApiChat, ApiUser } from '../../../api/types';\n\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\nconst MentionLink: FC = ({\n username,\n userOrChat,\n children,\n}) => {\n const {\n openChat,\n openChatByUsername,\n } = getDispatch();\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)(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-v7';\nexport const ASSET_CACHE_NAME = 'tt-assets';\nexport const AUTODOWNLOAD_FILESIZE_MB_LIMITS = [1, 5, 10, 50, 100, 500];\n\nexport const DOWNLOAD_WORKERS = 16;\nexport const UPLOAD_WORKERS = 16;\n\nconst isBigScreen = typeof window !== 'undefined' && window.innerHeight >= 900;\n\nexport const MIN_PASSWORD_LENGTH = 1;\n\nexport const MESSAGE_LIST_SLICE = isBigScreen ? 60 : 40;\nexport const MESSAGE_LIST_VIEWPORT_LIMIT = MESSAGE_LIST_SLICE * 2;\n\nexport const CHAT_HEIGHT_PX = 72;\nexport const CHAT_LIST_SLICE = isBigScreen ? 30 : 25;\nexport const CHAT_LIST_LOAD_SLICE = 100;\nexport const SHARED_MEDIA_SLICE = 42;\nexport const MESSAGE_SEARCH_SLICE = 42;\nexport const GLOBAL_SEARCH_SLICE = 20;\nexport const MEMBERS_SLICE = 30;\nexport const MEMBERS_LOAD_SLICE = 200;\nexport const PINNED_MESSAGES_LIMIT = 50;\nexport const BLOCKED_LIST_LIMIT = 100;\nexport const PROFILE_PHOTOS_LIMIT = 40;\nexport const PROFILE_SENSITIVE_AREA = 500;\nexport const COMMON_CHATS_LIMIT = 100;\nexport const GROUP_CALL_PARTICIPANTS_LIMIT = 100;\n\nexport const TOP_CHAT_MESSAGES_PRELOAD_LIMIT = 20;\nexport const ALL_CHATS_PRELOAD_DISABLED = false;\n\nexport const SPONSORED_MESSAGE_CACHE_MS = 300000; // 5 min\n\nexport const DEFAULT_VOLUME = 1;\nexport const DEFAULT_PLAYBACK_RATE = 1;\n\nexport const ANIMATION_LEVEL_MIN = 0;\nexport const ANIMATION_LEVEL_MED = 1;\nexport const ANIMATION_LEVEL_MAX = 2;\nexport const ANIMATION_LEVEL_DEFAULT = ANIMATION_LEVEL_MAX;\n\nexport const DEFAULT_MESSAGE_TEXT_SIZE_PX = 16;\nexport const IOS_DEFAULT_MESSAGE_TEXT_SIZE_PX = 17;\nexport const MACOS_DEFAULT_MESSAGE_TEXT_SIZE_PX = 15;\n\nexport const DRAFT_DEBOUNCE = 10000; // 10s\nexport const SEND_MESSAGE_ACTION_INTERVAL = 3000; // 3s\n\nexport const EDITABLE_INPUT_ID = 'editable-message-text';\nexport const EDITABLE_INPUT_MODAL_ID = 'editable-message-text-modal';\n\n// Screen width where Pinned Message / Audio Player in the Middle Header can be safely displayed\nexport const SAFE_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1440; // px\n// Screen width where Pinned Message / Audio Player in the Middle Header shouldn't collapse with ChatInfo\nexport const SAFE_SCREEN_WIDTH_FOR_CHAT_INFO = 1150; // px\n\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_RIGHT_COLUMN = 1275; // px\nexport const MIN_SCREEN_WIDTH_FOR_STATIC_LEFT_COLUMN = 925; // px\nexport const MOBILE_SCREEN_MAX_WIDTH = 600; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_WIDTH = 950; // px\nexport const MOBILE_SCREEN_LANDSCAPE_MAX_HEIGHT = 450; // px\n\nexport const LOCAL_MESSAGE_ID_BASE = 1e9;\nexport const TMP_CHAT_ID = '0';\n\nexport const ANIMATION_END_DELAY = 100;\n\nexport const FAST_SMOOTH_MAX_DISTANCE = 1500;\nexport const FAST_SMOOTH_MIN_DURATION = 250;\nexport const FAST_SMOOTH_MAX_DURATION = 600;\nexport const FAST_SMOOTH_SHORT_TRANSITION_MAX_DISTANCE = 500; // px\n\n// Average duration of message sending animation\nexport const API_UPDATE_THROTTLE = Math.round((FAST_SMOOTH_MIN_DURATION + FAST_SMOOTH_MAX_DURATION) / 2);\nexport const API_THROTTLE_RESET_UPDATES = new Set([\n 'newMessage', 'newScheduledMessage', 'deleteMessages', 'deleteScheduledMessages', 'deleteHistory',\n]);\n\nexport const STICKER_SIZE_INLINE_DESKTOP_FACTOR = 13;\nexport const STICKER_SIZE_INLINE_MOBILE_FACTOR = 11;\nexport const STICKER_SIZE_AUTH = 160;\nexport const STICKER_SIZE_AUTH_MOBILE = 120;\nexport const STICKER_SIZE_PICKER = 64;\nexport const STICKER_SIZE_GENERAL_SETTINGS = 48;\nexport const STICKER_SIZE_PICKER_HEADER = 32;\nexport const STICKER_SIZE_SEARCH = 64;\nexport const STICKER_SIZE_MODAL = 64;\nexport const STICKER_SIZE_TWO_FA = 160;\nexport const STICKER_SIZE_DISCUSSION_GROUPS = 140;\nexport const STICKER_SIZE_FOLDER_SETTINGS = 80;\nexport const STICKER_SIZE_INLINE_BOT_RESULT = 100;\nexport const RECENT_STICKERS_LIMIT = 20;\nexport const MEMOJI_STICKER_ID = 'MEMOJI_STICKER';\n\nexport const BASE_EMOJI_KEYWORD_LANG = 'en';\n\nexport const MENU_TRANSITION_DURATION = 200;\nexport const SLIDE_TRANSITION_DURATION = 450;\n\nexport const VIDEO_MOV_TYPE = 'video/quicktime';\n\nexport const SUPPORTED_IMAGE_CONTENT_TYPES = new Set([\n 'image/png', 'image/gif', 'image/jpeg',\n]);\n\nexport const SUPPORTED_VIDEO_CONTENT_TYPES = new Set([\n 'video/mp4', // video/quicktime added dynamically in environment.ts\n]);\n\nexport const CONTENT_TYPES_WITH_PREVIEW = new Set([\n ...SUPPORTED_IMAGE_CONTENT_TYPES,\n ...SUPPORTED_VIDEO_CONTENT_TYPES,\n]);\n\nexport const CONTENT_NOT_SUPPORTED = 'The message is not supported on this version of Telegram.';\n\n// eslint-disable-next-line max-len\nexport const RE_LINK_TEMPLATE = '((ftp|https?):\\\\/\\\\/)?((www\\\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\\\.[a-zA-Z0-9()]{1,63})\\\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)';\nexport const RE_MENTION_TEMPLATE = '(@[\\\\w\\\\d_-]+)';\nexport const RE_TG_LINK = /^tg:(\\/\\/)?([?=&\\d\\w_-]+)?/gm;\nexport const RE_TME_LINK = /^(?:https?:\\/\\/)?(?:t\\.me\\/)/gm;\n\n// eslint-disable-next-line max-len\nexport const COUNTRIES_WITH_12H_TIME_FORMAT = new Set(['AU', 'BD', 'CA', 'CO', 'EG', 'HN', 'IE', 'IN', 'JO', 'MX', 'MY', 'NI', 'NZ', 'PH', 'PK', 'SA', 'SV', 'US']);\n\n// MTProto constants\nexport const SERVICE_NOTIFICATIONS_USER_ID = '777000';\nexport const REPLIES_USER_ID = '1271266957'; // TODO For Test connection ID must be equal to 708513\nexport const ALL_FOLDER_ID = 0;\nexport const ARCHIVED_FOLDER_ID = 1;\nexport const DELETED_COMMENTS_CHANNEL_ID = '-777';\nexport const MAX_MEDIA_FILES_FOR_ALBUM = 10;\nexport const MAX_ACTIVE_PINNED_CHATS = 5;\nexport const SCHEDULED_WHEN_ONLINE = 0x7FFFFFFE;\nexport const DEFAULT_LANG_CODE = 'en';\nexport const DEFAULT_LANG_PACK = 'android';\nexport const LANG_PACKS = ['android', 'ios', 'tdesktop', 'macos'] as const;\nexport const TIPS_USERNAME = 'TelegramTips';\nexport const LOCALIZED_TIPS = ['ar', 'pt-br', 'id', 'it', 'ko', 'ms', 'pl', 'es', 'tr'];\nexport const FEEDBACK_URL = 'https://bugs.telegram.org/?tag_ids=41&sort=time';\nexport const LIGHT_THEME_BG_COLOR = '#A2AF8E';\nexport const DARK_THEME_BG_COLOR = '#0F0F0F';\nexport const DARK_THEME_PATTERN_COLOR = '#0a0a0a8c';\nexport const DEFAULT_PATTERN_COLOR = 'rgba(90, 110, 70, 0.6)';\n// TODO Get values from `getConfig` method once it's available\nexport const SEEN_BY_MEMBERS_CHAT_MAX = 50;\nexport const SEEN_BY_MEMBERS_EXPIRE = 604680; // One week - 2 min\n\n// Group calls\nexport const GROUP_CALL_VOLUME_MULTIPLIER = 100;\nexport const GROUP_CALL_DEFAULT_VOLUME = 100 * GROUP_CALL_VOLUME_MULTIPLIER;\nexport const ENABLE_THUMBNAIL_VIDEO = false;\n","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\nconst ANIMATION_START_EVENT = 'tt-event-heavy-animation-start';\nconst ANIMATION_END_EVENT = 'tt-event-heavy-animation-end';\n\nlet timeout: number | undefined;\nlet isAnimating = false;\n\n// Make sure to end even if end callback was not called (which was some hardly-reproducible bug)\nconst AUTO_END_TIMEOUT = 1000;\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\nexport function isHeavyAnimating() {\n return isAnimating;\n}\n\nexport function dispatchHeavyAnimationEvent(duration = AUTO_END_TIMEOUT) {\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 // Race condition may happen if another `dispatchHeavyAnimationEvent` is called before `onEnd`\n function onEnd() {\n if (timeout) {\n clearTimeout(timeout);\n timeout = undefined;\n }\n\n isAnimating = false;\n document.dispatchEvent(new Event(ANIMATION_END_EVENT));\n }\n\n timeout = window.setTimeout(onEnd, duration);\n\n return onEnd;\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;\ntype DelegationRegistry = Map;\n\nconst NON_BUBBLEABLE_EVENTS = new Set(['scroll', 'mouseenter', 'mouseleave']);\n\nconst documentEventCounters: Record = {};\nconst delegationRegistryByEventType: Record = {};\nconst delegatedEventTypesByElement = new Map>();\n\nexport function addEventListener(element: HTMLElement, propName: string, handler: Handler, asCapture = false) {\n const eventType = resolveEventType(propName, element);\n if (canUseEventDelegation(eventType, element, asCapture)) {\n addDelegatedListener(eventType, element, handler);\n } else {\n element.addEventListener(eventType, handler, asCapture);\n }\n}\n\nexport function removeEventListener(element: HTMLElement, propName: string, handler: Handler, asCapture = false) {\n const eventType = resolveEventType(propName, element);\n if (canUseEventDelegation(eventType, element, asCapture)) {\n removeDelegatedListener(eventType, element);\n } else {\n element.removeEventListener(eventType, handler, asCapture);\n }\n}\n\nfunction resolveEventType(propName: string, element: HTMLElement) {\n const eventType = propName\n .replace(/^on/, '')\n .replace(/Capture$/, '').toLowerCase();\n\n if (eventType === '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 (eventType === 'doubleclick') {\n return 'dblclick';\n }\n\n // Replace focus/blur by their \"bubbleable\" versions\n if (eventType === 'focus') {\n return 'focusin';\n }\n\n if (eventType === 'blur') {\n return 'focusout';\n }\n\n return eventType;\n}\n\nfunction canUseEventDelegation(realEventType: string, element: HTMLElement, asCapture: boolean) {\n return (\n !asCapture\n && !NON_BUBBLEABLE_EVENTS.has(realEventType)\n && element.tagName !== 'VIDEO'\n && element.tagName !== 'IFRAME'\n );\n}\n\nfunction addDelegatedListener(eventType: string, element: HTMLElement, handler: Handler) {\n if (!documentEventCounters[eventType]) {\n documentEventCounters[eventType] = 0;\n document.addEventListener(eventType, handleEvent);\n }\n\n resolveDelegationRegistry(eventType).set(element, handler);\n resolveDelegatedEventTypes(element).add(eventType);\n documentEventCounters[eventType]++;\n}\n\nfunction removeDelegatedListener(eventType: string, element: HTMLElement) {\n documentEventCounters[eventType]--;\n if (!documentEventCounters[eventType]) {\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(eventType, handleEvent);\n }\n\n delegationRegistryByEventType[eventType].delete(element);\n delegatedEventTypesByElement.get(element)!.delete(eventType);\n}\n\nexport function removeAllDelegatedListeners(element: HTMLElement) {\n const eventTypes = delegatedEventTypesByElement.get(element);\n if (!eventTypes) {\n return;\n }\n\n eventTypes.forEach((eventType) => removeDelegatedListener(eventType, element));\n delegatedEventTypesByElement.delete(element);\n}\n\nfunction handleEvent(realEvent: Event) {\n const events = delegationRegistryByEventType[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 resolveDelegationRegistry(eventType: string) {\n if (!delegationRegistryByEventType[eventType]) {\n delegationRegistryByEventType[eventType] = new Map();\n }\n\n return delegationRegistryByEventType[eventType];\n}\n\nfunction resolveDelegatedEventTypes(element: HTMLElement) {\n const existing = delegatedEventTypesByElement.get(element);\n if (existing) {\n return existing;\n }\n\n const newSet = new Set();\n delegatedEventTypesByElement.set(element, newSet);\n\n return newSet;\n}\n\nif (DEBUG) {\n document.addEventListener('dblclick', () => {\n const documentListenersCount = Object.keys(documentEventCounters).length;\n const delegatedHandlersCount1 = Object.values(documentEventCounters)\n .reduce((acc, counter) => acc + counter, 0);\n const delegationRegistriesCount = Object.keys(delegationRegistryByEventType).length;\n const delegatedHandlersCount2 = Object.values(delegationRegistryByEventType)\n .reduce((acc, delegationRegistry) => acc + delegationRegistry.size, 0);\n const delegationElementsCount = delegatedEventTypesByElement.size;\n const delegatedEventTypesCount = Array.from(delegatedEventTypesByElement.values())\n .reduce((acc, eventTypes) => acc + eventTypes.size, 0);\n\n // eslint-disable-next-line no-console\n console.warn('DELEGATED EVENTS STATS', {\n delegatedHandlersCount1,\n delegatedHandlersCount2,\n delegatedEventTypesCount,\n delegationRegistriesCount,\n delegationElementsCount,\n documentListenersCount,\n });\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', 'role']);\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 if (props[key] !== undefined) {\n setAttribute(element, key, props[key]);\n }\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 // eslint-disable-next-line no-null/no-null\n if (DEBUG && isRealElement($newChild) && (key === undefined || key === null)) {\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 // eslint-disable-next-line no-null/no-null\n const isKeyPresent = key !== undefined && key !== null;\n\n // First we handle removed children\n if (isKeyPresent && !newKeys.has(key)) {\n renderWithVirtual(currentEl, $currentChild, undefined, $new, -1);\n\n return acc;\n } else if (!isKeyPresent) {\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 const currentValue = $current.props[key];\n const newValue = $new.props[key];\n\n if (\n currentValue !== undefined\n && (\n newValue === undefined\n || (currentValue !== newValue && key.startsWith('on'))\n )\n ) {\n removeAttribute(element, key, currentValue);\n }\n });\n\n newKeys.forEach((key) => {\n const currentValue = $current.props[key];\n const newValue = $new.props[key];\n\n if (newValue !== undefined && newValue !== currentValue) {\n setAttribute(element, key, newValue);\n }\n });\n}\n\nfunction setAttribute(element: HTMLElement, key: string, value: any) {\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 === 'dangerouslySetInnerHTML') {\n // eslint-disable-next-line no-underscore-dangle\n element.innerHTML = value.__html;\n } else if (key.startsWith('on')) {\n addEventListener(element, key, value, key.endsWith('Capture'));\n } else if (key.startsWith('data-') || key.startsWith('aria-') || 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 === 'dangerouslySetInnerHTML') {\n element.innerHTML = '';\n } else if (key.startsWith('on')) {\n removeEventListener(element, key, value, key.endsWith('Capture'));\n } else if (key.startsWith('data-') || key.startsWith('aria-') || 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\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\nconst DEBUG_RENDER_THRESHOLD = 7;\nconst DEBUG_EFFECT_THRESHOLD = 7;\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.warn('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 duration = performance.now() - DEBUG_startAt!;\n const componentName = componentInstance.name;\n if (duration > DEBUG_RENDER_THRESHOLD) {\n // eslint-disable-next-line no-console\n console.warn(`[Teact] Slow component render: ${componentName}, ${Math.round(duration)} ms`);\n }\n DEBUG_components[componentName].renderTimes.push(duration);\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 // 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 cleanup();\n\n if (DEBUG) {\n const duration = performance.now() - DEBUG_startAt!;\n const componentName = componentInstance.name;\n if (duration > DEBUG_EFFECT_THRESHOLD) {\n // eslint-disable-next-line no-console\n console.warn(\n `[Teact] Slow cleanup at effect cursor #${cursor}: ${componentName}, ${Math.round(duration)} ms`,\n );\n }\n }\n } catch (err) {\n handleError(err);\n }\n }\n }\n\n function exec() {\n if (!componentInstance.isMounted) {\n return;\n }\n\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 byCursor[cursor].cleanup = effect() as Function;\n\n if (DEBUG) {\n const duration = performance.now() - DEBUG_startAt!;\n const componentName = componentInstance.name;\n if (duration > DEBUG_EFFECT_THRESHOLD) {\n // eslint-disable-next-line no-console\n console.warn(`[Teact] Slow effect at cursor #${cursor}: ${componentName}, ${Math.round(duration)} ms`);\n }\n }\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(`[Teact] Effect \"${debugKey}\" caused by dependencies.`, causedBy.join(', '));\n }\n\n primarySchedulerFn(execCleanup);\n schedulerFn(exec);\n }\n } else {\n if (debugKey) {\n // eslint-disable-next-line no-console\n console.log(`[Teact] Effect \"${debugKey}\" caused by missing dependencies.`);\n }\n\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[], debugKey?: string): F {\n // eslint-disable-next-line react-hooks/exhaustive-deps\n return useMemo(() => newCallback, dependencies, debugKey);\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 { fastRaf, throttleWithTickEnd } from '../../util/schedulers';\nimport arePropsShallowEqual, { getUnequalProps } from '../../util/arePropsShallowEqual';\nimport { orderBy } from '../../util/iteratees';\nimport {\n GlobalState, GlobalActions, ActionTypes, DispatchOptions,\n} from '../../global/types';\nimport { handleError } from '../../util/handleError';\nimport { isHeavyAnimating } from '../../hooks/useHeavyAnimationCheck';\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);\n\nlet currentGlobal = {} as GlobalState;\n\nconst reducers: Record = {};\nconst callbacks: Function[] = [updateContainers];\nconst actions = {} as GlobalActions;\nconst containers = new Map;\n ownProps: Props;\n mappedProps?: Props;\n forceUpdate: Function;\n areMappedPropsChanged: boolean;\n DEBUG_updates: number;\n DEBUG_componentName: string;\n}>();\n\nconst runCallbacksThrottled = throttleWithTickEnd(runCallbacks);\n\nfunction runCallbacks(forceOnHeavyAnimation = false) {\n if (!forceOnHeavyAnimation && isHeavyAnimating()) {\n fastRaf(runCallbacksThrottled);\n return;\n }\n\n callbacks.forEach((cb) => cb(currentGlobal));\n}\n\nexport function setGlobal(newGlobal?: GlobalState, options?: DispatchOptions) {\n if (typeof newGlobal === 'object' && newGlobal !== currentGlobal) {\n currentGlobal = newGlobal;\n if (options?.forceSyncOnIOs) {\n runCallbacks(true);\n } else {\n runCallbacksThrottled(options?.forceOnHeavyAnimation);\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, options?: DispatchOptions) {\n if (reducers[name]) {\n reducers[name].forEach((reducer) => {\n const newGlobal = reducer(currentGlobal, actions, payload);\n if (newGlobal) {\n setGlobal(newGlobal, options);\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, ownProps, mappedProps, forceUpdate,\n } = container;\n\n let newMappedProps;\n\n try {\n newMappedProps = mapStateToProps(currentGlobal, ownProps);\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, options?: DispatchOptions) => {\n onDispatch(name, payload, options);\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) {\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 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 = mapStateToProps(currentGlobal, props);\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.warn(\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 });\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_SAFARI, 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 if (IS_SAFARI) {\n document.body.classList.add('is-safari');\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 }, { forceSyncOnIOs: 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 { GlobalState } from '../../global/types';\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';\nimport { prepareSearchWordsForNeedle } from '../../util/searchWords';\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(chat.joinDate || 0, chat.draftDate || 0, chat.lastMessage?.date || 0);\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 allListIds: GlobalState['chats']['listIds'],\n chatsById: Record,\n usersById: Record,\n folder: ApiChatFolder,\n notifySettings: NotifySettings,\n notifyExceptions?: Record,\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 = ([] as string[]).concat(allListIds.active || [], allListIds.archived || [])\n .filter((id) => {\n const chat = chatsById[id];\n return chat && filterChatFolder(\n chat,\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\n// This function is the most expensive in the project, so any possible optimizations are welcome\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 const { id: chatId, type, unreadMentionsCount } = chat;\n\n if (excludedChatIds?.has(chatId)) {\n return false;\n }\n\n if (includedChatIds?.has(chatId)) {\n return true;\n }\n\n if (pinnedChatIds?.has(chatId)) {\n return true;\n }\n\n if (folder.excludeArchived && chat.folderId === ARCHIVED_FOLDER_ID) {\n return false;\n }\n\n if (folder.excludeRead && !chat.unreadCount && !unreadMentionsCount && !chat.hasUnreadMark) {\n return false;\n }\n\n if (folder.excludeMuted && !unreadMentionsCount && selectIsChatMuted(chat, notifySettings, notifyExceptions)) {\n return false;\n }\n\n if (type === 'chatTypePrivate') {\n const user = usersById[chatId];\n if (user) {\n const { type: userType, isContact } = user;\n\n if (userType === 'userTypeBot') {\n if (folder.bots) {\n return true;\n }\n } else {\n if (folder.contacts && isContact) {\n return true;\n }\n\n if (folder.nonContacts && !isContact) {\n return true;\n }\n }\n }\n } else if (type === 'chatTypeChannel') {\n return !!folder.channels;\n } else if (type === 'chatTypeBasicGroup' || type === 'chatTypeSuperGroup') {\n return !!folder.groups;\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 noOrder = false,\n) {\n const listIdsSet = new Set(listIds);\n const orderedPinnedIdsSet = orderedPinnedIds ? new Set(orderedPinnedIds) : undefined;\n\n const pinnedChats = orderedPinnedIds?.reduce((acc, id) => {\n const chat = chatsById[id];\n\n if (chat && listIdsSet.has(chat.id) && checkChat(chat, folderType)) {\n acc.push(chat);\n }\n\n return acc;\n }, [] as ApiChat[]) || [];\n\n const otherChats = listIds.reduce((acc, id) => {\n const chat = chatsById[id];\n\n if (chat && (!orderedPinnedIdsSet || !orderedPinnedIdsSet.has(chat.id)) && checkChat(chat, folderType)) {\n acc.push(chat);\n }\n\n return acc;\n }, [] as ApiChat[]);\n\n return {\n pinnedChats,\n otherChats: noOrder ? otherChats : orderBy(otherChats, getChatOrder, 'desc'),\n };\n}\n\nfunction checkChat(chat: ApiChat, folderType: 'all' | 'archived' | 'folder') {\n return (\n chat.lastMessage && !chat.migratedTo && !chat.isRestricted && !chat.isNotJoined\n && !(folderType === 'all' && chat.folderId === ARCHIVED_FOLDER_ID)\n && !(folderType === 'archived' && chat.folderId !== ARCHIVED_FOLDER_ID)\n );\n}\n\nexport function reduceChatList(\n chatArrays: { pinnedChats: ApiChat[]; otherChats: ApiChat[] },\n filteredIds: string[],\n) {\n const filteredIdsSet = new Set(filteredIds);\n\n return {\n pinnedChats: chatArrays.pinnedChats.filter(({ id }) => filteredIdsSet.has(id)),\n otherChats: chatArrays.otherChats.filter(({ id }) => filteredIdsSet.has(id)),\n };\n}\n\nexport function getFolderUnreadDialogs(\n allListIds: GlobalState['chats']['listIds'],\n chatsById: Record,\n usersById: Record,\n folder: ApiChatFolder,\n notifySettings: NotifySettings,\n notifyExceptions?: Record,\n) {\n const [listIds] = prepareFolderListIds(allListIds, chatsById, usersById, folder, notifySettings, notifyExceptions);\n\n let hasActiveDialogs = false;\n const unreadDialogsCount = listIds.reduce((acc, id) => {\n const chat = chatsById[id];\n if (!chat?.lastMessage || chat?.isRestricted || chat?.isNotJoined) {\n return acc;\n }\n\n const isUnread = chat.unreadCount || chat.hasUnreadMark;\n\n if (isUnread) {\n acc++;\n }\n\n if (!hasActiveDialogs && (\n chat.unreadMentionsCount || (isUnread && !selectIsChatMuted(chat, notifySettings, notifyExceptions))\n )) {\n hasActiveDialogs = true;\n }\n\n return acc;\n }, 0);\n\n return {\n unreadDialogsCount,\n hasActiveDialogs,\n };\n}\n\nexport function getFolderDescriptionText(\n lang: LangFn,\n allListIds: GlobalState['chats']['listIds'],\n chatsById: Record,\n usersById: Record,\n folder: ApiChatFolder,\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(allListIds, chatsById, usersById, folder, 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 allListIds: GlobalState['chats']['listIds'],\n chatsById: Record,\n usersById: Record,\n folder: ApiChatFolder,\n notifySettings: NotifySettings,\n notifyExceptions?: Record,\n) {\n const [listIds, pinnedIds] = prepareFolderListIds(\n allListIds, chatsById, usersById, folder, notifySettings, notifyExceptions,\n );\n const { pinnedChats, otherChats } = prepareChatList(chatsById, listIds, pinnedIds, 'folder', true);\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\nexport function filterChatsByName(\n lang: LangFn,\n chatIds: string[],\n chatsById: Record,\n query?: string,\n currentUserId?: string,\n) {\n if (!query) {\n return chatIds;\n }\n\n const searchWords = prepareSearchWordsForNeedle(query);\n\n return chatIds.filter((id) => {\n const chat = chatsById[id];\n if (!chat) {\n return false;\n }\n\n return searchWords(getChatTitle(lang, chat, undefined, id === currentUserId));\n });\n}\n","import {\n ApiChat, ApiMessage, ApiMessageEntityTypes, ApiUser,\n} from '../../api/types';\nimport { LangFn } from '../../hooks/useLang';\n\nimport {\n LOCAL_MESSAGE_ID_BASE,\n SERVICE_NOTIFICATIONS_USER_ID,\n RE_LINK_TEMPLATE,\n CONTENT_NOT_SUPPORTED,\n} 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 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 mediaId = (messagePhoto || messageVideo || sticker || audio || voice || document)!.id;\n const base = `${getMessageKey(message)}${mediaId ? `:${mediaId}` : ''}`;\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, ApiUserStatus } 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';\nimport { prepareSearchWordsForNeedle } from '../../util/searchWords';\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(\n lang: LangFn, user: ApiUser, userStatus: ApiUserStatus | undefined, serverTimeOffset: number,\n) {\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 (!userStatus) {\n return '';\n }\n\n switch (userStatus.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 } = userStatus;\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, userStatus?: ApiUserStatus) {\n const { id, type } = user;\n\n if (!userStatus) {\n return false;\n }\n\n if (id === SERVICE_NOTIFICATIONS_USER_ID) {\n return false;\n }\n\n return userStatus.type === 'userStatusOnline' && type !== 'userTypeBot';\n}\n\nexport function isDeletedUser(user: ApiUser) {\n if (user.noStatus || 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 userStatusesById: 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 const userStatus = userStatusesById[id];\n if (!user || !userStatus) {\n return 0;\n }\n\n if (userStatus.type === 'userStatusOnline') {\n return userStatus.expires;\n } else if (userStatus.type === 'userStatusOffline' && userStatus.wasOnline) {\n return userStatus.wasOnline;\n }\n\n switch (userStatus.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 filterUsersByName(userIds: string[], usersById: Record, query?: string) {\n if (!query) {\n return userIds;\n }\n\n const searchWords = prepareSearchWordsForNeedle(query);\n\n return userIds.filter((id) => {\n const user = usersById[id];\n if (!user) {\n return false;\n }\n\n const name = getUserFullName(user);\n return (name && searchWords(name)) || searchWords(user.username);\n });\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\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 if (!updatedChat) {\n return global;\n }\n\n return replaceChats(global, {\n ...byId,\n [chatId]: updatedChat,\n });\n}\n\nexport function updateChats(global: GlobalState, newById: Record): GlobalState {\n const updatedById = Object.keys(newById).reduce((acc: Record, id) => {\n const updatedChat = getUpdatedChat(global, id, newById[id]);\n if (updatedChat) {\n acc[id] = updatedChat;\n }\n\n return acc;\n }, {});\n\n global = replaceChats(global, {\n ...global.chats.byId,\n ...updatedById,\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, newById: Record): GlobalState {\n const { byId } = global.chats;\n let isUpdated = false;\n\n const addedById = Object.keys(newById).reduce>((acc, id) => {\n if (!byId[id] || (byId[id].isMin && !newById[id].isMin)) {\n const updatedChat = getUpdatedChat(global, id, newById[id]);\n if (updatedChat) {\n acc[id] = updatedChat;\n if (!isUpdated) {\n isUpdated = true;\n }\n }\n }\n return acc;\n }, {});\n\n if (!isUpdated) {\n return global;\n }\n\n global = replaceChats(global, {\n ...byId,\n ...addedById,\n });\n\n return global;\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) {\n const { byId } = global.chats;\n const chat = byId[chatId];\n const shouldOmitMinInfo = chatUpdate.isMin && chat && !chat.isMin;\n const updatedChat: ApiChat = {\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 undefined;\n }\n\n return updatedChat;\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 {\n ApiMessage, ApiSponsoredMessage, ApiThreadInfo, MAIN_THREAD_ID,\n} 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 updateSponsoredMessage(\n global: GlobalState, chatId: string, message: ApiSponsoredMessage,\n): GlobalState {\n return {\n ...global,\n messages: {\n ...global.messages,\n sponsoredByChatId: {\n ...global.messages.sponsoredByChatId,\n [chatId]: message,\n },\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, ApiUserStatus } from '../../api/types';\n\nimport { omit, pick } 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\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 if (!updatedUser) {\n return global;\n }\n\n global = updateContactList(global, [updatedUser]);\n\n return replaceUsers(global, {\n ...byId,\n [userId]: updatedUser,\n });\n}\n\nexport function updateUsers(global: GlobalState, newById: Record): GlobalState {\n const updatedById = Object.keys(newById).reduce((acc: Record, id) => {\n const updatedUser = getUpdatedUser(global, id, newById[id]);\n if (updatedUser) {\n acc[id] = updatedUser;\n }\n\n return acc;\n }, {});\n\n global = replaceUsers(global, {\n ...global.users.byId,\n ...updatedById,\n });\n\n global = updateContactList(global, Object.values(updatedById));\n\n return global;\n}\n\n// @optimization Allows to avoid redundant updates which cause a lot of renders\nexport function addUsers(global: GlobalState, newById: Record): GlobalState {\n const { byId } = global.users;\n let isUpdated = false;\n\n const addedById = Object.keys(newById).reduce>((acc, id) => {\n if (!byId[id] || (byId[id].isMin && !newById[id].isMin)) {\n const updatedUser = getUpdatedUser(global, id, newById[id]);\n if (updatedUser) {\n acc[id] = updatedUser;\n if (!isUpdated) {\n isUpdated = true;\n }\n }\n }\n return acc;\n }, {});\n\n if (!isUpdated) {\n return global;\n }\n\n global = replaceUsers(global, {\n ...byId,\n ...addedById,\n });\n\n global = updateContactList(global, Object.values(addedById));\n\n return global;\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) {\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 undefined;\n }\n\n return updatedUser;\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 deleteContact(global: GlobalState, userId: string): GlobalState {\n const { byId } = global.users;\n const { userIds } = global.contactList || {};\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, {\n ...byId,\n [userId]: {\n ...byId[userId],\n isContact: undefined,\n },\n });\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\nexport function replaceUserStatuses(global: GlobalState, newById: Record): GlobalState {\n return {\n ...global,\n users: {\n ...global.users,\n statusesById: newById,\n },\n };\n}\n\n// @optimization Allows to avoid redundant updates which cause a lot of renders\nexport function addUserStatuses(global: GlobalState, newById: Record): GlobalState {\n const { statusesById } = global.users;\n\n const newKeys = Object.keys(newById).filter((id) => !statusesById[id]);\n if (!newKeys.length) {\n return global;\n }\n\n global = replaceUserStatuses(global, {\n ...statusesById,\n ...pick(newById, newKeys),\n });\n\n return global;\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 { 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 (\n userId !== global.currentUserId\n && global.users.byId[userId]\n && isUserOnline(global.users.byId[userId], global.users.statusesById[userId])\n ) {\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\nexport function selectSendAs(global: GlobalState, chatId: string) {\n const chat = selectChat(global, chatId);\n if (!chat) return undefined;\n\n const id = chat?.fullInfo?.sendAsId;\n if (!id) return undefined;\n\n return selectUser(global, id) || selectChat(global, 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 // Favorites\n global.stickers.favorite.stickers.forEach((sticker) => {\n if (sticker.emoji === emoji) stickersForEmoji.push(sticker);\n });\n\n // Added sets\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 return listIds.find((id) => {\n return (\n (!lastReadId || 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(global: GlobalState, message: ApiMessage) {\n const chat = selectChat(global, message.chatId);\n if (!chat) {\n return undefined;\n }\n\n const sender = selectSender(global, message);\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\nexport function selectIsMessageProtected(global: GlobalState, message?: ApiMessage) {\n return message ? message.isProtected || selectChat(global, message.chatId)?.isProtected : false;\n}\n\nexport function selectHasProtectedMessage(global: GlobalState, chatId: string, messageIds?: number[]) {\n if (selectChat(global, chatId)?.isProtected) {\n return true;\n }\n\n if (!messageIds) {\n return false;\n }\n\n const messages = selectChatMessages(global, chatId);\n\n return messageIds.some((messageId) => messages[messageId]?.isProtected);\n}\n\nexport function selectSponsoredMessage(global: GlobalState, chatId: string) {\n const chat = selectChat(global, chatId);\n const message = chat && isChatChannel(chat) ? global.messages.sponsoredByChatId[chatId] : undefined;\n\n return message && message.expiresAt >= Math.round(Date.now() / 1000) ? message : undefined;\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 { 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 { GlobalState } from '../../global/types';\nimport { ApiChat, ApiUser, ApiUserStatus } from '../../api/types';\n\nexport function selectUser(global: GlobalState, userId: string): ApiUser | undefined {\n return global.users.byId[userId];\n}\n\nexport function selectUserStatus(global: GlobalState, userId: string): ApiUserStatus | undefined {\n return global.users.statusesById[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 {\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 ChatNewAdminRights,\n GroupMembers,\n GroupAddAdmins,\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\nexport type TimingFn = (t: number) => number;\n\nexport type AnimateNumberProps = {\n to: number | number[];\n from: number | number[];\n duration: number;\n onUpdate: (value: any) => void;\n timing?: TimingFn;\n onEnd?: () => void;\n};\n\nexport const timingFunctions = {\n linear: (t: number) => t,\n easeIn: (t: number) => t ** 1.675,\n easeOut: (t: number) => 1 - (1 - t ** 1.675),\n easeInOut: (t: number) => 0.5 * (Math.sin((t - 0.5) * Math.PI) + 1),\n easeInQuad: (t: number) => t * t,\n easeOutQuad: (t: number) => t * (2 - t),\n easeInOutQuad: (t: number) => (t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t),\n easeInCubic: (t: number) => t * t * t,\n easeOutCubic: (t: number) => (--t) * t * t + 1,\n easeInOutCubic: (t: number) => (t < 0.5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1),\n easeInQuart: (t: number) => t * t * t * t,\n easeOutQuart: (t: number) => 1 - (--t) * t * t * t,\n easeInOutQuart: (t: number) => (t < 0.5 ? 8 * t * t * t * t : 1 - 8 * (--t) * t * t * t),\n easeInQuint: (t: number) => t * t * t * t * t,\n easeOutQuint: (t: number) => 1 + (--t) * t * t * t * t,\n easeInOutQuint: (t: number) => (t < 0.5 ? 16 * t * t * t * t * t : 1 + 16 * (--t) * t * t * t * t),\n};\n\nexport function animateNumber({\n timing = timingFunctions.linear,\n onUpdate,\n duration,\n onEnd,\n from,\n to,\n}: AnimateNumberProps) {\n const t0 = Date.now();\n let canceled = false;\n\n animate(() => {\n if (canceled) return false;\n const t1 = Date.now();\n let t = (t1 - t0) / duration;\n if (t > 1) t = 1;\n const progress = timing(t);\n if (typeof from === 'number' && typeof to === 'number') {\n onUpdate(from + ((to - from) * progress));\n } else if (Array.isArray(from) && Array.isArray(to)) {\n const result = from.map((f, i) => f + ((to[i] - f) * progress));\n onUpdate(result);\n }\n if (t === 1 && onEnd) onEnd();\n return t < 1;\n });\n\n return () => {\n canceled = true;\n if (onEnd) onEnd();\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 // Workaround for https://bugs.telegram.org/c/5777\n .replace(/'de'/g, 'de');\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(datetime: Date | number, locale = 'en-US') {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n return date.toLocaleString(\n locale,\n {\n year: 'numeric',\n month: 'short',\n day: 'numeric',\n },\n );\n}\n\nexport function formatDateTimeToString(datetime: Date | number, locale = 'en-US') {\n const date = typeof datetime === 'number' ? new Date(datetime) : datetime;\n return date.toLocaleString(\n locale,\n {\n year: 'numeric',\n month: 'short',\n day: 'numeric',\n hour: 'numeric',\n minute: 'numeric',\n second: '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[^\\ufe0f]/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","export function ensureProtocol(url?: string) {\n if (!url) {\n return undefined;\n }\n\n // HTTP was chosen by default as a fix for https://bugs.telegram.org/c/10712.\n // It is also the default protocol in the official TDesktop client.\n return url.includes('://') ? url : `http://${url}`;\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 = (\n window.matchMedia('(display-mode: standalone)').matches\n || (window.navigator as any).standalone\n || document.referrer.includes('android-app://')\n);\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 IS_REQUEST_FULLSCREEN_SUPPORTED = 'requestFullscreen' in document.createElement('div');\nexport const ARE_CALLS_SUPPORTED = !navigator.userAgent.includes('Firefox');\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\nexport const IS_SCROLL_PATCH_NEEDED = !IS_MAC_OS && !IS_IOS && !IS_ANDROID;\n\n// Smaller area reduces scroll jumps caused by `patchChromiumScroll`\nexport const MESSAGE_LIST_SENSITIVE_AREA = IS_SCROLL_PATCH_NEEDED ? 300 : 750;\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 ADMINS_TOO_MUCH: 'There are too many admins',\n ADMIN_RANK_EMOJI_NOT_ALLOWED: 'An admin rank cannot contain emojis',\n ADMIN_RANK_INVALID: 'The specified admin rank is invalid',\n FRESH_CHANGE_ADMINS_FORBIDDEN: 'You were just elected admin, you can\\'t add or modify other admins yet',\n INPUT_USER_DEACTIVATED: 'The specified user was deleted',\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 =\n 'asc'\n | 'desc';\n\ninterface OrderCallback {\n (member: T): any;\n}\n\nexport function buildCollectionByKey(collection: T[], key: keyof T) {\n return collection.reduce((byKey: CollectionByKey, member: T) => {\n byKey[member[key]] = member;\n\n return byKey;\n }, {});\n}\n\nexport function mapValues(\n byKey: CollectionByKey,\n callback: (member: M, key: string, index: number, originalByKey: CollectionByKey) => R,\n): CollectionByKey {\n return Object.keys(byKey).reduce((newByKey: CollectionByKey, key, index) => {\n newByKey[key] = callback(byKey[key], key, index, byKey);\n return newByKey;\n }, {});\n}\n\nexport function pick(object: T, keys: K[]) {\n return keys.reduce((result, key) => {\n result[key] = object[key];\n return result;\n }, {} as Pick);\n}\n\nexport function pickTruthy(object: T, keys: K[]) {\n return keys.reduce((result, key) => {\n if (object[key]) {\n result[key] = object[key];\n }\n\n return result;\n }, {} as Pick);\n}\n\nexport function omit(object: T, keys: K[]) {\n const stringKeys = new Set(keys.map(String));\n const savedKeys = Object.keys(object)\n .filter((key) => !stringKeys.has(key)) as Array>;\n\n return pick(object, savedKeys);\n}\n\nexport function orderBy(\n collection: T[],\n orderRule: (keyof T) | OrderCallback | ((keyof T) | OrderCallback)[],\n mode: OrderDirection | [OrderDirection, OrderDirection] = 'asc',\n): T[] {\n function compareValues(a: T, b: T, currentOrderRule: (keyof T) | OrderCallback, isAsc: boolean) {\n const aValue = (typeof currentOrderRule === 'function' ? currentOrderRule(a) : a[currentOrderRule]) || 0;\n const bValue = (typeof currentOrderRule === 'function' ? currentOrderRule(b) : b[currentOrderRule]) || 0;\n\n return isAsc ? aValue - bValue : bValue - aValue;\n }\n\n if (Array.isArray(orderRule)) {\n const [mode1, mode2] = Array.isArray(mode) ? mode : [mode, mode];\n const [orderRule1, orderRule2] = orderRule;\n const isAsc1 = mode1 === 'asc';\n const isAsc2 = mode2 === 'asc';\n\n return collection.sort((a, b) => {\n return compareValues(a, b, orderRule1, isAsc1) || compareValues(a, b, orderRule2, isAsc2);\n });\n }\n\n const isAsc = mode === 'asc';\n return collection.sort((a, b) => {\n return compareValues(a, b, orderRule, isAsc);\n });\n}\n\nexport function flatten(array: any[]) {\n return array.reduce((result, member) => {\n if (Array.isArray(member)) {\n return result.concat(member);\n } else {\n result.push(member);\n return result;\n }\n }, []);\n}\n\nexport function unique(array: T[]): T[] {\n return Array.from(new Set(array));\n}\n\nexport function compact(array: any[]) {\n return array.filter(Boolean);\n}\n\nexport function areSortedArraysEqual(array1: any[], array2: any[]) {\n if (array1.length !== array2.length) {\n return false;\n }\n\n return array1.every((item, i) => item === array2[i]);\n}\n\nexport function areSortedArraysIntersecting(array1: any[], array2: any[]) {\n return array1[0] <= array2[array2.length - 1] && array1[array1.length - 1] >= array2[0];\n}\n\nexport function findIntersectionWithSet(array: T[], set: Set): T[] {\n return array.filter((a) => set.has(a));\n}\n\nexport function split(array: any[], chunkSize: number) {\n const result = [];\n for (let i = 0; i < array.length; i += chunkSize) {\n result.push(array.slice(i, i + chunkSize));\n }\n\n return result;\n}\n\nexport function cloneDeep(value: T): T {\n if (typeof value !== 'object') {\n return value;\n }\n\n if (Array.isArray(value)) {\n return value.map(cloneDeep) as typeof value;\n }\n\n return Object.keys(value).reduce((acc, key) => {\n acc[key as keyof T] = cloneDeep(value[key as keyof T]);\n return acc;\n }, {} as T);\n}\n\nexport function findLast(array: Array, predicate: (value: T, index: number, obj: T[]) => boolean): T | undefined {\n let cursor = array.length;\n\n while (cursor--) {\n if (predicate(array[cursor], cursor, array)) {\n return array[cursor];\n }\n }\n\n return undefined;\n}\n","import { 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 Calls,\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 [Bundles.Calls]: typeof import('../bundles/calls');\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 case Bundles.Calls:\n LOAD_PROMISES[Bundles.Calls] = import('../bundles/calls');\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 fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n waitingTimeout = self.setTimeout(() => {\n if (shouldRunLast) {\n fn(...args);\n }\n\n waitingTimeout = undefined;\n }, ms);\n };\n}\n\nexport function throttle(\n fn: F,\n ms: number,\n shouldRunFirst = true,\n) {\n let interval: number | undefined;\n let isPending: boolean;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n isPending = true;\n args = _args;\n\n if (!interval) {\n if (shouldRunFirst) {\n isPending = false;\n fn(...args);\n }\n\n // eslint-disable-next-line no-restricted-globals\n interval = self.setInterval(() => {\n if (!isPending) {\n // eslint-disable-next-line no-restricted-globals\n self.clearInterval(interval!);\n interval = undefined;\n return;\n }\n\n isPending = false;\n fn(...args);\n }, ms);\n }\n };\n}\n\nexport function throttleWithRaf(fn: F) {\n return throttleWith(fastRaf, fn);\n}\n\nexport function throttleWithPrimaryRaf(fn: F) {\n return throttleWith(fastRafPrimary, fn);\n}\n\nexport function throttleWithTickEnd(fn: F) {\n return throttleWith(onTickEnd, fn);\n}\n\nexport function throttleWithNow(fn: F) {\n return throttleWith(runNow, fn);\n}\n\nexport function throttleWith(schedulerFn: Scheduler, fn: F) {\n let waiting = false;\n let args: Parameters;\n\n return (..._args: Parameters) => {\n args = _args;\n\n if (!waiting) {\n waiting = true;\n\n schedulerFn(() => {\n waiting = false;\n fn(...args);\n });\n }\n };\n}\n\nexport function onIdle(cb: NoneToVoidFunction, timeout?: number) {\n // eslint-disable-next-line no-restricted-globals\n if (self.requestIdleCallback) {\n // eslint-disable-next-line no-restricted-globals\n self.requestIdleCallback(cb, { timeout });\n } else {\n onTickEnd(cb);\n }\n}\n\nfunction runNow(fn: NoneToVoidFunction) {\n fn();\n}\n\nexport const pause = (ms: number) => new Promise((resolve) => {\n setTimeout(() => resolve(), ms);\n});\n\nexport function rafPromise() {\n return new Promise((resolve) => {\n fastRaf(resolve);\n });\n}\n\nlet fastRafCallbacks: NoneToVoidFunction[] | undefined;\nlet fastRafPrimaryCallbacks: NoneToVoidFunction[] | undefined;\n\n// May result in an immediate execution if called from another `requestAnimationFrame` callback\nexport function fastRaf(callback: NoneToVoidFunction, isPrimary = false) {\n if (!fastRafCallbacks) {\n fastRafCallbacks = isPrimary ? [] : [callback];\n fastRafPrimaryCallbacks = isPrimary ? [callback] : [];\n\n requestAnimationFrame(() => {\n const currentCallbacks = fastRafCallbacks!;\n const currentPrimaryCallbacks = fastRafPrimaryCallbacks!;\n fastRafCallbacks = undefined;\n fastRafPrimaryCallbacks = undefined;\n currentPrimaryCallbacks.forEach((cb) => cb());\n currentCallbacks.forEach((cb) => cb());\n });\n } else if (isPrimary) {\n fastRafPrimaryCallbacks!.push(callback);\n } else {\n fastRafCallbacks.push(callback);\n }\n}\n\nexport function fastRafPrimary(callback: NoneToVoidFunction) {\n fastRaf(callback, true);\n}\n\nlet onTickEndCallbacks: NoneToVoidFunction[] | undefined;\nlet onTickEndPrimaryCallbacks: NoneToVoidFunction[] | undefined;\n\nexport function onTickEnd(callback: NoneToVoidFunction, isPrimary = false) {\n if (!onTickEndCallbacks) {\n onTickEndCallbacks = isPrimary ? [] : [callback];\n onTickEndPrimaryCallbacks = isPrimary ? [callback] : [];\n\n Promise.resolve().then(() => {\n const currentCallbacks = onTickEndCallbacks!;\n const currentPrimaryCallbacks = onTickEndPrimaryCallbacks!;\n onTickEndCallbacks = undefined;\n onTickEndPrimaryCallbacks = undefined;\n currentPrimaryCallbacks.forEach((cb) => cb());\n currentCallbacks.forEach((cb) => cb());\n });\n } else if (isPrimary) {\n onTickEndPrimaryCallbacks!.push(callback);\n } else {\n onTickEndCallbacks.push(callback);\n }\n}\n\nexport function onTickEndPrimary(callback: NoneToVoidFunction) {\n onTickEnd(callback, true);\n}\n\nlet beforeUnloadCallbacks: NoneToVoidFunction[] | undefined;\n\nexport function onBeforeUnload(callback: NoneToVoidFunction, isLast = false) {\n if (!beforeUnloadCallbacks) {\n beforeUnloadCallbacks = [];\n // eslint-disable-next-line no-restricted-globals\n self.addEventListener('beforeunload', () => {\n beforeUnloadCallbacks!.forEach((cb) => cb());\n });\n }\n\n if (isLast) {\n beforeUnloadCallbacks.push(callback);\n } else {\n beforeUnloadCallbacks.unshift(callback);\n }\n\n return () => {\n beforeUnloadCallbacks = beforeUnloadCallbacks!.filter((cb) => cb !== callback);\n };\n}\n","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 | string[]) {\n if (!haystack || !needle) {\n return false;\n }\n\n const needleWords = typeof needle === 'string' ? needle.toLowerCase().split(RE_NOT_LETTER) : needle;\n const haystackLower = haystack.toLowerCase();\n\n // @optimization\n if (needleWords.length === 1 && !haystackLower.includes(needleWords[0])) {\n return false;\n }\n\n let haystackWords: string[];\n\n return needleWords.every((needleWord) => {\n if (!haystackLower.includes(needleWord)) {\n return false;\n }\n\n if (!haystackWords) {\n haystackWords = haystackLower.split(RE_NOT_LETTER);\n }\n\n return haystackWords.some((haystackWord) => haystackWord.startsWith(needleWord));\n });\n}\n\nexport function prepareSearchWordsForNeedle(needle: string) {\n const needleWords = needle.toLowerCase().split(RE_NOT_LETTER);\n\n return (haystack: string) => searchWords(haystack, needleWords);\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 + \".\" + {\"87\":\"77459230580aafa8639a\",\"99\":\"f03a947e6e336feffec8\",\"133\":\"64de2daa3ae6549d8f45\",\"161\":\"286d0207d962142ad548\",\"301\":\"751950a7a21e70acdb7c\",\"354\":\"44bc53595e49ca5bc9f9\",\"472\":\"21e5264f606f2b525030\",\"501\":\"72ce4b6e27f459e194cd\",\"524\":\"80c446dcb25355f04b36\",\"532\":\"5ff953a5af12d8af60a9\",\"536\":\"55dc7dd4ab42a2c9f037\",\"739\":\"462b85f7a954e903b4cd\",\"745\":\"9316c5c2b711c39a20a5\",\"884\":\"bf91279ce235c0463204\",\"886\":\"2870895152d4462e05bf\",\"915\":\"0588cdc78683d0e9bbbc\",\"927\":\"04b93a71a7d051ccd448\",\"941\":\"5b93118a31cc89905ee3\",\"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 + \".\" + {\"87\":\"77459230580aafa8639a\",\"133\":\"64de2daa3ae6549d8f45\",\"301\":\"751950a7a21e70acdb7c\",\"472\":\"21e5264f606f2b525030\",\"532\":\"5ff953a5af12d8af60a9\",\"886\":\"2870895152d4462e05bf\"}[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, DEBUG_MORE } 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_MORE) {\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 statusesById: {},\n },\n\n chats: {\n listIds: {},\n isFullyLoaded: {},\n orderedPinnedIds: {},\n totalCount: {},\n byId: {},\n },\n\n messages: {\n byChatId: {},\n messageLists: [],\n sponsoredByChatId: {},\n },\n\n groupCalls: {\n byId: {},\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 { isHeavyAnimating } 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 unsubscribeFromBeforeUnload: NoneToVoidFunction | undefined;\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 if (!cached.groupCalls) {\n cached.groupCalls = initialState.groupCalls;\n }\n\n if (!cached.users.statusesById) {\n cached.users.statusesById = {};\n }\n\n if (!cached.messages.sponsoredByChatId) {\n cached.messages.sponsoredByChatId = {};\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 groupCalls: reduceGroupCalls(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, statusesById, selectedId } } = global;\n const chatIds = (global.chats.listIds.active || []).slice(0, GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT).filter(isUserId);\n const userIds = Object.keys(byId);\n const idsToSave = chatIds.concat(userIds).slice(0, GLOBAL_STATE_CACHE_USER_LIST_LIMIT);\n\n return {\n byId: pick(byId, idsToSave),\n statusesById: pick(statusesById, 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 newListIds = (global.chats.listIds.active || []).slice(0, GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT);\n const { chatId: currentChatId } = selectCurrentMessageList(global) || {};\n const idsToSave = newListIds.concat(currentChatId ? [currentChatId] : []);\n\n return {\n ...global.chats,\n byId: pick(global.chats.byId, idsToSave),\n listIds: {\n active: newListIds,\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 chatIds = (global.chats.listIds.active || []).slice(0, GLOBAL_STATE_CACHE_CHAT_LIST_LIMIT);\n const chatIdsToSave = chatIds.concat(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 sponsoredByChatId: {},\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 reduceGroupCalls(global: GlobalState): GlobalState['groupCalls'] {\n return {\n ...global.groupCalls,\n byId: {},\n activeGroupCallId: undefined,\n isGroupCallPanelHidden: undefined,\n isFallbackConfirmOpen: undefined,\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 { getDispatch, getGlobal, withGlobal } from '../../lib/teact/teactn';\n\nimport { ApiMediaFormat } from '../../api/types';\nimport { 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 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 =\n Pick\n & {\n hasCustomBackground?: boolean;\n hasCustomBackgroundColor: boolean;\n isRightColumnShown?: boolean;\n leftColumnWidth?: number;\n };\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}) => {\n const { setIsUiReady } = getDispatch();\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)(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 { prepareSearchWordsForNeedle } 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 if (!filter.length) {\n return countryList;\n }\n\n const searchWords = prepareSearchWordsForNeedle(filter);\n\n return countryList.filter((country) => (\n searchWords(country.defaultName) || (country.name && searchWords(country.name))\n ));\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 { getDispatch, withGlobal } from '../../lib/teact/teactn';\n\nimport { 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};\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}) => {\n const {\n setAuthPhoneNumber,\n setAuthRememberMe,\n loadNearestCountry,\n loadCountryList,\n clearAuthError,\n goToAuthQrCode,\n setSettingOption,\n } = getDispatch();\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)(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 & {\n language?: LangCode;\n };\n\nconst DATA_PREFIX = 'tg://login?token=';\n\nconst AuthCode: FC = ({\n connectionState,\n authState,\n authQrCode,\n language,\n}) => {\n const {\n returnToAuthPhoneNumber,\n setSettingOption,\n } = getDispatch();\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 useEffect(() => {\n if (connectionState === 'connectionStateReady') {\n void setLanguage(DEFAULT_LANG_CODE);\n }\n }, [connectionState]);\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)(AuthCode));\n","import React, { FC, useEffect, memo } from '../../lib/teact/teact';\nimport { getDispatch, withGlobal } from '../../lib/teact/teactn';\n\nimport { 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;\n\nconst Auth: FC = ({\n authState,\n}) => {\n const {\n reset, initApi, returnToAuthPhoneNumber, goToAuthQrCode,\n } = getDispatch();\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)(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, { getDispatch, withGlobal } from './lib/teact/teactn';\n\nimport { 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;\n\nconst App: FC = ({ authState }) => {\n const { disconnect } = getDispatch();\n\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)(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","Error","message","subscribeToWorker","platform","window","async","Promise","race","makeRequest","pause","then","err","Date","now","startedAt","location","reload","args","callApi","fnName","name","warn","cancelApiProgress","progressCallback","isCanceled","postMessage","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","getDomain","url","href","ensureProtocol","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","sender","openUserInfo","id","Link","focusMessage","handleMessageClick","chatId","openChat","groupCall","joinGroupCall","accessHash","renderActionMessageText","lang","actionOrigin","targetUsers","targetMessage","targetChatId","options","action","translationValues","amount","currency","call","textOptions","maxTextLength","processed","unprocessed","undefined","includes","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","renderGroupCallContent","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","splittenParts","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","withGlobal","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_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","SEND_MESSAGE_ACTION_INTERVAL","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","CONTENT_NOT_SUPPORTED","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","SEEN_BY_MEMBERS_CHAT_MAX","SEEN_BY_MEMBERS_EXPIRE","GROUP_CALL_VOLUME_MULTIPLIER","GROUP_CALL_DEFAULT_VOLUME","ENABLE_THUMBNAIL_VIDEO","cb","dependencies","debugKey","prevDeps","usePrevious","initial","setValue","setTrigger","ANIMATION_START_EVENT","ANIMATION_END_EVENT","timeout","isAnimating","handleAnimationStart","handleAnimationEnd","removeEventListener","isHeavyAnimating","duration","onEnd","clearTimeout","dispatchEvent","Event","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","documentEventCounters","delegationRegistryByEventType","delegatedEventTypesByElement","propName","handler","asCapture","eventType","resolveEventType","canUseEventDelegation","resolveDelegationRegistry","existing","newSet","resolveDelegatedEventTypes","add","addDelegatedListener","removeDelegatedListener","tagName","realEventType","has","removeAllDelegatedListeners","eventTypes","realEvent","events","furtherCallsPrevented","Proxy","p","Reflect","body","parentNode","documentListenersCount","keys","delegatedHandlersCount1","values","acc","counter","delegationRegistriesCount","delegatedHandlersCount2","delegationRegistry","delegationElementsCount","delegatedEventTypesCount","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","newKeys","key","currentValue","newValue","cssText","removeAttribute","setAttribute","updateAttributes","currentEl","teactFastList","$newChild","currentRemainingIndex","remainingByKey","$currentChild","isKeyPresent","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","__html","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","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","React","currentGlobal","reducers","callbacks","containers","mapStateToProps","ownProps","mappedProps","newMappedProps","Number","isNaN","DEBUG_componentName","areMappedPropsChanged","DEBUG_updates","updateTime","actions","runCallbacksThrottled","throttleWithTickEnd","runCallbacks","forceOnHeavyAnimation","setGlobal","newGlobal","forceSyncOnIOs","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","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","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","IS_SAFARI","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","allListIds","folder","excludedChatIds","includedChatIds","pinnedChatIds","active","archived","isListed","unreadMentionsCount","excludeArchived","excludeRead","unreadCount","hasUnreadMark","excludeMuted","userType","isContact","bots","contacts","nonContacts","channels","groups","filterChatFolder","prepareChatList","listIds","orderedPinnedIds","folderType","noOrder","listIdsSet","orderedPinnedIdsSet","pinnedChats","checkChat","otherChats","reduceChatList","chatArrays","filteredIds","filteredIdsSet","getFolderUnreadDialogs","hasActiveDialogs","unreadDialogsCount","isUnread","getFolderDescriptionText","emoticon","description","pinnedIds","getFolderChatsCount","getMessageSenderName","getUserFirstOrLastName","sortChatIds","chatIds","shouldPrioritizeVerified","priorityIds","priority","isVerified","filterChatsByName","query","searchWords","prepareSearchWordsForNeedle","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","mediaId","hasMessageLocalBlobUrl","getVideoOrAudioBaseHash","getAudioHasCover","IS_PROGRESSIVE_SUPPORTED","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","userStatus","wasOnline","getTime","wasOnlineDate","diff","today","setHours","yesterday","setDate","getDate","formatFullDate","isUserOnline","noStatus","isUserBot","getCanAddContact","sortUserIds","userIds","userStatusesById","getServerTime","expires","filterUsersByName","getUserIdDividend","abs","getUserColorKey","peer","replaceChatListIds","newIds","updateChatListIds","idsUpdate","replaceChats","newById","updateChat","chatUpdate","updatedChat","getUpdatedChat","updatedById","addChats","isUpdated","addedById","isMin","shouldOmitMinInfo","omit","photos","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","updateSponsoredMessage","sponsoredByChatId","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","updateContactList","updatedUsers","contactUserIds","contactList","newContactUserIds","userUpdate","updatedUser","getUpdatedUser","updateUsers","updateSelectedUserId","selectedId","deleteContact","MEMO_EMPTY_ARRAY","updateUserSearch","searchStatePartial","userSearch","updateUserSearchFetchingStatus","newState","fetchingStatus","updateUserBlockedState","isBlocked","replaceUserStatuses","statusesById","addUserStatuses","pick","getComplexKey","updateGlobalSearch","globalSearch","updateGlobalSearchContent","currentContent","updateGlobalSearchResults","newFoundMessages","nextRate","resultsByType","newFoundMessagesById","foundIdsForType","foundIds","updateGlobalSearchFetchingStatus","prevFoundIds","newFoundIds","foundOrPrevFoundIds","nextOffsetId","replaceLocalTextSearch","chatThreadKey","searchParams","localTextSearch","byChatThreadKey","updateLocalTextSearch","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","selectChat","selectChatUser","selectIsChatWithSelf","selectIsChatWithBot","selectSupportChat","isSupport","selectChatOnlineCount","members","onlineCount","selectChatBot","selectIsChatBotNotStarted","bot","messageInfo","selectAreActiveChatsLoaded","selectIsChatListed","targetList","list","selectChatFolder","chatFolders","selectIsChatPinned","chatFoldersById","selectChatByUsername","usernameLowered","selectCountNotMutedUnread","activeChatIds","selectNotifyExceptions","selectIsServiceChatReady","selectSendAs","sendAsId","selectCurrentStickerSearch","selectCurrentGifSearch","selectStickerSet","selectStickerSetByShortName","shortName","stickerSets","stickersForEmoji","favorite","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","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","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","selectIsMessageProtected","isProtected","selectHasProtectedMessage","selectSponsoredMessage","expiresAt","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","selectUserStatus","selectIsUserBlocked","LoadMoreDirection","FocusDirection","SettingsScreens","LeftColumnContent","GlobalSearchContent","MediaViewerOrigin","AudioOrigin","ChatCreationProgress","ManagementProgress","ProfileState","PaymentStep","ManagementScreens","currentInstance","animateSingle","tick","instance","isCancelled","animate","timingFunctions","linear","easeIn","easeOut","easeInOut","sin","PI","easeInQuad","easeOutQuad","easeInOutQuad","easeInCubic","easeOutCubic","easeInOutCubic","easeInQuart","easeOutQuart","easeInOutQuart","easeInQuint","easeOutQuint","easeInOutQuint","animateNumber","timing","t0","canceled","f","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","formatDateTimeToString","hour","minute","second","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","IS_REQUEST_FULLSCREEN_SUPPORTED","ARE_CALLS_SUPPORTED","LAYERS_ANIMATION_NAME","TEST_VIDEO","DPR","devicePixelRatio","MASK_IMAGE_DISABLED","IS_SCROLL_PATCH_NEEDED","MESSAGE_LIST_SENSITIVE_AREA","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","fetchFile","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","ADMINS_TOO_MUCH","ADMIN_RANK_EMOJI_NOT_ALLOWED","ADMIN_RANK_INVALID","FRESH_CHANGE_ADMINS_FORBIDDEN","INPUT_USER_DEACTIVATED","SHIPPING_ERRORS","getReadableErrorText","isSlowMode","textParams","extraPartIndex","errorMessage","handleErrorEvent","ErrorEvent","reason","throttle","alert","collection","member","mapValues","newByKey","object","stringKeys","orderRule","mode","compareValues","currentOrderRule","isAsc","aValue","bValue","mode1","mode2","orderRule1","orderRule2","isAsc1","isAsc2","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","Calls","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","privateChatUser","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","haystack","needle","needleWords","haystackLower","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__","m","getter","__esModule","getPrototypeOf","obj","ns","create","def","getOwnPropertyNames","definition","o","defineProperty","enumerable","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","hasErrorKey","INITIAL_STATE","isLeftColumnShown","phoneCodes","general","groupCalls","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","setupCaching","clearCaching","reducedGlobal","reduceShowChatInfo","reduceUsers","reduceChats","reduceMessages","recentlyFoundChatIds","reduceSettings","reduceChatFolders","reduceGroupCalls","idsToSave","newListIds","mainThread","activeGroupCallId","isGroupCallPanelHidden","isFallbackConfirmOpen","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 72c8fac7..b306e859 100644 --- a/dist/report.html +++ b/dist/report.html @@ -3,7 +3,7 @@ - telegram-t [13 Jan 2022 at 01:15] + telegram-t [13 Jan 2022 at 14:54]